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): toy-style figures, symbol pets, live chat monitors and a faster walk

rubenluetke10-beep917e457bf10e
diff --git a/jarvis/ui/web/frontend/src/components/society/office/CheckpointMarker.tsx b/jarvis/ui/web/frontend/src/components/society/office/CheckpointMarker.tsx
index b9ce4b29c2..eff95492e6 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/CheckpointMarker.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/CheckpointMarker.tsx
@@ -11,6 +11,7 @@ import {
CircleGeometry, CylinderGeometry, DoubleSide, MeshStandardMaterial, Vector3,
type Group, type Mesh, type MeshBasicMaterial,
} from "three";
+import { useT } from "@/i18n";
import { plateScale } from "./OfficeAgents";
import { cachedCanvasTexture } from "./OfficeProps";
import type { Checkpoint } from "./officeLayout";
@@ -119,29 +120,38 @@ export function CheckpointMarker({ checkpoint, label, icon, active, animate, onA
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 t = useT();
+ const hint = t(`society.office.cp_${checkpoint.id}_hint`);
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;
+ const time = clock.elapsedTime + phase;
if (token.current) {
+ // Turn the icon face towards the camera (a full spin showed it edge-on half
+ // the time); animation only adds a gentle bob and sway around that.
+ const toCamera = Math.atan2(camera.position.x - checkpoint.x, camera.position.z - checkpoint.z);
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);
+ token.current.position.y = TOKEN_Y + Math.sin(time * 1.8) * 0.07;
+ const sway = Math.sin(time * (active ? 2.2 : 1.1)) * (active ? 0.45 : 0.3);
+ const goal = toCamera + sway;
+ // Ease towards the goal along the shorter way round, so orbiting never snaps it.
+ const diff = Math.atan2(Math.sin(goal - token.current.rotation.y), Math.cos(goal - token.current.rotation.y));
+ token.current.rotation.y += diff * Math.min(1, delta * 6);
} else {
token.current.position.y = TOKEN_Y;
- token.current.rotation.y = Math.PI / 4;
+ token.current.rotation.y = toCamera;
}
}
if (ring.current) {
const material = ring.current.material as MeshBasicMaterial;
- material.opacity = animate && active ? 0.75 + Math.sin(t * 4) * 0.2 : ringOpacity;
+ material.opacity = animate && active ? 0.75 + Math.sin(time * 4) * 0.2 : ringOpacity;
}
if (pulse.current) {
const material = pulse.current.material as MeshBasicMaterial;
if (animate && active) {
- const k = (t % 1.6) / 1.6;
+ const k = (time % 1.6) / 1.6;
pulse.current.visible = true;
pulse.current.scale.setScalar(1 + k * 0.35);
material.opacity = 0.6 * (1 - k);
@@ -199,9 +209,14 @@ export function CheckpointMarker({ checkpoint, label, icon, active, animate, onA
<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"}
+ aria-label={hint ? `${label}: ${hint}` : label} title={hint || undefined}
onClick={(event) => { event.stopPropagation(); onActivate(); }}>
<span className="office-checkpoint-badge"><IconSvg icon={icon} /></span>
- <span className="office-checkpoint-label">{label}</span>
+ <span className="office-checkpoint-text">
+ <span className="office-checkpoint-label">{label}</span>
+ {/* Up close, say what the place does, not only what it is called. */}
+ {active && hint ? <span className="office-checkpoint-hint">{hint}</span> : null}
+ </span>
</button>
</Html>
</group>
diff --git a/jarvis/ui/web/frontend/src/components/society/office/DeskInstances.tsx b/jarvis/ui/web/frontend/src/components/society/office/DeskInstances.tsx
index e2981c0397..622fa7e7a6 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/DeskInstances.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/DeskInstances.tsx
@@ -14,7 +14,7 @@ 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 CHAIR_Z = 0.62;
const rounded = (w: number, h: number, d: number, r: number) => new RoundedBoxGeometry(w, h, d, 2, r);
const PARTS: Part[] = [
@@ -25,7 +25,7 @@ const PARTS: Part[] = [
{ 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.box, material: MAT.keyboard, position: [0, 0.78, 0.24], 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 },
diff --git a/jarvis/ui/web/frontend/src/components/society/office/LiveMonitors.tsx b/jarvis/ui/web/frontend/src/components/society/office/LiveMonitors.tsx
new file mode 100644
index 0000000000..4002b307a7
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/LiveMonitors.tsx
@@ -0,0 +1,128 @@
+/**
+ * Desk monitors that show the seated agent's live chat. A click on a screen
+ * zooms the camera into it and then opens that agent's chat view.
+ */
+import { useEffect, useMemo, useRef } from "react";
+import { useFrame, type ThreeEvent } from "@react-three/fiber";
+import { CanvasTexture, SRGBColorSpace, type Mesh } from "three";
+import type { SocietyAgent } from "../data";
+import type { DeskSlot, Point } from "./officeLayout";
+import type { DeskChat } from "./useDeskChats";
+import type { ChatLineKind } from "./deskChat";
+import { seatedAtDesk } from "./walkerRegistry";
+
+const W = 512, H = 296;
+/** Same place as the instanced screen, a hair in front of it. */
+const SCREEN_Y = 1.18, SCREEN_Z = -0.2095, SCREEN_W = 0.66, SCREEN_H = 0.38;
+
+const PREFIX: Record<ChatLineKind, { mark: string; colour: string }> = {
+ user: { mark: "›", colour: "#93c5fd" },
+ agent: { mark: "●", colour: "#e2e8f0" },
+ tool: { mark: "⚙", colour: "#fcd34d" },
+ notice: { mark: "i", colour: "#a7f3d0" },
+ error: { mark: "!", colour: "#fca5a5" },
+};
+
+function wrap(ctx: CanvasRenderingContext2D, text: string, width: number): string[] {
+ const words = text.split(" ");
+ const rows: string[] = [];
+ let row = "";
+ for (const word of words) {
+ const next = row ? `${row} ${word}` : word;
+ if (ctx.measureText(next).width > width && row) { rows.push(row); row = word; } else row = next;
+ }
+ if (row) rows.push(row);
+ return rows;
+}
+
+export function drawChatScreen(ctx: CanvasRenderingContext2D, agent: Pick<SocietyAgent, "name" | "state">, chat: DeskChat | undefined): void {
+ ctx.fillStyle = "#0f1420";
+ ctx.fillRect(0, 0, W, H);
+ // Title bar: the agent and its state, like a chat window header.
+ ctx.fillStyle = "#1c2433";
+ ctx.fillRect(0, 0, W, 34);
+ ctx.fillStyle = agent.state === "working" ? "#4ade80" : agent.state === "waiting" ? "#fbbf24" : "#94a3b8";
+ ctx.beginPath(); ctx.arc(18, 17, 6, 0, Math.PI * 2); ctx.fill();
+ ctx.fillStyle = "#f8fafc";
+ ctx.font = "600 17px system-ui, -apple-system, 'Segoe UI', sans-serif";
+ ctx.textBaseline = "middle";
+ ctx.fillText(agent.name.length > 34 ? `${agent.name.slice(0, 33)}…` : agent.name, 32, 18);
+ ctx.font = "15px ui-monospace, 'Cascadia Mono', Menlo, Consolas, monospace";
+ ctx.textBaseline = "alphabetic";
+ const lineH = 19, left = 12, textLeft = 30, maxW = W - textLeft - 10;
+ // Lay out from the newest line upwards, so the latest message is always visible.
+ const rows: { colour: string; mark: string; text: string }[] = [];
+ const lines = chat?.lines ?? [];
+ if (lines.length === 0) rows.push({ colour: "#64748b", mark: "…", text: "" });
+ for (const line of lines) {
+ const p = PREFIX[line.kind];
+ wrap(ctx, line.text, maxW).slice(0, 4).forEach((text, i) => rows.push({ colour: p.colour, mark: i === 0 ? p.mark : "", text }));
+ }
+ const fit = Math.floor((H - 44) / lineH);
+ const visible = rows.slice(-fit);
+ visible.forEach((row, i) => {
+ const y = 44 + (i + 1) * lineH - 5;
+ ctx.fillStyle = row.colour;
+ ctx.fillText(row.mark, left, y);
+ ctx.fillText(row.text, textLeft, y);
+ });
+ // A blinking-style caret block at the bottom while working.
+ if (agent.state === "working") { ctx.fillStyle = "#4ade80"; ctx.fillRect(textLeft, H - 12, 9, 4); }
+}
+
+function Screen({ desk, agent, chat, onOpen }: {
+ desk: DeskSlot; agent: SocietyAgent; chat: DeskChat | undefined; onOpen: (agentId: string, screen: Point & { y: number }, facing: number) => void;
+}) {
+ const mesh = useRef<Mesh>(null);
+ const turn = desk.facing === "north" ? 0 : Math.PI;
+ const surface = useMemo(() => {
+ const canvas = typeof document !== "undefined" ? document.createElement("canvas") : null;
+ const ctx = canvas?.getContext("2d") ?? null;
+ if (!canvas || !ctx) return null;
+ canvas.width = W; canvas.height = H;
+ const texture = new CanvasTexture(canvas);
+ texture.colorSpace = SRGBColorSpace;
+ texture.anisotropy = 4;
+ return { ctx, texture };
+ }, []);
+ useEffect(() => () => surface?.texture.dispose(), [surface]);
+ useEffect(() => {
+ if (!surface) return;
+ drawChatScreen(surface.ctx, agent, chat);
+ surface.texture.needsUpdate = true;
+ }, [surface, agent.name, agent.state, chat]);
+ useFrame(() => {
+ if (mesh.current) mesh.current.visible = seatedAtDesk.has(agent.agentId);
+ });
+ if (!surface) return null;
+ // World position of the screen centre, for the zoom.
+ const sx = desk.x + Math.sin(turn) * SCREEN_Z, sz = desk.z + Math.cos(turn) * SCREEN_Z;
+ const click = (event: ThreeEvent<MouseEvent>) => {
+ if (event.delta > 6) return;
+ event.stopPropagation();
+ onOpen(agent.agentId, { x: sx, y: SCREEN_Y, z: sz }, turn);
+ };
+ return (
+ <group position={[desk.x, 0, desk.z]} rotation={[0, turn, 0]}>
+ <mesh ref={mesh} position={[0, SCREEN_Y, SCREEN_Z]} visible={false} onClick={click}
+ onPointerOver={() => { document.body.style.cursor = "zoom-in"; }} onPointerOut={() => { document.body.style.cursor = ""; }}>
+ <planeGeometry args={[SCREEN_W, SCREEN_H]} />
+ <meshBasicMaterial map={surface.texture} toneMapped={false} />
+ </mesh>
+ </group>
+ );
+}
+
+export function LiveMonitors({ desks, agents, chats, onOpen }: {
+ desks: DeskSlot[]; agents: ReadonlyMap<string, SocietyAgent>; chats: ReadonlyMap<string, DeskChat>;
+ onOpen: (agentId: string, screen: Point & { y: number }, facing: number) => void;
+}) {
+ return (
+ <group>
+ {desks.map((desk) => {
+ const agent = desk.agentId ? agents.get(desk.agentId) : undefined;
+ return agent ? <Screen key={desk.id} desk={desk} agent={agent} chat={chats.get(agent.agentId)} onOpen={onOpen} /> : 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.tsx
index 3454f7c7b3..d9aa63244a 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsx
@@ -13,35 +13,36 @@ 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, type FigureMode } from "../figures/FigureRig";
-import { shufflePalette, type FigureRecipe } from "../figures/figureRecipe";
+import type { FigureDrive, FigureMode } from "../figures/FigureRig";
+import { ToyFigure } from "./ToyFigure";
+import { SEAT_HEIGHT, toyLookFor } from "./toyFigureModel";
import { OFFICE } from "./officePalette";
import type { DeskSlot, OfficeLayout, Point } from "./officeLayout";
-import { findPath, type NavGrid } from "./officeNav";
+import { findPath, isWalkable, type NavGrid } from "./officeNav";
+import { AgentFollower } from "../companion/AgentFollower";
+import { resolveCompanion } from "../companion/appearance";
+import type { TrailPoint } from "../companion/trail";
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";
+import { agentPositions, seatedAtDesk } from "./walkerRegistry";
+
+/** The agent's symbol walks behind it as a little pet, about a fifth of its height. */
+export const PET_SIZE_M = 0.26;
+const PET_FOLLOW_M = 0.7;
/** 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. */
-export function fallbackRecipe(agentId: string): FigureRecipe {
- let hash = 0;
- for (const ch of agentId) hash = (hash * 31 + ch.charCodeAt(0)) >>> 0;
- return { contract: 1, archetype: "biped", base: "chibi", parts: {}, palette: shufflePalette((hash % 10_000) / 10_000) };
-}
-
/** 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" };
-/** 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;
+/** The seat-top height under a seated agent, per activity; the figure puts its hips exactly there. */
+export function seatHeightFor(kind: ActivityKind): number {
+ if (kind === "couch" || kind === "nap") return SEAT_HEIGHT.couch;
+ if (kind === "beanbag") return SEAT_HEIGHT.beanbag;
+ if (kind === "meeting") return SEAT_HEIGHT.meeting;
+ return SEAT_HEIGHT.chair;
}
/** Nameplate scale by camera distance: readable up close, compact in the overview, never huge. */
@@ -99,7 +100,7 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,
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]);
+ const look = useMemo(() => toyLookFor(agent.figure, agent.agentId), [agent.figure, agent.agentId]);
const group = useRef<Group>(null);
const body = useRef<Group>(null);
const ring = useRef<Mesh>(null);
@@ -113,9 +114,19 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,
const planState = useRef("");
const summonKey = useRef("");
const [activity, setActivity] = useState<ActivityKind | null>(null);
+ const [seatHeight, setSeatHeight] = useState<number>(SEAT_HEIGHT.chair);
// 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]);
+ useEffect(() => () => {
+ ctx.book.release(agent.agentId);
+ agentPositions.delete(agent.agentId);
+ seatedAtDesk.delete(agent.agentId);
+ }, [ctx.book, agent.agentId]);
+ const pet = useMemo(() => ({ ...resolveCompanion(agent.agentId, agent.figure?.companion), sizeM: PET_SIZE_M, followDistanceM: PET_FOLLOW_M }),
+ [agent.agentId, agent.figure?.companion]);
+ const petClear = useMemo(() => (point: TrailPoint, radius: number) =>
+ isWalkable(ctx.grid, { x: point[0] - radius, z: point[2] }) && isWalkable(ctx.grid, { x: point[0] + radius, z: point[2] })
+ && isWalkable(ctx.grid, { x: point[0], z: point[2] - radius }) && isWalkable(ctx.grid, { x: point[0], z: point[2] + radius }), [ctx.grid]);
useFrame((_, rawDt) => {
const dt = Math.min(rawDt, 0.1);
@@ -150,9 +161,10 @@ 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);
+ const nextSeat = seatHeightFor(next.kind);
+ if (nextSeat !== seatHeight) setSeatHeight(nextSeat);
}
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";
@@ -162,11 +174,12 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,
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 (phase.current === "dwell" && (p.kind === "work" || p.kind === "desk")) seatedAtDesk.add(agent.agentId);
+ else seatedAtDesk.delete(agent.agentId);
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 (body.current) body.current.rotation.y = m.heading;
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;
@@ -175,6 +188,7 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,
});
return (
+ <>
<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]} />
@@ -184,10 +198,12 @@ 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 = ""; }}>
- <FigureRig recipe={recipe} drive={drive} paused={!awake} heightM={OFFICE_FIGURE_HEIGHT_M} />
+ <ToyFigure look={look} drive={drive} paused={!awake} heightM={OFFICE_FIGURE_HEIGHT_M} seatHeight={seatHeight} />
</group>
<Nameplate agent={agent} activity={activity} selected={selected} onSelect={onSelect} />
</group>
+ <AgentFollower owner={group} appearance={pet} paused={!awake || reduced} lead={agent.tier === "lead"} 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 b540e8d38b..b9ba2fd9b9 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeCameraRig.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeCameraRig.tsx
@@ -17,6 +17,8 @@ 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;
+/** How long the dive into a monitor takes before the chat opens. */
+export const ZOOM_SECONDS = 0.9;
export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; overview: number }) {
const controls = useRef<OrbitControlsImpl>(null);
@@ -25,6 +27,10 @@ export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; ov
const gl = useThree((s) => s.gl);
const scene = useThree((s) => s.scene);
const lastFocus = useRef(0);
+ const lastZoom = useRef(0);
+ const backOff = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
+ useEffect(() => () => clearTimeout(backOff.current), []);
+ const dive = useRef<{ fromEye: Vector3; toEye: Vector3; fromTarget: Vector3; toTarget: Vector3; t: number } | null>(null);
const flight = useRef<{ from: Vector3; to: Vector3; t: number } | null>(null);
const desired = useRef(new Vector3());
const delta = useRef(new Vector3());
@@ -68,6 +74,34 @@ export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; ov
if (!c) return;
const dt = Math.min(rawDt, 0.1);
const store = useOfficeStore.getState();
+ if (store.zoom && store.zoom.seq !== lastZoom.current) {
+ lastZoom.current = store.zoom.seq;
+ flight.current = null;
+ dive.current = { fromEye: camera.position.clone(), toEye: new Vector3(...store.zoom.eye),
+ fromTarget: c.target.clone(), toTarget: new Vector3(...store.zoom.target), t: 0 };
+ // Orbit limits (minimum distance, pitch) would stop the camera short of the glass.
+ c.enabled = false;
+ }
+ if (dive.current) {
+ // Dive: eye and target travel together into the monitor, easing in at the end.
+ const d = dive.current;
+ d.t = Math.min(1, d.t + dt / ZOOM_SECONDS);
+ const ease = 1 - (1 - d.t) ** 3;
+ camera.position.lerpVectors(d.fromEye, d.toEye, ease);
+ c.target.lerpVectors(d.fromTarget, d.toTarget, ease);
+ camera.lookAt(c.target);
+ if (d.t >= 1) {
+ dive.current = null;
+ // If the chat does not take over (no handler), hand the camera back a step away.
+ backOff.current = setTimeout(() => {
+ const away = camera.position.clone().sub(c.target).setLength(CAMERA_LIMITS.minDistance + 1);
+ camera.position.copy(c.target).add(away);
+ c.enabled = true;
+ c.update();
+ }, 1500);
+ }
+ return;
+ }
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 };
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeFurniture.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeFurniture.tsx
index 18b3c54c6a..d2e2292e3a 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeFurniture.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeFurniture.tsx
@@ -101,7 +101,7 @@ export function Desk({ face }: { face: ScreenFace }) {
<mesh position={[0, 1.18, -0.212]} material={screenMaterial(face)}>
<planeGeometry args={[0.66, 0.38]} />
</mesh>
- <Box size={[0.42, 0.02, 0.14]} position={[0, 0.78, 0.1]} material={MAT.keyboard} />
+ <Box size={[0.42, 0.02, 0.14]} position={[0, 0.78, 0.24]} material={MAT.keyboard} />
<Chair />
</group>
);
@@ -110,7 +110,7 @@ export function Desk({ face }: { face: ScreenFace }) {
/** Office swivel chair behind the desk (local +z side). */
export function Chair() {
return (
- <group position={[0, 0, 0.72]}>
+ <group position={[0, 0, 0.62]}>
<mesh geometry={GEO.cyl} material={MAT.chair} position={[0, 0.03, 0]} scale={[0.3, 0.04, 0.3]} castShadow />
<mesh geometry={GEO.cyl} material={MAT.chair} position={[0, 0.25, 0]} scale={[0.03, 0.42, 0.03]} />
<Rounded size={[0.5, 0.08, 0.48]} radius={0.03} position={[0, 0.48, 0]} material={MAT.chairSeat} />
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficePanels.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficePanels.tsx
index 177dac762a..99b8c5a3b3 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficePanels.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficePanels.tsx
@@ -4,7 +4,7 @@
* 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 { useEffect, useId, useRef, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useT } from "@/i18n";
import { createSocietyChatGroup, useSocietyChatGroups } from "@/lib/societyChatGroups";
@@ -12,7 +12,7 @@ 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";
+import { HAIR_STYLES, playerLook, withHairStyle, withShuffledColours, type PlayerProfile } from "./playerProfile";
/** How long called or gathered agents stay before they drift back to their day. */
const CALL_MS = 25_000;
@@ -30,11 +30,16 @@ function StateDot({ state }: { state: SocietyAgent["state"] }) {
function PanelShell({ title, subtitle, onClose, children }: { title: string; subtitle?: string; onClose: () => void; children: React.ReactNode }) {
const t = useT();
+ const headingId = useId();
+ const panel = useRef<HTMLElement>(null);
+ // Move focus into a freshly opened panel so keyboard and screen-reader users
+ // land on it; walking keys keep working because they listen on the window.
+ useEffect(() => { panel.current?.focus({ preventScroll: true }); }, [title]);
return (
- <aside className="office-card office-panel" data-office-ui aria-label={title}>
+ <aside ref={panel} className="office-card office-panel" data-office-ui aria-labelledby={headingId} tabIndex={-1}>
<header className="office-panel-head">
<div>
- <strong>{title}</strong>
+ <h2 id={headingId}>{title}</h2>
{subtitle ? <span>{subtitle}</span> : null}
</div>
<button type="button" className="office-icon-button" onClick={onClose} aria-label={t("society.office.close")}>×</button>
@@ -55,19 +60,27 @@ export function AgentPanel({ agent, actions, onClose }: { agent: SocietyAgent; a
const store = useOfficeStore();
const inDraft = store.teamDraft.includes(agent.agentId);
const where = agentPositions.get(agent.agentId);
+ const [called, setCalled] = useState(false);
+ // A new agent in the same panel starts without the previous "coming over" note.
+ useEffect(() => setCalled(false), [agent.agentId]);
+ const subtitle = agent.title || agent.providerLabel;
return (
- <PanelShell title={agent.name} subtitle={agent.title || agent.providerLabel} onClose={onClose}>
+ <PanelShell title={agent.name} subtitle={subtitle} 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>
+ {agent.providerLabel && agent.providerLabel !== subtitle ? <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" onClick={() => {
+ store.summon([agent.agentId], { x: player.x, z: player.z }, CALL_MS);
+ setCalled(true);
+ }}>{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>
+ {called && <p className="office-hint" role="status">{t("society.office.call_sent").replace("{0}", agent.name)}</p>}
{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))}
@@ -94,20 +107,23 @@ function ManagePanel({ agents, actions }: { agents: SocietyAgent[]; actions: Off
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>
+ {agents.length === 0 ? <p className="office-note-inline">{t("society.office.manage_empty")}</p> : (
+ <ul className="office-list">
+ {agents.map((agent) => (
+ <li key={agent.agentId}>
+ <StateDot state={agent.state} />
+ <span className="office-list-name" title={agent.name}>{agent.name}</span>
+ <button type="button" className="office-mini" aria-label={t("society.office.show_agent").replace("{0}", agent.name)} 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" aria-label={t("society.office.open_agent").replace("{0}", agent.name)}
+ 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>
</>
);
@@ -126,7 +142,8 @@ function TeamPanel({ agents, layout, sample, actions }: { agents: SocietyAgent[]
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("");
+ if (!canCreate) return;
+ setBusy(true); setError(""); setCreated(null);
try {
const names = members.map((id) => agents.find((a) => a.agentId === id)?.name ?? id);
const group = await createSocietyChatGroup(name.trim() || names.join(" + "), members);
@@ -147,21 +164,25 @@ function TeamPanel({ agents, layout, sample, actions }: { agents: SocietyAgent[]
{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")} />
+ <input value={name} maxLength={60} onChange={(e) => setName(e.target.value)} placeholder={t("society.office.team_name_placeholder")}
+ onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); void create(); } }} />
</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()}>
+ {agents.length === 0 ? <p className="office-note-inline">{t("society.office.manage_empty")}</p> : (
+ <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" title={agent.name}>{agent.name}</span>
+ </label>
+ </li>
+ ))}
+ </ul>
+ )}
+ <button type="button" className="office-action office-action-primary" disabled={!canCreate} aria-busy={busy} onClick={() => void create()}>
{t("society.office.team_create").replace("{0}", String(members.length))}
</button>
+ {!sample && members.length < 2 && agents.length >= 2 && <p className="office-hint">{t("society.office.team_need_more")}</p>}
{error && <p role="alert" className="office-error">{error}</p>}
{created && (
<p className="office-success" role="status">
@@ -175,9 +196,11 @@ function TeamPanel({ agents, layout, sample, actions }: { agents: SocietyAgent[]
<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>}
+ <span className="office-list-name" title={group.name}>{group.name}</span>
+ <button type="button" className="office-mini" aria-label={t("society.office.team_gather_label").replace("{0}", group.name)}
+ onClick={() => store.summon(group.members, table, CALL_MS)}>{t("society.office.team_gather")}</button>
+ {actions.onOpenGroup && <button type="button" className="office-mini" aria-label={t("society.office.team_open_label").replace("{0}", group.name)}
+ onClick={() => actions.onOpenGroup?.(group.group_id)}>{t("society.office.action_open")}</button>}
</li>
))}
</ul>
@@ -189,17 +212,20 @@ function TeamPanel({ agents, layout, sample, actions }: { agents: SocietyAgent[]
function WardrobePanel({ profile, onProfile }: { profile: PlayerProfile; onProfile: (next: PlayerProfile) => void }) {
const t = useT();
+ const bodiesId = useId();
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 })} />
+ <input value={profile.name} maxLength={40} placeholder={t("society.office.you")} autoComplete="off" spellCheck={false}
+ onChange={(e) => onProfile({ ...profile, name: e.target.value })} />
+ <span>{t("society.office.wardrobe_saved")}</span>
</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)}
+ <p className="office-subhead" id={bodiesId}>{t("society.office.wardrobe_body")}</p>
+ <div className="office-chips" role="group" aria-labelledby={bodiesId}>
+ {HAIR_STYLES.map((style) => (
+ <button key={style} type="button" className="office-chip" aria-pressed={playerLook(profile).hairStyle === style} onClick={() => onProfile(withHairStyle(profile, style))}>
+ {t(`society.office.hair_${style}`)}
</button>
))}
</div>
@@ -211,16 +237,25 @@ function WardrobePanel({ profile, onProfile }: { profile: PlayerProfile; onProfi
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>;
+ // The lead office seats up to two leads (officeLayout, arrival order); offer both.
+ const leads = agents.filter((a) => a.tier === "lead")
+ .sort((a, b) => a.createdMs - b.createdMs || a.agentId.localeCompare(b.agentId)).slice(0, 2);
+ if (leads.length === 0) return <p>{t("society.office.lead_empty")}</p>;
+ const named = (action: string, name: string) => (leads.length > 1 ? `${action}: ${name}` : undefined);
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>
+ {leads.map((lead) => (
+ <div key={lead.agentId}>
+ <p className="office-panel-status"><StateDot state={lead.state} />{lead.name} · {t(`society.office.state_${lead.state}`)}</p>
+ <div className="office-actions">
+ <button type="button" className="office-action office-action-primary" aria-label={named(t("society.office.action_chat"), lead.name)}
+ onClick={() => actions.onOpenAgent(lead.agentId)}>{t("society.office.action_chat")}</button>
+ <button type="button" className="office-action" aria-label={named(t("society.office.action_call"), lead.name)}
+ onClick={() => store.summon([lead.agentId], { x: player.x, z: player.z }, CALL_MS)}>{t("society.office.action_call")}</button>
+ </div>
+ </div>
+ ))}
</>
);
}
@@ -229,14 +264,23 @@ function BreakPanel({ agents, layout }: { agents: SocietyAgent[]; layout: Office
const t = useT();
const store = useOfficeStore();
const idle = agents.filter((a) => a.state === "idle");
+ const [called, setCalled] = useState(0);
+ // Calls expire on their own (CALL_MS); only a live one is worth releasing.
+ const now = Date.now();
+ const anyoneCalled = Object.values(store.summons).some((summon) => summon.untilMs > now);
return (
<>
- <p>{t("society.office.break_body").replace("{0}", String(idle.length))}</p>
+ <p>{idle.length > 0 ? t("society.office.break_body").replace("{0}", String(idle.length)) : t("society.office.break_none")}</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>
+ onClick={() => {
+ store.summon(idle.map((a) => a.agentId), spotCentre(layout, "couch"), CALL_MS);
+ setCalled(idle.length);
+ }}>{t("society.office.break_call")}</button>
+ <button type="button" className="office-action" disabled={!anyoneCalled}
+ onClick={() => { store.clearSummons(); setCalled(0); }}>{t("society.office.break_release")}</button>
</div>
+ {called > 0 && anyoneCalled && <p className="office-hint" role="status">{t("society.office.break_called").replace("{0}", String(called))}</p>}
</>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx
index 048ddea8f7..59266c6cbd 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx
@@ -7,15 +7,20 @@ 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 type { FigureDrive } from "../figures/FigureRig";
+import { ToyFigure } from "./ToyFigure";
+import type { ToyLook } from "./toyFigureModel";
import { findPath, isWalkable, nearestWalkable, type NavGrid } from "./officeNav";
-import { RUN_SPEED, stepMover, turnToward, WALK_SPEED } from "./officeMotion";
+import { stepMover, turnToward } 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";
+/** The person's pace: a brisk walk, and a sprint on Shift (m/s). */
+export const PLAYER_WALK_SPEED = 2.0;
+export const PLAYER_SPRINT_SPEED = 4.4;
+
/** Talk range to an agent, in metres. */
export const AGENT_TALK_RANGE = 1.8;
@@ -79,8 +84,8 @@ function nearestInteractable(layout: OfficeLayout): Selection | null {
return best;
}
-export function OfficePlayer({ layout, grid, recipe, name, awake, reduced }: {
- layout: OfficeLayout; grid: NavGrid; recipe: FigureRecipe; name: string; awake: boolean; reduced: boolean;
+export function OfficePlayer({ layout, grid, look, name, awake, reduced }: {
+ layout: OfficeLayout; grid: NavGrid; look: ToyLook; name: string; awake: boolean; reduced: boolean;
}) {
const group = useRef<Group>(null);
const ring = useRef<Mesh>(null);
@@ -112,7 +117,7 @@ export function OfficePlayer({ layout, grid, recipe, name, awake, reduced }: {
// 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;
+ const speed = run.current ? PLAYER_SPRINT_SPEED : PLAYER_WALK_SPEED;
let moved = 0;
if (ix !== 0 || iz !== 0) {
player.path = [];
@@ -156,7 +161,7 @@ export function OfficePlayer({ layout, grid, recipe, name, awake, reduced }: {
<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} />
+ <ToyFigure look={look} 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>
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeRooms.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeRooms.tsx
index b63bcc5816..6011a93a33 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeRooms.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeRooms.tsx
@@ -7,7 +7,7 @@ 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 { ARCH, archPosts, type Door, type Room, type RoomKind, type WallSegment } from "./officeLayout";
import { OFFICE, ROOM_FLOOR_COLOURS } from "./officePalette";
// ---------------------------------------------------------------------------
@@ -168,10 +168,20 @@ function signMaterial(label: string): MeshStandardMaterial {
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);
+ // Shrink long names (e.g. "Despacho del líder") to fit before cutting them off.
+ const room = w - 32;
+ let size = 56;
+ const font = (px: number) => `600 ${px}px system-ui, -apple-system, 'Segoe UI', sans-serif`;
+ ctx.font = font(size);
+ while (size > 34 && ctx.measureText(label).width > room) {
+ size -= 2;
+ ctx.font = font(size);
+ }
+ let text = label;
+ while (text.length > 1 && ctx.measureText(text).width > room) text = text.slice(0, -1);
+ ctx.fillText(text === label ? label : `${text.slice(0, -1).trimEnd()}…`, w / 2, h / 2 + 2);
});
material = new MeshStandardMaterial({ color: map ? "#ffffff" : OFFICE.signBoard, map, roughness: 0.8 });
signMaterials.set(label, material);
@@ -219,11 +229,15 @@ export function RoomSign({ room, label }: { room: Room; label: string }) {
);
}
const archY = 2.3;
+ const postH = archY + SIGN_H / 2;
+ // Post positions come from the layout, which also makes them navigation obstacles.
+ const [west, east] = archPosts(room);
+ const cx = (west.x + east.x) / 2;
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={[cx, 0, west.z]}>
+ <Box size={[ARCH.post, postH, ARCH.post]} position={[west.x - cx, postH / 2, 0]} material={MAT.woodDark} />
+ <Box size={[ARCH.post, postH, ARCH.post]} position={[east.x - cx, postH / 2, 0]} material={MAT.woodDark} />
+ <Box size={[east.x - west.x + ARCH.post, 0.06, ARCH.post]} 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.tsx
index b077c44b3a..b93eb11ff0 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx
@@ -9,21 +9,23 @@ import type { ThreeEvent } from "@react-three/fiber";
import { CanvasTexture, Color, RepeatWrapping, SRGBColorSpace, type Texture } from "three";
import { useT } from "@/i18n";
import type { SocietyAgent } from "../data";
-import type { FigureRecipe } from "../figures/figureRecipe";
+import type { ToyLook } from "./toyFigureModel";
import { Railing, SignWall } from "./OfficeFurniture";
import { DeskInstances } from "./DeskInstances";
+import { LiveMonitors } from "./LiveMonitors";
+import type { DeskChat } from "./useDeskChats";
import { FurniturePiece, MeetingChairs } from "./OfficeProps";
import { RoomFloors, RoomSign, RoomWalls } from "./OfficeRooms";
-import { CheckpointMarker } from "./CheckpointMarker";
+import { CheckpointMarker, type CheckpointIcon } 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 { allDesks, type CheckpointKind, type Department, type OfficeLayout, type Point } from "./officeLayout";
import type { NavGrid } from "./officeNav";
import { DEPARTMENT_TINTS, OFFICE } from "./officePalette";
import { useOfficeStore, type Selection } from "./officeStore";
-const CHECKPOINT_ICON: Record<CheckpointKind, "plus" | "list" | "team" | "shirt" | "star" | "coffee"> = {
+const CHECKPOINT_ICON: Record<CheckpointKind, CheckpointIcon> = {
create: "plus", manage: "list", team: "team", wardrobe: "shirt", lead: "star", break: "coffee",
};
@@ -115,12 +117,14 @@ export interface OfficeSceneProps {
awake: boolean;
reduced: boolean;
overview: number;
- player: { recipe: FigureRecipe; name: string };
+ player: { look: ToyLook; name: string };
selection: Selection | null;
nearby: Selection | null;
+ chats: ReadonlyMap<string, DeskChat>;
+ onOpenScreen: (agentId: string, screen: Point & { y: number }, facing: number) => void;
}
-export function OfficeScene({ layout, grid, walkers, agents, newcomers, awake, reduced, overview, player, selection, nearby }: OfficeSceneProps) {
+export function OfficeScene({ layout, grid, walkers, agents, newcomers, awake, reduced, overview, player, selection, nearby, chats, onOpenScreen }: OfficeSceneProps) {
const t = useT();
const desks = useMemo(() => allDesks(layout), [layout]);
const background = useMemo(() => new Color(OFFICE.space), []);
@@ -151,6 +155,7 @@ export function OfficeScene({ layout, grid, walkers, agents, newcomers, awake, r
{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} />
+ <LiveMonitors desks={desks} agents={agents} chats={chats} onOpen={onOpenScreen} />
{layout.furniture.map((item) => <FurniturePiece key={item.id} item={item} />)}
{table && <MeetingChairs table={table} />}
{layout.checkpoints.map((cp) => (
@@ -158,7 +163,7 @@ export function OfficeScene({ layout, grid, walkers, agents, newcomers, awake, r
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} />
+ <OfficePlayer layout={layout} grid={grid} look={player.look} 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.tsx
index 24e33eb6a9..4f9997bcb1 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx
@@ -6,7 +6,7 @@
*/
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 { advance, Canvas } from "@react-three/fiber";
import { useReducedMotion } from "framer-motion";
import { useCanvasAwake } from "@/hooks/useCanvasAwake";
import { useWebglSurface } from "@/hooks/useWebglSurface";
@@ -18,9 +18,12 @@ import { allDesks, buildOfficeLayout, countStates, MAX_SEATED } from "./officeLa
import { buildNavGrid } from "./officeNav";
import { SpotBook } from "./officeBehavior";
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 { knownAgents } from "./walkerRegistry";
-import { loadProfile, saveProfile, type PlayerProfile } from "./playerProfile";
+import { agentPositions, knownAgents, seatedAtDesk } from "./walkerRegistry";
+import { loadProfile, playerLook, saveProfile, type PlayerProfile } from "./playerProfile";
import { AgentPanel, CheckpointPanel, type OfficeActions } from "./OfficePanels";
import type { WalkerContext } from "./OfficeAgents";
import { ownsKeyboard } from "./OfficePlayer";
@@ -28,7 +31,9 @@ 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 });
+if (import.meta.env.DEV && typeof window !== "undefined") Object.assign(window, { __officeStore: useOfficeStore, __officePlayer: player, __officeAgents: agentPositions, __officeSeated: seatedAtDesk,
+ // Steps the scene without requestAnimationFrame (hidden test tabs): __officeStep(frames, dtMs).
+ __officeStep: (frames = 60, dtMs = 16) => { let t = performance.now(); for (let i = 0; i < frames; i += 1) { t += dtMs; advance(t); } } });
/** Status refresh while the office is on screen; jittered so windows never poll in lockstep (AP-33). */
const REFRESH_MS = 5000;
@@ -124,6 +129,20 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
};
}, [layout, grid, book]);
+ const sessions = useMemo(() => new Map(active.filter((a) => a.chatSessionId).map((a) => [a.agentId, a.chatSessionId as string])), [active]);
+ const chats = useDeskChats(sessions, awake);
+ // Clicking a monitor dives into it, then opens that agent's chat.
+ const openTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
+ useEffect(() => () => clearTimeout(openTimer.current), []);
+ const openScreen = useCallback((agentId: string, screen: Point & { y: number }, facing: number) => {
+ const eye: [number, number, number] = [screen.x + Math.sin(facing) * 0.62, screen.y + 0.02, screen.z + Math.cos(facing) * 0.62];
+ select(null);
+ clearTimeout(openTimer.current);
+ if (reduced) { onSelectAgent?.(agentId); return; }
+ useOfficeStore.getState().zoomInto(eye, [screen.x, screen.y, screen.z]);
+ openTimer.current = setTimeout(() => onSelectAgent?.(agentId), ZOOM_SECONDS * 1000 + 120);
+ }, [onSelectAgent, reduced, select]);
+
const counts = countStates(active);
const updateProfile = useCallback((next: PlayerProfile) => { setProfile(next); saveProfile(next); }, []);
const actions = useMemo<OfficeActions>(() => ({
@@ -161,7 +180,7 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
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}`))
+ : t(`society.office.cp_${nearby.id}_hint`)
: null;
const playerName = profile.name.trim() || t("society.office.you");
@@ -176,8 +195,8 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
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} />
+ awake={awake} reduced={reduced} overview={overview} player={{ look: playerLook(profile), name: playerName }}
+ selection={selection} nearby={nearby} chats={chats} onOpenScreen={openScreen} />
</Canvas>
</Suspense>
</RenderBoundary>
@@ -192,7 +211,8 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
<div className="office-card office-counts" role="status" aria-live="polite">
<span data-tone="working"><i aria-hidden />{t("society.office.count_working").replace("{0}", String(counts.working))}</span>
<span data-tone="waiting"><i aria-hidden />{t("society.office.count_waiting").replace("{0}", String(counts.waiting))}</span>
- <span data-tone="idle"><i aria-hidden />{t("society.office.count_idle").replace("{0}", String(counts.idle + counts.paused))}</span>
+ <span data-tone="idle"><i aria-hidden />{t("society.office.count_idle").replace("{0}", String(counts.idle))}</span>
+ {counts.paused > 0 && <span data-tone="paused"><i aria-hidden />{t("society.office.count_paused").replace("{0}", String(counts.paused))}</span>}
</div>
{roster.data?.sample && <p className="office-card office-note">{t("society.office.sample")}</p>}
{active.length > MAX_SEATED && <p className="office-card office-note">{t("society.office.overflow").replace("{0}", String(MAX_SEATED))}</p>}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/ToyFigure.tsx b/jarvis/ui/web/frontend/src/components/society/office/ToyFigure.tsx
new file mode 100644
index 0000000000..ecb192d540
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/ToyFigure.tsx
@@ -0,0 +1,373 @@
+/**
+ * A chunky toy office character built from a handful of shared primitives:
+ * big round head with dot eyes, short rounded torso, stubby arms, short legs
+ * and chunky sneakers. The animation is procedural (`poseFor` in
+ * `toyFigure.ts`) and applied straight to a small joint hierarchy:
+ *
+ * root (scale) → pelvis → torso → head / shoulders → elbows
+ * → hips → knees → ankles
+ *
+ * Origin on the floor, the figure faces local +z. Geometries are module-level
+ * singletons and materials are cached by colour, so twenty figures share them;
+ * the frame loop allocates nothing.
+ */
+import { useMemo, useRef, type MutableRefObject } from "react";
+import { useFrame } from "@react-three/fiber";
+import {
+ CapsuleGeometry, Color, ConeGeometry, MeshBasicMaterial, MeshStandardMaterial, SphereGeometry, TorusGeometry,
+ type Group,
+} from "three";
+import { RoundedBoxGeometry } from "three-stdlib";
+
+import type { FigureMode } from "../figures/FigureRig";
+import {
+ blendPose, copyPose, createPose, poseFor, TOY, TOY_HEIGHT, walkCadence,
+ type HairStyle, type PoseOptions, type ToyLook, type ToyPose,
+} from "./toyFigureModel";
+
+// ---------------------------------------------------------------------------
+// Shared geometry
+
+const HD = TOY.head;
+
+const GEO = {
+ sphere: new SphereGeometry(1, 22, 16),
+ lowSphere: new SphereGeometry(1, 12, 8),
+ /** 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),
+ 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),
+ shin: new CapsuleGeometry(0.056, 0.1, 4, 10),
+ upperArm: new CapsuleGeometry(TOY.armRadius, 0.08, 4, 10),
+ foreArm: new CapsuleGeometry(0.043, 0.06, 4, 10),
+ shoe: new RoundedBoxGeometry(0.13, 0.075, TOY.heel + TOY.toe + 0.01, 3, 0.034),
+ sole: new RoundedBoxGeometry(0.136, 0.022, TOY.heel + TOY.toe + 0.018, 2, 0.01),
+ smile: new TorusGeometry(0.042, 0.009, 6, 14, Math.PI),
+ spike: new ConeGeometry(0.065, 0.16, 6),
+ brim: new RoundedBoxGeometry(0.3, 0.022, 0.17, 2, 0.01),
+};
+
+const materials = new Map<string, MeshStandardMaterial>();
+/** A matte material per colour, shared by every figure. */
+function matte(color: string, roughness = 0.82): MeshStandardMaterial {
+ const key = `${color}|${roughness}`;
+ let m = materials.get(key);
+ if (!m) {
+ m = new MeshStandardMaterial({ color, roughness, metalness: 0 });
+ materials.set(key, m);
+ }
+ return m;
+}
+
+const EYE = new MeshStandardMaterial({ color: "#16161b", roughness: 0.35, metalness: 0 });
+const CATCHLIGHT = new MeshBasicMaterial({ color: "#ffffff" });
+const MOUTH = matte("#5b2b28", 0.7);
+const SOLE_LIGHT = "#f4f4f2";
+
+function mix(a: string, b: string, k: number): string {
+ return `#${new Color(a).lerp(new Color(b), k).getHexString()}`;
+}
+
+function isLight(hex: string): boolean {
+ const c = new Color(hex);
+ return 0.299 * c.r + 0.587 * c.g + 0.114 * c.b > 0.6;
+}
+
+/** Depth of the head ellipsoid's front surface at (x, y) in head-group space. */
+function faceZ(x: number, y: number, inset = 0): number {
+ const u = x / HD.rx;
+ const v = (y - HD.y) / HD.ry;
+ return HD.rz * Math.sqrt(Math.max(0, 1 - u * u - v * v)) - inset;
+}
+
+// ---------------------------------------------------------------------------
+// Parts
+
+function Face({ look }: { look: ToyLook }) {
+ const skin = matte(look.skin);
+ const blush = matte(mix(look.skin, "#ff6f7d", 0.38));
+ const eyeY = HD.y - 0.03;
+ return (
+ <group>
+ {[-1, 1].map((sx) => {
+ const x = sx * 0.1;
+ const z = faceZ(x, eyeY, 0.012);
+ return (
+ <group key={sx}>
+ <mesh geometry={GEO.sphere} material={EYE} position={[x, eyeY, z]} rotation={[0, sx * 0.4, 0]} scale={[0.034, 0.043, 0.02]} />
+ <mesh geometry={GEO.lowSphere} material={CATCHLIGHT} position={[x + 0.011, eyeY + 0.014, z + 0.017]} scale={0.009} />
+ </group>
+ );
+ })}
+ <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;
+ 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]} />
+ );
+ })}
+ {[-1, 1].map((sx) => (
+ <mesh key={`e${sx}`} geometry={GEO.sphere} material={skin} position={[sx * (HD.rx - 0.012), HD.y - 0.02, -0.01]} scale={[0.03, 0.058, 0.045]} castShadow />
+ ))}
+ </group>
+ );
+}
+
+/** Hair cap shared by most styles: a dome tilted back so the forehead shows. */
+function HairCap({ color, grow = 0 }: { color: string; grow?: number }) {
+ 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 />
+ );
+}
+
+const SPIKES: Array<[number, number, number, number, number]> = [
+ [0, 0.6, 0.1, 0.75, 0], [-0.12, 0.6, 0.04, 0.35, 0.45], [0.12, 0.6, 0.04, 0.35, -0.45],
+ [0, 0.62, -0.05, -0.2, 0], [-0.21, 0.52, -0.04, -0.1, 0.95], [0.21, 0.52, -0.04, -0.1, -0.95],
+ [-0.09, 0.57, -0.13, -0.6, 0.35], [0.09, 0.57, -0.13, -0.6, -0.35],
+];
+
+/** Puff centres for the curly style: directions over the upper head, clear of the face. */
+const CURLS: Array<[number, number, number]> = (() => {
+ const out: Array<[number, number, number]> = [[0, 1, 0]];
+ const rings: Array<[number, number, number]> = [[0.5, 6, 0], [1.0, 8, 0.4]];
+ for (const [theta, count, offset] of rings) {
+ for (let i = 0; i < count; i += 1) {
+ const phi = offset + (i / count) * Math.PI * 2;
+ const x = Math.sin(theta) * Math.sin(phi);
+ const z = Math.sin(theta) * Math.cos(phi);
+ if (z > 0.55 && theta > 0.8) continue; // keep the forehead free
+ out.push([x, Math.cos(theta), z]);
+ }
+ }
+ return out;
+})();
+
+function Hair({ style, look }: { style: HairStyle; look: ToyLook }) {
+ const hair = matte(look.hair);
+ switch (style) {
+ case "bald":
+ return null;
+ case "short":
+ return <HairCap color={look.hair} />;
+ case "spiky":
+ return (
+ <group>
+ <HairCap color={look.hair} />
+ {SPIKES.map(([x, y, z, rx, rz], i) => (
+ <mesh key={i} geometry={GEO.spike} material={hair} position={[x, y, z]} rotation={[rx, 0, rz]} castShadow />
+ ))}
+ </group>
+ );
+ case "bun":
+ return (
+ <group>
+ <HairCap color={look.hair} />
+ <mesh geometry={GEO.sphere} material={hair} position={[0, HD.y + HD.ry + 0.02, -0.1]} scale={0.1} castShadow />
+ </group>
+ );
+ case "curly":
+ return (
+ <group>
+ <HairCap color={look.hair} grow={0.01} />
+ {CURLS.map(([x, y, z], i) => (
+ <mesh key={i} geometry={GEO.lowSphere} material={hair} castShadow
+ position={[x * HD.rx * 0.92, HD.y + y * HD.ry * 0.92 + 0.02, z * HD.rz * 0.72]} scale={0.085} />
+ ))}
+ </group>
+ );
+ case "long":
+ return (
+ <group>
+ <HairCap color={look.hair} />
+ <mesh geometry={GEO.sphere} material={hair} position={[0, HD.y - 0.1, -0.15]} scale={[0.29, 0.3, 0.125]} castShadow />
+ {[-1, 1].map((sx) => (
+ <mesh key={sx} geometry={GEO.sphere} material={hair} position={[sx * 0.285, HD.y - 0.1, -0.03]} scale={[0.07, 0.19, 0.1]} castShadow />
+ ))}
+ </group>
+ );
+ case "beanie": {
+ const knit = matte(look.shirtAccent, 0.95);
+ return (
+ <group>
+ <mesh geometry={GEO.dome} material={knit} position={[0, HD.y + 0.01, 0]} rotation={[-0.15, 0, 0]}
+ scale={[HD.rx + 0.025, HD.ry + 0.045, HD.rz + 0.028]} castShadow />
+ <mesh geometry={GEO.lowSphere} material={knit} position={[0, HD.y + HD.ry + 0.07, -0.03]} scale={0.06} castShadow />
+ {[-1, 1].map((sx) => (
+ <mesh key={sx} geometry={GEO.lowSphere} material={hair} position={[sx * 0.27, HD.y - 0.02, 0.06]} scale={[0.05, 0.07, 0.06]} />
+ ))}
+ </group>
+ );
+ }
+ case "cap": {
+ const cap = matte(look.shirtAccent, 0.7);
+ 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 />
+ <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>
+ );
+ }
+ }
+}
+
+type JointRef = MutableRefObject<Group | null>;
+
+function Arm({ side, look, shoulder, elbow }: { side: 1 | -1; look: ToyLook; shoulder: JointRef; elbow: JointRef }) {
+ const skin = matte(look.skin);
+ return (
+ <group ref={shoulder} position={[side * TOY.shoulderX, TOY.shoulderY, 0]}>
+ <mesh geometry={GEO.sphere} material={matte(look.shirt)} position={[0, -0.03, 0]} scale={[0.068, 0.078, 0.07]} castShadow />
+ <mesh geometry={GEO.upperArm} material={skin} position={[0, -TOY.upperArm / 2, 0]} castShadow />
+ <group ref={elbow} position={[0, -TOY.upperArm, 0]}>
+ <mesh geometry={GEO.foreArm} material={skin} position={[0, -0.06, 0]} castShadow />
+ <mesh geometry={GEO.sphere} material={skin} position={[0, -TOY.foreArm, 0]} scale={TOY.handRadius} castShadow />
+ </group>
+ </group>
+ );
+}
+
+function Leg({ side, look, hip, knee, ankle }: { side: 1 | -1; look: ToyLook; hip: JointRef; knee: JointRef; ankle: JointRef }) {
+ const pants = matte(look.pants);
+ const sole = matte(isLight(look.shoes) ? mix(look.shoes, "#9a9aa0", 0.25) : SOLE_LIGHT);
+ return (
+ <group ref={hip} position={[side * TOY.hipX, TOY.hipUp, 0]}>
+ <mesh geometry={GEO.thigh} material={pants} position={[0, -TOY.thigh / 2, 0]} castShadow />
+ <group ref={knee} position={[0, -TOY.thigh, 0]}>
+ <mesh geometry={GEO.shin} material={pants} position={[0, -TOY.shin / 2 + 0.005, 0]} castShadow />
+ <group ref={ankle} position={[0, -TOY.shin, 0]}>
+ <mesh geometry={GEO.shoe} material={matte(look.shoes, 0.6)} position={[0, -TOY.sole + 0.0425, (TOY.toe - TOY.heel) / 2]} castShadow />
+ <mesh geometry={GEO.sole} material={sole} position={[0, -TOY.sole + 0.011, (TOY.toe - TOY.heel) / 2]} castShadow />
+ </group>
+ </group>
+ </group>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Figure
+
+/** Cross-fade time between two modes, seconds. */
+const BLEND_S = 0.2;
+/** Longest frame step the animation accepts (a tab switch must not jump). */
+const MAX_DT = 0.1;
+
+export interface ToyFigureProps {
+ look: ToyLook;
+ drive: { current: { mode: FigureMode; speed: number } };
+ paused: boolean;
+ /** Rendered height in metres; the rig is designed at 1.3 m and scales uniformly. */
+ heightM?: number;
+ /** Seat-top height in metres for the seated modes (sit, work, sleep). */
+ seatHeight?: number;
+}
+
+export function ToyFigure({ look, drive, paused, heightM = TOY_HEIGHT, seatHeight = 0.52 }: ToyFigureProps) {
+ const scale = heightM / TOY_HEIGHT;
+ const pelvis = useRef<Group>(null);
+ const torso = useRef<Group>(null);
+ const head = useRef<Group>(null);
+ const lShoulder = useRef<Group>(null);
+ const rShoulder = useRef<Group>(null);
+ const lElbow = useRef<Group>(null);
+ const rElbow = useRef<Group>(null);
+ const lHip = useRef<Group>(null);
+ const rHip = useRef<Group>(null);
+ const lKnee = useRef<Group>(null);
+ const rKnee = useRef<Group>(null);
+ const lAnkle = useRef<Group>(null);
+ const rAnkle = useRef<Group>(null);
+
+ const state = useMemo(() => ({
+ time: Math.random() * 10, // desynchronise idle loops between figures
+ phase: 0,
+ mode: null as FigureMode | null,
+ blend: 1,
+ from: createPose(),
+ target: createPose(),
+ current: createPose(),
+ opts: { seatHeight: 0.52, phase: 0 } as PoseOptions & { phase: number },
+ settled: false,
+ }), []);
+
+ const shirtAccent = matte(look.shirtAccent);
+
+ useFrame((_, rawDt) => {
+ const s = state;
+ const dt = Math.min(rawDt, MAX_DT);
+ const { mode, speed } = drive.current;
+ const rigSpeed = Math.max(0, speed) / scale;
+ const modeChanged = mode !== s.mode;
+ if (paused && !modeChanged && s.settled) return;
+ if (!paused) {
+ s.time += dt;
+ if (mode === "walk") s.phase += dt * walkCadence(rigSpeed);
+ }
+ if (modeChanged) {
+ if (s.mode === null) s.blend = 1;
+ else { copyPose(s.current, s.from); s.blend = 0; }
+ s.mode = mode;
+ }
+ s.opts.seatHeight = seatHeight / scale;
+ s.opts.phase = s.phase;
+ poseFor(mode, s.time, rigSpeed, s.opts, s.target);
+ if (s.blend < 1) {
+ s.blend = Math.min(1, s.blend + dt / BLEND_S);
+ const k = s.blend * s.blend * (3 - 2 * s.blend);
+ blendPose(s.from, s.target, k, s.current);
+ } else {
+ copyPose(s.target, s.current);
+ }
+ s.settled = s.blend >= 1;
+ apply(s.current);
+ });
+
+ function apply(p: ToyPose): void {
+ pelvis.current?.position.set(0, p.hipY, p.hipZ);
+ if (torso.current) {
+ torso.current.position.y = TOY.hipUp + p.bob;
+ torso.current.rotation.set(p.torsoPitch, p.torsoYaw, p.torsoRoll);
+ }
+ head.current?.rotation.set(p.headPitch, p.headYaw, p.headRoll);
+ lShoulder.current?.rotation.set(p.leftShoulder[0], p.leftShoulder[1], p.leftShoulder[2]);
+ rShoulder.current?.rotation.set(p.rightShoulder[0], p.rightShoulder[1], p.rightShoulder[2]);
+ if (lElbow.current) lElbow.current.rotation.x = p.leftElbow;
+ if (rElbow.current) rElbow.current.rotation.x = p.rightElbow;
+ if (lHip.current) lHip.current.rotation.x = p.leftHip;
+ if (rHip.current) rHip.current.rotation.x = p.rightHip;
+ if (lKnee.current) lKnee.current.rotation.x = p.leftKnee;
+ if (rKnee.current) rKnee.current.rotation.x = p.rightKnee;
+ if (lAnkle.current) lAnkle.current.rotation.x = p.leftAnkle;
+ if (rAnkle.current) rAnkle.current.rotation.x = p.rightAnkle;
+ }
+
+ return (
+ <group scale={scale}>
+ <group ref={pelvis} position={[0, TOY.thigh + TOY.shin + TOY.sole - TOY.hipUp, 0]}>
+ <mesh geometry={GEO.pelvis} material={matte(look.pants)} position={[0, TOY.pelvis.h / 2, 0]} castShadow />
+ <Leg side={1} look={look} hip={lHip} knee={lKnee} ankle={lAnkle} />
+ <Leg side={-1} look={look} hip={rHip} knee={rKnee} ankle={rAnkle} />
+ <group ref={torso} position={[0, TOY.hipUp, 0]}>
+ <mesh geometry={GEO.chest} material={matte(look.shirt)} position={[0, 0.02 + (TOY.torso.h - 0.02) / 2, 0]} castShadow />
+ {/* Chest emblem in the accent colour, like the logo on a T-shirt. */}
+ <mesh geometry={GEO.sphere} material={shirtAccent} position={[0, 0.16, TOY.torso.d / 2 - 0.004]} scale={[0.05, 0.05, 0.012]} />
+ <mesh geometry={GEO.lowSphere} material={matte(look.skin)} position={[0, TOY.neckY - 0.01, 0]} scale={[0.07, 0.04, 0.07]} />
+ <Arm side={1} look={look} shoulder={lShoulder} elbow={lElbow} />
+ <Arm side={-1} look={look} shoulder={rShoulder} elbow={rElbow} />
+ <group ref={head} position={[0, TOY.neckY, 0]}>
+ <mesh geometry={GEO.sphere} material={matte(look.skin)} position={[0, HD.y, 0]} scale={[HD.rx, HD.ry, HD.rz]} castShadow />
+ <Face look={look} />
+ <Hair style={look.hairStyle} look={look} />
+ </group>
+ </group>
+ </group>
+ </group>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/deskChat.test.ts b/jarvis/ui/web/frontend/src/components/society/office/deskChat.test.ts
new file mode 100644
index 0000000000..fa7112d250
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/deskChat.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from "vitest";
+import type { AgentChatEvent } from "@/lib/agentChatApi";
+import { chatLines, chatVersion, MAX_CHAT_LINES, toolLabel } from "./deskChat";
+
+const ev = (seq: number, kind: string, payload: Record<string, unknown>): AgentChatEvent => ({ seq, ts_ms: seq, kind, payload });
+
+describe("desk chat lines", () => {
+ it("keeps who said what and which tool runs, dropping noise", () => {
+ const lines = chatLines([
+ ev(1, "user_message", { text: "Please ship it" }),
+ ev(2, "turn_started", {}),
+ ev(3, "reasoning", { text: "" }),
+ ev(4, "assistant_text", { text: "On it." }),
+ ev(5, "tool_call", { name: "mcp__jarvis__society_shell" }),
+ ev(6, "tool_result", { output: "…" }),
+ ev(7, "error", { message: "boom" }),
+ ]);
+ expect(lines).toEqual([
+ { kind: "user", text: "Please ship it" },
+ { kind: "agent", text: "On it." },
+ { kind: "tool", text: "society_shell" },
+ { kind: "error", text: "boom" },
+ ]);
+ });
+ it("keeps only the newest lines and truncates long text", () => {
+ const many = Array.from({ length: 40 }, (_, i) => ev(i, "assistant_text", { text: `line ${i} ${"x".repeat(300)}` }));
+ const lines = chatLines(many);
+ expect(lines).toHaveLength(MAX_CHAT_LINES);
+ expect(lines.at(-1)!.text.startsWith("line 39")).toBe(true);
+ expect(lines[0].text.length).toBeLessThanOrEqual(160);
+ });
+ it("labels tools and versions events", () => {
+ expect(toolLabel("Read")).toBe("Read");
+ expect(toolLabel(undefined)).toBe("tool");
+ expect(chatVersion([])).toBe("0");
+ expect(chatVersion([ev(9, "x", {})])).toBe("9:1");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/office/deskChat.ts b/jarvis/ui/web/frontend/src/components/society/office/deskChat.ts
new file mode 100644
index 0000000000..be6098107d
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/deskChat.ts
@@ -0,0 +1,50 @@
+/**
+ * What a desk monitor shows: the tail of the agent's own chat, reduced to a
+ * few short lines — who said what, and which tool is running. Pure, tested.
+ */
+import type { AgentChatEvent } from "@/lib/agentChatApi";
+
+export type ChatLineKind = "user" | "agent" | "tool" | "notice" | "error";
+
+export interface ChatLine { kind: ChatLineKind; text: string }
+
+/** Lines kept per monitor; the screen shows the newest that fit. */
+export const MAX_CHAT_LINES = 14;
+
+function clean(text: unknown, max = 160): string {
+ if (typeof text !== "string") return "";
+ const flat = text.replace(/\s+/g, " ").trim();
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
+}
+
+/** Short, human tool names: "mcp__jarvis__society_shell" → "society_shell". */
+export function toolLabel(name: unknown): string {
+ if (typeof name !== "string" || !name) return "tool";
+ const parts = name.split("__");
+ return parts[parts.length - 1] || name;
+}
+
+export function chatLines(events: readonly AgentChatEvent[]): ChatLine[] {
+ const lines: ChatLine[] = [];
+ for (const event of events) {
+ const p = event.payload ?? {};
+ let line: ChatLine | null = null;
+ switch (event.kind) {
+ case "user_message": line = { kind: "user", text: clean(p.text) }; break;
+ case "agent_message": line = { kind: p.sender_kind === "user" ? "user" : "agent", text: clean(p.text) }; break;
+ case "assistant_text": line = { kind: "agent", text: clean(p.text) }; break;
+ case "tool_call": line = { kind: "tool", text: clean(typeof p.summary === "string" && p.summary ? p.summary : toolLabel(p.name), 80) }; break;
+ case "notice": line = { kind: "notice", text: clean(p.text ?? p.summary, 100) }; break;
+ case "error": line = { kind: "error", text: clean(p.message, 100) }; break;
+ default: break;
+ }
+ if (line && line.text) lines.push(line);
+ }
+ return lines.slice(-MAX_CHAT_LINES);
+}
+
+/** A cheap identity for "did anything change": last event seq and count. */
+export function chatVersion(events: readonly AgentChatEvent[]): string {
+ const last = events[events.length - 1];
+ return last ? `${last.seq}:${events.length}` : "0";
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/office.css b/jarvis/ui/web/frontend/src/components/society/office/office.css
index 495e8da14d..106c3e7cca 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/office.css
+++ b/jarvis/ui/web/frontend/src/components/society/office/office.css
@@ -1,24 +1,25 @@
/* HUD over the office canvas: theme tokens, so it follows light and dark mode. */
-.office-stage { position:relative; height:100%; min-height:0; overflow:hidden; background:#0b1024; }
+.office-stage { position:relative; width:100%; min-width:0; height:100%; min-height:0; overflow:hidden; background:#0b1024; }
.office-viewport { position:absolute; inset:0; touch-action:none; }
.office-viewport:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:-2px; }
.office-fallback { display:flex; align-items:center; justify-content:center; height:100%; padding:24px; font-size:13px; color:hsl(var(--muted-foreground)); background:hsl(var(--background)); }
.office-hud { position:absolute; z-index:30; }
.office-hud-left { left:14px; top:14px; display:flex; flex-direction:column; align-items:flex-start; gap:8px; max-width:min(320px, calc(100% - 28px)); }
-.office-hud-right { right:14px; top:14px; display:flex; gap:6px; }
+/* Wraps (right-aligned) before it can run under the left cards or off the edge. */
+.office-hud-right { right:14px; top:14px; display:flex; flex-wrap:wrap; justify-content:flex-end; gap:6px; max-width:max(180px, calc(100% - 370px)); }
.office-card { border:1px solid hsl(var(--border)); border-radius:12px; background:hsl(var(--popover) / .92); color:hsl(var(--popover-foreground)); box-shadow:0 4px 18px rgb(0 0 0 / .25); backdrop-filter:blur(6px); }
.office-title { display:flex; flex-direction:column; gap:2px; padding:8px 12px; font-size:14px; }
.office-title span { font-size:11px; color:hsl(var(--muted-foreground)); }
.office-counts { display:flex; gap:14px; padding:7px 12px; font-size:12px; font-weight:600; }
.office-counts span { display:inline-flex; align-items:center; gap:6px; }
-.office-counts i { width:8px; height:8px; border-radius:50%; background:#94a3b8; }
-.office-counts [data-tone="working"] i { background:#22c55e; }
-.office-counts [data-tone="waiting"] i { background:#f59e0b; }
+.office-counts i { width:8px; height:8px; border-radius:50%; background:hsl(var(--muted-foreground)); }
+.office-counts [data-tone="working"] i { background:hsl(var(--success)); }
+.office-counts [data-tone="waiting"] i { background:hsl(var(--warning)); }
.office-note { margin:0; padding:6px 10px; font-size:11px; color:hsl(var(--muted-foreground)); }
-.office-button { border:1px solid hsl(var(--border)); border-radius:10px; padding:6px 11px; background:hsl(var(--popover) / .92); color:hsl(var(--popover-foreground)); font-size:12px; cursor:pointer; backdrop-filter:blur(6px); }
+.office-button { border:1px solid hsl(var(--border)); border-radius:10px; padding:6px 11px; background:hsl(var(--popover) / .92); color:hsl(var(--popover-foreground)); font-size:12px; white-space:nowrap; cursor:pointer; backdrop-filter:blur(6px); }
.office-button:hover { background:hsl(var(--secondary)); }
.office-button:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:2px; }
-.office-help { left:50%; bottom:12px; transform:translateX(-50%); margin:0; padding:5px 12px; border-radius:999px; font-size:11px; white-space:nowrap; background:hsl(var(--popover) / .85); color:hsl(var(--muted-foreground)); border:1px solid hsl(var(--border)); }
+.office-help { left:50%; bottom:12px; transform:translateX(-50%); margin:0; padding:5px 12px; border-radius:999px; font-size:11px; white-space:nowrap; max-width:calc(100% - 28px); overflow:hidden; text-overflow:ellipsis; background:hsl(var(--popover) / .85); color:hsl(var(--muted-foreground)); border:1px solid hsl(var(--border)); pointer-events:none; }
/* In-world name pills: part of the diorama, so they keep one dark look in both modes. */
.office-plate { transform-origin:center bottom; display:inline-flex; align-items:center; gap:5px; padding:2px 8px 2px 2px; border:0; border-radius:999px; background:rgb(24 26 32 / .84); color:#f8fafc; cursor:pointer; font-family:inherit; white-space:nowrap; user-select:none; box-shadow:0 2px 8px rgb(0 0 0 / .35); }
@@ -37,7 +38,11 @@
.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-text { display:flex; flex-direction:column; align-items:flex-start; min-width:0; line-height:1.2; }
+/* The action behind the place, shown while the character stands in (or the panel is open). */
+.office-checkpoint-hint { max-width:14em; overflow:hidden; text-overflow:ellipsis; font-size:10px; font-weight:600; color:#f5d493; }
.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:900px) { .office-help { white-space:normal; text-align:center; border-radius:12px; } }
@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.ts
index 937e59a1c5..978b6b639d 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/officeBehavior.test.ts
+++ b/jarvis/ui/web/frontend/src/components/society/office/officeBehavior.test.ts
@@ -81,7 +81,7 @@ describe("planFor", () => {
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 }));
+ const plan = planFor(input("a3", "idle", { calledTo: caller }));
expect(plan.kind).toBe("called");
expect(plan.pose).toBe("talk");
expect(plan.dwellMs).toBe(15000);
@@ -89,6 +89,11 @@ describe("planFor", () => {
expect(Math.hypot(plan.target.x - caller.x, plan.target.z - caller.z)).toBeLessThan(2);
});
+ it("keeps a working agent at its screen even when called", () => {
+ const caller = layout.checkpoints.find((c) => c.id === "create")!;
+ expect(planFor(input("a3", "working", { calledTo: caller })).kind).toBe("work");
+ });
+
function idleSequence(seed: string, steps: number, colleagues: PlanInput["workingColleagues"] = []): ActivityKind[] {
const rng = createRng(seed);
const book = new SpotBook();
diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeBehavior.ts b/jarvis/ui/web/frontend/src/components/society/office/officeBehavior.ts
index 05502cd949..708adbdfe3 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/officeBehavior.ts
+++ b/jarvis/ui/web/frontend/src/components/society/office/officeBehavior.ts
@@ -211,7 +211,8 @@ export function planFor(input: PlanInput): Plan {
const { agentId, state, desk, book } = input;
book.release(agentId);
- if (input.calledTo) return calledPlan(input, input.calledTo);
+ // A working agent stays at its screen: the map mirrors real work and never interrupts it, not even visually.
+ if (input.calledTo && input.state !== "working") return calledPlan(input, input.calledTo);
if (state === "working") {
if (desk) {
diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeHud.css b/jarvis/ui/web/frontend/src/components/society/office/officeHud.css
index 50cd164f82..b9f63c954d 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/officeHud.css
+++ b/jarvis/ui/web/frontend/src/components/society/office/officeHud.css
@@ -2,13 +2,17 @@
.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:focus { outline:none; }
+.office-panel:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:2px; }
+.office-panel-head > div { min-width:0; }
+.office-panel-head h2 { display:block; margin:0; font-size:14px; font-weight:700; overflow-wrap:anywhere; }
.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-icon-button:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:1px; color:hsl(var(--foreground)); }
.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)); }
@@ -25,22 +29,30 @@
.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-list li > .office-mini { flex:none; }
+.office-dot { display:inline-block; flex:none; width:8px; height:8px; border-radius:50%; background:hsl(var(--muted-foreground)); }
+.office-dot[data-state="working"] { background:hsl(var(--success)); }
+.office-dot[data-state="waiting"] { background:hsl(var(--warning)); }
+.office-dot[data-state="paused"] { background:transparent; box-shadow:inset 0 0 0 1.5px hsl(var(--muted-foreground)); }
.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:hover:not([aria-pressed="true"]) { background:hsl(var(--secondary)); }
.office-chip[aria-pressed="true"] { background:hsl(var(--primary)); color:hsl(var(--primary-foreground)); border-color:transparent; }
+.office-list input[type="checkbox"] { flex:none; accent-color:hsl(var(--primary)); }
+.office-list input[type="checkbox"]:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:1px; }
+.office-hint { margin:0; font-size:11px; color:hsl(var(--muted-foreground)); }
.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-hud-right .office-button[aria-pressed="true"] { border-color:#f5b83d; background:hsl(var(--secondary)); }
.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%; } }
+/* The right-hand buttons wrap onto a second row here; keep the panel below them. */
+@media (max-width:900px) { .office-panel-slot { top:96px; max-height:calc(100% - 150px); } .office-prompt { bottom:64px; } }
+@media (max-width:600px) { .office-panel-slot { top:auto; bottom:12px; max-height:55%; } .office-hud-right { max-width:60%; } .office-prompt { bottom:48px; max-width:calc(100% - 28px); } }
diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeLayout.test.ts b/jarvis/ui/web/frontend/src/components/society/office/officeLayout.test.ts
index 28d61770b1..3b6446262d 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/officeLayout.test.ts
+++ b/jarvis/ui/web/frontend/src/components/society/office/officeLayout.test.ts
@@ -1,5 +1,8 @@
import { describe, expect, it } from "vitest";
-import { allDesks, buildOfficeLayout, countStates, departmentKey, groupDepartments, MAX_DEPARTMENTS, MIN_DEPARTMENTS, type OfficeAgentInput } from "./officeLayout";
+import {
+ allDesks, archPosts, buildOfficeLayout, countStates, departmentKey, FURNITURE_SIZE, footprint, groupDepartments,
+ MAX_DEPARTMENTS, MIN_DEPARTMENTS, type OfficeAgentInput,
+} from "./officeLayout";
import { cameraHome, fitDistance, focusBounds } from "./officeCamera";
const agent = (id: string, provider: string, extra: Partial<OfficeAgentInput> = {}): OfficeAgentInput => ({
@@ -55,6 +58,25 @@ describe("office layout", () => {
expect(layout.departments.every((d) => d.label === "" && d.desks.length > 0)).toBe(true);
});
+ it("makes the posts of an open room's name arch solid", () => {
+ const layout = buildOfficeLayout([agent("a1", "Codex")]);
+ const open = layout.rooms.filter((r) => !r.walled);
+ expect(open.length).toBeGreaterThan(0);
+ for (const post of open.flatMap(archPosts)) {
+ const covered = layout.obstacles.some((o) => post.x >= o.minX && post.x <= o.maxX && post.z >= o.minZ && post.z <= o.maxZ);
+ expect(covered).toBe(true);
+ }
+ });
+
+ it("keeps every checkpoint centre clear of solid furniture", () => {
+ const layout = buildOfficeLayout(Array.from({ length: 12 }, (_, i) => agent(`a${i}`, i % 2 ? "Codex" : "Gemini")));
+ const solid = layout.furniture.filter((f) => FURNITURE_SIZE[f.kind].solid).map(footprint);
+ for (const cp of layout.checkpoints) {
+ const inside = solid.some((o) => cp.x >= o.minX && cp.x <= o.maxX && cp.z >= o.minZ && cp.z <= o.maxZ);
+ expect(inside, cp.id).toBe(false);
+ }
+ });
+
it("counts states", () => {
expect(countStates([{ state: "working" }, { state: "idle" }, { state: "working" }])).toEqual({ working: 2, idle: 1, waiting: 0, paused: 0 });
});
diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeLayout.ts b/jarvis/ui/web/frontend/src/components/society/office/officeLayout.ts
index 553cd70f3a..f703fbcffd 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/officeLayout.ts
+++ b/jarvis/ui/web/frontend/src/components/society/office/officeLayout.ts
@@ -136,7 +136,7 @@ export const BENCH_DEPTH_Z = 4.2;
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 SEAT_OFFSET = 0.62;
export const DESKS_PER_ROW = 4;
const SEATS_PER_BENCH = DESKS_PER_ROW * 2;
const MIN_BENCHES = 1;
@@ -265,6 +265,16 @@ function wallsOf(room: Room): WallSegment[] {
return out;
}
+/** The free-standing name arch of an open (unwalled) room: two posts on its north edge. */
+export const ARCH = { halfSpan: 0.95, inset: 0.25, post: 0.08 } as const;
+
+/** Post centres of an open room's name arch; the renderer and navigation share them. */
+export function archPosts(room: Rect): Point[] {
+ const cx = (room.minX + room.maxX) / 2;
+ const z = room.minZ + ARCH.inset;
+ return [{ x: cx - ARCH.halfSpan, z }, { x: cx + ARCH.halfSpan, z }];
+}
+
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 };
@@ -428,6 +438,10 @@ export function buildOfficeLayout(agents: readonly OfficeAgentInput[]): OfficeLa
// 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),
+ // The posts of an open room's name arch are solid too; nobody walks through them.
+ ...rooms.filter((r) => !r.walled).flatMap(archPosts).map((p) => ({
+ minX: p.x - ARCH.post / 2, maxX: p.x + ARCH.post / 2, minZ: p.z - ARCH.post / 2, maxZ: p.z + ARCH.post / 2,
+ })),
];
const floor = { minX: minX - EDGE + 0.35, maxX: maxX + EDGE - 0.35, minZ: topZ - EDGE + 0.35, maxZ: bottomZ + EDGE - 0.35 };
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 200c550165..e1188d5da1 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/officeStore.ts
+++ b/jarvis/ui/web/frontend/src/components/society/office/officeStore.ts
@@ -24,6 +24,9 @@ interface OfficeState {
/** One-shot camera fly-to request, consumed by the camera rig. */
focus: { point: Point; seq: number } | null;
summons: Record<string, Summon>;
+ /** One-shot camera dive into a desk monitor (then the chat opens), consumed by the camera rig. */
+ zoom: { eye: [number, number, number]; target: [number, number, number]; seq: number } | null;
+ zoomInto: (eye: [number, number, number], target: [number, number, number]) => void;
/** 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. */
@@ -48,6 +51,8 @@ export const useOfficeStore = create<OfficeState>((set) => ({
focus: null,
summons: {},
walkTo: null,
+ zoom: null,
+ zoomInto: (eye, target) => set({ zoom: { eye, target, seq: ++seq }, follow: false }),
teamDraft: [],
toggleDraft: (agentId) => set((s) => ({
teamDraft: s.teamDraft.includes(agentId) ? s.teamDraft.filter((id) => id !== agentId) : [...s.teamDraft, agentId],
@@ -59,8 +64,10 @@ export const useOfficeStore = create<OfficeState>((set) => ({
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 };
+ const now = Date.now();
+ const untilMs = now + durationMs;
+ // Expired calls are dropped here, so the map never grows with old calls.
+ const next = Object.fromEntries(Object.entries(s.summons).filter(([, summon]) => summon.untilMs > now));
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;
diff --git a/jarvis/ui/web/frontend/src/components/society/office/playerProfile.ts b/jarvis/ui/web/frontend/src/components/society/office/playerProfile.ts
index a50d932a51..a82e4a7a85 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/playerProfile.ts
+++ b/jarvis/ui/web/frontend/src/components/society/office/playerProfile.ts
@@ -7,12 +7,27 @@
*/
import { CATALOG } from "../figures/figureRegistry";
import { shufflePalette, type FigureRecipe } from "../figures/figureRecipe";
+import { toyLookFor, type HairStyle, type ToyLook } from "./toyFigureModel";
const STORAGE_KEY = "jarvis.office.player.v1";
export interface PlayerProfile {
name: string;
recipe: FigureRecipe;
+ /** The toy figure's hair; absent means the stable default from the player's identity. */
+ hairStyle?: HairStyle;
+}
+
+export const HAIR_STYLES: readonly HairStyle[] = ["short", "spiky", "bun", "curly", "long", "beanie", "cap", "bald"];
+
+/** The look the office draws for the person. */
+export function playerLook(profile: PlayerProfile): ToyLook {
+ const look = toyLookFor(profile.recipe, "office-player");
+ return profile.hairStyle ? { ...look, hairStyle: profile.hairStyle } : look;
+}
+
+export function withHairStyle(profile: PlayerProfile, hairStyle: HairStyle): PlayerProfile {
+ return { ...profile, hairStyle };
}
/** Bodies offered in the wardrobe: two-legged, first-party, not reserved. */
@@ -43,6 +58,7 @@ export function loadProfile(): PlayerProfile {
return {
name: typeof parsed.name === "string" ? parsed.name.slice(0, 40) : fallback.name,
recipe: isRecipe(parsed.recipe) ? parsed.recipe : fallback.recipe,
+ hairStyle: HAIR_STYLES.includes(parsed.hairStyle as HairStyle) ? parsed.hairStyle : undefined,
};
} catch (error) {
// Blocked storage (private window, thumbnail capture): the default look is the honest answer.
diff --git a/jarvis/ui/web/frontend/src/components/society/office/toyFigureModel.test.ts b/jarvis/ui/web/frontend/src/components/society/office/toyFigureModel.test.ts
new file mode 100644
index 0000000000..95d8c16161
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/toyFigureModel.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, it } from "vitest";
+
+import type { FigureRecipe } from "../figures/figureRecipe";
+import {
+ blendPose, createPose, isNaturalSkin, KEYBOARD, lowestSoleY, poseFor, SEAT_BACK_CLEARANCE, SEAT_HEIGHT,
+ TOY_HEIGHT, toyLookFor, toyPoints, type ToyMode,
+} from "./toyFigureModel";
+
+const SAMPLES = Array.from({ length: 40 }, (_, i) => i * 0.137);
+const SEATED: ToyMode[] = ["sit", "work", "sleep"];
+const GROUNDED: ToyMode[] = ["idle", "talk", "wave"];
+
+describe("poseFor — seated", () => {
+ it.each(SEATED)("%s rests the pelvis exactly on the seat", (mode) => {
+ for (const seat of Object.values(SEAT_HEIGHT)) {
+ for (const t of SAMPLES) {
+ const p = poseFor(mode, t, 0, { seatHeight: seat });
+ expect(p.hipY).toBeCloseTo(seat, 6);
+ }
+ }
+ });
+
+ it.each(SEATED)("%s keeps every body point clear of the backrest", (mode) => {
+ for (const t of SAMPLES) {
+ const pose = poseFor(mode, t, 0, { seatHeight: SEAT_HEIGHT.chair });
+ for (const { name, p } of toyPoints(pose)) {
+ expect(p[2], `${mode} ${name} at t=${t}`).toBeGreaterThanOrEqual(-SEAT_BACK_CLEARANCE);
+ }
+ }
+ });
+
+ it("sits with thighs forward and shins hanging down", () => {
+ const pts = new Map(toyPoints(poseFor("sit", 0, 0, { seatHeight: 0.52 })).map((x) => [x.name, x.p]));
+ const hip = pts.get("leftHip")!;
+ const knee = pts.get("leftKnee")!;
+ const ankle = pts.get("leftAnkle")!;
+ expect(knee[2]).toBeGreaterThan(hip[2] + 0.15);
+ expect(Math.abs(knee[1] - hip[1])).toBeLessThan(0.02);
+ expect(ankle[1]).toBeLessThan(knee[1] - 0.12);
+ expect(Math.abs(ankle[2] - knee[2])).toBeLessThan(0.03);
+ });
+
+ it("work puts both hands on the keyboard in front of the seat", () => {
+ for (const t of SAMPLES) {
+ const pts = new Map(toyPoints(poseFor("work", t, 0, { seatHeight: SEAT_HEIGHT.chair })).map((x) => [x.name, x.p]));
+ for (const side of ["left", "right"]) {
+ const hand = pts.get(`${side}Hand`)!;
+ expect(Math.abs(hand[2] - KEYBOARD.z)).toBeLessThan(0.02);
+ expect(hand[1]).toBeGreaterThan(KEYBOARD.y);
+ expect(hand[1]).toBeLessThan(KEYBOARD.y + 0.1);
+ }
+ }
+ });
+});
+
+describe("poseFor — standing and walking", () => {
+ it.each(GROUNDED)("%s keeps the feet on the floor", (mode) => {
+ for (const t of SAMPLES) expect(lowestSoleY(poseFor(mode, t, 0, { seatHeight: 0.52 }))).toBeCloseTo(0, 5);
+ });
+
+ it("walk keeps a foot on the floor at every speed", () => {
+ for (const speed of [0, 0.5, 1.4, 2.5, 4, 6]) {
+ for (const t of SAMPLES) expect(lowestSoleY(poseFor("walk", t, speed, { seatHeight: 0.52 }))).toBeCloseTo(0, 5);
+ }
+ });
+
+ it("walk swings harder and leans forward into a run", () => {
+ const peak = (speed: number) => Math.max(...SAMPLES.map((t) => Math.abs(poseFor("walk", t, speed, { seatHeight: 0.52 }).leftHip)));
+ expect(peak(4)).toBeGreaterThan(peak(1.2));
+ expect(poseFor("walk", 0.3, 4, { seatHeight: 0.52 }).torsoPitch).toBeGreaterThan(poseFor("walk", 0.3, 1.2, { seatHeight: 0.52 }).torsoPitch);
+ });
+
+ it("idle stands about as tall as the figure", () => {
+ const top = Math.max(...toyPoints(poseFor("idle", 0, 0, { seatHeight: 0.52 })).map((x) => x.p[1]));
+ expect(top).toBeGreaterThan(TOY_HEIGHT - 0.08);
+ expect(top).toBeLessThan(TOY_HEIGHT + 0.03);
+ });
+
+ it("celebrate hops off the floor but never sinks through it", () => {
+ const soles = SAMPLES.map((t) => lowestSoleY(poseFor("celebrate", t, 0, { seatHeight: 0.52 })));
+ expect(Math.min(...soles)).toBeGreaterThan(-1e-6);
+ expect(Math.max(...soles)).toBeGreaterThan(0.05);
+ });
+
+ it("wave raises the right arm above the head line", () => {
+ const pts = new Map(toyPoints(poseFor("wave", 0.4, 0, { seatHeight: 0.52 })).map((x) => [x.name, x.p]));
+ expect(pts.get("rightHand")![1]).toBeGreaterThan(pts.get("rightShoulder")![1] + 0.1);
+ expect(pts.get("rightHand")![0]).toBeLessThan(0);
+ });
+});
+
+describe("blendPose", () => {
+ it("interpolates and writes in place", () => {
+ const a = poseFor("idle", 0, 0, { seatHeight: 0.52 });
+ const b = poseFor("sit", 0, 0, { seatHeight: 0.52 });
+ const mid = blendPose(a, b, 0.5);
+ expect(mid.hipY).toBeCloseTo((a.hipY + b.hipY) / 2, 6);
+ const out = createPose();
+ expect(blendPose(a, b, 1, out)).toBe(out);
+ expect(out.leftHip).toBeCloseTo(b.leftHip, 6);
+ });
+});
+
+describe("toyLookFor", () => {
+ const recipe: FigureRecipe = {
+ contract: 1, archetype: "biped", base: "chibi", parts: {},
+ palette: { skin: "#d8a37c", hair: "#123456", primary: "#6fbf5a", secondary: "#2f4a7a", accent: "#f2c14e", shoes: "#ffffff" },
+ };
+
+ it("is deterministic", () => {
+ expect(toyLookFor(recipe, "agent-7")).toEqual(toyLookFor(recipe, "agent-7"));
+ expect(toyLookFor(null, "agent-7")).toEqual(toyLookFor(null, "agent-7"));
+ });
+
+ it("uses the recipe colours", () => {
+ const look = toyLookFor(recipe, "agent-7");
+ expect(look).toMatchObject({ skin: "#d8a37c", hair: "#123456", shirt: "#6fbf5a", pants: "#2f4a7a", shirtAccent: "#f2c14e", shoes: "#ffffff" });
+ });
+
+ it("keeps skin natural and varies hair styles across identities", () => {
+ const green = toyLookFor({ ...recipe, palette: { ...recipe.palette, skin: "#3fa34d" } }, "orc");
+ expect(isNaturalSkin(green.skin)).toBe(true);
+ const styles = new Set(Array.from({ length: 60 }, (_, i) => toyLookFor(null, `agent-${i}`).hairStyle));
+ expect(styles.size).toBeGreaterThanOrEqual(5);
+ for (let i = 0; i < 30; i += 1) expect(isNaturalSkin(toyLookFor(null, `a${i}`).skin)).toBe(true);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/office/toyFigureModel.ts b/jarvis/ui/web/frontend/src/components/society/office/toyFigureModel.ts
new file mode 100644
index 0000000000..ec300f2a09
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/toyFigureModel.ts
@@ -0,0 +1,606 @@
+/**
+ * The toy-figure look and its procedural animation, as pure data.
+ *
+ * The office characters are chunky avatar-app toys: a very big round head,
+ * a short rounded torso, stubby arms and short legs in chunky sneakers. This
+ * module holds everything that is not rendering — the colour look derived from
+ * a figure recipe, the rig dimensions, the per-mode pose and a tiny forward
+ * kinematics helper — so `ToyFigure.tsx` only applies numbers to joints and the
+ * tests can check the poses without a WebGL context.
+ *
+ * Conventions (figure-local, metres, designed at TOY_HEIGHT = 1.3 m):
+ * - Origin on the floor, the figure faces local +z, its right side is local -x.
+ * - Every joint angle is a raw three.js Euler value (order XYZ), exactly what the
+ * component writes into `rotation`. For a limb hanging along -y a positive
+ * x-rotation swings it backwards (-z), a negative one forwards (+z).
+ * - `hipY` is the bottom of the pelvis (the point that rests on a seat);
+ * the hip joints sit HIP_UP above it.
+ */
+
+import type { FigureRecipe, Palette } from "../figures/figureRecipe";
+import type { FigureMode } from "../figures/FigureRig";
+
+// ---------------------------------------------------------------------------
+// Look
+
+export type HairStyle = "short" | "spiky" | "bun" | "curly" | "long" | "beanie" | "cap" | "bald";
+
+export interface ToyLook {
+ skin: string;
+ hair: string;
+ hairStyle: HairStyle;
+ shirt: string;
+ shirtAccent: string;
+ pants: string;
+ shoes: string;
+ blush: boolean;
+}
+
+/** Natural skin tones, light to dark; the fallback and the snap target for fantasy skins. */
+export const SKIN_TONES = ["#f6d3b8", "#f1c4a0", "#e9b48e", "#d8a37c", "#c68a62", "#a8704c", "#8a5a3c", "#6b4430"] as const;
+const HAIR_COLOURS = ["#2a1d15", "#3b2a20", "#6b4226", "#9e5d47", "#d9b36c", "#c9c9c9", "#1d1d24"] as const;
+const SHIRT_COLOURS = ["#6fbf5a", "#3f7fd6", "#e5674f", "#f2c14e", "#8a63d2", "#2fb3a6", "#ef8fb3", "#2b2b33"] as const;
+const PANTS_COLOURS = ["#2f4a7a", "#3b3f4a", "#23304f", "#5a4636", "#46505e"] as const;
+const DEFAULT_SHOES = "#f4f4f2";
+
+/** Weighted so plain styles dominate and a bald figure stays rare. */
+const HAIR_STYLE_WHEEL: readonly HairStyle[] = [
+ "short", "short", "short", "spiky", "spiky", "bun", "curly", "curly", "long", "long", "beanie", "cap", "cap", "bald",
+];
+
+/** Stable 32-bit FNV-1a hash of a string. */
+export function hashString(value: string): number {
+ let h = 0x811c9dc5;
+ for (let i = 0; i < value.length; i += 1) {
+ h ^= value.charCodeAt(i);
+ h = Math.imul(h, 0x01000193) >>> 0;
+ }
+ return h >>> 0;
+}
+
+function pick<T>(list: readonly T[], hash: number, salt: number): T {
+ return list[(Math.imul(hash ^ salt, 0x9e3779b1) >>> 0) % list.length];
+}
+
+function parseHex(hex: string): [number, number, number] | null {
+ const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim());
+ if (!m) return null;
+ const n = parseInt(m[1], 16);
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
+}
+
+function validColour(value: string | undefined): string | null {
+ return value && parseHex(value) ? value : null;
+}
+
+/** True when a colour could be a human skin tone (warm hue, moderate saturation). */
+export function isNaturalSkin(hex: string): boolean {
+ const rgb = parseHex(hex);
+ if (!rgb) return false;
+ const [r, g, b] = rgb.map((c) => c / 255) as [number, number, number];
+ const max = Math.max(r, g, b);
+ const min = Math.min(r, g, b);
+ const l = (max + min) / 2;
+ if (max === min) return false;
+ const d = max - min;
+ const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
+ let h = 0;
+ if (max === r) h = ((g - b) / d) % 6;
+ else if (max === g) h = (b - r) / d + 2;
+ else h = (r - g) / d + 4;
+ h *= 60;
+ if (h < 0) h += 360;
+ return h >= 8 && h <= 48 && s >= 0.15 && s <= 0.85 && l >= 0.2 && l <= 0.9;
+}
+
+function luminance(hex: string): number {
+ const rgb = parseHex(hex) ?? [200, 160, 130];
+ return (0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2]) / 255;
+}
+
+/** The natural tone closest in brightness to a (possibly fantasy) skin colour. */
+function naturalSkinFor(hex: string): string {
+ const target = luminance(hex);
+ let best: string = SKIN_TONES[0];
+ let bestDist = Infinity;
+ for (const tone of SKIN_TONES) {
+ const dist = Math.abs(luminance(tone) - target);
+ if (dist < bestDist) { best = tone; bestDist = dist; }
+ }
+ return best;
+}
+
+/**
+ * The toy look for one agent: colours from the recipe palette (skin, hair,
+ * primary → shirt, accent → shirt accent, secondary → trousers, shoes), with a
+ * stable hash of `identity` choosing the hair style, blush and any missing colour.
+ */
+export function toyLookFor(recipe: FigureRecipe | null, identity: string): ToyLook {
+ const hash = hashString(identity || "toy");
+ const palette: Partial<Palette> = recipe?.palette ?? {};
+ const rawSkin = validColour(palette.skin);
+ const skin = rawSkin ? (isNaturalSkin(rawSkin) ? rawSkin : naturalSkinFor(rawSkin)) : pick(SKIN_TONES, hash, 0x51);
+ return {
+ skin,
+ hair: validColour(palette.hair) ?? pick(HAIR_COLOURS, hash, 0x7a),
+ hairStyle: pick(HAIR_STYLE_WHEEL, hash, 0x3c),
+ shirt: validColour(palette.primary) ?? pick(SHIRT_COLOURS, hash, 0x19),
+ shirtAccent: validColour(palette.accent) ?? pick(SHIRT_COLOURS, hash, 0x2d),
+ pants: validColour(palette.secondary) ?? pick(PANTS_COLOURS, hash, 0x44),
+ shoes: validColour(palette.shoes) ?? DEFAULT_SHOES,
+ blush: (hash & 0x3) !== 0,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Rig dimensions (metres at TOY_HEIGHT; the component scales uniformly)
+
+export const TOY_HEIGHT = 1.3;
+export const TOY = {
+ /** Pelvis: bottom at hipY, hip joints HIP_UP above it. */
+ pelvis: { w: 0.3, h: 0.14, d: 0.2 },
+ hipUp: 0.06,
+ hipX: 0.085,
+ thigh: 0.18,
+ shin: 0.14,
+ /** Ankle joint to sole. */
+ sole: 0.06,
+ /** Shoe extent along z around the ankle (heel behind, toe in front). */
+ heel: 0.06,
+ toe: 0.12,
+ legRadius: 0.062,
+ /** Torso pivot = hip-joint level; chest block spans 0.02 … 0.28 above it. */
+ torso: { w: 0.34, h: 0.28, d: 0.22 },
+ neckY: 0.3,
+ shoulderX: 0.215,
+ shoulderY: 0.23,
+ upperArm: 0.13,
+ /** Elbow to hand centre. */
+ foreArm: 0.12,
+ armRadius: 0.047,
+ handRadius: 0.052,
+ /** Head ellipsoid radii; its centre sits `head.y` above the neck pivot. */
+ head: { rx: 0.31, ry: 0.29, rz: 0.25, y: 0.3 },
+ /** Hair or a hat adds at most this much behind the head. */
+ hairBack: 0.035,
+} as const;
+
+/** Standing hip-joint height: leg straight down to the sole. */
+export const TOY_LEG = TOY.thigh + TOY.shin + TOY.sole;
+
+/**
+ * Seat-top heights of the office seating (floor to where the pelvis rests), read
+ * from the furniture: desk chair seat centre 0.48 + half its 0.08 thickness;
+ * couch cushions centre 0.50 + half 0.12; meeting chair seat 0.46 + 0.04; the
+ * beanbag's squashed sphere tops out at 0.52 but a body sinks in, so 0.42.
+ */
+export const SEAT_HEIGHT = { chair: 0.52, couch: 0.56, beanbag: 0.42, meeting: 0.5 } as const;
+
+/** Keyboard position relative to the seat centre at a desk (figure-local). */
+export const KEYBOARD = { y: 0.78, z: 0.38 } as const;
+
+/** The deepest any body point may reach behind the seat centre (backrest front at ~0.2). */
+export const SEAT_BACK_CLEARANCE = 0.16;
+
+// ---------------------------------------------------------------------------
+// Pose
+
+export type ToyMode = FigureMode;
+export type Vec3 = [number, number, number];
+
+export interface ToyPose {
+ /** Bottom of the pelvis above the floor (the seat contact point). */
+ hipY: number;
+ /** Pelvis offset forward (+z) from the origin. */
+ hipZ: number;
+ /** Extra lift of the upper body above the pelvis (breathing, walk bounce). */
+ bob: number;
+ torsoPitch: number;
+ torsoYaw: number;
+ torsoRoll: number;
+ headPitch: number;
+ headYaw: number;
+ headRoll: number;
+ leftShoulder: Vec3;
+ rightShoulder: Vec3;
+ leftElbow: number;
+ rightElbow: number;
+ leftHip: number;
+ rightHip: number;
+ leftKnee: number;
+ rightKnee: number;
+ leftAnkle: number;
+ rightAnkle: number;
+}
+
+export function createPose(): ToyPose {
+ return {
+ hipY: TOY_LEG - TOY.hipUp, hipZ: 0, bob: 0,
+ torsoPitch: 0, torsoYaw: 0, torsoRoll: 0,
+ headPitch: 0, headYaw: 0, headRoll: 0,
+ leftShoulder: [0, 0, 0.1], rightShoulder: [0, 0, -0.1],
+ leftElbow: 0, rightElbow: 0,
+ leftHip: 0, rightHip: 0, leftKnee: 0, rightKnee: 0, leftAnkle: 0, rightAnkle: 0,
+ };
+}
+
+const SCALAR_KEYS = [
+ "hipY", "hipZ", "bob", "torsoPitch", "torsoYaw", "torsoRoll", "headPitch", "headYaw", "headRoll",
+ "leftElbow", "rightElbow", "leftHip", "rightHip", "leftKnee", "rightKnee", "leftAnkle", "rightAnkle",
+] as const;
+
+export function copyPose(src: ToyPose, out: ToyPose): ToyPose {
+ for (const key of SCALAR_KEYS) out[key] = src[key];
+ for (let i = 0; i < 3; i += 1) {
+ out.leftShoulder[i] = src.leftShoulder[i];
+ out.rightShoulder[i] = src.rightShoulder[i];
+ }
+ return out;
+}
+
+/** Linear blend a → b by k (0 = a, 1 = b). Writes into `out` (may alias a or b); allocates only without it. */
+export function blendPose(a: ToyPose, b: ToyPose, k: number, out: ToyPose = createPose()): ToyPose {
+ const j = 1 - k;
+ for (const key of SCALAR_KEYS) out[key] = a[key] * j + b[key] * k;
+ for (let i = 0; i < 3; i += 1) {
+ out.leftShoulder[i] = a.leftShoulder[i] * j + b.leftShoulder[i] * k;
+ out.rightShoulder[i] = a.rightShoulder[i] * j + b.rightShoulder[i] * k;
+ }
+ return out;
+}
+
+const TAU = Math.PI * 2;
+const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
+const smooth = (e0: number, e1: number, v: number) => {
+ const x = clamp((v - e0) / (e1 - e0), 0, 1);
+ return x * x * (3 - 2 * x);
+};
+
+/** Walk cycles per second at a ground speed; the stride lengthens with speed. */
+export function walkCadence(speed: number): number {
+ const s = Math.max(0, speed);
+ const stride = 0.45 + 0.1 * Math.min(s, 5);
+ return clamp(s / stride, 1.2, 4.6);
+}
+
+/** Lowest sole point of one leg, relative to the hip joint (y is negative). */
+function soleDrop(hip: number, knee: number, ankle: number): number {
+ const a1 = hip;
+ const a2 = hip + knee;
+ const a3 = a2 + ankle;
+ // A limb along -y rotated by a about x points to (y = -cos a, z = -sin a).
+ const kneeY = -TOY.thigh * Math.cos(a1);
+ const ankleY = kneeY - TOY.shin * Math.cos(a2);
+ const c = Math.cos(a3);
+ const s = Math.sin(a3);
+ // Heel (z = -heel) and toe (z = +toe) at the sole, in the ankle frame, rotated by a3.
+ // Rx(a) maps (0, y, z) to (0, y cos a - z sin a, …).
+ const heelY = ankleY - TOY.sole * c + TOY.heel * s;
+ const toeY = ankleY - TOY.sole * c - TOY.toe * s;
+ return Math.min(heelY, toeY);
+}
+
+/** Put the lower of the two feet exactly on the floor. */
+function ground(p: ToyPose): void {
+ const drop = Math.min(soleDrop(p.leftHip, p.leftKnee, p.leftAnkle), soleDrop(p.rightHip, p.rightKnee, p.rightAnkle));
+ p.hipY = -drop - TOY.hipUp;
+}
+
+function standBase(p: ToyPose): void {
+ p.hipZ = 0; p.bob = 0;
+ p.torsoPitch = 0; p.torsoYaw = 0; p.torsoRoll = 0;
+ p.headPitch = 0; p.headYaw = 0; p.headRoll = 0;
+ p.leftShoulder[0] = 0.05; p.leftShoulder[1] = 0; p.leftShoulder[2] = 0.1;
+ p.rightShoulder[0] = 0.05; p.rightShoulder[1] = 0; p.rightShoulder[2] = -0.1;
+ p.leftElbow = -0.15; p.rightElbow = -0.15;
+ p.leftHip = 0; p.rightHip = 0; p.leftKnee = 0; p.rightKnee = 0; p.leftAnkle = 0; p.rightAnkle = 0;
+}
+
+/** Seated legs: thighs forward along +z, shins hanging straight down, feet level. */
+function seatBase(p: ToyPose, seatHeight: number): void {
+ standBase(p);
+ p.hipY = seatHeight;
+ p.hipZ = 0.05;
+ p.torsoPitch = 0.14;
+ p.leftHip = -Math.PI / 2 + 0.04; p.rightHip = -Math.PI / 2 + 0.04;
+ p.leftKnee = Math.PI / 2 - 0.04; p.rightKnee = Math.PI / 2 - 0.04;
+ // Hands resting on the thighs.
+ p.leftShoulder[0] = -0.55; p.leftShoulder[2] = 0.12;
+ p.rightShoulder[0] = -0.55; p.rightShoulder[2] = -0.12;
+ p.leftElbow = -0.75; p.rightElbow = -0.75;
+}
+
+/**
+ * Two-bone reach in the sagittal plane: shoulder pitch and elbow bend that put
+ * the hand centre at (dy, dz) from the shoulder, in the torso's frame.
+ */
+const REACH = { shoulder: 0, elbow: 0 };
+function reach(dy: number, dz: number): typeof REACH {
+ const l1 = TOY.upperArm;
+ const l2 = TOY.foreArm;
+ const d = clamp(Math.hypot(dy, dz), Math.abs(l1 - l2) + 1e-3, l1 + l2 - 1e-4);
+ const toward = Math.atan2(-dz, -dy);
+ const atShoulder = Math.acos(clamp((l1 * l1 + d * d - l2 * l2) / (2 * l1 * d), -1, 1));
+ const atElbow = Math.acos(clamp((l1 * l1 + l2 * l2 - d * d) / (2 * l1 * l2), -1, 1));
+ REACH.shoulder = toward + atShoulder;
+ REACH.elbow = -(Math.PI - atElbow);
+ return REACH;
+}
+
+/** Inward roll of the typing arms (left arm rolls towards -x, right towards +x). */
+const TYPE_ROLL = 0.1;
+const TYPE_ROLL_COS = Math.cos(TYPE_ROLL);
+
+/** Aim both forearms at the keyboard (work mode; the torso only pitches here). */
+function typeAt(p: ToyPose, t: number): void {
+ const cos = Math.cos(p.torsoPitch);
+ const sin = Math.sin(p.torsoPitch);
+ const shoulderY = p.hipY + TOY.hipUp + p.bob + TOY.shoulderY * cos;
+ const shoulderZ = p.hipZ + TOY.shoulderY * sin;
+ for (let side = 0; side < 2; side += 1) {
+ const tap = 0.012 * Math.max(0, Math.sin(t * TAU * 3.1 + side * 2.1));
+ const wy = KEYBOARD.y + 0.045 + tap - shoulderY;
+ const wz = KEYBOARD.z - shoulderZ + 0.004 * Math.sin(t * TAU * 1.3 + side);
+ // World -> torso frame (undo the torso pitch about x); the inward roll
+ // (applied first, Euler XYZ) shortens the arm's vertical reach by cos(roll).
+ const r = reach((wy * cos + wz * sin) / TYPE_ROLL_COS, -wy * sin + wz * cos);
+ if (side === 0) { p.leftShoulder[0] = r.shoulder; p.leftShoulder[2] = -TYPE_ROLL; p.leftElbow = r.elbow; }
+ else { p.rightShoulder[0] = r.shoulder; p.rightShoulder[2] = TYPE_ROLL; p.rightElbow = r.elbow; }
+ }
+}
+
+export interface PoseOptions {
+ /** Seat-top height for the seated modes (sit, work, sleep), in rig units. */
+ seatHeight: number;
+ /** Walk-cycle phase in cycles; when given it replaces `t * walkCadence(speed)` so cadence changes stay continuous. */
+ phase?: number;
+}
+
+/**
+ * The procedural pose for a mode at time `t` (seconds). Pure; writes into `out`
+ * when given so a render loop can call it every frame without allocating.
+ */
+export function poseFor(mode: ToyMode, t: number, speed: number, opts: PoseOptions, out: ToyPose = createPose()): ToyPose {
+ const p = out;
+ const breathe = Math.sin(t * TAU * 0.28);
+ switch (mode) {
+ case "walk": {
+ standBase(p);
+ const s = Math.max(0, speed);
+ const phase = (opts.phase ?? t * walkCadence(s)) * TAU;
+ const move = smooth(0, 0.35, s);
+ const run = smooth(2.6, 3.6, s);
+ const swing = move * (0.32 + 0.1 * Math.min(s, 3) + 0.2 * run);
+ const sL = Math.sin(phase);
+ const sR = -sL;
+ // Hip: negative = forward. The left leg leads when sL > 0.
+ p.leftHip = -swing * sL;
+ p.rightHip = -swing * sR;
+ // The knee lifts while its leg swings through (the half cycle it moves forward).
+ const liftL = Math.max(0, Math.cos(phase));
+ const liftR = Math.max(0, -Math.cos(phase));
+ const kneeAmp = move * (0.55 + 0.5 * run);
+ p.leftKnee = 0.08 * move + kneeAmp * liftL;
+ p.rightKnee = 0.08 * move + kneeAmp * liftR;
+ // Keep the sole roughly level; toes lift slightly on the trailing foot.
+ p.leftAnkle = -(p.leftHip + p.leftKnee) * 0.75;
+ p.rightAnkle = -(p.rightHip + p.rightKnee) * 0.75;
+ // Arms swing opposite to the legs, bent further into a run.
+ const armSwing = move * (0.35 + 0.35 * run);
+ p.leftShoulder[0] = armSwing * sL;
+ p.rightShoulder[0] = armSwing * sR;
+ p.leftElbow = -0.25 - 1.0 * run;
+ p.rightElbow = -0.25 - 1.0 * run;
+ p.torsoPitch = move * (0.05 + 0.02 * Math.min(s, 3)) + 0.16 * run;
+ p.torsoYaw = 0.08 * move * sL;
+ p.headPitch = -0.6 * p.torsoPitch * run;
+ p.bob = move * (0.012 + 0.012 * run) * Math.abs(Math.cos(phase));
+ ground(p);
+ return p;
+ }
+ case "sit": {
+ seatBase(p, opts.seatHeight);
+ p.bob = 0.004 * breathe;
+ p.headYaw = 0.18 * Math.sin(t * 0.37);
+ p.headPitch = 0.04 + 0.03 * Math.sin(t * 0.23);
+ return p;
+ }
+ case "work": {
+ seatBase(p, opts.seatHeight);
+ // Scoot forward and lean in so the short arms reach the keyboard.
+ p.hipZ = 0.08;
+ p.torsoPitch = 0.3;
+ p.bob = 0.003 * breathe;
+ p.headPitch = -0.14 + 0.02 * Math.sin(t * 0.5); // net ~0.16 rad down with the lean
+ p.headYaw = 0.05 * Math.sin(t * 0.31);
+ // Forearms forward to the keyboard; small alternating typing jitter.
+ typeAt(p, t);
+ return p;
+ }
+ case "sleep": {
+ seatBase(p, opts.seatHeight);
+ p.torsoPitch = 0.26 + 0.012 * Math.sin(t * TAU * 0.2);
+ p.torsoRoll = 0.08;
+ p.headPitch = 0.42 + 0.03 * Math.sin(t * TAU * 0.2);
+ p.headRoll = 0.3;
+ p.leftShoulder[0] = -0.3; p.rightShoulder[0] = -0.3;
+ p.leftElbow = -0.6; p.rightElbow = -0.6;
+ p.leftHip += 0.05; p.rightHip += 0.08;
+ p.leftShoulder[2] = 0.14; p.rightShoulder[2] = -0.14;
+ return p;
+ }
+ case "wave": {
+ standBase(p);
+ p.bob = 0.004 * breathe;
+ // Right arm up and out to the figure's right (-x), waving side to side.
+ p.rightShoulder[0] = -0.25;
+ p.rightShoulder[2] = -2.45 + 0.28 * Math.sin(t * TAU * 2.2);
+ p.rightElbow = -0.35;
+ p.torsoRoll = 0.04;
+ p.headRoll = -0.08;
+ p.headPitch = -0.05;
+ ground(p);
+ return p;
+ }
+ case "talk": {
+ standBase(p);
+ p.bob = 0.004 * breathe;
+ p.headPitch = 0.07 * Math.sin(t * TAU * 1.6) - 0.02;
+ p.headYaw = 0.12 * Math.sin(t * 0.8);
+ p.torsoYaw = 0.05 * Math.sin(t * 0.6);
+ p.rightShoulder[0] = -0.45 + 0.15 * Math.sin(t * TAU * 0.9);
+ p.rightElbow = -1.1 + 0.3 * Math.sin(t * TAU * 1.3);
+ p.leftShoulder[0] = -0.2 + 0.1 * Math.sin(t * TAU * 0.7 + 1.2);
+ p.leftElbow = -0.7 + 0.2 * Math.sin(t * TAU * 1.1 + 0.5);
+ ground(p);
+ return p;
+ }
+ case "celebrate": {
+ standBase(p);
+ const hop = Math.sin(t * TAU * 1.6);
+ const air = Math.max(0, hop);
+ const crouch = Math.max(0, -hop);
+ p.leftHip = -0.35 * crouch; p.rightHip = -0.35 * crouch;
+ p.leftKnee = 0.7 * crouch; p.rightKnee = 0.7 * crouch;
+ p.leftAnkle = -0.35 * crouch; p.rightAnkle = -0.35 * crouch;
+ p.leftShoulder[0] = -0.2; p.rightShoulder[0] = -0.2;
+ p.leftShoulder[2] = 2.6 + 0.2 * Math.sin(t * TAU * 3.2);
+ p.rightShoulder[2] = -2.6 - 0.2 * Math.sin(t * TAU * 3.2 + 1);
+ p.leftElbow = -0.2; p.rightElbow = -0.2;
+ p.headPitch = -0.15;
+ ground(p);
+ p.hipY += 0.11 * air;
+ return p;
+ }
+ case "idle":
+ default: {
+ standBase(p);
+ p.bob = 0.005 * breathe;
+ p.torsoRoll = 0.025 * Math.sin(t * TAU * 0.18);
+ p.headRoll = -0.5 * p.torsoRoll;
+ p.headYaw = 0.25 * Math.sin(t * 0.29) * Math.sin(t * 0.11);
+ p.leftShoulder[0] = 0.04 * breathe;
+ p.rightShoulder[0] = 0.04 * breathe;
+ p.leftHip = -0.02; p.rightHip = 0.02;
+ ground(p);
+ return p;
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Forward kinematics (tests and the work-mode reach)
+
+type Mat3 = [number, number, number, number, number, number, number, number, number];
+
+/** Rotation matrix of a three.js Euler in XYZ order (row-major). */
+function eulerXYZ(x: number, y: number, z: number): Mat3 {
+ const a = Math.cos(x), b = Math.sin(x);
+ const c = Math.cos(y), d = Math.sin(y);
+ const e = Math.cos(z), f = Math.sin(z);
+ const ae = a * e, af = a * f, be = b * e, bf = b * f;
+ return [
+ c * e, -c * f, d,
+ af + be * d, ae - bf * d, -b * c,
+ bf - ae * d, be + af * d, a * c,
+ ];
+}
+
+function mul(m: Mat3, n: Mat3): Mat3 {
+ const r = new Array(9).fill(0) as Mat3;
+ for (let i = 0; i < 3; i += 1)
+ for (let j = 0; j < 3; j += 1)
+ r[i * 3 + j] = m[i * 3] * n[j] + m[i * 3 + 1] * n[3 + j] + m[i * 3 + 2] * n[6 + j];
+ return r;
+}
+
+function apply(m: Mat3, v: Vec3): Vec3 {
+ return [
+ m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
+ m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
+ m[6] * v[0] + m[7] * v[1] + m[8] * v[2],
+ ];
+}
+
+interface Frame { pos: Vec3; rot: Mat3 }
+
+function child(parent: Frame, offset: Vec3, euler: Vec3): Frame {
+ const o = apply(parent.rot, offset);
+ return { pos: [parent.pos[0] + o[0], parent.pos[1] + o[1], parent.pos[2] + o[2]], rot: mul(parent.rot, eulerXYZ(euler[0], euler[1], euler[2])) };
+}
+
+function at(frame: Frame, local: Vec3): Vec3 {
+ const o = apply(frame.rot, local);
+ return [frame.pos[0] + o[0], frame.pos[1] + o[1], frame.pos[2] + o[2]];
+}
+
+export interface ToyPoint { name: string; p: Vec3 }
+
+/**
+ * Surface sample points of the posed figure in figure-local space: joints plus
+ * the outer extents of pelvis, chest, head (incl. hair), limbs and shoes. The
+ * joint layout mirrors `ToyFigure.tsx` exactly.
+ */
+export function toyPoints(pose: ToyPose): ToyPoint[] {
+ const pts: ToyPoint[] = [];
+ const push = (name: string, p: Vec3) => pts.push({ name, p });
+ const pelvis: Frame = { pos: [0, pose.hipY, pose.hipZ], rot: eulerXYZ(0, 0, 0) };
+ const { w, h, d } = TOY.pelvis;
+ for (const sx of [-1, 1]) for (const sy of [0, 1]) for (const sz of [-1, 1])
+ push("pelvis", at(pelvis, [sx * w / 2, sy * h, sz * d / 2]));
+
+ const torso = child(pelvis, [0, TOY.hipUp + pose.bob, 0], [pose.torsoPitch, pose.torsoYaw, pose.torsoRoll]);
+ const t = TOY.torso;
+ for (const sx of [-1, 1]) for (const y of [0.02, 0.15, 0.28]) for (const sz of [-1, 1])
+ push("torso", at(torso, [sx * t.w / 2, y, sz * t.d / 2]));
+
+ const head = child(torso, [0, TOY.neckY, 0], [pose.headPitch, pose.headYaw, pose.headRoll]);
+ const hd = TOY.head;
+ const back = hd.rz + TOY.hairBack;
+ for (let i = 0; i <= 8; i += 1) {
+ const a = (i / 8) * Math.PI - Math.PI / 2; // −90° (bottom) … +90° (top)
+ const y = hd.y + Math.sin(a) * hd.ry;
+ const r = Math.cos(a);
+ push("head", at(head, [0, y, -back * r]));
+ push("head", at(head, [0, y, hd.rz * r]));
+ push("head", at(head, [hd.rx * r, y, 0]));
+ push("head", at(head, [-hd.rx * r, y, 0]));
+ }
+
+ const arms: Array<[string, number, Vec3, number]> = [
+ ["left", 1, pose.leftShoulder, pose.leftElbow],
+ ["right", -1, pose.rightShoulder, pose.rightElbow],
+ ];
+ for (const [side, sx, sh, el] of arms) {
+ const shoulder = child(torso, [sx * TOY.shoulderX, TOY.shoulderY, 0], sh);
+ push(`${side}Shoulder`, shoulder.pos);
+ const elbow = child(shoulder, [0, -TOY.upperArm, 0], [el, 0, 0]);
+ push(`${side}Elbow`, elbow.pos);
+ push(`${side}ElbowBack`, at(elbow, [0, 0, -TOY.armRadius]));
+ push(`${side}Hand`, at(elbow, [0, -TOY.foreArm, 0]));
+ }
+
+ const legs: Array<[string, number, number, number, number]> = [
+ ["left", 1, pose.leftHip, pose.leftKnee, pose.leftAnkle],
+ ["right", -1, pose.rightHip, pose.rightKnee, pose.rightAnkle],
+ ];
+ for (const [side, sx, hp, kn, an] of legs) {
+ const hip = child(pelvis, [sx * TOY.hipX, TOY.hipUp, 0], [hp, 0, 0]);
+ push(`${side}Hip`, hip.pos);
+ push(`${side}ThighBack`, at(hip, [0, -TOY.thigh / 2, -TOY.legRadius]));
+ const knee = child(hip, [0, -TOY.thigh, 0], [kn, 0, 0]);
+ push(`${side}Knee`, knee.pos);
+ const ankle = child(knee, [0, -TOY.shin, 0], [an, 0, 0]);
+ push(`${side}Ankle`, ankle.pos);
+ push(`${side}Heel`, at(ankle, [0, -TOY.sole, -TOY.heel]));
+ push(`${side}Toe`, at(ankle, [0, -TOY.sole, TOY.toe]));
+ }
+ return pts;
+}
+
+/** The lowest shoe-sole point of the posed figure. */
+export function lowestSoleY(pose: ToyPose): number {
+ let min = Infinity;
+ for (const { name, p } of toyPoints(pose)) if (name.endsWith("Heel") || name.endsWith("Toe")) min = Math.min(min, p[1]);
+ return min;
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/useDeskChats.ts b/jarvis/ui/web/frontend/src/components/society/office/useDeskChats.ts
new file mode 100644
index 0000000000..c0e5d8b2ec
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/useDeskChats.ts
@@ -0,0 +1,58 @@
+/**
+ * Live chat tails for the agents who sit at their desk right now.
+ *
+ * Polls the existing session endpoint only for seated agents, one request per
+ * agent per interval, jittered so windows and agents never fire in lockstep
+ * (AP-33). A failed poll keeps the last good screen; it is logged, not shown.
+ */
+import { useEffect, useRef, useState } from "react";
+import { fetchAgentChatSession } from "@/lib/agentChatApi";
+import { chatLines, chatVersion, type ChatLine } from "./deskChat";
+import { seatedAtDesk } from "./walkerRegistry";
+
+const POLL_MS = 2500;
+const JITTER_MS = 1200;
+/** Never more sessions in flight per tick than this, however many agents sit. */
+const MAX_PER_TICK = 6;
+
+export interface DeskChat { lines: ChatLine[]; version: string }
+
+export function useDeskChats(sessions: ReadonlyMap<string, string>, awake: boolean): ReadonlyMap<string, DeskChat> {
+ const [chats, setChats] = useState<ReadonlyMap<string, DeskChat>>(new Map());
+ const sessionsRef = useRef(sessions);
+ sessionsRef.current = sessions;
+ useEffect(() => {
+ if (!awake) return;
+ let cancelled = false;
+ let timer: ReturnType<typeof setTimeout>;
+ const tick = async () => {
+ const due = [...seatedAtDesk].filter((id) => sessionsRef.current.has(id)).slice(0, MAX_PER_TICK);
+ const results = await Promise.all(due.map(async (agentId) => {
+ try {
+ const detail = await fetchAgentChatSession(sessionsRef.current.get(agentId)!);
+ return [agentId, { lines: chatLines(detail.events), version: chatVersion(detail.events) }] as const;
+ } catch (error) {
+ // The monitor keeps its last good frame; the chat view itself reports real failures.
+ console.debug("Desk chat poll failed", agentId, error);
+ return null;
+ }
+ }));
+ if (cancelled) return;
+ setChats((prev) => {
+ let next: Map<string, DeskChat> | null = null;
+ for (const result of results) {
+ if (!result) continue;
+ const [agentId, chat] = result;
+ if (prev.get(agentId)?.version === chat.version) continue;
+ next ??= new Map(prev);
+ next.set(agentId, chat);
+ }
+ return next ?? prev;
+ });
+ timer = setTimeout(() => void tick(), POLL_MS + Math.random() * JITTER_MS);
+ };
+ timer = setTimeout(() => void tick(), Math.random() * JITTER_MS);
+ return () => { cancelled = true; clearTimeout(timer); };
+ }, [awake]);
+ return chats;
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/walkerRegistry.ts b/jarvis/ui/web/frontend/src/components/society/office/walkerRegistry.ts
index a62bf1e263..e27bdb4ec7 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/walkerRegistry.ts
+++ b/jarvis/ui/web/frontend/src/components/society/office/walkerRegistry.ts
@@ -9,3 +9,6 @@ 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>();
+
+/** Agents sitting at their own desk right now — their monitor shows their chat. */
+export const seatedAtDesk = 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.json
index 83e59f1ea3..82a07b017a 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
@@ -721,7 +721,7 @@
},
"office": {
"title": "Agenten-Büro",
- "subtitle": "{0} Agenten im Büro",
+ "subtitle": "Agenten im Büro: {0}",
"viewport": "Karte des Agenten-Büros",
"loading": "Das Büro wird eingerichtet…",
"no_graphics": "3D-Darstellung ist hier nicht verfügbar. Den Status aller Agenten siehst du weiterhin in der Agentenliste.",
@@ -746,7 +746,7 @@
"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",
+ "draft_count": "{0} für ein neues Team ausgewählt · Teamraum öffnen",
"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",
@@ -762,11 +762,11 @@
"team_gather": "Versammeln",
"wardrobe_name": "Dein Name",
"you": "Du",
- "wardrobe_body": "Wähle deine Figur – die Farben kannst du mischen.",
+ "wardrobe_body": "Wähle Frisur oder Kopfbedeckung – 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_body": "Gerade frei: {0}. 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",
@@ -804,7 +804,25 @@
"activity_board": "Am Board",
"activity_wander": "Schlendert",
"activity_visit": "Plaudert",
- "activity_called": "Kommt rüber"
+ "activity_called": "Kommt rüber",
+ "break_none": "Gerade ist niemand frei.",
+ "break_called": "Unterwegs: {0}",
+ "call_sent": "{0} kommt rüber.",
+ "show_agent": "{0} auf der Karte zeigen",
+ "team_gather_label": "{0} am Tisch versammeln",
+ "team_open_label": "Chat von {0} öffnen",
+ "team_need_more": "Wähle mindestens zwei Agenten, um ein Team zu erstellen.",
+ "manage_empty": "Noch keine Agenten. Am Empfang stellst du den ersten ein.",
+ "wardrobe_saved": "Nur in diesem Browser gespeichert.",
+ "count_paused": "{0} pausiert",
+ "hair_short": "Kurz",
+ "hair_spiky": "Stachelig",
+ "hair_bun": "Dutt",
+ "hair_curly": "Locken",
+ "hair_long": "Lang",
+ "hair_beanie": "Mütze",
+ "hair_cap": "Cap",
+ "hair_bald": "Glatze"
}
}
}
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 3563f60ff9..3d57f4dcc0 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
@@ -721,7 +721,7 @@
},
"office": {
"title": "Agent office",
- "subtitle": "{0} agents on the floor",
+ "subtitle": "Agents on the floor: {0}",
"viewport": "Agent office map",
"loading": "Setting up the office…",
"no_graphics": "3D rendering is unavailable here. Every agent's status stays available in the agents list.",
@@ -746,7 +746,7 @@
"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",
+ "draft_count": "{0} picked for a new team · open 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",
@@ -762,11 +762,11 @@
"team_gather": "Gather",
"wardrobe_name": "Your name",
"you": "You",
- "wardrobe_body": "Pick your body — colours can be shuffled.",
+ "wardrobe_body": "Pick a hairstyle or hat — 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_body": "Free right now: {0}. 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",
@@ -804,7 +804,25 @@
"activity_board": "At the board",
"activity_wander": "Strolling",
"activity_visit": "Chatting",
- "activity_called": "Coming over"
+ "activity_called": "Coming over",
+ "break_none": "Nobody is free right now.",
+ "break_called": "On their way: {0}",
+ "call_sent": "{0} is coming over.",
+ "show_agent": "Show {0} on the map",
+ "team_gather_label": "Gather {0} at the table",
+ "team_open_label": "Open the chat of {0}",
+ "team_need_more": "Pick at least two agents to create a team.",
+ "manage_empty": "No agents yet. Reception hires the first one.",
+ "wardrobe_saved": "Saved in this browser only.",
+ "count_paused": "{0} paused",
+ "hair_short": "Short",
+ "hair_spiky": "Spiky",
+ "hair_bun": "Bun",
+ "hair_curly": "Curly",
+ "hair_long": "Long",
+ "hair_beanie": "Beanie",
+ "hair_cap": "Cap",
+ "hair_bald": "Bald"
}
}
}
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 ee1e9137f3..9103bfd752 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
@@ -721,7 +721,7 @@
},
"office": {
"title": "Oficina de agentes",
- "subtitle": "{0} agentes en la oficina",
+ "subtitle": "Agentes en la oficina: {0}",
"viewport": "Mapa de la oficina de agentes",
"loading": "Preparando la oficina…",
"no_graphics": "El renderizado 3D no está disponible aquí. El estado de cada agente sigue en la lista de agentes.",
@@ -746,7 +746,7 @@
"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",
+ "draft_count": "{0} elegidos para un equipo nuevo · abrir 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",
@@ -762,11 +762,11 @@
"team_gather": "Reunir",
"wardrobe_name": "Tu nombre",
"you": "Tú",
- "wardrobe_body": "Elige tu cuerpo; los colores se pueden mezclar.",
+ "wardrobe_body": "Elige peinado o sombrero; 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_body": "Libres ahora: {0}. 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",
@@ -804,7 +804,25 @@
"activity_board": "En el tablero",
"activity_wander": "Paseando",
"activity_visit": "Charlando",
- "activity_called": "Viene hacia ti"
+ "activity_called": "Viene hacia ti",
+ "break_none": "Ahora mismo no hay nadie libre.",
+ "break_called": "En camino: {0}",
+ "call_sent": "{0} viene hacia ti.",
+ "show_agent": "Mostrar a {0} en el mapa",
+ "team_gather_label": "Reunir a {0} en la mesa",
+ "team_open_label": "Abrir el chat de {0}",
+ "team_need_more": "Elige al menos dos agentes para crear un equipo.",
+ "manage_empty": "Aún no hay agentes. En recepción contratas al primero.",
+ "wardrobe_saved": "Guardado solo en este navegador.",
+ "count_paused": "{0} en pausa",
+ "hair_short": "Corto",
+ "hair_spiky": "De punta",
+ "hair_bun": "Moño",
+ "hair_curly": "Rizado",
+ "hair_long": "Largo",
+ "hair_beanie": "Gorro",
+ "hair_cap": "Gorra",
+ "hair_bald": "Calvo"
}
}
}