Skip to content

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.

feat(agents): Jarvis flies as Gigi, a floor minimap, and cleaner toy figures

rubenluetke10-beepa079effba53b
diff --git a/jarvis/ui/web/frontend/src/components/society/office/GigiFlyer.tsx b/jarvis/ui/web/frontend/src/components/society/office/GigiFlyer.tsx
new file mode 100644
index 0000000000..7d567939b1
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/GigiFlyer.tsx
@@ -0,0 +1,255 @@
+/**
+ * The lead agent (Jarvis) as it appears in the office: not a figure but Gigi,
+ * the mascot, flying at chest/head height above the walker's ground position.
+ *
+ * Motion comes from the pure `gigiFlight.ts`; this component only renders it
+ * with a few cheap effects: an additive halo behind Gigi, a small glow under
+ * its hover emitter, a recycled sparkle trail while travelling and a soft
+ * shadow blob on the floor. Everything is one draw call each, no lights.
+ */
+import { Component, Suspense, useEffect, useMemo, useRef, type ReactNode } from "react";
+import { useFrame } from "@react-three/fiber";
+import {
+ AdditiveBlending, BufferAttribute, BufferGeometry, CanvasTexture, CircleGeometry, Color, SRGBColorSpace,
+ type Group, type Mesh, type MeshBasicMaterial, type PointLight, type Points, type Sprite, type SpriteMaterial, type Texture,
+} from "three";
+import { CompanionModel } from "../companion/AgentFollower";
+import { defaultCompanion } from "../companion/appearance";
+import { createGigiFlight, createGigiPose, stepGigiFlight, type GigiFlightMode } from "./gigiFlight";
+
+/** Gigi's on-screen height in the office. */
+export const GIGI_OFFICE_SIZE_M = 0.5;
+/** Radius of the little orbs circling Gigi. */
+const ORBIT_RADIUS_M = 0.36;
+/** The authored model stands on its origin (y 0.014–0.40 of 0.4 m); lift so the flight point is its centre. */
+const MODEL_CENTRE_OFFSET = -0.207 * (GIGI_OFFICE_SIZE_M / 0.4);
+/** The hover emitter sits at the bottom of the shell. */
+const EMITTER_OFFSET = MODEL_CENTRE_OFFSET + 0.02;
+const TRAIL_SIZE = 24;
+const TRAIL_LIFE_S = 0.8;
+const TRAIL_RATE = 30;
+const MOVING_SPEED = 0.05;
+
+/** Local effect colours; the diorama keeps one palette in light and dark mode. */
+const GLOW_WARM = new Color("#ffd98a");
+const GLOW_SPEAK = new Color("#9ff3ff");
+const SPARK = new Color("#ffe7a8");
+
+// ---- Shared canvas textures (reference counted; GPU copies freed with the last user) ----
+
+interface TextureCache { glow: Texture; shadow: Texture; users: number }
+let cache: TextureCache | null = null;
+
+function radialTexture(stops: [number, string][]): Texture {
+ const canvas = document.createElement("canvas");
+ canvas.width = canvas.height = 64;
+ const context = canvas.getContext("2d");
+ if (context) {
+ const gradient = context.createRadialGradient(32, 32, 0, 32, 32, 32);
+ for (const [offset, colour] of stops) gradient.addColorStop(offset, colour);
+ context.fillStyle = gradient;
+ context.fillRect(0, 0, 64, 64);
+ }
+ const texture = new CanvasTexture(canvas);
+ texture.colorSpace = SRGBColorSpace;
+ return texture;
+}
+
+function sharedTextures(): TextureCache {
+ if (!cache) {
+ cache = {
+ glow: radialTexture([[0, "rgba(255,255,255,1)"], [0.25, "rgba(255,255,255,0.55)"], [0.6, "rgba(255,255,255,0.12)"], [1, "rgba(255,255,255,0)"]]),
+ shadow: radialTexture([[0, "rgba(0,0,0,1)"], [0.55, "rgba(0,0,0,0.45)"], [1, "rgba(0,0,0,0)"]]),
+ users: 0,
+ };
+ }
+ return cache;
+}
+
+/** Counted in an effect, so a StrictMode double mount never frees a texture in use. */
+function acquireTextures(): void {
+ sharedTextures().users++;
+}
+
+function releaseTextures(): void {
+ if (!cache) return;
+ cache.users--;
+ if (cache.users > 0) return;
+ // Frees the GPU copies; the tiny canvases stay cached and re-upload on next use,
+ // so a component still holding them (StrictMode remount) never renders a dead texture.
+ cache.glow.dispose();
+ cache.shadow.dispose();
+}
+
+/** A missing or broken GLB hides Gigi's body; the glow still marks the lead. */
+class ModelBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
+ state = { failed: false };
+ static getDerivedStateFromError() { return { failed: true }; }
+ componentDidCatch(error: Error) { console.warn("Gigi model unavailable", error.name); }
+ render() { return this.state.failed ? null : this.props.children; }
+}
+
+/** Tiny deterministic generator for sparkle jitter. */
+function nextRandom(seed: { value: number }): number {
+ seed.value = (Math.imul(seed.value, 1664525) + 1013904223) >>> 0;
+ return seed.value / 4294967296;
+}
+
+export function GigiFlyer({ owner, mode, speaking, paused, reduced }: {
+ /** The walker's mover: ground position and facing (0 = +z). */
+ owner: { current: { x: number; z: number; heading: number } };
+ mode: GigiFlightMode;
+ speaking: boolean;
+ paused: boolean;
+ reduced: boolean;
+}) {
+ const root = useRef<Group>(null);
+ const body = useRef<Group>(null);
+ const halo = useRef<Sprite>(null);
+ const emitter = useRef<Sprite>(null);
+ const shadow = useRef<Mesh>(null);
+ const trail = useRef<Points>(null);
+ const light = useRef<PointLight>(null);
+ const orbit = useRef<Group>(null);
+ const flight = useRef(createGigiFlight(owner.current.x, owner.current.z, owner.current.heading));
+ const pose = useMemo(() => createGigiPose(), []);
+ const clock = useRef(0);
+ const last = useRef({ x: owner.current.x, z: owner.current.z });
+ const emitDebt = useRef(0);
+ const seed = useRef({ value: 0x9e3779b9 });
+ const tint = useMemo(() => new Color(), []);
+ const appearance = useMemo(() => ({ ...defaultCompanion("jarvis"), sizeM: GIGI_OFFICE_SIZE_M }), []);
+
+ const textures = useMemo(() => sharedTextures(), []);
+ useEffect(() => { acquireTextures(); return releaseTextures; }, []);
+
+ const particles = useMemo(() => {
+ const geometry = new BufferGeometry();
+ const positions = new Float32Array(TRAIL_SIZE * 3);
+ const colours = new Float32Array(TRAIL_SIZE * 3);
+ geometry.setAttribute("position", new BufferAttribute(positions, 3));
+ geometry.setAttribute("color", new BufferAttribute(colours, 3));
+ const shadowGeometry = new CircleGeometry(0.28, 28);
+ return { geometry, shadowGeometry, positions, colours, age: new Float32Array(TRAIL_SIZE).fill(TRAIL_LIFE_S), rise: new Float32Array(TRAIL_SIZE), next: 0 };
+ }, []);
+ useEffect(() => () => { particles.geometry.dispose(); particles.shadowGeometry.dispose(); }, [particles]);
+
+ useFrame((_, rawDt) => {
+ if (paused) return;
+ const dt = Math.min(rawDt, 0.1);
+ clock.current += dt;
+ const m = owner.current;
+ const travelled = Math.hypot(m.x - last.current.x, m.z - last.current.z);
+ const moving = dt > 0 && travelled / dt > MOVING_SPEED && travelled < 4;
+ last.current.x = m.x; last.current.z = m.z;
+ stepGigiFlight(flight.current, {
+ targetX: m.x, targetZ: m.z, moving, mode, speaking, t: clock.current, dt, heading: m.heading, reduced,
+ }, pose);
+
+ if (root.current) root.current.position.set(pose.x, pose.y, pose.z);
+ if (body.current) {
+ body.current.rotation.set(pose.pitch, pose.yaw, pose.roll, "YXZ");
+ body.current.scale.setScalar(pose.scale);
+ }
+ tint.copy(GLOW_WARM).lerp(GLOW_SPEAK, speaking ? 1 : mode === "talk" ? 0.5 : 0);
+ if (halo.current) {
+ const material = halo.current.material as SpriteMaterial;
+ material.color.copy(tint);
+ material.opacity = 0.18 + 0.5 * pose.glow;
+ halo.current.scale.setScalar(0.75 + 0.35 * pose.glow);
+ }
+ if (emitter.current) {
+ const material = emitter.current.material as SpriteMaterial;
+ material.color.copy(tint);
+ material.opacity = 0.3 + 0.5 * pose.glow;
+ emitter.current.scale.setScalar(0.16 + 0.1 * pose.glow);
+ }
+ // A warm light that tints the floor and furniture around Gigi, brighter when it talks.
+ if (light.current) {
+ light.current.color.copy(tint);
+ light.current.intensity = reduced ? 0.5 : 0.45 + 0.9 * pose.glow;
+ }
+ // Three small orbs circle Gigi; they spin up while it speaks or works.
+ if (orbit.current) {
+ const spin = reduced ? 0 : speaking ? 3.2 : mode === "work" ? 2.2 : 1.1;
+ orbit.current.rotation.y += spin * dt;
+ orbit.current.rotation.z = 0.35 * Math.sin(clock.current * 0.7);
+ orbit.current.children.forEach((child, i) => {
+ const orb = child as Sprite;
+ (orb.material as SpriteMaterial).color.copy(tint);
+ orb.scale.setScalar(0.07 + 0.025 * Math.sin(clock.current * 3 + i * 2.1) + 0.03 * pose.glow);
+ });
+ }
+ if (shadow.current) {
+ const lift = Math.max(0, pose.y - 0.4);
+ (shadow.current.material as MeshBasicMaterial).opacity = Math.max(0.08, 0.34 - lift * 0.22);
+ shadow.current.position.set(pose.x, 0.012, pose.z);
+ shadow.current.scale.setScalar(0.85 + lift * 0.35);
+ }
+
+ // Sparkle trail: a fixed pool recycled round-robin, faded by age.
+ const { positions, colours, age, rise } = particles;
+ if (moving && !reduced && pose.speed > 0.1) {
+ emitDebt.current += dt * TRAIL_RATE;
+ while (emitDebt.current >= 1) {
+ emitDebt.current -= 1;
+ const i = particles.next;
+ particles.next = (i + 1) % TRAIL_SIZE;
+ positions[i * 3] = pose.x + (nextRandom(seed.current) - 0.5) * 0.12;
+ positions[i * 3 + 1] = pose.y + EMITTER_OFFSET + (nextRandom(seed.current) - 0.5) * 0.06;
+ positions[i * 3 + 2] = pose.z + (nextRandom(seed.current) - 0.5) * 0.12;
+ rise[i] = (nextRandom(seed.current) - 0.65) * 0.25;
+ age[i] = 0;
+ }
+ } else emitDebt.current = 0;
+ let alive = false;
+ for (let i = 0; i < TRAIL_SIZE; i++) {
+ if (age[i] >= TRAIL_LIFE_S) { colours[i * 3] = colours[i * 3 + 1] = colours[i * 3 + 2] = 0; continue; }
+ age[i] += dt;
+ positions[i * 3 + 1] += rise[i] * dt;
+ const fade = Math.max(0, 1 - age[i] / TRAIL_LIFE_S);
+ // Additive blending: fading the colour to black fades the sparkle out.
+ colours[i * 3] = SPARK.r * fade; colours[i * 3 + 1] = SPARK.g * fade; colours[i * 3 + 2] = SPARK.b * fade;
+ alive = true;
+ }
+ if (trail.current) trail.current.visible = alive;
+ if (alive) {
+ particles.geometry.attributes.position.needsUpdate = true;
+ particles.geometry.attributes.color.needsUpdate = true;
+ }
+ });
+
+ return (
+ <>
+ <group ref={root} position={[owner.current.x, pose.y, owner.current.z]}>
+ <sprite ref={halo} scale={0.9} renderOrder={1}>
+ <spriteMaterial map={textures.glow} color={GLOW_WARM} transparent opacity={0.35} blending={AdditiveBlending} depthWrite={false} />
+ </sprite>
+ <sprite ref={emitter} position={[0, EMITTER_OFFSET, 0]} scale={0.2} renderOrder={1}>
+ <spriteMaterial map={textures.glow} color={GLOW_WARM} transparent opacity={0.5} blending={AdditiveBlending} depthWrite={false} />
+ </sprite>
+ <pointLight ref={light} color={GLOW_WARM} intensity={0.6} distance={3.2} decay={2} />
+ <group ref={orbit}>
+ {[0, 1, 2].map((i) => (
+ <sprite key={i} position={[Math.cos((i / 3) * Math.PI * 2) * ORBIT_RADIUS_M, 0, Math.sin((i / 3) * Math.PI * 2) * ORBIT_RADIUS_M]} scale={0.08} renderOrder={2}>
+ <spriteMaterial map={textures.glow} color={GLOW_WARM} transparent opacity={0.9} blending={AdditiveBlending} depthWrite={false} />
+ </sprite>
+ ))}
+ </group>
+ <group ref={body}>
+ <group position={[0, MODEL_CENTRE_OFFSET, 0]}>
+ <ModelBoundary>
+ <Suspense fallback={null}><CompanionModel appearance={appearance} lead /></Suspense>
+ </ModelBoundary>
+ </group>
+ </group>
+ </group>
+ <mesh ref={shadow} geometry={particles.shadowGeometry} rotation={[-Math.PI / 2, 0, 0]} position={[owner.current.x, 0.012, owner.current.z]} renderOrder={1}>
+ <meshBasicMaterial map={textures.shadow} color="#000000" transparent opacity={0.3} depthWrite={false} />
+ </mesh>
+ <points ref={trail} geometry={particles.geometry} frustumCulled={false} visible={false} renderOrder={2}>
+ <pointsMaterial map={textures.glow} size={0.07} sizeAttenuation vertexColors transparent blending={AdditiveBlending} depthWrite={false} />
+ </points>
+ </>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsx
index d9aa63244a..04abbd6eb7 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsx
@@ -15,6 +15,9 @@ import { useT } from "@/i18n";
import type { SocietyAgent } from "../data";
import type { FigureDrive, FigureMode } from "../figures/FigureRig";
import { ToyFigure } from "./ToyFigure";
+import { GigiFlyer } from "./GigiFlyer";
+import type { GigiFlightMode } from "./gigiFlight";
+import { useEventStore } from "@/store/events";
import { SEAT_HEIGHT, toyLookFor } from "./toyFigureModel";
import { OFFICE } from "./officePalette";
import type { DeskSlot, OfficeLayout, Point } from "./officeLayout";
@@ -52,8 +55,16 @@ export function plateScale(distance: number): number {
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;
+/** Jarvis is not a person in the office: it is Gigi, flying at chest height. */
+function gigiModeFor(pose: Pose | null, travelling: boolean): GigiFlightMode {
+ if (travelling || !pose) return "idle";
+ if (pose === "sit" || pose === "work") return "work";
+ if (pose === "stand") return "idle";
+ return pose;
+}
+
+function Nameplate({ agent, activity, selected, onSelect, height = OFFICE_FIGURE_HEIGHT_M + 0.35 }: {
+ agent: SocietyAgent; activity: ActivityKind | null; selected: boolean; onSelect: (id: string) => void; height?: number;
}) {
const t = useT();
const plate = useRef<HTMLButtonElement>(null);
@@ -69,7 +80,7 @@ function Nameplate({ agent, activity, selected, onSelect }: {
});
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]}>
+ <group ref={anchor} position={[0, height, 0]}>
<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); }}
@@ -115,6 +126,9 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,
const summonKey = useRef("");
const [activity, setActivity] = useState<ActivityKind | null>(null);
const [seatHeight, setSeatHeight] = useState<number>(SEAT_HEIGHT.chair);
+ const isGigi = agent.tier === "lead";
+ const [gigiPose, setGigiPose] = useState<{ pose: Pose | null; travelling: boolean }>({ pose: null, travelling: false });
+ const speaking = useEventStore((s) => isGigi && s.voiceState === "speaking");
// Leaving the office releases the agent's spot and its registry entry.
useEffect(() => () => {
@@ -161,6 +175,7 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,
if (phase.current === "dwell") dwellUntil.current = now + next.dwellMs;
}
if (next.kind !== activity) setActivity(next.kind);
+ if (isGigi) setGigiPose({ pose: next.pose, travelling: phase.current === "travel" });
const nextSeat = seatHeightFor(next.kind);
if (nextSeat !== seatHeight) setSeatHeight(nextSeat);
}
@@ -169,7 +184,11 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,
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; }
+ if (arrived) {
+ phase.current = "dwell";
+ dwellUntil.current = now + p.dwellMs;
+ if (isGigi) setGigiPose({ pose: p.pose, travelling: false });
+ }
} else {
if (p.facing !== null) m.heading = turnToward(m.heading, p.facing, 8 * dt);
drive.current.mode = POSE_CLIP[p.pose];
@@ -183,7 +202,7 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,
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;
+ ring.current.visible = !isGigi && (phase.current === "dwell" || selected);
}
});
@@ -198,11 +217,13 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,
onClick={(event) => { event.stopPropagation(); onSelect(agent.agentId); }}
onPointerOver={() => { document.body.style.cursor = "pointer"; }}
onPointerOut={() => { document.body.style.cursor = ""; }}>
- <ToyFigure look={look} drive={drive} paused={!awake} heightM={OFFICE_FIGURE_HEIGHT_M} seatHeight={seatHeight} />
+ {!isGigi && <ToyFigure look={look} drive={drive} paused={!awake} heightM={OFFICE_FIGURE_HEIGHT_M} seatHeight={seatHeight} />}
</group>
- <Nameplate agent={agent} activity={activity} selected={selected} onSelect={onSelect} />
+ <Nameplate agent={agent} activity={activity} selected={selected} onSelect={onSelect} height={isGigi ? 1.75 : undefined} />
</group>
- <AgentFollower owner={group} appearance={pet} paused={!awake || reduced} lead={agent.tier === "lead"} clear={petClear} />
+ {isGigi
+ ? <GigiFlyer owner={mover} mode={gigiModeFor(gigiPose.pose, gigiPose.travelling)} speaking={speaking} paused={!awake} reduced={reduced} />
+ : <AgentFollower owner={group} appearance={pet} paused={!awake || reduced} clear={petClear} />}
</>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeCameraRig.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeCameraRig.tsx
index b9ba2fd9b9..d079d02919 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeCameraRig.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeCameraRig.tsx
@@ -12,7 +12,7 @@ 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";
+import { cameraView, player, useOfficeStore } from "./officeStore";
/** Where the camera starts: close behind the character, south-east, looking down. */
export const FOLLOW_DISTANCE = 15;
@@ -72,6 +72,12 @@ export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; ov
useFrame((_, rawDt) => {
const c = controls.current;
if (!c) return;
+ // Publish the view for the minimap: where the camera stands and which way it looks.
+ const lens = camera as unknown as { fov: number; aspect: number };
+ cameraView.x = camera.position.x; cameraView.z = camera.position.z;
+ cameraView.yaw = Math.atan2(c.target.x - camera.position.x, c.target.z - camera.position.z);
+ cameraView.halfWidth = Math.atan(Math.tan(((lens.fov ?? 35) * Math.PI) / 360) * (lens.aspect ?? 1.6));
+ cameraView.ready = true;
const dt = Math.min(rawDt, 0.1);
const store = useOfficeStore.getState();
if (store.zoom && store.zoom.seq !== lastZoom.current) {
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeMinimap.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeMinimap.tsx
new file mode 100644
index 0000000000..3d64ad0bd6
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeMinimap.tsx
@@ -0,0 +1,299 @@
+/**
+ * The office minimap: a north-up floor plan in the bottom-right corner.
+ *
+ * The static floor is drawn once into an offscreen canvas and only redrawn
+ * when the layout, the size, the pixel ratio or the theme changes. The moving
+ * layer (agents, the person's character, the camera's view) is painted over
+ * it at ~10 Hz from the per-frame module state (`agentPositions`, `player`),
+ * never from React state, and pauses while collapsed or the document is hidden.
+ *
+ * Click focuses the camera on a spot (or selects the agent under the pointer),
+ * double-click walks the character there.
+ */
+import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent as ReactMouseEvent, type PointerEvent as ReactPointerEvent } from "react";
+import { ChevronDown, ChevronUp } from "lucide-react";
+import { useT } from "@/i18n";
+import type { CheckpointKind, OfficeLayout, RoomKind } from "./officeLayout";
+import { player, useOfficeStore } from "./officeStore";
+import { agentPositions } from "./walkerRegistry";
+import {
+ agentAt, clampToRect, drawMinimapBase, drawMinimapDynamic, mapToWorld, minimapHeightFor, minimapTransform, placeAt,
+ resolveMinimapColours, worldToMap, type MapPoint, type MinimapAgentDot, type MinimapAgentState, type MinimapCamera,
+ type MinimapColours,
+} from "./minimap";
+
+export interface OfficeMinimapAgent { agentId: string; name: string; state: MinimapAgentState }
+
+export interface OfficeMinimapProps {
+ layout: OfficeLayout;
+ agents: ReadonlyMap<string, OfficeMinimapAgent>;
+ selectedId: string | null;
+ /** Optional live camera view (read at ~10 Hz); omit to hide the view wedge. */
+ camera?: () => MinimapCamera | null;
+}
+
+const MAP_WIDTH = 220;
+const PADDING = 6;
+const FRAME_MS = 100;
+const HIT_PX = 8;
+const STORAGE_KEY = "jarvis.office.minimap.collapsed";
+
+function readCollapsed(): boolean {
+ try {
+ return window.localStorage.getItem(STORAGE_KEY) === "1";
+ } catch {
+ // Storage blocked (private mode, sandboxed WebView): the map just starts expanded.
+ return false;
+ }
+}
+
+function writeCollapsed(collapsed: boolean): void {
+ try {
+ window.localStorage.setItem(STORAGE_KEY, collapsed ? "1" : "0");
+ } catch {
+ // Storage blocked: the choice lasts for this session only, which is harmless.
+ }
+}
+
+function pixelRatio(): number {
+ return typeof window !== "undefined" && window.devicePixelRatio > 0 ? window.devicePixelRatio : 1;
+}
+
+/** Bumps whenever light/dark mode may have changed: OS preference, or the app's class/data-theme on <html>. */
+function useThemeVersion(): number {
+ const [version, setVersion] = useState(0);
+ useEffect(() => {
+ const bump = () => setVersion((v) => v + 1);
+ const media = typeof window.matchMedia === "function" ? window.matchMedia("(prefers-color-scheme: dark)") : null;
+ media?.addEventListener?.("change", bump);
+ const observer = typeof MutationObserver === "function" ? new MutationObserver(bump) : null;
+ observer?.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "data-theme"] });
+ return () => {
+ media?.removeEventListener?.("change", bump);
+ observer?.disconnect();
+ };
+ }, []);
+ return version;
+}
+
+/** The device pixel ratio, refreshed when the window moves to another screen or zooms. */
+function usePixelRatio(): number {
+ const [dpr, setDpr] = useState(pixelRatio);
+ useEffect(() => {
+ const check = () => setDpr((prev) => (prev === pixelRatio() ? prev : pixelRatio()));
+ window.addEventListener("resize", check);
+ return () => window.removeEventListener("resize", check);
+ }, []);
+ return dpr;
+}
+
+interface Tooltip { x: number; y: number; text: string }
+
+export function OfficeMinimap({ layout, agents, selectedId, camera }: OfficeMinimapProps) {
+ const t = useT();
+ const [collapsed, setCollapsed] = useState(readCollapsed);
+ const [tooltip, setTooltip] = useState<Tooltip | null>(null);
+ const cardRef = useRef<HTMLDivElement>(null);
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+ const baseRef = useRef<HTMLCanvasElement | null>(null);
+ const coloursRef = useRef<MinimapColours | null>(null);
+ const themeVersion = useThemeVersion();
+ const dpr = usePixelRatio();
+
+ const height = useMemo(() => minimapHeightFor(layout.bounds, MAP_WIDTH, PADDING), [layout]);
+ const transform = useMemo(() => minimapTransform(layout.bounds, MAP_WIDTH, height, PADDING), [layout, height]);
+
+ // The render loop reads these through refs, so a roster refetch never restarts it.
+ const live = useRef({ agents, selectedId, camera, transform });
+ live.current = { agents, selectedId, camera, transform };
+
+ const dots = useCallback((): MinimapAgentDot[] => {
+ const out: MinimapAgentDot[] = [];
+ const { agents: roster, selectedId: sel } = live.current;
+ for (const agent of roster.values()) {
+ const pos = agentPositions.get(agent.agentId);
+ if (!pos) continue;
+ out.push({ id: agent.agentId, x: pos.x, z: pos.z, state: agent.state, selected: agent.agentId === sel });
+ }
+ return out;
+ }, []);
+
+ const draw = useCallback(() => {
+ const canvas = canvasRef.current;
+ const base = baseRef.current;
+ const colours = coloursRef.current;
+ const ctx = canvas?.getContext("2d");
+ if (!canvas || !ctx || !colours) return;
+ const { transform: tr, camera: cam } = live.current;
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ if (base) ctx.drawImage(base, 0, 0);
+ const ratio = canvas.width / tr.width;
+ ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
+ drawMinimapDynamic(ctx, tr, {
+ agents: dots(),
+ player: { x: player.x, z: player.z, heading: player.heading },
+ camera: cam ? cam() : null,
+ colours,
+ clear: false,
+ });
+ }, [dots]);
+
+ // Static layer: layout, size, pixel ratio or theme changed (or the map was just expanded).
+ useEffect(() => {
+ if (collapsed) return;
+ const canvas = canvasRef.current;
+ const card = cardRef.current;
+ if (!canvas || !card) return;
+ canvas.width = Math.round(MAP_WIDTH * dpr);
+ canvas.height = Math.round(height * dpr);
+ const style = getComputedStyle(card);
+ const colours = resolveMinimapColours((name) => style.getPropertyValue(name));
+ coloursRef.current = colours;
+ const base = document.createElement("canvas");
+ base.width = canvas.width;
+ base.height = canvas.height;
+ const ctx = base.getContext("2d");
+ if (!ctx) {
+ // No 2D canvas (headless test DOM): the card still renders, just without a picture.
+ baseRef.current = null;
+ return;
+ }
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+ drawMinimapBase(ctx, layout, transform, colours);
+ baseRef.current = base;
+ draw();
+ }, [collapsed, layout, transform, height, dpr, themeVersion, draw]);
+
+ // Moving layer at ~10 Hz; stops while collapsed or while the document is hidden.
+ useEffect(() => {
+ if (collapsed) return;
+ let raf = 0;
+ let last = 0;
+ const tick = (now: number) => {
+ raf = requestAnimationFrame(tick);
+ if (now - last < FRAME_MS) return;
+ last = now;
+ draw();
+ };
+ const start = () => { if (!raf && !document.hidden) raf = requestAnimationFrame(tick); };
+ const stop = () => { cancelAnimationFrame(raf); raf = 0; };
+ const onVisibility = () => (document.hidden ? stop() : start());
+ document.addEventListener("visibilitychange", onVisibility);
+ start();
+ return () => {
+ stop();
+ document.removeEventListener("visibilitychange", onVisibility);
+ };
+ }, [collapsed, draw]);
+
+ const toggle = () => {
+ setCollapsed((prev) => {
+ writeCollapsed(!prev);
+ return !prev;
+ });
+ setTooltip(null);
+ };
+
+ const mapPoint = (event: { clientX: number; clientY: number }): MapPoint | null => {
+ const canvas = canvasRef.current;
+ if (!canvas) return null;
+ const rect = canvas.getBoundingClientRect();
+ if (rect.width <= 0 || rect.height <= 0) return null;
+ return { x: ((event.clientX - rect.left) / rect.width) * MAP_WIDTH, y: ((event.clientY - rect.top) / rect.height) * height };
+ };
+
+ const onClick = (event: ReactMouseEvent<HTMLCanvasElement>) => {
+ const at = mapPoint(event);
+ if (!at) return;
+ const store = useOfficeStore.getState();
+ const hit = agentAt(transform, dots(), at, HIT_PX);
+ if (hit) {
+ store.select({ kind: "agent", id: hit.id });
+ store.focusOn({ x: hit.x, z: hit.z });
+ return;
+ }
+ store.focusOn(clampToRect(mapToWorld(transform, at), layout.floor));
+ };
+
+ const onDoubleClick = (event: ReactMouseEvent<HTMLCanvasElement>) => {
+ const at = mapPoint(event);
+ if (!at) return;
+ useOfficeStore.getState().requestWalk(clampToRect(mapToWorld(transform, at), layout.floor));
+ };
+
+ const checkpointLabels: Record<CheckpointKind, string> = {
+ create: t("society.office.cp_create"),
+ manage: t("society.office.cp_manage"),
+ team: t("society.office.cp_team"),
+ wardrobe: t("society.office.cp_wardrobe"),
+ lead: t("society.office.cp_lead"),
+ break: t("society.office.cp_break"),
+ };
+ const roomLabels: Record<RoomKind, string> = {
+ lead: t("society.office.room_lead"),
+ team: t("society.office.room_team"),
+ wardrobe: t("society.office.room_wardrobe"),
+ reception: t("society.office.room_reception"),
+ break: t("society.office.room_break"),
+ };
+ const youLabel = t("society.office.minimap_you");
+ const openSpace = t("society.office.open_space");
+
+ const onPointerMove = (event: ReactPointerEvent<HTMLCanvasElement>) => {
+ const at = mapPoint(event);
+ if (!at) return;
+ let text: string | null = null;
+ const hit = agentAt(transform, dots(), at, HIT_PX);
+ if (hit) {
+ text = agents.get(hit.id)?.name ?? null;
+ } else {
+ const me = worldToMap(transform, player);
+ if ((me.x - at.x) ** 2 + (me.y - at.y) ** 2 <= HIT_PX * HIT_PX) {
+ text = youLabel;
+ } else {
+ const place = placeAt(layout, mapToWorld(transform, at));
+ if (place?.kind === "checkpoint") text = checkpointLabels[place.id];
+ else if (place?.kind === "room") text = roomLabels[place.id];
+ else if (place?.kind === "department") text = place.label || openSpace;
+ }
+ }
+ setTooltip((prev) => {
+ if (!text) return null;
+ const next = { x: Math.round(at.x), y: Math.round(at.y), text };
+ return prev && prev.text === next.text && prev.x === next.x && prev.y === next.y ? prev : next;
+ });
+ };
+
+ let working = 0;
+ for (const agent of agents.values()) if (agent.state === "working") working += 1;
+ const summary = t("society.office.minimap_aria").replace("{0}", String(agents.size)).replace("{1}", String(working));
+ const title = t("society.office.minimap_title");
+
+ return (
+ <div ref={cardRef} className="office-hud office-card office-minimap" data-office-ui data-collapsed={collapsed ? "true" : "false"}>
+ <div className="office-minimap-head">
+ <span className="office-minimap-title">{title}</span>
+ <button type="button" className="office-icon-button office-minimap-toggle" onClick={toggle} aria-expanded={!collapsed}
+ aria-label={collapsed ? t("society.office.minimap_expand") : t("society.office.minimap_collapse")}
+ title={collapsed ? t("society.office.minimap_expand") : t("society.office.minimap_collapse")}>
+ {collapsed ? <ChevronUp aria-hidden size={14} /> : <ChevronDown aria-hidden size={14} />}
+ </button>
+ </div>
+ {!collapsed && (
+ <div className="office-minimap-map" style={{ width: MAP_WIDTH, height }}>
+ <canvas ref={canvasRef} className="office-minimap-canvas" role="img" aria-label={summary}
+ style={{ width: MAP_WIDTH, height }}
+ onClick={onClick} onDoubleClick={onDoubleClick} onPointerMove={onPointerMove} onPointerLeave={() => setTooltip(null)} />
+ {tooltip && (
+ // Flip to the pointer's left on the right half so the label never runs off the card.
+ <span className="office-minimap-tooltip" role="presentation" data-side={tooltip.x > MAP_WIDTH / 2 ? "left" : "right"}
+ style={{ left: tooltip.x > MAP_WIDTH / 2 ? tooltip.x - 10 : tooltip.x + 10, top: Math.max(tooltip.y - 8, 4) }}>
+ {tooltip.text}
+ </span>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx
index 4f9997bcb1..5db41a1f96 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx
@@ -21,7 +21,7 @@ import { CAMERA_FOV } from "./officeCamera";
import { ZOOM_SECONDS } from "./OfficeCameraRig";
import { useDeskChats } from "./useDeskChats";
import type { Point } from "./officeLayout";
-import { player, useOfficeStore } from "./officeStore";
+import { cameraView, player, useOfficeStore } from "./officeStore";
import { agentPositions, knownAgents, seatedAtDesk } from "./walkerRegistry";
import { loadProfile, playerLook, saveProfile, type PlayerProfile } from "./playerProfile";
import { AgentPanel, CheckpointPanel, type OfficeActions } from "./OfficePanels";
@@ -29,6 +29,8 @@ import type { WalkerContext } from "./OfficeAgents";
import { ownsKeyboard } from "./OfficePlayer";
import "./office.css";
import "./officeHud.css";
+import "./officeMinimap.css";
+import { OfficeMinimap } from "./OfficeMinimap";
// 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, __officeAgents: agentPositions, __officeSeated: seatedAtDesk,
@@ -242,6 +244,8 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
<kbd>E</kbd>{nearbyLabel}
</button>
)}
+ <OfficeMinimap layout={layout} agents={agents} selectedId={selection?.kind === "agent" ? selection.id : null}
+ camera={() => (cameraView.ready ? cameraView : null)} />
<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/ToyFigure.tsx b/jarvis/ui/web/frontend/src/components/society/office/ToyFigure.tsx
index ecb192d540..bb5446c933 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/ToyFigure.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/ToyFigure.tsx
@@ -31,10 +31,10 @@ import {
const HD = TOY.head;
const GEO = {
- sphere: new SphereGeometry(1, 22, 16),
- lowSphere: new SphereGeometry(1, 12, 8),
+ sphere: new SphereGeometry(1, 40, 28),
+ lowSphere: new SphereGeometry(1, 16, 12),
/** Upper half of a sphere, reaching slightly past the equator: hair caps and hats. */
- dome: new SphereGeometry(1, 22, 10, 0, Math.PI * 2, 0, Math.PI * 0.56),
+ dome: new SphereGeometry(1, 40, 18, 0, Math.PI * 2, 0, Math.PI * 0.56),
pelvis: new RoundedBoxGeometry(TOY.pelvis.w, TOY.pelvis.h, TOY.pelvis.d, 3, 0.05),
chest: new RoundedBoxGeometry(TOY.torso.w, TOY.torso.h - 0.02, TOY.torso.d, 3, 0.08),
thigh: new CapsuleGeometry(TOY.legRadius, 0.12, 4, 10),
@@ -87,6 +87,7 @@ function faceZ(x: number, y: number, inset = 0): number {
function Face({ look }: { look: ToyLook }) {
const skin = matte(look.skin);
const blush = matte(mix(look.skin, "#ff6f7d", 0.38));
+ const brow = matte(look.hairStyle === "bald" ? mix(look.skin, "#2a1a12", 0.55) : mix(look.hair, "#1a1210", 0.35));
const eyeY = HD.y - 0.03;
return (
<group>
@@ -100,14 +101,24 @@ function Face({ look }: { look: ToyLook }) {
</group>
);
})}
+ {/* Soft brows give the face an expression; hair-coloured, or a darker skin tone when bald. */}
+ {[-1, 1].map((sx) => {
+ const x = sx * 0.1;
+ const y = eyeY + 0.056;
+ return (
+ <mesh key={`w${sx}`} geometry={GEO.sphere} material={brow} position={[x, y, faceZ(x, y, 0.006)]}
+ rotation={[0, sx * 0.4, sx * -0.12]} scale={[0.036, 0.0095, 0.012]} />
+ );
+ })}
<mesh geometry={GEO.sphere} material={skin} position={[0, HD.y - 0.085, faceZ(0, HD.y - 0.085, 0.006)]} scale={[0.026, 0.021, 0.02]} />
<mesh geometry={GEO.smile} material={MOUTH} position={[0, HD.y - 0.115, faceZ(0, HD.y - 0.115, 0.004)]} rotation={[-0.25, 0, Math.PI]} />
{look.blush && [-1, 1].map((sx) => {
- const x = sx * 0.175;
- const y = HD.y - 0.095;
+ // Inside the face outline: further out, the cheek pokes past the head's silhouette.
+ const x = sx * 0.145;
+ const y = HD.y - 0.085;
return (
<mesh key={`b${sx}`} geometry={GEO.sphere} material={blush} position={[x, y, faceZ(x, y, 0.008)]}
- rotation={[0, sx * 0.62, 0]} scale={[0.045, 0.026, 0.012]} />
+ rotation={[0, sx * 0.5, 0]} scale={[0.04, 0.024, 0.012]} />
);
})}
{[-1, 1].map((sx) => (
@@ -118,10 +129,24 @@ function Face({ look }: { look: ToyLook }) {
}
/** Hair cap shared by most styles: a dome tilted back so the forehead shows. */
-function HairCap({ color, grow = 0 }: { color: string; grow?: number }) {
+/** Tufts along the hairline: a soft fringe instead of the hard rim of a bowl cut. */
+const FRINGE: Array<[number, number, number]> = [[-0.2, 0.075, -0.55], [-0.105, 0.098, -0.25], [0, 0.105, 0], [0.105, 0.098, 0.25], [0.2, 0.075, 0.55]];
+
+function HairCap({ color, grow = 0, fringe = true }: { color: string; grow?: number; fringe?: boolean }) {
+ const material = matte(color);
return (
- <mesh geometry={GEO.dome} material={matte(color)} position={[0, HD.y, 0]} rotation={[-0.4, 0, 0]}
- scale={[HD.rx + 0.018 + grow, HD.ry + 0.02 + grow, HD.rz + 0.02 + grow]} castShadow />
+ <group>
+ {/* Tilted back just enough to free the forehead; further and the crown shows skin. */}
+ <mesh geometry={GEO.dome} material={material} position={[0, HD.y + 0.01, -0.005]} rotation={[-0.5, 0, 0]}
+ scale={[HD.rx + 0.018 + grow, HD.ry + 0.03 + grow, HD.rz + 0.03 + grow]} castShadow />
+ {fringe && FRINGE.map(([x, dy, rz], i) => {
+ const y = HD.y + dy;
+ return (
+ <mesh key={i} geometry={GEO.sphere} material={material} position={[x, y, faceZ(x, y, -0.012)]}
+ rotation={[0.35, 0, rz]} scale={[0.085, 0.05, 0.045]} castShadow />
+ );
+ })}
+ </group>
);
}
@@ -208,8 +233,9 @@ function Hair({ style, look }: { style: HairStyle; look: ToyLook }) {
return (
<group>
<HairCap color={look.hair} />
- <mesh geometry={GEO.dome} material={cap} position={[0, HD.y + 0.035, 0]} rotation={[-0.12, 0, 0]}
- scale={[HD.rx + 0.022, HD.ry - 0.02, HD.rz + 0.03]} castShadow />
+ {/* Clearly larger than the hair cap underneath: equal shells z-fight and the hair flickers through. */}
+ <mesh geometry={GEO.dome} material={cap} position={[0, HD.y + 0.03, 0]} rotation={[-0.12, 0, 0]}
+ scale={[HD.rx + 0.045, HD.ry + 0.0, HD.rz + 0.05]} castShadow />
<mesh geometry={GEO.brim} material={cap} position={[0, HD.y + 0.07, HD.rz + 0.06]} rotation={[0.14, 0, 0]} castShadow />
<mesh geometry={GEO.lowSphere} material={cap} position={[0, HD.y + HD.ry + 0.01, -0.02]} scale={0.022} />
</group>
diff --git a/jarvis/ui/web/frontend/src/components/society/office/gigiFlight.test.ts b/jarvis/ui/web/frontend/src/components/society/office/gigiFlight.test.ts
new file mode 100644
index 0000000000..19acf29d83
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/gigiFlight.test.ts
@@ -0,0 +1,150 @@
+import { describe, expect, it } from "vitest";
+import {
+ createGigiFlight, createGigiPose, GIGI_HOVER_M, GIGI_MAX_LEAN, GIGI_MAX_Y, GIGI_MIN_Y, GIGI_SLEEP_HOVER_M,
+ stepGigiFlight, type GigiFlightMode,
+} from "./gigiFlight";
+
+const MODES: GigiFlightMode[] = ["idle", "work", "talk", "wave", "sleep"];
+const DT = 1 / 60;
+
+describe("gigi flight", () => {
+ it("stays between 0.6 and 1.5 m in every mode, speaking or not, at any frame rate", () => {
+ for (const mode of MODES) {
+ for (const speaking of [false, true]) {
+ for (const dt of [1 / 144, 1 / 30, 0.25]) {
+ const state = createGigiFlight(0, 0);
+ const pose = createGigiPose();
+ for (let t = 0; t < 20; t += dt) {
+ stepGigiFlight(state, { targetX: Math.sin(t) * 2, targetZ: 0, moving: t % 6 < 3, mode, speaking, t, dt }, pose);
+ expect(pose.y).toBeGreaterThanOrEqual(GIGI_MIN_Y);
+ expect(pose.y).toBeLessThanOrEqual(GIGI_MAX_Y);
+ expect(pose.glow).toBeGreaterThanOrEqual(0);
+ expect(pose.glow).toBeLessThanOrEqual(1);
+ expect(Number.isFinite(pose.x + pose.z + pose.yaw + pose.pitch + pose.roll + pose.scale)).toBe(true);
+ }
+ }
+ }
+ }
+ });
+
+ it("hovers at chest height, and sinks lower to sleep", () => {
+ const awake = createGigiFlight(0, 0);
+ const asleep = createGigiFlight(0, 0);
+ const sumAwake = { y: 0 }, sumAsleep = { y: 0 };
+ let n = 0;
+ for (let t = 0; t < 30; t += DT) {
+ const a = stepGigiFlight(awake, { targetX: 0, targetZ: 0, moving: false, mode: "idle", speaking: false, t, dt: DT });
+ const s = stepGigiFlight(asleep, { targetX: 0, targetZ: 0, moving: false, mode: "sleep", speaking: false, t, dt: DT });
+ if (t > 10) { sumAwake.y += a.y; sumAsleep.y += s.y; n++; }
+ }
+ expect(sumAwake.y / n).toBeCloseTo(GIGI_HOVER_M, 1);
+ expect(sumAsleep.y / n).toBeCloseTo(GIGI_SLEEP_HOVER_M, 1);
+ });
+
+ it("converges to a moved target without shooting more than 0.15 m past it", () => {
+ for (const dt of [1 / 144, DT, 1 / 20]) {
+ // A jump of 3 m (below the snap threshold) along +x.
+ const state = createGigiFlight(0, 0);
+ let maxPast = 0;
+ for (let t = 0; t < 6; t += dt) {
+ const pose = stepGigiFlight(state, { targetX: 3, targetZ: 0, moving: t < 2, mode: "work", speaking: false, t, dt });
+ maxPast = Math.max(maxPast, pose.x - 3);
+ }
+ expect(maxPast).toBeLessThanOrEqual(0.15);
+ expect(Math.abs(state.x - 3)).toBeLessThan(0.01);
+
+ // A walker going along an L-shaped path at walking pace, then stopping.
+ const walk = createGigiFlight(0, 0);
+ let pastX = 0, pastZ = 0;
+ for (let t = 0; t < 10; t += dt) {
+ const s = Math.min(t * 1.35, 6);
+ const tx = Math.min(s, 3), tz = Math.max(0, s - 3);
+ const pose = stepGigiFlight(walk, { targetX: tx, targetZ: tz, moving: s < 6, mode: "work", speaking: false, t, dt });
+ pastX = Math.max(pastX, pose.x - 3);
+ pastZ = Math.max(pastZ, pose.z - 3);
+ }
+ expect(pastX).toBeLessThanOrEqual(0.15);
+ expect(pastZ).toBeLessThanOrEqual(0.15);
+ expect(Math.hypot(walk.x - 3, walk.z - 3)).toBeLessThan(0.01);
+ }
+ });
+
+ it("snaps when the walker was re-placed far away", () => {
+ const state = createGigiFlight(0, 0);
+ stepGigiFlight(state, { targetX: 10, targetZ: -4, moving: false, mode: "idle", speaking: false, t: 0, dt: DT });
+ expect(state.x).toBe(10);
+ expect(state.z).toBe(-4);
+ });
+
+ it("faces the travel direction, leans forward and never over 15°", () => {
+ for (const [dx, dz] of [[1, 0], [0, 1], [-1, 0], [0.6, -0.8]] as const) {
+ const state = createGigiFlight(0, 0);
+ let pose = createGigiPose();
+ for (let t = 0; t < 3; t += DT) {
+ pose = stepGigiFlight(state, { targetX: dx * 1.35 * t, targetZ: dz * 1.35 * t, moving: true, mode: "idle", speaking: false, t, dt: DT }, pose);
+ expect(pose.pitch).toBeLessThanOrEqual(GIGI_MAX_LEAN + 1e-9);
+ }
+ const expected = Math.atan2(dx, dz);
+ expect(Math.abs(Math.atan2(Math.sin(pose.yaw - expected), Math.cos(pose.yaw - expected)))).toBeLessThan(0.05);
+ expect(pose.pitch).toBeGreaterThan(0.1);
+ }
+ });
+
+ it("banks into turns", () => {
+ const state = createGigiFlight(0, 0);
+ let minRoll = 0, maxRoll = 0;
+ // Circle counter-clockwise seen from above in x/z: yaw keeps increasing.
+ for (let t = 0; t < 4; t += DT) {
+ const a = t * 0.9;
+ const pose = stepGigiFlight(state, { targetX: Math.sin(a) * 1.5, targetZ: Math.cos(a) * 1.5 - 1.5, moving: true, mode: "idle", speaking: false, t, dt: DT });
+ minRoll = Math.min(minRoll, pose.roll); maxRoll = Math.max(maxRoll, pose.roll);
+ }
+ expect(minRoll).toBeLessThan(-0.02);
+ expect(maxRoll).toBeLessThan(0.02);
+ });
+
+ it("glows brighter when talking or speaking than when idle", () => {
+ const glowAfter = (mode: GigiFlightMode, speaking: boolean) => {
+ const state = createGigiFlight(0, 0);
+ let sum = 0, n = 0;
+ for (let t = 0; t < 8; t += DT) {
+ const pose = stepGigiFlight(state, { targetX: 0, targetZ: 0, moving: false, mode, speaking, t, dt: DT });
+ if (t > 4) { sum += pose.glow; n++; }
+ }
+ return sum / n;
+ };
+ expect(glowAfter("talk", false)).toBeGreaterThan(glowAfter("idle", false) + 0.2);
+ expect(glowAfter("idle", true)).toBeGreaterThan(glowAfter("idle", false) + 0.2);
+ expect(glowAfter("sleep", false)).toBeLessThan(glowAfter("idle", false));
+ });
+
+ it("reduced motion hovers statically on the target", () => {
+ const state = createGigiFlight(0, 0);
+ const pose = createGigiPose();
+ for (let t = 0; t < 3; t += DT) {
+ stepGigiFlight(state, { targetX: 1, targetZ: 2, moving: false, mode: "wave", speaking: true, t, dt: DT, heading: 1, reduced: true }, pose);
+ expect(pose.x).toBe(1);
+ expect(pose.z).toBe(2);
+ expect(pose.y).toBe(GIGI_HOVER_M);
+ expect(pose.yaw).toBeCloseTo(1);
+ expect(pose.pitch).toBe(0);
+ }
+ });
+
+ it("is deterministic and writes into the given pose", () => {
+ const run = () => {
+ const state = createGigiFlight(0.5, -1, 0.3);
+ const pose = createGigiPose();
+ const trace: number[] = [];
+ for (let i = 0; i < 600; i++) {
+ const t = i * DT;
+ const mode = MODES[Math.floor(t / 2) % MODES.length]!;
+ const returned = stepGigiFlight(state, { targetX: Math.cos(t) * 2, targetZ: Math.sin(t * 0.7), moving: i % 200 < 120, mode, speaking: i % 150 > 100, t, dt: DT }, pose);
+ expect(returned).toBe(pose);
+ trace.push(pose.x, pose.y, pose.z, pose.yaw, pose.pitch, pose.roll, pose.scale, pose.glow);
+ }
+ return trace;
+ };
+ expect(run()).toEqual(run());
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/office/gigiFlight.ts b/jarvis/ui/web/frontend/src/components/society/office/gigiFlight.ts
new file mode 100644
index 0000000000..01bda513ad
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/gigiFlight.ts
@@ -0,0 +1,241 @@
+/**
+ * Flight of Gigi, the lead agent's mascot, over the office floor. The lead is
+ * not drawn as a figure: Gigi hovers at chest/head height of the toy figures
+ * and follows the walker's ground position (x, z).
+ *
+ * Pure and deterministic: the same state and inputs give the same pose. With
+ * an `out` object a step allocates nothing, so it can run every frame.
+ */
+
+export type GigiFlightMode = "idle" | "work" | "talk" | "wave" | "sleep";
+
+export interface GigiFlightInput {
+ /** The walker's ground position; Gigi hovers above it. */
+ targetX: number;
+ targetZ: number;
+ /** True while the walker travels along a path. */
+ moving: boolean;
+ mode: GigiFlightMode;
+ /** The assistant is talking right now (voice output). */
+ speaking: boolean;
+ /** Seconds on a monotonic clock; drives bob, drift and hops. */
+ t: number;
+ /** Seconds since the last step. Clamped internally to 0.1 s. */
+ dt: number;
+ /** Facing to settle on while hovering in place (rotation about +y, 0 = +z). */
+ heading?: number;
+ /** Reduced motion: static hover, no bob, drift, hops or spins. */
+ reduced?: boolean;
+}
+
+export interface GigiFlightPose {
+ /** Body centre in world space. */
+ x: number;
+ y: number;
+ z: number;
+ /** Rotation about +y; 0 faces +z (the model's front). Includes happy spins. */
+ yaw: number;
+ /** Rotation about local x; positive tips the front down (leaning into travel). */
+ pitch: number;
+ /** Rotation about local z; banks into turns. */
+ roll: number;
+ /** Uniform scale multiplier around 1 (breathing, speaking pulse). */
+ scale: number;
+ /** Glow intensity, 0..1. */
+ glow: number;
+ /** Horizontal speed in m/s. */
+ speed: number;
+}
+
+export interface GigiFlightState {
+ x: number;
+ z: number;
+ vx: number;
+ vz: number;
+ /** Base hover height before bob/hops, spring-smoothed across modes. */
+ base: number;
+ vBase: number;
+ /** Smoothed facing without the spin offset. */
+ yaw: number;
+ pitch: number;
+ roll: number;
+ /** Extra yaw of a running happy spin, in [0, 2π); 0 = no spin. */
+ spin: number;
+ /** 0..1 blends so mode changes glide instead of jumping. */
+ idleBlend: number;
+ workBlend: number;
+ sleepBlend: number;
+ happyBlend: number;
+ glow: number;
+ scale: number;
+}
+
+/** Chest/head height of the 1.3 m toy figures. */
+export const GIGI_HOVER_M = 1.15;
+export const GIGI_SLEEP_HOVER_M = 0.8;
+export const GIGI_MIN_Y = 0.6;
+export const GIGI_MAX_Y = 1.5;
+/** Maximum forward lean (~15°). */
+export const GIGI_MAX_LEAN = (15 * Math.PI) / 180;
+const MAX_BANK = 0.35;
+/** Spring stiffness of horizontal follow; steady lag at walking pace is 2v/ω ≈ 0.4 m. */
+const FOLLOW_OMEGA = 6.5;
+const HEIGHT_OMEGA = 3.5;
+/** Farther than this and the walker was placed, not walked: re-place Gigi too. */
+const SNAP_DISTANCE_M = 4;
+/** Gigi never trails the walker by more than this (keeps it off walls at corners). */
+const MAX_LAG_M = 0.6;
+const LEAN_FULL_SPEED = 1.6;
+const SPIN_SECONDS = 0.9;
+const SPIN_PERIOD = 4.5;
+const TAU = Math.PI * 2;
+
+function wrap(angle: number): number {
+ let a = angle % TAU;
+ if (a <= -Math.PI) a += TAU;
+ else if (a > Math.PI) a -= TAU;
+ return a;
+}
+
+function clamp(value: number, min: number, max: number): number {
+ return value < min ? min : value > max ? max : value;
+}
+
+/** Frame-rate independent exponential approach factor. */
+function approach(rate: number, dt: number): number {
+ return 1 - Math.exp(-rate * dt);
+}
+
+export function createGigiFlight(x: number, z: number, heading = 0): GigiFlightState {
+ return {
+ x, z, vx: 0, vz: 0, base: GIGI_HOVER_M, vBase: 0, yaw: heading, pitch: 0, roll: 0, spin: 0,
+ idleBlend: 1, workBlend: 0, sleepBlend: 0, happyBlend: 0, glow: 0.35, scale: 1,
+ };
+}
+
+export function createGigiPose(): GigiFlightPose {
+ return { x: 0, y: GIGI_HOVER_M, z: 0, yaw: 0, pitch: 0, roll: 0, scale: 1, glow: 0.35, speed: 0 };
+}
+
+/**
+ * Exact critically damped spring step (no overshoot from rest, stable at any dt).
+ * Writes the new position to `result[0]` and velocity to `result[1]`.
+ */
+function springStep(position: number, velocity: number, target: number, omega: number, dt: number, result: [number, number]): void {
+ const offset = position - target;
+ const decay = Math.exp(-omega * dt);
+ const temp = (velocity + omega * offset) * dt;
+ result[0] = target + (offset + temp) * decay;
+ result[1] = (velocity - omega * temp) * decay;
+}
+
+const scratch: [number, number] = [0, 0];
+
+export function stepGigiFlight(state: GigiFlightState, input: GigiFlightInput, out?: GigiFlightPose): GigiFlightPose {
+ const pose = out ?? createGigiPose();
+ const dt = Number.isFinite(input.dt) ? clamp(input.dt, 0, 0.1) : 0;
+ const t = Number.isFinite(input.t) ? input.t : 0;
+ const reduced = input.reduced === true;
+ const { targetX, targetZ, mode } = input;
+ const happy = mode === "talk" || mode === "wave" || input.speaking;
+ const moving = input.moving;
+
+ // ---- Horizontal follow ------------------------------------------------
+ const px = state.x, pz = state.z;
+ const gap = Math.hypot(targetX - state.x, targetZ - state.z);
+ if (reduced || gap > SNAP_DISTANCE_M || !Number.isFinite(gap)) {
+ state.x = Number.isFinite(targetX) ? targetX : state.x;
+ state.z = Number.isFinite(targetZ) ? targetZ : state.z;
+ state.vx = 0; state.vz = 0;
+ } else if (dt > 0) {
+ springStep(state.x, state.vx, targetX, FOLLOW_OMEGA, dt, scratch);
+ state.x = scratch[0]; state.vx = scratch[1];
+ springStep(state.z, state.vz, targetZ, FOLLOW_OMEGA, dt, scratch);
+ state.z = scratch[0]; state.vz = scratch[1];
+ const lag = Math.hypot(state.x - targetX, state.z - targetZ);
+ if (lag > MAX_LAG_M) {
+ const k = MAX_LAG_M / lag;
+ state.x = targetX + (state.x - targetX) * k;
+ state.z = targetZ + (state.z - targetZ) * k;
+ }
+ }
+ const speed = dt > 0 ? Math.hypot(state.x - px, state.z - pz) / dt : 0;
+
+ // ---- Mode blends --------------------------------------------------------
+ const blend = approach(3, dt);
+ state.idleBlend += ((!moving && mode === "idle" && !input.speaking ? 1 : 0) - state.idleBlend) * blend;
+ state.workBlend += ((mode === "work" && !input.speaking ? 1 : 0) - state.workBlend) * blend;
+ state.sleepBlend += ((mode === "sleep" && !input.speaking ? 1 : 0) - state.sleepBlend) * blend;
+ state.happyBlend += ((happy ? 1 : 0) - state.happyBlend) * blend;
+
+ // ---- Height -------------------------------------------------------------
+ const baseTarget = mode === "sleep" && !input.speaking ? GIGI_SLEEP_HOVER_M : GIGI_HOVER_M;
+ if (reduced) { state.base = baseTarget; state.vBase = 0; }
+ else if (dt > 0) {
+ springStep(state.base, state.vBase, baseTarget, HEIGHT_OMEGA, dt, scratch);
+ state.base = scratch[0]; state.vBase = scratch[1];
+ }
+ let y = state.base;
+ let driftX = 0, driftZ = 0, wiggle = 0;
+ if (!reduced) {
+ const calm = 1 - state.sleepBlend;
+ // Gentle hover bob, ~0.06 m at 0.5 Hz; quieter while busy.
+ y += Math.sin(t * Math.PI) * 0.06 * calm * (1 - 0.6 * state.workBlend);
+ // Busy: small quick bobs as if typing along.
+ y += Math.sin(t * TAU * 2.4) * 0.018 * state.workBlend;
+ // Sleep: slow breathing.
+ y += Math.sin(t * TAU * 0.2) * 0.03 * state.sleepBlend;
+ // Happy hops.
+ y += Math.abs(Math.sin(t * Math.PI * 1.5)) * 0.07 * state.happyBlend;
+ // Idle: a slow figure-8 drift around the anchor.
+ const w = t * 0.45;
+ driftX = Math.sin(w) * 0.1 * state.idleBlend;
+ driftZ = Math.sin(2 * w) * 0.05 * state.idleBlend;
+ wiggle = Math.sin(t * 3.2) * 0.22 * state.happyBlend * (mode === "wave" ? 0 : 1);
+ }
+ y = clamp(y, GIGI_MIN_Y, GIGI_MAX_Y);
+
+ // ---- Facing, lean and bank ---------------------------------------------
+ const previousYaw = state.yaw;
+ if (moving && speed > 0.15 && !reduced) {
+ const travel = Math.atan2(state.x - px, state.z - pz);
+ state.yaw = wrap(state.yaw + wrap(travel - state.yaw) * approach(8, dt));
+ } else if (input.heading !== undefined && Number.isFinite(input.heading)) {
+ state.yaw = reduced ? wrap(input.heading) : wrap(state.yaw + wrap(input.heading - state.yaw) * approach(5, dt));
+ }
+ const yawRate = dt > 0 ? wrap(state.yaw - previousYaw) / dt : 0;
+ const leanTarget = reduced ? 0 : GIGI_MAX_LEAN * clamp(speed / LEAN_FULL_SPEED, 0, 1);
+ // Turning towards +x (yaw increasing) tips the top towards +x: negative roll.
+ const bankTarget = reduced ? 0 : clamp(-yawRate * clamp(speed, 0, 2) * 0.12, -MAX_BANK, MAX_BANK);
+ state.pitch += (leanTarget - state.pitch) * approach(6, dt);
+ state.roll += (bankTarget - state.roll) * approach(6, dt);
+
+ // ---- Happy spin (wave): one full turn every few seconds, always finished ----
+ if (reduced) state.spin = 0;
+ else if (state.spin > 0 || (mode === "wave" && !moving && t % SPIN_PERIOD < SPIN_SECONDS * 0.5)) {
+ state.spin += (dt * TAU) / SPIN_SECONDS;
+ if (state.spin >= TAU) state.spin = 0;
+ }
+
+ // ---- Glow and scale -----------------------------------------------------
+ let glowTarget = 0.35 + 0.15 * state.workBlend - 0.2 * state.sleepBlend + 0.4 * state.happyBlend;
+ let scaleTarget = 1;
+ if (!reduced) {
+ glowTarget += Math.sin(t * TAU * 2.4) * 0.06 * state.workBlend + Math.sin(t * TAU * 0.2) * 0.08 * state.sleepBlend;
+ scaleTarget += Math.sin(t * TAU * 0.2) * 0.03 * state.sleepBlend;
+ if (input.speaking) { glowTarget += 0.1 + Math.sin(t * 9) * 0.1; scaleTarget += 0.03 + Math.sin(t * 9) * 0.02; }
+ } else if (input.speaking) glowTarget += 0.1;
+ state.glow += (clamp(glowTarget, 0, 1) - state.glow) * (reduced ? 1 : approach(10, dt));
+ state.scale += (scaleTarget - state.scale) * (reduced ? 1 : approach(10, dt));
+
+ pose.x = state.x + driftX;
+ pose.y = y;
+ pose.z = state.z + driftZ;
+ pose.yaw = wrap(state.yaw + state.spin + wiggle);
+ pose.pitch = state.pitch;
+ pose.roll = state.roll;
+ pose.scale = state.scale;
+ pose.glow = clamp(state.glow, 0, 1);
+ pose.speed = speed;
+ return pose;
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/minimap.test.ts b/jarvis/ui/web/frontend/src/components/society/office/minimap.test.ts
new file mode 100644
index 0000000000..6e9976e959
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/minimap.test.ts
@@ -0,0 +1,155 @@
+import { describe, expect, it } from "vitest";
+import { buildOfficeLayout, type OfficeAgentInput } from "./officeLayout";
+import {
+ agentAt, clampToRect, drawMinimapBase, drawMinimapDynamic, mapToWorld, minimapHeightFor, minimapTransform, placeAt,
+ resolveMinimapColours, worldToMap,
+} from "./minimap";
+
+const agent = (id: string, provider: string, extra: Partial<OfficeAgentInput> = {}): OfficeAgentInput => ({
+ agentId: id, name: id, tier: "specialist", providerLabel: provider, state: "idle", createdMs: Number(id.replace(/\D/g, "")) || 0, ...extra,
+});
+
+/** A 2D context stand-in that records every call and property write, in order. */
+function recorder(): { ctx: CanvasRenderingContext2D; log: string[] } {
+ const log: string[] = [];
+ const state: Record<string, unknown> = {};
+ const ctx = new Proxy(state, {
+ get(target, prop: string) {
+ if (prop in target) return target[prop];
+ return (...args: unknown[]) => { log.push(`${prop}(${args.map((a) => (typeof a === "number" ? a.toFixed(1) : String(a))).join(",")})`); };
+ },
+ set(target, prop: string, value) {
+ target[prop] = value;
+ log.push(`${prop}=${String(value)}`);
+ return true;
+ },
+ });
+ return { ctx: ctx as unknown as CanvasRenderingContext2D, log };
+}
+
+const colours = resolveMinimapColours((name) => ({ "--success": "142 70% 45%", "--warning": "32 95% 34%" } as Record<string, string>)[name] ?? "");
+
+describe("minimap transform", () => {
+ const bounds = { minX: -10, maxX: 10, minZ: -20, maxZ: 20 };
+
+ it("keeps the aspect and centres the floor inside the padding", () => {
+ const t = minimapTransform(bounds, 220, 300, 10);
+ // Height limits: (300 - 20) / 40 = 7 px/m; width would allow 10 px/m.
+ expect(t.scale).toBeCloseTo(7);
+ const nw = worldToMap(t, { x: -10, z: -20 });
+ const se = worldToMap(t, { x: 10, z: 20 });
+ expect(nw.y).toBeCloseTo(10);
+ expect(se.y).toBeCloseTo(290);
+ expect(nw.x + se.x).toBeCloseTo(220); // centred horizontally
+ expect(se.x - nw.x).toBeCloseTo(140);
+ });
+
+ it("is north-up: +x goes right and +z (south) goes down", () => {
+ const t = minimapTransform(bounds, 200, 200);
+ const origin = worldToMap(t, { x: 0, z: 0 });
+ expect(worldToMap(t, { x: 1, z: 0 }).x).toBeGreaterThan(origin.x);
+ expect(worldToMap(t, { x: 0, z: 1 }).y).toBeGreaterThan(origin.y);
+ expect(origin).toEqual({ x: 100, y: 100 });
+ });
+
+ it("round-trips between world and map", () => {
+ const t = minimapTransform(bounds, 220, 260, 6);
+ for (const p of [{ x: 3.5, z: -7.25 }, { x: -10, z: 20 }, { x: 0, z: 0 }]) {
+ const back = mapToWorld(t, worldToMap(t, p));
+ expect(back.x).toBeCloseTo(p.x);
+ expect(back.z).toBeCloseTo(p.z);
+ }
+ });
+
+ it("sizes the map height by the floor aspect within limits", () => {
+ expect(minimapHeightFor(bounds, 220, 10)).toBe(300); // natural 420 clamps down
+ expect(minimapHeightFor({ minX: 0, maxX: 40, minZ: 0, maxZ: 30 }, 220, 10)).toBe(170);
+ expect(minimapHeightFor({ minX: 0, maxX: 100, minZ: 0, maxZ: 1 }, 220, 10)).toBe(110);
+ });
+
+ it("clamps a click on the railing onto the walkable floor", () => {
+ expect(clampToRect({ x: 50, z: -50 }, bounds)).toEqual({ x: 10, z: -20 });
+ });
+});
+
+describe("minimap hit testing", () => {
+ const t = minimapTransform({ minX: -10, maxX: 10, minZ: -10, maxZ: 10 }, 200, 200, 0); // 10 px/m
+ const agents = [{ id: "a", x: 0, z: 0 }, { id: "b", x: 0.5, z: 0 }, { id: "c", x: 5, z: 5 }];
+
+ it("picks the closest dot within the radius", () => {
+ expect(agentAt(t, agents, { x: 104, y: 100 })?.id).toBe("b");
+ expect(agentAt(t, agents, { x: 101, y: 101 })?.id).toBe("a");
+ expect(agentAt(t, agents, { x: 150, y: 157 }, 8)?.id).toBe("c");
+ });
+
+ it("returns null when nothing is within the radius", () => {
+ expect(agentAt(t, agents, { x: 150, y: 170 }, 8)).toBeNull();
+ });
+
+ it("names the place under a point: checkpoint, then room, then department", () => {
+ const layout = buildOfficeLayout([agent("a1", "codex"), agent("a2", "gemini")]);
+ const create = layout.checkpoints.find((c) => c.id === "create")!;
+ expect(placeAt(layout, create)).toEqual({ kind: "checkpoint", id: "create" });
+ const lead = layout.rooms.find((r) => r.kind === "lead")!;
+ expect(placeAt(layout, { x: lead.minX + 0.3, z: lead.minZ + 0.3 })).toEqual({ kind: "room", id: "lead" });
+ const dept = layout.departments[0];
+ expect(placeAt(layout, { x: dept.minX + 0.2, z: dept.minZ + 0.2 })).toEqual({ kind: "department", label: dept.label });
+ expect(placeAt(layout, { x: layout.bounds.minX + 0.01, z: 0 })).toBeNull();
+ });
+});
+
+describe("minimap drawing", () => {
+ const layout = buildOfficeLayout([agent("a1", "codex"), agent("a2", "codex", { state: "working" }), agent("l", "", { tier: "lead" })]);
+ const t = minimapTransform(layout.bounds, 220, minimapHeightFor(layout.bounds, 220));
+
+ it("reads theme tokens as hsl() colours with fallbacks", () => {
+ expect(colours.working).toBe("hsl(142 70% 45%)");
+ expect(colours.floor).toMatch(/^#/);
+ expect(colours.rooms.break).toMatch(/^#/);
+ });
+
+ it("draws the floor, every wall segment and one hexagon per checkpoint", () => {
+ const { ctx, log } = recorder();
+ drawMinimapBase(ctx, layout, t, colours);
+ expect(log[0]).toMatch(/^clearRect/);
+ expect(log.filter((l) => l.startsWith("moveTo")).length).toBe(layout.walls.length + layout.checkpoints.length);
+ expect(log.filter((l) => l.startsWith("closePath")).length).toBe(layout.checkpoints.length);
+ expect(log).toContain(`fillStyle=${colours.checkpoint}`);
+ expect(log).toContain(`fillStyle=${colours.rooms.lead}`);
+ expect(log[log.length - 1]).not.toMatch(/^globalAlpha=0/);
+ });
+
+ it("colours agents by state, rings the selected one and draws the player", () => {
+ const { ctx, log } = recorder();
+ drawMinimapDynamic(ctx, t, {
+ agents: [
+ { id: "w", x: 0, z: 0, state: "working", selected: false },
+ { id: "q", x: 1, z: 0, state: "waiting", selected: true },
+ { id: "i", x: 2, z: 0, state: "idle", selected: false },
+ { id: "p", x: 3, z: 0, state: "paused", selected: false },
+ ],
+ player: { x: 0, z: 2, heading: Math.PI },
+ camera: null,
+ colours,
+ });
+ expect(log).toContain(`fillStyle=${colours.working}`);
+ expect(log).toContain(`fillStyle=${colours.waiting}`);
+ expect(log).toContain(`fillStyle=${colours.idle}`);
+ expect(log).toContain(`strokeStyle=${colours.paused}`);
+ expect(log).toContain(`strokeStyle=${colours.selected}`);
+ expect(log).toContain(`fillStyle=${colours.player}`);
+ expect(log).not.toContain("clip()");
+ // Heading π looks north: the arrow tip lies above the player on the map.
+ const p = worldToMap(t, { x: 0, z: 2 });
+ const tip = log.filter((l) => l.startsWith("moveTo")).pop()!;
+ const [, y] = tip.slice("moveTo(".length, -1).split(",").map(Number);
+ expect(y).toBeLessThan(p.y);
+ });
+
+ it("draws the camera wedge clipped to the slab when a camera is given", () => {
+ const { ctx, log } = recorder();
+ drawMinimapDynamic(ctx, t, { agents: [], player: { x: 0, z: 0, heading: 0 }, camera: { x: 5, z: 5, yaw: -Math.PI * 0.75, halfWidth: 0.4 }, colours });
+ expect(log).toContain("clip()");
+ expect(log).toContain(`fillStyle=${colours.camera}`);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/office/minimap.ts b/jarvis/ui/web/frontend/src/components/society/office/minimap.ts
new file mode 100644
index 0000000000..2499534002
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/minimap.ts
@@ -0,0 +1,314 @@
+/**
+ * The office minimap as pure drawing code: a north-up plan of the floor with
+ * the agents, the person's character and (optionally) the camera's view.
+ *
+ * Map space is CSS pixels on the minimap canvas: +x right (east), +y down
+ * (south). The 3D camera looks from the south-east, but the map stays
+ * north-up so it reads like a floor plan. Nothing here touches the DOM, so
+ * the transform and hit-testing are unit-tested and the drawing takes any
+ * 2D context (the component's offscreen base canvas, or a test recorder).
+ */
+import { DEPARTMENT_TINTS, ROOM_FLOOR_COLOURS, CHECKPOINT_GOLD } from "./officePalette";
+import { DESK_SIZE, allDesks, roomAt, type CheckpointKind, type OfficeLayout, type Point, type Rect, type RoomKind } from "./officeLayout";
+
+export type MinimapAgentState = "idle" | "working" | "waiting" | "paused";
+
+export interface MinimapTransform {
+ /** Map pixels per metre. */
+ scale: number;
+ /** Map position of the world origin. */
+ offsetX: number;
+ offsetY: number;
+ width: number;
+ height: number;
+ bounds: Rect;
+}
+
+export interface MapPoint { x: number; y: number }
+
+export interface MinimapColours {
+ /** The slab outside the walkable floor (railing edge). */
+ slab: string;
+ floor: string;
+ outline: string;
+ wall: string;
+ desk: string;
+ /** Room fills per kind, drawn at `roomAlpha` over the floor. */
+ rooms: Record<RoomKind, string>;
+ roomAlpha: number;
+ /** Department carpet tints, indexed by `Department.tint` (wraps). */
+ carpets: readonly string[];
+ carpetAlpha: number;
+ checkpoint: string;
+ checkpointRim: string;
+ working: string;
+ waiting: string;
+ idle: string;
+ paused: string;
+ selected: string;
+ player: string;
+ playerRim: string;
+ camera: string;
+}
+
+export interface MinimapAgentDot extends Point { id: string; state: MinimapAgentState; selected: boolean }
+
+/**
+ * The camera's view on the floor: its ground position, the heading it looks
+ * along (same convention as the player: direction = (sin yaw, cos yaw), so
+ * 0 looks south) and the half-angle of the view in radians.
+ */
+export interface MinimapCamera extends Point { yaw: number; halfWidth: number }
+
+export interface MinimapDynamic {
+ agents: readonly MinimapAgentDot[];
+ player: Point & { heading: number };
+ camera: MinimapCamera | null;
+ colours: MinimapColours;
+ /** Clear the canvas first (default). Pass false to paint over a base already blitted into the same canvas. */
+ clear?: boolean;
+}
+
+/** Fit `bounds` into a widthPx × heightPx map with `padding` on every side, keeping the aspect and centring. */
+export function minimapTransform(bounds: Rect, widthPx: number, heightPx: number, padding = 6): MinimapTransform {
+ const bw = Math.max(1e-6, bounds.maxX - bounds.minX);
+ const bh = Math.max(1e-6, bounds.maxZ - bounds.minZ);
+ const innerW = Math.max(1, widthPx - padding * 2);
+ const innerH = Math.max(1, heightPx - padding * 2);
+ const scale = Math.min(innerW / bw, innerH / bh);
+ const offsetX = (widthPx - bw * scale) / 2 - bounds.minX * scale;
+ const offsetY = (heightPx - bh * scale) / 2 - bounds.minZ * scale;
+ return { scale, offsetX, offsetY, width: widthPx, height: heightPx, bounds };
+}
+
+/** Map height (CSS px) for a given width that keeps the floor's aspect, clamped to [minPx, maxPx]. */
+export function minimapHeightFor(bounds: Rect, widthPx: number, padding = 6, minPx = 110, maxPx = 300): number {
+ const bw = Math.max(1e-6, bounds.maxX - bounds.minX);
+ const bh = Math.max(1e-6, bounds.maxZ - bounds.minZ);
+ const natural = (widthPx - padding * 2) * (bh / bw) + padding * 2;
+ return Math.round(Math.min(maxPx, Math.max(minPx, natural)));
+}
+
+export function worldToMap(t: MinimapTransform, p: Point): MapPoint {
+ return { x: t.offsetX + p.x * t.scale, y: t.offsetY + p.z * t.scale };
+}
+
+export function mapToWorld(t: MinimapTransform, p: MapPoint): Point {
+ return { x: (p.x - t.offsetX) / t.scale, z: (p.y - t.offsetY) / t.scale };
+}
+
+/** Clamp a world point onto the walkable floor (a click on the railing still means "over there"). */
+export function clampToRect(p: Point, r: Rect): Point {
+ return { x: Math.min(r.maxX, Math.max(r.minX, p.x)), z: Math.min(r.maxZ, Math.max(r.minZ, p.z)) };
+}
+
+/** The agent whose dot is closest to `at` (map px) within `radiusPx`, or null. */
+export function agentAt<T extends Point & { id: string }>(t: MinimapTransform, agents: readonly T[], at: MapPoint, radiusPx = 8): T | null {
+ let best: T | null = null;
+ let bestD = radiusPx * radiusPx;
+ for (const agent of agents) {
+ const m = worldToMap(t, agent);
+ const d = (m.x - at.x) ** 2 + (m.y - at.y) ** 2;
+ if (d <= bestD) { best = agent; bestD = d; }
+ }
+ return best;
+}
+
+export type MinimapPlace =
+ | { kind: "checkpoint"; id: CheckpointKind }
+ | { kind: "room"; id: RoomKind }
+ | { kind: "department"; label: string };
+
+/** What lies under a world point: a checkpoint (within its radius) beats a room, a room beats a department. */
+export function placeAt(layout: OfficeLayout, p: Point): MinimapPlace | null {
+ for (const cp of layout.checkpoints) {
+ if ((cp.x - p.x) ** 2 + (cp.z - p.z) ** 2 <= cp.radius * cp.radius) return { kind: "checkpoint", id: cp.id };
+ }
+ const room = roomAt(layout, p);
+ if (room) return { kind: "room", id: room.kind };
+ const dept = layout.departments.find((d) => p.x >= d.minX && p.x <= d.maxX && p.z >= d.minZ && p.z <= d.maxZ);
+ return dept ? { kind: "department", label: dept.label } : null;
+}
+
+/** Theme colours for the map. `token(name)` returns a CSS custom property's raw value ("H S% L%"), or "". */
+export function resolveMinimapColours(token: (name: string) => string): MinimapColours {
+ const hsl = (name: string, fallback: string, alpha?: number): string => {
+ const raw = token(name).trim();
+ if (!raw) return fallback;
+ return alpha === undefined ? `hsl(${raw})` : `hsl(${raw} / ${alpha})`;
+ };
+ return {
+ slab: hsl("--muted", "#e5e7eb"),
+ floor: hsl("--card", "#ffffff"),
+ outline: hsl("--border", "#d4d4d8"),
+ wall: hsl("--foreground", "#171717", 0.7),
+ desk: hsl("--muted-foreground", "#737373", 0.75),
+ rooms: {
+ lead: ROOM_FLOOR_COLOURS.lead.base,
+ team: ROOM_FLOOR_COLOURS.team.base,
+ wardrobe: ROOM_FLOOR_COLOURS.wardrobe.base,
+ reception: ROOM_FLOOR_COLOURS.reception.base,
+ break: ROOM_FLOOR_COLOURS.break.base,
+ },
+ roomAlpha: 0.45,
+ carpets: DEPARTMENT_TINTS,
+ carpetAlpha: 0.35,
+ checkpoint: CHECKPOINT_GOLD.face,
+ checkpointRim: CHECKPOINT_GOLD.faceDeep,
+ working: hsl("--success", "#16a34a"),
+ waiting: hsl("--warning", "#d97706"),
+ idle: hsl("--muted-foreground", "#737373"),
+ paused: hsl("--muted-foreground", "#737373"),
+ selected: hsl("--accent", "#2563eb"),
+ player: CHECKPOINT_GOLD.ring,
+ playerRim: hsl("--background", "#ffffff"),
+ camera: hsl("--accent", "#2563eb", 0.16),
+ };
+}
+
+function fillRect(ctx: CanvasRenderingContext2D, t: MinimapTransform, r: Rect): void {
+ const a = worldToMap(t, { x: r.minX, z: r.minZ });
+ ctx.fillRect(a.x, a.y, (r.maxX - r.minX) * t.scale, (r.maxZ - r.minZ) * t.scale);
+}
+
+function hexagon(ctx: CanvasRenderingContext2D, cx: number, cy: number, r: number): void {
+ ctx.beginPath();
+ for (let i = 0; i < 6; i += 1) {
+ const a = (Math.PI / 3) * i;
+ const x = cx + Math.cos(a) * r;
+ const y = cy + Math.sin(a) * r;
+ if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
+ }
+ ctx.closePath();
+}
+
+/** The static floor: slab, floor, room fills, department carpets, desks, walls (with door gaps) and checkpoints. */
+export function drawMinimapBase(ctx: CanvasRenderingContext2D, layout: OfficeLayout, t: MinimapTransform, colours: MinimapColours): void {
+ ctx.clearRect(0, 0, t.width, t.height);
+ ctx.globalAlpha = 1;
+ ctx.fillStyle = colours.slab;
+ fillRect(ctx, t, layout.bounds);
+ ctx.fillStyle = colours.floor;
+ fillRect(ctx, t, layout.floor);
+
+ ctx.globalAlpha = colours.roomAlpha;
+ for (const room of layout.rooms) {
+ ctx.fillStyle = colours.rooms[room.kind];
+ fillRect(ctx, t, room);
+ }
+ ctx.globalAlpha = colours.carpetAlpha;
+ for (const dept of layout.departments) {
+ ctx.fillStyle = colours.carpets[dept.tint % Math.max(1, colours.carpets.length)] ?? colours.slab;
+ fillRect(ctx, t, dept);
+ }
+ ctx.globalAlpha = 1;
+
+ ctx.fillStyle = colours.desk;
+ for (const desk of allDesks(layout)) {
+ fillRect(ctx, t, { minX: desk.x - DESK_SIZE.w / 2, maxX: desk.x + DESK_SIZE.w / 2, minZ: desk.z - DESK_SIZE.d / 2, maxZ: desk.z + DESK_SIZE.d / 2 });
+ }
+
+ ctx.strokeStyle = colours.outline;
+ ctx.lineWidth = 1;
+ const f = worldToMap(t, { x: layout.floor.minX, z: layout.floor.minZ });
+ ctx.strokeRect(f.x + 0.5, f.y + 0.5, (layout.floor.maxX - layout.floor.minX) * t.scale - 1, (layout.floor.maxZ - layout.floor.minZ) * t.scale - 1);
+
+ // Walls come pre-split around their doors, so the gaps are simply not drawn.
+ ctx.strokeStyle = colours.wall;
+ ctx.lineWidth = Math.max(1, Math.min(2, t.scale * 0.2));
+ ctx.lineCap = "butt";
+ ctx.beginPath();
+ for (const w of layout.walls) {
+ const a = worldToMap(t, { x: w.x1, z: w.z1 });
+ const b = worldToMap(t, { x: w.x2, z: w.z2 });
+ ctx.moveTo(a.x, a.y);
+ ctx.lineTo(b.x, b.y);
+ }
+ ctx.stroke();
+
+ const hexR = Math.max(3, Math.min(5, t.scale * 0.55));
+ ctx.lineWidth = 1;
+ for (const cp of layout.checkpoints) {
+ const m = worldToMap(t, cp);
+ hexagon(ctx, m.x, m.y, hexR);
+ ctx.fillStyle = colours.checkpoint;
+ ctx.fill();
+ ctx.strokeStyle = colours.checkpointRim;
+ ctx.stroke();
+ }
+}
+
+/** Radius (map px) of an agent dot. */
+export const AGENT_DOT_PX = 3.2;
+
+/** The moving layer: camera wedge (under everything), agent dots, the selection ring and the player's arrow. */
+export function drawMinimapDynamic(ctx: CanvasRenderingContext2D, t: MinimapTransform, scene: MinimapDynamic): void {
+ const { colours } = scene;
+ if (scene.clear !== false) ctx.clearRect(0, 0, t.width, t.height);
+ ctx.globalAlpha = 1;
+
+ if (scene.camera) {
+ const c = scene.camera;
+ const origin = worldToMap(t, c);
+ const reach = Math.hypot(t.width, t.height) * 1.5;
+ const half = Math.max(0.05, Math.min(Math.PI / 2 - 0.05, c.halfWidth));
+ // World heading (sin, cos) maps onto map (x, y) directly: +x east → right, +z south → down.
+ const edge = (angle: number): MapPoint => ({ x: origin.x + Math.sin(angle) * reach, y: origin.y + Math.cos(angle) * reach });
+ const left = edge(c.yaw - half);
+ const right = edge(c.yaw + half);
+ ctx.save();
+ const b = worldToMap(t, { x: t.bounds.minX, z: t.bounds.minZ });
+ ctx.beginPath();
+ ctx.rect(b.x, b.y, (t.bounds.maxX - t.bounds.minX) * t.scale, (t.bounds.maxZ - t.bounds.minZ) * t.scale);
+ ctx.clip();
+ ctx.beginPath();
+ ctx.moveTo(origin.x, origin.y);
+ ctx.lineTo(left.x, left.y);
+ ctx.lineTo(right.x, right.y);
+ ctx.closePath();
+ ctx.fillStyle = colours.camera;
+ ctx.fill();
+ ctx.restore();
+ }
+
+ ctx.lineWidth = 1.5;
+ let selected: MapPoint | null = null;
+ for (const agent of scene.agents) {
+ const m = worldToMap(t, agent);
+ ctx.beginPath();
+ ctx.arc(m.x, m.y, AGENT_DOT_PX, 0, Math.PI * 2);
+ if (agent.state === "paused") {
+ ctx.strokeStyle = colours.paused;
+ ctx.stroke();
+ } else {
+ ctx.fillStyle = agent.state === "working" ? colours.working : agent.state === "waiting" ? colours.waiting : colours.idle;
+ ctx.fill();
+ }
+ if (agent.selected) selected = m;
+ }
+ if (selected) {
+ ctx.beginPath();
+ ctx.arc(selected.x, selected.y, AGENT_DOT_PX + 3, 0, Math.PI * 2);
+ ctx.strokeStyle = colours.selected;
+ ctx.lineWidth = 2;
+ ctx.stroke();
+ }
+
+ // The player: a gold arrow pointing along its heading.
+ const p = worldToMap(t, scene.player);
+ const dx = Math.sin(scene.player.heading);
+ const dy = Math.cos(scene.player.heading);
+ const len = 7;
+ const wing = 4.5;
+ ctx.beginPath();
+ ctx.moveTo(p.x + dx * len, p.y + dy * len);
+ ctx.lineTo(p.x - dx * len * 0.5 + dy * wing, p.y - dy * len * 0.5 - dx * wing);
+ ctx.lineTo(p.x - dx * len * 0.15, p.y - dy * len * 0.15);
+ ctx.lineTo(p.x - dx * len * 0.5 - dy * wing, p.y - dy * len * 0.5 + dx * wing);
+ ctx.closePath();
+ ctx.fillStyle = colours.player;
+ ctx.fill();
+ ctx.strokeStyle = colours.playerRim;
+ ctx.lineWidth = 1;
+ ctx.stroke();
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeMinimap.css b/jarvis/ui/web/frontend/src/components/society/office/officeMinimap.css
new file mode 100644
index 0000000000..8641f93bc0
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/officeMinimap.css
@@ -0,0 +1,13 @@
+/* Office minimap card: theme tokens only, so light and dark mode both work. The map picture reads the same tokens. */
+.office-minimap { right:14px; bottom:44px; display:flex; flex-direction:column; padding:4px 6px 6px; user-select:none; }
+.office-minimap[data-collapsed="true"] { padding-bottom:4px; }
+.office-minimap-head { display:flex; align-items:center; justify-content:space-between; gap:8px; padding:0 0 4px 4px; }
+.office-minimap[data-collapsed="true"] .office-minimap-head { padding-bottom:0; }
+.office-minimap-title { font-size:11px; font-weight:600; color:hsl(var(--muted-foreground)); }
+.office-minimap-toggle { display:inline-flex; align-items:center; justify-content:center; width:22px; height:22px; padding:0; }
+.office-minimap-map { position:relative; border-radius:8px; overflow:hidden; border:1px solid hsl(var(--border)); background:hsl(var(--background)); }
+.office-minimap-canvas { display:block; cursor:crosshair; touch-action:manipulation; }
+.office-minimap-tooltip { position:absolute; z-index:1; transform:translateY(-100%); padding:2px 7px; border-radius:6px; border:1px solid hsl(var(--border)); background:hsl(var(--popover)); color:hsl(var(--popover-foreground)); font-size:11px; font-weight:600; white-space:nowrap; max-width:180px; overflow:hidden; text-overflow:ellipsis; pointer-events:none; box-shadow:0 2px 8px rgb(0 0 0 / .2); }
+.office-minimap-tooltip[data-side="left"] { transform:translate(-100%, -100%); }
+@media (max-height:520px) { .office-minimap { display:none; } }
+@media (max-width:600px) { .office-minimap { display:none; } }
diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeStore.ts b/jarvis/ui/web/frontend/src/components/society/office/officeStore.ts
index e1188d5da1..546640cb09 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/officeStore.ts
+++ b/jarvis/ui/web/frontend/src/components/society/office/officeStore.ts
@@ -79,6 +79,9 @@ export const useOfficeStore = create<OfficeState>((set) => ({
requestWalk: (point) => set({ walkTo: { point, seq: ++seq }, follow: true }),
}));
+/** Where the camera looks on the floor, mutated by the camera rig every frame (for the minimap). */
+export const cameraView = { x: 0, z: 0, yaw: 0, halfWidth: 0.5, ready: false };
+
/** 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 };
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
index 526f8d7c72..70e1fc24e1 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
@@ -823,7 +823,12 @@
"hair_beanie": "Mütze",
"hair_cap": "Cap",
"hair_bald": "Glatze",
- "hair_label": "Frisur oder Kopfbedeckung"
+ "hair_label": "Frisur oder Kopfbedeckung",
+ "minimap_title": "Grundriss",
+ "minimap_expand": "Grundriss einblenden",
+ "minimap_collapse": "Grundriss ausblenden",
+ "minimap_aria": "Grundriss: {0} Agenten, {1} arbeiten",
+ "minimap_you": "Du"
}
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
index 55cc98e2b0..d53b30529c 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
@@ -823,7 +823,12 @@
"hair_beanie": "Beanie",
"hair_cap": "Cap",
"hair_bald": "Bald",
- "hair_label": "Hair or hat"
+ "hair_label": "Hair or hat",
+ "minimap_title": "Floor map",
+ "minimap_expand": "Show floor map",
+ "minimap_collapse": "Hide floor map",
+ "minimap_aria": "Floor map: {0} agents, {1} working",
+ "minimap_you": "You"
}
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
index f6bb297926..8ccd79dc3b 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
@@ -823,7 +823,12 @@
"hair_beanie": "Gorro",
"hair_cap": "Gorra",
"hair_bald": "Calvo",
- "hair_label": "Peinado o sombrero"
+ "hair_label": "Peinado o sombrero",
+ "minimap_title": "Plano de la planta",
+ "minimap_expand": "Mostrar plano",
+ "minimap_collapse": "Ocultar plano",
+ "minimap_aria": "Plano de la planta: {0} agentes, {1} trabajando",
+ "minimap_you": "Tú"
}
}
}