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(city): apply review cleanups across the redesign

[._.]/ Adam Eivybc3c37e52ca7
diff --git a/client/src/components/city/Borough.jsx b/client/src/components/city/Borough.jsx
index 43fd2bbe6a..f85babf17d 100644
--- a/client/src/components/city/Borough.jsx
+++ b/client/src/components/city/Borough.jsx
@@ -1,5 +1,5 @@
import { useMemo } from 'react';
-import { getBuildingHeight, BOROUGH_PARAMS, cityDayMix } from './cityConstants';
+import { getBuildingHeight, BOROUGH_PARAMS, cityDayMix, cityShowDetail } from './cityConstants';
import { hashString } from '../../utils/hashString';
import Building from './Building';
import AgentEntity from './AgentEntity';
@@ -46,7 +46,7 @@ export default function Borough({ app, position, agentMap, onBuildingClick, play
agentCount={agents.length}
onClick={() => onBuildingClick?.(app)}
playSfx={playSfx}
- rooftops={(settings?.particleDensity ?? 1) > 0.5}
+ rooftops={cityShowDetail(settings)}
neonBrightness={neonBrightness}
isProximity={isProximity}
dimmed={dimmed}
diff --git a/client/src/components/city/CityDataHarbor.jsx b/client/src/components/city/CityDataHarbor.jsx
index f898ee9607..d19b2624c8 100644
--- a/client/src/components/city/CityDataHarbor.jsx
+++ b/client/src/components/city/CityDataHarbor.jsx
@@ -5,7 +5,7 @@ import { PIXEL_FONT_URL, cityDayMix } from './cityConstants';
import { useCityPalette } from './CityPaletteContext';
import CityLabel from './CityLabel';
import { computeDataHarbor, DATA_HARBOR } from '../../utils/cityDataHarbor';
-import { WORLD } from '../../utils/cityPlan';
+import { WORLD, AVENUE_WIDTH } from '../../utils/cityPlan';
// CyberCity's Data Harbor: a pier district over the bay (master plan, north shore) that
// renders GET /api/city/introspection — the database quay (one disk-stack silo per Postgres
@@ -27,19 +27,21 @@ function HarborHoloCard({ selected }) {
<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>
- {kind === 'silo' ? (
- <div className="text-[9px] font-pixel tracking-wide mt-1 space-y-0.5 text-gray-300">
- <div>{data.rowEstimate.toLocaleString()} rows</div>
- <div>{data.bytesLabel}</div>
- {data.hasEmbedding && <div className="text-pink-400">pgvector embeddings</div>}
- </div>
- ) : (
- <div className="text-[9px] font-pixel tracking-wide mt-1 space-y-0.5 text-gray-300">
- <div>{data.sublabel}</div>
- <div>{data.files.toLocaleString()} files</div>
- <div className="text-gray-500">data/{data.name === '(root)' ? '' : data.name}</div>
- </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>
);
@@ -47,7 +49,7 @@ function HarborHoloCard({ selected }) {
// 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, onSelect, registerRing, dayMix }) {
+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;
@@ -67,8 +69,8 @@ function TableSilo({ silo, onSelect, registerRing, dayMix }) {
<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={silo.color}
- emissive={silo.color}
+ 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}
@@ -81,10 +83,10 @@ function TableSilo({ silo, onSelect, registerRing, dayMix }) {
{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={silo.color} transparent opacity={0.7} toneMapped={false} />
+ <meshBasicMaterial color={color} transparent opacity={0.7} toneMapped={false} />
</mesh>
)}
- <CityLabel position={[0, silo.height + 1.5, 0]} fontSize={0.42} color={silo.color} dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={7}>
+ <CityLabel 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}
</CityLabel>
<CityLabel position={[0, silo.height + 1.05, 0]} fontSize={0.3} color="#94a3b8" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={7}>
@@ -164,22 +166,26 @@ function PierDeck({ x, z, width, depth, tintStructure }) {
}
export default function CityDataHarbor({ introspection, settings }) {
- const { accent, tintStructure } = useCityPalette();
+ const { accent, tintStructure, getAccentColor } = useCityPalette();
const district = useMemo(() => computeDataHarbor(introspection), [introspection]);
const [selected, setSelected] = useState(null);
const dayMix = cityDayMix(settings);
const animate = (settings?.particleDensity ?? 1) >= 0.5;
- // All pgvector rings spin from one frame callback (single mutation site).
- const ringRefs = useRef([]);
- ringRefs.current = [];
- const registerRing = useCallback((el) => { if (el) ringRefs.current.push(el); }, []);
+ // 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) ring.rotation.z = t * 0.6;
+ 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;
@@ -189,31 +195,35 @@ export default function CityDataHarbor({ introspection, settings }) {
if (district.empty) return null;
const [bx, , bz] = district.base;
- const { silos, racks, obelisk, totals, overflow, dbDown } = district;
+ 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. */}
- <PierDeck x={bx} z={(WORLD.shorelineZ + bz) / 2} width={4.6} depth={Math.abs(bz - WORLD.shorelineZ) + 2} tintStructure={tintStructure} />
- {/* West quay (database silos) + east yard (archive racks). */}
- <PierDeck x={bx - 11} z={bz - 0.6} width={15} depth={11} tintStructure={tintStructure} />
- <PierDeck x={bx + 11} z={bz - 0.6} width={15} depth={11} tintStructure={tintStructure} />
+ {/* 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={registerRing}
+ 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={[bx - 11, DATA_HARBOR.deckY, bz - 0.6]}>
+ <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} />
@@ -237,7 +247,7 @@ export default function CityDataHarbor({ introspection, settings }) {
{/* Migration obelisk at the pier head. */}
{obelisk && (
- <group position={[bx, DATA_HARBOR.deckY, bz - 7]}>
+ <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} />
diff --git a/client/src/components/city/CityGround.jsx b/client/src/components/city/CityGround.jsx
index d288d1a268..0dfe02ecfa 100644
--- a/client/src/components/city/CityGround.jsx
+++ b/client/src/components/city/CityGround.jsx
@@ -9,8 +9,8 @@ import { WORLD } from '../../utils/cityPlan';
// The city ground stops at the master plan's shoreline (z = WORLD.shorelineZ) — the bay
// (CityWater) 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 = 60;
-const GROUND_DEPTH = GROUND_HALF - WORLD.shorelineZ; // shoreline → +60
+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
@@ -115,7 +115,7 @@ export default function CityGround({ settings }) {
<group>
{/* Reflective dark ground plane */}
{reflectionsEnabled && (
- <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, -0.02, GROUND_CENTER_Z]}>
+ <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, WORLD.groundY, GROUND_CENTER_Z]}>
<planeGeometry args={[GROUND_HALF * 2, GROUND_DEPTH]} />
<meshStandardMaterial
ref={groundMatRef}
diff --git a/client/src/components/city/CityLandscape.jsx b/client/src/components/city/CityLandscape.jsx
index 09895d48bc..823a8c2e61 100644
--- a/client/src/components/city/CityLandscape.jsx
+++ b/client/src/components/city/CityLandscape.jsx
@@ -2,6 +2,7 @@ import { useEffect, useMemo } from 'react';
import * as THREE from 'three';
import { cityDayMix, mixHex, seededRand, smoothstepRange } from './cityConstants';
import { useCityPalette } from './CityPaletteContext';
+import { WORLD } from '../../utils/cityPlan';
const TERRAIN_SIZE = 2400;
const MOUNTAIN_INNER_RADIUS = 560;
@@ -89,7 +90,7 @@ function TerrainPlane({ dayMix, accent }) {
return (
<mesh
rotation={[-Math.PI / 2, 0, 0]}
- position={[0, -0.08, 0]}
+ position={[0, WORLD.terrainY, 0]}
material={material}
frustumCulled={false}
>
diff --git a/client/src/components/city/CityStreetProps.jsx b/client/src/components/city/CityStreetProps.jsx
index 98b06e4e83..9856cecb58 100644
--- a/client/src/components/city/CityStreetProps.jsx
+++ b/client/src/components/city/CityStreetProps.jsx
@@ -1,31 +1,40 @@
import { useMemo, useLayoutEffect, useRef } from 'react';
import * as THREE from 'three';
-import { cityDayMix, mixHex } from './cityConstants';
+import { cityDayMix, cityShowDetail, mixHex } from './cityConstants';
import { useCityPalette } from './CityPaletteContext';
import { computeStreets, computeStreetProps } from '../../utils/cityPlan';
// Street furniture from the master plan: lamp posts pooling light along every street and
-// holo-trees ringing the AI Core plaza. Everything is instanced — four draw calls cover
+// holo-trees ringing the AI Core plaza. Everything is instanced — five draw calls cover
// the whole town regardless of lamp count. Lamp light pools are faked with emissive heads
// + additive ground discs (the city's established no-real-point-lights pattern).
// Quality-gated: the low preset renders streets only (this component returns null).
const dummy = new THREE.Object3D();
-// One instanced mesh whose matrices are written once from `placements`.
-function Instances({ placements, geometryArgs, geometry, position, children }) {
+// 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 POOL_POS = [0, 0.035, 0];
+const TRUNK_POS = [0, 0.55, 0];
+const CANOPY_POS = [0, 1.9, 0];
+
+// 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 Instances({ placements, geometry, geometryArgs, position, flat = false, children }) {
const ref = useRef();
useLayoutEffect(() => {
if (!ref.current) return;
placements.forEach((p, i) => {
- dummy.position.set(p.x + (position?.[0] ?? 0), position?.[1] ?? 0, p.z + (position?.[2] ?? 0));
- dummy.rotation.set(0, p.seed != null ? (p.seed * 1.7) % (Math.PI * 2) : 0, 0);
+ 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);
dummy.updateMatrix();
ref.current.setMatrixAt(i, dummy.matrix);
});
ref.current.instanceMatrix.needsUpdate = true;
- }, [placements, position]);
+ }, [placements, position, flat]);
return (
<instancedMesh ref={ref} args={[undefined, undefined, placements.length]} frustumCulled={false}>
@@ -38,28 +47,6 @@ function Instances({ placements, geometryArgs, geometry, position, children }) {
);
}
-// The glow discs lie flat — they need their own matrix writer with a rotation.
-function FlatInstances({ placements, radius, children }) {
- const ref = useRef();
- useLayoutEffect(() => {
- if (!ref.current) return;
- placements.forEach((p, i) => {
- dummy.position.set(p.x, 0.035, p.z);
- dummy.rotation.set(-Math.PI / 2, 0, 0);
- dummy.scale.setScalar(1);
- dummy.updateMatrix();
- ref.current.setMatrixAt(i, dummy.matrix);
- });
- ref.current.instanceMatrix.needsUpdate = true;
- }, [placements]);
- return (
- <instancedMesh ref={ref} args={[undefined, undefined, placements.length]} frustumCulled={false}>
- <circleGeometry args={[radius, 16]} />
- {children}
- </instancedMesh>
- );
-}
-
export default function CityStreetProps({ settings }) {
const { accent, tintStructure } = useCityPalette();
const dayMix = cityDayMix(settings);
@@ -71,7 +58,7 @@ export default function CityStreetProps({ settings }) {
}, [density]);
// Low preset: streets only, no furniture.
- if (density <= 0.5 || (props.lamps.length === 0 && props.trees.length === 0)) return null;
+ if (!cityShowDetail(settings) || (props.lamps.length === 0 && props.trees.length === 0)) return null;
const lampGlow = mixHex(accent, '#fff7d6', 0.35);
const headOpacity = 0.95 * (1 - dayMix) + 0.4 * dayMix; // lamps rest by day
@@ -80,16 +67,16 @@ export default function CityStreetProps({ settings }) {
return (
<group>
{/* Lamp poles */}
- <Instances placements={props.lamps} geometry="cylinder" geometryArgs={[0.05, 0.08, 3.4, 6]} position={[0, 1.7, 0]}>
+ <Instances placements={props.lamps} geometry="cylinder" geometryArgs={[0.05, 0.08, 3.4, 6]} position={POLE_POS}>
<meshStandardMaterial color={tintStructure('#141b2c')} roughness={0.7} metalness={0.45} />
</Instances>
{/* Lamp heads — emissive spheres standing in for point lights */}
- <Instances placements={props.lamps} geometry="sphere" geometryArgs={[0.16, 10, 10]} position={[0, 3.45, 0]}>
+ <Instances placements={props.lamps} geometry="sphere" geometryArgs={[0.16, 10, 10]} position={HEAD_POS}>
<meshBasicMaterial color={lampGlow} transparent opacity={headOpacity} toneMapped={false} />
</Instances>
{/* Faked light pools on the pavement */}
{poolOpacity > 0.005 && (
- <FlatInstances placements={props.lamps} radius={1.7}>
+ <Instances placements={props.lamps} geometry="circle" geometryArgs={[1.7, 16]} position={POOL_POS} flat>
<meshBasicMaterial
color={lampGlow}
transparent
@@ -97,14 +84,14 @@ export default function CityStreetProps({ settings }) {
blending={THREE.AdditiveBlending}
depthWrite={false}
/>
- </FlatInstances>
+ </Instances>
)}
{/* Holo-tree trunks around the plaza */}
- <Instances placements={props.trees} geometry="cylinder" geometryArgs={[0.07, 0.1, 1.1, 5]} position={[0, 0.55, 0]}>
+ <Instances placements={props.trees} geometry="cylinder" geometryArgs={[0.07, 0.1, 1.1, 5]} position={TRUNK_POS}>
<meshStandardMaterial color={tintStructure('#101626')} roughness={0.8} />
</Instances>
{/* Holo-tree canopies — wireframe polyhedra, the city's "digital foliage" */}
- <Instances placements={props.trees} geometry="icosahedron" geometryArgs={[0.8, 1]} position={[0, 1.9, 0]}>
+ <Instances placements={props.trees} geometry="icosahedron" geometryArgs={[0.8, 1]} position={CANOPY_POS}>
<meshBasicMaterial
color={mixHex(accent, '#22c55e', 0.45)}
wireframe
diff --git a/client/src/components/city/CityStreets.jsx b/client/src/components/city/CityStreets.jsx
index 89466fd7cd..64d22fb3d8 100644
--- a/client/src/components/city/CityStreets.jsx
+++ b/client/src/components/city/CityStreets.jsx
@@ -78,7 +78,7 @@ export default function CityStreets({ settings }) {
// 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 || id === 'aiCore') continue;
+ 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);
}
diff --git a/client/src/components/city/CityTransitLoop.jsx b/client/src/components/city/CityTransitLoop.jsx
index fb7bc66f99..86f4b4e259 100644
--- a/client/src/components/city/CityTransitLoop.jsx
+++ b/client/src/components/city/CityTransitLoop.jsx
@@ -1,7 +1,7 @@
import { useMemo, useRef, useEffect } from 'react';
import { useFrame } from '@react-three/fiber';
import * as THREE from 'three';
-import { cityDayMix, mixHex } from './cityConstants';
+import { cityDayMix, cityShowDetail, mixHex } from './cityConstants';
import { useCityPalette } from './CityPaletteContext';
import { TRANSIT } from '../../utils/cityPlan';
@@ -15,7 +15,7 @@ const TRAM_SIZE = [0.9, 0.5, 0.42];
export default function CityTransitLoop({ settings }) {
const { accent, tintStructure } = useCityPalette();
const dayMix = cityDayMix(settings);
- const showTrams = (settings?.particleDensity ?? 1) > 0.5;
+ const showTrams = cityShowDetail(settings);
const curve = useMemo(() => {
const points = TRANSIT.stops.map((s) => new THREE.Vector3(...s.point));
diff --git a/client/src/components/city/CityWater.jsx b/client/src/components/city/CityWater.jsx
index ade5622717..838d7664b1 100644
--- a/client/src/components/city/CityWater.jsx
+++ b/client/src/components/city/CityWater.jsx
@@ -49,7 +49,6 @@ export default function CityWater({ settings }) {
const waveTex = useMemo(() => makeWaveTexture(), []);
useEffect(() => () => waveTex.dispose(), [waveTex]);
- const matRef = useRef();
const shimmerRef = useRef();
const waterColor = mixHex(NIGHT_WATER, DAY_WATER, dayMix);
@@ -76,7 +75,6 @@ export default function CityWater({ settings }) {
<mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, WORLD.waterY, centerZ]}>
<planeGeometry args={[span * 2, span]} />
<meshStandardMaterial
- ref={matRef}
color={waterColor}
roughness={0.18}
metalness={0.55}
diff --git a/client/src/components/city/cityConstants.js b/client/src/components/city/cityConstants.js
index c31c2319fb..b1098ef701 100644
--- a/client/src/components/city/cityConstants.js
+++ b/client/src/components/city/cityConstants.js
@@ -215,6 +215,11 @@ export const cityDayMix = (settings) => {
return smoothstepRange(0.35, 1, preset?.daylightFactor ?? 0);
};
+// True when the active quality preset is above "low" (particleDensity 0.5) — the shared
+// gate for optional set dressing (rooftop kits, street furniture, transit trams). The
+// boundary is exact-0.5-excluded on purpose: the low preset renders structure only.
+export const cityShowDetail = (settings) => (settings?.particleDensity ?? 1) > 0.5;
+
// 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 no outline, so the established look is untouched. As day
diff --git a/client/src/pages/CyberCity.jsx b/client/src/pages/CyberCity.jsx
index cfa26414ef..c71cfc32a2 100644
--- a/client/src/pages/CyberCity.jsx
+++ b/client/src/pages/CyberCity.jsx
@@ -233,10 +233,15 @@ function CyberCityInner() {
// 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. Same last-good-snapshot semantics as the fetches above.
+ // 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.getCityIntrospection({ 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),
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index e0b0b5a476..b5c4953aea 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -22,7 +22,7 @@ grep -i "what you want to do" client/src/utils/README.md
| Module | Purpose |
|---|---|
-| `formatters` | Date/time/duration/byte/word formatters (`formatBytes`, `timeAgo`, `formatTimecode`, `formatDurationMs`, `formatDateShort`, `parseTimeoutMs`, `formatCooldown`, `parseSizeGb`, `recommendedRamGb`, …) plus timeout-input bounds and `getAppName`. Do not re-define formatters inside components. |
+| `formatters` | Date/time/duration/byte/word formatters (`formatBytes`, `formatCompactCount`, `timeAgo`, `formatTimecode`, `formatDurationMs`, `formatDateShort`, `parseTimeoutMs`, `formatCooldown`, `parseSizeGb`, `recommendedRamGb`, …) plus timeout-input bounds and `getAppName`. Do not re-define formatters inside components. |
| `cronHelpers` | Cron preset list, `isCronExpression` detection, and `describeCron` human-readable rendering. |
| `timeWindow` | Time-of-day window math (`isInTimeWindow`, `timeStringToMinutes`) and morning-layout auto-switch helpers (`pickActiveLayoutId`, `recordManualLayoutPick`). |
diff --git a/client/src/utils/cityDataHarbor.js b/client/src/utils/cityDataHarbor.js
index ad5a1d8b65..edd6a56d20 100644
--- a/client/src/utils/cityDataHarbor.js
+++ b/client/src/utils/cityDataHarbor.js
@@ -6,20 +6,23 @@
// 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/city/introspection; `db: null` (unreachable) renders as a dimmed offline quay,
-// distinct from a reachable-but-empty database. No three.js / React imports so the topology
-// is unit-testable (mirrors cityMemoryDistrict.js / cityTaskQueue.js).
+// 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 cityMemoryDistrict.js).
-import { hashString } from './hashString';
-import { formatBytes } from './formatters';
+import { formatBytes, formatCompactCount } from './formatters';
+import { scaleMetricToHeight } from './cityDistrictLayout';
import { PARCELS } from './cityPlan';
export const DATA_HARBOR = {
base: PARCELS.dataHarbor.anchor, // pier district over the bay (see cityPlan.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
- siloRowGap: 4.4, // z-distance between the two silo rows
+ 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,
@@ -33,45 +36,41 @@ export const DATA_HARBOR = {
rackSlats: 8, // emissive slat rows per rack; lit count tracks the fill ratio
};
-// Deterministic silo color per table name — the city's neon spread, hashed so a table keeps
-// its color across refetches and installs.
-const PALETTE = ['#06b6d4', '#ec4899', '#8b5cf6', '#22c55e', '#f59e0b', '#3b82f6', '#f43f5e', '#a855f7'];
-export function tableColor(name) {
- return PALETTE[hashString(String(name || '')) % PALETTE.length];
-}
-
const clamp = (n, lo, hi) => Math.min(hi, Math.max(lo, n));
-// log2-scale `value` into [0, 1] against `max` (both floored at 0). A zero max yields 0.
+// 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 v = Math.max(0, Number.isFinite(value) ? value : 0);
- const m = Math.max(0, Number.isFinite(max) ? max : 0);
- if (m <= 0) return 0;
- return clamp(Math.log2(1 + v) / Math.log2(1 + m), 0, 1);
+ const scaledMax = scaleMetricToHeight(max, { k: 1 });
+ if (scaledMax <= 0) return 0;
+ return clamp(scaleMetricToHeight(value, { k: 1 }) / scaledMax, 0, 1);
};
-const shortCount = (n) => {
- if (!Number.isFinite(n)) return '0';
- if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
- if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;
- return String(n);
+// 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). Two rows: the heavyweights up front (bay side), the rest behind.
+// 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;
- const perRow = Math.ceil(visible.length / 2);
return visible.map((table, i) => {
- const row = i < perRow ? 0 : 1;
- const col = row === 0 ? i : i - perRow;
- const rowCount = row === 0 ? perRow : visible.length - perRow;
- const rowWidth = (rowCount - 1) * DATA_HARBOR.siloSpacing;
+ 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,
@@ -81,41 +80,36 @@ function computeSilos(tables) {
+ logRatio(table.totalBytes, maxBytes) * (DATA_HARBOR.maxDiskRadius - DATA_HARBOR.minDiskRadius);
return {
name: table.name,
- x: bx - 11 + col * DATA_HARBOR.siloSpacing - rowWidth / 2 + (row === 0 ? 0 : DATA_HARBOR.siloSpacing / 2),
- z: bz + (row === 0 ? 1.5 : 1.5 - DATA_HARBOR.siloRowGap),
+ x: bx - DATA_HARBOR.quayOffsetX + dx,
+ z: bz + dz,
diskCount,
diskRadius,
height: diskCount * (DATA_HARBOR.diskHeight + DATA_HARBOR.diskGap),
hasEmbedding: Boolean(table.hasEmbedding),
- color: tableColor(table.name),
rowEstimate: table.rowEstimate ?? 0,
totalBytes: table.totalBytes ?? 0,
label: String(table.name || '').toUpperCase(),
- sublabel: `${shortCount(table.rowEstimate ?? 0)} ROWS`,
+ 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). Two rows on the east pier — a tight container yard.
+// 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;
- const perRow = Math.ceil(visible.length / 2);
return visible.map((domain, i) => {
- const row = i < perRow ? 0 : 1;
- const col = row === 0 ? i : i - perRow;
- const rowCount = row === 0 ? perRow : visible.length - perRow;
- const rowWidth = (rowCount - 1) * DATA_HARBOR.rackSpacing;
+ const { dx, dz } = twoRowOffset(i, visible.length, DATA_HARBOR.rackSpacing);
const fillRatio = logRatio(domain.bytes, maxBytes);
return {
name: domain.name,
- x: bx + 11 + col * DATA_HARBOR.rackSpacing - rowWidth / 2,
- z: bz + (row === 0 ? 1.5 : 1.5 - DATA_HARBOR.siloRowGap),
+ x: bx + DATA_HARBOR.quayOffsetX + dx,
+ z: bz + dz,
width: DATA_HARBOR.rackWidth,
depth: DATA_HARBOR.rackDepth,
height: DATA_HARBOR.rackHeight,
@@ -129,6 +123,20 @@ function computeRacks(domains) {
});
}
+// 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")
@@ -141,14 +149,23 @@ export function computeDataHarbor(introspection) {
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: computeSilos(tables),
- racks: computeRacks(domains),
+ 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 }
+ ? { applied: db.migrations.applied ?? 0, lastApplied: db.migrations.lastApplied ?? null, x: bx, z: bz - 7 }
: null,
totals: {
tableCount: tables.length,
diff --git a/client/src/utils/cityDataHarbor.test.js b/client/src/utils/cityDataHarbor.test.js
index d04f9d1f54..5ca72d6cea 100644
--- a/client/src/utils/cityDataHarbor.test.js
+++ b/client/src/utils/cityDataHarbor.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { computeDataHarbor, tableColor, DATA_HARBOR } from './cityDataHarbor';
+import { computeDataHarbor, DATA_HARBOR } from './cityDataHarbor';
import { PARCELS, isInWater, WORLD } from './cityPlan';
const table = (name, rowEstimate, totalBytes, hasEmbedding = false) =>
@@ -78,17 +78,25 @@ describe('computeDataHarbor', () => {
expect(district.silos.map((s) => s.name)).not.toContain('t0');
});
- it('keeps every structure inside the harbor parcel, over the water', () => {
+ 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]) {
- expect(Math.abs(s.x - parcel.anchor[0]), s.name).toBeLessThanOrEqual(parcel.w / 2);
- expect(Math.abs(s.z - parcel.anchor[2]), s.name).toBeLessThanOrEqual(parcel.d / 2);
+ 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', () => {
@@ -103,7 +111,7 @@ describe('computeDataHarbor', () => {
it('carries totals and the migration obelisk', () => {
const district = computeDataHarbor(happyIntrospection());
- expect(district.obelisk).toEqual({ applied: 12, lastApplied: '2026-06-01T00:00:00.000Z' });
+ 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');
@@ -115,14 +123,6 @@ describe('computeDataHarbor', () => {
});
});
-describe('tableColor', () => {
- it('is stable per name and varies across names', () => {
- expect(tableColor('memories')).toBe(tableColor('memories'));
- const colors = new Set(['memories', 'catalog_scraps', 'universes', 'memory_links'].map(tableColor));
- expect(colors.size).toBeGreaterThan(1);
- });
-});
-
describe('harbor sits inside the world', () => {
it('parcel is in the bay but inside the world bound', () => {
const [x, , z] = DATA_HARBOR.base;
diff --git a/client/src/utils/cityPlan.js b/client/src/utils/cityPlan.js
index 3f0c89206b..e4c314cace 100644
--- a/client/src/utils/cityPlan.js
+++ b/client/src/utils/cityPlan.js
@@ -25,7 +25,11 @@
export const WORLD = {
bound: 180, // hard XZ world bound (matches PlayerController)
shorelineZ: -56, // land for z > shorelineZ; water (the bay) beyond
- waterY: -0.04, // water plane height — above the terrain (-0.08), below the city ground (-0.02)
+ landHalf: 60, // half-extent of the paved city ground plane (x ±landHalf, z shoreline→+landHalf)
+ // The ground y-stack, bottom to top: terrain shader < water plane < city ground.
+ terrainY: -0.08,
+ waterY: -0.04,
+ groundY: -0.02,
waterSpan: 520, // how far the water plane extends past the shoreline / to each side
};
@@ -36,7 +40,8 @@ export const WORLD = {
// 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 = {
- aiCore: { anchor: [0, 0, 0], w: 24, d: 24, label: 'AI CORE PLAZA' },
+ // 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' },
@@ -59,21 +64,30 @@ export const PARCELS = {
export const PLAZA = { center: [0, 0, 0], radius: 12, sidewalkOuter: 14.5 };
// Elevated transit loop — a closed ride through every quarter, rendered as a glowing tube
-// with trams orbiting it. Stops are pulled toward the loop's centerline (offset from each
-// parcel anchor) so the track skims districts instead of impaling their monuments.
+// 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: 9, // track height — above street props, below most rooftops
+ y: TRANSIT_Y,
+ stopPull: TRANSIT_STOP_PULL,
stops: [
- { id: 'productivity', point: [-44, 9, 24] },
- { id: 'backupVault', point: [-32, 9, -8] },
- { id: 'memory', point: [-40, 9, -27] },
- { id: 'jira', point: [-20, 9, -40] },
- { id: 'harborGate', point: [0, 9, -47] },
- { id: 'goals', point: [26, 9, -36] },
- { id: 'artifacts', point: [40, 9, -25] },
- { id: 'taskQueue', point: [32, 9, -8] },
- { id: 'health', point: [44, 9, 24] },
- { id: 'warehouse', point: [0, 9, 38] },
+ 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)
@@ -90,7 +104,9 @@ export const isInWater = (x, z, margin = 0) => z < WORLD.shorelineZ + margin;
const RING_RADIUS = 30; // octagonal ring road just outside the downtown grid
const ROAD_WIDTH = 3.2;
-const AVENUE_WIDTH = 4.6;
+// 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
diff --git a/client/src/utils/cityPlan.test.js b/client/src/utils/cityPlan.test.js
index 5ddc934f88..94ffeb78b6 100644
--- a/client/src/utils/cityPlan.test.js
+++ b/client/src/utils/cityPlan.test.js
@@ -81,6 +81,17 @@ describe('TRANSIT', () => {
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', () => {
diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.js
index 0d6b4c3cf0..0ee66b417b 100644
--- a/client/src/utils/formatters.js
+++ b/client/src/utils/formatters.js
@@ -101,6 +101,18 @@ export function timeAgo(dateStr, fallback = 'never') {
* @param {number} decimals - Number of decimal places
* @returns {string} Formatted size (e.g., "1.5 KB", "2.3 MB", "4.2 TB")
*/
+/**
+ * Compact decimal count: 950 → "950", 1200 → "1.2K", 3400000 → "3.4M".
+ * @param {number} n - Count to abbreviate
+ * @returns {string} Abbreviated count
+ */
+export function formatCompactCount(n) {
+ if (!Number.isFinite(n)) return '0';
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
+ if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;
+ return String(n);
+}
+
export function formatBytes(bytes, decimals = 1) {
if (!bytes || bytes === 0) return '0 B';
diff --git a/server/services/cityIntrospection.js b/server/services/cityIntrospection.js
index 88cdceee3b..6ff067a48f 100644
--- a/server/services/cityIntrospection.js
+++ b/server/services/cityIntrospection.js
@@ -6,24 +6,19 @@
* domain directory). Purely derived state — nothing is stored, synced, or backed
* up (see docs/STORAGE.md: transient query results need no classification).
*
- * Caching: the data/ walk can take whole seconds on a media-heavy install
- * (data/images alone holds thousands of files), so results are cached with a TTL
- * and served stale-while-revalidate — once a payload exists, callers always get
- * an immediate answer while an expired cache refreshes in the background.
- * Concurrent first calls share one in-flight build.
+ * Caching: the data/ sizing shells out to du/find per domain (via dataManager's
+ * getDataOverview — fast, but still a subprocess fan-out on a media-heavy
+ * install), so results are cached with a TTL and served stale-while-revalidate —
+ * once a payload exists, callers always get an immediate answer while an expired
+ * cache refreshes in the background. Concurrent first calls share one in-flight
+ * build.
*/
-import { readdir, stat } from 'fs/promises';
-import { join } from 'path';
-import { PATHS } from '../lib/fileUtils.js';
import { query } from '../lib/db.js';
+import { getDataOverview } from './dataManager.js';
export const INTROSPECTION_TTL_MS = 45_000;
-// Domain directories walked concurrently (each walk is itself sequential —
-// bounded I/O pressure either way).
-const WALK_CONCURRENCY = 4;
-
let cache = null;
let cacheBuiltAt = 0;
let inFlight = null;
@@ -84,66 +79,18 @@ async function buildDbSection() {
};
}
-// Recursive size/count of a directory tree. Symlinks are skipped (a link into a
-// media library shouldn't count as local data); unreadable entries are tolerated
-// per-entry so one bad file can't sink a domain.
-async function walkDir(path) {
- let bytes = 0;
- let files = 0;
- const entries = await readdir(path, { withFileTypes: true }).catch(() => []);
- for (const entry of entries) {
- if (entry.isSymbolicLink()) continue;
- const childPath = join(path, entry.name);
- if (entry.isDirectory()) {
- const sub = await walkDir(childPath);
- bytes += sub.bytes;
- files += sub.files;
- } else if (entry.isFile()) {
- const s = await stat(childPath).catch(() => null);
- if (s) {
- bytes += s.size;
- files += 1;
- }
- }
- }
- return { bytes, files };
-}
-
-// The filesystem section: each depth-1 directory under data/ becomes a domain;
-// loose top-level files roll into a "(root)" pseudo-domain. Domains sorted by
-// size so the harbor's biggest racks come first.
+// The filesystem section: each depth-1 directory under data/ becomes a domain.
+// Sizing delegates to dataManager's getDataOverview (du/find per domain — the
+// same numbers the Data page shows, so the harbor never disagrees with it).
async function buildFsSection() {
- const entries = await readdir(PATHS.data, { withFileTypes: true }).catch(() => null);
- if (!entries) return null;
-
- const dirs = [];
- let rootBytes = 0;
- let rootFiles = 0;
- for (const entry of entries) {
- if (entry.isSymbolicLink()) continue;
- if (entry.isDirectory()) {
- dirs.push(entry.name);
- } else if (entry.isFile()) {
- const s = await stat(join(PATHS.data, entry.name)).catch(() => null);
- if (s) {
- rootBytes += s.size;
- rootFiles += 1;
- }
- }
- }
-
- const domains = [];
- for (let i = 0; i < dirs.length; i += WALK_CONCURRENCY) {
- const batch = dirs.slice(i, i + WALK_CONCURRENCY);
- const results = await Promise.all(batch.map((name) => walkDir(join(PATHS.data, name))));
- batch.forEach((name, j) => domains.push({ name, ...results[j] }));
- }
- if (rootFiles > 0) domains.push({ name: '(root)', bytes: rootBytes, files: rootFiles });
+ const overview = await getDataOverview().catch(() => null);
+ if (!overview) return null;
- domains.sort((a, b) => b.bytes - a.bytes || a.name.localeCompare(b.name));
+ // getDataOverview already sorts by size descending.
+ const domains = overview.categories.map((c) => ({ name: c.key, bytes: c.size, files: c.fileCount }));
return {
domains,
- totalBytes: domains.reduce((sum, d) => sum + d.bytes, 0),
+ totalBytes: overview.totalSize,
totalFiles: domains.reduce((sum, d) => sum + d.files, 0),
};
}
diff --git a/server/services/cityIntrospection.test.js b/server/services/cityIntrospection.test.js
index 98c4720af1..70ece6cf49 100644
--- a/server/services/cityIntrospection.test.js
+++ b/server/services/cityIntrospection.test.js
@@ -1,23 +1,18 @@
/**
* Tests for the Data Harbor introspection service: DB section shape (including
- * the down-DB → `db: null` absent-vs-empty contract), the data/ domain walk
- * (sizes, file counts, symlink skip, "(root)" pseudo-domain), and the
- * TTL + stale-while-revalidate cache discipline.
+ * 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.
*/
-import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
-import { mkdtempSync, rmSync, mkdirSync, writeFileSync, symlinkSync } from 'fs';
-import { tmpdir } from 'os';
-import { join } from 'path';
-import { makePathsProxy } from '../lib/mockPathsDataRoot.js';
+import { describe, it, expect, beforeEach, vi } from 'vitest';
-const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'city-introspection-test-'));
-
-vi.mock('../lib/fileUtils.js', async (importOriginal) =>
- makePathsProxy(await importOriginal(), { dataRoot: TEST_DATA_ROOT }));
-
-const { queryMock } = vi.hoisted(() => ({ queryMock: vi.fn() }));
+const { queryMock, overviewMock } = vi.hoisted(() => ({
+ queryMock: vi.fn(),
+ overviewMock: vi.fn(),
+}));
vi.mock('../lib/db.js', () => ({ query: queryMock }));
+vi.mock('./dataManager.js', () => ({ getDataOverview: overviewMock }));
const {
getCityIntrospection,
@@ -44,28 +39,24 @@ const happyQueries = (sql) => {
throw new Error(`unexpected query: ${sql}`);
};
-const writeFixtureTree = () => {
- rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
- mkdirSync(join(TEST_DATA_ROOT, 'images', 'sub'), { recursive: true });
- mkdirSync(join(TEST_DATA_ROOT, 'brain'), { recursive: true });
- writeFileSync(join(TEST_DATA_ROOT, 'images', 'a.png'), 'aaaaa'); // 5 bytes
- writeFileSync(join(TEST_DATA_ROOT, 'images', 'sub', 'b.png'), 'bbb'); // 3 bytes
- writeFileSync(join(TEST_DATA_ROOT, 'brain', 'x.json'), 'ccccccc'); // 7 bytes
- writeFileSync(join(TEST_DATA_ROOT, 'loose.json'), 'dd'); // 2 bytes
- // A symlinked directory must not be walked (or counted).
- symlinkSync(join(TEST_DATA_ROOT, 'images'), join(TEST_DATA_ROOT, 'linked'));
-};
+const happyOverview = () => ({
+ totalSize: 3_100_800_000,
+ dataDir: 'data',
+ categories: [
+ { key: 'images', path: 'data/images', size: 3_100_000_000, fileCount: 2400 },
+ { key: 'brain', path: 'data/brain', size: 800_000, fileCount: 60 },
+ ],
+});
beforeEach(() => {
resetIntrospectionCache();
vi.restoreAllMocks();
queryMock.mockReset();
queryMock.mockImplementation(async (sql) => happyQueries(sql));
- writeFixtureTree();
+ overviewMock.mockReset();
+ overviewMock.mockResolvedValue(happyOverview());
});
-afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
-
describe('getCityIntrospection — db section', () => {
it('maps tables with coerced numbers, embedding flags, size, and migrations', async () => {
const result = await getCityIntrospection();
@@ -108,19 +99,21 @@ describe('getCityIntrospection — db section', () => {
});
describe('getCityIntrospection — fs section', () => {
- it('walks domains recursively, rolls loose files into (root), sorts by size', async () => {
+ it('maps the data overview into harbor domains + totals', async () => {
const { fs } = await getCityIntrospection();
- expect(fs.domains.map((d) => d.name)).toEqual(['images', 'brain', '(root)']);
- expect(fs.domains[0]).toEqual({ name: 'images', bytes: 8, files: 2 });
- expect(fs.domains[1]).toEqual({ name: 'brain', bytes: 7, files: 1 });
- expect(fs.domains[2]).toEqual({ name: '(root)', bytes: 2, files: 1 });
- expect(fs.totalBytes).toBe(17);
- expect(fs.totalFiles).toBe(4);
+ expect(fs.domains).toEqual([
+ { name: 'images', bytes: 3_100_000_000, files: 2400 },
+ { name: 'brain', bytes: 800_000, files: 60 },
+ ]);
+ expect(fs.totalBytes).toBe(3_100_800_000);
+ expect(fs.totalFiles).toBe(2460);
});
- it('skips symlinked directories entirely', async () => {
- const { fs } = await getCityIntrospection();
- expect(fs.domains.find((d) => d.name === 'linked')).toBeUndefined();
+ it('returns fs: null (absent) when the overview fails, keeping the db section', async () => {
+ overviewMock.mockRejectedValue(new Error('du exploded'));
+ const result = await getCityIntrospection();
+ expect(result.fs).toBeNull();
+ expect(result.db.tables).toHaveLength(3);
});
});
@@ -131,12 +124,13 @@ describe('getCityIntrospection — cache discipline', () => {
const second = await getCityIntrospection();
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 getCityIntrospection();
// Jump past the TTL without fake timers — the background rebuild does real
- // (mocked-fs) I/O that fake timers can't flush.
+ // async work that fake timers can't flush.
vi.spyOn(Date, 'now').mockReturnValue(Date.now() + INTROSPECTION_TTL_MS + 1000);
// Make the rebuild distinguishable.
@@ -146,7 +140,7 @@ describe('getCityIntrospection — cache discipline', () => {
});
const stale = await getCityIntrospection();
- expect(stale).toBe(first); // immediate stale answer, no blocking on the walk
+ 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 () => {