Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(society): retire rejected city and restore original world
rubenluetke10-beepae76945085a9
diff --git a/jarvis/ui/web/frontend/src/components/society/city/CityAssets.tsx b/jarvis/ui/web/frontend/src/components/society/city/CityAssets.tsxdeleted file mode 100644index efc5e9ef56..0000000000--- a/jarvis/ui/web/frontend/src/components/society/city/CityAssets.tsx+++ /dev/null@@ -1,290 +0,0 @@-/** Authored assets: static geometry batches, with independent moving metro parts. */-import { memo, useEffect, useMemo, useRef } from "react";-import { useFrame, useThree } from "@react-three/fiber";-import { useGLTF } from "@react-three/drei";-import {- Group,- InstancedMesh,- Matrix4,- Mesh,- MeshStandardMaterial,- Plane,- Quaternion,- Vector3,- type Material,- type Object3D,-} from "three";-import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js";-import type { Vec3 } from "./cityModel";-import { trainAt, type CitySimulation } from "./citySimulation";-import { releaseCityInstances } from "./cityInstances";-import station from "../../../../../../../../art/studies/city-realism-study/exports/station.glb";-import terminal from "../../../../../../../../art/studies/city-realism-study/exports/building.glb";-import central from "../../../../../../../../art/studies/city-realism-study/exports/central.glb";-import knowledge from "../../../../../../../../art/studies/city-realism-study/exports/knowledge.glb";-import workshop from "../../../../../../../../art/studies/city-realism-study/exports/fabrication.glb";-import communications from "../../../../../../../../art/studies/city-realism-study/exports/communications.glb";-import office from "../../../../../../../../art/studies/city-realism-study/exports/skyline-office.glb";-import tower from "../../../../../../../../art/studies/city-realism-study/exports/skyline-tower.glb";-import residence from "../../../../../../../../art/studies/city-realism-study/exports/skyline-residence.glb";-import lamp from "../../../../../../../../art/studies/city-realism-study/exports/streetlamp.glb";-import tree from "../../../../../../../../art/studies/city-realism-study/exports/tree.glb";-import metro from "../../../../../../../../art/studies/city-realism-study/exports/train.glb";-export const CITY_ASSETS = {- station,- terminal,- central,- knowledge,- workshop,- communications,- office,- tower,- residence,- lamp,- tree,- metro,-};-export interface InstancePose {- position: Vec3;- yaw?: number;- scale?: number;-}--function prepare(scene: Object3D) {- scene.updateMatrixWorld(true);- const groups = new Map<Material, Mesh[]>();- scene.traverse((object) => {- if (!(object instanceof Mesh)) return;- if (Array.isArray(object.material))- throw new Error("City GLBs must export one material per mesh primitive");- const meshes = groups.get(object.material) ?? [];- meshes.push(object);- groups.set(object.material, meshes);- });- return [...groups].map(([source, meshes]) => {- const pieces = meshes.map((mesh) =>- mesh.geometry.clone().applyMatrix4(mesh.matrixWorld),- );- const geometry = mergeGeometries(pieces);- pieces.forEach((piece) => piece.dispose());- if (!geometry) throw new Error("Incompatible city mesh attributes");- return { geometry, material: source.clone() };- });-}-export const CityAsset = memo(function CityAsset({- url,- position,- yaw = 0,- onClick,- working = false,- cutaway = false,-}: {- url: string;- position: Vec3;- yaw?: number;- onClick?: () => void;- working?: boolean;- cutaway?: boolean;-}) {- const { scene } = useGLTF(url);- const invalidate = useThree((state) => state.invalidate);- const parts = useMemo(() => prepare(scene), [scene]);- useEffect(- () => () => {- parts.forEach((part) => {- part.geometry.dispose();- part.material.dispose();- });- },- [parts],- );- useEffect(() => {- for (const { material } of parts)- if (- material instanceof MeshStandardMaterial &&- /screen/i.test(material.name)- )- material.emissiveIntensity = working ? 2 : 0.5;- }, [working, parts]);- useEffect(() => {- const planes = cutaway- ? [new Plane(new Vector3(0, -1, 0), position[1] + 4.8)]- : [];- for (const { material } of parts) {- material.clippingPlanes = planes;- material.needsUpdate = true;- }- invalidate();- }, [cutaway, parts, position, invalidate]);- return (- <group- position={position}- rotation={[0, yaw, 0]}- onClick={- onClick- ? (event) => {- // Raycasting sees geometry that the shader clipped away; let those hits pass through.- if (cutaway && event.point.y > position[1] + 4.8) return;- event.stopPropagation();- onClick();- }- : undefined- }- >- {parts.map((part, index) => (- <mesh- key={index}- geometry={part.geometry}- material={part.material}- castShadow- receiveShadow- dispose={null}- />- ))}- </group>- );-});--/** One preparation per asset family, independent instances, no copies per tree/window. */-export const CityInstances = memo(function CityInstances({- url,- poses,- shadows = false,-}: {- url: string;- poses: InstancePose[];- shadows?: boolean;-}) {- const { scene } = useGLTF(url);- const parts = useMemo(() => prepare(scene), [scene]);- const group = useMemo(() => {- const result = new Group();- const matrix = new Matrix4();- const quaternion = new Quaternion();- const scale = new Vector3();- const position = new Vector3();- for (const part of parts) {- const mesh = new InstancedMesh(- part.geometry,- part.material,- poses.length,- );- poses.forEach((pose, i) => {- quaternion.setFromAxisAngle(new Vector3(0, 1, 0), pose.yaw ?? 0);- scale.setScalar(pose.scale ?? 1);- position.set(...pose.position);- matrix.compose(position, quaternion, scale);- mesh.setMatrixAt(i, matrix);- });- mesh.instanceMatrix.needsUpdate = true;- mesh.computeBoundingSphere();- mesh.castShadow = shadows;- mesh.receiveShadow = shadows;- result.add(mesh);- }- return result;- }, [parts, poses, shadows]);- useEffect(- () => () => {- group.traverse((object) => {- if (object instanceof InstancedMesh) releaseCityInstances(object);- });- },- [group],- );- useEffect(- () => () => {- parts.forEach((part) => {- part.geometry.dispose();- part.material.dispose();- });- },- [parts],- );- return <primitive object={group} dispose={null} />;-});--export function Metro({- sim,- paused,- follow,-}: {- sim: CitySimulation;- paused: boolean;- follow: string | null;-}) {- const { scene } = useGLTF(metro);- const root = useRef<Group>(null);- const clone = useMemo(() => {- const object = scene.clone(true);- const materials = new Map<Material, Material>();- object.traverse((child) => {- if (!(child instanceof Mesh)) return;- const original = child.material as Material;- if (!materials.has(original)) {- const material = original.clone();- if (- material instanceof MeshStandardMaterial &&- material.name === "Glazing"- ) {- material.transparent = true;- material.opacity = 0.42;- material.depthWrite = false;- }- materials.set(original, material);- }- child.material = materials.get(original)!;- });- return object;- }, [scene]);- useEffect(- () => () => {- const materials = new Set<Material>();- clone.traverse((child) => {- if (child instanceof Mesh) materials.add(child.material as Material);- });- materials.forEach((m) => m.dispose());- },- [clone],- );- const doors = useMemo(- () =>- ["Door_Platform_Left", "Door_Platform_Right"]- .map((name, i) => {- const object = clone.getObjectByName(name);- return object- ? { object, x: object.position.x, sign: i ? 1 : -1 }- : null;- })- .filter((door): door is NonNullable<typeof door> => door !== null),- [clone],- );- const opening = useRef(trainAt(sim.time).doorsOpen ? 1 : 0);- const interior = useRef(false);- const plane = useMemo(() => new Plane(new Vector3(0, -1, 0), 14.5), []);- useFrame((_, dt) => {- const state = trainAt(sim.time);- const passenger = follow ? sim.citizens.get(follow) : null;- const inspect = passenger?.seat !== null && passenger?.seat !== undefined;- if (inspect !== interior.current) {- interior.current = inspect;- clone.traverse((object) => { if (object instanceof Mesh) { const material = object.material as Material; material.clippingPlanes = inspect ? [plane] : []; material.needsUpdate = true; } });- }- if (root.current) {- root.current.position.set(...state.position);- root.current.rotation.y = state.heading;- }- const target = state.doorsOpen ? 1 : 0;- if (!paused)- opening.current +=- Math.sign(target - opening.current) *- Math.min(Math.abs(target - opening.current), dt * 3);- for (const door of doors)- door.object.position.x = door.x + door.sign * opening.current * 1.25;- });- return (- <group ref={root}>- <primitive object={clone} dispose={null} />- </group>- );-}diff --git a/jarvis/ui/web/frontend/src/components/society/city/CityEnvironment.tsx b/jarvis/ui/web/frontend/src/components/society/city/CityEnvironment.tsxdeleted file mode 100644index ff0229157a..0000000000--- a/jarvis/ui/web/frontend/src/components/society/city/CityEnvironment.tsx+++ /dev/null@@ -1,315 +0,0 @@-/** A continuous urban setting assembled from individually reviewed Blender modules. */-import { memo, useEffect, useMemo } from "react";-import { Html } from "@react-three/drei";-import {- BoxGeometry,- Color,- InstancedMesh,- Matrix4,- MeshStandardMaterial,- Quaternion,- Vector3,-} from "three";-import { useT } from "@/i18n";-import { releaseCityInstances } from "./cityInstances";-import {- CITY_ASSETS,- CityAsset,- CityInstances,- type InstancePose,-} from "./CityAssets";-import {- DISTRICTS,- LIFTS,- MATERIALS,- RAIL_POINTS,- graphWalkways,- transformPoint,- type Placements,- type RouteGraph,- type Stop,- type Vec3,-} from "./cityModel";--interface BoxPose extends InstancePose {- size: Vec3;- color?: string;-}-const UP = new Vector3(0, 1, 0);-function Boxes({- poses,- color,- shadows = false,-}: {- poses: BoxPose[];- color: string;- shadows?: boolean;-}) {- const mesh = useMemo(() => {- const geometry = new BoxGeometry(1, 1, 1);- const material = new MeshStandardMaterial({ color, roughness: 0.82 });- const result = new InstancedMesh(geometry, material, poses.length);- const matrix = new Matrix4(),- position = new Vector3(),- rotation = new Quaternion(),- scale = new Vector3();- poses.forEach((pose, index) => {- matrix.compose(- position.set(...pose.position),- rotation.setFromAxisAngle(UP, pose.yaw ?? 0),- scale.set(...pose.size),- );- result.setMatrixAt(index, matrix);- if (pose.color) result.setColorAt(index, new Color(pose.color));- });- result.instanceMatrix.needsUpdate = true;- result.computeBoundingSphere();- result.castShadow = shadows;- result.receiveShadow = true;- return result;- }, [poses, color, shadows]);- useEffect(- () => () => {- mesh.geometry.dispose();- (mesh.material as MeshStandardMaterial).dispose();- releaseCityInstances(mesh);- },- [mesh],- );- return <primitive object={mesh} dispose={null} />;-}-function segment(- a: Vec3,- b: Vec3,- width: number,- thickness: number,- lower = 0,-): BoxPose {- return {- position: [- (a[0] + b[0]) / 2,- (a[1] + b[1]) / 2 - thickness / 2 - lower,- (a[2] + b[2]) / 2,- ],- size: [Math.hypot(b[0] - a[0], b[2] - a[2]) + 0.25, thickness, width],- yaw: -Math.atan2(b[2] - a[2], b[0] - a[0]),- };-}-function hash(x: number, z: number): number {- const value = Math.sin(x * 127.1 + z * 311.7) * 43758.5453;- return value - Math.floor(value);-}-const stationPoses: InstancePose[] = DISTRICTS.map((d) => ({- position: [d.stationPosition[0], 12.08, d.stationPosition[2]],- yaw: d.stationYaw,-}));-const dressing = (() => {- const offices: InstancePose[] = [],- towers: InstancePose[] = [],- residences: InstancePose[] = [],- trees: InstancePose[] = [],- lamps: InstancePose[] = [],- far: BoxPose[] = [],- roads: BoxPose[] = [];- // Streets continue beyond the operational boundary, with a cheap distant silhouette.- for (let x = -3000; x <= 3000; x += 240)- roads.push({ position: [x, -0.12, 0], size: [18, 0.18, 6500] });- for (let z = -3000; z <= 3000; z += 240)- roads.push({ position: [0, -0.12, z], size: [6500, 0.18, 18] });- for (let x = -2700; x <= 2700; x += 90)- for (let z = -2250; z <= 2250; z += 90) {- if (Math.abs(x % 240) < 25 || Math.abs(z % 240) < 25) continue;- const onRing =- Math.abs((x / 500) ** 2 + ((z + 110) / 280) ** 2 - 1) < 0.48;- if (- onRing ||- DISTRICTS.some((d) => Math.hypot(x - d.x, z - d.z) < 108) ||- (Math.abs(x) < 45 && z > 20 && z < 320)- )- continue;- const choice = hash(x, z),- scale = 0.7 + hash(z, x) * 0.5;- const pose: InstancePose = {- position: [x + choice * 16, -0.15, z + choice * 10],- yaw: choice > 0.5 ? Math.PI / 2 : 0,- scale,- };- // The authored skyline kit is already only 288–636 triangles per model.- // Reuse it into the distance instead of a visible wall of unrelated boxes.- (choice < 0.35 ? offices : choice < 0.65 ? towers : residences).push(pose);- }- for (const d of DISTRICTS) {- for (const side of [-1, 1])- for (let z = 26; z < 132; z += 14) {- trees.push({- position: transformPoint(- [d.stationPosition[0], 0, d.stationPosition[2]],- d.stationYaw,- [side * 38, 0, z],- ),- scale: 0.8 + hash(z, side) * 0.35,- });- if (z % 28 === 12)- lamps.push({- position: transformPoint(- [d.stationPosition[0], 0, d.stationPosition[2]],- d.stationYaw,- [side * 25, 0, z],- ),- yaw: d.stationYaw,- });- }- }- return { offices, towers, residences, trees, lamps, far, roads };-})();-const infrastructure = (() => {- const decks: BoxPose[] = [],- rails: BoxPose[] = [],- pillars: BoxPose[] = [];- RAIL_POINTS.slice(1).forEach((b, index) => {- const a = RAIL_POINTS[index];- decks.push(segment(a, b, 6.4, 0.7, 1.5));- const dx = b[0] - a[0],- dz = b[2] - a[2],- length = Math.hypot(dx, dz);- for (const side of [-1, 1]) {- const offsetX = (-dz / length) * side * 1.65,- offsetZ = (dx / length) * side * 1.65;- rails.push(- segment(- [a[0] + offsetX, 10.88, a[2] + offsetZ],- [b[0] + offsetX, 10.88, b[2] + offsetZ],- 0.14,- 0.15,- ),- );- }- if (index % 8 === 0)- pillars.push({ position: [a[0], 5, a[2]], size: [1.4, 10, 1.4] });- });- return { decks, rails, pillars };-})();-export const CityEnvironment = memo(function CityEnvironment({- graph,- placements,- activeStops,- onSelect,- interiorStop,-}: {- graph: RouteGraph;- placements: Placements;- activeStops: Set<Stop>;- onSelect: (stop: Stop) => void;- interiorStop: Stop | null;-}) {- const t = useT();- const paths = useMemo(- () =>- graphWalkways(graph).map((way) => segment(way.a, way.b, way.width, 0.18)),- [graph],- );- const safetyRails = useMemo(- () =>- graphWalkways(graph)- .filter((way) => way.layer === "bridge")- .flatMap((way) => {- const dx = way.b[0] - way.a[0],- dz = way.b[2] - way.a[2],- length = Math.hypot(dx, dz);- return [-1, 1].map((side) => {- const x = ((-dz / length) * side * way.width) / 2,- z = ((dx / length) * side * way.width) / 2;- return segment(- [way.a[0] + x, way.a[1] + 1.2, way.a[2] + z],- [way.b[0] + x, way.b[1] + 1.2, way.b[2] + z],- 0.12,- 0.12,- );- });- }),- [graph],- );- const plazas = useMemo(- () =>- DISTRICTS.map((d): BoxPose => ({- position: transformPoint(- [d.stationPosition[0], 0, d.stationPosition[2]],- d.stationYaw,- [0, -0.25, 73],- ),- size: [96, 0.3, 132],- yaw: d.stationYaw,- })),- [],- );- return (- <>- <mesh- rotation={[-Math.PI / 2, 0, 0]}- position={[0, -0.35, 0]}- receiveShadow- >- <planeGeometry args={[18000, 18000]} />- <meshStandardMaterial color="#819085" roughness={1} />- </mesh>- <Boxes poses={dressing.roads} color="#3d4c53" />- <Boxes poses={dressing.far} color="#65737b" />- <CityInstances url={CITY_ASSETS.office} poses={dressing.offices} />- <CityInstances url={CITY_ASSETS.tower} poses={dressing.towers} />- <CityInstances url={CITY_ASSETS.residence} poses={dressing.residences} />- <CityInstances url={CITY_ASSETS.tree} poses={dressing.trees} />- <CityInstances url={CITY_ASSETS.lamp} poses={dressing.lamps} />- <Boxes poses={plazas} color={MATERIALS.concrete} />- <Boxes poses={paths} color="#c3c8bf" />- <Boxes poses={safetyRails} color={MATERIALS.metal} />- <Boxes poses={infrastructure.decks} color={MATERIALS.graphite} />- <Boxes poses={infrastructure.rails} color={MATERIALS.metal} />- <Boxes- poses={infrastructure.pillars}- color={MATERIALS.concrete}- shadows- />- <CityInstances url={CITY_ASSETS.station} poses={stationPoses} shadows />- {LIFTS.map((lift) => (- <group key={lift.id} position={lift.a}>- <mesh position={[0, (lift.b[1] - lift.a[1]) / 2, 0]}>- <boxGeometry args={[5, lift.b[1] - lift.a[1], 5]} />- <meshStandardMaterial- color="#8ab3c5"- transparent- opacity={0.12}- depthWrite={false}- roughness={0.2}- />- </mesh>- <mesh position={[0, lift.b[1] - lift.a[1] - 0.15, 0]}>- <boxGeometry args={[5.5, 0.3, 5.5]} />- <meshStandardMaterial color={MATERIALS.metal} />- </mesh>- </group>- ))}- {DISTRICTS.map((d) => (- <group key={d.stop}>- <CityAsset- url={CITY_ASSETS[d.id]}- position={placements[d.stop]}- yaw={d.buildingRotation}- working={activeStops.has(d.stop)}- cutaway={interiorStop === d.stop}- onClick={() => onSelect(d.stop)}- />- <Html- position={[d.stationPosition[0], 24, d.stationPosition[2]]}- zIndexRange={[1, 0]}- center- style={{ pointerEvents: "none" }}- >- <span className="whitespace-nowrap rounded border border-border bg-popover/95 px-2 py-1 text-xs text-popover-foreground">- {t(d.labelKey)}- </span>- </Html>- </group>- ))}- </>- );-});diff --git a/jarvis/ui/web/frontend/src/components/society/city/CityRuntime.tsx b/jarvis/ui/web/frontend/src/components/society/city/CityRuntime.tsxdeleted file mode 100644index 6c00445f1a..0000000000--- a/jarvis/ui/web/frontend/src/components/society/city/CityRuntime.tsx+++ /dev/null@@ -1,326 +0,0 @@-import {- memo,- useEffect,- useMemo,- useRef,- useState,- type MutableRefObject,-} from "react";-import { useFrame, useThree } from "@react-three/fiber";-import { Html, OrbitControls, useGLTF } from "@react-three/drei";-import {- AnimationMixer,- Color,- Fog,- Group,- Mesh,- PMREMGenerator,- Vector3,- type DirectionalLight,- type HemisphereLight,-} from "three";-import type { OrbitControls as OrbitControlsType } from "three-stdlib";-import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";-import { FigureRig, type FigureDrive } from "../figures/FigureRig";-import type { FigureRecipe } from "../figures/figureRecipe";-import { CAMERA_BOUNDS, type Vec3 } from "./cityModel";-import { daylight, type Citizen, type CitySimulation } from "./citySimulation";-import { tickCityClock, type CityClock } from "./cityClock";-import { Metro } from "./CityAssets";-import citizenUrl from "../../../../../../../../art/studies/city-realism-study/exports/citizen.glb";--export interface CityActor {- id: string;- label: string;- recipe?: FigureRecipe | null;- checkpoint: string;- state: string;-}-export interface CityMetrics {- fps: number;- calls: number;- triangles: number;- geometries: number;- textures: number;-}-export interface CameraFocus {- position: Vec3;- distance: number;- yaw: number;- key: number;-}-export const OVERVIEW: CameraFocus = {- position: [0, 0, -60],- distance: 950,- yaw: 0.65,- key: 0,-};-function ReferenceCitizen({- citizen,- paused,-}: {- citizen: Citizen;- paused: boolean;-}) {- const { scene, animations } = useGLTF(citizenUrl);- const clone = useMemo(() => scene.clone(true), [scene]);- const mixer = useMemo(() => new AnimationMixer(clone), [clone]);- const moving = useRef(false);- const phase = useRef(0);- useEffect(() => {- for (const clip of animations) mixer.clipAction(clip).play();- return () => {- mixer.stopAllAction();- mixer.uncacheRoot(clone);- };- }, [animations, clone, mixer]);- useFrame((_, dt) => {- const walking = !paused && citizen.speed > 0;- if (walking) mixer.update((Math.min(dt, 0.1) * citizen.speed) / 1.28);- else if (moving.current) mixer.setTime(0);- moving.current = walking;- const working = citizen.atWork && citizen.taskActive && !paused;- if (!paused) phase.current += Math.min(dt, 0.1);- for (const [index, side] of ["L", "R"].entries()) {- const arm = clone.getObjectByName(`Arm_${side}`),- forearm = clone.getObjectByName(`Forearm_${side}`);- if (arm) arm.rotation.x = working ? -0.45 : 0;- if (forearm)- forearm.rotation.x = working- ? -1.1 + Math.sin(phase.current * 8 + index * Math.PI) * 0.07- : 0;- }- });- return <primitive object={clone} dispose={null} />;-}-export const MovingActor = memo(function MovingActor({- actor,- sim,- paused,- selected,- onSelect,-}: {- actor: CityActor;- sim: CitySimulation;- paused: boolean;- selected: boolean;- onSelect: (id: string) => void;-}) {- const root = useRef<Group>(null),- body = useRef<Group>(null),- distant = useRef<Mesh>(null);- const nearRef = useRef(true);- const [near, setNear] = useState(true);- const drive = useRef<FigureDrive>({ mode: "idle", speed: 0 });- const citizen = sim.citizens.get(actor.id);- useFrame(({ camera }) => {- if (!root.current || !citizen) return;- root.current.position.set(...citizen.position);- root.current.rotation.y = citizen.heading;- const detail =- selected || camera.position.distanceTo(root.current.position) < 100;- if (detail !== nearRef.current) {- nearRef.current = detail;- setNear(detail);- }- if (body.current) body.current.visible = detail;- if (distant.current) distant.current.visible = !detail;- drive.current.mode =- citizen.speed > 0- ? "walk"- : citizen.atWork && citizen.taskActive- ? "work"- : "idle";- drive.current.speed = citizen.speed;- });- if (!citizen) return null;- return (- <group- ref={root}- onClick={(event) => {- event.stopPropagation();- onSelect(actor.id);- }}- >- <group ref={body}>- {actor.recipe ? (- <FigureRig- recipe={actor.recipe}- drive={drive}- paused={paused || !near}- />- ) : (- <ReferenceCitizen citizen={citizen} paused={paused || !near} />- )}- </group>- <mesh ref={distant} position={[0, 0.85, 0]} visible={false}>- <capsuleGeometry args={[0.24, 1.2, 3, 6]} />- <meshStandardMaterial color="#5595a4" roughness={0.8} />- </mesh>- {selected && (- <>- <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.025, 0]}>- <ringGeometry args={[0.65, 0.82, 24]} />- <meshBasicMaterial color="#ebc772" />- </mesh>- <Html- position={[0, 2.4, 0]}- center- zIndexRange={[1, 0]}- style={{ pointerEvents: "none" }}- >- <span className="whitespace-nowrap rounded border border-border bg-popover px-2 py-1 text-xs text-popover-foreground">- {actor.label}- </span>- </Html>- </>- )}- </group>- );-});--export const CityRuntime = memo(function CityRuntime({- sim,- clock,- paused,- focus,- follow,- metrics,- requestFrame,-}: {- sim: CitySimulation;- clock: CityClock;- paused: boolean;- focus: CameraFocus;- follow: string | null;- metrics: MutableRefObject<CityMetrics>;- requestFrame: MutableRefObject<() => void>;-}) {- const sun = useRef<DirectionalLight>(null),- sky = useRef<HemisphereLight>(null),- controls = useRef<OrbitControlsType>(null);- const { scene, camera, gl, invalidate } = useThree();- const samples = useRef({ seconds: 0, frames: 0 });- const light = useMemo(- () => ({- night: new Color("#182b3c"),- day: new Color("#a6beca"),- background: new Color(),- target: new Vector3(),- delta: new Vector3(),- }),- [],- );- useEffect(() => {- requestFrame.current = invalidate;- gl.localClippingEnabled = true;- const room = new RoomEnvironment(),- generator = new PMREMGenerator(gl),- target = generator.fromScene(room, 0.04);- scene.environment = target.texture;- scene.fog = new Fog("#a6beca", 1100, 4400);- room.dispose();- generator.dispose();- invalidate();- return () => {- scene.environment = null;- scene.fog = null;- target.dispose();- requestFrame.current = () => undefined;- };- }, [gl, scene, invalidate, requestFrame]);- useEffect(() => {- if (!controls.current) return;- const [x, y, z] = focus.position;- controls.current.target.set(x, y, z);- camera.position.set(- x + Math.sin(focus.yaw) * focus.distance,- y + focus.distance * 0.6,- z + Math.cos(focus.yaw) * focus.distance,- );- controls.current.update();- invalidate();- }, [focus, camera, invalidate]);- useEffect(() => {- const citizen = follow ? sim.citizens.get(follow) : null;- if (!citizen || !controls.current) return;- const [x, y, z] = citizen.position;- controls.current.target.set(x, y + 1, z);- camera.position.set(x + 12, y + 9, z - 16);- controls.current.update();- invalidate();- }, [follow, camera, sim, invalidate]);- useFrame((_, dt) => {- tickCityClock(clock, sim, performance.now(), paused);- const strength = daylight(clock.hour);- light.background.copy(light.night).lerp(light.day, strength);- scene.background = light.background;- if (scene.fog instanceof Fog) scene.fog.color.copy(light.background);- scene.environmentIntensity = 0.25 + strength * 0.6;- if (sky.current) sky.current.intensity = 0.7 + strength * 1.1;- if (sun.current) {- sun.current.intensity = 0.2 + strength * 2.1;- sun.current.position.set(- Math.cos((clock.hour / 24) * Math.PI * 2) * 350,- 160 + strength * 250,- 240,- );- }- const orbit = controls.current;- if (orbit) {- const citizen = follow ? sim.citizens.get(follow) : null;- if (citizen) {- light.target.set(...citizen.position);- light.target.y += 1;- light.delta.copy(light.target).sub(orbit.target);- camera.position.add(light.delta);- orbit.target.copy(light.target);- }- light.target.copy(orbit.target);- orbit.target.x = Math.max(- CAMERA_BOUNDS.minX,- Math.min(CAMERA_BOUNDS.maxX, orbit.target.x),- );- orbit.target.z = Math.max(- CAMERA_BOUNDS.minZ,- Math.min(CAMERA_BOUNDS.maxZ, orbit.target.z),- );- camera.position.add(light.delta.copy(orbit.target).sub(light.target));- camera.position.y = Math.max(2.5, camera.position.y);- orbit.update();- // City-scale distances need a larger near plane to prevent road/plaza z-fighting.- const near = Math.max(0.2, Math.min(15, camera.position.distanceTo(orbit.target) / 100));- if (Math.abs(camera.near - near) > 0.05) { camera.near = near; camera.updateProjectionMatrix(); }- }- if (dt > 0) {- samples.current.seconds += dt;- samples.current.frames++;- }- if (samples.current.seconds >= 1) {- metrics.current = {- fps: Math.round(samples.current.frames / samples.current.seconds),- calls: gl.info.render.calls,- triangles: gl.info.render.triangles,- geometries: gl.info.memory.geometries,- textures: gl.info.memory.textures,- };- samples.current = { seconds: 0, frames: 0 };- }- }, -1);- return (- <>- <hemisphereLight ref={sky} args={["#d2e0e9", "#697266", 1.5]} />- <directionalLight ref={sun} position={[250, 350, 240]} intensity={2.2} />- <OrbitControls- ref={controls}- makeDefault- target={[0, 0, -60]}- minDistance={CAMERA_BOUNDS.minDistance}- maxDistance={CAMERA_BOUNDS.maxDistance}- maxPolarAngle={Math.PI / 2 - 0.025}- enableDamping={!paused}- />- <Metro sim={sim} paused={paused} follow={follow} />- </>- );-});diff --git a/jarvis/ui/web/frontend/src/components/society/city/CityStage.test.tsx b/jarvis/ui/web/frontend/src/components/society/city/CityStage.test.tsxdeleted file mode 100644index a694a00a63..0000000000--- a/jarvis/ui/web/frontend/src/components/society/city/CityStage.test.tsx+++ /dev/null@@ -1,47 +0,0 @@-import { cleanup, render } from "@testing-library/react";-import { afterEach, expect, it, vi } from "vitest";--const fixture = vi.hoisted(() => ({ translations: 0, pending: false, roster: { sample: false, agents: [{ agentId: "real-agent", name: "Agent", figure: null, checkpoint: "idle", state: "idle" }] } }));-vi.mock("@/i18n", () => ({ useLocaleChunk: () => true, useT: () => {- if (++fixture.translations > 30) throw new Error("City entered a reconciliation loop");- return (key: string) => key;-} }));-vi.mock("../data", () => ({ useSocietyRoster: () => ({ data: fixture.pending ? undefined : fixture.roster, isError: false }) }));-vi.mock("@/hooks/useWebglSurface", () => ({ useWebglSurface: () => ({ generation: 0 }) }));-vi.mock("@/hooks/useCanvasAwake", () => ({ useCanvasAwake: () => false }));-vi.mock("@/lib/graphDimension", () => ({ useWebglSupported: () => false }));-vi.mock("./CityEnvironment", () => ({ CityEnvironment: () => null }));-vi.mock("./CityRuntime", () => ({ CityRuntime: () => null, MovingActor: () => null, OVERVIEW: { position: [0, 0, 0], distance: 100, yaw: 0, key: 0 } }));--import { CityStage } from "./CityStage";-import { citySessions } from "./citySession";-import { defaultPlacements } from "./cityModel";-import { addCitizen, setTarget, stepSimulation } from "./citySimulation";-afterEach(() => { cleanup(); fixture.translations = 0; fixture.pending = false; fixture.roster.sample = false; });-it("settles roster reconciliation with an unstable translation function", () => {- const view = render(<CityStage onOpenLedger={() => undefined} />);- expect(view.getByTestId("city-reference").getAttribute("data-version")).toBe("1");- expect(fixture.translations).toBeLessThan(10);-});-it("discloses successful sample responses instead of claiming a live feed", () => {- fixture.roster.sample = true;- const view = render(<CityStage onOpenLedger={() => undefined} />);- expect(view.getByText("society.city.sample_notice")).toBeTruthy();- expect(view.queryByText("society.city.live")).toBeNull();-});-it("retains cached live journeys while a returning roster fetch is pending", () => {- const live = citySessions.get("live", defaultPlacements, performance.now());- const citizen = addCitizen(live.sim, "real-agent", "west");- setTarget(live.sim, citizen.id, "east", citizen.revision + 1); stepSimulation(live.sim, 10);- const position = [...citizen.position]; fixture.pending = true;- const view = render(<CityStage onOpenLedger={() => undefined} />);- expect(live.sim.citizens.get(citizen.id)).toBe(citizen);- fixture.pending = false; view.rerender(<CityStage onOpenLedger={() => undefined} />);- expect(live.sim.citizens.get(citizen.id)).toBe(citizen); expect(citizen.position).toEqual(position);-});-it("never replaces live journeys with offline sample actors", () => {- const live = citySessions.get("live", defaultPlacements, performance.now());- const citizen = live.sim.citizens.get("real-agent");- fixture.roster.sample = true; render(<CityStage onOpenLedger={() => undefined} />);- expect(live.sim.citizens.get("real-agent")).toBe(citizen);-});diff --git a/jarvis/ui/web/frontend/src/components/society/city/CityStage.tsx b/jarvis/ui/web/frontend/src/components/society/city/CityStage.tsxdeleted file mode 100644index d36ad0f21f..0000000000--- a/jarvis/ui/web/frontend/src/components/society/city/CityStage.tsx+++ /dev/null@@ -1,637 +0,0 @@-/** Live city surface: authored districts, physical metro journeys and real work state. */-import {- Suspense,- useCallback,- useEffect,- useMemo,- useRef,- useState,- type ReactNode,-} from "react";-import { Canvas } from "@react-three/fiber";-import { useCanvasAwake } from "@/hooks/useCanvasAwake";-import { useWebglSurface } from "@/hooks/useWebglSurface";-import { useWebglSupported } from "@/lib/graphDimension";-import { useLocaleChunk, useT } from "@/i18n";-import { useEventStore } from "@/store/events";-import { useSocietyRoster } from "../data";-import type { PlaceId } from "../world/islandLayout";-import {- CAMERA_BOUNDS,- CITY,- DISTRICTS,- checkpointStop,- district,- restoreLayout,- transformPoint,- type Stop,-} from "./cityModel";-import {- addCitizen,- cancelJourney,- moveBuilding,- setTarget,- setTaskActive,- trainAt,- type JourneyStage,-} from "./citySimulation";-import { tickCityClock } from "./cityClock";-import { citySessions } from "./citySession";-import { useCityReducedMotion } from "./cityMotion";-import { CityEnvironment } from "./CityEnvironment";-import {- CityRuntime,- MovingActor,- OVERVIEW,- type CameraFocus,- type CityActor,- type CityMetrics,-} from "./CityRuntime";--interface Props {- topRight?: ReactNode;- onOpenLedger: () => void;- onSelectAgent?: (id: string | null) => void;- onSelectPlace?: (place: PlaceId) => void;-}-const LAYOUT_KEY = "jarvis.city.layout.v2";-function initialLayout() {- try {- return restoreLayout(- JSON.parse(localStorage.getItem(LAYOUT_KEY) ?? "null"),- );- } catch {- return restoreLayout(null); /* Private storage uses default city plots. */- }-}-const DEMO_CHECKPOINT: Record<Stop, string> = {- west: "meeting",- east: "hub:cli",- knowledge: "archive",- workshop: "hub:skills",- communications: "hub:comms",-};-const EMPTY_METRICS: CityMetrics = {- fps: 0,- calls: 0,- triangles: 0,- geometries: 0,- textures: 0,-};-export function CityStage(props: Props) {- const ready = useLocaleChunk("society");- return ready ? (- <ReadyCity {...props} />- ) : (- <div className="h-full animate-pulse bg-secondary" aria-busy="true" />- );-}-function ReadyCity({- topRight,- onOpenLedger,- onSelectAgent,- onSelectPlace,-}: Props) {- const t = useT();- const setActiveSection = useEventStore((s) => s.setActiveSection);- const host = useRef<HTMLDivElement>(null);- const { generation } = useWebglSurface(host);- const awake = useCanvasAwake(host),- webgl = useWebglSupported(),- reduced = useCityReducedMotion();- const roster = useSocietyRoster();- const [demo, setDemo] = useState(false);- const sample = !demo && roster.data?.sample === true;- const loading = !demo && !roster.data;- const { sim, clock } = useMemo(() => citySessions.get(demo ? "demo" : sample ? "sample" : "live", () => initialLayout().placements, performance.now()), [demo, sample]);- const metrics = useRef<CityMetrics>({ ...EMPTY_METRICS }),- requestFrame = useRef<() => void>(() => undefined);- const signatures = useRef(new Map<string, string>());- const [count, setCount] = useState(8),- [demoStop, setDemoStop] = useState<Stop>("east");- const [selected, setSelected] = useState<string | null>(null),- [follow, setFollow] = useState<string | null>(null);- const [selectedStop, setSelectedStop] = useState<Stop | null>(null),- [focus, setFocus] = useState<CameraFocus>(OVERVIEW);- const [interiorStop, setInteriorStop] = useState<Stop | null>(null);- const [details, setDetails] = useState(false),- [message, setMessage] = useState<string | null>(null);- const [version, setVersion] = useState(0),- [snapshot, setSnapshot] = useState({- hour: 10,- time: 0,- workKey: "",- debt: 0,- });- const demoLabel = t("society.city.reference_agent");- const actors = useMemo<CityActor[]>(- () =>- demo- ? Array.from({ length: count }, (_, i) => ({- id: `city-demo-${i}`,- label: `${demoLabel} ${i + 1}`,- checkpoint: DEMO_CHECKPOINT[demoStop],- state: "working",- }))- : (roster.data?.agents ?? []).map((a) => ({- id: a.agentId,- label: a.name,- recipe: a.figure,- checkpoint: a.checkpoint,- state: a.state,- })),- [demo, count, demoStop, roster.data, demoLabel],- );- useEffect(() => {- if (!demo && !roster.data) return; // A pending fetch is not an empty roster.- const ids = new Set(actors.map((a) => a.id));- for (const id of sim.citizens.keys())- if (!ids.has(id)) {- sim.citizens.delete(id);- signatures.current.delete(id);- }- for (const actor of actors) {- const created = !sim.citizens.has(actor.id);- const citizen = addCitizen(sim, actor.id, "west");- const signature = `${actor.checkpoint}:${actor.state}`;- if (!created && signatures.current.get(actor.id) === signature) continue;- signatures.current.set(actor.id, signature);- const target = checkpointStop(actor.checkpoint);- if (actor.state === "paused" || !target) {- setTaskActive(sim, actor.id, false);- if (citizen.stage !== "arrived")- cancelJourney(sim, actor.id, citizen.revision + 1);- } else {- setTarget(sim, actor.id, target, citizen.revision + 1);- setTaskActive(sim, actor.id, actor.state === "working");- }- }- setVersion((v) => v + 1);- requestFrame.current();- }, [actors, sim, demo, roster.data]);- useEffect(() => {- const timer = window.setInterval(() => {- tickCityClock(clock, sim, performance.now(), reduced);- setSnapshot({- hour: clock.hour,- time: sim.time,- workKey: [...sim.citizens.values()]- .filter((c) => c.atWork && c.taskActive)- .map((c) => c.target)- .sort()- .join(","),- debt: sim.debt,- });- }, 250);- return () => window.clearInterval(timer);- }, [clock, sim, reduced]);- const activeStops = useMemo(- () => new Set(snapshot.workKey.split(",").filter(Boolean) as Stop[]),- [snapshot.workKey],- );- const selectActor = useCallback((id: string) => {- setSelected(id);- requestFrame.current();- }, []);- const selectStop = useCallback(- (stop: Stop) => {- const d = district(stop);- setSelectedStop(stop);- setFollow(null);- setMessage(null);- setInteriorStop(stop);- const position = transformPoint(- sim.placements[stop],- d.buildingRotation,- [0, 0, -8],- );- setFocus((f) => ({- position,- distance: 88,- yaw: d.buildingRotation + Math.PI + 0.3,- key: f.key + 1,- }));- },- [sim],- );- function overview() {- setFollow(null);- setSelectedStop(null);- setInteriorStop(null);- setFocus((f) => ({ ...OVERVIEW, key: f.key + 1 }));- }- function movePlot(dx: number, dz: number) {- if (!selectedStop) return;- const p = sim.placements[selectedStop];- if (!moveBuilding(sim, selectedStop, [p[0] + dx, p[1], p[2] + dz])) {- setMessage("invalid_plot");- return;- }- if (demo || sample) { setMessage("demo_plot"); setVersion((v) => v + 1); requestFrame.current(); return; }- try {- localStorage.setItem(- LAYOUT_KEY,- JSON.stringify({ version: 2, placements: sim.placements }),- );- setMessage("saved_plot");- } catch {- setMessage("session_plot");- }- setVersion((v) => v + 1);- requestFrame.current();- }- const citizen = selected ? sim.citizens.get(selected) : undefined;- const actor = actors.find((a) => a.id === selected),- train = trainAt(snapshot.time);- const button =- "rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-foreground transition-colors hover:bg-muted focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring";- const activeDistrict = selectedStop ? district(selectedStop) : null;- const stageText = (stage: JourneyStage, workspaceQueue = false) =>- t(- workspaceQueue- ? "society.city.waiting_workspace"- : `society.city.stage_${stage}`,- );- return (- <div- className="relative flex h-full min-h-0 flex-col bg-background text-foreground"- data-testid="city-reference"- data-version={version}- >- <div className="flex flex-wrap items-center gap-2 border-b border-border bg-popover p-2">- <strong className="mr-auto text-sm">{t("society.city.title")}</strong>- {topRight}- <button className={button} onClick={overview}>- {t("society.city.overview")}- </button>- <button- className={button}- onClick={() => {- clock.dayPaused = !clock.dayPaused;- setSnapshot((s) => ({ ...s }));- }}- >- {t(- clock.dayPaused- ? "society.city.resume_day"- : "society.city.pause_day",- )}- </button>- <label className="flex items-center gap-1 text-xs">- {t("society.city.hour")}- <input- className="w-24"- aria-label={t("society.city.hour")}- type="range"- min="0"- max="23.9"- step="0.1"- value={snapshot.hour}- onChange={(e) => {- clock.hour = Number(e.target.value);- clock.dayPaused = true;- setSnapshot((s) => ({ ...s, hour: clock.hour }));- requestFrame.current();- }}- />- {String(Math.floor(snapshot.hour)).padStart(2, "0")}:00- </label>- <button- className={button}- aria-expanded={details}- onClick={() => setDetails(!details)}- >- {t("society.city.options")}- </button>- </div>- {details && (- <div className="flex flex-wrap items-center gap-2 border-b border-border bg-muted/40 p-2 text-xs">- <label className="flex items-center gap-1">- <input- type="checkbox"- checked={demo}- onChange={(e) => {- setDemo(e.target.checked);- setSelected(null);- setFollow(null);- }}- />- {t("society.city.demo")}- </label>- {demo && (- <>- <select- className={button}- aria-label={t("society.city.agent_count")}- value={count}- onChange={(e) => setCount(Number(e.target.value))}- >- {[1, 8, 30].map((n) => (- <option key={n}>{n}</option>- ))}- </select>- <select- className={button}- aria-label={t("society.city.demo_target")}- value={demoStop}- onChange={(e) => setDemoStop(e.target.value as Stop)}- >- {DISTRICTS.map((d) => (- <option key={d.stop} value={d.stop}>- {t(d.labelKey)}- </option>- ))}- </select>- </>- )}- <span data-testid="city-metrics">- {metrics.current.fps} FPS · {metrics.current.calls} draws ·{" "}- {metrics.current.triangles.toLocaleString()} triangles- </span>- </div>- )}- <div ref={host} className="relative isolate min-h-0 flex-1">- {webgl ? (- <Canvas- key={generation}- camera={{- position: [700, 550, 850],- fov: 45,- near: 0.2,- far: 9000,- }}- dpr={1}- gl={{ antialias: true, alpha: false }}- frameloop={!awake ? "never" : reduced ? "demand" : "always"}- >- <Suspense fallback={null}>- <CityRuntime- sim={sim}- clock={clock}- paused={reduced}- focus={focus}- follow={follow}- metrics={metrics}- requestFrame={requestFrame}- />- <CityEnvironment- graph={sim.graph}- placements={sim.placements}- activeStops={activeStops}- onSelect={selectStop}- interiorStop={interiorStop ?? (follow && sim.citizens.get(follow)?.atWork ? sim.citizens.get(follow)!.target : null)}- />- {actors- .filter((a) => sim.citizens.has(a.id))- .map((a) => (- <MovingActor- key={a.id}- actor={a}- sim={sim}- paused={reduced || !awake}- selected={selected === a.id}- onSelect={selectActor}- />- ))}- </Suspense>- </Canvas>- ) : (- <div className="p-6">- <p>{t("society.world.webgl_missing_body")}</p>- <button className={button} onClick={onOpenLedger}>- {t("society.world.open_ledger")}- </button>- </div>- )}- <div- className="absolute left-3 top-3 z-20 flex max-w-[55%] flex-wrap gap-1 rounded-lg border border-border bg-popover/95 p-1.5 shadow-sm"- aria-label={t("society.city.districts")}- >- {DISTRICTS.map((d) => (- <button- key={d.stop}- className="rounded px-2 py-1 text-xs hover:bg-muted"- onClick={() => selectStop(d.stop)}- >- {t(d.labelKey)}- </button>- ))}- </div>- <div className="absolute right-3 top-3 z-20 max-h-[40%] w-48 overflow-auto rounded-lg border border-border bg-popover/95 p-2 text-xs shadow-sm">- <p className="mb-2 font-medium">- {t(- demo- ? "society.city.demo"- : loading- ? "society.city.loading"- : sample- ? "society.city.sample"- : "society.city.live",- )}- </p>- {sample && (- <p className="mb-2 text-muted-foreground">- {t("society.city.sample_notice")}- </p>- )}- {roster.isError && !demo && (- <p role="alert">{t("society.city.feed_error")}</p>- )}- {actors.map((a) => (- <button- key={a.id}- className="mb-1 block w-full rounded p-1.5 text-left hover:bg-muted"- onClick={() => selectActor(a.id)}- >- {a.label}- <span className="block text-muted-foreground">- {stageText(- sim.citizens.get(a.id)?.stage ?? "arrived",- sim.citizens.get(a.id)?.waitingForWorkspace,- )}- </span>- </button>- ))}- </div>- <div className="absolute bottom-3 left-3 z-20 rounded-lg border border-border bg-popover/95 p-3 text-xs shadow-sm">- <svg- viewBox="-950 -650 1900 1300"- width="190"- height="120"- role="img"- aria-label={t("society.city.city_map")}- >- <rect- x={CAMERA_BOUNDS.minX}- y={CAMERA_BOUNDS.minZ}- width={CAMERA_BOUNDS.maxX - CAMERA_BOUNDS.minX}- height={CAMERA_BOUNDS.maxZ - CAMERA_BOUNDS.minZ}- rx="40"- fill="none"- stroke="currentColor"- opacity="0.2"- strokeWidth="8"- />- <ellipse- cx="0"- cy="-110"- rx="500"- ry="280"- fill="none"- stroke="currentColor"- strokeWidth="10"- opacity="0.4"- />- {DISTRICTS.map((d) => (- <circle- key={d.stop}- cx={d.stationPosition[0]}- cy={d.stationPosition[2]}- r="26"- fill={d.color}- />- ))}- <circle- cx={train.position[0]}- cy={train.position[2]}- r="17"- fill="currentColor"- />- </svg>- <p>- {t("society.city.metro_line")} · {actors.length}{" "}- {t("society.city.agents")}- </p>- <p className="mt-1 text-muted-foreground">- {CITY.width / 1000} × {CITY.depth / 1000} km ·{" "}- {t("society.city.city_limits")}- </p>- {reduced && (- <p className="mt-2 max-w-52">{t("society.city.reduced")}</p>- )}- {snapshot.debt > 1 && <p>{t("society.city.catching_up")}</p>}- </div>- {citizen && actor && (- <div- className="absolute bottom-3 right-3 z-20 w-64 rounded-lg border border-border bg-popover p-3 text-xs shadow-lg"- data-testid="city-journey"- data-stage={citizen.stage}- data-position={citizen.position.join(",")}- data-simulation-time={snapshot.time}- >- <strong>{actor.label}</strong>- <p className="mt-1">- {t(- demo || sample- ? "society.city.example_state"- : "society.city.task",- )}- : {actor.checkpoint} · {actor.state}- </p>- <p>- {t("society.city.travel")}:{" "}- {stageText(citizen.stage, citizen.waitingForWorkspace)}- </p>- <p>- {t("society.city.target")}: {t(district(citizen.target).labelKey)}- </p>- <div className="mt-2 flex flex-wrap gap-2">- <button- className={button}- onClick={() =>- setFollow(follow === citizen.id ? null : citizen.id)- }- >- {t(- follow === citizen.id- ? "society.city.unfollow"- : "society.city.follow",- )}- </button>- {!demo && !sample && (- <button- className={button}- onClick={() => onSelectAgent?.(citizen.id)}- >- {t("society.city.open_agent")}- </button>- )}- </div>- </div>- )}- {activeDistrict && (- <div- className="absolute left-3 top-16 z-20 max-w-72 rounded-lg border border-border bg-popover p-3 text-xs shadow-lg"- data-testid="city-building-panel"- >- <strong>{t(activeDistrict.labelKey)}</strong>- <p className="my-2 text-muted-foreground">- {t(`society.city.description_${activeDistrict.id}`)}- </p>- <button- className={button}- onClick={() =>- activeDistrict.stop === "east"- ? setActiveSection("agentic-ide")- : onSelectPlace?.(activeDistrict.placeId)- }- >- {t(- activeDistrict.stop === "east"- ? "society.city.open_terminal"- : "society.city.open_building",- )}- </button>- <button- className={`${button} ml-1`}- onClick={() => {- setInteriorStop(- interiorStop === activeDistrict.stop- ? null- : activeDistrict.stop,- );- requestFrame.current();- }}- >- {t(- interiorStop === activeDistrict.stop- ? "society.city.exterior"- : "society.city.work_floor",- )}- </button>- <details className="mt-3">- <summary className="cursor-pointer">- {t("society.city.adjust_plot")}- </summary>- <div className="my-2 flex flex-wrap gap-1">- <button className={button} onClick={() => movePlot(-4, 0)}>- ← 4 m- </button>- <button className={button} onClick={() => movePlot(4, 0)}>- 4 m →- </button>- <button className={button} onClick={() => movePlot(0, -4)}>- ↑ 4 m- </button>- <button className={button} onClick={() => movePlot(0, 4)}>- 4 m ↓- </button>- </div>- </details>- {message && (- <p role="status" className="my-2">- {t(`society.city.${message}`)}- </p>- )}- <button- className="mt-2 text-muted-foreground underline"- onClick={() => setSelectedStop(null)}- >- {t("society.city.close")}- </button>- </div>- )}- </div>- </div>- );-}diff --git a/jarvis/ui/web/frontend/src/components/society/city/cityClock.test.ts b/jarvis/ui/web/frontend/src/components/society/city/cityClock.test.tsdeleted file mode 100644index dbd1fc8b30..0000000000--- a/jarvis/ui/web/frontend/src/components/society/city/cityClock.test.ts+++ /dev/null@@ -1,36 +0,0 @@-import { describe, expect, it } from "vitest";-import { addCitizen, createSimulation, setTarget } from "./citySimulation";-import { createCityClock, tickCityClock } from "./cityClock";--describe("shared city clock", () => {- it("does not double-count a frame and timer at the same time", () => {- const sim = createSimulation(),- clock = createCityClock(0);- tickCityClock(clock, sim, 1000, false);- tickCityClock(clock, sim, 1000, false);- expect(sim.time).toBeCloseTo(1);- tickCityClock(clock, sim, 1500, false);- expect(sim.time).toBeCloseTo(1.5);- });- it("freezes journeys and daylight and does not replay the paused interval", () => {- const sim = createSimulation(),- clock = createCityClock(0);- tickCityClock(clock, sim, 30000, true);- expect(sim.time).toBe(0);- expect(clock.hour).toBe(10);- tickCityClock(clock, sim, 31000, false);- expect(sim.time).toBeCloseTo(1);- });- it("budgets active catch-up and retains remaining physical time", () => {- const sim = createSimulation(),- clock = createCityClock(0);- addCitizen(sim, "commuter", "west");- setTarget(sim, "commuter", "east", 1);- tickCityClock(clock, sim, 120000, false);- expect(sim.time).toBeLessThan(10);- expect(sim.debt).toBeGreaterThan(110);- for (let i = 0; i < 100; i++) tickCityClock(clock, sim, 120000, false);- expect(sim.time).toBeCloseTo(120);- expect(sim.debt).toBeLessThan(0.0001);- });-});diff --git a/jarvis/ui/web/frontend/src/components/society/city/cityClock.ts b/jarvis/ui/web/frontend/src/components/society/city/cityClock.tsdeleted file mode 100644index daa63f0e3a..0000000000--- a/jarvis/ui/web/frontend/src/components/society/city/cityClock.ts+++ /dev/null@@ -1,32 +0,0 @@-import {- advanceHour,- stepWithBudget,- type CitySimulation,-} from "./citySimulation";--export interface CityClock {- lastMs: number;- hour: number;- dayPaused: boolean;-}-export const createCityClock = (now: number): CityClock => ({- lastMs: now,- hour: 10,- dayPaused: false,-});-/** Both foreground frames and background ticks consume the SAME monotonic clock. */-export function tickCityClock(- clock: CityClock,- sim: CitySimulation,- now: number,- paused: boolean,-): void {- const elapsed = Math.max(0, (now - clock.lastMs) / 1000);- clock.lastMs = Math.max(clock.lastMs, now);- if (paused) {- sim.debt = 0;- return;- }- stepWithBudget(sim, elapsed, 20);- clock.hour = advanceHour(clock.hour, elapsed, clock.dayPaused);-}diff --git a/jarvis/ui/web/frontend/src/components/society/city/cityInstances.test.ts b/jarvis/ui/web/frontend/src/components/society/city/cityInstances.test.tsdeleted file mode 100644index f26ff591fa..0000000000--- a/jarvis/ui/web/frontend/src/components/society/city/cityInstances.test.ts+++ /dev/null@@ -1,13 +0,0 @@-import { applyProps } from "@react-three/fiber";-import { BoxGeometry, InstancedMesh, MeshBasicMaterial } from "three";-import { expect, it } from "vitest";-import { releaseCityInstances } from "./cityInstances";--it("releases instance buffers even when R3F shadows the native disposer", () => {- const geometry = new BoxGeometry(), material = new MeshBasicMaterial();- const mesh = new InstancedMesh(geometry, material, 1);- let releases = 0; mesh.addEventListener("dispose", () => releases++);- applyProps(mesh, { dispose: null });- expect(() => releaseCityInstances(mesh)).not.toThrow();- expect(releases).toBe(1); geometry.dispose(); material.dispose();-});diff --git a/jarvis/ui/web/frontend/src/components/society/city/cityInstances.ts b/jarvis/ui/web/frontend/src/components/society/city/cityInstances.tsdeleted file mode 100644index 7df591f819..0000000000--- a/jarvis/ui/web/frontend/src/components/society/city/cityInstances.ts+++ /dev/null@@ -1,6 +0,0 @@-import { InstancedMesh } from "three";--/** R3F's dispose={null} prop can shadow the instance's native dispose method. */-export function releaseCityInstances(mesh: InstancedMesh): void {- InstancedMesh.prototype.dispose.call(mesh);-}diff --git a/jarvis/ui/web/frontend/src/components/society/city/cityModel.ts b/jarvis/ui/web/frontend/src/components/society/city/cityModel.tsdeleted file mode 100644index fdfd2ba7ad..0000000000--- a/jarvis/ui/web/frontend/src/components/society/city/cityModel.ts+++ /dev/null@@ -1,206 +0,0 @@-/** Metre-based city: rendering and routing share the same authored anchors. */-export type Vec3 = [number, number, number];-export type Stop = "west" | "east" | "knowledge" | "workshop" | "communications";-export type DistrictId = "central" | "terminal" | "knowledge" | "workshop" | "communications";-export interface RouteNode { id: string; position: Vec3; layer: "ground" | "platform" | "bridge" | "interior"; }-export interface RouteEdge { from: string; to: string; speed: number; kind: "walk" | "lift" | "interior"; }-export const CITY = { width: 1800, depth: 1200, referenceWidth: 600, referenceDepth: 400, grid: 4 };-export const CAMERA_BOUNDS = { minX: -850, maxX: 850, minZ: -550, maxZ: 550, minDistance: 5, maxDistance: 1500 };-export const MATERIALS = { concrete: "#b8b5ac", graphite: "#252c32", metal: "#aab4bc", glass: "#708b95", green: "#60714d", light: "#ffe1ad" };-/** Clockwise order, matching the train tangent and platform side. */-export const STOPS: Stop[] = ["west", "east", "knowledge", "communications", "workshop"];-export const TRAIN_FLOOR = 12.08;-export const distance = (a: Vec3, b: Vec3) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);-export const mix = (a: Vec3, b: Vec3, t: number): Vec3 => a.map((v, i) => v + (b[i] - v) * t) as Vec3;-/** Three.js Y rotation; train/station local +X points along the track. */-export function transformPoint(origin: Vec3, yaw: number, p: Vec3): Vec3 {- const c = Math.cos(yaw), s = Math.sin(yaw);- return [origin[0] + c * p[0] + s * p[2], origin[1] + p[1], origin[2] - s * p[0] + c * p[2]];-}-export const RAIL_SEGMENTS = 320;-export function railPoint(progress: number): Vec3 {- const angle = Math.PI * 0.7 - progress * Math.PI * 2;- return [500 * Math.cos(angle), 12, -110 + 280 * Math.sin(angle)];-}-export function railHeading(progress: number): number {- const angle = Math.PI * 0.7 - progress * Math.PI * 2;- return Math.atan2(280 * Math.cos(angle), 500 * Math.sin(angle));-}-export const RAIL_POINTS: Vec3[] = Array.from({ length: RAIL_SEGMENTS + 1 }, (_, i) => railPoint(i / RAIL_SEGMENTS));-export interface District {- id: DistrictId; stop: Stop; labelKey: string;- placeId: "civic" | "cli" | "archive" | "skills" | "comms";- color: string; x: number; z: number;- stationPosition: Vec3; stationYaw: number;- buildingPosition: Vec3; buildingRotation: number; workplaces: Vec3[];-}-const districtInfo: Record<Stop, { id: DistrictId; color: string; placeId: District["placeId"] }> = {- west: { id: "central", color: "#d6b76a", placeId: "civic" },- east: { id: "terminal", color: "#54c9e0", placeId: "cli" },- knowledge: { id: "knowledge", color: "#799cde", placeId: "archive" },- workshop: { id: "workshop", color: "#e7a365", placeId: "skills" },- communications: { id: "communications", color: "#65c7b4", placeId: "comms" },-};-export function localWorkplaces(stop: Stop): Vec3[] {- const rows = stop === "east" ? [-9, -5, -1, 3, 7, 11] : [-8, -3, 2, 7, 12, 16];- return rows.flatMap((z) => [-12, -6, 0, 6, 12].map((x): Vec3 => [x, 0, z]));-}-export const DISTRICTS: District[] = STOPS.map((stop, index) => {- const info = districtInfo[stop];- const stationPosition = railPoint(index / STOPS.length);- const stationYaw = railHeading(index / STOPS.length);- const p = transformPoint([stationPosition[0], 0, stationPosition[2]], stationYaw, [0, 0, 88]);- const buildingPosition: Vec3 = [Math.round(p[0] / 4) * 4, 0, Math.round(p[2] / 4) * 4];- return { ...info, stop, labelKey: `society.city.${info.id}`, x: buildingPosition[0], z: buildingPosition[2], stationPosition, stationYaw, buildingPosition, buildingRotation: stationYaw, workplaces: localWorkplaces(stop).map((p) => transformPoint(buildingPosition, stationYaw, p)) };-});-export const STATIONS = DISTRICTS;-export const district = (stop: Stop): District => DISTRICTS.find((d) => d.stop === stop)!;-export const stopX = (stop: Stop): number => district(stop).stationPosition[0];-export const otherStop = (stop: Stop): Stop => STOPS[(STOPS.indexOf(stop) + 1) % STOPS.length];-export type Placements = Record<Stop, Vec3>;-export const defaultPlacements = (): Placements => Object.fromEntries(DISTRICTS.map((d) => [d.stop, [...d.buildingPosition]])) as Placements;-export interface Plot { id: string; x: number; z: number; width: number; depth: number; }-export const PLOTS: Plot[] = DISTRICTS.map((d) => ({ id: d.stop, x: d.x, z: d.z, width: 96, depth: 96 }));-export function validPlacement(plot: Plot, x: number, z: number, width: number, depth: number, occupied: Plot[]): boolean {- if (![x, z, width, depth].every(Number.isFinite) || width <= 0 || depth <= 0 || x % CITY.grid !== 0 || z % CITY.grid !== 0) return false;- if (Math.abs(x - plot.x) + width / 2 > plot.width / 2 || Math.abs(z - plot.z) + depth / 2 > plot.depth / 2) return false;- if (Math.abs(x) + width / 2 > CITY.width / 2 || Math.abs(z) + depth / 2 > CITY.depth / 2) return false;- const d = DISTRICTS.find((candidate) => candidate.stop === plot.id);- if (!d) return false;- const entrance = transformPoint([x, 0, z], d.buildingRotation, [0, 0, -19]);- const plaza = transformPoint([d.stationPosition[0], 0, d.stationPosition[2]], d.stationYaw, [0, 0, 42]);- const outward = transformPoint([0, 0, 0], d.stationYaw, [0, 0, 1]);- // The building must remain outside its plaza, with a clear four-metre entrance strip.- if ((entrance[0] - plaza[0]) * outward[0] + (entrance[2] - plaza[2]) * outward[2] < 8) return false;- const minX = Math.min(entrance[0], plaza[0]) - 2, maxX = Math.max(entrance[0], plaza[0]) + 2;- const minZ = Math.min(entrance[2], plaza[2]) - 2, maxZ = Math.max(entrance[2], plaza[2]) + 2;- return !occupied.some((p) =>- (Math.abs(x - p.x) < (width + p.width) / 2 && Math.abs(z - p.z) < (depth + p.depth) / 2) ||- (p.x + p.width / 2 > minX && p.x - p.width / 2 < maxX && p.z + p.depth / 2 > minZ && p.z - p.depth / 2 < maxZ));-}-export interface SavedCityLayout { version: 2; placements: Placements; }-/** Earlier preview/island coordinates are explicitly migrated to default city plots. */-export function restoreLayout(value: unknown): SavedCityLayout {- const placements = defaultPlacements();- if (!value || typeof value !== "object" || !("version" in value) || value.version !== 2 || !("placements" in value) || !value.placements || typeof value.placements !== "object") return { version: 2, placements };- for (const d of DISTRICTS) {- const p = (value.placements as Record<string, unknown>)[d.stop];- if (Array.isArray(p) && p.length === 3 && p.every((n) => typeof n === "number" && Number.isFinite(n)) && p[1] === 0 && validPlacement(PLOTS.find((plot) => plot.id === d.stop)!, p[0], p[2], 58, 58, [])) placements[d.stop] = [p[0], 0, p[2]];- }- return { version: 2, placements };-}-export interface RouteGraph {- nodes: Map<string, RouteNode>; edges: RouteEdge[];- outgoing: Map<string, RouteEdge[]>; cache: Map<string, string[] | null>;-}-export function createRouteGraph(placements: Placements = defaultPlacements()): RouteGraph {- const nodes = new Map<string, RouteNode>();- const edges: RouteEdge[] = [];- const addNode = (id: string, position: Vec3, layer: RouteNode["layer"]) => nodes.set(id, { id, position, layer });- const link = (from: string, to: string, speed: number, kind: RouteEdge["kind"] = "walk") => { edges.push({ from, to, speed, kind }, { from: to, to: from, speed, kind }); };- for (const d of DISTRICTS) {- const base: Vec3 = [d.stationPosition[0], 0, d.stationPosition[2]];- const local = (p: Vec3) => transformPoint(base, d.stationYaw, p);- const buildingLocal = (p: Vec3) => transformPoint(placements[d.stop], d.buildingRotation, p);- const s = d.stop;- addNode(`${s}:platform`, local([0, TRAIN_FLOOR, 4.2]), "platform");- addNode(`${s}:upper`, local([0, TRAIN_FLOOR, 15]), "platform");- addNode(`${s}:lift`, local([0, 0, 15]), "ground");- addNode(`${s}:plaza`, local([0, 0, 42]), "ground");- addNode(`${s}:entry`, buildingLocal([0, 0, -19]), "ground");- addNode(`${s}:foyer`, buildingLocal([-3, 0, -15]), "interior");- link(`${s}:platform`, `${s}:upper`, 1.8);- link(`${s}:upper`, `${s}:lift`, 3, "lift");- link(`${s}:lift`, `${s}:plaza`, 2.4);- link(`${s}:plaza`, `${s}:entry`, 2.4);- link(`${s}:entry`, `${s}:foyer`, 1.5, "interior");- localWorkplaces(s).forEach((p, index) => {- const row = Math.floor(index / 5), aisle = `${s}:aisle:${row}`;- if (!nodes.has(aisle)) {- addNode(aisle, buildingLocal([-3, 0, p[2] - 1.5]), "interior");- link(row === 0 ? `${s}:foyer` : `${s}:aisle:${row - 1}`, aisle, 1.5, "interior");- }- addNode(`${s}:approach:${index}`, buildingLocal([p[0], 0, p[2] - 1.5]), "interior");- addNode(`${s}:work:${index}`, buildingLocal(p), "interior");- link(aisle, `${s}:approach:${index}`, 1.5, "interior");- link(`${s}:approach:${index}`, `${s}:work:${index}`, 1.5, "interior");- });- addNode(`${s}:work`, buildingLocal([0, 0, -9]), "interior");- link(`${s}:aisle:0`, `${s}:work`, 1.5, "interior");- }- // The public promenade follows the viaduct outside, without cutting across halls.- for (let index = 0; index < STOPS.length; index++) {- let previous = `${STOPS[index]}:plaza`;- for (let step = 1; step < 16; step++) {- const progress = (index + step / 16) / STOPS.length;- const p = railPoint(progress), id = `promenade:${index}:${step}`;- addNode(id, transformPoint([p[0], 0, p[2]], railHeading(progress), [0, 0, 42]), "ground");- link(previous, id, 2.4);- previous = id;- }- link(previous, `${otherStop(STOPS[index])}:plaza`, 2.4);- }- addNode("cross:ground", [0, 0, 200], "ground");- addNode("cross:bridge", [0, 20, 200], "bridge");- addNode("bridge:north", [0, 20, 80], "bridge");- addNode("bridge:south", [0, 20, 260], "bridge");- addNode("bridge:base", [0, 0, 260], "ground");- link("promenade:0:8", "cross:ground", 2.4);- link("cross:ground", "bridge:base", 2.4);- link("bridge:base", "bridge:south", 3, "lift");- link("bridge:south", "cross:bridge", 2.4);- link("cross:bridge", "bridge:north", 2.4);- const outgoing = new Map<string, RouteEdge[]>();- for (const e of edges) outgoing.set(e.from, [...(outgoing.get(e.from) ?? []), e]);- return { nodes, edges, outgoing, cache: new Map() };-}-export const DEFAULT_GRAPH = createRouteGraph();-export const NODES = [...DEFAULT_GRAPH.nodes.values()];-export const EDGES = DEFAULT_GRAPH.edges;-export const node = (id: string, graph: RouteGraph = DEFAULT_GRAPH): RouteNode | undefined => graph.nodes.get(id);-export interface Walkway { id: string; a: Vec3; b: Vec3; width: number; layer: RouteNode["layer"]; }-export function graphWalkways(graph: RouteGraph): Walkway[] {- return graph.edges.filter((e) => e.from < e.to && e.kind === "walk").map((e) => ({ id: `${e.from}/${e.to}`, a: node(e.from, graph)!.position, b: node(e.to, graph)!.position, width: e.from.includes("platform") || e.to.includes("platform") ? 5 : 6, layer: node(e.from, graph)!.layer }));-}-export const WALKWAYS = graphWalkways(DEFAULT_GRAPH);-export const LIFTS = EDGES.filter((e) => e.kind === "lift" && node(e.from)!.position[1] < node(e.to)!.position[1]).map((e) => ({ id: e.from, a: node(e.from)!.position, b: node(e.to)!.position }));-/** Indexed adjacency and reusable paths avoid searching the graph on every frame. */-export function route(from: string, to: string, blocked = new Set<string>(), graph: RouteGraph = DEFAULT_GRAPH): string[] | null {- if (!node(from, graph) || !node(to, graph) || blocked.has(to) || blocked.has(from)) return null;- const key = `${from}|${to}`;- if (blocked.size === 0 && graph.cache.has(key)) { const cached = graph.cache.get(key); return cached ? [...cached] : null; }- const costs = new Map([[from, 0]]), previous = new Map<string, string>(), visited = new Set<string>();- while (true) {- let id: string | undefined, cost = Infinity;- for (const [candidate, value] of costs) if (!visited.has(candidate) && value < cost) { id = candidate; cost = value; }- if (id === undefined) { if (blocked.size === 0) graph.cache.set(key, null); return null; }- if (id === to) {- const path = [to];- while (previous.has(path[0])) path.unshift(previous.get(path[0])!);- if (blocked.size === 0) graph.cache.set(key, path);- return [...path];- }- visited.add(id);- for (const edge of graph.outgoing.get(id) ?? []) {- if (blocked.has(edge.to)) continue;- const next = cost + distance(node(id, graph)!.position, node(edge.to, graph)!.position) / edge.speed;- if (next < (costs.get(edge.to) ?? Infinity)) { costs.set(edge.to, next); previous.set(edge.to, id); }- }- }-}-export function routeSeconds(path: string[] | null, graph: RouteGraph = DEFAULT_GRAPH): number {- if (!path) return Infinity;- return path.slice(1).reduce((sum, id, i) => {- const edge = graph.outgoing.get(path[i])?.find((e) => e.to === id);- return edge ? sum + distance(node(path[i], graph)!.position, node(id, graph)!.position) / edge.speed : Infinity;- }, 0);-}-/** This maps presentation checkpoints; dispatch never depends on travel. */-export function checkpointStop(checkpoint: string): Stop | null {- if (["desk", "hub:cli", "hub:desktop", "hub:models"].includes(checkpoint)) return "east";- if (["archive", "gallery"].includes(checkpoint)) return "knowledge";- if (["hub:skills", "hub:plugins"].includes(checkpoint)) return "workshop";- if (["hub:mcp", "hub:web", "hub:comms", "gate"].includes(checkpoint)) return "communications";- if (["meeting", "civic"].includes(checkpoint)) return "west";- return null;-}diff --git a/jarvis/ui/web/frontend/src/components/society/city/cityMotion.test.ts b/jarvis/ui/web/frontend/src/components/society/city/cityMotion.test.tsdeleted file mode 100644index 666e84a34e..0000000000--- a/jarvis/ui/web/frontend/src/components/society/city/cityMotion.test.ts+++ /dev/null@@ -1,22 +0,0 @@-import { act, renderHook } from "@testing-library/react";-import { expect, it } from "vitest";-import { useCityReducedMotion } from "./cityMotion";--it("reacts to an accessibility preference changed after the city mounts", () => {- const original = Object.getOwnPropertyDescriptor(window, "matchMedia");- class Media extends EventTarget { matches = false; }- const media = new Media();- Object.defineProperty(window, "matchMedia", { configurable: true, value: () => media });- const hook = renderHook(useCityReducedMotion);- try {- expect(hook.result.current).toBe(false);- act(() => { media.matches = true; media.dispatchEvent(new Event("change")); });- expect(hook.result.current).toBe(true);- act(() => { media.matches = false; media.dispatchEvent(new Event("change")); });- expect(hook.result.current).toBe(false);- } finally {- hook.unmount();- if (original) Object.defineProperty(window, "matchMedia", original);- else Reflect.deleteProperty(window, "matchMedia");- }-});diff --git a/jarvis/ui/web/frontend/src/components/society/city/cityMotion.ts b/jarvis/ui/web/frontend/src/components/society/city/cityMotion.tsdeleted file mode 100644index f67c224738..0000000000--- a/jarvis/ui/web/frontend/src/components/society/city/cityMotion.ts+++ /dev/null@@ -1,16 +0,0 @@-import { useSyncExternalStore } from "react";--const QUERY = "(prefers-reduced-motion: reduce)";-function snapshot(): boolean {- return typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia(QUERY).matches;-}-function subscribe(listener: () => void): () => void {- if (typeof window.matchMedia !== "function") return () => undefined;- const media = window.matchMedia(QUERY);- media.addEventListener("change", listener);- return () => media.removeEventListener("change", listener);-}-/** The installed motion hook snapshots only at mount; city travel must react live. */-export function useCityReducedMotion(): boolean {- return useSyncExternalStore(subscribe, snapshot, () => false);-}diff --git a/jarvis/ui/web/frontend/src/components/society/city/citySession.test.ts b/jarvis/ui/web/frontend/src/components/society/city/citySession.test.tsdeleted file mode 100644index 81c467ffd3..0000000000--- a/jarvis/ui/web/frontend/src/components/society/city/citySession.test.ts+++ /dev/null@@ -1,18 +0,0 @@-import { expect, it } from "vitest";-import { defaultPlacements } from "./cityModel";-import { addCitizen, setTarget, stepSimulation } from "./citySimulation";-import { createCitySessions } from "./citySession";--it("retains a physical journey when leaving and reopening the city section", () => {- const sessions = createCitySessions();- const first = sessions.get("live", defaultPlacements, 0);- const person = addCitizen(first.sim, "agent", "west"); setTarget(first.sim, person.id, "east", 1); stepSimulation(first.sim, 10);- const position = [...person.position];- const reopened = sessions.get("live", defaultPlacements, 50000);- expect(reopened).toBe(first); expect(reopened.sim.citizens.get(person.id)!.position).toEqual(position);-});-it("keeps demo journeys separate from real agent positions", () => {- const sessions = createCitySessions(); const live = sessions.get("live", defaultPlacements, 0), demo = sessions.get("demo", defaultPlacements, 0);- addCitizen(demo.sim, "example", "west"); stepSimulation(demo.sim, 50);- expect(live.sim.citizens.size).toBe(0); expect(live.sim.time).toBe(0); expect(demo.sim.time).toBeCloseTo(50);-});diff --git a/jarvis/ui/web/frontend/src/components/society/city/citySession.ts b/jarvis/ui/web/frontend/src/components/society/city/citySession.tsdeleted file mode 100644index f070aac4eb..0000000000--- a/jarvis/ui/web/frontend/src/components/society/city/citySession.ts+++ /dev/null@@ -1,17 +0,0 @@-import { createCityClock, type CityClock } from "./cityClock";-import { createSimulation, type CitySimulation } from "./citySimulation";-import type { Placements } from "./cityModel";--interface Session { sim: CitySimulation; clock: CityClock }-/** Lazy, browser-local state survives section switches without keeping a canvas alive. */-export function createCitySessions() {- const sessions = new Map<"live" | "demo" | "sample", Session>();- return {- get(kind: "live" | "demo" | "sample", placements: () => Placements, now: number): Session {- let session = sessions.get(kind);- if (!session) { session = { sim: createSimulation(placements()), clock: createCityClock(now) }; sessions.set(kind, session); }- return session;- },- };-}-export const citySessions = createCitySessions();diff --git a/jarvis/ui/web/frontend/src/components/society/city/citySimulation.test.ts b/jarvis/ui/web/frontend/src/components/society/city/citySimulation.test.tsdeleted file mode 100644index 6ae4521eab..0000000000--- a/jarvis/ui/web/frontend/src/components/society/city/citySimulation.test.ts+++ /dev/null@@ -1,353 +0,0 @@-import { describe, expect, it } from "vitest";-import {- CAMERA_BOUNDS, checkpointStop, createRouteGraph, defaultPlacements, DISTRICTS,- district, distance, graphWalkways, localWorkplaces, node, PLOTS, RAIL_POINTS,- restoreLayout, route, STOPS, transformPoint, validPlacement,-} from "./cityModel";-import {- addCitizen, advanceHour, cancelJourney, CAPACITY, createSimulation, CYCLE,- DWELL, LEG_RIDES, moveBuilding, nextDeparture, previewCrossing, safeDestination,- setTarget, setTaskActive, STARTUP_HOLD, stepSimulation, stepWithBudget, trainAt,- type CitySimulation, type Citizen,-} from "./citySimulation";--function task(sim: CitySimulation, id: string, target: Citizen["target"], revision = 1): Citizen {- const c = addCitizen(sim, id);- setTarget(sim, id, target, revision);- setTaskActive(sim, id, true);- return c;-}-function until(sim: CitySimulation, predicate: () => boolean, timeout = 1200): void {- const deadline = sim.time + timeout;- while (!predicate() && sim.time < deadline) stepSimulation(sim, 0.1);- expect(predicate(), `Condition not reached by ${sim.time.toFixed(1)} seconds`).toBe(true);-}--describe("city graph and authored layout", () => {- it("contains all five functional destinations with the matching scene anchors", () => {- expect(DISTRICTS).toHaveLength(5);- expect(new Set(DISTRICTS.map((d) => d.stop)).size).toBe(5);- for (const d of DISTRICTS) {- expect(node(`${d.stop}:entry`)!.position).toEqual(transformPoint(d.buildingPosition, d.buildingRotation, [0, 0, -19]));- d.workplaces.forEach((p, i) => expect(node(`${d.stop}:work:${i}`)!.position).toEqual(p));- expect(route(`${d.stop}:platform`, `${d.stop}:work:29`)).not.toBeNull();- }- });- it("renders precisely the external graph links and closes its rail ring", () => {- const graph = createRouteGraph();- for (const path of graphWalkways(graph)) {- const [from, to] = path.id.split("/");- expect(path.a).toEqual(node(from, graph)!.position);- expect(path.b).toEqual(node(to, graph)!.position);- }- expect(distance(RAIL_POINTS[0], RAIL_POINTS.at(-1)!)).toBeLessThan(1e-8);- expect(CAMERA_BOUNDS.minX).toBeGreaterThan(-900);- expect(CAMERA_BOUNDS.maxZ).toBeLessThan(600);- });- it("never changes floors where bridge and ground overlap", () => {- expect(node("cross:ground")!.position[0]).toBe(node("cross:bridge")!.position[0]);- expect(route("cross:ground", "cross:bridge")).toEqual(["cross:ground", "bridge:base", "bridge:south", "cross:bridge"]);- expect(route("cross:ground", "cross:bridge", new Set(["bridge:base"]))).toBeNull();- });- it("approaches workstations in front of chairs rather than walking through them", () => {- const path = route("east:entry", "east:work:4")!;- expect(path.at(-2)).toBe("east:approach:4");- const p = localWorkplaces("east")[4], d = district("east");- expect(node("east:approach:4")!.position).toEqual(transformPoint(d.buildingPosition, d.buildingRotation, [p[0], 0, p[2] - 1.5]));- });- it("routes semantic checkpoints to the corresponding five districts", () => {- expect(checkpointStop("desk")).toBe("east");- expect(checkpointStop("hub:cli")).toBe("east");- expect(checkpointStop("meeting")).toBe("west");- expect(checkpointStop("archive")).toBe("knowledge");- expect(checkpointStop("hub:plugins")).toBe("workshop");- expect(checkpointStop("hub:web")).toBe("communications");- expect(checkpointStop("unknown")).toBeNull();- });- it("rejects overlap, malformed coordinates and off-grid placements", () => {- const p = PLOTS[0];- expect(validPlacement(p, p.x, p.z, 58, 58, [])).toBe(true);- expect(validPlacement(p, p.x + 1, p.z, 58, 58, [])).toBe(false);- expect(validPlacement(p, p.x, p.z, 58, 58, [p])).toBe(false);- expect(validPlacement(p, NaN, p.z, 58, 58, [])).toBe(false);- expect(validPlacement(p, p.x, p.z, 0, 58, [])).toBe(false);- expect(validPlacement(p, p.x + 100, p.z, 58, 58, [])).toBe(false);- });- it("migrates legacy coordinates and validates each saved plot independently", () => {- const defaults = defaultPlacements();- expect(restoreLayout({ version: 1, placements: { west: [-120, 0, 104] } }).placements).toEqual(defaults);- const changed = { ...defaults, west: [defaults.west[0] + 4, 0, defaults.west[2]], east: [Infinity, 0, 0] };- const restored = restoreLayout({ version: 2, placements: changed });- expect(restored.placements.west).toEqual(changed.west);- expect(restored.placements.east).toEqual(defaults.east);- expect(restoreLayout(null).placements).toEqual(defaults);- });- it("updates the actual entrance route when an empty building is moved", () => {- const sim = createSimulation(), d = district("east");- const before = node("east:entry", sim.graph)!.position;- expect(moveBuilding(sim, "east", [d.x + 4, 0, d.z])).toBe(true);- expect(node("east:entry", sim.graph)!.position[0]).toBeCloseTo(before[0] + 4);- const c = addCitizen(sim, "inside");- c.at = "east:work:0";- expect(moveBuilding(sim, "east", [d.x, 0, d.z])).toBe(false);- });-});--describe("physical city journeys", () => {- it("boards, rides, alights and operates a real terminal workstation without snapping", () => {- const sim = createSimulation(), c = task(sim, "one", "east");- const stages = new Set<string>();- let last = [...c.position] as Citizen["position"];- until(sim, () => {- stages.add(c.stage);- expect(distance(c.position, last)).toBeLessThan(2.8);- last = [...c.position];- return c.stage === "working";- });- for (const stage of ["walking", "waiting", "boarding", "riding", "exiting", "working"]) expect(stages.has(stage), stage).toBe(true);- expect(c.atWork).toBe(true);- expect(c.at).toBe(`east:work:${c.workIndex}`);- expect(c.position).toEqual(node(c.at, sim.graph)!.position);- expect(c.heading).toBe(district("east").buildingRotation);- expect(c.seat).toBeNull();- });- it("keeps working intent separate from the physical location", () => {- const sim = createSimulation(), c = task(sim, "one", "east");- expect(c.taskActive).toBe(true);- expect(c.atWork).toBe(false);- expect(c.at).toBe("west:plaza");- until(sim, () => c.stage === "working");- setTaskActive(sim, c.id, false);- expect(c.stage).toBe("arrived");- expect(c.atWork).toBe(true);- });- it("crosses the actual platform door only while the metro is stopped", () => {- const sim = createSimulation(), c = task(sim, "one", "east");- until(sim, () => c.stage === "boarding");- let closest = Infinity;- until(sim, () => {- if (c.stage !== "boarding") return true;- const train = trainAt(sim.time);- expect(train.stop).toBe("west");- expect(train.doorsOpen).toBe(true);- closest = Math.min(closest, distance(c.position, transformPoint(train.position, train.heading, [0, 0.08, 2.55])));- return false;- });- expect(closest).toBeLessThan(0.2);- expect(c.stage).toBe("riding");- });- it("reaches every district around the connected city", () => {- for (const stop of STOPS) {- const sim = createSimulation(), c = task(sim, "one", stop);- until(sim, () => c.stage === "working");- expect(c.at).toBe(`${stop}:work:0`);- }- });- it("retains passengers through intermediate ring stops", () => {- const sim = createSimulation(), c = task(sim, "one", "knowledge");- until(sim, () => c.stage === "riding");- until(sim, () => trainAt(sim.time).stop === "east");- expect(c.stage).toBe("riding");- expect(c.alightAt).toBe("knowledge");- until(sim, () => c.stage === "working");- expect(c.at).toBe("knowledge:work:0");- });- it("reserves seats and retains a queue when a train fills", () => {- const sim = createSimulation();- for (let i = 0; i < CAPACITY + 3; i++) {- const c = addCitizen(sim, String(i));- c.at = "west:platform"; c.position = [...node(c.at, sim.graph)!.position];- setTarget(sim, c.id, "east", 1); setTaskActive(sim, c.id, true);- }- stepSimulation(sim, 15);- const passengers = [...sim.citizens.values()].filter((c) => c.seat !== null);- expect(passengers).toHaveLength(CAPACITY);- expect(new Set(passengers.map((c) => c.seat)).size).toBe(CAPACITY);- expect([...sim.citizens.values()].filter((c) => c.stage === "waiting")).toHaveLength(3);- until(sim, () => [...sim.citizens.values()].every((c) => c.stage === "working"));- expect(new Set([...sim.citizens.values()].map((c) => c.workIndex)).size).toBe(CAPACITY + 3);- });- it("misses a departure when there is insufficient time to board", () => {- const sim = createSimulation();- sim.time = STARTUP_HOLD + DWELL - 1;- const c = addCitizen(sim, "one"); c.at = "west:platform"; c.position = [...node(c.at, sim.graph)!.position];- c.target = "east"; c.taskActive = true; c.stage = "waiting"; c.alightAt = "east";- stepSimulation(sim, 0.2);- expect(c.stage).toBe("waiting"); expect(c.seat).toBeNull();- until(sim, () => c.stage === "working");- });- it("leaves a workspace queue for a preview walk without stale queue replanning", () => {- const sim = createSimulation();- for (let i = 0; i < 31; i++) task(sim, String(i), "west");- const c = sim.citizens.get("30")!;- until(sim, () => c.waitingForWorkspace);- expect(previewCrossing(sim, c.id)).toBe(true);- expect(c.waitingForWorkspace).toBe(false);- stepSimulation(sim, 1);- const before = [...c.position] as Citizen["position"];- setTaskActive(sim, c.id, false);- stepSimulation(sim, 0.1);- expect(distance(c.position, before)).toBeLessThan(0.3);- until(sim, () => c.at === "bridge:north");- });- it("queues a full workplace and reaches a newly vacated desk physically", () => {- const sim = createSimulation();- for (let i = 0; i < 31; i++) task(sim, String(i), "west");- const waiting = sim.citizens.get("30")!;- until(sim, () => waiting.waitingForWorkspace);- expect(waiting.stage).toBe("waiting");- expect(waiting.atWork).toBe(false);- until(sim, () => sim.citizens.get("0")!.stage === "working");- cancelJourney(sim, "0", 2);- const before = [...waiting.position];- stepSimulation(sim, 0.1);- expect(distance(waiting.position, before as Citizen["position"])).toBeLessThan(0.3);- until(sim, () => waiting.stage === "working");- expect(waiting.workIndex).toBe(0);- expect(waiting.waitingForWorkspace).toBe(false);- expect(waiting.position).toEqual(node("west:work:0", sim.graph)!.position);- });- it("retargets on board at the next station and ignores older activity", () => {- const sim = createSimulation(), c = task(sim, "one", "knowledge");- until(sim, () => c.stage === "riding");- const p = [...c.position];- setTarget(sim, c.id, "west", 3); setTarget(sim, c.id, "knowledge", 2);- expect(c.position).toEqual(p); expect(c.target).toBe("west");- expect(c.alightAt).toBe("east");- until(sim, () => c.stage === "exiting");- expect(c.alightAt).toBe("east");- until(sim, () => c.stage === "working");- expect(c.at).toBe("west:work:0");- });- it("does not force a passenger off at an intermediate stop for a same-target update", () => {- const sim = createSimulation(), c = task(sim, "one", "knowledge");- until(sim, () => c.stage === "riding");- setTarget(sim, c.id, "knowledge", 2);- expect(c.alightAt).toBe("knowledge");- });- it("defers a late-dwell retarget until a stop with enough time to exit", () => {- const sim = createSimulation(), c = task(sim, "one", "knowledge");- until(sim, () => trainAt(sim.time).stop === "east" && trainAt(sim.time).remaining < 1);- expect(c.stage).toBe("riding");- expect(safeDestination(sim, c)).toBe("knowledge");- setTarget(sim, c.id, "west", 2);- expect(c.alightAt).toBe("knowledge");- stepSimulation(sim, 2);- expect(c.stage).toBe("riding");- expect(trainAt(sim.time).doorsOpen).toBe(false);- until(sim, () => c.stage === "exiting");- expect(trainAt(sim.time).stop).toBe("knowledge");- until(sim, () => c.stage === "working");- expect(c.at).toBe("west:work:0");- });- it("cancels to a safe station without teleporting or operating an old terminal", () => {- const sim = createSimulation(), c = task(sim, "one", "knowledge");- until(sim, () => c.stage === "riding");- const before = [...c.position];- cancelJourney(sim, c.id, 2);- expect(c.position).toEqual(before); expect(c.taskActive).toBe(false);- until(sim, () => c.stage === "arrived");- expect(c.at).toBe("east:plaza"); expect(c.atWork).toBe(false);- });- it("settles at the physical arrival station when work ends while exiting", () => {- const sim = createSimulation(), c = task(sim, "one", "east");- until(sim, () => c.stage === "exiting");- expect(safeDestination(sim, c)).toBe("east");- cancelJourney(sim, c.id, 2);- until(sim, () => c.stage === "arrived");- expect(c.at).toBe("east:plaza");- });- it("cancels a local approach after its current physical edge", () => {- const sim = createSimulation(), c = task(sim, "one", "west");- stepSimulation(sim, 1);- const p = [...c.position];- cancelJourney(sim, c.id, 2);- expect(c.position).toEqual(p);- expect(c.path.length).toBeLessThanOrEqual(2);- until(sim, () => c.stage === "arrived");- expect(c.at).toBe("west:plaza");- expect(c.workIndex).toBeNull();- });- it("physically returns to a workstation after cancelling and reactivating", () => {- const sim = createSimulation(), c = task(sim, "one", "west");- until(sim, () => c.stage === "working");- cancelJourney(sim, c.id, 2);- stepSimulation(sim, 1);- expect(c.stage).toBe("walking");- expect(c.atWork).toBe(false);- const p = [...c.position];- setTaskActive(sim, c.id, true);- expect(c.position).toEqual(p);- expect(c.stage).toBe("walking");- until(sim, () => c.stage === "working");- expect(c.at).toBe("west:work:0");- expect(c.position).toEqual(node(c.at, sim.graph)!.position);- });- it("reports unreachable targets and resumes on a newer intent", () => {- const sim = createSimulation();- sim.blocked.add("east:entry");- const c = task(sim, "one", "east");- // The preexisting access leg is completed before the blocked interior is reconsidered.- until(sim, () => c.stage === "unreachable");- sim.blocked.clear(); setTarget(sim, c.id, "east", 2);- until(sim, () => c.stage === "working");- });- it("walks the preview bridge at its exact deck height", () => {- const sim = createSimulation(), c = addCitizen(sim, "one");- expect(previewCrossing(sim, c.id)).toBe(true);- until(sim, () => c.at === "cross:bridge");- expect(c.position[1]).toBe(20);- until(sim, () => c.at === "bridge:north");- expect(c.stage).toBe("arrived");- });- it("does not reset a journey when the same roster citizen is observed again", () => {- const sim = createSimulation(), c = task(sim, "one", "east");- stepSimulation(sim, 20);- const p = [...c.position];- expect(addCitizen(sim, c.id)).toBe(c); expect(c.position).toEqual(p);- });-});--describe("train clock and bounded catch-up", () => {- it("keeps every train arrival and departure position continuous", () => {- let phase = STARTUP_HOLD;- for (const duration of LEG_RIDES) {- for (const time of [phase, phase + DWELL, phase + DWELL + duration]) expect(distance(trainAt(time - 0.001).position, trainAt(time).position)).toBeLessThan(0.03);- phase += DWELL + duration;- }- expect(trainAt(STARTUP_HOLD + CYCLE + 1).stop).toBe("west");- });- it("reserves the occupied block and closes its doors while moving", () => {- expect(trainAt(0).reservedBlock).toBe("platform:west");- const moving = trainAt(STARTUP_HOLD + DWELL + 10);- expect(moving.doorsOpen).toBe(false); expect(moving.reservedBlock).toBe("track:west:east");- expect(nextDeparture("west", 0)).toBe(STARTUP_HOLD + DWELL);- });- it("matches continuous travel when processing a hidden interval", () => {- const a = createSimulation(), b = createSimulation();- task(a, "one", "knowledge"); task(b, "one", "knowledge");- stepSimulation(a, 90);- for (let i = 0; i < 900; i++) stepSimulation(b, 0.1);- expect(a.citizens.get("one")!.stage).toBe(b.citizens.get("one")!.stage);- expect(distance(a.citizens.get("one")!.position, b.citizens.get("one")!.position)).toBeLessThan(1e-6);- });- it("limits catch-up work while retaining every elapsed second", () => {- const sim = createSimulation(), reference = createSimulation();- task(sim, "one", "knowledge"); task(reference, "one", "knowledge");- stepWithBudget(sim, 90, 20);- expect(sim.time).toBeCloseTo(2); expect(sim.debt).toBeCloseTo(88);- while (sim.debt > 0.00001) stepWithBudget(sim, 0, 20);- stepSimulation(reference, 90);- expect(distance(sim.citizens.get("one")!.position, reference.citizens.get("one")!.position)).toBeLessThan(1e-6);- });- it("skips empty idle intervals without moving any citizen", () => {- const sim = createSimulation(), c = addCitizen(sim, "one");- const p = [...c.position];- stepWithBudget(sim, 3600, 5);- expect(sim.time).toBe(3600); expect(sim.debt).toBe(0); expect(c.position).toEqual(p);- });- it("pauses and wraps the independent 30-minute daylight cycle", () => {- expect(advanceHour(10, 1800, false)).toBe(10);- expect(advanceHour(10, 300, true)).toBe(10);- });-});diff --git a/jarvis/ui/web/frontend/src/components/society/city/citySimulation.ts b/jarvis/ui/web/frontend/src/components/society/city/citySimulation.tsdeleted file mode 100644index a2527950ba..0000000000--- a/jarvis/ui/web/frontend/src/components/society/city/citySimulation.ts+++ /dev/null@@ -1,311 +0,0 @@-import {- createRouteGraph, defaultPlacements, distance, district, mix, node,- railHeading, railPoint, RAIL_POINTS, RAIL_SEGMENTS, route, routeSeconds,- STOPS, transformPoint, PLOTS, validPlacement,- type Placements, type RouteGraph, type Stop, type Vec3,-} from "./cityModel";--export const DWELL = 18;-export const CAPACITY = 24;-export const STARTUP_HOLD = 42;-const MAX_SPEED = 26;-const ACCELERATION = 3;-const STEP = 0.1;-const BOARD_SPEED = 1.8;-const CUMULATIVE = RAIL_POINTS.reduce<number[]>((lengths, p, i) => {- lengths.push(i ? lengths[i - 1] + distance(RAIL_POINTS[i - 1], p) : 0);- return lengths;-}, []);-export const LEG_LENGTHS = STOPS.map((_, i) => CUMULATIVE[(i + 1) * RAIL_SEGMENTS / STOPS.length] - CUMULATIVE[i * RAIL_SEGMENTS / STOPS.length]);-export const LEG_RIDES = LEG_LENGTHS.map((length) => length / MAX_SPEED + MAX_SPEED / ACCELERATION);-export const RIDE = LEG_RIDES[0];-export const CYCLE = LEG_RIDES.reduce((sum, duration) => sum + DWELL + duration, 0);-const PHASES = STOPS.map((_, i) => LEG_RIDES.slice(0, i).reduce((sum, duration) => sum + duration + DWELL, 0));-export type JourneyStage = "arrived" | "working" | "walking" | "waiting" | "boarding" | "riding" | "exiting" | "unreachable";-export interface TrainState {- position: Vec3; stop: Stop | null; next: Stop; remaining: number; heading: number;- doorsOpen: boolean; reservedBlock: string; speed: number;-}-function sampledProgress(length: number): number {- let low = 0, high = CUMULATIVE.length - 1;- while (low + 1 < high) {- const mid = (low + high) >> 1;- if (CUMULATIVE[mid] <= length) low = mid; else high = mid;- }- return (low + (length - CUMULATIVE[low]) / (CUMULATIVE[high] - CUMULATIVE[low])) / RAIL_SEGMENTS;-}-/** A single train holds one ring block at a time; smooth acceleration preserves passengers. */-export function trainAt(time: number): TrainState {- const raw = Math.max(0, time) - STARTUP_HOLD;- const t = raw < 0 ? 0 : raw % CYCLE;- let leg = STOPS.length - 1;- for (let i = 0; i < STOPS.length; i++) if (t < PHASES[i] + DWELL + LEG_RIDES[i] - 1e-9) { leg = i; break; }- const stop = STOPS[leg], next = STOPS[(leg + 1) % STOPS.length];- const phase = t - PHASES[leg];- if (phase < DWELL) {- const progress = leg / STOPS.length;- const remaining = DWELL - phase + (raw < 0 ? -raw : 0);- return { position: railPoint(progress), stop, next, remaining, heading: railHeading(progress), doorsOpen: remaining > 0.4, reservedBlock: `platform:${stop}`, speed: 0 };- }- const elapsed = phase - DWELL, duration = LEG_RIDES[leg], ramp = MAX_SPEED / ACCELERATION;- let travelled: number, speed: number;- if (elapsed < ramp) { travelled = ACCELERATION * elapsed * elapsed / 2; speed = ACCELERATION * elapsed; }- else if (elapsed > duration - ramp) {- const left = duration - elapsed;- travelled = LEG_LENGTHS[leg] - ACCELERATION * left * left / 2; speed = ACCELERATION * left;- } else { travelled = MAX_SPEED * (elapsed - ramp / 2); speed = MAX_SPEED; }- const progress = sampledProgress(CUMULATIVE[leg * RAIL_SEGMENTS / STOPS.length] + Math.max(0, Math.min(LEG_LENGTHS[leg], travelled)));- return { position: railPoint(progress), stop: null, next, remaining: duration - elapsed, heading: railHeading(progress), doorsOpen: false, reservedBlock: `track:${stop}:${next}`, speed };-}-export function nextDeparture(stop: Stop, time: number, boardingSeconds = 12): number {- const first = STARTUP_HOLD + PHASES[STOPS.indexOf(stop)] + DWELL;- return first + Math.max(0, Math.ceil((time + boardingSeconds + 0.5 - first) / CYCLE)) * CYCLE;-}-export function rideSeconds(from: Stop, to: Stop): number {- let i = STOPS.indexOf(from), total = 0;- while (STOPS[i] !== to) { total += LEG_RIDES[i]; i = (i + 1) % STOPS.length; if (STOPS[i] !== to) total += DWELL; }- return total;-}-export interface Citizen {- id: string; position: Vec3; at: string; target: Stop; stage: JourneyStage;- path: string[]; edgeTime: number; speed: number; heading: number;- seat: number | null; boardingAt: Stop | null; alightAt: Stop | null;- transition: number; transitionFrom: Vec3; transitionPath: Vec3[];- queued: number; revision: number; lane: number;- taskActive: boolean; atWork: boolean; workIndex: number | null;- waitingForWorkspace: boolean;- previewTarget: string | null;-}-export interface CitySimulation {- time: number; citizens: Map<string, Citizen>; blocked: Set<string>;- graph: RouteGraph; placements: Placements; debt: number;- reservedBlock: string;- nextBoardAt: number;- nextWorkCheck: number;-}-export function createSimulation(placements: Placements = defaultPlacements()): CitySimulation {- return { time: 0, citizens: new Map(), blocked: new Set(), graph: createRouteGraph(placements), placements, debt: 0, reservedBlock: "platform:west", nextBoardAt: 0, nextWorkCheck: 0 };-}-export function safeDestination(sim: CitySimulation, citizen: Citizen): Stop {- if (citizen.seat !== null) {- const train = trainAt(sim.time);- return citizen.stage === "exiting" && citizen.alightAt ? citizen.alightAt : canAlight(sim, citizen, train) ? train.stop! : train.next;- }- return STOPS.reduce((best, stop) => distance(citizen.position, node(`${stop}:plaza`, sim.graph)!.position) < distance(citizen.position, node(`${best}:plaza`, sim.graph)!.position) ? stop : best);-}-export function addCitizen(sim: CitySimulation, id: string, stop: Stop = "west"): Citizen {- const existing = sim.citizens.get(id);- if (existing) return existing;- const used = new Set([...sim.citizens.values()].map((c) => c.lane));- let lane = 0; while (used.has(lane)) lane++;- const p = [...node(`${stop}:plaza`, sim.graph)!.position] as Vec3;- const c: Citizen = { id, position: p, at: `${stop}:plaza`, target: stop, stage: "arrived", path: [], edgeTime: 0, speed: 0, heading: district(stop).buildingRotation, seat: null, boardingAt: null, alightAt: null, transition: 0, transitionFrom: p, transitionPath: [], queued: sim.time, revision: -1, lane, taskActive: false, atWork: false, workIndex: null, waitingForWorkspace: false, previewTarget: null };- c.position = routePoint(sim, c, c.at); sim.citizens.set(id, c); return c;-}-function routePoint(sim: CitySimulation, c: Citizen, id: string): Vec3 {- const n = node(id, sim.graph)!;- if (id.endsWith(":foyer")) {- const stop = id.split(":")[0] as Stop;- return transformPoint(n.position, district(stop).buildingRotation, [((c.lane % 7) - 3) * 0.45, 0, Math.floor(c.lane / 7) % 5 * 0.45]);- }- if (n.layer === "interior" || id.endsWith(":entry") || id.includes("bridge") || id.startsWith("cross:")) return [...n.position];- const stop = STOPS.find((s) => id.startsWith(`${s}:`));- const offset: Vec3 = [((c.lane % 7) - 3) * 0.3, 0, Math.floor(c.lane / 7) % 5 * 0.3];- return transformPoint(n.position, stop ? district(stop).stationYaw : 0, offset);-}-function assignWorkspace(sim: CitySimulation, c: Citizen): void {- const reserved = new Set([...sim.citizens.values()].filter((other) => other.id !== c.id && other.target === c.target && other.workIndex !== null).map((other) => other.workIndex));- if (c.workIndex !== null && !reserved.has(c.workIndex)) return;- c.workIndex = Array.from({ length: 30 }, (_, i) => i).find((i) => !reserved.has(i)) ?? null;-}-export function setTaskActive(sim: CitySimulation, id: string, active: boolean): void {- const c = sim.citizens.get(id);- if (!c || c.taskActive === active) return;- c.taskActive = active;- if (c.atWork && ["arrived", "working"].includes(c.stage) && c.at.startsWith(`${c.target}:work:`)) { c.stage = active ? "working" : "arrived"; return; }- if (!active && c.waitingForWorkspace && c.stage === "waiting") { plan(sim, c); return; }- if (active && c.stage === "walking") c.path = c.path.slice(0, 2);- if (active && c.stage === "arrived") plan(sim, c);-}-export function setTarget(sim: CitySimulation, id: string, target: Stop, revision: number): void {- const c = sim.citizens.get(id);- if (!c || !STOPS.includes(target) || revision <= c.revision) return;- c.revision = revision;- if (c.target === target && !c.previewTarget && !["arrived", "unreachable"].includes(c.stage)) return;- if (c.target !== target) c.workIndex = null;- c.target = target; c.previewTarget = null; c.atWork = false;- if (c.stage === "boarding" || c.stage === "riding") {- const train = trainAt(sim.time);- // Retargeting is an intent change; disembark at the next physical opportunity.- c.alightAt = canAlight(sim, c, train) ? train.stop! : train.next;- return;- }- if (c.stage === "exiting") return;- if (c.stage === "walking" && c.path.length > 1) { c.path = c.path.slice(0, 2); return; }- plan(sim, c);-}-export function cancelJourney(sim: CitySimulation, id: string, revision: number): void {- const c = sim.citizens.get(id);- if (!c || revision <= c.revision) return;- c.taskActive = false;- c.workIndex = null;- setTarget(sim, id, safeDestination(sim, c), revision);- // Cancelling within the current district must also trim a same-target access route.- if (c.stage === "walking" && c.path.length > 1) c.path = c.path.slice(0, 2);- else if (c.waitingForWorkspace || ["arrived", "working", "unreachable"].includes(c.stage)) plan(sim, c);-}-export function previewCrossing(sim: CitySimulation, id: string): boolean {- const c = sim.citizens.get(id);- if (!c || !["arrived", "working", "waiting", "unreachable"].includes(c.stage)) return false;- const path = route(c.at, "bridge:north", sim.blocked, sim.graph);- if (!path) return false;- c.previewTarget = "bridge:north"; c.atWork = false; c.waitingForWorkspace = false; c.path = path; c.edgeTime = 0; c.stage = "walking"; return true;-}-function destination(sim: CitySimulation, c: Citizen): string {- if (c.previewTarget) return c.previewTarget;- if (!c.taskActive) return `${c.target}:plaza`;- assignWorkspace(sim, c);- return c.workIndex === null ? `${c.target}:foyer` : `${c.target}:work:${c.workIndex}`;-}-function plan(sim: CitySimulation, c: Citizen): void {- c.edgeTime = 0; c.speed = 0; c.atWork = false; c.waitingForWorkspace = false;- const targetNode = destination(sim, c);- if (c.at === targetNode) {- c.path = []; c.atWork = targetNode.includes(":work:");- c.waitingForWorkspace = c.taskActive && c.workIndex === null && targetNode === `${c.target}:foyer`;- c.stage = c.waitingForWorkspace ? "waiting" : c.atWork && c.taskActive ? "working" : "arrived";- c.heading = district(c.target).buildingRotation; return;- }- const direct = route(c.at, targetNode, sim.blocked, sim.graph);- let selected = direct, best = routeSeconds(direct, sim.graph), alight: Stop | null = null;- if (!c.previewTarget && !sim.blocked.has(targetNode)) {- const exit = route(`${c.target}:platform`, targetNode, sim.blocked, sim.graph);- for (const stop of STOPS) {- if (stop === c.target || !exit) continue;- const access = route(c.at, `${stop}:platform`, sim.blocked, sim.graph);- if (!access) continue;- const reach = sim.time + routeSeconds(access, sim.graph);- const total = nextDeparture(stop, reach) - sim.time + rideSeconds(stop, c.target) + 12 + routeSeconds(exit, sim.graph);- if (total < best) { best = total; selected = access; alight = c.target; }- }- }- c.alightAt = alight;- if (!selected) { c.stage = "unreachable"; c.path = []; return; }- c.path = selected;- if (selected.length > 1) c.stage = "walking";- else { c.stage = "waiting"; c.queued = sim.time; }-}-function seatLocal(seat: number): Vec3 {- return [(seat % 12 - 5.5) * 1.5, 0.08, seat < 12 ? -0.8 : 0.8];-}-export function seatPosition(train: TrainState, seat: number): Vec3 { return transformPoint(train.position, train.heading, seatLocal(seat)); }-function doorPath(train: TrainState, seat: number): Vec3[] {- const local = seatLocal(seat);- return [[0, 0.08, 4.2], [0, 0.08, 2.55], [0, 0.08, 0], [local[0], 0.08, 0], local].map((p) => transformPoint(train.position, train.heading, p as Vec3));-}-function pathLength(points: Vec3[]): number { return points.slice(1).reduce((sum, p, i) => sum + distance(points[i], p), 0); }-function alightingPath(sim: CitySimulation, c: Citizen, train: TrainState): Vec3[] {- return [...doorPath(train, c.seat!).reverse(), routePoint(sim, c, `${train.stop}:platform`)];-}-function canAlight(sim: CitySimulation, c: Citizen, train: TrainState): boolean {- return train.stop !== null && train.stop !== c.boardingAt && train.remaining >= pathLength(alightingPath(sim, c, train)) / BOARD_SPEED + 0.5;-}-function advanceTransition(c: Citizen, dt: number): boolean {- c.transition += dt;- let travelled = c.transition * BOARD_SPEED;- const points = c.transitionPath;- for (let i = 1; i < points.length; i++) {- const a = points[i - 1], b = points[i], length = distance(a, b);- if (travelled < length && length > 1e-8) {- c.position = mix(a, b, travelled / length); c.speed = BOARD_SPEED;- c.heading = Math.atan2(b[0] - a[0], b[2] - a[2]); return false;- }- travelled -= length;- }- c.position = [...points[points.length - 1]]; c.speed = 0; return true;-}-function advanceWalk(sim: CitySimulation, c: Citizen, dt: number): void {- let left = dt;- while (left > 1e-8 && c.stage === "walking") {- const [from, to] = c.path;- if (!to) { plan(sim, c); break; }- const edge = sim.graph.outgoing.get(from)?.find((e) => e.to === to);- if (!edge || (sim.blocked.has(to) && c.edgeTime === 0)) { plan(sim, c); break; }- const a = routePoint(sim, c, from), b = routePoint(sim, c, to);- const duration = distance(a, b) / edge.speed;- const consumed = Math.min(left, Math.max(0, duration - c.edgeTime));- c.edgeTime += consumed; left -= consumed;- c.position = mix(a, b, duration ? Math.min(1, c.edgeTime / duration) : 1);- c.speed = edge.kind === "lift" ? 0 : edge.speed;- if (a[0] !== b[0] || a[2] !== b[2]) c.heading = Math.atan2(b[0] - a[0], b[2] - a[2]);- if (c.edgeTime + 1e-8 < duration) break;- c.at = to; c.path.shift(); c.edgeTime = 0;- if (c.path.length < 2) plan(sim, c);- }-}-function advance(sim: CitySimulation, dt: number): void {- sim.time += dt;- const train = trainAt(sim.time);- sim.reservedBlock = train.reservedBlock;- if (sim.time >= sim.nextWorkCheck) {- sim.nextWorkCheck = sim.time + 1;- for (const c of sim.citizens.values()) if (c.waitingForWorkspace && c.stage === "waiting") plan(sim, c);- }- for (const c of sim.citizens.values()) {- if (c.stage === "walking") advanceWalk(sim, c, dt);- else if (c.stage === "boarding") {- if (advanceTransition(c, dt)) { c.stage = "riding"; c.position = seatPosition(train, c.seat!); }- } else if (c.stage === "riding") {- c.position = seatPosition(train, c.seat!); c.speed = 0; c.heading = train.heading + Math.PI / 2;- if (train.stop && train.stop === c.alightAt && canAlight(sim, c, train)) {- const path = alightingPath(sim, c, train);- c.stage = "exiting"; c.transition = 0; c.transitionFrom = [...c.position]; c.transitionPath = path;- }- } else if (c.stage === "exiting" && advanceTransition(c, dt)) {- c.at = `${c.alightAt}:platform`; c.seat = null; c.boardingAt = null;- plan(sim, c);- }- }- if (!train.stop || !train.doorsOpen || sim.time < sim.nextBoardAt) return;- if ([...sim.citizens.values()].some((c) => c.stage === "exiting")) return;- const occupied = new Set([...sim.citizens.values()].filter((c) => c.seat !== null).map((c) => c.seat));- for (const c of [...sim.citizens.values()].filter((c) => c.stage === "waiting" && c.at === `${train.stop}:platform` && sim.time - c.queued >= 0.4).sort((a, b) => a.queued - b.queued || a.id.localeCompare(b.id))) {- const seat = Array.from({ length: CAPACITY }, (_, i) => i).find((i) => !occupied.has(i));- if (seat === undefined) break;- const path = [[...c.position] as Vec3, ...doorPath(train, seat)];- if (pathLength(path) / BOARD_SPEED + 0.5 > train.remaining) continue;- occupied.add(seat); c.seat = seat; c.stage = "boarding"; c.boardingAt = train.stop;- c.transition = 0; c.transitionFrom = [...c.position]; c.transitionPath = path;- sim.nextBoardAt = sim.time + 0.35;- break;- }-}-/** Test/offline advance with physical substeps; runtime should use the budgeted driver. */-export function stepSimulation(sim: CitySimulation, seconds: number): void {- if (!Number.isFinite(seconds) || seconds <= 0) return;- let left = seconds;- while (left > 1e-8) { const dt = Math.min(STEP, left); advance(sim, dt); left -= dt; }-}-/** Retains elapsed time as debt while bounding catch-up work for one event-loop turn. */-export function stepWithBudget(sim: CitySimulation, seconds: number, maxSteps = 40): void {- if (!Number.isFinite(seconds) || seconds < 0 || !Number.isFinite(maxSteps) || maxSteps < 1) return;- sim.debt += seconds;- if ([...sim.citizens.values()].every((c) => ["arrived", "working", "unreachable"].includes(c.stage))) {- sim.time += sim.debt; sim.debt = 0; sim.reservedBlock = trainAt(sim.time).reservedBlock; return;- }- for (let i = 0; i < Math.floor(maxSteps) && sim.debt >= STEP - 1e-8; i++) {- advance(sim, STEP); sim.debt = Math.max(0, sim.debt - STEP);- }-}-/** Occupied interiors cannot be moved under a physical journey. */-export function moveBuilding(sim: CitySimulation, stop: Stop, position: Vec3): boolean {- const plot = PLOTS.find((p) => p.id === stop)!;- if (position[1] !== 0 || !validPlacement(plot, position[0], position[2], 58, 58, [])) return false;- const interior = (id: string) => id.startsWith(`${stop}:`) && ["entry", "foyer", "aisle", "approach", "work"].includes(id.split(":")[1]);- if ([...sim.citizens.values()].some((c) => interior(c.at) || c.path.some(interior))) return false;- sim.placements = { ...sim.placements, [stop]: [...position] };- sim.graph = createRouteGraph(sim.placements);- return true;-}-export function daylight(hour: number): number { return Math.max(0, Math.sin(((hour - 6) / 24) * Math.PI * 2)); }-export function advanceHour(hour: number, dt: number, paused: boolean): number { return paused ? hour : ((hour + dt * 24 / 1800) % 24 + 24) % 24; }diff --git a/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsxindex 8284a31558..f6a210c161 100644--- a/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx+++ b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx@@ -36,6 +36,7 @@ import { DepartureBoard } from "./sub-agents/DepartureBoard";import { AgentInsight } from "./sub-agents/AgentInsight";import { selectTaskRows } from "./sub-agents/rows";import { mergeBoardRows, HISTORY_LIMIT, normalizeTraceId } from "./sub-agents/missionRows";+import { resolveAgentsMode, type AgentsMode } from "./sub-agents/agentsMode";import { fetchMissions } from "@/components/missions/api";import { useMissionWebSocket } from "@/components/missions/useMissionWebSocket";import { useMissionsStore } from "@/components/missions/store";@@ -54,26 +55,24 @@ const RUN_PARAM = "run";* WebGL is absent. The world is a lazy chunk — three.js and the island never* load for someone who only ever reads the ledger.*/-type AgentsMode = "world" | "ledger" | "city";const MODE_KEY = "jarvis.agents.mode.v2";const WorldStage = lazy(() =>import("@/components/society/world/WorldStage").then((m) => ({ default: m.WorldStage })),);-const CityStage = lazy(() =>- import("@/components/society/city/CityStage").then((m) => ({ default: m.CityStage })),-);-function readMode(): AgentsMode {if (!detectWebgl()) return "ledger";try {const raw = localStorage.getItem(MODE_KEY);- if (raw === "city" || raw === "world" || raw === "ledger") return raw;- if (localStorage.getItem("jarvis.agents.mode") === "ledger") return "ledger";+ if (raw === "city") writeMode("world");+ const legacy = raw === "city" || raw === "world" || raw === "ledger"+ ? null+ : localStorage.getItem("jarvis.agents.mode");+ return resolveAgentsMode(raw, legacy, true);} catch {/* private mode: fall through to the default */}- return "city";+ return "world";}function writeMode(mode: AgentsMode): void {@@ -95,9 +94,8 @@ function ModeSwitch({ mode, onChange }: { mode: AgentsMode; onChange: (m: AgentsonChange={onChange}label={t("society.world.mode_label")}options={[- { id: "city", label: t("society.city.mode") },+ { id: "world", label: t("society.world.mode_world") },{ id: "ledger", label: t("society.world.mode_ledger") },- { id: "world", label: t("society.city.legacy_mode") },]}/></div>@@ -260,10 +258,6 @@ export function JarvisAgentsView({ onSelectAgent, onSelectPlace }: JarvisAgentsVconst modeSwitch = <ModeSwitch mode={mode} onChange={switchMode} />;- if (mode === "city") {- return <Suspense fallback={<WorldLoading />}><CityStage topRight={modeSwitch} onOpenLedger={() => switchMode("ledger")} onSelectAgent={onSelectAgent} onSelectPlace={onSelectPlace} /></Suspense>;- }-if (mode === "world") {return (<div className="h-full min-h-0">diff --git a/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx b/jarvis/ui/web/frontend/src/views/society/SocietyView.tsxindex 032afeb1e3..59a2a4b336 100644--- a/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx+++ b/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx@@ -12,7 +12,7 @@*/import { lazy, Suspense, useCallback, useMemo, useState } from "react";-import { useLocaleChunk, useT } from "@/i18n";+import { useT } from "@/i18n";import { AgentCardOverlay } from "@/components/society/card/AgentCardOverlay";import { BuildingCardOverlay } from "@/components/society/card/BuildingCardOverlay";import { isBuildingPlace, type BuildingPlace } from "@/components/society/card/buildingCards";@@ -30,7 +30,6 @@ const JarvisAgentsBoard = lazy(() =>export function SocietyView() {useModelMenuData();const t = useT();- const cityTextReady = useLocaleChunk("society");const roster = useSocietyRoster();const agents = useMemo(() => roster.data?.agents ?? [], [roster.data]);const sample = roster.data?.sample ?? true;@@ -73,7 +72,6 @@ export function SocietyView() {<span aria-live="polite">{t("society.strip.active").replace("{0}", String(activeCount))}</span>- <span className="ml-auto">{cityTextReady ? t("society.city.subtitle") : null}</span></div><div className="relative min-h-0 flex-1"><CanvasActivity.Provider value={!openAgent && !openPlace && !creating}>diff --git a/jarvis/ui/web/frontend/src/views/sub-agents/agentsMode.test.ts b/jarvis/ui/web/frontend/src/views/sub-agents/agentsMode.test.tsnew file mode 100644index 0000000000..660c55cf73--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/sub-agents/agentsMode.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from "vitest";++import { resolveAgentsMode } from "./agentsMode";++describe("agent view preference migration", () => {+ it("opens the original world when no preference exists", () => {+ expect(resolveAgentsMode(null, null, true)).toBe("world");+ });++ it.each([null, "world", "ledger"])(+ "restores a saved city to world even when the old preference is %s",+ (legacy) => {+ expect(resolveAgentsMode("city", legacy, true)).toBe("world");+ },+ );++ it.each(["world", "ledger"] as const)(+ "preserves the current %s preference",+ (stored) => {+ expect(resolveAgentsMode(stored, stored === "world" ? "ledger" : "world", true)).toBe(stored);+ },+ );++ it("honors a legacy ledger choice when the current preference is unset or invalid", () => {+ expect(resolveAgentsMode(null, "ledger", true)).toBe("ledger");+ expect(resolveAgentsMode("unknown", "ledger", true)).toBe("ledger");+ expect(resolveAgentsMode("unknown", null, true)).toBe("world");+ });++ it.each([null, "city", "world", "ledger", "unknown"])(+ "uses the ledger without WebGL for stored preference %s",+ (stored) => {+ expect(resolveAgentsMode(stored, null, false)).toBe("ledger");+ },+ );+});diff --git a/jarvis/ui/web/frontend/src/views/sub-agents/agentsMode.ts b/jarvis/ui/web/frontend/src/views/sub-agents/agentsMode.tsnew file mode 100644index 0000000000..f540e5d2b5--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/sub-agents/agentsMode.ts@@ -0,0 +1,14 @@+/** Resolve persisted view preferences after retiring the city prototype. */+export type AgentsMode = "world" | "ledger";++export function resolveAgentsMode(+ stored: string | null,+ legacy: string | null,+ webglSupported: boolean,+): AgentsMode {+ if (!webglSupported) return "ledger";+ // A newer city preference takes precedence over an older ledger preference.+ if (stored === "city") return "world";+ if (stored === "world" || stored === "ledger") return stored;+ return legacy === "ledger" ? "ledger" : "world";+}