Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: retire OpenWorld surface (#5890)

[._.]/ Adam Eivy2a71f14afeb1
diff --git a/client/src/components/music/TracksManager.test.jsx b/client/src/components/music/TracksManager.test.jsx
index ea96a233a0..428c82a424 100644
--- a/client/src/components/music/TracksManager.test.jsx
+++ b/client/src/components/music/TracksManager.test.jsx
@@ -182,6 +182,7 @@ describe('<TracksManager> generator mode toggle', () => {
listTracks.mockResolvedValue([{ ...TRACK, prompt: 'Rainy arcade chase', lyrics: '[verse]\nRun!' }]);
renderAt('track-1');
await screen.findByTestId('gen-panel');
+ await screen.findByDisplayValue('Rainy arcade chase');
fireEvent.click(modeButton('Chiptune score'));
expect(chiptuneProps.current).toMatchObject({
diff --git a/client/src/components/openworld/AgentEntity.jsx b/client/src/components/openworld/AgentEntity.jsx
deleted file mode 100644
index b09c5f3406..0000000000
--- a/client/src/components/openworld/AgentEntity.jsx
+++ /dev/null
@@ -1,119 +0,0 @@
-import { useRef, useMemo, useEffect } from 'react';
-import { useFrame } from '@react-three/fiber';
-import { Sparkles } from '@react-three/drei';
-import * as THREE from 'three';
-import { AGENT_STATES } from '../cos/constants';
-import {
- AGENT_MOTION,
- computeAgentOrbit,
- computeAgentTrailPoints,
- computeTrailColors,
- resolveTrailSamples,
-} from '../../utils/openWorldAgentMotion';
-
-const DEFAULT_COLOR = '#06b6d4';
-
-export default function AgentEntity({ agent, position, index = 0, settings }) {
- const bodyRef = useRef();
- const ringRef = useRef();
- const trailRef = useRef();
-
- const state = agent.state || agent.status || 'coding';
- const color = AGENT_STATES[state]?.color || DEFAULT_COLOR;
-
- // Trail density follows the quality dial; 0 means "don't render a trail".
- const trailSamples = resolveTrailSamples(settings?.particleDensity ?? 1);
-
- // Static geometry sized to the sample count; positions stream in per frame,
- // the color ramp (head→tail fade) is baked once.
- const trailGeom = useMemo(() => {
- const geom = new THREE.BufferGeometry();
- if (trailSamples > 0) {
- const c = new THREE.Color(color);
- geom.setAttribute(
- 'position',
- new THREE.Float32BufferAttribute(new Float32Array(trailSamples * 3), 3),
- );
- geom.setAttribute(
- 'color',
- new THREE.Float32BufferAttribute(
- new Float32Array(computeTrailColors([c.r, c.g, c.b], trailSamples)),
- 3,
- ),
- );
- }
- return geom;
- }, [color, trailSamples]);
-
- // Dispose the geometry's GPU buffers when it's replaced (color/quality change)
- // or on unmount — the imperative geometry isn't reclaimed automatically.
- useEffect(() => () => trailGeom.dispose(), [trailGeom]);
-
- useFrame(({ clock }) => {
- const t = clock.getElapsedTime();
- const p = computeAgentOrbit(t, { index });
-
- if (bodyRef.current) {
- bodyRef.current.position.set(p.x, p.y, p.z);
- bodyRef.current.rotation.y = t * 0.8 + index * Math.PI * 0.5;
- const material = bodyRef.current.children[0]?.material;
- if (material) material.emissiveIntensity = 0.5 + Math.sin(t * 3) * 0.3;
- }
- if (ringRef.current) ringRef.current.rotation.z = -t * 0.55 - index * 0.4;
-
- if (trailRef.current && trailSamples > 0) {
- const attr = trailRef.current.geometry.getAttribute('position');
- // Fill the geometry buffer in place — no per-frame allocation.
- computeAgentTrailPoints(t, { index }, trailSamples, AGENT_MOTION.trailSeconds, attr.array);
- attr.needsUpdate = true;
- }
- });
-
- // The group sits at the building anchor; the agent body orbits within it so
- // its motion trail samples in anchor-relative space.
- return (
- <group position={position}>
- {trailSamples > 0 && (
- <line ref={trailRef} geometry={trailGeom}>
- <lineBasicMaterial
- vertexColors
- transparent
- opacity={0.38}
- blending={THREE.AdditiveBlending}
- depthWrite={false}
- />
- </line>
- )}
- <group ref={bodyRef}>
- <mesh>
- <icosahedronGeometry args={[0.3, 1]} />
- <meshStandardMaterial
- color={color}
- emissive={color}
- emissiveIntensity={0.5}
- transparent
- opacity={0.9}
- roughness={0.32}
- metalness={0.18}
- />
- </mesh>
- <mesh ref={ringRef} rotation={[Math.PI / 2, 0, 0]}>
- <torusGeometry args={[0.46, 0.016, 6, 20]} />
- <meshBasicMaterial color={color} transparent opacity={0.46} />
- </mesh>
- <mesh position={[0, 0.34, 0]}>
- <sphereGeometry args={[0.045, 8, 6]} />
- <meshBasicMaterial color={color} transparent opacity={0.9} />
- </mesh>
- <Sparkles
- count={8}
- scale={0.68}
- size={0.7}
- speed={0.35}
- color={color}
- opacity={0.34}
- />
- </group>
- </group>
- );
-}
diff --git a/client/src/components/openworld/Borough.jsx b/client/src/components/openworld/Borough.jsx
deleted file mode 100644
index 2befd6c4fd..0000000000
--- a/client/src/components/openworld/Borough.jsx
+++ /dev/null
@@ -1,85 +0,0 @@
-import { useMemo } from 'react';
-import { getBuildingHeight, BOROUGH_PARAMS, openWorldDayMix, openWorldShowDetail, openWorldShowInteriorWindows } from './openWorldConstants';
-import { hashString } from '../../utils/hashString';
-import Building from './Building';
-import AgentEntity from './AgentEntity';
-import ProcessBuilding from './ProcessBuilding';
-
-export default function Borough({ app, position, agentMap, onBuildingClick, playSfx, neonBrightness, isProximity, focused = false, dimmed = false, settings, playback = false, transitionState = null, onExited }) {
- const agentData = agentMap.get(app.id);
- const agents = agentData?.agents || [];
- const height = getBuildingHeight(app);
- // Get processes to render in ring (skip for archived apps)
- const processes = useMemo(() => {
- if (app.archived) return [];
- return app.processes || [];
- }, [app.archived, app.processes]);
-
- // Build pm2Status lookup map
- const pm2Status = app.pm2Status || {};
-
- // 0 at night, 1 in full daylight — buildings lighten and shed their neon by day.
- const dayMix = openWorldDayMix(settings);
-
- // Compute ring positions for process buildings
- const processPositions = useMemo(() => {
- const count = processes.length;
- if (count === 0) return [];
-
- return processes.map((proc, i) => {
- const angle = (i / count) * Math.PI * 2;
- const x = Math.cos(angle) * BOROUGH_PARAMS.processRingRadius;
- const z = Math.sin(angle) * BOROUGH_PARAMS.processRingRadius;
- // Rotation to face center: angle + PI so front face points inward
- const rotation = angle + Math.PI;
- const seed = hashString(proc.name || `proc-${i}`);
- return { x, z, rotation, seed, process: proc };
- });
- }, [processes]);
-
- return (
- <group>
- {/* Main building (the app) */}
- <Building
- app={app}
- position={position}
- agentCount={agents.length}
- onClick={() => onBuildingClick?.(app)}
- playSfx={playSfx}
- rooftops={openWorldShowDetail(settings)}
- interiorWindows={openWorldShowInteriorWindows(settings)}
- neonBrightness={neonBrightness}
- isProximity={isProximity}
- focused={focused}
- dimmed={dimmed}
- dayMix={dayMix}
- playback={playback}
- transitionState={transitionState}
- onExited={onExited}
- />
-
- {/* Process buildings in ring around main building */}
- {processPositions.map(({ x, z, rotation, seed, process: proc }) => (
- <ProcessBuilding
- key={proc.name}
- pm2Status={pm2Status[proc.name]}
- position={[position.x + x, 0, position.z + z, rotation]}
- seed={seed}
- dimmed={dimmed}
- dayMix={dayMix}
- />
- ))}
-
- {/* Agent entities floating above main building */}
- {agents.map((agent, i) => (
- <AgentEntity
- key={agent.agentId || i}
- agent={agent}
- position={[position.x, height + 1.5 + i * 1.0, position.z]}
- index={i}
- settings={settings}
- />
- ))}
- </group>
- );
-}
diff --git a/client/src/components/openworld/Building.jsx b/client/src/components/openworld/Building.jsx
deleted file mode 100644
index f8a33421e2..0000000000
--- a/client/src/components/openworld/Building.jsx
+++ /dev/null
@@ -1,1024 +0,0 @@
-import { useRef, useState, useMemo, useEffect } from 'react';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { getBuildingHeight, BUILDING_PARAMS, PIXEL_FONT_URL, mixHex, seededRand } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import OpenWorldLabel from './OpenWorldLabel';
-import HolographicPanel from './HolographicPanel';
-import BuildingHologram from './BuildingHologram';
-import BuildingWindows from './BuildingWindows';
-import { computeRooftopKit } from '../../utils/openWorldRooftops';
-import { buildingHasInteriorWindows } from '../../utils/openWorldInteriorWindows';
-import { computeAppMetrics, buildingSignalTone } from '../../utils/openWorldAppMetrics';
-
-// Rooftop fixture geometry/materials are module-scope singletons shared by every
-// building — fixtures are tiny set dressing, so they keep fixed colors (the antenna
-// tip is a red aviation blinker on purpose) instead of per-theme materials.
-const ROOF_METAL_MAT = new THREE.MeshStandardMaterial({ color: '#232d40', roughness: 0.6, metalness: 0.5 });
-const ROOF_TIP_MAT = new THREE.MeshBasicMaterial({ color: '#ff3344', toneMapped: false });
-const ROOF_GEOMS = {
- antennaMast: new THREE.CylinderGeometry(0.02, 0.035, 1.2, 5),
- antennaTip: new THREE.SphereGeometry(0.05, 6, 6),
- tank: new THREE.CylinderGeometry(0.22, 0.22, 0.45, 10),
- ac: new THREE.BoxGeometry(0.4, 0.22, 0.34),
- dish: new THREE.SphereGeometry(0.24, 10, 6, 0, Math.PI * 2, 0, Math.PI / 2),
-};
-const CONTACT_SHADOW_GEOM = new THREE.CircleGeometry(1, 16);
-const SMOKE_GEOM = new THREE.SphereGeometry(0.2, 6, 6);
-const SPARK_GEOM = new THREE.SphereGeometry(0.03, 4, 4);
-
-// 0–3 deterministic fixtures (antenna/tank/AC/dish) on the roof, seeded by app name —
-// the same determinism as the window textures, so a building keeps its roof forever.
-function RooftopKit({ name, width, y }) {
- const kit = useMemo(() => computeRooftopKit(name, width), [name, width]);
- if (kit.length === 0) return null;
- return (
- <group position={[0, y, 0]}>
- {kit.map((f, i) => (
- <group key={i} position={[f.x, 0, f.z]} rotation={[0, f.rotation, 0]} scale={f.scale}>
- {f.type === 'antenna' && (
- <>
- <mesh geometry={ROOF_GEOMS.antennaMast} material={ROOF_METAL_MAT} position={[0, 0.6, 0]} />
- <mesh geometry={ROOF_GEOMS.antennaTip} material={ROOF_TIP_MAT} position={[0, 1.22, 0]} />
- </>
- )}
- {f.type === 'tank' && (
- <mesh geometry={ROOF_GEOMS.tank} material={ROOF_METAL_MAT} position={[0, 0.225, 0]} />
- )}
- {f.type === 'ac' && (
- <mesh geometry={ROOF_GEOMS.ac} material={ROOF_METAL_MAT} position={[0, 0.11, 0]} />
- )}
- {f.type === 'dish' && (
- <mesh
- geometry={ROOF_GEOMS.dish}
- material={ROOF_METAL_MAT}
- position={[0, 0.12, 0]}
- rotation={[Math.PI / 5, 0, 0]}
- />
- )}
- </group>
- ))}
- </group>
- );
-}
-
-// 7x7 pixel art icons drawn on building faces via lit office windows
-const PIXEL_ICONS = [
- // Heart
- [
- [0,1,0,0,0,1,0],
- [1,1,1,0,1,1,1],
- [1,1,1,1,1,1,1],
- [0,1,1,1,1,1,0],
- [0,0,1,1,1,0,0],
- [0,0,0,1,0,0,0],
- [0,0,0,0,0,0,0],
- ],
- // Server rack
- [
- [1,1,1,1,1,1,1],
- [1,0,0,0,0,1,1],
- [1,1,1,1,1,1,1],
- [1,0,0,0,0,1,1],
- [1,1,1,1,1,1,1],
- [1,0,0,0,0,1,1],
- [1,1,1,1,1,1,1],
- ],
- // Lightning bolt
- [
- [0,0,0,1,1,0,0],
- [0,0,1,1,0,0,0],
- [0,1,1,1,1,0,0],
- [0,0,1,1,1,1,0],
- [0,0,0,1,1,0,0],
- [0,0,1,1,0,0,0],
- [0,0,1,0,0,0,0],
- ],
- // Star
- [
- [0,0,0,1,0,0,0],
- [0,0,1,1,1,0,0],
- [1,1,1,1,1,1,1],
- [0,1,1,1,1,1,0],
- [0,1,1,0,1,1,0],
- [0,1,0,0,0,1,0],
- [1,0,0,0,0,0,1],
- ],
- // Shield
- [
- [0,1,1,1,1,1,0],
- [1,1,1,1,1,1,1],
- [1,1,0,1,0,1,1],
- [1,1,1,1,1,1,1],
- [0,1,1,1,1,1,0],
- [0,0,1,1,1,0,0],
- [0,0,0,1,0,0,0],
- ],
- // Gear
- [
- [0,1,0,1,0,1,0],
- [1,1,1,1,1,1,1],
- [0,1,0,0,0,1,0],
- [1,1,0,0,0,1,1],
- [0,1,0,0,0,1,0],
- [1,1,1,1,1,1,1],
- [0,1,0,1,0,1,0],
- ],
- // Globe
- [
- [0,0,1,1,1,0,0],
- [0,1,0,1,0,1,0],
- [1,0,0,1,0,0,1],
- [1,1,1,1,1,1,1],
- [1,0,0,1,0,0,1],
- [0,1,0,1,0,1,0],
- [0,0,1,1,1,0,0],
- ],
- // Terminal
- [
- [1,1,1,1,1,1,1],
- [1,0,0,0,0,0,1],
- [1,0,1,1,0,0,1],
- [1,0,0,1,0,0,1],
- [1,0,0,0,0,0,1],
- [1,1,1,1,1,1,1],
- [0,0,1,1,1,0,0],
- ],
-];
-
-// Generate a pixel window texture with icon mural for a building face. `tintStructure`
-// is passed in (bound to the active palette accent) so the facade base tracks the theme.
-const createWindowTexture = (accentColor, _width, height, seed, tintStructure) => {
- const canvas = document.createElement('canvas');
- const px = 8;
- const cols = 12;
- const rowCount = Math.max(16, Math.floor(height * 5));
- canvas.width = px * cols;
- canvas.height = px * rowCount;
- const ctx = canvas.getContext('2d');
-
- // Dark, but not black: facades need enough albedo for moon/neon bounce to
- // reveal them. The theme tint keeps the texture in-family.
- ctx.fillStyle = tintStructure('#24324f');
- ctx.fillRect(0, 0, canvas.width, canvas.height);
-
- // Seeded random for consistent patterns
- const rand = seededRand(seed);
-
- // Draw random ambient windows (dimmer background pattern)
- for (let r = 1; r < rowCount - 1; r++) {
- for (let c = 1; c < cols - 1; c++) {
- if (r % 3 === 0 || c % 3 === 0) continue;
- if (rand() > 0.5) {
- const bright = rand();
- if (bright > 0.85) {
- // Bright window - full accent
- ctx.fillStyle = accentColor + '70';
- } else if (bright > 0.6) {
- ctx.fillStyle = accentColor + '40';
- } else if (bright > 0.3) {
- ctx.fillStyle = accentColor + '20';
- } else {
- ctx.fillStyle = tintStructure('#1d2b4a');
- }
- ctx.fillRect(c * px + 1, r * px + 1, px - 2, px - 2);
- }
- }
- }
-
- // Thin horizontal floor-light rows. These make large faces read as stacked
- // occupied floors instead of a single blank slab, especially in night mode.
- for (let r = 2; r < rowCount - 1; r += 3) {
- const warmRow = rand() > 0.55;
- const rowAlpha = rand() > 0.7 ? 0.44 : 0.28;
- ctx.fillStyle = warmRow
- ? `rgba(234, 244, 255, ${rowAlpha})`
- : accentColor + (rowAlpha > 0.35 ? '70' : '45');
-
- for (let c = 1; c < cols - 1; c++) {
- if (rand() < 0.24) continue;
- ctx.fillRect(c * px + 1, r * px + 3, px - 2, 2);
- }
- }
-
- // Occasional brighter architectural bands, like stacked balcony/maintenance
- // strips, to echo the city-light reference without covering every floor.
- for (let r = 4 + (seed % 3); r < rowCount - 2; r += 8) {
- ctx.fillStyle = accentColor + '85';
- ctx.fillRect(0, r * px + 2, canvas.width, 2);
- ctx.fillStyle = 'rgba(255,255,255,0.18)';
- ctx.fillRect(0, r * px + 1, canvas.width, 1);
- }
-
- // Draw pixel art icon mural centered on face
- const icon = PIXEL_ICONS[seed % PIXEL_ICONS.length];
- const iconRows = icon.length;
- const iconCols = icon[0].length;
- const startCol = Math.floor((cols - iconCols) / 2);
- const startRow = Math.floor((rowCount - iconRows) / 2);
-
- for (let r = 0; r < iconRows; r++) {
- for (let c = 0; c < iconCols; c++) {
- if (icon[r][c]) {
- // Bright accent pixel - solid, no frame gaps
- ctx.fillStyle = accentColor;
- ctx.fillRect((startCol + c) * px, (startRow + r) * px, px, px);
- // Slight inner highlight for pixel art depth
- ctx.fillStyle = 'rgba(255,255,255,0.2)';
- ctx.fillRect((startCol + c) * px + 1, (startRow + r) * px + 1, px - 3, px - 3);
- }
- }
- }
-
- // Draw vertical neon accent strips on edges of the face
- ctx.fillStyle = accentColor + '30';
- ctx.fillRect(0, 0, 2, canvas.height);
- ctx.fillRect(canvas.width - 2, 0, 2, canvas.height);
-
- // Horizontal accent line at top
- ctx.fillStyle = accentColor + '60';
- ctx.fillRect(0, 0, canvas.width, 2);
-
- const texture = new THREE.CanvasTexture(canvas);
- texture.minFilter = THREE.NearestFilter;
- texture.magFilter = THREE.NearestFilter;
- texture.wrapS = THREE.RepeatWrapping;
- texture.wrapT = THREE.RepeatWrapping;
- return texture;
-};
-
-// Rooftop antenna component
-function RooftopAntenna({ height, color, accentColor, seed, width: _width, dimMul = 1 }) {
- const antennaRef = useRef();
- const blinkRef = useRef();
- const type = seed % 4;
-
- useFrame(({ clock }) => {
- const t = clock.getElapsedTime();
- if (blinkRef.current) {
- // Blinking light on antenna tip
- blinkRef.current.material.opacity = ((Math.sin(t * 4 + seed) > 0.3) ? 0.9 : 0.1) * dimMul;
- }
- if (antennaRef.current && type === 2) {
- // Slow rotation for dish type
- antennaRef.current.rotation.y = t * 0.3 + seed;
- }
- });
-
- const antennaHeight = 0.6 + (seed % 30) / 30 * 0.8;
-
- return (
- <group position={[0, height, 0]}>
- {/* Main antenna mast */}
- <mesh position={[0, antennaHeight / 2, 0]}>
- <cylinderGeometry args={[0.015, 0.025, antennaHeight, 4]} />
- <meshBasicMaterial color={color} transparent opacity={0.7 * dimMul} />
- </mesh>
-
- {/* Blinking tip light */}
- <mesh ref={blinkRef} position={[0, antennaHeight + 0.05, 0]}>
- <sphereGeometry args={[0.04, 6, 6]} />
- <meshBasicMaterial
- color={seed % 2 === 0 ? '#ef4444' : accentColor}
- transparent
- opacity={0.9 * dimMul}
- />
- </mesh>
- <pointLight
- position={[0, antennaHeight + 0.05, 0]}
- color={seed % 2 === 0 ? '#ef4444' : accentColor}
- intensity={0.15 * dimMul}
- distance={3}
- decay={2}
- />
-
- {/* Type-specific details */}
- {type === 1 && (
- // Dish antenna
- <group ref={antennaRef} position={[0, antennaHeight * 0.7, 0]}>
- <mesh rotation={[0.3, 0, 0]}>
- <ringGeometry args={[0.05, 0.18, 8]} />
- <meshBasicMaterial color={accentColor} transparent opacity={0.4 * dimMul} side={THREE.DoubleSide} />
- </mesh>
- </group>
- )}
- {type === 2 && (
- // Array of small elements
- <group ref={antennaRef} position={[0, antennaHeight * 0.6, 0]}>
- {[0, 1, 2].map(i => (
- <mesh key={i} position={[0, i * 0.12, 0]} rotation={[Math.PI / 2, 0, (i * Math.PI) / 3]}>
- <planeGeometry args={[0.2, 0.03]} />
- <meshBasicMaterial color={accentColor} transparent opacity={0.5 * dimMul} side={THREE.DoubleSide} />
- </mesh>
- ))}
- </group>
- )}
- {type === 3 && (
- // Cross-bar antenna
- <>
- <mesh position={[0, antennaHeight * 0.75, 0]}>
- <boxGeometry args={[0.3, 0.015, 0.015]} />
- <meshBasicMaterial color={color} transparent opacity={0.6 * dimMul} />
- </mesh>
- <mesh position={[0, antennaHeight * 0.55, 0]}>
- <boxGeometry args={[0.2, 0.015, 0.015]} />
- <meshBasicMaterial color={color} transparent opacity={0.5 * dimMul} />
- </mesh>
- </>
- )}
- </group>
- );
-}
-
-// Vertical neon strip on building edge
-function NeonEdgeStrip({ position, height, color, delay, dimMul = 1 }) {
- const ref = useRef();
-
- useFrame(({ clock }) => {
- if (!ref.current) return;
- const t = clock.getElapsedTime();
- ref.current.material.opacity = (0.5 + Math.sin(t * 1.2 + delay) * 0.25) * dimMul;
- });
-
- return (
- <mesh ref={ref} position={position}>
- <boxGeometry args={[0.03, height, 0.03]} />
- <meshBasicMaterial color={color} transparent opacity={0.6 * dimMul} />
- </mesh>
- );
-}
-
-function FloorLightBands({ width, depth, height, color, accentColor, seed, dimMul = 1 }) {
- const bands = useMemo(() => {
- const rand = seededRand(seed + 97);
- const floorCount = Math.max(4, Math.min(14, Math.floor(height / 1.05)));
- const next = [];
-
- for (let i = 1; i <= floorCount; i++) {
- const y = (i / (floorCount + 1)) * height;
- const isCrown = i === floorCount || i === floorCount - 1;
- const show = isCrown || i % 3 === seed % 3 || rand() > 0.48;
- if (!show) continue;
-
- next.push({
- key: `${i}-${Math.round(y * 100)}`,
- y,
- color: rand() > 0.45 ? mixHex('#f8fbff', accentColor, 0.28) : color,
- opacity: isCrown ? 0.78 : 0.34 + rand() * 0.22,
- thickness: isCrown ? 0.055 : 0.032,
- });
- }
-
- return next;
- }, [accentColor, color, height, seed]);
-
- return (
- <group>
- {bands.map((band) => {
- const horizontalGeo = [width * 0.96, band.thickness, 0.035];
- const verticalGeo = [0.035, band.thickness, depth * 0.96];
- const faces = [
- { pos: [0, band.y, depth / 2 + 0.035], geo: horizontalGeo },
- { pos: [0, band.y, -(depth / 2 + 0.035)], geo: horizontalGeo },
- { pos: [width / 2 + 0.035, band.y, 0], geo: verticalGeo },
- { pos: [-(width / 2 + 0.035), band.y, 0], geo: verticalGeo },
- ];
- return (
- <group key={band.key}>
- {faces.map((face, i) => (
- <mesh key={i} position={face.pos}>
- <boxGeometry args={face.geo} />
- <meshBasicMaterial color={band.color} transparent opacity={band.opacity * dimMul} toneMapped={false} depthWrite={false} />
- </mesh>
- ))}
- </group>
- );
- })}
- </group>
- );
-}
-
-// A small, always-readable status marker replaces the old wall of floating holograms.
-// It gives each building a game-like "beacon" without turning every facade into a UI panel.
-function StatusBeacon({ height, color, accentColor, active = false, dimMul = 1 }) {
- const ringRef = useRef();
- const glowRef = useRef();
-
- useFrame(({ clock }) => {
- const t = clock.getElapsedTime();
- if (ringRef.current) ringRef.current.rotation.z = t * (active ? 0.9 : 0.35);
- if (glowRef.current) {
- glowRef.current.material.opacity = (active ? 0.5 + Math.sin(t * 3) * 0.15 : 0.28) * dimMul;
- }
- });
-
- return (
- <group position={[0, height + 0.08, 0]}>
- <mesh position={[0, 0.02, 0]}>
- <cylinderGeometry args={[0.16, 0.25, 0.06, 6]} />
- <meshBasicMaterial color={color} transparent opacity={0.42 * dimMul} />
- </mesh>
- <mesh ref={ringRef} rotation={[Math.PI / 2, 0, 0]}>
- <torusGeometry args={[0.32, 0.018, 6, 18]} />
- <meshBasicMaterial color={accentColor} transparent opacity={(active ? 0.72 : 0.34) * dimMul} />
- </mesh>
- <mesh ref={glowRef} position={[0, 0.18, 0]}>
- <octahedronGeometry args={[0.09, 0]} />
- <meshBasicMaterial color={accentColor} transparent opacity={0.35 * dimMul} />
- </mesh>
- </group>
- );
-}
-
-// The Vibes facade is a small cluster of matte, faceted masses rather than one cyber-era
-// slab. The seed comes from the app name, so the silhouette is stable across live updates
-// and playback. The main mass keeps the existing status-driven height/color semantics while
-// the side volumes provide the low-poly roofline variation the bright world needs.
-function LowPolyFacade({ width, depth, height, bodyColor, edgeColor, dimMul, surface, seed, meshRef, onClick, onPointerEnter, onPointerLeave }) {
- const variant = seed % 3;
- const side = variant === 0 ? -1 : 1;
- const shoulderWidth = width * (variant === 2 ? 0.34 : 0.24);
- const shoulderHeight = height * (variant === 1 ? 0.58 : 0.72);
- const shoulderDepth = depth * (variant === 0 ? 0.48 : 0.62);
- const shoulderColor = mixHex(bodyColor, edgeColor, 0.14);
-
- return (
- <group onClick={onClick} onPointerEnter={onPointerEnter} onPointerLeave={onPointerLeave}>
- <mesh ref={meshRef} position={[0, height / 2, 0]}>
- <boxGeometry args={[width * 0.78, height, depth * 0.78]} />
- <meshStandardMaterial
- {...surface}
- color={bodyColor}
- emissive={edgeColor}
- emissiveIntensity={0.14 * dimMul}
- transparent
- opacity={dimMul}
- />
- </mesh>
- <mesh position={[side * width * 0.27, shoulderHeight / 2 + height * 0.16, 0]} rotation={[0, variant * 0.18, variant % 2 ? 0.08 : -0.08]}>
- <boxGeometry args={[shoulderWidth, shoulderHeight, shoulderDepth]} />
- <meshStandardMaterial
- {...surface}
- color={shoulderColor}
- emissive={edgeColor}
- emissiveIntensity={0.08 * dimMul}
- transparent
- opacity={0.94 * dimMul}
- />
- </mesh>
- <mesh position={[-side * width * 0.24, height * 0.22, depth * 0.08]} rotation={[0, -variant * 0.14, -0.06]}>
- <boxGeometry args={[width * 0.22, height * 0.44, depth * 0.42]} />
- <meshStandardMaterial {...surface} color={mixHex(bodyColor, '#ffffff', 0.08)} roughness={0.98} />
- </mesh>
- </group>
- );
-}
-
-// Always-visible health belt (Roadmap 1.1) — a thin status-colored band wrapping all
-// four façades so the LED reads from any orbit angle, not just the labeled front.
-function HealthBandMeshes({ width, height, depth, color, dimMul, opacity, bandRef }) {
- const y = Math.max(0.4, height * 0.72);
- return (
- <group position={[0, y, 0]}>
- <mesh>
- <boxGeometry args={[width + 0.08, 0.07, depth + 0.08]} />
- <meshBasicMaterial color="#0f172a" transparent opacity={0.78 * dimMul} />
- </mesh>
- <mesh ref={bandRef}>
- <boxGeometry args={[width + 0.05, 0.038, depth + 0.05]} />
- <meshBasicMaterial color={color} transparent opacity={opacity} toneMapped={false} />
- </mesh>
- </group>
- );
-}
-
-function PulsingHealthBand({ width, height, depth, color, tone, dimMul }) {
- const ref = useRef();
- useFrame(({ clock }) => {
- if (!ref.current) return;
- const t = clock.getElapsedTime();
- const pulse = tone === 'busy'
- ? 0.6 + Math.sin(t * 2.5) * 0.2
- : 0.55 + Math.sin(t * 6) * 0.35;
- ref.current.material.opacity = pulse * dimMul;
- });
- return (
- <HealthBandMeshes
- width={width}
- height={height}
- depth={depth}
- color={color}
- dimMul={dimMul}
- opacity={0.7 * dimMul}
- bandRef={ref}
- />
- );
-}
-
-function BuildingHealthBand({ width, height, depth, color, tone = 'idle', pulsing = false, dimMul = 1, dayMix = 0 }) {
- if (pulsing) {
- return (
- <PulsingHealthBand
- width={width}
- height={height}
- depth={depth}
- color={color}
- tone={tone}
- dimMul={dimMul}
- />
- );
- }
- return (
- <HealthBandMeshes
- width={width}
- height={height}
- depth={depth}
- color={color}
- dimMul={dimMul}
- opacity={(0.62 - dayMix * 0.18) * dimMul}
- />
- );
-}
-
-// Stress smoke / sparks (Roadmap 1.2) — rooftop plume for a hot CPU, sparks for a crash.
-// Parent mounts this only when smoke or sparks is actually on, so healthy buildings pay
-// no extra useFrame. Hooks always run (no early return) to satisfy the rules of hooks.
-function StressEffects({ height, smoke = false, sparks = false, dimMul = 1 }) {
- const smokeRef = useRef();
- const sparksRef = useRef();
-
- useFrame(({ clock }) => {
- const t = clock.getElapsedTime();
- if (smokeRef.current) {
- smokeRef.current.children.forEach((puff, i) => {
- const age = (t * 0.8 + i * 0.33) % 1.0;
- puff.position.y = age * 1.6;
- puff.position.x = Math.sin(t * 1.5 + i * 2) * 0.15 * age;
- puff.position.z = Math.cos(t * 1.2 + i * 2) * 0.15 * age;
- puff.scale.setScalar(0.08 + age * 0.22);
- if (puff.material) puff.material.opacity = (1 - age) * 0.45 * dimMul;
- });
- }
- if (sparksRef.current) {
- sparksRef.current.children.forEach((spark, i) => {
- const age = (t * 2.2 + i * 0.25) % 1.0;
- spark.position.y = age * 0.9;
- spark.position.x = Math.sin(t * 8 + i * 4) * 0.25;
- spark.position.z = Math.cos(t * 7 + i * 3) * 0.25;
- if (spark.material) spark.material.opacity = (1 - age) * 0.8 * dimMul;
- });
- }
- });
-
- return (
- <group position={[0, height + 0.1, 0]}>
- {smoke && (
- <group ref={smokeRef}>
- {[0, 1, 2].map((i) => (
- <mesh key={`smoke-${i}`} geometry={SMOKE_GEOM}>
- <meshBasicMaterial color="#64748b" transparent opacity={0.3} depthWrite={false} />
- </mesh>
- ))}
- </group>
- )}
- {sparks && (
- <group ref={sparksRef}>
- {[0, 1, 2, 3].map((i) => (
- <mesh key={`spark-${i}`} geometry={SPARK_GEOM}>
- <meshBasicMaterial color="#f59e0b" transparent opacity={0.8} toneMapped={false} depthWrite={false} />
- </mesh>
- ))}
- </group>
- )}
- </group>
- );
-}
-
-export default function Building({ app, position, agentCount, onClick, playSfx, neonBrightness = 1.2, isProximity = false, focused = false, dimmed = false, dayMix = 0, playback = false, transitionState = null, onExited, rooftops = true, interiorWindows = false }) {
- const meshRef = useRef();
- const glowRef = useRef();
- const haloRef = useRef();
- const groupRef = useRef();
- const [hovered, setHovered] = useState(false);
-
- // Construction/teardown animation state (playback/scrubber only — issue #967).
- // In live mode buildings appear/disappear instantly as today; during playback a
- // newly-present building scales in from 0 (construction) and a departing one
- // scales out to 0 (teardown) before the cluster unmounts it.
- const exiting = transitionState === 'exiting';
- // Start small only when entering under playback; otherwise full size.
- const initialScale = playback && !exiting ? 0.001 : 1;
- const exitedFiredRef = useRef(false);
- // Smoothly-lerped status color so a status change recolors over a beat rather
- // than snapping. `displayed` is the current on-screen color; `target` is the
- // status color it eases toward. Both are persistent THREE.Color instances so
- // the per-frame lerp allocates nothing.
- const displayedColorRef = useRef(null);
- const targetColorRef = useRef(null);
-
- // `surface` carries the world style's finish (flat shading + matte under the low-poly
- // style); spread last on the facade material so it wins over the cyber defaults.
- const { getBuildingColor, getAccentColor, tintStructure, surface, lowPoly, neonLayers } = useOpenWorldPalette();
- const height = getBuildingHeight(app);
- const edgeColor = getBuildingColor(app.overallStatus, app.archived);
- const accentColor = getAccentColor(app);
- const isOnline = app.overallStatus === 'online' && !app.archived;
- const isStopped = app.overallStatus === 'stopped' && !app.archived;
- const { width, depth } = BUILDING_PARAMS;
- const dimMul = dimmed ? 0.25 : 1;
-
- // Daytime treatment: the building sheds its neon and reads as a sunlit solid. The
- // facade lerps from the dark cyber body toward a light, faintly status-tinted
- // wall; the dark window texture is dropped (it only reads at night) and the neon
- // edge softens to a plain architectural outline.
- // NOTE: dayMix is currently strictly 0 or 1 (the city renders only noon/sunset), so
- // the continuous lerps and the `daytime` hard-switches agree today. The lerps are
- // forward-looking — if an intermediate time-of-day is ever re-enabled, convert the
- // `!daytime`-gated mounts (halo/strips/glow/ground-lines) to opacity fades too so a
- // partial dayMix degrades gracefully instead of popping at 0.5.
- const daytime = dayMix > 0.5;
- const showNightFx = neonLayers && !daytime;
- const showBuildingSignal = !dimmed && (hovered || isProximity || focused);
- // Mid-tone facade (not near-white) so strong daylight lands around a clean gray
- // rather than clipping to white; a touch of the status color keeps variety.
- const dayFacade = mixHex('#9aa0ac', edgeColor, 0.12);
- const nightFacade = mixHex(app.archived ? '#273247' : '#26375d', edgeColor, app.archived ? 0.12 : 0.2);
- const bodyColor = mixHex(nightFacade, dayFacade, dayMix);
- const edgeLineColor = daytime ? mixHex('#4a4f57', edgeColor, 0.15) : edgeColor;
-
- // Name hash for seeded randomness
- const seed = useMemo(() => {
- let h = 0;
- const n = app.name || app.id;
- for (let i = 0; i < n.length; i++) h = ((h << 5) - h) + n.charCodeAt(i);
- return Math.abs(h);
- }, [app.name, app.id]);
-
- const metrics = useMemo(() => computeAppMetrics(app), [app]);
- const signal = useMemo(
- () => buildingSignalTone({
- status: app.overallStatus,
- metrics,
- pm2Status: app.pm2Status,
- playback,
- }),
- [app.overallStatus, metrics, app.pm2Status, playback]
- );
-
- const boxGeom = useMemo(() => new THREE.BoxGeometry(width, height, depth), [width, height, depth]);
- const edgesGeom = useMemo(() => new THREE.EdgesGeometry(boxGeom), [boxGeom]);
- useEffect(() => () => boxGeom.dispose(), [boxGeom]);
- useEffect(() => () => edgesGeom.dispose(), [edgesGeom]);
-
- // Night-only glow halo: memoized so re-renders don't force R3F to rebuild the
- // edges geometry (an inline `new THREE.BoxGeometry` in args changes identity
- // every render), and disposed on replace + unmount like the geometries above.
- const haloEdgesGeom = useMemo(
- () => new THREE.EdgesGeometry(new THREE.BoxGeometry(width + 0.15, height + 0.15, depth + 0.15)),
- [width, height, depth]
- );
- useEffect(() => () => haloEdgesGeom.dispose(), [haloEdgesGeom]);
-
- // Window texture with pixel art icon. Built ONLY when the facade will actually bind it:
- // the daytime material drops `map`/`emissiveMap` entirely, and the Vibes world style is
- // daytime at both times of day — so without this gate every install on the default style
- // would rasterize a full canvas per building (nested fillRect loops, ~1–2k 2D ops each)
- // at scene mount and again on every theme-accent change, and bind none of them.
- const windowTexture = useMemo(
- () => (showNightFx ? createWindowTexture(accentColor, width, height, seed, tintStructure) : null),
- [showNightFx, accentColor, width, height, seed, tintStructure]
- );
-
- // R3F does NOT dispose a CanvasTexture handed in via `map`/`emissiveMap` — it
- // only frees objects it owns on unmount. Since the city no longer remounts on
- // theme switch (issue-1064), each recolor recreates this texture and would
- // strand the previous one in VRAM per building. Dispose it on replace + unmount.
- useEffect(() => () => windowTexture?.dispose(), [windowTexture]);
-
- // Format name for building face
- const displayName = useMemo(() => {
- return (app.name || '').replace(/[-_.]/g, ' ').toUpperCase();
- }, [app.name]);
-
- useFrame(({ clock }, delta) => {
- // Construction/teardown scale animation (playback only). damp() eases the
- // group scale toward 1 (entering) or 0 (exiting); reaching ~0 on exit fires
- // onExited so the cluster can drop the building from the tree.
- if (groupRef.current && playback) {
- const target = exiting ? 0 : 1;
- const cur = groupRef.current.scale.x;
- const next = THREE.MathUtils.damp(cur, target, 6, delta || 0.016);
- groupRef.current.scale.setScalar(next);
- if (exiting && next < 0.02 && !exitedFiredRef.current) {
- exitedFiredRef.current = true;
- onExited?.(app.id);
- }
- } else if (groupRef.current && groupRef.current.scale.x !== 1) {
- // Live mode (or after entering completes): ensure full size.
- groupRef.current.scale.setScalar(1);
- }
-
- if (!meshRef.current) return;
- const t = clock.getElapsedTime();
-
- // Status recolor: ease the body emissive toward the current status color so a
- // scrub that flips online→stopped fades cyan→red rather than snapping. Skip
- // the work entirely once the displayed color has converged (the common case,
- // including all of live mode) so it costs nothing per frame at rest.
- const mat = meshRef.current.material;
- if (mat?.emissive) {
- if (!displayedColorRef.current) displayedColorRef.current = new THREE.Color(edgeColor);
- if (!targetColorRef.current) targetColorRef.current = new THREE.Color();
- targetColorRef.current.set(edgeColor);
- const disp = displayedColorRef.current;
- const tgt = targetColorRef.current;
- if (Math.abs(disp.r - tgt.r) + Math.abs(disp.g - tgt.g) + Math.abs(disp.b - tgt.b) > 0.002) {
- disp.lerp(tgt, Math.min(1, (delta || 0.016) * 6));
- mat.emissive.copy(disp);
- } else if (!disp.equals(tgt)) {
- disp.copy(tgt);
- mat.emissive.copy(disp);
- }
- }
-
- const nb = neonBrightness;
- const baseIntensity = (isOnline ? 0.5 : isStopped ? 0.35 : 0.2) * nb;
- const pulse = isOnline
- ? Math.sin(t * 2 + seed) * 0.15 * nb
- : isStopped
- ? Math.sin(t * 3.5 + seed) * 0.2 * nb
- : 0;
- const hoverBoost = hovered ? 0.4 * nb : 0;
- // Neon self-glow fades out in daylight — the building is lit by the sun instead.
- meshRef.current.material.emissiveIntensity = (baseIntensity + pulse + hoverBoost) * dimMul * (1 - dayMix * 0.9);
-
- if (glowRef.current) {
- glowRef.current.material.opacity = (0.35 + (isOnline ? Math.sin(t * 1.5) * 0.12 : 0) + (hovered ? 0.25 : 0)) * dimMul;
- }
-
- // Glow halo wireframe pulse
- if (haloRef.current) {
- const haloBase = hovered
- ? 0.15 + Math.sin(t * 8) * 0.1
- : 0.05 + Math.sin(t * 1.5 + seed) * 0.03;
- haloRef.current.material.opacity = haloBase * dimMul;
- }
- });
-
- return (
- <group ref={groupRef} position={[position.x, 0, position.z]} scale={initialScale}>
- {/* Building body with window texture + pixel art icon. Vibes replaces the flat slab
- with a deterministic low-poly massing cluster; cyber keeps the established slab. */}
- {lowPoly ? (
- <LowPolyFacade
- width={width}
- depth={depth}
- height={height}
- bodyColor={bodyColor}
- edgeColor={edgeColor}
- dimMul={dimMul}
- surface={surface}
- seed={seed}
- meshRef={meshRef}
- onClick={() => { playSfx?.('buildingClick'); onClick?.(); }}
- onPointerEnter={() => { setHovered(true); playSfx?.('buildingHover'); }}
- onPointerLeave={() => setHovered(false)}
- />
- ) : (
- <mesh
- ref={meshRef}
- position={[0, height / 2, 0]}
- onClick={() => { playSfx?.('buildingClick'); onClick?.(); }}
- onPointerEnter={() => { setHovered(true); playSfx?.('buildingHover'); }}
- onPointerLeave={() => setHovered(false)}
- >
- <boxGeometry args={[width, height, depth]} />
- <meshStandardMaterial
- color="#ffffff"
- emissive={edgeColor}
- emissiveIntensity={0.7 * neonBrightness * dimMul * (1 - dayMix * 0.88)}
- map={windowTexture || undefined}
- emissiveMap={windowTexture || undefined}
- roughness={0.78}
- metalness={0.08}
- {...surface}
- transparent
- opacity={(app.archived ? 0.78 : 1) * dimMul}
- />
- </mesh>
- )}
-
- {/* Interior-mapped window panes (InteriorMappingMaterial) — parallax fake-3D lit
- rooms on selected online towers. Night-only (by day the tower reads as a
- sunlit solid) and gated to the high quality preset by the caller. */}
- {showNightFx && interiorWindows && buildingHasInteriorWindows(app, height) && (
- <BuildingWindows
- width={width}
- depth={depth}
- height={height}
- seed={seed}
- accentColor={accentColor}
- edgeColor={edgeColor}
- neonBrightness={neonBrightness}
- dimMul={dimMul}
- />
- )}
-
- {/* Building edges — bright neon by night, a plain architectural outline by day */}
- <lineSegments position={[0, height / 2, 0]} geometry={edgesGeom}>
- <lineBasicMaterial
- color={edgeLineColor}
- transparent
- opacity={(neonLayers ? (app.archived ? 0.5 : 0.9) - dayMix * 0.55 : (focused || hovered ? 0.55 : 0.22)) * dimMul}
- />
- </lineSegments>
-
- {/* Reflective glass roof cap on online buildings */}
- <mesh position={[0, height + 0.02, 0]} rotation={[-Math.PI / 2, 0, 0]}>
- <planeGeometry args={[width + 0.1, depth + 0.1]} />
- {isOnline ? (
- <meshPhysicalMaterial
- color={edgeColor}
- roughness={0.1}
- metalness={0.8}
- transparent
- opacity={0.7 * dimMul}
- />
- ) : (
- <meshBasicMaterial
- color={edgeColor}
- transparent
- opacity={(app.archived ? 0.2 : 0.5) * dimMul}
- />
- )}
- </mesh>
-
- {/* Rooftop fixtures — deterministic per app name; off on the low preset */}
- {rooftops && <RooftopKit name={app.name || app.id} width={width} y={height} />}
-
- {!app.archived && (
- <StatusBeacon
- height={height}
- color={edgeColor}
- accentColor={accentColor}
- active={isProximity || focused || hovered}
- dimMul={dimMul}
- />
- )}
-
- {/* Glow halo wireframe - slightly larger than building (night only) */}
- {!app.archived && showNightFx && (
- <lineSegments ref={haloRef} position={[0, height / 2, 0]} geometry={haloEdgesGeom}>
- <lineBasicMaterial
- color={accentColor}
- transparent
- opacity={0.05 * dimMul}
- />
- </lineSegments>
- )}
-
- {/* Vertical neon edge strips on corners (night only) */}
- {!app.archived && showNightFx && (
- <>
- <NeonEdgeStrip position={[width / 2, height / 2, depth / 2]} height={height} color={accentColor} delay={0} dimMul={dimMul} />
- <NeonEdgeStrip position={[-width / 2, height / 2, depth / 2]} height={height} color={accentColor} delay={1} dimMul={dimMul} />
- <NeonEdgeStrip position={[width / 2, height / 2, -depth / 2]} height={height} color={accentColor} delay={2} dimMul={dimMul} />
- <NeonEdgeStrip position={[-width / 2, height / 2, -depth / 2]} height={height} color={accentColor} delay={3} dimMul={dimMul} />
- </>
- )}
-
- {/* Lit floor bands stay on even for archived buildings so dark towers remain readable. */}
- {showNightFx && (
- <FloorLightBands
- width={width}
- depth={depth}
- height={height}
- color={app.archived ? '#94a3b8' : edgeColor}
- accentColor={app.archived ? '#64748b' : accentColor}
- seed={seed}
- dimMul={dimMul * (app.archived ? 0.58 : 1)}
- />
- )}
-
- {/* Building name on front face - pixel font (dark ink + halo by day) */}
- <OpenWorldLabel
- position={[0, height * 0.88, depth / 2 + 0.02]}
- fontSize={0.2}
- color={edgeColor}
- dayMix={dayMix}
- fillOpacity={dimMul}
- anchorX="center"
- anchorY="middle"
- font={PIXEL_FONT_URL}
- maxWidth={width * 0.9}
- >
- {displayName}
- </OpenWorldLabel>
-
- {/* Always-visible wrapping health belt (Roadmap 1.1) */}
- {!app.archived && (
- <BuildingHealthBand
- width={width}
- height={height}
- depth={depth}
- color={signal.color}
- tone={signal.tone}
- pulsing={signal.pulsing}
- dimMul={dimMul}
- dayMix={dayMix}
- />
- )}
-
- {/* Stress smoke / sparks on rooftop when CPU is hot or crashed (Roadmap 1.2) */}
- {!app.archived && (signal.smoke || signal.sparks) && (
- <StressEffects
- height={height}
- smoke={signal.smoke}
- sparks={signal.sparks}
- dimMul={dimMul}
- />
- )}
-
- {/* Focus selection ring (issue #2593) — a bright accent ring at the base marking the
- URL-focused borough. Rendered day AND night (unlike the neon glow) so the selected
- building is unambiguously distinguished in any lighting. */}
- {focused && (
- <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.04, 0]}>
- <ringGeometry args={[Math.max(width, depth) * 0.9 + 0.6, Math.max(width, depth) * 0.9 + 0.95, 48]} />
- <meshBasicMaterial color={accentColor} transparent opacity={0.95} side={THREE.DoubleSide} />
- </mesh>
- )}
-
- {/* Base glow circle - wider and brighter (night only) */}
- {showNightFx && (
- <mesh ref={glowRef} rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.01, 0]}>
- <circleGeometry args={[1.8, 32]} />
- <meshBasicMaterial
- color={edgeColor}
- transparent
- opacity={0.25 * dimMul}
- side={THREE.DoubleSide}
- />
- </mesh>
- )}
-
- {/* Daytime contact shadow — grounds the tower on the meadow so it doesn't float. */}
- {daytime && !app.archived && (
- <mesh
- geometry={CONTACT_SHADOW_GEOM}
- rotation={[-Math.PI / 2, 0, 0]}
- position={[0, 0.008, 0]}
- scale={[Math.max(width, depth) * 0.82, Math.max(width, depth) * 0.82, 1]}
- >
- <meshBasicMaterial color="#0b1220" transparent opacity={0.26 * dimMul} depthWrite={false} />
- </mesh>
- )}
-
- {/* Neon ground line accents (night only) */}
- {!app.archived && showNightFx && (
- <>
- <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.02, depth / 2 + 0.3]}>
- <planeGeometry args={[width + 0.5, 0.05]} />
- <meshBasicMaterial color={accentColor} transparent opacity={0.5 * dimMul} />
- </mesh>
- <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.02, -(depth / 2 + 0.3)]}>
- <planeGeometry args={[width + 0.5, 0.05]} />
- <meshBasicMaterial color={accentColor} transparent opacity={0.5 * dimMul} />
- </mesh>
- </>
- )}
-
- {/* Rooftop antenna */}
- {!app.archived && (
- <RooftopAntenna
- height={height}
- color={edgeColor}
- accentColor={accentColor}
- seed={seed}
- width={width}
- dimMul={dimMul}
- />
- )}
-
- {/* A signal appears only when the player is actually looking at a building. This
- keeps the world legible at a distance and makes proximity feel rewarding. */}
- {showBuildingSignal && (
- <BuildingHologram
- position={[0, height + 0.8, 0]}
- color={accentColor}
- seed={seed}
- />
- )}
-
- {showBuildingSignal && (
- <HolographicPanel
- app={app}
- agentCount={agentCount}
- position={[0, height + 1.8, 0]}
- expanded={isProximity || focused}
- playback={playback}
- />
- )}
- </group>
- );
-}
diff --git a/client/src/components/openworld/Building.test.jsx b/client/src/components/openworld/Building.test.jsx
deleted file mode 100644
index a85bb886d4..0000000000
--- a/client/src/components/openworld/Building.test.jsx
+++ /dev/null
@@ -1,123 +0,0 @@
-import { describe, it, expect, vi } from 'vitest';
-import { render } from '@testing-library/react';
-
-vi.mock('@react-three/fiber', () => ({ useFrame: () => {} }));
-vi.mock('./OpenWorldPaletteContext', () => ({
- useOpenWorldPalette: () => ({
- getBuildingColor: (status, archived) => (archived ? '#475569' : status === 'online' ? '#06b6d4' : '#ef4444'),
- getAccentColor: () => '#06b6d4',
- tintStructure: (c) => c,
- surface: {},
- lowPoly: false,
- neonLayers: true,
- }),
-}));
-vi.mock('./BuildingHologram', () => ({ default: () => <div data-testid="hologram" /> }));
-vi.mock('./HolographicPanel', () => ({ default: () => <div data-testid="panel" /> }));
-vi.mock('./OpenWorldLabel', () => ({ default: ({ children }) => <div data-testid="label">{children}</div> }));
-vi.mock('./BuildingWindows', () => ({ default: () => <div data-testid="windows" /> }));
-
-import Building from './Building';
-
-describe('Building component', () => {
- const mockApp = {
- id: 'test-app',
- name: 'Test App',
- overallStatus: 'online',
- archived: false,
- pm2Status: {
- worker1: { status: 'online', cpu: 15, memory: 104857600, uptime: 100000 },
- },
- };
-
- it('renders building mesh, health strip, and label for an active app', () => {
- const { container } = render(
- <Building
- app={mockApp}
- position={{ x: 0, z: 0 }}
- agentCount={1}
- />
- );
- expect(container.getElementsByTagName('mesh').length).toBeGreaterThan(0);
- expect(container.querySelector('[data-testid="label"]')?.textContent).toBe('TEST APP');
- });
-
- it('renders stress effects when CPU is hot', () => {
- const hotApp = {
- ...mockApp,
- pm2Status: {
- worker1: { status: 'online', cpu: 92, memory: 500000000, uptime: 100000 },
- },
- };
- const { container } = render(
- <Building
- app={hotApp}
- position={{ x: 0, z: 0 }}
- agentCount={0}
- />
- );
- expect(container.getElementsByTagName('group').length).toBeGreaterThan(0);
- });
-
- it('renders stress effects when PM2 process is errored', () => {
- const errorApp = {
- ...mockApp,
- pm2Status: {
- worker1: { status: 'errored', cpu: 0, memory: 0, uptime: 0 },
- },
- };
- const { container } = render(
- <Building
- app={errorApp}
- position={{ x: 0, z: 0 }}
- agentCount={0}
- />
- );
- expect(container.getElementsByTagName('group').length).toBeGreaterThan(0);
- });
-
- it('suppresses live stress effects during history playback', () => {
- const hotApp = {
- ...mockApp,
- pm2Status: {
- worker1: { status: 'online', cpu: 95, memory: 500000000, uptime: 100000 },
- },
- };
- const { container } = render(
- <Building
- app={hotApp}
- position={{ x: 0, z: 0 }}
- agentCount={0}
- playback={true}
- />
- );
- expect(container).toBeTruthy();
- });
-
- it('omits health strip and stress effects for archived apps', () => {
- const archivedApp = {
- ...mockApp,
- archived: true,
- };
- const { container } = render(
- <Building
- app={archivedApp}
- position={{ x: 0, z: 0 }}
- agentCount={0}
- />
- );
- expect(container).toBeTruthy();
- });
-
- it('does not mount rooftop stress meshes for a calm healthy app', () => {
- const { container } = render(
- <Building
- app={mockApp}
- position={{ x: 0, z: 0 }}
- agentCount={0}
- />
- );
- const meshes = container.getElementsByTagName('mesh');
- expect(meshes.length).toBeGreaterThan(0);
- });
-});
diff --git a/client/src/components/openworld/BuildingCluster.jsx b/client/src/components/openworld/BuildingCluster.jsx
deleted file mode 100644
index d9605a0319..0000000000
--- a/client/src/components/openworld/BuildingCluster.jsx
+++ /dev/null
@@ -1,121 +0,0 @@
-import { useMemo, useEffect, useRef, useState, useCallback } from 'react';
-import { computeOpenWorldLayout } from './openWorldLayout';
-import { DISTRICT_PARAMS, PIXEL_FONT_URL, openWorldDayMix } from './openWorldConstants';
-import Borough from './Borough';
-import OpenWorldLabel from './OpenWorldLabel';
-
-export default function BuildingCluster({ apps, agentMap, onBuildingClick, onPositionsReady, playSfx, settings, proximityAppId, dimmedAppIds, focusedAppId, playback = false }) {
- const positions = useMemo(() => computeOpenWorldLayout(apps), [apps]);
- const dayMix = openWorldDayMix(settings);
-
- // Notify parent when positions change (for data streams, roads, traffic)
- useEffect(() => {
- onPositionsReady?.(positions);
- }, [positions, onPositionsReady]);
-
- // Teardown lifecycle (playback/scrubber only — issue #967). When an app id
- // disappears between frames, React would unmount its building instantly. To
- // animate the teardown, retain the departed app (with its last-known position)
- // in `exiting` and render it with transitionState='exiting' until the
- // building's scale-out completes and fires onExited. In live mode this stays
- // empty so behavior is unchanged.
- const prevRef = useRef(new Map()); // id → app (previous render)
- const prevPositionsRef = useRef(new Map()); // id → pos (previous render)
- const [exiting, setExiting] = useState([]);
- useEffect(() => {
- const current = new Map(apps.map(a => [a.id, a]));
- if (playback) {
- const departed = [];
- for (const [id, app] of prevRef.current) {
- if (current.has(id)) continue;
- const prevPos = prevPositionsRef.current.get(id);
- if (prevPos) departed.push({ app, pos: prevPos });
- }
- setExiting(prev => {
- // Drop anything that came back this frame, then add newly-departed ids.
- const kept = prev.filter(e => !current.has(e.app.id));
- const have = new Set(kept.map(e => e.app.id));
- return [...kept, ...departed.filter(d => !have.has(d.app.id))];
- });
- } else if (exiting.length > 0) {
- setExiting([]); // leaving playback: clear any in-flight teardowns
- }
- prevRef.current = current;
- prevPositionsRef.current = positions;
- }, [apps, positions, playback]);
-
- const handleExited = useCallback((id) => {
- setExiting(prev => prev.filter(e => e.app.id !== id));
- }, []);
-
- const hasArchived = apps.some(a => a.archived);
-
- const warehouseMinZ = useMemo(() => {
- let minZ = Infinity;
- positions.forEach((pos) => {
- if (pos.district === 'warehouse' && pos.z < minZ) minZ = pos.z;
- });
- return minZ === Infinity ? DISTRICT_PARAMS.warehouseOffset : minZ;
- }, [positions]);
-
- return (
- <group>
- {apps.map(app => {
- const pos = positions.get(app.id);
- if (!pos) return null;
-
- return (
- <Borough
- key={app.id}
- app={app}
- position={pos}
- agentMap={agentMap}
- onBuildingClick={onBuildingClick}
- playSfx={playSfx}
- neonBrightness={settings?.neonBrightness ?? 1.2}
- isProximity={proximityAppId === app.id}
- focused={focusedAppId === app.id}
- dimmed={dimmedAppIds?.has?.(app.id) || false}
- settings={settings}
- playback={playback}
- transitionState="entering"
- />
- );
- })}
-
- {/* Departed buildings animating out (playback teardown) */}
- {exiting.map(({ app, pos }) => (
- <Borough
- key={`exit-${app.id}`}
- app={app}
- position={pos}
- agentMap={agentMap}
- onBuildingClick={onBuildingClick}
- playSfx={playSfx}
- neonBrightness={settings?.neonBrightness ?? 1.2}
- isProximity={false}
- dimmed={dimmedAppIds?.has?.(app.id) || false}
- settings={settings}
- playback={playback}
- transitionState="exiting"
- onExited={handleExited}
- />
- ))}
-
- {/* Warehouse district label - pixel font (dark ink + halo by day) */}
- {hasArchived && (
- <OpenWorldLabel
- position={[0, 1.5, warehouseMinZ - 2]}
- fontSize={0.8}
- color="#475569"
- dayMix={dayMix}
- anchorX="center"
- anchorY="middle"
- font={PIXEL_FONT_URL}
- >
- ARCHIVE DISTRICT
- </OpenWorldLabel>
- )}
- </group>
- );
-}
diff --git a/client/src/components/openworld/BuildingHologram.jsx b/client/src/components/openworld/BuildingHologram.jsx
deleted file mode 100644
index e54b19fad8..0000000000
--- a/client/src/components/openworld/BuildingHologram.jsx
+++ /dev/null
@@ -1,161 +0,0 @@
-import { useRef } from 'react';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-
-const HOLOGRAM_TYPES = ['diamond', 'invertedPyramid', 'saturn', 'rings', 'cube', 'beacon'];
-
-// Every Holo* shape's geometry below has fixed parameters — `color`/`seed` only
-// drive material/animation, never geometry — so each is a module-scope singleton
-// shared by every hologram instance, mirroring Building.jsx's ROOF_GEOMS pattern.
-// A per-instance useMemo would otherwise allocate fresh, never-disposed GPU
-// geometry on every mount, and holograms mount/unmount on every dim/undim.
-const DIAMOND_GEOM = new THREE.OctahedronGeometry(0.5, 0);
-const DIAMOND_EDGES = new THREE.EdgesGeometry(DIAMOND_GEOM);
-
-const PYRAMID_GEOM = new THREE.ConeGeometry(0.5, 0.8, 4);
-const PYRAMID_EDGES = new THREE.EdgesGeometry(PYRAMID_GEOM);
-
-const SATURN_SPHERE_GEOM = new THREE.IcosahedronGeometry(0.25, 1);
-const SATURN_RING_GEOM = new THREE.TorusGeometry(0.5, 0.025, 8, 32);
-const SATURN_SPHERE_EDGES = new THREE.EdgesGeometry(SATURN_SPHERE_GEOM);
-
-const RINGS_GEOMS = [
- new THREE.TorusGeometry(0.45, 0.02, 8, 24),
- new THREE.TorusGeometry(0.3, 0.02, 8, 24),
- new THREE.TorusGeometry(0.38, 0.02, 8, 24),
-];
-
-const CUBE_GEOM = new THREE.BoxGeometry(0.45, 0.45, 0.45);
-const CUBE_EDGES = new THREE.EdgesGeometry(CUBE_GEOM);
-
-const BEACON_CYL_GEOM = new THREE.CylinderGeometry(0.025, 0.025, 0.5, 6);
-const BEACON_SPHERE_GEOM = new THREE.SphereGeometry(0.15, 8, 8);
-
-function HoloDiamond({ color }) {
- return (
- <group>
- <mesh geometry={DIAMOND_GEOM}>
- <meshBasicMaterial color={color} transparent opacity={0.12} side={THREE.DoubleSide} />
- </mesh>
- <lineSegments geometry={DIAMOND_EDGES}>
- <lineBasicMaterial color={color} transparent opacity={0.85} />
- </lineSegments>
- </group>
- );
-}
-
-function HoloPyramid({ color }) {
- return (
- <group rotation={[Math.PI, 0, Math.PI / 4]}>
- <mesh geometry={PYRAMID_GEOM}>
- <meshBasicMaterial color={color} transparent opacity={0.12} side={THREE.DoubleSide} />
- </mesh>
- <lineSegments geometry={PYRAMID_EDGES}>
- <lineBasicMaterial color={color} transparent opacity={0.85} />
- </lineSegments>
- </group>
- );
-}
-
-function HoloSaturn({ color }) {
- return (
- <group>
- <mesh geometry={SATURN_SPHERE_GEOM}>
- <meshBasicMaterial color={color} transparent opacity={0.15} />
- </mesh>
- <lineSegments geometry={SATURN_SPHERE_EDGES}>
- <lineBasicMaterial color={color} transparent opacity={0.7} />
- </lineSegments>
- <mesh geometry={SATURN_RING_GEOM} rotation={[Math.PI / 3, 0.3, 0]}>
- <meshBasicMaterial color={color} transparent opacity={0.35} side={THREE.DoubleSide} />
- </mesh>
- </group>
- );
-}
-
-function HoloRings({ color }) {
- return (
- <group>
- {RINGS_GEOMS.map((geom, i) => (
- <mesh key={i} geometry={geom} position={[0, (i - 1) * 0.22, 0]} rotation={[Math.PI / 2, 0, 0]}>
- <meshBasicMaterial color={color} transparent opacity={0.45 + i * 0.15} side={THREE.DoubleSide} />
- </mesh>
- ))}
- </group>
- );
-}
-
-function HoloCube({ color }) {
- return (
- <group rotation={[Math.PI / 6, Math.PI / 4, 0]}>
- <mesh geometry={CUBE_GEOM}>
- <meshBasicMaterial color={color} transparent opacity={0.08} />
- </mesh>
- <lineSegments geometry={CUBE_EDGES}>
- <lineBasicMaterial color={color} transparent opacity={0.85} />
- </lineSegments>
- </group>
- );
-}
-
-function HoloBeacon({ color }) {
- return (
- <group>
- <mesh geometry={BEACON_CYL_GEOM}>
- <meshBasicMaterial color={color} transparent opacity={0.5} />
- </mesh>
- <mesh geometry={BEACON_SPHERE_GEOM} position={[0, 0.32, 0]}>
- <meshBasicMaterial color={color} transparent opacity={0.75} />
- </mesh>
- </group>
- );
-}
-
-const SHAPES = {
- diamond: HoloDiamond,
- invertedPyramid: HoloPyramid,
- saturn: HoloSaturn,
- rings: HoloRings,
- cube: HoloCube,
- beacon: HoloBeacon,
-};
-
-export default function BuildingHologram({ position, color, seed }) {
- const bobRef = useRef();
- const spinRef = useRef();
- const glowRef = useRef();
-
- const type = HOLOGRAM_TYPES[seed % HOLOGRAM_TYPES.length];
- const Shape = SHAPES[type];
-
- useFrame(({ clock }) => {
- const t = clock.getElapsedTime();
- if (bobRef.current) {
- bobRef.current.position.y = Math.sin(t * 1.0 + seed * 0.7) * 0.15;
- }
- if (spinRef.current) {
- spinRef.current.rotation.y = t * 0.4 + seed;
- }
- if (glowRef.current) {
- glowRef.current.opacity = 0.15 + Math.sin(t * 1.5 + seed) * 0.08;
- }
- });
-
- return (
- <group position={position}>
- {/* Projector base disc */}
- <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, -0.1, 0]}>
- <circleGeometry args={[0.5, 16]} />
- <meshBasicMaterial ref={glowRef} color={color} transparent opacity={0.15} side={THREE.DoubleSide} />
- </mesh>
- {/* Animated hologram shape */}
- <group ref={bobRef}>
- <group ref={spinRef}>
- <Shape color={color} />
- </group>
- </group>
- {/* Subtle point light glow */}
- <pointLight color={color} intensity={0.5} distance={4} decay={2} />
- </group>
- );
-}
diff --git a/client/src/components/openworld/BuildingWindows.jsx b/client/src/components/openworld/BuildingWindows.jsx
deleted file mode 100644
index 95d54413d6..0000000000
--- a/client/src/components/openworld/BuildingWindows.jsx
+++ /dev/null
@@ -1,207 +0,0 @@
-import { useMemo, useEffect } from 'react';
-import * as THREE from 'three';
-import { InteriorMappingMaterial } from './InteriorMappingMaterial';
-import { computeWindowGrid, INTERIOR_WINDOW } from '../../utils/openWorldInteriorWindows';
-import { mixHex, seededRand } from './openWorldConstants';
-
-// Interior-mapped window panes for a building, using the in-tree
-// InteriorMappingMaterial — a parallax shader that fakes furnished 3D rooms
-// behind flat window planes (no real interior geometry). Selected towers get a
-// grid of these panes proud of each face so you can "look into" lit rooms as the
-// camera moves, instead of the flat emissive window texture alone.
-//
-// Every pane of every building is ONE InstancedMesh draw call: the grid math
-// (openWorldInteriorWindows.computeWindowGrid) places each pane, and a deterministic
-// per-pane `instanceWindowId` drives the shader's room-cell pick + lit/unlit and
-// warm/cool variation entirely on the GPU. Night-only + high-quality-preset
-// gated by the callers (Building / Borough), since the ray-march costs more than
-// the flat texture.
-
-const ATLAS_COLS = 4;
-const ATLAS_ROWS = 4;
-
-// Shared, palette-neutral interior-room atlas (4×4 = 16 room variants). Built
-// once and reused by every building — the per-building warm/cool tint comes from
-// the material's emissiveVariation, not the atlas, so a single grayscale-ish
-// atlas serves the whole city (and never needs disposing, like the rooftop-kit
-// singletons). Lazy so importing this module stays side-effect-free; returns
-// null under headless/jsdom where canvas has no 2d context.
-let _atlas = null;
-function getInteriorAtlas() {
- if (_atlas) return _atlas;
- const cell = 128;
- const canvas = document.createElement('canvas');
- canvas.width = cell * ATLAS_COLS;
- canvas.height = cell * ATLAS_ROWS;
- const ctx = canvas.getContext('2d');
- if (!ctx) return null;
-
- for (let row = 0; row < ATLAS_ROWS; row++) {
- for (let col = 0; col < ATLAS_COLS; col++) {
- const ox = col * cell;
- const oy = row * cell;
- const rand = seededRand(row * ATLAS_COLS + col + 1);
-
- // Back wall, floor band, ceiling band — neutral warm-gray so the emissive
- // tint reads as the room's light color rather than fighting a hue.
- ctx.fillStyle = '#3a3a42';
- ctx.fillRect(ox, oy, cell, cell);
- ctx.fillStyle = '#2b2b32';
- ctx.fillRect(ox, oy, cell, cell * 0.12);
- ctx.fillStyle = '#4c4c55';
- ctx.fillRect(ox, oy + cell * 0.7, cell, cell * 0.3);
-
- // 1–3 furniture silhouettes standing on the floor (desk/shelf/monitor).
- const pieces = 1 + Math.floor(rand() * 3);
- for (let p = 0; p < pieces; p++) {
- const w = cell * (0.18 + rand() * 0.24);
- const h = cell * (0.18 + rand() * 0.34);
- const x = ox + cell * 0.08 + rand() * (cell * 0.84 - w);
- const y = oy + cell * 0.7 - h;
- const shade = 35 + Math.floor(rand() * 45);
- ctx.fillStyle = `rgb(${shade},${shade},${shade + 8})`;
- ctx.fillRect(x, y, w, h);
- }
-
- // Occasional lit focal element (screen/lamp) — a small near-white block
- // that the warm/cool emissive turns into the visible "lights on" glow.
- if (rand() > 0.3) {
- const w = cell * (0.1 + rand() * 0.14);
- const h = cell * (0.08 + rand() * 0.12);
- const x = ox + cell * 0.12 + rand() * (cell * 0.68);
- const y = oy + cell * 0.3 + rand() * (cell * 0.3);
- ctx.fillStyle = '#dfe6f0';
- ctx.fillRect(x, y, w, h);
- }
- }
- }
-
- const tex = new THREE.CanvasTexture(canvas);
- tex.colorSpace = THREE.SRGBColorSpace;
- tex.wrapS = THREE.ClampToEdgeWrapping;
- tex.wrapT = THREE.ClampToEdgeWrapping;
- tex.minFilter = THREE.LinearFilter;
- tex.magFilter = THREE.LinearFilter;
- tex.needsUpdate = true;
- _atlas = tex;
- return _atlas;
-}
-
-// Hex → HDR-ish THREE.Color: emissive contributions want values >1 to read as a
-// glow under tone mapping, mirroring InteriorMappingMaterial's warm/cool defaults.
-function emissiveColor(hex, scale) {
- return new THREE.Color(hex).multiplyScalar(scale);
-}
-
-export default function BuildingWindows({
- width,
- depth,
- height,
- seed = 0,
- accentColor,
- edgeColor,
- neonBrightness = 1.2,
- dimMul = 1,
-}) {
- const atlas = getInteriorAtlas();
-
- // Geometry + per-pane instance data. Independent of palette/dim so a theme or
- // proximity-dim change doesn't rebuild the (potentially hundreds of) panes.
- const built = useMemo(() => {
- if (!atlas) return null;
- const windows = computeWindowGrid({ width, depth, height, seed });
- if (windows.length === 0) return null;
-
- const size = INTERIOR_WINDOW.size;
- const geo = new THREE.PlaneGeometry(size, size);
- const count = windows.length;
- const ids = new Float32Array(count * 3);
- const lods = new Float32Array(count).fill(1);
- const fades = new Float32Array(count).fill(1);
- const matrices = new Array(count);
-
- const m = new THREE.Matrix4();
- const q = new THREE.Quaternion();
- const e = new THREE.Euler();
- const v = new THREE.Vector3();
- const one = new THREE.Vector3(1, 1, 1);
- windows.forEach((w, i) => {
- e.set(0, w.rotationY, 0);
- q.setFromEuler(e);
- v.set(w.position[0], w.position[1], w.position[2]);
- m.compose(v, q, one);
- matrices[i] = m.clone();
- ids[i * 3] = w.windowId[0];
- ids[i * 3 + 1] = w.windowId[1];
- ids[i * 3 + 2] = w.windowId[2];
- });
-
- geo.setAttribute('instanceWindowId', new THREE.InstancedBufferAttribute(ids, 3));
- geo.setAttribute('instanceLod', new THREE.InstancedBufferAttribute(lods, 1));
- geo.setAttribute('instanceFade', new THREE.InstancedBufferAttribute(fades, 1));
- return { geo, matrices, count };
- }, [atlas, width, depth, height, seed]);
-
- // Palette-driven material — emissiveVariation gives per-window lit/unlit and
- // warm/cool rooms, with the cool tone pulled toward the building's neon accent
- // so the windows stay in-family with the rest of the scene.
- const material = useMemo(() => {
- if (!atlas) return null;
- const nb = neonBrightness;
- return new InteriorMappingMaterial({
- backAtlas: atlas,
- backAtlasCols: ATLAS_COLS,
- backAtlasRows: ATLAS_ROWS,
- planeSize: new THREE.Vector2(INTERIOR_WINDOW.size, INTERIOR_WINDOW.size),
- instanced: true,
- depth: 0.7,
- backScale: 0.6,
- roughness: 0.18,
- metalness: 0,
- transparent: true,
- glassFresnelStrength: 0.35,
- glassFresnelColor: emissiveColor(mixHex('#e8f0ff', accentColor, 0.2), 1),
- emissiveVariation: {
- litRatio: 0.55,
- warm: emissiveColor(mixHex('#ffd9a8', accentColor, 0.1), 1.6 * nb),
- cool: emissiveColor(accentColor, 1.4 * nb),
- coolChance: 0.5,
- brightMin: 0.35,
- brightRange: 0.5,
- dim: emissiveColor(edgeColor, 0.08),
- },
- });
- }, [atlas, accentColor, edgeColor, neonBrightness]);
-
- const mesh = useMemo(() => {
- if (!built || !material) return null;
- const im = new THREE.InstancedMesh(built.geo, material, built.count);
- for (let i = 0; i < built.count; i++) im.setMatrixAt(i, built.matrices[i]);
- im.instanceMatrix.needsUpdate = true;
- // Derive the bounding sphere from the instance matrices (the geometry's own
- // sphere is a single pane at the origin) so off-screen towers still cull.
- im.computeBoundingSphere();
- return im;
- }, [built, material]);
-
- // Proximity dim scales each pane's output alpha via instanceFade — done live so
- // a dim toggle never rebuilds the mesh. Re-applied whenever the mesh is rebuilt
- // too, since a fresh InstancedMesh starts with every fade at 1.
- useEffect(() => {
- if (!mesh) return;
- const attr = mesh.geometry.getAttribute('instanceFade');
- for (let i = 0; i < attr.count; i++) attr.setX(i, dimMul);
- attr.needsUpdate = true;
- }, [mesh, dimMul]);
-
- // R3F only auto-disposes objects it created via JSX; these are built
- // imperatively, so free their GPU buffers on replace/unmount ourselves. The
- // mesh is recreated whenever the material is rebuilt (theme/brightness change),
- // so its instanceMatrix buffer must be freed too — <primitive> won't.
- useEffect(() => (mesh ? () => mesh.dispose() : undefined), [mesh]);
- useEffect(() => (built ? () => built.geo.dispose() : undefined), [built]);
- useEffect(() => (material ? () => material.dispose() : undefined), [material]);
-
- if (!mesh) return null;
- return <primitive object={mesh} />;
-}
diff --git a/client/src/components/openworld/CameraTransition.jsx b/client/src/components/openworld/CameraTransition.jsx
deleted file mode 100644
index 37723ef66a..0000000000
--- a/client/src/components/openworld/CameraTransition.jsx
+++ /dev/null
@@ -1,79 +0,0 @@
-import { useRef } from 'react';
-import { useThree, useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { smoothstep } from '../../utils/easing';
-import { DEFAULT_SPAWN_Z, EYE_HEIGHT, THIRD_PERSON, thirdPersonCamera } from '../../utils/openWorldPlayerRig';
-
-const ORBITAL_POS = new THREE.Vector3(0, 95, 125);
-const ORBITAL_TARGET = new THREE.Vector3(0, 0, 0);
-const DEFAULT_EXPLORATION_RIG = { x: 0, y: EYE_HEIGHT, z: DEFAULT_SPAWN_Z };
-const DEFAULT_EXPLORATION_FRAME = thirdPersonCamera({
- pos: DEFAULT_EXPLORATION_RIG,
- yaw: THIRD_PERSON.isometricYaw,
- pitch: 0,
- pitchOffset: THIRD_PERSON.isometricPitch,
-});
-const DEFAULT_EXPLORATION_POS = new THREE.Vector3(
- DEFAULT_EXPLORATION_FRAME.camera.x,
- DEFAULT_EXPLORATION_FRAME.camera.y,
- DEFAULT_EXPLORATION_FRAME.camera.z,
-);
-const DEFAULT_EXPLORATION_TARGET = new THREE.Vector3(
- DEFAULT_EXPLORATION_FRAME.lookAt.x,
- DEFAULT_EXPLORATION_FRAME.lookAt.y,
- DEFAULT_EXPLORATION_FRAME.lookAt.z,
-);
-const DURATION = 0.8;
-
-export default function CameraTransition({ active, targetPos, targetLookAt, onTransitionComplete }) {
- const { camera } = useThree();
- const progressRef = useRef(0);
- const startPosRef = useRef(new THREE.Vector3());
- const startTargetRef = useRef(new THREE.Vector3());
- // The player controller already owns the initial exploration camera. Starting a
- // transition from the Canvas' orbital camera makes the world visibly sweep past
- // the player on load, and on a phone that can leave the first frame aimed at the
- // sky. Only animate when the user actually changes modes after mount.
- const wasActiveRef = useRef(active);
- const completedRef = useRef(true);
-
- useFrame((_, delta) => {
- // Detect transition start
- if (active !== wasActiveRef.current) {
- wasActiveRef.current = active;
- progressRef.current = 0;
- completedRef.current = false;
- startPosRef.current.copy(camera.position);
- // Approximate current look-at from camera direction
- const dir = new THREE.Vector3(0, 0, -1).applyQuaternion(camera.quaternion);
- startTargetRef.current.copy(camera.position).add(dir.multiplyScalar(10));
- }
-
- if (completedRef.current) return;
-
- progressRef.current += delta / DURATION;
- if (progressRef.current >= 1) {
- progressRef.current = 1;
- completedRef.current = true;
- }
-
- const t = smoothstep(Math.min(progressRef.current, 1));
-
- // Match the elevated diagonal exploration framing while the player rig takes over.
- // The transition target is only a short hand-off; PlayerController then tracks the
- // actual rover position and applies the same isometric offset every frame.
- const endPos = active ? (targetPos || DEFAULT_EXPLORATION_POS) : ORBITAL_POS;
- const endTarget = active ? (targetLookAt || DEFAULT_EXPLORATION_TARGET) : ORBITAL_TARGET;
-
- camera.position.lerpVectors(startPosRef.current, endPos, t);
-
- const currentTarget = new THREE.Vector3().lerpVectors(startTargetRef.current, endTarget, t);
- camera.lookAt(currentTarget);
-
- if (completedRef.current) {
- onTransitionComplete?.();
- }
- });
-
- return null;
-}
diff --git a/client/src/components/openworld/HolographicPanel.jsx b/client/src/components/openworld/HolographicPanel.jsx
deleted file mode 100644
index cc3665325f..0000000000
--- a/client/src/components/openworld/HolographicPanel.jsx
+++ /dev/null
@@ -1,108 +0,0 @@
-import { useMemo } from 'react';
-import { Html } from '@react-three/drei';
-import { formatBytes, formatDurationMs } from '../../utils/formatters';
-import { computeAppMetrics, cpuTone } from '../../utils/openWorldAppMetrics';
-
-const STATUS_ICONS = {
- online: '\u25CF',
- stopped: '\u25A0',
- not_started: '\u25CB',
- not_found: '\u25CB',
- unknown: '\u25CB',
-};
-
-// Glanceable load tone shared by the metric row's CPU readout.
-const TONE_CLASSES = {
- idle: 'text-cyan-300/60',
- calm: 'text-cyan-300',
- busy: 'text-amber-300',
- hot: 'text-red-400',
-};
-
-export default function HolographicPanel({ app, agentCount, position, expanded = false, playback = false }) {
- // Live per-process PM2 telemetry already riding the app payload (roadmap 1.1) —
- // aggregated once per payload change, rendered only when there is something to show.
- const metrics = useMemo(() => computeAppMetrics(app), [app]);
- const statusColors = {
- online: 'border-cyan-500/50 text-cyan-400',
- stopped: 'border-red-500/50 text-red-400',
- not_started: 'border-violet-500/50 text-violet-400',
- not_found: 'border-violet-500/50 text-violet-400',
- // PM2 read failed \u2014 gray, matching the city building, distinct from violet.
- unknown: 'border-gray-400/50 text-gray-400',
- };
-
- const statusDotColors = {
- online: 'text-cyan-400',
- stopped: 'text-red-400',
- not_started: 'text-violet-400',
- not_found: 'text-violet-400',
- unknown: 'text-gray-400',
- };
-
- const colorClass = app.archived
- ? 'border-slate-500/50 text-slate-400'
- : statusColors[app.overallStatus] || statusColors.not_started;
-
- const dotColor = app.archived
- ? 'text-slate-500'
- : statusDotColors[app.overallStatus] || 'text-violet-400';
-
- const processCount = app.processes?.length || 0;
-
- return (
- <Html
- position={position}
- center
- distanceFactor={expanded ? 8 : 15}
- occlude
- style={{ pointerEvents: 'none' }}
- >
- <div className={`bg-black/90 border ${colorClass} rounded-md ${expanded ? 'px-4 py-3' : 'px-3 py-2'} whitespace-nowrap backdrop-blur-sm`} style={{ boxShadow: expanded ? '0 0 20px rgba(6,182,212,0.3)' : '0 0 12px rgba(0,0,0,0.5)' }}>
- <div className={`font-pixel tracking-wider truncate font-bold ${expanded ? 'text-[14px] max-w-[200px]' : 'text-[12px] max-w-[160px]'}`}>{app.name}</div>
- <div className="flex items-center gap-2 text-[9px] font-pixel tracking-wide mt-1">
- <span className={dotColor}>
- {STATUS_ICONS[app.overallStatus] || '\u25CB'}
- </span>
- <span className="opacity-80">{app.archived ? 'ARCHIVED' : (app.overallStatus || '').toUpperCase().replace('_', ' ')}</span>
- {processCount > 0 && (
- <span className="opacity-50">| {processCount} PROC</span>
- )}
- {agentCount > 0 && (
- <span className="opacity-50">| {agentCount} AGENT{agentCount > 1 ? 'S' : ''}</span>
- )}
- </div>
- {/* Live telemetry is suppressed during history playback: pm2Status is always
- the live snapshot, and showing current CPU beside a historical building
- status would contradict the playback contract. */}
- {!playback && metrics.hasMetrics && metrics.onlineProcs > 0 && (
- <div className="flex items-center gap-2 text-[9px] font-pixel tracking-wide mt-1">
- <span className={TONE_CLASSES[cpuTone(metrics.cpuPercent)]}>CPU {metrics.cpuPercent}%</span>
- <span className="opacity-50">|</span>
- <span className="text-cyan-300">MEM {formatBytes(metrics.memBytes, 0)}</span>
- {Number.isFinite(metrics.uptimeMs) && (
- <>
- <span className="opacity-50">|</span>
- <span className="text-cyan-300/70">UP {formatDurationMs(metrics.uptimeMs)}</span>
- </>
- )}
- {metrics.restarts > 0 && (
- <>
- <span className="opacity-50">|</span>
- <span className="text-cyan-300/70" title={`${metrics.restarts} total PM2 restarts`}>{'\u21BB'}{metrics.restarts}</span>
- </>
- )}
- </div>
- )}
- {!playback && metrics.unstableRestarts > 0 && (
- <div className="font-pixel text-[8px] text-red-400 tracking-wider mt-1">
- {'\u21BB'} {metrics.unstableRestarts} UNSTABLE RESTART{metrics.unstableRestarts > 1 ? 'S' : ''}
- </div>
- )}
- <div className="font-pixel text-[8px] text-cyan-500/30 tracking-widest mt-1">
- {expanded ? 'PRESS E TO ENTER' : 'CLICK TO VIEW'}
- </div>
- </div>
- </Html>
- );
-}
diff --git a/client/src/components/openworld/InteriorMappingMaterial.js b/client/src/components/openworld/InteriorMappingMaterial.js
deleted file mode 100644
index b50062958c..0000000000
--- a/client/src/components/openworld/InteriorMappingMaterial.js
+++ /dev/null
@@ -1,279 +0,0 @@
-import { MeshStandardMaterial, Color, Vector2, Vector3 } from 'three';
-
-// Self-contained parallax interior-mapping material — a MeshStandardMaterial
-// subclass that fakes furnished 3D rooms behind flat window planes via
-// onBeforeCompile GLSL injection. Replaces the `three-fenestra` npm
-// dependency (#1874) with an in-tree port trimmed to the subset of its API
-// actually consumed by BuildingWindows.jsx: backAtlas/backAtlasCols/
-// backAtlasRows/planeSize/instanced/depth/backScale/roughness/metalness/
-// transparent/glassFresnelStrength/glassFresnelColor/emissiveVariation, plus
-// the `instanceWindowId`/`instanceLod`/`instanceFade` instanced attributes.
-// The original also supported a front PBR overlay atlas (albedo/normal/
-// roughness/metalness), glass dirt/refraction/thickness, and a flat
-// `interiorEmissive` fallback — none of which any PortOS caller uses, so
-// they were not ported. Re-derive them from upstream if a future caller
-// needs that surface: https://github.com/codedgar/three-fenestra
-//
-// The ported GLSL below is a derivative of [email protected]
-// (MIT License, Copyright (c) 2026 Edgar Perez):
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-
-// ── GLSL core ────────────────────────────────────────────────────────────
-// imHash: deterministic per-window hash. Public seed contract (other shaders
-// — e.g. a far-LOD impostor — can reproduce the exact same window from the
-// same windowId by reusing these seeds): lit 3.71, tone 9.27, brightness 5.43.
-// imWindowEmissive: lit/unlit + warm/cool tone + brightness jitter from the hash.
-// imAtlasUV: seeded atlas-cell lookup (picks one cell of a cols x rows grid).
-// imRoomBoxUV: the room-box ray-march — re-projects the view-ray exit point
-// onto one room photo (back+side walls baked into a single atlas cell).
-const glslCore = /* glsl */ `
- float imHash(vec3 p, float seed) {
- p = fract(p * 0.3183099 + vec3(0.1, 0.2, 0.3) + seed);
- p *= 17.0;
- return fract(p.x * p.y * p.z * (p.x + p.y + p.z));
- }
-
- vec3 imWindowEmissive(vec3 windowId, float litRatio, vec3 warm, vec3 cool,
- float coolChance, vec2 bright, vec3 dim) {
- float hLit = imHash(windowId, 3.71);
- float hTone = imHash(windowId, 9.27);
- float hBright = imHash(windowId, 5.43);
- if (hLit >= litRatio) return dim;
- vec3 tone = mix(warm, cool, step(1.0 - coolChance, hTone));
- return tone * (bright.x + bright.y * hBright);
- }
-
- vec2 imAtlasUV(vec2 cellUV, vec3 windowId, float cols, float rows, float seed) {
- float total = cols * rows;
- float idx = floor(imHash(windowId, seed) * total);
- float col = mod(idx, cols);
- float row = floor(idx / cols);
- vec2 cellSize = vec2(1.0 / cols, 1.0 / rows);
- vec2 inset = cellSize * 0.001;
- vec2 cellOrigin = vec2(col * cellSize.x, 1.0 - (row + 1.0) * cellSize.y) + inset;
- return cellOrigin + clamp(cellUV, 0.0, 1.0) * (cellSize - 2.0 * inset);
- }
-
- vec2 imRoomBoxUV(vec3 camLocal, vec2 localXY, float depth, float backScale) {
- vec3 origin = vec3(localXY, 0.0);
- vec3 dir = normalize(origin - camLocal);
- vec3 invDir = 1.0 / dir;
- vec3 tNear = (vec3(-0.5, -0.5, -depth) - origin) * invDir;
- vec3 tFar = (vec3(0.5, 0.5, 0.0) - origin) * invDir;
- vec3 tMax = max(tNear, tFar);
- float t = min(min(tMax.x, tMax.y), tMax.z);
- vec3 hit = origin + dir * t;
- float bs = clamp(backScale, 0.05, 0.999);
- float camDist = bs * depth / (1.0 - bs);
- float scale = camDist / (camDist - hit.z);
- return hit.xy * scale + 0.5;
- }
-`;
-
-const vertexCommon = /* glsl */ `
- varying vec2 vInteriorLocalXY;
- varying vec3 vInteriorCameraLocal;
- varying vec3 vImWindowId;
- varying float vImLod;
- varying float vImFade;
- uniform vec2 uPlaneSize;
- uniform vec3 uWindowId;
- uniform float uLod;
- #ifdef IM_INSTANCED
- // one InstancedMesh = thousands of windows in a single draw call;
- // per-window identity/LOD/fade live in instanced attributes
- attribute vec3 instanceWindowId;
- attribute float instanceLod;
- attribute float instanceFade;
- #endif
-`;
-
-const vertexBody = /* glsl */ `
- vInteriorLocalXY = position.xy / uPlaneSize;
- #ifdef IM_INSTANCED
- mat4 _imModel = modelMatrix * instanceMatrix;
- vImWindowId = instanceWindowId;
- vImLod = instanceLod;
- vImFade = instanceFade;
- #else
- mat4 _imModel = modelMatrix;
- vImWindowId = uWindowId;
- vImLod = uLod;
- vImFade = 1.0;
- #endif
- vec3 _imCamLocal = (inverse(_imModel) * vec4(cameraPosition, 1.0)).xyz;
- vInteriorCameraLocal = vec3(
- _imCamLocal.xy / uPlaneSize,
- _imCamLocal.z / max(uPlaneSize.x, uPlaneSize.y)
- );
-`;
-
-const fragmentCommon = /* glsl */ `
- varying vec2 vInteriorLocalXY;
- varying vec3 vInteriorCameraLocal;
- varying vec3 vImWindowId;
- varying float vImLod;
- varying float vImFade;
-
- uniform sampler2D uBackAtlas;
- uniform float uBackAtlasCols;
- uniform float uBackAtlasRows;
- uniform float uDepth;
- uniform float uBackScale;
- uniform vec3 uWindowId;
- uniform float uGlassFresnelStrength;
- uniform vec3 uGlassFresnelColor;
-
- // LOD blend: 1 = full interior mapping + glass fresnel, 0 = flat impostor
- // (the back cell sampled straight onto the plane, no parallax/fresnel).
- // Drive by camera distance to crossfade against a cheap far-LOD shader
- // that samples the same atlas cell flat.
- uniform float uLod;
-
- // GPU-side per-window emissive variation (lit/unlit, warm/cool, brightness
- // jitter) derived from the window id so a far-LOD impostor shader can hash
- // the same id with the same seeds and reproduce the exact same window.
- uniform float uVarLitRatio;
- uniform vec3 uVarWarm;
- uniform vec3 uVarCool;
- uniform float uVarCoolChance;
- uniform vec2 uVarBright; // (min, range)
- uniform vec3 uVarDim;
-
- vec3 _imWindowEmissive() {
- return imWindowEmissive(vImWindowId, uVarLitRatio, uVarWarm, uVarCool,
- uVarCoolChance, uVarBright, uVarDim);
- }
-
- vec3 _imInteriorRGB() {
- vec2 cellUV = imRoomBoxUV(vInteriorCameraLocal, vInteriorLocalXY, uDepth, uBackScale);
- // uLod = 0 collapses the room to a flat cell sample (LOD impostor match)
- cellUV = mix(vInteriorLocalXY + 0.5, cellUV, vImLod);
- vec2 atlasUV = imAtlasUV(cellUV, vImWindowId, uBackAtlasCols, uBackAtlasRows, 0.0);
- return texture2D(uBackAtlas, atlasUV).rgb;
- }
-`;
-
-// Replaces <map_fragment>. The window is opaque from the camera's
-// perspective — the interior IS the back of the surface, not a transparent
-// hole — so diffuseColor is forced to opaque black (no direct diffuse
-// lighting should paint over the interior) and the already-lit interior
-// color is stashed in a local that the output injection below adds back in
-// AFTER PBR lighting runs, skipping the GGX BRDF entirely.
-const fragmentMapReplacement = /* glsl */ `
- diffuseColor.rgb = vec3(0.0);
- diffuseColor.a = 1.0;
- vec3 _imInteriorEmissive = _imInteriorRGB() * _imWindowEmissive();
-`;
-
-// Injected BEFORE <tonemapping_fragment>: adds the linear-space interior on
-// top of the lit (black) front layer so it receives the same tonemap + sRGB
-// conversion as everything else, then layers a Schlick fresnel sheen at
-// grazing angles — the primary "this is a pane of glass" cue.
-const fragmentOutput = /* glsl */ `
- gl_FragColor.rgb += _imInteriorEmissive;
- gl_FragColor.a *= vImFade; // per-instance LOD fade (1.0 unless instanced)
-
- vec3 _imViewLocal = normalize(vInteriorCameraLocal - vec3(vInteriorLocalXY, 0.0));
- float _imNdotV = clamp(_imViewLocal.z, 0.0, 1.0);
- float _imFresnel = pow(1.0 - _imNdotV, 5.0) * vImLod; // glass cue fades out with LOD
- gl_FragColor.rgb += uGlassFresnelColor * uGlassFresnelStrength * _imFresnel;
-`;
-
-/**
- * Parallax interior-mapping `MeshStandardMaterial` subclass — fakes a
- * furnished 3D room behind a flat window pane. Use with a single plane (set
- * `windowId`/`lod`) or with a `THREE.InstancedMesh` (`instanced: true`,
- * geometry carries `instanceWindowId`/`instanceLod`/`instanceFade`).
- */
-export class InteriorMappingMaterial extends MeshStandardMaterial {
- /**
- * @param {object} params
- * @param {import('three').Texture} params.backAtlas - interior atlas (the rooms texture sampled by the ray-march).
- * @param {number} [params.backAtlasCols=4]
- * @param {number} [params.backAtlasRows=4]
- * @param {number} [params.depth=1.0] - apparent room depth in plane-local units.
- * @param {number} [params.backScale=0.66] - back-wall fill factor in [0.05, 0.999].
- * @param {import('three').Vector2} params.planeSize - plane size in world units (width, height); must match the geometry.
- * @param {import('three').Vector3} [params.windowId] - per-window seed (non-instanced mode only; instanced mode uses `instanceWindowId`).
- * @param {number} [params.lod=1.0] - LOD blend in [0,1] (non-instanced mode only; instanced mode uses `instanceLod`).
- * @param {number} [params.glassFresnelStrength=0.0] - Schlick fresnel sheen strength at grazing angles.
- * @param {import('three').Color} [params.glassFresnelColor] - tint of the fresnel sheen. Default cool white (0.85, 0.92, 1.0).
- * @param {object} [params.emissiveVariation] - GPU-side per-window emissive variation (lit/unlit, warm/cool, brightness jitter).
- * @param {number} [params.emissiveVariation.litRatio=0.5] - chance a window is lit, in [0,1].
- * @param {import('three').Color} [params.emissiveVariation.warm] - emissive tint of warm (incandescent) windows. Default (1.7, 1.35, 0.95).
- * @param {import('three').Color} [params.emissiveVariation.cool] - emissive tint of cool (fluorescent/TV) windows. Default (0.9, 1.15, 1.5).
- * @param {number} [params.emissiveVariation.coolChance=0.22] - chance a lit window uses the cool tone.
- * @param {number} [params.emissiveVariation.brightMin=0.3] - minimum brightness multiplier of a lit window.
- * @param {number} [params.emissiveVariation.brightRange=0.35] - random brightness range added on top of brightMin.
- * @param {import('three').Color} [params.emissiveVariation.dim] - emissive of unlit windows. Default (0.07, 0.08, 0.1).
- * @param {boolean} [params.instanced=false] - use with a THREE.InstancedMesh whose geometry carries
- * InstancedBufferAttributes `instanceWindowId` (vec3), `instanceLod` (float) and `instanceFade` (float).
- */
- constructor(params) {
- const {
- backAtlas, backAtlasCols, backAtlasRows, planeSize, windowId, depth, backScale,
- glassFresnelStrength, glassFresnelColor, lod, emissiveVariation, instanced,
- ...std
- } = params;
-
- super(std);
-
- this._instanced = instanced ?? false;
- const ev = emissiveVariation;
-
- this.interiorUniforms = {
- uBackAtlas: { value: backAtlas },
- uBackAtlasCols: { value: backAtlasCols ?? 4 },
- uBackAtlasRows: { value: backAtlasRows ?? 4 },
- uDepth: { value: depth ?? 1.0 },
- uBackScale: { value: backScale ?? 0.66 },
- uPlaneSize: { value: planeSize.clone() },
- uWindowId: { value: (windowId ?? new Vector3()).clone() },
- uGlassFresnelStrength: { value: glassFresnelStrength ?? 0.0 },
- uGlassFresnelColor: { value: (glassFresnelColor ?? new Color(0.85, 0.92, 1.0)).clone() },
- uLod: { value: lod ?? 1.0 },
- uVarLitRatio: { value: ev?.litRatio ?? 0.5 },
- uVarWarm: { value: (ev?.warm ?? new Color(1.7, 1.35, 0.95)).clone() },
- uVarCool: { value: (ev?.cool ?? new Color(0.9, 1.15, 1.5)).clone() },
- uVarCoolChance: { value: ev?.coolChance ?? 0.22 },
- uVarBright: { value: new Vector2(ev?.brightMin ?? 0.3, ev?.brightRange ?? 0.35) },
- uVarDim: { value: (ev?.dim ?? new Color(0.07, 0.08, 0.1)).clone() },
- };
-
- // Toggles vertex/fragment shader between the instanced-attribute path
- // (uses instanceWindowId/instanceLod/instanceFade) and the uniform path
- // (uses uWindowId/uLod, flat per-material instead of per-instance).
- this.defines = this._instanced ? { IM_INSTANCED: '' } : {};
- }
-
- onBeforeCompile = (shader) => {
- Object.assign(shader.uniforms, this.interiorUniforms);
-
- shader.vertexShader = shader.vertexShader
- .replace('#include <common>', `#include <common>\n${vertexCommon}`)
- .replace('#include <begin_vertex>', `#include <begin_vertex>\n${vertexBody}`);
-
- shader.fragmentShader = shader.fragmentShader
- .replace('#include <common>', `#include <common>\n${glslCore}\n${fragmentCommon}`)
- .replace('#include <map_fragment>', fragmentMapReplacement)
- .replace('#include <tonemapping_fragment>', `${fragmentOutput}\n#include <tonemapping_fragment>`);
- };
-}
diff --git a/client/src/components/openworld/OpenWorldActivityHeatmap.jsx b/client/src/components/openworld/OpenWorldActivityHeatmap.jsx
deleted file mode 100644
index 8c8ba9a290..0000000000
--- a/client/src/components/openworld/OpenWorldActivityHeatmap.jsx
+++ /dev/null
@@ -1,59 +0,0 @@
-import { useMemo, useRef } from 'react';
-import { useFrame } from '@react-three/fiber';
-import { computeActivityHeatmap } from '../../utils/openWorldActivityHeatmap';
-
-// OpenWorld productivity-district activity heatmap (issue #817): a GitHub-style contribution
-// grid laid out as a field of thin ground tiles framing the throughput monument. Each tile is one
-// day; its glow scales with that day's completed-task count relative to the busiest day in the
-// window. Today's tile reads accent-blue. Active tiles breathe on the highest quality presets;
-// the static glow keeps the field legible when the pulse is dropped. Data comes from the
-// activity calendar (`GET /api/cos/productivity/calendar`). Mirrors OpenWorldProductivityDistrict.
-export default function OpenWorldActivityHeatmap({ calendarData, settings }) {
- const heatmap = useMemo(() => computeActivityHeatmap(calendarData), [calendarData]);
- const groupRef = useRef();
-
- // Honor the quality dial: drop the per-tile shimmer on the lowest preset, keep the static
- // glow so the contribution field stays readable.
- const animate = (settings?.particleDensity ?? 1) >= 0.5;
-
- useFrame(({ clock }) => {
- if (!animate || !groupRef.current) return;
- // A gentle traveling wave across the field so active tiles shimmer like data flowing in.
- const t = clock.getElapsedTime();
- for (const tile of groupRef.current.children) {
- const base = tile.userData.baseIntensity;
- if (!base) continue;
- const phase = tile.userData.phase || 0;
- const wave = 0.85 + ((Math.sin(t * 1.4 + phase * 6.283) + 1) / 2) * 0.3;
- tile.material.emissiveIntensity = base * wave;
- }
- });
-
- if (!heatmap.present) return null;
-
- const { origin, tileSize, tileHeight, tiles } = heatmap;
-
- return (
- <group position={origin}>
- <group ref={groupRef}>
- {tiles.map((tile) => (
- <mesh
- key={tile.key}
- position={[tile.x, tileHeight / 2, tile.z]}
- userData={{ baseIntensity: tile.tasks > 0 ? tile.intensity : 0, phase: tile.phase }}
- >
- <boxGeometry args={[tileSize, tileHeight, tileSize]} />
- <meshStandardMaterial
- color={tile.color}
- emissive={tile.color}
- emissiveIntensity={tile.intensity}
- metalness={0.3}
- roughness={0.6}
- toneMapped={false}
- />
- </mesh>
- ))}
- </group>
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldAdaptiveQuality.jsx b/client/src/components/openworld/OpenWorldAdaptiveQuality.jsx
deleted file mode 100644
index fb5f93d77f..0000000000
--- a/client/src/components/openworld/OpenWorldAdaptiveQuality.jsx
+++ /dev/null
@@ -1,67 +0,0 @@
-import { useRef, useEffect } from 'react';
-import { useFrame } from '@react-three/fiber';
-import {
- createRenderBudget,
- recordFrame,
- restartWarmup,
- resetRenderBudget,
- getEffectiveTier,
-} from '../../utils/openWorldRenderBudget.js';
-
-// In-Canvas driver for Auto quality mode (issue #2592). It samples per-frame delta
-// times via useFrame, feeds them to the pure render-budget state machine, and lifts
-// tier changes back up to OpenWorld through a callback.
-// It renders nothing. All impurity (timers, refs, frame loop) lives here so the
-// state machine stays pure and unit-tested.
-//
-// - `enabled`: Auto mode is on. When off, the machine is left idle (Manual mode).
-// - `startTier`: the tier to (re)start the budget at when Auto engages.
-// - `resumeToken`: bumped by OpenWorldScene when the frameloop resumes after the tab was
-// hidden — re-arms the warm-up so post-resume jank doesn't drive a bogus decision.
-export default function OpenWorldAdaptiveQuality({
- enabled,
- startTier = 'high',
- resumeToken = 0,
- resetToken = 0,
- onTierChange,
-}) {
- const nowMs = () => (typeof performance !== 'undefined' ? performance.now() : 0);
- const stateRef = useRef(null);
- if (stateRef.current === null) {
- stateRef.current = createRenderBudget(startTier, nowMs());
- }
- // Tracks the last-seen resumeToken so the re-arm happens INSIDE the frame loop (below),
- // before the first resumed frame is measured — a passive effect could run after the
- // Canvas has already switched frameloop back to "always", letting one stale-window
- // frame classify against pre-hide samples first.
- const seenResumeRef = useRef(resumeToken);
-
- // Re-start the budget whenever Auto (re)engages, the starting tier changes, or the user
- // resets defaults (resetToken) — so a Manual→Auto switch and a RESET DEFAULTS both begin
- // adaptation fresh at the start tier rather than resuming a stale runtime tier.
- useEffect(() => {
- if (!enabled) return;
- stateRef.current = resetRenderBudget(stateRef.current, startTier, nowMs());
- seenResumeRef.current = resumeToken;
- onTierChange?.(getEffectiveTier(stateRef.current));
- // Deps are intentionally [enabled, startTier, resetToken] — a fresh onTierChange
- // callback identity must not reset the live budget mid-run.
- }, [enabled, startTier, resetToken]);
-
- useFrame((_, delta) => {
- if (!enabled) return;
- const now = nowMs();
- // Frameloop just resumed from a hidden tab → re-arm warm-up before measuring, so the
- // first sluggish post-resume frames (and any pre-hide streaks/samples) are dropped.
- if (seenResumeRef.current !== resumeToken) {
- seenResumeRef.current = resumeToken;
- stateRef.current = restartWarmup(stateRef.current, now);
- }
- const prevTier = getEffectiveTier(stateRef.current);
- stateRef.current = recordFrame(stateRef.current, { now, dt: delta * 1000 });
- const nextTier = getEffectiveTier(stateRef.current);
- if (nextTier !== prevTier) onTierChange?.(nextTier);
- });
-
- return null;
-}
diff --git a/client/src/components/openworld/OpenWorldAgentBar.jsx b/client/src/components/openworld/OpenWorldAgentBar.jsx
deleted file mode 100644
index b2c937c491..0000000000
--- a/client/src/components/openworld/OpenWorldAgentBar.jsx
+++ /dev/null
@@ -1,58 +0,0 @@
-import { AGENT_STATES } from '../cos/constants';
-
-export default function OpenWorldAgentBar({ cosAgents, agentMap }) {
- const activeAgents = (cosAgents || []).filter(a =>
- a.status === 'running' || a.state === 'coding' || a.state === 'thinking' || a.state === 'investigating'
- );
-
- if (activeAgents.length === 0) return null;
-
- const getAppName = (agent) => {
- for (const [, data] of agentMap) {
- if (data.agents.some(a => a.agentId === agent.agentId)) {
- return data.app.name;
- }
- }
- return null;
- };
-
- return (
- <div className="absolute bottom-20 left-1/2 -translate-x-1/2 w-fit max-w-[calc(100vw-2rem)] pointer-events-auto">
- <div className="openworld-hud-panel openworld-hud-panel--quiet px-3 py-2.5">
- <div className="flex items-center gap-3 overflow-x-auto" style={{ scrollbarWidth: 'thin', scrollbarColor: 'rgba(6,182,212,0.2) transparent' }}>
- <span className="text-cyan-400 text-[11px] font-pixel tracking-wider font-bold shrink-0">AGENTS</span>
- <div className="w-px h-4 bg-cyan-500/20 shrink-0" />
- {activeAgents.map((agent, i) => {
- const state = agent.state || 'coding';
- const stateConfig = AGENT_STATES[state];
- const appName = getAppName(agent);
- const stateLabel = stateConfig?.label || state;
-
- return (
- <div
- key={agent.agentId || i}
- className="flex items-center gap-2 px-2.5 py-1.5 bg-black/50 border border-white/10 rounded-md text-[9px] font-pixel tracking-wide shrink-0 min-h-[32px]"
- title={`${agent.type || 'agent'} - ${stateLabel}${appName ? ` (${appName})` : ''}`}
- >
- <span
- className="w-2 h-2 rounded-full shrink-0 animate-pulse"
- style={{
- backgroundColor: stateConfig?.color || '#06b6d4',
- boxShadow: `0 0 6px ${stateConfig?.color || '#06b6d4'}`,
- }}
- />
- <span className="text-gray-300">{agent.type || 'agent'}</span>
- {appName && (
- <>
- <span className="text-gray-600">|</span>
- <span className="text-cyan-400/70 truncate max-w-[120px]">{appName}</span>
- </>
- )}
- </div>
- );
- })}
- </div>
- </div>
- </div>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldAiCore.jsx b/client/src/components/openworld/OpenWorldAiCore.jsx
deleted file mode 100644
index 240120e9cf..0000000000
--- a/client/src/components/openworld/OpenWorldAiCore.jsx
+++ /dev/null
@@ -1,238 +0,0 @@
-import { useMemo, useRef } from 'react';
-import * as THREE from 'three';
-import { useFrame } from '@react-three/fiber';
-import { PIXEL_FONT_URL, openWorldDayMix, mixHex } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import OpenWorldLabel from './OpenWorldLabel';
-import { computeAiCore, computeAiCoreBeams, AI_CORE } from '../../utils/openWorldAiCore';
-
-// OpenWorld's AI Core landmark: a low kinetic seed at the center of The Port from
-// which all model activity radiates. The suspended orb glows by the active model tier (cyan
-// light → blue medium → violet heavy) and brightens with the number of in-flight calls;
-// activity beams fan outward from the apex while AI work is happening, and a fast call
-// still produces a brief flare. Idle, the core sits a dim slate. Driven by the live
-// `ai:status` ops threaded through useOpenWorldData.
-//
-// When a call originates from a managed app or CoS-agent workspace (its `ai:status` event
-// carries `appId` / `workspacePath`), its beam aims at that building's world position and
-// thickens with the call's tokens/sec; ops with no building association keep the generic
-// radial fan-out (roadmap 2.1, issue follow-up).
-
-// A radial beam: lies along +X from the apex, rotated about Y to its angle, tilted slightly
-// down so it reads as energy arcing out over the city.
-function RadialBeam({ angle, length, thickness, color }) {
- const ref = useRef();
- const { position, rotation } = useMemo(() => {
- const tilt = -0.18;
- return {
- position: [Math.cos(angle) * (length / 2), -Math.sin(-tilt) * (length / 2), Math.sin(angle) * (length / 2)],
- rotation: [0, -angle, tilt],
- };
- }, [angle, length]);
-
- useFrame(({ clock }) => {
- if (!ref.current) return;
- // A pulse travels the beam: opacity breathes out of phase per angle so beams shimmer.
- const t = clock.getElapsedTime() * 3 + angle * 2;
- ref.current.material.opacity = 0.25 + ((Math.sin(t) + 1) / 2) * 0.5;
- });
-
- return (
- <mesh ref={ref} position={position} rotation={rotation}>
- <boxGeometry args={[length, thickness, thickness]} />
- <meshStandardMaterial color={color} emissive={color} emissiveIntensity={1} transparent opacity={0.4} toneMapped={false} depthWrite={false} />
- </mesh>
- );
-}
-
-// A targeted beam: spans from the apex (group origin) to a building, given the apex-local
-// `target` vector. Orientation aligns the box's local +X axis with the apex→building
-// direction so a single box stretches cleanly along the line.
-function TargetedBeam({ target, thickness, color, seed }) {
- const ref = useRef();
- const { position, quaternion, length } = useMemo(() => {
- const vec = new THREE.Vector3(target[0], target[1], target[2]);
- const len = Math.max(vec.length(), 0.01);
- const q = new THREE.Quaternion().setFromUnitVectors(
- new THREE.Vector3(1, 0, 0),
- vec.clone().normalize(),
- );
- return { position: vec.multiplyScalar(0.5).toArray(), quaternion: q, length: len };
- }, [target]);
-
- useFrame(({ clock }) => {
- if (!ref.current) return;
- const t = clock.getElapsedTime() * 3 + seed * 2;
- ref.current.material.opacity = 0.3 + ((Math.sin(t) + 1) / 2) * 0.55;
- });
-
- return (
- <mesh ref={ref} position={position} quaternion={quaternion}>
- <boxGeometry args={[length, thickness, thickness]} />
- <meshStandardMaterial color={color} emissive={color} emissiveIntensity={1} transparent opacity={0.45} toneMapped={false} depthWrite={false} />
- </mesh>
- );
-}
-
-export default function OpenWorldAiCore({ aiActivity, positions, apps, settings }) {
- const { tintStructure } = useOpenWorldPalette();
- const core = useMemo(
- () => computeAiCore(aiActivity?.ops, aiActivity?.lastStartTs ?? 0),
- [aiActivity],
- );
- const apexRef = useRef();
- const apexGlowRef = useRef();
- const orbitRef = useRef();
- const petalRef = useRef();
-
- const animate = (settings?.particleDensity ?? 1) >= 0.5;
- const dayMix = openWorldDayMix(settings);
- const { position, apexY, color } = core;
- const orbColor = core.busy ? color : mixHex('#67e8f9', color, 0.28);
- const orbEmissive = (core.busy ? 0.85 : 0.48) + core.intensity * 0.45;
- const orbGlowOpacity = (0.14 + core.intensity * 0.08) * (1 - dayMix * 0.45);
- const baseColor = mixHex(tintStructure('#203b46'), '#8d9078', dayMix);
- const petalColor = mixHex(tintStructure('#365666'), '#b89a6c', dayMix);
- const ringColor = mixHex('#7dd3fc', orbColor, 0.5);
-
- // Per-op beams: targeted at the originating building when known, radial otherwise.
- // While flaring with no live op (a fast call that already cleared) keep one radial pulse.
- const beams = useMemo(() => {
- const computed = computeAiCoreBeams(aiActivity?.ops, positions, apps, apexY, color);
- if (computed.length === 0 && core.flaring) {
- return [{ key: 'flare', targeted: false, angle: 0, length: AI_CORE.radialLength, thickness: AI_CORE.beamThicknessBase, color }];
- }
- return computed;
- }, [aiActivity, positions, apps, apexY, color, core.flaring]);
-
- useFrame(({ clock }) => {
- if (!animate || !apexRef.current) return;
- // Busy core pulses faster; a flare spikes it; idle breathes slowly.
- const speed = core.busy ? 2.4 : core.flaring ? 3.2 : 0.7;
- const pulse = 0.5 + ((Math.sin(clock.getElapsedTime() * speed) + 1) / 2) * 0.6;
- apexRef.current.material.emissiveIntensity = orbEmissive + pulse * (core.busy ? 0.35 : 0.16);
- if (apexGlowRef.current) {
- apexGlowRef.current.material.opacity = orbGlowOpacity + pulse * 0.04;
- const scale = 1 + pulse * 0.04;
- apexGlowRef.current.scale.setScalar(scale);
- }
- if (orbitRef.current) {
- orbitRef.current.rotation.y = clock.getElapsedTime() * (core.busy ? 0.42 : 0.12);
- orbitRef.current.rotation.z = Math.sin(clock.getElapsedTime() * 0.18) * 0.08;
- }
- if (petalRef.current) {
- petalRef.current.rotation.y = -clock.getElapsedTime() * (core.busy ? 0.12 : 0.025);
- }
- });
-
- return (
- <group position={position}>
- {/* Terraced plaza: broad enough to be legible from orbit, low enough that it
- never hides the live app boroughs behind a decorative tower. */}
- <mesh position={[0, 0.12, 0]}>
- <cylinderGeometry args={[6.4, 6.8, 0.24, 12]} />
- <meshStandardMaterial color={baseColor} roughness={0.9} metalness={0.08} flatShading />
- </mesh>
- <mesh position={[0, 0.34, 0]}>
- <cylinderGeometry args={[4.8, 5.2, 0.3, 12]} />
- <meshStandardMaterial color={petalColor} roughness={0.78} metalness={0.16} flatShading />
- </mesh>
- <group ref={petalRef}>
- {Array.from({ length: 8 }, (_, index) => {
- const angle = (index / 8) * Math.PI * 2;
- return (
- <mesh
- key={`core-petal-${index}`}
- position={[Math.cos(angle) * 3.5, 0.68, Math.sin(angle) * 3.5]}
- rotation={[0, -angle, (index % 2 ? -1 : 1) * 0.08]}
- >
- <boxGeometry args={[3.6, 0.34, 1.05]} />
- <meshStandardMaterial
- color={petalColor}
- emissive={orbColor}
- emissiveIntensity={core.busy ? 0.24 : 0.06}
- roughness={0.72}
- metalness={0.22}
- flatShading
- />
- </mesh>
- );
- })}
- </group>
- <mesh position={[0, 2.7, 0]}>
- <cylinderGeometry args={[0.34, 0.78, 3.4, 6]} />
- <meshStandardMaterial color={baseColor} emissive={orbColor} emissiveIntensity={0.28} roughness={0.48} metalness={0.35} flatShading />
- </mesh>
- <group ref={orbitRef} position={[0, apexY, 0]}>
- <mesh rotation={[Math.PI / 2, 0.22, 0]}>
- <torusGeometry args={[2.55, 0.07, 6, 32]} />
- <meshBasicMaterial color={ringColor} transparent opacity={0.7} toneMapped={false} />
- </mesh>
- <mesh rotation={[0.42, Math.PI / 2, 0.4]}>
- <torusGeometry args={[2.1, 0.055, 6, 28]} />
- <meshBasicMaterial color={orbColor} transparent opacity={0.52} toneMapped={false} />
- </mesh>
- <mesh rotation={[-0.55, 0.18, Math.PI / 2]}>
- <torusGeometry args={[1.65, 0.045, 6, 24]} />
- <meshBasicMaterial color="#fff1c7" transparent opacity={0.42} toneMapped={false} />
- </mesh>
- </group>
- {/* Suspended seed — the live AI-activity indicator. */}
- <mesh ref={apexRef} position={[0, apexY, 0]}>
- <icosahedronGeometry args={[1.25, 1]} />
- <meshStandardMaterial color={orbColor} emissive={orbColor} emissiveIntensity={orbEmissive} roughness={0.28} metalness={0.15} toneMapped={false} />
- </mesh>
- <mesh ref={apexGlowRef} position={[0, apexY, 0]}>
- <sphereGeometry args={[1.62, 20, 12]} />
- <meshBasicMaterial
- color={orbColor}
- transparent
- opacity={orbGlowOpacity}
- blending={THREE.AdditiveBlending}
- depthWrite={false}
- toneMapped={false}
- />
- </mesh>
- <pointLight position={[0, apexY, 0]} color={orbColor} intensity={0.55 + core.intensity * 0.65} distance={18} decay={2} />
- {/* Activity beams emanate from the apex while AI work is in flight */}
- <group position={[0, apexY, 0]}>
- {beams.map((b, i) => (
- b.targeted
- ? <TargetedBeam key={b.key} target={b.target} thickness={b.thickness} color={b.color} seed={i} />
- : <RadialBeam key={b.key} angle={b.angle} length={b.length} thickness={b.thickness} color={b.color} />
- ))}
- </group>
- {/* Label above the apex */}
- <OpenWorldLabel
- position={[0, apexY + 3.2, 0]}
- fontSize={0.72}
- color={orbColor}
- dayMix={dayMix}
- anchorX="center"
- anchorY="middle"
- font={PIXEL_FONT_URL}
- maxWidth={14}
- renderOrder={40}
- material-depthTest={false}
- >
- AI CORE
- </OpenWorldLabel>
- {core.busy && (
- <OpenWorldLabel
- position={[0, apexY + 2.45, 0]}
- fontSize={0.42}
- color="#94a3b8"
- dayMix={dayMix}
- anchorX="center"
- anchorY="middle"
- font={PIXEL_FONT_URL}
- maxWidth={20}
- renderOrder={40}
- material-depthTest={false}
- >
- {`${core.activeCount} ACTIVE`}
- </OpenWorldLabel>
- )}
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldArchipelago.jsx b/client/src/components/openworld/OpenWorldArchipelago.jsx
deleted file mode 100644
index aae83bc33c..0000000000
--- a/client/src/components/openworld/OpenWorldArchipelago.jsx
+++ /dev/null
@@ -1,923 +0,0 @@
-import { useEffect, useLayoutEffect, useMemo, useRef } from 'react';
-import { Text } from '@react-three/drei';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import {
- ARCHIPELAGO_ISLANDS,
- ARCHIPELAGO_LINKS,
- PARCELS,
- VILLAGE_GROUND,
- VILLAGE_ROUTES,
- WORLD,
- archipelagoLinkPoints,
- computeVillageAppLayout,
- isOnArchipelagoIsland,
- openWorldTerrainHeight,
-} from '../../utils/openWorldPlan';
-import { computeArtifacts } from '../../utils/openWorldArtifacts';
-import { computeBackupVault } from '../../utils/openWorldBackupVault';
-import { computeDataHarbor } from '../../utils/openWorldDataHarbor';
-import { computeGoalMonuments } from '../../utils/openWorldGoalMonuments';
-import { computeHealthTower } from '../../utils/openWorldHealthTower';
-import { computeMemoryDistrict } from '../../utils/openWorldMemoryDistrict';
-import { computeProductivityMonument } from '../../utils/openWorldProductivity';
-import { computeTaskQueue } from '../../utils/openWorldTaskQueue';
-import { computeVoiceMarker } from '../../utils/openWorldVoiceMarker';
-import {
- PIXEL_FONT_URL,
- mixHex,
- openWorldDayMix,
- openWorldShowDetail,
- seededRand,
-} from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-
-const dummy = new THREE.Object3D();
-
-const BIOME_COLORS = {
- port: ['#244c43', '#78a66f'],
- memory: ['#24483f', '#5b916c'],
- forge: ['#604c3b', '#a77955'],
- signal: ['#315866', '#6d9d96'],
- harbor: ['#31545b', '#66929a'],
- archive: ['#475448', '#82956f'],
- garden: ['#315c42', '#79a65f'],
- wellness: ['#37644e', '#82ad73'],
-};
-
-const VILLAGE_SITES = [
- { id: 'core', parcel: 'aiCore', label: 'PORTOS COMMON', wall: '#f3d6a6', roof: '#ec755d', accent: '#ffd166', special: 'core' },
- { id: 'memory', parcel: 'memory', label: 'MEMORY HOUSE', wall: '#d7c6ee', roof: '#7c5aa6', accent: '#cab6ff' },
- { id: 'backup', parcel: 'backupVault', label: 'BACKUP COTTAGE', wall: '#d9d0bf', roof: '#47645b', accent: '#91d2b5' },
- { id: 'tasks', parcel: 'taskQueue', label: 'TASK WORKSHOP', wall: '#f1c7a3', roof: '#b95f4d', accent: '#ffb86b' },
- { id: 'archive', parcel: 'warehouse', label: 'ARCHIVE LODGE', wall: '#d7d8c8', roof: '#5f6c59', accent: '#b8c99d' },
- { id: 'wellness', parcel: 'health', label: 'WELLNESS', wall: '#d9edc6', roof: '#4d8b67', accent: '#9ee493', special: 'greenhouse' },
- { id: 'focus', parcel: 'productivity', label: 'FOCUS FARM', wall: '#f2ddb4', roof: '#d18b47', accent: '#ffd166' },
- { id: 'sprint', parcel: 'jira', label: 'SPRINT STUDIO', wall: '#cadde4', roof: '#597c91', accent: '#93d8ef' },
- { id: 'quiet', parcel: 'easterEggs', label: 'QUIET CORNER', wall: '#dfd0e8', roof: '#7d678f', accent: '#d0b1e8' },
- { id: 'goals', parcel: 'goals', label: 'GOALS LODGE', wall: '#f2c7bd', roof: '#b74e66', accent: '#ff8fa3' },
- { id: 'voice', parcel: 'voice', label: 'VOICE RADIO', wall: '#c8dce8', roof: '#49778c', accent: '#85d8e8', special: 'radio' },
- { id: 'artifacts', parcel: 'artifacts', label: 'TROPHY HOUSE', wall: '#ecd9aa', roof: '#b98439', accent: '#ffe29a' },
- { id: 'harbor', parcel: 'dataHarbor', label: 'DATA PIER', wall: '#c7d8d3', roof: '#3f7180', accent: '#85d8e8', special: 'harbor' },
-];
-
-function islandOutline(island, count = 28) {
- const rand = seededRand(island.seed);
- return Array.from({ length: count }, (_, index) => {
- const angle = (index / count) * Math.PI * 2;
- const wobble = 0.9 + rand() * 0.14;
- return [
- island.center[0] + Math.cos(angle) * island.radiusX * wobble,
- island.center[1] + Math.sin(angle) * island.radiusZ * wobble,
- ];
- });
-}
-
-function createIslandGeometry(island) {
- const outline = islandOutline(island);
- const segments = outline.length;
- // Enough radial samples for the shared height field to read as rolling terrain, while
- // keeping a subtle low-poly character instead of giant pie-slice lighting facets.
- const rings = 14;
- const positions = [island.center[0], openWorldTerrainHeight(...island.center), island.center[1]];
- const topIndices = [];
-
- for (let ring = 1; ring <= rings; ring += 1) {
- const fraction = ring / rings;
- outline.forEach(([outerX, outerZ]) => {
- const x = island.center[0] + (outerX - island.center[0]) * fraction;
- const z = island.center[1] + (outerZ - island.center[1]) * fraction;
- positions.push(x, openWorldTerrainHeight(x, z), z);
- });
- }
-
- for (let segment = 0; segment < segments; segment += 1) {
- // XZ polygons wind clockwise when viewed from +Y; reverse the naïve outline order so
- // the playable top faces upward instead of being culled and exposing the ocean below.
- topIndices.push(0, 1 + ((segment + 1) % segments), 1 + segment);
- }
- for (let ring = 1; ring < rings; ring += 1) {
- const innerStart = 1 + (ring - 1) * segments;
- const outerStart = 1 + ring * segments;
- for (let segment = 0; segment < segments; segment += 1) {
- const next = (segment + 1) % segments;
- const a = innerStart + segment;
- const b = outerStart + segment;
- const c = outerStart + next;
- const d = innerStart + next;
- topIndices.push(a, d, b, b, d, c);
- }
- }
-
- const sideIndices = [];
- const outerStart = 1 + (rings - 1) * segments;
- const sideStart = positions.length / 3;
- outline.forEach((_, segment) => {
- const source = (outerStart + segment) * 3;
- positions.push(positions[source], positions[source + 1], positions[source + 2]);
- positions.push(positions[source], WORLD.terrainY, positions[source + 2]);
- });
- for (let segment = 0; segment < segments; segment += 1) {
- const next = (segment + 1) % segments;
- const topA = sideStart + segment * 2;
- const bottomA = topA + 1;
- const topB = sideStart + next * 2;
- const bottomB = topB + 1;
- sideIndices.push(topA, bottomA, topB, bottomA, bottomB, topB);
- }
-
- const geometry = new THREE.BufferGeometry();
- geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
- geometry.setIndex([...topIndices, ...sideIndices]);
- geometry.addGroup(0, topIndices.length, 0);
- geometry.addGroup(topIndices.length, sideIndices.length, 1);
- geometry.computeVertexNormals();
- return { geometry, outline };
-}
-
-function Island({ island, dayMix, detailed }) {
- const { surface } = useOpenWorldPalette();
- const { geometry, outline } = useMemo(() => createIslandGeometry(island), [island]);
- const rimGeometry = useMemo(() => {
- if (!detailed) return null;
- const curve = new THREE.CatmullRomCurve3(
- outline.map(([x, z]) => new THREE.Vector3(x, openWorldTerrainHeight(x, z) + 0.06, z)),
- true,
- 'centripetal',
- );
- return new THREE.TubeGeometry(curve, outline.length * 2, 0.045, 4, true);
- }, [detailed, outline]);
-
- useEffect(() => () => {
- geometry.dispose();
- rimGeometry?.dispose();
- }, [geometry, rimGeometry]);
-
- const [nightColor, dayColor] = BIOME_COLORS[island.biome] || BIOME_COLORS.port;
- return (
- <group>
- <mesh geometry={geometry} receiveShadow>
- <meshStandardMaterial attach="material-0" {...surface} color={mixHex(nightColor, dayColor, dayMix)} roughness={0.98} metalness={0} flatShading />
- <meshStandardMaterial attach="material-1" {...surface} color={mixHex('#1d302a', '#5d6955', dayMix)} roughness={1} metalness={0} flatShading />
- </mesh>
- {rimGeometry && (
- <mesh geometry={rimGeometry}>
- <meshBasicMaterial color={mixHex('#7bb6a0', '#d8d6a7', dayMix)} transparent opacity={0.34} toneMapped={false} />
- </mesh>
- )}
- </group>
- );
-}
-
-const routeCurve = (route) => new THREE.CatmullRomCurve3(
- route.points.map(([x, z]) => new THREE.Vector3(x, 0, z)),
- Boolean(route.closed),
- 'centripetal',
-);
-
-function createRouteRibbon(route, width, yOffset) {
- const curve = routeCurve(route);
- const segments = Math.max(24, route.points.length * 16);
- const positions = [];
- const indices = [];
- for (let index = 0; index <= segments; index += 1) {
- const t = index / segments;
- const point = curve.getPointAt(t);
- const tangent = curve.getTangentAt(Math.min(0.9999, t)).normalize();
- const left = new THREE.Vector3(-tangent.z, 0, tangent.x).multiplyScalar(width / 2);
- const y = openWorldTerrainHeight(point.x, point.z) + yOffset;
- positions.push(point.x + left.x, y, point.z + left.z, point.x - left.x, y, point.z - left.z);
- if (index < segments) {
- const start = index * 2;
- indices.push(start, start + 2, start + 1, start + 2, start + 3, start + 1);
- }
- }
- const geometry = new THREE.BufferGeometry();
- geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
- geometry.setIndex(indices);
- geometry.computeVertexNormals();
- return { curve, geometry };
-}
-
-function VillageRoutes({ dayMix, detailed }) {
- const routeMeshes = useMemo(() => VILLAGE_ROUTES.map((route) => ({
- ...route,
- shoulder: createRouteRibbon(route, route.width + 1.1, 0.045),
- lane: createRouteRibbon(route, route.width, 0.065),
- })), []);
-
- useEffect(() => () => routeMeshes.forEach((route) => {
- route.shoulder.geometry.dispose();
- route.lane.geometry.dispose();
- }), [routeMeshes]);
-
- return (
- <group>
- {routeMeshes.map((route) => (
- <group key={route.id}>
- <mesh geometry={route.shoulder.geometry} receiveShadow>
- <meshStandardMaterial color={mixHex('#4a4b40', '#e5d3a2', dayMix)} roughness={1} flatShading />
- </mesh>
- <mesh geometry={route.lane.geometry} receiveShadow>
- <meshStandardMaterial
- color={route.kind === 'path' ? mixHex('#6e5546', '#c89968', dayMix) : mixHex('#364749', '#7e8b7d', dayMix)}
- roughness={0.96}
- flatShading
- />
- </mesh>
- {detailed && route.kind === 'road' && Array.from({ length: route.closed ? 22 : 7 }, (_, index) => {
- const t = (index + 0.5) / (route.closed ? 22 : 7);
- const point = route.lane.curve.getPointAt(t);
- const tangent = route.lane.curve.getTangentAt(Math.min(0.999, t));
- return (
- <mesh
- key={`${route.id}-marker-${index}`}
- position={[point.x, openWorldTerrainHeight(point.x, point.z) + 0.09, point.z]}
- rotation={[-Math.PI / 2, 0, Math.atan2(tangent.z, tangent.x)]}
- >
- <planeGeometry args={[1.15, 0.12]} />
- <meshBasicMaterial color={mixHex('#79b9b2', '#f4e1a7', dayMix)} transparent opacity={0.66} toneMapped={false} />
- </mesh>
- );
- })}
- </group>
- ))}
- </group>
- );
-}
-
-function createCausewayGeometries() {
- return ARCHIPELAGO_LINKS.map((link) => createRouteRibbon(
- { points: archipelagoLinkPoints(link) },
- link.width + 0.7,
- 0.02,
- ).geometry);
-}
-
-function VillageCauseways({ dayMix }) {
- const geometries = useMemo(() => createCausewayGeometries(), []);
- useEffect(() => () => geometries.forEach((geometry) => geometry.dispose()), [geometries]);
- return geometries.map((geometry, index) => (
- <mesh key={`causeway-${index}`} geometry={geometry} receiveShadow>
- <meshStandardMaterial color={mixHex('#40514b', '#b8a77f', dayMix)} roughness={1} flatShading />
- </mesh>
- ));
-}
-
-const distanceToSegment = (x, z, start, end) => {
- const dx = end[0] - start[0];
- const dz = end[1] - start[1];
- const lengthSq = dx * dx + dz * dz;
- const t = lengthSq <= 1e-8 ? 0 : Math.max(0, Math.min(1, ((x - start[0]) * dx + (z - start[1]) * dz) / lengthSq));
- return Math.hypot(x - (start[0] + dx * t), z - (start[1] + dz * t));
-};
-
-const nearRoute = (x, z, padding = 0) => VILLAGE_ROUTES.some((route) => {
- for (let index = 1; index < route.points.length; index += 1) {
- if (distanceToSegment(x, z, route.points[index - 1], route.points[index]) < route.width / 2 + padding) return true;
- }
- if (route.closed && distanceToSegment(x, z, route.points.at(-1), route.points[0]) < route.width / 2 + padding) return true;
- return false;
-});
-
-const nearDoorstep = (x, z, radius = 7) => Object.values(PARCELS).some((parcel) => (
- Math.hypot(x - parcel.anchor[0], z - parcel.anchor[2]) < radius
-));
-
-function createDressing(detail) {
- const rand = seededRand(4079);
- const trees = [];
- const grass = [];
- const flowers = [];
- const rocks = [];
- const addCandidate = (list, total, options = {}) => {
- let attempts = 0;
- while (list.length < total && attempts < total * 18) {
- attempts += 1;
- const x = -66 + rand() * 132;
- const z = -82 + rand() * 142;
- if (!isOnArchipelagoIsland(x, z, options.inset || 2)) continue;
- if (nearRoute(x, z, options.routePadding || 0.8)) continue;
- if (nearDoorstep(x, z, options.doorstep || 6.5)) continue;
- const marketRadius = Math.hypot(x, z);
- if (options.clearMarket && marketRadius > 10.4 && marketRadius < 19.4) continue;
- list.push({ x, z, yaw: rand() * Math.PI * 2, scale: (options.minScale || 0.65) + rand() * (options.scaleRange || 0.7), variant: Math.floor(rand() * 4) });
- }
- };
- addCandidate(trees, Math.round(205 * detail), { routePadding: 1.7, doorstep: 8.5, minScale: 0.72, scaleRange: 0.85, inset: 3, clearMarket: true });
- addCandidate(grass, Math.round(980 * detail), { routePadding: 0.5, doorstep: 5, minScale: 0.65, scaleRange: 0.85, inset: 1.5 });
- addCandidate(flowers, Math.round(185 * detail), { routePadding: 0.36, doorstep: 4.5, minScale: 0.7, scaleRange: 0.76, inset: 2 });
- addCandidate(rocks, Math.round(38 * detail), { routePadding: 1, doorstep: 7, minScale: 0.35, scaleRange: 0.75, inset: 2.5, clearMarket: true });
- return { trees, grass, flowers, rocks };
-}
-
-function VillageDressing({ settings, dayMix }) {
- const { surface } = useOpenWorldPalette();
- const detail = settings?.effectiveTier === 'low' ? 0.34 : settings?.effectiveTier === 'medium' ? 0.68 : settings?.effectiveTier === 'ultra' ? 1.2 : 1;
- const { trees, grass, flowers, rocks } = useMemo(() => createDressing(detail), [detail]);
- const trunkRef = useRef();
- const canopyRefs = useRef([]);
- const grassRef = useRef();
- const flowerRef = useRef();
- const rockRef = useRef();
-
- useLayoutEffect(() => {
- trees.forEach((tree, index) => {
- const y = openWorldTerrainHeight(tree.x, tree.z);
- dummy.position.set(tree.x, y + 0.85 * tree.scale, tree.z);
- dummy.rotation.set(0, tree.yaw, 0);
- dummy.scale.set(tree.scale, tree.scale, tree.scale);
- dummy.updateMatrix();
- trunkRef.current?.setMatrixAt(index, dummy.matrix);
- [[-0.5, 2.15, 0.05, 1], [0.5, 2.15, 0.12, 0.92], [0, 2.62, -0.08, 0.95]].forEach(([ox, oy, oz, size], canopyIndex) => {
- dummy.position.set(tree.x + ox * tree.scale, y + oy * tree.scale, tree.z + oz * tree.scale);
- dummy.rotation.set(tree.yaw * 0.13, tree.yaw + canopyIndex * 0.5, tree.yaw * 0.08);
- dummy.scale.setScalar(tree.scale * size);
- dummy.updateMatrix();
- canopyRefs.current[canopyIndex]?.setMatrixAt(index, dummy.matrix);
- });
- });
- grass.forEach((item, index) => {
- dummy.position.set(item.x, openWorldTerrainHeight(item.x, item.z) + 0.23 * item.scale, item.z);
- dummy.rotation.set(0, item.yaw, (item.variant - 1.5) * 0.035);
- dummy.scale.set(item.scale, item.scale, item.scale);
- dummy.updateMatrix();
- grassRef.current?.setMatrixAt(index, dummy.matrix);
- });
- flowers.forEach((item, index) => {
- dummy.position.set(item.x, openWorldTerrainHeight(item.x, item.z) + 0.2 * item.scale, item.z);
- dummy.rotation.set(0, item.yaw, 0);
- dummy.scale.setScalar(item.scale);
- dummy.updateMatrix();
- flowerRef.current?.setMatrixAt(index, dummy.matrix);
- });
- rocks.forEach((item, index) => {
- dummy.position.set(item.x, openWorldTerrainHeight(item.x, item.z) + 0.2 * item.scale, item.z);
- dummy.rotation.set(item.yaw * 0.1, item.yaw, item.yaw * 0.08);
- dummy.scale.set(item.scale * 1.2, item.scale * 0.72, item.scale);
- dummy.updateMatrix();
- rockRef.current?.setMatrixAt(index, dummy.matrix);
- });
- [trunkRef.current, ...canopyRefs.current, grassRef.current, flowerRef.current, rockRef.current].forEach((mesh) => {
- if (!mesh) return;
- mesh.instanceMatrix.needsUpdate = true;
- mesh.computeBoundingSphere?.();
- });
- }, [flowers, grass, rocks, trees]);
-
- const leafColors = [
- mixHex('#315f48', '#6ea35f', dayMix),
- mixHex('#3a5c4b', '#8aad66', dayMix),
- mixHex('#5f4a4e', '#d78b82', dayMix),
- ];
- return (
- <group>
- <instancedMesh ref={trunkRef} args={[undefined, undefined, trees.length]} castShadow receiveShadow>
- <cylinderGeometry args={[0.14, 0.26, 1.7, 7]} />
- <meshStandardMaterial {...surface} color={mixHex('#2d372f', '#75553c', dayMix)} roughness={1} flatShading />
- </instancedMesh>
- {leafColors.map((color, index) => (
- <instancedMesh key={color} ref={(node) => { canopyRefs.current[index] = node; }} args={[undefined, undefined, trees.length]} castShadow>
- <dodecahedronGeometry args={[0.95, 0]} />
- <meshStandardMaterial {...surface} color={color} roughness={1} flatShading />
- </instancedMesh>
- ))}
- <instancedMesh ref={grassRef} args={[undefined, undefined, grass.length]} receiveShadow>
- <coneGeometry args={[0.24, 0.7, 4]} />
- <meshStandardMaterial color={mixHex('#29533f', '#86a94f', dayMix)} roughness={1} flatShading />
- </instancedMesh>
- <instancedMesh ref={flowerRef} args={[undefined, undefined, flowers.length]}>
- <octahedronGeometry args={[0.16, 0]} />
- <meshStandardMaterial color={mixHex('#bd76b4', '#ffd166', dayMix * 0.38)} emissive="#c46fad" emissiveIntensity={0.16} roughness={0.9} flatShading />
- </instancedMesh>
- <instancedMesh ref={rockRef} args={[undefined, undefined, rocks.length]} castShadow receiveShadow>
- <dodecahedronGeometry args={[0.62, 0]} />
- <meshStandardMaterial {...surface} color={mixHex('#33434a', '#85877b', dayMix)} roughness={1} flatShading />
- </instancedMesh>
- </group>
- );
-}
-
-function WarmWindow({ position, scale = [0.8, 0.74, 0.06], color }) {
- return (
- <mesh position={position}>
- <boxGeometry args={scale} />
- <meshStandardMaterial color="#3b5361" emissive={color} emissiveIntensity={0.42} roughness={0.52} />
- </mesh>
- );
-}
-
-function Cottage({ site, dayMix, metric }) {
- const parcel = PARCELS[site.parcel];
- const x = parcel.anchor[0];
- const z = parcel.anchor[2];
- const y = openWorldTerrainHeight(x, z);
- const width = site.special === 'harbor' ? 6.8 : 5.2;
- const depth = site.special === 'harbor' ? 4.2 : 4.6;
- const roofColor = mixHex(site.roof, '#5c5047', 1 - dayMix);
- const labelSize = site.label.length > 13 ? 0.235 : site.label.length > 10 ? 0.265 : 0.3;
-
- return (
- <group position={[x, y, z]}>
- {site.special === 'harbor' && (
- <mesh position={[0, 0.08, 2.8]} receiveShadow>
- <boxGeometry args={[11, 0.22, 7.5]} />
- <meshStandardMaterial color={mixHex('#32433f', '#9a7651', dayMix)} roughness={1} />
- </mesh>
- )}
- <mesh position={[0, 1.55, 0]} castShadow receiveShadow>
- <boxGeometry args={[width, 3.1, depth]} />
- <meshStandardMaterial color={site.wall} roughness={0.96} flatShading />
- </mesh>
- <mesh position={[0, 3.55, 0]} rotation={[0, Math.PI / 4, 0]} castShadow>
- <coneGeometry args={[width * 0.73, 1.65, 4]} />
- <meshStandardMaterial color={roofColor} roughness={0.95} flatShading />
- </mesh>
- <mesh position={[0, 0.95, depth / 2 + 0.07]}>
- <boxGeometry args={[1.05, 1.9, 0.13]} />
- <meshStandardMaterial color={mixHex('#263a3b', '#755742', dayMix)} roughness={0.9} />
- </mesh>
- <WarmWindow position={[-1.55, 1.75, depth / 2 + 0.08]} color={site.accent} />
- <WarmWindow position={[1.55, 1.75, depth / 2 + 0.08]} color={site.accent} />
- {/* The plaque sits below and in front of the roofline. Its old y-position was exactly
- level with the roof's lower edge, so the eave hid every destination name. */}
- <mesh position={[0, 2.4, depth / 2 + 0.28]} castShadow>
- <boxGeometry args={[3.65, metric ? 0.82 : 0.62, 0.16]} />
- <meshStandardMaterial color={mixHex('#263c3a', '#fff1cc', dayMix * 0.16)} roughness={0.88} />
- </mesh>
- <Text position={[0, metric ? 2.55 : 2.4, depth / 2 + 0.39]} font={PIXEL_FONT_URL} fontSize={labelSize} color={mixHex(site.accent, '#fff0cf', dayMix * 0.72)} anchorX="center" anchorY="middle" letterSpacing={0.045}>
- {site.label}
- </Text>
- {metric && (
- <Text position={[0, 2.25, depth / 2 + 0.395]} font={PIXEL_FONT_URL} fontSize={0.145} color={mixHex(metric.color || site.accent, '#f7dfae', 0.46)} anchorX="center" anchorY="middle" letterSpacing={0.035}>
- {metric.label}
- </Text>
- )}
- <mesh position={[0, 0.17, depth / 2 + 1.15]} receiveShadow>
- <boxGeometry args={[2.7, 0.22, 1.6]} />
- <meshStandardMaterial color={mixHex('#3b4e45', '#c2a16d', dayMix)} roughness={1} />
- </mesh>
- {site.special === 'greenhouse' && (
- <mesh position={[0, 4.75, 0]}>
- <sphereGeometry args={[1.4, 16, 9, 0, Math.PI * 2, 0, Math.PI / 2]} />
- <meshStandardMaterial color="#b7ead3" transparent opacity={0.5} roughness={0.18} metalness={0.08} />
- </mesh>
- )}
- {site.special === 'radio' && (
- <group position={[0, 5.4, 0]}>
- <mesh rotation={[0, 0, -0.18]}><cylinderGeometry args={[0.05, 0.05, 3.1, 7]} /><meshStandardMaterial color="#38545d" roughness={0.65} metalness={0.25} /></mesh>
- <mesh position={[0.25, 1.25, 0]} rotation={[0, 0, 0.38]}><coneGeometry args={[0.7, 0.34, 14, 1, true]} /><meshStandardMaterial color={site.accent} emissive={site.accent} emissiveIntensity={0.28} side={THREE.DoubleSide} /></mesh>
- </group>
- )}
- {[[-width / 2 - 0.8, depth / 2 + 0.3], [width / 2 + 0.8, depth / 2 + 0.3]].map(([px, pz], index) => (
- <group key={`${site.id}-planter-${index}`} position={[px, 0, pz]}>
- <mesh position={[0, 0.24, 0]}><cylinderGeometry args={[0.48, 0.38, 0.48, 8]} /><meshStandardMaterial color={mixHex('#4a3b35', '#b97856', dayMix)} roughness={1} /></mesh>
- <mesh position={[0, 0.72, 0]}><dodecahedronGeometry args={[0.48, 0]} /><meshStandardMaterial color={mixHex('#2d5a42', '#71a55f', dayMix)} roughness={1} flatShading /></mesh>
- </group>
- ))}
- </group>
- );
-}
-
-function CorePavilion({ site, dayMix }) {
- const [x, , z] = PARCELS.aiCore.anchor;
- const y = openWorldTerrainHeight(x, z);
- const orbRef = useRef();
- useFrame(({ clock }) => {
- if (!orbRef.current) return;
- const t = clock.getElapsedTime();
- orbRef.current.position.y = 2.45 + Math.sin(t * 1.4) * 0.12;
- orbRef.current.rotation.y = t * 0.45;
- });
- return (
- <group position={[x, y, z]}>
- <mesh receiveShadow position={[0, 0.08, 0]}><cylinderGeometry args={[7.2, 7.8, 0.34, 24]} /><meshStandardMaterial color={mixHex('#3f554e', '#d7c593', dayMix)} roughness={1} flatShading /></mesh>
- {Array.from({ length: 8 }, (_, index) => {
- const angle = (index / 8) * Math.PI * 2;
- return (
- <mesh key={`core-seat-${index}`} position={[Math.cos(angle) * 5.3, 0.34, Math.sin(angle) * 5.3]} rotation={[0, -angle, 0]} castShadow>
- <boxGeometry args={[2.2, 0.32, 0.78]} />
- <meshStandardMaterial color={mixHex('#31433d', '#ad7c52', dayMix)} roughness={1} />
- </mesh>
- );
- })}
- {[0, 1, 2].map((index) => {
- const angle = (index / 3) * Math.PI * 2;
- return (
- <mesh key={`core-arch-${index}`} position={[Math.cos(angle) * 3.6, 2.5, Math.sin(angle) * 3.6]} rotation={[0, -angle, 0]} castShadow>
- <boxGeometry args={[0.56, 5, 0.72]} />
- <meshStandardMaterial color={mixHex('#334d48', site.wall, dayMix * 0.72)} roughness={0.92} flatShading />
- </mesh>
- );
- })}
- <group ref={orbRef} position={[0, 2.45, 0]}>
- <mesh castShadow><dodecahedronGeometry args={[1.42, 0]} /><meshStandardMaterial color={site.accent} emissive={site.accent} emissiveIntensity={0.66} roughness={0.4} flatShading toneMapped={false} /></mesh>
- <mesh rotation={[Math.PI / 2, 0, 0]}><torusGeometry args={[2.1, 0.07, 8, 42]} /><meshBasicMaterial color="#fff1bb" transparent opacity={0.78} toneMapped={false} /></mesh>
- </group>
- <mesh position={[0, 0.52, 5.4]}><boxGeometry args={[3.8, 0.72, 0.18]} /><meshStandardMaterial color={mixHex('#263b39', '#f2ddb4', dayMix * 0.15)} roughness={0.9} /></mesh>
- <Text position={[0, 0.52, 5.52]} font={PIXEL_FONT_URL} fontSize={0.38} color={mixHex(site.accent, '#fff0cf', dayMix * 0.72)} anchorX="center" anchorY="middle" letterSpacing={0.08}>PORTOS COMMON</Text>
- </group>
- );
-}
-
-function VillageSites({ dayMix, metrics, jiraEnabled }) {
- return VILLAGE_SITES.filter((site) => site.id !== 'sprint' || jiraEnabled).map((site) => (
- site.special === 'core'
- ? <CorePavilion key={site.id} site={site} dayMix={dayMix} />
- : <Cottage key={site.id} site={site} dayMix={dayMix} metric={metrics?.[site.id]} />
- ));
-}
-
-const APP_STATUS_COLOR = {
- online: '#67c77b',
- stopped: '#ef6b63',
- not_started: '#e5b85c',
- unknown: '#91a0a3',
- not_found: '#91a0a3',
-};
-
-const appDisplayName = (app) => {
- const name = String(app?.name || app?.id || 'APP').trim().toUpperCase();
- return name.length > 17 ? `${name.slice(0, 15)}…` : name;
-};
-
-const activeAgentsForApp = (agentMap, appId) => {
- const agents = agentMap?.get?.(appId)?.agents;
- if (!Array.isArray(agents)) return 0;
- return agents.filter((agent) => ['running', 'coding', 'thinking', 'investigating'].includes(agent?.status || agent?.state)).length;
-};
-
-function AppKiosk({ app, position, agentMap, dayMix, onBuildingClick }) {
- const statusColor = APP_STATUS_COLOR[app.overallStatus] || APP_STATUS_COLOR.unknown;
- const activeAgents = Math.min(3, activeAgentsForApp(agentMap, app.id));
- const label = appDisplayName(app);
- const y = openWorldTerrainHeight(position.x, position.z);
- const labelSize = label.length > 13 ? 0.19 : 0.225;
-
- return (
- <group
- position={[position.x, y, position.z]}
- rotation={[0, position.yaw, 0]}
- onClick={(event) => {
- event.stopPropagation();
- onBuildingClick?.(app);
- }}
- >
- <mesh position={[0, 0.08, 0]} receiveShadow>
- <boxGeometry args={[2.55, 0.16, 1.85]} />
- <meshStandardMaterial color={mixHex('#3c4a42', '#c5a16b', dayMix)} roughness={1} />
- </mesh>
- <mesh position={[0, 0.93, -0.34]} castShadow receiveShadow>
- <boxGeometry args={[2.28, 1.7, 0.56]} />
- <meshStandardMaterial color={mixHex('#4b5660', '#eee0be', dayMix)} roughness={0.94} />
- </mesh>
- <mesh position={[0, 1.86, -0.08]} rotation={[0, Math.PI / 4, 0]} castShadow>
- <coneGeometry args={[1.52, 0.72, 4]} />
- <meshStandardMaterial color={mixHex('#38595a', statusColor, dayMix * 0.55)} roughness={0.96} flatShading />
- </mesh>
- <mesh position={[0, 0.78, 0.63]} castShadow>
- <boxGeometry args={[2.22, 0.2, 0.55]} />
- <meshStandardMaterial color={mixHex('#31443e', '#8b6446', dayMix)} roughness={1} />
- </mesh>
- <mesh position={[0, 1.28, 0.34]}>
- <boxGeometry args={[2.08, 0.5, 0.12]} />
- <meshStandardMaterial color={mixHex('#263b39', '#fff1cf', dayMix * 0.14)} roughness={0.9} />
- </mesh>
- <Text position={[0, 1.29, 0.415]} font={PIXEL_FONT_URL} fontSize={labelSize} color={mixHex(statusColor, '#fff0cf', dayMix * 0.58)} anchorX="center" anchorY="middle" letterSpacing={0.035}>
- {label}
- </Text>
- <mesh position={[0.92, 2.38, -0.08]} castShadow>
- <sphereGeometry args={[0.16, 8, 6]} />
- <meshStandardMaterial color={statusColor} emissive={statusColor} emissiveIntensity={app.overallStatus === 'online' ? 0.72 : 0.3} roughness={0.5} />
- </mesh>
- {Array.from({ length: activeAgents }, (_, index) => (
- <mesh key={`agent-${index}`} position={[-0.42 + index * 0.42, 1.02, 0.58]}>
- <dodecahedronGeometry args={[0.105, 0]} />
- <meshBasicMaterial color="#fff0a6" toneMapped={false} />
- </mesh>
- ))}
- </group>
- );
-}
-
-function VillageAppMarket({ apps, appPositions, agentMap, dayMix, onBuildingClick }) {
- const managedApps = (Array.isArray(apps) ? apps : []).filter((app) => app?.id && !app.archived);
- const visibleApps = managedApps.filter((app) => appPositions?.has?.(app.id));
- const activeCount = managedApps.filter((app) => app.overallStatus === 'online').length;
- const totalManaged = managedApps.length;
- const overflow = Math.max(0, totalManaged - visibleApps.length);
- const banner = totalManaged === 0
- ? 'MANAGED APPS · READY FOR ARRIVALS'
- : `MANAGED APPS · ${activeCount}/${totalManaged} ONLINE${overflow ? ` · +${overflow} MORE` : ''}`;
-
- return (
- <group>
- <group position={[-5.8, openWorldTerrainHeight(-5.8, 10.5), 10.5]} rotation={[0, 0.18, 0]}>
- <mesh position={[-2.5, 1.22, 0]} castShadow><boxGeometry args={[0.12, 2.45, 0.14]} /><meshStandardMaterial color="#76553d" roughness={1} /></mesh>
- <mesh position={[2.5, 1.22, 0]} castShadow><boxGeometry args={[0.12, 2.45, 0.14]} /><meshStandardMaterial color="#76553d" roughness={1} /></mesh>
- <mesh position={[0, 2.1, 0]} castShadow><boxGeometry args={[5.2, 0.68, 0.15]} /><meshStandardMaterial color={mixHex('#29413d', '#f4dfad', dayMix * 0.15)} roughness={0.92} /></mesh>
- <Text position={[0, 2.1, 0.09]} font={PIXEL_FONT_URL} fontSize={0.185} color={mixHex('#80d5b0', '#fff0cf', dayMix * 0.72)} anchorX="center" anchorY="middle" letterSpacing={0.035}>{banner}</Text>
- </group>
- {visibleApps.map((app) => (
- <AppKiosk key={app.id} app={app} position={appPositions.get(app.id)} agentMap={agentMap} dayMix={dayMix} onBuildingClick={onBuildingClick} />
- ))}
- </group>
- );
-}
-
-function MemoryGrove({ district, inboxDepth, dayMix }) {
- return (
- <group>
- {district.clusters.slice(0, 7).map((cluster) => {
- const [x, , z] = cluster.position;
- const y = openWorldTerrainHeight(x, z);
- return (
- <group key={cluster.category} position={[x, y, z]}>
- <mesh position={[0, 0.65, 0]} castShadow><cylinderGeometry args={[0.09, 0.16, 1.3, 7]} /><meshStandardMaterial color="#71533f" roughness={1} /></mesh>
- {[[-0.32, 1.38], [0.32, 1.42], [0, 1.76]].map(([offset, height], blossomIndex) => (
- <mesh key={blossomIndex} position={[offset, height, (blossomIndex - 1) * 0.08]} castShadow>
- <dodecahedronGeometry args={[0.48 + Math.min(0.18, cluster.count * 0.015), 0]} />
- <meshStandardMaterial color={cluster.color} emissive={cluster.color} emissiveIntensity={0.16 + Math.min(0.32, cluster.importance * 0.025)} roughness={0.78} flatShading />
- </mesh>
- ))}
- <Text position={[0, 0.28, 0.52]} font={PIXEL_FONT_URL} fontSize={0.14} color={mixHex(cluster.color, '#4b4037', dayMix * 0.65)} anchorX="center" anchorY="middle">{cluster.count}</Text>
- </group>
- );
- })}
- {inboxDepth > 0 && (
- <group position={[-38, openWorldTerrainHeight(-38, -25), -25]}>
- <mesh position={[0, 0.3, 0]}><cylinderGeometry args={[0.72, 0.9, 0.6, 12]} /><meshStandardMaterial color="#46544d" roughness={1} /></mesh>
- <mesh position={[0, 0.57, 0]} rotation={[-Math.PI / 2, 0, 0]}><circleGeometry args={[0.56, 18]} /><meshBasicMaterial color="#cab6ff" transparent opacity={0.82} toneMapped={false} /></mesh>
- <Text position={[0, 1.12, 0]} font={PIXEL_FONT_URL} fontSize={0.14} color="#cab6ff" anchorX="center" anchorY="middle">{`${inboxDepth} TO SORT`}</Text>
- </group>
- )}
- </group>
- );
-}
-
-function TaskYard({ queue, dayMix }) {
- const [x, , z] = PARCELS.taskQueue.anchor;
- return (
- <group position={[x + 4.2, openWorldTerrainHeight(x + 4.2, z), z - 0.5]}>
- {queue.crates.map((crate, index) => {
- const column = index % 2;
- const row = Math.floor(index / 2);
- return (
- <mesh key={crate.index} position={[(column - 0.5) * 1.12, 0.46 + row * 0.86, 0]} castShadow receiveShadow>
- <boxGeometry args={[0.98, 0.78, 0.92]} />
- <meshStandardMaterial color={mixHex('#5d493d', queue.color, dayMix * 0.34)} emissive={queue.color} emissiveIntensity={queue.active ? 0.13 : 0.03} roughness={0.95} />
- </mesh>
- );
- })}
- {queue.hasBlocked && <mesh position={[0, 4.15, 0]} rotation={[0, 0, Math.PI / 4]}><octahedronGeometry args={[0.42, 0]} /><meshBasicMaterial color={queue.color} toneMapped={false} /></mesh>}
- </group>
- );
-}
-
-function BackupPost({ vault }) {
- const [x, , z] = PARCELS.backupVault.anchor;
- const px = x - 4.2;
- const pz = z + 0.3;
- const pulse = vault.running || vault.alerting ? 0.78 : 0.38;
- return (
- <group position={[px, openWorldTerrainHeight(px, pz), pz]}>
- <mesh position={[0, 1.05, 0]} castShadow><cylinderGeometry args={[0.08, 0.12, 2.1, 7]} /><meshStandardMaterial color="#644b3a" roughness={1} /></mesh>
- <mesh position={[0, 2.08, 0]} castShadow><dodecahedronGeometry args={[0.48, 0]} /><meshStandardMaterial color={vault.color} emissive={vault.color} emissiveIntensity={pulse} roughness={0.62} /></mesh>
- <Text position={[0, 2.82, 0]} font={PIXEL_FONT_URL} fontSize={0.15} color={vault.color} anchorX="center" anchorY="middle">{vault.statusLabel}</Text>
- </group>
- );
-}
-
-function DataCargo({ harbor, dayMix }) {
- if (harbor.empty) return null;
- const count = Math.min(8, harbor.silos.length + harbor.racks.length);
- const [x, , z] = PARCELS.dataHarbor.anchor;
- return (
- <group>
- {Array.from({ length: count }, (_, index) => {
- const side = index % 2 === 0 ? -1 : 1;
- const row = Math.floor(index / 2);
- const px = x + side * (4.4 + row * 0.9);
- const pz = z + 0.4 - row * 0.55;
- return (
- <mesh key={`data-cargo-${index}`} position={[px, openWorldTerrainHeight(px, pz) + 0.48, pz]} castShadow receiveShadow>
- <boxGeometry args={[1.25, 0.92, 0.92]} />
- <meshStandardMaterial color={mixHex('#375158', index % 3 === 0 ? '#77c2b1' : '#d29b62', dayMix * 0.62)} roughness={0.9} metalness={0.04} />
- </mesh>
- );
- })}
- </group>
- );
-}
-
-function GoalFlags({ goals, dayMix }) {
- const [x, , z] = PARCELS.goals.anchor;
- return (
- <group>
- {goals.monuments.slice(0, 6).map((goal, index) => {
- const px = x - 5 + index * 1.65;
- const pz = z + 4.2;
- return (
- <group key={goal.id} position={[px, openWorldTerrainHeight(px, pz), pz]}>
- <mesh position={[0, 1.15, 0]}><cylinderGeometry args={[0.035, 0.05, 2.3, 6]} /><meshStandardMaterial color="#654d3c" roughness={1} /></mesh>
- <mesh position={[0.32, 1.82, 0]} rotation={[0, 0, -0.12]}><coneGeometry args={[0.33, 0.68, 3]} /><meshStandardMaterial color={mixHex(goal.color, '#f0c97b', dayMix * 0.16)} emissive={goal.color} emissiveIntensity={goal.built ? 0.28 : 0.08} roughness={0.86} /></mesh>
- </group>
- );
- })}
- </group>
- );
-}
-
-function VillagePortosLife({
- apps,
- appPositions,
- agentMap,
- backupStatus,
- cosTasks,
- healthMetrics,
- productivityData,
- goals,
- character,
- memoryGraph,
- inboxDepth,
- jiraTickets,
- jiraEnabled,
- introspection,
- voiceState,
- dayMix,
- onBuildingClick,
-}) {
- const memory = useMemo(() => computeMemoryDistrict(memoryGraph), [memoryGraph]);
- const queue = useMemo(() => computeTaskQueue(cosTasks), [cosTasks]);
- const vault = useMemo(() => computeBackupVault(backupStatus), [backupStatus]);
- const harbor = useMemo(() => computeDataHarbor(introspection), [introspection]);
- const goalData = useMemo(() => computeGoalMonuments(Array.isArray(goals) ? goals : goals?.goals), [goals]);
- const artifacts = useMemo(() => computeArtifacts({ character, goals }), [character, goals]);
- const health = useMemo(() => computeHealthTower(healthMetrics), [healthMetrics]);
- const productivity = useMemo(() => computeProductivityMonument(productivityData), [productivityData]);
- const voice = useMemo(() => computeVoiceMarker(voiceState), [voiceState]);
- const archivedCount = (Array.isArray(apps) ? apps : []).filter((app) => app?.archived).length;
- const dataCount = harbor.empty ? 0 : harbor.silos.length + harbor.racks.length;
- const metrics = {
- memory: { label: `${memory.totalMemories} MEMORIES${inboxDepth > 0 ? ` · ${inboxDepth} TO SORT` : ''}`, color: '#8c6fd1' },
- backup: { label: vault.statusLabel, color: vault.color },
- tasks: { label: queue.total ? `${queue.total} OPEN · ${queue.state.toUpperCase()}` : 'QUEUE CLEAR', color: queue.color },
- archive: { label: `${archivedCount} ARCHIVED APP${archivedCount === 1 ? '' : 'S'}`, color: '#71806c' },
- wellness: { label: `${health.presentCount}/4 VITALS REPORTING`, color: health.hasData ? '#4d9b67' : '#71806c' },
- focus: { label: productivity.throughputLabel, color: productivity.color },
- sprint: { label: `${Array.isArray(jiraTickets) ? jiraTickets.length : 0} SPRINT TICKETS`, color: '#4f8ea9' },
- quiet: { label: 'SECRETS LIVE HERE', color: '#9477a5' },
- goals: { label: `${goalData.completedCount}/${goalData.total} GOALS COMPLETE`, color: '#b74e66' },
- voice: { label: voice.label, color: voice.color },
- artifacts: { label: `${artifacts.total} TROPH${artifacts.total === 1 ? 'Y' : 'IES'} EARNED`, color: '#b98439' },
- harbor: { label: `${dataCount} DATA DOMAINS`, color: harbor.dbDown ? '#c46b62' : '#4f8e91' },
- };
-
- return (
- <group>
- <VillageSites dayMix={dayMix} metrics={metrics} jiraEnabled={jiraEnabled} />
- <VillageAppMarket apps={apps} appPositions={appPositions} agentMap={agentMap} dayMix={dayMix} onBuildingClick={onBuildingClick} />
- <MemoryGrove district={memory} inboxDepth={inboxDepth} dayMix={dayMix} />
- <TaskYard queue={queue} dayMix={dayMix} />
- <BackupPost vault={vault} />
- <DataCargo harbor={harbor} dayMix={dayMix} />
- <GoalFlags goals={goalData} dayMix={dayMix} />
- </group>
- );
-}
-
-function Bench({ position, rotation = 0, dayMix }) {
- return (
- <group position={[position[0], openWorldTerrainHeight(position[0], position[1]), position[1]]} rotation={[0, rotation, 0]}>
- <mesh position={[0, 0.55, 0]} castShadow><boxGeometry args={[2.4, 0.22, 0.55]} /><meshStandardMaterial color={mixHex('#3a443d', '#bb8052', dayMix)} roughness={1} /></mesh>
- <mesh position={[0, 1.04, 0.22]} rotation={[-0.12, 0, 0]} castShadow><boxGeometry args={[2.4, 0.82, 0.18]} /><meshStandardMaterial color={mixHex('#3a443d', '#bb8052', dayMix)} roughness={1} /></mesh>
- {[-0.82, 0.82].map((x) => <mesh key={x} position={[x, 0.24, 0]}><boxGeometry args={[0.18, 0.48, 0.42]} /><meshStandardMaterial color="#34423f" roughness={0.8} /></mesh>)}
- </group>
- );
-}
-
-function VillageProps({ dayMix }) {
- const lanterns = [[-12, 32], [12, 32], [-27, 11], [28, 3], [-16, -18], [17, -18], [0, -37], [0, -53]];
- return (
- <group>
- <group position={[0, openWorldTerrainHeight(0, 41), 41]}>
- {[-3.3, 3.3].map((x) => <mesh key={x} position={[x, 3, 0]} castShadow><boxGeometry args={[0.52, 6, 0.65]} /><meshStandardMaterial color={mixHex('#354943', '#b98554', dayMix)} roughness={1} /></mesh>)}
- <mesh position={[0, 5.7, 0]} castShadow><boxGeometry args={[7.15, 0.65, 0.72]} /><meshStandardMaterial color={mixHex('#354943', '#b98554', dayMix)} roughness={1} /></mesh>
- <mesh position={[0, 5.08, 0.38]}><boxGeometry args={[3.8, 0.95, 0.18]} /><meshStandardMaterial color={mixHex('#293d39', '#f0ddb2', dayMix * 0.18)} roughness={0.9} /></mesh>
- <Text position={[0, 5.08, 0.5]} font={PIXEL_FONT_URL} fontSize={0.38} color={mixHex('#94d7bf', '#fff0cf', dayMix * 0.78)} anchorX="center" anchorY="middle" letterSpacing={0.08}>PORTOS VILLAGE</Text>
- </group>
- {lanterns.map(([x, z], index) => (
- <group key={`lantern-${index}`} position={[x, openWorldTerrainHeight(x, z), z]}>
- <mesh position={[0, 1.2, 0]} castShadow><cylinderGeometry args={[0.07, 0.11, 2.4, 7]} /><meshStandardMaterial color="#344746" roughness={0.75} metalness={0.12} /></mesh>
- <mesh position={[0, 2.25, 0]} castShadow><boxGeometry args={[0.52, 0.68, 0.52]} /><meshStandardMaterial color="#355058" emissive="#ffd27a" emissiveIntensity={0.58} roughness={0.48} /></mesh>
- <mesh position={[0, 2.67, 0]} rotation={[0, Math.PI / 4, 0]}><coneGeometry args={[0.5, 0.35, 4]} /><meshStandardMaterial color="#a85749" roughness={1} /></mesh>
- </group>
- ))}
- <Bench position={[-8, 9]} rotation={0.58} dayMix={dayMix} />
- <Bench position={[10, 10]} rotation={-0.6} dayMix={dayMix} />
- <Bench position={[-7, -30]} rotation={2.7} dayMix={dayMix} />
- {Array.from({ length: 20 }, (_, index) => {
- const row = Math.floor(index / 5);
- const column = index % 5;
- const x = -40 + column * 1.15;
- const z = 19 + row * 1.1;
- return (
- <group key={`crop-${index}`} position={[x, openWorldTerrainHeight(x, z), z]}>
- <mesh position={[0, 0.1, 0]}><boxGeometry args={[0.9, 0.16, 0.78]} /><meshStandardMaterial color="#74533c" roughness={1} /></mesh>
- <mesh position={[0, 0.47, 0]}><dodecahedronGeometry args={[0.34, 0]} /><meshStandardMaterial color={index % 3 === 0 ? '#e7b84b' : '#69a45b'} roughness={1} flatShading /></mesh>
- </group>
- );
- })}
- <mesh position={[8, openWorldTerrainHeight(8, 17) + 0.035, 17]} rotation={[-Math.PI / 2, 0, -0.18]}>
- <circleGeometry args={[4.7, 32]} />
- <meshStandardMaterial color={mixHex('#224f5c', '#69b4aa', dayMix)} emissive="#4e9d9b" emissiveIntensity={0.12} roughness={0.28} metalness={0.08} transparent opacity={0.92} />
- </mesh>
- </group>
- );
-}
-
-function Fireflies({ dayMix }) {
- const refs = useRef([]);
- const particles = useMemo(() => Array.from({ length: 24 }, (_, index) => ({ x: -24 + ((index * 17) % 49), z: -26 + ((index * 29) % 59), phase: index * 0.83 })), []);
- useFrame(({ clock }) => {
- const time = clock.getElapsedTime();
- refs.current.forEach((mesh, index) => {
- if (!mesh) return;
- const point = particles[index];
- mesh.position.set(point.x + Math.sin(time * 0.43 + point.phase) * 1.4, openWorldTerrainHeight(point.x, point.z) + 1.3 + Math.sin(time * 1.2 + point.phase) * 0.55, point.z + Math.cos(time * 0.37 + point.phase) * 1.1);
- });
- });
- return (
- <group>
- {particles.map((particle, index) => (
- <mesh key={particle.phase} ref={(node) => { refs.current[index] = node; }}><sphereGeometry args={[0.075, 6, 5]} /><meshBasicMaterial color={mixHex('#7ee4d5', '#fff0a6', dayMix)} transparent opacity={0.84} toneMapped={false} /></mesh>
- ))}
- </group>
- );
-}
-
-export default function OpenWorldArchipelago({
- settings,
- explorationMode = false,
- apps = [],
- appPositions = null,
- agentMap = null,
- backupStatus = null,
- cosTasks = [],
- healthMetrics = null,
- productivityData = null,
- goals = null,
- character = null,
- memoryGraph = null,
- inboxDepth = 0,
- jiraTickets = [],
- jiraEnabled = true,
- introspection = null,
- voiceState = null,
- onBuildingClick,
-}) {
- const naturalDayMix = openWorldDayMix(settings);
- // Keep the village colorful through evening hours. Night is expressed by warm windows,
- // lanterns, and the sky—not by turning the entire playable ground into near-black ink.
- const dayMix = explorationMode ? Math.max(0.74, naturalDayMix) : naturalDayMix;
- const detailed = openWorldShowDetail(settings);
- const resolvedAppPositions = useMemo(
- () => appPositions || computeVillageAppLayout(apps),
- [appPositions, apps],
- );
- return (
- <group>
- {explorationMode
- ? <Island island={VILLAGE_GROUND} dayMix={dayMix} detailed={detailed} />
- : ARCHIPELAGO_ISLANDS.map((island) => <Island key={island.id} island={island} dayMix={dayMix} detailed={detailed} />)}
- {!explorationMode && <VillageCauseways dayMix={dayMix} />}
- <VillageRoutes dayMix={dayMix} detailed={detailed} />
- <VillageDressing settings={settings} dayMix={dayMix} />
- {explorationMode && (
- <>
- <VillagePortosLife
- apps={apps}
- appPositions={resolvedAppPositions}
- agentMap={agentMap}
- backupStatus={backupStatus}
- cosTasks={cosTasks}
- healthMetrics={healthMetrics}
- productivityData={productivityData}
- goals={goals}
- character={character}
- memoryGraph={memoryGraph}
- inboxDepth={inboxDepth}
- jiraTickets={jiraTickets}
- jiraEnabled={jiraEnabled}
- introspection={introspection}
- voiceState={voiceState}
- dayMix={dayMix}
- onBuildingClick={onBuildingClick}
- />
- <VillageProps dayMix={dayMix} />
- {detailed && <Fireflies dayMix={dayMix} />}
- </>
- )}
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldArtifacts.jsx b/client/src/components/openworld/OpenWorldArtifacts.jsx
deleted file mode 100644
index cbb59e3990..0000000000
--- a/client/src/components/openworld/OpenWorldArtifacts.jsx
+++ /dev/null
@@ -1,88 +0,0 @@
-import { useMemo, useRef } from 'react';
-import { useFrame } from '@react-three/fiber';
-import { PIXEL_FONT_URL, openWorldDayMix } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import OpenWorldLabel from './OpenWorldLabel';
-import { computeArtifacts, ARTIFACTS } from '../../utils/openWorldArtifacts';
-
-// OpenWorld's earned artifacts (roadmap 3.5): a "Hall of Achievements" cluster of trophies
-// that only appear once a milestone is earned (level-ups and completed-goal counts). Each
-// artifact is a dark pedestal topped by a glowing faceted emblem (an octahedron)
-// — visually distinct from the goal monuments' tower/scaffold so milestones don't read as
-// goals. The emblems shimmer in unison via a single per-frame ref mutation, gated on the
-// quality dial. Mirrors OpenWorldGoalMonuments / OpenWorldProductivityDistrict.
-function Artifact({ artifact, dayMix = 0 }) {
- const { tintStructure } = useOpenWorldPalette();
- const { color, intensity, label, position } = artifact;
- const { pedestalWidth: pw, pedestalHeight: ph, emblemSize } = ARTIFACTS;
- const emblemY = ph + emblemSize * 0.6;
-
- return (
- <group position={position}>
- {/* Pedestal base */}
- <mesh position={[0, ph / 2, 0]}>
- <cylinderGeometry args={[pw * 0.6, pw * 0.7, ph, 6]} />
- <meshStandardMaterial color={tintStructure('#0a0e16')} emissive={color} emissiveIntensity={0.12} metalness={0.7} roughness={0.4} />
- </mesh>
-
- {/* Glowing faceted emblem — the artifact itself */}
- <mesh position={[0, emblemY, 0]} rotation={[0, Math.PI / 4, 0]}>
- <octahedronGeometry args={[emblemSize, 0]} />
- <meshStandardMaterial color={color} emissive={color} emissiveIntensity={intensity} metalness={0.5} roughness={0.25} toneMapped={false} />
- </mesh>
-
- {/* A small point light makes the emblem read as a beacon at distance */}
- <pointLight position={[0, emblemY, 0]} color={color} intensity={intensity * 1.5} distance={10} />
-
- {/* Label below the pedestal */}
- <OpenWorldLabel position={[0, ph + emblemSize * 1.7, 0]} fontSize={0.5} color={color} dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={6}>
- {label}
- </OpenWorldLabel>
- </group>
- );
-}
-
-export default function OpenWorldArtifacts({ character, goals, settings }) {
- const hall = useMemo(
- () => computeArtifacts({ character, goals }),
- [character, goals],
- );
-
- // Shared shimmer driver: one ref scales emissive intensity for the whole cluster, so the
- // shimmer is a single per-frame mutation regardless of artifact count.
- const groupRef = useRef();
-
- // Honor the quality dial: drop the shimmer on the lowest preset, but keep the static glow so
- // earned artifacts stay legible.
- const animate = (settings?.particleDensity ?? 1) >= 0.5;
- const dayMix = openWorldDayMix(settings);
-
- useFrame(({ clock }) => {
- if (!animate || !groupRef.current) return;
- const pulse = (Math.sin(clock.getElapsedTime() * 1.4) + 1) / 2; // 0..1
- const scale = 1 + pulse * 0.08;
- groupRef.current.scale.set(scale, scale, scale);
- });
-
- if (!hall.hasData) return null;
-
- const { base, artifacts, total } = hall;
-
- return (
- <group>
- <group ref={groupRef}>
- {artifacts.map((artifact) => (
- <Artifact key={artifact.id} artifact={artifact} dayMix={dayMix} />
- ))}
- </group>
-
- {/* District title behind the cluster */}
- <OpenWorldLabel position={[base[0], 10, base[2] + 4]} fontSize={1.2} color="#f59e0b" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={24}>
- ACHIEVEMENTS
- </OpenWorldLabel>
- <OpenWorldLabel position={[base[0], 9, base[2] + 4]} fontSize={0.7} color="#94a3b8" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={24}>
- {`${total} EARNED`}
- </OpenWorldLabel>
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldBackupVault.jsx b/client/src/components/openworld/OpenWorldBackupVault.jsx
deleted file mode 100644
index d3ad5fc56a..0000000000
--- a/client/src/components/openworld/OpenWorldBackupVault.jsx
+++ /dev/null
@@ -1,71 +0,0 @@
-import { useMemo, useRef } from 'react';
-import { useFrame } from '@react-three/fiber';
-import { PIXEL_FONT_URL, openWorldDayMix } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import OpenWorldLabel from './OpenWorldLabel';
-import { computeBackupVault } from '../../utils/openWorldBackupVault';
-import { timeAgo } from '../../utils/formatters';
-
-// OpenWorld's backup-vault landmark (roadmap 2.3): a squat armored bunker west of
-// downtown with a glowing circular seal on its face. The seal's color tracks backup
-// health (green protected → amber aging → red stale/failed → blue while a backup
-// runs), it pulses on `backup:started/completed`, and the label shows time-since the
-// last snapshot — going red and reading "STALE" when a backup is overdue.
-export default function OpenWorldBackupVault({ backupStatus, settings }) {
- const { tintStructure } = useOpenWorldPalette();
- const vault = useMemo(() => computeBackupVault(backupStatus), [backupStatus]);
- const sealRef = useRef();
-
- // Honor the quality dial: drop the seal pulse on the lowest preset, but keep the
- // static glow so the vault's health is still legible.
- const animate = (settings?.particleDensity ?? 1) >= 0.5;
- const dayMix = openWorldDayMix(settings);
-
- useFrame(({ clock }) => {
- if (!animate || !sealRef.current) return;
- // Running backups pulse fast; an alerting (stale/failed) vault throbs urgently;
- // a healthy vault breathes slowly.
- const speed = vault.running ? 4 : vault.alerting ? 2.4 : 0.8;
- const pulse = 0.5 + ((Math.sin(clock.getElapsedTime() * speed) + 1) / 2) * 0.7;
- sealRef.current.material.emissiveIntensity = pulse * (vault.intensity + 0.3);
- });
-
- const { position, width, height, color } = vault;
- const sublabel = vault.running
- ? vault.statusLabel
- : `${vault.statusLabel} · ${timeAgo(vault.lastRun)}`;
-
- return (
- <group position={position}>
- {/* A faceted memory cairn reads as part of the landscape, while its live seal
- preserves the original backup-health contract. */}
- <mesh position={[0, height * 0.36, 0]} scale={[1, 0.82, 0.82]}>
- <dodecahedronGeometry args={[width * 0.62, 0]} />
- <meshStandardMaterial
- color={tintStructure('#263238')}
- emissive={color}
- emissiveIntensity={0.12 + vault.intensity * 0.18}
- metalness={0.2}
- roughness={0.86}
- flatShading
- />
- </mesh>
- <mesh position={[0, 0.16, 0]}>
- <cylinderGeometry args={[width * 0.76, width * 0.9, 0.32, 10]} />
- <meshStandardMaterial color={tintStructure('#344247')} emissive={color} emissiveIntensity={0.16} roughness={0.9} flatShading />
- </mesh>
- {/* Circular vault seal on the front (+Z) face — the live health indicator */}
- <mesh ref={sealRef} position={[0, height * 0.37, width * 0.52]} rotation={[Math.PI / 2, 0, 0]}>
- <cylinderGeometry args={[width * 0.28, width * 0.28, 0.12, 24]} />
- <meshStandardMaterial color={color} emissive={color} emissiveIntensity={vault.intensity} toneMapped={false} />
- </mesh>
- {/* Label + status/time-since sublabel above the vault */}
- <OpenWorldLabel position={[0, height * 0.78, 0]} fontSize={0.64} color={color} dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={18}>
- VAULT
- </OpenWorldLabel>
- <OpenWorldLabel position={[0, height * 0.69, 0]} fontSize={0.38} color="#94a3b8" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={18}>
- {sublabel}
- </OpenWorldLabel>
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldBillboards.jsx b/client/src/components/openworld/OpenWorldBillboards.jsx
deleted file mode 100644
index cf5ca4a2ed..0000000000
--- a/client/src/components/openworld/OpenWorldBillboards.jsx
+++ /dev/null
@@ -1,338 +0,0 @@
-import { useRef, useMemo, useEffect } from 'react';
-import { useFrame } from '@react-three/fiber';
-import { Text } from '@react-three/drei';
-import * as THREE from 'three';
-import { computeDistrictBounds } from '../../utils/openWorldMiniMap';
-import { PIXEL_FONT_URL } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-
-// Holographic scan line shader for billboard overlay
-const SCAN_VERT = `
- varying vec2 vUv;
- void main() {
- vUv = uv;
- gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
- }
-`;
-
-const SCAN_FRAG = `
- uniform float uTime;
- uniform vec3 uColor;
- varying vec2 vUv;
- void main() {
- // Horizontal scan lines
- float scanLine = step(0.5, fract(vUv.y * 40.0));
- float scanAlpha = scanLine * 0.04;
-
- // Moving scan beam
- float beam = smoothstep(0.0, 0.02, abs(vUv.y - fract(uTime * 0.15)));
- beam = 1.0 - beam;
- scanAlpha += beam * 0.12;
-
- // Edge vignette
- float edgeX = smoothstep(0.0, 0.05, vUv.x) * smoothstep(1.0, 0.95, vUv.x);
- float edgeY = smoothstep(0.0, 0.05, vUv.y) * smoothstep(1.0, 0.95, vUv.y);
- float edge = 1.0 - edgeX * edgeY;
- scanAlpha += edge * 0.08;
-
- gl_FragColor = vec4(uColor, scanAlpha);
- }
-`;
-
-// A single floating holographic billboard that cycles through messages
-function Billboard({ position, rotation, messages, color, width = 3.5, height = 1.8, speed = 0.08 }) {
- const groupRef = useRef();
- const borderRef = useRef();
- const textRef = useRef();
- const scanRef = useRef();
- const glowRef = useRef();
- const stateRef = useRef({ index: 0, lastSwitch: 0 });
-
- const displayText = useRef(messages[0]?.text || '');
- const displayLabel = useRef(messages[0]?.label || '');
-
- const colorVec = useMemo(() => new THREE.Color(color), [color]);
-
- // The scan-overlay shader material persists across a theme switch (no more full-scene
- // remount), so push the new accent into its uColor uniform imperatively — the inline
- // `uniforms` object isn't re-uploaded to an already-built material on re-render. The
- // other billboard surfaces use declarative `color={color}` props, which R3F reconciles.
- useEffect(() => {
- if (scanRef.current) scanRef.current.uniforms.uColor.value.copy(colorVec);
- }, [colorVec]);
-
- useFrame(({ clock }) => {
- if (!groupRef.current) return;
- const t = clock.getElapsedTime();
-
- // Gentle bob
- groupRef.current.position.y = position[1] + Math.sin(t * (0.42 + speed) + position[0]) * 0.15;
-
- // Border pulse
- if (borderRef.current) {
- borderRef.current.material.opacity = 0.15 + Math.sin(t * 1.5) * 0.08;
- }
-
- // Scan line animation
- if (scanRef.current) {
- scanRef.current.uniforms.uTime.value = t;
- }
-
- // Glow pulse
- if (glowRef.current) {
- glowRef.current.material.opacity = 0.1 + Math.sin(t * 0.8 + position[0]) * 0.05;
- }
-
- // Cycle through messages every ~6 seconds
- const state = stateRef.current;
- if (t - state.lastSwitch > 6) {
- state.index = (state.index + 1) % messages.length;
- state.lastSwitch = t;
- displayText.current = messages[state.index]?.text || '';
- displayLabel.current = messages[state.index]?.label || '';
- if (textRef.current) {
- textRef.current.text = displayText.current;
- }
- }
- });
-
- // Static frame geometry
- const borderGeom = useMemo(() => {
- const shape = new THREE.Shape();
- shape.moveTo(-width / 2, -height / 2);
- shape.lineTo(width / 2, -height / 2);
- shape.lineTo(width / 2, height / 2);
- shape.lineTo(-width / 2, height / 2);
- shape.lineTo(-width / 2, -height / 2);
-
- const hole = new THREE.Path();
- const inset = 0.08;
- hole.moveTo(-width / 2 + inset, -height / 2 + inset);
- hole.lineTo(width / 2 - inset, -height / 2 + inset);
- hole.lineTo(width / 2 - inset, height / 2 - inset);
- hole.lineTo(-width / 2 + inset, height / 2 - inset);
- hole.lineTo(-width / 2 + inset, -height / 2 + inset);
- shape.holes.push(hole);
-
- return new THREE.ShapeGeometry(shape);
- }, [width, height]);
-
- useEffect(() => () => borderGeom.dispose(), [borderGeom]);
-
- return (
- <group ref={groupRef} position={position} rotation={rotation}>
- {/* Billboard background panel (front face only) */}
- <mesh renderOrder={20}>
- <planeGeometry args={[width, height]} />
- <meshBasicMaterial color="#111a36" transparent opacity={0.94} toneMapped={false} />
- </mesh>
-
- {/* Solid back blocker to prevent mirrored text bleed-through */}
- <mesh position={[0, 0, -0.01]} renderOrder={19}>
- <planeGeometry args={[width, height]} />
- <meshBasicMaterial color="#060a18" side={THREE.BackSide} toneMapped={false} />
- </mesh>
-
- {/* Neon border frame */}
- <mesh ref={borderRef} geometry={borderGeom} position={[0, 0, 0.01]} renderOrder={21}>
- <meshBasicMaterial color={color} transparent opacity={0.7} toneMapped={false} />
- </mesh>
-
- {/* Top label */}
- <Text
- position={[0, height / 2 - 0.28, 0.02]}
- fontSize={0.18}
- color={color}
- outlineWidth="5%"
- outlineColor="#020617"
- outlineOpacity={0.9}
- anchorX="center"
- anchorY="middle"
- font={PIXEL_FONT_URL}
- maxWidth={width - 0.4}
- >
- {displayLabel.current}
- </Text>
-
- {/* Main text - cycling content */}
- <Text
- ref={textRef}
- position={[0, -0.05, 0.02]}
- fontSize={0.26}
- color="#ffffff"
- outlineWidth="6%"
- outlineColor="#020617"
- outlineOpacity={0.95}
- anchorX="center"
- anchorY="middle"
- font={PIXEL_FONT_URL}
- maxWidth={width - 0.5}
- >
- {displayText.current}
- </Text>
-
- {/* Accent line under label */}
- <mesh position={[0, height / 2 - 0.45, 0.01]} renderOrder={21}>
- <planeGeometry args={[width - 0.3, 0.025]} />
- <meshBasicMaterial color={color} transparent opacity={0.85} toneMapped={false} />
- </mesh>
-
- {/* Holographic scan line overlay */}
- <mesh position={[0, 0, 0.03]} renderOrder={22}>
- <planeGeometry args={[width, height]} />
- <shaderMaterial
- ref={scanRef}
- vertexShader={SCAN_VERT}
- fragmentShader={SCAN_FRAG}
- uniforms={{
- uTime: { value: 0 },
- uColor: { value: colorVec },
- }}
- transparent
- blending={THREE.AdditiveBlending}
- depthWrite={false}
- />
- </mesh>
-
- {/* Glow halo behind billboard */}
- <mesh ref={glowRef} position={[0, 0, -0.05]} renderOrder={18}>
- <planeGeometry args={[width + 1.5, height + 1.0]} />
- <meshBasicMaterial
- color={color}
- transparent
- opacity={0.32}
- blending={THREE.AdditiveBlending}
- depthWrite={false}
- toneMapped={false}
- />
- </mesh>
-
- {/* Support pole / projector beam */}
- <mesh position={[0, -height / 2 - 0.3, 0]}>
- <cylinderGeometry args={[0.02, 0.04, 0.6, 6]} />
- <meshBasicMaterial color={color} transparent opacity={0.2} />
- </mesh>
- </group>
- );
-}
-
-export default function OpenWorldBillboards({ positions, apps, cosStatus, reviewCounts, instances, productivityData }) {
- const { neonAccents, neonLayers } = useOpenWorldPalette();
- // Build billboard messages from real system data
- const billboardConfig = useMemo(() => {
- if (!positions || positions.size < 2) return [];
-
- const onlineApps = apps.filter(a => !a.archived && a.overallStatus === 'online');
- const stoppedApps = apps.filter(a => !a.archived && a.overallStatus === 'stopped');
- const totalActive = apps.filter(a => !a.archived).length;
- const colors = neonAccents;
- const pendingReview = reviewCounts?.total || 0;
- const alertCount = reviewCounts?.alert || 0;
- const peers = instances?.peers || [];
- const onlinePeers = peers.filter(peer => peer.status === 'online').length;
- const nodeCount = 1 + peers.length;
-
- // Find downtown bounding box for billboard placement.
- const bounds = computeDistrictBounds(positions, 'downtown', { minCount: 2 });
- if (!bounds) return [];
- const { minX, maxX, minZ, maxZ } = bounds;
- const downtownCount = [...positions.values()].filter((pos) => pos.district === 'downtown').length;
-
- const uptime = totalActive > 0
- ? `${Math.round(onlineApps.length / totalActive * 100)}%`
- : '---';
-
- const systemMessages = [
- { label: 'SYSTEM STATUS', text: `${onlineApps.length} ONLINE / ${totalActive} TOTAL` },
- { label: 'UPTIME', text: uptime },
- { label: 'COS ENGINE', text: cosStatus?.running ? 'ACTIVE' : 'STANDBY' },
- ];
-
- if (stoppedApps.length > 0) {
- systemMessages.push({
- label: 'ATTENTION',
- text: `${stoppedApps.length} SYSTEM${stoppedApps.length > 1 ? 'S' : ''} STOPPED`,
- });
- }
- if (pendingReview > 0) {
- systemMessages.push({
- label: alertCount > 0 ? 'REVIEW ALERTS' : 'REVIEW HUB',
- text: `${pendingReview} PENDING · ${alertCount} ALERT${alertCount === 1 ? '' : 'S'}`,
- });
- }
-
- const activityMessages = [
- { label: 'CITY', text: 'DIGITAL INFRASTRUCTURE' },
- { label: 'PORTOS', text: 'PERSONAL OPERATING SYSTEM' },
- { label: 'INSTANCE MESH', text: `${onlinePeers}/${nodeCount} NODES LINKED` },
- ];
-
- if (productivityData) {
- if (productivityData.todaySucceeded > 0) {
- activityMessages.push({
- label: 'TODAY',
- text: `${productivityData.todaySucceeded} TASKS COMPLETED`,
- });
- }
- }
-
- const billboards = [];
- const pad = 4;
-
- // Billboard 1 - Left side facing outward (toward viewers)
- billboards.push({
- id: 'bb-left',
- position: [minX - pad, 6, (minZ + maxZ) / 2],
- rotation: [0, -Math.PI / 2, 0],
- messages: systemMessages,
- color: colors[0],
- });
-
- // Billboard 2 - Right side facing outward (toward viewers)
- billboards.push({
- id: 'bb-right',
- position: [maxX + pad, 7.5, (minZ + maxZ) / 2],
- rotation: [0, Math.PI / 2, 0],
- messages: activityMessages,
- color: colors[1],
- });
-
- // Billboard 3 - Front facing into the city (only if enough buildings)
- if (downtownCount >= 4) {
- const frontMessages = onlineApps.slice(0, 6).map(a => ({
- label: 'ONLINE',
- text: (a.name || '').toUpperCase(),
- }));
- if (frontMessages.length > 0) {
- billboards.push({
- id: 'bb-front',
- position: [(minX + maxX) / 2, 8.5, minZ - pad - 1],
- rotation: [0, 0, 0],
- messages: frontMessages.length > 1 ? frontMessages : [{ label: 'STATUS', text: 'ALL SYSTEMS NOMINAL' }],
- color: colors[5],
- });
- }
- }
-
- return billboards;
- }, [positions, apps, cosStatus, reviewCounts, instances, productivityData, neonAccents]);
-
- // Floating system billboards belong to the cyber style. The default Vibes world
- // communicates through landmarks and focused building signals instead of turning
- // the horizon into a second dashboard.
- if (!neonLayers || billboardConfig.length === 0) return null;
-
- return (
- <group>
- {billboardConfig.map(bb => (
- <Billboard
- key={bb.id}
- position={bb.position}
- rotation={bb.rotation}
- messages={bb.messages}
- color={bb.color}
- />
- ))}
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldCelestial.jsx b/client/src/components/openworld/OpenWorldCelestial.jsx
deleted file mode 100644
index d84036b26b..0000000000
--- a/client/src/components/openworld/OpenWorldCelestial.jsx
+++ /dev/null
@@ -1,136 +0,0 @@
-import { useRef, useMemo, useEffect } from 'react';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { CITY_COLORS, getTimeOfDayPreset } from './openWorldConstants';
-
-// Orbital ring line geometry
-function OrbitalRing({ radius, tilt, color, opacity = 0.15, nightFactorRef }) {
- const points = useMemo(() => {
- const pts = [];
- const segments = 128;
- for (let i = 0; i <= segments; i++) {
- const angle = (i / segments) * Math.PI * 2;
- pts.push(new THREE.Vector3(
- Math.cos(angle) * radius,
- 0,
- Math.sin(angle) * radius
- ));
- }
- return pts;
- }, [radius]);
-
- const geometry = useMemo(() => new THREE.BufferGeometry().setFromPoints(points), [points]);
- useEffect(() => () => geometry.dispose(), [geometry]);
- const matRef = useRef();
-
- useFrame(() => {
- if (matRef.current) {
- matRef.current.opacity = opacity * nightFactorRef.current;
- }
- });
-
- return (
- <group rotation={[tilt, 0, 0]}>
- <line geometry={geometry}>
- <lineBasicMaterial ref={matRef} color={color} transparent opacity={opacity} />
- </line>
- </group>
- );
-}
-
-// Small moon/asteroid sphere
-function Moon({ position, size = 0.4, color = '#64748b', nightFactorRef }) {
- const ref = useRef();
-
- useFrame(({ clock }) => {
- if (!ref.current) return;
- ref.current.rotation.y = clock.getElapsedTime() * 0.2;
- ref.current.material.opacity = nightFactorRef.current;
- });
-
- return (
- <mesh ref={ref} position={position}>
- <sphereGeometry args={[size, 12, 12]} />
- <meshStandardMaterial
- color={color}
- emissive={color}
- emissiveIntensity={0.1}
- roughness={0.8}
- transparent
- opacity={1}
- />
- </mesh>
- );
-}
-
-export default function OpenWorldCelestial({ settings }) {
- const planetRef = useRef();
- const ringGroupRef = useRef();
- const ringMatRef = useRef();
- const nightFactorRef = useRef(1);
-
- const timeOfDay = settings?.timeOfDay ?? 'sunset';
- const skyTheme = settings?.skyTheme ?? 'cyberpunk';
- const preset = getTimeOfDayPreset(timeOfDay, skyTheme);
- const targetDaylight = preset.daylightFactor ?? 0;
-
- useFrame(({ clock }, delta) => {
- const t = clock.getElapsedTime();
- const lf = Math.min(1, delta * 3);
-
- // Lerp night factor
- const targetNight = 1 - targetDaylight;
- nightFactorRef.current += (targetNight - nightFactorRef.current) * lf;
- const nf = nightFactorRef.current;
-
- if (planetRef.current) {
- planetRef.current.rotation.y = t * 0.05;
- planetRef.current.material.opacity = nf;
- }
- if (ringGroupRef.current) {
- ringGroupRef.current.rotation.y = t * 0.01;
- }
- if (ringMatRef.current) {
- ringMatRef.current.opacity = 0.2 * nf;
- }
- });
-
- return (
- <group position={[-25, 35, -40]}>
- {/* Planet */}
- <mesh ref={planetRef}>
- <sphereGeometry args={[3, 32, 32]} />
- <meshStandardMaterial
- color={CITY_COLORS.planet}
- emissive={CITY_COLORS.planet}
- emissiveIntensity={0.2}
- roughness={0.6}
- transparent
- opacity={1}
- />
- </mesh>
-
- {/* Planet ring */}
- <group ref={ringGroupRef} rotation={[0.4, 0.2, 0]}>
- <mesh rotation={[Math.PI / 2, 0, 0]}>
- <ringGeometry args={[4.2, 5.5, 64]} />
- <meshBasicMaterial
- ref={ringMatRef}
- color={CITY_COLORS.planet}
- transparent
- opacity={0.2}
- side={THREE.DoubleSide}
- />
- </mesh>
- </group>
-
- {/* Orbital paths */}
- <OrbitalRing radius={12} tilt={0.3} color={CITY_COLORS.orbit} opacity={0.1} nightFactorRef={nightFactorRef} />
- <OrbitalRing radius={18} tilt={0.5} color={CITY_COLORS.orbit} opacity={0.07} nightFactorRef={nightFactorRef} />
-
- {/* Moons */}
- <Moon position={[10, 2, -3]} size={0.5} color="#64748b" nightFactorRef={nightFactorRef} />
- <Moon position={[-14, -1, 8]} size={0.35} color="#475569" nightFactorRef={nightFactorRef} />
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldClouds.jsx b/client/src/components/openworld/OpenWorldClouds.jsx
deleted file mode 100644
index 4da4a45518..0000000000
--- a/client/src/components/openworld/OpenWorldClouds.jsx
+++ /dev/null
@@ -1,107 +0,0 @@
-import { useLayoutEffect, useMemo, useRef } from 'react';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { mixHex, openWorldDayMix, seededRand } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-
-const CLOUD_BANK_SPAN = 620;
-const CLOUD_BANK_COPIES = [-CLOUD_BANK_SPAN, 0, CLOUD_BANK_SPAN];
-const CLOUD_DRIFT_SPEED = 0.75;
-const cloudTransform = new THREE.Object3D();
-
-function clusterCount(settings) {
- if (settings?.effectiveTier === 'low') return 4;
- if (settings?.effectiveTier === 'medium') return 7;
- if (settings?.effectiveTier === 'ultra') return 13;
- return 10;
-}
-
-function createCloudPuffs(count) {
- const rand = seededRand(7421);
- const puffs = [];
-
- for (let cluster = 0; cluster < count; cluster += 1) {
- const center = {
- x: -CLOUD_BANK_SPAN / 2 + rand() * CLOUD_BANK_SPAN,
- y: 38 + rand() * 36,
- z: -250 + rand() * 500,
- };
- const puffCount = 3 + Math.floor(rand() * 3);
- const clusterScale = 2.4 + rand() * 3.4;
-
- for (let puff = 0; puff < puffCount; puff += 1) {
- const centerPuff = puff === 0;
- const angle = rand() * Math.PI * 2;
- const spread = centerPuff ? 0 : (0.7 + rand() * 1.45) * clusterScale;
- const scale = clusterScale * (centerPuff ? 1 : 0.52 + rand() * 0.44);
- puffs.push({
- position: [
- center.x + Math.cos(angle) * spread,
- center.y + (centerPuff ? 0.8 : (rand() - 0.58) * clusterScale * 0.44),
- center.z + Math.sin(angle) * spread * 0.58,
- ],
- rotation: [rand() * 0.22, rand() * Math.PI * 2, rand() * 0.16],
- scale: [scale * (1.25 + rand() * 0.5), scale * (0.48 + rand() * 0.24), scale],
- });
- }
- }
-
- return puffs;
-}
-
-function writeCloudMatrices(mesh, puffs) {
- if (!mesh || typeof mesh.setMatrixAt !== 'function') return;
- puffs.forEach((puff, index) => {
- cloudTransform.position.set(...puff.position);
- cloudTransform.rotation.set(...puff.rotation);
- cloudTransform.scale.set(...puff.scale);
- cloudTransform.updateMatrix();
- mesh.setMatrixAt(index, cloudTransform.matrix);
- });
- mesh.instanceMatrix.needsUpdate = true;
- mesh.computeBoundingSphere?.();
-}
-
-export default function OpenWorldClouds({ settings }) {
- const { accent, lowPoly, surface } = useOpenWorldPalette();
- const driftRef = useRef();
- const meshRefs = useRef([]);
- const puffs = useMemo(() => createCloudPuffs(clusterCount(settings)), [settings?.effectiveTier]);
- const dayMix = openWorldDayMix(settings);
- const cloudColor = mixHex(mixHex('#8290a6', accent, 0.08), '#f7fbff', 0.68 + dayMix * 0.22);
-
- useLayoutEffect(() => {
- meshRefs.current.forEach((mesh) => writeCloudMatrices(mesh, puffs));
- }, [puffs]);
-
- useFrame(({ clock }) => {
- if (!driftRef.current || !lowPoly) return;
- driftRef.current.position.x = (clock.getElapsedTime() * CLOUD_DRIFT_SPEED) % CLOUD_BANK_SPAN;
- });
-
- if (!lowPoly) return null;
-
- return (
- <group ref={driftRef}>
- {CLOUD_BANK_COPIES.map((offset, index) => (
- <instancedMesh
- key={offset}
- ref={(mesh) => { meshRefs.current[index] = mesh; }}
- args={[undefined, undefined, puffs.length]}
- position={[offset, 0, 0]}
- >
- <icosahedronGeometry args={[1, 1]} />
- <meshStandardMaterial
- {...surface}
- color={cloudColor}
- roughness={1}
- metalness={0}
- transparent
- opacity={0.74}
- depthWrite={false}
- />
- </instancedMesh>
- ))}
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldClouds.test.jsx b/client/src/components/openworld/OpenWorldClouds.test.jsx
deleted file mode 100644
index 78141a8acb..0000000000
--- a/client/src/components/openworld/OpenWorldClouds.test.jsx
+++ /dev/null
@@ -1,37 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { render } from '@testing-library/react';
-
-const palette = vi.hoisted(() => ({ lowPoly: true }));
-
-vi.mock('@react-three/fiber', () => ({ useFrame: () => {} }));
-vi.mock('./OpenWorldPaletteContext', () => ({
- useOpenWorldPalette: () => ({
- accent: '#22d3ee',
- lowPoly: palette.lowPoly,
- surface: { flatShading: true },
- }),
-}));
-
-import OpenWorldClouds from './OpenWorldClouds';
-
-describe('OpenWorldClouds', () => {
- beforeEach(() => {
- palette.lowPoly = true;
- });
-
- it('renders a repeating instanced cloud bank in the bright low-poly world', () => {
- const { container } = render(<OpenWorldClouds settings={{ effectiveTier: 'high' }} />);
- expect(container.getElementsByTagName('instancedMesh')).toHaveLength(3);
- });
-
- it('keeps the cloud bank out of the cyber world', () => {
- palette.lowPoly = false;
- const { container } = render(<OpenWorldClouds settings={{ effectiveTier: 'high' }} />);
- expect(container.getElementsByTagName('instancedMesh')).toHaveLength(0);
- });
-
- it('retains a signature cloud bank on the adaptive low tier', () => {
- const { container } = render(<OpenWorldClouds settings={{ effectiveTier: 'low' }} />);
- expect(container.getElementsByTagName('instancedMesh')).toHaveLength(3);
- });
-});
diff --git a/client/src/components/openworld/OpenWorldCollectibles.jsx b/client/src/components/openworld/OpenWorldCollectibles.jsx
deleted file mode 100644
index b336778703..0000000000
--- a/client/src/components/openworld/OpenWorldCollectibles.jsx
+++ /dev/null
@@ -1,151 +0,0 @@
-import { useMemo, useRef } from 'react';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { getCollectiblesList } from '../../utils/openWorldCollectibles';
-
-function ShardMesh({ shard, animate }) {
- const meshRef = useRef();
- const coreRef = useRef();
- const ringRef = useRef();
- const outerRingRef = useRef();
- const { color, x, y, z, pulsePhase } = shard;
-
- useFrame(({ clock }) => {
- if (!meshRef.current) return;
- const t = clock.getElapsedTime();
- if (animate) {
- meshRef.current.rotation.y = t * 1.6 + pulsePhase * Math.PI;
- meshRef.current.rotation.x = Math.sin(t * 1.2 + pulsePhase) * 0.15;
- meshRef.current.position.y = y + Math.sin(t * 2.4 + pulsePhase * Math.PI * 2) * 0.22;
- if (coreRef.current) {
- coreRef.current.rotation.y = -t * 2.2;
- coreRef.current.rotation.z = Math.cos(t * 1.5) * 0.2;
- coreRef.current.position.y = meshRef.current.position.y;
- }
- if (ringRef.current) {
- ringRef.current.rotation.z = t * 0.8;
- ringRef.current.scale.setScalar(1 + Math.sin(t * 3 + pulsePhase) * 0.1);
- }
- if (outerRingRef.current) {
- outerRingRef.current.rotation.z = -t * 0.5;
- outerRingRef.current.scale.setScalar(1 + Math.cos(t * 2.5 + pulsePhase) * 0.08);
- }
- }
- });
-
- return (
- <group position={[x, 0, z]}>
- {/* Outer crystal facet */}
- <mesh ref={meshRef} position={[0, y, 0]}>
- <octahedronGeometry args={[0.55, 0]} />
- <meshStandardMaterial
- color={color}
- emissive={color}
- emissiveIntensity={1.2}
- metalness={0.85}
- roughness={0.12}
- transparent
- opacity={0.92}
- toneMapped={false}
- />
- </mesh>
-
- {/* Inner glowing white-hot core */}
- <mesh ref={coreRef} position={[0, y, 0]} scale={0.36}>
- <octahedronGeometry args={[0.55, 0]} />
- <meshBasicMaterial
- color="#ffffff"
- toneMapped={false}
- />
- </mesh>
-
- {/* Inner ground energy ring */}
- <mesh ref={ringRef} rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.04, 0]}>
- <ringGeometry args={[0.55, 0.68, 16]} />
- <meshBasicMaterial
- color={color}
- transparent
- opacity={0.4}
- blending={THREE.AdditiveBlending}
- depthWrite={false}
- side={THREE.DoubleSide}
- />
- </mesh>
-
- {/* Outer faint shimmer halo ring */}
- <mesh ref={outerRingRef} rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.035, 0]}>
- <ringGeometry args={[0.75, 0.88, 16]} />
- <meshBasicMaterial
- color={color}
- transparent
- opacity={0.18}
- blending={THREE.AdditiveBlending}
- depthWrite={false}
- side={THREE.DoubleSide}
- />
- </mesh>
- </group>
- );
-}
-
-function CollectionBurst({ burst }) {
- const groupRef = useRef();
-
- useFrame((_, delta) => {
- if (!groupRef.current) return;
- burst.age += delta;
- const progress = Math.min(1, burst.age / 0.8);
- const scale = 1 + progress * 2.8;
- groupRef.current.scale.set(scale, scale, scale);
- groupRef.current.position.y = burst.y + progress * 1.5;
- if (groupRef.current.children[0]?.material) {
- groupRef.current.children[0].material.opacity = Math.max(0, 1 - progress);
- }
- });
-
- if (burst.age >= 0.8) return null;
-
- return (
- <group ref={groupRef} position={[burst.x, burst.y, burst.z]}>
- <mesh>
- <sphereGeometry args={[0.4, 8, 8]} />
- <meshBasicMaterial
- color={burst.color || '#06b6d4'}
- transparent
- opacity={0.9}
- blending={THREE.AdditiveBlending}
- depthWrite={false}
- />
- </mesh>
- </group>
- );
-}
-
-export default function OpenWorldCollectibles({
- collectedShardIds = new Set(),
- activeBursts = [],
- settings,
- shards,
-}) {
- const resolvedShards = useMemo(() => shards || getCollectiblesList(), [shards]);
- const animate = (settings?.particleDensity ?? 1) >= 0.5;
- const visibleShards = useMemo(
- () => resolvedShards.filter((s) => !collectedShardIds.has(s.id)),
- [resolvedShards, collectedShardIds]
- );
-
- return (
- <group>
- {visibleShards.map((shard) => (
- <ShardMesh
- key={shard.id}
- shard={shard}
- animate={animate}
- />
- ))}
- {activeBursts.map((burst) => (
- <CollectionBurst key={burst.id} burst={burst} />
- ))}
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldDataHarbor.jsx b/client/src/components/openworld/OpenWorldDataHarbor.jsx
deleted file mode 100644
index c4a14205de..0000000000
--- a/client/src/components/openworld/OpenWorldDataHarbor.jsx
+++ /dev/null
@@ -1,283 +0,0 @@
-import { useMemo, useRef, useState, useCallback } from 'react';
-import { useFrame } from '@react-three/fiber';
-import { Html } from '@react-three/drei';
-import { PIXEL_FONT_URL, openWorldDayMix } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import OpenWorldLabel from './OpenWorldLabel';
-import { computeDataHarbor, DATA_HARBOR } from '../../utils/openWorldDataHarbor';
-import { WORLD, AVENUE_WIDTH } from '../../utils/openWorldPlan';
-
-// OpenWorld's Data Harbor: a pier district over the bay (master plan, north shore) that
-// renders GET /api/openworld/introspection — the database quay (one disk-stack silo per Postgres
-// table, an orbiting ring on pgvector tables, a migration obelisk) beside the archive racks
-// (one container rack per data/ domain, lit slats tracking disk usage). Clicking a silo or
-// rack opens a holographic detail card. Mirrors OpenWorldMemoryDistrict: the pure helper does
-// all topology, this component only renders + animates.
-
-const DECK_COLOR = '#10182a';
-const PYLON_COLOR = '#0a0f1c';
-const OFFLINE_COLOR = '#ef4444';
-
-// Holographic info card for a clicked silo/rack — same visual language as
-// HolographicPanel.jsx (the app-building hologram).
-function HarborHoloCard({ selected }) {
- const { kind, data } = selected;
- const accentClass = kind === 'silo' ? 'border-cyan-500/50 text-cyan-300' : 'border-violet-500/50 text-violet-300';
- return (
- <Html position={[data.x, DATA_HARBOR.deckY + data.height + 2.6, data.z]} center distanceFactor={12} style={{ pointerEvents: 'none' }}>
- <div className={`bg-black/90 border ${accentClass} rounded-md px-3 py-2 whitespace-nowrap backdrop-blur-sm`} style={{ boxShadow: '0 0 16px rgba(6,182,212,0.25)' }}>
- <div className="font-pixel tracking-wider font-bold text-[12px] max-w-[180px] truncate">{data.label}</div>
- <div className="text-[9px] font-pixel tracking-wide mt-1 space-y-0.5 text-gray-300">
- {kind === 'silo' ? (
- <>
- <div>{data.rowEstimate.toLocaleString()} rows</div>
- <div>{data.bytesLabel}</div>
- {data.hasEmbedding && <div className="text-pink-400">pgvector embeddings</div>}
- </>
- ) : (
- <>
- <div>{data.sublabel}</div>
- <div>{data.files.toLocaleString()} files</div>
- <div className="text-gray-500">data/{data.name}</div>
- </>
- )}
- </div>
- </div>
- </Html>
- );
-}
-
-// One database table: a stack of glowing disks on a dark plinth; pgvector tables carry a
-// slowly orbiting ring (rotated by the parent's single useFrame via ringRefs).
-function TableSilo({ silo, color, onSelect, registerRing, dayMix }) {
- const disks = useMemo(() => Array.from({ length: silo.diskCount }, (_, i) => i), [silo.diskCount]);
- const [hovered, setHovered] = useState(false);
- const step = DATA_HARBOR.diskHeight + DATA_HARBOR.diskGap;
- return (
- <group position={[silo.x, DATA_HARBOR.deckY, silo.z]}>
- <group
- onClick={(e) => { e.stopPropagation(); onSelect(); }}
- onPointerEnter={() => setHovered(true)}
- onPointerLeave={() => setHovered(false)}
- >
- {/* Plinth */}
- <mesh position={[0, 0.1, 0]}>
- <cylinderGeometry args={[silo.diskRadius + 0.25, silo.diskRadius + 0.35, 0.2, 16]} />
- <meshStandardMaterial color={PYLON_COLOR} roughness={0.8} />
- </mesh>
- {disks.map((i) => (
- <mesh key={i} position={[0, 0.2 + step * i + DATA_HARBOR.diskHeight / 2, 0]}>
- <cylinderGeometry args={[silo.diskRadius, silo.diskRadius, DATA_HARBOR.diskHeight, 20]} />
- <meshStandardMaterial
- color={color}
- emissive={color}
- // The top disk reads as the silo's "live" surface; lower disks dim slightly.
- emissiveIntensity={(i === silo.diskCount - 1 ? 0.55 : 0.28) + (hovered ? 0.3 : 0)}
- metalness={0.4}
- roughness={0.3}
- toneMapped={false}
- />
- </mesh>
- ))}
- </group>
- {silo.hasEmbedding && (
- <mesh ref={registerRing} position={[0, 0.2 + step * silo.diskCount + 0.35, 0]} rotation={[Math.PI / 2.6, 0, 0]}>
- <torusGeometry args={[silo.diskRadius + 0.45, 0.05, 8, 32]} />
- <meshBasicMaterial color={color} transparent opacity={0.7} toneMapped={false} />
- </mesh>
- )}
- <OpenWorldLabel position={[0, silo.height + 1.5, 0]} fontSize={0.42} color={color} dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={7}>
- {silo.label}
- </OpenWorldLabel>
- <OpenWorldLabel position={[0, silo.height + 1.05, 0]} fontSize={0.3} color="#94a3b8" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={7}>
- {silo.sublabel}
- </OpenWorldLabel>
- </group>
- );
-}
-
-// One data/ domain: a container rack whose lit slat count tracks its share of disk usage.
-function DomainRack({ rack, accent, tintStructure, onSelect, dayMix }) {
- const [hovered, setHovered] = useState(false);
- const slats = useMemo(() => Array.from({ length: DATA_HARBOR.rackSlats }, (_, i) => i), []);
- const slatStep = (rack.height - 0.6) / DATA_HARBOR.rackSlats;
- return (
- <group position={[rack.x, DATA_HARBOR.deckY, rack.z]}>
- <group
- onClick={(e) => { e.stopPropagation(); onSelect(); }}
- onPointerEnter={() => setHovered(true)}
- onPointerLeave={() => setHovered(false)}
- >
- <mesh position={[0, rack.height / 2, 0]}>
- <boxGeometry args={[rack.width, rack.height, rack.depth]} />
- <meshStandardMaterial color={tintStructure(DECK_COLOR)} roughness={0.6} metalness={0.3} />
- </mesh>
- {/* Slat rows on the front (bay-facing) face — lit bottom-up by fill ratio. */}
- {slats.map((i) => {
- const lit = i < rack.litSlats;
- return (
- <mesh key={i} position={[0, 0.45 + i * slatStep, rack.depth / 2 + 0.02]}>
- <boxGeometry args={[rack.width - 0.5, slatStep * 0.45, 0.05]} />
- <meshStandardMaterial
- color={lit ? accent : '#1f2937'}
- emissive={lit ? accent : '#000000'}
- emissiveIntensity={lit ? 0.6 + (hovered ? 0.3 : 0) : 0}
- toneMapped={false}
- />
- </mesh>
- );
- })}
- </group>
- <OpenWorldLabel position={[0, rack.height + 1.2, 0]} fontSize={0.42} color={accent} dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={7}>
- {rack.label}
- </OpenWorldLabel>
- <OpenWorldLabel position={[0, rack.height + 0.75, 0]} fontSize={0.3} color="#94a3b8" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={7}>
- {rack.sublabel}
- </OpenWorldLabel>
- </group>
- );
-}
-
-// A pier deck on pylons over the water.
-function PierDeck({ x, z, width, depth, tintStructure }) {
- const pylons = useMemo(() => {
- const out = [];
- const halfW = width / 2 - 0.6;
- const halfD = depth / 2 - 0.6;
- for (const px of [-halfW, halfW]) {
- for (const pz of [-halfD, halfD]) out.push([x + px, pz + z]);
- }
- return out;
- }, [x, z, width, depth]);
- return (
- <group>
- <mesh position={[x, DATA_HARBOR.deckY - 0.15, z]}>
- <boxGeometry args={[width, 0.3, depth]} />
- <meshStandardMaterial color={tintStructure(DECK_COLOR)} roughness={0.7} metalness={0.25} />
- </mesh>
- {pylons.map(([px, pz], i) => (
- <mesh key={i} position={[px, WORLD.waterY - 0.8, pz]}>
- <cylinderGeometry args={[0.28, 0.34, 3, 8]} />
- <meshStandardMaterial color={PYLON_COLOR} roughness={0.9} />
- </mesh>
- ))}
- </group>
- );
-}
-
-export default function OpenWorldDataHarbor({ introspection, settings }) {
- const { accent, tintStructure, getAccentColor } = useOpenWorldPalette();
- const district = useMemo(() => computeDataHarbor(introspection), [introspection]);
- const [selected, setSelected] = useState(null);
- const dayMix = openWorldDayMix(settings);
- const animate = (settings?.particleDensity ?? 1) >= 0.5;
-
- // All pgvector rings spin from one frame callback (single mutation site). Keyed by
- // silo name (set on mount, cleared on unmount) so a re-render that doesn't remount
- // the silos can't strand the registry empty.
- const ringRefs = useRef(new Map());
- const makeRingRef = useCallback((name) => (el) => {
- if (el) ringRefs.current.set(name, el);
- else ringRefs.current.delete(name);
- }, []);
- const offlineRef = useRef();
-
- useFrame(({ clock }) => {
- const t = clock.getElapsedTime();
- if (animate) {
- for (const ring of ringRefs.current.values()) ring.rotation.z = t * 0.6;
- }
- if (offlineRef.current) {
- offlineRef.current.material.emissiveIntensity = 0.5 + ((Math.sin(t * 2.2) + 1) / 2) * 0.6;
- }
- });
-
- if (district.empty) return null;
-
- const [bx, , bz] = district.base;
- const { silos, racks, decks, obelisk, totals, overflow, dbDown } = district;
- const select = (kind, data) => setSelected((prev) =>
- prev && prev.kind === kind && prev.data.name === data.name ? null : { kind, data });
-
- return (
- <group>
- {/* Gangway from the shoreline avenue out to the pier head — same width as the
- avenue it continues, so the shoreline joint stays seamless. */}
- <PierDeck x={bx} z={(WORLD.shorelineZ + bz) / 2} width={AVENUE_WIDTH} depth={Math.abs(bz - WORLD.shorelineZ) + 2} tintStructure={tintStructure} />
- {/* West quay (database silos) + east yard (archive racks) — sized by the helper
- to contain whatever stands on them. */}
- {decks.map((deck, i) => (
- <PierDeck key={i} x={deck.x} z={deck.z} width={deck.w} depth={deck.d} tintStructure={tintStructure} />
- ))}
-
- {silos.map((silo) => (
- <TableSilo
- key={silo.name}
- silo={silo}
- color={getAccentColor({ name: silo.name })}
- onSelect={() => select('silo', silo)}
- registerRing={silo.hasEmbedding ? makeRingRef(silo.name) : undefined}
- dayMix={dayMix}
- />
- ))}
-
- {/* DB offline: the quay keeps its deck but flies a pulsing red beacon. */}
- {dbDown && (
- <group position={[decks[0].x, DATA_HARBOR.deckY, decks[0].z]}>
- <mesh ref={offlineRef} position={[0, 1.6, 0]}>
- <octahedronGeometry args={[0.9, 0]} />
- <meshStandardMaterial color={OFFLINE_COLOR} emissive={OFFLINE_COLOR} emissiveIntensity={0.8} toneMapped={false} />
- </mesh>
- <OpenWorldLabel position={[0, 3.4, 0]} fontSize={0.7} color={OFFLINE_COLOR} dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={10}>
- DB OFFLINE
- </OpenWorldLabel>
- </group>
- )}
-
- {racks.map((rack) => (
- <DomainRack
- key={rack.name}
- rack={rack}
- accent={accent}
- tintStructure={tintStructure}
- onSelect={() => select('rack', rack)}
- dayMix={dayMix}
- />
- ))}
-
- {/* Migration obelisk at the pier head. */}
- {obelisk && (
- <group position={[obelisk.x, DATA_HARBOR.deckY, obelisk.z]}>
- <mesh position={[0, 1.8, 0]}>
- <boxGeometry args={[0.7, 3.6, 0.7]} />
- <meshStandardMaterial color={tintStructure('#16213a')} emissive={accent} emissiveIntensity={0.18} roughness={0.4} toneMapped={false} />
- </mesh>
- <mesh position={[0, 3.85, 0]}>
- <octahedronGeometry args={[0.45, 0]} />
- <meshStandardMaterial color={accent} emissive={accent} emissiveIntensity={0.7} toneMapped={false} />
- </mesh>
- <OpenWorldLabel position={[0, 5, 0]} fontSize={0.42} color={accent} dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={8}>
- {`${obelisk.applied} MIGRATIONS`}
- </OpenWorldLabel>
- </group>
- )}
-
- {/* District title + totals, tall enough to read from the shore. */}
- <OpenWorldLabel position={[bx, 11, bz - 2]} fontSize={1.4} color={accent} dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={30}>
- DATA HARBOR
- </OpenWorldLabel>
- <OpenWorldLabel position={[bx, 9.9, bz - 2]} fontSize={0.7} color="#94a3b8" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={34}>
- {dbDown
- ? (totals.fsLabel ? `FILES ${totals.fsLabel}` : 'NO DATA')
- : `${totals.tableCount} TABLES${totals.dbSizeLabel ? ` ${totals.dbSizeLabel}` : ''}${totals.fsLabel ? ` • FILES ${totals.fsLabel}` : ''}`}
- </OpenWorldLabel>
- {(overflow.tables > 0 || overflow.domains > 0) && (
- <OpenWorldLabel position={[bx, 9.1, bz - 2]} fontSize={0.45} color="#64748b" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={30}>
- {`+${overflow.tables + overflow.domains} MORE`}
- </OpenWorldLabel>
- )}
-
- {selected && <HarborHoloCard selected={selected} />}
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldDataRain.jsx b/client/src/components/openworld/OpenWorldDataRain.jsx
deleted file mode 100644
index 9f0a41e140..0000000000
--- a/client/src/components/openworld/OpenWorldDataRain.jsx
+++ /dev/null
@@ -1,141 +0,0 @@
-import { useRef, useMemo } from 'react';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { seededRand } from './openWorldConstants';
-
-// Matrix-style cascading data columns falling through the sky
-
-const DATA_RAIN_VERT = `
- attribute float charIndex;
- attribute float columnPhase;
- attribute float speed;
- attribute float brightness;
- uniform float uTime;
- varying float vBrightness;
- varying float vFade;
-
- void main() {
- vec3 pos = position;
-
- // Each character falls independently within its column
- float t = mod(uTime * speed + columnPhase + charIndex * 0.05, 1.0);
- pos.y = mix(30.0, -5.0, t);
-
- // Head of the column is brightest, tail fades
- float headDist = t;
- vBrightness = brightness * smoothstep(0.0, 0.05, t) * smoothstep(1.0, 0.3, t);
-
- // Atmospheric fade with distance
- vec4 mvPosition = modelViewMatrix * vec4(pos, 1.0);
- vFade = smoothstep(-80.0, -20.0, mvPosition.z);
-
- gl_PointSize = (1.8 + brightness * 1.2) * (120.0 / -mvPosition.z);
- gl_Position = projectionMatrix * mvPosition;
- }
-`;
-
-const DATA_RAIN_FRAG = `
- varying float vBrightness;
- varying float vFade;
- uniform vec3 uColor;
-
- void main() {
- vec2 uv = gl_PointCoord - vec2(0.5);
- float d = length(uv);
- if (d > 0.5) discard;
-
- // Sharp rectangular glyph shape
- float rect = step(abs(uv.x), 0.35) * step(abs(uv.y), 0.4);
- float alpha = rect * vBrightness * vFade * 0.6;
-
- // Bright center, colored edges
- vec3 color = mix(uColor, vec3(1.0), vBrightness * 0.3);
- gl_FragColor = vec4(color, alpha);
- }
-`;
-
-export default function OpenWorldDataRain({ settings }) {
- const pointsRef = useRef();
- const matRef = useRef();
- // Follow OpenWorldParticles' quality-dial pattern: scale column count down under the
- // adaptive-quality low tier instead of paying for a fixed 480-point system always.
- const density = settings?.particleDensity ?? 1;
-
- const { positions, charIndices, columnPhases, speeds, brightnesses, count } = useMemo(() => {
- const columns = Math.max(4, Math.round(40 * density));
- const charsPerColumn = 12;
- const total = columns * charsPerColumn;
-
- const pos = new Float32Array(total * 3);
- const chars = new Float32Array(total);
- const phases = new Float32Array(total);
- const spd = new Float32Array(total);
- const bright = new Float32Array(total);
-
- // Seeded random
- const rand = seededRand(77);
-
- for (let col = 0; col < columns; col++) {
- const x = (rand() - 0.5) * 70;
- const z = (rand() - 0.5) * 70;
- const colPhase = rand();
- const colSpeed = 0.15 + rand() * 0.25;
-
- for (let ch = 0; ch < charsPerColumn; ch++) {
- const idx = col * charsPerColumn + ch;
- pos[idx * 3] = x + (rand() - 0.5) * 0.3;
- pos[idx * 3 + 1] = 0; // Will be animated in shader
- pos[idx * 3 + 2] = z + (rand() - 0.5) * 0.3;
-
- chars[idx] = ch / charsPerColumn;
- phases[idx] = colPhase;
- spd[idx] = colSpeed;
- // Head chars are brightest, tail dims out
- bright[idx] = 1.0 - (ch / charsPerColumn) * 0.7;
- }
- }
-
- return {
- positions: pos,
- charIndices: chars,
- columnPhases: phases,
- speeds: spd,
- brightnesses: bright,
- count: total,
- };
- }, [density]);
-
- useFrame(({ clock }) => {
- if (matRef.current) {
- matRef.current.uniforms.uTime.value = clock.getElapsedTime();
- }
- });
-
- return (
- <points ref={pointsRef}>
- {/* key remounts the geometry when density changes — three.js cannot resize
- a live BufferAttribute in place, and the warm-up clamp restores density
- ~1.2s after every mount. */}
- <bufferGeometry key={count}>
- <bufferAttribute attach="attributes-position" count={count} array={positions} itemSize={3} />
- <bufferAttribute attach="attributes-charIndex" count={count} array={charIndices} itemSize={1} />
- <bufferAttribute attach="attributes-columnPhase" count={count} array={columnPhases} itemSize={1} />
- <bufferAttribute attach="attributes-speed" count={count} array={speeds} itemSize={1} />
- <bufferAttribute attach="attributes-brightness" count={count} array={brightnesses} itemSize={1} />
- </bufferGeometry>
- <shaderMaterial
- ref={matRef}
- vertexShader={DATA_RAIN_VERT}
- fragmentShader={DATA_RAIN_FRAG}
- uniforms={{
- uTime: { value: 0 },
- uColor: { value: new THREE.Color('#06b6d4') },
- }}
- transparent
- blending={THREE.AdditiveBlending}
- depthWrite={false}
- fog={false}
- />
- </points>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldDataStreams.jsx b/client/src/components/openworld/OpenWorldDataStreams.jsx
deleted file mode 100644
index f57f025743..0000000000
--- a/client/src/components/openworld/OpenWorldDataStreams.jsx
+++ /dev/null
@@ -1,110 +0,0 @@
-import { useRef, useMemo, useEffect } from 'react';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { computeFlowConnections } from '../../utils/openWorldFlowLines';
-
-// A single animated data packet traveling along a path
-function DataPacket({ start, end, color, speed, offset, size = 0.08 }) {
- const meshRef = useRef();
- const trailRef = useRef();
-
- const direction = useMemo(() => {
- const dir = new THREE.Vector3(end[0] - start[0], end[1] - start[1], end[2] - start[2]);
- return dir;
- }, [start, end]);
-
- const trailGeom = useMemo(() => {
- const curve = new THREE.LineCurve3(
- new THREE.Vector3(start[0], start[1], start[2]),
- new THREE.Vector3(end[0], end[1], end[2])
- );
- return new THREE.BufferGeometry().setFromPoints(curve.getPoints(20));
- }, [start, end]);
-
- // Dispose the connection-line geometry's GPU buffers when the endpoints change
- // (topology shifts as buildings go on/offline) or on unmount.
- useEffect(() => () => trailGeom.dispose(), [trailGeom]);
-
- useFrame(({ clock }) => {
- if (!meshRef.current) return;
- const t = ((clock.getElapsedTime() * speed + offset) % 1.0);
-
- meshRef.current.position.set(
- start[0] + direction.x * t,
- start[1] + direction.y * t + Math.sin(t * Math.PI) * 0.5,
- start[2] + direction.z * t
- );
-
- // Pulse the packet
- const pulse = 0.6 + Math.sin(clock.getElapsedTime() * 8) * 0.4;
- meshRef.current.material.opacity = pulse * (t > 0.05 && t < 0.95 ? 1 : 0);
-
- // Trail opacity pulse
- if (trailRef.current) {
- trailRef.current.material.opacity = 0.08 + Math.sin(clock.getElapsedTime() * 2 + offset) * 0.04;
- }
- });
-
- return (
- <>
- {/* Faint connection line */}
- <line geometry={trailGeom} ref={trailRef}>
- <lineBasicMaterial color={color} transparent opacity={0.08} />
- </line>
- {/* Flying data packet */}
- <mesh ref={meshRef}>
- <sphereGeometry args={[size, 6, 6]} />
- <meshBasicMaterial color={color} transparent opacity={0.8} />
- </mesh>
- </>
- );
-}
-
-export default function OpenWorldDataStreams({ positions, apps, agentMap }) {
- // Derive the real operational state the flow topology is built from: which
- // buildings are online (flow sources) and which currently have running agents
- // (hot links). The pure helper turns that into the connection set so this
- // component stays presentation-only.
- const connections = useMemo(() => {
- const activeIds = new Set(
- (apps || []).filter(a => !a.archived && a.overallStatus === 'online').map(a => a.id)
- );
- const agentIds = new Set();
- agentMap?.forEach((entry, id) => {
- if (entry?.agents?.length) agentIds.add(id);
- });
- return computeFlowConnections({ positions, activeIds, agentIds });
- }, [positions, apps, agentMap]);
-
- if (connections.length === 0) return null;
-
- return (
- <group>
- {connections.map((conn) => (
- <group key={conn.key}>
- {/* Packets travel both directions; a hotter link carries more of them. */}
- {Array.from({ length: conn.packets }).map((_, k) => (
- <DataPacket
- key={`fwd-${k}`}
- start={conn.start}
- end={conn.end}
- color={conn.color}
- speed={conn.speed}
- offset={k / conn.packets}
- />
- ))}
- {Array.from({ length: conn.packets }).map((_, k) => (
- <DataPacket
- key={`rev-${k}`}
- start={conn.end}
- end={conn.start}
- color={conn.color}
- speed={conn.speed}
- offset={k / conn.packets + 0.5}
- />
- ))}
- </group>
- ))}
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldDepthOfField.jsx b/client/src/components/openworld/OpenWorldDepthOfField.jsx
deleted file mode 100644
index 0d78c0ea6d..0000000000
--- a/client/src/components/openworld/OpenWorldDepthOfField.jsx
+++ /dev/null
@@ -1,98 +0,0 @@
-import { useEffect, useMemo } from 'react';
-import { useThree, useFrame } from '@react-three/fiber';
-import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
-import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
-import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
-import { BokehPass } from 'three/addons/postprocessing/BokehPass.js';
-import { getDofParams } from '../../utils/openWorldPhotoMode';
-
-// Depth-of-field postprocessing for photo mode (roadmap 3.3). OpenWorld ships NO postprocessing
-// library — the city's "bloom" is hand-tuned emissive/additive materials, not a composer pass —
-// so DoF is the first composited effect. Rather than add a new npm dependency
-// (`@react-three/postprocessing`) or hand-roll a circle-of-confusion shader, this uses the
-// BokehPass + EffectComposer that already ship inside three's addons (`three/addons/*`), so it
-// adds depth-of-field with zero new packages.
-//
-// This component is mounted ONLY while photo mode is active (see OpenWorldScene), so the live dashboard
-// frameloop never pays for the extra render targets. While mounted it takes over the render loop
-// via a positive-priority useFrame (React Three Fiber then skips its own auto-render) and drives
-// the scene through a RenderPass → BokehPass → OutputPass chain. The focal plane is derived per
-// framing preset (`getDofParams`) so whatever the shot is pointed at stays sharp while nearer and
-// farther geometry falls off softly.
-//
-// `enabled` toggles only the BokehPass — the composer keeps driving the frame either way (with the
-// pass off the image matches the plain RenderPass → OutputPass output), so flipping DoF on/off in
-// photo mode never churns the render-loop ownership or strands a frozen demand-mode frame.
-export default function OpenWorldDepthOfField({ presetId, enabled = true, composerRef }) {
- const { gl, scene, camera, size, invalidate } = useThree();
-
- // Build the composer + passes once. BokehPass reads camera.near/far/aspect each render, so the
- // camera-fly mutating the shared camera needs no extra wiring here.
- const { composer, bokehPass } = useMemo(() => {
- const comp = new EffectComposer(gl);
- comp.addPass(new RenderPass(scene, camera));
- const params = getDofParams(presetId);
- const bokeh = new BokehPass(scene, camera, {
- focus: params.focus,
- aperture: params.aperture,
- maxblur: params.maxblur,
- });
- comp.addPass(bokeh);
- // OutputPass applies tone mapping + sRGB conversion so the composited frame matches the
- // renderer's normal output (RenderPass writes a linear HDR buffer; without this the postcard
- // would look dark/washed compared to the live view).
- comp.addPass(new OutputPass());
- return { composer: comp, bokehPass: bokeh };
- // gl/scene/camera are stable for the lifetime of this mount; presetId is applied via the
- // effect below so changing it doesn't rebuild the whole composer.
- }, [gl, scene, camera]);
-
- // Expose the composer so the capture path (OpenWorldPhotoCamera) renders the DoF frame too, instead
- // of bypassing it with a plain gl.render. Cleared on unmount so capture falls back to direct
- // rendering the moment photo mode (and this component) goes away.
- useEffect(() => {
- if (!composerRef) return undefined;
- composerRef.current = composer;
- return () => {
- if (composerRef.current === composer) composerRef.current = null;
- };
- }, [composer, composerRef]);
-
- // Keep the composer sized to the canvas (and at the renderer's pixel ratio) on resize.
- useEffect(() => {
- composer.setPixelRatio(gl.getPixelRatio());
- composer.setSize(size.width, size.height);
- invalidate();
- }, [composer, gl, size.width, size.height, invalidate]);
-
- // Re-tune the focal plane + blur when the framing preset changes, and toggle the bokeh pass.
- // invalidate() pumps the demand-mode loop so the change shows immediately on a frozen scene.
- useEffect(() => {
- const params = getDofParams(presetId);
- bokehPass.uniforms.focus.value = params.focus;
- bokehPass.uniforms.aperture.value = params.aperture;
- bokehPass.uniforms.maxblur.value = params.maxblur;
- bokehPass.enabled = enabled;
- invalidate();
- }, [bokehPass, presetId, enabled, invalidate]);
-
- // Free GPU resources when photo mode exits. EffectComposer.dispose() only frees the composer's
- // own read/write targets + internal copy pass — NOT the passes you added — so dispose each pass
- // (BokehPass owns a depth render target + materials + a full-screen quad; OutputPass owns a
- // material + quad) before disposing the composer. The Canvas key-remount tears the WebGL context
- // down on exit too, but disposing explicitly keeps this correct if that remount ever changes.
- useEffect(() => () => {
- for (const pass of composer.passes) pass.dispose?.();
- composer.dispose();
- }, [composer]);
-
- // Positive priority makes R3F hand the render loop to us: drive the scene through the composer
- // instead of the default renderer. In photo mode's frameloop="demand" this runs only when
- // something invalidates (the camera-fly, a resize, a preset/toggle change), so the scene still
- // freezes for a clean still once the fly settles.
- useFrame(() => {
- composer.render();
- }, 1);
-
- return null;
-}
diff --git a/client/src/components/openworld/OpenWorldEasterEggs.jsx b/client/src/components/openworld/OpenWorldEasterEggs.jsx
deleted file mode 100644
index 1ff706237e..0000000000
--- a/client/src/components/openworld/OpenWorldEasterEggs.jsx
+++ /dev/null
@@ -1,82 +0,0 @@
-import { useMemo, useRef } from 'react';
-import { useFrame } from '@react-three/fiber';
-import { useTimeTick } from '../../hooks/useTimeTick';
-import { PIXEL_FONT_URL, openWorldDayMix } from './openWorldConstants';
-import OpenWorldLabel from './OpenWorldLabel';
-import { computeEasterEggs, EGGS } from '../../utils/openWorldEasterEggs';
-
-// OpenWorld's easter eggs (roadmap 3.5 follow-up, #824): rare, hidden emblems that only appear
-// when a special condition is met (a developer's date, a "leet" level, or a clean-sweep goal
-// board). Tucked in a quiet far corner so they read as a discovery, not a
-// featured district. Each egg is a small glowing icosahedron with a tiny glyph label; they bob
-// (each on its own phase offset) gated on the quality dial (mirrors OpenWorldArtifacts).
-function Egg({ egg, animate, dayMix = 0 }) {
- const { color, label, hint, position, phase } = egg;
- const s = EGGS.size;
- const ref = useRef();
-
- // Per-egg twinkle/bob, offset by the descriptor's stable phase so eggs don't pulse in lockstep.
- useFrame(({ clock }) => {
- if (!animate || !ref.current) return;
- const t = clock.getElapsedTime();
- const pulse = (Math.sin(t * 2 + phase * Math.PI * 2) + 1) / 2; // 0..1, faster = twinkly
- ref.current.position.y = pulse * 0.4;
- ref.current.rotation.y = t * 0.3;
- });
-
- return (
- <group position={position}>
- <group ref={ref}>
- <mesh rotation={[0, Math.PI / 6, 0]}>
- <icosahedronGeometry args={[s, 0]} />
- <meshStandardMaterial color={color} emissive={color} emissiveIntensity={0.9} metalness={0.6} roughness={0.2} toneMapped={false} />
- </mesh>
-
- <pointLight color={color} intensity={1.1} distance={8} />
-
- {/* Tiny glyph so the egg hints at what it is without spelling it out. */}
- <OpenWorldLabel position={[0, s + 0.5, 0]} fontSize={0.45} color={color} dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={6}>
- {label}
- </OpenWorldLabel>
-
- {/* A muted hint sits below the glyph — the discovery payoff up close, kept small and dim
- so eggs still read as "hidden" from across the city. */}
- <OpenWorldLabel position={[0, s - 0.4, 0]} fontSize={0.28} color="#64748b" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={8}>
- {hint}
- </OpenWorldLabel>
- </group>
- </group>
- );
-}
-
-export default function OpenWorldEasterEggs({ date, character, goals, settings }) {
- // Re-resolve unlocked eggs as real time advances so calendar eggs (e.g. April 1) turn over at the
- // day boundary while OpenWorld stays open — an hourly tick is plenty and battery-friendly (shared
- // singleton timer, paused while hidden). An explicit `date` prop still wins for callers/tests.
- const tick = useTimeTick(3600000);
- const cluster = useMemo(
- () => computeEasterEggs({ date: date ?? new Date(tick), character, goals }),
- [date, tick, character, goals],
- );
-
- // Honor the quality dial: drop the bob on the lowest preset, keep the static glow.
- const animate = (settings?.particleDensity ?? 1) >= 0.5;
- const dayMix = openWorldDayMix(settings);
-
- if (!cluster.hasData) return null;
-
- const { base, eggs } = cluster;
-
- return (
- <group>
- {eggs.map((egg) => (
- <Egg key={egg.id} egg={egg} animate={animate} dayMix={dayMix} />
- ))}
-
- {/* A faint marker so a found cluster has a label, kept small to preserve the "hidden" feel. */}
- <OpenWorldLabel position={[base[0], 6, base[2]]} fontSize={0.7} color="#64748b" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={20}>
- :)
- </OpenWorldLabel>
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldEmbers.jsx b/client/src/components/openworld/OpenWorldEmbers.jsx
deleted file mode 100644
index a10ad5e3e8..0000000000
--- a/client/src/components/openworld/OpenWorldEmbers.jsx
+++ /dev/null
@@ -1,134 +0,0 @@
-import { useRef, useMemo } from 'react';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { seededRand } from './openWorldConstants';
-
-// Rising ember/spark particles that float upward from the city streets
-
-const EMBER_VERT = `
- attribute float size;
- attribute float speed;
- attribute float phase;
- attribute vec3 emberColor;
- uniform float uTime;
- varying vec3 vColor;
- varying float vAlpha;
-
- void main() {
- vColor = emberColor;
- vec3 pos = position;
-
- // Rise upward with drift
- float t = mod(uTime * speed + phase, 1.0);
- pos.y = mix(-1.0, 18.0, t);
- pos.x += sin(uTime * 0.5 + phase * 6.28) * 1.5 * t;
- pos.z += cos(uTime * 0.4 + phase * 3.14) * 1.0 * t;
-
- // Fade in at bottom, fade out at top
- vAlpha = smoothstep(0.0, 0.1, t) * smoothstep(1.0, 0.6, t);
-
- vec4 mvPosition = modelViewMatrix * vec4(pos, 1.0);
- gl_PointSize = size * (100.0 / -mvPosition.z);
- gl_Position = projectionMatrix * mvPosition;
- }
-`;
-
-const EMBER_FRAG = `
- varying vec3 vColor;
- varying float vAlpha;
-
- void main() {
- float d = length(gl_PointCoord - vec2(0.5));
- if (d > 0.5) discard;
-
- // Bright core, soft edge
- float core = smoothstep(0.5, 0.0, d);
- float alpha = core * vAlpha * 0.7;
-
- // Hot white center
- vec3 color = mix(vColor, vec3(1.0, 0.95, 0.9), core * 0.4);
-
- gl_FragColor = vec4(color, alpha);
- }
-`;
-
-export default function OpenWorldEmbers({ settings }) {
- const pointsRef = useRef();
- const matRef = useRef();
- // Follow OpenWorldParticles' quality-dial pattern: scale ember count down under the
- // adaptive-quality low tier instead of paying for a fixed 120-point system always.
- const density = settings?.particleDensity ?? 1;
-
- const { positions, sizes, speeds, phases, colors, count } = useMemo(() => {
- const n = Math.max(8, Math.round(120 * density));
- const pos = new Float32Array(n * 3);
- const sz = new Float32Array(n);
- const spd = new Float32Array(n);
- const ph = new Float32Array(n);
- const col = new Float32Array(n * 3);
-
- const palette = [
- [1.0, 0.6, 0.1], // orange
- [1.0, 0.3, 0.1], // red-orange
- [0.0, 0.7, 0.8], // cyan
- [0.9, 0.4, 0.9], // pink
- [0.4, 0.3, 1.0], // blue
- ];
-
- // Seeded, like OpenWorldDataRain: `density` is clamped for the first 1.2s of
- // every mount and every visibility resume, so this memo re-runs on a
- // boundary the user is looking at. Bare Math.random() re-draws every
- // position and color there — the whole ember field teleports rather than
- // just changing count. A fixed seed keeps the first `n` embers identical
- // across that transition.
- const rand = seededRand(41);
-
- for (let i = 0; i < n; i++) {
- // Spread across the city area
- pos[i * 3] = (rand() - 0.5) * 50;
- pos[i * 3 + 1] = 0; // Animated in shader
- pos[i * 3 + 2] = (rand() - 0.5) * 50;
-
- sz[i] = 0.8 + rand() * 1.5;
- spd[i] = 0.03 + rand() * 0.06;
- ph[i] = rand();
-
- const c = palette[Math.floor(rand() * palette.length)];
- col[i * 3] = c[0];
- col[i * 3 + 1] = c[1];
- col[i * 3 + 2] = c[2];
- }
-
- return { positions: pos, sizes: sz, speeds: spd, phases: ph, colors: col, count: n };
- }, [density]);
-
- useFrame(({ clock }) => {
- if (matRef.current) {
- matRef.current.uniforms.uTime.value = clock.getElapsedTime();
- }
- });
-
- return (
- <points ref={pointsRef}>
- {/* key remounts the geometry when density changes — three.js cannot resize
- a live BufferAttribute in place, and the warm-up clamp restores density
- ~1.2s after every mount. */}
- <bufferGeometry key={count}>
- <bufferAttribute attach="attributes-position" count={count} array={positions} itemSize={3} />
- <bufferAttribute attach="attributes-size" count={count} array={sizes} itemSize={1} />
- <bufferAttribute attach="attributes-speed" count={count} array={speeds} itemSize={1} />
- <bufferAttribute attach="attributes-phase" count={count} array={phases} itemSize={1} />
- <bufferAttribute attach="attributes-emberColor" count={count} array={colors} itemSize={3} />
- </bufferGeometry>
- <shaderMaterial
- ref={matRef}
- vertexShader={EMBER_VERT}
- fragmentShader={EMBER_FRAG}
- uniforms={{ uTime: { value: 0 } }}
- transparent
- blending={THREE.AdditiveBlending}
- depthWrite={false}
- />
- </points>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldEnergyOverlay.jsx b/client/src/components/openworld/OpenWorldEnergyOverlay.jsx
deleted file mode 100644
index b0c7ac5ce6..0000000000
--- a/client/src/components/openworld/OpenWorldEnergyOverlay.jsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { useRef } from 'react';
-import { useFrame } from '@react-three/fiber';
-import { computeChronotypeEnergy } from '../../utils/openWorldChronotype';
-
-// OpenWorld's chronotype energy overlay (roadmap 3.1): a subtle ambient atmosphere
-// that brightens and warms the city during the user's peak focus hours and dims it
-// during wind-down and recovery hours. It does NOT replace the scene lighting
-// (OpenWorldLights) — it composes on top with a single gentle, energy-tinted ambient
-// light so the user's circadian rhythm reads as the city's mood. No label; it's
-// pure ambiance.
-//
-// The pure helper (openWorldChronotype.js) takes the hour as a parameter for testability;
-// the live hour is computed here in the component.
-
-// Energy mid-point — at neutral energy the overlay contributes almost nothing.
-const BASE_INTENSITY = 0.12;
-
-export default function OpenWorldEnergyOverlay({ chronotype, settings }) {
- const lightRef = useRef();
-
- // Honor the quality dial: skip the per-frame energy lerp on the lowest preset, but
- // still apply a static energy tint so the chronotype mood is legible.
- const animate = (settings?.particleDensity ?? 1) >= 0.5;
-
- // Smoothed brightness so a clock tick across an hour boundary fades rather than jumps.
- const smoothedRef = useRef(null);
-
- useFrame((_, delta) => {
- if (!lightRef.current) return;
-
- const hour = new Date().getHours() + new Date().getMinutes() / 60;
- const { brightness } = computeChronotypeEnergy(chronotype, hour);
-
- // High energy → warmer/brighter; low energy → cooler/dimmer. Intensity rides
- // the brightness modifier (clamped 0.7–1.15 in the helper) so it stays subtle.
- const targetIntensity = BASE_INTENSITY * brightness;
-
- if (!animate || smoothedRef.current === null) {
- smoothedRef.current = targetIntensity;
- } else {
- const lf = Math.min(1, delta * 1.5);
- smoothedRef.current += (targetIntensity - smoothedRef.current) * lf;
- }
-
- lightRef.current.intensity = smoothedRef.current;
- });
-
- // A warm-tinted ambient fill — peak hours glow a touch warmer/brighter, recovery
- // hours fade it toward nothing. Faint by design so it layers over OpenWorldLights
- // without washing out the existing palette.
- return <ambientLight ref={lightRef} intensity={BASE_INTENSITY} color="#ffd9a0" />;
-}
diff --git a/client/src/components/openworld/OpenWorldFastTravel.jsx b/client/src/components/openworld/OpenWorldFastTravel.jsx
deleted file mode 100644
index 8ffb8d700f..0000000000
--- a/client/src/components/openworld/OpenWorldFastTravel.jsx
+++ /dev/null
@@ -1,215 +0,0 @@
-import { useEffect, useMemo, useRef, useState } from 'react';
-import Modal from '../ui/Modal';
-import {
- MINI_MAP_PADDING,
- computeBounds,
- projectPoint,
- spreadProjectedPoints,
-} from '../../utils/openWorldMiniMap';
-import { listRegions, searchRegions } from '../../utils/openWorldRegions';
-import { VILLAGE_GROUND, VILLAGE_ROUTES } from '../../utils/openWorldPlan';
-import useOpenWorldViewport from '../../hooks/useOpenWorldViewport';
-
-// OpenWorld's world map — the thing that makes this an open world rather than one city you pan
-// around. Every named region is a warp destination: pick one and the camera (or, in exploration
-// mode, the player) travels there. The region metadata describes the PortOS area represented by
-// the district; this panel never opens that area as a separate page.
-//
-// Selection is NOT held here. Clicking a region navigates to `/openworld/region/:regionId`
-// and the route param drives the camera — the same URL-is-the-source-of-truth rule building
-// focus follows, so a warp is shareable, bookmarkable, and reachable from ⌘K and voice.
-//
-// The dialog chrome (backdrop, Esc, click-outside, focus trap, and the module-scope Esc
-// stack that keeps layered dialogs from both closing on one keystroke) comes from the shared
-// <Modal> primitive — the same one OpenWorldPhotoOverlay's postcard uses. Portaled, which is safe
-// here because every class this panel wears (`port-media-overlay*`) is global rather than
-// scoped under `.openworld-themed`.
-
-// The plate projects the same unified ground and curved lane registry as street-level
-// rendering. This keeps the map spatially honest without resurrecting the old island graph.
-const MAP_BOUNDS = computeBounds([
- { x: VILLAGE_GROUND.center[0] - VILLAGE_GROUND.radiusX, z: VILLAGE_GROUND.center[1] },
- { x: VILLAGE_GROUND.center[0] + VILLAGE_GROUND.radiusX, z: VILLAGE_GROUND.center[1] },
- { x: VILLAGE_GROUND.center[0], z: VILLAGE_GROUND.center[1] - VILLAGE_GROUND.radiusZ },
- { x: VILLAGE_GROUND.center[0], z: VILLAGE_GROUND.center[1] + VILLAGE_GROUND.radiusZ },
-]);
-const villageCenter = projectPoint({ x: VILLAGE_GROUND.center[0], z: VILLAGE_GROUND.center[1] }, MAP_BOUNDS, MINI_MAP_PADDING);
-const villageEdgeX = projectPoint({ x: VILLAGE_GROUND.center[0] + VILLAGE_GROUND.radiusX, z: VILLAGE_GROUND.center[1] }, MAP_BOUNDS, MINI_MAP_PADDING);
-const villageEdgeZ = projectPoint({ x: VILLAGE_GROUND.center[0], z: VILLAGE_GROUND.center[1] + VILLAGE_GROUND.radiusZ }, MAP_BOUNDS, MINI_MAP_PADDING);
-const MAP_GROUND = {
- nx: villageCenter.nx,
- ny: villageCenter.ny,
- radiusX: Math.abs(villageEdgeX.nx - villageCenter.nx),
- radiusY: Math.abs(villageEdgeZ.ny - villageCenter.ny),
-};
-const MAP_ROUTES = VILLAGE_ROUTES.map((route) => ({
- ...route,
- points: [...route.points, ...(route.closed ? [route.points[0]] : [])]
- .map(([x, z]) => projectPoint({ x, z }, MAP_BOUNDS, MINI_MAP_PADDING)),
-}));
-
-export default function OpenWorldFastTravel({ open, onClose, onTravel, activeRegionId, onLeaveRegion, isFeatureEnabled }) {
- const [query, setQuery] = useState('');
- const inputRef = useRef(null);
- const { isCondensed } = useOpenWorldViewport();
-
- const regions = useMemo(() => listRegions(isFeatureEnabled), [isFeatureEnabled]);
- const matches = useMemo(() => searchRegions(query, isFeatureEnabled), [query, isFeatureEnabled]);
- const matchIds = useMemo(() => new Set(matches.map((r) => r.id)), [matches]);
- const mapMarkers = useMemo(
- () => spreadProjectedPoints(regions.map((region) => {
- const { nx, ny } = projectPoint({ x: region.anchor[0], z: region.anchor[2] }, MAP_BOUNDS, MINI_MAP_PADDING);
- return { id: region.id, nx, ny };
- })),
- [regions],
- );
- const markersById = useMemo(() => new Map(mapMarkers.map((marker) => [marker.id, marker])), [mapMarkers]);
-
- // Reopening always starts from the full list — a stale filter from the last visit would
- // read as "half my world is missing".
- useEffect(() => {
- if (!open) return undefined;
- setQuery('');
- const raf = requestAnimationFrame(() => inputRef.current?.focus());
- return () => cancelAnimationFrame(raf);
- }, [open]);
-
- // Modal renders null while closed, but only AFTER the caller has built the children
- // tree. This page re-renders on every socket event, so return early and skip ~60
- // discarded elements (and 14 projections) per event while the panel is shut.
- if (!open) return null;
-
- const travel = (region) => {
- onTravel?.(region);
- onClose?.();
- };
-
- return (
- <Modal
- open={open}
- onClose={onClose}
- size="none"
- usePortal
- ariaLabel="Village map"
- zIndexClassName="z-[120]"
- panelClassName="w-full max-w-3xl rounded-xl border port-media-overlay flex flex-col overflow-hidden"
- >
- <div className="flex items-center gap-3 px-4 py-3 border-b border-current/10">
- <div className="font-pixel text-[12px] tracking-widest">VILLAGE MAP</div>
- <input
- ref={inputRef}
- type="text"
- value={query}
- onChange={(e) => setQuery(e.target.value)}
- placeholder="Search village places…"
- aria-label="Search village places"
- className="flex-1 min-w-0 font-pixel text-[11px] px-2 py-1.5 rounded border border-current/20 bg-transparent focus:outline-none focus:border-current/50"
- />
- {/* The only way back out of a region to the whole-world overview — without it a
- warp is a one-way trip until you pick another region. */}
- {activeRegionId && onLeaveRegion && (
- <button
- type="button"
- onClick={() => { onLeaveRegion(); onClose?.(); }}
- className="port-media-overlay-item shrink-0 font-pixel text-[10px] px-2 py-1.5 rounded border border-current/20 tracking-wide"
- >
- OVERVIEW
- </button>
- )}
- <button
- type="button"
- onClick={onClose}
- className="port-media-overlay-item font-pixel text-[10px] px-2 py-1.5 rounded border border-current/20"
- >
- ESC
- </button>
- </div>
-
- <div className={`flex-1 min-h-0 grid gap-3 p-3 overflow-hidden ${isCondensed ? 'grid-cols-1 grid-rows-[minmax(190px,36vh)_minmax(0,1fr)]' : 'grid-cols-[240px_1fr]'}`}>
- {/* World plate — regions in their real plan positions, so the list and the map
- can't disagree about where a place is. Compact viewports get a full-width
- touch-sized plate above the searchable list; desktop keeps the square rail. */}
- <div
- className="block w-full h-full relative rounded-lg border border-current/15 overflow-hidden"
- role="region"
- aria-label="Village map"
- >
- <div className="absolute inset-0 bg-[#132521]/95" />
- <svg className="absolute inset-0 w-full h-full pointer-events-none" viewBox="0 0 100 100" aria-hidden="true">
- <ellipse
- cx={MAP_GROUND.nx * 100}
- cy={MAP_GROUND.ny * 100}
- rx={MAP_GROUND.radiusX * 100}
- ry={MAP_GROUND.radiusY * 100}
- fill="rgba(116, 156, 91, 0.86)"
- stroke="rgba(228, 218, 163, 0.78)"
- strokeWidth="1.2"
- />
- {MAP_ROUTES.map((route) => (
- <polyline
- key={route.id}
- points={route.points.map((point) => `${point.nx * 100},${point.ny * 100}`).join(' ')}
- fill="none"
- stroke={route.kind === 'path' ? 'rgba(218, 170, 112, 0.88)' : 'rgba(239, 221, 165, 0.92)'}
- strokeWidth={route.kind === 'path' ? '1.25' : '2.4'}
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- ))}
- </svg>
- {regions.map((region) => {
- const { nx, ny } = markersById.get(region.id);
- const isActive = region.id === activeRegionId;
- const isMatch = matchIds.has(region.id);
- return (
- <button
- key={region.id}
- type="button"
- title={region.label}
- aria-label={`Teleport to ${region.label}`}
- onClick={() => travel(region)}
- className={`absolute -translate-x-1/2 -translate-y-1/2 rounded-full transition-all flex items-center justify-center ${isCondensed ? 'w-11 h-11' : 'w-5 h-5 hover:scale-125'}`}
- style={{ left: `${nx * 100}%`, top: `${ny * 100}%` }}
- >
- <span
- className={`rounded-full border shadow-sm ${
- isActive
- ? 'w-4 h-4 border-[#fff5c7] bg-[#fff0a6] ring-2 ring-[#fff0a6]/35'
- : isMatch
- ? 'w-3 h-3 border-[#f5e7bd] bg-[#f5e7bd]/85'
- : 'w-2.5 h-2.5 border-current/40 bg-current/25'
- }`}
- aria-hidden="true"
- />
- </button>
- );
- })}
- </div>
-
- <ul className="min-h-0 overflow-y-auto space-y-1.5 pr-1">
- {matches.length === 0 && (
- <li className="font-pixel text-[10px] opacity-60 px-2 py-3">NO REGION MATCHES “{query}”</li>
- )}
- {matches.map((region) => (
- <li key={region.id}>
- <div
- className={`flex items-center gap-2 rounded-lg border px-2.5 py-2 ${
- region.id === activeRegionId ? 'border-current/60 bg-current/10' : 'border-current/15'
- }`}
- >
- <button
- type="button"
- onClick={() => travel(region)}
- className="flex-1 min-w-0 text-left"
- >
- <div className="font-pixel text-[11px] tracking-wide truncate">{region.label}</div>
- <div className="text-[11px] opacity-70 truncate">{region.blurb}</div>
- </button>
- </div>
- </li>
- ))}
- </ul>
- </div>
- </Modal>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldFastTravel.test.jsx b/client/src/components/openworld/OpenWorldFastTravel.test.jsx
deleted file mode 100644
index 4c8d6e628f..0000000000
--- a/client/src/components/openworld/OpenWorldFastTravel.test.jsx
+++ /dev/null
@@ -1,120 +0,0 @@
-import { describe, it, expect, vi } from 'vitest';
-import { render, screen, fireEvent, within } from '@testing-library/react';
-import OpenWorldFastTravel from './OpenWorldFastTravel';
-import { OPEN_WORLD_REGIONS } from '../../utils/openWorldRegions';
-
-const renderPanel = (props = {}) => render(
- <OpenWorldFastTravel
- open
- onClose={vi.fn()}
- onTravel={vi.fn()}
- activeRegionId={null}
- onLeaveRegion={vi.fn()}
- {...props}
- />
-);
-
-describe('OpenWorldFastTravel', () => {
- it('renders nothing when closed', () => {
- const { container } = render(<OpenWorldFastTravel open={false} />);
- expect(container).toBeEmptyDOMElement();
- });
-
- it('lists every region when open', () => {
- renderPanel();
- const list = screen.getByRole('list');
- for (const region of OPEN_WORLD_REGIONS) {
- expect(within(list).getByText(region.label)).toBeInTheDocument();
- }
- });
-
- it('warps and closes when a region is picked', () => {
- const onTravel = vi.fn();
- const onClose = vi.fn();
- renderPanel({ onTravel, onClose });
-
- fireEvent.click(screen.getByRole('list').querySelector('button'));
-
- expect(onTravel).toHaveBeenCalledTimes(1);
- expect(onTravel.mock.calls[0][0].id).toBe(OPEN_WORLD_REGIONS[0].id);
- // Warping dismisses the panel so the camera flight isn't hidden behind it.
- expect(onClose).toHaveBeenCalled();
- });
-
- it('filters the list by the search box', () => {
- renderPanel();
- fireEvent.change(screen.getByLabelText('Search village places'), { target: { value: 'memory house' } });
-
- const list = screen.getByRole('list');
- expect(within(list).getByText('Memory House')).toBeInTheDocument();
- expect(within(list).queryByText('Data Pier')).not.toBeInTheDocument();
- });
-
- it('reports an empty result rather than an empty panel', () => {
- renderPanel();
- fireEvent.change(screen.getByLabelText('Search village places'), { target: { value: 'zzzz' } });
- expect(screen.getByText(/NO REGION MATCHES/)).toBeInTheDocument();
- });
-
- it('does not offer a PortOS page escape hatch', () => {
- renderPanel();
-
- expect(screen.queryByText('OPEN')).not.toBeInTheDocument();
- expect(screen.queryByTitle(/Open\s+\//)).not.toBeInTheDocument();
- });
-
- it('omits the OPEN affordance for a region with no page behind it', () => {
- renderPanel();
- fireEvent.change(screen.getByLabelText('Search village places'), { target: { value: 'quiet corner' } });
- const list = screen.getByRole('list');
- expect(within(list).getByText('Quiet Corner')).toBeInTheDocument();
- expect(within(list).queryByText('OPEN')).not.toBeInTheDocument();
- });
-
- it('offers a way back to the overview only while a region is active', () => {
- const onLeaveRegion = vi.fn();
- const onClose = vi.fn();
- const { rerender } = renderPanel({ onLeaveRegion, onClose });
- // No region warped to → nothing to leave.
- expect(screen.queryByText('OVERVIEW')).not.toBeInTheDocument();
-
- rerender(
- <OpenWorldFastTravel
- open
- onClose={onClose}
- onTravel={vi.fn()}
- onLeaveRegion={onLeaveRegion}
- activeRegionId="memory"
- />
- );
- fireEvent.click(screen.getByText('OVERVIEW'));
- expect(onLeaveRegion).toHaveBeenCalled();
- expect(onClose).toHaveBeenCalled();
- });
-
- it('is an accessible dialog that closes from the backdrop and from Escape', () => {
- // Chrome comes from the shared <Modal>, so these assert the wiring, not a re-roll.
- const onClose = vi.fn();
- renderPanel({ onClose });
-
- const dialog = screen.getByRole('dialog');
- expect(dialog).toHaveAttribute('aria-modal', 'true');
- expect(dialog).toHaveAttribute('aria-label', 'Village map');
-
- fireEvent.click(dialog.parentElement);
- expect(onClose).toHaveBeenCalledTimes(1);
-
- fireEvent.keyDown(window, { key: 'Escape' });
- expect(onClose).toHaveBeenCalledTimes(2);
- });
-
- it('offers a map marker for every region, aimed at the same warp', () => {
- const onTravel = vi.fn();
- renderPanel({ onTravel });
- for (const region of OPEN_WORLD_REGIONS) {
- expect(screen.getByLabelText(`Teleport to ${region.label}`)).toBeInTheDocument();
- }
- fireEvent.click(screen.getByLabelText('Teleport to Data Pier'));
- expect(onTravel.mock.calls[0][0].id).toBe('data-harbor');
- });
-});
diff --git a/client/src/components/openworld/OpenWorldFederationHorizon.jsx b/client/src/components/openworld/OpenWorldFederationHorizon.jsx
deleted file mode 100644
index a9c61abf1f..0000000000
--- a/client/src/components/openworld/OpenWorldFederationHorizon.jsx
+++ /dev/null
@@ -1,139 +0,0 @@
-import { useMemo, useRef, useEffect } from 'react';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { PIXEL_FONT_URL, openWorldDayMix } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import OpenWorldLabel from './OpenWorldLabel';
-import { computeFederationHorizon, FEDERATION } from '../../utils/openWorldFederation';
-
-// The sync link reaching inward from a peer toward the city. Solid + bright when
-// the peer is actively syncing, dashed when the link is broken (offline / failing),
-// faint when idle.
-function FederationBridge({ from, color, broken, intensity }) {
- const lineRef = useRef();
-
- // `from` is the peer's ground position; the bridge stretches inward toward the
- // city center so it reads as a link reaching home.
- const geometry = useMemo(() => {
- const dir = new THREE.Vector3(-from[0], 0, -from[2]);
- if (dir.lengthSq() > 0) dir.normalize();
- const start = new THREE.Vector3(from[0] + dir.x * 1.5, 0.6, from[2] + dir.z * 1.5);
- const end = new THREE.Vector3(
- from[0] + dir.x * (1.5 + FEDERATION.bridgeReach),
- 0.6,
- from[2] + dir.z * (1.5 + FEDERATION.bridgeReach),
- );
- return new THREE.BufferGeometry().setFromPoints([start, end]);
- }, [from]);
-
- // computeLineDistances lives on the Line OBJECT, not on BufferGeometry — calling it on the
- // geometry throws ("computeLineDistances is not a function") and crashes the whole canvas. The
- // dashed (broken) material needs per-vertex line distances, so compute them on the line ref
- // after it mounts / whenever the geometry or broken state changes.
- useEffect(() => {
- if (broken) lineRef.current?.computeLineDistances();
- }, [geometry, broken]);
-
- useEffect(() => () => geometry.dispose(), [geometry]);
-
- return (
- <line ref={lineRef} geometry={geometry}>
- {broken ? (
- <lineDashedMaterial color={color} transparent opacity={0.15 + intensity * 0.25} dashSize={1.1} gapSize={0.9} />
- ) : (
- <lineBasicMaterial color={color} transparent opacity={0.2 + intensity * 0.4} />
- )}
- </line>
- );
-}
-
-// A distant peer (or the void marker) rendered as a neon-trimmed silhouette.
-function Monolith({ position, width, height, color, opacity, label, sublabel, online, animate, dayMix = 0 }) {
- const { tintStructure } = useOpenWorldPalette();
- const capRef = useRef();
-
- useFrame(({ clock }) => {
- if (!animate || !online || !capRef.current) return;
- const pulse = 0.6 + ((Math.sin(clock.getElapsedTime() * 1.2 + position[0]) + 1) / 2) * 0.6;
- capRef.current.material.emissiveIntensity = pulse;
- });
-
- return (
- <group position={position}>
- {/* Dark body with a faint neon glow scaled by reachability */}
- <mesh position={[0, height / 2, 0]}>
- <boxGeometry args={[width, height, width * 0.4]} />
- <meshStandardMaterial
- color={tintStructure('#0a0a18')}
- emissive={color}
- emissiveIntensity={opacity}
- transparent
- opacity={Math.min(0.9, 0.4 + opacity)}
- depthWrite={false}
- />
- </mesh>
- {/* Bright neon cap at the top edge */}
- <mesh ref={capRef} position={[0, height + 0.3, 0]}>
- <boxGeometry args={[width * 1.05, 0.6, width * 0.45]} />
- <meshStandardMaterial color={color} emissive={color} emissiveIntensity={online ? 0.9 : 0.4} transparent opacity={Math.min(1, opacity + 0.4)} depthWrite={false} />
- </mesh>
- {label && (
- <OpenWorldLabel position={[0, height + 2.2, 0]} fontSize={1.6} color={color} dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={20}>
- {label}
- </OpenWorldLabel>
- )}
- {sublabel && (
- <OpenWorldLabel position={[0, height + 0.9, 0]} fontSize={1.0} color="#94a3b8" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={20}>
- {sublabel}
- </OpenWorldLabel>
- )}
- </group>
- );
-}
-
-export default function OpenWorldFederationHorizon({ instances, settings }) {
- const { peers, voidMarker } = useMemo(
- () => computeFederationHorizon(instances?.peers),
- [instances],
- );
-
- // The horizon is a handful of distant static meshes, but honor the quality
- // dial: drop the gentle peer pulse on the lowest preset.
- const animate = (settings?.particleDensity ?? 1) >= 0.5;
- const dayMix = openWorldDayMix(settings);
-
- return (
- <group>
- {peers.map(peer => (
- <group key={peer.id}>
- <Monolith
- position={peer.position}
- width={peer.width}
- height={peer.height}
- color={peer.color}
- opacity={peer.opacity}
- label={peer.name}
- sublabel={peer.online ? 'LINKED' : peer.status.toUpperCase()}
- online={peer.online}
- animate={animate}
- dayMix={dayMix}
- />
- <FederationBridge from={peer.position} color={peer.color} broken={peer.bridge.broken} intensity={peer.bridge.intensity} />
- </group>
- ))}
- {/* Void machine — always present so the federation horizon never goes empty */}
- <Monolith
- position={voidMarker.position}
- width={voidMarker.width}
- height={voidMarker.height}
- color={voidMarker.color}
- opacity={voidMarker.opacity}
- label="VOID"
- sublabel="PRIMARY"
- online={false}
- animate={false}
- dayMix={dayMix}
- />
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldFilterBar.jsx b/client/src/components/openworld/OpenWorldFilterBar.jsx
deleted file mode 100644
index a22dd66a0a..0000000000
--- a/client/src/components/openworld/OpenWorldFilterBar.jsx
+++ /dev/null
@@ -1,105 +0,0 @@
-import { useEffect, useRef, useState } from 'react';
-import { STATUS_FILTERS } from '../../utils/openWorldFilter';
-
-export default function OpenWorldFilterBar({ filter, onChange, matchCount, onJumpToFirst, compact = false }) {
- const inputRef = useRef(null);
- const filterRef = useRef(filter);
- const onChangeRef = useRef(onChange);
- const [open, setOpen] = useState(Boolean(filter.search));
-
- filterRef.current = filter;
- onChangeRef.current = onChange;
-
- useEffect(() => {
- const onKey = (e) => {
- const tag = e.target?.tagName;
- const isTyping = tag === 'INPUT' || tag === 'TEXTAREA' || e.target?.isContentEditable;
- if (e.key === '/' && !isTyping && !e.metaKey && !e.ctrlKey && !e.altKey) {
- e.preventDefault();
- setOpen(true);
- setTimeout(() => inputRef.current?.focus(), 0);
- return;
- }
- if (e.key === 'Escape') {
- const current = filterRef.current;
- if (current?.search) onChangeRef.current({ ...current, search: '' });
- setOpen(false);
- inputRef.current?.blur();
- }
- };
- window.addEventListener('keydown', onKey);
- return () => window.removeEventListener('keydown', onKey);
- }, []);
-
- const handleSubmit = (e) => {
- e.preventDefault();
- onJumpToFirst?.();
- };
-
- // Compact/mobile context (rendered inside the OpenWorldHudCompact filter sheet) needs a real
- // ≥44px touch target; the dense desktop bar keeps its small px-2 py-1 chips.
- const chipBaseClass = compact
- ? 'font-pixel text-[10px] tracking-wider px-3 min-h-[44px] flex items-center rounded border transition-colors'
- : 'font-pixel text-[9px] tracking-wider px-2 py-1 rounded border transition-colors';
-
- return (
- <div className="openworld-hud-panel pointer-events-auto px-2 py-2 flex items-center gap-2 flex-wrap">
- <div className="flex items-center gap-1 flex-wrap">
- {STATUS_FILTERS.map(f => {
- const active = filter.status === f.id;
- return (
- <button
- key={f.id}
- type="button"
- onClick={() => onChange({ ...filter, status: f.id })}
- className={`${chipBaseClass} ${
- active
- ? 'border-cyan-400/70 bg-cyan-500/15 text-cyan-300 shadow-[0_0_4px_rgba(6,182,212,0.3)]'
- : 'border-cyan-500/20 text-cyan-500/50 hover:border-cyan-400/50 hover:text-cyan-300'
- }`}
- title={`Show ${f.label.toLowerCase()} only`}
- >
- {f.label}
- </button>
- );
- })}
- </div>
-
- <div className="w-px h-5 bg-cyan-500/20" />
-
- {!open ? (
- <button
- type="button"
- onClick={() => { setOpen(true); setTimeout(() => inputRef.current?.focus(), 0); }}
- className={`${chipBaseClass} border-cyan-500/20 text-cyan-500/50 hover:border-cyan-400/50 hover:text-cyan-300 flex items-center gap-1.5`}
- title="Search apps (press /)"
- >
- <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
- <circle cx="11" cy="11" r="7" />
- <path d="m20 20-3-3" strokeLinecap="round" />
- </svg>
- SEARCH
- <span className="font-pixel text-[8px] text-cyan-500/40 px-1 border border-cyan-500/20 rounded">/</span>
- </button>
- ) : (
- <form onSubmit={handleSubmit} className="flex items-center gap-1.5">
- <input
- ref={inputRef}
- type="text"
- value={filter.search}
- onChange={(e) => onChange({ ...filter, search: e.target.value })}
- onBlur={() => { if (!filter.search) setOpen(false); }}
- placeholder="search apps…"
- aria-label="Search apps"
- className={`font-pixel text-[10px] tracking-wide bg-black/60 border border-cyan-500/30 rounded px-2 text-cyan-300 placeholder:text-cyan-500/30 focus:outline-none focus:border-cyan-400/70 w-32 ${compact ? 'min-h-[44px]' : 'py-1'}`}
- />
- {filter.search && (
- <span className="font-pixel text-[8px] text-cyan-500/50 tracking-wider">
- {matchCount} {matchCount === 1 ? 'MATCH' : 'MATCHES'}
- </span>
- )}
- </form>
- )}
- </div>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldFilterBar.test.jsx b/client/src/components/openworld/OpenWorldFilterBar.test.jsx
deleted file mode 100644
index dfdc192760..0000000000
--- a/client/src/components/openworld/OpenWorldFilterBar.test.jsx
+++ /dev/null
@@ -1,76 +0,0 @@
-import { describe, it, expect, vi } from 'vitest';
-import { render, screen, fireEvent, waitFor } from '@testing-library/react';
-import OpenWorldFilterBar from './OpenWorldFilterBar';
-
-const baseFilter = { status: 'all', search: '' };
-
-const renderBar = (props = {}) =>
- render(
- <OpenWorldFilterBar
- filter={baseFilter}
- onChange={() => {}}
- matchCount={0}
- onJumpToFirst={() => {}}
- {...props}
- />
- );
-
-describe('OpenWorldFilterBar', () => {
- it('pressing / (not already typing) opens and focuses the search field', async () => {
- renderBar();
- // Closed by default: the search trigger button is shown, not the input.
- expect(screen.queryByLabelText('Search apps')).not.toBeInTheDocument();
-
- fireEvent.keyDown(window, { key: '/' });
-
- await waitFor(() => {
- expect(screen.getByLabelText('Search apps')).toBe(document.activeElement);
- });
- });
-
- it('pressing Escape clears the search via onChange, with the exact cleared filter', () => {
- const onChange = vi.fn();
- renderBar({ filter: { status: 'online', search: 'alpha' }, onChange });
-
- fireEvent.keyDown(window, { key: 'Escape' });
-
- expect(onChange).toHaveBeenCalledTimes(1);
- expect(onChange).toHaveBeenCalledWith({ status: 'online', search: '' });
- });
-
- it('pressing / while focus is already in another input does not steal focus', () => {
- render(
- <>
- <input aria-label="Unrelated field" />
- <OpenWorldFilterBar filter={baseFilter} onChange={() => {}} matchCount={0} onJumpToFirst={() => {}} />
- </>
- );
- const otherInput = screen.getByLabelText('Unrelated field');
- otherInput.focus();
- expect(document.activeElement).toBe(otherInput);
-
- fireEvent.keyDown(otherInput, { key: '/' });
-
- // Focus never moved, and the search panel never opened.
- expect(document.activeElement).toBe(otherInput);
- expect(screen.queryByLabelText('Search apps')).not.toBeInTheDocument();
- });
-
- it('renders filter chips with the 44px touch-target class in compact mode, not in default mode', () => {
- const { rerender } = renderBar();
- const defaultChip = screen.getByRole('button', { name: 'ALL' });
- expect(defaultChip.className).not.toContain('min-h-[44px]');
-
- rerender(
- <OpenWorldFilterBar
- filter={baseFilter}
- onChange={() => {}}
- matchCount={0}
- onJumpToFirst={() => {}}
- compact
- />
- );
- const compactChip = screen.getByRole('button', { name: 'ALL' });
- expect(compactChip.className).toContain('min-h-[44px]');
- });
-});
diff --git a/client/src/components/openworld/OpenWorldFocusCamera.jsx b/client/src/components/openworld/OpenWorldFocusCamera.jsx
deleted file mode 100644
index b302be6a9a..0000000000
--- a/client/src/components/openworld/OpenWorldFocusCamera.jsx
+++ /dev/null
@@ -1,134 +0,0 @@
-import { useRef, useEffect, useMemo } from 'react';
-import { useThree, useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { smoothstep } from '../../utils/easing';
-import { computeFocusCamera, computeRegionCamera } from '../../utils/openWorldFocusCamera';
-import { computeDistrictBounds } from '../../utils/openWorldMiniMap';
-
-// In-canvas camera controller for OpenWorld's two URL-addressed camera targets: a single
-// building (`/openworld/apps/:appId`, issue #2593) and a whole fast-travel region
-// (`/openworld/region/:regionId`). Either one flies the orbital camera (and the OrbitControls
-// target) to frame its subject; when both clear, it flies back to the overview.
-//
-// A building focus wins over a region when both are somehow set — the two live on separate
-// routes, so that only happens transiently mid-navigation, and framing the tighter subject is
-// the less jarring resolution.
-//
-// Staleness / unmount safety: all motion runs inside useFrame, which is inherently frame-gated —
-// there is NO setTimeout, so a stale deferred emit is impossible. Retargeting to a newly-selected
-// building simply restarts the fly on the frame the id changes (`currentKeyRef`). The unmount
-// cleanup restores OrbitControls if we were mid-fly, so navigating away can't strand the controls
-// disabled.
-
-const OVERVIEW_POS = new THREE.Vector3(0, 25, 45);
-const OVERVIEW_TARGET = new THREE.Vector3(0, 0, 0);
-const DURATION = 0.85; // seconds
-
-// Approximate the camera's current look-at point from its facing (used as the fly's start target
-// when OrbitControls hasn't exposed one yet).
-const deriveLookAt = (camera) => {
- const dir = new THREE.Vector3(0, 0, -1).applyQuaternion(camera.quaternion);
- return camera.position.clone().add(dir.multiplyScalar(10));
-};
-
-export default function OpenWorldFocusCamera({ focusedAppId, focusedRegion, positions, orbitRef, active = true, hudSafe }) {
- const { camera, size } = useThree();
- // `null` = overview (no fly needed on a plain /openworld mount). A transition into/out of focus flips
- // this and starts a fly.
- const currentKeyRef = useRef(null);
- // The region fly's identity, built once per target change rather than inside useFrame —
- // the live loop runs ~60×/s and must not allocate a string per frame.
- const regionKey = useMemo(
- () => (focusedRegion?.anchor ? `region:${focusedRegion.id}` : null),
- [focusedRegion?.anchor, focusedRegion?.id],
- );
- // A data-driven region (downtown / the archive grid) is framed by what's actually placed,
- // not by its nominal parcel — those grids grow with the install's app count, so a fixed
- // rectangle clips the outer towers on a big install. Static regions pass null and keep the
- // parcel footprint.
- const regionBounds = useMemo(
- () => (focusedRegion?.district ? computeDistrictBounds(positions, focusedRegion.district) : null),
- [focusedRegion?.district, positions],
- );
- const animRef = useRef(null);
- const controlsWasEnabledRef = useRef(true);
-
- useEffect(() => () => {
- // Restore controls if we unmount mid-fly (e.g. entering exploration/photo mode).
- const controls = orbitRef?.current;
- if (controls && animRef.current) controls.enabled = controlsWasEnabledRef.current;
- }, [orbitRef]);
-
- useFrame((_, delta) => {
- const controls = orbitRef?.current;
-
- const wantFocus = active && typeof focusedAppId === 'string' && focusedAppId.length > 0;
- const pos = wantFocus ? positions?.get?.(focusedAppId) : null;
- // Focus wanted but the layout position isn't ready yet → hold and retry next frame.
- if (wantFocus && !pos) return;
- // A static region comes straight from the plan, so there is no equivalent wait — but a
- // data-driven one must wait for the layout, or the first fly frames the nominal parcel
- // and never re-flies once the real bounds arrive. `positions` present with null bounds
- // is a genuinely EMPTY district (no archived apps yet), which correctly uses the parcel.
- if (!wantFocus && active && focusedRegion?.district && !positions) return;
- const wantRegion = !wantFocus && active && regionKey !== null;
- const key = wantFocus ? focusedAppId : wantRegion ? regionKey : null;
-
- if (key !== currentKeyRef.current) {
- currentKeyRef.current = key;
- // Only capture the controls' "real" enabled state when NO fly is in progress. Retargeting
- // mid-fly (rapid building/minimap clicks, or Close before the fly settles) would otherwise
- // capture the already-disabled value and restore `false` forever.
- const wasSettled = animRef.current === null;
- const startTarget = controls?.target ? controls.target.clone() : deriveLookAt(camera);
-
- let endPos;
- let endTarget;
- if (key === null) {
- endPos = OVERVIEW_POS.clone();
- endTarget = OVERVIEW_TARGET.clone();
- } else {
- const aspect = size.height > 0 ? size.width / size.height : 1;
- const fovDeg = camera.isPerspectiveCamera ? camera.fov : undefined;
- const framed = wantFocus
- ? computeFocusCamera({ building: pos, aspect, fovDeg, hudSafe })
- : computeRegionCamera({ region: focusedRegion, bounds: regionBounds, aspect, fovDeg, hudSafe });
- endPos = new THREE.Vector3(...framed.position);
- endTarget = new THREE.Vector3(...framed.target);
- }
-
- animRef.current = {
- fromPos: camera.position.clone(),
- fromTarget: startTarget,
- toPos: endPos,
- toTarget: endTarget,
- t: 0,
- };
- // Take over from OrbitControls for the duration of the fly, remembering its prior state.
- if (controls) {
- if (wasSettled) controlsWasEnabledRef.current = controls.enabled;
- controls.enabled = false;
- }
- }
-
- const anim = animRef.current;
- if (!anim) return; // settled — let the user orbit freely
-
- anim.t = Math.min(1, anim.t + delta / DURATION);
- const e = smoothstep(anim.t);
- camera.position.lerpVectors(anim.fromPos, anim.toPos, e);
- const tgt = new THREE.Vector3().lerpVectors(anim.fromTarget, anim.toTarget, e);
- if (controls) controls.target.copy(tgt);
- camera.lookAt(tgt);
-
- if (anim.t >= 1) {
- animRef.current = null;
- if (controls) {
- controls.enabled = controlsWasEnabledRef.current;
- controls.update?.();
- }
- }
- });
-
- return null;
-}
diff --git a/client/src/components/openworld/OpenWorldFocusPanel.jsx b/client/src/components/openworld/OpenWorldFocusPanel.jsx
deleted file mode 100644
index e0e11582f6..0000000000
--- a/client/src/components/openworld/OpenWorldFocusPanel.jsx
+++ /dev/null
@@ -1,204 +0,0 @@
-import { useMemo } from 'react';
-import { formatBytes, formatDurationMs } from '../../utils/formatters';
-import { computeAppMetrics, cpuTone } from '../../utils/openWorldAppMetrics';
-
-// Building-detail panel shown while a borough is focused (issue #2593). It REPLACES the Intel pane
-// (desktop) / renders as a bottom sheet (compact) — never overlapping it — and surfaces the app's
-// live state from data OpenWorld already has: status, process summary + unhealthy processes, and the
-// agents assigned to the app. Two explicit actions: focus the building in the world and Close
-// (returns to the OpenWorld overview). It never opens the represented PortOS page.
-
-const STATUS_STYLES = {
- online: { text: 'text-port-success', dot: 'bg-port-success', label: 'ONLINE' },
- stopped: { text: 'text-port-error', dot: 'bg-port-error', label: 'STOPPED' },
- not_started: { text: 'text-violet-400', dot: 'bg-violet-500', label: 'NOT STARTED' },
- not_found: { text: 'text-gray-400', dot: 'bg-gray-500', label: 'NOT FOUND' },
- unknown: { text: 'text-gray-400', dot: 'bg-gray-500', label: 'UNKNOWN' },
-};
-
-const UNHEALTHY = new Set(['errored', 'error', 'stopped', 'stopping']);
-
-// Same glanceable load tone the building hologram uses, so "hot" means hot everywhere.
-const CPU_TONE_CLASSES = {
- idle: 'text-gray-400',
- calm: 'text-cyan-300',
- busy: 'text-port-warning',
- hot: 'text-port-error',
-};
-
-function StatBlock({ label, value, tone = 'text-cyan-300' }) {
- return (
- <div className="bg-black/40 border border-cyan-500/20 rounded px-2 py-1.5">
- <div className="font-pixel text-[8px] text-cyan-500/50 tracking-wider">{label}</div>
- <div className={`font-pixel text-[13px] tracking-wide ${tone}`}>{value}</div>
- </div>
- );
-}
-
-export default function OpenWorldFocusPanel({ app, notFound = false, agents = [], onClose, onFocusInWorld, isDesktop = true }) {
- // Desktop: occupy the Intel-pane slot. Compact: a bottom sheet above the dock.
- const containerClass = isDesktop
- ? 'absolute top-20 right-4 bottom-24 w-[19rem] max-w-[calc(100vw-1rem)] pointer-events-auto'
- : 'absolute inset-x-2 bottom-16 pointer-events-auto';
-
- // Live per-process PM2 telemetry (roadmap 1.1) — same aggregation the building
- // hologram renders, so the focused panel and the in-world card never disagree.
- const metrics = useMemo(() => computeAppMetrics(app), [app]);
-
- const procSummary = useMemo(() => {
- const status = app?.pm2Status || {};
- const processes = Array.isArray(app?.processes) ? app.processes : [];
- const total = processes.length || Object.keys(status).length;
- const unhealthy = Object.entries(status)
- .filter(([, s]) => UNHEALTHY.has(s?.status))
- .map(([name, s]) => ({ name, status: s?.status }));
- const online = Object.values(status).filter((s) => s?.status === 'online' || s?.status === 'running').length;
- return { total, unhealthy, online };
- }, [app?.pm2Status, app?.processes]);
-
- const activeAgents = useMemo(
- () => (Array.isArray(agents) ? agents : []).filter(
- (a) => a && (a.status === 'running' || a.state === 'coding' || a.state === 'thinking' || a.state === 'investigating' || a.status === 'failed' || a.state === 'error' || a.error)
- ),
- [agents]
- );
-
- if (notFound || !app) {
- return (
- <div className={containerClass}>
- <div
- className="openworld-intel-surface overflow-hidden flex flex-col"
- role="region"
- aria-label="Building not found"
- >
- <div className="px-3 py-6 text-center">
- <div className="font-pixel text-[11px] text-port-warning tracking-wider mb-1">BUILDING NOT FOUND</div>
- <div className="font-pixel text-[8px] text-gray-500 tracking-wide mb-4">
- This app may have been archived or removed.
- </div>
- <button
- type="button"
- onClick={onClose}
- className="pointer-events-auto font-pixel text-[10px] text-cyan-400 tracking-wider border border-cyan-500/40 rounded px-3 py-2 hover:bg-cyan-500/10 transition-colors"
- >
- {'<'} RETURN TO OVERVIEW
- </button>
- </div>
- </div>
- </div>
- );
- }
-
- const statusKey = app.archived ? 'not_found' : (app.overallStatus || 'unknown');
- const statusStyle = STATUS_STYLES[statusKey] || STATUS_STYLES.unknown;
- const title = app.name || app.id;
-
- return (
- <div className={containerClass}>
- <div
- className={`${isDesktop ? 'h-full' : 'max-h-[55vh]'} openworld-intel-surface overflow-hidden flex flex-col`}
- role="region"
- aria-label={`Focused building: ${title}`}
- >
- {/* Header: name + status + close */}
- <div className="flex items-start gap-2 px-3 py-2 border-b border-cyan-500/20 shrink-0">
- <div className="flex-1 min-w-0">
- <div className="font-pixel text-[12px] text-cyan-300 tracking-wide truncate" title={title}>{title}</div>
- <div className="flex items-center gap-1.5 mt-1">
- <span className={`w-2 h-2 rounded-full ${statusStyle.dot} shadow-[0_0_4px_currentColor]`} aria-hidden="true" />
- <span className={`font-pixel text-[9px] tracking-wider ${statusStyle.text}`}>{app.archived ? 'ARCHIVED' : statusStyle.label}</span>
- </div>
- </div>
- <button
- type="button"
- onClick={onClose}
- aria-label="Close focus and return to overview"
- title="Close (return to overview)"
- className="shrink-0 min-w-[44px] min-h-[44px] flex items-center justify-center text-gray-400 hover:text-cyan-400 transition-colors font-pixel text-[13px]"
- >
- ✕
- </button>
- </div>
-
- {/* Body */}
- <div className="flex-1 overflow-y-auto px-3 py-2.5 space-y-3" style={{ scrollbarWidth: 'thin', scrollbarColor: 'rgba(6,182,212,0.2) transparent' }}>
- {/* Process summary */}
- <div>
- <div className="font-pixel text-[8px] text-cyan-500/50 tracking-wider mb-1.5">PROCESSES</div>
- <div className="grid grid-cols-3 gap-1.5">
- <StatBlock label="TOTAL" value={procSummary.total} />
- <StatBlock label="RUNNING" value={procSummary.online} tone="text-port-success" />
- <StatBlock label="ISSUES" value={procSummary.unhealthy.length} tone={procSummary.unhealthy.length ? 'text-port-error' : 'text-cyan-300'} />
- </div>
- {procSummary.unhealthy.length > 0 && (
- <ul className="mt-1.5 space-y-1">
- {procSummary.unhealthy.map((p) => (
- <li key={p.name} className="flex items-center gap-1.5 font-pixel text-[9px] tracking-wide text-port-error">
- <span className="w-1.5 h-1.5 rounded-full bg-port-error shrink-0" aria-hidden="true" />
- <span className="truncate" title={`${p.name} — ${p.status}`}>{p.name}</span>
- <span className="text-gray-500 ml-auto shrink-0">{p.status}</span>
- </li>
- ))}
- </ul>
- )}
- {metrics.hasMetrics && metrics.onlineProcs > 0 && (
- <div className="grid grid-cols-3 gap-1.5 mt-1.5">
- <StatBlock
- label="CPU"
- value={`${metrics.cpuPercent}%`}
- tone={CPU_TONE_CLASSES[cpuTone(metrics.cpuPercent)]}
- />
- <StatBlock label="MEM" value={formatBytes(metrics.memBytes, 0)} />
- <StatBlock label="UPTIME" value={formatDurationMs(metrics.uptimeMs)} tone="text-cyan-300/80" />
- </div>
- )}
- </div>
-
- {/* Active agents */}
- <div>
- <div className="font-pixel text-[8px] text-cyan-500/50 tracking-wider mb-1.5">
- AGENTS {activeAgents.length > 0 && <span className="text-cyan-400">· {activeAgents.length}</span>}
- </div>
- {activeAgents.length === 0 ? (
- <div className="font-pixel text-[9px] text-gray-500 tracking-wide">No agents assigned</div>
- ) : (
- <ul className="space-y-1">
- {activeAgents.map((agent) => {
- const id = agent.agentId || agent.id;
- const failed = agent.status === 'failed' || agent.state === 'error' || agent.error;
- const label = agent.task || agent.taskTitle || `Agent ${String(id || '').slice(0, 8)}`;
- return (
- <li key={id || label} className="flex items-center gap-1.5 font-pixel text-[9px] tracking-wide">
- <span className={`w-1.5 h-1.5 rounded-full shrink-0 ${failed ? 'bg-port-error' : 'bg-cyan-400 animate-pulse'}`} aria-hidden="true" />
- <span className={`truncate ${failed ? 'text-port-error' : 'text-cyan-300'}`} title={label}>{label}</span>
- </li>
- );
- })}
- </ul>
- )}
- </div>
- </div>
-
- {/* Footer actions */}
- <div className="flex items-center gap-2 px-3 py-2 border-t border-cyan-500/20 shrink-0">
- <button
- type="button"
- onClick={() => onFocusInWorld?.(app.id)}
- className="flex-1 min-h-[44px] font-pixel text-[10px] text-cyan-400 tracking-wider border border-cyan-500/40 rounded px-2 py-2 hover:bg-cyan-500/10 transition-colors"
- title="Focus this building in the world"
- >
- FOCUS BUILDING {'>'}
- </button>
- <button
- type="button"
- onClick={onClose}
- className="min-h-[44px] font-pixel text-[10px] text-gray-400 tracking-wider border border-cyan-500/20 rounded px-2 py-2 hover:text-cyan-400 hover:border-cyan-500/40 transition-colors"
- title="Return to the city overview"
- >
- BACK
- </button>
- </div>
- </div>
- </div>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldFocusPanel.test.jsx b/client/src/components/openworld/OpenWorldFocusPanel.test.jsx
deleted file mode 100644
index 2927930d34..0000000000
--- a/client/src/components/openworld/OpenWorldFocusPanel.test.jsx
+++ /dev/null
@@ -1,77 +0,0 @@
-import { describe, it, expect, vi } from 'vitest';
-import { render, screen, fireEvent } from '@testing-library/react';
-import OpenWorldFocusPanel from './OpenWorldFocusPanel';
-
-const app = {
- id: 'alpha',
- name: 'Alpha Service',
- overallStatus: 'online',
- processes: [{ name: 'web' }, { name: 'worker' }],
- pm2Status: {
- web: { status: 'online', cpu: 12.5, memory: 150 * 1024 * 1024, uptime: 3 * 24 * 60 * 60 * 1000 },
- worker: { status: 'errored', restarts: 2, unstableRestarts: 1 },
- },
-};
-
-describe('OpenWorldFocusPanel', () => {
- it('renders app name, status, process summary and unhealthy processes', () => {
- render(<OpenWorldFocusPanel app={app} agents={[]} />);
- expect(screen.getByText('Alpha Service')).toBeTruthy();
- // Status pill reads ONLINE (unique — the process stat block uses RUNNING).
- expect(screen.getByText('ONLINE')).toBeTruthy();
- expect(screen.getByText('RUNNING')).toBeTruthy();
- // The unhealthy worker process is listed.
- expect(screen.getByText('worker')).toBeTruthy();
- expect(screen.getByText('errored')).toBeTruthy();
- });
-
- it('lists active/failed agents assigned to the app', () => {
- const agents = [
- { agentId: 'a1', status: 'running', task: 'Refactor module' },
- { agentId: 'a2', status: 'completed', task: 'Old done task' },
- { agentId: 'a3', state: 'error', task: 'Broke the build' },
- ];
- render(<OpenWorldFocusPanel app={app} agents={agents} />);
- expect(screen.getByText('Refactor module')).toBeTruthy();
- // A failed agent whose only signal is state:'error' is still surfaced.
- expect(screen.getByText('Broke the build')).toBeTruthy();
- // A completed (non-active) agent is filtered out.
- expect(screen.queryByText('Old done task')).toBeNull();
- });
-
- it('renders live CPU/MEM/uptime telemetry from pm2Status', () => {
- render(<OpenWorldFocusPanel app={app} agents={[]} />);
- // Only the online process counts toward live usage.
- expect(screen.getByText('12.5%')).toBeTruthy();
- expect(screen.getByText('150 MB')).toBeTruthy();
- expect(screen.getByText('3d 0h')).toBeTruthy();
- });
-
- it('omits the telemetry row for apps with no PM2 status', () => {
- render(<OpenWorldFocusPanel app={{ id: 'x', name: 'X', overallStatus: 'n/a' }} agents={[]} />);
- expect(screen.queryByText('CPU')).toBeNull();
- });
-
- it('fires onFocusInWorld with the app id from the explicit in-world action', () => {
- const onFocusInWorld = vi.fn();
- render(<OpenWorldFocusPanel app={app} agents={[]} onFocusInWorld={onFocusInWorld} />);
- fireEvent.click(screen.getByTitle('Focus this building in the world'));
- expect(onFocusInWorld).toHaveBeenCalledWith('alpha');
- });
-
- it('fires onClose from the close and back actions', () => {
- const onClose = vi.fn();
- render(<OpenWorldFocusPanel app={app} agents={[]} onClose={onClose} />);
- fireEvent.click(screen.getByLabelText('Close focus and return to overview'));
- fireEvent.click(screen.getByTitle('Return to the city overview'));
- expect(onClose).toHaveBeenCalledTimes(2);
- });
-
- it('renders the not-found fallback with a return-to-overview action', () => {
- const onClose = vi.fn();
- render(<OpenWorldFocusPanel app={null} notFound onClose={onClose} />);
- expect(screen.getByText('BUILDING NOT FOUND')).toBeTruthy();
- fireEvent.click(screen.getByText(/RETURN TO OVERVIEW/));
- expect(onClose).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/client/src/components/openworld/OpenWorldGalaxySky.jsx b/client/src/components/openworld/OpenWorldGalaxySky.jsx
deleted file mode 100644
index c54df852cf..0000000000
--- a/client/src/components/openworld/OpenWorldGalaxySky.jsx
+++ /dev/null
@@ -1,71 +0,0 @@
-import { useEffect } from 'react';
-import { useThree, useLoader } from '@react-three/fiber';
-import * as THREE from 'three';
-import { openWorldDayMix } from './openWorldConstants';
-
-const GALAXY_TEXTURE_URL = '/sky/city-night-galaxy-8k.jpg';
-// Artistic yaw so the brightest stretch of the Milky Way band sits behind the city
-// rather than dead-ahead. Applied to both the visible background and the IBL probe so
-// reflections line up with what's on screen.
-const GALAXY_ROTATION = new THREE.Euler(0, -Math.PI * 0.18, 0);
-
-// Brightness knobs (multiplied by how deep into night we are). The panorama is a real,
-// dark Milky Way, so the background gets a >1 lift to read clearly against the night sky;
-// the IBL multiplier controls how strongly the galaxy tints the metallic facades.
-const BACKGROUND_INTENSITY = 2.4;
-const ENVIRONMENT_INTENSITY = 1.3;
-
-// The night sky is the equirectangular galaxy panorama wired through three.js's
-// environment system the way an HDRI is: the texture is mapped equirectangular, run
-// through a PMREMGenerator, and assigned to BOTH scene.background (the 360° spheremap
-// backdrop, visible in every camera direction) AND scene.environment (image-based
-// lighting, so the galaxy tints reflections/lighting on the PBR building + ground
-// materials). drei's <Environment files> can't load a .png panorama (its loader only
-// recognises .hdr/.exr/cube), so we do the PMREM wiring directly — the canonical setup.
-//
-// Mounted only at night (OpenWorldScene gates on !showGradientBackground), so the 2.8MB
-// panorama isn't fetched/decoded or PMREM-processed in daylight.
-export default function OpenWorldGalaxySky({ settings }) {
- const { gl, scene } = useThree();
- const texture = useLoader(THREE.TextureLoader, GALAXY_TEXTURE_URL);
- const nightOpacity = Math.max(0, Math.min(1, 1 - openWorldDayMix(settings)));
-
- // Build the PMREM environment once per texture and bind it to the scene; restore the
- // previous background/environment (and free the GPU targets) when night ends / unmounts.
- useEffect(() => {
- texture.mapping = THREE.EquirectangularReflectionMapping;
- texture.colorSpace = THREE.SRGBColorSpace;
- texture.needsUpdate = true;
-
- const pmrem = new THREE.PMREMGenerator(gl);
- const envTarget = pmrem.fromEquirectangular(texture);
-
- const prevBackground = scene.background;
- const prevEnvironment = scene.environment;
- scene.background = texture;
- scene.environment = envTarget.texture;
- scene.backgroundRotation.copy(GALAXY_ROTATION);
- scene.environmentRotation.copy(GALAXY_ROTATION);
-
- return () => {
- scene.background = prevBackground;
- scene.environment = prevEnvironment;
- // Reset the intensities to three's defaults so the daytime color background (set by
- // OpenWorldScene once this unmounts) isn't left dimmed by the last night value.
- scene.backgroundIntensity = 1;
- scene.environmentIntensity = 1;
- envTarget.dispose();
- pmrem.dispose();
- };
- }, [gl, scene, texture]);
-
- // Cross-fade with daylight without rebuilding the PMREM map: scale the background and
- // the IBL by how deep into night we are. The panorama is mostly dark space, so the IBL
- // gets a >1 multiplier to read as a light source on metallic facades.
- useEffect(() => {
- scene.backgroundIntensity = nightOpacity * BACKGROUND_INTENSITY;
- scene.environmentIntensity = nightOpacity * ENVIRONMENT_INTENSITY;
- }, [scene, nightOpacity]);
-
- return null;
-}
diff --git a/client/src/components/openworld/OpenWorldGoalMonuments.jsx b/client/src/components/openworld/OpenWorldGoalMonuments.jsx
deleted file mode 100644
index 365559cc4c..0000000000
--- a/client/src/components/openworld/OpenWorldGoalMonuments.jsx
+++ /dev/null
@@ -1,265 +0,0 @@
-import { useMemo, useRef } from 'react';
-import { useFrame } from '@react-three/fiber';
-import OpenWorldTubeLine from './OpenWorldTubeLine';
-import { PIXEL_FONT_URL, openWorldDayMix } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import OpenWorldLabel from './OpenWorldLabel';
-import { computeGoalMonuments, computeGoalForest, MONUMENTS, FOREST } from '../../utils/openWorldGoalMonuments';
-
-// OpenWorld's goal monuments (roadmap 2.7): each life goal is a structure in a
-// northeast monument district. Active goals are construction sites — a built base topped
-// by a translucent scaffold cage whose fill tracks progress. Completed goals are polished,
-// fully-built monuments that shimmer. Stalled (active-but-quiet) and abandoned goals read
-// dim. When a goal carries milestones, the tower is segmented into ordered floors so a
-// partially-built monument shows WHICH milestones are done (solid floor = complete,
-// translucent scaffold rung = pending). When goals form a parent→child hierarchy, the
-// district switches to a goal-tree layout: each root goal is a central spire with its
-// children clustered in a ring and a link drawn up to the parent apex. Mirrors
-// OpenWorldBackupVault / OpenWorldHealthTower.
-
-// Render the body of a monument: either milestone floors (when the goal has milestones)
-// or the plain built/scaffold split. `shimmerRef`/`isShimmer` wires the completed-monument
-// pulse onto whichever mesh carries the topmost built portion.
-function MonumentBody({ monument, shimmerRef, isShimmer }) {
- const { tintStructure } = useOpenWorldPalette();
- const { height, width, color, opacity, intensity, built, completeness, segments } = monument;
-
- // Milestone floors: one box per milestone, solid+emissive when done, wireframe scaffold
- // when pending. The top floor carries the shimmer — shimmer is only ever assigned to a
- // completed (built) monument, so all its floors render solid and the topmost is the apex.
- if (segments && segments.length > 0) {
- return (
- <>
- {segments.map((seg, i) => {
- const doneFloor = seg.done || built;
- const floorH = Math.max(0.15, seg.segHeight * 0.86); // gap between floors
- const carriesShimmer = isShimmer && i === segments.length - 1;
- return (
- <mesh
- key={seg.id}
- ref={carriesShimmer ? shimmerRef : undefined}
- position={[0, 0.4 + seg.cy, 0]}
- >
- <boxGeometry args={doneFloor ? [width, floorH, width] : [width * 1.05, floorH, width * 1.05]} />
- <meshStandardMaterial
- color={doneFloor ? (built ? tintStructure('#0d1a12') : tintStructure('#0c1424')) : color}
- emissive={color}
- emissiveIntensity={doneFloor ? intensity : intensity * 0.45}
- metalness={doneFloor ? (built ? 0.7 : 0.4) : 0.2}
- roughness={doneFloor ? (built ? 0.35 : 0.6) : 0.8}
- wireframe={!doneFloor}
- transparent={opacity < 1 || !doneFloor}
- opacity={doneFloor ? opacity : opacity * 0.55}
- toneMapped={false}
- />
- </mesh>
- );
- })}
- </>
- );
- }
-
- // No milestones: original built-base + scaffold-cap split.
- const builtHeight = Math.max(0.4, height * (built ? 1 : completeness));
- const scaffoldHeight = Math.max(0, height - builtHeight);
- return (
- <>
- <mesh ref={isShimmer ? shimmerRef : undefined} position={[0, 0.4 + builtHeight / 2, 0]}>
- <boxGeometry args={[width, builtHeight, width]} />
- <meshStandardMaterial
- color={built ? tintStructure('#0d1a12') : tintStructure('#0c1424')}
- emissive={color}
- emissiveIntensity={intensity}
- metalness={built ? 0.7 : 0.4}
- roughness={built ? 0.35 : 0.6}
- transparent={opacity < 1}
- opacity={opacity}
- toneMapped={false}
- />
- </mesh>
- {scaffoldHeight > 0.3 && (
- <mesh position={[0, 0.4 + builtHeight + scaffoldHeight / 2, 0]}>
- <boxGeometry args={[width * 1.05, scaffoldHeight, width * 1.05]} />
- <meshStandardMaterial color={color} emissive={color} emissiveIntensity={intensity * 0.5} wireframe transparent opacity={opacity * 0.6} toneMapped={false} />
- </mesh>
- )}
- </>
- );
-}
-
-function Monument({ monument, shimmerRef, isShimmer, dayMix = 0 }) {
- const { tintStructure } = useOpenWorldPalette();
- const { height, width, color, opacity, intensity, position, milestoneTotal, milestoneDone, isSpire } = monument;
-
- return (
- <group position={position}>
- {/* Plinth */}
- <mesh position={[0, 0.2, 0]}>
- <boxGeometry args={[width * 1.4, 0.4, width * 1.4]} />
- <meshStandardMaterial color={tintStructure('#0a0e16')} emissive={color} emissiveIntensity={0.1 * intensity + 0.04} metalness={0.6} roughness={0.5} />
- </mesh>
-
- <MonumentBody monument={monument} shimmerRef={shimmerRef} isShimmer={isShimmer} />
-
- {/* Title + progress label above the structure */}
- <OpenWorldLabel position={[0, height + 1.4, 0]} fontSize={isSpire ? 0.85 : 0.7} color={color} dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={9} fillOpacity={opacity}>
- {monument.title}
- </OpenWorldLabel>
- <OpenWorldLabel position={[0, height + 0.7, 0]} fontSize={0.55} color="#94a3b8" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={9} fillOpacity={opacity}>
- {monument.built ? 'COMPLETE' : milestoneTotal > 0 ? `${milestoneDone}/${milestoneTotal} STEPS` : `${Math.round(monument.progress)}%`}
- </OpenWorldLabel>
- </group>
- );
-}
-
-// Goal-tree hierarchy: root spires + child rings + apex links. Used when goals form a
-// parent→child structure; otherwise the flat row renders instead. The layout shows two
-// visible levels; a child's deeper sub-tree is summarized by a "+N UNDER" badge and roots
-// past the cap fold into a "+N MORE GOALS" marker, so nothing is silently dropped.
-function GoalForest({ forest, shimmerRef, shimmerId, dayMix = 0 }) {
- return (
- <group>
- {forest.clusters.map((cluster) => (
- <group key={cluster.spire.id}>
- <Monument monument={cluster.spire} shimmerRef={shimmerRef} isShimmer={cluster.spire.id === shimmerId} dayMix={dayMix} />
- {cluster.children.map((child) => (
- <group key={child.id}>
- <Monument monument={child} shimmerRef={shimmerRef} isShimmer={child.id === shimmerId} dayMix={dayMix} />
- {child.descendantCount > 0 && (
- <OpenWorldLabel position={[child.position[0], child.height + 1.9, child.position[2]]} fontSize={0.42} color="#64748b" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={9}>
- {`+${child.descendantCount} UNDER`}
- </OpenWorldLabel>
- )}
- </group>
- ))}
- {cluster.links.map((link) => (
- <OpenWorldTubeLine
- key={link.childId}
- points={[link.from, link.to]}
- color={cluster.spire.color}
- radius={0.06}
- opacity={0.4}
- />
- ))}
- {cluster.childOverflow > 0 && (
- <OpenWorldLabel position={[cluster.spire.position[0], cluster.spire.height + 2.1, cluster.spire.position[2]]} fontSize={0.5} color="#94a3b8" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={9}>
- {`+${cluster.childOverflow} SUB-GOALS`}
- </OpenWorldLabel>
- )}
- </group>
- ))}
-
- {/* Root overflow — top-level goal trees past the cap, mirroring the flat row's marker */}
- {forest.rootOverflow > 0 && forest.clusters.length > 0 && (
- <OpenWorldLabel
- position={[
- forest.clusters[forest.clusters.length - 1].spire.position[0] + FOREST.clusterSpacing / 2,
- MONUMENTS.minHeight + 2,
- forest.base[2],
- ]}
- fontSize={0.6}
- color="#94a3b8"
- dayMix={dayMix}
- anchorX="center"
- anchorY="middle"
- font={PIXEL_FONT_URL}
- maxWidth={12}
- >
- {`+${forest.rootOverflow} MORE GOALS`}
- </OpenWorldLabel>
- )}
- </group>
- );
-}
-
-export default function OpenWorldGoalMonuments({ goals, settings }) {
- const { tintStructure } = useOpenWorldPalette();
- // The API returns `{ goals: [...] }`; accept either the wrapper or a bare array.
- const list = Array.isArray(goals) ? goals : goals?.goals;
- const district = useMemo(() => computeGoalMonuments(list), [list]);
- const forest = useMemo(() => computeGoalForest(list), [list]);
- const shimmerRef = useRef();
-
- // Render the hierarchy view when goals actually form a parent→child tree; otherwise the
- // flat row. This keeps a flat goal set looking exactly as before while opting trees into
- // the spire layout automatically.
- const useForest = forest.hasHierarchy;
-
- // Honor the quality dial: drop the completed-monument shimmer on the lowest preset,
- // but keep the static glow so each goal's status stays legible.
- const animate = (settings?.particleDensity ?? 1) >= 0.5;
- const dayMix = openWorldDayMix(settings);
-
- // Pick the first completed monument to carry the shimmer (one per-frame ref mutation).
- // In forest mode, scan spires then children; in row mode, scan the row.
- const shimmer = useMemo(() => {
- if (useForest) {
- for (const cluster of forest.clusters) {
- if (cluster.spire.built) return { id: cluster.spire.id, intensity: cluster.spire.intensity };
- const child = cluster.children.find((c) => c.built);
- if (child) return { id: child.id, intensity: child.intensity };
- }
- return null;
- }
- const m = district.monuments.find((x) => x.built);
- return m ? { id: m.id, intensity: m.intensity } : null;
- }, [useForest, forest.clusters, district.monuments]);
-
- useFrame(({ clock }) => {
- if (!shimmerRef.current || !shimmer) return;
- if (!animate) {
- // Quality dial dropped below the pulse threshold (or the shimmer target changed):
- // settle the mesh back to its static base glow so it can't freeze mid-pulse at an
- // elevated emissive intensity.
- shimmerRef.current.material.emissiveIntensity = shimmer.intensity;
- return;
- }
- const pulse = (Math.sin(clock.getElapsedTime() * 1.6) + 1) / 2; // 0..1
- shimmerRef.current.material.emissiveIntensity = shimmer.intensity + pulse * 0.5;
- });
-
- if (!district.hasData) return null;
-
- const { base, monuments, overflow, total, completedCount } = district;
-
- return (
- <group>
- {useForest ? (
- <GoalForest forest={forest} shimmerRef={shimmerRef} shimmerId={shimmer?.id} dayMix={dayMix} />
- ) : (
- <>
- {monuments.map((monument) => (
- <Monument
- key={monument.id}
- monument={monument}
- shimmerRef={shimmerRef}
- isShimmer={monument.id === shimmer?.id}
- dayMix={dayMix}
- />
- ))}
-
- {/* Overflow marker — "+N MORE" past the end of the row */}
- {overflow && (
- <group position={overflow.position}>
- <mesh position={[0, MONUMENTS.minHeight / 2, 0]}>
- <boxGeometry args={[MONUMENTS.baseWidth, MONUMENTS.minHeight, MONUMENTS.baseWidth]} />
- <meshStandardMaterial color={tintStructure('#0c1424')} emissive="#64748b" emissiveIntensity={0.2} metalness={0.5} roughness={0.6} />
- </mesh>
- <OpenWorldLabel position={[0, MONUMENTS.minHeight + 1, 0]} fontSize={0.6} color="#94a3b8" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={9}>
- {`+${overflow.count} MORE`}
- </OpenWorldLabel>
- </group>
- )}
- </>
- )}
-
- {/* District title behind the row */}
- <OpenWorldLabel position={[base[0], 16, base[2] - 3]} fontSize={1.4} color="#22c55e" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={30}>
- GOALS
- </OpenWorldLabel>
- <OpenWorldLabel position={[base[0], 15, base[2] - 3]} fontSize={0.8} color="#94a3b8" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={30}>
- {`${completedCount}/${total} ACHIEVED`}
- </OpenWorldLabel>
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldGrass.jsx b/client/src/components/openworld/OpenWorldGrass.jsx
deleted file mode 100644
index 054f0271e8..0000000000
--- a/client/src/components/openworld/OpenWorldGrass.jsx
+++ /dev/null
@@ -1,146 +0,0 @@
-import { useMemo, useLayoutEffect, useRef } from 'react';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { mixHex, openWorldShowDetail, seededRand } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import { NATURE_PATCHES } from './OpenWorldNature';
-import { WORLD } from '../../utils/openWorldPlan';
-
-// Grass is placed in small readable meadows rather than across every square metre. That
-// keeps the low-poly look intentional, protects the road silhouettes, and gives the rover
-// a visual reason to leave the paved arrival lane and explore the edges of town.
-const GRASS_FIELDS = [
- { id: 'arrival-west', position: [-24, 0, 44], radius: 8.5 },
- { id: 'arrival-east', position: [24, 0, 44], radius: 8.5 },
- { id: 'west-greenway', position: [-45, 0, 20], radius: 7.5 },
- { id: 'east-greenway', position: [45, 0, 20], radius: 7.5 },
- { id: 'memory-edge', position: [-54, 0, -31], radius: 6.5 },
- { id: 'goal-edge', position: [52, 0, -39], radius: 7 },
- { id: 'shoreline-west', position: [-31, 0, -51], radius: 6 },
- { id: 'shoreline-east', position: [31, 0, -51], radius: 6 },
- ...NATURE_PATCHES.map((patch) => ({
- id: patch.id,
- position: patch.position,
- radius: 2.4 + patch.scale * 1.7,
- })),
-];
-
-const dummy = new THREE.Object3D();
-const GRASS_BASE_Y = WORLD.groundY + 0.08;
-
-function grassCount(settings) {
- // Keep a small signature patch on the low tier. Adaptive quality may downshift on
- // integrated GPUs, but the Vibes world should still read as a windy meadow rather
- // than a bare debug plane.
- if (settings?.effectiveTier === 'low') return 140;
- if (!openWorldShowDetail(settings)) return 0;
- if (settings?.effectiveTier === 'ultra') return 680;
- if (settings?.effectiveTier === 'medium') return 320;
- return 520;
-}
-
-function createBlades(count) {
- const rand = seededRand(9117);
- return Array.from({ length: count }, (_, index) => {
- const field = GRASS_FIELDS[index % GRASS_FIELDS.length];
- const angle = rand() * Math.PI * 2;
- const radius = Math.sqrt(rand()) * field.radius;
- return {
- x: field.position[0] + Math.cos(angle) * radius,
- z: field.position[2] + Math.sin(angle) * radius,
- height: 0.42 + rand() * 0.5,
- width: 0.7 + rand() * 0.42,
- yaw: rand() * Math.PI * 2,
- phase: rand() * Math.PI * 2,
- };
- });
-}
-
-function writeMatrices(ref, blades) {
- if (!ref.current || typeof ref.current.setMatrixAt !== 'function') return;
- blades.forEach((blade, index) => {
- dummy.position.set(blade.x, GRASS_BASE_Y + blade.height * 0.5, blade.z);
- dummy.rotation.set(0, blade.yaw, 0);
- dummy.scale.set(blade.width, blade.height, blade.width);
- dummy.updateMatrix();
- ref.current.setMatrixAt(index, dummy.matrix);
- });
- if (ref.current.instanceMatrix) {
- ref.current.instanceMatrix.needsUpdate = true;
- }
-}
-
-export default function OpenWorldGrass({ settings }) {
- const { accent, surface, lowPoly } = useOpenWorldPalette();
- const count = grassCount(settings);
- const blades = useMemo(() => createBlades(count), [count]);
- const ref = useRef();
- const grassColor = mixHex('#4f8a5d', accent, 0.16);
- const timeUniformRef = useRef({ value: 0 });
-
- useLayoutEffect(() => {
- writeMatrices(ref, blades);
- if (typeof ref.current?.computeBoundingSphere === 'function') {
- ref.current.computeBoundingSphere();
- }
- }, [blades, lowPoly]);
-
- const onBeforeCompile = useMemo(() => (shader) => {
- shader.uniforms.uGrassTime = timeUniformRef.current;
- shader.vertexShader = `
- uniform float uGrassTime;
- varying float vBladeHeight;
- ` + shader.vertexShader;
- shader.vertexShader = shader.vertexShader.replace(
- '#include <begin_vertex>',
- `
- #include <begin_vertex>
- // Cone geometry height 1 is centered at y=0, so base is at -0.5 and tip is at +0.5.
- float bladeHeightNorm = clamp(position.y + 0.5, 0.0, 1.0);
- vBladeHeight = bladeHeightNorm;
- float sway = bladeHeightNorm * bladeHeightNorm;
-
- vec3 instPos = vec3(instanceMatrix[3][0], instanceMatrix[3][1], instanceMatrix[3][2]);
- float gust = sin(uGrassTime * 0.75 + instPos.x * 0.05 + instPos.z * 0.04) * 0.32
- + sin(uGrassTime * 1.6 + instPos.x * 0.12) * 0.1;
-
- transformed.x += gust * 0.38 * sway;
- transformed.z += gust * 0.62 * sway;
- `
- );
- shader.fragmentShader = `
- varying float vBladeHeight;
- ` + shader.fragmentShader;
- shader.fragmentShader = shader.fragmentShader.replace(
- '#include <color_fragment>',
- `
- #include <color_fragment>
- vec3 bladeBase = diffuseColor.rgb * 0.52;
- vec3 bladeTip = diffuseColor.rgb * 1.28 + vec3(0.06, 0.10, 0.01);
- diffuseColor.rgb = mix(bladeBase, bladeTip, vBladeHeight);
- `
- );
- }, []);
-
- useFrame(({ clock }) => {
- if (lowPoly && blades.length > 0) {
- timeUniformRef.current.value = clock.getElapsedTime();
- }
- });
-
- if (!lowPoly || blades.length === 0) return null;
-
- return (
- <instancedMesh key={blades.length} ref={ref} args={[undefined, undefined, blades.length]}>
- <coneGeometry args={[0.12, 1, 3]} />
- <meshStandardMaterial
- {...surface}
- color={grassColor}
- roughness={1}
- metalness={0}
- side={THREE.DoubleSide}
- onBeforeCompile={onBeforeCompile}
- />
- </instancedMesh>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldGrass.test.jsx b/client/src/components/openworld/OpenWorldGrass.test.jsx
deleted file mode 100644
index 07b57fc0bf..0000000000
--- a/client/src/components/openworld/OpenWorldGrass.test.jsx
+++ /dev/null
@@ -1,27 +0,0 @@
-import { describe, it, expect, vi } from 'vitest';
-import { render } from '@testing-library/react';
-
-vi.mock('@react-three/fiber', () => ({ useFrame: () => {} }));
-vi.mock('./OpenWorldPaletteContext', () => ({
- useOpenWorldPalette: () => ({
- accent: '#22d3ee',
- surface: {},
- lowPoly: true,
- }),
-}));
-
-import OpenWorldGrass from './OpenWorldGrass';
-
-describe('OpenWorldGrass', () => {
- it('renders instancedMesh on lowPoly mode', () => {
- const { container } = render(<OpenWorldGrass settings={{ effectiveTier: 'high' }} />);
- const mesh = container.getElementsByTagName('instancedMesh');
- expect(mesh.length).toBe(1);
- });
-
- it('scales blade count per quality tier', () => {
- const { container: lowContainer } = render(<OpenWorldGrass settings={{ effectiveTier: 'low' }} />);
- const lowMesh = lowContainer.getElementsByTagName('instancedMesh');
- expect(lowMesh.length).toBe(1);
- });
-});
diff --git a/client/src/components/openworld/OpenWorldHealthTower.jsx b/client/src/components/openworld/OpenWorldHealthTower.jsx
deleted file mode 100644
index c3d3552d60..0000000000
--- a/client/src/components/openworld/OpenWorldHealthTower.jsx
+++ /dev/null
@@ -1,100 +0,0 @@
-import { useMemo, useRef } from 'react';
-import { useFrame } from '@react-three/fiber';
-import { PIXEL_FONT_URL, openWorldDayMix } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import OpenWorldLabel from './OpenWorldLabel';
-import { computeHealthTower } from '../../utils/openWorldHealthTower';
-
-// OpenWorld's biometric vitals tower (roadmap 2.9): a stacked cylindrical landmark in a
-// far-southeast wellness district. Each tier is one Apple Health metric (heart rate, steps,
-// active calories, sleep) whose height and glow track that metric's latest value normalized
-// against a target. A metric with no data reads as a thin dim disc (absent) — distinct from
-// a present-but-zero value, which keeps its lit color. The heart-rate tier pulses like a
-// heartbeat, faster as the rate climbs. Mirrors OpenWorldBackupVault / OpenWorldTaskQueue.
-function Segment({ segment, baseRadius, isHeart, heartRef }) {
- const { tintStructure } = useOpenWorldPalette();
- const { height, color, intensity } = segment;
- return (
- <mesh ref={isHeart ? heartRef : undefined} position={[0, segment.y, 0]}>
- <cylinderGeometry args={[baseRadius, baseRadius, height, 32]} />
- <meshStandardMaterial
- color={segment.present ? tintStructure('#0c1620') : tintStructure('#0a0e16')}
- emissive={color}
- emissiveIntensity={intensity}
- metalness={0.5}
- roughness={0.5}
- toneMapped={false}
- />
- </mesh>
- );
-}
-
-export default function OpenWorldHealthTower({ healthMetrics, settings }) {
- const { tintStructure } = useOpenWorldPalette();
- const tower = useMemo(() => computeHealthTower(healthMetrics), [healthMetrics]);
- const heartRef = useRef();
-
- // Honor the quality dial: drop the heartbeat pulse on the lowest preset, but keep the
- // static glow so the vitals stay legible.
- const animate = (settings?.particleDensity ?? 1) >= 0.5;
- const dayMix = openWorldDayMix(settings);
-
- useFrame(({ clock }) => {
- if (!animate || !heartRef.current || !tower.heartPresent) return;
- // Heartbeat: a higher heart-rate level beats faster. Base intensity comes from the
- // view-model so a present-but-low reading still glows; the pulse rides on top.
- const bpm = 2.2 + tower.heartLevel * 3.5;
- const pulse = (Math.sin(clock.getElapsedTime() * bpm) + 1) / 2; // 0..1
- heartRef.current.material.emissiveIntensity = tower.heartIntensity + pulse * 0.6;
- });
-
- const { position, baseRadius, segments, totalHeight, hasData } = tower;
-
- return (
- <group position={position}>
- {/* Plinth the tower rises from */}
- <mesh position={[0, 0.3, 0]}>
- <cylinderGeometry args={[baseRadius * 1.3, baseRadius * 1.45, 0.6, 32]} />
- <meshStandardMaterial color={tintStructure('#0a0e16')} emissive="#22c55e" emissiveIntensity={0.08} metalness={0.6} roughness={0.5} />
- </mesh>
-
- {/* Stacked metric segments — lifted above the plinth */}
- <group position={[0, 0.6, 0]}>
- {segments.map((segment) => (
- <Segment
- key={segment.key}
- segment={segment}
- baseRadius={baseRadius}
- isHeart={segment.key === 'heart_rate'}
- heartRef={heartRef}
- />
- ))}
-
- {/* Per-segment side labels so each tier is identifiable */}
- {segments.map((segment) => (
- <OpenWorldLabel
- key={`label-${segment.key}`}
- position={[baseRadius + 0.6, segment.y, 0]}
- fontSize={0.55}
- color={segment.present ? segment.color : '#64748b'}
- dayMix={dayMix}
- anchorX="left"
- anchorY="middle"
- font={PIXEL_FONT_URL}
- maxWidth={14}
- >
- {segment.present ? `${segment.label} ${segment.value}${segment.unit ? ' ' + segment.unit : ''}` : `${segment.label} —`}
- </OpenWorldLabel>
- ))}
-
- {/* Tower title + status above the stack */}
- <OpenWorldLabel position={[0, totalHeight + 1.6, 0]} fontSize={1.2} color="#22c55e" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={18}>
- VITALS
- </OpenWorldLabel>
- <OpenWorldLabel position={[0, totalHeight + 0.8, 0]} fontSize={0.8} color="#94a3b8" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={18}>
- {hasData ? `${tower.presentCount}/${segments.length} TRACKED` : 'NO HEALTH DATA'}
- </OpenWorldLabel>
- </group>
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldHud.jsx b/client/src/components/openworld/OpenWorldHud.jsx
deleted file mode 100644
index 0376a9709b..0000000000
--- a/client/src/components/openworld/OpenWorldHud.jsx
+++ /dev/null
@@ -1,416 +0,0 @@
-import { useState, useEffect, useMemo, useRef } from 'react';
-import { useNavigate, useLocation } from 'react-router';
-import { Camera, Compass, History, Map as MapIcon, Settings } from 'lucide-react';
-import { noPointerFocusSurfaceProps } from '../../lib/a11yKeyboard';
-import OpenWorldIntelPane from './OpenWorldIntelPane';
-import OpenWorldFocusPanel from './OpenWorldFocusPanel';
-import OpenWorldAgentBar from './OpenWorldAgentBar';
-import OpenWorldFilterBar from './OpenWorldFilterBar';
-import OpenWorldXpBadge from './OpenWorldXpBadge';
-import OpenWorldMiniMap from './OpenWorldMiniMap';
-import OpenWorldHudCompact from './OpenWorldHudCompact';
-import OpenWorldInteractionPrompt from './OpenWorldInteractionPrompt';
-import OpenWorldSpeedometer from './OpenWorldSpeedometer';
-import { HealthBar, getHealthSentinel, metricColor } from './openWorldHudBits';
-import useOpenWorldViewport from '../../hooks/useOpenWorldViewport';
-import { formatClockTime } from '../../utils/formatters';
-
-// The first drop-in hint is intentionally a small invitation, not a manual. The full
-// control reference remains discoverable from the settings drawer and keyboard behavior.
-function ControlsHint({ visible, isDesktop }) {
- const [show, setShow] = useState(false);
- const hasShownRef = useRef(false);
-
- useEffect(() => {
- if (visible && !hasShownRef.current) {
- hasShownRef.current = true;
- setShow(true);
- const timer = setTimeout(() => setShow(false), 4500);
- return () => clearTimeout(timer);
- }
- if (!visible) setShow(false);
- }, [visible]);
-
- if (!show || !isDesktop) return null;
-
- return (
- <div className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 pointer-events-none animate-in fade-in duration-500">
- <div className="openworld-hud-panel px-5 py-4 text-center">
- <div className="openworld-hud-eyebrow mb-2">WELCOME TO THE VILLAGE</div>
- <div className="mb-3 font-pixel text-[9px] tracking-[0.14em] text-[rgb(var(--port-text))]">
- TAKE THE LONG WAY · THERE IS ALWAYS SOMETHING AROUND THE BEND
- </div>
- <div className="mb-3 flex items-center justify-center gap-1.5">
- {['W', 'A', 'S', 'D'].map((key) => (
- <span key={key} className="flex h-7 w-7 items-center justify-center rounded-lg border border-[rgb(var(--port-accent)/.28)] bg-[rgb(var(--port-accent)/.08)] font-pixel text-[10px] text-[rgb(var(--port-text))]">
- {key}
- </span>
- ))}
- </div>
- <div className="font-pixel text-[8px] tracking-wide text-[rgb(var(--port-text-muted))]">
- WASD DRIVE <span className="mx-1 opacity-50">·</span> SHIFT BOOST <span className="mx-1 opacity-50">·</span> F VISIT <span className="mx-1 opacity-50">·</span> SPACE HOP <span className="mx-1 opacity-50">·</span> M VILLAGE MAP
- </div>
- </div>
- </div>
- );
-}
-
-function SystemMetric({ label, value }) {
- return (
- <div className="flex items-baseline justify-between gap-1">
- <span className="font-pixel text-[8px] tracking-[0.12em] text-[rgb(var(--port-text-muted))]">{label}</span>
- <span className={`font-pixel text-[9px] tracking-wide ${metricColor(value)}`}>
- {value != null ? `${value}%` : '—'}
- </span>
- </div>
- );
-}
-
-// The HUD floats over a keyboard-driven world: a pointer click must not leave
-// focus parked on the button, or Space stops jumping and starts re-pressing it.
-function HudAction({ icon: Icon, label, hint, active, primary = false, onClick }) {
- return (
- <button
- type="button"
- onClick={onClick}
-
- title={label}
- aria-label={label}
- aria-pressed={active === undefined ? undefined : active}
- className={`openworld-hud-action ${primary ? 'openworld-hud-action--primary' : ''}`}
- >
- <Icon size={16} strokeWidth={1.8} aria-hidden="true" />
- <span className="openworld-hud-action-copy">{label}</span>
- {hint && <span className="openworld-hud-action-hint">{hint}</span>}
- </button>
- );
-}
-
-export default function OpenWorldHud({
- cosStatus,
- cosAgents,
- agentMap,
- eventLogs,
- connected,
- apps,
- reviewCounts,
- instances,
- productivityData,
- systemHealth,
- notificationCounts,
- character,
- filter,
- onFilterChange,
- onJumpToFirst,
- matchCount,
- onToggleExploration,
- explorationMode,
- onSelectApp,
- onEnterPhotoMode,
- onEnterPlayback,
- focusedAppId,
- focusedApp,
- focusNotFound,
- focusAgents,
- onCloseFocus,
- onFocusInWorld,
- onOpenFastTravel,
- onOpenDestination,
- onAttentionItem,
- activeRegion,
- proximityTarget,
- playerPose = null,
- collectedCount = 0,
- totalShards = 18,
-}) {
- const isFocused = Boolean(focusedApp || focusNotFound);
- const navigate = useNavigate();
- const location = useLocation();
- const { isDesktop } = useOpenWorldViewport();
- const [time, setTime] = useState(new Date());
- const [uptimeSeconds, setUptimeSeconds] = useState(0);
-
- useEffect(() => {
- const interval = setInterval(() => {
- setTime(new Date());
- setUptimeSeconds(prev => prev + 1);
- }, 1000);
- return () => clearInterval(interval);
- }, []);
-
- const { activeApps, stoppedApps, totalApps, archivedApps } = useMemo(() => {
- const acc = { activeApps: 0, stoppedApps: 0, totalApps: 0, archivedApps: 0 };
- (apps || []).forEach(a => {
- if (a.archived) { acc.archivedApps++; return; }
- acc.totalApps++;
- if (a.overallStatus === 'online') acc.activeApps++;
- else if (a.overallStatus === 'stopped') acc.stoppedApps++;
- });
- return acc;
- }, [apps]);
-
- const onlineRatio = totalApps > 0 ? activeApps / totalApps : 1;
- const sentinel = useMemo(() => getHealthSentinel(systemHealth, onlineRatio), [systemHealth, onlineRatio]);
- const cpuPct = systemHealth?.system?.cpu?.usagePercent;
- const memPct = systemHealth?.system?.memory?.usagePercent;
- const diskPct = systemHealth?.system?.disk?.usagePercent;
- const pendingReview = reviewCounts?.total || 0;
- const alertCount = reviewCounts?.alert || 0;
- const peers = instances?.peers || [];
- const { onlinePeers, totalNodes } = useMemo(() => {
- let online = 0;
- peers.forEach(p => { if (p.status === 'online') online++; });
- return { onlinePeers: online, totalNodes: peers.length };
- }, [peers]);
-
- const activeAgentCount = (cosAgents || []).filter(a =>
- a.status === 'running' || a.state === 'coding' || a.state === 'thinking' || a.state === 'investigating'
- ).length;
-
- const vitals = {
- uptimeSeconds,
- sentinel,
- cpuPct,
- memPct,
- diskPct,
- warnings: systemHealth?.warnings,
- activeAgentCount,
- stoppedApps,
- archivedApps,
- pendingReview,
- alertCount,
- onlinePeers,
- totalNodes,
- notificationCounts,
- productivityData,
- activeApps,
- totalApps,
- onOpenDestination,
- };
-
- if (explorationMode) {
- const speedKmh = Math.round(Math.abs(playerPose?.speed || 0) * 3.6);
- const progress = totalShards > 0 ? Math.min(100, Math.round((collectedCount / totalShards) * 100)) : 0;
- const settingsOpen = location.pathname === '/openworld/settings';
- const toggleSettings = () => navigate(settingsOpen ? `/openworld${location.search}` : `/openworld/settings${location.search}`);
-
- return (
- <div className="absolute inset-0 z-20 pointer-events-none openworld-hud-shell overflow-hidden" {...noPointerFocusSurfaceProps}>
- <div className="openworld-village-status pointer-events-auto">
- <span className={`openworld-village-status__dot ${sentinel.dot}`} aria-hidden="true" />
- <span>
- <small>PORTOS VILLAGE</small>
- <strong>{activeRegion?.label || 'The Common'}</strong>
- </span>
- <span className="openworld-village-status__echo" aria-label={`${collectedCount} of ${totalShards} echoes recovered`}>
- <i style={{ width: `${progress}%` }} />
- ⯁ {collectedCount}/{totalShards}
- </span>
- </div>
-
- <div className="openworld-village-actions pointer-events-auto" role="toolbar" aria-label="Village controls">
- {onOpenFastTravel && <HudAction icon={MapIcon} label="Village map" hint="M" onClick={onOpenFastTravel} />}
- {onEnterPhotoMode && <HudAction icon={Camera} label="Take a postcard" onClick={onEnterPhotoMode} />}
- <HudAction icon={Compass} label="Fly out to world view" hint="TAB" onClick={onToggleExploration} />
- <HudAction icon={Settings} label="Village settings" active={settingsOpen} onClick={toggleSettings} />
- </div>
-
- <div className="openworld-village-speed" aria-label={`${speedKmh} kilometers per hour`}>
- <strong>{speedKmh}</strong><span>km/h</span>
- </div>
-
- {isFocused && (
- <OpenWorldFocusPanel
- app={focusedApp}
- notFound={focusNotFound}
- agents={focusAgents}
- onClose={onCloseFocus}
- onFocusInWorld={onFocusInWorld}
- isDesktop={isDesktop}
- />
- )}
- <OpenWorldInteractionPrompt target={proximityTarget} compact={!isDesktop} />
- <ControlsHint visible isDesktop={isDesktop} />
- </div>
- );
- }
-
- return (
- // The HUD floats over a keyboard-driven world (WASD to move, Space to jump,
- // the playback transport keys). A click on any HUD control must hand focus
- // straight back, or the next Space re-presses that control instead.
- <div className="absolute inset-0 z-20 pointer-events-none openworld-hud-shell overflow-hidden" {...noPointerFocusSurfaceProps}>
- {isDesktop ? (
- <>
- <div className="absolute left-4 top-4 pointer-events-auto">
- <div className="openworld-hud-panel w-[min(17rem,calc(100vw-2rem))] px-4 py-3.5">
- <div className="flex items-center justify-between gap-4">
- <span className="openworld-hud-eyebrow">{explorationMode ? 'OpenWorld / signal trail' : 'OpenWorld / world view'}</span>
- <span className={`h-2.5 w-2.5 rounded-full ${sentinel.dot}`} title={sentinel.label} aria-label={`World health ${sentinel.label}`} />
- </div>
- {explorationMode ? (
- <>
- <div className="mt-2 font-pixel text-lg tracking-[0.1em] text-[rgb(var(--port-text))]">{activeRegion?.label || 'THE PORT'}</div>
- <div className="mt-2 flex items-center justify-between gap-3 border-t border-[rgb(var(--port-accent)/.14)] pt-2 font-pixel text-[9px] tracking-[0.1em]">
- <span className="text-[rgb(var(--port-text-muted))]">ECHOES RECOVERED</span>
- <span className="text-[rgb(var(--port-accent))]">⯁ {collectedCount}/{totalShards}</span>
- </div>
- </>
- ) : (
- <>
- <div className="mt-2 flex items-end justify-between gap-4">
- <span className="font-pixel text-2xl tracking-[0.12em] text-[rgb(var(--port-text))]">{formatClockTime(time, { seconds: false })}</span>
- <span className="font-pixel text-[9px] tracking-[0.12em] text-[rgb(var(--port-accent))]">{activeApps}/{totalApps} ACTIVE</span>
- </div>
- <div className="mt-2">
- <HealthBar value={activeApps} max={totalApps} color="rgb(var(--port-accent))" />
- </div>
- <div
- className="mt-2 grid grid-cols-3 gap-3 border-t border-[rgb(var(--port-accent)/.14)] pt-2"
- aria-label="System resource usage"
- >
- <SystemMetric label="CPU" value={cpuPct} />
- <SystemMetric label="MEM" value={memPct} />
- <SystemMetric label="DISK" value={diskPct} />
- </div>
- <div className="mt-2 flex items-center justify-between gap-3 font-pixel text-[8px] tracking-[0.12em] text-[rgb(var(--port-text-muted))]">
- <span className="truncate">{activeRegion?.label || 'THE PORT'}</span>
- <span className={sentinel.text}>{sentinel.label}</span>
- </div>
- </>
- )}
- </div>
- </div>
-
- {!explorationMode && filter && onFilterChange && (
- <div className="absolute left-1/2 top-4 -translate-x-1/2">
- <OpenWorldFilterBar
- filter={filter}
- onChange={onFilterChange}
- onJumpToFirst={onJumpToFirst}
- matchCount={matchCount}
- />
- </div>
- )}
-
- {!explorationMode && <div className="absolute right-4 top-4 pointer-events-auto">
- <div className="openworld-hud-panel openworld-hud-panel--quiet flex items-center gap-3 px-3.5 py-2.5">
- <div className="flex items-center gap-2">
- <span className={`h-2 w-2 rounded-full ${connected ? 'bg-port-success' : 'bg-port-error animate-pulse'}`} />
- <span className={`font-pixel text-[9px] tracking-[0.12em] ${connected ? 'text-[rgb(var(--port-text-muted))]' : 'text-port-error'}`}>
- {connected ? 'SYNCED' : 'OFFLINE'}
- </span>
- </div>
- <span className="h-4 w-px bg-[rgb(var(--port-accent)/.22)]" />
- <div className="flex items-center gap-2">
- <span className={`h-2 w-2 rounded-full ${cosStatus?.running ? 'bg-[rgb(var(--port-accent))] animate-pulse' : 'bg-[rgb(var(--port-text-muted)/.45)]'}`} />
- <span className="font-pixel text-[9px] tracking-[0.12em] text-[rgb(var(--port-text-muted))]">CoS {cosStatus?.running ? 'RUN' : 'IDLE'}</span>
- </div>
- </div>
- </div>}
-
- {isFocused ? (
- <OpenWorldFocusPanel
- app={focusedApp}
- notFound={focusNotFound}
- agents={focusAgents}
- onClose={onCloseFocus}
- onFocusInWorld={onFocusInWorld}
- isDesktop
- />
- ) : (
- <OpenWorldIntelPane
- apps={apps}
- cosAgents={cosAgents}
- reviewCounts={reviewCounts}
- instances={instances}
- systemHealth={systemHealth}
- notificationCounts={notificationCounts}
- eventLogs={eventLogs}
- onItemActivate={onAttentionItem}
- onOpenFastTravel={onOpenFastTravel}
- />
- )}
-
- {!explorationMode && <OpenWorldAgentBar cosAgents={cosAgents} agentMap={agentMap} />}
- {!explorationMode && <OpenWorldXpBadge character={character} onOpenDestination={onOpenDestination} />}
-
- <div className="absolute bottom-4 left-4 pointer-events-auto flex flex-col gap-2 items-start">
- <OpenWorldMiniMap
- apps={apps}
- onSelectApp={onSelectApp}
- selectedAppId={focusedAppId}
- playerPose={playerPose}
- />
- {explorationMode && (
- <OpenWorldSpeedometer
- playerPose={playerPose}
- collectedCount={collectedCount}
- totalShards={totalShards}
- />
- )}
- <div className="openworld-hud-action-rail">
- {onOpenFastTravel && <HudAction icon={MapIcon} label="World map" hint="M" onClick={onOpenFastTravel} />}
- <HudAction
- icon={Compass}
- label={explorationMode ? 'Fly out' : 'Drop in'}
- hint="TAB"
- active={explorationMode}
- primary
- onClick={onToggleExploration}
- />
- {onEnterPhotoMode && <HudAction icon={Camera} label="Photo mode" onClick={onEnterPhotoMode} />}
- {onEnterPlayback && <HudAction icon={History} label="History" onClick={onEnterPlayback} />}
- <HudAction
- icon={Settings}
- label="OpenWorld settings"
- active={location.pathname === '/openworld/settings'}
- onClick={() => navigate(location.pathname === '/openworld/settings' ? `/openworld${location.search}` : `/openworld/settings${location.search}`)}
- />
- </div>
- </div>
- </>
- ) : (
- <OpenWorldHudCompact
- time={time}
- vitals={vitals}
- connected={connected}
- cosStatus={cosStatus}
- character={character}
- filter={filter}
- onFilterChange={onFilterChange}
- onJumpToFirst={onJumpToFirst}
- matchCount={matchCount}
- apps={apps}
- cosAgents={cosAgents}
- reviewCounts={reviewCounts}
- instances={instances}
- systemHealth={systemHealth}
- notificationCounts={notificationCounts}
- eventLogs={eventLogs}
- onToggleExploration={onToggleExploration}
- explorationMode={explorationMode}
- onSelectApp={onSelectApp}
- onEnterPhotoMode={onEnterPhotoMode}
- onEnterPlayback={onEnterPlayback}
- focusedAppId={focusedAppId}
- focusedApp={focusedApp}
- focusNotFound={focusNotFound}
- focusAgents={focusAgents}
- onCloseFocus={onCloseFocus}
- onFocusInWorld={onFocusInWorld}
- onOpenFastTravel={onOpenFastTravel}
- onOpenDestination={onOpenDestination}
- onAttentionItem={onAttentionItem}
- proximityTarget={proximityTarget}
- playerPose={playerPose}
- collectedCount={collectedCount}
- totalShards={totalShards}
- />
- )}
-
- {explorationMode && isDesktop && <OpenWorldInteractionPrompt target={proximityTarget} />}
- <ControlsHint visible={explorationMode} isDesktop={isDesktop} />
- </div>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldHud.test.jsx b/client/src/components/openworld/OpenWorldHud.test.jsx
deleted file mode 100644
index 6e4fe86084..0000000000
--- a/client/src/components/openworld/OpenWorldHud.test.jsx
+++ /dev/null
@@ -1,73 +0,0 @@
-import { describe, expect, it, vi } from 'vitest';
-import { render, screen, within } from '@testing-library/react';
-import { MemoryRouter } from 'react-router';
-
-vi.mock('../../hooks/useOpenWorldViewport', () => ({
- default: () => ({ isDesktop: true }),
-}));
-vi.mock('./OpenWorldIntelPane', () => ({ default: () => null }));
-vi.mock('./OpenWorldFocusPanel', () => ({ default: () => null }));
-vi.mock('./OpenWorldAgentBar', () => ({ default: () => null }));
-vi.mock('./OpenWorldXpBadge', () => ({ default: () => null }));
-vi.mock('./OpenWorldMiniMap', () => ({ default: () => null }));
-
-import OpenWorldHud from './OpenWorldHud';
-
-const renderHud = (overrides = {}) => render(
- <MemoryRouter initialEntries={['/openworld']}>
- <OpenWorldHud
- cosStatus={{ running: false }}
- cosAgents={[]}
- agentMap={new Map()}
- eventLogs={[]}
- connected
- apps={[{ id: 'app-1', name: 'Example App', overallStatus: 'online' }]}
- reviewCounts={{ total: 0, alert: 0 }}
- instances={{ peers: [] }}
- productivityData={null}
- systemHealth={{
- overallHealth: 'warning',
- system: {
- cpu: { usagePercent: 42 },
- memory: { usagePercent: 76 },
- disk: { usagePercent: 91 },
- },
- }}
- notificationCounts={{ unread: 0 }}
- character={null}
- filter={null}
- explorationMode={false}
- {...overrides}
- />
- </MemoryRouter>,
-);
-
-describe('OpenWorldHud', () => {
- it('keeps CPU, memory, and disk pressure visible in the desktop cockpit', () => {
- renderHud();
-
- const metrics = screen.getByLabelText('System resource usage');
- expect(within(metrics).getByText('CPU')).toBeInTheDocument();
- expect(within(metrics).getByText('42%')).toBeInTheDocument();
- expect(within(metrics).getByText('MEM')).toBeInTheDocument();
- expect(within(metrics).getByText('76%')).toBeInTheDocument();
- expect(within(metrics).getByText('DISK')).toBeInTheDocument();
- expect(within(metrics).getByText('91%')).toBeInTheDocument();
- });
-
- it('gives exploration a quiet village hierarchy instead of dashboard telemetry', () => {
- renderHud({
- explorationMode: true,
- activeRegion: { id: 'memory', label: 'Memory Wilds' },
- collectedCount: 3,
- totalShards: 17,
- });
-
- expect(screen.queryByLabelText('System resource usage')).not.toBeInTheDocument();
- expect(screen.getAllByText('Memory Wilds').length).toBeGreaterThan(0);
- expect(screen.getByText('PORTOS VILLAGE')).toBeInTheDocument();
- expect(screen.getByText('WELCOME TO THE VILLAGE')).toBeInTheDocument();
- expect(screen.getAllByText(/3\/17/).length).toBeGreaterThan(0);
- expect(screen.getByText(/Take the long way/i)).toBeInTheDocument();
- });
-});
diff --git a/client/src/components/openworld/OpenWorldHudCompact.jsx b/client/src/components/openworld/OpenWorldHudCompact.jsx
deleted file mode 100644
index 1084c89a90..0000000000
--- a/client/src/components/openworld/OpenWorldHudCompact.jsx
+++ /dev/null
@@ -1,299 +0,0 @@
-import { useMemo } from 'react';
-import { useNavigate, useLocation } from 'react-router';
-import { Gauge, Bell, Clock, Activity, Map as MapIcon, Filter, Palette, Compass, Camera, History, Settings, X } from 'lucide-react';
-import useDrawerTab from '../../hooks/useDrawerTab';
-import { buildAttentionItems, OpenWorldIntelContent } from './OpenWorldIntelPane';
-import OpenWorldVitalsList from './OpenWorldVitalsList';
-import OpenWorldMiniMap from './OpenWorldMiniMap';
-import OpenWorldFilterBar from './OpenWorldFilterBar';
-import OpenWorldFocusPanel from './OpenWorldFocusPanel';
-import OpenWorldInteractionPrompt from './OpenWorldInteractionPrompt';
-import { CITY_PANE_IDS, CITY_INTEL_PANE_IDS, CITY_PANE_LABELS } from './openWorldPanes';
-import { birthDateCta } from '../../utils/characterXp';
-import { formatClockTime } from '../../utils/formatters';
-
-// A 44×44 dock control. `active`/`aria-pressed` mark a toggled disclosure launcher;
-// omit `active` for one-shot actions (photo, history) that just fire a callback.
-function DockButton({ icon: Icon, label, active, badge = 0, badgeCritical = false, onClick }) {
- return (
- <button
- type="button"
- onClick={onClick}
- title={label}
- aria-label={label}
- aria-pressed={active === undefined ? undefined : active}
- className="openworld-hud-action relative shrink-0 w-11 h-11"
- >
- <Icon size={18} aria-hidden="true" />
- {badge > 0 && (
- <span
- className={`absolute -top-1 -right-1 min-w-[16px] h-4 px-1 rounded-full font-pixel text-[8px] flex items-center justify-center ${
- badgeCritical ? 'bg-port-error text-white' : 'bg-cyan-500 text-black'
- }`}
- >
- {badge}
- </span>
- )}
- </button>
- );
-}
-
-function StatusDot({ on, label, onClass, offClass = 'bg-gray-600' }) {
- return (
- <span className="flex items-center gap-1" title={label} aria-label={label}>
- <span className={`w-2.5 h-2.5 rounded-full ${on ? onClass : offClass}`} />
- </span>
- );
-}
-
-const LEGEND_ROWS = [
- { color: 'bg-cyan-500', label: 'ONLINE' },
- { color: 'bg-red-500', label: 'STOPPED' },
- { color: 'bg-violet-500', label: 'NOT STARTED' },
- { color: 'bg-slate-500', label: 'ARCHIVED' },
-];
-
-// Compact / phone HUD. Keeps the 3D scene the focus: by default only a small clock
-// chip, a status chip and a bottom dock are shown (well under 30% coverage). Every
-// secondary surface (vitals, attention, timeline, activity, map, filter, legend) is
-// a single mutually-exclusive disclosure sheet driven by the `openWorldPane` URL param —
-// so only one can be open, the open one is deep-linkable, and clearing it returns to
-// the unobstructed scene.
-export default function OpenWorldHudCompact({
- time,
- vitals,
- connected,
- cosStatus,
- character,
- filter,
- onFilterChange,
- onJumpToFirst,
- matchCount,
- apps,
- cosAgents,
- reviewCounts,
- instances,
- systemHealth,
- notificationCounts,
- eventLogs,
- onToggleExploration,
- explorationMode,
- onSelectApp,
- onEnterPhotoMode,
- onEnterPlayback,
- onOpenFastTravel,
- onOpenDestination,
- onAttentionItem,
- focusedAppId,
- focusedApp,
- focusNotFound,
- focusAgents,
- onCloseFocus,
- onFocusInWorld,
- proximityTarget,
- playerPose,
- collectedCount = 0,
- totalShards = 0,
-}) {
- const navigate = useNavigate();
- const location = useLocation();
- const [activePane, setActivePane] = useDrawerTab('openWorldPane', null, CITY_PANE_IDS);
- const togglePane = (id) => setActivePane(activePane === id ? null : id);
- const isFocused = Boolean(focusedApp || focusNotFound);
-
- const items = useMemo(
- () => buildAttentionItems({ apps, cosAgents, reviewCounts, instances, systemHealth, notificationCounts }),
- [apps, cosAgents, reviewCounts, instances, systemHealth, notificationCounts],
- );
- const criticalCount = items.filter(i => i.severity === 'critical').length;
- const hasApps = (apps || []).length > 0;
- const speedKmh = Math.round(Math.abs(playerPose?.speed || 0) * 3.6);
- // No usable level → the birth-date CTA distinguishes a genuinely unset date ("set") from a
- // present-but-unusable one ("fix" — invalid/future/unreadable) so we don't tell the user to
- // set a date they already entered (#2757). Null when a real level exists.
- const birthCta = character && character.level == null ? birthDateCta(character.birthDateStatus) : null;
-
- const onSettings = location.pathname === '/openworld/settings';
- const goSettings = () => navigate(onSettings ? `/openworld${location.search}` : `/openworld/settings${location.search}`);
-
- const renderPaneBody = () => {
- if (CITY_INTEL_PANE_IDS.includes(activePane)) {
- return <OpenWorldIntelContent tab={activePane} items={items} eventLogs={eventLogs} onItemActivate={onAttentionItem} onOpenFastTravel={onOpenFastTravel} />;
- }
- if (activePane === 'vitals') {
- return <div className="p-3"><OpenWorldVitalsList {...vitals} onOpenDestination={onOpenDestination} /></div>;
- }
- if (activePane === 'map') {
- return hasApps
- ? <div className="p-3 flex justify-center"><OpenWorldMiniMap apps={apps} onSelectApp={onSelectApp} selectedAppId={focusedAppId} alwaysShow /></div>
- : <div className="p-6 text-center font-pixel text-[9px] text-cyan-500/40 tracking-wide">No buildings to map</div>;
- }
- if (activePane === 'filter') {
- return (
- <div className="p-3">
- <OpenWorldFilterBar filter={filter} onChange={onFilterChange} onJumpToFirst={onJumpToFirst} matchCount={matchCount} compact />
- </div>
- );
- }
- if (activePane === 'legend') {
- return (
- <div className="p-3 grid grid-cols-2 gap-2">
- {LEGEND_ROWS.map(row => (
- <div key={row.label} className="flex items-center gap-1.5">
- <span className={`w-2.5 h-2.5 rounded-xs ${row.color}`} />
- <span className="font-pixel text-[9px] text-gray-300 tracking-wide">{row.label}</span>
- </div>
- ))}
- </div>
- );
- }
- return null;
- };
-
- return (
- <>
- {explorationMode && <OpenWorldInteractionPrompt target={proximityTarget} compact />}
- {/* Top-left: compact clock + health → opens vitals */}
- <div className="absolute top-2 left-2 pointer-events-auto">
- <button
- type="button"
- onClick={() => togglePane('vitals')}
- aria-label={explorationMode
- ? `Time and system vitals, ${speedKmh} kilometers per hour, ${collectedCount} of ${totalShards} shards collected`
- : 'Time and system vitals'}
- aria-pressed={activePane === 'vitals'}
- className="openworld-hud-chip openworld-hud-action relative px-3 min-h-[44px] flex items-center gap-2"
- >
- <span className={`w-2 h-2 rounded-full ${vitals.sentinel.dot} shadow-[0_0_4px_currentColor]`} />
- <span className="font-pixel text-cyan-400 text-sm tracking-wider" style={{ textShadow: '0 0 8px rgba(6,182,212,0.5)' }}>
- {formatClockTime(time, { seconds: false })}
- </span>
- <span className="font-pixel text-[9px] text-cyan-500 tracking-wide">{vitals.activeApps}/{vitals.totalApps}</span>
- {explorationMode && (
- <>
- <span className="h-4 w-px bg-cyan-500/20" aria-hidden="true" />
- <span className="font-pixel text-[11px] text-cyan-300 tracking-wide">{speedKmh}</span>
- <span className="font-pixel text-[7px] text-gray-500 tracking-wide">KM/H</span>
- <span className="font-pixel text-[8px] text-cyan-400 tracking-wide">
- ⯁ {collectedCount}/{totalShards}
- </span>
- </>
- )}
- </button>
- </div>
-
- {/* Top-right: connection + CoS + level */}
- <div className="absolute top-2 right-2 pointer-events-auto flex items-center gap-1.5">
- <div
- className="openworld-hud-chip px-2.5 min-h-[44px] flex items-center gap-2"
- role="status"
- aria-label={`Link ${connected ? 'online' : 'offline'}, Chief of Staff ${cosStatus?.running ? 'running' : 'idle'}`}
- >
- <StatusDot on={connected} label={connected ? 'Link online' : 'Link offline'} onClass="bg-port-success shadow-[0_0_8px_rgba(34,197,94,0.6)]" offClass="bg-port-error" />
- <StatusDot on={cosStatus?.running} label={cosStatus?.running ? 'CoS running' : 'CoS idle'} onClass="bg-cyan-400 animate-pulse shadow-[0_0_8px_rgba(6,182,212,0.6)]" />
- </div>
- {character?.level != null ? (
- <button
- type="button"
- onClick={() => onOpenDestination?.('artifacts')}
- aria-label={`Teleport to Hall of Achievements — level ${character.level}`}
- title="Teleport to Hall of Achievements"
- className="openworld-hud-chip openworld-hud-action px-2.5 min-h-[44px] flex items-center font-pixel text-[11px] text-cyan-300 tracking-wider"
- >
- LV {character.level}
- </button>
- ) : birthCta ? (
- // Character loaded but no usable level (age-based, #2673). Prompt the user to set the
- // birth date — or FIX it when present-but-unusable (#2757). The CTA points to a
- // nearby in-world district so the game remains the active surface.
- <button
- type="button"
- onClick={() => onOpenDestination?.('goals')}
- aria-label={`${birthCta.title} — teleport to Goal Monuments`}
- title="Teleport to Goal Monuments"
- // A present-but-unusable date (invalid/future/unreadable) renders in the warning color,
- // matching the CharacterSheet "fix" prompt and the changelog's promise (#2757).
- className={`openworld-hud-chip openworld-hud-action px-2.5 min-h-[44px] flex items-center font-pixel text-[11px] tracking-wider ${
- birthCta.kind === 'fix'
- ? 'border-port-warning/50 text-port-warning'
- : 'text-cyan-300/70'
- }`}
- >
- {birthCta.badgeLabel}
- </button>
- ) : null}
- </div>
-
- {/* Focused building detail sheet (issue #2593) — replaces the disclosure sheet while a
- borough is focused so the two never overlap. */}
- {isFocused && (
- <OpenWorldFocusPanel
- app={focusedApp}
- notFound={focusNotFound}
- agents={focusAgents}
- onClose={onCloseFocus}
- onFocusInWorld={onFocusInWorld}
- isDesktop={false}
- />
- )}
-
- {/* Disclosure sheet — one surface at a time, above the dock */}
- {!isFocused && activePane && (
- <div className="absolute inset-x-2 bottom-16 pointer-events-auto">
- <div className="openworld-intel-surface flex flex-col max-h-[55vh] overflow-hidden">
- <div className="flex items-center justify-between pl-3 pr-1 py-1.5 border-b border-cyan-500/20 shrink-0">
- <span className="font-pixel text-[11px] text-cyan-400 tracking-widest" style={{ textShadow: '0 0 8px rgba(6,182,212,0.4)' }}>
- {(CITY_PANE_LABELS[activePane] || '').toUpperCase()}
- </span>
- <button
- type="button"
- onClick={() => setActivePane(null)}
- aria-label="Close panel"
- title="Close"
- className="w-11 h-11 flex items-center justify-center text-gray-400 hover:text-cyan-400 transition-colors"
- >
- <X size={18} aria-hidden="true" />
- </button>
- </div>
- <div className="flex-1 flex flex-col min-h-0 overflow-y-auto">
- {renderPaneBody()}
- </div>
- </div>
- </div>
- )}
-
- {/* Bottom dock — every HUD function within two taps */}
- <div className="absolute bottom-2 left-2 right-2 pointer-events-auto">
- <div
- className="openworld-hud-dock overflow-x-auto scrollbar-hide touch-pan-x"
- role="toolbar"
- aria-label="OpenWorld controls"
- >
- <DockButton icon={Gauge} label="System vitals" active={activePane === 'vitals'} onClick={() => togglePane('vitals')} />
- <DockButton icon={Bell} label="Attention" active={activePane === 'attention'} badge={items.length} badgeCritical={criticalCount > 0} onClick={() => togglePane('attention')} />
- <DockButton icon={Clock} label="Timeline" active={activePane === 'timeline'} onClick={() => togglePane('timeline')} />
- <DockButton icon={Activity} label="Activity log" active={activePane === 'activity'} onClick={() => togglePane('activity')} />
- {onOpenFastTravel ? (
- <DockButton icon={MapIcon} label="World map — teleport to a region" onClick={onOpenFastTravel} />
- ) : hasApps && (
- <DockButton icon={MapIcon} label="Building map" active={activePane === 'map'} onClick={() => togglePane('map')} />
- )}
- <DockButton icon={Filter} label="Filter apps" active={activePane === 'filter'} onClick={() => togglePane('filter')} />
- <DockButton icon={Palette} label="Legend" active={activePane === 'legend'} onClick={() => togglePane('legend')} />
-
- <div className="w-px h-6 bg-cyan-500/20 shrink-0" />
-
- <DockButton
- icon={Compass}
- label={explorationMode ? 'Fly out to orbital view' : 'Drop in to street level'}
- active={explorationMode}
- onClick={onToggleExploration}
- />
- {onEnterPhotoMode && <DockButton icon={Camera} label="Photo mode" onClick={onEnterPhotoMode} />}
- {onEnterPlayback && <DockButton icon={History} label="History playback" onClick={onEnterPlayback} />}
- <DockButton icon={Settings} label="OpenWorld settings" active={onSettings} onClick={goSettings} />
- </div>
- </div>
- </>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldHudCompact.test.jsx b/client/src/components/openworld/OpenWorldHudCompact.test.jsx
deleted file mode 100644
index 362c3a6de4..0000000000
--- a/client/src/components/openworld/OpenWorldHudCompact.test.jsx
+++ /dev/null
@@ -1,169 +0,0 @@
-import { describe, it, expect, vi } from 'vitest';
-import { render, screen, fireEvent } from '@testing-library/react';
-import { MemoryRouter, useLocation } from 'react-router';
-import OpenWorldHudCompact from './OpenWorldHudCompact';
-
-function Loc() {
- const l = useLocation();
- return <div data-testid="loc">{l.search}</div>;
-}
-
-const baseVitals = {
- uptimeSeconds: 0,
- sentinel: { dot: 'bg-cyan-400', text: 'text-cyan-400', label: 'OK' },
- cpuPct: 10,
- memPct: 20,
- diskPct: 30,
- warnings: [],
- activeAgentCount: 0,
- stoppedApps: 0,
- archivedApps: 0,
- pendingReview: 0,
- alertCount: 0,
- onlinePeers: 0,
- totalNodes: 0,
- notificationCounts: { unread: 0 },
- productivityData: {},
- activeApps: 1,
- totalApps: 2,
-};
-
-const baseProps = {
- time: new Date('2026-07-14T12:00:00'),
- vitals: baseVitals,
- connected: true,
- cosStatus: { running: false },
- character: { level: 5 },
- filter: { status: 'all', search: '' },
- onFilterChange: () => {},
- onJumpToFirst: () => {},
- matchCount: 0,
- apps: [{ id: 'a1', name: 'App One', overallStatus: 'online' }],
- cosAgents: [],
- reviewCounts: { total: 0, alert: 0 },
- instances: { peers: [] },
- systemHealth: {},
- notificationCounts: { unread: 0 },
- eventLogs: [],
- onToggleExploration: () => {},
- explorationMode: false,
- onSelectApp: () => {},
- onEnterPhotoMode: () => {},
- onEnterPlayback: () => {},
- onOpenFastTravel: () => {},
- onOpenDestination: () => {},
-};
-
-const renderCompact = (search = '', props = {}) =>
- render(
- <MemoryRouter initialEntries={[`/openworld${search}`]}>
- <OpenWorldHudCompact {...baseProps} {...props} />
- <Loc />
- </MemoryRouter>,
- );
-
-describe('OpenWorldHudCompact', () => {
- it('shows no secondary surface by default (scene stays unobscured)', () => {
- renderCompact();
- // Dock controls present…
- expect(screen.getByLabelText('System vitals')).toBeInTheDocument();
- expect(screen.getByLabelText('Attention')).toBeInTheDocument();
- // …but no disclosure sheet is open.
- expect(screen.queryByText('SYSTEM VITALS')).not.toBeInTheDocument();
- expect(screen.queryByRole('button', { name: 'Close panel' })).not.toBeInTheDocument();
- });
-
- it('opens a pane from the dock and reflects it in the URL', () => {
- renderCompact();
- fireEvent.click(screen.getByLabelText('Attention'));
- expect(screen.getByTestId('loc').textContent).toContain('openWorldPane=attention');
- // The sheet header for the opened pane appears.
- expect(screen.getByText('ATTENTION')).toBeInTheDocument();
- });
-
- it('uses the map icon to open the in-world teleport map', () => {
- const onOpenFastTravel = vi.fn();
- renderCompact('', { onOpenFastTravel });
- fireEvent.click(screen.getByLabelText('World map — teleport to a region'));
- expect(onOpenFastTravel).toHaveBeenCalledTimes(1);
- });
-
- it('explains the nearby warp-pad action', () => {
- renderCompact('', { explorationMode: true, proximityTarget: { type: 'warpPad', id: 'memory', label: 'Memory Quarter' } });
- expect(screen.getByTestId('openworld-interaction-prompt')).toHaveTextContent('WARP GATE');
- expect(screen.getByTestId('openworld-interaction-prompt')).toHaveTextContent('Memory Quarter');
- expect(screen.getByTestId('openworld-interaction-prompt')).toHaveTextContent('ACTION');
- });
-
- it('shows live speed and collectible progress while free roaming', () => {
- renderCompact('', {
- explorationMode: true,
- playerPose: { speed: 10 },
- collectedCount: 4,
- totalShards: 12,
- });
-
- expect(screen.getByText('36')).toBeInTheDocument();
- expect(screen.getByText('KM/H')).toBeInTheDocument();
- expect(screen.getByRole('button', { name: /36 kilometers per hour, 4 of 12 shards collected/i })).toHaveTextContent('4/12');
- });
-
- it('restores the open pane from the URL on load', () => {
- renderCompact('?openWorldPane=vitals');
- expect(screen.getByText('SYSTEM VITALS')).toBeInTheDocument();
- });
-
- it('keeps only one surface open at a time (mutual exclusivity)', () => {
- renderCompact('?openWorldPane=vitals');
- expect(screen.getByText('SYSTEM VITALS')).toBeInTheDocument();
- fireEvent.click(screen.getByLabelText('Attention'));
- // Switching panes closes the previous one.
- expect(screen.queryByText('SYSTEM VITALS')).not.toBeInTheDocument();
- expect(screen.getByText('ATTENTION')).toBeInTheDocument();
- expect(screen.getByTestId('loc').textContent).toContain('openWorldPane=attention');
- });
-
- it('toggling the active dock launcher closes the pane', () => {
- renderCompact('?openWorldPane=vitals');
- fireEvent.click(screen.getByLabelText('System vitals'));
- expect(screen.queryByText('SYSTEM VITALS')).not.toBeInTheDocument();
- expect(screen.getByTestId('loc').textContent).toBe('');
- });
-
- it('the close button clears the surface and the URL param', () => {
- renderCompact('?openWorldPane=attention');
- expect(screen.getByText('ATTENTION')).toBeInTheDocument();
- fireEvent.click(screen.getByRole('button', { name: 'Close panel' }));
- expect(screen.queryByText('ATTENTION')).not.toBeInTheDocument();
- expect(screen.getByTestId('loc').textContent).toBe('');
- });
-
- describe('birth-date level CTA (#2757)', () => {
- it('shows a SET prompt (LV —) for a genuinely unset birth date', () => {
- renderCompact('', { character: { level: null, birthDateStatus: 'unset' } });
- expect(screen.getByRole('button', { name: /set your birth date/i })).toBeInTheDocument();
- expect(screen.getByText('LV —')).toBeInTheDocument();
- });
-
- it('shows a FIX prompt (LV !) for a present-but-invalid birth date', () => {
- renderCompact('', { character: { level: null, birthDateStatus: 'invalid' } });
- const btn = screen.getByRole('button', { name: /fix your birth date/i });
- expect(btn).toBeInTheDocument();
- expect(screen.getByText('LV !')).toBeInTheDocument();
- expect(screen.queryByText('LV —')).not.toBeInTheDocument();
- });
-
- it('shows a FIX prompt for an unreadable config, not a set prompt', () => {
- renderCompact('', { character: { level: null, birthDateStatus: 'unreadable' } });
- expect(screen.getByRole('button', { name: /fix your birth date/i })).toBeInTheDocument();
- expect(screen.queryByRole('button', { name: /set your birth date/i })).not.toBeInTheDocument();
- });
-
- it('shows the numeric level (no CTA) when a level exists', () => {
- renderCompact('', { character: { level: 7, birthDateStatus: 'ok' } });
- expect(screen.getByText('LV 7')).toBeInTheDocument();
- expect(screen.queryByText('LV —')).not.toBeInTheDocument();
- expect(screen.queryByText('LV !')).not.toBeInTheDocument();
- });
- });
-});
diff --git a/client/src/components/openworld/OpenWorldIntelPane.jsx b/client/src/components/openworld/OpenWorldIntelPane.jsx
deleted file mode 100644
index 48ffb0239c..0000000000
--- a/client/src/components/openworld/OpenWorldIntelPane.jsx
+++ /dev/null
@@ -1,469 +0,0 @@
-import { useMemo, useRef, useEffect, useState } from 'react';
-import { formatClockTime } from '../../utils/formatters';
-import { computeActivityDensity, buildTimelineBuckets } from '../../utils/openWorldTimeline';
-import useDrawerTab from '../../hooks/useDrawerTab';
-import { CITY_PANE_IDS, CITY_INTEL_PANE_IDS } from './openWorldPanes';
-
-const SEVERITY_RANK = { critical: 0, warning: 1, info: 2 };
-const SEVERITY_COLORS = {
- critical: { dot: 'bg-port-error', text: 'text-port-error', border: 'border-port-error/40' },
- warning: { dot: 'bg-port-warning', text: 'text-port-warning', border: 'border-port-warning/30' },
- info: { dot: 'bg-cyan-400', text: 'text-cyan-300', border: 'border-cyan-500/25' },
-};
-
-export function buildAttentionItems({ apps, cosAgents, reviewCounts, instances, systemHealth, notificationCounts }) {
- const items = [];
-
- (apps || []).forEach(app => {
- if (app.archived) return;
- if (app.overallStatus === 'stopped') {
- items.push({
- id: `app-stopped-${app.id}`,
- severity: 'critical',
- label: `${app.name || app.id}`,
- detail: 'Stopped',
- appId: app.id,
- category: 'app',
- });
- }
- const pm2 = app.pm2Status || {};
- Object.entries(pm2).forEach(([procName, s]) => {
- if (s?.status === 'errored' || s?.status === 'error') {
- items.push({
- id: `proc-err-${app.id}-${procName}`,
- severity: 'critical',
- label: `${app.name || app.id} · ${procName}`,
- detail: 'Process errored',
- appId: app.id,
- category: 'app',
- });
- }
- });
- });
-
- if (systemHealth?.warnings?.length) {
- systemHealth.warnings.forEach((w, i) => {
- const sev = systemHealth.overallHealth === 'critical' ? 'critical' : 'warning';
- items.push({
- id: `sys-warn-${i}-${w.type}`,
- severity: sev,
- label: w.message || `System: ${w.type}`,
- detail: 'System health',
- regionId: 'wellness',
- category: 'system',
- });
- });
- }
-
- if (reviewCounts?.alert > 0) {
- items.push({
- id: 'review-alerts',
- severity: 'critical',
- label: `${reviewCounts.alert} alert${reviewCounts.alert === 1 ? '' : 's'}`,
- detail: 'Review hub',
- regionId: 'task-queue',
- category: 'review',
- });
- }
- if (reviewCounts?.total > 0) {
- items.push({
- id: 'review-pending',
- severity: 'warning',
- label: `${reviewCounts.total} pending review${reviewCounts.total === 1 ? '' : 's'}`,
- detail: 'Review hub',
- regionId: 'task-queue',
- category: 'review',
- });
- }
-
- const peers = instances?.peers || [];
- const offlinePeers = peers.filter(p => p.status !== 'online');
- if (offlinePeers.length > 0) {
- items.push({
- id: 'peers-offline',
- severity: 'warning',
- label: `${offlinePeers.length} of ${peers.length} peer${peers.length === 1 ? '' : 's'} offline`,
- detail: 'Federation',
- regionId: 'data-harbor',
- category: 'federation',
- });
- }
-
- const erroredAgents = (cosAgents || []).filter(a =>
- a.status === 'failed' || a.state === 'error' || a.error
- );
- erroredAgents.forEach(agent => {
- items.push({
- id: `agent-err-${agent.agentId || agent.id}`,
- severity: 'warning',
- label: agent.task || agent.taskTitle || `Agent ${agent.agentId?.slice(0, 8) || ''}`,
- detail: 'Agent failed',
- regionId: 'ai-core',
- category: 'agent',
- });
- });
-
- const unread = notificationCounts?.unread ?? 0;
- if (unread > 0) {
- items.push({
- id: 'notifs-unread',
- severity: 'info',
- label: `${unread} unread notification${unread === 1 ? '' : 's'}`,
- detail: 'Open dashboard alerts',
- regionId: 'downtown',
- category: 'notifications',
- });
- }
-
- return items.sort((a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity]);
-}
-
-function AttentionList({ items, onItemActivate }) {
- if (items.length === 0) {
- return (
- <div className="flex-1 flex items-center justify-center px-3 py-6">
- <div className="text-center">
- <div className="font-pixel text-[10px] text-port-success/70 tracking-wider mb-1">ALL CLEAR</div>
- <div className="font-pixel text-[8px] text-cyan-500/30 tracking-wide">No items need attention</div>
- </div>
- </div>
- );
- }
-
- return (
- <div className="flex-1 overflow-y-auto px-2 py-1.5 space-y-1" style={{ scrollbarWidth: 'thin', scrollbarColor: 'rgba(6,182,212,0.2) transparent' }}>
- {items.map(item => {
- const colors = SEVERITY_COLORS[item.severity] || SEVERITY_COLORS.info;
- return (
- <button
- key={item.id}
- type="button"
- onClick={() => onItemActivate?.(item)}
- className={`w-full text-left flex items-start gap-2 px-2 py-1.5 rounded border ${colors.border} bg-black/40 hover:bg-cyan-500/10 transition-colors`}
- title={`${item.label} — ${item.detail}`}
- >
- <span className={`w-1.5 h-1.5 rounded-full ${colors.dot} shrink-0 mt-1.5 shadow-[0_0_4px_currentColor]`} />
- <div className="flex-1 min-w-0">
- <div className={`font-pixel text-[10px] tracking-wide truncate ${colors.text}`}>
- {item.label}
- </div>
- <div className="font-pixel text-[8px] text-gray-500 tracking-wide truncate mt-0.5">
- {item.detail}
- </div>
- </div>
- <span className="font-pixel text-[8px] text-cyan-500/40 tracking-wide self-center">{'>'}</span>
- </button>
- );
- })}
- </div>
- );
-}
-
-const LEVEL_COLORS = {
- info: 'text-cyan-400',
- warn: 'text-port-warning',
- error: 'text-port-error',
- success: 'text-port-success',
- debug: 'text-gray-500',
-};
-
-const LEVEL_INDICATORS = {
- info: 'bg-cyan-400',
- warn: 'bg-port-warning',
- error: 'bg-port-error',
- success: 'bg-port-success',
- debug: 'bg-gray-600',
-};
-
-function ActivityLogList({ logs }) {
- const scrollRef = useRef(null);
-
- useEffect(() => {
- if (scrollRef.current) {
- scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
- }
- }, [logs]);
-
- if (!logs || logs.length === 0) {
- return (
- <div className="flex-1 flex items-center justify-center px-3 py-6">
- <div className="font-pixel text-[8px] text-cyan-500/30 tracking-wide">No activity yet</div>
- </div>
- );
- }
-
- return (
- <div
- ref={scrollRef}
- className="flex-1 overflow-y-auto px-3 py-1.5 space-y-1"
- style={{ scrollbarWidth: 'thin', scrollbarColor: 'rgba(6,182,212,0.2) transparent' }}
- >
- {logs.slice(-40).map((log) => {
- const level = log.level || 'info';
- const colorClass = LEVEL_COLORS[level] || LEVEL_COLORS.info;
- const indicatorClass = LEVEL_INDICATORS[level] || LEVEL_INDICATORS.info;
- const time = log.timestamp ? formatClockTime(new Date(log.timestamp)) : '';
- const message = log.message || log.event || JSON.stringify(log);
- const key = log._localId ?? `${log.timestamp}-${message}`;
-
- return (
- <div
- key={key}
- className="font-pixel text-[9px] leading-tight flex items-start gap-1.5 tracking-wide group hover:bg-cyan-500/5 rounded px-1 py-0.5 -mx-1 transition-colors"
- title={message}
- >
- <span className={`w-1 h-1 rounded-full ${indicatorClass} shrink-0 mt-1 opacity-70`} />
- <span className="text-gray-500 shrink-0">{time}</span>
- <span className={`${colorClass} truncate group-hover:whitespace-normal group-hover:break-all`}>{message}</span>
- </div>
- );
- })}
- </div>
- );
-}
-
-const DENSITY_BAR_COLORS = {
- error: 'bg-port-error',
- warn: 'bg-port-warning',
- success: 'bg-port-success',
- info: 'bg-cyan-400',
- debug: 'bg-gray-600',
-};
-
-const relativeAge = (ms) => {
- const s = Math.floor(ms / 1000);
- if (s < 10) return 'now';
- if (s < 60) return `${s}s`;
- const m = Math.floor(s / 60);
- if (m < 60) return `${m}m`;
- return `${Math.floor(m / 60)}h`;
-};
-
-// Temporal view of the event stream: a density sparkbar (when did bursts of
-// activity happen) over relative-age buckets (what happened, newest first).
-// Reads the same `eventLogs` the ACTIVITY tab does — no new data wiring.
-function TimelineView({ logs, onOpenFastTravel }) {
- // Tick `now` every 15s so "2m" ages forward without re-fetching anything.
- const [now, setNow] = useState(() => Date.now());
- useEffect(() => {
- const id = setInterval(() => setNow(Date.now()), 15_000);
- return () => clearInterval(id);
- }, []);
-
- const density = useMemo(() => computeActivityDensity(logs, { now }), [logs, now]);
- const buckets = useMemo(() => buildTimelineBuckets(logs, { now }), [logs, now]);
- const maxCount = useMemo(() => Math.max(1, ...density.map(d => d.count)), [density]);
-
- if (!logs || logs.length === 0) {
- return (
- <div className="flex-1 flex items-center justify-center px-3 py-6">
- <div className="font-pixel text-[8px] text-cyan-500/30 tracking-wide">No recent activity</div>
- </div>
- );
- }
-
- return (
- <div
- className="flex-1 overflow-y-auto px-3 py-2 space-y-2.5"
- style={{ scrollbarWidth: 'thin', scrollbarColor: 'rgba(6,182,212,0.2) transparent' }}
- >
- {/* Density sparkbar — last 10 minutes, oldest at left */}
- <div>
- <div className="flex items-center justify-between mb-1">
- <span className="font-pixel text-[8px] text-cyan-500/50 tracking-wider">ACTIVITY · 10 MIN</span>
- <span className="font-pixel text-[8px] text-cyan-500/30 tracking-wider">NOW {'>'}</span>
- </div>
- <div className="flex items-end gap-px h-8" title="Event density over the last 10 minutes">
- {density.map((slot, i) => {
- // Floor non-empty bins at 12% so a single event is still visible.
- const heightPct = slot.count > 0 ? Math.max(12, (slot.count / maxCount) * 100) : 0;
- const colorClass = slot.level ? (DENSITY_BAR_COLORS[slot.level] || DENSITY_BAR_COLORS.info) : 'bg-cyan-500/10';
- return (
- <div key={i} className="flex-1 flex items-end h-full">
- <div
- className={`w-full rounded-sm ${colorClass} ${slot.count > 0 ? 'opacity-80' : 'opacity-100'}`}
- style={{ height: slot.count > 0 ? `${heightPct}%` : '2px' }}
- />
- </div>
- );
- })}
- </div>
- </div>
-
- {/* Time-bucketed event spine, newest first */}
- <div className="space-y-2">
- {buckets.map(bucket => (
- <div key={bucket.id}>
- <div className="font-pixel text-[8px] text-cyan-500/40 tracking-widest mb-1 border-b border-cyan-500/10 pb-0.5">
- {bucket.label}
- </div>
- <div className="space-y-1 pl-1">
- {bucket.events.map(event => {
- const colorClass = LEVEL_COLORS[event.level] || LEVEL_COLORS.info;
- const indicatorClass = LEVEL_INDICATORS[event.level] || LEVEL_INDICATORS.info;
- return (
- <div
- key={event.id}
- className="font-pixel text-[9px] leading-tight flex items-start gap-1.5 tracking-wide group hover:bg-cyan-500/5 rounded px-1 py-0.5 -mx-1"
- title={event.message}
- >
- <span className={`w-1 h-1 rounded-full ${indicatorClass} shrink-0 mt-1 opacity-70`} />
- <span className="text-gray-500 shrink-0 w-7 text-right">{relativeAge(event.ageMs)}</span>
- <span className={`${colorClass} truncate group-hover:whitespace-normal group-hover:break-all`}>
- {event.message || '(event)'}
- </span>
- </div>
- );
- })}
- </div>
- </div>
- ))}
- </div>
-
- <button
- type="button"
- onClick={onOpenFastTravel}
- className="w-full font-pixel text-[8px] text-cyan-500/40 hover:text-cyan-400 tracking-wider py-1 transition-colors"
- >
- OPEN WORLD MAP {'>'}
- </button>
- </div>
- );
-}
-
-// Intel-pane tabs. `attention`/`timeline`/`activity` line up with the same-named
-// `openWorldPane` values so the desktop tab and the compact disclosure sheet address the
-// same surface through one URL param.
-export const CITY_INTEL_TABS = [
- { id: 'attention', label: 'ATTENTION', hint: 'Things needing your attention' },
- { id: 'timeline', label: 'TIMELINE', hint: 'Recent-action timeline' },
- { id: 'activity', label: 'ACTIVITY', hint: 'Live event log' },
-];
-
-// Renders just the body for a given intel tab — reused by the desktop cockpit pane
-// and the compact/phone disclosure sheet so both show identical content. The parent
-// must be a bounded `flex flex-col` container (the lists are `flex-1`).
-export function OpenWorldIntelContent({ tab, items, eventLogs, onItemActivate, onOpenFastTravel }) {
- if (tab === 'timeline') return <TimelineView logs={eventLogs} onOpenFastTravel={onOpenFastTravel} />;
- if (tab === 'activity') return <ActivityLogList logs={eventLogs} />;
- return <AttentionList items={items} onItemActivate={onItemActivate} />;
-}
-
-export default function OpenWorldIntelPane({ apps, cosAgents, reviewCounts, instances, systemHealth, notificationCounts, eventLogs, onItemActivate, onOpenFastTravel }) {
- // The active tab is URL-addressable via `openWorldPane` (shared with the compact
- // layout), so a reload / back-forward restores it and a deep link opens it.
- // `vitals`/`map`/etc. aren't intel tabs, so anything outside the intel subset
- // falls back to `attention`.
- const [activePane, setActivePane] = useDrawerTab('openWorldPane', null, CITY_PANE_IDS);
- const tab = CITY_INTEL_PANE_IDS.includes(activePane) ? activePane : 'attention';
- const [collapsed, setCollapsed] = useState(false);
-
- const items = useMemo(
- () => buildAttentionItems({ apps, cosAgents, reviewCounts, instances, systemHealth, notificationCounts }),
- [apps, cosAgents, reviewCounts, instances, systemHealth, notificationCounts]
- );
-
- const criticalCount = items.filter(i => i.severity === 'critical').length;
- const selectTab = (id) => { setActivePane(id); setCollapsed(false); };
-
- // Roving tabindex: only the selected tab is in the sequential tab order, and
- // Left/Right/Home/End move selection *and* focus between tabs (WAI-ARIA
- // automatic-activation tabs pattern).
- const tabRefs = useRef({});
- const onTabKeyDown = (e) => {
- const dir = { ArrowRight: 1, ArrowLeft: -1 }[e.key];
- let next = null;
- if (dir) {
- const i = CITY_INTEL_TABS.findIndex(t => t.id === tab);
- next = CITY_INTEL_TABS[(i + dir + CITY_INTEL_TABS.length) % CITY_INTEL_TABS.length].id;
- } else if (e.key === 'Home') next = CITY_INTEL_TABS[0].id;
- else if (e.key === 'End') next = CITY_INTEL_TABS[CITY_INTEL_TABS.length - 1].id;
- if (!next) return;
- e.preventDefault();
- selectTab(next);
- tabRefs.current[next]?.focus();
- };
-
- const tabCount = (id) => {
- if (id === 'attention') return items.length;
- if (id === 'activity') return eventLogs?.length || 0;
- return 0;
- };
-
- return (
- <div className={`absolute top-20 right-4 ${collapsed ? '' : 'bottom-24'} w-[19rem] max-w-[calc(100vw-1rem)] pointer-events-auto`}>
- <div className={`${collapsed ? '' : 'h-full'} openworld-intel-surface overflow-hidden flex flex-col`}>
- <div className="flex items-stretch border-b border-cyan-500/20">
- {/* Deliberately NOT `ui/TabPills`: this bar wears the immersive OpenWorld
- HUD skin (cyan-on-black, `font-pixel` micro-caps, per-tab severity-tinted
- count chips) that the shared component hardcodes as port-accent, and it
- can only be expressed there by adding a one-off variant that no other
- call site would use. The ARIA/roving-tabindex wiring below mirrors
- TabPills' contract, so audits can skip this divergence. */}
- <div className="flex-1 flex items-stretch min-w-0" role="tablist" aria-label="Intel">
- {CITY_INTEL_TABS.map((t, i) => {
- const active = t.id === tab;
- const count = tabCount(t.id);
- return (
- <button
- key={t.id}
- ref={(el) => { tabRefs.current[t.id] = el; }}
- type="button"
- role="tab"
- id={`city-intel-tab-${t.id}`}
- aria-selected={active}
- // Only one panel is mounted at a time, so only the selected tab
- // owns an `aria-controls` — an inactive tab would otherwise point
- // at an element that doesn't exist.
- aria-controls={active && !collapsed ? `city-intel-panel-${t.id}` : undefined}
- tabIndex={active ? 0 : -1}
- onKeyDown={onTabKeyDown}
- onClick={() => selectTab(t.id)}
- className={`flex-1 min-w-0 flex items-center justify-center gap-1.5 px-2 py-2 transition-colors ${
- i > 0 ? 'border-l border-cyan-500/20' : ''
- } ${active ? 'bg-cyan-500/10 text-cyan-400' : 'text-cyan-500/50 hover:bg-cyan-500/5'}`}
- title={t.hint}
- >
- <span className="font-pixel text-[10px] tracking-wider font-bold">{t.label}</span>
- {count > 0 && (t.id === 'attention' ? (
- <span className={`font-pixel text-[9px] px-1 rounded ${
- criticalCount > 0 ? 'bg-port-error/30 text-port-error' : 'bg-cyan-500/20 text-cyan-300'
- }`}>
- {count}
- </span>
- ) : (
- <span className="font-pixel text-[9px] text-cyan-500/40">{count}</span>
- ))}
- </button>
- );
- })}
- </div>
- <button
- type="button"
- onClick={() => setCollapsed(c => !c)}
- className="px-2 py-2 border-l border-cyan-500/20 text-cyan-500/50 hover:bg-cyan-500/5 hover:text-cyan-400 transition-colors"
- title={collapsed ? 'Expand' : 'Collapse'}
- aria-expanded={!collapsed}
- aria-controls={collapsed ? undefined : `city-intel-panel-${tab}`}
- aria-label={collapsed ? 'Expand intel pane' : 'Collapse intel pane'}
- >
- <span className="font-pixel text-[11px]">{collapsed ? '[+]' : '[-]'}</span>
- </button>
- </div>
- {!collapsed && (
- <div
- role="tabpanel"
- id={`city-intel-panel-${tab}`}
- aria-labelledby={`city-intel-tab-${tab}`}
- // An empty tab renders no focusable children, so the panel itself has to
- // be a tab stop or keyboard users can't reach its content at all.
- tabIndex={0}
- className="flex-1 min-h-0 flex flex-col focus:outline-none focus-visible:ring-1 focus-visible:ring-cyan-400/60"
- >
- <OpenWorldIntelContent tab={tab} items={items} eventLogs={eventLogs} onItemActivate={onItemActivate} onOpenFastTravel={onOpenFastTravel} />
- </div>
- )}
- </div>
- </div>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldIntelPane.test.jsx b/client/src/components/openworld/OpenWorldIntelPane.test.jsx
deleted file mode 100644
index dbace3403f..0000000000
--- a/client/src/components/openworld/OpenWorldIntelPane.test.jsx
+++ /dev/null
@@ -1,81 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import { render, screen, fireEvent } from '@testing-library/react';
-import { MemoryRouter } from 'react-router';
-import OpenWorldIntelPane from './OpenWorldIntelPane';
-
-function renderPane(props = {}) {
- return render(
- <MemoryRouter>
- <OpenWorldIntelPane apps={[]} cosAgents={[]} instances={[]} eventLogs={[]} {...props} />
- </MemoryRouter>
- );
-}
-
-describe('OpenWorldIntelPane tab bar', () => {
- it('exposes exactly the three intel tabs in a labelled tablist', () => {
- renderPane();
- const list = screen.getByRole('tablist', { name: 'Intel' });
- const tabs = screen.getAllByRole('tab');
- expect(tabs.map(t => t.textContent)).toEqual(['ATTENTION', 'TIMELINE', 'ACTIVITY']);
- // The collapse toggle is a sibling of the tablist, not a child of it —
- // a non-tab child would be an invalid `role="tablist"` owner.
- expect(list).not.toContainElement(screen.getByRole('button', { name: /collapse intel pane/i }));
- });
-
- it('wires aria-selected, roving tabindex, and aria-controls to a matching tabpanel', () => {
- renderPane();
- const [attention, timeline] = screen.getAllByRole('tab');
- expect(attention).toHaveAttribute('aria-selected', 'true');
- expect(attention).toHaveAttribute('tabindex', '0');
- expect(timeline).toHaveAttribute('aria-selected', 'false');
- expect(timeline).toHaveAttribute('tabindex', '-1');
-
- const panel = screen.getByRole('tabpanel');
- expect(attention.getAttribute('aria-controls')).toBe(panel.id);
- expect(panel.getAttribute('aria-labelledby')).toBe(attention.id);
- // Only one panel is mounted, so an unselected tab must not point at a
- // nonexistent element.
- expect(timeline).not.toHaveAttribute('aria-controls');
- // An empty panel has no focusable children — it must be its own tab stop.
- expect(panel).toHaveAttribute('tabindex', '0');
- });
-
- it('moves selection and focus with arrow keys and wraps, and jumps with Home/End', () => {
- renderPane();
- const tabs = () => screen.getAllByRole('tab');
- const step = (from, key, to) => {
- fireEvent.keyDown(tabs()[from], { key });
- expect(tabs()[to]).toHaveAttribute('aria-selected', 'true');
- expect(document.activeElement).toBe(tabs()[to]);
- };
- step(0, 'ArrowRight', 1);
- step(1, 'End', 2);
- step(2, 'ArrowRight', 0); // wraps forward
- step(0, 'ArrowLeft', 2); // wraps backward
- step(2, 'Home', 0);
- });
-
- it('collapses the panel and drops the stale aria-controls reference', () => {
- renderPane();
- const toggle = screen.getByRole('button', { name: /collapse intel pane/i });
- expect(toggle).toHaveAttribute('aria-expanded', 'true');
- fireEvent.click(toggle);
-
- expect(screen.queryByRole('tabpanel')).toBeNull();
- const expand = screen.getByRole('button', { name: /expand intel pane/i });
- expect(expand).toHaveAttribute('aria-expanded', 'false');
- expect(expand).not.toHaveAttribute('aria-controls');
- // Selection survives the collapse; the tab just has no rendered panel to own.
- const [attention] = screen.getAllByRole('tab');
- expect(attention).toHaveAttribute('aria-selected', 'true');
- expect(attention).not.toHaveAttribute('aria-controls');
- });
-
- it('re-expands when a tab is clicked while collapsed', () => {
- renderPane();
- fireEvent.click(screen.getByRole('button', { name: /collapse intel pane/i }));
- fireEvent.click(screen.getAllByRole('tab')[1]);
- expect(screen.getByRole('tabpanel')).toBeTruthy();
- expect(screen.getAllByRole('tab')[1]).toHaveAttribute('aria-selected', 'true');
- });
-});
diff --git a/client/src/components/openworld/OpenWorldInteractionPrompt.jsx b/client/src/components/openworld/OpenWorldInteractionPrompt.jsx
deleted file mode 100644
index fd12ab49e6..0000000000
--- a/client/src/components/openworld/OpenWorldInteractionPrompt.jsx
+++ /dev/null
@@ -1,31 +0,0 @@
-function targetCopy(target) {
- if (!target) return null;
- const isWarpPad = target.type === 'warpPad';
- const label = target.label || (isWarpPad ? 'REGION' : 'BUILDING');
- return {
- eyebrow: target.eyebrow || (isWarpPad ? 'WARP GATE' : 'NEARBY BUILDING'),
- action: target.action || (isWarpPad ? 'WARP TO' : 'OPEN'),
- label,
- };
-}
-
-export default function OpenWorldInteractionPrompt({ target, compact = false }) {
- const copy = targetCopy(target);
- if (!copy) return null;
-
- return (
- <div
- className={`openworld-interaction-prompt ${compact ? 'openworld-interaction-prompt--compact' : ''}`}
- role="status"
- aria-live="polite"
- data-testid="openworld-interaction-prompt"
- >
- <span className="openworld-hud-eyebrow">{copy.eyebrow}</span>
- <span className="openworld-interaction-prompt__label">{copy.label}</span>
- <span className="openworld-interaction-prompt__action">
- <kbd>{compact ? 'ACTION' : 'F'}</kbd>
- {copy.action}
- </span>
- </div>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldJiraDistrict.jsx b/client/src/components/openworld/OpenWorldJiraDistrict.jsx
deleted file mode 100644
index df9ca39d7f..0000000000
--- a/client/src/components/openworld/OpenWorldJiraDistrict.jsx
+++ /dev/null
@@ -1,118 +0,0 @@
-import { useMemo, useRef } from 'react';
-import { useFrame } from '@react-three/fiber';
-import { PIXEL_FONT_URL, openWorldDayMix } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import OpenWorldLabel from './OpenWorldLabel';
-import { computeJiraDistrict, JIRA_DISTRICT } from '../../utils/openWorldJiraDistrict';
-
-// OpenWorld's JIRA sprint district (roadmap 3.7): the current sprint's tickets become a small
-// construction yard. To-Do tickets are stacked crates (unbuilt), In-Progress tickets are
-// under-construction wireframe frames (scaffold), and Done tickets are finished, lit buildings.
-// Tickets are gathered across every JIRA-enabled app and deduped by key in the pure helper; this
-// component only renders + animates. Mirrors OpenWorldTaskQueue / OpenWorldGoalMonuments.
-
-// One ticket structure. The mesh form is chosen by workflow state so the yard reads as work
-// progressing from crates → scaffolds → finished buildings.
-function SprintStructure({ structure, pulseRef, isPulse }) {
- const { tintStructure } = useOpenWorldPalette();
- const { position, color, height, state } = structure;
- const size = JIRA_DISTRICT.crateSize;
-
- if (state === 'done') {
- // Finished building — solid, emissive, the in-progress pulse never lands here.
- return (
- <group position={position}>
- <mesh position={[0, height / 2, 0]}>
- <boxGeometry args={[size, height, size]} />
- <meshStandardMaterial color={tintStructure('#0d1a12')} emissive={color} emissiveIntensity={0.7} metalness={0.6} roughness={0.4} toneMapped={false} />
- </mesh>
- </group>
- );
- }
-
- if (state === 'inProgress') {
- // Under construction — a built lower portion topped by a translucent scaffold cage that
- // breathes (the pulse target). Reads as "actively being worked".
- const builtH = Math.max(0.4, height * 0.45);
- const scaffoldH = Math.max(0.3, height - builtH);
- return (
- <group position={position}>
- <mesh position={[0, builtH / 2, 0]}>
- <boxGeometry args={[size, builtH, size]} />
- <meshStandardMaterial color="#1a1206" emissive={color} emissiveIntensity={0.5} metalness={0.4} roughness={0.6} toneMapped={false} />
- </mesh>
- <mesh ref={isPulse ? pulseRef : undefined} position={[0, builtH + scaffoldH / 2, 0]}>
- <boxGeometry args={[size * 1.05, scaffoldH, size * 1.05]} />
- <meshStandardMaterial color={color} emissive={color} emissiveIntensity={0.5} wireframe transparent opacity={0.7} toneMapped={false} />
- </mesh>
- </group>
- );
- }
-
- // To-Do — a stack of dim crates waiting to be built.
- const crateH = size * 0.7;
- const crates = Math.max(1, Math.round(height / crateH));
- return (
- <group position={position}>
- {Array.from({ length: crates }, (_, i) => (
- <mesh key={i} position={[0, crateH * (i + 0.5), 0]}>
- <boxGeometry args={[size * 0.9, crateH * 0.9, size * 0.9]} />
- <meshStandardMaterial color="#161a22" emissive={color} emissiveIntensity={0.18} metalness={0.5} roughness={0.7} />
- </mesh>
- ))}
- </group>
- );
-}
-
-export default function OpenWorldJiraDistrict({ jiraTickets, settings }) {
- const district = useMemo(() => computeJiraDistrict(jiraTickets), [jiraTickets]);
- const pulseRef = useRef();
-
- const animate = (settings?.particleDensity ?? 1) >= 0.5;
- const dayMix = openWorldDayMix(settings);
-
- // The first in-progress structure carries a breathing scaffold glow (one ref mutation/frame).
- const pulseKey = useMemo(
- () => district.structures.find(s => s.state === 'inProgress')?.key ?? null,
- [district.structures]
- );
-
- useFrame(({ clock }) => {
- if (!pulseRef.current) return;
- if (!animate) { pulseRef.current.material.emissiveIntensity = 0.5; return; }
- const pulse = (Math.sin(clock.getElapsedTime() * 2.2) + 1) / 2;
- pulseRef.current.material.emissiveIntensity = 0.4 + pulse * 0.5;
- });
-
- if (district.empty) return null;
-
- const { base, structures, counts, total, overflow, overflowPosition } = district;
-
- return (
- <group>
- {structures.map((structure) => (
- <SprintStructure
- key={structure.key}
- structure={structure}
- pulseRef={pulseRef}
- isPulse={structure.key === pulseKey}
- />
- ))}
-
- {/* Overflow marker — tickets past the render cap */}
- {overflow > 0 && overflowPosition && (
- <OpenWorldLabel position={[overflowPosition[0], 1.4, overflowPosition[2]]} fontSize={0.5} color="#94a3b8" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={9}>
- {`+${overflow} MORE`}
- </OpenWorldLabel>
- )}
-
- {/* District title + sprint progress */}
- <OpenWorldLabel position={[base[0], 12, base[2] - 2]} fontSize={1.2} color="#3b82f6" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={30}>
- SPRINT
- </OpenWorldLabel>
- <OpenWorldLabel position={[base[0], 11.1, base[2] - 2]} fontSize={0.72} color="#94a3b8" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={30}>
- {`${counts.done}/${total} DONE · ${counts.inProgress} IN PROGRESS`}
- </OpenWorldLabel>
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldLabel.jsx b/client/src/components/openworld/OpenWorldLabel.jsx
deleted file mode 100644
index f8677814f2..0000000000
--- a/client/src/components/openworld/OpenWorldLabel.jsx
+++ /dev/null
@@ -1,34 +0,0 @@
-import { forwardRef } from 'react';
-import { Text } from '@react-three/drei';
-import { openWorldLabelColors } from './openWorldConstants';
-
-// A drei <Text> for an informational in-world label (app/process names, district
-// readouts) that stays legible day AND night. Pass the night/neon `color` plus the
-// scene `dayMix` (0 night → 1 day); the label keeps its neon fill at night and swaps
-// to dark ink + a light outline halo as day ramps up. Every other <Text> prop
-// (position, fontSize, font, anchorX, fillOpacity, children, …) passes straight
-// through. A caller may still override `outlineColor` explicitly.
-//
-// Use this for content the user needs to READ in daytime. Decorative neon signage
-// (OpenWorldNeonSigns, ambient billboards) intentionally does NOT use it — neon should
-// dim in daylight like the real thing.
-const OpenWorldLabel = forwardRef(function OpenWorldLabel({ color, dayMix = 0, outlineColor, ...props }, ref) {
- const themed = openWorldLabelColors(color, dayMix);
- // Small tracking and a consistent line box keep stacked labels from collapsing into
- // the pixel glyphs. A slight depth bias prevents facades and signs from eating the ink.
- return (
- <Text
- ref={ref}
- {...props}
- letterSpacing={props.letterSpacing ?? 0.01}
- lineHeight={props.lineHeight ?? 1.1}
- depthOffset={props.depthOffset ?? -1}
- color={themed.color}
- outlineColor={outlineColor ?? themed.outlineColor}
- outlineWidth={themed.outlineWidth}
- outlineOpacity={themed.outlineOpacity}
- />
- );
-});
-
-export default OpenWorldLabel;
diff --git a/client/src/components/openworld/OpenWorldLandscape.jsx b/client/src/components/openworld/OpenWorldLandscape.jsx
deleted file mode 100644
index 0f73e0a14b..0000000000
--- a/client/src/components/openworld/OpenWorldLandscape.jsx
+++ /dev/null
@@ -1,189 +0,0 @@
-import { useEffect, useMemo } from 'react';
-import * as THREE from 'three';
-import { openWorldDayMix, mixHex, seededRand, smoothstepRange } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import { WORLD } from '../../utils/openWorldPlan';
-
-const TERRAIN_SIZE = 2400;
-const MOUNTAIN_INNER_RADIUS = 560;
-const MOUNTAIN_RADIUS_SPREAD = 190;
-
-const TERRAIN_VERT = `
- varying vec2 vUv;
- varying vec3 vWorldPosition;
- void main() {
- vUv = uv;
- vec4 worldPos = modelMatrix * vec4(position, 1.0);
- vWorldPosition = worldPos.xyz;
- gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
- }
-`;
-
-const TERRAIN_FRAG = `
- uniform vec3 uInner;
- uniform vec3 uMeadow;
- uniform vec3 uRidge;
- uniform vec3 uAccent;
- uniform float uDayMix;
- varying vec2 vUv;
- varying vec3 vWorldPosition;
-
- float hash(vec2 p) {
- return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
- }
-
- float noise(vec2 p) {
- vec2 i = floor(p);
- vec2 f = fract(p);
- f = f * f * (3.0 - 2.0 * f);
- float a = hash(i);
- float b = hash(i + vec2(1.0, 0.0));
- float c = hash(i + vec2(0.0, 1.0));
- float d = hash(i + vec2(1.0, 1.0));
- return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
- }
-
- void main() {
- float dist = length(vWorldPosition.xz);
- float meadowMix = smoothstep(42.0, 86.0, dist);
- float ridgeMix = smoothstep(260.0, 760.0, dist);
- float n = noise(vWorldPosition.xz * 0.035);
- float largeN = noise(vWorldPosition.xz * 0.006);
- vec3 color = mix(uInner, uMeadow, meadowMix);
- color = mix(color, uRidge, ridgeMix * mix(0.26, 0.42, uDayMix));
- color += (n - 0.5) * mix(0.025, 0.06, uDayMix);
- color += (largeN - 0.5) * mix(0.025, 0.045, uDayMix);
-
- // Keep a faint themed tech trace near the city, but let nature dominate outside.
- float openWorldTrace = (1.0 - meadowMix) * 0.08 * (1.0 - uDayMix * 0.65);
- color = mix(color, uAccent, openWorldTrace);
-
- gl_FragColor = vec4(color, 1.0);
- }
-`;
-
-function TerrainPlane({ dayMix, accent, terrain }) {
- const material = useMemo(() => new THREE.ShaderMaterial({
- vertexShader: TERRAIN_VERT,
- fragmentShader: TERRAIN_FRAG,
- uniforms: {
- // Night bands are shared; the daytime bands come from the active world style's
- // terrain trio (WORLD_STYLE_DEFS in openWorldConstants), so retuning a style's ground
- // doesn't mean grepping raw hexes across two files.
- uInner: { value: new THREE.Color(mixHex('#202426', terrain.inner, dayMix)) },
- uMeadow: { value: new THREE.Color(mixHex('#172719', terrain.meadow, dayMix)) },
- uRidge: { value: new THREE.Color(mixHex('#111827', terrain.ridge, dayMix)) },
- uAccent: { value: new THREE.Color(accent) },
- uDayMix: { value: dayMix },
- },
- side: THREE.DoubleSide,
- depthWrite: true,
- // accent intentionally NOT a dep — a theme switch updates the uniform in
- // place (effect below) rather than recompiling the GLSL program. Matches the
- // imperative-uniform pattern in OpenWorldSky / OpenWorldBillboards / OpenWorldVolumetricLights.
- }), [dayMix, terrain]);
-
- // Push the accent into the existing material on theme change — no rebuild.
- useEffect(() => { material.uniforms.uAccent.value.set(accent); }, [material, accent]);
-
- // R3F doesn't dispose a material handed in via the `material` prop, so free the
- // prior one when dayMix flips (Day/Night toggle) and on unmount.
- useEffect(() => () => material.dispose(), [material]);
-
- return (
- <mesh
- rotation={[-Math.PI / 2, 0, 0]}
- position={[0, WORLD.terrainY, 0]}
- material={material}
- frustumCulled={false}
- >
- <planeGeometry args={[TERRAIN_SIZE, TERRAIN_SIZE, 1, 1]} />
- </mesh>
- );
-}
-
-function Mountain({ mountain, dayMix, surface }) {
- const geometry = useMemo(() => {
- const geom = new THREE.ConeGeometry(mountain.radius, mountain.height, mountain.sides, 6);
- const position = geom.getAttribute('position');
- const colors = [];
- const base = new THREE.Color(mixHex('#111827', '#9aa794', dayMix));
- const lit = new THREE.Color(mixHex('#243044', '#dfe7d8', dayMix));
- const snow = new THREE.Color(mixHex('#64748b', '#f4f7f0', dayMix));
-
- for (let i = 0; i < position.count; i += 1) {
- const y = (position.getY(i) + mountain.height / 2) / mountain.height;
- const shoulder = smoothstepRange(0.22, 0.88, y);
- const snowMix = smoothstepRange(0.68, 0.95, y) * mountain.snow;
- const color = base.clone()
- .lerp(lit, Math.min(1, mountain.light + shoulder * 0.28))
- .lerp(snow, snowMix);
- colors.push(color.r, color.g, color.b);
- }
-
- geom.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
- geom.computeVertexNormals();
- return geom;
- }, [dayMix, mountain.height, mountain.light, mountain.radius, mountain.sides, mountain.snow]);
-
- // Attached via <primitive object={geometry}>, which R3F never auto-disposes —
- // free the prior cone when dayMix rebuilds it, and on unmount.
- useEffect(() => () => geometry.dispose(), [geometry]);
-
- return (
- <group position={mountain.position} rotation={[0, mountain.rotation, 0]} scale={mountain.scale}>
- <mesh position={[0, mountain.height / 2 - 0.08, 0]}>
- <primitive attach="geometry" object={geometry} />
- <meshStandardMaterial
- vertexColors
- roughness={0.92}
- metalness={0}
- depthWrite
- {...surface}
- />
- </mesh>
- </group>
- );
-}
-
-export default function OpenWorldLandscape({ settings }) {
- const { accent, terrain, surface } = useOpenWorldPalette();
- const dayMix = openWorldDayMix(settings);
-
- const mountains = useMemo(() => {
- const result = [];
- const rand = seededRand(3187);
- const count = 28;
-
- for (let i = 0; i < count; i++) {
- const angle = (i / count) * Math.PI * 2 + (rand() - 0.5) * 0.16;
- const radius = MOUNTAIN_INNER_RADIUS + rand() * MOUNTAIN_RADIUS_SPREAD;
- const height = 42 + rand() * 66;
- const base = 72 + rand() * 86;
- result.push({
- id: `mountain-${i}`,
- position: [Math.cos(angle) * radius, 0, Math.sin(angle) * radius],
- rotation: -angle + Math.PI / 2,
- height,
- radius: base,
- sides: rand() > 0.45 ? 4 : 5,
- light: 0.18 + rand() * 0.34,
- snow: rand() > 0.35 ? 1 : 0.35,
- scale: [1.1 + rand() * 1.8, 1, 0.2 + rand() * 0.22],
- });
- }
-
- return result;
- }, []);
-
- return (
- <group>
- <TerrainPlane dayMix={dayMix} accent={accent} terrain={terrain} />
- <group>
- {mountains.map((mountain) => (
- <Mountain key={mountain.id} mountain={mountain} dayMix={dayMix} surface={surface} />
- ))}
- </group>
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldLights.jsx b/client/src/components/openworld/OpenWorldLights.jsx
deleted file mode 100644
index 3964b548a4..0000000000
--- a/client/src/components/openworld/OpenWorldLights.jsx
+++ /dev/null
@@ -1,212 +0,0 @@
-import { useRef } from 'react';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { openWorldShowDetail, getTimeOfDayPreset } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-
-// Animated accent light that slowly shifts color, with reactive brightness
-function AnimatedLight({ position, baseColor, baseIntensity, distance, shiftRange = 0.1, speed = 0.5, brightnessRef, neonScaleRef }) {
- const ref = useRef();
-
- useFrame(({ clock }) => {
- if (!ref.current) return;
- const b = brightnessRef.current;
- const ns = neonScaleRef?.current ?? 1;
- const t = clock.getElapsedTime();
- ref.current.intensity = (baseIntensity + Math.sin(t * speed) * baseIntensity * shiftRange) * b * ns;
- });
-
- return (
- <pointLight
- ref={ref}
- position={position}
- intensity={baseIntensity}
- color={baseColor}
- distance={distance}
- />
- );
-}
-
-// Sweeping searchlight effect with reactive brightness
-function Searchlight({ brightnessRef, neonScaleRef }) {
- const ref = useRef();
-
- useFrame(({ clock }) => {
- if (!ref.current) return;
- const t = clock.getElapsedTime();
- const angle = t * 0.2;
- const radius = 25;
- ref.current.position.x = Math.cos(angle) * radius;
- ref.current.position.z = Math.sin(angle) * radius;
- const ns = neonScaleRef?.current ?? 1;
- ref.current.intensity = 0.6 * brightnessRef.current * ns;
- ref.current.target.position.set(0, 0, 0);
- ref.current.target.updateMatrixWorld();
- });
-
- return (
- <spotLight
- ref={ref}
- position={[25, 30, 0]}
- intensity={0.6}
- color="#06b6d4"
- angle={0.2}
- penumbra={0.8}
- distance={90}
- decay={1.2}
- castShadow={false}
- />
- );
-}
-
-// Static point light that updates intensity every frame from brightness ref
-function ReactivePointLight({ position, baseIntensity, color, distance, brightnessRef, neonScaleRef }) {
- const ref = useRef();
-
- useFrame(() => {
- if (!ref.current) return;
- const ns = neonScaleRef?.current ?? 1;
- ref.current.intensity = baseIntensity * brightnessRef.current * ns;
- });
-
- return (
- <pointLight
- ref={ref}
- position={position}
- intensity={baseIntensity}
- color={color}
- distance={distance}
- />
- );
-}
-
-export default function OpenWorldLights({ settings, lightingTier }) {
- const { ground } = useOpenWorldPalette();
- const brightnessRef = useRef(settings?.ambientBrightness ?? 1.2);
- brightnessRef.current = settings?.ambientBrightness ?? 1.2;
-
- const timeOfDay = settings?.timeOfDay ?? 'sunset';
- const skyTheme = settings?.skyTheme ?? 'cyberpunk';
- const preset = getTimeOfDayPreset(timeOfDay, skyTheme);
- const cozyLighting = Boolean(settings?.explorationMode);
- const daylightFactor = cozyLighting ? Math.max(0.72, preset.daylightFactor ?? 0) : (preset.daylightFactor ?? 0);
- const nightGlow = 1 - Math.min(1, daylightFactor);
-
- // Medium tier and up — the same gate the rest of the optional set dressing uses, so the
- // low tier sheds light count along with the props those lights were there to accent.
- //
- // Gated on the SETTLED tier, not the render tier the rest of the set dressing
- // reads. OpenWorldScene pins `effectiveTier: 'low'` for the first 1.2s of every mount
- // and visibility resume, and light count is part of three.js's program cache key
- // — so reading the clamped tier here would recompile every MeshStandardMaterial
- // in the scene at the warm-up boundary, a stall at exactly the moment the warm-up
- // exists to avoid one. Falls back to `settings` when the prop is absent.
- const showAccentLights = openWorldShowDetail(lightingTier ? { effectiveTier: lightingTier } : settings);
-
- // Neon scale: dim neon point lights during daytime (30% at noon, 100% at night)
- const neonScaleRef = useRef(1);
- const targetNeonScale = 1.0 - daylightFactor * 0.7;
-
- // Hemisphere light refs — provides natural sky fill (like Unreal Engine's Sky Light)
- const hemiRef = useRef();
- const hemiSkyTarget = useRef(new THREE.Color(preset.hemiSkyColor));
- const hemiGroundTarget = useRef(new THREE.Color(preset.hemiGroundColor));
- hemiSkyTarget.current.set(cozyLighting ? '#b9d9dc' : preset.hemiSkyColor);
- hemiGroundTarget.current.set(cozyLighting ? '#7c7153' : preset.hemiGroundColor);
- const hemiIntensityTarget = useRef(preset.hemiIntensity);
- hemiIntensityTarget.current = (cozyLighting ? 0.92 : preset.hemiIntensity) * brightnessRef.current;
-
- // Ambient light refs
- const ambientRef = useRef();
- const ambientColorTarget = useRef(new THREE.Color(preset.ambientColor));
- ambientColorTarget.current.set(cozyLighting ? '#fff0ce' : preset.ambientColor);
- const ambientIntensityTarget = useRef(preset.ambientIntensity);
- ambientIntensityTarget.current = (cozyLighting ? 0.3 : preset.ambientIntensity) * brightnessRef.current;
-
- useFrame((_, delta) => {
- const lf = Math.min(1, delta * 3);
-
- // Lerp neon scale
- neonScaleRef.current += (targetNeonScale - neonScaleRef.current) * lf;
-
- // Hemisphere light — main daytime fill
- if (hemiRef.current) {
- hemiRef.current.color.lerp(hemiSkyTarget.current, lf);
- hemiRef.current.groundColor.lerp(hemiGroundTarget.current, lf);
- hemiRef.current.intensity += (hemiIntensityTarget.current - hemiRef.current.intensity) * lf;
- }
-
- // Ambient light
- if (ambientRef.current) {
- ambientRef.current.color.lerp(ambientColorTarget.current, lf);
- ambientRef.current.intensity += (ambientIntensityTarget.current - ambientRef.current.intensity) * lf;
- }
- });
-
- return (
- <>
- {/* Hemisphere sky light — like Unreal Engine's Sky Light, illuminates all geometry from sky/ground */}
- <hemisphereLight ref={hemiRef} color="#1a1a3a" groundColor="#0a0a20" intensity={0.3} />
- <ambientLight ref={ambientRef} intensity={0.18} color="#1a1a3a" />
- {cozyLighting && (
- <>
- {/* One authored sun creates the long readable shadows and object grounding the
- village references rely on. A soft amber fill keeps shaded porches warm. */}
- <directionalLight
- position={[-42, 68, 36]}
- color="#fff0c4"
- intensity={(0.72 + daylightFactor * 1.15) * brightnessRef.current}
- castShadow={showAccentLights}
- shadow-mapSize-width={2048}
- shadow-mapSize-height={2048}
- shadow-camera-left={-78}
- shadow-camera-right={78}
- shadow-camera-top={78}
- shadow-camera-bottom={-78}
- shadow-camera-near={1}
- shadow-camera-far={165}
- shadow-normalBias={0.035}
- />
- <ReactivePointLight position={[18, 14, 26]} baseIntensity={0.42} color="#ffb982" distance={82} brightnessRef={brightnessRef} neonScaleRef={neonScaleRef} />
- </>
- )}
- {!cozyLighting && (
- <>
- {/* Main overhead cyan */}
- <ReactivePointLight position={[0, 30, 0]} baseIntensity={1.2} color="#06b6d4" distance={100} brightnessRef={brightnessRef} neonScaleRef={neonScaleRef} />
- {/* Secondary overhead fill - broad white/blue */}
- <ReactivePointLight position={[0, 20, 10]} baseIntensity={0.5} color="#4488cc" distance={90} brightnessRef={brightnessRef} neonScaleRef={neonScaleRef} />
- {/* Broad nighttime city glow — signage bounce + moonlit haze, faded in daylight */}
- <ReactivePointLight position={[0, 16, 0]} baseIntensity={1.8 * nightGlow} color={ground} distance={150} brightnessRef={brightnessRef} neonScaleRef={neonScaleRef} />
- <ReactivePointLight position={[-28, 10, 24]} baseIntensity={1.05 * nightGlow} color="#ec4899" distance={118} brightnessRef={brightnessRef} neonScaleRef={neonScaleRef} />
- <ReactivePointLight position={[30, 12, -22]} baseIntensity={1.1 * nightGlow} color="#60a5fa" distance={120} brightnessRef={brightnessRef} neonScaleRef={neonScaleRef} />
- {/* Magenta accent from left - animated color shift */}
- <AnimatedLight position={[-20, 12, -15]} baseColor="#ec4899" baseIntensity={0.7} distance={60} speed={0.3} shiftRange={0.15} brightnessRef={brightnessRef} neonScaleRef={neonScaleRef} />
- {/* Blue accent from right - animated shift */}
- <AnimatedLight position={[20, 12, 15]} baseColor="#3b82f6" baseIntensity={0.7} distance={60} speed={0.4} shiftRange={0.12} brightnessRef={brightnessRef} neonScaleRef={neonScaleRef} />
- {/* Purple from behind - more presence */}
- <ReactivePointLight position={[0, 15, -25]} baseIntensity={0.5} color="#8b5cf6" distance={60} brightnessRef={brightnessRef} neonScaleRef={neonScaleRef} />
- {/* Warm orange ground level accent */}
- <ReactivePointLight position={[10, 3, 5]} baseIntensity={0.35} color="#f97316" distance={35} brightnessRef={brightnessRef} neonScaleRef={neonScaleRef} />
- </>
- )}
- {/* Ground-level small-radius accents (green + red warning). Culled on the low tier:
- every mounted light costs a per-fragment iteration in the lighting loop of every
- MeshStandardMaterial in the scene, whatever its intensity — so dimming them saves
- nothing and only unmounting does (#3397). These two are the least visually
- significant of the set: lowest intensity (0.2 / 0.15) and smallest radius (25 / 22
- units), so they only tint a small patch of street the low tier already renders
- without its set dressing. */}
- {showAccentLights && !cozyLighting && (
- <>
- {/* Additional green accent - ground level from opposite side */}
- <ReactivePointLight position={[-12, 3, 8]} baseIntensity={0.2} color="#22c55e" distance={25} brightnessRef={brightnessRef} neonScaleRef={neonScaleRef} />
- {/* Red warning accent from below-right */}
- <ReactivePointLight position={[15, 2, -10]} baseIntensity={0.15} color="#f43f5e" distance={22} brightnessRef={brightnessRef} neonScaleRef={neonScaleRef} />
- </>
- )}
- {/* Sweeping searchlight */}
- {!cozyLighting && <Searchlight brightnessRef={brightnessRef} neonScaleRef={neonScaleRef} />}
- </>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldLights.test.jsx b/client/src/components/openworld/OpenWorldLights.test.jsx
deleted file mode 100644
index ec6e7f941b..0000000000
--- a/client/src/components/openworld/OpenWorldLights.test.jsx
+++ /dev/null
@@ -1,50 +0,0 @@
-import { describe, it, expect, vi } from 'vitest';
-import { render } from '@testing-library/react';
-
-// jsdom has no WebGL context, so the real three.js stack can't mount. `useFrame` is
-// stubbed to a no-op — the per-frame intensity maths are irrelevant here; what this file
-// covers is which lights get MOUNTED per quality tier (#3397). The r3f primitives
-// (<pointLight>, <ambientLight>, …) render as unknown DOM elements, which is exactly what
-// makes them countable by tag name.
-vi.mock('@react-three/fiber', () => ({ useFrame: () => {} }));
-vi.mock('./OpenWorldPaletteContext', () => ({ useOpenWorldPalette: () => ({ ground: '#22d3ee' }) }));
-
-import OpenWorldLights from './OpenWorldLights';
-
-const pointLightCount = (settings) => {
- const { container } = render(<OpenWorldLights settings={settings} />);
- return container.getElementsByTagName('pointLight').length;
-};
-
-describe('OpenWorldLights quality-tier culling', () => {
- // Zero-intensity lights still cost a per-fragment iteration in every
- // MeshStandardMaterial's lighting loop, so the low tier has to shed the light
- // by unmounting it — dimming it saves nothing.
- it('drops the two ground-level accent lights on the low tier', () => {
- const full = pointLightCount({ effectiveTier: 'high' });
- expect(pointLightCount({ effectiveTier: 'low' })).toBe(full - 2);
- });
-
- it('leaves the medium tier and above untouched', () => {
- const high = pointLightCount({ effectiveTier: 'high' });
- expect(pointLightCount({ effectiveTier: 'medium' })).toBe(high);
- expect(pointLightCount({ effectiveTier: 'ultra' })).toBe(high);
- });
-
- it('keeps every light when no settings are supplied', () => {
- // Legacy/absent payloads fall through openWorldShowDetail's particleDensity default of 1,
- // so an install that never set effectiveTier keeps the established look.
- expect(pointLightCount(undefined)).toBe(pointLightCount({ effectiveTier: 'high' }));
- });
-
- it('keeps the key, fill and glow lights on the low tier', () => {
- // The cull is scoped to the two dimmest small-radius accents — the overhead key/fill
- // pair, the broad night glow, the animated side accents and the ambient/hemisphere
- // fill all stay, so the low tier is dimmer in one street corner, not gutted.
- const { container } = render(<OpenWorldLights settings={{ effectiveTier: 'low' }} />);
- expect(container.getElementsByTagName('pointLight').length).toBe(9);
- expect(container.getElementsByTagName('ambientLight').length).toBe(1);
- expect(container.getElementsByTagName('hemisphereLight').length).toBe(1);
- expect(container.getElementsByTagName('spotLight').length).toBe(1);
- });
-});
diff --git a/client/src/components/openworld/OpenWorldMemoryDistrict.jsx b/client/src/components/openworld/OpenWorldMemoryDistrict.jsx
deleted file mode 100644
index c4318fa822..0000000000
--- a/client/src/components/openworld/OpenWorldMemoryDistrict.jsx
+++ /dev/null
@@ -1,164 +0,0 @@
-import { useMemo, useRef } from 'react';
-import { useFrame } from '@react-three/fiber';
-import { PIXEL_FONT_URL, openWorldDayMix } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import OpenWorldLabel from './OpenWorldLabel';
-import OpenWorldTubeLine from './OpenWorldTubeLine';
-import { computeMemoryDistrict, MEMORY_DISTRICT } from '../../utils/openWorldMemoryDistrict';
-
-// OpenWorld's memory / knowledge district (roadmap 3.2): the user's long-term memory graph
-// crystallizes into a quiet northwest quarter. Each memory *category* is a cluster of glowing
-// octahedral crystals — taller and brighter the more (and more important) the memories — and
-// edges that connect different categories arc between clusters as light bridges. A central
-// "well" glows with the brain-inbox backlog: brighter and pulsing when captures are waiting to
-// be classified, calm when the inbox is clear. Mirrors OpenWorldGoalMonuments / OpenWorldBackupVault:
-// pure helper does all topology, this component only renders + animates.
-
-// One category's crystal cluster: a small ring of octahedra of varying height around the
-// cluster center, plus a category label. The tallest crystal carries the cluster's breathing
-// glow (one per-frame ref mutation per cluster).
-function CrystalCluster({ cluster, glowRef, isGlow, dayMix = 0 }) {
- const { position, color, height, crystals, label, count, isOverflow } = cluster;
- // Arrange the crystals in a tight ring; the count is already capped in the helper.
- const ring = useMemo(() => {
- const out = [];
- for (let i = 0; i < crystals; i++) {
- const a = (i / crystals) * Math.PI * 2;
- const r = crystals === 1 ? 0 : MEMORY_DISTRICT.crystalSpacing;
- // Deterministic per-crystal height falloff so the cluster reads as a faceted shard pile.
- const h = height * (0.55 + 0.45 * Math.abs(Math.cos(a * 1.7 + i)));
- out.push({ x: Math.cos(a) * r, z: Math.sin(a) * r, h, tallest: false });
- }
- if (out.length) {
- // Tag the tallest so the breathing glow lands on a stable crystal.
- let max = 0;
- out.forEach((c, i) => { if (c.h > out[max].h) max = i; });
- out[max].tallest = true;
- }
- return out;
- }, [crystals, height]);
-
- return (
- <group position={position}>
- {ring.map((c, i) => (
- <mesh
- key={i}
- ref={isGlow && c.tallest ? glowRef : undefined}
- position={[c.x, c.h / 2 + 0.3, c.z]}
- >
- {/* Octahedron reads as a crystal shard */}
- <octahedronGeometry args={[0.5 + c.h * 0.12, 0]} />
- <meshStandardMaterial
- color={color}
- emissive={color}
- emissiveIntensity={isOverflow ? 0.4 : 0.7}
- metalness={0.3}
- roughness={0.15}
- transparent
- opacity={isOverflow ? 0.55 : 0.9}
- toneMapped={false}
- />
- </mesh>
- ))}
- <OpenWorldLabel position={[0, height + 1.3, 0]} fontSize={0.6} color={color} dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={9}>
- {label}
- </OpenWorldLabel>
- <OpenWorldLabel position={[0, height + 0.7, 0]} fontSize={0.42} color="#94a3b8" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={9}>
- {count}
- </OpenWorldLabel>
- </group>
- );
-}
-
-export default function OpenWorldMemoryDistrict({ memoryGraph, inboxDepth = 0, settings }) {
- const { tintStructure } = useOpenWorldPalette();
- const district = useMemo(() => computeMemoryDistrict(memoryGraph), [memoryGraph]);
- const glowRef = useRef();
- const wellRef = useRef();
-
- const animate = (settings?.particleDensity ?? 1) >= 0.5;
- const dayMix = openWorldDayMix(settings);
-
- // The brightest (most important) cluster carries the breathing glow.
- const glowCategory = useMemo(() => {
- let best = null;
- for (const c of district.clusters) {
- if (!c.isOverflow && (!best || c.importance > best.importance)) best = c;
- }
- return best?.category ?? null;
- }, [district.clusters]);
-
- // Inbox well: glows brighter and pulses faster the deeper the unclassified backlog.
- const inboxActive = inboxDepth > 0;
- const wellColor = inboxActive ? '#06b6d4' : tintStructure('#1e3a5f');
-
- useFrame(({ clock }) => {
- const t = clock.getElapsedTime();
- if (animate && glowRef.current) {
- const pulse = (Math.sin(t * 1.4) + 1) / 2;
- glowRef.current.material.emissiveIntensity = 0.7 + pulse * 0.6;
- }
- if (wellRef.current) {
- const base = inboxActive ? 0.6 + Math.min(inboxDepth, 10) * 0.06 : 0.25;
- const speed = inboxActive ? 2.5 + Math.min(inboxDepth, 10) * 0.2 : 0.7;
- const pulse = animate ? (Math.sin(t * speed) + 1) / 2 : 0.5;
- wellRef.current.material.emissiveIntensity = base + pulse * (inboxActive ? 0.7 : 0.15);
- }
- });
-
- if (district.empty) return null;
-
- const { base, clusters, bridges, totalMemories } = district;
-
- return (
- <group>
- {clusters.map((cluster) => (
- <CrystalCluster
- key={cluster.category}
- cluster={cluster}
- glowRef={glowRef}
- isGlow={cluster.category === glowCategory}
- dayMix={dayMix}
- />
- ))}
-
- {/* Light bridges between connected categories — thicker/brighter the stronger the link */}
- {bridges.map((bridge, i) => {
- const from = [bridge.fromPos[0], MEMORY_DISTRICT.bridgeY, bridge.fromPos[2]];
- const to = [bridge.toPos[0], MEMORY_DISTRICT.bridgeY, bridge.toPos[2]];
- // Arc the midpoint up so bridges read as light arcs, not flat lines.
- const mid = [(from[0] + to[0]) / 2, MEMORY_DISTRICT.bridgeY + 2 + Math.min(bridge.weight, 6) * 0.3, (from[2] + to[2]) / 2];
- return (
- <OpenWorldTubeLine
- key={i}
- points={[from, mid, to]}
- color="#67e8f9"
- radius={Math.min(0.05 + bridge.weight * 0.03, 0.22)}
- opacity={Math.min(0.25 + bridge.weight * 0.12, 0.8)}
- />
- );
- })}
-
- {/* Brain-inbox well at the district center: a glowing ring whose intensity tracks backlog */}
- <group position={base}>
- <mesh ref={wellRef} position={[0, 0.1, 0]} rotation={[Math.PI / 2, 0, 0]}>
- <ringGeometry args={[1.4, 2.4, 32]} />
- <meshStandardMaterial color={wellColor} emissive={wellColor} emissiveIntensity={0.4} side={2} toneMapped={false} transparent opacity={0.85} />
- </mesh>
- {inboxActive && (
- <OpenWorldLabel position={[0, 1.2, 0]} fontSize={0.5} color="#06b6d4" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={9}>
- {`${inboxDepth} TO SORT`}
- </OpenWorldLabel>
- )}
- </group>
-
- {/* District title */}
- <OpenWorldLabel position={[base[0], 14, base[2] - 3]} fontSize={1.3} color="#8b5cf6" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={30}>
- MEMORY
- </OpenWorldLabel>
- <OpenWorldLabel position={[base[0], 13, base[2] - 3]} fontSize={0.75} color="#94a3b8" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={30}>
- {`${totalMemories} MEMORIES`}
- </OpenWorldLabel>
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldMiniMap.jsx b/client/src/components/openworld/OpenWorldMiniMap.jsx
deleted file mode 100644
index cefee40016..0000000000
--- a/client/src/components/openworld/OpenWorldMiniMap.jsx
+++ /dev/null
@@ -1,178 +0,0 @@
-import { useMemo } from 'react';
-import { computeOpenWorldLayout } from './openWorldLayout';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import { computeMiniMap } from '../../utils/openWorldMiniMap';
-
-// OpenWorld's compact top-down Signal Map. It shows the authored archipelago and every
-// building at its real layout position, colored by status. The layout comes
-// from `computeOpenWorldLayout(apps)` — the same function OpenWorldScene uses to place buildings — so
-// the map can't drift from the actual city. Status colors reuse `getBuildingColor`, so a dot
-// matches its building's color exactly.
-//
-// Click-to-select reuses the existing building-click plumbing: `onSelectApp(app)` is the same
-// callback OpenWorldScene fires on a building click (OpenWorld focuses the building in-world).
-// When no callback is supplied the map is purely informational.
-//
-// Hidden on very small screens (per OpenWorldHud conventions — the right-side intel pane and
-// bottom agent bar already crowd a phone viewport). It's flow-positioned (no absolute) so it
-// stacks cleanly at the top of OpenWorldHud's bottom-left rail above the status legend.
-
-// Map box size in px. Fixed so the projection has a stable target on desktop.
-const MAP_SIZE = 132;
-
-export default function OpenWorldMiniMap({
- apps,
- onSelectApp,
- selectedAppId = null,
- alwaysShow = false,
- playerPose = null,
-}) {
- const { getBuildingColor, accent } = useOpenWorldPalette();
- const positions = useMemo(() => computeOpenWorldLayout(Array.isArray(apps) ? apps : []), [apps]);
- const view = useMemo(() => {
- return computeMiniMap(apps, positions, {
- geography: true,
- landmarks: true,
- player: playerPose ? { position: playerPose, heading: playerPose.heading || 0 } : null,
- });
- }, [apps, positions, playerPose]);
-
- if (view.empty && !view.geography) return null;
-
- return (
- <div className={`${alwaysShow ? 'block' : 'hidden md:block'} mb-2 w-fit pointer-events-auto`}>
- <div className="openworld-hud-panel openworld-hud-map relative w-fit p-2">
- <div className="flex items-center justify-between mb-1.5 px-0.5">
- <span className="font-pixel text-[8px] text-cyan-500/60 tracking-wider">SIGNAL MAP</span>
- <span className="font-pixel text-[8px] text-cyan-400/80 tracking-wider">{view.count} LIVE</span>
- </div>
-
- <div
- className="relative rounded-sm border border-cyan-500/20 bg-[#061520]/90 overflow-hidden"
- style={{ width: MAP_SIZE, height: MAP_SIZE }}
- >
- {/* The same island/link graph that drives the 3D terrain. SVG keeps the shape
- legible at this compact size without creating dozens of positioned divs. */}
- {view.geography && (
- <svg className="absolute inset-0 w-full h-full pointer-events-none" viewBox="0 0 100 100" aria-hidden="true">
- <defs>
- <filter id="signal-map-glow" x="-50%" y="-50%" width="200%" height="200%">
- <feGaussianBlur stdDeviation="1.1" result="blur" />
- <feMerge><feMergeNode in="blur" /><feMergeNode in="SourceGraphic" /></feMerge>
- </filter>
- </defs>
- {view.geography.links.map((link) => (
- <polyline
- key={link.id}
- points={link.points.map((point) => `${point.nx * 100},${point.ny * 100}`).join(' ')}
- fill="none"
- stroke="rgba(103,232,249,0.78)"
- strokeWidth="1.7"
- strokeLinecap="round"
- strokeLinejoin="round"
- filter="url(#signal-map-glow)"
- />
- ))}
- {view.geography.islands.map((island) => (
- <ellipse
- key={island.id}
- cx={island.nx * 100}
- cy={island.ny * 100}
- rx={island.radiusX * 100}
- ry={island.radiusY * 100}
- fill={island.id === 'core' ? 'rgba(74,138,112,0.74)' : 'rgba(51,104,93,0.78)'}
- stroke="rgba(165,243,224,0.52)"
- strokeWidth="0.7"
- />
- ))}
- </svg>
- )}
-
- {/* Cardinal ticks replace the old city-block grid. */}
- <div className="absolute inset-0 pointer-events-none" aria-hidden="true">
- <span className="absolute top-1 left-1/2 -translate-x-1/2 font-pixel text-[6px] text-cyan-200/45">N</span>
- <span className="absolute bottom-1 left-1/2 -translate-x-1/2 font-pixel text-[6px] text-cyan-200/35">S</span>
- </div>
-
- {/* District landmark indicators */}
- {view.landmarks?.map((lm) => {
- const left = `${(lm.nx * 100).toFixed(2)}%`;
- const top = `${(lm.ny * 100).toFixed(2)}%`;
- return (
- <span
- key={lm.id}
- title={lm.label}
- className="absolute w-1 h-1 rounded-xs -translate-x-1/2 -translate-y-1/2 opacity-70"
- style={{
- left,
- top,
- backgroundColor: lm.color,
- boxShadow: `0 0 2px ${lm.color}`,
- }}
- />
- );
- })}
-
- {/* App building dots */}
- {view.dots.map((dot) => {
- const color = getBuildingColor(dot.status, dot.archived);
- const left = `${(dot.nx * 100).toFixed(2)}%`;
- const top = `${(dot.ny * 100).toFixed(2)}%`;
- const dotStyle = {
- left,
- top,
- backgroundColor: color,
- boxShadow: `0 0 4px ${color}`,
- };
- const isSelected = selectedAppId != null && dot.id === selectedAppId;
- const title = `${dot.name} — ${dot.status.replace(/_/g, ' ')}${isSelected ? ' (focused)' : ''}`;
-
- if (onSelectApp) {
- return (
- <button
- key={dot.id}
- type="button"
- onClick={() => onSelectApp({ id: dot.id })}
- title={title}
- aria-label={title}
- aria-current={isSelected ? 'true' : undefined}
- className={`absolute w-1.5 h-1.5 rounded-full -translate-x-1/2 -translate-y-1/2 hover:scale-[2] hover:z-10 transition-transform focus:outline-none focus:ring-1 focus:ring-cyan-400 ${
- isSelected ? 'ring-2 ring-cyan-200 scale-[1.8] z-10' : ''
- }`}
- style={dotStyle}
- />
- );
- }
- return (
- <span
- key={dot.id}
- title={title}
- className="absolute w-1.5 h-1.5 rounded-full -translate-x-1/2 -translate-y-1/2"
- style={dotStyle}
- />
- );
- })}
-
- {/* Live Player Pose Blip & Heading Arrow */}
- {view.player && (
- <div
- className="absolute pointer-events-none z-20 -translate-x-1/2 -translate-y-1/2"
- style={{
- left: `${(view.player.nx * 100).toFixed(2)}%`,
- top: `${(view.player.ny * 100).toFixed(2)}%`,
- }}
- >
- <div
- className="w-0 h-0 border-l-[3.5px] border-l-transparent border-r-[3.5px] border-r-transparent border-b-[8px] filter drop-shadow-[0_0_4px_rgba(6,182,212,0.9)]"
- style={{
- borderBottomColor: accent || '#06b6d4',
- transform: `rotate(${view.player.rotationDeg}deg)`,
- }}
- />
- </div>
- )}
- </div>
- </div>
- </div>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldMobileControls.jsx b/client/src/components/openworld/OpenWorldMobileControls.jsx
deleted file mode 100644
index 4584789c25..0000000000
--- a/client/src/components/openworld/OpenWorldMobileControls.jsx
+++ /dev/null
@@ -1,182 +0,0 @@
-import { useCallback, useEffect, useRef, useState } from 'react';
-import { ArrowUp, Hand, Zap } from 'lucide-react';
-
-const STICK_TRAVEL = 32;
-
-function clearMobileInput(mobileInputRef) {
- if (!mobileInputRef.current) return;
- mobileInputRef.current.moveX = 0;
- mobileInputRef.current.moveY = 0;
- mobileInputRef.current.lookDeltaX = 0;
- mobileInputRef.current.lookDeltaY = 0;
- mobileInputRef.current.boost = false;
- mobileInputRef.current.jump = false;
-}
-
-function HoldButton({ label, hint, icon: Icon, onStart, onEnd, wide = false }) {
- const finish = (event) => {
- event.preventDefault();
- onEnd?.();
- };
-
- return (
- <button
- type="button"
- aria-label={label}
- className={`openworld-mobile-action ${wide ? 'openworld-mobile-action--wide' : ''}`}
- onPointerDown={(event) => {
- event.preventDefault();
- event.currentTarget.setPointerCapture?.(event.pointerId);
- onStart?.();
- }}
- onPointerUp={finish}
- onPointerCancel={finish}
- onLostPointerCapture={finish}
- onContextMenu={(event) => event.preventDefault()}
- >
- <Icon size={18} strokeWidth={1.9} aria-hidden="true" />
- <span>{label}</span>
- {hint && <small>{hint}</small>}
- </button>
- );
-}
-
-export default function OpenWorldMobileControls({
- mobileInputRef,
- playerActionRef,
-}) {
- const joystickRef = useRef(null);
- const joystickPointerRef = useRef(null);
- const lookPointRef = useRef(null);
- const [stick, setStick] = useState({ x: 0, y: 0 });
-
- const writeMovement = useCallback((clientX, clientY) => {
- const bounds = joystickRef.current?.getBoundingClientRect();
- if (!bounds) return;
- const centerX = bounds.left + bounds.width / 2;
- const centerY = bounds.top + bounds.height / 2;
- const radius = Math.max(1, Math.min(bounds.width, bounds.height) / 2 - 24);
- const x = clientX - centerX;
- const y = clientY - centerY;
- const distance = Math.min(radius, Math.hypot(x, y));
- const angle = Math.atan2(y, x);
- const next = {
- x: Math.cos(angle) * distance / radius,
- y: Math.sin(angle) * distance / radius,
- };
- if (distance < radius * 0.12) {
- next.x = 0;
- next.y = 0;
- }
- setStick(next);
- if (mobileInputRef.current) {
- mobileInputRef.current.moveX = next.x;
- mobileInputRef.current.moveY = next.y;
- }
- }, [mobileInputRef]);
-
- const resetMovement = useCallback((event) => {
- if (event && joystickPointerRef.current !== event.pointerId) return;
- joystickPointerRef.current = null;
- setStick({ x: 0, y: 0 });
- if (mobileInputRef.current) {
- mobileInputRef.current.moveX = 0;
- mobileInputRef.current.moveY = 0;
- }
- }, [mobileInputRef]);
-
- const handleJoystickDown = (event) => {
- event.preventDefault();
- if (joystickPointerRef.current !== null) return;
- joystickPointerRef.current = event.pointerId;
- event.currentTarget.setPointerCapture?.(event.pointerId);
- writeMovement(event.clientX, event.clientY);
- };
-
- const handleJoystickMove = (event) => {
- if (joystickPointerRef.current !== event.pointerId) return;
- writeMovement(event.clientX, event.clientY);
- };
-
- const handleLookDown = (event) => {
- event.preventDefault();
- if (lookPointRef.current) return;
- event.currentTarget.setPointerCapture?.(event.pointerId);
- lookPointRef.current = { pointerId: event.pointerId, x: event.clientX, y: event.clientY };
- };
-
- const handleLookMove = (event) => {
- const previous = lookPointRef.current;
- if (!previous || previous.pointerId !== event.pointerId || !mobileInputRef.current) return;
- mobileInputRef.current.lookDeltaX += event.clientX - previous.x;
- mobileInputRef.current.lookDeltaY += event.clientY - previous.y;
- lookPointRef.current = { pointerId: event.pointerId, x: event.clientX, y: event.clientY };
- };
-
- const handleLookEnd = (event) => {
- if (event && lookPointRef.current?.pointerId !== event.pointerId) return;
- lookPointRef.current = null;
- };
-
- const setBoost = (active) => {
- if (mobileInputRef.current) mobileInputRef.current.boost = active;
- };
-
- const setJump = (active) => {
- if (mobileInputRef.current) mobileInputRef.current.jump = active;
- };
-
- useEffect(() => () => clearMobileInput(mobileInputRef), [mobileInputRef]);
-
- return (
- <div className="openworld-mobile-controls absolute inset-0 z-30 pointer-events-none" aria-label="Mobile free roam controls">
- <div
- className="openworld-mobile-look-zone"
- role="group"
- aria-label="Drag to look around"
- onPointerDown={handleLookDown}
- onPointerMove={handleLookMove}
- onPointerUp={handleLookEnd}
- onPointerCancel={handleLookEnd}
- onLostPointerCapture={handleLookEnd}
- onContextMenu={(event) => event.preventDefault()}
- >
- <span className="openworld-mobile-look-hint">DRAG TO LOOK</span>
- </div>
-
- <div
- ref={joystickRef}
- className="openworld-mobile-joystick"
- role="group"
- aria-label="Movement joystick"
- onPointerDown={handleJoystickDown}
- onPointerMove={handleJoystickMove}
- onPointerUp={resetMovement}
- onPointerCancel={resetMovement}
- onLostPointerCapture={resetMovement}
- onContextMenu={(event) => event.preventDefault()}
- >
- <span
- className="openworld-mobile-joystick-knob"
- style={{ transform: `translate(calc(-50% + ${stick.x * STICK_TRAVEL}px), calc(-50% + ${stick.y * STICK_TRAVEL}px))` }}
- aria-hidden="true"
- />
- <span className="openworld-mobile-joystick-label" aria-hidden="true">DRIVE</span>
- </div>
-
- <div className="openworld-mobile-actions pointer-events-auto" role="toolbar" aria-label="Mobile game actions">
- <HoldButton label="BOOST" hint="HOLD" icon={Zap} onStart={() => setBoost(true)} onEnd={() => setBoost(false)} />
- <HoldButton label="JUMP" icon={ArrowUp} onStart={() => setJump(true)} onEnd={() => setJump(false)} />
- <button
- type="button"
- aria-label="Interact with nearby building or warp pad"
- className="openworld-mobile-action openworld-mobile-action--wide"
- onClick={() => playerActionRef.current?.interact?.()}
- >
- <Hand size={18} strokeWidth={1.9} aria-hidden="true" />
- <span>ACTION</span>
- </button>
- </div>
- </div>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldMobileControls.test.jsx b/client/src/components/openworld/OpenWorldMobileControls.test.jsx
deleted file mode 100644
index 2daeae5ce0..0000000000
--- a/client/src/components/openworld/OpenWorldMobileControls.test.jsx
+++ /dev/null
@@ -1,178 +0,0 @@
-import { describe, expect, it, vi } from 'vitest';
-import { fireEvent, render, screen } from '@testing-library/react';
-import OpenWorldMobileControls from './OpenWorldMobileControls';
-
-function createInput() {
- return {
- current: {
- moveX: 0,
- moveY: 0,
- lookDeltaX: 0,
- lookDeltaY: 0,
- boost: false,
- jump: false,
- },
- };
-}
-
-function renderControls(overrides = {}) {
- const mobileInputRef = createInput();
- const playerActionRef = { current: { interact: vi.fn() } };
- const props = {
- mobileInputRef,
- playerActionRef,
- ...overrides,
- };
-
- return { ...render(<OpenWorldMobileControls {...props} />), ...props };
-}
-
-describe('OpenWorldMobileControls', () => {
- it('exposes a focused touch action set', () => {
- renderControls();
-
- expect(screen.getByRole('group', { name: 'Movement joystick' })).toBeInTheDocument();
- expect(screen.getByRole('group', { name: 'Drag to look around' })).toBeInTheDocument();
- expect(screen.getByRole('button', { name: 'BOOST' })).toBeInTheDocument();
- expect(screen.getByRole('button', { name: 'JUMP' })).toBeInTheDocument();
- expect(screen.getByRole('button', { name: 'Interact with nearby building or warp pad' })).toBeInTheDocument();
- expect(screen.queryByRole('button', { name: 'Switch camera view' })).not.toBeInTheDocument();
- expect(screen.queryByRole('button', { name: 'Fly out to orbital view' })).not.toBeInTheDocument();
- });
-
- it('maps hold actions to the game input refs and clears them on release', () => {
- const { mobileInputRef } = renderControls();
- const boost = screen.getByRole('button', { name: 'BOOST' });
- const jump = screen.getByRole('button', { name: 'JUMP' });
-
- fireEvent.pointerDown(boost, { pointerId: 1 });
- expect(mobileInputRef.current.boost).toBe(true);
- fireEvent.pointerUp(boost, { pointerId: 1 });
- expect(mobileInputRef.current.boost).toBe(false);
-
- fireEvent.pointerDown(jump, { pointerId: 2 });
- expect(mobileInputRef.current.jump).toBe(true);
- fireEvent.pointerUp(jump, { pointerId: 2 });
- expect(mobileInputRef.current.jump).toBe(false);
- });
-
- it('clears a held action if pointer capture is lost', () => {
- const { mobileInputRef } = renderControls();
- const boost = screen.getByRole('button', { name: 'BOOST' });
-
- fireEvent.pointerDown(boost, { pointerId: 12 });
- expect(mobileInputRef.current.boost).toBe(true);
- fireEvent.lostPointerCapture(boost, { pointerId: 12 });
- expect(mobileInputRef.current.boost).toBe(false);
- });
-
- it('maps the virtual joystick to normalized drive input', () => {
- const { mobileInputRef } = renderControls();
- const joystick = screen.getByRole('group', { name: 'Movement joystick' });
- vi.spyOn(joystick, 'getBoundingClientRect').mockReturnValue({
- left: 0,
- top: 0,
- width: 100,
- height: 100,
- right: 100,
- bottom: 100,
- x: 0,
- y: 0,
- toJSON: () => {},
- });
-
- fireEvent.pointerDown(joystick, { pointerId: 6, clientX: 75, clientY: 25 });
- expect(mobileInputRef.current.moveX).toBeCloseTo(Math.SQRT1_2);
- expect(mobileInputRef.current.moveY).toBeCloseTo(-Math.SQRT1_2);
-
- fireEvent.pointerUp(joystick, { pointerId: 6 });
- expect(mobileInputRef.current.moveX).toBe(0);
- expect(mobileInputRef.current.moveY).toBe(0);
- });
-
- it('does not steer from pointer hover without an active drag', () => {
- const { mobileInputRef } = renderControls();
- const joystick = screen.getByRole('group', { name: 'Movement joystick' });
- vi.spyOn(joystick, 'getBoundingClientRect').mockReturnValue({
- left: 0,
- top: 0,
- width: 100,
- height: 100,
- right: 100,
- bottom: 100,
- x: 0,
- y: 0,
- toJSON: () => {},
- });
-
- fireEvent.pointerMove(joystick, { pointerId: 9, clientX: 75, clientY: 25 });
-
- expect(mobileInputRef.current.moveX).toBe(0);
- expect(mobileInputRef.current.moveY).toBe(0);
- });
-
- it('ignores a second pointer and clears movement if capture is lost', () => {
- const { mobileInputRef } = renderControls();
- const joystick = screen.getByRole('group', { name: 'Movement joystick' });
- vi.spyOn(joystick, 'getBoundingClientRect').mockReturnValue({
- left: 0,
- top: 0,
- width: 100,
- height: 100,
- right: 100,
- bottom: 100,
- x: 0,
- y: 0,
- toJSON: () => {},
- });
-
- fireEvent.pointerDown(joystick, { pointerId: 10, clientX: 75, clientY: 25 });
- const firstX = mobileInputRef.current.moveX;
- fireEvent.pointerMove(joystick, { pointerId: 11, clientX: 25, clientY: 75 });
- expect(mobileInputRef.current.moveX).toBe(firstX);
-
- fireEvent.lostPointerCapture(joystick, { pointerId: 10 });
- expect(mobileInputRef.current.moveX).toBe(0);
- expect(mobileInputRef.current.moveY).toBe(0);
- });
-
- it('accumulates drag-to-look deltas for the player rig', () => {
- const { mobileInputRef } = renderControls();
- const lookZone = screen.getByRole('group', { name: 'Drag to look around' });
-
- fireEvent.pointerDown(lookZone, { pointerId: 3, clientX: 100, clientY: 120 });
- fireEvent.pointerMove(lookZone, { pointerId: 3, clientX: 128, clientY: 110 });
- fireEvent.pointerMove(lookZone, { pointerId: 3, clientX: 120, clientY: 114 });
- fireEvent.pointerUp(lookZone, { pointerId: 3 });
-
- expect(mobileInputRef.current.lookDeltaX).toBe(20);
- expect(mobileInputRef.current.lookDeltaY).toBe(-6);
- });
-
- it('routes the action button to the interaction callback', () => {
- const { playerActionRef } = renderControls();
-
- fireEvent.click(screen.getByRole('button', { name: 'Interact with nearby building or warp pad' }));
-
- expect(playerActionRef.current.interact).toHaveBeenCalledTimes(1);
- });
-
- it('clears active touch state when the controls unmount', () => {
- const { mobileInputRef, unmount } = renderControls();
- fireEvent.pointerDown(screen.getByRole('button', { name: 'BOOST' }), { pointerId: 4 });
- fireEvent.pointerDown(screen.getByRole('button', { name: 'JUMP' }), { pointerId: 5 });
- mobileInputRef.current.moveX = 0.8;
- mobileInputRef.current.lookDeltaX = 12;
-
- unmount();
-
- expect(mobileInputRef.current).toEqual({
- moveX: 0,
- moveY: 0,
- lookDeltaX: 0,
- lookDeltaY: 0,
- boost: false,
- jump: false,
- });
- });
-});
diff --git a/client/src/components/openworld/OpenWorldNature.jsx b/client/src/components/openworld/OpenWorldNature.jsx
deleted file mode 100644
index 30f3ef8fd9..0000000000
--- a/client/src/components/openworld/OpenWorldNature.jsx
+++ /dev/null
@@ -1,125 +0,0 @@
-import { mixHex, openWorldDayMix, openWorldShowDetail } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-
-// The playable city uses plants as wayfinding language: arrival gardens sit beside the
-// southern entry road, district greens soften the outer parcels, and warp-pad planters frame
-// an interaction surface. These are grounded, broad silhouettes rather than floating ornaments.
-export const NATURE_PATCHES = [
- { id: 'arrival-west', position: [-10, 0, 48], scale: 1.15, variant: 0 },
- { id: 'arrival-east', position: [10, 0, 48], scale: 1.15, variant: 1 },
- { id: 'plaza-southwest', position: [-14, 0, 18], scale: 0.9, variant: 1 },
- { id: 'plaza-southeast', position: [14, 0, 18], scale: 0.9, variant: 0 },
- { id: 'productivity-greenway', position: [-43, 0, 20], scale: 1.1, variant: 2 },
- { id: 'wellness-greenway', position: [43, 0, 20], scale: 1.1, variant: 1 },
- { id: 'memory-garden', position: [-39, 0, -19], scale: 1.05, variant: 2 },
- { id: 'goals-garden', position: [29, 0, -29], scale: 1.05, variant: 0 },
- { id: 'archive-garden', position: [-14, 0, 46], scale: 0.85, variant: 2 },
- { id: 'quiet-garden', position: [-48, 0, 38], scale: 1.15, variant: 0 },
-];
-
-const LEAF_LAYOUTS = [
- [
- { position: [0, 0.96, 0], scale: [0.54, 0.68, 0.54] },
- { position: [-0.34, 0.72, 0.14], scale: [0.38, 0.42, 0.38] },
- { position: [0.35, 0.78, -0.1], scale: [0.42, 0.5, 0.42] },
- ],
- [
- { position: [0, 1.04, 0], scale: [0.48, 0.72, 0.48] },
- { position: [-0.28, 0.74, -0.16], scale: [0.42, 0.5, 0.42] },
- { position: [0.3, 0.69, 0.16], scale: [0.36, 0.45, 0.36] },
- ],
- [
- { position: [0, 0.9, 0], scale: [0.62, 0.5, 0.62] },
- { position: [-0.42, 0.76, 0.08], scale: [0.4, 0.55, 0.4] },
- { position: [0.38, 0.8, -0.08], scale: [0.4, 0.5, 0.4] },
- ],
-];
-
-const FLOWER_LAYOUT = [
- { position: [0.22, 1.45, 0.16], scale: 1 },
- { position: [-0.3, 1.23, -0.18], scale: 0.82 },
- { position: [0.38, 1.25, -0.08], scale: 0.76 },
-];
-
-function Plant({ position, scale = 1, variant = 0, flowerColor, foliageColor, foliageDark, cyber }) {
- const leaves = LEAF_LAYOUTS[variant % LEAF_LAYOUTS.length];
- const stemColor = mixHex(foliageDark, '#b29368', cyber ? 0.08 : 0.28);
- const leafGlow = mixHex(foliageColor, '#173b25', cyber ? 0.1 : 0.56);
-
- return (
- <group position={position} scale={scale}>
- <mesh position={[0, 0.42, 0]}>
- <cylinderGeometry args={[0.045, 0.08, 0.82, 6]} />
- {cyber ? (
- <meshBasicMaterial color={foliageColor} transparent opacity={0.8} wireframe />
- ) : (
- <meshStandardMaterial color={stemColor} roughness={0.95} metalness={0} />
- )}
- </mesh>
- {leaves.map((leaf, index) => (
- <mesh key={`leaf-${index}`} position={leaf.position} scale={leaf.scale} rotation={[0, index * 0.9, index * 0.15]}>
- <icosahedronGeometry args={[1, 1]} />
- {cyber ? (
- <meshBasicMaterial color={foliageColor} transparent opacity={0.34} wireframe toneMapped={false} />
- ) : (
- <meshStandardMaterial
- color={index === 0 ? foliageColor : foliageDark}
- emissive={leafGlow}
- emissiveIntensity={0.18}
- roughness={0.98}
- metalness={0}
- />
- )}
- </mesh>
- ))}
- {FLOWER_LAYOUT.map((flower, index) => (
- <mesh key={`flower-${index}`} position={flower.position} scale={flower.scale}>
- <sphereGeometry args={[0.16, 8, 6]} />
- <meshBasicMaterial color={flowerColor} transparent opacity={cyber ? 0.9 : 0.88} toneMapped={false} />
- </mesh>
- ))}
- </group>
- );
-}
-
-export function PlantCluster({ position = [0, 0, 0], scale = 1, variant = 0, container = false, dayMix = 0 }) {
- const { accent, lowPoly, tintStructure } = useOpenWorldPalette();
- const cyber = !lowPoly;
- const foliageColor = mixHex(lowPoly ? '#5f9b6d' : '#20b7a5', accent, lowPoly ? 0.14 : 0.56);
- const foliageDark = mixHex(foliageColor, lowPoly ? '#214934' : '#071c25', lowPoly ? 0.42 : 0.7);
- const flowerColor = mixHex(mixHex(accent, '#ffd166', lowPoly ? 0.45 : 0.18), '#fff3c4', dayMix * 0.2);
-
- return (
- <group position={position} scale={scale}>
- {container && (
- <>
- <mesh position={[0, 0.15, 0]}>
- <cylinderGeometry args={[0.78, 0.88, 0.3, 8]} />
- <meshStandardMaterial color={tintStructure('#263938')} roughness={0.9} metalness={cyber ? 0.35 : 0} />
- </mesh>
- <mesh position={[0, 0.31, 0]}>
- <cylinderGeometry args={[0.64, 0.68, 0.05, 8]} />
- <meshStandardMaterial color={mixHex(foliageDark, '#111c1b', 0.35)} roughness={1} metalness={0} />
- </mesh>
- </>
- )}
- <Plant position={[-0.36, container ? 0.28 : 0, 0]} scale={0.82} variant={variant} flowerColor={flowerColor} foliageColor={foliageColor} foliageDark={foliageDark} cyber={cyber} />
- <Plant position={[0.34, container ? 0.28 : 0, 0.08]} scale={0.68} variant={variant + 1} flowerColor={flowerColor} foliageColor={foliageColor} foliageDark={foliageDark} cyber={cyber} />
- <Plant position={[0, container ? 0.28 : 0, -0.28]} scale={0.72} variant={variant + 2} flowerColor={flowerColor} foliageColor={foliageColor} foliageDark={foliageDark} cyber={cyber} />
- </group>
- );
-}
-
-export default function OpenWorldNature({ settings }) {
- const dayMix = openWorldDayMix(settings);
- const detailed = openWorldShowDetail(settings);
- const patches = detailed ? NATURE_PATCHES : NATURE_PATCHES.slice(0, 4);
-
- return (
- <group>
- {patches.map((patch) => (
- <PlantCluster key={patch.id} position={patch.position} scale={patch.scale * (detailed ? 1 : 0.86)} variant={patch.variant} dayMix={dayMix} />
- ))}
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldNeonSigns.jsx b/client/src/components/openworld/OpenWorldNeonSigns.jsx
deleted file mode 100644
index 2bca18d57d..0000000000
--- a/client/src/components/openworld/OpenWorldNeonSigns.jsx
+++ /dev/null
@@ -1,259 +0,0 @@
-import { useRef, useMemo } from 'react';
-import { useFrame } from '@react-three/fiber';
-import { Text } from '@react-three/drei';
-import * as THREE from 'three';
-import { computeDistrictBounds } from '../../utils/openWorldMiniMap';
-import { PIXEL_FONT_URL } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-
-// Floating neon street-level signs with animated glow
-
-function NeonSign({ position, rotation, text, color, fontSize = 0.4, flickerRate = 0, phase = 0 }) {
- const textRef = useRef();
- const backRef = useRef();
- const glowRef = useRef();
-
- useFrame(({ clock }) => {
- const t = clock.getElapsedTime();
-
- // Flicker effect for some signs
- let opacity = 0.9;
- if (flickerRate > 0) {
- const flicker = Math.sin(t * flickerRate + phase);
- // Occasional rapid flicker
- if (flicker > 0.85) opacity = 0.3 + Math.random() * 0.5;
- else if (flicker > 0.7) opacity = 0.1;
- }
-
- if (textRef.current) {
- textRef.current.fillOpacity = opacity;
- }
- if (backRef.current) {
- backRef.current.material.opacity = 0.5 * opacity;
- }
- if (glowRef.current) {
- glowRef.current.material.opacity = 0.15 * opacity;
- }
- });
-
- const textWidth = text.length * fontSize * 0.55;
- const textHeight = fontSize * 1.4;
-
- return (
- <group position={position} rotation={rotation}>
- {/* Dark backing panel (front face only) */}
- <mesh ref={backRef} position={[0, 0, -0.02]}>
- <planeGeometry args={[textWidth + 0.3, textHeight + 0.15]} />
- <meshBasicMaterial color="#020208" transparent opacity={0.5} />
- </mesh>
-
- {/* Styled back blocker to prevent mirrored text — a tinted panel plus a thin
- accent strip so the sign reads as a finished object from behind, not a
- flat black cutout. */}
- <mesh position={[0, 0, -0.03]}>
- <planeGeometry args={[textWidth + 0.3, textHeight + 0.15]} />
- <meshBasicMaterial color="#07111f" transparent opacity={0.78} side={THREE.BackSide} />
- </mesh>
- <mesh position={[0, 0, -0.032]}>
- <planeGeometry args={[textWidth + 0.42, 0.04]} />
- <meshBasicMaterial color={color} transparent opacity={0.24} side={THREE.BackSide} />
- </mesh>
-
- {/* Neon text */}
- <Text
- ref={textRef}
- fontSize={fontSize}
- color={color}
- anchorX="center"
- anchorY="middle"
- font={PIXEL_FONT_URL}
- >
- {text}
- </Text>
-
- {/* Glow halo behind text */}
- <mesh ref={glowRef} position={[0, 0, -0.04]}>
- <planeGeometry args={[textWidth + 0.8, textHeight + 0.6]} />
- <meshBasicMaterial
- color={color}
- transparent
- opacity={0.15}
- blending={THREE.AdditiveBlending}
- />
- </mesh>
-
- {/* Point light for neon glow effect on surroundings */}
- <pointLight color={color} intensity={0.3} distance={4} decay={2} />
- </group>
- );
-}
-
-// Vertical neon bar decoration
-function NeonBar({ position, rotation, color, height = 2 }) {
- const ref = useRef();
-
- useFrame(({ clock }) => {
- if (!ref.current) return;
- const t = clock.getElapsedTime();
- ref.current.material.opacity = 0.4 + Math.sin(t * 2 + position[0]) * 0.15;
- });
-
- return (
- <mesh ref={ref} position={position} rotation={rotation}>
- <boxGeometry args={[0.04, height, 0.04]} />
- <meshBasicMaterial color={color} transparent opacity={0.4} />
- </mesh>
- );
-}
-
-export default function OpenWorldNeonSigns({ positions }) {
- const { neonAccents } = useOpenWorldPalette();
- const signs = useMemo(() => {
- if (!positions || positions.size < 2) return [];
-
- const bounds = computeDistrictBounds(positions, 'downtown', { minCount: 2 });
- if (!bounds) return [];
- const { minX, maxX, minZ, maxZ } = bounds;
-
- const colors = neonAccents;
- const pad = 3;
- const result = [];
-
- // Signs along the perimeter of downtown
- const signTexts = [
- 'PORTOS', 'SYSTEM ONLINE', 'CYBER', 'DIGITAL',
- 'NEURAL NET', 'DATA CORE', 'QUANTUM', 'UPLINK',
- 'OVERRIDE', 'SYNC', 'MATRIX', 'NEON',
- ];
-
- // Front signs
- result.push({
- id: 'sign-front-1',
- position: [minX - pad + 2, 2.5, minZ - pad + 1],
- rotation: [0, 0, 0],
- text: signTexts[0],
- color: colors[0],
- fontSize: 0.5,
- flickerRate: 0,
- phase: 0,
- });
- result.push({
- id: 'sign-front-2',
- position: [maxX + pad - 2, 1.8, minZ - pad + 1],
- rotation: [0, 0, 0],
- text: signTexts[1],
- color: colors[1],
- fontSize: 0.35,
- flickerRate: 8,
- phase: 1,
- });
-
- // Right side signs (facing outward)
- result.push({
- id: 'sign-right-1',
- position: [maxX + pad, 3.2, (minZ + maxZ) / 2 - 3],
- rotation: [0, Math.PI / 2, 0],
- text: signTexts[2],
- color: colors[4],
- fontSize: 0.6,
- flickerRate: 0,
- phase: 2,
- });
- result.push({
- id: 'sign-right-2',
- position: [maxX + pad, 1.5, (minZ + maxZ) / 2 + 2],
- rotation: [0, Math.PI / 2, 0],
- text: signTexts[3],
- color: colors[5],
- fontSize: 0.3,
- flickerRate: 12,
- phase: 3,
- });
-
- // Left side signs (facing outward)
- result.push({
- id: 'sign-left-1',
- position: [minX - pad, 2.8, (minZ + maxZ) / 2],
- rotation: [0, -Math.PI / 2, 0],
- text: signTexts[4],
- color: colors[2],
- fontSize: 0.35,
- flickerRate: 0,
- phase: 4,
- });
-
- // Back signs
- result.push({
- id: 'sign-back-1',
- position: [(minX + maxX) / 2, 2, maxZ + pad - 1],
- rotation: [0, Math.PI, 0],
- text: signTexts[5],
- color: colors[3],
- fontSize: 0.4,
- flickerRate: 6,
- phase: 5,
- });
-
- return result;
- }, [positions, neonAccents]);
-
- const bars = useMemo(() => {
- if (!positions || positions.size < 2) return [];
-
- const bounds = computeDistrictBounds(positions, 'downtown', { minCount: 2 });
- if (!bounds) return [];
- const { minX, maxX, minZ, maxZ } = bounds;
-
- const colors = neonAccents;
- const pad = 3;
- const result = [];
-
- // Vertical neon bars at corners
- const corners = [
- [minX - pad, minZ - pad],
- [maxX + pad, minZ - pad],
- [minX - pad, maxZ + pad],
- [maxX + pad, maxZ + pad],
- ];
-
- corners.forEach(([x, z], i) => {
- result.push({
- id: `bar-${i}`,
- position: [x, 1.5, z],
- rotation: [0, 0, 0],
- color: colors[i % colors.length],
- height: 3,
- });
- });
-
- return result;
- }, [positions, neonAccents]);
-
- if (signs.length === 0) return null;
-
- return (
- <group>
- {signs.map(sign => (
- <NeonSign
- key={sign.id}
- position={sign.position}
- rotation={sign.rotation}
- text={sign.text}
- color={sign.color}
- fontSize={sign.fontSize}
- flickerRate={sign.flickerRate}
- phase={sign.phase}
- />
- ))}
- {bars.map(bar => (
- <NeonBar
- key={bar.id}
- position={bar.position}
- rotation={bar.rotation}
- color={bar.color}
- height={bar.height}
- />
- ))}
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldPaletteContext.jsx b/client/src/components/openworld/OpenWorldPaletteContext.jsx
deleted file mode 100644
index 0946f650fb..0000000000
--- a/client/src/components/openworld/OpenWorldPaletteContext.jsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import { createContext, useContext } from 'react';
-import { deriveOpenWorldPalette } from './openWorldConstants';
-
-// OpenWorld's "brand" surfaces (ground grid, particles, online buildings, the lead
-// neon accent, the dark structural bases) track the active PortOS theme accent. The
-// palette is derived once per theme (see deriveOpenWorldPalette) and handed down through
-// this context instead of mutating a shared module-level singleton during render —
-// the old approach fired a side-effect mid-render that was fragile under React
-// StrictMode's double-invoke and concurrent rendering.
-//
-// IMPORTANT: react-three-fiber's <Canvas> runs its own reconciler, so React context
-// does NOT cross that boundary automatically (the same reason `settings` is prop-
-// threaded into every scene component). The palette is therefore provided TWICE: once
-// by OpenWorldInner for the DOM-side HUD/minimap, and again inside <Canvas> by
-// OpenWorldScene for the 3D scene. Both providers share the same derived palette object.
-
-// Default to the cyan-era baseline so a consumer rendered outside a provider (or in a
-// test) still gets a valid, fully-formed palette rather than crashing on undefined.
-const DEFAULT_OPEN_WORLD_PALETTE = deriveOpenWorldPalette(undefined);
-
-const OpenWorldPaletteContext = createContext(DEFAULT_OPEN_WORLD_PALETTE);
-
-export function OpenWorldPaletteProvider({ palette, children }) {
- return (
- <OpenWorldPaletteContext.Provider value={palette || DEFAULT_OPEN_WORLD_PALETTE}>
- {children}
- </OpenWorldPaletteContext.Provider>
- );
-}
-
-export function useOpenWorldPalette() {
- return useContext(OpenWorldPaletteContext);
-}
diff --git a/client/src/components/openworld/OpenWorldParticles.jsx b/client/src/components/openworld/OpenWorldParticles.jsx
deleted file mode 100644
index 0a761cd4e6..0000000000
--- a/client/src/components/openworld/OpenWorldParticles.jsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import { Sparkles } from '@react-three/drei';
-import { openWorldDayMix } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-
-const NIGHT_LAYERS = [
- { count: 120, scale: [50, 20, 50], size: 1.8, speed: 0.3, opacity: 0.3 },
- { count: 50, scale: [40, 15, 40], size: 1.2, speed: 0.25, opacity: 0.2, color: '#ec4899' },
- { count: 35, scale: [45, 15, 45], size: 1, speed: 0.2, opacity: 0.15, color: '#8b5cf6' },
- { count: 25, scale: [35, 5, 35], size: 0.8, speed: 0.15, opacity: 0.12, color: '#f97316', position: [0, 2, 0] },
- { count: 30, scale: [50, 8, 50], size: 0.6, speed: 0.1, opacity: 0.1, color: '#3b82f6', position: [0, 15, 0] },
-];
-
-function nightLayerCount(tier) {
- if (tier === 'low') return 1;
- if (tier === 'medium') return 2;
- if (tier === 'ultra') return 5;
- return 3;
-}
-
-export default function OpenWorldParticles({ settings }) {
- const { particles, lowPoly } = useOpenWorldPalette();
- const density = settings?.particleDensity ?? 1.0;
- const scale = (base) => Math.max(1, Math.round(base * density));
- const dayMix = openWorldDayMix(settings);
- const dayFade = 1 - dayMix;
-
- if (density <= 0) return null;
-
- const layers = NIGHT_LAYERS.slice(0, nightLayerCount(settings?.effectiveTier));
- const pollenCount = settings?.effectiveTier === 'low' ? 28 : (lowPoly ? 70 : 40);
-
- return (
- <>
- {/* Daylight meadow motes: soft golden pollen drifting in the sunlit breeze */}
- {dayMix > 0.1 && (
- <Sparkles
- count={scale(pollenCount)}
- scale={[60, 16, 60]}
- size={1.4}
- speed={0.2}
- opacity={0.35 * dayMix}
- color="#fde047"
- position={[0, 4, 0]}
- />
- )}
-
- {/* Night-time neon atmospheric dust — layer count follows the render tier so
- a struggling GPU sheds sparkle systems before it sheds buildings. */}
- {dayFade > 0.05 && layers.map((layer, i) => (
- <Sparkles
- key={i}
- count={scale(layer.count)}
- scale={layer.scale}
- size={layer.size}
- speed={layer.speed}
- opacity={layer.opacity * dayFade}
- color={layer.color ?? particles}
- position={layer.position}
- />
- ))}
- </>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldParticles.test.jsx b/client/src/components/openworld/OpenWorldParticles.test.jsx
deleted file mode 100644
index 3ceca55d23..0000000000
--- a/client/src/components/openworld/OpenWorldParticles.test.jsx
+++ /dev/null
@@ -1,37 +0,0 @@
-import { describe, it, expect, vi } from 'vitest';
-import { render } from '@testing-library/react';
-
-vi.mock('@react-three/drei', () => ({
- Sparkles: ({ color, count }) => <div data-testid="sparkles" data-color={color} data-count={count} />,
-}));
-vi.mock('./OpenWorldPaletteContext', () => ({
- useOpenWorldPalette: () => ({
- particles: '#22d3ee',
- lowPoly: true,
- }),
-}));
-
-import OpenWorldParticles from './OpenWorldParticles';
-
-describe('OpenWorldParticles', () => {
- it('renders daylight pollen sparkles when dayMix is high', () => {
- const { container } = render(<OpenWorldParticles settings={{ timeOfDay: 'vibesDay' }} />);
- const sparkles = container.querySelectorAll('[data-testid="sparkles"]');
- expect(sparkles.length).toBeGreaterThan(0);
- expect(sparkles[0].getAttribute('data-color')).toBe('#fde047');
- });
-
- it('renders neon night sparkles when at sunset/night', () => {
- const { container } = render(<OpenWorldParticles settings={{ timeOfDay: 'sunset' }} />);
- const sparkles = container.querySelectorAll('[data-testid="sparkles"]');
- expect(sparkles.length).toBeGreaterThan(1);
- });
-
- it('keeps a single night sparkle system on the low render tier', () => {
- const { container } = render(
- <OpenWorldParticles settings={{ timeOfDay: 'sunset', effectiveTier: 'low' }} />
- );
- const sparkles = container.querySelectorAll('[data-testid="sparkles"]');
- expect(sparkles.length).toBe(1);
- });
-});
diff --git a/client/src/components/openworld/OpenWorldPhotoCamera.jsx b/client/src/components/openworld/OpenWorldPhotoCamera.jsx
deleted file mode 100644
index 4e450ea8c5..0000000000
--- a/client/src/components/openworld/OpenWorldPhotoCamera.jsx
+++ /dev/null
@@ -1,75 +0,0 @@
-import { useRef, useEffect } from 'react';
-import { useThree, useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { getPreset, stepFly } from '../../utils/openWorldPhotoMode';
-
-// Photo-mode camera driver (roadmap 3.3 / 3.6). When photo mode is active this flies the camera
-// to the selected cinematic preset with a smooth ease, and registers a capture function with the
-// page (via `onReady`) that grabs the current WebGL frame as a PNG data URL. It renders nothing
-// itself — it only mutates the shared camera and forces an on-demand render before each capture
-// so `preserveDrawingBuffer` has a fresh frame to read. Mirrors CameraTransition's ease/lerp.
-//
-// In photo mode the Canvas runs frameloop="demand" (roadmap 3.6 animation-pause): the scene
-// animates only while the camera is flying, then freezes for a clean, deliberate still. Because
-// "demand" stops ticking useFrame on its own, this component pumps the loop via `invalidate()` —
-// once when a fly begins (activation / preset change) and again every frame until the fly
-// settles. After that nothing invalidates, so the scene holds frozen until the next fly.
-
-export default function OpenWorldPhotoCamera({ active, presetId, onReady, composerRef }) {
- const { camera, gl, scene, invalidate } = useThree();
- const progressRef = useRef(1);
- const startPosRef = useRef(new THREE.Vector3());
- const startTargetRef = useRef(new THREE.Vector3());
-
- // Register the capture function with the page. Reading the canvas requires the renderer to
- // have been created with preserveDrawingBuffer:true (set on the Canvas gl prop). We force one
- // synchronous render first so the buffer matches what's on screen even when the frameloop is
- // paused ("demand") in photo mode. When the depth-of-field composer is mounted (DoF on), render
- // THROUGH it so the captured postcard carries the same bokeh as the live preview; otherwise fall
- // back to a plain renderer pass.
- useEffect(() => {
- if (!onReady) return;
- const capture = () => {
- const composer = composerRef?.current;
- if (composer) composer.render();
- else gl.render(scene, camera);
- return gl.domElement.toDataURL('image/png');
- };
- onReady(capture);
- return () => onReady(null);
- }, [onReady, gl, scene, camera, composerRef]);
-
- // Start a new fly whenever photo mode turns on or the preset changes. This MUST live in an
- // effect (fired on the React commit), not inside useFrame: in frameloop="demand" the loop is
- // asleep once a fly settles, so a useFrame-gated start would never run when the user cycles
- // presets on a frozen scene — the camera would stay parked on the old preset. The effect kicks
- // the demand loop via invalidate() so useFrame resumes and steps the fly to completion.
- useEffect(() => {
- if (!active) return;
- progressRef.current = 0;
- startPosRef.current.copy(camera.position);
- const dir = new THREE.Vector3(0, 0, -1).applyQuaternion(camera.quaternion);
- startTargetRef.current.copy(camera.position).add(dir.multiplyScalar(10));
- invalidate();
- }, [active, presetId, camera, invalidate]);
-
- useFrame((_, delta) => {
- if (!active || progressRef.current >= 1) return; // inactive, or settled — scene stays frozen
-
- const { progress, t, done } = stepFly(progressRef.current, delta);
- progressRef.current = progress;
-
- const preset = getPreset(presetId);
- const endPos = new THREE.Vector3(...preset.position);
- const endTarget = new THREE.Vector3(...preset.target);
-
- camera.position.lerpVectors(startPosRef.current, endPos, t);
- camera.lookAt(new THREE.Vector3().lerpVectors(startTargetRef.current, endTarget, t));
-
- // In frameloop="demand" the loop sleeps after this frame unless something requests another.
- // Keep pumping until the fly settles; once done, stop so the scene freezes for the shot.
- if (!done) invalidate();
- });
-
- return null;
-}
diff --git a/client/src/components/openworld/OpenWorldPhotoOverlay.jsx b/client/src/components/openworld/OpenWorldPhotoOverlay.jsx
deleted file mode 100644
index 7215575ac8..0000000000
--- a/client/src/components/openworld/OpenWorldPhotoOverlay.jsx
+++ /dev/null
@@ -1,194 +0,0 @@
-import { useState, useCallback } from 'react';
-import Modal from '../ui/Modal.jsx';
-import { PHOTO_PRESETS, getPreset, cyclePreset, buildPostcardStats, screenshotFilename } from '../../utils/openWorldPhotoMode';
-
-// Photo-mode HUD overlay (roadmap 3.3). When photo mode is active it dims the rest of the HUD,
-// draws cinematic letterbox bars, and offers preset framing controls + a capture button. Capture
-// composites the live WebGL frame (grabbed via the page's `captureFn`) onto a postcard with a
-// stats caption baked in, then offers it as a PNG download and an in-overlay preview. All the
-// non-visual logic (presets, caption lines, filename) lives in the pure openWorldPhotoMode helper.
-
-// Composite the raw screenshot data URL onto a postcard: the city image with a subtle vignette,
-// an OPENWORLD title, and the stats caption along the bottom. Returns a PNG data URL. Runs on a
-// 2D canvas so it's independent of the WebGL renderer. Resolves null if the image fails to load.
-function composePostcard(dataUrl, statLines) {
- return new Promise((resolve) => {
- const img = new Image();
- img.onload = () => {
- const canvas = document.createElement('canvas');
- canvas.width = img.width;
- canvas.height = img.height;
- const ctx = canvas.getContext('2d');
- if (!ctx) { resolve(null); return; }
- ctx.drawImage(img, 0, 0);
-
- // Bottom gradient scrim so the caption stays readable over a bright skyline.
- const scrimH = Math.max(110, img.height * 0.18);
- const grad = ctx.createLinearGradient(0, img.height - scrimH, 0, img.height);
- grad.addColorStop(0, 'rgba(0,0,0,0)');
- grad.addColorStop(1, 'rgba(0,0,0,0.82)');
- ctx.fillStyle = grad;
- ctx.fillRect(0, img.height - scrimH, img.width, scrimH);
-
- const pad = Math.round(img.width * 0.03);
- ctx.textBaseline = 'alphabetic';
-
- // Title
- ctx.fillStyle = '#06b6d4';
- ctx.font = `bold ${Math.round(img.height * 0.045)}px monospace`;
- ctx.fillText('OPENWORLD', pad, img.height - pad - Math.round(img.height * 0.04));
-
- // Stats caption — one line, separated by middots, right under the title.
- ctx.fillStyle = '#cbd5e1';
- ctx.font = `${Math.round(img.height * 0.026)}px monospace`;
- ctx.fillText(statLines.join(' · '), pad, img.height - pad);
-
- resolve(canvas.toDataURL('image/png'));
- };
- img.onerror = () => resolve(null);
- img.src = dataUrl;
- });
-}
-
-function PresetControls({ presetId, onCycle }) {
- const preset = getPreset(presetId);
- return (
- <div className="flex items-center gap-3 pointer-events-auto">
- <button
- type="button"
- onClick={() => onCycle(-1)}
- className="font-pixel text-cyan-400 text-lg px-2 hover:text-cyan-300 transition-colors"
- title="Previous shot (←)"
- >‹</button>
- <div className="font-pixel text-[11px] text-cyan-300 tracking-widest w-32 text-center" style={{ textShadow: '0 0 8px rgba(6,182,212,0.5)' }}>
- {preset.label}
- </div>
- <button
- type="button"
- onClick={() => onCycle(1)}
- className="font-pixel text-cyan-400 text-lg px-2 hover:text-cyan-300 transition-colors"
- title="Next shot (→)"
- >›</button>
- </div>
- );
-}
-
-export default function OpenWorldPhotoOverlay({ active, presetId, onPresetChange, onExit, captureFnRef, statsSnapshot, dofEnabled = true, onToggleDof }) {
- const [postcard, setPostcard] = useState(null);
- const [busy, setBusy] = useState(false);
-
- const handleCycle = useCallback((dir) => {
- onPresetChange(cyclePreset(presetId, dir));
- }, [presetId, onPresetChange]);
-
- const handleCapture = useCallback(async () => {
- // Read the capture fn from the ref at click time — the in-canvas camera populates it after
- // mount, so reading it now (not at render) guarantees the latest registered grabber.
- const captureFn = captureFnRef?.current;
- if (!captureFn || busy) return;
- setBusy(true);
- // Grab the raw frame, then composite the postcard off the WebGL thread.
- const raw = captureFn();
- const lines = buildPostcardStats(statsSnapshot);
- const card = raw ? await composePostcard(raw, lines) : null;
- setPostcard(card || raw);
- setBusy(false);
- }, [captureFnRef, busy, statsSnapshot]);
-
- const handleDownload = useCallback(() => {
- if (!postcard) return;
- // A detached anchor click is enough to trigger a data-URL download — no need to mount it.
- const a = document.createElement('a');
- a.href = postcard;
- a.download = screenshotFilename(new Date());
- a.click();
- }, [postcard]);
-
- if (!active) return null;
-
- return (
- <>
- {/* Cinematic letterbox bars */}
- <div className="absolute top-0 left-0 right-0 h-[10vh] bg-black pointer-events-none z-20 transition-all" />
- <div className="absolute bottom-0 left-0 right-0 h-[10vh] bg-black pointer-events-none z-20 transition-all" />
-
- {/* Top bar: title + exit */}
- <div className="absolute top-0 left-0 right-0 h-[10vh] flex items-center justify-between px-6 z-30">
- <div className="font-pixel text-[11px] text-cyan-500/70 tracking-widest pointer-events-none">
- PHOTO MODE
- </div>
- <button
- type="button"
- onClick={onExit}
- className="font-pixel text-[10px] text-cyan-400 tracking-wider border border-cyan-500/40 rounded px-3 py-1.5 hover:bg-cyan-500/10 transition-all pointer-events-auto"
- title="Exit photo mode (Esc)"
- >
- [ EXIT ]
- </button>
- </div>
-
- {/* Bottom bar: preset cycle + DoF toggle + capture */}
- <div className="absolute bottom-0 left-0 right-0 h-[10vh] flex items-center justify-between px-6 z-30">
- <div className="flex items-center gap-4">
- <PresetControls presetId={presetId} onCycle={handleCycle} />
- {onToggleDof && (
- <button
- type="button"
- onClick={onToggleDof}
- aria-pressed={dofEnabled}
- className={`font-pixel text-[10px] tracking-wider rounded px-3 py-1.5 border transition-all pointer-events-auto ${
- dofEnabled
- ? 'text-black bg-cyan-400 border-cyan-400 hover:bg-cyan-300'
- : 'text-cyan-400 border-cyan-500/40 hover:bg-cyan-500/10'
- }`}
- title="Toggle depth of field (D)"
- >
- ◐ DEPTH {dofEnabled ? 'ON' : 'OFF'}
- </button>
- )}
- </div>
- <button
- type="button"
- onClick={handleCapture}
- disabled={busy}
- className="font-pixel text-[11px] text-black bg-cyan-400 tracking-wider rounded px-4 py-2 hover:bg-cyan-300 transition-all pointer-events-auto disabled:opacity-50"
- title="Capture a city postcard"
- >
- {busy ? 'CAPTURING…' : '◉ CAPTURE'}
- </button>
- </div>
-
- {/* Postcard preview modal — portaled so it escapes the pointer-events-none
- / z-indexed WebGL HUD stacking context and gets focus-trap + Esc from
- the shared Modal. */}
- <Modal
- open={!!postcard}
- onClose={() => setPostcard(null)}
- size="none"
- usePortal
- ariaLabel="OpenWorld postcard preview"
- panelClassName="max-w-[80vw] flex flex-col items-center gap-3"
- >
- <img src={postcard} alt="OpenWorld postcard" className="max-w-full max-h-[68vh] rounded-lg border border-cyan-500/40 shadow-[0_0_30px_rgba(6,182,212,0.3)]" />
- <div className="flex gap-3">
- <button
- type="button"
- onClick={handleDownload}
- className="font-pixel text-[11px] text-black bg-cyan-400 tracking-wider rounded px-4 py-2 hover:bg-cyan-300 transition-all"
- >
- ↓ SAVE POSTCARD
- </button>
- <button
- type="button"
- onClick={() => setPostcard(null)}
- className="font-pixel text-[11px] text-cyan-400 tracking-wider border border-cyan-500/40 rounded px-4 py-2 hover:bg-cyan-500/10 transition-all"
- >
- CLOSE
- </button>
- </div>
- </Modal>
- </>
- );
-}
-
-export { PHOTO_PRESETS };
diff --git a/client/src/components/openworld/OpenWorldPlaybackOverlay.jsx b/client/src/components/openworld/OpenWorldPlaybackOverlay.jsx
deleted file mode 100644
index 0d3d69e82a..0000000000
--- a/client/src/components/openworld/OpenWorldPlaybackOverlay.jsx
+++ /dev/null
@@ -1,157 +0,0 @@
-import { formatDateTime, timeAgo } from '../../utils/formatters';
-
-// Timeline-scrubber HUD overlay (roadmap 3.6, issue #967). When playback mode is
-// active it draws a bottom transport bar: play/pause, speed, a draggable timeline
-// slider, frame-step buttons, the current frame's timestamp, and a note that the
-// landmarks the snapshot can't replay are showing LIVE data (frozen during scrub).
-// Mirrors OpenWorldPhotoOverlay's bottom-bar styling. All transport logic lives in the
-// useOpenWorldPlayback hook; this is presentation only.
-
-// One historical stat chip; renders a null value as "—" so an unavailable
-// capture reads distinctly from a real zero.
-function Stat({ label, value, suffix = '' }) {
- return (
- <span className="text-cyan-300/80">
- <span className="text-cyan-500/60">{label}</span>{' '}
- {value == null ? '—' : `${value}${suffix}`}
- </span>
- );
-}
-
-export default function OpenWorldPlaybackOverlay({
- active,
- loading,
- error,
- snapshots = [],
- frameIndex,
- currentFrame,
- stats,
- playing,
- speed,
- onSeek,
- onStep,
- onTogglePlay,
- onCycleSpeed,
- onExit,
-}) {
- if (!active) return null;
-
- const frameCount = snapshots.length;
- const hasFrames = frameCount > 0;
- const ts = currentFrame?.ts;
-
- return (
- <div className="absolute inset-0 z-30 pointer-events-none openworld-themed">
- {/* Top-right: title + exit */}
- <div className="absolute top-0 left-0 right-0 flex items-center justify-between px-6 py-4">
- <div className="font-pixel text-[11px] text-cyan-400 tracking-widest" style={{ textShadow: '0 0 10px rgba(6,182,212,0.5)' }}>
- ⟲ CITY HISTORY {hasFrames ? `— ${frameIndex + 1}/${frameCount}` : ''}
- </div>
- <button
- type="button"
- onClick={onExit}
- className="font-pixel text-[10px] text-cyan-400 tracking-wider border border-cyan-500/40 rounded px-3 py-1.5 hover:bg-cyan-500/10 transition-all pointer-events-auto"
- title="Exit playback (Esc)"
- >
- [ EXIT ]
- </button>
- </div>
-
- {/* Bottom transport bar */}
- <div className="absolute bottom-0 left-0 right-0 px-6 pb-5 pt-3 bg-gradient-to-t from-black/70 to-transparent">
- {loading && (
- <div className="font-pixel text-[10px] text-cyan-500/70 tracking-wider text-center pb-2">LOADING HISTORY…</div>
- )}
-
- {!loading && error && (
- <div className="font-pixel text-[10px] text-port-warning/80 tracking-wider text-center pb-2">
- COULDN'T LOAD HISTORY — the snapshot service didn't respond. Try again later.
- </div>
- )}
-
- {!loading && !error && !hasFrames && (
- <div className="font-pixel text-[10px] text-cyan-500/70 tracking-wider text-center pb-2">
- NO SNAPSHOTS YET — the city records its state every few minutes. Check back later.
- </div>
- )}
-
- {!loading && !error && hasFrames && (
- <div className="flex flex-col gap-2">
- {/* Timestamp + live-data note */}
- <div className="flex items-center justify-between font-pixel text-[10px] text-cyan-300/90 tracking-wider">
- <span title={ts ? formatDateTime(ts) : ''}>{ts ? formatDateTime(ts) : '—'}</span>
- <span className="text-port-warning/80" title="Buildings, agents, health, backup, tasks & counts are historical. Memory, goals, Jira & activity show current live data.">
- ⚠ some districts show LIVE data
- </span>
- <span className="text-cyan-500/60">{ts ? timeAgo(ts) : ''}</span>
- </div>
-
- {/* Captured-at-this-moment stats whose 3D landmarks stay live (so the
- historical numbers are still visible while scrubbing). */}
- {stats && (
- <div className="flex items-center justify-center flex-wrap gap-x-4 gap-y-1 font-pixel text-[9px] tracking-wider">
- <Stat label="CPU" value={stats.cpuPercent} suffix="%" />
- <Stat label="MEM" value={stats.memPercent} suffix="%" />
- <Stat label="DISK" value={stats.diskPercent} suffix="%" />
- <Stat label="AGENTS" value={stats.agentsActive} />
- <Stat label="TASKS" value={stats.tasksPending == null && stats.tasksInProgress == null ? null : (stats.tasksPending ?? 0) + (stats.tasksInProgress ?? 0)} />
- <Stat label="PEERS" value={stats.peersOnline == null ? null : `${stats.peersOnline}/${stats.peersTotal ?? '?'}`} />
- <Stat label="REVIEW" value={stats.reviewTotal} />
- </div>
- )}
-
- {/* Timeline slider */}
- <input
- type="range"
- min={0}
- max={frameCount - 1}
- step={1}
- value={frameIndex}
- onChange={(e) => onSeek?.(Number(e.target.value))}
- aria-label="Timeline position"
- className="w-full accent-cyan-400 pointer-events-auto cursor-pointer"
- />
-
- {/* Transport controls */}
- <div className="flex items-center justify-center gap-4">
- <button
- type="button"
- onClick={() => onStep?.(-1)}
- disabled={frameIndex <= 0}
- className="font-pixel text-cyan-400 text-lg px-2 hover:text-cyan-300 transition-colors pointer-events-auto disabled:opacity-30"
- title="Previous frame (←)"
- >
- ◀
- </button>
- <button
- type="button"
- onClick={onTogglePlay}
- className="font-pixel text-[11px] text-black bg-cyan-400 tracking-wider rounded px-4 py-2 hover:bg-cyan-300 transition-all pointer-events-auto"
- title="Play / pause (Space)"
- >
- {playing ? '❚❚ PAUSE' : '▶ PLAY'}
- </button>
- <button
- type="button"
- onClick={() => onStep?.(1)}
- disabled={frameIndex >= frameCount - 1}
- className="font-pixel text-cyan-400 text-lg px-2 hover:text-cyan-300 transition-colors pointer-events-auto disabled:opacity-30"
- title="Next frame (→)"
- >
- ▶
- </button>
- <button
- type="button"
- onClick={onCycleSpeed}
- className="font-pixel text-[10px] text-cyan-400 tracking-wider border border-cyan-500/40 rounded px-3 py-1.5 hover:bg-cyan-500/10 transition-all pointer-events-auto"
- title="Playback speed"
- >
- {speed}×
- </button>
- </div>
- </div>
- )}
- </div>
- </div>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldProductivityDistrict.jsx b/client/src/components/openworld/OpenWorldProductivityDistrict.jsx
deleted file mode 100644
index bcecb2a51a..0000000000
--- a/client/src/components/openworld/OpenWorldProductivityDistrict.jsx
+++ /dev/null
@@ -1,76 +0,0 @@
-import { useMemo, useRef } from 'react';
-import { useFrame } from '@react-three/fiber';
-import { PIXEL_FONT_URL, openWorldDayMix } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import OpenWorldLabel from './OpenWorldLabel';
-import { computeProductivityMonument } from '../../utils/openWorldProductivity';
-
-// OpenWorld's productivity district: a tapered throughput monument whose
-// height reflects tasks completed today and whose color reflects recent pace.
-export default function OpenWorldProductivityDistrict({ productivityData, settings }) {
- const { tintStructure } = useOpenWorldPalette();
- const monument = useMemo(() => computeProductivityMonument(productivityData), [productivityData]);
- const capRef = useRef();
-
- // Honor the quality dial: drop the capstone pulse on the lowest preset.
- const animate = (settings?.particleDensity ?? 1) >= 0.5;
- const dayMix = openWorldDayMix(settings);
-
- useFrame(({ clock }) => {
- if (!animate || !capRef.current) return;
- const speed = monument.surging ? 3.2 : 1.1;
- const pulse = 0.5 + ((Math.sin(clock.getElapsedTime() * speed) + 1) / 2) * 0.6;
- capRef.current.material.emissiveIntensity = pulse * (monument.intensity + 0.25);
- });
-
- const { position, baseWidth, height, color } = monument;
- const shaftTop = height; // top of the tapered shaft (above the plinth, see group offset)
- const sublabel = monument.tierLabel;
-
- return (
- <group position={position}>
- {/* Stepped plinth the obelisk rises from */}
- <mesh position={[0, 0.4, 0]}>
- <boxGeometry args={[baseWidth * 1.6, 0.8, baseWidth * 1.6]} />
- <meshStandardMaterial color={tintStructure('#0a0e16')} emissive={color} emissiveIntensity={0.08} metalness={0.6} roughness={0.5} />
- </mesh>
- <mesh position={[0, 1.0, 0]}>
- <boxGeometry args={[baseWidth * 1.2, 0.5, baseWidth * 1.2]} />
- <meshStandardMaterial color={tintStructure('#0c121d')} emissive={color} emissiveIntensity={0.12} metalness={0.6} roughness={0.5} />
- </mesh>
-
- {/* Tapered obelisk shaft — height scales with today's throughput. */}
- <group position={[0, 1.25, 0]}>
- <mesh position={[0, shaftTop / 2, 0]}>
- <cylinderGeometry args={[baseWidth * 0.18, baseWidth * 0.42, shaftTop, 4]} />
- <meshStandardMaterial
- color={tintStructure('#0a0e16')}
- emissive={color}
- emissiveIntensity={0.12 + monument.intensity * 0.25}
- metalness={0.6}
- roughness={0.45}
- />
- </mesh>
-
- {/* Glowing capstone — the live pace indicator that pulses. */}
- <mesh ref={capRef} position={[0, shaftTop + baseWidth * 0.22, 0]} rotation={[0, Math.PI / 4, 0]}>
- <coneGeometry args={[baseWidth * 0.34, baseWidth * 0.55, 4]} />
- <meshStandardMaterial color={color} emissive={color} emissiveIntensity={monument.intensity} toneMapped={false} />
- </mesh>
-
- {/* District title + throughput above the monument. */}
- <OpenWorldLabel position={[0, shaftTop + 2.6, 0]} fontSize={1.3} color={color} dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={22}>
- {monument.throughputLabel}
- </OpenWorldLabel>
- <OpenWorldLabel position={[0, shaftTop + 1.7, 0]} fontSize={0.8} color="#94a3b8" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={22}>
- {sublabel}
- </OpenWorldLabel>
- </group>
-
- {/* Ground readout of today's throughput */}
- <OpenWorldLabel position={[0, 0.05, baseWidth * 1.1]} rotation={[-Math.PI / 2, 0, 0]} fontSize={0.7} color="#94a3b8" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={22}>
- {monument.completedToday !== null ? `TODAY ${monument.completedToday} DONE` : 'PRODUCTIVITY'}
- </OpenWorldLabel>
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldScene.jsx b/client/src/components/openworld/OpenWorldScene.jsx
deleted file mode 100644
index 7fa4789f2d..0000000000
--- a/client/src/components/openworld/OpenWorldScene.jsx
+++ /dev/null
@@ -1,556 +0,0 @@
-import { memo, useState, useCallback, useRef, useEffect, useMemo, Suspense } from 'react';
-import * as THREE from 'three';
-import { Canvas } from '@react-three/fiber';
-import { OrbitControls } from '@react-three/drei';
-import OpenWorldLights from './OpenWorldLights';
-import OpenWorldParticles from './OpenWorldParticles';
-import OpenWorldStarfield from './OpenWorldStarfield';
-import OpenWorldCelestial from './OpenWorldCelestial';
-import BuildingCluster from './BuildingCluster';
-import OpenWorldDataStreams from './OpenWorldDataStreams';
-import OpenWorldTraffic from './OpenWorldTraffic';
-import OpenWorldWeather from './OpenWorldWeather';
-import OpenWorldBillboards from './OpenWorldBillboards';
-import OpenWorldShootingStars from './OpenWorldShootingStars';
-import OpenWorldVolumetricLights from './OpenWorldVolumetricLights';
-import OpenWorldFederationHorizon from './OpenWorldFederationHorizon';
-import OpenWorldBackupVault from './OpenWorldBackupVault';
-import OpenWorldTaskQueue from './OpenWorldTaskQueue';
-import OpenWorldHealthTower from './OpenWorldHealthTower';
-import OpenWorldProductivityDistrict from './OpenWorldProductivityDistrict';
-import OpenWorldActivityHeatmap from './OpenWorldActivityHeatmap';
-import OpenWorldTaskFlowRiver from './OpenWorldTaskFlowRiver';
-import OpenWorldGoalMonuments from './OpenWorldGoalMonuments';
-import OpenWorldArtifacts from './OpenWorldArtifacts';
-import OpenWorldEasterEggs from './OpenWorldEasterEggs';
-import OpenWorldVoiceMarker from './OpenWorldVoiceMarker';
-import OpenWorldMemoryDistrict from './OpenWorldMemoryDistrict';
-import OpenWorldDataHarbor from './OpenWorldDataHarbor';
-import OpenWorldJiraDistrict from './OpenWorldJiraDistrict';
-import OpenWorldAiCore from './OpenWorldAiCore';
-import OpenWorldDataRain from './OpenWorldDataRain';
-import OpenWorldNeonSigns from './OpenWorldNeonSigns';
-import OpenWorldEmbers from './OpenWorldEmbers';
-import OpenWorldSignalBeacons from './OpenWorldSignalBeacons';
-import OpenWorldSky from './OpenWorldSky';
-import OpenWorldGalaxySky from './OpenWorldGalaxySky';
-import OpenWorldClouds from './OpenWorldClouds';
-import OpenWorldWater from './OpenWorldWater';
-import OpenWorldArchipelago from './OpenWorldArchipelago';
-import OpenWorldEnergyOverlay from './OpenWorldEnergyOverlay';
-import OpenWorldSpeedPads from './OpenWorldSpeedPads';
-import OpenWorldCollectibles from './OpenWorldCollectibles';
-import PlayerController from './PlayerController';
-import CameraTransition from './CameraTransition';
-import OpenWorldFocusCamera from './OpenWorldFocusCamera';
-import OpenWorldPhotoCamera from './OpenWorldPhotoCamera';
-import OpenWorldDepthOfField from './OpenWorldDepthOfField';
-import OpenWorldAdaptiveQuality from './OpenWorldAdaptiveQuality';
-import { openWorldDayMix, getTimeOfDayPreset } from './openWorldConstants';
-import { CITY_MAX_ORBIT_DISTANCE } from '../../utils/openWorldFocusCamera';
-import { THIRD_PERSON } from '../../utils/openWorldPlayerRig';
-import { listRegions } from '../../utils/openWorldRegions';
-import { getResolvedLandmarks } from '../../utils/openWorldProximity';
-import { getCollectiblesList } from '../../utils/openWorldCollectibles';
-import { computeEasterEggs } from '../../utils/openWorldEasterEggs';
-import { computeVillageAppLayout } from '../../utils/openWorldPlan';
-import { OpenWorldPaletteProvider } from './OpenWorldPaletteContext';
-import ErrorBoundary from '../ErrorBoundary';
-import { useVisibilityEvent } from '../../hooks/useVisibilityEvent';
-
-const STARTUP_PARTICLE_DENSITY = 0.49;
-
-function OpenWorldScene({
- apps,
- agentMap,
- onBuildingClick,
- onToggleCameraView,
- cosStatus,
- reviewCounts,
- instances,
- backupStatus,
- cosTasks,
- healthMetrics,
- voiceState,
- aiActivity,
- productivityData,
- activityCalendar,
- goals,
- character,
- chronotype,
- memoryGraph,
- inboxDepth,
- jiraTickets,
- introspection,
- playback = false,
- photoMode,
- photoPresetId,
- photoDof,
- onPhotoCaptureReady,
- settings,
- playSfx,
- keysRef,
- mobileInputRef,
- playerActionRef,
- dimmedAppIds,
- focusedAppId,
- focusedRegion,
- isFeatureEnabled,
- isPassiveFeatureEnabled,
- playerTeleport,
- hudSafe,
- background,
- palette,
- onTravelToRegion,
- onProximityChange,
- autoQuality = false,
- autoStartTier = 'high',
- autoResetToken = 0,
- onAutoTierChange,
- collectedShardIds = new Set(),
- onCollectShard,
- activeBursts = [],
- onPlayerPoseChange,
-}) {
- const [positions, setPositions] = useState(null);
- const [proximityApp, setProximityApp] = useState(null);
- const [transitioning, setTransitioning] = useState(false);
- const [webglLost, setWebglLost] = useState(false);
- const [canvasRevision, setCanvasRevision] = useState(0);
- const [contextRecoveryMode, setContextRecoveryMode] = useState(false);
- const [startupSettled, setStartupSettled] = useState(false);
- // Visibility-aware frameloop (issue #2592): pause the live OpenWorld render loop while the
- // tab is hidden, resume (with a fresh warm-up) when it's shown again. `resumeToken`
- // bumps on each show so the warm-up effect re-runs and the adaptive budget re-arms.
- const [documentHidden, setDocumentHidden] = useState(
- () => typeof document !== 'undefined' && document.visibilityState === 'hidden'
- );
- const [resumeToken, setResumeToken] = useState(0);
- // Bumped whenever the scene warm-up (re)starts — startup, an app-count change, or a
- // visibility resume — so the adaptive budget re-arms and ignores the 1.2s of artificially
- // cheap (forced-Low) warm-up frames instead of banking them as headroom/erasing pressure.
- const [budgetRearmToken, setBudgetRearmToken] = useState(0);
- useVisibilityEvent(useCallback((state) => {
- const hidden = state === 'hidden';
- setDocumentHidden(hidden);
- if (!hidden) setResumeToken(t => t + 1);
- }, []));
- const prevExplorationRef = useRef(null);
- const orbitRef = useRef(null);
- const contextCleanupRef = useRef(null);
- const villageAppPositions = useMemo(() => computeVillageAppLayout(apps), [apps]);
- const contextLostTimerRef = useRef(null);
- const activeCanvasRef = useRef(null);
- const contextRecoveryRef = useRef(0);
- // Shared between OpenWorldDepthOfField (which owns the EffectComposer while photo mode is on) and
- // OpenWorldPhotoCamera (whose capture path renders through that composer so the postcard matches the
- // DoF preview). Null whenever DoF isn't mounted — capture then falls back to a plain render.
- const photoComposerRef = useRef(null);
-
- const explorationMode = settings?.explorationMode ?? true;
- // Art direction gate, read off the palette every other themed surface already consumes
- // (Building, ProcessBuilding, OpenWorldLandscape) rather than re-resolving the style from
- // settings — one bit, one channel. The neon-night layers below (galaxy spheremap,
- // starfield/shooting stars, data rain, embers, volumetric light cones, neon signage)
- // belong to the OpenWorld style; over the Vibes world's sunlit low-poly landscape they
- // read as haze and grain, so they don't mount at all rather than fading per-frame.
- const neonLayers = Boolean(palette?.neonLayers);
- const jiraFeatureEnabled = typeof isPassiveFeatureEnabled === 'function'
- ? isPassiveFeatureEnabled('jira')
- : typeof isFeatureEnabled === 'function' ? isFeatureEnabled('jira') : true;
- const warpRegions = useMemo(() => listRegions(isFeatureEnabled), [isFeatureEnabled]);
- const landmarks = useMemo(() => getResolvedLandmarks(isFeatureEnabled), [isFeatureEnabled]);
- const collectibles = useMemo(() => getCollectiblesList(isPassiveFeatureEnabled), [isPassiveFeatureEnabled]);
- const easterEggsList = useMemo(
- () => computeEasterEggs({ character, goals }),
- [character, goals]
- );
-
- useEffect(() => {
- if (photoMode) {
- setStartupSettled(true);
- return undefined;
- }
-
- setStartupSettled(false);
- setBudgetRearmToken(t => t + 1);
- const timer = window.setTimeout(() => setStartupSettled(true), 1200);
- return () => window.clearTimeout(timer);
- }, [apps.length, photoMode, resumeToken]);
-
- const renderSettings = useMemo(() => {
- if (!contextRecoveryMode && (photoMode || startupSettled)) return settings;
- // During the startup (and post-visibility-resume) warm-up, drop to the cheapest
- // render path. `effectiveTier: 'low'` also suppresses set dressing + the ray-marched
- // interior-window shader via openWorldShowDetail/openWorldShowInteriorWindows — previously the
- // clamped particleDensity (0.49) did that implicitly; the explicit tier now owns it.
- return {
- ...settings,
- effectiveTier: 'low',
- particleDensity: Math.min(settings?.particleDensity ?? 1, contextRecoveryMode ? 0.25 : STARTUP_PARTICLE_DENSITY),
- dpr: [1, 1],
- };
- }, [contextRecoveryMode, photoMode, settings, startupSettled]);
-
- const clearContextTimer = useCallback(() => {
- if (contextLostTimerRef.current) {
- window.clearTimeout(contextLostTimerRef.current);
- contextLostTimerRef.current = null;
- }
- }, []);
-
- // drei's `keyEvents` only (re)connects pointer events to the DOM element in this
- // three-stdlib version — it does NOT attach the keydown listener OrbitControls
- // needs for arrow-key panning. Wire that explicitly when the orbital controls are
- // mounted (re-runs when the mode flips them in/out), with matching teardown.
- useEffect(() => {
- const controls = orbitRef.current;
- if (!controls?.listenToKeyEvents) return undefined;
- controls.listenToKeyEvents(window);
- return () => controls.stopListenToKeyEvents?.();
- }, [explorationMode, transitioning, photoMode]);
-
- useEffect(() => () => {
- clearContextTimer();
- contextCleanupRef.current?.();
- }, [clearContextTimer]);
-
- // Set transitioning=true when exploration mode toggles. The initial mount is
- // already in the requested mode; starting a transition there briefly hands the
- // camera to the orbital framing before the player rig takes over.
- useEffect(() => {
- if (prevExplorationRef.current === null) {
- prevExplorationRef.current = explorationMode;
- return;
- }
- if (prevExplorationRef.current !== explorationMode) {
- setTransitioning(true);
- prevExplorationRef.current = explorationMode;
- }
- }, [explorationMode]);
-
- const handlePositionsReady = useCallback((pos) => {
- setPositions(pos);
- }, []);
-
- const handleBuildingProximity = useCallback((app) => {
- setProximityApp(app);
- }, []);
-
- useEffect(() => {
- if (explorationMode) return;
- setProximityApp(null);
- onProximityChange?.(null);
- }, [explorationMode, onProximityChange]);
-
- const handleTransitionComplete = useCallback(() => {
- setTransitioning(false);
- }, []);
-
- // Weather reflects confirmed outages. A PM2-unavailable ('unknown') app's
- // status is simply unknown, not down — excluded so a read blip doesn't
- // conjure rain/lightning over apps that may well be online.
- const stoppedCount = apps.filter(a => !a.archived && a.overallStatus !== 'online' && a.overallStatus !== 'unknown').length;
- const totalCount = apps.filter(a => !a.archived).length;
-
- // Quality presets always express dpr as a [min, max] pair. Cap it to the live
- // ceiling so a high preset can't push a context-losing pixel ratio; photo mode
- // gets a touch more for crisp postcards.
- const rawDpr = renderSettings?.dpr || [1, 1.25];
- const dprLimit = photoMode ? 1.5 : 1.25;
- const dpr = rawDpr.map(value => Math.min(value, dprLimit));
- const showGradientBackground = openWorldDayMix(renderSettings) > 0.5;
- const sceneClearColor = background || '#030308';
- // The pre-canvas / WebGL-lost backdrop. Under OpenWorld's daylight it's the blue sky
- // gradient; under the Vibes style the sky is warm at the horizon, so it takes its bands
- // from the resolved scene color rather than the hardcoded cyber gradient.
- const skyPreset = getTimeOfDayPreset(renderSettings?.timeOfDay ?? 'sunset');
- const fallbackBackground = showGradientBackground
- ? `linear-gradient(180deg, ${skyPreset.zenith} 0%, ${skyPreset.midSky} 48%, ${skyPreset.horizonLow} 100%)`
- : sceneClearColor;
-
- const handleCanvasCreated = useCallback(({ gl }) => {
- contextCleanupRef.current?.();
- const canvas = gl.domElement;
- activeCanvasRef.current = canvas;
- clearContextTimer();
- const handleContextLost = (event) => {
- event.preventDefault();
- clearContextTimer();
- contextLostTimerRef.current = window.setTimeout(() => {
- contextLostTimerRef.current = null;
- if (activeCanvasRef.current !== canvas || !canvas.isConnected) return;
- const context = gl.getContext?.();
- if (context?.isContextLost?.()) {
- // A transient mobile GPU reset can recover if the renderer is recreated
- // at the cheap tier. Give it one bounded retry instead of leaving the
- // player with an invisible Canvas forever. If the replacement also loses
- // its context, keep the fallback visible and stop retrying.
- if (contextRecoveryRef.current < 1) {
- contextRecoveryRef.current += 1;
- setContextRecoveryMode(true);
- setWebglLost(false);
- setCanvasRevision(revision => revision + 1);
- } else {
- setWebglLost(true);
- }
- }
- }, 750);
- };
- const handleContextRestored = () => {
- clearContextTimer();
- setWebglLost(false);
- };
- canvas.addEventListener('webglcontextlost', handleContextLost, false);
- canvas.addEventListener('webglcontextrestored', handleContextRestored, false);
- contextCleanupRef.current = () => {
- clearContextTimer();
- if (activeCanvasRef.current === canvas) {
- activeCanvasRef.current = null;
- }
- canvas.removeEventListener('webglcontextlost', handleContextLost, false);
- canvas.removeEventListener('webglcontextrestored', handleContextRestored, false);
- };
- setWebglLost(false);
- }, [clearContextTimer]);
-
- return (
- <div className="absolute inset-0" style={{ background: fallbackBackground }}>
- <Canvas
- key={`${photoMode ? 'photo' : 'live'}-${canvasRevision}`}
- camera={{ position: [0, 95, 125], fov: THIRD_PERSON.fov }}
- dpr={dpr}
- shadows={explorationMode && settings?.effectiveTier !== 'low'}
- // Photo mode freezes the scene for a clean still (roadmap 3.6): "demand" stops the
- // frameloop once the camera-fly settles, so particles/streams/weather/pulses pause for a
- // deliberate shot. OpenWorldPhotoCamera pumps invalidate() during the fly; capture renders
- // directly via gl.render(). Live mode keeps the always-on loop the dashboard relies on —
- // except while the tab is hidden, where "never" halts rendering entirely (issue #2592).
- // Photo mode always keeps its own demand loop so capture still works in a hidden tab.
- frameloop={photoMode ? 'demand' : (documentHidden ? 'never' : 'always')}
- onCreated={handleCanvasCreated}
- style={{ background: sceneClearColor, cursor: explorationMode ? 'grab' : 'auto', opacity: webglLost ? 0 : 1 }}
- // preserveDrawingBuffer is only needed while taking postcards. Keeping it
- // always-on makes Chromium's WebGL context much easier to lose in the live
- // dashboard, which reads as a blank white scene.
- gl={{ antialias: !contextRecoveryMode, preserveDrawingBuffer: Boolean(photoMode), alpha: false, powerPreference: contextRecoveryMode ? 'default' : 'high-performance' }}
- >
- {/* Re-provide the themed palette INSIDE the Canvas — react-three-fiber runs its
- own reconciler, so the provider in OpenWorldInner doesn't reach these scene
- components. Plain React Context.Provider works across the r3f tree. */}
- <OpenWorldPaletteProvider palette={palette}>
- {/* Exactly one owner for scene.background, written as a ternary so the invariant is
- structural rather than two conditions a reader has to De Morgan: the galaxy
- Environment (the equirectangular spheremap) and a solid <color attach="background">
- both write scene.background and would fight every frame. The galaxy mounts only for
- the neon-night style at night — which also keeps its 2.8MB panorama from being
- fetched/decoded (and PMREM-processed) in daylight, where it's faded out anyway.
- Suspense keeps the texture load from suspending the whole canvas while it streams
- in; the error boundary degrades to the plain solid sky if the texture is
- missing/corrupt (e.g. a partial checkout) instead of crashing. */}
- {neonLayers && !showGradientBackground ? (
- <ErrorBoundary fallback={null}>
- <Suspense fallback={null}>
- <OpenWorldGalaxySky settings={renderSettings} />
- </Suspense>
- </ErrorBoundary>
- ) : (
- <color attach="background" args={[sceneClearColor]} />
- )}
- {explorationMode && <fog attach="fog" args={[sceneClearColor, 72, 190]} />}
- <OpenWorldSky settings={renderSettings} />
- {/* `lightingTier` is the SETTLED tier, deliberately not the warm-up-clamped
- one: the accent-light gate changes the scene's light COUNT, which is part
- of three.js's shader program cache key, so letting the clamp toggle it
- would recompile every lit material 1.2s into each load. */}
- <OpenWorldLights settings={renderSettings} lightingTier={settings?.effectiveTier} />
- <OpenWorldWater settings={renderSettings} />
- <OpenWorldArchipelago
- settings={renderSettings}
- explorationMode={explorationMode}
- apps={apps}
- appPositions={villageAppPositions}
- agentMap={agentMap}
- backupStatus={backupStatus}
- cosTasks={cosTasks}
- healthMetrics={healthMetrics}
- productivityData={productivityData}
- goals={goals}
- character={character}
- memoryGraph={memoryGraph}
- inboxDepth={inboxDepth}
- jiraTickets={jiraTickets}
- jiraEnabled={jiraFeatureEnabled}
- introspection={introspection}
- voiceState={voiceState}
- onBuildingClick={onBuildingClick}
- />
- {palette?.lowPoly && <OpenWorldClouds settings={renderSettings} />}
- {!explorationMode && <OpenWorldEnergyOverlay chronotype={chronotype} settings={renderSettings} />}
- {neonLayers && <OpenWorldStarfield settings={renderSettings} />}
- {neonLayers && <OpenWorldShootingStars playSfx={playSfx} settings={renderSettings} />}
- {!explorationMode && !palette?.lowPoly && <OpenWorldCelestial settings={renderSettings} />}
- {!explorationMode && (
- <>
- <OpenWorldFederationHorizon instances={instances} settings={renderSettings} />
- <OpenWorldBackupVault backupStatus={backupStatus} settings={renderSettings} />
- <OpenWorldTaskQueue cosTasks={cosTasks} settings={renderSettings} />
- <OpenWorldHealthTower healthMetrics={healthMetrics} settings={renderSettings} />
- <OpenWorldProductivityDistrict productivityData={productivityData} settings={renderSettings} />
- <OpenWorldActivityHeatmap calendarData={activityCalendar} settings={renderSettings} />
- <OpenWorldTaskFlowRiver cosTasks={cosTasks} productivityData={productivityData} calendarData={activityCalendar} settings={renderSettings} />
- <OpenWorldGoalMonuments goals={goals} settings={renderSettings} />
- <OpenWorldArtifacts character={character} goals={goals} settings={renderSettings} />
- <OpenWorldEasterEggs character={character} goals={goals} settings={renderSettings} />
- <OpenWorldVoiceMarker voiceState={voiceState} settings={renderSettings} />
- <OpenWorldMemoryDistrict memoryGraph={memoryGraph} inboxDepth={inboxDepth} settings={renderSettings} />
- <OpenWorldDataHarbor introspection={introspection} settings={renderSettings} />
- {jiraFeatureEnabled && <OpenWorldJiraDistrict jiraTickets={jiraTickets} settings={renderSettings} />}
- <OpenWorldAiCore aiActivity={aiActivity} positions={positions} apps={apps} settings={renderSettings} />
- </>
- )}
- <OpenWorldSpeedPads settings={renderSettings} />
- <OpenWorldCollectibles
- collectedShardIds={collectedShardIds}
- activeBursts={activeBursts}
- settings={renderSettings}
- shards={collectibles}
- />
- {!explorationMode && (
- <>
- <BuildingCluster
- apps={apps}
- agentMap={agentMap}
- onBuildingClick={onBuildingClick}
- onPositionsReady={handlePositionsReady}
- playSfx={playSfx}
- settings={renderSettings}
- proximityAppId={proximityApp?.id}
- dimmedAppIds={dimmedAppIds}
- focusedAppId={focusedAppId}
- playback={playback}
- />
- <OpenWorldDataStreams positions={positions} apps={apps} agentMap={agentMap} />
- <OpenWorldTraffic positions={positions} />
- <OpenWorldBillboards
- positions={positions}
- apps={apps}
- cosStatus={cosStatus}
- reviewCounts={reviewCounts}
- instances={instances}
- productivityData={productivityData}
- />
- <OpenWorldSignalBeacons
- positions={positions}
- reviewCounts={reviewCounts}
- instances={instances}
- settings={renderSettings}
- activeRegionId={focusedRegion?.id}
- onTravelToRegion={onTravelToRegion}
- regions={warpRegions}
- />
- </>
- )}
- {neonLayers && <OpenWorldVolumetricLights positions={positions} settings={renderSettings} />}
- {neonLayers && <OpenWorldNeonSigns positions={positions} />}
- <OpenWorldWeather stoppedCount={stoppedCount} totalCount={totalCount} playSfx={playSfx} />
- {neonLayers && <OpenWorldDataRain settings={renderSettings} />}
- {neonLayers && <OpenWorldEmbers settings={renderSettings} />}
- <OpenWorldParticles settings={renderSettings} />
- {explorationMode && (
- <PlayerController
- keysRef={keysRef}
- positions={villageAppPositions}
- onBuildingProximity={handleBuildingProximity}
- onProximityChange={onProximityChange}
- onBuildingClick={onBuildingClick}
- onToggleCameraView={onToggleCameraView}
- apps={apps}
- active={explorationMode}
- transitioning={transitioning}
- cameraView={settings?.cameraView ?? 'third'}
- teleport={playerTeleport}
- // Street-level travel is attached to visible cottages and landmarks. The old
- // invisible region pads produced prompts in the middle of otherwise empty roads.
- warpPads={[]}
- landmarks={landmarks}
- onWarpPadInteract={onTravelToRegion}
- easterEggs={easterEggsList.eggs}
- shards={collectibles}
- collectedShardIds={collectedShardIds}
- onCollectShard={onCollectShard}
- onPlayerPoseChange={onPlayerPoseChange}
- playSfx={playSfx}
- mobileInputRef={mobileInputRef}
- playerActionRef={playerActionRef}
- />
- )}
- {!explorationMode && !transitioning && !photoMode && (
- <OrbitControls
- // Map-style navigation: left-drag pans the camera across the city (so you can
- // reach off-center districts without first-person mode), right-drag rotates, scroll
- // zooms, arrow keys pan (wired via listenToKeyEvents in the effect above). On a Mac
- // trackpad, ctrl+drag registers as a right-click so it rotates. screenSpacePanning=
- // false keeps panning in the ground plane (map feel).
- ref={orbitRef}
- enablePan
- screenSpacePanning={false}
- panSpeed={1.0}
- keyPanSpeed={24}
- maxPolarAngle={Math.PI / 2.2}
- minDistance={5}
- // Shared with the framing math (see CITY_MAX_ORBIT_DISTANCE) so a fast-travel fly
- // never ends past a distance the controls would immediately snap back.
- maxDistance={CITY_MAX_ORBIT_DISTANCE}
- enableDamping
- dampingFactor={0.05}
- mouseButtons={{ LEFT: THREE.MOUSE.PAN, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: THREE.MOUSE.ROTATE }}
- touches={{ ONE: THREE.TOUCH.PAN, TWO: THREE.TOUCH.DOLLY_ROTATE }}
- />
- )}
- {/* Auto quality mode: samples frame times inside the live loop and lifts tier
- changes back up to the page. Never mounted in photo mode (its demand loop
- isn't a steady-state signal). Renders nothing. */}
- {!photoMode && (
- <OpenWorldAdaptiveQuality
- enabled={autoQuality}
- startTier={autoStartTier}
- resumeToken={budgetRearmToken}
- resetToken={autoResetToken}
- onTierChange={onAutoTierChange}
- />
- )}
- <CameraTransition
- active={explorationMode}
- onTransitionComplete={handleTransitionComplete}
- />
- {/* URL-addressed building focus (issue #2593). Mounted only in the orbital overview (not
- exploration/photo, which own the camera). Placed AFTER CameraTransition so its per-frame
- camera write wins during any brief overlap on load. */}
- {!explorationMode && !photoMode && (
- <OpenWorldFocusCamera
- focusedAppId={focusedAppId}
- focusedRegion={focusedRegion}
- positions={positions}
- orbitRef={orbitRef}
- active={!explorationMode && !photoMode}
- hudSafe={hudSafe}
- />
- )}
- <OpenWorldPhotoCamera active={photoMode} presetId={photoPresetId} onReady={onPhotoCaptureReady} composerRef={photoComposerRef} />
- {/* Depth-of-field is photo-mode-only: mounting it here (never in the live dashboard) keeps the
- extra composer render targets off the always-on frameloop. It stays mounted for the whole
- photo session and toggles only the bokeh pass via `enabled` — mounting/unmounting per
- toggle would churn render-loop ownership and could strand a blurred frozen frame on screen
- when DoF flips off mid-freeze. */}
- {photoMode && <OpenWorldDepthOfField presetId={photoPresetId} enabled={photoDof} composerRef={photoComposerRef} />}
- </OpenWorldPaletteProvider>
- </Canvas>
- </div>
- );
-}
-
-// HUD telemetry (rover pose, clock, socket logs) updates much more often than scene
-// inputs. Keep those parent renders out of the expensive r3f tree; React still
-// re-enters the scene whenever any actual scene prop changes.
-export default memo(OpenWorldScene);
diff --git a/client/src/components/openworld/OpenWorldSettingsContext.jsx b/client/src/components/openworld/OpenWorldSettingsContext.jsx
deleted file mode 100644
index 9abf983140..0000000000
--- a/client/src/components/openworld/OpenWorldSettingsContext.jsx
+++ /dev/null
@@ -1,25 +0,0 @@
-import { createContext, useContext, useMemo } from 'react';
-import useOpenWorldSettings from '../../hooks/useOpenWorldSettings';
-
-const OpenWorldSettingsContext = createContext(null);
-
-export function OpenWorldSettingsProvider({ children }) {
- const [settings, updateSetting, resetSettings, resetNonce] = useOpenWorldSettings();
-
- const value = useMemo(
- () => ({ settings, updateSetting, resetSettings, resetNonce }),
- [settings, updateSetting, resetSettings, resetNonce]
- );
-
- return (
- <OpenWorldSettingsContext.Provider value={value}>
- {children}
- </OpenWorldSettingsContext.Provider>
- );
-}
-
-export function useOpenWorldSettingsContext() {
- const ctx = useContext(OpenWorldSettingsContext);
- if (!ctx) return { settings: null, updateSetting: () => {}, resetSettings: () => {}, resetNonce: 0 };
- return ctx;
-}
diff --git a/client/src/components/openworld/OpenWorldSettingsDrawer.jsx b/client/src/components/openworld/OpenWorldSettingsDrawer.jsx
deleted file mode 100644
index 71b2126d95..0000000000
--- a/client/src/components/openworld/OpenWorldSettingsDrawer.jsx
+++ /dev/null
@@ -1,335 +0,0 @@
-import Drawer from '../Drawer';
-import useDrawerTab from '../../hooks/useDrawerTab';
-import { useOpenWorldSettingsContext } from './OpenWorldSettingsContext';
-import { SOUNDSCAPE_MOODS, isSoundscapeMood } from '../../utils/openWorldSoundscape';
-import { WORLD_STYLE_DEFS, WORLD_STYLES, resolveWorldStyle } from './openWorldConstants';
-
-// Derived from the style table, so registering a style makes it pickable — no second list.
-const WORLD_STYLE_OPTIONS = WORLD_STYLES.map((key) => ({ key, label: WORLD_STYLE_DEFS[key].label }));
-
-// The soundscape override's "no override" option. A <select> cannot carry null, so the
-// auto choice rides as the empty string and the change handler maps it back to the null
-// sentinel — keeping "following live state" distinct from "pinned to a mood".
-const SOUNDSCAPE_AUTO = '';
-const SOUNDSCAPE_OPTIONS = [
- { value: SOUNDSCAPE_AUTO, label: 'AUTO' },
- ...SOUNDSCAPE_MOODS.map(mood => ({ value: mood, label: mood.toUpperCase() })),
-];
-
-// OpenWorld settings stay on the shared Drawer, but the surface is intentionally small:
-// world style, sound, and controls are player choices. Render quality, scanlines, reflections,
-// and brightness sliders were implementation leftovers from earlier versions of the world and
-// are now resolved by the scene's art direction and adaptive renderer.
-
-function SettingToggle({ id, label, value, onChange, description, disabled = false }) {
- return (
- <div className={`flex items-center justify-between py-2 group ${disabled ? 'opacity-40' : ''}`} title={description}>
- <label htmlFor={id} className={`font-sans text-[12px] text-gray-300 tracking-wide ${disabled ? 'cursor-not-allowed' : 'cursor-pointer'}`}>
- {label}
- </label>
- <button
- id={id}
- type="button"
- role="switch"
- aria-checked={value}
- aria-label={label}
- disabled={disabled}
- onClick={() => !disabled && onChange(!value)}
- className={`w-11 h-6 rounded-full relative transition-colors border ${value ? 'bg-cyan-500/40 border-cyan-500/60' : 'bg-gray-700/40 border-gray-600/40'} ${disabled ? 'cursor-not-allowed' : ''}`}
- >
- <span
- className={`absolute top-0.5 w-4 h-4 rounded-full transition-all ${value ? 'left-[22px] bg-cyan-400 shadow-[0_0_6px_rgba(6,182,212,0.5)]' : 'left-[2px] bg-gray-500'}`}
- />
- </button>
- </div>
- );
-}
-
-function SettingSlider({ id, label, value, onChange, min = 0, max = 1, step = 0.05, format, description, disabled = false }) {
- const displayValue = format ? format(value) : `${Math.round(value * 100)}%`;
- return (
- <div className={`py-2 ${disabled ? 'opacity-40' : ''}`} title={description}>
- <div className="flex items-center justify-between mb-1.5">
- <label htmlFor={id} className="font-sans text-[12px] text-gray-300 tracking-wide">{label}</label>
- <span className="font-mono text-[11px] text-cyan-400/70">{displayValue}</span>
- </div>
- <input
- id={id}
- type="range"
- min={min}
- max={max}
- step={step}
- value={value}
- disabled={disabled}
- onChange={(e) => onChange(parseFloat(e.target.value))}
- aria-label={label}
- className={`w-full h-2 bg-gray-700 rounded-full appearance-none accent-cyan-500 ${disabled ? 'cursor-not-allowed' : 'cursor-pointer'}`}
- style={{
- background: `linear-gradient(to right, #06b6d4 0%, #06b6d4 ${(value - min) / (max - min) * 100}%, #374151 ${(value - min) / (max - min) * 100}%, #374151 100%)`,
- }}
- />
- </div>
- );
-}
-
-// Dropdown enum picker, for enums with too many options to read as a segmented row.
-// `options` is [{ value, label }]; values are plain strings (the caller maps any sentinel).
-function SettingSelect({ id, label, value, onChange, options, hint, description }) {
- return (
- <div className="py-2" title={description}>
- <label htmlFor={id} className="block font-sans text-[12px] text-gray-300 tracking-wide mb-1.5">{label}</label>
- <select
- id={id}
- value={value}
- onChange={(e) => onChange(e.target.value)}
- className="w-full font-sans text-[12px] min-h-[44px] px-2 rounded border border-gray-700/40 bg-gray-800/40 text-gray-300 tracking-wide focus:border-cyan-500/50 focus:outline-none"
- >
- {options.map(({ value: optionValue, label: optionLabel }) => (
- <option key={optionValue} value={optionValue}>{optionLabel}</option>
- ))}
- </select>
- {hint && <div className="font-mono text-[10px] text-gray-500 tracking-wide mt-1.5">{hint}</div>}
- </div>
- );
-}
-
-// Segmented enum picker. `isActive` defaults to strict equality; pass a predicate
-// for legacy-value mapping.
-function SettingSegment({ label, options, value, onChange, hint, isActive }) {
- const activeFor = isActive ?? ((key) => value === key);
- return (
- <div className="py-2">
- {label && <div className="font-sans text-[12px] text-gray-300 tracking-wide mb-2">{label}</div>}
- <div className={`grid gap-1.5 ${options.length === 2 ? 'grid-cols-2' : 'grid-cols-3'}`} role="group" aria-label={label}>
- {options.map(({ key, label: optionLabel }) => (
- <button
- key={key}
- type="button"
- aria-pressed={activeFor(key)}
- onClick={() => onChange(key)}
- className={`font-sans text-[11px] min-h-[44px] rounded border transition-all tracking-wide ${
- activeFor(key)
- ? 'bg-cyan-500/20 border-cyan-500/50 text-cyan-400 shadow-[0_0_8px_rgba(6,182,212,0.2)]'
- : 'bg-gray-800/40 border-gray-700/40 text-gray-400 hover:border-gray-600 hover:text-gray-300'
- }`}
- >
- {optionLabel}
- </button>
- ))}
- </div>
- {hint && <div className="font-mono text-[10px] text-gray-500 tracking-wide mt-1.5">{hint}</div>}
- </div>
- );
-}
-
-function SectionHeader({ title, subtitle }) {
- return (
- <div className="mb-2">
- <div className="font-mono text-[10px] font-semibold text-cyan-500/70 tracking-[0.14em]">{title}</div>
- {subtitle && <div className="font-sans text-[11px] text-gray-500 tracking-wide mt-0.5">{subtitle}</div>}
- </div>
- );
-}
-
-function KeyCaps({ keys }) {
- return (
- <span className="flex shrink-0 items-center gap-1" aria-label={keys.join(' / ')}>
- {keys.map(key => (
- <kbd key={key} className="inline-flex min-w-[28px] min-h-[26px] items-center justify-center rounded-md border border-cyan-500/25 bg-cyan-500/[0.08] px-1.5 font-mono text-[10px] font-semibold text-cyan-300">
- {key}
- </kbd>
- ))}
- </span>
- );
-}
-
-function ControlRow({ keys, label, hint }) {
- return (
- <div className="flex items-center justify-between gap-3 border-b border-gray-700/30 py-2.5 last:border-b-0">
- <div className="min-w-0">
- <div className="font-sans text-[12px] text-gray-200">{label}</div>
- {hint && <div className="font-sans text-[10px] text-gray-500 mt-0.5">{hint}</div>}
- </div>
- <KeyCaps keys={keys} />
- </div>
- );
-}
-
-export const CITY_SETTINGS_TABS = [
- { id: 'audio', label: 'Audio' },
- { id: 'visual', label: 'Visual' },
- { id: 'controls', label: 'Controls' },
-];
-const TAB_IDS = CITY_SETTINGS_TABS.map(t => t.id);
-
-export default function OpenWorldSettingsDrawer({ open, onClose }) {
- const { settings, updateSetting, resetSettings } = useOpenWorldSettingsContext();
- const [activeTab, setActiveTab] = useDrawerTab('openWorldTab', 'audio', TAB_IDS);
-
- if (!open || !settings) return null;
-
- const worldStyle = resolveWorldStyle(settings.worldStyle);
- const isCyberCity = worldStyle === 'cyber';
-
- return (
- <Drawer
- open={open}
- onClose={onClose}
- title="OpenWorld Settings"
- size="sm"
- tabs={CITY_SETTINGS_TABS}
- activeTab={activeTab}
- onTabChange={setActiveTab}
- closeLabel="Close city settings"
- // Drawer portals to <body>, so re-apply the page scope for the themed panel and its
- // typography. The extra hook is useful for drawer-only spacing without touching all HUD.
- portalClassName="openworld-themed openworld-settings-portal"
- >
- {activeTab === 'audio' && (
- <div className="space-y-5">
- <div>
- <SectionHeader title="MUSIC" subtitle="Procedural synthwave background" />
- <SettingToggle
- id="city-music-enabled"
- label="SYNTHWAVE"
- value={settings.musicEnabled}
- onChange={(v) => updateSetting('musicEnabled', v)}
- description="Enable ambient synthwave music"
- />
- {settings.musicEnabled && (
- <>
- <SettingSlider
- id="city-music-volume"
- label="VOLUME"
- value={settings.musicVolume}
- onChange={(v) => updateSetting('musicVolume', v)}
- description="Music playback volume"
- />
- <SettingSelect
- id="city-soundscape-override"
- label="SOUNDSCAPE"
- value={isSoundscapeMood(settings.soundscapeOverride) ? settings.soundscapeOverride : SOUNDSCAPE_AUTO}
- onChange={(v) => updateSetting('soundscapeOverride', v === SOUNDSCAPE_AUTO ? null : v)}
- options={SOUNDSCAPE_OPTIONS}
- hint="AUTO FOLLOWS SYSTEM HEALTH AND AGENT ACTIVITY"
- description="Pin the ambient music's mood, or follow live system state"
- />
- </>
- )}
- </div>
- <div>
- <SectionHeader title="SOUND FX" subtitle="UI and environment sounds" />
- <SettingToggle
- id="city-sfx-enabled"
- label="ENABLED"
- value={settings.sfxEnabled}
- onChange={(v) => updateSetting('sfxEnabled', v)}
- description="Enable sound effects for interactions"
- />
- {settings.sfxEnabled && (
- <SettingSlider
- id="city-sfx-volume"
- label="VOLUME"
- value={settings.sfxVolume}
- onChange={(v) => updateSetting('sfxVolume', v)}
- description="Sound effects volume"
- />
- )}
- </div>
- </div>
- )}
-
- {activeTab === 'visual' && (
- <div className="space-y-5">
- <div>
- <SectionHeader title="WORLD" subtitle="Choose the world’s art direction" />
- <SettingSegment
- label="WORLD STYLE"
- options={WORLD_STYLE_OPTIONS}
- value={worldStyle}
- onChange={(key) => updateSetting('worldStyle', key)}
- hint="OPEN WORLD IS BRIGHT AND LOW-POLY; CYBER CITY IS NEON AFTER DARK"
- />
- </div>
- <div>
- <SectionHeader title="TIME" subtitle={isCyberCity ? 'Cyber City keeps its nocturnal identity' : 'Open World can follow your PortOS theme'} />
- {isCyberCity ? (
- <div className="rounded-xl border border-cyan-500/20 bg-cyan-500/[0.06] px-3 py-3">
- <div className="font-mono text-[10px] font-semibold tracking-[0.14em] text-cyan-300">ALWAYS NIGHT</div>
- <p className="mt-1 font-sans text-[11px] leading-5 text-gray-400">Neon materials and the moonlit sky are designed as one scene, so daylight is not offered in this style.</p>
- </div>
- ) : (
- <SettingSegment
- label="TIME OF DAY"
- options={[
- { key: 'auto', label: 'AUTO' },
- { key: 'day', label: 'DAY' },
- { key: 'night', label: 'NIGHT' },
- ]}
- value={settings.timeOfDay}
- onChange={(key) => updateSetting('timeOfDay', key)}
- hint="AUTO FOLLOWS YOUR PORTOS THEME"
- isActive={(key) => (settings.timeOfDay === 'day' || settings.timeOfDay === 'night')
- ? settings.timeOfDay === key
- : key === 'auto'}
- />
- )}
- </div>
- <div className="rounded-xl border border-gray-700/35 bg-black/10 px-3 py-3">
- <div className="font-sans text-[12px] text-gray-200">A focused visual language</div>
- <p className="mt-1 font-sans text-[11px] leading-5 text-gray-500">The renderer now adapts detail automatically. The scene keeps its lighting, ground, and atmosphere coherent on every tier.</p>
- </div>
- </div>
- )}
-
- {activeTab === 'controls' && (
- <div className="space-y-5">
- <div>
- <SectionHeader title="PLAY MODE" subtitle="Switch between the map and street level" />
- <SettingToggle
- id="city-exploration-mode"
- label="DROP IN MODE"
- value={settings.explorationMode}
- onChange={(v) => updateSetting('explorationMode', v)}
- description="Toggle street-level exploration (Tab)"
- />
- <SettingSegment
- label="CAMERA"
- options={[
- { key: 'third', label: 'ROVER' },
- { key: 'first', label: 'FIRST PERSON' },
- ]}
- value={settings.cameraView ?? 'third'}
- onChange={(key) => updateSetting('cameraView', key)}
- hint="V SWITCHES CAMERA WHILE EXPLORING"
- />
- </div>
- <div>
- <SectionHeader title="MOVEMENT" subtitle="Keyboard and mouse controls" />
- <div className="rounded-xl border border-gray-700/35 bg-black/10 px-3">
- <ControlRow keys={['W', 'A', 'S', 'D']} label="Move" hint="Arrow keys also work" />
- <ControlRow keys={['SHIFT']} label="Boost" />
- <ControlRow keys={['CTRL']} label="Brake" hint="Hold while steering for a tighter turn" />
- <ControlRow keys={['SPACE']} label="Jump" />
- <ControlRow keys={['E', 'Q']} label="Fly up / down" hint="Free-fly vertical movement" />
- <ControlRow keys={['F']} label="Interact" hint="Buildings and warp pads" />
- <ControlRow keys={['R']} label="Respawn" hint="Return to your drop-in point" />
- <ControlRow keys={['V']} label="Switch camera" />
- <ControlRow keys={['TAB']} label="Drop in / fly out" />
- <ControlRow keys={['M']} label="World map" />
- <ControlRow keys={['DRAG']} label="Look around" hint="Click the scene to capture the mouse" />
- <ControlRow keys={['SCROLL']} label="Camera zoom" hint="Mouse wheel pulls the camera in / out" />
- </div>
- </div>
- <button
- type="button"
- onClick={resetSettings}
- className="w-full font-sans text-[12px] min-h-[44px] rounded border border-port-error/30 text-port-error/70 hover:bg-port-error/10 hover:text-port-error transition-all tracking-wider"
- >
- RESET DEFAULTS
- </button>
- </div>
- )}
- </Drawer>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldSettingsDrawer.test.jsx b/client/src/components/openworld/OpenWorldSettingsDrawer.test.jsx
deleted file mode 100644
index 22c0455d2c..0000000000
--- a/client/src/components/openworld/OpenWorldSettingsDrawer.test.jsx
+++ /dev/null
@@ -1,95 +0,0 @@
-import { describe, it, expect, vi } from 'vitest';
-import { render, screen, fireEvent } from '@testing-library/react';
-import { MemoryRouter, useLocation } from 'react-router';
-import OpenWorldSettingsDrawer from './OpenWorldSettingsDrawer';
-import { OpenWorldSettingsProvider } from './OpenWorldSettingsContext';
-
-function Loc() {
- const l = useLocation();
- return <div data-testid="loc">{l.search}</div>;
-}
-
-const renderDrawer = (search = '', onClose = () => {}) =>
- render(
- <MemoryRouter initialEntries={[`/openworld/settings${search}`]}>
- <OpenWorldSettingsProvider>
- <OpenWorldSettingsDrawer open onClose={onClose} />
- </OpenWorldSettingsProvider>
- <Loc />
- </MemoryRouter>,
- );
-
-describe('OpenWorldSettingsDrawer', () => {
- it('renders the shared Drawer with focused player-choice tabs', () => {
- renderDrawer();
- expect(screen.getByRole('dialog', { name: 'OpenWorld Settings' })).toBeInTheDocument();
- ['Audio', 'Visual', 'Controls'].forEach(label => {
- expect(screen.getByRole('tab', { name: label })).toBeInTheDocument();
- });
- // Default tab content.
- expect(screen.getByText('MUSIC')).toBeInTheDocument();
- });
-
- it('switches tabs and persists the active tab in the URL', () => {
- renderDrawer();
- fireEvent.click(screen.getByRole('tab', { name: 'Controls' }));
- expect(screen.getByText('MOVEMENT')).toBeInTheDocument();
- expect(screen.queryByText('MUSIC')).not.toBeInTheDocument();
- expect(screen.getByTestId('loc').textContent).toContain('openWorldTab=controls');
- });
-
- it('shows the actual exploration controls without legacy renderer knobs', () => {
- renderDrawer('?openWorldTab=controls');
- expect(screen.getByText('MOVEMENT')).toBeInTheDocument();
- expect(screen.getByText('Drop in / fly out')).toBeInTheDocument();
- expect(screen.getByText('SPACE')).toBeInTheDocument();
- expect(screen.queryByText('QUALITY')).not.toBeInTheDocument();
- expect(screen.queryByText('PARTICLE DENSITY')).not.toBeInTheDocument();
- });
-
- it('deep-links the active tab from the URL param', () => {
- renderDrawer('?openWorldTab=visual');
- expect(screen.getByText('WORLD')).toBeInTheDocument();
- expect(screen.getByRole('tab', { name: 'Visual', selected: true })).toBeInTheDocument();
- });
-
- it('invokes onClose from the Drawer close control', () => {
- const onClose = vi.fn();
- renderDrawer('', onClose);
- fireEvent.click(screen.getByRole('button', { name: 'Close city settings' }));
- expect(onClose).toHaveBeenCalledTimes(1);
- });
-
- it('offers a soundscape override with Auto plus every mood, and persists the choice', () => {
- window.localStorage.clear();
- renderDrawer('?openWorldTab=audio');
- // The override rides with the music controls, so it appears once music is on.
- expect(screen.queryByLabelText('SOUNDSCAPE')).toBeNull();
- fireEvent.click(screen.getByRole('switch', { name: 'SYNTHWAVE' }));
-
- const select = screen.getByLabelText('SOUNDSCAPE');
- expect([...select.options].map(o => o.textContent)).toEqual(['AUTO', 'BRIGHT', 'NEUTRAL', 'TENSE']);
- expect(select.value).toBe('');
-
- fireEvent.change(select, { target: { value: 'tense' } });
- expect(screen.getByLabelText('SOUNDSCAPE').value).toBe('tense');
- expect(JSON.parse(window.localStorage.getItem('portos-city-settings')).soundscapeOverride).toBe('tense');
-
- // Back to Auto — stored as the explicit null sentinel, not an empty string.
- fireEvent.change(screen.getByLabelText('SOUNDSCAPE'), { target: { value: '' } });
- expect(screen.getByLabelText('SOUNDSCAPE').value).toBe('');
- expect(JSON.parse(window.localStorage.getItem('portos-city-settings')).soundscapeOverride).toBeNull();
- window.localStorage.clear();
- });
-
- it('renders nothing when closed', () => {
- const { container } = render(
- <MemoryRouter initialEntries={['/openworld']}>
- <OpenWorldSettingsProvider>
- <OpenWorldSettingsDrawer open={false} onClose={() => {}} />
- </OpenWorldSettingsProvider>
- </MemoryRouter>,
- );
- expect(container.querySelector('[role="dialog"]')).toBeNull();
- });
-});
diff --git a/client/src/components/openworld/OpenWorldShootingStars.jsx b/client/src/components/openworld/OpenWorldShootingStars.jsx
deleted file mode 100644
index 3aaec07ae5..0000000000
--- a/client/src/components/openworld/OpenWorldShootingStars.jsx
+++ /dev/null
@@ -1,213 +0,0 @@
-import { useRef, useMemo } from 'react';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { getTimeOfDayPreset } from './openWorldConstants';
-
-// Vertex shader for shooting star trail
-const TRAIL_VERT = `
- attribute float trailPosition;
- varying float vTrailPos;
- void main() {
- vTrailPos = trailPosition;
- vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
- gl_Position = projectionMatrix * mvPosition;
- }
-`;
-
-const TRAIL_FRAG = `
- varying float vTrailPos;
- uniform vec3 uColor;
- uniform float uOpacity;
- void main() {
- // Fade trail from bright head to transparent tail
- float alpha = smoothstep(0.0, 0.3, vTrailPos) * (1.0 - vTrailPos) * uOpacity;
- gl_FragColor = vec4(uColor, alpha * 0.8);
- }
-`;
-
-// A single shooting star with glowing head and fading trail
-function ShootingStar({ index, playSfx, daylightRef }) {
- const groupRef = useRef();
- const headRef = useRef();
- const trailRef = useRef();
- const matRef = useRef();
-
- const state = useRef({
- active: false,
- nextSpawn: 3 + index * 5 + Math.random() * 10,
- progress: 0,
- speed: 0,
- startPos: [0, 0, 0],
- direction: [0, 0, 0],
- color: [1, 1, 1],
- length: 8,
- });
-
- const trailPoints = useMemo(() => {
- const segments = 20;
- const positions = new Float32Array(segments * 3);
- const trailPos = new Float32Array(segments);
- for (let i = 0; i < segments; i++) {
- trailPos[i] = i / (segments - 1); // 0 = head, 1 = tail
- }
- return { positions, trailPos, segments };
- }, []);
-
- const colors = useMemo(() => [
- [1.0, 1.0, 1.0], // white
- [0.6, 0.8, 1.0], // blue-white
- [1.0, 0.7, 0.3], // golden
- [0.4, 1.0, 0.9], // cyan
- ], []);
-
- useFrame(({ clock }) => {
- const t = clock.getElapsedTime();
- const s = state.current;
-
- const daylight = daylightRef?.current ?? 0;
- const nightFactor = 1 - daylight;
-
- if (!s.active) {
- // Block spawning when daylight > 0.5
- if (t > s.nextSpawn && daylight <= 0.5) {
- // Spawn a new shooting star
- s.active = true;
- s.progress = 0;
- s.speed = 0.6 + Math.random() * 0.8;
- playSfx?.('shootingStar');
- s.length = 6 + Math.random() * 6;
-
- // Random start position in upper sky hemisphere
- const theta = Math.random() * Math.PI * 2;
- const phi = Math.random() * 0.4; // Near top
- const r = 55 + Math.random() * 20;
- s.startPos = [
- r * Math.sin(phi) * Math.cos(theta),
- r * Math.cos(phi) + 10,
- r * Math.sin(phi) * Math.sin(theta),
- ];
-
- // Direction: downward and across
- const dx = (Math.random() - 0.5) * 2;
- const dy = -0.5 - Math.random() * 0.5;
- const dz = (Math.random() - 0.5) * 2;
- const len = Math.sqrt(dx * dx + dy * dy + dz * dz);
- s.direction = [dx / len, dy / len, dz / len];
-
- s.color = colors[Math.floor(Math.random() * colors.length)];
- }
- if (headRef.current) headRef.current.visible = false;
- if (trailRef.current) trailRef.current.visible = false;
- return;
- }
-
- // Advance the star
- s.progress += s.speed * 0.016; // ~60fps delta
-
- if (s.progress > 1.5) {
- // Star has crossed the sky
- s.active = false;
- s.nextSpawn = t + 5 + Math.random() * 15;
- return;
- }
-
- // Current head position
- const totalDist = s.length * 8;
- const headX = s.startPos[0] + s.direction[0] * totalDist * s.progress;
- const headY = s.startPos[1] + s.direction[1] * totalDist * s.progress;
- const headZ = s.startPos[2] + s.direction[2] * totalDist * s.progress;
-
- // Update head glow (scale opacity by nightFactor)
- if (headRef.current) {
- headRef.current.visible = true;
- headRef.current.position.set(headX, headY, headZ);
- headRef.current.material.opacity = Math.min(1, (1 - s.progress) * 2) * nightFactor;
- }
-
- // Update trail geometry
- if (trailRef.current) {
- trailRef.current.visible = true;
- const posAttr = trailRef.current.geometry.attributes.position;
- for (let i = 0; i < trailPoints.segments; i++) {
- const tp = (i / (trailPoints.segments - 1)) * s.length;
- posAttr.array[i * 3] = headX - s.direction[0] * tp;
- posAttr.array[i * 3 + 1] = headY - s.direction[1] * tp;
- posAttr.array[i * 3 + 2] = headZ - s.direction[2] * tp;
- }
- posAttr.needsUpdate = true;
- }
-
- if (matRef.current) {
- matRef.current.uniforms.uColor.value.set(s.color[0], s.color[1], s.color[2]);
- matRef.current.uniforms.uOpacity.value = Math.min(1, (1 - s.progress) * 2.5) * nightFactor;
- }
- });
-
- return (
- <group ref={groupRef}>
- {/* Glowing head */}
- <mesh ref={headRef} visible={false}>
- <sphereGeometry args={[0.15, 8, 8]} />
- <meshBasicMaterial
- color="#ffffff"
- transparent
- opacity={1}
- blending={THREE.AdditiveBlending}
- depthWrite={false}
- />
- </mesh>
-
- {/* Trail line */}
- <line ref={trailRef} visible={false}>
- <bufferGeometry>
- <bufferAttribute
- attach="attributes-position"
- count={trailPoints.segments}
- array={trailPoints.positions}
- itemSize={3}
- />
- <bufferAttribute
- attach="attributes-trailPosition"
- count={trailPoints.segments}
- array={trailPoints.trailPos}
- itemSize={1}
- />
- </bufferGeometry>
- <shaderMaterial
- ref={matRef}
- vertexShader={TRAIL_VERT}
- fragmentShader={TRAIL_FRAG}
- uniforms={{
- uColor: { value: new THREE.Color(1, 1, 1) },
- uOpacity: { value: 1.0 },
- }}
- transparent
- blending={THREE.AdditiveBlending}
- depthWrite={false}
- />
- </line>
- </group>
- );
-}
-
-export default function OpenWorldShootingStars({ playSfx, settings }) {
- const daylightRef = useRef(0);
- const timeOfDay = settings?.timeOfDay ?? 'sunset';
- const skyTheme = settings?.skyTheme ?? 'cyberpunk';
- const preset = getTimeOfDayPreset(timeOfDay, skyTheme);
- const targetDaylight = preset.daylightFactor ?? 0;
-
- useFrame((_, delta) => {
- const lf = Math.min(1, delta * 3);
- daylightRef.current += (targetDaylight - daylightRef.current) * lf;
- });
-
- return (
- <group>
- {/* 3 potential shooting stars, staggered spawn times */}
- <ShootingStar index={0} playSfx={playSfx} daylightRef={daylightRef} />
- <ShootingStar index={1} playSfx={playSfx} daylightRef={daylightRef} />
- <ShootingStar index={2} playSfx={playSfx} daylightRef={daylightRef} />
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldSignalBeacons.jsx b/client/src/components/openworld/OpenWorldSignalBeacons.jsx
deleted file mode 100644
index f16d88e58f..0000000000
--- a/client/src/components/openworld/OpenWorldSignalBeacons.jsx
+++ /dev/null
@@ -1,253 +0,0 @@
-import { useMemo, useRef } from 'react';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { computeDistrictBounds } from '../../utils/openWorldMiniMap';
-import { regionWarpPadPosition } from '../../utils/openWorldRegions';
-import { PIXEL_FONT_URL, openWorldDayMix, openWorldShowDetail, mixHex } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import OpenWorldLabel from './OpenWorldLabel';
-import { PlantCluster } from './OpenWorldNature';
-
-function SignalBeacon({ position, color, label, sublabel, intensity = 1, dayMix = 0 }) {
- const { tintStructure } = useOpenWorldPalette();
- const groupRef = useRef();
- const glowRef = useRef();
- const beamRef = useRef();
-
- useFrame(({ clock }) => {
- const t = clock.getElapsedTime();
- const pulse = 0.7 + ((Math.sin(t * (1.5 + intensity)) + 1) / 2) * 0.8 * intensity;
-
- if (groupRef.current) {
- groupRef.current.position.y = position[1] + Math.sin(t * 0.6 + position[0]) * 0.1;
- }
- if (glowRef.current) {
- glowRef.current.material.opacity = 0.15 * pulse;
- glowRef.current.scale.setScalar(0.9 + pulse * 0.15);
- }
- if (beamRef.current) {
- beamRef.current.material.opacity = Math.min(0.35, 0.08 + pulse * 0.08);
- }
- });
-
- return (
- <group ref={groupRef} position={position}>
- <mesh ref={beamRef} position={[0, 2.8, 0]}>
- <cylinderGeometry args={[0.08, 0.45, 5.5, 12, 1, true]} />
- <meshBasicMaterial color={color} transparent opacity={0.18} side={THREE.DoubleSide} blending={THREE.AdditiveBlending} depthWrite={false} />
- </mesh>
-
- <mesh position={[0, 0.15, 0]}>
- <cylinderGeometry args={[0.35, 0.45, 0.3, 10]} />
- <meshStandardMaterial color={tintStructure('#0a0a18')} emissive={color} emissiveIntensity={0.35 * intensity} />
- </mesh>
-
- <mesh position={[0, 0.42, 0]}>
- <sphereGeometry args={[0.18, 16, 16]} />
- <meshBasicMaterial color={color} transparent opacity={0.95} />
- </mesh>
-
- <mesh ref={glowRef} position={[0, 0.42, 0]}>
- <sphereGeometry args={[0.5, 16, 16]} />
- <meshBasicMaterial color={color} transparent opacity={0.18} blending={THREE.AdditiveBlending} depthWrite={false} />
- </mesh>
-
- <OpenWorldLabel
- position={[0, 5.9, 0]}
- fontSize={0.32}
- color={color}
- dayMix={dayMix}
- anchorX="center"
- anchorY="middle"
- font={PIXEL_FONT_URL}
- >
- {label}
- </OpenWorldLabel>
- {sublabel && (
- <OpenWorldLabel
- position={[0, 5.45, 0]}
- fontSize={0.18}
- color="#cbd5e1"
- dayMix={dayMix}
- anchorX="center"
- anchorY="middle"
- font={PIXEL_FONT_URL}
- maxWidth={6}
- >
- {sublabel}
- </OpenWorldLabel>
- )}
- </group>
- );
-}
-
-function WarpPad({ region, active, detailed, dayMix, onTravel }) {
- const { accent, tintStructure } = useOpenWorldPalette();
- const groupRef = useRef();
- const ringRef = useRef();
- const beamRef = useRef();
- const color = active ? '#fff4d6' : accent;
- const padRadius = active ? 1.8 : 1.55;
- const ringRadius = active ? 1.2 : 1.02;
- const gardenScale = detailed ? 0.66 : 0.38;
- const position = regionWarpPadPosition(region);
-
- useFrame(({ clock }) => {
- if (!position) return;
- const t = clock.getElapsedTime();
- const pulse = 0.72 + (Math.sin(t * 2.2 + region.id.length) + 1) * 0.14;
- if (groupRef.current) groupRef.current.position.y = position[1] + Math.sin(t * 0.8 + region.id.length) * 0.025;
- if (ringRef.current) {
- ringRef.current.rotation.z = t * 0.35;
- ringRef.current.material.opacity = 0.35 + pulse * 0.25;
- }
- if (beamRef.current) beamRef.current.material.opacity = detailed && active ? 0.05 + pulse * 0.07 : 0;
- });
-
- if (!position) return null;
-
- return (
- <group
- ref={groupRef}
- position={position}
- onClick={(event) => {
- event.stopPropagation();
- onTravel?.(region);
- }}
- >
- {/* The pad is always present, including the low tier, because it is an interaction
- surface rather than decoration. The player proximity radius remains larger than
- the disc so it stays easy to use on foot. */}
- <mesh position={[0, 0, 0]}>
- <cylinderGeometry args={[padRadius, padRadius, 0.16, 24]} />
- <meshStandardMaterial color={tintStructure('#13212a')} emissive={color} emissiveIntensity={active ? 1.1 : 0.5} roughness={0.8} metalness={0} />
- </mesh>
- <mesh position={[0, 0.11, 0]}>
- <cylinderGeometry args={[padRadius * 0.58, padRadius * 0.66, 0.05, 6]} />
- <meshStandardMaterial
- color={mixHex(color, '#183246', 0.42)}
- emissive={color}
- emissiveIntensity={active ? 0.75 : 0.3}
- roughness={0.74}
- metalness={0.08}
- />
- </mesh>
- <mesh ref={ringRef} position={[0, 0.1, 0]} rotation={[0, 0, Math.PI / 4]}>
- <torusGeometry args={[ringRadius, 0.07, 8, 4]} />
- <meshBasicMaterial color={color} transparent opacity={0.5} blending={THREE.AdditiveBlending} depthWrite={false} />
- </mesh>
- <mesh position={[0, 0.17, 0]} rotation={[-Math.PI / 2, 0, 0]}>
- <circleGeometry args={[0.18, 6]} />
- <meshBasicMaterial color={color} transparent opacity={0.9} toneMapped={false} />
- </mesh>
- {detailed && active && (
- <mesh ref={beamRef} position={[0, 3.2, 0]}>
- <cylinderGeometry args={[0.08, 0.72, 6.2, 12, 1, true]} />
- <meshBasicMaterial color={color} transparent opacity={0.1} blending={THREE.AdditiveBlending} depthWrite={false} side={THREE.DoubleSide} />
- </mesh>
- )}
- {/* These small planting beds frame the warp pad so the destination reads as a
- place to use, not a random glowing disc dropped onto the lawn. They are detail-tier
- dressing; the pad and label remain available on the low tier as the wayfinding cue. */}
- {detailed && (
- <group>
- <PlantCluster
- position={[padRadius + 0.9, 0, 0.18]}
- scale={gardenScale}
- variant={region.id.length % 3}
- dayMix={dayMix}
- container
- />
- <PlantCluster
- position={[-padRadius - 0.9, 0, 0.18]}
- scale={gardenScale}
- variant={(region.id.length + 1) % 3}
- dayMix={dayMix}
- container
- />
- </group>
- )}
- <OpenWorldLabel
- position={[0, active ? 3.7 : 1.55, 0]}
- fontSize={active ? 0.28 : 0.17}
- color={color}
- dayMix={dayMix}
- anchorX="center"
- anchorY="middle"
- font={PIXEL_FONT_URL}
- >
- {region.label}
- </OpenWorldLabel>
- {detailed && active && (
- <OpenWorldLabel
- position={[0, 3.25, 0]}
- fontSize={0.16}
- color="#d8e5ea"
- dayMix={dayMix}
- anchorX="center"
- anchorY="middle"
- font={PIXEL_FONT_URL}
- >
- F TO WARP
- </OpenWorldLabel>
- )}
- </group>
- );
-}
-
-export default function OpenWorldSignalBeacons({ positions, reviewCounts, instances, settings, activeRegionId, onTravelToRegion, regions = [] }) {
- const dayMix = openWorldDayMix(settings);
- const showDetail = openWorldShowDetail(settings);
- const config = useMemo(() => {
- if (!positions || positions.size === 0) return [];
-
- const bounds = computeDistrictBounds(positions, 'downtown');
- if (!bounds) return [];
- const { minX, maxX, minZ, maxZ } = bounds;
-
- const pending = reviewCounts?.total || 0;
- const alerts = reviewCounts?.alert || 0;
- const peers = instances?.peers || [];
- const onlinePeers = peers.filter(peer => peer.status === 'online').length;
- const totalNodes = 1 + peers.length;
-
- return [
- {
- id: 'review-beacon',
- position: [minX - 6, 0, minZ - 6],
- color: alerts > 0 ? '#f97316' : '#06b6d4',
- label: alerts > 0 ? 'REVIEW PRESSURE' : 'REVIEW HUB',
- sublabel: pending > 0 ? `${pending} pending · ${alerts} alerts` : 'inbox clear',
- intensity: alerts > 0 ? 1.6 : pending > 0 ? 1.1 : 0.7,
- },
- {
- id: 'void-beacon',
- position: [maxX + 8, 0, maxZ + 8],
- color: onlinePeers > 0 ? '#8b5cf6' : '#64748b',
- label: 'INSTANCE MESH',
- sublabel: `${onlinePeers}/${totalNodes} nodes linked`,
- intensity: onlinePeers > 0 ? 1.2 : 0.65,
- }
- ];
- }, [positions, reviewCounts, instances]);
-
- if (config.length === 0 && regions.length === 0) return null;
-
- return (
- <group>
- {config.map(beacon => (
- <SignalBeacon key={beacon.id} {...beacon} dayMix={dayMix} />
- ))}
- {regions.map((region) => (
- <WarpPad
- key={`warp-pad-${region.id}`}
- region={region}
- active={region.id === activeRegionId}
- detailed={showDetail}
- dayMix={dayMix}
- onTravel={onTravelToRegion}
- />
- ))}
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldSky.jsx b/client/src/components/openworld/OpenWorldSky.jsx
deleted file mode 100644
index e4879bbf1d..0000000000
--- a/client/src/components/openworld/OpenWorldSky.jsx
+++ /dev/null
@@ -1,343 +0,0 @@
-import { useRef, useMemo } from 'react';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { getTimeOfDayPreset, tintTowardAccent } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-
-const SUN_RADIUS = 100;
-
-// Compute sun/moon position from hour (0-24) along a proper overhead arc
-// 6h = east horizon, 12h = high overhead, 18h = west horizon, 0h = below (north)
-const getArcPosition = (hour) => {
- // Normalize hour to 0-2PI, where 6h=0 (sunrise east), 12h=PI/2 (overhead), 18h=PI (sunset west)
- const t = ((hour - 6) / 24) * Math.PI * 2;
- // Elevation: sin curve, peaks at noon (t=PI/2), dips below at midnight
- const elevation = Math.sin(t);
- // Azimuth: sweeps from east(0) through south(PI/2) to west(PI) to north
- const azimuth = t;
- const y = elevation * SUN_RADIUS;
- const horizontalR = Math.cos(Math.asin(Math.min(1, Math.max(-1, elevation)))) * SUN_RADIUS;
- const x = Math.cos(azimuth) * horizontalR;
- const z = -Math.sin(azimuth) * horizontalR;
- return [x, y, z];
-};
-
-// Sky dome gradient shader (inverted sphere)
-const SkyDomeShader = {
- vertexShader: `
- varying vec3 vWorldPosition;
- void main() {
- vec4 worldPos = modelMatrix * vec4(position, 1.0);
- vWorldPosition = worldPos.xyz;
- gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
- }
- `,
- fragmentShader: `
- uniform vec3 uZenith;
- uniform vec3 uMidSky;
- uniform vec3 uHorizonHigh;
- uniform vec3 uHorizonLow;
- uniform vec3 uBelowHorizon;
- uniform vec3 uSunDirection;
- uniform float uSunIntensity;
- uniform float uIsMoon;
- uniform float uOpacity;
- uniform float uTime;
- varying vec3 vWorldPosition;
-
- float hash(vec2 p) {
- return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
- }
- float noise(vec2 p) {
- vec2 i = floor(p);
- vec2 f = fract(p);
- f = f * f * (3.0 - 2.0 * f);
- float a = hash(i);
- float b = hash(i + vec2(1.0, 0.0));
- float c = hash(i + vec2(0.0, 1.0));
- float d = hash(i + vec2(1.0, 1.0));
- return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
- }
-
- void main() {
- vec3 dir = normalize(vWorldPosition);
- float h = max(dir.y, 0.0);
-
- // Base gradient bands
- vec3 color = uHorizonLow;
- color = mix(color, uHorizonHigh, smoothstep(0.0, 0.08, h));
- color = mix(color, uMidSky, smoothstep(0.05, 0.25, h));
- color = mix(color, uZenith, smoothstep(0.2, 0.6, h));
-
- // Glow around sun/moon
- float bodyDot = max(dot(dir, normalize(uSunDirection)), 0.0);
-
- if (uIsMoon < 0.5) {
- // Sun: warm orange/red glow
- float sunGlow = pow(bodyDot, 8.0) * 0.4 * uSunIntensity;
- color += vec3(1.0, 0.3, 0.15) * sunGlow;
- float warmWash = pow(bodyDot, 3.0) * 0.15 * uSunIntensity;
- color += vec3(0.8, 0.2, 0.3) * warmWash;
- } else {
- // Moon: cool silver/blue glow
- float moonGlow = pow(bodyDot, 12.0) * 0.3 * uSunIntensity;
- color += vec3(0.6, 0.65, 0.9) * moonGlow;
- float coolWash = pow(bodyDot, 4.0) * 0.08 * uSunIntensity;
- color += vec3(0.3, 0.35, 0.6) * coolWash;
- }
-
- // Subtle noise ripple
- float n = noise(dir.xz * 3.0 + uTime * 0.02) * 0.03;
- color += n;
-
- // Below horizon: fade to dark. smoothstep requires edge0 < edge1;
- // reverse the result instead of reversing the edges, which is undefined
- // in GLSL and can blow the sky out on some WebGL implementations.
- float belowFade = 1.0 - smoothstep(-0.05, 0.0, dir.y);
- color = mix(color, uBelowHorizon, belowFade);
-
- gl_FragColor = vec4(color, uOpacity);
- }
- `,
-};
-
-// Lerp THREE.Color in place
-const lerpColor = (target, a, b, t) => {
- target.r = a.r + (b.r - a.r) * t;
- target.g = a.g + (b.g - a.g) * t;
- target.b = a.b + (b.b - a.b) * t;
-};
-
-// Pre-allocate parsed preset colors (keyed by "theme:timeOfDay:accent"). The upper
-// sky bands (zenith, midSky) are tinted toward the active theme accent so the sky
-// tracks the theme; horizon haze + sun colors stay physical/untinted. The accent is
-// in the cache key so a theme switch re-derives instead of serving a stale tint.
-// Reused scratch vector for the per-frame sun direction — avoids allocating a
-// fresh THREE.Vector3 every frame (~60/sec) inside the useFrame loop below.
-const sunDirScratch = new THREE.Vector3();
-
-const presetColors = {};
-const getPresetColors = (name, skyTheme, accent) => {
- const cacheKey = `${skyTheme}:${name}:${accent}`;
- if (!presetColors[cacheKey]) {
- const p = getTimeOfDayPreset(name, skyTheme);
- const isBrightDay = (p.daylightFactor ?? 0) >= 0.75;
- const belowHorizon = isBrightDay ? p.horizonLow : '#03030a';
- presetColors[cacheKey] = {
- zenith: new THREE.Color(tintTowardAccent(p.zenith, 0.16, accent)),
- midSky: new THREE.Color(tintTowardAccent(p.midSky, 0.12, accent)),
- horizonHigh: new THREE.Color(p.horizonHigh),
- horizonLow: new THREE.Color(p.horizonLow),
- belowHorizon: new THREE.Color(belowHorizon),
- sunCore: new THREE.Color(p.sunCore),
- sunGlow: new THREE.Color(p.sunGlow),
- sunLight: new THREE.Color(p.sunLight),
- hour: p.hour,
- sunIntensity: p.sunIntensity,
- // Day is the gradient sky. Night is the bundled galaxy map, so the shader
- // dome gets out of the way and only the moon/light meshes remain.
- overlayOpacity: isBrightDay ? 1.0 : 0.0,
- sunScale: p.sunScale,
- isMoon: p.isMoon,
- };
- }
- return presetColors[cacheKey];
-};
-
-// Sun/Moon mesh
-function CelestialBody({ groupRef }) {
- const bodyRef = useRef();
- const haloRef = useRef();
-
- useFrame(({ clock }) => {
- if (!bodyRef.current) return;
- const t = clock.getElapsedTime();
- const pulse = 1.0 + Math.sin(t * 0.5) * 0.08;
- bodyRef.current.material.emissiveIntensity = 0.45 * pulse;
- if (haloRef.current) {
- haloRef.current.material.opacity = 0.035 + Math.sin(t * 0.3) * 0.012;
- }
- });
-
- return (
- <group ref={groupRef}>
- <mesh ref={bodyRef}>
- <sphereGeometry args={[2.2, 24, 24]} />
- <meshStandardMaterial
- color="#ffaa44"
- emissive="#ffaa44"
- emissiveIntensity={0.45}
- toneMapped
- />
- </mesh>
- <mesh ref={haloRef}>
- <ringGeometry args={[3, 7, 32]} />
- <meshBasicMaterial
- color="#ff6080"
- transparent
- opacity={0.035}
- side={THREE.DoubleSide}
- blending={THREE.AdditiveBlending}
- depthWrite={false}
- />
- </mesh>
- </group>
- );
-}
-
-export default function OpenWorldSky({ settings }) {
- // The upper sky bands are tinted toward the theme accent. Mirror it into a ref so
- // the useFrame loop reads the current accent without re-subscribing each frame.
- const { accent } = useOpenWorldPalette();
- const accentRef = useRef(accent);
- accentRef.current = accent;
-
- const brightnessRef = useRef(settings?.ambientBrightness ?? 1.2);
- brightnessRef.current = settings?.ambientBrightness ?? 1.2;
-
- const timeOfDayRef = useRef(settings?.timeOfDay ?? 'sunset');
- timeOfDayRef.current = settings?.timeOfDay ?? 'sunset';
-
- const skyThemeRef = useRef(settings?.skyTheme ?? 'cyberpunk');
- const previousSkyThemeRef = useRef(skyThemeRef.current);
-
- const currentPresetRef = useRef(timeOfDayRef.current);
- const transitionRef = useRef(1.0);
-
- const nextSkyTheme = settings?.skyTheme ?? 'cyberpunk';
- if (previousSkyThemeRef.current !== nextSkyTheme) {
- previousSkyThemeRef.current = nextSkyTheme;
- skyThemeRef.current = nextSkyTheme;
- transitionRef.current = 0;
- } else {
- skyThemeRef.current = nextSkyTheme;
- }
-
- const bodyGroupRef = useRef();
- const lightRef = useRef();
- const currentScaleRef = useRef(1.0);
- const initialPreset = getTimeOfDayPreset(settings?.timeOfDay ?? 'sunset', settings?.skyTheme ?? 'cyberpunk');
- const currentHourRef = useRef(initialPreset.hour ?? 18);
-
- const skyMaterial = useMemo(() => {
- const initialTheme = skyThemeRef.current;
- const initialTod = timeOfDayRef.current;
- const initialHour = getTimeOfDayPreset(initialTod, initialTheme).hour ?? 18;
- const preset = getPresetColors(initialTod, initialTheme, accentRef.current);
- const initPos = getArcPosition(initialHour);
- return new THREE.ShaderMaterial({
- vertexShader: SkyDomeShader.vertexShader,
- fragmentShader: SkyDomeShader.fragmentShader,
- uniforms: {
- uZenith: { value: preset.zenith.clone() },
- uMidSky: { value: preset.midSky.clone() },
- uHorizonHigh: { value: preset.horizonHigh.clone() },
- uHorizonLow: { value: preset.horizonLow.clone() },
- uBelowHorizon: { value: preset.belowHorizon.clone() },
- uSunDirection: { value: new THREE.Vector3(...initPos).normalize() },
- uSunIntensity: { value: preset.sunIntensity },
- uIsMoon: { value: preset.isMoon ? 1.0 : 0.0 },
- uOpacity: { value: preset.overlayOpacity },
- uTime: { value: 0 },
- },
- side: THREE.BackSide,
- transparent: preset.overlayOpacity < 0.999,
- opacity: preset.overlayOpacity,
- blending: THREE.NormalBlending,
- depthWrite: false,
- });
- }, []);
-
- useFrame(({ clock }, delta) => {
- const target = timeOfDayRef.current;
- const brightness = brightnessRef.current;
-
- if (currentPresetRef.current !== target) {
- currentPresetRef.current = target;
- transitionRef.current = 0;
- }
-
- transitionRef.current = Math.min(1.0, transitionRef.current + delta * 1.5);
- const lerpFactor = transitionRef.current < 1 ? delta * 3 : 1;
-
- const preset = getPresetColors(target, skyThemeRef.current, accentRef.current);
-
- // Lerp hour along shortest path on the 24h clock
- let hourDiff = preset.hour - currentHourRef.current;
- if (hourDiff > 12) hourDiff -= 24;
- if (hourDiff < -12) hourDiff += 24;
- currentHourRef.current += hourDiff * lerpFactor;
- // Wrap to 0-24
- if (currentHourRef.current < 0) currentHourRef.current += 24;
- if (currentHourRef.current >= 24) currentHourRef.current -= 24;
-
- // Compute sun position from current hour on the arc
- const bodyPos = getArcPosition(currentHourRef.current);
- const bodyDir = sunDirScratch.set(bodyPos[0], bodyPos[1], bodyPos[2]).normalize();
-
- // Lerp sky dome colors
- lerpColor(skyMaterial.uniforms.uZenith.value, skyMaterial.uniforms.uZenith.value, preset.zenith, lerpFactor);
- lerpColor(skyMaterial.uniforms.uMidSky.value, skyMaterial.uniforms.uMidSky.value, preset.midSky, lerpFactor);
- lerpColor(skyMaterial.uniforms.uHorizonHigh.value, skyMaterial.uniforms.uHorizonHigh.value, preset.horizonHigh, lerpFactor);
- lerpColor(skyMaterial.uniforms.uHorizonLow.value, skyMaterial.uniforms.uHorizonLow.value, preset.horizonLow, lerpFactor);
- lerpColor(skyMaterial.uniforms.uBelowHorizon.value, skyMaterial.uniforms.uBelowHorizon.value, preset.belowHorizon, lerpFactor);
-
- // Update sun direction directly from arc position
- skyMaterial.uniforms.uSunDirection.value.copy(bodyDir);
- skyMaterial.uniforms.uSunIntensity.value += (preset.sunIntensity - skyMaterial.uniforms.uSunIntensity.value) * lerpFactor;
- skyMaterial.uniforms.uIsMoon.value += ((preset.isMoon ? 1.0 : 0.0) - skyMaterial.uniforms.uIsMoon.value) * lerpFactor;
- skyMaterial.uniforms.uOpacity.value += (preset.overlayOpacity - skyMaterial.uniforms.uOpacity.value) * lerpFactor;
- skyMaterial.opacity = skyMaterial.uniforms.uOpacity.value;
- const shouldBeTransparent = skyMaterial.opacity < 0.999;
- if (skyMaterial.transparent !== shouldBeTransparent) {
- skyMaterial.transparent = shouldBeTransparent;
- skyMaterial.needsUpdate = true;
- }
- skyMaterial.uniforms.uTime.value = clock.getElapsedTime();
-
- // Move celestial body mesh
- if (bodyGroupRef.current) {
- const sp = bodyGroupRef.current.position;
- sp.set(bodyPos[0], bodyPos[1], bodyPos[2]);
-
- currentScaleRef.current += (preset.sunScale - currentScaleRef.current) * lerpFactor;
- const s = currentScaleRef.current;
- bodyGroupRef.current.scale.set(s, s, s);
-
- const bodyMesh = bodyGroupRef.current.children[0];
- const haloMesh = bodyGroupRef.current.children[1];
- if (bodyMesh?.material) {
- bodyMesh.material.color.lerp(preset.sunCore, lerpFactor);
- bodyMesh.material.emissive.lerp(preset.sunCore, lerpFactor);
- }
- if (haloMesh?.material) {
- haloMesh.material.color.lerp(preset.sunGlow, lerpFactor);
- }
- }
-
- // Directional light follows body
- if (lightRef.current) {
- lightRef.current.position.set(bodyPos[0], bodyPos[1], bodyPos[2]);
- lightRef.current.intensity += (preset.sunIntensity * brightness - lightRef.current.intensity) * lerpFactor;
- lightRef.current.color.lerp(preset.sunLight, lerpFactor);
- }
- });
-
- return (
- <group>
- {/* Dome radius must exceed the OpenWorldLandscape mountain ring (~1210 max extent)
- so the horizon mountains sit INSIDE the dome and aren't occluded by the
- opaque daytime sky. Kept under the camera far plane (2000). */}
- <mesh material={skyMaterial} renderOrder={-1000}>
- <sphereGeometry args={[1600, 32, 32]} />
- </mesh>
- <CelestialBody groupRef={bodyGroupRef} />
- <directionalLight
- ref={lightRef}
- position={[-60, 5, -80]}
- intensity={0.6}
- color="#ffccaa"
- />
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldSkyline.jsx b/client/src/components/openworld/OpenWorldSkyline.jsx
deleted file mode 100644
index 81dc3feb09..0000000000
--- a/client/src/components/openworld/OpenWorldSkyline.jsx
+++ /dev/null
@@ -1,150 +0,0 @@
-import { useMemo } from 'react';
-import * as THREE from 'three';
-import { openWorldDayMix, seededRand } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import { isInWater } from '../../utils/openWorldPlan';
-
-// Distant cyberpunk skyline silhouettes with neon trim
-// Creates a ring of faint skyscraper outlines around the city perimeter
-
-const SKYLINE_VERT = `
- varying vec2 vUv;
- varying float vHeight;
- void main() {
- vUv = uv;
- vHeight = position.y;
- gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
- }
-`;
-
-const SKYLINE_FRAG = `
- uniform vec3 uColor;
- uniform vec3 uAccent;
- uniform float uMaxHeight;
- uniform float uDayMix;
- varying vec2 vUv;
- varying float vHeight;
- void main() {
- // Dark body that fades near top
- float bodyAlpha = mix(0.15, 0.035, uDayMix) * (1.0 - vUv.y * 0.5);
-
- // Window dots - grid of small lit windows
- float cellX = fract(vUv.x * 8.0);
- float cellY = fract(vUv.y * 20.0);
- float window = step(0.3, cellX) * step(cellX, 0.7) * step(0.3, cellY) * step(cellY, 0.65);
-
- // Only some windows lit (pseudo-random via position)
- float lit = step(0.55, fract(sin(floor(vUv.x * 8.0) * 127.1 + floor(vUv.y * 20.0) * 311.7) * 43758.5453));
- window *= lit;
-
- vec3 nightBase = vec3(0.02, 0.02, 0.05);
- vec3 dayBase = vec3(0.58, 0.70, 0.78);
- vec3 color = mix(nightBase, dayBase, uDayMix);
- color = mix(color, uAccent, window * mix(0.5, 0.15, uDayMix));
- float alpha = bodyAlpha + window * mix(0.15, 0.035, uDayMix);
-
- // Neon trim at top edge
- float topLine = smoothstep(0.98, 1.0, vUv.y);
- color = mix(color, uAccent, topLine);
- alpha = max(alpha, topLine * mix(0.4, 0.12, uDayMix));
-
- // Neon trim at bottom
- float bottomLine = smoothstep(0.02, 0.0, vUv.y);
- color = mix(color, uColor, bottomLine);
- alpha = max(alpha, bottomLine * mix(0.3, 0.08, uDayMix));
-
- // Fade with distance (atmospheric perspective)
- alpha *= 0.7;
-
- gl_FragColor = vec4(color, alpha);
- }
-`;
-
-// Create a single skyline building silhouette
-function DistantBuilding({ position, width, height, color, accent, dayMix }) {
- const colorVec = useMemo(() => new THREE.Color(color), [color]);
- const accentVec = useMemo(() => new THREE.Color(accent), [accent]);
-
- return (
- <mesh position={[position[0], height / 2, position[2]]}>
- <boxGeometry args={[width, height, width * 0.3]} />
- <shaderMaterial
- vertexShader={SKYLINE_VERT}
- fragmentShader={SKYLINE_FRAG}
- uniforms={{
- uColor: { value: colorVec },
- uAccent: { value: accentVec },
- uMaxHeight: { value: height },
- uDayMix: { value: dayMix },
- }}
- transparent
- side={THREE.DoubleSide}
- depthWrite={false}
- />
- </mesh>
- );
-}
-
-export default function OpenWorldSkyline({ settings }) {
- const { lowPoly } = useOpenWorldPalette();
- const dayMix = openWorldDayMix(settings);
- const buildings = useMemo(() => {
- const result = [];
- const colors = ['#06b6d4', '#ec4899', '#8b5cf6', '#3b82f6', '#22c55e', '#f97316'];
- const accents = ['#06b6d4', '#ec4899', '#8b5cf6', '#3b82f6', '#f43f5e', '#a855f7'];
-
- // Seeded random for consistent skyline
- const rand = seededRand(42);
-
- const radius = 55;
- const count = 60;
-
- for (let i = 0; i < count; i++) {
- const angle = (i / count) * Math.PI * 2 + rand() * 0.1;
- const r = radius + rand() * 15 - 7;
- const x = Math.cos(angle) * r;
- const z = Math.sin(angle) * r;
-
- const bWidth = 1.5 + rand() * 4;
- const bHeight = 5 + rand() * 25;
- const colorIdx = Math.floor(rand() * colors.length);
-
- // The north arc of the ring lands in the bay — no silhouette stands in the water.
- // The harbor piers and the federation peers across the bay own that horizon.
- // (rand() calls above stay unconditional so the rest of the ring keeps its layout.)
- if (isInWater(x, z, 4)) continue;
-
- result.push({
- id: `skyline-${i}`,
- position: [x, 0, z],
- width: bWidth,
- height: bHeight,
- color: colors[colorIdx],
- accent: accents[colorIdx],
- });
- }
-
- return result;
- }, []);
-
- // The Vibes world uses the low-poly hill ring as its horizon. The old translucent
- // cyber skyline reads as floating glass slabs against the clean landscape, so keep
- // that silhouette layer exclusive to the cyber art direction.
- if (lowPoly) return null;
-
- return (
- <group>
- {buildings.map(b => (
- <DistantBuilding
- key={b.id}
- position={b.position}
- width={b.width}
- height={b.height}
- color={b.color}
- accent={b.accent}
- dayMix={dayMix}
- />
- ))}
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldSpeedPads.jsx b/client/src/components/openworld/OpenWorldSpeedPads.jsx
deleted file mode 100644
index a005f9a4df..0000000000
--- a/client/src/components/openworld/OpenWorldSpeedPads.jsx
+++ /dev/null
@@ -1,66 +0,0 @@
-import { useMemo, useRef } from 'react';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { getSpeedPadsList } from '../../utils/openWorldSpeedPads';
-import { openWorldTerrainHeight } from '../../utils/openWorldPlan';
-
-function SpeedPad({ pad, animate }) {
- const { x, z, angle, width, length, color } = pad;
- const chevronsRef = useRef();
-
- useFrame(({ clock }) => {
- if (!animate || !chevronsRef.current) return;
- const t = clock.getElapsedTime();
- // A soft traveling paint shimmer makes the boost readable without a neon plate.
- chevronsRef.current.children.forEach((mesh, index) => {
- if (!mesh?.material) return;
- const phase = (t * 3.5 - index * 0.4) % Math.PI;
- const intensity = Math.sin(Math.max(0, phase));
- mesh.material.opacity = 0.5 + intensity * 0.35;
- });
- });
-
- return (
- <group position={[x, openWorldTerrainHeight(x, z) + 0.07, z]} rotation={[0, angle, 0]}>
- <mesh rotation={[-Math.PI / 2, 0, 0]} receiveShadow>
- <planeGeometry args={[length, width]} />
- <meshStandardMaterial
- color="#d8bc7d"
- emissive={color}
- emissiveIntensity={0.06}
- roughness={0.96}
- metalness={0}
- />
- </mesh>
-
- {/* Three hand-painted arrows point along the lane. */}
- <group ref={chevronsRef} position={[0, 0.01, 0]}>
- {[-1.25, 0, 1.25].map((offsetX, idx) => (
- <mesh key={idx} position={[offsetX, 0, 0]} rotation={[-Math.PI / 2, 0, -Math.PI / 2]}>
- <coneGeometry args={[0.62, 0.82, 3]} />
- <meshBasicMaterial
- color={color}
- transparent
- opacity={0.72}
- depthWrite={false}
- side={THREE.DoubleSide}
- />
- </mesh>
- ))}
- </group>
- </group>
- );
-}
-
-export default function OpenWorldSpeedPads({ settings }) {
- const pads = useMemo(() => getSpeedPadsList(), []);
- const animate = (settings?.particleDensity ?? 1) >= 0.5;
-
- return (
- <group>
- {pads.map((pad) => (
- <SpeedPad key={pad.id} pad={pad} animate={animate} />
- ))}
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldSpeedometer.jsx b/client/src/components/openworld/OpenWorldSpeedometer.jsx
deleted file mode 100644
index 96e8e5947c..0000000000
--- a/client/src/components/openworld/OpenWorldSpeedometer.jsx
+++ /dev/null
@@ -1,59 +0,0 @@
-import { useMemo } from 'react';
-import { TOTAL_SHARDS } from '../../utils/openWorldCollectibles';
-
-export default function OpenWorldSpeedometer({
- playerPose,
- collectedCount = 0,
- totalShards = TOTAL_SHARDS,
-}) {
- const speed = playerPose?.speed || 0;
- const kmh = Math.round(Math.abs(speed) * 3.6);
- const speedRatio = Math.min(1, Math.abs(speed) / 38);
-
- const modeBadge = useMemo(() => {
- if (playerPose?.airborne) return { label: 'AIRBORNE', color: 'text-purple-400 border-purple-500/40 bg-purple-500/10' };
- if (playerPose?.skid > 0.4 && Math.abs(speed) > 5) return { label: 'DRIFT', color: 'text-amber-400 border-amber-500/40 bg-amber-500/10' };
- if (playerPose?.boosting || Math.abs(speed) > 26) return { label: 'BOOST', color: 'text-cyan-300 border-cyan-400/50 bg-cyan-400/20 animate-pulse' };
- if (speed < -0.2) return { label: 'REVERSE', color: 'text-rose-400 border-rose-500/40 bg-rose-500/10' };
- if (Math.abs(speed) > 0.2) return { label: 'DRIVE', color: 'text-emerald-400 border-emerald-500/40 bg-emerald-500/10' };
- return { label: 'PARK', color: 'text-slate-400 border-slate-500/30 bg-slate-500/10' };
- }, [playerPose, speed]);
-
- return (
- <div className="openworld-hud-panel px-3.5 py-2 flex items-center gap-3.5 select-none pointer-events-auto">
- {/* Speedometer Digital Readout */}
- <div className="flex flex-col items-start min-w-[3.6rem]">
- <div className="flex items-baseline gap-1">
- <span className="font-pixel text-lg font-bold tracking-tight text-[rgb(var(--port-text))]">
- {kmh}
- </span>
- <span className="font-pixel text-[8px] text-[rgb(var(--port-text-muted))]">
- KM/H
- </span>
- </div>
- {/* Speed Bar Gauge */}
- <div className="w-full h-1 bg-[rgb(var(--port-accent)/.15)] rounded-full overflow-hidden mt-0.5">
- <div
- className="h-full bg-[rgb(var(--port-accent))] transition-all duration-75 rounded-full"
- style={{ width: `${Math.round(speedRatio * 100)}%` }}
- />
- </div>
- </div>
-
- {/* Drive Mode Pill */}
- <span
- className={`font-pixel text-[8px] px-2 py-0.5 rounded-md border tracking-wider uppercase ${modeBadge.color}`}
- >
- {modeBadge.label}
- </span>
-
- {/* Cyber Shards Counter */}
- <div className="flex items-center gap-1.5 px-2 py-0.5 rounded-md bg-[rgb(var(--port-accent)/.08)] border border-[rgb(var(--port-accent)/.2)]">
- <span className="font-pixel text-[10px] text-cyan-400">⯁</span>
- <span className="font-pixel text-[8px] tracking-wider text-[rgb(var(--port-text))]">
- {collectedCount}/{totalShards}
- </span>
- </div>
- </div>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldSpeedometer.test.jsx b/client/src/components/openworld/OpenWorldSpeedometer.test.jsx
deleted file mode 100644
index 9fa9067078..0000000000
--- a/client/src/components/openworld/OpenWorldSpeedometer.test.jsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import { render, screen } from '@testing-library/react';
-import OpenWorldSpeedometer from './OpenWorldSpeedometer';
-
-describe('OpenWorldSpeedometer', () => {
- it('renders stationary parked state by default', () => {
- render(<OpenWorldSpeedometer playerPose={{ speed: 0 }} collectedCount={3} totalShards={18} />);
- expect(screen.getByText('0')).toBeDefined();
- expect(screen.getByText('KM/H')).toBeDefined();
- expect(screen.getByText('PARK')).toBeDefined();
- expect(screen.getByText('3/18')).toBeDefined();
- });
-
- it('renders driving speed and mode badge when moving forward', () => {
- render(<OpenWorldSpeedometer playerPose={{ speed: 10 }} collectedCount={5} totalShards={18} />);
- // 10 units/s * 3.6 = 36 km/h
- expect(screen.getByText('36')).toBeDefined();
- expect(screen.getByText('DRIVE')).toBeDefined();
- });
-
- it('renders BOOST mode when sprinting or high speed', () => {
- render(<OpenWorldSpeedometer playerPose={{ speed: 30, boosting: true }} collectedCount={8} totalShards={18} />);
- expect(screen.getByText('BOOST')).toBeDefined();
- });
-
- it('renders DRIFT badge when skidding', () => {
- render(<OpenWorldSpeedometer playerPose={{ speed: 12, skid: 0.6 }} collectedCount={2} totalShards={18} />);
- expect(screen.getByText('DRIFT')).toBeDefined();
- });
-
- it('renders AIRBORNE badge when in flight', () => {
- render(<OpenWorldSpeedometer playerPose={{ speed: 10, airborne: true }} collectedCount={4} totalShards={18} />);
- expect(screen.getByText('AIRBORNE')).toBeDefined();
- });
-});
diff --git a/client/src/components/openworld/OpenWorldStarfield.jsx b/client/src/components/openworld/OpenWorldStarfield.jsx
deleted file mode 100644
index bb82a16587..0000000000
--- a/client/src/components/openworld/OpenWorldStarfield.jsx
+++ /dev/null
@@ -1,122 +0,0 @@
-import { useRef, useMemo } from 'react';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { getTimeOfDayPreset } from './openWorldConstants';
-
-const STAR_VERT = `
- attribute float size;
- attribute float phase;
- attribute vec3 starColor;
- varying float vPhase;
- varying vec3 vColor;
- uniform float uTime;
- void main() {
- vPhase = phase;
- vColor = starColor;
- vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
- gl_PointSize = size * (200.0 / -mvPosition.z);
- gl_Position = projectionMatrix * mvPosition;
- }
-`;
-
-const STAR_FRAG = `
- varying float vPhase;
- varying vec3 vColor;
- uniform float uTime;
- uniform float uDaylight;
- void main() {
- // Soft circular point
- float d = length(gl_PointCoord - vec2(0.5));
- if (d > 0.5) discard;
- float alpha = smoothstep(0.5, 0.15, d);
- // Twinkle: slow shimmer unique per star
- float twinkle = 0.7 + 0.3 * sin(uTime * (0.4 + vPhase * 0.6) + vPhase * 6.2831);
- // Fade out during daytime
- float nightFactor = 1.0 - uDaylight;
- gl_FragColor = vec4(vColor, alpha * twinkle * nightFactor);
- }
-`;
-
-export default function OpenWorldStarfield({ settings }) {
- const pointsRef = useRef();
- const matRef = useRef();
- const daylightRef = useRef(0);
-
- const { positions, sizes, phases, colors } = useMemo(() => {
- const count = 1500;
- const pos = new Float32Array(count * 3);
- const sz = new Float32Array(count);
- const ph = new Float32Array(count);
- const col = new Float32Array(count * 3);
-
- // Star color palette: white, blue-white, warm-white, cyan-tinted
- const palette = [
- [1.0, 1.0, 1.0],
- [0.8, 0.85, 1.0],
- [1.0, 0.95, 0.85],
- [0.75, 0.9, 1.0],
- [0.85, 0.8, 1.0],
- ];
-
- for (let i = 0; i < count; i++) {
- const theta = Math.random() * Math.PI * 2;
- const phi = Math.random() * Math.PI * 0.5; // Upper hemisphere
- const r = 60 + Math.random() * 50;
-
- pos[i * 3] = r * Math.sin(phi) * Math.cos(theta);
- pos[i * 3 + 1] = r * Math.cos(phi) + 8;
- pos[i * 3 + 2] = r * Math.sin(phi) * Math.sin(theta);
-
- // Most stars small, a few bright ones
- const bright = Math.random();
- sz[i] = bright < 0.05 ? 2.0 + Math.random() * 1.5 : 0.4 + Math.random() * 1.0;
-
- ph[i] = Math.random(); // Unique twinkle phase
-
- const c = palette[Math.floor(Math.random() * palette.length)];
- col[i * 3] = c[0];
- col[i * 3 + 1] = c[1];
- col[i * 3 + 2] = c[2];
- }
-
- return { positions: pos, sizes: sz, phases: ph, colors: col };
- }, []);
-
- const timeOfDay = settings?.timeOfDay ?? 'sunset';
- const skyTheme = settings?.skyTheme ?? 'cyberpunk';
- const preset = getTimeOfDayPreset(timeOfDay, skyTheme);
- const targetDaylight = preset.daylightFactor ?? 0;
-
- useFrame(({ clock }, delta) => {
- if (!pointsRef.current) return;
- pointsRef.current.rotation.y = clock.getElapsedTime() * 0.003;
- // Lerp daylight uniform toward target
- const lf = Math.min(1, delta * 3);
- daylightRef.current += (targetDaylight - daylightRef.current) * lf;
- if (matRef.current) {
- matRef.current.uniforms.uTime.value = clock.getElapsedTime();
- matRef.current.uniforms.uDaylight.value = daylightRef.current;
- }
- });
-
- return (
- <points ref={pointsRef}>
- <bufferGeometry>
- <bufferAttribute attach="attributes-position" count={positions.length / 3} array={positions} itemSize={3} />
- <bufferAttribute attach="attributes-size" count={sizes.length} array={sizes} itemSize={1} />
- <bufferAttribute attach="attributes-phase" count={phases.length} array={phases} itemSize={1} />
- <bufferAttribute attach="attributes-starColor" count={colors.length / 3} array={colors} itemSize={3} />
- </bufferGeometry>
- <shaderMaterial
- ref={matRef}
- vertexShader={STAR_VERT}
- fragmentShader={STAR_FRAG}
- uniforms={{ uTime: { value: 0 }, uDaylight: { value: 0 } }}
- transparent
- blending={THREE.AdditiveBlending}
- depthWrite={false}
- fog={false}
- />
- </points>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldStreetProps.jsx b/client/src/components/openworld/OpenWorldStreetProps.jsx
deleted file mode 100644
index 40dc8efc57..0000000000
--- a/client/src/components/openworld/OpenWorldStreetProps.jsx
+++ /dev/null
@@ -1,174 +0,0 @@
-import { useMemo, useLayoutEffect, useRef } from 'react';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { openWorldDayMix, openWorldShowDetail, mixHex } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import { computeStreets, computeStreetProps } from '../../utils/openWorldPlan';
-
-// Street furniture from the master plan: lamp posts pooling light along every street and
-// planting trees ringing the AI Core plaza. Everything is instanced, so lamp count does not
-// multiply the scene's draw calls. Lamp light pools are faked with emissive heads + additive
-// ground discs (the city's established no-real-point-lights pattern).
-// The Vibes silhouettes remain on the low tier; Cyber keeps the older detail gate because its
-// neon dressing is much heavier and the grove is already enough orientation at that tier.
-
-const dummy = new THREE.Object3D();
-const swayTimeUniform = { value: 0 };
-
-// Module-scope position offsets — stable identities so the matrix-writing effect below
-// runs only when placements actually change, not on every parent re-render.
-const POLE_POS = [0, 1.7, 0];
-const HEAD_POS = [0, 3.45, 0];
-const HEAD_CORE_POS = [0, 3.45, 0];
-const HEAD_CAP_POS = [0, 3.75, 0];
-const POOL_POS = [0, 0.035, 0];
-const TRUNK_POS = [0, 0.55, 0];
-const CANOPY_POS = [0, 1.55, 0];
-const CANOPY_TOP_POS = [0, 2.12, 0, 0.72];
-
-// One instanced mesh whose matrices are written once from `placements`. `flat` lays the
-// geometry into the ground plane (used by the light-pool discs).
-function writeMatrices(ref, placements, position, flat) {
- if (!ref.current || typeof ref.current.setMatrixAt !== 'function') return;
- const scaleMultiplier = position[3] ?? 1;
- placements.forEach((p, i) => {
- dummy.position.set(p.x + position[0], position[1], p.z + position[2]);
- dummy.rotation.set(flat ? -Math.PI / 2 : 0, !flat && p.seed != null ? (p.seed * 1.7) % (Math.PI * 2) : 0, 0);
- dummy.scale.setScalar((p.scale ?? 1) * scaleMultiplier);
- dummy.updateMatrix();
- ref.current.setMatrixAt(i, dummy.matrix);
- });
- if (ref.current.instanceMatrix) {
- ref.current.instanceMatrix.needsUpdate = true;
- }
- if (typeof ref.current.computeBoundingSphere === 'function') {
- ref.current.computeBoundingSphere();
- }
-}
-
-const onSwayCompile = (shader) => {
- shader.uniforms.uSwayTime = swayTimeUniform;
- shader.vertexShader = `
- uniform float uSwayTime;
- ` + shader.vertexShader;
- shader.vertexShader = shader.vertexShader.replace(
- '#include <begin_vertex>',
- `
- #include <begin_vertex>
- vec3 instPos = vec3(instanceMatrix[3][0], instanceMatrix[3][1], instanceMatrix[3][2]);
- float gust = sin(uSwayTime * 0.72 + instPos.x * 0.04 + instPos.z * 0.03) * 0.045
- + sin(uSwayTime * 1.21 + instPos.z * 0.08) * 0.02;
- transformed.x += gust * (position.y + 0.8);
- transformed.z += gust * 0.8 * (position.y + 0.8);
- `
- );
-};
-
-function Instances({ placements, geometry, geometryArgs, position, flat = false, children }) {
- const ref = useRef();
- useLayoutEffect(() => {
- writeMatrices(ref, placements, position, flat);
- }, [placements, position, flat]);
-
- return (
- <instancedMesh ref={ref} args={[undefined, undefined, placements.length]}>
- {geometry === 'cylinder' && <cylinderGeometry args={geometryArgs} />}
- {geometry === 'sphere' && <sphereGeometry args={geometryArgs} />}
- {geometry === 'circle' && <circleGeometry args={geometryArgs} />}
- {geometry === 'icosahedron' && <icosahedronGeometry args={geometryArgs} />}
- {geometry === 'box' && <boxGeometry args={geometryArgs} />}
- {children}
- </instancedMesh>
- );
-}
-
-export default function OpenWorldStreetProps({ settings }) {
- const { accent, tintStructure, lowPoly, surface } = useOpenWorldPalette();
- const dayMix = openWorldDayMix(settings);
- const density = settings?.particleDensity ?? 1;
-
- const props = useMemo(() => {
- const streets = computeStreets();
- return computeStreetProps(streets, density);
- }, [density]);
-
- useFrame(({ clock }) => {
- swayTimeUniform.value = clock.getElapsedTime();
- });
-
- // Keep the plaza grove even on the low tier: it is cheap, anchors the center of the map,
- // and gives the bright world a sense of scale. Lamps and their additive pools remain detail-only.
- const showLamps = lowPoly || openWorldShowDetail(settings);
- if (!showLamps && props.trees.length === 0) return null;
-
- const lampGlow = mixHex(accent, '#ffe2a6', 0.58);
- const headOpacity = 0.95 * (1 - dayMix) + 0.4 * dayMix; // lamps rest by day
- const poolOpacity = 0.1 * (1 - dayMix); // light pools are a night thing
- const structureColor = lowPoly
- ? mixHex('#3e5a5f', accent, 0.18)
- : tintStructure('#141b2c');
- const foliageColor = mixHex(mixHex('#6fa37f', accent, 0.22), '#d5bd83', dayMix * 0.18);
-
- return (
- <group>
- {showLamps && (
- <>
- {/* Lamp poles */}
- <Instances placements={props.lamps} geometry="cylinder" geometryArgs={[0.05, 0.08, 3.4, 6]} position={POLE_POS}>
- <meshStandardMaterial {...surface} color={structureColor} roughness={0.7} metalness={lowPoly ? 0 : 0.45} />
- </Instances>
- {/* Faceted lantern housings + warm cores: a stronger silhouette than a bare orb,
- while still keeping the city's no-point-light performance budget. */}
- <Instances placements={props.lamps} geometry="box" geometryArgs={[0.48, 0.5, 0.48]} position={HEAD_POS}>
- <meshStandardMaterial {...surface} color={structureColor} roughness={0.65} metalness={lowPoly ? 0 : 0.35} />
- </Instances>
- <Instances placements={props.lamps} geometry="box" geometryArgs={[0.29, 0.31, 0.29]} position={HEAD_CORE_POS}>
- <meshBasicMaterial color={lampGlow} transparent opacity={headOpacity} toneMapped={false} />
- </Instances>
- <Instances placements={props.lamps} geometry="box" geometryArgs={[0.58, 0.07, 0.58]} position={HEAD_CAP_POS}>
- <meshStandardMaterial {...surface} color={structureColor} roughness={0.7} metalness={lowPoly ? 0 : 0.4} />
- </Instances>
- {/* Faked light pools on the pavement */}
- {poolOpacity > 0.005 && (
- <Instances placements={props.lamps} geometry="circle" geometryArgs={[1.7, 16]} position={POOL_POS} flat>
- <meshBasicMaterial
- color={lampGlow}
- transparent
- opacity={poolOpacity}
- blending={THREE.AdditiveBlending}
- depthWrite={false}
- />
- </Instances>
- )}
- </>
- )}
- {/* Tree trunks around the plaza */}
- <Instances placements={props.trees} geometry="cylinder" geometryArgs={[0.07, 0.1, 1.1, 5]} position={TRUNK_POS}>
- <meshStandardMaterial {...surface} color={structureColor} roughness={0.8} />
- </Instances>
- {/* Vibes uses two broad faceted leaf layers so the grove reads as trees rather than
- floating gems; Cyber keeps the established wireframe treatment. */}
- {lowPoly ? (
- <>
- <Instances placements={props.trees} geometry="sphere" geometryArgs={[0.9, 8, 5]} position={CANOPY_POS}>
- <meshStandardMaterial {...surface} color={foliageColor} roughness={0.98} onBeforeCompile={onSwayCompile} />
- </Instances>
- <Instances placements={props.trees} geometry="sphere" geometryArgs={[0.68, 8, 5]} position={CANOPY_TOP_POS}>
- <meshStandardMaterial {...surface} color={mixHex(foliageColor, '#d5e7a4', 0.28)} roughness={0.98} onBeforeCompile={onSwayCompile} />
- </Instances>
- </>
- ) : (
- <Instances placements={props.trees} geometry="icosahedron" geometryArgs={[0.8, 1]} position={CANOPY_POS}>
- <meshBasicMaterial
- color={mixHex(accent, '#22c55e', 0.45)}
- wireframe
- transparent
- opacity={0.5 * (1 - dayMix) + 0.3 * dayMix}
- toneMapped={false}
- onBeforeCompile={onSwayCompile}
- />
- </Instances>
- )}
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldStreets.jsx b/client/src/components/openworld/OpenWorldStreets.jsx
deleted file mode 100644
index a9c7c86dca..0000000000
--- a/client/src/components/openworld/OpenWorldStreets.jsx
+++ /dev/null
@@ -1,139 +0,0 @@
-import { useMemo, useEffect } from 'react';
-import * as THREE from 'three';
-import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
-import { openWorldDayMix, mixHex, getAccentColor } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import { computeStreets, PARCELS, PLAZA } from '../../utils/openWorldPlan';
-
-// The street network from the master plan (openWorldPlan.js): an octagonal ring road around
-// downtown, spokes out to every district, the grand avenue to the harbor, a plaza
-// sidewalk ring, crosswalk bands, and a faint tinted ground pad under each district.
-// Everything merges into THREE draw calls total (asphalt / neon edge strips / paint),
-// using native merged geometry — never drei <Line> (broken in this three-stdlib combo).
-
-const STRIP_WIDTH = 0.16;
-
-// A flat rectangle at ground level: PlaneGeometry(length × width) rotated into XZ and
-// aimed along `angle` (atan2(dz,dx) convention — rotateY(-angle) maps +x onto it).
-const flatRect = (x, z, length, width, angle, y) => {
- const geom = new THREE.PlaneGeometry(length, width);
- geom.rotateX(-Math.PI / 2);
- geom.rotateY(-angle);
- geom.translate(x, y, z);
- return geom;
-};
-
-export default function OpenWorldStreets({ settings }) {
- const { accent, neonAccents } = useOpenWorldPalette();
- const dayMix = openWorldDayMix(settings);
-
- const streets = useMemo(() => computeStreets(), []);
-
- // Asphalt: every street segment, one merged geometry.
- const asphaltGeom = useMemo(() => {
- const rects = streets.segments.map((s) => flatRect(s.x, s.z, s.length, s.width, s.angle, 0.02));
- return mergeGeometries(rects);
- }, [streets]);
-
- // Neon edge strips: a thin glowing border along each side of every segment.
- const stripGeom = useMemo(() => {
- const rects = [];
- for (const s of streets.segments) {
- const off = s.width / 2 + STRIP_WIDTH;
- const px = -Math.sin(s.angle) * off;
- const pz = Math.cos(s.angle) * off;
- rects.push(flatRect(s.x + px, s.z + pz, s.length, STRIP_WIDTH, s.angle, 0.025));
- rects.push(flatRect(s.x - px, s.z - pz, s.length, STRIP_WIDTH, s.angle, 0.025));
- }
- return mergeGeometries(rects);
- }, [streets]);
-
- // Paint layer: crosswalk bands + the plaza sidewalk ring + tinted district pads,
- // vertex-colored so one material covers all of it.
- const paintGeom = useMemo(() => {
- const parts = [];
- const paintColor = new THREE.Color('#aab4c2');
- const pushColored = (geom, color) => {
- const count = geom.getAttribute('position').count;
- const arr = new Float32Array(count * 3);
- for (let i = 0; i < count; i++) {
- arr[i * 3] = color.r;
- arr[i * 3 + 1] = color.g;
- arr[i * 3 + 2] = color.b;
- }
- geom.setAttribute('color', new THREE.BufferAttribute(arr, 3));
- parts.push(geom);
- };
-
- for (const c of streets.crosswalks) {
- pushColored(flatRect(c.x, c.z, c.length, c.width, c.angle, 0.028), paintColor);
- }
-
- // Dashed center marks make the southern drop-in lane read as a drivable approach
- // instead of a dark rectangle, especially on the first mobile frame.
- for (const arrival of streets.segments.filter((segment) => segment.kind === 'arrival')) {
- const dashLength = 1.5;
- const dashGap = 3.4;
- const count = Math.floor(arrival.length / (dashLength + dashGap));
- const cos = Math.cos(arrival.angle);
- const sin = Math.sin(arrival.angle);
- for (let i = 0; i < count; i++) {
- const along = -arrival.length / 2 + dashLength / 2 + i * (dashLength + dashGap);
- pushColored(
- flatRect(arrival.x + cos * along, arrival.z + sin * along, dashLength, 0.12, arrival.angle, 0.032),
- new THREE.Color(mixHex('#f2d49c', '#ffffff', dayMix * 0.35)),
- );
- }
- }
-
- // A faceted plaza floor gives the central AI Core a readable stage even when
- // there are no live app towers yet. The outer sidewalk ring remains separate,
- // so the avenue and ring road still read as the town's navigation landmarks.
- const plaza = new THREE.CircleGeometry(PLAZA.radius, 12);
- plaza.rotateX(-Math.PI / 2);
- plaza.translate(0, 0.022, 0);
- pushColored(plaza, new THREE.Color(mixHex('#2e4b55', '#c7b995', dayMix)));
-
- const ring = new THREE.RingGeometry(streets.plazaRing.inner, streets.plazaRing.outer, 48);
- ring.rotateX(-Math.PI / 2);
- ring.translate(0, 0.018, 0);
- pushColored(ring, paintColor.clone().multiplyScalar(0.6));
-
- // District ground pads — a quiet color wash so each quarter reads as a zone.
- // The pad color is each district's deterministic neon accent (same picker the
- // buildings use), well under the labels so it never competes with them.
- for (const [id, parcel] of Object.entries(PARCELS)) {
- if (parcel.dynamic || parcel.water || parcel.noPad) continue;
- const tint = new THREE.Color(getAccentColor({ name: id }, neonAccents)).multiplyScalar(0.5);
- pushColored(flatRect(parcel.anchor[0], parcel.anchor[2], parcel.w, parcel.d, 0, 0.012), tint);
- }
-
- return mergeGeometries(parts);
- }, [streets, neonAccents]);
-
- useEffect(() => () => {
- asphaltGeom.dispose();
- stripGeom.dispose();
- paintGeom.dispose();
- }, [asphaltGeom, stripGeom, paintGeom]);
-
- // Night: deep blue asphalt with accent-glow borders. Day: slate-blue roads keep
- // their contrast against the sage ground instead of disappearing into a gray slab.
- const asphaltColor = mixHex('#152536', '#536d7a', dayMix);
- const stripOpacity = 0.55 * (1 - dayMix) + 0.25 * dayMix;
- const paintOpacity = 0.16 + 0.18 * dayMix;
-
- return (
- <group>
- <mesh geometry={asphaltGeom}>
- <meshStandardMaterial color={asphaltColor} roughness={0.92} metalness={0.08} />
- </mesh>
- <mesh geometry={stripGeom}>
- <meshBasicMaterial color={mixHex(accent, '#f1d5a5', dayMix)} transparent opacity={stripOpacity} toneMapped={false} />
- </mesh>
- <mesh geometry={paintGeom}>
- <meshBasicMaterial vertexColors transparent opacity={paintOpacity} />
- </mesh>
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldTaskFlowRiver.jsx b/client/src/components/openworld/OpenWorldTaskFlowRiver.jsx
deleted file mode 100644
index cc4e98fb80..0000000000
--- a/client/src/components/openworld/OpenWorldTaskFlowRiver.jsx
+++ /dev/null
@@ -1,93 +0,0 @@
-import { useMemo, useRef } from 'react';
-import { useFrame } from '@react-three/fiber';
-import { computeTaskQueue } from '../../utils/openWorldTaskQueue';
-import { computeTaskFlowRiver, recentCalendarThroughput } from '../../utils/openWorldTaskFlowRiver';
-
-// OpenWorld task-flow river (issue #817): an animated channel running from the task-queue
-// warehouse to the productivity district, tying queued work to completed throughput. The
-// channel WIDTH tracks the live backlog (more pending/in-progress/blocked work → broader) and
-// the flow SPEED tracks recent throughput / queue drain. Flow nodes travel warehouse→monument
-// along the channel; they animate only on the higher quality presets, while the channel bed
-// itself stays drawn so the link between the two districts is always legible. Mirrors
-// OpenWorldProductivityDistrict / OpenWorldTaskQueue.
-export default function OpenWorldTaskFlowRiver({ cosTasks, productivityData, calendarData, settings }) {
- const river = useMemo(() => {
- const queue = computeTaskQueue(cosTasks);
- // Recent throughput drives the current speed. Prefer today's completed count from the
- // quick-summary (the freshest "draining now" signal); fall back to a bounded last-7-days
- // total from the calendar so the river still flows before today's count is meaningful.
- // Using the calendar's full 12-week total would pin the river at max speed forever, so we
- // deliberately window it. Optional chaining tolerates missing/non-object payloads, and
- // computeTaskFlowRiver reads a non-number as zero.
- const todayCompleted = productivityData?.today?.completed;
- const throughput = typeof todayCompleted === 'number'
- ? todayCompleted
- : recentCalendarThroughput(calendarData, 7);
- return computeTaskFlowRiver(queue, throughput);
- }, [cosTasks, productivityData, calendarData]);
-
- const nodesRef = useRef();
-
- // Honor the quality dial: drop the traveling flow nodes on the lowest preset; the channel
- // bed remains so the districts stay visually linked.
- const animate = (settings?.particleDensity ?? 1) >= 0.5;
-
- useFrame(({ clock }) => {
- if (!animate || !nodesRef.current || !river.flowing) return;
- const t = clock.getElapsedTime();
- const half = river.length / 2;
- for (const node of nodesRef.current.children) {
- const phase = node.userData.phase || 0;
- // Flow runs warehouse(-half) → monument(+half) along the channel's local +x. Wrap with
- // a fractional cycle so nodes stream continuously; speed scales with throughput.
- const frac = (phase + t * river.speed * 0.12) % 1;
- node.position.x = -half + frac * river.length;
- }
- });
-
- const { center, angle, length, width, color, particles } = river;
-
- return (
- // Center the channel between the two districts and rotate it to align local +x with the
- // warehouse→monument axis. A slight lift keeps the bed from z-fighting the ground plane.
- <group position={[center[0], 0.06, center[2]]} rotation={[0, angle, 0]}>
- {/* Channel bed — a flat ribbon laid on the ground along the district axis */}
- <mesh rotation={[-Math.PI / 2, 0, 0]}>
- <planeGeometry args={[length, width]} />
- <meshStandardMaterial
- color={color}
- emissive={color}
- emissiveIntensity={0.12 + river.speedLevel * 0.18}
- transparent
- opacity={0.32}
- metalness={0.2}
- roughness={0.7}
- toneMapped={false}
- />
- </mesh>
-
- {/* Traveling flow nodes — only when there's a live current to depict; on the lowest
- preset (animation off) or an idle/not-draining channel the bed alone stays drawn so
- static glowing boxes never imply movement that isn't happening. */}
- {animate && river.flowing && (
- <group ref={nodesRef}>
- {particles.map((p) => (
- <mesh
- key={p.index}
- position={[-length / 2 + p.phase * length, 0.18, 0]}
- userData={{ phase: p.phase }}
- >
- <boxGeometry args={[width * 0.5, 0.22, Math.min(width * 0.7, 1.4)]} />
- <meshStandardMaterial
- color={color}
- emissive={color}
- emissiveIntensity={0.6 + river.speedLevel * 0.6}
- toneMapped={false}
- />
- </mesh>
- ))}
- </group>
- )}
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldTaskQueue.jsx b/client/src/components/openworld/OpenWorldTaskQueue.jsx
deleted file mode 100644
index 11155628d4..0000000000
--- a/client/src/components/openworld/OpenWorldTaskQueue.jsx
+++ /dev/null
@@ -1,102 +0,0 @@
-import { useMemo, useRef } from 'react';
-import { useFrame } from '@react-three/fiber';
-import { PIXEL_FONT_URL, openWorldDayMix } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import OpenWorldLabel from './OpenWorldLabel';
-import { computeTaskQueue, TASK_QUEUE } from '../../utils/openWorldTaskQueue';
-
-// OpenWorld's CoS task-queue silhouette (roadmap 2.2): a warehouse east of downtown with
-// a stack of crates whose height tracks the depth of the Chief-of-Staff task backlog.
-// Crates pile up as tasks queue and clear as they complete; the warehouse roof light
-// glows green while an agent is working a task and amber when a task is blocked. An
-// overflow cap keeps a runaway backlog from scraping the sky — a marker crate signals
-// "more waiting" instead.
-function Crate({ y, size, color, topGlow }) {
- return (
- <mesh position={[0, y, 0]}>
- <boxGeometry args={[size, size, size]} />
- <meshStandardMaterial
- color="#13202e"
- emissive={color}
- emissiveIntensity={topGlow ? 0.5 : 0.18}
- metalness={0.3}
- roughness={0.7}
- />
- </mesh>
- );
-}
-
-export default function OpenWorldTaskQueue({ cosTasks, settings }) {
- const { tintStructure } = useOpenWorldPalette();
- const queue = useMemo(() => computeTaskQueue(cosTasks), [cosTasks]);
- const roofRef = useRef();
-
- // Honor the quality dial: drop the roof-light pulse on the lowest preset, but keep the
- // static glow so the queue state stays legible.
- const animate = (settings?.particleDensity ?? 1) >= 0.5;
- const dayMix = openWorldDayMix(settings);
-
- useFrame(({ clock }) => {
- if (!animate || !roofRef.current) return;
- // Blocked queues throb urgently; an active queue breathes; idle/queued sits calm.
- const speed = queue.hasBlocked ? 2.6 : queue.active ? 1.4 : 0.6;
- const base = queue.state === 'idle' ? 0.25 : 0.6;
- roofRef.current.material.emissiveIntensity = base + ((Math.sin(clock.getElapsedTime() * speed) + 1) / 2) * 0.6;
- });
-
- const { position, color, crates, overflow, pending, inProgress, blocked } = queue;
- const { crateSize, warehouseWidth } = TASK_QUEUE;
- // Where the overflow marker (and label) sits: just above the visible crate stack.
- const stackTop = crates.length ? crates[crates.length - 1].y + crateSize : crateSize;
-
- const sublabel = blocked > 0
- ? `${blocked} BLOCKED · ${pending} QUEUED`
- : inProgress > 0
- ? `${inProgress} ACTIVE · ${pending} QUEUED`
- : pending > 0
- ? `${pending} QUEUED`
- : 'IDLE';
-
- return (
- <group position={position}>
- {/* Queueworks is an open hexagonal maker dais, not another opaque warehouse. */}
- <mesh position={[0, 0.32, 0]}>
- <cylinderGeometry args={[warehouseWidth * 0.62, warehouseWidth * 0.76, 0.64, 8]} />
- <meshStandardMaterial color={tintStructure('#27373c')} emissive={color} emissiveIntensity={0.16} metalness={0.12} roughness={0.84} flatShading />
- </mesh>
- {/* Roof light bar — the live queue-state indicator */}
- <mesh ref={roofRef} position={[0, 0.7, 0]} rotation={[-Math.PI / 2, 0, 0]}>
- <torusGeometry args={[warehouseWidth * 0.44, 0.12, 8, 8]} />
- <meshStandardMaterial color={color} emissive={color} emissiveIntensity={0.6} toneMapped={false} />
- </mesh>
-
- {/* Crate stack rises from the dock roof; height ∝ pending backlog */}
- <group position={[0, 0.8, 0]}>
- {crates.map((crate, i) => (
- <Crate
- key={crate.index}
- y={crate.y}
- size={crateSize}
- color={color}
- topGlow={i === crates.length - 1}
- />
- ))}
- {/* Overflow marker — a half-height capstone meaning "more waiting than shown" */}
- {overflow && (
- <mesh position={[0, stackTop + crateSize * 0.4, 0]}>
- <boxGeometry args={[crateSize * 0.6, crateSize * 0.5, crateSize * 0.6]} />
- <meshStandardMaterial color={color} emissive={color} emissiveIntensity={0.7} toneMapped={false} />
- </mesh>
- )}
-
- {/* Label + count sublabel above the stack */}
- <OpenWorldLabel position={[0, stackTop + crateSize * (overflow ? 1.05 : 0.78), 0]} fontSize={0.58} color={color} dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={20}>
- QUEUEWORKS
- </OpenWorldLabel>
- <OpenWorldLabel position={[0, stackTop + crateSize * (overflow ? 0.62 : 0.32), 0]} fontSize={0.36} color="#94a3b8" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={20}>
- {sublabel}
- </OpenWorldLabel>
- </group>
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldTraffic.jsx b/client/src/components/openworld/OpenWorldTraffic.jsx
deleted file mode 100644
index d133ad50d9..0000000000
--- a/client/src/components/openworld/OpenWorldTraffic.jsx
+++ /dev/null
@@ -1,195 +0,0 @@
-import { useRef, useMemo } from 'react';
-import { useFrame } from '@react-three/fiber';
-import { computeDistrictBounds } from '../../utils/openWorldMiniMap';
-import { mixHex } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-
-// A single ambient vehicle. Vibes keeps traffic on the road; cyber keeps the original hover lanes.
-function HoverVehicle({ path, color, speed, offset, altitude, lowPoly, surface }) {
- const groupRef = useRef();
- const lightRef = useRef();
- const bodyRef = useRef();
-
- useFrame(({ clock }) => {
- if (!groupRef.current || path.length < 2) return;
- const t = ((clock.getElapsedTime() * speed + offset) % 1.0);
-
- // Interpolate along path
- const totalT = t * (path.length - 1);
- const segIdx = Math.min(Math.floor(totalT), path.length - 2);
- const segT = totalT - segIdx;
-
- const ax = path[segIdx][0];
- const az = path[segIdx][2];
- const bx = path[segIdx + 1][0];
- const bz = path[segIdx + 1][2];
-
- const x = ax + (bx - ax) * segT;
- const z = az + (bz - az) * segT;
- const y = lowPoly
- ? 0.02 + Math.sin(t * Math.PI * 2) * 0.025
- : altitude + Math.sin(t * Math.PI * 2) * 0.15;
-
- groupRef.current.position.set(x, y, z);
-
- // Face direction of travel
- const angle = Math.atan2(bz - az, bx - ax);
- groupRef.current.rotation.y = -angle;
-
- // Tail light flicker
- if (lightRef.current) {
- lightRef.current.intensity = 0.3 + Math.sin(clock.getElapsedTime() * 12 + offset * 10) * 0.15;
- }
-
- // Subtle tilt into turns
- if (bodyRef.current) {
- const tilt = Math.sin(t * Math.PI * 4) * 0.1;
- bodyRef.current.rotation.z = tilt;
- }
- });
-
- return (
- <group ref={groupRef}>
- <group ref={bodyRef}>
- {/* Vehicle body — grounded in Vibes, airborne in the cyber style. */}
- <mesh position={lowPoly ? [0, 0.3, 0] : [0, 0, 0]}>
- <boxGeometry args={lowPoly ? [0.72, 0.24, 0.34] : [0.4, 0.08, 0.15]} />
- {lowPoly ? (
- <meshStandardMaterial {...surface} color={mixHex(color, '#f2c28e', 0.28)} roughness={0.74} metalness={0.08} />
- ) : (
- <meshBasicMaterial color={color} transparent opacity={0.6} />
- )}
- </mesh>
- {/* Cockpit windshield */}
- <mesh position={[lowPoly ? 0.1 : 0.12, lowPoly ? 0.48 : 0.05, 0]}>
- <boxGeometry args={lowPoly ? [0.3, 0.13, 0.25] : [0.12, 0.04, 0.12]} />
- {lowPoly ? (
- <meshStandardMaterial {...surface} color="#27384a" roughness={0.28} metalness={0.24} />
- ) : (
- <meshBasicMaterial color="#ffffff" transparent opacity={0.3} />
- )}
- </mesh>
- {lowPoly && (
- <>
- <mesh position={[-0.38, 0.34, 0]}>
- <boxGeometry args={[0.035, 0.08, 0.22]} />
- <meshBasicMaterial color="#ef6b61" toneMapped={false} />
- </mesh>
- {[-1, 1].map((side) => (
- <mesh key={`headlight-${side}`} position={[0.38, 0.32, side * 0.1]}>
- <boxGeometry args={[0.035, 0.07, 0.07]} />
- <meshBasicMaterial color="#fff1c9" toneMapped={false} />
- </mesh>
- ))}
- {[-1, 1].map((side) => (
- <group key={`wheel-${side}`} position={[0, 0.15, side * 0.2]}>
- <mesh rotation={[Math.PI / 2, 0, 0]}>
- <cylinderGeometry args={[0.13, 0.13, 0.08, 10]} />
- <meshStandardMaterial color="#1b2633" roughness={0.9} metalness={0.05} />
- </mesh>
- </group>
- ))}
- </>
- )}
- {/* Engine glow at rear — cyber traffic keeps its luminous signature. */}
- {!lowPoly && (
- <>
- <mesh position={[-0.22, 0, 0]}>
- <sphereGeometry args={[0.04, 6, 6]} />
- <meshBasicMaterial color={color} transparent opacity={0.9} />
- </mesh>
- <pointLight ref={lightRef} position={[-0.22, 0, 0]} color={color} intensity={0.3} distance={3} decay={2} />
- </>
- )}
- </group>
- </group>
- );
-}
-
-export default function OpenWorldTraffic({ positions }) {
- const { neonAccents, lowPoly, surface } = useOpenWorldPalette();
- // Generate traffic lanes based on building layout
- const vehicles = useMemo(() => {
- if (!positions || positions.size < 2) return [];
-
- const bounds = computeDistrictBounds(positions, 'downtown', { minCount: 2 });
- if (!bounds) return [];
- const { minX, maxX, minZ, maxZ } = bounds;
-
- const pad = 3;
- const colors = neonAccents;
- const result = [];
-
- // Create traffic lanes around the perimeter
- const perimeter = [
- [minX - pad, 0, minZ - pad],
- [maxX + pad, 0, minZ - pad],
- [maxX + pad, 0, maxZ + pad],
- [minX - pad, 0, maxZ + pad],
- [minX - pad, 0, minZ - pad],
- ];
-
- // Perimeter vehicles (3-5 hover cars circling the downtown)
- const downtownCount = [...positions.values()].filter((pos) => pos.district === 'downtown').length;
- const vehicleCount = Math.min(5, Math.max(3, downtownCount));
- for (let i = 0; i < vehicleCount; i++) {
- result.push({
- id: `perim-${i}`,
- path: perimeter,
- color: colors[i % colors.length],
- speed: 0.04 + i * 0.008,
- offset: i / vehicleCount,
- altitude: 1.5 + i * 0.6,
- });
- }
-
- // Cross-city lanes (a few vehicles going through the center)
- if (downtownCount >= 3) {
- // Horizontal lane
- result.push({
- id: 'cross-h',
- path: [
- [minX - pad - 5, 0, 0],
- [maxX + pad + 5, 0, 0],
- ],
- color: colors[5 % colors.length],
- speed: 0.06,
- offset: 0.3,
- altitude: 3.0,
- });
- // Diagonal lane
- result.push({
- id: 'cross-d',
- path: [
- [minX - pad - 3, 0, maxZ + pad + 3],
- [maxX + pad + 3, 0, minZ - pad - 3],
- ],
- color: colors[6 % colors.length],
- speed: 0.05,
- offset: 0.7,
- altitude: 4.0,
- });
- }
-
- return result;
- }, [positions, neonAccents]);
-
- if (vehicles.length === 0) return null;
-
- return (
- <group>
- {vehicles.map(v => (
- <HoverVehicle
- key={v.id}
- path={v.path}
- color={v.color}
- speed={v.speed}
- offset={v.offset}
- altitude={v.altitude}
- lowPoly={lowPoly}
- surface={surface}
- />
- ))}
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldTransitLoop.jsx b/client/src/components/openworld/OpenWorldTransitLoop.jsx
deleted file mode 100644
index cabdf3e954..0000000000
--- a/client/src/components/openworld/OpenWorldTransitLoop.jsx
+++ /dev/null
@@ -1,99 +0,0 @@
-import { useMemo, useRef, useEffect } from 'react';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { openWorldDayMix, openWorldShowDetail, mixHex } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import { TRANSIT } from '../../utils/openWorldPlan';
-
-// The elevated transit loop from the master plan: a closed glowing track linking every
-// quarter, with a few trams orbiting it — the city's "alive" motion layer. Native
-// TubeGeometry along a closed CatmullRom curve (never drei <Line>); support pylons drop
-// at each district stop. Trams hide on the low preset; the track itself is one mesh.
-
-const TRAM_SIZE = [0.9, 0.5, 0.42];
-
-export default function OpenWorldTransitLoop({ settings }) {
- const { accent, tintStructure, lowPoly, surface } = useOpenWorldPalette();
- const dayMix = openWorldDayMix(settings);
- const showTrams = openWorldShowDetail(settings);
-
- const curve = useMemo(() => {
- const points = TRANSIT.stops.map((s) => new THREE.Vector3(...s.point));
- const c = new THREE.CatmullRomCurve3(points, true, 'centripetal');
- return c;
- }, []);
-
- const trackGeom = useMemo(() => new THREE.TubeGeometry(curve, 220, 0.1, 6, true), [curve]);
- useEffect(() => () => trackGeom.dispose(), [trackGeom]);
-
- const tramRefs = useRef([]);
- tramRefs.current = [];
- const lookAhead = useRef(new THREE.Vector3());
-
- useFrame(({ clock }) => {
- const t = clock.getElapsedTime() * TRANSIT.tramSpeed;
- tramRefs.current.forEach((tram, i) => {
- if (!tram) return;
- const u = (t + i / TRANSIT.tramCount) % 1;
- curve.getPointAt(u, tram.position);
- curve.getPointAt((u + 0.005) % 1, lookAhead.current);
- tram.lookAt(lookAhead.current);
- });
- });
-
- const trackColor = lowPoly
- ? mixHex('#4e7c7f', '#e1c28d', dayMix)
- : mixHex(accent, '#8b9bb0', dayMix);
- const trackOpacity = lowPoly
- ? 0.46 * (1 - dayMix) + 0.62 * dayMix
- : 0.5 * (1 - dayMix) + 0.3 * dayMix;
- const pylonColor = lowPoly ? mixHex('#38545a', '#6d887c', dayMix) : tintStructure('#121a2c');
-
- return (
- <group>
- <mesh geometry={trackGeom}>
- <meshBasicMaterial color={trackColor} transparent opacity={trackOpacity} toneMapped={false} />
- </mesh>
-
- {/* Support pylon + station halo at every stop */}
- {TRANSIT.stops.map((stop) => (
- <group key={stop.id} position={[stop.point[0], 0, stop.point[2]]}>
- <mesh position={[0, TRANSIT.y / 2, 0]}>
- <cylinderGeometry args={[0.12, 0.2, TRANSIT.y, 6]} />
- <meshStandardMaterial {...surface} color={pylonColor} roughness={0.7} metalness={lowPoly ? 0 : 0.4} />
- </mesh>
- <mesh position={[0, TRANSIT.y - 0.35, 0]} rotation={[Math.PI / 2, 0, 0]}>
- <torusGeometry args={[0.55, 0.05, 6, 20]} />
- <meshBasicMaterial color={trackColor} transparent opacity={trackOpacity + 0.15} toneMapped={false} />
- </mesh>
- </group>
- ))}
-
- {showTrams && Array.from({ length: TRANSIT.tramCount }, (_, i) => (
- <group key={i} ref={(el) => { if (el) tramRefs.current[i] = el; }}>
- <mesh>
- <boxGeometry args={TRAM_SIZE} />
- <meshStandardMaterial
- {...surface}
- color={lowPoly ? mixHex('#d57b67', accent, 0.2) : tintStructure('#1a2440')}
- emissive={accent}
- emissiveIntensity={0.5 * (1 - dayMix) + 0.15 * dayMix}
- metalness={lowPoly ? 0.05 : 0.5}
- roughness={lowPoly ? 0.85 : 0.3}
- toneMapped={false}
- />
- </mesh>
- {/* Front headlamp bar and rear brake light */}
- <mesh position={[0, 0, TRAM_SIZE[2] / 2 + 0.01]}>
- <boxGeometry args={[TRAM_SIZE[0] * 0.65, 0.08, 0.02]} />
- <meshBasicMaterial color="#fef08a" toneMapped={false} />
- </mesh>
- <mesh position={[0, 0, -TRAM_SIZE[2] / 2 - 0.01]}>
- <boxGeometry args={[TRAM_SIZE[0] * 0.6, 0.06, 0.02]} />
- <meshBasicMaterial color="#ef4444" toneMapped={false} />
- </mesh>
- </group>
- ))}
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldTubeLine.jsx b/client/src/components/openworld/OpenWorldTubeLine.jsx
deleted file mode 100644
index 83c4e3baf3..0000000000
--- a/client/src/components/openworld/OpenWorldTubeLine.jsx
+++ /dev/null
@@ -1,29 +0,0 @@
-import { useMemo, useEffect } from 'react';
-import * as THREE from 'three';
-
-// A thin glowing connector rendered as a native-three tube along a curve through `points`.
-// Used for OpenWorld's light bridges (memory district) and goal-tree links. We deliberately do
-// NOT use drei's <Line>: it builds a three-stdlib Line2 whose fat-line geometry needs
-// `computeLineDistances`, and the bundled three-stdlib instance mismatches the app's three
-// (0.182), so that method is missing on the reconciled object and the whole Canvas crashes
-// ("m.computeLineDistances is not a function"). A TubeGeometry needs none of that, gives real
-// width (native LineBasicMaterial ignores linewidth anyway), and reads better as a glow.
-export default function OpenWorldTubeLine({ points, color, radius = 0.08, opacity = 0.5, segments = 24 }) {
- const geometry = useMemo(() => {
- const pts = (points || []).filter(Boolean).map((p) => new THREE.Vector3(p[0], p[1], p[2]));
- if (pts.length < 2) return null;
- const curve = new THREE.CatmullRomCurve3(pts);
- // Tubular segments scale with point count so a multi-point arc stays smooth.
- return new THREE.TubeGeometry(curve, Math.max(segments, pts.length * 8), radius, 6, false);
- }, [points, radius, segments]);
-
- useEffect(() => () => geometry?.dispose(), [geometry]);
-
- if (!geometry) return null;
-
- return (
- <mesh geometry={geometry}>
- <meshBasicMaterial color={color} transparent opacity={opacity} toneMapped={false} />
- </mesh>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldVitalsList.jsx b/client/src/components/openworld/OpenWorldVitalsList.jsx
deleted file mode 100644
index 555ce1c4b7..0000000000
--- a/client/src/components/openworld/OpenWorldVitalsList.jsx
+++ /dev/null
@@ -1,118 +0,0 @@
-import { formatDurationMs, formatMonthDay } from '../../utils/formatters';
-import { StatButton, metricColor } from './openWorldHudBits';
-
-// The System Vitals rows (uptime, health CPU/MEM/DISK, agents, stopped, archived,
-// review, nodes, notifs, tasks + the SYS.OK footer). Extracted from the
-// desktop clock-rail so the SAME rows back both the desktop cockpit's vitals panel
-// AND the compact/phone `vitals` disclosure surface — no divergent copies.
-export default function OpenWorldVitalsList({
- uptimeSeconds,
- sentinel,
- cpuPct,
- memPct,
- diskPct,
- warnings,
- activeAgentCount,
- stoppedApps,
- archivedApps,
- pendingReview,
- alertCount,
- onlinePeers,
- totalNodes,
- notificationCounts,
- productivityData,
- onOpenDestination,
-}) {
- return (
- <div className="space-y-1.5">
- <div className="font-pixel text-[10px] text-cyan-500/70 tracking-wider mb-1">
- SYSTEM VITALS
- </div>
-
- {/* Uptime */}
- <div className="flex items-center justify-between gap-6">
- <span className="font-pixel text-[10px] text-gray-400 tracking-wide">UPTIME</span>
- <span className="font-pixel text-[11px] text-cyan-400" style={{ textShadow: '0 0 6px rgba(6,182,212,0.4)' }}>
- {formatDurationMs(uptimeSeconds * 1000)}
- </span>
- </div>
-
- <button
- type="button"
- onClick={() => onOpenDestination?.('wellness')}
- className="w-full flex items-center justify-between gap-3 -mx-1 px-1 py-1 min-h-[44px] sm:min-h-0 rounded hover:bg-cyan-500/5 transition-colors"
- title={warnings?.length ? warnings.map(w => w.message).join(' · ') : 'Teleport to Wellness District'}
- aria-label="System health — teleport to Wellness District"
- >
- <span className="font-pixel text-[10px] text-gray-400 tracking-wide flex items-center gap-1.5">
- <span className={`w-1.5 h-1.5 rounded-full ${sentinel.dot} shadow-[0_0_4px_currentColor]`} />
- HEALTH
- </span>
- <span className="font-pixel text-[10px] tracking-wide flex items-center gap-2">
- <span className={metricColor(cpuPct)}>{cpuPct != null ? `${cpuPct}%` : '—'}</span>
- <span className="text-gray-600">/</span>
- <span className={metricColor(memPct)}>{memPct != null ? `${memPct}%` : '—'}</span>
- <span className="text-gray-600">/</span>
- <span className={metricColor(diskPct)}>{diskPct != null ? `${diskPct}%` : '—'}</span>
- </span>
- </button>
- <div className="flex items-center justify-between gap-6 -mt-0.5">
- <span className="font-pixel text-[8px] text-gray-600 tracking-wider pl-3.5">CPU · MEM · DISK</span>
- <span className={`font-pixel text-[8px] ${sentinel.text} tracking-wider`}>{sentinel.label}</span>
- </div>
-
- <StatButton
- label="AGENTS"
- valueClass={activeAgentCount > 0 ? 'text-emerald-400' : 'text-gray-600'}
- value={`${activeAgentCount} ACTIVE`}
- prefix={activeAgentCount > 0 ? <span className="inline-block w-1.5 h-1.5 rounded-full bg-emerald-400 mr-1 animate-pulse" /> : null}
- onClick={() => onOpenDestination?.('ai-core')}
- title="Teleport to AI Core"
- />
-
- {stoppedApps > 0 && (
- <StatButton label="STOPPED" valueClass="text-red-400" value={stoppedApps} onClick={() => onOpenDestination?.('downtown')} title="Teleport to Downtown" />
- )}
-
- {archivedApps > 0 && (
- <StatButton label="ARCHIVED" valueClass="text-gray-500" value={archivedApps} onClick={() => onOpenDestination?.('downtown')} title="Teleport to Downtown" />
- )}
-
- {(pendingReview > 0 || alertCount > 0) && (
- <StatButton
- label="REVIEW"
- valueClass={alertCount > 0 ? 'text-orange-400' : 'text-cyan-400'}
- value={`${pendingReview} PENDING${alertCount > 0 ? ` · ${alertCount} ALERT${alertCount === 1 ? '' : 'S'}` : ''}`}
- onClick={() => onOpenDestination?.('task-queue')}
- title="Teleport to Task Queue"
- />
- )}
-
- <StatButton
- label="NODES"
- valueClass={onlinePeers > 0 ? 'text-violet-400' : 'text-gray-500'}
- value={`${onlinePeers}/${totalNodes} LINKED`}
- onClick={() => onOpenDestination?.('data-harbor')}
- title="Teleport to Data Harbor"
- />
-
- {notificationCounts?.unread > 0 && (
- <StatButton label="NOTIFS" valueClass="text-cyan-400" value={`${notificationCounts.unread} UNREAD`} onClick={() => onOpenDestination?.('downtown')} title="Teleport to Downtown" />
- )}
-
- {productivityData?.todaySucceeded > 0 && (
- <StatButton label="TASKS" valueClass="text-purple-400" value={`${productivityData.todaySucceeded} TODAY`} onClick={() => onOpenDestination?.('productivity')} title="Teleport to Productivity" />
- )}
-
- {/* Divider */}
- <div className="border-t border-cyan-500/15 mt-1.5 pt-1.5">
- <div className="flex items-center justify-between">
- <span className="font-pixel text-[9px] text-cyan-500/40 tracking-widest">SYS.OK</span>
- <span className="font-pixel text-[9px] text-cyan-500/40 tracking-widest">
- {formatMonthDay(new Date()).toUpperCase()}
- </span>
- </div>
- </div>
- </div>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldVoiceMarker.jsx b/client/src/components/openworld/OpenWorldVoiceMarker.jsx
deleted file mode 100644
index 3d883bc348..0000000000
--- a/client/src/components/openworld/OpenWorldVoiceMarker.jsx
+++ /dev/null
@@ -1,66 +0,0 @@
-import { useMemo, useRef } from 'react';
-import { useFrame } from '@react-three/fiber';
-import { PIXEL_FONT_URL, openWorldDayMix, mixHex } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import OpenWorldLabel from './OpenWorldLabel';
-import { computeVoiceMarker } from '../../utils/openWorldVoiceMarker';
-
-// OpenWorld's voice-agent district marker (roadmap 2.4): a modest ground-level beacon
-// north of downtown — a low disc with a short pole and a glowing orb on top. The orb's
-// color and pulse mirror the voice agent's live state: calm slate on standby, accent blue
-// while listening, green while dictating, red on error, and barely-lit when voice mode is
-// off. Keeps to a small footprint so it reads as a district marker, not a landmark.
-export default function OpenWorldVoiceMarker({ voiceState, settings }) {
- const { tintStructure, lowPoly, surface } = useOpenWorldPalette();
- const marker = useMemo(() => computeVoiceMarker(voiceState), [voiceState]);
- const orbRef = useRef();
-
- // Honor the quality dial: drop the beacon pulse on the lowest preset, but keep the
- // static glow so the voice state stays legible.
- const animate = (settings?.particleDensity ?? 1) >= 0.5;
- const dayMix = openWorldDayMix(settings);
-
- useFrame(({ clock }) => {
- if (!animate || !orbRef.current) return;
- // Error throbs urgently; listening/dictating breathe actively; idle sits calm;
- // a disabled marker holds its dim static glow (no pulse).
- if (marker.disabled) {
- orbRef.current.material.emissiveIntensity = marker.intensity;
- return;
- }
- const speed = marker.alerting ? 3 : marker.active ? 2 : 0.7;
- const pulse = 0.5 + ((Math.sin(clock.getElapsedTime() * speed) + 1) / 2) * 0.6;
- orbRef.current.material.emissiveIntensity = pulse * (marker.intensity + 0.2);
- });
-
- const { position, baseRadius, poleHeight, beaconRadius, color, label } = marker;
- const baseColor = lowPoly ? mixHex('#426267', '#d1b47f', dayMix) : tintStructure('#0c1620');
- const poleColor = lowPoly ? mixHex('#38545a', '#718678', dayMix) : '#1a2533';
-
- return (
- <group position={position}>
- {/* Low disc base — anchors the marker to the ground */}
- <mesh position={[0, 0.1, 0]}>
- <cylinderGeometry args={[baseRadius, baseRadius * 1.15, 0.2, 24]} />
- <meshStandardMaterial {...surface} color={baseColor} emissive={color} emissiveIntensity={0.12} metalness={lowPoly ? 0 : 0.5} roughness={0.6} />
- </mesh>
- {/* Slim antenna pole */}
- <mesh position={[0, poleHeight / 2, 0]}>
- <cylinderGeometry args={[0.14, 0.18, poleHeight, 12]} />
- <meshStandardMaterial {...surface} color={poleColor} emissive={color} emissiveIntensity={0.15} metalness={lowPoly ? 0 : 0.7} roughness={0.4} />
- </mesh>
- {/* Beacon orb — the live voice-state indicator */}
- <mesh ref={orbRef} position={[0, poleHeight + beaconRadius * 0.6, 0]}>
- <sphereGeometry args={[beaconRadius, 20, 20]} />
- <meshStandardMaterial color={color} emissive={color} emissiveIntensity={marker.intensity} toneMapped={false} />
- </mesh>
- {/* Label + live-state sublabel above the beacon */}
- <OpenWorldLabel position={[0, poleHeight + beaconRadius * 0.6 + 1.6, 0]} fontSize={1} color={color} dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={16}>
- VOICE
- </OpenWorldLabel>
- <OpenWorldLabel position={[0, poleHeight + beaconRadius * 0.6 + 0.9, 0]} fontSize={0.7} color="#94a3b8" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={16}>
- {label}
- </OpenWorldLabel>
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldVolumetricLights.jsx b/client/src/components/openworld/OpenWorldVolumetricLights.jsx
deleted file mode 100644
index a5fa1df7e0..0000000000
--- a/client/src/components/openworld/OpenWorldVolumetricLights.jsx
+++ /dev/null
@@ -1,207 +0,0 @@
-import { useRef, useMemo, useEffect } from 'react';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { computeDistrictBounds } from '../../utils/openWorldMiniMap';
-import { openWorldDayMix } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-
-// Volumetric light cone shader
-const CONE_VERT = `
- varying vec2 vUv;
- varying float vHeight;
- void main() {
- vUv = uv;
- vHeight = position.y;
- gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
- }
-`;
-
-const CONE_FRAG = `
- uniform vec3 uColor;
- uniform float uTime;
- uniform float uIntensity;
- varying vec2 vUv;
- varying float vHeight;
- void main() {
- // Fade from bottom to top
- float alpha = (1.0 - vUv.y) * 0.12 * uIntensity;
- // Radial fade from center
- float radial = 1.0 - abs(vUv.x - 0.5) * 2.0;
- alpha *= radial * radial;
- // Slow shimmer
- alpha *= 0.8 + 0.2 * sin(uTime * 0.5 + vHeight * 2.0);
- // Noise-like variation
- float noise = sin(vUv.y * 30.0 + uTime) * 0.1;
- alpha += noise * 0.02;
- alpha = max(alpha, 0.0);
- gl_FragColor = vec4(uColor, alpha);
- }
-`;
-
-// A single volumetric light beam (upward cone)
-function LightBeam({ position, color, height = 15, radius = 2, intensity = 1, phase = 0 }) {
- const matRef = useRef();
-
- const coneGeom = useMemo(() => {
- const geom = new THREE.CylinderGeometry(radius * 0.3, radius, height, 8, 16, true);
- return geom;
- }, [radius, height]);
-
- useEffect(() => () => coneGeom.dispose(), [coneGeom]);
-
- useFrame(({ clock }) => {
- if (!matRef.current) return;
- matRef.current.uniforms.uTime.value = clock.getElapsedTime() + phase;
- });
-
- const colorVec = useMemo(() => new THREE.Color(color), [color]);
-
- // The shader material persists across a theme switch (no more full-scene remount),
- // so push the new accent/intensity into its uniforms imperatively — re-rendering
- // with a new `uniforms` object does not re-upload them to an already-built material.
- useEffect(() => {
- const mat = matRef.current;
- if (!mat) return;
- mat.uniforms.uColor.value.copy(colorVec);
- mat.uniforms.uIntensity.value = intensity;
- }, [colorVec, intensity]);
-
- return (
- <group position={position}>
- <mesh geometry={coneGeom} position={[0, height / 2, 0]}>
- <shaderMaterial
- ref={matRef}
- vertexShader={CONE_VERT}
- fragmentShader={CONE_FRAG}
- uniforms={{
- uColor: { value: colorVec },
- uTime: { value: 0 },
- uIntensity: { value: intensity },
- }}
- transparent
- blending={THREE.AdditiveBlending}
- side={THREE.DoubleSide}
- depthWrite={false}
- />
- </mesh>
- {/* Ground glow disc */}
- <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.03, 0]}>
- <circleGeometry args={[radius, 16]} />
- <meshBasicMaterial
- color={color}
- transparent
- opacity={0.08 * intensity}
- blending={THREE.AdditiveBlending}
- side={THREE.DoubleSide}
- />
- </mesh>
- </group>
- );
-}
-
-// Horizontal scanning laser beam between two points
-function ScanBeam({ start, end, color, speed = 0.2, delay = 0, intensityScale = 1 }) {
- const meshRef = useRef();
-
- const { length, midX, midZ, angle } = useMemo(() => {
- const dx = end[0] - start[0];
- const dz = end[2] - start[2];
- return {
- length: Math.sqrt(dx * dx + dz * dz),
- midX: (start[0] + end[0]) / 2,
- midZ: (start[2] + end[2]) / 2,
- angle: Math.atan2(dz, dx),
- };
- }, [start, end]);
-
- useFrame(({ clock }) => {
- if (!meshRef.current) return;
- const t = clock.getElapsedTime();
- // Slowly fade in and out
- const cycle = ((t * speed + delay) % 4.0);
- meshRef.current.material.opacity = cycle < 2 ?
- Math.sin((cycle / 2) * Math.PI) * 0.06 * intensityScale : 0;
- });
-
- const y = 3 + Math.sin(delay * 7) * 2;
-
- return (
- <mesh
- ref={meshRef}
- position={[midX, y, midZ]}
- rotation={[-Math.PI / 2, 0, angle]}
- >
- <planeGeometry args={[length, 0.03]} />
- <meshBasicMaterial
- color={color}
- transparent
- opacity={0.05 * intensityScale}
- blending={THREE.AdditiveBlending}
- side={THREE.DoubleSide}
- />
- </mesh>
- );
-}
-
-export default function OpenWorldVolumetricLights({ positions, settings }) {
- const { neonAccents } = useOpenWorldPalette();
- const nightFade = 1 - openWorldDayMix(settings);
- const beams = useMemo(() => {
- if (!positions || positions.size < 2) return { lights: [], scans: [] };
-
- const bounds = computeDistrictBounds(positions, 'downtown', { minCount: 2 });
- if (!bounds) return { lights: [], scans: [] };
- const { minX, maxX, minZ, maxZ } = bounds;
-
- const pad = 5;
- const colors = neonAccents;
-
- // Spotlight beams at corners and edges of the city
- const lights = [
- { pos: [minX - pad, 0, minZ - pad], color: colors[0], height: 20, radius: 2.5, intensity: 0.8, phase: 0 },
- { pos: [maxX + pad, 0, minZ - pad], color: colors[1], height: 18, radius: 2, intensity: 0.7, phase: 1.5 },
- { pos: [minX - pad, 0, maxZ + pad], color: colors[4], height: 16, radius: 2, intensity: 0.6, phase: 3 },
- { pos: [maxX + pad, 0, maxZ + pad], color: colors[5], height: 22, radius: 3, intensity: 0.9, phase: 4.5 },
- // Center beam - tall and bright
- { pos: [(minX + maxX) / 2, 0, (minZ + maxZ) / 2], color: colors[0], height: 25, radius: 1.5, intensity: 0.5, phase: 2 },
- ];
-
- // Scanning laser beams across the city
- const scans = [
- { start: [minX - pad - 3, 0, minZ], end: [maxX + pad + 3, 0, minZ], color: colors[0], speed: 0.15, delay: 0 },
- { start: [minX, 0, minZ - pad - 3], end: [minX, 0, maxZ + pad + 3], color: colors[1], speed: 0.12, delay: 1 },
- { start: [minX - pad, 0, maxZ], end: [maxX + pad, 0, maxZ], color: colors[4], speed: 0.18, delay: 2 },
- ];
-
- return { lights, scans };
- }, [positions, neonAccents]);
-
- if (nightFade <= 0.05 || beams.lights.length === 0) return null;
-
- return (
- <group>
- {beams.lights.map((beam, i) => (
- <LightBeam
- key={`beam-${i}`}
- position={beam.pos}
- color={beam.color}
- height={beam.height}
- radius={beam.radius}
- intensity={beam.intensity * nightFade}
- phase={beam.phase}
- />
- ))}
- {beams.scans.map((scan, i) => (
- <ScanBeam
- key={`scan-${i}`}
- start={scan.start}
- end={scan.end}
- color={scan.color}
- speed={scan.speed}
- delay={scan.delay}
- intensityScale={nightFade}
- />
- ))}
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldWater.jsx b/client/src/components/openworld/OpenWorldWater.jsx
deleted file mode 100644
index fd02e9f475..0000000000
--- a/client/src/components/openworld/OpenWorldWater.jsx
+++ /dev/null
@@ -1,101 +0,0 @@
-import { useMemo, useEffect, useRef } from 'react';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { openWorldDayMix, mixHex } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import { WORLD } from '../../utils/openWorldPlan';
-
-// The world-sea below the PortOS archipelago. Deliberately cheap: one tiled wave
-// texture and a soft second swell layer, no reflection/refraction pass. The raised
-// islands provide the shoreline, so the water can continue beneath every causeway
-// and through every inlet without geometry seams.
-
-const NIGHT_WATER = '#050d1c'; // near-black ink so neon reflections read
-const DAY_WATER = '#2e4f6e'; // steel-blue daytime bay
-
-// Procedural wave streaks: sparse horizontal sine ridges on a transparent canvas,
-// tiled + scrolled as the emissive map so the water reads as slowly moving swell.
-const makeWaveTexture = () => {
- const canvas = document.createElement('canvas');
- canvas.width = 256;
- canvas.height = 256;
- const ctx = canvas.getContext('2d');
- ctx.clearRect(0, 0, 256, 256);
- ctx.lineWidth = 0.8;
- for (let row = 0; row < 8; row++) {
- const y = (row + 0.5) * 32;
- const amp = 2 + (row % 3) * 1.5;
- const phase = row * 1.7;
- ctx.strokeStyle = `rgba(255, 255, 255, ${0.07 + (row % 4) * 0.025})`;
- ctx.beginPath();
- for (let x = 0; x <= 256; x += 4) {
- const wy = y + Math.sin(x / 28 + phase) * amp;
- if (x === 0) ctx.moveTo(x, wy);
- else ctx.lineTo(x, wy);
- }
- ctx.stroke();
- }
- const tex = new THREE.CanvasTexture(canvas);
- tex.wrapS = THREE.RepeatWrapping;
- tex.wrapT = THREE.RepeatWrapping;
- tex.repeat.set(18, 10);
- return tex;
-};
-
-export default function OpenWorldWater({ settings }) {
- const { accent } = useOpenWorldPalette();
- const naturalDayMix = openWorldDayMix(settings);
- const dayMix = settings?.explorationMode ? Math.max(0.68, naturalDayMix) : naturalDayMix;
- const waveTex = useMemo(() => makeWaveTexture(), []);
- useEffect(() => () => waveTex.dispose(), [waveTex]);
-
- const swellRef = useRef();
-
- const waterColor = mixHex(NIGHT_WATER, DAY_WATER, dayMix);
- // Night: the swell glows faint accent neon. Day: barely-there white glints.
- const emissiveColor = mixHex(accent, '#dfeaf2', dayMix);
- const emissiveIntensity = 0.28 * (1 - dayMix) + 0.07 * dayMix;
-
- useFrame(({ clock }, delta) => {
- // Two motions at different scales keep the sea from reading as a scrolling decal.
- waveTex.offset.y -= delta * 0.012;
- waveTex.offset.x = Math.sin(clock.getElapsedTime() * 0.05) * 0.03;
- if (swellRef.current) {
- const t = clock.getElapsedTime();
- swellRef.current.rotation.z = Math.sin(t * 0.035) * 0.025;
- swellRef.current.material.opacity = 0.04 + Math.sin(t * 0.22) * 0.012;
- }
- });
-
- const span = WORLD.waterSpan;
-
- return (
- <group>
- <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, WORLD.waterY, 0]}>
- <planeGeometry args={[span * 2, span * 2]} />
- <meshStandardMaterial
- color={waterColor}
- roughness={0.4}
- metalness={0.28}
- emissive={emissiveColor}
- emissiveIntensity={emissiveIntensity}
- emissiveMap={waveTex}
- />
- </mesh>
- <mesh
- ref={swellRef}
- rotation={[-Math.PI / 2, 0, 0]}
- position={[0, WORLD.waterY + 0.018, 0]}
- >
- <ringGeometry args={[34, 185, 96]} />
- <meshBasicMaterial
- color={mixHex(accent, '#dff7ff', dayMix * 0.7)}
- transparent
- opacity={0.04}
- blending={THREE.AdditiveBlending}
- depthWrite={false}
- />
- </mesh>
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldWeather.jsx b/client/src/components/openworld/OpenWorldWeather.jsx
deleted file mode 100644
index 80903cb1f1..0000000000
--- a/client/src/components/openworld/OpenWorldWeather.jsx
+++ /dev/null
@@ -1,142 +0,0 @@
-import { useRef, useMemo } from 'react';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-
-// Rain particle shader - elongated drops falling downward
-const RAIN_VERT = `
- attribute float speed;
- attribute float offset;
- uniform float uTime;
- varying float vAlpha;
- void main() {
- vec3 pos = position;
- // Animate downward, looping
- float t = mod(uTime * speed + offset, 1.0);
- pos.y = mix(25.0, -2.0, t);
- vAlpha = smoothstep(0.0, 0.1, t) * smoothstep(1.0, 0.8, t);
- vec4 mvPosition = modelViewMatrix * vec4(pos, 1.0);
- // Elongated point to simulate a rain streak
- gl_PointSize = 2.5 * (150.0 / -mvPosition.z);
- gl_Position = projectionMatrix * mvPosition;
- }
-`;
-
-const RAIN_FRAG = `
- varying float vAlpha;
- void main() {
- // Elongated vertical drop shape
- vec2 uv = gl_PointCoord - vec2(0.5);
- float d = length(vec2(uv.x * 3.0, uv.y));
- if (d > 0.5) discard;
- float alpha = smoothstep(0.5, 0.1, d) * vAlpha * 0.4;
- gl_FragColor = vec4(0.4, 0.7, 1.0, alpha);
- }
-`;
-
-// Lightning flash - brief bright flash across the scene
-function LightningFlash({ active, playSfx }) {
- const lightRef = useRef();
- const flashState = useRef({ nextFlash: 0, intensity: 0, flickerCount: 0 });
- // Pick the flash origin once — inlining Math.random() in the JSX below re-rolls the
- // light position on every render, teleporting the lightning flash around the scene.
- const flashPosition = useMemo(() => [Math.random() * 40 - 20, 30, Math.random() * 40 - 20], []);
-
- useFrame(({ clock }) => {
- if (!lightRef.current || !active) {
- if (lightRef.current) lightRef.current.intensity = 0;
- return;
- }
- const t = clock.getElapsedTime();
- const state = flashState.current;
-
- if (t > state.nextFlash && state.intensity === 0) {
- // Trigger new flash (every 8-20 seconds when active)
- state.intensity = 2.0 + Math.random() * 3.0;
- state.flickerCount = 2 + Math.floor(Math.random() * 3);
- state.nextFlash = t + 8 + Math.random() * 12;
- playSfx?.('lightning');
- }
-
- if (state.intensity > 0) {
- // Rapid decay with flicker
- state.intensity *= 0.85;
- if (state.flickerCount > 0 && state.intensity < 0.5) {
- state.intensity = 1.5 + Math.random() * 2;
- state.flickerCount--;
- }
- if (state.intensity < 0.05) state.intensity = 0;
- }
-
- lightRef.current.intensity = state.intensity;
- });
-
- return (
- <pointLight
- ref={lightRef}
- position={flashPosition}
- color="#b4d4ff"
- intensity={0}
- distance={100}
- decay={1.5}
- />
- );
-}
-
-export default function OpenWorldWeather({ stoppedCount = 0, totalCount = 1, playSfx }) {
- const pointsRef = useRef();
- const matRef = useRef();
-
- // Weather intensity based on system health (more stopped = more rain)
- const healthRatio = totalCount > 0 ? stoppedCount / totalCount : 0;
- const rainIntensity = healthRatio; // 0 = clear, 1 = heavy rain
- const showLightning = healthRatio > 0.3;
-
- const rainCount = Math.floor(rainIntensity * 400);
-
- const { positions, speeds, offsets } = useMemo(() => {
- const count = 400; // Max particles, we'll show a subset based on intensity
- const pos = new Float32Array(count * 3);
- const spd = new Float32Array(count);
- const off = new Float32Array(count);
-
- for (let i = 0; i < count; i++) {
- pos[i * 3] = (Math.random() - 0.5) * 60;
- pos[i * 3 + 1] = Math.random() * 25;
- pos[i * 3 + 2] = (Math.random() - 0.5) * 60;
- spd[i] = 0.3 + Math.random() * 0.5;
- off[i] = Math.random();
- }
-
- return { positions: pos, speeds: spd, offsets: off };
- }, []);
-
- useFrame(({ clock }) => {
- if (matRef.current) {
- matRef.current.uniforms.uTime.value = clock.getElapsedTime();
- }
- });
-
- if (rainCount < 5) return null;
-
- return (
- <group>
- <points ref={pointsRef}>
- <bufferGeometry drawRange={{ start: 0, count: rainCount }}>
- <bufferAttribute attach="attributes-position" count={positions.length / 3} array={positions} itemSize={3} />
- <bufferAttribute attach="attributes-speed" count={speeds.length} array={speeds} itemSize={1} />
- <bufferAttribute attach="attributes-offset" count={offsets.length} array={offsets} itemSize={1} />
- </bufferGeometry>
- <shaderMaterial
- ref={matRef}
- vertexShader={RAIN_VERT}
- fragmentShader={RAIN_FRAG}
- uniforms={{ uTime: { value: 0 } }}
- transparent
- blending={THREE.AdditiveBlending}
- depthWrite={false}
- />
- </points>
- {showLightning && <LightningFlash active={showLightning} playSfx={playSfx} />}
- </group>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldXpBadge.jsx b/client/src/components/openworld/OpenWorldXpBadge.jsx
deleted file mode 100644
index a1f09bd31e..0000000000
--- a/client/src/components/openworld/OpenWorldXpBadge.jsx
+++ /dev/null
@@ -1,144 +0,0 @@
-import { useState, useEffect, useRef, useMemo } from 'react';
-import { computeAgeView, diffXp, birthDateCta } from '../../utils/characterXp';
-
-// OpenWorld character HUD badge (roadmap 2.11; reframed in #2673). A compact floating panel
-// showing the current **age-based level** (life experience = age) and a progress bar =
-// fractional part of the current year of life (progress toward the next birthday), plus HP
-// when known. useOpenWorldData polls the character on an interval; this component still diffs
-// successive snapshots and fires a transient flash on XP gain (xp survives as a cumulative
-// stat) — a louder, longer celebratory flash when the level ticks up (a birthday).
-//
-// Animations are self-contained (transient state + inline transition) so the component
-// stays standalone and doesn't depend on global keyframes.
-export default function OpenWorldXpBadge({ character, onOpenDestination }) {
- const view = useMemo(() => computeAgeView(character), [character]);
-
- const prevCharRef = useRef(null);
- // burst.kind: null | 'gain' | 'levelup' — drives the flash overlay; burst.seq forces a
- // re-trigger even when two consecutive bursts are the same kind.
- const [burst, setBurst] = useState({ kind: null, seq: 0, gained: 0 });
- const burstTimerRef = useRef(null);
-
- useEffect(() => {
- const prev = prevCharRef.current;
- prevCharRef.current = character;
- if (!character) return;
-
- const { gained, leveledUp } = diffXp(prev, character);
- // Fire on an XP gain (cyan) OR a birthday age-level tick (amber) — a birthday rarely
- // coincides with an XP gain, so it must be able to burst on its own.
- if (gained <= 0 && !leveledUp) return;
-
- setBurst(b => ({ kind: leveledUp ? 'levelup' : 'gain', seq: b.seq + 1, gained }));
- clearTimeout(burstTimerRef.current);
- burstTimerRef.current = setTimeout(
- () => setBurst(b => ({ ...b, kind: null })),
- leveledUp ? 2200 : 1100,
- );
- }, [character]);
-
- // Clear the pending flash timer on unmount so it can't fire into a dead component.
- useEffect(() => () => clearTimeout(burstTimerRef.current), []);
-
- // Render nothing until we have a real character — avoids a flash of a zeroed badge
- // before the first poll lands (absent vs. a legitimate level-1 zero-XP character).
- if (!character) return null;
-
- const leveling = burst.kind === 'levelup';
- const gaining = burst.kind !== null;
- const barColor = leveling ? '#f59e0b' : '#06b6d4';
- const pct = Math.round(view.progress * 100);
- // No usable level → show a prompt instead of NaN and send the click to the Goal Monuments
- // district. The CTA distinguishes a genuinely unset date ("set") from a present-but-unusable
- // one ("fix" — invalid/future/unreadable), so we never tell the user to set a date they already
- // entered (#2757).
- // birthDateCta returns null for 'ok' (a real level exists). It's non-null whenever hasBirthDate
- // is false under the server's status⟺level invariant, but read every cta.* through `?.`/`??`
- // anyway so a hypothetical invariant break degrades to the SET prompt instead of crashing the
- // whole HUD — the same defensive gate CharacterSheet and OpenWorldHudCompact use (#2757, claude review).
- const cta = view.hasBirthDate ? null : birthDateCta(view.birthDateStatus);
- const levelLabel = view.hasBirthDate ? `LV ${view.level}` : (cta?.badgeLabel ?? 'LV —');
- const destination = view.hasBirthDate ? 'artifacts' : 'goals';
- // A present-but-unusable date (invalid/future/unreadable) renders in the warning color, matching
- // the CharacterSheet "fix" prompt and the changelog's promise (#2757). Never true while leveling.
- const fixState = cta?.kind === 'fix';
-
- return (
- <div className="absolute bottom-4 right-4 pointer-events-auto">
- <button
- type="button"
- onClick={() => onOpenDestination?.(destination)}
- title={view.hasBirthDate ? 'Teleport to Hall of Achievements' : 'Teleport to Goal Monuments'}
- className={`openworld-hud-panel relative block w-40 sm:w-48 px-3 py-2.5 overflow-hidden text-left transition-all duration-300 hover:bg-cyan-500/10 ${
- leveling
- ? 'border-amber-400/70 shadow-[0_0_16px_rgba(245,158,11,0.5)]'
- : fixState
- ? 'border-port-warning/60 shadow-[0_0_12px_rgba(245,158,11,0.35)]'
- : gaining
- ? 'border-cyan-400/70 shadow-[0_0_12px_rgba(6,182,212,0.45)]'
- : 'border-cyan-500/30'
- }`}
- >
- {/* Transient flash overlay keyed on burst.seq so it re-mounts each gain */}
- {gaining && (
- <div
- key={burst.seq}
- className="absolute inset-0 pointer-events-none"
- style={{
- background: leveling
- ? 'radial-gradient(circle at 50% 50%, rgba(245,158,11,0.45), transparent 70%)'
- : 'radial-gradient(circle at 50% 50%, rgba(6,182,212,0.35), transparent 70%)',
- animation: leveling ? 'cos-pulse 0.55s ease-in-out 3' : 'cos-pulse 0.5s ease-in-out 2',
- }}
- />
- )}
-
- <div className="relative flex items-center justify-between gap-2">
- <div className="flex items-center gap-2">
- <span
- className={`font-pixel text-base tracking-wider ${leveling ? 'text-amber-300' : fixState ? 'text-port-warning' : 'text-cyan-300'}`}
- style={{ textShadow: leveling ? '0 0 10px rgba(245,158,11,0.7)' : fixState ? '0 0 8px rgba(245,158,11,0.5)' : '0 0 8px rgba(6,182,212,0.5)' }}
- >
- {levelLabel}
- </span>
- </div>
- {gaining && burst.gained > 0 && (
- <span
- className={`font-pixel text-[10px] tracking-wide ${leveling ? 'text-amber-300' : 'text-emerald-400'}`}
- style={{ textShadow: '0 0 6px currentColor' }}
- >
- +{burst.gained}
- </span>
- )}
- </div>
-
- {/* Progress bar toward the next birthday (fractional part of the current year) */}
- <div className="relative mt-1.5 w-full h-1.5 bg-gray-800/70 rounded-full overflow-hidden">
- <div
- className="h-full rounded-full transition-all duration-700"
- style={{
- width: `${pct}%`,
- backgroundColor: barColor,
- boxShadow: `0 0 6px ${barColor}`,
- }}
- />
- </div>
-
- <div className="relative flex items-center justify-between mt-1">
- <span className="font-pixel text-[8px] text-gray-500 tracking-wider">
- {view.hasBirthDate ? `${pct}% TO NEXT` : (cta?.badgeCaption ?? 'SET BIRTH DATE')}
- </span>
- {view.hp != null && view.maxHp != null && (
- <span
- className={`font-pixel text-[8px] tracking-wider ${
- view.maxHp > 0 && view.hp / view.maxHp <= 0.25 ? 'text-red-400' : 'text-rose-300/70'
- }`}
- >
- {view.hp}/{view.maxHp} HP
- </span>
- )}
- </div>
- </button>
- </div>
- );
-}
diff --git a/client/src/components/openworld/OpenWorldXpBadge.test.jsx b/client/src/components/openworld/OpenWorldXpBadge.test.jsx
deleted file mode 100644
index 2504dbb0d8..0000000000
--- a/client/src/components/openworld/OpenWorldXpBadge.test.jsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import { render, screen } from '@testing-library/react';
-import { MemoryRouter } from 'react-router';
-import OpenWorldXpBadge from './OpenWorldXpBadge';
-
-const renderBadge = (character) =>
- render(
- <MemoryRouter initialEntries={['/openworld']}>
- <OpenWorldXpBadge character={character} />
- </MemoryRouter>,
- );
-
-describe('OpenWorldXpBadge birth-date CTA (#2757)', () => {
- it('shows the numeric level and % caption when a level exists', () => {
- renderBadge({ level: 7, ageYears: 7.5, birthDateStatus: 'ok' });
- expect(screen.getByText('LV 7')).toBeInTheDocument();
- expect(screen.queryByText('LV —')).not.toBeInTheDocument();
- expect(screen.queryByText('LV !')).not.toBeInTheDocument();
- });
-
- it('shows the SET prompt (LV —) for a genuinely unset date', () => {
- renderBadge({ level: null, ageYears: null, birthDateStatus: 'unset' });
- expect(screen.getByText('LV —')).toBeInTheDocument();
- expect(screen.getByText('SET BIRTH DATE')).toBeInTheDocument();
- expect(screen.getByTitle('Teleport to Goal Monuments')).toBeInTheDocument();
- });
-
- it('shows the FIX prompt (LV !) in the warning style for a present-but-unusable date', () => {
- for (const status of ['invalid', 'future', 'unreadable']) {
- const { unmount } = renderBadge({ level: null, ageYears: null, birthDateStatus: status });
- expect(screen.getByText('LV !')).toBeInTheDocument();
- expect(screen.getByText('FIX BIRTH DATE')).toBeInTheDocument();
- // Warning-colored, not the normal cyan accent (changelog promise).
- expect(screen.getByText('LV !').className).toMatch(/text-port-warning/);
- unmount();
- }
- });
-
- it('degrades to the SET prompt instead of crashing if status is "ok" with no level (invariant break)', () => {
- // birthDateCta('ok') is null; the badge must not throw on cta.badgeLabel — it falls back to
- // the SET prompt (claude review defensive gate). Rendering without throwing is the assertion.
- renderBadge({ level: null, ageYears: null, birthDateStatus: 'ok' });
- expect(screen.getByText('LV —')).toBeInTheDocument();
- });
-});
diff --git a/client/src/components/openworld/PlayerAvatar.jsx b/client/src/components/openworld/PlayerAvatar.jsx
deleted file mode 100644
index f956a3c7e9..0000000000
--- a/client/src/components/openworld/PlayerAvatar.jsx
+++ /dev/null
@@ -1,282 +0,0 @@
-import { useRef } from 'react';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import { dampFactor, EYE_HEIGHT, solveVehicleSuspensionPose, VEHICLE } from '../../utils/openWorldPlayerRig';
-import { openWorldTerrainHeight } from '../../utils/openWorldPlan';
-import { mixHex } from './openWorldConstants';
-
-// A small procedural utility cart keeps the player local to OpenWorld. Its orchard-orange
-// body, canvas roof, timber cargo bed, and chunky suspension belong to the village instead
-// of reading like a generic sports car dropped into it.
-const CAR_LENGTH = VEHICLE.bodyLength;
-const CAR_WIDTH = VEHICLE.bodyWidth;
-const WHEEL_RADIUS = 0.34;
-const WHEEL_X = CAR_WIDTH * 0.57;
-const WHEEL_Z = CAR_LENGTH * 0.31;
-const _rootTarget = new THREE.Vector3();
-const _suspensionTarget = new THREE.Quaternion();
-const _bankTarget = new THREE.Quaternion();
-const _identityTarget = new THREE.Quaternion();
-const _bankAxis = new THREE.Vector3(0, 0, 1);
-
-export default function PlayerAvatar({ rigRef }) {
- const { accent, surface } = useOpenWorldPalette();
- const rootRef = useRef();
- const bodyRef = useRef();
- const hoverRingRef = useRef();
- const underglowRef = useRef();
- const thrusterRef = useRef();
- const brakeLightRef = useRef();
- const skidSmokeRef = useRef();
- const wheelSteerRefs = useRef([]);
- const wheelRollRefs = useRef([]);
-
- const bodyColor = mixHex('#e98b55', accent, 0.1);
- const bodyShadow = mixHex('#36544f', accent, 0.12);
- const glassColor = mixHex('#6ca7aa', accent, 0.14);
- const wheelColor = '#17212d';
- useFrame(({ clock }, delta) => {
- const root = rootRef.current;
- const body = bodyRef.current;
- const rig = rigRef?.current;
- if (!root || !body || !rig) return;
-
- const t = clock.getElapsedTime();
- const hovering = rig.state === 'hover';
- const moving = rig.state === 'walk' || rig.state === 'run';
- const running = rig.state === 'run';
- const follow = dampFactor(10, delta);
- const targetY = rig.position.y - EYE_HEIGHT + (hovering ? 0.25 : 0);
- const speed = rig.speed || 0;
- const speedRatio = Math.min(1, Math.abs(speed) / 38);
- const isBoosting = Math.abs(speed) > 24 || (running && speedRatio > 0.6);
- const isBraking = speed < -0.1 || (rig.skid > 0.5 && speedRatio > 0.2);
-
- root.position.lerp(_rootTarget.set(rig.position.x, targetY, rig.position.z), follow);
- root.rotation.y = rig.facing;
- root.rotation.z = 0;
-
- const terrainHeight = openWorldTerrainHeight(rig.position.x, rig.position.z);
- const suspension = solveVehicleSuspensionPose({
- x: rig.position.x,
- z: rig.position.z,
- heading: rig.facing,
- centerHeight: terrainHeight,
- halfWidth: WHEEL_X,
- halfLength: WHEEL_Z,
- heightAt: openWorldTerrainHeight,
- });
- _suspensionTarget.set(
- suspension.rotation.x,
- suspension.rotation.y,
- suspension.rotation.z,
- suspension.rotation.w,
- );
- _bankTarget.setFromAxisAngle(_bankAxis, rig.bank * 0.24);
- _suspensionTarget.multiply(_bankTarget);
-
- const bob = hovering
- ? 0.2 + Math.sin(t * 2.4) * 0.07
- : Math.sin(t * (7 + speedRatio * 8)) * 0.018 * speedRatio;
- const rideOffset = hovering || rig.jumping ? 0 : suspension.translation.y;
- body.position.y += (rideOffset + bob - body.position.y) * follow;
- body.quaternion.slerp(hovering || rig.jumping ? _identityTarget : _suspensionTarget, dampFactor(12, delta));
-
- const wheelSpeed = speed !== 0 ? speed / WHEEL_RADIUS : running ? 15 : moving ? 8 : 0;
- wheelSteerRefs.current.forEach((steerPivot, index) => {
- if (!steerPivot) return;
- // Steering, suspension travel, and rolling live on separate nested pivots. Combining
- // them on one Euler made the cylinder's roll axis precess as the front wheels turned,
- // which read as a wobble even on flat ground.
- steerPivot.rotation.y = index >= 2 ? (rig.wheelAngle || 0) : 0;
- const wheelOffset = hovering || rig.jumping ? -0.08 : suspension.wheelTravel[index];
- steerPivot.position.y += ((WHEEL_RADIUS + wheelOffset) - steerPivot.position.y) * dampFactor(15, delta);
- const rollPivot = wheelRollRefs.current[index];
- if (rollPivot) rollPivot.rotation.y -= wheelSpeed * delta;
- });
-
- if (hoverRingRef.current) {
- hoverRingRef.current.rotation.z = t * 0.75;
- hoverRingRef.current.material.opacity = hovering ? 0.72 : 0.22;
- hoverRingRef.current.scale.setScalar(hovering ? 1 + Math.sin(t * 3) * 0.08 : 1);
- }
- if (underglowRef.current) {
- underglowRef.current.material.opacity = (hovering ? 0.42 : moving ? 0.26 : 0.16) + Math.sin(t * 4) * 0.025;
- }
-
- if (thrusterRef.current) {
- const flameScale = isBoosting ? 1 + Math.sin(t * 28) * 0.3 : 0.001;
- thrusterRef.current.scale.set(flameScale, flameScale, isBoosting ? 1.4 + Math.sin(t * 32) * 0.4 : 0.001);
- thrusterRef.current.visible = isBoosting;
- }
-
- if (brakeLightRef.current) {
- brakeLightRef.current.material.emissiveIntensity = isBraking ? 1.2 : 0.28;
- }
-
- if (skidSmokeRef.current) {
- const isSkidding = rig.skid > 0.35 && speedRatio > 0.3;
- skidSmokeRef.current.visible = isSkidding;
- if (isSkidding) {
- skidSmokeRef.current.rotation.z = t * 4;
- skidSmokeRef.current.scale.setScalar(0.8 + Math.sin(t * 16) * 0.25);
- }
- }
- });
-
- const setWheelSteerRef = (index) => (node) => {
- wheelSteerRefs.current[index] = node;
- };
-
- const setWheelRollRef = (index) => (node) => {
- wheelRollRefs.current[index] = node;
- };
-
- return (
- <group ref={rootRef}>
- <group ref={bodyRef}>
- {/* Low, friendly utility-cart body. */}
- <mesh position={[0, 0.48, 0]} castShadow receiveShadow>
- <boxGeometry args={[CAR_WIDTH, 0.42, CAR_LENGTH]} />
- <meshStandardMaterial {...surface} color={bodyColor} roughness={0.58} metalness={0.22} />
- </mesh>
- <mesh position={[0, 0.76, -CAR_LENGTH * 0.12]} castShadow receiveShadow>
- <boxGeometry args={[CAR_WIDTH * 0.72, 0.3, CAR_LENGTH * 0.38]} />
- <meshStandardMaterial {...surface} color={glassColor} roughness={0.24} metalness={0.36} transparent opacity={0.92} />
- </mesh>
- <mesh position={[0, 0.7, -CAR_LENGTH * 0.38]} castShadow receiveShadow>
- <boxGeometry args={[CAR_WIDTH * 0.62, 0.08, CAR_LENGTH * 0.2]} />
- <meshStandardMaterial {...surface} color={bodyShadow} roughness={0.5} metalness={0.3} />
- </mesh>
-
- {/* Canvas sun roof and roll bars give the cart a memorable toy-like profile. */}
- {[-1, 1].map((side) => (
- <mesh key={`rollbar-${side}`} position={[side * CAR_WIDTH * 0.31, 1.03, -CAR_LENGTH * 0.08]} castShadow>
- <boxGeometry args={[0.07, 0.56, 0.07]} />
- <meshStandardMaterial color="#584b3d" roughness={0.82} metalness={0.12} />
- </mesh>
- ))}
- <mesh position={[0, 1.3, -CAR_LENGTH * 0.08]} castShadow receiveShadow>
- <boxGeometry args={[CAR_WIDTH * 0.82, 0.08, CAR_LENGTH * 0.5]} />
- <meshStandardMaterial color="#f4d8a8" roughness={0.94} metalness={0} />
- </mesh>
- <mesh position={[0, 1.345, -CAR_LENGTH * 0.08]}>
- <boxGeometry args={[CAR_WIDTH * 0.55, 0.012, CAR_LENGTH * 0.34]} />
- <meshStandardMaterial color={accent} roughness={0.7} metalness={0} />
- </mesh>
-
- {/* Timber cargo bed makes this a working village runabout. */}
- <mesh position={[0, 0.75, CAR_LENGTH * 0.3]} castShadow receiveShadow>
- <boxGeometry args={[CAR_WIDTH * 0.74, 0.13, CAR_LENGTH * 0.3]} />
- <meshStandardMaterial color="#8b5e3c" roughness={0.9} metalness={0} />
- </mesh>
- {[-1, 1].map((side) => (
- <mesh key={`cargo-rail-${side}`} position={[side * CAR_WIDTH * 0.33, 0.91, CAR_LENGTH * 0.31]} castShadow>
- <boxGeometry args={[0.07, 0.24, CAR_LENGTH * 0.34]} />
- <meshStandardMaterial color="#5c402f" roughness={0.92} metalness={0} />
- </mesh>
- ))}
- <mesh position={[0.18, 0.93, CAR_LENGTH * 0.31]} rotation={[0.08, 0.18, 0]} castShadow>
- <boxGeometry args={[0.42, 0.28, 0.48]} />
- <meshStandardMaterial color="#d6a64d" roughness={0.92} metalness={0} />
- </mesh>
- <mesh position={[-0.25, 0.92, CAR_LENGTH * 0.31]} rotation={[0, 0, Math.PI / 2]} castShadow>
- <cylinderGeometry args={[0.13, 0.13, 0.42, 12]} />
- <meshStandardMaterial color="#7ea89a" roughness={0.95} metalness={0} />
- </mesh>
-
- {/* Sturdy bumpers and running boards ground the silhouette. */}
- <mesh position={[0, 0.24, -CAR_LENGTH * 0.52]} castShadow>
- <boxGeometry args={[CAR_WIDTH * 0.94, 0.09, 0.16]} />
- <meshStandardMaterial color="#584b3d" roughness={0.84} metalness={0.1} />
- </mesh>
- {[-1, 1].map((side) => (
- <mesh key={`step-${side}`} position={[side * (CAR_WIDTH * 0.54), 0.27, 0]} castShadow>
- <boxGeometry args={[0.12, 0.08, CAR_LENGTH * 0.5]} />
- <meshStandardMaterial color="#584b3d" roughness={0.84} metalness={0.1} />
- </mesh>
- ))}
- <mesh position={[0, 0.39, -CAR_LENGTH * 0.53]}>
- <boxGeometry args={[CAR_WIDTH * 0.88, 0.08, 0.1]} />
- <meshStandardMaterial color={accent} emissive={accent} emissiveIntensity={0.45} />
- </mesh>
- <mesh ref={brakeLightRef} position={[0, 0.4, CAR_LENGTH * 0.53]}>
- <boxGeometry args={[CAR_WIDTH * 0.82, 0.07, 0.08]} />
- <meshStandardMaterial color="#ef5252" emissive="#ef5252" emissiveIntensity={0.28} />
- </mesh>
- <mesh position={[0, 0.3, CAR_LENGTH * 0.55]} castShadow>
- <boxGeometry args={[CAR_WIDTH * 0.9, 0.08, 0.12]} />
- <meshStandardMaterial color="#584b3d" roughness={0.84} metalness={0.1} />
- </mesh>
-
- <group ref={thrusterRef} position={[0, 0.38, CAR_LENGTH * 0.58]} visible={false}>
- {[-CAR_WIDTH * 0.24, CAR_WIDTH * 0.24].map((offsetX, i) => (
- <mesh key={`flame-${i}`} position={[offsetX, 0, 0]} rotation={[Math.PI / 2, 0, 0]}>
- <coneGeometry args={[0.14, 0.65, 8]} />
- <meshBasicMaterial color="#38bdf8" transparent opacity={0.88} blending={THREE.AdditiveBlending} />
- </mesh>
- ))}
- </group>
-
- {/* Front lamps and a little village pennant make the cart readable in both views. */}
- {[-1, 1].map((side) => (
- <mesh key={`lamp-${side}`} position={[side * CAR_WIDTH * 0.3, 0.55, -CAR_LENGTH * 0.53]}>
- <boxGeometry args={[0.13, 0.08, 0.035]} />
- <meshBasicMaterial color="#fff5cf" toneMapped={false} />
- </mesh>
- ))}
- <mesh position={[0, 1.56, -CAR_LENGTH * 0.08]} castShadow>
- <cylinderGeometry args={[0.018, 0.018, 0.44, 6]} />
- <meshStandardMaterial color="#584b3d" roughness={0.8} />
- </mesh>
- <mesh position={[0.13, 1.69, -CAR_LENGTH * 0.08]} rotation={[0, 0, -0.18]} castShadow>
- <coneGeometry args={[0.16, 0.3, 3]} />
- <meshStandardMaterial color={accent} emissive={accent} emissiveIntensity={0.12} roughness={0.8} />
- </mesh>
-
- {/* Wheels are deliberately chunky: the actor should read as a vehicle at a glance. */}
- {[
- [-WHEEL_X, WHEEL_Z],
- [WHEEL_X, WHEEL_Z],
- [-WHEEL_X, -WHEEL_Z],
- [WHEEL_X, -WHEEL_Z],
- ].map(([x, z], index) => (
- <group key={`wheel-${index}`} ref={setWheelSteerRef(index)} position={[x, WHEEL_RADIUS, z]}>
- <group rotation={[0, 0, Math.PI / 2]}>
- <group ref={setWheelRollRef(index)}>
- <mesh castShadow receiveShadow>
- <cylinderGeometry args={[WHEEL_RADIUS, WHEEL_RADIUS, 0.16, 12]} />
- <meshStandardMaterial color={wheelColor} roughness={0.88} metalness={0.08} />
- </mesh>
- <mesh>
- <cylinderGeometry args={[WHEEL_RADIUS * 0.44, WHEEL_RADIUS * 0.44, 0.17, 10]} />
- <meshStandardMaterial color={bodyShadow} roughness={0.48} metalness={0.4} />
- </mesh>
- </group>
- </group>
- </group>
- ))}
- </group>
-
- <group ref={skidSmokeRef} position={[0, 0.08, WHEEL_Z]} visible={false}>
- {[-WHEEL_X, WHEEL_X].map((wx, i) => (
- <mesh key={`smoke-${i}`} position={[wx, 0, 0]}>
- <sphereGeometry args={[0.22, 6, 6]} />
- <meshBasicMaterial color="#94a3b8" transparent opacity={0.45} blending={THREE.AdditiveBlending} depthWrite={false} />
- </mesh>
- ))}
- </group>
-
- {/* Ground feedback is intentionally simpler than the old robot's large footprint. */}
- <mesh ref={underglowRef} rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.025, 0]}>
- <circleGeometry args={[0.9, 24]} />
- <meshBasicMaterial color={accent} transparent opacity={0.16} blending={THREE.AdditiveBlending} depthWrite={false} side={THREE.DoubleSide} />
- </mesh>
- <mesh ref={hoverRingRef} rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.04, 0]}>
- <torusGeometry args={[0.82, 0.025, 6, 24]} />
- <meshBasicMaterial color={accent} transparent opacity={0.22} blending={THREE.AdditiveBlending} depthWrite={false} />
- </mesh>
- </group>
- );
-}
diff --git a/client/src/components/openworld/PlayerController.jsx b/client/src/components/openworld/PlayerController.jsx
deleted file mode 100644
index c527c4d47d..0000000000
--- a/client/src/components/openworld/PlayerController.jsx
+++ /dev/null
@@ -1,628 +0,0 @@
-import { useRef, useEffect, useCallback, useMemo, Suspense } from 'react';
-import { useThree, useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import PlayerAvatar from './PlayerAvatar';
-import useKeyCapture from '../../hooks/useKeyCapture';
-import ErrorBoundary from '../ErrorBoundary';
-import {
- THIRD_PERSON, EYE_HEIGHT, DEFAULT_SPAWN_Z,
- thirdPersonCamera, resolveBoom, nextBoomZoom,
- dampFactor, dampAngle, moveFacing, avatarState, bankAngle, stepVehicle,
- moveWithCollisions, PLAYER_COLLISION_RADIUS, VEHICLE_COLLISION,
-} from '../../utils/openWorldPlayerRig';
-import {
- isWalkable, openWorldTerrainHeight, VILLAGE_COLLIDERS, WORLD,
-} from '../../utils/openWorldPlan';
-import { BOROUGH_PARAMS, BUILDING_PARAMS, PROCESS_BUILDING_PARAMS } from './openWorldConstants';
-import { regionWarpPadPosition, getRegion } from '../../utils/openWorldRegions';
-import { checkSpeedPadOverlap } from '../../utils/openWorldSpeedPads';
-import { checkShardCollection, getCollectiblesList } from '../../utils/openWorldCollectibles';
-import { detectProximity, getResolvedLandmarks } from '../../utils/openWorldProximity';
-
-const WALK_SPEED = 10;
-const SPRINT_SPEED = 20;
-const VERTICAL_SPEED = 8;
-const JUMP_SPEED = 10; // initial upward velocity of a Space jump (units/s)
-const GRAVITY = -26; // downward acceleration applied through the jump arc (units/s²)
-const MAX_CAMERA_HEIGHT = 160;
-const BUILDING_FLYOVER_HEIGHT = 12; // above this the player clears rooftops, so skip collision
-const AIRBORNE_CLEARANCE = 0.6; // above the local terrain eye-line the avatar reads as flying
-const MOUSE_SENSITIVITY = 0.002;
-const PITCH_LIMIT = Math.PI / 2 - 0.02;
-const POSE_REPORT_INTERVAL_SECONDS = 0.1;
-
-// Frame-loop scratch vectors (module scope — no per-frame allocation in useFrame).
-const _forward = new THREE.Vector3();
-const _right = new THREE.Vector3();
-const _moveDir = new THREE.Vector3();
-const _nextPos = new THREE.Vector3();
-const _lookDir = new THREE.Vector3();
-const _camTarget = new THREE.Vector3();
-const _lookTarget = new THREE.Vector3();
-
-// Exploration-mode player rig. One mutable rig object is the single source of truth for
-// the player's pose; both camera modes (and the third-person avatar) read from it:
-// - 'third' (default): a damped follow camera behind a visible low-poly rover with
-// arcade vehicle handling, building-aware boom shortening, and speed-weighted steering.
-// - 'first' (V to toggle): the classic invisible first-person camera.
-// WASD/arrows, shift boost, E/Q vertical, F interact, R respawn, H horn, pointer-lock mouselook,
-// scroll-wheel camera zoom, speed boost pads, cyber shards collection, landmark discovery, and
-// world boundaries.
-export default function PlayerController({
- keysRef,
- positions,
- onBuildingProximity,
- onBuildingClick,
- onToggleCameraView,
- apps,
- active,
- transitioning = false,
- cameraView = 'third',
- teleport = null,
- warpPads = [],
- landmarks = getResolvedLandmarks(),
- onWarpPadInteract,
- onWarpPadProximity,
- onProximityChange,
- easterEggs = [],
- shards = getCollectiblesList(),
- collectedShardIds = new Set(),
- onCollectShard,
- onPlayerPoseChange,
- playSfx,
- mobileInputRef = null,
- playerActionRef = null,
-}) {
- const { camera, gl } = useThree();
- const rigRef = useRef({
- position: new THREE.Vector3(0, EYE_HEIGHT, 0),
- yaw: THIRD_PERSON.isometricYaw, // camera heading; forward is (-sin yaw, 0, -cos yaw)
- heading: THIRD_PERSON.isometricYaw, // rover heading; camera orbit can look independently
- pitch: 0,
- facing: THIRD_PERSON.isometricYaw, // the character's body heading (damped toward movement direction)
- bank: 0, // lean into turns
- speed: 0, // signed rover speed; positive forward, negative reverse
- wheelAngle: 0,
- skid: 0,
- vy: 0, // vertical velocity for the Space jump arc (E/Q free-fly zeroes it)
- jumping: false, // an active Space jump arc — gates gravity so E/Q free-fly holds altitude
- state: 'idle',
- });
- // Stable array view of the positions Map for the per-frame boom collision test —
- // re-collected only when the layout itself changes, never per frame.
- const buildingList = useMemo(() => [
- ...VILLAGE_COLLIDERS.map(({ x, z, height }) => ({ x, z, height })),
- ...(positions ? [...positions.values()] : []),
- ], [positions]);
- // Movement colliders mirror the rendered footprint: app buildings are boxes and
- // process pylons are round. The boom keeps its own larger camera-only padding above.
- const collisionShapes = useMemo(() => {
- const appById = new Map((apps || []).map((app) => [app.id, app]));
- const shapes = [...VILLAGE_COLLIDERS];
-
- positions?.forEach((pos, appId) => {
- shapes.push({
- shape: 'box',
- x: pos.x,
- z: pos.z,
- halfWidth: pos.halfWidth ?? BUILDING_PARAMS.width / 2,
- halfDepth: pos.halfDepth ?? BUILDING_PARAMS.depth / 2,
- });
-
- const app = appById.get(appId);
- const processCount = pos.compact || app?.archived || !Array.isArray(app?.processes) ? 0 : app.processes.length;
- const processRadius = Math.max(PROCESS_BUILDING_PARAMS.width, PROCESS_BUILDING_PARAMS.depth) * 0.58;
- for (let index = 0; index < processCount; index += 1) {
- const angle = (index / processCount) * Math.PI * 2;
- shapes.push({
- shape: 'circle',
- x: pos.x + Math.cos(angle) * BOROUGH_PARAMS.processRingRadius,
- z: pos.z + Math.sin(angle) * BOROUGH_PARAMS.processRingRadius,
- radius: processRadius,
- });
- }
- });
-
- return shapes;
- }, [apps, positions]);
- const warpPadList = useMemo(
- () => warpPads.map((region) => ({ region, position: regionWarpPadPosition(region) })).filter((entry) => entry.position),
- [warpPads],
- );
- const proximityTargetRef = useRef(null);
- const lastBoostPadRef = useRef(null);
- const boostOverrideTimerRef = useRef(0);
- const localCollectedSetRef = useRef(new Set(collectedShardIds));
- const poseReportElapsedRef = useRef(POSE_REPORT_INTERVAL_SECONDS);
- const lastSpawnRef = useRef(null);
- const pointerLockedRef = useRef(false);
- // Camera boom zoom: `boomZoomTargetRef` is the player's chosen multiplier, `boomZoomRef`
- // the smoothed value the camera actually uses this frame.
- const boomZoomTargetRef = useRef(1);
- const boomZoomRef = useRef(1);
-
- useEffect(() => {
- localCollectedSetRef.current = new Set(collectedShardIds);
- }, [collectedShardIds]);
-
- // Damped third-person aim point — lags the true lookAt so the aim stays smooth.
- const lookRef = useRef(new THREE.Vector3());
- const lookInitRef = useRef(false);
-
- // Re-snap the aim whenever the camera mode flips (V) so the lerp never starts
- // from a stale aim point left by the previous third-person stint.
- useEffect(() => {
- const rig = rigRef.current;
- // A camera-mode change is also a clean handoff: first person inherits the current
- // rover heading, and returning to the rover starts with the camera's current aim.
- rig.heading = rig.yaw;
- rig.facing = rig.yaw;
- rig.speed = 0;
- rig.wheelAngle = 0;
- rig.skid = 0;
- lookInitRef.current = false;
- }, [cameraView]);
-
- // Initialize spawn position
- useEffect(() => {
- const rig = rigRef.current;
- if (!active) {
- // Orbital mode pauses the frame loop. Clear a partially applied throttle so
- // dropping back into the street never resumes with stale momentum.
- rig.speed = 0;
- rig.wheelAngle = 0;
- rig.skid = 0;
- rig.vy = 0;
- rig.jumping = false;
- return;
- }
- if (lastSpawnRef.current) {
- rig.position.copy(lastSpawnRef.current);
- } else {
- // Every install enters at the authored Port overlook. App count must not move the
- // player's starting line onto Archive Rise or behind a data-driven building row.
- rig.position.set(0, EYE_HEIGHT + openWorldTerrainHeight(0, DEFAULT_SPAWN_Z), DEFAULT_SPAWN_Z);
- rig.yaw = THIRD_PERSON.isometricYaw;
- rig.heading = THIRD_PERSON.isometricYaw;
- rig.pitch = 0;
- rig.facing = THIRD_PERSON.isometricYaw;
- rig.speed = 0;
- rig.wheelAngle = 0;
- rig.skid = 0;
- lastSpawnRef.current = rig.position.clone();
- }
- // Publish the spawn immediately on the next frame so the mini-map never shows
- // the previous street position while the player is dropping back in.
- poseReportElapsedRef.current = POSE_REPORT_INTERVAL_SECONDS;
- lookInitRef.current = false;
- }, [active, positions]);
-
- // Fast travel while on foot: warping to a region drops the player at its arrival point
- // instead of moving only the orbital camera. `teleport.token` is the trigger — the same
- // destination can be re-selected, and a plain {x,z} identity check would swallow the
- // second warp. Keyed on the token alone so a re-render with an equal object is a no-op.
- const teleportToken = teleport?.token ?? null;
- useEffect(() => {
- if (!active || teleportToken === null || !teleport) return;
- const rig = rigRef.current;
- rig.position.set(teleport.x, EYE_HEIGHT + openWorldTerrainHeight(teleport.x, teleport.z), teleport.z);
- // Face the destination from the same diagonal heading as the default isometric view.
- rig.yaw = THIRD_PERSON.isometricYaw;
- rig.heading = THIRD_PERSON.isometricYaw;
- rig.pitch = 0;
- rig.facing = THIRD_PERSON.isometricYaw;
- rig.speed = 0;
- rig.wheelAngle = 0;
- rig.skid = 0;
- rig.vy = 0;
- rig.jumping = false;
- lastSpawnRef.current = rig.position.clone();
- poseReportElapsedRef.current = POSE_REPORT_INTERVAL_SECONDS;
- lookInitRef.current = false;
- // `teleport` is read for its coordinates but is not the trigger — see above.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [active, teleportToken]);
-
- // Pointer lock management
- const handleClick = useCallback(() => {
- if (!active) return;
- gl.domElement.requestPointerLock?.();
- }, [active, gl.domElement]);
-
- const handlePointerLockChange = useCallback(() => {
- pointerLockedRef.current = document.pointerLockElement === gl.domElement;
- }, [gl.domElement]);
-
- const handleMouseMove = useCallback((e) => {
- if (!pointerLockedRef.current || !active) return;
- const rig = rigRef.current;
- rig.yaw -= e.movementX * MOUSE_SENSITIVITY;
- rig.pitch -= e.movementY * MOUSE_SENSITIVITY;
- rig.pitch = Math.max(-PITCH_LIMIT, Math.min(PITCH_LIMIT, rig.pitch));
- }, [active]);
-
- // Wheel zooms the third-person boom. Bound on the canvas (not window) so HUD panels
- // and dialogs keep their own scroll; preventDefault stops any residual page scroll.
- const handleWheel = useCallback((e) => {
- if (!active) return;
- e.preventDefault();
- boomZoomTargetRef.current = nextBoomZoom(boomZoomTargetRef.current, e.deltaY);
- }, [active]);
-
- useEffect(() => {
- if (!active) {
- // Release pointer lock when leaving exploration mode
- if (document.pointerLockElement === gl.domElement) {
- document.exitPointerLock?.();
- }
- // Save last position for re-entry
- lastSpawnRef.current = rigRef.current.position.clone();
- return;
- }
-
- const canvas = gl.domElement;
- canvas.addEventListener('click', handleClick);
- document.addEventListener('pointerlockchange', handlePointerLockChange);
- document.addEventListener('mousemove', handleMouseMove);
- canvas.addEventListener('wheel', handleWheel, { passive: false });
-
- return () => {
- canvas.removeEventListener('click', handleClick);
- document.removeEventListener('pointerlockchange', handlePointerLockChange);
- document.removeEventListener('mousemove', handleMouseMove);
- canvas.removeEventListener('wheel', handleWheel);
- if (document.pointerLockElement === canvas) {
- document.exitPointerLock?.();
- }
- };
- }, [active, gl.domElement, handleClick, handlePointerLockChange, handleMouseMove, handleWheel]);
-
- // F interacts with the nearby target; V swaps first/third person; H plays horn; R returns to drop-in.
- const interact = useCallback(() => {
- if (!active) return;
- const target = proximityTargetRef.current;
- if (!target) return;
- if (target.type === 'warpPad') {
- onWarpPadInteract?.(target.raw);
- } else if (target.type === 'building') {
- onBuildingClick?.(target.raw);
- } else if (target.type === 'landmark') {
- if (target.regionId) {
- const region = getRegion(target.regionId);
- if (region) onWarpPadInteract?.(region);
- }
- } else if (target.type === 'easterEgg') {
- playSfx?.('eggDiscover');
- }
- }, [active, onBuildingClick, onWarpPadInteract, playSfx]);
-
- useEffect(() => {
- if (!active) return;
- const handleKeyDown = (e) => {
- const key = e.key.toLowerCase();
- if (key === 'f') {
- interact();
- } else if (key === 'v') {
- onToggleCameraView?.();
- } else if (key === 'h') {
- playSfx?.('horn');
- } else if (key === 'r' && lastSpawnRef.current) {
- rigRef.current.position.copy(lastSpawnRef.current);
- rigRef.current.yaw = THIRD_PERSON.isometricYaw;
- rigRef.current.heading = THIRD_PERSON.isometricYaw;
- rigRef.current.pitch = 0;
- rigRef.current.facing = THIRD_PERSON.isometricYaw;
- rigRef.current.speed = 0;
- rigRef.current.wheelAngle = 0;
- rigRef.current.skid = 0;
- rigRef.current.vy = 0;
- rigRef.current.jumping = false;
- lookInitRef.current = false;
- }
- };
- window.addEventListener('keydown', handleKeyDown);
- return () => window.removeEventListener('keydown', handleKeyDown);
- }, [active, interact, onToggleCameraView, playSfx]);
-
- useEffect(() => {
- if (!playerActionRef) return undefined;
- playerActionRef.current = { interact };
- return () => {
- if (playerActionRef.current?.interact === interact) playerActionRef.current = null;
- };
- }, [interact, playerActionRef]);
-
- // In exploration mode, Space is the jump key — claim it in the capture phase so it
- // never reaches the global voice push-to-talk hotkey (VoiceWidget listens for the
- // same key on `window`). Claiming the keydown is also what stops useKeyboardControls
- // from recording the hold, hence the manual add here; the release needs no handler,
- // because that keyup is NOT claimed and useKeyboardControls clears the key itself.
- useKeyCapture({
- enabled: active,
- onKeyDown: (e) => {
- if (e.code !== 'Space') return false;
- keysRef.current.add(' ');
- return true;
- },
- });
-
- // Drop a held jump when exploration mode ends — the keyup that would have cleared it
- // can land after the mode switch, and the rig would resume mid-jump on re-entry.
- useEffect(() => () => { keysRef.current.delete(' '); }, [active, keysRef]);
-
- useFrame((_, delta) => {
- if (!active) return;
- const rig = rigRef.current;
-
- const keys = keysRef.current;
- const mobileInput = mobileInputRef?.current;
- if (mobileInput) {
- const lookDeltaX = mobileInput.lookDeltaX || 0;
- const lookDeltaY = mobileInput.lookDeltaY || 0;
- mobileInput.lookDeltaX = 0;
- mobileInput.lookDeltaY = 0;
- rig.yaw -= lookDeltaX * MOUSE_SENSITIVITY;
- rig.pitch = Math.max(-PITCH_LIMIT, Math.min(PITCH_LIMIT, rig.pitch - lookDeltaY * MOUSE_SENSITIVITY));
- }
-
- const isVehicle = cameraView === 'third';
- const isSprinting = keys.has('shift') || Boolean(mobileInput?.boost);
- const speed = (isSprinting ? SPRINT_SPEED : WALK_SPEED) * delta;
- const verticalSpeed = (isSprinting ? SPRINT_SPEED : VERTICAL_SPEED) * delta;
- const keyboardForward = (keys.has('w') || keys.has('arrowup') ? 1 : 0)
- - (keys.has('s') || keys.has('arrowdown') ? 1 : 0);
- const keyboardStrafe = (keys.has('d') || keys.has('arrowright') ? 1 : 0)
- - (keys.has('a') || keys.has('arrowleft') ? 1 : 0);
- const forwardInput = THREE.MathUtils.clamp(keyboardForward - (mobileInput?.moveY || 0), -1, 1);
- const strafeInput = THREE.MathUtils.clamp(keyboardStrafe + (mobileInput?.moveX || 0), -1, 1);
- const brake = keys.has('control') || keys.has('x');
- const previousHeading = rig.heading;
- const moveDir = _moveDir.set(0, 0, 0);
- if (isVehicle) {
- // Third-person is a rover: left/right steer the nose, while the analog stick's
- // horizontal axis remains the same steering input on touch devices.
- const drive = stepVehicle({
- speed: rig.speed,
- heading: rig.heading,
- wheelAngle: rig.wheelAngle,
- throttle: forwardInput,
- steer: strafeInput,
- boost: isSprinting,
- brake,
- delta,
- });
- rig.speed = drive.speed;
- rig.heading = drive.heading;
- rig.wheelAngle = drive.wheelAngle;
- rig.skid = drive.skid;
- moveDir.set(drive.displacement.x, 0, drive.displacement.z);
- } else {
- // First person remains the useful free-roam inspection mode.
- const forward = _forward.set(-Math.sin(rig.yaw), 0, -Math.cos(rig.yaw));
- const right = _right.set(-forward.z, 0, forward.x);
- moveDir
- .addScaledVector(forward, forwardInput)
- .addScaledVector(right, strafeInput);
- if (moveDir.lengthSq() > 0) moveDir.normalize().multiplyScalar(speed);
- rig.heading = rig.yaw;
- rig.speed = 0;
- rig.wheelAngle = 0;
- rig.skid = 0;
- }
- const hasHorizontal = moveDir.lengthSq() > 0;
-
- // Vertical: E/Q is direct free-fly and takes precedence — it cancels any jump and
- // holds altitude when released (no gravity). Gravity applies ONLY during an active
- // Space jump arc.
- const flyDir = (keys.has('e') ? 1 : 0) - (keys.has('q') ? 1 : 0);
- const currentGroundY = EYE_HEIGHT + openWorldTerrainHeight(rig.position.x, rig.position.z);
- const grounded = rig.position.y <= currentGroundY + 1e-3;
- let dy = 0;
- if (flyDir !== 0) {
- rig.jumping = false;
- rig.vy = 0;
- dy = flyDir * verticalSpeed;
- } else {
- if ((keys.has(' ') || mobileInput?.jump) && grounded && !rig.jumping) {
- rig.vy = JUMP_SPEED;
- rig.jumping = true;
- playSfx?.('jump');
- }
- if (rig.jumping) {
- rig.vy += GRAVITY * delta; // gravity through the arc
- dy = rig.vy * delta;
- }
- }
- const hasMotionIntent = hasHorizontal || dy !== 0;
- let movedHorizontally = false;
-
- if (hasMotionIntent) {
- const startX = rig.position.x;
- const startZ = rig.position.z;
- const nextPos = _nextPos.copy(rig.position).add(moveDir);
- nextPos.y += dy;
-
- // Collision detection is skipped above rooftop height so the player can fly over
- // the city.
- let blocked = false;
- if (hasHorizontal && nextPos.y < BUILDING_FLYOVER_HEIGHT) {
- const collision = moveWithCollisions({
- position: rig.position,
- displacement: { x: moveDir.x, z: moveDir.z },
- colliders: collisionShapes,
- body: isVehicle
- ? { type: 'vehicle', heading: rig.heading, ...VEHICLE_COLLISION }
- : { type: 'circle', radius: PLAYER_COLLISION_RADIUS },
- });
- nextPos.x = collision.x;
- nextPos.z = collision.z;
- blocked = collision.blocked;
- if (!isWalkable(nextPos.x, nextPos.z)) {
- blocked = true;
- nextPos.x = rig.position.x;
- nextPos.z = rig.position.z;
- }
- }
-
- const nextGroundY = EYE_HEIGHT + openWorldTerrainHeight(nextPos.x, nextPos.z);
- if (!rig.jumping && flyDir === 0) nextPos.y = nextGroundY;
-
- if (blocked) {
- if (isVehicle) rig.speed = 0;
- }
- // World bounds
- nextPos.x = Math.max(-WORLD.bound, Math.min(WORLD.bound, nextPos.x));
- nextPos.y = Math.max(nextGroundY, Math.min(MAX_CAMERA_HEIGHT, nextPos.y));
- nextPos.z = Math.max(-WORLD.bound, Math.min(WORLD.bound, nextPos.z));
-
- // Landed
- if (nextPos.y <= nextGroundY + 1e-3 || nextPos.y >= MAX_CAMERA_HEIGHT) {
- if (rig.jumping && nextPos.y <= nextGroundY + 1e-3) {
- playSfx?.('land');
- }
- rig.vy = 0;
- rig.jumping = false;
- }
- movedHorizontally = Math.abs(nextPos.x - startX) > 1e-5 || Math.abs(nextPos.z - startZ) > 1e-5;
- rig.position.copy(nextPos);
- }
-
- // Speed boost pads detection and duration handling
- const activeBoostPad = checkSpeedPadOverlap(rig.position);
- if (activeBoostPad && lastBoostPadRef.current !== activeBoostPad.id) {
- lastBoostPadRef.current = activeBoostPad.id;
- boostOverrideTimerRef.current = 1.4;
- if (isVehicle) {
- rig.speed = Math.max(rig.speed, activeBoostPad.boostSpeed);
- }
- playSfx?.('boostPad');
- } else if (!activeBoostPad) {
- lastBoostPadRef.current = null;
- }
-
- if (boostOverrideTimerRef.current > 0) {
- boostOverrideTimerRef.current -= delta;
- }
-
- // Cyber Shards collectible detection
- const collectedShards = checkShardCollection(rig.position, shards, localCollectedSetRef.current);
- if (collectedShards.length > 0) {
- collectedShards.forEach((shard) => {
- localCollectedSetRef.current.add(shard.id);
- onCollectShard?.(shard);
- playSfx?.('collect');
- });
- }
-
- // Pose classification for the avatar + facing/banking toward movement.
- const moving = movedHorizontally || dy !== 0;
- rig.state = avatarState({
- moving,
- sprinting: isVehicle ? Math.abs(rig.speed) > 16 || (isSprinting && moving) : isSprinting && moving,
- airborne: rig.position.y > EYE_HEIGHT + openWorldTerrainHeight(rig.position.x, rig.position.z) + AIRBORNE_CLEARANCE,
- });
- if (isVehicle) {
- const prevFacing = rig.facing;
- rig.facing = dampAngle(rig.facing, rig.heading, dampFactor(14, delta));
- const headingStep = delta > 0 ? (dampAngle(previousHeading, rig.heading, 1) - previousHeading) / delta : 0;
- const turnBank = bankAngle(headingStep, 0.24, 0.045) + rig.wheelAngle * rig.skid * 0.08;
- rig.bank += (turnBank - rig.bank) * dampFactor(8, delta);
- if (!movedHorizontally && Math.abs(prevFacing - rig.heading) < 0.001) rig.facing = rig.heading;
- } else if (movedHorizontally) {
- const target = moveFacing(rig.yaw, { forward: forwardInput, strafe: strafeInput });
- const prevFacing = rig.facing;
- rig.facing = dampAngle(rig.facing, target, dampFactor(10, delta));
- const yawRate = delta > 0 ? (rig.facing - prevFacing) / delta : 0;
- rig.bank += (bankAngle(yawRate) - rig.bank) * dampFactor(6, delta);
- } else {
- rig.bank += (0 - rig.bank) * dampFactor(6, delta);
- }
-
- const proxTarget = detectProximity({
- playerPos: rig.position,
- apps,
- positions,
- warpPads: warpPadList,
- easterEggs,
- landmarks,
- });
-
- if (proxTarget?.id !== proximityTargetRef.current?.id || proxTarget?.type !== proximityTargetRef.current?.type) {
- proximityTargetRef.current = proxTarget;
- onBuildingProximity?.(proxTarget?.type === 'building' ? proxTarget.raw : null);
- onWarpPadProximity?.(proxTarget?.type === 'warpPad' ? proxTarget.raw : null);
- onProximityChange?.(proxTarget);
- }
-
- const reportingSpeed = isVehicle
- ? rig.speed
- : (hasHorizontal ? (isSprinting ? SPRINT_SPEED : WALK_SPEED) * (forwardInput < 0 ? -1 : 1) : 0);
-
- // DOM telemetry does not need the 60fps camera cadence. A time-based 10Hz publish
- // stays smooth at both 30fps and 120fps while avoiding ~20 full page renders/sec.
- poseReportElapsedRef.current += delta;
- if (poseReportElapsedRef.current >= POSE_REPORT_INTERVAL_SECONDS) {
- poseReportElapsedRef.current %= POSE_REPORT_INTERVAL_SECONDS;
- onPlayerPoseChange?.({
- x: rig.position.x,
- y: rig.position.y,
- z: rig.position.z,
- heading: rig.heading,
- speed: reportingSpeed,
- skid: rig.skid,
- state: rig.state,
- jumping: rig.jumping,
- airborne: rig.position.y > EYE_HEIGHT + openWorldTerrainHeight(rig.position.x, rig.position.z) + AIRBORNE_CLEARANCE,
- boosting: isSprinting,
- });
- }
-
- // Camera application
- if (transitioning) return;
-
- if (cameraView === 'first') {
- camera.position.copy(rig.position);
- const lookDir = _lookDir.set(
- -Math.sin(rig.yaw) * Math.cos(rig.pitch),
- Math.sin(rig.pitch),
- -Math.cos(rig.yaw) * Math.cos(rig.pitch),
- );
- camera.lookAt(_lookTarget.copy(rig.position).add(lookDir));
- return;
- }
-
- // Third person: boom behind camera yaw. The wheel multiplier eases toward its
- // target so a fast scroll produces a smooth dolly instead of a jump cut.
- boomZoomRef.current += (boomZoomTargetRef.current - boomZoomRef.current) * dampFactor(9, delta);
- const desired = thirdPersonCamera({
- pos: rig.position,
- yaw: rig.yaw,
- pitch: rig.pitch,
- pitchOffset: THIRD_PERSON.isometricPitch,
- boom: THIRD_PERSON.boom * boomZoomRef.current,
- });
- const anchor = { x: rig.position.x, y: rig.position.y + THIRD_PERSON.lookHeight, z: rig.position.z };
- const { point: resolvedCam } = resolveBoom({ anchor, camera: desired.camera, buildings: buildingList });
-
- if (!lookInitRef.current) {
- lookRef.current.set(desired.lookAt.x, desired.lookAt.y, desired.lookAt.z);
- lookInitRef.current = true;
- }
- const posFactor = dampFactor(THIRD_PERSON.camDampRate, delta);
- const lookFactor = dampFactor(THIRD_PERSON.lookDampRate, delta);
- camera.position.lerp(_camTarget.set(resolvedCam.x, resolvedCam.y, resolvedCam.z), posFactor);
- lookRef.current.lerp(_lookTarget.set(desired.lookAt.x, desired.lookAt.y, desired.lookAt.z), lookFactor);
- camera.lookAt(lookRef.current);
- });
-
- if (!active) return null;
-
- if (cameraView !== 'third') return null;
- return (
- <ErrorBoundary fallback={null}>
- <Suspense fallback={null}>
- <PlayerAvatar rigRef={rigRef} />
- </Suspense>
- </ErrorBoundary>
- );
-}
diff --git a/client/src/components/openworld/PlayerController.test.jsx b/client/src/components/openworld/PlayerController.test.jsx
deleted file mode 100644
index 11d5b2b7f3..0000000000
--- a/client/src/components/openworld/PlayerController.test.jsx
+++ /dev/null
@@ -1,122 +0,0 @@
-import { describe, it, expect, beforeEach, vi } from 'vitest';
-import { render, fireEvent, act } from '@testing-library/react';
-import * as THREE from 'three';
-import { installVoiceHotkeySpy } from '../../test/voiceHotkeySpy';
-
-// PlayerController is an r3f component, but its Space handling is plain DOM wiring. The
-// fiber hooks are stubbed so it can mount in jsdom without a WebGL canvas; rendering in
-// first-person camera mode returns null, so nothing three.js-specific ever paints.
-// The useFrame stub CAPTURES the per-frame callback so tests can drive the frame loop
-// (the path where a thrown TypeError would kill scene rendering) without WebGL.
-const frameCallbacks = [];
-vi.mock('@react-three/fiber', () => ({
- useThree: () => ({ camera: new THREE.PerspectiveCamera(), gl: { domElement: document.createElement('canvas') } }),
- useFrame: (cb) => { frameCallbacks.push(cb); },
-}));
-
-const PlayerController = (await import('./PlayerController')).default;
-
-describe('PlayerController Space (jump) capture', () => {
- const voiceHotkey = installVoiceHotkeySpy();
- let keysRef;
-
- beforeEach(() => { keysRef = { current: new Set() }; frameCallbacks.length = 0; });
-
- const renderRig = (props = {}) => render(
- <PlayerController keysRef={keysRef} active cameraView="first" positions={new Map()} apps={[]} {...props} />,
- );
-
- it('holds the jump key without leaking Space to the global voice hotkey', () => {
- renderRig();
-
- act(() => { fireEvent.keyDown(document.body, { key: ' ', code: 'Space' }); });
-
- expect(keysRef.current.has(' ')).toBe(true);
- expect(voiceHotkey()).not.toHaveBeenCalled();
- });
-
- it('ignores Space typed into a text field', () => {
- // The old guard read document.activeElement, so an un-focused field did not
- // suppress the jump; the shared isEditableTarget reads the event target.
- const { container } = renderRig();
- const input = document.createElement('input');
- container.appendChild(input);
-
- act(() => { fireEvent.keyDown(input, { key: ' ', code: 'Space' }); });
-
- expect(keysRef.current.has(' ')).toBe(false);
- });
-
- it('stands down while a dialog is open, so Space can activate its buttons', () => {
- const { container } = renderRig();
- const dialog = document.createElement('div');
- dialog.setAttribute('aria-modal', 'true');
- container.appendChild(dialog);
-
- act(() => { fireEvent.keyDown(document.body, { key: ' ', code: 'Space' }); });
-
- expect(keysRef.current.has(' ')).toBe(false);
- expect(voiceHotkey()).toHaveBeenCalledTimes(1);
- });
-
- it('drops a held jump when exploration mode ends', () => {
- const { rerender } = renderRig();
- act(() => { fireEvent.keyDown(document.body, { key: ' ', code: 'Space' }); });
- expect(keysRef.current.has(' ')).toBe(true);
-
- act(() => {
- rerender(
- <PlayerController keysRef={keysRef} active={false} cameraView="first" positions={new Map()} apps={[]} />,
- );
- });
-
- expect(keysRef.current.has(' ')).toBe(false);
- });
-
- it('binds nothing while exploration mode is off', () => {
- renderRig({ active: false });
-
- act(() => { fireEvent.keyDown(document.body, { key: ' ', code: 'Space' }); });
-
- expect(keysRef.current.has(' ')).toBe(false);
- expect(voiceHotkey()).toHaveBeenCalledTimes(1);
- });
-
- it('runs a frame without throwing on a non-iterable easterEggs payload', () => {
- // Regression (#4702): the scene passed computeEasterEggs' wrapper object as
- // easterEggs; the per-frame detectProximity loop then threw "not iterable"
- // every frame, halting the render loop — on a default install the world never
- // painted at all (mobile: "all I see is sky"). The frame path must survive.
- renderRig({ easterEggs: { eggs: [], total: 0, hasData: false } });
- const runFrame = frameCallbacks.at(-1);
- expect(typeof runFrame).toBe('function');
-
- expect(() => act(() => runFrame({}, 1 / 60))).not.toThrow();
- });
-
- it('runs a frame with a well-formed easterEggs array without throwing', () => {
- renderRig({
- easterEggs: [{ id: 'leet', label: '1337', hint: 'LEET', position: [0, 1.2, 52] }],
- });
- const runFrame = frameCallbacks.at(-1);
-
- expect(() => act(() => runFrame({}, 1 / 60))).not.toThrow();
- });
-
- it('publishes HUD pose telemetry immediately, then at a time-based 10Hz cadence', () => {
- const onPlayerPoseChange = vi.fn();
- renderRig({ onPlayerPoseChange });
- const runFrame = frameCallbacks.at(-1);
-
- act(() => runFrame({}, 0.016));
- expect(onPlayerPoseChange).toHaveBeenCalledTimes(1);
-
- act(() => {
- for (let frame = 0; frame < 4; frame += 1) runFrame({}, 0.02);
- });
- expect(onPlayerPoseChange).toHaveBeenCalledTimes(1);
-
- act(() => runFrame({}, 0.02));
- expect(onPlayerPoseChange).toHaveBeenCalledTimes(2);
- });
-});
diff --git a/client/src/components/openworld/ProcessBuilding.jsx b/client/src/components/openworld/ProcessBuilding.jsx
deleted file mode 100644
index 3802f5bbd8..0000000000
--- a/client/src/components/openworld/ProcessBuilding.jsx
+++ /dev/null
@@ -1,124 +0,0 @@
-import { useRef, useMemo, useEffect } from 'react';
-import { useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
-import { PROCESS_BUILDING_PARAMS, mixHex } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-
-// Process status → color, unified with the themed building map (so 'online' follows
-// the active theme accent and the semantic colors match a stopped/missing *app*):
-// 'stopped' is the same red as a stopped app (was amber), 'not_found' the same purple
-// (was indigo). PM2's hard-failure states ("errored"; some legacy callers send "error")
-// read as the same red as stopped — both mean "down".
-const getProcessColor = (status, building) => {
- switch (status) {
- case 'online': return building.online;
- case 'stopped':
- case 'errored':
- case 'error': return building.stopped;
- case 'not_found':
- default: return building.not_found;
- }
-};
-
-export default function ProcessBuilding({ pm2Status, position, seed, dimmed = false, dayMix = 0 }) {
- const { building, buildingBody, surface } = useOpenWorldPalette();
- const blinkRef = useRef();
- const glowRef = useRef();
- const ringRef = useRef();
-
- const status = pm2Status?.status || 'not_found';
- const color = getProcessColor(status, building);
- const { width, depth } = PROCESS_BUILDING_PARAMS;
- const radius = Math.max(width, depth) * 0.58;
- const dimMul = dimmed ? 0.25 : 1;
- // Match the main Building's daytime treatment — sheds neon, lightens to a lit solid.
- const bodyColor = mixHex(buildingBody, mixHex('#9aa0ac', color, 0.12), dayMix);
- const neonFade = 1 - dayMix;
-
- // Height based on status + seed variation
- const height = useMemo(() => {
- if (status === 'online') {
- return 2.0 + (seed % 100) / 100 * 1.5; // 2.0 - 3.5
- }
- return 1.5;
- }, [status, seed]);
-
- const bodyGeom = useMemo(() => new THREE.CylinderGeometry(radius * 0.82, radius, height, 6), [radius, height]);
- const edgesGeom = useMemo(() => new THREE.EdgesGeometry(bodyGeom), [bodyGeom]);
-
- // edgesGeom is handed to <lineSegments> via a `geometry` prop, so R3F does not
- // manage its disposal the way it would a JSX <edgesGeometry> child. `height`
- // (and thus this geometry) is keyed on `status` — an online process is taller
- // than a stopped/errored one — so every status flip would otherwise strand the
- // previous geometry's GPU buffers, same leak class as Building.jsx's windowTexture.
- useEffect(() => {
- return () => {
- bodyGeom.dispose();
- edgesGeom.dispose();
- };
- }, [bodyGeom, edgesGeom]);
-
- // Rotation to face center (passed via position array)
- const rotation = position[3] || 0;
-
- useFrame(({ clock }) => {
- const t = clock.getElapsedTime();
- if (blinkRef.current) {
- blinkRef.current.material.opacity = ((Math.sin(t * 3 + seed) > 0.3) ? 0.8 : 0.1) * dimMul * neonFade;
- }
- if (glowRef.current) {
- const base = status === 'online'
- ? 0.15 + Math.sin(t * 1.5 + seed) * 0.08
- : 0.08;
- glowRef.current.material.opacity = base * dimMul * neonFade;
- }
- if (ringRef.current) ringRef.current.rotation.z = t * 0.45 + seed;
- });
-
- return (
- <group position={[position[0], 0, position[2]]} rotation={[0, rotation, 0]}>
- {/* Hexagonal process pylon: a readable status token rather than a second tiny building. */}
- <mesh position={[0, height / 2, 0]} geometry={bodyGeom}>
- <meshStandardMaterial
- {...surface}
- color={bodyColor}
- emissive={color}
- emissiveIntensity={(status === 'online' ? 0.2 : 0.08) * dimMul * (1 - dayMix * 0.9)}
- roughness={dayMix > 0.5 ? 0.9 : 1}
- transparent
- opacity={0.9 * dimMul}
- />
- </mesh>
-
- {/* Neon wireframe edges (soften to a plain outline by day) */}
- <lineSegments position={[0, height / 2, 0]} geometry={edgesGeom}>
- <lineBasicMaterial color={dayMix > 0.5 ? mixHex('#4a4f57', color, 0.15) : color} transparent opacity={(0.8 - dayMix * 0.55) * dimMul} />
- </lineSegments>
-
- {/* Neon top cap */}
- <mesh position={[0, height + 0.01, 0]}>
- <cylinderGeometry args={[radius * 0.86, radius * 0.86, 0.05, 6]} />
- <meshBasicMaterial color={color} transparent opacity={0.4 * dimMul * (1 - dayMix * 0.6)} />
- </mesh>
-
- {/* A quiet rotating ring makes the pylon readable at a glance while keeping labels
- reserved for the focused main building. */}
- <mesh ref={ringRef} rotation={[Math.PI / 2, 0, 0]} position={[0, 0.09, 0]}>
- <torusGeometry args={[radius * 0.78, 0.014, 6, 12]} />
- <meshBasicMaterial color={color} transparent opacity={0.42 * dimMul * (0.35 + neonFade * 0.65)} />
- </mesh>
-
- {/* Blinking tip light */}
- <mesh ref={blinkRef} position={[0, height + 0.12, 0]}>
- <sphereGeometry args={[0.03, 6, 6]} />
- <meshBasicMaterial color={color} transparent opacity={0.8 * dimMul} />
- </mesh>
-
- {/* Base glow circle */}
- <mesh ref={glowRef} rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.01, 0]}>
- <circleGeometry args={[0.6, 16]} />
- <meshBasicMaterial color={color} transparent opacity={0.15 * dimMul} side={THREE.DoubleSide} />
- </mesh>
- </group>
- );
-}
diff --git a/client/src/components/openworld/WorldGround.jsx b/client/src/components/openworld/WorldGround.jsx
deleted file mode 100644
index 74a6298f6b..0000000000
--- a/client/src/components/openworld/WorldGround.jsx
+++ /dev/null
@@ -1,177 +0,0 @@
-import { useRef, useMemo } from 'react';
-import { useFrame } from '@react-three/fiber';
-import { Grid } from '@react-three/drei';
-import * as THREE from 'three';
-import { getTimeOfDayPreset, openWorldDayMix, mixHex, seededRand } from './openWorldConstants';
-import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import { WORLD } from '../../utils/openWorldPlan';
-
-// The city ground stops at the master plan's shoreline (z = WORLD.shorelineZ) — the bay
-// (OpenWorldWater) owns everything north of it. Both the pavement plane and the neon grid are
-// sized/offset to end exactly at the water's edge.
-const GROUND_HALF = WORLD.landHalf;
-const GROUND_DEPTH = GROUND_HALF - WORLD.shorelineZ; // shoreline → +landHalf
-const GROUND_CENTER_Z = (GROUND_HALF + WORLD.shorelineZ) / 2;
-
-// Reflective puddle/wet-ground patches
-function WetPatch({ position, size, color, dayMix = 0 }) {
- const ref = useRef();
-
- useFrame(({ clock }) => {
- if (!ref.current) return;
- const t = clock.getElapsedTime();
- // Neon puddle reflections are a wet-night look — fade them out by day.
- ref.current.material.opacity = (0.1 + Math.sin(t * 0.8 + position[0] * 3) * 0.04) * (1 - dayMix);
- });
-
- return (
- <mesh ref={ref} rotation={[-Math.PI / 2, 0, 0]} position={position}>
- <circleGeometry args={[size, 16]} />
- <meshBasicMaterial
- color={color}
- transparent
- opacity={0.1}
- blending={THREE.AdditiveBlending}
- side={THREE.DoubleSide}
- />
- </mesh>
- );
-}
-
-// Rolling fog layer with animated opacity
-function RollingFog({ dayMix = 0 }) {
- const ref = useRef();
- const { ground } = useOpenWorldPalette();
-
- useFrame(({ clock }) => {
- if (!ref.current) return;
- const t = clock.getElapsedTime();
- ref.current.material.opacity = (0.025 + Math.sin(t * 0.15) * 0.012) * (1 - dayMix);
- ref.current.position.z = Math.sin(t * 0.05) * 3;
- });
-
- return (
- <mesh ref={ref} rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.5, 0]}>
- <planeGeometry args={[100, 100]} />
- <meshBasicMaterial
- color={ground}
- transparent
- opacity={0.012}
- blending={THREE.AdditiveBlending}
- side={THREE.DoubleSide}
- />
- </mesh>
- );
-}
-
-export default function WorldGround({ settings }) {
- const { ground, neonAccents, lowPoly } = useOpenWorldPalette();
- // Wet-night dressing is now an art-direction/performance decision, not a user-facing
- // toggle. The ground itself must always render: the old REFLECTIONS setting accidentally
- // removed the base plane on low quality, leaving only the debug-like grid underneath the
- // player. Vibes stays clean and matte; Cyber City keeps a small wet-night layer above the
- // always-present pavement.
- const wetEffectsEnabled = !lowPoly && settings?.effectiveTier !== 'low';
- const groundMatRef = useRef();
-
- const timeOfDay = settings?.timeOfDay ?? 'sunset';
- const skyTheme = settings?.skyTheme ?? 'cyberpunk';
- const preset = getTimeOfDayPreset(timeOfDay, skyTheme);
- const dayMix = openWorldDayMix(settings);
- const groundColorTarget = useRef(new THREE.Color(preset.groundColor ?? '#0a0a20'));
- groundColorTarget.current.set(preset.groundColor ?? '#0a0a20');
- const targetRoughness = preset.groundRoughness ?? 0.7;
- const targetMetalness = 0.4 * (1 - dayMix) + 0.04 * dayMix;
-
- // The neon grid + additive fog follow the themed accent (palette.ground tracks the
- // theme). At night they read as accent neon; by day the grid mutes to faint pavement
- // lines and the glow fog fades out.
- const accent = ground;
- // The original cyber grid is useful orientation in the neon world, but a dense
- // cyan debug grid fights the open-air Vibes landscape. Keep a sparse, low-contrast
- // field there so the player can still read distance without feeling boxed into a UI.
- const gridSectionColor = lowPoly
- ? mixHex('#6d8f77', '#c5a77d', dayMix)
- : mixHex(accent, '#bcc4cc', dayMix);
- const gridCellColor = lowPoly
- ? mixHex('#557866', '#9eb39a', dayMix)
- : mixHex(mixHex(accent, '#0a1420', 0.5), '#a7afb8', dayMix);
- const groundFogOpacity = 0.045 * (1 - dayMix);
-
- useFrame((_, delta) => {
- if (!groundMatRef.current) return;
- const lf = Math.min(1, delta * 3);
- groundMatRef.current.color.lerp(groundColorTarget.current, lf);
- groundMatRef.current.roughness += (targetRoughness - groundMatRef.current.roughness) * lf;
- groundMatRef.current.metalness += (targetMetalness - groundMatRef.current.metalness) * lf;
- });
-
- const puddles = useMemo(() => {
- const result = [];
- const rand = seededRand(137);
- const colors = neonAccents;
- const count = wetEffectsEnabled ? 40 : 0;
-
- for (let i = 0; i < count; i++) {
- result.push({
- id: `puddle-${i}`,
- position: [(rand() - 0.5) * 50, 0.005, (rand() - 0.5) * 50],
- size: 0.5 + rand() * 2.5,
- color: colors[Math.floor(rand() * colors.length)],
- });
- }
- return result;
- }, [wetEffectsEnabled, neonAccents]);
-
- return (
- <group>
- {/* Always-present ground plane. Surface finish follows the active world style and
- preset; it is never removed by a quality choice. */}
- <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, WORLD.groundY, GROUND_CENTER_Z]}>
- <planeGeometry args={[GROUND_HALF * 2, GROUND_DEPTH]} />
- <meshStandardMaterial
- ref={groundMatRef}
- color={preset.groundColor ?? '#0a0a20'}
- metalness={targetMetalness}
- roughness={0.7}
- side={THREE.DoubleSide}
- />
- </mesh>
-
- <Grid
- args={[GROUND_HALF * 2, GROUND_DEPTH]}
- cellSize={lowPoly ? 4 : 2}
- sectionSize={lowPoly ? 16 : 6}
- cellColor={gridCellColor}
- sectionColor={gridSectionColor}
- cellThickness={lowPoly ? 0.22 : 0.6}
- sectionThickness={lowPoly ? 0.55 : 1.4}
- fadeDistance={80}
- fadeStrength={lowPoly ? 0.8 : 0.6}
- position={[0, -0.01, GROUND_CENTER_Z]}
- />
-
- {/* Wet street reflective patches */}
- {puddles.map(p => (
- <WetPatch key={p.id} position={p.position} size={p.size} color={p.color} dayMix={dayMix} />
- ))}
-
- {/* Subtle ground fog layer (night neon haze; gone by day) */}
- {groundFogOpacity > 0.001 && (
- <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.1, 0]}>
- <planeGeometry args={[80, 80]} />
- <meshBasicMaterial
- color={accent}
- transparent
- opacity={groundFogOpacity}
- blending={THREE.AdditiveBlending}
- side={THREE.DoubleSide}
- />
- </mesh>
- )}
-
- {/* Rolling fog layer at street level */}
- {wetEffectsEnabled && <RollingFog dayMix={dayMix} />}
- </group>
- );
-}
diff --git a/client/src/components/openworld/audio/openWorldAudioEngine.js b/client/src/components/openworld/audio/openWorldAudioEngine.js
deleted file mode 100644
index e9ce7dccc4..0000000000
--- a/client/src/components/openworld/audio/openWorldAudioEngine.js
+++ /dev/null
@@ -1,73 +0,0 @@
-// Singleton audio engine -- Web Audio API only, no external dependencies
-let audioCtx = null;
-let masterGain = null;
-let musicGain = null;
-let sfxGain = null;
-let pendingCleanup = null;
-
-export const getAudioContext = () => audioCtx;
-export const getMusicGain = () => musicGain;
-export const getSfxGain = () => sfxGain;
-
-export const initAudio = () => {
- // A remount can re-init while a delayed close (scheduleCleanup) is pending;
- // cancel it so the shared context isn't yanked out from under the new mount.
- if (pendingCleanup) {
- clearTimeout(pendingCleanup);
- pendingCleanup = null;
- }
- if (audioCtx) return audioCtx;
- audioCtx = new (window.AudioContext || window.webkitAudioContext)();
-
- masterGain = audioCtx.createGain();
- masterGain.gain.value = 1.0;
- masterGain.connect(audioCtx.destination);
-
- musicGain = audioCtx.createGain();
- musicGain.gain.value = 0.3;
- musicGain.connect(masterGain);
-
- sfxGain = audioCtx.createGain();
- sfxGain.gain.value = 0.5;
- sfxGain.connect(masterGain);
-
- return audioCtx;
-};
-
-export const setMusicVolume = (v) => {
- if (musicGain) musicGain.gain.value = Math.max(0, Math.min(1, v));
-};
-
-export const setSfxVolume = (v) => {
- if (sfxGain) sfxGain.gain.value = Math.max(0, Math.min(1, v));
-};
-
-export const cleanup = () => {
- if (pendingCleanup) {
- clearTimeout(pendingCleanup);
- pendingCleanup = null;
- }
- if (audioCtx && audioCtx.state !== 'closed') {
- audioCtx.close();
- }
- audioCtx = null;
- masterGain = null;
- musicGain = null;
- sfxGain = null;
-};
-
-// Close after `delayMs` (e.g. once a stop-ramp settles) unless initAudio runs
-// again first — an immediate close would cut the ramp short, but an
-// uncancelled one would kill a remounted consumer's freshly built graph.
-export const scheduleCleanup = (delayMs) => {
- if (pendingCleanup) clearTimeout(pendingCleanup);
- if (!delayMs || delayMs <= 0) {
- pendingCleanup = null;
- cleanup();
- return;
- }
- pendingCleanup = setTimeout(() => {
- pendingCleanup = null;
- cleanup();
- }, delayMs);
-};
diff --git a/client/src/components/openworld/audio/openWorldSoundEffects.js b/client/src/components/openworld/audio/openWorldSoundEffects.js
deleted file mode 100644
index 63d06378a4..0000000000
--- a/client/src/components/openworld/audio/openWorldSoundEffects.js
+++ /dev/null
@@ -1,305 +0,0 @@
-// Procedural sound effects using Web Audio API -- each SFX is a pure function
-import { getAudioContext, getSfxGain } from './openWorldAudioEngine';
-
-// Helper: create white noise buffer
-const createNoiseBuffer = (ctx, duration) => {
- const sampleRate = ctx.sampleRate;
- const length = sampleRate * duration;
- const buffer = ctx.createBuffer(1, length, sampleRate);
- const data = buffer.getChannelData(0);
- for (let i = 0; i < length; i++) {
- data[i] = Math.random() * 2 - 1;
- }
- return buffer;
-};
-
-// Building hover: soft scan tone (sine sweep 200->800Hz, 100ms)
-const playBuildingHover = (ctx, output) => {
- const now = ctx.currentTime;
- const osc = ctx.createOscillator();
- osc.type = 'sine';
- osc.frequency.setValueAtTime(200, now);
- osc.frequency.exponentialRampToValueAtTime(800, now + 0.1);
- const filter = ctx.createBiquadFilter();
- filter.type = 'bandpass';
- filter.frequency.value = 500;
- filter.Q.value = 2;
- const gain = ctx.createGain();
- gain.gain.setValueAtTime(0.15, now);
- gain.gain.exponentialRampToValueAtTime(0.001, now + 0.12);
- osc.connect(filter);
- filter.connect(gain);
- gain.connect(output);
- osc.start(now);
- osc.stop(now + 0.15);
-};
-
-// Building click: percussive ping (noise burst + sine)
-const playBuildingClick = (ctx, output) => {
- const now = ctx.currentTime;
- // Noise burst
- const noise = ctx.createBufferSource();
- noise.buffer = createNoiseBuffer(ctx, 0.03);
- const noiseGain = ctx.createGain();
- noiseGain.gain.setValueAtTime(0.2, now);
- noiseGain.gain.exponentialRampToValueAtTime(0.001, now + 0.03);
- noise.connect(noiseGain);
- noiseGain.connect(output);
- noise.start(now);
- // Sine ping
- const osc = ctx.createOscillator();
- osc.type = 'sine';
- osc.frequency.value = 1200;
- const gain = ctx.createGain();
- gain.gain.setValueAtTime(0.15, now);
- gain.gain.exponentialRampToValueAtTime(0.001, now + 0.15);
- osc.connect(gain);
- gain.connect(output);
- osc.start(now);
- osc.stop(now + 0.2);
-};
-
-// Lightning: thunder crack (noise, high-pass, distortion, decay)
-const playLightning = (ctx, output) => {
- const now = ctx.currentTime;
- const noise = ctx.createBufferSource();
- noise.buffer = createNoiseBuffer(ctx, 0.5);
- const filter = ctx.createBiquadFilter();
- filter.type = 'highpass';
- filter.frequency.value = 400;
- const distortion = ctx.createWaveShaper();
- const curve = new Float32Array(256);
- for (let i = 0; i < 256; i++) {
- const x = (i / 128) - 1;
- curve[i] = (Math.PI + 50) * x / (Math.PI + 50 * Math.abs(x));
- }
- distortion.curve = curve;
- const gain = ctx.createGain();
- gain.gain.setValueAtTime(0.3, now);
- gain.gain.exponentialRampToValueAtTime(0.001, now + 0.35);
- noise.connect(filter);
- filter.connect(distortion);
- distortion.connect(gain);
- gain.connect(output);
- noise.start(now);
-};
-
-// Shooting star: whoosh (high-pass noise sweep 2kHz->200Hz, panned)
-const playShootingStar = (ctx, output) => {
- const now = ctx.currentTime;
- const noise = ctx.createBufferSource();
- noise.buffer = createNoiseBuffer(ctx, 0.6);
- const filter = ctx.createBiquadFilter();
- filter.type = 'highpass';
- filter.frequency.setValueAtTime(2000, now);
- filter.frequency.exponentialRampToValueAtTime(200, now + 0.5);
- const panner = ctx.createStereoPanner();
- panner.pan.value = Math.random() * 2 - 1;
- const gain = ctx.createGain();
- gain.gain.setValueAtTime(0.12, now);
- gain.gain.exponentialRampToValueAtTime(0.001, now + 0.55);
- noise.connect(filter);
- filter.connect(panner);
- panner.connect(gain);
- gain.connect(output);
- noise.start(now);
-};
-
-// Data pulse: chirp (sine 400->600Hz, 80ms)
-const playDataPulse = (ctx, output) => {
- const now = ctx.currentTime;
- const osc = ctx.createOscillator();
- osc.type = 'sine';
- osc.frequency.setValueAtTime(400, now);
- osc.frequency.exponentialRampToValueAtTime(600, now + 0.08);
- const gain = ctx.createGain();
- gain.gain.setValueAtTime(0.1, now);
- gain.gain.exponentialRampToValueAtTime(0.001, now + 0.1);
- osc.connect(gain);
- gain.connect(output);
- osc.start(now);
- osc.stop(now + 0.12);
-};
-
-// Task complete: a bright two-note major-third chime (E6 → G#6) with a soft bell decay. Played
-// when a CoS task completes (roadmap 3.4) so finishing work has an audible reward in the city.
-const playTaskComplete = (ctx, output) => {
- const now = ctx.currentTime;
- const notes = [1318.51, 1661.22]; // E6, G#6 — a rising major third reads as "success"
- notes.forEach((freq, i) => {
- const t = now + i * 0.09; // slight arpeggiation
- const osc = ctx.createOscillator();
- osc.type = 'sine';
- osc.frequency.value = freq;
- const gain = ctx.createGain();
- gain.gain.setValueAtTime(0.0001, t);
- gain.gain.exponentialRampToValueAtTime(0.18, t + 0.01);
- gain.gain.exponentialRampToValueAtTime(0.0001, t + 0.5);
- osc.connect(gain);
- gain.connect(output);
- osc.start(t);
- osc.stop(t + 0.55);
- });
-};
-
-// Horn: dual-tone retro-futuristic synth horn
-const playHorn = (ctx, output) => {
- const now = ctx.currentTime;
- const freqs = [440, 554.37]; // A4 + C#5 major third interval
- freqs.forEach((freq) => {
- const osc = ctx.createOscillator();
- osc.type = 'sawtooth';
- osc.frequency.setValueAtTime(freq, now);
- const filter = ctx.createBiquadFilter();
- filter.type = 'lowpass';
- filter.frequency.setValueAtTime(1400, now);
- const gain = ctx.createGain();
- gain.gain.setValueAtTime(0.001, now);
- gain.gain.exponentialRampToValueAtTime(0.14, now + 0.02);
- gain.gain.setValueAtTime(0.12, now + 0.22);
- gain.gain.exponentialRampToValueAtTime(0.001, now + 0.35);
- osc.connect(filter);
- filter.connect(gain);
- gain.connect(output);
- osc.start(now);
- osc.stop(now + 0.38);
- });
-};
-
-// Boost: high-energy rising whoosh + resonance sweep
-const playBoost = (ctx, output) => {
- const now = ctx.currentTime;
- const noise = ctx.createBufferSource();
- noise.buffer = createNoiseBuffer(ctx, 0.45);
- const filter = ctx.createBiquadFilter();
- filter.type = 'bandpass';
- filter.Q.value = 3;
- filter.frequency.setValueAtTime(300, now);
- filter.frequency.exponentialRampToValueAtTime(1800, now + 0.4);
- const gain = ctx.createGain();
- gain.gain.setValueAtTime(0.001, now);
- gain.gain.exponentialRampToValueAtTime(0.15, now + 0.04);
- gain.gain.exponentialRampToValueAtTime(0.001, now + 0.45);
- noise.connect(filter);
- filter.connect(gain);
- gain.connect(output);
- noise.start(now);
-};
-
-// Boost pad: turbo charged surge
-const playBoostPad = (ctx, output) => {
- const now = ctx.currentTime;
- const osc = ctx.createOscillator();
- osc.type = 'sawtooth';
- osc.frequency.setValueAtTime(220, now);
- osc.frequency.exponentialRampToValueAtTime(880, now + 0.25);
- const filter = ctx.createBiquadFilter();
- filter.type = 'lowpass';
- filter.frequency.setValueAtTime(600, now);
- filter.frequency.exponentialRampToValueAtTime(3200, now + 0.25);
- const gain = ctx.createGain();
- gain.gain.setValueAtTime(0.001, now);
- gain.gain.exponentialRampToValueAtTime(0.2, now + 0.03);
- gain.gain.exponentialRampToValueAtTime(0.001, now + 0.3);
- osc.connect(filter);
- filter.connect(gain);
- gain.connect(output);
- osc.start(now);
- osc.stop(now + 0.32);
-};
-
-// Jump: springy upward chirp
-const playJump = (ctx, output) => {
- const now = ctx.currentTime;
- const osc = ctx.createOscillator();
- osc.type = 'sine';
- osc.frequency.setValueAtTime(260, now);
- osc.frequency.exponentialRampToValueAtTime(620, now + 0.12);
- const gain = ctx.createGain();
- gain.gain.setValueAtTime(0.15, now);
- gain.gain.exponentialRampToValueAtTime(0.001, now + 0.16);
- osc.connect(gain);
- gain.connect(output);
- osc.start(now);
- osc.stop(now + 0.18);
-};
-
-// Land: solid low-end damping thud
-const playLand = (ctx, output) => {
- const now = ctx.currentTime;
- const osc = ctx.createOscillator();
- osc.type = 'sine';
- osc.frequency.setValueAtTime(110, now);
- osc.frequency.exponentialRampToValueAtTime(40, now + 0.14);
- const gain = ctx.createGain();
- gain.gain.setValueAtTime(0.22, now);
- gain.gain.exponentialRampToValueAtTime(0.001, now + 0.15);
- osc.connect(gain);
- gain.connect(output);
- osc.start(now);
- osc.stop(now + 0.18);
-};
-
-// Collectible shard: sparkling 4-note ascending crystalline arpeggio
-const playCollect = (ctx, output) => {
- const now = ctx.currentTime;
- const notes = [1046.5, 1318.51, 1567.98, 2093.0]; // C6, E6, G6, C7
- notes.forEach((freq, i) => {
- const t = now + i * 0.055;
- const osc = ctx.createOscillator();
- osc.type = 'sine';
- osc.frequency.value = freq;
- const gain = ctx.createGain();
- gain.gain.setValueAtTime(0.001, t);
- gain.gain.exponentialRampToValueAtTime(0.16, t + 0.01);
- gain.gain.exponentialRampToValueAtTime(0.001, t + 0.38);
- osc.connect(gain);
- gain.connect(output);
- osc.start(t);
- osc.stop(t + 0.4);
- });
-};
-
-// Easter egg discovery: shimmering mystical chord
-const playEggDiscover = (ctx, output) => {
- const now = ctx.currentTime;
- const freqs = [739.99, 932.33, 1108.73, 1396.91]; // F#5, A#5, C#6, F6 (Major 7th sparkle)
- freqs.forEach((freq, i) => {
- const t = now + i * 0.04;
- const osc = ctx.createOscillator();
- osc.type = 'triangle';
- osc.frequency.value = freq;
- const gain = ctx.createGain();
- gain.gain.setValueAtTime(0.001, t);
- gain.gain.exponentialRampToValueAtTime(0.12, t + 0.08);
- gain.gain.exponentialRampToValueAtTime(0.001, t + 0.7);
- osc.connect(gain);
- gain.connect(output);
- osc.start(t);
- osc.stop(t + 0.75);
- });
-};
-
-const SFX_MAP = {
- buildingHover: playBuildingHover,
- buildingClick: playBuildingClick,
- lightning: playLightning,
- shootingStar: playShootingStar,
- dataPulse: playDataPulse,
- taskComplete: playTaskComplete,
- horn: playHorn,
- boost: playBoost,
- boostPad: playBoostPad,
- jump: playJump,
- land: playLand,
- collect: playCollect,
- eggDiscover: playEggDiscover,
-};
-
-export const playSfx = (name) => {
- const ctx = getAudioContext();
- const output = getSfxGain();
- if (!ctx || !output || ctx.state === 'closed') return;
- const fn = SFX_MAP[name];
- if (fn) fn(ctx, output);
-};
diff --git a/client/src/components/openworld/audio/openWorldSynthMusic.js b/client/src/components/openworld/audio/openWorldSynthMusic.js
deleted file mode 100644
index 201afd9d30..0000000000
--- a/client/src/components/openworld/audio/openWorldSynthMusic.js
+++ /dev/null
@@ -1,327 +0,0 @@
-// Procedural ambient synthwave using Web Audio oscillators.
-//
-// Scheduling follows the "two clocks" pattern the sibling synth players use (see
-// lib/metronome.js:3-6 and lib/lookaheadTransport.js): a coarse setInterval
-// *lookahead* timer wakes every LOOKAHEAD_MS and hands every note event falling
-// inside the next SCHEDULE_AHEAD window to the AudioContext clock at an ABSOLUTE
-// time. Previously the chord changes (2400ms) and arp plucks (150ms) rode two
-// independent setIntervals that read ctx.currentTime at fire time, so both
-// drifted under main-thread load and drifted apart from each other.
-//
-// It does NOT reuse createLookaheadTransport, deliberately: that transport reads
-// its clock from the shared lib/audioContext.js singleton with no injection
-// point, while openWorldAudioEngine is a documented holdout that owns its own
-// AudioContext (and close()s it on unmount). Driving this graph from the shared
-// context's currentTime would mean scheduling against a clock the graph doesn't
-// run on. The transport also models a finite piece (total length, pause/seek/
-// position, per-note node teardown) — none of which an endless drone built from
-// long-lived oscillators has. What IS shared is the timing feel: SYNTH_TIMING.
-import { getAudioContext, getMusicGain } from './openWorldAudioEngine';
-import { CHORD_SETS } from '../../../utils/openWorldSoundscape';
-import { SYNTH_TIMING } from '../../../lib/lookaheadTransport';
-
-const { LOOKAHEAD_MS, SCHEDULE_AHEAD } = SYNTH_TIMING;
-
-// The note grid: one 16th note every ARP_SEC (150ms at 100BPM), with a chord
-// change every CHORD_STEPS sixteenths (2.4s = 4 beats). Deriving both from ONE
-// step counter is what keeps the arp phase-locked to the chords — the previous
-// pair of independent timers could only stay aligned by luck.
-const ARP_SEC = 0.15;
-const CHORD_STEPS = 16;
-
-let isPlaying = false;
-let oscillators = [];
-let nodesCleanup = [];
-
-// Lookahead scheduler state. `gridOrigin` is the ctx time of step 0; every event
-// time is gridOrigin + step * ARP_SEC, so the grid can never accumulate drift.
-let schedulerTimer = null;
-let gridOrigin = 0;
-let nextStep = 1;
-let currentChordIdx = 0;
-
-// Default chord progression (Am -> Em -> F -> C). The soundscape layer (roadmap 3.4) can swap
-// this for the darker `tense` set via setSoundscape(); we keep a mutable pointer so the running
-// chord interval reads whatever's current without re-scheduling.
-const DEFAULT_CHORDS = CHORD_SETS.bright;
-let activeChords = DEFAULT_CHORDS;
-
-// Live references to the modulatable nodes, captured in startMusic(). setSoundscape() ramps
-// these in real time so the music's mood/brightness/energy follows system state. Null while
-// the music is stopped. `baseArpGain` is the energy-driven target the arp envelope peaks at.
-let liveBassFilter = null;
-let livePadOscs = [];
-let liveArpPeak = 0.06; // peak gain the arp pluck opens to; raised/lowered by energy
-
-// Layer gain nodes, captured in startMusic() so stopMusic() can ramp each audible
-// layer to silence before the hard oscillator stop (see stopMusic() below).
-let liveBassGain = null;
-let livePadGain = null;
-let liveArpGain = null;
-
-// Oscillators the scheduler retunes each step. Null while stopped.
-let liveBassOsc = null;
-let liveArpOsc = null;
-
-// Arp note patterns (scale degrees relative to chord root)
-const ARP_PATTERN = [0, 2, 4, 7, 12, 7, 4, 2];
-
-// Apply a soundscape view-model (from computeSoundscape) to the running music graph. Safe to call
-// whether or not music is playing — it just updates the targets the next chord/arp tick uses.
-export const setSoundscape = (params) => {
- if (!params) return;
- const ctx = getAudioContext();
- activeChords = params.chordSet === 'tense' ? CHORD_SETS.tense : CHORD_SETS.bright;
- liveArpPeak = Math.max(0.01, params.arpGain ?? 0.06);
- if (ctx && liveBassFilter) {
- // Ramp the base cutoff smoothly so mood shifts glide rather than click. The LFO still rides
- // on top of this via its own connection to bassFilter.frequency.
- liveBassFilter.frequency.setTargetAtTime(params.filterBase ?? 200, ctx.currentTime, 0.5);
- }
- if (ctx && livePadOscs.length) {
- livePadOscs.forEach((osc, i) => {
- osc.detune.setTargetAtTime((i - 1) * (params.padDetune ?? 8), ctx.currentTime, 0.5);
- });
- }
-};
-
-// Advance to the next chord and glide the bass + pad onto it AT `when`. Reads
-// `activeChords` live so a soundscape mood-swap (bright↔tense) takes effect on
-// the next chord; the walk is incremental (not derived from the step index) so
-// swapping to a set of a different length can't jump the progression.
-const scheduleChordChange = (when) => {
- const chords = activeChords;
- currentChordIdx = (currentChordIdx + 1) % chords.length;
- const chord = chords[currentChordIdx];
- liveBassOsc.frequency.setTargetAtTime(chord[0], when, 0.3);
- livePadOscs.forEach((osc, i) => {
- osc.frequency.setTargetAtTime(chord[i] * 2, when, 0.3);
- });
-};
-
-// One arp 16th note AT `when`. The pluck peaks at `liveArpPeak`, which the
-// soundscape raises with system energy (more active agents → a louder lead).
-const scheduleArpPluck = (step, when) => {
- const chords = activeChords;
- const chord = chords[currentChordIdx % chords.length];
- const rootFreq = chord[0] * 4; // two octaves up
- const semitone = ARP_PATTERN[(step - 1) % ARP_PATTERN.length];
- const freq = rootFreq * Math.pow(2, semitone / 12);
-
- liveArpOsc.frequency.setTargetAtTime(freq, when, 0.01);
- // Short percussive envelope
- liveArpGain.gain.setTargetAtTime(liveArpPeak, when, 0.005);
- liveArpGain.gain.setTargetAtTime(0.0, when + 0.06, 0.04);
-};
-
-// One lookahead tick: schedule every step due inside the next SCHEDULE_AHEAD
-// window. Chord-first at a shared step so the pluck landing on the downbeat
-// already sounds the new chord.
-const scheduleWindow = () => {
- const ctx = getAudioContext();
- if (!isPlaying || !ctx) return;
-
- // A backgrounded tab throttles this timer to once a second or worse. Without
- // this, catching up would schedule every missed step at a time already in the
- // past — Web Audio clamps those to "now", firing them as one burst. Re-anchor
- // to whole steps instead, which keeps the grid phase (and so the arp/chord
- // lock) while dropping the steps nobody was there to hear.
- const behind = ctx.currentTime - (gridOrigin + nextStep * ARP_SEC);
- if (behind > ARP_SEC) nextStep += Math.floor(behind / ARP_SEC);
-
- const horizon = ctx.currentTime + SCHEDULE_AHEAD;
- while (gridOrigin + nextStep * ARP_SEC < horizon) {
- const when = gridOrigin + nextStep * ARP_SEC;
- if (nextStep % CHORD_STEPS === 0) scheduleChordChange(when);
- scheduleArpPluck(nextStep, when);
- nextStep += 1;
- }
-};
-
-const createReverb = (ctx) => {
- const convolver = ctx.createConvolver();
- const rate = ctx.sampleRate;
- const length = rate * 2.5;
- const impulse = ctx.createBuffer(2, length, rate);
- for (let ch = 0; ch < 2; ch++) {
- const data = impulse.getChannelData(ch);
- for (let i = 0; i < length; i++) {
- data[i] = (Math.random() * 2 - 1) * Math.pow(1 - i / length, 2.5);
- }
- }
- convolver.buffer = impulse;
- return convolver;
-};
-
-export const startMusic = () => {
- const ctx = getAudioContext();
- const output = getMusicGain();
- if (!ctx || !output || isPlaying) return;
- isPlaying = true;
-
- const reverb = createReverb(ctx);
- const reverbGain = ctx.createGain();
- reverbGain.gain.value = 0.3;
- reverb.connect(reverbGain);
- reverbGain.connect(output);
-
- const delay = ctx.createDelay(1.0);
- delay.delayTime.value = 0.375; // dotted eighth at ~100BPM
- const delayFeedback = ctx.createGain();
- delayFeedback.gain.value = 0.35;
- delay.connect(delayFeedback);
- delayFeedback.connect(delay);
- delayFeedback.connect(output);
-
- // --- Bass drone layer ---
- const bassFilter = ctx.createBiquadFilter();
- bassFilter.type = 'lowpass';
- bassFilter.frequency.value = 200;
- bassFilter.Q.value = 2;
- bassFilter.connect(output);
- bassFilter.connect(reverb);
-
- const bassOsc = ctx.createOscillator();
- bassOsc.type = 'sawtooth';
- bassOsc.frequency.value = activeChords[0][0];
- const bassGain = ctx.createGain();
- bassGain.gain.value = 0.12;
- bassOsc.connect(bassGain);
- bassGain.connect(bassFilter);
- bassOsc.start();
- oscillators.push(bassOsc);
-
- // LFO for filter sweep
- const lfo = ctx.createOscillator();
- lfo.type = 'sine';
- lfo.frequency.value = 0.08;
- const lfoGain = ctx.createGain();
- lfoGain.gain.value = 120;
- lfo.connect(lfoGain);
- lfoGain.connect(bassFilter.frequency);
- lfo.start();
- oscillators.push(lfo);
-
- // --- Pad layer (wide stereo detuned sines) ---
- const padGain = ctx.createGain();
- padGain.gain.value = 0.04;
- padGain.connect(output);
- padGain.connect(reverb);
-
- const padOscs = [];
- for (let i = 0; i < 3; i++) {
- const osc = ctx.createOscillator();
- osc.type = 'sine';
- osc.frequency.value = activeChords[0][i];
- osc.detune.value = (i - 1) * 8; // slight spread
- osc.connect(padGain);
- osc.start();
- padOscs.push(osc);
- oscillators.push(osc);
- }
-
- // --- Arp lead layer ---
- const arpFilter = ctx.createBiquadFilter();
- arpFilter.type = 'bandpass';
- arpFilter.frequency.value = 1200;
- arpFilter.Q.value = 1.5;
- const arpGain = ctx.createGain();
- arpGain.gain.value = 0;
- arpFilter.connect(arpGain);
- arpGain.connect(output);
- arpGain.connect(delay);
- arpGain.connect(reverb);
-
- const arpOsc = ctx.createOscillator();
- arpOsc.type = 'triangle';
- arpOsc.frequency.value = 440;
- arpOsc.detune.value = 5;
- arpOsc.connect(arpFilter);
- arpOsc.start();
- oscillators.push(arpOsc);
-
- // Expose the modulatable nodes so setSoundscape() and the scheduler can reach them.
- liveBassFilter = bassFilter;
- livePadOscs = padOscs;
- liveBassGain = bassGain;
- livePadGain = padGain;
- liveArpGain = arpGain;
- liveBassOsc = bassOsc;
- liveArpOsc = arpOsc;
-
- nodesCleanup.push(reverb, reverbGain, delay, delayFeedback, bassFilter, bassGain, padGain, arpFilter, arpGain);
-
- // Anchor the note grid to the audio clock and start the lookahead timer. Chord
- // index 0 is already sounding from the oscillator frequencies above, so the
- // grid starts at step 1 — the first chord CHANGE lands on step CHORD_STEPS.
- gridOrigin = ctx.currentTime;
- nextStep = 1;
- currentChordIdx = 0;
- scheduleWindow();
- schedulerTimer = setInterval(scheduleWindow, LOOKAHEAD_MS);
-};
-
-// Fade time constant for the pre-stop ramp (setTargetAtTime never truly reaches
-// zero, so REST settles ~3 time-constants in — audibly silent well under 100ms).
-const STOP_RAMP_TC = 0.02;
-// Oscillators are hard-stopped this long after the ramp starts, once the layers
-// have settled toward silence, instead of mid-waveform (the audible pop this fixes).
-const STOP_SETTLE = 0.08;
-
-// Stops the running music graph. Ramps each audible layer to silence first — an
-// abrupt osc.stop() while a waveform is mid-cycle truncates it at a non-zero
-// sample, which reads as an audible click/pop on mute toggle or OpenWorld unmount.
-// Mirrors openWorldSoundEffects.js's envelope-before-stop pattern (setTargetAtTime /
-// exponentialRampToValueAtTime before every osc.stop() there).
-//
-// Returns the settle time in milliseconds so a caller that needs to tear down the
-// AudioContext right after (useOpenWorldAudio's unmount cleanup) can delay the close
-// until the ramp has actually finished, instead of cutting it off immediately.
-export const stopMusic = () => {
- if (!isPlaying) return 0;
- isPlaying = false;
- // Stop the lookahead timer before the ramps below, so no further note events
- // get scheduled onto a graph that is already fading out.
- if (schedulerTimer != null) {
- clearInterval(schedulerTimer);
- schedulerTimer = null;
- }
- const ctx = getAudioContext();
- const now = ctx ? ctx.currentTime : 0;
-
- if (ctx) {
- [liveBassGain, livePadGain, liveArpGain].forEach(gainNode => {
- if (gainNode) gainNode.gain.setTargetAtTime(0, now, STOP_RAMP_TC);
- });
- }
-
- const stopAt = ctx ? now + STOP_SETTLE : 0;
- const pendingOscillators = oscillators;
- const pendingNodes = nodesCleanup;
- pendingOscillators.forEach(osc => {
- if (ctx) osc.stop(stopAt);
- else osc.stop();
- });
-
- oscillators = [];
- nodesCleanup = [];
- // Drop references to the now-stopping nodes so a stray setSoundscape() can't ramp a
- // dead graph. The next startMusic() re-captures fresh ones.
- liveBassFilter = null;
- livePadOscs = [];
- liveBassGain = null;
- livePadGain = null;
- liveArpGain = null;
- liveBassOsc = null;
- liveArpOsc = null;
-
- // Disconnect after the ramp/stop settles instead of instantly — an immediate
- // disconnect() would cut the fade above short, defeating the point of it.
- const settleMs = ctx ? (STOP_SETTLE + STOP_RAMP_TC) * 1000 : 0;
- setTimeout(() => {
- pendingOscillators.forEach(osc => osc.disconnect());
- pendingNodes.forEach(node => node.disconnect());
- }, settleMs);
-
- return settleMs;
-};
diff --git a/client/src/components/openworld/audio/openWorldSynthMusic.test.js b/client/src/components/openworld/audio/openWorldSynthMusic.test.js
deleted file mode 100644
index ac5523fc99..0000000000
--- a/client/src/components/openworld/audio/openWorldSynthMusic.test.js
+++ /dev/null
@@ -1,302 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { CHORD_SETS } from '../../../utils/openWorldSoundscape';
-import { SYNTH_TIMING } from '../../../lib/lookaheadTransport';
-
-// Minimal fake Web Audio graph for openWorldSynthMusic.js. The module pulls its
-// context/output gain from openWorldAudioEngine's getAudioContext()/getMusicGain()
-// (module-level singleton getters, not a constructor call or a param it
-// receives) and drives: a convolver reverb, a feedback delay, a lowpass bass
-// filter, a bandpass arp filter, and several gain-ramped oscillators.
-//
-// Mirrors the connectable()/fakeParam() idiom from
-// src/test/fakeAudioContext.js, extended with createConvolver/createDelay —
-// nodes that shared fake doesn't cover but this module actually touches.
-const fakeParam = (initial) => {
- const values = [];
- return {
- value: initial,
- values,
- // Records (v, when, timeConstant) so a test can assert the exact ramp the
- // source schedules, not just "some call happened".
- setTargetAtTime: (v, when, tc) => { values.push({ v, when, tc }); },
- };
-};
-
-const connectable = () => ({
- connections: [],
- connect(target) { this.connections.push(target); return target; },
- disconnect: vi.fn(),
-});
-
-const makeFakeContext = () => {
- const ctx = {
- now: 0,
- get currentTime() { return ctx.now; },
- sampleRate: 48000,
- oscillators: [],
- gains: [],
- createConvolver() {
- return { buffer: null, ...connectable() };
- },
- createBuffer(channels, length, rate) {
- const chans = Array.from({ length: channels }, () => new Float32Array(length));
- return { length, sampleRate: rate, getChannelData: (ch) => chans[ch] };
- },
- createGain() {
- const gain = { gain: fakeParam(1), ...connectable() };
- ctx.gains.push(gain);
- return gain;
- },
- createDelay() {
- return { delayTime: fakeParam(0), ...connectable() };
- },
- createBiquadFilter() {
- return { type: '', frequency: fakeParam(0), Q: { value: 1 }, ...connectable() };
- },
- createOscillator() {
- const osc = {
- type: '',
- frequency: fakeParam(0),
- detune: fakeParam(0),
- started: null,
- stopped: null,
- ...connectable(),
- start(t) { this.started = t; },
- stop: vi.fn(function stop(t) { this.stopped = t; }),
- };
- ctx.oscillators.push(osc);
- return osc;
- },
- };
- return ctx;
-};
-
-// Constants read straight from openWorldSynthMusic.js (not exported, so pinned
-// here as literals): STOP_RAMP_TC = 0.02 (gain fade time constant),
-// STOP_SETTLE = 0.08 (delay before the hard oscillator stop).
-const STOP_RAMP_TC = 0.02;
-const STOP_SETTLE = 0.08;
-// The note grid, likewise pinned from the source: one 16th every ARP_SEC, with
-// a chord change every CHORD_STEPS of them.
-const ARP_SEC = 0.15;
-const CHORD_STEPS = 16;
-const { LOOKAHEAD_MS } = SYNTH_TIMING;
-
-// The bass is the only sawtooth oscillator and the arp the only gain that
-// starts at 0 — identify both by that rather than by creation order, so
-// re-ordering the graph build can't silently point these assertions at the
-// wrong node.
-const bassOsc = () => fakeCtx.oscillators.find(o => o.type === 'sawtooth');
-const arpGain = () => fakeCtx.gains.find(g => g.gain.value === 0);
-
-// Drive both clocks forward together the way a browser does: every lookahead
-// tick also advances the audio clock. Scheduling asserts are meaningless if the
-// audio clock stands still while the timer fires.
-const runAudio = (seconds) => {
- const ticks = Math.round((seconds * 1000) / LOOKAHEAD_MS);
- for (let i = 0; i < ticks; i += 1) {
- fakeCtx.now += LOOKAHEAD_MS / 1000;
- vi.advanceTimersByTime(LOOKAHEAD_MS);
- }
-};
-
-// Same, but with the timer firing at irregular points on the audio clock —
-// main-thread jank. This is the condition the old scheduling drifted under: a
-// note written at "whatever currentTime is right now" lands off the grid, while
-// a note written at an absolute grid time does not. The multipliers average
-// 1.0, so the two clocks stay in sync across each cycle and only the sampling
-// points jitter.
-const runAudioJanky = (seconds) => {
- const jitter = [0.9, 1.6, 0.4, 1.3, 0.8];
- let elapsed = 0;
- for (let i = 0; elapsed < seconds; i += 1) {
- const delta = (LOOKAHEAD_MS / 1000) * jitter[i % jitter.length];
- fakeCtx.now += delta;
- elapsed += delta;
- vi.advanceTimersByTime(LOOKAHEAD_MS);
- }
-};
-
-let fakeCtx;
-let fakeOutput;
-
-vi.mock('./openWorldAudioEngine', () => ({
- getAudioContext: () => fakeCtx,
- getMusicGain: () => fakeOutput,
-}));
-
-let synth;
-
-beforeEach(async () => {
- vi.resetModules();
- fakeCtx = makeFakeContext();
- fakeOutput = { ...connectable() };
- synth = await import('./openWorldSynthMusic.js');
-});
-
-afterEach(() => {
- // openWorldSynthMusic schedules real setInterval timers on startMusic(); stop
- // whatever's running so a test that never called stopMusic doesn't leak
- // intervals into later tests. stopMusic() is a documented no-op when
- // already stopped, so this is always safe to call.
- synth.stopMusic();
-});
-
-describe('openWorldSynthMusic', () => {
- it('startMusic is a no-op when already playing', () => {
- synth.startMusic();
- const oscCount = fakeCtx.oscillators.length;
- const gainCount = fakeCtx.gains.length;
- expect(oscCount).toBeGreaterThan(0);
-
- synth.startMusic();
- // No new nodes created — the second call returns before building anything.
- expect(fakeCtx.oscillators.length).toBe(oscCount);
- expect(fakeCtx.gains.length).toBe(gainCount);
- });
-
- it('stopMusic ramps each audible layer gain to 0 with the settle time constant', () => {
- synth.startMusic();
- fakeCtx.now = 5;
- synth.stopMusic();
-
- // liveBassGain/livePadGain/liveArpGain are the three layer gains ramped
- // in stopMusic() — identify them by the ramp-to-0 call they each receive.
- const ramped = fakeCtx.gains.filter(g => g.gain.values.some(entry => entry.v === 0));
- expect(ramped).toHaveLength(3);
- for (const g of ramped) {
- expect(g.gain.values.at(-1)).toEqual({ v: 0, when: 5, tc: STOP_RAMP_TC });
- }
- });
-
- it('stopMusic schedules oscillator stop at a future time, not immediately', () => {
- synth.startMusic();
- fakeCtx.now = 10;
- synth.stopMusic();
-
- expect(fakeCtx.oscillators.length).toBeGreaterThan(0);
- for (const osc of fakeCtx.oscillators) {
- expect(osc.stop).toHaveBeenCalledTimes(1);
- // A fade-out, not an abrupt cut: stop lands STOP_SETTLE after "now".
- expect(osc.stopped).toBeCloseTo(10 + STOP_SETTLE, 10);
- expect(osc.stopped).toBeGreaterThan(10);
- }
- });
-
- it('stopMusic returns the settle/fade duration in ms', () => {
- synth.startMusic();
- const settleMs = synth.stopMusic();
- expect(settleMs).toBe((STOP_SETTLE + STOP_RAMP_TC) * 1000);
- });
-
- it('defers node disconnects until the ramp settles (the pop-fix contract)', () => {
- vi.useFakeTimers();
- try {
- synth.startMusic();
- const settleMs = synth.stopMusic();
-
- // An immediate disconnect would cut the fade short — nothing may
- // disconnect at stopMusic() return time.
- const disconnects = () =>
- fakeCtx.oscillators.filter(o => o.disconnect.mock.calls.length > 0).length;
- expect(disconnects()).toBe(0);
-
- vi.advanceTimersByTime(settleMs + 1);
- expect(disconnects()).toBe(fakeCtx.oscillators.length);
- } finally {
- vi.useRealTimers();
- }
- });
-
- it('clears is-playing state so a later startMusic creates fresh nodes', () => {
- synth.startMusic();
- const firstOscCount = fakeCtx.oscillators.length;
- synth.stopMusic();
-
- synth.startMusic();
- // Not a no-op this time: a fresh set of oscillators was built.
- expect(fakeCtx.oscillators.length).toBe(firstOscCount * 2);
- });
-
- describe('lookahead scheduling (#3396)', () => {
- beforeEach(() => { vi.useFakeTimers(); });
- afterEach(() => { vi.useRealTimers(); });
-
- it('schedules arp notes at absolute future times on the 16th grid, despite jank', () => {
- synth.startMusic(); // gridOrigin = 0
- runAudioJanky(0.5);
-
- // Every pluck is a (peak, when) pair; the peak ramps are the note onsets.
- const onsets = arpGain().gain.values
- .filter(e => e.v !== 0)
- .map(e => e.when);
- expect(onsets.length).toBeGreaterThan(0);
- // Exactly on the grid — n * ARP_SEC, never "whatever currentTime was".
- onsets.forEach((when, i) => {
- expect(when).toBeCloseTo((i + 1) * ARP_SEC, 10);
- });
- // And scheduled ahead of the clock, not at it.
- expect(Math.max(...onsets)).toBeGreaterThan(fakeCtx.now);
- });
-
- it('changes chord exactly on the CHORD_STEPS boundary, phase-locked to the arp', () => {
- synth.startMusic();
- runAudioJanky(2.6); // just past step 16 (2.4s)
-
- const chordChanges = bassOsc().frequency.values;
- expect(chordChanges).toHaveLength(1);
- expect(chordChanges[0].when).toBeCloseTo(CHORD_STEPS * ARP_SEC, 10);
- // Walked to the next chord of the active (bright) set, not re-derived.
- expect(chordChanges[0].v).toBe(CHORD_SETS.bright[1][0]);
-
- // An arp pluck lands on that same instant — the two grids share one counter.
- const onsets = arpGain().gain.values.filter(e => e.v !== 0).map(e => e.when);
- expect(onsets.some(w => Math.abs(w - CHORD_STEPS * ARP_SEC) < 1e-9)).toBe(true);
- });
-
- it('stops scheduling once stopMusic clears the lookahead timer', () => {
- synth.startMusic();
- runAudio(0.5);
- const scheduled = arpGain().gain.values.length;
- expect(scheduled).toBeGreaterThan(0);
-
- synth.stopMusic();
- const afterStop = arpGain().gain.values.length; // includes the stop ramp
- runAudio(2.0);
- expect(arpGain().gain.values).toHaveLength(afterStop);
- });
-
- it('re-anchors instead of bursting after the tab is backgrounded', () => {
- synth.startMusic();
- runAudio(0.5);
- const before = arpGain().gain.values.length;
-
- // A throttled tab: 30s of audio clock passes with no timer tick.
- fakeCtx.now += 30;
- vi.advanceTimersByTime(LOOKAHEAD_MS);
-
- // One window's worth of notes (a couple), not the ~200 missed steps.
- const scheduledInBurst = arpGain().gain.values.length - before;
- expect(scheduledInBurst).toBeLessThan(10);
- // Still on the original grid phase, so the arp/chord lock survives.
- const last = arpGain().gain.values.filter(e => e.v !== 0).at(-1).when;
- expect(last / ARP_SEC).toBeCloseTo(Math.round(last / ARP_SEC), 6);
- });
- });
-
- it('double-stop is safe: no throw and no double-schedule', () => {
- synth.startMusic();
- fakeCtx.now = 3;
- const first = synth.stopMusic();
- expect(first).toBeGreaterThan(0);
- const stopCallCounts = fakeCtx.oscillators.map(o => o.stop.mock.calls.length);
-
- // stopMusic() guards on `if (!isPlaying) return 0` — the second call is a
- // no-op, matching the guard actually present in the source.
- expect(() => { synth.stopMusic(); }).not.toThrow();
- const second = synth.stopMusic();
- expect(second).toBe(0);
- expect(fakeCtx.oscillators.map(o => o.stop.mock.calls.length)).toEqual(stopCallCounts);
- });
-});
-// @vitest-environment node
diff --git a/client/src/components/openworld/openWorldConstants.js b/client/src/components/openworld/openWorldConstants.js
deleted file mode 100644
index e8a82a2d8c..0000000000
--- a/client/src/components/openworld/openWorldConstants.js
+++ /dev/null
@@ -1,572 +0,0 @@
-import { hashString } from '../../utils/hashString';
-
-// Drei <Text> needs a TTF; this copy keeps the Geist Pixel glyphs but strips
-// layout tables that Troika's font parser logs as unsupported.
-export const PIXEL_FONT_URL = '/fonts/GeistPixel-Square-3d.ttf';
-
-export const CITY_COLORS = {
- ground: '#06b6d4',
- ambient: '#0d0d2b',
- building: {
- online: '#06b6d4',
- stopped: '#ef4444',
- not_started: '#8b5cf6',
- not_found: '#8b5cf6',
- // PM2 read failed — status unavailable. A muted amber-gray so it reads as
- // "unknown," distinct from the purple "never launched" buildings.
- unknown: '#9ca3af',
- archived: '#64748b',
- },
- buildingBody: '#0c0c24',
- particles: '#06b6d4',
- stars: '#ffffff',
- // Neon accent palette for building window/decoration variety
- neonAccents: ['#06b6d4', '#ec4899', '#8b5cf6', '#22c55e', '#f97316', '#3b82f6', '#f43f5e', '#a855f7'],
- // Celestial colors
- planet: '#3b82f6',
- orbit: '#1e3a5f',
- // Time-of-day presets (used by OpenWorldSky + OpenWorldLights)
- // hour: 0-24 mapped to sun arc. Sun traces east(6h) → overhead(12h) → west(18h) → below(0h)
- // daylightFactor: multiplier for scene ambient/point lights (bright day, dim night)
- // NOTE: the city UI now selects only day/night (→ 'noon'/'sunset' via resolveOpenWorldTimeOfDay).
- // 'sunrise' and 'midnight' are retained for legacy stored reads and possible future use,
- // but are no longer reachable from the settings picker.
- timeOfDay: {
- sunrise: {
- hour: 6,
- zenith: '#0a0a30',
- midSky: '#1a1040',
- horizonHigh: '#ff6050',
- horizonLow: '#ffaa40',
- sunCore: '#ff8844',
- sunGlow: '#ff6060',
- sunLight: '#ffccaa',
- sunIntensity: 2.0,
- sunScale: 1.0,
- isMoon: false,
- daylightFactor: 0.3,
- groundColor: '#2a2a40',
- groundRoughness: 0.7,
- // Hemisphere sky light (Unreal Engine "sky light" equivalent)
- hemiSkyColor: '#ff9966',
- hemiGroundColor: '#2a1a30',
- hemiIntensity: 0.6,
- ambientColor: '#2a1a3a',
- ambientIntensity: 0.25,
- },
- noon: {
- hour: 12,
- // Bright daytime sky, but with enough blue/chroma in the horizon bands that
- // the dome reads as sky instead of a white fog sheet over the city.
- zenith: '#0f4f9a',
- midSky: '#1e78bf',
- horizonHigh: '#3d95d2',
- horizonLow: '#58a9dc',
- sunCore: '#fffef2',
- sunGlow: '#fff7d6',
- sunLight: '#fff4e0',
- // Moderate intensities — kept low enough that lit surfaces don't clip to white
- // (the post-process previously bloomed the over-bright scene into a white disc).
- sunIntensity: 1.25,
- sunScale: 0.7,
- isMoon: false,
- daylightFactor: 1.0,
- // Muted blue-gray pavement; daylight + sky reflections otherwise turn the
- // central city plane into a white mirror.
- groundColor: '#3f5268',
- groundRoughness: 0.9,
- // Soft daytime sky fill (blue from above, warm bounce) — gentle, not high-key.
- hemiSkyColor: '#8bb8e0',
- hemiGroundColor: '#8f9488',
- hemiIntensity: 0.65,
- ambientColor: '#8ea4c6',
- ambientIntensity: 0.24,
- },
- sunset: {
- // Theme-night preset: moonlit cyber-night, not blackout. The city should
- // feel nocturnal while still being readable from moonlight and neon bounce.
- hour: 12,
- zenith: '#071329',
- midSky: '#0b1f38',
- horizonHigh: '#251445',
- horizonLow: '#080917',
- sunCore: '#d9ecff',
- sunGlow: '#7bbcff',
- sunLight: '#8fc7ff',
- sunIntensity: 1.1,
- sunScale: 0.72,
- isMoon: true,
- daylightFactor: 0.2,
- groundColor: '#283246',
- groundRoughness: 0.75,
- hemiSkyColor: '#5c8ac6',
- hemiGroundColor: '#121626',
- hemiIntensity: 1.1,
- ambientColor: '#1b2a4a',
- ambientIntensity: 0.55,
- },
- midnight: {
- hour: 0,
- zenith: '#020208',
- midSky: '#040412',
- horizonHigh: '#08081a',
- horizonLow: '#0a0a22',
- sunCore: '#ccccee',
- sunGlow: '#8888bb',
- sunLight: '#334466',
- sunIntensity: 0.12,
- sunScale: 0.6,
- isMoon: true,
- daylightFactor: 0.0,
- groundColor: '#0a0a20',
- groundRoughness: 0.85,
- hemiSkyColor: '#111122',
- hemiGroundColor: '#050508',
- hemiIntensity: 0.05,
- ambientColor: '#0a0a1a',
- ambientIntensity: 0.1,
- },
- // --- Vibes world style ---------------------------------------------------
- // The low-poly bright look: a warm, high-key outdoor world rather than a neon
- // night city. Colors mirror the Vibes open-world reference palette (teal-blue
- // zenith → warm sand horizon, warm sun, cool sky bounce) so the two worlds read
- // as the same art direction. `daylightFactor: 1` puts every dayMix-driven surface
- // (grid, fog, puddles, neon albedo, label ink) fully into its bright form.
- vibesDay: {
- hour: 12,
- zenith: '#4a9ec2',
- midSky: '#5faebf',
- horizonHigh: '#a8cfc4',
- horizonLow: '#f3af78',
- sunCore: '#fff4e2',
- sunGlow: '#ffe4ba',
- sunLight: '#ffe0b8',
- sunIntensity: 1.5,
- sunScale: 0.8,
- isMoon: false,
- daylightFactor: 1.0,
- // Meadow green rather than pavement — the ground plane is a landscape here.
- groundColor: '#86b893',
- groundRoughness: 0.95,
- hemiSkyColor: '#b9e3d8',
- hemiGroundColor: '#3f5c4a',
- hemiIntensity: 1.05,
- ambientColor: '#ffceae',
- ambientIntensity: 0.4,
- },
- // The "night" half of the Vibes style. Deliberately still bright — a golden-hour
- // dusk, not a blackout — so the world keeps its low-poly readability. daylightFactor
- // stays high (0.9) so dayMix ≈ 0.99 and the neon-night surfaces stay suppressed.
- vibesDusk: {
- hour: 18,
- zenith: '#2f6f92',
- midSky: '#71a2b0',
- horizonHigh: '#f0a46f',
- horizonLow: '#f07f6d',
- sunCore: '#ffd9a8',
- sunGlow: '#ffb27a',
- sunLight: '#ffc48f',
- sunIntensity: 1.2,
- sunScale: 1.0,
- isMoon: false,
- daylightFactor: 0.9,
- groundColor: '#6f9b80',
- groundRoughness: 0.95,
- hemiSkyColor: '#9fc7cd',
- hemiGroundColor: '#3a4a3c',
- hemiIntensity: 0.95,
- ambientColor: '#ffc9a2',
- ambientIntensity: 0.45,
- },
- },
- // The OpenWorld uses one canonical cyber sky. Legacy stored skyTheme values are
- // ignored by the scene and fall back to these presets.
- skyThemes: {},
-};
-
-export const BOROUGH_PARAMS = {
- processRingRadius: 3.0, // Distance of process buildings from center
- processMinHeight: 1.5,
- processMaxHeight: 3.5,
-};
-
-export const PROCESS_BUILDING_PARAMS = {
- width: 0.8,
- depth: 0.8,
-};
-
-export const BUILDING_PARAMS = {
- width: 2.0,
- depth: 2.0,
- spacing: 12.0,
- heights: {
- online: 5,
- stopped: 2.5,
- not_started: 1.5,
- not_found: 1.5,
- unknown: 1.5,
- archived: 2.0,
- },
- processHeightBonus: 0.8,
- // Height variation: seeded by app name hash for consistent randomness
- heightVariation: 2.5,
-};
-
-export const DISTRICT_PARAMS = {
- warehouseOffset: 18,
- gap: 4,
-};
-
-// Resolve a building's color from a status against a building-color map. The map
-// defaults to the static CITY_COLORS table; pass a themed palette's `building` map
-// (where `online` tracks the theme accent) to follow a theme switch.
-export const getBuildingColor = (status, archived, building = CITY_COLORS.building) => {
- if (archived) return building.archived;
- return building[status] || building.not_started;
-};
-
-export const getBuildingHeight = (app) => {
- if (app.archived) return BUILDING_PARAMS.heights.archived;
- const base = BUILDING_PARAMS.heights[app.overallStatus] || BUILDING_PARAMS.heights.not_started;
- const processBonus = app.overallStatus === 'online'
- ? (app.processes?.length || 0) * BUILDING_PARAMS.processHeightBonus
- : 0;
- // Add name-based variation so buildings look like a real skyline
- const hash = hashString(app.name || app.id);
- const variation = (hash % 100) / 100 * BUILDING_PARAMS.heightVariation;
- return base + processBonus + variation;
-};
-
-// Resolve the time-of-day preset for a given sky theme
-// Returns theme-specific overrides if available, otherwise default timeOfDay preset
-export const getTimeOfDayPreset = (timeOfDay, skyTheme) => {
- const hasOwn = Object.prototype.hasOwnProperty;
- const skyThemes = CITY_COLORS.skyThemes;
- const timeOfDayPresets = CITY_COLORS.timeOfDay;
-
- if (skyThemes && hasOwn.call(skyThemes, skyTheme)) {
- const themeOverrides = skyThemes[skyTheme];
- if (themeOverrides && hasOwn.call(themeOverrides, timeOfDay)) {
- return themeOverrides[timeOfDay];
- }
- }
-
- if (timeOfDayPresets && hasOwn.call(timeOfDayPresets, timeOfDay)) {
- return timeOfDayPresets[timeOfDay];
- }
-
- return timeOfDayPresets.sunset;
-};
-
-// 0 at night (sunset preset), ramping to 1 at full day (noon). The scene's many
-// night-cyberpunk surfaces (post-fx grade, building albedo/neon, ground grid/fog)
-// lerp toward a bright daytime look by this factor. The ramp starts at 0.35 so the
-// established night look (sunset's daylightFactor 0.2) stays fully at 0/unchanged.
-export const openWorldDayMix = (settings) => {
- const preset = getTimeOfDayPreset(settings?.timeOfDay ?? 'sunset', settings?.skyTheme ?? 'cyberpunk');
- return smoothstepRange(0.35, 1, preset?.daylightFactor ?? 0);
-};
-
-// Explicit tier rank for the detail gates below. `settings.effectiveTier` is the
-// runtime tier selected by the adaptive render budget — a first-class signal that
-// replaces the old `particleDensity`-as-quality-proxy (issue #2592).
-// When it's absent (older payloads, tests, or code that never set it) we fall back
-// to the legacy particleDensity thresholds so behavior is unchanged.
-const DETAIL_TIER_RANK = { low: 0, medium: 1, high: 2, ultra: 3 };
-
-// True at medium tier and above — the shared gate for optional set dressing (rooftop
-// kits, street furniture, transit trams). The low tier renders structure only.
-export const openWorldShowDetail = (settings) => (
- settings?.effectiveTier
- ? (DETAIL_TIER_RANK[settings.effectiveTier] ?? DETAIL_TIER_RANK.high) >= DETAIL_TIER_RANK.medium
- : (settings?.particleDensity ?? 1) > 0.5
-);
-
-// True at high tier and above — the gate for the heavier InteriorMappingMaterial
-// window panes, which ray-march a fake interior per pane and so cost more than the
-// flat window texture. Held one tier above openWorldShowDetail so medium-tier machines
-// keep the rest of the set dressing but skip the per-pane interior shader.
-export const openWorldShowInteriorWindows = (settings) => (
- settings?.effectiveTier
- ? (DETAIL_TIER_RANK[settings.effectiveTier] ?? DETAIL_TIER_RANK.high) >= DETAIL_TIER_RANK.high
- : (settings?.particleDensity ?? 1) >= 1
-);
-
-// Drei <Text> props for an informational in-world label that stays legible in both
-// the night-neon scene AND the bright daytime scene. At night (dayMix→0) the label keeps
-// its neon fill with a hairline dark keyline so it survives the bright grid and props. As day
-// ramps up (dayMix→1) the fill lerps toward a dark ink — readable against the bright
-// sky and sunlit mid-tone facades where a glowing neon fill just washes out — and a
-// light outline halo fades in to lift the glyphs off whatever's behind them. The ink
-// keeps a hint of the label's hue so day labels stay loosely color-coded by status.
-// Continuous in dayMix so it degrades gracefully if an intermediate time-of-day is
-// ever re-enabled (today dayMix is strictly 0 or 1). Decorative neon signage is NOT
-// a caller — it is meant to dim in daylight like real neon.
-export const openWorldLabelColors = (neonColor, dayMix = 0) => {
- const d = Math.max(0, Math.min(1, dayMix || 0));
- const darkInk = mixHex('#0d1422', neonColor, 0.22);
- return {
- color: mixHex(neonColor, darkInk, d),
- outlineColor: d > 0 ? '#eef4ff' : '#020817',
- // Percentage strings are relative to fontSize, so the keyline scales with each label.
- // The tiny night keyline is intentionally subdued; daylight gets the stronger halo.
- outlineWidth: `${(0.9 + d * 10.1).toFixed(2)}%`,
- outlineOpacity: 0.45 + d * 0.37,
- };
-};
-
-// Get a deterministic neon accent color per app (for windows/decorations). The accent
-// list defaults to the static palette; pass a themed palette's `neonAccents` to follow
-// a theme switch (its lead entry tracks the theme accent).
-export const getAccentColor = (app, neonAccents = CITY_COLORS.neonAccents) => {
- const hash = hashString(app.name || app.id);
- return neonAccents[hash % neonAccents.length];
-};
-
-// --- Theme integration -------------------------------------------------------
-// OpenWorld's "brand" surfaces (ground grid, particles, online buildings, the
-// lead neon accent, the dark structural bases) default to cyan. When the user picks
-// a PortOS theme, deriveOpenWorldPalette recolors those surfaces toward the theme accent
-// so the 3D scene tracks the rest of the UI; status colors (stopped=red, etc.) stay
-// semantic. The palette is a fresh immutable object per theme — every brand surface
-// is recomputed from the theme accent (never from a previous theme), so repeated
-// switches can't compound. ORIGINAL_GROUND is the fallback accent for a theme with no
-// --port-accent; the cyan-era brand defaults are captured up front to recompute from.
-const ORIGINAL_GROUND = CITY_COLORS.ground;
-const ORIGINAL_BUILDING_BODY = CITY_COLORS.buildingBody;
-
-// Shared color primitives. parseHex: "#0a7a4a" -> [10, 122, 74] (null on bad input).
-// toHex: clamps/rounds each channel back to "#rrggbb".
-const parseHex = (hex) => {
- const m = /^#([0-9a-f]{6})$/i.exec(hex || '');
- if (!m) return null;
- const n = parseInt(m[1], 16);
- return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
-};
-const toHex = (r, g, b) => '#' + [r, g, b]
- .map((v) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, '0'))
- .join('');
-
-// "10 122 74" (a --port-* rgb triplet) -> "#0a7a4a"
-const tripletToHex = (triplet) => {
- if (typeof triplet !== 'string') return null;
- const parts = triplet.trim().split(/\s+/).map(Number);
- if (parts.length !== 3 || parts.some(Number.isNaN)) return null;
- return toHex(parts[0], parts[1], parts[2]);
-};
-
-const darkenHex = (hex, factor) => {
- const rgb = parseHex(hex);
- return rgb ? toHex(rgb[0] * factor, rgb[1] * factor, rgb[2] * factor) : hex;
-};
-
-// Mix a hex color t of the way toward white (t in 0..1). Used to derive a bright,
-// accent-tinted daytime sky backdrop from the theme accent.
-const lightenHex = (hex, t) => {
- const rgb = parseHex(hex);
- return rgb ? toHex(...rgb.map((c) => c + (255 - c) * t)) : hex;
-};
-
-// Mix two hex colors (t in 0..1, 0=a, 1=b).
-export const mixHex = (a, b, t) => {
- const ca = parseHex(a);
- const cb = parseHex(b);
- return ca && cb ? toHex(...ca.map((c, i) => c + (cb[i] - c) * t)) : a;
-};
-
-// Tint a color toward the theme accent by `amount`, then rescale to the original
-// luminance so ONLY hue/saturation shift — the scene's brightness hierarchy (dark
-// structural bases stay dark, bright sky bands stay bright) is preserved while every
-// surface picks up the theme. The accent defaults to the static cyan brand; pass a
-// themed palette's accent to track a theme switch. Pure; null-safe.
-export const tintTowardAccent = (hex, amount = 0.2, accentHex = CITY_COLORS.ground) => {
- const base = parseHex(hex);
- const accent = parseHex(accentHex);
- if (!base || !accent) return hex;
- const lum = (c) => 0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2];
- const lb = lum(base);
- if (lb === 0) return hex; // pure black has no hue to tint
- const mixed = base.map((c, i) => c + (accent[i] - c) * amount);
- const lm = lum(mixed) || 1;
- const k = lb / lm; // rescale mixed back to the base's luminance
- return toHex(mixed[0] * k, mixed[1] * k, mixed[2] * k);
-};
-
-// Convenience for the dark structural bases (building bodies, district plinths,
-// monument footings) — a slightly stronger tint than the default. The accent defaults
-// to the static brand; pass a themed accent (from useOpenWorldPalette().accent) to theme.
-export const tintStructure = (hex, accentHex = CITY_COLORS.ground) => tintTowardAccent(hex, 0.22, accentHex);
-
-// GLSL-style smoothstep with an edge remap (distinct from the plain Hermite
-// smoothstep(t) in utils/easing.js — different arity, kept local on purpose).
-export const smoothstepRange = (a, b, x) => {
- if (a === b) return x < a ? 0 : 1;
- const t = Math.max(0, Math.min(1, (x - a) / (b - a)));
- return t * t * (3 - 2 * t);
-};
-
-// Deterministic Park-Miller LCG. Returns a () => [0,1) generator seeded from an
-// integer — the shared form of the inline seeded-random used across city scenery
-// so a given seed always yields the same building/terrain layout.
-export const seededRand = (seed) => {
- let s = seed;
- return () => {
- s = (s * 16807) % 2147483647;
- return (s & 0x7fffffff) / 2147483647;
- };
-};
-
-// --- World style -------------------------------------------------------------
-// OpenWorld renders in one of two art directions, and the style is DATA rather than a
-// binary tested in four places: every consumer reads a field off the def below instead of
-// asking "is this cyber?". Adding a third style means adding a row here, not editing the
-// sky resolver, the palette, the layer gates, and the settings picker.
-//
-// - presets the time-of-day pair fed to OpenWorldSky / OpenWorldLights / OpenWorldGround. Through
-// each preset's daylightFactor → openWorldDayMix, this alone carries most of the
-// look: every surface that already lerped night→day follows it for free.
-// - lowPoly flat-shaded, matte structural surfaces (see the palette's `surface`).
-// - neonLayers whether the neon-night scene layers (galaxy spheremap, starfield, shooting
-// stars, data rain, embers, volumetric light cones, neon signage) mount at
-// all. Over a sunlit low-poly landscape they read as haze and grain, so they
-// are gated out rather than faded per-frame.
-// - accents the decorative spread for windows/props. The lead slot is always replaced
-// by the live theme accent, so the world follows the UI in either style.
-// - buildingBody the structural body color, re-tinted toward the theme accent.
-// - terrain the daytime bands OpenWorldLandscape's terrain shader mixes between.
-//
-// 'cyber' is kept as a real option, not nostalgia: it keeps the whole neon layer exercised
-// by the suite instead of bit-rotting behind a default nobody selects.
-export const WORLD_STYLE_DEFS = {
- vibes: {
- id: 'vibes',
- label: 'OPEN WORLD',
- presets: { day: 'vibesDay', night: 'vibesDusk' },
- lowPoly: true,
- neonLayers: false,
- // Warm sand / coral / teal / sage / amber instead of the cyberpunk neon set, so the
- // bright low-poly world doesn't wear night-club colors.
- accents: ['#63f2db', '#f07f6d', '#d7b98c', '#9873b9', '#f3b562', '#57c9c0', '#8c7169', '#dde4df'],
- // A painted coastal palette: blue-green city soil, sage meadows, and cool stone
- // ridges keep the empty world readable before any live app towers arrive.
- buildingBody: '#7e9e90',
- terrain: { inner: '#6d8f8f', meadow: '#91b983', ridge: '#7896a2' },
- },
- cyber: {
- id: 'cyber',
- label: 'CYBER CITY',
- presets: { day: 'noon', night: 'sunset' },
- lowPoly: false,
- neonLayers: true,
- accents: CITY_COLORS.neonAccents,
- buildingBody: ORIGINAL_BUILDING_BODY,
- terrain: { inner: '#686d68', meadow: '#6f8758', ridge: '#8d937f' },
- },
-};
-
-export const WORLD_STYLES = Object.keys(WORLD_STYLE_DEFS);
-export const DEFAULT_WORLD_STYLE = 'vibes';
-
-// Sentinel-safe: an absent / legacy / misspelled stored value resolves to the default
-// rather than silently selecting an undefined style.
-export const resolveWorldStyle = (style) => (
- Object.hasOwn(WORLD_STYLE_DEFS, style) ? style : DEFAULT_WORLD_STYLE
-);
-
-// The style's definition, always a real one.
-export const getWorldStyle = (style) => WORLD_STYLE_DEFS[resolveWorldStyle(style)];
-
-// OpenWorld renders just two times of day — day and night — and follows the active
-// theme's mode by default ('auto'). The user can still force 'day'/'night'. Legacy
-// stored values (sunrise/noon/sunset/midnight) are treated as 'auto' so existing
-// installs pick up theme coupling without a migration. Open World uses its selected
-// preset pair; Cyber City is intentionally locked to its moonlit-night preset because
-// its neon materials are authored for darkness.
-export const resolveOpenWorldTimeOfDay = (setting, themeIsDay, worldStyle) => {
- const style = getWorldStyle(worldStyle);
- // Cyber City is an explicitly nocturnal art direction. Keeping that invariant here means
- // a theme switch, an old stored time-of-day value, and the settings drawer can never put
- // its neon materials under a daylight preset.
- if (style.id === 'cyber') return { daytime: false, presetKey: style.presets.night };
-
- const daytime = setting === 'day' ? true
- : setting === 'night' ? false
- : !!themeIsDay;
- return { daytime, presetKey: daytime ? style.presets.day : style.presets.night };
-};
-
-// Derive the OpenWorld palette from a PortOS theme object (a THEMES entry) and the
-// active world style. Pure. The style swaps the decorative/structural brand surfaces
-// (nothing semantic): status colors stay semantic in both worlds.
-export const deriveOpenWorldPalette = (theme, worldStyle) => {
- const style = getWorldStyle(worldStyle);
- const { lowPoly } = style;
- const accent = tripletToHex(theme?.colors?.['--port-accent']) || ORIGINAL_GROUND;
- const isDay = theme?.mode === 'day';
- // Night backdrop: a near-black, accent-tinted void — the neon's additive/bloom
- // materials need darkness or they blow out. Day backdrop: a bright, accent-tinted
- // sky (the daytime preset dims the neon, so a light surround is safe and reads as
- // actual daytime). The scene picks one based on the resolved time of day; the HUD
- // panels follow the light/dark theme independently (see .openworld-themed CSS).
- // In the Vibes world there is no neon to protect, and "night" is a golden dusk — so
- // both surrounds are bright sky rather than a near-black void.
- const nightBackground = lowPoly
- ? getTimeOfDayPreset(style.presets.night).midSky
- : darkenHex(accent, 0.1);
- const dayBackground = lowPoly
- ? getTimeOfDayPreset(style.presets.day).midSky
- : lightenHex(accent, 0.72);
-
- // Themed brand surfaces — recomputed from the theme accent each time, so switching
- // back and forth never compounds. The lead neonAccents entry tracks the accent;
- // the rest of the spread is the world style's decorative palette. The structural
- // body color is re-tinted toward the accent (luminance preserved) so structures
- // track the theme too, not just the accent surfaces. Status colors stay semantic.
- const neonAccents = [accent, ...style.accents.slice(1)];
- const building = { ...CITY_COLORS.building, online: accent };
- const buildingBody = tintStructure(style.buildingBody, accent);
-
- return {
- themeId: theme?.id || 'classic-midnight',
- mode: theme?.mode || 'night',
- isDay,
- // The active art direction. Scene components read these off the palette they already
- // consume rather than re-resolving the style from settings — one bit, one channel.
- worldStyle: style.id,
- lowPoly,
- neonLayers: style.neonLayers,
- terrain: style.terrain,
- // Material props every structural world mesh spreads so it inherits the art direction
- // instead of hardcoding a finish: `<meshStandardMaterial … {...surface} />`, spread
- // AFTER the mesh's own roughness/metalness so the style wins where it has an opinion.
- // Low-poly worlds read by their facets — flat shading gives each face one normal — and
- // a matte, non-metallic finish keeps buildings looking painted rather than wet like the
- // cyber city's glass. Derived here (not per render) so its identity is stable and r3f
- // never sees a changed material prop; `flatShading` is part of three.js's shader program
- // cache key, so a value that flipped per render would recompile every lit material.
- surface: lowPoly
- ? { flatShading: true, roughness: 0.95, metalness: 0 }
- : { flatShading: false },
- accent,
- nightBackground,
- dayBackground,
- // Default surround by theme mode — used for the loading screen before settings resolve.
- background: isDay ? dayBackground : nightBackground,
- // Brand surfaces the 3D scene reads via useOpenWorldPalette() instead of the old
- // mutated singleton. `ground`/`particles` are the accent; `building`/`buildingBody`/
- // `neonAccents` carry the themed maps.
- ground: accent,
- particles: accent,
- neonAccents,
- building,
- buildingBody,
- // Helper functions pre-bound to this palette's accent/maps, so a consumer can call
- // `palette.tintStructure(hex)` (no accent threading) and still track the theme. These
- // are the themed equivalents of the bare module helpers, which default to the static
- // cyan brand when called without a palette.
- tintTowardAccent: (hex, amount = 0.2) => tintTowardAccent(hex, amount, accent),
- tintStructure: (hex) => tintStructure(hex, accent),
- getBuildingColor: (status, archived) => getBuildingColor(status, archived, building),
- getAccentColor: (app) => getAccentColor(app, neonAccents),
- };
-};
diff --git a/client/src/components/openworld/openWorldHudBits.jsx b/client/src/components/openworld/openWorldHudBits.jsx
deleted file mode 100644
index e88c73d62e..0000000000
--- a/client/src/components/openworld/openWorldHudBits.jsx
+++ /dev/null
@@ -1,68 +0,0 @@
-// Small presentational bits shared by the OpenWorld HUD panels (desktop cockpit +
-// compact/phone disclosure surfaces). Extracted so the vitals rows, health
-// sentinel and corner chrome render identically in both layouts instead of being
-// copy-pasted per host.
-
-// Animated corner decoration for HUD panels.
-export function HudCorner({ position = 'tl', color = 'cyan' }) {
- const corners = {
- tl: 'top-0 left-0 border-t border-l',
- tr: 'top-0 right-0 border-t border-r',
- bl: 'bottom-0 left-0 border-b border-l',
- br: 'bottom-0 right-0 border-b border-r',
- };
- return (
- <div
- className={`absolute w-2 h-2 ${corners[position]} border-${color}-400/60`}
- style={{ borderWidth: '1px' }}
- />
- );
-}
-
-export function HealthBar({ value, max, color }) {
- const pct = max > 0 ? (value / max) * 100 : 0;
- return (
- <div className="w-full h-1 bg-gray-800/60 rounded-full overflow-hidden">
- <div
- className="h-full rounded-full transition-all duration-1000"
- style={{ width: `${pct}%`, backgroundColor: color, boxShadow: `0 0 4px ${color}` }}
- />
- </div>
- );
-}
-
-// A tappable vitals row (label + value). 44px min height keeps it a valid touch
-// target on phone where these rows become the primary controls.
-export function StatButton({ label, valueClass, value, onClick, title, prefix = null }) {
- return (
- <button
- type="button"
- onClick={onClick}
- title={title}
- aria-label={title || label}
- className="w-full flex items-center justify-between gap-6 -mx-1 px-1 py-0.5 min-h-[44px] sm:min-h-0 rounded hover:bg-cyan-500/5 transition-colors"
- >
- <span className="font-pixel text-[10px] text-gray-400 tracking-wide">{label}</span>
- <span className={`font-pixel text-[11px] ${valueClass || 'text-cyan-400'}`}>
- {prefix}
- {value}
- </span>
- </button>
- );
-}
-
-export const getHealthSentinel = (systemHealth, onlineRatio) => {
- if (systemHealth?.overallHealth === 'critical') return { dot: 'bg-port-error', text: 'text-port-error', label: 'CRITICAL' };
- if (systemHealth?.overallHealth === 'warning') return { dot: 'bg-port-warning', text: 'text-port-warning', label: 'WARN' };
- if (systemHealth?.overallHealth === 'healthy') return { dot: 'bg-port-success', text: 'text-port-success', label: 'OK' };
- if (onlineRatio >= 0.8) return { dot: 'bg-cyan-400', text: 'text-cyan-400', label: 'OK' };
- if (onlineRatio >= 0.5) return { dot: 'bg-port-warning', text: 'text-port-warning', label: 'WARN' };
- return { dot: 'bg-port-error', text: 'text-port-error', label: 'CRIT' };
-};
-
-export const metricColor = (pct) => {
- if (pct == null) return 'text-gray-500';
- if (pct >= 90) return 'text-port-error';
- if (pct >= 75) return 'text-port-warning';
- return 'text-cyan-400';
-};
diff --git a/client/src/components/openworld/openWorldLayout.js b/client/src/components/openworld/openWorldLayout.js
deleted file mode 100644
index cf3b49faf4..0000000000
--- a/client/src/components/openworld/openWorldLayout.js
+++ /dev/null
@@ -1,107 +0,0 @@
-import { BUILDING_PARAMS, DISTRICT_PARAMS, getBuildingHeight } from './openWorldConstants';
-import { autoColumns, gridIndexToPosition } from '../../utils/openWorldDistrictLayout';
-
-const STATUS_ORDER = { online: 0, stopped: 1, not_started: 2, not_found: 3 };
-
-// Keep downtown buildings off the central AI Core landmark: anything that lands
-// inside a one-cell plaza radius is pushed out onto the plaza ring so its
-// tower/label doesn't intersect the core. A building exactly at the origin has no
-// radial direction, so it starts from a fixed front bearing.
-const CORE_CLEARANCE_RADIUS = BUILDING_PARAMS.spacing;
-const CENTER_FALLBACK_ANGLE = -Math.PI / 2;
-
-const cleanZero = (n) => (Math.abs(n) < 1e-9 ? 0 : n);
-const slotKey = (x, z) => `${Math.round(x)},${Math.round(z)}`;
-
-// Push a cell that sits inside the core plaza out onto the plaza ring, starting
-// from its own radial bearing (or the front fallback for a dead-centre cell) and
-// fanning out in 45° steps to dodge any slot already taken. Without the dodge, an
-// odd×odd grid's centre cell would land on the front-edge cell that's already on
-// the ring (e.g. 9 apps → two buildings stacked at (0, -spacing)).
-const placeOnPlazaRing = (x, z, occupied) => {
- const baseAngle = (x === 0 && z === 0) ? CENTER_FALLBACK_ANGLE : Math.atan2(z, x);
- const onRing = (angle) => ({
- x: cleanZero(Math.cos(angle) * CORE_CLEARANCE_RADIUS),
- z: cleanZero(Math.sin(angle) * CORE_CLEARANCE_RADIUS),
- });
- for (let step = 0; step < 8; step++) {
- // 0, +45, -45, +90, -90, … — radial bearing first, then fan symmetrically.
- const offset = Math.ceil(step / 2) * (step % 2 === 1 ? 1 : -1) * (Math.PI / 4);
- const slot = onRing(baseAngle + offset);
- if (!occupied.has(slotKey(slot.x, slot.z))) return slot;
- }
- return onRing(baseAngle);
-};
-
-export const computeOpenWorldLayout = (apps) => {
- const active = [];
- const archived = [];
-
- apps.forEach(app => {
- if (app.archived) {
- archived.push(app);
- } else {
- active.push(app);
- }
- });
-
- // Sort active: online first, then stopped, then not_started
- active.sort((a, b) => (STATUS_ORDER[a.overallStatus] ?? 3) - (STATUS_ORDER[b.overallStatus] ?? 3));
-
- const positions = new Map();
- const { spacing } = BUILDING_PARAMS;
- const occupied = new Set();
-
- // Downtown district (active apps): a roughly-square grid centered on the origin (both axes).
- const activeCols = autoColumns(active.length);
- const activeRows = Math.ceil(active.length / activeCols);
-
- const downtownCells = active.map((app, i) => {
- const [x, , z] = gridIndexToPosition(i, { columns: activeCols, spacing, rowCount: activeRows });
- return { app, x, z };
- });
-
- // Pass 1: cells already clear of the plaza keep their grid slot (and reserve it).
- const insidePlaza = [];
- downtownCells.forEach((cell) => {
- if (Math.hypot(cell.x, cell.z) >= CORE_CLEARANCE_RADIUS) {
- occupied.add(slotKey(cell.x, cell.z));
- positions.set(cell.app.id, { x: cell.x, z: cell.z, district: 'downtown', height: getBuildingHeight(cell.app) });
- } else {
- insidePlaza.push(cell);
- }
- });
-
- // Pass 2: cells inside the plaza get pushed to a free spot on the plaza ring.
- insidePlaza.forEach((cell) => {
- const { x, z } = placeOnPlazaRing(cell.x, cell.z, occupied);
- occupied.add(slotKey(x, z));
- positions.set(cell.app.id, { x, z, district: 'downtown', height: getBuildingHeight(cell.app) });
- });
-
- // Warehouse district (archived apps): X-centered grid offset along +Z from downtown.
- // The +Z offset follows downtown's depth, but is floored so the near row (and the
- // ARCHIVE DISTRICT label two units in front of it) always clears the central AI Core
- // plaza. Without the floor, few-/no-active-app installs collapse the warehouse onto
- // the core (all-archived → warehouseZ 4, label at z=2, on top of the monument). The
- // floor is a no-op for normal installs: any layout with 3+ active apps already has
- // activeRows ≥ 2, so warehouseZ is already ≥ CORE_CLEARANCE_RADIUS + gap.
- if (archived.length > 0) {
- const archiveCols = autoColumns(archived.length);
- const warehouseZ = Math.max(
- activeRows * spacing / 2 + DISTRICT_PARAMS.gap,
- CORE_CLEARANCE_RADIUS + DISTRICT_PARAMS.gap,
- );
-
- archived.forEach((app, i) => {
- const [x, , z] = gridIndexToPosition(i, {
- columns: archiveCols,
- spacing,
- base: [0, 0, warehouseZ],
- });
- positions.set(app.id, { x, z, district: 'warehouse', height: getBuildingHeight(app) });
- });
- }
-
- return positions;
-};
diff --git a/client/src/components/openworld/openWorldLayout.test.js b/client/src/components/openworld/openWorldLayout.test.js
deleted file mode 100644
index fe28b16df9..0000000000
--- a/client/src/components/openworld/openWorldLayout.test.js
+++ /dev/null
@@ -1,95 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import { computeOpenWorldLayout } from './openWorldLayout';
-
-// spacing = BUILDING_PARAMS.spacing = 12, DISTRICT_PARAMS.gap = 4 (see openWorldConstants.js)
-const online = (id) => ({ id, overallStatus: 'online', archived: false });
-
-describe('computeOpenWorldLayout', () => {
- it('lays active apps around a reserved AI Core plaza', () => {
- const pos = computeOpenWorldLayout([online('a'), online('b'), online('c'), online('d')]);
- // 4 apps → 2 cols, 2 rows at ±6; each cell falls inside the 12-unit core plaza,
- // so clearCorePlaza pushes it radially out to the plaza edge (12/√2 ≈ 8.4853).
- expect(pos.get('a').district).toBe('downtown');
- expect(pos.get('a').x).toBeCloseTo(-8.485281);
- expect(pos.get('a').z).toBeCloseTo(-8.485281);
- expect(pos.get('b').x).toBeCloseTo(8.485281);
- expect(pos.get('b').z).toBeCloseTo(-8.485281);
- expect(pos.get('c').x).toBeCloseTo(-8.485281);
- expect(pos.get('c').z).toBeCloseTo(8.485281);
- expect(pos.get('d').x).toBeCloseTo(8.485281);
- expect(pos.get('d').z).toBeCloseTo(8.485281);
- // Plaza clearance only rewrites x/z — each entry still carries a numeric building
- // height (consumed by the PlayerController proximity check).
- expect(typeof pos.get('a').height).toBe('number');
- expect(pos.get('a').height).toBeGreaterThan(0);
- });
-
- it('pushes a lone centered app to the front edge of the core plaza', () => {
- const pos = computeOpenWorldLayout([online('solo')]);
- // A single app grids to the origin, which has no push direction → front (-Z) edge.
- expect(pos.get('solo')).toMatchObject({ x: 0, z: -12, district: 'downtown' });
- expect(typeof pos.get('solo').height).toBe('number');
- });
-
- it('offsets archived apps into a warehouse grid clear of the core plaza on sparse installs', () => {
- const pos = computeOpenWorldLayout([
- online('a'),
- { id: 'x', overallStatus: 'online', archived: true },
- { id: 'y', overallStatus: 'online', archived: true },
- ]);
- // 1 active → raw warehouseZ = 1*12/2 + 4 = 10, which sits inside the 12-unit core
- // plaza — so the floor lifts it to CORE_CLEARANCE_RADIUS + gap = 16. 2 archived → 2
- // cols, X offset 6. The active app clears to the plaza front edge.
- expect(pos.get('a')).toMatchObject({ x: 0, z: -12, district: 'downtown' });
- expect(pos.get('x')).toMatchObject({ x: -6, z: 16, district: 'warehouse' });
- expect(pos.get('y')).toMatchObject({ x: 6, z: 16, district: 'warehouse' });
- });
-
- it('keeps the warehouse off the core on an all-archived install (no active apps)', () => {
- const pos = computeOpenWorldLayout([
- { id: 'x', overallStatus: 'online', archived: true },
- { id: 'y', overallStatus: 'online', archived: true },
- ]);
- // No active apps → raw warehouseZ = 0*12/2 + 4 = 4, which would drop the near row
- // (and the ARCHIVE DISTRICT label at z-2) on top of the AI Core. The floor lifts the
- // near row to 16 so the label lands at z=14, clear of the 12-unit core plaza.
- expect(pos.get('x')).toMatchObject({ x: -6, z: 16, district: 'warehouse' });
- expect(pos.get('y')).toMatchObject({ x: 6, z: 16, district: 'warehouse' });
- });
-
- it('leaves the warehouse offset untouched for normal installs (3+ active apps)', () => {
- const pos = computeOpenWorldLayout([
- online('a'), online('b'), online('c'),
- { id: 'x', overallStatus: 'online', archived: true },
- ]);
- // 3 active → activeRows 2 → raw warehouseZ = 2*12/2 + 4 = 16, already at the floor,
- // so max(16, 16) is a no-op: established layouts for normal installs don't shift.
- expect(pos.get('x')).toMatchObject({ x: 0, z: 16, district: 'warehouse' });
- });
-
- it('never stacks two downtown buildings when clearing the core plaza', () => {
- // 9 apps → 3×3 grid: the centre cell sits on the core and must move, but the
- // front-edge slot is already taken, so it must dodge to a free ring slot rather
- // than stack. Assert every resolved position is unique.
- const pos = computeOpenWorldLayout(Array.from({ length: 9 }, (_, i) => online(String(i))));
- const seen = new Set();
- for (const p of pos.values()) {
- const key = `${Math.round(p.x)},${Math.round(p.z)}`;
- expect(seen.has(key)).toBe(false);
- seen.add(key);
- }
- expect(seen.size).toBe(9);
- });
-
- it('sorts active apps online-first so status drives grid order', () => {
- const pos = computeOpenWorldLayout([
- { id: 'stopped', overallStatus: 'stopped', archived: false },
- { id: 'live', overallStatus: 'online', archived: false },
- ]);
- // online sorts to index 0 (col 0), stopped to index 1 (col 1) at ±6; clearCorePlaza
- // then pushes both out along ±X to the 12-unit plaza edge.
- expect(pos.get('live')).toMatchObject({ x: -12, z: 0, district: 'downtown' });
- expect(pos.get('stopped')).toMatchObject({ x: 12, z: 0, district: 'downtown' });
- });
-});
-// @vitest-environment node
diff --git a/client/src/components/openworld/openWorldPanes.js b/client/src/components/openworld/openWorldPanes.js
deleted file mode 100644
index c87e4d2c4e..0000000000
--- a/client/src/components/openworld/openWorldPanes.js
+++ /dev/null
@@ -1,32 +0,0 @@
-// Secondary-HUD disclosure surfaces, driven by the `openWorldPane` URL search param so
-// the open surface is deep-linkable, reload-safe, and restored by browser
-// back/forward — the same "URL is the source of truth for what's open" convention
-// the rest of the app follows. A single param means only ONE surface can be open at
-// a time (mutual exclusivity is structural, not enforced by hand). Clearing the
-// param returns to the unobstructed 3D scene.
-//
-// `attention` / `timeline` / `activity` double as the desktop Intel pane's active
-// tab, so the same param addresses the Intel tab on the cockpit and the disclosure
-// sheet on phone/compact.
-export const CITY_PANE_IDS = [
- 'vitals',
- 'attention',
- 'timeline',
- 'activity',
- 'map',
- 'filter',
- 'legend',
-];
-
-// The subset that maps to the Intel pane's tabs (shared with the desktop cockpit).
-export const CITY_INTEL_PANE_IDS = ['attention', 'timeline', 'activity'];
-
-export const CITY_PANE_LABELS = {
- vitals: 'Vitals',
- attention: 'Attention',
- timeline: 'Timeline',
- activity: 'Activity',
- map: 'Map',
- filter: 'Filter',
- legend: 'Legend',
-};
diff --git a/client/src/components/openworld/openWorldTheme.test.js b/client/src/components/openworld/openWorldTheme.test.js
deleted file mode 100644
index 6cad6e0f92..0000000000
--- a/client/src/components/openworld/openWorldTheme.test.js
+++ /dev/null
@@ -1,442 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import { deriveOpenWorldPalette, resolveOpenWorldTimeOfDay, openWorldLabelColors, tintTowardAccent, tintStructure, CITY_COLORS, getBuildingColor, getAccentColor, seededRand, smoothstepRange, openWorldDayMix, getTimeOfDayPreset, openWorldShowDetail, openWorldShowInteriorWindows, resolveWorldStyle, getWorldStyle, WORLD_STYLE_DEFS, WORLD_STYLES, DEFAULT_WORLD_STYLE } from './openWorldConstants';
-
-const hexLum = (hex) => {
- const n = parseInt(hex.slice(1), 16);
- const r = (n >> 16) & 255, g = (n >> 8) & 255, b = n & 255;
- return 0.299 * r + 0.587 * g + 0.114 * b;
-};
-const hexChannels = (hex) => {
- const n = parseInt(hex.slice(1), 16);
- return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
-};
-import { getTheme, THEMES } from '../../themes/portosThemes';
-
-describe('deriveOpenWorldPalette', () => {
- it('derives the accent hex from a theme --port-accent triplet', () => {
- const phosphor = getTheme('black-ice-terminal-day');
- const p = deriveOpenWorldPalette(phosphor);
- expect(p.accent).toBe('#086c43'); // 8 108 67
- expect(p.themeId).toBe('black-ice-terminal-day');
- expect(p.isDay).toBe(true);
- });
-
- it('exposes a dark night void and a bright day sky, both accent-tinted', () => {
- const phosphor = getTheme('black-ice-terminal-day'); // accent #086c43
- const p = deriveOpenWorldPalette(phosphor, 'cyber');
- expect(p.nightBackground).toBe('#010b07'); // #086c43 * 0.1
- expect(p.dayBackground).toBe('#bad6ca'); // #086c43 lightened 0.72 toward white
- // A day theme's default surround (loading screen) is the bright day sky.
- expect(p.isDay).toBe(true);
- expect(p.background).toBe('#bad6ca');
- });
-
- it('defaults a night theme surround to the dark void', () => {
- const midnight = getTheme('classic-midnight'); // accent #2563eb
- const p = deriveOpenWorldPalette(midnight, 'cyber');
- expect(p.isDay).toBe(false);
- expect(p.background).toBe('#040a18'); // nightBackground = #2563eb * 0.1
- expect(p.dayBackground).toBe('#c2d3f9');
- });
-
- it('falls back to defaults for a missing/invalid theme', () => {
- const p = deriveOpenWorldPalette(undefined, 'cyber');
- expect(p.themeId).toBe('classic-midnight');
- expect(p.accent).toBe('#06b6d4'); // original cyan brand
- expect(p.background).toBe('#011215'); // night theme default -> #06b6d4 * 0.1
- });
-
- it('keeps Cyber City nocturnal regardless of theme or legacy time settings', () => {
- for (const setting of ['auto', undefined, 'sunrise', 'noon', 'sunset', 'midnight', 'day', 'night']) {
- expect(resolveOpenWorldTimeOfDay(setting, true, 'cyber')).toEqual({ daytime: false, presetKey: 'sunset' });
- expect(resolveOpenWorldTimeOfDay(setting, false, 'cyber')).toEqual({ daytime: false, presetKey: 'sunset' });
- }
- });
-
- it('follows the selected day/night mode for Open World', () => {
- expect(resolveOpenWorldTimeOfDay('auto', true, 'vibes')).toEqual({ daytime: true, presetKey: 'vibesDay' });
- expect(resolveOpenWorldTimeOfDay('auto', false, 'vibes')).toEqual({ daytime: false, presetKey: 'vibesDusk' });
- expect(resolveOpenWorldTimeOfDay('day', false, 'vibes')).toEqual({ daytime: true, presetKey: 'vibesDay' });
- expect(resolveOpenWorldTimeOfDay('night', true, 'vibes')).toEqual({ daytime: false, presetKey: 'vibesDusk' });
- });
-
- it('picks the Vibes preset pair by default, and for any unrecognized style', () => {
- // The default world style is 'vibes' — an absent, legacy, or misspelled value must
- // resolve there rather than falling through to an undefined preset key.
- expect(resolveOpenWorldTimeOfDay('auto', true)).toEqual({ daytime: true, presetKey: 'vibesDay' });
- expect(resolveOpenWorldTimeOfDay('auto', false)).toEqual({ daytime: false, presetKey: 'vibesDusk' });
- expect(resolveOpenWorldTimeOfDay('day', false, 'nonsense')).toEqual({ daytime: true, presetKey: 'vibesDay' });
- expect(resolveOpenWorldTimeOfDay('night', true, undefined)).toEqual({ daytime: false, presetKey: 'vibesDusk' });
- });
-
- it('keeps both Vibes presets bright, so neither reads as the neon-night look', () => {
- // Every dayMix-driven surface (grid, fog, puddles, neon albedo, label ink) lerps on
- // daylightFactor. If dusk dropped low the world would silently fall back to the cyber
- // night grade under a Vibes sky.
- for (const key of ['vibesDay', 'vibesDusk']) {
- const preset = getTimeOfDayPreset(key);
- expect(preset.daylightFactor).toBeGreaterThan(0.8);
- expect(preset.isMoon).toBe(false);
- expect(openWorldDayMix({ timeOfDay: key })).toBeGreaterThan(0.9);
- }
- });
-
- it('derives a valid palette for every shipped theme (4 day + 4 night)', () => {
- const themes = Object.values(THEMES);
- const day = themes.filter((t) => t.mode === 'day');
- const night = themes.filter((t) => t.mode === 'night');
- // The OpenWorld must support all 8 PortOS themes — 4 day, 4 night.
- expect(day).toHaveLength(4);
- expect(night).toHaveLength(4);
-
- for (const theme of themes) {
- const p = deriveOpenWorldPalette(theme, 'cyber');
- expect(p.themeId).toBe(theme.id);
- expect(p.isDay).toBe(theme.mode === 'day');
- // Accent is parsed to a concrete hex (never left as a raw triplet/empty).
- expect(p.accent).toMatch(/^#[0-9a-f]{6}$/);
- // Day surround is a bright sky; night surround is a near-black void — and the
- // two are always distinct so the backdrop actually swaps with time of day.
- expect(p.dayBackground).toMatch(/^#[0-9a-f]{6}$/);
- expect(p.nightBackground).toMatch(/^#[0-9a-f]{6}$/);
- expect(p.dayBackground).not.toBe(p.nightBackground);
- expect(p.background).toBe(p.isDay ? p.dayBackground : p.nightBackground);
- }
- });
-
-});
-
-describe('city sky visibility', () => {
- it('keeps daytime horizon bands blue enough to avoid a white sky wash', () => {
- const noon = getTimeOfDayPreset('noon', 'cyberpunk');
- const horizonLow = hexChannels(noon.horizonLow);
- const horizonHigh = hexChannels(noon.horizonHigh);
-
- // The lower horizon can be bright, but should not be near-white across all
- // channels; otherwise the sky dome becomes a fog overlay.
- expect(Math.max(...horizonLow) - Math.min(...horizonLow)).toBeGreaterThan(35);
- expect(Math.max(...horizonHigh) - Math.min(...horizonHigh)).toBeGreaterThan(45);
- expect(hexLum(noon.horizonLow)).toBeLessThan(205);
- });
-
- it('falls back to the cyber sky for legacy dreamworld settings', () => {
- const cyber = getTimeOfDayPreset('noon', 'cyberpunk');
- const noon = getTimeOfDayPreset('noon', 'dreamworld');
- expect(noon).toBe(cyber);
- });
-});
-
-describe('openWorldLabelColors', () => {
- it('keeps the neon fill with a hairline keyline at night (dayMix 0)', () => {
- const c = openWorldLabelColors('#06b6d4', 0);
- expect(c.color).toBe('#06b6d4'); // untouched neon
- expect(c.outlineColor).toBe('#020817');
- expect(c.outlineWidth).toBe('0.90%');
- expect(c.outlineOpacity).toBeCloseTo(0.45);
- });
-
- it('darkens the fill toward ink and fades in a light outline by day (dayMix 1)', () => {
- const c = openWorldLabelColors('#06b6d4', 1);
- // Fill lands on the dark ink (a near-black tinted 22% toward the label hue),
- // i.e. clearly darker than the original neon so it reads on a bright sky.
- expect(c.color).not.toBe('#06b6d4');
- const lum = parseInt(c.color.slice(1, 3), 16) + parseInt(c.color.slice(3, 5), 16) + parseInt(c.color.slice(5, 7), 16);
- expect(lum).toBeLessThan(180); // dark ink (~140), far below the neon's ~400
- expect(c.outlineColor).toBe('#eef4ff');
- expect(c.outlineWidth).toBe('11.00%');
- expect(c.outlineOpacity).toBeCloseTo(0.82);
- });
-
- it('clamps out-of-range / missing dayMix', () => {
- expect(openWorldLabelColors('#06b6d4', 2).outlineOpacity).toBeCloseTo(0.82);
- expect(openWorldLabelColors('#06b6d4', -1).outlineWidth).toBe('0.90%');
- expect(openWorldLabelColors('#06b6d4').color).toBe('#06b6d4'); // undefined → night
- });
-});
-
-describe('tintTowardAccent / tintStructure', () => {
- // These are now pure: the accent is passed in explicitly (no shared-singleton read).
- it('shifts hue toward the accent while preserving luminance', () => {
- const base = '#0a0e16'; // a dark blue-dominant structural base
- const out = tintStructure(base, '#ff0000'); // pure red accent
- // Luminance preserved within rounding — the base stays just as dark.
- expect(hexLum(out)).toBeCloseTo(hexLum(base), 0);
- // Hue pulled toward red: the red channel rises relative to the original.
- expect(hexChannels(out)[0]).toBeGreaterThan(hexChannels(base)[0]);
- });
-
- it('leaves pure black untouched (no hue to tint)', () => {
- expect(tintTowardAccent('#000000', 0.2, '#22c55e')).toBe('#000000');
- });
-
- it('is a no-op-ish identity when the accent equals the base hue direction', () => {
- // Tinting toward itself preserves the color (luminance + channels unchanged).
- expect(hexLum(tintStructure('#0a0e16', '#0a0e16'))).toBeCloseTo(hexLum('#0a0e16'), 0);
- });
-
- it('returns the input unchanged for an unparseable color', () => {
- expect(tintTowardAccent('not-a-hex', 0.2, '#22c55e')).toBe('not-a-hex');
- });
-
- it('defaults to the static cyan brand accent when none is passed', () => {
- // The bare helper (no accent arg) tints toward the cyan brand default, so a
- // consumer that hasn't wired the palette still gets a sensible result.
- const out = tintStructure('#0a0e16');
- expect(out).toMatch(/^#[0-9a-f]{6}$/);
- expect(hexLum(out)).toBeCloseTo(hexLum('#0a0e16'), 0);
- });
-});
-
-describe('deriveOpenWorldPalette — world style', () => {
- it('reports the resolved style and its low-poly flag', () => {
- expect(deriveOpenWorldPalette(getTheme('classic-midnight'), 'cyber')).toMatchObject({ worldStyle: 'cyber', lowPoly: false });
- expect(deriveOpenWorldPalette(getTheme('classic-midnight'), 'vibes')).toMatchObject({ worldStyle: 'vibes', lowPoly: true });
- // Absent / unrecognized falls back to the default rather than an undefined style.
- expect(deriveOpenWorldPalette(getTheme('classic-midnight'))).toMatchObject({ worldStyle: 'vibes', lowPoly: true });
- expect(deriveOpenWorldPalette(getTheme('classic-midnight'), 'neon-noir')).toMatchObject({ worldStyle: 'vibes', lowPoly: true });
- });
-
- it('gives the Vibes world a bright surround at BOTH times of day', () => {
- // The cyber world needs darkness for its additive neon; the Vibes world has none, and
- // its "night" is a golden dusk — so neither surround may be a near-black void.
- const p = deriveOpenWorldPalette(getTheme('classic-midnight'), 'vibes');
- expect(hexLum(p.nightBackground)).toBeGreaterThan(80);
- expect(hexLum(p.dayBackground)).toBeGreaterThan(80);
- });
-
- it('lightens the structural body relative to the cyber world', () => {
- const theme = getTheme('classic-midnight');
- const cyber = deriveOpenWorldPalette(theme, 'cyber');
- const vibes = deriveOpenWorldPalette(theme, 'vibes');
- expect(hexLum(vibes.buildingBody)).toBeGreaterThan(hexLum(cyber.buildingBody));
- });
-
- it('swaps the decorative spread but keeps the theme accent leading, in both styles', () => {
- const theme = getTheme('classic-midnight');
- const cyber = deriveOpenWorldPalette(theme, 'cyber');
- const vibes = deriveOpenWorldPalette(theme, 'vibes');
- expect(vibes.neonAccents[0]).toBe(vibes.accent);
- expect(cyber.neonAccents[0]).toBe(cyber.accent);
- expect(vibes.neonAccents.slice(1)).not.toEqual(cyber.neonAccents.slice(1));
- expect(vibes.neonAccents).toHaveLength(cyber.neonAccents.length);
- });
-
- it('keeps status colors semantic in both styles', () => {
- const theme = getTheme('classic-midnight');
- for (const style of ['cyber', 'vibes']) {
- const p = deriveOpenWorldPalette(theme, style);
- expect(p.getBuildingColor('stopped')).toBe(CITY_COLORS.building.stopped);
- expect(p.getBuildingColor('online', true)).toBe(CITY_COLORS.building.archived);
- }
- });
-});
-
-describe('deriveOpenWorldPalette brand surfaces', () => {
- it('carries themed brand surfaces derived from the accent', () => {
- const p = deriveOpenWorldPalette(getTheme('black-ice-terminal-day'));
- expect(p.ground).toBe('#086c43');
- expect(p.particles).toBe('#086c43');
- expect(p.building.online).toBe('#086c43');
- expect(p.neonAccents[0]).toBe('#086c43');
- // online buildings follow the recolor through the palette-bound helper
- expect(p.getBuildingColor('online')).toBe('#086c43');
- });
-
- it('leaves status colors untouched', () => {
- const p = deriveOpenWorldPalette(getTheme('black-ice-terminal-day'));
- expect(p.building.stopped).toBe('#ef4444');
- expect(p.getBuildingColor('stopped')).toBe('#ef4444');
- // not_found stays the canonical purple — the value ProcessBuilding now unifies to.
- expect(p.building.not_found).toBe('#8b5cf6');
- });
-
- it('re-tints the building body toward the accent, preserving its darkness', () => {
- const ORIGINAL_BODY = '#0c0c24';
- const p = deriveOpenWorldPalette(getTheme('black-ice-terminal-day'), 'cyber'); // green accent
- expect(p.buildingBody).not.toBe(ORIGINAL_BODY); // picked up the theme
- expect(hexLum(p.buildingBody)).toBeCloseTo(hexLum(ORIGINAL_BODY), 0); // still a dark body
- });
-
- it('is pure — never mutates the shared CITY_COLORS singleton', () => {
- deriveOpenWorldPalette(getTheme('black-ice-terminal-day'));
- // The static table keeps its cyan baseline; only the returned palette is themed.
- expect(CITY_COLORS.ground).toBe('#06b6d4');
- expect(CITY_COLORS.building.online).toBe('#06b6d4');
- expect(CITY_COLORS.neonAccents[0]).toBe('#06b6d4');
- expect(CITY_COLORS.buildingBody).toBe('#0c0c24');
- // The bare helper, reading no palette, still reports the static brand.
- expect(getBuildingColor('online')).toBe('#06b6d4');
- });
-
- it('does not compound across repeated derivations — each is recomputed from the accent', () => {
- const green = deriveOpenWorldPalette(getTheme('black-ice-terminal-day'));
- deriveOpenWorldPalette(getTheme('classic-midnight'));
- const greenAgain = deriveOpenWorldPalette(getTheme('black-ice-terminal-day'));
- // classic-midnight accent is 37 99 235 -> #2563eb, never a blend of green+blue.
- expect(deriveOpenWorldPalette(getTheme('classic-midnight')).ground).toBe('#2563eb');
- // Re-deriving the green theme yields an identical body — proof it's recomputed
- // from ORIGINAL_BUILDING_BODY, not from a previously-tinted value.
- expect(greenAgain.buildingBody).toBe(green.buildingBody);
- });
-
- it('binds getAccentColor to the themed neon list', () => {
- const p = deriveOpenWorldPalette(getTheme('black-ice-terminal-day'));
- // The lead neon accent tracks the theme, so an app hashing to index 0 gets it.
- expect(p.neonAccents[0]).toBe('#086c43');
- // Bound helper picks from the palette's list; the bare helper picks from the
- // static list. Both are deterministic for a given app and stay in their list.
- const app = { name: 'anything' };
- expect(p.neonAccents).toContain(p.getAccentColor(app));
- expect(CITY_COLORS.neonAccents).toContain(getAccentColor(app));
- });
-});
-
-describe('seededRand', () => {
- it('is deterministic for a given seed', () => {
- const a = seededRand(42);
- const b = seededRand(42);
- const seqA = [a(), a(), a(), a(), a()];
- const seqB = [b(), b(), b(), b(), b()];
- expect(seqA).toEqual(seqB);
- });
-
- it('produces different streams for different seeds', () => {
- const a = seededRand(42);
- const b = seededRand(137);
- expect(a()).not.toBe(b());
- });
-
- it('yields values in [0, 1)', () => {
- const r = seededRand(3187);
- for (let i = 0; i < 100; i++) {
- const v = r();
- expect(v).toBeGreaterThanOrEqual(0);
- expect(v).toBeLessThan(1);
- }
- });
-
- it('matches the original inline LCG it replaced', () => {
- // Reference: the exact expression copy-pasted across the city components.
- let s = 77;
- const ref = () => { s = (s * 16807) % 2147483647; return (s & 0x7fffffff) / 2147483647; };
- const r = seededRand(77);
- expect([r(), r(), r()]).toEqual([ref(), ref(), ref()]);
- });
-});
-
-describe('smoothstepRange', () => {
- it('clamps below edge0 to 0 and above edge1 to 1', () => {
- expect(smoothstepRange(0.35, 1, 0.2)).toBe(0);
- expect(smoothstepRange(0.35, 1, 1)).toBe(1);
- expect(smoothstepRange(0.35, 1, 2)).toBe(1);
- });
-
- it('returns the Hermite midpoint at the center', () => {
- expect(smoothstepRange(0, 1, 0.5)).toBeCloseTo(0.5, 10);
- });
-
- it('guards against a zero-width range', () => {
- expect(smoothstepRange(0.5, 0.5, 0.4)).toBe(0);
- expect(smoothstepRange(0.5, 0.5, 0.6)).toBe(1);
- });
-});
-
-describe('openWorldDayMix', () => {
- it('is 1 in full daylight and 0 at night', () => {
- expect(openWorldDayMix({ timeOfDay: 'noon' })).toBe(1);
- expect(openWorldDayMix({ timeOfDay: 'sunset' })).toBe(0);
- });
-
- it('defaults to the night preset when unset', () => {
- expect(openWorldDayMix(undefined)).toBe(0);
- });
-});
-
-describe('adaptive render-tier gates', () => {
- // Internal tier densities: low 0.5, medium 0.75, high 1.0, ultra 1.5.
- it('openWorldShowDetail turns on above the low tier', () => {
- expect(openWorldShowDetail({ particleDensity: 0.5 })).toBe(false);
- expect(openWorldShowDetail({ particleDensity: 0.75 })).toBe(true);
- expect(openWorldShowDetail(undefined)).toBe(true); // defaults to 1
- });
-
- it('openWorldShowInteriorWindows holds one tier above detail (high+)', () => {
- expect(openWorldShowInteriorWindows({ particleDensity: 0.5 })).toBe(false);
- expect(openWorldShowInteriorWindows({ particleDensity: 0.75 })).toBe(false);
- expect(openWorldShowInteriorWindows({ particleDensity: 1.0 })).toBe(true);
- expect(openWorldShowInteriorWindows({ particleDensity: 1.5 })).toBe(true);
- expect(openWorldShowInteriorWindows(undefined)).toBe(true); // defaults to 1
- });
-
- it('detail gates prefer the explicit effectiveTier over particleDensity', () => {
- // effectiveTier is authoritative when present — particleDensity is ignored. The
- // warm-up path expresses its detail suppression by setting effectiveTier:'low'
- // (see OpenWorldScene.renderSettings), not by clamping particleDensity.
- expect(openWorldShowDetail({ effectiveTier: 'low', particleDensity: 2 })).toBe(false);
- expect(openWorldShowDetail({ effectiveTier: 'medium', particleDensity: 0.1 })).toBe(true);
- expect(openWorldShowInteriorWindows({ effectiveTier: 'medium', particleDensity: 2 })).toBe(false);
- expect(openWorldShowInteriorWindows({ effectiveTier: 'high', particleDensity: 0.1 })).toBe(true);
- expect(openWorldShowInteriorWindows({ effectiveTier: 'ultra' })).toBe(true);
- });
-});
-// @vitest-environment node
-
-describe('resolveWorldStyle / getWorldStyle', () => {
- it('passes through a known style', () => {
- for (const style of WORLD_STYLES) expect(resolveWorldStyle(style)).toBe(style);
- });
-
- it('falls back to the default for absent, legacy, or malformed values', () => {
- for (const bad of [undefined, null, '', 'CYBER', 'neon', 0, {}]) {
- expect(resolveWorldStyle(bad)).toBe(DEFAULT_WORLD_STYLE);
- }
- });
-
- it('always returns a real definition, even for a bad style', () => {
- for (const bad of [undefined, null, '', 'neon', 0, {}]) {
- expect(getWorldStyle(bad)).toBe(WORLD_STYLE_DEFS[DEFAULT_WORLD_STYLE]);
- }
- });
-
- it('gates the neon-only scene layers on the cyber style alone', () => {
- // OpenWorldScene mounts the galaxy spheremap, starfield, data rain, embers, volumetric
- // cones, and neon signage on palette.neonLayers. An absent style must NOT read as
- // cyber — that would haze the default bright world.
- expect(deriveOpenWorldPalette(undefined, 'cyber').neonLayers).toBe(true);
- expect(deriveOpenWorldPalette(undefined, 'vibes').neonLayers).toBe(false);
- expect(deriveOpenWorldPalette(undefined).neonLayers).toBe(false);
- expect(deriveOpenWorldPalette(undefined, 'nonsense').neonLayers).toBe(false);
- });
-
- it('every style definition is complete, so a new row cannot half-register', () => {
- for (const [id, def] of Object.entries(WORLD_STYLE_DEFS)) {
- expect(def.id).toBe(id);
- expect(def.label).toBeTruthy();
- // Both preset keys must name a real time-of-day preset, or the sky renders undefined.
- expect(getTimeOfDayPreset(def.presets.day)).toBeDefined();
- expect(getTimeOfDayPreset(def.presets.night)).toBeDefined();
- expect(CITY_COLORS.timeOfDay[def.presets.day]).toBeDefined();
- expect(CITY_COLORS.timeOfDay[def.presets.night]).toBeDefined();
- expect(typeof def.lowPoly).toBe('boolean');
- expect(typeof def.neonLayers).toBe('boolean');
- expect(def.accents.length).toBeGreaterThan(1);
- expect(def.buildingBody).toMatch(/^#[0-9a-f]{6}$/i);
- for (const band of ['inner', 'meadow', 'ridge']) {
- expect(def.terrain[band]).toMatch(/^#[0-9a-f]{6}$/i);
- }
- }
- });
-
- it('carries a style-appropriate material surface for structural meshes', () => {
- // flatShading is part of three.js's shader program cache key, so this must be a
- // concrete boolean on both styles rather than absent on one of them.
- expect(deriveOpenWorldPalette(undefined, 'vibes').surface)
- .toEqual({ flatShading: true, roughness: 0.95, metalness: 0 });
- expect(deriveOpenWorldPalette(undefined, 'cyber').surface).toEqual({ flatShading: false });
- });
-
- it('exposes the style terrain bands so components do not hardcode hexes', () => {
- expect(deriveOpenWorldPalette(undefined, 'vibes').terrain).toEqual(WORLD_STYLE_DEFS.vibes.terrain);
- expect(deriveOpenWorldPalette(undefined, 'cyber').terrain).toEqual(WORLD_STYLE_DEFS.cyber.terrain);
- });
-});
diff --git a/client/src/components/threejsModels/ThreejsModelPreview.jsx b/client/src/components/threejsModels/ThreejsModelPreview.jsx
index 80837bc8ae..447af1a2e8 100644
--- a/client/src/components/threejsModels/ThreejsModelPreview.jsx
+++ b/client/src/components/threejsModels/ThreejsModelPreview.jsx
@@ -23,7 +23,7 @@ import {
getEffectiveTier,
recordFrame,
resetRenderBudget,
-} from '../../utils/openWorldRenderBudget';
+} from '../../utils/renderBudget';
const radians = (degrees = 0) => THREE.MathUtils.degToRad(degrees);
const rotation = (degrees = [0, 0, 0]) => degrees.map(radians);
@@ -243,8 +243,8 @@ function SceneRefit({ growth, clipId }) {
}
// The preview owns only the R3F sampling boundary; the quality decisions stay in
-// openWorldRenderBudget so its warm-up, hysteresis, cooldown, and gap handling remain
-// deterministic and shared with OpenWorld.
+// renderBudget so its warm-up, hysteresis, cooldown, and gap handling remain
+// deterministic and reusable.
function PreviewAdaptiveQuality({ enabled, resetToken, onTierChange }) {
const stateRef = useRef(null);
if (stateRef.current === null) stateRef.current = createRenderBudget('high', 0);
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 19b67f637c..96d3ef82d6 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -111,10 +111,9 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useStoryImportIntake` | Story Builder "Import a finished work" intake: the form fields plus the analyze → commit → create-session workflow, in one `{ ...state, patch, analyze, retryIssues, importAndBuild }` bag. | Call from the always-mounted Story Builder index and pass down as `intake` — holding this in the panel loses the manuscript and analysis on an intake tab flip (#3904). |
| `useRowDraft` | Multi-column row draft (analogue of `useFieldDraft`). | Multi-column row that commits as a unit. |
| `usePendingListRows` | List-of-rows where a new row is held client-side until a required column fills, then promoted to `onChange`. | Editable list whose nameless rows would otherwise be dropped by the server sanitizer (WardrobeSection, CharacterDetailEditor list sections). |
-| `useKeyboardControls` | Held-key Set for the OpenWorld rig plus the Tab mode toggle. Keydowns aimed at an editable field, or fired while an `aria-modal` dialog is open, are ignored — movement is for the world behind the UI. Keyup and the window `blur` reset are deliberately ungated, so a key held when a dialog opens still clears. | OpenWorld-specific. A surface that must CLAIM a key an app-global handler binds wants `useKeyCapture` instead. |
| `useFirstTouchHint` | `{ visible, showOnFirstTouch }` — reveals a brief one-time touch gesture hint, then auto-hides it. | 3D canvases whose primary one-finger gesture needs an initial explanation. |
| `useKeyCapture` | `useKeyCapture({ enabled?, enabledInDialog?, onKeyDown, onKeyUp })` — capture-phase window listener whose handler *claims* an event by returning `true`; a claimed event is `preventDefault`ed AND `stopImmediatePropagation`ed so no app-global bubble handler sees it. Which events are offered is decided by the shared `shouldIgnoreGlobalKey` predicate (`lib/a11yKeyboard.js`): never events from an editable field, never Space on a focused button (so native activation still works), and not while an `aria-modal` dialog is open (`{ enabledInDialog: true }` for a surface that lives INSIDE one — same name and default as `useKeyboardShortcuts`). Auto-repeat and ⌘/Ctrl/Alt chords deliberately DO still arrive, because a claiming surface tracks press/release itself. Each listener subscribes only when its handler is supplied. | A surface that must own a key an app-global handler already binds — chiefly Space, which the voice widget uses for push-to-talk: the POST cognitive drills (n-back, go/no-go, reaction-time), the Morse keyer, RapidReader, the OpenWorld playback transport, and the exploration-mode jump key. Not for ordinary shortcuts (that is `useKeyboardShortcuts`). |
-| `useKeyboardShortcuts` | `useKeyboardShortcuts(active, bindings, opts?)` — fire a `{ key: handler }` map while `active`; ignores whatever the shared `shouldIgnoreGlobalKey` predicate (`lib/a11yKeyboard.js`) rules out — editable fields, Space on a focused button, ⌘/Ctrl/Alt chords, OS key auto-repeat (`{ ignoreRepeat: false }` to opt back in), and any keystroke while an `aria-modal` dialog is open (`{ enabledInDialog: true }` for a modal-owned shortcut); a falsy handler disables that key. | Single-surface action shortcuts (editorial comment card prev/next + accept/dismiss/generate, #1603). Not for held-key/game input (that's `useKeyboardControls`). |
+| `useKeyboardShortcuts` | `useKeyboardShortcuts(active, bindings, opts?)` — fire a `{ key: handler }` map while `active`; ignores whatever the shared `shouldIgnoreGlobalKey` predicate (`lib/a11yKeyboard.js`) rules out — editable fields, Space on a focused button, ⌘/Ctrl/Alt chords, OS key auto-repeat (`{ ignoreRepeat: false }` to opt back in), and any keystroke while an `aria-modal` dialog is open (`{ enabledInDialog: true }` for a modal-owned shortcut); a falsy handler disables that key. | Single-surface action shortcuts (editorial comment card prev/next + accept/dismiss/generate, #1603). Not for held-key game input. |
| `useHfTokenStatus` | Reads the central HuggingFace token status (`GET /image-gen/setup/hf-token-status` → `server/lib/hfToken.js`: stored → env → `hf auth login`). Returns `{ present, source, refresh }` where `present` is TRI-state — `null` means "unknown/failed", not "absent" — so a slow fetch can't flash a token nag at a user who has one. `{ enabled }` gates the fetch (false resets to unknown, so a modal re-checks per open); `{ errorAs: 'absent' }` opts a surface into offering the paste form when the status call fails. | Any gated-HuggingFace surface (3D page, MIDI gated modal, Image Gen banners) — use this instead of re-rolling the fetch, or the same blip renders differently per page. |
| `useKeyboardHelp` | Esc closes, even from inputs/textareas. | Help/cheatsheet modals. |
| `useLiveSuggest` | Post-typing debounce for an imperative panel trigger: `{ registerTrigger, scheduleSuggest }` re-arms one `debounceMs` timer per keystroke and fires the registered fn only while `enabled` and still mounted. | An editor that asks a sibling AI panel to suggest once the writer pauses (WorkEditor ↔ LiveContinuationPanel). |
@@ -161,11 +160,6 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useAppOverrideActions` | Per-app scheduled-task override mutations (`{ handleUpdateOverride, handleBulkToggleOverride }`) with shared toast copy + silent flag; pass the tab's `refetch`. | Any surface hosting `PerAppOverrideList` (Schedule tab, Timeline tab) — don't re-copy the write-plus-toast-plus-refetch handlers. |
| `useTaskModelPins` | Provider/model/effort pins for one CoS scheduled task: optimistic write per change (`'' → null` clears; picking a provider clears model+effort, picking a model clears the effort only when that model has no tiers at all), rollback when `onUpdate` resolves falsy, a `saving` flag to gate "Run Now", plus the derived `availableModels` (Antigravity base models, stale pin kept selectable), `effectiveProviderId` and `defaultProviderLabel` a `ProviderModelSelector` needs. | Any surface that retargets a scheduled task's model (schedule card quick controls, config drawer Global defaults) — don't re-roll the select/PUT/rollback trio. |
| `useCanonPatch` | Optimistic canon-entry patch: rebuild the kind list with one entry mutated, apply locally, PATCH the universe, re-apply the server copy. Targets + staleness-guards on the loaded record's `universe.id` so a mid-flight universe swap can't cross-PATCH or resurrect stale state. `apply` is `setUniverse` or `onUniverseChange`. | Inline canon-field edits on a universe (UniverseCanonSection, NounsStage). Don't re-roll the optimistic-then-confirm dance. |
-| `useOpenWorldAudio` | OpenWorld ambient audio. | OpenWorld only. |
-| `useOpenWorldData` | OpenWorld environment data + physics. | OpenWorld only. |
-| `useOpenWorldPlayback` | Timeline-scrubber transport: loads the snapshot series, steps a frame index, play/pause/speed. | OpenWorld playback (history) mode only. |
-| `useOpenWorldViewport` | Classifies the window width into `phone` / `compact` / `desktop` brackets (mirrors Tailwind `sm`/`lg`) so the OpenWorld HUD can branch between the desktop cockpit and the compact/phone disclosure layout in JS (only one tree mounts). Returns `{ mode, isPhone, isCompact, isDesktop, isCondensed }`. | OpenWorld HUD responsive layout only. |
-| `useOpenWorldSettings` | OpenWorld quality presets + persistence. | OpenWorld only. |
| `useColorMatch` | Drives a song color-match run: counts the singer in with the metronome, walks the notated score in tempo, grades each note against the live mic pitch (#1022 tracker + colorMatch lib), and exposes `{ running, countingIn, noteColors, summary, activeIndex, start, stop }` for the `<ScoreSheet>` + an accuracy readout. Taps the passed recording stream (no second mic); tears down on stop/unmount. | The Song editor's color-match panel. Don't re-wire the metronome + tracker + grading loop by hand. |
| `useCodeReviewDefaults` | Global Code Review Defaults (Review Loop reviewer chain + every per-reviewer `<reviewer>Model` / `<reviewer>Effort` pin scalar) via a small Provider/hook pair. | TaskAddForm, ScheduleTab, anywhere a default reviewer picker is shown. |
| `useCatalogTypes` | Catalog ingredient type registry (system + user-defined) merged with the static fallback via a Provider/hook pair; synchronous fallback to the built-in six so first render never blanks. | Catalog list/picker/editor; anywhere the catalog type list/lookup is needed. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 4b03b6fe03..62f9f11309 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -13,7 +13,6 @@ export { default as useAudioSessionClaim } from './useAudioSessionClaim.js';
export { default as useAsyncCaptureGuard } from './useAsyncCaptureGuard.js';
export { default as useAssignableInstances } from './useAssignableInstances.js';
export { default as useAutoscroll } from './useAutoscroll.js';
-export { default as useOpenWorldAudio } from './useOpenWorldAudio.js';
export { default as useClonedGltf } from './useClonedGltf.jsx';
export * from './useClonedGltf.jsx';
export { default as useAutoSizeTextarea } from './useAutoSizeTextarea.js';
@@ -45,7 +44,6 @@ export { default as useRoundRows } from './useRoundRows.js';
export { default as useRoundViewParams } from './useRoundViewParams.js';
export { default as useSongTraining } from './useSongTraining.js';
export { default as useMediaPreviewActions } from './useMediaPreviewActions.js';
-export { default as useKeyboardControls } from './useKeyboardControls.js';
export { default as useKeyCapture } from './useKeyCapture.js';
export { default as useKeyboardShortcuts } from './useKeyboardShortcuts.js';
export * from './useKeyboardShortcuts.js';
@@ -102,8 +100,6 @@ export { default as useTokenPopover } from './useTokenPopover.js';
// === Mixed (both default and named) — surface both ===
export { default as useAsyncAction } from './useAsyncAction.js';
export * from './useAsyncAction.js';
-export { default as useOpenWorldSettings } from './useOpenWorldSettings.js';
-export * from './useOpenWorldSettings.js';
// === Notifications & toasts ===
export * from './useAIStatusNotifications.js';
@@ -186,16 +182,12 @@ export * from './useSidebarApps.js';
export * from './useSidebarSeries.js';
export * from './useSidebarUniverses.js';
-// === Domain: OpenWorld / Voice / Mortality / Universe / Apps / Sessions ===
+// === Domain: Voice / Mortality / Universe / Apps / Sessions ===
export * from './useAppDeploy.js';
export * from './useAppOperation.js';
export * from './useAppOverrideActions.js';
export * from './useTaskModelPins.js';
export * from './useCanonPatch.js';
-export * from './useOpenWorldData.js';
-export * from './useOpenWorldPlayback.js';
-export { default as useOpenWorldViewport } from './useOpenWorldViewport.js';
-export * from './useOpenWorldViewport.js';
export * from './useDeathClock.js';
export * from './useFederatedMediaTarget.js';
export * from './useGoalDetail.js';
diff --git a/client/src/hooks/useAutoRefetch.js b/client/src/hooks/useAutoRefetch.js
index b6ebb274a2..0843b9c89c 100644
--- a/client/src/hooks/useAutoRefetch.js
+++ b/client/src/hooks/useAutoRefetch.js
@@ -27,7 +27,7 @@ import { useVisibilityEvent } from './useVisibilityEvent.js';
* @param {boolean} [options.enabled=true] - when false, no interval and no fetch.
* @param {boolean} [options.immediate=true] - when false, skip the on-mount
* fetch and wait `intervalMs` before the first fetch. Use when the caller
- * already performs a one-shot fetch via another path (e.g. `useOpenWorldData.fetchAll`).
+ * already performs a one-shot fetch via another path.
* @param {(prev:any, next:any)=>boolean} [options.compare] - when provided,
* each fetch keeps the previous reference (skipping the re-render) if
* `compare(prev, next)` returns true. Only invoked when both `prev` and
diff --git a/client/src/hooks/useCooldownTick.js b/client/src/hooks/useCooldownTick.js
index 7ee69743bc..7a0a61d4e5 100644
--- a/client/src/hooks/useCooldownTick.js
+++ b/client/src/hooks/useCooldownTick.js
@@ -22,7 +22,7 @@ export function useCooldownTick(options = {}) {
// is always visible to the interval tick — a useEffect-driven ref update
// can lag one render behind and, if `onAllExpired` changes right before
// the expiry tick, the interval would fire the previous closure once.
- // Pattern mirrored from usePostSession.js / useOpenWorldAudio.js.
+ // Pattern mirrored from usePostSession.js.
const callbackRef = useRef(onAllExpired);
callbackRef.current = onAllExpired;
diff --git a/client/src/hooks/useKeyboardControls.js b/client/src/hooks/useKeyboardControls.js
deleted file mode 100644
index c583ac8d22..0000000000
--- a/client/src/hooks/useKeyboardControls.js
+++ /dev/null
@@ -1,49 +0,0 @@
-import { useRef, useEffect, useCallback } from 'react';
-import { shouldIgnoreGlobalKey } from '../lib/a11yKeyboard.js';
-
-// Movement input is only ever meant for the world behind the UI, so a keystroke aimed at
-// a form field, at a focused HUD button, or at an open dialog must not reach the rig:
-// typing "w" in the fast-travel search would otherwise walk the avatar, Space on a focused
-// HUD button would jump AND press the button, and Space inside the settings drawer would
-// jump it (Tab likewise has to move focus in those contexts, not flip exploration mode).
-// The shared predicate is the same one PlayerController's own Space claim consults, so the
-// two agree on when the rig stands down. Chords and auto-repeat stay allowed through: the
-// rig reads held keys, so dropping either would strand or stutter a movement key.
-// Note this is a keyDOWN-only gate — keyup always clears, or a key held when a dialog
-// opens would stay stuck down forever.
-const ignoresMovement = (e) => shouldIgnoreGlobalKey(e, { allowChords: true, ignoreRepeat: false });
-
-export default function useKeyboardControls(onToggleMode) {
- const keysRef = useRef(new Set());
-
- const handleKeyDown = useCallback((e) => {
- if (ignoresMovement(e)) return;
- if (e.key === 'Tab') {
- e.preventDefault();
- onToggleMode?.();
- return;
- }
- keysRef.current.add(e.key.toLowerCase());
- }, [onToggleMode]);
-
- const handleKeyUp = useCallback((e) => {
- keysRef.current.delete(e.key.toLowerCase());
- }, []);
-
- const handleBlur = useCallback(() => {
- keysRef.current.clear();
- }, []);
-
- useEffect(() => {
- window.addEventListener('keydown', handleKeyDown);
- window.addEventListener('keyup', handleKeyUp);
- window.addEventListener('blur', handleBlur);
- return () => {
- window.removeEventListener('keydown', handleKeyDown);
- window.removeEventListener('keyup', handleKeyUp);
- window.removeEventListener('blur', handleBlur);
- };
- }, [handleKeyDown, handleKeyUp, handleBlur]);
-
- return keysRef;
-}
diff --git a/client/src/hooks/useKeyboardControls.test.jsx b/client/src/hooks/useKeyboardControls.test.jsx
deleted file mode 100644
index c74cd0f6b5..0000000000
--- a/client/src/hooks/useKeyboardControls.test.jsx
+++ /dev/null
@@ -1,95 +0,0 @@
-import { describe, it, expect, vi, afterEach } from 'vitest';
-import { render, fireEvent, cleanup } from '@testing-library/react';
-import useKeyboardControls from './useKeyboardControls';
-
-// The hook hands back the live held-key Set the OpenWorld rig reads every frame, so the
-// assertions here are about what does and does not end up in that Set.
-const keys = { current: null };
-
-function Probe({ onToggleMode }) {
- keys.current = useKeyboardControls(onToggleMode);
- return <input aria-label="search" />;
-}
-
-function openDialog() {
- const dialog = document.createElement('div');
- dialog.setAttribute('aria-modal', 'true');
- document.body.appendChild(dialog);
- return () => dialog.remove();
-}
-
-afterEach(cleanup);
-
-describe('useKeyboardControls', () => {
- it('records a held movement key and clears it on release', () => {
- render(<Probe />);
-
- fireEvent.keyDown(document.body, { key: 'W' });
- expect(keys.current.current.has('w')).toBe(true);
-
- fireEvent.keyUp(document.body, { key: 'W' });
- expect(keys.current.current.has('w')).toBe(false);
- });
-
- it('clears the released key even for a Space claimed by a capture-phase listener', () => {
- // PlayerController claims the Space keydown (so the voice hotkey never sees it) and
- // adds ' ' itself, then relies on THIS listener to clear it — it binds no keyup.
- render(<Probe />);
- keys.current.current.add(' ');
-
- fireEvent.keyUp(document.body, { key: ' ' });
-
- expect(keys.current.current.has(' ')).toBe(false);
- });
-
- it('ignores keys typed into a form field', () => {
- const { getByLabelText } = render(<Probe />);
-
- fireEvent.keyDown(getByLabelText('search'), { key: 'w' });
-
- expect(keys.current.current.has('w')).toBe(false);
- });
-
- it('ignores movement while a dialog is open, so the rig stays put behind it', () => {
- render(<Probe />);
- const close = openDialog();
-
- fireEvent.keyDown(document.body, { key: ' ' });
- fireEvent.keyDown(document.body, { key: 'w' });
-
- expect(keys.current.current.has(' ')).toBe(false);
- expect(keys.current.current.has('w')).toBe(false);
- close();
- });
-
- it('toggles exploration mode on Tab', () => {
- const onToggleMode = vi.fn();
- render(<Probe onToggleMode={onToggleMode} />);
-
- fireEvent.keyDown(document.body, { key: 'Tab' });
-
- expect(onToggleMode).toHaveBeenCalledTimes(1);
- expect(keys.current.current.has('tab')).toBe(false);
- });
-
- it('leaves Tab alone in a form field and behind a dialog, where it must move focus', () => {
- const onToggleMode = vi.fn();
- const { getByLabelText } = render(<Probe onToggleMode={onToggleMode} />);
-
- fireEvent.keyDown(getByLabelText('search'), { key: 'Tab' });
- const close = openDialog();
- fireEvent.keyDown(document.body, { key: 'Tab' });
- close();
-
- expect(onToggleMode).not.toHaveBeenCalled();
- });
-
- it('drops every held key when the window loses focus', () => {
- render(<Probe />);
- fireEvent.keyDown(document.body, { key: 'w' });
-
- fireEvent.blur(window);
-
- expect(keys.current.current.size).toBe(0);
- });
-});
diff --git a/client/src/hooks/useOpenWorldAudio.js b/client/src/hooks/useOpenWorldAudio.js
deleted file mode 100644
index c641e5750f..0000000000
--- a/client/src/hooks/useOpenWorldAudio.js
+++ /dev/null
@@ -1,110 +0,0 @@
-import { useState, useEffect, useCallback, useRef } from 'react';
-import { initAudio, setMusicVolume, setSfxVolume, scheduleCleanup as scheduleAudioCleanup } from '../components/openworld/audio/openWorldAudioEngine';
-import { startMusic, stopMusic, setSoundscape } from '../components/openworld/audio/openWorldSynthMusic';
-import { playSfx as playSfxFn } from '../components/openworld/audio/openWorldSoundEffects';
-import { applyMoodOverride } from '../utils/openWorldSoundscape';
-
-// `soundscape` is the computeSoundscape() view-model (roadmap 3.4): the live mood/energy the
-// ambient music should reflect. Optional — when omitted the music plays its default progression.
-export default function useOpenWorldAudio(settings, soundscape) {
- const [isAudioReady, setIsAudioReady] = useState(false);
- const initedRef = useRef(false);
- const settingsRef = useRef(settings);
- settingsRef.current = settings;
- // A manual soundscape override (#3395) pins the mood, overriding the live classification; the
- // `null` sentinel (auto) passes the computed soundscape straight through. Everything below
- // works off this effective view-model, so the forced mood reaches every apply path — the
- // gesture-init start, the music-toggle start, and the live-state effect alike.
- const effectiveSoundscape = applyMoodOverride(soundscape, settings?.soundscapeOverride);
- // Mirror the latest soundscape so deferred starts (gesture-init, music-toggle) apply it without
- // depending on render timing.
- const soundscapeRef = useRef(effectiveSoundscape);
- soundscapeRef.current = effectiveSoundscape;
- const musicEnabled = settings?.musicEnabled;
- const musicVolume = settings?.musicVolume;
- const sfxVolume = settings?.sfxVolume;
-
- // Init AudioContext on first user gesture
- useEffect(() => {
- const handleGesture = () => {
- if (initedRef.current) return;
- initedRef.current = true;
- const ctx = initAudio();
- if (ctx) {
- setIsAudioReady(true);
- // Start music if enabled at init time
- if (settingsRef.current?.musicEnabled) {
- startMusic();
- setMusicVolume(settingsRef.current.musicVolume);
- if (soundscapeRef.current) setSoundscape(soundscapeRef.current);
- }
- }
- window.removeEventListener('click', handleGesture);
- window.removeEventListener('keydown', handleGesture);
- };
- window.addEventListener('click', handleGesture);
- window.addEventListener('keydown', handleGesture);
- return () => {
- window.removeEventListener('click', handleGesture);
- window.removeEventListener('keydown', handleGesture);
- };
- }, []);
-
- // Toggle music on/off based on settings. Apply the current soundscape right after starting so
- // the music opens in the right mood rather than the default progression for a beat.
- useEffect(() => {
- if (!isAudioReady || musicEnabled == null) return;
- if (musicEnabled) {
- startMusic();
- if (soundscapeRef.current) setSoundscape(soundscapeRef.current);
- } else {
- stopMusic();
- }
- }, [isAudioReady, musicEnabled]);
-
- // Drive the ambient soundscape from live system state (or the manual override). The deps are
- // the individual field values (not the `soundscape` object), so a poll that recomputes an equal
- // snapshot — a new object with identical fields — doesn't re-ramp the graph; only an actual
- // mood/energy change does. Setting or clearing the override changes these same fields, so the
- // music re-ramps the moment it flips rather than waiting for the next live mood change. The
- // effect reads the freshest snapshot from the ref at run time.
- const mood = effectiveSoundscape?.mood;
- const chordSet = effectiveSoundscape?.chordSet;
- const filterBase = effectiveSoundscape?.filterBase;
- const arpGain = effectiveSoundscape?.arpGain;
- const padDetune = effectiveSoundscape?.padDetune;
- useEffect(() => {
- const s = soundscapeRef.current;
- if (!isAudioReady || !musicEnabled || !s) return;
- setSoundscape(s);
- }, [isAudioReady, musicEnabled, mood, chordSet, filterBase, arpGain, padDetune]);
-
- // Update music volume
- useEffect(() => {
- if (!isAudioReady || !musicEnabled) return;
- setMusicVolume(musicVolume);
- }, [isAudioReady, musicEnabled, musicVolume]);
-
- // Update SFX volume
- useEffect(() => {
- if (!isAudioReady || sfxVolume == null) return;
- setSfxVolume(sfxVolume);
- }, [isAudioReady, sfxVolume]);
-
- // Cleanup on unmount. stopMusic() ramps the music layers to silence and returns
- // how long that ramp takes (ms) — closing the AudioContext immediately would cut
- // the ramp short and reintroduce the pop it exists to avoid, so delay the close
- // until the ramp has actually settled.
- useEffect(() => {
- return () => {
- scheduleAudioCleanup(stopMusic());
- };
- }, []);
-
- const playSfx = useCallback((name) => {
- if (!isAudioReady || !settingsRef.current?.sfxEnabled) return;
- playSfxFn(name);
- }, [isAudioReady]);
-
- return { playSfx, isAudioReady };
-}
diff --git a/client/src/hooks/useOpenWorldAudio.test.jsx b/client/src/hooks/useOpenWorldAudio.test.jsx
deleted file mode 100644
index 68c22c5a1b..0000000000
--- a/client/src/hooks/useOpenWorldAudio.test.jsx
+++ /dev/null
@@ -1,108 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { renderHook, act } from '@testing-library/react';
-
-vi.mock('../components/openworld/audio/openWorldAudioEngine', () => ({
- initAudio: vi.fn(() => ({})),
- setMusicVolume: vi.fn(),
- setSfxVolume: vi.fn(),
- scheduleCleanup: vi.fn(),
-}));
-vi.mock('../components/openworld/audio/openWorldSynthMusic', () => ({
- startMusic: vi.fn(),
- stopMusic: vi.fn(() => 0),
- setSoundscape: vi.fn(),
-}));
-vi.mock('../components/openworld/audio/openWorldSoundEffects', () => ({
- playSfx: vi.fn(),
-}));
-
-import useOpenWorldAudio from './useOpenWorldAudio.js';
-import { setSoundscape } from '../components/openworld/audio/openWorldSynthMusic';
-import { computeSoundscape } from '../utils/openWorldSoundscape';
-
-// A healthy, moderately busy city — the live mood is `bright`, so a `tense` override is an
-// observable change and clearing it back to auto is observable in the other direction.
-const LIVE = computeSoundscape({ systemHealth: { overallHealth: 'healthy' }, agentCount: 3 });
-
-const baseSettings = {
- musicEnabled: true,
- musicVolume: 0.3,
- sfxEnabled: true,
- sfxVolume: 0.5,
- soundscapeOverride: null,
-};
-
-// The AudioContext only comes up on a user gesture; without it the hook never applies anything.
-const primeAudio = () => act(() => { window.dispatchEvent(new Event('click')); });
-
-const lastSoundscape = () => setSoundscape.mock.calls.at(-1)?.[0];
-
-beforeEach(() => {
- vi.clearAllMocks();
-});
-
-describe('useOpenWorldAudio soundscape override', () => {
- it('applies the live soundscape when no override is set', () => {
- renderHook(() => useOpenWorldAudio(baseSettings, LIVE));
- primeAudio();
- expect(lastSoundscape()).toMatchObject({ mood: 'bright', chordSet: 'bright' });
- });
-
- it('applies the forced chord set while the override is set', () => {
- const { rerender } = renderHook(
- ({ settings }) => useOpenWorldAudio(settings, LIVE),
- { initialProps: { settings: baseSettings } },
- );
- primeAudio();
-
- rerender({ settings: { ...baseSettings, soundscapeOverride: 'tense' } });
- expect(lastSoundscape()).toMatchObject({ mood: 'tense', chordSet: 'tense' });
- expect(lastSoundscape().filterBase).toBeLessThan(LIVE.filterBase);
- });
-
- it('keeps the forced mood when live system state changes underneath it', () => {
- const { rerender } = renderHook(
- ({ settings, soundscape }) => useOpenWorldAudio(settings, soundscape),
- { initialProps: { settings: { ...baseSettings, soundscapeOverride: 'bright' }, soundscape: LIVE } },
- );
- primeAudio();
- expect(lastSoundscape()).toMatchObject({ chordSet: 'bright' });
-
- // The system goes critical — auto would swap to the tense table; the override must not.
- const stressed = computeSoundscape({ systemHealth: { overallHealth: 'critical' }, agentCount: 3 });
- rerender({ settings: { ...baseSettings, soundscapeOverride: 'bright' }, soundscape: stressed });
- expect(lastSoundscape()).toMatchObject({ mood: 'bright', chordSet: 'bright' });
- });
-
- it('resumes live computation immediately when the override is cleared to Auto', () => {
- const { rerender } = renderHook(
- ({ settings }) => useOpenWorldAudio(settings, LIVE),
- { initialProps: { settings: { ...baseSettings, soundscapeOverride: 'tense' } } },
- );
- primeAudio();
- expect(lastSoundscape()).toMatchObject({ chordSet: 'tense' });
-
- rerender({ settings: { ...baseSettings, soundscapeOverride: null } });
- expect(lastSoundscape()).toMatchObject({ mood: LIVE.mood, chordSet: LIVE.chordSet });
- expect(lastSoundscape().filterBase).toBeCloseTo(LIVE.filterBase, 5);
- });
-
- it('ignores an unknown stored override value and stays on live state', () => {
- renderHook(() => useOpenWorldAudio({ ...baseSettings, soundscapeOverride: 'stale-mood' }, LIVE));
- primeAudio();
- expect(lastSoundscape()).toMatchObject({ mood: LIVE.mood, chordSet: LIVE.chordSet });
- });
-
- it('does not re-apply when a poll recomputes an identical soundscape', () => {
- const { rerender } = renderHook(
- ({ soundscape }) => useOpenWorldAudio(baseSettings, soundscape),
- { initialProps: { soundscape: LIVE } },
- );
- primeAudio();
- const callsAfterInit = setSoundscape.mock.calls.length;
-
- // A fresh object with identical fields — the graph must not re-ramp.
- rerender({ soundscape: { ...LIVE } });
- expect(setSoundscape.mock.calls.length).toBe(callsAfterInit);
- });
-});
diff --git a/client/src/hooks/useOpenWorldData.js b/client/src/hooks/useOpenWorldData.js
deleted file mode 100644
index 2d25c937a7..0000000000
--- a/client/src/hooks/useOpenWorldData.js
+++ /dev/null
@@ -1,372 +0,0 @@
-import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
-import * as api from '../services/api';
-import socket from '../services/socket';
-import { useAutoRefetch } from './useAutoRefetch';
-import { METRICS as HEALTH_TOWER_METRICS } from '../utils/openWorldHealthTower';
-import { applyAiStatusEvent, pruneAiOps, AI_CORE } from '../utils/openWorldAiCore';
-import { coalesce } from '../utils/coalesce';
-import { appendEventLogBatch } from '../utils/openWorldTimeline';
-
-// Metric keys the vitals-tower landmark renders — fetched as the latest-value snapshot.
-const HEALTH_METRIC_KEYS = HEALTH_TOWER_METRICS.map(m => m.key);
-const EVENT_LOG_FLUSH_MS = 100;
-
-const healthSignature = (h) => {
- const warnings = (h?.warnings || []).map(w => `${w.type}:${w.message}`).join(';');
- return `${h?.overallHealth}|${h?.system?.cpu?.usagePercent}|${h?.system?.memory?.usagePercent}|${h?.system?.disk?.usagePercent}|${warnings}`;
-};
-
-export const useOpenWorldData = () => {
- const [apps, setApps] = useState([]);
- const [cosAgents, setCosAgents] = useState([]);
- const [cosStatus, setCosStatus] = useState({ running: false });
- const [runningAgents, setRunningAgents] = useState([]);
- const [eventLogs, setEventLogs] = useState([]);
- const [reviewCounts, setReviewCounts] = useState({ total: 0, alert: 0, todo: 0, briefing: 0, cos: 0 });
- const [instances, setInstances] = useState({ self: null, peers: [], syncStatus: null });
- const [systemHealth, setSystemHealth] = useState(null);
- const [notificationCounts, setNotificationCounts] = useState({ unread: 0 });
- const [backupStatus, setBackupStatus] = useState(null);
- const [cosTasks, setCosTasks] = useState([]);
- const [healthMetrics, setHealthMetrics] = useState(null);
- // Voice-agent district marker: `enabled` from the persisted /voice/status payload,
- // `live` driven by the per-socket voice:* events (idle | listening | dictating | error).
- const [voiceState, setVoiceState] = useState(null);
- const [character, setCharacter] = useState(null);
- // AI Core landmark: in-flight `ai:status` ops keyed by id + the last op-start timestamp
- // (for the flare). Purely event-driven — there's no GET for in-flight ops, so it starts
- // empty and the socket handler below maintains it.
- const [aiActivity, setAiActivity] = useState({ ops: {}, lastStartTs: 0 });
- const [loading, setLoading] = useState(true);
- const logIdRef = useRef(0);
- const pendingEventLogsRef = useRef([]);
- const eventLogFlushTimerRef = useRef(null);
- // One-shot timer that prunes expired AI Core ops. `ai:status` is purely event-driven, so
- // without this a `done` afterglow (or a flare) beam would linger until the next event —
- // the render derivations check the clock but nothing re-renders to advance it.
- const aiPruneTimerRef = useRef(null);
- // Mirror of the latest aiActivity so the prune timer can decide whether to re-arm without
- // depending on React having run the state updater synchronously (it isn't guaranteed to).
- const aiActivityRef = useRef(aiActivity);
- aiActivityRef.current = aiActivity;
-
- const fetchApps = useCallback(async () => {
- // Silent + last-good preservation: this now doubles as the 30s telemetry poll,
- // so a transient /api/apps blip must blank neither the city nor toast repeatedly.
- const data = await api.getApps({ silent: true }).catch(() => null);
- if (data) setApps(data);
- return data;
- }, []);
-
- const fetchAll = useCallback(async () => {
- // /notifications/count returns the lightweight { count } payload — the HUD
- // and Attention pane only need unread, and notifications:count socket
- // events keep it fresh after this initial fetch.
- const [appsData, agents, cosAgentsData, status, reviewData, instanceData, health, notif, backup, cosTasksData, healthMetricsData, voice, characterData] = await Promise.all([
- api.getApps().catch(() => []),
- api.getRunningAgents().catch(() => []),
- api.getCosAgents().catch(() => []),
- api.getCosStatus().catch(() => ({ running: false })),
- api.getReviewCounts().catch(() => ({ total: 0, alert: 0, todo: 0, briefing: 0, cos: 0 })),
- api.getInstances().catch(() => ({ self: null, peers: [], syncStatus: null })),
- api.getSystemHealth({ silent: true }).catch(() => null),
- api.getNotificationCount().catch(() => ({ count: 0 })),
- api.getBackupStatus({ silent: true }).catch(() => null),
- api.getCosTasks({ silent: true }).catch(() => ({ tasks: [] })),
- api.getLatestHealthMetrics(HEALTH_METRIC_KEYS, { silent: true }).catch(() => null),
- api.getVoiceStatus({ silent: true }).catch(() => null),
- // `skills`/`metrics: false` — the city only renders the level (see fetchCharacter).
- api.getCharacter({ silent: true, skills: false, metrics: false }).catch(() => null),
- ]);
-
- setApps(appsData);
- setRunningAgents(agents);
- setCosAgents(cosAgentsData);
- setCosStatus(status);
- setReviewCounts(reviewData);
- setInstances(instanceData);
- setSystemHealth(health);
- setNotificationCounts({ unread: notif?.count ?? 0 });
- setBackupStatus(backup);
- setCosTasks(Array.isArray(cosTasksData?.tasks) ? cosTasksData.tasks : []);
- setHealthMetrics(healthMetricsData);
- // Seed the marker with the persisted enabled flag; live sub-state starts idle and the
- // voice:* socket handlers below take over. Preserve a prior `live` across refetches so
- // a mid-turn fetchAll doesn't snap the beacon back to idle.
- setVoiceState(prev => ({ enabled: voice?.enabled ?? false, live: prev?.live || 'idle' }));
- if (characterData) setCharacter(characterData);
- setLoading(false);
- }, []);
-
- // Pull a fresh backup snapshot status — used after backup:completed so the vault
- // landmark reflects the new lastRun/status without a full fetchAll.
- const fetchBackup = useCallback(async () => {
- const backup = await api.getBackupStatus({ silent: true }).catch(() => null);
- if (backup) setBackupStatus(backup);
- }, []);
-
- const healthInFlightRef = useRef(false);
- const fetchHealth = useCallback(async () => {
- // In-flight guard: a slow /system/health/details (>15s) would otherwise
- // let the next interval tick fire a concurrent request. Drop the new tick
- // when one is already pending; the next interval picks up fresh state.
- if (healthInFlightRef.current) return;
- healthInFlightRef.current = true;
- const health = await api.getSystemHealth({ silent: true }).catch(() => null);
- healthInFlightRef.current = false;
- if (!health) return;
- setSystemHealth(prev => {
- if (prev && healthSignature(prev) === healthSignature(health)) return prev;
- return health;
- });
- }, []);
-
- // Character XP badge: there's no XP-gain socket event, so the only way an XP
- // gain (e.g. a synced JIRA ticket / completed task) surfaces in the HUD is a
- // periodic poll. The Xp badge diffs successive snapshots to fire its burst.
- // Preserve last-good character on a transient blip (don't wipe to null).
- const fetchCharacter = useCallback(async () => {
- // The HUD badge renders only the level, and this polls every 15s — `skills`/`metrics:
- // false` skip the server's domain stat fan-outs that nothing here reads.
- const next = await api.getCharacter({ silent: true, skills: false, metrics: false }).catch(() => null);
- if (next) setCharacter(next);
- }, []);
-
- // Only overwrite the running-agents HUD/list when a fresh fetch lands —
- // a transient blip used to wipe the visible agents to `[]` until the
- // next successful poll.
- const fetchRunningAgents = useCallback(async () => {
- try {
- const agents = await api.getRunningAgents({ silent: true });
- setRunningAgents(agents);
- } catch {
- // preserve last-good agents on transient blip
- }
- }, []);
-
- // `immediate: false` — `fetchAll()` (run from the socket-setup effect below
- // and from agent socket events) already covers the initial fetch for both
- // running agents and system health; the hook then takes over the polling
- // cadence without double-fetching at mount.
- useAutoRefetch(fetchRunningAgents, 10_000, { immediate: false, pollOnly: true });
- useAutoRefetch(fetchHealth, 15_000, { immediate: false, pollOnly: true });
- useAutoRefetch(fetchCharacter, 15_000, { immediate: false, pollOnly: true });
- // PM2 telemetry (cpu/memory/uptime/restarts) drifts continuously and emits no
- // `apps:changed` socket event — without this poll a building's metric readout
- // freezes at whatever the mount-time fetch saw until an app mutation or reload.
- useAutoRefetch(fetchApps, 30_000, { immediate: false, pollOnly: true });
-
- const agentMap = useMemo(() => {
- const map = new Map();
- const allAgents = [...(cosAgents || [])];
-
- allAgents.forEach(agent => {
- if (!agent.workspacePath) return;
- const matchedApp = apps.find(app =>
- app.repoPath && agent.workspacePath.startsWith(app.repoPath)
- );
- if (matchedApp) {
- const existing = map.get(matchedApp.id) || { app: matchedApp, agents: [] };
- existing.agents.push(agent);
- map.set(matchedApp.id, existing);
- }
- });
-
- return map;
- }, [apps, cosAgents]);
-
- // CoS agent spawn/complete events arrive in bursts (a wave of agents starting fires
- // several within milliseconds), and each one triggers a full `fetchAll`. Coalesce those
- // socket-driven refreshes into a single trailing refetch (~120ms) so a burst costs one
- // round of requests instead of N. The mount fetch below stays immediate.
- const coalescedFetchAll = useMemo(() => coalesce(fetchAll, 120), [fetchAll]);
-
- useEffect(() => {
- fetchAll();
-
- const flushEventLogs = () => {
- eventLogFlushTimerRef.current = null;
- if (pendingEventLogsRef.current.length === 0) return;
- const incoming = pendingEventLogsRef.current;
- pendingEventLogsRef.current = [];
- setEventLogs(prev => appendEventLogBatch(prev, incoming));
- };
-
- const subscribe = () => {
- socket.emit('cos:subscribe');
- socket.emit('notifications:subscribe');
- };
- if (socket.connected) subscribe();
- socket.on('connect', subscribe);
-
- const handleAppsChanged = () => fetchApps();
- socket.on('apps:changed', handleAppsChanged);
-
- const handleAgentSpawned = (data) => {
- setCosAgents(prev => [...prev, data]);
- coalescedFetchAll();
- };
- socket.on('cos:agent:spawned', handleAgentSpawned);
-
- const handleAgentUpdated = (updatedAgent) => {
- setCosAgents(prev => prev.map(a => a.agentId === updatedAgent.agentId ? updatedAgent : a));
- };
- socket.on('cos:agent:updated', handleAgentUpdated);
-
- const handleAgentCompleted = () => {
- coalescedFetchAll();
- };
- socket.on('cos:agent:completed', handleAgentCompleted);
-
- const handleCosLog = (data) => {
- const entry = { ...data, timestamp: data.timestamp || Date.now(), _localId: ++logIdRef.current };
- pendingEventLogsRef.current.push(entry);
- if (eventLogFlushTimerRef.current == null) {
- eventLogFlushTimerRef.current = setTimeout(flushEventLogs, EVENT_LOG_FLUSH_MS);
- }
- };
- socket.on('cos:log', handleCosLog);
-
- const handleCosStatus = (data) => {
- setCosStatus(prev => ({ ...prev, running: data.running }));
- };
- socket.on('cos:status', handleCosStatus);
-
- // notifications:count fires after every add/update/remove on the server,
- // so we don't need to listen to those individually or refetch — count is
- // the only field the city UI surfaces.
- const handleNotifCount = (count) => {
- setNotificationCounts(prev => prev?.unread === count ? prev : { unread: count });
- };
- const handleNotifCleared = () => setNotificationCounts({ unread: 0 });
- socket.on('notifications:count', handleNotifCount);
- socket.on('notifications:cleared', handleNotifCleared);
-
- // Backup vault landmark: mark in-flight on start (so the seal pulses blue), then
- // refetch on completion to pick up the fresh lastRun/status and clear `running`.
- const handleBackupStarted = () => setBackupStatus(prev => ({ ...(prev || {}), running: true }));
- // Clear `running` optimistically so the seal stops pulsing blue even if the
- // refetch fails, then pull authoritative lastRun/status from the server.
- const handleBackupCompleted = () => {
- setBackupStatus(prev => (prev?.running ? { ...prev, running: false } : prev));
- fetchBackup();
- };
- socket.on('backup:started', handleBackupStarted);
- socket.on('backup:completed', handleBackupCompleted);
-
- // CoS task-queue silhouette: the server broadcasts the full current task list as
- // `cos:tasks:cos:changed` on every add/modify/complete, so one handler keeps the
- // warehouse's crate stack in sync without per-event bookkeeping.
- const handleCosTasksChanged = (data) => setCosTasks(Array.isArray(data?.tasks) ? data.tasks : []);
- socket.on('cos:tasks:cos:changed', handleCosTasksChanged);
-
- // Voice-agent district marker: the voice pipeline emits these directly to the
- // active socket (no subscribe gate). `voice:dictation` toggles the dictating beacon,
- // `voice:error` lights it red, and `voice:idle` (turn complete / reset) returns it to
- // standby — unless dictation is still on, in which case it stays green.
- const handleVoiceDictation = (data) => setVoiceState(prev => ({
- ...(prev || { enabled: true }),
- enabled: prev?.enabled ?? true,
- live: data?.enabled ? 'dictating' : 'idle',
- }));
- const handleVoiceError = () => setVoiceState(prev => ({ ...(prev || { enabled: true }), live: 'error' }));
- const handleVoiceIdle = () => setVoiceState(prev => (
- // Keep dictating lit while a dictation session is active; a turn ending mid-dictation
- // shouldn't blink the beacon back to standby.
- prev?.live === 'dictating' ? prev : { ...(prev || { enabled: true }), live: 'idle' }
- ));
- socket.on('voice:dictation', handleVoiceDictation);
- socket.on('voice:error', handleVoiceError);
- socket.on('voice:idle', handleVoiceIdle);
-
- // AI Core landmark: every LLM/model call broadcasts phase-tagged `ai:status` events
- // (start → model:loading → model:loaded → complete/error) globally. Track the in-flight
- // set so the central spire glows/beams with live model activity; the pure reducer adds
- // on non-terminal phases, drops on complete/error, and prunes stale ops.
- // Prune expired ops AND clear a stale flare, re-arming while either is still pending —
- // so a `done` afterglow beam (afterglowMs), a stranded in-flight op (opMaxAgeMs), and a
- // flare-only beam (flareMs, when a fast throughput-less call left no op behind) all fade
- // without depending on a further `ai:status` event to advance the clock. Tick at the
- // afterglow cadence; both pruneAiOps and the lastStartTs clear short-circuit to no
- // re-render when nothing expired.
- const scheduleAiPrune = () => {
- if (aiPruneTimerRef.current) clearTimeout(aiPruneTimerRef.current);
- aiPruneTimerRef.current = setTimeout(() => {
- const now = Date.now();
- setAiActivity(prev => {
- const ops = pruneAiOps(prev.ops, now);
- const flareActive = prev.lastStartTs > 0 && now - prev.lastStartTs <= AI_CORE.flareMs;
- const lastStartTs = prev.lastStartTs > 0 && !flareActive ? 0 : prev.lastStartTs;
- if (ops === prev.ops && lastStartTs === prev.lastStartTs) return prev;
- return { ...prev, ops, lastStartTs };
- });
- // Decide re-arm from the ref (kept in sync with state every render), NOT from a flag
- // set inside the updater above — React doesn't guarantee that updater ran by now, so
- // reading its result synchronously would be unreliable. The ref reflects pre-tick
- // state; if anything is still within its window we re-arm and the next tick prunes it.
- const { ops: liveOps, lastStartTs: liveStart } = aiActivityRef.current;
- const flarePending = liveStart > 0 && now - liveStart <= AI_CORE.flareMs;
- if (Object.keys(pruneAiOps(liveOps, now)).length > 0 || flarePending) scheduleAiPrune();
- }, AI_CORE.afterglowMs + 100);
- };
-
- const handleAiStatus = (event) => {
- setAiActivity(prev => ({
- ops: applyAiStatusEvent(prev.ops, event),
- lastStartTs: event?.phase === 'start' ? Date.now() : prev.lastStartTs,
- }));
- scheduleAiPrune();
- };
- socket.on('ai:status', handleAiStatus);
-
- // Subscribe but do NOT unsubscribe on cleanup. The cos:* and notifications:*
- // namespaces are shared (useNotifications in Layout, useAgentFeedbackToast).
- // Server uses a per-socket Set, so unsubscribing here would yank the
- // subscription out from under those always-mounted consumers. The socket
- // disconnect handler cleans up Set membership when the tab closes.
- return () => {
- socket.off('connect', subscribe);
- socket.off('apps:changed', handleAppsChanged);
- socket.off('cos:agent:spawned', handleAgentSpawned);
- socket.off('cos:agent:updated', handleAgentUpdated);
- socket.off('cos:agent:completed', handleAgentCompleted);
- socket.off('cos:log', handleCosLog);
- socket.off('cos:status', handleCosStatus);
- socket.off('notifications:count', handleNotifCount);
- socket.off('notifications:cleared', handleNotifCleared);
- socket.off('backup:started', handleBackupStarted);
- socket.off('backup:completed', handleBackupCompleted);
- socket.off('cos:tasks:cos:changed', handleCosTasksChanged);
- socket.off('voice:dictation', handleVoiceDictation);
- socket.off('voice:error', handleVoiceError);
- socket.off('voice:idle', handleVoiceIdle);
- socket.off('ai:status', handleAiStatus);
- if (aiPruneTimerRef.current) clearTimeout(aiPruneTimerRef.current);
- if (eventLogFlushTimerRef.current != null) clearTimeout(eventLogFlushTimerRef.current);
- eventLogFlushTimerRef.current = null;
- pendingEventLogsRef.current = [];
- coalescedFetchAll.cancel(); // drop any pending trailing refetch on unmount
- };
- }, [fetchAll, fetchApps, fetchBackup, coalescedFetchAll]);
-
- return {
- apps,
- cosAgents,
- cosStatus,
- runningAgents,
- eventLogs,
- agentMap,
- reviewCounts,
- instances,
- systemHealth,
- notificationCounts,
- backupStatus,
- cosTasks,
- healthMetrics,
- voiceState,
- character,
- aiActivity,
- loading,
- connected: socket.connected,
- };
-};
diff --git a/client/src/hooks/useOpenWorldData.test.jsx b/client/src/hooks/useOpenWorldData.test.jsx
deleted file mode 100644
index 401bfa56e3..0000000000
--- a/client/src/hooks/useOpenWorldData.test.jsx
+++ /dev/null
@@ -1,90 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { act, renderHook } from '@testing-library/react';
-
-const { socketHandlers, socket } = vi.hoisted(() => {
- const handlers = new Map();
- return {
- socketHandlers: handlers,
- socket: {
- connected: true,
- emit: vi.fn(),
- on: vi.fn((event, handler) => handlers.set(event, handler)),
- off: vi.fn((event, handler) => {
- if (handlers.get(event) === handler) handlers.delete(event);
- }),
- },
- };
-});
-
-vi.mock('../services/socket', () => ({ default: socket }));
-vi.mock('../services/api', () => ({
- getApps: vi.fn(async () => []),
- getRunningAgents: vi.fn(async () => []),
- getCosAgents: vi.fn(async () => []),
- getCosStatus: vi.fn(async () => ({ running: false })),
- getReviewCounts: vi.fn(async () => ({ total: 0, alert: 0, todo: 0, briefing: 0, cos: 0 })),
- getInstances: vi.fn(async () => ({ self: null, peers: [], syncStatus: null })),
- getSystemHealth: vi.fn(async () => null),
- getNotificationCount: vi.fn(async () => ({ count: 0 })),
- getBackupStatus: vi.fn(async () => null),
- getCosTasks: vi.fn(async () => ({ tasks: [] })),
- getLatestHealthMetrics: vi.fn(async () => null),
- getVoiceStatus: vi.fn(async () => null),
- getCharacter: vi.fn(async () => null),
-}));
-vi.mock('./useAutoRefetch', () => ({ useAutoRefetch: () => ({ data: null }) }));
-
-import { useOpenWorldData } from './useOpenWorldData';
-
-const settleInitialFetch = async () => {
- await act(async () => {
- await Promise.resolve();
- await Promise.resolve();
- });
-};
-
-beforeEach(() => {
- vi.useFakeTimers();
- socketHandlers.clear();
- socket.emit.mockClear();
- socket.on.mockClear();
- socket.off.mockClear();
-});
-
-afterEach(() => vi.useRealTimers());
-
-describe('useOpenWorldData activity log batching', () => {
- it('applies a socket burst in one render without dropping entries', async () => {
- let renders = 0;
- const { result } = renderHook(() => {
- renders += 1;
- return useOpenWorldData();
- });
- await settleInitialFetch();
- const rendersAfterMount = renders;
-
- act(() => {
- for (let index = 0; index < 50; index += 1) {
- socketHandlers.get('cos:log')?.({ message: `event-${index}`, timestamp: index + 1 });
- }
- });
- expect(result.current.eventLogs).toEqual([]);
- expect(renders).toBe(rendersAfterMount);
-
- act(() => vi.advanceTimersByTime(100));
-
- expect(result.current.eventLogs).toHaveLength(50);
- expect(result.current.eventLogs.at(-1).message).toBe('event-49');
- expect(renders - rendersAfterMount).toBe(1);
- });
-
- it('drops a pending batch when the page unmounts', async () => {
- const { unmount } = renderHook(() => useOpenWorldData());
- await settleInitialFetch();
- act(() => socketHandlers.get('cos:log')?.({ message: 'pending' }));
-
- unmount();
- expect(() => vi.advanceTimersByTime(200)).not.toThrow();
- expect(socketHandlers.has('cos:log')).toBe(false);
- });
-});
diff --git a/client/src/hooks/useOpenWorldPlayback.js b/client/src/hooks/useOpenWorldPlayback.js
deleted file mode 100644
index 7bb639072b..0000000000
--- a/client/src/hooks/useOpenWorldPlayback.js
+++ /dev/null
@@ -1,116 +0,0 @@
-import { useState, useCallback, useEffect, useMemo } from 'react';
-import useMounted from './useMounted';
-import { getOpenWorldSnapshots } from '../services/apiOpenWorld.js';
-import { isPlayableFrame, buildPlaybackStats } from '../lib/openWorldPlaybackFrame.js';
-
-// Transport state for the OpenWorld timeline scrubber (issue #967). Owns the
-// snapshot series, the current frame index, and play/pause/speed so OpenWorld.jsx
-// stays lean. Pure-UI: it reads the snapshot API and steps an index; the page
-// turns the current frame into scene props via lib/openWorldPlaybackFrame.js.
-
-export const PLAYBACK_SPEEDS = [1, 2, 4]; // × frames/sec
-const BASE_INTERVAL_MS = 1000; // 1×: advance one frame per second
-
-export function useOpenWorldPlayback() {
- const [active, setActive] = useState(false);
- const [snapshots, setSnapshots] = useState([]);
- const [frameIndex, setFrameIndex] = useState(0);
- const [playing, setPlaying] = useState(false);
- const [speed, setSpeed] = useState(PLAYBACK_SPEEDS[0]);
- const [loading, setLoading] = useState(false);
- // null = no error; true = the series fetch failed. Distinct from an empty
- // series (a real, fetched-empty history) so the overlay can say "couldn't
- // load" vs "nothing recorded yet" — the absent-vs-empty rule.
- const [error, setError] = useState(false);
-
- // Guards a deferred/interval callback against firing after unmount (AGENTS.md
- // deferred-work rule).
- const mountedRef = useMounted();
-
- const enter = useCallback(async () => {
- setActive(true);
- setLoading(true);
- setPlaying(false);
- setError(false);
- // Sentinel: catch → null marks a failed fetch, distinct from a fetched-empty
- // history. Validate the payload is actually an array before trusting it.
- const res = await getOpenWorldSnapshots({ silent: true }).catch(() => null);
- if (!mountedRef.current) return;
- if (!res || !Array.isArray(res.snapshots)) {
- setError(true);
- setSnapshots([]);
- setLoading(false);
- return;
- }
- // Only keep frames this scrubber can render (schemaVersion gate); a future
- // bump leaves older/newer frames out rather than mis-rendering them.
- const frames = res.snapshots.filter(isPlayableFrame);
- setSnapshots(frames);
- setFrameIndex(frames.length > 0 ? frames.length - 1 : 0); // start at "now"
- setLoading(false);
- }, []);
-
- const exit = useCallback(() => {
- setActive(false);
- setPlaying(false);
- }, []);
-
- const togglePlay = useCallback(() => {
- // At the last frame, play restarts from the beginning.
- setPlaying((p) => {
- if (!p) setFrameIndex((i) => (i >= snapshots.length - 1 ? 0 : i));
- return !p;
- });
- }, [snapshots.length]);
-
- const cycleSpeed = useCallback(() => {
- setSpeed((s) => {
- const idx = PLAYBACK_SPEEDS.indexOf(s);
- return PLAYBACK_SPEEDS[(idx + 1) % PLAYBACK_SPEEDS.length];
- });
- }, []);
-
- // Clamped step; pauses if a manual step is taken while playing.
- const step = useCallback((delta) => {
- setPlaying(false);
- setFrameIndex((i) => Math.max(0, Math.min(snapshots.length - 1, i + delta)));
- }, [snapshots.length]);
-
- const seek = useCallback((index) => {
- setFrameIndex(() => Math.max(0, Math.min(snapshots.length - 1, index)));
- }, [snapshots.length]);
-
- // Auto-advance timer. Guarded by mountedRef and torn down on
- // pause/exit/speed-change/unmount so it never fires into the void. The updater
- // stays PURE — it only clamps the index forward; the "stop at the end" pause
- // is a separate effect below (calling a setter inside a state updater would
- // double-fire under StrictMode).
- useEffect(() => {
- if (!active || !playing || snapshots.length === 0) return undefined;
- const id = setInterval(() => {
- if (!mountedRef.current) return;
- setFrameIndex((i) => Math.min(i + 1, snapshots.length - 1));
- }, BASE_INTERVAL_MS / speed);
- return () => clearInterval(id);
- }, [active, playing, speed, snapshots.length]);
-
- // Pause when playback reaches the last frame (kept out of the interval's
- // updater so that updater stays a pure function of the previous index).
- useEffect(() => {
- if (playing && snapshots.length > 0 && frameIndex >= snapshots.length - 1) {
- setPlaying(false);
- }
- }, [playing, frameIndex, snapshots.length]);
-
- const currentFrame = snapshots[frameIndex] || null;
- const stats = useMemo(() => buildPlaybackStats(currentFrame), [currentFrame]);
-
- return {
- active, enter, exit,
- snapshots, frameIndex, currentFrame, stats, seek, step,
- playing, togglePlay,
- speed, cycleSpeed,
- loading, error,
- frameCount: snapshots.length,
- };
-}
diff --git a/client/src/hooks/useOpenWorldPlayback.test.jsx b/client/src/hooks/useOpenWorldPlayback.test.jsx
deleted file mode 100644
index bfac10746a..0000000000
--- a/client/src/hooks/useOpenWorldPlayback.test.jsx
+++ /dev/null
@@ -1,116 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { renderHook, act } from '@testing-library/react';
-
-const getOpenWorldSnapshots = vi.fn();
-vi.mock('../services/apiOpenWorld.js', () => ({
- getOpenWorldSnapshots: (...a) => getOpenWorldSnapshots(...a),
-}));
-
-import { useOpenWorldPlayback, PLAYBACK_SPEEDS } from './useOpenWorldPlayback.js';
-
-const mkFrames = (n) => Array.from({ length: n }, (_, i) => ({
- ts: `2026-06-05T0${i}:00:00.000Z`,
- schemaVersion: 1,
- apps: [],
- counts: {},
-}));
-
-describe('useOpenWorldPlayback', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- getOpenWorldSnapshots.mockResolvedValue({ total: 3, snapshots: mkFrames(3) });
- });
-
- it('loads the series on enter and starts at the most recent frame', async () => {
- const { result } = renderHook(() => useOpenWorldPlayback());
- await act(async () => { await result.current.enter(); });
- expect(result.current.active).toBe(true);
- expect(result.current.frameCount).toBe(3);
- expect(result.current.frameIndex).toBe(2); // newest
- expect(result.current.currentFrame.ts).toBe('2026-06-05T02:00:00.000Z');
- });
-
- it('flags an error (distinct from empty) when the fetch fails', async () => {
- getOpenWorldSnapshots.mockRejectedValue(new Error('network down'));
- const { result } = renderHook(() => useOpenWorldPlayback());
- await act(async () => { await result.current.enter(); });
- expect(result.current.error).toBe(true);
- expect(result.current.frameCount).toBe(0);
- });
-
- it('a real empty history is not an error', async () => {
- getOpenWorldSnapshots.mockResolvedValue({ total: 0, snapshots: [] });
- const { result } = renderHook(() => useOpenWorldPlayback());
- await act(async () => { await result.current.enter(); });
- expect(result.current.error).toBe(false);
- expect(result.current.frameCount).toBe(0);
- });
-
- it('filters out frames with an unsupported schemaVersion', async () => {
- getOpenWorldSnapshots.mockResolvedValue({
- snapshots: [...mkFrames(2), { ts: 'x', schemaVersion: 99, apps: [] }],
- });
- const { result } = renderHook(() => useOpenWorldPlayback());
- await act(async () => { await result.current.enter(); });
- expect(result.current.frameCount).toBe(2);
- });
-
- it('step clamps at both ends and pauses', async () => {
- const { result } = renderHook(() => useOpenWorldPlayback());
- await act(async () => { await result.current.enter(); });
- act(() => result.current.step(1)); // already at last → clamps
- expect(result.current.frameIndex).toBe(2);
- act(() => result.current.seek(0));
- act(() => result.current.step(-1)); // at first → clamps
- expect(result.current.frameIndex).toBe(0);
- });
-
- it('cycleSpeed walks the speed presets', async () => {
- const { result } = renderHook(() => useOpenWorldPlayback());
- await act(async () => { await result.current.enter(); });
- expect(result.current.speed).toBe(PLAYBACK_SPEEDS[0]);
- act(() => result.current.cycleSpeed());
- expect(result.current.speed).toBe(PLAYBACK_SPEEDS[1]);
- });
-
- it('exit clears active + playing', async () => {
- const { result } = renderHook(() => useOpenWorldPlayback());
- await act(async () => { await result.current.enter(); });
- act(() => result.current.exit());
- expect(result.current.active).toBe(false);
- expect(result.current.playing).toBe(false);
- });
-
- describe('autoplay timer', () => {
- beforeEach(() => vi.useFakeTimers());
- afterEach(() => vi.useRealTimers());
-
- it('advances frames while playing and stops at the end', async () => {
- const { result } = renderHook(() => useOpenWorldPlayback());
- await act(async () => { await result.current.enter(); });
- // seek to start, then play
- act(() => result.current.seek(0));
- act(() => result.current.togglePlay());
- expect(result.current.playing).toBe(true);
-
- act(() => vi.advanceTimersByTime(1000)); // 1× → +1 frame
- expect(result.current.frameIndex).toBe(1);
- act(() => vi.advanceTimersByTime(1000));
- expect(result.current.frameIndex).toBe(2);
- // at last frame → auto-pauses, no further advance
- act(() => vi.advanceTimersByTime(2000));
- expect(result.current.frameIndex).toBe(2);
- expect(result.current.playing).toBe(false);
- });
-
- it('does not advance after exit (timer torn down)', async () => {
- const { result } = renderHook(() => useOpenWorldPlayback());
- await act(async () => { await result.current.enter(); });
- act(() => result.current.seek(0));
- act(() => result.current.togglePlay());
- act(() => result.current.exit());
- act(() => vi.advanceTimersByTime(5000));
- expect(result.current.frameIndex).toBe(0);
- });
- });
-});
diff --git a/client/src/hooks/useOpenWorldSettings.js b/client/src/hooks/useOpenWorldSettings.js
deleted file mode 100644
index 925fdeea53..0000000000
--- a/client/src/hooks/useOpenWorldSettings.js
+++ /dev/null
@@ -1,93 +0,0 @@
-import { useEffect, useState, useCallback } from 'react';
-import { safeReadStorage, safeWriteStorage, safeRemoveStorage } from '../lib/safeStorage.js';
-
-// Exported so useTheme can reset the city's time-of-day override without
-// re-declaring these magic strings (a typo there would silently break the reset).
-export const STORAGE_KEY = 'portos-city-settings';
-export const TIME_OF_DAY_AUTO_EVENT = 'portos-city-timeofday-auto';
-
-const DEFAULT_SETTINGS = {
- musicEnabled: false,
- musicVolume: 0.3,
- sfxEnabled: true,
- sfxVolume: 0.5,
- // Manual soundscape override (issue #3395). `null` is the explicit "auto" sentinel: the music's
- // mood follows live system state. A mood name from SOUNDSCAPE_MOODS pins it instead.
- soundscapeOverride: null,
- timeOfDay: 'auto', // 'auto' follows the active theme's day/night mode; 'day'/'night' force it
- // Art direction: 'vibes' is the low-poly bright open world (default); 'cyber' restores
- // the original neon-night OpenWorld look. Existing installs have no stored value and so
- // land on the new default — deliberate, this IS the world's new look — and the picker in
- // the Visual tab switches back with no migration.
- worldStyle: 'vibes',
- // OpenWorld opens as a game, not an orbital dashboard. Users can still press Tab (or the
- // HUD control) to pull back to the planning view, while V / settings can switch to first person.
- explorationMode: true,
- cameraView: 'third', // the rover is the default actor; first person remains an explicit option
-};
-
-// Old releases persisted renderer controls alongside player choices. They are intentionally
-// ignored on read so a saved payload cannot resurrect removed settings in the live state.
-const LEGACY_RENDER_KEYS = new Set([
- 'qualityMode',
- 'qualityPreset',
- 'reflectionsEnabled',
- 'particleDensity',
- 'scanlineOverlay',
- 'ambientBrightness',
- 'neonBrightness',
- 'dpr',
-]);
-
-const loadSettings = () => {
- const saved = safeReadStorage(STORAGE_KEY);
- if (!saved) return DEFAULT_SETTINGS;
- let parsed;
- try {
- parsed = JSON.parse(saved);
- } catch {
- return DEFAULT_SETTINGS; // Corrupt stored JSON — fall back to defaults.
- }
- if (!parsed || typeof parsed !== 'object') return DEFAULT_SETTINGS;
- const persistedChoices = Object.fromEntries(
- Object.entries(parsed).filter(([key]) => !LEGACY_RENDER_KEYS.has(key)),
- );
- return { ...DEFAULT_SETTINGS, ...persistedChoices };
-};
-
-export default function useOpenWorldSettings() {
- const [settings, setSettings] = useState(loadSettings);
- // Monotonic counter bumped on every reset. The runtime render budget (Auto mode) lives
- // outside `settings`, so RESET DEFAULTS must still re-arm it even though renderer tiers
- // are no longer persisted — consumers watch this token to reset the budget too.
- const [resetNonce, setResetNonce] = useState(0);
-
- useEffect(() => {
- const handleTimeOfDayAuto = () => {
- setSettings(prev => {
- if (prev.timeOfDay === 'auto') return prev;
- const next = { ...prev, timeOfDay: 'auto' };
- safeWriteStorage(STORAGE_KEY, JSON.stringify(next));
- return next;
- });
- };
- window.addEventListener(TIME_OF_DAY_AUTO_EVENT, handleTimeOfDayAuto);
- return () => window.removeEventListener(TIME_OF_DAY_AUTO_EVENT, handleTimeOfDayAuto);
- }, []);
-
- const updateSetting = useCallback((key, value) => {
- setSettings(prev => {
- const next = { ...prev, [key]: value };
- safeWriteStorage(STORAGE_KEY, JSON.stringify(next));
- return next;
- });
- }, []);
-
- const resetSettings = useCallback(() => {
- safeRemoveStorage(STORAGE_KEY);
- setSettings(DEFAULT_SETTINGS);
- setResetNonce(n => n + 1);
- }, []);
-
- return [settings, updateSetting, resetSettings, resetNonce];
-}
diff --git a/client/src/hooks/useOpenWorldSettings.test.jsx b/client/src/hooks/useOpenWorldSettings.test.jsx
deleted file mode 100644
index 00b683ada0..0000000000
--- a/client/src/hooks/useOpenWorldSettings.test.jsx
+++ /dev/null
@@ -1,117 +0,0 @@
-import { describe, it, expect, afterEach, vi } from 'vitest';
-import { renderHook, act } from '@testing-library/react';
-import useOpenWorldSettings, { TIME_OF_DAY_AUTO_EVENT } from './useOpenWorldSettings.js';
-
-const STORAGE_KEY = 'portos-city-settings';
-
-afterEach(() => {
- vi.restoreAllMocks();
- window.localStorage.clear();
-});
-
-describe('useOpenWorldSettings localStorage resilience', () => {
- it('initializes to defaults when reads throw (blocked storage)', () => {
- vi.spyOn(window.localStorage, 'getItem').mockImplementation(() => {
- throw new DOMException('The operation is insecure.', 'SecurityError');
- });
-
- let result;
- expect(() => {
- ({ result } = renderHook(() => useOpenWorldSettings()));
- }).not.toThrow();
-
- const [settings] = result.current;
- expect(settings.timeOfDay).toBe('auto');
- expect(settings.worldStyle).toBe('vibes');
- });
-
- it('initializes to defaults when stored JSON is corrupt', () => {
- window.localStorage.setItem(STORAGE_KEY, '{ not valid json');
- const { result } = renderHook(() => useOpenWorldSettings());
- const [settings] = result.current;
- expect(settings.worldStyle).toBe('vibes');
- });
-
- it('keeps in-memory setting updates working when writes throw', () => {
- vi.spyOn(window.localStorage, 'setItem').mockImplementation(() => {
- throw new DOMException('QuotaExceededError', 'QuotaExceededError');
- });
-
- const { result } = renderHook(() => useOpenWorldSettings());
-
- expect(() => {
- act(() => {
- const [, updateSetting] = result.current;
- updateSetting('timeOfDay', 'night');
- });
- }).not.toThrow();
-
- const [settings] = result.current;
- expect(settings.timeOfDay).toBe('night');
- });
-
- it('defaults a fresh install to player-facing world settings', () => {
- const { result } = renderHook(() => useOpenWorldSettings());
- const [settings] = result.current;
- expect(settings.explorationMode).toBe(true);
- expect(settings.cameraView).toBe('third');
- expect(settings.worldStyle).toBe('vibes');
- expect(settings.qualityMode).toBeUndefined();
- expect(settings.qualityPreset).toBeUndefined();
- expect(settings.reflectionsEnabled).toBeUndefined();
- expect(settings.scanlineOverlay).toBeUndefined();
- });
-
- it('drops legacy renderer controls when loading an existing payload', () => {
- window.localStorage.setItem(STORAGE_KEY, JSON.stringify({
- worldStyle: 'cyber',
- qualityMode: 'manual',
- qualityPreset: 'ultra',
- reflectionsEnabled: true,
- scanlineOverlay: true,
- ambientBrightness: 2,
- neonBrightness: 2,
- particleDensity: 2,
- dpr: [1, 2],
- }));
- const { result } = renderHook(() => useOpenWorldSettings());
- const [settings] = result.current;
- expect(settings.worldStyle).toBe('cyber');
- for (const key of ['qualityMode', 'qualityPreset', 'reflectionsEnabled', 'scanlineOverlay', 'ambientBrightness', 'neonBrightness', 'particleDensity', 'dpr']) {
- expect(settings[key]).toBeUndefined();
- }
- });
-
- it('bumps resetNonce on reset so the runtime budget can re-arm', () => {
- const { result } = renderHook(() => useOpenWorldSettings());
- const before = result.current[3];
- act(() => {
- const resetSettings = result.current[2];
- resetSettings();
- });
- expect(result.current[3]).toBe(before + 1);
- const [settings] = result.current;
- expect(settings.explorationMode).toBe(true);
- expect(settings.cameraView).toBe('third');
- });
-
- it('handles the time-of-day-auto event without throwing when writes fail', () => {
- // This is the listener fired by useTheme.setTheme; with storage blocked its
- // write must not surface an unhandled error on the theme-switch path.
- window.localStorage.setItem(STORAGE_KEY, JSON.stringify({ timeOfDay: 'night' }));
- vi.spyOn(window.localStorage, 'setItem').mockImplementation(() => {
- throw new DOMException('QuotaExceededError', 'QuotaExceededError');
- });
-
- const { result } = renderHook(() => useOpenWorldSettings());
-
- expect(() => {
- act(() => {
- window.dispatchEvent(new Event(TIME_OF_DAY_AUTO_EVENT));
- });
- }).not.toThrow();
-
- const [settings] = result.current;
- expect(settings.timeOfDay).toBe('auto');
- });
-});
diff --git a/client/src/hooks/useOpenWorldViewport.js b/client/src/hooks/useOpenWorldViewport.js
deleted file mode 100644
index abeb369d2c..0000000000
--- a/client/src/hooks/useOpenWorldViewport.js
+++ /dev/null
@@ -1,49 +0,0 @@
-import { useEffect, useState } from 'react';
-
-// Coordinated responsive breakpoints for the OpenWorld HUD. The HUD is a fixed
-// overlay on top of a full-bleed 3D scene, so it can't rely on the page's normal
-// flow/scroll to reflow — it needs to KNOW the viewport bracket to swap between the
-// desktop cockpit and the compact/phone disclosure layout (rendering both trees at
-// once would double the always-live timers and stack the panels). We branch in JS
-// (not just CSS `lg:hidden`) so only one layout mounts and the branch is testable.
-//
-// Brackets mirror Tailwind's `sm` (640) and `lg` (1024), with a height floor
-// for the full cockpit. Its top-left vitals stack and bottom-left map/action rail
-// are intentionally independent on a spacious desktop; on a short viewport those
-// anchors would otherwise overlap. The compact HUD keeps the same tools reachable
-// as one-at-a-time disclosure panels instead.
-// phone : < 640 essential status + a single disclosure surface
-// compact : 640 – 1023, or < 900px h condensed rail + collapsed launchers
-// desktop : >= 1024 and >= 900px h the full multi-panel cockpit
-export const CITY_PHONE_MAX = 639;
-export const CITY_COMPACT_MAX = 1023;
-export const CITY_DESKTOP_MIN_HEIGHT = 900;
-
-export function classifyOpenWorldViewport(width, height = Infinity) {
- if (width <= CITY_PHONE_MAX) return 'phone';
- if (width <= CITY_COMPACT_MAX) return 'compact';
- if (height < CITY_DESKTOP_MIN_HEIGHT) return 'compact';
- return 'desktop';
-}
-
-export default function useOpenWorldViewport() {
- const [mode, setMode] = useState(() =>
- typeof window === 'undefined' ? 'desktop' : classifyOpenWorldViewport(window.innerWidth, window.innerHeight),
- );
-
- useEffect(() => {
- const onResize = () => setMode(classifyOpenWorldViewport(window.innerWidth, window.innerHeight));
- onResize(); // sync once in case width changed before the listener attached
- window.addEventListener('resize', onResize);
- return () => window.removeEventListener('resize', onResize);
- }, []);
-
- return {
- mode,
- isPhone: mode === 'phone',
- isCompact: mode === 'compact',
- isDesktop: mode === 'desktop',
- // convenience: everything that is NOT the desktop cockpit
- isCondensed: mode !== 'desktop',
- };
-}
diff --git a/client/src/hooks/useOpenWorldViewport.test.jsx b/client/src/hooks/useOpenWorldViewport.test.jsx
deleted file mode 100644
index 53cb2a963a..0000000000
--- a/client/src/hooks/useOpenWorldViewport.test.jsx
+++ /dev/null
@@ -1,54 +0,0 @@
-import { describe, it, expect, afterEach } from 'vitest';
-import { renderHook, act } from '@testing-library/react';
-import useOpenWorldViewport, { classifyOpenWorldViewport } from './useOpenWorldViewport.js';
-
-const setViewport = (width, height = 1080) => {
- window.innerWidth = width;
- window.innerHeight = height;
-};
-
-afterEach(() => setViewport(1024));
-
-describe('classifyOpenWorldViewport', () => {
- it('classifies phone / compact / desktop at the sm+lg breakpoints', () => {
- expect(classifyOpenWorldViewport(390)).toBe('phone');
- expect(classifyOpenWorldViewport(639)).toBe('phone');
- expect(classifyOpenWorldViewport(640)).toBe('compact');
- expect(classifyOpenWorldViewport(1023)).toBe('compact');
- expect(classifyOpenWorldViewport(1024)).toBe('desktop');
- expect(classifyOpenWorldViewport(1440)).toBe('desktop');
- });
-
- it('uses the compact HUD when a desktop-width viewport is too short for both HUD rails', () => {
- expect(classifyOpenWorldViewport(1440, 899)).toBe('compact');
- expect(classifyOpenWorldViewport(1440, 900)).toBe('desktop');
- });
-});
-
-describe('useOpenWorldViewport', () => {
- it('reports the initial bracket from the current width', () => {
- setViewport(390);
- const { result } = renderHook(() => useOpenWorldViewport());
- expect(result.current.mode).toBe('phone');
- expect(result.current.isPhone).toBe(true);
- expect(result.current.isCondensed).toBe(true);
- expect(result.current.isDesktop).toBe(false);
- });
-
- it('updates on resize across width and height brackets', () => {
- setViewport(1440);
- const { result } = renderHook(() => useOpenWorldViewport());
- expect(result.current.isDesktop).toBe(true);
-
- act(() => { setViewport(1440, 899); window.dispatchEvent(new Event('resize')); });
- expect(result.current.isCompact).toBe(true);
- expect(result.current.isCondensed).toBe(true);
-
- act(() => { setViewport(800); window.dispatchEvent(new Event('resize')); });
- expect(result.current.isCompact).toBe(true);
- expect(result.current.isCondensed).toBe(true);
-
- act(() => { setViewport(375); window.dispatchEvent(new Event('resize')); });
- expect(result.current.isPhone).toBe(true);
- });
-});
diff --git a/client/src/hooks/useTheme.js b/client/src/hooks/useTheme.js
index def5a62c8a..2750d6df24 100644
--- a/client/src/hooks/useTheme.js
+++ b/client/src/hooks/useTheme.js
@@ -6,10 +6,6 @@ import {
getPairedThemeId,
normalizeThemeId,
} from '../themes/portosThemes';
-import {
- STORAGE_KEY as OPEN_WORLD_SETTINGS_KEY,
- TIME_OF_DAY_AUTO_EVENT as OPEN_WORLD_TIME_OF_DAY_AUTO_EVENT,
-} from './useOpenWorldSettings';
import { safeReadStorage, safeWriteStorage } from '../lib/safeStorage.js';
import { getSettings, updateSettings } from '../services/apiSystem.js';
@@ -37,21 +33,6 @@ const loadTheme = () => {
return normalized;
};
-const resetOpenWorldTimeOfDayOverride = () => {
- const raw = safeReadStorage(OPEN_WORLD_SETTINGS_KEY);
- let openWorldSettings = {};
- if (raw) {
- try {
- const parsed = JSON.parse(raw);
- if (parsed && typeof parsed === 'object') openWorldSettings = parsed;
- } catch {
- // Corrupt OpenWorld settings — start from an empty object rather than bail.
- }
- }
- safeWriteStorage(OPEN_WORLD_SETTINGS_KEY, JSON.stringify({ ...openWorldSettings, timeOfDay: 'auto' }));
- window.dispatchEvent(new Event(OPEN_WORLD_TIME_OF_DAY_AUTO_EVENT));
-};
-
export default function useTheme() {
const [themeId, setThemeId] = useState(() => {
const id = loadTheme();
@@ -75,7 +56,6 @@ export default function useTheme() {
applyTheme(serverTheme);
setThemeId(serverTheme);
safeWriteStorage(STORAGE_KEY, serverTheme);
- resetOpenWorldTimeOfDayOverride();
}
})
.catch((err) => {
@@ -97,7 +77,6 @@ export default function useTheme() {
applyTheme(normalized);
setThemeId(normalized);
safeWriteStorage(STORAGE_KEY, normalized);
- resetOpenWorldTimeOfDayOverride();
// Silent — the theme is already applied locally; a failed sync only warrants
// a console warning, not a toast on every theme switch.
updateSettings({ theme: normalized }, { silent: true })
diff --git a/client/src/index.css b/client/src/index.css
index d565738c70..162af71e24 100644
--- a/client/src/index.css
+++ b/client/src/index.css
@@ -1308,10 +1308,7 @@ html[data-port-theme-mode="day"] .always-dark [class~="hover:text-slate-100"]:ho
- `.port-media-overlay*` — the default for new overlay chrome.
- `.always-dark` (above) — only when the surface underneath is genuinely
fixed-dark regardless of theme: video-player chrome, a terminal, a
- full-screen lightbox.
- - `.openworld-themed` (below) — a page-scoped `!important` remap of the
- OpenWorld HUD's fixed cyberpunk palette. Legacy shape, kept because that HUD is
- authored against a fixed palette on purpose; don't add a second one. */
+ full-screen lightbox. */
.port-media-overlay {
background-color: rgb(var(--port-card) / 0.9);
}
@@ -1367,676 +1364,6 @@ html[data-port-theme-mode="day"] .always-dark [class~="hover:text-slate-100"]:ho
background-color: rgb(var(--port-text) / 0.2);
}
-/* === OpenWorld HUD theming ===
- The page-scoped `.openworld-themed` root keeps this remap isolated from the
- rest of the application. The OpenWorld overlay (clock, vitals, intel pane, agent bar, mini-map, filter
- bar, settings panel, photo overlay, holographic panels) was authored in a fixed
- cyberpunk palette: near-black panels (`bg-black/85`), cyan accent text/borders
- (`text-cyan-400`, `border-cyan-500/40`), and many very-low-opacity tokens
- (`text-cyan-500/20`, `text-gray-600`, `border-cyan-500/15`). On a light theme
- like Phosphor Paper that reads as dim teal on near-black floating over a cream
- page — low contrast and off-theme. Rather than edit every component, we remap
- those exact utility tokens to the active theme's `--port-*` vars, scoped to the
- `.openworld-themed` page root so nothing else is affected. Status colors
- (red/amber/emerald/violet/...) are intentionally left to the global day-mode
- remap above so they keep their semantic meaning. The low-opacity variants are
- given a higher legibility floor than their original alpha.
- When adding a new HUD element, prefer these same tokens so it themes for free. */
-
-/* Panels — near-black backgrounds follow the theme card color (dark in night
- themes, paper in day themes). Kept fully opaque so the busy 3D scene behind
- them never bleeds through and hurts text legibility. A two-tier split keeps
- nested elements distinct: the main panels take the card color, inner fills
- (agent items, list rows) take the slightly-different page bg color. */
-html[data-port-theme] .openworld-themed [class~="bg-black/95"],
-html[data-port-theme] .openworld-themed [class~="bg-black/92"],
-html[data-port-theme] .openworld-themed [class~="bg-black/90"],
-html[data-port-theme] .openworld-themed [class~="bg-black/85"],
-html[data-port-theme] .openworld-themed [class~="bg-black/80"],
-html[data-port-theme] .openworld-themed [class~="bg-black/70"] { background-color: rgb(var(--port-card)) !important; }
-html[data-port-theme] .openworld-themed [class~="bg-black/60"],
-html[data-port-theme] .openworld-themed [class~="bg-black/50"],
-html[data-port-theme] .openworld-themed [class~="bg-black/40"] { background-color: rgb(var(--port-bg)) !important; }
-
-/* Accent text — cyan family → theme accent, tiered so emphasis survives. */
-html[data-port-theme] .openworld-themed [class~="text-cyan-400"],
-html[data-port-theme] .openworld-themed [class~="text-cyan-300"],
-html[data-port-theme] .openworld-themed [class~="text-cyan-500"] { color: rgb(var(--port-accent)) !important; }
-html[data-port-theme] .openworld-themed [class~="text-cyan-400/80"],
-html[data-port-theme] .openworld-themed [class~="text-cyan-400/70"],
-html[data-port-theme] .openworld-themed [class~="text-cyan-500/70"],
-html[data-port-theme] .openworld-themed [class~="text-cyan-500/60"] { color: rgb(var(--port-accent) / 0.82) !important; }
-html[data-port-theme] .openworld-themed [class~="text-cyan-400/60"],
-html[data-port-theme] .openworld-themed [class~="text-cyan-400/50"],
-html[data-port-theme] .openworld-themed [class~="text-cyan-500/50"],
-html[data-port-theme] .openworld-themed [class~="text-cyan-500/40"] { color: rgb(var(--port-accent) / 0.7) !important; }
-html[data-port-theme] .openworld-themed [class~="text-cyan-500/30"],
-html[data-port-theme] .openworld-themed [class~="text-cyan-500/25"],
-html[data-port-theme] .openworld-themed [class~="text-cyan-500/20"],
-html[data-port-theme] .openworld-themed [class~="text-cyan-400/20"] { color: rgb(var(--port-accent) / 0.55) !important; }
-html[data-port-theme] .openworld-themed [class~="hover:text-cyan-400"]:hover,
-html[data-port-theme] .openworld-themed [class~="hover:text-cyan-300"]:hover { color: rgb(var(--port-accent)) !important; }
-
-/* Neutral / muted text — gray tokens follow the theme text colors so faint
- labels stay legible on both dark and paper panels (gray-600 on near-black was
- the worst offender). */
-html[data-port-theme] .openworld-themed [class~="text-gray-300"] { color: rgb(var(--port-text) / 0.92) !important; }
-html[data-port-theme] .openworld-themed [class~="text-gray-400"],
-html[data-port-theme] .openworld-themed [class~="text-gray-500"],
-html[data-port-theme] .openworld-themed [class~="text-gray-600"] { color: rgb(var(--port-text-muted)) !important; }
-
-/* Borders — cyan accent borders → theme accent, with a visibility floor so the
- hairline panel frames don't vanish on a light background. */
-html[data-port-theme] .openworld-themed [class~="border-cyan-500/60"],
-html[data-port-theme] .openworld-themed [class~="border-cyan-500/50"],
-html[data-port-theme] .openworld-themed [class~="border-cyan-500/40"],
-html[data-port-theme] .openworld-themed [class~="border-cyan-400/70"],
-html[data-port-theme] .openworld-themed [class~="border-cyan-400/60"] { border-color: rgb(var(--port-accent) / 0.55) !important; }
-html[data-port-theme] .openworld-themed [class~="border-cyan-500/35"],
-html[data-port-theme] .openworld-themed [class~="border-cyan-500/30"],
-html[data-port-theme] .openworld-themed [class~="border-cyan-500/25"],
-html[data-port-theme] .openworld-themed [class~="border-cyan-400/50"] { border-color: rgb(var(--port-accent) / 0.42) !important; }
-html[data-port-theme] .openworld-themed [class~="border-cyan-500/20"],
-html[data-port-theme] .openworld-themed [class~="border-cyan-500/15"],
-html[data-port-theme] .openworld-themed [class~="border-cyan-500/10"] { border-color: rgb(var(--port-accent) / 0.3) !important; }
-
-/* Accent fills — solid swatches (status dots, knobs, capture button) take the
- full accent; the alpha variants (dividers, active chips, mini-map grid, hover
- washes) scale down to match their original weight. */
-html[data-port-theme] .openworld-themed [class~="bg-cyan-400"],
-html[data-port-theme] .openworld-themed [class~="bg-cyan-500"] { background-color: rgb(var(--port-accent)) !important; }
-html[data-port-theme] .openworld-themed [class~="bg-cyan-400/60"] { background-color: rgb(var(--port-accent) / 0.6) !important; }
-html[data-port-theme] .openworld-themed [class~="bg-cyan-400/40"],
-html[data-port-theme] .openworld-themed [class~="bg-cyan-500/40"] { background-color: rgb(var(--port-accent) / 0.4) !important; }
-html[data-port-theme] .openworld-themed [class~="bg-cyan-500/25"],
-html[data-port-theme] .openworld-themed [class~="bg-cyan-500/20"] { background-color: rgb(var(--port-accent) / 0.2) !important; }
-html[data-port-theme] .openworld-themed [class~="bg-cyan-500/15"],
-html[data-port-theme] .openworld-themed [class~="bg-cyan-400/15"] { background-color: rgb(var(--port-accent) / 0.16) !important; }
-html[data-port-theme] .openworld-themed [class~="bg-cyan-500/10"] { background-color: rgb(var(--port-accent) / 0.12) !important; }
-html[data-port-theme] .openworld-themed [class~="bg-cyan-500/[0.03]"] { background-color: rgb(var(--port-accent) / 0.05) !important; }
-html[data-port-theme] .openworld-themed [class~="hover:bg-cyan-300"]:hover { background-color: rgb(var(--port-accent) / 0.9) !important; }
-html[data-port-theme] .openworld-themed [class~="hover:bg-cyan-500/10"]:hover { background-color: rgb(var(--port-accent) / 0.12) !important; }
-html[data-port-theme] .openworld-themed [class~="hover:bg-cyan-500/5"]:hover { background-color: rgb(var(--port-accent) / 0.08) !important; }
-
-/* === OpenWorld HUD refresh ===
- OpenWorld is a playable map, so its controls should feel like a light cockpit
- around the world instead of a stack of debug panels. These primitives keep the
- HUD quiet, theme-aware, and consistent across the desktop and compact layouts.
- The older utility remap above remains for legacy scene labels and settings. */
-.openworld-themed {
- --ow-panel: rgb(var(--port-card) / 0.92);
- --ow-panel-soft: rgb(var(--port-card) / 0.76);
- --ow-ink: rgb(var(--port-text));
- --ow-muted: rgb(var(--port-text-muted));
- --ow-accent: rgb(var(--port-accent));
- --ow-line: rgb(var(--port-accent) / 0.28);
- --ow-soft: rgb(var(--port-accent) / 0.1);
- --ow-ui-font: var(--port-font-ui);
- --ow-micro-font: var(--port-font-mono);
- font-family: var(--ow-ui-font);
-}
-
-/* The pixel face is useful for a title or a deliberately diegetic sign, but it made
- OpenWorld's live controls and status copy hard to scan. Keep the game UI in the same
- readable face as the reference's control panel; reserve the mono face for small labels. */
-.openworld-themed .font-pixel,
-.openworld-themed .font-pixel-grid {
- font-family: var(--ow-ui-font);
- letter-spacing: 0.01em;
-}
-
-.openworld-themed .openworld-hud-eyebrow,
-.openworld-themed .openworld-hud-action-hint,
-.openworld-themed .openworld-mobile-look-hint {
- font-family: var(--ow-micro-font);
-}
-
-/* Existing HUD components use compact utility sizes. Nudge only the smallest game-facing
- copy upward so it remains legible without changing the global typography scale. */
-.openworld-hud-shell [class~="text-[8px]"],
-.openworld-settings-portal [class~="text-[8px]"] {
- font-size: 0.68rem;
- line-height: 1.35;
-}
-
-.openworld-settings-portal [class~="text-[9px]"] {
- font-size: 0.72rem;
- line-height: 1.4;
-}
-
-.openworld-settings-portal .font-mono {
- letter-spacing: 0.08em;
-}
-
-.openworld-hud-shell {
- color: var(--ow-ink);
- font-variant-numeric: tabular-nums;
-}
-
-.openworld-hud-panel {
- background: linear-gradient(145deg, var(--ow-panel), rgb(var(--port-bg) / 0.88));
- border: 1px solid var(--ow-line);
- border-radius: 18px;
- box-shadow: 0 16px 42px rgb(0 0 0 / 0.16), inset 0 1px 0 rgb(255 255 255 / 0.08);
- backdrop-filter: blur(18px) saturate(1.08);
-}
-
-.openworld-hud-panel--quiet {
- background: var(--ow-panel-soft);
- box-shadow: 0 12px 32px rgb(0 0 0 / 0.12), inset 0 1px 0 rgb(255 255 255 / 0.06);
-}
-
-.openworld-hud-eyebrow {
- color: var(--ow-muted);
- font-family: var(--font-pixel, monospace);
- font-size: 0.58rem;
- font-weight: 700;
- letter-spacing: 0.16em;
- line-height: 1;
- text-transform: uppercase;
-}
-
-.openworld-hud-action-rail {
- display: flex;
- align-items: center;
- gap: 0.35rem;
- padding: 0.35rem;
- border: 1px solid var(--ow-line);
- border-radius: 18px;
- background: var(--ow-panel-soft);
- box-shadow: 0 16px 40px rgb(0 0 0 / 0.15), inset 0 1px 0 rgb(255 255 255 / 0.06);
- backdrop-filter: blur(18px) saturate(1.08);
-}
-
-.openworld-hud-action {
- position: relative;
- display: inline-flex;
- min-height: 2.65rem;
- min-width: 2.65rem;
- align-items: center;
- justify-content: center;
- gap: 0.45rem;
- border: 1px solid transparent;
- border-radius: 13px;
- color: var(--ow-muted);
- font-family: var(--font-pixel, monospace);
- font-size: 0.6rem;
- letter-spacing: 0.08em;
- line-height: 1.1;
- padding: 0.42rem 0.55rem;
- text-transform: uppercase;
- transition: background-color 160ms ease, border-color 160ms ease, color 160ms ease, transform 160ms ease;
-}
-
-.openworld-hud-action:hover,
-.openworld-hud-action:focus-visible {
- border-color: rgb(var(--port-accent) / 0.38);
- background: rgb(var(--port-accent) / 0.1);
- color: var(--ow-ink);
- outline: none;
- transform: translateY(-1px);
-}
-
-.openworld-hud-action[aria-pressed="true"] {
- border-color: rgb(var(--port-accent) / 0.5);
- background: rgb(var(--port-accent) / 0.16);
- color: var(--ow-accent);
-}
-
-.openworld-hud-action--primary {
- border-color: rgb(var(--port-accent) / 0.36);
- background: linear-gradient(135deg, rgb(var(--port-accent) / 0.2), rgb(var(--port-accent) / 0.06));
- color: var(--ow-accent);
- padding-inline: 0.75rem;
-}
-
-.openworld-hud-action-copy {
- display: none;
- white-space: nowrap;
-}
-
-.openworld-hud-action-hint {
- color: var(--ow-muted);
- font-size: 0.5rem;
- letter-spacing: 0.12em;
- opacity: 0.72;
-}
-
-.openworld-hud-map {
- border-radius: 16px;
- overflow: hidden;
-}
-
-.openworld-hud-dock {
- display: flex;
- align-items: center;
- gap: 0.32rem;
- padding: 0.32rem;
- border: 1px solid var(--ow-line);
- border-radius: 17px;
- background: var(--ow-panel-soft);
- box-shadow: 0 10px 28px rgb(0 0 0 / 0.14), inset 0 1px 0 rgb(255 255 255 / 0.06);
- backdrop-filter: blur(18px) saturate(1.08);
-}
-
-.openworld-hud-chip {
- border-radius: 12px;
- background: var(--ow-panel-soft);
- border: 1px solid var(--ow-line);
- box-shadow: 0 10px 28px rgb(0 0 0 / 0.12), inset 0 1px 0 rgb(255 255 255 / 0.06);
- backdrop-filter: blur(16px) saturate(1.05);
-}
-
-.openworld-hud-chip[aria-pressed="true"] {
- border-color: rgb(var(--port-accent) / 0.5);
- background: rgb(var(--port-accent) / 0.14);
-}
-
-/* Street-level OpenWorld uses one quiet, toy-like interface shared by desktop and
- touch. Operational dashboards stay in orbital mode; the village only names the
- current place, the errand progress, and four reversible exits/tools. */
-.openworld-village-status {
- position: absolute;
- top: 1rem;
- left: 1rem;
- display: flex;
- min-height: 3.2rem;
- max-width: min(23rem, calc(100vw - 15rem));
- align-items: center;
- gap: 0.7rem;
- padding: 0.55rem 0.75rem;
- border: 1px solid rgb(var(--port-accent) / 0.26);
- border-radius: 1.05rem;
- background: linear-gradient(145deg, rgb(var(--port-card) / 0.82), rgb(var(--port-bg) / 0.64));
- box-shadow: 0 12px 34px rgb(0 0 0 / 0.14), inset 0 1px 0 rgb(255 255 255 / 0.12);
- backdrop-filter: blur(14px) saturate(1.08);
-}
-
-.openworld-village-status__dot {
- width: 0.58rem;
- height: 0.58rem;
- flex: 0 0 auto;
- border-radius: 50%;
- box-shadow: 0 0 10px currentColor;
-}
-
-.openworld-village-status small,
-.openworld-village-status strong {
- display: block;
- overflow: hidden;
- max-width: 10rem;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.openworld-village-status small {
- margin-bottom: 0.12rem;
- color: var(--ow-muted);
- font-family: var(--ow-micro-font);
- font-size: 0.5rem;
- font-weight: 700;
- letter-spacing: 0.15em;
-}
-
-.openworld-village-status strong {
- color: var(--ow-ink);
- font-size: 0.86rem;
- font-weight: 720;
- letter-spacing: 0.015em;
-}
-
-.openworld-village-status__echo {
- position: relative;
- min-width: 4.6rem;
- margin-left: auto;
- overflow: hidden;
- padding: 0.34rem 0.45rem;
- border-radius: 0.65rem;
- background: rgb(var(--port-accent) / 0.08);
- color: var(--ow-accent);
- font-family: var(--ow-micro-font);
- font-size: 0.62rem;
- font-weight: 700;
- letter-spacing: 0.06em;
- text-align: center;
-}
-
-.openworld-village-status__echo i {
- position: absolute;
- inset: auto auto 0 0;
- height: 2px;
- border-radius: 999px;
- background: var(--ow-accent);
- transition: width 240ms ease;
-}
-
-.openworld-village-actions {
- position: absolute;
- top: 1rem;
- right: 1rem;
- display: flex;
- gap: 0.28rem;
- padding: 0.28rem;
- border: 1px solid rgb(var(--port-accent) / 0.22);
- border-radius: 1rem;
- background: rgb(var(--port-card) / 0.72);
- box-shadow: 0 12px 32px rgb(0 0 0 / 0.13), inset 0 1px 0 rgb(255 255 255 / 0.1);
- backdrop-filter: blur(14px) saturate(1.08);
-}
-
-.openworld-village-speed {
- position: absolute;
- bottom: 1rem;
- left: 1rem;
- display: flex;
- align-items: baseline;
- gap: 0.28rem;
- color: rgb(255 255 255 / 0.88);
- font-variant-numeric: tabular-nums;
- text-shadow: 0 2px 12px rgb(0 0 0 / 0.55);
-}
-
-.openworld-village-speed strong { font-size: 1.4rem; font-weight: 760; }
-.openworld-village-speed span { font-family: var(--ow-micro-font); font-size: 0.55rem; letter-spacing: 0.08em; text-transform: uppercase; }
-
-.openworld-hud-crosshair {
- position: relative;
- width: 1.75rem;
- height: 1.75rem;
- opacity: 0.78;
-}
-
-.openworld-hud-crosshair::before,
-.openworld-hud-crosshair::after {
- position: absolute;
- content: '';
- inset: 0.72rem 0.15rem;
- border-top: 1px solid rgb(var(--port-accent) / 0.72);
- border-bottom: 1px solid rgb(var(--port-accent) / 0.72);
-}
-
-.openworld-hud-crosshair::after {
- inset: 0.15rem 0.72rem;
- border-top: 0;
- border-right: 1px solid rgb(var(--port-accent) / 0.72);
- border-bottom: 0;
- border-left: 1px solid rgb(var(--port-accent) / 0.72);
-}
-
-.openworld-interaction-prompt {
- position: absolute;
- left: 50%;
- bottom: 5.6rem;
- z-index: 2;
- display: flex;
- align-items: center;
- gap: 0.7rem;
- padding: 0.48rem 0.7rem;
- border: 1px solid rgb(var(--port-accent) / 0.34);
- border-radius: 12px;
- background: var(--ow-panel-soft);
- box-shadow: 0 12px 28px rgb(0 0 0 / 0.18), inset 0 1px 0 rgb(255 255 255 / 0.07);
- backdrop-filter: blur(16px) saturate(1.08);
- color: var(--ow-ink);
- font-family: var(--font-pixel, monospace);
- font-size: 0.56rem;
- letter-spacing: 0.08em;
- pointer-events: none;
- transform: translateX(-50%);
- white-space: nowrap;
-}
-
-.openworld-interaction-prompt__label {
- max-width: min(18rem, 36vw);
- overflow: hidden;
- color: var(--ow-ink);
- text-overflow: ellipsis;
- text-transform: uppercase;
-}
-
-.openworld-interaction-prompt__action {
- display: inline-flex;
- align-items: center;
- gap: 0.35rem;
- color: var(--ow-accent);
-}
-
-.openworld-interaction-prompt kbd {
- min-width: 1.35rem;
- padding: 0.2rem 0.28rem;
- border: 1px solid rgb(var(--port-accent) / 0.4);
- border-radius: 5px;
- background: rgb(var(--port-accent) / 0.12);
- color: var(--ow-ink);
- font: inherit;
- font-size: 0.5rem;
- text-align: center;
-}
-
-.openworld-interaction-prompt--compact {
- bottom: calc(13.35rem + env(safe-area-inset-bottom));
- max-width: calc(100vw - 2rem);
- gap: 0.45rem;
- padding: 0.42rem 0.58rem;
- font-size: 0.5rem;
-}
-
-.openworld-interaction-prompt--compact .openworld-interaction-prompt__label {
- max-width: 34vw;
-}
-
-.openworld-intel-surface {
- border-radius: 20px;
- background: linear-gradient(160deg, var(--ow-panel), rgb(var(--port-bg) / 0.9));
- border: 1px solid var(--ow-line);
- box-shadow: 0 20px 48px rgb(0 0 0 / 0.18), inset 0 1px 0 rgb(255 255 255 / 0.07);
- backdrop-filter: blur(20px) saturate(1.08);
-}
-
-@media (min-width: 768px) {
- .openworld-hud-action-copy { display: inline; }
-}
-
-/* The village toolbar shares the top edge with a status card, so its four long labels
- need more room than the general HUD actions. Keep the tablet layout icon-only. */
-.openworld-village-actions .openworld-hud-action-copy { display: none; }
-
-@media (min-width: 1280px) {
- .openworld-village-actions .openworld-hud-action-copy { display: inline; }
-}
-
-@media (max-width: 767px) {
- .openworld-hud-panel { border-radius: 16px; }
- .openworld-hud-dock { border-radius: 16px; overflow-x: auto; scrollbar-width: none; }
- .openworld-hud-dock::-webkit-scrollbar { display: none; }
- .openworld-hud-action { min-height: 2.75rem; min-width: 2.75rem; }
- .openworld-village-status {
- top: 0.65rem;
- left: 0.65rem;
- min-height: 2.85rem;
- max-width: calc(100vw - 13.25rem);
- gap: 0.5rem;
- padding: 0.45rem 0.55rem;
- }
- .openworld-village-status__dot { width: 0.5rem; height: 0.5rem; }
- .openworld-village-status small { font-size: 0.42rem; }
- .openworld-village-status strong { font-size: 0.72rem; }
- .openworld-village-status__echo { min-width: 3.7rem; padding-inline: 0.28rem; font-size: 0.52rem; }
- .openworld-village-actions { top: 0.65rem; right: 0.65rem; }
- .openworld-village-actions .openworld-hud-action { min-width: 2.45rem; min-height: 2.45rem; padding: 0.32rem; }
- .openworld-village-speed { top: 4.15rem; bottom: auto; left: 0.85rem; }
- .openworld-village-speed strong { font-size: 1.05rem; }
- .openworld-village-speed span { font-size: 0.46rem; }
- .openworld-interaction-prompt--compact { bottom: calc(5.4rem + env(safe-area-inset-bottom)); }
-}
-
-/* === OpenWorld mobile game controls ===
- The compact HUD owns information and navigation panels. These controls own the
- game loop, so a phone can drive, look, jump, interact, and exit without a keyboard. */
-.openworld-mobile-controls {
- isolation: isolate;
- user-select: none;
-}
-
-.openworld-mobile-look-zone {
- position: absolute;
- right: 0.4rem;
- bottom: calc(0.8rem + env(safe-area-inset-bottom));
- width: 48%;
- height: 46%;
- pointer-events: auto;
- touch-action: none;
-}
-
-.openworld-mobile-look-hint {
- position: absolute;
- top: 50%;
- right: 1.25rem;
- color: var(--ow-muted);
- font-family: var(--font-pixel, monospace);
- font-size: 0.5rem;
- letter-spacing: 0.16em;
- opacity: 0;
- transform: translateY(-50%);
- transition: opacity 160ms ease;
-}
-
-.openworld-mobile-look-zone:active .openworld-mobile-look-hint,
-.openworld-mobile-look-zone:focus-visible .openworld-mobile-look-hint {
- opacity: 0.7;
-}
-
-.openworld-mobile-joystick {
- position: absolute;
- left: 1rem;
- bottom: calc(1rem + env(safe-area-inset-bottom));
- width: 6.4rem;
- height: 6.4rem;
- border: 1px solid rgb(var(--port-accent) / 0.34);
- border-radius: 50%;
- background: radial-gradient(circle, rgb(var(--port-accent) / 0.14), rgb(var(--port-bg) / 0.42));
- box-shadow: 0 12px 30px rgb(0 0 0 / 0.2), inset 0 1px 0 rgb(255 255 255 / 0.08);
- backdrop-filter: blur(12px) saturate(1.08);
- pointer-events: auto;
- touch-action: none;
-}
-
-.openworld-mobile-joystick::before,
-.openworld-mobile-joystick::after {
- position: absolute;
- content: '';
- background: rgb(var(--port-accent) / 0.16);
-}
-
-.openworld-mobile-joystick::before {
- top: 50%;
- left: 1rem;
- right: 1rem;
- height: 1px;
-}
-
-.openworld-mobile-joystick::after {
- top: 1rem;
- bottom: 1rem;
- left: 50%;
- width: 1px;
-}
-
-.openworld-mobile-joystick-knob {
- position: absolute;
- top: 50%;
- left: 50%;
- width: 3rem;
- height: 3rem;
- border: 1px solid rgb(var(--port-accent) / 0.6);
- border-radius: 50%;
- background: linear-gradient(145deg, rgb(var(--port-accent) / 0.32), rgb(var(--port-bg) / 0.62));
- box-shadow: 0 0 18px rgb(var(--port-accent) / 0.16), inset 0 1px 0 rgb(255 255 255 / 0.12);
- transition: transform 80ms ease-out;
- z-index: 1;
-}
-
-.openworld-mobile-joystick-label {
- position: absolute;
- right: 0;
- bottom: 0.95rem;
- left: 0;
- color: var(--ow-muted);
- font-family: var(--font-pixel, monospace);
- font-size: 0.48rem;
- letter-spacing: 0.16em;
- text-align: center;
- pointer-events: none;
-}
-
-.openworld-mobile-actions {
- position: absolute;
- right: 0.5rem;
- bottom: calc(1rem + env(safe-area-inset-bottom));
- display: flex;
- align-items: flex-end;
- gap: 0.2rem;
- max-width: calc(100vw - 8.75rem);
- overflow: visible;
- padding: 0.2rem;
- scrollbar-width: none;
-}
-
-.openworld-mobile-actions::-webkit-scrollbar {
- display: none;
-}
-
-.openworld-mobile-action {
- display: inline-flex;
- flex: 0 0 auto;
- width: 2.65rem;
- height: 3.05rem;
- align-items: center;
- justify-content: center;
- flex-direction: column;
- gap: 0.15rem;
- border: 1px solid rgb(var(--port-accent) / 0.38);
- border-radius: 1rem;
- background: var(--ow-panel-soft);
- color: var(--ow-ink);
- font-family: var(--font-pixel, monospace);
- font-size: 0.46rem;
- letter-spacing: 0.1em;
- line-height: 1;
- box-shadow: 0 12px 28px rgb(0 0 0 / 0.18), inset 0 1px 0 rgb(255 255 255 / 0.08);
- backdrop-filter: blur(16px) saturate(1.08);
- touch-action: none;
-}
-
-.openworld-mobile-action:active,
-.openworld-mobile-action:focus-visible {
- border-color: rgb(var(--port-accent) / 0.78);
- background: rgb(var(--port-accent) / 0.2);
- color: var(--ow-accent);
- outline: none;
- transform: translateY(-1px);
-}
-
-.openworld-mobile-action small {
- color: var(--ow-muted);
- font-size: 0.4rem;
- letter-spacing: 0.08em;
-}
-
-.openworld-mobile-action--wide {
- width: 3.4rem;
- border-color: rgb(var(--port-accent) / 0.54);
- background: linear-gradient(145deg, rgb(var(--port-accent) / 0.2), var(--ow-panel-soft));
-}
-
-.openworld-mobile-action--exit {
- color: var(--ow-muted);
-}
-
-@media (min-width: 768px) {
- .openworld-mobile-controls { display: none; }
-}
-
/* === Classic Noon === */
/* Classic Noon uses the classic card surface directly; keeping the selector
explicit makes the day variant's card fill part of the theme contract. */
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index e60f051c79..6cfeedadb5 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -141,7 +141,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `moodBoardItemSrc.js` | `moodBoardItemSrc(item)` resolves a mood-board item to a display image/poster src (`imageUrl` → served `image:<file>` bytes → derived video thumbnail → null); `moodBoardItemVideoSrc(item)` resolves a `type:'video'` item's playback URL; `moodBoardItemAnalysisSource(item)` resolves an item to a prompt-from-media source (null when not a local gallery asset). Shared by MoodBoardDetail + MoodBoardReferenceStrip. |
| `rapidReaderPosition.js` | Cursor-to-word mapping plus privacy-preserving Rapid Reader progress persistence keyed by a text fingerprint; stores position/settings without storing pasted source text. |
| `registerServiceWorker.js` | `registerServiceWorker()` / `unregisterServiceWorkers()` — wires up the offline app-shell + low-bandwidth asset-caching service worker (`public/sw.js`). Registers only in a production secure context (HTTPS or localhost); no-ops over plain-HTTP Tailnet and tears down any stale SW in dev. Called once from `main.jsx`. |
-| `safeStorage.js` | `safeReadStorage` / `safeReadJsonStorage` / `safeWriteStorage` / `safeWriteJsonStorage` / `safeRemoveStorage` — guarded `localStorage` access that swallows throws (Safari private mode, blocked storage), with fallback-safe JSON parsing for structured entries. Use instead of touching `localStorage` inline so a storage failure never crashes init or a write path (#2387). Consumed by `useTheme`, `useOpenWorldSettings`, `useNavWorkingSet`, and the command palette. Also `safeReadJsonSession` / `safeWriteJsonSession` / `safeRemoveSession` — the same guarantees over `sessionStorage`, for tab-scoped crash-recovery buffers of edits the server has not accepted yet (QuotaBurn's unsaved-patch stash). `safeReadSession` / `safeWriteSession` are the raw-string session pair, for a plain flag (the stale-chunk build-id marker) that must not be JSON-quoted. |
+| `safeStorage.js` | `safeReadStorage` / `safeReadJsonStorage` / `safeWriteStorage` / `safeWriteJsonStorage` / `safeRemoveStorage` — guarded `localStorage` access that swallows throws (Safari private mode, blocked storage), with fallback-safe JSON parsing for structured entries. Use instead of touching `localStorage` inline so a storage failure never crashes init or a write path (#2387). Consumed by `useTheme`, `useNavWorkingSet`, and the command palette. Also `safeReadJsonSession` / `safeWriteJsonSession` / `safeRemoveSession` — the same guarantees over `sessionStorage`, for tab-scoped crash-recovery buffers of edits the server has not accepted yet (QuotaBurn's unsaved-patch stash). |
| `sameJsonShape.js` | `sameJsonShape(prev, next)` — JSON.stringify-based equality for `useAutoRefetch`'s `compare` option on small, deterministically-shaped poll payloads. |
| `sketchCanvas.js` | Pure stroke model + 2D-context renderer for the media annotation canvas (`createStroke`, `appendPoint`, `undoStrokes`, `drawStrokes`, `clampSize`). Points stored in natural-pixel space; erase strokes use `destination-out`. Used by `AnnotationCanvas.jsx` / `MediaAnnotate.jsx` (#2036). |
| `unsorted.js` | Synthetic "Unsorted" collection from media not filed in any real collection. |
@@ -155,7 +155,6 @@ grep -i "what you want to do" client/src/lib/README.md
| Module | Purpose |
|---|---|
| `audioContext.js` | `getAudioContext()` + `resumeAudioContext(c)` + `acquireAudioSession(type)` + `getNoiseBuffer(c)` (the app-wide 1s white-noise buffer every noise voice loops over — chiptune drums, the drum kit's snare/hats/cymbals; don't grow a third copy) — the ONE app-wide lazy Web Audio `AudioContext` singleton every playback feature shares (`songPlayback`, `scorePlayback`, `metronome`, `midiPlayback`). Browsers cap live contexts and one context = one sample clock, so simultaneous features stay aligned. **Every playback entry point resumes via `resumeAudioContext(c)`, never by hand** (it takes any context, so per-mount ones use it too) — it gates on `state !== 'running'`, not `state === 'suspended'`, because iOS Safari also parks a context in the non-standard `'interrupted'` (a call/Siri/screen lock) which a suspended-only check walks past into silent "playback". **`acquireAudioSession(type)` ARBITRATES `navigator.audioSession.type`, which is document-wide, and returns an idempotent release** — `playback` keeps the hardware ring/silent switch from muting a pure-synth page but REFUSES capture, and the VoiceWidget is mounted on every page, so a last-writer-wins assignment trades one platform's silence for a dead mic. Each feature claims for exactly as long as it needs (`play-and-record` while a `getUserMedia` stream is open, `playback` while a player sounds) and the arbiter declares the union — capture always wins, since `play-and-record` also ignores the silent switch. Output-only players don't call it directly: pass `audioSession: 'playback'` to `createLookaheadTransport`, which claims on play and releases on teardown; a React surface owning its own context/stream uses `hooks/useAudioSessionClaim.js`, which adds the release-on-unmount backstop. Constructor resolved lazily (`window` → `globalThis`) so node-env test runs import cleanly; tests inject a fake via `vi.stubGlobal('AudioContext', …)` before first call. |
-| `openWorldPlaybackFrame.js` | Map a recorded OpenWorld snapshot frame onto the prop shape OpenWorldScene/OpenWorldHud consume for the timeline scrubber (`mergeFrameIntoOpenWorldProps`, `buildPlaybackApps`, `buildPlaybackAgentMap`, `isPlayableFrame`). Honors `schemaVersion` and the capture-side null sentinels; returns only snapshot-backed props so unfed landmarks stay live. |
| `chordPlayback.js` | Chord-sheet play-along for the SongBook `tab`/`chordpro` formats (#4104) — the chord-sheet sibling of `drumPlayback.js` and the fourth consumer of `lookaheadTransport.js`. `sheetChordOccurrences(lines)` flattens `parseTabSheet(text).lines` into the ordered chord tokens, each addressed `{ lineIndex, chordIndex }` so `<TabSheetView>` can light exactly the token that is sounding; `chordMidiNotes(name)` voices one chord (bass note + chord tones, via `chordShapes.chordTones`); `buildChordSchedule(lines, { bpm, beatsPerBar, countInBars })` is the PURE chord→`[{ index, name, lineIndex, chordIndex, midis, startSec, durSec, rest }]` mapping (a chord sheet writes no rhythm, so ONE chord token = ONE bar, and a dash-joined "Am-Am7" splits its bar between its segments) plus the count-in clicks; `resolveChordPlayhead(schedule, posSec)` converts an audio-clock position to `{ countIn, index, beat }`; `createChordPlayer(lines, …)` strums it through `scorePlayback`'s `scheduleTone` with a live metronome toggle. |
| `chordShapes.js` | Chord-name → per-instrument voicing derivation for the SongBook viewer's instrument-view toggle (#2656). `getChordVoicing(name, instrument)` → guitar `{ frets: [6 × (-1/0/n)], baseFret, bass }`, ukulele (4-string GCEA, exact lowest-position search), or piano `{ notes: ['A','C','E'], bass }` with letter-accurate degree spelling (the 3rd of E is G#, never Ab); guitar shapes come from a curated first-position table + movable E-/A-form barre templates offset by `baseFret` (aug/dim7 exploit shape symmetry). Slash chords voice the base chord and carry `bass` separately. `parseChordName(name)`, `splitJoinedChords('Am-Am7')`, `toVoicingInstrument(songInstrument)`, `VOICING_INSTRUMENTS`. `chordTones(name)` returns the instrument-free half — the parse plus `semitones` above the root — so `chordPlayback.js` sounds a sheet without re-typing the interval tables. Reuses `tabNotation.js`'s `CHORD_TOKEN_RE`/`NOTE_TO_PC`/`spellPitchClass` (exported from there for this module) instead of duplicating the tables. Unknown/unparseable chords → null, never throws. |
| `canvasRoll.js` | Shared canvas helpers for the two piano-roll renderers (`<PianoRoll>` falling-note + `<MidiPianoRoll>` DAW-style, #2477). `layerColor(index)` — the per-layer/track palette (8 hues, wraps both directions) used by note bars, keyboards, and legends; `roundRect(ctx, x, y, w, h, r)` — rounded-rect path with `ctx.roundRect` feature-detect and arcTo fallback; `rollPalette()` — resolves the theme-following `{ bg, accent, accentRgb }` from `--port-accent` via `getComputedStyle` (canvas can't read CSS vars); `ROLL_BG` — the shared near-black bg literal. Pure canvas math/palette, no React. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 513e9edbd6..3df16c0322 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -122,7 +122,6 @@ export * from './youtubeUrl.js';
// === Page-scoped pure helpers ===
export * from './audioContext.js';
-export * from './openWorldPlaybackFrame.js';
export * from './canvasRoll.js';
export * from './chiptunePlayback.js';
export * from './chordPlayback.js';
diff --git a/client/src/lib/openWorldPlaybackFrame.js b/client/src/lib/openWorldPlaybackFrame.js
deleted file mode 100644
index f5612d5be8..0000000000
--- a/client/src/lib/openWorldPlaybackFrame.js
+++ /dev/null
@@ -1,131 +0,0 @@
-// Pure mappers that turn a recorded OpenWorld snapshot frame (issue #877 capture
-// pipeline) into the prop shape OpenWorldScene consumes, for the timeline scrubber
-// (issue #967). No React, no I/O — unit-tested in openWorldPlaybackFrame.test.js.
-//
-// A snapshot frame is compact: per-app { id, name, status }, agent assignments,
-// and counts/health/cos/backup/character. It does NOT carry the rich landmark
-// inputs (memory graph, goals, jira, activity, productivity), so playback drives
-// only what the frame can feed and the page leaves the rest at their live values
-// ("freeze unfed landmarks at live").
-//
-// Sentinel discipline mirrors the capture side: a `null` field means "source
-// unavailable at capture time" — never fabricate a 0/empty in its place. A null
-// apps/assignments array falls back to the live value rather than emptying the
-// city.
-
-// The snapshot shape this scrubber understands. A frame whose schemaVersion
-// differs should be skipped/flagged by the caller rather than mis-rendered.
-export const SUPPORTED_SNAPSHOT_SCHEMA_VERSION = 1;
-
-export const isPlayableFrame = (frame) =>
- !!frame && frame.schemaVersion === SUPPORTED_SNAPSHOT_SCHEMA_VERSION;
-
-// Build the apps array OpenWorldScene renders from a frame, recovering render-only
-// fields (processes, repoPath, type, archived) from the matching live app and
-// overriding overallStatus with the frame's recorded status. Apps in the live
-// set but absent from the frame are dropped (they teardown-animate out). Apps in
-// the frame but no longer live render from the compact fields with safe defaults.
-export function buildPlaybackApps(frame, liveApps = []) {
- // Failed capture → fall back to live apps rather than emptying the city.
- if (!Array.isArray(frame?.apps)) return liveApps;
- const liveById = new Map((liveApps || []).map((a) => [a.id, a]));
- return frame.apps.map((snap) => {
- const live = liveById.get(snap.id);
- if (live) {
- return { ...live, overallStatus: snap.status };
- }
- // App no longer exists live — render a minimal building from the frame.
- return {
- id: snap.id,
- name: snap.name,
- overallStatus: snap.status,
- archived: false,
- processes: [],
- };
- });
-}
-
-// Rebuild the agentMap (Map<appId, { app, agents }>) from the frame's compact
-// assignment list. Only running assignments are captured.
-//
-// Sentinel discipline: a `null` assignments array means "agent source failed at
-// capture time" — return the live agentMap (passed in) rather than an empty map,
-// so a transient capture failure doesn't read as "no agents were running." A
-// real empty array yields a real empty map (no agent entities).
-export function buildPlaybackAgentMap(frame, playbackApps = [], liveAgentMap = new Map()) {
- if (!Array.isArray(frame?.assignments)) return liveAgentMap;
- const map = new Map();
- const appById = new Map((playbackApps || []).map((a) => [a.id, a]));
- for (const asn of frame.assignments) {
- if (!asn?.appId) continue;
- const app = appById.get(asn.appId);
- if (!app) continue;
- const existing = map.get(asn.appId) || { app, agents: [] };
- existing.agents.push({ agentId: asn.agentId, status: asn.status });
- map.set(asn.appId, existing);
- }
- return map;
-}
-
-// The OpenWorldScene props a snapshot frame can FAITHFULLY drive — i.e. scene elements
-// whose data the frame actually carries at the right granularity:
-// apps → buildings (per-app status)
-// agentMap → agent entities (assignments)
-// cosStatus → skyline automation state (running/paused/active)
-// backupStatus→ backup vault (status/lastRun)
-// character → artifact placement (level)
-//
-// Deliberately NOT returned (so the page leaves them at LIVE — "freeze unfed
-// landmarks at live"): the count-only landmarks (task queue, federation horizon,
-// health tower, memory, goals, jira, activity) render from rich per-item arrays
-// the snapshot doesn't carry, only aggregate counts. Faking array items from a
-// count would misrepresent history; instead the captured counts are surfaced as
-// numbers in the playback overlay via buildPlaybackStats(). Each value is null
-// when the frame recorded null (source unavailable at capture).
-//
-// Returns null when the frame isn't playable (wrong/absent schemaVersion) so the
-// caller can keep showing live data and flag the frame.
-export function mergeFrameIntoOpenWorldProps(frame, live = {}) {
- if (!isPlayableFrame(frame)) return null;
- const apps = buildPlaybackApps(frame, live.apps);
- const agentMap = buildPlaybackAgentMap(frame, apps, live.agentMap);
- return {
- apps,
- agentMap,
- cosStatus: frame?.cos == null ? null : {
- running: frame.cos.running ?? false,
- paused: frame.cos.paused ?? false,
- activeAgents: frame.counts?.agentsActive ?? null,
- pausedAgents: frame.counts?.agentsPaused ?? null,
- stats: { tasksCompleted: frame.counts?.tasksCompleted ?? null },
- },
- backupStatus: frame?.backup == null ? null : {
- status: frame.backup.status ?? null,
- lastRun: frame.backup.lastRun ?? null,
- },
- character: frame?.character == null ? null : { level: frame.character.level ?? null },
- };
-}
-
-// Historical numbers the snapshot captured that don't drive a 3D landmark (their
-// landmarks render from rich arrays and stay live). Surfaced as a readout in the
-// playback overlay so the captured counts/health are still visible while
-// scrubbing. Preserves null (unavailable at capture) vs a real number — the
-// overlay renders null as "—". Returns null for an unplayable frame.
-export function buildPlaybackStats(frame) {
- if (!isPlayableFrame(frame)) return null;
- const c = frame.counts || {};
- const h = frame.health || {};
- return {
- cpuPercent: h.cpuPercent ?? null,
- memPercent: h.memPercent ?? null,
- diskPercent: h.diskPercent ?? null,
- agentsActive: c.agentsActive ?? null,
- tasksPending: c.tasksPending ?? null,
- tasksInProgress: c.tasksInProgress ?? null,
- peersOnline: c.peersOnline ?? null,
- peersTotal: c.peersTotal ?? null,
- reviewTotal: c.reviewTotal ?? null,
- notificationsUnread: c.notificationsUnread ?? null,
- };
-}
diff --git a/client/src/lib/openWorldPlaybackFrame.test.js b/client/src/lib/openWorldPlaybackFrame.test.js
deleted file mode 100644
index b3c0338a09..0000000000
--- a/client/src/lib/openWorldPlaybackFrame.test.js
+++ /dev/null
@@ -1,146 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- isPlayableFrame,
- buildPlaybackApps,
- buildPlaybackAgentMap,
- mergeFrameIntoOpenWorldProps,
- buildPlaybackStats,
- SUPPORTED_SNAPSHOT_SCHEMA_VERSION,
-} from './openWorldPlaybackFrame.js';
-
-const liveApps = [
- { id: 'a1', name: 'App One', overallStatus: 'online', archived: false, processes: [{ name: 'api' }], repoPath: '/repos/a1', type: 'express' },
- { id: 'a2', name: 'App Two', overallStatus: 'online', archived: false, processes: [], repoPath: '/repos/a2', type: 'express' },
-];
-
-const frame = (over = {}) => ({
- ts: '2026-06-05T12:00:00.000Z',
- schemaVersion: SUPPORTED_SNAPSHOT_SCHEMA_VERSION,
- apps: [
- { id: 'a1', name: 'App One', status: 'stopped' },
- { id: 'a2', name: 'App Two', status: 'online' },
- ],
- assignments: [{ agentId: 'agent-1', appId: 'a1', status: 'running' }],
- counts: {
- appsOnline: 1, appsTotal: 2, agentsActive: 1, agentsPaused: 0,
- tasksCompleted: 7, tasksPending: 2, tasksInProgress: 1,
- peersOnline: 1, peersTotal: 2, notificationsUnread: 3, reviewTotal: 4,
- },
- cos: { running: true, paused: false },
- backup: { status: 'success', lastRun: '2026-06-05T00:00:00.000Z' },
- health: { cpuPercent: 12, memPercent: 40, diskPercent: 55 },
- character: { level: 4 },
- instance: { id: 'inst-1', name: 'void' },
- ...over,
-});
-
-describe('isPlayableFrame', () => {
- it('accepts a frame on the supported schema version', () => {
- expect(isPlayableFrame(frame())).toBe(true);
- });
- it('rejects a frame with a mismatched or absent schemaVersion', () => {
- expect(isPlayableFrame(frame({ schemaVersion: 99 }))).toBe(false);
- expect(isPlayableFrame({ ...frame(), schemaVersion: undefined })).toBe(false);
- expect(isPlayableFrame(null)).toBe(false);
- });
-});
-
-describe('buildPlaybackApps', () => {
- it('overrides live overallStatus with the frame status, keeping render-only fields', () => {
- const apps = buildPlaybackApps(frame(), liveApps);
- expect(apps).toHaveLength(2);
- const a1 = apps.find(a => a.id === 'a1');
- expect(a1.overallStatus).toBe('stopped'); // overridden from frame
- expect(a1.processes).toEqual([{ name: 'api' }]); // recovered from live
- expect(a1.repoPath).toBe('/repos/a1');
- });
-
- it('drops live apps absent from the frame (teardown)', () => {
- const f = frame({ apps: [{ id: 'a1', name: 'App One', status: 'online' }] });
- const apps = buildPlaybackApps(f, liveApps);
- expect(apps.map(a => a.id)).toEqual(['a1']);
- });
-
- it('renders a minimal building for a frame app no longer live', () => {
- const f = frame({ apps: [{ id: 'gone', name: 'Ghost', status: 'stopped' }] });
- const apps = buildPlaybackApps(f, liveApps);
- expect(apps).toEqual([{ id: 'gone', name: 'Ghost', overallStatus: 'stopped', archived: false, processes: [] }]);
- });
-
- it('falls back to live apps when the frame apps array is null (failed capture)', () => {
- const f = frame({ apps: null });
- expect(buildPlaybackApps(f, liveApps)).toBe(liveApps);
- });
-});
-
-describe('buildPlaybackAgentMap', () => {
- it('rebuilds the agentMap keyed by appId from assignments', () => {
- const apps = buildPlaybackApps(frame(), liveApps);
- const map = buildPlaybackAgentMap(frame(), apps);
- expect(map.get('a1').agents).toEqual([{ agentId: 'agent-1', status: 'running' }]);
- expect(map.has('a2')).toBe(false);
- });
-
- it('returns an EMPTY map for a real empty assignments array (no agents running)', () => {
- const apps = buildPlaybackApps(frame(), liveApps);
- const map = buildPlaybackAgentMap(frame({ assignments: [] }), apps, new Map([['x', {}]]));
- expect(map.size).toBe(0);
- });
-
- it('falls back to the LIVE agentMap when assignments are null (failed capture)', () => {
- const apps = buildPlaybackApps(frame(), liveApps);
- const live = new Map([['a1', { app: liveApps[0], agents: [{ agentId: 'live-1' }] }]]);
- const map = buildPlaybackAgentMap(frame({ assignments: null }), apps, live);
- expect(map).toBe(live);
- });
-});
-
-describe('buildPlaybackStats', () => {
- it('surfaces captured numbers, preserving null vs real values', () => {
- const s = buildPlaybackStats(frame());
- expect(s).toMatchObject({ cpuPercent: 12, memPercent: 40, diskPercent: 55, agentsActive: 1, tasksPending: 2, tasksInProgress: 1, peersOnline: 1, peersTotal: 2, reviewTotal: 4 });
- });
- it('returns null fields when the capture recorded null', () => {
- const s = buildPlaybackStats(frame({ health: { cpuPercent: null, memPercent: null, diskPercent: null }, counts: { reviewTotal: null } }));
- expect(s.cpuPercent).toBeNull();
- expect(s.reviewTotal).toBeNull();
- });
- it('returns null for an unplayable frame', () => {
- expect(buildPlaybackStats(frame({ schemaVersion: 99 }))).toBeNull();
- });
-});
-
-describe('mergeFrameIntoOpenWorldProps', () => {
- it('returns null for an unplayable frame so the page keeps live data', () => {
- expect(mergeFrameIntoOpenWorldProps(frame({ schemaVersion: 99 }), { apps: liveApps })).toBeNull();
- });
-
- it('maps the faithfully-driveable scene props (apps/agentMap/cos/backup/character)', () => {
- const props = mergeFrameIntoOpenWorldProps(frame(), { apps: liveApps });
- expect(props.apps).toHaveLength(2);
- expect(props.agentMap.get('a1').agents).toEqual([{ agentId: 'agent-1', status: 'running' }]);
- expect(props.cosStatus).toMatchObject({ running: true, activeAgents: 1, stats: { tasksCompleted: 7 } });
- expect(props.backupStatus).toEqual({ status: 'success', lastRun: '2026-06-05T00:00:00.000Z' });
- expect(props.character).toEqual({ level: 4 });
- });
-
- it('passes null (not a fabricated 0/empty) when cos/backup/character were unavailable at capture', () => {
- const props = mergeFrameIntoOpenWorldProps(
- frame({ cos: null, backup: null, character: null }),
- { apps: liveApps },
- );
- expect(props.cosStatus).toBeNull();
- expect(props.backupStatus).toBeNull();
- expect(props.character).toBeNull();
- });
-
- it('does NOT return count-only / unfed landmark props, so the page leaves them at live values', () => {
- const props = mergeFrameIntoOpenWorldProps(frame(), { apps: liveApps });
- // count-driven landmarks (freeze at live; their numbers go to the overlay instead)
- // + rich-array landmarks the frame never captured.
- for (const key of ['instances', 'systemHealth', 'reviewCounts', 'notificationCounts', 'cosTasks', 'memoryGraph', 'goals', 'jiraTickets', 'activityCalendar', 'productivityData', 'chronotype']) {
- expect(props).not.toHaveProperty(key);
- }
- });
-});
-// @vitest-environment node
diff --git a/client/src/pages/CharacterSheet.jsx b/client/src/pages/CharacterSheet.jsx
index 7007dd333f..7741209522 100644
--- a/client/src/pages/CharacterSheet.jsx
+++ b/client/src/pages/CharacterSheet.jsx
@@ -413,8 +413,7 @@ export default function CharacterSheet() {
const hpPct = Math.max(0, Math.min(100, (char.hp / char.maxHp) * 100));
// Level is age-derived now (#2673) — it no longer maps to an XP threshold, so the old
- // "XP toward next level" bar is gone. XP survives as a plain cumulative stat here; the
- // birthday-progress bar lives on the OpenWorld HUD badge (full page reframe is Slice 5).
+ // "XP toward next level" bar is gone. XP survives as a plain cumulative stat here.
const birthdayPct = Number.isFinite(char.ageYears)
? Math.round((char.ageYears - Math.floor(char.ageYears)) * 100)
: 0;
diff --git a/client/src/pages/OpenWorld.fastTravel.test.jsx b/client/src/pages/OpenWorld.fastTravel.test.jsx
deleted file mode 100644
index c0fbef48f0..0000000000
--- a/client/src/pages/OpenWorld.fastTravel.test.jsx
+++ /dev/null
@@ -1,229 +0,0 @@
-import { describe, it, expect, beforeEach, vi } from 'vitest';
-import { render, screen, fireEvent, act } from '@testing-library/react';
-import { MemoryRouter, Routes, Route, useLocation } from 'react-router';
-
-// The 3D scene and the cockpit HUD are stubbed: this suite is about the page's fast-travel
-// WIRING (route param → scene props, M → panel, pick → navigate + teleport), not about
-// rendering WebGL in jsdom. The scene stub records the props it received so the assertions
-// can read them directly.
-const sceneProps = { current: null };
-const openWorldDataState = vi.hoisted(() => ({ loading: false }));
-vi.mock('../components/openworld/OpenWorldScene', () => ({
- default: (props) => {
- sceneProps.current = props;
- return <div data-testid="scene" />;
- },
-}));
-vi.mock('../components/openworld/OpenWorldHud', () => ({
- default: ({ onOpenFastTravel, activeRegion, onEnterPhotoMode }) => (
- <div>
- <button type="button" onClick={onOpenFastTravel}>hud-fast-travel</button>
- <button type="button" onClick={onEnterPhotoMode}>hud-photo</button>
- <span data-testid="hud-region">{activeRegion?.id || 'none'}</span>
- </div>
- ),
-}));
-vi.mock('../components/openworld/OpenWorldPhotoOverlay', () => ({ default: () => null }));
-vi.mock('../components/openworld/OpenWorldPlaybackOverlay', () => ({ default: () => null }));
-vi.mock('../components/openworld/OpenWorldSettingsDrawer', () => ({ default: () => null }));
-
-vi.mock('../hooks/useOpenWorldData', async () => {
- const { OPEN_WORLD_DATA } = await import('../test/openWorldPageMocks.js');
- // Only `loading` varies per test here; everything else is the shared empty shape.
- return { useOpenWorldData: () => ({ ...OPEN_WORLD_DATA, loading: openWorldDataState.loading }) };
-});
-vi.mock('../hooks/useOpenWorldPlayback', async () => {
- const { openWorldPlaybackMock } = await import('../test/openWorldPageMocks.js');
- const playback = openWorldPlaybackMock(vi);
- return { useOpenWorldPlayback: () => playback };
-});
-vi.mock('../hooks/useOpenWorldAudio', () => ({ default: () => ({ playSfx: vi.fn(), isAudioReady: false }) }));
-vi.mock('../hooks/useAutoRefetch', () => ({ useAutoRefetch: () => ({ data: null }) }));
-vi.mock('../hooks/useInstanceFeatures', () => ({
- useInstanceFeatures: () => ({
- features: [],
- error: null,
- isFeatureEnabled: () => true,
- reload: () => Promise.resolve(),
- }),
-}));
-// Only the endpoints this page polls, from the shared page fixture. The vi.mock
-// CALL has to stay here (vitest hoists it), so the factory dynamic-imports it.
-vi.mock('../services/api', async () => (await import('../test/openWorldPageMocks.js')).openWorldApiMock(vi));
-
-const OpenWorld = (await import('./OpenWorld')).default;
-
-function LocationProbe() {
- const location = useLocation();
- return <span data-testid="path">{location.pathname}</span>;
-}
-
-const renderAt = (path) => render(
- <MemoryRouter initialEntries={[path]}>
- <LocationProbe />
- <Routes>
- <Route path="/openworld" element={<OpenWorld />} />
- <Route path="/openworld/region/:regionId" element={<OpenWorld />} />
- <Route path="/brain/inbox" element={<div>brain page</div>} />
- </Routes>
- </MemoryRouter>
-);
-
-describe('OpenWorld — fast travel wiring', () => {
- beforeEach(() => {
- sceneProps.current = null;
- openWorldDataState.loading = false;
- localStorage.clear();
- });
-
- it('keeps the scene mounted while the initial data bundle is loading', () => {
- openWorldDataState.loading = true;
-
- renderAt('/openworld');
-
- expect(screen.getByTestId('scene')).toBeInTheDocument();
- expect(screen.queryByText('ENTERING OPENWORLD')).not.toBeInTheDocument();
- });
-
- it('hands the scene no region on the plain overview route', () => {
- renderAt('/openworld');
- expect(sceneProps.current.focusedRegion).toBeNull();
- });
-
- it('resolves the :regionId route param into a region for the camera', () => {
- renderAt('/openworld/region/memory');
- expect(sceneProps.current.focusedRegion.id).toBe('memory');
- // Geography comes from the master town plan, not from the route.
- expect(sceneProps.current.focusedRegion.anchor).toBeDefined();
- });
-
- it('arms the first-person arrival point for a direct region deep link', () => {
- renderAt('/openworld/region/memory');
- expect(sceneProps.current.playerTeleport).toMatchObject({
- x: expect.any(Number),
- z: expect.any(Number),
- regionId: 'memory',
- token: 1,
- });
- });
-
- it('hands the scene a null region for an unknown id rather than crashing', () => {
- renderAt('/openworld/region/atlantis');
- expect(sceneProps.current.focusedRegion).toBeNull();
- });
-
- it('defaults to the Vibes world style, and reflects it in the scene settings', () => {
- renderAt('/openworld');
- expect(sceneProps.current.settings.worldStyle).toBe('vibes');
- expect(sceneProps.current.settings.timeOfDay).toMatch(/^vibes/);
- expect(sceneProps.current.palette.lowPoly).toBe(true);
- });
-
- it('honors a stored cyber style, restoring the original preset pair', () => {
- localStorage.setItem('portos-city-settings', JSON.stringify({ worldStyle: 'cyber' }));
- renderAt('/openworld');
- expect(sceneProps.current.settings.worldStyle).toBe('cyber');
- expect(sceneProps.current.settings.timeOfDay).toBe('sunset');
- expect(sceneProps.current.palette.lowPoly).toBe(false);
- });
-
- it('opens fast travel with M and warps to the picked region', () => {
- renderAt('/openworld');
- act(() => { fireEvent.keyDown(window, { key: 'm' }); });
-
- fireEvent.click(screen.getByLabelText('Teleport to Memory House'));
-
- expect(screen.getByTestId('path')).toHaveTextContent('/openworld/region/memory');
- expect(sceneProps.current.focusedRegion.id).toBe('memory');
- });
-
- it('opens fast travel from the HUD button too', () => {
- renderAt('/openworld');
- fireEvent.click(screen.getByText('hud-fast-travel'));
- expect(screen.getByLabelText('Teleport to Memory House')).toBeInTheDocument();
- });
-
- it('closes fast travel with Escape', () => {
- renderAt('/openworld');
- act(() => { fireEvent.keyDown(window, { key: 'm' }); });
- expect(screen.getByLabelText('Search village places')).toBeInTheDocument();
-
- act(() => { fireEvent.keyDown(window, { key: 'Escape' }); });
- expect(screen.queryByLabelText('Search village places')).not.toBeInTheDocument();
- });
-
- it('arms no arrival point until something is actually warped to', () => {
- renderAt('/openworld');
- expect(sceneProps.current.playerTeleport).toBeNull();
- });
-
- it(`arms the walking player's arrival point on every warp, exploring or not`, () => {
- // PlayerController mounts only in exploration mode and applies the current token on
- // mount, so arming it from the orbital overview is what makes "warp, then Tab in"
- // land at the region rather than the old spawn.
- renderAt('/openworld');
- act(() => { fireEvent.keyDown(window, { key: 'm' }); });
- fireEvent.click(screen.getByLabelText('Teleport to Memory House'));
-
- const teleport = sceneProps.current.playerTeleport;
- expect(teleport).toMatchObject({ x: expect.any(Number), z: expect.any(Number) });
- expect(teleport.token).toBe(1);
- });
-
- it('teleports the player when warping on foot', () => {
- localStorage.setItem('portos-city-settings', JSON.stringify({ explorationMode: true }));
- renderAt('/openworld');
- act(() => { fireEvent.keyDown(window, { key: 'm' }); });
- fireEvent.click(screen.getByLabelText('Teleport to Memory House'));
-
- const teleport = sceneProps.current.playerTeleport;
- expect(teleport).toMatchObject({ x: expect.any(Number), z: expect.any(Number) });
- expect(teleport.token).toBe(1);
- });
-
- it('bumps the teleport token when the same region is picked twice', () => {
- renderAt('/openworld');
-
- act(() => { fireEvent.keyDown(window, { key: 'm' }); });
- fireEvent.click(screen.getByLabelText('Teleport to Memory House'));
- expect(sceneProps.current.playerTeleport.token).toBe(1);
-
- act(() => { fireEvent.keyDown(window, { key: 'm' }); });
- fireEvent.click(screen.getByLabelText('Teleport to Memory House'));
- // Same destination, new warp — a plain {x,z} identity check would have swallowed this.
- expect(sceneProps.current.playerTeleport.token).toBe(2);
- });
-
- it('does not bank an M keypress while photo mode owns the camera', () => {
- // The panel is hidden in photo/playback mode; a live binding there would spring it
- // open the moment the user returned to the live view.
- renderAt('/openworld');
- fireEvent.click(screen.getByText('hud-photo'));
- act(() => { fireEvent.keyDown(window, { key: 'm' }); });
- expect(screen.queryByLabelText('Search village places')).not.toBeInTheDocument();
-
- fireEvent.keyDown(window, { key: 'Escape' }); // leave photo mode
- act(() => {});
- expect(screen.queryByLabelText('Search village places')).not.toBeInTheDocument();
- });
-
- it('tells the HUD which region is active', () => {
- renderAt('/openworld/region/data-harbor');
- expect(screen.getByTestId('hud-region')).toHaveTextContent('data-harbor');
- });
-
- it('keeps map interactions inside OpenWorld', () => {
- renderAt('/openworld/region/memory');
- act(() => { fireEvent.keyDown(window, { key: 'm' }); });
- expect(screen.queryByTitle(/Open\s+\//)).not.toBeInTheDocument();
- expect(screen.getByTestId('path')).toHaveTextContent('/openworld/region/memory');
- });
-
- it('returns to the overview from the panel', () => {
- renderAt('/openworld/region/memory');
- act(() => { fireEvent.keyDown(window, { key: 'm' }); });
- fireEvent.click(screen.getByText('OVERVIEW'));
- expect(screen.getByTestId('path')).toHaveTextContent('/openworld');
- expect(sceneProps.current.focusedRegion).toBeNull();
- });
-});
diff --git a/client/src/pages/OpenWorld.jsx b/client/src/pages/OpenWorld.jsx
deleted file mode 100644
index 47ac11c415..0000000000
--- a/client/src/pages/OpenWorld.jsx
+++ /dev/null
@@ -1,713 +0,0 @@
-import { useCallback, useState, useEffect, useMemo, useRef } from 'react';
-import { useNavigate, useLocation, useParams } from 'react-router';
-import { useOpenWorldData } from '../hooks/useOpenWorldData';
-import { useOpenWorldPlayback } from '../hooks/useOpenWorldPlayback';
-import useOpenWorldAudio from '../hooks/useOpenWorldAudio';
-import useKeyboardControls from '../hooks/useKeyboardControls';
-import useKeyboardShortcuts from '../hooks/useKeyboardShortcuts';
-import useKeyCapture from '../hooks/useKeyCapture';
-import { useAutoRefetch } from '../hooks/useAutoRefetch';
-import { mergeFrameIntoOpenWorldProps } from '../lib/openWorldPlaybackFrame';
-import { safeReadJsonSession, safeWriteJsonSession } from '../lib/safeStorage.js';
-import * as api from '../services/api';
-import OpenWorldScene from '../components/openworld/OpenWorldScene';
-import OpenWorldHud from '../components/openworld/OpenWorldHud';
-import OpenWorldMobileControls from '../components/openworld/OpenWorldMobileControls';
-import OpenWorldPhotoOverlay from '../components/openworld/OpenWorldPhotoOverlay';
-import OpenWorldPlaybackOverlay from '../components/openworld/OpenWorldPlaybackOverlay';
-import { OpenWorldSettingsProvider, useOpenWorldSettingsContext } from '../components/openworld/OpenWorldSettingsContext';
-import OpenWorldSettingsDrawer from '../components/openworld/OpenWorldSettingsDrawer';
-import { computeFilterResult } from '../utils/openWorldFilter';
-import { resolveOpenWorldFocus } from '../utils/openWorldFocusState';
-import useOpenWorldViewport from '../hooks/useOpenWorldViewport';
-import { DEFAULT_PRESET_ID, cyclePreset } from '../utils/openWorldPhotoMode';
-import { computeSoundscape } from '../utils/openWorldSoundscape';
-import { deriveOpenWorldPalette, getTimeOfDayPreset, resolveOpenWorldTimeOfDay, resolveWorldStyle } from '../components/openworld/openWorldConstants';
-import OpenWorldFastTravel from '../components/openworld/OpenWorldFastTravel';
-import { getRegion, regionArrivalPoint, regionPath } from '../utils/openWorldRegions';
-import { getCollectiblesList, loadCollectedShardIds, saveCollectedShardIds } from '../utils/openWorldCollectibles';
-import { OpenWorldPaletteProvider } from '../components/openworld/OpenWorldPaletteContext';
-import { useThemeContext } from '../components/ThemeContext';
-import { useInstanceFeatures } from '../hooks/useInstanceFeatures';
-import { recommendOpenWorldStartTier } from '../utils/openWorldRenderBudget';
-
-// Tab-scoped: the app filter should survive a reload but not outlive the tab.
-const FILTER_STORAGE_KEY = 'openworld.filter';
-
-// Internal render budgets only. These tiers are selected from sustained frame time and are
-// deliberately not persisted or exposed as player settings; art direction stays coherent while
-// the renderer sheds work on slower hardware.
-const RENDER_TIERS = {
- low: { particleDensity: 0.5, dpr: [1, 1] },
- medium: { particleDensity: 0.75, dpr: [1, 1.25] },
- high: { particleDensity: 1, dpr: [1, 1.25] },
- ultra: { particleDensity: 1.5, dpr: [1, 1.5] },
-};
-
-function OpenWorldInner() {
- const { apps, cosAgents, cosStatus, eventLogs, agentMap, reviewCounts, instances, systemHealth, notificationCounts, backupStatus, cosTasks, healthMetrics, voiceState, character, aiActivity, loading, connected } = useOpenWorldData();
- const { settings, updateSetting, resetNonce } = useOpenWorldSettingsContext();
-
- // Ambient soundscape (roadmap 3.4): the music's mood follows system health and its energy
- // follows live agent activity. Derived from data the page already has — no extra fetch.
- const activeAgentCount = useMemo(
- () => (cosAgents || []).filter(a => a.status === 'running' || a.state === 'coding' || a.state === 'thinking' || a.state === 'investigating').length,
- [cosAgents]
- );
- const soundscape = useMemo(
- () => computeSoundscape({ systemHealth, agentCount: activeAgentCount }),
- [systemHealth, activeAgentCount]
- );
- const { playSfx } = useOpenWorldAudio(settings, soundscape);
- const navigate = useNavigate();
- const location = useLocation();
- const { appId, regionId } = useParams();
- const { isDesktop } = useOpenWorldViewport();
- const {
- features: instanceFeatures,
- error: instanceFeaturesError,
- isFeatureEnabled,
- } = useInstanceFeatures();
- // OpenWorld browse surfaces use the hook's fail-open gate so a settings
- // hiccup never blanks navigation. Passive JIRA data is different: do not
- // poll or render tickets while participation is loading or unreadable.
- const isPassiveFeatureEnabled = useCallback((featureId) => (
- !featureId
- || (!instanceFeaturesError
- && Array.isArray(instanceFeatures)
- && instanceFeatures.some((feature) => feature?.id === featureId && feature.enabled === true))
- ), [instanceFeatures, instanceFeaturesError]);
- const visibleCollectibles = useMemo(
- () => getCollectiblesList(isPassiveFeatureEnabled),
- [isPassiveFeatureEnabled],
- );
-
- // URL-addressed building focus (issue #2593). The `/openworld/apps/:appId` route param is the
- // single source of truth for "which borough is focused" — reload/back-forward/deep-link all
- // restore it.
- const { hasFocus, focusedApp, notFound: focusNotFound } = useMemo(
- () => resolveOpenWorldFocus(appId, apps, { loading }),
- [appId, apps, loading],
- );
- // Fast travel: `/openworld/region/:regionId` is the same contract one level out — the URL says
- // which region you warped to, so a warp is shareable, bookmarkable, and reachable from ⌘K and
- // voice. The registry is static (no loading race), and an unknown id resolves to null, which
- // simply leaves the camera on the overview.
- const focusedRegion = useMemo(() => getRegion(regionId), [regionId]);
- const focusAgents = useMemo(() => agentMap?.get?.(appId)?.agents || [], [agentMap, appId]);
- // HUD safe area the focus camera frames around: the detail panel sits on the right (desktop) or
- // as a bottom sheet (compact), so keep the borough clear of it.
- const focusHudSafe = useMemo(
- () => (isDesktop ? { right: 0.28, bottom: 0 } : { right: 0, bottom: 0.5 }),
- [isDesktop],
- );
-
- // OpenWorld follows the active PortOS theme: the HUD recolors via the
- // `openworld-themed` CSS scope (see index.css) and the 3D scene's brand colors
- // + surround are derived from the same theme here.
- const { theme: openWorldTheme } = useThemeContext();
- // Art direction — 'vibes' (bright low-poly open world, the default) or 'cyber' (the
- // original neon night). It selects the time-of-day preset pair and the palette's
- // structural/decorative surfaces, so it must resolve before either.
- const worldStyle = resolveWorldStyle(settings?.worldStyle);
- // Pure: derive the themed palette and hand it down through OpenWorldPaletteContext (and,
- // inside <Canvas>, a second provider in OpenWorldScene since r3f's reconciler doesn't
- // bridge context). No more during-render mutation of a shared singleton.
- const openWorldPalette = useMemo(() => deriveOpenWorldPalette(openWorldTheme, worldStyle), [openWorldTheme, worldStyle]);
-
- // Open World renders day or night, following the theme mode by default; Cyber City is
- // always night (see resolveOpenWorldTimeOfDay). The resolved preset key is handed to the scene via a
- // settings override (OpenWorldSky/OpenWorldLights/OpenWorldGround read settings.timeOfDay), and the
- // backdrop takes the matching preset's mid-sky band so the DOM surround behind the
- // canvas agrees with the sky the scene actually paints, in either art direction.
- const openWorldTimeOfDay = resolveOpenWorldTimeOfDay(settings?.timeOfDay, openWorldPalette.isDay, worldStyle);
- const sceneBackground = openWorldTimeOfDay.daytime
- ? getTimeOfDayPreset(openWorldTimeOfDay.presetKey).midSky
- : openWorldPalette.nightBackground;
-
- // Rendering adapts silently. The player gets a stable art direction and the renderer
- // chooses its detail tier from sustained frame time; low/medium/high/ultra are internal
- // budgets, not design settings. This keeps the settings drawer focused on choices a player
- // can actually feel (world style, audio, and controls).
- const [renderStartTier] = useState(() => recommendOpenWorldStartTier({
- coarsePointer: typeof window !== 'undefined'
- && Boolean(window.matchMedia?.('(pointer: coarse)').matches),
- hardwareConcurrency: typeof navigator !== 'undefined' ? navigator.hardwareConcurrency : null,
- deviceMemory: typeof navigator !== 'undefined' ? navigator.deviceMemory : null,
- }));
- const [autoTier, setAutoTier] = useState(renderStartTier);
- const effectiveTier = autoTier;
-
- const sceneSettings = useMemo(() => {
- // Derive render-affecting fields from the adaptive tier. The settings store contains
- // player choices only, so old renderer knobs cannot override the coherent world look.
- const tierCfg = RENDER_TIERS[effectiveTier] || RENDER_TIERS.high;
- return {
- ...settings,
- effectiveTier,
- skyTheme: 'cyberpunk',
- timeOfDay: openWorldTimeOfDay.presetKey,
- particleDensity: tierCfg.particleDensity,
- dpr: tierCfg.dpr,
- ambientBrightness: 1,
- neonBrightness: worldStyle === 'cyber' ? 1.1 : 1,
- };
- }, [settings, effectiveTier, openWorldTimeOfDay.presetKey, worldStyle]);
-
- const [filter, setFilter] = useState(() => {
- // A guarded read is necessary because sessionStorage values are external
- // state: an inaccessible storage or a corrupted/older-schema entry would
- // otherwise throw and crash the page render.
- const parsed = safeReadJsonSession(FILTER_STORAGE_KEY, null);
- if (parsed && typeof parsed.status === 'string') {
- return {
- status: parsed.status,
- search: typeof parsed.search === 'string' ? parsed.search : '',
- };
- }
- return { status: 'all', search: '' };
- });
-
- useEffect(() => {
- // Best-effort — the persisted filter is a UX nicety, not load-bearing state,
- // and setItem throws in Safari private mode / at quota.
- safeWriteJsonSession(FILTER_STORAGE_KEY, filter);
- }, [filter]);
-
- const filterResult = useMemo(
- () => computeFilterResult({ apps, agentMap, status: filter.status, search: filter.search }),
- [apps, agentMap, filter.status, filter.search]
- );
-
- const showSettings = location.pathname === '/openworld/settings';
-
- // Mode precedence (issue #2593): entering exploration/photo/history while a borough is focused
- // clears the focused route first, so the focus camera + detail panel stand down deterministically
- // before the new mode takes the camera. `hasFocus` reads the URL, the single source of truth.
- const clearFocusRoute = useCallback(() => {
- if (hasFocus) navigate('/openworld');
- }, [hasFocus, navigate]);
-
- const handleToggleExploration = useCallback(() => {
- clearFocusRoute();
- updateSetting('explorationMode', !settings?.explorationMode);
- }, [clearFocusRoute, updateSetting, settings?.explorationMode]);
-
- // V (in exploration mode) swaps the follow-camera character view and first person.
- const handleToggleCameraView = useCallback(() => {
- updateSetting('cameraView', (settings?.cameraView ?? 'third') === 'first' ? 'third' : 'first');
- }, [updateSetting, settings?.cameraView]);
-
- const keysRef = useKeyboardControls(handleToggleExploration);
- const mobileInputRef = useRef({
- moveX: 0,
- moveY: 0,
- lookDeltaX: 0,
- lookDeltaY: 0,
- boost: false,
- jump: false,
- });
- const playerActionRef = useRef(null);
- const [proximityTarget, setProximityTarget] = useState(null);
-
- // Cyber Shards collectible state + live player pose
- const [collectedShardIds, setCollectedShardIds] = useState(() => loadCollectedShardIds());
- const [activeBursts, setActiveBursts] = useState([]);
- const [playerPose, setPlayerPose] = useState(null);
- const visibleCollectedCount = useMemo(
- () => visibleCollectibles.filter((shard) => collectedShardIds.has(shard.id)).length,
- [visibleCollectibles, collectedShardIds],
- );
-
- const handleCollectShard = useCallback((shard) => {
- setCollectedShardIds((prev) => {
- const next = new Set(prev);
- next.add(shard.id);
- saveCollectedShardIds(next);
- return next;
- });
- const burstId = `${shard.id}-${Date.now()}`;
- setActiveBursts((prev) => [
- ...prev.slice(-4),
- { id: burstId, x: shard.x, y: shard.y, z: shard.z, color: shard.color, age: 0 },
- ]);
- setTimeout(() => {
- setActiveBursts((prev) => prev.filter((b) => b.id !== burstId));
- }, 850);
- }, []);
-
- // --- World map / fast travel ----------------------------------------------
- // Warping stays under `/openworld/region/:regionId`; the route param drives the orbital
- // camera and, on foot, the player rig. The destination is still shareable, but it never
- // sends the player to the 2D page represented by that district.
- const [fastTravelOpen, setFastTravelOpen] = useState(false);
- // The walking player's arrival point for the latest warp, carrying a monotonic token so
- // PlayerController can tell "warp again to the same place" from a re-render with equal
- // coordinates — which is why it isn't derived from the region id. Direct region deep links
- // seed the first arrival synchronously; later route changes arm the same handoff in an effect.
- // Set on every warp, not only while exploring: PlayerController mounts only in exploration mode
- // and applies the current token on mount, so arming it unconditionally also means warping in the
- // orbital overview and THEN dropping in (Tab) lands you at the region you were looking at,
- // instead of back at your old spawn.
- const [playerTeleport, setPlayerTeleport] = useState(() => {
- if (!focusedRegion) return null;
- const arrival = regionArrivalPoint(focusedRegion);
- return arrival ? { ...arrival, regionId: focusedRegion.id, token: 1 } : null;
- });
- const lastRoutedRegionIdRef = useRef(regionId);
-
- const armPlayerTeleport = useCallback((region, force = false) => {
- const arrival = regionArrivalPoint(region);
- if (!arrival) return;
- setPlayerTeleport(prev => {
- if (!force && prev?.regionId === region.id) return prev;
- return { ...arrival, regionId: region.id, token: (prev?.token ?? 0) + 1 };
- });
- }, []);
-
- useEffect(() => {
- if (!focusedRegion) {
- lastRoutedRegionIdRef.current = regionId;
- return;
- }
- if (lastRoutedRegionIdRef.current === regionId) return;
- lastRoutedRegionIdRef.current = regionId;
- armPlayerTeleport(focusedRegion);
- }, [armPlayerTeleport, focusedRegion, regionId]);
-
- const handleTravelToRegion = useCallback((region) => {
- if (!region?.id) return;
- navigate(regionPath(region.id));
- // A map pick is an explicit warp even when the destination matches the current route (or
- // stale route state), so always re-arm it; browser back/forward and direct deep links are
- // armed by the effect above.
- armPlayerTeleport(region, true);
- playSfx?.('dataPulse');
- }, [armPlayerTeleport, navigate, playSfx]);
-
- const openFastTravel = useCallback(() => setFastTravelOpen(true), []);
-
- // Photo mode (roadmap 3.3): a cinematic capture mode with framing presets and a postcard
- // screenshot. The in-canvas OpenWorldPhotoCamera registers its capture function here via a ref so
- // the overlay (outside the Canvas) can trigger a grab. Exiting photo mode clears the fn.
- const [photoMode, setPhotoMode] = useState(false);
- const [photoPresetId, setPhotoPresetId] = useState(DEFAULT_PRESET_ID);
- // Depth-of-field for cinematic shots (roadmap 3.3) — on by default since it's the point of the
- // mode; the user can toggle it off (D / overlay button) for a fully-sharp frame.
- const [photoDof, setPhotoDof] = useState(true);
- const captureFnRef = useRef(null);
- const handlePhotoCaptureReady = useCallback((fn) => { captureFnRef.current = fn; }, []);
-
- // Playback / "history" mode (roadmap 3.6): scrub recorded city-state snapshots.
- // Transport state lives in the hook; the page swaps the current frame's data
- // into the scene props below. Mutually exclusive with photo mode.
- const playback = useOpenWorldPlayback();
-
- // M opens the fast-travel map. Deliberately open-only, not a toggle: the panel is a
- // <Modal>, which owns Esc/backdrop dismissal — and the shared shortcut hook suppresses
- // itself while any `aria-modal` dialog is up, so a toggle binding could never have
- // fired the close half anyway. The hook also drops ⌘/Ctrl/Alt chords, auto-repeat, and
- // keystrokes typed into a field, so the HUD filter and the panel's own search box keep
- // their letters. Inactive in photo and playback mode: those own the camera and hide the
- // panel, so a live binding there would only bank an "open" that springs the panel the
- // moment the user returns to the live view.
- useKeyboardShortcuts(!photoMode && !playback.active, { m: openFastTravel, M: openFastTravel });
-
- // Entering photo mode leaves exploration + playback; they're mutually exclusive modes.
- const enterPhotoMode = useCallback(() => {
- clearFocusRoute();
- updateSetting('explorationMode', false);
- playback.exit();
- setPhotoPresetId(DEFAULT_PRESET_ID);
- setPhotoMode(true);
- }, [clearFocusRoute, updateSetting, playback]);
- const exitPhotoMode = useCallback(() => setPhotoMode(false), []);
-
- // Entering playback leaves photo + exploration mode.
- const enterPlayback = useCallback(() => {
- clearFocusRoute();
- setPhotoMode(false);
- updateSetting('explorationMode', false);
- playback.enter();
- }, [clearFocusRoute, updateSetting, playback]);
-
- // Esc exits photo mode; ←/→ cycle the framing preset; D toggles depth-of-field. Bound only while
- // photo mode is on so it doesn't shadow other shortcuts. These are ordinary shortcuts, not keys
- // an app-global handler already owns, so they ride useKeyboardShortcuts rather than a capture-phase
- // claim — which also yields them to any dialog opened on top of photo mode.
- useKeyboardShortcuts(photoMode, {
- Escape: () => setPhotoMode(false),
- ArrowLeft: () => setPhotoPresetId(id => cyclePreset(id, -1)),
- ArrowRight: () => setPhotoPresetId(id => cyclePreset(id, 1)),
- d: () => setPhotoDof(v => !v),
- D: () => setPhotoDof(v => !v),
- });
-
- // Playback keyboard transport: Esc exits, Space play/pause, ←/→ step a frame.
- // Bound only while playback is active. Claimed in the capture phase so Space
- // toggles playback WITHOUT also tripping the voice widget's app-global
- // push-to-talk hotkey; keys we do not handle pass through untouched.
- useKeyCapture({
- enabled: playback.active,
- onKeyDown: (e) => {
- if (e.key === 'Escape') playback.exit();
- else if (e.key === ' ') playback.togglePlay();
- else if (e.key === 'ArrowLeft') playback.step(-1);
- else if (e.key === 'ArrowRight') playback.step(1);
- else return false;
- return true;
- },
- });
-
- // Task-complete chime (roadmap 3.4): when a CoS task transitions to completed, play a reward
- // chime. Track the set of completed ids across socket updates and chime on each newly-seen one.
- // Seeded on first populated render (completedSeenRef === null) so a fresh page load doesn't
- // chime for every already-completed task in the backlog.
- const completedSeenRef = useRef(null);
- useEffect(() => {
- const completedIds = (cosTasks || []).filter(t => t?.status === 'completed').map(t => t.id);
- if (completedSeenRef.current === null) {
- completedSeenRef.current = new Set(completedIds);
- return;
- }
- let fired = false;
- for (const id of completedIds) {
- if (!completedSeenRef.current.has(id)) {
- completedSeenRef.current.add(id);
- if (!fired) { playSfx('taskComplete'); fired = true; } // one chime per batch, not per task
- }
- }
- }, [cosTasks, playSfx]);
-
- // Productivity data for HUD vitals and billboards. Let errors throw —
- // `useAutoRefetch` preserves the last-good snapshot on transient failures.
- const { data: productivityData } = useAutoRefetch(
- () => api.getCosQuickSummary({ silent: true }),
- 60_000,
- );
-
- // Activity calendar drives the productivity district's heatmap ground tiles and feeds the
- // task-flow river's throughput signal. Low-frequency: the daily contribution grid changes
- // slowly. Same last-good-snapshot semantics as productivityData.
- const { data: activityCalendar } = useAutoRefetch(
- () => api.getCosActivityCalendar(12, { silent: true }),
- 120_000,
- );
-
- // Life goals drive the goal-monument district. Same pattern as productivityData —
- // `useAutoRefetch` keeps the last-good snapshot on transient failures.
- const { data: goalsData } = useAutoRefetch(
- () => api.getGoals({ silent: true }),
- 120_000,
- );
-
- // Chronotype profile drives the ambient energy overlay — the city brightens during
- // peak focus hours and dims during recovery. Low-frequency: the daily schedule
- // rarely changes. Same last-good-snapshot semantics as the fetches above.
- const { data: chronotypeData } = useAutoRefetch(
- () => api.getChronotype({ silent: true }),
- 600_000,
- );
-
- // Long-term memory graph drives the knowledge district (crystal clusters + light bridges).
- // The graph changes slowly (new memories trickle in), so a 2-minute poll is plenty. Same
- // last-good-snapshot semantics as the fetches above.
- const { data: memoryGraph } = useAutoRefetch(
- () => api.getMemoryGraph({ silent: true }),
- 120_000,
- );
-
- // Brain-inbox backlog feeds the memory district's glowing well — `needs_review` is the count
- // of captures waiting for the user to sort. Lightweight; the well pulses harder as it grows.
- const { data: inboxData } = useAutoRefetch(
- () => api.getBrainInbox({ status: 'needs_review', limit: 1, silent: true }),
- 60_000,
- );
-
- // Storage introspection drives the Data Harbor district (DB table silos + data/ domain
- // racks on the waterfront). Server-side cache does the heavy lifting; a 2-minute poll
- // keeps the harbor current. `compare` strips the always-changing `ts` so a byte-identical
- // payload keeps its identity and the harbor subtree skips reconciliation.
- const { data: introspection } = useAutoRefetch(
- () => api.getOpenWorldIntrospection({ silent: true }),
- 120_000,
- {
- compare: (prev, next) =>
- JSON.stringify({ ...prev, ts: null }) === JSON.stringify({ ...next, ts: null }),
- },
- );
-
- // JIRA sprint district: the set of apps with JIRA wired up (each carries instanceId+projectKey),
- // collapsed to a stable signature that gates and re-triggers the poll only when that set changes.
- const jiraAppsKey = useMemo(
- () => (apps || [])
- .filter(a => a?.jira?.enabled && a.jira.instanceId && a.jira.projectKey)
- .map(a => `${a.jira.instanceId}/${a.jira.projectKey}`)
- .sort().join(','),
- [apps]
- );
- const jiraFeatureEnabled = isPassiveFeatureEnabled('jira');
- // Fetch each enabled app's current-sprint tickets and merge; the helper dedupes by key. Skip
- // the poll entirely when no app has JIRA configured. Keyed on `jiraAppsKey` so the closure (and
- // poll) refresh when JIRA apps appear/disappear.
- const fetchSprintTickets = useCallback(async () => {
- if (!jiraFeatureEnabled) return [];
- const specs = (apps || [])
- .filter(a => a?.jira?.enabled && a.jira.instanceId && a.jira.projectKey)
- .map(a => ({ instanceId: a.jira.instanceId, projectKey: a.jira.projectKey }));
- if (specs.length === 0) return [];
- const batches = await Promise.all(
- specs.map(j => api.getMySprintTickets(j.instanceId, j.projectKey, { silent: true }).catch(() => []))
- );
- return batches.flat();
- }, [apps, jiraFeatureEnabled]);
- const { data: jiraTickets } = useAutoRefetch(
- fetchSprintTickets,
- 120_000,
- { enabled: jiraFeatureEnabled && jiraAppsKey.length > 0 },
- );
-
- // Selecting a building focuses it in-place (issue #2593) — the URL becomes /openworld/apps/:id and the
- // camera/HUD stay inside OpenWorld. This is also the interaction target for the first-person player:
- // walking up to a building and pressing F opens its live status panel, never the 2D app page.
- const handleBuildingClick = useCallback((app) => {
- if (!app?.id) return;
- navigate(`/openworld/apps/${app.id}`);
- }, [navigate]);
-
- const handleJumpToFirst = useCallback(() => {
- const first = filterResult.matches[0];
- if (!first?.id) return;
- handleBuildingClick(first);
- }, [filterResult.matches, handleBuildingClick]);
-
- const handleTravelToRegionId = useCallback((id) => {
- const region = getRegion(id);
- if (region) handleTravelToRegion(region);
- }, [handleTravelToRegion]);
-
- // Every HUD attention item resolves to a building/region in the world. There is no external
- // page fallback: an item without a more specific destination opens the world map instead.
- const handleAttentionItem = useCallback((item) => {
- if (item?.appId) {
- handleBuildingClick({ id: item.appId });
- return;
- }
- if (item?.regionId) {
- handleTravelToRegionId(item.regionId);
- return;
- }
- openFastTravel();
- }, [handleBuildingClick, handleTravelToRegionId, openFastTravel]);
-
- // Close focus → back to the plain in-world overview. The panel's primary action also
- // re-focuses the building in OpenWorld rather than opening a separate PortOS page.
- const handleCloseFocus = useCallback(() => navigate('/openworld'), [navigate]);
- const handleFocusInWorld = useCallback((id) => {
- if (id) handleBuildingClick({ id });
- }, [handleBuildingClick]);
-
- // Headline numbers baked onto a captured city postcard. Derived from data the page already
- // has — no extra fetch. buildPostcardStats (in the overlay) omits absent/zero fields.
- const photoStats = useMemo(() => {
- const active = (apps || []).filter(a => !a.archived);
- return {
- online: active.filter(a => a.overallStatus === 'online').length,
- total: active.length,
- agents: (cosAgents || []).filter(a => a.status === 'running' || a.state === 'coding' || a.state === 'thinking').length,
- peers: (instances?.peers || []).filter(p => p.status === 'online').length,
- level: character?.level,
- };
- }, [apps, cosAgents, instances, character]);
-
- // In playback mode, overlay the current snapshot frame's data onto the props
- // the scene consumes. mergeFrameIntoOpenWorldProps returns ONLY the props the frame
- // can faithfully drive (apps, agentMap, cosStatus, backupStatus, character),
- // so anything it omits (the count-only and rich-array landmarks: task queue,
- // federation, health tower, memory, goals, jira, activity, productivity) keeps
- // its live value — the "freeze unfed landmarks at live" behavior; their
- // captured numbers show in the playback overlay instead. Returns null for an
- // unplayable frame → keep live.
- const playbackProps = useMemo(() => {
- if (!playback.active || !playback.currentFrame) return null;
- return mergeFrameIntoOpenWorldProps(playback.currentFrame, { apps, agentMap });
- }, [playback.active, playback.currentFrame, apps, agentMap]);
-
- const v = useCallback((key, live) => (playbackProps && key in playbackProps ? playbackProps[key] : live), [playbackProps]);
-
- // Keep the scene and app shell mounted while the initial data bundle arrives. The route's
- // Suspense boundary already covers the lazy OpenWorld chunk; replacing the entire page here
- // created a second full-screen loader after the first one, then remounted WebGL once the API
- // calls settled. Empty/default props are safe for every landmark, and OpenWorldScene's own
- // warm-up keeps the first data-driven layout cheap while the real values stream in.
-
- return (
- <OpenWorldPaletteProvider palette={openWorldPalette}>
- <div
- className={`${settings?.explorationMode ? 'fixed inset-0 z-[90]' : 'relative w-full h-full'} openworld-themed`}
- style={{ background: sceneBackground, isolation: 'isolate' }}
- >
- <OpenWorldScene
- // A theme switch recolors the live scene in place — NO full-scene remount.
- // Every themed surface either reads the palette fresh each render (declarative
- // `color=` props, palette helper fns) or carries the palette value in its
- // useMemo deps so it rebuilds on a new palette object (WorldGround, OpenWorldLandscape,
- // OpenWorldTraffic, OpenWorldNeonSigns, …). The two persistent GPU shader materials whose
- // uniforms are set once at construction (OpenWorldBillboards scan overlay,
- // OpenWorldVolumetricLights cones) push the new accent into their uColor uniform
- // imperatively, mirroring OpenWorldSky's per-frame uniform updates. Dropping the old
- // `key={openWorldPalette.themeId}` avoids the jarring full-scene rebuild flash.
- palette={openWorldPalette}
- background={sceneBackground}
- apps={v('apps', apps)}
- agentMap={v('agentMap', agentMap)}
- onBuildingClick={handleBuildingClick}
- onToggleCameraView={handleToggleCameraView}
- cosStatus={v('cosStatus', cosStatus)}
- reviewCounts={reviewCounts}
- instances={instances}
- backupStatus={v('backupStatus', backupStatus)}
- cosTasks={cosTasks}
- healthMetrics={healthMetrics}
- voiceState={voiceState}
- aiActivity={aiActivity}
- productivityData={productivityData}
- activityCalendar={activityCalendar}
- goals={goalsData}
- character={v('character', character)}
- chronotype={chronotypeData}
- memoryGraph={memoryGraph}
- inboxDepth={inboxData?.counts?.needs_review ?? 0}
- jiraTickets={jiraTickets}
- introspection={introspection}
- playback={playback.active}
- photoMode={photoMode}
- photoPresetId={photoPresetId}
- photoDof={photoDof}
- onPhotoCaptureReady={handlePhotoCaptureReady}
- settings={sceneSettings}
- playSfx={playSfx}
- keysRef={keysRef}
- mobileInputRef={mobileInputRef}
- playerActionRef={playerActionRef}
- dimmedAppIds={filterResult.dimmed}
- autoQuality
- autoStartTier={renderStartTier}
- autoResetToken={resetNonce}
- onAutoTierChange={setAutoTier}
- focusedAppId={appId || null}
- focusedRegion={focusedRegion}
- isFeatureEnabled={isFeatureEnabled}
- isPassiveFeatureEnabled={isPassiveFeatureEnabled}
- playerTeleport={playerTeleport}
- hudSafe={focusHudSafe}
- onTravelToRegion={handleTravelToRegion}
- onProximityChange={setProximityTarget}
- collectedShardIds={collectedShardIds}
- onCollectShard={handleCollectShard}
- activeBursts={activeBursts}
- onPlayerPoseChange={setPlayerPose}
- />
- {/* The full HUD hides in photo + playback mode so the view is clean; each
- mode's overlay replaces it. */}
- {!photoMode && !playback.active && (
- <OpenWorldHud
- cosStatus={cosStatus}
- cosAgents={cosAgents}
- agentMap={agentMap}
- eventLogs={eventLogs}
- connected={connected}
- apps={apps}
- reviewCounts={reviewCounts}
- instances={instances}
- productivityData={productivityData}
- systemHealth={systemHealth}
- notificationCounts={notificationCounts}
- character={character}
- filter={filter}
- onFilterChange={setFilter}
- onJumpToFirst={handleJumpToFirst}
- matchCount={filterResult.matches.length}
- onToggleExploration={handleToggleExploration}
- explorationMode={settings?.explorationMode}
- onSelectApp={handleBuildingClick}
- onEnterPhotoMode={enterPhotoMode}
- onEnterPlayback={enterPlayback}
- focusedAppId={appId || null}
- focusedApp={focusedApp}
- focusNotFound={focusNotFound}
- focusAgents={focusAgents}
- onCloseFocus={handleCloseFocus}
- onFocusInWorld={handleFocusInWorld}
- onOpenFastTravel={openFastTravel}
- onOpenDestination={handleTravelToRegionId}
- onAttentionItem={handleAttentionItem}
- activeRegion={focusedRegion}
- proximityTarget={proximityTarget}
- playerPose={playerPose}
- collectedCount={visibleCollectedCount}
- totalShards={visibleCollectibles.length}
- />
- )}
- {!photoMode && !playback.active && !isDesktop && settings?.explorationMode && !showSettings && !fastTravelOpen && (
- <OpenWorldMobileControls
- mobileInputRef={mobileInputRef}
- playerActionRef={playerActionRef}
- />
- )}
- <OpenWorldPhotoOverlay
- active={photoMode}
- presetId={photoPresetId}
- onPresetChange={setPhotoPresetId}
- onExit={exitPhotoMode}
- captureFnRef={captureFnRef}
- statsSnapshot={photoStats}
- dofEnabled={photoDof}
- onToggleDof={() => setPhotoDof(v => !v)}
- />
- <OpenWorldPlaybackOverlay
- active={playback.active}
- loading={playback.loading}
- error={playback.error}
- snapshots={playback.snapshots}
- frameIndex={playback.frameIndex}
- currentFrame={playback.currentFrame}
- stats={playback.stats}
- playing={playback.playing}
- speed={playback.speed}
- onSeek={playback.seek}
- onStep={playback.step}
- onTogglePlay={playback.togglePlay}
- onCycleSpeed={playback.cycleSpeed}
- onExit={playback.exit}
- />
- {/* World map (M). Hidden in photo + playback mode, which own the camera and would
- fight a warp. Mounted OUTSIDE the HUD's pointer-events-none shell so it can take
- clicks, and above the CRT overlay so its panel isn't scanlined. */}
- <OpenWorldFastTravel
- open={fastTravelOpen && !photoMode && !playback.active}
- onClose={() => setFastTravelOpen(false)}
- onTravel={handleTravelToRegion}
- activeRegionId={focusedRegion?.id || null}
- onLeaveRegion={() => navigate('/openworld')}
- isFeatureEnabled={isFeatureEnabled}
- />
- {/* Settings on the shared Drawer. Closing preserves other query params (e.g. an open
- openWorldPane) so the disclosure state survives. Rendering quality is automatic and
- intentionally absent from this player-facing surface. */}
- <OpenWorldSettingsDrawer
- open={showSettings}
- onClose={() => navigate(`/openworld${location.search}`)}
- />
- </div>
- </OpenWorldPaletteProvider>
- );
-}
-
-export default function OpenWorld() {
- return (
- <OpenWorldSettingsProvider>
- <OpenWorldInner />
- </OpenWorldSettingsProvider>
- );
-}
diff --git a/client/src/pages/OpenWorld.transport.test.jsx b/client/src/pages/OpenWorld.transport.test.jsx
deleted file mode 100644
index e6cd755bd8..0000000000
--- a/client/src/pages/OpenWorld.transport.test.jsx
+++ /dev/null
@@ -1,190 +0,0 @@
-import { describe, it, expect, beforeEach, vi } from 'vitest';
-import { render, screen, fireEvent, act } from '@testing-library/react';
-import { MemoryRouter, Routes, Route } from 'react-router';
-import { installVoiceHotkeySpy } from '../test/voiceHotkeySpy';
-
-// Same stubbing strategy as OpenWorld.fastTravel.test.jsx: the 3D scene and the HUD are
-// replaced with inert divs so the page's keyboard WIRING can be exercised in jsdom.
-vi.mock('../components/openworld/OpenWorldScene', () => ({ default: () => <div data-testid="scene" /> }));
-vi.mock('../components/openworld/OpenWorldHud', () => ({
- default: ({ onEnterPhotoMode }) => (
- <button type="button" onClick={onEnterPhotoMode}>hud-photo</button>
- ),
-}));
-// Photo mode has no other observable surface once the overlay is stubbed, so the stub
-// records the props the page drives from its keyboard shortcuts.
-vi.mock('../components/openworld/OpenWorldPhotoOverlay', () => ({
- default: (props) => { photoProps.current = props; return null; },
-}));
-vi.mock('../components/openworld/OpenWorldPlaybackOverlay', () => ({ default: () => null }));
-vi.mock('../components/openworld/OpenWorldSettingsDrawer', () => ({ default: () => null }));
-
-vi.mock('../hooks/useOpenWorldData', async () => {
- const { OPEN_WORLD_DATA } = await import('../test/openWorldPageMocks.js');
- return { useOpenWorldData: () => OPEN_WORLD_DATA };
-});
-
-// The playback hook is the surface under test: the page binds its transport keys only
-// while `active`, and the spies below record what each key reached.
-const photoProps = vi.hoisted(() => ({ current: null }));
-const playback = vi.hoisted(() => ({
- active: true, currentFrame: null, snapshots: [], frameIndex: 0, stats: null,
- playing: false, speed: 1, loading: false, error: null,
- enter: vi.fn(), exit: vi.fn(), seek: vi.fn(), step: vi.fn(),
- togglePlay: vi.fn(), cycleSpeed: vi.fn(),
-}));
-vi.mock('../hooks/useOpenWorldPlayback', () => ({ useOpenWorldPlayback: () => playback }));
-vi.mock('../hooks/useOpenWorldAudio', () => ({ default: () => ({ playSfx: vi.fn(), isAudioReady: false }) }));
-vi.mock('../hooks/useAutoRefetch', () => ({ useAutoRefetch: () => ({ data: null }) }));
-vi.mock('../hooks/useInstanceFeatures', () => ({
- useInstanceFeatures: () => ({
- features: [],
- error: null,
- isFeatureEnabled: () => true,
- reload: () => Promise.resolve(),
- }),
-}));
-// Only the endpoints this page polls, from the shared page fixture. The vi.mock
-// CALL has to stay here (vitest hoists it), so the factory dynamic-imports it.
-vi.mock('../services/api', async () => (await import('../test/openWorldPageMocks.js')).openWorldApiMock(vi));
-
-const OpenWorld = (await import('./OpenWorld')).default;
-
-const renderPage = () => render(
- <MemoryRouter initialEntries={['/openworld']}>
- <Routes><Route path="/openworld" element={<OpenWorld />} /></Routes>
- </MemoryRouter>
-);
-
-describe('OpenWorld playback transport keys', () => {
- const voiceHotkey = installVoiceHotkeySpy();
-
- beforeEach(() => {
- playback.active = true;
- playback.exit.mockClear();
- playback.step.mockClear();
- playback.togglePlay.mockClear();
- localStorage.clear();
- });
-
- it('toggles play on Space without leaking the key to the global voice hotkey', () => {
- renderPage();
-
- act(() => { fireEvent.keyDown(document.body, { key: ' ', code: 'Space' }); });
-
- expect(playback.togglePlay).toHaveBeenCalledTimes(1);
- expect(voiceHotkey()).not.toHaveBeenCalled();
- });
-
- it('claims Escape and the arrow keys too', () => {
- renderPage();
-
- act(() => { fireEvent.keyDown(document.body, { key: 'ArrowLeft' }); });
- act(() => { fireEvent.keyDown(document.body, { key: 'ArrowRight' }); });
- act(() => { fireEvent.keyDown(document.body, { key: 'Escape' }); });
-
- expect(playback.step.mock.calls).toEqual([[-1], [1]]);
- expect(playback.exit).toHaveBeenCalledTimes(1);
- expect(voiceHotkey()).not.toHaveBeenCalled();
- });
-
- it('lets unhandled keys through to app-global listeners', () => {
- renderPage();
-
- act(() => { fireEvent.keyDown(document.body, { key: 'j' }); });
-
- expect(voiceHotkey()).toHaveBeenCalledTimes(1);
- expect(playback.togglePlay).not.toHaveBeenCalled();
- });
-
- it('ignores Space typed into a text field, leaving the transport alone', () => {
- const { container } = renderPage();
- const input = document.createElement('input');
- container.appendChild(input);
- input.focus();
-
- act(() => { fireEvent.keyDown(input, { key: ' ', code: 'Space' }); });
-
- expect(playback.togglePlay).not.toHaveBeenCalled();
- });
-
- it('yields the transport keys to an open dialog layer', () => {
- // The settings drawer renders aria-modal and closes on its own Escape handler; the
- // transport must not swallow that keystroke out from under it (useKeyCapture's
- // enabledInDialog default).
- const { container } = renderPage();
- const drawer = document.createElement('div');
- drawer.setAttribute('aria-modal', 'true');
- container.appendChild(drawer);
-
- act(() => { fireEvent.keyDown(document.body, { key: 'Escape' }); });
- act(() => { fireEvent.keyDown(document.body, { key: ' ', code: 'Space' }); });
-
- expect(playback.exit).not.toHaveBeenCalled();
- expect(playback.togglePlay).not.toHaveBeenCalled();
- expect(voiceHotkey()).toHaveBeenCalledTimes(2);
- });
-
- it('binds nothing while playback is inactive', () => {
- playback.active = false;
- renderPage();
-
- act(() => { fireEvent.keyDown(document.body, { key: ' ', code: 'Space' }); });
-
- expect(playback.togglePlay).not.toHaveBeenCalled();
- expect(voiceHotkey()).toHaveBeenCalledTimes(1);
- });
-});
-
-describe('OpenWorld photo mode shortcuts', () => {
- const voiceHotkey = installVoiceHotkeySpy();
-
- beforeEach(() => {
- playback.active = false;
- photoProps.current = null;
- localStorage.clear();
- });
-
- const enterPhotoMode = () => {
- const rendered = renderPage();
- fireEvent.click(screen.getByText('hud-photo'));
- return rendered;
- };
-
- it('cycles the framing preset and toggles depth of field', () => {
- enterPhotoMode();
- expect(photoProps.current.active).toBe(true);
- const first = photoProps.current.presetId;
- expect(photoProps.current.dofEnabled).toBe(true);
-
- act(() => { fireEvent.keyDown(document.body, { key: 'ArrowRight' }); });
- expect(photoProps.current.presetId).not.toBe(first);
-
- act(() => { fireEvent.keyDown(document.body, { key: 'ArrowLeft' }); });
- expect(photoProps.current.presetId).toBe(first);
-
- act(() => { fireEvent.keyDown(document.body, { key: 'd' }); });
- expect(photoProps.current.dofEnabled).toBe(false);
- });
-
- it('exits on Escape', () => {
- enterPhotoMode();
-
- act(() => { fireEvent.keyDown(document.body, { key: 'Escape' }); });
-
- expect(photoProps.current.active).toBe(false);
- });
-
- it('leaves its keys for an open dialog, and does not claim them from the app', () => {
- const { container } = enterPhotoMode();
- const dialog = document.createElement('div');
- dialog.setAttribute('aria-modal', 'true');
- container.appendChild(dialog);
-
- act(() => { fireEvent.keyDown(document.body, { key: 'Escape' }); });
-
- expect(photoProps.current.active).toBe(true);
- // Bubble-phase shortcuts, not a capture-phase claim: the app still sees the key.
- expect(voiceHotkey()).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 2ed0d3c7ff..4aa6e61edb 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -136,7 +136,6 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiOpenClaw.js` | File browser / picker backend. |
| `apiPalette.js` | Command-palette manifest + action dispatch. |
| `apiVoice.js` | Voice synthesis / processing. |
-| `apiOpenWorld.js` | OpenWorld snapshots — historical world-state series for the timeline scrubber (GET /snapshots) plus introspection. |
| `apiPrivacy.js` | Privacy Center — encrypted PII Vault + Trusted Organizations registry (status, vault CRUD + reveal, org CRUD, org holdings replace-set) + Digital Twin social-account cross-link + household subjects (subject CRUD, consent audit, and a `subjectId` scope passed in each wrapper's trailing `options`). |
## Browser-facing (DOM, voice, build) — not pure API wrappers
diff --git a/client/src/services/api.js b/client/src/services/api.js
index efefc3a7f5..077729f47a 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -84,7 +84,6 @@ export * from './apiImporter.js';
export * from './apiStoryBuilder.js';
export * from './apiVoice.js';
export * from './apiAuth.js';
-export * from './apiOpenWorld.js';
export * from './apiPrivacy.js';
export * from './apiQuotaBurn.js';
export * from './apiRapidReader.js';
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index fdd0f329a9..044d691282 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -1,7 +1,7 @@
import { request } from './apiCore.js';
// Running Agents (Process Management)
-export const getRunningAgents = (options) => request('/agents', options);
+const getRunningAgents = (options) => request('/agents', options);
const killRunningAgent = (pid) => request(`/agents/${pid}`, { method: 'DELETE' });
// Legacy aliases
export const getAgents = getRunningAgents;
diff --git a/client/src/services/apiOpenWorld.js b/client/src/services/apiOpenWorld.js
deleted file mode 100644
index 0128a1596f..0000000000
--- a/client/src/services/apiOpenWorld.js
+++ /dev/null
@@ -1,20 +0,0 @@
-import { request } from './apiCore.js';
-
-// OpenWorld snapshots — historical world-state series for the timeline scrubber.
-// The capture pipeline (issue #877) records frames server-side; these read them.
-
-// GET /api/openworld/snapshots — the recorded series, oldest-first.
-// options: { since?: ISO string, limit?: number, silent?: boolean }
-export const getOpenWorldSnapshots = (options = {}) => {
- const { since, limit, ...rest } = options;
- const params = new URLSearchParams();
- if (since) params.set('since', since);
- if (limit != null) params.set('limit', limit);
- const qs = params.toString();
- return request(`/openworld/snapshots${qs ? `?${qs}` : ''}`, rest);
-};
-
-// GET /api/openworld/introspection — DB tables + data/ domain sizes for the Data
-// Harbor district. Server-cached; `db: null` means the database is unreachable.
-export const getOpenWorldIntrospection = (options = {}) =>
- request('/openworld/introspection', options);
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index e7347c8dec..d870ba918e 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -4,24 +4,6 @@ import { downloadBlob } from '../lib/downloadBlob.js';
// Alerts
export const getAlertsSummary = (options) => request('/alerts/summary', options);
-// Character sheet (age-based level / XP / HP / usage-derived skills + metrics grid).
-// `skills: false` / `metrics: false` skip the server's domain stat fan-out for each derived
-// registry — pass them from callers that only read the persisted fields or the level (e.g.
-// the polling OpenWorld XP HUD badge). Both default on, so a caller that wants the whole
-// sheet just calls getCharacter().
-export const getCharacter = ({ skills = true, metrics = true, ...options } = {}) => {
- const params = new URLSearchParams();
- if (!skills) params.set('skills', '0');
- if (!metrics) params.set('metrics', '0');
- // `metrics=1` must go on the wire EXPLICITLY when skills are off, because the server infers
- // an absent `metrics` from `skills` (back-compat: a bare `?skills=0` predates the metrics
- // grid and means "cheap sheet"). Without this, `{ skills: false }` would silently drop the
- // metrics this wrapper's own default promises.
- else if (!skills) params.set('metrics', '1');
- const query = params.toString();
- return request(`/character${query ? `?${query}` : ''}`, options);
-};
-
// Health
export const checkHealth = (options) => request('/system/health', options);
export const getSystemHealth = (options) => request('/system/health/details', options);
diff --git a/client/src/services/apiSystem.test.js b/client/src/services/apiSystem.test.js
index 3f73059133..d777b05877 100644
--- a/client/src/services/apiSystem.test.js
+++ b/client/src/services/apiSystem.test.js
@@ -6,12 +6,11 @@ vi.mock('./apiCore.js', () => ({
let request;
let patchSettingsSlice;
-let getCharacter;
beforeEach(async () => {
vi.resetModules();
({ request } = await import('./apiCore.js'));
- ({ patchSettingsSlice, getCharacter } = await import('./apiSystem.js'));
+ ({ patchSettingsSlice } = await import('./apiSystem.js'));
request.mockReset();
});
@@ -139,38 +138,4 @@ describe('patchSettingsSlice', () => {
});
});
-// The character query builder encodes a non-obvious server rule: an ABSENT `metrics` is
-// inferred from `skills` (back-compat — a bare `?skills=0` predates the metrics grid and has
-// only ever meant "cheap sheet"). So this wrapper must put `metrics` on the wire explicitly
-// whenever inference would contradict its own documented defaults.
-describe('getCharacter query building (#2676)', () => {
- const pathOf = () => request.mock.calls[0][0];
-
- it('sends no query at all when the caller wants the whole sheet', () => {
- getCharacter();
- expect(pathOf()).toBe('/character');
- });
-
- it('sends both flags off for the cheap path', () => {
- getCharacter({ skills: false, metrics: false });
- expect(pathOf()).toBe('/character?skills=0&metrics=0');
- });
-
- it('sends metrics=1 explicitly when skills are off but metrics are wanted', () => {
- // Without the explicit `1` the server would infer metrics=false from `skills=0` and
- // silently drop the metrics this wrapper's `metrics = true` default promises.
- getCharacter({ skills: false });
- expect(pathOf()).toBe('/character?skills=0&metrics=1');
- });
-
- it('sends only metrics=0 when metrics alone are declined', () => {
- getCharacter({ metrics: false });
- expect(pathOf()).toBe('/character?metrics=0');
- });
-
- it('forwards request options without leaking the flags into them', () => {
- getCharacter({ skills: false, metrics: false, silent: true });
- expect(request.mock.calls[0][1]).toEqual({ silent: true });
- });
-});
// @vitest-environment node
diff --git a/client/src/test/openWorldPageMocks.js b/client/src/test/openWorldPageMocks.js
deleted file mode 100644
index 0babb2f453..0000000000
--- a/client/src/test/openWorldPageMocks.js
+++ /dev/null
@@ -1,96 +0,0 @@
-/**
- * Shared fixture payloads for the `OpenWorld` PAGE suites (transport, fast
- * travel, and whatever comes next). Each of those suites stubs the same 3D
- * scene, the same data hook, and the same nine API endpoints purely to get the
- * page mountable in jsdom — none of it is what any of them is testing, and a
- * new endpoint the page starts polling otherwise has to be added to every copy.
- *
- * The `vi.mock` CALLS must stay in each test file: vitest hoists them above the
- * imports, so a factory defined here can only be reached by `await import`ing
- * this module INSIDE the factory —
- *
- * vi.mock('../hooks/useOpenWorldData', async () => ({
- * useOpenWorldData: () => (await import('../test/openWorldPageMocks.js')).OPEN_WORLD_DATA,
- * }));
- *
- * — which is why these are plain exported values rather than a helper that
- * registers the mocks for you.
- *
- * Anything a suite ASSERTS on stays in that suite: the scene/HUD stubs that
- * record props, the playback spies, the per-test payload overrides.
- */
-
-/**
- * The `useOpenWorldData` return shape, with every field empty. A suite that
- * needs one field populated spreads this and overrides that field.
- */
-export const OPEN_WORLD_DATA = {
- apps: [],
- cosAgents: [],
- cosStatus: {},
- eventLogs: [],
- agentMap: new Map(),
- reviewCounts: {},
- instances: {},
- systemHealth: null,
- notificationCounts: {},
- backupStatus: null,
- cosTasks: [],
- healthMetrics: null,
- voiceState: null,
- character: null,
- aiActivity: null,
- loading: false,
- connected: true,
-};
-
-/**
- * Build the `services/api` stub — only the endpoints the page polls. The real
- * module pulls in the socket client, which has no place in a jsdom page test;
- * `useAutoRefetch` is stubbed alongside it, so none of these actually fire.
- *
- * Takes `vi` as an argument because a `vi.mock` factory runs before this
- * module's own imports would resolve.
- *
- * @param {typeof import('vitest').vi} vi
- */
-export function openWorldApiMock(vi) {
- return {
- getInstanceFeatures: vi.fn(async () => ({ features: [] })),
- getCosQuickSummary: vi.fn(async () => null),
- getCosActivityCalendar: vi.fn(async () => null),
- getGoals: vi.fn(async () => null),
- getChronotype: vi.fn(async () => null),
- getMemoryGraph: vi.fn(async () => null),
- getBrainInbox: vi.fn(async () => null),
- getOpenWorldIntrospection: vi.fn(async () => null),
- getMySprintTickets: vi.fn(async () => []),
- };
-}
-
-/**
- * The `useOpenWorldPlayback` return shape with playback INACTIVE — what a suite
- * that isn't testing the transport wants. Spies are built per call so two
- * suites never share call history.
- *
- * @param {typeof import('vitest').vi} vi
- */
-export function openWorldPlaybackMock(vi) {
- return {
- active: false,
- currentFrame: null,
- snapshots: [],
- frameIndex: 0,
- stats: null,
- playing: false,
- speed: 1,
- loading: false,
- error: null,
- enter: vi.fn(),
- exit: vi.fn(),
- seek: vi.fn(),
- step: vi.fn(),
- togglePlay: vi.fn(),
- cycleSpeed: vi.fn(),
- };
-}
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index 56b6d6c667..fc60714ba3 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -37,6 +37,7 @@ grep -i "what you want to do" client/src/utils/README.md
| `easing` | Interpolation easing curves — `linear`, `easeIn`, `easeOut`, `smoothstep` (ease in/out), plus the `EASING_CURVES` map keyed by the declarative Three.js clip contract's easing enum. Extend here rather than re-defining an easing inline. |
| `hashString` | Deterministic string → 32-bit hash (stable colors, keys, seeds). |
| `modelFit` | `fitModelToHeight(object, { targetHeight, feetOnGround, yOffset })` — normalize a loaded GLB to a fixed on-screen height and anchor it vertically, either by bounding-box center (portrait framing) or by its lowest point (a figure standing on a ground plane). Recenters x/z, guards a zero-height model against an infinite scale, leaves a geometry-less object or a non-finite `targetHeight` untouched rather than writing `NaN`/`Infinity` through the transform, and resets to identity before measuring so a repeat call (StrictMode's double mount effect) converges instead of blowing the model back up. Call from an effect, never during render — a skinned mesh measures wrong before `useAnimations` binds the skeleton. |
+| `renderBudget` | Pure adaptive render-quality state machine: capability-aware startup tier (`recommendStartTier`), p75 frame-time windows, hysteresis, cooldown, warm-up/gap rejection (`createRenderBudget`, `recordFrame`, `restartWarmup`, `resetRenderBudget`, `getEffectiveTier`, `QUALITY_TIERS`, `DEFAULT_RENDER_BUDGET_CONFIG`). |
| `sleep` | `sleep(ms)` — promise-returning `setTimeout` for retry backoffs and race timeouts. Use instead of re-declaring a local `delay`. |
| `urlNormalize` | `isUrl` detection, `normalizeUrl` (optional git/`requireDot` modes), `isHttpUrl` / `isHttpsUrl` (safe-href checks), and `tiktokVideoId` / `tiktokEmbedSrc` (host-anchored TikTok video-id extraction + its Embed Player URL, so a reference embeds without loading TikTok's embed.js). |
| `platform` | `isMac` detection and `modKey` (⌘/Ctrl) for keyboard-shortcut display. |
@@ -62,49 +63,4 @@ grep -i "what you want to do" client/src/utils/README.md
| Module | Purpose |
|---|---|
-| `characterXp` | Character HUD badge math: `computeAgeView` (age-based level + progress to next birthday), `diffXp` (XP-gain / birthday burst diff), `birthDateCta` (missing-birth-date call to action), plus the legacy `levelFromXP` XP-curve lookup used by `openWorldArtifacts`. |
-
-## OpenWorld — scene compute helpers
-
-Pure `compute*` functions that turn PortOS state into 3D-scene descriptors for the OpenWorld
-districts. One module per district/feature; each exports a `compute<Feature>` entry point plus
-its tunable constants and placement helpers.
-
-| Module | Purpose |
-|---|---|
-| `openWorldActivityHeatmap` | Calendar activity → per-tile heat levels (`computeActivityHeatmap`, `tileLevel`). |
-| `openWorldAgentMotion` | Agent orbit/trail motion math (`computeAgentOrbit`, `computeAgentTrailPoints`, trail colors). |
-| `openWorldAiCore` | AI-ops core: model tiers, beam thickness, and `computeAiCore` / `computeAiCoreBeams` from live AI status events. |
-| `openWorldAppMetrics` | Per-building live telemetry: aggregate an app's `pm2Status` CPU/memory/uptime/restarts into one snapshot (`computeAppMetrics`, `cpuTone`, `hasPm2Error`, `buildingSignalTone` — façade LED / rooftop stress flags). |
-| `openWorldArtifacts` | Earned-artifact milestones (level/goal) → placed artifact descriptors (`computeArtifacts`). |
-| `openWorldBackupVault` | Backup-vault health/alerting state and color (`computeBackupVault`, `vaultHealth`). |
-| `openWorldChronotype` | Chronotype energy curve by hour → brightness/tempo modifiers (`computeChronotypeEnergy`). |
-| `openWorldCollectibles` | Deterministic Cyber Shards collectible placement, collection overlap math, and progress tracking (`getCollectiblesList`, `checkShardCollection`, `getCollectionStats`, `CYBER_SHARDS`). |
-| `openWorldDataHarbor` | Data Harbor pier district: DB table silos + data/ domain racks from /api/openworld/introspection (`computeDataHarbor`). |
-| `openWorldDistrictLayout` | Shared district layout math: auto-columns, grid placement, tallying, metric→height scaling. |
-| `openWorldEasterEggs` | Unlockable easter eggs from context (date/character/goals) → placements (`computeEasterEggs`). |
-| `openWorldFederation` | Sync-peer reachability horizon: status color/opacity, bridge state, peer placement (`computeFederationHorizon`). |
-| `openWorldFilter` | Status-filter definitions and app-filtering result (`computeFilterResult`). |
-| `openWorldFocusCamera` | Pure camera-framing math for OpenWorld's camera targets: orbital `position`/`target` framing one borough (`computeFocusCamera`) or a whole fast-travel region (`computeRegionCamera`) for a given aspect ratio + HUD safe area. |
-| `openWorldFocusState` | Resolve the `/openworld/apps/:appId` route param + app list into `{ hasFocus, focusedApp, notFound }`, deferring the not-found flag until apps finish loading (`resolveOpenWorldFocus`). |
-| `openWorldFlowLines` | Inter-building flow-line connections between active/agent nodes (`computeFlowConnections`). |
-| `openWorldGoalMonuments` | Goal monuments & forest: stall detection, milestone segments, placement (`computeGoalMonuments`, `computeGoalForest`). |
-| `openWorldHealthTower` | Health-metric tower segments from the latest health entry (`computeHealthTower`). |
-| `openWorldInteriorWindows` | Per-building interior-mapping window grid + selection predicate for InteriorMappingMaterial panes (`computeWindowGrid`, `buildingHasInteriorWindows`, `INTERIOR_WINDOW`). |
-| `openWorldJiraDistrict` | Jira ticket district: ticket state, sprint structures, placement (`computeJiraDistrict`). |
-| `openWorldMemoryDistrict` | Brain-graph memory district: category clustering, bridges, placement (`computeMemoryDistrict`). |
-| `openWorldMiniMap` | Mini-map projection of building positions into 2D bounds, plus opt-in waterfront geography (bay/shoreline/harbor) read from `openWorldPlan` (`computeMiniMap`, `projectPoint`, `geographyWorldPoints`, `projectGeography`). |
-| `openWorldPhotoMode` | Photo-mode camera presets, the demand-loop fly stepper, postcard stats, and screenshot filename (`getPreset`, `cyclePreset`, `stepFly`). |
-| `openWorldPlan` | Master town plan: district parcels, shoreline/bay, plaza, transit loop, street network (`PARCELS`, `WORLD`, `computeStreets`, `computeStreetProps`, `isInWater`). |
-| `openWorldProximity` | Unified player proximity detection across warp pads, buildings, easter eggs, and district landmarks (`detectProximity`, `getResolvedLandmarks`, `WORLD_LANDMARKS`). |
-| `openWorldRegions` | OpenWorld fast-travel registry: named regions over the `openWorldPlan` parcels, each mapped to the PortOS page it visualizes (`OPEN_WORLD_REGIONS`, `getRegion`, `listRegions`, `searchRegions`, `regionArrivalPoint`, `regionPath`). |
-| `openWorldPlayerRig` | Exploration player-rig math: third-person follow camera, boom collision, damping, facing, avatar state (`thirdPersonCamera`, `resolveBoom`, `dampAngle`, `moveFacing`, `avatarState`). |
-| `openWorldRenderBudget` | Pure Auto-quality render-budget state machine: capability-aware startup tier (`recommendOpenWorldStartTier`), p75 frame-time windows, hysteresis, cooldown, warm-up/gap rejection (`createRenderBudget`, `recordFrame`, `restartWarmup`, `resetRenderBudget`, `getEffectiveTier`, `QUALITY_TIERS`, `DEFAULT_RENDER_BUDGET_CONFIG`). |
-| `openWorldRooftops` | Deterministic rooftop fixture kits (antenna/tank/AC/dish) per app name (`computeRooftopKit`). |
-| `openWorldProductivity` | Productivity monument from same-day throughput and velocity tiers (`computeProductivityMonument`). |
-| `openWorldSoundscape` | Ambient soundscape: mood/energy classification, chord selection (`computeSoundscape`), and the manual mood override (`applyMoodOverride`). |
-| `openWorldSpeedPads` | Luminous road speed boost pads placement and geometric local-coordinate overlap detection (`getSpeedPadsList`, `checkSpeedPadOverlap`, `SPEED_PADS`). |
-| `openWorldTaskFlowRiver` | Task-flow river width/speed from backlog & throughput (`computeTaskFlowRiver`). |
-| `openWorldTaskQueue` | Task-queue state/color from status counts (`computeTaskQueue`). |
-| `openWorldTimeline` | Bounded activity-log batch appends plus density bins and timeline buckets (`appendEventLogBatch`, `computeActivityDensity`, `buildTimelineBuckets`). |
-| `openWorldVoiceMarker` | Voice-agent marker state/color/label from voice status (`computeVoiceMarker`). |
+| `characterXp` | Character age and birthday-progress helpers: `computeAgeView`, `diffXp`, `birthDateCta`, and legacy `levelFromXP`. |
diff --git a/client/src/utils/index.js b/client/src/utils/index.js
index ece34d5a7d..99d79b0dc3 100644
--- a/client/src/utils/index.js
+++ b/client/src/utils/index.js
@@ -40,40 +40,4 @@ export * from './fileUpload.js';
// === OpenWorld — character & avatar ===
export * from './characterXp.js';
-// === OpenWorld — scene compute helpers (one per district / feature) ===
-export * from './openWorldActivityHeatmap.js';
-export * from './openWorldAgentMotion.js';
-export * from './openWorldAiCore.js';
-export * from './openWorldAppMetrics.js';
-export * from './openWorldArtifacts.js';
-export * from './openWorldBackupVault.js';
-export * from './openWorldChronotype.js';
-export * from './openWorldDataHarbor.js';
-export * from './openWorldDistrictLayout.js';
-export * from './openWorldEasterEggs.js';
-export * from './openWorldFederation.js';
-export * from './openWorldFilter.js';
-export * from './openWorldFocusCamera.js';
-export * from './openWorldFocusState.js';
-export * from './openWorldFlowLines.js';
-export * from './openWorldGoalMonuments.js';
-export * from './openWorldHealthTower.js';
-export * from './openWorldInteriorWindows.js';
-export * from './openWorldJiraDistrict.js';
-export * from './openWorldMemoryDistrict.js';
-export * from './openWorldMiniMap.js';
-export * from './openWorldPhotoMode.js';
-export * from './openWorldPlan.js';
-export * from './openWorldPlayerRig.js';
-export * from './openWorldRenderBudget.js';
-export * from './openWorldRooftops.js';
-export * from './openWorldProductivity.js';
-export * from './openWorldSoundscape.js';
-export * from './openWorldCollectibles.js';
-export * from './openWorldProximity.js';
-export * from './openWorldSpeedPads.js';
-export * from './openWorldTaskFlowRiver.js';
-export * from './openWorldTaskQueue.js';
-export * from './openWorldTimeline.js';
-export * from './openWorldVoiceMarker.js';
-export * from './openWorldRegions.js';
+export * from './renderBudget.js';
diff --git a/client/src/utils/openWorldActivityHeatmap.js b/client/src/utils/openWorldActivityHeatmap.js
deleted file mode 100644
index e927a41698..0000000000
--- a/client/src/utils/openWorldActivityHeatmap.js
+++ /dev/null
@@ -1,113 +0,0 @@
-// Pure, deterministic helpers for OpenWorld's productivity-district activity heatmap
-// (roadmap 2.6 follow-up, issue #817): a GitHub-style contribution grid rendered as a field
-// of ground tiles laid out around the throughput monument. Each tile is one day; its glow scales
-// with that day's completed-task count relative to the busiest day in the window. The grid
-// matches the calendar payload's shape exactly — weeks run left→right (x), day-of-week runs
-// front→back (z) — so the field reads like the contribution chart on the productivity tab.
-// No three.js / React imports so the topology is unit-testable (mirrors openWorldProductivity.js).
-
-import { MONUMENT } from './openWorldProductivity';
-
-export const HEATMAP = {
- // Anchored just east of the monument plinth so the grid frames the obelisk without
- // overlapping its footprint. Monument lives at MONUMENT.position ([-48, 0, 28]).
- origin: [MONUMENT.position[0] + MONUMENT.baseWidth * 1.4, 0, MONUMENT.position[2] - 12],
- tileSize: 1.6, // square footprint of each day tile
- tileGap: 0.4, // gap between adjacent tiles
- tileHeight: 0.18, // a thin slab so the field stays low to the ground
- maxWeeks: 14, // cap columns so the field never sprawls past the district (calendar default is 12)
-};
-
-const ACTIVE_COLOR = '#22c55e'; // port-success — completed work, GitHub-contribution green
-const TODAY_COLOR = '#3b82f6'; // port-accent — highlight the current day
-const EMPTY_COLOR = '#1a2030'; // near port-card — a quiet, unlit "no activity" tile
-
-const clamp01 = (n) => Math.max(0, Math.min(1, n));
-
-// Coerce to a finite, positive count or 0. Tile counts are never negative and a garbage
-// value should read as "no activity," not crash the field.
-function countOrZero(value) {
- return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;
-}
-
-// Map a day's task count to a 0..1 intensity against the window's busiest day. A zero-task
-// day is 0 (drawn dim/empty); the busiest day(s) reach 1. A 0/garbage `maxTasks` falls back
-// to 1 so a single active day still lights up rather than dividing by zero.
-export function tileLevel(tasks, maxTasks) {
- const t = countOrZero(tasks);
- if (t === 0) return 0;
- const max = countOrZero(maxTasks);
- return clamp01(t / (max || 1));
-}
-
-// Full derived view-model for the component. `calendarData` is the `getActivityCalendar`
-// payload (`{ weeks: [[{ date, dayOfWeek, tasks, isToday, isFuture, ... }]], maxTasks,
-// summary }`). A missing/non-object payload, or one with no usable weeks,
-// yields `present: false` and an empty tile list so the field simply doesn't render rather
-// than crashing.
-export function computeActivityHeatmap(calendarData) {
- const payload = calendarData && typeof calendarData === 'object' ? calendarData : {};
- const rawWeeks = Array.isArray(payload.weeks) ? payload.weeks : [];
- // Keep only the most recent `maxWeeks` columns so the field stays inside the district.
- const weeks = rawWeeks.slice(-HEATMAP.maxWeeks);
- const maxTasks = countOrZero(payload.maxTasks) || 1;
-
- const { tileSize, tileGap, tileHeight } = HEATMAP;
- const step = tileSize + tileGap;
-
- const tiles = [];
- let activeCount = 0;
- let totalTasks = 0;
-
- weeks.forEach((week, weekIndex) => {
- const days = Array.isArray(week) ? week : [];
- days.forEach((day) => {
- const dayObj = day && typeof day === 'object' ? day : {};
- // Future days in the trailing partial week aren't real activity — skip them so the
- // grid doesn't render a row of empty tiles past today.
- if (dayObj.isFuture) return;
- const dow = typeof dayObj.dayOfWeek === 'number' && Number.isFinite(dayObj.dayOfWeek)
- ? dayObj.dayOfWeek
- : 0;
- const tasks = countOrZero(dayObj.tasks);
- const level = tileLevel(tasks, maxTasks);
- const isToday = dayObj.isToday === true;
- if (tasks > 0) {
- activeCount += 1;
- totalTasks += tasks;
- }
- tiles.push({
- key: dayObj.date || `${weekIndex}-${dow}`,
- // Weeks run along x (columns), day-of-week runs along z (front→back rows).
- x: weekIndex * step,
- z: dow * step,
- // Animation phase derived from grid indices (not world coords) so the component's
- // shimmer reads as a coherent diagonal wave sweeping across the field rather than
- // near-random per-tile flicker.
- phase: (weekIndex + dow) * 0.18,
- tasks,
- level,
- isToday,
- // Today is always picked out in accent blue, even on a zero-task day — it's a
- // location sentinel, not an activity reading. Otherwise empty days sit dark and
- // active days glow green scaled by level.
- color: isToday ? TODAY_COLOR : tasks === 0 ? EMPTY_COLOR : ACTIVE_COLOR,
- // Emissive intensity: today always reads clearly (legible even at zero tasks); other
- // empty tiles barely glow; active tiles ramp with level.
- intensity: isToday ? Math.max(0.5, 0.25 + level * 0.7) : tasks === 0 ? 0.04 : 0.18 + level * 0.6,
- });
- });
- });
-
- return {
- origin: HEATMAP.origin,
- tileSize,
- tileHeight,
- present: tiles.length > 0,
- weekCount: weeks.length,
- tiles,
- activeCount,
- totalTasks,
- maxTasks,
- };
-}
diff --git a/client/src/utils/openWorldActivityHeatmap.test.js b/client/src/utils/openWorldActivityHeatmap.test.js
deleted file mode 100644
index 12cd77b6f0..0000000000
--- a/client/src/utils/openWorldActivityHeatmap.test.js
+++ /dev/null
@@ -1,143 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import { HEATMAP, tileLevel, computeActivityHeatmap } from './openWorldActivityHeatmap';
-
-// Minimal calendar payload mirroring getActivityCalendar's shape: weeks of 7 days.
-function makeCalendar(taskGrid, { maxTasks, todayIndex } = {}) {
- let flat = 0;
- const weeks = taskGrid.map((week, wi) =>
- week.map((tasks, dow) => {
- const idx = flat++;
- return {
- date: `2026-w${wi}-d${dow}`,
- dayOfWeek: dow,
- tasks,
- successes: tasks,
- failures: 0,
- successRate: 100,
- isToday: idx === todayIndex,
- isFuture: false,
- };
- })
- );
- const computedMax = Math.max(1, ...taskGrid.flat());
- return { weeks, maxTasks: maxTasks ?? computedMax };
-}
-
-describe('tileLevel', () => {
- it('maps tasks/maxTasks into 0..1', () => {
- expect(tileLevel(5, 10)).toBe(0.5);
- expect(tileLevel(10, 10)).toBe(1);
- });
-
- it('treats a zero-task day as level 0', () => {
- expect(tileLevel(0, 10)).toBe(0);
- });
-
- it('clamps above the busiest day to 1', () => {
- expect(tileLevel(20, 10)).toBe(1);
- });
-
- it('falls back to max=1 (not divide-by-zero) for a single active day', () => {
- expect(tileLevel(3, 0)).toBe(1);
- expect(tileLevel(3, undefined)).toBe(1);
- });
-
- it('reads garbage / negative tasks as 0', () => {
- expect(tileLevel(undefined, 10)).toBe(0);
- expect(tileLevel(-4, 10)).toBe(0);
- expect(tileLevel('5', 10)).toBe(0);
- expect(tileLevel(NaN, 10)).toBe(0);
- });
-});
-
-describe('computeActivityHeatmap', () => {
- it('carries the anchored origin through unchanged', () => {
- const vm = computeActivityHeatmap(makeCalendar([[0, 0, 0, 0, 0, 0, 0]]));
- expect(vm.origin).toEqual(HEATMAP.origin);
- });
-
- it('builds one tile per non-future day with grid-aligned x/z', () => {
- const cal = makeCalendar([
- [0, 1, 2, 0, 0, 0, 0],
- [3, 0, 0, 0, 0, 0, 4],
- ]);
- const vm = computeActivityHeatmap(cal);
- expect(vm.present).toBe(true);
- expect(vm.tiles).toHaveLength(14);
- const step = HEATMAP.tileSize + HEATMAP.tileGap;
- // Week 1, day-of-week 6 (the "4-task" tile) sits at x=step, z=6*step.
- const last = vm.tiles.find((t) => t.tasks === 4);
- expect(last.x).toBeCloseTo(step);
- expect(last.z).toBeCloseTo(6 * step);
- });
-
- it('scales intensity by the busiest day and totals active days/tasks', () => {
- const cal = makeCalendar([[0, 2, 4, 0, 0, 0, 0]], { maxTasks: 4 });
- const vm = computeActivityHeatmap(cal);
- expect(vm.maxTasks).toBe(4);
- expect(vm.activeCount).toBe(2);
- expect(vm.totalTasks).toBe(6);
- const busiest = vm.tiles.find((t) => t.tasks === 4);
- const lighter = vm.tiles.find((t) => t.tasks === 2);
- expect(busiest.level).toBe(1);
- expect(lighter.level).toBe(0.5);
- expect(busiest.intensity).toBeGreaterThan(lighter.intensity);
- });
-
- it('draws empty days dim and dark, not glowing', () => {
- const vm = computeActivityHeatmap(makeCalendar([[0, 1, 0, 0, 0, 0, 0]]));
- const empty = vm.tiles.find((t) => t.tasks === 0);
- expect(empty.level).toBe(0);
- expect(empty.color).toBe('#1a2030');
- expect(empty.intensity).toBeLessThan(0.1);
- });
-
- it('accents today and keeps it legible even on a light day', () => {
- const cal = makeCalendar([[0, 1, 0, 0, 0, 0, 0]], { maxTasks: 10, todayIndex: 1 });
- const vm = computeActivityHeatmap(cal);
- const today = vm.tiles.find((t) => t.isToday);
- expect(today.color).toBe('#3b82f6'); // accent
- expect(today.intensity).toBeGreaterThanOrEqual(0.5);
- });
-
- it('picks out a zero-task today as accent, not as a dark empty day', () => {
- // todayIndex 0 has 0 tasks — it's still the "you are here" tile, not an empty day.
- const cal = makeCalendar([[0, 3, 0, 0, 0, 0, 0]], { maxTasks: 3, todayIndex: 0 });
- const vm = computeActivityHeatmap(cal);
- const today = vm.tiles.find((t) => t.isToday);
- expect(today.tasks).toBe(0);
- expect(today.color).toBe('#3b82f6'); // accent, NOT the empty #1a2030
- expect(today.intensity).toBeGreaterThanOrEqual(0.5);
- });
-
- it('skips future days in the trailing partial week', () => {
- const cal = makeCalendar([[1, 0, 0, 0, 0, 0, 0]]);
- cal.weeks[0][3].isFuture = true;
- cal.weeks[0][4].isFuture = true;
- const vm = computeActivityHeatmap(cal);
- expect(vm.tiles).toHaveLength(5); // 7 days minus 2 future
- });
-
- it('caps columns at maxWeeks, keeping the most recent', () => {
- const grid = Array.from({ length: 20 }, () => [1, 0, 0, 0, 0, 0, 0]);
- const vm = computeActivityHeatmap(makeCalendar(grid));
- expect(vm.weekCount).toBe(HEATMAP.maxWeeks);
- });
-
- it('handles missing / non-object / empty input as not-present without crashing', () => {
- for (const bad of [null, undefined, 'nope', 42, [], {}, { weeks: 'oops' }]) {
- const vm = computeActivityHeatmap(bad);
- expect(vm.present).toBe(false);
- expect(vm.tiles).toEqual([]);
- expect(vm.origin).toEqual(HEATMAP.origin);
- }
- });
-
- it('tolerates a non-object day or missing dayOfWeek', () => {
- const vm = computeActivityHeatmap({ weeks: [[null, { tasks: 2 }]], maxTasks: 2 });
- expect(vm.tiles).toHaveLength(2);
- // both fall back to dayOfWeek 0 → z 0
- expect(vm.tiles.every((t) => t.z === 0)).toBe(true);
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldAgentMotion.js b/client/src/utils/openWorldAgentMotion.js
deleted file mode 100644
index fff8c8329f..0000000000
--- a/client/src/utils/openWorldAgentMotion.js
+++ /dev/null
@@ -1,80 +0,0 @@
-// Pure, deterministic helpers for animating OpenWorld agent entities along an
-// orbit path and rendering a fading motion trail behind them. No three.js /
-// React imports here so the geometry math can be unit-tested in isolation
-// (mirrors the openWorldTimeline.js helper pattern).
-
-export const AGENT_MOTION = {
- orbitRadius: 0.9, // horizontal orbit radius around the building anchor
- orbitSpeed: 0.6, // radians/sec around the anchor
- bobAmp: 0.3, // vertical bob amplitude (matches the legacy AgentEntity bob)
- bobSpeed: 1.5, // vertical bob speed
- trailSeconds: 1.6, // how far back in time the trail samples
- trailSamples: 24, // points along the trail at full quality
-};
-
-// Position of an agent at elapsed time `t` (seconds), as an offset relative to
-// its building anchor. `index` fans multiple agents on the same building into
-// distinct orbit phases so their paths and trails don't overlap.
-export function computeAgentOrbit(t, { index = 0, radius, orbitSpeed, bobAmp, bobSpeed } = {}) {
- const r = radius ?? AGENT_MOTION.orbitRadius;
- const os = orbitSpeed ?? AGENT_MOTION.orbitSpeed;
- const ba = bobAmp ?? AGENT_MOTION.bobAmp;
- const bs = bobSpeed ?? AGENT_MOTION.bobSpeed;
- const phase = index * (Math.PI * 0.5); // quarter-turn fan per agent
- const angle = t * os + phase;
- return {
- x: Math.cos(angle) * r,
- y: Math.sin(t * bs + index) * ba,
- z: Math.sin(angle) * r,
- };
-}
-
-// Resolve how many trail samples to draw for a given quality density.
-// `particleDensity` ranges ~0.5 (low) .. 1.5 (ultra). At/above the low floor it
-// scales linearly to the full sample count; below the floor the trail is
-// dropped entirely (returns 0) so weak hardware pays nothing for it.
-export function resolveTrailSamples(particleDensity = 1, maxSamples = AGENT_MOTION.trailSamples) {
- if (!(particleDensity >= 0.5)) return 0;
- const scaled = Math.round((maxSamples * Math.min(1.5, particleDensity)) / 1.5);
- return Math.max(2, scaled);
-}
-
-// Sample the orbit path backwards from time `t` into `samples` points, newest
-// first. Writes a flat [x0,y0,z0, x1,y1,z1, ...] of offsets relative to the
-// anchor — the caller adds the anchor position when placing the trail. Pass a
-// pre-allocated `out` array (e.g. the geometry's Float32Array) to fill it in
-// place and avoid a per-frame allocation on the render hot path; otherwise a
-// fresh Array is allocated and returned.
-export function computeAgentTrailPoints(
- t,
- opts = {},
- samples = AGENT_MOTION.trailSamples,
- trailSeconds = AGENT_MOTION.trailSeconds,
- out = null,
-) {
- const n = Math.max(2, samples);
- const pts = out || new Array(n * 3);
- for (let i = 0; i < n; i++) {
- const dt = (i / (n - 1)) * trailSeconds; // 0 at head (newest), trailSeconds at tail
- const p = computeAgentOrbit(t - dt, opts);
- pts[i * 3] = p.x;
- pts[i * 3 + 1] = p.y;
- pts[i * 3 + 2] = p.z;
- }
- return pts;
-}
-
-// Per-vertex color ramp aligned with computeAgentTrailPoints: full color at the
-// head (newest) fading to black at the tail. `rgb` is a [r,g,b] triple in 0..1.
-// Pairs with an additive-blended lineBasicMaterial so black reads as transparent.
-export function computeTrailColors(rgb, samples = AGENT_MOTION.trailSamples) {
- const n = Math.max(2, samples);
- const colors = new Array(n * 3);
- for (let i = 0; i < n; i++) {
- const fade = 1 - i / (n - 1); // 1 at head .. 0 at tail
- colors[i * 3] = rgb[0] * fade;
- colors[i * 3 + 1] = rgb[1] * fade;
- colors[i * 3 + 2] = rgb[2] * fade;
- }
- return colors;
-}
diff --git a/client/src/utils/openWorldAgentMotion.test.js b/client/src/utils/openWorldAgentMotion.test.js
deleted file mode 100644
index 9717d75b86..0000000000
--- a/client/src/utils/openWorldAgentMotion.test.js
+++ /dev/null
@@ -1,145 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- AGENT_MOTION,
- computeAgentOrbit,
- resolveTrailSamples,
- computeAgentTrailPoints,
- computeTrailColors,
-} from './openWorldAgentMotion';
-
-describe('computeAgentOrbit', () => {
- it('places the agent on a circle of the configured radius (ignoring bob)', () => {
- const { x, z } = computeAgentOrbit(0, { radius: 2, bobAmp: 0 });
- expect(Math.hypot(x, z)).toBeCloseTo(2, 6);
- });
-
- it('at t=0 with no bob sits at angle 0 (x=radius, z=0)', () => {
- const p = computeAgentOrbit(0, { radius: 1, bobAmp: 0 });
- expect(p.x).toBeCloseTo(1, 6);
- expect(p.z).toBeCloseTo(0, 6);
- expect(p.y).toBeCloseTo(0, 6);
- });
-
- it('advances around the circle as time progresses', () => {
- const a = computeAgentOrbit(0, { radius: 1, orbitSpeed: 1, bobAmp: 0 });
- const b = computeAgentOrbit(Math.PI / 2, { radius: 1, orbitSpeed: 1, bobAmp: 0 });
- // quarter turn: x→0, z→1
- expect(b.x).toBeCloseTo(0, 6);
- expect(b.z).toBeCloseTo(1, 6);
- expect(a.x).not.toBeCloseTo(b.x, 3);
- });
-
- it('fans agents on the same building into distinct phases by index', () => {
- const a0 = computeAgentOrbit(0, { radius: 1, bobAmp: 0, index: 0 });
- const a1 = computeAgentOrbit(0, { radius: 1, bobAmp: 0, index: 1 });
- expect(a0.x).not.toBeCloseTo(a1.x, 3);
- });
-
- it('applies vertical bob within the configured amplitude', () => {
- let maxY = 0;
- for (let t = 0; t < 20; t += 0.05) {
- maxY = Math.max(maxY, Math.abs(computeAgentOrbit(t, { bobAmp: 0.3 }).y));
- }
- expect(maxY).toBeGreaterThan(0.25);
- expect(maxY).toBeLessThanOrEqual(0.3 + 1e-9);
- });
-
- it('falls back to AGENT_MOTION defaults when opts are omitted', () => {
- const { x, z } = computeAgentOrbit(0);
- expect(Math.hypot(x, z)).toBeCloseTo(AGENT_MOTION.orbitRadius, 6);
- });
-});
-
-describe('resolveTrailSamples', () => {
- it('drops the trail entirely below the low-quality floor', () => {
- expect(resolveTrailSamples(0)).toBe(0);
- expect(resolveTrailSamples(0.4)).toBe(0);
- });
-
- it('renders a short trail at the low preset (0.5)', () => {
- expect(resolveTrailSamples(0.5, 24)).toBe(8);
- });
-
- it('scales up to the full sample count at ultra (1.5)', () => {
- expect(resolveTrailSamples(1.5, 24)).toBe(24);
- expect(resolveTrailSamples(1.0, 24)).toBe(16);
- });
-
- it('clamps densities above ultra to the max sample count', () => {
- expect(resolveTrailSamples(5, 24)).toBe(24);
- });
-
- it('never returns fewer than 2 points for a renderable trail', () => {
- expect(resolveTrailSamples(0.5, 2)).toBe(2);
- });
-});
-
-describe('computeAgentTrailPoints', () => {
- it('returns samples*3 flat coordinates', () => {
- const pts = computeAgentTrailPoints(1, {}, 10);
- expect(pts).toHaveLength(30);
- });
-
- it('head (first point) matches the current orbit position', () => {
- const t = 3.21;
- const opts = { index: 2 };
- const head = computeAgentOrbit(t, opts);
- const pts = computeAgentTrailPoints(t, opts, 12);
- expect(pts[0]).toBeCloseTo(head.x, 6);
- expect(pts[1]).toBeCloseTo(head.y, 6);
- expect(pts[2]).toBeCloseTo(head.z, 6);
- });
-
- it('tail (last point) matches the orbit position trailSeconds in the past', () => {
- const t = 3.21;
- const opts = { index: 0 };
- const tail = computeAgentOrbit(t - AGENT_MOTION.trailSeconds, opts);
- const pts = computeAgentTrailPoints(t, opts, 8, AGENT_MOTION.trailSeconds);
- const last = pts.length - 3;
- expect(pts[last]).toBeCloseTo(tail.x, 6);
- expect(pts[last + 1]).toBeCloseTo(tail.y, 6);
- expect(pts[last + 2]).toBeCloseTo(tail.z, 6);
- });
-
- it('clamps to a minimum of 2 points', () => {
- expect(computeAgentTrailPoints(0, {}, 1)).toHaveLength(6);
- });
-
- it('fills a pre-allocated out buffer in place and returns it (no allocation)', () => {
- const out = new Float32Array(8 * 3);
- const ret = computeAgentTrailPoints(2.5, { index: 1 }, 8, AGENT_MOTION.trailSeconds, out);
- expect(ret).toBe(out);
- const fresh = computeAgentTrailPoints(2.5, { index: 1 }, 8);
- for (let i = 0; i < fresh.length; i++) {
- expect(out[i]).toBeCloseTo(fresh[i], 5);
- }
- });
-});
-
-describe('computeTrailColors', () => {
- it('returns samples*3 channel values', () => {
- expect(computeTrailColors([1, 0.5, 0.25], 10)).toHaveLength(30);
- });
-
- it('is full color at the head and black at the tail', () => {
- const rgb = [0.2, 0.4, 0.8];
- const colors = computeTrailColors(rgb, 5);
- expect(colors[0]).toBeCloseTo(rgb[0], 6);
- expect(colors[1]).toBeCloseTo(rgb[1], 6);
- expect(colors[2]).toBeCloseTo(rgb[2], 6);
- const last = colors.length - 3;
- expect(colors[last]).toBeCloseTo(0, 6);
- expect(colors[last + 1]).toBeCloseTo(0, 6);
- expect(colors[last + 2]).toBeCloseTo(0, 6);
- });
-
- it('fades monotonically from head to tail', () => {
- const colors = computeTrailColors([1, 1, 1], 6);
- const reds = [];
- for (let i = 0; i < colors.length; i += 3) reds.push(colors[i]);
- for (let i = 1; i < reds.length; i++) {
- expect(reds[i]).toBeLessThan(reds[i - 1]);
- }
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldAiCore.js b/client/src/utils/openWorldAiCore.js
deleted file mode 100644
index c6028dce59..0000000000
--- a/client/src/utils/openWorldAiCore.js
+++ /dev/null
@@ -1,279 +0,0 @@
-// Pure, deterministic helpers for OpenWorld's AI Core landmark (roadmap 2.1): a central
-// spire above downtown from which all model activity radiates. The server broadcasts
-// phase-tagged `ai:status` events (start → model:loading → model:loaded → complete/error)
-// for every LLM/model call; this module tracks the in-flight set and derives the core's
-// glow/beam state. No three.js / React imports so the logic is unit-testable (mirrors
-// openWorldBackupVault.js).
-//
-// When a call originates on behalf of a managed app or CoS-agent workspace, the event
-// carries `appId` / `workspacePath`; `computeAiCoreBeams` maps that to the building's world
-// position and aims the beam there, scaling its thickness by the call's tokens/sec. Ops
-// with no building association (most PortOS-internal calls — taste summaries, embeddings)
-// keep the generic radial fan-out. Model tier is a best-effort heuristic from the model
-// name (the event has no explicit tier).
-
-import { PARCELS } from './openWorldPlan';
-
-export const AI_CORE = {
- position: PARCELS.aiCore.anchor, // world center — the kinetic core anchors The Port
- height: 6,
- apexY: 5.5, // beams/glow originate from the suspended seed above the plaza
- maxBeams: 6, // visible activity beams cap
- // How long an op with no terminal (complete/error) event lingers before being pruned,
- // so a dropped/never-finished call can't pin the core "busy" forever.
- opMaxAgeMs: 60_000,
- // How long after the last op start the core keeps its "just fired" flare.
- flareMs: 1200,
- // How long a just-completed op lingers as an "afterglow" beam. The provider only reports
- // token throughput on the completion event (which ends the op), so this window is what
- // lets a measured tokens/sec actually thicken a beam before it fades — without it, every
- // beam would render at the base thickness.
- afterglowMs: 1500,
- // Generic (un-targeted) radial beam length, in world units.
- radialLength: 16,
- // Beam thickness clamps (world units). Un-measured ops use `beamThicknessBase`;
- // measured throughput scales between base and max across `beamThicknessTopTokensPerSec`.
- beamThicknessBase: 0.18,
- beamThicknessMax: 0.6,
- beamThicknessTopTokensPerSec: 200,
-};
-
-const TIER_COLORS = {
- light: '#22d3ee', // cyan — fast/cheap models
- medium: '#3b82f6', // port-accent — standard models
- heavy: '#a855f7', // violet — large/expensive models
- idle: '#334155', // slate — core at rest
-};
-
-// Phases that mean the op is no longer in flight.
-const TERMINAL_PHASES = new Set(['complete', 'error']);
-
-// Best-effort model-tier classification from the model name. The `ai:status` event has no
-// explicit tier, so we pattern-match common families. Unknown models fall to `medium`.
-export function modelTier(model) {
- if (!model || typeof model !== 'string') return 'medium';
- const m = model.toLowerCase();
- if (/\b(opus|70b|72b|405b|large|heavy|ultra|max)\b/.test(m) || /:(70|72|405)b/.test(m)) return 'heavy';
- if (/(haiku|mini|flash|lite|light|tiny|small|1\.5b|3b|7b|8b|9b|nano|gemma)/.test(m)) return 'light';
- return 'medium';
-}
-
-export function tierColor(tier) {
- return TIER_COLORS[tier] || TIER_COLORS.medium;
-}
-
-// Rank tiers so the core can pick the "loudest" active tier when several ops overlap.
-const TIER_RANK = { light: 1, medium: 2, heavy: 3 };
-
-// Coerce a finite, non-negative tokens/sec from an event; otherwise null ("unknown").
-// Keeps "the provider didn't report usage" distinct from a measured zero. Only an actual
-// number counts — `null`/`undefined`/`''` (which `Number()` would coerce to 0/NaN) are
-// "unknown", per the sentinel-vs-empty convention.
-function readTokensPerSec(v) {
- return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : null;
-}
-
-// True while an op should still draw a beam: in flight (within opMaxAgeMs), or just
-// completed and within its afterglow window. `done` ops keep their last `ts` and are timed
-// against `afterglowMs` so a measured tokens/sec gets a moment to thicken its beam.
-function opWithinWindow(op, now) {
- const age = now - op.ts;
- return op.done ? age <= AI_CORE.afterglowMs : age <= AI_CORE.opMaxAgeMs;
-}
-
-// Apply one `ai:status` event to the in-flight op map (plain object keyed by op id),
-// returning a NEW object. A terminal phase (complete/error) doesn't drop the op outright:
-// if it reported token throughput, the op is kept briefly as a `done` afterglow entry (so
-// the measured tokens/sec can size its beam — throughput only arrives at completion); a
-// terminal phase with no throughput drops the op immediately. Every other phase adds/updates
-// it with the event's model, building association (`appId`/`workspacePath`), last-known
-// tokens/sec, and a last-seen timestamp. Entries past their window are pruned so a
-// never-completed op can't wedge the core busy. Pure — `now` is injected.
-export function applyAiStatusEvent(ops, event, now = Date.now()) {
- const next = {};
- // Prune ops past their (in-flight or afterglow) window first.
- for (const [id, op] of Object.entries(ops || {})) {
- if (opWithinWindow(op, now)) next[id] = op;
- }
- const id = event?.id;
- if (!id) return next;
- const prev = next[id] || {};
- const tokensPerSec = readTokensPerSec(event.tokensPerSec) ?? prev.tokensPerSec ?? null;
- if (TERMINAL_PHASES.has(event.phase)) {
- // Drop immediately when there's nothing to show; otherwise keep a short afterglow so
- // the just-measured throughput visibly thickens the beam before it fades. Re-read the
- // association from the event (every phase event carries it) — the in-flight entry may
- // have been pruned at opMaxAgeMs on a long call, so falling back to `prev` alone would
- // lose the building target.
- if (tokensPerSec === null) {
- delete next[id];
- return next;
- }
- next[id] = {
- id,
- done: true,
- model: event.model || prev.model || null,
- tier: modelTier(event.model || prev.model),
- appId: event.appId ?? prev.appId ?? null,
- workspacePath: event.workspacePath ?? prev.workspacePath ?? null,
- tokensPerSec,
- ts: now,
- };
- return next;
- }
- next[id] = {
- id,
- done: false,
- model: event.model || prev.model || null,
- tier: modelTier(event.model || prev.model),
- // Association is stamped at start; carry it forward across intermediate phases even if
- // a later event omits it.
- appId: event.appId ?? prev.appId ?? null,
- workspacePath: event.workspacePath ?? prev.workspacePath ?? null,
- // Throughput typically only arrives on later phases; keep the last measured value.
- tokensPerSec,
- ts: now,
- };
- return next;
-}
-
-// True when `child` is `parent` itself or a path nested under it — a boundary-aware check so
-// `/repos/app` does NOT match the sibling `/repos/app-other`. Compares on a trailing-slash
-// normalized form. Pure.
-function isPathUnder(child, parent) {
- if (!child || !parent) return false;
- if (child === parent) return true;
- const base = parent.endsWith('/') ? parent : `${parent}/`;
- return child.startsWith(base);
-}
-
-// Drop every op past its window (in-flight or afterglow). Returns the SAME reference when
-// nothing changed so callers can skip a no-op state update; otherwise a new pruned object.
-// Used by a one-shot timer so a `done`/flare beam fades on schedule even when no further
-// `ai:status` event arrives to trigger the reducer. Pure.
-export function pruneAiOps(ops, now = Date.now()) {
- const entries = Object.entries(ops || {});
- const kept = entries.filter(([, op]) => opWithinWindow(op, now));
- if (kept.length === entries.length) return ops;
- return Object.fromEntries(kept);
-}
-
-// Map an op's building association to an app id. Prefers an explicit `appId`; otherwise
-// matches the app whose `repoPath` is the longest path-boundary prefix of the op's
-// `workspacePath` (a CoS-agent worktree lives under its app's repo). Returns null when
-// nothing matches. Pure.
-export function resolveOpAppId(op, apps = []) {
- if (op?.appId) return op.appId;
- const wp = op?.workspacePath;
- if (!wp || !Array.isArray(apps)) return null;
- let best = null;
- let bestLen = -1;
- for (const app of apps) {
- if (app?.repoPath && isPathUnder(wp, app.repoPath) && app.repoPath.length > bestLen) {
- best = app.id;
- bestLen = app.repoPath.length;
- }
- }
- return best;
-}
-
-// Map measured tokens/sec to a beam thickness, clamped between base and max. A null/unknown
-// throughput renders at the base thickness so an un-instrumented call still draws a beam.
-export function beamThickness(tokensPerSec) {
- const base = AI_CORE.beamThicknessBase;
- const max = AI_CORE.beamThicknessMax;
- const tps = readTokensPerSec(tokensPerSec);
- if (tps === null) return base;
- const frac = Math.min(tps / AI_CORE.beamThicknessTopTokensPerSec, 1);
- return base + (max - base) * frac;
-}
-
-// Derive the core's view-model from the in-flight op map. `lastStartTs` (the timestamp of
-// the most recent op start) drives a brief flare; `now` is injected for determinism.
-export function computeAiCore(ops, lastStartTs = 0, now = Date.now()) {
- // Only in-flight ops count toward "busy"/concurrency; `done` afterglow ops still draw a
- // beam (see computeAiCoreBeams) but the call is finished, so they don't inflate the count.
- const active = Object.values(ops || {}).filter(op => !op.done && now - op.ts <= AI_CORE.opMaxAgeMs);
- const activeCount = active.length;
- const busy = activeCount > 0;
- // Loudest active tier wins the color; idle when nothing is in flight.
- const tier = busy
- ? active.reduce((hi, op) => (TIER_RANK[op.tier] > TIER_RANK[hi] ? op.tier : hi), 'light')
- : 'idle';
- const flaring = lastStartTs > 0 && now - lastStartTs <= AI_CORE.flareMs;
- return {
- position: AI_CORE.position,
- height: AI_CORE.height,
- apexY: AI_CORE.apexY,
- activeCount,
- busy,
- tier,
- color: busy ? tierColor(tier) : TIER_COLORS.idle,
- // Beam count tracks concurrency, capped; at least one beam while flaring even if the
- // op already cleared (so a fast call still produces a visible pulse).
- beamCount: Math.min(Math.max(activeCount, flaring ? 1 : 0), AI_CORE.maxBeams),
- flaring,
- // Idle core breathes faintly; busy core glows; a flare spikes intensity briefly.
- intensity: busy ? 0.7 + Math.min(activeCount, 4) * 0.075 : flaring ? 0.6 : 0.25,
- };
-}
-
-// Build the per-beam descriptors the renderer draws from the apex. Each op still within its
-// window (in flight, or completed within the afterglow) becomes one beam: if it resolves to
-// a building whose world position is known, the beam is `targeted` and aims at that building
-// (in apex-local space); otherwise it falls back to a generic radial beam at an even angle.
-// Thickness scales by the op's measured tokens/sec — which is why afterglow ops are kept:
-// throughput is only known once the call completes.
-//
-// ops — op map (from applyAiStatusEvent), including afterglow `done` entries
-// positions — Map<appId, { x, z }> of building world positions (OpenWorldScene's layout)
-// apps — app records (for workspacePath → app resolution)
-// apexY — world Y of the spire apex (beams originate here)
-// color — fallback color when an op has no tier (e.g. the core's active-tier color)
-// now — injected for determinism
-//
-// Returns up to AI_CORE.maxBeams descriptors. Pure.
-export function computeAiCoreBeams(ops, positions, apps = [], apexY = AI_CORE.apexY, color, now = Date.now()) {
- const active = Object.values(ops || {})
- .filter(op => opWithinWindow(op, now))
- .slice(0, AI_CORE.maxBeams);
-
- const getPos = (id) => {
- if (!id || !positions) return null;
- // Tolerate both a Map and a plain object so callers can pass either.
- return typeof positions.get === 'function' ? positions.get(id) : positions[id];
- };
-
- // Radial fallback angles spread evenly across however many beams we draw, so a mix of
- // targeted + radial beams still reads as a balanced fan.
- const total = Math.max(active.length, 1);
-
- return active.map((op, i) => {
- const appId = resolveOpAppId(op, apps);
- const pos = getPos(appId);
- const thickness = beamThickness(op.tokensPerSec);
- // Color by the op's own tier so a `done` afterglow beam keeps its tier color even when
- // the core has gone idle (no in-flight op left to set the core color).
- const beamColor = op.tier ? tierColor(op.tier) : color;
- if (pos && Number.isFinite(pos.x) && Number.isFinite(pos.z)) {
- // Apex-local target: building roof-ish height so the beam arcs down to the building.
- return {
- key: op.id,
- targeted: true,
- appId,
- // Vector from the apex (group origin) to the building, in apex-local space.
- target: [pos.x, -apexY + 4, pos.z],
- thickness,
- color: beamColor,
- };
- }
- return {
- key: op.id,
- targeted: false,
- angle: (i / total) * Math.PI * 2,
- length: AI_CORE.radialLength,
- thickness,
- color: beamColor,
- };
- });
-}
diff --git a/client/src/utils/openWorldAiCore.test.js b/client/src/utils/openWorldAiCore.test.js
deleted file mode 100644
index 7fdc4c4cd7..0000000000
--- a/client/src/utils/openWorldAiCore.test.js
+++ /dev/null
@@ -1,364 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- AI_CORE,
- modelTier,
- tierColor,
- applyAiStatusEvent,
- computeAiCore,
- resolveOpAppId,
- beamThickness,
- computeAiCoreBeams,
- pruneAiOps,
-} from './openWorldAiCore';
-
-const NOW = 1_000_000;
-const ev = (id, phase, model, extra = {}) => ({ id, phase, model, ...extra });
-
-describe('modelTier', () => {
- it('classifies heavy families', () => {
- expect(modelTier('claude-opus-4-8')).toBe('heavy');
- expect(modelTier('llama-3.1-70b')).toBe('heavy');
- expect(modelTier('qwen2.5:72b')).toBe('heavy');
- });
- it('classifies light families', () => {
- expect(modelTier('claude-haiku-4-5')).toBe('light');
- expect(modelTier('gpt-4o-mini')).toBe('light');
- expect(modelTier('gemini-1.5-flash')).toBe('light');
- expect(modelTier('llama-3-8b')).toBe('light');
- });
- it('defaults unknown / missing to medium', () => {
- expect(modelTier('some-unknown-model')).toBe('medium');
- expect(modelTier(undefined)).toBe('medium');
- expect(modelTier(null)).toBe('medium');
- expect(modelTier(42)).toBe('medium');
- });
-});
-
-describe('tierColor', () => {
- it('maps tiers to distinct colors and falls back to medium', () => {
- expect(tierColor('light')).toBe('#22d3ee');
- expect(tierColor('medium')).toBe('#3b82f6');
- expect(tierColor('heavy')).toBe('#a855f7');
- expect(tierColor('bogus')).toBe(tierColor('medium'));
- });
-});
-
-describe('applyAiStatusEvent', () => {
- it('adds an op on a non-terminal phase', () => {
- const ops = applyAiStatusEvent({}, ev('a', 'start', 'gpt-4o-mini'), NOW);
- expect(Object.keys(ops)).toEqual(['a']);
- expect(ops.a.tier).toBe('light');
- expect(ops.a.ts).toBe(NOW);
- });
-
- it('keeps the op across intermediate phases, refreshing its timestamp', () => {
- let ops = applyAiStatusEvent({}, ev('a', 'start', 'claude-opus-4-8'), NOW);
- ops = applyAiStatusEvent(ops, ev('a', 'model:loading', 'claude-opus-4-8'), NOW + 500);
- expect(Object.keys(ops)).toEqual(['a']);
- expect(ops.a.ts).toBe(NOW + 500);
- expect(ops.a.tier).toBe('heavy');
- });
-
- it('removes the op on complete and on error', () => {
- let ops = applyAiStatusEvent({}, ev('a', 'start', 'm'), NOW);
- ops = applyAiStatusEvent(ops, ev('b', 'start', 'm'), NOW);
- ops = applyAiStatusEvent(ops, ev('a', 'complete', 'm'), NOW + 1);
- expect(Object.keys(ops)).toEqual(['b']);
- ops = applyAiStatusEvent(ops, ev('b', 'error', 'm'), NOW + 2);
- expect(Object.keys(ops)).toEqual([]);
- });
-
- it('prunes ops older than opMaxAgeMs', () => {
- let ops = applyAiStatusEvent({}, ev('old', 'start', 'm'), NOW);
- // A later event prunes the stale 'old' op while adding the new one.
- ops = applyAiStatusEvent(ops, ev('new', 'start', 'm'), NOW + AI_CORE.opMaxAgeMs + 1);
- expect(Object.keys(ops)).toEqual(['new']);
- });
-
- it('ignores an event with no id but still prunes', () => {
- let ops = applyAiStatusEvent({}, ev('old', 'start', 'm'), NOW);
- ops = applyAiStatusEvent(ops, { phase: 'start', model: 'm' }, NOW + AI_CORE.opMaxAgeMs + 1);
- expect(Object.keys(ops)).toEqual([]);
- });
-
- it('returns a new object (no mutation of the input)', () => {
- const input = {};
- const out = applyAiStatusEvent(input, ev('a', 'start', 'm'), NOW);
- expect(out).not.toBe(input);
- expect(Object.keys(input)).toEqual([]);
- });
-});
-
-describe('computeAiCore', () => {
- it('is idle with no ops', () => {
- const vm = computeAiCore({}, 0, NOW);
- expect(vm.busy).toBe(false);
- expect(vm.activeCount).toBe(0);
- expect(vm.tier).toBe('idle');
- expect(vm.color).toBe('#334155');
- expect(vm.beamCount).toBe(0);
- expect(vm.intensity).toBe(0.25);
- expect(vm.position).toEqual(AI_CORE.position);
- });
-
- it('glows with the loudest active tier when ops overlap', () => {
- const ops = {
- a: { id: 'a', tier: 'light', ts: NOW },
- b: { id: 'b', tier: 'heavy', ts: NOW },
- c: { id: 'c', tier: 'medium', ts: NOW },
- };
- const vm = computeAiCore(ops, NOW, NOW);
- expect(vm.busy).toBe(true);
- expect(vm.activeCount).toBe(3);
- expect(vm.tier).toBe('heavy');
- expect(vm.color).toBe('#a855f7');
- expect(vm.beamCount).toBe(3);
- });
-
- it('caps beam count at maxBeams', () => {
- const ops = {};
- for (let i = 0; i < AI_CORE.maxBeams + 5; i++) ops[i] = { id: String(i), tier: 'medium', ts: NOW };
- const vm = computeAiCore(ops, NOW, NOW);
- expect(vm.activeCount).toBe(AI_CORE.maxBeams + 5);
- expect(vm.beamCount).toBe(AI_CORE.maxBeams);
- });
-
- it('ignores stale ops past opMaxAgeMs', () => {
- const ops = { a: { id: 'a', tier: 'heavy', ts: NOW } };
- const vm = computeAiCore(ops, 0, NOW + AI_CORE.opMaxAgeMs + 1);
- expect(vm.busy).toBe(false);
- expect(vm.activeCount).toBe(0);
- });
-
- it('flares briefly after a start even once the op has cleared', () => {
- const vm = computeAiCore({}, NOW, NOW + 200);
- expect(vm.busy).toBe(false);
- expect(vm.flaring).toBe(true);
- expect(vm.beamCount).toBe(1); // a fast call still pulses
- expect(vm.intensity).toBe(0.6);
- });
-
- it('stops flaring after flareMs', () => {
- const vm = computeAiCore({}, NOW, NOW + AI_CORE.flareMs + 1);
- expect(vm.flaring).toBe(false);
- expect(vm.beamCount).toBe(0);
- });
-});
-
-describe('applyAiStatusEvent building association', () => {
- it('stamps appId / workspacePath / tokensPerSec from the event', () => {
- const ops = applyAiStatusEvent({}, ev('a', 'start', 'gpt-4o', { appId: 'app-1', workspacePath: '/r/x', tokensPerSec: 90 }), NOW);
- expect(ops.a.appId).toBe('app-1');
- expect(ops.a.workspacePath).toBe('/r/x');
- expect(ops.a.tokensPerSec).toBe(90);
- });
-
- it('carries association forward when a later phase omits it', () => {
- let ops = applyAiStatusEvent({}, ev('a', 'start', 'm', { appId: 'app-1' }), NOW);
- ops = applyAiStatusEvent(ops, ev('a', 'model:loading', 'm'), NOW + 100);
- expect(ops.a.appId).toBe('app-1');
- });
-
- it('updates tokensPerSec when a later phase reports it, keeping last-known otherwise', () => {
- let ops = applyAiStatusEvent({}, ev('a', 'start', 'm'), NOW);
- expect(ops.a.tokensPerSec).toBeNull();
- ops = applyAiStatusEvent(ops, ev('a', 'provider:starting', 'm', { tokensPerSec: 150 }), NOW + 10);
- expect(ops.a.tokensPerSec).toBe(150);
- ops = applyAiStatusEvent(ops, ev('a', 'provider:starting', 'm'), NOW + 20);
- expect(ops.a.tokensPerSec).toBe(150); // preserved
- });
-
- it('drops a terminal op with no throughput immediately', () => {
- let ops = applyAiStatusEvent({}, ev('a', 'start', 'm', { appId: 'app-1' }), NOW);
- ops = applyAiStatusEvent(ops, ev('a', 'complete', 'm'), NOW + 1);
- expect(Object.keys(ops)).toEqual([]);
- });
-
- it('keeps a completed op as a done afterglow when it reported throughput', () => {
- let ops = applyAiStatusEvent({}, ev('a', 'start', 'm', { appId: 'app-1' }), NOW);
- ops = applyAiStatusEvent(ops, ev('a', 'complete', 'm', { tokens: 200, tokensPerSec: 80 }), NOW + 5);
- expect(ops.a.done).toBe(true);
- expect(ops.a.tokensPerSec).toBe(80);
- expect(ops.a.appId).toBe('app-1'); // association carried onto the afterglow
- });
-
- it('reads the association from the completion event when the in-flight op was already pruned', () => {
- // A long call (300s) whose in-flight entry was pruned at opMaxAgeMs (60s); the completion
- // event still carries appId, so the afterglow must target the building, not go radial.
- const completeEvent = ev('a', 'complete', 'm', { appId: 'app-9', workspacePath: '/r/x', tokensPerSec: 40 });
- const ops = applyAiStatusEvent({}, completeEvent, NOW); // empty prior map → no prev
- expect(ops.a.done).toBe(true);
- expect(ops.a.appId).toBe('app-9');
- expect(ops.a.workspacePath).toBe('/r/x');
- });
-
- it('prunes a done afterglow op once afterglowMs has passed', () => {
- let ops = applyAiStatusEvent({}, ev('a', 'start', 'm'), NOW);
- ops = applyAiStatusEvent(ops, ev('a', 'complete', 'm', { tokensPerSec: 80 }), NOW + 5);
- // A later event past the afterglow window prunes the done op.
- ops = applyAiStatusEvent(ops, ev('b', 'start', 'm'), NOW + 5 + AI_CORE.afterglowMs + 1);
- expect(Object.keys(ops)).toEqual(['b']);
- });
-});
-
-describe('resolveOpAppId', () => {
- const apps = [
- { id: 'outer', repoPath: '/repos/proj' },
- { id: 'inner', repoPath: '/repos/proj/packages/web' },
- ];
- it('prefers an explicit appId', () => {
- expect(resolveOpAppId({ appId: 'x', workspacePath: '/repos/proj' }, apps)).toBe('x');
- });
- it('matches the longest repoPath prefix of workspacePath', () => {
- expect(resolveOpAppId({ workspacePath: '/repos/proj/packages/web/src' }, apps)).toBe('inner');
- expect(resolveOpAppId({ workspacePath: '/repos/proj/docs' }, apps)).toBe('outer');
- expect(resolveOpAppId({ workspacePath: '/repos/proj' }, apps)).toBe('outer'); // exact match
- });
- it('does not match a sibling path that merely shares a prefix', () => {
- // /repos/proj-other is NOT under /repos/proj — boundary-aware, not raw startsWith.
- expect(resolveOpAppId({ workspacePath: '/repos/proj-other/src' }, apps)).toBeNull();
- });
- it('returns null when nothing matches', () => {
- expect(resolveOpAppId({ workspacePath: '/elsewhere' }, apps)).toBeNull();
- expect(resolveOpAppId({}, apps)).toBeNull();
- expect(resolveOpAppId(null, apps)).toBeNull();
- });
-});
-
-describe('readTokensPerSec sentinel (via afterglow retention)', () => {
- it('treats null / empty-string throughput as unknown, not a measured zero', () => {
- // A terminal event with no real throughput must drop the op (unknown), not keep it as
- // a zero-throughput afterglow.
- let ops = applyAiStatusEvent({}, ev('a', 'start', 'm'), NOW);
- ops = applyAiStatusEvent(ops, ev('a', 'complete', 'm', { tokensPerSec: null }), NOW + 1);
- expect(Object.keys(ops)).toEqual([]);
- ops = applyAiStatusEvent({}, ev('b', 'start', 'm'), NOW);
- ops = applyAiStatusEvent(ops, ev('b', 'complete', 'm', { tokensPerSec: '' }), NOW + 1);
- expect(Object.keys(ops)).toEqual([]);
- });
- it('keeps a genuine zero-throughput afterglow distinct from unknown', () => {
- let ops = applyAiStatusEvent({}, ev('a', 'start', 'm'), NOW);
- ops = applyAiStatusEvent(ops, ev('a', 'complete', 'm', { tokensPerSec: 0 }), NOW + 1);
- expect(ops.a?.done).toBe(true);
- expect(ops.a.tokensPerSec).toBe(0);
- });
-});
-
-describe('pruneAiOps', () => {
- it('returns the same reference when nothing expired', () => {
- const ops = { a: { id: 'a', ts: NOW } };
- expect(pruneAiOps(ops, NOW)).toBe(ops);
- });
- it('drops expired in-flight and afterglow ops', () => {
- const ops = {
- live: { id: 'live', ts: NOW },
- stale: { id: 'stale', ts: NOW - AI_CORE.opMaxAgeMs - 1 },
- glow: { id: 'glow', done: true, ts: NOW - AI_CORE.afterglowMs - 1 },
- };
- const pruned = pruneAiOps(ops, NOW);
- expect(Object.keys(pruned)).toEqual(['live']);
- });
-});
-
-describe('beamThickness', () => {
- it('renders base thickness for unknown / null throughput', () => {
- expect(beamThickness(null)).toBe(AI_CORE.beamThicknessBase);
- expect(beamThickness(undefined)).toBe(AI_CORE.beamThicknessBase);
- expect(beamThickness('nope')).toBe(AI_CORE.beamThicknessBase);
- });
- it('scales toward max with throughput and clamps at the top', () => {
- expect(beamThickness(0)).toBe(AI_CORE.beamThicknessBase);
- expect(beamThickness(AI_CORE.beamThicknessTopTokensPerSec)).toBe(AI_CORE.beamThicknessMax);
- expect(beamThickness(AI_CORE.beamThicknessTopTokensPerSec * 10)).toBe(AI_CORE.beamThicknessMax);
- const mid = beamThickness(AI_CORE.beamThicknessTopTokensPerSec / 2);
- expect(mid).toBeGreaterThan(AI_CORE.beamThicknessBase);
- expect(mid).toBeLessThan(AI_CORE.beamThicknessMax);
- });
-});
-
-describe('computeAiCoreBeams', () => {
- const apps = [{ id: 'app-1', repoPath: '/repos/one' }];
- const positions = new Map([['app-1', { x: 10, z: -6, district: 'downtown' }]]);
-
- it('targets the building for an app-associated op (apex-local target vector)', () => {
- const ops = { a: { id: 'a', appId: 'app-1', tokensPerSec: 200, ts: NOW } };
- const beams = computeAiCoreBeams(ops, positions, apps, AI_CORE.apexY, '#fff', NOW);
- expect(beams).toHaveLength(1);
- expect(beams[0].targeted).toBe(true);
- expect(beams[0].appId).toBe('app-1');
- expect(beams[0].target).toEqual([10, -AI_CORE.apexY + 4, -6]);
- expect(beams[0].thickness).toBe(AI_CORE.beamThicknessMax); // 200 tok/s → max
- });
-
- it('resolves a workspacePath op to its app building', () => {
- const ops = { a: { id: 'a', workspacePath: '/repos/one/worktrees/x', ts: NOW } };
- const beams = computeAiCoreBeams(ops, positions, apps, AI_CORE.apexY, '#fff', NOW);
- expect(beams[0].targeted).toBe(true);
- expect(beams[0].appId).toBe('app-1');
- });
-
- it('falls back to a radial beam when there is no building association', () => {
- const ops = { a: { id: 'a', ts: NOW }, b: { id: 'b', appId: 'unknown', ts: NOW } };
- const beams = computeAiCoreBeams(ops, positions, apps, AI_CORE.apexY, '#fff', NOW);
- expect(beams).toHaveLength(2);
- expect(beams.every(b => !b.targeted)).toBe(true);
- expect(beams[0]).toMatchObject({ angle: 0, length: AI_CORE.radialLength });
- });
-
- it('accepts a plain-object position map and caps at maxBeams', () => {
- const ops = {};
- for (let i = 0; i < AI_CORE.maxBeams + 4; i++) ops[i] = { id: String(i), ts: NOW };
- const beams = computeAiCoreBeams(ops, {}, apps, AI_CORE.apexY, '#fff', NOW);
- expect(beams).toHaveLength(AI_CORE.maxBeams);
- });
-
- it('ignores stale ops past opMaxAgeMs', () => {
- const ops = { a: { id: 'a', appId: 'app-1', ts: NOW } };
- const beams = computeAiCoreBeams(ops, positions, apps, AI_CORE.apexY, '#fff', NOW + AI_CORE.opMaxAgeMs + 1);
- expect(beams).toHaveLength(0);
- });
-
- it('colors each beam by its own tier, falling back to the passed color when tier is absent', () => {
- const ops = {
- a: { id: 'a', appId: 'app-1', tier: 'heavy', ts: NOW },
- b: { id: 'b', tier: 'light', ts: NOW }, // radial
- c: { id: 'c', ts: NOW }, // no tier → fallback color
- };
- const beams = computeAiCoreBeams(ops, positions, apps, AI_CORE.apexY, '#fallback', NOW);
- const byKey = Object.fromEntries(beams.map(b => [b.key, b]));
- expect(byKey.a.color).toBe(tierColor('heavy'));
- expect(byKey.b.color).toBe(tierColor('light'));
- expect(byKey.c.color).toBe('#fallback');
- });
-
- it('draws a done afterglow op with its measured thickness, then drops it after afterglowMs', () => {
- const ops = { a: { id: 'a', appId: 'app-1', done: true, tokensPerSec: 200, ts: NOW } };
- const within = computeAiCoreBeams(ops, positions, apps, AI_CORE.apexY, '#fff', NOW + AI_CORE.afterglowMs - 1);
- expect(within).toHaveLength(1);
- expect(within[0].targeted).toBe(true);
- expect(within[0].thickness).toBe(AI_CORE.beamThicknessMax);
- const after = computeAiCoreBeams(ops, positions, apps, AI_CORE.apexY, '#fff', NOW + AI_CORE.afterglowMs + 1);
- expect(after).toHaveLength(0);
- });
-});
-
-describe('computeAiCore with afterglow ops', () => {
- it('does not count a done afterglow op toward busy/activeCount', () => {
- const ops = {
- a: { id: 'a', tier: 'heavy', ts: NOW }, // in flight
- b: { id: 'b', tier: 'light', done: true, tokensPerSec: 50, ts: NOW }, // afterglow
- };
- const vm = computeAiCore(ops, 0, NOW);
- expect(vm.activeCount).toBe(1);
- expect(vm.busy).toBe(true);
- expect(vm.tier).toBe('heavy');
- });
-
- it('reads idle when only done afterglow ops remain', () => {
- const ops = { b: { id: 'b', tier: 'light', done: true, tokensPerSec: 50, ts: NOW } };
- const vm = computeAiCore(ops, 0, NOW);
- expect(vm.busy).toBe(false);
- expect(vm.activeCount).toBe(0);
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldAppMetrics.js b/client/src/utils/openWorldAppMetrics.js
deleted file mode 100644
index 327ba201b0..0000000000
--- a/client/src/utils/openWorldAppMetrics.js
+++ /dev/null
@@ -1,89 +0,0 @@
-// Per-building live telemetry (roadmap 1.1). `GET /api/apps` already ships per-process
-// PM2 metrics (`cpu` %, `memory` bytes, `uptime` ms, restart counts) inside each app's
-// `pm2Status` map — this module aggregates them into the single snapshot the building
-// hologram and focus panel render. Pure: no fetching, no React.
-
-const ONLINE_STATES = new Set(['online', 'running']);
-
-const sum = (values) => values.reduce((acc, v) => acc + (Number.isFinite(v) ? v : 0), 0);
-
-/**
- * Aggregate an app's per-process PM2 metrics into one building-level snapshot.
- *
- * CPU and memory sum across ONLINE processes only — a stopped or errored worker
- * reports no live usage, and counting it as 0 would silently deflate a hot app's
- * numbers. Uptime is the MINIMUM uptime among online processes: the honest "how
- * long has this whole app been stable" reading when any worker has recently
- * restarted. Restarts count every process (historical signal, live or not).
- *
- * @param {object|null} app - enriched app record (`pm2Status` from GET /api/apps)
- * @returns {{hasMetrics: boolean, totalProcs: number, onlineProcs: number,
- * cpuPercent: number|null, memBytes: number, uptimeMs: number|null,
- * restarts: number, unstableRestarts: number}}
- * `hasMetrics` is false when the app carries no PM2 status at all (non-PM2 apps,
- * archived shells, failed reads) so callers can omit the rows entirely instead of
- * rendering dashes.
- */
-export function computeAppMetrics(app) {
- const statuses = Object.values(app?.pm2Status || {});
- const online = statuses.filter((p) => ONLINE_STATES.has(p?.status));
- const uptimes = online.map((p) => p?.uptime).filter(Number.isFinite);
-
- return {
- hasMetrics: statuses.length > 0,
- totalProcs: statuses.length,
- onlineProcs: online.length,
- cpuPercent: online.length ? Math.round(sum(online.map((p) => p?.cpu)) * 10) / 10 : null,
- memBytes: sum(online.map((p) => p?.memory)),
- uptimeMs: uptimes.length ? Math.min(...uptimes) : null,
- restarts: sum(statuses.map((p) => p?.restarts)),
- unstableRestarts: sum(statuses.map((p) => p?.unstableRestarts)),
- };
-}
-
-/**
- * Stress tone for a live metric pair, shared by the hologram row and the focus
- * panel stat blocks so a hot building reads the same everywhere. Thresholds are
- * deliberately coarse — this is glanceable atmosphere, not monitoring.
- */
-export function cpuTone(cpuPercent) {
- if (!Number.isFinite(cpuPercent)) return 'idle';
- if (cpuPercent >= 85) return 'hot';
- if (cpuPercent >= 40) return 'busy';
- return 'calm';
-}
-
-const SIGNAL_COLORS = Object.freeze({
- errored: '#f43f5e',
- hot: '#ef4444',
- busy: '#f59e0b',
- online: '#10b981',
- idle: '#64748b',
-});
-
-export function hasPm2Error(pm2Status) {
- return Object.values(pm2Status || {}).some((p) => p?.status === 'errored' || p?.status === 'error');
-}
-
-/**
- * Glanceable façade/rooftop signal for a building. Playback hides live CPU/restart
- * atmosphere so a historical frame doesn't grow smoke from today's metrics; the
- * snapshot's own `status` (and any PM2 error on that frame) still paints the LED.
- */
-export function buildingSignalTone({ status, metrics, pm2Status, playback = false } = {}) {
- const pm2Errored = hasPm2Error(pm2Status);
- const errored = status === 'errored' || pm2Errored || (!playback && (metrics?.unstableRestarts || 0) > 0);
- const cpu = !playback && metrics?.hasMetrics ? cpuTone(metrics.cpuPercent) : 'idle';
- const hot = cpu === 'hot';
- const busy = cpu === 'busy';
- const tone = errored ? 'errored' : hot ? 'hot' : busy ? 'busy' : status === 'online' ? 'online' : 'idle';
- // Playback keeps the snapshot LED color but drops live atmosphere (pulse/smoke/sparks)
- // so a historical frame does not grow today's CPU plume.
- return {
- tone,
- color: SIGNAL_COLORS[tone],
- pulsing: !playback && (errored || hot || busy),
- smoke: !playback && hot,
- sparks: !playback && errored,
- };
-}
diff --git a/client/src/utils/openWorldAppMetrics.test.js b/client/src/utils/openWorldAppMetrics.test.js
deleted file mode 100644
index a89c35a945..0000000000
--- a/client/src/utils/openWorldAppMetrics.test.js
+++ /dev/null
@@ -1,147 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import { computeAppMetrics, cpuTone, hasPm2Error, buildingSignalTone } from './openWorldAppMetrics';
-
-describe('computeAppMetrics', () => {
- it('sums cpu/memory across online processes and takes the minimum uptime', () => {
- const app = {
- pm2Status: {
- web: { status: 'online', cpu: 12.4, memory: 150 * 1024 * 1024, uptime: 5000 },
- worker: { status: 'online', cpu: 30.2, memory: 50 * 1024 * 1024, uptime: 1000 },
- },
- };
- expect(computeAppMetrics(app)).toMatchObject({
- hasMetrics: true,
- totalProcs: 2,
- onlineProcs: 2,
- cpuPercent: 42.6,
- memBytes: 200 * 1024 * 1024,
- // The youngest online process bounds "how long the whole app has been stable".
- uptimeMs: 1000,
- });
- });
-
- it('excludes non-online processes from live usage but keeps their restarts', () => {
- const app = {
- pm2Status: {
- web: { status: 'online', cpu: 10, memory: 1024, uptime: 60_000 },
- worker: { status: 'errored', cpu: 99, memory: 999_999, uptime: 5, restarts: 3, unstableRestarts: 2 },
- },
- };
- const m = computeAppMetrics(app);
- expect(m.onlineProcs).toBe(1);
- expect(m.cpuPercent).toBe(10);
- expect(m.memBytes).toBe(1024);
- expect(m.uptimeMs).toBe(60_000);
- expect(m.restarts).toBe(3);
- expect(m.unstableRestarts).toBe(2);
- });
-
- it('reports null cpu/uptime (not zero) when nothing is online', () => {
- const app = {
- pm2Status: {
- web: { status: 'stopped', cpu: 0, memory: 0 },
- },
- };
- const m = computeAppMetrics(app);
- expect(m.hasMetrics).toBe(true);
- expect(m.cpuPercent).toBeNull();
- expect(m.uptimeMs).toBeNull();
- expect(m.memBytes).toBe(0);
- });
-
- it('flags no metrics for non-PM2 / failed-read apps', () => {
- expect(computeAppMetrics({}).hasMetrics).toBe(false);
- expect(computeAppMetrics({ pm2Status: {} }).hasMetrics).toBe(false);
- expect(computeAppMetrics(null).hasMetrics).toBe(false);
- });
-
- it('tolerates missing numeric fields on status entries', () => {
- const app = { pm2Status: { web: { status: 'online' } } };
- const m = computeAppMetrics(app);
- expect(m.cpuPercent).toBe(0);
- expect(m.memBytes).toBe(0);
- expect(m.uptimeMs).toBeNull();
- });
-});
-
-describe('cpuTone', () => {
- it('buckets by threshold with an idle bucket for absent data', () => {
- expect(cpuTone(null)).toBe('idle');
- expect(cpuTone(0)).toBe('calm');
- expect(cpuTone(39.9)).toBe('calm');
- expect(cpuTone(40)).toBe('busy');
- expect(cpuTone(84.9)).toBe('busy');
- expect(cpuTone(85)).toBe('hot');
- });
-});
-
-describe('hasPm2Error', () => {
- it('treats errored and error process statuses as a PM2 error', () => {
- expect(hasPm2Error({ web: { status: 'online' } })).toBe(false);
- expect(hasPm2Error({ web: { status: 'errored' } })).toBe(true);
- expect(hasPm2Error({ web: { status: 'error' } })).toBe(true);
- expect(hasPm2Error(null)).toBe(false);
- });
-});
-
-describe('buildingSignalTone', () => {
- const hotMetrics = { hasMetrics: true, cpuPercent: 92, unstableRestarts: 0 };
- const calmMetrics = { hasMetrics: true, cpuPercent: 12, unstableRestarts: 0 };
-
- it('maps a healthy online app to a calm green LED with no rooftop effects', () => {
- expect(buildingSignalTone({
- status: 'online',
- metrics: calmMetrics,
- pm2Status: { web: { status: 'online' } },
- })).toMatchObject({
- tone: 'online',
- color: '#10b981',
- pulsing: false,
- smoke: false,
- sparks: false,
- });
- });
-
- it('raises smoke on a hot CPU and sparks on a PM2 error', () => {
- expect(buildingSignalTone({
- status: 'online',
- metrics: hotMetrics,
- pm2Status: { web: { status: 'online' } },
- })).toMatchObject({ tone: 'hot', pulsing: true, smoke: true, sparks: false });
-
- expect(buildingSignalTone({
- status: 'online',
- metrics: calmMetrics,
- pm2Status: { web: { status: 'errored' } },
- })).toMatchObject({ tone: 'errored', pulsing: true, smoke: false, sparks: true });
- });
-
- it('hides live CPU smoke during playback while keeping the snapshot status LED', () => {
- expect(buildingSignalTone({
- status: 'online',
- metrics: hotMetrics,
- pm2Status: { web: { status: 'online' } },
- playback: true,
- })).toMatchObject({
- tone: 'online',
- pulsing: false,
- smoke: false,
- sparks: false,
- });
- });
-
- it('keeps a snapshot error LED during playback without live sparks or pulse', () => {
- expect(buildingSignalTone({
- status: 'online',
- metrics: hotMetrics,
- pm2Status: { web: { status: 'errored' } },
- playback: true,
- })).toMatchObject({
- tone: 'errored',
- color: '#f43f5e',
- pulsing: false,
- smoke: false,
- sparks: false,
- });
- });
-});
diff --git a/client/src/utils/openWorldArtifacts.js b/client/src/utils/openWorldArtifacts.js
deleted file mode 100644
index 6f8b33c6eb..0000000000
--- a/client/src/utils/openWorldArtifacts.js
+++ /dev/null
@@ -1,132 +0,0 @@
-// Pure, deterministic helpers for OpenWorld's "earned artifacts" (roadmap 3.5): a small
-// "Hall of Achievements" cluster of trophies/statues that only appear once a milestone is
-// earned. Artifacts are DERIVED from data the city already has — no new endpoint:
-// • level milestones — D&D-style character level crossing a threshold (level-up statues)
-// • completed-goal milestones — every Nth completed life goal (achievement trophies)
-// Nothing earned → empty cluster (no crash). No three.js / React imports so the topology is
-// unit-testable (mirrors openWorldGoalMonuments.js / openWorldProductivity.js).
-
-import { levelFromXP } from './characterXp';
-import { gridIndexToPosition } from './openWorldDistrictLayout';
-import { PARCELS } from './openWorldPlan';
-
-// Hall of Achievements — a clear cluster in the +X / -Z quadrant, between the task-queue,
-// health tower, goal-monument row, and voice beacon. Artifacts lay out in a tight grid
-// centered on this base, anchored by the master plan (openWorldPlan.js).
-export const ARTIFACTS = {
- base: PARCELS.artifacts.anchor, // center of the cluster
- spacing: 6, // distance between adjacent pedestals (both x and z)
- columns: 3, // grid width before wrapping to the next row (toward -Z)
- pedestalWidth: 2,
- pedestalHeight: 1.2,
- emblemSize: 1.4, // size of the glowing emblem atop a pedestal
-};
-
-// Tiers drive the emblem color + glow so a richer milestone reads brighter. Colors reuse the
-// PortOS Tailwind design tokens.
-const TIERS = {
- bronze: { color: '#f59e0b', intensity: 0.45 }, // port-warning
- silver: { color: '#94a3b8', intensity: 0.6 }, // slate-light
- gold: { color: '#22c55e', intensity: 0.85 }, // port-success
-};
-
-// Level-up milestones: a statue per crossed level threshold. Below level 2 nothing is earned
-// (level 1 is the starting state). Higher levels read as richer tiers.
-export const LEVEL_MILESTONES = [
- { level: 2, tier: 'bronze', label: 'NOVICE' },
- { level: 5, tier: 'silver', label: 'ADEPT' },
- { level: 10, tier: 'gold', label: 'MASTER' },
-];
-
-// Completed-goal milestones: a trophy for every Nth completed life goal.
-export const GOAL_MILESTONES = [
- { count: 1, tier: 'bronze', label: 'FIRST GOAL' },
- { count: 5, tier: 'silver', label: '5 GOALS' },
- { count: 10, tier: 'gold', label: '10 GOALS' },
-];
-
-// Coerce a value to a finite number or return null (the "absent" sentinel) so an absent field
-// never collapses into a real 0.
-function finiteOrNull(value) {
- return typeof value === 'number' && Number.isFinite(value) ? value : null;
-}
-
-// Effective character level. The level is age-based now (#2673): a finite `level` is the
-// age-derived value; an explicit `null` means the birthDate is unset, so age — the ONLY level
-// source — is unknown and we return null WITHOUT resurrecting an XP-derived level (otherwise
-// XP would silently unlock level trophies/eggs while the HUD shows "LV —"). Only an ABSENT
-// `level` field (a legacy payload that predates age-based level) falls back to XP.
-export function effectiveLevel(character) {
- const lvl = character?.level;
- // Any finite nonnegative level is authoritative — including 0, a legitimate age level for a
- // birthDate less than a year ago. (`>= 1` would reject it and let XP unlock level artifacts.)
- if (Number.isFinite(lvl) && lvl >= 0) return Math.floor(lvl);
- if (lvl === null) return null;
- const xp = finiteOrNull(character?.xp);
- if (xp === null) return null;
- return levelFromXP(xp);
-}
-
-// Count completed goals from the goals payload. Accepts either the API wrapper `{ goals: [] }`
-// or a bare array; a missing/garbage input counts as 0.
-export function completedGoalCount(goals) {
- const list = Array.isArray(goals) ? goals : Array.isArray(goals?.goals) ? goals.goals : [];
- return list.filter((g) => g && typeof g === 'object' && g.status === 'completed').length;
-}
-
-// Build the list of EARNED artifact descriptors (kind/label/tier/threshold) from the three
-// inputs, before placement. Deterministic and side-effect-free.
-export function earnedArtifacts({ character, goals } = {}) {
- const earned = [];
-
- const level = effectiveLevel(character);
- if (level !== null) {
- for (const m of LEVEL_MILESTONES) {
- if (level >= m.level) {
- earned.push({ id: `level-${m.level}`, kind: 'level', tier: m.tier, label: m.label, threshold: m.level });
- }
- }
- }
-
- const completed = completedGoalCount(goals);
- for (const m of GOAL_MILESTONES) {
- if (completed >= m.count) {
- earned.push({ id: `goals-${m.count}`, kind: 'goal', tier: m.tier, label: m.label, threshold: m.count });
- }
- }
-
- return earned;
-}
-
-// Place a descriptor into the cluster grid. `index` is the 0-based slot; the grid fills left→
-// right across ARTIFACTS.columns, then wraps to the next row toward -Z. Centered on base.x.
-export function placeArtifact(descriptor, index) {
- const tier = TIERS[descriptor.tier] || TIERS.bronze;
- return {
- ...descriptor,
- color: tier.color,
- intensity: tier.intensity,
- position: gridIndexToPosition(index, {
- base: ARTIFACTS.base,
- columns: ARTIFACTS.columns,
- spacing: ARTIFACTS.spacing,
- rowDir: -1, // rows wrap toward -Z
- }),
- };
-}
-
-// Full derived view-model for the component. Injects all inputs; an all-absent / nothing-earned
-// state yields an empty cluster (`hasData: false`) rather than a crash. Ordering is stable
-// (level → goal, each ascending threshold) so the cluster doesn't reshuffle across
-// refetches.
-export function computeArtifacts({ character, goals } = {}) {
- const descriptors = earnedArtifacts({ character, goals });
- const artifacts = descriptors.map((d, i) => placeArtifact(d, i));
-
- return {
- base: ARTIFACTS.base,
- artifacts,
- total: artifacts.length,
- hasData: artifacts.length > 0,
- };
-}
diff --git a/client/src/utils/openWorldArtifacts.test.js b/client/src/utils/openWorldArtifacts.test.js
deleted file mode 100644
index 3ab030895d..0000000000
--- a/client/src/utils/openWorldArtifacts.test.js
+++ /dev/null
@@ -1,159 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- ARTIFACTS,
- LEVEL_MILESTONES,
- GOAL_MILESTONES,
- effectiveLevel,
- completedGoalCount,
- earnedArtifacts,
- placeArtifact,
- computeArtifacts,
-} from './openWorldArtifacts';
-
-const completedGoals = (n) =>
- Array.from({ length: n }, (_, i) => ({ id: `g-${i}`, status: 'completed' }));
-
-describe('effectiveLevel', () => {
- it('trusts a stored, consistent level', () => {
- expect(effectiveLevel({ level: 7 })).toBe(7);
- expect(effectiveLevel({ level: 3.9 })).toBe(3); // floored
- });
-
- it('derives level from xp only when the level field is ABSENT (legacy payload)', () => {
- expect(effectiveLevel({ xp: 300 })).toBe(2); // 300 xp → level 2
- expect(effectiveLevel({ xp: 0 })).toBe(1);
- });
-
- it('returns null for an explicit null level (age unknown) — no XP fallback', () => {
- // Age-based level (#2673): birthDate unset → level: null. XP must not resurrect a level,
- // or trophies/eggs would unlock while the HUD shows "LV —".
- expect(effectiveLevel({ level: null, xp: 999999 })).toBeNull();
- expect(effectiveLevel({ level: null, xp: 0 })).toBeNull();
- });
-
- it('treats age level 0 (birthDate < 1yr ago) as authoritative, not an XP fallback', () => {
- expect(effectiveLevel({ level: 0, xp: 999999 })).toBe(0);
- });
-
- it('returns null when neither level nor xp is usable', () => {
- expect(effectiveLevel(null)).toBeNull();
- expect(effectiveLevel({})).toBeNull();
- expect(effectiveLevel({ level: null, xp: 'nope' })).toBeNull();
- });
-});
-
-describe('completedGoalCount', () => {
- it('counts only completed goals', () => {
- const goals = [
- { id: 'a', status: 'completed' },
- { id: 'b', status: 'active' },
- { id: 'c', status: 'completed' },
- { id: 'd', status: 'abandoned' },
- ];
- expect(completedGoalCount(goals)).toBe(2);
- });
-
- it('accepts the API wrapper { goals: [] }', () => {
- expect(completedGoalCount({ goals: completedGoals(3) })).toBe(3);
- });
-
- it('is 0 for missing / garbage / null-entry input', () => {
- for (const bad of [null, undefined, 'nope', 42, {}]) {
- expect(completedGoalCount(bad)).toBe(0);
- }
- expect(completedGoalCount([null, 'x', { status: 'completed' }])).toBe(1);
- });
-});
-
-describe('earnedArtifacts — thresholds', () => {
- it('returns nothing when nothing is earned', () => {
- expect(earnedArtifacts({})).toEqual([]);
- expect(earnedArtifacts({ character: { level: 1 }, goals: [] })).toEqual([]);
- });
-
- it('earns level milestones at/above each threshold', () => {
- const ids = earnedArtifacts({ character: { level: 5 } }).map((a) => a.id);
- expect(ids).toContain('level-2');
- expect(ids).toContain('level-5');
- expect(ids).not.toContain('level-10');
- });
-
- it('does not earn a level statue at level 1', () => {
- expect(earnedArtifacts({ character: { level: 1 } })).toEqual([]);
- });
-
- it('earns goal milestones for completed-goal counts', () => {
- const ids = earnedArtifacts({ goals: completedGoals(5) }).map((a) => a.id);
- expect(ids).toContain('goals-1');
- expect(ids).toContain('goals-5');
- expect(ids).not.toContain('goals-10');
- });
-
- it('combines level and goal sources in stable order', () => {
- const earned = earnedArtifacts({
- character: { level: 2 },
- goals: completedGoals(1),
- });
- expect(earned.map((a) => a.kind)).toEqual(['level', 'goal']);
- expect(earned.map((a) => a.id)).toEqual(['level-2', 'goals-1']);
- });
-
- it('attaches a tier + label to each descriptor', () => {
- const [a] = earnedArtifacts({ character: { level: 2 } });
- expect(a.tier).toBe('bronze');
- expect(a.label).toBe('NOVICE');
- expect(a.threshold).toBe(2);
- });
-});
-
-describe('placeArtifact', () => {
- it('centers the first row on base.x and resolves the tier color', () => {
- const placed = placeArtifact({ id: 'x', kind: 'level', tier: 'gold', label: 'L' }, 1);
- // index 1 is the middle column of a 3-wide grid → centered on base.x
- expect(placed.position[0]).toBeCloseTo(ARTIFACTS.base[0]);
- expect(placed.position[2]).toBe(ARTIFACTS.base[2]);
- expect(placed.color).toBe('#22c55e');
- expect(placed.intensity).toBeGreaterThan(0);
- });
-
- it('wraps to the next row toward -Z after columns are filled', () => {
- const first = placeArtifact({ id: 'a', tier: 'bronze' }, 0);
- const wrapped = placeArtifact({ id: 'b', tier: 'bronze' }, ARTIFACTS.columns);
- expect(wrapped.position[0]).toBeCloseTo(first.position[0]); // same column
- expect(wrapped.position[2]).toBe(ARTIFACTS.base[2] - ARTIFACTS.spacing); // one row back
- });
-
- it('falls back to the bronze tier for an unknown tier', () => {
- const placed = placeArtifact({ id: 'x', tier: 'unknown' }, 0);
- expect(placed.color).toBe('#f59e0b');
- });
-});
-
-describe('computeArtifacts', () => {
- it('handles all-absent input as an empty cluster (no crash)', () => {
- const vm = computeArtifacts({});
- expect(vm.artifacts).toEqual([]);
- expect(vm.total).toBe(0);
- expect(vm.hasData).toBe(false);
- expect(vm.base).toEqual(ARTIFACTS.base);
- });
-
- it('handles a fully-undefined call', () => {
- const vm = computeArtifacts();
- expect(vm.hasData).toBe(false);
- });
-
- it('places one artifact per earned milestone', () => {
- const vm = computeArtifacts({
- character: { level: 10 }, // 3 level milestones
- goals: completedGoals(10), // 3 goal milestones
- });
- expect(vm.total).toBe(LEVEL_MILESTONES.length + GOAL_MILESTONES.length);
- expect(vm.hasData).toBe(true);
- for (const a of vm.artifacts) {
- expect(a.position).toHaveLength(3);
- expect(typeof a.color).toBe('string');
- }
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldBackupVault.js b/client/src/utils/openWorldBackupVault.js
deleted file mode 100644
index d9a8b89d5e..0000000000
--- a/client/src/utils/openWorldBackupVault.js
+++ /dev/null
@@ -1,92 +0,0 @@
-// Pure, deterministic helpers for OpenWorld's backup-vault landmark (roadmap 2.3):
-// a small monument west of downtown whose color, label, and pulse reflect backup
-// health. The vault derives "staleness" from the time since the last snapshot, so a
-// backup that hasn't run in too long glows red and reads as needing attention. No
-// three.js / React imports so the topology is unit-testable (mirrors openWorldFederation.js).
-
-import { PARCELS } from './openWorldPlan';
-
-export const VAULT = {
- position: PARCELS.backupVault.anchor, // west of the building grid, anchored by the master plan (openWorldPlan.js)
- width: 5,
- height: 8,
- // Staleness thresholds, in ms since the last snapshot. A fresh backup is healthy;
- // between fresh and stale it ages to amber; past `staleMs` it goes red.
- freshMs: 24 * 60 * 60 * 1000, // < 1 day → healthy
- staleMs: 3 * 24 * 60 * 60 * 1000, // ≥ 3 days → stale
-};
-
-// Color per health classification — reuses the PortOS Tailwind design tokens so the
-// vault speaks the same visual language as the rest of the UI.
-const HEALTH_COLORS = {
- ok: '#22c55e', // port-success — recent snapshot
- aging: '#f59e0b', // port-warning — getting old
- stale: '#ef4444', // port-error — overdue
- error: '#ef4444', // port-error — last run failed
- degraded: '#f59e0b', // port-warning — files saved but DB dump failed
- never: '#64748b', // slate — never backed up / not configured
- running: '#3b82f6', // port-accent — a backup is in flight
-};
-
-// Map persisted backup state → a health classification. `state.status` is the stored
-// status ('never' | 'ok' | 'degraded' | 'error'); `state.lastRun` is the ISO timestamp of the last
-// run (or null); `state.running` is set true while a backup is in flight (socket-driven).
-// `now` is injected so the staleness derivation is deterministic in tests.
-export function vaultHealth(state, now = Date.now()) {
- if (state?.running) return 'running';
- const status = state?.status || 'never';
- if (status === 'error') return 'error';
- // 'degraded' = files backed up but the DB dump failed — alert, don't read as
- // PROTECTED. Classified before the staleness path so a recent degraded run
- // (fresh lastRun) can't fall through to 'ok'.
- if (status === 'degraded') return 'degraded';
- if (status === 'never' || !state?.lastRun) return 'never';
- const last = new Date(state.lastRun).getTime();
- if (!Number.isFinite(last)) return 'never';
- const age = now - last;
- if (age >= VAULT.staleMs) return 'stale';
- if (age >= VAULT.freshMs) return 'aging';
- return 'ok';
-}
-
-export function vaultColor(health) {
- return HEALTH_COLORS[health] || HEALTH_COLORS.never;
-}
-
-// Should the vault read as needing attention (urgent pulse, brighter glow)?
-export function vaultIsAlerting(health) {
- return health === 'stale' || health === 'error' || health === 'degraded';
-}
-
-// Short uppercase label rendered under the monument.
-export function vaultStatusLabel(health) {
- switch (health) {
- case 'running': return 'BACKING UP';
- case 'ok': return 'PROTECTED';
- case 'aging': return 'AGING';
- case 'stale': return 'STALE';
- case 'error': return 'FAILED';
- case 'degraded': return 'DB FAILED';
- default: return 'NO BACKUP';
- }
-}
-
-// Full derived view-model for the component: geometry + health + color + alert flag +
-// emissive intensity (brighter while running or alerting, calm otherwise). `now` is
-// injected so the whole view-model is deterministic under test.
-export function computeBackupVault(state, now = Date.now()) {
- const health = vaultHealth(state, now);
- const alerting = vaultIsAlerting(health);
- return {
- position: VAULT.position,
- width: VAULT.width,
- height: VAULT.height,
- health,
- color: vaultColor(health),
- alerting,
- running: health === 'running',
- statusLabel: vaultStatusLabel(health),
- lastRun: state?.lastRun ?? null,
- intensity: health === 'running' ? 1 : alerting ? 0.85 : 0.5,
- };
-}
diff --git a/client/src/utils/openWorldBackupVault.test.js b/client/src/utils/openWorldBackupVault.test.js
deleted file mode 100644
index 0154974f7e..0000000000
--- a/client/src/utils/openWorldBackupVault.test.js
+++ /dev/null
@@ -1,134 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- VAULT,
- vaultHealth,
- vaultColor,
- vaultIsAlerting,
- vaultStatusLabel,
- computeBackupVault,
-} from './openWorldBackupVault';
-
-const NOW = new Date('2026-06-03T12:00:00Z').getTime();
-const hoursAgo = (h) => new Date(NOW - h * 60 * 60 * 1000).toISOString();
-const daysAgo = (d) => new Date(NOW - d * 24 * 60 * 60 * 1000).toISOString();
-
-describe('vaultHealth', () => {
- it('returns "never" when there is no state, no lastRun, or status never', () => {
- expect(vaultHealth(undefined, NOW)).toBe('never');
- expect(vaultHealth({}, NOW)).toBe('never');
- expect(vaultHealth({ status: 'never', lastRun: null }, NOW)).toBe('never');
- });
-
- it('returns "never" when lastRun is an unparseable timestamp', () => {
- expect(vaultHealth({ status: 'ok', lastRun: 'not-a-date' }, NOW)).toBe('never');
- });
-
- it('returns "ok" for a snapshot inside the fresh window', () => {
- expect(vaultHealth({ status: 'ok', lastRun: hoursAgo(2) }, NOW)).toBe('ok');
- });
-
- it('ages to "aging" between the fresh and stale thresholds', () => {
- expect(vaultHealth({ status: 'ok', lastRun: daysAgo(2) }, NOW)).toBe('aging');
- });
-
- it('goes "stale" once past the stale threshold', () => {
- expect(vaultHealth({ status: 'ok', lastRun: daysAgo(5) }, NOW)).toBe('stale');
- });
-
- it('treats the thresholds as inclusive lower bounds', () => {
- expect(vaultHealth({ status: 'ok', lastRun: new Date(NOW - VAULT.freshMs).toISOString() }, NOW)).toBe('aging');
- expect(vaultHealth({ status: 'ok', lastRun: new Date(NOW - VAULT.staleMs).toISOString() }, NOW)).toBe('stale');
- });
-
- it('reports "error" when the last run failed, regardless of age', () => {
- expect(vaultHealth({ status: 'error', lastRun: hoursAgo(1) }, NOW)).toBe('error');
- });
-
- it('reports "running" when a backup is in flight, overriding everything', () => {
- expect(vaultHealth({ status: 'error', lastRun: daysAgo(9), running: true }, NOW)).toBe('running');
- });
-
- it('reports "degraded" when files saved but the DB dump failed, even on a fresh run', () => {
- expect(vaultHealth({ status: 'degraded', lastRun: hoursAgo(1) }, NOW)).toBe('degraded');
- });
-});
-
-describe('vaultColor', () => {
- it('maps each health to a distinct token; stale and error share the error red', () => {
- expect(vaultColor('ok')).toBe('#22c55e');
- expect(vaultColor('aging')).toBe('#f59e0b');
- expect(vaultColor('stale')).toBe('#ef4444');
- expect(vaultColor('error')).toBe('#ef4444');
- expect(vaultColor('running')).toBe('#3b82f6');
- expect(vaultColor('never')).toBe('#64748b');
- expect(vaultColor('degraded')).toBe('#f59e0b');
- });
-
- it('falls back to the never color for an unknown health', () => {
- expect(vaultColor('bogus')).toBe(vaultColor('never'));
- });
-});
-
-describe('vaultIsAlerting', () => {
- it('alerts on stale, error, or degraded', () => {
- expect(vaultIsAlerting('stale')).toBe(true);
- expect(vaultIsAlerting('error')).toBe(true);
- expect(vaultIsAlerting('degraded')).toBe(true);
- expect(vaultIsAlerting('ok')).toBe(false);
- expect(vaultIsAlerting('aging')).toBe(false);
- expect(vaultIsAlerting('running')).toBe(false);
- expect(vaultIsAlerting('never')).toBe(false);
- });
-});
-
-describe('vaultStatusLabel', () => {
- it('gives a label for every health and a default for unknown', () => {
- expect(vaultStatusLabel('running')).toBe('BACKING UP');
- expect(vaultStatusLabel('ok')).toBe('PROTECTED');
- expect(vaultStatusLabel('aging')).toBe('AGING');
- expect(vaultStatusLabel('stale')).toBe('STALE');
- expect(vaultStatusLabel('error')).toBe('FAILED');
- expect(vaultStatusLabel('degraded')).toBe('DB FAILED');
- expect(vaultStatusLabel('never')).toBe('NO BACKUP');
- expect(vaultStatusLabel('bogus')).toBe('NO BACKUP');
- });
-});
-
-describe('computeBackupVault', () => {
- it('carries the fixed geometry through unchanged', () => {
- const vm = computeBackupVault({ status: 'ok', lastRun: hoursAgo(1) }, NOW);
- expect(vm.position).toEqual(VAULT.position);
- expect(vm.width).toBe(VAULT.width);
- expect(vm.height).toBe(VAULT.height);
- });
-
- it('a fresh backup is calm, protected, and not alerting', () => {
- const vm = computeBackupVault({ status: 'ok', lastRun: hoursAgo(1) }, NOW);
- expect(vm.health).toBe('ok');
- expect(vm.alerting).toBe(false);
- expect(vm.running).toBe(false);
- expect(vm.statusLabel).toBe('PROTECTED');
- expect(vm.intensity).toBe(0.5);
- });
-
- it('a stale backup alerts and burns brighter', () => {
- const vm = computeBackupVault({ status: 'ok', lastRun: daysAgo(5) }, NOW);
- expect(vm.health).toBe('stale');
- expect(vm.alerting).toBe(true);
- expect(vm.intensity).toBe(0.85);
- expect(vm.color).toBe('#ef4444');
- });
-
- it('a running backup is the brightest and exposes running=true', () => {
- const vm = computeBackupVault({ status: 'ok', lastRun: hoursAgo(1), running: true }, NOW);
- expect(vm.health).toBe('running');
- expect(vm.running).toBe(true);
- expect(vm.intensity).toBe(1);
- });
-
- it('passes lastRun through for the time-since label, null when never', () => {
- expect(computeBackupVault({ status: 'ok', lastRun: hoursAgo(3) }, NOW).lastRun).toBe(hoursAgo(3));
- expect(computeBackupVault({ status: 'never' }, NOW).lastRun).toBeNull();
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldChronotype.js b/client/src/utils/openWorldChronotype.js
deleted file mode 100644
index 1a658e2ddc..0000000000
--- a/client/src/utils/openWorldChronotype.js
+++ /dev/null
@@ -1,138 +0,0 @@
-// Pure, deterministic helpers for OpenWorld's chronotype energy overlay (roadmap 3.1):
-// the city brightens and quickens during the user's peak focus hours and dims/slows
-// during wind-down and sleep. Energy is derived from the digital-twin chronotype
-// profile's recommended daily schedule (wake / peak focus / wind-down / sleep). No
-// three.js / React imports so the topology is unit-testable (mirrors openWorldBackupVault.js).
-//
-// The hour-of-day is ALWAYS injected as a parameter — no `new Date()` here — so the
-// energy curve is deterministic in tests. The component computes the live hour and
-// passes it in.
-//
-// `computeChronotypeEnergy` is the module's ONLY export: everything below it is an
-// internal step of that one calculation, and keeping it unexported keeps the flat
-// `client/src/utils/index.js` barrel free of generic names like `parseHour` that
-// would collide with a future module.
-
-import { clamp } from './formatters.js';
-
-// Sentinel energy for "no usable profile" — distinct from any real curve value so a
-// missing profile is recognizable. It maps to NEUTRAL_MODIFIERS (no visible change),
-// NOT to peak brightness, so an unconfigured city looks untouched rather than washed out.
-const NEUTRAL_ENERGY = 1.0;
-
-// Tasteful clamp ranges so the overlay stays atmospheric, never washing out or
-// blacking out the existing scene. Brightness rides slightly above/below 1; tempo
-// (animation-speed multiplier) is gentler still.
-const ENERGY_RANGE = {
- brightnessMin: 0.7,
- brightnessMax: 1.15,
- tempoMin: 0.8,
- tempoMax: 1.15,
-};
-
-// What the overlay applies when there's no usable chronotype profile: a true no-op —
-// brightness and tempo at 1.0 so the scene renders exactly as it would without the
-// overlay. Keeps "unconfigured / failed to fetch" visually distinct from "low energy."
-const NEUTRAL_MODIFIERS = { energy: NEUTRAL_ENERGY, brightness: 1.0, tempo: 1.0 };
-
-// Parse "HH:MM" → fractional hours in [0,24). Returns NaN for unparseable input.
-// Hours past midnight that belong to "today's" late night (e.g. a 00:30 sleep time)
-// are returned as-is (0.5); callers that need a continuous timeline normalize.
-function parseHour(str) {
- if (typeof str !== 'string') return NaN;
- const [h, m] = str.split(':').map(Number);
- if (!Number.isFinite(h) || !Number.isFinite(m)) return NaN;
- const val = h + m / 60;
- return val >= 0 && val < 24 ? val : NaN;
-}
-
-// Circular distance between two hours on a 24h clock (shortest arc), in [0,12].
-function hourDistance(a, b) {
- const d = Math.abs(a - b) % 24;
- return Math.min(d, 24 - d);
-}
-
-// Build the set of energy anchor points from the chronotype recommendations.
-// Each anchor is { hour, energy } where energy ∈ [0,1]: 1 at the center of peak
-// focus, low through wind-down and sleep, mid on waking. Returns null when the
-// profile lacks the timing fields we need (caller falls back to neutral).
-function buildAnchors(profile) {
- const rec = profile?.recommendations;
- if (!rec) return null;
-
- const wake = parseHour(rec.wakeTime);
- const peakStart = parseHour(rec.peakFocusStart);
- const peakEnd = parseHour(rec.peakFocusEnd);
- const windDown = parseHour(rec.windDownStart);
- const sleep = parseHour(rec.sleepTime);
-
- const anchors = [];
-
- // Peak focus center → maximum energy. This is the anchor the overlay is built
- // around, so we require at least the peak window to be present.
- if (Number.isFinite(peakStart) && Number.isFinite(peakEnd)) {
- const center = peakStart + ((peakEnd - peakStart + 24) % 24) / 2;
- anchors.push({ hour: center % 24, energy: 1.0 });
- } else {
- return null;
- }
-
- // Waking → ramping up (mid energy).
- if (Number.isFinite(wake)) anchors.push({ hour: wake, energy: 0.55 });
-
- // Wind-down → low energy.
- if (Number.isFinite(windDown)) anchors.push({ hour: windDown, energy: 0.3 });
-
- // Sleep → lowest energy (recovery / dim city).
- if (Number.isFinite(sleep)) anchors.push({ hour: sleep, energy: 0.12 });
-
- return anchors;
-}
-
-// Given the chronotype profile and the current hour (0..23, fractional ok), compute
-// an energy level in [0,1]. Energy is the inverse-distance-weighted blend of the
-// nearest anchors on the 24h clock — smooth, wrap-around-aware, no hard edges.
-// Returns `null` (sentinel) when there's no usable profile or the hour is non-finite,
-// so callers can distinguish "no profile" from a real curve value that happens to be
-// 1.0 (peak focus center). Callers map null → neutral (no visible change).
-function computeEnergy(profile, hour) {
- const anchors = buildAnchors(profile);
- if (!anchors || !Number.isFinite(hour)) return null;
-
- let weightSum = 0;
- let energySum = 0;
- for (const a of anchors) {
- const dist = hourDistance(hour, a.hour);
- // Exact hit on an anchor returns it directly (avoids divide-by-zero).
- if (dist < 1e-6) return clamp(a.energy, 0, 1);
- const weight = 1 / (dist * dist);
- weightSum += weight;
- energySum += weight * a.energy;
- }
- return clamp(energySum / weightSum, 0, 1);
-}
-
-// Map an energy level 0..1 → the tasteful, clamped display modifiers the overlay
-// applies: a brightness multiplier and a tempo (animation-speed) multiplier. Energy
-// 1 → top of each range, energy 0 → bottom; linear in between. A null/non-finite
-// energy (no usable profile) returns NEUTRAL_MODIFIERS — a true no-op.
-function energyModifiers(energy) {
- if (!Number.isFinite(energy)) return { ...NEUTRAL_MODIFIERS };
- const e = clamp(energy, 0, 1);
- const { brightnessMin, brightnessMax, tempoMin, tempoMax } = ENERGY_RANGE;
- return {
- energy: e,
- brightness: clamp(brightnessMin + e * (brightnessMax - brightnessMin), brightnessMin, brightnessMax),
- tempo: clamp(tempoMin + e * (tempoMax - tempoMin), tempoMin, tempoMax),
- };
-}
-
-// Full derived view-model for the component: energy + brightness + tempo. `hour` is
-// injected so the whole view-model is deterministic under test. A missing/partial
-// profile (or non-finite hour) yields NEUTRAL_MODIFIERS — a true no-op (brightness
-// and tempo at 1.0), so an unconfigured city is untouched rather than washed out or
-// dimmed. A real curve value of exactly 1.0 (peak focus center) still maps to peak
-// brightness because computeEnergy returns null — not 1.0 — for the "no profile" case.
-export function computeChronotypeEnergy(profile, hour) {
- return energyModifiers(computeEnergy(profile, hour));
-}
diff --git a/client/src/utils/openWorldChronotype.test.js b/client/src/utils/openWorldChronotype.test.js
deleted file mode 100644
index 6d487b2210..0000000000
--- a/client/src/utils/openWorldChronotype.test.js
+++ /dev/null
@@ -1,181 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import { computeChronotypeEnergy } from './openWorldChronotype';
-
-// The module's internals (parseHour / computeEnergy / energyModifiers and the range
-// constants) are deliberately NOT exported — computeChronotypeEnergy is the sole
-// public entry point, so every behavior below is exercised through it. The expected
-// bounds are written as literals here rather than imported, so a change to the
-// tasteful ranges has to be re-affirmed in the test instead of silently agreeing
-// with itself.
-const BRIGHTNESS_MIN = 0.7;
-const BRIGHTNESS_MAX = 1.15;
-const TEMPO_MIN = 0.8;
-const TEMPO_MAX = 1.15;
-// A missing/partial profile is a true no-op: brightness and tempo untouched.
-const NEUTRAL = { energy: 1.0, brightness: 1.0, tempo: 1.0 };
-
-// A representative "intermediate" chronotype profile (mirrors the shape returned by
-// GET /api/digital-twin/identity/chronotype — only the recommendations the overlay
-// reads are included).
-const PROFILE = {
- type: 'intermediate',
- recommendations: {
- wakeTime: '07:00',
- sleepTime: '23:00',
- peakFocusStart: '09:30',
- peakFocusEnd: '13:00',
- windDownStart: '21:30',
- },
-};
-// Peak focus center is (9.5 + 13) / 2 = 11.25.
-const PEAK_HOUR = 11.25;
-
-describe('computeChronotypeEnergy — energy curve', () => {
- it('is highest at the peak focus center', () => {
- const atPeak = computeChronotypeEnergy(PROFILE, PEAK_HOUR);
- const atWake = computeChronotypeEnergy(PROFILE, 7);
- const atSleep = computeChronotypeEnergy(PROFILE, 23);
- expect(atPeak.energy).toBeGreaterThan(atWake.energy);
- expect(atPeak.energy).toBeGreaterThan(atSleep.energy);
- expect(atPeak.energy).toBeCloseTo(1.0, 5);
- });
-
- it('is lowest during recovery (sleep) hours', () => {
- const atSleep = computeChronotypeEnergy(PROFILE, 23);
- expect(atSleep.energy).toBeLessThan(computeChronotypeEnergy(PROFILE, PEAK_HOUR).energy);
- expect(atSleep.energy).toBeLessThan(0.5);
- });
-
- it('parses HH:MM recommendations into fractional hours (09:30 peak start ⇒ 11.25 center)', () => {
- // The peak center is the maximum of the curve, so an exact hit at 11.25 proves
- // the ":30" half-hour was parsed as 9.5 rather than truncated to 9 or 10.
- expect(computeChronotypeEnergy(PROFILE, 11.25).energy).toBeCloseTo(1.0, 5);
- expect(computeChronotypeEnergy(PROFILE, 11).energy).toBeLessThan(1.0);
- expect(computeChronotypeEnergy(PROFILE, 11.5).energy).toBeLessThan(1.0);
- });
-
- it('handles wrap-around midnight for an evening chronotype with after-midnight sleep', () => {
- const evening = {
- recommendations: {
- wakeTime: '08:30',
- sleepTime: '00:30', // 12:30 AM — wraps past midnight
- peakFocusStart: '11:00',
- peakFocusEnd: '15:00',
- windDownStart: '23:00',
- },
- };
- // Land exactly on the after-midnight sleep anchor (00:30 → hour 0.5). An exact
- // anchor hit returns that anchor's energy verbatim, so 0.12 proves the wrapped
- // "00:30" was parsed and anchored at 0.5 — a weaker "1 AM is below 0.5" check
- // would still pass if 00:30 were dropped entirely, since the 23:00 wind-down
- // anchor alone keeps the small hours low.
- const atSleepAnchor = computeChronotypeEnergy(evening, 0.5);
- expect(atSleepAnchor.energy).toBeCloseTo(0.12, 10);
- // ...and that low energy maps through the bottom of the display ranges:
- // brightness = 0.7 + 0.12 * (1.15 - 0.7), tempo = 0.8 + 0.12 * (1.15 - 0.8).
- expect(atSleepAnchor.brightness).toBeCloseTo(0.754, 10);
- expect(atSleepAnchor.tempo).toBeCloseTo(0.842, 10);
-
- // The post-midnight small hours read lower than the peak center.
- const at1am = computeChronotypeEnergy(evening, 1);
- const atPeak = computeChronotypeEnergy(evening, 13); // peak center
- expect(at1am.energy).toBeLessThan(atPeak.energy);
- expect(at1am.energy).toBeLessThan(0.5);
- });
-
- it('blends anchors across the midnight seam (circular distance, not absolute)', () => {
- // Only two anchors, and the low one sits exactly on midnight: peak center 12:00,
- // sleep 00:00. Hours 23:00 and 01:00 are one hour from the sleep anchor and
- // eleven from the peak in EITHER direction, so on a 24h clock they must produce
- // the same energy. With plain |a - b| the pre-midnight hour would read as 23
- // hours from sleep and fall to the peak anchor instead — the symmetry below is
- // what distinguishes the two.
- const midnightSleeper = {
- recommendations: { peakFocusStart: '11:00', peakFocusEnd: '13:00', sleepTime: '00:00' },
- };
- const before = computeChronotypeEnergy(midnightSleeper, 23);
- const after = computeChronotypeEnergy(midnightSleeper, 1);
- expect(before.energy).toBeCloseTo(after.energy, 10);
- // Both sit near the sleep anchor's 0.12, nowhere near the peak's 1.0.
- expect(before.energy).toBeLessThan(0.2);
- expect(after.energy).toBeLessThan(0.2);
- });
-});
-
-describe('computeChronotypeEnergy — neutral no-op fallbacks', () => {
- it('returns the neutral no-op for a missing or partial profile (no crash)', () => {
- expect(computeChronotypeEnergy(null, 12)).toEqual(NEUTRAL);
- expect(computeChronotypeEnergy({}, 12)).toEqual(NEUTRAL);
- expect(computeChronotypeEnergy({ recommendations: {} }, 12)).toEqual(NEUTRAL);
- // peak window missing → can't anchor → neutral
- expect(computeChronotypeEnergy({ recommendations: { wakeTime: '07:00' } }, 12)).toEqual(NEUTRAL);
- });
-
- it('returns the neutral no-op when the peak window is unparseable', () => {
- const bad = (peakFocusStart, peakFocusEnd) => ({
- recommendations: { ...PROFILE.recommendations, peakFocusStart, peakFocusEnd },
- });
- expect(computeChronotypeEnergy(bad('not-a-time', '13:00'), 12)).toEqual(NEUTRAL);
- expect(computeChronotypeEnergy(bad('09:30', '24:00'), 12)).toEqual(NEUTRAL);
- expect(computeChronotypeEnergy(bad(null, '13:00'), 12)).toEqual(NEUTRAL);
- expect(computeChronotypeEnergy(bad(undefined, undefined), 12)).toEqual(NEUTRAL);
- });
-
- it('returns the neutral no-op when the hour is not finite', () => {
- expect(computeChronotypeEnergy(PROFILE, NaN)).toEqual(NEUTRAL);
- expect(computeChronotypeEnergy(PROFILE, undefined)).toEqual(NEUTRAL);
- });
-
- it('drops an unparseable secondary anchor rather than falling back to neutral', () => {
- const peak = { peakFocusStart: '09:30', peakFocusEnd: '13:00' };
- const withBadSleep = { recommendations: { ...peak, sleepTime: 'nope' } };
- const withNoSleep = { recommendations: { ...peak } };
- const withGoodSleep = { recommendations: { ...peak, sleepTime: '23:00' } };
- // Evaluate away from every anchor: an exact anchor hit short-circuits before the
- // other anchors are blended, which would hide whether the bad one was dropped.
- const OFF_ANCHOR = 20;
-
- const bad = computeChronotypeEnergy(withBadSleep, OFF_ANCHOR);
- expect(bad).not.toEqual(NEUTRAL);
- // An unparseable sleep time is dropped, leaving the same curve as omitting it...
- expect(bad.energy).toBeCloseTo(computeChronotypeEnergy(withNoSleep, OFF_ANCHOR).energy, 10);
- // ...and a parseable one genuinely changes the curve, so the equality above is
- // evidence the anchor was dropped rather than evidence anchors do nothing.
- expect(bad.energy).toBeGreaterThan(computeChronotypeEnergy(withGoodSleep, OFF_ANCHOR).energy);
- });
-});
-
-describe('computeChronotypeEnergy — display modifiers', () => {
- it('maps the peak focus center to the top of each clamped range', () => {
- const m = computeChronotypeEnergy(PROFILE, PEAK_HOUR);
- expect(m.brightness).toBeCloseTo(BRIGHTNESS_MAX);
- expect(m.tempo).toBeCloseTo(TEMPO_MAX);
- // A real curve value of exactly 1.0 must map to peak brightness, NOT the neutral no-op.
- expect(m.brightness).not.toBe(1.0);
- });
-
- it('peak hour → higher brightness and tempo than a recovery hour', () => {
- const peak = computeChronotypeEnergy(PROFILE, PEAK_HOUR);
- const recovery = computeChronotypeEnergy(PROFILE, 23);
- expect(peak.brightness).toBeGreaterThan(recovery.brightness);
- expect(peak.tempo).toBeGreaterThan(recovery.tempo);
- });
-
- it('keeps energy, brightness and tempo inside the tasteful bounds across the whole day', () => {
- for (let h = 0; h < 24; h += 0.5) {
- const m = computeChronotypeEnergy(PROFILE, h);
- expect(m.energy).toBeGreaterThanOrEqual(0);
- expect(m.energy).toBeLessThanOrEqual(1);
- expect(m.brightness).toBeGreaterThanOrEqual(BRIGHTNESS_MIN);
- expect(m.brightness).toBeLessThanOrEqual(BRIGHTNESS_MAX);
- expect(m.tempo).toBeGreaterThanOrEqual(TEMPO_MIN);
- expect(m.tempo).toBeLessThanOrEqual(TEMPO_MAX);
- }
- });
-
- it('exposes only computeChronotypeEnergy as the module surface', async () => {
- const mod = await import('./openWorldChronotype');
- expect(Object.keys(mod)).toEqual(['computeChronotypeEnergy']);
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldCollectibles.js b/client/src/utils/openWorldCollectibles.js
deleted file mode 100644
index c35d2ac423..0000000000
--- a/client/src/utils/openWorldCollectibles.js
+++ /dev/null
@@ -1,107 +0,0 @@
-// Pure deterministic helpers for OpenWorld's collectible Cyber Shards system.
-// Shards are floating, glowing crystal pickups scattered along roads, plazas, and
-// landmarks. Driving or walking over a shard collects it with particle + audio feedback,
-// increments the session score, and unlocks discovery recognition.
-// No three.js / React imports — pure, testable in node.
-
-import { safeReadJsonSession, safeWriteJsonSession } from '../lib/safeStorage.js';
-import { WORLD } from './openWorldPlan';
-
-export const SHARD_COLLECTION_RADIUS = 2.4;
-export const DEFAULT_SHARD_Y = 1.0;
-
-// Curated deterministic list of collectible Cyber Shards across all major quarters.
-export const CYBER_SHARDS = [
- // Plaza & Central Spine
- { id: 'shard-plaza-n', label: 'Plaza Zenith', x: 0, y: DEFAULT_SHARD_Y, z: -12, color: '#06b6d4', value: 10 },
- { id: 'shard-plaza-s', label: 'Plaza Gateway', x: 0, y: DEFAULT_SHARD_Y, z: 14, color: '#06b6d4', value: 10 },
- { id: 'shard-plaza-e', label: 'Plaza East Wing', x: 13, y: DEFAULT_SHARD_Y, z: 0, color: '#06b6d4', value: 10 },
- { id: 'shard-plaza-w', label: 'Plaza West Wing', x: -13, y: DEFAULT_SHARD_Y, z: 0, color: '#06b6d4', value: 10 },
-
- // Harbor Avenue (Northbound)
- { id: 'shard-avenue-mid', label: 'Avenue Walk', x: 0, y: DEFAULT_SHARD_Y, z: -28, color: '#38bdf8', value: 15 },
- { id: 'shard-avenue-shore', label: 'Shoreline Overlook', x: 0, y: DEFAULT_SHARD_Y, z: WORLD.shorelineZ + 2, color: '#38bdf8', value: 15 },
- { id: 'shard-harbor-pier', label: 'Harbor Pier Head', x: 0, y: DEFAULT_SHARD_Y, z: -68, color: '#0ea5e9', value: 25 },
-
- // Western Districts (Memory, Backup, Jira, Productivity)
- { id: 'shard-memory-steps', label: 'Memory Crystal Shard', x: -38, y: DEFAULT_SHARD_Y, z: -24, color: '#a855f7', value: 20 },
- { id: 'shard-backup-vault', label: 'Vault Crypt Cache', x: -30, y: DEFAULT_SHARD_Y, z: -8, color: '#f59e0b', value: 20 },
- { id: 'shard-jira-yard', label: 'Sprint Yard Crate', x: -16, y: DEFAULT_SHARD_Y, z: -38, color: '#ec4899', value: 20, feature: 'jira' },
- { id: 'shard-productivity', label: 'Focus Terrace Spark', x: -44, y: DEFAULT_SHARD_Y, z: 24, color: '#22c55e', value: 20 },
- { id: 'shard-quiet-corner', label: 'Secret Shard', x: -44, y: DEFAULT_SHARD_Y, z: 38, color: '#e879f9', value: 30 },
-
- // Eastern Districts (Task Queue, Health, Goals, Artifacts)
- { id: 'shard-task-queue', label: 'Queue Stream Shard', x: 30, y: DEFAULT_SHARD_Y, z: -8, color: '#f97316', value: 20 },
- { id: 'shard-health-tower', label: 'Wellness Pulse', x: 44, y: DEFAULT_SHARD_Y, z: 24, color: '#10b981', value: 20 },
- { id: 'shard-goal-monuments', label: 'Goal Milestone Shard', x: 26, y: DEFAULT_SHARD_Y, z: -36, color: '#eab308', value: 25 },
- { id: 'shard-artifacts-hall', label: 'Hall of Trophies Shard', x: 40, y: DEFAULT_SHARD_Y, z: -24, color: '#facc15', value: 25 },
-
- // Downtown Ring Road Corners
- { id: 'shard-ring-ne', label: 'Boulevard North-East', x: 21, y: DEFAULT_SHARD_Y, z: -21, color: '#06b6d4', value: 15 },
- { id: 'shard-ring-sw', label: 'Boulevard South-West', x: -21, y: DEFAULT_SHARD_Y, z: 21, color: '#06b6d4', value: 15 },
-];
-
-export const TOTAL_SHARDS = CYBER_SHARDS.length;
-
-export const isCollectibleVisible = (shard, isFeatureEnabled) => (
- !shard?.feature
- || typeof isFeatureEnabled !== 'function'
- || isFeatureEnabled(shard.feature)
-);
-
-// Return all shards with placement metadata and individual animation phase offsets.
-export function getCollectiblesList(isFeatureEnabled) {
- return CYBER_SHARDS
- .filter((shard) => isCollectibleVisible(shard, isFeatureEnabled))
- .map((shard, index) => ({
- ...shard,
- pulsePhase: (index * 0.13) % 1,
- }));
-}
-
-// Check which uncollected shards are within range of the player position.
-// Returns array of newly collected shard objects.
-export function checkShardCollection(playerPos, shards = CYBER_SHARDS, collectedSet = new Set(), radius = SHARD_COLLECTION_RADIUS) {
- if (!playerPos || typeof playerPos.x !== 'number' || typeof playerPos.z !== 'number') {
- return [];
- }
- const rSq = radius * radius;
- const newlyCollected = [];
-
- for (const shard of shards) {
- if (!shard || collectedSet.has(shard.id)) continue;
- const dx = playerPos.x - shard.x;
- const dz = playerPos.z - shard.z;
- const distSq = dx * dx + dz * dz;
- if (distSq <= rSq) {
- newlyCollected.push(shard);
- }
- }
-
- return newlyCollected;
-}
-
-// Compute progress summary from collected set
-export function getCollectionStats(collectedSet = new Set(), totalCount = TOTAL_SHARDS) {
- const count = collectedSet instanceof Set ? collectedSet.size : Array.isArray(collectedSet) ? collectedSet.length : 0;
- const clampedCount = Math.min(totalCount, Math.max(0, count));
- const percentage = totalCount > 0 ? Math.round((clampedCount / totalCount) * 100) : 0;
- return {
- collectedCount: clampedCount,
- totalCount,
- percentage,
- allCollected: clampedCount >= totalCount && totalCount > 0,
- };
-}
-
-// Session storage persistence helpers
-const STORAGE_KEY = 'openworld.shards';
-
-export function loadCollectedShardIds() {
- const parsed = safeReadJsonSession(STORAGE_KEY, null);
- return Array.isArray(parsed) ? new Set(parsed) : new Set();
-}
-
-export function saveCollectedShardIds(set) {
- safeWriteJsonSession(STORAGE_KEY, Array.from(set || []));
-}
diff --git a/client/src/utils/openWorldCollectibles.test.js b/client/src/utils/openWorldCollectibles.test.js
deleted file mode 100644
index f296ef5b9f..0000000000
--- a/client/src/utils/openWorldCollectibles.test.js
+++ /dev/null
@@ -1,98 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- CYBER_SHARDS,
- TOTAL_SHARDS,
- getCollectiblesList,
- checkShardCollection,
- getCollectionStats,
- SHARD_COLLECTION_RADIUS,
- isCollectibleVisible,
-} from './openWorldCollectibles';
-import { isWalkable } from './openWorldPlan';
-
-describe('openWorldCollectibles', () => {
- it('defines a non-empty array of valid collectible shards with unique ids', () => {
- expect(CYBER_SHARDS.length).toBeGreaterThanOrEqual(10);
- expect(TOTAL_SHARDS).toBe(CYBER_SHARDS.length);
-
- const ids = new Set();
- CYBER_SHARDS.forEach((shard) => {
- expect(typeof shard.id).toBe('string');
- expect(typeof shard.label).toBe('string');
- expect(typeof shard.x).toBe('number');
- expect(typeof shard.y).toBe('number');
- expect(typeof shard.z).toBe('number');
- expect(typeof shard.color).toBe('string');
- expect(typeof shard.value).toBe('number');
- expect(isWalkable(shard.x, shard.z), shard.id).toBe(true);
- expect(ids.has(shard.id)).toBe(false);
- ids.add(shard.id);
- });
- });
-
- it('getCollectiblesList returns copies with pulse phases', () => {
- const list = getCollectiblesList();
- expect(list.length).toBe(CYBER_SHARDS.length);
- list.forEach((s) => {
- expect(s.pulsePhase).toBeGreaterThanOrEqual(0);
- expect(s.pulsePhase).toBeLessThanOrEqual(1);
- });
- });
-
- it('checkShardCollection detects uncollected shards within radius', () => {
- const shard = CYBER_SHARDS[0];
- const playerPos = { x: shard.x + 0.5, z: shard.z + 0.5 };
- const collectedSet = new Set();
-
- const result = checkShardCollection(playerPos, CYBER_SHARDS, collectedSet, SHARD_COLLECTION_RADIUS);
- expect(result.some((s) => s.id === shard.id)).toBe(true);
-
- // If already in collectedSet, does not return again
- collectedSet.add(shard.id);
- const resultAfter = checkShardCollection(playerPos, CYBER_SHARDS, collectedSet, SHARD_COLLECTION_RADIUS);
- expect(resultAfter.some((s) => s.id === shard.id)).toBe(false);
- });
-
- it('checkShardCollection ignores far player positions or invalid inputs', () => {
- expect(checkShardCollection(null)).toEqual([]);
- expect(checkShardCollection({ x: 'invalid', z: 0 })).toEqual([]);
- expect(checkShardCollection({ x: 9999, z: 9999 }, CYBER_SHARDS, new Set())).toEqual([]);
- });
-
- it('hides the Sprint Yard shard when JIRA is disabled', () => {
- const jiraOff = (featureId) => featureId !== 'jira';
- const jiraShard = CYBER_SHARDS.find((shard) => shard.feature === 'jira');
-
- expect(isCollectibleVisible(jiraShard, jiraOff)).toBe(false);
- expect(getCollectiblesList(jiraOff).map((shard) => shard.id)).not.toContain('shard-jira-yard');
- expect(getCollectiblesList(() => true).map((shard) => shard.id)).toContain('shard-jira-yard');
- });
-
- it('getCollectionStats calculates accurate percentages and completion flags', () => {
- const emptyStats = getCollectionStats(new Set(), 10);
- expect(emptyStats).toEqual({
- collectedCount: 0,
- totalCount: 10,
- percentage: 0,
- allCollected: false,
- });
-
- const halfSet = new Set(['s1', 's2', 's3', 's4', 's5']);
- const halfStats = getCollectionStats(halfSet, 10);
- expect(halfStats).toEqual({
- collectedCount: 5,
- totalCount: 10,
- percentage: 50,
- allCollected: false,
- });
-
- const fullSet = new Set(['s1', 's2', 's3', 's4']);
- const fullStats = getCollectionStats(fullSet, 4);
- expect(fullStats).toEqual({
- collectedCount: 4,
- totalCount: 4,
- percentage: 100,
- allCollected: true,
- });
- });
-});
diff --git a/client/src/utils/openWorldDataHarbor.js b/client/src/utils/openWorldDataHarbor.js
deleted file mode 100644
index 30342ed1c4..0000000000
--- a/client/src/utils/openWorldDataHarbor.js
+++ /dev/null
@@ -1,182 +0,0 @@
-// Pure, deterministic helpers for OpenWorld's Data Harbor: a pier district over the bay
-// (master-plan parcel `dataHarbor`, north shore) that makes the install's storage legible
-// at a glance. The PostgreSQL datastore becomes the **database quay** — one disk-stack silo
-// per table, stack height log-scaled by row count, disk radius log-scaled by relation size,
-// an orbiting ring marking pgvector (embedding) tables, and a migration obelisk at the pier
-// head. The `data/` filesystem becomes the **archive racks** — one shipping-container rack
-// per domain directory, lit slats log-scaled by disk usage. Data arrives from
-// GET /api/openworld/introspection; `db: null` (unreachable) renders as a dimmed offline quay,
-// distinct from a reachable-but-empty database. Structure colors are resolved by the
-// component from the live theme palette (deterministic per name via getAccentColor). No
-// three.js / React imports so the topology is unit-testable (mirrors openWorldMemoryDistrict.js).
-
-import { clamp, formatBytes, formatCompactCount } from './formatters';
-import { scaleMetricToHeight } from './openWorldDistrictLayout';
-import { PARCELS } from './openWorldPlan';
-
-export const DATA_HARBOR = {
- base: PARCELS.dataHarbor.anchor, // pier district over the bay (see openWorldPlan.js)
- deckY: 0.55, // pier deck height above the water
- quayOffsetX: 11, // west quay (silos) / east yard (racks) x-distance from the pier axis
- maxSilos: 10, // visible table-silo cap; the rest fold into the overflow count
- maxRacks: 8, // visible domain-rack cap
- siloSpacing: 3.6, // x-distance between adjacent silos
- rowGap: 4.4, // z-distance between the two rows of a quay/yard
- rowFrontZ: 1.5, // front (bay-side) row's z offset from the district base
- diskHeight: 0.42, // one disk in a silo stack
- diskGap: 0.14, // vertical gap between disks
- minDisks: 1,
- maxDisks: 7, // a packed table stays a legible stack, not a tower
- minDiskRadius: 0.65,
- maxDiskRadius: 1.35,
- rackSpacing: 3.1, // x-distance between adjacent racks
- rackWidth: 2.3,
- rackDepth: 1.6,
- rackHeight: 3.2,
- rackSlats: 8, // emissive slat rows per rack; lit count tracks the fill ratio
-};
-
-// log2-scale `value` into [0, 1] against `max`. Delegates the curve to the shared
-// scaleMetricToHeight so every district's log scaling stays one implementation.
-const logRatio = (value, max) => {
- const scaledMax = scaleMetricToHeight(max, { k: 1 });
- if (scaledMax <= 0) return 0;
- return clamp(scaleMetricToHeight(value, { k: 1 }) / scaledMax, 0, 1);
-};
-
-// Two-row layout shared by the silo quay and the rack yard: items split into a front
-// (bay-side) row and a back row, each row x-centered; `stagger` shifts the back row by a
-// half-step (the silo quay uses it so stacks read brick-laid rather than gridded).
-const twoRowOffset = (index, total, spacing, stagger = 0) => {
- const perRow = Math.ceil(total / 2);
- const row = index < perRow ? 0 : 1;
- const col = row === 0 ? index : index - perRow;
- const rowCount = row === 0 ? perRow : total - perRow;
- return {
- dx: col * spacing - ((rowCount - 1) * spacing) / 2 + row * stagger,
- dz: DATA_HARBOR.rowFrontZ - row * DATA_HARBOR.rowGap,
- };
-};
-
-// Silo geometry for the visible top-N tables (already size-sorted by the server; re-sorted
-// here defensively).
-function computeSilos(tables) {
- const sorted = [...tables].sort((a, b) => (b.totalBytes ?? 0) - (a.totalBytes ?? 0));
- const visible = sorted.slice(0, DATA_HARBOR.maxSilos);
- const maxRows = Math.max(...visible.map((t) => t.rowEstimate ?? 0), 0);
- const maxBytes = Math.max(...visible.map((t) => t.totalBytes ?? 0), 0);
- const [bx, , bz] = DATA_HARBOR.base;
-
- return visible.map((table, i) => {
- const { dx, dz } = twoRowOffset(i, visible.length, DATA_HARBOR.siloSpacing, DATA_HARBOR.siloSpacing / 2);
- const diskCount = clamp(
- Math.round(1 + logRatio(table.rowEstimate, maxRows) * (DATA_HARBOR.maxDisks - 1)),
- DATA_HARBOR.minDisks,
- DATA_HARBOR.maxDisks,
- );
- const diskRadius = DATA_HARBOR.minDiskRadius
- + logRatio(table.totalBytes, maxBytes) * (DATA_HARBOR.maxDiskRadius - DATA_HARBOR.minDiskRadius);
- return {
- name: table.name,
- x: bx - DATA_HARBOR.quayOffsetX + dx,
- z: bz + dz,
- diskCount,
- diskRadius,
- height: diskCount * (DATA_HARBOR.diskHeight + DATA_HARBOR.diskGap),
- hasEmbedding: Boolean(table.hasEmbedding),
- rowEstimate: table.rowEstimate ?? 0,
- totalBytes: table.totalBytes ?? 0,
- label: String(table.name || '').toUpperCase(),
- sublabel: `${formatCompactCount(table.rowEstimate ?? 0)} ROWS`,
- bytesLabel: formatBytes(table.totalBytes ?? 0),
- };
- });
-}
-
-// Rack geometry for the visible top-N data/ domains (server sorts by size; defensively
-// re-sorted). Same two-row layout — a tight container yard.
-function computeRacks(domains) {
- const sorted = [...domains].sort((a, b) => (b.bytes ?? 0) - (a.bytes ?? 0));
- const visible = sorted.slice(0, DATA_HARBOR.maxRacks);
- const maxBytes = Math.max(...visible.map((d) => d.bytes ?? 0), 0);
- const [bx, , bz] = DATA_HARBOR.base;
-
- return visible.map((domain, i) => {
- const { dx, dz } = twoRowOffset(i, visible.length, DATA_HARBOR.rackSpacing);
- const fillRatio = logRatio(domain.bytes, maxBytes);
- return {
- name: domain.name,
- x: bx + DATA_HARBOR.quayOffsetX + dx,
- z: bz + dz,
- width: DATA_HARBOR.rackWidth,
- depth: DATA_HARBOR.rackDepth,
- height: DATA_HARBOR.rackHeight,
- fillRatio,
- litSlats: clamp(Math.round(fillRatio * DATA_HARBOR.rackSlats), domain.bytes > 0 ? 1 : 0, DATA_HARBOR.rackSlats),
- bytes: domain.bytes ?? 0,
- files: domain.files ?? 0,
- label: String(domain.name || '').toUpperCase(),
- sublabel: formatBytes(domain.bytes ?? 0),
- };
- });
-}
-
-// A deck sized to contain a set of structures (plus a margin) — so a spacing or cap
-// retune can never strand a silo off the pier. Falls back to a minimum platform so an
-// empty quay still reads as a deck, not open water.
-function deckFor(structures, centerX, centerZ, margin = 2.2) {
- let maxHalfW = 5;
- let maxHalfD = 4;
- for (const s of structures) {
- const r = s.diskRadius ?? Math.max(s.width ?? 0, s.depth ?? 0) / 2;
- maxHalfW = Math.max(maxHalfW, Math.abs(s.x - centerX) + r);
- maxHalfD = Math.max(maxHalfD, Math.abs(s.z - centerZ) + r);
- }
- return { x: centerX, z: centerZ, w: (maxHalfW + margin) * 2, d: (maxHalfD + margin) * 2 };
-}
-
-// The whole district model from one introspection payload.
-// - introspection missing entirely → { empty: true } (nothing renders — first load)
-// - db: null → dbDown: true (quay renders dimmed + "DB OFFLINE")
-// - fs: null → racks: [] (rack pier renders empty deck)
-export function computeDataHarbor(introspection) {
- if (!introspection || typeof introspection !== 'object') return { empty: true };
-
- const db = introspection.db && Array.isArray(introspection.db.tables) ? introspection.db : null;
- const fsSection = introspection.fs && Array.isArray(introspection.fs.domains) ? introspection.fs : null;
- const tables = db?.tables ?? [];
- const domains = fsSection?.domains ?? [];
-
- const [bx, , bz] = DATA_HARBOR.base;
- const silos = computeSilos(tables);
- const racks = computeRacks(domains);
- const rowCenterZ = bz + DATA_HARBOR.rowFrontZ - DATA_HARBOR.rowGap / 2;
-
- return {
- empty: false,
- dbDown: !db,
- base: DATA_HARBOR.base,
- silos,
- racks,
- decks: [
- deckFor(silos, bx - DATA_HARBOR.quayOffsetX, rowCenterZ),
- deckFor(racks, bx + DATA_HARBOR.quayOffsetX, rowCenterZ),
- ],
- obelisk: db?.migrations
- ? { applied: db.migrations.applied ?? 0, lastApplied: db.migrations.lastApplied ?? null, x: bx, z: bz - 7 }
- : null,
- totals: {
- tableCount: tables.length,
- dbSizeBytes: db?.sizeBytes ?? null,
- dbSizeLabel: db?.sizeBytes != null ? formatBytes(db.sizeBytes) : null,
- fsBytes: fsSection?.totalBytes ?? null,
- fsLabel: fsSection?.totalBytes != null ? formatBytes(fsSection.totalBytes) : null,
- fsFiles: fsSection?.totalFiles ?? null,
- domainCount: domains.length,
- },
- overflow: {
- tables: Math.max(0, tables.length - DATA_HARBOR.maxSilos),
- domains: Math.max(0, domains.length - DATA_HARBOR.maxRacks),
- },
- };
-}
diff --git a/client/src/utils/openWorldDataHarbor.test.js b/client/src/utils/openWorldDataHarbor.test.js
deleted file mode 100644
index 71db338d0e..0000000000
--- a/client/src/utils/openWorldDataHarbor.test.js
+++ /dev/null
@@ -1,133 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import { computeDataHarbor, DATA_HARBOR } from './openWorldDataHarbor';
-import { PARCELS, isInWater, WORLD } from './openWorldPlan';
-
-const table = (name, rowEstimate, totalBytes, hasEmbedding = false) =>
- ({ name, rowEstimate, totalBytes, hasEmbedding });
-const domain = (name, bytes, files) => ({ name, bytes, files });
-
-const happyIntrospection = () => ({
- ts: '2026-06-09T00:00:00.000Z',
- db: {
- sizeBytes: 5_000_000,
- tables: [
- table('memories', 1200, 900_000, true),
- table('catalog_scraps', 40, 50_000, true),
- table('schema_migrations', 12, 8_000),
- ],
- migrations: { applied: 12, lastApplied: '2026-06-01T00:00:00.000Z' },
- },
- fs: {
- domains: [domain('images', 3_100_000_000, 2400), domain('brain', 800_000, 60)],
- totalBytes: 3_100_800_000,
- totalFiles: 2460,
- },
-});
-
-describe('computeDataHarbor', () => {
- it('returns empty for a missing payload (nothing fetched yet)', () => {
- expect(computeDataHarbor(null)).toEqual({ empty: true });
- expect(computeDataHarbor(undefined)).toEqual({ empty: true });
- });
-
- it('flags dbDown when db is null without losing the filesystem racks', () => {
- const district = computeDataHarbor({ ...happyIntrospection(), db: null });
- expect(district.dbDown).toBe(true);
- expect(district.silos).toEqual([]);
- expect(district.obelisk).toBeNull();
- expect(district.racks).toHaveLength(2);
- });
-
- it('distinguishes a reachable-but-empty db from a down one', () => {
- const district = computeDataHarbor({
- ts: 'x',
- db: { sizeBytes: 1000, tables: [], migrations: null },
- fs: { domains: [], totalBytes: 0, totalFiles: 0 },
- });
- expect(district.dbDown).toBe(false);
- expect(district.silos).toEqual([]);
- });
-
- it('builds one silo per table with monotonic log scaling', () => {
- const district = computeDataHarbor(happyIntrospection());
- expect(district.silos).toHaveLength(3);
- const byName = Object.fromEntries(district.silos.map((s) => [s.name, s]));
- // More rows → at least as many disks; more bytes → at least as wide.
- expect(byName.memories.diskCount).toBeGreaterThanOrEqual(byName.catalog_scraps.diskCount);
- expect(byName.catalog_scraps.diskCount).toBeGreaterThanOrEqual(byName.schema_migrations.diskCount);
- expect(byName.memories.diskRadius).toBeGreaterThanOrEqual(byName.catalog_scraps.diskRadius);
- expect(byName.memories.diskCount).toBeLessThanOrEqual(DATA_HARBOR.maxDisks);
- // Embedding flag passes through.
- expect(byName.memories.hasEmbedding).toBe(true);
- expect(byName.schema_migrations.hasEmbedding).toBe(false);
- // Labels are render-ready.
- expect(byName.memories.label).toBe('MEMORIES');
- expect(byName.memories.sublabel).toBe('1.2K ROWS');
- });
-
- it('caps silos/racks at the visible max and reports the overflow', () => {
- const intro = happyIntrospection();
- intro.db.tables = Array.from({ length: 14 }, (_, i) => table(`t${i}`, i * 10, i * 1000));
- intro.fs.domains = Array.from({ length: 11 }, (_, i) => domain(`d${i}`, i * 1000, i));
- const district = computeDataHarbor(intro);
- expect(district.silos).toHaveLength(DATA_HARBOR.maxSilos);
- expect(district.racks).toHaveLength(DATA_HARBOR.maxRacks);
- expect(district.overflow).toEqual({ tables: 4, domains: 3 });
- // The visible set is the biggest-by-size, not the first-N.
- expect(district.silos.map((s) => s.name)).toContain('t13');
- expect(district.silos.map((s) => s.name)).not.toContain('t0');
- });
-
- it('keeps every structure inside the harbor parcel, over the water, on a deck', () => {
- const intro = happyIntrospection();
- intro.db.tables = Array.from({ length: 14 }, (_, i) => table(`t${i}`, i * 10, i * 1000));
- intro.fs.domains = Array.from({ length: 11 }, (_, i) => domain(`d${i}`, i * 1000, i));
- const district = computeDataHarbor(intro);
- const parcel = PARCELS.dataHarbor;
- const inParcel = (x, z, name) => {
- expect(Math.abs(x - parcel.anchor[0]), name).toBeLessThanOrEqual(parcel.w / 2);
- expect(Math.abs(z - parcel.anchor[2]), name).toBeLessThanOrEqual(parcel.d / 2);
- };
- for (const s of [...district.silos, ...district.racks]) {
- inParcel(s.x, s.z, s.name);
- expect(isInWater(s.x, s.z), s.name).toBe(true);
- // Every structure stands on one of the decks the helper emitted.
- const onDeck = district.decks.some((deck) =>
- Math.abs(s.x - deck.x) <= deck.w / 2 && Math.abs(s.z - deck.z) <= deck.d / 2);
- expect(onDeck, `${s.name} on a deck`).toBe(true);
- }
- inParcel(district.obelisk.x, district.obelisk.z, 'obelisk');
- });
-
- it('scales rack slats by log byte share with a lit floor for non-empty domains', () => {
- const district = computeDataHarbor(happyIntrospection());
- const images = district.racks.find((r) => r.name === 'images');
- const brain = district.racks.find((r) => r.name === 'brain');
- expect(images.litSlats).toBe(DATA_HARBOR.rackSlats); // the max domain is fully lit
- expect(brain.litSlats).toBeGreaterThanOrEqual(1); // non-empty never reads as unlit
- expect(brain.litSlats).toBeLessThan(images.litSlats);
- expect(images.sublabel).toBe('2.9 GB');
- });
-
- it('carries totals and the migration obelisk', () => {
- const district = computeDataHarbor(happyIntrospection());
- expect(district.obelisk).toMatchObject({ applied: 12, lastApplied: '2026-06-01T00:00:00.000Z' });
- expect(district.totals.tableCount).toBe(3);
- expect(district.totals.dbSizeLabel).toBe('4.8 MB');
- expect(district.totals.fsLabel).toBe('2.9 GB');
- expect(district.totals.domainCount).toBe(2);
- });
-
- it('is deterministic', () => {
- expect(computeDataHarbor(happyIntrospection())).toEqual(computeDataHarbor(happyIntrospection()));
- });
-});
-
-describe('harbor sits inside the world', () => {
- it('parcel is in the bay but inside the world bound', () => {
- const [x, , z] = DATA_HARBOR.base;
- expect(isInWater(x, z)).toBe(true);
- expect(Math.abs(z)).toBeLessThanOrEqual(WORLD.bound);
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldDistrictLayout.js b/client/src/utils/openWorldDistrictLayout.js
deleted file mode 100644
index 518e531f6e..0000000000
--- a/client/src/utils/openWorldDistrictLayout.js
+++ /dev/null
@@ -1,89 +0,0 @@
-// Shared, pure layout primitives for OpenWorld districts. Several district modules had
-// converged on the same three computations — column-wrapped grid placement, count-into-buckets
-// tallies, and log-scaled clamped heights — each rolling its own copy. These helpers are the
-// single source of truth they now delegate to. No three.js / React imports so every district
-// stays headless-testable (mirrors openWorldJiraDistrict.js / openWorldMemoryDistrict.js / openWorldTaskQueue.js).
-
-// ---------------------------------------------------------------------------
-// Grid placement: index → world position, wrapping into columns and X-centered.
-// ---------------------------------------------------------------------------
-
-// Auto-pick a roughly-square column count for `count` items (downtown/warehouse grow both ways
-// as apps are added). Floors at 1 so an empty or single-item grid still has a valid column.
-export function autoColumns(count) {
- const n = Number.isFinite(count) ? count : 0;
- return Math.max(1, Math.ceil(Math.sqrt(Math.max(0, n))));
-}
-
-// Column-wrapped grid position for the `index`-th cell, returned as `[x, y, z]`.
-// - columns: cells per row before wrapping (use autoColumns(n) for the sqrt-auto mode).
-// - spacing: distance between adjacent cells (applied on both axes).
-// - base: [x, y, z] origin of the grid (default origin).
-// - rowDir: +1 lays successive rows toward +Z, -1 toward -Z.
-// - rowCount: when provided, rows are *centered* on Z (offset by half the grid depth) — the
-// downtown behavior; omit it to have rows extend outward from the base (jira yard,
-// warehouse). Columns are always X-centered regardless.
-export function gridIndexToPosition(index, opts = {}) {
- const { columns = 1, spacing = 1, base = [0, 0, 0], rowDir = 1, rowCount = null } = opts;
- const cols = Math.max(1, columns);
- const col = index % cols;
- const row = Math.floor(index / cols);
- const offsetX = ((cols - 1) * spacing) / 2;
- const offsetZ = rowCount != null ? ((Math.max(1, rowCount) - 1) * spacing) / 2 : 0;
- return [
- base[0] + col * spacing - offsetX,
- base[1],
- base[2] + rowDir * (row * spacing - offsetZ),
- ];
-}
-
-// ---------------------------------------------------------------------------
-// Bucketing: count (and optionally weight) items by a categorical field.
-// ---------------------------------------------------------------------------
-
-// Count items into buckets keyed by `keyFn(item)`, returned as a plain `{ key: count }` object.
-// `seed` pre-creates zeroed buckets so a caller that depends on a fixed set of keys (e.g. a status
-// breakdown where `other` must always be present) always gets them; unknown keys are added on
-// demand. Tolerates a non-array input (returns just the seeded zeros).
-export function tallyByKey(items, keyFn, seed = []) {
- const counts = {};
- for (const key of seed) counts[key] = 0;
- for (const item of Array.isArray(items) ? items : []) {
- const key = keyFn(item);
- counts[key] = (counts[key] || 0) + 1;
- }
- return counts;
-}
-
-// Group items into buckets keyed by `keyFn`, each carrying a `count` and a summed `weight`
-// (`weightFn` defaults to 1 per item — i.e. weight == count). Returns an array of
-// `{ key, count, weight }` sorted by count desc, then key asc — the stable order districts render
-// in. Use when a district needs both a population and an accumulated magnitude per bucket.
-export function groupByFieldValue(items, keyFn, { weightFn = () => 1, seed = [] } = {}) {
- const buckets = new Map();
- for (const key of seed) buckets.set(key, { key, count: 0, weight: 0 });
- for (const item of Array.isArray(items) ? items : []) {
- const key = keyFn(item);
- const entry = buckets.get(key) || { key, count: 0, weight: 0 };
- const w = weightFn(item);
- entry.count += 1;
- entry.weight += Number.isFinite(w) ? w : 0;
- buckets.set(key, entry);
- }
- return [...buckets.values()].sort(
- (a, b) => b.count - a.count || String(a.key).localeCompare(String(b.key)),
- );
-}
-
-// ---------------------------------------------------------------------------
-// Height: log-scale a metric into a clamped band so big values don't dwarf the skyline.
-// ---------------------------------------------------------------------------
-
-// height = base + log2(1 + value) * k, clamped to [min, max]. `value` is floored at 0 (a zero or
-// missing metric yields exactly `base`). Districts use this so a chunky ticket / heavy memory
-// cluster reads as taller while staying within a legible band.
-export function scaleMetricToHeight(value, { min = 0, max = Infinity, k = 1, base = 0 } = {}) {
- const v = Math.max(0, Number.isFinite(value) ? value : 0);
- const scaled = base + Math.log2(1 + v) * k;
- return Math.min(max, Math.max(min, scaled));
-}
diff --git a/client/src/utils/openWorldDistrictLayout.test.js b/client/src/utils/openWorldDistrictLayout.test.js
deleted file mode 100644
index 50d03071de..0000000000
--- a/client/src/utils/openWorldDistrictLayout.test.js
+++ /dev/null
@@ -1,131 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- autoColumns,
- gridIndexToPosition,
- tallyByKey,
- groupByFieldValue,
- scaleMetricToHeight,
-} from './openWorldDistrictLayout';
-
-describe('autoColumns', () => {
- it('returns a roughly-square column count', () => {
- expect(autoColumns(0)).toBe(1); // empty grid still has a valid column
- expect(autoColumns(1)).toBe(1);
- expect(autoColumns(4)).toBe(2);
- expect(autoColumns(5)).toBe(3); // ceil(sqrt(5)) = 3
- expect(autoColumns(9)).toBe(3);
- expect(autoColumns(10)).toBe(4);
- });
-
- it('floors at 1 for negative / NaN input', () => {
- expect(autoColumns(-3)).toBe(1);
- expect(autoColumns(NaN)).toBe(1);
- });
-});
-
-describe('gridIndexToPosition', () => {
- it('wraps into columns and centers X', () => {
- const opts = { columns: 3, spacing: 2, base: [0, 0, 0] };
- // 3 columns, spacing 2 → X offset = (3-1)*2/2 = 2, so cols sit at -2, 0, +2
- expect(gridIndexToPosition(0, opts)).toEqual([-2, 0, 0]);
- expect(gridIndexToPosition(1, opts)).toEqual([0, 0, 0]);
- expect(gridIndexToPosition(2, opts)).toEqual([2, 0, 0]);
- // index 3 wraps to row 1, col 0 → rows extend toward +Z by default
- expect(gridIndexToPosition(3, opts)).toEqual([-2, 0, 2]);
- });
-
- it('carries base x/y/z through', () => {
- const p = gridIndexToPosition(0, { columns: 1, spacing: 1, base: [5, 7, 9] });
- expect(p).toEqual([5, 7, 9]); // single column → no X offset
- });
-
- it('lays rows toward -Z when rowDir is -1 (jira yard)', () => {
- const opts = { columns: 2, spacing: 3, base: [0, 0, 0], rowDir: -1 };
- expect(gridIndexToPosition(2, opts)).toEqual([-1.5, 0, -3]); // row 1 recedes to -Z
- });
-
- it('centers rows on Z when rowCount is given (downtown)', () => {
- // 4 items, 2 cols → 2 rows, spacing 2 → Z offset = (2-1)*2/2 = 1, rows at -1 and +1
- const opts = { columns: 2, spacing: 2, base: [0, 0, 0], rowCount: 2 };
- expect(gridIndexToPosition(0, opts)).toEqual([-1, 0, -1]);
- expect(gridIndexToPosition(2, opts)).toEqual([-1, 0, 1]);
- });
-});
-
-describe('tallyByKey', () => {
- it('counts items into buckets by key', () => {
- const items = [{ s: 'a' }, { s: 'b' }, { s: 'a' }];
- expect(tallyByKey(items, (i) => i.s)).toEqual({ a: 2, b: 1 });
- });
-
- it('seeds fixed buckets to zero so absent keys are present', () => {
- expect(tallyByKey([], (i) => i.s, ['a', 'b'])).toEqual({ a: 0, b: 0 });
- const items = [{ s: 'a' }];
- expect(tallyByKey(items, (i) => i.s, ['a', 'b', 'c'])).toEqual({ a: 1, b: 0, c: 0 });
- });
-
- it('tolerates a non-array input', () => {
- expect(tallyByKey(null, (i) => i.s, ['a'])).toEqual({ a: 0 });
- expect(tallyByKey(undefined, (i) => i.s)).toEqual({});
- });
-});
-
-describe('groupByFieldValue', () => {
- it('groups, counts, and sums weight, sorted by count desc then key asc', () => {
- const items = [
- { c: 'work', w: 2 },
- { c: 'home', w: 5 },
- { c: 'work', w: 3 },
- ];
- const out = groupByFieldValue(items, (i) => i.c, { weightFn: (i) => i.w });
- expect(out).toEqual([
- { key: 'work', count: 2, weight: 5 },
- { key: 'home', count: 1, weight: 5 },
- ]);
- });
-
- it('defaults weight to 1 per item when no weightFn', () => {
- const items = [{ c: 'x' }, { c: 'x' }, { c: 'y' }];
- expect(groupByFieldValue(items, (i) => i.c)).toEqual([
- { key: 'x', count: 2, weight: 2 },
- { key: 'y', count: 1, weight: 1 },
- ]);
- });
-
- it('treats a non-finite weight as 0 contribution', () => {
- const items = [{ c: 'x', w: NaN }, { c: 'x', w: 4 }];
- const out = groupByFieldValue(items, (i) => i.c, { weightFn: (i) => i.w });
- expect(out).toEqual([{ key: 'x', count: 2, weight: 4 }]);
- });
-
- it('breaks count ties by key ascending', () => {
- const items = [{ c: 'b' }, { c: 'a' }];
- expect(groupByFieldValue(items, (i) => i.c).map((b) => b.key)).toEqual(['a', 'b']);
- });
-
- it('seeds buckets so an empty group still appears', () => {
- expect(groupByFieldValue([], (i) => i.c, { seed: ['a'] })).toEqual([
- { key: 'a', count: 0, weight: 0 },
- ]);
- });
-});
-
-describe('scaleMetricToHeight', () => {
- it('log-scales and clamps to the band', () => {
- // base 0.9 + log2(1+1)*1.1 = 0.9 + 1.1 = 2.0
- expect(scaleMetricToHeight(1, { max: 4.5, k: 1.1, base: 0.9 })).toBeCloseTo(2.0);
- // clamps at max
- expect(scaleMetricToHeight(1000, { max: 4.5, k: 1.1, base: 0.9 })).toBe(4.5);
- });
-
- it('floors value at 0 → yields exactly base', () => {
- expect(scaleMetricToHeight(0, { min: 1.2, max: 4.5, k: 0.7, base: 1.2 })).toBe(1.2);
- expect(scaleMetricToHeight(-9, { min: 1.2, max: 4.5, k: 0.7, base: 1.2 })).toBe(1.2);
- expect(scaleMetricToHeight(NaN, { base: 3 })).toBe(3);
- });
-
- it('respects the min clamp', () => {
- expect(scaleMetricToHeight(0, { min: 2, base: 0 })).toBe(2);
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldEasterEggs.js b/client/src/utils/openWorldEasterEggs.js
deleted file mode 100644
index f0a255656b..0000000000
--- a/client/src/utils/openWorldEasterEggs.js
+++ /dev/null
@@ -1,121 +0,0 @@
-// Pure, deterministic helpers for OpenWorld's "easter eggs" (roadmap 3.5 follow-up, #824):
-// hidden/rare artifacts that only appear when a special, non-obvious condition is met. Unlike
-// the earned-artifact trophies (openWorldArtifacts.js), which mark expected milestones, easter eggs
-// are surprises — a developer's date (Apr 1), a numerically-special level (the "leet" 13/42),
-// or an exact all-goals-complete state. Each is DERIVED from data the city
-// already has plus a caller-supplied date — nothing here calls `new Date()` so every condition
-// is unit-testable on a fixed day. No three.js / React imports (mirrors openWorldArtifacts.js).
-//
-// Easter eggs render as small, glowing, rare emblems tucked at the city's edge — found, not
-// announced. A given egg appears at most once (deduped by id) and the set is stable-ordered so
-// the placement doesn't reshuffle across refetches.
-
-import { hashString } from './hashString';
-import { effectiveLevel, completedGoalCount } from './openWorldArtifacts';
-import { PARCELS } from './openWorldPlan';
-
-// Placement: a tight cluster at the far -X / +Z corner, deliberately off in a quiet quadrant
-// away from the achievement hall (+X/-Z) so an egg reads as "hidden" rather than featured.
-export const EGGS = {
- base: PARCELS.easterEggs.anchor,
- spacing: 5,
- columns: 2,
- size: 1.1,
-};
-
-// Each egg is { id, label, hint, color, test }. `test` is a pure predicate over the derived
-// context { date, level, completedGoals, totalGoals }. Ordered most-special first
-// for stable placement. Colors lean into rare/arcade neon (the city's accent palette).
-export const EASTER_EGGS = [
- {
- id: 'april-fools',
- label: '?!',
- hint: "APRIL FOOLS",
- color: '#ec4899',
- test: ({ date }) =>
- !!date && typeof date.getMonth === 'function' && date.getMonth() + 1 === 4 && date.getDate() === 1,
- },
- {
- id: 'leet',
- label: '1337',
- hint: 'LEET',
- color: '#22c55e',
- // The classic "elite" level. Exact match, not a threshold — it's a wink, not a milestone.
- test: ({ level }) => level === 13,
- },
- {
- id: 'answer',
- label: '42',
- hint: 'THE ANSWER',
- color: '#3b82f6',
- test: ({ level }) => level === 42,
- },
- {
- id: 'clean-sweep',
- label: '★',
- hint: 'CLEAN SWEEP',
- color: '#fcd34d',
- // Every tracked goal completed (and there is at least one) — a rare, perfect board.
- test: ({ completedGoals, totalGoals }) => totalGoals > 0 && completedGoals === totalGoals,
- },
-];
-
-// Count the "real" goal entries (objects) from a list or the API `{ goals: [] }` wrapper, so the
-// clean-sweep egg can compare completed vs total. Mirrors completedGoalCount's input tolerance.
-function totalGoalCount(goals) {
- const list = Array.isArray(goals) ? goals : Array.isArray(goals?.goals) ? goals.goals : [];
- return list.filter((g) => g && typeof g === 'object').length;
-}
-
-// Normalize the raw inputs into the flat predicate context, reusing the openWorldArtifacts derivations
-// so the egg conditions stay consistent with the earned-artifact trophies.
-export function eggContext({ date, character, goals } = {}) {
- return {
- date: date || null,
- level: effectiveLevel(character), // floored level or null (xp-derived if needed)
- completedGoals: completedGoalCount(goals),
- totalGoals: totalGoalCount(goals),
- };
-}
-
-// Build the list of UNLOCKED egg descriptors. Deterministic, side-effect-free, stable order.
-export function unlockedEggs(inputs = {}) {
- const ctx = eggContext(inputs);
- return EASTER_EGGS.filter((egg) => egg.test(ctx)).map((egg) => ({
- id: egg.id,
- label: egg.label,
- hint: egg.hint,
- color: egg.color,
- }));
-}
-
-// Place an egg descriptor into the corner cluster grid (left→right, wrapping toward +Z), seeded
-// per-id so the per-egg float phase differs. Mirrors openWorldArtifacts.placeArtifact.
-export function placeEgg(descriptor, index) {
- const col = index % EGGS.columns;
- const row = Math.floor(index / EGGS.columns);
- const xOffset = (col - (EGGS.columns - 1) / 2) * EGGS.spacing;
- const x = EGGS.base[0] + xOffset;
- const z = EGGS.base[2] + row * EGGS.spacing;
- const seed = hashString(descriptor.id);
-
- return {
- ...descriptor,
- position: [x, EGGS.size + 0.6, z],
- phase: (seed % 100) / 100,
- };
-}
-
-// Full derived view-model for the easter-egg component. Inject the date so calendar eggs are
-// deterministic in tests. Nothing unlocked → empty cluster (`hasData: false`), never a crash.
-export function computeEasterEggs(inputs = {}) {
- const descriptors = unlockedEggs(inputs);
- const eggs = descriptors.map((d, i) => placeEgg(d, i));
-
- return {
- base: EGGS.base,
- eggs,
- total: eggs.length,
- hasData: eggs.length > 0,
- };
-}
diff --git a/client/src/utils/openWorldEasterEggs.test.js b/client/src/utils/openWorldEasterEggs.test.js
deleted file mode 100644
index b5cf1904e9..0000000000
--- a/client/src/utils/openWorldEasterEggs.test.js
+++ /dev/null
@@ -1,123 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- EGGS,
- EASTER_EGGS,
- eggContext,
- unlockedEggs,
- placeEgg,
- computeEasterEggs,
-} from './openWorldEasterEggs';
-
-const on = (month, day) => new Date(2025, month - 1, day, 12, 0, 0);
-const completedGoals = (n) =>
- Array.from({ length: n }, (_, i) => ({ id: `g-${i}`, status: 'completed' }));
-
-describe('eggContext', () => {
- it('normalizes level to a floored nonnegative int, else null', () => {
- expect(eggContext({ character: { level: 7.9 } }).level).toBe(7);
- // Age level 0 (birthDate < 1yr ago) is authoritative now (#2673), not null.
- expect(eggContext({ character: { level: 0 } }).level).toBe(0);
- // Explicit null (no birthDate) and an absent character both yield null.
- expect(eggContext({ character: { level: null } }).level).toBeNull();
- expect(eggContext({}).level).toBeNull();
- });
-
- it('counts goals and total from a list or wrapper, ignoring junk entries', () => {
- const ctx = eggContext({ goals: [{ status: 'completed' }, { status: 'active' }, null, 'x'] });
- expect(ctx.completedGoals).toBe(1);
- expect(ctx.totalGoals).toBe(2); // two real objects, junk dropped
- });
-
-});
-
-describe('unlockedEggs — conditions', () => {
- it('unlocks nothing for an empty/default context', () => {
- expect(unlockedEggs({})).toEqual([]);
- });
-
- it('unlocks the April Fools egg only on Apr 1', () => {
- expect(unlockedEggs({ date: on(4, 1) }).map((e) => e.id)).toContain('april-fools');
- expect(unlockedEggs({ date: on(4, 2) }).map((e) => e.id)).not.toContain('april-fools');
- expect(unlockedEggs({ date: on(3, 1) }).map((e) => e.id)).not.toContain('april-fools');
- });
-
- it('unlocks the leet egg at exactly level 13 (not a threshold)', () => {
- expect(unlockedEggs({ character: { level: 13 } }).map((e) => e.id)).toContain('leet');
- expect(unlockedEggs({ character: { level: 14 } }).map((e) => e.id)).not.toContain('leet');
- expect(unlockedEggs({ character: { level: 12 } }).map((e) => e.id)).not.toContain('leet');
- });
-
- it('unlocks the answer egg at exactly level 42', () => {
- expect(unlockedEggs({ character: { level: 42 } }).map((e) => e.id)).toContain('answer');
- expect(unlockedEggs({ character: { level: 41 } }).map((e) => e.id)).not.toContain('answer');
- });
-
- it('unlocks the clean-sweep egg only when all (>=1) goals are completed', () => {
- expect(unlockedEggs({ goals: completedGoals(3) }).map((e) => e.id)).toContain('clean-sweep');
- const mixed = [...completedGoals(2), { id: 'x', status: 'active' }];
- expect(unlockedEggs({ goals: mixed }).map((e) => e.id)).not.toContain('clean-sweep');
- expect(unlockedEggs({ goals: [] }).map((e) => e.id)).not.toContain('clean-sweep'); // empty board does not count
- });
-
- it('preserves the stable table order when several unlock at once', () => {
- const ids = unlockedEggs({
- date: on(4, 1),
- character: { level: 13 },
- goals: completedGoals(2),
- }).map((e) => e.id);
- // april-fools precedes leet precedes clean-sweep in EASTER_EGGS
- expect(ids).toEqual(['april-fools', 'leet', 'clean-sweep']);
- });
-
- it('every egg descriptor carries an id, label, hint, and color', () => {
- for (const egg of EASTER_EGGS) {
- expect(typeof egg.id).toBe('string');
- expect(typeof egg.label).toBe('string');
- expect(typeof egg.hint).toBe('string');
- expect(typeof egg.color).toBe('string');
- expect(typeof egg.test).toBe('function');
- }
- });
-});
-
-describe('placeEgg', () => {
- it('centers the first column on base.x and wraps toward +Z', () => {
- const first = placeEgg({ id: 'a', color: '#fff' }, 0);
- const wrapped = placeEgg({ id: 'b', color: '#fff' }, EGGS.columns);
- expect(wrapped.position[0]).toBeCloseTo(first.position[0]); // same column
- expect(wrapped.position[2]).toBe(EGGS.base[2] + EGGS.spacing); // one row toward +Z
- });
-
- it('attaches a deterministic 0..1 phase per id', () => {
- const a = placeEgg({ id: 'leet', color: '#fff' }, 0);
- const b = placeEgg({ id: 'leet', color: '#fff' }, 0);
- expect(a.phase).toBe(b.phase);
- expect(a.phase).toBeGreaterThanOrEqual(0);
- expect(a.phase).toBeLessThanOrEqual(1);
- });
-});
-
-describe('computeEasterEggs', () => {
- it('handles an empty input as an empty cluster (no crash)', () => {
- const vm = computeEasterEggs({});
- expect(vm.eggs).toEqual([]);
- expect(vm.total).toBe(0);
- expect(vm.hasData).toBe(false);
- expect(vm.base).toEqual(EGGS.base);
- });
-
- it('handles a fully-undefined call', () => {
- expect(computeEasterEggs().hasData).toBe(false);
- });
-
- it('places one egg per unlocked condition', () => {
- const vm = computeEasterEggs({ date: on(4, 1), character: { level: 13 } });
- expect(vm.total).toBe(2);
- expect(vm.hasData).toBe(true);
- for (const e of vm.eggs) {
- expect(e.position).toHaveLength(3);
- expect(typeof e.color).toBe('string');
- }
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldFederation.js b/client/src/utils/openWorldFederation.js
deleted file mode 100644
index cb0f6a9255..0000000000
--- a/client/src/utils/openWorldFederation.js
+++ /dev/null
@@ -1,83 +0,0 @@
-// Pure, deterministic helpers for OpenWorld's "federation horizon": placing sync
-// peers as distant skyline silhouettes and deriving their reachability (opacity)
-// and sync-bridge state from real instance data. A void marker is always present
-// so the horizon stays meaningful even on a single-instance install. No three.js
-// / React imports so the topology is unit-testable (mirrors openWorldFlowLines.js).
-
-import { hashString } from './hashString';
-
-export const FEDERATION = {
- radius: 76, // distant ring, beyond OpenWorldSkyline (~55–70) so peers read as far cities
- bridgeReach: 16, // how far the sync bridge stretches inward from a peer toward the city
- onlineColor: '#8b5cf6', // violet — matches the existing INSTANCE MESH beacon
- offlineColor: '#ef4444',
- unknownColor: '#64748b', // slate — also the void marker's color
-};
-
-// Silhouette opacity by reachability. Online peers read clearly; unknown/unprobed
-// are dim; offline are barely visible — but never zero, so the horizon never goes
-// empty when a peer drops.
-export function reachabilityOpacity(status) {
- if (status === 'online') return 0.55;
- if (status === 'offline') return 0.18;
- return 0.3; // unknown / not yet probed
-}
-
-export function statusColor(status) {
- if (status === 'online') return FEDERATION.onlineColor;
- if (status === 'offline') return FEDERATION.offlineColor;
- return FEDERATION.unknownColor;
-}
-
-// The sync "bridge" between this install and a peer. It's `active` (solid, bright)
-// only when the peer is online AND sync is enabled; `broken` (dashed) when the
-// peer is offline or has recent sync failures; otherwise a faint idle link.
-export function bridgeState(peer) {
- const online = peer?.status === 'online';
- const failing = peer?.status === 'offline' || (peer?.consecutiveFailures || 0) > 0;
- const active = online && !!peer?.syncEnabled;
- return {
- active,
- broken: failing,
- intensity: active ? 1 : online ? 0.5 : 0.2,
- };
-}
-
-// Place one peer on the distant ring. Angle/height/width are derived from a stable
-// hash of the peer id, so a peer keeps its spot (and shape) across reloads and is
-// independent of its position in the list.
-export function placePeer(peer, index, { radius = FEDERATION.radius } = {}) {
- const seed = hashString(peer?.id || peer?.name || peer?.address || `peer-${index}`);
- const angle = ((seed % 3600) / 3600) * Math.PI * 2;
- const r = radius + (seed % 11); // slight depth variation across the ring
- return {
- id: peer?.id || `peer-${index}`,
- name: peer?.name || peer?.host || peer?.address || 'peer',
- status: peer?.status || 'unknown',
- online: peer?.status === 'online',
- angle,
- position: [Math.cos(angle) * r, 0, Math.sin(angle) * r],
- height: 18 + (seed % 14), // taller than the faint skyline so peers stand out
- width: 3 + (seed % 3),
- opacity: reachabilityOpacity(peer?.status),
- color: statusColor(peer?.status),
- bridge: bridgeState(peer),
- };
-}
-
-// Build the full horizon: a placement per peer plus a fixed "void machine" marker
-// (the reserved zone for the remote primary instance) that is always rendered, so
-// the federation horizon is visible even with zero peers.
-export function computeFederationHorizon(peers, opts = {}) {
- const radius = opts.radius ?? FEDERATION.radius;
- const placed = (peers || []).map((peer, i) => placePeer(peer, i, { radius }));
- const voidMarker = {
- id: 'void-machine',
- position: [0, 0, -(radius + 6)],
- height: 28,
- width: 6,
- color: FEDERATION.unknownColor,
- opacity: 0.22,
- };
- return { peers: placed, voidMarker };
-}
diff --git a/client/src/utils/openWorldFederation.test.js b/client/src/utils/openWorldFederation.test.js
deleted file mode 100644
index b26169cd5e..0000000000
--- a/client/src/utils/openWorldFederation.test.js
+++ /dev/null
@@ -1,115 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- FEDERATION,
- reachabilityOpacity,
- statusColor,
- bridgeState,
- placePeer,
- computeFederationHorizon,
-} from './openWorldFederation';
-
-describe('reachabilityOpacity', () => {
- it('orders online > unknown > offline, all non-zero', () => {
- const online = reachabilityOpacity('online');
- const unknown = reachabilityOpacity('unknown');
- const offline = reachabilityOpacity('offline');
- expect(online).toBeGreaterThan(unknown);
- expect(unknown).toBeGreaterThan(offline);
- expect(offline).toBeGreaterThan(0); // offline peers stay faintly visible
- });
-
- it('treats an unrecognised/missing status as unknown', () => {
- expect(reachabilityOpacity(undefined)).toBe(reachabilityOpacity('unknown'));
- });
-});
-
-describe('statusColor', () => {
- it('maps each status to its color', () => {
- expect(statusColor('online')).toBe(FEDERATION.onlineColor);
- expect(statusColor('offline')).toBe(FEDERATION.offlineColor);
- expect(statusColor('whatever')).toBe(FEDERATION.unknownColor);
- });
-});
-
-describe('bridgeState', () => {
- it('is active and unbroken when online and syncing', () => {
- const b = bridgeState({ status: 'online', syncEnabled: true });
- expect(b).toMatchObject({ active: true, broken: false });
- expect(b.intensity).toBe(1);
- });
-
- it('is broken when offline', () => {
- const b = bridgeState({ status: 'offline', syncEnabled: true });
- expect(b.active).toBe(false);
- expect(b.broken).toBe(true);
- });
-
- it('is broken when online but accumulating sync failures', () => {
- const b = bridgeState({ status: 'online', syncEnabled: true, consecutiveFailures: 3 });
- expect(b.broken).toBe(true);
- });
-
- it('is an idle (not active, not broken) link when online with sync disabled', () => {
- const b = bridgeState({ status: 'online', syncEnabled: false });
- expect(b.active).toBe(false);
- expect(b.broken).toBe(false);
- expect(b.intensity).toBe(0.5); // online but idle sits between active (1) and unreachable (0.2)
- });
-});
-
-describe('placePeer', () => {
- const peer = { id: 'peer-abc', name: 'studio', status: 'online', syncEnabled: true };
-
- it('is deterministic for the same peer id', () => {
- expect(placePeer(peer, 0)).toEqual(placePeer(peer, 5));
- });
-
- it('places the peer on the distant ring near the configured radius', () => {
- const { position } = placePeer(peer, 0);
- const r = Math.hypot(position[0], position[2]);
- expect(r).toBeGreaterThanOrEqual(FEDERATION.radius);
- expect(r).toBeLessThan(FEDERATION.radius + 11);
- });
-
- it('carries the peer color, opacity, and bridge derived from status', () => {
- const placed = placePeer(peer, 0);
- expect(placed.color).toBe(FEDERATION.onlineColor);
- expect(placed.opacity).toBe(reachabilityOpacity('online'));
- expect(placed.bridge.active).toBe(true);
- expect(placed.online).toBe(true);
- });
-
- it('gives distinct peers distinct angles', () => {
- const a = placePeer({ id: 'aaa' }, 0);
- const b = placePeer({ id: 'zzz' }, 1);
- expect(a.angle).not.toBeCloseTo(b.angle, 3);
- });
-
- it('falls back to a stable label and unknown status for a bare peer', () => {
- const placed = placePeer({ id: 'x' }, 2);
- expect(placed.name).toBe('peer');
- expect(placed.status).toBe('unknown');
- expect(placed.color).toBe(FEDERATION.unknownColor);
- });
-});
-
-describe('computeFederationHorizon', () => {
- it('always returns a void marker, even with no peers', () => {
- expect(computeFederationHorizon([]).voidMarker.id).toBe('void-machine');
- expect(computeFederationHorizon(undefined).voidMarker.id).toBe('void-machine');
- expect(computeFederationHorizon([]).peers).toEqual([]);
- });
-
- it('places the void marker behind downtown beyond the ring', () => {
- const { voidMarker } = computeFederationHorizon([], { radius: 50 });
- expect(voidMarker.position).toEqual([0, 0, -56]);
- });
-
- it('returns one placement per peer', () => {
- const peers = [{ id: 'a', status: 'online' }, { id: 'b', status: 'offline' }];
- const { peers: placed } = computeFederationHorizon(peers);
- expect(placed).toHaveLength(2);
- expect(placed.map(p => p.id)).toEqual(['a', 'b']);
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldFilter.js b/client/src/utils/openWorldFilter.js
deleted file mode 100644
index 2fd197b066..0000000000
--- a/client/src/utils/openWorldFilter.js
+++ /dev/null
@@ -1,42 +0,0 @@
-export const STATUS_FILTERS = [
- { id: 'all', label: 'ALL', match: () => true },
- { id: 'online', label: 'ONLINE', match: (app) => !app.archived && app.overallStatus === 'online' },
- { id: 'stopped', label: 'STOPPED', match: (app) => !app.archived && app.overallStatus === 'stopped' },
- {
- id: 'errored',
- label: 'ERRORED',
- match: (app) => {
- if (app.archived) return false;
- const pm2 = app.pm2Status || {};
- return Object.values(pm2).some(s => s?.status === 'errored' || s?.status === 'error');
- },
- },
- {
- id: 'agent',
- label: 'AGENT',
- match: (app, { agentMap }) => agentMap?.has?.(app.id),
- },
-];
-
-export function computeFilterResult({ apps, status, search, agentMap }) {
- const matcher = STATUS_FILTERS.find(f => f.id === status) || STATUS_FILTERS[0];
- const trimmed = (search || '').trim().toLowerCase();
- const matches = [];
- const dimmed = new Set();
-
- (apps || []).forEach(app => {
- const passesStatus = matcher.match(app, { agentMap });
- const haystack = [app.name, app.id, ...(app.tags || [])]
- .filter(Boolean)
- .join(' ')
- .toLowerCase();
- const passesSearch = trimmed.length === 0 || haystack.includes(trimmed);
- if (passesStatus && passesSearch) {
- matches.push(app);
- } else {
- dimmed.add(app.id);
- }
- });
-
- return { matches, dimmed };
-}
diff --git a/client/src/utils/openWorldFilter.test.js b/client/src/utils/openWorldFilter.test.js
deleted file mode 100644
index dc4befed78..0000000000
--- a/client/src/utils/openWorldFilter.test.js
+++ /dev/null
@@ -1,41 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import { computeFilterResult } from './openWorldFilter.js';
-
-const apps = [
- { id: 'a', name: 'Alpha', tags: ['prod'], archived: false, overallStatus: 'online', pm2Status: {} },
- { id: 'b', name: 'Beta', tags: [], archived: false, overallStatus: 'stopped', pm2Status: {} },
- { id: 'c', name: 'Gamma', tags: ['ops'], archived: false, overallStatus: 'online', pm2Status: { web: { status: 'errored' } } },
- { id: 'd', name: 'Delta', tags: [], archived: true, overallStatus: 'online', pm2Status: {} },
-];
-
-describe('computeFilterResult', () => {
- it('returns every app as a match for status=all with no search', () => {
- const { matches, dimmed } = computeFilterResult({ apps, status: 'all', search: '' });
- expect(matches.map((a) => a.id)).toEqual(['a', 'b', 'c', 'd']);
- expect(dimmed.size).toBe(0);
- });
-
- it('excludes archived apps from online/stopped/errored', () => {
- // `online` is overallStatus; an app can also match `errored` via pm2.
- expect(computeFilterResult({ apps, status: 'online' }).matches.map((a) => a.id)).toEqual(['a', 'c']);
- expect(computeFilterResult({ apps, status: 'stopped' }).matches.map((a) => a.id)).toEqual(['b']);
- expect(computeFilterResult({ apps, status: 'errored' }).matches.map((a) => a.id)).toEqual(['c']);
- });
-
- it('filters by name, id, or tag and puts the rest in dimmed', () => {
- const byName = computeFilterResult({ apps, status: 'all', search: 'alp' });
- expect(byName.matches.map((a) => a.id)).toEqual(['a']);
- expect([...byName.dimmed]).toEqual(['b', 'c', 'd']);
-
- const byTag = computeFilterResult({ apps, status: 'all', search: 'ops' });
- expect(byTag.matches.map((a) => a.id)).toEqual(['c']);
- });
-
- it('restricts the agent filter to ids present in agentMap', () => {
- const agentMap = new Set(['b']);
- const { matches, dimmed } = computeFilterResult({ apps, status: 'agent', agentMap });
- expect(matches.map((a) => a.id)).toEqual(['b']);
- expect(dimmed.has('a')).toBe(true);
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldFlowLines.js b/client/src/utils/openWorldFlowLines.js
deleted file mode 100644
index 56361dd13d..0000000000
--- a/client/src/utils/openWorldFlowLines.js
+++ /dev/null
@@ -1,75 +0,0 @@
-// Pure, deterministic helpers for OpenWorld's inter-building "flow lines": which
-// active buildings connect to each other, and how intense each stream is. The
-// topology is derived from real operational state — a building is a flow source
-// only when it's online, and a link runs "hot" when either endpoint has a
-// running agent — rather than the previous random nearest-neighbor decoration.
-// No three.js / React imports here so the topology can be unit-tested in
-// isolation (mirrors the openWorldTimeline.js / openWorldAgentMotion.js helper pattern).
-
-import { hashString } from './hashString';
-
-export const FLOW = {
- maxNeighbors: 2, // connect each active building to up to N nearest active neighbors
- hotColor: '#22d3ee', // links touching a building with a running agent (work in flight)
- idleColor: '#3b82f6', // links between plain-online buildings (steady-state traffic)
- basePackets: 1, // packets travelling each direction on a steady link
- hotPackets: 2, // packets each direction when an endpoint has a running agent
- baseSpeed: 0.12, // packet speed on a steady link (fraction of the path per second)
- hotSpeedBonus: 0.06, // extra speed on a hot link — work-in-flight reads as faster traffic
-};
-
-// Build the flow-line connection set between ACTIVE downtown buildings.
-// positions — Map<id, { x, z, district }> from the city layout
-// activeIds — Set<id> of buildings that are online (flow sources/sinks)
-// agentIds — Set<id> of buildings that currently have >=1 running agent
-// Returns deterministic descriptors: { key, start:[x,y,z], end:[x,y,z], color,
-// hot, packets, speed }. `hot`/color/packets/speed encode the link's intensity
-// (color = type, packets+speed = volume) so the renderer stays presentation-only.
-export function computeFlowConnections({ positions, activeIds, agentIds, maxNeighbors = FLOW.maxNeighbors } = {}) {
- if (!positions || !activeIds || activeIds.size < 2) return [];
-
- const entries = [];
- positions.forEach((pos, id) => {
- if (pos.district === 'downtown' && activeIds.has(id)) {
- entries.push({ id, x: pos.x, z: pos.z });
- }
- });
- if (entries.length < 2) return [];
-
- const conns = [];
- const seen = new Set();
-
- for (let i = 0; i < entries.length; i++) {
- const a = entries[i];
- const neighbors = [];
- for (let j = 0; j < entries.length; j++) {
- if (i === j) continue;
- const b = entries[j];
- const dist = (a.x - b.x) ** 2 + (a.z - b.z) ** 2;
- neighbors.push({ id: b.id, x: b.x, z: b.z, dist });
- }
- neighbors.sort((m, n) => m.dist - n.dist);
-
- const take = Math.min(maxNeighbors, neighbors.length);
- for (let n = 0; n < take; n++) {
- const b = neighbors[n];
- const key = [a.id, b.id].sort().join('→');
- if (seen.has(key)) continue;
- seen.add(key);
-
- const hot = agentIds?.has(a.id) || agentIds?.has(b.id) || false;
- const variation = (hashString(key) % 100) / 100; // 0..1, deterministic per link
- conns.push({
- key,
- start: [a.x, 0.5, a.z],
- end: [b.x, 0.5, b.z],
- color: hot ? FLOW.hotColor : FLOW.idleColor,
- hot,
- packets: hot ? FLOW.hotPackets : FLOW.basePackets,
- speed: FLOW.baseSpeed + (hot ? FLOW.hotSpeedBonus : 0) + variation * 0.05,
- });
- }
- }
-
- return conns;
-}
diff --git a/client/src/utils/openWorldFlowLines.test.js b/client/src/utils/openWorldFlowLines.test.js
deleted file mode 100644
index bb87cbe9d6..0000000000
--- a/client/src/utils/openWorldFlowLines.test.js
+++ /dev/null
@@ -1,90 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import { FLOW, computeFlowConnections } from './openWorldFlowLines';
-
-// Four downtown buildings in a row plus one non-downtown and one offscreen.
-const positions = new Map([
- ['a', { x: 0, z: 0, district: 'downtown' }],
- ['b', { x: 2, z: 0, district: 'downtown' }],
- ['c', { x: 4, z: 0, district: 'downtown' }],
- ['d', { x: 6, z: 0, district: 'downtown' }],
- ['w', { x: 0, z: 20, district: 'warehouse' }],
-]);
-
-describe('computeFlowConnections', () => {
- it('returns nothing with fewer than two active buildings', () => {
- expect(computeFlowConnections({ positions, activeIds: new Set(['a']), agentIds: new Set() })).toEqual([]);
- expect(computeFlowConnections({ positions, activeIds: new Set(), agentIds: new Set() })).toEqual([]);
- expect(computeFlowConnections({})).toEqual([]);
- });
-
- it('only connects buildings that are active (online)', () => {
- const conns = computeFlowConnections({
- positions,
- activeIds: new Set(['a', 'b']),
- agentIds: new Set(),
- });
- expect(conns).toHaveLength(1);
- expect(conns[0].key).toBe('a→b');
- });
-
- it('excludes non-downtown districts even when marked active', () => {
- const conns = computeFlowConnections({
- positions,
- activeIds: new Set(['a', 'w']),
- agentIds: new Set(),
- });
- // 'w' is warehouse district → not a flow source, leaving <2 downtown actives
- expect(conns).toEqual([]);
- });
-
- it('connects each active building to up to maxNeighbors nearest active neighbors, deduped', () => {
- const conns = computeFlowConnections({
- positions,
- activeIds: new Set(['a', 'b', 'c', 'd']),
- agentIds: new Set(),
- maxNeighbors: 2,
- });
- const keys = conns.map(c => c.key).sort();
- // a↔b, b↔c, c↔d (adjacent), plus a→c and b→d as second-nearest — deduped both ways
- expect(new Set(keys).size).toBe(keys.length); // no duplicate keys
- expect(keys).toContain('a→b');
- expect(keys).toContain('c→d');
- // never a self-link
- expect(keys.every(k => k.split('→')[0] !== k.split('→')[1])).toBe(true);
- });
-
- it('marks a link hot (agent color, more+faster packets) when either endpoint has a running agent', () => {
- const conns = computeFlowConnections({
- positions,
- activeIds: new Set(['a', 'b']),
- agentIds: new Set(['b']),
- });
- expect(conns[0].hot).toBe(true);
- expect(conns[0].color).toBe(FLOW.hotColor);
- expect(conns[0].packets).toBe(FLOW.hotPackets);
- expect(conns[0].speed).toBeGreaterThan(FLOW.baseSpeed);
- });
-
- it('marks a link idle (steady color, base packets) when neither endpoint has an agent', () => {
- const conns = computeFlowConnections({
- positions,
- activeIds: new Set(['a', 'b']),
- agentIds: new Set(['c']), // agent on an unrelated building
- });
- expect(conns[0].hot).toBe(false);
- expect(conns[0].color).toBe(FLOW.idleColor);
- expect(conns[0].packets).toBe(FLOW.basePackets);
- });
-
- it('produces a deterministic topology across calls', () => {
- const args = { positions, activeIds: new Set(['a', 'b', 'c']), agentIds: new Set(['a']) };
- expect(computeFlowConnections(args)).toEqual(computeFlowConnections(args));
- });
-
- it('places stream endpoints at the buildings xz with a fixed y', () => {
- const conns = computeFlowConnections({ positions, activeIds: new Set(['a', 'b']), agentIds: new Set() });
- expect(conns[0].start).toEqual([0, 0.5, 0]);
- expect(conns[0].end).toEqual([2, 0.5, 0]);
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldFocusCamera.js b/client/src/utils/openWorldFocusCamera.js
deleted file mode 100644
index 79f55a9ff1..0000000000
--- a/client/src/utils/openWorldFocusCamera.js
+++ /dev/null
@@ -1,183 +0,0 @@
-// Pure camera-framing math for OpenWorld's building focus mode (issue #2593). Given a single
-// borough's ground position + tower height, the current viewport aspect ratio, and the HUD safe
-// area, it computes an orbital camera `position` and look-at `target` that frame the WHOLE borough
-// without intersecting its geometry and without hiding it under the on-screen detail panel.
-//
-// No React / three.js imports so the topology stays unit-testable (mirrors openWorldMiniMap.js). Callers
-// (OpenWorldFocusCamera) convert the returned `[x, y, z]` tuples into THREE.Vector3 and animate toward
-// them.
-
-// Vertical field of view of the city camera (matches OpenWorldScene's <Canvas camera={{ fov: 50 }}>).
-export const CITY_CAMERA_FOV_DEG = 50;
-
-// How far the orbital camera may sit from its target. OpenWorldScene passes this straight to
-// OrbitControls as `maxDistance`, and every framing helper here clamps to it — the two MUST
-// be the same number. When they weren't, a fast-travel warp to a big district on a phone
-// computed ~218 units while the controls capped at 120, so OrbitControls yanked the camera
-// in the moment the fly handed control back and the region never fit the frame.
-// Sized to fit the widest region (60-unit Downtown) on a narrow portrait viewport, where the
-// horizontal extent — not the HUD — is what forces the camera back.
-export const CITY_MAX_ORBIT_DISTANCE = 240;
-
-// Ground-footprint radius of a single borough: the process ring (BOROUGH_PARAMS.processRingRadius
-// = 3) plus a process building's half-footprint and a little breathing room. Buildings never spread
-// wider than this on the ground, so a sphere of this radius (grown by the tower height) bounds the
-// entire borough.
-export const BOROUGH_GROUND_RADIUS = 4.5;
-
-// Empty space left around the framed borough (1 = edge-to-edge, 1.35 = 35% margin).
-const FRAMING_MARGIN = 1.35;
-
-// Extra vertical reach above the tower for the things that float over it — the building hologram
-// (~tower + 1.8) and the stacked AgentEntity markers — so a borough with several active agents
-// isn't clipped above the frame. A fixed cushion (the pure math only knows the tower `height`, not
-// the live agent count) that comfortably covers a typical stack.
-const BOROUGH_TOP_CLEARANCE = 3.0;
-
-// How far above the horizon the focus camera sits (~40°). Keeps the shot looking slightly down onto
-// the borough like the overview, without going full top-down.
-const PITCH_RAD = (40 * Math.PI) / 180;
-
-// A HUD panel can never eat more than this fraction of an axis for framing purposes — a floor that
-// stops a degenerate viewport from pushing the camera to infinity.
-const MIN_USABLE_FRACTION = 0.35;
-
-const clamp01 = (v) => (v < 0 ? 0 : v > 1 ? 1 : v);
-const toRad = (deg) => (deg * Math.PI) / 180;
-const finiteOr = (v, fallback) => (Number.isFinite(v) ? v : fallback);
-
-// Compute the framing camera for one borough.
-// building — { x, z, height } layout entry (from computeOpenWorldLayout). Missing/invalid fields fall
-// back to sane defaults so a not-yet-resolved building can't produce NaNs.
-// aspect — viewport width / height (portrait < 1 needs the camera farther back).
-// fovDeg — vertical FOV in degrees (defaults to the city camera's 50).
-// hudSafe — { right, bottom } fractions (0..1) of the viewport occupied by the HUD, so the
-// borough frames in the CLEAR region rather than under the detail panel.
-// Returns { position:[x,y,z], target:[x,y,z], distance, radius }.
-export function computeFocusCamera({ building, aspect = 1, fovDeg = CITY_CAMERA_FOV_DEG, hudSafe } = {}) {
- const bx = finiteOr(building?.x, 0);
- const bz = finiteOr(building?.z, 0);
- const heightRaw = finiteOr(building?.height, 4);
- const height = heightRaw > 0 ? heightRaw : 4;
-
- // Bounding radius: the wider of the borough's ground footprint and half its tower height (plus the
- // hologram/agent clearance above), so a tall skinny tower, a short wide cluster, and a
- // many-agent borough all stay fully in frame.
- const radius = Math.max(BOROUGH_GROUND_RADIUS, height * 0.6 + BOROUGH_TOP_CLEARANCE) * FRAMING_MARGIN;
-
- return frameFromRadius({
- centerX: bx,
- centerZ: bz,
- targetY: height * 0.45,
- radius,
- aspect,
- fovDeg,
- hudSafe,
- pitchRad: PITCH_RAD,
- });
-}
-
-// Shared optics for every framing helper here: given a bounding sphere on the ground plane,
-// back the camera off far enough that the sphere fits the HUD-reduced viewport, then pan the
-// whole shot clear of the HUD panels. Kept in one place so a borough and a whole district
-// can't drift into different framing rules.
-function frameFromRadius({ centerX, centerZ, targetY, radius, aspect, fovDeg, hudSafe, pitchRad }) {
- const safeAspect = Number.isFinite(aspect) && aspect > 0 ? aspect : 1;
- const safeFov = Number.isFinite(fovDeg) && fovDeg > 0 ? fovDeg : CITY_CAMERA_FOV_DEG;
-
- // Usable viewport fraction once the HUD safe area is subtracted, clamped to a floor.
- const right = clamp01(hudSafe?.right ?? 0);
- const bottom = clamp01(hudSafe?.bottom ?? 0);
- const usableW = Math.max(MIN_USABLE_FRACTION, 1 - right);
- const usableH = Math.max(MIN_USABLE_FRACTION, 1 - bottom);
-
- const halfV = Math.tan(toRad(safeFov) / 2);
- const halfH = halfV * safeAspect;
-
- // Distance so the bounding sphere fits both the (HUD-reduced) vertical and horizontal extents.
- const distV = radius / (halfV * usableH);
- const distH = radius / (halfH * usableW);
- // Clamped to the ceiling the controls enforce: a fly that ended beyond it would be snapped
- // back by OrbitControls the instant it re-enabled. A subject too large to fit at the cap is
- // framed as well as the cap allows — imperfect, but stable instead of jarring.
- const distance = Math.min(CITY_MAX_ORBIT_DISTANCE, Math.max(distV, distH));
-
- // Pan the framed region so the subject sits in the clear area: push it left of a right-edge panel
- // and up above a bottom-edge panel. Panning moves camera + target by the same world delta.
- const visHalfW = distance * halfH;
- const visHalfH = distance * halfV;
- const shiftX = right * visHalfW;
- const shiftY = bottom * visHalfH;
-
- const target = [centerX + shiftX, targetY - shiftY, centerZ];
-
- // Camera above + on the +Z side (like the overview camera), pitched down by `pitchRad`.
- const position = [
- target[0],
- target[1] + distance * Math.sin(pitchRad),
- centerZ + distance * Math.cos(pitchRad),
- ];
-
- return { position, target, distance, radius };
-}
-
-// --- Region framing (fast travel) -------------------------------------------
-// Same optics as computeFocusCamera, but framing a whole district parcel instead of one
-// borough: the bounding radius comes from the parcel's [w × d] footprint rather than a
-// tower's height. Used by the `/openworld/region/:regionId` warp so every region arrives
-// at a consistent, fully-in-frame establishing shot.
-
-// Empty space around a framed region — a touch tighter than a single borough's, since a
-// district already reads as a group and doesn't need the extra breathing room.
-const REGION_FRAMING_MARGIN = 1.2;
-
-// A parcel with no declared footprint (or a degenerate one) still needs a usable shot.
-const MIN_REGION_RADIUS = 10;
-
-// Regions are framed from a little higher than a borough (~46°) so the district's LAYOUT
-// reads — you're arriving to see a place, not to inspect one building's facade.
-const REGION_PITCH_RAD = (46 * Math.PI) / 180;
-
-// Look slightly above the ground plane so the district's structures, not the pavement,
-// sit at the center of frame.
-const REGION_TARGET_Y = 3;
-
-// Compute the establishing camera for one fast-travel region.
-// region — { anchor: [x, y, z], w, d } (from openWorldRegions.getRegion).
-// bounds — optional { minX, maxX, minZ, maxZ } of what is ACTUALLY on the ground for a
-// data-driven district (downtown / the archive grid, whose extent grows with the
-// install's app count). When given it supersedes the parcel's nominal w/d, so a
-// big install frames its real skyline instead of clipping the outer towers; the
-// parcel is still the floor, so a near-empty install doesn't zoom into one tower.
-// aspect / fovDeg / hudSafe — as computeFocusCamera.
-// Returns { position:[x,y,z], target:[x,y,z], distance, radius }.
-export function computeRegionCamera({ region, bounds, aspect = 1, fovDeg = CITY_CAMERA_FOV_DEG, hudSafe } = {}) {
- const anchor = Array.isArray(region?.anchor) ? region.anchor : [];
- let cx = finiteOr(anchor[0], 0);
- let cz = finiteOr(anchor[2], 0);
- let w = Math.max(0, finiteOr(region?.w, 0));
- let d = Math.max(0, finiteOr(region?.d, 0));
-
- const hasBounds = [bounds?.minX, bounds?.maxX, bounds?.minZ, bounds?.maxZ].every(Number.isFinite);
- if (hasBounds) {
- // Center on the live cloud and take the larger of live vs nominal on each axis — a grid
- // that has outgrown its parcel widens the shot, one that hasn't keeps the parcel's.
- cx = (bounds.minX + bounds.maxX) / 2;
- cz = (bounds.minZ + bounds.maxZ) / 2;
- w = Math.max(w, bounds.maxX - bounds.minX + BOROUGH_GROUND_RADIUS * 2);
- d = Math.max(d, bounds.maxZ - bounds.minZ + BOROUGH_GROUND_RADIUS * 2);
- }
-
- const radius = Math.max(MIN_REGION_RADIUS, Math.hypot(w, d) / 2) * REGION_FRAMING_MARGIN;
-
- return frameFromRadius({
- centerX: cx,
- centerZ: cz,
- targetY: REGION_TARGET_Y,
- radius,
- aspect,
- fovDeg,
- hudSafe,
- pitchRad: REGION_PITCH_RAD,
- });
-}
diff --git a/client/src/utils/openWorldFocusCamera.test.js b/client/src/utils/openWorldFocusCamera.test.js
deleted file mode 100644
index 97f1f23625..0000000000
--- a/client/src/utils/openWorldFocusCamera.test.js
+++ /dev/null
@@ -1,189 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import { computeFocusCamera, BOROUGH_GROUND_RADIUS, CITY_CAMERA_FOV_DEG, computeRegionCamera, CITY_MAX_ORBIT_DISTANCE } from './openWorldFocusCamera';
-
-const building = { x: 12, z: -24, height: 6 };
-
-describe('computeFocusCamera', () => {
- it('targets the borough centre (up the tower) with no HUD offset', () => {
- const { target } = computeFocusCamera({ building, aspect: 1.6 });
- expect(target[0]).toBeCloseTo(building.x, 6);
- expect(target[2]).toBeCloseTo(building.z, 6);
- expect(target[1]).toBeGreaterThan(0);
- expect(target[1]).toBeLessThan(building.height);
- });
-
- it('places the camera above the tower and in front (+Z) so it never intersects geometry', () => {
- const { position } = computeFocusCamera({ building, aspect: 1.6 });
- expect(position[1]).toBeGreaterThan(building.height);
- expect(position[2]).toBeGreaterThan(building.z);
- });
-
- it('pulls the camera farther back for a portrait (narrow) aspect than a landscape one', () => {
- const portrait = computeFocusCamera({ building, aspect: 0.5 });
- const landscape = computeFocusCamera({ building, aspect: 2.0 });
- expect(portrait.distance).toBeGreaterThan(landscape.distance);
- });
-
- it('frames a taller tower from farther away', () => {
- const shortB = computeFocusCamera({ building: { x: 0, z: 0, height: 3 }, aspect: 1.6 });
- const tallB = computeFocusCamera({ building: { x: 0, z: 0, height: 40 }, aspect: 1.6 });
- expect(tallB.distance).toBeGreaterThan(shortB.distance);
- expect(tallB.radius).toBeGreaterThan(shortB.radius);
- });
-
- it('reserves headroom above the tower for the hologram / floating agents', () => {
- const { target, radius } = computeFocusCamera({ building, aspect: 1.6 });
- // The framed sphere reaches well above the tower top so agent markers are not clipped.
- expect(target[1] + radius).toBeGreaterThan(building.height + 3);
- });
-
- it('uses the borough ground radius floor for short buildings', () => {
- const { radius } = computeFocusCamera({ building: { x: 0, z: 0, height: 1 }, aspect: 1.6 });
- expect(radius).toBeGreaterThanOrEqual(BOROUGH_GROUND_RADIUS);
- });
-
- it('backs off and shifts the target when the HUD occupies the right edge', () => {
- // A portrait-ish aspect makes the horizontal extent the binding constraint, so shrinking the
- // usable width strictly increases the distance (in landscape a pan alone keeps it clear).
- const bare = computeFocusCamera({ building, aspect: 0.6 });
- const withPanel = computeFocusCamera({ building, aspect: 0.6, hudSafe: { right: 0.28 } });
- expect(withPanel.distance).toBeGreaterThan(bare.distance);
- // Target pans +x (borough shifts left, into the clear area beside the panel).
- expect(withPanel.target[0]).toBeGreaterThan(bare.target[0]);
- // Camera pans with the target so the view direction is preserved.
- expect(withPanel.position[0]).toBeCloseTo(withPanel.target[0], 6);
- });
-
- it('raises the framed region above a bottom-edge HUD panel', () => {
- const bare = computeFocusCamera({ building, aspect: 1.0 });
- const withSheet = computeFocusCamera({ building, aspect: 1.0, hudSafe: { bottom: 0.45 } });
- expect(withSheet.distance).toBeGreaterThan(bare.distance);
- // Panning up moves the target down in world space (building rises on screen).
- expect(withSheet.target[1]).toBeLessThan(bare.target[1]);
- });
-
- it('returns finite numbers for a missing/degenerate building', () => {
- const { position, target, distance } = computeFocusCamera({ building: undefined, aspect: 0 });
- [...position, ...target, distance].forEach((n) => expect(Number.isFinite(n)).toBe(true));
- });
-
- it('defaults to the city camera FOV', () => {
- const a = computeFocusCamera({ building, aspect: 1.6 });
- const b = computeFocusCamera({ building, aspect: 1.6, fovDeg: CITY_CAMERA_FOV_DEG });
- expect(a.distance).toBeCloseTo(b.distance, 6);
- });
-});
-// @vitest-environment node
-
-describe('computeRegionCamera', () => {
- const region = { id: 'memory', anchor: [-44, 0, -30], w: 22, d: 22 };
-
- it('centers the shot on the parcel anchor', () => {
- const { target } = computeRegionCamera({ region, aspect: 16 / 9 });
- expect(target[0]).toBeCloseTo(region.anchor[0], 6);
- expect(target[2]).toBeCloseTo(region.anchor[2], 6);
- });
-
- it('sits above and on the +Z side of the region, like the overview camera', () => {
- const { position, target } = computeRegionCamera({ region, aspect: 16 / 9 });
- expect(position[1]).toBeGreaterThan(target[1]);
- expect(position[2]).toBeGreaterThan(region.anchor[2]);
- });
-
- it('backs off farther for a bigger parcel', () => {
- const small = computeRegionCamera({ region, aspect: 16 / 9 });
- const big = computeRegionCamera({ region: { ...region, w: 66, d: 40 }, aspect: 16 / 9 });
- expect(big.distance).toBeGreaterThan(small.distance);
- });
-
- it('floors the radius so a zero-footprint parcel still frames usefully', () => {
- const { distance, radius } = computeRegionCamera({ region: { anchor: [0, 0, 0], w: 0, d: 0 }, aspect: 1 });
- expect(radius).toBeGreaterThan(0);
- expect(Number.isFinite(distance)).toBe(true);
- });
-
- it('pans clear of the HUD safe area', () => {
- const bare = computeRegionCamera({ region, aspect: 16 / 9 });
- const withPanel = computeRegionCamera({ region, aspect: 16 / 9, hudSafe: { right: 0.28 } });
- expect(withPanel.target[0]).toBeGreaterThan(bare.target[0]);
- });
-
- it('survives a missing/degenerate region without producing NaNs', () => {
- for (const bad of [undefined, {}, { anchor: null }, { anchor: [NaN, 0, NaN], w: NaN, d: NaN }]) {
- const { position, target } = computeRegionCamera({ region: bad, aspect: 16 / 9 });
- for (const n of [...position, ...target]) expect(Number.isFinite(n)).toBe(true);
- }
- });
-});
-
-import { listRegions } from './openWorldRegions';
-
-describe('framing stays inside the orbit-distance ceiling', () => {
- // OpenWorldScene hands CITY_MAX_ORBIT_DISTANCE straight to OrbitControls as maxDistance. A fly
- // that ended beyond it would be yanked back the instant the controls re-enabled, so the
- // framing math must never return a farther distance than the controls will keep.
- const VIEWPORTS = [
- ['desktop', 16 / 9, { right: 0.28, bottom: 0 }],
- ['narrow phone', 390 / 780, { right: 0, bottom: 0.5 }],
- ['degenerate', 0.2, { right: 0.9, bottom: 0.9 }],
- ];
-
- it('every real region frames within the ceiling on every viewport', () => {
- const over = [];
- for (const region of listRegions()) {
- for (const [name, aspect, hudSafe] of VIEWPORTS) {
- const { distance } = computeRegionCamera({ region, aspect, fovDeg: 50, hudSafe });
- if (distance > CITY_MAX_ORBIT_DISTANCE) over.push(`${region.id} @ ${name}: ${distance.toFixed(1)}`);
- }
- }
- expect(over).toEqual([]);
- });
-
- it('clamps rather than exceeding the ceiling for an absurdly large region', () => {
- const { distance } = computeRegionCamera({
- region: { anchor: [0, 0, 0], w: 5000, d: 5000 }, aspect: 0.4, fovDeg: 50,
- });
- expect(distance).toBe(CITY_MAX_ORBIT_DISTANCE);
- });
-
- it('clamps the borough focus camera too — they share the optics', () => {
- const { distance } = computeFocusCamera({
- building: { x: 0, z: 0, height: 100000 }, aspect: 0.4, fovDeg: 50,
- });
- expect(distance).toBe(CITY_MAX_ORBIT_DISTANCE);
- });
-});
-
-describe('computeRegionCamera — data-driven districts', () => {
- const parcel = { anchor: [0, 0, 0], w: 60, d: 60 };
-
- it('widens and re-centers on live layout bounds that outgrew the parcel', () => {
- const nominal = computeRegionCamera({ region: parcel, aspect: 16 / 9 });
- const grown = computeRegionCamera({
- region: parcel,
- bounds: { minX: -90, maxX: 90, minZ: -40, maxZ: 40 },
- aspect: 16 / 9,
- });
- expect(grown.radius).toBeGreaterThan(nominal.radius);
- // Re-centered on the live cloud, which here is symmetric about the parcel anchor.
- expect(grown.target[2]).toBeCloseTo(0, 6);
- });
-
- it('keeps the parcel as a floor so a near-empty install does not zoom into one tower', () => {
- const nominal = computeRegionCamera({ region: parcel, aspect: 16 / 9 });
- const tiny = computeRegionCamera({
- region: parcel,
- bounds: { minX: -6, maxX: 6, minZ: -6, maxZ: 6 },
- aspect: 16 / 9,
- });
- expect(tiny.radius).toBe(nominal.radius);
- });
-
- it('ignores partial or non-finite bounds rather than producing NaNs', () => {
- for (const bounds of [null, undefined, {}, { minX: 0, maxX: 10 }, { minX: NaN, maxX: 1, minZ: 0, maxZ: 1 }]) {
- const { position, target, radius } = computeRegionCamera({ region: parcel, bounds, aspect: 16 / 9 });
- for (const n of [...position, ...target, radius]) expect(Number.isFinite(n)).toBe(true);
- expect(radius).toBe(computeRegionCamera({ region: parcel, aspect: 16 / 9 }).radius);
- }
- });
-});
diff --git a/client/src/utils/openWorldFocusState.js b/client/src/utils/openWorldFocusState.js
deleted file mode 100644
index 17f0347b2d..0000000000
--- a/client/src/utils/openWorldFocusState.js
+++ /dev/null
@@ -1,18 +0,0 @@
-// Pure resolver for OpenWorld's URL-addressed building focus (issue #2593). Maps the
-// `/openworld/apps/:appId` route param + the live app list into a concrete render state.
-//
-// The key subtlety: a valid deep link whose app list is still loading must NOT flash the
-// "building not found" fallback. So `notFound` is only true once the list has finished loading
-// AND the id still matches nothing (deleted/archived-away/never-existed id).
-
-export function resolveOpenWorldFocus(appId, apps, { loading = false } = {}) {
- const hasFocus = typeof appId === 'string' && appId.length > 0;
- if (!hasFocus) return { hasFocus: false, focusedApp: null, notFound: false };
-
- const list = Array.isArray(apps) ? apps : [];
- const focusedApp = list.find((a) => a?.id === appId) || null;
- // Still loading → keep waiting (a valid id may resolve once apps arrive). Loaded + missing → 404.
- const notFound = !focusedApp && !loading;
-
- return { hasFocus: true, focusedApp, notFound };
-}
diff --git a/client/src/utils/openWorldFocusState.test.js b/client/src/utils/openWorldFocusState.test.js
deleted file mode 100644
index a28a90ae47..0000000000
--- a/client/src/utils/openWorldFocusState.test.js
+++ /dev/null
@@ -1,45 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import { resolveOpenWorldFocus } from './openWorldFocusState';
-
-const apps = [
- { id: 'alpha', name: 'Alpha' },
- { id: 'beta', name: 'Beta' },
-];
-
-describe('resolveOpenWorldFocus', () => {
- it('reports no focus when there is no appId (overview)', () => {
- expect(resolveOpenWorldFocus(null, apps)).toEqual({ hasFocus: false, focusedApp: null, notFound: false });
- expect(resolveOpenWorldFocus('', apps)).toEqual({ hasFocus: false, focusedApp: null, notFound: false });
- expect(resolveOpenWorldFocus(undefined, apps)).toEqual({ hasFocus: false, focusedApp: null, notFound: false });
- });
-
- it('resolves a valid id to its app', () => {
- const res = resolveOpenWorldFocus('beta', apps);
- expect(res.hasFocus).toBe(true);
- expect(res.focusedApp).toBe(apps[1]);
- expect(res.notFound).toBe(false);
- });
-
- it('does NOT flag not-found while the app list is still loading (deep link + reload)', () => {
- const res = resolveOpenWorldFocus('beta', [], { loading: true });
- expect(res.hasFocus).toBe(true);
- expect(res.focusedApp).toBeNull();
- expect(res.notFound).toBe(false);
- });
-
- it('flags not-found for a stale/deleted id once loading has finished', () => {
- const res = resolveOpenWorldFocus('ghost', apps, { loading: false });
- expect(res.hasFocus).toBe(true);
- expect(res.focusedApp).toBeNull();
- expect(res.notFound).toBe(true);
- });
-
- it('tolerates a non-array app list', () => {
- expect(resolveOpenWorldFocus('alpha', null, { loading: false })).toEqual({
- hasFocus: true,
- focusedApp: null,
- notFound: true,
- });
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldGoalMonuments.js b/client/src/utils/openWorldGoalMonuments.js
deleted file mode 100644
index 022afdf0de..0000000000
--- a/client/src/utils/openWorldGoalMonuments.js
+++ /dev/null
@@ -1,356 +0,0 @@
-// Pure, deterministic helpers for OpenWorld's "goal monuments" (roadmap 2.7): each
-// life goal renders as a structure in a northeast monument district. Active goals are
-// construction sites (scaffolded/partial towers whose build completeness tracks
-// progress); completed goals are polished, fully-built monuments that shimmer; stalled
-// goals (active but with no recent progress) and abandoned goals read dim. The goal
-// list is capped to a sensible row; the rest are summarized by an overflow marker. No
-// three.js / React imports so the topology is unit-testable (mirrors openWorldFederation.js
-// / openWorldHealthTower.js).
-
-import { PARCELS } from './openWorldPlan';
-
-export const MONUMENTS = {
- // Northeast monument district — a row anchored by the master plan (openWorldPlan.js), clear
- // of the vault, task-queue, voice beacon, health tower, AI core, and productivity district.
- base: PARCELS.goals.anchor, // center of the row
- spacing: 9, // x-distance between adjacent monuments
- z: PARCELS.goals.anchor[2], // shared depth of the row
- maxMonuments: 8, // cap; goals beyond this fold into an overflow marker
- minHeight: 2, // floor height so even a 0%-progress site reads as a small structure
- fullHeight: 12, // height of a completed (100%) monument
- baseWidth: 2.4,
-};
-
-// Status → visual treatment. `dim` collapses opacity + glow so stalled/abandoned goals
-// recede; `built` flags a finished monument (drives the polished material + shimmer).
-const STATUS_STYLES = {
- completed: { color: '#22c55e', opacity: 1, intensity: 0.7, dim: false, built: true }, // port-success
- active: { color: '#3b82f6', opacity: 0.92, intensity: 0.4, dim: false, built: false }, // port-accent — under construction
- stalled: { color: '#f59e0b', opacity: 0.55, intensity: 0.18, dim: true, built: false }, // port-warning, dimmed
- abandoned: { color: '#64748b', opacity: 0.32, intensity: 0.08, dim: true, built: false }, // slate, dimmed
-};
-
-const DEFAULT_STYLE = STATUS_STYLES.active;
-
-const clamp01 = (n) => Math.max(0, Math.min(1, n));
-
-// Days since the most recent progressHistory entry (or createdAt as a fallback).
-// Returns null when there's nothing to measure from, so callers can distinguish
-// "no signal" from a real recency.
-export function daysSinceLastProgress(goal, now = Date.now()) {
- const history = Array.isArray(goal?.progressHistory) ? goal.progressHistory : [];
- let latest = null;
- for (const entry of history) {
- const t = entry?.date ? Date.parse(entry.date) : NaN;
- if (Number.isFinite(t) && (latest === null || t > latest)) latest = t;
- }
- if (latest === null) {
- const created = goal?.createdAt ? Date.parse(goal.createdAt) : NaN;
- if (Number.isFinite(created)) latest = created;
- }
- if (latest === null) return null;
- return Math.max(0, (now - latest) / (1000 * 60 * 60 * 24));
-}
-
-// Derive the *effective* status used for visualization. The stored status enum is
-// active | completed | abandoned (server: goalStatusEnum). "stalled" is a derived
-// state — an active, not-yet-complete goal with no progress in STALL_DAYS — so the
-// monument visibly dims when a goal goes quiet. Threshold is conservative.
-export const STALL_DAYS = 45;
-
-export function effectiveGoalStatus(goal, now = Date.now()) {
- const raw = goal?.status;
- if (raw === 'completed') return 'completed';
- if (raw === 'abandoned') return 'abandoned';
- // Treat anything else as active for styling purposes.
- const progress = Number.isFinite(goal?.progress) ? goal.progress : 0;
- if (progress >= 100) return 'completed';
- const idleDays = daysSinceLastProgress(goal, now);
- if (idleDays !== null && idleDays >= STALL_DAYS) return 'stalled';
- return 'active';
-}
-
-// Build completeness 0..1: completed monuments are always fully built; everything else
-// tracks `progress` (clamped). A present-but-zero progress reads as a 1-floor stub, not
-// nothing, so a freshly-created goal still shows on the row.
-export function buildCompleteness(goal, status) {
- if (status === 'completed') return 1;
- const progress = Number.isFinite(goal?.progress) ? goal.progress : 0;
- return clamp01(progress / 100);
-}
-
-// A milestone is "done" when it carries a completion timestamp (`completedAt`, the
-// server's stored field) or an explicit `completed: true` flag. Absent both, it's
-// pending. Kept tolerant so an older/foreign goal record doesn't crash the view.
-export function isMilestoneDone(milestone) {
- if (!milestone || typeof milestone !== 'object') return false;
- if (milestone.completed === true) return true;
- return typeof milestone.completedAt === 'string' && milestone.completedAt.length > 0;
-}
-
-// Break a monument's height into ordered milestone segments (floors). Each segment
-// reports its vertical extent (`y0`..`y1`, centered at `cy`) and whether the milestone
-// is done — so the component can render completed floors solid and pending floors as
-// translucent scaffold rungs. `height` is the monument's built+scaffold total; segments
-// are sorted by the milestone `order` field (stable, ties keep input order) and split the
-// height evenly. A goal with no milestones returns an empty array (the caller falls back
-// to the plain built/scaffold split). Pure + deterministic — no three.js.
-export function computeMilestoneSegments(goal, height) {
- const raw = Array.isArray(goal?.milestones) ? goal.milestones.filter((m) => m && typeof m === 'object') : [];
- if (raw.length === 0 || !(height > 0)) return [];
-
- // Stable order: by `order` field ascending, ties keep original index.
- const ordered = raw
- .map((milestone, i) => ({ milestone, i }))
- .sort((a, b) => {
- const oa = Number.isFinite(a.milestone.order) ? a.milestone.order : a.i;
- const ob = Number.isFinite(b.milestone.order) ? b.milestone.order : b.i;
- if (oa !== ob) return oa - ob;
- return a.i - b.i;
- });
-
- const segHeight = height / ordered.length;
- return ordered.map(({ milestone }, slot) => {
- const y0 = slot * segHeight;
- const y1 = y0 + segHeight;
- return {
- id: milestone.id || `ms-${slot}`,
- title: typeof milestone.title === 'string' && milestone.title ? milestone.title : `Milestone ${slot + 1}`,
- order: slot,
- done: isMilestoneDone(milestone),
- y0,
- y1,
- cy: (y0 + y1) / 2,
- segHeight,
- };
- });
-}
-
-// Stamp a monument view-model with its milestone segments + done/total counts. Used by
-// placeMonument and again by the forest layout after a spire's height is boosted (the
-// segments must be recomputed against the taller height). Mutates and returns `monument`.
-function attachMilestones(monument, goal, height) {
- monument.segments = computeMilestoneSegments(goal, height);
- monument.milestoneTotal = monument.segments.length;
- monument.milestoneDone = monument.segments.filter((s) => s.done).length;
- return monument;
-}
-
-// Status ordering shared by the flat row and the forest: completed first (trophies up
-// front), then active, stalled, abandoned; ties broken by goal id for a layout that
-// doesn't reshuffle across refetches. Used as an Array.sort comparator over items that
-// expose `{ status, id }`.
-const STATUS_RANK = { completed: 0, active: 1, stalled: 2, abandoned: 3 };
-function compareByStatusThenId(a, b) {
- const sa = STATUS_RANK[a.status] ?? 9;
- const sb = STATUS_RANK[b.status] ?? 9;
- if (sa !== sb) return sa - sb;
- return String(a.id || '').localeCompare(String(b.id || ''));
-}
-
-// Map one goal to its placed monument view-model. `index` is the slot in the row (0-based);
-// `count` is how many monuments are actually placed, so the row is centered on MONUMENTS.base.
-// When `position` is supplied (goal-forest layout) it overrides the centered-row placement,
-// so the same monument view-model serves both the flat row and the hierarchy spires.
-// `heightScale` (forest spires) boosts the tower height; passing it here means milestone
-// segments are computed once against the final height instead of re-segmented after.
-export function placeMonument(goal, index, count, now = Date.now(), position = null, heightScale = 1) {
- const status = effectiveGoalStatus(goal, now);
- const style = STATUS_STYLES[status] || DEFAULT_STYLE;
- const completeness = buildCompleteness(goal, status);
- const height = (MONUMENTS.minHeight + completeness * (MONUMENTS.fullHeight - MONUMENTS.minHeight)) * heightScale;
-
- // Center the row: slot 0 sits at the leftmost, the middle slot aligns with base.x.
- const offset = (index - (count - 1) / 2) * MONUMENTS.spacing;
- const x = MONUMENTS.base[0] + offset;
-
- return attachMilestones({
- id: goal?.id || `goal-${index}`,
- title: typeof goal?.title === 'string' && goal.title ? goal.title : 'Untitled Goal',
- status,
- progress: Number.isFinite(goal?.progress) ? clamp01(goal.progress / 100) * 100 : 0,
- completeness, // 0..1 — fraction of the monument that is "built"
- color: style.color,
- opacity: style.opacity,
- intensity: style.intensity,
- dim: style.dim,
- built: style.built,
- height,
- width: MONUMENTS.baseWidth,
- position: Array.isArray(position) ? position : [x, 0, MONUMENTS.z],
- }, goal, height);
-}
-
-// Full derived view-model for the component. `goals` is the raw goals list (the API
-// returns `{ goals: [...] }`; callers should pass `data?.goals`). A missing / non-array
-// input yields an empty district rather than a crash. Goals beyond MONUMENTS.maxMonuments
-// fold into an `overflow` marker placed just past the end of the row.
-export function computeGoalMonuments(goals, now = Date.now()) {
- const list = Array.isArray(goals) ? goals.filter((g) => g && typeof g === 'object') : [];
-
- // Stable ordering so the row doesn't reshuffle across refetches (see STATUS_RANK).
- const ranked = list
- .map((goal) => ({ goal, id: goal?.id, status: effectiveGoalStatus(goal, now) }))
- .sort(compareByStatusThenId);
-
- const visible = ranked.slice(0, MONUMENTS.maxMonuments);
- const overflowCount = Math.max(0, ranked.length - visible.length);
-
- const monuments = visible.map(({ goal }, index) =>
- placeMonument(goal, index, visible.length, now)
- );
-
- // Overflow marker sits one slot past the right end of the row.
- let overflow = null;
- if (overflowCount > 0) {
- const offset = (visible.length - (visible.length - 1) / 2) * MONUMENTS.spacing;
- overflow = {
- count: overflowCount,
- position: [MONUMENTS.base[0] + offset, 0, MONUMENTS.z],
- };
- }
-
- const completedCount = ranked.filter((r) => r.status === 'completed').length;
- const activeCount = ranked.filter((r) => r.status === 'active').length;
-
- return {
- base: MONUMENTS.base,
- monuments,
- overflow,
- total: ranked.length,
- completedCount,
- activeCount,
- hasData: ranked.length > 0,
- };
-}
-
-// Goal-tree (hierarchy) layout. Goals carry `parentId`; the server's getGoalsTree()
-// builds the same parent→child forest. Here we lay each ROOT goal out as a central spire
-// (taller than a flat-row monument) with its direct children clustered in a ring around
-// it and a link drawn from each child up to the parent apex — so a glance reads which
-// goals roll up under which. Multiple roots are spread along the row depth so their
-// clusters don't overlap. Pure + deterministic (no three.js): the component consumes the
-// returned positions/links directly.
-export const FOREST = {
- base: MONUMENTS.base, // shared center with the flat row
- clusterSpacing: 26, // x-distance between adjacent root clusters
- childRadius: 7.5, // ring radius of children around their root spire
- spireBoost: 1.5, // root spires render this much taller than a flat monument
- maxRoots: 4, // cap root clusters so the district stays legible
- maxChildren: 6, // cap children per root (ring slots); extras fold into the root's count
-};
-
-// Build the { id -> goal, children: [...] } forest from a flat goals list using parentId.
-// Mirrors getGoalsTree()'s tree builder: a goal whose parentId points at a present goal
-// becomes that goal's child; everything else (null/dangling parentId) is a root. Cycles
-// are impossible because the server validates parentId against ancestor cycles on write,
-// but we still guard by only attaching when the parent exists and isn't the node itself.
-export function buildGoalForest(goals) {
- const list = Array.isArray(goals) ? goals.filter((g) => g && typeof g === 'object' && g.id) : [];
- const byId = new Map(list.map((g) => [g.id, { goal: g, children: [] }]));
- const roots = [];
- for (const node of byId.values()) {
- const pid = node.goal.parentId;
- if (pid && pid !== node.goal.id && byId.has(pid)) {
- byId.get(pid).children.push(node);
- } else {
- roots.push(node);
- }
- }
- return { roots, byId };
-}
-
-// Total number of goals nested under a forest node (its children, grandchildren, …),
-// excluding the node itself. The forest layout renders only two visible levels (root spire
-// + child ring), so a node's deeper descendants are summarized by this count rather than
-// drawn — nothing is silently dropped. Guarded against the (server-prevented) cycle case
-// via a visited set so a hand-corrupted parentId loop can't recurse forever.
-export function countDescendants(node, seen = new Set()) {
- if (!node || seen.has(node)) return 0;
- seen.add(node);
- let total = 0;
- for (const child of node.children || []) {
- total += 1 + countDescendants(child, seen);
- }
- return total;
-}
-
-// Full hierarchy view-model. Returns root spires (each a placed monument with extra
-// height) plus their child monuments arranged in a ring, and `links` joining each child
-// apex-ward to its root. Roots are ordered completed→active→stalled→abandoned (same as the
-// flat row) so finished towers lead; ties broken by id for stable layout across refetches.
-export function computeGoalForest(goals, now = Date.now()) {
- const { roots } = buildGoalForest(goals);
-
- // Same completed→active→stalled→abandoned ordering as the flat row (see STATUS_RANK).
- const rankedRoots = roots
- .map((node) => ({ node, id: node.goal?.id, status: effectiveGoalStatus(node.goal, now) }))
- .sort(compareByStatusThenId);
-
- const visibleRoots = rankedRoots.slice(0, FOREST.maxRoots);
- // Root overflow counts the folded-away root trees AND everything nested under them, so a
- // child-bearing root past the cap isn't silently undercounted (it's `roots + descendants`).
- const rootOverflow = rankedRoots
- .slice(FOREST.maxRoots)
- .reduce((sum, { node }) => sum + 1 + countDescendants(node), 0);
-
- const clusters = visibleRoots.map(({ node }, rootIndex) => {
- // Spread root clusters along x, centered on FOREST.base.
- const clusterX = FOREST.base[0] + (rootIndex - (visibleRoots.length - 1) / 2) * FOREST.clusterSpacing;
- const clusterZ = FOREST.base[2];
-
- // Root spire — a placed monument boosted in height so it visually anchors the cluster.
- // The spireBoost is applied inside placeMonument so milestone floors fill the taller
- // tower in one pass (no discarded re-segment).
- const spire = placeMonument(node.goal, 0, 1, now, [clusterX, 0, clusterZ], FOREST.spireBoost);
- spire.isSpire = true;
-
- const childNodes = node.children.slice(0, FOREST.maxChildren);
- // Child overflow counts the folded-away children plus their own sub-trees, mirroring
- // the descendantCount surfaced on displayed children — nothing nested vanishes silently.
- const childOverflow = node.children
- .slice(FOREST.maxChildren)
- .reduce((sum, child) => sum + 1 + countDescendants(child), 0);
-
- // Children ring around the spire. A single child sits directly in front; multiple
- // children spread evenly across a forward-facing arc so links don't cross the spire.
- const children = childNodes.map((child, ci) => {
- const n = childNodes.length;
- const angle = n === 1 ? Math.PI / 2 : (Math.PI / (n + 1)) * (ci + 1); // 0..PI forward arc
- const cx = clusterX + Math.cos(angle) * FOREST.childRadius;
- const cz = clusterZ + Math.sin(angle) * FOREST.childRadius; // +z = toward the camera/front
- const m = placeMonument(child.goal, 0, 1, now, [cx, 0, cz]);
- m.parentId = node.goal.id;
- // Deeper descendants aren't drawn (the layout is two levels); surface their count so
- // a grandchild-bearing sub-goal advertises its sub-tree instead of hiding it.
- m.descendantCount = countDescendants(child);
- return m;
- });
-
- // Links: from each child's apex up to the root spire's apex. Towers rise from a 0.4
- // plinth, so the nominal top sits at 0.4 + height — links join near the tips (segmented
- // towers leave a sub-floor gap below this from the inter-floor spacing, visually fine).
- const links = children.map((child) => ({
- from: [child.position[0], 0.4 + child.height, child.position[2]],
- to: [spire.position[0], 0.4 + spire.height, spire.position[2]],
- childId: child.id,
- }));
-
- return { spire, children, links, childOverflow };
- });
-
- return {
- base: FOREST.base,
- clusters,
- rootOverflow,
- rootCount: rankedRoots.length,
- hasData: rankedRoots.length > 0,
- // A forest is only worth showing when at least one root actually has children;
- // otherwise it's just the flat row with extra spacing. The component uses this to
- // decide whether to render the hierarchy view vs. fall back to the flat row.
- // Derived from ALL ranked roots (pre-cap) so a child-bearing root that overflows past
- // FOREST.maxRoots still flips the district into the forest layout instead of the flat
- // row — otherwise its sub-tree would be invisible AND uncounted.
- hasHierarchy: rankedRoots.some(({ node }) => node.children.length > 0),
- };
-}
diff --git a/client/src/utils/openWorldGoalMonuments.test.js b/client/src/utils/openWorldGoalMonuments.test.js
deleted file mode 100644
index dbcb9248c4..0000000000
--- a/client/src/utils/openWorldGoalMonuments.test.js
+++ /dev/null
@@ -1,448 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- MONUMENTS,
- FOREST,
- STALL_DAYS,
- daysSinceLastProgress,
- effectiveGoalStatus,
- buildCompleteness,
- placeMonument,
- computeGoalMonuments,
- isMilestoneDone,
- computeMilestoneSegments,
- buildGoalForest,
- countDescendants,
- computeGoalForest,
-} from './openWorldGoalMonuments';
-
-const NOW = Date.parse('2026-06-03T00:00:00Z');
-const daysAgo = (d) => new Date(NOW - d * 24 * 60 * 60 * 1000).toISOString();
-
-const goal = (over = {}) => ({
- id: 'goal-1',
- title: 'Run a marathon',
- status: 'active',
- progress: 50,
- createdAt: daysAgo(10),
- progressHistory: [{ date: daysAgo(5), value: 50 }],
- ...over,
-});
-
-describe('daysSinceLastProgress', () => {
- it('measures from the most recent progressHistory entry', () => {
- const g = goal({ progressHistory: [{ date: daysAgo(3), value: 20 }, { date: daysAgo(10), value: 5 }] });
- expect(daysSinceLastProgress(g, NOW)).toBeCloseTo(3, 1);
- });
-
- it('falls back to createdAt when no history', () => {
- const g = goal({ progressHistory: [], createdAt: daysAgo(7) });
- expect(daysSinceLastProgress(g, NOW)).toBeCloseTo(7, 1);
- });
-
- it('returns null when there is no usable date', () => {
- expect(daysSinceLastProgress({ progressHistory: [] }, NOW)).toBeNull();
- expect(daysSinceLastProgress(null, NOW)).toBeNull();
- expect(daysSinceLastProgress({ progressHistory: [{ date: 'nope' }] }, NOW)).toBeNull();
- });
-});
-
-describe('effectiveGoalStatus', () => {
- it('maps stored completed/abandoned through unchanged', () => {
- expect(effectiveGoalStatus(goal({ status: 'completed' }), NOW)).toBe('completed');
- expect(effectiveGoalStatus(goal({ status: 'abandoned' }), NOW)).toBe('abandoned');
- });
-
- it('treats progress >= 100 as completed even if stored active', () => {
- expect(effectiveGoalStatus(goal({ status: 'active', progress: 100 }), NOW)).toBe('completed');
- });
-
- it('derives stalled for an active goal with no progress past the threshold', () => {
- const stale = goal({ progressHistory: [{ date: daysAgo(STALL_DAYS + 5), value: 50 }] });
- expect(effectiveGoalStatus(stale, NOW)).toBe('stalled');
- });
-
- it('keeps a recently-progressed active goal active', () => {
- const fresh = goal({ progressHistory: [{ date: daysAgo(2), value: 50 }] });
- expect(effectiveGoalStatus(fresh, NOW)).toBe('active');
- });
-
- it('defaults to active for an unknown/missing status', () => {
- expect(effectiveGoalStatus({ progressHistory: [{ date: daysAgo(1) }] }, NOW)).toBe('active');
- });
-});
-
-describe('buildCompleteness', () => {
- it('is always 1 for a completed monument', () => {
- expect(buildCompleteness(goal({ progress: 12 }), 'completed')).toBe(1);
- });
-
- it('tracks progress/100 for active, clamped', () => {
- expect(buildCompleteness(goal({ progress: 40 }), 'active')).toBeCloseTo(0.4);
- expect(buildCompleteness(goal({ progress: 250 }), 'active')).toBe(1);
- expect(buildCompleteness(goal({ progress: -5 }), 'active')).toBe(0);
- });
-
- it('treats missing progress as 0 (a floor stub), not a crash', () => {
- expect(buildCompleteness({}, 'active')).toBe(0);
- });
-});
-
-describe('placeMonument', () => {
- it('maps status to color/opacity/dim/built', () => {
- const completed = placeMonument(goal({ status: 'completed' }), 0, 1, NOW);
- expect(completed.built).toBe(true);
- expect(completed.dim).toBe(false);
- expect(completed.completeness).toBe(1);
- expect(completed.height).toBeCloseTo(MONUMENTS.fullHeight);
-
- const abandoned = placeMonument(goal({ status: 'abandoned' }), 0, 1, NOW);
- expect(abandoned.dim).toBe(true);
- expect(abandoned.built).toBe(false);
- expect(abandoned.opacity).toBeLessThan(completed.opacity);
- });
-
- it('progress drives height between min and full', () => {
- const half = placeMonument(goal({ status: 'active', progress: 50, progressHistory: [{ date: daysAgo(1) }] }), 0, 1, NOW);
- expect(half.height).toBeGreaterThan(MONUMENTS.minHeight);
- expect(half.height).toBeLessThan(MONUMENTS.fullHeight);
- });
-
- it('centers a single monument on base.x', () => {
- const only = placeMonument(goal(), 0, 1, NOW);
- expect(only.position[0]).toBeCloseTo(MONUMENTS.base[0]);
- expect(only.position[2]).toBe(MONUMENTS.z);
- });
-
- it('lays out a row centered around base.x with consistent spacing', () => {
- const a = placeMonument(goal(), 0, 3, NOW);
- const b = placeMonument(goal(), 1, 3, NOW);
- const c = placeMonument(goal(), 2, 3, NOW);
- expect(b.position[0]).toBeCloseTo(MONUMENTS.base[0]); // middle slot on center
- expect(b.position[0] - a.position[0]).toBeCloseTo(MONUMENTS.spacing);
- expect(c.position[0] - b.position[0]).toBeCloseTo(MONUMENTS.spacing);
- });
-
- it('falls back to a title and id without crashing', () => {
- const m = placeMonument({}, 2, 5, NOW);
- expect(m.title).toBe('Untitled Goal');
- expect(m.id).toBe('goal-2');
- });
-});
-
-describe('computeGoalMonuments', () => {
- it('handles missing / non-array input as an empty district', () => {
- for (const bad of [null, undefined, 'nope', 42, {}]) {
- const vm = computeGoalMonuments(bad, NOW);
- expect(vm.monuments).toEqual([]);
- expect(vm.overflow).toBeNull();
- expect(vm.hasData).toBe(false);
- expect(vm.total).toBe(0);
- }
- });
-
- it('places one monument per goal up to the cap', () => {
- const goals = Array.from({ length: 4 }, (_, i) => goal({ id: `g-${i}` }));
- const vm = computeGoalMonuments(goals, NOW);
- expect(vm.monuments).toHaveLength(4);
- expect(vm.overflow).toBeNull();
- expect(vm.total).toBe(4);
- expect(vm.hasData).toBe(true);
- });
-
- it('caps at maxMonuments and folds the rest into an overflow marker', () => {
- const goals = Array.from({ length: MONUMENTS.maxMonuments + 3 }, (_, i) => goal({ id: `g-${i}` }));
- const vm = computeGoalMonuments(goals, NOW);
- expect(vm.monuments).toHaveLength(MONUMENTS.maxMonuments);
- expect(vm.overflow).not.toBeNull();
- expect(vm.overflow.count).toBe(3);
- expect(vm.overflow.position[2]).toBe(MONUMENTS.z);
- expect(vm.total).toBe(MONUMENTS.maxMonuments + 3);
- });
-
- it('orders completed monuments before active before stalled before abandoned', () => {
- const goals = [
- goal({ id: 'ab', status: 'abandoned' }),
- goal({ id: 'co', status: 'completed' }),
- goal({ id: 'st', progressHistory: [{ date: daysAgo(STALL_DAYS + 1) }] }),
- goal({ id: 'ac', progressHistory: [{ date: daysAgo(1) }] }),
- ];
- const vm = computeGoalMonuments(goals, NOW);
- expect(vm.monuments.map((m) => m.status)).toEqual(['completed', 'active', 'stalled', 'abandoned']);
- });
-
- it('reports completed / active counts', () => {
- const goals = [
- goal({ id: 'a', status: 'completed' }),
- goal({ id: 'b', status: 'completed' }),
- goal({ id: 'c', progressHistory: [{ date: daysAgo(1) }] }),
- ];
- const vm = computeGoalMonuments(goals, NOW);
- expect(vm.completedCount).toBe(2);
- expect(vm.activeCount).toBe(1);
- });
-
- it('skips null / non-object entries without crashing', () => {
- const vm = computeGoalMonuments([null, goal({ id: 'ok' }), 'bad', 42], NOW);
- expect(vm.monuments).toHaveLength(1);
- expect(vm.monuments[0].id).toBe('ok');
- });
-});
-
-const milestone = (over = {}) => ({ id: `ms-${over.order ?? 0}`, title: `MS`, order: 0, completedAt: null, ...over });
-
-describe('isMilestoneDone', () => {
- it('is true when completedAt is a non-empty string', () => {
- expect(isMilestoneDone(milestone({ completedAt: '2026-01-01T00:00:00Z' }))).toBe(true);
- });
-
- it('is true when the explicit completed flag is set', () => {
- expect(isMilestoneDone(milestone({ completed: true, completedAt: null }))).toBe(true);
- });
-
- it('is false when neither signal is present', () => {
- expect(isMilestoneDone(milestone({ completedAt: null }))).toBe(false);
- expect(isMilestoneDone(milestone({ completedAt: '' }))).toBe(false);
- expect(isMilestoneDone(null)).toBe(false);
- expect(isMilestoneDone('nope')).toBe(false);
- });
-});
-
-describe('computeMilestoneSegments', () => {
- it('returns an empty array for a goal with no milestones', () => {
- expect(computeMilestoneSegments(goal({ milestones: [] }), 10)).toEqual([]);
- expect(computeMilestoneSegments(goal({ milestones: undefined }), 10)).toEqual([]);
- expect(computeMilestoneSegments(goal(), 0)).toEqual([]);
- });
-
- it('splits the height evenly into ordered, stacked floors', () => {
- const g = goal({ milestones: [milestone({ order: 0 }), milestone({ order: 1 }), milestone({ order: 2 })] });
- const segs = computeMilestoneSegments(g, 12);
- expect(segs).toHaveLength(3);
- expect(segs.map((s) => s.segHeight)).toEqual([4, 4, 4]);
- expect(segs[0].y0).toBe(0);
- expect(segs[0].y1).toBe(4);
- expect(segs[1].y0).toBe(4);
- expect(segs[2].y1).toBeCloseTo(12);
- expect(segs[1].cy).toBe(6);
- });
-
- it('sorts by the order field, ties keep input order', () => {
- const g = goal({ milestones: [
- milestone({ id: 'c', order: 2, title: 'Third' }),
- milestone({ id: 'a', order: 0, title: 'First' }),
- milestone({ id: 'b', order: 1, title: 'Second' }),
- ] });
- const segs = computeMilestoneSegments(g, 9);
- expect(segs.map((s) => s.title)).toEqual(['First', 'Second', 'Third']);
- expect(segs.map((s) => s.order)).toEqual([0, 1, 2]); // re-indexed slot order
- });
-
- it('falls back to input index when the order field is absent (manual milestones)', () => {
- // addMilestone() on the server omits `order`; computeMilestoneSegments must keep input
- // order for those (sort key = input index). An explicit `order` (AI phases set it)
- // sorts by its value; ties with an index-keyed entry break by original input index.
- const g = goal({ milestones: [
- { id: 'm1', title: 'First added' }, // no order → key = index 0
- { id: 'm2', title: 'Second added' }, // no order → key = index 1
- { id: 'm3', title: 'Phase', order: 5 }, // explicit order 5 → sorts last
- ] });
- const segs = computeMilestoneSegments(g, 9);
- expect(segs.map((s) => s.title)).toEqual(['First added', 'Second added', 'Phase']);
- });
-
- it('marks the done flag per milestone', () => {
- const g = goal({ milestones: [
- milestone({ order: 0, completedAt: '2026-01-01T00:00:00Z' }),
- milestone({ order: 1, completedAt: null }),
- ] });
- const segs = computeMilestoneSegments(g, 8);
- expect(segs[0].done).toBe(true);
- expect(segs[1].done).toBe(false);
- });
-
- it('skips non-object milestone entries', () => {
- const g = goal({ milestones: [null, milestone({ order: 0 }), 42] });
- expect(computeMilestoneSegments(g, 6)).toHaveLength(1);
- });
-});
-
-describe('placeMonument with milestones', () => {
- it('attaches milestone segments and done/total counts', () => {
- const g = goal({ status: 'active', progress: 60, progressHistory: [{ date: daysAgo(1) }], milestones: [
- milestone({ order: 0, completedAt: '2026-01-01T00:00:00Z' }),
- milestone({ order: 1, completedAt: '2026-02-01T00:00:00Z' }),
- milestone({ order: 2, completedAt: null }),
- ] });
- const m = placeMonument(g, 0, 1, NOW);
- expect(m.segments).toHaveLength(3);
- expect(m.milestoneTotal).toBe(3);
- expect(m.milestoneDone).toBe(2);
- });
-
- it('honors an explicit position override (forest layout)', () => {
- const m = placeMonument(goal(), 0, 1, NOW, [5, 0, -10]);
- expect(m.position).toEqual([5, 0, -10]);
- });
-
- it('reports zero milestones for a goal without any', () => {
- const m = placeMonument(goal({ milestones: [] }), 0, 1, NOW);
- expect(m.segments).toEqual([]);
- expect(m.milestoneTotal).toBe(0);
- expect(m.milestoneDone).toBe(0);
- });
-});
-
-describe('buildGoalForest', () => {
- it('attaches children under a present parent and leaves the rest as roots', () => {
- const goals = [
- goal({ id: 'root', parentId: null }),
- goal({ id: 'child-a', parentId: 'root' }),
- goal({ id: 'child-b', parentId: 'root' }),
- goal({ id: 'orphan', parentId: 'gone' }), // dangling parentId → root
- ];
- const { roots } = buildGoalForest(goals);
- const ids = roots.map((r) => r.goal.id).sort();
- expect(ids).toEqual(['orphan', 'root']);
- const root = roots.find((r) => r.goal.id === 'root');
- expect(root.children.map((c) => c.goal.id).sort()).toEqual(['child-a', 'child-b']);
- });
-
- it('does not attach a goal to itself', () => {
- const { roots } = buildGoalForest([goal({ id: 'self', parentId: 'self' })]);
- expect(roots).toHaveLength(1);
- expect(roots[0].children).toHaveLength(0);
- });
-
- it('ignores entries without an id or non-objects', () => {
- const { roots } = buildGoalForest([null, 'x', { parentId: 'p' }, goal({ id: 'ok' })]);
- expect(roots.map((r) => r.goal.id)).toEqual(['ok']);
- });
-
- it('nests grandchildren under children (multi-level)', () => {
- const { roots } = buildGoalForest([
- goal({ id: 'root', parentId: null }),
- goal({ id: 'child', parentId: 'root' }),
- goal({ id: 'grand', parentId: 'child' }),
- ]);
- expect(roots).toHaveLength(1);
- const child = roots[0].children[0];
- expect(child.goal.id).toBe('child');
- expect(child.children.map((g) => g.goal.id)).toEqual(['grand']);
- });
-});
-
-describe('countDescendants', () => {
- const forestOf = (goals) => buildGoalForest(goals).roots[0];
-
- it('counts children and grandchildren, excluding the node itself', () => {
- const root = forestOf([
- goal({ id: 'root', parentId: null }),
- goal({ id: 'c1', parentId: 'root' }),
- goal({ id: 'c2', parentId: 'root' }),
- goal({ id: 'g1', parentId: 'c1' }),
- goal({ id: 'g2', parentId: 'c1' }),
- ]);
- expect(countDescendants(root)).toBe(4); // c1, c2, g1, g2
- });
-
- it('is 0 for a leaf', () => {
- const root = forestOf([goal({ id: 'solo', parentId: null })]);
- expect(countDescendants(root)).toBe(0);
- });
-});
-
-describe('computeGoalForest', () => {
- const tree = () => [
- goal({ id: 'apex', parentId: null, status: 'active', progressHistory: [{ date: daysAgo(1) }] }),
- goal({ id: 'c1', parentId: 'apex', progressHistory: [{ date: daysAgo(1) }] }),
- goal({ id: 'c2', parentId: 'apex', progressHistory: [{ date: daysAgo(1) }] }),
- ];
-
- it('reports hasHierarchy only when a root has children', () => {
- const flat = computeGoalForest([goal({ id: 'a' }), goal({ id: 'b' })], NOW);
- expect(flat.hasHierarchy).toBe(false);
- const nested = computeGoalForest(tree(), NOW);
- expect(nested.hasHierarchy).toBe(true);
- });
-
- it('places a root spire taller than a flat monument and clusters its children', () => {
- const vm = computeGoalForest(tree(), NOW);
- expect(vm.clusters).toHaveLength(1);
- const cluster = vm.clusters[0];
- expect(cluster.spire.isSpire).toBe(true);
- const flat = placeMonument(goal({ id: 'apex', status: 'active', progressHistory: [{ date: daysAgo(1) }] }), 0, 1, NOW);
- expect(cluster.spire.height).toBeCloseTo(flat.height * FOREST.spireBoost);
- expect(cluster.children).toHaveLength(2);
- // Children carry a parentId back-reference and one link each to the spire apex.
- expect(cluster.children.every((c) => c.parentId === 'apex')).toBe(true);
- expect(cluster.links).toHaveLength(2);
- // Links join the tower tops, which sit a 0.4 plinth above the height baseline.
- expect(cluster.links[0].to).toEqual([cluster.spire.position[0], 0.4 + cluster.spire.height, cluster.spire.position[2]]);
- });
-
- it('centers a single root cluster on FOREST.base', () => {
- const vm = computeGoalForest(tree(), NOW);
- expect(vm.clusters[0].spire.position[0]).toBeCloseTo(FOREST.base[0]);
- expect(vm.clusters[0].spire.position[2]).toBe(FOREST.base[2]);
- });
-
- it('caps root clusters and reports the overflow (folded roots + their descendants)', () => {
- const goals = [];
- for (let i = 0; i < FOREST.maxRoots + 2; i++) {
- goals.push(goal({ id: `r${i}`, parentId: null }));
- goals.push(goal({ id: `c${i}`, parentId: `r${i}` }));
- }
- const vm = computeGoalForest(goals, NOW);
- expect(vm.clusters).toHaveLength(FOREST.maxRoots);
- // 2 overflowed roots, each with 1 child → 2 * (1 + 1) = 4 goals folded away.
- expect(vm.rootOverflow).toBe(4);
- expect(vm.rootCount).toBe(FOREST.maxRoots + 2);
- });
-
- it('flips to the forest view when only an OVERFLOWED root has children', () => {
- // First maxRoots roots are flat leaves; the next root (which overflows the cap) is the
- // only one with a child. hasHierarchy must be derived pre-cap so the forest still shows.
- // Status ties sort by id ascending, so the flat roots use ids that sort BEFORE the deep
- // one ('aflat*' < 'zdeep-root') to guarantee the child-bearing root lands past the cap.
- const goals = [];
- for (let i = 0; i < FOREST.maxRoots; i++) goals.push(goal({ id: `aflat${i}`, parentId: null }));
- goals.push(goal({ id: 'zdeep-root', parentId: null }));
- goals.push(goal({ id: 'zdeep-child', parentId: 'zdeep-root' }));
- const vm = computeGoalForest(goals, NOW);
- // The child-bearing root is beyond FOREST.maxRoots, so it is NOT in the visible clusters…
- expect(vm.clusters.every((c) => c.children.length === 0)).toBe(true);
- // …yet the district must still pick the forest layout (pre-cap hierarchy detection)…
- expect(vm.hasHierarchy).toBe(true);
- // …and the overflowed root + its child are both counted, not silently dropped.
- expect(vm.rootOverflow).toBe(2);
- });
-
- it('surfaces a descendant count on a child that has its own sub-tree (no silent drop)', () => {
- const vm = computeGoalForest([
- goal({ id: 'apex', parentId: null }),
- goal({ id: 'child', parentId: 'apex', progressHistory: [{ date: daysAgo(1) }] }),
- goal({ id: 'grand1', parentId: 'child' }),
- goal({ id: 'grand2', parentId: 'child' }),
- ], NOW);
- const child = vm.clusters[0].children.find((c) => c.id === 'child');
- expect(child.descendantCount).toBe(2); // grand1 + grand2, summarized not dropped
- });
-
- it('caps children per root and reports childOverflow', () => {
- const goals = [goal({ id: 'apex', parentId: null })];
- for (let i = 0; i < FOREST.maxChildren + 3; i++) goals.push(goal({ id: `c${i}`, parentId: 'apex' }));
- const vm = computeGoalForest(goals, NOW);
- expect(vm.clusters[0].children).toHaveLength(FOREST.maxChildren);
- expect(vm.clusters[0].childOverflow).toBe(3);
- });
-
- it('handles missing / non-array input as an empty forest', () => {
- for (const bad of [null, undefined, 'nope', 42, {}]) {
- const vm = computeGoalForest(bad, NOW);
- expect(vm.clusters).toEqual([]);
- expect(vm.hasData).toBe(false);
- expect(vm.hasHierarchy).toBe(false);
- }
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldHealthTower.js b/client/src/utils/openWorldHealthTower.js
deleted file mode 100644
index 481b5e3d1a..0000000000
--- a/client/src/utils/openWorldHealthTower.js
+++ /dev/null
@@ -1,98 +0,0 @@
-// Pure, deterministic helpers for OpenWorld's biometric vitals tower (roadmap 2.9): a
-// stacked landmark in a far-southeast wellness district whose segments visualize the
-// latest Apple Health metrics (heart rate / steps / sleep / active calories). Each
-// segment's height and glow track that metric's normalized level; a metric with no data
-// reads dim (absent) — distinct from a metric whose value is legitimately zero (e.g. a
-// 0-step day). No three.js / React imports so the topology is unit-testable (mirrors
-// openWorldBackupVault.js / openWorldTaskQueue.js).
-
-import { PARCELS } from './openWorldPlan';
-
-export const TOWER = {
- position: PARCELS.health.anchor, // far southeast — a wellness district anchored by the master plan (openWorldPlan.js)
- baseRadius: 3.2,
- segmentHeight: 3, // height of a fully-lit (level === 1) segment
- segmentGap: 0.25, // vertical gap between stacked segments
- minHeight: 0.35, // floor height so an absent/zero segment still reads as a thin disc, not nothing
-};
-
-// One descriptor per visualized metric, in stacking order (bottom → top). `key` is the
-// Apple Health metric name as returned by GET /api/health/metrics/latest; `target` is the
-// value mapped to a full (level === 1) segment; `color` reuses the meatspace health palette
-// (which itself maps to PortOS tokens) so the tower speaks the same visual language.
-export const METRICS = [
- { key: 'heart_rate', label: 'HEART', unit: 'bpm', target: 120, color: '#ef4444' }, // port-error red — the pulsing segment
- { key: 'step_count', label: 'STEPS', unit: 'steps', target: 10000, color: '#3b82f6' }, // port-accent blue
- { key: 'active_energy', label: 'CALORIES', unit: 'Cal', target: 600, color: '#f59e0b' }, // port-warning amber
- { key: 'sleep_analysis', label: 'SLEEP', unit: 'hrs', target: 8, color: '#8b5cf6' }, // violet
-];
-
-const DIM_COLOR = '#475569'; // slate — an absent (no-data) segment
-
-const clamp01 = (n) => Math.max(0, Math.min(1, n));
-
-// Normalize a raw metric value to a 0..1 level against its target, clamped. Returns null
-// for a non-finite input so callers can distinguish "no usable number" from a real 0.
-export function normalizeLevel(value, target) {
- if (typeof value !== 'number' || !Number.isFinite(value)) return null;
- if (typeof target !== 'number' || !Number.isFinite(target) || target <= 0) return null;
- return clamp01(value / target);
-}
-
-// Derive a single segment's view-model from the latest-metrics payload entry. The endpoint
-// returns `{ date, value } | null` per metric — null (or a missing key) is the "absent"
-// sentinel and must NOT collapse into the same state as a present value of 0.
-export function computeSegment(descriptor, entry) {
- // Absent: key missing, null entry, or a non-numeric/absent value field.
- const rawValue = entry && typeof entry === 'object' ? entry.value : undefined;
- const hasValue = typeof rawValue === 'number' && Number.isFinite(rawValue);
- // normalizeLevel returns null when the value/target can't be normalized; an absent or
- // unnormalizable segment renders at level 0 (its `present` flag disambiguates from a real 0).
- const level = (hasValue ? normalizeLevel(rawValue, descriptor.target) : null) ?? 0;
- return {
- key: descriptor.key,
- label: descriptor.label,
- unit: descriptor.unit,
- present: hasValue,
- value: hasValue ? rawValue : null,
- date: entry && typeof entry === 'object' ? entry.date ?? null : null,
- level, // 0..1; 0 for both an absent segment and a legitimate zero — `present` disambiguates
- color: hasValue ? descriptor.color : DIM_COLOR,
- // Lit segment height scales with level (with a thin floor so it's always visible); an
- // absent segment collapses to the floor height and reads dim.
- height: TOWER.minHeight + (hasValue ? level : 0) * TOWER.segmentHeight,
- // Emissive intensity: present segments glow proportional to level (with a small base so
- // even a zero-value-but-present segment is faintly lit); absent segments stay dark.
- intensity: hasValue ? 0.25 + level * 0.75 : 0.08,
- };
-}
-
-// Full derived view-model for the component: a fixed base position plus a bottom→top stack
-// of segments with their y offsets pre-computed. `latest` is the raw latest-metrics payload
-// (`{ [metricKey]: { date, value } | null }`); a missing/non-object payload yields an
-// all-absent tower rather than a crash.
-export function computeHealthTower(latest) {
- const payload = latest && typeof latest === 'object' ? latest : {};
- let y = 0;
- const segments = METRICS.map((descriptor) => {
- const segment = computeSegment(descriptor, payload[descriptor.key]);
- const placed = { ...segment, y: y + segment.height / 2 };
- y += segment.height + TOWER.segmentGap;
- return placed;
- });
- const presentCount = segments.filter((s) => s.present).length;
- // The heart-rate segment drives the heartbeat pulse; pre-extract its level/intensity/
- // presence so the component's per-frame loop never re-searches the segment list.
- const heart = segments.find((s) => s.key === 'heart_rate');
- return {
- position: TOWER.position,
- baseRadius: TOWER.baseRadius,
- segments,
- totalHeight: y - (segments.length ? TOWER.segmentGap : 0), // top of the highest segment
- presentCount,
- hasData: presentCount > 0,
- heartPresent: heart?.present ?? false,
- heartLevel: heart?.level ?? 0,
- heartIntensity: heart?.intensity ?? 0,
- };
-}
diff --git a/client/src/utils/openWorldHealthTower.test.js b/client/src/utils/openWorldHealthTower.test.js
deleted file mode 100644
index 2a10f11db4..0000000000
--- a/client/src/utils/openWorldHealthTower.test.js
+++ /dev/null
@@ -1,158 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- TOWER,
- METRICS,
- normalizeLevel,
- computeSegment,
- computeHealthTower,
-} from './openWorldHealthTower';
-
-const full = {
- heart_rate: { date: '2026-06-01', value: 60 },
- step_count: { date: '2026-06-01', value: 5000 },
- active_energy: { date: '2026-06-01', value: 300 },
- sleep_analysis: { date: '2026-06-01', value: 4 },
-};
-
-describe('normalizeLevel', () => {
- it('maps value/target into 0..1', () => {
- expect(normalizeLevel(5000, 10000)).toBe(0.5);
- expect(normalizeLevel(120, 120)).toBe(1);
- });
-
- it('clamps above target to 1 and below zero to 0', () => {
- expect(normalizeLevel(99999, 10000)).toBe(1);
- expect(normalizeLevel(-50, 10000)).toBe(0);
- });
-
- it('returns null for non-finite values or bad targets', () => {
- expect(normalizeLevel(NaN, 10000)).toBeNull();
- expect(normalizeLevel(undefined, 10000)).toBeNull();
- expect(normalizeLevel('5000', 10000)).toBeNull();
- expect(normalizeLevel(5000, 0)).toBeNull();
- expect(normalizeLevel(5000, -1)).toBeNull();
- });
-
- it('treats a legitimate zero value as level 0, not absent', () => {
- expect(normalizeLevel(0, 10000)).toBe(0);
- });
-});
-
-describe('computeSegment', () => {
- const heart = METRICS.find((m) => m.key === 'heart_rate');
-
- it('derives a present segment with proportional level and full color', () => {
- const seg = computeSegment(heart, { date: '2026-06-01', value: 60 });
- expect(seg.present).toBe(true);
- expect(seg.value).toBe(60);
- expect(seg.level).toBe(0.5);
- expect(seg.color).toBe(heart.color);
- expect(seg.height).toBeGreaterThan(TOWER.minHeight);
- });
-
- it('distinguishes a zero-value-but-present metric from an absent one', () => {
- const zero = computeSegment(heart, { date: '2026-06-01', value: 0 });
- expect(zero.present).toBe(true);
- expect(zero.value).toBe(0);
- expect(zero.level).toBe(0);
- expect(zero.color).toBe(heart.color); // still lit color, not the dim slate
- expect(zero.height).toBeCloseTo(TOWER.minHeight);
- expect(zero.intensity).toBeGreaterThan(0.08); // faintly lit, above the absent floor
-
- const absent = computeSegment(heart, null);
- expect(absent.present).toBe(false);
- expect(absent.value).toBeNull();
- expect(absent.level).toBe(0);
- expect(absent.color).not.toBe(heart.color); // dim slate
- expect(absent.height).toBeCloseTo(TOWER.minHeight);
- expect(absent.intensity).toBeLessThan(zero.intensity);
- });
-
- it('treats a missing/undefined entry as absent without crashing', () => {
- expect(computeSegment(heart, undefined).present).toBe(false);
- expect(computeSegment(heart, {}).present).toBe(false);
- expect(computeSegment(heart, { date: '2026-06-01', value: null }).present).toBe(false);
- expect(computeSegment(heart, { value: 'oops' }).present).toBe(false);
- });
-
- it('clamps a level above target to 1', () => {
- const seg = computeSegment(heart, { value: 999 });
- expect(seg.level).toBe(1);
- expect(seg.height).toBeCloseTo(TOWER.minHeight + TOWER.segmentHeight);
- });
-});
-
-describe('computeHealthTower', () => {
- it('carries the fixed position and base radius through unchanged', () => {
- const vm = computeHealthTower(full);
- expect(vm.position).toEqual(TOWER.position);
- expect(vm.baseRadius).toBe(TOWER.baseRadius);
- });
-
- it('produces one segment per metric in stacking order', () => {
- const vm = computeHealthTower(full);
- expect(vm.segments).toHaveLength(METRICS.length);
- expect(vm.segments.map((s) => s.key)).toEqual(METRICS.map((m) => m.key));
- });
-
- it('stacks segments upward with strictly increasing y', () => {
- const vm = computeHealthTower(full);
- for (let i = 1; i < vm.segments.length; i++) {
- expect(vm.segments[i].y).toBeGreaterThan(vm.segments[i - 1].y);
- }
- });
-
- it('reports presentCount and hasData from full metrics', () => {
- const vm = computeHealthTower(full);
- expect(vm.presentCount).toBe(METRICS.length);
- expect(vm.hasData).toBe(true);
- expect(vm.heartLevel).toBeCloseTo(0.5);
- });
-
- it('handles partial metrics — absent segments dim, present ones lit', () => {
- const vm = computeHealthTower({ step_count: { value: 10000 } });
- expect(vm.presentCount).toBe(1);
- expect(vm.hasData).toBe(true);
- const steps = vm.segments.find((s) => s.key === 'step_count');
- const heart = vm.segments.find((s) => s.key === 'heart_rate');
- expect(steps.present).toBe(true);
- expect(steps.level).toBe(1);
- expect(heart.present).toBe(false);
- expect(heart.level).toBe(0);
- });
-
- it('handles an all-null payload as an all-absent tower (no crash)', () => {
- const vm = computeHealthTower({
- heart_rate: null,
- step_count: null,
- active_energy: null,
- sleep_analysis: null,
- });
- expect(vm.presentCount).toBe(0);
- expect(vm.hasData).toBe(false);
- expect(vm.segments.every((s) => !s.present)).toBe(true);
- });
-
- it('handles null / undefined / non-object input as all-absent', () => {
- for (const bad of [null, undefined, 'nope', 42, []]) {
- const vm = computeHealthTower(bad);
- expect(vm.presentCount).toBe(0);
- expect(vm.hasData).toBe(false);
- expect(vm.segments).toHaveLength(METRICS.length);
- }
- });
-
- it('keeps all segment levels within [0,1]', () => {
- const vm = computeHealthTower({
- heart_rate: { value: -10 },
- step_count: { value: 1e9 },
- active_energy: { value: 0 },
- sleep_analysis: { value: 8 },
- });
- for (const s of vm.segments) {
- expect(s.level).toBeGreaterThanOrEqual(0);
- expect(s.level).toBeLessThanOrEqual(1);
- }
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldInteriorWindows.js b/client/src/utils/openWorldInteriorWindows.js
deleted file mode 100644
index 92aa06b94c..0000000000
--- a/client/src/utils/openWorldInteriorWindows.js
+++ /dev/null
@@ -1,111 +0,0 @@
-// Procedural window-grid layout for OpenWorld buildings that use the
-// InteriorMappingMaterial interior-mapping material (parallax fake-3D rooms
-// behind flat window panes). The geometry/material live in
-// `client/src/components/openworld/BuildingWindows.jsx`; this module is the pure,
-// side-effect-free math it consumes so the placement is unit-testable without a
-// WebGL context (headless GL can't render the city — see the city visual
-// verification notes).
-//
-// A building's four vertical faces are each tiled with a centered grid of square
-// panes. Each pane becomes one InstancedMesh instance carrying a deterministic
-// `windowId` (vec3) the shader hashes to pick an interior room cell and to decide
-// lit/unlit + warm/cool, so a building keeps the exact same lit rooms forever
-// (same determinism contract as the flat window texture and rooftop kits).
-
-// Pane + spacing geometry, in building-local world units. Tuned so a default
-// 2.0-wide face reads as ~4 columns of distinct windows and a 5-tall online
-// tower as ~7 stacked floors.
-export const INTERIOR_WINDOW = {
- size: 0.26, // square pane edge
- gapX: 0.14, // horizontal gap between panes
- gapY: 0.22, // vertical gap (taller → reads as stacked floors)
- inset: 0.015, // how far the pane sits proud of the wall (avoids z-fighting)
- edgePad: 0.2, // horizontal margin kept clear at each face edge
- marginBottom: 0.5, // skip the ground-floor / base-glow band
- marginTop: 0.5, // skip the roof cap + crown floor band
- // Below this building height there isn't enough clear facade for a readable
- // grid, so the building keeps just its flat emissive window texture.
- minHeight: 3,
-};
-
-// Which buildings get interior-mapped windows. Kept deliberately narrow ("some
-// of the buildings"): online, non-archived towers tall enough for a real grid.
-// Stopped/idle/short buildings stay on the cheaper flat texture. Height is read
-// from the already-resolved value (getBuildingHeight) rather than recomputed.
-export function buildingHasInteriorWindows(app, height) {
- if (!app || app.archived) return false;
- if (!(height >= INTERIOR_WINDOW.minHeight)) return false;
- return app.overallStatus === 'online';
-}
-
-// Count panes that fit along a span, centered, given pane size + gap. Returns 0
-// when not even one pane fits in the usable span.
-function fitCount(span, size, gap) {
- if (!(span > 0)) return 0;
- return Math.max(0, Math.floor((span + gap) / (size + gap)));
-}
-
-// The four vertical faces, as (faceIndex, rotationY about the building's up axis,
-// outward normal axis + sign). PlaneGeometry faces +Z at rotation 0.
-const FACES = [
- { index: 0, axis: 'z', sign: 1, rotationY: 0 }, // front (+Z)
- { index: 1, axis: 'z', sign: -1, rotationY: Math.PI }, // back (-Z)
- { index: 2, axis: 'x', sign: 1, rotationY: Math.PI / 2 }, // right (+X)
- { index: 3, axis: 'x', sign: -1, rotationY: -Math.PI / 2 }, // left (-X)
-];
-
-// Compute every window instance for a building. Returns a flat array of
-// `{ position: [x,y,z], rotationY, windowId: [a,b,c] }`. `planeSize` (the square
-// pane edge) is uniform across all panes, so the material's `planeSize` uniform
-// is just `INTERIOR_WINDOW.size`.
-export function computeWindowGrid({ width, depth, height, seed = 0 }) {
- const { size, gapX, gapY, inset, edgePad, marginBottom, marginTop } = INTERIOR_WINDOW;
- const usableH = height - marginBottom - marginTop;
- const rows = fitCount(usableH, size, gapY);
- if (rows <= 0) return [];
-
- const gridH = rows * size + (rows - 1) * gapY;
- const startY = marginBottom + (usableH - gridH) / 2 + size / 2;
- const stepY = size + gapY;
-
- const windows = [];
- for (const face of FACES) {
- // The horizontal extent of this face: building width for front/back, depth
- // for the sides. The pane plane is always normal to the face's axis.
- const faceWidth = face.axis === 'z' ? width : depth;
- const usableW = faceWidth - 2 * edgePad;
- const cols = fitCount(usableW, size, gapX);
- if (cols <= 0) continue;
-
- const gridW = cols * size + (cols - 1) * gapX;
- const startH = -gridW / 2 + size / 2;
- const stepX = size + gapX;
- // Distance from center out to the (slightly proud) face plane.
- const offset = (face.axis === 'z' ? depth : width) / 2 + inset;
-
- for (let r = 0; r < rows; r++) {
- const y = startY + r * stepY;
- for (let c = 0; c < cols; c++) {
- const h = startH + c * stepX; // position along the face's horizontal axis
- const position = face.axis === 'z'
- ? [h, y, face.sign * offset]
- : [face.sign * offset, y, h];
- // Deterministic, well-spread seed per pane so the shader hash varies
- // per window, per face, and per building. Keep every component SMALL: the
- // IDs round-trip through a Float32Array for the instanced attribute, and
- // float32 loses sub-integer precision past ~16.7M — a raw app-name hash
- // (hundreds of millions) would swamp the c/r offsets and collapse every
- // pane on a face to one room. A bounded per-building phase shifts the
- // hash input without dominating the per-pane column/row offsets.
- const phase = seed % 360;
- const windowId = [
- c + face.index * 2.3 + phase * 0.11,
- r + face.index * 1.7 + phase * 0.07,
- face.index + (seed % 17) * 0.13,
- ];
- windows.push({ position, rotationY: face.rotationY, windowId });
- }
- }
- }
- return windows;
-}
diff --git a/client/src/utils/openWorldInteriorWindows.test.js b/client/src/utils/openWorldInteriorWindows.test.js
deleted file mode 100644
index f3aec3ce64..0000000000
--- a/client/src/utils/openWorldInteriorWindows.test.js
+++ /dev/null
@@ -1,102 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- INTERIOR_WINDOW,
- buildingHasInteriorWindows,
- computeWindowGrid,
-} from './openWorldInteriorWindows';
-
-describe('buildingHasInteriorWindows', () => {
- it('selects online, non-archived towers tall enough for a grid', () => {
- expect(buildingHasInteriorWindows({ overallStatus: 'online' }, 5)).toBe(true);
- });
-
- it('rejects archived buildings even when online and tall', () => {
- expect(buildingHasInteriorWindows({ overallStatus: 'online', archived: true }, 5)).toBe(false);
- });
-
- it('rejects non-online statuses', () => {
- for (const overallStatus of ['stopped', 'not_started', 'not_found', 'unknown']) {
- expect(buildingHasInteriorWindows({ overallStatus }, 5)).toBe(false);
- }
- });
-
- it('rejects towers below the minimum height', () => {
- expect(buildingHasInteriorWindows({ overallStatus: 'online' }, INTERIOR_WINDOW.minHeight - 0.01)).toBe(false);
- expect(buildingHasInteriorWindows({ overallStatus: 'online' }, INTERIOR_WINDOW.minHeight)).toBe(true);
- });
-
- it('rejects a missing app', () => {
- expect(buildingHasInteriorWindows(null, 5)).toBe(false);
- expect(buildingHasInteriorWindows(undefined, 5)).toBe(false);
- });
-});
-
-describe('computeWindowGrid', () => {
- // Asymmetric width !== depth so the per-face extent logic is actually
- // exercised (a width/depth swap in the placement math would change results).
- const dims = { width: 3, depth: 2, height: 5, seed: 42 };
-
- it('tiles all four vertical faces', () => {
- const windows = computeWindowGrid(dims);
- expect(windows.length).toBeGreaterThan(0);
- const rotations = new Set(windows.map((w) => w.rotationY.toFixed(4)));
- expect(rotations).toEqual(
- new Set([0, Math.PI, Math.PI / 2, -Math.PI / 2].map((r) => r.toFixed(4)))
- );
- });
-
- it('is deterministic for the same input', () => {
- expect(computeWindowGrid(dims)).toEqual(computeWindowGrid(dims));
- });
-
- it('varies window ids by seed', () => {
- const a = computeWindowGrid(dims);
- const b = computeWindowGrid({ ...dims, seed: 43 });
- expect(a[0].windowId).not.toEqual(b[0].windowId);
- });
-
- it('keeps per-pane window ids distinct after the Float32Array round-trip, even for a large hash', () => {
- // The instanced attribute stores windowId in a Float32Array, which loses
- // sub-integer precision past ~16.7M. A raw app-name hash this large must not
- // collapse every pane on a face to the same id (which would make every room
- // identical). Quantize through Float32Array exactly as the GPU upload does.
- const windows = computeWindowGrid({ width: 3, depth: 2, height: 5, seed: 1234567890 });
- const buf = new Float32Array(windows.length * 3);
- windows.forEach((w, i) => buf.set(w.windowId, i * 3));
- const keys = new Set(Array.from({ length: windows.length }, (_, i) => buf.slice(i * 3, i * 3 + 3).join(',')));
- // Distinct ids per pane (allow a tiny collision margin from the modular phase).
- expect(keys.size).toBeGreaterThan(windows.length * 0.9);
- });
-
- it('places panes proud of the correct face plane', () => {
- const { width, depth } = dims;
- const offset = depth / 2 + INTERIOR_WINDOW.inset;
- for (const w of computeWindowGrid(dims)) {
- const [x, , z] = w.position;
- if (w.rotationY === 0) expect(z).toBeCloseTo(offset, 5);
- else if (w.rotationY === Math.PI) expect(z).toBeCloseTo(-offset, 5);
- else if (w.rotationY === Math.PI / 2) expect(x).toBeCloseTo(width / 2 + INTERIOR_WINDOW.inset, 5);
- else if (w.rotationY === -Math.PI / 2) expect(x).toBeCloseTo(-(width / 2 + INTERIOR_WINDOW.inset), 5);
- }
- });
-
- it('keeps every pane within the usable vertical band and its own face width', () => {
- const { width, depth, height } = dims;
- for (const w of computeWindowGrid(dims)) {
- const [x, y, z] = w.position;
- expect(y).toBeGreaterThanOrEqual(INTERIOR_WINDOW.marginBottom);
- expect(y).toBeLessThanOrEqual(height - INTERIOR_WINDOW.marginTop);
- // Front/back faces span `width` (along x); side faces span `depth` (along
- // z). Each pane must stay inside the half-extent of its own face.
- const frontBack = w.rotationY === 0 || w.rotationY === Math.PI;
- const horiz = frontBack ? x : z;
- const halfExtent = (frontBack ? width : depth) / 2;
- expect(Math.abs(horiz)).toBeLessThanOrEqual(halfExtent);
- }
- });
-
- it('returns no windows when the tower is too short for a single row', () => {
- expect(computeWindowGrid({ width: 2, depth: 2, height: 1, seed: 1 })).toEqual([]);
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldJiraDistrict.js b/client/src/utils/openWorldJiraDistrict.js
deleted file mode 100644
index 14b50c4d0a..0000000000
--- a/client/src/utils/openWorldJiraDistrict.js
+++ /dev/null
@@ -1,114 +0,0 @@
-// Pure, deterministic helpers for OpenWorld's JIRA sprint district (roadmap 3.7): the current
-// sprint's tickets become a small construction yard southeast-north of downtown. Each ticket is
-// a structure whose form reads its workflow state — To-Do tickets are stacked crates waiting to
-// be built, In-Progress tickets are under-construction frames (scaffold), and Done tickets are
-// finished, lit buildings. Tickets are gathered across every JIRA-enabled app, deduped by key.
-// No three.js / React imports so the topology is unit-testable (mirrors openWorldTaskQueue.js etc.).
-
-import { gridIndexToPosition, tallyByKey, scaleMetricToHeight } from './openWorldDistrictLayout';
-import { PARCELS } from './openWorldPlan';
-
-export const JIRA_DISTRICT = {
- // North-of-downtown yard between the goal monuments and downtown, on the -X side so it
- // doesn't collide with the artifact hall or memory quarter. Anchored by openWorldPlan.js;
- // sits near the shoreline on purpose — a dockside construction yard.
- base: PARCELS.jira.anchor,
- columns: 6, // structures per row before wrapping toward -Z
- spacing: 3.2, // distance between adjacent structures
- maxStructures: 24, // cap; overflow folds into a "+N MORE" marker
- crateSize: 1.1,
- maxHeight: 4.5,
-};
-
-// JIRA's three status categories. We normalize the API's statusCategory name to one of these
-// buckets; an unrecognized/blank category is treated as 'todo' (safest — it shows as unbuilt).
-export const SPRINT_STATES = {
- todo: { key: 'todo', label: 'TO DO', color: '#64748b' }, // slate — not started
- inProgress: { key: 'inProgress', label: 'IN PROGRESS', color: '#f59e0b' }, // amber — building
- done: { key: 'done', label: 'DONE', color: '#22c55e' }, // green — complete
-};
-
-// Map a ticket's JIRA statusCategory to one of our three buckets. JIRA uses the category names
-// "To Do" / "In Progress" / "Done" (and the key forms new/indeterminate/done); accept both.
-export function ticketState(ticket) {
- const raw = String(ticket?.statusCategory || '').toLowerCase().trim();
- if (raw === 'done' || raw === 'complete') return 'done';
- if (raw === 'in progress' || raw === 'indeterminate') return 'inProgress';
- return 'todo'; // "to do" / "new" / unknown / blank
-}
-
-// Story-point-driven height so a chunky ticket reads as a taller structure; defaults to a 1-point
-// floor when the ticket carries no estimate so every ticket is at least a visible crate.
-export function structureHeight(storyPoints) {
- const pts = Number.isFinite(storyPoints) && storyPoints > 0 ? storyPoints : 1;
- return scaleMetricToHeight(pts, { max: JIRA_DISTRICT.maxHeight, k: 1.1, base: 0.9 });
-}
-
-// Dedupe tickets across apps by key (the same JIRA ticket can surface under two apps that share a
-// project) and sort into a stable render order: done → in-progress → to-do, then by key, so the
-// yard reads left-to-right as "finished work piling up" with active work in the middle.
-const STATE_ORDER = { done: 0, inProgress: 1, todo: 2 };
-export function dedupeAndSort(tickets) {
- const byKey = new Map();
- for (const t of Array.isArray(tickets) ? tickets : []) {
- if (!t?.key || byKey.has(t.key)) continue;
- byKey.set(t.key, t);
- }
- return [...byKey.values()].sort((a, b) => {
- const sa = STATE_ORDER[ticketState(a)] ?? 3;
- const sb = STATE_ORDER[ticketState(b)] ?? 3;
- return sa - sb || String(a.key).localeCompare(String(b.key));
- });
-}
-
-// Grid position for the i-th structure in the yard: rows wrap toward -Z, centered on the base X.
-export function structurePosition(index, opts = {}) {
- return gridIndexToPosition(index, {
- base: opts.base || JIRA_DISTRICT.base,
- columns: opts.columns ?? JIRA_DISTRICT.columns,
- spacing: opts.spacing ?? JIRA_DISTRICT.spacing,
- rowDir: -1, // rows pile toward -Z so the yard reads receding from the viewer
- });
-}
-
-// Tally tickets by bucket — drives the district label ("3/8 DONE") and per-state counts.
-export function tallyStates(tickets) {
- return tallyByKey(tickets, ticketState, ['todo', 'inProgress', 'done']);
-}
-
-// Full derived view-model for the component: positioned structures (capped, overflow summarized)
-// + per-state tallies. `tickets` is the merged sprint-ticket list across all JIRA-enabled apps.
-// Pure + deterministic — same tickets in, same yard out — so the whole thing is headless-testable.
-export function computeJiraDistrict(tickets, opts = {}) {
- const sorted = dedupeAndSort(tickets);
- const counts = tallyStates(sorted);
- const total = sorted.length;
- const maxStructures = opts.maxStructures ?? JIRA_DISTRICT.maxStructures;
-
- const shown = sorted.slice(0, maxStructures);
- const structures = shown.map((t, i) => {
- const state = ticketState(t);
- return {
- key: t.key,
- summary: t.summary || t.key,
- state,
- color: SPRINT_STATES[state].color,
- height: structureHeight(t.storyPoints),
- position: structurePosition(i, opts),
- url: t.url || null,
- };
- });
-
- const overflow = total > maxStructures ? total - maxStructures : 0;
-
- return {
- base: opts.base || JIRA_DISTRICT.base,
- structures,
- counts,
- total,
- overflow,
- // Overflow marker sits just past the last rendered structure.
- overflowPosition: overflow > 0 ? structurePosition(maxStructures, opts) : null,
- empty: total === 0,
- };
-}
diff --git a/client/src/utils/openWorldJiraDistrict.test.js b/client/src/utils/openWorldJiraDistrict.test.js
deleted file mode 100644
index 3ef3221310..0000000000
--- a/client/src/utils/openWorldJiraDistrict.test.js
+++ /dev/null
@@ -1,133 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- JIRA_DISTRICT,
- SPRINT_STATES,
- ticketState,
- structureHeight,
- dedupeAndSort,
- structurePosition,
- tallyStates,
- computeJiraDistrict,
-} from './openWorldJiraDistrict';
-
-describe('ticketState', () => {
- it('maps JIRA category names', () => {
- expect(ticketState({ statusCategory: 'Done' })).toBe('done');
- expect(ticketState({ statusCategory: 'In Progress' })).toBe('inProgress');
- expect(ticketState({ statusCategory: 'To Do' })).toBe('todo');
- });
- it('maps JIRA category key forms', () => {
- expect(ticketState({ statusCategory: 'indeterminate' })).toBe('inProgress');
- expect(ticketState({ statusCategory: 'new' })).toBe('todo');
- });
- it('defaults unknown/blank to todo', () => {
- expect(ticketState({ statusCategory: '' })).toBe('todo');
- expect(ticketState({})).toBe('todo');
- expect(ticketState(null)).toBe('todo');
- });
-});
-
-describe('structureHeight', () => {
- it('floors a point-less ticket to a visible crate', () => {
- expect(structureHeight(undefined)).toBeGreaterThan(0.5);
- expect(structureHeight(0)).toBe(structureHeight(undefined));
- });
- it('grows with story points and clamps', () => {
- expect(structureHeight(8)).toBeGreaterThan(structureHeight(2));
- expect(structureHeight(1000)).toBeLessThanOrEqual(JIRA_DISTRICT.maxHeight);
- });
-});
-
-describe('dedupeAndSort', () => {
- it('dedupes by key (first wins)', () => {
- const out = dedupeAndSort([
- { key: 'A-1', statusCategory: 'To Do' },
- { key: 'A-1', statusCategory: 'Done' },
- ]);
- expect(out).toHaveLength(1);
- expect(ticketState(out[0])).toBe('todo'); // first occurrence kept
- });
- it('orders done → in-progress → to-do, then by key', () => {
- const out = dedupeAndSort([
- { key: 'A-3', statusCategory: 'To Do' },
- { key: 'A-2', statusCategory: 'Done' },
- { key: 'A-1', statusCategory: 'In Progress' },
- ]);
- expect(out.map(t => t.key)).toEqual(['A-2', 'A-1', 'A-3']);
- });
- it('handles non-array input', () => {
- expect(dedupeAndSort(undefined)).toEqual([]);
- });
-});
-
-describe('structurePosition', () => {
- it('wraps rows toward -Z at the column count', () => {
- const p0 = structurePosition(0);
- const pWrap = structurePosition(JIRA_DISTRICT.columns);
- expect(pWrap[2]).toBeLessThan(p0[2]); // next row is further -Z
- expect(pWrap[0]).toBeCloseTo(p0[0], 5); // back to the first column's X
- });
- it('centers the row on base X', () => {
- const cols = JIRA_DISTRICT.columns;
- const xs = Array.from({ length: cols }, (_, i) => structurePosition(i)[0]);
- const mean = xs.reduce((a, b) => a + b, 0) / xs.length;
- expect(mean).toBeCloseTo(JIRA_DISTRICT.base[0], 5);
- });
-});
-
-describe('tallyStates', () => {
- it('counts each bucket', () => {
- const counts = tallyStates([
- { statusCategory: 'Done' },
- { statusCategory: 'Done' },
- { statusCategory: 'In Progress' },
- { statusCategory: 'To Do' },
- ]);
- expect(counts).toEqual({ todo: 1, inProgress: 1, done: 2 });
- });
-});
-
-describe('SPRINT_STATES', () => {
- it('has a color + label for each bucket', () => {
- for (const k of ['todo', 'inProgress', 'done']) {
- expect(SPRINT_STATES[k].color).toMatch(/^#/);
- expect(typeof SPRINT_STATES[k].label).toBe('string');
- }
- });
-});
-
-describe('computeJiraDistrict', () => {
- it('is empty with no tickets', () => {
- const d = computeJiraDistrict([]);
- expect(d.empty).toBe(true);
- expect(d.structures).toEqual([]);
- expect(d.total).toBe(0);
- });
- it('handles undefined input', () => {
- expect(computeJiraDistrict(undefined).empty).toBe(true);
- });
- it('builds positioned, colored structures with counts', () => {
- const d = computeJiraDistrict([
- { key: 'P-1', summary: 'Build login', statusCategory: 'In Progress', storyPoints: 3, url: 'http://x/P-1' },
- { key: 'P-2', summary: 'Ship it', statusCategory: 'Done' },
- ]);
- expect(d.total).toBe(2);
- expect(d.counts.done).toBe(1);
- expect(d.structures[0].state).toBe('done'); // done sorts first
- expect(d.structures[0].position).toHaveLength(3);
- expect(d.structures.find(s => s.key === 'P-1').color).toBe(SPRINT_STATES.inProgress.color);
- });
- it('folds the tail into an overflow count', () => {
- const tickets = [];
- for (let i = 0; i < 30; i++) tickets.push({ key: `P-${i}`, statusCategory: 'To Do' });
- const d = computeJiraDistrict(tickets, { maxStructures: 10 });
- expect(d.structures).toHaveLength(10);
- expect(d.overflow).toBe(20);
- expect(d.overflowPosition).toHaveLength(3);
- });
- it('falls back summary to key', () => {
- const d = computeJiraDistrict([{ key: 'P-9', statusCategory: 'To Do' }]);
- expect(d.structures[0].summary).toBe('P-9');
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldMemoryDistrict.js b/client/src/utils/openWorldMemoryDistrict.js
deleted file mode 100644
index 1252ce4b1e..0000000000
--- a/client/src/utils/openWorldMemoryDistrict.js
+++ /dev/null
@@ -1,172 +0,0 @@
-// Pure, deterministic helpers for OpenWorld's memory / knowledge district (roadmap 3.2):
-// a quiet quarter in the northwest where the user's long-term memory graph crystallizes
-// into the city. Each memory *category* becomes a cluster of glowing crystals — taller and
-// brighter the more (and more important) the memories it holds — and edges that cross
-// category boundaries arc between clusters as light bridges, so the shape of how knowledge
-// connects is legible at a glance. No three.js / React imports so the topology is
-// unit-testable (mirrors openWorldFederation.js / openWorldBackupVault.js).
-
-import { hashString } from './hashString';
-import { groupByFieldValue, scaleMetricToHeight } from './openWorldDistrictLayout';
-import { PARCELS } from './openWorldPlan';
-
-export const MEMORY_DISTRICT = {
- // Northwest quadrant — mirrors the artifact cluster at NE, clear of the productivity
- // district, the backup vault, and downtown. Anchored by the master plan (openWorldPlan.js).
- base: PARCELS.memory.anchor,
- radius: 9, // clusters arrange on a ring of this radius around the district center
- maxCrystalsPerCluster: 7, // visual cap; overflow is summarized in the cluster label
- crystalSpacing: 1.4, // horizontal spread of crystals within a cluster
- minCrystalHeight: 1.2,
- maxCrystalHeight: 4.5,
- bridgeY: 2.2, // height the light bridges arc at
- maxClusters: 8, // most-populous categories rendered; the rest fold into "OTHER"
-};
-
-// Per-category crystal color. Reuses the PortOS neon palette feel; unknown/uncategorized
-// memories fall back to slate so an unclassified cluster still reads as present-but-quiet.
-const CATEGORY_COLORS = {
- personal: '#ec4899', // pink
- work: '#3b82f6', // port-accent blue
- technical: '#06b6d4', // cyan
- health: '#22c55e', // port-success green
- finance: '#f59e0b', // port-warning amber
- relationships: '#f43f5e', // rose
- preferences: '#a855f7', // violet
- ideas: '#8b5cf6', // purple
- other: '#64748b', // slate — fallback
-};
-
-// Deterministic color for any category string: known categories map to their token, unknown
-// ones hash into the neon palette so two distinct unknown categories still look distinct.
-const PALETTE = ['#ec4899', '#3b82f6', '#06b6d4', '#22c55e', '#f59e0b', '#f43f5e', '#a855f7', '#8b5cf6'];
-export function categoryColor(category) {
- const key = String(category || 'other').toLowerCase();
- if (CATEGORY_COLORS[key]) return CATEGORY_COLORS[key];
- return PALETTE[hashString(key) % PALETTE.length];
-}
-
-// Normalize a raw graph node's category to a stable, lowercase bucket key. Missing/blank →
-// 'other' so uncategorized memories collect into one cluster instead of vanishing.
-export function categoryKey(node) {
- const raw = node?.category;
- if (typeof raw !== 'string' || raw.trim() === '') return 'other';
- return raw.trim().toLowerCase();
-}
-
-// Group graph nodes into per-category buckets, each carrying a node count and a summed
-// importance (importance defaults to 1 when absent so every memory contributes some mass).
-// Returns buckets sorted by count desc, then category asc for a stable order.
-export function groupByCategory(nodes) {
- const nodeImportance = (node) => (Number.isFinite(node?.importance) ? node.importance : 1);
- return groupByFieldValue(nodes, categoryKey, { weightFn: nodeImportance }).map(
- ({ key, count, weight }) => ({ category: key, count, importance: weight }),
- );
-}
-
-// Place a cluster on the district ring. Angle is seeded by the category name (not the index)
-// so a category keeps its spot as the graph grows, and index is a stable tiebreaker fan-out
-// so two categories hashing near the same angle still separate.
-export function placeCluster(category, index, total, opts = {}) {
- const base = opts.base || MEMORY_DISTRICT.base;
- const radius = opts.radius ?? MEMORY_DISTRICT.radius;
- const hashAngle = (hashString(category) % 360) * (Math.PI / 180);
- const fan = total > 0 ? (index / total) * Math.PI * 2 : 0;
- // Blend the hash angle with an even fan so clusters neither overlap nor drift on regrouping.
- const angle = hashAngle * 0.5 + fan * 0.5;
- return [
- base[0] + Math.cos(angle) * radius,
- base[1],
- base[2] + Math.sin(angle) * radius,
- ];
-}
-
-// Crystal height scales with the cluster's total importance, clamped to the configured band so
-// a huge category doesn't dwarf the skyline and a tiny one is still visible.
-export function clusterHeight(importance) {
- const { minCrystalHeight, maxCrystalHeight } = MEMORY_DISTRICT;
- return scaleMetricToHeight(importance, {
- min: minCrystalHeight,
- max: maxCrystalHeight,
- k: 0.7,
- base: minCrystalHeight,
- });
-}
-
-// Build the bridges between category clusters from the graph's cross-category edges. Each edge
-// whose endpoints live in different categories increments that category-pair's weight; the
-// result is a deduped, sorted list of { from, to, weight, count } the renderer arcs as light.
-// `linked` edges count double vs `similar` so explicit links read as stronger connective tissue.
-export function computeBridges(nodes, edges) {
- const catOf = new Map();
- for (const node of Array.isArray(nodes) ? nodes : []) {
- catOf.set(node?.id, categoryKey(node));
- }
- const pairs = new Map();
- for (const edge of Array.isArray(edges) ? edges : []) {
- const a = catOf.get(edge?.source);
- const b = catOf.get(edge?.target);
- if (!a || !b || a === b) continue; // intra-cluster edges don't bridge
- const [from, to] = a < b ? [a, b] : [b, a];
- const key = `${from}|${to}`;
- const w = edge?.type === 'linked' ? 2 : 1;
- const entry = pairs.get(key) || { from, to, weight: 0, count: 0 };
- entry.weight += w;
- entry.count += 1;
- pairs.set(key, entry);
- }
- return [...pairs.values()].sort((a, b) => b.weight - a.weight || a.from.localeCompare(b.from));
-}
-
-// Full derived view-model for the component: positioned clusters (capped at maxClusters with the
-// overflow folded into a single 'other'-style summary) plus the light bridges between them. Pure
-// and deterministic — same graph in, same scene out — so the whole thing is testable headless.
-export function computeMemoryDistrict(graph, opts = {}) {
- const nodes = Array.isArray(graph?.nodes) ? graph.nodes : [];
- const edges = Array.isArray(graph?.edges) ? graph.edges : [];
- const maxClusters = opts.maxClusters ?? MEMORY_DISTRICT.maxClusters;
-
- const grouped = groupByCategory(nodes);
-
- // Fold the long tail of small categories into one "+N more" overflow cluster so the district
- // stays readable; its mass is the sum of what it absorbs.
- let clustersData = grouped;
- if (grouped.length > maxClusters) {
- const rest = grouped.slice(maxClusters - 1);
- const overflow = {
- category: 'other',
- count: rest.reduce((s, c) => s + c.count, 0),
- importance: rest.reduce((s, c) => s + c.importance, 0),
- overflowOf: rest.length,
- };
- clustersData = [...grouped.slice(0, maxClusters - 1), overflow];
- }
-
- const total = clustersData.length;
- const clusters = clustersData.map((c, i) => ({
- category: c.category,
- label: c.overflowOf ? `+${c.overflowOf} MORE` : c.category.toUpperCase(),
- count: c.count,
- importance: c.importance,
- color: categoryColor(c.category),
- position: placeCluster(c.category, i, total, opts),
- height: clusterHeight(c.importance),
- crystals: Math.min(MEMORY_DISTRICT.maxCrystalsPerCluster, Math.max(1, c.count)),
- isOverflow: !!c.overflowOf,
- }));
-
- // Bridges reference category keys; resolve them to cluster positions, dropping any whose
- // endpoint folded into overflow (those edges are summarized away rather than mis-drawn).
- const posByCategory = new Map(clusters.map(c => [c.category, c.position]));
- const bridges = computeBridges(nodes, edges)
- .map(b => ({ ...b, fromPos: posByCategory.get(b.from), toPos: posByCategory.get(b.to) }))
- .filter(b => b.fromPos && b.toPos);
-
- return {
- base: opts.base || MEMORY_DISTRICT.base,
- clusters,
- bridges,
- totalMemories: nodes.length,
- empty: nodes.length === 0,
- };
-}
diff --git a/client/src/utils/openWorldMemoryDistrict.test.js b/client/src/utils/openWorldMemoryDistrict.test.js
deleted file mode 100644
index c88715f76c..0000000000
--- a/client/src/utils/openWorldMemoryDistrict.test.js
+++ /dev/null
@@ -1,172 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- MEMORY_DISTRICT,
- categoryColor,
- categoryKey,
- groupByCategory,
- placeCluster,
- clusterHeight,
- computeBridges,
- computeMemoryDistrict,
-} from './openWorldMemoryDistrict';
-
-describe('categoryKey', () => {
- it('lowercases and trims a category', () => {
- expect(categoryKey({ category: ' Work ' })).toBe('work');
- });
- it('falls back to "other" for missing/blank categories', () => {
- expect(categoryKey({})).toBe('other');
- expect(categoryKey({ category: ' ' })).toBe('other');
- expect(categoryKey(null)).toBe('other');
- });
-});
-
-describe('categoryColor', () => {
- it('maps known categories to their token color', () => {
- expect(categoryColor('work')).toBe('#3b82f6');
- expect(categoryColor('Health')).toBe('#22c55e'); // case-insensitive
- });
- it('is deterministic for unknown categories', () => {
- expect(categoryColor('quokkas')).toBe(categoryColor('quokkas'));
- });
-});
-
-describe('groupByCategory', () => {
- it('counts nodes and sums importance per category', () => {
- const nodes = [
- { id: 'a', category: 'work', importance: 3 },
- { id: 'b', category: 'work', importance: 2 },
- { id: 'c', category: 'health', importance: 5 },
- ];
- const grouped = groupByCategory(nodes);
- expect(grouped[0]).toMatchObject({ category: 'work', count: 2, importance: 5 });
- expect(grouped[1]).toMatchObject({ category: 'health', count: 1, importance: 5 });
- });
- it('defaults importance to 1 when absent', () => {
- const grouped = groupByCategory([{ id: 'a', category: 'x' }, { id: 'b', category: 'x' }]);
- expect(grouped[0].importance).toBe(2);
- });
- it('sorts by count desc then category asc', () => {
- const nodes = [
- { id: '1', category: 'zeta' },
- { id: '2', category: 'alpha' },
- { id: '3', category: 'alpha' },
- { id: '4', category: 'beta' },
- ];
- expect(groupByCategory(nodes).map(g => g.category)).toEqual(['alpha', 'beta', 'zeta']);
- });
- it('handles non-array input', () => {
- expect(groupByCategory(undefined)).toEqual([]);
- });
-});
-
-describe('placeCluster', () => {
- it('is deterministic for the same category regardless of fan index span', () => {
- const a = placeCluster('work', 1, 4);
- const b = placeCluster('work', 1, 4);
- expect(a).toEqual(b);
- });
- it('places the cluster near the district ring radius from the base', () => {
- const base = MEMORY_DISTRICT.base;
- const [x, , z] = placeCluster('work', 0, 3);
- const r = Math.hypot(x - base[0], z - base[2]);
- expect(r).toBeCloseTo(MEMORY_DISTRICT.radius, 5);
- });
- it('gives different categories different positions', () => {
- expect(placeCluster('aaa', 0, 3)).not.toEqual(placeCluster('zzz', 1, 3));
- });
-});
-
-describe('clusterHeight', () => {
- it('clamps to the configured band', () => {
- expect(clusterHeight(0)).toBeGreaterThanOrEqual(MEMORY_DISTRICT.minCrystalHeight);
- expect(clusterHeight(1e9)).toBeLessThanOrEqual(MEMORY_DISTRICT.maxCrystalHeight);
- });
- it('grows monotonically with importance', () => {
- expect(clusterHeight(10)).toBeGreaterThan(clusterHeight(2));
- });
-});
-
-describe('computeBridges', () => {
- const nodes = [
- { id: 'a', category: 'work' },
- { id: 'b', category: 'health' },
- { id: 'c', category: 'work' },
- ];
- it('only bridges cross-category edges', () => {
- const edges = [
- { source: 'a', target: 'c', type: 'similar' }, // intra-category → skipped
- { source: 'a', target: 'b', type: 'similar' }, // cross → bridge
- ];
- const bridges = computeBridges(nodes, edges);
- expect(bridges).toHaveLength(1);
- expect(bridges[0]).toMatchObject({ from: 'health', to: 'work', count: 1 });
- });
- it('weights linked edges double vs similar', () => {
- const linked = computeBridges(nodes, [{ source: 'a', target: 'b', type: 'linked' }]);
- const similar = computeBridges(nodes, [{ source: 'a', target: 'b', type: 'similar' }]);
- expect(linked[0].weight).toBe(2 * similar[0].weight);
- });
- it('aggregates multiple edges between the same category pair', () => {
- const edges = [
- { source: 'a', target: 'b', type: 'similar' },
- { source: 'c', target: 'b', type: 'similar' },
- ];
- const bridges = computeBridges(nodes, edges);
- expect(bridges).toHaveLength(1);
- expect(bridges[0].count).toBe(2);
- });
- it('handles missing edges/nodes gracefully', () => {
- expect(computeBridges(undefined, undefined)).toEqual([]);
- expect(computeBridges(nodes, [{ source: 'a', target: 'missing' }])).toEqual([]);
- });
-});
-
-describe('computeMemoryDistrict', () => {
- it('marks empty when there are no nodes', () => {
- const d = computeMemoryDistrict({ nodes: [], edges: [] });
- expect(d.empty).toBe(true);
- expect(d.clusters).toEqual([]);
- expect(d.totalMemories).toBe(0);
- });
- it('handles undefined graph', () => {
- expect(computeMemoryDistrict(undefined).empty).toBe(true);
- });
- it('builds one cluster per category with positions and labels', () => {
- const graph = {
- nodes: [
- { id: 'a', category: 'work', importance: 3 },
- { id: 'b', category: 'health', importance: 1 },
- ],
- edges: [{ source: 'a', target: 'b', type: 'linked' }],
- };
- const d = computeMemoryDistrict(graph);
- expect(d.clusters).toHaveLength(2);
- expect(d.clusters.map(c => c.label)).toContain('WORK');
- expect(d.totalMemories).toBe(2);
- expect(d.bridges).toHaveLength(1);
- expect(d.bridges[0].fromPos).toBeDefined();
- expect(d.bridges[0].toPos).toBeDefined();
- });
- it('folds the long tail into a single overflow cluster', () => {
- const nodes = [];
- for (let i = 0; i < 12; i++) nodes.push({ id: `n${i}`, category: `cat${i}` });
- const d = computeMemoryDistrict({ nodes, edges: [] }, { maxClusters: 5 });
- expect(d.clusters).toHaveLength(5);
- const overflow = d.clusters.find(c => c.isOverflow);
- expect(overflow).toBeDefined();
- expect(overflow.label).toMatch(/MORE/);
- });
- it('drops bridges whose endpoint folded into overflow', () => {
- const nodes = [];
- for (let i = 0; i < 12; i++) nodes.push({ id: `n${i}`, category: `cat${i}` });
- // edge between two rare categories that both fold away
- const d = computeMemoryDistrict(
- { nodes, edges: [{ source: 'n10', target: 'n11', type: 'linked' }] },
- { maxClusters: 5 },
- );
- // n10/n11's categories aren't rendered as their own clusters → bridge dropped
- expect(d.bridges.every(b => b.fromPos && b.toPos)).toBe(true);
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldMiniMap.js b/client/src/utils/openWorldMiniMap.js
deleted file mode 100644
index 572b23850f..0000000000
--- a/client/src/utils/openWorldMiniMap.js
+++ /dev/null
@@ -1,249 +0,0 @@
-// Pure, deterministic helpers for OpenWorld's mini-map overlay (roadmap 2.8): a top-down
-// HUD map that plots every building as a dot at its REAL city-layout position. The layout
-// itself comes from `computeOpenWorldLayout(apps)` (the same function OpenWorldScene uses to place
-// buildings), so the map can't drift from the actual city. This module only handles the
-// projection math — world (x, z) ground coordinates → normalized 0..1 map coordinates for a
-// fixed-size map box — plus bounds and empty/degenerate handling. No React / three.js
-// imports so the topology stays unit-testable (mirrors openWorldTaskQueue.js).
-//
-// Geography awareness: every island and Signal Trail causeway is read from the SAME
-// archipelago plan (`openWorldPlan.js`) the 3D scene uses. `geographyWorldPoints()` feeds
-// the island extents into the map bounds and `projectGeography()` projects the actual
-// island/link geometry, so the HUD map cannot drift back into the old rectangular city.
-
-import {
- ARCHIPELAGO_ISLANDS,
- ARCHIPELAGO_LINKS,
- PARCELS,
- archipelagoLinkPoints,
-} from './openWorldPlan';
-
-// Padding (as a fraction of the box) so dots never sit exactly on the frame edge.
-export const MINI_MAP_PADDING = 0.08;
-
-// Compute the world-space bounds of a set of { x, z } layout positions. Returns null for an
-// empty input so callers can render an "empty city" state rather than a degenerate box.
-export function computeBounds(positions) {
- const list = Array.isArray(positions) ? positions : [];
- if (list.length === 0) return null;
-
- let minX = Infinity;
- let maxX = -Infinity;
- let minZ = Infinity;
- let maxZ = -Infinity;
- for (const p of list) {
- if (p.x < minX) minX = p.x;
- if (p.x > maxX) maxX = p.x;
- if (p.z < minZ) minZ = p.z;
- if (p.z > maxZ) maxZ = p.z;
- }
- return { minX, maxX, minZ, maxZ };
-}
-
-// Compute bounds for one layout district directly from the Map returned by
-// computeOpenWorldLayout. Keeping the filter + minimum-count gate beside the
-// canonical extrema reducer prevents visual layers from re-implementing the
-// Infinity/-Infinity sentinel loop (and forgetting the empty-district case).
-export function computeDistrictBounds(positions, district, { minCount = 1 } = {}) {
- if (!positions || typeof positions.forEach !== 'function') return null;
- const entries = [];
- positions.forEach((position) => {
- if (position?.district === district) entries.push(position);
- });
- if (entries.length < minCount) return null;
- return computeBounds(entries);
-}
-
-// Project a single world (x, z) into normalized 0..1 map coordinates given the world bounds.
-// `nx` runs left→right with world +x; `ny` runs top→bottom with world +z (so the map reads
-// like a top-down floor plan). A zero-width or zero-height span (one app, or a row/column)
-// centers along that axis instead of dividing by zero. `padding` insets the usable area so
-// dots clear the frame. Results are clamped to [0, 1].
-export function projectPoint(point, bounds, padding = MINI_MAP_PADDING) {
- if (!bounds) return { nx: 0.5, ny: 0.5 };
- const spanX = bounds.maxX - bounds.minX;
- const spanZ = bounds.maxZ - bounds.minZ;
- const usable = 1 - 2 * padding;
-
- const fracX = spanX > 0 ? (point.x - bounds.minX) / spanX : 0.5;
- const fracZ = spanZ > 0 ? (point.z - bounds.minZ) / spanZ : 0.5;
-
- const nx = padding + fracX * usable;
- const ny = padding + fracZ * usable;
- return { nx: clamp01(nx), ny: clamp01(ny) };
-}
-
-// Keep dense projected markers aimable on compact touch surfaces. The first marker keeps
-// its true projection; later markers that land too close are fanned out in a deterministic
-// ring so the map remains spatially honest without stacking hit targets invisibly.
-export function spreadProjectedPoints(points, { minDistance = 0.075, offset = 0.045 } = {}) {
- const list = Array.isArray(points) ? points : [];
- const placed = [];
- return list.map((point, index) => {
- const nearby = placed.filter((candidate) => {
- const dx = candidate.nx - point.nx;
- const dy = candidate.ny - point.ny;
- return Math.sqrt(dx * dx + dy * dy) < minDistance;
- });
- if (nearby.length === 0) {
- const result = { ...point };
- placed.push(result);
- return result;
- }
-
- const ring = Math.ceil(nearby.length / 6);
- const slot = nearby.length % 6;
- const angle = (slot / 6) * Math.PI * 2 + index * 0.17;
- const result = {
- ...point,
- nx: clamp01(point.nx + Math.cos(angle) * offset * ring),
- ny: clamp01(point.ny + Math.sin(angle) * offset * ring),
- };
- placed.push(result);
- return result;
- });
-}
-
-function clamp01(v) {
- if (v < 0) return 0;
- if (v > 1) return 1;
- return v;
-}
-
-// World-space extrema for every island. These are folded into the map bounds so the
-// complete playable world remains visible even when the install has few or no app buildings.
-export function geographyWorldPoints() {
- return ARCHIPELAGO_ISLANDS.flatMap((island) => {
- const [x, z] = island.center;
- return [
- { x: x - island.radiusX, z },
- { x: x + island.radiusX, z },
- { x, z: z - island.radiusZ },
- { x, z: z + island.radiusZ },
- ];
- });
-}
-
-// Normalized (0..1) projection of the authored islands and their Signal Trail links.
-export function projectGeography(bounds, padding = MINI_MAP_PADDING) {
- if (!bounds) return null;
- return {
- islands: ARCHIPELAGO_ISLANDS.map((island) => {
- const [x, z] = island.center;
- const center = projectPoint({ x, z }, bounds, padding);
- const edgeX = projectPoint({ x: x + island.radiusX, z }, bounds, padding);
- const edgeZ = projectPoint({ x, z: z + island.radiusZ }, bounds, padding);
- return {
- id: island.id,
- label: island.label,
- biome: island.biome,
- nx: center.nx,
- ny: center.ny,
- radiusX: Math.abs(edgeX.nx - center.nx),
- radiusY: Math.abs(edgeZ.ny - center.ny),
- };
- }),
- links: ARCHIPELAGO_LINKS.map((link) => ({
- id: link.id,
- points: archipelagoLinkPoints(link).map(([x, z]) => projectPoint({ x, z }, bounds, padding)),
- })),
- };
-}
-
-// Project the live player pose (position + heading) into normalized mini-map coordinates.
-// Returns null when bounds or player position are absent/invalid.
-export function projectPlayer(playerPos, heading = 0, bounds = null, padding = MINI_MAP_PADDING) {
- if (!playerPos || typeof playerPos.x !== 'number' || typeof playerPos.z !== 'number' || !bounds) {
- return null;
- }
- const { nx, ny } = projectPoint({ x: playerPos.x, z: playerPos.z }, bounds, padding);
- // Three.js / rover heading increases counter-clockwise (0 faces north / -Z; -π/2 faces east / +X).
- // CSS rotation is clockwise in screen space, so we negate the angle to align the blip's pointer.
- const rotationDeg = -(heading * 180) / Math.PI;
- return { nx, ny, rotationDeg };
-}
-
-// Project major district landmarks onto the mini-map
-const MAP_LANDMARKS = [
- { id: 'ai-core', parcel: 'aiCore', label: 'AI Core', color: '#06b6d4' },
- { id: 'backup-vault', parcel: 'backupVault', label: 'Vault', color: '#f59e0b' },
- { id: 'task-queue', parcel: 'taskQueue', label: 'Queue', color: '#f97316' },
- { id: 'wellness', parcel: 'health', label: 'Health', color: '#10b981' },
- { id: 'memory', parcel: 'memory', label: 'Memory', color: '#a855f7' },
- { id: 'goals', parcel: 'goals', label: 'Goals', color: '#eab308' },
- { id: 'artifacts', parcel: 'artifacts', label: 'Artifacts', color: '#facc15' },
- { id: 'productivity', parcel: 'productivity', label: 'Productivity', color: '#22c55e' },
-];
-
-export function projectLandmarks(bounds, padding = MINI_MAP_PADDING) {
- if (!bounds) return [];
- const results = [];
- for (const lm of MAP_LANDMARKS) {
- const parcel = PARCELS[lm.parcel];
- if (!parcel) continue;
- const { nx, ny } = projectPoint({ x: parcel.anchor[0], z: parcel.anchor[2] }, bounds, padding);
- results.push({
- id: lm.id,
- label: lm.label,
- color: lm.color,
- nx,
- ny,
- });
- }
- return results;
-}
-
-// Full derived view-model for the mini-map component. Takes the layout `positions` Map (the
-// return value of `computeOpenWorldLayout(apps)`, keyed by app id) plus the `apps` array (for
-// status/name/archived metadata), and produces a flat list of plotted dots with normalized
-// coordinates, the world bounds, and a count. Apps missing a layout position are skipped
-// (defensive — every active/archived app should have one). Handles empty/non-array inputs by
-// returning an empty, bounds-null view.
-//
-// `opts.geography` (default false) folds the whole archipelago into the bounds and returns
-// its projected island/link view-model. The live overlay passes `true`.
-export function computeMiniMap(apps, positions, opts = {}) {
- const padding = opts.padding ?? MINI_MAP_PADDING;
- const includeGeography = opts.geography === true;
- const includeLandmarks = opts.landmarks === true;
- const appList = Array.isArray(apps) ? apps : [];
- const posMap = positions instanceof Map ? positions : new Map();
-
- const placed = [];
- for (const app of appList) {
- const pos = posMap.get(app?.id);
- if (!pos) continue;
- placed.push({ app, pos });
- }
-
- // Geography anchors expand the box to the complete playable world, but never become dots.
- const boundsPoints = placed.map(({ pos }) => pos);
- if (includeGeography) boundsPoints.push(...geographyWorldPoints());
- const bounds = computeBounds(boundsPoints);
-
- const dots = placed.map(({ app, pos }) => {
- const { nx, ny } = projectPoint(pos, bounds, padding);
- return {
- id: app.id,
- name: app.name || app.id,
- status: app.archived ? 'archived' : (app.overallStatus || 'not_started'),
- archived: Boolean(app.archived),
- district: pos.district,
- nx,
- ny,
- };
- });
-
- const player = opts.player ? projectPlayer(opts.player.position, opts.player.heading, bounds, padding) : null;
- const landmarks = includeLandmarks ? projectLandmarks(bounds, padding) : [];
-
- return {
- dots,
- bounds,
- count: dots.length,
- empty: dots.length === 0,
- geography: includeGeography ? projectGeography(bounds, padding) : null,
- player,
- landmarks,
- };
-}
diff --git a/client/src/utils/openWorldMiniMap.test.js b/client/src/utils/openWorldMiniMap.test.js
deleted file mode 100644
index bfce6e9b76..0000000000
--- a/client/src/utils/openWorldMiniMap.test.js
+++ /dev/null
@@ -1,322 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- MINI_MAP_PADDING,
- computeBounds,
- computeDistrictBounds,
- projectPoint,
- computeMiniMap,
- geographyWorldPoints,
- projectGeography,
- projectPlayer,
- projectLandmarks,
- spreadProjectedPoints,
-} from './openWorldMiniMap';
-import { ARCHIPELAGO_ISLANDS, ARCHIPELAGO_LINKS } from './openWorldPlan';
-
-const pos = (x, z, district = 'downtown') => ({ x, z, district });
-
-describe('computeBounds', () => {
- it('returns null for empty / non-array input', () => {
- expect(computeBounds([])).toBeNull();
- expect(computeBounds(undefined)).toBeNull();
- expect(computeBounds(null)).toBeNull();
- });
-
- it('computes the min/max box for many points', () => {
- const b = computeBounds([pos(-12, 0), pos(0, -12), pos(12, 12), pos(0, 0)]);
- expect(b).toEqual({ minX: -12, maxX: 12, minZ: -12, maxZ: 12 });
- });
-
- it('collapses to a zero-span box for a single point', () => {
- const b = computeBounds([pos(5, -3)]);
- expect(b).toEqual({ minX: 5, maxX: 5, minZ: -3, maxZ: -3 });
- });
-});
-
-describe('computeDistrictBounds', () => {
- it('returns null when a populated layout has no entries in the requested district', () => {
- const positions = new Map([
- ['archived-a', { x: -6, z: 16, district: 'warehouse' }],
- ['archived-b', { x: 6, z: 16, district: 'warehouse' }],
- ]);
-
- expect(computeDistrictBounds(positions, 'downtown', { minCount: 2 })).toBeNull();
- });
-
- it('uses the canonical bounds reducer after applying the district and count gate', () => {
- const positions = new Map([
- ['a', { x: -4, z: 3, district: 'downtown' }],
- ['b', { x: 7, z: -2, district: 'downtown' }],
- ['archived', { x: 100, z: 100, district: 'warehouse' }],
- ]);
-
- expect(computeDistrictBounds(positions, 'downtown', { minCount: 2 })).toEqual({
- minX: -4,
- maxX: 7,
- minZ: -2,
- maxZ: 3,
- });
- });
-});
-
-describe('projectPoint', () => {
- const bounds = { minX: -10, maxX: 10, minZ: -10, maxZ: 10 };
- const p = MINI_MAP_PADDING;
- const usable = 1 - 2 * p;
-
- it('maps the min corner to the padded top-left', () => {
- const { nx, ny } = projectPoint(pos(-10, -10), bounds);
- expect(nx).toBeCloseTo(p);
- expect(ny).toBeCloseTo(p);
- });
-
- it('maps the max corner to the padded bottom-right', () => {
- const { nx, ny } = projectPoint(pos(10, 10), bounds);
- expect(nx).toBeCloseTo(p + usable);
- expect(ny).toBeCloseTo(p + usable);
- });
-
- it('maps the center to the middle of the box', () => {
- const { nx, ny } = projectPoint(pos(0, 0), bounds);
- expect(nx).toBeCloseTo(0.5);
- expect(ny).toBeCloseTo(0.5);
- });
-
- it('maps +x right and +z down (top-down floor plan)', () => {
- const right = projectPoint(pos(10, 0), bounds);
- const left = projectPoint(pos(-10, 0), bounds);
- const down = projectPoint(pos(0, 10), bounds);
- const up = projectPoint(pos(0, -10), bounds);
- expect(right.nx).toBeGreaterThan(left.nx);
- expect(down.ny).toBeGreaterThan(up.ny);
- });
-
- it('centers a point along a zero-span axis instead of dividing by zero', () => {
- const colBounds = { minX: 5, maxX: 5, minZ: -10, maxZ: 10 };
- const { nx, ny } = projectPoint(pos(5, 0), colBounds);
- expect(nx).toBeCloseTo(0.5); // x span is zero → centered
- expect(ny).toBeCloseTo(0.5); // z span resolves normally
- });
-
- it('clamps out-of-bounds points into [0, 1]', () => {
- const { nx, ny } = projectPoint(pos(1000, -1000), bounds);
- expect(nx).toBeGreaterThanOrEqual(0);
- expect(nx).toBeLessThanOrEqual(1);
- expect(ny).toBeGreaterThanOrEqual(0);
- expect(ny).toBeLessThanOrEqual(1);
- });
-
- it('falls back to center when bounds are null', () => {
- expect(projectPoint(pos(3, 7), null)).toEqual({ nx: 0.5, ny: 0.5 });
- });
-});
-
-describe('spreadProjectedPoints', () => {
- it('keeps isolated points at their true projection', () => {
- const points = [{ id: 'a', nx: 0.2, ny: 0.2 }, { id: 'b', nx: 0.8, ny: 0.8 }];
- expect(spreadProjectedPoints(points)).toEqual(points);
- });
-
- it('fans colliding points into visible deterministic positions', () => {
- const points = Array.from({ length: 4 }, (_, index) => ({ id: String(index), nx: 0.5, ny: 0.5 }));
- const first = spreadProjectedPoints(points);
- const second = spreadProjectedPoints(points);
- expect(first).toEqual(second);
- expect(new Set(first.map((point) => `${point.nx}:${point.ny}`)).size).toBe(4);
- });
-});
-
-describe('computeMiniMap', () => {
- const positions = (entries) => new Map(entries.map(([id, x, z, district]) => [id, pos(x, z, district)]));
-
- it('returns an empty, bounds-null view for no apps', () => {
- const vm = computeMiniMap([], new Map());
- expect(vm.empty).toBe(true);
- expect(vm.count).toBe(0);
- expect(vm.dots).toEqual([]);
- expect(vm.bounds).toBeNull();
- });
-
- it('tolerates non-array apps / non-Map positions', () => {
- const vm = computeMiniMap(undefined, undefined);
- expect(vm.empty).toBe(true);
- expect(vm.count).toBe(0);
- });
-
- it('plots a single app at the center', () => {
- const apps = [{ id: 'a', name: 'Alpha', overallStatus: 'online' }];
- const vm = computeMiniMap(apps, positions([['a', 0, 0]]));
- expect(vm.count).toBe(1);
- expect(vm.empty).toBe(false);
- expect(vm.dots[0].nx).toBeCloseTo(0.5);
- expect(vm.dots[0].ny).toBeCloseTo(0.5);
- expect(vm.dots[0].status).toBe('online');
- });
-
- it('projects many apps within the padded box and preserves order', () => {
- const apps = [
- { id: 'a', overallStatus: 'online' },
- { id: 'b', overallStatus: 'stopped' },
- { id: 'c', overallStatus: 'online' },
- ];
- const vm = computeMiniMap(apps, positions([['a', -12, -12], ['b', 12, 12], ['c', 0, 0]]));
- expect(vm.count).toBe(3);
- expect(vm.dots.map(d => d.id)).toEqual(['a', 'b', 'c']);
- for (const d of vm.dots) {
- expect(d.nx).toBeGreaterThanOrEqual(0);
- expect(d.nx).toBeLessThanOrEqual(1);
- expect(d.ny).toBeGreaterThanOrEqual(0);
- expect(d.ny).toBeLessThanOrEqual(1);
- }
- });
-
- it('marks archived apps with the archived status regardless of overallStatus', () => {
- const apps = [{ id: 'a', overallStatus: 'online', archived: true }];
- const vm = computeMiniMap(apps, positions([['a', 0, 0, 'warehouse']]));
- expect(vm.dots[0].status).toBe('archived');
- expect(vm.dots[0].archived).toBe(true);
- expect(vm.dots[0].district).toBe('warehouse');
- });
-
- it('defaults a missing status to not_started', () => {
- const apps = [{ id: 'a' }];
- const vm = computeMiniMap(apps, positions([['a', 0, 0]]));
- expect(vm.dots[0].status).toBe('not_started');
- });
-
- it('falls back to the id when an app has no name', () => {
- const apps = [{ id: 'svc-42', overallStatus: 'online' }];
- const vm = computeMiniMap(apps, positions([['svc-42', 0, 0]]));
- expect(vm.dots[0].name).toBe('svc-42');
- });
-
- it('skips apps that have no layout position', () => {
- const apps = [
- { id: 'a', overallStatus: 'online' },
- { id: 'ghost', overallStatus: 'online' },
- ];
- const vm = computeMiniMap(apps, positions([['a', 0, 0]]));
- expect(vm.count).toBe(1);
- expect(vm.dots.map(d => d.id)).toEqual(['a']);
- });
-
- it('omits geography by default (pure building bounds)', () => {
- const apps = [{ id: 'a', overallStatus: 'online' }];
- const vm = computeMiniMap(apps, positions([['a', 0, 0]]));
- expect(vm.geography).toBeNull();
- });
-
- it('keeps the playable archipelago visible for an install with no app buildings', () => {
- const vm = computeMiniMap([], new Map(), { geography: true });
- expect(vm.geography).not.toBeNull();
- expect(vm.geography.islands).toHaveLength(ARCHIPELAGO_ISLANDS.length);
- expect(vm.bounds).not.toBeNull();
- expect(vm.empty).toBe(true);
- });
-
- it('folds the whole archipelago into the bounds when geography is enabled', () => {
- const apps = [{ id: 'a', overallStatus: 'online' }];
- const land = computeMiniMap(apps, positions([['a', 0, 0]]));
- const sea = computeMiniMap(apps, positions([['a', 0, 0]]), { geography: true });
- expect(sea.bounds.minZ).toBeLessThan(land.bounds.minZ);
- expect(sea.bounds.maxZ).toBeGreaterThan(land.bounds.maxZ);
- expect(sea.bounds.minX).toBeLessThan(land.bounds.minX);
- expect(sea.bounds.maxX).toBeGreaterThan(land.bounds.maxX);
- expect(sea.geography).not.toBeNull();
- expect(sea.geography.links).toHaveLength(ARCHIPELAGO_LINKS.length);
- });
-
- it('projects every island and every link inside the normalized map', () => {
- const apps = [
- { id: 'a', overallStatus: 'online' },
- { id: 'b', overallStatus: 'online' },
- ];
- const vm = computeMiniMap(apps, positions([['a', -20, 20], ['b', 20, 40]]), { geography: true });
- for (const island of vm.geography.islands) {
- for (const value of [island.nx, island.ny, island.radiusX, island.radiusY]) {
- expect(value).toBeGreaterThanOrEqual(0);
- expect(value).toBeLessThanOrEqual(1);
- }
- }
- for (const link of vm.geography.links) {
- expect(link.points.length).toBeGreaterThanOrEqual(2);
- link.points.forEach((point) => {
- expect(point.nx).toBeGreaterThanOrEqual(0);
- expect(point.nx).toBeLessThanOrEqual(1);
- expect(point.ny).toBeGreaterThanOrEqual(0);
- expect(point.ny).toBeLessThanOrEqual(1);
- });
- }
- });
-});
-
-describe('geographyWorldPoints', () => {
- it('returns four extrema for every island in the master plan', () => {
- const pts = geographyWorldPoints();
- expect(pts).toHaveLength(ARCHIPELAGO_ISLANDS.length * 4);
- ARCHIPELAGO_ISLANDS.forEach((island, index) => {
- const offset = index * 4;
- expect(pts[offset]).toEqual({ x: island.center[0] - island.radiusX, z: island.center[1] });
- expect(pts[offset + 1]).toEqual({ x: island.center[0] + island.radiusX, z: island.center[1] });
- expect(pts[offset + 2]).toEqual({ x: island.center[0], z: island.center[1] - island.radiusZ });
- expect(pts[offset + 3]).toEqual({ x: island.center[0], z: island.center[1] + island.radiusZ });
- });
- });
-});
-
-describe('projectGeography', () => {
- it('returns null when bounds are null', () => {
- expect(projectGeography(null)).toBeNull();
- });
-
- it('projects islands and links into normalized coordinates', () => {
- const bounds = { minX: -60, maxX: 60, minZ: -70, maxZ: 60 };
- const geo = projectGeography(bounds);
- expect(geo.islands).toHaveLength(ARCHIPELAGO_ISLANDS.length);
- expect(geo.links).toHaveLength(ARCHIPELAGO_LINKS.length);
- expect(geo.islands.find((island) => island.id === 'harbor')?.label).toBe('Data Harbor');
- });
-});
-
-describe('projectPlayer', () => {
- const bounds = { minX: -60, maxX: 60, minZ: -70, maxZ: 60 };
-
- it('projects player position and converts heading to degrees for clockwise CSS rotation', () => {
- const player = projectPlayer({ x: 0, z: 0 }, 0, bounds);
- expect(player).not.toBeNull();
- expect(player.nx).toBeCloseTo(0.5);
- expect(player.rotationDeg).toBeCloseTo(0);
-
- // Rover heading -π/2 (turning right / east / +X) corresponds to +90° clockwise CSS rotation:
- const playerEast = projectPlayer({ x: 10, z: -10 }, -Math.PI / 2, bounds);
- expect(playerEast.rotationDeg).toBeCloseTo(90);
- });
-
- it('returns null on invalid / absent inputs', () => {
- expect(projectPlayer(null, 0, bounds)).toBeNull();
- expect(projectPlayer({ x: 0, z: 0 }, 0, null)).toBeNull();
- });
-});
-
-describe('projectLandmarks', () => {
- const bounds = { minX: -60, maxX: 60, minZ: -70, maxZ: 60 };
-
- it('projects landmarks onto normalized coordinates', () => {
- const landmarks = projectLandmarks(bounds);
- expect(landmarks.length).toBeGreaterThanOrEqual(5);
- landmarks.forEach((lm) => {
- expect(typeof lm.id).toBe('string');
- expect(typeof lm.label).toBe('string');
- expect(lm.nx).toBeGreaterThanOrEqual(0);
- expect(lm.nx).toBeLessThanOrEqual(1);
- expect(lm.ny).toBeGreaterThanOrEqual(0);
- expect(lm.ny).toBeLessThanOrEqual(1);
- });
- });
-
- it('returns empty array when bounds are null', () => {
- expect(projectLandmarks(null)).toEqual([]);
- });
-});
-
-// @vitest-environment node
diff --git a/client/src/utils/openWorldPhotoMode.js b/client/src/utils/openWorldPhotoMode.js
deleted file mode 100644
index 4d1399ce12..0000000000
--- a/client/src/utils/openWorldPhotoMode.js
+++ /dev/null
@@ -1,129 +0,0 @@
-// Pure, deterministic helpers for OpenWorld's photo mode (roadmap 3.3): cinematic camera
-// presets, the camera-fly stepper, the "OpenWorld postcard" stats overlay, and screenshot filename
-// generation. No three.js / React imports so it's unit-testable (mirrors the other city
-// helpers). The component reads these presets to fly the camera and composites the postcard
-// caption from a live stats snapshot the page passes in.
-import { smoothstep } from './easing';
-
-// Cinematic camera presets. Each is a stable framing of the city — position + look-at target —
-// the photo UI cycles through. Tuned against the default orbital view (camera at [0,25,45]
-// looking at origin) and the ±60-unit landmark ring, so every preset keeps downtown and at
-// least one landmark district in frame.
-export const PHOTO_PRESETS = [
- { id: 'establishing', label: 'ESTABLISHING', position: [0, 28, 52], target: [0, 2, 0] },
- { id: 'downtown', label: 'DOWNTOWN', position: [0, 10, 26], target: [0, 4, 0] },
- { id: 'skyline', label: 'SKYLINE', position: [44, 6, 44], target: [-6, 8, -6] },
- { id: 'overhead', label: 'OVERHEAD', position: [0, 70, 0.01], target: [0, 0, 0] },
- { id: 'horizon', label: 'HORIZON', position: [0, 4, 60], target: [0, 10, -60] },
- // Low-angle is the most dramatic, close-in framing — a wider aperture pushes a shallower,
- // more cinematic falloff so the foreground subject pops against a soft background.
- { id: 'low-angle', label: 'LOW ANGLE', position: [-18, 2, 30], target: [0, 12, 0], dof: { aperture: 0.09 } },
-];
-
-export const DEFAULT_PRESET_ID = 'establishing';
-
-// Resolve a preset by id, falling back to the default establishing shot for an unknown id so a
-// stale persisted id can never strand the camera with no framing.
-export function getPreset(id) {
- return PHOTO_PRESETS.find(p => p.id === id) || PHOTO_PRESETS.find(p => p.id === DEFAULT_PRESET_ID);
-}
-
-// Depth-of-field defaults for cinematic photo-mode shots (roadmap 3.3). `aperture` and `maxblur`
-// shape the blur falloff for three's BokehPass; both are intentionally gentle so the effect reads
-// as "cinematic" rather than "broken". A preset may override either via an optional `dof: { … }`
-// field. The focal distance is NOT a default — it's derived per preset from the camera framing
-// (see `presetFocusDistance`) so the subject the camera is pointed at always stays sharp without
-// hand-tuning a separate focus number that could drift from the framing.
-export const DOF_DEFAULTS = { aperture: 0.05, maxblur: 0.012 };
-
-// Distance (world units) from a preset's camera position to its look-at target. This is the focal
-// plane: BokehPass keeps geometry at this depth sharp and blurs nearer/farther geometry. Deriving
-// it from the preset's own position→target keeps focus locked to whatever the shot frames. Pure
-// (no three.js) so it stays unit-testable alongside the other helpers.
-export function presetFocusDistance(preset) {
- if (!Array.isArray(preset?.position) || !Array.isArray(preset?.target)) return 1;
- const [px, py, pz] = preset.position;
- const [tx, ty, tz] = preset.target;
- const dx = px - tx;
- const dy = py - ty;
- const dz = pz - tz;
- const dist = Math.sqrt(dx * dx + dy * dy + dz * dz);
- return Number.isFinite(dist) && dist > 0 ? dist : 1;
-}
-
-// Accept a per-preset override only when it's a positive finite number; otherwise fall back to the
-// default. A negative/zero/NaN aperture or maxblur is meaningless to the bokeh shader (blur radius
-// is non-negative), so a malformed hand-edited preset can't push a broken value into the pass.
-const positiveOr = (value, fallback) => (Number.isFinite(value) && value > 0 ? value : fallback);
-
-// Resolve the BokehPass parameters for a preset: derived focal distance + (per-preset-overridable)
-// aperture/maxblur. Used by OpenWorldDepthOfField to build and re-tune the pass when the preset changes.
-export function getDofParams(presetId) {
- const preset = getPreset(presetId);
- const override = preset?.dof || {};
- return {
- focus: presetFocusDistance(preset),
- aperture: positiveOr(override.aperture, DOF_DEFAULTS.aperture),
- maxblur: positiveOr(override.maxblur, DOF_DEFAULTS.maxblur),
- };
-}
-
-// Step to the next/previous preset in the ring (wraps). Used by the ‹ › controls and arrow keys.
-export function cyclePreset(currentId, direction = 1) {
- const idx = PHOTO_PRESETS.findIndex(p => p.id === currentId);
- const base = idx === -1 ? 0 : idx;
- const next = (base + direction + PHOTO_PRESETS.length) % PHOTO_PRESETS.length;
- return PHOTO_PRESETS[next].id;
-}
-
-// Photo mode runs the Canvas frameloop in "demand" mode (roadmap 3.6): the scene animates only
-// while the camera is flying to a preset, then freezes for a clean, deliberate still. This pure
-// stepper advances the fly progress by an elapsed delta and reports whether the loop still needs
-// pumping. `FLY_DURATION` is the seconds the cinematic ease takes (slower than the exploration
-// transition). `stepFly` returns the clamped next progress, the eased interpolation factor `t`,
-// and `done` (true once settled) so the component can stop invalidating the demand loop.
-export const FLY_DURATION = 1.1;
-
-// Cap the per-step delta to a frame-sized maximum. In demand mode the loop sleeps while the scene
-// is frozen, so the FIRST frame after a freeze (e.g. when the user cycles presets) carries a
-// delta equal to the whole idle gap — often several seconds. Unclamped, that would complete the
-// fly in a single step and the camera would snap instead of animating. Clamping keeps every fly
-// smooth (~at least FLY_DURATION/MAX_FLY_DELTA frames) regardless of how long the scene was idle.
-export const MAX_FLY_DELTA = 1 / 30; // seconds — one 30fps frame
-
-export function stepFly(progress, deltaSeconds) {
- const rawDelta = Number.isFinite(deltaSeconds) && deltaSeconds > 0 ? deltaSeconds : 0;
- const safeDelta = Math.min(rawDelta, MAX_FLY_DELTA);
- const next = Math.min(1, (Number.isFinite(progress) ? progress : 1) + safeDelta / FLY_DURATION);
- return { progress: next, t: smoothstep(next), done: next >= 1 };
-}
-
-// Build the short stat lines printed on a "city postcard". Pulls a handful of headline numbers
-// from a stats snapshot the page already has (apps, agents, peers, level). Missing fields are
-// omitted rather than rendered as "0/undefined", so a sparse install still prints a clean card.
-export function buildPostcardStats(snapshot = {}) {
- const lines = [];
- const { online, total, agents, peers, level } = snapshot;
- if (Number.isFinite(total)) lines.push(`${online ?? 0}/${total} SYSTEMS ONLINE`);
- if (Number.isFinite(agents) && agents > 0) lines.push(`${agents} AGENT${agents === 1 ? '' : 'S'} ACTIVE`);
- if (Number.isFinite(peers) && peers > 0) lines.push(`${peers} PEER${peers === 1 ? '' : 'S'} LINKED`);
- if (Number.isFinite(level)) lines.push(`LEVEL ${level}`);
- return lines;
-}
-
-// Pad a number to two digits without Date formatting (Date.now is unavailable in some contexts;
-// the timestamp is always passed in from the caller).
-const pad2 = (n) => String(n).padStart(2, '0');
-
-// Build a stable, filesystem-safe screenshot filename from a Date. Format:
-// `openworld-YYYYMMDD-HHMMSS.png`. The Date is injected so the function is deterministic in
-// tests and the caller controls the clock.
-export function screenshotFilename(date = new Date()) {
- const y = date.getFullYear();
- const m = pad2(date.getMonth() + 1);
- const d = pad2(date.getDate());
- const hh = pad2(date.getHours());
- const mm = pad2(date.getMinutes());
- const ss = pad2(date.getSeconds());
- return `openworld-${y}${m}${d}-${hh}${mm}${ss}.png`;
-}
diff --git a/client/src/utils/openWorldPhotoMode.test.js b/client/src/utils/openWorldPhotoMode.test.js
deleted file mode 100644
index ff58f25606..0000000000
--- a/client/src/utils/openWorldPhotoMode.test.js
+++ /dev/null
@@ -1,179 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- PHOTO_PRESETS,
- DEFAULT_PRESET_ID,
- getPreset,
- cyclePreset,
- stepFly,
- FLY_DURATION,
- MAX_FLY_DELTA,
- buildPostcardStats,
- screenshotFilename,
- DOF_DEFAULTS,
- presetFocusDistance,
- getDofParams,
-} from './openWorldPhotoMode';
-import { smoothstep } from './easing';
-
-describe('PHOTO_PRESETS', () => {
- it('has unique ids and a position + target each', () => {
- const ids = PHOTO_PRESETS.map(p => p.id);
- expect(new Set(ids).size).toBe(ids.length);
- for (const p of PHOTO_PRESETS) {
- expect(p.position).toHaveLength(3);
- expect(p.target).toHaveLength(3);
- expect(typeof p.label).toBe('string');
- }
- });
- it('includes the default preset id', () => {
- expect(PHOTO_PRESETS.some(p => p.id === DEFAULT_PRESET_ID)).toBe(true);
- });
-});
-
-describe('getPreset', () => {
- it('resolves a known id', () => {
- expect(getPreset('downtown').id).toBe('downtown');
- });
- it('falls back to the default for an unknown id', () => {
- expect(getPreset('nope').id).toBe(DEFAULT_PRESET_ID);
- expect(getPreset(undefined).id).toBe(DEFAULT_PRESET_ID);
- });
-});
-
-describe('cyclePreset', () => {
- it('advances forward and wraps', () => {
- const first = PHOTO_PRESETS[0].id;
- const last = PHOTO_PRESETS[PHOTO_PRESETS.length - 1].id;
- expect(cyclePreset(last, 1)).toBe(first);
- });
- it('advances backward and wraps', () => {
- const first = PHOTO_PRESETS[0].id;
- const last = PHOTO_PRESETS[PHOTO_PRESETS.length - 1].id;
- expect(cyclePreset(first, -1)).toBe(last);
- });
- it('treats an unknown current id as the first preset', () => {
- expect(cyclePreset('bogus', 1)).toBe(PHOTO_PRESETS[1].id);
- });
-});
-
-describe('stepFly', () => {
- it('advances progress by delta/duration and eases t for a frame-sized delta', () => {
- const { progress, t, done } = stepFly(0, MAX_FLY_DELTA);
- expect(progress).toBeCloseTo(MAX_FLY_DELTA / FLY_DURATION, 5);
- expect(t).toBeCloseTo(smoothstep(progress), 5);
- expect(done).toBe(false);
- });
- it('clamps a huge idle delta to one frame so a fly never snaps in a single step', () => {
- // In demand mode the first frame after a freeze carries the whole idle gap as delta. The fly
- // must still advance only one frame's worth, not jump straight to settled.
- const { progress, done } = stepFly(0, 9999);
- expect(progress).toBeCloseTo(MAX_FLY_DELTA / FLY_DURATION, 5);
- expect(done).toBe(false);
- });
- it('clamps progress to 1 and reports done once enough frames accumulate', () => {
- const { progress, t, done } = stepFly(0.999, MAX_FLY_DELTA);
- expect(progress).toBe(1);
- expect(t).toBe(1);
- expect(done).toBe(true);
- });
- it('reports done when already settled (no negative drift)', () => {
- expect(stepFly(1, 0.016).done).toBe(true);
- expect(stepFly(1, 0.016).progress).toBe(1);
- });
- it('treats a non-positive or non-finite delta as no advance', () => {
- expect(stepFly(0.3, 0).progress).toBeCloseTo(0.3, 5);
- expect(stepFly(0.3, -1).progress).toBeCloseTo(0.3, 5);
- expect(stepFly(0.3, NaN).progress).toBeCloseTo(0.3, 5);
- });
- it('treats a non-finite progress as settled', () => {
- expect(stepFly(undefined, 0.016).progress).toBe(1);
- expect(stepFly(NaN, 0.016).done).toBe(true);
- });
-});
-
-describe('buildPostcardStats', () => {
- it('renders the headline lines that have data', () => {
- const lines = buildPostcardStats({ online: 3, total: 5, agents: 2, peers: 1, level: 7 });
- expect(lines).toContain('3/5 SYSTEMS ONLINE');
- expect(lines).toContain('2 AGENTS ACTIVE');
- expect(lines).toContain('1 PEER LINKED');
- expect(lines).toContain('LEVEL 7');
- });
- it('omits zero/absent fields rather than printing 0', () => {
- const lines = buildPostcardStats({ online: 0, total: 2, agents: 0, peers: 0 });
- expect(lines).toEqual(['0/2 SYSTEMS ONLINE']);
- });
- it('singularizes agent/peer counts of one', () => {
- const lines = buildPostcardStats({ agents: 1, peers: 1, total: 1, online: 1 });
- expect(lines).toContain('1 AGENT ACTIVE');
- expect(lines).toContain('1 PEER LINKED');
- });
- it('handles an empty snapshot', () => {
- expect(buildPostcardStats()).toEqual([]);
- expect(buildPostcardStats({})).toEqual([]);
- });
- it('renders level 0', () => {
- expect(buildPostcardStats({ level: 0 })).toContain('LEVEL 0');
- });
-});
-
-describe('screenshotFilename', () => {
- it('formats a zero-padded timestamped name', () => {
- const d = new Date(2026, 5, 3, 9, 7, 5); // 2026-06-03 09:07:05 (month is 0-based)
- expect(screenshotFilename(d)).toBe('openworld-20260603-090705.png');
- });
- it('is deterministic for the same date', () => {
- const d = new Date(2026, 0, 1, 0, 0, 0);
- expect(screenshotFilename(d)).toBe(screenshotFilename(d));
- });
-});
-
-describe('presetFocusDistance', () => {
- it('is the euclidean distance from camera position to look-at target', () => {
- // position 3-4-0 from origin target → 5 (3-4-5 triangle)
- expect(presetFocusDistance({ position: [3, 4, 0], target: [0, 0, 0] })).toBe(5);
- });
- it('is always positive and finite for every shipped preset', () => {
- for (const p of PHOTO_PRESETS) {
- const d = presetFocusDistance(p);
- expect(Number.isFinite(d)).toBe(true);
- expect(d).toBeGreaterThan(0);
- }
- });
- it('falls back to 1 for malformed presets (never zero focal plane)', () => {
- expect(presetFocusDistance(undefined)).toBe(1);
- expect(presetFocusDistance({})).toBe(1);
- expect(presetFocusDistance({ position: [0, 0, 0], target: [0, 0, 0] })).toBe(1); // distance 0 → fallback
- });
-});
-
-describe('getDofParams', () => {
- it('derives focus from the preset framing and applies the default aperture/maxblur', () => {
- const params = getDofParams('downtown');
- expect(params.focus).toBe(presetFocusDistance(getPreset('downtown')));
- expect(params.aperture).toBe(DOF_DEFAULTS.aperture);
- expect(params.maxblur).toBe(DOF_DEFAULTS.maxblur);
- });
- it('falls back to the default preset for an unknown id', () => {
- expect(getDofParams('nope').focus).toBe(getDofParams(DEFAULT_PRESET_ID).focus);
- });
- it('honors a per-preset aperture override while still defaulting unspecified fields', () => {
- // low-angle ships a wider aperture override but no maxblur override.
- const lowAngle = getPreset('low-angle');
- expect(lowAngle.dof?.aperture).toBe(0.09); // guards the shipped override against drift
- const params = getDofParams('low-angle');
- expect(params.aperture).toBe(0.09);
- expect(params.maxblur).toBe(DOF_DEFAULTS.maxblur); // unspecified → default
- });
- it('always returns positive finite aperture/maxblur and a positive focus', () => {
- for (const p of PHOTO_PRESETS) {
- const params = getDofParams(p.id);
- expect(params.focus).toBeGreaterThan(0);
- expect(params.aperture).toBeGreaterThan(0);
- expect(params.maxblur).toBeGreaterThan(0);
- expect(Number.isFinite(params.aperture)).toBe(true);
- expect(Number.isFinite(params.maxblur)).toBe(true);
- }
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldPlan.js b/client/src/utils/openWorldPlan.js
deleted file mode 100644
index dbabf7cd1a..0000000000
--- a/client/src/utils/openWorldPlan.js
+++ /dev/null
@@ -1,446 +0,0 @@
-// OpenWorld's master archipelago plan — THE single source of truth for its geography.
-// Every district helper anchors its parcel here (instead of each module hardcoding its own
-// compass position), so streets, the transit loop, the waterfront, and the overlap/shoreline
-// invariant tests all read the same map. No three.js / React imports — the whole plan is
-// plain data + pure math, unit-testable in node (mirrors openWorldDistrictLayout.js).
-//
-// The Port sits at the center; Memory Wilds and Maker Reach branch north, Signal Cape
-// carries their trails to Data Harbor, and Archive Rise branches south into the Focus
-// Gardens and Wellness Grove. Open water makes those regions readable at a glance.
-
-export const WORLD = {
- bound: 180, // hard XZ world bound (matches PlayerController)
- shorelineZ: -56, // land for z > shorelineZ; water (the bay) beyond
- landHalf: 60, // half-extent of the paved city ground plane (x ±landHalf, z shoreline→+landHalf)
- // The new world is a chain of raised islands. Live landmarks still sit at y=0,
- // while the ocean and distant terrain sit well below the playable shelves.
- terrainY: -2.8,
- waterY: -2.55,
- groundY: 0,
- waterSpan: 520, // how far the water plane extends past the shoreline / to each side
-};
-
-// OpenWorld is an authored archipelago rather than a rectangular city slab. Each
-// island owns a recognizable PortOS biome; bridges make a continuous Signal Trail
-// through all of them. The same data drives rendering, collision, and the mini-map.
-// Radii are deliberately generous around landmark anchors so a live-data structure
-// never appears to float off the terrain when its own footprint grows slightly.
-export const ARCHIPELAGO_ISLANDS = [
- // The street-level game now reads as one cozy valley rather than eight empty plates.
- // Overlap is deliberate: the named neighborhoods remain legible on the map, while the
- // playable ground joins into an Animal-Crossing-like village with no dead ocean gaps.
- { id: 'core', label: 'The Port', center: [0, -4], radiusX: 56, radiusZ: 51, seed: 111, biome: 'port' },
- { id: 'memory', label: 'Memory Wilds', center: [-39, -33], radiusX: 29, radiusZ: 24, seed: 223, biome: 'memory' },
- { id: 'forge', label: 'Maker Reach', center: [39, -29], radiusX: 29, radiusZ: 24, seed: 337, biome: 'forge' },
- { id: 'signal', label: 'Signal Cape', center: [7, -48], radiusX: 20, radiusZ: 15, seed: 449, biome: 'signal' },
- { id: 'harbor', label: 'Data Harbor', center: [0, -66], radiusX: 31, radiusZ: 18, seed: 557, biome: 'harbor' },
- { id: 'archive', label: 'Archive Rise', center: [0, 40], radiusX: 46, radiusZ: 28, seed: 661, biome: 'archive' },
- { id: 'garden', label: 'Focus Gardens', center: [-45, 32], radiusX: 23, radiusZ: 20, seed: 773, biome: 'garden' },
- { id: 'wellness', label: 'Wellness Grove', center: [45, 30], radiusX: 23, radiusZ: 20, seed: 887, biome: 'wellness' },
-];
-
-// The close game renders one continuous valley shelf. Named neighborhood islands remain
-// as semantic geography for orbital view and compatibility, while this outline is the
-// street-level ground and the Village Map silhouette.
-export const VILLAGE_GROUND = {
- id: 'village-ground',
- label: 'PortOS Village',
- center: [0, -5],
- radiusX: 74,
- radiusZ: 80,
- seed: 1061,
- biome: 'port',
-};
-
-// Causeways use explicit waypoints so the visual path can arc around landmarks.
-// `width` is the full rendered deck width and also the ground-collision corridor.
-export const ARCHIPELAGO_LINKS = [
- { id: 'core-memory', from: 'core', to: 'memory', width: 5.2, points: [[-18, -11], [-28, -22]] },
- { id: 'core-forge', from: 'core', to: 'forge', width: 5.2, points: [[18, -10], [28, -19]] },
- { id: 'core-signal', from: 'core', to: 'signal', width: 5.6, points: [[2, -27], [5, -35]] },
- { id: 'signal-harbor', from: 'signal', to: 'harbor', width: 5.6, points: [[5, -50], [2, -57]] },
- { id: 'core-archive', from: 'core', to: 'archive', width: 6.2, points: [[0, 26], [0, 31]] },
- { id: 'archive-garden', from: 'archive', to: 'garden', width: 4.8, points: [[-18, 39], [-32, 36]] },
- { id: 'archive-wellness', from: 'archive', to: 'wellness', width: 4.8, points: [[18, 38], [32, 34]] },
- { id: 'memory-signal', from: 'memory', to: 'signal', width: 4.4, points: [[-23, -39], [-9, -42]] },
- { id: 'forge-signal', from: 'forge', to: 'signal', width: 4.4, points: [[24, -36], [15, -41]] },
-];
-
-const islandById = (id) => ARCHIPELAGO_ISLANDS.find((island) => island.id === id);
-
-export const archipelagoLinkPoints = (link) => {
- const from = islandById(link?.from);
- const to = islandById(link?.to);
- if (!from || !to) return [];
- return [from.center, ...(link.points || []), to.center];
-};
-
-const pointNearSegment = (x, z, start, end, radius) => {
- const dx = end[0] - start[0];
- const dz = end[1] - start[1];
- const lengthSq = dx * dx + dz * dz;
- if (lengthSq <= 1e-9) return Math.hypot(x - start[0], z - start[1]) <= radius;
- const t = Math.max(0, Math.min(1, ((x - start[0]) * dx + (z - start[1]) * dz) / lengthSq));
- return Math.hypot(x - (start[0] + dx * t), z - (start[1] + dz * t)) <= radius;
-};
-
-export const isOnArchipelagoIsland = (x, z, inset = 0) => ARCHIPELAGO_ISLANDS.some((island) => {
- const safeX = Math.max(0.5, island.radiusX - inset);
- const safeZ = Math.max(0.5, island.radiusZ - inset);
- const nx = (x - island.center[0]) / safeX;
- const nz = (z - island.center[1]) / safeZ;
- return nx * nx + nz * nz <= 1;
-});
-
-// Street-level rendering uses one continuous valley shelf rather than the orbital
-// archipelago plates. Keep its collision outline beside the authored ground descriptor so
-// the rover never hits an invisible island boundary while still visibly on village grass.
-export const isOnVillageGround = (x, z, inset = 0) => {
- const safeX = Math.max(0.5, VILLAGE_GROUND.radiusX - inset);
- const safeZ = Math.max(0.5, VILLAGE_GROUND.radiusZ - inset);
- const nx = (x - VILLAGE_GROUND.center[0]) / safeX;
- const nz = (z - VILLAGE_GROUND.center[1]) / safeZ;
- return nx * nx + nz * nz <= 1;
-};
-
-export const isOnArchipelagoLink = (x, z, padding = 0) => ARCHIPELAGO_LINKS.some((link) => {
- const points = archipelagoLinkPoints(link);
- const radius = link.width / 2 + padding;
- for (let index = 1; index < points.length; index += 1) {
- if (pointNearSegment(x, z, points[index - 1], points[index], radius)) return true;
- }
- return false;
-});
-
-// Land parcels. `anchor` is the district's center on the ground; `w`/`d` are the static
-// footprint (x-width / z-depth) used by the invariant tests and the tinted ground pads.
-// `dynamic: true` marks data-driven grids (downtown/warehouse) whose extent grows with the
-// install — they're excluded from static-footprint checks. Anchors mirror the hand-tuned
-// pre-plan positions except: the voice beacon steps aside for the harbor avenue, and the
-// Data Harbor is new — piers over the bay, straight ahead of the default camera.
-export const PARCELS = {
- // noPad: the plaza paints its own sidewalk ring — no tinted ground pad.
- aiCore: { anchor: [0, 0, 0], w: 24, d: 24, noPad: true, label: 'AI CORE PLAZA' },
- downtown: { anchor: [0, 0, 0], w: 60, d: 60, dynamic: true, label: 'DOWNTOWN' },
- warehouse: { anchor: [0, 0, 30], w: 60, d: 60, dynamic: true, label: 'ARCHIVE DISTRICT' },
- backupVault: { anchor: [-34, 0, -10], w: 7, d: 7, label: 'BACKUP VAULT' },
- taskQueue: { anchor: [34, 0, -10], w: 8, d: 8, label: 'TASK QUEUE' },
- memory: { anchor: [-44, 0, -30], w: 22, d: 22, label: 'MEMORY QUARTER' },
- jira: { anchor: [-20, 0, -44], w: 18, d: 12, label: 'SPRINT YARD' },
- // Goal monuments + the artifact hall grow toward each other with enough earned
- // milestones (a pre-plan, visually-tolerated rarity) — footprints reflect typical installs.
- goals: { anchor: [30, 0, -40], w: 66, d: 5, label: 'GOAL MONUMENTS' },
- artifacts: { anchor: [44, 0, -28], w: 16, d: 14, label: 'HALL OF ACHIEVEMENTS' },
- // Stepped off the avenue centerline (was [0,0,-40]) so the plaza→harbor avenue runs clear.
- voice: { anchor: [9, 0, -38], w: 5, d: 5, label: 'VOICE BEACON' },
- productivity: { anchor: [-48, 0, 28], w: 10, d: 10, label: 'PRODUCTIVITY' },
- health: { anchor: [48, 0, 28], w: 8, d: 8, label: 'WELLNESS TOWER' },
- easterEggs: { anchor: [-46, 0, 40], w: 8, d: 10, label: 'QUIET CORNER' },
- // Over the water: a pier district between the shoreline and the federation horizon.
- dataHarbor: { anchor: [0, 0, -64], w: 40, d: 16, water: true, label: 'DATA HARBOR' },
-};
-
-export const PLAZA = { center: [0, 0, 0], radius: 12, sidewalkOuter: 14.5 };
-
-// Street-level cottage footprints. Rendering, rover collision, and camera avoidance all
-// share these envelopes so the cozy village is a physical place instead of set dressing
-// the player can ghost through. The central pavilion stays open; only its floating core
-// is solid so the rover can still circle between the benches and arches.
-export const VILLAGE_COLLIDERS = [
- { id: 'core', shape: 'circle', x: 0, z: 0, radius: 2.35, height: 5.2 },
- ...[
- 'memory', 'backupVault', 'taskQueue', 'warehouse', 'health', 'productivity',
- 'jira', 'easterEggs', 'goals', 'voice', 'artifacts', 'dataHarbor',
- ].map((parcelId) => {
- const [x, , z] = PARCELS[parcelId].anchor;
- return { id: parcelId, shape: 'box', x, z, halfWidth: 3.1, halfDepth: 2.6, height: 6.4 };
- }),
-];
-
-// Curved village lanes are the visual and play rhythm of street-level OpenWorld. The
-// broad heart loop keeps a landmark or garden entering the frame every few seconds; short
-// branches terminate at real PortOS destinations. Curves are rendered from this registry,
-// so art direction and vehicle route composition cannot drift apart.
-export const VILLAGE_ROUTES = [
- {
- id: 'heart-loop',
- kind: 'road',
- width: 5.4,
- closed: true,
- points: [[0, 36], [-16, 32], [-27, 18], [-29, 1], [-20, -14], [-5, -22], [13, -20], [28, -8], [29, 11], [19, 28]],
- },
- { id: 'harbor-lane', kind: 'road', width: 5.2, points: [[-5, -22], [0, -36], [3, -50], [0, -64]] },
- { id: 'memory-lane', kind: 'path', width: 3.8, points: [[-20, -14], [-31, -22], [-44, -30]] },
- { id: 'maker-lane', kind: 'path', width: 3.8, points: [[13, -20], [28, -26], [43, -28]] },
- { id: 'garden-lane', kind: 'path', width: 3.6, points: [[-16, 32], [-30, 34], [-47, 31]] },
- { id: 'wellness-lane', kind: 'path', width: 3.6, points: [[19, 28], [32, 30], [47, 28]] },
- { id: 'arrival-lane', kind: 'road', width: 5.4, points: [[0, 50], [0, 43], [0, 36]] },
-];
-
-// Managed apps become a little market around the Common in exploration mode. The first
-// ring reads from the main road; a staggered second ring lets larger installs keep their
-// identity without rebuilding the village around app count. Archived apps belong to the
-// Archive Lodge and are summarized there instead of occupying active market stalls.
-export const VILLAGE_APP_MARKET = {
- innerRadius: 12.8,
- outerRadius: 17.2,
- innerCapacity: 8,
- maxKiosks: 18,
- halfWidth: 1.28,
- halfDepth: 0.92,
- height: 3.25,
-};
-
-const APP_STATUS_ORDER = { online: 0, stopped: 1, not_started: 2, unknown: 3, not_found: 4 };
-
-export function computeVillageAppLayout(apps = []) {
- const active = (Array.isArray(apps) ? apps : [])
- .filter((app) => app?.id && !app.archived)
- .sort((a, b) => {
- const statusDelta = (APP_STATUS_ORDER[a.overallStatus] ?? 5) - (APP_STATUS_ORDER[b.overallStatus] ?? 5);
- if (statusDelta !== 0) return statusDelta;
- return String(a.name || a.id).localeCompare(String(b.name || b.id));
- })
- .slice(0, VILLAGE_APP_MARKET.maxKiosks);
-
- const positions = new Map();
- active.forEach((app, index) => {
- const outer = index >= VILLAGE_APP_MARKET.innerCapacity;
- const ringIndex = outer ? index - VILLAGE_APP_MARKET.innerCapacity : index;
- const ringCount = outer
- ? Math.max(1, active.length - VILLAGE_APP_MARKET.innerCapacity)
- : Math.min(active.length, VILLAGE_APP_MARKET.innerCapacity);
- const radius = outer ? VILLAGE_APP_MARKET.outerRadius : VILLAGE_APP_MARKET.innerRadius;
- const stagger = outer ? Math.PI / Math.max(3, ringCount) : 0;
- // Begin in the Common's front-right quarter so even a one-app install presents a
- // storefront on arrival instead of hiding its only kiosk behind the pavilion.
- const angle = (ringIndex / ringCount) * Math.PI * 2 + stagger + Math.PI / 4;
- const x = Math.cos(angle) * radius;
- const z = Math.sin(angle) * radius;
- positions.set(app.id, {
- x,
- z,
- yaw: Math.atan2(x, z),
- district: 'village-market',
- height: VILLAGE_APP_MARKET.height,
- halfWidth: VILLAGE_APP_MARKET.halfWidth,
- halfDepth: VILLAGE_APP_MARKET.halfDepth,
- compact: true,
- });
- });
- return positions;
-}
-
-const smoothstep = (edge0, edge1, value) => {
- const t = Math.max(0, Math.min(1, (value - edge0) / (edge1 - edge0)));
- return t * t * (3 - 2 * t);
-};
-
-// Pure height function shared by the terrain mesh, player grounding, camera, and rover
-// suspension. Broad rolls establish a toy-diorama silhouette; fine ripples are deliberately
-// small enough for a Kabsch-fitted chassis to reveal them without making the route bumpy.
-export function openWorldTerrainHeight(x, z) {
- let influence = 0;
- let seed = 0;
- for (const island of ARCHIPELAGO_ISLANDS) {
- const nx = (x - island.center[0]) / island.radiusX;
- const nz = (z - island.center[1]) / island.radiusZ;
- const radius = Math.hypot(nx, nz);
- if (radius >= 1) continue;
- const nextInfluence = smoothstep(1, 0.18, radius);
- if (nextInfluence > influence) {
- influence = nextInfluence;
- seed = island.seed;
- }
- }
- if (influence <= 0) return 0;
-
- const broad = Math.sin((x + seed * 0.01) * 0.075) * 0.28
- + Math.cos((z - seed * 0.006) * 0.09) * 0.22;
- const fine = Math.sin(x * 0.31 + z * 0.19) * 0.055;
- const arrivalHump = 0.48 * Math.exp(-((x * x) + ((z - 42) * (z - 42)) * 0.55) / 34);
- const harborDip = -0.28 * Math.exp(-((x * x) + ((z + 56) * (z + 56))) / 95);
-
- // Keep the immediate doorstep of every destination calm so cottages and live-data
- // monuments share a dependable foundation in both game and orbital modes.
- const nearestParcel = Object.values(PARCELS).reduce((nearest, parcel) => {
- const distance = Math.hypot(x - parcel.anchor[0], z - parcel.anchor[2]);
- return Math.min(nearest, distance);
- }, Infinity);
- const doorstep = smoothstep(3.5, 9, nearestParcel);
-
- return (broad + fine + arrivalHump + harborDip) * influence * (0.28 + doorstep * 0.72);
-}
-
-// Elevated transit loop — a closed ride through every quarter, rendered as a glowing tube
-// with trams orbiting it. District stops are DERIVED from their parcel anchors (pulled 10%
-// toward the city center so the track skims districts instead of impaling their monuments)
-// — move a parcel and its tram stop follows. The harbor-gate stop (on the shoreline, since
-// the track stays over land) is the one explicit point.
-const TRANSIT_Y = 9; // track height — above street props, below most rooftops
-const TRANSIT_STOP_PULL = 0.1;
-const districtStop = (id) => {
- const [x, , z] = PARCELS[id].anchor;
- return { id, point: [x * (1 - TRANSIT_STOP_PULL), TRANSIT_Y, z * (1 - TRANSIT_STOP_PULL)] };
-};
-export const TRANSIT = {
- y: TRANSIT_Y,
- stopPull: TRANSIT_STOP_PULL,
- stops: [
- districtStop('productivity'),
- districtStop('backupVault'),
- districtStop('memory'),
- districtStop('jira'),
- { id: 'harborGate', point: [0, TRANSIT_Y, WORLD.shorelineZ + 9] },
- districtStop('goals'),
- districtStop('artifacts'),
- districtStop('taskQueue'),
- districtStop('health'),
- districtStop('warehouse'),
- ],
- tramCount: 3,
- tramSpeed: 0.012, // loop fraction per second — a leisurely orbit (~80s per lap)
-};
-
-// True when a ground position sits in the bay (used by the skyline ring to skip silhouettes
-// that would otherwise stand in the water, and by the player controller to keep walking
-// players on land). `margin` extends the water zone toward land (positive = stricter).
-export const isInWater = (_x, z, margin = 0) => z < WORLD.shorelineZ + margin;
-
-// True where a ground-level player may stand: inside the continuous village shelf or on
-// an authored causeway. Flying players (above rooftop height) ignore this entirely.
-export const isWalkable = (x, z) => {
- // Pull the collision boundary slightly inside the decorative village rim so the
- // rover cannot balance over open water on its outside wheels. Causeways get a
- // small forgiving shoulder for analog controls and high-speed boost entries.
- return isOnVillageGround(x, z, 0.75) || isOnArchipelagoLink(x, z, 0.45);
-};
-
-// ---------------------------------------------------------------------------
-// Streets: ring road + spokes + the harbor avenue, as flat rotated rectangles.
-// ---------------------------------------------------------------------------
-
-const RING_RADIUS = 30; // octagonal ring road just outside the downtown grid
-const ROAD_WIDTH = 3.2;
-// Exported: the Data Harbor's pier gangway continues the avenue over the water, so the
-// two widths must agree or the shoreline joint shows a seam.
-export const AVENUE_WIDTH = 4.6;
-const SPOKE_CLEARANCE = 6; // stop a spoke this short of the district anchor
-
-// Static parcels that get a street spoke from the ring road. The harbor is served by the
-// avenue; downtown/warehouse sit inside/astride the ring; aiCore is the plaza itself.
-const SPOKE_PARCELS = [
- 'backupVault', 'taskQueue', 'memory', 'jira', 'goals',
- 'artifacts', 'productivity', 'health', 'easterEggs',
-];
-
-// A street segment is a centered rectangle: rotate a [length × width] quad by `angle`
-// (radians, around Y) at ground position [x, z].
-const segment = (x1, z1, x2, z2, width) => {
- const dx = x2 - x1;
- const dz = z2 - z1;
- return {
- x: (x1 + x2) / 2,
- z: (z1 + z2) / 2,
- length: Math.hypot(dx, dz),
- angle: Math.atan2(dz, dx),
- width,
- };
-};
-
-// The full street network, derived from the plan. Pure + deterministic; the component
-// merges every rectangle into one geometry, so count here is free.
-export function computeStreets() {
- const segments = [];
-
- // Octagonal ring road around downtown.
- const ringPoints = [];
- for (let k = 0; k < 8; k++) {
- const a = (k / 8) * Math.PI * 2 + Math.PI / 8; // flat edges face the compass directions
- ringPoints.push([Math.cos(a) * RING_RADIUS, Math.sin(a) * RING_RADIUS]);
- }
- for (let k = 0; k < 8; k++) {
- const [x1, z1] = ringPoints[k];
- const [x2, z2] = ringPoints[(k + 1) % 8];
- segments.push({ ...segment(x1, z1, x2, z2, ROAD_WIDTH), kind: 'ring' });
- }
-
- // Spokes: ring → each served district, stopping short of the anchor.
- const crosswalks = [];
- for (const id of SPOKE_PARCELS) {
- const [ax, , az] = PARCELS[id].anchor;
- const dist = Math.hypot(ax, az);
- if (dist <= RING_RADIUS + SPOKE_CLEARANCE) continue; // hugs the ring already
- const ux = ax / dist;
- const uz = az / dist;
- const inner = RING_RADIUS - ROAD_WIDTH / 2; // tuck under the ring edge — no gap at the joint
- const outer = dist - SPOKE_CLEARANCE;
- segments.push({ ...segment(ux * inner, uz * inner, ux * outer, uz * outer, ROAD_WIDTH), kind: 'spoke', to: id });
- // Crosswalk band where the spoke meets the ring.
- crosswalks.push({ x: ux * RING_RADIUS, z: uz * RING_RADIUS, angle: Math.atan2(uz, ux), length: ROAD_WIDTH * 1.4, width: 2.0 });
- }
-
- // The grand avenue: plaza edge → shoreline, straight up the city's axis to the harbor.
- segments.push({
- ...segment(0, -(PLAZA.radius - 1), 0, WORLD.shorelineZ + 1, AVENUE_WIDTH),
- kind: 'avenue',
- });
-
- // A short southern arrival lane gives the rover a deliberate place to enter the
- // world when the install has no app data yet. It connects the downtown ring to
- // the default drop-in area without cutting through the central plaza.
- segments.push({
- ...segment(0, PLAZA.sidewalkOuter + 15, 0, WORLD.landHalf + 12, AVENUE_WIDTH),
- kind: 'arrival',
- });
-
- return { segments, crosswalks, plazaRing: { inner: PLAZA.radius, outer: PLAZA.sidewalkOuter } };
-}
-
-// ---------------------------------------------------------------------------
-// Street props: lamp posts along every street, planting trees ringing the plaza.
-// ---------------------------------------------------------------------------
-
-const LAMP_SPACING = 11; // world units between lamp pairs along a street
-const LAMP_SIDE_OFFSET = 2.6; // lateral distance from the street centerline
-
-// Lamp + tree positions for a given street layout. `density` scales counts (quality
-// presets): 0 → no props, 1 → full. Deterministic — same input, same town furniture.
-export function computeStreetProps(streets, density = 1) {
- const lamps = [];
- const trees = [];
- if (!streets || density <= 0) return { lamps, trees };
-
- const spacing = LAMP_SPACING / Math.min(1.5, Math.max(0.25, density));
- for (const seg of streets.segments) {
- const count = Math.floor(seg.length / spacing);
- const cos = Math.cos(seg.angle);
- const sin = Math.sin(seg.angle);
- for (let i = 0; i < count; i++) {
- // March along the segment; alternate which side of the street the lamp stands on.
- const t = (i + 0.5) / count - 0.5;
- const side = i % 2 === 0 ? 1 : -1;
- const along = t * seg.length;
- const off = side * (seg.width / 2 + LAMP_SIDE_OFFSET - 1);
- lamps.push({
- x: seg.x + cos * along - sin * off,
- z: seg.z + sin * along + cos * off,
- });
- }
- }
-
- // Trees around the plaza sidewalk, skipping the avenue mouth (north) so the walkway
- // to the harbor stays open. The stable scale variation keeps the grove from reading
- // as a repeated ring of identical icons.
- const treeCount = Math.round(10 * Math.min(1.5, density));
- const treeRadius = (streets.plazaRing.inner + streets.plazaRing.outer) / 2 + 0.6;
- for (let i = 0; i < treeCount; i++) {
- const a = (i / treeCount) * Math.PI * 2 + Math.PI / 2; // start at the south point
- const x = Math.cos(a) * treeRadius;
- const z = Math.sin(a) * treeRadius;
- if (z < -treeRadius * 0.86) continue; // the avenue mouth
- trees.push({ x, z, seed: i, scale: 0.86 + ((i * 7) % 5) * 0.07 });
- }
-
- return { lamps, trees };
-}
diff --git a/client/src/utils/openWorldPlan.test.js b/client/src/utils/openWorldPlan.test.js
deleted file mode 100644
index 3846f93cd5..0000000000
--- a/client/src/utils/openWorldPlan.test.js
+++ /dev/null
@@ -1,277 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- ARCHIPELAGO_ISLANDS,
- ARCHIPELAGO_LINKS,
- WORLD,
- PARCELS,
- PLAZA,
- TRANSIT,
- VILLAGE_APP_MARKET,
- archipelagoLinkPoints,
- computeVillageAppLayout,
- isInWater,
- isOnArchipelagoIsland,
- isOnVillageGround,
- isWalkable,
- computeStreets,
- computeStreetProps,
-} from './openWorldPlan';
-
-const staticParcels = Object.entries(PARCELS).filter(([, p]) => !p.dynamic);
-
-describe('openWorldPlan PARCELS', () => {
- it('keeps every parcel inside the world bound', () => {
- for (const [id, p] of Object.entries(PARCELS)) {
- expect(Math.abs(p.anchor[0]) + p.w / 2, id).toBeLessThanOrEqual(WORLD.bound);
- expect(Math.abs(p.anchor[2]) + p.d / 2, id).toBeLessThanOrEqual(WORLD.bound);
- }
- });
-
- it('keeps land parcels on land and water parcels in the bay', () => {
- for (const [id, p] of staticParcels) {
- const nearEdge = p.anchor[2] - p.d / 2; // most-northern (bay-ward) edge
- if (p.water) {
- expect(isInWater(p.anchor[0], p.anchor[2]), id).toBe(true);
- } else {
- expect(nearEdge, id).toBeGreaterThan(WORLD.shorelineZ);
- }
- }
- });
-
- it('keeps static parcels (except the plaza itself) clear of the AI Core plaza', () => {
- for (const [id, p] of staticParcels) {
- if (id === 'aiCore') continue;
- const dist = Math.hypot(p.anchor[0], p.anchor[2]);
- expect(dist - Math.max(p.w, p.d) / 2, id).toBeGreaterThanOrEqual(PLAZA.radius - 0.01);
- }
- });
-
- it('keeps the new harbor parcel clear of every land parcel', () => {
- const harbor = PARCELS.dataHarbor;
- for (const [id, p] of staticParcels) {
- if (id === 'dataHarbor') continue;
- const xOverlap = Math.abs(harbor.anchor[0] - p.anchor[0]) < (harbor.w + p.w) / 2;
- const zOverlap = Math.abs(harbor.anchor[2] - p.anchor[2]) < (harbor.d + p.d) / 2;
- expect(xOverlap && zOverlap, `dataHarbor vs ${id}`).toBe(false);
- }
- });
-
- it('every parcel carries an anchor, footprint, and label', () => {
- for (const [id, p] of Object.entries(PARCELS)) {
- expect(p.anchor, id).toHaveLength(3);
- expect(p.w, id).toBeGreaterThan(0);
- expect(p.d, id).toBeGreaterThan(0);
- expect(typeof p.label, id).toBe('string');
- }
- });
-});
-
-describe('isInWater', () => {
- it('classifies the bay vs land around the shoreline', () => {
- expect(isInWater(0, WORLD.shorelineZ - 1)).toBe(true);
- expect(isInWater(0, WORLD.shorelineZ + 1)).toBe(false);
- expect(isInWater(0, 0)).toBe(false);
- });
-
- it('margin extends the water zone toward land', () => {
- expect(isInWater(0, WORLD.shorelineZ + 2, 4)).toBe(true);
- expect(isInWater(0, WORLD.shorelineZ + 6, 4)).toBe(false);
- });
-});
-
-describe('isWalkable', () => {
- it('allows the continuous village shelf and connected causeways while blocking open water', () => {
- ARCHIPELAGO_ISLANDS.forEach((island) => {
- expect(isWalkable(island.center[0], island.center[1]), island.id).toBe(true);
- expect(isOnArchipelagoIsland(island.center[0], island.center[1]), island.id).toBe(true);
- });
- ARCHIPELAGO_LINKS.forEach((link) => {
- const points = archipelagoLinkPoints(link);
- for (let index = 1; index < points.length; index += 1) {
- const [x1, z1] = points[index - 1];
- const [x2, z2] = points[index];
- expect(isWalkable((x1 + x2) / 2, (z1 + z2) / 2), link.id).toBe(true);
- }
- });
- // The close game renders one valley outline, including grass between the named
- // orbital islands. That visible shelf must not contain an invisible collision wall.
- expect(isOnArchipelagoIsland(68, 0, 0.75)).toBe(false);
- expect(isOnVillageGround(68, 0, 0.75)).toBe(true);
- expect(isWalkable(68, 0)).toBe(true);
- expect(isWalkable(78, -58)).toBe(false);
- expect(isWalkable(-75, 0)).toBe(false);
- });
-
- it('keeps every island inside the hard world bound', () => {
- ARCHIPELAGO_ISLANDS.forEach((island) => {
- expect(Math.abs(island.center[0]) + island.radiusX, island.id).toBeLessThanOrEqual(WORLD.bound);
- expect(Math.abs(island.center[1]) + island.radiusZ, island.id).toBeLessThanOrEqual(WORLD.bound);
- });
- });
-});
-
-describe('computeVillageAppLayout', () => {
- it('places active apps in compact market rings and leaves archived apps at the lodge', () => {
- const apps = [
- { id: 'stopped', name: 'Stopped', overallStatus: 'stopped' },
- { id: 'online', name: 'Online', overallStatus: 'online' },
- { id: 'archived', name: 'Archived', archived: true },
- ];
- const positions = computeVillageAppLayout(apps);
-
- expect([...positions.keys()]).toEqual(['online', 'stopped']);
- expect(positions.has('archived')).toBe(false);
- for (const position of positions.values()) {
- expect(position.compact).toBe(true);
- expect(position.halfWidth).toBe(VILLAGE_APP_MARKET.halfWidth);
- expect(position.halfDepth).toBe(VILLAGE_APP_MARKET.halfDepth);
- expect(Math.hypot(position.x, position.z)).toBeCloseTo(VILLAGE_APP_MARKET.innerRadius, 6);
- }
- });
-
- it('caps stalls deterministically for very large installs', () => {
- const apps = Array.from({ length: VILLAGE_APP_MARKET.maxKiosks + 5 }, (_, index) => ({
- id: `app-${index}`,
- name: `App ${index}`,
- overallStatus: 'online',
- }));
- const first = computeVillageAppLayout(apps);
- const second = computeVillageAppLayout([...apps].reverse());
-
- expect(first.size).toBe(VILLAGE_APP_MARKET.maxKiosks);
- expect([...first]).toEqual([...second]);
- });
-});
-
-describe('TRANSIT', () => {
- it('keeps the loop track on land, above the streets, below rooftop scale', () => {
- expect(TRANSIT.y).toBeGreaterThan(6);
- expect(TRANSIT.y).toBeLessThan(14);
- for (const stop of TRANSIT.stops) {
- expect(stop.point[1], stop.id).toBe(TRANSIT.y);
- expect(isInWater(stop.point[0], stop.point[2]), stop.id).toBe(false);
- expect(Math.abs(stop.point[0]), stop.id).toBeLessThanOrEqual(WORLD.bound);
- expect(Math.abs(stop.point[2]), stop.id).toBeLessThanOrEqual(WORLD.bound);
- }
- });
-
- it('has unique stop ids', () => {
- const ids = TRANSIT.stops.map((s) => s.id);
- expect(new Set(ids).size).toBe(ids.length);
- });
-
- it('derives district stops from their parcel anchors — moving a parcel moves its stop', () => {
- for (const stop of TRANSIT.stops) {
- const parcel = PARCELS[stop.id];
- if (!parcel) continue; // harborGate / warehouse promenade are explicit
- expect(stop.point[0], stop.id).toBeCloseTo(parcel.anchor[0] * (1 - TRANSIT.stopPull), 6);
- expect(stop.point[2], stop.id).toBeCloseTo(parcel.anchor[2] * (1 - TRANSIT.stopPull), 6);
- }
- // The loop serves most quarters: at least 7 stops are parcel-derived.
- expect(TRANSIT.stops.filter((s) => PARCELS[s.id]).length).toBeGreaterThanOrEqual(7);
- });
-});
-
-describe('computeStreets', () => {
- const streets = computeStreets();
-
- it('is deterministic', () => {
- expect(computeStreets()).toEqual(streets);
- });
-
- it('builds a closed 8-segment ring road', () => {
- const ring = streets.segments.filter((s) => s.kind === 'ring');
- expect(ring).toHaveLength(8);
- for (const seg of ring) {
- // Every ring segment's center sits on the ring radius (chord midpoint, slightly inside).
- expect(Math.hypot(seg.x, seg.z)).toBeGreaterThan(20);
- expect(Math.hypot(seg.x, seg.z)).toBeLessThan(31);
- }
- });
-
- it('runs a spoke toward every outlying served district', () => {
- const spokeTargets = streets.segments.filter((s) => s.kind === 'spoke').map((s) => s.to);
- for (const id of ['memory', 'jira', 'goals', 'artifacts', 'productivity', 'health', 'easterEggs']) {
- expect(spokeTargets, id).toContain(id);
- }
- // Each spoke ends short of its district anchor (clearance) and starts at the ring.
- for (const seg of streets.segments.filter((s) => s.kind === 'spoke')) {
- const [ax, , az] = PARCELS[seg.to].anchor;
- const anchorDist = Math.hypot(ax, az);
- const segFar = Math.hypot(seg.x, seg.z) + seg.length / 2;
- expect(segFar, seg.to).toBeLessThan(anchorDist);
- }
- });
-
- it('runs the avenue from the plaza to the shoreline without entering the water', () => {
- const avenue = streets.segments.find((s) => s.kind === 'avenue');
- expect(avenue).toBeTruthy();
- expect(avenue.x).toBe(0);
- const farEdge = avenue.z - avenue.length / 2;
- expect(farEdge).toBeGreaterThanOrEqual(WORLD.shorelineZ);
- });
-
- it('provides a southern arrival lane for the default rover drop-in', () => {
- const arrival = streets.segments.find((s) => s.kind === 'arrival');
- expect(arrival).toBeTruthy();
- expect(arrival.x).toBe(0);
- expect(arrival.z + arrival.length / 2).toBeGreaterThan(WORLD.landHalf);
- expect(arrival.z - arrival.length / 2).toBeGreaterThan(PLAZA.sidewalkOuter);
- });
-
- it('keeps every street on land', () => {
- for (const seg of streets.segments) {
- const cos = Math.cos(seg.angle);
- const sin = Math.sin(seg.angle);
- for (const t of [-0.5, 0, 0.5]) {
- const z = seg.z + sin * t * seg.length;
- expect(isInWater(seg.x + cos * t * seg.length, z), seg.kind).toBe(false);
- }
- }
- });
-
- it('places a crosswalk where each spoke meets the ring', () => {
- const spokes = streets.segments.filter((s) => s.kind === 'spoke');
- expect(streets.crosswalks).toHaveLength(spokes.length);
- });
-});
-
-describe('computeStreetProps', () => {
- const streets = computeStreets();
-
- it('is deterministic and density-scaled', () => {
- const full = computeStreetProps(streets, 1);
- expect(computeStreetProps(streets, 1)).toEqual(full);
- const half = computeStreetProps(streets, 0.5);
- expect(half.lamps.length).toBeLessThan(full.lamps.length);
- expect(half.lamps.length).toBeGreaterThan(0);
- });
-
- it('returns no props at zero density or missing streets', () => {
- expect(computeStreetProps(streets, 0)).toEqual({ lamps: [], trees: [] });
- expect(computeStreetProps(null, 1)).toEqual({ lamps: [], trees: [] });
- });
-
- it('keeps lamps on land and inside the world bound', () => {
- const { lamps } = computeStreetProps(streets, 1.5);
- expect(lamps.length).toBeGreaterThan(10);
- for (const lamp of lamps) {
- expect(isInWater(lamp.x, lamp.z)).toBe(false);
- expect(Math.abs(lamp.x)).toBeLessThanOrEqual(WORLD.bound);
- expect(Math.abs(lamp.z)).toBeLessThanOrEqual(WORLD.bound);
- }
- });
-
- it('rings the plaza with trees but leaves the avenue mouth open', () => {
- const { trees } = computeStreetProps(streets, 1);
- expect(trees.length).toBeGreaterThan(5);
- for (const tree of trees) {
- const r = Math.hypot(tree.x, tree.z);
- expect(r).toBeGreaterThan(PLAZA.radius);
- // No tree blocks the avenue (north sector around x=0, z negative).
- const onAvenue = Math.abs(tree.x) < 3 && tree.z < -PLAZA.radius * 0.8;
- expect(onAvenue).toBe(false);
- }
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldPlayerRig.js b/client/src/utils/openWorldPlayerRig.js
deleted file mode 100644
index 194763e2d4..0000000000
--- a/client/src/utils/openWorldPlayerRig.js
+++ /dev/null
@@ -1,466 +0,0 @@
-// Pure math for OpenWorld's exploration-mode player rig: the third-person follow camera
-// (spherical boom behind the character with building-aware shortening), frame-rate-
-// independent damping, shortest-arc facing, and the avatar's animation-state classifier.
-// PlayerController owns the THREE.Vector3 plumbing; every formula lives here on plain
-// `{x, y, z}` objects so the whole rig is node-testable (no three.js / React imports).
-
-// Convention (matches PlayerController): forward at yaw is (-sin(yaw), 0, -cos(yaw));
-// the camera hangs BEHIND the character at (+sin(yaw), 0, +cos(yaw)) scaled by the boom.
-
-// Shared rig dimensions — the controller, the avatar, and the boom collision all read
-// these (restating them at call sites is how walk collision and camera collision drift).
-export const EYE_HEIGHT = 1.6;
-// Camera boom padding stays deliberately generous so the view does not clip into a
-// facade. Player movement uses the shape-aware colliders below instead of this radius.
-export const BUILDING_COLLISION_RADIUS = 3.5;
-export const PLAYER_COLLISION_RADIUS = 0.55;
-export const DEFAULT_SPAWN_Z = 48;
-
-export const THIRD_PERSON = {
- boom: 10.5, // intimate chase framing: the rover is a character, not a map cursor
- shoulder: 0.72, // slight lateral offset keeps the next cottage visible past the cab
- height: 3.1, // low enough for fences and trees to create useful occlusion
- isometricYaw: Math.PI / 18, // nearly aligned with the arrival lane and village gate
- isometricPitch: 0.36, // cozy diorama angle without flattening the street into a map
- fov: 42, // restrained perspective keeps nearby props substantial
- minPitch: -0.45, // looking up from under the character — floor-limited
- maxPitch: 1.15, // looking down over the character
- minCamY: 0.6, // the camera never dips into the pavement
- lookAhead: 3.2, // compose the rover against the next bend and doorway
- lookHeight: 1.05, // aim just over the roof so village silhouettes fill the frame
- camDampRate: 10, // close camera needs a little less float through tight paths
- lookDampRate: 14, // aim smoothing stays tighter than position
-};
-
-// Scroll-wheel boom zoom: a multiplier over THIRD_PERSON.boom. Steps are multiplicative
-// (exp of the wheel delta) so each notch feels equally sized at both ends of the range,
-// the way pinch-zoom does.
-export const BOOM_ZOOM = {
- min: 0.45,
- max: 2.1,
- wheelRate: 0.0011, // exp factor per unit of WheelEvent.deltaY
-};
-
-export const nextBoomZoom = (current, deltaY) =>
- Math.min(BOOM_ZOOM.max, Math.max(BOOM_ZOOM.min, current * Math.exp(deltaY * BOOM_ZOOM.wheelRate)));
-
-// Arcade vehicle tuning for the default rover. It deliberately stops short of a full
-// rigid-body simulation: OpenWorld needs a dependable, low-latency toy-car feel on a
-// dashboard canvas, while still borrowing the important reference-game cues — ramped
-// acceleration, a real brake, reverse, speed-weighted steering, and a little drift.
-export const VEHICLE = {
- bodyLength: 2.5,
- bodyWidth: 1.46,
- maxSpeed: 24,
- boostMaxSpeed: 38,
- reverseMaxSpeed: 10,
- acceleration: 22,
- boostAcceleration: 31,
- coastDeceleration: 5.5,
- brakeDeceleration: 34,
- turnRate: 2.8,
- maxWheelAngle: 0.62,
- steeringResponse: 9,
-};
-
-// The visible wheels extend a little beyond the body box. Keep that small envelope in
-// one place so the rover cannot visually overlap a wall without bringing back the old
-// multi-unit empty cushion around every building.
-export const VEHICLE_COLLISION = {
- halfWidth: 0.92,
- halfLength: 1.36,
-};
-
-const centroid = (points) => {
- const total = points.reduce((sum, point) => ({
- x: sum.x + point.x,
- y: sum.y + point.y,
- z: sum.z + point.z,
- }), { x: 0, y: 0, z: 0 });
- const count = Math.max(1, points.length);
- return { x: total.x / count, y: total.y / count, z: total.z / count };
-};
-
-const rotateByQuaternion = (point, quaternion) => {
- const { x, y, z, w } = quaternion;
- const ix = w * point.x + y * point.z - z * point.y;
- const iy = w * point.y + z * point.x - x * point.z;
- const iz = w * point.z + x * point.y - y * point.x;
- const iw = -x * point.x - y * point.y - z * point.z;
- return {
- x: ix * w + iw * -x + iy * -z - iz * -y,
- y: iy * w + iw * -y + iz * -x - ix * -z,
- z: iz * w + iw * -z + ix * -y - iy * -x,
- };
-};
-
-// Horn's quaternion form of the Kabsch fit. Given matching point clouds, return the
-// one rigid transform that best maps `reference` onto `target`. The suspension uses it
-// to let four contradictory wheel heights agree on one rigid chassis pose—roll, pitch,
-// and ride-height emerge from the fit instead of being faked from steering input.
-export function solveKabschTransform(reference, target) {
- if (!Array.isArray(reference) || !Array.isArray(target) || reference.length !== target.length || reference.length < 3) {
- return { rotation: { x: 0, y: 0, z: 0, w: 1 }, translation: { x: 0, y: 0, z: 0 }, residual: 0 };
- }
- const fromCenter = centroid(reference);
- const toCenter = centroid(target);
- const covariance = Array.from({ length: 3 }, () => [0, 0, 0]);
- reference.forEach((point, index) => {
- const p = [point.x - fromCenter.x, point.y - fromCenter.y, point.z - fromCenter.z];
- const q = [target[index].x - toCenter.x, target[index].y - toCenter.y, target[index].z - toCenter.z];
- for (let row = 0; row < 3; row += 1) {
- for (let column = 0; column < 3; column += 1) covariance[row][column] += p[row] * q[column];
- }
- });
- const [[sxx, sxy, sxz], [syx, syy, syz], [szx, szy, szz]] = covariance;
- const horn = [
- [sxx + syy + szz, syz - szy, szx - sxz, sxy - syx],
- [syz - szy, sxx - syy - szz, sxy + syx, szx + sxz],
- [szx - sxz, sxy + syx, -sxx + syy - szz, syz + szy],
- [sxy - syx, szx + sxz, syz + szy, -sxx - syy + szz],
- ];
- // Shift the symmetric matrix above zero so power iteration finds its greatest
- // algebraic eigenvalue rather than whichever signed eigenvalue has greatest magnitude.
- const shift = Math.max(...horn.map((row) => row.reduce((sum, value) => sum + Math.abs(value), 0))) + 1e-9;
- let vector = [1, 0, 0, 0];
- for (let iteration = 0; iteration < 18; iteration += 1) {
- const next = horn.map((row, rowIndex) => row.reduce((sum, value, column) => sum + value * vector[column], shift * vector[rowIndex]));
- const length = Math.hypot(...next) || 1;
- vector = next.map((value) => value / length);
- }
- const rotation = { w: vector[0], x: vector[1], y: vector[2], z: vector[3] };
- const rotatedCenter = rotateByQuaternion(fromCenter, rotation);
- const translation = {
- x: toCenter.x - rotatedCenter.x,
- y: toCenter.y - rotatedCenter.y,
- z: toCenter.z - rotatedCenter.z,
- };
- const residual = Math.sqrt(reference.reduce((sum, point, index) => {
- const rotated = rotateByQuaternion(point, rotation);
- const dx = rotated.x + translation.x - target[index].x;
- const dy = rotated.y + translation.y - target[index].y;
- const dz = rotated.z + translation.z - target[index].z;
- return sum + dx * dx + dy * dy + dz * dz;
- }, 0) / reference.length);
- return { rotation, translation, residual };
-}
-
-export function solveVehicleSuspensionPose({
- x = 0,
- z = 0,
- heading = 0,
- centerHeight = 0,
- halfWidth = VEHICLE.bodyWidth * 0.57,
- halfLength = VEHICLE.bodyLength * 0.31,
- heightAt = () => centerHeight,
-} = {}) {
- const reference = [
- { x: -halfWidth, y: 0, z: halfLength },
- { x: halfWidth, y: 0, z: halfLength },
- { x: -halfWidth, y: 0, z: -halfLength },
- { x: halfWidth, y: 0, z: -halfLength },
- ];
- const cosine = Math.cos(heading);
- const sine = Math.sin(heading);
- const wheelOffsets = reference.map((mount) => {
- const worldX = x + mount.x * cosine + mount.z * sine;
- const worldZ = z - mount.x * sine + mount.z * cosine;
- return heightAt(worldX, worldZ) - centerHeight;
- });
- const target = reference.map((mount, index) => ({ ...mount, y: wheelOffsets[index] }));
- const pose = solveKabschTransform(reference, target);
- // The rigid chassis pose already accounts for the shared slope under all four mounts.
- // Per-wheel travel is only the vertical residual that the best-fit plane could not
- // explain. Applying the full wheel offset again would double the slope: uphill tires
- // float while downhill tires sink even though the chassis is already tilted correctly.
- const wheelTravel = reference.map((mount, index) => {
- const fitted = rotateByQuaternion(mount, pose.rotation);
- return wheelOffsets[index] - (fitted.y + pose.translation.y);
- });
- return { ...pose, wheelOffsets, wheelTravel };
-}
-
-export const clampPitch = (pitch) =>
- Math.min(THIRD_PERSON.maxPitch, Math.max(THIRD_PERSON.minPitch, pitch));
-
-// Desired third-person camera + aim point for a rig pose. Pure — collision is applied
-// separately via resolveBoom so callers can damp toward the resolved point.
-export function thirdPersonCamera({
- pos,
- yaw,
- pitch,
- boom = THIRD_PERSON.boom,
- pitchOffset = 0,
-}) {
- const p = clampPitch(pitch + pitchOffset);
- const back = boom * Math.cos(p);
- const sinYaw = Math.sin(yaw);
- const cosYaw = Math.cos(yaw);
- // Right vector at this yaw (for the shoulder offset).
- const rightX = cosYaw;
- const rightZ = -sinYaw;
- return {
- camera: {
- x: pos.x + sinYaw * back + rightX * THIRD_PERSON.shoulder,
- y: Math.max(THIRD_PERSON.minCamY, pos.y + THIRD_PERSON.height + boom * Math.sin(p)),
- z: pos.z + cosYaw * back + rightZ * THIRD_PERSON.shoulder,
- },
- lookAt: {
- x: pos.x - sinYaw * THIRD_PERSON.lookAhead,
- y: pos.y + THIRD_PERSON.lookHeight,
- z: pos.z - cosYaw * THIRD_PERSON.lookAhead,
- },
- };
-}
-
-// True when a camera point lands inside a building safety cylinder. The camera keeps a
-// simpler generous envelope than the movement solver so the boom does not clip a facade.
-const insideBuilding = (point, building, radius) =>
- point.y < (building.height ?? 4) + 0.5
- && Math.hypot(point.x - building.x, point.z - building.z) < radius;
-
-// Walk the camera in toward the aim anchor until it clears every building safety cylinder,
-// returning `{ t, point }` — the boom fraction and the resolved camera position (so the
-// caller never re-derives the lerp). "Collision-aware enough" — a sampled pull-in, not a
-// raycast. `buildings` is an array or any iterable of { x, z, height }; pass a memoized
-// array on hot paths (an iterable is re-collected per call).
-export function resolveBoom({ anchor, camera, buildings, radius = BUILDING_COLLISION_RADIUS }) {
- const list = Array.isArray(buildings) ? buildings : buildings ? [...buildings] : [];
- const at = (t) => ({
- x: anchor.x + (camera.x - anchor.x) * t,
- y: anchor.y + (camera.y - anchor.y) * t,
- z: anchor.z + (camera.z - anchor.z) * t,
- });
- if (list.length === 0) return { t: 1, point: at(1) };
- const steps = [1, 0.85, 0.7, 0.55, 0.4, 0.3];
- for (const t of steps) {
- const point = at(t);
- if (!list.some((b) => insideBuilding(point, b, radius))) return { t, point };
- }
- return { t: 0.25, point: at(0.25) };
-}
-
-const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
-
-const circleIntersectsBox = (point, collider, radius) => {
- const halfWidth = Math.max(0, collider.halfWidth ?? 0);
- const halfDepth = Math.max(0, collider.halfDepth ?? 0);
- const closestX = clamp(point.x, collider.x - halfWidth, collider.x + halfWidth);
- const closestZ = clamp(point.z, collider.z - halfDepth, collider.z + halfDepth);
- const dx = point.x - closestX;
- const dz = point.z - closestZ;
- return dx * dx + dz * dz < radius * radius;
-};
-
-const vehicleAxes = (heading) => ({
- right: { x: Math.cos(heading), z: -Math.sin(heading) },
- forward: { x: -Math.sin(heading), z: -Math.cos(heading) },
-});
-
-const vehicleIntersectsCircle = (point, collider, body) => {
- const { right, forward } = vehicleAxes(body.heading ?? 0);
- const dx = collider.x - point.x;
- const dz = collider.z - point.z;
- const localX = dx * right.x + dz * right.z;
- const localZ = dx * forward.x + dz * forward.z;
- const closestX = clamp(localX, -body.halfWidth, body.halfWidth);
- const closestZ = clamp(localZ, -body.halfLength, body.halfLength);
- const offsetX = localX - closestX;
- const offsetZ = localZ - closestZ;
- return offsetX * offsetX + offsetZ * offsetZ < (collider.radius ?? 0) ** 2;
-};
-
-const vehicleIntersectsBox = (point, collider, body) => {
- const { right, forward } = vehicleAxes(body.heading ?? 0);
- const axes = [
- { x: 1, z: 0 },
- { x: 0, z: 1 },
- right,
- forward,
- ];
- const dx = collider.x - point.x;
- const dz = collider.z - point.z;
- const halfWidth = Math.max(0, collider.halfWidth ?? 0);
- const halfDepth = Math.max(0, collider.halfDepth ?? 0);
-
- return axes.every((axis) => {
- const distance = Math.abs(dx * axis.x + dz * axis.z);
- const vehicleProjection = Math.abs(axis.x * right.x + axis.z * right.z) * body.halfWidth
- + Math.abs(axis.x * forward.x + axis.z * forward.z) * body.halfLength;
- const colliderProjection = Math.abs(axis.x) * halfWidth + Math.abs(axis.z) * halfDepth;
- return distance < vehicleProjection + colliderProjection;
- });
-};
-
-const bodyIntersects = (point, colliders, body) => {
- const bodyType = body?.type || 'circle';
- if (bodyType === 'vehicle') {
- return colliders.some((collider) => {
- if (!Number.isFinite(collider?.x) || !Number.isFinite(collider?.z)) return false;
- return collider.shape === 'circle'
- ? vehicleIntersectsCircle(point, collider, body)
- : vehicleIntersectsBox(point, collider, body);
- });
- }
-
- const radius = Math.max(0, body?.radius ?? PLAYER_COLLISION_RADIUS);
- return colliders.some((collider) => {
- if (!Number.isFinite(collider?.x) || !Number.isFinite(collider?.z)) return false;
- if (collider.shape === 'circle') {
- const combinedRadius = radius + Math.max(0, collider.radius ?? 0);
- const dx = point.x - collider.x;
- const dz = point.z - collider.z;
- return dx * dx + dz * dz < combinedRadius * combinedRadius;
- }
- return circleIntersectsBox(point, collider, radius);
- });
-};
-
-// Move a player body through static 2D colliders. Each world axis is swept in small
-// increments, then the first colliding increment is binary-searched to the contact
-// point. Resolving X and Z independently gives the familiar arcade-game wall slide,
-// while the sweep prevents a fast rover frame from tunneling through a pylon.
-export function moveWithCollisions({
- position,
- displacement,
- colliders = [],
- body = { type: 'circle', radius: PLAYER_COLLISION_RADIUS },
- maxSampleDistance = 0.25,
-}) {
- const current = { x: position?.x ?? 0, z: position?.z ?? 0 };
- const shapes = Array.isArray(colliders) ? colliders : [];
- const stepDistance = Math.max(0.01, Number.isFinite(maxSampleDistance) ? maxSampleDistance : 0.25);
- const blockedAxes = { x: false, z: false };
- let blocked = false;
-
- const moveAxis = (axis, amount) => {
- if (!Number.isFinite(amount) || amount === 0) return;
- const sampleCount = Math.max(1, Math.ceil(Math.abs(amount) / stepDistance));
- const sample = amount / sampleCount;
-
- for (let index = 0; index < sampleCount; index += 1) {
- const start = current[axis];
- const end = start + sample;
- const candidate = { x: current.x, z: current.z };
- candidate[axis] = end;
- if (!bodyIntersects(candidate, shapes, body)) {
- current[axis] = end;
- continue;
- }
-
- let safe = 0;
- let contact = 1;
- for (let iteration = 0; iteration < 10; iteration += 1) {
- const midpoint = (safe + contact) * 0.5;
- const probe = { x: current.x, z: current.z };
- probe[axis] = start + sample * midpoint;
- if (bodyIntersects(probe, shapes, body)) contact = midpoint;
- else safe = midpoint;
- }
- current[axis] = start + sample * safe;
- blocked = true;
- blockedAxes[axis] = true;
- return;
- }
- };
-
- moveAxis('x', displacement?.x ?? 0);
- moveAxis('z', displacement?.z ?? 0);
-
- return { ...current, blocked, blockedAxes };
-}
-
-// Frame-rate-independent damping factor: lerp by this each frame and the closure rate
-// stays constant whether the frame took 4ms or 40ms.
-export const dampFactor = (rate, delta) => 1 - Math.exp(-rate * Math.max(0, delta));
-
-const approach = (value, target, distance) => {
- if (value < target) return Math.min(target, value + distance);
- if (value > target) return Math.max(target, value - distance);
- return target;
-};
-
-// Advance the rover by one frame. Keeping this pure makes the handling tunable without
-// tying the math to React or Three.js, and gives the controller one stable contract for
-// keyboard, touch, and future gamepad inputs.
-export function stepVehicle({
- speed = 0,
- heading = 0,
- wheelAngle = 0,
- throttle = 0,
- steer = 0,
- boost = false,
- brake = false,
- delta = 0.016,
-}) {
- const dt = Math.min(0.05, Math.max(0, delta));
- const gas = Math.max(-1, Math.min(1, throttle));
- const steering = Math.max(-1, Math.min(1, steer));
- const targetLimit = gas < 0
- ? VEHICLE.reverseMaxSpeed
- : boost ? VEHICLE.boostMaxSpeed : VEHICLE.maxSpeed;
- const targetSpeed = brake ? 0 : gas * targetLimit;
- const changingDirection = speed !== 0 && targetSpeed !== 0 && Math.sign(speed) !== Math.sign(targetSpeed);
- const response = brake || changingDirection
- ? VEHICLE.brakeDeceleration
- : Math.abs(gas) > 0.01 ? (boost && gas > 0 ? VEHICLE.boostAcceleration : VEHICLE.acceleration) : VEHICLE.coastDeceleration;
- const nextSpeed = approach(speed, targetSpeed, response * dt);
- const targetWheelAngle = steering * VEHICLE.maxWheelAngle;
- const nextWheelAngle = wheelAngle + (targetWheelAngle - wheelAngle) * dampFactor(VEHICLE.steeringResponse, dt);
- const speedRatio = Math.min(1, Math.abs(nextSpeed) / VEHICLE.boostMaxSpeed);
- const reverseFactor = nextSpeed < -0.05 ? -1 : 1;
- const nextHeading = heading - nextWheelAngle * speedRatio * VEHICLE.turnRate * dt * reverseFactor;
- const forwardX = -Math.sin(nextHeading);
- const forwardZ = -Math.cos(nextHeading);
-
- return {
- speed: nextSpeed,
- heading: nextHeading,
- wheelAngle: nextWheelAngle,
- speedRatio,
- // `skid` is intentionally a visual signal, not a second physics state. It lets the
- // rover lean into a hard turn and gives the player feedback before a full tire-trail
- // system exists.
- skid: Math.min(1, Math.abs(nextWheelAngle / VEHICLE.maxWheelAngle) * speedRatio),
- displacement: {
- x: forwardX * nextSpeed * dt,
- z: forwardZ * nextSpeed * dt,
- },
- };
-}
-
-// Shortest-arc angular lerp — never spins the long way around ±π.
-export function dampAngle(current, target, factor) {
- let diff = (target - current) % (Math.PI * 2);
- if (diff > Math.PI) diff -= Math.PI * 2;
- if (diff < -Math.PI) diff += Math.PI * 2;
- return current + diff * factor;
-}
-
-// The facing angle of the character for a local movement input: `forward` is +1 for W /
-// -1 for S, `strafe` is +1 for D / -1 for A. The camera yaw stays mouse-driven; the
-// character turns toward where it's actually going (strafe = quarter-turn run, S = run
-// toward the camera).
-export function moveFacing(yaw, { forward = 0, strafe = 0 }) {
- if (forward === 0 && strafe === 0) return yaw;
- // World-space movement direction.
- const sinYaw = Math.sin(yaw);
- const cosYaw = Math.cos(yaw);
- const dx = -sinYaw * forward + cosYaw * strafe;
- const dz = -cosYaw * forward - sinYaw * strafe;
- // Character forward is (-sin θ, -cos θ): solve θ so it aligns with (dx, dz).
- return Math.atan2(-dx, -dz);
-}
-
-// The avatar's animation state for the current rig pose.
-export function avatarState({ moving = false, sprinting = false, airborne = false }) {
- if (airborne) return 'hover';
- if (!moving) return 'idle';
- return sprinting ? 'run' : 'walk';
-}
-
-// Banking target from yaw angular velocity (rad/s): lean into turns, clamped so the
-// character never keels over. Callers damp toward this.
-export function bankAngle(yawRate, max = 0.25, gain = 0.08) {
- return Math.min(max, Math.max(-max, -yawRate * gain));
-}
diff --git a/client/src/utils/openWorldPlayerRig.test.js b/client/src/utils/openWorldPlayerRig.test.js
deleted file mode 100644
index 50d1b3d529..0000000000
--- a/client/src/utils/openWorldPlayerRig.test.js
+++ /dev/null
@@ -1,323 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- DEFAULT_SPAWN_Z, THIRD_PERSON, BOOM_ZOOM, clampPitch, thirdPersonCamera, nextBoomZoom, resolveBoom,
- dampFactor, dampAngle, moveFacing, avatarState, bankAngle, stepVehicle,
- moveWithCollisions, solveKabschTransform, solveVehicleSuspensionPose, VEHICLE_COLLISION,
-} from './openWorldPlayerRig';
-import { isWalkable } from './openWorldPlan';
-
-const pos = { x: 0, y: 1.6, z: 0 };
-
-describe('authored arrival', () => {
- it('starts the rover on The Port rather than deriving spawn from app layout', () => {
- expect(DEFAULT_SPAWN_Z).toBeGreaterThan(0);
- expect(DEFAULT_SPAWN_Z).toBeGreaterThan(40);
- expect(DEFAULT_SPAWN_Z).toBeLessThan(55);
- expect(isWalkable(0, DEFAULT_SPAWN_Z)).toBe(true);
- });
-});
-
-describe('terrain suspension', () => {
- it('preserves an identity point cloud with no residual', () => {
- const points = [
- { x: -1, y: 0, z: 1 },
- { x: 1, y: 0, z: 1 },
- { x: -1, y: 0, z: -1 },
- { x: 1, y: 0, z: -1 },
- ];
- const pose = solveKabschTransform(points, points);
- expect(pose.rotation.w).toBeCloseTo(1, 6);
- expect(pose.rotation.x).toBeCloseTo(0, 6);
- expect(pose.rotation.z).toBeCloseTo(0, 6);
- expect(pose.residual).toBeCloseTo(0, 6);
- });
-
- it('fits the chassis to four independently sampled wheel contacts', () => {
- const pose = solveVehicleSuspensionPose({
- x: 4,
- z: -7,
- heading: 0.4,
- centerHeight: 0,
- halfWidth: 0.8,
- halfLength: 1.1,
- heightAt: (x, z) => x * 0.1 + z * 0.06,
- });
- expect(new Set(pose.wheelOffsets.map((value) => value.toFixed(4))).size).toBeGreaterThan(2);
- expect(Math.hypot(pose.rotation.x, pose.rotation.z)).toBeGreaterThan(0.02);
- expect(Math.hypot(pose.rotation.x, pose.rotation.y, pose.rotation.z, pose.rotation.w)).toBeCloseTo(1, 6);
- expect(pose.residual).toBeLessThan(0.02);
- });
-
- it('uses only the small fit residual for per-wheel travel on a planar slope', () => {
- const pose = solveVehicleSuspensionPose({
- x: 0,
- z: 0,
- heading: 0,
- centerHeight: 0,
- halfWidth: 0.8,
- halfLength: 1.1,
- heightAt: (_x, z) => z * 0.25,
- });
-
- expect(Math.max(...pose.wheelOffsets.map(Math.abs))).toBeGreaterThan(0.2);
- expect(Math.max(...pose.wheelTravel.map(Math.abs))).toBeLessThan(0.01);
- });
-});
-
-describe('nextBoomZoom', () => {
- it('zooms in for an upward wheel scroll and out for a downward one', () => {
- const zoomIn = nextBoomZoom(1, -120);
- const zoomOut = nextBoomZoom(1, 120);
- expect(zoomIn).toBeLessThan(1);
- expect(zoomOut).toBeGreaterThan(1);
- });
-
- it('is symmetric per notch — equal deltas move the multiplier equally in log space', () => {
- const zoomIn = nextBoomZoom(1, -120);
- const zoomOut = nextBoomZoom(1, 120);
- expect(Math.log(zoomIn)).toBeCloseTo(-Math.log(zoomOut), 6);
- });
-
- it('clamps both ends so the boom never vanishes nor leaves the world scale', () => {
- expect(nextBoomZoom(1, -1e9)).toBe(BOOM_ZOOM.min);
- expect(nextBoomZoom(1, 1e9)).toBe(BOOM_ZOOM.max);
- });
-
- it('feeds thirdPersonCamera as a boom multiplier', () => {
- const base = thirdPersonCamera({ pos, yaw: 0, pitch: 0 });
- const close = thirdPersonCamera({ pos, yaw: 0, pitch: 0, boom: THIRD_PERSON.boom * BOOM_ZOOM.min });
- expect(Math.abs(close.camera.z - pos.z)).toBeLessThan(Math.abs(base.camera.z - pos.z));
- });
-});
-
-describe('thirdPersonCamera', () => {
- it('hangs the camera behind the character at yaw 0 (facing -Z → camera at +Z)', () => {
- const { camera, lookAt } = thirdPersonCamera({ pos, yaw: 0, pitch: 0 });
- expect(camera.z).toBeGreaterThan(pos.z + THIRD_PERSON.boom * 0.9);
- expect(camera.x).toBeCloseTo(THIRD_PERSON.shoulder, 5); // right vector at yaw 0 is +X
- expect(camera.y).toBeCloseTo(pos.y + THIRD_PERSON.height, 5);
- // Aim leads the character forward (-Z) at chest height.
- expect(lookAt.z).toBeCloseTo(-THIRD_PERSON.lookAhead, 5);
- expect(lookAt.y).toBeCloseTo(pos.y + THIRD_PERSON.lookHeight, 5);
- });
-
- it('tracks yaw — at yaw π/2 (facing -X) the camera sits at +X', () => {
- const { camera } = thirdPersonCamera({ pos, yaw: Math.PI / 2, pitch: 0 });
- expect(camera.x).toBeGreaterThan(THIRD_PERSON.boom * 0.9);
- expect(Math.abs(camera.z)).toBeLessThan(1.5); // just the shoulder offset
- });
-
- it('raises the camera with positive pitch and clamps both ends', () => {
- const level = thirdPersonCamera({ pos, yaw: 0, pitch: 0 });
- const high = thirdPersonCamera({ pos, yaw: 0, pitch: 0.8 });
- expect(high.camera.y).toBeGreaterThan(level.camera.y);
- // Clamped: an absurd pitch matches the clamp boundary exactly.
- const over = thirdPersonCamera({ pos, yaw: 0, pitch: 9 });
- const atMax = thirdPersonCamera({ pos, yaw: 0, pitch: THIRD_PERSON.maxPitch });
- expect(over.camera.y).toBeCloseTo(atMax.camera.y, 6);
- expect(clampPitch(-9)).toBe(THIRD_PERSON.minPitch);
- });
-
- it('supports a separate isometric tilt without changing the rig pitch', () => {
- const level = thirdPersonCamera({ pos, yaw: 0, pitch: 0 });
- const tilted = thirdPersonCamera({
- pos,
- yaw: 0,
- pitch: 0,
- pitchOffset: THIRD_PERSON.isometricPitch,
- });
- expect(tilted.camera.y).toBeGreaterThan(level.camera.y);
- expect(tilted.camera.z).toBeLessThan(level.camera.z);
- });
-
- it('never dips the camera into the pavement', () => {
- const { camera } = thirdPersonCamera({ pos: { x: 0, y: 1.6, z: 0 }, yaw: 0, pitch: -0.45 });
- expect(camera.y).toBeGreaterThanOrEqual(THIRD_PERSON.minCamY);
- });
-});
-
-describe('resolveBoom', () => {
- const anchor = { x: 0, y: 2, z: 0 };
-
- it('keeps the full boom with no obstructions', () => {
- const clear = resolveBoom({ anchor, camera: { x: 0, y: 3, z: 7 }, buildings: [] });
- expect(clear.t).toBe(1);
- expect(clear.point).toEqual({ x: 0, y: 3, z: 7 });
- expect(resolveBoom({ anchor, camera: { x: 0, y: 3, z: 7 }, buildings: null }).t).toBe(1);
- });
-
- it('shortens the boom when the camera lands inside a building cylinder', () => {
- const buildings = [{ x: 0, z: 7, height: 10 }];
- const { t, point } = resolveBoom({ anchor, camera: { x: 0, y: 3, z: 7 }, buildings });
- expect(t).toBeLessThan(1);
- // The resolved point actually clears the cylinder.
- expect(Math.abs(point.z - 7)).toBeGreaterThanOrEqual(3.5);
- });
-
- it('ignores buildings the camera clears above (flyover)', () => {
- const buildings = [{ x: 0, z: 7, height: 4 }];
- expect(resolveBoom({ anchor, camera: { x: 0, y: 12, z: 7 }, buildings }).t).toBe(1);
- });
-
- it('accepts any iterable (e.g. Map.values())', () => {
- const map = new Map([['a', { x: 0, z: 7, height: 10 }]]);
- const { t } = resolveBoom({ anchor, camera: { x: 0, y: 3, z: 7 }, buildings: map.values() });
- expect(t).toBeLessThan(1);
- });
-});
-
-describe('moveWithCollisions', () => {
- const box = { shape: 'box', x: 0, z: 0, halfWidth: 1, halfDepth: 1 };
-
- it('stops at a box facade instead of using a large center radius', () => {
- const result = moveWithCollisions({
- position: { x: -4, z: 0 },
- displacement: { x: 4, z: 0 },
- colliders: [box],
- body: { type: 'circle', radius: 0.5 },
- });
-
- expect(result.blocked).toBe(true);
- expect(result.x).toBeCloseTo(-1.5, 2);
- expect(result.z).toBe(0);
- expect(Number.isFinite(result.x)).toBe(true);
- });
-
- it('slides along a wall while preserving movement on the open axis', () => {
- const result = moveWithCollisions({
- position: { x: -3, z: 0 },
- displacement: { x: 3, z: 0.8 },
- colliders: [box],
- body: { type: 'circle', radius: 0.5 },
- });
-
- expect(result.blockedAxes.x).toBe(true);
- expect(result.blockedAxes.z).toBe(false);
- expect(result.x).toBeCloseTo(-1.5, 2);
- expect(result.z).toBeCloseTo(0.8, 2);
- });
-
- it('uses the rover footprint and heading for box contact', () => {
- const result = moveWithCollisions({
- position: { x: -4, z: 0 },
- displacement: { x: 4, z: 0 },
- colliders: [box],
- body: { type: 'vehicle', heading: 0, ...VEHICLE_COLLISION },
- });
-
- expect(result.blocked).toBe(true);
- expect(result.x).toBeCloseTo(-1 - VEHICLE_COLLISION.halfWidth, 2);
- });
-
- it('treats round process pylons as their actual small footprint', () => {
- const result = moveWithCollisions({
- position: { x: -3, z: 0 },
- displacement: { x: 3, z: 0 },
- colliders: [{ shape: 'circle', x: 0, z: 0, radius: 0.46 }],
- body: { type: 'circle', radius: 0.5 },
- });
-
- expect(result.blocked).toBe(true);
- expect(result.x).toBeCloseTo(-0.96, 2);
- });
-});
-
-describe('dampFactor', () => {
- it('is monotonic in delta and bounded to [0, 1)', () => {
- const a = dampFactor(8, 0.004);
- const b = dampFactor(8, 0.016);
- const c = dampFactor(8, 0.1);
- expect(a).toBeLessThan(b);
- expect(b).toBeLessThan(c);
- expect(c).toBeLessThan(1);
- expect(dampFactor(8, 0)).toBe(0);
- expect(dampFactor(8, -1)).toBe(0); // negative delta can't overshoot backward
- });
-
- it('two small steps ≈ one big step (frame-rate independence)', () => {
- const one = dampFactor(8, 0.032);
- const half = dampFactor(8, 0.016);
- const twoStep = half + (1 - half) * half;
- expect(twoStep).toBeCloseTo(one, 6);
- });
-});
-
-describe('dampAngle', () => {
- it('moves toward the target', () => {
- expect(dampAngle(0, 1, 0.5)).toBeCloseTo(0.5, 6);
- });
-
- it('takes the shortest arc across ±π', () => {
- // From just below π to just above -π is a tiny step, not a full spin.
- const next = dampAngle(Math.PI - 0.1, -Math.PI + 0.1, 0.5);
- expect(next).toBeGreaterThan(Math.PI - 0.1); // continues past π, not backward
- expect(next - (Math.PI - 0.1)).toBeCloseTo(0.1, 5);
- });
-});
-
-describe('stepVehicle', () => {
- it('ramps speed instead of teleporting to the target velocity', () => {
- const first = stepVehicle({ throttle: 1, delta: 0.016 });
- expect(first.speed).toBeGreaterThan(0);
- expect(first.speed).toBeLessThan(24);
- expect(first.displacement.z).toBeLessThan(0);
- });
-
- it('coasts down and brakes faster', () => {
- const coasting = stepVehicle({ speed: 12, delta: 0.016 });
- const braking = stepVehicle({ speed: 12, throttle: 1, brake: true, delta: 0.016 });
- expect(coasting.speed).toBeLessThan(12);
- expect(braking.speed).toBeLessThan(coasting.speed);
- });
-
- it('steers more as speed builds and reverses the turn in reverse', () => {
- const forward = stepVehicle({ speed: 18, heading: 0, steer: 1, delta: 0.016 });
- const reverse = stepVehicle({ speed: -8, heading: 0, steer: 1, delta: 0.016 });
- expect(forward.heading).toBeLessThan(0);
- expect(reverse.heading).toBeGreaterThan(0);
- expect(forward.wheelAngle).toBeGreaterThan(0);
- });
-});
-
-describe('moveFacing', () => {
- it('faces the camera yaw when moving forward', () => {
- expect(moveFacing(0.3, { forward: 1, strafe: 0 })).toBeCloseTo(0.3, 6);
- });
-
- it('quarter-turns for a pure strafe', () => {
- const right = moveFacing(0, { forward: 0, strafe: 1 });
- // Strafing right at yaw 0 moves along +X; the character faces +X → θ = -π/2.
- expect(right).toBeCloseTo(-Math.PI / 2, 6);
- const left = moveFacing(0, { forward: 0, strafe: -1 });
- expect(left).toBeCloseTo(Math.PI / 2, 6);
- });
-
- it('faces the camera when backpedaling', () => {
- const back = moveFacing(0, { forward: -1, strafe: 0 });
- expect(Math.abs(back)).toBeCloseTo(Math.PI, 6);
- });
-
- it('keeps the current yaw with no input', () => {
- expect(moveFacing(0.7, { forward: 0, strafe: 0 })).toBe(0.7);
- });
-});
-
-describe('avatarState', () => {
- it('classifies the four states with airborne taking priority', () => {
- expect(avatarState({ moving: false })).toBe('idle');
- expect(avatarState({ moving: true })).toBe('walk');
- expect(avatarState({ moving: true, sprinting: true })).toBe('run');
- expect(avatarState({ moving: true, sprinting: true, airborne: true })).toBe('hover');
- });
-});
-
-describe('bankAngle', () => {
- it('leans opposite the yaw rate and clamps', () => {
- expect(bankAngle(1)).toBeLessThan(0);
- expect(bankAngle(-1)).toBeGreaterThan(0);
- expect(bankAngle(100)).toBe(-0.25);
- expect(bankAngle(-100)).toBe(0.25);
- expect(bankAngle(0)).toBeCloseTo(0, 10);
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldProductivity.js b/client/src/utils/openWorldProductivity.js
deleted file mode 100644
index 18acc15564..0000000000
--- a/client/src/utils/openWorldProductivity.js
+++ /dev/null
@@ -1,92 +0,0 @@
-// Pure, deterministic helpers for OpenWorld's productivity district: a glowing
-// obelisk whose height reflects today's completed agent tasks and whose color
-// reflects recent velocity. No three.js / React imports.
-
-import { PARCELS } from './openWorldPlan';
-
-export const MONUMENT = {
- position: PARCELS.productivity.anchor, // southwest district — anchored by the master plan (openWorldPlan.js)
- baseWidth: 5, // footprint of the obelisk base
- minHeight: 3,
- maxHeight: 26,
- taskCap: 20,
-};
-
-// Velocity tiers drive the monument color so the district speaks recent throughput at a
-// glance. `velocity.percentage` from the quick-summary payload is "today vs. historical
-// average", where 100 ≈ on pace. Colors reuse the PortOS Tailwind design tokens.
-const TIERS = [
- { min: 120, key: 'surging', color: '#22c55e', label: 'SURGING' }, // port-success — well above pace
- { min: 80, key: 'steady', color: '#3b82f6', label: 'STEADY' }, // port-accent — roughly on pace
- { min: 40, key: 'slowing', color: '#f59e0b', label: 'SLOWING' }, // port-warning — below pace
- { min: 0, key: 'idle', color: '#ef4444', label: 'IDLE' }, // port-error — little/no recent throughput
-];
-
-const ABSENT_COLOR = '#64748b'; // slate — no productivity data at all
-
-const clamp01 = (n) => Math.max(0, Math.min(1, n));
-
-// Coerce a value to a finite number or return null (the "absent" sentinel) so callers can
-// distinguish a missing/garbage field from a legitimate 0.
-function finiteOrNull(value) {
- return typeof value === 'number' && Number.isFinite(value) ? value : null;
-}
-
-// Map today's completed task count to a 0..1 fill against the cap.
-export function throughputLevel(tasks, cap = MONUMENT.taskCap) {
- const count = finiteOrNull(tasks);
- if (count === null) return null;
- if (typeof cap !== 'number' || !Number.isFinite(cap) || cap <= 0) return null;
- return clamp01(count / cap);
-}
-
-// Classify recent velocity into a color tier. A non-numeric velocity (absent) falls through
-// to the lowest tier's color via the caller; here we only resolve a present number.
-export function velocityTier(velocity) {
- const v = finiteOrNull(velocity);
- if (v === null) return null;
- return TIERS.find((t) => v >= t.min) || TIERS[TIERS.length - 1];
-}
-
-// Full derived view-model for the component. `productivityData` is the quick-summary payload
-// (`{ today: { completed, ... }, velocity: { percentage, ... } }`).
-export function computeProductivityMonument(productivityData) {
- const payload = productivityData && typeof productivityData === 'object' ? productivityData : {};
- const todaySrc = payload.today && typeof payload.today === 'object' ? payload.today : {};
- const velocitySrc = payload.velocity && typeof payload.velocity === 'object' ? payload.velocity : {};
-
- const completedToday = finiteOrNull(todaySrc.completed);
- const level = throughputLevel(completedToday) ?? 0;
- const present = completedToday !== null;
-
- const tier = velocityTier(velocitySrc.percentage);
- // Absent productivity data reads slate/dim; a present payload always gets a tier color
- // (idle red when velocity is missing-but-data-exists, so the monument never goes dark on
- // a real-but-quiet day).
- const color = present ? (tier?.color ?? TIERS[TIERS.length - 1].color) : ABSENT_COLOR;
- const tierLabel = present ? (tier?.label ?? TIERS[TIERS.length - 1].label) : 'NO DATA';
-
- const height = MONUMENT.minHeight + level * (MONUMENT.maxHeight - MONUMENT.minHeight);
- // A present-but-quiet day still glows faintly; absent data is nearly dark.
- const intensity = present ? 0.3 + level * 0.7 : 0.1;
-
- let throughputLabel;
- if (!present) throughputLabel = 'NO DATA';
- else if (completedToday === 0) throughputLabel = 'NO TASKS TODAY';
- else throughputLabel = `${completedToday} TASK${completedToday === 1 ? '' : 'S'} TODAY`;
-
- return {
- position: MONUMENT.position,
- baseWidth: MONUMENT.baseWidth,
- height,
- level,
- present,
- completedToday,
- color,
- intensity,
- tierKey: present ? (tier?.key ?? TIERS[TIERS.length - 1].key) : 'absent',
- tierLabel,
- throughputLabel,
- surging: tier?.key === 'surging',
- };
-}
diff --git a/client/src/utils/openWorldProductivity.test.js b/client/src/utils/openWorldProductivity.test.js
deleted file mode 100644
index 34b7cdfc34..0000000000
--- a/client/src/utils/openWorldProductivity.test.js
+++ /dev/null
@@ -1,68 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import {
- MONUMENT,
- computeProductivityMonument,
- throughputLevel,
- velocityTier,
-} from './openWorldProductivity';
-
-describe('throughputLevel', () => {
- it('maps completed tasks into a clamped 0..1 level', () => {
- expect(throughputLevel(10, 20)).toBe(0.5);
- expect(throughputLevel(999, 20)).toBe(1);
- expect(throughputLevel(-5, 20)).toBe(0);
- expect(throughputLevel(0, 20)).toBe(0);
- });
-
- it('returns null for absent values and invalid caps', () => {
- expect(throughputLevel(undefined)).toBeNull();
- expect(throughputLevel('10')).toBeNull();
- expect(throughputLevel(10, 0)).toBeNull();
- });
-});
-
-// @vitest-environment node
-
-describe('velocityTier', () => {
- it('classifies present pace values and preserves absence', () => {
- expect(velocityTier(150)?.key).toBe('surging');
- expect(velocityTier(100)?.key).toBe('steady');
- expect(velocityTier(50)?.key).toBe('slowing');
- expect(velocityTier(0)?.key).toBe('idle');
- expect(velocityTier(undefined)).toBeNull();
- });
-});
-
-describe('computeProductivityMonument', () => {
- it('uses today throughput for height and labeling', () => {
- const vm = computeProductivityMonument({
- today: { completed: 10 },
- velocity: { percentage: 125 },
- });
-
- expect(vm.present).toBe(true);
- expect(vm.completedToday).toBe(10);
- expect(vm.level).toBe(0.5);
- expect(vm.height).toBe(MONUMENT.minHeight + 0.5 * (MONUMENT.maxHeight - MONUMENT.minHeight));
- expect(vm.throughputLabel).toBe('10 TASKS TODAY');
- expect(vm.tierKey).toBe('surging');
- });
-
- it('distinguishes zero throughput from absent data', () => {
- const zero = computeProductivityMonument({ today: { completed: 0 }, velocity: { percentage: 50 } });
- expect(zero.present).toBe(true);
- expect(zero.throughputLabel).toBe('NO TASKS TODAY');
- expect(zero.height).toBe(MONUMENT.minHeight);
-
- const absent = computeProductivityMonument({});
- expect(absent.present).toBe(false);
- expect(absent.throughputLabel).toBe('NO DATA');
- expect(absent.height).toBe(MONUMENT.minHeight);
- });
-
- it('tolerates malformed payloads and clamps unusually high throughput', () => {
- expect(computeProductivityMonument(null).throughputLabel).toBe('NO DATA');
- expect(computeProductivityMonument({ today: 5 }).throughputLabel).toBe('NO DATA');
- expect(computeProductivityMonument({ today: { completed: 9999 } }).level).toBe(1);
- });
-});
diff --git a/client/src/utils/openWorldProximity.js b/client/src/utils/openWorldProximity.js
deleted file mode 100644
index e1df78c7ad..0000000000
--- a/client/src/utils/openWorldProximity.js
+++ /dev/null
@@ -1,159 +0,0 @@
-// Pure deterministic proximity detection for OpenWorld exploration mode.
-// Unifies detection across buildings, warp pads, landmarks, and easter eggs.
-// No three.js / React imports — pure, testable in node.
-
-import { PARCELS } from './openWorldPlan';
-import { isOpenWorldEntryVisible } from './openWorldRegions';
-
-export const PROXIMITY_DISTANCES = {
- warpPad: 3.6,
- building: 6.0,
- landmark: 8.5,
- easterEgg: 4.5,
- shard: 3.0,
-};
-
-// Curated list of recognizable world landmarks derived from the master town plan
-export const WORLD_LANDMARKS = [
- { id: 'ai-core', regionId: 'ai-core', parcel: 'aiCore', label: 'PortOS Common', eyebrow: 'VILLAGE COMMON', action: 'VISIT THE AI CORE' },
- { id: 'backup-vault', regionId: 'backup-vault', parcel: 'backupVault', label: 'Backup Cottage', eyebrow: 'VILLAGE HOUSE', action: 'CHECK THE BACKUPS' },
- { id: 'task-queue', regionId: 'task-queue', parcel: 'taskQueue', label: 'Task Workshop', eyebrow: 'VILLAGE HOUSE', action: 'VISIT THE TASKS' },
- { id: 'archive', regionId: 'archive', parcel: 'warehouse', label: 'Archive Lodge', eyebrow: 'VILLAGE HOUSE', action: 'VISIT THE ARCHIVE' },
- { id: 'wellness', regionId: 'wellness', parcel: 'health', label: 'Wellness Greenhouse', eyebrow: 'VILLAGE GARDEN', action: 'CHECK THE VITALS' },
- { id: 'memory', regionId: 'memory', parcel: 'memory', label: 'Memory House', eyebrow: 'VILLAGE HOUSE', action: 'VISIT MEMORY' },
- { id: 'sprint-yard', regionId: 'sprint-yard', parcel: 'jira', feature: 'jira', label: 'Sprint Yard', eyebrow: 'VILLAGE YARD', action: 'VISIT THE SPRINT' },
- { id: 'quiet-corner', regionId: 'quiet-corner', parcel: 'easterEggs', label: 'Quiet Cottage', eyebrow: 'VILLAGE SECRET', action: 'VISIT THE QUIET CORNER' },
- { id: 'goals', regionId: 'goals', parcel: 'goals', label: 'Goals Lodge', eyebrow: 'VILLAGE HOUSE', action: 'VISIT THE GOALS' },
- { id: 'artifacts', regionId: 'artifacts', parcel: 'artifacts', label: 'Trophy House', eyebrow: 'VILLAGE HOUSE', action: 'SEE THE TROPHIES' },
- { id: 'voice', regionId: 'voice', parcel: 'voice', label: 'Voice Radio', eyebrow: 'VILLAGE RADIO', action: 'VISIT VOICE' },
- { id: 'data-harbor', regionId: 'data-harbor', parcel: 'dataHarbor', label: 'Data Pier', eyebrow: 'VILLAGE HARBOR', action: 'VISIT THE PIER' },
-];
-
-export function getResolvedLandmarks(isFeatureEnabled) {
- return WORLD_LANDMARKS
- .filter((landmark) => isOpenWorldEntryVisible(landmark, isFeatureEnabled))
- .map((lm) => {
- const parcel = PARCELS[lm.parcel];
- if (!parcel) return null;
- return {
- ...lm,
- x: parcel.anchor[0],
- y: 0,
- z: parcel.anchor[2],
- };
- })
- .filter(Boolean);
-}
-
-// Compute the closest interactable target to the player
-export function detectProximity({
- playerPos,
- apps = [],
- positions = null,
- warpPads = [],
- easterEggs = [],
- landmarks = getResolvedLandmarks(),
-} = {}) {
- if (!playerPos || typeof playerPos.x !== 'number' || typeof playerPos.z !== 'number') {
- return null;
- }
-
- // Validate collection-shaped inputs before iterating: this runs inside the r3f frame
- // loop, where a thrown TypeError kills rendering for the whole scene (the canvas would
- // show only its clear color). A wrong-shaped payload degrades to "no targets" instead.
- const pads = Array.isArray(warpPads) ? warpPads : [];
- const eggs = Array.isArray(easterEggs) ? easterEggs : [];
-
- const px = playerPos.x;
- const pz = playerPos.z;
-
- let closestTarget = null;
- let closestDist = Infinity;
-
- // 1. Warp pads (highest priority for fast travel nodes)
- for (const pad of pads) {
- if (!pad) continue;
- const pos = pad.position || (pad.region ? [pad.region.anchor[0], 0, pad.region.anchor[2]] : null);
- if (!pos) continue;
- const dx = px - pos[0];
- const dz = pz - pos[2];
- const dist = Math.hypot(dx, dz);
- if (dist < PROXIMITY_DISTANCES.warpPad && dist < closestDist) {
- closestDist = dist;
- const region = pad.region || pad;
- closestTarget = {
- type: 'warpPad',
- id: region.id,
- label: region.label || 'WARP GATE',
- eyebrow: 'WARP GATE',
- action: 'WARP TO',
- raw: region,
- };
- }
- }
-
- // 2. Apps / Buildings
- if (positions && typeof positions.forEach === 'function') {
- positions.forEach((pos, appId) => {
- const dx = px - pos.x;
- const dz = pz - pos.z;
- const dist = Math.hypot(dx, dz);
- if (dist < PROXIMITY_DISTANCES.building && dist < closestDist) {
- closestDist = dist;
- const app = apps.find((a) => a.id === appId);
- const name = app?.name || appId;
- closestTarget = {
- type: 'building',
- id: appId,
- label: name,
- eyebrow: 'NEARBY BUILDING',
- action: 'OPEN APP STATUS',
- raw: app || { id: appId, name },
- };
- }
- });
- }
-
- // 3. Easter eggs
- for (const egg of eggs) {
- if (!egg || !egg.position) continue;
- const dx = px - egg.position[0];
- const dz = pz - egg.position[2];
- const dist = Math.hypot(dx, dz);
- if (dist < PROXIMITY_DISTANCES.easterEgg && dist < closestDist) {
- closestDist = dist;
- closestTarget = {
- type: 'easterEgg',
- id: egg.id,
- label: `${egg.label || '?!'} — ${egg.hint || 'SECRET'}`,
- eyebrow: 'EASTER EGG FOUND',
- action: 'DISCOVER',
- raw: egg,
- };
- }
- }
-
- // 4. District landmarks (only if no closer specific target was matched)
- if (!closestTarget) {
- for (const lm of landmarks) {
- if (!lm) continue;
- const dx = px - lm.x;
- const dz = pz - lm.z;
- const dist = Math.hypot(dx, dz);
- if (dist < PROXIMITY_DISTANCES.landmark && dist < closestDist) {
- closestDist = dist;
- closestTarget = {
- type: 'landmark',
- id: lm.id,
- regionId: lm.regionId,
- label: lm.label,
- eyebrow: lm.eyebrow,
- action: lm.action,
- raw: lm,
- };
- }
- }
- }
-
- return closestTarget;
-}
diff --git a/client/src/utils/openWorldProximity.test.js b/client/src/utils/openWorldProximity.test.js
deleted file mode 100644
index 06b9299e56..0000000000
--- a/client/src/utils/openWorldProximity.test.js
+++ /dev/null
@@ -1,106 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- detectProximity,
- getResolvedLandmarks,
- WORLD_LANDMARKS,
-} from './openWorldProximity';
-
-describe('openWorldProximity', () => {
- it('resolves all world landmarks against plan parcels', () => {
- const list = getResolvedLandmarks();
- expect(list.length).toBe(WORLD_LANDMARKS.length);
- list.forEach((lm) => {
- expect(typeof lm.x).toBe('number');
- expect(typeof lm.z).toBe('number');
- expect(typeof lm.label).toBe('string');
- expect(typeof lm.eyebrow).toBe('string');
- expect(typeof lm.action).toBe('string');
- });
- });
-
- it('hides a disabled feature landmark from proximity browse surfaces', () => {
- const jiraOff = (featureId) => featureId !== 'jira';
- expect(getResolvedLandmarks(jiraOff).map((landmark) => landmark.id)).not.toContain('sprint-yard');
- expect(getResolvedLandmarks(() => true).map((landmark) => landmark.id)).toContain('sprint-yard');
- });
-
- it('detects landmark when player is close', () => {
- const aiCore = getResolvedLandmarks().find((l) => l.id === 'ai-core');
- expect(aiCore).toBeDefined();
-
- const target = detectProximity({
- playerPos: { x: aiCore.x + 1, y: 1.6, z: aiCore.z + 1 },
- landmarks: [aiCore],
- });
-
- expect(target).toBeDefined();
- expect(target?.type).toBe('landmark');
- expect(target?.id).toBe('ai-core');
- expect(target?.action).toBe('VISIT THE AI CORE');
- });
-
- it('detects warp pad with higher priority when close to warp pad', () => {
- const warpPad = {
- id: 'downtown',
- region: { id: 'downtown', label: 'Downtown' },
- position: [10, 0, 10],
- };
- const landmark = {
- id: 'downtown-landmark',
- x: 10,
- z: 10,
- label: 'Downtown Hub',
- eyebrow: 'LANDMARK',
- action: 'VIEW',
- };
-
- const target = detectProximity({
- playerPos: { x: 10.5, y: 1.6, z: 10.5 },
- warpPads: [warpPad],
- landmarks: [landmark],
- });
-
- expect(target?.type).toBe('warpPad');
- expect(target?.id).toBe('downtown');
- });
-
- it('detects easter egg when near its position', () => {
- const egg = {
- id: 'leet',
- label: '1337',
- hint: 'LEET',
- position: [-45, 1.2, 40],
- };
-
- const target = detectProximity({
- playerPos: { x: -45.5, y: 1.6, z: 40.5 },
- easterEggs: [egg],
- });
-
- expect(target?.type).toBe('easterEgg');
- expect(target?.id).toBe('leet');
- expect(target?.eyebrow).toBe('EASTER EGG FOUND');
- });
-
- it('returns null when player is far from all targets', () => {
- const target = detectProximity({
- playerPos: { x: 999, y: 1.6, z: 999 },
- landmarks: getResolvedLandmarks(),
- });
- expect(target).toBeNull();
- });
-
- it('degrades non-iterable collection payloads to "no targets" instead of throwing', () => {
- // Regression: OpenWorldScene once passed computeEasterEggs' wrapper object
- // ({ base, eggs, total, hasData }) as easterEggs. detectProximity runs inside
- // the r3f frame loop, so the resulting TypeError killed rendering every frame —
- // the world never painted and no interaction worked. A bad shape must degrade.
- const target = detectProximity({
- playerPos: { x: -45.5, y: 1.6, z: 40.5 },
- easterEggs: { eggs: [], total: 0, hasData: false },
- warpPads: { warpPadList: [] },
- landmarks: [],
- });
- expect(target).toBeNull();
- });
-});
diff --git a/client/src/utils/openWorldRegions.js b/client/src/utils/openWorldRegions.js
deleted file mode 100644
index ab1f6bd953..0000000000
--- a/client/src/utils/openWorldRegions.js
+++ /dev/null
@@ -1,138 +0,0 @@
-// OpenWorld's fast-travel region registry — the list of named places you can warp to and
-// the PortOS page each one stands for. This is what turns the world from "one city you pan
-// around" into an open world you teleport across (Breath-of-the-Wild style): every region is
-// a real destination with a name, a one-line pitch, and a door back into the 2D app.
-//
-// Geography is NOT re-declared here. Each region names a parcel in the master town plan
-// (`openWorldPlan.js` PARCELS) and reads its anchor/footprint from there, so moving a district on
-// the plan moves its fast-travel marker too — the same no-drift rule the mini-map follows.
-//
-// No React / three.js imports so the registry stays unit-testable in node (mirrors
-// openWorldMiniMap.js / openWorldFocusCamera.js). `OPEN_WORLD_REGIONS` is ALSO the source of truth for
-// the `/openworld/region/:regionId` nav-manifest entries — `server/lib/navManifest.test.js`
-// scrapes the `id:` values out of this array and fails if a region has no ⌘K / voice command
-// (or vice versa), so a new region can't ship unreachable.
-
-import { ARCHIPELAGO_ISLANDS, PARCELS, isWalkable } from './openWorldPlan';
-
-// Ordered for the fast-travel list: the two places you look at most first, then a clockwise
-// sweep of the outer districts, then the far shore. `parcel` keys into PARCELS for geography;
-// `appPath` is semantic metadata for the PortOS area the region visualizes (null for pure set
-// dressing). OpenWorld uses the region id for in-world travel and never follows this path.
-//
-// `district` marks a region whose real extent is DATA-DRIVEN — the downtown and archive grids
-// grow with the install's app count, so their PARCELS footprint is only a nominal size. It
-// names the district key in `computeOpenWorldLayout`'s output, which the camera uses to measure the
-// buildings actually on the ground instead of framing a fixed rectangle and clipping the
-// outer towers.
-export const OPEN_WORLD_REGIONS = [
- { id: 'downtown', parcel: 'downtown', district: 'downtown', label: 'Village Green', blurb: 'The sunny crossroads where every PortOS lane meets.', appPath: '/apps', aliases: ['downtown', 'apps district', 'app towers', 'village green'] },
- { id: 'ai-core', parcel: 'aiCore', label: 'PortOS Common', blurb: 'A gathering circle around the bright AI pavilion.', appPath: '/ai', aliases: ['ai core', 'core plaza', 'the core', 'reactor', 'common'] },
- { id: 'task-queue', parcel: 'taskQueue', label: 'Task Workshop', blurb: 'Chief of Staff work stacked, sorted, and ready to go.', appPath: '/cos/tasks', aliases: ['task queue', 'queue', 'cos queue', 'task workshop'] },
- { id: 'wellness', parcel: 'health', label: 'Wellness Greenhouse', blurb: 'A glass garden for CPU, memory, disk, and personal vitals.', appPath: '/system-resources/overview', aliases: ['wellness tower', 'health tower', 'vitals tower', 'greenhouse'] },
- { id: 'archive', parcel: 'warehouse', district: 'warehouse', label: 'Archive Lodge', blurb: 'A quiet lodge for archived apps and older work.', appPath: '/apps', aliases: ['archive district', 'warehouse', 'cold storage', 'archive lodge'] },
- { id: 'quiet-corner', parcel: 'easterEggs', label: 'Quiet Corner', blurb: 'The odd little things the world keeps to itself.', appPath: null, aliases: ['quiet corner', 'easter eggs'] },
- { id: 'productivity', parcel: 'productivity', label: 'Focus Farm', blurb: 'Crops, throughput, pace, and the activity calendar.', appPath: '/insights/overview', aliases: ['productivity terrace', 'productivity', 'throughput district', 'streak district', 'focus farm'] },
- { id: 'backup-vault', parcel: 'backupVault', label: 'Backup Cottage', blurb: 'The snug house that watches over the latest backup.', appPath: '/settings/backup', aliases: ['backup vault', 'the vault', 'backup cottage'] },
- { id: 'memory', parcel: 'memory', label: 'Memory House', blurb: 'A wooded home for long-term memory and the inbox well.', appPath: '/brain/inbox', aliases: ['memory quarter', 'memory district', 'knowledge district', 'memory house'] },
- { id: 'sprint-yard', parcel: 'jira', label: 'Sprint Studio', blurb: 'The current sprint laid out as a little maker yard.', appPath: '/devtools/jira', feature: 'jira', aliases: ['sprint yard', 'jira yard', 'sprint district', 'sprint studio'] },
- { id: 'voice', parcel: 'voice', label: 'Voice Radio', blurb: 'A tiny radio house that wakes when the voice agent listens.', appPath: '/digital-twin/voice', aliases: ['voice beacon', 'the beacon', 'voice radio'] },
- { id: 'goals', parcel: 'goals', label: 'Goals Lodge', blurb: 'A lodge for life goals and the paths toward them.', appPath: '/goals/tree', aliases: ['goal monuments', 'monuments', 'goals district', 'goals lodge'] },
- { id: 'artifacts', parcel: 'artifacts', label: 'Trophy House', blurb: 'Earned artifacts on cheerful display.', appPath: '/character', aliases: ['hall of achievements', 'artifact hall', 'achievements hall', 'trophy house'] },
- { id: 'data-harbor', parcel: 'dataHarbor', label: 'Data Pier', blurb: 'A cottage over the bay for tables and data domains.', appPath: '/data', aliases: ['data harbor', 'the harbor', 'piers', 'data pier'] },
-];
-
-// Route prefix the fast-travel deep links live under. Exported so callers build the URL from
-// one constant instead of re-typing it (and so the nav-manifest guard can name the prefix).
-export const OPEN_WORLD_REGION_PREFIX = '/openworld/region';
-
-export const regionPath = (id) => `${OPEN_WORLD_REGION_PREFIX}/${id}`;
-
-const REGIONS_BY_ID = new Map(OPEN_WORLD_REGIONS.map((r) => [r.id, r]));
-
-// Optional feature tags follow the caller's shared navigation gate. Untagged entries
-// and callers without a gate remain visible; tagged entries follow the gate's answer.
-export const isOpenWorldEntryVisible = (entry, isFeatureEnabled) => (
- !entry?.feature
- || typeof isFeatureEnabled !== 'function'
- || isFeatureEnabled(entry.feature)
-);
-
-// A region with its geography resolved from the master town plan: `anchor` is the ground
-// center [x, y, z], `w`/`d` the parcel footprint. The registry's `label` is what the UI
-// shows; the plan's own label rides along as `planLabel` for anything that wants the
-// in-world signage wording. Returns null for an unknown id — and for a region naming a
-// parcel that no longer exists, which the tests fail on rather than rendering at the origin.
-export function getRegion(id) {
- const region = REGIONS_BY_ID.get(id);
- if (!region) return null;
- const parcel = PARCELS[region.parcel];
- if (!parcel) return null;
- return {
- ...region,
- anchor: parcel.anchor,
- w: parcel.w,
- d: parcel.d,
- planLabel: parcel.label,
- };
-}
-
-// Every region, geography resolved, in fast-travel order. Regions whose parcel has vanished
-// from the plan are dropped rather than rendered at [0,0,0].
-export function listRegions(isFeatureEnabled) {
- return OPEN_WORLD_REGIONS
- .filter((region) => isOpenWorldEntryVisible(region, isFeatureEnabled))
- .map((r) => getRegion(r.id))
- .filter(Boolean);
-}
-
-// Case/punctuation-insensitive lookup over labels + aliases, for the fast-travel filter box.
-// Returns regions in registry order so the list never jumps around as you type.
-export function searchRegions(query, isFeatureEnabled) {
- const q = (query || '').trim().toLowerCase();
- const all = listRegions(isFeatureEnabled);
- if (!q) return all;
- return all.filter((r) =>
- r.label.toLowerCase().includes(q)
- || r.id.includes(q)
- || (r.blurb || '').toLowerCase().includes(q)
- || (r.aliases || []).some((a) => a.includes(q)));
-}
-
-// Where a walking player lands when they warp in. Start from the parcel's near (+Z)
-// edge, pulled back far enough to see the district rather than spawning inside a monument.
-// If that point falls beyond its island's authored shoreline, pull it toward the nearest
-// island interior. This keeps every gate on visible ground without teaching the region
-// registry a second, drifting set of hard-coded arrival coordinates.
-export const REGION_ARRIVAL_SETBACK = 6;
-
-export function regionArrivalPoint(region) {
- if (!region) return null;
- const [x, , z] = region.anchor;
- const proposed = { x, z: z + region.d / 2 + REGION_ARRIVAL_SETBACK };
- if (isWalkable(proposed.x, proposed.z)) return proposed;
-
- const island = ARCHIPELAGO_ISLANDS.reduce((nearest, candidate) => {
- const normalized = ((x - candidate.center[0]) / candidate.radiusX) ** 2
- + ((z - candidate.center[1]) / candidate.radiusZ) ** 2;
- return !nearest || normalized < nearest.normalized ? { island: candidate, normalized } : nearest;
- }, null)?.island;
- if (!island) return proposed;
-
- const dx = proposed.x - island.center[0];
- const dz = proposed.z - island.center[1];
- const normalizedRadius = Math.hypot(dx / island.radiusX, dz / island.radiusZ);
- const scale = normalizedRadius > 0.72 ? 0.72 / normalizedRadius : 1;
- return {
- x: island.center[0] + dx * scale,
- z: island.center[1] + dz * scale,
- };
-}
-
-// The arrival point is also the physical location of a region's warp pad. Keeping the
-// pad and the walking spawn on one projection prevents a diegetic warp from landing the
-// player somewhere different from the marker they walked to.
-export function regionWarpPadPosition(region) {
- const arrival = regionArrivalPoint(region);
- return arrival ? [arrival.x, 0.12, arrival.z] : null;
-}
diff --git a/client/src/utils/openWorldRegions.test.js b/client/src/utils/openWorldRegions.test.js
deleted file mode 100644
index 1ddfc7e645..0000000000
--- a/client/src/utils/openWorldRegions.test.js
+++ /dev/null
@@ -1,137 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- OPEN_WORLD_REGIONS,
- OPEN_WORLD_REGION_PREFIX,
- getRegion,
- listRegions,
- regionArrivalPoint,
- regionWarpPadPosition,
- regionPath,
- searchRegions,
- REGION_ARRIVAL_SETBACK,
-} from './openWorldRegions';
-import { PARCELS, isWalkable } from './openWorldPlan';
-
-describe('OPEN_WORLD_REGIONS registry', () => {
- it('has unique, URL-safe ids', () => {
- const ids = OPEN_WORLD_REGIONS.map((r) => r.id);
- expect(new Set(ids).size).toBe(ids.length);
- for (const id of ids) expect(id).toMatch(/^[a-z0-9-]+$/);
- });
-
- it('every region names a parcel that exists in the master town plan', () => {
- const missing = OPEN_WORLD_REGIONS.filter((r) => !PARCELS[r.parcel]);
- expect(missing.map((r) => `${r.id}→${r.parcel}`)).toEqual([]);
- });
-
- it('every region carries a label and a blurb', () => {
- for (const region of OPEN_WORLD_REGIONS) {
- expect(region.label).toBeTruthy();
- expect(region.blurb).toBeTruthy();
- }
- });
-
- it('app paths are absolute PortOS routes (or an explicit null for set dressing)', () => {
- for (const region of OPEN_WORLD_REGIONS) {
- if (region.appPath === null) continue;
- expect(region.appPath).toMatch(/^\//);
- }
- });
-
- it('builds deep links under the region prefix', () => {
- expect(regionPath('memory')).toBe(`${OPEN_WORLD_REGION_PREFIX}/memory`);
- });
-});
-
-describe('getRegion', () => {
- it('resolves geography from the plan rather than re-declaring it', () => {
- const region = getRegion('memory');
- expect(region.anchor).toBe(PARCELS.memory.anchor);
- expect(region.w).toBe(PARCELS.memory.w);
- expect(region.d).toBe(PARCELS.memory.d);
- expect(region.planLabel).toBe(PARCELS.memory.label);
- });
-
- it('returns null for an absent or unknown id', () => {
- // This IS the route contract: /openworld/region/:regionId hands the raw param
- // straight to getRegion, and a null means "stay on the overview".
- expect(getRegion('atlantis')).toBeNull();
- expect(getRegion('')).toBeNull();
- expect(getRegion(undefined)).toBeNull();
- expect(getRegion(null)).toBeNull();
- });
-});
-
-describe('listRegions', () => {
- it('returns every region, geography resolved, in registry order', () => {
- const list = listRegions();
- expect(list).toHaveLength(OPEN_WORLD_REGIONS.length);
- expect(list.map((r) => r.id)).toEqual(OPEN_WORLD_REGIONS.map((r) => r.id));
- for (const region of list) expect(Array.isArray(region.anchor)).toBe(true);
- });
-
- it('hides a disabled feature region from browse lists while leaving untagged regions visible', () => {
- const jiraOff = (featureId) => featureId !== 'jira';
- const list = listRegions(jiraOff);
-
- expect(list.map((region) => region.id)).not.toContain('sprint-yard');
- expect(list.map((region) => region.id)).toContain('memory');
- expect(searchRegions('jira', jiraOff)).toEqual([]);
- expect(searchRegions('jira', () => true).map((region) => region.id)).toContain('sprint-yard');
- });
-});
-
-describe('searchRegions', () => {
- it('returns everything for an empty query', () => {
- expect(searchRegions('')).toHaveLength(OPEN_WORLD_REGIONS.length);
- expect(searchRegions(' ')).toHaveLength(OPEN_WORLD_REGIONS.length);
- expect(searchRegions(undefined)).toHaveLength(OPEN_WORLD_REGIONS.length);
- });
-
- it('matches labels case-insensitively', () => {
- expect(searchRegions('MEMORY').map((r) => r.id)).toContain('memory');
- });
-
- it('matches aliases the label does not contain', () => {
- // "jira yard" is an alias of the Sprint Yard — the label never says JIRA.
- expect(searchRegions('jira').map((r) => r.id)).toContain('sprint-yard');
- });
-
- it('preserves registry order so the list does not reshuffle as you type', () => {
- const order = OPEN_WORLD_REGIONS.map((r) => r.id);
- const hits = searchRegions('t').map((r) => r.id);
- expect(hits).toEqual(order.filter((id) => hits.includes(id)));
- });
-
- it('returns an empty list for a query nothing matches', () => {
- expect(searchRegions('zzzzz-nothing')).toEqual([]);
- });
-});
-
-describe('regionArrivalPoint', () => {
- it('lands on the near (+Z) edge of the parcel, set back so you can see it', () => {
- const region = getRegion('goals');
- const point = regionArrivalPoint(region);
- expect(point.x).toBe(PARCELS.goals.anchor[0]);
- expect(point.z).toBe(PARCELS.goals.anchor[2] + PARCELS.goals.d / 2 + REGION_ARRIVAL_SETBACK);
- });
-
- it('never drops a walking player into the bay', () => {
- for (const region of listRegions()) {
- const { x, z } = regionArrivalPoint(region);
- expect(isWalkable(x, z)).toBe(true);
- }
- });
-
- it('is null-safe', () => {
- expect(regionArrivalPoint(null)).toBeNull();
- expect(regionArrivalPoint(undefined)).toBeNull();
- });
-
- it('puts the warp pad at the same ground point as the walking arrival', () => {
- const region = getRegion('memory');
- const arrival = regionArrivalPoint(region);
- expect(regionWarpPadPosition(region)).toEqual([arrival.x, 0.12, arrival.z]);
- expect(regionWarpPadPosition(null)).toBeNull();
- });
-});
diff --git a/client/src/utils/openWorldRooftops.js b/client/src/utils/openWorldRooftops.js
deleted file mode 100644
index 925b1e5e21..0000000000
--- a/client/src/utils/openWorldRooftops.js
+++ /dev/null
@@ -1,49 +0,0 @@
-// Pure, deterministic helpers for OpenWorld's rooftop fixtures: small antennas, water
-// tanks, AC units, and dish arrays scattered on app-building roofs so the skyline reads
-// as a lived-in game city instead of bare boxes. Fixtures are seeded from the app name
-// (same determinism as the procedural window textures in Building.jsx) so a building
-// keeps its roof across refetches, theme switches, and installs. No three.js / React
-// imports so the kit is unit-testable (mirrors openWorldTaskQueue.js etc.).
-
-import { hashString } from './hashString';
-
-export const ROOFTOP_TYPES = ['antenna', 'tank', 'ac', 'dish'];
-
-const MAX_FIXTURES = 3;
-const EDGE_MARGIN = 0.45; // keep fixtures off the roof edge (relative to a width-2 roof)
-
-// Successive bit-slices of the name hash drive each pick — cheap, allocation-free
-// determinism without a generator.
-const pick = (hash, shift, mod) => Math.abs(hash >> shift) % mod;
-
-// 0–3 fixtures for a roof of `width`×`width` (buildings are square). Positions are
-// offsets from the roof center; `scale` tracks the building width so kits read
-// proportionate on the rare wider structure.
-export function computeRooftopKit(name, width = 2) {
- const hash = hashString(String(name || ''));
- const count = pick(hash, 0, MAX_FIXTURES + 1); // 0..3 — some roofs stay bare
- const half = Math.max(0.2, width / 2 - EDGE_MARGIN);
- const fixtures = [];
- for (let i = 0; i < count; i++) {
- const shift = 3 + i * 7;
- const type = ROOFTOP_TYPES[pick(hash, shift, ROOFTOP_TYPES.length)];
- // Two more slices position the fixture on a 5×5 roof grid (deterministic, clamped).
- const gx = pick(hash, shift + 2, 5) / 4 - 0.5; // -0.5..0.5
- const gz = pick(hash, shift + 4, 5) / 4 - 0.5;
- fixtures.push({
- type,
- x: gx * 2 * half,
- z: gz * 2 * half,
- scale: 0.8 + pick(hash, shift + 5, 3) * 0.2, // 0.8 / 1.0 / 1.2
- rotation: pick(hash, shift + 6, 8) * (Math.PI / 4),
- });
- }
- // Two fixtures on the same grid cell read as one mangled prop — drop duplicates.
- const seen = new Set();
- return fixtures.filter((f) => {
- const key = `${Math.round(f.x * 10)},${Math.round(f.z * 10)}`;
- if (seen.has(key)) return false;
- seen.add(key);
- return true;
- });
-}
diff --git a/client/src/utils/openWorldRooftops.test.js b/client/src/utils/openWorldRooftops.test.js
deleted file mode 100644
index 35ed80b708..0000000000
--- a/client/src/utils/openWorldRooftops.test.js
+++ /dev/null
@@ -1,51 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import { computeRooftopKit, ROOFTOP_TYPES } from './openWorldRooftops';
-
-describe('computeRooftopKit', () => {
- it('is deterministic per name', () => {
- expect(computeRooftopKit('port-os')).toEqual(computeRooftopKit('port-os'));
- expect(computeRooftopKit('another-app', 2)).toEqual(computeRooftopKit('another-app', 2));
- });
-
- it('returns 0–3 fixtures of known types', () => {
- for (const name of ['a', 'bb', 'ccc', 'port-os', 'my-app', 'svc-12', 'x9', 'zzz']) {
- const kit = computeRooftopKit(name);
- expect(kit.length).toBeLessThanOrEqual(3);
- for (const f of kit) {
- expect(ROOFTOP_TYPES).toContain(f.type);
- expect(f.scale).toBeGreaterThan(0);
- }
- }
- });
-
- it('keeps every fixture inside the roof bounds', () => {
- for (const width of [2, 3.5]) {
- for (const name of ['port-os', 'another-app', 'svc-12', 'big-roof-app']) {
- for (const f of computeRooftopKit(name, width)) {
- expect(Math.abs(f.x), name).toBeLessThanOrEqual(width / 2);
- expect(Math.abs(f.z), name).toBeLessThanOrEqual(width / 2);
- }
- }
- }
- });
-
- it('varies across names (not every roof identical)', () => {
- const kits = ['app-one', 'app-two', 'app-three', 'app-four', 'app-five', 'gamma', 'delta']
- .map((n) => JSON.stringify(computeRooftopKit(n)));
- expect(new Set(kits).size).toBeGreaterThan(1);
- });
-
- it('never stacks two fixtures on the same spot', () => {
- for (const name of ['port-os', 'another-app', 'svc-12', 'abcdefg', 'q']) {
- const kit = computeRooftopKit(name);
- const keys = kit.map((f) => `${Math.round(f.x * 10)},${Math.round(f.z * 10)}`);
- expect(new Set(keys).size).toBe(keys.length);
- }
- });
-
- it('tolerates a missing name', () => {
- expect(() => computeRooftopKit(undefined)).not.toThrow();
- expect(() => computeRooftopKit('')).not.toThrow();
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldSoundscape.js b/client/src/utils/openWorldSoundscape.js
deleted file mode 100644
index 46d0c09105..0000000000
--- a/client/src/utils/openWorldSoundscape.js
+++ /dev/null
@@ -1,101 +0,0 @@
-// Pure, deterministic mapping from live system state → ambient soundscape parameters
-// (OpenWorld v2 roadmap 3.4). The synth-music layer reads these to shift its mood, brightness,
-// and "energy" so the city's drone reflects what's actually happening: a healthy, quiet system
-// sounds calm and bright; a stressed system (high CPU/mem, health warnings) darkens and tenses;
-// active agents add rhythmic energy (a louder arp voice). No Web Audio / React imports so the
-// mapping is unit-testable — openWorldSynthMusic.js applies the result to the live graph.
-
-// Two chord tables the music engine switches between. BRIGHT is the existing major-leaning
-// progression (calm/healthy); TENSE is a darker, more dissonant set used when the system is
-// under stress. Frequencies are bass roots + chord tones in Hz, matching openWorldSynthMusic's shape.
-export const CHORD_SETS = {
- bright: [
- [110, 130.81, 164.81], // Am
- [82.41, 123.47, 164.81], // Em
- [87.31, 110, 130.81], // F
- [65.41, 98.0, 130.81], // C
- ],
- tense: [
- [110, 138.59, 164.81], // A diminished-ish (A, C#dim color)
- [77.78, 116.54, 155.56], // Eb — tritone-ish tension
- [92.50, 116.54, 138.59], // F#m color
- [69.30, 103.83, 138.59], // C# — unresolved
- ],
-};
-
-// The moods the soundscape can be in, in brightening→darkening order. Also the set of values a
-// manual override (#3395) may pin the music to — anything outside this list is not a mood.
-export const SOUNDSCAPE_MOODS = ['bright', 'neutral', 'tense'];
-
-// Validate an override value. `null`/`undefined` is the "auto" sentinel (follow live system
-// state); an unknown string (a stale or hand-edited stored setting) is also treated as auto
-// rather than silently pinning the music to a mood that no longer exists.
-export function isSoundscapeMood(mood) {
- return SOUNDSCAPE_MOODS.includes(mood);
-}
-
-// Classify overall system stress into a mood. Driven primarily by the health verdict, with a
-// CPU/memory fallback so a system that's hammered but not yet "warning" still tenses up.
-// `health` is the /system/health/details payload (or null); `agentCount` is live agents.
-export function classifyMood(health) {
- const verdict = health?.overallHealth;
- if (verdict === 'critical' || verdict === 'unhealthy') return 'tense';
- const cpu = health?.system?.cpu?.usagePercent ?? 0;
- const mem = health?.system?.memory?.usagePercent ?? 0;
- if (cpu >= 85 || mem >= 90) return 'tense';
- if (verdict === 'degraded' || cpu >= 65 || mem >= 75) return 'neutral';
- return 'bright';
-}
-
-// Energy 0..1 — how much rhythmic "life" the music has. Rises with the number of active agents
-// (the city is busy → the music gets busier), saturating so a swarm of agents doesn't blow it
-// out. A quiet, agent-less city sits at a low ambient floor, never fully silent.
-export function computeActivityEnergy(agentCount) {
- const n = Math.max(0, agentCount || 0);
- // Diminishing returns: 0 agents → 0.15 floor, ~5 agents → ~0.85, asymptotic to 1.
- return Math.min(1, 0.15 + (1 - Math.exp(-n / 2.5)) * 0.85);
-}
-
-// Full soundscape view-model the music engine applies. `mood` picks the chord table and a base
-// filter brightness; `energy` scales the arp/lead voice gain and a subtle tempo feel; `detune`
-// widens the pads as tension rises for an uneasy shimmer. Deterministic for a given snapshot.
-export function computeSoundscape(snapshot = {}) {
- const { systemHealth, agentCount } = snapshot;
- return soundscapeForMood(classifyMood(systemHealth), computeActivityEnergy(agentCount));
-}
-
-// Build the view-model for an explicit (mood, energy) pair. Split out of computeSoundscape so a
-// manual mood override re-derives every mood-driven field — chord table, filter, pad detune —
-// instead of swapping the chord set alone and leaving a bright filter over a tense progression.
-export function soundscapeForMood(mood, energy) {
- // Brighter (higher) filter cutoff when healthy; clamped low when tense for a muffled, anxious
- // tone. Energy nudges it up a touch so a busy-but-healthy city sparkles.
- const filterBase = (mood === 'bright' ? 320 : mood === 'neutral' ? 220 : 150) + energy * 80;
-
- return {
- mood,
- energy,
- chordSet: mood === 'tense' ? 'tense' : 'bright', // neutral still uses the bright table, just darker filter
- filterBase,
- arpGain: 0.02 + energy * 0.08, // near-silent at rest, prominent when many agents run
- padDetune: mood === 'tense' ? 14 : mood === 'neutral' ? 10 : 8, // wider = more unease
- // A gentle tempo feel: the arp envelope opens a little faster with energy. Expressed as a
- // 0..1 scalar the engine maps onto its arp attack, NOT a literal BPM change (rescheduling
- // the running intervals mid-stream would race; modulating the voice is equivalent + safe).
- pulse: energy,
- };
-}
-
-// Pin a computed soundscape to a manually chosen mood (#3395). `mood` is the persisted override:
-// `null`/`undefined` (or any non-mood value) means auto, in which case the live soundscape passes
-// through untouched. The activity-driven half stays live even under an override — the listener is
-// choosing a mood, not freezing the city's energy — so `energy`/`arpGain`/`pulse` still follow the
-// running agent count. With no live soundscape yet, the override still yields a playable
-// view-model at the resting energy floor so the forced mood applies immediately.
-export function applyMoodOverride(soundscape, mood) {
- if (!isSoundscapeMood(mood)) return soundscape;
- const energy = typeof soundscape?.energy === 'number' && Number.isFinite(soundscape.energy)
- ? soundscape.energy
- : computeActivityEnergy(0);
- return soundscapeForMood(mood, energy);
-}
diff --git a/client/src/utils/openWorldSoundscape.test.js b/client/src/utils/openWorldSoundscape.test.js
deleted file mode 100644
index 4f34779bb6..0000000000
--- a/client/src/utils/openWorldSoundscape.test.js
+++ /dev/null
@@ -1,145 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- CHORD_SETS,
- SOUNDSCAPE_MOODS,
- applyMoodOverride,
- classifyMood,
- computeActivityEnergy,
- computeSoundscape,
- isSoundscapeMood,
-} from './openWorldSoundscape';
-
-describe('CHORD_SETS', () => {
- it('has bright and tense tables of equal length', () => {
- expect(CHORD_SETS.bright).toHaveLength(CHORD_SETS.tense.length);
- for (const set of [...CHORD_SETS.bright, ...CHORD_SETS.tense]) {
- expect(set).toHaveLength(3);
- }
- });
-});
-
-describe('classifyMood', () => {
- it('is bright for a healthy, quiet system', () => {
- expect(classifyMood({ overallHealth: 'healthy', system: { cpu: { usagePercent: 10 }, memory: { usagePercent: 20 } } })).toBe('bright');
- });
- it('is tense for a critical/unhealthy verdict', () => {
- expect(classifyMood({ overallHealth: 'critical' })).toBe('tense');
- expect(classifyMood({ overallHealth: 'unhealthy' })).toBe('tense');
- });
- it('tenses on very high CPU/memory even without a warning verdict', () => {
- expect(classifyMood({ system: { cpu: { usagePercent: 90 } } })).toBe('tense');
- expect(classifyMood({ system: { memory: { usagePercent: 95 } } })).toBe('tense');
- });
- it('is neutral when degraded or moderately loaded', () => {
- expect(classifyMood({ overallHealth: 'degraded' })).toBe('neutral');
- expect(classifyMood({ system: { cpu: { usagePercent: 70 } } })).toBe('neutral');
- });
- it('defaults to bright with no health data', () => {
- expect(classifyMood(null)).toBe('bright');
- expect(classifyMood(undefined)).toBe('bright');
- expect(classifyMood({})).toBe('bright');
- });
-});
-
-describe('computeActivityEnergy', () => {
- it('has a non-zero floor with no agents', () => {
- expect(computeActivityEnergy(0)).toBeCloseTo(0.15, 5);
- expect(computeActivityEnergy(undefined)).toBeCloseTo(0.15, 5);
- });
- it('rises monotonically with agent count and saturates below 1', () => {
- const e1 = computeActivityEnergy(1);
- const e3 = computeActivityEnergy(3);
- const e10 = computeActivityEnergy(10);
- expect(e3).toBeGreaterThan(e1);
- expect(e10).toBeGreaterThan(e3);
- expect(e10).toBeLessThanOrEqual(1);
- });
- it('clamps negatives to the floor', () => {
- expect(computeActivityEnergy(-5)).toBeCloseTo(0.15, 5);
- });
-});
-
-describe('computeSoundscape', () => {
- it('maps a healthy quiet city to a bright, low-energy soundscape', () => {
- const s = computeSoundscape({ systemHealth: { overallHealth: 'healthy' }, agentCount: 0 });
- expect(s.mood).toBe('bright');
- expect(s.chordSet).toBe('bright');
- expect(s.arpGain).toBeCloseTo(0.02 + 0.15 * 0.08, 4);
- expect(s.padDetune).toBe(8);
- });
- it('maps a stressed city to a tense chord set and muffled filter', () => {
- const calm = computeSoundscape({ systemHealth: { overallHealth: 'healthy' }, agentCount: 0 });
- const tense = computeSoundscape({ systemHealth: { overallHealth: 'critical' }, agentCount: 0 });
- expect(tense.chordSet).toBe('tense');
- expect(tense.filterBase).toBeLessThan(calm.filterBase);
- expect(tense.padDetune).toBeGreaterThan(calm.padDetune);
- });
- it('raises arp gain and energy as agents spin up', () => {
- const idle = computeSoundscape({ agentCount: 0 });
- const busy = computeSoundscape({ agentCount: 6 });
- expect(busy.arpGain).toBeGreaterThan(idle.arpGain);
- expect(busy.energy).toBeGreaterThan(idle.energy);
- expect(busy.pulse).toBe(busy.energy);
- });
- it('keeps the bright chord table for neutral mood (only filter darkens)', () => {
- const s = computeSoundscape({ systemHealth: { overallHealth: 'degraded' }, agentCount: 1 });
- expect(s.mood).toBe('neutral');
- expect(s.chordSet).toBe('bright');
- });
- it('handles an empty snapshot', () => {
- const s = computeSoundscape();
- expect(s.mood).toBe('bright');
- expect(Number.isFinite(s.filterBase)).toBe(true);
- });
-});
-
-describe('isSoundscapeMood', () => {
- it('accepts every listed mood and rejects the auto sentinel or junk', () => {
- SOUNDSCAPE_MOODS.forEach(mood => expect(isSoundscapeMood(mood)).toBe(true));
- [null, undefined, '', 'auto', 'BRIGHT', 0, {}].forEach(value => {
- expect(isSoundscapeMood(value)).toBe(false);
- });
- });
-});
-
-describe('applyMoodOverride', () => {
- const live = computeSoundscape({ systemHealth: { overallHealth: 'healthy' }, agentCount: 4 });
-
- it('pins the forced mood, re-deriving chord set, filter and detune', () => {
- expect(live.mood).toBe('bright');
- const forced = applyMoodOverride(live, 'tense');
- expect(forced.mood).toBe('tense');
- expect(forced.chordSet).toBe('tense');
- expect(forced.filterBase).toBeLessThan(live.filterBase);
- expect(forced.padDetune).toBeGreaterThan(live.padDetune);
- });
-
- it('keeps the activity-driven half live under an override', () => {
- const forced = applyMoodOverride(live, 'tense');
- expect(forced.energy).toBe(live.energy);
- expect(forced.arpGain).toBe(live.arpGain);
- expect(forced.pulse).toBe(live.pulse);
- });
-
- it('forces the neutral mood onto the bright table with a darker filter', () => {
- const forced = applyMoodOverride(live, 'neutral');
- expect(forced.chordSet).toBe('bright');
- expect(forced.filterBase).toBeLessThan(live.filterBase);
- });
-
- it('passes the live soundscape through untouched for auto or an unknown value', () => {
- expect(applyMoodOverride(live, null)).toBe(live);
- expect(applyMoodOverride(live, undefined)).toBe(live);
- expect(applyMoodOverride(live, '')).toBe(live);
- expect(applyMoodOverride(live, 'stale-mood')).toBe(live);
- });
-
- it('still yields a playable view-model when there is no live soundscape yet', () => {
- const forced = applyMoodOverride(null, 'tense');
- expect(forced.chordSet).toBe('tense');
- expect(forced.energy).toBeCloseTo(computeActivityEnergy(0), 5);
- expect(Number.isFinite(forced.filterBase)).toBe(true);
- expect(applyMoodOverride(null, null)).toBe(null);
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldSpeedPads.js b/client/src/utils/openWorldSpeedPads.js
deleted file mode 100644
index 45da9e287a..0000000000
--- a/client/src/utils/openWorldSpeedPads.js
+++ /dev/null
@@ -1,88 +0,0 @@
-// Pure deterministic helpers for OpenWorld boost markings.
-// They are painted lane flourishes in the village rather than sci-fi metal plates.
-// Driving onto a boost pad gives an instant surge of acceleration and plays a turbo SFX.
-// No three.js / React imports — pure, testable in node.
-
-export const DEFAULT_PAD_BOOST_SPEED = 48; // Peak surge velocity in units/s
-export const PAD_TRIGGER_RADIUS = 2.4;
-
-export const SPEED_PADS = [
- {
- id: 'pad-harbor-lane',
- label: 'Harbor Lane',
- x: 0,
- z: -41,
- angle: -Math.PI / 2,
- width: 3.7,
- length: 5.2,
- boostSpeed: DEFAULT_PAD_BOOST_SPEED,
- color: '#7cc9be',
- },
- {
- id: 'pad-arrival-lane',
- label: 'Village Welcome',
- x: 0,
- z: 34,
- angle: -Math.PI / 2,
- width: 3.7,
- length: 5.2,
- boostSpeed: DEFAULT_PAD_BOOST_SPEED,
- color: '#f3b856',
- },
- {
- id: 'pad-west-loop',
- label: 'Orchard Bend',
- x: -28,
- z: 8,
- angle: -Math.PI / 2,
- width: 3.6,
- length: 4.8,
- boostSpeed: DEFAULT_PAD_BOOST_SPEED,
- color: '#ec8265',
- },
- {
- id: 'pad-east-loop',
- label: 'Pond Bend',
- x: 28,
- z: 6,
- angle: Math.PI / 2,
- width: 3.6,
- length: 4.8,
- boostSpeed: DEFAULT_PAD_BOOST_SPEED,
- color: '#8ccf9e',
- },
-];
-
-// Return list of speed boost pads with geometric bounding envelopes
-export function getSpeedPadsList() {
- return SPEED_PADS.map((pad) => ({
- ...pad,
- halfWidth: pad.width / 2,
- halfLength: pad.length / 2,
- }));
-}
-
-// Check if player position is currently overlapping a speed boost pad using oriented box bounds
-export function checkSpeedPadOverlap(playerPos, pads = SPEED_PADS, padding = 0.4) {
- if (!playerPos || typeof playerPos.x !== 'number' || typeof playerPos.z !== 'number') {
- return null;
- }
-
- for (const pad of pads) {
- const dx = playerPos.x - pad.x;
- const dz = playerPos.z - pad.z;
- const cos = Math.cos(-pad.angle);
- const sin = Math.sin(-pad.angle);
- const localX = cos * dx - sin * dz;
- const localZ = sin * dx + cos * dz;
-
- const halfL = (pad.length / 2) + padding;
- const halfW = (pad.width / 2) + padding;
-
- if (Math.abs(localX) <= halfL && Math.abs(localZ) <= halfW) {
- return pad;
- }
- }
-
- return null;
-}
diff --git a/client/src/utils/openWorldSpeedPads.test.js b/client/src/utils/openWorldSpeedPads.test.js
deleted file mode 100644
index 5b1681a9f7..0000000000
--- a/client/src/utils/openWorldSpeedPads.test.js
+++ /dev/null
@@ -1,56 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- SPEED_PADS,
- getSpeedPadsList,
- checkSpeedPadOverlap,
- PAD_TRIGGER_RADIUS,
-} from './openWorldSpeedPads';
-
-describe('openWorldSpeedPads', () => {
- it('defines a valid set of speed pads with positions and angles', () => {
- expect(SPEED_PADS.length).toBeGreaterThanOrEqual(4);
- const ids = new Set();
- SPEED_PADS.forEach((pad) => {
- expect(typeof pad.id).toBe('string');
- expect(typeof pad.x).toBe('number');
- expect(typeof pad.z).toBe('number');
- expect(typeof pad.angle).toBe('number');
- expect(typeof pad.width).toBe('number');
- expect(typeof pad.length).toBe('number');
- expect(pad.boostSpeed).toBeGreaterThan(30);
- expect(ids.has(pad.id)).toBe(false);
- ids.add(pad.id);
- });
- });
-
- it('getSpeedPadsList returns pads with half dimensions', () => {
- const list = getSpeedPadsList();
- list.forEach((pad) => {
- expect(pad.halfWidth).toBe(pad.width / 2);
- expect(pad.halfLength).toBe(pad.length / 2);
- });
- });
-
- it('checkSpeedPadOverlap returns pad when player is directly on it', () => {
- const pad = SPEED_PADS[0];
- const playerPos = { x: pad.x + 0.2, z: pad.z + 0.2 };
- const matched = checkSpeedPadOverlap(playerPos, SPEED_PADS, PAD_TRIGGER_RADIUS);
- expect(matched).toBeDefined();
- expect(matched?.id).toBe(pad.id);
- });
-
- it('checkSpeedPadOverlap returns pad when player is on the rectangular edge', () => {
- // Pad 0 has length 5.5 (half 2.75). Point at pad.z - 2.5 along the facing direction (-Z)
- const pad = SPEED_PADS[0]; // angle: -Math.PI / 2 (length extends along -Z / +Z in world space)
- const playerPos = { x: pad.x, z: pad.z - 2.5 };
- const matched = checkSpeedPadOverlap(playerPos, SPEED_PADS);
- expect(matched).toBeDefined();
- expect(matched?.id).toBe(pad.id);
- });
-
- it('checkSpeedPadOverlap returns null when player is far away or invalid', () => {
- expect(checkSpeedPadOverlap(null)).toBeNull();
- expect(checkSpeedPadOverlap({ x: 999, z: 999 })).toBeNull();
- expect(checkSpeedPadOverlap({ x: 'invalid', z: 0 })).toBeNull();
- });
-});
diff --git a/client/src/utils/openWorldTaskFlowRiver.js b/client/src/utils/openWorldTaskFlowRiver.js
deleted file mode 100644
index a2abc1943b..0000000000
--- a/client/src/utils/openWorldTaskFlowRiver.js
+++ /dev/null
@@ -1,153 +0,0 @@
-// Pure, deterministic helpers for OpenWorld's task-flow river (roadmap 2.6 follow-up, issue
-// #817): an animated flow that runs from the task-queue warehouse to the productivity
-// district, visually tying queued work to completed throughput. The river's WIDTH tracks the
-// live backlog (more pending/in-progress work → a broader channel) and its SPEED tracks
-// recent throughput / queue drain (more recently-completed tasks relative to the backlog → a
-// faster current). No three.js / React imports so the topology is unit-testable (mirrors
-// openWorldProductivity.js / openWorldTaskQueue.js).
-
-import { MONUMENT } from './openWorldProductivity';
-import { TASK_QUEUE } from './openWorldTaskQueue';
-
-export const RIVER = {
- // The channel runs warehouse → monument. Endpoints mirror the two districts it links.
- from: TASK_QUEUE.position, // task-queue warehouse (east)
- to: MONUMENT.position, // productivity-district monument (southwest)
- minWidth: 1.4, // a thin trickle when the queue is empty
- maxWidth: 7, // a broad channel at/above the backlog cap
- backlogCap: 12, // backlog count mapped to full width; beyond this stays capped
- minSpeed: 0.15, // a barely-moving current when nothing is draining
- maxSpeed: 1.6, // full-tilt flow when throughput is high
- throughputCap: 10, // recently-completed count mapped to full speed
- particleSpacing: 3.2, // world units between flow particles along the channel
-};
-
-const ACTIVE_COLOR = '#22c55e'; // port-success — work is draining (completing)
-const QUEUED_COLOR = '#3b82f6'; // port-accent — backlog present, little draining
-const BLOCKED_COLOR = '#f59e0b'; // port-warning — blocked work gumming up the flow
-const IDLE_COLOR = '#475569'; // slate — empty channel, nothing moving
-
-const clamp01 = (n) => Math.max(0, Math.min(1, n));
-
-// Coerce to a finite, non-negative number or 0 — counts and throughput are never negative.
-function nonNegOrZero(value) {
- return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;
-}
-
-// Map a backlog count to a 0..1 width level against the cap, clamped.
-export function widthLevel(backlog, cap = RIVER.backlogCap) {
- const b = nonNegOrZero(backlog);
- const c = nonNegOrZero(cap) || 1;
- return clamp01(b / c);
-}
-
-// Map a recent-throughput count to a 0..1 speed level against the cap, clamped.
-export function speedLevel(throughput, cap = RIVER.throughputCap) {
- const t = nonNegOrZero(throughput);
- const c = nonNegOrZero(cap) || 1;
- return clamp01(t / c);
-}
-
-// Sum completed tasks over the most recent `days` calendar days (excluding future days), as a
-// bounded "recent drain" signal. The activity calendar's `summary.totalTasks` spans the whole
-// 12-week window, so it would pin the river at full speed forever after a few historical
-// completions; a trailing window keeps the current honest about *recent* throughput. Returns
-// null when there's no usable calendar so the caller can fall back to today's count.
-export function recentCalendarThroughput(calendarData, days = 7) {
- const weeks = Array.isArray(calendarData?.weeks) ? calendarData.weeks : null;
- if (!weeks) return null;
- const flat = [];
- for (const week of weeks) {
- if (!Array.isArray(week)) continue;
- for (const day of week) {
- if (day && typeof day === 'object' && !day.isFuture) flat.push(day);
- }
- }
- if (flat.length === 0) return null;
- const window = days > 0 ? flat.slice(-days) : flat;
- return window.reduce((sum, day) => sum + nonNegOrZero(day.tasks), 0);
-}
-
-// Euclidean distance on the ground plane (x/z) between the two endpoints.
-function groundLength(from, to) {
- const dx = to[0] - from[0];
- const dz = to[2] - from[2];
- return Math.sqrt(dx * dx + dz * dz);
-}
-
-// Full derived view-model for the component. Inputs:
-// - `taskQueue`: the `computeTaskQueue` view-model (`{ pending, inProgress, blocked, ... }`)
-// — the live backlog that sets the channel width.
-// - `recentThroughput`: a count of recently-completed tasks (e.g. the calendar window's
-// `summary.totalTasks` or today's completed) that sets the current speed.
-// Tolerates missing/garbage inputs by reading them as zero, yielding a thin, near-still,
-// idle-slate channel that still renders as a quiet seam between the districts.
-export function computeTaskFlowRiver(taskQueue, recentThroughput) {
- const queue = taskQueue && typeof taskQueue === 'object' ? taskQueue : {};
- const pending = nonNegOrZero(queue.pending);
- const inProgress = nonNegOrZero(queue.inProgress);
- const blocked = nonNegOrZero(queue.blocked);
- const backlog = pending + inProgress + blocked;
- const throughput = nonNegOrZero(recentThroughput);
-
- const wLevel = widthLevel(backlog);
- const sLevel = speedLevel(throughput);
-
- const width = RIVER.minWidth + wLevel * (RIVER.maxWidth - RIVER.minWidth);
- const speed = RIVER.minSpeed + sLevel * (RIVER.maxSpeed - RIVER.minSpeed);
-
- // Color reads the queue's dominant state, mirroring the warehouse: blocked work warns,
- // active draining flows green, a non-empty backlog sits accent-blue, an empty channel idles.
- let state;
- if (blocked > 0) state = 'blocked';
- else if (inProgress > 0) state = 'active';
- else if (pending > 0) state = 'queued';
- else state = 'idle';
- const color = state === 'blocked' ? BLOCKED_COLOR
- : state === 'active' ? ACTIVE_COLOR
- : state === 'queued' ? QUEUED_COLOR
- : IDLE_COLOR;
-
- const length = groundLength(RIVER.from, RIVER.to);
- // Rotation about +Y so the channel's local +x (its length axis) points from `from` toward
- // `to`. A +Y rotation by θ maps local +x (1,0,0) to world (cosθ, 0, -sinθ); aligning that
- // with the ground-plane direction (dx, dz) gives θ = atan2(-dz, dx).
- const dx = RIVER.to[0] - RIVER.from[0];
- const dz = RIVER.to[2] - RIVER.from[2];
- const angle = Math.atan2(-dz, dx);
- const center = [
- (RIVER.from[0] + RIVER.to[0]) / 2,
- 0,
- (RIVER.from[2] + RIVER.to[2]) / 2,
- ];
-
- // Evenly-spaced flow particles along the channel; their count scales with length so the
- // current reads continuously regardless of how far apart the districts sit. Each carries a
- // 0..1 phase offset so the component can animate them flowing along the channel.
- const particleCount = Math.max(2, Math.round(length / RIVER.particleSpacing));
- const particles = [];
- for (let i = 0; i < particleCount; i++) {
- particles.push({ index: i, phase: i / particleCount });
- }
-
- return {
- from: RIVER.from,
- to: RIVER.to,
- center,
- angle,
- length,
- width,
- widthLevel: wLevel,
- speed,
- speedLevel: sLevel,
- backlog,
- pending,
- inProgress,
- blocked,
- throughput,
- state,
- color,
- flowing: state !== 'idle' && sLevel > 0,
- particles,
- };
-}
diff --git a/client/src/utils/openWorldTaskFlowRiver.test.js b/client/src/utils/openWorldTaskFlowRiver.test.js
deleted file mode 100644
index df694f3245..0000000000
--- a/client/src/utils/openWorldTaskFlowRiver.test.js
+++ /dev/null
@@ -1,162 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import { MONUMENT } from './openWorldProductivity';
-import { TASK_QUEUE } from './openWorldTaskQueue';
-import {
- RIVER,
- widthLevel,
- speedLevel,
- recentCalendarThroughput,
- computeTaskFlowRiver,
-} from './openWorldTaskFlowRiver';
-
-describe('widthLevel', () => {
- it('maps backlog/cap into 0..1', () => {
- expect(widthLevel(6, 12)).toBe(0.5);
- expect(widthLevel(12, 12)).toBe(1);
- });
- it('clamps above the cap and reads garbage as 0', () => {
- expect(widthLevel(99, 12)).toBe(1);
- expect(widthLevel(0, 12)).toBe(0);
- expect(widthLevel(undefined, 12)).toBe(0);
- expect(widthLevel(-3, 12)).toBe(0);
- });
-});
-
-describe('speedLevel', () => {
- it('maps throughput/cap into 0..1', () => {
- expect(speedLevel(5, 10)).toBe(0.5);
- expect(speedLevel(10, 10)).toBe(1);
- });
- it('clamps above the cap and reads garbage as 0', () => {
- expect(speedLevel(50, 10)).toBe(1);
- expect(speedLevel(undefined, 10)).toBe(0);
- expect(speedLevel('5', 10)).toBe(0);
- });
-});
-
-describe('computeTaskFlowRiver', () => {
- it('connects the warehouse to the monument', () => {
- const vm = computeTaskFlowRiver({ pending: 0 }, 0);
- expect(vm.from).toEqual(TASK_QUEUE.position);
- expect(vm.to).toEqual(MONUMENT.position);
- // Center is the midpoint of the two endpoints.
- expect(vm.center[0]).toBeCloseTo((TASK_QUEUE.position[0] + MONUMENT.position[0]) / 2);
- expect(vm.center[2]).toBeCloseTo((TASK_QUEUE.position[2] + MONUMENT.position[2]) / 2);
- // Length is the ground-plane distance between them.
- const dx = MONUMENT.position[0] - TASK_QUEUE.position[0];
- const dz = MONUMENT.position[2] - TASK_QUEUE.position[2];
- expect(vm.length).toBeCloseTo(Math.sqrt(dx * dx + dz * dz));
- });
-
- it('yaws so the channel local +x points from warehouse to monument', () => {
- const vm = computeTaskFlowRiver({ pending: 0 }, 0);
- // A +Y rotation by `angle` maps local +x (1,0,0) to world (cos, 0, -sin); that vector,
- // scaled by length, must reconstruct the warehouse→monument displacement.
- const dirX = Math.cos(vm.angle) * vm.length;
- const dirZ = -Math.sin(vm.angle) * vm.length;
- expect(dirX).toBeCloseTo(MONUMENT.position[0] - TASK_QUEUE.position[0]);
- expect(dirZ).toBeCloseTo(MONUMENT.position[2] - TASK_QUEUE.position[2]);
- });
-
- it('widens with backlog and quickens with throughput', () => {
- const empty = computeTaskFlowRiver({ pending: 0, inProgress: 0, blocked: 0 }, 0);
- const busy = computeTaskFlowRiver({ pending: 8, inProgress: 4, blocked: 0 }, 10);
- expect(busy.width).toBeGreaterThan(empty.width);
- expect(busy.speed).toBeGreaterThan(empty.speed);
- expect(busy.backlog).toBe(12);
- expect(busy.widthLevel).toBe(1); // 12 >= backlogCap
- expect(busy.speedLevel).toBe(1); // 10 >= throughputCap
- expect(busy.width).toBeCloseTo(RIVER.maxWidth);
- expect(busy.speed).toBeCloseTo(RIVER.maxSpeed);
- });
-
- it('floors width/speed for an empty, still channel', () => {
- const vm = computeTaskFlowRiver({ pending: 0 }, 0);
- expect(vm.width).toBeCloseTo(RIVER.minWidth);
- expect(vm.speed).toBeCloseTo(RIVER.minSpeed);
- expect(vm.flowing).toBe(false);
- expect(vm.state).toBe('idle');
- expect(vm.color).toBe('#475569');
- });
-
- it('colors by dominant queue state', () => {
- expect(computeTaskFlowRiver({ blocked: 1 }, 1).state).toBe('blocked');
- expect(computeTaskFlowRiver({ blocked: 1 }, 1).color).toBe('#f59e0b');
- expect(computeTaskFlowRiver({ inProgress: 2 }, 3).state).toBe('active');
- expect(computeTaskFlowRiver({ inProgress: 2 }, 3).color).toBe('#22c55e');
- expect(computeTaskFlowRiver({ pending: 2 }, 0).state).toBe('queued');
- expect(computeTaskFlowRiver({ pending: 2 }, 0).color).toBe('#3b82f6');
- });
-
- it('flows only when there is throughput and a non-idle state', () => {
- expect(computeTaskFlowRiver({ inProgress: 1 }, 4).flowing).toBe(true);
- // backlog present but nothing draining → not flowing
- expect(computeTaskFlowRiver({ pending: 5 }, 0).flowing).toBe(false);
- });
-
- it('emits evenly-phased particles scaled to channel length', () => {
- const vm = computeTaskFlowRiver({ pending: 3 }, 2);
- expect(vm.particles.length).toBeGreaterThanOrEqual(2);
- expect(vm.particles[0].phase).toBe(0);
- expect(vm.particles.every((p, i) => p.index === i)).toBe(true);
- expect(vm.particles.every((p) => p.phase >= 0 && p.phase < 1)).toBe(true);
- });
-
-});
-
-describe('recentCalendarThroughput', () => {
- const cal = (taskRows) => ({
- weeks: taskRows.map((row) =>
- row.map((tasks, dow) => ({ date: `d${dow}`, dayOfWeek: dow, tasks, isFuture: false }))
- ),
- summary: { totalTasks: taskRows.flat().reduce((s, t) => s + t, 0) },
- });
-
- it('sums only the most recent N days, excluding future days', () => {
- // 14 days total (two weeks); last 7 days carry 1+2+3 = 6 tasks.
- const data = cal([
- [5, 5, 5, 5, 5, 5, 5],
- [0, 0, 0, 0, 1, 2, 3],
- ]);
- expect(recentCalendarThroughput(data, 7)).toBe(6);
- });
-
- it('windows away the 12-week-total saturation problem', () => {
- // A big historical total but a quiet recent week reads as low, not pinned high.
- const busyWeeks = Array.from({ length: 12 }, () => [9, 9, 9, 9, 9, 9, 9]);
- busyWeeks.push([0, 0, 0, 0, 0, 0, 0]); // quiet current week
- const data = cal(busyWeeks);
- expect(data.summary.totalTasks).toBe(12 * 7 * 9); // huge historical total
- expect(recentCalendarThroughput(data, 7)).toBe(0); // but the recent window is quiet
- });
-
- it('skips future days in the trailing window', () => {
- const data = cal([[1, 1, 1, 1, 1, 1, 1]]);
- data.weeks[0][5].isFuture = true;
- data.weeks[0][6].isFuture = true;
- expect(recentCalendarThroughput(data, 7)).toBe(5);
- });
-
- it('returns null for a missing/empty calendar so the caller can fall back', () => {
- expect(recentCalendarThroughput(null)).toBeNull();
- expect(recentCalendarThroughput({})).toBeNull();
- expect(recentCalendarThroughput({ weeks: [] })).toBeNull();
- expect(recentCalendarThroughput({ weeks: 'oops' })).toBeNull();
- });
-});
-
-describe('computeTaskFlowRiver — idle resilience', () => {
- it('handles missing / non-object inputs as an idle trickle without crashing', () => {
- for (const badQueue of [null, undefined, 'nope', 42, []]) {
- for (const badThroughput of [null, undefined, 'nope', -5, NaN]) {
- const vm = computeTaskFlowRiver(badQueue, badThroughput);
- expect(vm.state).toBe('idle');
- expect(vm.backlog).toBe(0);
- expect(vm.throughput).toBe(0);
- expect(vm.width).toBeCloseTo(RIVER.minWidth);
- expect(vm.from).toEqual(TASK_QUEUE.position);
- }
- }
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldTaskQueue.js b/client/src/utils/openWorldTaskQueue.js
deleted file mode 100644
index 1f696228ac..0000000000
--- a/client/src/utils/openWorldTaskQueue.js
+++ /dev/null
@@ -1,78 +0,0 @@
-// Pure, deterministic helpers for OpenWorld's CoS task-queue silhouette (roadmap 2.2):
-// a warehouse east of downtown whose stacked crates track the depth of the Chief-of-
-// Staff task queue. Crates accumulate as tasks queue up and clear as they complete; an
-// in-progress task lights the warehouse, a blocked task tints it amber. No three.js /
-// React imports so the topology is unit-testable (mirrors openWorldBackupVault.js).
-
-import { tallyByKey } from './openWorldDistrictLayout';
-import { PARCELS } from './openWorldPlan';
-
-export const TASK_QUEUE = {
- position: PARCELS.taskQueue.anchor, // east of the building grid, mirroring the backup vault to the west
- maxCrates: 8, // visible-crate cap; beyond this the warehouse reads as "overflow"
- crateSize: 1.5,
- crateGap: 0.18,
- warehouseWidth: 6,
- warehouseHeight: 4,
-};
-
-// Warehouse lighting color per queue "mood". Reuses the PortOS Tailwind tokens so the
-// silhouette speaks the same visual language as the rest of the UI.
-const STATE_COLORS = {
- idle: '#475569', // slate — empty queue, nothing waiting
- queued: '#3b82f6', // port-accent — pending work piling up
- active: '#22c55e', // port-success — an agent is working a task
- blocked: '#f59e0b', // port-warning — a task needs attention
-};
-
-// Tally CoS tasks by status. Tolerates a missing/non-array input (returns all-zero) and
-// buckets unrecognized statuses under `other` so the counts always sum to the input length.
-const KNOWN_TASK_STATUSES = ['pending', 'in_progress', 'blocked', 'completed'];
-const taskStatusKey = (t) => (KNOWN_TASK_STATUSES.includes(t?.status) ? t.status : 'other');
-export function countByStatus(tasks) {
- return tallyByKey(tasks, taskStatusKey, [...KNOWN_TASK_STATUSES, 'other']);
-}
-
-// Overall queue mood for the warehouse lighting, in priority order: a blocked task is the
-// loudest signal, then active work, then a non-empty backlog, then idle.
-export function queueState(counts) {
- if (counts?.blocked > 0) return 'blocked';
- if (counts?.in_progress > 0) return 'active';
- if (counts?.pending > 0) return 'queued';
- return 'idle';
-}
-
-export function queueColor(state) {
- return STATE_COLORS[state] || STATE_COLORS.idle;
-}
-
-// Full derived view-model for the component: counts + warehouse state/color + a crate
-// layout. The crate stack height tracks pending (queued) work — the depth of the queue —
-// capped at maxCrates with an `overflow` flag when more is waiting than crates shown.
-export function computeTaskQueue(tasks, opts = {}) {
- const maxCrates = opts.maxCrates ?? TASK_QUEUE.maxCrates;
- const counts = countByStatus(tasks);
- const state = queueState(counts);
- const crateCount = Math.min(counts.pending, maxCrates);
- const crates = [];
- for (let i = 0; i < crateCount; i++) {
- crates.push({
- index: i,
- y: TASK_QUEUE.crateSize / 2 + i * (TASK_QUEUE.crateSize + TASK_QUEUE.crateGap),
- });
- }
- return {
- position: TASK_QUEUE.position,
- pending: counts.pending,
- inProgress: counts.in_progress,
- blocked: counts.blocked,
- total: counts.pending + counts.in_progress + counts.blocked,
- state,
- color: queueColor(state),
- crateCount,
- crates,
- overflow: counts.pending > maxCrates,
- active: counts.in_progress > 0,
- hasBlocked: counts.blocked > 0,
- };
-}
diff --git a/client/src/utils/openWorldTaskQueue.test.js b/client/src/utils/openWorldTaskQueue.test.js
deleted file mode 100644
index fbef367485..0000000000
--- a/client/src/utils/openWorldTaskQueue.test.js
+++ /dev/null
@@ -1,128 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- TASK_QUEUE,
- countByStatus,
- queueState,
- queueColor,
- computeTaskQueue,
-} from './openWorldTaskQueue';
-
-const tasks = (...statuses) => statuses.map((status, i) => ({ id: `t${i}`, status }));
-
-describe('countByStatus', () => {
- it('tallies each status and buckets unknowns under other', () => {
- const c = countByStatus(tasks('pending', 'pending', 'in_progress', 'blocked', 'completed', 'weird'));
- expect(c).toEqual({ pending: 2, in_progress: 1, blocked: 1, completed: 1, other: 1 });
- });
-
- it('returns all-zero for missing / non-array input', () => {
- const zero = { pending: 0, in_progress: 0, blocked: 0, completed: 0, other: 0 };
- expect(countByStatus(undefined)).toEqual(zero);
- expect(countByStatus(null)).toEqual(zero);
- expect(countByStatus('nope')).toEqual(zero);
- expect(countByStatus([])).toEqual(zero);
- });
-
- it('counts always sum to the input length', () => {
- const list = tasks('pending', 'in_progress', 'blocked', 'completed', 'other', 'pending');
- const c = countByStatus(list);
- const sum = c.pending + c.in_progress + c.blocked + c.completed + c.other;
- expect(sum).toBe(list.length);
- });
-});
-
-describe('queueState', () => {
- it('prioritizes blocked > active > queued > idle', () => {
- expect(queueState({ blocked: 1, in_progress: 3, pending: 5 })).toBe('blocked');
- expect(queueState({ blocked: 0, in_progress: 2, pending: 5 })).toBe('active');
- expect(queueState({ blocked: 0, in_progress: 0, pending: 5 })).toBe('queued');
- expect(queueState({ blocked: 0, in_progress: 0, pending: 0 })).toBe('idle');
- });
-
- it('treats missing counts as idle', () => {
- expect(queueState(undefined)).toBe('idle');
- expect(queueState({})).toBe('idle');
- });
-});
-
-describe('queueColor', () => {
- it('maps each state to a distinct token', () => {
- expect(queueColor('idle')).toBe('#475569');
- expect(queueColor('queued')).toBe('#3b82f6');
- expect(queueColor('active')).toBe('#22c55e');
- expect(queueColor('blocked')).toBe('#f59e0b');
- });
-
- it('falls back to idle for an unknown state', () => {
- expect(queueColor('bogus')).toBe(queueColor('idle'));
- });
-});
-
-describe('computeTaskQueue', () => {
- it('carries the fixed position through unchanged', () => {
- expect(computeTaskQueue([]).position).toEqual(TASK_QUEUE.position);
- });
-
- it('an empty queue is idle with no crates', () => {
- const vm = computeTaskQueue([]);
- expect(vm.state).toBe('idle');
- expect(vm.crateCount).toBe(0);
- expect(vm.crates).toEqual([]);
- expect(vm.overflow).toBe(false);
- expect(vm.total).toBe(0);
- });
-
- it('stacks one crate per pending task', () => {
- const vm = computeTaskQueue(tasks('pending', 'pending', 'pending'));
- expect(vm.pending).toBe(3);
- expect(vm.crateCount).toBe(3);
- expect(vm.crates).toHaveLength(3);
- expect(vm.state).toBe('queued');
- expect(vm.overflow).toBe(false);
- });
-
- it('stacks crates upward with increasing y', () => {
- const vm = computeTaskQueue(tasks('pending', 'pending'));
- expect(vm.crates[0].y).toBeLessThan(vm.crates[1].y);
- expect(vm.crates[0].y).toBeCloseTo(TASK_QUEUE.crateSize / 2);
- });
-
- it('caps crate count at maxCrates and flags overflow', () => {
- const many = tasks(...Array(TASK_QUEUE.maxCrates + 4).fill('pending'));
- const vm = computeTaskQueue(many);
- expect(vm.pending).toBe(TASK_QUEUE.maxCrates + 4);
- expect(vm.crateCount).toBe(TASK_QUEUE.maxCrates);
- expect(vm.overflow).toBe(true);
- });
-
- it('honors a custom maxCrates', () => {
- const vm = computeTaskQueue(tasks('pending', 'pending', 'pending'), { maxCrates: 2 });
- expect(vm.crateCount).toBe(2);
- expect(vm.overflow).toBe(true);
- });
-
- it('lights active when an agent is working, even with pending backlog', () => {
- const vm = computeTaskQueue(tasks('pending', 'pending', 'in_progress'));
- expect(vm.state).toBe('active');
- expect(vm.active).toBe(true);
- expect(vm.color).toBe('#22c55e');
- // crate stack still reflects the pending backlog, independent of the lighting
- expect(vm.crateCount).toBe(2);
- });
-
- it('tints blocked when any task needs attention, overriding active', () => {
- const vm = computeTaskQueue(tasks('pending', 'in_progress', 'blocked'));
- expect(vm.state).toBe('blocked');
- expect(vm.hasBlocked).toBe(true);
- expect(vm.color).toBe('#f59e0b');
- expect(vm.total).toBe(3);
- });
-
- it('ignores completed tasks for stacking and totals', () => {
- const vm = computeTaskQueue(tasks('completed', 'completed', 'pending'));
- expect(vm.crateCount).toBe(1);
- expect(vm.total).toBe(1);
- expect(vm.state).toBe('queued');
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldTimeline.js b/client/src/utils/openWorldTimeline.js
deleted file mode 100644
index 7c9fc65b25..0000000000
--- a/client/src/utils/openWorldTimeline.js
+++ /dev/null
@@ -1,113 +0,0 @@
-// Pure helpers for OpenWorld's recent-action timeline overlay.
-//
-// The Intel pane's ACTIVITY tab shows a flat, newest-at-bottom log; the
-// TIMELINE tab instead conveys *cadence* — when bursts of activity happened
-// versus quiet stretches — by binning recent events into a density sparkbar
-// and grouping them into relative-age buckets. Both transforms are pure so
-// they can be unit-tested without a DOM (mirrors openWorldFilter.js).
-
-// Default cap on events the timeline considers, so a runaway log can't blow
-// up the render. `now` is injectable into both transforms for deterministic tests.
-const MAX_TIMELINE_EVENTS = 40;
-
-// Append a socket burst to the HUD's bounded activity buffer in one immutable
-// update. The data hook batches raw cos:log frames before calling this helper so
-// a chatty agent costs one React render per short window, without dropping any
-// entries from the burst.
-export function appendEventLogBatch(previous, incoming, max = 50) {
- const combined = [...(previous || []), ...(incoming || [])];
- return combined.length > max ? combined.slice(-max) : combined;
-}
-
-// Lower-case so lookups against the lower-cased color maps in OpenWorldIntelPane
-// stay robust; the cos:log stream only emits info/warn/error/success/debug, so
-// unknown values just fall through to the maps' info default (same as the
-// sibling ACTIVITY tab).
-const normalizeLevel = (level) => (level || 'info').toLowerCase();
-
-const eventTime = (log) => {
- const t = new Date(log?.timestamp ?? NaN).getTime();
- return Number.isFinite(t) ? t : null;
-};
-
-/**
- * Bin recent events into evenly-spaced time slots for a density sparkbar.
- * Returns one entry per bin, oldest-first, each `{ count, level }` where
- * `level` is the highest-severity event in that bin (drives the bar color).
- *
- * @param {Array} logs - raw event log entries (`{ timestamp, level }`)
- * @param {object} opts
- * @param {number} opts.now - reference "now" epoch ms (injectable for tests)
- * @param {number} [opts.windowMs] - how far back the bar spans (default 10m)
- * @param {number} [opts.bins] - number of bars (default 24)
- * @returns {Array<{count:number, level:string|null}>}
- */
-export function computeActivityDensity(logs, { now, windowMs = 10 * 60 * 1000, bins = 24 } = {}) {
- const slotMs = windowMs / bins;
- const slots = Array.from({ length: bins }, () => ({ count: 0, level: null }));
-
- const severityRank = { error: 3, warn: 2, success: 1, info: 0, debug: 0 };
-
- (logs || []).forEach(log => {
- const t = eventTime(log);
- if (t == null) return;
- const ageMs = now - t;
- if (ageMs < 0 || ageMs >= windowMs) return; // outside the visible window
- // Oldest events land in bin 0, newest in the last bin.
- const idx = Math.min(bins - 1, Math.floor((windowMs - ageMs) / slotMs));
- const slot = slots[idx];
- slot.count += 1;
- const lvl = normalizeLevel(log.level);
- if (slot.level == null || (severityRank[lvl] ?? 0) > (severityRank[slot.level] ?? 0)) {
- slot.level = lvl;
- }
- });
-
- return slots;
-}
-
-// Relative-age buckets, newest first. Each event falls into the first bucket
-// whose `maxAgeMs` it does not exceed; the final bucket is open-ended.
-const BUCKET_DEFS = [
- { id: 'now', label: 'JUST NOW', maxAgeMs: 60 * 1000 },
- { id: 'recent', label: 'LAST 5 MIN', maxAgeMs: 5 * 60 * 1000 },
- { id: 'quarter', label: 'LAST 15 MIN', maxAgeMs: 15 * 60 * 1000 },
- { id: 'older', label: 'EARLIER', maxAgeMs: Infinity },
-];
-
-/**
- * Group recent events into relative-age buckets, newest event first within
- * each bucket. Empty buckets are dropped. Each event carries its normalized
- * level and ms-age so the renderer can show "2m ago" without re-parsing.
- *
- * @param {Array} logs - raw event log entries
- * @param {object} opts
- * @param {number} opts.now - reference "now" epoch ms (injectable for tests)
- * @param {number} [opts.max] - cap on total events considered (default 40)
- * @returns {Array<{id:string, label:string, events:Array}>}
- */
-export function buildTimelineBuckets(logs, { now, max = MAX_TIMELINE_EVENTS } = {}) {
- const dated = (logs || [])
- .map(log => {
- const t = eventTime(log);
- if (t == null) return null;
- return {
- id: log._localId ?? `${log.timestamp}-${log.message || log.event || ''}`,
- ageMs: now - t,
- timestamp: t,
- level: normalizeLevel(log.level),
- message: log.message || log.event || '',
- };
- })
- .filter(e => e && e.ageMs >= 0)
- .sort((a, b) => b.timestamp - a.timestamp) // newest first
- .slice(0, max);
-
- const buckets = BUCKET_DEFS.map(def => ({ id: def.id, label: def.label, events: [] }));
- dated.forEach(event => {
- const idx = BUCKET_DEFS.findIndex(def => event.ageMs < def.maxAgeMs);
- buckets[idx === -1 ? buckets.length - 1 : idx].events.push(event);
- });
-
- return buckets.filter(b => b.events.length > 0);
-}
diff --git a/client/src/utils/openWorldTimeline.test.js b/client/src/utils/openWorldTimeline.test.js
deleted file mode 100644
index 0282f6fefa..0000000000
--- a/client/src/utils/openWorldTimeline.test.js
+++ /dev/null
@@ -1,132 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import { appendEventLogBatch, computeActivityDensity, buildTimelineBuckets } from './openWorldTimeline';
-
-// Fixed reference "now" so the relative-age math is deterministic.
-const NOW = 1_700_000_000_000;
-const minsAgo = (m) => NOW - m * 60 * 1000;
-const secsAgo = (s) => NOW - s * 1000;
-
-describe('appendEventLogBatch', () => {
- it('preserves every event in a socket burst and caps the oldest entries', () => {
- const previous = [{ _localId: 1 }, { _localId: 2 }];
- const incoming = [{ _localId: 3 }, { _localId: 4 }, { _localId: 5 }];
-
- expect(appendEventLogBatch(previous, incoming, 4).map((event) => event._localId))
- .toEqual([2, 3, 4, 5]);
- expect(previous).toHaveLength(2);
- expect(incoming).toHaveLength(3);
- });
-});
-
-describe('computeActivityDensity', () => {
- it('returns one empty slot per bin', () => {
- const slots = computeActivityDensity([], { now: NOW, bins: 24 });
- expect(slots).toHaveLength(24);
- expect(slots.every(s => s.count === 0 && s.level === null)).toBe(true);
- });
-
- it('bins recent events into the correct slot and counts them', () => {
- const logs = [
- { timestamp: secsAgo(5), level: 'info' }, // newest → last bin
- { timestamp: secsAgo(6), level: 'info' },
- { timestamp: minsAgo(9.9), level: 'info' }, // oldest → bin 0
- ];
- const slots = computeActivityDensity(logs, { now: NOW, windowMs: 10 * 60 * 1000, bins: 24 });
- expect(slots[slots.length - 1].count).toBe(2);
- expect(slots[0].count).toBe(1);
- });
-
- it('drops events outside the window', () => {
- const logs = [
- { timestamp: minsAgo(20), level: 'info' }, // older than 10m window
- { timestamp: NOW + 5000, level: 'info' }, // future
- ];
- const slots = computeActivityDensity(logs, { now: NOW, windowMs: 10 * 60 * 1000, bins: 24 });
- expect(slots.reduce((n, s) => n + s.count, 0)).toBe(0);
- });
-
- it('keeps the highest-severity level per bin', () => {
- const logs = [
- { timestamp: secsAgo(5), level: 'info' },
- { timestamp: secsAgo(6), level: 'error' },
- { timestamp: secsAgo(7), level: 'warn' },
- ];
- const slots = computeActivityDensity(logs, { now: NOW, windowMs: 60 * 1000, bins: 1 });
- expect(slots[0].count).toBe(3);
- expect(slots[0].level).toBe('error');
- });
-
- it('ignores entries with an unparseable timestamp', () => {
- const slots = computeActivityDensity(
- [{ timestamp: 'not-a-date', level: 'info' }, { level: 'info' }],
- { now: NOW },
- );
- expect(slots.reduce((n, s) => n + s.count, 0)).toBe(0);
- });
-});
-
-describe('buildTimelineBuckets', () => {
- it('groups events into relative-age buckets, newest first', () => {
- const logs = [
- { _localId: 1, timestamp: secsAgo(10), level: 'info', message: 'now-ish' },
- { _localId: 2, timestamp: minsAgo(3), level: 'warn', message: 'recent' },
- { _localId: 3, timestamp: minsAgo(12), level: 'error', message: 'quarter' },
- { _localId: 4, timestamp: minsAgo(40), level: 'info', message: 'older' },
- ];
- const buckets = buildTimelineBuckets(logs, { now: NOW });
- expect(buckets.map(b => b.id)).toEqual(['now', 'recent', 'quarter', 'older']);
- expect(buckets[0].events[0].message).toBe('now-ish');
- expect(buckets[2].events[0].level).toBe('error');
- });
-
- it('drops empty buckets', () => {
- const logs = [{ _localId: 1, timestamp: secsAgo(5), level: 'info', message: 'just happened' }];
- const buckets = buildTimelineBuckets(logs, { now: NOW });
- expect(buckets).toHaveLength(1);
- expect(buckets[0].id).toBe('now');
- });
-
- it('orders events newest-first within a bucket', () => {
- const logs = [
- { _localId: 1, timestamp: minsAgo(4), level: 'info', message: 'first' },
- { _localId: 2, timestamp: minsAgo(2), level: 'info', message: 'second' },
- ];
- const buckets = buildTimelineBuckets(logs, { now: NOW });
- expect(buckets[0].events.map(e => e.message)).toEqual(['second', 'first']);
- });
-
- it('caps total events at `max`', () => {
- const logs = Array.from({ length: 100 }, (_, i) => ({
- _localId: i,
- timestamp: secsAgo(i),
- level: 'info',
- message: `e${i}`,
- }));
- const buckets = buildTimelineBuckets(logs, { now: NOW, max: 10 });
- const total = buckets.reduce((n, b) => n + b.events.length, 0);
- expect(total).toBe(10);
- });
-
- it('lower-cases the level and defaults a missing one to info', () => {
- const logs = [
- { _localId: 1, timestamp: secsAgo(1), level: 'WARN', message: 'w' },
- { _localId: 2, timestamp: secsAgo(2), message: 'no-level' },
- ];
- const buckets = buildTimelineBuckets(logs, { now: NOW });
- const levels = buckets.flatMap(b => b.events.map(e => e.level));
- expect(levels).toContain('warn');
- expect(levels).toContain('info');
- });
-
- it('skips events with future or invalid timestamps', () => {
- const logs = [
- { _localId: 1, timestamp: NOW + 60000, level: 'info', message: 'future' },
- { _localId: 2, timestamp: 'nope', level: 'info', message: 'bad' },
- { _localId: 3, timestamp: secsAgo(5), level: 'info', message: 'good' },
- ];
- const buckets = buildTimelineBuckets(logs, { now: NOW });
- const msgs = buckets.flatMap(b => b.events.map(e => e.message));
- expect(msgs).toEqual(['good']);
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldVoiceMarker.js b/client/src/utils/openWorldVoiceMarker.js
deleted file mode 100644
index a92abe92ae..0000000000
--- a/client/src/utils/openWorldVoiceMarker.js
+++ /dev/null
@@ -1,95 +0,0 @@
-// Pure, deterministic helpers for OpenWorld's voice-agent district marker (roadmap 2.4):
-// a small ground-level beacon north of downtown whose lighting mirrors the voice agent's
-// live state — calm slate when idle, accent blue while listening, green while dictating,
-// red on error, and dimmed when voice mode is disabled. The live state is socket-driven
-// (`voice:idle` / `voice:dictation` / `voice:error`); the `enabled` flag comes from the
-// persisted /voice/status payload. No three.js / React imports so the topology is
-// unit-testable (mirrors openWorldBackupVault.js).
-
-import { PARCELS } from './openWorldPlan';
-
-export const MARKER = {
- position: PARCELS.voice.anchor, // north of downtown, stepped just off the harbor avenue's
- // centerline so the plaza→harbor walkway runs clear past the beacon (see openWorldPlan.js).
- baseRadius: 2.2,
- poleHeight: 6,
- beaconRadius: 0.9,
-};
-
-// Beacon color per voice state — reuses the PortOS Tailwind design tokens so the marker
-// speaks the same visual language as the rest of the UI.
-const STATE_COLORS = {
- idle: '#475569', // slate — voice mode on, nothing happening
- listening: '#3b82f6', // port-accent — capturing a turn
- dictating: '#22c55e', // port-success — dictation appending to the daily log
- error: '#ef4444', // port-error — a turn failed
- disabled: '#1e293b', // dim slate — voice mode off
-};
-
-const STATE_LABELS = {
- idle: 'STANDBY',
- listening: 'LISTENING',
- dictating: 'DICTATING',
- error: 'VOICE ERROR',
- disabled: 'VOICE OFF',
-};
-
-// Emissive intensity per state — the marker glows brightest while actively working
-// (listening / dictating), throbs on error, sits calm when idle, and barely lights when
-// disabled so it reads as "asleep" without disappearing.
-const STATE_INTENSITY = {
- idle: 0.45,
- listening: 1,
- dictating: 1,
- error: 0.9,
- disabled: 0.12,
-};
-
-const VALID_STATES = new Set(['idle', 'listening', 'dictating', 'error', 'disabled']);
-
-// Derive the marker's live state from the voice view payload. `enabled` is the persisted
-// flag; `live` is the latest socket-driven sub-state (idle | listening | dictating | error).
-// Voice mode is treated as off unless `enabled === true` — an absent flag (status fetch
-// failed / voice never configured) reads as `disabled`, never as a live "on" state. A stale
-// live value is ignored while disabled. An unrecognized live value falls back to `idle`.
-export function markerState(voice) {
- if (!voice || voice.enabled !== true) return 'disabled';
- const live = voice.live;
- if (live === 'error') return 'error';
- if (live === 'dictating') return 'dictating';
- if (live === 'listening') return 'listening';
- return 'idle';
-}
-
-export function markerColor(state) {
- return STATE_COLORS[VALID_STATES.has(state) ? state : 'idle'] || STATE_COLORS.idle;
-}
-
-export function markerLabel(state) {
- return STATE_LABELS[VALID_STATES.has(state) ? state : 'idle'] || STATE_LABELS.idle;
-}
-
-// Should the beacon pulse urgently (error) vs. calmly? Listening/dictating get an active
-// pulse; idle breathes slowly; disabled doesn't animate.
-export function markerIsActive(state) {
- return state === 'listening' || state === 'dictating';
-}
-
-// Full derived view-model for the component: position + state + color + label + flags +
-// emissive intensity. Mirrors computeBackupVault's shape so the component layer stays thin.
-export function computeVoiceMarker(voice) {
- const state = markerState(voice);
- return {
- position: MARKER.position,
- baseRadius: MARKER.baseRadius,
- poleHeight: MARKER.poleHeight,
- beaconRadius: MARKER.beaconRadius,
- state,
- color: markerColor(state),
- label: markerLabel(state),
- active: markerIsActive(state),
- alerting: state === 'error',
- disabled: state === 'disabled',
- intensity: STATE_INTENSITY[state] ?? STATE_INTENSITY.idle,
- };
-}
diff --git a/client/src/utils/openWorldVoiceMarker.test.js b/client/src/utils/openWorldVoiceMarker.test.js
deleted file mode 100644
index 42dbcb6409..0000000000
--- a/client/src/utils/openWorldVoiceMarker.test.js
+++ /dev/null
@@ -1,120 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- MARKER,
- markerState,
- markerColor,
- markerLabel,
- markerIsActive,
- computeVoiceMarker,
-} from './openWorldVoiceMarker';
-
-describe('markerState', () => {
- it('is disabled when voice mode is off, regardless of a stale live value', () => {
- expect(markerState({ enabled: false })).toBe('disabled');
- expect(markerState({ enabled: false, live: 'listening' })).toBe('disabled');
- });
-
- it('is disabled for missing / empty input', () => {
- expect(markerState(undefined)).toBe('disabled');
- expect(markerState(null)).toBe('disabled');
- expect(markerState({})).toBe('disabled'); // enabled absent → treated as off
- });
-
- it('maps each live sub-state when voice mode is enabled', () => {
- expect(markerState({ enabled: true, live: 'error' })).toBe('error');
- expect(markerState({ enabled: true, live: 'dictating' })).toBe('dictating');
- expect(markerState({ enabled: true, live: 'listening' })).toBe('listening');
- expect(markerState({ enabled: true, live: 'idle' })).toBe('idle');
- });
-
- it('falls back to idle for an absent / unrecognized live value when enabled', () => {
- expect(markerState({ enabled: true })).toBe('idle');
- expect(markerState({ enabled: true, live: 'bogus' })).toBe('idle');
- });
-
- it('prioritizes error over other live states', () => {
- // The live field carries one sub-state, but guard the precedence contract anyway.
- expect(markerState({ enabled: true, live: 'error' })).toBe('error');
- });
-});
-
-describe('markerColor', () => {
- it('maps each state to a distinct token', () => {
- expect(markerColor('idle')).toBe('#475569');
- expect(markerColor('listening')).toBe('#3b82f6');
- expect(markerColor('dictating')).toBe('#22c55e');
- expect(markerColor('error')).toBe('#ef4444');
- expect(markerColor('disabled')).toBe('#1e293b');
- });
-
- it('falls back to idle for an unknown state', () => {
- expect(markerColor('bogus')).toBe(markerColor('idle'));
- });
-});
-
-describe('markerLabel', () => {
- it('gives a distinct uppercase label per state', () => {
- expect(markerLabel('idle')).toBe('STANDBY');
- expect(markerLabel('listening')).toBe('LISTENING');
- expect(markerLabel('dictating')).toBe('DICTATING');
- expect(markerLabel('error')).toBe('VOICE ERROR');
- expect(markerLabel('disabled')).toBe('VOICE OFF');
- });
-
- it('falls back to the idle label for an unknown state', () => {
- expect(markerLabel('bogus')).toBe(markerLabel('idle'));
- });
-});
-
-describe('markerIsActive', () => {
- it('is active only while listening or dictating', () => {
- expect(markerIsActive('listening')).toBe(true);
- expect(markerIsActive('dictating')).toBe(true);
- expect(markerIsActive('idle')).toBe(false);
- expect(markerIsActive('error')).toBe(false);
- expect(markerIsActive('disabled')).toBe(false);
- });
-});
-
-describe('computeVoiceMarker', () => {
- it('carries the fixed position/geometry through unchanged', () => {
- const vm = computeVoiceMarker({ enabled: true });
- expect(vm.position).toEqual(MARKER.position);
- expect(vm.baseRadius).toBe(MARKER.baseRadius);
- expect(vm.poleHeight).toBe(MARKER.poleHeight);
- expect(vm.beaconRadius).toBe(MARKER.beaconRadius);
- });
-
- it('derives color/label/flags/intensity for each state', () => {
- const idle = computeVoiceMarker({ enabled: true, live: 'idle' });
- expect(idle).toMatchObject({ state: 'idle', color: '#475569', label: 'STANDBY', active: false, alerting: false, disabled: false });
- expect(idle.intensity).toBeGreaterThan(0);
-
- const listening = computeVoiceMarker({ enabled: true, live: 'listening' });
- expect(listening).toMatchObject({ state: 'listening', color: '#3b82f6', active: true, alerting: false });
-
- const dictating = computeVoiceMarker({ enabled: true, live: 'dictating' });
- expect(dictating).toMatchObject({ state: 'dictating', color: '#22c55e', active: true });
-
- const error = computeVoiceMarker({ enabled: true, live: 'error' });
- expect(error).toMatchObject({ state: 'error', color: '#ef4444', alerting: true, active: false });
-
- const disabled = computeVoiceMarker({ enabled: false });
- expect(disabled).toMatchObject({ state: 'disabled', color: '#1e293b', disabled: true, active: false });
- expect(disabled.intensity).toBeLessThan(idle.intensity);
- });
-
- it('treats missing / empty input as disabled', () => {
- expect(computeVoiceMarker(undefined).state).toBe('disabled');
- expect(computeVoiceMarker(null).state).toBe('disabled');
- expect(computeVoiceMarker({}).state).toBe('disabled');
- });
-
- it('always returns a finite emissive intensity', () => {
- for (const live of ['idle', 'listening', 'dictating', 'error', undefined, 'bogus']) {
- const vm = computeVoiceMarker({ enabled: true, live });
- expect(Number.isFinite(vm.intensity)).toBe(true);
- }
- });
-});
-// @vitest-environment node
diff --git a/client/src/utils/openWorldRenderBudget.js b/client/src/utils/renderBudget.js
similarity index 98%
rename from client/src/utils/openWorldRenderBudget.js
rename to client/src/utils/renderBudget.js
index 14201d99bd..edc2187c56 100644
--- a/client/src/utils/openWorldRenderBudget.js
+++ b/client/src/utils/renderBudget.js
@@ -1,4 +1,4 @@
-// Pure render-budget state machine for OpenWorld's Auto quality mode (issue #2592).
+// Pure render-budget state machine for adaptive quality (issue #2592).
//
// It observes per-frame delta times and decides when the *effective* detail tier
// should step down (frame pressure) or up (headroom), with hysteresis + a cooldown
@@ -20,7 +20,7 @@ export const QUALITY_TIERS = ['low', 'medium', 'high', 'ultra'];
// before Auto quality could react. Unknown desktop capabilities remain High; a coarse
// pointer or sub-8-core/sub-8GB device starts at Medium, while clearly constrained
// hardware starts at Low. The live budget can still climb when it measures headroom.
-export function recommendOpenWorldStartTier({
+export function recommendStartTier({
coarsePointer = false,
hardwareConcurrency = null,
deviceMemory = null,
@@ -104,7 +104,7 @@ export function createRenderBudget(startTier = 'high', now = 0) {
};
}
-// Re-arm the warm-up without touching the current tier — used when the OpenWorld frameloop
+// Re-arm the warm-up without touching the current tier — used when a frameloop
// resumes after the tab was hidden, so the first sluggish post-resume frames (and any
// pre-hide pressure/headroom streaks) don't drive a bogus decision.
export function restartWarmup(state, now) {
diff --git a/client/src/utils/openWorldRenderBudget.test.js b/client/src/utils/renderBudget.test.js
similarity index 88%
rename from client/src/utils/openWorldRenderBudget.test.js
rename to client/src/utils/renderBudget.test.js
index 1061f98329..709df60728 100644
--- a/client/src/utils/openWorldRenderBudget.test.js
+++ b/client/src/utils/renderBudget.test.js
@@ -8,9 +8,9 @@ import {
resetRenderBudget,
getEffectiveTier,
percentile,
- recommendOpenWorldStartTier,
+ recommendStartTier,
tierToIndex,
-} from './openWorldRenderBudget.js';
+} from './renderBudget.js';
const CFG = DEFAULT_RENDER_BUDGET_CONFIG;
@@ -39,7 +39,7 @@ function makeDriver(startTier) {
};
}
-describe('openWorldRenderBudget — helpers', () => {
+describe('renderBudget — helpers', () => {
it('percentile uses nearest-rank and handles empty input', () => {
expect(percentile([], 0.75)).toBeNull();
expect(percentile([10, 20, 30, 40], 0.75)).toBe(30);
@@ -53,21 +53,21 @@ describe('openWorldRenderBudget — helpers', () => {
});
it('starts conservatively on touch and lower-capability devices', () => {
- expect(recommendOpenWorldStartTier({ coarsePointer: true, hardwareConcurrency: 12 })).toBe('medium');
- expect(recommendOpenWorldStartTier({ hardwareConcurrency: 6 })).toBe('medium');
- expect(recommendOpenWorldStartTier({ deviceMemory: 6 })).toBe('medium');
- expect(recommendOpenWorldStartTier({ hardwareConcurrency: 2 })).toBe('low');
- expect(recommendOpenWorldStartTier({ deviceMemory: 4 })).toBe('low');
+ expect(recommendStartTier({ coarsePointer: true, hardwareConcurrency: 12 })).toBe('medium');
+ expect(recommendStartTier({ hardwareConcurrency: 6 })).toBe('medium');
+ expect(recommendStartTier({ deviceMemory: 6 })).toBe('medium');
+ expect(recommendStartTier({ hardwareConcurrency: 2 })).toBe('low');
+ expect(recommendStartTier({ deviceMemory: 4 })).toBe('low');
});
it('keeps capable and unknown desktops at high', () => {
- expect(recommendOpenWorldStartTier()).toBe('high');
- expect(recommendOpenWorldStartTier({ hardwareConcurrency: 12, deviceMemory: 16 })).toBe('high');
- expect(recommendOpenWorldStartTier({ hardwareConcurrency: 0, deviceMemory: Number.NaN })).toBe('high');
+ expect(recommendStartTier()).toBe('high');
+ expect(recommendStartTier({ hardwareConcurrency: 12, deviceMemory: 16 })).toBe('high');
+ expect(recommendStartTier({ hardwareConcurrency: 0, deviceMemory: Number.NaN })).toBe('high');
});
});
-describe('openWorldRenderBudget — warm-up & gap rejection (ignored samples)', () => {
+describe('renderBudget — warm-up & gap rejection (ignored samples)', () => {
it('ignores frames inside the warm-up window but records after it', () => {
let s = createRenderBudget('high', 0);
// Frames before warmupMs never accumulate (dt=40 would otherwise be pressure).
@@ -139,7 +139,7 @@ describe('openWorldRenderBudget — warm-up & gap rejection (ignored samples)',
});
});
-describe('openWorldRenderBudget — downshift', () => {
+describe('renderBudget — downshift', () => {
it('steps down exactly one tier after two consecutive pressure windows', () => {
const d = makeDriver('high');
d.window(30); // window 1: p75 30ms > 25ms
@@ -159,7 +159,7 @@ describe('openWorldRenderBudget — downshift', () => {
});
});
-describe('openWorldRenderBudget — recovery (upshift)', () => {
+describe('renderBudget — recovery (upshift)', () => {
it('steps up one tier after five consecutive headroom windows', () => {
const d = makeDriver('medium');
for (let w = 0; w < 4; w += 1) d.window(10); // four fast windows: not enough
@@ -178,7 +178,7 @@ describe('openWorldRenderBudget — recovery (upshift)', () => {
});
});
-describe('openWorldRenderBudget — cooldown', () => {
+describe('renderBudget — cooldown', () => {
it('blocks a second tier change until the cooldown elapses', () => {
const d = makeDriver('high');
d.window(30);
@@ -208,7 +208,7 @@ describe('openWorldRenderBudget — cooldown', () => {
});
});
-describe('openWorldRenderBudget — visibility transitions', () => {
+describe('renderBudget — visibility transitions', () => {
it('restartWarmup re-arms warm-up and clears streaks/samples without changing tier', () => {
const d = makeDriver('high');
d.window(30); // pressure streak = 1
@@ -230,7 +230,7 @@ describe('openWorldRenderBudget — visibility transitions', () => {
});
});
-describe('openWorldRenderBudget — purity', () => {
+describe('renderBudget — purity', () => {
it('recordFrame does not mutate the input state', () => {
const s = createRenderBudget('high', 0);
const before = JSON.stringify(s);
diff --git a/data.reference/settings.json b/data.reference/settings.json
index 9db31b01f0..c524f769d1 100644
--- a/data.reference/settings.json
+++ b/data.reference/settings.json
@@ -46,11 +46,6 @@
},
"vad": { "endOfSpeechMs": 700, "minUtteranceMs": 250 }
},
- "citySnapshots": {
- "enabled": true,
- "intervalMinutes": 5,
- "maxSnapshots": 1000
- },
"apiAccess": {
"voice": { "exposed": false, "requireAuth": false },
"sdapi": { "exposed": false, "requireAuth": false }
diff --git a/docs/features/openworld.md b/docs/features/openworld.md
index 45bd70c7b0..db0708626a 100644
--- a/docs/features/openworld.md
+++ b/docs/features/openworld.md
@@ -1,198 +1,7 @@
# OpenWorld
-> **Retired in favor of Eidoverse.** The implementation remains in the checkout
-> for compatibility and reference, but `/openworld` and `/city` now redirect to
-> the private, persistent Eidoverse PortOS world. New world content and PortOS
-> resource projection belong in [Eidoverse Worlds](./eidoverse.md).
+> **Retired in favor of Eidoverse.** The retired OpenWorld implementation was removed. Persistent `/openworld`, `/openworld/*`, `/city`, and `/city/*` URLs redirect to `/eidoverse` without retaining deep-path suffixes.
-The historical snapshot scheduler is no longer started at PortOS boot. Existing
-snapshot files and compatibility endpoints remain readable for older clients;
-new automatic world synchronization is owned by Eidoverse's page-open refresh
-and optional install-local projection job.
+Existing `data/city-snapshots.jsonl` files remain untouched and inert. Eidoverse is the canonical optional 3D surface.
-> **Historical rename (2026-08-19).** This surface shipped as *CyberCity* at `/city`.
-> It was renamed **OpenWorld** at `/openworld`; the `/city` routes redirected so existing bookmarks,
-> pinned rows, palette history, and peer deep links keep working. Persisted nav-command
-> ids remain unchanged.
-
-## Vision
-
-OpenWorld is a playable, spatial interpretation of PortOS: a small world whose places
-are shaped by the systems, memories, goals, apps, and agents inside an install. It is
-not a 3D dashboard with ornamental streets. The world should be enjoyable to cross even
-before the player reads a number.
-
-The design has four priorities, in this order:
-
-1. **A memorable place.** Water, silhouettes, terrain color, and landmarks make each
- part of the world recognizable before labels do.
-2. **A satisfying traversal loop.** Arrive through the village gate, follow curving
- lanes, recover Echo Shards, and stop at cottages that open real PortOS places.
-3. **PortOS made physical.** Live app and system state changes structures and motion,
- but never replaces the authored geography.
-4. **A useful route back into the product.** Buildings, destinations, search, and URL
- deep links remain direct paths into canonical PortOS surfaces.
-
-## PortOS Village
-
-Street-level OpenWorld is a compact, continuous valley rather than a systems diagram spread
-across a flat plane. Its named neighborhoods remain useful for the map and deep links, but
-the player experiences them as parts of one village:
-
-- **The Common** — a circular gathering place around the kinetic AI Core.
-- **Memory Wilds** — the Memory House and Backup Cottage among denser trees.
-- **Maker Reach** — the Task Workshop, Goals Lodge, and Trophy House.
-- **Data Pier** — the waterfront cottage for database tables and data domains.
-- **Focus Gardens** — crops, productivity, quiet discoveries, and activity terrain.
-- **Wellness Grove** — the Wellness Greenhouse and personal-health destinations.
-
-`client/src/utils/openWorldPlan.js` is the geography contract. Its curved lanes, terrain
-height function, cottage footprints, region anchors, and walkability rules are shared by
-rendering, player grounding, collision, camera avoidance, suspension, and map views.
-
-The valley uses a deterministic irregular outline, rolling low-poly terrain, dense instanced
-broadleaf trees, grass, flowers, rocks, crops, benches, lanterns, a pond, and a harbor. The
-sea remains one inexpensive procedural surface outside the village shelf.
-
-Live PortOS state is woven into this authored setting rather than displayed as a detached
-dashboard. Active managed apps occupy small status-lit market kiosks around the Common;
-nearby app interaction opens the same focused app route used elsewhere in PortOS. Cottage
-plaques show their place name and a compact live metric, while memories grow a grove, tasks
-stack as workshop cargo, goals raise flags, and backup, health, voice, trophy, and data state
-alter their corresponding landmarks. Archived apps remain summarized at Archive Lodge so
-the active market stays legible.
-
-## The Village Run
-
-Street-level exploration is the game layer:
-
-1. The utility rover enters through the authored PortOS Village gate. App count never
- moves the starting line or blocks the arrival view.
-2. A broad heart loop and short destination lanes keep a cottage, garden, pond, or landmark
- entering the frame every few seconds without floating horizon labels.
-3. Echo Shards reward exploring the whole valley. Collection has audiovisual feedback and
- session persistence.
-4. Landmark proximity offers one clear action with `F`: visit the visible nearby cottage
- or place. Invisible street-level warp triggers are not used.
-5. `M` opens the Village Map. A destination warp is shareable via
- `/openworld/region/:regionId`, and dropping back to street level lands at that region.
-
-The exploration HUD deliberately removes dashboard noise and takes over the whole viewport.
-It shows only the current place, Echo progress, speed, nearby interaction, and four compact
-tools. Operational vitals, filters, agent bars, and attention panes return in orbital view.
-
-Controls:
-
-| Input | Action |
-|---|---|
-| `W` / `S` | accelerate / reverse |
-| `A` / `D` | steer |
-| `Shift` | boost |
-| `Ctrl` or `X` | brake |
-| `Space` | jump |
-| `F` | use the nearby building, landmark, or gate |
-| `V` | switch rover and first-person camera |
-| `M` | open the Village Map |
-| `Tab` | switch street-level and orbital view |
-| `R` | return to the latest arrival point |
-
-Touch uses a joystick plus only three verbs: boost, hop, and action.
-
-## PortOS Places
-
-The cozy places are authored; their destinations still tell the truth about the install.
-
-- App state → Common market kiosks, status lamps, active-agent markers, and focused app routes.
-- AI activity → the suspended seed and orbital rings at the AI Core, with targeted beams.
-- CoS tasks → crates outside the Task Workshop.
-- Backup state → the status lamp outside Backup Cottage.
-- Memory graph and inbox → blossom clusters and the memory well at Memory House.
-- Goals and artifacts → flags and earned displays around their cottages.
-- Productivity and calendar history → terrain heat and task-flow motion.
-- Health → the Wellness landmark.
-- Database introspection → Data Harbor structures.
-- Federated peers → distant silhouettes beyond the local islands.
-
-These mappings are symbolic and read-only. OpenWorld may navigate to an existing action,
-but it must not invent an implicit write path or trigger an automation merely because the
-player approached something.
-
-## Historical Views and URL Contracts
-
-- `/openworld` and `/city` redirect to `/eidoverse`.
-- Historical `/openworld/apps/:appId`, `/openworld/region/:regionId`, and
- `/openworld/settings` paths are caught by the compatibility redirect.
-
-Selection remains in the URL. Building focus and region travel are bookmarkable,
-back/forward safe, and reachable from the command palette and voice navigation.
-
-Orbital view is an establishing shot of the complete archipelago, with pan/orbit/zoom,
-search, operational filters, attention, history, and photo tools. Street-level view is
-for movement and discovery. The two modes intentionally have different information
-hierarchies.
-
-## Art Direction
-
-`settings.worldStyle` selects one of two material languages over the same world:
-
-| Style | Look |
-|---|---|
-| `vibes` (default) | colorful low-poly valley, cottage destinations, dense trees, rolling lanes, drifting clouds |
-| `cyber` | nocturnal orbital dashboard, galaxy and weather layers, emissive live-state accents |
-
-The new direction follows current Three.js practice without making experimental renderer
-features a runtime requirement:
-
-- Procedural, data-driven terrain is authored as deterministic buffer geometry, inspired
- by Three.js’s
- [procedural terrain example](https://threejs.org/examples/webgpu_tsl_procedural_terrain).
-- Repeated world detail is instanced and geometry is reused, following
- [React Three Fiber’s scaling guidance](https://r3f.docs.pmnd.rs/advanced/scaling-performance).
-- Dense procedural city generation informed the decision to keep live structures modular,
- while making geography a stronger authored composition; see Three.js’s
- [city generator example](https://threejs.org/examples/webgpu_generator_city.html).
-
-WebGPU/TSL is not required for OpenWorld. The current WebGL path supports the app’s browsers
-and quality tiers, while the geometry/data separation leaves room for a future renderer
-upgrade.
-
-## Performance Contract
-
-- No per-frame React state for camera, player, water, pulses, or instanced dressing.
-- Geometry derived from static geography is memoized and explicitly disposed.
-- Repeated terrain detail uses instancing; the village terrain and curved lane ribbons are memoized.
-- Expensive atmosphere layers mount only for the appropriate style/tier.
-- Adaptive quality remains internal. Player-facing settings describe mood, sound, and
- controls rather than renderer implementation.
-- Photo-only postprocessing stays out of the always-on live canvas.
-- Hidden tabs stop the live frame loop.
-
-## Critical Files
-
-- `client/src/utils/openWorldPlan.js` — terrain height, lanes, cottage collision, parcels, and walkability
-- `client/src/components/openworld/OpenWorldArchipelago.jsx` — village terrain, cottages, routes, and dressing
-- `client/src/components/openworld/OpenWorldWater.jsx` — world sea
-- `client/src/pages/OpenWorld.jsx` — route state and mode/game orchestration
-- `client/src/components/openworld/OpenWorldScene.jsx` — Canvas and scene composition
-- `client/src/components/openworld/PlayerController.jsx` — rover movement and interaction
-- `client/src/utils/openWorldPlayerRig.js` — camera and vehicle math
-- `client/src/utils/openWorldCollectibles.js` — Echo Shard placement and progress
-- `client/src/utils/openWorldRegions.js` — region registry and arrival projection
-- `client/src/utils/openWorldMiniMap.js` — shared world-map projection
-- `client/src/components/openworld/OpenWorldFastTravel.jsx` — searchable Village Map
-- `client/src/components/openworld/OpenWorldHud.jsx` — desktop mode hierarchy
-- `client/src/components/openworld/OpenWorldHudCompact.jsx` — compact/touch hierarchy
-
-## Verification
-
-Before shipping a geography or traversal change:
-
-1. Run the focused OpenWorld utility and component tests.
-2. Run the client production build.
-3. Inspect orbital view and confirm the full PortOS world remains readable and useful.
-4. Drop into street level and confirm the rover enters at the village gate, the next bend and
- destination are visible, cottages are solid, suspension follows terrain, shards collect,
- and `F` exposes only a visible nearby place.
-5. Open the Village Map and confirm its neighborhoods, player, cottages, and destinations
- match the 3D world.
-6. Check at least one compact viewport and one desktop viewport.
+> **Historical rename (2026-08-19).** This surface originally shipped as CyberCity at `/city`, then as OpenWorld at `/openworld`. The permanent redirects preserve bookmarks, pinned rows, and command-palette history.
diff --git a/scripts/generate-api-route-catalog.test.js b/scripts/generate-api-route-catalog.test.js
index bf39635b9b..77ad759714 100644
--- a/scripts/generate-api-route-catalog.test.js
+++ b/scripts/generate-api-route-catalog.test.js
@@ -255,8 +255,6 @@ describe('generated API route catalog', () => {
const operations = new Set(readApiRouteCatalog().routes.map((route) => `${route.method} ${route.path}`));
for (const operation of [
'POST /api/brain/songbook/import/url',
- 'GET /api/city/introspection',
- 'GET /api/openworld/introspection',
'GET /api/providers/readiness',
'DELETE /api/providers/:id',
'POST /api/providers/:id/test',
diff --git a/server/index.js b/server/index.js
index 58ec6ffb7b..fd1e8fa0e8 100644
--- a/server/index.js
+++ b/server/index.js
@@ -87,7 +87,6 @@ import jiraRoutes from './routes/jira.js';
import autobiographyRoutes from './routes/autobiography.js';
import backupRoutes from './routes/backup.js';
import legacyExportRoutes from './routes/legacyExport.js';
-import openWorldRoutes from './routes/openWorldRoutes.js';
import eidoverseWorldRoutes from './routes/eidoverseWorldRoutes.js';
import databaseRoutes from './routes/database.js';
import localLlmRoutes from './routes/localLlm.js';
@@ -299,9 +298,6 @@ app.use('/api/autofix', autoFixMetricsRoutes);
app.use('/api/backup', backupRoutes);
app.use('/api/legacy-export', legacyExportRoutes);
app.use('/api/eidoverse/world', eidoverseWorldRoutes);
-app.use('/api/openworld', openWorldRoutes);
-// Keep the pre-rename API prefix available to older clients and installed voice tools.
-app.use('/api/city', openWorldRoutes);
app.use('/api/database', databaseRoutes);
app.use('/api/uploads', uploadsRoutes);
app.use('/api/image-clean', imageCleanRoutes);
diff --git a/server/lib/README.md b/server/lib/README.md
index f9f05618dd..9b9c344d77 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -77,7 +77,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `genomeValidation.js` | Genome upload + search schemas. |
| `identityValidation.js` | Identity section + chronotype + scheduling schemas. |
| `meatspaceValidation.js` | Meatspace (location/health log) schemas. |
-| `mediaValidation.js` | Media-generation & local-model infra schemas (LoRA training, local-LLM/Ollama/LM Studio management, OpenWorld snapshots, media-collection bulk ops). |
+| `mediaValidation.js` | Media-generation & local-model infra schemas (LoRA training, local-LLM/Ollama/LM Studio management, media-collection bulk ops). |
| `memoryValidation.js` | Memory record + retrieval schemas. |
| `modelPersonalityValidation.js` | LLM personality self-profile test schemas: trait taxonomy (versioned), self-eval + twin-alignment response schemas, run/settings route inputs. |
| `moodBoardValidation.js` | Mood board + board-item create/update schemas. |
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index c363efd736..0d61132141 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -30,7 +30,6 @@
"/api/capabilities",
"/api/catalog",
"/api/character",
- "/api/city",
"/api/client-errors",
"/api/code-review",
"/api/commands",
@@ -98,7 +97,6 @@
"/api/notes",
"/api/notifications",
"/api/openclaw",
- "/api/openworld",
"/api/palette",
"/api/peer-sync",
"/api/pipeline",
@@ -3318,38 +3316,6 @@
"server/routes/character.js"
]
},
- {
- "method": "GET",
- "path": "/api/city/introspection",
- "mountPath": "/api/city",
- "sources": [
- "server/routes/openWorldRoutes.js"
- ]
- },
- {
- "method": "GET",
- "path": "/api/city/snapshots",
- "mountPath": "/api/city",
- "sources": [
- "server/routes/openWorldRoutes.js"
- ]
- },
- {
- "method": "POST",
- "path": "/api/city/snapshots/capture",
- "mountPath": "/api/city",
- "sources": [
- "server/routes/openWorldRoutes.js"
- ]
- },
- {
- "method": "GET",
- "path": "/api/city/snapshots/config",
- "mountPath": "/api/city",
- "sources": [
- "server/routes/openWorldRoutes.js"
- ]
- },
{
"method": "POST",
"path": "/api/client-errors",
@@ -11702,38 +11668,6 @@
"server/routes/openclaw.js"
]
},
- {
- "method": "GET",
- "path": "/api/openworld/introspection",
- "mountPath": "/api/openworld",
- "sources": [
- "server/routes/openWorldRoutes.js"
- ]
- },
- {
- "method": "GET",
- "path": "/api/openworld/snapshots",
- "mountPath": "/api/openworld",
- "sources": [
- "server/routes/openWorldRoutes.js"
- ]
- },
- {
- "method": "POST",
- "path": "/api/openworld/snapshots/capture",
- "mountPath": "/api/openworld",
- "sources": [
- "server/routes/openWorldRoutes.js"
- ]
- },
- {
- "method": "GET",
- "path": "/api/openworld/snapshots/config",
- "mountPath": "/api/openworld",
- "sources": [
- "server/routes/openWorldRoutes.js"
- ]
- },
{
"method": "POST",
"path": "/api/palette/action/:id",
@@ -14334,6 +14268,14 @@
"server/routes/settings.js"
]
},
+ {
+ "method": "GET",
+ "path": "/api/settings/credentials",
+ "mountPath": "/api/settings",
+ "sources": [
+ "server/routes/settings.js"
+ ]
+ },
{
"method": "GET",
"path": "/api/settings/features",
@@ -17472,9 +17414,9 @@
}
],
"stats": {
- "mounts": 147,
- "operations": 2164,
- "declarations": 2168,
- "sourceFiles": 229
+ "mounts": 145,
+ "operations": 2157,
+ "declarations": 2165,
+ "sourceFiles": 228
}
}
diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.js
index d82e30dcf8..46bfffb02d 100644
--- a/server/lib/mediaValidation.js
+++ b/server/lib/mediaValidation.js
@@ -14,16 +14,6 @@ import { ASSESSABLE_RUNTIMES } from './localProviderRuntime.js';
import { SWEEP_SCOPES } from './localModelAssessment.js';
import { CAPABILITY_TEST_IDS } from './modelCapabilityTests.js';
-// OpenWorld snapshot pipeline (issue #877): how often to capture a city-state
-// frame and how many to retain. Validated as a settings slice on PUT /api/settings;
-// service-side defaults (DEFAULT_SNAPSHOT_CONFIG) fill any absent field so an
-// install with no `openWorldSnapshots` key still captures.
-export const openWorldSnapshotConfigSchema = z.object({
- enabled: z.boolean().optional(),
- intervalMinutes: z.number().int().min(1).max(1440).optional(),
- maxSnapshots: z.number().int().min(10).max(100000).optional()
-});
-
// iMessage ingestion config (#2151) — the `settings.imessage` slice. Sync is OFF
// by default and only reads chat.db when enabled (needs macOS Full Disk Access).
// Validated as a settings slice on PUT /api/settings; service-side DEFAULT_CONFIG
@@ -128,13 +118,6 @@ export const startTrainingRunSchema = z.object({
acknowledgeCaptionLeak: z.boolean().optional(),
});
-// Query for GET /api/openworld/snapshots — `since` (ISO timestamp) and `limit`
-// (most-recent N) both arrive as strings on the query string.
-export const openWorldSnapshotsQuerySchema = z.object({
- since: z.string().datetime().optional(),
- limit: z.coerce.number().int().min(1).max(100000).optional()
-});
-
// === Local LLM backends (Ollama / LM Studio) ===
export const localLlmBackendSchema = z.enum(['ollama', 'lmstudio']);
// modelId is passed positionally to the `lms` CLI (execFile, no shell) — reject
diff --git a/server/lib/staticImportGraph.js b/server/lib/staticImportGraph.js
index f385a5052f..d9fbe5cc48 100644
--- a/server/lib/staticImportGraph.js
+++ b/server/lib/staticImportGraph.js
@@ -22,7 +22,7 @@
*/
import { readdirSync, readFileSync, existsSync } from 'fs';
-import { dirname, join, relative, resolve } from 'path';
+import { dirname, join, relative, resolve, sep } from 'path';
// `import … from 'x'` / `export … from 'x'` (line-anchored, non-greedy up to
// the `from`), and bare `import 'x'` side-effect imports.
@@ -119,7 +119,7 @@ export function buildStaticImportGraph(rootDir) {
const deps = new Set();
for (const spec of staticImportSpecifiers(abs)) {
if (!spec.startsWith('.')) continue;
- const rel = relative(rootDir, resolve(dirname(abs), spec));
+ const rel = relative(rootDir, resolve(dirname(abs), spec)).split(sep).join('/');
if (known.has(rel)) deps.add(rel);
}
graph.set(file, [...deps]);
diff --git a/server/routes/openWorldRoutes.js b/server/routes/openWorldRoutes.js
deleted file mode 100644
index a20ea73dd5..0000000000
--- a/server/routes/openWorldRoutes.js
+++ /dev/null
@@ -1,40 +0,0 @@
-import { Router } from 'express';
-import { asyncHandler } from '../lib/errorHandler.js';
-import { validateRequest, openWorldSnapshotsQuerySchema } from '../lib/validation.js';
-import {
- captureSnapshot,
- getSnapshots,
- getSnapshotConfig,
-} from '../services/openWorldSnapshots.js';
-import { getNextSnapshotTime } from '../services/openWorldSnapshotScheduler.js';
-import { getOpenWorldIntrospection } from '../services/openWorldIntrospection.js';
-
-const router = Router();
-
-// GET /api/openworld/snapshots — the recorded world-state series, oldest-first.
-// A future timeline scrubber loads this and drives the 3D scene from a frame.
-router.get('/snapshots', asyncHandler(async (req, res) => {
- const { since, limit } = validateRequest(openWorldSnapshotsQuerySchema, req.query);
- res.json(await getSnapshots({ since, limit }));
-}));
-
-// POST /api/openworld/snapshots/capture — capture a frame on demand (manual /
-// testing trigger; the scheduler drives the periodic captures).
-router.post('/snapshots/capture', asyncHandler(async (req, res) => {
- res.json(await captureSnapshot());
-}));
-
-// GET /api/openworld/introspection — DB tables + data/ domain sizes for the Data
-// Harbor district. Cached server-side (stale-while-revalidate); `db: null`
-// means the database is unreachable, distinct from a reachable-but-empty one.
-router.get('/introspection', asyncHandler(async (req, res) => {
- res.json(await getOpenWorldIntrospection());
-}));
-
-// GET /api/openworld/snapshots/config — effective capture config + next run time.
-router.get('/snapshots/config', asyncHandler(async (req, res) => {
- const config = await getSnapshotConfig();
- res.json({ ...config, nextRun: getNextSnapshotTime() });
-}));
-
-export default router;
diff --git a/server/routes/openWorldRoutes.test.js b/server/routes/openWorldRoutes.test.js
deleted file mode 100644
index f6d3918662..0000000000
--- a/server/routes/openWorldRoutes.test.js
+++ /dev/null
@@ -1,103 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-import express from 'express';
-import { request } from '../lib/testHelper.js';
-import { errorMiddleware } from '../lib/errorHandler.js';
-
-// Mock the service layer — these route tests verify routing + query validation,
-// not the capture/store logic (covered in openWorldSnapshots.test.js).
-const captureSnapshot = vi.fn();
-const getSnapshots = vi.fn();
-const getSnapshotConfig = vi.fn();
-const getNextSnapshotTime = vi.fn();
-const getOpenWorldIntrospection = vi.fn();
-
-vi.mock('../services/openWorldSnapshots.js', () => ({
- captureSnapshot: (...a) => captureSnapshot(...a),
- getSnapshots: (...a) => getSnapshots(...a),
- getSnapshotConfig: (...a) => getSnapshotConfig(...a),
-}));
-vi.mock('../services/openWorldSnapshotScheduler.js', () => ({
- getNextSnapshotTime: (...a) => getNextSnapshotTime(...a),
-}));
-vi.mock('../services/openWorldIntrospection.js', () => ({
- getOpenWorldIntrospection: (...a) => getOpenWorldIntrospection(...a),
-}));
-
-const { default: openWorldRoutes } = await import('./openWorldRoutes.js');
-
-const makeApp = () => {
- const app = express();
- app.use(express.json());
- app.use('/api/openworld', openWorldRoutes);
- app.use(errorMiddleware);
- return app;
-};
-
-describe('city snapshot routes', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- getSnapshots.mockResolvedValue({ total: 0, snapshots: [] });
- getSnapshotConfig.mockResolvedValue({ enabled: true, intervalMinutes: 5, maxSnapshots: 1000 });
- getNextSnapshotTime.mockReturnValue('2026-06-05T12:00:00.000Z');
- captureSnapshot.mockResolvedValue({ ts: '2026-06-05T11:55:00.000Z', schemaVersion: 1, counts: {} });
- });
-
- describe('GET /api/openworld/snapshots', () => {
- it('returns the series with no query params', async () => {
- getSnapshots.mockResolvedValue({ total: 2, snapshots: [{ ts: 'a' }, { ts: 'b' }] });
- const res = await request(makeApp()).get('/api/openworld/snapshots');
- expect(res.status).toBe(200);
- expect(res.body.total).toBe(2);
- expect(getSnapshots).toHaveBeenCalledWith({ since: undefined, limit: undefined });
- });
-
- it('coerces limit and passes a valid since through', async () => {
- const res = await request(makeApp()).get('/api/openworld/snapshots?limit=10&since=2026-06-01T00:00:00.000Z');
- expect(res.status).toBe(200);
- expect(getSnapshots).toHaveBeenCalledWith({ since: '2026-06-01T00:00:00.000Z', limit: 10 });
- });
-
- it('rejects a non-numeric limit', async () => {
- const res = await request(makeApp()).get('/api/openworld/snapshots?limit=abc');
- expect(res.status).toBe(400);
- expect(res.body.code).toBe('VALIDATION_ERROR');
- });
-
- it('rejects a malformed since timestamp', async () => {
- const res = await request(makeApp()).get('/api/openworld/snapshots?since=not-a-date');
- expect(res.status).toBe(400);
- expect(res.body.code).toBe('VALIDATION_ERROR');
- });
- });
-
- describe('POST /api/openworld/snapshots/capture', () => {
- it('captures a frame on demand', async () => {
- const res = await request(makeApp()).post('/api/openworld/snapshots/capture');
- expect(res.status).toBe(200);
- expect(res.body.schemaVersion).toBe(1);
- expect(captureSnapshot).toHaveBeenCalledOnce();
- });
- });
-
- describe('GET /api/openworld/introspection', () => {
- it('passes the introspection payload through, including db: null', async () => {
- const payload = { ts: '2026-06-09T00:00:00.000Z', db: null, fs: { domains: [], totalBytes: 0, totalFiles: 0 } };
- getOpenWorldIntrospection.mockResolvedValue(payload);
- const res = await request(makeApp()).get('/api/openworld/introspection');
- expect(res.status).toBe(200);
- expect(res.body).toEqual(payload);
- expect(getOpenWorldIntrospection).toHaveBeenCalledOnce();
- });
- });
-
- describe('GET /api/openworld/snapshots/config', () => {
- it('returns effective config plus the next run time', async () => {
- const res = await request(makeApp()).get('/api/openworld/snapshots/config');
- expect(res.status).toBe(200);
- expect(res.body).toEqual({
- enabled: true, intervalMinutes: 5, maxSnapshots: 1000,
- nextRun: '2026-06-05T12:00:00.000Z',
- });
- });
- });
-});
diff --git a/server/routes/settings.js b/server/routes/settings.js
index 5be8abb24a..85859bf02d 100644
--- a/server/routes/settings.js
+++ b/server/routes/settings.js
@@ -20,7 +20,7 @@ import { asyncHandler } from '../lib/errorHandler.js';
import { isPlainObject } from '../lib/objects.js';
import { agentContextSettingsSchema } from '../lib/agentContextValidation.js';
import { EFFORT_LEVELS } from '../lib/providerModels.js';
-import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, localLlmSettingsSchema, openWorldSnapshotConfigSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, instanceFeatureSettingsSchema, instanceFeatureIdSchema, instanceFeatureUpdateSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, federationSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, usageApiBilledInstanceIdsSchema, validateRequest } from '../lib/validation.js';
+import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, localLlmSettingsSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, instanceFeatureSettingsSchema, instanceFeatureIdSchema, instanceFeatureUpdateSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, federationSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, usageApiBilledInstanceIdsSchema, validateRequest } from '../lib/validation.js';
const router = Router();
@@ -278,17 +278,6 @@ router.put('/', asyncHandler(async (req, res) => {
if (req.body?.localLlm !== undefined) {
validateRequest(localLlmSettingsSchema, req.body.localLlm);
}
- // OpenWorld snapshot capture config — validate the slice when present so a
- // malformed interval/cap can't reach disk and break the scheduler.
- if (req.body?.openWorldSnapshots !== undefined) {
- validateRequest(openWorldSnapshotConfigSchema.partial(), req.body.openWorldSnapshots);
- }
- // The settings slice predates the OpenWorld rename. Keep accepting the old
- // property so an older client can still update capture settings safely.
- const legacySnapshotSettingsKey = ['city', 'Snapshots'].join('');
- if (req.body?.[legacySnapshotSettingsKey] !== undefined) {
- validateRequest(openWorldSnapshotConfigSchema.partial(), req.body[legacySnapshotSettingsKey]);
- }
// iMessage ingestion config (#2151) — validate the slice when present so a
// malformed enabled/interval can't reach disk and break the sync scheduler.
if (req.body?.imessage !== undefined) {
diff --git a/server/services/openWorldIntrospection.js b/server/services/dataIntrospection.js
similarity index 94%
rename from server/services/openWorldIntrospection.js
rename to server/services/dataIntrospection.js
index 054f4c04e3..3164670016 100644
--- a/server/services/openWorldIntrospection.js
+++ b/server/services/dataIntrospection.js
@@ -1,7 +1,7 @@
/**
- * OpenWorld Introspection
+ * Data Introspection
*
- * Read-only diagnostics backing OpenWorld's Data Harbor district: the PostgreSQL
+ * Read-only diagnostics for data-backed product surfaces: the PostgreSQL
* datastore (one silo per table) and the `data/` filesystem (one archive rack per
* domain directory). Purely derived state — nothing is stored, synced, or backed
* up (see docs/STORAGE.md: transient query results need no classification).
@@ -100,7 +100,7 @@ async function build() {
return { ts: new Date().toISOString(), db, fs };
}
-export async function getOpenWorldIntrospection() {
+export async function getDataIntrospection() {
const now = Date.now();
if (cache && now - cacheBuiltAt < INTROSPECTION_TTL_MS) return cache;
@@ -117,7 +117,7 @@ export async function getOpenWorldIntrospection() {
// rethrow would be an unhandled rejection — resolve to the stale
// payload instead and only propagate when there's nothing to serve.
inFlight = null;
- console.error(`❌ OpenWorld introspection rebuild failed: ${err.message}`);
+ console.error(`❌ Data introspection rebuild failed: ${err.message}`);
if (cache) return cache;
throw err;
},
diff --git a/server/services/openWorldIntrospection.test.js b/server/services/dataIntrospection.test.js
similarity index 85%
rename from server/services/openWorldIntrospection.test.js
rename to server/services/dataIntrospection.test.js
index fa3523b5ec..9e9400f6c4 100644
--- a/server/services/openWorldIntrospection.test.js
+++ b/server/services/dataIntrospection.test.js
@@ -1,5 +1,5 @@
/**
- * Tests for the Data Harbor introspection service: DB section shape (including
+ * Tests for the data introspection service: DB section shape (including
* the down-DB → `db: null` absent-vs-empty contract), the data/ domain section
* (delegated to dataManager's getDataOverview so the harbor and the Data page
* always agree), and the TTL + stale-while-revalidate cache discipline.
@@ -15,10 +15,10 @@ vi.mock('../lib/db.js', () => ({ query: queryMock }));
vi.mock('./dataManager.js', () => ({ getDataOverview: overviewMock }));
const {
- getOpenWorldIntrospection,
+ getDataIntrospection,
resetIntrospectionCache,
INTROSPECTION_TTL_MS,
-} = await import('./openWorldIntrospection.js');
+} = await import('./dataIntrospection.js');
const TABLE_ROWS = [
{ name: 'memories', row_estimate: '1200', total_bytes: '900000' },
@@ -57,9 +57,9 @@ beforeEach(() => {
overviewMock.mockResolvedValue(happyOverview());
});
-describe('getOpenWorldIntrospection — db section', () => {
+describe('getDataIntrospection — db section', () => {
it('maps tables with coerced numbers, embedding flags, size, and migrations', async () => {
- const result = await getOpenWorldIntrospection();
+ const result = await getDataIntrospection();
expect(result.ts).toBeTruthy();
expect(result.db.sizeBytes).toBe(5000000);
expect(result.db.tables).toHaveLength(3);
@@ -77,7 +77,7 @@ describe('getOpenWorldIntrospection — db section', () => {
if (sql.includes('pg_stat_user_tables')) throw new Error('connection refused');
return happyQueries(sql);
});
- const result = await getOpenWorldIntrospection();
+ const result = await getDataIntrospection();
expect(result.db).toBeNull();
// The filesystem section is independent of DB health.
expect(result.fs.domains.length).toBeGreaterThan(0);
@@ -90,7 +90,7 @@ describe('getOpenWorldIntrospection — db section', () => {
if (sql.includes('information_schema.columns')) throw new Error('nope');
return happyQueries(sql);
});
- const result = await getOpenWorldIntrospection();
+ const result = await getDataIntrospection();
expect(result.db.tables).toHaveLength(3);
expect(result.db.migrations).toBeNull();
expect(result.db.sizeBytes).toBeNull();
@@ -98,9 +98,9 @@ describe('getOpenWorldIntrospection — db section', () => {
});
});
-describe('getOpenWorldIntrospection — fs section', () => {
+describe('getDataIntrospection — fs section', () => {
it('maps the data overview into harbor domains + totals', async () => {
- const { fs } = await getOpenWorldIntrospection();
+ const { fs } = await getDataIntrospection();
expect(fs.domains).toEqual([
{ name: 'images', bytes: 3_100_000_000, files: 2400 },
{ name: 'brain', bytes: 800_000, files: 60 },
@@ -111,24 +111,24 @@ describe('getOpenWorldIntrospection — fs section', () => {
it('returns fs: null (absent) when the overview fails, keeping the db section', async () => {
overviewMock.mockRejectedValue(new Error('du exploded'));
- const result = await getOpenWorldIntrospection();
+ const result = await getDataIntrospection();
expect(result.fs).toBeNull();
expect(result.db.tables).toHaveLength(3);
});
});
-describe('getOpenWorldIntrospection — cache discipline', () => {
+describe('getDataIntrospection — cache discipline', () => {
it('serves the cached payload within the TTL without re-querying', async () => {
- const first = await getOpenWorldIntrospection();
+ const first = await getDataIntrospection();
const callsAfterFirst = queryMock.mock.calls.length;
- const second = await getOpenWorldIntrospection();
+ const second = await getDataIntrospection();
expect(second).toBe(first);
expect(queryMock.mock.calls.length).toBe(callsAfterFirst);
expect(overviewMock).toHaveBeenCalledTimes(1);
});
it('serves stale immediately past the TTL while revalidating in the background', async () => {
- const first = await getOpenWorldIntrospection();
+ const first = await getDataIntrospection();
// Jump past the TTL without fake timers — the background rebuild does real
// async work that fake timers can't flush.
vi.spyOn(Date, 'now').mockReturnValue(Date.now() + INTROSPECTION_TTL_MS + 1000);
@@ -139,12 +139,12 @@ describe('getOpenWorldIntrospection — cache discipline', () => {
return happyQueries(sql);
});
- const stale = await getOpenWorldIntrospection();
+ const stale = await getDataIntrospection();
expect(stale).toBe(first); // immediate stale answer, no blocking on the rebuild
// Once the background rebuild settles, the fresh payload is served.
await vi.waitFor(async () => {
- expect((await getOpenWorldIntrospection()).db.sizeBytes).toBe(777);
+ expect((await getDataIntrospection()).db.sizeBytes).toBe(777);
});
vi.restoreAllMocks();
});
diff --git a/server/services/eidoverseWorldSources.js b/server/services/eidoverseWorldSources.js
index aebe39982e..4878d35be4 100644
--- a/server/services/eidoverseWorldSources.js
+++ b/server/services/eidoverseWorldSources.js
@@ -22,7 +22,7 @@ import { getGoals } from './identity.js';
import { getActivityCalendar, getVelocityMetrics } from './productivity.js';
import { getBrainGraphOverview } from './brainGraph.js';
import { getInboxLogCounts } from './brainStorage.js';
-import { getOpenWorldIntrospection } from './openWorldIntrospection.js';
+import { getDataIntrospection } from './dataIntrospection.js';
import { fetchMyCurrentSprintTickets } from './jira.js';
const safeText = (value, fallback = '', max = 160) => {
@@ -434,7 +434,7 @@ export async function collectEidoverseWorldSources({ signal } = {}) {
getGoals().catch(() => null),
getBrainGraphOverview({ limit: 100 }).catch(() => null),
getInboxLogCounts().catch(() => null),
- getOpenWorldIntrospection().catch(() => null),
+ getDataIntrospection().catch(() => null),
]), signal);
const [apps, appConfig, agents, taskState, cosStatus, review, featuresState, peers, backupState, notifications, character, voiceConfig, memory, diskPercent, todayActivity, velocity, activityCalendar, goalsData, memoryGraph, inboxCounts, introspection] = reads;
diff --git a/server/services/eidoverseWorldSources.test.js b/server/services/eidoverseWorldSources.test.js
index bfaff43589..fa2768026b 100644
--- a/server/services/eidoverseWorldSources.test.js
+++ b/server/services/eidoverseWorldSources.test.js
@@ -46,8 +46,8 @@ vi.mock('./brainGraph.js', () => ({
vi.mock('./brainStorage.js', () => ({
getInboxLogCounts: vi.fn(async () => sources.inboxCounts),
}));
-vi.mock('./openWorldIntrospection.js', () => ({
- getOpenWorldIntrospection: vi.fn(async () => sources.introspection),
+vi.mock('./dataIntrospection.js', () => ({
+ getDataIntrospection: vi.fn(async () => sources.introspection),
}));
vi.mock('./jira.js', () => ({
fetchMyCurrentSprintTickets: vi.fn(async () => []),
diff --git a/server/services/openWorldSnapshotScheduler.js b/server/services/openWorldSnapshotScheduler.js
deleted file mode 100644
index 716e5fc6fa..0000000000
--- a/server/services/openWorldSnapshotScheduler.js
+++ /dev/null
@@ -1,66 +0,0 @@
-/**
- * OpenWorld Snapshot Scheduler
- *
- * Registers an interval job that periodically captures a OpenWorld state
- * snapshot (see openWorldSnapshots.js). Mirrors the backupScheduler.js pattern.
- *
- * Like the backup scheduler's cron expression, the *interval value* is locked
- * in at registration — changing `intervalMinutes` requires a restart. But the
- * `enabled` toggle is re-read inside the handler on every run, so disabling
- * capture from settings takes effect on the next tick without a restart.
- */
-
-import { schedule, cancel, getEvent } from './eventScheduler.js';
-import { captureSnapshot, getSnapshotConfig } from './openWorldSnapshots.js';
-
-const EVENT_ID = 'city-snapshot';
-
-/**
- * Start the snapshot scheduler. No-ops if disabled in settings.
- */
-export async function startOpenWorldSnapshotScheduler() {
- const { enabled, intervalMinutes } = await getSnapshotConfig();
-
- if (!enabled) {
- console.log('🏙️ OpenWorld snapshot scheduler: disabled in settings — skipping');
- return;
- }
-
- const intervalMs = intervalMinutes * 60 * 1000;
-
- schedule({
- id: EVENT_ID,
- type: 'interval',
- intervalMs,
- handler: async () => {
- // Re-read settings each run so an `enabled: false` toggle takes effect
- // without a restart (the interval value itself is locked at registration).
- const current = await getSnapshotConfig();
- if (!current.enabled) {
- console.log('🏙️ OpenWorld snapshot scheduler: disabled since registration — skipping run');
- return;
- }
- const frame = await captureSnapshot();
- console.log(`🏙️ OpenWorld snapshot captured: ${frame.counts.appsOnline}/${frame.counts.appsTotal} apps online, ${frame.counts.agentsActive} agents active`);
- },
- metadata: { source: 'openWorldSnapshotScheduler' },
- });
-
- console.log(`🏙️ OpenWorld snapshot scheduler: registered every ${intervalMinutes}min`);
-}
-
-/**
- * Stop the snapshot scheduler.
- */
-export function stopOpenWorldSnapshotScheduler() {
- cancel(EVENT_ID);
- console.log('🏙️ OpenWorld snapshot scheduler: stopped');
-}
-
-/**
- * ISO timestamp of the next scheduled capture, or null if not scheduled.
- */
-export function getNextSnapshotTime() {
- const event = getEvent(EVENT_ID);
- return event?.nextRunAt ? new Date(event.nextRunAt).toISOString() : null;
-}
diff --git a/server/services/openWorldSnapshots.js b/server/services/openWorldSnapshots.js
deleted file mode 100644
index 815096dcc5..0000000000
--- a/server/services/openWorldSnapshots.js
+++ /dev/null
@@ -1,299 +0,0 @@
-/**
- * OpenWorld Snapshot Store
- *
- * Periodically captures a compact snapshot of the OpenWorld's derived state
- * (per-app status, agent activity, landmark counts, system health) to a
- * rolling, capped JSONL store. This is the prerequisite slice for the roadmap
- * 3.6 "historical timeline scrubber" (issue #877): the city derives everything
- * live with no persistence of past state, so there is nothing to scrub to until
- * snapshots accumulate. A future scrubber UI loads this series and drives the
- * 3D scene from a past frame.
- *
- * Snapshots are local-only — each install records its own derived state and
- * never syncs to federated peers.
- *
- * Storage mirrors the proven rolling-JSONL pattern in `history.js`: append on
- * the hot path, compact (rewrite) only when the cap is exceeded, 2s read cache,
- * and a single write-queue tail so concurrent captures can't interleave.
- */
-
-import { join } from 'path';
-import {
- appendJSONLine,
- ensureDir,
- PATHS,
- readJSONLines,
- writeJSONLines,
-} from '../lib/fileUtils.js';
-import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
-import { getSettings } from './settings.js';
-import * as apps from './apps.js';
-import * as cos from './cos.js';
-import { getAgents } from './cosAgentLifecycle.js';
-import { getCosTasks } from './cosTaskStore.js';
-import { getPendingCounts } from './review.js';
-import { getSelf, getPeers } from './instances.js';
-import * as backup from './backup.js';
-import { getCountsByType } from './notifications.js';
-import { getCharacter } from './character.js';
-import { getMemoryStats } from '../lib/memoryStats.js';
-import { statfs } from 'fs/promises';
-import os from 'os';
-
-// Root-filesystem disk usage percent, derived the same way the
-// /api/system/health/details route does (bavail = blocks available to the
-// user). Returns null when statfs is unavailable so a failed read reads as
-// "unknown," not "0% full".
-async function getDiskPercent() {
- const stats = await statfs('/').catch(() => null);
- if (!stats) return null;
- const total = stats.blocks * stats.bsize;
- if (!(total > 0)) return null;
- const used = total - stats.bavail * stats.bsize;
- return Math.round((used / total) * 100);
-}
-
-const DATA_DIR = PATHS.data;
-const SNAPSHOTS_FILE = join(DATA_DIR, 'city-snapshots.jsonl');
-
-// Sentinel a getter falls back to when it throws — distinct from a successful
-// empty read. `null` for object/array sources means "source unavailable at
-// capture time" (AGENTS.md's absent-vs-empty rule), so a transient failure
-// never reads as a legitimate "zero apps / zero peers" in the history.
-const FAILED = null;
-
-// Bump when the snapshot shape changes incompatibly so a future scrubber can
-// gate on frame shape and skip / migrate older frames rather than mis-render.
-export const SNAPSHOT_SCHEMA_VERSION = 1;
-
-// Config defaults — surfaced via getSnapshotConfig() so installs with no
-// `openWorldSnapshots` settings key behave sanely without a migration.
-export const DEFAULT_SNAPSHOT_CONFIG = {
- enabled: true,
- intervalMinutes: 5,
- maxSnapshots: 1000, // ~3.5 days at the 5-minute default
-};
-
-// In-memory cache with TTL (mirrors history.js).
-let snapshotCache = null;
-let cacheTimestamp = 0;
-const CACHE_TTL_MS = 2000;
-const queueSnapshotWrite = createFileWriteQueue();
-
-/**
- * Resolve the effective snapshot config, layering the user's settings slice
- * over the defaults. Hand-edited / partial settings degrade to defaults
- * field-by-field rather than disabling capture wholesale.
- */
-export async function getSnapshotConfig() {
- const settings = await getSettings().catch(() => ({}));
- const legacySnapshotSettingsKey = ['city', 'Snapshots'].join('');
- const c = settings?.openWorldSnapshots || settings?.[legacySnapshotSettingsKey] || {};
- return {
- enabled: typeof c.enabled === 'boolean' ? c.enabled : DEFAULT_SNAPSHOT_CONFIG.enabled,
- intervalMinutes: Number.isFinite(c.intervalMinutes) && c.intervalMinutes >= 1
- ? Math.floor(c.intervalMinutes)
- : DEFAULT_SNAPSHOT_CONFIG.intervalMinutes,
- maxSnapshots: Number.isFinite(c.maxSnapshots) && c.maxSnapshots >= 10
- ? Math.floor(c.maxSnapshots)
- : DEFAULT_SNAPSHOT_CONFIG.maxSnapshots,
- };
-}
-
-async function loadSnapshots() {
- const now = Date.now();
- if (snapshotCache && (now - cacheTimestamp) < CACHE_TTL_MS) {
- return snapshotCache;
- }
- await ensureDir(DATA_DIR);
- snapshotCache = await readJSONLines(SNAPSHOTS_FILE, { logErrors: true });
- cacheTimestamp = now;
- return snapshotCache;
-}
-
-// True when `child` is `parent` itself or a path strictly nested under it.
-// Plain `startsWith` would mis-match sibling-prefix repos (/repos/proj would
-// "contain" /repos/project), so require a path boundary at the join.
-function isPathUnder(child, parent) {
- if (child === parent) return true;
- const base = parent.endsWith('/') ? parent : `${parent}/`;
- return child.startsWith(base);
-}
-
-// Map a CoS agent to the app it's working in by matching its workspacePath
-// against each app's repoPath. workspacePath may sit on the agent or in its
-// metadata depending on spawn path. Unlike the client's live agentMap (which
-// recomputes every render), this mapping is persisted replay data, so it must
-// be unambiguous: match on a path boundary and let the LONGEST matching
-// repoPath win, so a nested app repo beats its parent.
-function resolveAgentApp(agent, appStatuses) {
- const workspacePath = agent?.workspacePath || agent?.metadata?.workspacePath;
- if (!workspacePath || !Array.isArray(appStatuses)) return null;
- let best = null;
- for (const a of appStatuses) {
- if (!a.repoPath || !isPathUnder(workspacePath, a.repoPath)) continue;
- if (!best || a.repoPath.length > best.repoPath.length) best = a;
- }
- return best?.id ?? null;
-}
-
-/**
- * Assemble a compact city-state frame from server-side service getters.
- *
- * Each source is wrapped so one failing getter degrades to the `FAILED` (null)
- * sentinel rather than dropping the whole frame — a partial snapshot is more
- * useful to a scrubber than a missing one. Crucially, a thrown getter records
- * `null` (source unavailable), NOT an empty array / zero count, so a transient
- * failure can't masquerade as a legitimate "zero apps / zero peers" in the
- * history (AGENTS.md's absent-vs-empty rule). Counts derived from a FAILED
- * source are likewise `null`, distinct from a real `0` on a successful read.
- */
-async function buildSnapshot() {
- const [appStatuses, cosStatus, agents, taskState, reviewCounts, self, peers, backupState, notifCounts, character, memStats, diskPercent] =
- await Promise.all([
- apps.getAppStatuses().catch(() => FAILED),
- cos.getStatus().catch(() => FAILED),
- getAgents().catch(() => FAILED),
- getCosTasks().catch(() => FAILED),
- getPendingCounts().catch(() => FAILED),
- getSelf().catch(() => FAILED),
- getPeers().catch(() => FAILED),
- backup.getState().catch(() => FAILED),
- getCountsByType().catch(() => FAILED),
- // Only `character.level` is snapshotted (see the frame below), so skip both derived
- // fan-outs — this runs on every snapshot tick.
- getCharacter({ withSkills: false, withMetrics: false }).catch(() => FAILED),
- getMemoryStats().catch(() => FAILED),
- getDiskPercent().catch(() => null),
- ]);
-
- // Per-app state + agent→app assignments — the minimum a scrubber needs to
- // re-render buildings and diff adjacent frames for construction/teardown.
- // `null` (not `[]`) when the source failed, so the scrubber can skip vs. clear.
- const appsFrame = Array.isArray(appStatuses)
- ? appStatuses.map(a => ({ id: a.id, name: a.name, status: a.overallStatus }))
- : null;
- const assignmentsFrame = Array.isArray(agents)
- ? agents
- .filter(a => a?.status === 'running')
- .map(a => ({ agentId: a.id, appId: resolveAgentApp(a, appStatuses), status: a.status }))
- : null;
-
- const tasks = Array.isArray(taskState?.tasks) ? taskState.tasks : null;
- const taskCount = (status) => tasks === null ? null : tasks.filter(t => t?.status === status).length;
-
- const memUsagePercent = memStats && memStats.total > 0
- ? Math.round((memStats.used / memStats.total) * 100)
- : null;
- // os.loadavg() returns [0,0,0] on Windows (no load average) — record null
- // there rather than a misleading 0% so it reads as "unavailable," not "idle."
- const cpuPercent = process.platform === 'win32'
- ? null
- : Math.min(100, Math.round((os.loadavg()[0] / (os.cpus().length || 1)) * 100));
-
- // Successful-empty reads yield real 0s; FAILED sources yield null.
- const onlineApps = appsFrame === null ? null : appsFrame.filter(a => a.status === 'online').length;
- const onlinePeers = peers === null ? null : peers.filter(p => p?.status === 'online').length;
-
- return {
- ts: new Date().toISOString(),
- schemaVersion: SNAPSHOT_SCHEMA_VERSION,
- apps: appsFrame,
- assignments: assignmentsFrame,
- counts: {
- appsOnline: onlineApps,
- appsTotal: appsFrame === null ? null : appsFrame.length,
- agentsActive: cosStatus === null ? null : (cosStatus.activeAgents ?? 0),
- agentsPaused: cosStatus === null ? null : (cosStatus.pausedAgents ?? 0),
- tasksCompleted: cosStatus === null ? null : (cosStatus.stats?.tasksCompleted ?? 0),
- tasksPending: taskCount('pending'),
- tasksInProgress: taskCount('in_progress'),
- peersOnline: onlinePeers,
- peersTotal: peers === null ? null : peers.length,
- notificationsUnread: notifCounts === null ? null : (notifCounts.unread ?? 0),
- reviewTotal: reviewCounts === null ? null : (reviewCounts.total ?? 0),
- },
- cos: cosStatus === null ? null : {
- running: cosStatus.running ?? false,
- paused: cosStatus.paused ?? false,
- },
- backup: backupState === null ? null : {
- status: backupState.status ?? null,
- lastRun: backupState.lastRun ?? null,
- },
- health: {
- cpuPercent,
- memPercent: memUsagePercent,
- diskPercent,
- },
- character: { level: character === null ? null : (character.level ?? null) },
- instance: self === null ? null : {
- id: self.instanceId ?? null,
- name: self.name ?? null,
- },
- };
-}
-
-/**
- * Capture a snapshot now: build the frame, append it, and enforce the cap.
- * Serialized on the write queue so a scheduled capture and a manual
- * `POST /capture` can't interleave their read-modify-write.
- *
- * @returns {Promise<object>} the captured snapshot frame
- */
-export async function captureSnapshot() {
- const frame = await buildSnapshot();
-
- return queueSnapshotWrite(async () => {
- // Resolve the cap inside the queued turn so the trim reads the freshest
- // config alongside the persisted series (mirrors history.js keeping MAX in
- // its write path).
- const { maxSnapshots } = await getSnapshotConfig();
- const existing = await loadSnapshots();
- const next = [...existing, frame];
-
- if (next.length > maxSnapshots) {
- // Over cap: rewrite the file with the trailing window (drops oldest).
- const trimmed = next.slice(-maxSnapshots);
- await ensureDir(DATA_DIR);
- await writeJSONLines(SNAPSHOTS_FILE, trimmed);
- snapshotCache = trimmed;
- } else {
- await appendJSONLine(SNAPSHOTS_FILE, frame);
- snapshotCache = next;
- }
- cacheTimestamp = Date.now();
- return frame;
- });
-}
-
-/**
- * Read the snapshot series, oldest-first (chronological — a scrubber drags
- * left→right through time).
- *
- * @param {object} [options]
- * @param {number} [options.limit] - return only the most recent N frames
- * @param {string} [options.since] - ISO timestamp; return only frames at/after it
- * @returns {Promise<{ total: number, snapshots: Array }>}
- */
-export async function getSnapshots({ limit, since } = {}) {
- const all = await loadSnapshots();
- let frames = all;
-
- if (since) {
- const sinceMs = Date.parse(since);
- if (Number.isFinite(sinceMs)) {
- frames = frames.filter(f => Date.parse(f.ts) >= sinceMs);
- }
- }
-
- const total = frames.length;
- // A direct caller passing limit 0 means "none" — but slice(-0) returns the
- // WHOLE array, so handle 0 explicitly. The route's Zod schema enforces
- // limit >= 1, so this only hardens direct callers.
- if (Number.isFinite(limit) && limit >= 0 && limit < frames.length) {
- frames = limit === 0 ? [] : frames.slice(-limit); // most-recent N, chronological
- }
-
- return { total, snapshots: frames };
-}
diff --git a/server/services/openWorldSnapshots.test.js b/server/services/openWorldSnapshots.test.js
deleted file mode 100644
index a9454e72ef..0000000000
--- a/server/services/openWorldSnapshots.test.js
+++ /dev/null
@@ -1,260 +0,0 @@
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
-import { existsSync, mkdtempSync, readFileSync, rmSync } from 'fs';
-import { join } from 'path';
-import { tmpdir } from 'os';
-
-const readLines = (path) =>
- readFileSync(path, 'utf-8').trim().split('\n').filter(Boolean).map((line) => JSON.parse(line));
-
-describe('openWorldSnapshots service', () => {
- let dataDir;
- let snapshotsFile;
-
- beforeEach(() => {
- vi.resetModules();
- dataDir = mkdtempSync(join(tmpdir(), 'portos-openworld-snap-'));
- snapshotsFile = join(dataDir, 'city-snapshots.jsonl');
- });
-
- afterEach(() => {
- vi.doUnmock('../lib/fileUtils.js');
- vi.doUnmock('./settings.js');
- vi.doUnmock('./apps.js');
- vi.doUnmock('./cos.js');
- vi.doUnmock('./cosAgentLifecycle.js');
- vi.doUnmock('./cosTaskStore.js');
- vi.doUnmock('./review.js');
- vi.doUnmock('./instances.js');
- vi.doUnmock('./backup.js');
- vi.doUnmock('./notifications.js');
- vi.doUnmock('./character.js');
- rmSync(dataDir, { recursive: true, force: true });
- });
-
- // Load the service with the data dir redirected and all data-source services
- // mocked. `sources`/`settings` overrides let individual tests vary inputs.
- async function loadService({ settings = {}, sources = {}, reject = [], fileOverrides = {} } = {}) {
- // Honor an explicitly-provided override (including `null`) over the default;
- // `key in sources` distinguishes "not provided" from "provided as null".
- const src = (key, fallback) => (key in sources ? sources[key] : fallback);
- // A getter named in `reject` rejects (simulating a failed source) so the
- // service's .catch(() => FAILED) sentinel path is exercised.
- const mock = (key, value) => reject.includes(key)
- ? vi.fn().mockRejectedValue(new Error(`${key} unavailable`))
- : vi.fn().mockResolvedValue(value);
- vi.doMock('../lib/fileUtils.js', async (importOriginal) => {
- const actual = await importOriginal();
- return { ...actual, PATHS: { ...actual.PATHS, data: dataDir }, ...fileOverrides };
- });
- vi.doMock('./settings.js', () => ({
- getSettings: vi.fn().mockResolvedValue(settings),
- }));
- vi.doMock('./apps.js', () => ({
- getAppStatuses: mock('appStatuses', src('appStatuses', [
- { id: 'a1', name: 'App One', type: 'express', repoPath: '/repos/a1', overallStatus: 'online', managed: true },
- { id: 'a2', name: 'App Two', type: 'express', repoPath: '/repos/a2', overallStatus: 'stopped', managed: true },
- ])),
- }));
- vi.doMock('./cos.js', () => ({
- getStatus: mock('cosStatus', src('cosStatus', {
- running: true, paused: false, activeAgents: 2, pausedAgents: 0,
- stats: { tasksCompleted: 7 },
- })),
- }));
- vi.doMock('./cosAgentLifecycle.js', () => ({
- getAgents: mock('agents', src('agents', [
- { id: 'agent-1', status: 'running', workspacePath: '/repos/a1/sub' },
- { id: 'agent-2', status: 'completed', workspacePath: '/repos/a2' },
- ])),
- }));
- vi.doMock('./cosTaskStore.js', () => ({
- getCosTasks: mock('taskState', src('taskState', {
- tasks: [{ status: 'pending' }, { status: 'pending' }, { status: 'in_progress' }],
- })),
- }));
- vi.doMock('./review.js', () => ({
- getPendingCounts: mock('reviewCounts', src('reviewCounts', { total: 4, alert: 1, todo: 3 })),
- }));
- vi.doMock('./instances.js', () => ({
- getSelf: mock('self', src('self', { instanceId: 'inst-1', name: 'void' })),
- getPeers: mock('peers', src('peers', [
- { status: 'online' }, { status: 'offline' },
- ])),
- }));
- vi.doMock('./backup.js', () => ({
- getState: mock('backupState', src('backupState', { status: 'success', lastRun: '2026-06-05T00:00:00.000Z' })),
- }));
- vi.doMock('./notifications.js', () => ({
- getCountsByType: mock('notifCounts', src('notifCounts', { total: 5, unread: 3, byType: {} })),
- }));
- vi.doMock('./character.js', () => ({
- getCharacter: mock('character', src('character', { level: 4 })),
- }));
- return import('./openWorldSnapshots.js');
- }
-
- it('captures a compact frame and appends it as JSONL', async () => {
- const svc = await loadService();
- const frame = await svc.captureSnapshot();
-
- expect(frame.schemaVersion).toBe(svc.SNAPSHOT_SCHEMA_VERSION);
- expect(typeof frame.ts).toBe('string');
- expect(frame.apps).toEqual([
- { id: 'a1', name: 'App One', status: 'online' },
- { id: 'a2', name: 'App Two', status: 'stopped' },
- ]);
- // Only the running agent is captured, mapped to its app via repoPath prefix.
- expect(frame.assignments).toEqual([
- { agentId: 'agent-1', appId: 'a1', status: 'running' },
- ]);
- expect(frame.counts).toMatchObject({
- appsOnline: 1, appsTotal: 2, agentsActive: 2, tasksCompleted: 7,
- tasksPending: 2, tasksInProgress: 1,
- peersOnline: 1, peersTotal: 2, notificationsUnread: 3, reviewTotal: 4,
- });
- expect(frame.cos).toEqual({ running: true, paused: false });
- expect(frame.backup).toEqual({ status: 'success', lastRun: '2026-06-05T00:00:00.000Z' });
- expect(frame.character).toEqual({ level: 4 });
- expect(frame.instance).toEqual({ id: 'inst-1', name: 'void' });
- // Health triad — cpu/mem/disk are number-or-null (real values from the host).
- expect(frame.health).toHaveProperty('cpuPercent');
- expect(frame.health).toHaveProperty('memPercent');
- expect(frame.health).toHaveProperty('diskPercent');
- for (const v of [frame.health.cpuPercent, frame.health.memPercent, frame.health.diskPercent]) {
- expect(v === null || typeof v === 'number').toBe(true);
- }
-
- expect(existsSync(snapshotsFile)).toBe(true);
- expect(readLines(snapshotsFile)).toHaveLength(1);
- });
-
- it('resolves config defaults when settings absent, and overrides when present', async () => {
- const svcDefault = await loadService();
- expect(await svcDefault.getSnapshotConfig()).toEqual(svcDefault.DEFAULT_SNAPSHOT_CONFIG);
-
- vi.resetModules();
- const svcCustom = await loadService({
- settings: { openWorldSnapshots: { enabled: false, intervalMinutes: 15, maxSnapshots: 50 } },
- });
- expect(await svcCustom.getSnapshotConfig()).toEqual({ enabled: false, intervalMinutes: 15, maxSnapshots: 50 });
- });
-
- it('falls back to defaults field-by-field for invalid settings values', async () => {
- const svc = await loadService({
- settings: { openWorldSnapshots: { enabled: 'yes', intervalMinutes: 0, maxSnapshots: 5 } },
- });
- // enabled non-boolean → default true; intervalMinutes <1 → default; maxSnapshots <10 → default
- expect(await svc.getSnapshotConfig()).toEqual(svc.DEFAULT_SNAPSHOT_CONFIG);
- });
-
- it('enforces the maxSnapshots cap by dropping the oldest frames', async () => {
- const svc = await loadService({ settings: { openWorldSnapshots: { maxSnapshots: 10 } } });
-
- for (let i = 0; i < 13; i += 1) {
- await svc.captureSnapshot();
- }
-
- const lines = readLines(snapshotsFile);
- expect(lines).toHaveLength(10);
-
- const { total, snapshots } = await svc.getSnapshots();
- expect(total).toBe(10);
- expect(snapshots).toHaveLength(10);
- // Chronological (oldest-first) and timestamps non-decreasing.
- for (let i = 1; i < snapshots.length; i += 1) {
- expect(Date.parse(snapshots[i].ts)).toBeGreaterThanOrEqual(Date.parse(snapshots[i - 1].ts));
- }
- });
-
- it('degrades a null data source to a sentinel rather than dropping the frame', async () => {
- const svc = await loadService({
- sources: { character: null, backupState: null, self: null },
- });
- const frame = await svc.captureSnapshot();
- expect(frame.character).toEqual({ level: null });
- expect(frame.backup).toBeNull();
- expect(frame.instance).toBeNull();
- // Frame still recorded despite missing sources.
- expect(readLines(snapshotsFile)).toHaveLength(1);
- });
-
- it('records null (not zero/empty) when a source throws, distinguishing failure from a real empty read', async () => {
- const svc = await loadService({ reject: ['appStatuses', 'peers', 'reviewCounts'] });
- const frame = await svc.captureSnapshot();
-
- // Failed array sources → null, NOT [] — so the scrubber can skip the frame
- // rather than rendering a transient outage as "all buildings demolished."
- expect(frame.apps).toBeNull();
- // Counts derived from a failed source are null, not a misleading 0.
- expect(frame.counts.appsOnline).toBeNull();
- expect(frame.counts.appsTotal).toBeNull();
- expect(frame.counts.peersOnline).toBeNull();
- expect(frame.counts.peersTotal).toBeNull();
- expect(frame.counts.reviewTotal).toBeNull();
- // Frame is still captured (partial > missing).
- expect(readLines(snapshotsFile)).toHaveLength(1);
- });
-
- it('distinguishes a real empty read (0) from a failed one (null)', async () => {
- const svc = await loadService({ sources: { appStatuses: [], peers: [], reviewCounts: { total: 0 } } });
- const frame = await svc.captureSnapshot();
- // Successful but empty → real zeros, not null.
- expect(frame.apps).toEqual([]);
- expect(frame.counts.appsOnline).toBe(0);
- expect(frame.counts.appsTotal).toBe(0);
- expect(frame.counts.peersOnline).toBe(0);
- expect(frame.counts.reviewTotal).toBe(0);
- });
-
- it('getSnapshots honors limit (most-recent N) and since filters', async () => {
- const svc = await loadService();
- const frames = [];
- for (let i = 0; i < 5; i += 1) frames.push(await svc.captureSnapshot());
-
- const limited = await svc.getSnapshots({ limit: 2 });
- expect(limited.total).toBe(5);
- expect(limited.snapshots).toHaveLength(2);
- expect(limited.snapshots[1].ts).toBe(frames[4].ts);
-
- const since = frames[3].ts;
- const sinceResult = await svc.getSnapshots({ since });
- expect(sinceResult.snapshots.every(f => Date.parse(f.ts) >= Date.parse(since))).toBe(true);
- });
-
- it('maps an agent to the longest matching repoPath, not a sibling-prefix app', async () => {
- const svc = await loadService({
- sources: {
- // App order deliberately puts the prefix-only app FIRST; boundary +
- // longest-match must still pick the nested app the agent actually works in.
- appStatuses: [
- { id: 'proj', name: 'Proj', repoPath: '/repos/proj', overallStatus: 'online' },
- { id: 'project', name: 'Project', repoPath: '/repos/project', overallStatus: 'online' },
- ],
- agents: [
- { id: 'agent-1', status: 'running', workspacePath: '/repos/project/sub/dir' },
- // A bare-prefix path that is NOT under /repos/proj (no boundary) maps to nothing.
- { id: 'agent-2', status: 'running', workspacePath: '/repos/projectile' },
- ],
- },
- });
- const frame = await svc.captureSnapshot();
- expect(frame.assignments).toEqual([
- { agentId: 'agent-1', appId: 'project', status: 'running' },
- { agentId: 'agent-2', appId: null, status: 'running' },
- ]);
- });
-
- it('getSnapshots({ limit: 0 }) returns no frames (not the whole series)', async () => {
- const svc = await loadService();
- for (let i = 0; i < 3; i += 1) await svc.captureSnapshot();
- const result = await svc.getSnapshots({ limit: 0 });
- expect(result.total).toBe(3);
- expect(result.snapshots).toEqual([]);
- });
-
- it('serializes concurrent captures so none are lost', async () => {
- const svc = await loadService();
- await Promise.all(Array.from({ length: 12 }, () => svc.captureSnapshot()));
- expect(readLines(snapshotsFile)).toHaveLength(12);
- });
-});
diff --git a/server/services/voice/fineTuning.js b/server/services/voice/fineTuning.js
index 0c361141f6..8004ba238a 100644
--- a/server/services/voice/fineTuning.js
+++ b/server/services/voice/fineTuning.js
@@ -73,8 +73,12 @@ const serializableJob = ({
* `error` can both fire for one child and each rewrites the same file.
*/
const persistJob = (jobState) => {
+ // Capture the durable state when this write is queued. Otherwise a checkpoint
+ // write that runs after a later terminal event serializes the mutable current
+ // object and can race the terminal write out of order.
+ const record = structuredClone(serializableJob(jobState));
jobState.persistChain = (jobState.persistChain || Promise.resolve())
- .then(() => atomicWrite(jobRecordPath(jobState.profileId, jobState.id), serializableJob(jobState)))
+ .then(() => atomicWrite(jobRecordPath(jobState.profileId, jobState.id), record))
.catch((err) => console.error(`❌ Failed to persist fine-tune job ${jobState.id}: ${err.message}`));
return jobState.persistChain;
};