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
feat(agents): walkable office prototype with rooms, checkpoints and agent life
rubenluetke10-beep85c03df792c8
diff --git a/docs/agent-society/office-map.md b/docs/agent-society/office-map.mdindex fba0d88d5e..60c5abb077 100644--- a/docs/agent-society/office-map.md+++ b/docs/agent-society/office-map.md@@ -1,6 +1,6 @@# Agent office map-Status: **first map built 2026-09-28, awaiting the maintainer's visual review.**+Status: **walkable prototype built 2026-09-28, awaiting the maintainer's visual review.**It replaces the Mars colony as the renderer behind **Agents > Map**. The Marscode, its backend contracts and the communications station remain in the treeand reachable from the Agents workspace; only the map surface changed.@@ -48,37 +48,70 @@ the renderer is already Three.js inside the WebView, the figures and theiranimation clips (`sit`, `work`, `idle`, `walk`, …) already exist, and every OStarget runs WebGL.-## 4. Layout model--`officeLayout.ts` is pure and tested:--- Departments = provider families (`providerLabel`; empty means Jarvis' own- brain). At most six; the rest fold into "Other". The floor always shows at- least four; spare ones are "Open space" with free desks.-- Each department is benches of back-to-back desks, four per row, eight per- bench, one to four benches.-- The lead tier sits in a glass office at the back; a lounge fills the front.-- Seating is by arrival (`createdMs`, then id), so a refetch never re-seats- anyone; run state changes only repaint monitors and rings.--## 5. Plan--1. **First map (done):** floor, departments, lead office, lounge, seated- figures, state rings/monitors/pills, HUD counts, camera, click-to-open.-2. **Review:** the maintainer looks at the map in the app. Capture feedback on- look, camera and department grouping before any further art.-3. **Life:** optional short walks (desk ↔ lounge when idle for long), typing- animation while working, a "waiting for you" bubble. Driven only by real- state changes, never by LLM calls.-4. **Detail pass:** a coffee corner, meeting room for group chats, per-department- decor, name boards with provider logos.-5. **Scale and performance:** instanced desks for large rosters, measured frame- times on a laptop GPU and a low-end integrated GPU.--## 6. Verification so far--- Unit tests: `officeLayout.test.ts` (grouping, stable seating, no overlap,- empty roster, camera framing), `JarvisAgentsView.test.tsx`.+## 4. Floor plan and data model++`officeLayout.ts` is pure and tested. It builds the whole floor from the roster:++- **North strip:** lead office (lead-tier agents), team room (long table, board),+ wardrobe (lockers, mirror). Glass walls with a door towards the office.+- **Middle:** departments = provider families (`providerLabel`; empty means+ Jarvis' own brain), two columns, at least four (spare ones are "Open space"),+ at most six (the rest fold into "Other"). Benches of back-to-back desks.+- **South strip:** an open reception/lobby with the elevator, the reception desk+ and the agent board; a walled break room with couches, coffee bar, water+ cooler, arcade and beanbags.+- **Furniture** has fixed footprints (`FURNITURE_SIZE`) shared by renderer and+ navigation; **spots** are hangout places with pose and facing; **checkpoints**+ are action places; **obstacles** are every solid footprint.+- Seating is by arrival (`createdMs`, then id), so a refetch never re-seats anyone.++## 5. Behaviour, player and interaction++- **Navigation** (`officeNav.ts`): a 0.2 m occupancy grid, A* with line-of-sight+ smoothing, and a final snap onto seats that sit inside a furniture footprint.+- **Agents** (`officeBehavior.ts`, `OfficeAgents.tsx`): working → seated at their+ own screen; waiting → standing at the desk, waving; paused → napping on a+ couch; idle → a weighted day of coffee, couch, window, arcade, books, water+ cooler, team table, strolling or chatting at a busy colleague's desk. Spots are+ reserved so nobody sits on anybody. All of it is client-side, deterministic+ per agent, costs no tokens and never starts or stops work. Reduced motion+ places agents without walking. Agents created while the office is open arrive+ by the elevator.+- **The person's character** (`OfficePlayer.tsx`, `playerProfile.ts`): WASD /+ arrows (camera-relative, Shift runs) or click the floor to walk; E interacts+ with the nearest agent or checkpoint. Name and body are chosen in the+ wardrobe and stored per browser profile (not roster data).+- **Camera** (`OfficeCameraRig.tsx`): one orbit camera that glides after the+ character; zoom out and it is the overview. Everything stays clickable from+ afar, so walking is optional. A right-drag pan or a fly-to stops following;+ moving resumes it.+- **Checkpoints** (`OfficePanels.tsx`): reception → create an agent (existing+ dialog); agent board → list, show on map, open, agent management; team room →+ pick agents and create a team (existing chat groups), gather teams at the+ table; wardrobe → your look; lead office → talk to the lead; break room → call+ free agents for a coffee break (visual only).+- **Agent panel:** open chat, walk there, call over, show on map, add to a new team.++## 6. Plan++1. First map (done 2026-09-28).+2. Walkable prototype (done 2026-09-28): rooms, checkpoints, agent life, own character.+3. **Review:** the maintainer plays it and gives feedback on look, camera, rooms and actions.+4. Polish: typing animation while working, speech bubbles for "waiting for you",+ door animations, agents greeting the person, sound.+5. Scale: instanced chairs/props beyond desks, measured frame times on a laptop+ GPU and a low-end integrated GPU, macOS/Linux WebViews.++## 7. Verification so far++- Unit tests: layout (grouping, stable seating, no overlap, camera framing),+ navigation (every seat, spot and checkpoint reachable from the elevator for+ 0/10/40 agents; paths never cross obstacles), motion, behaviour (state rules,+ exclusive spots, determinism), props (every kind renders inside its footprint).+- Runtime (Chrome, dev build, live roster of ten agents): walking by click and+ by keyboard, camera follow and overview, nearby prompt and E, agent panel,+ "call over". Desks are instanced; the full floor measured ~730 draw calls and+ ~18 ms per frame on the development machine.- Runtime: checked in Chrome against the live roster (ten agents, one lead)through a temporary dev preview: rendering, click on figure and on pill.- Not yet measured: frame time and device coverage; macOS/Linux WebViews.diff --git a/jarvis/ui/web/frontend/src/components/society/office/CheckpointMarker.tsx b/jarvis/ui/web/frontend/src/components/society/office/CheckpointMarker.tsxnew file mode 100644index 0000000000..b9ce4b29c2--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/CheckpointMarker.tsx@@ -0,0 +1,210 @@+/**+ * A checkpoint the person walks to (or clicks from afar): a gold ring on the+ * floor, a floating hexagon token with a canvas-drawn icon, and a label pill.+ * Icons are simple SVG path strings, drawn on the token's canvas and inlined+ * in the pill — no emoji, no icon fonts, nothing fetched.+ */+import { useEffect, useMemo, useRef } from "react";+import { Html } from "@react-three/drei";+import { useFrame, type ThreeEvent } from "@react-three/fiber";+import {+ CircleGeometry, CylinderGeometry, DoubleSide, MeshStandardMaterial, Vector3,+ type Group, type Mesh, type MeshBasicMaterial,+} from "three";+import { plateScale } from "./OfficeAgents";+import { cachedCanvasTexture } from "./OfficeProps";+import type { Checkpoint } from "./officeLayout";+import { CHECKPOINT_GOLD } from "./officePalette";++export type CheckpointIcon = "plus" | "list" | "team" | "shirt" | "star" | "coffee";++/** Stroke-only icons in a 24 × 24 box (round caps and joins). */+export const CHECKPOINT_ICON_PATHS: Record<CheckpointIcon, string> = {+ plus: "M12 5v14M5 12h14",+ list: "M9 6h11M9 12h11M9 18h11M4.5 6h.01M4.5 12h.01M4.5 18h.01",+ team: "M9 11a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM3 20c0-3.3 2.7-5.5 6-5.5s6 2.2 6 5.5M16.5 11a2.5 2.5 0 1 0 0-5M18 14.5c2 .6 3.5 2.4 3.5 5",+ shirt: "M8 3L3 6l2 4 2.5-1v12h9V9l2.5 1 2-4-5-3c-.5 1.5-2 2.5-4 2.5S8.5 4.5 8 3z",+ star: "M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z",+ coffee: "M4 9h12v5a5 5 0 0 1-5 5H9a5 5 0 0 1-5-5V9zM16 10h1.5a2.5 2.5 0 0 1 0 5H16M8 3.5c0 1 1 1 1 2M12 3.5c0 1 1 1 1 2",+};++const TOKEN_RADIUS = 0.36;+const TOKEN_DEPTH = 0.1;+/** Height of the token centre above the floor. */+export const TOKEN_Y = 1.7;+const LABEL_Y = TOKEN_Y - 0.62;+const RING_Y = 0.025;++// A flat-topped hexagon prism whose faces point along ±z; the face discs match its corners.+const prismGeometry = new CylinderGeometry(TOKEN_RADIUS, TOKEN_RADIUS, TOKEN_DEPTH, 6, 1, false, Math.PI / 2);+prismGeometry.rotateX(Math.PI / 2);+const faceGeometry = new CircleGeometry(TOKEN_RADIUS * 0.9, 6);++const rimMaterial = new MeshStandardMaterial({+ color: CHECKPOINT_GOLD.rim, roughness: 0.4, metalness: 0.2, emissive: CHECKPOINT_GOLD.ring, emissiveIntensity: 0.3,+});++const faceMaterials = new Map<CheckpointIcon, MeshStandardMaterial>();+function faceMaterial(icon: CheckpointIcon): MeshStandardMaterial {+ let material = faceMaterials.get(icon);+ if (!material) {+ const map = cachedCanvasTexture(`checkpoint:${icon}`, 256, 256, (ctx, w, h) => {+ const grad = ctx.createLinearGradient(0, 0, 0, h);+ grad.addColorStop(0, CHECKPOINT_GOLD.face);+ grad.addColorStop(1, CHECKPOINT_GOLD.faceDeep);+ ctx.fillStyle = grad;+ ctx.fillRect(0, 0, w, h);+ // Inner hexagon outline (flat top, matching the geometry).+ ctx.strokeStyle = "rgba(255,255,255,0.55)";+ ctx.lineWidth = 6;+ ctx.beginPath();+ for (let i = 0; i < 6; i += 1) {+ const a = (i * Math.PI) / 3;+ const x = w / 2 + Math.cos(a) * w * 0.4, y = h / 2 + Math.sin(a) * h * 0.4;+ if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);+ }+ ctx.closePath();+ ctx.stroke();+ if (typeof Path2D === "undefined") return;+ const path = new Path2D(CHECKPOINT_ICON_PATHS[icon]);+ const scale = 5.2;+ ctx.save();+ ctx.translate(w / 2 - 12 * scale, h / 2 - 12 * scale);+ ctx.scale(scale, scale);+ ctx.lineCap = "round";+ ctx.lineJoin = "round";+ // A soft dark under-stroke keeps the white icon readable on gold.+ ctx.translate(0.25, 0.3);+ ctx.strokeStyle = "rgba(90,55,0,0.45)";+ ctx.lineWidth = 3.2;+ ctx.stroke(path);+ ctx.translate(-0.25, -0.3);+ ctx.strokeStyle = CHECKPOINT_GOLD.icon;+ ctx.lineWidth = 2.3;+ ctx.stroke(path);+ ctx.restore();+ });+ material = new MeshStandardMaterial({+ color: map ? "#ffffff" : CHECKPOINT_GOLD.face, map, roughness: 0.45,+ emissive: "#ffffff", emissiveMap: map, emissiveIntensity: map ? 0.5 : 0,+ });+ faceMaterials.set(icon, material);+ }+ return material;+}++function IconSvg({ icon }: { icon: CheckpointIcon }) {+ return (+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2.4} strokeLinecap="round" strokeLinejoin="round" aria-hidden>+ <path d={CHECKPOINT_ICON_PATHS[icon]} />+ </svg>+ );+}++export function CheckpointMarker({ checkpoint, label, icon, active, animate, onActivate }: {+ checkpoint: Checkpoint;+ label: string;+ icon: CheckpointIcon;+ active: boolean;+ animate: boolean;+ onActivate: () => void;+}) {+ const token = useRef<Group>(null);+ const ring = useRef<Mesh>(null);+ const pulse = useRef<Mesh>(null);+ const anchor = useRef<Group>(null);+ const pill = useRef<HTMLButtonElement>(null);+ const lastScale = useRef(0);+ const hovered = useRef(false);+ const world = useMemo(() => new Vector3(), []);+ // A per-checkpoint phase so the tokens do not bob in lockstep.+ const phase = useMemo(() => [...checkpoint.id].reduce((sum, ch) => sum + ch.charCodeAt(0), 0) % 7, [checkpoint.id]);+ const face = faceMaterial(icon);+ const ringOpacity = active ? 0.95 : 0.6;+ const fillOpacity = active ? 0.16 : 0.07;++ useFrame(({ clock, camera }, delta) => {+ const t = clock.elapsedTime + phase;+ if (token.current) {+ if (animate) {+ token.current.position.y = TOKEN_Y + Math.sin(t * 1.8) * 0.07;+ token.current.rotation.y += delta * (active ? 1.2 : 0.6);+ } else {+ token.current.position.y = TOKEN_Y;+ token.current.rotation.y = Math.PI / 4;+ }+ }+ if (ring.current) {+ const material = ring.current.material as MeshBasicMaterial;+ material.opacity = animate && active ? 0.75 + Math.sin(t * 4) * 0.2 : ringOpacity;+ }+ if (pulse.current) {+ const material = pulse.current.material as MeshBasicMaterial;+ if (animate && active) {+ const k = (t % 1.6) / 1.6;+ pulse.current.visible = true;+ pulse.current.scale.setScalar(1 + k * 0.35);+ material.opacity = 0.6 * (1 - k);+ } else {+ pulse.current.visible = false;+ }+ }+ if (anchor.current && pill.current) {+ const scale = plateScale(camera.position.distanceTo(anchor.current.getWorldPosition(world)));+ if (Math.abs(scale - lastScale.current) >= 0.02) {+ lastScale.current = scale;+ pill.current.style.transform = `scale(${scale.toFixed(2)})`;+ }+ }+ });++ // Never leave a pointer cursor behind when the marker unmounts under the mouse.+ useEffect(() => () => { if (hovered.current) document.body.style.cursor = ""; }, []);++ const activate = (event: ThreeEvent<MouseEvent>) => { event.stopPropagation(); onActivate(); };+ const over = (event: ThreeEvent<PointerEvent>) => {+ event.stopPropagation();+ hovered.current = true;+ document.body.style.cursor = "pointer";+ };+ const out = () => {+ hovered.current = false;+ document.body.style.cursor = "";+ };++ return (+ <group position={[checkpoint.x, 0, checkpoint.z]} name={`checkpoint:${checkpoint.id}`}>+ {/* Floor ring, a faint fill and (active + animated) an expanding pulse. */}+ <mesh ref={ring} rotation={[-Math.PI / 2, 0, 0]} position={[0, RING_Y, 0]}>+ <ringGeometry args={[Math.max(0.05, checkpoint.radius - 0.09), checkpoint.radius, 64]} />+ <meshBasicMaterial color={CHECKPOINT_GOLD.ring} transparent opacity={ringOpacity} side={DoubleSide} depthWrite={false} toneMapped={false} />+ </mesh>+ <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, RING_Y - 0.002, 0]}>+ <circleGeometry args={[Math.max(0.05, checkpoint.radius - 0.09), 64]} />+ <meshBasicMaterial color={CHECKPOINT_GOLD.ring} transparent opacity={fillOpacity} depthWrite={false} toneMapped={false} />+ </mesh>+ <mesh ref={pulse} rotation={[-Math.PI / 2, 0, 0]} position={[0, RING_Y + 0.002, 0]} visible={false}>+ <ringGeometry args={[Math.max(0.05, checkpoint.radius - 0.04), checkpoint.radius, 64]} />+ <meshBasicMaterial color={CHECKPOINT_GOLD.ring} transparent opacity={0} side={DoubleSide} depthWrite={false} toneMapped={false} />+ </mesh>++ {/* Floating hexagon token with the icon on both faces. */}+ <group ref={token} position={[0, TOKEN_Y, 0]} rotation={[0, Math.PI / 4, 0]} scale={active ? 1.15 : 1}+ onClick={activate} onPointerOver={over} onPointerOut={out}>+ <mesh geometry={prismGeometry} material={rimMaterial} castShadow />+ <mesh geometry={faceGeometry} material={face} position={[0, 0, TOKEN_DEPTH / 2 + 0.002]} />+ <mesh geometry={faceGeometry} material={face} position={[0, 0, -TOKEN_DEPTH / 2 - 0.002]} rotation={[0, Math.PI, 0]} />+ </group>++ <group ref={anchor} position={[0, LABEL_Y, 0]}>+ <Html center zIndexRange={[20, 0]}>+ <button ref={pill} type="button" data-office-ui className="office-checkpoint" data-active={active ? "true" : "false"}+ onClick={(event) => { event.stopPropagation(); onActivate(); }}>+ <span className="office-checkpoint-badge"><IconSvg icon={icon} /></span>+ <span className="office-checkpoint-label">{label}</span>+ </button>+ </Html>+ </group>+ </group>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/DeskInstances.tsx b/jarvis/ui/web/frontend/src/components/society/office/DeskInstances.tsxnew file mode 100644index 0000000000..e2981c0397--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/DeskInstances.tsx@@ -0,0 +1,88 @@+/**+ * Every workstation on the floor, drawn as instanced meshes: one draw call+ * per desk part instead of one per part per desk. Same parts and local+ * placement as `Desk` in OfficeFurniture (the agent sits at local +z and looks+ * north at its monitor); a desk facing south is rotated half a turn.+ */+import { useLayoutEffect, useMemo, useRef } from "react";+import { BufferGeometry, Euler, InstancedMesh, Matrix4, PlaneGeometry, Quaternion, Vector3, type Material } from "three";+import { RoundedBoxGeometry } from "three-stdlib";+import type { SocietyAgent } from "../data";+import { GEO, MAT, screenMaterial } from "./OfficeFurniture";+import type { DeskSlot } from "./officeLayout";+import type { ScreenFace } from "./screenTextures";++interface Part { geometry: BufferGeometry; material: Material; position: [number, number, number]; scale?: [number, number, number]; cast: boolean }++const CHAIR_Z = 0.72;+const rounded = (w: number, h: number, d: number, r: number) => new RoundedBoxGeometry(w, h, d, 2, r);++const PARTS: Part[] = [+ { geometry: rounded(1.5, 0.06, 0.8, 0.02), material: MAT.deskTop, position: [0, 0.74, 0], cast: true },+ { geometry: GEO.box, material: MAT.deskBody, position: [0.53, 0.36, 0], scale: [0.36, 0.7, 0.72], cast: true },+ { geometry: GEO.box, material: MAT.deskLeg, position: [-0.7, 0.36, 0], scale: [0.05, 0.7, 0.7], cast: true },+ { geometry: GEO.box, material: MAT.deskBody, position: [0, 0.94, -0.41], scale: [1.5, 0.34, 0.03], cast: true },+ { geometry: GEO.box, material: MAT.monitor, position: [0, 0.87, -0.22], scale: [0.08, 0.2, 0.08], cast: true },+ { geometry: GEO.box, material: MAT.monitor, position: [0, 0.78, -0.22], scale: [0.24, 0.02, 0.16], cast: true },+ { geometry: rounded(0.72, 0.44, 0.05, 0.02), material: MAT.monitor, position: [0, 1.18, -0.24], cast: true },+ { geometry: GEO.box, material: MAT.keyboard, position: [0, 0.78, 0.1], scale: [0.42, 0.02, 0.14], cast: true },+ { geometry: GEO.cyl, material: MAT.chair, position: [0, 0.03, CHAIR_Z], scale: [0.3, 0.04, 0.3], cast: true },+ { geometry: GEO.cyl, material: MAT.chair, position: [0, 0.25, CHAIR_Z], scale: [0.03, 0.42, 0.03], cast: false },+ { geometry: rounded(0.5, 0.08, 0.48, 0.03), material: MAT.chairSeat, position: [0, 0.48, CHAIR_Z], cast: true },+ { geometry: rounded(0.48, 0.5, 0.07, 0.03), material: MAT.chairSeat, position: [0, 0.78, CHAIR_Z + 0.24], cast: true },+];++const SCREEN_GEOMETRY = new PlaneGeometry(0.66, 0.38);+const SCREEN_LOCAL: [number, number, number] = [0, 1.18, -0.212];+const FACES: ScreenFace[] = ["working", "idle", "waiting", "paused", "empty"];++function deskMatrix(desk: DeskSlot, local: [number, number, number], scale: [number, number, number] = [1, 1, 1]): Matrix4 {+ const turn = desk.facing === "north" ? 0 : Math.PI;+ const world = new Matrix4().compose(new Vector3(desk.x, 0, desk.z), new Quaternion().setFromEuler(new Euler(0, turn, 0)), new Vector3(1, 1, 1));+ const part = new Matrix4().compose(new Vector3(...local), new Quaternion(), new Vector3(...scale));+ return world.multiply(part);+}++function PartInstances({ part, desks }: { part: Part; desks: DeskSlot[] }) {+ const ref = useRef<InstancedMesh>(null);+ useLayoutEffect(() => {+ const mesh = ref.current;+ if (!mesh) return;+ desks.forEach((desk, i) => mesh.setMatrixAt(i, deskMatrix(desk, part.position, part.scale)));+ mesh.count = desks.length;+ mesh.instanceMatrix.needsUpdate = true;+ mesh.computeBoundingSphere();+ }, [desks, part]);+ return <instancedMesh ref={ref} args={[part.geometry, part.material, Math.max(1, desks.length)]} castShadow={part.cast} receiveShadow frustumCulled={false} />;+}++function ScreenInstances({ face, desks }: { face: ScreenFace; desks: DeskSlot[] }) {+ const ref = useRef<InstancedMesh>(null);+ useLayoutEffect(() => {+ const mesh = ref.current;+ if (!mesh) return;+ desks.forEach((desk, i) => mesh.setMatrixAt(i, deskMatrix(desk, SCREEN_LOCAL)));+ mesh.count = desks.length;+ mesh.instanceMatrix.needsUpdate = true;+ }, [desks]);+ // Remount when the capacity must grow; InstancedMesh cannot resize in place.+ return <instancedMesh key={Math.max(1, desks.length)} ref={ref} args={[SCREEN_GEOMETRY, screenMaterial(face), Math.max(1, desks.length)]} frustumCulled={false} />;+}++/** All desks with the monitor face each one's agent state calls for. */+export function DeskInstances({ desks, agents }: { desks: DeskSlot[]; agents: ReadonlyMap<string, SocietyAgent> }) {+ const byFace = useMemo(() => {+ const groups = new Map<ScreenFace, DeskSlot[]>(FACES.map((f) => [f, []]));+ for (const desk of desks) {+ const agent = desk.agentId ? agents.get(desk.agentId) : undefined;+ groups.get(agent ? agent.state : "empty")!.push(desk);+ }+ return groups;+ }, [desks, agents]);+ return (+ <group>+ {PARTS.map((part, i) => <PartInstances key={`${i}:${desks.length}`} part={part} desks={desks} />)}+ {FACES.map((face) => (byFace.get(face)!.length > 0 ? <ScreenInstances key={face} face={face} desks={byFace.get(face)!} /> : null))}+ </group>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsxindex a7f1bbd13c..3454f7c7b3 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsx@@ -1,20 +1,29 @@/**- * Agents at their desks: the stored character, seated, with a floating name- * pill and a floor ring in the colour of its run state. The office is a- * projection of the roster — nothing here moves an agent or starts work.+ * Agents living in the office. Working agents sit at their screens, waiting+ * agents stand and wave at their desk, idle agents wander: coffee, couch,+ * window, arcade, a chat at a busy colleague's desk. Paused agents nap.+ *+ * The office is a projection of the roster: run state comes from the backend,+ * everything else is client-side choreography that costs no tokens and never+ * starts or stops work.*/-import { useMemo, useRef } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import { Html } from "@react-three/drei";import { useFrame } from "@react-three/fiber";import { DoubleSide, Vector3, type Group, type Mesh, type MeshBasicMaterial } from "three";import { useT } from "@/i18n";import type { SocietyAgent } from "../data";-import { FigureRig, type FigureDrive } from "../figures/FigureRig";+import { FigureRig, type FigureDrive, type FigureMode } from "../figures/FigureRig";import { shufflePalette, type FigureRecipe } from "../figures/figureRecipe";import { OFFICE } from "./officePalette";-import type { DeskSlot } from "./officeLayout";+import type { DeskSlot, OfficeLayout, Point } from "./officeLayout";+import { findPath, type NavGrid } from "./officeNav";+import { stepMover, turnToward, WALK_SPEED, type Mover } from "./officeMotion";+import { createRng, planFor, type ActivityKind, type Plan, type Pose, type SpotBook } from "./officeBehavior";+import { useOfficeStore } from "./officeStore";+import { agentPositions } from "./walkerRegistry";-/** Seated figures share one toy scale, so the desks read the same everywhere. */+/** Every figure shares one toy scale, so desks and couches read the same everywhere. */export const OFFICE_FIGURE_HEIGHT_M = 1.3;/** Agents without a stored character get a stable chibi look from their id. */@@ -24,25 +33,15 @@ export function fallbackRecipe(agentId: string): FigureRecipe {return { contract: 1, archetype: "biped", base: "chibi", parts: {}, palette: shufflePalette((hash % 10_000) / 10_000) };}-const RING_COLOUR = {- working: OFFICE.ringWorking,- idle: OFFICE.ringIdle,- waiting: OFFICE.ringWaiting,- paused: OFFICE.ringPaused,-} as const;+/** Pose → animation clip. Seated work uses the seated clip; the monitor shows the typing. */+export const POSE_CLIP: Record<Pose, FigureMode> = { sit: "sit", work: "sit", stand: "idle", wave: "wave", talk: "talk", sleep: "sleep" };-function StatusRing({ state, animate }: { state: SocietyAgent["state"]; animate: boolean }) {- const ref = useRef<Mesh>(null);- useFrame(({ clock }) => {- if (!ref.current || !animate || state !== "working") return;- (ref.current.material as MeshBasicMaterial).opacity = 0.55 + Math.sin(clock.elapsedTime * 3) * 0.3;- });- return (- <mesh ref={ref} rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.015, 0]}>- <ringGeometry args={[0.46, 0.54, 40]} />- <meshBasicMaterial color={RING_COLOUR[state]} transparent opacity={0.8} side={DoubleSide} depthWrite={false} />- </mesh>- );+/** How far a seated figure is lifted onto its seat, per activity. */+function seatLift(kind: ActivityKind): number {+ if (kind === "work" || kind === "desk" || kind === "meeting") return 0.12;+ if (kind === "couch" || kind === "nap") return 0.04;+ if (kind === "beanbag") return -0.1;+ return 0;}/** Nameplate scale by camera distance: readable up close, compact in the overview, never huge. */@@ -50,11 +49,14 @@ export function plateScale(distance: number): number {return Math.min(1.05, Math.max(0.8, 24 / Math.max(1, distance)));}-function Nameplate({ agent, onSelect }: { agent: SocietyAgent; onSelect: (id: string) => void }) {+const RING_COLOUR = { working: OFFICE.ringWorking, idle: OFFICE.ringIdle, waiting: OFFICE.ringWaiting, paused: OFFICE.ringPaused } as const;++function Nameplate({ agent, activity, selected, onSelect }: {+ agent: SocietyAgent; activity: ActivityKind | null; selected: boolean; onSelect: (id: string) => void;+}) {const t = useT();- const lead = agent.tier === "lead";- const anchor = useRef<Group>(null);const plate = useRef<HTMLButtonElement>(null);+ const anchor = useRef<Group>(null);const last = useRef(0);const world = useMemo(() => new Vector3(), []);useFrame(({ camera }) => {@@ -64,62 +66,143 @@ function Nameplate({ agent, onSelect }: { agent: SocietyAgent; onSelect: (id: stlast.current = scale;plate.current.style.transform = `scale(${scale.toFixed(2)})`;});+ const detail = agent.state !== "idle" ? t(`society.office.state_${agent.state}`) : activity ? t(`society.office.activity_${activity}`) : "";return (<group ref={anchor} position={[0, OFFICE_FIGURE_HEIGHT_M + 0.35, 0]}>- <Html center zIndexRange={[20, 0]}>- <button ref={plate} type="button" data-office-ui className="office-plate" data-state={agent.state}- onClick={(event) => { event.stopPropagation(); onSelect(agent.agentId); }}- aria-label={t("society.office.open_agent").replace("{0}", agent.name)}>- <span className="office-plate-badge" style={{ background: agent.palette.primary }} aria-hidden>- {lead ? "★" : agent.name.slice(0, 1).toUpperCase()}- </span>- <span className="office-plate-name">{agent.name}</span>- <span className="office-plate-state" title={t(`society.office.state_${agent.state}`)}>- <i aria-hidden />- {agent.state === "idle" ? null : <em>{t(`society.office.state_${agent.state}`)}</em>}- </span>- </button>- </Html>+ <Html center zIndexRange={[20, 0]}>+ <button ref={plate} type="button" data-office-ui className="office-plate" data-state={agent.state} data-selected={selected || undefined}+ onClick={(event) => { event.stopPropagation(); onSelect(agent.agentId); }}+ aria-label={t("society.office.open_agent").replace("{0}", agent.name)}>+ <span className="office-plate-badge" style={{ background: agent.palette.primary }} aria-hidden>+ {agent.tier === "lead" ? "★" : agent.name.slice(0, 1).toUpperCase()}+ </span>+ <span className="office-plate-name">{agent.name}</span>+ <span className="office-plate-state" title={t(`society.office.state_${agent.state}`)}>+ <i aria-hidden />{detail ? <em>{detail}</em> : null}+ </span>+ </button>+ </Html></group>);}-function SeatedAgent({ agent, desk, awake, reduced, onSelect }: {- agent: SocietyAgent; desk: DeskSlot; awake: boolean; reduced: boolean; onSelect: (id: string) => void;+export interface WalkerContext {+ layout: OfficeLayout;+ grid: NavGrid;+ book: SpotBook;+ /** Busy colleagues someone idle may visit, refreshed with the roster. */+ colleagues: () => { agentId: string; desk: DeskSlot }[];+ spawn: Point;+}++function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected, onSelect }: {+ agent: SocietyAgent; desk: DeskSlot | null; ctx: WalkerContext; arrivesByElevator: boolean;+ awake: boolean; reduced: boolean; selected: boolean; onSelect: (id: string) => void;}) {const recipe = useMemo(() => agent.figure ?? fallbackRecipe(agent.agentId), [agent.figure, agent.agentId]);- // Seated at every state; the monitor and the ring carry the difference.- const drive = useRef<FigureDrive>({ mode: "sit", speed: 0 });+ const group = useRef<Group>(null);+ const body = useRef<Group>(null);+ const ring = useRef<Mesh>(null);+ const drive = useRef<FigureDrive>({ mode: "idle", speed: 0 });+ const rng = useMemo(() => createRng(agent.agentId), [agent.agentId]);+ const mover = useRef<Mover>({ ...(arrivesByElevator ? ctx.spawn : { x: 0, z: 0 }), heading: Math.PI, path: [] });+ const plan = useRef<Plan | null>(null);+ const phase = useRef<"travel" | "dwell">("dwell");+ const dwellUntil = useRef(0);+ const placed = useRef(arrivesByElevator);+ const planState = useRef("");+ const summonKey = useRef("");+ const [activity, setActivity] = useState<ActivityKind | null>(null);++ // Leaving the office releases the agent's spot and its registry entry.+ useEffect(() => () => { ctx.book.release(agent.agentId); agentPositions.delete(agent.agentId); }, [ctx.book, agent.agentId]);++ useFrame((_, rawDt) => {+ const dt = Math.min(rawDt, 0.1);+ const now = Date.now();+ const m = mover.current;+ const summon = useOfficeStore.getState().summons[agent.agentId];+ const calledTo = summon && summon.untilMs > now ? summon.target : null;+ const sKey = calledTo ? `${calledTo.x.toFixed(2)},${calledTo.z.toFixed(2)}` : "";+ const needsPlan = !plan.current || planState.current !== agent.state || summonKey.current !== sKey+ || (phase.current === "dwell" && now >= dwellUntil.current);+ if (needsPlan) {+ const next = planFor({+ agentId: agent.agentId, state: agent.state, desk, layout: ctx.layout, grid: ctx.grid, rng, book: ctx.book,+ previous: plan.current?.kind ?? null, workingColleagues: ctx.colleagues().filter((c) => c.agentId !== agent.agentId), calledTo,+ });+ // Reduced motion: no idle wandering — a placement holds until the state changes.+ if (reduced && !calledTo) next.dwellMs = Infinity;+ plan.current = next;+ planState.current = agent.state;+ summonKey.current = sKey;+ if (!placed.current || reduced) {+ // First sight (or reduced motion): already there, no walk across the floor.+ m.x = next.target.x; m.z = next.target.z; m.path = [];+ if (next.facing !== null) m.heading = next.facing;+ placed.current = true;+ phase.current = "dwell";+ dwellUntil.current = now + next.dwellMs;+ } else {+ m.path = findPath(ctx.grid, m, next.target) ?? [];+ if (m.path.length === 0) { m.x = next.target.x; m.z = next.target.z; }+ phase.current = m.path.length > 0 ? "travel" : "dwell";+ if (phase.current === "dwell") dwellUntil.current = now + next.dwellMs;+ }+ if (next.kind !== activity) setActivity(next.kind);+ }+ const p = plan.current!;+ let lift = 0;+ if (phase.current === "travel") {+ const { moved, arrived } = awake ? stepMover(m, WALK_SPEED, dt) : { moved: 0, arrived: false };+ drive.current.mode = "walk";+ drive.current.speed = moved / Math.max(dt, 1e-3);+ if (arrived) { phase.current = "dwell"; dwellUntil.current = now + p.dwellMs; }+ } else {+ if (p.facing !== null) m.heading = turnToward(m.heading, p.facing, 8 * dt);+ drive.current.mode = POSE_CLIP[p.pose];+ drive.current.speed = 0;+ if (p.pose === "sit" || p.pose === "work" || p.pose === "sleep") lift = seatLift(p.kind);+ }+ agentPositions.set(agent.agentId, { x: m.x, z: m.z });+ if (group.current) group.current.position.set(m.x, 0, m.z);+ if (body.current) { body.current.rotation.y = m.heading; body.current.position.y = lift; }+ if (ring.current) {+ const material = ring.current.material as MeshBasicMaterial;+ material.opacity = agent.state === "working" && awake && !reduced ? 0.55 + Math.sin(now / 330) * 0.3 : 0.8;+ ring.current.visible = phase.current === "dwell" || selected;+ }+ });+return (- <group position={[desk.x, 0, desk.z]} rotation={[0, desk.facing === "north" ? 0 : Math.PI, 0]}>- <group position={[0, 0, 0.72]}>- <StatusRing state={agent.state} animate={awake && !reduced} />- {/* Figures face +z; the agent looks at its monitor on the local -z side. */}- <group rotation={[0, Math.PI, 0]} position={[0, SEAT_LIFT_M, SEAT_BACK_M]}- onClick={(event) => { event.stopPropagation(); onSelect(agent.agentId); }}- onPointerOver={() => { document.body.style.cursor = "pointer"; }}- onPointerOut={() => { document.body.style.cursor = ""; }}>- <FigureRig recipe={recipe} drive={drive} paused={!awake || reduced} heightM={OFFICE_FIGURE_HEIGHT_M} />- </group>- <Nameplate agent={agent} onSelect={onSelect} />+ <group ref={group} userData={{ agentId: agent.agentId }}>+ <mesh ref={ring} rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.015, 0]}>+ <ringGeometry args={[selected ? 0.4 : 0.46, 0.54, 40]} />+ <meshBasicMaterial color={selected ? "#93c5fd" : RING_COLOUR[agent.state]} transparent opacity={0.8} side={DoubleSide} depthWrite={false} />+ </mesh>+ <group ref={body}+ onClick={(event) => { event.stopPropagation(); onSelect(agent.agentId); }}+ onPointerOver={() => { document.body.style.cursor = "pointer"; }}+ onPointerOut={() => { document.body.style.cursor = ""; }}>+ <FigureRig recipe={recipe} drive={drive} paused={!awake} heightM={OFFICE_FIGURE_HEIGHT_M} /></group>+ <Nameplate agent={agent} activity={activity} selected={selected} onSelect={onSelect} /></group>);}-/** Seat offsets for the shared "sit" clip, measured in the runtime against the chair. */-export const SEAT_LIFT_M = 0.12;-export const SEAT_BACK_M = 0.04;--export function OfficeAgents({ desks, agents, awake, reduced, onSelect }: {- desks: DeskSlot[]; agents: ReadonlyMap<string, SocietyAgent>; awake: boolean; reduced: boolean; onSelect: (id: string) => void;+export function OfficeAgents({ desks, agents, ctx, newcomers, awake, reduced, selectedId, onSelect }: {+ desks: DeskSlot[]; agents: ReadonlyMap<string, SocietyAgent>; ctx: WalkerContext; newcomers: ReadonlySet<string>;+ awake: boolean; reduced: boolean; selectedId: string | null; onSelect: (id: string) => void;}) {+ const deskOf = useMemo(() => new Map(desks.filter((d) => d.agentId).map((d) => [d.agentId as string, d])), [desks]);return (<group>- {desks.map((desk) => {- const agent = desk.agentId ? agents.get(desk.agentId) : undefined;- return agent ? <SeatedAgent key={agent.agentId} agent={agent} desk={desk} awake={awake} reduced={reduced} onSelect={onSelect} /> : null;- })}+ {[...agents.values()].map((agent) => (+ <Walker key={agent.agentId} agent={agent} desk={deskOf.get(agent.agentId) ?? null} ctx={ctx}+ arrivesByElevator={newcomers.has(agent.agentId)} awake={awake} reduced={reduced}+ selected={selectedId === agent.agentId} onSelect={onSelect} />+ ))}</group>);}diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeCameraRig.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeCameraRig.tsxnew file mode 100644index 0000000000..b540e8d38b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeCameraRig.tsx@@ -0,0 +1,99 @@+/**+ * One camera for walking and for the overview. OrbitControls always own+ * rotate and zoom; in follow mode the orbit target glides after the+ * character, so zooming out turns the same view into an overview without a+ * mode switch. A right-drag pan or a fly-to leaves follow mode; moving the+ * character re-enters it.+ */+import { useEffect, useRef } from "react";+import { OrbitControls } from "@react-three/drei";+import { useFrame, useThree } from "@react-three/fiber";+import { Vector3 } from "three";+import type { OrbitControls as OrbitControlsImpl } from "three-stdlib";+import { cameraHome, CAMERA_LIMITS, HOME_PITCH_RAD, HOME_YAW_RAD } from "./officeCamera";+import type { OfficeLayout } from "./officeLayout";+import { player, useOfficeStore } from "./officeStore";++/** Where the camera starts: close behind the character, south-east, looking down. */+export const FOLLOW_DISTANCE = 15;+const TARGET_HEIGHT = 0.8;++export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; overview: number }) {+ const controls = useRef<OrbitControlsImpl>(null);+ const camera = useThree((s) => s.camera);+ const size = useThree((s) => s.size);+ const gl = useThree((s) => s.gl);+ const scene = useThree((s) => s.scene);+ const lastFocus = useRef(0);+ const flight = useRef<{ from: Vector3; to: Vector3; t: number } | null>(null);+ const desired = useRef(new Vector3());+ const delta = useRef(new Vector3());++ // Start close to the character.+ useEffect(() => {+ const target = new Vector3(player.x, TARGET_HEIGHT, player.z);+ const horizontal = Math.cos(HOME_PITCH_RAD) * FOLLOW_DISTANCE;+ camera.position.set(target.x + Math.sin(HOME_YAW_RAD) * horizontal, Math.sin(HOME_PITCH_RAD) * FOLLOW_DISTANCE + TARGET_HEIGHT,+ target.z + Math.cos(HOME_YAW_RAD) * horizontal);+ controls.current?.target.copy(target);+ controls.current?.update();+ useOfficeStore.getState().setFollow(true);+ if (import.meta.env.DEV) (window as unknown as Record<string, unknown>).__office = { camera, controls: controls.current, gl, scene };+ }, [camera, gl, scene, layout.spawn]);++ // "Overview": frame the whole floor and stop following.+ useEffect(() => {+ if (overview === 0) return;+ const home = cameraHome(layout.bounds, size.width / Math.max(1, size.height));+ flight.current = null;+ useOfficeStore.getState().setFollow(false);+ camera.position.set(...home.position);+ controls.current?.target.set(...home.target);+ controls.current?.update();+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [overview]);++ // A right-drag (or Shift/Ctrl-drag) pans: the person takes the camera, so stop following.+ useEffect(() => {+ const el = gl.domElement;+ const down = (event: PointerEvent) => {+ if (event.button === 2 || event.shiftKey || event.ctrlKey || event.metaKey) useOfficeStore.getState().setFollow(false);+ };+ el.addEventListener("pointerdown", down);+ return () => el.removeEventListener("pointerdown", down);+ }, [gl]);++ useFrame((_, rawDt) => {+ const c = controls.current;+ if (!c) return;+ const dt = Math.min(rawDt, 0.1);+ const store = useOfficeStore.getState();+ if (store.focus && store.focus.seq !== lastFocus.current) {+ lastFocus.current = store.focus.seq;+ flight.current = { from: c.target.clone(), to: new Vector3(store.focus.point.x, TARGET_HEIGHT, store.focus.point.z), t: 0 };+ }+ if (flight.current) {+ const f = flight.current;+ f.t = Math.min(1, f.t + dt / 0.7);+ const ease = f.t < 0.5 ? 2 * f.t * f.t : 1 - (-2 * f.t + 2) ** 2 / 2;+ desired.current.copy(f.from).lerp(f.to, ease);+ if (f.t >= 1) flight.current = null;+ } else if (store.follow) {+ desired.current.set(player.x, TARGET_HEIGHT, player.z);+ desired.current.lerp(c.target, Math.exp(-8 * dt));+ } else {+ return;+ }+ // Move camera and target together: rotation and zoom stay what the person chose.+ delta.current.copy(desired.current).sub(c.target);+ c.target.add(delta.current);+ camera.position.add(delta.current);+ c.update();+ });++ return (+ <OrbitControls ref={controls} makeDefault enableDamping dampingFactor={0.12} screenSpacePanning={false}+ minPolarAngle={CAMERA_LIMITS.minPolar} maxPolarAngle={CAMERA_LIMITS.maxPolar}+ minDistance={CAMERA_LIMITS.minDistance} maxDistance={CAMERA_LIMITS.maxDistance} />+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeFurniture.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeFurniture.tsxindex 88f125b06e..18b3c54c6a 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeFurniture.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeFurniture.tsx@@ -12,7 +12,7 @@ import { RoundedBoxGeometry } from "three-stdlib";import { OFFICE } from "./officePalette";import { screenTexture, type ScreenFace } from "./screenTextures";-const matte = (color: string, extra: Partial<ConstructorParameters<typeof MeshStandardMaterial>[0]> = {}) =>+export const matte = (color: string, extra: Partial<ConstructorParameters<typeof MeshStandardMaterial>[0]> = {}) =>new MeshStandardMaterial({ color, roughness: 0.85, metalness: 0, ...extra });export const MAT = {@@ -39,14 +39,14 @@ export const MAT = {books: OFFICE.book.map((c) => matte(c)),};-const GEO = {+export const GEO = {box: new BoxGeometry(1, 1, 1),cyl: new CylinderGeometry(1, 1, 1, 16),potCyl: new CylinderGeometry(1, 0.8, 1, 16),blob: new IcosahedronGeometry(1, 0),};-function Box({ size, position, material, cast = true }: {+export function Box({ size, position, material, cast = true }: {size: [number, number, number]; position: [number, number, number]; material: MeshStandardMaterial; cast?: boolean;}) {return <mesh geometry={GEO.box} material={material} position={position} scale={size} castShadow={cast} receiveShadow />;@@ -54,7 +54,7 @@ function Box({ size, position, material, cast = true }: {/** Rounded boxes are cached by size: every desk shares the same few geometries. */const roundedCache = new Map<string, RoundedBoxGeometry>();-function Rounded({ size, radius, position, material, cast = true }: {+export function Rounded({ size, radius, position, material, cast = true }: {size: [number, number, number]; radius: number; position: [number, number, number]; material: MeshStandardMaterial; cast?: boolean;}) {const key = `${size.join("x")}:${radius}`;@@ -67,7 +67,7 @@ function Rounded({ size, radius, position, material, cast = true }: {}const screenMaterials = new Map<ScreenFace, MeshStandardMaterial>();-function screenMaterial(face: ScreenFace): MeshStandardMaterial {+export function screenMaterial(face: ScreenFace): MeshStandardMaterial {let material = screenMaterials.get(face);if (!material) {const map = screenTexture(face);diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficePanels.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficePanels.tsxnew file mode 100644index 0000000000..177dac762a--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficePanels.tsx@@ -0,0 +1,259 @@+/**+ * DOM panels for what the person selects in the office: an agent, or one of+ * the checkpoints (reception, agent board, team room, wardrobe, lead office,+ * break room). Every action here uses an existing app path — create dialog,+ * agent card/chat, chat groups — the office adds no new backend contract.+ */+import { useState } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { useT } from "@/i18n";+import { createSocietyChatGroup, useSocietyChatGroups } from "@/lib/societyChatGroups";+import type { SocietyAgent } from "../data";+import type { CheckpointKind, OfficeLayout, Point } from "./officeLayout";+import { player, useOfficeStore } from "./officeStore";+import { agentPositions } from "./walkerRegistry";+import { WARDROBE_BASES, withBase, withShuffledColours, type PlayerProfile } from "./playerProfile";++/** How long called or gathered agents stay before they drift back to their day. */+const CALL_MS = 25_000;++export interface OfficeActions {+ onOpenAgent: (id: string) => void;+ onOpenLedger: () => void;+ onCreateAgent?: () => void;+ onOpenGroup?: (groupId: string) => void;+}++function StateDot({ state }: { state: SocietyAgent["state"] }) {+ return <i className="office-dot" data-state={state} aria-hidden />;+}++function PanelShell({ title, subtitle, onClose, children }: { title: string; subtitle?: string; onClose: () => void; children: React.ReactNode }) {+ const t = useT();+ return (+ <aside className="office-card office-panel" data-office-ui aria-label={title}>+ <header className="office-panel-head">+ <div>+ <strong>{title}</strong>+ {subtitle ? <span>{subtitle}</span> : null}+ </div>+ <button type="button" className="office-icon-button" onClick={onClose} aria-label={t("society.office.close")}>×</button>+ </header>+ <div className="office-panel-body">{children}</div>+ </aside>+ );+}++function spotCentre(layout: OfficeLayout, kind: "meeting" | "couch"): Point {+ const spots = layout.spots.filter((s) => s.kind === kind);+ if (spots.length === 0) return layout.spawn;+ return { x: spots.reduce((s, p) => s + p.x, 0) / spots.length, z: spots.reduce((s, p) => s + p.z, 0) / spots.length };+}++export function AgentPanel({ agent, actions, onClose }: { agent: SocietyAgent; actions: OfficeActions; onClose: () => void }) {+ const t = useT();+ const store = useOfficeStore();+ const inDraft = store.teamDraft.includes(agent.agentId);+ const where = agentPositions.get(agent.agentId);+ return (+ <PanelShell title={agent.name} subtitle={agent.title || agent.providerLabel} onClose={onClose}>+ <p className="office-panel-status"><StateDot state={agent.state} />{t(`society.office.state_${agent.state}`)}+ {agent.providerLabel ? <span> · {agent.providerLabel}</span> : null}</p>+ <div className="office-actions">+ <button type="button" className="office-action office-action-primary" onClick={() => actions.onOpenAgent(agent.agentId)}>{t("society.office.action_chat")}</button>+ <button type="button" className="office-action" disabled={!where} onClick={() => where && store.requestWalk(where)}>{t("society.office.action_walk")}</button>+ <button type="button" className="office-action" onClick={() => store.summon([agent.agentId], { x: player.x, z: player.z }, CALL_MS)}>{t("society.office.action_call")}</button>+ <button type="button" className="office-action" disabled={!where} onClick={() => where && store.focusOn(where)}>{t("society.office.action_focus")}</button>+ <button type="button" className="office-action" aria-pressed={inDraft} onClick={() => store.toggleDraft(agent.agentId)}>+ {t(inDraft ? "society.office.action_undraft" : "society.office.action_draft")}+ </button>+ </div>+ {store.teamDraft.length > 0 && (+ <button type="button" className="office-link" onClick={() => store.select({ kind: "checkpoint", id: "team" })}>+ {t("society.office.draft_count").replace("{0}", String(store.teamDraft.length))}+ </button>+ )}+ </PanelShell>+ );+}++function CreatePanel({ actions }: { actions: OfficeActions }) {+ const t = useT();+ return (+ <>+ <p>{t("society.office.create_body")}</p>+ <button type="button" className="office-action office-action-primary" disabled={!actions.onCreateAgent} onClick={() => actions.onCreateAgent?.()}>+ {t("society.office.create_action")}+ </button>+ </>+ );+}++function ManagePanel({ agents, actions }: { agents: SocietyAgent[]; actions: OfficeActions }) {+ const t = useT();+ const store = useOfficeStore();+ return (+ <>+ <ul className="office-list">+ {agents.map((agent) => (+ <li key={agent.agentId}>+ <StateDot state={agent.state} />+ <span className="office-list-name">{agent.name}</span>+ <button type="button" className="office-mini" onClick={() => {+ const p = agentPositions.get(agent.agentId);+ if (p) store.focusOn(p);+ store.select({ kind: "agent", id: agent.agentId });+ }}>{t("society.office.action_show")}</button>+ <button type="button" className="office-mini" onClick={() => actions.onOpenAgent(agent.agentId)}>{t("society.office.action_open")}</button>+ </li>+ ))}+ </ul>+ <button type="button" className="office-action office-action-primary" onClick={actions.onOpenLedger}>{t("society.office.manage_action")}</button>+ </>+ );+}++function TeamPanel({ agents, layout, sample, actions }: { agents: SocietyAgent[]; layout: OfficeLayout; sample: boolean; actions: OfficeActions }) {+ const t = useT();+ const store = useOfficeStore();+ const client = useQueryClient();+ const groups = useSocietyChatGroups(!sample);+ const [name, setName] = useState("");+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState("");+ const [created, setCreated] = useState<{ id: string; name: string } | null>(null);+ const table = spotCentre(layout, "meeting");+ const members = store.teamDraft.filter((id) => agents.some((a) => a.agentId === id));+ const canCreate = !sample && !busy && members.length >= 2;+ const create = async () => {+ setBusy(true); setError("");+ try {+ const names = members.map((id) => agents.find((a) => a.agentId === id)?.name ?? id);+ const group = await createSocietyChatGroup(name.trim() || names.join(" + "), members);+ await client.invalidateQueries({ queryKey: ["society", "chat-groups"] });+ store.summon(members, table, CALL_MS);+ store.clearDraft();+ setName("");+ setCreated({ id: group.group_id, name: group.name });+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setBusy(false);+ }+ };+ return (+ <>+ <p>{t("society.office.team_body")}</p>+ {sample && <p className="office-note-inline">{t("society.office.sample")}</p>}+ <label className="office-field">+ <span>{t("society.office.team_name")}</span>+ <input value={name} maxLength={60} onChange={(e) => setName(e.target.value)} placeholder={t("society.office.team_name_placeholder")} />+ </label>+ <ul className="office-list office-list-check">+ {agents.map((agent) => (+ <li key={agent.agentId}>+ <label>+ <input type="checkbox" checked={store.teamDraft.includes(agent.agentId)} onChange={() => store.toggleDraft(agent.agentId)} />+ <StateDot state={agent.state} /><span className="office-list-name">{agent.name}</span>+ </label>+ </li>+ ))}+ </ul>+ <button type="button" className="office-action office-action-primary" disabled={!canCreate} onClick={() => void create()}>+ {t("society.office.team_create").replace("{0}", String(members.length))}+ </button>+ {error && <p role="alert" className="office-error">{error}</p>}+ {created && (+ <p className="office-success" role="status">+ {t("society.office.team_created").replace("{0}", created.name)}+ {actions.onOpenGroup && <button type="button" className="office-link" onClick={() => actions.onOpenGroup?.(created.id)}>{t("society.office.team_open")}</button>}+ </p>+ )}+ {(groups.data?.length ?? 0) > 0 && (+ <>+ <h4 className="office-subhead">{t("society.office.team_existing")}</h4>+ <ul className="office-list">+ {groups.data!.map((group) => (+ <li key={group.group_id}>+ <span className="office-list-name">{group.name}</span>+ <button type="button" className="office-mini" onClick={() => store.summon(group.members, table, CALL_MS)}>{t("society.office.team_gather")}</button>+ {actions.onOpenGroup && <button type="button" className="office-mini" onClick={() => actions.onOpenGroup?.(group.group_id)}>{t("society.office.action_open")}</button>}+ </li>+ ))}+ </ul>+ </>+ )}+ </>+ );+}++function WardrobePanel({ profile, onProfile }: { profile: PlayerProfile; onProfile: (next: PlayerProfile) => void }) {+ const t = useT();+ return (+ <>+ <label className="office-field">+ <span>{t("society.office.wardrobe_name")}</span>+ <input value={profile.name} maxLength={40} placeholder={t("society.office.you")} onChange={(e) => onProfile({ ...profile, name: e.target.value })} />+ </label>+ <p className="office-subhead">{t("society.office.wardrobe_body")}</p>+ <div className="office-chips">+ {WARDROBE_BASES.map((base) => (+ <button key={base} type="button" className="office-chip" aria-pressed={profile.recipe.base === base} onClick={() => onProfile(withBase(profile, base))}>+ {base.charAt(0).toUpperCase() + base.slice(1)}+ </button>+ ))}+ </div>+ <button type="button" className="office-action" onClick={() => onProfile(withShuffledColours(profile))}>{t("society.office.wardrobe_shuffle")}</button>+ </>+ );+}++function LeadPanel({ agents, actions }: { agents: SocietyAgent[]; actions: OfficeActions }) {+ const t = useT();+ const store = useOfficeStore();+ const lead = agents.find((a) => a.tier === "lead");+ if (!lead) return <p>{t("society.office.lead_empty")}</p>;+ return (+ <>+ <p className="office-panel-status"><StateDot state={lead.state} />{lead.name} · {t(`society.office.state_${lead.state}`)}</p>+ <p>{t("society.office.lead_body")}</p>+ <div className="office-actions">+ <button type="button" className="office-action office-action-primary" onClick={() => actions.onOpenAgent(lead.agentId)}>{t("society.office.action_chat")}</button>+ <button type="button" className="office-action" onClick={() => store.summon([lead.agentId], { x: player.x, z: player.z }, CALL_MS)}>{t("society.office.action_call")}</button>+ </div>+ </>+ );+}++function BreakPanel({ agents, layout }: { agents: SocietyAgent[]; layout: OfficeLayout }) {+ const t = useT();+ const store = useOfficeStore();+ const idle = agents.filter((a) => a.state === "idle");+ return (+ <>+ <p>{t("society.office.break_body").replace("{0}", String(idle.length))}</p>+ <div className="office-actions">+ <button type="button" className="office-action office-action-primary" disabled={idle.length === 0}+ onClick={() => store.summon(idle.map((a) => a.agentId), spotCentre(layout, "couch"), CALL_MS)}>{t("society.office.break_call")}</button>+ <button type="button" className="office-action" onClick={store.clearSummons}>{t("society.office.break_release")}</button>+ </div>+ </>+ );+}++export function CheckpointPanel({ id, agents, layout, sample, profile, onProfile, actions, onClose }: {+ id: CheckpointKind; agents: SocietyAgent[]; layout: OfficeLayout; sample: boolean;+ profile: PlayerProfile; onProfile: (next: PlayerProfile) => void; actions: OfficeActions; onClose: () => void;+}) {+ const t = useT();+ return (+ <PanelShell title={t(`society.office.cp_${id}`)} subtitle={t(`society.office.cp_${id}_hint`)} onClose={onClose}>+ {id === "create" && <CreatePanel actions={actions} />}+ {id === "manage" && <ManagePanel agents={agents} actions={actions} />}+ {id === "team" && <TeamPanel agents={agents} layout={layout} sample={sample} actions={actions} />}+ {id === "wardrobe" && <WardrobePanel profile={profile} onProfile={onProfile} />}+ {id === "lead" && <LeadPanel agents={agents} actions={actions} />}+ {id === "break" && <BreakPanel agents={agents} layout={layout} />}+ </PanelShell>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsxnew file mode 100644index 0000000000..cfadd423ec--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx@@ -0,0 +1,166 @@+/**+ * The person's own character: walks with WASD/arrows (camera-relative, Shift+ * runs) or by clicking the floor, and interacts with whatever is nearby (E).+ * Zooming out never requires walking — everything stays clickable from afar.+ */+import { useEffect, useMemo, useRef } from "react";+import { Html } from "@react-three/drei";+import { useFrame, useThree } from "@react-three/fiber";+import { DoubleSide, Vector3, type Group, type Mesh, type MeshBasicMaterial } from "three";+import { FigureRig, type FigureDrive } from "../figures/FigureRig";+import type { FigureRecipe } from "../figures/figureRecipe";+import { findPath, isWalkable, nearestWalkable, type NavGrid } from "./officeNav";+import { RUN_SPEED, stepMover, turnToward, WALK_SPEED } from "./officeMotion";+import { player, sameSelection, useOfficeStore, type Selection } from "./officeStore";+import { agentPositions } from "./walkerRegistry";+import { OFFICE_FIGURE_HEIGHT_M } from "./OfficeAgents";+import type { OfficeLayout } from "./officeLayout";++/** Talk range to an agent, in metres. */+export const AGENT_TALK_RANGE = 1.8;++const MOVE_KEYS: Record<string, [number, number]> = {+ KeyW: [0, 1], ArrowUp: [0, 1], KeyS: [0, -1], ArrowDown: [0, -1],+ KeyA: [-1, 0], ArrowLeft: [-1, 0], KeyD: [1, 0], ArrowRight: [1, 0],+};++/** Keys typed into a field, a dialog or any other DOM control never walk the character. */+export function ownsKeyboard(target: EventTarget | null): boolean {+ if (!(target instanceof HTMLElement)) return false;+ if (target.isContentEditable) return true;+ const tag = target.tagName;+ return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || !!target.closest("[role='dialog']");+}++/** Pressed movement keys, tracked on the window while the office is awake. */+function useMoveKeys(enabled: boolean, onInteract: () => void) {+ const pressed = useRef(new Set<string>());+ const run = useRef(false);+ useEffect(() => {+ if (!enabled) { pressed.current.clear(); return; }+ const down = (event: KeyboardEvent) => {+ if (ownsKeyboard(event.target) || event.ctrlKey || event.metaKey || event.altKey) return;+ run.current = event.shiftKey;+ if (event.code in MOVE_KEYS) { pressed.current.add(event.code); event.preventDefault(); }+ else if (event.code === "KeyE" && !event.repeat) { onInteract(); event.preventDefault(); }+ };+ const up = (event: KeyboardEvent) => { pressed.current.delete(event.code); run.current = event.shiftKey; };+ // A key held while the window loses focus or gets hidden never sees its+ // keyup; forget everything then, or the character walks on by itself.+ const release = () => pressed.current.clear();+ window.addEventListener("keydown", down);+ window.addEventListener("keyup", up);+ window.addEventListener("blur", release);+ document.addEventListener("visibilitychange", release);+ return () => {+ release();+ window.removeEventListener("keydown", down);+ window.removeEventListener("keyup", up);+ window.removeEventListener("blur", release);+ document.removeEventListener("visibilitychange", release);+ };+ }, [enabled, onInteract]);+ return { pressed, run };+}++function nearestInteractable(layout: OfficeLayout): Selection | null {+ let best: Selection | null = null;+ let bestDistance = Infinity;+ for (const cp of layout.checkpoints) {+ const d = Math.hypot(cp.x - player.x, cp.z - player.z);+ if (d <= cp.radius && d < bestDistance) { best = { kind: "checkpoint", id: cp.id }; bestDistance = d; }+ }+ for (const [id, p] of agentPositions) {+ const d = Math.hypot(p.x - player.x, p.z - player.z);+ if (d <= AGENT_TALK_RANGE && d < bestDistance) { best = { kind: "agent", id }; bestDistance = d; }+ }+ return best;+}++export function OfficePlayer({ layout, grid, recipe, name, awake, reduced }: {+ layout: OfficeLayout; grid: NavGrid; recipe: FigureRecipe; name: string; awake: boolean; reduced: boolean;+}) {+ const group = useRef<Group>(null);+ const ring = useRef<Mesh>(null);+ const drive = useRef<FigureDrive>({ mode: "idle", speed: 0 });+ const camera = useThree((s) => s.camera);+ const forward = useMemo(() => new Vector3(), []);+ const lastWalk = useRef(0);+ const nearbyRef = useRef<Selection | null>(null);+ const interact = useMemo(() => () => {+ const nearby = nearbyRef.current;+ if (nearby) useOfficeStore.getState().select(nearby);+ }, []);+ const { pressed, run } = useMoveKeys(awake, interact);++ // Place the character at the elevator once per floor plan.+ useEffect(() => {+ const start = nearestWalkable(grid, layout.spawn) ?? layout.spawn;+ player.x = start.x; player.z = start.z; player.heading = Math.PI; player.path = []; player.moving = false;+ }, [grid, layout.spawn]);++ useFrame((_, rawDt) => {+ const dt = Math.min(rawDt, 0.1);+ const store = useOfficeStore.getState();+ // Click-to-move / "walk there" requests.+ if (store.walkTo && store.walkTo.seq !== lastWalk.current) {+ lastWalk.current = store.walkTo.seq;+ player.path = findPath(grid, player, store.walkTo.point) ?? [];+ }+ // Keyboard movement, relative to where the camera looks.+ let ix = 0, iz = 0;+ for (const code of pressed.current) { ix += MOVE_KEYS[code][0]; iz += MOVE_KEYS[code][1]; }+ const speed = run.current ? RUN_SPEED : WALK_SPEED;+ let moved = 0;+ if (ix !== 0 || iz !== 0) {+ player.path = [];+ camera.getWorldDirection(forward);+ forward.y = 0;+ if (forward.lengthSq() < 1e-6) forward.set(0, 0, -1);+ forward.normalize();+ // Right = forward × up.+ const rx = -forward.z, rz = forward.x;+ let dx = forward.x * iz + rx * ix, dz = forward.z * iz + rz * ix;+ const len = Math.hypot(dx, dz);+ dx /= len; dz /= len;+ const step = speed * dt;+ const nx = player.x + dx * step, nz = player.z + dz * step;+ // Slide along walls: full move, else each axis alone.+ if (isWalkable(grid, { x: nx, z: nz })) { player.x = nx; player.z = nz; moved = step; }+ else if (isWalkable(grid, { x: nx, z: player.z })) { player.x = nx; moved = Math.abs(dx * step); }+ else if (isWalkable(grid, { x: player.x, z: nz })) { player.z = nz; moved = Math.abs(dz * step); }+ player.heading = turnToward(player.heading, Math.atan2(dx, dz), 12 * dt);+ if (!store.follow) store.setFollow(true);+ } else if (player.path.length > 0) {+ const result = stepMover(player, speed, dt);+ moved = result.moved;+ }+ player.moving = moved > 0;+ drive.current.mode = moved > 0 ? "walk" : "idle";+ drive.current.speed = moved / Math.max(dt, 1e-3);+ if (group.current) {+ group.current.position.set(player.x, 0, player.z);+ group.current.rotation.y = player.heading;+ }+ if (ring.current) (ring.current.material as MeshBasicMaterial).opacity = reduced ? 0.8 : 0.6 + Math.sin(performance.now() / 400) * 0.2;+ // What can the character reach right now?+ const nearby = nearestInteractable(layout);+ if (!sameSelection(nearby, nearbyRef.current)) { nearbyRef.current = nearby; store.setNearby(nearby); }+ });++ return (+ <group ref={group}>+ <mesh ref={ring} rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.02, 0]}>+ <ringGeometry args={[0.42, 0.52, 40]} />+ <meshBasicMaterial color="#f5b83d" transparent opacity={0.8} side={DoubleSide} depthWrite={false} />+ </mesh>+ <FigureRig recipe={recipe} drive={drive} paused={!awake} heightM={OFFICE_FIGURE_HEIGHT_M} />+ <Html center position={[0, OFFICE_FIGURE_HEIGHT_M + 0.35, 0]} zIndexRange={[25, 0]}>+ <span className="office-plate office-plate-player" data-office-ui>+ <span className="office-plate-badge" style={{ background: "#f5b83d" }} aria-hidden>★</span>+ <span className="office-plate-name">{name}</span>+ </span>+ </Html>+ </group>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeProps.test.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeProps.test.tsxnew file mode 100644index 0000000000..b7da2aeb59--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeProps.test.tsx@@ -0,0 +1,81 @@+import { afterEach, describe, expect, it } from "vitest";+import { act, createRoot, extend, type ReconcilerRoot } from "@react-three/fiber";+import * as THREE from "three";+import { Box3, type Object3D } from "three";+import { FURNITURE_SIZE, type Furniture, type FurnitureKind } from "./officeLayout";+import { FurniturePiece, MeetingChairs, PROP_RENDERERS } from "./OfficeProps";++/** Just enough of a WebGLRenderer for R3F to mount a scene graph without a GPU. */+function fakeRenderer(canvas: HTMLCanvasElement) {+ const noop = () => undefined;+ return {+ domElement: canvas,+ render: noop, setSize: noop, setPixelRatio: noop, setAnimationLoop: noop, dispose: noop,+ getPixelRatio: () => 1,+ shadowMap: { enabled: false, type: 0, needsUpdate: false },+ xr: { enabled: false, isPresenting: false, addEventListener: noop, removeEventListener: noop, setAnimationLoop: noop },+ outputColorSpace: "srgb", toneMapping: 0, toneMappingExposure: 1,+ info: { render: {}, memory: {} },+ };+}++// <Canvas> registers the three namespace; a bare root must do it itself.+extend(THREE);++let root: ReconcilerRoot<HTMLCanvasElement> | null = null;++async function mount(element: JSX.Element): Promise<Object3D> {+ const canvas = document.createElement("canvas");+ const current = createRoot(canvas);+ root = current;+ current.configure({+ // Test double: R3F only needs the renderer's shape here, nothing is drawn.+ gl: fakeRenderer(canvas) as unknown as NonNullable<Parameters<typeof current.configure>[0]>["gl"],+ frameloop: "never",+ size: { width: 100, height: 100, top: 0, left: 0 },+ });+ let captured: Object3D | null = null;+ await act(async () => {+ current.render(<group ref={(g) => { captured = g; }}>{element}</group>);+ });+ if (!captured) throw new Error("the element did not mount");+ return captured;+}++afterEach(() => {+ root?.unmount();+ root = null;+});++const KINDS = Object.keys(FURNITURE_SIZE) as FurnitureKind[];++describe("office props", () => {+ it("has a renderer for every furniture kind", () => {+ expect(Object.keys(PROP_RENDERERS).sort()).toEqual([...KINDS].sort());+ });++ it.each(KINDS)("%s stays inside its footprint", async (kind) => {+ const size = kind === "rug" ? { w: 3, d: 2 } : undefined;+ const item: Furniture = { id: `test-${kind}`, kind, x: 0, z: 0, rotationY: 0, room: "floor", size };+ const group = await mount(<FurniturePiece item={item} />);+ group.updateMatrixWorld(true);+ const box = new Box3().setFromObject(group);+ const { w, d, h } = { ...FURNITURE_SIZE[kind], ...(size ?? {}) };+ const eps = 0.02;+ expect(box.min.x).toBeGreaterThanOrEqual(-w / 2 - eps);+ expect(box.max.x).toBeLessThanOrEqual(w / 2 + eps);+ expect(box.min.z).toBeGreaterThanOrEqual(-d / 2 - eps);+ expect(box.max.z).toBeLessThanOrEqual(d / 2 + eps);+ expect(box.min.y).toBeGreaterThanOrEqual(-eps);+ expect(box.max.y).toBeLessThanOrEqual(Math.max(h, 0.03) + 0.05);+ });++ it("puts the meeting chairs on both long sides, outside the table", async () => {+ const table: Furniture = { id: "t", kind: "meetingTable", x: 0, z: 0, rotationY: 0, room: "team" };+ const group = await mount(<MeetingChairs table={table} />);+ group.updateMatrixWorld(true);+ const box = new Box3().setFromObject(group);+ expect(box.min.z).toBeLessThan(-FURNITURE_SIZE.meetingTable.d / 2);+ expect(box.max.z).toBeGreaterThan(FURNITURE_SIZE.meetingTable.d / 2);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeProps.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeProps.tsxnew file mode 100644index 0000000000..48685be843--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeProps.tsx@@ -0,0 +1,647 @@+/**+ * Room props for the walkable office: every `FurnitureKind` in the toy-office+ * style (docs/agent-society/office-map.md §2) — rounded primitives, matte+ * colours, and a few simple canvas-drawn faces (screens, board, mirror).+ *+ * Every piece is built in local space centred on the origin, front facing +z,+ * and stays inside its `FURNITURE_SIZE` box (w along x, d along z, height h):+ * navigation walks around exactly that footprint. Geometries, materials and+ * canvas textures are module-level singletons shared by every copy.+ */+import { memo } from "react";+import {+ CanvasTexture, CylinderGeometry, MeshStandardMaterial, SphereGeometry, SRGBColorSpace, type Texture,+} from "three";+import { Bookshelf, Box, Couch, MAT, matte, Plant, Rounded, Rug } from "./OfficeFurniture";+import { FURNITURE_SIZE, type Furniture, type FurnitureKind } from "./officeLayout";+import { PROP_COLOURS as P } from "./officePalette";++type Vec3 = [number, number, number];++// ---------------------------------------------------------------------------+// Shared canvas textures+// ---------------------------------------------------------------------------++const textureCache = new Map<string, Texture | null>();++/**+ * A canvas-drawn texture, drawn once per key and cached. Returns null where no+ * 2D canvas exists (SSR, tests without canvas); callers fall back to a colour.+ */+export function cachedCanvasTexture(+ key: string, width: number, height: number, draw: (ctx: CanvasRenderingContext2D, w: number, h: number) => void,+): Texture | null {+ if (textureCache.has(key)) return textureCache.get(key) ?? null;+ const canvas = typeof document !== "undefined" ? document.createElement("canvas") : null;+ let ctx: CanvasRenderingContext2D | null = null;+ try {+ ctx = canvas?.getContext("2d") ?? null;+ } catch {+ // jsdom without the canvas package throws "not implemented": no texture, the colour fallback is correct.+ ctx = null;+ }+ let texture: Texture | null = null;+ if (canvas && ctx) {+ canvas.width = width;+ canvas.height = height;+ draw(ctx, width, height);+ const made = new CanvasTexture(canvas);+ made.colorSpace = SRGBColorSpace;+ made.anisotropy = 4;+ texture = made;+ }+ textureCache.set(key, texture);+ return texture;+}++const materialCache = new Map<string, MeshStandardMaterial>();++/** A material showing a cached canvas texture; `glow` > 0 makes it self-lit like a screen. */+function canvasMaterial(+ key: string, width: number, height: number, draw: (ctx: CanvasRenderingContext2D, w: number, h: number) => void,+ { glow = 0, fallback = "#ffffff", roughness = 0.6 }: { glow?: number; fallback?: string; roughness?: number } = {},+): MeshStandardMaterial {+ let material = materialCache.get(key);+ if (!material) {+ const map = cachedCanvasTexture(key, width, height, draw);+ material = new MeshStandardMaterial({+ color: map ? "#ffffff" : fallback, map, roughness,+ emissive: glow > 0 ? "#ffffff" : "#000000", emissiveMap: glow > 0 ? map : null, emissiveIntensity: glow,+ });+ materialCache.set(key, material);+ }+ return material;+}++function roundRect(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number): void {+ ctx.beginPath();+ ctx.moveTo(x + r, y);+ ctx.arcTo(x + w, y, x + w, y + h, r);+ ctx.arcTo(x + w, y + h, x, y + h, r);+ ctx.arcTo(x, y + h, x, y, r);+ ctx.arcTo(x, y, x + w, y, r);+ ctx.closePath();+}++/** Team board: an org chart on the left, sticky notes on the right. */+function drawTeamBoard(ctx: CanvasRenderingContext2D, w: number, h: number): void {+ ctx.fillStyle = P.boardWhite;+ ctx.fillRect(0, 0, w, h);+ // Org chart: one box on top, three below, joined by marker lines.+ const node = (x: number, y: number, colour: string) => {+ ctx.fillStyle = colour;+ roundRect(ctx, x - 62, y - 26, 124, 52, 10);+ ctx.fill();+ ctx.fillStyle = "rgba(255,255,255,0.85)";+ ctx.fillRect(x - 40, y - 5, 80, 10);+ };+ ctx.strokeStyle = "#3b4250";+ ctx.lineWidth = 5;+ ctx.lineCap = "round";+ ctx.beginPath();+ ctx.moveTo(250, 120); ctx.lineTo(250, 200);+ ctx.moveTo(90, 200); ctx.lineTo(410, 200);+ for (const x of [90, 250, 410]) { ctx.moveTo(x, 200); ctx.lineTo(x, 262); }+ ctx.stroke();+ node(250, 100, "#4f7cac");+ node(90, 288, "#5e9c76");+ node(250, 288, "#c8553d");+ node(410, 288, "#8d6cab");+ // Marker scribbles under the chart.+ ctx.strokeStyle = "#6b7280";+ ctx.lineWidth = 4;+ for (let i = 0; i < 3; i += 1) {+ ctx.beginPath();+ ctx.moveTo(40, 380 + i * 30);+ ctx.lineTo(40 + 180 + ((i * 70) % 160), 380 + i * 30);+ ctx.stroke();+ }+ // Sticky notes, slightly askew.+ const notes = ["#fde68a", "#fbcfe8", "#bbf7d0", "#bfdbfe", "#fed7aa", "#fde68a"];+ notes.forEach((colour, i) => {+ const col = i % 3, row = Math.floor(i / 3);+ ctx.save();+ ctx.translate(620 + col * 135, 110 + row * 170);+ ctx.rotate(((i * 37) % 9 - 4) * 0.02);+ ctx.fillStyle = "rgba(0,0,0,0.12)";+ ctx.fillRect(-52, -48, 110, 110);+ ctx.fillStyle = colour;+ ctx.fillRect(-55, -55, 110, 110);+ ctx.fillStyle = "rgba(60,60,70,0.55)";+ for (let line = 0; line < 3; line += 1) ctx.fillRect(-40, -30 + line * 22, 50 + ((i + line) * 17) % 30, 6);+ ctx.restore();+ });+}++/** Kiosk screen: a list of agents with a gold header and an add button. */+function drawKioskList(ctx: CanvasRenderingContext2D, w: number, h: number): void {+ const grad = ctx.createLinearGradient(0, 0, 0, h);+ grad.addColorStop(0, "#22345a");+ grad.addColorStop(1, "#16223b");+ ctx.fillStyle = grad;+ ctx.fillRect(0, 0, w, h);+ ctx.fillStyle = "#f5b83d";+ ctx.fillRect(0, 0, w, 56);+ ctx.fillStyle = "#2a1d0a";+ ctx.fillRect(24, 22, 150, 12);+ const dots = ["#4ade80", "#fbbf24", "#e8ecf2", "#4ade80"];+ dots.forEach((colour, i) => {+ const y = 92 + i * 62;+ ctx.fillStyle = "rgba(255,255,255,0.08)";+ roundRect(ctx, 20, y - 24, w - 40, 48, 10);+ ctx.fill();+ ctx.fillStyle = colour;+ ctx.beginPath();+ ctx.arc(48, y, 10, 0, Math.PI * 2);+ ctx.fill();+ ctx.fillStyle = "rgba(255,255,255,0.85)";+ ctx.fillRect(72, y - 6, 180 + ((i * 53) % 120), 12);+ });+ ctx.fillStyle = "#f5b83d";+ ctx.beginPath();+ ctx.arc(w - 50, h - 42, 24, 0, Math.PI * 2);+ ctx.fill();+ ctx.fillStyle = "#2a1d0a";+ ctx.fillRect(w - 62, h - 45, 24, 6);+ ctx.fillRect(w - 53, h - 54, 6, 24);+}++/** A generic desktop UI for the reception monitor. */+function drawDeskScreen(ctx: CanvasRenderingContext2D, w: number, h: number): void {+ ctx.fillStyle = "#1b2a44";+ ctx.fillRect(0, 0, w, h);+ ctx.fillStyle = "#7dd3fc";+ ctx.fillRect(12, 12, w - 24, 16);+ ctx.fillStyle = "rgba(255,255,255,0.75)";+ for (let i = 0; i < 5; i += 1) ctx.fillRect(16, 44 + i * 20, 60 + ((i * 41) % 110), 8);+ ctx.fillStyle = "#a7f3d0";+ ctx.fillRect(w - 80, 44, 60, 90);+}++const INVADER = [+ "..X.....X..", "...X...X...", "..XXXXXXX..", ".XX.XXX.XX.",+ "XXXXXXXXXXX", "X.XXXXXXX.X", "X.X.....X.X", "...XX.XX...",+];++/** Arcade screen: two rows of pixel invaders, a ship and a score. */+function drawArcade(ctx: CanvasRenderingContext2D, w: number, h: number): void {+ ctx.fillStyle = "#07060f";+ ctx.fillRect(0, 0, w, h);+ const px = 4;+ for (let row = 0; row < 2; row += 1) {+ for (let col = 0; col < 4; col += 1) {+ ctx.fillStyle = row === 0 ? "#ff7ab8" : "#7cfc9a";+ const ox = 22 + col * 58, oy = 34 + row * 44;+ INVADER.forEach((line, y) => {+ for (let x = 0; x < line.length; x += 1) if (line[x] === "X") ctx.fillRect(ox + x * px, oy + y * px, px, px);+ });+ }+ }+ ctx.fillStyle = "#7dd3fc";+ ctx.fillRect(w / 2 - 18, h - 30, 36, 10);+ ctx.fillRect(w / 2 - 4, h - 40, 8, 10);+ ctx.fillStyle = "#fde68a";+ ctx.fillRect(w / 2 - 1, h - 90, 3, 14);+ ctx.fillStyle = "#ffffff";+ for (let i = 0; i < 5; i += 1) ctx.fillRect(14 + i * 12, 10, 8, 10);+}++/** Elevator floor indicator: an amber "up" arrow and a dim "down" arrow. */+function drawIndicator(ctx: CanvasRenderingContext2D, w: number, h: number): void {+ ctx.fillStyle = "#111318";+ ctx.fillRect(0, 0, w, h);+ const arrow = (cx: number, up: boolean, colour: string) => {+ ctx.fillStyle = colour;+ ctx.beginPath();+ const s = up ? -1 : 1;+ ctx.moveTo(cx, h / 2 + s * 14);+ ctx.lineTo(cx - 14, h / 2 - s * 10);+ ctx.lineTo(cx + 14, h / 2 - s * 10);+ ctx.closePath();+ ctx.fill();+ };+ arrow(w * 0.3, true, P.indicator);+ arrow(w * 0.7, false, "#4b5160");+}++/** Mirror glass: a cool gradient with two soft diagonal highlights. */+function drawMirror(ctx: CanvasRenderingContext2D, w: number, h: number): void {+ const grad = ctx.createLinearGradient(0, 0, w, h);+ grad.addColorStop(0, "#f1f9fe");+ grad.addColorStop(1, "#b9d7ea");+ ctx.fillStyle = grad;+ ctx.fillRect(0, 0, w, h);+ ctx.fillStyle = "rgba(255,255,255,0.55)";+ for (const [x, width] of [[0.15, 0.18], [0.5, 0.08]] as const) {+ ctx.beginPath();+ ctx.moveTo(w * x, h);+ ctx.lineTo(w * (x + width), h);+ ctx.lineTo(w * (x + width + 0.6), 0);+ ctx.lineTo(w * (x + 0.6), 0);+ ctx.closePath();+ ctx.fill();+ }+}++/** Coffee menu chalkboard. */+function drawMenu(ctx: CanvasRenderingContext2D, w: number, h: number): void {+ ctx.fillStyle = P.chalkboard;+ ctx.fillRect(0, 0, w, h);+ ctx.fillStyle = "#f8fafc";+ ctx.font = "700 36px system-ui, -apple-system, 'Segoe UI', sans-serif";+ ctx.textAlign = "center";+ ctx.textBaseline = "middle";+ ctx.fillText("MENU", w / 2, 34);+ for (let i = 0; i < 4; i += 1) {+ const y = 78 + i * 28;+ ctx.fillStyle = "rgba(248,250,252,0.8)";+ ctx.fillRect(24, y, 90 + ((i * 29) % 50), 7);+ ctx.fillStyle = "#fde68a";+ ctx.fillRect(w - 58, y, 34, 7);+ }+}++// ---------------------------------------------------------------------------+// Shared materials and geometries+// ---------------------------------------------------------------------------++const PM = {+ steel: matte(P.steel, { roughness: 0.35, metalness: 0.25 }),+ steelDark: matte(P.steelDark, { roughness: 0.45, metalness: 0.2 }),+ shaft: matte(P.elevatorShaft),+ lockers: P.lockers.map((c) => matte(c)),+ lockerVent: matte(P.lockerVent),+ bottle: new MeshStandardMaterial({ color: P.waterBottle, roughness: 0.2, transparent: true, opacity: 0.8 }),+ taps: P.waterTap.map((c) => matte(c)),+ mug: matte(P.mug),+ coffee: matte(P.coffee),+ espresso: matte(P.espresso, { roughness: 0.35, metalness: 0.25 }),+ arcadeBody: matte(P.arcadeBody),+ arcadeTrim: matte(P.arcadeTrim),+ marquee: matte(P.arcadeMarquee, { emissive: P.arcadeMarquee, emissiveIntensity: 0.8 }),+ joystick: matte(P.joystick, { roughness: 0.4 }),+ arcadeButtons: P.arcadeButtons.map((c) => matte(c, { emissive: c, emissiveIntensity: 0.35 })),+ beanbags: P.beanbag.map((c) => matte(c, { roughness: 0.95 })),+ bell: matte(P.bell, { roughness: 0.35, metalness: 0.3 }),+ boardFrame: matte(P.boardFrame),+ kioskBody: matte(P.kioskBody),+ kioskHead: matte(P.kioskHead, { roughness: 0.5 }),+ paper: matte(P.paper),+ rugInner: matte(P.rugInner),+ gold: matte("#f5b83d", { emissive: "#f5b83d", emissiveIntensity: 0.6 }),+ indicatorLight: matte(P.indicator, { emissive: P.indicator, emissiveIntensity: 0.9 }),+};++const lazy = {+ board: () => canvasMaterial("prop:teamBoard", 1024, 478, drawTeamBoard, { fallback: P.boardWhite, roughness: 0.7 }),+ kiosk: () => canvasMaterial("prop:kiosk", 512, 360, drawKioskList, { glow: 0.85, fallback: "#1b2a44", roughness: 0.4 }),+ deskScreen: () => canvasMaterial("prop:deskScreen", 256, 160, drawDeskScreen, { glow: 0.8, fallback: "#1b2a44", roughness: 0.4 }),+ arcade: () => canvasMaterial("prop:arcade", 256, 200, drawArcade, { glow: 1, fallback: "#07060f", roughness: 0.4 }),+ indicator: () => canvasMaterial("prop:indicator", 128, 48, drawIndicator, { glow: 0.9, fallback: "#111318", roughness: 0.4 }),+ mirror: () => canvasMaterial("prop:mirror", 128, 256, drawMirror, { glow: 0.25, fallback: P.mirror, roughness: 0.1 }),+ menu: () => canvasMaterial("prop:menu", 256, 192, drawMenu, { glow: 0.15, fallback: P.chalkboard, roughness: 0.9 }),+};++const PGEO = {+ cyl: new CylinderGeometry(1, 1, 1, 20),+ sphere: new SphereGeometry(1, 20, 14),+ dome: new SphereGeometry(1, 16, 8, 0, Math.PI * 2, 0, Math.PI / 2),+};++function Cyl({ radius, height, position, material, cast = true }: {+ radius: number; height: number; position: Vec3; material: MeshStandardMaterial; cast?: boolean;+}) {+ return <mesh geometry={PGEO.cyl} material={material} position={position} scale={[radius, height, radius]} castShadow={cast} receiveShadow />;+}++function Panel({ size, position, material, rotation }: {+ size: [number, number]; position: Vec3; material: MeshStandardMaterial; rotation?: Vec3;+}) {+ return (+ <mesh position={position} rotation={rotation} material={material}>+ <planeGeometry args={size} />+ </mesh>+ );+}++// ---------------------------------------------------------------------------+// Props (local space: centred on the origin, front faces +z)+// ---------------------------------------------------------------------------++/** Long light-wood meeting table on two white pedestals. Chairs are `MeetingChairs`. */+function MeetingTable() {+ return (+ <group>+ <Rounded size={[3.6, 0.07, 1.6]} radius={0.03} position={[0, 0.725, 0]} material={MAT.deskTop} />+ <Rounded size={[0.22, 0.69, 1.1]} radius={0.03} position={[-1.3, 0.345, 0]} material={MAT.deskBody} />+ <Rounded size={[0.22, 0.69, 1.1]} radius={0.03} position={[1.3, 0.345, 0]} material={MAT.deskBody} />+ <Box size={[2.4, 0.06, 0.08]} position={[0, 0.3, 0]} material={MAT.deskLeg} />+ <Box size={[0.3, 0.006, 0.42]} position={[-0.9, 0.763, 0.35]} material={PM.paper} cast={false} />+ <Box size={[0.3, 0.006, 0.42]} position={[0.6, 0.763, -0.35]} material={PM.paper} cast={false} />+ <Box size={[0.42, 0.02, 0.3]} position={[0.1, 0.77, 0.3]} material={MAT.monitor} />+ </group>+ );+}++/** A meeting chair centred on its seat, facing +z (backrest on the -z side). */+function MeetingChair() {+ return (+ <group>+ <Cyl radius={0.26} height={0.04} position={[0, 0.02, 0]} material={MAT.chair} />+ <Cyl radius={0.03} height={0.4} position={[0, 0.24, 0]} material={MAT.chair} cast={false} />+ <Rounded size={[0.48, 0.08, 0.46]} radius={0.03} position={[0, 0.46, 0]} material={MAT.chairSeat} />+ <Rounded size={[0.46, 0.46, 0.07]} radius={0.03} position={[0, 0.74, -0.21]} material={MAT.chairSeat} />+ </group>+ );+}++/**+ * Six chairs around a meeting table: three per long side at local x = -1.1, 0,+ * +1.1 and z = ∓1.25, each facing the table. They sit outside the table's+ * footprint and are not navigation obstacles (they match the `meeting-*` spots).+ */+export function MeetingChairs({ table }: { table: Furniture }) {+ return (+ <group position={[table.x, 0, table.z]} rotation={[0, table.rotationY, 0]}>+ {[-1.1, 0, 1.1].map((x) => (+ <group key={x}>+ <group position={[x, 0, -1.25]}><MeetingChair /></group>+ <group position={[x, 0, 1.25]} rotation={[0, Math.PI, 0]}><MeetingChair /></group>+ </group>+ ))}+ </group>+ );+}++/** Mobile whiteboard (org chart + sticky notes) on two slim legs, board face towards +z. */+function TeamBoard() {+ return (+ <group>+ {[-1.26, 1.26].map((x) => (+ <group key={x}>+ <Box size={[0.05, 1.86, 0.05]} position={[x, 0.93, -0.04]} material={MAT.railing} />+ <Box size={[0.06, 0.03, 0.2]} position={[x, 0.015, 0]} material={MAT.railing} />+ </group>+ ))}+ <Rounded size={[2.5, 1.22, 0.05]} radius={0.02} position={[0, 1.25, -0.04]} material={PM.boardFrame} />+ <Panel size={[2.4, 1.12]} position={[0, 1.25, -0.0135]} material={lazy.board()} />+ <Box size={[2.1, 0.03, 0.08]} position={[0, 0.66, 0]} material={PM.boardFrame} />+ {[PM.joystick, MAT.books[2], MAT.keyboard].map((material, i) => (+ <Box key={i} size={[0.12, 0.02, 0.02]} position={[-0.3 + i * 0.18, 0.685, 0.01]} material={material} cast={false} />+ ))}+ </group>+ );+}++/**+ * Reception counter: the visitor side (+z) is a high white counter with a+ * wood top and a service bell; the receptionist side (-z) is a lower work+ * surface whose monitor faces -z.+ */+function ReceptionDesk() {+ return (+ <group>+ <Rounded size={[2.8, 0.98, 0.4]} radius={0.15} position={[0, 0.49, 0.25]} material={MAT.deskBody} />+ <Rounded size={[2.8, 0.05, 0.46]} radius={0.02} position={[0, 1.005, 0.22]} material={MAT.wood} />+ <Box size={[2.3, 0.1, 0.02]} position={[0, 0.55, 0.44]} material={MAT.wood} cast={false} />+ <Rounded size={[2.5, 0.04, 0.44]} radius={0.015} position={[0, 0.74, -0.2]} material={MAT.deskTop} />+ <Box size={[0.36, 0.72, 0.42]} position={[-1.05, 0.36, -0.2]} material={MAT.deskBody} />+ <Box size={[0.36, 0.72, 0.42]} position={[1.05, 0.36, -0.2]} material={MAT.deskBody} />+ {/* Monitor facing the receptionist. */}+ <Box size={[0.2, 0.015, 0.14]} position={[-0.3, 0.768, -0.05]} material={MAT.monitor} />+ <Box size={[0.06, 0.12, 0.05]} position={[-0.3, 0.83, -0.05]} material={MAT.monitor} />+ <Rounded size={[0.56, 0.32, 0.035]} radius={0.012} position={[-0.3, 0.93, -0.08]} material={MAT.monitor} />+ <Panel size={[0.52, 0.28]} position={[-0.3, 0.93, -0.0985]} rotation={[0, Math.PI, 0]} material={lazy.deskScreen()} />+ <Box size={[0.4, 0.02, 0.13]} position={[-0.3, 0.77, -0.3]} material={MAT.keyboard} />+ {/* Service bell on the visitor counter. */}+ <Cyl radius={0.07} height={0.012} position={[0.9, 1.036, 0.26]} material={MAT.monitor} />+ <mesh geometry={PGEO.dome} material={PM.bell} position={[0.9, 1.042, 0.26]} scale={0.055} castShadow />+ <mesh geometry={PGEO.sphere} material={PM.bell} position={[0.9, 1.1, 0.26]} scale={0.012} />+ </group>+ );+}++/** Standing touch terminal; the screen (a list of agents) faces +z, tilted slightly up. */+function Kiosk() {+ return (+ <group>+ <Rounded size={[0.6, 0.05, 0.42]} radius={0.02} position={[0, 0.025, 0]} material={PM.kioskBody} />+ <Rounded size={[0.24, 1.1, 0.18]} radius={0.05} position={[0, 0.6, -0.04]} material={PM.kioskBody} />+ <group position={[0, 1.43, 0]} rotation={[-0.12, 0, 0]}>+ <Rounded size={[0.9, 0.66, 0.1]} radius={0.04} position={[0, 0, 0]} material={PM.kioskHead} />+ <Panel size={[0.8, 0.56]} position={[0, 0, 0.051]} material={lazy.kiosk()} />+ <Box size={[0.5, 0.03, 0.04]} position={[0, 0.345, 0]} material={PM.gold} cast={false} />+ </group>+ </group>+ );+}++/** A row of four coloured lockers, doors facing +z. */+function Lockers() {+ return (+ <group>+ <Box size={[2.4, 0.05, 0.46]} position={[0, 0.025, 0]} material={MAT.deskLeg} />+ {PM.lockers.map((material, i) => {+ const x = -0.9 + i * 0.6;+ return (+ <group key={i}>+ <Rounded size={[0.57, 1.8, 0.46]} radius={0.03} position={[x, 0.95, 0]} material={material} />+ {[1.6, 1.66, 1.72].map((y) => <Box key={y} size={[0.3, 0.025, 0.01]} position={[x, y, 0.232]} material={PM.lockerVent} cast={false} />)}+ <Box size={[0.03, 0.14, 0.03]} position={[x + 0.2, 1.0, 0.235]} material={PM.steelDark} cast={false} />+ </group>+ );+ })}+ <Box size={[2.4, 0.04, 0.48]} position={[0, 1.87, 0]} material={MAT.deskBody} />+ </group>+ );+}++/** Tall standing mirror in a wood frame; the glass faces +z. */+function Mirror() {+ return (+ <group>+ <Box size={[0.14, 0.05, 0.12]} position={[-0.33, 0.025, 0]} material={MAT.woodDark} />+ <Box size={[0.14, 0.05, 0.12]} position={[0.33, 0.025, 0]} material={MAT.woodDark} />+ <Rounded size={[0.9, 1.84, 0.07]} radius={0.03} position={[0, 0.97, -0.02]} material={MAT.wood} />+ <Panel size={[0.74, 1.66]} position={[0, 0.97, 0.0155]} material={lazy.mirror()} />+ </group>+ );+}++/** Coffee counter with an espresso machine, cups and a small menu board; service side faces +z. */+function CoffeeBar() {+ return (+ <group>+ <Rounded size={[2.4, 0.68, 0.62]} radius={0.04} position={[0, 0.34, 0.03]} material={MAT.deskBody} />+ {[-0.78, 0, 0.78].map((x) => <Box key={x} size={[0.7, 0.5, 0.012]} position={[x, 0.33, 0.342]} material={MAT.wood} cast={false} />)}+ <Rounded size={[2.4, 0.04, 0.68]} radius={0.015} position={[0, 0.7, 0.01]} material={MAT.woodDark} />+ {/* Espresso machine. */}+ <Rounded size={[0.5, 0.3, 0.34]} radius={0.04} position={[-0.65, 0.87, -0.1]} material={PM.espresso} />+ <Box size={[0.4, 0.08, 0.01]} position={[-0.65, 0.95, 0.072]} material={MAT.monitor} cast={false} />+ <Box size={[0.08, 0.05, 0.08]} position={[-0.72, 0.82, 0.1]} material={PM.steelDark} />+ <Box size={[0.08, 0.05, 0.08]} position={[-0.58, 0.82, 0.1]} material={PM.steelDark} />+ <Box size={[0.32, 0.015, 0.12]} position={[-0.65, 0.728, 0.12]} material={PM.steelDark} cast={false} />+ <Cyl radius={0.035} height={0.06} position={[-0.72, 0.765, 0.12]} material={PM.mug} />+ {/* Cups. */}+ {[0.05, 0.17, 0.29, 0.41].map((x, i) => (+ <group key={x}>+ <Cyl radius={0.04} height={0.08} position={[x, 0.76, 0.14]} material={PM.mug} />+ {i === 1 && <Cyl radius={0.034} height={0.004} position={[x, 0.8, 0.14]} material={PM.coffee} cast={false} />}+ </group>+ ))}+ {/* Menu board leaning back on the counter. */}+ <group position={[0.92, 0.72, -0.18]} rotation={[-0.18, 0, 0]}>+ <Box size={[0.44, 0.33, 0.02]} position={[0, 0.165, -0.005]} material={MAT.wood} />+ <Panel size={[0.38, 0.28]} position={[0, 0.165, 0.0055]} material={lazy.menu()} />+ </group>+ </group>+ );+}++/** Water cooler: white stand, taps on the +z side, a blue bottle on top. */+function WaterCooler() {+ return (+ <group>+ <Rounded size={[0.36, 0.9, 0.36]} radius={0.04} position={[0, 0.45, 0]} material={MAT.deskBody} />+ <Box size={[0.26, 0.2, 0.01]} position={[0, 0.72, 0.181]} material={PM.steelDark} cast={false} />+ <Box size={[0.04, 0.05, 0.04]} position={[-0.06, 0.74, 0.2]} material={PM.taps[0]} />+ <Box size={[0.04, 0.05, 0.04]} position={[0.06, 0.74, 0.2]} material={PM.taps[1]} />+ <Box size={[0.22, 0.02, 0.06]} position={[0, 0.6, 0.2]} material={PM.steelDark} />+ <Cyl radius={0.12} height={0.04} position={[0, 0.92, 0]} material={MAT.deskBody} />+ <Cyl radius={0.16} height={0.3} position={[0, 1.09, 0]} material={PM.bottle} />+ <Cyl radius={0.15} height={0.03} position={[0, 1.255, 0]} material={PM.bottle} />+ </group>+ );+}++/** Round low wood table with a mug and a magazine. */+function CoffeeTable() {+ return (+ <group>+ <Cyl radius={0.28} height={0.03} position={[0, 0.015, 0]} material={MAT.woodDark} />+ <Cyl radius={0.06} height={0.24} position={[0, 0.135, 0]} material={MAT.woodDark} />+ <Cyl radius={0.55} height={0.05} position={[0, 0.275, 0]} material={MAT.wood} />+ <Box size={[0.22, 0.01, 0.3]} position={[-0.15, 0.305, -0.05]} material={MAT.books[2]} cast={false} />+ <Cyl radius={0.045} height={0.085} position={[0.18, 0.3425, 0.1]} material={PM.mug} />+ <Cyl radius={0.038} height={0.004} position={[0.18, 0.386, 0.1]} material={PM.coffee} cast={false} />+ <Box size={[0.015, 0.045, 0.012]} position={[0.232, 0.345, 0.1]} material={PM.mug} cast={false} />+ </group>+ );+}++/** Retro arcade cabinet; screen, controls and marquee face +z. */+function Arcade() {+ return (+ <group>+ <Rounded size={[0.7, 0.95, 0.62]} radius={0.03} position={[0, 0.475, -0.04]} material={PM.arcadeBody} />+ <Box size={[0.6, 0.12, 0.01]} position={[0, 0.12, 0.272]} material={PM.arcadeTrim} cast={false} />+ <Box size={[0.2, 0.22, 0.01]} position={[0, 0.6, 0.272]} material={PM.arcadeTrim} cast={false} />+ <group position={[0, 1.0, 0.2]} rotation={[0.25, 0, 0]}>+ <Rounded size={[0.7, 0.08, 0.3]} radius={0.02} position={[0, 0, 0]} material={PM.arcadeTrim} />+ <Cyl radius={0.012} height={0.08} position={[-0.15, 0.08, 0]} material={MAT.monitor} cast={false} />+ <mesh geometry={PGEO.sphere} material={PM.joystick} position={[-0.15, 0.13, 0]} scale={0.035} castShadow />+ {PM.arcadeButtons.map((material, i) => (+ <Cyl key={i} radius={0.025} height={0.02} position={[0.05 + i * 0.08, 0.045, 0]} material={material} cast={false} />+ ))}+ </group>+ <Rounded size={[0.7, 0.72, 0.42]} radius={0.03} position={[0, 1.4, -0.15]} material={PM.arcadeBody} />+ <Box size={[0.62, 0.5, 0.01]} position={[0, 1.36, 0.062]} material={PM.arcadeTrim} cast={false} />+ <Panel size={[0.56, 0.44]} position={[0, 1.36, 0.068]} material={lazy.arcade()} />+ <Box size={[0.7, 0.14, 0.14]} position={[0, 1.72, 0]} material={PM.marquee} />+ <Box size={[0.012, 1.6, 0.5]} position={[-0.356, 0.9, -0.05]} material={PM.arcadeTrim} cast={false} />+ <Box size={[0.012, 1.6, 0.5]} position={[0.356, 0.9, -0.05]} material={PM.arcadeTrim} cast={false} />+ </group>+ );+}++/** Stable small hash of an id (colour picks, variations). */+export function idHash(id: string): number {+ let hash = 0;+ for (const ch of id) hash = (hash * 31 + ch.charCodeAt(0)) >>> 0;+ return hash;+}++/** A squashed soft beanbag; the raised back is on the -z side, so it faces +z. */+function Beanbag({ id }: { id: string }) {+ const material = PM.beanbags[idHash(id) % PM.beanbags.length];+ return (+ <group>+ <mesh geometry={PGEO.sphere} material={material} position={[0, 0.26, 0]} scale={[0.44, 0.26, 0.44]} castShadow receiveShadow />+ <mesh geometry={PGEO.sphere} material={material} position={[0, 0.42, -0.16]} scale={[0.36, 0.18, 0.24]} castShadow receiveShadow />+ </group>+ );+}++/** A flat rug with an inner field, sized per instance. */+function RugPiece({ w, d }: { w: number; d: number }) {+ const inset = Math.min(0.3, Math.min(w, d) * 0.15);+ return (+ <group>+ <Rug position={[0, 0.01, 0]} size={[w, d]} />+ <Box size={[w - inset, 0.022, d - inset]} position={[0, 0.011, 0]} material={PM.rugInner} cast={false} />+ </group>+ );+}++/** Steel elevator doors in a free-standing shaft block; doors face +z, wood slats on the back. */+function Elevator() {+ return (+ <group>+ <Rounded size={[2.2, 2.4, 0.3]} radius={0.04} position={[0, 1.2, -0.05]} material={PM.shaft} />+ <Box size={[0.1, 2.08, 0.06]} position={[-0.66, 1.04, 0.12]} material={PM.steelDark} />+ <Box size={[0.1, 2.08, 0.06]} position={[0.66, 1.04, 0.12]} material={PM.steelDark} />+ <Box size={[1.42, 0.1, 0.06]} position={[0, 2.13, 0.12]} material={PM.steelDark} />+ <Box size={[0.6, 2.0, 0.03]} position={[-0.305, 1.0, 0.11]} material={PM.steel} />+ <Box size={[0.6, 2.0, 0.03]} position={[0.305, 1.0, 0.11]} material={PM.steel} />+ <Box size={[0.012, 2.0, 0.035]} position={[0, 1.0, 0.112]} material={PM.steelDark} cast={false} />+ <Box size={[1.3, 0.02, 0.08]} position={[0, 0.01, 0.15]} material={PM.steelDark} cast={false} />+ <Box size={[0.34, 0.14, 0.02]} position={[0, 2.28, 0.11]} material={MAT.monitor} cast={false} />+ <Panel size={[0.3, 0.1]} position={[0, 2.28, 0.1205]} material={lazy.indicator()} />+ <Box size={[0.1, 0.22, 0.02]} position={[0.9, 1.1, 0.11]} material={PM.steel} cast={false} />+ <Box size={[0.035, 0.035, 0.01]} position={[0.9, 1.15, 0.122]} material={PM.indicatorLight} cast={false} />+ <Box size={[0.035, 0.035, 0.01]} position={[0.9, 1.05, 0.122]} material={PM.steelDark} cast={false} />+ {[-0.9, -0.54, -0.18, 0.18, 0.54, 0.9].map((x) => (+ <Box key={x} size={[0.1, 2.1, 0.03]} position={[x, 1.1, -0.185]} material={MAT.woodDark} cast={false} />+ ))}+ </group>+ );+}++/** Plant scale that keeps the canopy inside the 0.6 m plant footprint. */+export const PROP_PLANT_SIZE = 0.82;++const COUCH_FIT_X = FURNITURE_SIZE.couch.w / 2.36;++/** Every furniture kind maps to exactly one renderer (the Record type keeps this exhaustive). */+export const PROP_RENDERERS: Record<FurnitureKind, (props: { item: Furniture }) => JSX.Element> = {+ meetingTable: () => <MeetingTable />,+ teamBoard: () => <TeamBoard />,+ receptionDesk: () => <ReceptionDesk />,+ kiosk: () => <Kiosk />,+ lockers: () => <Lockers />,+ mirror: () => <Mirror />,+ coffeeBar: () => <CoffeeBar />,+ waterCooler: () => <WaterCooler />,+ // The shared couch's armrests reach 2.36 m; squeeze it into the 2.2 m footprint.+ couch: () => <group scale={[COUCH_FIT_X, 1, 1]}><Couch position={[0, 0, 0]} /></group>,+ coffeeTable: () => <CoffeeTable />,+ arcade: () => <Arcade />,+ beanbag: ({ item }) => <Beanbag id={item.id} />,+ bookshelf: () => <Bookshelf position={[0, 0, 0]} />,+ plant: () => <Plant position={[0, 0, 0]} size={PROP_PLANT_SIZE} />,+ rug: ({ item }) => {+ const size = item.size ?? FURNITURE_SIZE.rug;+ return <RugPiece w={size.w} d={size.d} />;+ },+ elevator: () => <Elevator />,+};++/** One furniture item, placed at (x, 0, z) and turned by `rotationY` (0 = front faces +z). */+export const FurniturePiece = memo(function FurniturePiece({ item }: { item: Furniture }) {+ const Render = PROP_RENDERERS[item.kind];+ return (+ <group position={[item.x, 0, item.z]} rotation={[0, item.rotationY, 0]} name={`prop:${item.id}`}>+ <Render item={item} />+ </group>+ );+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeRooms.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeRooms.tsxnew file mode 100644index 0000000000..b63bcc5816--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeRooms.tsx@@ -0,0 +1,230 @@+/**+ * Rooms of the walkable office: a floor overlay per room, glass walls along+ * the layout's wall segments, and a name sign above each room's door.+ * Pattern textures and sign textures are drawn once and cached.+ */+import { useEffect, useMemo } from "react";+import { MeshStandardMaterial, RepeatWrapping, type Texture } from "three";+import { Box, MAT, Rounded } from "./OfficeFurniture";+import { cachedCanvasTexture } from "./OfficeProps";+import type { Door, Room, RoomKind, WallSegment } from "./officeLayout";+import { OFFICE, ROOM_FLOOR_COLOURS } from "./officePalette";++// ---------------------------------------------------------------------------+// Floors+// ---------------------------------------------------------------------------++/** Deterministic pseudo-random numbers, so the patterns never shimmer between loads. */+function lcg(seed: number): () => number {+ let state = seed >>> 0;+ return () => {+ state = (state * 1664525 + 1013904223) >>> 0;+ return state / 0x1_0000_0000;+ };+}++/** Metres covered by one repeat of each floor pattern. */+const PATTERN_METRES: Record<RoomKind, number> = { lead: 3, team: 2, wardrobe: 2, reception: 2.4, break: 2 };++function drawFloor(kind: RoomKind, ctx: CanvasRenderingContext2D, w: number, h: number): void {+ const { base, accents } = ROOM_FLOOR_COLOURS[kind];+ const rand = lcg(kind.length * 7919 + kind.charCodeAt(0));+ ctx.fillStyle = base;+ ctx.fillRect(0, 0, w, h);+ if (kind === "lead") {+ // Warm planks, narrower and richer than the main floor.+ const rows = 10, rowH = h / rows;+ for (let row = 0; row < rows; row += 1) {+ const offset = ((row * 71) % 128) - 128;+ for (let seg = 0; seg < 4; seg += 1) {+ ctx.fillStyle = accents[(row + seg) % accents.length];+ ctx.fillRect(offset + seg * 128, row * rowH, 128, rowH);+ ctx.fillStyle = "rgba(70,40,20,0.35)";+ ctx.fillRect(offset + seg * 128, row * rowH, 2, rowH);+ }+ ctx.fillStyle = "rgba(70,40,20,0.3)";+ ctx.fillRect(0, row * rowH, w, 2);+ }+ } else if (kind === "team" || kind === "break") {+ // Carpet grain: fine speckles in the accent tones, plus a faint weave.+ for (let i = 0; i < 2600; i += 1) {+ ctx.fillStyle = accents[Math.floor(rand() * accents.length)];+ ctx.fillRect(Math.floor(rand() * w), Math.floor(rand() * h), 2, 2);+ }+ ctx.fillStyle = "rgba(0,0,0,0.035)";+ for (let y = 0; y < h; y += 8) ctx.fillRect(0, y, w, 1);+ } else {+ // Tiles: wardrobe small square tiles, reception large stone slabs.+ const tiles = kind === "wardrobe" ? 4 : 2;+ const size = w / tiles;+ for (let ty = 0; ty < tiles; ty += 1) {+ for (let tx = 0; tx < tiles; tx += 1) {+ ctx.fillStyle = accents[Math.floor(rand() * accents.length)];+ ctx.fillRect(tx * size, ty * size, size, size);+ if (kind === "reception") {+ for (let i = 0; i < 90; i += 1) {+ ctx.fillStyle = rand() > 0.5 ? "rgba(255,255,255,0.18)" : "rgba(120,110,95,0.12)";+ ctx.fillRect(tx * size + rand() * size, ty * size + rand() * size, 3, 3);+ }+ }+ }+ }+ ctx.fillStyle = kind === "wardrobe" ? "rgba(120,100,150,0.35)" : "rgba(140,130,115,0.45)";+ for (let i = 0; i < tiles; i += 1) {+ ctx.fillRect(i * size, 0, 3, h);+ ctx.fillRect(0, i * size, w, 3);+ }+ }+}++function floorTexture(kind: RoomKind): Texture | null {+ const texture = cachedCanvasTexture(`floor:${kind}`, 256, 256, (ctx, w, h) => drawFloor(kind, ctx, w, h));+ if (texture) {+ texture.wrapS = texture.wrapT = RepeatWrapping;+ texture.anisotropy = 8;+ }+ return texture;+}++function RoomFloor({ room }: { room: Room }) {+ const w = room.maxX - room.minX;+ const d = room.maxZ - room.minZ;+ const material = useMemo(() => {+ const base = floorTexture(room.kind);+ let map: Texture | null = null;+ if (base) {+ map = base.clone();+ map.repeat.set(w / PATTERN_METRES[room.kind], d / PATTERN_METRES[room.kind]);+ map.needsUpdate = true;+ }+ return new MeshStandardMaterial({ color: map ? "#ffffff" : ROOM_FLOOR_COLOURS[room.kind].base, map, roughness: 0.85 });+ }, [room.kind, w, d]);+ // The clone and its material belong to this room; the cached base texture stays.+ useEffect(() => () => { material.map?.dispose(); material.dispose(); }, [material]);+ return (+ <mesh position={[(room.minX + room.maxX) / 2, 0.004, (room.minZ + room.maxZ) / 2]} rotation={[-Math.PI / 2, 0, 0]}+ material={material} receiveShadow>+ <planeGeometry args={[w, d]} />+ </mesh>+ );+}++/** A floor overlay per room: wood (lead), teal carpet (team), lilac tile (wardrobe), stone (reception), coral carpet (break). */+export function RoomFloors({ rooms }: { rooms: Room[] }) {+ return <group>{rooms.map((room) => <RoomFloor key={room.id} room={room} />)}</group>;+}++// ---------------------------------------------------------------------------+// Walls+// ---------------------------------------------------------------------------++export const WALL_HEIGHT = 2.1;+const BASE_HEIGHT = 0.12;+const POST_SPACING = 1.5;++/** One glass wall run: white base strip, glass pane, metal posts and a top rail. */+function GlassWall({ wall }: { wall: WallSegment }) {+ const length = Math.hypot(wall.x2 - wall.x1, wall.z2 - wall.z1);+ if (length < 0.05) return null;+ const angle = Math.atan2(wall.z2 - wall.z1, wall.x2 - wall.x1);+ const posts = Math.max(2, Math.ceil(length / POST_SPACING) + 1);+ return (+ <group position={[(wall.x1 + wall.x2) / 2, 0, (wall.z1 + wall.z2) / 2]} rotation={[0, -angle, 0]}>+ <Box size={[length, BASE_HEIGHT, 0.1]} position={[0, BASE_HEIGHT / 2, 0]} material={MAT.wall} />+ <Box size={[length, WALL_HEIGHT - BASE_HEIGHT - 0.04, 0.02]} position={[0, (WALL_HEIGHT + BASE_HEIGHT - 0.04) / 2, 0]}+ material={MAT.glass} cast={false} />+ <Box size={[length, 0.05, 0.07]} position={[0, WALL_HEIGHT - 0.025, 0]} material={MAT.railing} />+ {Array.from({ length: posts }, (_, i) => (+ <Box key={i} size={[0.05, WALL_HEIGHT, 0.07]} position={[-length / 2 + (length * i) / (posts - 1), WALL_HEIGHT / 2, 0]}+ material={MAT.railing} />+ ))}+ </group>+ );+}++/** Glass walls, 2.1 m high, along every wall segment of the layout. */+export function RoomWalls({ walls }: { walls: WallSegment[] }) {+ return (+ <group>+ {walls.map((wall) => <GlassWall key={`${wall.room}:${wall.x1}:${wall.z1}:${wall.x2}:${wall.z2}`} wall={wall} />)}+ </group>+ );+}++// ---------------------------------------------------------------------------+// Signs+// ---------------------------------------------------------------------------++const SIGN_W = 1.5;+const SIGN_H = 0.36;+const SIGN_TEXT_W = 1.4;+const SIGN_CANVAS = { w: 512, h: 112 } as const;++const signMaterials = new Map<string, MeshStandardMaterial>();+function signMaterial(label: string): MeshStandardMaterial {+ let material = signMaterials.get(label);+ if (!material) {+ const map = cachedCanvasTexture(`room-sign:${label}`, SIGN_CANVAS.w, SIGN_CANVAS.h, (ctx, w, h) => {+ ctx.fillStyle = OFFICE.signBoard;+ ctx.fillRect(0, 0, w, h);+ ctx.fillStyle = OFFICE.signText;+ ctx.font = "600 56px system-ui, -apple-system, 'Segoe UI', sans-serif";+ ctx.textAlign = "center";+ ctx.textBaseline = "middle";+ ctx.fillText(label.length > 16 ? `${label.slice(0, 15)}…` : label, w / 2, h / 2 + 2);+ });+ material = new MeshStandardMaterial({ color: map ? "#ffffff" : OFFICE.signBoard, map, roughness: 0.8 });+ signMaterials.set(label, material);+ }+ return material;+}++/** Dark-wood board with the label on both faces, centred on its local origin. */+function SignBoard({ label }: { label: string }) {+ const material = signMaterial(label);+ const textH = (SIGN_TEXT_W * SIGN_CANVAS.h) / SIGN_CANVAS.w;+ return (+ <group>+ <Rounded size={[SIGN_W, SIGN_H, 0.06]} radius={0.025} position={[0, 0, 0]} material={MAT.sign} />+ <mesh position={[0, 0, 0.0305]} material={material}><planeGeometry args={[SIGN_TEXT_W, textH]} /></mesh>+ <mesh position={[0, 0, -0.0305]} rotation={[0, Math.PI, 0]} material={material}><planeGeometry args={[SIGN_TEXT_W, textH]} /></mesh>+ </group>+ );+}++/** Where a door-top sign sits: the door's centre on its wall line, turned to run along the wall. */+function doorAnchor(room: Room, door: Door): { x: number; z: number; rotationY: number } {+ switch (door.side) {+ case "south": return { x: door.at, z: room.maxZ, rotationY: 0 };+ case "north": return { x: door.at, z: room.minZ, rotationY: 0 };+ case "west": return { x: room.minX, z: door.at, rotationY: Math.PI / 2 };+ case "east": return { x: room.maxX, z: door.at, rotationY: Math.PI / 2 };+ }+}++/**+ * A room's name sign. Walled rooms: a board sitting on a header rail across+ * their first door, readable from both sides. Open rooms: a free-standing arch+ * (two slim posts, board on top) centred on the room's north edge.+ */+export function RoomSign({ room, label }: { room: Room; label: string }) {+ const door = room.walled ? room.doors[0] : undefined;+ if (door) {+ const { x, z, rotationY } = doorAnchor(room, door);+ return (+ <group position={[x, 0, z]} rotation={[0, rotationY, 0]}>+ <Box size={[door.width, 0.07, 0.07]} position={[0, WALL_HEIGHT - 0.035, 0]} material={MAT.railing} />+ <group position={[0, WALL_HEIGHT + SIGN_H / 2 + 0.02, 0]}><SignBoard label={label} /></group>+ </group>+ );+ }+ const archY = 2.3;+ return (+ <group position={[(room.minX + room.maxX) / 2, 0, room.minZ + 0.25]}>+ <Box size={[0.08, archY + SIGN_H / 2, 0.08]} position={[-0.95, (archY + SIGN_H / 2) / 2, 0]} material={MAT.woodDark} />+ <Box size={[0.08, archY + SIGN_H / 2, 0.08]} position={[0.95, (archY + SIGN_H / 2) / 2, 0]} material={MAT.woodDark} />+ <Box size={[1.98, 0.06, 0.08]} position={[0, archY - SIGN_H / 2 - 0.03, 0]} material={MAT.woodDark} />+ <group position={[0, archY, 0]}><SignBoard label={label} /></group>+ </group>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsxindex 899fa241ba..b077c44b3a 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx@@ -1,23 +1,33 @@/**- * The office floor: a wood-and-carpet plate floating in a starry night, glass- * railings around it, one carpeted department per provider family, the lead's- * glass office at the back and a lounge at the front.+ * The office floor: a wood-plank plate floating in a starry night, glass+ * railings around it, walled rooms in the north and south, one carpeted+ * department per provider family in between — and everybody in it.*/-import { useEffect, useMemo, useRef } from "react";-import { OrbitControls, Stars } from "@react-three/drei";-import { useThree } from "@react-three/fiber";+import { useMemo } from "react";+import { Stars } from "@react-three/drei";+import type { ThreeEvent } from "@react-three/fiber";import { CanvasTexture, Color, RepeatWrapping, SRGBColorSpace, type Texture } from "three";import { useT } from "@/i18n";-import type { OrbitControls as OrbitControlsImpl } from "three-stdlib";import type { SocietyAgent } from "../data";-import { Bookshelf, Couch, Desk, MAT, Plant, Railing, Rug, SignWall } from "./OfficeFurniture";-import { OfficeAgents } from "./OfficeAgents";-import { allDesks, type Department, type OfficeLayout } from "./officeLayout";+import type { FigureRecipe } from "../figures/figureRecipe";+import { Railing, SignWall } from "./OfficeFurniture";+import { DeskInstances } from "./DeskInstances";+import { FurniturePiece, MeetingChairs } from "./OfficeProps";+import { RoomFloors, RoomSign, RoomWalls } from "./OfficeRooms";+import { CheckpointMarker } from "./CheckpointMarker";+import { OfficeAgents, type WalkerContext } from "./OfficeAgents";+import { OfficePlayer } from "./OfficePlayer";+import { OfficeCameraRig } from "./OfficeCameraRig";+import { allDesks, type CheckpointKind, type Department, type OfficeLayout } from "./officeLayout";+import type { NavGrid } from "./officeNav";import { DEPARTMENT_TINTS, OFFICE } from "./officePalette";-import { cameraHome, CAMERA_LIMITS, focusBounds } from "./officeCamera";-import type { ScreenFace } from "./screenTextures";+import { useOfficeStore, type Selection } from "./officeStore";-/** Warm planks drawn once; repeated across the floor at about 1 m per plank run. */+const CHECKPOINT_ICON: Record<CheckpointKind, "plus" | "list" | "team" | "shirt" | "star" | "coffee"> = {+ create: "plus", manage: "list", team: "team", wardrobe: "shirt", lead: "star", break: "coffee",+};++/** Warm planks drawn once; repeated across the floor. */let plankTexture: Texture | null | undefined;function planks(): Texture | null {if (plankTexture !== undefined) return plankTexture;@@ -51,7 +61,7 @@ function planks(): Texture | null {return plankTexture;}-function Slab({ layout }: { layout: OfficeLayout }) {+function Slab({ layout, onFloorClick }: { layout: OfficeLayout; onFloorClick: (event: ThreeEvent<MouseEvent>) => void }) {const { minX, maxX, minZ, maxZ } = layout.bounds;const w = maxX - minX, d = maxZ - minZ, cx = (minX + maxX) / 2, cz = (minZ + maxZ) / 2;const floorMap = useMemo(() => {@@ -68,8 +78,7 @@ function Slab({ layout }: { layout: OfficeLayout }) {<boxGeometry args={[w, 0.6, d]} /><meshStandardMaterial color={OFFICE.slabEdge} roughness={0.9} /></mesh>- {/* Warm wood floor everywhere; departments lay carpet on top. */}- <mesh position={[cx, 0.001, cz]} rotation={[-Math.PI / 2, 0, 0]} receiveShadow>+ <mesh position={[cx, 0.001, cz]} rotation={[-Math.PI / 2, 0, 0]} receiveShadow onClick={onFloorClick}><planeGeometry args={[w, d]} /><meshStandardMaterial color={floorMap ? "#ffffff" : OFFICE.walkway} map={floorMap} roughness={0.8} /></mesh>@@ -81,12 +90,7 @@ function Slab({ layout }: { layout: OfficeLayout }) {);}-function deskFace(agentId: string | null, agents: ReadonlyMap<string, SocietyAgent>): ScreenFace {- const agent = agentId ? agents.get(agentId) : undefined;- return agent ? agent.state : "empty";-}--function DepartmentArea({ dept, agents }: { dept: Department; agents: ReadonlyMap<string, SocietyAgent> }) {+function DepartmentArea({ dept }: { dept: Department }) {const t = useT();const w = dept.maxX - dept.minX, d = dept.maxZ - dept.minZ;const cx = (dept.minX + dept.maxX) / 2, cz = (dept.minZ + dept.maxZ) / 2;@@ -98,91 +102,38 @@ function DepartmentArea({ dept, agents }: { dept: Department; agents: ReadonlyMa<meshStandardMaterial color={tint} roughness={0.95} /></mesh><SignWall label={dept.label || t("society.office.open_space")} width={w - 0.4} position={[cx, 0, dept.minZ + 0.1]} />- {dept.desks.map((desk) => (- <group key={desk.id} position={[desk.x, 0, desk.z]} rotation={[0, desk.facing === "north" ? 0 : Math.PI, 0]}>- <Desk face={deskFace(desk.agentId, agents)} />- </group>- ))}- <Plant position={[dept.minX + 0.45, 0, dept.maxZ - 0.45]} size={0.9} />- <Plant position={[dept.maxX - 0.45, 0, dept.maxZ - 0.45]} size={0.9} />- </group>- );-}--function LeadOfficeRoom({ layout, agents }: { layout: OfficeLayout; agents: ReadonlyMap<string, SocietyAgent> }) {- const { minX, maxX, minZ, maxZ } = layout.lead;- const w = maxX - minX, d = maxZ - minZ, cx = (minX + maxX) / 2, cz = (minZ + maxZ) / 2;- return (- <group>- <mesh position={[cx, 0.006, cz]} rotation={[-Math.PI / 2, 0, 0]} receiveShadow>- <planeGeometry args={[w, d]} />- <meshStandardMaterial color={OFFICE.wood} roughness={0.8} />- </mesh>- <SignWall label="Lead" width={w - 0.4} position={[cx, 0, minZ + 0.1]} />- {/* Glass walls on the open sides, with a door gap facing the floor. */}- <Railing from={[maxX, minZ + 0.3]} to={[maxX, maxZ]} height={2.1} />- <Railing from={[minX + 0.2, maxZ]} to={[cx - 0.7, maxZ]} height={2.1} />- <Railing from={[cx + 0.7, maxZ]} to={[maxX, maxZ]} height={2.1} />- {layout.lead.desks.map((desk) => (- <group key={desk.id} position={[desk.x, 0, desk.z]} rotation={[0, Math.PI, 0]}>- <Desk face={deskFace(desk.agentId, agents)} />- </group>- ))}- <Bookshelf position={[maxX - 1.3, 0, minZ + 0.45]} />- <Plant position={[minX + 0.5, 0, maxZ - 0.5]} size={1.2} /></group>);}-function Lounge({ layout }: { layout: OfficeLayout }) {- const { minX, maxX, minZ, maxZ } = layout.lounge;- const cx = (minX + maxX) / 2, cz = (minZ + maxZ) / 2;- return (- <group>- <Rug position={[cx - 3, 0.01, cz]} size={[6.5, 4]} />- <Couch position={[cx - 3, 0, cz - 1]} />- <Couch position={[cx - 5.4, 0, cz + 0.3]} rotationY={Math.PI / 2} />- <mesh position={[cx - 3, 0.22, cz + 0.4]} castShadow receiveShadow material={MAT.wood}>- <cylinderGeometry args={[0.55, 0.55, 0.06, 24]} />- </mesh>- <Bookshelf position={[cx + 2.5, 0, maxZ - 0.5]} rotationY={Math.PI} />- <Bookshelf position={[cx + 4.6, 0, maxZ - 0.5]} rotationY={Math.PI} />- <Plant position={[minX + 0.6, 0, maxZ - 0.6]} size={1.4} />- <Plant position={[maxX - 0.6, 0, minZ + 0.6]} size={1.2} />- <Plant position={[cx + 0.4, 0, cz - 1.2]} size={1.1} />- </group>- );+export interface OfficeSceneProps {+ layout: OfficeLayout;+ grid: NavGrid;+ walkers: WalkerContext;+ agents: ReadonlyMap<string, SocietyAgent>;+ newcomers: ReadonlySet<string>;+ awake: boolean;+ reduced: boolean;+ overview: number;+ player: { recipe: FigureRecipe; name: string };+ selection: Selection | null;+ nearby: Selection | null;}-function CameraRig({ layout, reset }: { layout: OfficeLayout; reset: number }) {- const focus = useMemo(() => focusBounds(allDesks(layout).filter((d) => d.agentId)), [layout]);- const controls = useRef<OrbitControlsImpl>(null);- const camera = useThree((s) => s.camera);- const size = useThree((s) => s.size);- useEffect(() => {- const home = cameraHome(layout.bounds, size.width / Math.max(1, size.height), focus);- camera.position.set(...home.position);- controls.current?.target.set(...home.target);- controls.current?.update();- // Dev-only handle for runtime screenshots at chosen angles.- if (import.meta.env.DEV) (window as unknown as Record<string, unknown>).__office = { camera, controls: controls.current };- // `size` only matters for the first framing; a resize keeps the user's view.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [camera, layout.bounds, focus, reset]);- return (- <OrbitControls ref={controls} makeDefault enableDamping dampingFactor={0.12} screenSpacePanning={false}- minPolarAngle={CAMERA_LIMITS.minPolar} maxPolarAngle={CAMERA_LIMITS.maxPolar}- minDistance={CAMERA_LIMITS.minDistance} maxDistance={CAMERA_LIMITS.maxDistance} />- );-}--export function OfficeScene({ layout, agents, awake, reduced, reset, onSelect }: {- layout: OfficeLayout; agents: ReadonlyMap<string, SocietyAgent>; awake: boolean; reduced: boolean; reset: number; onSelect: (id: string) => void;-}) {+export function OfficeScene({ layout, grid, walkers, agents, newcomers, awake, reduced, overview, player, selection, nearby }: OfficeSceneProps) {+ const t = useT();const desks = useMemo(() => allDesks(layout), [layout]);const background = useMemo(() => new Color(OFFICE.space), []);const { minX, maxX, minZ, maxZ } = layout.bounds;const span = Math.max(maxX - minX, maxZ - minZ);+ const select = useOfficeStore((s) => s.select);+ const table = layout.furniture.find((f) => f.kind === "meetingTable");+ const onFloorClick = (event: ThreeEvent<MouseEvent>) => {+ // A drag that ends on the floor rotated the camera; only a real click walks.+ if (event.delta > 6) return;+ event.stopPropagation();+ useOfficeStore.getState().requestWalk({ x: event.point.x, z: event.point.z });+ };return (<><primitive attach="background" object={background} />@@ -194,12 +145,23 @@ export function OfficeScene({ layout, agents, awake, reduced, reset, onSelect }:shadow-mapSize={[2048, 2048]} shadow-bias={-0.0004} shadow-normalBias={0.03}shadow-camera-left={-span * 0.7} shadow-camera-right={span * 0.7}shadow-camera-top={span * 0.7} shadow-camera-bottom={-span * 0.7} shadow-camera-far={120} />- <Slab layout={layout} />- <LeadOfficeRoom layout={layout} agents={agents} />- {layout.departments.map((dept) => <DepartmentArea key={dept.id} dept={dept} agents={agents} />)}- <Lounge layout={layout} />- <OfficeAgents desks={desks} agents={agents} awake={awake} reduced={reduced} onSelect={onSelect} />- <CameraRig layout={layout} reset={reset} />+ <Slab layout={layout} onFloorClick={onFloorClick} />+ <RoomFloors rooms={layout.rooms} />+ <RoomWalls walls={layout.walls} />+ {layout.rooms.map((room) => <RoomSign key={room.id} room={room} label={t(`society.office.room_${room.kind}`)} />)}+ {layout.departments.map((dept) => <DepartmentArea key={dept.id} dept={dept} />)}+ <DeskInstances desks={desks} agents={agents} />+ {layout.furniture.map((item) => <FurniturePiece key={item.id} item={item} />)}+ {table && <MeetingChairs table={table} />}+ {layout.checkpoints.map((cp) => (+ <CheckpointMarker key={cp.id} checkpoint={cp} label={t(`society.office.cp_${cp.id}`)} icon={CHECKPOINT_ICON[cp.id]}+ active={(nearby?.kind === "checkpoint" && nearby.id === cp.id) || (selection?.kind === "checkpoint" && selection.id === cp.id)}+ animate={awake && !reduced} onActivate={() => select({ kind: "checkpoint", id: cp.id })} />+ ))}+ <OfficePlayer layout={layout} grid={grid} recipe={player.recipe} name={player.name} awake={awake} reduced={reduced} />+ <OfficeAgents desks={desks} agents={agents} ctx={walkers} newcomers={newcomers} awake={awake} reduced={reduced}+ selectedId={selection?.kind === "agent" ? selection.id : null} onSelect={(id) => select({ kind: "agent", id })} />+ <OfficeCameraRig layout={layout} overview={overview} /></>);}diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsxindex f159667a4d..dffe58f53f 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx@@ -1,9 +1,10 @@/**- * Agents > Map: the office. One overview of every agent at its desk, grouped- * into departments, with a live working/idle count. Clicking an agent opens- * its card; the map itself never starts or stops work.+ * Agents > Map: the office. The person walks their own character through the+ * floor (or zooms out and clicks), agents live their day according to their+ * real run state, and checkpoints turn rooms into actions: create, manage,+ * team up, dress up, talk to the lead, call a coffee break.*/-import { Component, Suspense, useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import { Component, Suspense, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";import { useQueryClient } from "@tanstack/react-query";import { Canvas } from "@react-three/fiber";import { useReducedMotion } from "framer-motion";@@ -13,9 +14,20 @@ import { useWebglSupported } from "@/lib/graphDimension";import { useT } from "@/i18n";import { useSocietyRoster, type SocietyAgent } from "../data";import { OfficeScene } from "./OfficeScene";-import { buildOfficeLayout, countStates, MAX_SEATED } from "./officeLayout";+import { allDesks, buildOfficeLayout, countStates, MAX_SEATED } from "./officeLayout";+import { buildNavGrid } from "./officeNav";+import { SpotBook } from "./officeBehavior";import { CAMERA_FOV } from "./officeCamera";+import { player, useOfficeStore } from "./officeStore";+import { knownAgents } from "./walkerRegistry";+import { loadProfile, saveProfile, type PlayerProfile } from "./playerProfile";+import { AgentPanel, CheckpointPanel, type OfficeActions } from "./OfficePanels";+import type { WalkerContext } from "./OfficeAgents";import "./office.css";+import "./officeHud.css";++// Dev-only handles for runtime checks of walking and panels.+if (import.meta.env.DEV && typeof window !== "undefined") Object.assign(window, { __officeStore: useOfficeStore, __officePlayer: player });/** Status refresh while the office is on screen; jittered so windows never poll in lockstep (AP-33). */const REFRESH_MS = 5000;@@ -33,19 +45,12 @@ class RenderBoundary extends Component<{ children: ReactNode; fallbackText: striexport interface OfficeStageProps {onOpenLedger: () => void;onSelectAgent?: (id: string | null) => void;+ onCreateAgent?: () => void;+ onOpenGroup?: (groupId: string) => void;}-export function OfficeStage({ onOpenLedger, onSelectAgent }: OfficeStageProps) {- const t = useT();- const hostRef = useRef<HTMLDivElement>(null);- const awake = useCanvasAwake(hostRef);- const reduced = useReducedMotion() ?? false;- const { generation } = useWebglSurface(hostRef);- const webgl = useWebglSupported();- const roster = useSocietyRoster();+function useRosterRefresh(awake: boolean) {const client = useQueryClient();- const [reset, setReset] = useState(0);-useEffect(() => {if (!awake) return;let timer: ReturnType<typeof setTimeout>;@@ -58,17 +63,91 @@ export function OfficeStage({ onOpenLedger, onSelectAgent }: OfficeStageProps) {schedule();return () => clearTimeout(timer);}, [awake, client]);+}++/** Agents created while the office is open arrive by the elevator; everyone else is simply there. */+function useNewcomers(active: SocietyAgent[]): ReadonlySet<string> {+ const [newcomers, setNewcomers] = useState<ReadonlySet<string>>(new Set());+ useEffect(() => {+ if (active.length === 0) return;+ if (knownAgents.size === 0) { active.forEach((a) => knownAgents.add(a.agentId)); return; }+ const fresh = active.filter((a) => !knownAgents.has(a.agentId)).map((a) => a.agentId);+ if (fresh.length === 0) return;+ fresh.forEach((id) => knownAgents.add(id));+ setNewcomers((prev) => new Set([...prev, ...fresh]));+ }, [active]);+ return newcomers;+}++export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenGroup }: OfficeStageProps) {+ const t = useT();+ const hostRef = useRef<HTMLDivElement>(null);+ const awake = useCanvasAwake(hostRef);+ const reduced = useReducedMotion() ?? false;+ const { generation } = useWebglSurface(hostRef);+ const webgl = useWebglSupported();+ const roster = useSocietyRoster();+ useRosterRefresh(awake);+ const [overview, setOverview] = useState(0);+ const [profile, setProfile] = useState<PlayerProfile>(loadProfile);+ const selection = useOfficeStore((s) => s.selection);+ const nearby = useOfficeStore((s) => s.nearby);+ const follow = useOfficeStore((s) => s.follow);+ const select = useOfficeStore((s) => s.select);const active = useMemo(() => (roster.data?.agents ?? []).filter((a) => a.lifecycle !== "archived"), [roster.data]);const agents = useMemo(() => new Map<string, SocietyAgent>(active.map((a) => [a.agentId, a])), [active]);- // The layout only depends on who works where, never on run state, so a- // status refresh repaints monitors without re-seating anyone.+ const newcomers = useNewcomers(active);+ // The floor plan depends on who works where, never on run state: a status+ // refresh changes monitors and behaviour without re-seating anyone.const seatingKey = active.map((a) => `${a.agentId}|${a.tier}|${a.providerLabel}|${a.createdMs}`).join(",");const layout = useMemo(() => buildOfficeLayout(active),// eslint-disable-next-line react-hooks/exhaustive-deps[seatingKey]);+ const grid = useMemo(() => buildNavGrid(layout), [layout]);+ const book = useMemo(() => new SpotBook(), [layout]);+ const agentsRef = useRef(agents);+ agentsRef.current = agents;+ const walkers = useMemo<WalkerContext>(() => {+ const desks = allDesks(layout);+ return {+ layout, grid, book, spawn: layout.spawn,+ colleagues: () => desks.filter((d) => d.agentId && agentsRef.current.get(d.agentId)?.state === "working")+ .map((d) => ({ agentId: d.agentId as string, desk: d })),+ };+ }, [layout, grid, book]);+const counts = countStates(active);- const select = (id: string) => onSelectAgent?.(id);+ const updateProfile = useCallback((next: PlayerProfile) => { setProfile(next); saveProfile(next); }, []);+ const actions = useMemo<OfficeActions>(() => ({+ onOpenAgent: (id) => onSelectAgent?.(id),+ onOpenLedger, onCreateAgent, onOpenGroup,+ }), [onSelectAgent, onOpenLedger, onCreateAgent, onOpenGroup]);++ // Escape closes an open panel before it can leave the map.+ useEffect(() => {+ const onKey = (event: KeyboardEvent) => {+ if (event.key !== "Escape" || !useOfficeStore.getState().selection) return;+ event.preventDefault();+ event.stopPropagation();+ select(null);+ };+ document.addEventListener("keydown", onKey, true);+ return () => document.removeEventListener("keydown", onKey, true);+ }, [select]);++ // A panel for an agent that left the roster closes itself.+ useEffect(() => {+ if (selection?.kind === "agent" && roster.data && !agents.has(selection.id)) select(null);+ }, [selection, agents, roster.data, select]);++ const selectedAgent = selection?.kind === "agent" ? agents.get(selection.id) ?? null : null;+ const nearbyLabel = nearby+ ? nearby.kind === "agent"+ ? t("society.office.prompt_agent").replace("{0}", agents.get(nearby.id)?.name ?? "")+ : t("society.office.prompt_checkpoint").replace("{0}", t(`society.office.cp_${nearby.id}`))+ : null;+ const playerName = profile.name.trim() || t("society.office.you");return (<section className="office-stage" aria-label={t("society.office.title")} data-office-agents={active.length}>@@ -77,9 +156,12 @@ export function OfficeStage({ onOpenLedger, onSelectAgent }: OfficeStageProps) {<RenderBoundary key={generation} fallbackText={t("society.office.no_graphics")}><Suspense fallback={<div className="office-fallback" role="status">{t("society.office.loading")}</div>}><Canvas shadows="percentage" camera={{ fov: CAMERA_FOV, near: 0.2, far: 800, position: [30, 30, 30] }} dpr={[1, 1.75]}- gl={{ antialias: true, alpha: false, preserveDrawingBuffer: import.meta.env.DEV }} frameloop={!awake ? "never" : reduced ? "demand" : "always"}- onPointerMissed={() => onSelectAgent?.(null)}>- <OfficeScene layout={layout} agents={agents} awake={awake} reduced={reduced} reset={reset} onSelect={select} />+ gl={{ antialias: true, alpha: false, preserveDrawingBuffer: import.meta.env.DEV }}+ frameloop={!awake ? "never" : "always"}+ onPointerMissed={() => select(null)}>+ <OfficeScene layout={layout} grid={grid} walkers={walkers} agents={agents} newcomers={newcomers}+ awake={awake} reduced={reduced} overview={overview} player={{ recipe: profile.recipe, name: playerName }}+ selection={selection} nearby={nearby} /></Canvas></Suspense></RenderBoundary>@@ -101,10 +183,29 @@ export function OfficeStage({ onOpenLedger, onSelectAgent }: OfficeStageProps) {</div><div className="office-hud office-hud-right" data-office-ui>- <button type="button" className="office-button" onClick={() => setReset((v) => v + 1)}>{t("society.office.overview")}</button>+ <button type="button" className="office-button" aria-pressed={follow} onClick={() => useOfficeStore.getState().setFollow(true)}>{t("society.office.me")}</button>+ <button type="button" className="office-button" onClick={() => setOverview((v) => v + 1)}>{t("society.office.overview")}</button>+ <button type="button" className="office-button" onClick={() => select({ kind: "checkpoint", id: "wardrobe" })}>{t("society.office.cp_wardrobe")}</button><button type="button" className="office-button" onClick={onOpenLedger}>{t("society.office.ledger")}</button></div>+ {selection && (+ <div className="office-panel-slot">+ {selection.kind === "agent" && selectedAgent && (+ <AgentPanel agent={selectedAgent} actions={actions} onClose={() => select(null)} />+ )}+ {selection.kind === "checkpoint" && (+ <CheckpointPanel id={selection.id} agents={active} layout={layout} sample={roster.data?.sample ?? false}+ profile={profile} onProfile={updateProfile} actions={actions} onClose={() => select(null)} />+ )}+ </div>+ )}++ {nearbyLabel && !selection && (+ <button type="button" className="office-hud office-prompt" data-office-ui onClick={() => nearby && select(nearby)}>+ <kbd>E</kbd>{nearbyLabel}+ </button>+ )}<p className="office-hud office-help" data-office-ui>{t("society.office.help")}</p></section>);diff --git a/jarvis/ui/web/frontend/src/components/society/office/office.css b/jarvis/ui/web/frontend/src/components/society/office/office.cssindex c3192ad5ee..495e8da14d 100644--- a/jarvis/ui/web/frontend/src/components/society/office/office.css+++ b/jarvis/ui/web/frontend/src/components/society/office/office.css@@ -31,4 +31,13 @@.office-plate[data-state="working"] .office-plate-state i { background:#4ade80; box-shadow:0 0 6px #4ade80; }.office-plate[data-state="waiting"] .office-plate-state i { background:#fbbf24; }.office-plate:focus-visible { outline:2px solid #93c5fd; outline-offset:2px; }+/* Checkpoint label pills: same dark in-world pill as .office-plate, with a gold hexagon badge. */+.office-checkpoint { transform-origin:center center; display:inline-flex; align-items:center; gap:6px; padding:3px 11px 3px 3px; border:1px solid rgb(245 184 61 / .55); border-radius:999px; background:rgb(24 26 32 / .86); color:#fff7ec; cursor:pointer; font-family:inherit; font-size:12px; font-weight:700; white-space:nowrap; user-select:none; box-shadow:0 2px 8px rgb(0 0 0 / .35); transition:background .15s, border-color .15s, box-shadow .15s; }+.office-checkpoint:hover { background:rgb(36 39 48 / .95); border-color:#f5b83d; }+.office-checkpoint-badge { display:inline-flex; align-items:center; justify-content:center; flex:none; width:20px; height:20px; background:#f5b83d; color:#2a1d0a; clip-path:polygon(25% 3%, 75% 3%, 100% 50%, 75% 97%, 25% 97%, 0 50%); }+.office-checkpoint-badge svg { width:12px; height:12px; }+.office-checkpoint-label { max-width:12em; overflow:hidden; text-overflow:ellipsis; }+.office-checkpoint[data-active="true"] { background:rgb(58 42 12 / .94); border-color:#f5b83d; color:#fff; box-shadow:0 0 0 2px rgb(245 184 61 / .35), 0 2px 14px rgb(245 184 61 / .5); }+.office-checkpoint:focus-visible { outline:2px solid #93c5fd; outline-offset:2px; }+@media (prefers-reduced-motion:reduce) { .office-checkpoint { transition:none; } }@media (max-width:600px) { .office-help { display:none; } .office-counts { gap:8px; } }diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeBehavior.test.ts b/jarvis/ui/web/frontend/src/components/society/office/officeBehavior.test.tsnew file mode 100644index 0000000000..4e254a49c9--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/officeBehavior.test.ts@@ -0,0 +1,155 @@+import { describe, expect, it } from "vitest";+import type { AgentRunState } from "../data";+import { allDesks, buildOfficeLayout, seatOf, standOf, type DeskSlot, type OfficeAgentInput } from "./officeLayout";+import { buildNavGrid, isWalkable } from "./officeNav";+import { createRng, planFor, SpotBook, type ActivityKind, type PlanInput } from "./officeBehavior";++const roster: OfficeAgentInput[] = Array.from({ length: 8 }, (_, i) => ({+ agentId: `a${i}`, name: `a${i}`, tier: "specialist", providerLabel: i % 2 ? "Codex" : "Gemini", state: "idle", createdMs: i,+}));+const layout = buildOfficeLayout(roster);+const grid = buildNavGrid(layout);+const deskOf = (id: string): DeskSlot => allDesks(layout).find((d) => d.agentId === id)!;++function input(agentId: string, state: AgentRunState, extra: Partial<PlanInput> = {}): PlanInput {+ return {+ agentId, state, desk: deskOf(agentId), layout, grid, rng: createRng(agentId), book: new SpotBook(),+ previous: null, workingColleagues: [], calledTo: null, ...extra,+ };+}++describe("createRng", () => {+ it("is deterministic per seed and stays in [0, 1)", () => {+ const a = createRng("x"), b = createRng("x"), c = createRng("y");+ const sa = Array.from({ length: 20 }, a);+ expect(Array.from({ length: 20 }, b)).toEqual(sa);+ expect(Array.from({ length: 20 }, c)).not.toEqual(sa);+ expect(sa.every((v) => v >= 0 && v < 1)).toBe(true);+ });+});++describe("SpotBook", () => {+ it("gives a spot to one agent at a time and one spot per agent", () => {+ const book = new SpotBook();+ expect(book.claim("s1", "a")).toBe(true);+ expect(book.claim("s1", "b")).toBe(false);+ expect(book.holder("s1")).toBe("a");+ expect(book.claim("s2", "a")).toBe(true);+ expect(book.isFree("s1")).toBe(true);+ expect(book.holder("s2")).toBe("a");+ book.release("a");+ expect(book.isFree("s2")).toBe(true);+ expect(book.holder("s2")).toBeNull();+ });+});++describe("planFor", () => {+ it("seats a working agent at its desk, typing, until the state changes", () => {+ const plan = planFor(input("a1", "working"));+ const seat = seatOf(deskOf("a1"));+ expect(plan).toMatchObject({ kind: "work", target: { x: seat.x, z: seat.z }, facing: seat.facing, pose: "work", dwellMs: Infinity });+ });++ it("puts a deskless worker at a window", () => {+ const plan = planFor(input("ghost", "working", { desk: null }));+ expect(plan.kind).toBe("work");+ expect(plan.pose).toBe("work");+ expect(plan.spotId).toMatch(/^window-/);+ });++ it("stands a waiting agent beside its chair, waving", () => {+ const plan = planFor(input("a2", "waiting"));+ const stand = standOf(deskOf("a2"));+ expect(plan).toMatchObject({ kind: "wait", target: { x: stand.x, z: stand.z }, pose: "wave", dwellMs: Infinity });+ });++ it("sends paused agents to sleep, then to the couch, then to their desk", () => {+ const book = new SpotBook();+ const sleepSpots = layout.spots.filter((s) => s.pose === "sleep").length;+ const couchSeats = layout.spots.filter((s) => s.kind === "couch" && s.pose !== "sleep").length;+ const plans = roster.map((a) => planFor(input(a.agentId, "paused", { book })));+ expect(plans.every((p) => p.kind === "nap" && p.dwellMs === Infinity)).toBe(true);+ expect(plans.filter((p) => p.pose === "sleep")).toHaveLength(sleepSpots);+ const onCouch = plans.filter((p) => p.spotId && layout.spots.find((s) => s.id === p.spotId)?.kind === "couch" && p.pose === "sit");+ expect(onCouch).toHaveLength(couchSeats);+ const atDesk = plans.filter((p) => p.spotId === null);+ expect(atDesk.length).toBe(roster.length - sleepSpots - couchSeats);+ for (const p of atDesk) expect(p.pose).toBe("sit");+ const ids = plans.map((p) => p.spotId).filter(Boolean);+ expect(new Set(ids).size).toBe(ids.length);+ });++ it("answers a call by walking up to the caller and talking", () => {+ const caller = layout.checkpoints.find((c) => c.id === "create")!;+ const plan = planFor(input("a3", "working", { calledTo: caller }));+ expect(plan.kind).toBe("called");+ expect(plan.pose).toBe("talk");+ expect(plan.dwellMs).toBe(15000);+ expect(isWalkable(grid, plan.target)).toBe(true);+ expect(Math.hypot(plan.target.x - caller.x, plan.target.z - caller.z)).toBeLessThan(2);+ });++ function idleSequence(seed: string, steps: number, colleagues: PlanInput["workingColleagues"] = []): ActivityKind[] {+ const rng = createRng(seed);+ const book = new SpotBook();+ const kinds: ActivityKind[] = [];+ let previous: ActivityKind | null = null;+ for (let i = 0; i < steps; i += 1) {+ const plan = planFor({ ...input("a4", "idle", { rng, book, previous, workingColleagues: colleagues }) });+ kinds.push(plan.kind);+ previous = plan.kind;+ expect(plan.dwellMs).toBeGreaterThanOrEqual(6000);+ expect(plan.dwellMs).toBeLessThanOrEqual(45000);+ }+ return kinds;+ }++ it("gives the same idle life for the same seed and never repeats an activity back to back", () => {+ const colleagues = [{ agentId: "a5", desk: deskOf("a5") }];+ const first = idleSequence("seed-1", 200, colleagues);+ expect(idleSequence("seed-1", 200, colleagues)).toEqual(first);+ expect(idleSequence("seed-2", 200, colleagues)).not.toEqual(first);+ for (let i = 1; i < first.length; i += 1) {+ // A full-spot fallback may land on wander after wander; a chosen activity never repeats.+ if (first[i] !== "wander") expect(first[i]).not.toBe(first[i - 1]);+ }+ expect(new Set(first).size).toBeGreaterThan(6);+ });++ it("visits a working colleague by standing next to their chair", () => {+ const colleague = { agentId: "a5", desk: deskOf("a5") };+ for (let i = 0; i < 200; i += 1) {+ const plan = planFor(input("a4", "idle", { rng: createRng(`visit-${i}`), workingColleagues: [colleague] }));+ if (plan.kind !== "visit") continue;+ const stand = standOf(colleague.desk);+ expect(plan).toMatchObject({ with: "a5", pose: "talk", target: { x: stand.x, z: stand.z } });+ return;+ }+ throw new Error("no visit in 200 seeds");+ });++ it("falls back to wandering when every spot of the chosen kind is taken", () => {+ const book = new SpotBook();+ for (const spot of layout.spots) book.claim(spot.id, `holder-${spot.id}`);+ const office = layout.departments;+ for (let i = 0; i < 50; i += 1) {+ const plan = planFor(input("a6", "idle", { rng: createRng(`full-${i}`), book, desk: null }));+ expect(["wander", "visit"]).toContain(plan.kind);+ expect(plan.spotId).toBeNull();+ if (plan.kind === "wander") {+ expect(plan.facing).toBeNull();+ expect(isWalkable(grid, plan.target)).toBe(true);+ expect(office.some((d) => plan.target.x >= d.minX - 3.3 && plan.target.x <= d.maxX + 3.3)).toBe(true);+ }+ }+ });++ it("releases an agent's spot when it goes back to work", () => {+ const book = new SpotBook();+ const idle = planFor(input("a7", "paused", { book }));+ expect(idle.spotId).not.toBeNull();+ expect(book.holder(idle.spotId!)).toBe("a7");+ planFor(input("a7", "working", { book }));+ expect(book.isFree(idle.spotId!)).toBe(true);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeBehavior.ts b/jarvis/ui/web/frontend/src/components/society/office/officeBehavior.tsnew file mode 100644index 0000000000..833aa73679--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/officeBehavior.ts@@ -0,0 +1,242 @@+/**+ * What each figure on the office map does, decided client-side and+ * deterministically from a seeded random stream.+ *+ * The map is a projection of the roster: it never starts work, and idle life+ * (coffee, couch, wandering) costs zero model calls. Working, waiting and+ * paused agents mirror their real run state; only idle agents pick hobbies.+ */+import type { AgentRunState } from "../data";+import { seatOf, standOf, type DeskSlot, type OfficeLayout, type Point, type Rect, type Spot, type SpotKind } from "./officeLayout";+import { nearestWalkable, randomWalkablePoint, type NavGrid } from "./officeNav";++export type Pose = "sit" | "stand" | "sleep" | "wave" | "talk" | "work";++export type ActivityKind =+ | "work" | "wait" | "desk" | "coffee" | "couch" | "nap" | "window" | "shelf" | "arcade"+ | "cooler" | "beanbag" | "meeting" | "board" | "wander" | "visit" | "called";++export interface Plan {+ kind: ActivityKind;+ target: Point;+ /** Heading to settle into on arrival; null = keep the walking heading. */+ facing: number | null;+ pose: Pose;+ dwellMs: number;+ spotId: string | null;+ /** Agent id being visited. */+ with: string | null;+}++/** Deterministic PRNG (mulberry32) seeded from a string hash. */+export function createRng(seed: string): () => number {+ // FNV-1a over the UTF-16 code units, then one avalanche round.+ let h = 0x811c9dc5;+ for (let i = 0; i < seed.length; i += 1) {+ h ^= seed.charCodeAt(i);+ h = Math.imul(h, 0x01000193);+ }+ h ^= h >>> 16; h = Math.imul(h, 0x85ebca6b); h ^= h >>> 13;+ let state = h >>> 0;+ return () => {+ state = (state + 0x6d2b79f5) >>> 0;+ let t = state;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++/** Exclusive claims on hangout spots: one agent per spot, one spot per agent. */+export class SpotBook {+ private bySpot = new Map<string, string>();+ private byAgent = new Map<string, string>();++ /** Claim a spot for an agent; releases the agent's previous spot. False if another agent holds it. */+ claim(spotId: string, agentId: string): boolean {+ const holder = this.bySpot.get(spotId);+ if (holder !== undefined && holder !== agentId) return false;+ this.release(agentId);+ this.bySpot.set(spotId, agentId);+ this.byAgent.set(agentId, spotId);+ return true;+ }++ release(agentId: string): void {+ const spotId = this.byAgent.get(agentId);+ if (spotId === undefined) return;+ this.byAgent.delete(agentId);+ if (this.bySpot.get(spotId) === agentId) this.bySpot.delete(spotId);+ }++ holder(spotId: string): string | null {+ return this.bySpot.get(spotId) ?? null;+ }++ isFree(spotId: string): boolean {+ return !this.bySpot.has(spotId);+ }+}++export interface PlanInput {+ agentId: string;+ state: AgentRunState;+ desk: DeskSlot | null;+ layout: OfficeLayout;+ grid: NavGrid;+ rng: () => number;+ book: SpotBook;+ previous: ActivityKind | null;+ workingColleagues: { agentId: string; desk: DeskSlot }[];+ calledTo: Point | null;+ /** Where the agent currently is; lets a called agent stop on its own side of the caller. */+ position?: Point | null;+}++/** Idle activities and their relative weights. */+const IDLE_WEIGHTS: readonly [ActivityKind, number][] = [+ ["couch", 22], ["coffee", 18], ["window", 12], ["cooler", 8], ["arcade", 8], ["shelf", 7], ["beanbag", 8],+ ["meeting", 5], ["board", 4], ["wander", 10], ["visit", 6], ["desk", 10],+];++const SPOT_KIND: Partial<Record<ActivityKind, SpotKind>> = {+ couch: "couch", coffee: "coffee", window: "window", cooler: "cooler", arcade: "arcade",+ shelf: "shelf", beanbag: "beanbag", meeting: "meeting", board: "board",+};++const CALLED_DISTANCE = 1.2;+const CALLED_DWELL_MS = 15000;++function between(rng: () => number, minMs: number, maxMs: number): number {+ return Math.round(minMs + rng() * (maxMs - minMs));+}++function pick<T>(rng: () => number, items: readonly T[]): T {+ return items[Math.min(items.length - 1, Math.floor(rng() * items.length))];+}++function poseOfSpot(spot: Spot): Pose {+ return spot.pose;+}++/** Claim a random free spot matching `filter`; null when all are taken. */+function claimSpot(input: PlanInput, filter: (s: Spot) => boolean): Spot | null {+ const free = input.layout.spots.filter((s) => filter(s) && input.book.isFree(s.id));+ if (free.length === 0) return null;+ const spot = pick(input.rng, free);+ input.book.claim(spot.id, input.agentId);+ return spot;+}++/** The open office between the north and south strips: the departments' bounding box. */+function openOffice(layout: OfficeLayout): Rect {+ if (layout.departments.length === 0) return layout.floor;+ return {+ minX: Math.min(...layout.departments.map((d) => d.minX)),+ maxX: Math.max(...layout.departments.map((d) => d.maxX)),+ minZ: Math.min(...layout.departments.map((d) => d.minZ)),+ maxZ: Math.max(...layout.departments.map((d) => d.maxZ)),+ };+}++function wanderPlan(input: PlanInput, pose: Pose, dwellMs: number): Plan {+ const target = randomWalkablePoint(input.grid, input.rng, openOffice(input.layout))+ ?? randomWalkablePoint(input.grid, input.rng)+ ?? input.layout.spawn;+ return { kind: "wander", target, facing: null, pose, dwellMs, spotId: null, with: null };+}++function spotPlan(kind: ActivityKind, spot: Spot, pose: Pose, dwellMs: number): Plan {+ return { kind, target: { x: spot.x, z: spot.z }, facing: spot.facing, pose, dwellMs, spotId: spot.id, with: null };+}++function calledPlan(input: PlanInput, caller: Point): Plan {+ const from = input.position;+ let angle: number;+ if (from && Math.hypot(from.x - caller.x, from.z - caller.z) > 1e-3) angle = Math.atan2(from.x - caller.x, from.z - caller.z);+ else angle = input.rng() * Math.PI * 2;+ const wanted = { x: caller.x + Math.sin(angle) * CALLED_DISTANCE, z: caller.z + Math.cos(angle) * CALLED_DISTANCE };+ const target = nearestWalkable(input.grid, wanted) ?? nearestWalkable(input.grid, caller) ?? wanted;+ const facing = Math.atan2(caller.x - target.x, caller.z - target.z);+ return { kind: "called", target, facing, pose: "talk", dwellMs: CALLED_DWELL_MS, spotId: null, with: null };+}++function idlePlan(input: PlanInput): Plan {+ const { rng, desk, previous } = input;+ const colleagues = input.workingColleagues.filter((c) => c.agentId !== input.agentId);+ const available = IDLE_WEIGHTS.filter(([kind]) => {+ if (kind === "visit") return colleagues.length > 0;+ if (kind === "desk") return desk !== null;+ return true;+ });+ const options = available.length > 1 ? available.filter(([kind]) => kind !== previous) : available;+ const total = options.reduce((sum, [, w]) => sum + w, 0);+ let roll = rng() * total;+ let kind: ActivityKind = options[options.length - 1][0];+ for (const [k, w] of options) {+ if (roll < w) { kind = k; break; }+ roll -= w;+ }++ if (kind === "wander") return wanderPlan(input, "stand", between(rng, 6000, 12000));+ if (kind === "desk" && desk) {+ const seat = seatOf(desk);+ return { kind: "desk", target: { x: seat.x, z: seat.z }, facing: seat.facing, pose: "sit", dwellMs: between(rng, 15000, 30000), spotId: null, with: null };+ }+ if (kind === "visit") {+ const colleague = pick(rng, colleagues);+ const seat = seatOf(colleague.desk);+ const stand = standOf(colleague.desk);+ return {+ kind: "visit", target: { x: stand.x, z: stand.z }, facing: Math.atan2(seat.x - stand.x, seat.z - stand.z),+ pose: "talk", dwellMs: between(rng, 8000, 15000), spotId: null, with: colleague.agentId,+ };+ }+ const spotKind = SPOT_KIND[kind];+ const spot = spotKind ? claimSpot(input, (s) => s.kind === spotKind) : null;+ if (!spot) return wanderPlan(input, "stand", between(rng, 6000, 12000));+ if (kind === "couch") return spotPlan(kind, spot, "sit", between(rng, 20000, 45000));+ return spotPlan(kind, spot, poseOfSpot(spot) === "sleep" ? "sit" : poseOfSpot(spot), between(rng, 8000, 25000));+}++/** Decide the next activity for one agent. Releases its previous spot claim first. */+export function planFor(input: PlanInput): Plan {+ const { agentId, state, desk, book } = input;+ book.release(agentId);++ if (input.calledTo) return calledPlan(input, input.calledTo);++ if (state === "working") {+ if (desk) {+ const seat = seatOf(desk);+ return { kind: "work", target: { x: seat.x, z: seat.z }, facing: seat.facing, pose: "work", dwellMs: Infinity, spotId: null, with: null };+ }+ const spot = claimSpot(input, (s) => s.kind === "window");+ if (spot) return spotPlan("work", spot, "work", Infinity);+ return { ...wanderPlan(input, "work", Infinity), kind: "work" };+ }++ if (state === "waiting") {+ if (desk) {+ const stand = standOf(desk);+ return { kind: "wait", target: { x: stand.x, z: stand.z }, facing: stand.facing, pose: "wave", dwellMs: Infinity, spotId: null, with: null };+ }+ const spot = claimSpot(input, (s) => s.pose === "stand");+ if (spot) return spotPlan("wait", spot, "wave", Infinity);+ return { ...wanderPlan(input, "wave", Infinity), kind: "wait" };+ }++ if (state === "paused") {+ const bed = claimSpot(input, (s) => s.pose === "sleep");+ if (bed) return spotPlan("nap", bed, "sleep", Infinity);+ const couch = claimSpot(input, (s) => s.kind === "couch");+ if (couch) return spotPlan("nap", couch, "sit", Infinity);+ if (desk) {+ const seat = seatOf(desk);+ return { kind: "nap", target: { x: seat.x, z: seat.z }, facing: seat.facing, pose: "sit", dwellMs: Infinity, spotId: null, with: null };+ }+ return { ...wanderPlan(input, "sit", Infinity), kind: "nap" };+ }++ return idlePlan(input);+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeCamera.ts b/jarvis/ui/web/frontend/src/components/society/office/officeCamera.tsindex 9e22d0c0cb..8ab549c69a 100644--- a/jarvis/ui/web/frontend/src/components/society/office/officeCamera.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/officeCamera.ts@@ -20,7 +20,7 @@ export interface Bounds { minX: number; maxX: number; minZ: number; maxZ: numberexport interface CameraPose { position: [number, number, number]; target: [number, number, number] }/** Distance that fits a floor of this footprint into a viewport of this aspect. */-export function fitDistance(bounds: Bounds, aspect: number, fovDeg = CAMERA_FOV): number {+export function fitDistance(bounds: Bounds, aspect: number, fovDeg = CAMERA_FOV, tightness = 0.62): number {const width = bounds.maxX - bounds.minX;const depth = bounds.maxZ - bounds.minZ;// Seen diagonally, the floor's screen width is roughly its diagonal; its@@ -30,7 +30,7 @@ export function fitDistance(bounds: Bounds, aspect: number, fovDeg = CAMERA_FOV)const hHalf = Math.atan(Math.tan(vHalf) * Math.max(0.3, aspect));const needH = (diagonal * 0.5) / Math.tan(hHalf);const needV = (diagonal * Math.sin(HOME_PITCH_RAD) * 0.5 + 1.5) / Math.tan(vHalf);- return Math.min(CAMERA_LIMITS.maxDistance, Math.max(CAMERA_LIMITS.minDistance, Math.max(needH, needV) * 0.62));+ return Math.min(CAMERA_LIMITS.maxDistance, Math.max(CAMERA_LIMITS.minDistance, Math.max(needH, needV) * tightness));}/** Smallest area the home view frames, so a lone agent still shows its neighbourhood. */@@ -51,7 +51,8 @@ export function focusBounds(points: readonly { x: number; z: number }[]): Boundsexport function cameraHome(bounds: Bounds, aspect: number, focus: Bounds | null = null): CameraPose {const frame = focus ?? bounds;const target: [number, number, number] = [(frame.minX + frame.maxX) / 2, 0, (frame.minZ + frame.maxZ) / 2];- const distance = fitDistance(frame, aspect);+ // The whole floor must fit edge to edge; a focus area may crop its padding.+ const distance = fitDistance(frame, aspect, CAMERA_FOV, focus ? 0.62 : 0.9);const horizontal = Math.cos(HOME_PITCH_RAD) * distance;return {target,diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeHud.css b/jarvis/ui/web/frontend/src/components/society/office/officeHud.cssnew file mode 100644index 0000000000..50cd164f82--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/officeHud.css@@ -0,0 +1,46 @@+/* Office HUD panels and prompts: theme tokens only, so light and dark mode both work. */+.office-panel-slot { position:absolute; z-index:35; right:14px; top:60px; width:min(340px, calc(100% - 28px)); max-height:calc(100% - 120px); display:flex; }+.office-panel { display:flex; flex-direction:column; width:100%; min-height:0; overflow:hidden; }+.office-panel-head { display:flex; align-items:flex-start; justify-content:space-between; gap:8px; padding:10px 12px 6px; }+.office-panel-head strong { display:block; font-size:14px; }+.office-panel-head span { display:block; font-size:11px; color:hsl(var(--muted-foreground)); margin-top:2px; }+.office-panel-body { display:flex; flex-direction:column; gap:9px; padding:4px 12px 12px; overflow:auto; font-size:12px; line-height:1.45; }+.office-panel-body p { margin:0; }+.office-panel-status { display:flex; align-items:center; gap:6px; font-weight:600; }+.office-icon-button { border:0; background:none; color:hsl(var(--muted-foreground)); font-size:18px; line-height:1; cursor:pointer; padding:0 4px; border-radius:6px; }+.office-icon-button:hover { color:hsl(var(--foreground)); background:hsl(var(--secondary)); }+.office-actions { display:flex; flex-wrap:wrap; gap:6px; }+.office-action { border:1px solid hsl(var(--border)); border-radius:9px; padding:6px 10px; background:hsl(var(--background)); color:hsl(var(--foreground)); font-size:12px; cursor:pointer; }+.office-action:hover:not(:disabled) { background:hsl(var(--secondary)); }+.office-action[aria-pressed="true"] { background:hsl(var(--secondary)); border-color:hsl(var(--ring)); }+.office-action:disabled { opacity:.5; cursor:not-allowed; }+.office-action-primary { background:hsl(var(--primary)); color:hsl(var(--primary-foreground)); border-color:transparent; font-weight:600; }+.office-action-primary:hover:not(:disabled) { background:hsl(var(--primary) / .88); }+.office-action:focus-visible, .office-mini:focus-visible, .office-chip:focus-visible, .office-link:focus-visible, .office-prompt:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:2px; }+.office-link { border:0; background:none; padding:0; color:hsl(var(--primary)); font-size:12px; cursor:pointer; text-decoration:underline; text-underline-offset:2px; }+.office-list { list-style:none; margin:0; padding:0; display:flex; flex-direction:column; gap:3px; max-height:260px; overflow:auto; }+.office-list li { display:flex; align-items:center; gap:6px; padding:4px 6px; border-radius:7px; }+.office-list li:hover { background:hsl(var(--secondary) / .6); }+.office-list label { display:flex; align-items:center; gap:6px; width:100%; cursor:pointer; }+.office-list-name { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }+.office-mini { border:1px solid hsl(var(--border)); border-radius:6px; padding:2px 7px; background:hsl(var(--background)); color:hsl(var(--foreground)); font-size:11px; cursor:pointer; }+.office-mini:hover { background:hsl(var(--secondary)); }+.office-dot { display:inline-block; flex:none; width:8px; height:8px; border-radius:50%; background:#94a3b8; }+.office-dot[data-state="working"] { background:#22c55e; }+.office-dot[data-state="waiting"] { background:#f59e0b; }+.office-field { display:flex; flex-direction:column; gap:4px; font-size:11px; color:hsl(var(--muted-foreground)); }+.office-field input { border:1px solid hsl(var(--border)); border-radius:8px; padding:6px 8px; background:hsl(var(--background)); color:hsl(var(--foreground)); font-size:12px; }+.office-field input:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:0; }+.office-subhead { margin:4px 0 0; font-size:11px; font-weight:600; color:hsl(var(--muted-foreground)); }+.office-chips { display:flex; flex-wrap:wrap; gap:5px; }+.office-chip { border:1px solid hsl(var(--border)); border-radius:999px; padding:3px 9px; background:hsl(var(--background)); color:hsl(var(--foreground)); font-size:11px; cursor:pointer; }+.office-chip[aria-pressed="true"] { background:hsl(var(--primary)); color:hsl(var(--primary-foreground)); border-color:transparent; }+.office-error { color:hsl(var(--destructive)); }+.office-success { display:flex; flex-wrap:wrap; gap:6px; align-items:center; color:hsl(var(--foreground)); }+.office-note-inline { color:hsl(var(--muted-foreground)); }+.office-prompt { left:50%; bottom:48px; transform:translateX(-50%); display:inline-flex; align-items:center; gap:8px; padding:7px 14px 7px 7px; border-radius:999px; border:1px solid hsl(var(--border)); background:hsl(var(--popover) / .94); color:hsl(var(--popover-foreground)); font-size:13px; font-weight:600; cursor:pointer; box-shadow:0 6px 20px rgb(0 0 0 / .3); }+.office-prompt kbd { display:inline-flex; align-items:center; justify-content:center; width:24px; height:24px; border-radius:7px; background:#f5b83d; color:#1f1300; font-family:inherit; font-size:12px; font-weight:800; }+.office-hud-right .office-button[aria-pressed="true"] { border-color:#f5b83d; }+.office-plate[data-selected] { box-shadow:0 0 0 2px #93c5fd, 0 2px 8px rgb(0 0 0 / .35); }+.office-plate-player { cursor:default; background:rgb(58 44 12 / .9); box-shadow:0 0 0 1.5px #f5b83d, 0 2px 8px rgb(0 0 0 / .35); }+@media (max-width:600px) { .office-panel-slot { top:auto; bottom:12px; max-height:55%; } .office-hud-right { flex-wrap:wrap; justify-content:flex-end; max-width:60%; } }diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeLayout.ts b/jarvis/ui/web/frontend/src/components/society/office/officeLayout.tsindex e0dfded6a6..553cd70f3a 100644--- a/jarvis/ui/web/frontend/src/components/society/office/officeLayout.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/officeLayout.ts@@ -1,9 +1,15 @@/**- * The office floor as data: departments, desk slots and who sits where.+ * The office floor as data: rooms, departments, desks, furniture, hangout+ * spots, checkpoints and the obstacles that navigation walks around.*- * Pure and deterministic — the same roster always produces the same seating,- * so an agent never "moves desks" on a refetch. Units are metres, +x east,- * +z south, origin at the floor centre. The camera looks from the south-east.+ * Pure and deterministic — the same roster always produces the same floor and+ * seating, so an agent never "moves desks" on a refetch. Units are metres,+ * +x east, +z south, origin at the floor centre. The camera looks from the+ * south-east, so tall rooms stand in the north and the lobby lies in front.+ *+ * ┌──────────── north strip: Lead office · Team room · Wardrobe ───────────┐+ * │ departments (open office, 2 columns) │+ * └──── south strip: Reception + lobby (Agent board) · Break room ─────────┘*/import type { AgentRunState, AgentTier } from "../data";@@ -16,6 +22,9 @@ export interface OfficeAgentInput {createdMs: number;}+export interface Rect { minX: number; maxX: number; minZ: number; maxZ: number }+export interface Point { x: number; z: number }+export type Facing = "north" | "south";export interface DeskSlot {@@ -28,34 +37,96 @@ export interface DeskSlot {agentId: string | null;}-export interface Department {+export interface Department extends Rect {id: string;/** Provider family shown on the sign; "" for a spare open-space department. */label: string;- /** Floor rectangle of the department's carpet. */- minX: number;- maxX: number;- minZ: number;- maxZ: number;desks: DeskSlot[];/** Carpet tint index into the palette's department colours. */tint: number;}-export interface LeadOffice {- minX: number;- maxX: number;- minZ: number;- maxZ: number;- desks: DeskSlot[];+export type RoomKind = "lead" | "team" | "wardrobe" | "reception" | "break";++export interface Door { side: "north" | "south" | "east" | "west"; /** Centre of the gap along the wall. */ at: number; width: number }++export interface Room extends Rect {+ id: RoomKind;+ kind: RoomKind;+ /** Walled rooms get glass walls on every side except their doors; open rooms have none. */+ walled: boolean;+ doors: Door[];+}++export interface WallSegment { x1: number; z1: number; x2: number; z2: number; room: RoomKind }++export type CheckpointKind = "create" | "manage" | "team" | "wardrobe" | "lead" | "break";++/** A place the person can walk to (or click from afar) to act. */+export interface Checkpoint extends Point { id: CheckpointKind; room: RoomKind; /** Walk-in radius in metres. */ radius: number }++export type FurnitureKind =+ | "meetingTable" | "teamBoard" | "receptionDesk" | "kiosk" | "lockers" | "mirror"+ | "coffeeBar" | "waterCooler" | "couch" | "coffeeTable" | "arcade" | "beanbag"+ | "bookshelf" | "plant" | "rug" | "elevator";++/**+ * Footprint (x-extent × z-extent before rotation) and height of each piece.+ * The renderer MUST build every prop inside this box: navigation reads the+ * same numbers, so a prop larger than its footprint makes figures clip into it.+ */+export const FURNITURE_SIZE: Record<FurnitureKind, { w: number; d: number; h: number; solid: boolean }> = {+ meetingTable: { w: 3.6, d: 1.6, h: 0.76, solid: true },+ teamBoard: { w: 2.6, d: 0.2, h: 1.9, solid: true },+ receptionDesk: { w: 2.8, d: 0.9, h: 1.1, solid: true },+ kiosk: { w: 1.0, d: 0.5, h: 1.8, solid: true },+ lockers: { w: 2.4, d: 0.5, h: 1.9, solid: true },+ mirror: { w: 0.9, d: 0.12, h: 1.9, solid: true },+ coffeeBar: { w: 2.4, d: 0.7, h: 1.05, solid: true },+ waterCooler: { w: 0.45, d: 0.45, h: 1.3, solid: true },+ couch: { w: 2.2, d: 0.9, h: 0.85, solid: true },+ coffeeTable: { w: 1.1, d: 1.1, h: 0.4, solid: true },+ arcade: { w: 0.8, d: 0.8, h: 1.8, solid: true },+ beanbag: { w: 0.9, d: 0.9, h: 0.6, solid: true },+ bookshelf: { w: 1.8, d: 0.36, h: 1.4, solid: true },+ plant: { w: 0.6, d: 0.6, h: 1.3, solid: true },+ rug: { w: 1, d: 1, h: 0.02, solid: false },+ elevator: { w: 2.2, d: 0.4, h: 2.4, solid: true },+};++export interface Furniture extends Point {+ id: string;+ kind: FurnitureKind;+ /** Rotation about +y. 0 = the prop's front faces +z (south, towards the camera). */+ rotationY: number;+ room: RoomKind | "floor";+ /** Only rugs are sized per instance (w × d); everything else uses FURNITURE_SIZE. */+ size?: { w: number; d: number };}+export type SpotKind = "couch" | "coffee" | "cooler" | "window" | "shelf" | "arcade" | "meeting" | "beanbag" | "board";+export type SpotPose = "sit" | "stand" | "sleep";++/** Where an idle agent (or the person) can hang out. `facing` is the figure's rotation about +y. */+export interface Spot extends Point { id: string; kind: SpotKind; pose: SpotPose; facing: number; room: RoomKind | "floor" }+export interface OfficeLayout {departments: Department[];- lead: LeadOffice;- lounge: { minX: number; maxX: number; minZ: number; maxZ: number };- /** The whole walkable floor, railing included. */- bounds: { minX: number; maxX: number; minZ: number; maxZ: number };+ /** Lead desks live in the lead office. */+ lead: Rect & { desks: DeskSlot[] };+ rooms: Room[];+ walls: WallSegment[];+ furniture: Furniture[];+ spots: Spot[];+ checkpoints: Checkpoint[];+ /** Solid footprints (desks, walls, furniture), un-inflated. Navigation inflates them by the walker radius. */+ obstacles: Rect[];+ /** Where the person's character starts. */+ spawn: Point;+ /** The walkable floor inside the railing. */+ floor: Rect;+ /** The whole slab, railing included. */+ bounds: Rect;}/** Desk pitch along a row and the depth of one bench (two rows back to back plus chairs). */@@ -63,6 +134,9 @@ export const DESK_PITCH_X = 1.7;export const BENCH_DEPTH_Z = 4.2;/** Half the gap between the two monitors of a back-to-back pair. */export const DESK_HALF_GAP = 0.45;+export const DESK_SIZE = { w: 1.5, d: 0.8 } as const;+/** Chair centre behind a desk, along the agent's back direction. */+export const SEAT_OFFSET = 0.72;export const DESKS_PER_ROW = 4;const SEATS_PER_BENCH = DESKS_PER_ROW * 2;const MIN_BENCHES = 1;@@ -72,13 +146,14 @@ const DEPT_HEADER_Z = 1.8;const DEPT_FOOTER_Z = 0.8;const AISLE = 3.2;const EDGE = 1.6;-const LOUNGE_DEPTH = 6;-const LEAD_DEPTH = 6;+const NORTH_DEPTH = 7;+const SOUTH_DEPTH = 8;const COLUMNS = 2;-/** The floor always shows at least this many departments; spare ones are open space with free desks. */-export const MIN_DEPARTMENTS = 4;+const WALL_THICKNESS = 0.12;/** More departments than this fold into the last one — the floor stays one screen. */export const MAX_DEPARTMENTS = 6;+/** The floor always shows at least this many departments; spare ones are open space with free desks. */+export const MIN_DEPARTMENTS = 4;export const MAX_SEATED = MAX_DEPARTMENTS * MAX_BENCHES * SEATS_PER_BENCH;/** The department an agent works in: its provider family, or Jarvis' own brain. */@@ -115,9 +190,7 @@ function benchCount(members: number): number {return Math.min(MAX_BENCHES, Math.max(MIN_BENCHES, Math.ceil(members / SEATS_PER_BENCH)));}-function deptWidth(): number {- return DESKS_PER_ROW * DESK_PITCH_X + DEPT_MARGIN_X * 2;-}+const DEPT_WIDTH = DESKS_PER_ROW * DESK_PITCH_X + DEPT_MARGIN_X * 2;function deptDepth(benches: number): number {return DEPT_HEADER_Z + benches * BENCH_DEPTH_Z + DEPT_FOOTER_Z;@@ -142,63 +215,227 @@ function layoutDesks(deptId: string, minX: number, minZ: number, benches: numberreturn desks;}-/** Build the floor for a roster. Seating is stable for an unchanged roster. */+/** The chair a desk's agent sits on, and the figure's heading while seated. */+export function seatOf(desk: Pick<DeskSlot, "x" | "z" | "facing">): Point & { facing: number } {+ return desk.facing === "north"+ ? { x: desk.x, z: desk.z + SEAT_OFFSET, facing: Math.PI }+ : { x: desk.x, z: desk.z - SEAT_OFFSET, facing: 0 };+}++/** Where an agent stands beside its chair (e.g. waiting for the person). */+export function standOf(desk: Pick<DeskSlot, "x" | "z" | "facing">): Point & { facing: number } {+ const seat = seatOf(desk);+ return { x: seat.x + 0.55, z: seat.z, facing: seat.facing };+}++/** Axis-aligned footprint of a rotated piece (rotations are multiples of 90°). */+export function footprint(item: Pick<Furniture, "x" | "z" | "kind" | "rotationY" | "size">): Rect {+ const base = item.size ?? FURNITURE_SIZE[item.kind];+ const quarter = Math.round(item.rotationY / (Math.PI / 2)) % 2 !== 0;+ const w = quarter ? base.d : base.w;+ const d = quarter ? base.w : base.d;+ return { minX: item.x - w / 2, maxX: item.x + w / 2, minZ: item.z - d / 2, maxZ: item.z + d / 2 };+}++function wallsOf(room: Room): WallSegment[] {+ if (!room.walled) return [];+ const sides: { side: Door["side"]; a: Point; b: Point }[] = [+ { side: "north", a: { x: room.minX, z: room.minZ }, b: { x: room.maxX, z: room.minZ } },+ { side: "south", a: { x: room.minX, z: room.maxZ }, b: { x: room.maxX, z: room.maxZ } },+ { side: "west", a: { x: room.minX, z: room.minZ }, b: { x: room.minX, z: room.maxZ } },+ { side: "east", a: { x: room.maxX, z: room.minZ }, b: { x: room.maxX, z: room.maxZ } },+ ];+ const out: WallSegment[] = [];+ for (const { side, a, b } of sides) {+ const horizontal = side === "north" || side === "south";+ const start = horizontal ? a.x : a.z;+ const end = horizontal ? b.x : b.z;+ const gaps = room.doors.filter((d) => d.side === side).map((d) => [d.at - d.width / 2, d.at + d.width / 2] as const)+ .sort((p, q) => p[0] - q[0]);+ let cursor = start;+ const push = (from: number, to: number) => {+ if (to - from < 0.05) return;+ out.push(horizontal+ ? { x1: from, z1: a.z, x2: to, z2: a.z, room: room.kind }+ : { x1: a.x, z1: from, x2: a.x, z2: to, room: room.kind });+ };+ for (const [g0, g1] of gaps) { push(cursor, Math.max(cursor, g0)); cursor = Math.max(cursor, g1); }+ push(cursor, end);+ }+ return out;+}++function wallRect(w: WallSegment): Rect {+ const t = WALL_THICKNESS / 2;+ return { minX: Math.min(w.x1, w.x2) - t, maxX: Math.max(w.x1, w.x2) + t, minZ: Math.min(w.z1, w.z2) - t, maxZ: Math.max(w.z1, w.z2) + t };+}++/** Build the floor for a roster. Seating and the whole floor plan are stable for an unchanged roster. */export function buildOfficeLayout(agents: readonly OfficeAgentInput[]): OfficeLayout {const groups: { label: string; members: OfficeAgentInput[] }[] = groupDepartments(agents);if (groups.length === 1 && groups[0].members.length === 0) groups.length = 0;while (groups.length < MIN_DEPARTMENTS) groups.push({ label: "", members: [] });- const width = deptWidth();- const rows = Math.ceil(groups.length / COLUMNS);- const columns = Math.min(COLUMNS, groups.length);- const totalWidth = columns * width + (columns - 1) * AISLE;- const minX = -Math.max(totalWidth, 2 * width + AISLE) / 2;- // Row depth is the deepest department in that row, so rows line up.+ const floorWidth = COLUMNS * DEPT_WIDTH + (COLUMNS - 1) * AISLE;+ const minX = -floorWidth / 2;+ const maxX = floorWidth / 2;+ const rows = Math.ceil(groups.length / COLUMNS);const rowDepths: number[] = [];for (let row = 0; row < rows; row += 1) {const inRow = groups.slice(row * COLUMNS, row * COLUMNS + COLUMNS);rowDepths.push(Math.max(...inRow.map((g) => deptDepth(benchCount(g.members.length)))));}- const floorDepth = LEAD_DEPTH + AISLE + rowDepths.reduce((s, d) => s + d, 0) + (rows - 1) * AISLE + AISLE + LOUNGE_DEPTH;+ const floorDepth = NORTH_DEPTH + AISLE + rowDepths.reduce((s, d) => s + d, 0) + (rows - 1) * AISLE + AISLE + SOUTH_DEPTH;const topZ = -floorDepth / 2;- const floorWidth = Math.max(totalWidth, 2 * width + AISLE);+ const bottomZ = floorDepth / 2;- const leadAgents = agents.filter((a) => a.tier === "lead").sort(byArrival).slice(0, 2);- const leadWidth = width;- const lead: LeadOffice = {- minX, maxX: minX + leadWidth, minZ: topZ, maxZ: topZ + LEAD_DEPTH,- desks: [0, 1].map((i) => ({- id: `lead:${i}`,- x: minX + leadWidth * (i === 0 ? 0.35 : 0.72),- z: topZ + LEAD_DEPTH * 0.45,- facing: "south" as const,- agentId: leadAgents[i]?.agentId ?? null,- })),- };+ // North strip: lead office · team room · wardrobe, each with a door facing the office.+ const leadW = 8.2, teamW = 8.4;+ const northMaxZ = topZ + NORTH_DEPTH;+ const leadRoom: Room = { id: "lead", kind: "lead", walled: true, minX, maxX: minX + leadW, minZ: topZ, maxZ: northMaxZ,+ doors: [{ side: "south", at: minX + leadW / 2, width: 1.6 }] };+ const teamRoom: Room = { id: "team", kind: "team", walled: true, minX: leadRoom.maxX, maxX: leadRoom.maxX + teamW, minZ: topZ, maxZ: northMaxZ,+ doors: [{ side: "south", at: leadRoom.maxX + teamW / 2, width: 1.8 }] };+ const wardrobeRoom: Room = { id: "wardrobe", kind: "wardrobe", walled: true, minX: teamRoom.maxX, maxX, minZ: topZ, maxZ: northMaxZ,+ doors: [{ side: "south", at: (teamRoom.maxX + maxX) / 2, width: 1.5 }] };+ // Departments between the strips.const departments: Department[] = [];- let z = topZ + LEAD_DEPTH + AISLE;+ let z = northMaxZ + AISLE;for (let row = 0; row < rows; row += 1) {for (let col = 0; col < COLUMNS; col += 1) {const index = row * COLUMNS + col;const group = groups[index];if (!group) continue;const benches = benchCount(group.members.length);- const dMinX = minX + col * (width + AISLE);+ const dMinX = minX + col * (DEPT_WIDTH + AISLE);const id = `dept-${index}`;departments.push({id, label: group.label, tint: index,- minX: dMinX, maxX: dMinX + width, minZ: z, maxZ: z + deptDepth(benches),+ minX: dMinX, maxX: dMinX + DEPT_WIDTH, minZ: z, maxZ: z + deptDepth(benches),desks: layoutDesks(id, dMinX, z, benches, group.members.slice(0, benches * SEATS_PER_BENCH)),});}z += rowDepths[row] + AISLE;}- const lounge = { minX, maxX: minX + floorWidth, minZ: z, maxZ: z + LOUNGE_DEPTH };+ // South strip: an open reception/lobby in the west, a walled break room in the east.+ const southMinZ = bottomZ - SOUTH_DEPTH;+ const breakW = 10.5;+ const receptionRoom: Room = { id: "reception", kind: "reception", walled: false, minX, maxX: maxX - breakW, minZ: southMinZ, maxZ: bottomZ, doors: [] };+ const breakRoom: Room = { id: "break", kind: "break", walled: true, minX: maxX - breakW, maxX, minZ: southMinZ, maxZ: bottomZ,+ doors: [{ side: "north", at: maxX - breakW / 2, width: 2.2 }, { side: "west", at: southMinZ + SOUTH_DEPTH / 2, width: 2 }] };+ const rooms = [leadRoom, teamRoom, wardrobeRoom, receptionRoom, breakRoom];++ // Lead desks face south, towards the door and the office.+ const leadAgents = agents.filter((a) => a.tier === "lead").sort(byArrival).slice(0, 2);+ const lead = {+ minX: leadRoom.minX, maxX: leadRoom.maxX, minZ: leadRoom.minZ, maxZ: leadRoom.maxZ,+ desks: [0, 1].map((i): DeskSlot => ({+ id: `lead:${i}`, x: minX + leadW * (i === 0 ? 0.3 : 0.7), z: topZ + 2.6, facing: "south", agentId: leadAgents[i]?.agentId ?? null,+ })),+ };++ const tcx = (teamRoom.minX + teamRoom.maxX) / 2, tcz = (teamRoom.minZ + teamRoom.maxZ) / 2;+ const wcx = (wardrobeRoom.minX + wardrobeRoom.maxX) / 2;+ const bx0 = breakRoom.minX, bz0 = breakRoom.minZ;+ const rx0 = receptionRoom.minX;+ const furniture: Furniture[] = [+ // Lead office.+ { id: "lead-shelf", kind: "bookshelf", x: leadRoom.maxX - 1.3, z: topZ + 0.35, rotationY: 0, room: "lead" },+ { id: "lead-plant", kind: "plant", x: minX + 0.6, z: northMaxZ - 0.6, rotationY: 0, room: "lead" },+ // Team room: one long table, a board on the north wall.+ { id: "team-table", kind: "meetingTable", x: tcx, z: tcz + 0.4, rotationY: 0, room: "team" },+ { id: "team-board", kind: "teamBoard", x: tcx, z: topZ + 0.25, rotationY: 0, room: "team" },+ { id: "team-plant", kind: "plant", x: teamRoom.maxX - 0.6, z: northMaxZ - 0.6, rotationY: 0, room: "team" },+ // Wardrobe: lockers and a mirror.+ { id: "wardrobe-lockers", kind: "lockers", x: wcx - 0.2, z: topZ + 0.4, rotationY: 0, room: "wardrobe" },+ { id: "wardrobe-mirror", kind: "mirror", x: wardrobeRoom.maxX - 0.25, z: tcz, rotationY: -Math.PI / 2, room: "wardrobe" },+ // Reception and lobby.+ { id: "elevator", kind: "elevator", x: rx0 + 0.25, z: bottomZ - 2.6, rotationY: Math.PI / 2, room: "reception" },+ { id: "reception-desk", kind: "receptionDesk", x: rx0 + 3.2, z: southMinZ + 2.6, rotationY: 0, room: "reception" },+ { id: "kiosk", kind: "kiosk", x: receptionRoom.maxX - 2.2, z: southMinZ + 2.2, rotationY: 0, room: "reception" },+ { id: "lobby-plant-a", kind: "plant", x: rx0 + 0.6, z: southMinZ + 0.8, rotationY: 0, room: "reception" },+ { id: "lobby-plant-b", kind: "plant", x: receptionRoom.maxX - 0.8, z: bottomZ - 0.7, rotationY: 0, room: "reception" },+ // Break room: couches around a table, coffee bar, water cooler, arcade, beanbags.+ { id: "break-rug", kind: "rug", x: bx0 + 3.6, z: bz0 + 4.6, rotationY: 0, room: "break", size: { w: 5.6, d: 4.2 } },+ { id: "break-couch-a", kind: "couch", x: bx0 + 3.6, z: bz0 + 6.3, rotationY: Math.PI, room: "break" },+ { id: "break-couch-b", kind: "couch", x: bx0 + 1.75, z: bz0 + 4.6, rotationY: Math.PI / 2, room: "break" },+ { id: "break-table", kind: "coffeeTable", x: bx0 + 3.6, z: bz0 + 4.6, rotationY: 0, room: "break" },+ { id: "coffee-bar", kind: "coffeeBar", x: bx0 + 7.9, z: bz0 + 0.5, rotationY: 0, room: "break" },+ { id: "water-cooler", kind: "waterCooler", x: breakRoom.maxX - 0.45, z: bz0 + 2.6, rotationY: -Math.PI / 2, room: "break" },+ { id: "arcade", kind: "arcade", x: breakRoom.maxX - 0.6, z: bottomZ - 0.7, rotationY: -Math.PI / 2, room: "break" },+ { id: "beanbag-a", kind: "beanbag", x: bx0 + 7.2, z: bz0 + 5.4, rotationY: 0, room: "break" },+ { id: "beanbag-b", kind: "beanbag", x: bx0 + 8.4, z: bz0 + 6.3, rotationY: 0, room: "break" },+ { id: "break-shelf", kind: "bookshelf", x: bx0 + 2.2, z: bz0 + 0.3, rotationY: 0, room: "break" },+ { id: "break-plant", kind: "plant", x: bx0 + 0.6, z: bottomZ - 0.6, rotationY: 0, room: "break" },+ ];+ for (const dept of departments) {+ furniture.push({ id: `${dept.id}-plant-w`, kind: "plant", x: dept.minX + 0.45, z: dept.maxZ - 0.45, rotationY: 0, room: "floor" });+ furniture.push({ id: `${dept.id}-plant-e`, kind: "plant", x: dept.maxX - 0.45, z: dept.maxZ - 0.45, rotationY: 0, room: "floor" });+ }++ const table = furniture.find((f) => f.id === "team-table")!;+ const spots: Spot[] = [+ // Couch seats: couch A faces north (rotated π), couch B faces east.+ { id: "couch-a1", kind: "couch", pose: "sit", x: bx0 + 3.0, z: bz0 + 6.15, facing: Math.PI, room: "break" },+ { id: "couch-a2", kind: "couch", pose: "sit", x: bx0 + 4.2, z: bz0 + 6.15, facing: Math.PI, room: "break" },+ { id: "couch-b1", kind: "couch", pose: "sit", x: bx0 + 1.9, z: bz0 + 4.0, facing: Math.PI / 2, room: "break" },+ { id: "couch-b2", kind: "couch", pose: "sleep", x: bx0 + 1.9, z: bz0 + 5.2, facing: Math.PI / 2, room: "break" },+ { id: "coffee-1", kind: "coffee", pose: "stand", x: bx0 + 7.3, z: bz0 + 1.4, facing: Math.PI, room: "break" },+ { id: "coffee-2", kind: "coffee", pose: "stand", x: bx0 + 8.5, z: bz0 + 1.4, facing: Math.PI, room: "break" },+ { id: "cooler", kind: "cooler", pose: "stand", x: breakRoom.maxX - 1.2, z: bz0 + 2.6, facing: Math.PI / 2, room: "break" },+ { id: "arcade", kind: "arcade", pose: "stand", x: breakRoom.maxX - 1.45, z: bottomZ - 0.7, facing: Math.PI / 2, room: "break" },+ { id: "beanbag-a", kind: "beanbag", pose: "sit", x: bx0 + 7.2, z: bz0 + 5.4, facing: Math.PI * 1.25, room: "break" },+ { id: "beanbag-b", kind: "beanbag", pose: "sit", x: bx0 + 8.4, z: bz0 + 6.3, facing: Math.PI * 1.25, room: "break" },+ { id: "shelf-break", kind: "shelf", pose: "stand", x: bx0 + 2.2, z: bz0 + 1.1, facing: Math.PI, room: "break" },+ { id: "shelf-lead", kind: "shelf", pose: "stand", x: leadRoom.maxX - 1.3, z: topZ + 1.2, facing: Math.PI, room: "lead" },+ { id: "board", kind: "board", pose: "stand", x: tcx - 0.6, z: topZ + 1.2, facing: Math.PI, room: "team" },+ ];+ // Meeting chairs: three per long side of the team table.+ for (let i = 0; i < 3; i += 1) {+ const x = table.x - 1.1 + i * 1.1;+ spots.push({ id: `meeting-n${i}`, kind: "meeting", pose: "sit", x, z: table.z - 1.25, facing: 0, room: "team" });+ spots.push({ id: `meeting-s${i}`, kind: "meeting", pose: "sit", x, z: table.z + 1.25, facing: Math.PI, room: "team" });+ }+ // Window spots along the east and west railing, looking out at the stars.+ for (const dept of departments) {+ const side = dept.minX <= minX + 0.01 ? "west" : dept.maxX >= maxX - 0.01 ? "east" : null;+ if (!side) continue;+ const zc = (dept.minZ + dept.maxZ) / 2;+ spots.push({+ id: `window-${dept.id}`, kind: "window", pose: "stand", room: "floor",+ x: side === "west" ? minX - EDGE + 0.9 : maxX + EDGE - 0.9, z: zc, facing: side === "west" ? -Math.PI / 2 : Math.PI / 2,+ });+ }++ const reception = furniture.find((f) => f.id === "reception-desk")!;+ const kiosk = furniture.find((f) => f.id === "kiosk")!;+ const checkpoints: Checkpoint[] = [+ { id: "create", room: "reception", x: reception.x, z: reception.z + 1.7, radius: 1.2 },+ { id: "manage", room: "reception", x: kiosk.x, z: kiosk.z + 1.4, radius: 1.1 },+ { id: "team", room: "team", x: tcx + 2.2, z: northMaxZ - 1.05, radius: 0.95 },+ { id: "wardrobe", room: "wardrobe", x: wcx, z: tcz + 0.8, radius: 1.5 },+ { id: "lead", room: "lead", x: minX + leadW / 2, z: northMaxZ - 1.5, radius: 1.3 },+ { id: "break", room: "break", x: bx0 + 5.6, z: bz0 + 2.6, radius: 1.8 },+ ];++ const walls = rooms.flatMap(wallsOf);+ const desks = [...lead.desks, ...departments.flatMap((d) => d.desks)];+ const obstacles: Rect[] = [+ ...walls.map(wallRect),+ ...desks.map((d) => ({ minX: d.x - DESK_SIZE.w / 2, maxX: d.x + DESK_SIZE.w / 2, minZ: d.z - DESK_SIZE.d / 2, maxZ: d.z + DESK_SIZE.d / 2 })),+ // Department sign walls along each department's north edge.+ ...departments.map((d) => ({ minX: d.minX + 0.2, maxX: d.maxX - 0.2, minZ: d.minZ + 0.02, maxZ: d.minZ + 0.2 })),+ ...furniture.filter((f) => FURNITURE_SIZE[f.kind].solid).map(footprint),+ ];++ const floor = { minX: minX - EDGE + 0.35, maxX: maxX + EDGE - 0.35, minZ: topZ - EDGE + 0.35, maxZ: bottomZ + EDGE - 0.35 };return {- departments, lead, lounge,- bounds: { minX: minX - EDGE, maxX: minX + floorWidth + EDGE, minZ: topZ - EDGE, maxZ: lounge.maxZ + EDGE },+ departments, lead, rooms, walls, furniture, spots, checkpoints, obstacles,+ spawn: { x: rx0 + 1.4, z: bottomZ - 2.6 },+ floor,+ bounds: { minX: minX - EDGE, maxX: maxX + EDGE, minZ: topZ - EDGE, maxZ: bottomZ + EDGE },};}@@ -207,6 +444,10 @@ export function allDesks(layout: OfficeLayout): DeskSlot[] {return [...layout.lead.desks, ...layout.departments.flatMap((d) => d.desks)];}+export function roomAt(layout: OfficeLayout, p: Point): Room | null {+ return layout.rooms.find((r) => p.x >= r.minX && p.x <= r.maxX && p.z >= r.minZ && p.z <= r.maxZ) ?? null;+}+export interface StatusCounts { working: number; idle: number; waiting: number; paused: number }export function countStates(agents: readonly Pick<OfficeAgentInput, "state">[]): StatusCounts {diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeMotion.test.ts b/jarvis/ui/web/frontend/src/components/society/office/officeMotion.test.tsnew file mode 100644index 0000000000..fc2346563a--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/officeMotion.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from "vitest";+import { stepMover, turnToward, WALK_SPEED, wrapAngle, type Mover } from "./officeMotion";++describe("office motion", () => {+ it("turns the short way and clamps the step", () => {+ expect(turnToward(0, 1, 0.5)).toBeCloseTo(0.5);+ expect(turnToward(0, 1, 2)).toBeCloseTo(1);+ // From just below +π to just above -π is a tiny step across the seam.+ expect(turnToward(3.1, -3.1, 0.2)).toBeCloseTo(wrapAngle(-3.1));+ expect(turnToward(3.0, -3.0, 0.1)).toBeCloseTo(3.1);+ });++ it("walks a path to its end at the given speed and faces the travel direction", () => {+ const m: Mover = { x: 0, z: 0, heading: 0, path: [{ x: 2, z: 0 }, { x: 2, z: 3 }] };+ let total = 0;+ let arrived = false;+ let ticks = 0;+ let headingOnFirstLeg = NaN;+ while (!arrived && ticks < 1000) {+ const res = stepMover(m, WALK_SPEED, 1 / 60);+ total += res.moved;+ arrived = res.arrived;+ ticks += 1;+ if (m.x > 1 && m.x < 1.9 && m.z === 0) headingOnFirstLeg = m.heading;+ }+ expect(arrived).toBe(true);+ expect(m.x).toBeCloseTo(2);+ expect(m.z).toBeCloseTo(3);+ expect(total).toBeCloseTo(5);+ expect(ticks).toBeCloseTo(Math.ceil(5 / WALK_SPEED * 60), -1);+ // East = +x = heading π/2; south = +z = heading 0.+ expect(headingOnFirstLeg).toBeCloseTo(Math.PI / 2);+ expect(m.heading).toBeCloseTo(0);+ expect(m.path).toHaveLength(0);+ });++ it("does nothing without a path", () => {+ const m: Mover = { x: 1, z: 1, heading: 0.3, path: [] };+ expect(stepMover(m, WALK_SPEED, 0.1)).toEqual({ moved: 0, arrived: true });+ expect(m).toEqual({ x: 1, z: 1, heading: 0.3, path: [] });+ });++ it("consumes several waypoints in one large step", () => {+ const m: Mover = { x: 0, z: 0, heading: 0, path: [{ x: 0, z: 1 }, { x: 0, z: 2 }, { x: 0, z: 3 }] };+ const res = stepMover(m, 1, 2.5);+ expect(res.moved).toBeCloseTo(2.5);+ expect(res.arrived).toBe(false);+ expect(m.path).toHaveLength(1);+ expect(m.z).toBeCloseTo(2.5);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeMotion.ts b/jarvis/ui/web/frontend/src/components/society/office/officeMotion.tsnew file mode 100644index 0000000000..f3bbcf151c--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/officeMotion.ts@@ -0,0 +1,65 @@+/**+ * Walking a figure along a waypoint path at a fixed speed, turning smoothly+ * towards the direction of travel. Pure: callers own the Mover and the clock.+ */+import type { Point } from "./officeLayout";++/** Metres per second. */+export const WALK_SPEED = 1.35;+export const RUN_SPEED = 3.2;+/** Maximum turn rate in radians per second. */+export const TURN_RATE = 10;++export interface Mover {+ x: number;+ z: number;+ /** Rotation about +y; 0 = the figure faces +z. */+ heading: number;+ /** Remaining waypoints; the first one is the next target. */+ path: Point[];+}++const TAU = Math.PI * 2;++/** Wrap an angle into (-π, π]. */+export function wrapAngle(angle: number): number {+ let a = angle % TAU;+ if (a <= -Math.PI) a += TAU;+ else if (a > Math.PI) a -= TAU;+ return a;+}++/** Turn `current` towards `target` along the shorter way by at most `maxStep` radians. */+export function turnToward(current: number, target: number, maxStep: number): number {+ const diff = wrapAngle(target - current);+ if (Math.abs(diff) <= maxStep) return wrapAngle(target);+ return wrapAngle(current + Math.sign(diff) * maxStep);+}++/**+ * Advance the mover by speed × dt metres along its path, consuming reached+ * waypoints. Mutates `m`. `arrived` is true once the path is empty.+ */+export function stepMover(m: Mover, speed: number, dt: number): { moved: number; arrived: boolean } {+ let budget = Math.max(0, speed * dt);+ let moved = 0;+ let dirX = 0, dirZ = 0;+ while (m.path.length > 0 && budget > 0) {+ const next = m.path[0];+ const dx = next.x - m.x, dz = next.z - m.z;+ const dist = Math.hypot(dx, dz);+ if (dist <= budget) {+ m.x = next.x; m.z = next.z;+ budget -= dist; moved += dist;+ m.path.shift();+ } else {+ m.x += (dx / dist) * budget; m.z += (dz / dist) * budget;+ moved += budget; budget = 0;+ }+ if (dist > 1e-9) { dirX = dx; dirZ = dz; }+ }+ // Drop waypoints that coincide with the current position.+ while (m.path.length > 0 && Math.hypot(m.path[0].x - m.x, m.path[0].z - m.z) < 1e-9) m.path.shift();+ if (dirX !== 0 || dirZ !== 0) m.heading = turnToward(m.heading, Math.atan2(dirX, dirZ), TURN_RATE * dt);+ return { moved, arrived: m.path.length === 0 };+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeNav.test.ts b/jarvis/ui/web/frontend/src/components/society/office/officeNav.test.tsnew file mode 100644index 0000000000..99d8f57ab7--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/officeNav.test.ts@@ -0,0 +1,134 @@+import { describe, expect, it } from "vitest";+import { allDesks, buildOfficeLayout, seatOf, standOf, type OfficeAgentInput, type OfficeLayout, type Point } from "./officeLayout";+import { buildNavGrid, findPath, hasLineOfSight, isWalkable, nearestWalkable, randomWalkablePoint, type NavGrid } from "./officeNav";+import { createRng } from "./officeBehavior";++const PROVIDERS = ["Codex", "Claude Code", "Gemini", "OpenCode", "Kimi", "GLM", "Jarvis"];++function roster(count: number): OfficeAgentInput[] {+ return Array.from({ length: count }, (_, i) => ({+ agentId: `a${i}`, name: `a${i}`, tier: i === 0 ? "lead" : "specialist",+ providerLabel: PROVIDERS[i % PROVIDERS.length], state: "idle", createdMs: i,+ }));+}++function targetsOf(layout: OfficeLayout): { name: string; p: Point }[] {+ return [+ ...allDesks(layout).flatMap((d) => [{ name: `seat ${d.id}`, p: seatOf(d) }, { name: `stand ${d.id}`, p: standOf(d) }]),+ ...layout.spots.map((s) => ({ name: `spot ${s.id}`, p: s })),+ ...layout.checkpoints.map((c) => ({ name: `checkpoint ${c.id}`, p: c })),+ ];+}++/** Every sampled point of every segment is walkable, except the final snap onto a blocked target. */+function assertClearPath(grid: NavGrid, from: Point, to: Point, path: Point[], name: string): void {+ const last = path[path.length - 1];+ expect(last.x, name).toBeCloseTo(to.x, 9);+ expect(last.z, name).toBeCloseTo(to.z, 9);+ const segments = path.length - (isWalkable(grid, to) ? 0 : 1);+ let prev = from;+ for (let i = 0; i < segments; i += 1) {+ const next = path[i];+ expect(hasLineOfSight(grid, prev, next), `${name}: segment ${i}`).toBe(true);+ const len = Math.hypot(next.x - prev.x, next.z - prev.z);+ const steps = Math.max(1, Math.ceil(len / 0.03));+ for (let k = 0; k <= steps; k += 1) {+ const t = k / steps;+ const p = { x: prev.x + (next.x - prev.x) * t, z: prev.z + (next.z - prev.z) * t };+ if (!isWalkable(grid, p)) throw new Error(`${name}: segment ${i} crosses a blocked cell at ${p.x.toFixed(2)},${p.z.toFixed(2)}`);+ }+ prev = next;+ }+ if (!isWalkable(grid, to)) {+ const approach = path[path.length - 2] ?? from;+ expect(Math.hypot(approach.x - to.x, approach.z - to.z), `${name}: snap length`).toBeLessThanOrEqual(1.0 + 1e-9);+ }+}++describe("office navigation", () => {+ for (const count of [0, 10, 40]) {+ it(`reaches every seat, spot and checkpoint from the spawn (${count} agents)`, () => {+ const layout = buildOfficeLayout(roster(count));+ const grid = buildNavGrid(layout);+ expect(isWalkable(grid, layout.spawn)).toBe(true);+ for (const { name, p } of targetsOf(layout)) {+ const path = findPath(grid, layout.spawn, p);+ if (!path) throw new Error(`${name} at ${p.x.toFixed(2)},${p.z.toFixed(2)} is unreachable`);+ assertClearPath(grid, layout.spawn, p, path, name);+ }+ });+ }++ it("walks back from every target to the spawn, starting inside furniture if need be", () => {+ const layout = buildOfficeLayout(roster(10));+ const grid = buildNavGrid(layout);+ for (const { name, p } of targetsOf(layout)) {+ const path = findPath(grid, p, layout.spawn);+ expect(path, name).not.toBeNull();+ const tail = path!.at(-1)!;+ expect(tail).toEqual(layout.spawn);+ }+ });++ it("blocks obstacles and everything outside the floor", () => {+ const layout = buildOfficeLayout(roster(4));+ const grid = buildNavGrid(layout);+ const desk = allDesks(layout)[0];+ expect(isWalkable(grid, desk)).toBe(false);+ expect(isWalkable(grid, { x: layout.floor.minX - 0.5, z: 0 })).toBe(false);+ expect(isWalkable(grid, { x: 1e6, z: 1e6 })).toBe(false);+ const near = nearestWalkable(grid, desk)!;+ expect(isWalkable(grid, near)).toBe(true);+ expect(Math.hypot(near.x - desk.x, near.z - desk.z)).toBeLessThan(1.5);+ expect(nearestWalkable(grid, layout.spawn)).toEqual(layout.spawn);+ });++ it("has no line of sight through a desk row", () => {+ const layout = buildOfficeLayout(roster(4));+ const grid = buildNavGrid(layout);+ const desk = allDesks(layout).find((d) => d.id.startsWith("dept-0:0:south"))!;+ const seat = seatOf(desk);+ const across = { x: seat.x, z: desk.z + 2 };+ expect(hasLineOfSight(grid, seat, across)).toBe(false);+ });++ it("returns an empty path when already at the target, and null when unreachable", () => {+ const layout = buildOfficeLayout([]);+ const grid = buildNavGrid(layout);+ expect(findPath(grid, layout.spawn, layout.spawn)).toEqual([]);+ expect(findPath(grid, layout.spawn, { x: 1e4, z: 1e4 })).toBeNull();+ });++ it("draws random walkable points inside the requested rect", () => {+ const layout = buildOfficeLayout(roster(10));+ const grid = buildNavGrid(layout);+ const rng = createRng("wander");+ const within = layout.departments[0];+ for (let i = 0; i < 50; i += 1) {+ const p = randomWalkablePoint(grid, rng, within)!;+ expect(isWalkable(grid, p)).toBe(true);+ expect(p.x).toBeGreaterThanOrEqual(within.minX);+ expect(p.x).toBeLessThanOrEqual(within.maxX);+ expect(p.z).toBeGreaterThanOrEqual(within.minZ);+ expect(p.z).toBeLessThanOrEqual(within.maxZ);+ }+ expect(randomWalkablePoint(grid, rng, { minX: 1e5, maxX: 1e5 + 1, minZ: 0, maxZ: 1 })).toBeNull();+ });++ it("finds paths fast on a full floor", () => {+ const layout = buildOfficeLayout(roster(40));+ const grid = buildNavGrid(layout);+ const rng = createRng("perf");+ const points = Array.from({ length: 60 }, () => randomWalkablePoint(grid, rng)!);+ findPath(grid, points[0], points[1]); // warm up caches+ const started = performance.now();+ let runs = 0;+ for (let i = 0; i + 1 < points.length; i += 1) {+ expect(findPath(grid, points[i], points[i + 1])).not.toBeNull();+ runs += 1;+ }+ const perPath = (performance.now() - started) / runs;+ // Typically well under 5 ms; the bound is generous for slow CI machines.+ expect(perPath).toBeLessThan(25);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeNav.ts b/jarvis/ui/web/frontend/src/components/society/office/officeNav.tsnew file mode 100644index 0000000000..2d0b3da9c3--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/officeNav.ts@@ -0,0 +1,393 @@+/**+ * Grid navigation for the office floor: an occupancy grid built from the+ * layout's obstacles (inflated by the walker radius), A* over it, and+ * line-of-sight smoothing so figures walk straight lines instead of+ * staircases.+ *+ * Pure and allocation-light: per-grid scratch buffers are cached, so a path+ * search on a full floor costs well under a few milliseconds.+ */+import type { OfficeLayout, Point, Rect } from "./officeLayout";++/** Half the shoulder width of a walking figure, in metres. */+export const WALKER_RADIUS = 0.28;++export interface NavGrid {+ /** Edge length of one square cell, in metres. */+ cell: number;+ cols: number;+ rows: number;+ /** World position of the grid's north-west corner. */+ originX: number;+ originZ: number;+ /** 1 = blocked, 0 = walkable; index = row * cols + col. */+ blocked: Uint8Array;+}++/** A snapped approach may end at most this far from a blocked target. */+const SNAP_DISTANCE = 1.0;+/** How far a blocked start or an unreachable target may search for a walkable cell. */+const FALLBACK_SEARCH = 3.0;+const SQRT2 = Math.SQRT2;++export function buildNavGrid(layout: OfficeLayout, opts: { cell?: number; radius?: number } = {}): NavGrid {+ const cell = opts.cell ?? 0.2;+ const radius = opts.radius ?? WALKER_RADIUS;+ const { floor } = layout;+ const cols = Math.max(1, Math.ceil((floor.maxX - floor.minX) / cell));+ const rows = Math.max(1, Math.ceil((floor.maxZ - floor.minZ) / cell));+ const originX = floor.minX;+ const originZ = floor.minZ;+ const blocked = new Uint8Array(cols * rows);++ // Cells whose centre lies outside the walkable floor.+ for (let r = 0; r < rows; r += 1) {+ const cz = originZ + (r + 0.5) * cell;+ for (let c = 0; c < cols; c += 1) {+ const cx = originX + (c + 0.5) * cell;+ if (cx < floor.minX || cx > floor.maxX || cz < floor.minZ || cz > floor.maxZ) blocked[r * cols + c] = 1;+ }+ }+ // Cells whose centre lies inside an inflated obstacle.+ for (const o of layout.obstacles) {+ const minX = o.minX - radius, maxX = o.maxX + radius, minZ = o.minZ - radius, maxZ = o.maxZ + radius;+ const c0 = Math.max(0, Math.ceil((minX - originX) / cell - 0.5));+ const c1 = Math.min(cols - 1, Math.floor((maxX - originX) / cell - 0.5));+ const r0 = Math.max(0, Math.ceil((minZ - originZ) / cell - 0.5));+ const r1 = Math.min(rows - 1, Math.floor((maxZ - originZ) / cell - 0.5));+ for (let r = r0; r <= r1; r += 1) {+ for (let c = c0; c <= c1; c += 1) blocked[r * cols + c] = 1;+ }+ }+ return { cell, cols, rows, originX, originZ, blocked };+}++function colOf(grid: NavGrid, x: number): number {+ return Math.floor((x - grid.originX) / grid.cell);+}++function rowOf(grid: NavGrid, z: number): number {+ return Math.floor((z - grid.originZ) / grid.cell);+}++function walkableCell(grid: NavGrid, c: number, r: number): boolean {+ return c >= 0 && r >= 0 && c < grid.cols && r < grid.rows && grid.blocked[r * grid.cols + c] === 0;+}++function centreOf(grid: NavGrid, index: number): Point {+ const c = index % grid.cols;+ const r = (index - c) / grid.cols;+ return { x: grid.originX + (c + 0.5) * grid.cell, z: grid.originZ + (r + 0.5) * grid.cell };+}++/** Index of the cell containing p, or -1 when p lies outside the grid. */+function indexOf(grid: NavGrid, p: Point): number {+ const c = colOf(grid, p.x);+ const r = rowOf(grid, p.z);+ if (c < 0 || r < 0 || c >= grid.cols || r >= grid.rows) return -1;+ return r * grid.cols + c;+}++export function isWalkable(grid: NavGrid, p: Point): boolean {+ return walkableCell(grid, colOf(grid, p.x), rowOf(grid, p.z));+}++/** Nearest walkable cell (by centre distance) within maxRadius that passes `accept`; -1 if none. */+function nearestCell(grid: NavGrid, p: Point, maxRadius: number, accept?: (index: number) => boolean): number {+ const pc = Math.min(grid.cols - 1, Math.max(0, colOf(grid, p.x)));+ const pr = Math.min(grid.rows - 1, Math.max(0, rowOf(grid, p.z)));+ // Distance from p to its (clamped) cell, so points just off the grid still search correctly.+ const offGrid = Math.hypot(+ Math.max(0, grid.originX - p.x, p.x - (grid.originX + grid.cols * grid.cell)),+ Math.max(0, grid.originZ - p.z, p.z - (grid.originZ + grid.rows * grid.cell)),+ );+ if (offGrid > maxRadius) return -1;+ const maxRing = Math.ceil((maxRadius + offGrid) / grid.cell) + 1;+ let best = -1;+ let bestDist = Infinity;+ for (let ring = 0; ring <= maxRing; ring += 1) {+ // Every centre in this ring is at least this far from p.+ if (best >= 0 && (ring - 1) * grid.cell - offGrid > bestDist) break;+ for (let dr = -ring; dr <= ring; dr += 1) {+ const r = pr + dr;+ if (r < 0 || r >= grid.rows) continue;+ const edgeRow = dr === -ring || dr === ring;+ for (let dc = -ring; dc <= ring; dc += edgeRow ? 1 : ring * 2) {+ const c = pc + dc;+ if (c >= 0 && c < grid.cols) {+ const index = r * grid.cols + c;+ if (grid.blocked[index] === 0) {+ const cx = grid.originX + (c + 0.5) * grid.cell;+ const cz = grid.originZ + (r + 0.5) * grid.cell;+ const d = Math.hypot(cx - p.x, cz - p.z);+ if (d <= maxRadius && d < bestDist && (!accept || accept(index))) { best = index; bestDist = d; }+ }+ }+ if (ring === 0) break;+ }+ }+ }+ return best;+}++/** Centre of the walkable cell nearest to p (p's own cell when walkable), or null within maxRadius. */+export function nearestWalkable(grid: NavGrid, p: Point, maxRadius = FALLBACK_SEARCH): Point | null {+ if (isWalkable(grid, p)) return { x: p.x, z: p.z };+ const index = nearestCell(grid, p, maxRadius);+ return index < 0 ? null : centreOf(grid, index);+}++/**+ * True when every cell the segment a→b touches is walkable (supercover walk).+ * A segment through a cell corner must have both side cells free, which+ * matches the "no corner cutting" rule of the path search.+ */+export function hasLineOfSight(grid: NavGrid, a: Point, b: Point): boolean {+ const ax = (a.x - grid.originX) / grid.cell, az = (a.z - grid.originZ) / grid.cell;+ const bx = (b.x - grid.originX) / grid.cell, bz = (b.z - grid.originZ) / grid.cell;+ let c = Math.floor(ax), r = Math.floor(az);+ if (!walkableCell(grid, c, r)) return false;+ const dx = bx - ax, dz = bz - az;+ const stepX = dx > 0 ? 1 : dx < 0 ? -1 : 0;+ const stepZ = dz > 0 ? 1 : dz < 0 ? -1 : 0;+ const tDeltaX = stepX !== 0 ? 1 / Math.abs(dx) : Infinity;+ const tDeltaZ = stepZ !== 0 ? 1 / Math.abs(dz) : Infinity;+ let tMaxX = stepX > 0 ? (c + 1 - ax) * tDeltaX : stepX < 0 ? (ax - c) * tDeltaX : Infinity;+ let tMaxZ = stepZ > 0 ? (r + 1 - az) * tDeltaZ : stepZ < 0 ? (az - r) * tDeltaZ : Infinity;+ const limit = Math.abs(Math.floor(bx) - c) + Math.abs(Math.floor(bz) - r) + 4;+ for (let i = 0; i < limit * 2; i += 1) {+ const next = Math.min(tMaxX, tMaxZ);+ if (next > 1) return true;+ if (Math.abs(tMaxX - tMaxZ) < 1e-9) {+ // Exactly through a corner: both side cells must be free.+ if (!walkableCell(grid, c + stepX, r) || !walkableCell(grid, c, r + stepZ)) return false;+ c += stepX; r += stepZ; tMaxX += tDeltaX; tMaxZ += tDeltaZ;+ } else if (tMaxX < tMaxZ) {+ c += stepX; tMaxX += tDeltaX;+ } else {+ r += stepZ; tMaxZ += tDeltaZ;+ }+ if (!walkableCell(grid, c, r)) return false;+ }+ return true;+}++interface Scratch {+ g: Float64Array;+ parent: Int32Array;+ seen: Uint32Array;+ closed: Uint32Array;+ stamp: number;+ heapIndex: Int32Array;+ heapKey: Float64Array;+ /** Connected-region label per cell (-1 = blocked). */+ region: Int32Array | null;+}++const scratchCache = new WeakMap<NavGrid, Scratch>();++function scratchOf(grid: NavGrid): Scratch {+ let s = scratchCache.get(grid);+ if (!s) {+ const n = grid.cols * grid.rows;+ s = {+ g: new Float64Array(n), parent: new Int32Array(n), seen: new Uint32Array(n), closed: new Uint32Array(n), stamp: 0,+ heapIndex: new Int32Array(1024), heapKey: new Float64Array(1024), region: null,+ };+ scratchCache.set(grid, s);+ }+ return s;+}++/** Label 4-connected walkable regions (equivalent to 8-connected without corner cutting). */+function regionsOf(grid: NavGrid): Int32Array {+ const s = scratchOf(grid);+ if (s.region) return s.region;+ const n = grid.cols * grid.rows;+ const region = new Int32Array(n).fill(-1);+ const queue = new Int32Array(n);+ let label = 0;+ for (let start = 0; start < n; start += 1) {+ if (grid.blocked[start] !== 0 || region[start] !== -1) continue;+ let head = 0, tail = 0;+ queue[tail++] = start;+ region[start] = label;+ while (head < tail) {+ const i = queue[head++];+ const c = i % grid.cols;+ const neighbours = [c > 0 ? i - 1 : -1, c < grid.cols - 1 ? i + 1 : -1, i - grid.cols, i + grid.cols];+ for (const j of neighbours) {+ if (j < 0 || j >= n || grid.blocked[j] !== 0 || region[j] !== -1) continue;+ region[j] = label;+ queue[tail++] = j;+ }+ }+ label += 1;+ }+ s.region = region;+ return region;+}++/** A* from cell s to cell t (8-connected, no corner cutting). Returns cells from s to t inclusive, or null. */+function aStar(grid: NavGrid, s: number, t: number): number[] | null {+ const sc = scratchOf(grid);+ sc.stamp += 1;+ if (sc.stamp === 0xffffffff) { sc.seen.fill(0); sc.closed.fill(0); sc.stamp = 1; }+ const stamp = sc.stamp;+ const { g, parent, seen, closed } = sc;+ const cols = grid.cols, rows = grid.rows, blocked = grid.blocked;+ const tc = t % cols, tr = (t - tc) / cols;+ const h = (i: number): number => {+ const c = i % cols, r = (i - c) / cols;+ const dx = Math.abs(c - tc), dz = Math.abs(r - tr);+ return dx > dz ? dx + (SQRT2 - 1) * dz : dz + (SQRT2 - 1) * dx;+ };++ // Binary min-heap with lazy deletion.+ let size = 0;+ const push = (index: number, key: number) => {+ if (size >= sc.heapIndex.length) {+ const grownI = new Int32Array(sc.heapIndex.length * 2); grownI.set(sc.heapIndex); sc.heapIndex = grownI;+ const grownK = new Float64Array(sc.heapKey.length * 2); grownK.set(sc.heapKey); sc.heapKey = grownK;+ }+ const hi = sc.heapIndex, hk = sc.heapKey;+ let pos = size++;+ while (pos > 0) {+ const up = (pos - 1) >> 1;+ if (hk[up] <= key) break;+ hi[pos] = hi[up]; hk[pos] = hk[up]; pos = up;+ }+ hi[pos] = index; hk[pos] = key;+ };+ const pop = (): number => {+ const hi = sc.heapIndex, hk = sc.heapKey;+ const top = hi[0];+ size -= 1;+ if (size > 0) {+ const lastI = hi[size], lastK = hk[size];+ let pos = 0;+ for (;;) {+ let child = pos * 2 + 1;+ if (child >= size) break;+ if (child + 1 < size && hk[child + 1] < hk[child]) child += 1;+ if (hk[child] >= lastK) break;+ hi[pos] = hi[child]; hk[pos] = hk[child]; pos = child;+ }+ hi[pos] = lastI; hk[pos] = lastK;+ }+ return top;+ };++ g[s] = 0; parent[s] = -1; seen[s] = stamp;+ push(s, h(s));+ while (size > 0) {+ const cur = pop();+ if (closed[cur] === stamp) continue;+ closed[cur] = stamp;+ if (cur === t) {+ const cells: number[] = [];+ for (let i = t; i !== -1; i = parent[i]) cells.push(i);+ return cells.reverse();+ }+ const c = cur % cols, r = (cur - c) / cols;+ for (let dr = -1; dr <= 1; dr += 1) {+ const nr = r + dr;+ if (nr < 0 || nr >= rows) continue;+ for (let dc = -1; dc <= 1; dc += 1) {+ if (dc === 0 && dr === 0) continue;+ const nc = c + dc;+ if (nc < 0 || nc >= cols) continue;+ const ni = nr * cols + nc;+ if (blocked[ni] !== 0 || closed[ni] === stamp) continue;+ let cost = 1;+ if (dc !== 0 && dr !== 0) {+ // No corner cutting: both orthogonal neighbours must be free.+ if (blocked[r * cols + nc] !== 0 || blocked[nr * cols + c] !== 0) continue;+ cost = SQRT2;+ }+ const ng = g[cur] + cost;+ if (seen[ni] === stamp && ng >= g[ni]) continue;+ seen[ni] = stamp; g[ni] = ng; parent[ni] = cur;+ push(ni, ng + h(ni));+ }+ }+ }+ return null;+}++/**+ * Waypoints from `from` to `to`, excluding the start, or null when `to` is+ * genuinely unreachable.+ *+ * A blocked start first steps to its nearest walkable cell. A blocked target+ * (a couch seat, a chair tucked against a desk) is approached through the+ * nearest reachable cell; when that cell lies within 1 m, the exact target is+ * appended as a final "snap" step that may cross the inflated margin.+ */+export function findPath(grid: NavGrid, from: Point, to: Point): Point[] | null {+ const region = regionsOf(grid);+ let s = indexOf(grid, from);+ let startSnapped = false;+ if (s < 0 || grid.blocked[s] !== 0) {+ s = nearestCell(grid, from, FALLBACK_SEARCH);+ if (s < 0) return null;+ startSnapped = true;+ }+ const home = region[s];+ const sameRegion = (index: number) => region[index] === home;++ let t = indexOf(grid, to);+ let goalSnap = false;+ const targetWalkable = t >= 0 && grid.blocked[t] === 0;+ if (targetWalkable) {+ if (region[t] !== home) return null;+ } else {+ t = nearestCell(grid, to, SNAP_DISTANCE, sameRegion);+ if (t >= 0) goalSnap = true;+ else t = nearestCell(grid, to, FALLBACK_SEARCH, sameRegion);+ if (t < 0) return null;+ }++ const cells = aStar(grid, s, t);+ if (!cells) return null;++ const startPoint = startSnapped ? centreOf(grid, s) : from;+ const points = cells.slice(1).map((i) => centreOf(grid, i));+ if (targetWalkable) {+ if (points.length > 0) points[points.length - 1] = { x: to.x, z: to.z };+ else if (Math.hypot(to.x - startPoint.x, to.z - startPoint.z) > 1e-6) points.push({ x: to.x, z: to.z });+ }++ // String pulling: drop every waypoint the previous kept point can see past.+ const smoothed: Point[] = [];+ let anchor = startPoint;+ for (let i = 0; i < points.length; i += 1) {+ if (i === points.length - 1 || !hasLineOfSight(grid, anchor, points[i + 1])) {+ smoothed.push(points[i]);+ anchor = points[i];+ }+ }++ const out: Point[] = [];+ if (startSnapped) out.push(startPoint);+ out.push(...smoothed);+ if (goalSnap) out.push({ x: to.x, z: to.z });+ return out;+}++/** A uniformly drawn walkable cell centre (inside `within` when given), or null after a bounded number of tries. */+export function randomWalkablePoint(grid: NavGrid, rng: () => number, within?: Rect): Point | null {+ const minX = Math.max(grid.originX, within?.minX ?? -Infinity);+ const maxX = Math.min(grid.originX + grid.cols * grid.cell, within?.maxX ?? Infinity);+ const minZ = Math.max(grid.originZ, within?.minZ ?? -Infinity);+ const maxZ = Math.min(grid.originZ + grid.rows * grid.cell, within?.maxZ ?? Infinity);+ if (maxX <= minX || maxZ <= minZ) return null;+ for (let attempt = 0; attempt < 64; attempt += 1) {+ const p = { x: minX + rng() * (maxX - minX), z: minZ + rng() * (maxZ - minZ) };+ const index = indexOf(grid, p);+ if (index < 0 || grid.blocked[index] !== 0) continue;+ const centre = centreOf(grid, index);+ if (centre.x >= minX && centre.x <= maxX && centre.z >= minZ && centre.z <= maxZ) return centre;+ }+ return null;+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/officePalette.ts b/jarvis/ui/web/frontend/src/components/society/office/officePalette.tsindex 86d05c6a87..caa5d78437 100644--- a/jarvis/ui/web/frontend/src/components/society/office/officePalette.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/officePalette.ts@@ -38,3 +38,45 @@ export const OFFICE = {/** Carpet tints per department — soft, desaturated, readable next to wood. */export const DEPARTMENT_TINTS = ["#9aa6b8", "#a9b59a", "#b8a39a", "#a39ab8", "#9ab5b1", "#b8b19a"] as const;++/** Colours of the room props (lobby, team room, wardrobe, break room). */+export const PROP_COLOURS = {+ steel: "#aab2bc",+ steelDark: "#6f7782",+ elevatorShaft: "#e7e4de",+ indicator: "#ffb347",+ lockers: ["#5fa8a0", "#e2856e", "#f2c14e", "#9b8ac4"],+ lockerVent: "#2f3440",+ mirror: "#d6ecf8",+ waterBottle: "#6fb7ea",+ waterTap: ["#e05a4f", "#4f8fe0"],+ mug: "#fdfbf7",+ coffee: "#5a3a24",+ espresso: "#c9ced4",+ chalkboard: "#2c3a33",+ arcadeBody: "#5b4a9e",+ arcadeTrim: "#2a2140",+ arcadeMarquee: "#ff7ab8",+ joystick: "#e0463c",+ arcadeButtons: ["#f2c14e", "#4fb3e0", "#6fd07a"],+ beanbag: ["#e27d60", "#85cdca", "#e8a87c", "#c38d9e", "#7d9bd6"],+ bell: "#e0b64a",+ boardFrame: "#d7d9dd",+ boardWhite: "#fbfbf8",+ kioskBody: "#f4f2ee",+ kioskHead: "#2a2e36",+ paper: "#fdfcf9",+ rugInner: "#c9b28f",+} as const;++/** Floor overlays per room kind: base colour plus the pattern's accent tones. */+export const ROOM_FLOOR_COLOURS = {+ lead: { base: "#a9774d", accents: ["#b3825a", "#9e6d45", "#ad7b52", "#a47249"] },+ team: { base: "#7fb3ad", accents: ["#8bbdb7", "#74a7a1", "#86b8b2"] },+ wardrobe: { base: "#ddd3ea", accents: ["#cfc3e0", "#e6ddf1"] },+ reception: { base: "#e7e2d9", accents: ["#ece8e0", "#e0dacf", "#e9e4dc"] },+ break: { base: "#d98b6e", accents: ["#e0967a", "#d08065", "#dc9074"] },+} as const;++/** Checkpoint gold: floor ring, hexagon token and the label badge. */+export const CHECKPOINT_GOLD = { ring: "#f5b83d", rim: "#e0a02a", face: "#f7c65a", faceDeep: "#e39b1f", icon: "#ffffff" } as const;diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeStore.ts b/jarvis/ui/web/frontend/src/components/society/office/officeStore.tsnew file mode 100644index 0000000000..200c550165--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/officeStore.ts@@ -0,0 +1,80 @@+/**+ * Office interaction state shared between the canvas and the DOM HUD.+ *+ * Positions that change every frame live in the mutable `player` object and+ * are never React state; the store only carries what the HUD renders or what+ * the walkers must react to (selection, nearby target, calls, gatherings).+ */+import { create } from "zustand";+import type { CheckpointKind, Point } from "./officeLayout";++export type Selection = { kind: "agent"; id: string } | { kind: "checkpoint"; id: CheckpointKind };++export interface PlayerBody { x: number; z: number; heading: number; path: Point[]; moving: boolean }++/** Agents walking over to a point for a while (called by the person, or a team gathering). */+export interface Summon { target: Point; untilMs: number }++interface OfficeState {+ selection: Selection | null;+ /** The closest thing the character can interact with (E), or null. */+ nearby: Selection | null;+ /** Camera follows the character; any manual pan turns it off, moving turns it back on. */+ follow: boolean;+ /** One-shot camera fly-to request, consumed by the camera rig. */+ focus: { point: Point; seq: number } | null;+ summons: Record<string, Summon>;+ /** Walk the character to this point (click-to-move / "walk there"), consumed by the player. */+ walkTo: { point: Point; seq: number } | null;+ /** Agents picked for a new team, carried from agent panels to the team room. */+ teamDraft: string[];+ toggleDraft: (agentId: string) => void;+ clearDraft: () => void;+ clearSummons: () => void;+ select: (selection: Selection | null) => void;+ setNearby: (nearby: Selection | null) => void;+ setFollow: (follow: boolean) => void;+ focusOn: (point: Point) => void;+ summon: (agentIds: readonly string[], target: Point, durationMs: number) => void;+ requestWalk: (point: Point) => void;+}++let seq = 0;++export const useOfficeStore = create<OfficeState>((set) => ({+ selection: null,+ nearby: null,+ follow: true,+ focus: null,+ summons: {},+ walkTo: null,+ teamDraft: [],+ toggleDraft: (agentId) => set((s) => ({+ teamDraft: s.teamDraft.includes(agentId) ? s.teamDraft.filter((id) => id !== agentId) : [...s.teamDraft, agentId],+ })),+ clearDraft: () => set({ teamDraft: [] }),+ clearSummons: () => set({ summons: {} }),+ select: (selection) => set({ selection }),+ setNearby: (nearby) => set((s) => (sameSelection(s.nearby, nearby) ? s : { nearby })),+ setFollow: (follow) => set((s) => (s.follow === follow ? s : { follow })),+ focusOn: (point) => set({ focus: { point, seq: ++seq }, follow: false }),+ summon: (agentIds, target, durationMs) => set((s) => {+ const untilMs = Date.now() + durationMs;+ const next = { ...s.summons };+ agentIds.forEach((id, i) => {+ // Fan the group out around the target so nobody stands inside anybody.+ const angle = (i / Math.max(1, agentIds.length)) * Math.PI * 2;+ const r = agentIds.length > 1 ? 0.9 + 0.15 * agentIds.length : 1.2;+ next[id] = { target: { x: target.x + Math.sin(angle) * r, z: target.z + Math.cos(angle) * r }, untilMs };+ });+ return { summons: next };+ }),+ requestWalk: (point) => set({ walkTo: { point, seq: ++seq }, follow: true }),+}));++/** The character's body, mutated by the player controller every frame. */+export const player: PlayerBody = { x: 0, z: 0, heading: Math.PI, path: [], moving: false };++export function sameSelection(a: Selection | null, b: Selection | null): boolean {+ return a === b || (!!a && !!b && a.kind === b.kind && a.id === b.id);+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/playerProfile.ts b/jarvis/ui/web/frontend/src/components/society/office/playerProfile.tsnew file mode 100644index 0000000000..a50d932a51--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/playerProfile.ts@@ -0,0 +1,68 @@+/**+ * The person's own character in the office: a name and a figure recipe.+ *+ * Stored per browser profile (localStorage) — it is a presentation choice, not+ * roster data, so it never touches society.db. Every read and write tolerates+ * a missing or blocked storage and falls back to the default look.+ */+import { CATALOG } from "../figures/figureRegistry";+import { shufflePalette, type FigureRecipe } from "../figures/figureRecipe";++const STORAGE_KEY = "jarvis.office.player.v1";++export interface PlayerProfile {+ name: string;+ recipe: FigureRecipe;+}++/** Bodies offered in the wardrobe: two-legged, first-party, not reserved. */+export const WARDROBE_BASES: readonly string[] = CATALOG.bases+ .filter((b) => b.archetype === "biped" && !b.styles.includes("custom"))+ .map((b) => b.base);++export function defaultProfile(): PlayerProfile {+ const base = WARDROBE_BASES.includes("toon") ? "toon" : WARDROBE_BASES[0] ?? "chibi";+ return {+ name: "",+ recipe: { contract: 1, archetype: "biped", base, parts: {}, palette: { primary: "#3f9d5a", secondary: "#2b4a8b", hair: "#6b3f2a", shoes: "#f2f2ee" } },+ };+}++function isRecipe(value: unknown): value is FigureRecipe {+ const r = value as Partial<FigureRecipe> | null;+ return !!r && r.contract === 1 && r.archetype === "biped" && typeof r.base === "string" && WARDROBE_BASES.includes(r.base)+ && typeof r.parts === "object" && r.parts !== null;+}++export function loadProfile(): PlayerProfile {+ try {+ const raw = window.localStorage.getItem(STORAGE_KEY);+ if (!raw) return defaultProfile();+ const parsed = JSON.parse(raw) as Partial<PlayerProfile>;+ const fallback = defaultProfile();+ return {+ name: typeof parsed.name === "string" ? parsed.name.slice(0, 40) : fallback.name,+ recipe: isRecipe(parsed.recipe) ? parsed.recipe : fallback.recipe,+ };+ } catch (error) {+ // Blocked storage (private window, thumbnail capture): the default look is the honest answer.+ console.debug("Office player profile unavailable", error);+ return defaultProfile();+ }+}++export function saveProfile(profile: PlayerProfile): void {+ try {+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(profile));+ } catch (error) {+ console.debug("Office player profile not saved", error);+ }+}++export function withBase(profile: PlayerProfile, base: string): PlayerProfile {+ return { ...profile, recipe: { ...profile.recipe, base, parts: {} } };+}++export function withShuffledColours(profile: PlayerProfile, seed = Math.random()): PlayerProfile {+ return { ...profile, recipe: { ...profile.recipe, palette: shufflePalette(seed) } };+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/walkerRegistry.ts b/jarvis/ui/web/frontend/src/components/society/office/walkerRegistry.tsnew file mode 100644index 0000000000..a62bf1e263--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/walkerRegistry.ts@@ -0,0 +1,11 @@+/**+ * Where every agent stands right now, written by the walkers each frame and+ * read by the player (who is nearby?) and the HUD (focus the camera on X).+ * A plain module map: per-frame positions must never become React state.+ */+import type { Point } from "./officeLayout";++export const agentPositions = new Map<string, Point>();++/** Agent ids the office has already seen; a newcomer arrives by the elevator. */+export const knownAgents = new Set<string>();diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json b/jarvis/ui/web/frontend/src/i18n/locales/society/de.jsonindex 28d80ab1e3..83e59f1ea3 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json@@ -735,10 +735,76 @@"open_agent": "{0} öffnen","overview": "Übersicht","ledger": "Agentenliste",- "help": "Ziehen zum Drehen · Rechts ziehen zum Verschieben · Scrollen zum Zoomen · Agent anklicken zum Öffnen",+ "help": "WASD / Pfeile laufen · Shift rennt · Boden anklicken zum Hingehen · E interagiert · Ziehen dreht · Scrollen zoomt","sample": "Beispiel-Agenten – das Backend ist noch nicht erreichbar.","overflow": "Nur die ersten {0} Agenten haben einen Schreibtisch; die Liste zeigt alle.",- "open_space": "Open Space"+ "open_space": "Open Space",+ "close": "Schließen",+ "action_chat": "Chat öffnen",+ "action_walk": "Hingehen",+ "action_call": "Herrufen",+ "action_focus": "Auf der Karte zeigen",+ "action_draft": "Zum neuen Team",+ "action_undraft": "Aus neuem Team entfernen",+ "draft_count": "{0} für ein neues Team ausgewählt – ab in den Teamraum",+ "create_body": "Stell einen neuen Agenten ein: Aufgabe, Gehirn und Aussehen. Er kommt mit dem Aufzug und nimmt einen freien Schreibtisch.",+ "create_action": "Neuen Agenten erstellen",+ "action_show": "Zeigen",+ "action_open": "Öffnen",+ "manage_action": "Agentenverwaltung öffnen",+ "team_body": "Wähle mindestens zwei Agenten und bündle sie zu einem Team mit gemeinsamem Chat. Sie treffen sich sofort am Tisch.",+ "team_name": "Teamname",+ "team_name_placeholder": "z. B. Launch-Crew",+ "team_create": "Team erstellen ({0})",+ "team_created": "Team „{0}“ ist bereit.",+ "team_open": "Team-Chat öffnen",+ "team_existing": "Bestehende Teams",+ "team_gather": "Versammeln",+ "wardrobe_name": "Dein Name",+ "you": "Du",+ "wardrobe_body": "Wähle deine Figur – die Farben kannst du mischen.",+ "wardrobe_shuffle": "Farben mischen",+ "lead_empty": "Noch kein Chef-Agent.",+ "lead_body": "Dein Chef-Agent koordiniert die anderen. Sprich hier mit ihm.",+ "break_body": "Gerade sind {0} Agenten frei. Ruf sie zur Kaffeepause – nur fürs Bild, ihre Arbeit bleibt unberührt.",+ "break_call": "Kaffeepause ausrufen",+ "break_release": "Alle zurück an die Arbeit",+ "cp_create": "Empfang",+ "cp_create_hint": "Neuen Agenten erstellen",+ "cp_manage": "Agenten-Board",+ "cp_manage_hint": "Alle Agenten sehen und verwalten",+ "cp_team": "Teamraum",+ "cp_team_hint": "Agenten zu einem Team bündeln",+ "cp_wardrobe": "Garderobe",+ "cp_wardrobe_hint": "Deine Figur ändern",+ "cp_lead": "Chefbüro",+ "cp_lead_hint": "Mit deinem Chef-Agenten sprechen",+ "cp_break": "Pausenraum",+ "cp_break_hint": "Kaffeepause ausrufen",+ "room_lead": "Chefbüro",+ "room_team": "Teamraum",+ "room_wardrobe": "Garderobe",+ "room_reception": "Empfang",+ "room_break": "Pausenraum",+ "prompt_agent": "Mit {0} sprechen",+ "prompt_checkpoint": "Benutzen: {0}",+ "me": "Mir folgen",+ "activity_work": "Arbeitet",+ "activity_wait": "Wartet auf dich",+ "activity_desk": "Am Schreibtisch",+ "activity_coffee": "Kaffee",+ "activity_couch": "Auf der Couch",+ "activity_nap": "Macht ein Nickerchen",+ "activity_window": "Am Fenster",+ "activity_shelf": "Stöbert in Büchern",+ "activity_arcade": "Zockt am Automaten",+ "activity_cooler": "Am Wasserspender",+ "activity_beanbag": "Chillt",+ "activity_meeting": "Im Teamraum",+ "activity_board": "Am Board",+ "activity_wander": "Schlendert",+ "activity_visit": "Plaudert",+ "activity_called": "Kommt rüber"}}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json b/jarvis/ui/web/frontend/src/i18n/locales/society/en.jsonindex 483247418a..3563f60ff9 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json@@ -735,10 +735,76 @@"open_agent": "Open {0}","overview": "Overview","ledger": "Agents list",- "help": "Drag to rotate · Right-drag to pan · Scroll to zoom · Click an agent to open it",+ "help": "WASD / arrows walk · Shift runs · Click the floor to walk there · E interacts · Drag rotates · Scroll zooms","sample": "Sample agents — the backend is not reachable yet.","overflow": "Only the first {0} agents have a desk; the list shows everyone.",- "open_space": "Open space"+ "open_space": "Open space",+ "close": "Close",+ "action_chat": "Open chat",+ "action_walk": "Walk there",+ "action_call": "Call over",+ "action_focus": "Show on map",+ "action_draft": "Add to new team",+ "action_undraft": "Remove from new team",+ "draft_count": "{0} picked for a new team — go to the team room",+ "create_body": "Hire a new agent: give it a job, a brain and a look. It arrives by the elevator and takes a free desk.",+ "create_action": "Create a new agent",+ "action_show": "Show",+ "action_open": "Open",+ "manage_action": "Open agent management",+ "team_body": "Pick at least two agents and bundle them into a team with a shared chat. They meet at the table right away.",+ "team_name": "Team name",+ "team_name_placeholder": "e.g. Launch crew",+ "team_create": "Create team ({0})",+ "team_created": "Team “{0}” is ready.",+ "team_open": "Open team chat",+ "team_existing": "Existing teams",+ "team_gather": "Gather",+ "wardrobe_name": "Your name",+ "you": "You",+ "wardrobe_body": "Pick your body — colours can be shuffled.",+ "wardrobe_shuffle": "Shuffle colours",+ "lead_empty": "No lead agent yet.",+ "lead_body": "Your lead coordinates the other agents. Talk to it here.",+ "break_body": "{0} agents are free right now. Call them over for a coffee break — purely for the view, their work is not affected.",+ "break_call": "Call a coffee break",+ "break_release": "Everyone back to their day",+ "cp_create": "Reception",+ "cp_create_hint": "Create a new agent",+ "cp_manage": "Agent board",+ "cp_manage_hint": "See and manage every agent",+ "cp_team": "Team room",+ "cp_team_hint": "Bundle agents into a team",+ "cp_wardrobe": "Wardrobe",+ "cp_wardrobe_hint": "Change your character",+ "cp_lead": "Lead office",+ "cp_lead_hint": "Talk to your lead agent",+ "cp_break": "Break room",+ "cp_break_hint": "Call a coffee break",+ "room_lead": "Lead office",+ "room_team": "Team room",+ "room_wardrobe": "Wardrobe",+ "room_reception": "Reception",+ "room_break": "Break room",+ "prompt_agent": "Talk to {0}",+ "prompt_checkpoint": "Use: {0}",+ "me": "Follow me",+ "activity_work": "Working",+ "activity_wait": "Waiting for you",+ "activity_desk": "At the desk",+ "activity_coffee": "Coffee",+ "activity_couch": "On the couch",+ "activity_nap": "Napping",+ "activity_window": "At the window",+ "activity_shelf": "Browsing books",+ "activity_arcade": "Playing arcade",+ "activity_cooler": "At the water cooler",+ "activity_beanbag": "Chilling",+ "activity_meeting": "In the team room",+ "activity_board": "At the board",+ "activity_wander": "Strolling",+ "activity_visit": "Chatting",+ "activity_called": "Coming over"}}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json b/jarvis/ui/web/frontend/src/i18n/locales/society/es.jsonindex 63e958e256..ee1e9137f3 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json@@ -735,10 +735,76 @@"open_agent": "Abrir {0}","overview": "Vista general","ledger": "Lista de agentes",- "help": "Arrastra para girar · Clic derecho para desplazar · Rueda para zoom · Clic en un agente para abrirlo",+ "help": "WASD / flechas para andar · Shift corre · Clic en el suelo para ir · E interactúa · Arrastrar gira · Rueda para zoom","sample": "Agentes de ejemplo: el backend aún no está disponible.","overflow": "Solo los primeros {0} agentes tienen escritorio; la lista muestra a todos.",- "open_space": "Espacio abierto"+ "open_space": "Espacio abierto",+ "close": "Cerrar",+ "action_chat": "Abrir chat",+ "action_walk": "Ir allí",+ "action_call": "Llamar",+ "action_focus": "Mostrar en el mapa",+ "action_draft": "Añadir al nuevo equipo",+ "action_undraft": "Quitar del nuevo equipo",+ "draft_count": "{0} elegidos para un equipo nuevo: ve a la sala de equipos",+ "create_body": "Contrata un agente nuevo: tarea, cerebro y aspecto. Llega en ascensor y ocupa un escritorio libre.",+ "create_action": "Crear un agente nuevo",+ "action_show": "Mostrar",+ "action_open": "Abrir",+ "manage_action": "Abrir gestión de agentes",+ "team_body": "Elige al menos dos agentes y agrúpalos en un equipo con chat compartido. Se reúnen en la mesa enseguida.",+ "team_name": "Nombre del equipo",+ "team_name_placeholder": "p. ej. Equipo de lanzamiento",+ "team_create": "Crear equipo ({0})",+ "team_created": "El equipo «{0}» está listo.",+ "team_open": "Abrir chat del equipo",+ "team_existing": "Equipos existentes",+ "team_gather": "Reunir",+ "wardrobe_name": "Tu nombre",+ "you": "Tú",+ "wardrobe_body": "Elige tu cuerpo; los colores se pueden mezclar.",+ "wardrobe_shuffle": "Mezclar colores",+ "lead_empty": "Aún no hay agente líder.",+ "lead_body": "Tu líder coordina a los demás agentes. Habla con él aquí.",+ "break_body": "Ahora hay {0} agentes libres. Llámalos a una pausa de café: solo visual, su trabajo no cambia.",+ "break_call": "Pausa de café",+ "break_release": "Todos de vuelta a lo suyo",+ "cp_create": "Recepción",+ "cp_create_hint": "Crear un agente nuevo",+ "cp_manage": "Tablero de agentes",+ "cp_manage_hint": "Ver y gestionar todos los agentes",+ "cp_team": "Sala de equipos",+ "cp_team_hint": "Agrupar agentes en un equipo",+ "cp_wardrobe": "Vestuario",+ "cp_wardrobe_hint": "Cambiar tu personaje",+ "cp_lead": "Despacho del líder",+ "cp_lead_hint": "Hablar con tu agente líder",+ "cp_break": "Sala de descanso",+ "cp_break_hint": "Hacer una pausa de café",+ "room_lead": "Despacho del líder",+ "room_team": "Sala de equipos",+ "room_wardrobe": "Vestuario",+ "room_reception": "Recepción",+ "room_break": "Sala de descanso",+ "prompt_agent": "Hablar con {0}",+ "prompt_checkpoint": "Usar: {0}",+ "me": "Seguirme",+ "activity_work": "Trabajando",+ "activity_wait": "Te espera",+ "activity_desk": "En su escritorio",+ "activity_coffee": "Café",+ "activity_couch": "En el sofá",+ "activity_nap": "Echando una siesta",+ "activity_window": "En la ventana",+ "activity_shelf": "Mirando libros",+ "activity_arcade": "Jugando arcade",+ "activity_cooler": "En el dispensador de agua",+ "activity_beanbag": "Relajándose",+ "activity_meeting": "En la sala de equipos",+ "activity_board": "En el tablero",+ "activity_wander": "Paseando",+ "activity_visit": "Charlando",+ "activity_called": "Viene hacia ti"}}}diff --git a/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsxindex 4a728e001a..c4ef6ec669 100644--- a/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx+++ b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx@@ -9,15 +9,17 @@ export interface JarvisAgentsViewProps {onSelectAgent?: (agentId: string | null) => void;onSelectPlace?: (place: PlaceId) => void;onOpenAgents: () => void;+ onCreateAgent?: () => void;+ onOpenGroup?: (groupId: string) => void;}-export function JarvisAgentsView({ onSelectAgent, onOpenAgents }: JarvisAgentsViewProps) {+export function JarvisAgentsView({ onSelectAgent, onOpenAgents, onCreateAgent, onOpenGroup }: JarvisAgentsViewProps) {const ready = useLocaleChunk("society");if (!ready) return null;return (<div className="h-full min-h-0"><Suspense fallback={<div className="h-full w-full animate-pulse bg-secondary" aria-hidden />}>- <OfficeStage onOpenLedger={onOpenAgents} onSelectAgent={onSelectAgent} />+ <OfficeStage onOpenLedger={onOpenAgents} onSelectAgent={onSelectAgent} onCreateAgent={onCreateAgent} onOpenGroup={onOpenGroup} /></Suspense></div>);diff --git a/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx b/jarvis/ui/web/frontend/src/views/society/SocietyView.tsxindex 922add832d..f39a7e08ae 100644--- a/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx+++ b/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx@@ -184,7 +184,8 @@ export function SocietyView() {<div className="min-w-0 flex-1"><CanvasActivity.Provider value={!openPlace && !creating}><Suspense fallback={null}>- <JarvisAgentsBoard onSelectAgent={onIslandSelect} onSelectPlace={onIslandPlace} onOpenAgents={() => switchMode("agents")} />+ <JarvisAgentsBoard onSelectAgent={onIslandSelect} onSelectPlace={onIslandPlace} onOpenAgents={() => switchMode("agents")}+ onCreateAgent={() => setCreating(true)} onOpenGroup={(groupId) => { selectGroup(groupId); switchMode("agents"); }} /></Suspense></CanvasActivity.Provider></div>