Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(verse): rebuild the agents floor as a team campus (#561)
Ruben Lütke2f34bb49a8dd
diff --git a/docs/agent-society/level-system.md b/docs/agent-society/level-system.mdindex 21f839b081..a7784570ec 100644--- a/docs/agent-society/level-system.md+++ b/docs/agent-society/level-system.md@@ -50,7 +50,7 @@ works with any single key.| Source | Pays | XP | Limit ||---|---|---|---|| `daily_visit` | person | 25 | once per day (server date) |-| `floor_discovered` | person | 20 | once per floor (`agents`, `coding`, `arcade`) |+| `floor_discovered` | person | 20 | once per floor (`agents`, `coding`, `arcade`, `hall`) || `dog_petted` | person | 3 | every 60 s, 30/day || `dog_treat` | person | 10 | every 5 min, 30/day || `arcade_round` | person | 8 | every 45 s, 80/day (a scored round) |@@ -147,7 +147,8 @@ Reduced motion keeps the information (card, plate, toast) and drops the motion.- On the figures: enlisted insignia on both upper sleeves, officer andgeneral insignia on shoulder boards, the decoration over the left breastpocket (the aiguillette from the right shoulder), the cap on the head.-- **The Level Hall** on the agents floor (office-map.md §5f): the rank wall,+- **The Level Hall**, the building's top floor (floor 3 in the elevator,+ office-map.md §5f; its first visit pays `floor_discovered` like every floor): the rank wall,the studio dais, a display case per uniform piece along the runner and theservice guide. Stepping on the dais opens the screen's Studio page, theguide its Overview, a case its piece on the promotion road.diff --git a/docs/agent-society/office-map.md b/docs/agent-society/office-map.mdindex 1a31e6bb21..b5f479b51c 100644--- a/docs/agent-society/office-map.md+++ b/docs/agent-society/office-map.md@@ -4,7 +4,12 @@ Product name: **Jarvis Verse** (since 2026-09-30). The interface calls thewhole map, the Map tab and the IDE side-panel tab "Jarvis Verse"; the code keepsits `office` identifiers, and rooms and floors inside it keep their own names.-Status: **walkable prototype built 2026-09-28, awaiting the maintainer's visual review.**+Status: **team campus (2026-10-12).** The agents floor was rebuilt from the+2026-09-28 prototype: one studio per team instead of provider departments, a+larger plan with an atrium and commons, stations that are the objects+themselves, team-aware behaviour and the Level Hall on its own floor (§5g–§5i).+Sections 2–5 describe the engine and the rooms the rebuild kept; where they+disagree with §5g–§5i, the later sections hold.It replaces the Mars colony as the renderer behind **Agents > Jarvis Verse**. The Marscode, its backend contracts and the communications station remain in the treeand reachable from the Agents workspace; only the map surface changed.@@ -25,20 +30,20 @@ a name pill show the run state. It is a projection of the roster only: the mapnever moves an agent, starts work or invents activity (world-behaviour-manual§1 still holds).-## 2. Style guide (derived from the maintainer's reference screenshots)+## 2. Style guide| Aspect | Rule ||---|---|-| Genre | Stylised "toy office" diorama: chunky low-poly 3D, not anime, not pixel art, not realistic. Close to casual social-game and avatar-app styling. |+| Genre | Stylised "toy office" diorama: chunky low-poly 3D, not anime, not pixel art, not realistic. || Characters | Chibi proportions (big head, short body), dot eyes, flat matte colours, no textures. Seated at desks; the stored figure recipe is kept, agents without one get a stable chibi look. || Furniture | A contemporary workplace built from rounded primitives: light-oak bench desks on black steel T-legs with a white pedestal and a felt privacy screen, slim monitors on arms, ergonomic chairs with a mesh back on a five-star base, open oak-and-steel shelving, low modular sofas on slim legs, tall charcoal planters with full crowns. Department back walls are fluted acoustic felt with a charcoal name plate in white type and oak ledges with small plants. || Materials | Mostly matte; black steel and chrome arms carry a little metalness. Light microcement floor, a rounded felt rug per department whose colour also dyes that department's felt screens and seat fabric (`DEPARTMENT_ZONES`). Rooms: slate felt (team), terrazzo (wardrobe), pale stone (reception), light oak (break room). Glass walls and the outer balustrade have slim black frames. || Light | Cool sky / neutral ground hemisphere light plus one soft, slightly warm directional sun with PCF shadows. Always bright enough to read, never moody. |-| Setting | The floor floats in a starry night sky behind glass railings. |-| Camera | Perspective, 35° FOV, three-quarter view from the south-east about 40° below the horizon. Orbit, pan and zoom within limits (20°–72° polar, 4–140 m). Home view frames the occupied desks. |-| Labels | Dark translucent pill above each agent: hexagon badge (initial, star for the lead), name, state dot; the state word only when it is not idle. Scale is clamped by distance. |+| Setting | The agents floor and the Level Hall are floors of a tower in a city at night: a window wall on the far sides, the tower's body below, lit towers outside (§5h). The coding floor still floats in its own violet night behind glass railings. |+| Camera | Perspective, 35° FOV, three-quarter view from the south-east about 40° below the horizon. Orbit, pan and zoom within limits (20°–72° polar, from 2.5 m out to wherever the overview needs: 140 m at least, more on a large campus). The overview frames the whole floor (§5i). |+| Labels | From across the floor an agent is one small state dot. The dark translucent plate (hexagon badge with the initial or the lead's star, name, rank chip, state dot and activity) fades in over the dot when the camera or the person is near, when the pointer or keyboard focus rests on the agent, or when it is selected (§5g). Scale is clamped by distance. || State language | Green = working (pulsing floor ring, code on the monitor), amber = waiting for the person, grey = idle (smiley monitor) or paused (dark monitor). |-| HUD | Theme-token cards over the canvas (title, working/waiting/idle counts, Overview and Agents list buttons), so light and dark mode both work. The diorama itself keeps one palette in both modes. |+| HUD | Theme-token cards over the canvas, so light and dark mode both work: one floor card (name and who is doing what), the level card, the minimap, a small icon toolbar and one prompt (§5g). The diorama itself keeps one palette in both modes. |## 3. Technology decision@@ -54,25 +59,25 @@ target runs WebGL.## 4. Floor plan and data model-`officeLayout.ts` is pure and tested. It builds the whole floor from the roster:--- **North strip:** lead office (lead-tier agents), team room (long table, board),- wardrobe (lockers, mirror). Glass walls with a door towards the office.-- **Middle:** departments = provider families (`providerLabel`; empty means- Jarvis' own brain), two columns, at least four (spare ones are "Open space"),- at most six (the rest fold into "Other"). Benches of back-to-back desks.-- **Spawn point (both floors):** a round pad with a terminal on the crossing of- the centre aisle and the cross aisle nearest the floor's middle, the one plaza- every route passes. `layout.arrival` (south of the terminal) is where anyone+The plans are pure and tested. `officeLayout.ts` holds the shared vocabulary+(types, footprints, desk and wall helpers) and the coding floor's plan;+`buildOfficeLayout(agents, { variant, teams })` hands the agents floor to+`campusLayout.ts`. The Level Hall (`hallFloorLayout.ts`) and the arcade+(`arcade/arcadeFloorLayout.ts`) have floors of their own.++- **Agents floor: a team campus** (§5h). North strip: focus booths, lead+ office, team room, wardrobe, library. Middle: one studio per team, shoulder+ to shoulder in rows of four, two either side of the boulevard. South strip:+ café, lobby with the elevator, break room.+- **Coding floor:** north strip Mission Control, team room, server room;+ departments = IDE workspaces, two columns, at least four (spare ones are+ "Open space"), at most six (the rest fold into "Other"); south strip lobby+ and break room.+- **Spawn point (both working floors):** a round pad with a terminal. On the+ agents floor it stands in the atrium, where the two boulevards cross; on the+ coding floor on the crossing of the centre aisle and the cross aisle nearest+ the floor's middle. `layout.arrival` (south of the terminal) is where anyonenew to the floor appears.-- **South strip:** an open reception/lobby with the elevator, the reception desk- and the agent board; a walled break room with couches, coffee bar, water- cooler, arcade and beanbags.-- **Level Hall (agents floor only):** an east wing one aisle beyond the office,- across the floor's whole depth, with doors onto the north aisle, the spawn- point's cross aisle (the main door with the sign) and the south aisle. The- coding floor keeps the office's footprint without it; both floors share the- same west edge, so the elevator stands at the same spot on each.- **Furniture** has fixed footprints (`FURNITURE_SIZE`) shared by renderer andnavigation; **spots** are hangout places with pose and facing; **checkpoints**are action places; **obstacles** are every solid footprint.@@ -84,32 +89,39 @@ target runs WebGL.smoothing, and a final snap onto seats that sit inside a furniture footprint.- **Agents** (`officeBehavior.ts`, `OfficeAgents.tsx`): working → seated at theirown screen; waiting → standing at the desk, waving; paused → napping on a- couch; idle → a weighted day of coffee, couch, window, arcade, books, water- cooler, team table, strolling or chatting at a busy colleague's desk. Spots are- reserved so nobody sits on anybody. All of it is client-side, deterministic- per agent, costs no tokens and never starts or stops work. Reduced motion- places agents without walking. Agents created while the office is open appear- on the spawn pad in a column of light and walk to their desk.+ couch; idle → a weighted day that, on the agents floor, happens mostly in and+ around the agent's own team studio and only sometimes at the shared places+ (§5i). A running round of a team and a message from one agent to another are+ shown as they happen (§5i). Places are reserved so nobody sits or stands on+ anybody. All of it is client-side, deterministic per agent, costs no tokens+ and never starts or stops work. Reduced motion places agents without walking.+ Agents created while the office is open appear on the spawn pad in a column+ of light and walk to their desk.- **The person's character** (`OfficePlayer.tsx`, `playerProfile.ts`): WASD /- arrows (camera-relative, Shift runs) or click the floor to walk; E interacts- with the nearest agent or checkpoint. Name and body are chosen in the- wardrobe and stored per browser profile (not roster data).+ arrows (camera-relative, Shift runs) or click the floor to walk; a click+ draws the route as dots to a ring at the destination. E interacts with the+ nearest agent or station. The character walks round people and furniture+ and never comes to rest inside anything solid (§5i). Name and body are+ chosen in the wardrobe and stored per browser profile (not roster data).- **Camera** (`OfficeCameraRig.tsx`): one orbit camera that glides after thecharacter; zoom out and it is the overview. Everything stays clickable fromafar, so walking is optional. A right-drag pan or a fly-to stops following;- moving resumes it.-- **Checkpoints** (`OfficePanels.tsx`): spawn point → spawn a new Jarvis agent- (existing create dialog; a host without one, like the IDE side panel, gets the- office's own copy); reception → help, and create an agent too; agent board → list, show on map, open, agent management; team room →- pick agents and create a team (existing chat groups), gather teams at the- table; wardrobe → your look; lead office → talk to the lead; break room → call- free agents for a coffee break (visual only).+ moving resumes it. Inside a walled room the walls between camera and+ character drop to a kerb (§5i).+- **Stations** (`stations.ts`, `StationObjects.tsx`, `OfficePanels.tsx`): every+ action place is an object of the room, one station per job. Spawn terminal →+ a new Jarvis agent (the app's create dialog; a host without one, like the IDE+ side panel, creates at once); reception desk → the directory (agents, places,+ controls, settings); team board → teams (the existing chat groups); a team+ studio's board → that team; wardrobe mirror → your look; the lead's desk →+ talk to the lead; coffee bar → call free agents for a coffee break (visual+ only). §5g has the details.- **Agent panel:** open chat, walk there, call over, show on map, add to a new team.## 5a. Figures, pets and live monitors (2026-09-28, round 2)- **Toy figures** (`ToyFigure.tsx`, `toyFigureModel.ts`): every agent and the- person are procedural toy characters in the reference style — big round+ person are procedural toy characters — big roundhead, dot eyes, smile, T-shirt, trousers, chunky sneakers, eight hair/hatstyles. Colours come from the stored figure recipe; hair from a stable hash(the person picks it in the wardrobe). Poses are pure and tested: the hips@@ -137,7 +149,9 @@ target runs WebGL.- **Live monitors** (`LiveMonitors.tsx`, `useDeskChats.ts`, `deskChat.ts`): anagent seated at its own desk shows the tail of its chat (user lines, replies,running tools) on its monitor, refreshed by jittered polling of the existing- session endpoint for seated agents only (at most six per tick). Clicking the+ session endpoint for seated agents only (at most six reads at once, the+ longest unread first, so every monitor of a full floor gets its turn; each+ read has an eight-second timeout and the ticks do not wait for it). Clicking thescreen dives the camera into it and then opens that agent's chat.Follow-up: a `limit` query on the session endpoint, so long chats are notfetched whole.@@ -236,8 +250,11 @@ The lead office is the one room that breaks the plain toy-office palette onpurpose, so the boss's room reads as the most precious place on the floor(`LeadSuite.tsx`, colours in `LEAD_SUITE`):-- **Shell:** dark walnut chevron floor, brass-framed walls with warm-tinted- glass, a gold-on-black door sign.+- **Shell:** smoked-oak chevron floor, the same steel-and-glass walls as+ every room, a door sign lettered in bronze. Since 2026-10-12 the suite's+ palette is the campus's own a tone deeper (smoked oak, bronze, cognac+ leather, a slate rug; see 5h), so where this section says walnut, brass,+ oxblood or navy, read those.- **Feature wall (north, 2.9 m):** walnut slats around a backlit black-glassstar emblem, two lit bookcases with books, trophies and vases, warm LED coves.- **Executive desk:** 2.4 m walnut desk with a brass edge, three monitors, a@@ -287,9 +304,9 @@ cabinets. No agents work here; it is a place for the person (and their pet,which follows like on the coding floor).- **Elevator**: pressing the call button (click, or E at the doors) opens a- floor picker (`ElevatorPanel.tsx`) that lists all three floors top first;+ floor picker (`ElevatorPanel.tsx`) that lists all four floors top first;a click, Enter on the focused floor or the floor's number key (0 agents,- 1 coding, 2 arcade) rides there, Escape closes it. The call button shows+ 1 coding, 2 arcade, 3 Level Hall) rides there, Escape closes it. The call button showsup, down or both arrows depending on the floor (`callDirection`).- **Floor plan** (`arcade/arcadeFloorLayout.ts`, `buildArcadeLayout()`),reworked 2026-10-02 after the maintainer found the first open hall@@ -341,8 +358,12 @@ promotion card on screen. Figures wear their insignia on the sleeves orshoulder boards, and the person their unlocked uniform, cap and decorations.The whole contract lives in [level-system.md](level-system.md).-The Level Hall is the levels' own room on the agents floor, dressed as a hall-of honour: cream and charcoal marble underfoot, walnut and brass, a red+The Level Hall is the levels' own floor, the top one of the building (floor+3 in the elevator, `hallFloorLayout.ts`): a small foyer where the person steps+out of the elevator, and behind its door the hall, 9.2 m wide and 34 m deep.+No agents work there; the person's pet comes along. Visiting it is not yet+paid as a discovered floor: the server's list of floors does not know it, so+the map does not report it. It is dressed as a hall of honour: cream and charcoal marble underfoot, walnut and brass, a redrunner up the middle. The rank wall in the north holds all 24 insignia in awalnut-framed velvet shadow box (held ranks struck in metal, the current oneframed in brass, the ones ahead as pewter silhouettes) above a brass plaque@@ -356,6 +377,503 @@ rank, and a click opens it on the promotion road. The framed service guidestands at the runner's start. Its two checkpoints, the dais (`studio`) and theguide (`levels`), open the Level Hall screen (level-system.md §6).+## 5g. Stations, HUD and name plates (2026-10-12)++Stations used to be floating tokens over gold floor rings with a label pill+each, and every one opened a narrow side card. They are now the objects+themselves, and what they open is the app's own surface.++- **A station is an object** (`stations.ts`, pure and tested). Every checkpoint+ and every team studio's board is bound to the piece of the room that stands+ for it, by furniture kind nearest to the checkpoint: spawn terminal,+ reception desk, team board, dressing mirror, coffee bar, elevator, Mission+ Control's wall, the Level Hall's dais and guide, and the lead's desks (their+ `desk:<id>` groups). Nothing floats over the floor and nothing is painted on+ it at rest.+- **Showing that it can be used** (`StationObjects.tsx`, `stationRim.ts`): an+ invisible click target the size of the object keeps every station usable from+ the overview, so walking stays optional. While the person stands at it,+ points at it or has it open, the object wears a thin blue rim on its own+ silhouette: each of its meshes gets a shell pushed out along the normals and+ drawn back faces only. The rim fades in and out; reduced motion switches it.+ The lead desk's target is its visitor-side front panel, so the chair and the+ monitors keep their own clicks.+- **One prompt** (`OfficeHud.tsx`): bottom centre, a key cap, the action and+ the object's name ("E · Create an agent · Spawn point"). It names what the+ character stands at, or, with "Click" in place of the key, what the pointer+ rests on from afar. It is a real button.+- **Keyboard and screen readers**: the toolbar's Places button opens a card+ that lists every station of the floor as real buttons (open it, or walk+ there), the rooms' places first and the team studios under "Teams", each+ under its team's name (the studio of agents without a team is "Without a+ team"). Arrow keys move through the rows, right and left reach a row's+ "walk there", Home and End jump; arrow down on the button opens the card+ on its first row. Resting on a row lights its object in the world. The+ card is opaque, as tall as its list down to the stage's lower edge (capped+ at 680 px), and fades at its lower edge while there is more to scroll. The reception's Places tab is the same list.+- **Focus**: closing a dialog (Escape, its close button) hands focus to the+ map's canvas host, so the walking keys answer at once; a docked panel does+ the same on Escape.+- **What a station opens** (`OfficePanels.tsx`, `StationSheet.tsx`):++ | Station | Opens |+ |---|---|+ | Spawn terminal (agents floor) | The camera dives into its screen, then the app's create-agent dialog opens. Agents are created only here. |+ | Spawn terminal (coding floor) | Mission Control's launcher, as a dialog. |+ | Reception desk | The directory: agents (show on the map, open, the agents view), places, the controls guide, settings. `H` opens it on the controls from anywhere and closes it again. |+ | Team board (team room) | Teams: members with their state, meet at the table, the team's real chat, rename, members, delete, new team. |+ | A team studio's board | The same sheet on that studio's team (`{ kind: "team", id: <Studio.board.id> }`). Its "Meet at the board" gathers the team right there, on the standing places in front of the board (`boardSeats`, `TeamMeeting.boardId`); the meeting card then counts who is "at the board" and offers "Go to the board". The board of agents without a team offers to make them one. |+ | The free plot's stand | The same sheet, opened on the new-team form ("Start a team here"). The stand is the furniture piece whose id starts with `team-stand` (`TEAM_STAND_ID`); it selects `{ kind: "team", id: <its id> }`. |+ | Wardrobe mirror | The look editor, docked at the side so the character stays in view and can keep walking. |+ | Lead's desk | Selects the lead (the walkie-talkie panel). |+ | Coffee bar | Calls the free agents to the lounge; using it again sends them back. The answer is one line in the HUD. |+ | Elevator, Mission Control, Level Hall | As before: the floor picker, Mission Control, the Level Hall screen. |++ The teams sheet does one job at a time: the new-team form replaces the+ list, its member list scrolls on its own (search from seven agents up) and+ its buttons stay pinned to the sheet's lower edge.+ Dialogs are built like every other dialog of the app (same scrim, surface,+ header and type scale, the shared button, input, tabs and switch). A team+ sent to the table closes the sheet so the person sees it gather; the+ gathering then shows as a small card under the level card, which also lets+ the team go when its time is up.+- **Live means a real round** (`teamStatus.ts`, pure and tested): "Meet" is a+ gathering on the map only — members walk over, nothing is posted to the+ team and no agent starts work. The card says so ("Launch crew · called to+ the table", "Send them back", no live dot), the team's row and the team+ room's board mark it with a plain "Called". The green "Live" mark, on the+ row and on the board, comes only from the backend's running round+ (teamwork's `TeamRound.running`).+- **HUD**: top left the floor card (name, and one line of working / waiting /+ idle) and the level card; top right the minimap with a five-button icon+ toolbar beside it (follow me, overview, places, the floor's list, help);+ bottom centre the prompt. The compass bar, the six text buttons and the+ permanent controls line are gone: the wardrobe and the Level Hall are places,+ `L` and the level card open the Level Hall. First-time visitors see the four+ essential controls once in a card they dismiss; that is remembered per+ browser profile (`officeSettings.ts`, `hintsSeen`) and the reception's+ settings bring it back. In the IDE side panel the toolbar is a column in the+ corner.+- **Name plates** (`namePlate.ts`, pure and tested): a dot from afar, the whole+ plate within 10.5 m of the camera or 4.6 m of the person, for the agent the+ pointer or keyboard focus rests on, and for the selected one. A plate closes+ again only beyond 12.5 m / 6 m, so it does not flicker at the threshold. Dot+ and plate share one grid cell, so nothing moves when one takes over from the+ other; the plate's button stays in the tab order while it shows a dot.+- **Plates in a crowd** (`plateCrowd.ts`, pure and tested): a plate is wider+ than the figure under it, so people standing together would stack their+ plates. Every frame the plates that want to open report where they would+ sit on screen and are seated in order: the selected or pointed-at agent+ (always), whoever speaks in a team round (with room kept free above the+ plate for its speech bubble), plates that are already open, then the+ nearest to the person. A plate that would cover a seated one, or the+ person's own plate, stays a dot. Opening needs 12 px of clear space,+ staying open only 2 px, so a plate at the edge of another does not flicker.+ The seating is kept per stage (keyed by its scene, released when its last+ plate unmounts), so two offices awake at once never seat each other's plates.+- **In-world labels stay under the HUD**: the viewport is one stacking+ context, so no plate or bubble can lie over a HUD card.+- **Faces in lists** (`AgentFace.tsx`: directory, team rows, member lists,+ member picker) are drawn without the run state: a working agent's symbol+ would turn into its three thinking dots, which in a list reads as a picture+ still loading. The state dot and word beside the face say it. Every face+ sits on a neutral tile from theme tokens with a hairline in the text colour+ round the symbol's own outline, so a white symbol stays readable on a light+ dialog and a black one on a dark dialog.++## 5h. Team campus and the building (2026-10-12)++The maintainer found the agents floor far too small and built round model+providers instead of teams. It is now a campus whose unit is the team: a+street of team rooms round an atrium, with commons people use in between.++- **Teams are studios.** A team is a society chat group (`teams` option, fed+ from `useSocietyChatGroups` in the stage). Every team has a studio; agents+ without a team share the pool studio, which always comes first. An agent in+ several teams sits in the oldest one (ties by id); lead-tier agents keep the+ lead office; a team whose members are unknown still has its (empty) studio.+ `planStudios` decides who sits where, `layout.studios` describes each+ studio (team, seated members, board, huddle places, centre) and+ `Department.teamId` links its desks.+- **A team's lead sits at the head of its studio.** The roster names a lead+ per team (`lead_agent_id` of the chat group, `OfficeTeamInput.leadId`). A+ lead who is a member the roster knows, and who does not sit in the lead+ office, takes the head desk: the first desk of the bench nearest the name+ wall (`dept.desks[0]`). It changes places with the earliest arrival, who+ would sit there; everyone else keeps arrival order. So naming a lead+ moves two people and changing one at most three (old lead back to its own+ place, new lead to the head, the earliest arrival to the new lead's+ place); the studio's size and everyone outside the team stay as they are.+ Leading a team comes before "the oldest team" for an agent in several and+ before the seat cap; an agent named lead of two teams sits with the older+ one. `Studio.leadId` is that seated lead and null in every other case (no+ lead, not a member, unknown, in the lead office): never guessed.+ `leadDesks(layout)` lists the desks. The lead's place is marked+ (`leadMark` in deskKit.ts, drawn as instances by `DeskDressing`): a deep+ red shell on the back of its chair with a bronze cap along the top edge+ and a pad on the seat in the same red (one red in every studio, because+ the studio's own chairs already wear the team's colour; a test holds it+ clear of every studio's fabric, panel and rug), a chair mat in the team's colour+ on the floor under it, and a name stand on the desk's front right corner+ whose plate, in the team's colour, leans back towards the camera. The chair is what the south-east camera sees first+ and it stays when the lead is at the board; the mat is what reads from+ the overview. `leadMark.test.tsx` puts the mark through the real cameras+ at 1600 x 900: in the follow view the shell covers about 43 x 45 px and+ the plate 15 x 12 px, in the overview the mat at least 11 px each way,+ with no monitor, screen, chair, sitter or pendant in front. The plan is+ rebuilt when a lead is named or changed, and by nothing else new.+- **A studio is a room** (`studioShape`, one cell: 11 m wide). At its back a+ name wall capped in the team's colour, the team's name on the west half and+ the studio board in front of the east half with four to seven huddle places+ south of it. Low felt-and-glass screens close both sides (two studios+ shoulder to shoulder share the one between them). The front is planted,+ with a 4.8 m entrance in its middle. Inside: the desks — one free desk to+ grow into, whole facing pairs, spread evenly over as few benches as hold+ them (two members: four desks; twelve: fourteen) — a storage cabinet under+ the name, a sofa by the entrance and a standing table opposite, each with+ its spots; a rug in the team's colour and a slim pendant light over every+ desk row (five centimetres wide, 2.75 m up, on two wires from the ceiling+ line, a soft pool of light on the floor below). Nothing overhead is wide+ enough to stand between the camera and the people at the desks. Only the+ desks grow with the team, so a team of three still has a furnished room.+ Twelve colours, so a full campus never repeats one. A studio seats up to+ 32; the newest members of a larger team sit in the pool, and a pool of more+ than 32 opens a second pool studio.+- **The plan** is four cells wide at every size (51.8 m between the window+ strips: four cells, the boulevard and a 1.4 m promenade along each window)+ and grows southwards by a row of studios whenever a row is full, up to+ three rows (twelve studios; later teams fold into the pool). Along both+ windows the promenade leaves 2.35 m to walk between the benches and+ planters at the glass and the outer studios' screens. The+ boulevard (5 m) runs on the floor's axis from the lobby to the team room's+ door; streets between rows are 3.6 m. The main boulevard (9 m) crosses in+ the gap between two blocks nearest the floor's middle, and at the crossing+ lies the atrium. Every route from the lobby to a studio or a north room+ passes over it. Rooms, studios and commons take about 70 % of the plan.+ Sizes including the window strip: 55.0 m x 47.0 m for one row (five agents+ without a team, or fifteen in three teams), 55.0 m x 81.2 m for forty+ agents in eight teams. The floor it replaces measured 24.4 m x 38.2 m plus+ the Level Hall's wing.+- **The atrium** is the campus's heart: the spawn point on a pale stone disc+ inside a bronze ring, a flight of step seating on either side facing it, a+ large tree behind each, and a ring of light over it. The step seating has+ dark risers under pale oak treads that nose out over them; the lowest tier+ is plainly a seat (a linen pad and a back cushion per place, where people+ sit) and loose cushions in the studios' colours lie on the tiers above.+ The ring is a light fitting: a steel band the size of the disc, 2.9 m up,+ whose inner face is a warm lamp, hung on six rods from the ceiling line.+ The lobby's name stands on an arch against the back of the reception desk+ (`Room.arch`), not at the atrium's rim.+- **Commons** are named places with spots, so idle people go there: the café+ beside the lobby (kitchen run, island, standing tables, sofas), the library+ in the north-east corner (bookcases, reading chairs, a sofa on a rug), the+ focus booths in the north-west corner (three booths a person walks into, a+ sofa, a standing table), and in a cell without a studio the free plot or a+ garden court (a lawn, one large tree, two olives, two benches). The free+ plot is the first empty cell, the next team's place: the bare floor taped+ out with dashed marking tape, its lettering on the floor, a stack of moving+ crates and a plant at the back, and at the street side the team stand+ (furniture kind `teamStand`, id `team-stand`, one per plan while a plot+ exists), where a new team is started.+- **Stations** stand in front of what the person uses: the spawn terminal in+ the atrium, the reception desk (the one directory and help station; the+ agent-board totem and the reception's own create station are gone), the+ team board, the wardrobe mirror, the lead's desk, the coffee bar, the+ elevator, and the free plot's team stand.+- **Fittings and planting are data** (`agentsAmbience.ts`, `layout.ambience`):+ screens, cabinets, sofas, standing tables, booths, step seating, the+ kitchen, benches, planters, crates, olive trees and large trees are items with a+ footprint, each an obstacle and a few entries of instanced meshes+ (`CampusFittings.tsx`, `AgentsFloorAmbience.tsx`). Planting is a few+ deliberate groups of two kinds of tree, not rows. `layout.zones` names the+ flat areas (boulevard, plaza, atrium, plot, garden, booths, library, café)+ for the ground (`CampusGround.tsx`) and the maps.+- **Maps:** the minimap and the full map paint the paved boulevards, the+ atrium, the commons' carpets, the free plot, trees, fittings and every+ studio's name wall. The full map's sheet takes the plan's shape, names+ each studio on the street behind its wall (shrunk or cut to the studio's+ width, clear of the people inside) and each commons along its south edge;+ the pool is "The Pool". The minimap zooms out to 90 m.+- **The building** (`BuildingShell.tsx`, agents floor and Level Hall): the+ tower's dark body under the slab, and on the floor's far sides a 3.4 m+ window wall with steel mullions and a ceiling edge. The floor is shown like+ a cut-open model: a side's window wall stands only while the camera is on+ the opposite side of the floor; the other sides keep the glass balustrade.+ Outside lies a city at night that stays a backdrop: a few dozen unlit+ towers a shade lighter than the deep navy sky, the first 62 m from the+ building, every roof at least 24 m below the floor and the nearest ones+ lowest. About one window in twenty is dimly lit, from one small tiling+ texture; a tower sinks into the sky's colour towards its foot and with its+ distance, the scene's sun never reaches it, and the faintest glow lies+ over the streets where detail would be. Apart from the sparse windows+ nothing outside is brighter than a dark navy (#1a2233). The office is+ always the brightest and most detailed thing on screen.+- **One material language** from the studios to the last room: light plank+ oak, limestone and felt on the floor; light oak for timber; dark steel for+ metal, with bronze as the one accent; steel-framed clear glass with a+ frosted band for every wall. The rooms' floors come from that family+ (`CAMPUS_ROOM_FLOORS`, agents floor only): the break room lies on the open+ floor's plank oak, the lobby on the window band's limestone, the wardrobe+ on a terrazzo of the same stone with oak chips, the team room on the focus+ booths' slate felt, and the lead office on the same oak a tone deeper,+ laid as a chevron. The lead suite stays the richest room but in the+ family: smoked oak, bronze, cognac leather and a slate rug (`LEAD_SUITE`),+ behind the same glazing as every room. The team room's timber is the+ campus's oak, and the rooms' small metal details are the same bronze.+- **Cost** (2026-10-12, counted without a GPU as visible meshes plus the+ shadow-casting ones again for the shadow pass; a browser adds one merged+ mesh per textured material):+ - The agents floor's furniture, room signs, studio walls and meeting chairs+ never change once built, so they are drawn merged (`StaticBatch.tsx`):+ parts whose material is only a colour share one material per finish and+ carry the colour in their vertices, textured and glowing parts merge per+ material, parts smaller than a hand's width cast no shadow. A station's+ prop is merged within its own group, so its rim still finds it. The+ static floor is 441 / 452 / 507 draw calls for 5 / 15 / 40 people (it was+ about 2450 piece by piece for 15) and 0.48 / 0.60 / 0.92 million+ triangles over both passes.+ - Planting, studio fittings, commons, desks and the city are instanced:+ another studio adds no draw call for its furniture, another tree none.+ Grass blades are eight-sided spindles and olive foliage twenty-sided+ clusters (planting was the largest triangle count on the floor). A crown+ is a few large clusters (fourteen on a large tree, eleven on an olive),+ and two of its three leaf tones throw its shadow.+ - A glass wall run is three meshes whatever its length.+ - A figure is 19 meshes (13 casting, 32 draw calls) and about 31 thousand+ triangles over both passes: its rigid head and torso and each half of an+ arm (shoulder cap, sleeve and upper arm; forearm, cuff, hand and thumb)+ are merged in the frame of their joint, so every pose moves them as+ before, and its spheres have fewer segments. An arm's merged half casts+ as one, so the figure's shadow keeps its arms. The merged parts are baked+ again only when the look or what is worn changes by content+ (`contentKey`): the level store's minute-by-minute re-read hands out new+ JSX for the same regalia, and that bakes nothing. It was 41 meshes (28+ casting) and 43 thousand triangles in a single pass. The legs stay+ parts of their own: shoe and sole differ in finish, so merging them+ would save nothing.+ - Rounded boxes have one bevel segment, the task chair's tubes and bevels+ fewer segments; small things on desks cast no shadow.+ - The sun's shadow map is 4096 px on this floor, so shadows keep their+ detail over the longer plan.+ - A studio's lettering shows a name the person typed, so its texture is+ never cached by its text: the wall owns it (`ownedCanvasTexture`) and+ disposes it when the team is renamed or deleted. The session-long+ texture cache only holds keys from fixed sets (kinds, palette entries,+ a locale's own strings).++## 5i. Team life, teamwork and movement (2026-10-12)++The maintainer asked for teams that visibly work together, mechanics that+hold up, and agents that behave well in the larger world. The rule that+governs all of it: the floor shows what is real. Run state, a team's round+and a message between two agents come from the roster, the team's meeting and+the board; idle life is seeded choreography; nothing else is ever staged.++**Agents belong somewhere** (`officeBehavior.ts`, `officeTeams.ts`). The state+rules are unchanged: working sits at its own screen, waiting stands at its+desk, paused rests. An idle agent with a studio picks its next activity from+a weighted table (`TEAM_IDLE_WEIGHTS`, `POOL_IDLE_WEIGHTS`):++| Idle choice | Team member | Agent without a team |+|---|---|---|+| Sit at its own desk (40–90 s) | 30 | 20 |+| Look in on a studio mate who sits at their desk | 14 | — |+| Stand at the studio board | 12 | — |+| Stroll between its studio's benches | 12 | 10 |+| A hangout place round the corner of the studio | 12 | 10 |+| Look in on a working colleague | — | 8 |+| A trip to a shared place anywhere on the floor | 14 | 40 |+| A stroll within 12 m of the studio | 6 | 12 |++Four in five of a team member's idle choices keep it at home; an agent in+the pool studio uses the shared places far more. A trip earns a long stay+(below), so the weights are tuned by the clock: simulated, a team member+spends about two thirds of its idle time in and around its studio and 16 %+walking; an agent without a team a little over half. A trip picks among all+free shared places, weighted by what the place is (couch 22, coffee 18,+window 12, cooler 8, arcade 8, books 7, beanbag 8, team table 4, team board+3) and by how far from the studio it lies: at the trip's reach a place is+half as likely as one next door, at twice the reach a fifth. The reach is+10 m with up to six agents on the floor and grows to 20 m at thirty, so a+handful of agents on a large campus keep to their neighbourhood and the+commons near it, and nobody crosses the campus for a window when there is a+coffee round the corner. The same home activity is never taken twice in a+row. Standing at the studio board and looking in on a studio mate are idle+life, and the name plate says so ("In the studio"); "At the team board" is+shown only for a gathering that is real, a running round or a meeting the+person called there. A visitor stands in the gap between the colleague's chair and the next+one (out of the aisle behind the chairs and out of the way the colleague+gets up) and watches: the talking pose is kept for exchanges that really+happened. Every standing place beside a desk and at a board is reserved+through the same book as the spots. A stroll ends on open ground (floor a+body's width to every side), so nobody stops for a rest in a doorway. A floor+without studios (the coding floor) keeps its plain idle day.++Long ways are walked briskly (1.35 m/s up to 9 m of route left, rising to+2.1 m/s at 26 m), and an agent that got work hurries to its screen (2.1 m/s+on anything but the last steps). Measured along real routes from the lobby+to a desk, corners and getting up included, an agent averages 1.45–1.6 m/s.+A stay lasts at least 3.2 times as long as the walk to it would take at+walking pace, up to 150 s. Simulated over twenty minutes with+60 idle agents, about one agent in six is on the move at any moment.++**Real teamwork** (`teamwork.ts`, `useTeamRounds.ts`). Two things are shown,+because they are what the app can see:++- *A round of a team.* A team's meeting is read from+ `GET /api/society/chat-groups/{id}/meeting` (running, transcript, the room's+ next speaker); that a round opened or settled and each line said in it also+ arrive on the socket (`SocietyRoomChanged`, `SocietyMessageSent` with a+ `meeting:<group>:…` room id). While a round runs, its idle members walk to+ their studio board and stand there in loose arcs (2.2 m, 3.3 m and 4.4 m+ from the board, every place more than a metre from the next), the arc+ nearest the board first; when it settles they return to their desks. They+ take no place within 1.25 m of the person's character, and when the person+ walks up to one of them (closer than 0.95 m) it moves to another place in+ the arcs. A working member stays at its screen, with one exception that is+ the round itself: the member contributing right now (the room's next+ speaker) reads "working" and stands at the board in the talking pose, with+ a thought bubble until its line is written. A line said in the round+ appears over its speaker in its own words for up to nine seconds, and gives+ way the moment the next member has the word: only one member of a team+ carries a bubble at a time, and a listener at the board shows none of its+ own. A member of the team that sits in another studio comes to the board+ of the team whose round it is. Waiting and paused members stay where their+ state puts them. The person's own call still outranks a round. A meeting+ the person starts at a studio's own board uses the same arcs:+ `boardSeats(layout, studio, members)` gives every member its place,+ and `startMeeting` holds them there as it holds a team at the team room's+ table.+- *A message from one agent to another.* `SocietyMessageSent` without a room,+ between two roster agents other than the lead (ASSIGN, SAY, QUERY, ANSWER,+ PROPOSE). The sender's bubble shows "To <name>: <text>"; once the sender is+ idle (within 90 s) it walks to a place beside the receiver's chair, or to+ where the receiver stands, and stays eight seconds. A working sender never+ leaves its screen. The lead's own messages remain its pet's errands.++Reads are scheduled, jittered (2.4–3.6 s between ticks), capped at four at+once and silent while the stage sleeps. The ticks do not wait for the reads:+each is folded in when its answer comes, is given up after eight seconds and+aborted when the poller stops, so a request that hangs holds nothing back.+There is one poller for the whole app: when two floors are awake at once+(the Agents view and the IDE's side panel), one of them reads and the other+takes over when it sleeps. What is read: running rounds every tick, a team the+roster shows in a room every six seconds, a team whose board is near the+camera every eighteen, and the sweep. The sweep makes the floor independent+of the socket: every team is read once after the stage wakes (two a tick)+and again about once a minute, so a round that was already running when the+Verse was opened, or whose event was missed, is found. A round that fails to+read five times in a row is no longer shown as running.++A team can have a lead (`lead_agent_id` of its chat group, `Studio.leadId` on+the floor). The floor shows that and invents nothing more: the studio board+lists the lead first and names it ("Lead: <name>"), and in a gathering at the+board (a running round, or a meeting the person called there) the lead stands+at the centre of the front arc when it is among those gathering; the others+leave that place free while any other is. A working lead stays at its screen+like anyone, an idle lead lives the same idle day as its team, and a team+without a lead is planned and drawn exactly as before.++Not shown, because the app cannot see it: when a line was said (the meeting's+messages carry no time), a task shared by several agents, and whether a+hand-off was accepted.++**Studio boards** (`StudioBoards.tsx`, `studioBoardContent.ts`). Each board's+face shows the team's name, its members with their real run state (the+speaker marked), and the newest lines of the team's chat, or says honestly+that nothing has been said, that the chat is still being read or cannot be+read right now, or that the pool has no team chat. A face is a canvas texture on the board's own paper+sheet, created the first time the camera comes within 60 m and redrawn only+when its content changed. The three boards nearest the camera (within 30 m)+are live. The faces take no pointer events; the board's station does.++**Movement** (`officeMotion.ts`, `officeWalk.ts`). One controller walks every+agent and the person's click-to-move:++- Every step is checked against the floor and against the other bodies; the+ candidates are the steered direction, straight at the waypoint, then a slide+ past whatever is in the way, right before left. When none is free the figure+ waits. Bodies keep 0.62 m between their centres.+- A figure turns before it walks (it slows as soon as it faces more than+ about 30° off its way, down to a crawl of 8 % of its pace), faces where it+ moves, and lands exactly on its last waypoint. Leaving a seat it waits for+ whoever stands in its way and leaves on the free side.+- The route is recomputed when steering carried the figure off it, and when+ the floor plan changes under a walk (a team was created or deleted). A plan+ survives a rebuilt floor only if its place still exists there; otherwise the+ agent plans again, and a target the new plan walls off is reported instead+ of walked at.+- A figure that makes less than 0.4 m of progress in 1.5 s takes a detour+ planned round the bodies near it. After two detours that did not help, or+ when a walk overruns three times its expected duration plus eight seconds,+ the walk ends. Within 3 m of its target the figure is placed: on its+ reserved seat, or on free ground at the target, never on top of anybody.+ Further away it gives the walk up and its agent plans again from where it+ stands: nobody is moved across the floor. The one exception is a place the+ agent's real state demands (its screen while it works, the board while its+ round runs): after two walks given up in a row it is placed there. The+ person's own character always just stops.+- Blocked beside someone who stands on the place it was heading for, a figure+ stops there: that is an arrival.++**Camera and character** (`OfficeCameraRig.tsx`, `officeCamera.ts`,+`wallCutaway.ts`, `OfficePlayer.tsx`). While the character stands in a walled+room, the sides of that room the camera looks in through drop to 12 % of+their height and rise again when the character leaves or the camera turns;+the rule is by side, so nothing flickers while the character walks about+inside. The rig moves any object tagged `userData.officeWall`. The overview+is fitted to the viewport: the look-at point is moved until the plan sits in+the middle of the view (seen at an angle, the near corner looms larger than+the far one), and the camera comes as close as the plan allows, so the plan+spans 85 % of whichever axis binds — the height in a wide window, the width+in the IDE's narrow panel. The zoom limit grows with the floor so the wheel+can always reach that view. A wheel notch zooms 12 % of the way up close and up to 35 % from+90 m out, so the overview of a large campus comes down to a studio in about+five notches while the last metres stay fine. Following is exponential (the+same motion at any frame rate); resumed more than 12 m from the character,+the view glides over in 0.6 s instead of snapping, and after the overview it+also glides back to the distance the person walked at (15 m when there was+none), unless the person zoomed by hand meanwhile. A remembered view (after+a monitor dive, or from the last visit) is checked against the current floor+plan: one that looks at a place the floor no longer has starts from the+character instead, and a camera that would stand inside a wall backs out+along its line of sight. A click-to-move target on free floor is the target+itself. A click on a bench desk, its chair or whoever sits there resolves to+a standing place at that desk (in the gap beside the chair, where a visiting+colleague would stand, else behind it), and anything else solid or occupied+to the nearest free floor beside it, 0.75 m from everybody: the character+never ends up on a chair, in a desk or inside a figure. Sitting down stays+its own action (the executive chair, Mission Control's chair). The person's+pet follows on free floor that is nobody's, 0.5 m from every agent. A long+click-to-move route is+jogged (up to the sprint pace of 4.4 m/s with more than 22 m to go) and ends+in a walk over the last 7 m; and a character left standing in a solid cell+by a rebuilt floor plan is put on the nearest free ground.++**Dev handles** (development builds only):++- `__officeLife.walkers()` — one row per agent: `team`, `studio`, `role`+ (its part in a running round: none, gather, speaker, busy), `plan`, `phase`,+ `target`, `spot`, `with`, `at`, `remainingM`, `stuckS` (seconds without+ progress on the current walk), `walkS` and `speed` (seconds walked and+ average m/s along the route on the current walk, by the frame time the+ walker was really given), and counters since it mounted: `replans`+ (detours), `rescues` (placements), `blocked` (walks given up), `repaths`+ (route repairs), `near` (arrivals beside an occupied place), `lost`+ (targets a new floor plan walled off). `__officeLife.walker(id)` is one+ row, `__officeLife.stuck()` the rows with a detour, a placement or a walk+ given up.+- `__officeLife.teamwork()` — rounds by team (`running`, `speakerId`,+ `members`, `lines`, `spoke`) and the messages still to be walked over;+ `__officeLife.store` is the store itself, so a round or a message can be+ set by hand; `__officeLife.boards()` lists the teams whose board is live.+- Measuring speeds: while the frame loop runs, `__officeStep(frames, dtMs)`+ renders `frames` frames but each gets the real time since the one before,+ not `dtMs`; distance over `frames x dtMs` is therefore not a speed. Read+ `speed` from the handle instead.+- `__officeCamera.cut()` — the walls lowered right now; `.walls()` how many+ wall objects are tagged; `.limits()` this floor's zoom limits.+## 6. Plan1. First map (done 2026-09-28).@@ -372,6 +890,44 @@ guide (`levels`), open the Level Hall screen (level-system.md §6).navigation (every seat, spot and checkpoint reachable from the elevator for0/10/40 agents; paths never cross obstacles), motion, behaviour (state rules,exclusive spots, determinism), props (every kind renders inside its footprint).+- Team campus (2026-10-12), unit tests: team grouping (several teams, an+ agent in two, unknown members, leads, the studio cap), studio sizing, stable+ seating, a studio's enclosure and entrance, the furnished share of the+ plan, no two solid things in one place, free doorways and streets, every+ seat, spot, station and studio board reachable for zero, one, three and+ eight teams and teams of two and twelve, the route over the main+ boulevard, the Level Hall's floor and its elevator stop, the map painting+ and sheet, and a mount of the whole dressing without a GPU (mesh counts,+ bounds). The first plan was checked in a browser by the orchestrator and+ reworked into this one, which the orchestrator checked too. The third+ round (the receded city, pendants instead of baffles, the atrium's ring,+ the step seating, the rooms' materials, the promenade and the furnished+ free plot) is covered by unit tests for the plan (the stand and its+ standing place, the arch at the desk, 1.2 m or more to walk along both+ windows) and was then checked in a browser by the orchestrator.+- Floors (2026-10-12): `progression/verseFloors.test.ts` reads+ `VERSE_FLOORS` from jarvis/progression/service.py and holds it equal to the+ client's `METERED_FLOORS` and the elevator's `OFFICE_FLOORS`; a world+ action the server refuses is logged (`reportWorldAction`).+- Team life and movement (2026-10-12), unit and component tests; a browser+ run on a scripted roster confirmed the live board, the gathering, the wall+ cutaway, the route marker and stuck recovery. Tested: the idle weights and+ that a team member's day stays at home; trips staying near on a five-agent+ floor; exclusive places; a round gathering its free members in arcs with a+ metre between them, the speaker, the return to the desks, making room for+ the person; a round found by reading alone; a message walked over; the+ reducers behind rounds and messages and which meetings are read when; the+ board's content; a long diagonal walk across a 60-agent campus (on the+ floor all the way, no gliding, exact arrival); two walkers swapping places+ through a door and in a 1.6 m aisle without touching; a studio built on a+ walker's route; detour, placement, a walk given up and the walk budget; the+ wall cutaway by side; the overview holding every corner of small and large+ floors in wide and portrait viewports; the wheel's reach, the follow+ distance after the overview and a remembered view on a rebuilt floor; the+ click-to-move pace; a click on an occupied bench seat, a desk top and an+ empty chair ending beside them. A mounted floor of 40 agents (a quarter working, one+ team round) simulated for ten minutes kept every pair of bodies 0.62 m+ apart, with 17 detours, no placement and no walk given up.- Runtime (Chrome, dev build, live roster of ten agents): walking by click andby keyboard, camera follow and overview, nearby prompt and E, agent panel,"call over". Desks are instanced; the full floor measured ~730 draw calls anddiff --git a/jarvis/progression/service.py b/jarvis/progression/service.pyindex 367421428d..374f39f599 100644--- a/jarvis/progression/service.py+++ b/jarvis/progression/service.py@@ -40,7 +40,7 @@ from .store import Award, ProgressionStorelog = logging.getLogger(__name__)#: The floors of the Verse a ``floor_discovered`` report may name.-VERSE_FLOORS = frozenset({"agents", "coding", "arcade"})+VERSE_FLOORS = frozenset({"agents", "coding", "arcade", "hall"})class UnknownAction(ValueError):diff --git a/jarvis/ui/web/frontend/src/components/society/office/AgentFace.tsx b/jarvis/ui/web/frontend/src/components/society/office/AgentFace.tsxnew file mode 100644index 0000000000..fd35233269--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/AgentFace.tsx@@ -0,0 +1,27 @@+/**+ * An agent's face in a list of the office (the directory, team rows, member+ * lists, the member picker): its symbol on a neutral tile.+ *+ * Two things a bare symbol gets wrong in a list. Its colour is the agent's+ * own, and a white or very pale one vanishes on a light dialog (a black one+ * on a dark dialog): the tile and a hairline round the symbol's own outline,+ * both from theme tokens, keep every colour readable in both themes. And a+ * working agent's symbol turns into three "thinking" dots, which in a row of+ * faces reads as a picture that is still loading: the run state is left out+ * here, the state dot beside the face says it.+ */+import { AgentSwatch } from "../AgentSwatch";+import type { SocietyAgent } from "../data";+import "./agentFace.css";++/** The tile is this much wider than the symbol on it. */+const TILE_MARGIN_PX = 8;++export function AgentFace({ agent, size = 24 }: { agent: SocietyAgent; size?: number }) {+ const tile = size + TILE_MARGIN_PX;+ return (+ <span className="office-face" style={{ width: tile, height: tile }}>+ <AgentSwatch agent={{ ...agent, state: undefined }} size={size} />+ </span>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/AgentTalkPanel.tsx b/jarvis/ui/web/frontend/src/components/society/office/AgentTalkPanel.tsxindex 7c27873980..eab3b4fe9b 100644--- a/jarvis/ui/web/frontend/src/components/society/office/AgentTalkPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/AgentTalkPanel.tsx@@ -15,21 +15,23 @@*/import { useCallback, useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type PointerEvent } from "react";import { useQueryClient } from "@tanstack/react-query";-import { ArrowUp, Footprints, Hand, LocateFixed, Maximize2, Mic, Square, UserPlus } from "lucide-react";+import { ArrowUp, Footprints, Hand, LocateFixed, Maximize2, Mic, Square, UserPlus, X } from "lucide-react";import { useT } from "@/i18n";import { getWSClient } from "@/hooks/useWebSocket";import { useEventStore } from "@/store/events";import type { TimelineItem } from "@/components/agentchat/reduce";import type { SocietyAgent } from "../data";import { player, useOfficeStore } from "./officeStore";+import { CALL_MS } from "./stations";++// The session command panel imports the call duration from here.+export { CALL_MS };import { agentPositions } from "./walkerRegistry";import { ownsKeyboard } from "./OfficePlayer";import { useBubbleLabels } from "./OfficeBubbles";import { bubbleText, itemsFor, talkStoreFor, turnBubble, useOfficeTalk } from "./officeTalk";import "./officeTalk.css";-/** How long called or gathered agents stay before they drift back to their day. */-export const CALL_MS = 25_000;/** A press on the microphone longer than this is push-to-talk: releasing sends. */const HOLD_MS = 350;/** After the microphone closes, the transcript usually lands within a few seconds. */@@ -242,7 +244,7 @@ export function AgentTalkPanel({ agent, actions, onClose }: { agent: SocietyAgen<h2 id={headingId}>{agent.name}</h2><span><StateDot state={agent.state} />{t(`society.office.state_${agent.state}`)}{agent.title || agent.providerLabel ? ` · ${agent.title || agent.providerLabel}` : ""}</span></div>- <button type="button" className="office-icon-button" onClick={onClose} aria-label={t("society.office.close")}>×</button>+ <button type="button" className="office-icon-button" onClick={onClose} aria-label={t("society.office.close")}><X size={16} aria-hidden /></button></header><ol ref={log} className="office-talk-log" aria-live="polite" aria-label={t("society.office.talk_log").replace("{0}", agent.name)}>diff --git a/jarvis/ui/web/frontend/src/components/society/office/AgentsFloorAmbience.tsx b/jarvis/ui/web/frontend/src/components/society/office/AgentsFloorAmbience.tsxindex 1c0a3a8a8c..6efa84e87e 100644--- a/jarvis/ui/web/frontend/src/components/society/office/AgentsFloorAmbience.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/AgentsFloorAmbience.tsx@@ -1,23 +1,24 @@/**- * The agents floor's ambience between the rooms: olive trees in pale stone- * pots closing the cross aisles at the windows, cushioned oak window benches- * and slatted oak planters of grasses along both glass sides, a rack of felt- * acoustic baffles floating over every bench in its department's colour with- * two warm linear lights under it and soft pools of light below, and one warm- * fill light for the whole floor.+ * The agents floor's planting, fittings and light: olive trees in pale stone+ * pots at the end of every street and in a few deliberate groups, cushioned+ * oak benches, slatted oak planters of grasses (every studio's planted front+ * among them), the built fittings of studios and commons (`CampusFittings`),+ * a slim linear pendant light over every desk row with a soft pool of light+ * below, and one warm fill light for the whole floor.** Every repeated part is one instanced mesh, so the whole dressing costs a- * handful of draw calls. The solid pieces come from `agentsAmbience`, which- * the layout also adds to its obstacles; the baffles and light pools are out- * of reach (overhead, or flat on the floor). The baffles fade out whenever the- * camera comes down towards their height, so they never block a close view.+ * few dozen draw calls however large the campus grows. The solid pieces are+ * the plan's `ambience` items, which the layout also adds to its obstacles;+ * the pendants and light pools are out of reach (a metre over every head, or+ * flat on the floor), and nothing overhead is wide enough to hide a desk.*/-import { useEffect, useMemo, useRef } from "react";-import { useFrame } from "@react-three/fiber";-import { AdditiveBlending, Group, MeshBasicMaterial, MeshStandardMaterial, PlaneGeometry } from "three";+import { useMemo } from "react";+import { AdditiveBlending, MeshBasicMaterial, MeshStandardMaterial, PlaneGeometry } from "three";import { cachedCanvasTexture } from "./canvasMaterials";-import { agentsAmbience, BENCH_H, PLANTER_H, type AgentsAmbienceItem } from "./agentsAmbience";-import { agentsRug, AGENTS_SCENE } from "./AgentsFloorLook";+import { BENCH_H, PLANTER_H, type AgentsAmbienceItem } from "./agentsAmbience";+import { FACADE } from "./BuildingShell";+import { AGENTS_SCENE } from "./AgentsFloorLook";+import { CampusFittings } from "./CampusFittings";import { benchesOf, Instances, type Placement } from "./CodingFloorAmbience";import { GEO, MAT, matte } from "./OfficeFurniture";import type { Department, OfficeLayout } from "./officeLayout";@@ -87,10 +88,10 @@ function Olives({ items }: { items: readonly AgentsAmbienceItem[] }) {trunk.push({ position: [x - 0.08, 1.35, z + 0.02], scale: [0.035, 0.62, 0.035], rotation: [0.1, 0, 0.28] });trunk.push({ position: [x + 0.09, 1.4, z - 0.03], scale: [0.032, 0.66, 0.032], rotation: [-0.12, 0, -0.26] });// The crown: an open dome of small clusters, so the trunk shows through.- for (let k = 0; k < 22; k += 1) {- const a = rand() * Math.PI * 2, ring = 0.15 + rand() * 0.45;+ for (let k = 0; k < 11; k += 1) {+ const a = (k / 11) * Math.PI * 2 + rand() * 0.6, ring = 0.15 + rand() * 0.42;const y = 1.55 + rand() * 0.7 - ring * 0.35;- const s = 0.1 + rand() * 0.09;+ const s = 0.15 + rand() * 0.1;leaves[Math.floor(rand() * leaves.length)].push({position: [x + Math.cos(a) * ring, y, z + Math.sin(a) * ring], scale: [s * 1.3, s * 0.8, s * 1.3],});@@ -101,10 +102,12 @@ function Olives({ items }: { items: readonly AgentsAmbienceItem[] }) {return (<group><Instances geometry={GEO.potCyl} material={AMB.stone} items={parts.pot} />- <Instances geometry={GEO.cyl} material={AMB.stoneDark} items={parts.lip} />+ <Instances geometry={GEO.cyl} material={AMB.stoneDark} items={parts.lip} cast={false} /><Instances geometry={GEO.cyl} material={AMB.gravel} items={parts.gravel} cast={false} /><Instances geometry={GEO.cyl} material={AMB.bark} items={parts.trunk} />- {parts.leaves.map((list, i) => <Instances key={i} geometry={GEO.blob} material={OLIVE_LEAVES[i]} items={list} />)}+ {/* Flat-shaded clusters: twenty faces each read the same as eighty. */}+ {/* Two of a crown's three tones throw its shadow; the third would only draw it again. */}+ {parts.leaves.map((list, i) => <Instances key={i} geometry={GEO.facet} material={OLIVE_LEAVES[i]} items={list} cast={i < 2} />)}</group>);}@@ -162,8 +165,8 @@ function Benches({ items }: { items: readonly AgentsAmbienceItem[] }) {<group><Instances geometry={GEO.box} material={AMB.oakDark} items={parts.plinth} cast={false} /><Instances geometry={GEO.box} material={AMB.oak} items={parts.box} />- <Instances geometry={GEO.box} material={AMB.linen} items={parts.cushion} />- <Instances geometry={GEO.box} material={AMB.fabric} items={parts.fabric} />+ <Instances geometry={GEO.box} material={AMB.linen} items={parts.cushion} cast={false} />+ <Instances geometry={GEO.box} material={AMB.fabric} items={parts.fabric} cast={false} /></group>);}@@ -177,6 +180,7 @@ function Planters({ items }: { items: readonly AgentsAmbienceItem[] }) {const parts = useMemo(() => {const liner: Placement[] = [], slats: Placement[] = [], cap: Placement[] = [], soil: Placement[] = [], plumes: Placement[] = [], stalks: Placement[] = [];const grass: Placement[][] = GRASS.map(() => []);+ const mounds: Placement[][] = GRASS.map(() => []);for (const item of items) {const rand = lcg(seedOf(item.id));const depth = item.maxX - item.minX, len = item.maxZ - item.minZ;@@ -193,9 +197,13 @@ function Planters({ items }: { items: readonly AgentsAmbienceItem[] }) {cap.push({ position: [cx, PLANTER_H - 0.015, cz], scale: [depth + 0.01, 0.03, len + 0.01] });soil.push({ position: [cx, PLANTER_H + 0.002, cz], scale: [depth - 0.06, 0.006, len - 0.06] });// Clumps of fine blades fanning out of a low mound, and every so often a pale plume above them.- for (let z = item.minZ + 0.12; z < item.maxZ - 0.08; z += 0.11 + rand() * 0.05) {- const bx = cx + (rand() - 0.5) * 0.1, tone = Math.floor(rand() * GRASS.length);- grass[tone].push({ position: [bx, PLANTER_H + 0.03, z], scale: [0.07, 0.06, 0.07] });+ // A planter runs along its longer side; the clumps follow it.+ const alongX = depth > len;+ const [from, to] = alongX ? [item.minX, item.maxX] : [item.minZ, item.maxZ];+ for (let at = from + 0.12; at < to - 0.08; at += 0.11 + rand() * 0.05) {+ const across = (alongX ? cz : cx) + (rand() - 0.5) * 0.1, tone = Math.floor(rand() * GRASS.length);+ const bx = alongX ? at : across, z = alongX ? across : at;+ mounds[tone].push({ position: [bx, PLANTER_H + 0.03, z], scale: [0.07, 0.06, 0.07] });let tallest = 0;for (let k = 0; k < 6; k += 1) {const h = 0.18 + rand() * 0.24, rx = (rand() - 0.5) * 0.9, rz = (rand() - 0.5) * 0.9;@@ -214,29 +222,36 @@ function Planters({ items }: { items: readonly AgentsAmbienceItem[] }) {}}}- return { liner, slats, cap, soil, grass, plumes, stalks };+ return { liner, slats, cap, soil, grass, mounds, plumes, stalks };}, [items]);return (<group><Instances geometry={GEO.box} material={AMB.oakDark} items={parts.liner} /><Instances geometry={GEO.box} material={AMB.oak} items={parts.slats} cast={false} />- <Instances geometry={GEO.box} material={AMB.oak} items={parts.cap} />+ <Instances geometry={GEO.box} material={AMB.oak} items={parts.cap} cast={false} /><Instances geometry={GEO.box} material={MAT.soil} items={parts.soil} cast={false} />- {parts.grass.map((list, i) => <Instances key={i} geometry={GEO.blob} material={GRASS[i]} items={list} />)}- <Instances geometry={GEO.blob} material={AMB.plume} items={parts.plumes} />+ {/* Hundreds of blades per planter: each is a slim spindle of eight faces, the mound under them a facet. */}+ {parts.grass.map((list, i) => <Instances key={i} geometry={GEO.blade} material={GRASS[i]} items={list} cast={false} />)}+ {parts.mounds.map((list, i) => <Instances key={`m${i}`} geometry={GEO.facet} material={GRASS[i]} items={list} cast={false} />)}+ <Instances geometry={GEO.facet} material={AMB.plume} items={parts.plumes} cast={false} /><Instances geometry={GEO.cyl} material={AMB.stalk} items={parts.stalks} cast={false} /></group>);}// ----------------------------------------------------------------------------// Felt baffles over the benches+// Pendant lights over the benches// ----------------------------------------------------------------------------/** Top of the baffle rack, a baffle's height, thickness and length (across the bench), and their pitch along it. */-const BAFFLE = { top: 3.3, h: 0.36, t: 0.035, len: 1.8, pitch: 0.4 } as const;-/** The baffles fade out between these camera heights, so a close or low view never looks through them. */-const BAFFLE_FADE = { from: 6.5, to: 9 } as const;+/**+ * A slim linear pendant over each desk row: its height and its housing. Its two wires run up to the ceiling line.+ * A line five centimetres wide a metre over every head never stands between the camera and the people at the desks.+ */+const PENDANT = { y: 2.75, w: 0.05, h: 0.035 } as const;+const PENDANT_MAT = {+ housing: matte("#2a2724", { roughness: 0.5 }),+ glow: new MeshStandardMaterial({ color: AGENTS_SCENE.light.glow, emissive: AGENTS_SCENE.light.glow, emissiveIntensity: 1.5, toneMapped: false }),+};let poolMaterial: MeshBasicMaterial | null = null;/** A soft oval of warm light, added onto the floor. */@@ -258,65 +273,36 @@ function pool(): MeshBasicMaterial {}const POOL_GEOMETRY = new PlaneGeometry(1, 1).rotateX(-Math.PI / 2);-function Baffles({ departments }: { departments: readonly Department[] }) {- const lamps = useRef<Group>(null);- // Own materials, so fading them touches nothing else in the scene.- const mats = useMemo(() => ({- felt: matte("#ffffff", { roughness: 1, transparent: true }),- strip: new MeshStandardMaterial({- color: AGENTS_SCENE.light.glow, emissive: AGENTS_SCENE.light.glow, emissiveIntensity: 1.8, toneMapped: false, transparent: true,- }),- cable: matte("#2a2724", { roughness: 0.5, transparent: true }),- }), []);- useEffect(() => () => { mats.felt.dispose(); mats.strip.dispose(); mats.cable.dispose(); }, [mats]);+/** The housing of every pendant on the floor: its middle, its length along x, its height and its width. Pure. */+export function pendantHousings(departments: readonly Pick<Department, "id" | "desks">[]): { x: number; y: number; z: number; length: number; h: number; w: number }[] {+ return benchesOf(departments).flatMap((bench) => {+ const length = Math.max(1.2, bench.length - 1.3);+ // One over each desk row of the bench.+ return [-0.45, 0.45].map((dz) => ({ x: bench.x, y: PENDANT.y + PENDANT.h / 2, z: bench.z + dz, length, h: PENDANT.h, w: PENDANT.w }));+ });+}++function Pendants({ departments }: { departments: readonly Department[] }) {const parts = useMemo(() => {- const fins: Placement[] = [], rails: Placement[] = [], strips: Placement[] = [], cables: Placement[] = [], pools: Placement[] = [];- for (const dept of departments) {- const felt = agentsRug(dept.tint).felt;- for (const bench of benchesOf([dept])) {- // A rack of vertical felt fins across the bench: seen from above they are fine lines, so the desks stay visible.- const run = bench.length - 0.9, count = Math.max(2, Math.round(run / BAFFLE.pitch) + 1);- for (let i = 0; i < count; i += 1) {- const x = bench.x - run / 2 + (run * i) / (count - 1);- fins.push({ position: [x, BAFFLE.top - BAFFLE.h / 2, bench.z], scale: [BAFFLE.t, BAFFLE.h, BAFFLE.len], color: felt });- }- for (const dz of [-BAFFLE.len * 0.35, BAFFLE.len * 0.35]) {- rails.push({ position: [bench.x, BAFFLE.top + 0.012, bench.z + dz], scale: [run + 0.08, 0.024, 0.03], color: felt });- }- // Two linear lights under the fins, one over each desk row.- for (const dz of [-0.45, 0.45]) {- strips.push({ position: [bench.x, BAFFLE.top - BAFFLE.h - 0.05, bench.z + dz], scale: [run - 0.4, 0.025, 0.05] });- }- for (const dx of [-run * 0.4, run * 0.4]) {- for (const dz of [-BAFFLE.len * 0.35, BAFFLE.len * 0.35]) cables.push({ position: [bench.x + dx, BAFFLE.top + 0.6, bench.z + dz], scale: [0.005, 1.2, 0.005] });- // The light hangs from the rack on short drops.- for (const dz of [-0.45, 0.45]) cables.push({ position: [bench.x + dx, BAFFLE.top - (BAFFLE.h + 0.05) / 2, bench.z + dz], scale: [0.005, BAFFLE.h + 0.05, 0.005] });- }- pools.push({ position: [bench.x, 0.012, bench.z], scale: [bench.length + 1.4, 1, 3.4] });+ const housings: Placement[] = [], glows: Placement[] = [], wires: Placement[] = [], pools: Placement[] = [];+ const wire = FACADE.h - PENDANT.y - PENDANT.h;+ for (const { x, y, z, length: run, h, w } of pendantHousings(departments)) {+ housings.push({ position: [x, y, z], scale: [run, h, w] });+ glows.push({ position: [x, PENDANT.y - 0.006, z], scale: [run - 0.04, 0.012, w - 0.014] });+ for (const dx of [-run * 0.4, run * 0.4]) {+ wires.push({ position: [x + dx, PENDANT.y + h + wire / 2, z], scale: [0.006, wire, 0.006] });}}- return { fins, rails, strips, cables, pools };- }, [departments]);- const fade = useRef(-1);- useFrame(({ camera }) => {- const t = Math.min(1, Math.max(0, (camera.position.y - BAFFLE_FADE.from) / (BAFFLE_FADE.to - BAFFLE_FADE.from)));- if (t === fade.current) return;- fade.current = t;- for (const m of [mats.felt, mats.strip, mats.cable]) {- m.opacity = t;- // Opaque when fully shown, so the fins sort and shadow like any solid.- m.depthWrite = t >= 1;+ for (const bench of benchesOf(departments)) {+ pools.push({ position: [bench.x, 0.012, bench.z], scale: [bench.length + 1.4, 1, 3.4] });}- if (lamps.current) lamps.current.visible = t > 0;- });+ // Housings and wires are the same steel: one mesh.+ return { steel: [...housings, ...wires], glows, pools };+ }, [departments]);return (<group>- <group ref={lamps}>- <Instances geometry={GEO.box} material={mats.felt} items={parts.fins} cast={false} />- <Instances geometry={GEO.box} material={mats.felt} items={parts.rails} cast={false} />- <Instances geometry={GEO.box} material={mats.strip} items={parts.strips} cast={false} />- <Instances geometry={GEO.box} material={mats.cable} items={parts.cables} cast={false} />- </group>+ <Instances geometry={GEO.box} material={PENDANT_MAT.housing} items={parts.steel} cast={false} />+ <Instances geometry={GEO.box} material={PENDANT_MAT.glow} items={parts.glows} cast={false} /><Instances geometry={POOL_GEOMETRY} material={pool()} items={parts.pools} cast={false} /></group>);@@ -327,7 +313,7 @@ function Baffles({ departments }: { departments: readonly Department[] }) {// ---------------------------------------------------------------------------export function AgentsFloorAmbience({ layout }: { layout: OfficeLayout }) {- const items = useMemo(() => agentsAmbience(layout), [layout]);+ const items = useMemo(() => layout.ambience ?? [], [layout]);const byKind = useMemo(() => ({olive: items.filter((i) => i.kind === "olive"),bench: items.filter((i) => i.kind === "bench"),@@ -341,7 +327,9 @@ export function AgentsFloorAmbience({ layout }: { layout: OfficeLayout }) {<Olives items={byKind.olive} /><Benches items={byKind.bench} /><Planters items={byKind.planter} />- <Baffles departments={layout.departments} />+ {/* Studio screens, cabinets, sofas and tables, and the commons' step seating, kitchen, booths and large trees. */}+ <CampusFittings items={items} />+ <Pendants departments={layout.departments} /></group>);}diff --git a/jarvis/ui/web/frontend/src/components/society/office/AgentsFloorLook.letters.test.tsx b/jarvis/ui/web/frontend/src/components/society/office/AgentsFloorLook.letters.test.tsxnew file mode 100644index 0000000000..13b391eac8--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/AgentsFloorLook.letters.test.tsx@@ -0,0 +1,130 @@+/**+ * A studio's lettering shows a name the person typed. Each wall owns its+ * lettering and lets go of it: renaming, creating and deleting teams all+ * session long must leave exactly one texture per wall on screen.+ */+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";+import { act, createRoot, extend, type ReconcilerRoot } from "@react-three/fiber";+import * as THREE from "three";+import type { Mesh, MeshStandardMaterial, Object3D } from "three";+import { AgentsDepartment } from "./AgentsFloorLook";+import { buildOfficeLayout, type Department, type OfficeAgentInput } from "./officeLayout";++/** Just enough of a WebGLRenderer for R3F to mount a scene graph without a GPU. */+function fakeRenderer(canvas: HTMLCanvasElement) {+ const noop = () => undefined;+ return {+ domElement: canvas,+ render: noop, setSize: noop, setPixelRatio: noop, setAnimationLoop: noop, dispose: noop,+ getPixelRatio: () => 1,+ shadowMap: { enabled: false, type: 0, needsUpdate: false },+ xr: { enabled: false, isPresenting: false, addEventListener: noop, removeEventListener: noop, setAnimationLoop: noop },+ outputColorSpace: "srgb", toneMapping: 0, toneMappingExposure: 1,+ info: { render: {}, memory: {} },+ };+}++/**+ * A 2D context that accepts every call and draws nothing: jsdom has no canvas, and without a context no texture+ * is made at all. Measuring text answers a fixed width, a gradient takes its stops.+ */+function inertContext(): CanvasRenderingContext2D {+ const gradient = { addColorStop: () => undefined };+ return new Proxy({}, {+ get: (_target, prop) => {+ if (prop === "measureText") return () => ({ width: 10 });+ if (prop === "createLinearGradient" || prop === "createRadialGradient") return () => gradient;+ if (prop === "createImageData") return (w: number, h: number) => ({ data: new Uint8ClampedArray(w * h * 4), width: w, height: h });+ return () => undefined;+ },+ set: () => true,+ }) as CanvasRenderingContext2D;+}++extend(THREE);++const realGetContext = HTMLCanvasElement.prototype.getContext;+beforeAll(() => {+ HTMLCanvasElement.prototype.getContext = (() => inertContext()) as unknown as typeof HTMLCanvasElement.prototype.getContext;+});+afterAll(() => {+ HTMLCanvasElement.prototype.getContext = realGetContext;+});++let root: ReconcilerRoot<HTMLCanvasElement> | null = null;+let scene: Object3D | null = null;++/** Render into one root, so a second call updates what the first one mounted. */+async function render(element: JSX.Element): Promise<Object3D> {+ if (!root) {+ const canvas = document.createElement("canvas");+ root = createRoot(canvas);+ root.configure({+ // Test double: R3F only needs the renderer's shape here, nothing is drawn.+ gl: fakeRenderer(canvas) as unknown as NonNullable<Parameters<typeof root.configure>[0]>["gl"],+ frameloop: "never",+ size: { width: 100, height: 100, top: 0, left: 0 },+ });+ }+ const current = root;+ await act(async () => { current.render(<group ref={(g) => { if (g) scene = g; }}>{element}</group>); });+ if (!scene) throw new Error("the element did not mount");+ return scene;+}++afterEach(() => {+ root?.unmount();+ root = null;+ scene = null;+});++const staff: OfficeAgentInput[] = Array.from({ length: 6 }, (_, i) => ({+ agentId: `a${i + 1}`, name: `Agent ${i + 1}`, tier: "specialist", providerLabel: "Codex", state: "idle", createdMs: i,+}));+const studio: Department = buildOfficeLayout(staff, { teams: [{ id: "g1", name: "Launch crew", members: ["a1", "a2", "a3"], createdMs: 1 }] })+ .departments.find((d) => d.teamId === "g1")!;++/** The wall's lettering: the one cut-out, textured sheet on it. */+function lettering(node: Object3D): MeshStandardMaterial {+ const found: MeshStandardMaterial[] = [];+ node.traverse((child) => {+ const material = (child as Mesh).isMesh ? ((child as Mesh).material as MeshStandardMaterial) : null;+ if (material?.isMeshStandardMaterial && material.alphaTest > 0.25 && material.alphaTest < 0.35) found.push(material);+ });+ expect(found).toHaveLength(1);+ return found[0];+}++describe("a studio's lettering", () => {+ it("belongs to its wall: a renamed team's old lettering is disposed, texture and all, and the last one with the studio", async () => {+ let made = 0, gone = 0, texturesGone = 0;+ const seen = new Set<MeshStandardMaterial>();+ const watch = (material: MeshStandardMaterial) => {+ if (seen.has(material)) return material;+ seen.add(material);+ made += 1;+ material.addEventListener("dispose", () => { gone += 1; });+ expect(material.map).toBeTruthy();+ material.map!.addEventListener("dispose", () => { texturesGone += 1; });+ return material;+ };+ const first = watch(lettering(await render(<AgentsDepartment dept={studio} />)));+ // The same name again draws nothing new.+ expect(lettering(await render(<AgentsDepartment dept={{ ...studio }} />))).toBe(first);+ expect([made, gone]).toEqual([1, 0]);++ // Forty renames: forty new letterings, each replacing the one before.+ for (let i = 0; i < 40; i += 1) {+ const next = watch(lettering(await render(<AgentsDepartment dept={{ ...studio, label: `Launch crew ${i}` }} />)));+ expect(next).not.toBe(first);+ expect(made - gone, `rename ${i}`).toBe(1);+ expect(texturesGone).toBe(gone);+ }+ expect(made).toBe(41);++ // The team is deleted: its studio goes, and its lettering with it.+ await act(async () => { root?.unmount(); });+ root = null;+ expect([gone, texturesGone]).toEqual([41, 41]);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/AgentsFloorLook.tsx b/jarvis/ui/web/frontend/src/components/society/office/AgentsFloorLook.tsxindex 453d4a12f3..f7dfd67815 100644--- a/jarvis/ui/web/frontend/src/components/society/office/AgentsFloorLook.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/AgentsFloorLook.tsx@@ -2,19 +2,21 @@* The agents floor's own look — the same company as the coding floor above,* but lighter and Scandinavian where that one is walnut and amber: wide* pale-oak planks framed by a warm limestone band along the windows with a- * bronze inlay, a soft warm rim round the slab, and every department on a- * bordered linen rug in front of a pale-oak tambour wall with clean ink- * lettering and two floating shelves.+ * bronze inlay, a soft warm rim round the slab, and every team studio on a+ * bordered rug in its own colour in front of a pale-oak tambour wall capped+ * in that colour, the team's name lettered in ink on its west half (the+ * studio board hangs in front of the east half).*- * Purely visual. The only solid part is the department wall, which stays- * inside the sign-wall footprint the layout already walks round.+ * Purely visual. The only solid part is the studio wall, which stays inside+ * the name-wall footprint the layout already walks round.*/import { useEffect, useMemo } from "react";import type { ThreeEvent } from "@react-three/fiber";import { AdditiveBlending, MeshBasicMaterial, MeshStandardMaterial, RepeatWrapping, Shape, type Texture } from "three";-import { fill, useT } from "@/i18n";-import { cachedCanvasTexture } from "./canvasMaterials";-import { Box, GEO, MAT, matte, Railing } from "./OfficeFurniture";+import { useT } from "@/i18n";+import { cachedCanvasTexture, ownedCanvasTexture } from "./canvasMaterials";+import { Box, matte } from "./OfficeFurniture";+import { studioWallParts } from "./campusLayout";import type { Department, OfficeLayout } from "./officeLayout";/** The agents floor's surfaces and light. */@@ -51,6 +53,13 @@ export const AGENTS_RUGS: readonly AgentsRug[] = [{ weave: "chevron", field: "#e6d0c3", thread: "#dbc0b0", border: "#bb7f66", felt: "#cf9d88" },{ weave: "windowpane", field: "#d2ccdc", thread: "#c4bdd1", border: "#8c84a6", felt: "#aaa3c0" },{ weave: "rib", field: "#c5d7d0", thread: "#b5cbc3", border: "#6a988c", felt: "#8fb3a9" },+ // Mustard, rose, sky, olive, cocoa and indigo: a full campus of twelve studios never repeats a colour.+ { weave: "chevron", field: "#e6d7a6", thread: "#dccb93", border: "#b8963c", felt: "#cdb05f" },+ { weave: "boucle", field: "#dcc3cb", thread: "#d1b4be", border: "#a8647c", felt: "#bf8a9c" },+ { weave: "pinstripe", field: "#b9cfdc", thread: "#a9c2d1", border: "#4f86a6", felt: "#7ba5bf" },+ { weave: "basket", field: "#cfd3aa", thread: "#c2c798", border: "#868c4a", felt: "#a4a96c" },+ { weave: "rib", field: "#d9c4b4", thread: "#cdb5a3", border: "#9a6a4c", felt: "#b68b70" },+ { weave: "windowpane", field: "#bfc6d9", thread: "#b0b8ce", border: "#5c6aa0", felt: "#8590bb" },];/** The rug a department lies on: cycles through the set by the department's tint index. */@@ -142,7 +151,7 @@ function drawStone(ctx: CanvasRenderingContext2D, w: number, h: number): void {}/** A cached base texture, cloned per surface with its own repeat. */-function repeated(base: Texture | null, repeatX: number, repeatZ: number): Texture | null {+export function repeated(base: Texture | null, repeatX: number, repeatZ: number): Texture | null {if (!base) return null;const map = base.clone();map.wrapS = map.wrapT = RepeatWrapping;@@ -152,14 +161,21 @@ function repeated(base: Texture | null, repeatX: number, repeatZ: number): Textureturn map;}+/** A limestone surface `along` × `across` metres, one repeat of the stone per 3 m. The caller owns (and disposes) it. */+export function limestone(along: number, across: number): MeshStandardMaterial {+ const map = repeated(cachedCanvasTexture("agents:stone", 256, 256, drawStone), along / 3, across / 3);+ return new MeshStandardMaterial({ color: map ? "#ffffff" : AGENTS_SCENE.stone.base, map, roughness: 0.45 });+}+/** Width of the limestone band along the slab's edge, and of its bronze inlay. */const BAND_M = 1.35;const INLAY_M = 0.03;/**- * The slab, railing and floor of the agents floor: wide pale-oak planks,- * framed by a limestone band with a bronze inlay along the windows, a warm- * stone edge and a soft warm rim.+ * The slab and floor of the agents floor: wide pale-oak planks, framed by a+ * limestone band with a bronze inlay along the windows, a warm stone edge and+ * a soft warm rim. The floor's edges (window walls, balustrades) are the+ * building shell's.*/export function AgentsSlab({ layout, onFloorClick }: { layout: OfficeLayout; onFloorClick: (event: ThreeEvent<MouseEvent>) => void }) {const { minX, maxX, minZ, maxZ } = layout.bounds;@@ -214,10 +230,6 @@ export function AgentsSlab({ layout, onFloorClick }: { layout: OfficeLayout; onF<Box size={[innerW + INLAY_M, 0.004, INLAY_M]} position={[cx, 0.002, maxZ - BAND_M]} material={inlay} cast={false} /><Box size={[INLAY_M, 0.004, innerD]} position={[minX + BAND_M, 0.002, cz]} material={inlay} cast={false} /><Box size={[INLAY_M, 0.004, innerD]} position={[maxX - BAND_M, 0.002, cz]} material={inlay} cast={false} />- <Railing from={[minX + 0.2, minZ + 0.2]} to={[maxX - 0.2, minZ + 0.2]} />- <Railing from={[maxX - 0.2, minZ + 0.2]} to={[maxX - 0.2, maxZ - 0.2]} />- <Railing from={[maxX - 0.2, maxZ - 0.2]} to={[minX + 0.2, maxZ - 0.2]} />- <Railing from={[minX + 0.2, maxZ - 0.2]} to={[minX + 0.2, minZ + 0.2]} /></group>);}@@ -365,7 +377,7 @@ function tambourMaterial(width: number): MeshStandardMaterial {return material;}-/** Ink letters on a transparent ground: the department's name, a short rule and "Department 0n" under it. */+/** Ink letters on a transparent ground: the studio's name, a short rule in its colour and a caption under it. */function drawLetters(label: string, caption: string, accent: string, ctx: CanvasRenderingContext2D, w: number, h: number): void {ctx.clearRect(0, 0, w, h);const tracked = (text: string, font: string, y: number, spacing: number, fill: string) => {@@ -392,19 +404,16 @@ function drawLetters(label: string, caption: string, accent: string, ctx: Canvastracked(name, "600 104px Inter, system-ui, -apple-system, 'Segoe UI', sans-serif", 84, 4, AGENTS_SCENE.ink);ctx.fillStyle = accent;ctx.fillRect(w / 2 - 44, 154, 88, 5);- tracked(caption, "600 32px Inter, system-ui, -apple-system, 'Segoe UI', sans-serif", 194, 10, "#5d564e");+ tracked(caption.toLocaleUpperCase(), "600 32px Inter, system-ui, -apple-system, 'Segoe UI', sans-serif", 194, 10, "#5d564e");}-const letterMaterials = new Map<string, MeshStandardMaterial>();+/**+ * A studio's lettering. A team's name is whatever the person typed, so this is never cached by its text: the wall+ * that shows it owns the material and its texture, and disposes both when the name changes or the studio goes.+ */function letterMaterial(label: string, caption: string, accent: string): MeshStandardMaterial {- const key = `${caption}:${accent}:${label}`;- let material = letterMaterials.get(key);- if (!material) {- const map = cachedCanvasTexture(`agents:letters:${key}`, LETTERS.w, LETTERS.h, (ctx, w, h) => drawLetters(label, caption, accent, ctx, w, h));- material = new MeshStandardMaterial({ color: map ? "#ffffff" : AGENTS_SCENE.ink, map, transparent: true, alphaTest: 0.3, roughness: 0.6 });- letterMaterials.set(key, material);- }- return material;+ const map = ownedCanvasTexture(LETTERS.w, LETTERS.h, (ctx, w, h) => drawLetters(label, caption, accent, ctx, w, h));+ return new MeshStandardMaterial({ color: map ? "#ffffff" : AGENTS_SCENE.ink, map, transparent: true, alphaTest: 0.3, roughness: 0.6 });}let washCache: MeshBasicMaterial | null = null;@@ -433,29 +442,23 @@ function washMaterial(): MeshBasicMaterial {const WALL_MAT = {cap: matte(AGENTS_SCENE.tambour.cap, { roughness: 0.55 }),- oak: matte("#d9bf97", { roughness: 0.6 }),strip: new MeshStandardMaterial({ color: AGENTS_SCENE.light.glow, emissive: AGENTS_SCENE.light.glow, emissiveIntensity: 1.4, toneMapped: false }),- ceramic: matte("#f2ece2", { roughness: 0.5 }),- clay: matte("#c2856a", { roughness: 0.7 }),- stone: matte("#8e8a84", { roughness: 0.6 }),- linen: [matte("#e8dcc6"), matte("#c9b79a"), matte("#9fb094"), matte("#7d8ea3"), matte("#bb7f66")],};/**- * A department's back wall, centred on its front face: a pale-oak tambour- * panel with an oak cap and a warm light strip under it, the department's- * name in ink letters, a felt kick band in the rug's colour, and on a wide- * wall two floating oak shelves with ceramics, books and a plant.+ * A studio's name wall, centred on its front face: a pale-oak tambour panel+ * under a cap in the studio's colour with a warm light strip, a felt kick+ * band in the same colour, and the name in ink letters on the west half.*/-function DepartmentWall({ label, number, width, position, rug }: {- label: string; number: number; width: number; position: [number, number, number]; rug: AgentsRug;+function StudioWall({ label, caption, width, nameX, position, rug }: {+ label: string; caption: string; width: number; nameX: number; position: [number, number, number]; rug: AgentsRug;}) {const kit = rugKit(rug);- const plateW = Math.min(3.0, width * 0.5);+ const plateW = Math.min(3.0, width / 2 - 0.5);const plateH = (plateW * LETTERS.h) / LETTERS.w;- const shelfX = width / 2 - 0.9;- const t = useT();- const caption = fill(t("society.office.department_n"), { number: String(number).padStart(2, "0") });+ const accent = rug.border;+ const letters = useMemo(() => letterMaterial(label, caption, accent), [label, caption, accent]);+ useEffect(() => () => { letters.map?.dispose(); letters.dispose(); }, [letters]);return (<group position={position}><Box size={[width, WALL_H, 0.1]} position={[0, WALL_H / 2, -0.02]} material={WALL_MAT.cap} />@@ -463,36 +466,21 @@ function DepartmentWall({ label, number, width, position, rug }: {<planeGeometry args={[width - 0.06, WALL_H - 0.16]} /></mesh><Box size={[width - 0.06, 0.12, 0.02]} position={[0, 0.08, 0.04]} material={kit.felt} cast={false} />- <Box size={[width + 0.04, 0.05, 0.16]} position={[0, WALL_H + 0.025, 0]} material={WALL_MAT.cap} />+ {/* The cap wears the studio's colour, so a team reads from across the campus. */}+ <Box size={[width + 0.04, 0.09, 0.16]} position={[0, WALL_H + 0.045, 0]} material={kit.border} />{/* The light strip tucked under the cap, washing down the flutes. */}<Box size={[width - 0.2, 0.012, 0.02]} position={[0, WALL_H - 0.012, 0.06]} material={WALL_MAT.strip} cast={false} /><mesh position={[0, WALL_H - 0.42, 0.035]} material={washMaterial()}><planeGeometry args={[width - 0.1, 0.8]} /></mesh>- <mesh position={[0, 1.34, 0.04]} material={letterMaterial(label, caption, rug.border)}>+ <mesh position={[nameX, 1.3, 0.04]} material={letters}><planeGeometry args={[plateW, plateH]} /></mesh>- {shelfX > plateW / 2 + 0.55 && [-shelfX, shelfX].map((x, side) => (- <group key={x} position={[x, 0, 0]}>- <Box size={[0.95, 0.04, 0.16]} position={[0, 1.1, 0.11]} material={WALL_MAT.oak} />- {/* A ribbed ceramic vase with a sprig, a stack of linen books, a clay pot with a trailing plant. */}- <mesh geometry={GEO.potCyl} material={WALL_MAT.ceramic} position={[-0.3, 1.21, 0.11]} scale={[0.05, 0.18, 0.05]} castShadow />- <mesh geometry={GEO.blob} material={MAT.leafLight} position={[-0.3, 1.36, 0.11]} scale={[0.06, 0.08, 0.06]} castShadow />- {[0, 1, 2].map((i) => (- <Box key={i} size={[0.24 - i * 0.02, 0.035, 0.13]} position={[-0.02, 1.1375 + i * 0.037, 0.11]}- material={WALL_MAT.linen[(i + number + side) % WALL_MAT.linen.length]} />- ))}- <mesh geometry={GEO.cyl} material={WALL_MAT.stone} position={[-0.02, 1.27, 0.11]} scale={[0.035, 0.04, 0.035]} castShadow />- <mesh geometry={GEO.potCyl} material={WALL_MAT.clay} position={[0.3, 1.18, 0.11]} scale={[0.065, 0.12, 0.065]} castShadow />- <mesh geometry={GEO.blob} material={MAT.leaf} position={[0.3, 1.28, 0.11]} scale={[0.11, 0.07, 0.11]} castShadow />- <mesh geometry={GEO.blob} material={MAT.leafDark} position={[0.36, 1.14, 0.17]} scale={[0.05, 0.1, 0.04]} castShadow />- </group>- ))}</group>);}-/** One department's ground and back wall: a bordered, rounded linen rug and the tambour name wall. */+/** One team studio's ground and name wall: a bordered, rounded rug in the studio's colour and the tambour wall. */export function AgentsDepartment({ dept }: { dept: Department }) {const t = useT();const rug = agentsRug(dept.tint);@@ -504,6 +492,8 @@ export function AgentsDepartment({ dept }: { dept: Department }) {line: roundedRect(w - 0.36, d - 0.36, 0.28),field: roundedRect(w - 0.44, d - 0.44, 0.24),}), [w, d]);+ // The pool has no team name: the wall says what it is.+ const pool = dept.teamId === null || dept.teamId === undefined;return (<group><mesh position={[cx, 0.005, cz]} rotation={[-Math.PI / 2, 0, 0]} material={kit.border} receiveShadow>@@ -515,8 +505,9 @@ export function AgentsDepartment({ dept }: { dept: Department }) {<mesh position={[cx, 0.007, cz]} rotation={[-Math.PI / 2, 0, 0]} material={kit.field} receiveShadow><shapeGeometry args={[shapes.field, 6]} /></mesh>- <DepartmentWall label={dept.label || t("society.office.open_space")} number={dept.tint + 1} width={w - 0.4}- position={[cx, 0, dept.minZ + 0.1]} rug={rug} />+ <StudioWall label={dept.label || t("society.office.studio_pool")}+ caption={t(pool ? "society.office.studio_sign_pool" : "society.office.studio_sign_team")}+ width={w - 0.4} nameX={studioWallParts(dept).nameX - cx} position={[cx, 0, dept.minZ + 0.1]} rug={rug} /></group>);}diff --git a/jarvis/ui/web/frontend/src/components/society/office/BreakLounge.tsx b/jarvis/ui/web/frontend/src/components/society/office/BreakLounge.tsxindex 1704212069..8862101123 100644--- a/jarvis/ui/web/frontend/src/components/society/office/BreakLounge.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/BreakLounge.tsx@@ -63,7 +63,7 @@ const BM = {charcoal: matte(C.charcoal, { roughness: 0.7 }),cream: matte(C.cream, { roughness: 0.45 }),navy: matte(C.navy, { roughness: 0.7 }),- brass: matte("#c9a25a", { roughness: 0.35, metalness: 0.6 }),+ brass: matte("#b08d5c", { roughness: 0.35, metalness: 0.6 }),chrome: matte("#d5d8dc", { roughness: 0.25, metalness: 0.7 }),black: matte("#1d1e21", { roughness: 0.5 }),marble: matte("#ece9e4", { roughness: 0.3 }),@@ -962,6 +962,10 @@ export const BreakLoungeFittings = memo(function BreakLoungeFittings({ room, furconst bar = furniture.find((f) => f.kind === "coffeeBar" && f.room === "break");const wallX = room.minX + 0.075;const t = useT();+ // The gallery and the clock hang either side of the west door, wherever a floor's break room has it.+ const westDoor = room.doors.find((door) => door.side === "west");+ const galleryZ = westDoor ? westDoor.at + westDoor.width / 2 + 0.55 : room.minZ + 5.55;+ const clockZ = westDoor ? westDoor.at - westDoor.width / 2 - 0.65 : room.minZ + 2.35;return (<group>{table && (@@ -982,9 +986,9 @@ export const BreakLoungeFittings = memo(function BreakLoungeFittings({ room, fur{/* West wall: a gallery of three prints south of the door, a clock north of it. */}<group position={[wallX, 0, 0]} rotation={[0, Math.PI / 2, 0]}>{([- [room.minZ + 5.55, 1.42, 0.36, 0.45, faces.arches()],- [room.minZ + 6.25, 1.3, 0.56, 0.7, faces.sunset()],- [room.minZ + 6.95, 1.48, 0.36, 0.45, faces.botanical()],+ [galleryZ, 1.42, 0.36, 0.45, faces.arches()],+ [galleryZ + 0.7, 1.3, 0.56, 0.7, faces.sunset()],+ [galleryZ + 1.4, 1.48, 0.36, 0.45, faces.botanical()],] as const).map(([z, y, fw, fh, face]) => (<group key={z} position={[-z, y, 0]}><Box size={[fw + 0.05, fh + 0.05, 0.025]} position={[0, 0, 0]} material={BM.oak} />@@ -992,7 +996,7 @@ export const BreakLoungeFittings = memo(function BreakLoungeFittings({ room, fur<Panel size={[fw - 0.08, fh - 0.08]} position={[0, 0, 0.0155]} material={face} /></group>))}- <group position={[-(room.minZ + 2.35), 1.55, 0]}>+ <group position={[-clockZ, 1.55, 0]}><Cyl radius={0.17} height={0.03} position={[0, 0, 0]} rotation={[Math.PI / 2, 0, 0]} material={BM.oak} /><mesh position={[0, 0, 0.0155]} material={faces.clock()}><circleGeometry args={[0.15, 32]} /></mesh></group>diff --git a/jarvis/ui/web/frontend/src/components/society/office/BuildingShell.tsx b/jarvis/ui/web/frontend/src/components/society/office/BuildingShell.tsxnew file mode 100644index 0000000000..4e8403ecf8--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/BuildingShell.tsx@@ -0,0 +1,284 @@+/**+ * What makes the agents floor (and the Level Hall above it) a floor of a+ * building instead of a plate in space: the tower's body under the slab, a+ * window wall with steel mullions and a ceiling edge on the far sides, the+ * glass balustrade on the sides the camera looks in through, and a city at+ * night far below.+ *+ * The floor is shown like a cut-open model: a side's window wall stands only+ * while the camera is on the opposite side of the floor, so it is always the+ * backdrop and never in the way; the other sides keep the low balustrade.+ *+ * The city is a backdrop and stays one: a few dozen unlit towers a shade+ * lighter than the deep navy night, a long way off and far below the floor,+ * the near ones lowest. One window in twenty is lit, dimly; every tower sinks+ * into the sky's own colour towards its foot and with its distance from the+ * building, and the faintest glow lies over the streets where detail would+ * be. The scene's sun never reaches them. Apart from the sparse windows+ * nothing out there is brighter than a dark navy (#1a2233): the office is+ * always the brightest and most detailed thing on screen.+ *+ * Purely visual and out of reach: everything stands on or beyond the slab's+ * edge, outside the walkable floor. The city is four draw calls (three tower+ * classes and the haze), the shell about two dozen, at any floor size.+ * Nothing casts a shadow.+ */+import { useEffect, useMemo, useRef } from "react";+import { useFrame } from "@react-three/fiber";+import { AdditiveBlending, BufferGeometry, Float32BufferAttribute, Group, MeshBasicMaterial, MeshStandardMaterial, RepeatWrapping, RingGeometry } from "three";+import { cachedCanvasTexture } from "./canvasMaterials";+import { Instances, type Placement } from "./CodingFloorAmbience";+import { Box, GEO, matte, Railing } from "./OfficeFurniture";+import type { OfficeLayout, Rect } from "./officeLayout";++/** The window wall: its height, the mullion pitch, and how far the ceiling edge reaches into the floor. */+export const FACADE = { h: 3.4, pitch: 2.9, soffit: 1.1 } as const;+/** Metres of façade one repeat of the window texture covers (four windows across, four storeys up). */+const WINDOW_TILE_M = 12;+/** A side's window wall changes only once the camera is this far past the floor's middle, so it never flickers. */+const SIDE_DEAD_BAND_M = 4;++const SHELL = {+ steel: matte("#23262b", { roughness: 0.45, metalness: 0.4 }),+ soffit: matte("#f1ede6", { roughness: 0.9 }),+ glass: new MeshStandardMaterial({ color: "#cfe6f7", transparent: true, opacity: 0.16, roughness: 0.08, metalness: 0.1, depthWrite: false }),+ roof: matte("#0f1420", { roughness: 0.95 }),+};++function lcg(seed: number): () => number {+ let state = seed >>> 0;+ return () => {+ state = (state * 1664525 + 1013904223) >>> 0;+ return state / 0x1_0000_0000;+ };+}++/** A tower's cladding at night: a shade lighter than the sky (#0d1320), so a near tower reads against it. */+const CLADDING = "#141b2b";++let windows: MeshBasicMaterial | null = null;+/**+ * A tower's face at night, unlit so the scene's sun never touches it: cladding a shade off the sky and rows of+ * windows of which about one in twenty is lit, dimly and mostly warm. One 128 px tile for the whole city; a+ * tower's own colour (towards the sky's with distance) and its vertex colours (towards the foot) multiply it.+ */+function windowMaterial(): MeshBasicMaterial {+ if (!windows) {+ const map = cachedCanvasTexture("shell:windows:night", 128, 128, (ctx, w, h) => {+ const rand = lcg(0xc17e);+ ctx.fillStyle = CLADDING;+ ctx.fillRect(0, 0, w, h);+ const cols = 8, rows = 8, cw = w / cols, rh = h / rows;+ for (let r = 0; r < rows; r += 1) {+ for (let c = 0; c < cols; c += 1) {+ const roll = rand();+ ctx.fillStyle = roll < 0.04 ? "#6f5b3c" : roll < 0.055 ? "#3c475c" : "#101726";+ ctx.fillRect(c * cw + 4, r * rh + 5, cw - 8, rh - 11);+ }+ }+ });+ if (map) { map.wrapS = map.wrapT = RepeatWrapping; map.anisotropy = 4; }+ windows = new MeshBasicMaterial({ color: map ? "#ffffff" : CLADDING, map, vertexColors: true });+ }+ return windows;+}++/** How dark a tower's foot is against its roof line (in linear light): at the foot the cladding is about the sky's colour. */+const FOOT_SHADE = 0.72;++/**+ * A tower w × h × d, its roof at y = 0: four faces with texture coordinates+ * in metres of façade (every tower shows windows of the same size) and the+ * roof, which takes the cladding's colour from the tile's margin. The vertex+ * colours darken the faces towards the foot.+ */+function towerGeometry(w: number, h: number, d: number): BufferGeometry {+ const positions: number[] = [], normals: number[] = [], uvs: number[] = [], colours: number[] = [], index: number[] = [];+ const face = (ax: number, az: number, bx: number, bz: number, nx: number, nz: number) => {+ const at = positions.length / 3, run = Math.hypot(bx - ax, bz - az) / WINDOW_TILE_M, rise = h / WINDOW_TILE_M;+ positions.push(ax, -h, az, bx, -h, bz, bx, 0, bz, ax, 0, az);+ for (let i = 0; i < 4; i += 1) normals.push(nx, 0, nz);+ uvs.push(0, 0, run, 0, run, rise, 0, rise);+ colours.push(FOOT_SHADE, FOOT_SHADE, FOOT_SHADE, FOOT_SHADE, FOOT_SHADE, FOOT_SHADE, 1, 1, 1, 1, 1, 1);+ index.push(at, at + 1, at + 2, at, at + 2, at + 3);+ };+ const x = w / 2, z = d / 2;+ face(-x, z, x, z, 0, 1);+ face(x, z, x, -z, 1, 0);+ face(x, -z, -x, -z, 0, -1);+ face(-x, -z, -x, z, -1, 0);+ // The roof: every corner samples the tile's margin, which is plain cladding.+ const at = positions.length / 3;+ positions.push(-x, 0, z, x, 0, z, x, 0, -z, -x, 0, -z);+ for (let i = 0; i < 4; i += 1) { normals.push(0, 1, 0); uvs.push(0.008, 0.008); colours.push(1, 1, 1); }+ index.push(at, at + 1, at + 2, at, at + 2, at + 3);+ const geometry = new BufferGeometry();+ geometry.setAttribute("position", new Float32BufferAttribute(positions, 3));+ geometry.setAttribute("normal", new Float32BufferAttribute(normals, 3));+ geometry.setAttribute("uv", new Float32BufferAttribute(uvs, 2));+ geometry.setAttribute("color", new Float32BufferAttribute(colours, 3));+ geometry.setIndex(index);+ return geometry;+}++/** Tower sizes of the city: every tower of a class shares one geometry, so each class is one draw call. */+const TOWER_CLASSES = [{ w: 14, d: 14, h: 110 }, { w: 22, d: 16, h: 110 }, { w: 30, d: 20, h: 110 }] as const;+/**+ * The city's reserve. `clear`: empty air round the building before the first tower. `reach`: how far the city+ * goes on from there. `roofTop`: the highest any roof comes, metres below the floor; the towers nearest the+ * building lie `nearDrop` lower still, and each a random share of `roofDrop` below that. `near`/`far`: a+ * tower's tint beside the clear air and at the city's far end, where the cladding comes out at the sky's colour.+ */+const CITY = { clear: 62, reach: 170, towers: 60, roofTop: -24, nearDrop: 22, roofDrop: 56, near: 1, far: 0.8, haze: -64 } as const;++const grey = (v: number): string => {+ const c = Math.round(Math.min(1, Math.max(0, v)) * 255).toString(16).padStart(2, "0");+ return `#${c}${c}${c}`;+};++/** How bright the haze is at each of its rings, from the building outwards: nothing, rising, full, fading, nothing. */+const HAZE_RINGS = [0, 0.55, 1, 0.45, 0] as const;+/**+ * The glow of streets too far down to see, added over the night. In LINEAR light, where the sky itself is about+ * (0.004, 0.007, 0.014): at its brightest the haze lifts the navy to about #181b27 and no further.+ */+const HAZE_TONE = [0.005, 0.0045, 0.006] as const;+const HAZE_MATERIAL = new MeshBasicMaterial({+ vertexColors: true, transparent: true, blending: AdditiveBlending, depthWrite: false, fog: false, toneMapped: false,+});++/** A flat ring of haze from `inner` to `outer` metres, brightest a third of the way out. */+function hazeGeometry(inner: number, outer: number): BufferGeometry {+ const rings = HAZE_RINGS.length - 1, segments = 48;+ const geometry = new RingGeometry(inner, outer, segments, rings).rotateX(-Math.PI / 2);+ const colours: number[] = [];+ for (let ring = 0; ring <= rings; ring += 1) {+ for (let s = 0; s <= segments; s += 1) colours.push(HAZE_TONE[0] * HAZE_RINGS[ring], HAZE_TONE[1] * HAZE_RINGS[ring], HAZE_TONE[2] * HAZE_RINGS[ring]);+ }+ geometry.setAttribute("color", new Float32BufferAttribute(colours, 3));+ return geometry;+}++/**+ * The city: a thin field of towers whose roofs all lie far below the floor,+ * the nearest lowest, so none ever rises into the view or stands in front of+ * the office, and a ring of haze over their feet.+ */+function Skyline({ bounds }: { bounds: Rect }) {+ const cx = (bounds.minX + bounds.maxX) / 2, cz = (bounds.minZ + bounds.maxZ) / 2;+ const halfW = (bounds.maxX - bounds.minX) / 2, halfD = (bounds.maxZ - bounds.minZ) / 2;+ const geometries = useMemo(() => TOWER_CLASSES.map((c) => towerGeometry(c.w, c.h, c.d)), []);+ useEffect(() => () => { for (const g of geometries) g.dispose(); }, [geometries]);+ const haze = useMemo(() => hazeGeometry(Math.hypot(halfW, halfD) + 6, Math.hypot(halfW, halfD) + CITY.clear + CITY.reach + 80), [halfW, halfD]);+ useEffect(() => () => haze.dispose(), [haze]);+ const towers = useMemo(() => {+ const rand = lcg(0x51a7e);+ const towers: Placement[][] = TOWER_CLASSES.map(() => []);+ const taken: { x: number; z: number; r: number }[] = [];+ for (let i = 0; i < CITY.towers; i += 1) {+ const angle = rand() * Math.PI * 2, far = rand(), reach = CITY.clear + far * CITY.reach;+ const x = cx + Math.cos(angle) * (halfW + reach), z = cz + Math.sin(angle) * (halfD + reach);+ const kind = Math.floor(rand() * TOWER_CLASSES.length);+ const top = CITY.roofTop - (1 - far) * CITY.nearDrop - rand() * rand() * CITY.roofDrop;+ // Wide gaps: the city is a few silhouettes, never a wall.+ const size = TOWER_CLASSES[kind], r = Math.hypot(size.w, size.d) / 2 + 9;+ if (taken.some((t) => Math.hypot(t.x - x, t.z - z) < t.r + r)) continue;+ taken.push({ x, z, r });+ towers[kind].push({ position: [x, top, z], scale: [1, 1, 1], color: grey(CITY.near + (CITY.far - CITY.near) * far) });+ }+ return towers;+ }, [cx, cz, halfW, halfD]);+ return (+ <group>+ {geometries.map((geometry, i) => <Instances key={i} geometry={geometry} material={windowMaterial()} items={towers[i]} cast={false} />)}+ <mesh geometry={haze} material={HAZE_MATERIAL} position={[cx, CITY.haze, cz]} renderOrder={1} />+ </group>+ );+}++/** The building's own body under the slab: the tower this floor belongs to, dark and plain so the floor above it carries. */+function TowerBody({ bounds }: { bounds: Rect }) {+ const w = bounds.maxX - bounds.minX - 1.2, d = bounds.maxZ - bounds.minZ - 1.2;+ const geometry = useMemo(() => towerGeometry(w, 140, d), [w, d]);+ useEffect(() => () => geometry.dispose(), [geometry]);+ return <mesh geometry={geometry} material={SHELL.roof} position={[(bounds.minX + bounds.maxX) / 2, -0.6, (bounds.minZ + bounds.maxZ) / 2]} />;+}++type Side = "north" | "south" | "west" | "east";++/** One side's window wall, in its own frame: it runs along +x, the floor lies towards +z. */+function WindowWall({ length }: { length: number }) {+ const mullions = useMemo<Placement[]>(() => {+ const count = Math.max(2, Math.round(length / FACADE.pitch) + 1);+ return Array.from({ length: count }, (_, i) => ({+ position: [-length / 2 + (length * i) / (count - 1), FACADE.h / 2, 0] as [number, number, number], scale: [0.07, FACADE.h, 0.12] as [number, number, number],+ }));+ }, [length]);+ return (+ <group>+ <Box size={[length, 0.22, 0.14]} position={[0, 0.11, 0]} material={SHELL.steel} cast={false} />+ <Box size={[length, FACADE.h - 0.5, 0.03]} position={[0, 0.22 + (FACADE.h - 0.5) / 2, 0]} material={SHELL.glass} cast={false} />+ <Box size={[length, 0.28, 0.2]} position={[0, FACADE.h - 0.14, 0]} material={SHELL.steel} cast={false} />+ {/* The ceiling's edge: a pale band running into the floor from the head of the wall. */}+ <Box size={[length, 0.1, FACADE.soffit]} position={[0, FACADE.h + 0.05, FACADE.soffit / 2 - 0.1]} material={SHELL.soffit} cast={false} />+ <Instances geometry={GEO.box} material={SHELL.steel} items={mullions} cast={false} />+ </group>+ );+}++/**+ * The floor's four edges. Each has a window wall and a balustrade; the wall+ * shows on the sides the camera looks towards, the balustrade on the others.+ */+function Edges({ bounds }: { bounds: Rect }) {+ const { minX, maxX, minZ, maxZ } = bounds;+ const cx = (minX + maxX) / 2, cz = (minZ + maxZ) / 2, w = maxX - minX, d = maxZ - minZ;+ const walls = useRef<Partial<Record<Side, Group | null>>>({});+ const rails = useRef<Partial<Record<Side, Group | null>>>({});+ // The home view looks from the south-east: north and west are the backdrop.+ const shown = useRef<Record<Side, boolean>>({ north: true, west: true, south: false, east: false });+ useFrame(({ camera }) => {+ const dx = camera.position.x - cx, dz = camera.position.z - cz;+ const next = shown.current;+ if (Math.abs(dz) > SIDE_DEAD_BAND_M) { next.north = dz > 0; next.south = dz < 0; }+ if (Math.abs(dx) > SIDE_DEAD_BAND_M) { next.west = dx > 0; next.east = dx < 0; }+ for (const side of ["north", "south", "west", "east"] as const) {+ const wall = walls.current[side], rail = rails.current[side];+ if (wall) wall.visible = next[side];+ if (rail) rail.visible = !next[side];+ }+ });+ // The walls stand just inside the slab's edge and meet in its corners; the balustrade keeps its own line.+ const inset = 0.12, rail = 0.2;+ // A wall's frame: +x along the edge, +z into the floor.+ const sides: { side: Side; position: [number, number, number]; rotationY: number; length: number; from: [number, number]; to: [number, number] }[] = [+ { side: "north", position: [cx, 0, minZ + inset], rotationY: 0, length: w - inset * 2, from: [minX + rail, minZ + rail], to: [maxX - rail, minZ + rail] },+ { side: "south", position: [cx, 0, maxZ - inset], rotationY: Math.PI, length: w - inset * 2, from: [maxX - rail, maxZ - rail], to: [minX + rail, maxZ - rail] },+ { side: "west", position: [minX + inset, 0, cz], rotationY: Math.PI / 2, length: d - inset * 2, from: [minX + rail, maxZ - rail], to: [minX + rail, minZ + rail] },+ { side: "east", position: [maxX - inset, 0, cz], rotationY: -Math.PI / 2, length: d - inset * 2, from: [maxX - rail, minZ + rail], to: [maxX - rail, maxZ - rail] },+ ];+ return (+ <group>+ {sides.map(({ side, position, rotationY, length, from, to }) => (+ <group key={side}>+ <group ref={(g) => { walls.current[side] = g; }} position={position} rotation={[0, rotationY, 0]} visible={shown.current[side]}>+ <WindowWall length={length} />+ </group>+ <group ref={(g) => { rails.current[side] = g; }} visible={!shown.current[side]}>+ <Railing from={from} to={to} />+ </group>+ </group>+ ))}+ </group>+ );+}++export function BuildingShell({ layout }: { layout: OfficeLayout }) {+ return (+ <group>+ <Skyline bounds={layout.bounds} />+ <TowerBody bounds={layout.bounds} />+ <Edges bounds={layout.bounds} />+ </group>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/CampusFittings.tsx b/jarvis/ui/web/frontend/src/components/society/office/CampusFittings.tsxnew file mode 100644index 0000000000..53df450b5b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/CampusFittings.tsx@@ -0,0 +1,256 @@+/**+ * The agents floor's built fittings: what encloses and furnishes a team+ * studio (low felt-and-glass screens, a storage cabinet, a sofa, a standing+ * table) and what furnishes the commons (the atrium's step seating, the+ * café's kitchen run and island, focus booths, large trees).+ *+ * Every piece is assembled from a handful of shapes, and every shape of one+ * material is one instanced mesh for the whole floor: a campus of twelve+ * furnished studios costs the same sixteen draw calls as an empty one. Each+ * piece is built inside the box the plan (`layout.ambience`) gives it, which+ * is also what navigation walks round; a studio's pieces wear its colour.+ */+import { useMemo } from "react";+import { MeshStandardMaterial } from "three";+import {+ BOOTH, CABINET, COUNTER, CRATE, HIGH_TABLE, ISLAND, SCREEN, SOFA, STEPS, ownSize, stepsSeats, yawOf, type AgentsAmbienceItem,+} from "./agentsAmbience";+import { agentsRug, AGENTS_RUGS } from "./AgentsFloorLook";+import { Instances, type Placement } from "./CodingFloorAmbience";+import { GEO, MAT, matte } from "./OfficeFurniture";++const FIT = {+ oak: matte("#d9bf97", { roughness: 0.6 }),+ oakDark: matte("#b89b74", { roughness: 0.65 }),+ /** White, so each instance's colour is its felt, fabric or paint. */+ tint: matte("#ffffff", { roughness: 0.95 }),+ steel: matte("#23262b", { roughness: 0.45, metalness: 0.4 }),+ stone: matte("#e4ddd1", { roughness: 0.6 }),+ bark: matte("#6f5d4b", { roughness: 0.9 }),+ glass: new MeshStandardMaterial({ color: "#d6ecff", transparent: true, opacity: 0.28, roughness: 0.08, depthWrite: false }),+ glow: new MeshStandardMaterial({ color: "#fff0d8", emissive: "#fff0d8", emissiveIntensity: 1.5, toneMapped: false }),+};++/** Neutral tones for pieces that belong to no team, and the small things that stand on them. */+const NEUTRAL = { felt: "#cfc7ba", fabric: "#d6cfc2", paint: "#f3f1ec", linen: "#e9e1d2", sage: "#9fb094", ceramic: "#f2ece2" } as const;+const ACCENTS = ["#c07f63", "#8fa383", "#d2a650", "#7f93a8", "#d9c9ab"] as const;++function lcg(seed: number): () => number {+ let state = seed >>> 0;+ return () => {+ state = (state * 1664525 + 1013904223) >>> 0;+ return state / 0x1_0000_0000;+ };+}++function seedOf(id: string): number {+ let h = 2166136261;+ for (let i = 0; i < id.length; i += 1) h = Math.imul(h ^ id.charCodeAt(i), 16777619);+ return h >>> 0;+}++/** The shapes of the whole floor, sorted by the instanced mesh that draws them. */+interface Parts {+ oak: Placement[]; oakDark: Placement[]; tint: Placement[]; steel: Placement[]; stone: Placement[]; glass: Placement[]; glow: Placement[];+ roundOak: Placement[]; roundSteel: Placement[]; roundTint: Placement[]; roundStone: Placement[]; pot: Placement[]; bark: Placement[];+ leaf: Placement[]; leafDark: Placement[]; leafLight: Placement[];+}++/**+ * Places a shape given in a piece's own frame (x along its front, z towards+ * its front, origin on the floor under its middle) into the world.+ */+function frameOf(item: AgentsAmbienceItem) {+ const yaw = yawOf(item.facing), cos = Math.cos(yaw), sin = Math.sin(yaw);+ const cx = (item.minX + item.maxX) / 2, cz = (item.minZ + item.maxZ) / 2;+ return (lx: number, y: number, lz: number, sx: number, sy: number, sz: number, color?: string): Placement => ({+ position: [cx + lx * cos + lz * sin, y, cz - lx * sin + lz * cos], scale: [sx, sy, sz], rotation: [0, yaw, 0], ...(color ? { color } : {}),+ });+}++const feltOf = (item: AgentsAmbienceItem) => (item.tint === undefined ? NEUTRAL.felt : agentsRug(item.tint).felt);+const accentOf = (item: AgentsAmbienceItem) => (item.tint === undefined ? "#8e8a84" : agentsRug(item.tint).border);++/** A low screen: a felt panel in the studio's colour on a steel shoe, a band of glass above it and a slim steel cap. */+function buildScreen(item: AgentsAmbienceItem, p: Parts): void {+ const dx = item.maxX - item.minX, dz = item.maxZ - item.minZ, alongX = dx > dz;+ const cx = (item.minX + item.maxX) / 2, cz = (item.minZ + item.maxZ) / 2;+ const felt = 0.92, glass = SCREEN.h - felt - 0.09;+ p.steel.push({ position: [cx, 0.03, cz], scale: [dx + (alongX ? 0 : 0.02), 0.06, dz + (alongX ? 0.02 : 0)] });+ p.tint.push({ position: [cx, 0.06 + felt / 2, cz], scale: [dx, felt, dz], color: feltOf(item) });+ p.glass.push({ position: [cx, 0.06 + felt + glass / 2, cz], scale: alongX ? [dx, glass, 0.02] : [0.02, glass, dz] });+ p.steel.push({ position: [cx, SCREEN.h - 0.015, cz], scale: alongX ? [dx, 0.03, 0.05] : [0.05, 0.03, dz] });+}++/** A storage cabinet: white fronts on a recessed plinth under an oak top, a line in the studio's colour, books and a plant on it. */+function buildCabinet(item: AgentsAmbienceItem, p: Parts): void {+ const at = frameOf(item), { w, d } = CABINET;+ p.oakDark.push(at(0, 0.03, 0, w - 0.06, 0.06, d - 0.06));+ p.tint.push(at(0, 0.46, 0, w, 0.8, d - 0.02, NEUTRAL.paint));+ p.oak.push(at(0, 0.8775, 0, w + 0.02, 0.035, d + 0.02));+ p.tint.push(at(0, 0.78, d / 2 - 0.004, w - 0.1, 0.05, 0.012, accentOf(item)));+ p.tint.push(at(-0.45, 0.92, 0, 0.3, 0.05, 0.22, ACCENTS[0]));+ p.tint.push(at(-0.43, 0.97, 0, 0.26, 0.05, 0.2, ACCENTS[4]));+ p.roundTint.push(at(0.5, 0.965, 0, 0.09, 0.14, 0.09, NEUTRAL.ceramic));+ p.leafLight.push(at(0.5, 1.13, 0, 0.16, 0.14, 0.16));+}++/** A two-seat sofa on a recessed plinth: a deep base, two seat cushions, a back and two arms, in the studio's felt. */+function buildSofa(item: AgentsAmbienceItem, p: Parts): void {+ const at = frameOf(item), { w, d } = SOFA;+ const fabric = item.tint === undefined ? NEUTRAL.fabric : agentsRug(item.tint).felt;+ p.oakDark.push(at(0, 0.06, 0, w - 0.12, 0.12, d - 0.14));+ p.tint.push(at(0, 0.22, 0, w, 0.2, d, fabric));+ for (const lx of [-0.44, 0.44]) p.tint.push(at(lx, 0.39, 0.08, w / 2 - 0.2, 0.14, d - 0.3, fabric));+ p.tint.push(at(0, 0.57, -d / 2 + 0.11, w - 0.28, 0.42, 0.2, fabric));+ for (const lx of [-(w / 2 - 0.07), w / 2 - 0.07]) p.tint.push(at(lx, 0.44, 0, 0.14, 0.32, d - 0.02, fabric));+ p.tint.push(at(0.62, 0.58, -0.12, 0.32, 0.26, 0.1, ACCENTS[seedOf(item.id) % ACCENTS.length]));+}++/** A round standing table: an oak top on a steel stem, a cup left on it. */+function buildHighTable(item: AgentsAmbienceItem, p: Parts): void {+ const x = (item.minX + item.maxX) / 2, z = (item.minZ + item.maxZ) / 2, { r, h } = HIGH_TABLE;+ p.roundSteel.push({ position: [x, 0.015, z], scale: [0.24, 0.03, 0.24] });+ p.roundSteel.push({ position: [x, (h - 0.04) / 2, z], scale: [0.03, h - 0.04, 0.03] });+ p.roundOak.push({ position: [x, h - 0.02, z], scale: [r, 0.04, r] });+ p.roundTint.push({ position: [x + 0.14, h + 0.045, z - 0.06], scale: [0.04, 0.09, 0.04], color: NEUTRAL.ceramic });+}++/** A focus booth: oak walls and roof round a felt back panel with a shelf and a light, a glass sidelight beside the doorway. */+function buildBooth(item: AgentsAmbienceItem, p: Parts): void {+ const at = frameOf(item), { w, d, h, wall } = BOOTH;+ const wallH = h - 0.04, wallY = 0.04 + wallH / 2;+ p.oakDark.push(at(0, 0.02, 0, w, 0.04, d));+ p.oak.push(at(0, wallY, -d / 2 + wall / 2, w, wallH, wall));+ for (const lx of [-(w / 2 - wall / 2), w / 2 - wall / 2]) p.oak.push(at(lx, wallY, wall / 2, wall, wallH, d - wall));+ p.oak.push(at(0, h - 0.04, 0, w, 0.08, d));+ p.tint.push(at(0, 1.35, -d / 2 + wall + 0.01, w - 0.2, 1.3, 0.02, feltOf(item)));+ p.oak.push(at(0, 1.02, -d / 2 + wall + 0.15, w - 0.24, 0.035, 0.3));+ p.glow.push(at(0, h - 0.1, 0, w - 0.3, 0.02, 0.05));+ p.glass.push(at(-(w / 2 - wall - 0.15), 0.04 + (h - 0.3) / 2, d / 2 - 0.02, 0.3, h - 0.3, 0.02));+}++/**+ * Step seating, the atrium's own furniture. Each tier is a dark riser under a pale timber tread that noses out+ * over it. The lowest tier is plainly a seat: a linen pad per place and a back cushion against the next riser.+ * Higher up lie loose cushions in the studios' colours, as if the teams had left them there.+ */+function buildSteps(item: AgentsAmbienceItem, p: Parts): void {+ const at = frameOf(item), { w, d } = ownSize(item);+ const tread = 0.05, nose = 0.035;+ for (let k = 0; k < STEPS.tiers; k += 1) {+ const top = STEPS.rise * (k + 1), front = d / 2 - STEPS.tier * k;+ // The riser: the tier's body, set back a little under the tread and darker, so every step casts a line.+ p.oakDark.push(at(0, (top - tread) / 2, front - STEPS.tier / 2 - 0.01, w - 0.04, top - tread, STEPS.tier - 0.02));+ p.oak.push(at(0, top - tread / 2, front - STEPS.tier / 2 + nose / 2, w, tread, STEPS.tier + nose));+ }+ // Steel cheeks close both ends.+ for (const lx of [-w / 2 + 0.012, w / 2 - 0.012]) p.steel.push(at(lx, STEPS.rise / 2, d / 2 - STEPS.tier / 2, 0.024, STEPS.rise, STEPS.tier));+ const seats = stepsSeats(item).length, seatZ = d / 2 - STEPS.tier / 2;+ for (let i = 0; i < seats; i += 1) {+ const lx = (i - (seats - 1) / 2) * 0.9;+ // A thin pad: a seated figure's height is the tread's.+ p.tint.push(at(lx, STEPS.rise + 0.0125, seatZ + 0.06, 0.74, 0.025, 0.58, NEUTRAL.linen));+ p.tint.push(at(lx, STEPS.rise + 0.2, seatZ - STEPS.tier / 2 + 0.07, 0.7, 0.3, 0.1, NEUTRAL.fabric));+ }+ const rand = lcg(seedOf(item.id));+ const count = Math.max(3, Math.round(w / 1.3));+ for (let i = 0; i < count; i += 1) {+ const tier = 1 + (i % 2), top = STEPS.rise * (tier + 1);+ const lx = -w / 2 + 0.5 + ((w - 1) * (i + rand() * 0.6)) / count;+ p.tint.push(at(lx, top + 0.05, d / 2 - STEPS.tier * tier - STEPS.tier / 2 + (rand() - 0.5) * 0.2, 0.44, 0.1, 0.44,+ AGENTS_RUGS[Math.floor(rand() * AGENTS_RUGS.length)].border));+ }+}++/** Two moving crates, one on the other and a little askew, with dark handles and a label. */+function buildCrate(item: AgentsAmbienceItem, p: Parts): void {+ const at = frameOf(item), { w, d, h } = CRATE;+ const half = h / 2 - 0.01;+ p.oak.push(at(0, half / 2, 0, w, half, d));+ p.oak.push(at(0.06, half + 0.01 + half / 2, -0.03, w - 0.14, half, d - 0.08));+ for (const y of [half / 2, half + 0.01 + half / 2]) p.oakDark.push(at(y < half ? 0 : 0.06, y, d / 2 - 0.02 - (y < half ? 0 : 0.07), 0.24, 0.05, 0.012));+ p.tint.push(at(-0.2, half * 0.55, d / 2 + 0.002, 0.2, 0.13, 0.006, NEUTRAL.paint));+}++/** The café's kitchen run: white base units under a stone top, an oak back wall with two shelves of cups and jars, a coffee machine. */+function buildCounter(item: AgentsAmbienceItem, p: Parts): void {+ const at = frameOf(item), { w, d } = ownSize(item);+ const top = 0.92, back = -d / 2 + 0.025, shelfZ = -d / 2 + 0.18;+ p.oakDark.push(at(0, 0.04, 0.02, w, 0.08, d - 0.12));+ p.tint.push(at(0, 0.48, 0, w, 0.8, d - 0.04, NEUTRAL.paint));+ p.stone.push(at(0, 0.9, 0, w + 0.02, 0.04, d + 0.02));+ p.oak.push(at(0, top + (COUNTER.h - top) / 2, back, w, COUNTER.h - top, 0.05));+ for (const y of [1.42, 1.78]) p.oak.push(at(0, y, shelfZ, w - 0.3, 0.035, 0.26));+ p.glow.push(at(0, 1.75, shelfZ + 0.1, w - 0.4, 0.015, 0.03));+ p.steel.push(at(-w / 4, top + 0.23, -0.05, 0.5, 0.46, 0.42));+ for (let i = 0; i < 6; i += 1) p.roundTint.push(at(0.2 + i * 0.17, 1.42 + 0.0175 + 0.045, shelfZ, 0.04, 0.09, 0.04, NEUTRAL.ceramic));+ for (let i = 0; i < 5; i += 1) p.roundTint.push(at(-w / 2 + 0.5 + i * 0.26, 1.78 + 0.0175 + 0.08, shelfZ, 0.06, 0.16, 0.06, ACCENTS[i % ACCENTS.length]));+}++/** The café's island: a sage base under an oak top that overhangs it, a bowl and a plant on it. */+function buildIsland(item: AgentsAmbienceItem, p: Parts): void {+ const at = frameOf(item), { w, d, h } = ISLAND;+ p.tint.push(at(0, (h - 0.05) / 2, 0, w - 0.3, h - 0.05, d - 0.24, NEUTRAL.sage));+ p.oak.push(at(0, h - 0.025, 0, w, 0.05, d));+ p.roundTint.push(at(-0.7, h + 0.03, 0, 0.17, 0.06, 0.17, NEUTRAL.ceramic));+ p.roundTint.push(at(0.75, h + 0.07, 0.05, 0.08, 0.14, 0.08, ACCENTS[0]));+ p.leaf.push(at(0.75, h + 0.24, 0.05, 0.17, 0.15, 0.17));+}++/** A large tree: a round stone planter, a tall trunk with two boughs and a full crown that spreads above head height. */+function buildTree(item: AgentsAmbienceItem, p: Parts): void {+ const x = (item.minX + item.maxX) / 2, z = (item.minZ + item.maxZ) / 2, r = (item.maxX - item.minX) / 2;+ const rand = lcg(seedOf(item.id));+ p.pot.push({ position: [x, 0.35, z], scale: [r - 0.05, 0.7, r - 0.05] });+ p.roundStone.push({ position: [x, 0.72, z], scale: [r - 0.02, 0.05, r - 0.02] });+ p.bark.push({ position: [x, 1.85, z], scale: [0.09, 2.2, 0.09], rotation: [(rand() - 0.5) * 0.08, 0, (rand() - 0.5) * 0.08] });+ p.bark.push({ position: [x - 0.3, 2.9, z + 0.1], scale: [0.05, 1.0, 0.05], rotation: [0.15, 0, 0.55] });+ p.bark.push({ position: [x + 0.32, 3.0, z - 0.12], scale: [0.045, 1.1, 0.045], rotation: [-0.18, 0, -0.5] });+ const crowns = [p.leaf, p.leafDark, p.leafLight];+ // A crown of a few large clusters reads as one tree; many small ones only cost triangles.+ for (let k = 0; k < 14; k += 1) {+ const a = (k / 14) * Math.PI * 2 + rand() * 0.5, ring = 0.2 + rand() * 1.0;+ const y = 3.45 + (rand() - 0.5) * 0.8 - ring * 0.35;+ const s = 0.46 + rand() * 0.26;+ crowns[Math.floor(rand() * 2.4)].push({ position: [x + Math.cos(a) * ring, y, z + Math.sin(a) * ring], scale: [s * 1.25, s * 0.85, s * 1.25] });+ }+}++const BUILDERS: Partial<Record<AgentsAmbienceItem["kind"], (item: AgentsAmbienceItem, parts: Parts) => void>> = {+ screen: buildScreen, cabinet: buildCabinet, sofa: buildSofa, hightable: buildHighTable,+ booth: buildBooth, steps: buildSteps, counter: buildCounter, island: buildIsland, tree: buildTree, crate: buildCrate,+};++/** Every built fitting of the floor, drawn by sixteen instanced meshes. */+export function CampusFittings({ items }: { items: readonly AgentsAmbienceItem[] }) {+ const p = useMemo(() => {+ const parts: Parts = {+ oak: [], oakDark: [], tint: [], steel: [], stone: [], glass: [], glow: [],+ roundOak: [], roundSteel: [], roundTint: [], roundStone: [], pot: [], bark: [], leaf: [], leafDark: [], leafLight: [],+ };+ for (const item of items) BUILDERS[item.kind]?.(item, parts);+ return parts;+ }, [items]);+ return (+ <group>+ <Instances geometry={GEO.box} material={FIT.oak} items={p.oak} />+ <Instances geometry={GEO.box} material={FIT.oakDark} items={p.oakDark} cast={false} />+ <Instances geometry={GEO.box} material={FIT.tint} items={p.tint} />+ <Instances geometry={GEO.box} material={FIT.steel} items={p.steel} />+ <Instances geometry={GEO.box} material={FIT.stone} items={p.stone} />+ <Instances geometry={GEO.box} material={FIT.glass} items={p.glass} cast={false} />+ <Instances geometry={GEO.box} material={FIT.glow} items={p.glow} cast={false} />+ <Instances geometry={GEO.cyl} material={FIT.oak} items={p.roundOak} />+ <Instances geometry={GEO.cyl} material={FIT.steel} items={p.roundSteel} />+ <Instances geometry={GEO.cyl} material={FIT.tint} items={p.roundTint} cast={false} />+ <Instances geometry={GEO.cyl} material={FIT.stone} items={p.roundStone} />+ <Instances geometry={GEO.potCyl} material={FIT.stone} items={p.pot} />+ <Instances geometry={GEO.cyl} material={FIT.bark} items={p.bark} />+ <Instances geometry={GEO.blob} material={MAT.leaf} items={p.leaf} />+ <Instances geometry={GEO.blob} material={MAT.leafDark} items={p.leafDark} />+ {/* Two of a crown's three tones throw its shadow. */}+ <Instances geometry={GEO.blob} material={MAT.leafLight} items={p.leafLight} cast={false} />+ </group>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/CampusGround.tsx b/jarvis/ui/web/frontend/src/components/society/office/CampusGround.tsxnew file mode 100644index 0000000000..574c7b9ce7--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/CampusGround.tsx@@ -0,0 +1,234 @@+/**+ * The agents floor's ground between the studios, and the atrium's crown: the+ * two boulevards paved in the limestone of the window band, the atrium's+ * round inlay under the spawn point with a ring of light over it, the free+ * plot taped out for the next team with its lettering on the floor, and a+ * carpet of its own under every commons (moss in a garden court, slate felt+ * under the focus booths, warm tiles in the café).+ *+ * The ring is a light fitting, not a glow: a steel band the size of the disc+ * whose inner face is the lamp, hung on six rods from the ceiling line, each+ * under its own small canopy.+ *+ * The ground is flat and takes no pointer events, so walking and clicking the+ * floor work through it; the ring hangs above every head. Each surface is+ * one mesh; all of it costs about twenty draw calls at any campus size.+ */+import { useEffect, useMemo } from "react";+import { BackSide, CylinderGeometry, MeshStandardMaterial, RingGeometry, Shape } from "three";+import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js";+import { useT } from "@/i18n";+import { AGENTS_SCENE, limestone } from "./AgentsFloorLook";+import { FACADE } from "./BuildingShell";+import { cachedCanvasTexture } from "./canvasMaterials";+import { Instances, type Placement } from "./CodingFloorAmbience";+import { GEO, matte } from "./OfficeFurniture";+import type { CampusZone, CampusZoneKind, OfficeLayout, Rect } from "./officeLayout";++/**+ * Heights of the layers. The plank floor lies at 1 mm; whatever overlaps something else is at least a millimetre+ * above it, which is what the depth buffer still tells apart from the far end of the zoom.+ */+const Y = { paving: 0.003, moss: 0.003, field: 0.004, mark: 0.005 } as const;+/** The window band's width (see AgentsSlab): the main boulevard's paving runs out to it. */+const WINDOW_BAND = 1.35;+/** The atrium's disc lies between its two flights of step seating; the ring of light hangs over its rim. */+const ATRIUM_R = 4.2;+/** The ring: its top's height, the band's height and thickness, and how many rods carry it up to the ceiling line. */+const ATRIUM_RING = { y: 2.9, band: 0.11, rods: 6 } as const;+const RING_T = 0.03;+/** The band's steel: its outer face and its top edge. Its origin is the ring's middle at the height of its top. */+const RING_BODY = mergeGeometries([+ new CylinderGeometry(ATRIUM_R, ATRIUM_R, ATRIUM_RING.band, 72, 1, true).translate(0, -ATRIUM_RING.band / 2, 0),+ new RingGeometry(ATRIUM_R - RING_T, ATRIUM_R, 72).rotateX(-Math.PI / 2),+]);+/** The lamp: the band's inner face, seen from inside the ring. */+const RING_LAMP = new CylinderGeometry(ATRIUM_R - RING_T, ATRIUM_R - RING_T, ATRIUM_RING.band - 0.02, 72, 1, true).translate(0, -ATRIUM_RING.band / 2, 0);++/** The rods the ring hangs on, and the canopy at the head of each, round the ring's own middle. */+const RING_RODS: Placement[] = Array.from({ length: ATRIUM_RING.rods }, (_, i) => {+ const a = ((i + 0.5) / ATRIUM_RING.rods) * Math.PI * 2, r = ATRIUM_R - RING_T / 2;+ const x = Math.cos(a) * r, z = Math.sin(a) * r, drop = FACADE.h - ATRIUM_RING.y;+ return [+ { position: [x, ATRIUM_RING.y + drop / 2, z], scale: [0.016, drop, 0.016] },+ { position: [x, FACADE.h - 0.012, z], scale: [0.12, 0.024, 0.12] },+ ] satisfies Placement[];+}).flat();++const GROUND = {+ inlay: matte(AGENTS_SCENE.stone.inlay, { roughness: 0.4, metalness: 0.45 }),+ disc: matte("#f1ece3", { roughness: 0.5 }),+ /** Floor marking tape. */+ tape: matte("#e2bc62", { roughness: 0.75 }),+ steel: matte("#23262b", { roughness: 0.45, metalness: 0.4 }),+ /** Warm and tone-mapped: a lamp behind a diffuser, never a white line. */+ lamp: new MeshStandardMaterial({ color: "#f3cf9c", emissive: "#ffbf78", emissiveIntensity: 0.85, roughness: 0.6, side: BackSide }),+};++/** A commons' carpet: a darker rim round a lighter field. The library lies on its own rug and the plain oak. */+const CARPETS: Partial<Record<CampusZoneKind, { edge: MeshStandardMaterial; field: MeshStandardMaterial }>> = {+ garden: { edge: matte("#a9b795", { roughness: 1 }), field: matte("#c7d1b5", { roughness: 1 }) },+ booths: { edge: matte("#9aa5b1", { roughness: 1 }), field: matte("#c3cbd3", { roughness: 1 }) },+ cafe: { edge: matte("#c9ad8c", { roughness: 0.7 }), field: matte("#eadfcd", { roughness: 0.7 }) },+};++/** A flat rounded rectangle in the XY plane, laid on the floor by its mesh's rotation. */+function roundedRect(w: number, d: number, r: number): Shape {+ const x = -w / 2, y = -d / 2;+ const shape = new Shape();+ shape.moveTo(x + r, y);+ shape.lineTo(x + w - r, y);+ shape.quadraticCurveTo(x + w, y, x + w, y + r);+ shape.lineTo(x + w, y + d - r);+ shape.quadraticCurveTo(x + w, y + d, x + w - r, y + d);+ shape.lineTo(x + r, y + d);+ shape.quadraticCurveTo(x, y + d, x, y + d - r);+ shape.lineTo(x, y + r);+ shape.quadraticCurveTo(x, y, x + r, y);+ return shape;+}++const centre = (r: Rect): [number, number] => [(r.minX + r.maxX) / 2, (r.minZ + r.maxZ) / 2];++/** One paved street: limestone at the stone's own scale, whatever the street's size. */+function Paving({ rect }: { rect: Rect }) {+ const w = rect.maxX - rect.minX, d = rect.maxZ - rect.minZ;+ const material = useMemo(() => limestone(w, d), [w, d]);+ useEffect(() => () => { material.map?.dispose(); material.dispose(); }, [material]);+ const [x, z] = centre(rect);+ return (+ <mesh position={[x, Y.paving, z]} rotation={[-Math.PI / 2, 0, 0]} material={material} receiveShadow>+ <planeGeometry args={[w, d]} />+ </mesh>+ );+}++/** The carpet of a commons: a darker rim round a lighter field. */+function Carpet({ zone, edge, field }: { zone: CampusZone; edge: MeshStandardMaterial; field: MeshStandardMaterial }) {+ const w = zone.maxX - zone.minX - 0.7, d = zone.maxZ - zone.minZ - 0.7;+ const shapes = useMemo(() => ({ edge: roundedRect(w, d, 0.6), field: roundedRect(w - 0.3, d - 0.3, 0.5) }), [w, d]);+ const [x, z] = centre(zone);+ return (+ <group>+ <mesh position={[x, Y.moss, z]} rotation={[-Math.PI / 2, 0, 0]} material={edge} receiveShadow>+ <shapeGeometry args={[shapes.edge, 6]} />+ </mesh>+ <mesh position={[x, Y.field, z]} rotation={[-Math.PI / 2, 0, 0]} material={field} receiveShadow>+ <shapeGeometry args={[shapes.field, 6]} />+ </mesh>+ </group>+ );+}++const PLOT_TEXT = { w: 1024, h: 320 } as const;+const plotTexts = new Map<string, MeshStandardMaterial>();+/** The plot's lettering, painted on the floor: what the place is for, and where a team is started. */+function plotText(title: string, hint: string): MeshStandardMaterial {+ const key = `${title}\n${hint}`;+ let material = plotTexts.get(key);+ if (!material) {+ const map = cachedCanvasTexture(`campus:plot:${key}`, PLOT_TEXT.w, PLOT_TEXT.h, (ctx, w, h) => {+ ctx.clearRect(0, 0, w, h);+ ctx.textAlign = "center";+ ctx.textBaseline = "middle";+ const fit = (text: string, px: number, weight: number, y: number, fill: string) => {+ let size = px;+ const font = (s: number) => `${weight} ${s}px Inter, system-ui, -apple-system, 'Segoe UI', sans-serif`;+ ctx.font = font(size);+ while (size > px * 0.5 && ctx.measureText(text).width > w - 48) { size -= 2; ctx.font = font(size); }+ ctx.fillStyle = fill;+ ctx.fillText(text, w / 2, y);+ };+ fit(title.toLocaleUpperCase(), 92, 700, 118, "#8a7350");+ fit(hint, 56, 500, 232, "#9a8a70");+ });+ material = new MeshStandardMaterial({ color: "#ffffff", map, transparent: true, alphaTest: 0.25, roughness: 0.9, visible: !!map });+ plotTexts.set(key, material);+ }+ return material;+}++/** Tape on the floor: the length of a dash, the gap to the next, a corner's legs and the tape's width. */+const TAPE = { dash: 0.55, gap: 0.4, corner: 0.9, w: 0.06 } as const;++/** The dashes of a taped outline w × d round the origin: solid corners, dashed runs between them. */+function tapeOutline(w: number, d: number): Placement[] {+ const out: Placement[] = [];+ const piece = (x: number, z: number, along: "x" | "z", length: number) => {+ out.push({ position: [x, Y.mark, z], scale: along === "x" ? [length, 0.003, TAPE.w] : [TAPE.w, 0.003, length] });+ };+ const run = (length: number, place: (offset: number, len: number) => void) => {+ const inner = length - TAPE.corner * 2;+ const count = Math.max(1, Math.floor((inner - TAPE.gap) / (TAPE.dash + TAPE.gap)));+ const dash = (inner - TAPE.gap * (count + 1)) / count;+ place(-length / 2 + TAPE.corner / 2, TAPE.corner);+ place(length / 2 - TAPE.corner / 2, TAPE.corner);+ for (let i = 0; i < count; i += 1) place(-inner / 2 + TAPE.gap + dash / 2 + i * (dash + TAPE.gap), dash);+ };+ for (const z of [-d / 2, d / 2]) run(w, (offset, len) => piece(offset, z, "x", len));+ for (const x of [-w / 2, w / 2]) run(d, (offset, len) => piece(x, offset, "z", len));+ return out;+}++/**+ * The free plot: the bare floor taped out like a site about to be moved into, with its lettering facing the+ * lobby. The stand where a team is started, the crates and the plant are the plan's own pieces.+ */+function Plot({ zone }: { zone: CampusZone }) {+ const t = useT();+ const w = zone.maxX - zone.minX - 0.5, d = zone.maxZ - zone.minZ - 0.5;+ const [x, z] = centre(zone);+ const tape = useMemo(() => tapeOutline(w, d), [w, d]);+ const textW = Math.min(w - 1.2, 5.6), textH = (textW * PLOT_TEXT.h) / PLOT_TEXT.w;+ return (+ <group position={[x, 0, z]}>+ <Instances geometry={GEO.box} material={GROUND.tape} items={tape} cast={false} />+ <mesh position={[0, Y.mark, -0.4]} rotation={[-Math.PI / 2, 0, 0]} material={plotText(t("society.office.plot_free"), t("society.office.plot_hint"))}>+ <planeGeometry args={[textW, textH]} />+ </mesh>+ </group>+ );+}++export function CampusGround({ layout }: { layout: OfficeLayout }) {+ const zones = layout.zones;+ const paved = useMemo(() => {+ const boulevard = zones?.find((z) => z.kind === "boulevard");+ const plaza = zones?.find((z) => z.kind === "plaza");+ if (!boulevard || !plaza) return null;+ return {+ // The boulevard's paving stops at the plaza on both sides: two surfaces never share a plane.+ streets: [{ ...boulevard, maxZ: plaza.minZ }, { ...boulevard, minZ: plaza.maxZ }].filter((r) => r.maxZ - r.minZ > 0.01),+ // The main boulevard's paving meets the stone band along both windows.+ plaza: { ...plaza, minX: layout.bounds.minX + WINDOW_BAND, maxX: layout.bounds.maxX - WINDOW_BAND },+ atrium: centre(plaza),+ };+ }, [zones, layout.bounds]);+ if (!zones || !paved) return null;+ const [ax, az] = paved.atrium;+ return (+ <group>+ {paved.streets.map((rect) => <Paving key={rect.minZ} rect={rect} />)}+ <Paving rect={paved.plaza} />+ {/* The atrium: a pale disc inside a bronze ring, the spawn point in its middle. */}+ <mesh position={[ax, Y.field, az]} rotation={[-Math.PI / 2, 0, 0]} material={GROUND.disc} receiveShadow>+ <circleGeometry args={[ATRIUM_R, 64]} />+ </mesh>+ <mesh position={[ax, Y.mark, az]} rotation={[-Math.PI / 2, 0, 0]} material={GROUND.inlay} receiveShadow>+ <ringGeometry args={[ATRIUM_R - 0.07, ATRIUM_R + 0.07, 64]} />+ </mesh>+ <mesh position={[ax, Y.mark, az]} rotation={[-Math.PI / 2, 0, 0]} material={GROUND.inlay} receiveShadow>+ <ringGeometry args={[2.05, 2.11, 48]} />+ </mesh>+ {/* The atrium's crown: a steel band hung from the ceiling line, its inner face the lamp. */}+ <mesh geometry={RING_BODY} material={GROUND.steel} position={[ax, ATRIUM_RING.y, az]} />+ <mesh geometry={RING_LAMP} material={GROUND.lamp} position={[ax, ATRIUM_RING.y, az]} />+ <group position={[ax, 0, az]}><Instances geometry={GEO.box} material={GROUND.steel} items={RING_RODS} cast={false} /></group>+ {zones.map((zone) => {+ if (zone.kind === "plot") return <Plot key={zone.id} zone={zone} />;+ const carpet = CARPETS[zone.kind];+ return carpet ? <Carpet key={zone.id} zone={zone} edge={carpet.edge} field={carpet.field} /> : null;+ })}+ </group>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/CampusScene.test.tsx b/jarvis/ui/web/frontend/src/components/society/office/CampusScene.test.tsxnew file mode 100644index 0000000000..b4d7223b95--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/CampusScene.test.tsx@@ -0,0 +1,282 @@+import { afterEach, describe, expect, it } from "vitest";+import { act, createRoot, extend, type ReconcilerRoot } from "@react-three/fiber";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import * as THREE from "three";+import { Box3, type InstancedMesh, type Mesh, type Object3D } from "three";+import { AgentsDepartment, AgentsSlab } from "./AgentsFloorLook";+import { AgentsFloorAmbience } from "./AgentsFloorAmbience";+import { BuildingShell, FACADE } from "./BuildingShell";+import { CampusGround } from "./CampusGround";+import { DeskDressing } from "./DeskDressing";+import { DeskInstances } from "./DeskInstances";+import { buildHallLayout } from "./hallFloorLayout";+import { buildOfficeLayout, type OfficeAgentInput, type OfficeLayout, type OfficeTeamInput } from "./officeLayout";+import { FurniturePiece, MeetingChairs } from "./OfficeProps";+import { StaticBatch } from "./StaticBatch";+import { ToyFigure } from "./ToyFigure";+import { loadProfile, playerLook } from "./playerProfile";+import { RoomFloors, RoomSign, RoomWalls } from "./OfficeRooms";++/** Just enough of a WebGLRenderer for R3F to mount a scene graph without a GPU. */+function fakeRenderer(canvas: HTMLCanvasElement) {+ const noop = () => undefined;+ return {+ domElement: canvas,+ render: noop, setSize: noop, setPixelRatio: noop, setAnimationLoop: noop, dispose: noop,+ getPixelRatio: () => 1,+ shadowMap: { enabled: false, type: 0, needsUpdate: false },+ xr: { enabled: false, isPresenting: false, addEventListener: noop, removeEventListener: noop, setAnimationLoop: noop },+ outputColorSpace: "srgb", toneMapping: 0, toneMappingExposure: 1,+ info: { render: {}, memory: {} },+ };+}++// <Canvas> registers the three namespace; a bare root must do it itself.+extend(THREE);++let root: ReconcilerRoot<HTMLCanvasElement> | null = null;++async function mount(element: JSX.Element): Promise<Object3D> {+ const canvas = document.createElement("canvas");+ const current = createRoot(canvas);+ root = current;+ current.configure({+ // Test double: R3F only needs the renderer's shape here, nothing is drawn.+ gl: fakeRenderer(canvas) as unknown as NonNullable<Parameters<typeof current.configure>[0]>["gl"],+ frameloop: "never",+ size: { width: 100, height: 100, top: 0, left: 0 },+ });+ let captured: Object3D | null = null;+ await act(async () => {+ current.render(+ <QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>+ <group ref={(g) => { captured = g; }}>{element}</group>+ </QueryClientProvider>,+ );+ });+ if (!captured) throw new Error("the element did not mount");+ return captured;+}++afterEach(() => {+ root?.unmount();+ root = null;+});++const staff = (count: number): OfficeAgentInput[] => Array.from({ length: count }, (_, i) => ({+ agentId: `a${i + 1}`, name: `Agent ${i + 1}`, tier: i === 0 ? "lead" : "specialist", providerLabel: "Codex", state: "idle", createdMs: i,+}));+const teamsOf = (count: number, size: number): OfficeTeamInput[] => Array.from({ length: count }, (_, t) => ({+ id: `team-${t}`, name: `Team ${t}`, createdMs: t, members: Array.from({ length: size }, (_, i) => `a${2 + t * size + i}`),+}));++/**+ * What a frame costs: every visible mesh is a draw call (however many instances it holds), every one that casts a+ * shadow a second one in the shadow pass, and its triangles are drawn in each.+ */+function cost(node: Object3D): { meshes: number; casters: number; calls: number; triangles: number } {+ let meshes = 0, casters = 0, triangles = 0;+ node.traverseVisible((child) => {+ const mesh = child as Mesh;+ if (!mesh.isMesh) return;+ const own = (mesh.geometry.index ? mesh.geometry.index.count : mesh.geometry.getAttribute("position").count) / 3+ * ((mesh as unknown as InstancedMesh).isInstancedMesh ? (mesh as unknown as InstancedMesh).count : 1);+ meshes += 1;+ triangles += own;+ if (mesh.castShadow) { casters += 1; triangles += own; }+ });+ return { meshes, casters, calls: meshes + casters, triangles: Math.round(triangles) };+}++const noClick = () => undefined;+const STATION_KINDS = new Set(["spawnTerminal", "spawnPad", "receptionDesk", "teamBoard", "dressingMirror", "coffeeBar", "elevator", "studioBoard", "teamStand"]);++/** The floor's static dressing, mounted the way the scene mounts it; the agents floor's furniture goes through the batch. */+function Dressing({ layout, batch = layout.variant === "agents" }: { layout: OfficeLayout; batch?: boolean }) {+ const desks = layout.departments.flatMap((d) => d.desks);+ const table = layout.furniture.find((f) => f.kind === "meetingTable");+ const signs = layout.rooms.map((room) => <RoomSign key={room.id} room={room} label={room.kind} />);+ const studios = layout.departments.map((dept) => <AgentsDepartment key={dept.id} dept={dept} />);+ return (+ <>+ <AgentsSlab layout={layout} onFloorClick={noClick} />+ <BuildingShell layout={layout} />+ <AgentsFloorAmbience layout={layout} />+ <CampusGround layout={layout} />+ <RoomFloors rooms={layout.rooms} campus />+ <RoomWalls walls={layout.walls} />+ {desks.length > 0 && <DeskInstances desks={desks} agents={new Map()} zones={new Map(layout.departments.flatMap((d) => d.desks.map((desk) => [desk.id, d.tint] as const)))} />}+ {desks.length > 0 && <DeskDressing desks={desks} departments={layout.departments} floor="agents" />}+ {batch+ ? <>+ <StaticBatch signature={layout.furniture.map((f) => f.id).join()}>+ {signs}{studios}+ {layout.furniture.filter((f) => !STATION_KINDS.has(f.kind)).map((item) => <FurniturePiece key={item.id} item={item} />)}+ {table && <MeetingChairs table={table} />}+ </StaticBatch>+ {layout.furniture.filter((f) => STATION_KINDS.has(f.kind)).map((item) => <FurniturePiece key={item.id} item={item} merged />)}+ </>+ : <>+ {signs}{studios}+ {layout.furniture.map((item) => <FurniturePiece key={item.id} item={item} />)}+ {table && <MeetingChairs table={table} />}+ </>}+ </>+ );+}++describe("campus scene", () => {+ it("mounts the agents floor's dressing for 5, 15 and 40 people, and the Level Hall's, within its budget", async () => {+ const floors: [string, OfficeLayout][] = [+ ["5", buildOfficeLayout(staff(5))],+ ["15", buildOfficeLayout(staff(15), { teams: teamsOf(3, 4) })],+ ["40", buildOfficeLayout(staff(40), { teams: teamsOf(8, 4) })],+ ["hall", buildHallLayout()],+ ];+ const costs: Record<string, ReturnType<typeof cost>> = {};+ for (const [name, layout] of floors) {+ const group = await mount(<Dressing layout={layout} />);+ costs[name] = cost(group);+ root?.unmount();+ root = null;+ }+ // The whole static floor — slab, building, planting, fittings, rooms, studios, desks — in a few hundred draw+ // calls, shadow pass included. (Without a GPU no texture exists; in a browser each textured material adds+ // a merged mesh of its own, a few dozen on this floor.)+ expect(costs["5"].calls).toBeLessThan(520);+ expect(costs["15"].calls).toBeLessThan(540);+ expect(costs["40"].calls).toBeLessThan(600);+ // Studios, desks, fittings and trees are merged or instanced: eight teams cost little more than none.+ expect(costs["40"].meshes - costs["5"].meshes).toBeLessThan(60);+ // Triangles, both passes: what grows with the roster is the desks and their chairs.+ expect(costs["5"].triangles).toBeLessThan(560_000);+ expect(costs["15"].triangles).toBeLessThan(700_000);+ expect(costs["40"].triangles).toBeLessThan(1_050_000);+ expect(costs.hall.calls).toBeLessThan(costs["5"].calls);+ });++ it("draws the furniture in a fraction of the calls it takes piece by piece", async () => {+ const layout = buildOfficeLayout(staff(15), { teams: teamsOf(3, 4) });+ const loose = cost(await mount(<Dressing layout={layout} batch={false} />));+ root?.unmount();+ const merged = cost(await mount(<Dressing layout={layout} />));+ expect(merged.calls).toBeLessThan(loose.calls / 3);+ // The same shapes: merging changes how they are drawn, not what is drawn.+ expect(merged.triangles).toBeLessThanOrEqual(loose.triangles);+ expect(merged.triangles).toBeGreaterThan(loose.triangles * 0.6);+ });++ it("keeps the ground flat and inside the slab, and a studio's wall inside its studio", async () => {+ const layout = buildOfficeLayout(staff(12), { teams: teamsOf(2, 3) });+ const ground = await mount(<CampusGround layout={layout} />);+ ground.updateMatrixWorld(true);+ const box = new Box3().setFromObject(ground);+ // Everything is either flat on the floor or the atrium's ring of light (band, lamp and rods) above every head.+ let overhead = 0;+ ground.traverse((child) => {+ if (!(child as Mesh).isMesh) return;+ const own = new Box3().setFromObject(child);+ if (own.min.y > 2.6) { overhead += 1; expect(own.max.y).toBeLessThanOrEqual(3.4 + 1e-6); return; }+ expect(own.min.y).toBeGreaterThan(0.001);+ expect(own.max.y).toBeLessThan(0.02);+ });+ expect(overhead).toBe(3);+ expect(box.min.x).toBeGreaterThanOrEqual(layout.bounds.minX);+ expect(box.max.x).toBeLessThanOrEqual(layout.bounds.maxX);+ expect(box.min.z).toBeGreaterThanOrEqual(layout.bounds.minZ);+ expect(box.max.z).toBeLessThanOrEqual(layout.bounds.maxZ);+ root?.unmount();+ for (const dept of layout.departments) {+ const studio = await mount(<AgentsDepartment dept={dept} />);+ studio.updateMatrixWorld(true);+ const own = new Box3().setFromObject(studio);+ expect(own.min.x, dept.id).toBeGreaterThanOrEqual(dept.minX - 0.01);+ expect(own.max.x, dept.id).toBeLessThanOrEqual(dept.maxX + 0.01);+ expect(own.min.z, dept.id).toBeGreaterThanOrEqual(dept.minZ - 0.01);+ expect(own.max.z, dept.id).toBeLessThanOrEqual(dept.maxZ + 0.01);+ root?.unmount();+ }+ root = null;+ });++ it("builds the building's edges on the slab's edge: a window wall and a balustrade per side, the far sides' walls shown", async () => {+ const layout = buildOfficeLayout(staff(5));+ const shell = await mount(<BuildingShell layout={layout} />);+ shell.updateMatrixWorld(true);+ const { minX, maxX, minZ, maxZ } = layout.bounds;+ // Everything the person could bump into stays out of the walkable floor: nothing of a wall or a rail lies inside it below head height.+ const inside = (child: Object3D) => {+ const box = new Box3().setFromObject(child);+ return box.min.x > layout.floor.minX && box.max.x < layout.floor.maxX && box.min.z > layout.floor.minZ && box.max.z < layout.floor.maxZ && box.min.y < 2;+ };+ const visible: number[] = [];+ let walls = 0;+ shell.traverse((child) => {+ const box = new Box3().setFromObject(child);+ // A window wall's group: as tall as the façade, on the slab, as long as one of its sides.+ if (child.type !== "Group" || child.children.length !== 5) return;+ if (Math.abs(box.max.y - (FACADE.h + 0.1)) > 0.01) return;+ walls += 1;+ expect(inside(child)).toBe(false);+ expect(box.min.x).toBeGreaterThanOrEqual(minX - 0.01);+ expect(box.max.x).toBeLessThanOrEqual(maxX + 0.01);+ expect(box.min.z).toBeGreaterThanOrEqual(minZ - 0.01);+ expect(box.max.z).toBeLessThanOrEqual(maxZ + 0.01);+ if (child.parent?.visible) visible.push(Math.round((box.min.x + box.max.x) / 2) + Math.round((box.min.z + box.max.z) / 2) * 1000);+ });+ expect(walls).toBe(4);+ // The home view looks from the south-east: the north and the west wall stand, the other two sides show the balustrade.+ expect(visible).toHaveLength(2);+ });++ it("tags every room wall run for the camera's cutaway", async () => {+ const layout = buildOfficeLayout(staff(5));+ const group = await mount(<RoomWalls walls={layout.walls} />);+ const tagged: unknown[] = [];+ group.traverse((child) => { if (child.userData.officeWall) tagged.push(child.userData.officeWall); });+ expect(tagged).toHaveLength(layout.walls.length);+ expect(new Set(tagged).size).toBe(layout.walls.length);+ });+});++describe("a figure", () => {+ const still = { current: { mode: "idle" as const, speed: 0 } };++ it("is a few dozen draw calls: its rigid head, torso and arm halves are merged, only the legs are parts of their own", async () => {+ const figure = cost(await mount(<ToyFigure look={playerLook(loadProfile())} drive={still} paused />));+ expect(figure.meshes).toBeLessThanOrEqual(22);+ // What still casts: head, torso, pelvis, each half of an arm and each segment of a leg.+ expect(figure.casters).toBeLessThanOrEqual(14);+ // Both passes together.+ expect(figure.triangles).toBeLessThan(40_000);+ });++ it("keeps its shape when it is merged: the same triangles in the same place, for a bare arm, a sleeve and a held thing", async () => {+ const base = playerLook(loadProfile());+ const looks = [base, { ...base, outfit: "tee" as const }, { ...base, outfit: "suit" as const }];+ for (const look of looks) {+ const group = await mount(<ToyFigure look={look} drive={still} paused holding={<mesh><boxGeometry args={[0.05, 0.05, 0.05]} /></mesh>} />);+ group.updateMatrixWorld(true);+ const merged = { triangles: 0, box: new Box3() }, parts = { triangles: 0, box: new Box3() };+ let loose = 0;+ group.traverse((child) => {+ const mesh = child as Mesh;+ if (!mesh.isMesh) return;+ if (!mesh.userData.staticBatched) { loose += 1; return; }+ const into = mesh.visible ? merged : parts;+ into.triangles += (mesh.geometry.index ? mesh.geometry.index.count : mesh.geometry.getAttribute("position").count) / 3;+ // Measured vertex by vertex: a turned part's own box would overstate it.+ into.box.union(new Box3().setFromObject(mesh, true));+ });+ expect(merged.triangles, look.outfit).toBe(parts.triangles);+ for (const axis of ["x", "y", "z"] as const) {+ expect(merged.box.min[axis], look.outfit).toBeCloseTo(parts.box.min[axis], 5);+ expect(merged.box.max[axis], look.outfit).toBeCloseTo(parts.box.max[axis], 5);+ }+ // Outside every batch: the pelvis, three segments of each leg with a sole, and what the hand holds.+ expect(loose, look.outfit).toBeLessThanOrEqual(12);+ root?.unmount();+ root = null;+ }+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/CheckpointMarker.tsx b/jarvis/ui/web/frontend/src/components/society/office/CheckpointMarker.tsxdeleted file mode 100644index 0a4f51b30b..0000000000--- a/jarvis/ui/web/frontend/src/components/society/office/CheckpointMarker.tsx+++ /dev/null@@ -1,246 +0,0 @@-/**- * A checkpoint the person walks to (or clicks from afar): a gold ring on the- * floor, a floating hexagon token with a canvas-drawn icon, and a label pill.- * Icons are simple SVG path strings, drawn on the token's canvas and inlined- * in the pill — no emoji, no icon fonts, nothing fetched.- */-import { useEffect, useMemo, useRef } from "react";-import { Html } from "@react-three/drei";-import { useFrame, type ThreeEvent } from "@react-three/fiber";-import {- CircleGeometry, CylinderGeometry, DoubleSide, MeshStandardMaterial, Vector3,- type Group, type Mesh, type MeshBasicMaterial,-} from "three";-import { useT } from "@/i18n";-import { plateScale } from "./OfficeAgents";-import { cachedCanvasTexture } from "./canvasMaterials";-import type { Checkpoint, CheckpointKind } from "./officeLayout";-import { CHECKPOINT_GOLD } from "./officePalette";--export type CheckpointIcon = "spawn" | "plus" | "list" | "team" | "shirt" | "star" | "coffee" | "updown" | "target" | "sparkle" | "trophy";--/** The Upgrade Studio: a large four-point sparkle and a small one. */-export const SPARKLE_PATH = "M10 3l1.6 5.4L17 10l-5.4 1.6L10 17l-1.6-5.4L3 10l5.4-1.6zM18 14l.8 2.2L21 17l-2.2.8L18 20l-.8-2.2L15 17l2.2-.8z";-/** The level guide: a trophy cup on its stand. */-export const TROPHY_PATH = "M7 4h10v5a5 5 0 0 1-10 0V4zM7 6H4.5a2.5 2.5 0 0 0 2.6 3.6M17 6h2.5a2.5 2.5 0 0 1-2.6 3.6M12 14v3M8 20h8M9.5 17h5";--/** Stroke-only icons in a 24 × 24 box (round caps and joins). */-export const CHECKPOINT_ICON_PATHS: Record<CheckpointIcon, string> = {- // The spawn point: a plus between two arcs, a portal opening.- spawn: "M12 8.5v7M8.5 12h7M5.2 7.5A8 8 0 0 1 18.8 7.5M18.8 16.5A8 8 0 0 1 5.2 16.5",- plus: "M12 5v14M5 12h14",- list: "M9 6h11M9 12h11M9 18h11M4.5 6h.01M4.5 12h.01M4.5 18h.01",- team: "M9 11a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM3 20c0-3.3 2.7-5.5 6-5.5s6 2.2 6 5.5M16.5 11a2.5 2.5 0 1 0 0-5M18 14.5c2 .6 3.5 2.4 3.5 5",- shirt: "M8 3L3 6l2 4 2.5-1v12h9V9l2.5 1 2-4-5-3c-.5 1.5-2 2.5-4 2.5S8.5 4.5 8 3z",- star: "M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z",- coffee: "M4 9h12v5a5 5 0 0 1-5 5H9a5 5 0 0 1-5-5V9zM16 10h1.5a2.5 2.5 0 0 1 0 5H16M8 3.5c0 1 1 1 1 2M12 3.5c0 1 1 1 1 2",- // The elevator: an up arrow beside a down arrow.- updown: "M8 20V4M4 8l4-4 4 4M16 4v16M12 16l4 4 4-4",- // Mission Control: a target with crosshairs.- target: "M12 3a9 9 0 1 1 0 18a9 9 0 1 1 0-18zM12 8a4 4 0 1 1 0 8a4 4 0 1 1 0-8zM12 1v4M12 19v4M1 12h4M19 12h4",- sparkle: SPARKLE_PATH,- trophy: TROPHY_PATH,-};--/** The icon each checkpoint wears, on its floor token and in the reception's list of places. */-export const CHECKPOINT_ICON: Record<CheckpointKind, CheckpointIcon> = {- spawn: "spawn", launch: "spawn", create: "plus", manage: "list", team: "team", wardrobe: "shirt", lead: "star", break: "coffee", elevator: "updown", mission: "target",- studio: "sparkle", levels: "trophy",-};--const TOKEN_RADIUS = 0.36;-const TOKEN_DEPTH = 0.1;-/** Height of the token centre above the floor. */-export const TOKEN_Y = 1.7;-const LABEL_Y = TOKEN_Y - 0.62;-const RING_Y = 0.025;--// A flat-topped hexagon prism whose faces point along ±z; the face discs match its corners.-const prismGeometry = new CylinderGeometry(TOKEN_RADIUS, TOKEN_RADIUS, TOKEN_DEPTH, 6, 1, false, Math.PI / 2);-prismGeometry.rotateX(Math.PI / 2);-const faceGeometry = new CircleGeometry(TOKEN_RADIUS * 0.9, 6);--const rimMaterial = new MeshStandardMaterial({- color: CHECKPOINT_GOLD.rim, roughness: 0.4, metalness: 0.2, emissive: CHECKPOINT_GOLD.ring, emissiveIntensity: 0.3,-});--const faceMaterials = new Map<CheckpointIcon, MeshStandardMaterial>();-function faceMaterial(icon: CheckpointIcon): MeshStandardMaterial {- let material = faceMaterials.get(icon);- if (!material) {- const map = cachedCanvasTexture(`checkpoint:${icon}`, 256, 256, (ctx, w, h) => {- const grad = ctx.createLinearGradient(0, 0, 0, h);- grad.addColorStop(0, CHECKPOINT_GOLD.face);- grad.addColorStop(1, CHECKPOINT_GOLD.faceDeep);- ctx.fillStyle = grad;- ctx.fillRect(0, 0, w, h);- // Inner hexagon outline (flat top, matching the geometry).- ctx.strokeStyle = "rgba(255,255,255,0.55)";- ctx.lineWidth = 6;- ctx.beginPath();- for (let i = 0; i < 6; i += 1) {- const a = (i * Math.PI) / 3;- const x = w / 2 + Math.cos(a) * w * 0.4, y = h / 2 + Math.sin(a) * h * 0.4;- if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);- }- ctx.closePath();- ctx.stroke();- if (typeof Path2D === "undefined") return;- const path = new Path2D(CHECKPOINT_ICON_PATHS[icon]);- const scale = 5.2;- ctx.save();- ctx.translate(w / 2 - 12 * scale, h / 2 - 12 * scale);- ctx.scale(scale, scale);- ctx.lineCap = "round";- ctx.lineJoin = "round";- // A soft dark under-stroke keeps the white icon readable on gold.- ctx.translate(0.25, 0.3);- ctx.strokeStyle = "rgba(90,55,0,0.45)";- ctx.lineWidth = 3.2;- ctx.stroke(path);- ctx.translate(-0.25, -0.3);- ctx.strokeStyle = CHECKPOINT_GOLD.icon;- ctx.lineWidth = 2.3;- ctx.stroke(path);- ctx.restore();- });- material = new MeshStandardMaterial({- color: map ? "#ffffff" : CHECKPOINT_GOLD.face, map, roughness: 0.45,- emissive: "#ffffff", emissiveMap: map, emissiveIntensity: map ? 0.5 : 0,- });- faceMaterials.set(icon, material);- }- return material;-}--export function IconSvg({ icon }: { icon: CheckpointIcon }) {- return (- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2.4} strokeLinecap="round" strokeLinejoin="round" aria-hidden>- <path d={CHECKPOINT_ICON_PATHS[icon]} />- </svg>- );-}--export function CheckpointMarker({ checkpoint, label, icon, active, animate, onActivate }: {- checkpoint: Checkpoint;- label: string;- icon: CheckpointIcon;- active: boolean;- animate: boolean;- onActivate: () => void;-}) {- const token = useRef<Group>(null);- const ring = useRef<Mesh>(null);- const pulse = useRef<Mesh>(null);- const anchor = useRef<Group>(null);- const pill = useRef<HTMLButtonElement>(null);- const lastScale = useRef(0);- const hovered = useRef(false);- const world = useMemo(() => new Vector3(), []);- // A per-checkpoint phase so the tokens do not bob in lockstep.- const phase = useMemo(() => [...checkpoint.id].reduce((sum, ch) => sum + ch.charCodeAt(0), 0) % 7, [checkpoint.id]);- const t = useT();- const hint = t(`society.office.cp_${checkpoint.id}_hint`);- // A checkpoint over a tall prop (the holo deck) floats its token above it.- const tokenY = checkpoint.tokenY ?? TOKEN_Y;- const face = faceMaterial(icon);- const ringOpacity = active ? 0.95 : 0.6;- const fillOpacity = active ? 0.16 : 0.07;-- useFrame(({ clock, camera }, delta) => {- 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 = tokenY + 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 = tokenY;- token.current.rotation.y = toCamera;- }- }- if (ring.current) {- const material = ring.current.material as MeshBasicMaterial;- 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 = (time % 1.6) / 1.6;- pulse.current.visible = true;- pulse.current.scale.setScalar(1 + k * 0.35);- material.opacity = 0.6 * (1 - k);- } else {- pulse.current.visible = false;- }- }- if (anchor.current && pill.current) {- const scale = plateScale(camera.position.distanceTo(anchor.current.getWorldPosition(world)));- if (Math.abs(scale - lastScale.current) >= 0.02) {- lastScale.current = scale;- pill.current.style.transform = `scale(${scale.toFixed(2)})`;- }- }- });-- // Never leave a pointer cursor behind when the marker unmounts under the mouse.- useEffect(() => () => { if (hovered.current) document.body.style.cursor = ""; }, []);-- const activate = (event: ThreeEvent<MouseEvent>) => { event.stopPropagation(); onActivate(); };- const over = (event: ThreeEvent<PointerEvent>) => {- event.stopPropagation();- hovered.current = true;- document.body.style.cursor = "pointer";- };- const out = () => {- hovered.current = false;- document.body.style.cursor = "";- };-- return (- <group position={[checkpoint.x, 0, checkpoint.z]} name={`checkpoint:${checkpoint.id}`}>- {/* Floor ring, a faint fill and (active + animated) an expanding pulse. */}- <mesh ref={ring} rotation={[-Math.PI / 2, 0, 0]} position={[0, RING_Y, 0]}>- <ringGeometry args={[Math.max(0.05, checkpoint.radius - 0.09), checkpoint.radius, 64]} />- <meshBasicMaterial color={CHECKPOINT_GOLD.ring} transparent opacity={ringOpacity} side={DoubleSide} depthWrite={false} toneMapped={false} />- </mesh>- <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, RING_Y - 0.002, 0]}>- <circleGeometry args={[Math.max(0.05, checkpoint.radius - 0.09), 64]} />- <meshBasicMaterial color={CHECKPOINT_GOLD.ring} transparent opacity={fillOpacity} depthWrite={false} toneMapped={false} />- </mesh>- <mesh ref={pulse} rotation={[-Math.PI / 2, 0, 0]} position={[0, RING_Y + 0.002, 0]} visible={false}>- <ringGeometry args={[Math.max(0.05, checkpoint.radius - 0.04), checkpoint.radius, 64]} />- <meshBasicMaterial color={CHECKPOINT_GOLD.ring} transparent opacity={0} side={DoubleSide} depthWrite={false} toneMapped={false} />- </mesh>-- {/* Floating hexagon token with the icon on both faces. */}- <group ref={token} position={[0, tokenY, 0]} rotation={[0, Math.PI / 4, 0]} scale={active ? 1.15 : 1}- onClick={activate} onPointerOver={over} onPointerOut={out}>- <mesh geometry={prismGeometry} material={rimMaterial} castShadow />- <mesh geometry={faceGeometry} material={face} position={[0, 0, TOKEN_DEPTH / 2 + 0.002]} />- <mesh geometry={faceGeometry} material={face} position={[0, 0, -TOKEN_DEPTH / 2 - 0.002]} rotation={[0, Math.PI, 0]} />- </group>-- <group ref={anchor} position={[0, tokenY - TOKEN_Y + 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-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>- </group>- );-}diff --git a/jarvis/ui/web/frontend/src/components/society/office/DeskDressing.tsx b/jarvis/ui/web/frontend/src/components/society/office/DeskDressing.tsxindex 55f4fca39a..aaa451f05a 100644--- a/jarvis/ui/web/frontend/src/components/society/office/DeskDressing.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/DeskDressing.tsx@@ -18,7 +18,8 @@ import {import { RoundedBoxGeometry } from "three-stdlib";import { cachedCanvasTexture } from "./canvasMaterials";import {- dressDesk, dressOfficeDesk, kitPlacements, oakPlanterPlacements, officeKitPlacements, planterPlacements, type DressingPart, type Placement,+ dressDesk, dressOfficeDesk, kitPlacements, leadMarkPlacements, oakPlanterPlacements, officeKitPlacements, planterPlacements,+ type DressingPart, type Placement,} from "./deskKit";import { GEO, MAT, matte } from "./OfficeFurniture";import { benchPlanters, type Department, type DeskSlot, type OfficeVariant } from "./officeLayout";@@ -157,34 +158,38 @@ const blackMetal = matte("#23262c", { roughness: 0.55, metalness: 0.3 });const brass = matte("#b8914f", { roughness: 0.32, metalness: 0.75 });const graphite = matte("#2a2c31", { roughness: 0.4, metalness: 0.3 });+/**+ * `cast`: only what is large enough for its shadow to show at the floor's scale (lamp shades, planters and their+ * foliage). Every casting part is drawn a second time into the shadow map; a cup's shadow is not worth that.+ */interface PartSpec { geometry: BufferGeometry; material: Material; tinted: boolean; cast: boolean }const PARTS: Record<DressingPart, PartSpec> = {- mat: { geometry: new RoundedBoxGeometry(0.82, 0.004, 0.34, 2, 0.002), material: tintedMatte, tinted: true, cast: false },- standPlate: { geometry: GEO.box, material: aluminium, tinted: false, cast: true },+ mat: { geometry: new RoundedBoxGeometry(0.82, 0.004, 0.34, 1, 0.002), material: tintedMatte, tinted: true, cast: false },+ standPlate: { geometry: GEO.box, material: aluminium, tinted: false, cast: false },standLeg: { geometry: GEO.box, material: aluminium, tinted: false, cast: false },- laptopBase: { geometry: new RoundedBoxGeometry(0.3, 0.012, 0.21, 2, 0.005), material: aluminium, tinted: false, cast: true },- laptopLid: { geometry: new RoundedBoxGeometry(0.3, 0.2, 0.007, 2, 0.003), material: aluminium, tinted: false, cast: true },+ laptopBase: { geometry: new RoundedBoxGeometry(0.3, 0.012, 0.21, 1, 0.005), material: aluminium, tinted: false, cast: false },+ laptopLid: { geometry: new RoundedBoxGeometry(0.3, 0.2, 0.007, 1, 0.003), material: aluminium, tinted: false, cast: false },laptopScreen: { geometry: new PlaneGeometry(0.28, 0.18), material: laptopScreen, tinted: false, cast: false },- lampBase: { geometry: GEO.cyl, material: tintedGloss, tinted: true, cast: true },- lampArm: { geometry: GEO.cyl, material: tintedGloss, tinted: true, cast: true },+ lampBase: { geometry: GEO.cyl, material: tintedGloss, tinted: true, cast: false },+ lampArm: { geometry: GEO.cyl, material: tintedGloss, tinted: true, cast: false },lampShade: { geometry: new CylinderGeometry(0.45, 1, 1, 16), material: tintedGloss, tinted: true, cast: true },lampBulb: {geometry: GEO.cyl, tinted: false, cast: false,material: new MeshStandardMaterial({ color: "#fff2d6", emissive: "#ffd89a", emissiveIntensity: 1.6, toneMapped: false }),},- pot: { geometry: GEO.potCyl, material: tintedGloss, tinted: true, cast: true },+ pot: { geometry: GEO.potCyl, material: tintedGloss, tinted: true, cast: false },soil: { geometry: GEO.cyl, material: MAT.soil, tinted: false, cast: false },- succulent: { geometry: new IcosahedronGeometry(1, 0), material: tintedLeaf, tinted: true, cast: true },- book: { geometry: GEO.box, material: tintedMatte, tinted: true, cast: true },- bottle: { geometry: GEO.cyl, material: tintedGloss, tinted: true, cast: true },+ succulent: { geometry: new IcosahedronGeometry(1, 0), material: tintedLeaf, tinted: true, cast: false },+ book: { geometry: GEO.box, material: tintedMatte, tinted: true, cast: false },+ bottle: { geometry: GEO.cyl, material: tintedGloss, tinted: true, cast: false },bottleCap: { geometry: GEO.cyl, material: blackMetal, tinted: false, cast: false },- notebook: { geometry: GEO.box, material: tintedMatte, tinted: true, cast: true },+ notebook: { geometry: GEO.box, material: tintedMatte, tinted: true, cast: false },notebookBand: { geometry: GEO.box, material: blackMetal, tinted: false, cast: false },pen: { geometry: GEO.cyl, material: blackMetal, tinted: false, cast: false },hook: { geometry: GEO.box, material: blackMetal, tinted: false, cast: false },- headband: { geometry: new TorusGeometry(0.08, 0.01, 8, 24, Math.PI), material: tintedMatte, tinted: true, cast: true },- earCup: { geometry: GEO.cyl, material: tintedMatte, tinted: true, cast: true },+ headband: { geometry: new TorusGeometry(0.08, 0.01, 8, 24, Math.PI), material: tintedMatte, tinted: true, cast: false },+ earCup: { geometry: GEO.cyl, material: tintedMatte, tinted: true, cast: false },note: { geometry: new PlaneGeometry(0.065, 0.065), material: tintedMatte, tinted: true, cast: false },tray: { geometry: GEO.box, material: blackMetal, tinted: false, cast: false },snake: { geometry: new CylinderGeometry(1, 1, 1, 10), material: blackMetal, tinted: false, cast: false },@@ -194,32 +199,33 @@ const PARTS: Record<DressingPart, PartSpec> = {planterRail: { geometry: GEO.box, material: MAT.wood, tinted: false, cast: false },planterSoil: { geometry: GEO.box, material: MAT.soil, tinted: false, cast: false },foliage: { geometry: GEO.blob, material: tintedLeaf, tinted: true, cast: true },- blade: { geometry: new CylinderGeometry(0.15, 1, 1, 4), material: tintedLeaf, tinted: true, cast: true },- letterTray: { geometry: GEO.box, material: tintedGloss, tinted: true, cast: true },+ blade: { geometry: new CylinderGeometry(0.15, 1, 1, 4), material: tintedLeaf, tinted: true, cast: false },+ letterTray: { geometry: GEO.box, material: tintedGloss, tinted: true, cast: false },trayPost: { geometry: GEO.cyl, material: brass, tinted: false, cast: false },- paper: { geometry: GEO.box, material: tintedMatte, tinted: true, cast: true },+ paper: { geometry: GEO.box, material: tintedMatte, tinted: true, cast: false },page: { geometry: new PlaneGeometry(1, 1), material: faceMaterial("desk:page", 64, 88, drawPage, "#fbfaf6"), tinted: false, cast: false },- folder: { geometry: GEO.box, material: tintedMatte, tinted: true, cast: true },- tabletBody: { geometry: new RoundedBoxGeometry(0.24, 0.17, 0.008, 2, 0.004), material: graphite, tinted: false, cast: true },+ folder: { geometry: GEO.box, material: tintedMatte, tinted: true, cast: false },+ tabletBody: { geometry: new RoundedBoxGeometry(0.24, 0.17, 0.008, 1, 0.004), material: graphite, tinted: false, cast: false },tabletScreen: {geometry: new PlaneGeometry(0.224, 0.154), material: faceMaterial("desk:calendar", 128, 88, drawCalendar, "#e9e5dc", 0.45), tinted: false, cast: false,},- tabletStand: { geometry: GEO.box, material: brass, tinted: false, cast: true },- phoneBody: { geometry: new RoundedBoxGeometry(0.072, 0.15, 0.008, 2, 0.004), material: graphite, tinted: false, cast: true },+ tabletStand: { geometry: GEO.box, material: brass, tinted: false, cast: false },+ phoneBody: { geometry: new RoundedBoxGeometry(0.072, 0.15, 0.008, 1, 0.004), material: graphite, tinted: false, cast: false },phoneScreen: {geometry: new PlaneGeometry(0.064, 0.138), material: faceMaterial("desk:messages", 64, 128, drawMessages, "#1b1d22", 0.5), tinted: false, cast: false,},- dock: { geometry: GEO.box, material: aluminium, tinted: false, cast: true },- penCup: { geometry: GEO.cyl, material: tintedGloss, tinted: true, cast: true },+ dock: { geometry: GEO.box, material: aluminium, tinted: false, cast: false },+ penCup: { geometry: GEO.cyl, material: tintedGloss, tinted: true, cast: false },pencil: { geometry: GEO.cyl, material: tintedGloss, tinted: true, cast: false },- frame: { geometry: GEO.box, material: tintedGloss, tinted: true, cast: true },+ frame: { geometry: GEO.box, material: tintedGloss, tinted: true, cast: false },photo: { geometry: new PlaneGeometry(1, 1), material: faceMaterial("desk:photo", 64, 84, drawPhoto, "#c9b99c"), tinted: true, cast: false },- cup: { geometry: new CylinderGeometry(1, 0.78, 1, 16), material: tintedMatte, tinted: true, cast: true },+ cup: { geometry: new CylinderGeometry(1, 0.78, 1, 16), material: tintedMatte, tinted: true, cast: false },cupLid: { geometry: GEO.cyl, material: tintedGloss, tinted: true, cast: false },cupSleeve: { geometry: new CylinderGeometry(1, 0.9, 1, 16), material: matte("#b98b5e", { roughness: 0.9 }), tinted: false, cast: false },oakPlanter: { geometry: GEO.box, material: matte("#d8bd91", { roughness: 0.7 }), tinted: false, cast: true },- oakSlat: { geometry: GEO.box, material: matte("#caa574", { roughness: 0.65 }), tinted: false, cast: true },+ oakSlat: { geometry: GEO.box, material: matte("#caa574", { roughness: 0.65 }), tinted: false, cast: false },brassTrim: { geometry: GEO.box, material: brass, tinted: false, cast: false },+ felt: { geometry: GEO.box, material: tintedMatte, tinted: true, cast: false },};const PART_KEYS = Object.keys(PARTS) as DressingPart[];@@ -230,7 +236,8 @@ const quat = new Quaternion();const pos = new Vector3();const scl = new Vector3();-function localMatrix(part: Placement): Matrix4 {+/** A placement's own transform: where it stands in its space (a desk's, or the world's), turned and sized. */+export function placementMatrix(part: Placement): Matrix4 {const [rx, ry, rz] = part.r ?? [0, 0, 0];euler.set(rx, ry, rz, "YXZ");return new Matrix4().compose(pos.set(...part.p), quat.setFromEuler(euler), scl.set(...(part.s ?? [1, 1, 1])));@@ -240,13 +247,17 @@ function localMatrix(part: Placement): Matrix4 {* Every instance of every part on the floor: desk kits (desk space → world) and planters (already world space).* The coding floor carries the developer's kit and walnut planters, the agents floor the office kit and oak planters.*/+const NO_SIGNS: ReadonlyMap<string, string> = new Map();+export function buildDressing(desks: readonly DeskSlot[], departments: readonly Department[], floor: OfficeVariant = "coding",+ /** Desk id -> the team's colour, for the desks a team lead sits at: each is marked as the lead's place. */+ leadSigns: ReadonlyMap<string, string> = NO_SIGNS,): Map<DressingPart, Batch> {const batches = new Map<DressingPart, Batch>(PART_KEYS.map((k) => [k, { matrices: [], colours: [] }]));const add = (part: Placement, world?: Matrix4) => {const batch = batches.get(part.part)!;- const local = localMatrix(part);+ const local = placementMatrix(part);batch.matrices.push(world ? world.clone().multiply(local) : local);batch.colours.push(new Color(part.c ?? "#ffffff"));};@@ -254,8 +265,12 @@ export function buildDressing(const turn = desk.facing === "north" ? 0 : Math.PI;const world = new Matrix4().makeRotationY(turn).setPosition(desk.x, 0, desk.z);const occupied = desk.agentId !== null;- const kit = floor === "coding" ? kitPlacements(dressDesk(desk.id, occupied)) : officeKitPlacements(dressOfficeDesk(desk.id, occupied));+ const lead = leadSigns.get(desk.id);+ // The lead's name stand takes the front right corner, where a phone would lie.+ const kit = floor === "coding" ? kitPlacements(dressDesk(desk.id, occupied))+ : officeKitPlacements({ ...dressOfficeDesk(desk.id, occupied), ...(lead === undefined ? {} : { phone: false }) });for (const part of kit) add(part, world);+ if (lead !== undefined) for (const part of leadMarkPlacements(lead)) add(part, world);}const planter = floor === "coding" ? planterPlacements : oakPlanterPlacements;for (const dept of departments) {@@ -282,10 +297,12 @@ function PartInstances({ spec, batch }: { spec: PartSpec; batch: Batch }) {}/** The dressing of every bench desk on the floor and the planters of every department's benches. */-export function DeskDressing({ desks, departments, floor = "coding" }: {+export function DeskDressing({ desks, departments, floor = "coding", leadSigns = NO_SIGNS }: {desks: readonly DeskSlot[]; departments: readonly Department[]; floor?: OfficeVariant;+ /** Desk id -> the team's colour, for the desks a team lead sits at. */+ leadSigns?: ReadonlyMap<string, string>;}) {- const batches = useMemo(() => buildDressing(desks, departments, floor), [desks, departments, floor]);+ const batches = useMemo(() => buildDressing(desks, departments, floor, leadSigns), [desks, departments, floor, leadSigns]);return (<group>{PART_KEYS.map((key) => {diff --git a/jarvis/ui/web/frontend/src/components/society/office/DeskInstances.tsx b/jarvis/ui/web/frontend/src/components/society/office/DeskInstances.tsxindex c41feef9ba..2e9333037f 100644--- a/jarvis/ui/web/frontend/src/components/society/office/DeskInstances.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/DeskInstances.tsx@@ -49,7 +49,7 @@ interface Part {}const CHAIR_Z = 0.62;-const rounded = (w: number, h: number, d: number, r: number) => new RoundedBoxGeometry(w, h, d, 2, r);+const rounded = (w: number, h: number, d: number, r: number) => new RoundedBoxGeometry(w, h, d, 1, r);/** The task chair's finishes as desk part roles: the frame and fabric follow a desk tone, metal and mesh stay. */const CHAIR_ROLE: Record<ChairFinish, PartRole> = { frame: "chair", fabric: "seat", metal: "chrome", mesh: "mesh" };diff --git a/jarvis/ui/web/frontend/src/components/society/office/ElevatorCallButton.tsx b/jarvis/ui/web/frontend/src/components/society/office/ElevatorCallButton.tsxindex 93edc66f3b..346ef0f31a 100644--- a/jarvis/ui/web/frontend/src/components/society/office/ElevatorCallButton.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/ElevatorCallButton.tsx@@ -5,14 +5,12 @@* the elevator) opens the floor picker; picking a floor lights it, then the* doors close. The ground floor shows an up arrow, the top floor a down* arrow, the floors between both. While the person stands at the elevator it- * breathes softly and a pill above it invites a press; clicking it from afar+ * breathes softly (the HUD's prompt names the press); clicking it from afar* only walks the character over (see `elevatorCall.ts`).*/import { useEffect, useMemo, useRef } from "react";-import { Html } from "@react-three/drei";import { useFrame, type ThreeEvent } from "@react-three/fiber";import { MeshStandardMaterial } from "three";-import { useT } from "@/i18n";import { cachedCanvasTexture } from "./canvasMaterials";import { callButtonPose } from "./elevatorCall";import type { Furniture } from "./officeLayout";@@ -52,19 +50,16 @@ function arrowTexture(direction: ArrowDirection) {});}-export function ElevatorCallButton({ shaft, floor, near, hint, lit, animate, onPress }: {+export function ElevatorCallButton({ shaft, floor, near, lit, animate, onPress }: {shaft: Furniture;floor: OfficeFloor;/** The person stands at the elevator: the button invites a press. */near: boolean;- /** Show the pill over the button (not while the floor picker it opens is on screen). */- hint: boolean;/** Pressed: glowing until the ride starts. */lit: boolean;animate: boolean;onPress: () => void;}) {- const t = useT();const pose = callButtonPose(shaft);const direction = callDirection(floor);const button = useMemo(() => new MeshStandardMaterial({ color: IDLE, roughness: 0.35, metalness: 0.3, emissive: LIT, emissiveIntensity: 0 }), []);@@ -108,14 +103,6 @@ export function ElevatorCallButton({ shaft, floor, near, hint, lit, animate, onP<mesh position={[0, 0, 0.0231]} material={arrow} raycast={() => null}><planeGeometry args={[BUTTON_RADIUS * 1.6, BUTTON_RADIUS * 1.6]} /></mesh>- {hint && !lit && (- <Html center position={[0, 0.62, 0.05]} zIndexRange={[24, 0]} pointerEvents="none">- <span className="office-call-pill" data-office-ui>- <b>{t("society.office.elevator_choose")}</b>- <small>{t("society.office.elevator_press")}</small>- </span>- </Html>- )}{/* The click target: a see-through pad a little larger than the button, so it is easy to hit from a distance. */}<mesh position={[0, 0, 0.03]} onClick={press}onPointerOver={(event) => { event.stopPropagation(); document.body.style.cursor = "pointer"; }}diff --git a/jarvis/ui/web/frontend/src/components/society/office/ElevatorPanel.tsx b/jarvis/ui/web/frontend/src/components/society/office/ElevatorPanel.tsxindex 869705d710..bb380fe1ae 100644--- a/jarvis/ui/web/frontend/src/components/society/office/ElevatorPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/ElevatorPanel.tsx@@ -6,7 +6,7 @@* in the indicator and cannot be pressed. A pressed button lights its rim* for a moment, then the panel closes and the doors start to move.*- * Keys: the floor's number (0, 1, 2) presses it, arrows move between the+ * Keys: the floor's number (0 to 3) presses it, arrows move between the* buttons, Escape (or E) closes. It is a dialog, so the character stands* still while it is open (`ownsKeyboard`). Part of the diorama: one steel* palette in light and dark mode.diff --git a/jarvis/ui/web/frontend/src/components/society/office/LobbyDecor.tsx b/jarvis/ui/web/frontend/src/components/society/office/LobbyDecor.tsxindex 44a131d7da..990353d83b 100644--- a/jarvis/ui/web/frontend/src/components/society/office/LobbyDecor.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/LobbyDecor.tsx@@ -69,7 +69,7 @@ const LM = {travertine: matte(C.travertine, { roughness: 0.45 }),marble: matte(C.marble, { roughness: 0.25 }),clay: matte(C.clay, { roughness: 0.8 }),- brass: matte("#c7a15e", { roughness: 0.3, metalness: 0.7 }),+ brass: matte("#b08d5c", { roughness: 0.3, metalness: 0.7 }),bronze: matte("#5a4a3a", { roughness: 0.4, metalness: 0.5 }),charcoal: matte("#2b2f33", { roughness: 0.5, metalness: 0.1 }),ceramic: matte("#f3efe8", { roughness: 0.35 }),diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.groundAnchor.test.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.groundAnchor.test.tsxindex 9dcab799c8..c13a67fc79 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.groundAnchor.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.groundAnchor.test.tsx@@ -20,6 +20,16 @@ vi.mock("@react-three/drei", async (original) => ({useGLTF: () => ({ scene: model }),Html: () => null,}));+// The pet's vinyl gets a studio reflection that is rendered into GPU targets; the renderer double below has+// none, and where the pet stands on the floor does not depend on it. The reflection is a plain texture here.+vi.mock("three", async (original) => {+ const actual = await original<typeof import("three")>();+ class FlatReflection {+ fromScene() { return { texture: new actual.Texture() }; }+ dispose() { /* nothing was allocated */ }+ }+ return { ...actual, PMREMGenerator: FlatReflection };+});extend(THREE);let root: ReconcilerRoot<HTMLCanvasElement> | null = null;diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.teamwork.test.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.teamwork.test.tsxnew file mode 100644index 0000000000..cf6da54868--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.teamwork.test.tsx@@ -0,0 +1,307 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { act, createRoot, extend, type ReconcilerRoot, type RootState } from "@react-three/fiber";+import * as THREE from "three";+import { OfficeAgents, type WalkerContext } from "./OfficeAgents";+import type { AgentRunState, SocietyAgent } from "../data";+import { allDesks, seatOf, type OfficeLayout } from "./officeLayout";+import { buildNavGrid, isWalkable } from "./officeNav";+import { PERSON_CROWD_M, PERSON_SPACE_M, SpotBook } from "./officeBehavior";+import { huddlePlaces, studioOfTeam } from "./officeTeams";+import { player, useOfficeStore } from "./officeStore";+import { emptyRound, useTeamwork, type Handoff } from "./teamwork";+import { agentPositions, seatedAtDesk, walkerDebug } from "./walkerRegistry";+import { campusOf, type Campus } from "./officeFixtures";++vi.mock("@react-three/drei", async (original) => ({+ ...await original<typeof import("@react-three/drei")>(),+ // The walkers' choreography is under test, not their models or their DOM labels.+ useGLTF: () => ({ scene: new THREE.Group() }),+ Html: () => null,+}));++// The little symbol pets behind the agents need their shipped models; they are not what is tested here.+vi.mock("../companion/AgentFollower", () => ({ AgentFollower: () => null }));+// The store is driven by hand here; the hook that feeds it from the network has its own tests.+vi.mock("./useTeamRounds", () => ({ useTeamRounds: () => undefined }));++extend(THREE);+let root: ReconcilerRoot<HTMLCanvasElement> | null = null;+const originalPlayer = { ...player };++beforeEach(() => {+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(1_000_000);+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);+ vi.spyOn(console, "warn").mockImplementation(() => undefined);+ // The person stands far away from everything that happens.+ Object.assign(player, { x: 500, z: 500, heading: 0, path: [], moving: false });+ useOfficeStore.setState({ summons: {} });+ useTeamwork.getState().reset();+});++afterEach(async () => {+ await act(async () => root?.unmount());+ root = null;+ Object.assign(player, originalPlayer);+ useTeamwork.getState().reset();+ agentPositions.clear();+ seatedAtDesk.clear();+ walkerDebug.clear();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ vi.useRealTimers();+});++/** R3F scene graph test double; no browser, GPU or network. */+function fakeRenderer(canvas: HTMLCanvasElement) {+ const noop = () => undefined;+ return {+ domElement: canvas, render: noop, setSize: noop, setPixelRatio: noop, setAnimationLoop: noop, dispose: noop,+ getPixelRatio: () => 1, shadowMap: { enabled: false, type: 0, needsUpdate: false },+ xr: { enabled: false, isPresenting: false, addEventListener: noop, removeEventListener: noop, setAnimationLoop: noop },+ outputColorSpace: "srgb", toneMapping: 0, toneMappingExposure: 1,+ info: { render: {}, memory: {} },+ };+}++function societyAgents(campus: Campus, states: Record<string, AgentRunState> = {}): Map<string, SocietyAgent> {+ return new Map(campus.roster.map((a) => [a.agentId, {+ agentId: a.agentId, name: a.name, tier: "specialist", state: states[a.agentId] ?? "idle", figure: null,+ palette: { primary: "#f2a65a" }, provider: "", chatSessionId: null, checkpoint: "desk",+ } as unknown as SocietyAgent]));+}++async function mount(campus: Campus) {+ const canvas = document.createElement("canvas");+ const current = createRoot(canvas);+ root = current;+ let state!: RootState;+ current.configure({+ gl: fakeRenderer(canvas) as unknown as NonNullable<Parameters<typeof current.configure>[0]>["gl"],+ frameloop: "never", size: { width: 100, height: 100, top: 0, left: 0 },+ onCreated: (value) => { state = value; },+ });+ const book = new SpotBook();+ let agents = societyAgents(campus);+ let layout: OfficeLayout = campus.layout;+ let grid = campus.grid;+ const context = (): WalkerContext => {+ const desks = allDesks(layout);+ return {+ layout, grid, book, spawn: layout.arrival,+ colleagues: () => desks.filter((d) => d.agentId && agents.get(d.agentId)?.state === "working").map((d) => ({ agentId: d.agentId as string, desk: d })),+ };+ };+ let ctx = context();+ const render = async () => {+ await act(async () => {+ current.render(+ <OfficeAgents agents={agents} desks={allDesks(layout)} ctx={ctx} newcomers={new Set()} awake reduced={false} selectedId={null} onSelect={() => undefined} />,+ );+ });+ };+ await render();+ let time = 0;+ let closest = Infinity;+ /** Run the office for `seconds`, 30 frames each; keeps the smallest gap between any two figures on the move. */+ const run = async (seconds: number) => {+ await act(async () => {+ for (let i = 0; i < seconds * 30; i += 1) {+ time += 1000 / 30;+ vi.setSystemTime(1_000_000 + time);+ // R3F takes the frame time in seconds.+ state.advance(time / 1000);+ for (const a of walkerDebug.values()) {+ if (a.phase !== "travel") continue;+ for (const b of walkerDebug.values()) {+ if (a.id !== b.id) closest = Math.min(closest, Math.hypot(a.at.x - b.at.x, a.at.z - b.at.z));+ }+ }+ }+ });+ };+ return {+ run, book,+ closest: () => closest,+ walker: (id: string) => walkerDebug.get(id)!,+ setStates: async (states: Record<string, AgentRunState>) => { agents = societyAgents(campus, states); await render(); },+ swapFloor: async (next: Campus) => { layout = next.layout; grid = buildNavGrid(next.layout); book.retain(new Set(layout.spots.map((s) => s.id))); ctx = context(); await render(); },+ grid: () => grid,+ };+}++const TEAM = "team-0";++describe("teamwork on the floor", () => {+ it("gathers a team's free members at their studio board while its round runs, and sends them back when it ends", async () => {+ const campus = campusOf(12, [5]);+ const office = await mount(campus);+ const studio = studioOfTeam(campus.layout, TEAM)!;+ const members = studio.members;+ const places = huddlePlaces(campus.layout, campus.grid, studio);+ await office.run(1);+ for (const id of members) expect(office.walker(id)).toMatchObject({ team: TEAM, role: "none" });+ expect(members.every((id) => office.walker(id).plan !== "huddle" || office.walker(id).phase === "dwell")).toBe(true);++ // A round opens; one member is working on something else.+ await office.setStates({ [members[4]]: "working" });+ act(() => useTeamwork.getState().setRound({ ...emptyRound(TEAM), running: true, members: [...members], loaded: true }));+ await office.run(40);+ const free = members.slice(0, 4);+ for (const id of free) {+ const w = office.walker(id);+ expect(w, id).toMatchObject({ plan: "huddle", phase: "dwell", role: "gather" });+ const place = places.find((p) => p.id === w.spot)!;+ expect(Math.hypot(w.at.x - place.x, w.at.z - place.z), id).toBeLessThan(1e-6);+ }+ expect(new Set(free.map((id) => office.walker(id).spot)).size).toBe(4);+ // The busy member never left its screen.+ const seat = seatOf(allDesks(campus.layout).find((d) => d.agentId === members[4])!);+ expect(office.walker(members[4])).toMatchObject({ plan: "work", role: "busy", at: { x: seat.x, z: seat.z } });++ // The member contributing now reads "working" and stays at the board, as the speaker.+ act(() => useTeamwork.getState().setRound({ ...useTeamwork.getState().rounds[TEAM], speakerId: members[1] }));+ await office.setStates({ [members[4]]: "working", [members[1]]: "working" });+ await office.run(12);+ expect(office.walker(members[1])).toMatchObject({ plan: "huddle", phase: "dwell", role: "speaker" });++ // The round settles: everyone goes back to their own desk first.+ act(() => useTeamwork.getState().setRound({ ...useTeamwork.getState().rounds[TEAM], running: false, speakerId: null }));+ await office.setStates({ [members[4]]: "working" });+ await office.run(1);+ for (const id of free) expect(office.walker(id), id).toMatchObject({ plan: "desk", role: "none" });+ await office.run(30);+ for (const id of free) {+ const own = seatOf(allDesks(campus.layout).find((d) => d.agentId === id)!);+ const w = office.walker(id);+ if (w.plan === "desk") expect([w.at.x, w.at.z], id).toEqual([own.x, own.z]);+ }+ // On the way there and back nobody walked through anybody, and nobody had to be placed.+ expect(office.closest()).toBeGreaterThan(0.5);+ expect(members.reduce((n, id) => n + office.walker(id).rescues, 0)).toBe(0);+ });++ it("makes room when the person walks into the group at the board, and takes no place on the person's toes", async () => {+ const campus = campusOf(12, [5]);+ const office = await mount(campus);+ const studio = studioOfTeam(campus.layout, TEAM)!;+ const places = huddlePlaces(campus.layout, campus.grid, studio);+ // The person already stands on the best place when the round opens.+ Object.assign(player, { x: places[0].x, z: places[0].z });+ act(() => useTeamwork.getState().setRound({ ...emptyRound(TEAM), running: true, members: [...studio.members], loaded: true }));+ await office.run(40);+ const gap = (id: string) => Math.hypot(office.walker(id).at.x - player.x, office.walker(id).at.z - player.z);+ for (const id of studio.members) {+ expect(office.walker(id), id).toMatchObject({ plan: "huddle", phase: "dwell" });+ expect(gap(id), id).toBeGreaterThanOrEqual(PERSON_SPACE_M - 0.01);+ }+ // Now the person steps right up to one of them.+ const neighbour = studio.members[2];+ const was = office.walker(neighbour).spot;+ Object.assign(player, { x: office.walker(neighbour).at.x + 0.7, z: office.walker(neighbour).at.z });+ expect(gap(neighbour)).toBeLessThan(PERSON_CROWD_M);+ await office.run(12);+ expect(office.walker(neighbour)).toMatchObject({ plan: "huddle", phase: "dwell" });+ expect(office.walker(neighbour).spot).not.toBe(was);+ expect(gap(neighbour)).toBeGreaterThanOrEqual(PERSON_SPACE_M - 0.01);+ // Everybody still has a place of their own, more than a metre from the next.+ const at = studio.members.map((id) => office.walker(id).at);+ for (const [i, p] of at.entries()) for (const q of at.slice(i + 1)) expect(Math.hypot(p.x - q.x, p.z - q.z)).toBeGreaterThan(1);+ });++ it("hurries a working agent back to its screen, at the pace the walker reports", async () => {+ const campus = campusOf(12, [5]);+ const office = await mount(campus);+ // Idle life spreads the floor out; then an agent away from its desk gets work.+ await office.run(40);+ const desks = allDesks(campus.layout);+ const away = campus.roster.map((a) => a.agentId).filter((id) => {+ const seat = seatOf(desks.find((d) => d.agentId === id)!);+ return Math.hypot(office.walker(id).at.x - seat.x, office.walker(id).at.z - seat.z) > 8;+ });+ expect(away.length).toBeGreaterThan(0);+ const id = away[0];+ const seat = seatOf(desks.find((d) => d.agentId === id)!);+ await office.setStates({ [id]: "working" });+ await office.run(2);+ const start = office.walker(id);+ expect(start).toMatchObject({ plan: "work", phase: "travel" });+ const metres = start.remainingM + start.walkS * start.speed;+ // By its own clock it walks briskly: well above the stroll, never above the brisk pace.+ expect(start.speed).toBeGreaterThan(1.5);+ expect(start.speed).toBeLessThanOrEqual(2.1 + 1e-6);+ // And it is seated within the time that pace gives, plus the turns.+ await office.run(Math.ceil(metres / 1.6) + 2);+ expect(office.walker(id)).toMatchObject({ plan: "work", phase: "dwell", at: { x: seat.x, z: seat.z }, speed: 0, walkS: 0 });+ });++ it("walks a message from its sender to the receiver, and delivers it once", async () => {+ const campus = campusOf(12, [5]);+ const office = await mount(campus);+ const studio = studioOfTeam(campus.layout, TEAM)!;+ const receiver = studio.members[0];+ const sender = campus.roster.find((a) => !studio.members.includes(a.agentId))!.agentId;+ await office.setStates({ [receiver]: "working" });+ await office.run(1);+ const handoff: Handoff = {+ id: "ev-1", from: sender, to: receiver, toName: "Agent 0", text: "Here are the numbers you asked for.", msgType: "ANSWER",+ atMs: Date.now(), phase: "queued", untilMs: Date.now() + 90_000,+ };+ act(() => useTeamwork.getState().addHandoff(handoff));+ await office.run(1);+ expect(office.walker(sender)).toMatchObject({ plan: "handoff", with: receiver });+ // It arrives beside the receiver's chair and stays a moment.+ let delivered = false;+ for (let i = 0; i < 60 && !delivered; i += 1) {+ await office.run(1);+ delivered = useTeamwork.getState().handoffs[0]?.phase === "delivering";+ }+ expect(delivered).toBe(true);+ const seat = seatOf(allDesks(campus.layout).find((d) => d.agentId === receiver)!);+ const at = office.walker(sender).at;+ // Beside the chair, or a step away when both places beside it are taken.+ expect(Math.hypot(at.x - seat.x, at.z - seat.z)).toBeLessThan(1.7);+ expect(Math.hypot(at.x - seat.x, at.z - seat.z)).toBeGreaterThan(0.6);+ // The receiver kept working at its screen throughout.+ expect(office.walker(receiver)).toMatchObject({ plan: "work", at: { x: seat.x, z: seat.z } });+ await office.run(10);+ expect(useTeamwork.getState().handoffs).toEqual([]);+ expect(office.walker(sender).plan).not.toBe("handoff");+ });++ it("keeps a working sender at its screen: the message is not walked over", async () => {+ const campus = campusOf(12, [5]);+ const office = await mount(campus);+ const [a, b] = studioOfTeam(campus.layout, TEAM)!.members;+ await office.setStates({ [a]: "working" });+ await office.run(1);+ act(() => useTeamwork.getState().addHandoff({ id: "ev-2", from: a, to: b, toName: "Agent 1", text: "Take this over", msgType: "ASSIGN", atMs: Date.now(), phase: "queued", untilMs: Date.now() + 90_000 }));+ await office.run(5);+ expect(office.walker(a).plan).toBe("work");+ expect(useTeamwork.getState().handoffs[0].phase).toBe("queued");+ });++ it("keeps everyone on their feet when the floor plan is rebuilt under them", async () => {+ const before = campusOf(14, [5]);+ const office = await mount(before);+ // Let the idle floor spread out, then build a second team's studio mid-walk.+ await office.run(25);+ const after = campusOf(14, [5, 5]);+ await office.swapFloor(after);+ await office.run(60);+ const grid = office.grid();+ for (const agent of after.roster) {+ const w = office.walker(agent.agentId);+ expect(w.plan, agent.agentId).not.toBeNull();+ // Standing people stand on the floor; seated ones on a seat that exists on the new plan.+ const seated = w.phase === "dwell" && ["desk", "couch", "beanbag", "meeting", "work", "nap"].includes(w.plan!);+ if (w.phase === "dwell" && !seated) expect(isWalkable(grid, w.at), `${agent.agentId} ${w.plan}`).toBe(true);+ if (w.plan === "desk" && w.phase === "dwell") {+ const own = seatOf(allDesks(after.layout).find((d) => d.agentId === agent.agentId)!);+ expect([w.at.x, w.at.z], agent.agentId).toEqual([own.x, own.z]);+ }+ expect(w.team, agent.agentId).toBe(after.teams.find((t) => t.members.includes(agent.agentId))?.id ?? null);+ }+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsxindex 774bfe84d2..b024a800ac 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsx@@ -1,7 +1,10 @@/*** Agents living in the office. Working agents sit at their screens, waiting- * agents stand and wave at their desk, idle agents wander: coffee, couch,- * window, arcade, a chat at a busy colleague's desk. Paused agents nap.+ * agents stand and wave at their desk, paused agents nap, and idle agents+ * live round their team's studio: their desk, the studio board, a teammate's+ * desk, now and then a coffee or the couch. A running round of a team brings+ * its free members to their studio board, and a message one agent sent+ * another is walked over (teamwork.ts): both are real, nothing is staged.** The office is a projection of the roster: run state comes from the backend,* everything else is client-side choreography that costs no tokens and never@@ -27,10 +30,17 @@ import { useCompanionPet } from "../companion/companionPetStore";import { companionFlies } from "../companion/petCompanions";import { resolveCompanion } from "../companion/appearance";import type { TrailPoint } from "../companion/trail";-import { stepMover, stepMoverAvoiding, turnToward, WALK_SPEED, type Mover } from "./officeMotion";-import { createRng, planFor, type ActivityKind, type Plan, type Pose, type SpotBook } from "./officeBehavior";-import { player, useOfficeStore } from "./officeStore";-import { agentPositions, bodiesExcept, companions, seatedAtDesk } from "./walkerRegistry";+import { clearOfBodies, hurryPaceFor, stepMover, turnToward, WALK_SPEED, type Mover } from "./officeMotion";+import { advanceWalk, beginWalk, type Walk } from "./officeWalk";+import {+ createRng, dwellAfter, HANDOFF_DWELL_MS, PERSON_CROWD_M, planFor, planStillValid, shownActivity, type ActivityKind, type Plan, type Pose, type SpotBook,+} from "./officeBehavior";+import { homeStudio, mateDesks, studiosOf } from "./officeTeams";+import { boardWatch, pendingHandoff, roundFor, roundRole, steadyRole, useTeamwork, type RoleMemory } from "./teamwork";+import { useTeamRounds } from "./useTeamRounds";+import { StudioBoards } from "./StudioBoards";+import { player, useOfficeStore, type Summon } from "./officeStore";+import { agentPositions, bodiesNear, companions, placeAgent, seatedAtDesk, walkerDebug } from "./walkerRegistry";import { AgentBubble } from "./OfficeBubbles";import type { ChatLine } from "./deskChat";import type { DeskChat } from "./useDeskChats";@@ -39,6 +49,11 @@ import { deliverySpot, ERRAND_SPEED, useErrandFeed, useGigiErrands } from "./gigimport { isPaneAgentId, plateTitle } from "./codingFloor";import { agentLogoAsset } from "@/components/agentic/AgentMark";import { LevelChip } from "../progression/LevelHud";+import { plateDetail, type PlateDetail } from "./namePlate";+import type { Camera } from "three";+import { useThree } from "@react-three/fiber";+import { joinPlates, plateSeating, reportPlate, type ScreenRect } from "./plateCrowd";+import { isSpeaking, lastSpokeBy, SPOKE_LINGER_MS } from "./teamwork";import { agentSubject, petSubject } from "../progression/progressionApi";import { useProgression } from "../progression/progressionStore";import { useDressedFigure } from "../progression/regalia/dress";@@ -56,6 +71,32 @@ const FOLLOW_CATCH_M = 1;const LEAD_PLATE_FLYING_M = 1.75;const LEAD_PLATE_ON_FLOOR_M = 0.85;+/** The person's pet keeps this far from every agent while it follows the person. */+const PET_CLEAR_M = 0.5;+/** Bodies further than this from a walker play no part in its steering or its detours. */+const BODY_RANGE_M = 7;++// Dev-only: what every walker, team round and studio board is doing right now.+// __officeLife.walkers() one row per agent: team, role in a running round, plan, phase, target, stuck seconds,+// walkS / speed (seconds and average m/s on the current walk, by the frame time the+// walker really got: with the frame loop running, __officeStep's dtMs is not that time),+// and how often it took a detour (replans), was placed (rescues), gave a walk up (blocked)+// or had its route repaired (repaths)+// __officeLife.walker(id) the same for one agent+// __officeLife.stuck() the walkers that needed a detour or a placement, or gave a walk up, so far+// __officeLife.teamwork() rounds by team (running, speaker, lines) and the messages still to be walked over+// __officeLife.boards() the team ids whose studio board is live (near the camera)+if (import.meta.env.DEV && typeof window !== "undefined") {+ Object.assign(window, { __officeLife: {+ walkers: () => [...walkerDebug.values()],+ walker: (id: string) => walkerDebug.get(id) ?? null,+ stuck: () => [...walkerDebug.values()].filter((w) => w.replans + w.rescues + w.blocked > 0),+ teamwork: () => { const { rounds, handoffs } = useTeamwork.getState(); return { rounds, handoffs }; },+ boards: () => [...boardWatch.near()],+ store: useTeamwork,+ } });+}+/** Every figure shares one toy scale, so desks and couches read the same everywhere. */export const OFFICE_FIGURE_HEIGHT_M = 1.3;@@ -90,17 +131,65 @@ function Nameplate({ agent, activity, selected, onSelect, height = OFFICE_FIGURE}) {const t = useT();const plate = useRef<HTMLButtonElement>(null);+ const wrap = useRef<HTMLSpanElement>(null);const anchor = useRef<Group>(null);const last = useRef(0);const world = useMemo(() => new Vector3(), []);- useFrame(({ camera }) => {- if (!anchor.current || !plate.current) return;- const scale = plateScale(camera.position.distanceTo(anchor.current.getWorldPosition(world)));+ const [open, setOpen] = useState(false);+ // The pointer on the figure itself counts like the pointer on its plate.+ const pointedAt = useOfficeStore((s) => s.hover?.kind === "agent" && s.hover.id === agent.agentId);+ const shown = useRef<PlateDetail>("dot");+ // What the distance rule alone says (it has its own memory); a crowd may still keep the plate a dot.+ const ruled = useRef<PlateDetail>("dot");+ const wanted = useRef({ pointed: false, selected: false });+ wanted.current = { pointed: open || pointedAt, selected };+ // Whoever speaks in a team round keeps its plate in a crowd, with room for the bubble above it.+ const speaking = useTeamwork((s) => isSpeaking(s.rounds, agent.agentId));+ const spokeAt = useTeamwork((s) => lastSpokeBy(s.rounds, agent.agentId)?.atMs ?? 0);+ const voice = useRef({ speaking, spokeAt });+ voice.current = { speaking, spokeAt };+ const measured = useRef({ w: 0, h: 0, tick: 0 });+ const scene = useThree((s) => s.scene);+ const onScreen = useMemo(() => new Vector3(), []);+ // Plates are seated per stage (two offices can be awake at once); this one leaves its stage's seating on unmount.+ useEffect(() => joinPlates(scene), [scene]);+ useFrame(({ camera, size, clock }) => {+ if (!anchor.current || !plate.current || !wrap.current) return;+ anchor.current.getWorldPosition(world);+ const cameraDistance = camera.position.distanceTo(world);+ const personDistance = Math.hypot(world.x - player.x, world.z - player.z);+ const scale = plateScale(cameraDistance);+ // Far away the agent is a dot; the plate opens near the camera or the person, and for the one pointed at or selected.+ ruled.current = plateDetail(ruled.current, { cameraDistance, personDistance, ...wanted.current });+ let detail = ruled.current;+ if (detail === "full") {+ // In a crowd only the plates that do not cover one another open (plateCrowd.ts); the rest stay dots.+ const m = measured.current;+ if (m.w === 0 || m.tick % PLATE_MEASURE_FRAMES === 0) {+ m.w = plate.current.offsetWidth || PLATE_FALLBACK_PX.w;+ m.h = plate.current.offsetHeight || PLATE_FALLBACK_PX.h;+ }+ m.tick += 1;+ onScreen.copy(world).project(camera);+ if (onScreen.z < 1) {+ const pinned = wanted.current.pointed || wanted.current.selected;+ const taken = () => personPlate(camera, size);+ if (!pinned && !plateSeating(scene, clock.elapsedTime, taken).has(agent.agentId)) detail = "dot";+ reportPlate(scene, {+ id: agent.agentId, x: (onScreen.x * 0.5 + 0.5) * size.width, y: (0.5 - onScreen.y * 0.5) * size.height,+ w: m.w * scale, h: m.h * scale, pinned, distance: personDistance, shown: shown.current === "full",+ speaker: voice.current.speaking || Date.now() - voice.current.spokeAt < SPOKE_LINGER_MS,+ });+ }+ }+ if (detail !== shown.current || wrap.current.dataset.detail !== detail) {+ shown.current = detail;+ wrap.current.dataset.detail = detail;+ }if (Math.abs(scale - last.current) < 0.02) return;last.current = scale;plate.current.style.transform = `scale(${scale.toFixed(2)})`;});- const [open, setOpen] = useState(false);const detail = agent.state !== "idle" ? t(`society.office.state_${agent.state}`) : activity ? t(`society.office.activity_${activity}`) : "";const pane = isPaneAgentId(agent.agentId);const logo = pane ? agentLogoAsset(agent.provider) : null;@@ -111,12 +200,15 @@ function Nameplate({ agent, activity, selected, onSelect, height = OFFICE_FIGURE);return (<group ref={anchor} position={[0, height, 0]}>- {/* Hover/focus raises a plate above its neighbours; coding titles stay expanded independently. */}- <Html center zIndexRange={open ? [40, 30] : [20, 0]}>- <button ref={plate} type="button" data-office-ui className="office-plate" data-state={agent.state} data-selected={selected || undefined}+ {/* Hover/focus raises a plate above its neighbours. Only the dot and the open plate take the pointer: the+ wrapper is as wide as the plate even while it shows a dot, and must not swallow clicks meant for the floor. */}+ <Html center zIndexRange={open ? [40, 30] : [20, 0]} style={PLATE_PASS_THROUGH}>+ <span ref={wrap} className="office-plate-wrap" data-office-ui data-state={agent.state} data-detail={shown.current}+ onPointerEnter={() => setOpen(true)} onPointerLeave={() => setOpen(false)}>+ <i className="office-plate-dot" aria-hidden onClick={(event) => { event.stopPropagation(); onSelect(agent.agentId); }} />+ <button ref={plate} type="button" className="office-plate" data-state={agent.state} data-selected={selected || undefined}data-pane={pane || undefined} data-open={pane || open || undefined}onClick={(event) => { event.stopPropagation(); onSelect(agent.agentId); }}- onPointerEnter={() => setOpen(true)} onPointerLeave={() => setOpen(false)}onFocus={() => setOpen(true)} onBlur={() => setOpen(false)}aria-label={t("society.office.open_agent").replace("{0}", agent.name)}>{pane && logo ? <PaneLogo url={logo.url} ground={logo.ground} /> : (@@ -132,11 +224,27 @@ function Nameplate({ agent, activity, selected, onSelect, height = OFFICE_FIGURE</>)}</button>+ </span></Html></group>);}+/** The plate's wrapper never takes the pointer itself; the dot and the open plate inside it do. */+const PLATE_PASS_THROUGH = { pointerEvents: "none" } as const;+/** A plate's size on screen is read from the DOM now and then, not every frame; before the first reading it is assumed. */+const PLATE_MEASURE_FRAMES = 45;+const PLATE_FALLBACK_PX = { w: 150, h: 22 } as const;+/** The person's own plate (OfficePlayer draws it) is always there: agents' plates keep clear of it. */+const PERSON_PLATE_PX = { w: 150, h: 26 } as const;+const personAt = new Vector3();++function personPlate(camera: Camera, size: { width: number; height: number }): ScreenRect[] {+ personAt.set(player.x, OFFICE_FIGURE_HEIGHT_M + 0.35, player.z).project(camera);+ if (personAt.z >= 1) return [];+ return [{ x: (personAt.x * 0.5 + 0.5) * size.width, y: (0.5 - personAt.y * 0.5) * size.height, ...PERSON_PLATE_PX }];+}+/** An agent's level on its plate; the lead shows its pet's level, since the lead IS the pet. */function PlateLevel({ agent }: { agent: SocietyAgent }) {const lead = agent.tier === "lead";@@ -216,8 +324,8 @@ export interface WalkerContext {spawn: Point;}-function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected, lines, onSelect }: {- agent: SocietyAgent; desk: DeskSlot | null; ctx: WalkerContext; arrivesByElevator: boolean;+function Walker({ agent, desk, ctx, deskOf, arrivesByElevator, awake, reduced, selected, lines, onSelect }: {+ agent: SocietyAgent; desk: DeskSlot | null; ctx: WalkerContext; deskOf: ReadonlyMap<string, DeskSlot>; arrivesByElevator: boolean;awake: boolean; reduced: boolean; selected: boolean; lines: readonly ChatLine[] | undefined; onSelect: (id: string) => void;}) {const look = useMemo(() => toyLookFor(agent.figure, agent.agentId), [agent.figure, agent.agentId]);@@ -236,6 +344,23 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,// The desk the current plan was made for: a roster change can move an agent to another desk.const planDesk = useRef<string | null>(null);const summonKey = useRef("");+ // The walk in progress (its route, stuck watch and time budget), and the floor plan the current plan was made on.+ const walk = useRef<Walk | null>(null);+ const planGrid = useRef<NavGrid | null>(null);+ // Team life: the studio the agent belongs to, its part in a running round, and the message it is walking over.+ const home = useMemo(() => homeStudio(ctx.layout, agent.agentId, desk), [ctx.layout, agent.agentId, desk]);+ const roleMemory = useRef<RoleMemory>({ role: "none", busySinceMs: null });+ const roundKey = useRef("");+ const handoffKey = useRef("");+ const nearby = useRef<Point[]>([]);+ const tally = useRef({ replans: 0, rescues: 0, repaths: 0, near: 0, blocked: 0, lost: 0 });+ // Walks in a row that were given up because the way stayed closed.+ const givenUp = useRef(0);+ // The keys a plan is made for, built when the desk or the call changes and not on every frame.+ const deskKey = useMemo(() => (desk ? `${desk.id}@${desk.x.toFixed(2)},${desk.z.toFixed(2)}` : null), [desk]);+ const called = useRef<{ summon: Summon | undefined; key: string }>({ summon: undefined, key: "" });+ // Seconds the person has stood right beside this agent at a board (negative: it just made room, give it a moment).+ const crowded = useRef(0);const [activity, setActivity] = useState<ActivityKind | null>(null);const [seatHeight, setSeatHeight] = useState<number>(SEAT_HEIGHT.chair);const isGigi = agent.tier === "lead";@@ -247,6 +372,11 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,const followingRef = useRef(false);const gigiSide = useRef<1 | -1>(1);const airClear = useMemo(() => (x: number, z: number) => isWalkable(ctx.grid, { x, z }), [ctx.grid]);+ // Where the pet keeps the person company: free floor that is nobody's, so it never sits in a seated agent or on a chair.+ const petSpot = useMemo(() => {+ const around: Point[] = [];+ return (x: number, z: number) => isWalkable(ctx.grid, { x, z }) && clearOfBodies({ x, z }, bodiesNear(agent.agentId, { x, z }, 1, null, around), PET_CLEAR_M);+ }, [ctx.grid, agent.agentId]);// The lead is drawn as the person's pet; one that walks takes floor routes instead of flying over desks.const petOnFloor = useCompanionPet((s) => isGigi && !companionFlies(s.pet));const onFloorRef = useRef(petOnFloor);@@ -259,6 +389,7 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,agentPositions.delete(agent.agentId);seatedAtDesk.delete(agent.agentId);companions.delete(agent.agentId);+ walkerDebug.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]);@@ -307,7 +438,7 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,}// The day resumes from wherever the errand ended.plan.current = null;- agentPositions.set(agent.agentId, { x: m.x, z: m.z });+ placeAgent(agent.agentId, m.x, m.z);seatedAtDesk.delete(agent.agentId);if (group.current) group.current.position.set(m.x, 0, m.z);return;@@ -317,7 +448,7 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,const calledTo = summon && summon.untilMs > now ? summon.target : null;if (isGigi && !calledTo) {// Gigi keeps the person company, as on the coding floor; an errand or a summons still takes it away.- const anchor = followAnchor(player.x, player.z, player.heading, gigiSide.current, airClear, onFloorRef.current);+ const anchor = followAnchor(player.x, player.z, player.heading, gigiSide.current, petSpot, onFloorRef.current);gigiSide.current = anchor.side;const far = Math.hypot(anchor.x - m.x, anchor.z - m.z) > FOLLOW_CATCH_M;if (!placed.current || reduced || !far) {@@ -339,7 +470,7 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,// The day resumes from wherever the person leaves Gigi (a summons).plan.current = null;summonKey.current = "";- agentPositions.set(agent.agentId, { x: m.x, z: m.z });+ placeAgent(agent.agentId, m.x, m.z);seatedAtDesk.delete(agent.agentId);if (group.current) group.current.position.set(m.x, 0, m.z);return;@@ -347,15 +478,58 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,if (followingRef.current) { followingRef.current = false; setFollowing(false); }companions.delete(agent.agentId);const calledSeat = calledTo ? summon.spotId ?? null : null;- const sKey = calledTo ? `${calledTo.x.toFixed(2)},${calledTo.z.toFixed(2)},${calledSeat ?? ""}` : "";- const deskKey = desk ? `${desk.id}@${desk.x.toFixed(2)},${desk.z.toFixed(2)}` : null;+ if (called.current.summon !== summon) {+ called.current = { summon, key: summon ? `${summon.target.x.toFixed(2)},${summon.target.z.toFixed(2)},${summon.spotId ?? ""}` : "" };+ }+ const sKey = calledTo ? called.current.key : "";+ // Team life, from what is real right now: a running round of the agent's team, and a message it sent a colleague.+ const teamwork = useTeamwork.getState();+ const round = isGigi ? undefined : roundFor(teamwork.rounds, agent.agentId, home?.teamId ?? null);+ const role = steadyRole(roleMemory.current, roundRole(agent, round), now);+ const inRound = !!round && !calledTo && (role === "gather" || role === "speaker");+ const rKey = inRound && round ? round.teamId : "";+ // The stay with the receiver is over: the message has been delivered.+ if (plan.current?.kind === "handoff" && handoffKey.current && phase.current === "dwell" && now >= dwellUntil.current) {+ teamwork.finishHandoff(handoffKey.current);+ }+ // Only a free agent walks a message over; a working one keeps its screen (its bubble still says what it sent).+ const handoff = isGigi || reduced || agent.state !== "idle" || calledTo || inRound+ ? null : pendingHandoff(useTeamwork.getState().handoffs, agent.agentId, now);+ const hKey = handoff ? handoff.id : "";+ // A rebuilt floor plan: the plan holds only if its place still exists there, and its spot is still this agent's.+ let stale = false;+ if (plan.current && planGrid.current !== ctx.grid) {+ const held = plan.current;+ stale = !planStillValid(held, ctx.layout, ctx.grid) || (held.spotId !== null && !ctx.book.claim(held.spotId, agent.agentId));+ planGrid.current = ctx.grid;+ }+ // The person walked into the group at the board: the agent beside them makes room (another place in the arc).+ let makeRoom = false;+ if (plan.current?.kind === "huddle" && phase.current === "dwell" && Math.hypot(player.x - m.x, player.z - m.z) < PERSON_CROWD_M) {+ crowded.current += dt;+ if (crowded.current > 0.4) { makeRoom = true; crowded.current = -3; }+ } else if (crowded.current > 0) crowded.current = 0;+ else crowded.current = Math.min(0, crowded.current + dt);const needsPlan = !plan.current || planState.current !== agent.state || summonKey.current !== sKey- || planDesk.current !== deskKey+ || planDesk.current !== deskKey || roundKey.current !== rKey || handoffKey.current !== hKey || stale || makeRoom|| (phase.current === "dwell" && now >= dwellUntil.current);if (needsPlan) {+ const seatedMates = home ? mateDesks(ctx.layout, home, agent.agentId).filter((d) => seatedAtDesk.has(d.agentId as string)) : [];const next = planFor({agentId: agent.agentId, state: agent.state, desk, layout: ctx.layout, grid: ctx.grid, rng, book: ctx.book,previous: plan.current?.kind ?? null, workingColleagues: ctx.colleagues().filter((c) => c.agentId !== agent.agentId), calledTo, calledSeat,+ position: placed.current ? { x: m.x, z: m.z } : null,+ // The member contributing right now reads "working"; it is the one working member a round places.+ round: inRound && round ? { speaker: role === "speaker" || agent.state === "working", teamId: round.teamId } : null,+ // A receiver that works is at its screen, or on its way there: its desk is where to find it.+ handoff: handoff ? {+ to: handoff.to, desk: deskOf.get(handoff.to) ?? null, at: agentPositions.get(handoff.to) ?? null,+ seated: seatedAtDesk.has(handoff.to) || ctx.colleagues().some((c) => c.agentId === handoff.to),+ } : null,+ matesAtDesk: seatedMates.map((d) => ({ agentId: d.agentId as string, desk: d })),+ backToDesk: roundKey.current !== "" && rKey === "",+ bodies: bodiesNear(agent.agentId, m, Infinity, player, nearby.current),+ person: player,});// Reduced motion: no idle wandering — a placement holds until the state changes.if (reduced && !calledTo) next.dwellMs = Infinity;@@ -363,46 +537,94 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,planState.current = agent.state;planDesk.current = deskKey;summonKey.current = sKey;+ roundKey.current = rKey;+ handoffKey.current = hKey;+ planGrid.current = ctx.grid;+ walk.current = null;if (!placed.current || reduced) {// First sight (or reduced motion): already there, no walk across the floor.m.x = next.target.x; m.z = next.target.z; m.path = [];if (next.facing !== null) m.heading = next.facing;placed.current = true;phase.current = "dwell";- dwellUntil.current = now + next.dwellMs;- } else {+ } else if (isGigi) {m.path = findPath(ctx.grid, m, next.target) ?? [];// Gigi flies: after an errand it may hover over a desk, where no floor path starts.- if (m.path.length === 0 && isGigi && !onFloorRef.current && Math.hypot(next.target.x - m.x, next.target.z - m.z) > 0.05) m.path = [next.target];+ if (m.path.length === 0 && !onFloorRef.current && Math.hypot(next.target.x - m.x, next.target.z - m.z) > 0.05) m.path = [next.target];if (m.path.length === 0) { m.x = next.target.x; m.z = next.target.z; }phase.current = m.path.length > 0 ? "travel" : "dwell";- if (phase.current === "dwell") dwellUntil.current = now + next.dwellMs;+ } else {+ walk.current = beginWalk(ctx.grid, m, next.target, bodiesNear(agent.agentId, m, BODY_RANGE_M, player, nearby.current));+ // No way there on this floor plan: the agent is simply there.+ if (!walk.current) { m.x = next.target.x; m.z = next.target.z; m.path = []; }+ phase.current = m.path.length > 0 ? "travel" : "dwell";}- if (next.kind !== activity) setActivity(next.kind);+ if (phase.current === "dwell") {+ dwellUntil.current = now + next.dwellMs;+ if (next.kind === "handoff" && hKey) teamwork.deliverHandoff(hKey, now, HANDOFF_DWELL_MS);+ }+ // The plate says "at the team board" only for a gathering that is real: a running round, or a meeting the person called.+ const shown = shownActivity(next.kind, inRound || calledTo !== null);+ if (shown !== activity) setActivity(shown);if (isGigi) setGigiPose({ pose: next.pose, travelling: phase.current === "travel" });const nextSeat = seatHeightFor(next.kind);if (nextSeat !== seatHeight) setSeatHeight(nextSeat);}const p = plan.current!;if (phase.current === "travel") {- // Walkers steer around other people instead of through them; Gigi flies over everyone.- const { moved, arrived } = !awake ? { moved: 0, arrived: false }- : isGigi ? stepMover(m, WALK_SPEED, dt)- : stepMoverAvoiding(m, WALK_SPEED, dt, Array.from(bodiesExcept(agent.agentId, player)), (q) => isWalkable(ctx.grid, q));- drive.current.mode = "walk";+ // Walkers steer round other people and never through them or the furniture; Gigi flies over everyone.+ let moved = 0, arrived = false;+ const going = walk.current;+ if (!awake) { /* A sleeping stage holds every walk where it is. */ }+ else if (isGigi || !going) ({ moved, arrived } = stepMover(m, WALK_SPEED, dt));+ else {+ // Nobody is moved across the floor, with one exception: a place the agent's real state demands (its screen+ // while it works, the board while its round runs) that it failed to reach twice.+ const step = advanceWalk(going, m, ctx.grid, dt, bodiesNear(agent.agentId, m, BODY_RANGE_M, player, nearby.current),+ { far: givenUp.current >= 2 && !Number.isFinite(p.dwellMs), ...(p.kind === "work" ? { speed: hurryPaceFor(going.remaining) } : {}) });+ ({ moved, arrived } = step);+ if (step.event === "replan") tally.current.replans += 1;+ else if (step.event === "rescue") tally.current.rescues += 1;+ else if (step.event === "repath") tally.current.repaths += 1;+ else if (step.event === "near") tally.current.near += 1;+ else if (step.event === "lost" || step.event === "blocked") {+ // No way to this place (a new floor plan walled it off, or the way stays closed): plan again next frame.+ if (step.event === "lost") tally.current.lost += 1;+ else { tally.current.blocked += 1; givenUp.current += 1; }+ plan.current = null;+ }+ }+ // Waiting for someone to pass is standing, not walking on the spot.+ drive.current.mode = moved > 1e-4 ? "walk" : "idle";drive.current.speed = moved / Math.max(dt, 1e-3);if (arrived) {phase.current = "dwell";- dwellUntil.current = now + p.dwellMs;+ givenUp.current = 0;+ // A long way earns a long stay, so a large floor shows people being somewhere.+ dwellUntil.current = now + dwellAfter(p, going?.length ?? 0);+ if (p.kind === "handoff" && handoffKey.current) teamwork.deliverHandoff(handoffKey.current, now, HANDOFF_DWELL_MS);if (isGigi) setGigiPose({ pose: p.pose, travelling: false });}} else {if (p.facing !== null) m.heading = turnToward(m.heading, p.facing, 8 * dt);- drive.current.mode = POSE_CLIP[p.pose];+ // At the board the member contributing right now talks; everyone else listens.+ drive.current.mode = POSE_CLIP[p.kind === "huddle" && role === "speaker" ? "talk" : p.pose];drive.current.speed = 0;}- agentPositions.set(agent.agentId, { x: m.x, z: m.z });- if (phase.current === "dwell" && (p.kind === "work" || p.kind === "desk")) seatedAtDesk.add(agent.agentId);+ if (import.meta.env.DEV) {+ walkerDebug.set(agent.agentId, {+ id: agent.agentId, name: agent.name, state: agent.state, team: home?.teamId ?? null, studio: home?.deptId ?? null, role,+ plan: plan.current?.kind ?? null, phase: phase.current, target: plan.current?.target ?? null, spot: plan.current?.spotId ?? null,+ with: plan.current?.with ?? null, at: { x: m.x, z: m.z }, pathLength: m.path.length, remainingM: walk.current?.remaining ?? 0,+ stuckS: phase.current === "travel" ? walk.current?.watch.idleS ?? 0 : 0,+ walkS: phase.current === "travel" ? walk.current?.elapsedS ?? 0 : 0,+ speed: phase.current === "travel" && walk.current && walk.current.elapsedS > 0+ ? (walk.current.length - walk.current.remaining) / walk.current.elapsedS : 0,+ ...tally.current,+ });+ }+ placeAgent(agent.agentId, m.x, m.z);+ if (plan.current && 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;@@ -425,13 +647,17 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,</mesh><group ref={body}onClick={(event) => { event.stopPropagation(); onSelect(agent.agentId); }}- onPointerOver={() => { document.body.style.cursor = "pointer"; }}- onPointerOut={() => { document.body.style.cursor = ""; }}>+ onPointerOver={() => { document.body.style.cursor = "pointer"; useOfficeStore.getState().setHover({ kind: "agent", id: agent.agentId }); }}+ onPointerOut={() => {+ document.body.style.cursor = "";+ const hover = useOfficeStore.getState().hover;+ if (hover?.kind === "agent" && hover.id === agent.agentId) useOfficeStore.getState().setHover(null);+ }}>{!isGigi && <ToyFigure look={dressed.look} drive={drive} paused={!awake} heightM={OFFICE_FIGURE_HEIGHT_M} seatHeight={seatHeight}regalia={dressed.regalia} />}</group><Nameplate agent={agent} activity={activity} selected={selected} onSelect={onSelect} height={isGigi ? leadPlate : undefined} />- <AgentBubble agent={agent} lines={lines} selected={selected} onSelect={onSelect}+ <AgentBubble agent={agent} lines={lines} selected={selected} onSelect={onSelect} listening={activity === "huddle"}height={(isGigi ? leadPlate : OFFICE_FIGURE_HEIGHT_M + 0.35) + 0.14} />{carrying && <ErrandEnvelope />}</group>@@ -451,15 +677,19 @@ export function OfficeAgents({ desks, agents, ctx, newcomers, awake, reduced, se}) {const deskOf = useMemo(() => new Map(desks.filter((d) => d.agentId).map((d) => [d.agentId as string, d])), [desks]);useErrandFeed(agents, awake);+ // Team rounds and messages between agents exist only where there are team studios (the agents floor).+ const studios = studiosOf(ctx.layout);+ useTeamRounds(studios, agents, awake && studios.length > 0);// Leaving the office hangs up: the talk socket closes, the chat keeps running on the server.useEffect(() => () => { officeTalkChat.getState().disconnect(); useOfficeTalk.getState().setAgent(null); }, []);return (<group>{[...agents.values()].map((agent) => (- <Walker key={agent.agentId} agent={agent} desk={deskOf.get(agent.agentId) ?? null} ctx={ctx}+ <Walker key={agent.agentId} agent={agent} desk={deskOf.get(agent.agentId) ?? null} ctx={ctx} deskOf={deskOf}arrivesByElevator={newcomers.has(agent.agentId)} awake={awake} reduced={reduced}selected={selectedId === agent.agentId} lines={chats?.get(agent.agentId)?.lines} onSelect={onSelect} />))}+ {studios.length > 0 && <StudioBoards layout={ctx.layout} agents={agents} awake={awake} />}</group>);}diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeBubbles.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeBubbles.tsxindex 78b18497c0..46198e3983 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeBubbles.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeBubbles.tsx@@ -22,6 +22,7 @@ import { player } from "./officeStore";import { plateScale } from "./OfficeAgents";import { useGigiErrands } from "./gigiErrands";import { memoryLine, type MemoryLabels, type MemoryLine } from "./memoryBubble";+import { isSpeaking, lastSpokeBy, teamBubble, teamBubbleLive, useTeamwork } from "./teamwork";import {ambientBubble, bubbleText, conversationBubble, itemsFor, PLAYER_LINE_MS, REPLY_LINGER_MS, talkStoreFor, useOfficeTalk,type Bubble, type BubbleLabels,@@ -29,6 +30,8 @@ import {/** Ambient bubbles only show within this camera distance (metres). */const AMBIENT_RANGE_M = 20;+/** What a team says and hands over is the floor's real news: readable from a little further away. */+const TEAM_RANGE_M = 34;export function useBubbleLabels(): BubbleLabels {const t = useT();@@ -90,6 +93,25 @@ function useErrandBubble(agent: SocietyAgent): Bubble | null {return null;}+/**+ * Real teamwork over an agent's head: the line it just said in its team's+ * round, a thought while it is the round's speaker, and the message it sent+ * (or is walking over to) a colleague. See teamwork.ts.+ */+function useTeamBubble(agent: SocietyAgent): Bubble | null {+ const t = useT();+ const spoke = useTeamwork((s) => lastSpokeBy(s.rounds, agent.agentId));+ const speaking = useTeamwork((s) => isSpeaking(s.rounds, agent.agentId));+ const handoff = useTeamwork((s) => s.handoffs.find((h) => h.from === agent.agentId) ?? null);+ // The clock runs only while a line or a message is still on its way out; a line said long ago needs none.+ const now = useClock(teamBubbleLive(spoke, handoff, Date.now()));+ if (!spoke && !speaking && !handoff) return null;+ return teamBubble({+ spoke, speaking, handoff, now: Math.max(now, spoke?.atMs ?? 0, handoff?.atMs ?? 0), short: bubbleText,+ labels: { thinking: t("society.office.bubble_thinking"), to: t("society.office.handoff_to") },+ });+}+/** Re-renders once a second while `active`, so a settled bubble can expire. */function useClock(active: boolean): number {const [now, setNow] = useState(() => Date.now());@@ -153,8 +175,10 @@ function MemoryRow({ line }: { line: MemoryLine }) {* The agent's bubble: its live conversation when the person talks to it,* otherwise what it is busy with (from the desk-monitor tail).*/-export function AgentBubble({ agent, lines, selected, height, onSelect }: {+export function AgentBubble({ agent, lines, selected, height, onSelect, listening = false }: {agent: SocietyAgent; lines: readonly ChatLine[] | undefined; selected: boolean; height: number; onSelect: (id: string) => void;+ /** The agent stands at its team's board in a running round: there only the member who has the word carries a bubble. */+ listening?: boolean;}) {const labels = useBubbleLabels();const talking = useOfficeTalk((s) => s.agentId === agent.agentId);@@ -169,12 +193,16 @@ export function AgentBubble({ agent, lines, selected, height, onSelect }: {const now = useClock(lingering);const open = () => onSelect(agent.agentId);const errand = useErrandBubble(agent);+ const team = useTeamBubble(agent);const memory = useMemoryLine(agent);if (errand) return <BubbleView bubble={errand} height={height} onClick={open} memory={memory} />;if (talk && (talk.live || selected || now - talk.atMs < REPLY_LINGER_MS)) {return <BubbleView bubble={talk} height={height} onClick={open} memory={memory} />;}- const ambient = ambientBubble(agent.state, lines, labels);+ if (team) return <BubbleView bubble={team} height={height} range={memory ? Infinity : TEAM_RANGE_M} onClick={open} memory={memory} />;+ // A listener at the board says nothing: its own work bubble would read as a second voice in the round.+ if (listening && !memory) return null;+ const ambient = listening ? null : ambientBubble(agent.state, lines, labels);if (ambient) return <BubbleView bubble={ambient} height={height} range={memory ? Infinity : AMBIENT_RANGE_M} onClick={open} memory={memory} />;// Nothing else to say: the memory receipt alone fills the thought cloud.return memorydiff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeCameraRig.follow.test.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeCameraRig.follow.test.tsxnew file mode 100644index 0000000000..7dd9a9881e--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeCameraRig.follow.test.tsx@@ -0,0 +1,143 @@+import { useEffect, useImperativeHandle } from "react";+import { act, cleanup, render } from "@testing-library/react";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { PerspectiveCamera, Vector3 } from "three";+import { CanvasActivity } from "@/hooks/useCanvasAwake";+import { FOLLOW_DISTANCE, OfficeCameraRig } from "./OfficeCameraRig";+import { cameraLimitsFor } from "./officeCamera";+import { officeSession, player, useOfficeStore } from "./officeStore";+import { campusOf } from "./officeFixtures";++const state = vi.hoisted(() => ({+ frames: new Set<(frame: unknown, dt: number) => void>(),+ renderer: null as unknown as { camera: PerspectiveCamera; size: { width: number; height: number }; gl: { domElement: HTMLCanvasElement }; scene: object; events: { connected: undefined } },+ controls: null as unknown as { target: Vector3; enabled: boolean; update: () => void; mouseButtons: { LEFT: number }; zoomSpeed: number; maxDistance: number },+}));++vi.mock("@react-three/fiber", () => ({+ useThree: (select: (value: typeof state.renderer) => unknown) => select(state.renderer),+ useFrame: (frame: (frame: unknown, dt: number) => void) => {+ useEffect(() => { state.frames.add(frame); return () => { state.frames.delete(frame); }; }, [frame]);+ },+}));+vi.mock("@react-three/drei", async () => {+ const { forwardRef } = await import("react");+ return {+ OrbitControls: forwardRef(({ enabled, maxDistance }: { enabled: boolean; maxDistance: number }, ref) => {+ state.controls.enabled = enabled;+ state.controls.maxDistance = maxDistance;+ useImperativeHandle(ref, () => state.controls);+ return null;+ }),+ };+});++const campus = campusOf(40, [8, 7, 6, 5]);+const originalPlayer = { ...player };++beforeEach(() => {+ state.renderer = {+ camera: new PerspectiveCamera(35, 1.6, 0.2, 800), size: { width: 1280, height: 800 },+ gl: { domElement: document.createElement("canvas") }, scene: {}, events: { connected: undefined },+ };+ state.controls = { target: new Vector3(), enabled: true, update: () => undefined, mouseButtons: { LEFT: 0 }, zoomSpeed: 1, maxDistance: 0 };+ officeSession.camera = null;+ Object.assign(player, { x: campus.layout.spawn.x, z: campus.layout.spawn.z, heading: 0, path: [], moving: false });+ useOfficeStore.setState({ zoom: null, focus: null, follow: true });+});++afterEach(() => {+ cleanup();+ state.frames.clear();+ Object.assign(player, originalPlayer);+ officeSession.camera = null;+});++const tree = (overview: number) => (+ <CanvasActivity.Provider value><OfficeCameraRig layout={campus.layout} overview={overview} /></CanvasActivity.Provider>+);+const frames = (count: number) => act(() => { for (let i = 0; i < count; i += 1) for (const step of state.frames) step(null, 1 / 30); });+const orbit = () => state.renderer.camera.position.distanceTo(state.controls.target);+const offTarget = () => Math.hypot(state.controls.target.x - player.x, state.controls.target.z - player.z);++it("comes back to the walking view when following resumes after the overview", () => {+ const view = render(tree(0));+ frames(5);+ expect(orbit()).toBeCloseTo(FOLLOW_DISTANCE, 1);+ const angle = () => { const c = state.renderer.camera.position, t = state.controls.target; return Math.atan2(c.x - t.x, c.z - t.z); };++ view.rerender(tree(1));+ frames(5);+ // The overview stands a campus away and looks at the middle of the floor.+ expect(orbit()).toBeGreaterThan(60);+ expect(useOfficeStore.getState().follow).toBe(false);+ const from = orbit();+ const yaw = angle();++ act(() => useOfficeStore.getState().setFollow(true));+ frames(3);+ // A glide, not a cut: on its way after a tenth of a second.+ expect(orbit()).toBeLessThan(from);+ expect(orbit()).toBeGreaterThan(FOLLOW_DISTANCE + 5);+ frames(40);+ expect(orbit()).toBeCloseTo(FOLLOW_DISTANCE, 1);+ expect(offTarget()).toBeLessThan(0.05);+ // Only the distance changed: the direction the person looks from stays.+ expect(angle()).toBeCloseTo(yaw, 2);+});++it("keeps a distance the person zoomed to by hand in the overview", () => {+ const view = render(tree(0));+ frames(5);+ view.rerender(tree(1));+ frames(5);+ const chosen = orbit();+ act(() => { state.renderer.gl.domElement.dispatchEvent(new WheelEvent("wheel", { deltaY: 100 })); });+ // Far out a notch zooms further than up close.+ expect(state.controls.zoomSpeed).toBeGreaterThan(4);+ act(() => useOfficeStore.getState().setFollow(true));+ frames(40);+ expect(orbit()).toBeCloseTo(chosen, 1);+ expect(offTarget()).toBeLessThan(0.05);+});++it("lets the wheel reach the overview of this floor", () => {+ render(tree(0));+ expect(state.controls.maxDistance).toBe(cameraLimitsFor(campus.layout.bounds, 1280 / 800).maxDistance);+ expect(state.controls.maxDistance).toBeGreaterThan(100);+});++it("does not restore a remembered view of a place the floor no longer has", () => {+ officeSession.camera = { position: [900, 20, 900], target: [880, 0.8, 880] };+ officeSession.follow = false;+ render(tree(0));+ frames(2);+ // The view starts from the character instead.+ expect(offTarget()).toBeLessThan(0.05);+ expect(orbit()).toBeCloseTo(FOLLOW_DISTANCE, 1);+ expect(useOfficeStore.getState().follow).toBe(true);+});++it("leaves the view where it is when the floor plan is rebuilt (a team was created)", () => {+ // A view remembered from an earlier visit; restoring it again now would be a jump.+ officeSession.camera = { position: [30, 25, 30], target: [10, 0.8, 10] };+ officeSession.follow = false;+ const view = render(tree(0));+ frames(3);+ // The person turns and pans to a view of their own.+ act(() => {+ state.renderer.camera.position.set(-12, 18, 4);+ state.controls.target.set(-20, 0.8, -6);+ useOfficeStore.getState().setFollow(false);+ });+ frames(2);+ const position = state.renderer.camera.position.toArray();+ const target = state.controls.target.toArray();+ // Same floor, new plan: one more team, so a fresh layout object with a fresh `spawn`.+ const rebuilt = campusOf(40, [8, 7, 6, 5, 4]);+ view.rerender(<CanvasActivity.Provider value><OfficeCameraRig layout={rebuilt.layout} overview={0} /></CanvasActivity.Provider>);+ frames(5);+ expect(state.renderer.camera.position.toArray()).toEqual(position);+ expect(state.controls.target.toArray()).toEqual(target);+ expect(useOfficeStore.getState().follow).toBe(false);+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeCameraRig.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeCameraRig.tsxindex 3240c87fed..aa096b1c26 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeCameraRig.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeCameraRig.tsx@@ -7,24 +7,38 @@* into the character's eyes (first person onto the monitors) and back out* when it stands up; asking for the overview or a fly-to stands it up.*+ * The zoom limits and the overview follow the floor's size, so a campus of+ * any extent can be framed whole. While the character stands inside a walled+ * room, the walls the camera looks in through drop to a kerb (wallCutaway.ts).+ ** A press that turned the camera never ends in a click, and the wheel zooms* by how far it turned (see officeCamera.ts).*/-import { useContext, useEffect, useRef } from "react";+import { useContext, useEffect, useMemo, useRef } from "react";+import { useReducedMotion } from "framer-motion";import { CanvasActivity } from "@/hooks/useCanvasAwake";import { OrbitControls } from "@react-three/drei";import { useFrame, useThree } from "@react-three/fiber";-import { MOUSE, Vector3, type PerspectiveCamera } from "three";+import { MOUSE, Vector3, type Object3D, type PerspectiveCamera } from "three";import type { OrbitControls as OrbitControlsImpl } from "three-stdlib";-import { cameraHome, CAMERA_LIMITS, depthNear, DRAG_CLICK_PX, HOME_PITCH_RAD, HOME_YAW_RAD, wheelZoomSpeed } from "./officeCamera";-import { seatOf, type OfficeLayout } from "./officeLayout";+import {+ cameraLimitsFor, campusOverview, CAMERA_LIMITS, depthNear, DRAG_CLICK_PX, FOLLOW_CATCH_UP_M, FOLLOW_DISTANCE_M, followBlend, followDistanceAfterOverview,+ HOME_PITCH_RAD, HOME_YAW_RAD, settleView, wheelZoomSpeed, type CameraPose,+} from "./officeCamera";+import { seatOf, wallRect, type OfficeLayout, type WallSegment } from "./officeLayout";+import { cutawayStep, cutawayWalls, wallKey } from "./wallCutaway";import { useLeadSeat } from "./leadSeat";import { cameraView, officeSession, player, useOfficeStore } from "./officeStore";import "./officeCameraRig.css";/** Where the camera starts: close behind the character, south-east, looking down. */-export const FOLLOW_DISTANCE = 15;+export const FOLLOW_DISTANCE = FOLLOW_DISTANCE_M;const TARGET_HEIGHT = 0.8;+/** How often the scene is searched for wall objects, and how often the cutaway is decided (seconds). */+const WALL_SCAN_S = 1;+const CUTAWAY_CHECK_S = 0.12;+/** How long the glide back to a far-away character takes when following resumes. */+const CATCH_UP_SECONDS = 0.6;/** How long the dive into a monitor takes before the chat opens. */export const ZOOM_SECONDS = 1.15;/** Monitor screen size in metres (see LiveMonitors): the dive ends with it filling the view. */@@ -53,8 +67,21 @@ export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; ovconst scene = useThree((s) => s.scene);// The element R3F and the orbit controls listen on (the canvas wrapper, which also holds the <Html> labels).const connected = useThree((s) => s.events.connected) as HTMLElement | undefined;+ const reduced = useReducedMotion() ?? false;+ // The wheel may back away far enough to frame this floor whole, however large it is.+ const aspect = size.width / Math.max(1, size.height);+ const limits = useMemo(() => cameraLimitsFor(layout.bounds, aspect), [layout.bounds, aspect]);const lastFocus = useRef(0);const lastZoom = useRef(0);+ // Following resumed far from the character: glide over instead of snapping across the floor.+ // The glide can also bring the camera back to a walking distance (after the overview).+ const catchUp = useRef<{ from: Vector3; t: number; fromDistance: number; toDistance: number } | null>(null);+ const wasFollowing = useRef(false);+ // The orbit distance before the overview took the camera away; cleared once the person zooms by hand.+ const beforeOverview = useRef<number | null>(null);+ // A remembered view is only restored where it still makes sense on this floor plan.+ const wallRects = useMemo(() => layout.walls.map(wallRect), [layout.walls]);+ const settle = (pose: CameraPose) => settleView(pose, layout.bounds, wallRects);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);@@ -150,11 +177,20 @@ export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; ovif (beforeSeat) { (camera as PerspectiveCamera).fov = beforeSeat.fov; (camera as PerspectiveCamera).updateProjectionMatrix(); }}, [camera]);- // Start where the last visit left off, or close to the character.+ // Start where the last visit left off, or close to the character. This runs when the map comes on screen and+ // when the floor changes (an elevator ride), never because the floor plan was rebuilt: creating or renaming a+ // team while the person looks at the map must leave the view where it is.+ const floorKey = layout.variant;+ const startedOn = useRef<string | null>(null);useEffect(() => {- if (!active) return;+ if (!active) { startedOn.current = null; return; }if (import.meta.env.DEV) (window as unknown as Record<string, unknown>).__office = { camera, controls: controls.current, gl, scene };- const saved = officeSession.camera;+ // The remembered view belongs to the floor the map was left on: after a ride the view starts from the character.+ const rode = startedOn.current !== null && startedOn.current !== floorKey;+ startedOn.current = floorKey;+ // The floor plan may have been rebuilt since the view was remembered: a view of a place that is gone+ // starts from the character instead, and a camera that would stand in a wall backs out of it.+ const saved = !rode && officeSession.camera ? settle(officeSession.camera) : null;if (saved) {camera.position.set(...saved.position);controls.current?.target.set(...saved.target);@@ -169,15 +205,20 @@ export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; ovcontrols.current?.target.copy(target);controls.current?.update();useOfficeStore.getState().setFollow(true);- }, [camera, gl, scene, layout.spawn, active]);+ // `settle` reads the plan of the render that runs this effect; a rebuilt plan alone must not run it again.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [camera, gl, scene, floorKey, active]);// "Overview": frame the whole floor and stop following.useEffect(() => {if (!active || overview === 0) return;// Seated in first person the glide would keep the camera in the chair: stand up first.if (seated.current.blend > 0 || (layout.command && useLeadSeat.getState().seated === layout.command.id)) leaveFirstPerson();- const home = cameraHome(layout.bounds, size.width / Math.max(1, size.height));+ const home = campusOverview(layout.bounds, size.width / Math.max(1, size.height));+ // "Follow me" comes back to the view the person walked in, not to a view from across the campus.+ if (controls.current) beforeOverview.current ??= camera.position.distanceTo(controls.current.target);flight.current = null;+ catchUp.current = null;useOfficeStore.getState().setFollow(false);camera.position.set(...home.position);controls.current?.target.set(...home.target);@@ -235,7 +276,12 @@ export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; ovevent.preventDefault();};const wheel = (event: WheelEvent) => {- if (controls.current) controls.current.zoomSpeed = wheelZoomSpeed(event.deltaY, event.deltaMode);+ const c = controls.current;+ if (!c) return;+ // Far out a notch covers more of the way, so a large floor zooms in a few notches.+ c.zoomSpeed = wheelZoomSpeed(event.deltaY, event.deltaMode, camera.position.distanceTo(c.target));+ // The person chose a distance: following keeps it from here on.+ beforeOverview.current = null;};el.addEventListener("pointerdown", down, true);window.addEventListener("pointermove", move, true);@@ -251,6 +297,53 @@ export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; ov};}, [connected, gl, active]);+ // Inside a walled room the walls between camera and character drop to a kerb, so the room stays readable.+ // Walls are whatever the scene tags with `userData.officeWall`; an untagged wall is simply never moved.+ const walls = useRef<{ object: Object3D; key: string }[]>([]);+ const wallScan = useRef(0);+ const cutCheck = useRef(0);+ const cut = useRef<Set<string>>(new Set());+ useEffect(() => {+ // A new floor plan brings new wall objects: look again at once.+ wallScan.current = 0;+ cutCheck.current = 0;+ return () => {+ for (const wall of walls.current) wall.object.scale.y = 1;+ walls.current = [];+ };+ }, [layout]);+ useFrame((frame, rawDt) => {+ if (!active || typeof (scene as Partial<Object3D>).traverse !== "function") return;+ const t = frame.clock.elapsedTime;+ if (t >= wallScan.current) {+ wallScan.current = t + WALL_SCAN_S;+ const found: { object: Object3D; key: string }[] = [];+ scene.traverse((object) => {+ const wall = object.userData?.officeWall as WallSegment | undefined;+ if (wall && typeof wall.x1 === "number") found.push({ object, key: wallKey(wall) });+ });+ walls.current = found;+ }+ if (walls.current.length === 0) return;+ if (t >= cutCheck.current) {+ cutCheck.current = t + CUTAWAY_CHECK_S;+ // First person looks out of the room from inside it: nothing is in the way.+ cut.current = cameraView.firstPerson ? new Set() : cutawayWalls(layout.rooms, layout.walls, player, { x: camera.position.x, z: camera.position.z });+ }+ const dt = Math.min(rawDt, 0.1);+ for (const wall of walls.current) {+ const next = cutawayStep(wall.object.scale.y, cut.current.has(wall.key), dt, reduced);+ if (next !== wall.object.scale.y) wall.object.scale.y = next;+ }+ });+ useEffect(() => {+ if (!import.meta.env.DEV || !active) return;+ // Dev-only: the walls lowered right now, how many wall objects are tagged, and this floor's zoom limits.+ (window as unknown as Record<string, unknown>).__officeCamera = {+ cut: () => [...cut.current], walls: () => walls.current.length, limits: () => limits,+ };+ }, [active, limits]);+// The near plane follows the zoom, or coplanar layers (oak over slab) fight in bands when zoomed out.useFrame(() => {if (!active) return;@@ -343,7 +436,8 @@ export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; ovdive.current = null;// If the chat does not take over (no handler), return to the view before the dive.backOff.current = setTimeout(() => {- const back = preDive.current;+ // Back to the view before the dive, unless the floor plan changed under it meanwhile.+ const back = preDive.current ? settle(preDive.current) : null;if (back) { camera.position.set(...back.position); c.target.set(...back.target); }else camera.position.copy(c.target).add(camera.position.clone().sub(c.target).setLength(CAMERA_LIMITS.minDistance + 1));preDive.current = null;@@ -357,6 +451,8 @@ export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; ovlastFocus.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 };}+ // Set while a glide also brings the camera back to a walking distance.+ let zoomTo: number | null = null;if (flight.current) {const f = flight.current;f.t = Math.min(1, f.t + dt / 0.7);@@ -365,20 +461,47 @@ export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; ovif (f.t >= 1) flight.current = null;} else if (store.follow) {desired.current.set(player.x, TARGET_HEIGHT, player.z);- desired.current.lerp(c.target, Math.exp(-8 * dt));+ // Following resumed (the "follow me" button, a step after a pan) far from the character: one eased glide over.+ if (!wasFollowing.current) {+ const orbit = camera.position.distanceTo(c.target);+ const back = beforeOverview.current;+ beforeOverview.current = null;+ if (back !== null || desired.current.distanceTo(c.target) > FOLLOW_CATCH_UP_M) {+ catchUp.current = { from: c.target.clone(), t: 0, fromDistance: orbit, toDistance: back !== null ? followDistanceAfterOverview(back) : orbit };+ }+ }+ const glide = catchUp.current;+ if (glide) {+ glide.t = Math.min(1, glide.t + dt / CATCH_UP_SECONDS);+ const ease = glide.t < 0.5 ? 2 * glide.t * glide.t : 1 - (-2 * glide.t + 2) ** 2 / 2;+ desired.current.lerpVectors(glide.from, desired.current, ease);+ zoomTo = glide.fromDistance + (glide.toDistance - glide.fromDistance) * ease;+ if (glide.t >= 1) catchUp.current = null;+ } else {+ // Exponential, so the motion is the same at any frame rate and eases out when the character stops.+ desired.current.lerpVectors(c.target, desired.current, followBlend(dt));+ }} else {+ wasFollowing.current = false;+ catchUp.current = null;return;}+ wasFollowing.current = store.follow && !flight.current;// Move camera and target together: rotation and zoom stay what the person chose.delta.current.copy(desired.current).sub(c.target);c.target.add(delta.current);camera.position.add(delta.current);+ if (zoomTo !== null) {+ // Along the line of sight, so the angle the person chose stays.+ delta.current.copy(camera.position).sub(c.target).setLength(zoomTo);+ camera.position.copy(c.target).add(delta.current);+ }c.update();});return (<OrbitControls ref={controls} makeDefault enabled={active} enableDamping dampingFactor={0.12} screenSpacePanning={false}minPolarAngle={CAMERA_LIMITS.minPolar} maxPolarAngle={CAMERA_LIMITS.maxPolar}- minDistance={CAMERA_LIMITS.minDistance} maxDistance={CAMERA_LIMITS.maxDistance} />+ minDistance={limits.minDistance} maxDistance={limits.maxDistance} />);}diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeChairs.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeChairs.tsxindex 8344b52e33..a6af8ba5d9 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeChairs.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeChairs.tsx@@ -2,14 +2,13 @@* The office's chairs, built once as merged geometry so every copy costs a* handful of draw calls however much detail a chair carries.*- * - The desk task chair is an ergonomic mesh chair in the Aeron / Gesture- * class: a sculpted seat with a waterfall front edge, a curved mesh back in+ * - The desk task chair is an ergonomic mesh chair: a sculpted seat with a+ * waterfall front edge, a curved mesh back in* a black frame with a lumbar pad, T-arms with soft pads, a gas lift in its* sleeve and a polished five-star base on twin-wheel casters. It is exported* as a part list (`TASK_CHAIR_PARTS`) that `DeskInstances` instances per desk.- * - The meeting chair is a soft-pad conference chair after the Eames- * Aluminium Group: stitched leather pads slung between polished side rails- * on a four-star base.+ * - The meeting chair is a soft-pad conference chair: stitched leather pads+ * slung between polished side rails on a four-star base.** Both keep the seat top where the seated pose expects it (0.52 m at a desk,* 0.50 m at the table) and stay inside a chair's 0.29 m reach from the column.@@ -68,12 +67,12 @@ function smooth(geometry: BufferGeometry): BufferGeometry {}/** A round tube along a smooth curve through `points`; callers squash it with a scale to make a blade. */-function tube(points: Vec3[], radius: number, closed = false, segments = 32): BufferGeometry {+function tube(points: Vec3[], radius: number, closed = false, segments = 14): BufferGeometry {const curve = new CatmullRomCurve3(points.map((p) => new Vector3(...p)), closed, "centripetal");- return new TubeGeometry(curve, segments, radius, 8, closed);+ return new TubeGeometry(curve, segments, radius, 5, closed);}-const rounded = (w: number, h: number, d: number, r: number) => new RoundedBoxGeometry(w, h, d, 2, r);+const rounded = (w: number, h: number, d: number, r: number) => new RoundedBoxGeometry(w, h, d, 1, r);// ---------------------------------------------------------------------------// Shared base pieces@@ -128,7 +127,7 @@ function seatCushion(): BufferGeometry {s.quadraticCurveTo(0.196, 0.514, 0.198, 0.494);s.lineTo(0.19, 0.466);const depth = 0.43;- const g = new ExtrudeGeometry(s, { depth, bevelEnabled: true, bevelThickness: 0.028, bevelSize: 0.012, bevelSegments: 3, curveSegments: 8 });+ const g = new ExtrudeGeometry(s, { depth, bevelEnabled: true, bevelThickness: 0.028, bevelSize: 0.012, bevelSegments: 1, curveSegments: 5 });// Extruded along z; turn it so the profile's first axis becomes local z and the width runs along x.g.applyMatrix4(new Matrix4().makeRotationY(-Math.PI / 2));g.translate(depth / 2, 0, 0);@@ -153,7 +152,7 @@ function backPoint(s: number, t: number, inset = 0): Vector3 {}function backPanel(): BufferGeometry {- const g = new PlaneGeometry(1, 1, 12, 8);+ const g = new PlaneGeometry(1, 1, 6, 4);const pos = g.getAttribute("position");for (let i = 0; i < pos.count; i += 1) {const p = backPoint(pos.getX(i) * 2, pos.getY(i) + 0.5);@@ -177,7 +176,7 @@ function backFrame(): BufferGeometry {edge([1, 0], [1, 1], 6);edge([1, 1], [-1, 1], 6);edge([-1, 1], [-1, 0], 6);- return tube(points, 0.015, true, 96);+ return tube(points, 0.015, true, 36);}/** A rounded box bent round the backrest's curve at height `t`, standing `inset` in front of the mesh. */@@ -255,7 +254,8 @@ const TASK_METAL = merged([/** The ergonomic desk chair, one entry per draw call. */export const TASK_CHAIR_PARTS: ChairPart[] = [{ finish: "metal", geometry: TASK_METAL, cast: true },- { finish: "frame", geometry: TASK_FRAME, cast: true },+ // The frame is arms, spine and casters: the seat and the back panel already throw the chair's shadow.+ { finish: "frame", geometry: TASK_FRAME, cast: false },{ finish: "fabric", geometry: seatCushion(), cast: true },// Lumbar pad in the seat fabric across the small of the back.{ finish: "fabric", geometry: bentPad(0.34, 0.07, 0.022, 0.2, 0.014), cast: false },@@ -304,7 +304,7 @@ const MEETING_METAL = merged([...starBase(4, 0.29, 0.1),[new CylinderGeometry(0.024, 0.024, 0.32, 16), at([0, 0.27, 0])],// Side rails, flattened into blades, and the spreaders that tie them together.- ...[-1, 1].map((side): [BufferGeometry, Matrix4] => [tube(RAIL, 0.02, false, 40), at([side * RAIL_X, 0, 0], [0, 0, 0], [0.55, 1, 1])]),+ ...[-1, 1].map((side): [BufferGeometry, Matrix4] => [tube(RAIL, 0.02, false, 24), at([side * RAIL_X, 0, 0], [0, 0, 0], [0.55, 1, 1])]),[new BoxGeometry(RAIL_X * 2, 0.02, 0.05), at([0, 0.44, -0.02])],[new BoxGeometry(RAIL_X * 2, 0.03, 0.02), at([0, 0.8, -0.3], [BACK_TILT, 0, 0])],// Arm posts rising off the rails.diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeCompass.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeCompass.tsxdeleted file mode 100644index a1c45474b2..0000000000--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeCompass.tsx+++ /dev/null@@ -1,158 +0,0 @@-/**- * The compass bar, game style: a strip at the top centre of the stage that- * shows where the camera faces (N/NE/E/… letters, a tick every 15°, a centre- * marker and the heading in degrees), plus small pips for the selected agent- * and the checkpoints at their bearing from the person's character.- *- * Drawn on a canvas at ≤ 20 Hz from the per-frame module state (`cameraView`,- * `player`, `agentPositions`); colours come from theme tokens, so light and- * dark mode both work. Pauses while the document is hidden.- */-import { useCallback, useEffect, useRef } from "react";-import { useT } from "@/i18n";-import type { OfficeLayout } from "./officeLayout";-import { cameraView, player } from "./officeStore";-import { agentPositions } from "./walkerRegistry";-import { MAP_PAINT, bearingOf, compassPosition, compassTicks, relativeBearing, yawToBearing, type CompassPoint } from "./minimap";-import { agentColour, context2d, tokenColour, useElementSize, usePixelRatio, useThemeVersion, useThrottledFrames, type OfficeMapAgent } from "./mapHooks";--export interface OfficeCompassProps {- layout: OfficeLayout;- agents: ReadonlyMap<string, OfficeMapAgent>;- selectedId: string | null;-}--/** Degrees visible across the bar. */-const SPAN_DEG = 150;-const FRAME_MS = 50;--interface CompassColours { ink: string; muted: string; tick: string; marker: string; rim: string }--export function OfficeCompass({ layout, agents, selectedId }: OfficeCompassProps) {- const t = useT();- const rootRef = useRef<HTMLDivElement>(null);- const canvasRef = useRef<HTMLCanvasElement>(null);- const readoutRef = useRef<HTMLSpanElement>(null);- const coloursRef = useRef<CompassColours | null>(null);- const size = useElementSize(canvasRef);- const dpr = usePixelRatio();- const themeVersion = useThemeVersion();-- const letters: Record<CompassPoint, string> = {- n: t("society.office.compass_n"), ne: t("society.office.compass_ne"), e: t("society.office.compass_e"),- se: t("society.office.compass_se"), s: t("society.office.compass_s"), sw: t("society.office.compass_sw"),- w: t("society.office.compass_w"), nw: t("society.office.compass_nw"),- };-- const live = useRef({ layout, agents, selectedId, size, letters });- live.current = { layout, agents, selectedId, size, letters };-- useEffect(() => {- const root = rootRef.current;- const style = root ? getComputedStyle(root) : null;- coloursRef.current = {- ink: tokenColour(style, "--popover-foreground", "#111827"),- muted: tokenColour(style, "--muted-foreground", "#6b7280"),- tick: tokenColour(style, "--muted-foreground", "#6b7280", 0.7),- marker: MAP_PAINT.checkpoint,- rim: tokenColour(style, "--popover", "#ffffff"),- };- }, [themeVersion]);-- const draw = useCallback(() => {- const canvas = canvasRef.current;- const ctx = context2d(canvas);- const colours = coloursRef.current;- const { layout: lay, agents: roster, selectedId: sel, size: box, letters: names } = live.current;- if (!canvas || !ctx || !colours || box.width <= 0 || box.height <= 0) return;- const w = box.width;- const h = box.height;- const ratio = canvas.width / w;- ctx.setTransform(ratio, 0, 0, ratio, 0, 0);- ctx.clearRect(0, 0, w, h);- const heading = cameraView.ready ? yawToBearing(cameraView.yaw) : yawToBearing(player.heading);- if (readoutRef.current) readoutRef.current.textContent = `${Math.round(heading) % 360}°`;-- ctx.textAlign = "center";- ctx.textBaseline = "middle";- for (const tick of compassTicks(heading, SPAN_DEG, 15)) {- const x = Math.round(tick.at * w) + 0.5;- if (tick.point) {- const main = tick.point.length === 1;- ctx.fillStyle = tick.point === "n" ? MAP_PAINT.checkpointDeep : colours.ink;- ctx.font = `${main ? 800 : 700} ${main ? 14 : 11}px system-ui, -apple-system, "Segoe UI", sans-serif`;- ctx.fillText(names[tick.point], x, h * 0.42);- ctx.fillStyle = colours.tick;- ctx.fillRect(x - 0.5, h - 7, 1, 5);- } else {- ctx.fillStyle = colours.tick;- ctx.fillRect(x - 0.5, h - 6, 1, 4);- ctx.fillStyle = colours.muted;- ctx.font = `600 9px system-ui, -apple-system, "Segoe UI", sans-serif`;- ctx.fillText(String(Math.round(tick.deg)), x, h * 0.42);- }- }-- // Checkpoint pips: small gold diamonds on the bottom edge.- for (const cp of lay.checkpoints) {- const at = compassPosition(bearingOf(cp.x - player.x, cp.z - player.z), heading, SPAN_DEG);- if (at === null) continue;- const x = at * w;- ctx.beginPath();- ctx.moveTo(x, h - 9);- ctx.lineTo(x + 3.2, h - 5.5);- ctx.lineTo(x, h - 2);- ctx.lineTo(x - 3.2, h - 5.5);- ctx.closePath();- ctx.fillStyle = MAP_PAINT.checkpoint;- ctx.fill();- }-- // The selected agent: a pip in its colour, pinned to the nearer end when out of view.- const agent = sel ? roster.get(sel) : undefined;- const pos = sel ? agentPositions.get(sel) : undefined;- if (agent && pos) {- const bearing = bearingOf(pos.x - player.x, pos.z - player.z);- const inView = compassPosition(bearing, heading, SPAN_DEG);- const at = inView ?? (relativeBearing(bearing, heading) < 0 ? 0.02 : 0.98);- const x = at * w;- ctx.globalAlpha = inView === null ? 0.6 : 1;- ctx.beginPath();- ctx.arc(x, h - 6, 4.2, 0, Math.PI * 2);- ctx.fillStyle = agentColour(agent);- ctx.fill();- ctx.strokeStyle = colours.rim;- ctx.lineWidth = 1.5;- ctx.stroke();- ctx.globalAlpha = 1;- }-- // Centre marker: a gold notch at the top.- ctx.beginPath();- ctx.moveTo(w / 2 - 5, 0);- ctx.lineTo(w / 2 + 5, 0);- ctx.lineTo(w / 2, 6);- ctx.closePath();- ctx.fillStyle = colours.marker;- ctx.fill();- }, []);-- // Size the backing store to the measured CSS size and pixel ratio.- useEffect(() => {- const canvas = canvasRef.current;- if (!canvas || size.width <= 0 || size.height <= 0) return;- canvas.width = Math.round(size.width * dpr);- canvas.height = Math.round(size.height * dpr);- draw();- }, [size, dpr, themeVersion, draw]);-- useThrottledFrames(draw, FRAME_MS, size.width > 0);-- return (- <div ref={rootRef} className="office-hud office-compass" data-office-ui role="img"- aria-label={t("society.office.compass_label")}>- <canvas ref={canvasRef} className="office-compass-canvas" aria-hidden />- <span ref={readoutRef} className="office-compass-readout" aria-hidden />- </div>- );-}diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeFullMap.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeFullMap.tsxindex 54f1c064af..e7a913b877 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeFullMap.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeFullMap.tsx@@ -13,13 +13,13 @@ import { useCallback, useEffect, useId, useMemo, useRef, useState, type Keyboardimport { X } from "lucide-react";import { useReducedMotion } from "framer-motion";import { useT } from "@/i18n";-import type { CheckpointKind, OfficeLayout, Rect, RoomKind } from "./officeLayout";+import type { CampusZoneKind, CheckpointKind, OfficeLayout, Rect, RoomKind } from "./officeLayout";import { cameraView, player, useOfficeStore } from "./officeStore";import { agentPositions } from "./walkerRegistry";import { ownsKeyboard } from "./OfficePlayer";import {MAP_PAINT, clampToRect, columnLabel, drawAgentToken, drawCheckpointBadge, drawFloorArt, drawMapLabel, drawPlayerArrow,- drawViewCone, fitTransform, gridLabel, mapGrid, mapToWorld, placeAt, worldToMap, type AgentToken, type MapPoint, type MapTransform,+ drawViewCone, fitSheet, fitTransform, gridLabel, mapGrid, mapToWorld, placeAt, worldToMap, type AgentToken, type MapPoint, type MapTransform,} from "./minimap";import {agentColour, context2d, offscreenLayer, useElementSize, usePixelRatio, useThemeVersion, useThrottledFrames, type OfficeMapAgent,@@ -84,6 +84,8 @@ function FullMapDialog({ onClose, layout, agents, selectedId }: Omit<OfficeFullMconst reduced = useReducedMotion() ?? false;const titleId = useId();const hintId = useId();+ const backdropRef = useRef<HTMLDivElement>(null);+ const headRef = useRef<HTMLElement>(null);const dialogRef = useRef<HTMLDivElement>(null);const closeRef = useRef<HTMLButtonElement>(null);const bodyRef = useRef<HTMLDivElement>(null);@@ -98,6 +100,15 @@ function FullMapDialog({ onClose, layout, agents, selectedId }: Omit<OfficeFullMconst gridRect = useMemo<Rect>(() => ({minX: grid.originX, maxX: grid.originX + grid.columns * grid.cell, minZ: grid.originZ, maxZ: grid.originZ + grid.rows * grid.cell,}), [grid]);+ // The sheet takes the plan's shape: a floor that is nearly square or taller than wide leaves no empty band beside it.+ const outer = useElementSize(backdropRef);+ const head = useElementSize(headRef);+ const sheet = useMemo(() => {+ // The backdrop pads 3 % of its width on every side.+ const inset = outer.width * 0.03;+ const availW = outer.width - inset * 2, availH = outer.height - inset * 2;+ return availW > 200 && availH > 200 ? fitSheet(gridRect, availW, availH, GRID_PAD, head.height || 46) : null;+ }, [outer, head.height, gridRect]);const transform = useMemo<MapTransform | null>(() => (size.width > GRID_PAD * 2 && size.height > GRID_PAD * 2 ? fitTransform(gridRect, size.width, size.height, GRID_PAD) : null),[gridRect, size],@@ -134,11 +145,22 @@ function FullMapDialog({ onClose, layout, agents, selectedId }: Omit<OfficeFullMsnack: t("society.office.room_snack"),levels: t("society.office.room_levels"),};- const openSpace = t("society.office.open_space");+ // Agents floor: the campus between the studios. The pool studio has no team name; the map gives it one.+ const zoneLabels: Record<CampusZoneKind, string> = {+ boulevard: t("society.office.zone_boulevard"),+ plaza: t("society.office.zone_boulevard"),+ atrium: t("society.office.zone_atrium"),+ plot: t("society.office.zone_plot"),+ garden: t("society.office.zone_garden"),+ booths: t("society.office.zone_booths"),+ library: t("society.office.zone_library"),+ cafe: t("society.office.zone_cafe"),+ };+ const openSpace = t(layout.variant === "agents" ? "society.office.studio_pool" : "society.office.open_space");const youLabel = t("society.office.minimap_you");- const labelKey = JSON.stringify([checkpointLabels, roomLabels, openSpace]);- const labels = useRef({ checkpointLabels, roomLabels, openSpace, youLabel });- labels.current = { checkpointLabels, roomLabels, openSpace, youLabel };+ const labelKey = JSON.stringify([checkpointLabels, roomLabels, zoneLabels, openSpace]);+ const labels = useRef({ checkpointLabels, roomLabels, zoneLabels, openSpace, youLabel });+ labels.current = { checkpointLabels, roomLabels, zoneLabels, openSpace, youLabel };// Focus moves into the dialog and returns to where it was on close.useEffect(() => {@@ -220,15 +242,24 @@ function FullMapDialog({ onClose, layout, agents, selectedId }: Omit<OfficeFullM}ctx.stroke();- const { roomLabels: rooms, checkpointLabels: cps, openSpace: spare } = labels.current;+ const { roomLabels: rooms, checkpointLabels: cps, zoneLabels: zoneNames, openSpace: spare } = labels.current;const roomPx = Math.max(11, Math.min(15, transform.scale * 0.75));+ // The campus's own places, quieter than rooms and studios; the streets need no name.+ for (const zone of layout.zones ?? []) {+ if (zone.kind === "boulevard" || zone.kind === "plaza") continue;+ // Along the zone's south edge: its seats and tables stay readable, and the atrium's name sits under the spawn point.+ const c = worldToMap(transform, { x: (zone.minX + zone.maxX) / 2, z: zone.maxZ - 0.9 });+ drawMapLabel(ctx, zoneNames[zone.kind], c.x, c.y, roomPx * 0.8, 700, (zone.maxX - zone.minX - 0.6) * transform.scale);+ }for (const room of layout.rooms) {const c = worldToMap(transform, { x: (room.minX + room.maxX) / 2, z: room.minZ + 1.1 });drawMapLabel(ctx, rooms[room.kind].toLocaleUpperCase(), c.x, c.y, roomPx, 800);}+ // A studio's name stands on the street behind its name wall, clear of everyone working inside, and never+ // wider than the studio itself.for (const dept of layout.departments) {- const c = worldToMap(transform, { x: (dept.minX + dept.maxX) / 2, z: dept.minZ + 0.9 });- drawMapLabel(ctx, (dept.label || spare).toLocaleUpperCase(), c.x, c.y, roomPx * 0.85, 800);+ const c = worldToMap(transform, { x: (dept.minX + dept.maxX) / 2, z: dept.minZ - 1.0 });+ drawMapLabel(ctx, (dept.label || spare).toLocaleUpperCase(), c.x, c.y, roomPx * 0.85, 800, (dept.maxX - dept.minX - 0.6) * transform.scale);}const badge = Math.max(14, Math.min(22, transform.scale * 1.1));for (const cp of layout.checkpoints) {@@ -265,7 +296,8 @@ function FullMapDialog({ onClose, layout, agents, selectedId }: Omit<OfficeFullMconst place = placeAt(layout, world);const name = place?.kind === "checkpoint" ? checkpointLabels[place.id]: place?.kind === "room" ? roomLabels[place.id]- : place?.kind === "department" ? place.label || openSpace : "";+ : place?.kind === "department" ? place.label || openSpace+ : place?.kind === "zone" ? zoneLabels[place.id] : "";const next = { cell: gridLabel(grid, world), place: name };setReadout((prev) => (prev && prev.cell === next.cell && prev.place === next.place ? prev : next));};@@ -281,10 +313,11 @@ function FullMapDialog({ onClose, layout, agents, selectedId }: Omit<OfficeFullMconst cellPx = transform ? grid.cell * transform.scale : 0;return (- <div className="office-fullmap-backdrop" data-office-ui onMouseDown={(event) => { if (event.target === event.currentTarget) onClose(); }}>+ <div ref={backdropRef} className="office-fullmap-backdrop" data-office-ui onMouseDown={(event) => { if (event.target === event.currentTarget) onClose(); }}><div ref={dialogRef} className="office-card office-fullmap" role="dialog" aria-modal="true" data-state="open"- aria-labelledby={titleId} aria-describedby={hintId} onKeyDown={onKeyDown}>- <header className="office-fullmap-head">+ aria-labelledby={titleId} aria-describedby={hintId} onKeyDown={onKeyDown}+ style={sheet ? { width: sheet.width, height: sheet.height } : undefined}>+ <header ref={headRef} className="office-fullmap-head"><div className="office-fullmap-heading"><h2 id={titleId}>{t("society.office.map_title")}</h2><span id={hintId}>{t("society.office.map_hint")}</span>diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeFurniture.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeFurniture.tsxindex bde5a400a6..6d1345d41b 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeFurniture.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeFurniture.tsx@@ -7,7 +7,7 @@*/import { useMemo } from "react";import {- BoxGeometry, CylinderGeometry, DoubleSide, IcosahedronGeometry, MeshStandardMaterial, RepeatWrapping, type Texture,+ BoxGeometry, CylinderGeometry, DoubleSide, IcosahedronGeometry, OctahedronGeometry, MeshStandardMaterial, RepeatWrapping, type Texture,} from "three";import { RoundedBoxGeometry } from "three-stdlib";import { cachedCanvasTexture } from "./canvasMaterials";@@ -58,6 +58,10 @@ export const GEO = {potCyl: new CylinderGeometry(1, 0.8, 1, 16),// One subdivision: foliage reads as soft clusters rather than faceted low-poly rocks.blob: new IcosahedronGeometry(1, 1),+ // Twenty faces: for foliage that is flat-shaded anyway, and for anything drawn by the hundred.+ facet: new IcosahedronGeometry(1, 0),+ // A blade of grass: a slim four-sided spindle, eight faces.+ blade: new OctahedronGeometry(1, 0),};export function Box({ size, position, material, cast = true }: {@@ -66,7 +70,10 @@ export function Box({ size, position, material, cast = true }: {return <mesh geometry={GEO.box} material={material} position={position} scale={size} castShadow={cast} receiveShadow />;}-/** Rounded boxes are cached by size: every desk shares the same few geometries. */+/**+ * Rounded boxes are cached by size: every desk shares the same few geometries. One bevel segment: the corners are+ * a few centimetres at most, and a second segment tripled the triangles of every piece of furniture on the floor.+ */const roundedCache = new Map<string, RoundedBoxGeometry>();export function Rounded({ size, radius, position, material, cast = true }: {size: [number, number, number]; radius: number; position: [number, number, number]; material: MeshStandardMaterial; cast?: boolean;@@ -74,7 +81,7 @@ export function Rounded({ size, radius, position, material, cast = true }: {const key = `${size.join("x")}:${radius}`;let geometry = roundedCache.get(key);if (!geometry) {- geometry = new RoundedBoxGeometry(size[0], size[1], size[2], 2, radius);+ geometry = new RoundedBoxGeometry(size[0], size[1], size[2], 1, radius);roundedCache.set(key, geometry);}return <mesh geometry={geometry} material={material} position={position} castShadow={cast} receiveShadow />;diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeHud.test.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeHud.test.tsxnew file mode 100644index 0000000000..62d5833156--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeHud.test.tsx@@ -0,0 +1,265 @@+import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";+import { afterEach, beforeAll, beforeEach, describe, expect, test, vi } from "vitest";+import { loadLocaleChunk, useT } from "@/i18n";+import { buildOfficeLayout, type OfficeLayout, type Studio } from "./officeLayout";+import { useOfficeStore } from "./officeStore";+import { ControlHints, OfficeTools, StationPrompt, stationAction, stationLabel } from "./OfficeHud";+import { stationsFor } from "./stations";+import { DEFAULT_OFFICE_SETTINGS, loadOfficeSettings, useOfficeSettings } from "./officeSettings";++const layout = buildOfficeLayout([+ { agentId: "a1", name: "Ada", tier: "specialist", providerLabel: "Codex", state: "idle", createdMs: 1 },+]);++beforeAll(async () => { await loadLocaleChunk("society"); });+beforeEach(() => {+ localStorage.clear();+ useOfficeStore.setState({ selection: null, hover: null, walkTo: null });+ useOfficeSettings.setState({ ...DEFAULT_OFFICE_SETTINGS });+});+afterEach(cleanup);++function tools(overrides: Partial<Parameters<typeof OfficeTools>[0]> = {}) {+ const props = {+ layout, follow: false, onFollow: vi.fn(), onOverview: vi.fn(), helpOpen: false, onHelp: vi.fn(),+ list: { label: "Agents list", ide: false, onOpen: vi.fn() }, ...overrides,+ };+ render(<OfficeTools {...props} />);+ return props;+}++describe("office toolbar", () => {+ test("is a handful of named icon buttons, each doing its one thing", () => {+ const props = tools();+ const bar = screen.getByRole("toolbar", { name: "Map tools" });+ expect(within(bar).getAllByRole("button").map((b) => b.getAttribute("aria-label"))).toEqual([+ "Follow me", "Overview", "Places", "Agents list", "Help & settings",+ ]);+ fireEvent.click(screen.getByRole("button", { name: "Follow me" }));+ fireEvent.click(screen.getByRole("button", { name: "Overview" }));+ fireEvent.click(screen.getByRole("button", { name: "Agents list" }));+ fireEvent.click(screen.getByRole("button", { name: "Help & settings" }));+ expect(props.onFollow).toHaveBeenCalledOnce();+ expect(props.onOverview).toHaveBeenCalledOnce();+ expect(props.list?.onOpen).toHaveBeenCalledOnce();+ expect(props.onHelp).toHaveBeenCalledOnce();+ // The help key is announced, and shown in the button's label on hover.+ const help = screen.getByRole("button", { name: "Help & settings" });+ expect(help.getAttribute("aria-keyshortcuts")).toBe("H");+ expect(help.dataset.tip).toBe("Help & settings (H)");+ });++ test("shows what is on: following, the open directory; and no list on a floor without one", () => {+ tools({ follow: true, helpOpen: true, list: null });+ expect(screen.getByRole("button", { name: "Follow me" }).getAttribute("aria-pressed")).toBe("true");+ expect(screen.getByRole("button", { name: "Help & settings" }).getAttribute("aria-pressed")).toBe("true");+ expect(screen.queryByRole("button", { name: "Agents list" })).toBeNull();+ });++ test("the places menu reaches every station by keyboard: open one, or walk there", () => {+ tools();+ const trigger = screen.getByRole("button", { name: "Places" });+ expect(trigger.getAttribute("aria-expanded")).toBe("false");+ fireEvent.click(trigger);+ expect(trigger.getAttribute("aria-expanded")).toBe("true");+ const menu = screen.getByRole("group", { name: "Places" });+ // One "open" and one "walk there" button per station of the floor, the reception among them.+ expect(within(menu).getAllByRole("button")).toHaveLength(stationsFor(layout).length * 2);+ expect(within(menu).getByRole("button", { name: "Reception: Open the directory" })).toBeTruthy();++ // Resting on a place lights its object in the world.+ const open = within(menu).getByRole("button", { name: "Team room: Manage teams" });+ fireEvent.focus(open);+ expect(useOfficeStore.getState().hover).toEqual({ kind: "checkpoint", id: "team" });+ fireEvent.click(open);+ expect(useOfficeStore.getState().selection).toEqual({ kind: "checkpoint", id: "team" });+ expect(useOfficeStore.getState().hover).toBeNull();+ expect(screen.queryByRole("group", { name: "Places" })).toBeNull();++ fireEvent.click(screen.getByRole("button", { name: "Places" }));+ fireEvent.click(screen.getByRole("button", { name: "Walk to Wardrobe" }));+ const wardrobe = stationsFor(layout).find((s) => s.selection.id === "wardrobe")!;+ expect(useOfficeStore.getState().walkTo?.point).toEqual(wardrobe.approach);+ expect(useOfficeStore.getState().selection).toBeNull();+ });++ test("lists the rooms' places and the teams apart, and gives every row a name", () => {+ const board = (dept: string) => ({ id: `studio-board:${dept}`, x: 4, z: -6, facing: 0 });+ const studios: Studio[] = [+ { deptId: "d0", teamId: "g1", name: "Launch crew", members: ["a1"], leadId: null, board: board("d0"), huddleSpotIds: [], centre: { x: 4, z: -3 } },+ { deptId: "pool", teamId: null, name: "", members: [], leadId: null, board: board("pool"), huddleSpotIds: [], centre: { x: 9, z: -3 } },+ ];+ const campus: OfficeLayout = { ...layout, studios };+ tools({ layout: campus });+ fireEvent.click(screen.getByRole("button", { name: "Places" }));+ const menu = screen.getByRole("group", { name: "Places" });+ const teams = within(menu).getByRole("region", { name: "Teams" });+ expect(within(teams).getByRole("button", { name: "Launch crew: Open the team" })).toBeTruthy();+ // The studio of agents without a team is never a bare "Team board".+ expect(within(teams).getByRole("button", { name: "Without a team: Open the team" })).toBeTruthy();+ expect(within(menu).queryByRole("button", { name: /^Team board/ })).toBeNull();+ const places = within(menu).getByRole("region", { name: "Places" });+ expect(within(places).getByRole("button", { name: "Team room: Manage teams" })).toBeTruthy();+ expect(within(places).queryByRole("button", { name: /Launch crew/ })).toBeNull();+ for (const station of stationsFor(campus)) expect(stationLabel(station, (key) => key)).not.toBe("");+ });++ test("the free plot's stand is listed with the teams, as the place to start one", () => {+ const stand = { id: "team-stand", kind: "lobbyLamp" as const, x: 6, z: 4, rotationY: 0, room: "floor" as const };+ tools({ layout: { ...layout, furniture: [...layout.furniture.filter((item) => item.id !== stand.id), stand] } });+ fireEvent.click(screen.getByRole("button", { name: "Places" }));+ const teams = within(screen.getByRole("group", { name: "Places" })).getByRole("region", { name: "Teams" });+ fireEvent.click(within(teams).getByRole("button", { name: "Free plot: Start a team here" }));+ expect(useOfficeStore.getState().selection).toEqual({ kind: "team", id: "team-stand" });+ });++ test("the arrow keys move through the rows, and sideways to a row's walk button", () => {+ tools();+ fireEvent.click(screen.getByRole("button", { name: "Places" }));+ const menu = screen.getByRole("group", { name: "Places" });+ const rows = [...menu.querySelectorAll<HTMLElement>("[data-place-open]")];+ expect(rows.length).toBeGreaterThan(3);+ const press = (key: string) => {+ const event = new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true });+ const reachedWindow = vi.fn();+ window.addEventListener("keydown", reachedWindow);+ (document.activeElement ?? menu).dispatchEvent(event);+ window.removeEventListener("keydown", reachedWindow);+ // The list keeps its arrows to itself: the character must not walk on them.+ expect(reachedWindow, key).not.toHaveBeenCalled();+ expect(event.defaultPrevented, key).toBe(true);+ };+ rows[0]!.focus();+ press("ArrowDown");+ expect(document.activeElement).toBe(rows[1]);+ press("ArrowDown");+ expect(document.activeElement).toBe(rows[2]);+ press("ArrowUp");+ expect(document.activeElement).toBe(rows[1]);+ press("ArrowRight");+ expect((document.activeElement as HTMLElement).dataset.placeWalk).toBeDefined();+ expect(rows[1]!.closest("[data-place-row]")!.contains(document.activeElement)).toBe(true);+ press("ArrowLeft");+ expect(document.activeElement).toBe(rows[1]);+ press("End");+ expect(document.activeElement).toBe(rows[rows.length - 1]);+ press("ArrowDown");+ expect(document.activeElement).toBe(rows[rows.length - 1]);+ press("Home");+ expect(document.activeElement).toBe(rows[0]);+ press("ArrowUp");+ expect(document.activeElement).toBe(rows[0]);+ // The row in focus is lit in the world.+ expect(useOfficeStore.getState().hover).toEqual(stationsFor(layout)[0]!.selection);+ });++ test("opened from the keyboard it lands on the first place", () => {+ tools();+ const trigger = screen.getByRole("button", { name: "Places" });+ trigger.focus();+ fireEvent.keyDown(trigger, { key: "ArrowDown" });+ const menu = screen.getByRole("group", { name: "Places" });+ expect(document.activeElement).toBe(menu.querySelector("[data-place-open]"));+ });++ test("Escape closes the places menu and hands focus back to its button", () => {+ tools();+ const trigger = screen.getByRole("button", { name: "Places" });+ fireEvent.click(trigger);+ fireEvent.focus(screen.getByRole("button", { name: "Team room: Manage teams" }));+ fireEvent.keyDown(screen.getByRole("group", { name: "Places" }), { key: "Escape" });+ expect(screen.queryByRole("group", { name: "Places" })).toBeNull();+ expect(document.activeElement).toBe(trigger);+ // Nothing stays lit in the world behind a closed menu.+ expect(useOfficeStore.getState().hover).toBeNull();+ });+});++describe("station prompt", () => {+ test("is one button: the key, the action, the object's name", () => {+ const onUse = vi.fn();+ render(<StationPrompt line={{ how: "key", action: "Create an agent", object: "Spawn point" }} onUse={onUse} />);+ const prompt = screen.getByRole("button");+ expect(prompt.textContent).toBe("ECreate an agentSpawn point");+ fireEvent.click(prompt);+ expect(onUse).toHaveBeenCalledOnce();+ });++ test("in a narrow host it shows the key and the whole action, and keeps the object's name for screen readers", () => {+ render(<StationPrompt compact line={{ how: "key", action: "Call the elevator", object: "Elevator" }} onUse={vi.fn()} />);+ const prompt = screen.getByRole("button");+ expect(prompt.dataset.compact).toBe("true");+ expect(prompt.querySelector("kbd")!.textContent).toBe("E");+ expect(prompt.querySelector("b")!.textContent).toBe("Call the elevator");+ // The name is still part of the button's text, but not drawn.+ const object = screen.getByText("Elevator");+ expect(object.className).toBe("sr-only");+ cleanup();+ render(<StationPrompt line={{ how: "key", action: "Call the elevator", object: "Elevator" }} onUse={vi.fn()} />);+ expect(screen.getByText("Elevator").className).toBe("");+ expect(screen.getByRole("button").dataset.compact).toBeUndefined();+ });++ test("names the click instead of the key for something pointed at from afar", () => {+ render(<StationPrompt line={{ how: "click", action: "Talk to Ada" }} onUse={vi.fn()} />);+ expect(screen.getByRole("button").textContent).toBe("ClickTalk to Ada");+ });++ test("every station of every floor has its action in words", () => {+ const t = (key: string) => key;+ const floors = [layout, buildOfficeLayout([], { variant: "coding" })];+ const ids = new Set(floors.flatMap((floor) => stationsFor(floor).map((s) => s.id)));+ render(<ul>{[...ids].map((id) => <li key={id}><StationWords id={id} /></li>)}</ul>);+ for (const id of ids) {+ const words = screen.getByTestId(`words-${id}`).textContent ?? "";+ expect(words, id).not.toContain("society.");+ expect(words.length, id).toBeGreaterThan(3);+ }+ // The coffee bar's action flips while a break is on.+ expect(stationAction({ id: "break" }, t)).toBe("society.office.use_break");+ expect(stationAction({ id: "break" }, t, true)).toBe("society.office.use_break_end");+ expect(stationAction({ id: "team" }, t, true)).toBe("society.office.use_team");+ });+});++function StationWords({ id }: { id: string }) {+ // The real translator, so a missing key shows up as the key itself.+ const t = useT();+ return <span data-testid={`words-${id}`}>{stationAction({ id }, t)} · {t(`society.office.cp_${id}`)}</span>;+}++describe("control hints", () => {+ test("show the essentials once and are dismissed for good", () => {+ const onDismiss = vi.fn();+ render(<ControlHints onDismiss={onDismiss} />);+ const hints = screen.getByRole("region", { name: "Controls" });+ expect(within(hints).getAllByRole("listitem").map((li) => li.textContent)).toEqual([+ "WASDWalk", "DragLook around", "EUse what is near", "HAll controls",+ ]);+ fireEvent.click(screen.getByRole("button", { name: "Got it" }));+ expect(onDismiss).toHaveBeenCalledOnce();+ });++ test("are remembered per browser profile", () => {+ expect(loadOfficeSettings().hintsSeen).toBe(false);+ useOfficeSettings.getState().set({ hintsSeen: true });+ expect(loadOfficeSettings().hintsSeen).toBe(true);+ useOfficeSettings.getState().reset();+ expect(loadOfficeSettings().hintsSeen).toBe(false);+ });++ test("stay away for someone who had switched the old permanent hint bar off", () => {+ localStorage.setItem("jarvis.office.settings.v1", JSON.stringify({ alwaysRun: true, showHintBar: false }));+ expect(loadOfficeSettings()).toEqual({ alwaysRun: true, hintsSeen: true });+ localStorage.setItem("jarvis.office.settings.v1", JSON.stringify({ alwaysRun: false, showHintBar: true }));+ expect(loadOfficeSettings().hintsSeen).toBe(false);+ });++ test("fall back to the defaults when storage is unreadable", () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);+ localStorage.setItem("jarvis.office.settings.v1", "{not json");+ expect(loadOfficeSettings()).toEqual(DEFAULT_OFFICE_SETTINGS);+ expect(warn).toHaveBeenCalled();+ warn.mockRestore();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeHud.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeHud.tsxnew file mode 100644index 0000000000..5fb8404d59--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeHud.tsx@@ -0,0 +1,169 @@+/**+ * The quiet parts of the office HUD: a small icon toolbar (follow, overview,+ * places, list, help), the one prompt for whatever the person can use right+ * now, and the control hints a first-time visitor sees once. Theme tokens+ * only; nothing here polls or animates on its own.+ */+import { useEffect, useId, useRef, useState, type ReactNode } from "react";+import { CircleHelp, List, LocateFixed, MapPin, Maximize, SquareTerminal } from "lucide-react";+import { useT } from "@/i18n";+import type { OfficeLayout } from "./officeLayout";+import { OFFICE_CONTROLS } from "./officeControls";+import { useOfficeStore } from "./officeStore";+import { KeyCaps, PlacesList } from "./ReceptionPanel";++export { stationAction, stationLabel } from "./stationText";++function Tool({ label, shortcut, children, ...rest }: {+ label: string; shortcut?: string; children: ReactNode;+} & Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, "children" | "aria-label">) {+ return (+ <button type="button" className="office-tool" aria-label={label} aria-keyshortcuts={shortcut}+ data-tip={shortcut ? `${label} (${shortcut})` : label} {...rest}>+ {children}+ </button>+ );+}++/**+ * The places of this floor, opened from the toolbar: every station as a real+ * button, for pointer and keyboard alike. An opaque card that never grows+ * past the stage; when there is more below, its lower edge fades to say so.+ */+function PlacesCard({ id, layout, focusFirst, onPicked }: { id: string; layout: OfficeLayout; focusFirst: boolean; onPicked: () => void }) {+ const t = useT();+ const scroller = useRef<HTMLDivElement>(null);+ const [more, setMore] = useState(false);+ useEffect(() => {+ const el = scroller.current;+ if (!el) return;+ const check = () => setMore(el.scrollHeight - el.scrollTop - el.clientHeight > 4);+ check();+ el.addEventListener("scroll", check, { passive: true });+ window.addEventListener("resize", check);+ return () => {+ el.removeEventListener("scroll", check);+ window.removeEventListener("resize", check);+ };+ }, [layout]);+ // Opened from the keyboard: land on the first place, so the arrows work at once.+ useEffect(() => {+ if (focusFirst) scroller.current?.querySelector<HTMLElement>("[data-place-open]")?.focus({ preventScroll: true });+ }, [focusFirst]);+ return (+ <div id={id} className="office-places-card" role="group" aria-label={t("society.office.hud_places")} data-more={more || undefined}>+ <div ref={scroller} className="office-places-scroll">+ <PlacesList layout={layout} withReception onPicked={onPicked} />+ </div>+ </div>+ );+}++export function OfficeTools({ layout, follow, onFollow, onOverview, helpOpen, onHelp, list }: {+ layout: OfficeLayout;+ follow: boolean; onFollow: () => void; onOverview: () => void;+ helpOpen: boolean; onHelp: () => void;+ /** The roster this floor belongs to: the agents view, the IDE, or the IDE tab's sessions list; null on a floor without one. */+ list: { label: string; ide: boolean; onOpen: () => void } | null;+}) {+ const t = useT();+ const [places, setPlaces] = useState<{ open: boolean; byKeyboard: boolean }>({ open: false, byKeyboard: false });+ const dock = useRef<HTMLDivElement>(null);+ const trigger = useRef<HTMLButtonElement>(null);+ const placesId = useId();+ const close = () => {+ setPlaces({ open: false, byKeyboard: false });+ // A row that was pointed at is gone with the card; nothing may stay lit in the world.+ useOfficeStore.getState().setHover(null);+ };+ useEffect(() => {+ if (!places.open) return;+ const outside = (event: PointerEvent) => {+ if (event.target instanceof Node && !dock.current?.contains(event.target)) close();+ };+ document.addEventListener("pointerdown", outside, true);+ return () => document.removeEventListener("pointerdown", outside, true);+ }, [places.open]);+ return (+ <div ref={dock} className="office-hud office-tools-dock" data-office-ui+ onKeyDown={(event) => {+ if (event.key !== "Escape" || !places.open) return;+ event.preventDefault();+ event.stopPropagation();+ close();+ trigger.current?.focus();+ }}>+ <div className="office-tools" role="toolbar" aria-label={t("society.office.hud_tools")}>+ <Tool label={t("society.office.me")} aria-pressed={follow} onClick={onFollow}><LocateFixed aria-hidden /></Tool>+ <Tool label={t("society.office.overview")} onClick={onOverview}><Maximize aria-hidden /></Tool>+ <button ref={trigger} type="button" className="office-tool" aria-label={t("society.office.hud_places")}+ data-tip={places.open ? undefined : t("society.office.hud_places")} aria-expanded={places.open} aria-controls={placesId}+ // A click without a pointer (Enter, Space) came from the keyboard.+ onClick={(event) => (places.open ? close() : setPlaces({ open: true, byKeyboard: event.detail === 0 }))}+ onKeyDown={(event) => {+ if (event.key !== "ArrowDown") return;+ // Arrow down opens the card on its first place, or steps into a card that is already open.+ event.preventDefault();+ event.stopPropagation();+ if (places.open) dock.current?.querySelector<HTMLElement>("[data-place-open]")?.focus();+ else setPlaces({ open: true, byKeyboard: true });+ }}>+ <MapPin aria-hidden />+ </button>+ {list && <Tool label={list.label} onClick={list.onOpen}>{list.ide ? <SquareTerminal aria-hidden /> : <List aria-hidden />}</Tool>}+ <Tool label={t("society.office.guide.hud_button")} shortcut="H" aria-pressed={helpOpen} onClick={onHelp}><CircleHelp aria-hidden /></Tool>+ </div>+ {places.open && <PlacesCard id={placesId} layout={layout} focusFirst={places.byKeyboard} onPicked={close} />}+ </div>+ );+}++/** What the prompt says: how it is triggered, the action, and (for a station) the object it belongs to. */+export interface PromptLine {+ /** `key`: the person stands at it and E uses it. `click`: the pointer rests on it from afar. */+ how: "key" | "click";+ action: string;+ object?: string;+}++/**+ * The one prompt on screen: a key cap, the action, the object's name. A real button, so a click or a tap works too.+ * In a narrow host (`compact`, the IDE side panel) there is no room for both texts: the action is shown whole,+ * wrapping if it must, and the object's name is kept for screen readers only.+ */+export function StationPrompt({ line, onUse, compact = false }: { line: PromptLine; onUse: () => void; compact?: boolean }) {+ const t = useT();+ return (+ <button type="button" className="office-prompt" data-office-ui data-compact={compact || undefined} onClick={onUse}>+ {line.how === "key"+ ? <kbd className="office-key">E</kbd>+ : <kbd className="office-key" data-mouse>{t("society.office.guide.mouse_click")}</kbd>}+ <b>{line.action}</b>+ {line.object && <span className={compact ? "sr-only" : undefined}>{line.object}</span>}+ </button>+ );+}++const HINT_IDS = ["walk", "rotate", "interact", "guide"] as const;++/**+ * The controls, once: shown to someone who has not dismissed them yet,+ * remembered per browser profile (officeSettings). Reception's settings bring+ * them back.+ */+export function ControlHints({ onDismiss }: { onDismiss: () => void }) {+ const t = useT();+ return (+ <section className="office-card office-hints" data-office-ui aria-label={t("society.office.hints_label")}>+ <ul>+ {HINT_IDS.map((id) => {+ const control = OFFICE_CONTROLS.find((c) => c.id === id);+ if (!control) return null;+ // One way to do it is enough for a first hint; the guide lists every alternative.+ return <li key={id}><KeyCaps control={{ keys: control.keys.slice(0, 1) }} />{t(`society.office.hint_${id}`)}</li>;+ })}+ </ul>+ <button type="button" className="office-hints-dismiss" onClick={onDismiss}>{t("society.office.hints_dismiss")}</button>+ </section>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeMinimap.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeMinimap.tsxindex b31e70d30c..a328025824 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeMinimap.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeMinimap.tsx@@ -18,11 +18,11 @@ import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent as Rimport { Map as MapIcon, Minus, Plus } from "lucide-react";import { useReducedMotion } from "framer-motion";import { useT } from "@/i18n";-import type { CheckpointKind, OfficeLayout, Point, Rect, RoomKind } from "./officeLayout";+import type { CampusZoneKind, CheckpointKind, OfficeLayout, Point, Rect, RoomKind } from "./officeLayout";import { cameraView, player, useOfficeStore } from "./officeStore";import { agentPositions } from "./walkerRegistry";import {- MAP_PAINT, ZOOM_DEFAULT_M, ZOOM_MAX_M, ZOOM_MIN_M, centredTransform, clampToEdge, clampToRect, clampZoom, drawAgentToken, drawCheckpoints,+ MAP_PAINT, ZOOM_DEFAULT_M, ZOOM_MAX_M, ZOOM_MIN_M, centredTransform, clampToEdge, clampToRect, clampZoom, drawAgentToken, drawCheckpoints, minimapCentre,drawEdgeArrow, drawFloorArt, drawPlayerArrow, drawViewCone, mapToWorld, pickNearest, placeAt, worldToMap, zoomStep,type AgentToken, type MapPoint, type MapTransform,} from "./minimap";@@ -87,16 +87,19 @@ export function OfficeMinimap({ layout, agents, selectedId, onOpenMap }: OfficeMconst dpr = usePixelRatio();// The render loop reads these through a ref, so a roster refetch never restarts it.- const live = useRef({ agents, selectedId, zoom, reduced });- live.current = { agents, selectedId, zoom, reduced };+ const live = useRef({ agents, selectedId, zoom, reduced, bounds: layout.bounds });+ live.current = { agents, selectedId, zoom, reduced, bounds: layout.bounds };+ /** Where the person's arrow is on the card: the middle, except near the floor's edge. */+ const meRef = useRef({ x: MINIMAP_SIZE / 2, y: MINIMAP_SIZE / 2 });const draw = useCallback((now: number) => {const canvas = canvasRef.current;const ctx = context2d(canvas);if (!canvas || !ctx) return;- const { agents: roster, selectedId: sel, zoom: metres, reduced: still } = live.current;+ const { agents: roster, selectedId: sel, zoom: metres, reduced: still, bounds } = live.current;const size = MINIMAP_SIZE;- const tr = centredTransform(player, metres, size, size);+ // The card follows the person but stays on the floor.+ const tr = centredTransform(minimapCentre(player, bounds, metres), metres, size, size);transformRef.current = tr;const ratio = canvas.width / size;ctx.setTransform(ratio, 0, 0, ratio, 0, 0);@@ -109,6 +112,7 @@ export function OfficeMinimap({ layout, agents, selectedId, onOpenMap }: OfficeMctx.drawImage(layer.canvas, origin.x, origin.y, layer.cssW, layer.cssH);}const centre = worldToMap(tr, player);+ meRef.current = centre;if (cameraView.ready) drawViewCone(ctx, centre, cameraView.yaw, cameraView.halfWidth, size * 0.5);const hits: Hit[] = [];@@ -242,7 +246,18 @@ export function OfficeMinimap({ layout, agents, selectedId, onOpenMap }: OfficeMlevels: t("society.office.room_levels"),};const youLabel = t("society.office.minimap_you");- const openSpace = t("society.office.open_space");+ // Agents floor: the campus between the studios. The pool studio has no team name; the map gives it one.+ const zoneLabels: Record<CampusZoneKind, string> = {+ boulevard: t("society.office.zone_boulevard"),+ plaza: t("society.office.zone_boulevard"),+ atrium: t("society.office.zone_atrium"),+ plot: t("society.office.zone_plot"),+ garden: t("society.office.zone_garden"),+ booths: t("society.office.zone_booths"),+ library: t("society.office.zone_library"),+ cafe: t("society.office.zone_cafe"),+ };+ const openSpace = t(layout.variant === "agents" ? "society.office.studio_pool" : "society.office.open_space");const onPointerMove = (event: ReactPointerEvent<HTMLCanvasElement>) => {const at = mapPoint(event);@@ -251,13 +266,14 @@ export function OfficeMinimap({ layout, agents, selectedId, onOpenMap }: OfficeMconst hit = pickNearest(hitsRef.current, at, HIT_PX);if (hit) {text = agents.get(hit.id)?.name ?? null;- } else if ((at.x - MINIMAP_SIZE / 2) ** 2 + (at.y - MINIMAP_SIZE / 2) ** 2 <= HIT_PX * HIT_PX) {+ } else if ((at.x - meRef.current.x) ** 2 + (at.y - meRef.current.y) ** 2 <= HIT_PX * HIT_PX) {text = youLabel;} else {const place = placeAt(layout, mapToWorld(transformRef.current, at));if (place?.kind === "checkpoint") text = checkpointLabels[place.id];else if (place?.kind === "room") text = roomLabels[place.id];else if (place?.kind === "department") text = place.label || openSpace;+ else if (place?.kind === "zone") text = zoneLabels[place.id];}setTooltip((prev) => {if (!text) return null;diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficePanels.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficePanels.tsxindex 46b6e3d30a..880f657815 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficePanels.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficePanels.tsx@@ -1,25 +1,29 @@/**- * DOM panels for what the person selects in the office: an agent (an IDE- * session on the coding floor has its own PaneCommandPanel), or one of the- * checkpoints (the spawn point, reception, agent board, team room, wardrobe,- * lead office, break room, elevator, Mission Control). Every action here uses an existing app path — create dialog,- * agent card/chat, chat groups — the office adds no new backend contract.+ * What the person's selection opens in the office: an agent's walkie-talkie+ * (an IDE session on the coding floor has its own PaneCommandPanel), or the+ * surface of a station. Every action here uses an existing app path — the+ * create dialog, agent card and chat, chat groups — the office adds no new+ * backend contract.+ *+ * Not every station has a surface here: the spawn terminal opens the app's+ * create dialog, the lead's desk selects the lead, the coffee bar calls a+ * break, the elevator and the Level Hall open their own screens. OfficeStage+ * turns those selections into their action.*/-import { useEffect, useId, useRef, useState } from "react";import { useT } from "@/i18n";import type { SocietyAgent } from "../data";-import type { CheckpointKind, OfficeLayout, Point } from "./officeLayout";-import { player, useOfficeStore, type OfficeFloor } from "./officeStore";-import { agentPositions } from "./walkerRegistry";-import { AgentTalkPanel, CALL_MS } from "./AgentTalkPanel";+import type { OfficeLayout } from "./officeLayout";+import type { NavGrid } from "./officeNav";+import { type OfficeFloor, type Selection } from "./officeStore";+import { AgentTalkPanel } from "./AgentTalkPanel";import type { PlayerProfile } from "./playerProfile";import { WardrobePanel } from "./WardrobePanel";import { ReceptionPanel } from "./ReceptionPanel";import { TeamRoomPanel } from "./TeamRoomPanel";import { MissionControlPanel } from "./MissionControlPanel";-import { LaunchPanel, SpawnPanel } from "./SpawnPanel";-import { CHECKPOINT_ICON, IconSvg, type CheckpointIcon } from "./CheckpointMarker";-+import { LaunchPanel } from "./SpawnPanel";+import { StationSheet, StationSidePanel } from "./StationSheet";+import { isReception, isTeamStand } from "./stations";export interface OfficeActions {onOpenAgent: (id: string) => void;@@ -28,38 +32,17 @@ export interface OfficeActions {onOpenGroup?: (groupId: string) => void;}-function StateDot({ state }: { state: SocietyAgent["state"] }) {- return <i className="office-dot" data-state={state} aria-hidden />;-}--function PanelShell({ title, subtitle, icon, kind, onClose, children }: {- title: string; subtitle?: string; icon?: CheckpointIcon; kind?: 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 ref={panel} className="office-card office-panel" data-office-ui data-panel={kind} aria-labelledby={headingId} tabIndex={-1}>- <header className="office-panel-head">- {icon && <span className="office-panel-badge" aria-hidden><IconSvg icon={icon} /></span>}- <div>- <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>- </header>- <div className="office-panel-body">{children}</div>- </aside>- );-}+/** How a station's surface is shown: a dialog over the map, or a panel docked beside it. */+export type StationSurfaceKind = "sheet" | "side";-function spotCentre(layout: OfficeLayout, kind: "couch"): Point {- const spots = layout.spots.filter((s) => s.kind === kind);- if (spots.length === 0) return layout.spawn;- return { x: spots.reduce((s, p) => s + p.x, 0) / spots.length, z: spots.reduce((s, p) => s + p.z, 0) / spots.length };+/** The stations that open a surface of their own, and how. Everything else is an action (see OfficeStage). */+export function stationSurface(selection: Selection | null): StationSurfaceKind | null {+ if (!selection) return null;+ if (selection.kind === "team") return "sheet";+ if (selection.kind !== "checkpoint") return null;+ if (selection.id === "wardrobe") return "side";+ if (isReception(selection) || selection.id === "team" || selection.id === "launch" || selection.id === "mission") return "sheet";+ return null;}/** The agent panel is a walkie-talkie to that agent (AgentTalkPanel). */@@ -67,102 +50,69 @@ export function AgentPanel({ agent, actions, onClose }: { agent: SocietyAgent; areturn <AgentTalkPanel agent={agent} actions={actions} onClose={onClose} />;}-function ManagePanel({ agents, actions }: { agents: SocietyAgent[]; actions: OfficeActions }) {- const t = useT();- const store = useOfficeStore();- return (- <>- {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>- </>- );-}--function LeadPanel({ agents, actions }: { agents: SocietyAgent[]; actions: OfficeActions }) {- const t = useT();- const store = useOfficeStore();- // 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>{t("society.office.lead_body")}</p>- {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_talk"), lead.name)}- onClick={() => store.select({ kind: "agent", id: lead.agentId })}>{t("society.office.action_talk")}</button>- <button type="button" className="office-action" 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>- ))}- </>- );-}--function BreakPanel({ agents, layout }: { agents: SocietyAgent[]; layout: OfficeLayout }) {- 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>{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);- 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>}- </>- );-}--export function CheckpointPanel({ id, floor = "agents", agents, layout, sample, profile, onProfile, actions, onClose }: {- id: CheckpointKind; floor?: OfficeFloor; agents: SocietyAgent[]; layout: OfficeLayout; sample: boolean;+export function StationSurface({ selection, floor = "agents", agents, layout, grid, sample, profile, onProfile, actions, onClose, returnFocus }: {+ selection: Selection; floor?: OfficeFloor; agents: SocietyAgent[]; layout: OfficeLayout; sample: boolean;+ /** The floor's nav grid: a team opened from its studio board meets at that board, on places the grid allows. */+ grid?: NavGrid;profile: PlayerProfile; onProfile: (next: PlayerProfile) => void; actions: OfficeActions; onClose: () => void;+ /** Hands focus back to the map once a dialog has closed. */+ returnFocus?: () => void;}) {const t = useT();- return (- <PanelShell title={t(`society.office.cp_${id}`)} subtitle={t(`society.office.cp_${id}_hint`)} icon={CHECKPOINT_ICON[id]} kind={id} onClose={onClose}>- {id === "spawn" && <SpawnPanel agents={agents} onCreateAgent={actions.onCreateAgent} />}- {id === "launch" && <LaunchPanel />}- {id === "create" && <ReceptionPanel floor={floor} layout={layout} onCreateAgent={actions.onCreateAgent} />}- {id === "manage" && <ManagePanel agents={agents} actions={actions} />}- {id === "team" && <TeamRoomPanel agents={agents} layout={layout} sample={sample} actions={actions} />}- {id === "wardrobe" && <WardrobePanel profile={profile} onProfile={onProfile} agents={agents} sample={sample} />}- {id === "lead" && <LeadPanel agents={agents} actions={actions} />}- {id === "break" && <BreakPanel agents={agents} layout={layout} />}- {id === "mission" && <MissionControlPanel />}- </PanelShell>- );+ if (selection.kind === "team") {+ const studio = (layout.studios ?? []).find((s) => s.board?.id === selection.id);+ if (!studio) {+ // The free plot's stand: no team stands here yet, so the sheet opens on the form that starts one.+ if (!isTeamStand(layout, selection)) return null;+ return (+ <StationSheet title={t("society.office.cp_found")} description={t("society.office.plot_free")} onClose={onClose} returnFocus={returnFocus}>+ <TeamRoomPanel agents={agents} layout={layout} sample={sample} actions={actions} onMeet={onClose} compose />+ </StationSheet>+ );+ }+ return (+ <StationSheet title={studio.teamId ? studio.name : t("society.office.team_pool")} description={t("society.office.cp_board_hint")} onClose={onClose} returnFocus={returnFocus}>+ <TeamRoomPanel agents={agents} layout={layout} sample={sample} actions={actions} onMeet={onClose}+ focus={{ teamId: studio.teamId, members: studio.members, studio, grid }} />+ </StationSheet>+ );+ }+ if (selection.kind !== "checkpoint") return null;+ const id = selection.id;+ if (id === "wardrobe") {+ return (+ <StationSidePanel title={t("society.office.cp_wardrobe")} description={t("society.office.wardrobe_body")} onClose={onClose}>+ <WardrobePanel profile={profile} onProfile={onProfile} agents={agents} sample={sample} />+ </StationSidePanel>+ );+ }+ if (isReception(selection)) {+ return (+ <StationSheet title={t("society.office.cp_manage")} description={t("society.office.cp_manage_hint")} onClose={onClose} returnFocus={returnFocus}>+ <ReceptionPanel floor={floor} layout={layout} agents={agents} actions={actions} />+ </StationSheet>+ );+ }+ if (id === "team") {+ return (+ <StationSheet title={t("society.office.cp_team")} description={t("society.office.cp_team_hint")} onClose={onClose} returnFocus={returnFocus}>+ <TeamRoomPanel agents={agents} layout={layout} sample={sample} actions={actions} onMeet={onClose} />+ </StationSheet>+ );+ }+ if (id === "launch") {+ return (+ <StationSheet size="md" title={t("society.office.cp_launch")} description={t("society.office.launch_body")} onClose={onClose} returnFocus={returnFocus}>+ <LaunchPanel />+ </StationSheet>+ );+ }+ if (id === "mission") {+ return (+ <StationSheet size="md" title={t("society.office.cp_mission")} description={t("society.office.cp_mission_hint")} onClose={onClose} returnFocus={returnFocus}>+ <MissionControlPanel />+ </StationSheet>+ );+ }+ return null;}diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsxindex f85e2944ba..bd78db6f1c 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx@@ -3,24 +3,31 @@* runs, Space jumps — a sprint jump is faster than a sprint) or by clicking* the floor, and interacts with whatever is nearby (E).* Zooming out never requires walking — everything stays clickable from afar.+ *+ * A click draws the route on the floor (dots to a ring at the destination).+ * The character walks round people and furniture, never through them, and+ * never comes to rest inside anything solid or beyond the floor's edge.*/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 { DoubleSide, Object3D, Vector3, type Group, type InstancedMesh, type Mesh, type MeshBasicMaterial } from "three";import type { FigureDrive } from "../figures/FigureRig";import { ToyFigure } from "./ToyFigure";import type { ToyLook } from "./toyFigureModel";-import { findPath, isWalkable, nearestWalkable, type NavGrid } from "./officeNav";-import { applySeparation, separation, stepClearOfBodies, stepMover, turnToward } from "./officeMotion";+import { isWalkable, nearestWalkable, type NavGrid } from "./officeNav";+import { clickPaceFor, stepClearOfBodies, turnToward } from "./officeMotion";+import { advanceWalk, beginWalk, routeMarks, type Walk } from "./officeWalk";+import { standingPlaceFor } from "./officeTeams";import { officeSession, player, sameSelection, useOfficeStore, type Selection } from "./officeStore";-import { agentPositions, bodiesExcept, companions } from "./walkerRegistry";+import { agentPositions, bodiesExcept, bodiesNear, companions } from "./walkerRegistry";import { OFFICE_FIGURE_HEIGHT_M } from "./OfficeAgents";import { seatOf, type OfficeLayout } from "./officeLayout";import { chairInReach, seatDesks, useLeadSeat } from "./leadSeat";import { useOfficeDog } from "./dogLife";import { TreatBone } from "./dogProps";import { isRunning, useOfficeSettings } from "./officeSettings";+import { nearestInteractable } from "./stations";import { jumpSquash, newJump, pressJump, stepJump } from "./officeJump";import { useProgression } from "../progression/progressionStore";import { PERSON_SUBJECT } from "../progression/progressionApi";@@ -31,6 +38,13 @@ import { useDressedFigure } from "../progression/regalia/dress";export const PLAYER_WALK_SPEED = 2.0;export const PLAYER_SPRINT_SPEED = 4.4;+/** Bodies further than this from the character play no part in a click-to-move walk. */+const BODY_RANGE_M = 7;+/** How far the character may be from free ground before it is put back at the floor's entrance instead. */+const RESCUE_RANGE_M = 8;+/** The route marker: dots on the floor and a ring at the destination, in the character's own gold. */+const MARKER = { dots: 40, colour: "#f5b83d", y: 0.035 } as const;+/** Talk range to an agent, in metres. */export const AGENT_TALK_RANGE = 1.8;@@ -110,28 +124,8 @@ function useMoveKeys(enabled: boolean, onInteract: () => void, onJump: () => voireturn { pressed, run, jumpHeld };}-function nearestInteractable(layout: OfficeLayout): Selection | null {- let best: Selection | null = null;- let bestDistance = Infinity;- for (const cp of layout.checkpoints) {- const d = Math.hypot(cp.x - player.x, cp.z - player.z);- if (d <= cp.radius && d < bestDistance) { best = { kind: "checkpoint", id: cp.id }; bestDistance = d; }- }- for (const [id, p] of agentPositions) {- if (companions.has(id)) continue;- const d = Math.hypot(p.x - player.x, p.z - player.z);- if (d <= AGENT_TALK_RANGE && d < bestDistance) { best = { kind: "agent", id }; bestDistance = d; }- }- for (const item of layout.furniture) {- // The break room's cabinet, and every game cabinet on the arcade floor.- if (item.kind !== "arcade" && item.kind !== "retroCabinet") continue;- // The cabinet's screen faces its local +z; you play standing in front of it.- const fx = item.x + Math.sin(item.rotationY) * 0.85, fz = item.z + Math.cos(item.rotationY) * 0.85;- const d = Math.hypot(fx - player.x, fz - player.z);- if (d <= ARCADE_PLAY_RANGE && d < bestDistance) { best = { kind: "arcade", id: item.id }; bestDistance = d; }- }- return best;-}+/** What E reaches from where the character stands: a station, an agent or a game cabinet (stations.ts). */+const REACH = { agent: AGENT_TALK_RANGE, arcade: ARCADE_PLAY_RANGE } as const;export function OfficePlayer({ layout, grid, look, name, awake, reduced }: {layout: OfficeLayout; grid: NavGrid; look: ToyLook; name: string; awake: boolean; reduced: boolean;@@ -144,6 +138,9 @@ export function OfficePlayer({ layout, grid, look, name, awake, reduced }: {const camera = useThree((s) => s.camera);const forward = useMemo(() => new Vector3(), []);const lastWalk = useRef(0);+ // The click-to-move walk in progress: its route, stuck watch and time budget.+ const walk = useRef<Walk | null>(null);+ const others = useRef<{ x: number; z: number }[]>([]);const nearbyRef = useRef<Selection | null>(null);const interact = useMemo(() => () => {// E on the lead's chair sits down (or stands up again); otherwise it opens what is nearby.@@ -217,10 +214,13 @@ export function OfficePlayer({ layout, grid, look, name, awake, reduced }: {// Click-to-move / "walk there" requests.if (store.walkTo && store.walkTo.seq !== lastWalk.current) {lastWalk.current = store.walkTo.seq;- // A target inside something solid (the middle of the holo deck) walks to the nearest free spot instead.+ // A target inside something solid or on somebody (a desk, a chair, a seated agent, the middle of the holo+ // deck) is reached at a free standing place beside it: the character never comes to rest inside furniture+ // or a figure, and never on a chair that is not its own to sit on.const goal = store.walkTo.point;- const free = isWalkable(grid, goal) ? null : nearestWalkable(grid, goal);- player.path = findPath(grid, player, goal) ?? (free ? findPath(grid, player, free) : null) ?? [];+ const free = standingPlaceFor(layout, grid, goal, bodiesNear(null, goal, 4, null, []));+ walk.current = free ? beginWalk(grid, player, free, bodiesNear(null, player, BODY_RANGE_M, null, others.current)) : null;+ if (!walk.current) player.path = [];}// Keyboard movement, relative to where the camera looks; nothing while a dialog owns the keys.if (forgetHeldKeysUnderDialog(pressed.current)) jumpHeld.current = false;@@ -258,10 +258,21 @@ export function OfficePlayer({ layout, grid, look, name, awake, reduced }: {else if (free({ x: player.x, z: nz })) { player.z = nz; moved = Math.abs(dz * step); }player.heading = turnToward(player.heading, Math.atan2(dx, dz), 12 * dt);if (!store.follow) store.setFollow(true);+ } else if (player.path.length > 0 && walk.current) {+ // Round people and furniture, never through them; a walk that cannot go on stops where it is. A long+ // route is jogged and ends in a walk; Shift (or "always run") sprints all the way.+ const pace = sprinting ? speed : clickPaceFor(walk.current.remaining, PLAYER_WALK_SPEED, PLAYER_SPRINT_SPEED) * jump.speedMul;+ const step = advanceWalk(walk.current, player, grid, dt, bodiesNear(null, player, BODY_RANGE_M, null, others.current), { speed: pace, place: false });+ moved = step.moved;+ if (step.arrived || step.event === "lost" || step.event === "blocked") { player.path = []; walk.current = null; }} else if (player.path.length > 0) {- const result = stepMover(player, speed, dt);- moved = result.moved;- applySeparation(player, separation(player, player.heading, bodiesExcept(null, null)), dt, (q) => isWalkable(grid, q));+ player.path = [];+ }+ // Never inside furniture or beyond the floor: whatever left the standing character in a solid cell (a floor+ // plan rebuilt under it, a seat it was lifted out of) puts it on the nearest free ground.+ if (player.path.length === 0 && !isWalkable(grid, player)) {+ const out = nearestWalkable(grid, player, RESCUE_RANGE_M) ?? nearestWalkable(grid, layout.spawn) ?? layout.spawn;+ player.x = out.x; player.z = out.z;}player.moving = moved > 0;drive.current.mode = moved > 0 ? "walk" : performance.now() < useProgression.getState().cheerUntil ? "wave" : "idle";@@ -281,12 +292,14 @@ export function OfficePlayer({ layout, grid, look, name, awake, reduced }: {// What can the character reach right now? The lead's chair has its own prompt beside it.const chair = chairInReach(seatDesks(layout), player);if (useLeadSeat.getState().near !== (chair?.id ?? null)) useLeadSeat.getState().set({ near: chair?.id ?? null });- const nearby = chair ? null : nearestInteractable(layout);+ const nearby = chair ? null : nearestInteractable(layout, player, agentPositions, companions, REACH);// Compared with the store too: a floor switch clears the store's reading while the character still stands at the elevator.if (!sameSelection(nearby, nearbyRef.current) || !sameSelection(nearby, store.nearby)) { nearbyRef.current = nearby; store.setNearby(nearby); }});return (+ <>+ <RouteMarker animate={awake && !reduced} /><group ref={group} visible={!firstPerson}><mesh ref={ring} rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.02, 0]}><ringGeometry args={[0.42, 0.52, 40]} />@@ -306,5 +319,64 @@ export function OfficePlayer({ layout, grid, look, name, awake, reduced }: {)}</group></group>+ </>+ );+}++/**+ * Where a click sends the character: dots along the route and a ring at its+ * end, shown while a click-to-move walk is under way. It reads the route the+ * character is following, so it shortens as the walk goes on and vanishes on+ * arrival or when the keyboard takes over. Takes no pointer events.+ */+function RouteMarker({ animate }: { animate: boolean }) {+ const dots = useRef<InstancedMesh>(null);+ const goal = useRef<Group>(null);+ const pulse = useRef<Mesh>(null);+ const dummy = useMemo(() => new Object3D(), []);+ useFrame(({ clock }) => {+ const path = player.path;+ const showing = path.length > 0;+ if (goal.current) goal.current.visible = showing;+ if (dots.current) dots.current.visible = showing;+ if (!showing || !goal.current || !dots.current) return;+ const end = path[path.length - 1];+ goal.current.position.set(end.x, MARKER.y, end.z);+ if (pulse.current) {+ const beat = animate ? (clock.elapsedTime * 1.4) % 1 : 0.35;+ pulse.current.scale.setScalar(0.7 + beat * 0.9);+ (pulse.current.material as MeshBasicMaterial).opacity = animate ? 0.6 * (1 - beat) : 0.4;+ }+ const marks = routeMarks(player, path, 0.9, MARKER.dots);+ marks.forEach((mark, i) => {+ dummy.position.set(mark.x, MARKER.y, mark.z);+ dummy.rotation.set(-Math.PI / 2, 0, 0);+ dummy.updateMatrix();+ dots.current!.setMatrixAt(i, dummy.matrix);+ });+ dots.current.count = marks.length;+ dots.current.instanceMatrix.needsUpdate = true;+ });+ return (+ <>+ <instancedMesh ref={dots} args={[undefined, undefined, MARKER.dots]} visible={false} frustumCulled={false} raycast={() => null}>+ <circleGeometry args={[0.07, 12]} />+ <meshBasicMaterial color={MARKER.colour} transparent opacity={0.7} side={DoubleSide} depthWrite={false} />+ </instancedMesh>+ <group ref={goal} visible={false}>+ <mesh rotation={[-Math.PI / 2, 0, 0]} raycast={() => null}>+ <ringGeometry args={[0.2, 0.27, 32]} />+ <meshBasicMaterial color={MARKER.colour} transparent opacity={0.9} side={DoubleSide} depthWrite={false} />+ </mesh>+ <mesh rotation={[-Math.PI / 2, 0, 0]} raycast={() => null}>+ <circleGeometry args={[0.07, 16]} />+ <meshBasicMaterial color={MARKER.colour} transparent opacity={0.9} side={DoubleSide} depthWrite={false} />+ </mesh>+ <mesh ref={pulse} rotation={[-Math.PI / 2, 0, 0]} raycast={() => null}>+ <ringGeometry args={[0.3, 0.34, 32]} />+ <meshBasicMaterial color={MARKER.colour} transparent opacity={0.4} side={DoubleSide} depthWrite={false} />+ </mesh>+ </group>+ </>);}diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeProps.test.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeProps.test.tsxindex 046e5cf436..355a3e610c 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeProps.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeProps.test.tsx@@ -55,7 +55,8 @@ afterEach(() => {const KINDS = Object.keys(FURNITURE_SIZE) as FurnitureKind[];-describe("office props", () => {+// Every case mounts a scene graph; on a loaded runner the first mounts share the suite's start-up cost.+describe("office props", { timeout: 20_000 }, () => {it("has a renderer for every furniture kind", () => {expect(Object.keys(PROP_RENDERERS).sort()).toEqual([...KINDS].sort());});diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeProps.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeProps.tsxindex c33895eb57..2a9f0d389d 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeProps.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeProps.tsx@@ -21,6 +21,8 @@ import { WARDROBE_RENDERERS } from "./WardrobeRoom";import { LOBBY_RENDERERS } from "./LobbyDecor";import { SPAWN_RENDERERS } from "./SpawnPoint";import { LEVEL_HALL_RENDERERS } from "./LevelHall";+import { STUDIO_RENDERERS } from "./StudioBoard";+import { StaticBatch } from "./StaticBatch";import { ARCADE_RENDERERS } from "../arcade/ArcadeHallProps";import { MeetingChair } from "./OfficeChairs";import { Bookshelf, Box, Couch, GEO, MAT, matte, Plant, Rounded, Rug } from "./OfficeFurniture";@@ -569,15 +571,20 @@ export const PROP_RENDERERS: Record<FurnitureKind, (props: { item: Furniture })...LOBBY_RENDERERS,...SPAWN_RENDERERS,...LEVEL_HALL_RENDERERS,+ ...STUDIO_RENDERERS,...ARCADE_RENDERERS,};-/** One furniture item, placed at (x, 0, z) and turned by `rotationY` (0 = front faces +z). */-export const FurniturePiece = memo(function FurniturePiece({ item }: { item: Furniture }) {+/**+ * One furniture item, placed at (x, 0, z) and turned by `rotationY` (0 = front faces +z). `merged` draws the+ * piece as a few merged meshes that stay inside its own named group: for a piece that must remain an object of+ * its own (a station lights up through the meshes under its group) but is as static as any other.+ */+export const FurniturePiece = memo(function FurniturePiece({ item, merged = false }: { item: Furniture; merged?: boolean }) {const Render = PROP_RENDERERS[item.kind];return (<group position={[item.x, 0, item.z]} rotation={[0, item.rotationY, 0]} name={`prop:${item.id}`}>- <Render item={item} />+ {merged ? <StaticBatch signature={item.id} keepFlat><Render item={item} /></StaticBatch> : <Render item={item} />}</group>);});diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeRooms.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeRooms.tsxindex 05c71c0d35..b50bdf11d4 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeRooms.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeRooms.tsx@@ -4,12 +4,12 @@* Pattern textures and sign textures are drawn once and cached.*/import { useEffect, useMemo } from "react";-import { DoubleSide, MeshStandardMaterial, RepeatWrapping, type Texture } from "three";+import { BoxGeometry, DoubleSide, MeshStandardMaterial, RepeatWrapping, type BufferGeometry, type Texture } from "three";+import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js";import { Box, MAT, Rounded } from "./OfficeFurniture";import { cachedCanvasTexture } from "./canvasMaterials";import { ARCH, archPosts, type Door, type Room, type RoomKind, type WallSegment } from "./officeLayout";-import { LEAD_MAT } from "./LeadSuite";-import { OFFICE, ROOM_FLOOR_COLOURS } from "./officePalette";+import { CAMPUS_ROOM_FLOORS, OFFICE, ROOM_FLOOR_COLOURS } from "./officePalette";// ---------------------------------------------------------------------------// Floors@@ -28,13 +28,19 @@ function lcg(seed: number): () => number {const PATTERN_METRES: Record<RoomKind, number> = { lead: 2.6, team: 2, wardrobe: 2, reception: 3.2, break: 2.4, command: 3.2, server: 2,arcade: 2.4, classics: 2, puzzle: 2, action: 2, foyer: 2.4, prizes: 2, snack: 1.6, levels: 3.2 };-function drawFloor(kind: RoomKind, ctx: CanvasRenderingContext2D, w: number, h: number): void {- const { base, accents } = ROOM_FLOOR_COLOURS[kind];+interface FloorTones { base: string; accents: readonly string[] }+const CAMPUS_FLOORS: Partial<Record<RoomKind, FloorTones>> = CAMPUS_ROOM_FLOORS;+/** A room kind's floor tones: the agents floor's rooms wear the campus's finishes, every other floor its own. */+function floorTones(kind: RoomKind, campus: boolean): FloorTones {+ return (campus ? CAMPUS_FLOORS[kind] : undefined) ?? ROOM_FLOOR_COLOURS[kind];+}++function drawFloor(kind: RoomKind, { base, accents }: FloorTones, ctx: CanvasRenderingContext2D, w: number, h: number): void {const rand = lcg(kind.length * 7919 + kind.charCodeAt(0));ctx.fillStyle = base;ctx.fillRect(0, 0, w, h);if (kind === "lead") {- // Dark walnut chevron: columns of slanted planks that alternate direction, so+ // A chevron of planks: columns of slanted planks that alternate direction, so// the tile wraps seamlessly on both axes (64-px columns, 16-px planks).const col = 64, plank = 16, image = ctx.createImageData(w, h);const tones = accents.map((hex) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16)));@@ -160,8 +166,9 @@ function drawFloor(kind: RoomKind, ctx: CanvasRenderingContext2D, w: number, h:}}-function floorTexture(kind: RoomKind): Texture | null {- const texture = cachedCanvasTexture(`floor:${kind}`, 256, 256, (ctx, w, h) => drawFloor(kind, ctx, w, h));+function floorTexture(kind: RoomKind, campus: boolean): Texture | null {+ const tones = floorTones(kind, campus);+ const texture = cachedCanvasTexture(`floor:${kind}:${tones.base}`, 256, 256, (ctx, w, h) => drawFloor(kind, tones, ctx, w, h));if (texture) {texture.wrapS = texture.wrapT = RepeatWrapping;texture.anisotropy = 8;@@ -169,19 +176,19 @@ function floorTexture(kind: RoomKind): Texture | null {return texture;}-function RoomFloor({ room }: { room: Room }) {+function RoomFloor({ room, campus }: { room: Room; campus: boolean }) {const w = room.maxX - room.minX;const d = room.maxZ - room.minZ;const material = useMemo(() => {- const base = floorTexture(room.kind);+ const base = floorTexture(room.kind, campus);let map: Texture | null = null;if (base) {map = base.clone();map.repeat.set(w / PATTERN_METRES[room.kind], d / PATTERN_METRES[room.kind]);map.needsUpdate = true;}- return new MeshStandardMaterial({ color: map ? "#ffffff" : ROOM_FLOOR_COLOURS[room.kind].base, map, roughness: 0.85 });- }, [room.kind, w, d]);+ return new MeshStandardMaterial({ color: map ? "#ffffff" : floorTones(room.kind, campus).base, map, roughness: 0.85 });+ }, [room.kind, campus, w, d]);// The clone and its material belong to this room; the cached base texture stays.useEffect(() => () => { material.map?.dispose(); material.dispose(); }, [material]);return (@@ -192,9 +199,12 @@ function RoomFloor({ room }: { room: Room }) {);}-/** A floor overlay per room: walnut chevron (lead), slate felt (team), terrazzo (wardrobe), pale stone (reception), light oak (break). */-export function RoomFloors({ rooms }: { rooms: Room[] }) {- return <group>{rooms.map((room) => <RoomFloor key={room.id} room={room} />)}</group>;+/**+ * A floor overlay per room: a plank chevron (lead), slate felt (team), terrazzo (wardrobe), pale stone (reception),+ * light oak (break). `campus`: the agents floor, whose rooms take the campus's own oak, limestone and felt.+ */+export function RoomFloors({ rooms, campus = false }: { rooms: Room[]; campus?: boolean }) {+ return <group>{rooms.map((room) => <RoomFloor key={room.id} room={room} campus={campus} />)}</group>;}// ---------------------------------------------------------------------------@@ -211,35 +221,44 @@ const frostMaterial = new MeshStandardMaterial({color: "#f4f1ec", transparent: true, opacity: 0.55, roughness: 0.95, side: DoubleSide, depthWrite: false,});+/** A box of a wall run, in the run's own frame. */+function boxAt(size: [number, number, number], position: [number, number, number]): BufferGeometry {+ return new BoxGeometry(...size).translate(...position);+}+/*** One glass wall run: slim black steel base, mullions and top rail around a* clear pane with a frosted band at eye level, so the glass reads as glass.+ * Every room on every floor has the same glazing. A run is three meshes+ * whatever its length: the whole frame is one merged geometry, the two+ * frosted bands another.*/function GlassWall({ wall }: { wall: WallSegment }) {- // The lead office is framed in brass on a walnut base, behind warm-tinted glass.- const lead = wall.room === "lead";- const frame = lead ? LEAD_MAT.brass : MAT.railing;- const base = lead ? LEAD_MAT.walnutDark : MAT.railing;- const glass = lead ? LEAD_MAT.wallGlass : MAT.glass;const length = Math.hypot(wall.x2 - wall.x1, wall.z2 - wall.z1);- if (length < 0.05) return null;const angle = Math.atan2(wall.z2 - wall.z1, wall.x2 - wall.x1);- const posts = Math.max(2, Math.ceil(length / POST_SPACING) + 1);- const post = lead ? 0.05 : 0.03;+ const parts = useMemo(() => {+ const posts = Math.max(2, Math.ceil(length / POST_SPACING) + 1);+ const steel = [+ boxAt([length, 0.06, 0.06], [0, 0.03, 0]),+ boxAt([length, 0.04, 0.05], [0, WALL_HEIGHT - 0.02, 0]),+ ...Array.from({ length: posts }, (_, i) => boxAt([0.03, WALL_HEIGHT, 0.05], [-length / 2 + (length * i) / (posts - 1), WALL_HEIGHT / 2, 0])),+ ];+ const frame = mergeGeometries(steel);+ for (const piece of steel) piece.dispose();+ const bands = [boxAt([length, FROST.h, 0.024], [0, FROST.y, 0]), boxAt([length, FROST.stripeH, 0.024], [0, FROST.stripeY, 0])];+ const frost = mergeGeometries(bands);+ for (const band of bands) band.dispose();+ return { frame, frost };+ }, [length]);+ useEffect(() => () => { parts.frame?.dispose(); parts.frost?.dispose(); }, [parts]);+ if (length < 0.05) return null;return (- <group position={[(wall.x1 + wall.x2) / 2, 0, (wall.z1 + wall.z2) / 2]} rotation={[0, -angle, 0]}>- <Box size={[length, lead ? BASE_HEIGHT : 0.06, lead ? 0.1 : 0.06]} position={[0, lead ? BASE_HEIGHT / 2 : 0.03, 0]} material={base} />+ // The camera rig finds a wall run by this tag and lowers it while it stands between camera and character.+ <group position={[(wall.x1 + wall.x2) / 2, 0, (wall.z1 + wall.z2) / 2]} rotation={[0, -angle, 0]} userData={{ officeWall: wall }}>+ {parts.frame && <mesh geometry={parts.frame} material={MAT.railing} castShadow receiveShadow />}<Box size={[length, WALL_HEIGHT - BASE_HEIGHT - 0.04, 0.02]} position={[0, (WALL_HEIGHT + BASE_HEIGHT - 0.04) / 2, 0]}- material={glass} cast={false} />- {!lead && <>- <Box size={[length, FROST.h, 0.024]} position={[0, FROST.y, 0]} material={frostMaterial} cast={false} />- <Box size={[length, FROST.stripeH, 0.024]} position={[0, FROST.stripeY, 0]} material={frostMaterial} cast={false} />- </>}- <Box size={[length, 0.04, lead ? 0.07 : 0.05]} position={[0, WALL_HEIGHT - 0.02, 0]} material={frame} />- {Array.from({ length: posts }, (_, i) => (- <Box key={i} size={[post, WALL_HEIGHT, lead ? 0.07 : 0.05]} position={[-length / 2 + (length * i) / (posts - 1), WALL_HEIGHT / 2, 0]}- material={frame} />- ))}+ material={MAT.glass} cast={false} />+ {parts.frost && <mesh geometry={parts.frost} material={frostMaterial} />}</group>);}@@ -263,20 +282,20 @@ const SIGN_TEXT_W = 1.4;const SIGN_CANVAS = { w: 512, h: 112 } as const;const signMaterials = new Map<string, MeshStandardMaterial>();-/** A sign face; the lead office's is gold lettering on black between two brass rules. */+/** A sign face; the lead office's is bronze lettering between two fine rules, on the same board as every room's. */function signMaterial(label: string, lead = false): MeshStandardMaterial {const key = `${lead ? "lead" : "room"}:${label}`;let material = signMaterials.get(key);if (!material) {const map = cachedCanvasTexture(`room-sign:${key}`, SIGN_CANVAS.w, SIGN_CANVAS.h, (ctx, w, h) => {- ctx.fillStyle = lead ? "#111217" : OFFICE.signBoard;+ ctx.fillStyle = OFFICE.signBoard;ctx.fillRect(0, 0, w, h);if (lead) {- ctx.fillStyle = "#d8ae52";+ ctx.fillStyle = "#b08d5c";ctx.fillRect(14, 10, w - 28, 3);ctx.fillRect(14, h - 13, w - 28, 3);}- ctx.fillStyle = lead ? "#f5c55a" : OFFICE.signText;+ ctx.fillStyle = lead ? "#e3c594" : OFFICE.signText;ctx.textAlign = "center";ctx.textBaseline = "middle";// Shrink long names (e.g. "Despacho del líder") to fit before cutting them off.@@ -294,7 +313,7 @@ function signMaterial(label: string, lead = false): MeshStandardMaterial {});material = new MeshStandardMaterial({color: map ? "#ffffff" : OFFICE.signBoard, map, roughness: 0.8,- // The lead's gold lettering glows faintly, like a lit plaque.+ // The lead's bronze lettering glows faintly, like a lit plaque....(lead && map ? { emissive: "#ffffff", emissiveMap: map, emissiveIntensity: 0.35 } : {}),});signMaterials.set(key, material);@@ -308,7 +327,7 @@ function SignBoard({ label, lead = false }: { label: string; lead?: boolean }) {const textH = (SIGN_TEXT_W * SIGN_CANVAS.h) / SIGN_CANVAS.w;return (<group>- <Rounded size={[SIGN_W, SIGN_H, 0.06]} radius={0.025} position={[0, 0, 0]} material={lead ? LEAD_MAT.brass : MAT.sign} />+ <Rounded size={[SIGN_W, SIGN_H, 0.06]} radius={0.025} position={[0, 0, 0]} material={MAT.sign} /><mesh position={[0, 0, 0.0305]} material={material}><planeGeometry args={[SIGN_TEXT_W, textH]} /></mesh><mesh position={[0, 0, -0.0305]} rotation={[0, Math.PI, 0]} material={material}><planeGeometry args={[SIGN_TEXT_W, textH]} /></mesh></group>@@ -336,7 +355,7 @@ export function RoomSign({ room, label }: { room: Room; label: string }) {const { x, z, rotationY } = doorAnchor(room, door);return (<group position={[x, 0, z]} rotation={[0, rotationY, 0]}>- <Box size={[door.width, 0.07, 0.07]} position={[0, WALL_HEIGHT - 0.035, 0]} material={room.kind === "lead" ? LEAD_MAT.brass : MAT.railing} />+ <Box size={[door.width, 0.07, 0.07]} position={[0, WALL_HEIGHT - 0.035, 0]} material={MAT.railing} /><group position={[0, WALL_HEIGHT + SIGN_H / 2 + 0.02, 0]}><SignBoard label={label} lead={room.kind === "lead"} /></group></group>);diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsxindex e2f465df16..d9a51ccb03 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx@@ -1,9 +1,11 @@/**- * The office floor: an oak-floored plate floating in a starry night behind- * frameless glass, walled rooms in the north and south, one rug-zoned- * department per provider family in between — and everybody in it. Each- * floor dresses the shared plan in its own look (AgentsFloorLook /- * CodingFloorLook). The arcade floor on top has a plan and a look of its own+ * The office floors: an oak-floored plate floating in a starry night behind+ * frameless glass, walled rooms in the north and south and the desks in+ * between — and everybody in it. The agents floor is a team campus (a studio+ * per team round an atrium, boulevards, planted courts), the coding floor has+ * a department per IDE workspace; each dresses its plan in its own look+ * (AgentsFloorLook / CodingFloorLook). The Level Hall's floor wears the+ * agents floor's materials. The arcade floor has a plan and a look of its own* (ArcadeHall); the person, the elevator and the camera work the same there.*/import { useLayoutEffect, useMemo } from "react";@@ -17,8 +19,11 @@ import { DeskInstances } from "./DeskInstances";import { DeskDressing } from "./DeskDressing";import { CodingSlab, CodingStudio } from "./CodingFloorLook";import { CodingFloorAmbience } from "./CodingFloorAmbience";-import { AGENTS_SCENE, AgentsDepartment, AgentsSlab } from "./AgentsFloorLook";+import { AGENTS_SCENE, AgentsDepartment, agentsRug, AgentsSlab } from "./AgentsFloorLook";import { AgentsFloorAmbience } from "./AgentsFloorAmbience";+import { CampusGround } from "./CampusGround";+import { StaticBatch } from "./StaticBatch";+import { BuildingShell } from "./BuildingShell";import { ExecutiveDesks, LeadOfficeLight } from "./LeadSuite";import { LiveMonitors } from "./LiveMonitors";import { TerminalMonitors } from "./TerminalMonitors";@@ -35,7 +40,7 @@ import { LevelHallFittings } from "./LevelHall";import { LobbyFittings } from "./LobbyDecor";import { SpawnFittings } from "./SpawnPoint";import { RoomFloors, RoomSign, RoomWalls } from "./OfficeRooms";-import { CHECKPOINT_ICON, CheckpointMarker } from "./CheckpointMarker";+import { StationObjects } from "./StationObjects";import { ElevatorCallButton } from "./ElevatorCallButton";import { ArcadeHall } from "../arcade/ArcadeHall";import { OFFICE_FIGURE_HEIGHT_M, OfficeAgents, type WalkerContext } from "./OfficeAgents";@@ -43,7 +48,7 @@ import { OfficePlayer } from "./OfficePlayer";import { OfficeDog } from "./OfficeDog";import { PlayerBubble } from "./OfficeBubbles";import { OfficeCameraRig } from "./OfficeCameraRig";-import { allDesks, type OfficeLayout, type Point } from "./officeLayout";+import { allDesks, leadDesks, type FurnitureKind, type OfficeLayout, type Point } from "./officeLayout";import { isWalkable, nearestWalkable, type NavGrid } from "./officeNav";import { CODING_SCENE, OFFICE } from "./officePalette";import { officeSession, player as playerBody, useOfficeStore, type OfficeFloor, type Selection } from "./officeStore";@@ -104,24 +109,18 @@ export interface OfficeSceneProps {elevatorCall: { lit: boolean; picking: boolean; onPress: () => void };}-/** The checkpoints, the elevator's call button and the person: the same on every floor. */+/** The stations, the elevator's call button and the person: the same on every floor. */function SharedFloorParts({ floor, layout, grid, ready, awake, reduced, player, selection, nearby, elevatorCall }: Pick<OfficeSceneProps,"floor" | "layout" | "grid" | "ready" | "awake" | "reduced" | "player" | "selection" | "nearby" | "elevatorCall">) {- const t = useT();- const select = useOfficeStore((s) => s.select);const shaft = layout.furniture.find((f) => f.kind === "elevator");const atLift = nearby?.kind === "checkpoint" && nearby.id === "elevator";return (<>- {/* At the elevator its call button takes over from the floating token, which would hide it. */}- {layout.checkpoints.filter((cp) => cp.id !== "elevator" || !atLift).map((cp) => (- <CheckpointMarker key={cp.id} checkpoint={cp} label={t(`society.office.cp_${cp.id}`)} icon={CHECKPOINT_ICON[cp.id]}- active={(nearby?.kind === "checkpoint" && nearby.id === cp.id) || (selection?.kind === "checkpoint" && selection.id === cp.id)}- animate={awake && !reduced} onActivate={() => select({ kind: "checkpoint", id: cp.id })} />- ))}+ {/* Stations are the objects of the room: a click target and a rim on each, nothing floating over the floor. */}+ <StationObjects layout={layout} nearby={nearby} selection={selection} animate={awake && !reduced} />{shaft && (<ElevatorCallButton shaft={shaft} floor={floor} lit={elevatorCall.lit} animate={awake && !reduced}- near={atLift} hint={atLift && !elevatorCall.picking} onPress={elevatorCall.onPress} />+ near={atLift} onPress={elevatorCall.onPress} />)}<FloorArrival floor={floor} layout={layout} grid={grid} ready={ready} awake={awake} /><OfficePlayer layout={layout} grid={grid} look={player.look} name={player.name} awake={awake} reduced={reduced} />@@ -167,6 +166,15 @@ export function OfficeScene(props: OfficeSceneProps) {);}+/**+ * The props a station lights up when the person is near, and the spawn point's pad: each stays an object of its+ * own (the rim is drawn on the meshes under its group) and is merged only within itself. Every other piece of+ * the agents floor is drawn merged with all the others (StaticBatch).+ */+const STATION_PROP_KINDS: ReadonlySet<FurnitureKind> = new Set<FurnitureKind>([+ "spawnTerminal", "spawnPad", "receptionDesk", "agentTotem", "teamBoard", "dressingMirror", "mirror", "coffeeBar", "elevator", "studioBoard", "teamStand",+]);+/** Everything that dresses the agents and coding floors: slab, rooms, departments, desks, monitors, furniture. */function OfficeFloorDressing({ floor, occupants, layout, agents, newcomers, awake, reduced, chats, onOpenScreen, desks, onFloorClick }: OfficeSceneProps & {desks: ReturnType<typeof allDesks>;@@ -177,6 +185,8 @@ function OfficeFloorDressing({ floor, occupants, layout, agents, newcomers, awakconst benchDesks = useMemo(() => desks.filter((d) => !d.size), [desks]);// Each desk takes its department's zone colour for the felt screen and the seat fabric.const zones = useMemo(() => new Map(layout.departments.flatMap((dept) => dept.desks.map((desk) => [desk.id, dept.tint] as const))), [layout]);+ // A team lead's place is marked in its team's colour: the chair, a mat under it and a name stand on the desk.+ const leadSigns = useMemo(() => new Map(leadDesks(layout).map(({ desk, dept }) => [desk.id, agentsRug(dept.tint).border] as const)), [layout]);const leadRoom = layout.rooms.find((r) => r.kind === "lead");const teamRoom = layout.rooms.find((r) => r.kind === "team");const breakRoom = layout.rooms.find((r) => r.kind === "break");@@ -186,6 +196,7 @@ function OfficeFloorDressing({ floor, occupants, layout, agents, newcomers, awakconst background = useMemo(() => new Color(space), [space]);const { minX, maxX, minZ, maxZ } = layout.bounds;const span = Math.max(maxX - minX, maxZ - minZ);+ const shadowMap = span > 50 ? 4096 : 2048;const table = layout.furniture.find((f) => f.kind === "meetingTable");const board = layout.furniture.find((f) => f.kind === "teamBoard");const wardrobeRug = layout.furniture.find((f) => f.kind === "roundRug" && f.room === "wardrobe");@@ -193,6 +204,17 @@ function OfficeFloorDressing({ floor, occupants, layout, agents, newcomers, awakconst spawnTerminal = layout.furniture.find((f) => f.kind === "spawnTerminal");const levelStage = layout.furniture.find((f) => f.kind === "studioStage");const levelGuide = layout.furniture.find((f) => f.kind === "levelGuide") ?? null;+ // The agents floor's furniture, room signs, studio walls and meeting chairs never change once built: they are+ // merged by material, a few dozen draw calls instead of well over a thousand (and as many again for shadows).+ const batch = floor === "agents";+ const roomLabels = layout.rooms.map((room) => t(`society.office.room_${room.kind}`));+ const signs = layout.rooms.map((room, i) => <RoomSign key={room.id} room={room} label={roomLabels[i]} />);+ const batchKey = useMemo(() => [+ layout.furniture.map((f) => `${f.id}@${f.x},${f.z},${f.rotationY}`).join(";"),+ layout.departments.map((d) => `${d.id}:${d.label}:${d.tint}@${d.minX},${d.minZ},${d.maxX},${d.maxZ}`).join(";"),+ roomLabels.join(";"), t("society.office.studio_pool"), t("society.office.studio_sign_team"), t("society.office.studio_sign_pool"),+ // eslint-disable-next-line react-hooks/exhaustive-deps+ ].join("|"), [layout, roomLabels.join(";"), t]);return (<><primitive attach="background" object={background} />@@ -200,32 +222,50 @@ function OfficeFloorDressing({ floor, occupants, layout, agents, newcomers, awak<Stars radius={span * 3} depth={span} count={2500} factor={4} saturation={0} fade speed={reduced ? 0 : 0.3} /><hemisphereLight args={coding ? [CODING_SCENE.sky, CODING_SCENE.ground, 0.95] : [AGENTS_SCENE.sky, AGENTS_SCENE.ground, 0.95]} /><ambientLight intensity={0.25} />- <directionalLight position={[maxX + 10, 26, maxZ + 6]} intensity={1.55} color="#fff7ec" castShadow- shadow-mapSize={[2048, 2048]} shadow-bias={-0.0004} shadow-normalBias={0.03}+ {/* The campus is twice as long as the other floors: its sun keeps the same shadow detail with a larger map. */}+ <directionalLight key={shadowMap} position={[maxX + 10, 26, maxZ + 6]} intensity={1.55} color="#fff7ec" castShadow+ shadow-mapSize={[shadowMap, shadowMap]} shadow-bias={-0.0004} shadow-normalBias={0.03}shadow-camera-left={-span * 0.7} shadow-camera-right={span * 0.7}- shadow-camera-top={span * 0.7} shadow-camera-bottom={-span * 0.7} shadow-camera-far={120} />+ shadow-camera-top={span * 0.7} shadow-camera-bottom={-span * 0.7} shadow-camera-far={Math.max(120, span * 2 + 40)} />{coding ? <CodingSlab layout={layout} onFloorClick={onFloorClick} /> : <AgentsSlab layout={layout} onFloorClick={onFloorClick} />}{coding ? <CodingFloorAmbience layout={layout} /> : <AgentsFloorAmbience layout={layout} />}- <RoomFloors rooms={layout.rooms} />+ {/* The agents floor and the Level Hall are floors of a building: window walls, the tower below, the city outside. */}+ {!coding && <BuildingShell layout={layout} />}+ <RoomFloors rooms={layout.rooms} campus={!coding} /><RoomWalls walls={layout.walls} />- {layout.rooms.map((room) => <RoomSign key={room.id} room={room} label={t(`society.office.room_${room.kind}`)} />)}+ {!batch && signs}{coding? <>{layout.departments.map((dept) => <CodingStudio key={dept.id} dept={dept} agents={agents} />)}<DeskDressing desks={benchDesks} departments={layout.departments} /></>: <>- {layout.departments.map((dept) => <AgentsDepartment key={dept.id} dept={dept} />)}- <DeskInstances desks={benchDesks} agents={agents} zones={zones} />- <DeskDressing desks={benchDesks} departments={layout.departments} floor="agents" />+ {/* The campus ground (boulevards, atrium, free plot, planted courts); the Level Hall's floor has none. */}+ <CampusGround layout={layout} />+ {benchDesks.length > 0 && <>+ <DeskInstances desks={benchDesks} agents={agents} zones={zones} />+ <DeskDressing desks={benchDesks} departments={layout.departments} floor="agents" leadSigns={leadSigns} />+ </>}</>}<ExecutiveDesks desks={desks} agents={agents} onOpenScreen={onOpenScreen} />{leadRoom && <LeadOfficeLight room={leadRoom} />}{floor === "coding"? <TerminalMonitors desks={desks} occupants={occupants} awake={awake} onOpen={onOpenScreen} />: <LiveMonitors desks={desks} agents={agents} chats={chats} onOpen={onOpenScreen} />}- {layout.furniture.map((item) => <FurniturePiece key={item.id} item={item} />)}- {table && <MeetingChairs table={table} />}+ {batch+ ? <>+ <StaticBatch signature={batchKey}>+ {signs}+ {layout.departments.map((dept) => <AgentsDepartment key={dept.id} dept={dept} />)}+ {layout.furniture.filter((item) => !STATION_PROP_KINDS.has(item.kind)).map((item) => <FurniturePiece key={item.id} item={item} />)}+ {table && <MeetingChairs table={table} />}+ </StaticBatch>+ {layout.furniture.filter((item) => STATION_PROP_KINDS.has(item.kind)).map((item) => <FurniturePiece key={item.id} item={item} merged />)}+ </>+ : <>+ {layout.furniture.map((item) => <FurniturePiece key={item.id} item={item} />)}+ {table && <MeetingChairs table={table} />}+ </>}{board && <TeamBoardFace board={board} enabled={awake && floor === "agents"} />}{teamRoom && table && <TeamRoomFittings room={teamRoom} table={table} />}{breakRoom && <BreakLoungeFittings room={breakRoom} furniture={layout.furniture} />}diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.lifecycle.test.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.lifecycle.test.tsxindex 51597ad61f..8e83ad13ed 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.lifecycle.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.lifecycle.test.tsx@@ -7,7 +7,7 @@ import { useProgression } from "../progression/progressionStore";import { OfficeStage } from "./OfficeStage";const state = vi.hoisted(() => ({- canvasMounts: 0, canvasUnmounts: 0, visits: 0, maps: 0,+ canvasMounts: 0, canvasUnmounts: 0, visits: 0, maps: 0, tools: 0, drawn: [] as [string, string][],roster: { data: { agents: [], sample: false } },coding: { occupants: [], byAgentId: new Map(), loaded: true },rosterEnabled: vi.fn(), codingEnabled: vi.fn(), chatsEnabled: vi.fn(),@@ -32,6 +32,8 @@ vi.mock("./useDeskChats", () => ({useDeskChats: (_sessions: unknown, enabled: boolean) => { state.chatsEnabled(enabled); return new Map(); },}));vi.mock("./useDprBudget", () => ({ useDprBudget: () => 1 }));+// The agents floor is built from the teams; the stage waits for the first answer about them.+vi.mock("@/lib/societyChatGroups", () => ({ useSocietyChatGroups: () => ({ data: [], isSuccess: true, isError: false }) }));vi.mock("@react-three/fiber", () => ({advance: () => undefined,Canvas: ({ children, frameloop }: { children: ReactNode; frameloop: string }) => {@@ -43,16 +45,30 @@ vi.mock("@react-three/fiber", () => ({return <div data-testid="canvas" data-loop={frameloop} data-active={active}>{children}</div>;},}));-vi.mock("./OfficeScene", () => ({ OfficeScene: ({ awake }: { awake: boolean }) => <div data-testid="scene" data-awake={awake} /> }));+vi.mock("./OfficeScene", () => ({+ OfficeScene: ({ awake, floor }: { awake: boolean; floor: string }) => {+ // What the stage draws, and what the shared store says at that very moment of rendering.+ state.drawn.push([floor, useOfficeStore.getState().floor]);+ return <div data-testid="scene" data-awake={awake} />;+ },+}));vi.mock("./OfficeCameraRig", () => ({ ZOOM_SECONDS: 1 }));vi.mock("./OfficeFrameDriver", () => ({ OfficeFrameDriver: () => null }));vi.mock("./OfficePlayer", () => ({ ownsKeyboard: () => false }));-vi.mock("./OfficePanels", () => ({ AgentPanel: () => null, CheckpointPanel: () => null }));+vi.mock("./OfficePanels", () => ({+ AgentPanel: () => null,+ StationSurface: () => <div data-testid="surface" />,+ stationSurface: (selection: { kind: string; id: string } | null) => (selection?.kind === "checkpoint" && selection.id === "manage" ? "sheet" : null),+}));+vi.mock("./TeamRoomPanel", () => ({ MeetingStatus: () => null }));+vi.mock("./OfficeHud", () => ({+ OfficeTools: () => { useEffect(() => { state.tools += 1; return () => { state.tools -= 1; }; }, []); return null; },+ StationPrompt: () => null, ControlHints: () => <div data-testid="hints" />, stationAction: () => "", stationLabel: () => "",+}));vi.mock("./PaneCommandPanel", () => ({ PaneCommandPanel: () => null }));vi.mock("./ArcadeCabinet", () => ({ ArcadeCabinet: () => null }));vi.mock("./ElevatorPanel", () => ({ ElevatorPanel: () => null }));vi.mock("./ElevatorDoors", () => ({ ElevatorDoors: () => null }));-vi.mock("./OfficeCompass", () => ({ OfficeCompass: () => null }));vi.mock("./OfficeMinimap", () => ({ OfficeMinimap: () => {useEffect(() => { state.maps += 1; return () => { state.maps -= 1; }; }, []);return null;@@ -82,8 +98,15 @@ it("retains one canvas across chat visits while stopping input, visits, HUD andexpect(state.canvasMounts).toBe(1);expect(state.visits).toBe(1);expect(state.maps).toBe(1);+ expect(state.tools).toBe(1);+ // H opens the directory at the reception from anywhere, as a dialog over the map; H again closes it.+ fireEvent.keyDown(window, { code: "KeyH" });+ expect(useOfficeStore.getState().selection).toEqual({ kind: "checkpoint", id: "manage" });+ expect(screen.getByTestId("surface")).toBeTruthy();fireEvent.keyDown(window, { code: "KeyH" });- expect(useOfficeStore.getState().selection).toEqual({ kind: "checkpoint", id: "create" });+ expect(useOfficeStore.getState().selection).toBeNull();+ fireEvent.keyDown(window, { code: "KeyH" });+ expect(useOfficeStore.getState().selection).toEqual({ kind: "checkpoint", id: "manage" });view.rerender(<OfficeStage active={false} />);expect(screen.getByTestId("canvas")).toBe(canvas);@@ -92,6 +115,8 @@ it("retains one canvas across chat visits while stopping input, visits, HUD andexpect(screen.getByTestId("scene").dataset.awake).toBe("false");expect(state.visits).toBe(0);expect(state.maps).toBe(0);+ expect(state.tools).toBe(0);+ expect(screen.queryByTestId("surface")).toBeNull();expect(state.rosterEnabled).toHaveBeenLastCalledWith(false);expect(state.codingEnabled).toHaveBeenLastCalledWith(false);expect(state.chatsEnabled).toHaveBeenLastCalledWith(false);@@ -122,6 +147,24 @@ it("retains one canvas across chat visits while stopping input, visits, HUD andexpect(state.maps).toBe(0);});+it("opens on the floor its host names without writing to the shared store while rendering", () => {+ useOfficeStore.setState({ floor: "agents" });+ state.drawn.length = 0;+ // Another mounted office (the Agents view behind the IDE tab) watches the same store.+ const seenByOther: string[] = [];+ function OtherHost() { seenByOther.push(useOfficeStore((s) => s.floor)); return null; }+ render(<><OtherHost /><OfficeStage initialFloor="coding" /></>);+ // The store was untouched while the stage rendered: the switch came after, in an effect…+ expect(state.drawn[0]).toEqual(["coding", "agents"]);+ // …yet the stage never drew a frame of the other floor,+ expect(state.drawn.map(([floor]) => floor)).not.toContain("agents");+ // and the store, and with it every other host, ends up on the named floor.+ expect(useOfficeStore.getState().floor).toBe("coding");+ expect(seenByOther).toEqual(["agents", "coding"]);+ expect(document.querySelector(".office-stage")?.getAttribute("data-office-floor")).toBe("coding");+ useOfficeStore.setState({ floor: "agents" });+});+it("releases the coding poll while a visited coding floor is hidden", () => {const view = render(<OfficeStage initialFloor="coding" />);expect(state.codingEnabled).toHaveBeenLastCalledWith(true);diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsxindex 94a666707c..792db5ca29 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx@@ -7,7 +7,7 @@* on the monitor, and Gigi flying along with the person. The top floor is the* arcade: a hall of retro cabinets, every one of them playable.*/-import { Component, lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import { Component, lazy, Suspense, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";import { useQueryClient } from "@tanstack/react-query";import { useSyncCompanionPet } from "../companion/companionPetStore";import { useActivePet } from "@/hooks/usePets";@@ -21,14 +21,16 @@ import { useEventStore } from "@/store/events";import { useQuickCreateAgent, useSocietyRoster, type SocietyAgent } from "../data";import { isCreateCancelled } from "../create/createAgentStore";import { OfficeScene } from "./OfficeScene";-import { allDesks, buildOfficeLayout, countStates, MAX_SEATED } from "./officeLayout";+import { allDesks, buildOfficeLayout, countStates, seatedCount, type OfficeTeamInput } from "./officeLayout";+import { buildHallLayout } from "./hallFloorLayout";+import { useSocietyChatGroups } from "@/lib/societyChatGroups";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, switchFloor, useOfficeStore, type OfficeFloor } from "./officeStore";+import { player, sameSelection, switchFloor, useOfficeStore, type OfficeFloor, type Selection } from "./officeStore";import { agentPositions, seatedAtDesk } from "./walkerRegistry";import { useCodingFloorOccupants, type PaneOccupant } from "./codingFloor";import { openPaneSession } from "./codingNavigate";@@ -36,7 +38,10 @@ import { useDprBudget } from "./useDprBudget";import { knownOnFloor, noteArrivals } from "./officeFloors";import { atElevator } from "./elevatorCall";import { loadProfile, playerLook, saveProfile, type PlayerProfile } from "./playerProfile";-import { AgentPanel, CheckpointPanel, type OfficeActions } from "./OfficePanels";+import { AgentPanel, StationSurface, stationSurface, type OfficeActions } from "./OfficePanels";+import { MeetingStatus } from "./TeamRoomPanel";+import { ControlHints, OfficeTools, StationPrompt, stationAction, stationLabel, type PromptLine } from "./OfficeHud";+import { CALL_MS, isReception, loungeCentre, selectionKey, spawnScreenDive, stationOf, stationsFor } from "./stations";import { PaneCommandPanel } from "./PaneCommandPanel";import type { WalkerContext } from "./OfficeAgents";import { ownsKeyboard } from "./OfficePlayer";@@ -51,7 +56,6 @@ import "./officeHud.css";import "./officeMinimap.css";import "./officeFloors.css";import { OfficeMinimap } from "./OfficeMinimap";-import { OfficeCompass } from "./OfficeCompass";import { OfficeFullMap } from "./OfficeFullMap";import { OfficeFrameDriver } from "./OfficeFrameDriver";import { useProgressionSync } from "../progression/useProgressionSync";@@ -76,6 +80,14 @@ const REFRESH_JITTER_MS = 1500;const EMPTY_OCCUPANTS: ReadonlyMap<string, PaneOccupant> = new Map();+/** How long a station's short answer stays on screen. */+const NOTICE_MS = 4200;++/** Is this key press text going into a field? */+function typesText(target: EventTarget | null): boolean {+ return target instanceof HTMLElement && (target.isContentEditable || target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.tagName === "SELECT");+}+/** The elevator doors: they slide in DOORS_MS and stay shut between DOORS_HOLD_MIN_MS and DOORS_HOLD_MAX_MS while the floor changes. */const DOORS_MS = 640;const DOORS_HOLD_MIN_MS = 450;@@ -154,11 +166,24 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenconst { generation } = useWebglSurface(hostRef);const webgl = useWebglSupported();// A mount that names a floor opens there (e.g. the IDE tab on the coding floor).- useState(() => { if (initialFloor) switchFloor(initialFloor, false); return null; });- const floor = useOfficeStore((s) => s.floor);+ // The switch writes to the store every host shares, so it happens in a layout effect, never while rendering+ // (another mounted office subscribed to `floor` would be updated in the middle of this render). Until it has+ // run, this stage already renders the floor it was asked for, so not a single frame shows the other one.+ const [opening, setOpening] = useState<OfficeFloor | null>(initialFloor ?? null);+ useLayoutEffect(() => {+ if (!opening) return;+ switchFloor(opening, false);+ setOpening(null);+ // Once per mount: a host that changes `initialFloor` later does not move a person who has ridden elsewhere.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);+ const storeFloor = useOfficeStore((s) => s.floor);+ const floor = opening ?? storeFloor;const coding = floor === "coding";// The arcade floor has no agents: no roster, desks or chats, just the cabinets.const arcade = floor === "arcade";+ // Nobody works in the Level Hall either: it is the levels' own floor.+ const hall = floor === "hall";const roster = useSocietyRoster(awake);useRosterRefresh(awake && floor === "agents");// Jarvis keeps the person company as the pet chosen in My Pets.@@ -178,8 +203,17 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenconst codingFloor = useCodingFloorOccupants(awake && (coding || atLift));const jarvisAgents = useMemo(() => (roster.data?.agents ?? []).filter((a) => a.lifecycle !== "archived"), [roster.data]);const codingAgents = useMemo(() => codingFloor.occupants.map((o) => o.agent), [codingFloor.occupants]);- const active = useMemo(() => (arcade ? [] : coding ? codingAgents : jarvisAgents), [arcade, coding, codingAgents, jarvisAgents]);- const ready = arcade ? true : coding ? codingFloor.loaded : !!roster.data;+ // The agents floor is built from the teams (society chat groups): every team has its studio. The roster waits+ // for the first answer about them, so nobody is seated in the pool and then sent across the floor.+ const chatGroups = useSocietyChatGroups(awake && floor === "agents");+ // A first failed read counts as an answer too: the floor opens without teams and rebuilds if a retry brings them.+ const teamsKnown = chatGroups.isSuccess || chatGroups.isError || chatGroups.failureCount > 0;+ const teams = useMemo<OfficeTeamInput[]>(() => (chatGroups.data ?? []).map((group) => ({+ id: group.group_id, name: group.name, members: group.members, createdMs: group.created_ms, leadId: group.lead_agent_id ?? null,+ })), [chatGroups.data]);+ const active = useMemo(() => (arcade || hall ? [] : coding ? codingAgents : teamsKnown ? jarvisAgents : []),+ [arcade, hall, coding, codingAgents, jarvisAgents, teamsKnown]);+ const ready = arcade || hall ? true : coding ? codingFloor.loaded : !!roster.data && teamsKnown;const occupants = useMemo(() => (coding ? codingFloor.byAgentId : EMPTY_OCCUPANTS), [coding, codingFloor.byAgentId]);const occupantsRef = useRef(occupants);occupantsRef.current = occupants;@@ -187,10 +221,16 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenconst newcomers = useNewcomers(active, floor);// The floor plan depends on who works where, never on run state: a status// refresh changes monitors and behaviour without re-seating anyone.- const seatingKey = floor + ":" + active.map((a) => `${a.agentId}|${a.tier}|${a.providerLabel}|${a.createdMs}`).join(",");- const layout = useMemo(() => (floor === "arcade" ? buildArcadeLayout() : buildOfficeLayout(active, { variant: floor })),+ // The same holds for the teams: their 10 s refetch rebuilds the floor only when a team's name, members or lead changed.+ const teamsKey = floor === "agents"+ ? teams.map((team) => `${team.id}|${team.name}|${team.createdMs}|${team.leadId ?? ""}|${team.members.join("+")}`).join(",") : "";+ const seatingKey = floor + ":" + active.map((a) => `${a.agentId}|${a.tier}|${a.providerLabel}|${a.createdMs}`).join(",") + "#" + teamsKey;+ const layout = useMemo(() => (floor === "arcade" ? buildArcadeLayout() : floor === "hall" ? buildHallLayout()+ : buildOfficeLayout(active, { variant: floor, teams })),// eslint-disable-next-line react-hooks/exhaustive-deps[seatingKey]);+ // Truthful overflow: how many of the floor's agents the plan could not seat.+ const seated = useMemo(() => seatedCount(layout), [layout]);const grid = useMemo(() => buildNavGrid(layout), [layout]);// One reservation book for the whole visit: a rebuilt floor plan (someone// joined or left) must not forget who already sits on which couch.@@ -318,10 +358,10 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen// own where the host has none. The panel closes and the camera turns to the pad, where the agent appears.const quickCreate = useQuickCreateAgent();const creatingRef = useRef(false);- const createAgent = useCallback(() => {+ const createAgent = useCallback((turnToPad = true) => {const store = useOfficeStore.getState();store.select(null);- if (Math.hypot(player.x - layout.arrival.x, player.z - layout.arrival.z) > 4) store.focusOn(layout.arrival);+ if (turnToPad && Math.hypot(player.x - layout.arrival.x, player.z - layout.arrival.z) > 4) store.focusOn(layout.arrival);if (onCreateAgent) { onCreateAgent(); return; }// A double click must not create two agents.if (creatingRef.current) return;@@ -334,9 +374,93 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen}, [onCreateAgent, layout, quickCreate]);const actions = useMemo<OfficeActions>(() => ({onOpenAgent: openAgent,- onOpenLedger: openList, onCreateAgent: createAgent, onOpenGroup,+ onOpenLedger: openList, onCreateAgent: () => createAgent(), onOpenGroup,}), [openAgent, openList, createAgent, onOpenGroup]);+ // A short line the HUD says once (a station answered without opening anything).+ const [notice, setNotice] = useState<string | null>(null);+ const noticeTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);+ useEffect(() => () => clearTimeout(noticeTimer.current), []);+ const say = useCallback((text: string) => {+ setNotice(text);+ clearTimeout(noticeTimer.current);+ noticeTimer.current = setTimeout(() => setNotice(null), NOTICE_MS);+ }, []);+ // The coffee break in progress: who was called, until the call runs out on its own.+ const [coffeeBreak, setCoffeeBreak] = useState<{ ids: string[]; untilMs: number } | null>(null);+ useEffect(() => {+ if (!coffeeBreak) return;+ const timer = setTimeout(() => setCoffeeBreak(null), Math.max(0, coffeeBreak.untilMs - Date.now()));+ return () => clearTimeout(timer);+ }, [coffeeBreak]);+ // Stations that act instead of opening a surface: the spawn terminal opens the app's create dialog+ // (after a dive into its screen), the lead's desk selects the lead, the coffee bar calls or ends a break.+ useEffect(() => {+ if (!awake || selection?.kind !== "checkpoint") return;+ const store = useOfficeStore.getState();+ if (selection.id === "spawn") {+ store.select(null);+ clearTimeout(openTimer.current);+ // The dive leads into the dialog; a host that creates at once (no dialog) keeps the pad in view instead.+ const dive = onCreateAgent && !reduced ? spawnScreenDive(layout, player) : null;+ if (!dive) { createAgent(); return; }+ store.zoomInto(dive.target, dive.facing, dive.size);+ openTimer.current = setTimeout(() => createAgent(false), ZOOM_SECONDS * 1000 + 120);+ } else if (selection.id === "lead") {+ const lead = active.filter((a) => a.tier === "lead").sort((a, b) => a.createdMs - b.createdMs || a.agentId.localeCompare(b.agentId))[0];+ if (lead) { store.select({ kind: "agent", id: lead.agentId }); return; }+ store.select(null);+ say(t("society.office.lead_empty"));+ } else if (selection.id === "break") {+ store.select(null);+ if (coffeeBreak && coffeeBreak.untilMs > Date.now()) {+ store.release(coffeeBreak.ids);+ setCoffeeBreak(null);+ say(t("society.office.break_ended"));+ return;+ }+ const idle = active.filter((a) => a.state === "idle").map((a) => a.agentId);+ if (idle.length === 0) { say(t("society.office.break_none")); return; }+ store.summon(idle, loungeCentre(layout), CALL_MS);+ setCoffeeBreak({ ids: idle, untilMs: Date.now() + CALL_MS });+ say(t("society.office.break_called").replace("{0}", String(idle.length)));+ }+ }, [selection, awake, onCreateAgent, reduced, layout, createAgent, active, coffeeBreak, say, t]);+ // Something opened: whatever the pointer rested on in the world is behind it now (a dialog swallows the pointer-out).+ useEffect(() => {+ if (!selection) return;+ useOfficeStore.getState().setHover(null);+ document.body.style.cursor = "";+ }, [selection]);+ // The coding floor's spawn terminal: dive into its screen first, then its launcher opens (reduced motion: at once).+ const atLaunch = selection?.kind === "checkpoint" && selection.id === "launch";+ const [launcherOpen, setLauncherOpen] = useState(false);+ const layoutRef = useRef(layout);+ layoutRef.current = layout;+ useEffect(() => {+ if (!awake || !atLaunch) { setLauncherOpen(false); return; }+ const dive = reduced ? null : spawnScreenDive(layoutRef.current, player);+ if (!dive) { setLauncherOpen(true); return; }+ useOfficeStore.getState().zoomInto(dive.target, dive.facing, dive.size);+ const timer = setTimeout(() => setLauncherOpen(true), ZOOM_SECONDS * 1000 + 120);+ return () => clearTimeout(timer);+ }, [atLaunch, awake, reduced]);+ // A team studio that left the floor plan takes its open sheet with it.+ useEffect(() => {+ if (awake && selection?.kind === "team" && !stationOf(layout, selection)) select(null);+ }, [selection, layout, select, awake]);++ // Whatever closes (a dialog, a docked panel) hands the keyboard back to the map's canvas host, so the walking+ // keys answer at once and focus never strands on a button that is gone.+ const focusMap = useCallback(() => hostRef.current?.focus({ preventScroll: true }), []);+ const hadSelection = useRef(false);+ useEffect(() => {+ const had = hadSelection.current;+ hadSelection.current = !!selection;+ if (!awake || selection || !had) return;+ const focused = document.activeElement;+ if (!focused || focused === document.body) focusMap();+ }, [selection, awake, focusMap]);// Escape closes an open panel before it can leave the map.useEffect(() => {if (!awake) return;@@ -346,6 +470,7 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenevent.preventDefault();event.stopPropagation();select(null);+ focusMap();};document.addEventListener("keydown", onKey, true);return () => document.removeEventListener("keydown", onKey, true);@@ -353,16 +478,18 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen// H (or the HUD button) opens reception on the controls guide from anywhere, and closes it again.const toggleGuide = useCallback(() => {- const current = useOfficeStore.getState().selection;- if (current?.kind === "checkpoint" && current.id === "create") { select(null); return; }+ if (isReception(useOfficeStore.getState().selection)) { select(null); return; }useReceptionTab.getState().setTab("controls");- select({ kind: "checkpoint", id: "create" });+ select({ kind: "checkpoint", id: "manage" });}, [select]);useEffect(() => {if (!awake) return;const onKey = (event: KeyboardEvent) => {- if (event.code !== "KeyH" || event.repeat || event.ctrlKey || event.metaKey || event.altKey || ownsKeyboard(event.target)) return;- if (useOfficeStore.getState().selection?.kind === "arcade") return;+ if (event.code !== "KeyH" || event.repeat || event.ctrlKey || event.metaKey || event.altKey) return;+ const current = useOfficeStore.getState().selection;+ // The open directory is a dialog of its own: H closes it again unless the person is typing in it.+ if (isReception(current) ? typesText(event.target) : ownsKeyboard(event.target)) return;+ if (current?.kind === "arcade") return;event.preventDefault();toggleGuide();};@@ -400,6 +527,7 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenconst store = useOfficeStore.getState();store.select(null);store.setNearby(null);+ store.setHover(null);store.clearSummons();}, []);@@ -413,9 +541,13 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpensetRide(null);setMapOpen(false);useProgression.getState().openPanel(null);+ clearTimeout(noticeTimer.current);+ setNotice(null);+ setCoffeeBreak(null);const store = useOfficeStore.getState();store.select(null);store.setNearby(null);+ store.setHover(null);store.clearSummons();}, [onScreen]);@@ -427,27 +559,41 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenconst selectedAgent = selection?.kind === "agent" ? agents.get(selection.id) ?? null : null;const selectedPane = selectedAgent ? occupants.get(selectedAgent.agentId) ?? null : null;const nearbyGame = nearby?.kind === "arcade" ? gameForCabinet(nearby.id) : null;- const nearbyLabel = nearby- ? nearby.kind === "agent"- ? t(coding ? "society.office.prompt_pane" : "society.office.prompt_agent").replace("{0}", agents.get(nearby.id)?.name ?? "")- : nearby.kind === "arcade"- ? nearbyGame ? t("society.arcade.play_prompt").replace("{0}", nearbyGame.title) : t("society.office.arcade_prompt")- : t(`society.office.cp_${nearby.id}_hint`)- : null;+ // The one prompt: what the pointer rests on from afar, else what the character stands at.+ const hover = useOfficeStore((s) => s.hover);+ const promptTarget: Selection | null = hover && !sameSelection(hover, nearby) ? hover : nearby;+ const breakOn = !!coffeeBreak;+ const promptLine = useMemo<PromptLine | null>(() => {+ if (!promptTarget) return null;+ const how = promptTarget === nearby ? "key" : "click";+ if (promptTarget.kind === "agent") {+ const name = agents.get(promptTarget.id)?.name;+ return name ? { how, action: t(coding ? "society.office.prompt_pane" : "society.office.prompt_agent").replace("{0}", name) } : null;+ }+ if (promptTarget.kind === "arcade") {+ const game = gameForCabinet(promptTarget.id);+ return { how, action: game ? t("society.arcade.play_prompt").replace("{0}", game.title) : t("society.office.arcade_prompt") };+ }+ const station = stationsFor(layout).find((s) => s.key === selectionKey(promptTarget));+ return station ? { how, action: stationAction(station, t, breakOn), object: stationLabel(station, t) } : null;+ }, [promptTarget, nearby, agents, coding, layout, breakOn, t]);// Standing at a retro cabinet fetches its overlay, so pressing E opens it at once instead of after a chunk load.const nearbyRetro = nearbyGame?.kind === "retro";useEffect(() => { if (nearbyRetro) void import("../arcade/RetroArcadeOverlay"); }, [nearbyRetro]);// The cabinet being played: the break room's (and the hall's Asteroid Run) open the 3D game, the others a retro game.const playing = selection?.kind === "arcade" ? gameForCabinet(selection.id) : null;const playsAsteroids = selection?.kind === "arcade" && (!playing || playing.kind === "asteroid3d");- const titleKey = arcade ? "society.office.arcade_floor_title" : coding ? "society.office.coding_title" : "society.office.title";+ const titleKey = arcade ? "society.office.arcade_floor_title" : hall ? "society.office.hall_floor_title"+ : coding ? "society.office.coding_title" : "society.office.title";const playerName = profile.name.trim() || t("society.office.you");const playerToyLook = useMemo(() => playerLook(profile), [profile]);const agentNames = useMemo(() => new Map(jarvisAgents.map((a) => [a.agentId, a.name])), [jarvisAgents]);- const showHintBar = useOfficeSettings((s) => s.showHintBar);- const receptionOpen = selection?.kind === "checkpoint" && selection.id === "create";- // Mission Control and the spawn point carry forms: they get the wide slot, like reception.- const widePanel = selection?.kind === "checkpoint" && (selection.id === "mission" || selection.id === "spawn" || selection.id === "launch");+ const hintsSeen = useOfficeSettings((s) => s.hintsSeen);+ const receptionOpen = isReception(selection);+ // A station's own surface: a dialog over the map, or a panel docked beside it (the wardrobe).+ // The coding floor's spawn terminal has a screen: its launcher opens once the camera has dived into it.+ const surface = atLaunch && !launcherOpen ? null : stationSurface(selection);+ const agentPanel = selection?.kind === "agent" && !!selectedAgent && !selectedPane;// A full-view office draws no more pixels than a side-panel one would afford.const dpr = useDprBudget(hostRef);@@ -478,42 +624,35 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen{awake && <><OfficeVisit floor={floor} /><div className="office-hud office-hud-left" data-office-ui>+ {/* One card: the floor's name, and under it who is doing what. */}<div className="office-card office-title"><strong>{t(titleKey)}</strong>- <span>{arcade- ? t("society.office.arcade_floor_subtitle").replace("{0}", String(ARCADE_GAMES.length))- : t(coding ? "society.office.coding_subtitle" : "society.office.subtitle").replace("{0}", String(active.length))}</span>+ {arcade+ ? <span>{t("society.office.arcade_floor_subtitle").replace("{0}", String(ARCADE_GAMES.length))}</span>+ : hall ? <span>{t("society.office.hall_floor_subtitle")}</span> : (+ <span className="office-states" 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))}</span>+ {counts.paused > 0 && <span data-tone="paused"><i aria-hidden />{t("society.office.count_paused").replace("{0}", String(counts.paused))}</span>}+ </span>+ )}</div><LevelHud playerName={playerName} petName={petName} compact={compact} />- {arcade && <p className="office-card office-note">{t("society.office.arcade_floor_hint")}</p>}- {!arcade && <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))}</span>- {counts.paused > 0 && <span data-tone="paused"><i aria-hidden />{t("society.office.count_paused").replace("{0}", String(counts.paused))}</span>}- </div>}+ {/* A running team meeting, while its sheet is closed; this card also ends it when its time is up. */}+ {surface !== "sheet" && <MeetingStatus agents={active} layout={layout} actions={actions} compact />}{!coding && roster.data?.sample && <p className="office-card office-note">{t("society.office.sample")}</p>}{coding && codingFloor.loaded && active.length === 0 && <p className="office-card office-note">{t("society.office.coding_empty")}</p>}- {active.length > MAX_SEATED && <p className="office-card office-note">{t("society.office.overflow").replace("{0}", String(MAX_SEATED))}</p>}+ {active.length > seated && <p className="office-card office-note">{t("society.office.overflow").replace("{0}", String(seated))}</p>}</div>- <div className="office-hud office-hud-right" data-office-ui>- <button type="button" className="office-button" aria-pressed={follow} onClick={() => useOfficeStore.getState().setFollow(true)}>{t("society.office.me")}</button>- <button type="button" className="office-button" onClick={() => setOverview((v) => v + 1)}>{t("society.office.overview")}</button>- <button type="button" className="office-button" onClick={() => select({ kind: "checkpoint", id: "wardrobe" })}>{t("society.office.cp_wardrobe")}</button>- <button type="button" className="office-button" aria-keyshortcuts="L" onClick={() => useProgression.getState().openPanel("overview")}>- {t("society.level.hud_button")}- </button>- <button type="button" className="office-button" aria-pressed={receptionOpen} aria-keyshortcuts="H"- onClick={toggleGuide}>- {t("society.office.guide.hud_button")}- </button>- {!arcade && (!coding || !compact || onOpenLedger) && (- <button type="button" className="office-button" onClick={openList}>- {t(coding ? (compact ? "society.office.ledger_coding" : "society.office.open_ide") : "society.office.ledger")}- </button>- )}- </div>+ {/* The wardrobe and the Level Hall are places (the places menu, their own keys), not permanent buttons. */}+ <OfficeTools layout={layout} follow={follow} onFollow={() => useOfficeStore.getState().setFollow(true)}+ onOverview={() => setOverview((v) => v + 1)} helpOpen={receptionOpen} onHelp={toggleGuide}+ list={!arcade && !hall && (!coding || !compact || onOpenLedger) ? {+ label: t(coding ? (compact ? "society.office.ledger_coding" : "society.office.open_ide") : "society.office.ledger"),+ ide: coding && !compact, onOpen: openList,+ } : null} />{playsAsteroids && <ArcadeCabinet onClose={() => select(null)} />}{playing && playing.kind === "retro" && (@@ -526,23 +665,30 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen{selection?.kind === "agent" && selectedPane && (<PaneCommandPanel occupant={selectedPane} compact={compact} onOpen={() => openPaneSession(selectedPane.pane)} onClose={() => select(null)} />)}- {selection && selection.kind !== "arcade" && !(selection.kind === "agent" && selectedPane) && (- <div className="office-panel-slot" data-wide={receptionOpen || widePanel || undefined}>- {selection.kind === "agent" && selectedAgent && <AgentPanel agent={selectedAgent} actions={actions} onClose={() => select(null)} />}- {/* The Level Hall's checkpoints open their own screen (the effect above), never a side panel. */}- {selection.kind === "checkpoint" && selection.id !== "studio" && selection.id !== "levels" && (- <CheckpointPanel id={selection.id} floor={floor} agents={active} layout={layout} sample={!coding && (roster.data?.sample ?? false)}- profile={profile} onProfile={updateProfile} actions={actions} onClose={() => select(null)} />- )}+ {/* An agent's walkie-talkie and the wardrobe sit beside the map; every other station's surface is a dialog over it. */}+ {(agentPanel || surface === "side") && selection && (+ <div className="office-panel-slot" data-tall={surface === "side" || undefined}>+ {agentPanel && selectedAgent+ ? <AgentPanel agent={selectedAgent} actions={actions} onClose={() => select(null)} />+ : <StationSurface selection={selection} floor={floor} agents={active} layout={layout} grid={grid} sample={!coding && (roster.data?.sample ?? false)}+ profile={profile} onProfile={updateProfile} actions={actions} onClose={() => select(null)} />}</div>)}-- {nearbyLabel && !selection && !picking && !ride && (- <button type="button" className="office-hud office-prompt" data-office-ui onClick={() => nearby && select(nearby)}>- <kbd>E</kbd>{nearbyLabel}- </button>+ {surface === "sheet" && selection && (+ <StationSurface selection={selection} floor={floor} agents={active} layout={layout} grid={grid} sample={!coding && (roster.data?.sample ?? false)}+ profile={profile} onProfile={updateProfile} actions={actions} onClose={() => select(null)} returnFocus={focusMap} />)}- {!compact && <OfficeCompass layout={layout} agents={agents} selectedId={selection?.kind === "agent" ? selection.id : null} />}++ {/* Bottom centre: the one prompt, a station's short answer, and the controls for a first visit. */}+ <div className="office-hud office-hud-bottom">+ {promptLine && promptTarget && !selection && !picking && !ride && (+ <StationPrompt line={promptLine} compact={compact} onUse={() => select(promptTarget)} />+ )}+ <div role="status" aria-live="polite">{notice && <p className="office-card office-notice" data-office-ui>{notice}</p>}</div>+ {!compact && !hintsSeen && !selection && !picking && !ride && (+ <ControlHints onDismiss={() => useOfficeSettings.getState().set({ hintsSeen: true })} />+ )}+ </div>{diving && <div className="office-dive-fade" aria-hidden />}{picking && !ride && <ElevatorPanel floor={floor} onPick={pickFloor} onClose={closePicker} />}{ride && <ElevatorDoors from={ride.from} to={ride.to} phase={ride.phase} />}@@ -550,7 +696,6 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenonOpenMap={() => setMapOpen(true)} />}<OfficeFullMap open={mapOpen} onOpen={() => setMapOpen(true)} onClose={() => setMapOpen(false)}layout={layout} agents={agents} selectedId={selection?.kind === "agent" ? selection.id : null} />- {!compact && showHintBar && <p className="office-hud office-help" data-office-ui>{t("society.office.help")}</p>}<LevelToasts names={agentNames} agents={jarvisAgents} /><LevelHallScreen agents={jarvisAgents} playerName={playerName} petName={petName} playerLook={playerToyLook} /><LevelUpBanner playerName={playerName} petName={petName} />diff --git a/jarvis/ui/web/frontend/src/components/society/office/ReceptionPanel.tsx b/jarvis/ui/web/frontend/src/components/society/office/ReceptionPanel.tsxindex 02c8975552..13235c5891 100644--- a/jarvis/ui/web/frontend/src/components/society/office/ReceptionPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/ReceptionPanel.tsx@@ -1,53 +1,35 @@/**- * Reception: the office's front desk and help centre. Three tabs — a welcome- * with hiring and every place on the floor, the complete controls guide (from- * officeControls, searchable), and the map's settings (officeSettings). H- * opens it on the controls tab from anywhere, so nobody has to find the desk- * to learn the keys.+ * Reception: the office's directory. Four tabs — everyone on the floor (show+ * on the map, open, the agents view), every place of the floor (open it, or+ * walk there), the complete controls guide (from officeControls, searchable)+ * and the map's settings (officeSettings). H opens it on the controls tab+ * from anywhere, so nobody has to find the desk to learn the keys.+ *+ * Nothing is created here: new agents come from the spawn terminal.*/-import { useId, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent } from "react";+import { useState } from "react";+import { ArrowDown, ArrowLeft, ArrowRight, ArrowUp, ChevronRight, Footprints, Search } from "lucide-react";import { useT } from "@/i18n";-import type { OfficeLayout } from "./officeLayout";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Switch } from "@/components/ui/switch";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";+import type { SocietyAgent } from "../data";+import { countStates, type OfficeLayout } from "./officeLayout";import { useOfficeStore, type OfficeFloor } from "./officeStore";-import { CHECKPOINT_ICON, IconSvg } from "./CheckpointMarker";-import { arrowCap, CONTROL_GROUPS, controlsFor, mouseGesture, type ControlGroup, type OfficeControl } from "./officeControls";+import { agentPositions } from "./walkerRegistry";+import { isReception, stationsFor, type Station } from "./stations";+import { AgentFace } from "./AgentFace";+import { StationGlyph } from "./stationIcons";+import { stationAction, stationLabel } from "./stationText";+import { arrowCap, CONTROL_GROUPS, controlsFor, mouseGesture, type ArrowKey, type OfficeControl } from "./officeControls";import { useOfficeSettings, useReceptionTab, type ReceptionTab } from "./officeSettings";+import type { OfficeActions } from "./OfficePanels";import "./reception.css";-const TABS: readonly ReceptionTab[] = ["welcome", "controls", "settings"];+const TABS: readonly ReceptionTab[] = ["agents", "places", "controls", "settings"];-/** Stroke-only glyphs in a 24 × 24 box, drawn like the checkpoint icons. */-const GLYPH = {- welcome: "M3 11l9-7 9 7M5.5 9.5V20h5v-6h3v6h5V9.5",- controls: "M4 6h16a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1zM7 10h.01M11 10h.01M15 10h.01M8 14h8",- settings: "M4 7h9M17 7h3M15 5v4M4 17h3M11 17h9M9 15v4",- move: "M12 3v18M3 12h18M9 6l3-3 3 3M18 9l3 3-3 3M9 18l3 3 3-3M6 9l-3 3 3 3",- camera: "M4 8h3l2-3h6l2 3h3v11H4zM12 16.5a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7z",- interact: "M9 11V5.5a1.5 1.5 0 0 1 3 0V11M12 10V8.5a1.5 1.5 0 0 1 3 0V12M15 11a1.5 1.5 0 0 1 3 0v3a7 7 0 0 1-7 7h-.5A6.5 6.5 0 0 1 5 16.5L3.8 13a1.5 1.5 0 0 1 2.7-1.2L9 15",- map: "M9 4L3 6v14l6-2 6 2 6-2V4l-6 2-6-2zM9 4v14M15 6v14",- arcade: "M7 9h10a4 4 0 0 1 0 8c-1.4 0-2.3-.8-2.8-2H9.8c-.5 1.2-1.4 2-2.8 2a4 4 0 0 1 0-8zM8 11.5v3M6.5 13h3M15.5 12.5h.01M17.5 14h.01",- run: "M13 4a1.5 1.5 0 1 0 0 .01M9 20l3-6 3 2v4M7 12l3-4 4 1 2 3 3 1",- bar: "M3 17h18v3H3zM6 18.5h.01M10 18.5h6M3 5h18v8H3z",- search: "M11 18a7 7 0 1 0 0-14 7 7 0 0 0 0 14zM20 20l-4-4",- chevron: "M9 6l6 6-6 6",- reset: "M4 12a8 8 0 1 0 2.4-5.7M4 4v5h5",- ArrowUp: "M12 19V5M6 11l6-6 6 6",- ArrowDown: "M12 5v14M6 13l6 6 6-6",- ArrowLeft: "M19 12H5M11 6l-6 6 6 6",- ArrowRight: "M5 12h14M13 6l6 6-6 6",-} as const;--type GlyphName = keyof typeof GLYPH;--function Glyph({ name }: { name: GlyphName }) {- return (- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden>- <path d={GLYPH[name]} />- </svg>- );-}--const GROUP_GLYPH: Record<ControlGroup, GlyphName> = { move: "move", camera: "camera", interact: "interact", map: "map", arcade: "arcade" };+const ARROW_ICON: Record<ArrowKey, typeof ArrowUp> = { up: ArrowUp, down: ArrowDown, left: ArrowLeft, right: ArrowRight };/** How a key cap reads aloud and in the search ("Space", "Arrow up", "Drag"). */function useCapLabel() {@@ -61,19 +43,23 @@ function useCapLabel() {};}-function KeyCaps({ control }: { control: OfficeControl }) {+export function KeyCaps({ control }: { control: Pick<OfficeControl, "keys"> }) {const t = useT();const label = useCapLabel();return (- <span className="office-rx-keys">+ <span className="office-keys">{control.keys.map((alt, i) => (- <span key={i} className="office-rx-alt">- {i > 0 && <span className="office-rx-or">{t("society.office.guide.or")}</span>}+ <span key={i} className="office-keys-alt">+ {i > 0 && <span className="office-keys-or">{t("society.office.guide.or")}</span>}{alt.map((cap, j) => {- if (cap === "+") return <span key={j} className="office-rx-plus" aria-hidden>+</span>;- if (mouseGesture(cap)) return <kbd key={j} className="office-rx-cap" data-mouse>{label(cap)}</kbd>;- if (arrowCap(cap)) return <kbd key={j} className="office-rx-cap" aria-label={label(cap)}><Glyph name={cap as GlyphName} /></kbd>;- return <kbd key={j} className="office-rx-cap">{label(cap)}</kbd>;+ if (cap === "+") return <span key={j} className="office-keys-plus" aria-hidden>+</span>;+ if (mouseGesture(cap)) return <kbd key={j} className="office-key" data-mouse>{label(cap)}</kbd>;+ const arrow = arrowCap(cap);+ if (arrow) {+ const Icon = ARROW_ICON[arrow];+ return <kbd key={j} className="office-key" aria-label={label(cap)}><Icon size={12} aria-hidden /></kbd>;+ }+ return <kbd key={j} className="office-key">{label(cap)}</kbd>;})}</span>))}@@ -81,6 +67,135 @@ function KeyCaps({ control }: { control: OfficeControl }) {);}+/**+ * Arrow keys inside the places list: up and down move through the rows, right+ * goes to a row's "walk there" and left back to the row, Home and End jump.+ * Returns the button to focus, or null when the key is not one of them.+ */+export function placesKeyTarget(list: HTMLElement, from: Element | null, key: string): HTMLElement | null {+ const rows = [...list.querySelectorAll<HTMLElement>("[data-place-open]")];+ if (rows.length === 0) return null;+ const row = from instanceof HTMLElement ? from.closest<HTMLElement>("[data-place-row]") : null;+ const index = row ? rows.findIndex((button) => row.contains(button)) : -1;+ if (key === "Home") return rows[0]!;+ if (key === "End") return rows[rows.length - 1]!;+ if (key === "ArrowDown") return rows[index < 0 ? 0 : Math.min(rows.length - 1, index + 1)]!;+ if (key === "ArrowUp") return rows[index < 0 ? rows.length - 1 : Math.max(0, index - 1)]!;+ if (!row) return null;+ if (key === "ArrowRight") return row.querySelector<HTMLElement>("[data-place-walk]");+ if (key === "ArrowLeft") return row.querySelector<HTMLElement>("[data-place-open]");+ return null;+}++/**+ * Every place of the floor as a real button: open it from here, or walk+ * there. Also the keyboard path to every station. The rooms' stations come+ * first, then the team studios' boards under their team's name.+ */+export function PlacesList({ layout, onPicked, withReception = false }: {+ layout: OfficeLayout; onPicked?: () => void;+ /** The reception itself is a place too, except in its own directory. */+ withReception?: boolean;+}) {+ const t = useT();+ const store = useOfficeStore;+ const stations = stationsFor(layout).filter((station) => withReception || !isReception(station.selection));+ const groups = [+ { id: "places", label: t("society.office.hud_places"), rows: stations.filter((station) => station.selection.kind !== "team") },+ { id: "teams", label: t("society.office.places_teams"), rows: stations.filter((station) => station.selection.kind === "team") },+ ].filter((group) => group.rows.length > 0);+ const point = (station: Station | null) => store.getState().setHover(station ? station.selection : null);+ // Whatever closes the list must not leave a place lit in the world.+ const done = () => { point(null); onPicked?.(); };+ return (+ <div className="grid gap-2" data-places+ onKeyDown={(event) => {+ const target = placesKeyTarget(event.currentTarget, document.activeElement, event.key);+ if (!target) return;+ // The arrows belong to the list while focus is in it; they must not walk the character too.+ event.preventDefault();+ event.stopPropagation();+ target.focus();+ target.scrollIntoView?.({ block: "nearest" });+ }}>+ {groups.map((group) => (+ <section key={group.id} className="grid gap-0.5" aria-label={group.label}>+ {groups.length > 1 && <h3 className="px-2 pt-1 text-xs font-semibold text-muted-foreground">{group.label}</h3>}+ <ul className="grid list-none gap-0.5 p-0">+ {group.rows.map((station) => {+ const name = stationLabel(station, t);+ const action = stationAction(station, t);+ return (+ <li key={station.key} data-place-row className="flex items-center gap-1 rounded-md hover:bg-secondary focus-within:bg-secondary"+ onPointerEnter={() => point(station)} onPointerLeave={() => point(null)}>+ <button type="button" data-place-open className="flex min-w-0 flex-1 items-center gap-3 rounded-md px-2 py-1.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ aria-label={`${name}: ${action}`}+ onFocus={() => point(station)} onBlur={() => point(null)}+ onClick={() => { done(); store.getState().select(station.selection); }}>+ <span aria-hidden className="grid size-7 shrink-0 place-items-center rounded-md border border-border bg-background text-muted-foreground"><StationGlyph icon={station.icon} size={15} /></span>+ <span className="grid min-w-0 gap-0.5">+ <span className="truncate text-sm font-medium text-foreground">{name}</span>+ <span className="truncate text-xs text-muted-foreground">{action}</span>+ </span>+ <ChevronRight size={14} aria-hidden className="ml-auto shrink-0 text-muted-foreground" />+ </button>+ <button type="button" data-place-walk className="mr-1 inline-flex size-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-background hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ aria-label={t("society.office.guide.place_walk_label").replace("{0}", name)} title={t("society.office.guide.place_walk")}+ onClick={() => { done(); store.getState().select(null); store.getState().requestWalk(station.approach); }}>+ <Footprints size={15} aria-hidden />+ </button>+ </li>+ );+ })}+ </ul>+ </section>+ ))}+ </div>+ );+}++function AgentsTab({ agents, actions }: { agents: readonly SocietyAgent[]; actions: OfficeActions }) {+ const t = useT();+ const counts = countStates(agents);+ const show = (agent: SocietyAgent) => {+ const store = useOfficeStore.getState();+ const where = agentPositions.get(agent.agentId);+ if (where) store.focusOn(where);+ store.select({ kind: "agent", id: agent.agentId });+ };+ return (+ <div className="grid gap-3">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <p className="text-sm text-muted-foreground">+ {[t("society.office.count_working").replace("{0}", String(counts.working)), t("society.office.count_waiting").replace("{0}", String(counts.waiting)),+ t("society.office.count_idle").replace("{0}", String(counts.idle))].join(" · ")}+ </p>+ <Button type="button" size="sm" variant="outline" onClick={actions.onOpenLedger}>{t("society.office.manage_action")}</Button>+ </div>+ {agents.length === 0 ? <p className="rounded-lg border border-dashed border-border p-5 text-sm text-muted-foreground">{t("society.office.manage_empty")}</p> : (+ <ul className="grid max-h-[22rem] list-none gap-0.5 overflow-y-auto p-0">+ {agents.map((agent) => (+ <li key={agent.agentId} className="flex items-center gap-3 rounded-md px-2 py-1.5 hover:bg-secondary/60">+ <AgentFace agent={agent} />+ <span className="grid min-w-0 flex-1">+ <span className="truncate text-sm font-medium" title={agent.name}>{agent.name}</span>+ {(agent.title || agent.providerLabel) && <span className="truncate text-xs text-muted-foreground">{agent.title || agent.providerLabel}</span>}+ </span>+ <span className="flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground">+ <i className="office-dot" data-state={agent.state} aria-hidden />{t(`society.office.state_${agent.state}`)}+ </span>+ <Button type="button" size="sm" variant="ghost" aria-label={t("society.office.show_agent").replace("{0}", agent.name)}+ onClick={() => show(agent)}>{t("society.office.action_show")}</Button>+ <Button type="button" size="sm" variant="ghost" aria-label={t("society.office.open_agent").replace("{0}", agent.name)}+ onClick={() => actions.onOpenAgent(agent.agentId)}>{t("society.office.action_open")}</Button>+ </li>+ ))}+ </ul>+ )}+ </div>+ );+}+function ControlsTab({ floor }: { floor: OfficeFloor }) {const t = useT();const label = useCapLabel();@@ -94,22 +209,22 @@ function ControlsTab({ floor }: { floor: OfficeFloor }) {.map((group) => ({ group, controls: controlsFor(group, floor).filter(matches) })).filter((g) => g.controls.length > 0);return (- <>- <label className="office-rx-search">- <Glyph name="search" />- <input type="search" value={query} onChange={(e) => setQuery(e.target.value)} placeholder={t("society.office.guide.search")}+ <div className="grid gap-3">+ <div className="relative">+ <Search size={15} aria-hidden className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />+ <Input type="search" className="pl-9" value={query} onChange={(e) => setQuery(e.target.value)} placeholder={t("society.office.guide.search")}aria-label={t("society.office.guide.search")}onKeyDown={(e) => { if (e.key === "Escape" && query) { e.preventDefault(); e.stopPropagation(); setQuery(""); } }} />- </label>- {groups.length === 0 ? <p className="office-rx-empty" role="status">{t("society.office.guide.search_empty")}</p> : (- <div className="office-rx-groups">+ </div>+ {groups.length === 0 ? <p className="py-4 text-center text-sm text-muted-foreground" role="status">{t("society.office.guide.search_empty")}</p> : (+ <div className="grid gap-4">{groups.map(({ group, controls }) => (- <section key={group} className="office-rx-group" aria-label={t(`society.office.guide.group_${group}`)}>- <h3><Glyph name={GROUP_GLYPH[group]} />{t(`society.office.guide.group_${group}`)}</h3>- <ul>+ <section key={group} className="grid gap-1" aria-label={t(`society.office.guide.group_${group}`)}>+ <h3 className="text-xs font-semibold text-muted-foreground">{t(`society.office.guide.group_${group}`)}</h3>+ <ul className="grid list-none p-0">{controls.map((control) => (- <li key={control.id}>- <span className="office-rx-what">{t(`society.office.guide.ctl_${control.id}`)}</span>+ <li key={control.id} className="flex items-center justify-between gap-3 border-t border-border/60 py-1.5 text-sm first:border-t-0">+ <span className="min-w-0">{t(`society.office.guide.ctl_${control.id}`)}</span><KeyCaps control={control} /></li>))}@@ -118,25 +233,19 @@ function ControlsTab({ floor }: { floor: OfficeFloor }) {))}</div>)}- </>+ <p className="flex items-center gap-2 text-xs text-muted-foreground"><kbd className="office-key">H</kbd>{t("society.office.guide.tip_guide")}</p>+ </div>);}-function Toggle({ glyph, label, hint, checked, onChange }: {- glyph: GlyphName; label: string; hint: string; checked: boolean; onChange: (next: boolean) => void;-}) {- const hintId = useId();+function SettingRow({ title, hint, children }: { title: string; hint: string; children: React.ReactNode }) {return (- <div className="office-rx-setting">- <span className="office-rx-icon"><Glyph name={glyph} /></span>- <div>- <strong>{label}</strong>- <span id={hintId}>{hint}</span>- </div>- <button type="button" role="switch" className="office-rx-switch" aria-checked={checked} aria-label={label}- aria-describedby={hintId} onClick={() => onChange(!checked)}>- <i aria-hidden />- </button>+ <div className="flex items-center justify-between gap-4 p-3">+ <span className="grid min-w-0 gap-0.5">+ <span className="text-sm font-medium">{title}</span>+ <span className="text-xs text-muted-foreground">{hint}</span>+ </span>+ {children}</div>);}@@ -145,104 +254,39 @@ function SettingsTab() {const t = useT();const settings = useOfficeSettings();return (- <>- <p className="office-rx-lead">{t("society.office.guide.settings_intro")}</p>- <h3 className="office-rx-heading">{t("society.office.guide.set_section_move")}</h3>- <div className="office-rx-settings">- <Toggle glyph="run" label={t("society.office.guide.set_always_run")} hint={t("society.office.guide.set_always_run_hint")}- checked={settings.alwaysRun} onChange={(alwaysRun) => settings.set({ alwaysRun })} />- </div>- <h3 className="office-rx-heading">{t("society.office.guide.set_section_view")}</h3>- <div className="office-rx-settings">- <Toggle glyph="bar" label={t("society.office.guide.set_hint_bar")} hint={t("society.office.guide.set_hint_bar_hint")}- checked={settings.showHintBar} onChange={(showHintBar) => settings.set({ showHintBar })} />+ <div className="grid gap-3">+ <p className="text-sm text-muted-foreground">{t("society.office.guide.settings_intro")}</p>+ <div className="divide-y divide-border rounded-lg border border-border">+ <SettingRow title={t("society.office.guide.set_always_run")} hint={t("society.office.guide.set_always_run_hint")}>+ <Switch checked={settings.alwaysRun} aria-label={t("society.office.guide.set_always_run")}+ onCheckedChange={(alwaysRun) => settings.set({ alwaysRun })} />+ </SettingRow>+ <SettingRow title={t("society.office.guide.set_hints")} hint={t("society.office.guide.set_hints_hint")}>+ <Button type="button" size="sm" variant="outline" disabled={!settings.hintsSeen} onClick={() => settings.set({ hintsSeen: false })}>+ {t("society.office.guide.set_hints_action")}+ </Button>+ </SettingRow></div>- <button type="button" className="office-rx-reset" onClick={settings.reset}><Glyph name="reset" />{t("society.office.guide.set_reset")}</button>- </>- );-}--function WelcomeTab({ floor, layout, onCreateAgent }: { floor: OfficeFloor; layout: OfficeLayout; onCreateAgent?: () => void }) {- const t = useT();- const places = layout.checkpoints.filter((cp) => cp.id !== "create");- const walk = (x: number, z: number) => {- const store = useOfficeStore.getState();- store.select(null);- store.requestWalk({ x, z });- };- return (- <>- {floor === "agents" && (- <div className="office-rx-hero">- <span className="office-rx-icon" data-tone="gold"><IconSvg icon="plus" /></span>- <div>- <strong>{t("society.office.guide.hero_title")}</strong>- <p>{t("society.office.create_body")}</p>- <button type="button" className="office-action office-action-primary" disabled={!onCreateAgent} onClick={() => onCreateAgent?.()}>- {t("society.office.create_action")}- </button>- </div>- </div>- )}- <h3 className="office-rx-heading">{t("society.office.guide.places")}</h3>- <ul className="office-rx-places">- {places.map((cp) => {- const name = t(`society.office.cp_${cp.id}`);- return (- <li key={cp.id}>- <button type="button" className="office-rx-place" aria-label={t("society.office.guide.place_walk_label").replace("{0}", name)}- onClick={() => walk((cp.approach ?? cp).x, (cp.approach ?? cp).z)}>- <span className="office-rx-icon"><IconSvg icon={CHECKPOINT_ICON[cp.id]} /></span>- <span className="office-rx-place-text">- <strong>{name}</strong>- <span>{t(`society.office.cp_${cp.id}_hint`)}</span>- </span>- <span className="office-rx-go" aria-hidden>{t("society.office.guide.place_walk")}<Glyph name="chevron" /></span>- </button>- </li>- );- })}- </ul>- <p className="office-rx-tip"><kbd className="office-rx-cap">H</kbd>{t("society.office.guide.tip_guide")}</p>- </>+ <div><Button type="button" size="sm" variant="ghost" onClick={settings.reset}>{t("society.office.guide.set_reset")}</Button></div>+ </div>);}-export function ReceptionPanel({ floor, layout, onCreateAgent }: { floor: OfficeFloor; layout: OfficeLayout; onCreateAgent?: () => void }) {+export function ReceptionPanel({ floor, layout, agents, actions }: {+ floor: OfficeFloor; layout: OfficeLayout; agents: readonly SocietyAgent[]; actions: OfficeActions;+}) {const t = useT();const tab = useReceptionTab((s) => s.tab);const setTab = useReceptionTab((s) => s.setTab);- const baseId = useId();- const tabRefs = useRef<(HTMLButtonElement | null)[]>([]);- // Arrow keys move between tabs (WAI-ARIA tabs pattern); the map's walking keys listen on the window, not here.- const onTabKey = (event: ReactKeyboardEvent<HTMLDivElement>) => {- const step = event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : 0;- if (!step) return;- event.preventDefault();- event.stopPropagation();- const next = TABS[(TABS.indexOf(tab) + step + TABS.length) % TABS.length]!;- setTab(next);- tabRefs.current[TABS.indexOf(next)]?.focus();- };return (- <div className="office-reception">- <div className="office-rx-tabs" role="tablist" aria-label={t("society.office.guide.tablist")} onKeyDown={onTabKey}- style={{ "--rx-tab": TABS.indexOf(tab) } as CSSProperties}>- <i className="office-rx-tab-thumb" aria-hidden />- {TABS.map((id, i) => (- <button key={id} ref={(el) => { tabRefs.current[i] = el; }} type="button" role="tab" id={`${baseId}-${id}`}- aria-selected={tab === id} aria-controls={`${baseId}-${id}-panel`} tabIndex={tab === id ? 0 : -1}- className="office-rx-tab" onClick={() => setTab(id)}>- <Glyph name={id} />{t(`society.office.guide.tab_${id}`)}- </button>- ))}- </div>- {/* Keyed by tab so each switch replays the short entrance. */}- <div key={tab} role="tabpanel" id={`${baseId}-${tab}-panel`} aria-labelledby={`${baseId}-${tab}`} className="office-rx-body">- {tab === "welcome" && <WelcomeTab floor={floor} layout={layout} onCreateAgent={onCreateAgent} />}- {tab === "controls" && <ControlsTab floor={floor} />}- {tab === "settings" && <SettingsTab />}- </div>- </div>+ <Tabs value={tab} onValueChange={(value) => setTab(value as ReceptionTab)}>+ <TabsList aria-label={t("society.office.guide.tablist")}>+ {TABS.map((id) => <TabsTrigger key={id} value={id}>{t(`society.office.guide.tab_${id}`)}</TabsTrigger>)}+ </TabsList>+ <TabsContent value="agents"><AgentsTab agents={agents} actions={actions} /></TabsContent>+ <TabsContent value="places"><PlacesList layout={layout} /></TabsContent>+ <TabsContent value="controls"><ControlsTab floor={floor} /></TabsContent>+ <TabsContent value="settings"><SettingsTab /></TabsContent>+ </Tabs>);}diff --git a/jarvis/ui/web/frontend/src/components/society/office/SpawnPanel.tsx b/jarvis/ui/web/frontend/src/components/society/office/SpawnPanel.tsxindex 1d2d8f6381..b7f5f1001f 100644--- a/jarvis/ui/web/frontend/src/components/society/office/SpawnPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/SpawnPanel.tsx@@ -1,59 +1,13 @@/**- * The spawn point's panel. On the agents floor it spawns a new Jarvis agent- * through the app's create dialog; on the coding floor it starts new coding- * agents in the Agentic IDE with Mission Control's launcher. Whoever is new- * then appears on the spawn pad and walks to a free desk. Like every office- * panel it uses existing app paths only.+ * The coding floor's spawn terminal: Mission Control's launcher (CLI,+ * workspace, how many, an optional first task). Whoever it starts appears on+ * the spawn pad and walks to a free desk.+ *+ * The agents floor's terminal has no panel of its own: it opens the app's+ * create dialog (see OfficeStage).*/-import { useT } from "@/i18n";-import type { SocietyAgent } from "../data";-import { IconSvg } from "./CheckpointMarker";import { StartAgent } from "./MissionControlPanel";-import "./spawnPanel.css";-const STEPS = ["job", "brain", "arrive"] as const;--function Hero({ title, body }: { title: string; body: string }) {- return (- <div className="office-spawn-hero">- <span className="office-spawn-mark" aria-hidden><IconSvg icon="spawn" /></span>- <div>- <strong>{title}</strong>- <p>{body}</p>- </div>- </div>- );-}--/** Agents floor: what a new Jarvis agent needs, and the button that opens the create dialog. */-export function SpawnPanel({ agents, onCreateAgent }: { agents: readonly SocietyAgent[]; onCreateAgent?: () => void }) {- const t = useT();- const working = agents.filter((a) => a.state === "working").length;- return (- <div className="office-spawn">- <Hero title={t("society.office.spawn_title")} body={t("society.office.spawn_body")} />- <ol className="office-spawn-steps">- {STEPS.map((step, i) => (- <li key={step}><span aria-hidden>{i + 1}</span>{t(`society.office.spawn_step_${step}`)}</li>- ))}- </ol>- <button type="button" className="office-spawn-go" disabled={!onCreateAgent} onClick={() => onCreateAgent?.()}>- <IconSvg icon="plus" />{t("society.office.spawn_action")}- </button>- <p className="office-spawn-foot" role="status">- {t("society.office.spawn_team").replace("{0}", String(agents.length)).replace("{1}", String(working))}- </p>- </div>- );-}--/** Coding floor: Mission Control's launcher, right at the spawn point. */export function LaunchPanel() {- const t = useT();- return (- <div className="office-spawn">- <Hero title={t("society.office.launch_title")} body={t("society.office.launch_body")} />- <div className="office-mc"><StartAgent /></div>- </div>- );+ return <div className="office-mc"><StartAgent /></div>;}diff --git a/jarvis/ui/web/frontend/src/components/society/office/SpawnPoint.tsx b/jarvis/ui/web/frontend/src/components/society/office/SpawnPoint.tsxindex b89b6ab9ce..2cd2324139 100644--- a/jarvis/ui/web/frontend/src/components/society/office/SpawnPoint.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/SpawnPoint.tsx@@ -65,6 +65,12 @@ export const SPAWN_LOOKS: Record<OfficeFloor, SpawnLook> = {screenTop: "#1c1540", screenBottom: "#0b0918", text: "#f4f1ff", accent: "#ff5fa2", accentDeep: "#1a1236",pad: "#1a1430", speck: ["#2a1f4a", "#151027", "#7df9ff"], padEdge: "#9b8cff", padBand: "#ff5fa2",},+ // The Level Hall has no spawn point; the entry keeps the table complete in the hall's cream, charcoal and brass.+ hall: {+ body: "#e7e0d0", plinth: "#2b2d33", metal: "#b8964f", bezel: "#23262b", glow: "#ffe2bd",+ screenTop: "#2b2d33", screenBottom: "#16171b", text: "#f6efe1", accent: "#b8964f", accentDeep: "#1c1d21",+ pad: "#e7e0d0", speck: ["#ddd5c7", "#f3efe7", "#bdb3a0"], padEdge: "#b8964f", padBand: "#2b2d33",+ },};interface SpawnMaterials {@@ -575,7 +581,7 @@ function beamMaterialsFor(floor: OfficeFloor) {}/**- * The spawn point's life: two gyroscope rings turning round the floor token,+ * The spawn point's life: a beacon of two gyroscope rings turning above the terminal,* the glow breathing, and a column of light on the pad whenever someone new* arrives on the floor (a newcomer walks off the pad to its desk). Reduced* motion keeps the rings still and skips the beam.@@ -628,7 +634,7 @@ export function SpawnFittings({ terminal, arrival, floor, newcomers, animate }:return (<>- <group position={[terminal.x, SPAWN.tokenY, terminal.z]}>+ <group position={[terminal.x, SPAWN.beaconY, terminal.z]}><group ref={gyroA}><mesh geometry={gyroGeometry[0]} material={m.glow} /></group><group ref={gyroB}><mesh geometry={gyroGeometry[1]} material={m.glow} /></group></group>diff --git a/jarvis/ui/web/frontend/src/components/society/office/StaticBatch.test.tsx b/jarvis/ui/web/frontend/src/components/society/office/StaticBatch.test.tsxnew file mode 100644index 0000000000..09d895de1e--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/StaticBatch.test.tsx@@ -0,0 +1,176 @@+import { afterEach, describe, expect, it } from "vitest";+import { act, createRoot, extend, type ReconcilerRoot } from "@react-three/fiber";+import * as THREE from "three";+import { Box3, BoxGeometry, InstancedMesh, MeshBasicMaterial, MeshStandardMaterial, PlaneGeometry, type Mesh, type Object3D } from "three";+import { StaticBatch } from "./StaticBatch";++/** Just enough of a WebGLRenderer for R3F to mount a scene graph without a GPU. */+function fakeRenderer(canvas: HTMLCanvasElement) {+ const noop = () => undefined;+ return {+ domElement: canvas,+ render: noop, setSize: noop, setPixelRatio: noop, setAnimationLoop: noop, dispose: noop,+ getPixelRatio: () => 1,+ shadowMap: { enabled: false, type: 0, needsUpdate: false },+ xr: { enabled: false, isPresenting: false, addEventListener: noop, removeEventListener: noop, setAnimationLoop: noop },+ outputColorSpace: "srgb", toneMapping: 0, toneMappingExposure: 1,+ info: { render: {}, memory: {} },+ };+}++extend(THREE);++let root: ReconcilerRoot<HTMLCanvasElement> | null = null;++async function render(element: JSX.Element): Promise<Object3D> {+ if (!root) {+ const canvas = document.createElement("canvas");+ root = createRoot(canvas);+ root.configure({+ // Test double: R3F only needs the renderer's shape here, nothing is drawn.+ gl: fakeRenderer(canvas) as unknown as NonNullable<Parameters<typeof root.configure>[0]>["gl"],+ frameloop: "never",+ size: { width: 100, height: 100, top: 0, left: 0 },+ });+ }+ const current = root;+ // A local: an earlier test's root lets go of its own group late, and must not clear this one.+ let captured: Object3D | null = null;+ await act(async () => { current.render(<group ref={(g) => { if (g) captured = g; }}>{element}</group>); });+ if (!captured) throw new Error("the element did not mount");+ return captured;+}++afterEach(() => {+ root?.unmount();+ root = null;+});++const box = new BoxGeometry(1, 1, 1);+const small = new BoxGeometry(0.1, 0.1, 0.1);+const oak = new MeshStandardMaterial({ color: "#d9bf97", roughness: 0.6 });+const oakish = new MeshStandardMaterial({ color: "#b89b74", roughness: 0.55 });+const steel = new MeshStandardMaterial({ color: "#23262b", roughness: 0.45, metalness: 0.5 });+const glass = new MeshStandardMaterial({ color: "#d6ecff", transparent: true, opacity: 0.3 });+const glow = new MeshStandardMaterial({ color: "#fff0d8", emissive: "#fff0d8", emissiveIntensity: 1.5 });+const flatPaint = new MeshBasicMaterial({ color: "#ff0000" });++const drawn = (node: Object3D) => { const out: Mesh[] = []; node.traverseVisible((c) => { if ((c as Mesh).isMesh) out.push(c as Mesh); }); return out; };+const all = (node: Object3D) => { const out: Mesh[] = []; node.traverse((c) => { if ((c as Mesh).isMesh) out.push(c as Mesh); }); return out; };+const triangles = (meshes: Mesh[]) => meshes.reduce((sum, m) => sum + (m.geometry.index ? m.geometry.index.count : m.geometry.getAttribute("position").count) / 3, 0);++function Shelf({ x }: { x: number }) {+ return (+ <group position={[x, 0, 0]} name={`shelf:${x}`}>+ <mesh geometry={box} material={oak} position={[0, 0.5, 0]} castShadow receiveShadow />+ <mesh geometry={box} material={oakish} position={[0, 1.6, 0]} scale={[1, 0.1, 1]} castShadow receiveShadow />+ <mesh geometry={box} material={steel} position={[0.4, 1, 0]} scale={[0.05, 2, 0.05]} castShadow receiveShadow />+ <mesh geometry={small} material={oak} position={[0, 1.7, 0]} castShadow receiveShadow />+ <mesh geometry={box} material={glass} position={[0, 1, 0.5]} scale={[1, 1, 0.02]} />+ <mesh geometry={box} material={glow} position={[0, 2, 0]} scale={[1, 0.02, 0.05]} />+ </group>+ );+}++describe("static batch", () => {+ it("draws many parts as a few merged meshes with the same shape, and hides the parts", async () => {+ const group = await render(<StaticBatch signature="a"><Shelf x={0} /><Shelf x={3} /><Shelf x={6} /></StaticBatch>);+ group.updateMatrixWorld(true);+ const parts = all(group).filter((m) => !m.userData.staticBatched || !m.visible);+ const merged = drawn(group);+ expect(parts).toHaveLength(18);+ expect(parts.every((m) => !m.visible)).toBe(true);+ // Oak and its near twin share a finish; steel is more metallic; the tiny box no longer casts; glass and glow keep their materials.+ expect(merged).toHaveLength(5);+ expect(triangles(merged)).toBe(18 * 12);+ // Same extent as the parts had.+ const extent = new Box3().setFromObject(group);+ expect(extent.min.x).toBeCloseTo(-0.5, 6);+ expect(extent.max.x).toBeCloseTo(6.5, 6);+ expect(extent.min.y).toBeCloseTo(0, 6);+ expect(extent.max.y).toBeCloseTo(2.01, 6);+ // The glowing strip is still drawn with the very material object someone may pulse; so is the glass.+ expect(merged.some((m) => m.material === glow)).toBe(true);+ expect(merged.some((m) => m.material === glass)).toBe(true);+ // Plain parts share a white material and carry their own colour in the vertices.+ const plain = merged.filter((m) => (m.material as MeshStandardMaterial).vertexColors);+ expect(plain).toHaveLength(3);+ for (const mesh of plain) {+ expect((mesh.material as MeshStandardMaterial).color.getHexString()).toBe("ffffff");+ expect(mesh.geometry.getAttribute("color")).toBeDefined();+ }+ const wood = plain.find((m) => m.castShadow && (m.material as MeshStandardMaterial).metalness === 0)!;+ const colour = wood.geometry.getAttribute("color");+ expect(colour.getX(0)).toBeCloseTo(oak.color.r, 6);+ // The second part in that mesh is the darker oak.+ expect(colour.getX(36)).toBeCloseTo(oakish.color.r, 6);+ // Shadows: the big parts cast, the hand-sized one does not, receiving is kept.+ const tiny = plain.find((m) => !m.castShadow)!;+ expect(triangles([tiny])).toBe(3 * 12);+ expect(plain.every((m) => m.receiveShadow)).toBe(true);+ // A merged mesh never takes a click meant for a part.+ expect(merged.every((m) => m.userData.staticBatched)).toBe(true);+ });++ it("leaves alone what it cannot bake, and what someone hid", async () => {+ const instanced = new InstancedMesh(box, oak, 4);+ const group = await render(+ <StaticBatch signature="a">+ <mesh geometry={box} material={oak} />+ <mesh geometry={box} material={[oak, steel] as unknown as MeshStandardMaterial} name="multi" />+ <mesh geometry={box} material={flatPaint} name="basic" />+ <mesh geometry={box} material={oak} visible={false} name="hidden" />+ <group visible={false}><mesh geometry={box} material={oak} name="in-hidden-group" /></group>+ <primitive object={instanced} />+ </StaticBatch>,+ );+ const names = drawn(group).map((m) => m.name || (m.userData.staticBatched ? "merged" : (m as unknown as InstancedMesh).isInstancedMesh ? "instanced" : "part"));+ // The plain box is merged (alone), the basic-material one too (by its own material); the rest draw themselves or stay hidden.+ expect(names.sort()).toEqual(["instanced", "merged", "merged", "multi"]);+ expect(all(group).find((m) => m.name === "hidden")!.visible).toBe(false);+ });++ it("keeps flat sheets apart when asked, for pieces that get a silhouette rim", async () => {+ const sheet = new PlaneGeometry(1, 1);+ const group = await render(+ <StaticBatch signature="a" keepFlat>+ <mesh geometry={box} material={oak} />+ <mesh geometry={box} material={oak} position={[2, 0, 0]} />+ <mesh geometry={sheet} material={oak} name="sheet" />+ </StaticBatch>,+ );+ const meshes = drawn(group);+ expect(meshes).toHaveLength(2);+ expect(meshes.find((m) => m.name === "sheet")!.geometry).toBe(sheet);+ });++ it("keeps a jointed thing's shadow whole when asked: small parts still cast, and a finish is one mesh", async () => {+ const parts = (+ <>+ <mesh geometry={small} material={oak} castShadow />+ <mesh geometry={small} material={oakish} position={[0, 0.1, 0]} castShadow />+ <mesh geometry={small} material={oak} position={[0, 0.2, 0]} />+ </>+ );+ // By default a part a hand wide casts nothing, and what casts is kept apart from what does not.+ const plain = drawn(await render(<StaticBatch signature="a">{parts}</StaticBatch>));+ expect(plain.map((m) => m.castShadow)).toEqual([false]);+ root?.unmount();+ root = null;+ const whole = drawn(await render(<StaticBatch signature="a" castAsOne>{parts}</StaticBatch>));+ expect(whole).toHaveLength(1);+ expect(whole[0].castShadow).toBe(true);+ expect(triangles(whole)).toBe(3 * 12);+ });++ it("rebuilds when its content changes and gives the parts back when it goes", async () => {+ const first = await render(<StaticBatch signature="a"><Shelf x={0} /></StaticBatch>);+ expect(drawn(first)).toHaveLength(5);+ const second = await render(<StaticBatch signature="b"><Shelf x={0} /><Shelf x={3} /></StaticBatch>);+ const merged = drawn(second);+ expect(merged).toHaveLength(5);+ expect(triangles(merged)).toBe(12 * 12);+ // No merged mesh of the first bake is left behind.+ expect(all(second).filter((m) => m.userData.staticBatched && m.visible)).toHaveLength(5);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/StaticBatch.tsx b/jarvis/ui/web/frontend/src/components/society/office/StaticBatch.tsxnew file mode 100644index 0000000000..5c47471ee8--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/StaticBatch.tsx@@ -0,0 +1,204 @@+/**+ * Draws a set of static props as a few merged meshes instead of one per+ * part. A furnished room is hundreds of small meshes (every drawer, book and+ * cushion); each is a draw call, and a second one in the shadow pass. Merged,+ * a whole floor's furniture is a few dozen.+ *+ * The props are mounted as usual, so their components stay the single source+ * of their shape. Once they are in the scene, every plain mesh is baked into+ * a merged geometry and hidden; the merged meshes are drawn in its place.+ * Parts whose material is nothing but a colour (no texture, not transparent)+ * share one material per finish and carry their colour in the vertices, so a+ * shelf of twenty differently coloured books is still one mesh. Textured and+ * transparent parts merge per material.+ *+ * Hidden meshes still take pointer events and keep their place in the scene+ * graph, so clicks and lookups by name work as before. A part that glows+ * keeps its own material object, so whoever pulses that material still does.+ * Parts smaller than a hand's width (a cup, a book, a handle) stop casting a+ * shadow of their own: at the floor's scale it never shows, and it halves+ * what the shadow pass draws.+ *+ * Only for props that never change after they mount: no animated parts, no+ * material swapped on state. Instanced, skinned and multi-material meshes and+ * anything already hidden are left alone and keep drawing themselves.+ * `signature` names the content: the batch is rebuilt when it changes.+ */+import { useLayoutEffect, useRef, type ReactNode } from "react";+import {+ Box3, BufferAttribute, BufferGeometry, Group, Matrix4, Mesh, Vector3,+ type InstancedMesh, type Material, type MeshStandardMaterial, type Object3D, type SkinnedMesh,+} from "three";+import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js";++const BAKED_FLAG = "staticBatched";+/** A part whose largest side is shorter than this casts no shadow of its own. */+const SHADOW_MIN_M = 0.22;+/** Sheets with no thickness; a batch that keeps them apart leaves them as their own meshes. */+const FLAT_GEOMETRY = new Set(["PlaneGeometry", "CircleGeometry", "RingGeometry", "ShapeGeometry"]);++export interface BakeOptions {+ /** Leave flat sheets (planes, discs, rings) as their own meshes: for props whose merged meshes get a silhouette rim. */+ keepFlat?: boolean;+ /**+ * Shadows as one: no part is dropped from the shadow for being small, and the parts of a finish share one merged+ * mesh, which casts if any of them did. For a jointed thing made of small parts (a figure's arm), where the+ * shadow of the whole must stay as it was.+ */+ castAsOne?: boolean;+}++/** A mesh that can be baked: one material, plain geometry with positions, visible all the way up to the batch. */+function bakeable(object: Object3D, root: Object3D, options: BakeOptions): object is Mesh<BufferGeometry, Material> {+ const mesh = object as Mesh;+ if (!mesh.isMesh || (mesh as unknown as InstancedMesh).isInstancedMesh || (mesh as unknown as SkinnedMesh).isSkinnedMesh) return false;+ if (Array.isArray(mesh.material) || !mesh.geometry?.getAttribute("position")) return false;+ if (options.keepFlat && FLAT_GEOMETRY.has(mesh.geometry.type)) return false;+ if ((mesh.material as Material & { vertexColors?: boolean }).vertexColors) return false;+ for (let node: Object3D | null = mesh; node && node !== root; node = node.parent) {+ // A part someone hid stays hidden; a part this batch hid earlier is baked again.+ if (!node.visible && !node.userData[BAKED_FLAG]) return false;+ }+ return true;+}++/**+ * The finish of a material that is only a colour: everything the shared material must match. Null for a material+ * with any texture, transparency or special rendering, which keeps a mesh of its own kind.+ */+function plainFinish(material: Material): string | null {+ const m = material as MeshStandardMaterial;+ if (!m.isMeshStandardMaterial || m.type !== "MeshStandardMaterial") return null;+ if (m.map || m.emissiveMap || m.normalMap || m.roughnessMap || m.metalnessMap || m.alphaMap || m.aoMap || m.bumpMap || m.envMap) return null;+ if (m.transparent || m.opacity < 1 || m.alphaTest > 0 || m.wireframe || !m.depthWrite || !m.depthTest || !m.visible) return null;+ // A part that glows keeps its own material: lights are pulsed through the material object.+ if (m.emissive.getHex() !== 0 && m.emissiveIntensity !== 0) return null;+ return [step(m.roughness, ROUGHNESS_STEP), step(m.metalness, METALNESS_STEP), m.flatShading ? 1 : 0, m.side, m.toneMapped ? 1 : 0, m.fog ? 1 : 0].join(":");+}++/**+ * Finishes are told apart in steps: furniture is authored with a dozen roughness values between "matt" and+ * "satin" that nobody can tell apart on a prop a hand wide, and each would be a draw call of its own.+ */+const ROUGHNESS_STEP = 0.25;+const METALNESS_STEP = 0.25;+const step = (value: number, size: number) => Math.round(value / size) * size;++/** One white, vertex-coloured material per finish, shared by every batch. */+const finishMaterials = new Map<string, MeshStandardMaterial>();+function finishMaterial(finish: string, like: MeshStandardMaterial): MeshStandardMaterial {+ let material = finishMaterials.get(finish);+ if (!material) {+ material = like.clone();+ material.color.set("#ffffff");+ material.vertexColors = true;+ material.roughness = step(like.roughness, ROUGHNESS_STEP);+ material.metalness = step(like.metalness, METALNESS_STEP);+ finishMaterials.set(finish, material);+ }+ return material;+}++/**+ * A copy of a mesh's geometry in the batch's own frame, reduced to position, normal and uv — and, for a plain+ * part, its material's colour in every vertex.+ */+function baked(mesh: Mesh<BufferGeometry, Material>, toBatch: Matrix4, tinted: boolean): BufferGeometry {+ const source = mesh.geometry;+ const flat = source.index ? source.toNonIndexed() : source.clone();+ for (const name of Object.keys(flat.attributes)) if (name !== "position" && name !== "normal" && name !== "uv") flat.deleteAttribute(name);+ if (!flat.getAttribute("normal")) flat.computeVertexNormals();+ const count = flat.getAttribute("position").count;+ if (!flat.getAttribute("uv")) flat.setAttribute("uv", new BufferAttribute(new Float32Array(count * 2), 2));+ if (tinted) {+ const { r, g, b } = (mesh.material as MeshStandardMaterial).color;+ const colours = new Float32Array(count * 3);+ for (let i = 0; i < count; i += 1) { colours[i * 3] = r; colours[i * 3 + 1] = g; colours[i * 3 + 2] = b; }+ flat.setAttribute("color", new BufferAttribute(colours, 3));+ }+ flat.morphAttributes = {};+ flat.clearGroups();+ return flat.applyMatrix4(new Matrix4().multiplyMatrices(toBatch, mesh.matrixWorld));+}++/**+ * Bake every bakeable mesh under `source` into merged meshes under `target` and hide the originals: one merged+ * mesh per finish for plain coloured parts, one per material for the rest, each split by its shadow flags.+ * Returns the merged meshes; the caller disposes their geometries.+ */+export function bakeStatic(source: Object3D, target: Object3D, options: BakeOptions = {}): Mesh[] {+ source.updateMatrixWorld(true);+ target.updateMatrixWorld(true);+ const toBatch = new Matrix4().copy(target.matrixWorld).invert();+ const buckets = new Map<string, { material: Material; cast: boolean; receive: boolean; order: number; pieces: BufferGeometry[]; meshes: Mesh[] }>();+ const box = new Box3(), extent = new Vector3();+ source.traverse((object) => {+ if (!bakeable(object, source, options)) return;+ const finish = plainFinish(object.material);+ const piece = baked(object, toBatch, finish !== null);+ piece.computeBoundingBox();+ box.copy(piece.boundingBox as Box3).getSize(extent);+ const cast = object.castShadow && (options.castAsOne || Math.max(extent.x, extent.y, extent.z) >= SHADOW_MIN_M);+ const key = `${finish === null ? object.material.uuid : `plain:${finish}`}:${options.castAsOne ? "" : cast ? 1 : 0}${object.receiveShadow ? 1 : 0}:${object.renderOrder}`;+ let bucket = buckets.get(key);+ if (!bucket) {+ bucket = {+ material: finish === null ? object.material : finishMaterial(finish, object.material as MeshStandardMaterial),+ cast, receive: object.receiveShadow, order: object.renderOrder, pieces: [], meshes: [],+ };+ buckets.set(key, bucket);+ }+ bucket.cast ||= cast;+ bucket.pieces.push(piece);+ bucket.meshes.push(object);+ });+ const out: Mesh[] = [];+ for (const bucket of buckets.values()) {+ const geometry = bucket.pieces.length === 1 ? bucket.pieces[0] : mergeGeometries(bucket.pieces, false);+ if (bucket.pieces.length > 1) for (const piece of bucket.pieces) piece.dispose();+ // A set that will not merge keeps drawing itself.+ if (!geometry) continue;+ const mesh = new Mesh(geometry, bucket.material);+ mesh.castShadow = bucket.cast;+ mesh.receiveShadow = bucket.receive;+ mesh.renderOrder = bucket.order;+ mesh.userData[BAKED_FLAG] = true;+ // The merged mesh is only drawn; pointer events stay with the parts it stands for.+ mesh.raycast = () => undefined;+ target.add(mesh);+ out.push(mesh);+ for (const original of bucket.meshes) {+ original.visible = false;+ original.userData[BAKED_FLAG] = true;+ }+ }+ return out;+}++export function StaticBatch({ signature, keepFlat = false, castAsOne = false, children }: {+ signature: string; keepFlat?: boolean; castAsOne?: boolean; children: ReactNode;+}) {+ const source = useRef<Group>(null);+ const target = useRef<Group>(null);+ useLayoutEffect(() => {+ const from = source.current, to = target.current;+ if (!from || !to) return;+ const meshes = bakeStatic(from, to, { keepFlat, castAsOne });+ return () => {+ for (const mesh of meshes) {+ to.remove(mesh);+ mesh.geometry.dispose();+ }+ // Whatever is still mounted draws itself again until the next bake.+ from.traverse((object) => {+ if (object.userData[BAKED_FLAG]) { object.visible = true; delete object.userData[BAKED_FLAG]; }+ });+ };+ }, [signature, keepFlat, castAsOne]);+ return (+ <>+ <group ref={source}>{children}</group>+ <group ref={target} />+ </>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/StationObjects.tsx b/jarvis/ui/web/frontend/src/components/society/office/StationObjects.tsxnew file mode 100644index 0000000000..e397e9b11d--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/StationObjects.tsx@@ -0,0 +1,119 @@+/**+ * The stations in the world. Nothing floats over the floor: the object in the+ * room is the station. Each one gets an invisible click target the size of+ * its object (so it stays usable from the overview, walking is optional) and+ * a thin rim on the object itself while the person stands at it, points at+ * it or has it open. The one prompt that names it lives in the HUD.+ */+import { useEffect, useMemo, useRef } from "react";+import { useFrame, useThree, type ThreeEvent } from "@react-three/fiber";+import type { Mesh, Object3D } from "three";+import type { OfficeLayout } from "./officeLayout";+import { sameSelection, useOfficeStore, type Selection } from "./officeStore";+import { stationsFor, type Station } from "./stations";+import { attachRim, attachedTo, createRimMaterial, detachRim, rimTargets } from "./stationRim";++/** The rim at full strength, and how fast it fades in and out (per second, exponential). */+const RIM_OPACITY = 0.92;+const RIM_FADE = 12;+/** While lit, look this often (frames) whether the object was rebuilt under the rim. */+const RIM_CHECK_FRAMES = 30;++function StationRim({ objects, lit, animate }: { objects: readonly string[]; lit: boolean; animate: boolean }) {+ const scene = useThree((s) => s.scene);+ const invalidate = useThree((s) => s.invalidate);+ const material = useMemo(createRimMaterial, []);+ const worn = useRef<{ roots: Object3D[]; shells: Mesh[] }>({ roots: [], shells: [] });+ const frames = useRef(0);+ const names = objects.join("|");++ const takeOff = () => {+ detachRim(worn.current.shells);+ worn.current = { roots: [], shells: [] };+ };+ useEffect(() => () => { takeOff(); material.dispose(); }, [material]);+ // Another object under the same station (a rebuilt floor plan): start clean.+ useEffect(() => takeOff, [names]);+ // A paused or on-demand canvas still has to draw the change.+ useEffect(() => { invalidate(); }, [lit, invalidate]);++ useFrame((_, delta) => {+ const uniform = material.uniforms.rimOpacity;+ const goal = lit ? RIM_OPACITY : 0;+ if (uniform.value !== goal) {+ uniform.value = animate ? uniform.value + (goal - uniform.value) * (1 - Math.exp(-RIM_FADE * Math.min(delta, 0.1))) : goal;+ if (Math.abs(uniform.value - goal) < 0.01) uniform.value = goal;+ invalidate();+ }+ const state = worn.current;+ if (!lit) {+ if (uniform.value === 0 && state.shells.length > 0) takeOff();+ frames.current = 0;+ return;+ }+ // Dress the object on the first lit frame, then look now and then whether it was rebuilt under the rim.+ const first = frames.current === 0;+ frames.current += 1;+ if (!first && frames.current % RIM_CHECK_FRAMES !== 0) return;+ const intact = state.roots.length > 0 && state.roots.every((root) => attachedTo(root, scene))+ && state.roots.reduce((sum, root) => sum + rimTargets(root).length, 0) === state.shells.length;+ if (intact) return;+ takeOff();+ const roots = objects.map((name) => scene.getObjectByName(name)).filter((root): root is Object3D => !!root);+ worn.current = { roots, shells: roots.flatMap((root) => attachRim(root, material)) };+ });+ return null;+}++function StationObject({ station, lit, animate }: { station: Station; lit: boolean; animate: boolean }) {+ const hovered = useRef(false);+ const leave = () => {+ if (!hovered.current) return;+ hovered.current = false;+ document.body.style.cursor = "";+ const store = useOfficeStore.getState();+ if (sameSelection(store.hover, station.selection)) store.setHover(null);+ };+ // Never leave a pointer cursor or a stale hover behind when the station goes away under the mouse.+ useEffect(() => leave, []); // eslint-disable-line react-hooks/exhaustive-deps++ const onClick = (event: ThreeEvent<MouseEvent>) => {+ // A drag that ends on the object turned the camera; only a real click uses it.+ if (event.delta > 6) return;+ event.stopPropagation();+ useOfficeStore.getState().select(station.selection);+ };+ const onPointerOver = (event: ThreeEvent<PointerEvent>) => {+ event.stopPropagation();+ hovered.current = true;+ document.body.style.cursor = "pointer";+ useOfficeStore.getState().setHover(station.selection);+ };++ return (+ <group name={`station:${station.key}`}>+ {station.hits.map((box, i) => (+ <mesh key={i} position={[box.x, box.y, box.z]} rotation={[0, box.rotationY, 0]} visible={false}+ onClick={onClick} onPointerOver={onPointerOver} onPointerOut={leave}>+ <boxGeometry args={[box.w, box.h, box.d]} />+ </mesh>+ ))}+ {station.objects.length > 0 && <StationRim objects={station.objects} lit={lit} animate={animate} />}+ </group>+ );+}++export function StationObjects({ layout, nearby, selection, animate }: {+ layout: OfficeLayout; nearby: Selection | null; selection: Selection | null; animate: boolean;+}) {+ const stations = useMemo(() => stationsFor(layout), [layout]);+ const hover = useOfficeStore((s) => s.hover);+ return (+ <>+ {stations.map((station) => (+ <StationObject key={station.key} station={station} animate={animate}+ lit={sameSelection(nearby, station.selection) || sameSelection(hover, station.selection) || sameSelection(selection, station.selection)} />+ ))}+ </>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/StationSheet.test.tsx b/jarvis/ui/web/frontend/src/components/society/office/StationSheet.test.tsxnew file mode 100644index 0000000000..e099aa6c2a--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/StationSheet.test.tsx@@ -0,0 +1,72 @@+import { useState } from "react";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeAll, describe, expect, test, vi } from "vitest";+import { loadLocaleChunk } from "@/i18n";+import { ownsKeyboard } from "./OfficePlayer";+import { StationSheet, StationSidePanel } from "./StationSheet";++beforeAll(async () => { await loadLocaleChunk("society"); });+afterEach(cleanup);++/** A map host with a button that opens a station's dialog, the way the stage mounts one. */+function Stage({ onReturn }: { onReturn?: () => void }) {+ const [open, setOpen] = useState(false);+ return (+ <div>+ <div data-testid="host" tabIndex={0} />+ <button type="button" onClick={() => setOpen(true)}>Open teams</button>+ {open && (+ <StationSheet title="Team room" description="Your teams and their meetings" onClose={() => setOpen(false)}+ returnFocus={() => { onReturn?.(); screen.getByTestId("host").focus(); }}>+ <input aria-label="Team name" />+ </StationSheet>+ )}+ </div>+ );+}++describe("station dialog", () => {+ test("is a labelled modal dialog that owns the keyboard while it is open", () => {+ render(<Stage />);+ fireEvent.click(screen.getByRole("button", { name: "Open teams" }));+ const dialog = screen.getByRole("dialog", { name: "Team room" });+ expect(dialog.getAttribute("data-state")).toBe("open");+ expect(screen.getByText("Your teams and their meetings")).toBeTruthy();+ // The walking keys stand down while a dialog is open, wherever focus sits.+ expect(ownsKeyboard(document.body)).toBe(true);+ });++ test("Escape closes it and hands focus to the map, so the walking keys answer at once", async () => {+ const onReturn = vi.fn();+ render(<Stage onReturn={onReturn} />);+ fireEvent.click(screen.getByRole("button", { name: "Open teams" }));+ const dialog = screen.getByRole("dialog");+ fireEvent.keyDown(dialog, { key: "Escape" });+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ await waitFor(() => expect(onReturn).toHaveBeenCalledOnce());+ const host = screen.getByTestId("host");+ expect(document.activeElement).toBe(host);+ expect(ownsKeyboard(host)).toBe(false);+ });++ test("the close button does the same", async () => {+ const onReturn = vi.fn();+ render(<Stage onReturn={onReturn} />);+ fireEvent.click(screen.getByRole("button", { name: "Open teams" }));+ fireEvent.click(screen.getByRole("button", { name: "Close" }));+ await waitFor(() => expect(onReturn).toHaveBeenCalledOnce());+ expect(document.activeElement).toBe(screen.getByTestId("host"));+ });+});++describe("station side panel", () => {+ test("is a labelled panel that takes focus without taking the walking keys", () => {+ const onClose = vi.fn();+ render(<StationSidePanel title="Wardrobe" description="Dress yourself or an agent" onClose={onClose}><p>Outfits</p></StationSidePanel>);+ const panel = screen.getByRole("complementary", { name: "Wardrobe" });+ expect(document.activeElement).toBe(panel);+ expect(ownsKeyboard(panel)).toBe(false);+ fireEvent.click(screen.getByRole("button", { name: "Close" }));+ expect(onClose).toHaveBeenCalledOnce();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/StationSheet.tsx b/jarvis/ui/web/frontend/src/components/society/office/StationSheet.tsxnew file mode 100644index 0000000000..0103fdd599--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/StationSheet.tsx@@ -0,0 +1,78 @@+/**+ * What opens from a station. A station that manages something (teams, the+ * directory, a launcher) opens a dialog built like every other dialog of the+ * app: the same scrim, surface, header and type scale. A station whose effect+ * shows in the world (the wardrobe) opens a panel docked at the side instead,+ * so the person keeps seeing — and walking — their character.+ */+import { useEffect, useId, useRef, type ReactNode } from "react";+import * as Dialog from "@radix-ui/react-dialog";+import { X } from "lucide-react";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";++const closeButton = "inline-flex size-8 shrink-0 items-center justify-center rounded-md border border-border bg-background text-foreground hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";++const WIDTH = {+ md: "w-[min(32rem,calc(100vw-2rem))]",+ lg: "w-[min(42rem,calc(100vw-2rem))]",+} as const;++export function StationSheet({ title, description, size = "lg", onClose, returnFocus, children }: {+ title: string; description?: string; size?: keyof typeof WIDTH; onClose: () => void;+ /**+ * Where focus goes when the dialog has closed (the map's canvas host, so the walking keys answer at once).+ * Without it focus returns to whatever had it before the dialog opened.+ */+ returnFocus?: () => void;+ children: ReactNode;+}) {+ const t = useT();+ return (+ <Dialog.Root open onOpenChange={(open) => { if (!open) onClose(); }}>+ <Dialog.Portal>+ <Dialog.Overlay className="fixed inset-0 z-[150] bg-scrim/60 backdrop-blur-sm" />+ <Dialog.Content data-office-ui {...(description ? {} : { "aria-describedby": undefined })}+ onCloseAutoFocus={(event) => {+ if (!returnFocus) return;+ event.preventDefault();+ returnFocus();+ }}+ className={cn("fixed left-1/2 top-1/2 z-[151] flex max-h-[90dvh] -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden rounded-xl border border-border bg-background text-foreground shadow-xl", WIDTH[size])}>+ <div className="flex items-start justify-between gap-4 border-b border-border p-5">+ <div className="grid min-w-0 gap-1.5">+ <Dialog.Title className="font-display text-lg font-semibold">{title}</Dialog.Title>+ {description && <Dialog.Description className="text-sm text-muted-foreground">{description}</Dialog.Description>}+ </div>+ <Dialog.Close className={closeButton} aria-label={t("society.office.close")}><X size={16} aria-hidden /></Dialog.Close>+ </div>+ <div className="grid gap-5 overflow-y-auto p-5">{children}</div>+ </Dialog.Content>+ </Dialog.Portal>+ </Dialog.Root>+ );+}++/** The docked variant: a panel in the stage's side slot. Not modal; Escape (handled by the stage) closes it. */+export function StationSidePanel({ title, description, onClose, children }: {+ title: string; description?: string; onClose: () => void; children: ReactNode;+}) {+ const t = useT();+ const headingId = useId();+ const panel = useRef<HTMLElement>(null);+ // Focus moves into the fresh panel so keyboard and screen-reader users land on it;+ // the walking keys keep working because they listen on the window.+ useEffect(() => { panel.current?.focus({ preventScroll: true }); }, []);+ return (+ <aside ref={panel} className="office-card office-panel" data-office-ui aria-labelledby={headingId} tabIndex={-1}>+ <header className="flex items-start justify-between gap-3 border-b border-border px-4 py-3">+ <div className="grid min-w-0 gap-0.5">+ <h2 id={headingId} className="font-display text-base font-semibold">{title}</h2>+ {description && <p className="text-xs text-muted-foreground">{description}</p>}+ </div>+ <button type="button" className={closeButton} onClick={onClose} aria-label={t("society.office.close")}><X size={16} aria-hidden /></button>+ </header>+ <div className="office-panel-body">{children}</div>+ </aside>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/StudioBoard.tsx b/jarvis/ui/web/frontend/src/components/society/office/StudioBoard.tsxnew file mode 100644index 0000000000..c712c5de64--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/StudioBoard.tsx@@ -0,0 +1,101 @@+/**+ * The studio board: every team studio's own wall screen, standing in front of+ * its name wall. A slim graphite panel on two steel legs with an oak ledge+ * and a warm light bar on top. Its face is a calm paper-white sheet with a+ * dot grid; whatever the team is doing is drawn over it by the layer that+ * owns the live content, placed with `studioBoardFace` from the layout.+ *+ * Everything stays inside the `studioBoard` footprint, which navigation walks+ * round. All boards share their materials.+ *+ * The team stand belongs to the same family: the lectern on the free plot+ * where a new team is started. A steel post on a foot carries a slanted oak+ * panel with a pale sheet, a plus drawn on it and the board's light bar along+ * its upper edge. It carries no text; the layer that owns the interaction+ * labels it.+ */+import { MeshStandardMaterial } from "three";+import { cachedCanvasTexture } from "./canvasMaterials";+import { Box, matte } from "./OfficeFurniture";+import { FURNITURE_SIZE, STUDIO_BOARD_FACE } from "./officeLayout";++const SIZE = FURNITURE_SIZE.studioBoard;+/** The panel behind the face: a bezel round it, and thin enough to leave the face proud of nothing but itself. */+const PANEL = { w: SIZE.w, h: STUDIO_BOARD_FACE.h + 0.18, d: 0.1 } as const;+/** The resting face is the board's face plane; live content is drawn a few millimetres in front of it. */+const REST_FACE_Z = STUDIO_BOARD_FACE.z;++const BOARD_MAT = {+ panel: matte("#2a2d33", { roughness: 0.55 }),+ leg: matte("#1f2226", { roughness: 0.4, metalness: 0.5 }),+ ledge: matte("#d9bf97", { roughness: 0.6 }),+ light: new MeshStandardMaterial({ color: "#fff0d8", emissive: "#fff0d8", emissiveIntensity: 1.3, toneMapped: false }),+};++let restFace: MeshStandardMaterial | null = null;+/** Paper-white with a fine dot grid, lit a little from within so it reads as a screen at rest. */+function restFaceMaterial(): MeshStandardMaterial {+ if (!restFace) {+ const map = cachedCanvasTexture("studio-board:rest", 432, 232, (ctx, w, h) => {+ ctx.fillStyle = "#f6f3ec";+ ctx.fillRect(0, 0, w, h);+ ctx.fillStyle = "rgba(60,56,50,0.16)";+ for (let y = 12; y < h; y += 20) for (let x = 12; x < w; x += 20) ctx.fillRect(x, y, 2, 2);+ });+ restFace = new MeshStandardMaterial({+ color: map ? "#ffffff" : "#f6f3ec", map, roughness: 0.9,+ ...(map ? { emissive: "#ffffff", emissiveMap: map, emissiveIntensity: 0.18 } : {}),+ });+ }+ return restFace;+}++/** One studio board, in its own frame: origin on the floor under its centre, face towards +z. */+function StudioBoard() {+ const panelY = STUDIO_BOARD_FACE.y;+ const panelBottom = panelY - PANEL.h / 2;+ return (+ <group>+ {[-SIZE.w / 2 + 0.22, SIZE.w / 2 - 0.22].map((x) => (+ <Box key={x} size={[0.05, panelBottom, 0.05]} position={[x, panelBottom / 2, -0.02]} material={BOARD_MAT.leg} />+ ))}+ <Box size={[PANEL.w, PANEL.h, PANEL.d]} position={[0, panelY, 0]} material={BOARD_MAT.panel} />+ <mesh position={[0, panelY, REST_FACE_Z]} material={restFaceMaterial()}>+ <planeGeometry args={[STUDIO_BOARD_FACE.w, STUDIO_BOARD_FACE.h]} />+ </mesh>+ {/* The ledge for pens, and the light bar washing the face from above. */}+ <Box size={[1.5, 0.03, 0.075]} position={[0, panelBottom - 0.015, 0.035]} material={BOARD_MAT.ledge} cast={false} />+ <Box size={[PANEL.w - 0.16, 0.025, 0.05]} position={[0, panelY + PANEL.h / 2 + 0.0125, 0.045]} material={BOARD_MAT.light} cast={false} />+ </group>+ );+}++/** The slanted panel of the team stand: its size, its slope from the horizontal and its middle's height. */+const STAND = { w: 0.74, d: 0.42, t: 0.03, slope: 0.6, y: 1.04 } as const;+const STAND_MAT = {+ sheet: matte("#f6f3ec", { roughness: 0.9 }),+ ink: matte("#2b2926", { roughness: 0.8 }),+};++/** The team stand, in its own frame: origin on the floor under its middle, its face towards +z and up. */+function TeamStand() {+ return (+ <group>+ <Box size={[0.46, 0.03, 0.4]} position={[0, 0.015, 0]} material={BOARD_MAT.leg} cast={false} />+ <Box size={[0.06, STAND.y - 0.03, 0.06]} position={[0, (STAND.y + 0.03) / 2, -0.03]} material={BOARD_MAT.leg} />+ <group position={[0, STAND.y, 0]} rotation={[STAND.slope, 0, 0]}>+ <Box size={[STAND.w, STAND.t, STAND.d]} position={[0, 0, 0]} material={BOARD_MAT.ledge} />+ <Box size={[STAND.w - 0.1, 0.006, STAND.d - 0.1]} position={[0, STAND.t / 2 + 0.003, 0.01]} material={STAND_MAT.sheet} cast={false} />+ {/* The plus: start something here. */}+ <Box size={[0.2, 0.006, 0.045]} position={[0, STAND.t / 2 + 0.008, 0.01]} material={STAND_MAT.ink} cast={false} />+ <Box size={[0.045, 0.006, 0.2]} position={[0, STAND.t / 2 + 0.008, 0.01]} material={STAND_MAT.ink} cast={false} />+ <Box size={[STAND.w - 0.06, 0.018, 0.022]} position={[0, STAND.t / 2 + 0.009, -STAND.d / 2 + 0.02]} material={BOARD_MAT.light} cast={false} />+ </group>+ </group>+ );+}++export const STUDIO_RENDERERS = {+ studioBoard: () => <StudioBoard />,+ teamStand: () => <TeamStand />,+};diff --git a/jarvis/ui/web/frontend/src/components/society/office/StudioBoards.tsx b/jarvis/ui/web/frontend/src/components/society/office/StudioBoards.tsxnew file mode 100644index 0000000000..89f716ac4f--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/StudioBoards.tsx@@ -0,0 +1,119 @@+/**+ * The live face of every studio board: team name, members with their real+ * run state, the newest lines of the team's chat (studioBoardContent.ts).+ *+ * A face is a canvas texture, created the first time the camera comes close+ * and redrawn only when what it shows changed. Only the few boards nearest+ * the camera count as live: they are the ones whose transcript is refreshed+ * (useTeamRounds reads `boardWatch`). The faces take no pointer events; the+ * board's station does.+ */+import { useEffect, useMemo, useRef, useState } from "react";+import { useFrame } from "@react-three/fiber";+import { CanvasTexture, SRGBColorSpace } from "three";+import { useT } from "@/i18n";+import type { SocietyAgent } from "../data";+import { studioBoardFace, type OfficeLayout, type Studio } from "./officeLayout";+import { studiosOf } from "./officeTeams";+import { BOARD_CANVAS, BOARD_LIFT_M, boardModel, boardSignature, drawStudioBoard, pickBoards, type BoardLabels } from "./studioBoardContent";+import { boardWatch, useTeamwork } from "./teamwork";++const CHECK_EVERY_S = 0.4;++function useBoardLabels(): BoardLabels {+ const t = useT();+ return useMemo(() => ({+ pool: t("society.office.studio_pool"),+ members: t("society.office.team_members"),+ live: t("society.office.team_live"),+ speaking: t("society.office.board_speaking"),+ you: t("society.office.you"),+ empty: t("society.office.board_empty"),+ poolNote: t("society.office.board_pool_note"),+ loading: t("society.office.board_loading"),+ unavailable: t("society.office.board_unavailable"),+ lead: t("society.office.team_lead"),+ more: t("society.office.board_more"),+ state: {+ working: t("society.office.state_working"), waiting: t("society.office.state_waiting"),+ idle: t("society.office.state_idle"), paused: t("society.office.state_paused"),+ },+ }), [t]);+}++function BoardFace({ studio, agents, labels, active }: {+ studio: Studio; agents: ReadonlyMap<string, SocietyAgent>; labels: BoardLabels; active: boolean;+}) {+ const board = studio.board;+ const round = useTeamwork((s) => (studio.teamId ? s.rounds[studio.teamId] : undefined));+ // The canvas exists from the first time the camera came close; a board never seen costs nothing.+ const [seen, setSeen] = useState(active);+ useEffect(() => { if (active) setSeen(true); }, [active]);+ const surface = useMemo(() => {+ if (!seen || typeof document === "undefined") return null;+ const canvas = document.createElement("canvas");+ const ctx = canvas.getContext("2d");+ if (!ctx) return null;+ canvas.width = BOARD_CANVAS.w; canvas.height = BOARD_CANVAS.h;+ const texture = new CanvasTexture(canvas);+ texture.colorSpace = SRGBColorSpace;+ texture.anisotropy = 4;+ return { ctx, texture };+ }, [seen]);+ useEffect(() => () => surface?.texture.dispose(), [surface]);+ const model = useMemo(() => boardModel(studio, agents, round, labels), [studio, agents, round, labels]);+ const signature = boardSignature(model, labels);+ const drawnSignature = useRef("");+ useEffect(() => {+ // A board out of sight keeps its last face; it catches up when the camera returns.+ if (!surface || !active || drawnSignature.current === signature) return;+ drawnSignature.current = signature;+ drawStudioBoard(surface.ctx, model, labels);+ surface.texture.needsUpdate = true;+ // `signature` covers the model and the labels.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [surface, active, signature]);+ if (!board || !surface) return null;+ // The same sheet the board shows at rest, a hair in front of it and lit the same way, so the writing simply appears on it.+ const face = studioBoardFace(board);+ const nx = Math.sin(face.rotationY), nz = Math.cos(face.rotationY);+ return (+ <mesh position={[face.position[0] + nx * BOARD_LIFT_M, face.position[1], face.position[2] + nz * BOARD_LIFT_M]}+ rotation={[0, face.rotationY, 0]} raycast={() => null} userData={{ studioBoard: board.id }}>+ <planeGeometry args={face.size} />+ <meshStandardMaterial map={surface.texture} roughness={0.9} emissive="#ffffff" emissiveMap={surface.texture} emissiveIntensity={0.18} />+ </mesh>+ );+}++export function StudioBoards({ layout, agents, awake }: { layout: OfficeLayout; agents: ReadonlyMap<string, SocietyAgent>; awake: boolean }) {+ const labels = useBoardLabels();+ // This floor's own entry among the watched boards; another floor awake at the same time has its own.+ const stage = useMemo(() => Symbol("studio-boards"), []);+ const studios = useMemo(() => studiosOf(layout).filter((s) => s.board !== null), [layout]);+ const [drawn, setDrawn] = useState<ReadonlySet<string>>(new Set());+ const nextCheck = useRef(0);+ useFrame(({ camera, clock }) => {+ if (clock.elapsedTime < nextCheck.current) return;+ nextCheck.current = clock.elapsedTime + CHECK_EVERY_S;+ const picked = pickBoards(studios.map((s) => ({+ id: s.board!.id, teamId: s.teamId,+ distance: Math.hypot(camera.position.x - s.board!.x, camera.position.y - 1.2, camera.position.z - s.board!.z),+ })));+ boardWatch.set(stage, picked.live);+ if (picked.drawn.size !== drawn.size || [...picked.drawn].some((id) => !drawn.has(id))) setDrawn(picked.drawn);+ });+ // Asleep or gone, this floor watches no board; what another floor watches is its own business.+ useEffect(() => {+ if (!awake) boardWatch.clear(stage);+ return () => boardWatch.clear(stage);+ }, [awake, stage]);+ if (studios.length === 0) return null;+ return (+ <group>+ {studios.map((studio) => (+ <BoardFace key={studio.board!.id} studio={studio} agents={agents} labels={labels} active={drawn.has(studio.board!.id)} />+ ))}+ </group>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/TeamBoardFace.tsx b/jarvis/ui/web/frontend/src/components/society/office/TeamBoardFace.tsxindex 8e2426a3a7..75849fca7e 100644--- a/jarvis/ui/web/frontend/src/components/society/office/TeamBoardFace.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/TeamBoardFace.tsx@@ -1,7 +1,10 @@/*** The team room's whiteboard shows the real teams: up to four names with their- * member counts, and the one meeting at the table right now marked "live".- * Without any team the board keeps its drawn org chart.+ * member counts. A team whose round is answering right now (the backend's+ * word, through teamwork's rounds) wears the green "Live" mark; a team the+ * person merely called to the table or to its board wears a plain "Called"+ * one — a gathering on the map is not a round. Without any team the board+ * keeps its drawn org chart.*/import { useEffect, useMemo } from "react";import { CanvasTexture, SRGBColorSpace } from "three";@@ -9,6 +12,8 @@ import { useT } from "@/i18n";import { useSocietyChatGroups, type SocietyChatGroup } from "@/lib/societyChatGroups";import type { Furniture } from "./officeLayout";import { useOfficeStore } from "./officeStore";+import { teamMark, type TeamMark } from "./teamStatus";+import { useTeamwork } from "./teamwork";const W = 1024, H = 478;/** Board face in the teamBoard prop's local space (OfficeProps `TeamBoard`), a hair in front of the drawn panel. */@@ -23,7 +28,7 @@ function clipped(ctx: CanvasRenderingContext2D, text: string, maxWidth: number):return `${cut}…`;}-function drawBoard(ctx: CanvasRenderingContext2D, teams: SocietyChatGroup[], liveId: string | null, labels: { title: string; members: string; live: string }) {+function drawBoard(ctx: CanvasRenderingContext2D, teams: SocietyChatGroup[], marks: Record<string, TeamMark>, labels: { title: string; members: string; live: string; called: string }) {ctx.fillStyle = "#f4f4f0";ctx.fillRect(0, 0, W, H);ctx.fillStyle = "#2f3645";@@ -38,25 +43,33 @@ function drawBoard(ctx: CanvasRenderingContext2D, teams: SocietyChatGroup[], livconst rowH = (H - 130) / MAX_ROWS;rows.forEach((team, i) => {const y = 125 + i * rowH + rowH / 2 - 6;- const live = team.group_id === liveId;+ const mark = marks[team.group_id] ?? null;ctx.fillStyle = NOTE_COLOURS[i % NOTE_COLOURS.length];ctx.fillRect(50, y - rowH / 2 + 10, 26, rowH - 20);const count = labels.members.replace("{0}", String(team.members.length));ctx.font = "500 32px system-ui, sans-serif";const countW = ctx.measureText(count).width;- const liveW = live ? 150 : 0;+ const liveW = mark ? 150 : 0;ctx.fillStyle = "#1f2430";ctx.font = "600 40px system-ui, sans-serif";ctx.fillText(clipped(ctx, team.name, W - 190 - countW - liveW), 100, y);ctx.font = "500 32px system-ui, sans-serif";ctx.fillStyle = "#5b6475";ctx.fillText(count, W - 50 - countW - liveW, y);- if (live) {+ if (mark === "live") {ctx.fillStyle = "#2f9e5b";ctx.beginPath(); ctx.roundRect(W - 180, y - 24, 130, 48, 24); ctx.fill();ctx.fillStyle = "#ffffff";ctx.font = "700 28px system-ui, sans-serif";ctx.fillText(clipped(ctx, labels.live, 100), W - 162, y + 1);+ } else if (mark === "called") {+ // An outlined, colourless mark: the team was asked to gather, nothing more.+ ctx.strokeStyle = "#5b6475";+ ctx.lineWidth = 3;+ ctx.beginPath(); ctx.roundRect(W - 180, y - 24, 130, 48, 24); ctx.stroke();+ ctx.fillStyle = "#3b4250";+ ctx.font = "600 26px system-ui, sans-serif";+ ctx.fillText(clipped(ctx, labels.called, 104), W - 166, y + 1);}});}@@ -64,7 +77,8 @@ function drawBoard(ctx: CanvasRenderingContext2D, teams: SocietyChatGroup[], livexport function TeamBoardFace({ board, enabled }: { board: Furniture; enabled: boolean }) {const t = useT();const groups = useSocietyChatGroups(enabled);- const liveId = useOfficeStore((s) => (s.meeting && s.meeting.untilMs > Date.now() ? s.meeting.groupId : null));+ const gathering = useOfficeStore((s) => s.meeting);+ const rounds = useTeamwork((s) => s.rounds);const canvas = useMemo(() => {const el = typeof document === "undefined" ? null : document.createElement("canvas");if (el) { el.width = W; el.height = H; }@@ -79,14 +93,19 @@ export function TeamBoardFace({ board, enabled }: { board: Furniture; enabled: b}, [canvas]);useEffect(() => () => texture?.dispose(), [texture]);const teams = useMemo(() => [...(groups.data ?? [])].sort((a, b) => b.updated_ms - a.updated_ms), [groups.data]);- const labels = { title: t("society.office.team_yours"), members: t("society.office.team_members"), live: t("society.office.team_live") };- const signature = JSON.stringify([teams.map((g) => [g.group_id, g.name, g.members.length]), liveId, labels]);+ const labels = {+ title: t("society.office.team_yours"), members: t("society.office.team_members"),+ live: t("society.office.team_live"), called: t("society.office.team_called"),+ };+ const now = Date.now();+ const marks = Object.fromEntries(teams.map((g) => [g.group_id, teamMark(g.group_id, rounds, gathering, now)]));+ const signature = JSON.stringify([teams.map((g) => [g.group_id, g.name, g.members.length]), marks, labels]);useEffect(() => {const ctx = canvas?.getContext("2d");if (!ctx || !texture) return;- drawBoard(ctx, teams, liveId, labels);+ drawBoard(ctx, teams, marks, labels);texture.needsUpdate = true;- // `signature` covers teams, liveId and labels.+ // `signature` covers teams, marks and labels.// eslint-disable-next-line react-hooks/exhaustive-deps}, [signature, canvas, texture]);if (!texture || teams.length === 0) return null;diff --git a/jarvis/ui/web/frontend/src/components/society/office/TeamRoomDecor.tsx b/jarvis/ui/web/frontend/src/components/society/office/TeamRoomDecor.tsxindex ed8fb32feb..976399ae15 100644--- a/jarvis/ui/web/frontend/src/components/society/office/TeamRoomDecor.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/TeamRoomDecor.tsx@@ -26,9 +26,10 @@ type Vec3 = [number, number, number];// ---------------------------------------------------------------------------const C = {- walnut: "#6a4631",- walnutDark: "#3f2a1d",- walnutLight: "#8b6246",+ // The campus's oak: the keys keep the names the room was built with.+ walnut: "#b99a72",+ walnutDark: "#8e7252",+ walnutLight: "#d2b68c",travertine: "#e8dfd0",clay: "#c4775a",sage: "#8d9f86",@@ -44,7 +45,7 @@ const TM = {walnutLight: matte(C.walnutLight, { roughness: 0.55 }),travertine: matte(C.travertine, { roughness: 0.45 }),alu: matte("#c3c7cc", { roughness: 0.35, metalness: 0.5 }),- brass: matte("#c9a25a", { roughness: 0.35, metalness: 0.6 }),+ brass: matte("#b08d5c", { roughness: 0.35, metalness: 0.6 }),ceramic: matte(C.cream, { roughness: 0.4 }),clay: matte(C.clay, { roughness: 0.8 }),terracotta: matte(C.terracotta, { roughness: 0.75 }),diff --git a/jarvis/ui/web/frontend/src/components/society/office/TeamRoomPanel.test.tsx b/jarvis/ui/web/frontend/src/components/society/office/TeamRoomPanel.test.tsxindex ea4404bcd2..55c7c79b9e 100644--- a/jarvis/ui/web/frontend/src/components/society/office/TeamRoomPanel.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/TeamRoomPanel.test.tsx@@ -1,11 +1,13 @@import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";import { afterEach, beforeAll, beforeEach, describe, expect, test, vi } from "vitest";import { loadLocaleChunk } from "@/i18n";import type { SocietyAgent } from "../data";import type { SocietyChatGroup } from "@/lib/societyChatGroups";import { buildOfficeLayout } from "./officeLayout";+import { buildNavGrid } from "./officeNav";import { useOfficeStore } from "./officeStore";+import { emptyRound, useTeamwork } from "./teamwork";import { TeamRoomPanel } from "./TeamRoomPanel";const agents = [@@ -44,15 +46,16 @@ beforeEach(() => {}return new Response(JSON.stringify({ groups }));});- useOfficeStore.setState({ meeting: null, summons: {}, teamDraft: [] });+ useOfficeStore.setState({ meeting: null, summons: {}, teamDraft: [], selection: null, walkTo: null });+ useTeamwork.setState({ rounds: {} });});afterEach(() => { cleanup(); vi.unstubAllGlobals(); });-function mount(onOpenGroup = vi.fn()) {+function mount(props: Partial<Parameters<typeof TeamRoomPanel>[0]> = {}, onOpenGroup = vi.fn()) {render(<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>- <TeamRoomPanel agents={agents} layout={layout} sample={false} actions={{ onOpenAgent: vi.fn(), onOpenLedger: vi.fn(), onOpenGroup }} />+ <TeamRoomPanel agents={agents} layout={layout} sample={false} actions={{ onOpenAgent: vi.fn(), onOpenLedger: vi.fn(), onOpenGroup }} {...props} /></QueryClientProvider>,);return onOpenGroup;@@ -63,7 +66,9 @@ describe("team room panel", () => {mount();expect(await screen.findByText("Launch crew")).toBeTruthy();expect(screen.getByText(/2 members · 1 working/)).toBeTruthy();- expect(screen.getByTitle(/Ada Lovelace/).textContent).toContain("AL");+ // Every member shows as a face that names the agent and its state.+ expect(screen.getByTitle("Ada Lovelace · Idle")).toBeTruthy();+ expect(screen.getByTitle("Bo · Working")).toBeTruthy();fireEvent.click(screen.getByRole("button", { name: "Meet with Launch crew at the table" }));const { meeting, summons } = useOfficeStore.getState();@@ -71,9 +76,13 @@ describe("team room panel", () => {expect(summons.a1.spotId).toMatch(/^meeting-/);expect(summons.a2.spotId).toMatch(/^meeting-/);// The running meeting shows up top, and ending it releases everyone.- expect(await screen.findByText("Meeting: Launch crew")).toBeTruthy();+ // The gathering is named for what it is, with no live mark: nothing was posted and no round runs.+ expect(await screen.findByText("Launch crew · called to the table")).toBeTruthy();+ expect(screen.getByText(/nothing is posted to the team's chat/)).toBeTruthy();+ expect(screen.queryByText("Live")).toBeNull();+ expect((screen.getByRole("button", { name: "Meet with Launch crew at the table" }) as HTMLButtonElement).textContent).toBe("Called");expect(screen.getByText(/Working, so they stay at their desk: Bo/)).toBeTruthy();- fireEvent.click(screen.getByRole("button", { name: "End meeting" }));+ fireEvent.click(screen.getByRole("button", { name: "Send them back" }));expect(useOfficeStore.getState().meeting).toBeNull();expect(useOfficeStore.getState().summons).toEqual({});});@@ -107,4 +116,160 @@ describe("team room panel", () => {expect(calls.find((c) => c.method === "POST")?.body).toEqual({ name: "Ada Lovelace + Cy", members: ["a1", "a3"] });expect(useOfficeStore.getState().teamDraft).toEqual([]);});++ test("with no team yet it opens straight on the new-team form, with nothing to cancel back to", async () => {+ groups = [];+ mount();+ expect(await screen.findByRole("region", { name: "New team" })).toBeTruthy();+ expect(screen.getByRole("heading", { name: "New team" })).toBeTruthy();+ expect(screen.queryByRole("button", { name: "Cancel" })).toBeNull();+ const create = screen.getByRole("button", { name: "Create team and meet (0)" }) as HTMLButtonElement;+ expect(create.disabled).toBe(true);+ expect(screen.getByText("Pick at least two agents to create a team.")).toBeTruthy();+ fireEvent.click(screen.getByRole("checkbox", { name: /Ada Lovelace/ }));+ fireEvent.click(screen.getByRole("checkbox", { name: /Cy/ }));+ expect((screen.getByRole("button", { name: "Create team and meet (2)" }) as HTMLButtonElement).disabled).toBe(false);+ });++ test("eight teams are eight rows, and the new-team form takes the sheet to itself", async () => {+ groups = Array.from({ length: 8 }, (_, i) => ({ group_id: `g${i}`, name: `Team ${i}`, members: ["a1", "a2"], created_ms: i, updated_ms: i }));+ mount();+ expect(await screen.findByText("Team 7")).toBeTruthy();+ expect(screen.getAllByRole("listitem")).toHaveLength(8);+ expect(screen.getAllByRole("button", { name: /^Meet with Team \d at the table$/ })).toHaveLength(8);+ fireEvent.click(screen.getByRole("button", { name: "New team" }));+ // One job at a time: the list steps aside, so the form's buttons are never pushed off the sheet.+ expect(screen.queryByText("Team 7")).toBeNull();+ expect(screen.getByRole("button", { name: "Create team and meet (0)" })).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));+ expect(screen.getByText("Team 7")).toBeTruthy();+ });++ test("forty agents: the picker scrolls on its own, searches, and the buttons stay outside the list", async () => {+ const many = Array.from({ length: 40 }, (_, i) => ({+ agentId: `m${i}`, name: `Agent ${String(i).padStart(2, "0")}`, title: i % 2 ? "Writer" : "Research",+ state: i % 4 === 0 ? "working" : "idle", palette: { primary: "#4f7cac" },+ })) as SocietyAgent[];+ groups = [];+ mount({ agents: many });+ const list = await screen.findByRole("group", { name: "Members" });+ expect(list.className).toContain("team-picker-list");+ expect(within(list).getAllByRole("checkbox")).toHaveLength(40);+ // The buttons are not inside the scrolling list: they sit in the footer that stays at the sheet's edge.+ const create = screen.getByRole("button", { name: "Create team and meet (0)" });+ expect(list.contains(create)).toBe(false);+ expect(create.closest(".team-footer")).toBeTruthy();++ fireEvent.change(screen.getByRole("searchbox", { name: "Find an agent" }), { target: { value: "agent 07" } });+ expect(within(list).getAllByRole("checkbox")).toHaveLength(1);+ fireEvent.click(within(list).getByRole("checkbox", { name: /Agent 07/ }));+ fireEvent.change(screen.getByRole("searchbox", { name: "Find an agent" }), { target: { value: "nobody" } });+ expect(screen.getByText("No agent matches.")).toBeTruthy();+ // The pick survives the search.+ expect(screen.getByText("1 selected")).toBeTruthy();+ fireEvent.change(screen.getByRole("searchbox", { name: "Find an agent" }), { target: { value: "" } });+ fireEvent.click(screen.getByRole("button", { name: "All free agents" }));+ expect(screen.getByText("30 selected")).toBeTruthy();+ expect(screen.getByRole("button", { name: "Create team and meet (30)" })).toBeTruthy();+ });++ test("a working agent's face is its symbol, never the three thinking dots", async () => {+ mount();+ await screen.findByText("Launch crew");+ const face = screen.getByTitle("Bo · Working");+ expect(face.querySelector("[data-agent-symbol]")).toBeTruthy();+ expect(face.querySelector("[data-thinking='true']")).toBeNull();+ // Every face sits on the neutral tile, so a white or black symbol never vanishes into the dialog.+ expect(face.querySelector(".office-face [data-agent-symbol]")).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "Edit" }));+ const picker = screen.getByRole("group", { name: "Members" });+ expect(picker.querySelectorAll(".office-face [data-agent-symbol]")).toHaveLength(agents.length);+ });++ test("opened to start a team it shows the new-team form at once, and Cancel leads to the teams", async () => {+ mount({ compose: true });+ expect(await screen.findByRole("region", { name: "New team" })).toBeTruthy();+ expect(screen.getByRole("button", { name: "Create team and meet (0)" })).toBeTruthy();+ await waitFor(() => expect(screen.getByRole("button", { name: "Cancel" })).toBeTruthy());+ expect(screen.queryByText("Launch crew")).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));+ expect(screen.getByText("Launch crew")).toBeTruthy();+ });++ test("a team is marked live only while the backend says its round is answering", async () => {+ mount();+ await screen.findByText("Launch crew");+ expect(screen.queryByText("Live")).toBeNull();+ act(() => useTeamwork.getState().setRound({ ...emptyRound("g1"), running: true }));+ expect(screen.getByText("Live")).toBeTruthy();+ // The round ended: the mark goes, whatever the person has called together on the map.+ act(() => useTeamwork.getState().setRound({ ...emptyRound("g1"), running: false }));+ fireEvent.click(screen.getByRole("button", { name: "Meet with Launch crew at the table" }));+ expect(await screen.findByText("Launch crew · called to the table")).toBeTruthy();+ expect(screen.queryByText("Live")).toBeNull();+ });++ test("opens the real team chat from a team's row", async () => {+ const onOpenGroup = mount();+ fireEvent.click(await screen.findByRole("button", { name: "Open the chat of Launch crew" }));+ expect(onOpenGroup).toHaveBeenCalledWith("g1");+ });++ test("steps aside when a team is sent to the table, so the person sees it gather", async () => {+ const onMeet = vi.fn();+ mount({ onMeet });+ fireEvent.click(await screen.findByRole("button", { name: "Meet with Launch crew at the table" }));+ expect(onMeet).toHaveBeenCalledOnce();+ });++ test("a studio board opens its own team with every member, and the other teams one step away", async () => {+ groups = [...groups, { group_id: "g9", name: "Night shift", members: ["a2", "a3"], created_ms: 3, updated_ms: 3 }];+ mount({ focus: { teamId: "g1", members: ["a1", "a2"] } });+ expect(await screen.findByText("Launch crew")).toBeTruthy();+ expect(screen.getByText("This team")).toBeTruthy();+ expect(screen.queryByText("Night shift")).toBeNull();+ // The members are listed by name, each with a way to talk to them.+ fireEvent.click(screen.getByRole("button", { name: "Talk to Ada Lovelace" }));+ expect(useOfficeStore.getState().selection).toEqual({ kind: "agent", id: "a1" });+ fireEvent.click(screen.getByRole("button", { name: "All teams (2)" }));+ expect(screen.getByText("Night shift")).toBeTruthy();+ expect(screen.getByText("Your teams")).toBeTruthy();+ });++ test("from its own studio board a team meets at that board, not at the team room's table", async () => {+ const campus = buildOfficeLayout(agents.map((a, i) => ({+ agentId: a.agentId, name: a.name, tier: "specialist" as const, providerLabel: "Codex", state: a.state, createdMs: i,+ })), { teams: [{ id: "g1", name: "Launch crew", members: ["a1", "a2"], createdMs: 1 }] });+ const studio = campus.studios!.find((s) => s.teamId === "g1")!;+ expect(studio.board).toBeTruthy();+ groups = [...groups, { group_id: "g9", name: "Night shift", members: ["a2", "a3"], created_ms: 3, updated_ms: 3 }];+ mount({ layout: campus, focus: { teamId: "g1", members: studio.members, studio, grid: buildNavGrid(campus) } });+ expect(await screen.findByText("Launch crew")).toBeTruthy();+ expect(screen.queryByRole("button", { name: "Meet with Launch crew at the table" })).toBeNull();+ // Another team, reached through "All teams", has no board here: it still meets at the table.+ fireEvent.click(screen.getByRole("button", { name: "All teams (2)" }));+ expect(screen.getByRole("button", { name: "Meet with Night shift at the table" })).toBeTruthy();++ fireEvent.click(screen.getByRole("button", { name: "Meet with Launch crew at the board" }));+ const { meeting, summons } = useOfficeStore.getState();+ expect(meeting).toMatchObject({ groupId: "g1", boardId: studio.board!.id });+ // Each member is called to a standing place in the arcs in front of the studio's board.+ expect(summons.a1.spotId).toMatch(new RegExp(`^fan:${studio.deptId}:`));+ expect(summons.a2.spotId).toMatch(new RegExp(`^fan:${studio.deptId}:`));+ expect(summons.a1.spotId).not.toBe(summons.a2.spotId);+ // The running meeting says where it is, and "go there" walks to that board.+ expect(await screen.findByText(/of 2 at the board/)).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "Go to the board" }));+ const goal = useOfficeStore.getState().walkTo!.point;+ expect(Math.hypot(goal.x - studio.board!.x, goal.z - studio.board!.z)).toBeLessThan(2);+ });++ test("the board of agents without a team offers to make them one", async () => {+ mount({ focus: { teamId: null, members: ["a2", "a3"] } });+ expect(await screen.findByText(/not in a team yet/)).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "New team" }));+ // The people sitting there are picked already.+ expect(useOfficeStore.getState().teamDraft).toEqual(["a2", "a3"]);+ expect(screen.getByRole("button", { name: "Create team and meet (2)" })).toBeTruthy();+ });});diff --git a/jarvis/ui/web/frontend/src/components/society/office/TeamRoomPanel.tsx b/jarvis/ui/web/frontend/src/components/society/office/TeamRoomPanel.tsxindex fafe81a10f..7c63180295 100644--- a/jarvis/ui/web/frontend/src/components/society/office/TeamRoomPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/TeamRoomPanel.tsx@@ -1,48 +1,73 @@/**- * The team room checkpoint: your teams as cards (meet at the table, open the- * team chat, rename, change members, delete), a live meeting banner while a- * team sits at the table, and a quick way to put a new team together.+ * Teams in the office. The team room's board opens every team; a team+ * studio's board opens that studio's team. Either way this is the same sheet:+ * who is in the team and what they do right now, meet at the table, open the+ * team's real chat, rename it, change its members, delete it, and put a new+ * team together.** Teams are the existing society chat groups; the office adds no backend* contract. A meeting is purely spatial — members walk to the team room and* sit down — and never interrupts an agent that is working.*/-import { useEffect, useMemo, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import { useQueryClient } from "@tanstack/react-query";+import { MessagesSquare, Pencil, Plus, Users } from "lucide-react";import { useT } from "@/i18n";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";import {createSocietyChatGroup, deleteSocietyChatGroup, updateSocietyChatGroup, useSocietyChatGroups, type SocietyChatGroup,} from "@/lib/societyChatGroups";+import { cn } from "@/lib/utils";import type { SocietyAgent } from "../data";-import type { OfficeLayout, Point } from "./officeLayout";+import type { OfficeLayout, Point, Studio } from "./officeLayout";+import type { NavGrid } from "./officeNav";+import { stationOf } from "./stations";import { useOfficeStore } from "./officeStore";import { agentPositions } from "./walkerRegistry";-import { MEETING_MS, meetingProgress, meetingSeats, minutesLeft } from "./teamMeeting";+import { boardSeats, MEETING_MS, meetingProgress, meetingSeats, minutesLeft } from "./teamMeeting";import type { OfficeActions } from "./OfficePanels";+import { AgentFace } from "./AgentFace";+import { useTeamwork } from "./teamwork";import "./teamRoom.css";const GROUPS_KEY = ["society", "chat-groups"] as const;/** Above this many agents the picker gets a search field. */const SEARCH_FROM = 7;+/** Faces shown in a team's row before the rest fold into "+n". */+const STACK_MAX = 6;-function initials(name: string): string {- const parts = name.trim().split(/\s+/).filter(Boolean);- if (parts.length === 0) return "?";- return (parts.length > 1 ? parts[0][0] + parts[1][0] : parts[0].slice(0, 2)).toUpperCase();+/** The studio whose board was used: its team (null = the studio of agents without a team) and who sits there. */+export interface TeamFocus {+ teamId: string | null; members: readonly string[];+ /** The studio itself: its team meets at its own board instead of the table. `grid` is the floor's nav grid when the host has it. */+ studio?: Studio; grid?: NavGrid;}function errorText(err: unknown): string {return err instanceof Error ? err.message : String(err);}-/** A member as a small round badge in the agent's colour, with its state dot. */-function MemberBadge({ agent }: { agent: SocietyAgent }) {+function StateDot({ state }: { state: SocietyAgent["state"] }) {+ return <i className="office-dot" data-state={state} aria-hidden />;+}++/** An agent's face in these lists: its symbol on the neutral tile (AgentFace.tsx). */+const Face = AgentFace;++/** A team's members as overlapping faces, each with its state dot. */+function MemberStack({ agents }: { agents: SocietyAgent[] }) {const t = useT();+ const shown = agents.slice(0, STACK_MAX);return (- <span className="team-badge" style={{ background: agent.palette.primary }}- title={`${agent.name} · ${t(`society.office.state_${agent.state}`)}`}>- {initials(agent.name)}- <i className="office-dot" data-state={agent.state} aria-hidden />+ <span className="team-stack">+ {shown.map((agent) => (+ <span key={agent.agentId} className="team-face" title={`${agent.name} · ${t(`society.office.state_${agent.state}`)}`}>+ <Face agent={agent} />+ <StateDot state={agent.state} />+ </span>+ ))}+ {agents.length > shown.length && <span className="team-face team-face-more office-face" aria-hidden>+{agents.length - shown.length}</span>}</span>);}@@ -63,44 +88,51 @@ function MemberPicker({ agents, selected, onToggle, onSet }: {const shown = needle ? agents.filter((a) => `${a.name} ${a.title}`.toLowerCase().includes(needle)) : agents;const free = agents.filter((a) => a.state === "idle").map((a) => a.agentId);return (- <div className="team-picker">- {agents.length >= SEARCH_FROM && (- <label className="office-field">- <span className="sr-only">{t("society.office.team_search")}</span>- <input type="search" value={query} onChange={(e) => setQuery(e.target.value)} placeholder={t("society.office.team_search")} />- </label>- )}- <div className="office-actions">- <button type="button" className="office-mini" disabled={free.length === 0} onClick={() => onSet([...new Set([...selected, ...free])])}>- {t("society.office.team_pick_idle")}- </button>- <button type="button" className="office-mini" disabled={selected.length === 0} onClick={() => onSet([])}>- {t("society.office.team_pick_clear")}- </button>- <span className="office-hint team-picker-count" aria-live="polite">- {t("society.office.team_selected").replace("{0}", String(selected.length))}+ <div className="grid gap-2">+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-sm font-medium">{t("society.office.team_members_label")}</span>+ <span className="text-xs text-muted-foreground" aria-live="polite">{t("society.office.team_selected").replace("{0}", String(selected.length))}</span>+ <span className="ml-auto flex gap-1">+ <Button type="button" variant="ghost" size="sm" disabled={free.length === 0} onClick={() => onSet([...new Set([...selected, ...free])])}>+ {t("society.office.team_pick_idle")}+ </Button>+ <Button type="button" variant="ghost" size="sm" disabled={selected.length === 0} onClick={() => onSet([])}>+ {t("society.office.team_pick_clear")}+ </Button></span></div>- {shown.length === 0 ? <p className="office-note-inline">{t("society.office.team_no_match")}</p> : (- <ul className="office-list office-list-check">+ {agents.length >= SEARCH_FROM && (+ <Input type="search" value={query} onChange={(e) => setQuery(e.target.value)} placeholder={t("society.office.team_search")}+ aria-label={t("society.office.team_search")} />+ )}+ {shown.length === 0 ? <p className="text-sm text-muted-foreground">{t("society.office.team_no_match")}</p> : (+ <div className="team-picker-list min-h-0 overflow-y-auto rounded-md border border-border p-1" role="group" aria-label={t("society.office.team_members_label")}>{shown.map((agent) => (- <li key={agent.agentId}>- <label>- <input type="checkbox" checked={selected.includes(agent.agentId)} onChange={() => onToggle(agent.agentId)} />- <i className="office-dot" data-state={agent.state} aria-hidden />- <span className="office-list-name" title={agent.title ? `${agent.name} · ${agent.title}` : agent.name}>{agent.name}</span>- {agent.title && <span className="team-picker-title">{agent.title}</span>}- </label>- </li>+ <label key={agent.agentId} className="flex cursor-pointer items-center gap-3 rounded-md px-2 py-1.5 hover:bg-secondary">+ <input type="checkbox" className="accent-primary" checked={selected.includes(agent.agentId)} onChange={() => onToggle(agent.agentId)} />+ <Face agent={agent} />+ <span className="min-w-0 flex-1 truncate text-sm">{agent.name}</span>+ {agent.title && <span className="max-w-[40%] truncate text-xs text-muted-foreground">{agent.title}</span>}+ <StateDot state={agent.state} />+ </label>))}- </ul>+ </div>)}</div>);}-/** The meeting at the table right now: who sits, who is coming, who keeps working. */-function MeetingBanner({ agents, layout, actions }: { agents: SocietyAgent[]; layout: OfficeLayout; actions: OfficeActions }) {+/**+ * The team the person called together right now: who stands or sits there,+ * who is coming, who keeps working. It is a gathering on the map and says so+ * — nothing is posted to the team and no round runs because of it, so it+ * carries no "live" mark (that belongs to a real round, see teamStatus.ts).+ * The sheet shows it as a banner; the HUD shows it as a small card while the+ * sheet is closed, and also lets the team go when its time is up.+ */+export function MeetingStatus({ agents, layout, actions, compact = false }: {+ agents: readonly SocietyAgent[]; layout: OfficeLayout; actions: OfficeActions; compact?: boolean;+}) {const t = useT();const meeting = useOfficeStore((s) => s.meeting);const summons = useOfficeStore((s) => s.summons);@@ -118,34 +150,38 @@ function MeetingBanner({ agents, layout, actions }: { agents: SocietyAgent[]; laconst progress = meetingProgress(meeting, agents, summons, agentPositions);const present = meeting.members.length - progress.missing.length;const nameOf = (id: string) => agents.find((a) => a.agentId === id)?.name ?? id;- const approach = tableApproach(layout);+ // A meeting at a studio's board is joined in front of that board; any other at the team room's table.+ const atBoard = !!meeting.boardId;+ const approach = atBoard ? stationOf(layout, { kind: "team", id: meeting.boardId as string })?.approach ?? null : tableApproach(layout);return (- <section className="team-meeting" aria-live="polite">- <p className="team-meeting-title"><span className="team-meeting-live" aria-hidden />{t("society.office.meeting_title").replace("{0}", meeting.name)}</p>- <p className="office-hint">- {t("society.office.meeting_status")+ <section className={cn("team-meeting", compact && "office-card")} data-compact={compact || undefined} data-office-ui aria-live="polite">+ <p className="team-meeting-title">{t(atBoard ? "society.office.gather_board" : "society.office.gather_table").replace("{0}", meeting.name)}</p>+ <p className="team-meeting-line">+ {t(atBoard ? "society.office.meeting_status_board" : "society.office.meeting_status").replace("{0}", String(progress.seated.length)).replace("{1}", String(present)).replace("{2}", String(minutesLeft(meeting, now)))}</p>{progress.busy.length > 0 && (- <p className="office-hint">{t("society.office.meeting_busy").replace("{0}", progress.busy.map(nameOf).join(", "))}</p>+ <p className="team-meeting-line">{t("society.office.meeting_busy").replace("{0}", progress.busy.map(nameOf).join(", "))}</p>)}- <div className="office-actions">+ {!compact && <p className="team-meeting-line">{t("society.office.gather_note")}</p>}+ <div className="flex flex-wrap gap-2 pt-1">{actions.onOpenGroup && (- <button type="button" className="office-action office-action-primary" onClick={() => actions.onOpenGroup?.(meeting.groupId)}>- {t("society.office.team_chat")}- </button>+ <Button type="button" size="sm" onClick={() => actions.onOpenGroup?.(meeting.groupId)}>{t("society.office.team_chat")}</Button>)}- {approach && <button type="button" className="office-action" onClick={() => requestWalk(approach)}>{t("society.office.meeting_join")}</button>}- <button type="button" className="office-action" onClick={endMeeting}>{t("society.office.meeting_end")}</button>+ {approach && <Button type="button" size="sm" variant="outline" onClick={() => requestWalk(approach)}>{t(atBoard ? "society.office.meeting_join_board" : "society.office.meeting_join")}</Button>}+ <Button type="button" size="sm" variant="outline" onClick={endMeeting}>{t("society.office.gather_end")}</Button></div></section>);}-/** One team: members at a glance, meet / chat, and an inline editor. */-function TeamCard({ group, agents, layout, sample, actions }: {+/** One team: who is in it, meet / chat, and an editor that unfolds in place. `detail` also lists every member. */+function TeamCard({ group, agents, layout, sample, actions, detail = false, onMeet, board = null }: {group: SocietyChatGroup; agents: SocietyAgent[]; layout: OfficeLayout; sample: boolean; actions: OfficeActions;+ detail?: boolean; onMeet?: () => void;+ /** This team's own studio, when the sheet was opened from its board: the team meets there. */+ board?: { studio: Studio; grid?: NavGrid } | null;}) {const t = useT();const client = useQueryClient();@@ -161,12 +197,21 @@ function TeamCard({ group, agents, layout, sample, actions }: {const working = present.filter((a) => a.state === "working").length;const lead = present.find((a) => a.agentId === group.lead_agent_id);const inMeeting = !!meeting && meeting.groupId === group.group_id && meeting.untilMs > Date.now();+ // A round of this team is answering right now (the backend's word): the only thing that is called live.+ const live = useTeamwork((s) => !!s.rounds[group.group_id]?.running);const meet = () => {const ids = present.map((a) => a.agentId);- startMeeting({ groupId: group.group_id, name: group.name, members: ids, untilMs: Date.now() + MEETING_MS }, meetingSeats(layout, ids));+ const meeting = { groupId: group.group_id, name: group.name, members: ids, untilMs: Date.now() + MEETING_MS };+ // From its own studio board the team gathers right there; from the team room it sits down at the table.+ if (board?.studio.board) startMeeting({ ...meeting, boardId: board.studio.board.id }, boardSeats(layout, board.studio, ids, board.grid));+ else startMeeting(meeting, meetingSeats(layout, ids));+ onMeet?.();};+ const editor = useRef<HTMLDivElement>(null);const openEditor = () => { setName(group.name); setMembers(group.members); setConfirmDelete(false); setError(""); setEditing(true); };+ // A team far down the list: its editor, with the Save button, comes into view.+ useEffect(() => { if (editing) editor.current?.scrollIntoView?.({ block: "nearest" }); }, [editing]);const save = async () => {if (members.length < 2 || busy) return;setBusy(true); setError("");@@ -194,78 +239,108 @@ function TeamCard({ group, agents, layout, sample, actions }: {};return (- <li className="team-card" data-meeting={inMeeting || undefined}>- <div className="team-card-head">- <span className="team-card-name" title={group.name}>{group.name}</span>- <span className="office-hint">- {t("society.office.team_members").replace("{0}", String(present.length))}- {working > 0 ? ` · ${t("society.office.team_working").replace("{0}", String(working))}` : ""}- {lead ? ` · ${t("society.office.team_lead").replace("{0}", lead.name)}` : ""}- </span>- </div>- <div className="team-badges">- {present.map((agent) => <MemberBadge key={agent.agentId} agent={agent} />)}- </div>- {!editing ? (- <div className="office-actions">- <button type="button" className="office-action office-action-primary" disabled={inMeeting || present.length === 0}- aria-label={t("society.office.team_gather_label").replace("{0}", group.name)} onClick={meet}>- {inMeeting ? t("society.office.team_meeting_now") : t("society.office.team_meet")}- </button>+ <li className="team-card rounded-xl border border-border bg-background" data-live={live || undefined} data-called={inMeeting || undefined}>+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2 p-4">+ <MemberStack agents={present} />+ <div className="grid min-w-0 flex-1 gap-0.5">+ <span className="flex min-w-0 items-center gap-2">+ <span className="truncate text-sm font-semibold" title={group.name}>{group.name}</span>+ {live && <span className="team-live-mark"><i aria-hidden />{t("society.office.team_live")}</span>}+ </span>+ <span className="text-xs text-muted-foreground">+ {t("society.office.team_members").replace("{0}", String(present.length))}+ {working > 0 ? ` · ${t("society.office.team_working").replace("{0}", String(working))}` : ""}+ {lead ? ` · ${t("society.office.team_lead").replace("{0}", lead.name)}` : ""}+ </span>+ </div>+ <div className="flex flex-wrap gap-2">+ <Button type="button" size="sm" disabled={inMeeting || present.length === 0}+ aria-label={t(board ? "society.office.team_gather_board_label" : "society.office.team_gather_label").replace("{0}", group.name)} onClick={meet}>+ <Users aria-hidden />{inMeeting ? t("society.office.team_called") : t(board ? "society.office.team_meet_board" : "society.office.team_meet")}+ </Button>{actions.onOpenGroup && (- <button type="button" className="office-action" aria-label={t("society.office.team_open_label").replace("{0}", group.name)}- onClick={() => actions.onOpenGroup?.(group.group_id)}>{t("society.office.team_chat")}</button>+ <Button type="button" size="sm" variant="outline" aria-label={t("society.office.team_open_label").replace("{0}", group.name)}+ onClick={() => actions.onOpenGroup?.(group.group_id)}><MessagesSquare aria-hidden />{t("society.office.team_chat")}</Button>+ )}+ {!sample && !editing && (+ <Button type="button" size="sm" variant="ghost" onClick={openEditor}><Pencil aria-hidden />{t("society.office.team_edit")}</Button>)}- {!sample && <button type="button" className="office-action" onClick={openEditor}>{t("society.office.team_edit")}</button>}</div>- ) : (- <div className="team-editor">- <label className="office-field">- <span>{t("society.office.team_name")}</span>- <input value={name} maxLength={60} onChange={(e) => setName(e.target.value)}+ </div>+ {detail && !editing && present.length > 0 && (+ <ul className="grid gap-0.5 border-t border-border p-2">+ {present.map((agent) => (+ <li key={agent.agentId} className="flex items-center gap-3 rounded-md px-2 py-1.5">+ <Face agent={agent} />+ <span className="min-w-0 flex-1 truncate text-sm">{agent.name}</span>+ <span className="flex items-center gap-1.5 text-xs text-muted-foreground"><StateDot state={agent.state} />{t(`society.office.state_${agent.state}`)}</span>+ <Button type="button" size="sm" variant="ghost" aria-label={t("society.office.prompt_agent").replace("{0}", agent.name)}+ onClick={() => useOfficeStore.getState().select({ kind: "agent", id: agent.agentId })}>{t("society.office.action_talk")}</Button>+ </li>+ ))}+ </ul>+ )}+ {editing && (+ <div ref={editor} className="grid gap-3 border-t border-border p-4">+ <label className="grid gap-1 text-sm font-medium">+ {t("society.office.team_name")}+ <Input value={name} maxLength={60} onChange={(e) => setName(e.target.value)}onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); void save(); } }} /></label><MemberPicker agents={agents} selected={members}onToggle={(id) => setMembers((m) => (m.includes(id) ? m.filter((x) => x !== id) : [...m, id]))} onSet={setMembers} />- {members.length < 2 && <p className="office-hint">{t("society.office.team_edit_need_more")}</p>}- <div className="office-actions">- <button type="button" className="office-action office-action-primary" disabled={busy || members.length < 2} aria-busy={busy}- onClick={() => void save()}>{t("society.office.team_save")}</button>- <button type="button" className="office-action" disabled={busy} onClick={() => setEditing(false)}>{t("society.office.team_cancel")}</button>- {confirmDelete ? (- <button type="button" className="office-action team-danger" disabled={busy} onClick={() => void remove()}>- {t("society.office.team_delete_confirm")}- </button>- ) : (- <button type="button" className="office-action" disabled={busy} onClick={() => setConfirmDelete(true)}>{t("society.office.team_delete")}</button>- )}+ {members.length < 2 && <p className="text-xs text-muted-foreground">{t("society.office.team_edit_need_more")}</p>}+ <div className="flex flex-wrap items-center gap-2">+ <Button type="button" size="sm" disabled={busy || members.length < 2} aria-busy={busy} onClick={() => void save()}>{t("society.office.team_save")}</Button>+ <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => setEditing(false)}>{t("society.office.team_cancel")}</Button>+ <span className="ml-auto">+ {confirmDelete ? (+ <Button type="button" size="sm" variant="destructive" disabled={busy} onClick={() => void remove()}>{t("society.office.team_delete_confirm")}</Button>+ ) : (+ <button type="button" className="text-xs text-destructive underline underline-offset-2 disabled:opacity-50" disabled={busy}+ onClick={() => setConfirmDelete(true)}>{t("society.office.team_delete")}</button>+ )}+ </span></div></div>)}- {error && <p role="alert" className="office-error">{error}</p>}+ {error && <p role="alert" className="px-4 pb-3 text-xs text-destructive">{error}</p>}</li>);}-export function TeamRoomPanel({ agents, layout, sample, actions }: { agents: SocietyAgent[]; layout: OfficeLayout; sample: boolean; actions: OfficeActions }) {+export function TeamRoomPanel({ agents, layout, sample, actions, focus = null, onMeet, compose = false }: {+ agents: SocietyAgent[]; layout: OfficeLayout; sample: boolean; actions: OfficeActions;+ /** Opened from a team studio's board: show that studio's team first. */+ focus?: TeamFocus | null;+ /** A team was sent to the table (the sheet steps aside so the person sees them gather). */+ onMeet?: () => void;+ /** Open on the new-team form (the free plot's stand: "start a team here"). */+ compose?: boolean;+}) {const t = useT();const client = useQueryClient();- const store = useOfficeStore();+ const teamDraft = useOfficeStore((s) => s.teamDraft);+ const toggleDraft = useOfficeStore((s) => s.toggleDraft);+ const clearDraft = useOfficeStore((s) => s.clearDraft);const groups = useSocietyChatGroups(!sample);const [name, setName] = useState("");const [busy, setBusy] = useState(false);const [error, setError] = useState("");const [created, setCreated] = useState("");+ const [everyTeam, setEveryTeam] = useState(false);const teams = useMemo(() => [...(groups.data ?? [])].sort((a, b) => b.updated_ms - a.updated_ms), [groups.data]);- const members = store.teamDraft.filter((id) => agents.some((a) => a.agentId === id));+ const members = teamDraft.filter((id) => agents.some((a) => a.agentId === id));// The new-team form stays folded behind a button once teams exist, unless agents were already picked on the map.- const [composing, setComposing] = useState(false);- const showComposer = composing || teams.length === 0 || members.length > 0;+ const [composing, setComposing] = useState(compose);+ const studioTeam = focus?.teamId ? teams.find((g) => g.group_id === focus.teamId) ?? null : null;+ const studioOnly = !!focus && !everyTeam;+ const showComposer = composing || members.length > 0 || (!studioOnly && teams.length === 0 && !groups.isLoading && !groups.isError);const canCreate = !sample && !busy && members.length >= 2;const setDraft = (ids: string[]) => {- store.clearDraft();- ids.forEach((id) => store.toggleDraft(id));+ clearDraft();+ ids.forEach((id) => toggleDraft(id));};const create = async () => {if (!canCreate) return;@@ -274,8 +349,9 @@ export function TeamRoomPanel({ agents, layout, sample, actions }: { agents: Socconst names = members.map((id) => agents.find((a) => a.agentId === id)?.name ?? id);const group = await createSocietyChatGroup(name.trim() || names.join(" + "), members);await client.invalidateQueries({ queryKey: GROUPS_KEY });- store.startMeeting({ groupId: group.group_id, name: group.name, members, untilMs: Date.now() + MEETING_MS }, meetingSeats(layout, members));- store.clearDraft();+ useOfficeStore.getState().startMeeting(+ { groupId: group.group_id, name: group.name, members, untilMs: Date.now() + MEETING_MS }, meetingSeats(layout, members));+ clearDraft();setName("");setComposing(false);setCreated(group.name);@@ -285,50 +361,74 @@ export function TeamRoomPanel({ agents, layout, sample, actions }: { agents: SocsetBusy(false);}};+ const poolMembers = focus && !focus.teamId ? agents.filter((a) => focus.members.includes(a.agentId)) : [];+ const shownTeams = studioOnly ? (studioTeam ? [studioTeam] : []) : teams;return (<>- <MeetingBanner agents={agents} layout={layout} actions={actions} />- {sample && <p className="office-note-inline">{t("society.office.sample")}</p>}- {created && <p className="office-success" role="status">{t("society.office.team_created").replace("{0}", created)}</p>}-- <h3 className="office-subhead">{t("society.office.team_yours")}</h3>- {groups.isError && <p role="alert" className="office-error">{t("society.office.team_load_error").replace("{0}", errorText(groups.error))}</p>}- {teams.length === 0 && !groups.isLoading && !groups.isError && <p className="office-note-inline">{t("society.office.team_none")}</p>}- {teams.length > 0 && (- <ul className="team-cards">- {teams.map((group) => <TeamCard key={group.group_id} group={group} agents={agents} layout={layout} sample={sample} actions={actions} />)}- </ul>- )}+ <MeetingStatus agents={agents} layout={layout} actions={actions} />+ {sample && <p className="text-sm text-muted-foreground">{t("society.office.sample")}</p>}+ {created && <p className="text-sm" role="status">{t("society.office.team_created").replace("{0}", created)}</p>}- {!showComposer ? (- <button type="button" className="office-action" onClick={() => setComposing(true)}>{t("society.office.team_new")}</button>- ) : (- <section className="team-composer" aria-label={t("society.office.team_new")}>- <h3 className="office-subhead">{t("society.office.team_new")}</h3>- <p className="office-hint">{t("society.office.team_body")}</p>- {agents.length === 0 ? <p className="office-note-inline">{t("society.office.manage_empty")}</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")}- onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); void create(); } }} />- </label>- <MemberPicker agents={agents} selected={members} onToggle={store.toggleDraft} onSet={setDraft} />- </>+ <section className="grid gap-3">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <h3 className="text-sm font-semibold">{t(showComposer ? "society.office.team_new" : studioOnly ? "society.office.team_this" : "society.office.team_yours")}</h3>+ {!showComposer && !sample && (+ <Button type="button" size="sm" variant="outline" onClick={() => {+ // From the studio of agents without a team, the people sitting there are the obvious first pick.+ if (studioOnly && poolMembers.length > 0 && members.length === 0) setDraft(poolMembers.map((a) => a.agentId));+ setComposing(true);+ }}><Plus aria-hidden />{t("society.office.team_new")}</Button>)}- <div className="office-actions">- <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>- {teams.length > 0 && (- <button type="button" className="office-action" onClick={() => { setComposing(false); store.clearDraft(); }}>{t("society.office.team_cancel")}</button>+ </div>+ {groups.isError && <p role="alert" className="text-sm text-destructive">{t("society.office.team_load_error").replace("{0}", errorText(groups.error))}</p>}++ {showComposer && (+ <section className="grid gap-3" aria-label={t("society.office.team_new")}>+ <p className="text-sm text-muted-foreground">{t("society.office.team_body")}</p>+ {agents.length === 0 ? <p className="text-sm text-muted-foreground">{t("society.office.manage_empty")}</p> : (+ <>+ <label className="grid gap-1 text-sm font-medium">+ {t("society.office.team_name")}+ <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>+ <MemberPicker agents={agents} selected={members} onToggle={toggleDraft} onSet={setDraft} />+ </>)}+ {error && <p role="alert" className="text-xs text-destructive">{error}</p>}+ {/* Pinned to the sheet's lower edge, so the button is in reach however long the list above it is. */}+ <div className="team-footer">+ <Button type="button" size="sm" disabled={!canCreate} aria-busy={busy} onClick={() => void create()}>+ {t("society.office.team_create").replace("{0}", String(members.length))}+ </Button>+ {(teams.length > 0 || studioOnly) && (+ <Button type="button" size="sm" variant="outline" onClick={() => { setComposing(false); clearDraft(); }}>{t("society.office.team_cancel")}</Button>+ )}+ {!sample && members.length < 2 && agents.length >= 2 && <span className="text-xs text-muted-foreground">{t("society.office.team_need_more")}</span>}+ </div>+ </section>+ )}++ {!showComposer && shownTeams.length > 0 && (+ <ul className="grid list-none gap-3 p-0">+ {shownTeams.map((group) => (+ <TeamCard key={group.group_id} group={group} agents={agents} layout={layout} sample={sample} actions={actions}+ detail={studioOnly} onMeet={onMeet}+ board={focus?.studio?.board && group.group_id === focus.teamId ? { studio: focus.studio, grid: focus.grid } : null} />+ ))}+ </ul>+ )}+ {!showComposer && studioOnly && !studioTeam && !groups.isLoading && (+ <div className="grid gap-2 rounded-lg border border-dashed border-border p-4">+ <p className="text-sm text-muted-foreground">{t(focus?.teamId ? "society.office.team_gone" : "society.office.team_pool_body")}</p>+ {poolMembers.length > 0 && <MemberStack agents={poolMembers} />}</div>- {!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>}- </section>- )}+ )}+ {!showComposer && studioOnly && teams.length > (studioTeam ? 1 : 0) && (+ <div><Button type="button" size="sm" variant="ghost" onClick={() => setEveryTeam(true)}>{t("society.office.team_all").replace("{0}", String(teams.length))}</Button></div>+ )}+ </section></>);}diff --git a/jarvis/ui/web/frontend/src/components/society/office/ToyFigure.rebake.test.tsx b/jarvis/ui/web/frontend/src/components/society/office/ToyFigure.rebake.test.tsxnew file mode 100644index 0000000000..b80953b7d4--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/ToyFigure.rebake.test.tsx@@ -0,0 +1,128 @@+/**+ * A figure's merged parts are baked again only when what it wears changes.+ * The level store takes a freshly parsed snapshot about once a minute; the+ * regalia built from it are then new JSX with the same content, and must not+ * make every dressed figure on the floor bake all its parts again.+ */+import { afterEach, describe, expect, it } from "vitest";+import { act, createRoot, extend, type ReconcilerRoot } from "@react-three/fiber";+import * as THREE from "three";+import type { Mesh, Object3D } from "three";+import { loadProfile, playerLook } from "./playerProfile";+import { PERSON_SUBJECT, type ProgressionSnapshot, type RewardRow } from "../progression/progressionApi";+import { useProgression } from "../progression/progressionStore";+import { regaliaFor, useDressedFigure } from "../progression/regalia/dress";+import { contentKey, ToyFigure, type FigureRegalia } from "./ToyFigure";++/** Just enough of a WebGLRenderer for R3F to mount a scene graph without a GPU. */+function fakeRenderer(canvas: HTMLCanvasElement) {+ const noop = () => undefined;+ return {+ domElement: canvas,+ render: noop, setSize: noop, setPixelRatio: noop, setAnimationLoop: noop, dispose: noop,+ getPixelRatio: () => 1,+ shadowMap: { enabled: false, type: 0, needsUpdate: false },+ xr: { enabled: false, isPresenting: false, addEventListener: noop, removeEventListener: noop, setAnimationLoop: noop },+ outputColorSpace: "srgb", toneMapping: 0, toneMappingExposure: 1,+ info: { render: {}, memory: {} },+ };+}++extend(THREE);++let root: ReconcilerRoot<HTMLCanvasElement> | null = null;+let scene: Object3D | null = null;++/** Render into one root, so a second call updates what the first one mounted. */+async function render(element: JSX.Element): Promise<Object3D> {+ if (!root) {+ const canvas = document.createElement("canvas");+ root = createRoot(canvas);+ root.configure({+ // Test double: R3F only needs the renderer's shape here, nothing is drawn.+ gl: fakeRenderer(canvas) as unknown as NonNullable<Parameters<typeof root.configure>[0]>["gl"],+ frameloop: "never",+ size: { width: 100, height: 100, top: 0, left: 0 },+ });+ }+ const current = root;+ await act(async () => { current.render(<group ref={(g) => { if (g) scene = g; }}>{element}</group>); });+ if (!scene) throw new Error("the element did not mount");+ return scene;+}++afterEach(() => {+ root?.unmount();+ root = null;+ scene = null;+});++/** The merged meshes a figure is drawn with right now; a bake replaces every one of them. */+function merged(node: Object3D): Mesh[] {+ const out: Mesh[] = [];+ node.traverse((child) => { if ((child as Mesh).isMesh && child.userData.staticBatched && child.visible) out.push(child as Mesh); });+ return out;+}++const REWARDS: RewardRow[] = [+ { rewardId: "decoration_ribbon_bar", slot: "decoration", levels: { person: 3, agent: 3, pet: null } },+ { rewardId: "headwear_patrol_cap", slot: "headwear", levels: { person: 7, agent: null, pet: null } },+];+const BANDS = [{ level: 1, title: "private" }, { level: 2, title: "private_second_class" }, { level: 4, title: "private_first_class" }];++/** A snapshot as the server sends it: parsed afresh every time, so no array in it is ever the same object twice. */+function snapshot(level: number, xp: number): ProgressionSnapshot {+ return {+ subjects: [{ subjectId: PERSON_SUBJECT, kind: "person", xp, level, xpIntoLevel: 0, xpForNext: 90, title: "private_first_class" }],+ petId: "ember", recent: [], latestSeq: 0, maxLevel: 50, levelXp: [0, 40, 105, 195, 310, 450, 600, 760], rules: [],+ rewards: REWARDS.map((row) => ({ ...row, levels: { ...row.levels } })),+ titles: { person: BANDS.map((b) => ({ ...b })), agent: BANDS.map((b) => ({ ...b })), pet: BANDS.map((b) => ({ ...b })) },+ looks: { cap: 1, suit: 4, crown: 10 },+ };+}++const still = { current: { mode: "idle" as const, speed: 0 } };+const look = playerLook(loadProfile());++describe("a dressed figure", () => {+ it("does not bake its parts again when the level store takes an equal snapshot, and does when it wears something new", async () => {+ const seen: FigureRegalia[] = [];+ function Dressed() {+ const dressed = useDressedFigure("person", PERSON_SUBJECT, look);+ seen.push(dressed.regalia);+ return <ToyFigure look={dressed.look} regalia={dressed.regalia} drive={still} paused />;+ }+ useProgression.getState().hydrate(snapshot(4, 200), []);+ const figure = await render(<Dressed />);+ const first = merged(figure);+ expect(first.length).toBeGreaterThan(4);+ expect(seen[seen.length - 1].chest).toBeTruthy();++ // The minute's re-read: the same levels and rewards in new objects.+ await act(async () => { useProgression.getState().hydrate(snapshot(4, 200), []); });+ // The regalia are new JSX (which is what made the figure bake again)...+ expect(seen[seen.length - 1].chest).not.toBe(seen[0].chest);+ // ...with the same content, so every merged mesh is still the one from before.+ expect(merged(figure)).toHaveLength(first.length);+ expect(merged(figure).every((mesh, i) => mesh === first[i])).toBe(true);++ // A new rank and a cap: now the figure is baked again.+ await act(async () => { useProgression.getState().hydrate(snapshot(7, 700), []); });+ expect(seen[seen.length - 1].hat).toBeTruthy();+ const dressedAnew = merged(figure);+ expect(dressedAnew.some((mesh) => first.includes(mesh))).toBe(false);+ });++ it("names what is worn by its content, not by the JSX object", () => {+ const a = regaliaFor("private_first_class", { decoration: "decoration_ribbon_bar", headwear: "headwear_patrol_cap" });+ const b = regaliaFor("private_first_class", { decoration: "decoration_ribbon_bar", headwear: "headwear_patrol_cap" });+ expect(a.hat).not.toBe(b.hat);+ expect(contentKey([a.hat, a.chest, a.shoulder, a.sleeve])).toBe(contentKey([b.hat, b.chest, b.shoulder, b.sleeve]));+ const bare = regaliaFor("private_first_class", { decoration: "decoration_ribbon_bar" });+ expect(contentKey([bare.hat, bare.chest])).not.toBe(contentKey([a.hat, a.chest]));+ const other = regaliaFor("private", { decoration: "decoration_ribbon_bar", headwear: "headwear_patrol_cap" });+ expect(contentKey([other.hat, other.sleeve, other.shoulder])).not.toBe(contentKey([a.hat, a.sleeve, a.shoulder]));+ // Nothing worn has an empty name, whatever shape "nothing" takes.+ expect(contentKey([undefined, null, false])).toBe(contentKey([undefined, undefined, undefined]));+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/ToyFigure.tsx b/jarvis/ui/web/frontend/src/components/society/office/ToyFigure.tsxindex 0f1bc52749..6e0eb72905 100644--- a/jarvis/ui/web/frontend/src/components/society/office/ToyFigure.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/ToyFigure.tsx@@ -11,8 +11,9 @@* singletons and materials are cached by colour, so twenty figures share them;* the frame loop allocates nothing.*/-import { type ReactNode, useMemo, useRef, type MutableRefObject } from "react";+import { isValidElement, type ReactNode, useMemo, useRef, type MutableRefObject } from "react";import { useFrame } from "@react-three/fiber";+import { StaticBatch } from "./StaticBatch";import {BoxGeometry, CapsuleGeometry, Color, ConeGeometry, CylinderGeometry, MeshBasicMaterial, MeshStandardMaterial,SphereGeometry, TorusGeometry, type Group,@@ -32,32 +33,34 @@ const HD = TOY.head;/** The forearm tapers a little below the upper arm towards the wrist. */const FORE_RADIUS = TOY.armRadius - 0.006;+// Tessellation is sized for a figure a few centimetres tall on screen: a floor of forty figures draws each of+// these shapes forty times, twice with the shadow pass.const GEO = {- sphere: new SphereGeometry(1, 40, 28),+ sphere: new SphereGeometry(1, 28, 18),lowSphere: new SphereGeometry(1, 16, 12),/** Upper half of a sphere, reaching slightly past the equator: hair caps and hats. */- dome: new SphereGeometry(1, 40, 18, 0, Math.PI * 2, 0, Math.PI * 0.56),- pelvis: new RoundedBoxGeometry(TOY.pelvis.w, TOY.pelvis.h, TOY.pelvis.d, 3, 0.05),- chest: new RoundedBoxGeometry(TOY.torso.w, TOY.torso.h - 0.02, TOY.torso.d, 3, 0.08),+ dome: new SphereGeometry(1, 28, 12, 0, Math.PI * 2, 0, Math.PI * 0.56),+ pelvis: new RoundedBoxGeometry(TOY.pelvis.w, TOY.pelvis.h, TOY.pelvis.d, 2, 0.05),+ chest: new RoundedBoxGeometry(TOY.torso.w, TOY.torso.h - 0.02, TOY.torso.d, 2, 0.08),thigh: new CapsuleGeometry(TOY.legRadius, 0.12, 4, 10),shin: new CapsuleGeometry(0.056, 0.1, 4, 10),// Each limb capsule overshoots its joint, so the rounded ends overlap into a closed elbow at any bend.- upperArm: new CapsuleGeometry(TOY.armRadius, TOY.upperArm - 0.04, 6, 16),- foreArm: new CapsuleGeometry(FORE_RADIUS, TOY.foreArm - 0.05, 6, 16),+ upperArm: new CapsuleGeometry(TOY.armRadius, TOY.upperArm - 0.04, 4, 12),+ foreArm: new CapsuleGeometry(FORE_RADIUS, TOY.foreArm - 0.05, 4, 12),/** A short T-shirt sleeve, slightly flared, hanging from the shoulder cap. */- sleeve: new CylinderGeometry(TOY.armRadius + 0.011, TOY.armRadius + 0.016, 0.075, 24),- cuff: new CylinderGeometry(FORE_RADIUS + 0.007, FORE_RADIUS + 0.007, 0.024, 24),- shoe: new RoundedBoxGeometry(0.13, 0.075, TOY.heel + TOY.toe + 0.01, 3, 0.034),+ sleeve: new CylinderGeometry(TOY.armRadius + 0.011, TOY.armRadius + 0.016, 0.075, 16),+ cuff: new CylinderGeometry(FORE_RADIUS + 0.007, FORE_RADIUS + 0.007, 0.024, 16),+ shoe: new RoundedBoxGeometry(0.13, 0.075, TOY.heel + TOY.toe + 0.01, 2, 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),/** A band of hair around the back and sides, from just above the equator down: the hair a hat leaves visible. */- hairBand: new SphereGeometry(1, 40, 14, Math.PI * 0.92, Math.PI * 1.16, Math.PI * 0.46, Math.PI * 0.3),+ hairBand: new SphereGeometry(1, 28, 10, Math.PI * 0.92, Math.PI * 1.16, Math.PI * 0.46, Math.PI * 0.3),/** A unit triangular pyramid, one flat face towards +z, tip up: a jacket's V-opening (scaled, turned tip down). */wedge: new ConeGeometry(1, 1, 3, 1, false, Math.PI),box: new BoxGeometry(1, 1, 1),- collar: new CylinderGeometry(0.085, 0.097, 1, 24),+ collar: new CylinderGeometry(0.085, 0.097, 1, 16),pocket: new RoundedBoxGeometry(0.2, 0.07, 0.02, 2, 0.01),lens: new TorusGeometry(0.047, 0.008, 8, 24),};@@ -139,7 +142,7 @@ function Face({ look }: { look: ToyLook }) {);})}{[-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 />+ <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]} />))}</group>);@@ -416,11 +419,11 @@ function OutfitDetails({ look }: { look: ToyLook }) {</group>);case "turtleneck":- return <mesh geometry={GEO.collar} material={garment(look, look.shirt)} position={[0, 0.29, 0]} scale={[1, 0.075, 1]} castShadow />;+ return <mesh geometry={GEO.collar} material={garment(look, look.shirt)} position={[0, 0.29, 0]} scale={[1, 0.075, 1]} />;case "quarterzip":return (<group>- <mesh geometry={GEO.collar} material={garment(look, look.shirt)} position={[0, 0.285, 0]} scale={[1.04, 0.055, 1.04]} castShadow />+ <mesh geometry={GEO.collar} material={garment(look, look.shirt)} position={[0, 0.285, 0]} scale={[1.04, 0.055, 1.04]} /><mesh geometry={GEO.box} material={METAL} position={[0, 0.25, FRONT - 0.01]} rotation={[-0.45, 0, 0]} scale={[0.008, 0.09, 0.01]} /><mesh geometry={GEO.box} material={METAL} position={[0.012, 0.21, FRONT + 0.004]} scale={[0.012, 0.022, 0.006]} /></group>@@ -429,7 +432,7 @@ function OutfitDetails({ look }: { look: ToyLook }) {return (<group>{/* The hood lies folded behind the neck. */}- <mesh geometry={GEO.sphere} material={garment(look, look.shirt)} position={[0, 0.275, -0.07]} scale={[0.15, 0.065, 0.085]} castShadow />+ <mesh geometry={GEO.sphere} material={garment(look, look.shirt)} position={[0, 0.275, -0.07]} scale={[0.15, 0.065, 0.085]} />{[-1, 1].map((sx) => (<mesh key={sx} geometry={GEO.box} material={accent} position={[sx * 0.035, 0.22, FRONT - 0.002]} rotation={[-0.3, 0, 0]} scale={[0.009, 0.075, 0.009]} />))}@@ -484,7 +487,7 @@ function UniformDetails({ look, u }: { look: ToyLook; u: UniformStyle }) {case "field":return (<group>- <mesh geometry={GEO.collar} material={garment(look, u.coat)} position={[0, 0.287, 0]} scale={[1.05, 0.06, 1.05]} castShadow />+ <mesh geometry={GEO.collar} material={garment(look, u.coat)} position={[0, 0.287, 0]} scale={[1.05, 0.06, 1.05]} /><mesh geometry={GEO.box} material={garment(look, mix(u.coat, "#000000", 0.1))} position={[0.008, 0.15, FRONT + 0.004]} scale={[0.026, 0.25, 0.008]} />{Array.from({ length: 4 }, (_, i) => (<mesh key={i} geometry={GEO.lowSphere} material={metal} position={[0.008, 0.23 - i * 0.055, FRONT + 0.009]} scale={[0.007, 0.007, 0.004]} />@@ -564,8 +567,10 @@ type JointRef = MutableRefObject<Group | null>;* sleeve over a bare arm; every other outfit has long sleeves ending in a cuff* at the wrist (a vest shows the shirt's sleeves, a suit the shirt cuff).*/-function Arm({ side, look, shoulder, elbow, holding, sleeve }: {+function Arm({ side, look, shoulder, elbow, holding, sleeve, rigidKey }: {side: 1 | -1; look: ToyLook; shoulder: JointRef; elbow: JointRef; holding?: ReactNode; sleeve?: ReactNode;+ /** Names the look and what is worn: each rigid half of the arm is baked again when it changes. */+ rigidKey: string;}) {const skin = matte(look.skin);const sleeveColour = look.outfit === "vest" && !look.uniform ? look.inner : look.shirt;@@ -578,18 +583,24 @@ function Arm({ side, look, shoulder, elbow, holding, sleeve }: {const hand = -TOY.foreArm - 0.006;return (<group ref={shoulder} position={[side * TOY.shoulderX, TOY.shoulderY, 0]}>- {/* Shoulder cap, pulled in towards the chest so it rounds off the torso's corner instead of perching on it. */}- <mesh geometry={GEO.sphere} material={cloth} position={[-side * 0.008, -0.004, 0]} scale={[TOY.armRadius + 0.012, TOY.armRadius + 0.008, TOY.armRadius + 0.012]} castShadow />- {!long && <mesh geometry={GEO.sleeve} material={cloth} position={[0, -0.045, 0]} castShadow />}- <mesh geometry={GEO.upperArm} material={long ? cloth : skin} position={[0, -TOY.upperArm / 2, 0]} castShadow />- {/* A rank patch on the outer face of the upper sleeve, bent round the arm. */}- {sleeve && <group position={[side * (TOY.armRadius + 0.001), -0.088, 0]} rotation={[0, side * Math.PI / 2, 0]}>{sleeve}</group>}+ {/* Each half of the arm is rigid between its joints, so it is drawn merged, in the joint's own frame. */}+ <StaticBatch signature={rigidKey} castAsOne>+ {/* Shoulder cap, pulled in towards the chest so it rounds off the torso's corner instead of perching on it. */}+ <mesh geometry={GEO.sphere} material={cloth} position={[-side * 0.008, -0.004, 0]} scale={[TOY.armRadius + 0.012, TOY.armRadius + 0.008, TOY.armRadius + 0.012]} castShadow />+ {!long && <mesh geometry={GEO.sleeve} material={cloth} position={[0, -0.045, 0]} />}+ <mesh geometry={GEO.upperArm} material={long ? cloth : skin} position={[0, -TOY.upperArm / 2, 0]} castShadow />+ {/* A rank patch on the outer face of the upper sleeve, bent round the arm. */}+ {sleeve && <group position={[side * (TOY.armRadius + 0.001), -0.088, 0]} rotation={[0, side * Math.PI / 2, 0]}>{sleeve}</group>}+ </StaticBatch><group ref={elbow} position={[0, -TOY.upperArm, 0]}>- <mesh geometry={GEO.foreArm} material={long ? cloth : skin} position={[0, -TOY.foreArm / 2 + 0.01, 0]} castShadow />- {long && <mesh geometry={GEO.cuff} material={cuff} position={[0, hand + 0.052, 0]} />}- {/* Mitten hand: a soft paddle, palm turned towards the body, with a thumb pointing forward. */}- <mesh geometry={GEO.sphere} material={skin} position={[0, hand, 0.004]} scale={[TOY.handRadius * 0.82, TOY.handRadius * 1.08, TOY.handRadius * 0.95]} castShadow />- <mesh geometry={GEO.lowSphere} material={skin} position={[-side * 0.03, hand + 0.018, 0.034]} rotation={[0.5, 0, side * 0.45]} scale={[0.02, 0.03, 0.02]} castShadow />+ <StaticBatch signature={rigidKey} castAsOne>+ <mesh geometry={GEO.foreArm} material={long ? cloth : skin} position={[0, -TOY.foreArm / 2 + 0.01, 0]} castShadow />+ {long && <mesh geometry={GEO.cuff} material={cuff} position={[0, hand + 0.052, 0]} />}+ {/* Mitten hand: a soft paddle, palm turned towards the body, with a thumb pointing forward. */}+ <mesh geometry={GEO.sphere} material={skin} position={[0, hand, 0.004]} scale={[TOY.handRadius * 0.82, TOY.handRadius * 1.08, TOY.handRadius * 0.95]} castShadow />+ <mesh geometry={GEO.lowSphere} material={skin} position={[-side * 0.03, hand + 0.018, 0.034]} rotation={[0.5, 0, side * 0.45]} scale={[0.02, 0.03, 0.02]} />+ </StaticBatch>+ {/* Whatever the hand holds comes and goes, so it stays a part of its own. */}{holding && <group position={[0, hand - 0.01, 0.03]}>{holding}</group>}</group></group>@@ -611,7 +622,7 @@ function Leg({ side, look, hip, knee, ankle }: { side: 1 | -1; look: ToyLook; hi{stripe && <mesh geometry={GEO.box} material={stripe} position={[side * 0.054, -TOY.shin / 2 + 0.005, 0]} scale={[0.006, TOY.shin + 0.04, 0.018]} />}<group ref={ankle} position={[0, -TOY.shin, 0]}><mesh geometry={GEO.shoe} material={matte(look.shoes, dress ? 0.3 : 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 />+ <mesh geometry={GEO.sole} material={sole} position={[0, -TOY.sole + 0.011, (TOY.toe - TOY.heel) / 2]} /></group></group></group>@@ -657,6 +668,42 @@ export interface FigureRegalia {hat?: ReactNode;}+const identities = new WeakMap<object, number>();+let lastIdentity = 0;+/** A number for an object that has no content to name it by (a component, a material): the same object, the same number. */+function identityOf(value: object): number {+ let id = identities.get(value);+ if (id === undefined) {+ lastIdentity += 1;+ id = lastIdentity;+ identities.set(value, id);+ }+ return id;+}++/**+ * A name for what a piece of JSX draws, by content: its element types, keys+ * and props all the way down. Two renders of the same regalia are new objects+ * with the same name, so the figure's merged parts are not baked again for+ * them. Components, functions and class instances (materials, geometries)+ * count as themselves.+ */+export function contentKey(node: unknown, depth = 0): string {+ if (node === null || node === undefined || typeof node === "boolean") return "";+ if (typeof node !== "object" && typeof node !== "function") return String(node);+ if (typeof node === "function" || depth > 16) return `@${identityOf(node)}`;+ if (Array.isArray(node)) return `[${node.map((item) => contentKey(item, depth + 1)).join(",")}]`;+ if (isValidElement(node)) {+ const type: unknown = node.type;+ const name = typeof type === "string" ? type : typeof type === "symbol" ? String(type) : `@${identityOf(type as object)}`;+ return `<${name}${node.key === null ? "" : `#${node.key}`} ${contentKey(node.props, depth + 1)}>`;+ }+ const proto: unknown = Object.getPrototypeOf(node);+ if (proto !== Object.prototype && proto !== null) return `@${identityOf(node)}`;+ const record = node as Record<string, unknown>;+ return `{${Object.keys(record).sort().map((key) => `${key}:${contentKey(record[key], depth + 1)}`).join(",")}}`;+}+/** Where a shoulder piece rests on the torso: over the shoulder cap, sloping down outward. */const SHOULDER_REST = { x: 0.15, y: 0.288, slope: 0.22 };@@ -678,6 +725,15 @@ export function ToyFigure({ look, drive, paused, heightM = TOY_HEIGHT, seatHeighconst lAnkle = useRef<Group>(null);const rAnkle = useRef<Group>(null);+ // The head, the torso and each half of an arm are rigid: everything on them (face, hair, hat, collar, pockets,+ // insignia, sleeve, cuff, hand) is drawn as a few merged meshes instead of three dozen, and baked again whenever+ // the look or what is worn changes. What is worn is named by its content: the level store hands out new JSX for+ // the same regalia with every snapshot it reads, and that must not bake every dressed figure again.+ const lookKey = useMemo(() => JSON.stringify(look), [look]);+ const hat = regalia?.hat, chest = regalia?.chest, shoulder = regalia?.shoulder, sleeve = regalia?.sleeve;+ const wornKey = useMemo(() => contentKey([hat, chest, shoulder, sleeve]), [hat, chest, shoulder, sleeve]);+ const rigidKey = `${lookKey}#${wornKey}#${mannequin ? 1 : 0}`;+const state = useMemo(() => ({time: Math.random() * 10, // desynchronise idle loops between figuresphase: 0,@@ -753,23 +809,27 @@ export function ToyFigure({ look, drive, paused, heightM = TOY_HEIGHT, seatHeigh<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={garment(look, look.shirt)} position={[0, 0.02 + (TOY.torso.h - 0.02) / 2, 0]} castShadow />- {look.uniform ? <UniformDetails look={look} u={look.uniform} /> : <OutfitDetails look={look} />}- <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} sleeve={regalia?.sleeve} />- <Arm side={-1} look={look} shoulder={rShoulder} elbow={rElbow} holding={holding} sleeve={regalia?.sleeve} />- {regalia?.shoulder && ([1, -1] as const).map((side) => (- <group key={side} position={[side * SHOULDER_REST.x, SHOULDER_REST.y, 0]} rotation={[0, side === 1 ? 0 : Math.PI, -SHOULDER_REST.slope]}>- {regalia.shoulder}- </group>- ))}- {regalia?.chest}+ <StaticBatch signature={rigidKey}>+ <mesh geometry={GEO.chest} material={garment(look, look.shirt)} position={[0, 0.02 + (TOY.torso.h - 0.02) / 2, 0]} castShadow />+ {look.uniform ? <UniformDetails look={look} u={look.uniform} /> : <OutfitDetails look={look} />}+ <mesh geometry={GEO.lowSphere} material={matte(look.skin)} position={[0, TOY.neckY - 0.01, 0]} scale={[0.07, 0.04, 0.07]} />+ {regalia?.shoulder && ([1, -1] as const).map((side) => (+ <group key={side} position={[side * SHOULDER_REST.x, SHOULDER_REST.y, 0]} rotation={[0, side === 1 ? 0 : Math.PI, -SHOULDER_REST.slope]}>+ {regalia.shoulder}+ </group>+ ))}+ {regalia?.chest}+ </StaticBatch>+ <Arm side={1} look={look} shoulder={lShoulder} elbow={lElbow} sleeve={regalia?.sleeve} rigidKey={rigidKey} />+ <Arm side={-1} look={look} shoulder={rShoulder} elbow={rElbow} holding={holding} sleeve={regalia?.sleeve} rigidKey={rigidKey} /><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 />- {!mannequin && <Face look={look} />}- {!mannequin && <Eyewear look={look} />}- {mannequin ? null : regalia?.hat ? <HairUnderHat color={look.hair} /> : <Hair style={look.hairStyle} look={look} />}- {regalia?.hat}+ <StaticBatch signature={rigidKey}>+ <mesh geometry={GEO.sphere} material={matte(look.skin)} position={[0, HD.y, 0]} scale={[HD.rx, HD.ry, HD.rz]} castShadow />+ {!mannequin && <Face look={look} />}+ {!mannequin && <Eyewear look={look} />}+ {mannequin ? null : regalia?.hat ? <HairUnderHat color={look.hair} /> : <Hair style={look.hairStyle} look={look} />}+ {regalia?.hat}+ </StaticBatch></group></group></group>diff --git a/jarvis/ui/web/frontend/src/components/society/office/WardrobePanel.tsx b/jarvis/ui/web/frontend/src/components/society/office/WardrobePanel.tsxindex be59e83e49..574b21f84b 100644--- a/jarvis/ui/web/frontend/src/components/society/office/WardrobePanel.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/WardrobePanel.tsx@@ -1,5 +1,5 @@/**- * The wardrobe checkpoint: dress your own character or any agent on foot —+ * The wardrobe mirror: dress your own character or any agent on foot —* office outfits in curated colourways, hair style and colour, skin tone and* eyewear. Your own look saves in this browser at once; an agent's look is a* draft with a live preview until you save it to the roster (the same@@ -8,6 +8,8 @@import { lazy, Suspense, useId, useMemo, useState, type ReactNode } from "react";import { useQueryClient } from "@tanstack/react-query";import { useT } from "@/i18n";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";import type { SocietyAgent } from "../data";import type { FigureRecipe } from "../figures/figureRecipe";import { playerLook, playerRecipe, type PlayerProfile } from "./playerProfile";@@ -146,7 +148,6 @@ export function WardrobePanel({ profile, onProfile, agents, sample }: {return (<>- <p>{t("society.office.wardrobe_body")}</p>{people.length > 0 && (<Section label={t("society.office.wardrobe_who")}><button type="button" className="office-chip" aria-pressed={target === YOU} onClick={() => { setTarget(YOU); setStatus("idle"); }}>@@ -165,22 +166,22 @@ export function WardrobePanel({ profile, onProfile, agents, sample }: {<Suspense fallback={null}><AgentFigureViewer recipe={recipe} quiet /></Suspense></div>) : (- <label className="office-field">- <span>{t("society.office.wardrobe_name")}</span>- <input value={profile.name} maxLength={40} placeholder={t("society.office.you")} autoComplete="off" spellCheck={false}+ <label className="grid gap-1 text-sm font-medium">+ {t("society.office.wardrobe_name")}+ <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>+ <span className="text-xs font-normal text-muted-foreground">{t("society.office.wardrobe_saved")}</span></label>)}<LookEditor recipe={recipe} onChange={change} />- <button type="button" className="office-action" onClick={() => change(randomLook(recipe, `${target}:${Math.random()}`))}>+ <Button type="button" size="sm" variant="outline" onClick={() => change(randomLook(recipe, `${target}:${Math.random()}`))}>{t("society.office.wardrobe_random")}- </button>+ </Button>{agent && (<>- <button type="button" className="office-action office-action-primary" disabled={!dirty || saving || sample} aria-busy={saving} onClick={() => void save()}>+ <Button type="button" size="sm" disabled={!dirty || saving || sample} aria-busy={saving} onClick={() => void save()}>{t(saving ? "society.card.saving" : "society.office.wardrobe_save_agent").replace("{0}", agent.name)}- </button>+ </Button>{sample && <p className="office-hint">{t("society.office.wardrobe_sample_hint")}</p>}{status === "saved" && <p className="office-success" role="status">{t("society.office.wardrobe_saved_agent").replace("{0}", agent.name)}</p>}{status === "error" && <p className="office-error" role="alert">{t("society.office.wardrobe_save_error")}</p>}diff --git a/jarvis/ui/web/frontend/src/components/society/office/WardrobeRoom.tsx b/jarvis/ui/web/frontend/src/components/society/office/WardrobeRoom.tsxindex 358a8eb5e3..cb99ef5496 100644--- a/jarvis/ui/web/frontend/src/components/society/office/WardrobeRoom.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/WardrobeRoom.tsx@@ -36,7 +36,7 @@ const C = {linen: "#e8dfcf",sage: "#8d9f86",velvet: "#7e9378",- brass: "#c9a25a",+ brass: "#b08d5c",led: "#ffe2bd",bulb: "#fff0d2",} as const;diff --git a/jarvis/ui/web/frontend/src/components/society/office/agentFace.css b/jarvis/ui/web/frontend/src/components/society/office/agentFace.cssnew file mode 100644index 0000000000..9ec5db255f--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/agentFace.css@@ -0,0 +1,6 @@+/* An agent's face on a neutral tile (AgentFace.tsx). Theme tokens only: the tile is one step off the dialog's+ ground in either theme, with a hairline rim. */+.office-face { display:inline-flex; flex:none; align-items:center; justify-content:center; border-radius:50%; background:hsl(var(--surface-raised)); box-shadow:inset 0 0 0 1px hsl(var(--border-strong) / .7); }+/* A hairline in the text colour round the symbol's own outline: dark round a white symbol in light mode, light+ round a black one in dark mode. Two passes make a line of it instead of a haze. */+.office-face > * { filter:drop-shadow(0 0 .5px hsl(var(--foreground) / .55)) drop-shadow(0 0 .5px hsl(var(--foreground) / .35)); }diff --git a/jarvis/ui/web/frontend/src/components/society/office/agentsAmbience.test.ts b/jarvis/ui/web/frontend/src/components/society/office/agentsAmbience.test.tsindex 05d8e0e147..283659fc4b 100644--- a/jarvis/ui/web/frontend/src/components/society/office/agentsAmbience.test.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/agentsAmbience.test.ts@@ -1,64 +1,181 @@import { describe, expect, it } from "vitest";import { agentsRug, AGENTS_RUGS } from "./AgentsFloorLook";-import { agentsAmbience } from "./agentsAmbience";-import { buildOfficeLayout, type OfficeAgentInput, type Rect } from "./officeLayout";-import { CODING_STUDIOS } from "./officePalette";+import {+ ambienceObstacles, bench, BENCH_DEPTH, BENCH_H, benchSeats, booth, BOOTH, boothPlace, counter, counterStands, highTable, HIGH_TABLE,+ olive, OLIVE_BOX, OLIVE_H, ownSize, planter, PLANTER_H, screen, SCREEN, sofa, SOFA, sofaSeats, steps, STEPS, stepsSeats, tableStands,+ toFloor, tree, TREE_BOX, yawOf,+} from "./agentsAmbience";+import { buildOfficeLayout, type OfficeAgentInput } from "./officeLayout";+import { CODING_STUDIOS, DEPARTMENT_ZONES } from "./officePalette";const agent = (id: string, provider: string): OfficeAgentInput => ({agentId: id, name: id, tier: "specialist", providerLabel: provider, state: "working", createdMs: 0,});+const near = (a: number, b: number) => expect(a).toBeCloseTo(b, 9);-const overlaps = (a: Rect, b: Rect) => a.minX < b.maxX && a.maxX > b.minX && a.minZ < b.maxZ && a.maxZ > b.minZ;+describe("agents floor fittings as data", () => {+ it("builds trees, benches and planters as boxes on the floor plan", () => {+ const pot = olive("t", 2, -3);+ expect([pot.kind, pot.h]).toEqual(["olive", OLIVE_H]);+ near(pot.maxX - pot.minX, OLIVE_BOX);+ near(pot.maxZ - pot.minZ, OLIVE_BOX);+ expect([(pot.minX + pot.maxX) / 2, (pot.minZ + pot.maxZ) / 2]).toEqual([2, -3]);+ const big = tree("b", 0, 0);+ near(big.maxX - big.minX, TREE_BOX);+ expect(big.h).toBeGreaterThan(pot.h);+ // A bench runs north-south whichever end is named first, and faces east or west.+ const seat = bench("b", 5, 4, 1, "west");+ expect([seat.kind, seat.facing, seat.h]).toEqual(["bench", "west", BENCH_H]);+ expect([seat.minZ, seat.maxZ]).toEqual([1, 4]);+ near(seat.maxX - seat.minX, BENCH_DEPTH);+ expect(benchSeats(seat).map((p) => p.z)).toEqual([1.75, 3.25]);+ near(benchSeats(seat)[0].facing, -Math.PI / 2);+ const box = planter("p", { minX: 0, maxX: 3, minZ: 1, maxZ: 1.34 });+ expect([box.kind, box.h, box.minX, box.maxX, box.minZ, box.maxZ]).toEqual(["planter", PLANTER_H, 0, 3, 1, 1.34]);+ // A screen is a thin box along its line, north-south or east-west, and may wear a studio's colour.+ const line = screen("s", 4, 1, 4, 7, 3);+ near(line.maxX - line.minX, SCREEN.t);+ near(line.maxZ - line.minZ, 6 + SCREEN.t);+ expect(line.tint).toBe(3);+ expect("tint" in screen("n", 0, 0, 5, 0)).toBe(false);+ });++ it("turns a piece's footprint with the way it faces, and finds its own frame on the floor", () => {+ for (const facing of ["north", "south"] as const) {+ const piece = sofa("s", 10, 20, facing);+ near(piece.maxX - piece.minX, SOFA.w);+ near(piece.maxZ - piece.minZ, SOFA.d);+ }+ for (const facing of ["east", "west"] as const) {+ const piece = sofa("s", 10, 20, facing);+ near(piece.maxX - piece.minX, SOFA.d);+ near(piece.maxZ - piece.minZ, SOFA.w);+ expect(ownSize(piece).w).toBeCloseTo(SOFA.w, 9);+ }+ // Local +z is the front: one metre in front of an east-facing piece is one metre east of it.+ const east = sofa("e", 10, 20, "east"), north = sofa("n", 10, 20, "north");+ near(toFloor(east, 0, 1).x, 11);+ near(toFloor(east, 0, 1).z, 20);+ near(toFloor(north, 0, 1).z, 19);+ // Local +x is the piece's own right-hand side seen from behind it: south of an east-facing piece's middle is -x.+ near(toFloor(east, 1, 0).z, 19);+ expect(yawOf("south")).toBe(0);+ near(yawOf("west"), -Math.PI / 2);+ });++ it("gives every piece the places people use it from", () => {+ // Two seats on a sofa, side by side, looking the way it faces.+ const couch = sofa("s", 0, 0, "east");+ const seats = sofaSeats(couch);+ expect(seats).toHaveLength(2);+ for (const seat of seats) {+ expect(seat.x > couch.minX && seat.x < couch.maxX && seat.z > couch.minZ && seat.z < couch.maxZ).toBe(true);+ near(seat.facing, Math.PI / 2);+ }+ near(Math.abs(seats[0].z - seats[1].z), 0.9);+ // Standing places round a table look at it from just outside its top.+ const table = highTable("t", 3, 3);+ for (const stand of tableStands(table, [0, Math.PI / 2, Math.PI])) {+ const d = Math.hypot(stand.x - 3, stand.z - 3);+ expect(d).toBeGreaterThan(HIGH_TABLE.r + 0.3);+ expect(d).toBeLessThan(HIGH_TABLE.r + 0.6);+ near(stand.x + Math.sin(stand.facing) * d, 3);+ near(stand.z + Math.cos(stand.facing) * d, 3);+ }+ // Step seating seats people on its lowest tier, at its front, looking out.+ const flight = steps("f", 0, 0, 5, "east");+ near(flight.maxX - flight.minX, STEPS.d);+ near(flight.maxZ - flight.minZ, 5);+ const tier = stepsSeats(flight);+ expect(tier.length).toBeGreaterThanOrEqual(4);+ for (const seat of tier) {+ near(seat.x, flight.maxX - STEPS.tier / 2);+ near(seat.facing, Math.PI / 2);+ }+ // In front of a counter, facing it.+ const run = counter("c", 0, 0, 4, "east");+ for (const stand of counterStands(run, [-1, 1])) {+ expect(stand.x).toBeGreaterThan(run.maxX + 0.4);+ near(Math.sin(stand.facing), -1);+ }+ });-describe("agents floor ambience", () => {+ it("makes a focus booth three walls and an open front, so a person stands inside it", () => {+ const box = booth("b", 0, 0, "south", 1);+ const walls = ambienceObstacles(box);+ expect(walls).toHaveLength(3);+ const blocked = (x: number, z: number) => walls.some((w) => x >= w.minX && x <= w.maxX && z >= w.minZ && z <= w.maxZ);+ // The back (north) and both sides are solid; the middle and the front (south) are not.+ expect(blocked(0, -BOOTH.d / 2 + 0.02)).toBe(true);+ expect(blocked(-BOOTH.w / 2 + 0.02, 0)).toBe(true);+ expect(blocked(BOOTH.w / 2 - 0.02, 0)).toBe(true);+ expect(blocked(0, 0)).toBe(false);+ expect(blocked(0, BOOTH.d / 2 - 0.02)).toBe(false);+ const inside = boothPlace(box);+ expect(blocked(inside.x, inside.z)).toBe(false);+ // The person looks at the shelf on the back wall.+ near(Math.cos(inside.facing), -1);+ // Turned east, the open side is the east one.+ const turned = ambienceObstacles(booth("b", 0, 0, "east"));+ expect(turned.some((w) => w.maxX >= BOOTH.d / 2 - 1e-9 && w.minZ < 0 && w.maxZ > 0)).toBe(false);+ // Every other piece is simply its footprint.+ const couch = sofa("s", 1, 2, "north");+ expect(ambienceObstacles(couch)).toEqual([{ minX: couch.minX, maxX: couch.maxX, minZ: couch.minZ, maxZ: couch.maxZ }]);+ });+});++describe("agents floor fittings on the campus", () => {for (const count of [0, 12, 40]) {- const layout = buildOfficeLayout(Array.from({ length: count }, (_, i) => agent(`a${i}`, `P${i % 5}`)));- const items = agentsAmbience(layout);+ const layout = buildOfficeLayout(Array.from({ length: count }, (_, i) => agent(`a${i}`, `P${i % 5}`)), {+ teams: count > 0 ? [{ id: "t", name: "T", createdMs: 1, members: ["a1", "a2", "a3", "a4", "a5"] }] : [],+ });+ const items = layout.ambience!;- it(`stands in the window strip, clear of every department, room and the railing (${count} agents)`, () => {- for (const kind of ["olive", "bench", "planter"] as const) expect(items.some((i) => i.kind === kind), kind).toBe(true);- for (const item of items) {- for (const area of [...layout.departments, ...layout.rooms]) expect(overlaps(item, area), item.id).toBe(false);- // The railing's base is 8 cm wide on a line 0.2 m in from the slab edge.- expect(item.minX, item.id).toBeGreaterThan(layout.bounds.minX + 0.24);- expect(item.maxX, item.id).toBeLessThan(layout.bounds.maxX - 0.24);+ it(`furnishes the atrium, the commons, every studio and the windows (${count} agents)`, () => {+ const has = (prefix: string, kind: string) => items.some((i) => i.id.startsWith(prefix) && i.kind === kind);+ expect(has("atrium-steps-west", "steps") && has("atrium-steps-east", "steps") && has("atrium-tree-", "tree")).toBe(true);+ expect(has("median-west", "planter") && has("median-east-olive", "olive") && has("median-west-table", "hightable")).toBe(true);+ expect(has("booth-", "booth") && has("booths-sofa", "sofa") && has("library-sofa", "sofa")).toBe(true);+ expect(has("cafe-counter", "counter") && has("cafe-island", "island") && has("cafe-table-", "hightable") && has("cafe-sofa-", "sofa")).toBe(true);+ expect(has("olive-west-0", "olive") && has("olive-east-0", "olive")).toBe(true);+ // Every studio: screens, planted front, cabinet, sofa, standing table.+ for (const dept of layout.departments) {+ const mine = (part: string) => items.find((i) => i.id === `${dept.id}-${part}`);+ expect([mine("front-w")?.kind, mine("front-e")?.kind, mine("cabinet")?.kind, mine("sofa")?.kind, mine("table")?.kind, mine("screen-e")?.kind])+ .toEqual(["planter", "planter", "cabinet", "sofa", "hightable", "screen"]);+ // The front planters leave the entrance between them.+ expect(mine("front-e")!.minX - mine("front-w")!.maxX).toBeGreaterThan(4);}});- it(`is solid in the layout and leaves every window spot free (${count} agents)`, () => {- for (const item of items) {- expect(layout.obstacles.some((o) => o.minX === item.minX && o.maxZ === item.maxZ), item.id).toBe(true);- }- for (const spot of layout.spots.filter((s) => s.kind === "window")) {- expect(items.some((i) => spot.x >= i.minX - 0.3 && spot.x <= i.maxX + 0.3 && spot.z >= i.minZ - 0.3 && spot.z <= i.maxZ + 0.3), spot.id).toBe(false);- }+ it(`puts a bench and a planter beside each window, swapped between west and east (${count} agents)`, () => {+ const kind = (id: string) => items.find((i) => i.id === id)?.kind;+ expect([kind("bench-west-0"), kind("planter-west-0"), kind("planter-east-0"), kind("bench-east-0")]).toEqual(["bench", "planter", "planter", "bench"]);+ const west = items.find((i) => i.id === "bench-west-0")!, westBox = items.find((i) => i.id === "planter-west-0")!;+ expect(west.maxZ).toBeLessThan(westBox.minZ);+ const east = items.find((i) => i.id === "bench-east-0")!, eastBox = items.find((i) => i.id === "planter-east-0")!;+ expect(eastBox.maxZ).toBeLessThan(east.minZ);+ expect([west.facing, east.facing]).toEqual(["east", "west"]);});}- it("puts a bench and a planter beside each window, mirrored between west and east", () => {- const items = agentsAmbience(buildOfficeLayout([]));- const kindAt = (side: "west" | "east", run: number) => items.find((i) => i.id.endsWith(`-${side}-0-${run}`))?.kind;- expect(kindAt("west", 0)).toBe("bench");- expect(kindAt("west", 1)).toBe("planter");- expect(new Set(items.map((i) => i.id)).size).toBe(items.length);- });-it("adds nothing to the coding floor", () => {- const coding = buildOfficeLayout([], { variant: "coding" });- for (const item of agentsAmbience(coding)) {- expect(coding.obstacles.some((o) => o.minX === item.minX && o.maxZ === item.maxZ), item.id).toBe(false);- }+ expect(buildOfficeLayout([], { variant: "coding" }).ambience).toBeUndefined();});});describe("agents floor rugs", () => {- it("gives the six departments a floor can hold six different rugs, none shared with the coding floor", () => {- const rugs = Array.from({ length: 6 }, (_, i) => agentsRug(i));- expect(new Set(rugs.map((r) => r.weave)).size).toBe(6);- expect(new Set(rugs.map((r) => r.field)).size).toBe(6);+ it("gives the twelve studios a floor can hold twelve different rugs, none shared with the coding floor", () => {+ const rugs = Array.from({ length: 12 }, (_, i) => agentsRug(i));+ expect(AGENTS_RUGS).toHaveLength(12);+ expect(new Set(rugs.map((r) => `${r.weave}:${r.field}`)).size).toBe(12);+ expect(new Set(rugs.map((r) => r.field)).size).toBe(12);+ expect(new Set(rugs.map((r) => r.border)).size).toBe(12);const above = new Set(CODING_STUDIOS.map((s) => s.carpet));for (const rug of AGENTS_RUGS) expect(above.has(rug.field)).toBe(false);+ // Desk screens and seats take their zone from the same index.+ expect(DEPARTMENT_ZONES).toHaveLength(AGENTS_RUGS.length);});it("cycles for any tint index", () => {diff --git a/jarvis/ui/web/frontend/src/components/society/office/agentsAmbience.ts b/jarvis/ui/web/frontend/src/components/society/office/agentsAmbience.tsindex 4a5d9c8fd5..3c73daedbe 100644--- a/jarvis/ui/web/frontend/src/components/society/office/agentsAmbience.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/agentsAmbience.ts@@ -1,103 +1,211 @@/**- * The agents floor's window strip as data: olive trees in stone pots closing- * every cross aisle at the glass, and beside each outer department a- * cushioned oak window bench on one side of its window spot and a slatted oak- * planter of grasses on the other (swapped between west and east, so the two- * windows never mirror each other).+ * The agents floor's fittings between the rooms, as data: what makes a team+ * studio a place (low screens round it, a storage cabinet, a sofa, a standing+ * table, planted front edges) and what furnishes the commons (the atrium's+ * step seating, the café's kitchen run and island, focus booths, benches,+ * planters, olive trees in pots and a few large trees).*- * Pure and shared: the layout adds every item to its obstacles, the renderer- * builds each piece inside the same box. Everything stands in the 1.6 m- * window strip between the departments and the railing, so no desk, room door- * or checkpoint loses its way in. Where the Level Hall stands beyond the east- * window, the east olives stay away: the hall's doors open onto those aisles.+ * The campus plan (`campusLayout.ts`) places every piece, adds its footprint+ * to the floor's obstacles and gives it the spots people use it from. Pure+ * and shared: navigation reads the same boxes the renderer+ * (`AgentsFloorAmbience.tsx`) builds each piece inside. Every piece is a few+ * entries of instanced meshes there, so furnishing another studio costs no+ * extra draw calls.*/-import type { Rect } from "./officeLayout";+import type { Point, Rect } from "./officeLayout";-export type AgentsAmbienceKind = "olive" | "bench" | "planter";+export type AgentsAmbienceKind =+ | "olive" | "tree" | "bench" | "planter"+ // A team studio's own pieces.+ | "screen" | "cabinet" | "sofa" | "hightable"+ // The commons.+ | "booth" | "steps" | "counter" | "island"+ // On the free plot: a stack of moving crates, waiting for a team.+ | "crate";++export type Compass = "north" | "south" | "east" | "west";export interface AgentsAmbienceItem extends Rect {id: string;kind: AgentsAmbienceKind;- /** The side the piece's front looks at: benches face into the office. */- facing: "east" | "west";- /** Height of the piece in metres (the olive's crown top). */+ /** The side the piece's front looks at. A bench runs north-south and faces east or west. */+ facing: Compass;+ /** Height of the piece in metres (a tree's crown top). */h: number;+ /** A team studio's colour index, for the pieces that wear it; absent = the floor's neutral oak and linen. */+ tint?: number;}-/** An olive pot's square footprint, and how far its centre stands out from the department column. */+/** An olive pot's square footprint, and a large tree's. */export const OLIVE_BOX = 0.8;-const OLIVE_OUT = 0.8;-/** Benches and planters: depth, and how far their inner face stands out from the department column. */+export const TREE_BOX = 1.2;+/** Depth of a bench (its seat, front to back) and of a planter box. */export const BENCH_DEPTH = 0.4;export const PLANTER_DEPTH = 0.34;-const RUN_OUT = 0.95;-/** Half the gap left round a department's window spot, and the margin at the department's ends. */-const WINDOW_GAP = 0.85;-const END_MARGIN = 0.4;-const MIN_RUN = 1.2;export const OLIVE_H = 2.3;+export const TREE_H = 4.2;export const BENCH_H = 0.46;export const PLANTER_H = 0.52;-/** Where the aisles are: the department rows and the room strips north and south of them. */-export interface AgentsAmbienceFrame {- departments: readonly Rect[];- rooms: readonly Rect[];-}--/** Every window-strip piece of the agents floor, in a stable order. */-export function agentsAmbience({ departments, rooms }: AgentsAmbienceFrame): AgentsAmbienceItem[] {- if (departments.length === 0) return [];- const colMinX = Math.min(...departments.map((d) => d.minX));- const colMaxX = Math.max(...departments.map((d) => d.maxX));- const firstZ = Math.min(...departments.map((d) => d.minZ));- const lastZ = Math.max(...departments.map((d) => d.maxZ));- const north = rooms.filter((r) => r.maxZ <= firstZ + 1e-6).map((r) => r.maxZ);- const south = rooms.filter((r) => r.minZ >= lastZ - 1e-6).map((r) => r.minZ);- const items: AgentsAmbienceItem[] = [];-- // Cross aisles: in front of the north rooms, between department rows, in front of the south strip.- const rowStarts = [...new Set(departments.map((d) => d.minZ))].sort((a, b) => a - b);- const aisles: number[] = [];- if (north.length > 0) aisles.push((Math.max(...north) + firstZ) / 2);- for (let i = 1; i < rowStarts.length; i += 1) {- const above = Math.max(...departments.filter((d) => d.minZ === rowStarts[i - 1]).map((d) => d.maxZ));- aisles.push((above + rowStarts[i]) / 2);- }- if (south.length > 0) aisles.push((lastZ + Math.min(...south)) / 2);- // A wing beyond the east window (the Level Hall) opens its doors onto the cross aisles: no olive may close them.- const eastWing = rooms.some((r) => r.minX >= colMaxX - 1e-6 && r.minZ < lastZ && r.maxZ > firstZ);- aisles.forEach((z, i) => {- for (const [side, x] of [["west", colMinX - OLIVE_OUT], ["east", colMaxX + OLIVE_OUT]] as const) {- if (side === "east" && eastWing) continue;- items.push({- id: `olive-${side}-${i}`, kind: "olive", facing: side === "west" ? "east" : "west", h: OLIVE_H,- minX: x - OLIVE_BOX / 2, maxX: x + OLIVE_BOX / 2, minZ: z - OLIVE_BOX / 2, maxZ: z + OLIVE_BOX / 2,- });- }- });-- // Beside each outer department: two runs, one either side of its window spot.- departments.forEach((dept, index) => {- const zc = (dept.minZ + dept.maxZ) / 2;- const runs = [[dept.minZ + END_MARGIN, zc - WINDOW_GAP], [zc + WINDOW_GAP, dept.maxZ - END_MARGIN]] as const;- runs.forEach(([z0, z1], run) => {- if (z1 - z0 < MIN_RUN) return;- for (const side of ["west", "east"] as const) {- if (side === "west" ? dept.minX > colMinX + 1e-6 : dept.maxX < colMaxX - 1e-6) continue;- // West: bench north of the spot, planter south of it; the east window the other way round.- const kind: AgentsAmbienceKind = (run === 0) === (side === "west") ? "bench" : "planter";- const depth = kind === "bench" ? BENCH_DEPTH : PLANTER_DEPTH;- const [minX, maxX] = side === "west"- ? [colMinX - RUN_OUT - depth, colMinX - RUN_OUT]- : [colMaxX + RUN_OUT, colMaxX + RUN_OUT + depth];- items.push({- id: `${kind}-${side}-${index}-${run}`, kind, facing: side === "west" ? "east" : "west",- h: kind === "bench" ? BENCH_H : PLANTER_H, minX, maxX, minZ: z0, maxZ: z1,- });- }- });- });- return items;+/** A studio's low screen: felt below, glass above. */+export const SCREEN = { t: 0.08, h: 1.3 } as const;+export const CABINET = { w: 1.6, d: 0.45, h: 1.0 } as const;+/** A two-seat sofa; its seat is at the height a seated figure's couch pose expects. */+export const SOFA = { w: 2.0, d: 0.85, h: 0.8 } as const;+export const HIGH_TABLE = { r: 0.4, h: 1.08 } as const;+/** A focus booth: three felt walls, a roof and a glass front with the doorway. */+export const BOOTH = { w: 1.3, d: 1.3, h: 2.25, wall: 0.08 } as const;+/** Step seating: three tiers rising towards the back. */+export const STEPS = { d: 2.4, tier: 0.8, rise: 0.45, tiers: 3 } as const;+/** The café's kitchen run with its shelf wall, and the island in front of it. */+export const COUNTER = { d: 0.65, h: 2.1 } as const;+export const ISLAND = { w: 2.6, d: 0.9, h: 0.95 } as const;+export const CRATE = { w: 0.9, d: 0.6, h: 0.9 } as const;++/** Rotation about +y that turns a piece's front (its local +z) towards `facing`. */+export function yawOf(facing: Compass): number {+ return facing === "south" ? 0 : facing === "east" ? Math.PI / 2 : facing === "north" ? Math.PI : -Math.PI / 2;+}++/** A piece's own width (along its front) and depth, whatever way it is turned. */+export function ownSize(item: Pick<AgentsAmbienceItem, "facing" | keyof Rect>): { w: number; d: number } {+ const dx = item.maxX - item.minX, dz = item.maxZ - item.minZ;+ return item.facing === "east" || item.facing === "west" ? { w: dz, d: dx } : { w: dx, d: dz };+}++/** A point of a piece's own frame (x along its front, z towards its front, origin in its middle) on the floor plan. */+export function toFloor(item: Pick<AgentsAmbienceItem, "facing" | keyof Rect>, lx: number, lz: number): Point {+ const yaw = yawOf(item.facing), cos = Math.cos(yaw), sin = Math.sin(yaw);+ return { x: (item.minX + item.maxX) / 2 + lx * cos + lz * sin, z: (item.minZ + item.maxZ) / 2 - lx * sin + lz * cos };+}++/** A piece w wide (along its front) and d deep, centred on (x, z), its front towards `facing`. */+function oriented(id: string, kind: AgentsAmbienceKind, x: number, z: number, w: number, d: number, facing: Compass, h: number, tint?: number): AgentsAmbienceItem {+ const turned = facing === "east" || facing === "west";+ const halfX = (turned ? d : w) / 2, halfZ = (turned ? w : d) / 2;+ return { id, kind, facing, h, minX: x - halfX, maxX: x + halfX, minZ: z - halfZ, maxZ: z + halfZ, ...(tint === undefined ? {} : { tint }) };+}++/** An olive tree in its pot, centred on (x, z). */+export function olive(id: string, x: number, z: number): AgentsAmbienceItem {+ return oriented(id, "olive", x, z, OLIVE_BOX, OLIVE_BOX, "south", OLIVE_H);+}++/** A large tree in a round stone planter; its crown spreads above head height, beyond its footprint. */+export function tree(id: string, x: number, z: number): AgentsAmbienceItem {+ return oriented(id, "tree", x, z, TREE_BOX, TREE_BOX, "south", TREE_H);+}++/** A bench running north-south from z0 to z1, centred on x, its front towards `facing`. */+export function bench(id: string, x: number, z0: number, z1: number, facing: "east" | "west"): AgentsAmbienceItem {+ return { id, kind: "bench", facing, h: BENCH_H, minX: x - BENCH_DEPTH / 2, maxX: x + BENCH_DEPTH / 2, minZ: Math.min(z0, z1), maxZ: Math.max(z0, z1) };+}++/** A planter box filling `rect`; it may run north-south or east-west. */+export function planter(id: string, rect: Rect): AgentsAmbienceItem {+ return { id, kind: "planter", facing: "south", h: PLANTER_H, minX: rect.minX, maxX: rect.maxX, minZ: rect.minZ, maxZ: rect.maxZ };+}++/** A low screen along a straight line from (x0, z0) to (x1, z1) (north-south or east-west), in a studio's colour. */+export function screen(id: string, x0: number, z0: number, x1: number, z1: number, tint?: number): AgentsAmbienceItem {+ const t = SCREEN.t / 2;+ return {+ id, kind: "screen", facing: "south", h: SCREEN.h, ...(tint === undefined ? {} : { tint }),+ minX: Math.min(x0, x1) - t, maxX: Math.max(x0, x1) + t, minZ: Math.min(z0, z1) - t, maxZ: Math.max(z0, z1) + t,+ };+}++export function cabinet(id: string, x: number, z: number, facing: Compass, tint?: number): AgentsAmbienceItem {+ return oriented(id, "cabinet", x, z, CABINET.w, CABINET.d, facing, CABINET.h, tint);+}++export function sofa(id: string, x: number, z: number, facing: Compass, tint?: number): AgentsAmbienceItem {+ return oriented(id, "sofa", x, z, SOFA.w, SOFA.d, facing, SOFA.h, tint);+}++export function highTable(id: string, x: number, z: number): AgentsAmbienceItem {+ return oriented(id, "hightable", x, z, HIGH_TABLE.r * 2, HIGH_TABLE.r * 2, "south", HIGH_TABLE.h);+}++export function booth(id: string, x: number, z: number, facing: Compass, tint?: number): AgentsAmbienceItem {+ return oriented(id, "booth", x, z, BOOTH.w, BOOTH.d, facing, BOOTH.h, tint);+}++/** Step seating `length` wide, centred on (x, z), its lowest tier towards `facing`. */+export function steps(id: string, x: number, z: number, length: number, facing: Compass): AgentsAmbienceItem {+ return oriented(id, "steps", x, z, length, STEPS.d, facing, STEPS.rise * STEPS.tiers);+}++export function counter(id: string, x: number, z: number, length: number, facing: Compass): AgentsAmbienceItem {+ return oriented(id, "counter", x, z, length, COUNTER.d, facing, COUNTER.h);+}++export function crate(id: string, x: number, z: number, facing: Compass): AgentsAmbienceItem {+ return oriented(id, "crate", x, z, CRATE.w, CRATE.d, facing, CRATE.h);+}++export function island(id: string, x: number, z: number, facing: Compass): AgentsAmbienceItem {+ return oriented(id, "island", x, z, ISLAND.w, ISLAND.d, facing, ISLAND.h);+}++/** The box round two points of a piece's own frame, on the floor plan. */+function boxOf(item: AgentsAmbienceItem, lx0: number, lz0: number, lx1: number, lz1: number): Rect {+ const a = toFloor(item, lx0, lz0), b = toFloor(item, lx1, lz1);+ return { minX: Math.min(a.x, b.x), maxX: Math.max(a.x, b.x), minZ: Math.min(a.z, b.z), maxZ: Math.max(a.z, b.z) };+}++/**+ * What a walker bumps into at a piece: its footprint — except a focus booth,+ * which is its back and its two side walls, so a person walks in through the+ * front and stands inside.+ */+export function ambienceObstacles(item: AgentsAmbienceItem): Rect[] {+ if (item.kind !== "booth") return [{ minX: item.minX, maxX: item.maxX, minZ: item.minZ, maxZ: item.maxZ }];+ const { w, d } = ownSize(item), t = BOOTH.wall;+ return [+ boxOf(item, -w / 2, -d / 2, w / 2, -d / 2 + t),+ boxOf(item, -w / 2, -d / 2, -w / 2 + t, d / 2),+ boxOf(item, w / 2 - t, -d / 2, w / 2, d / 2),+ ];+}++/** A place at a piece, in the plan: where a figure is and the yaw it looks along. */+export interface AmbiencePlace extends Point { facing: number }++/** The two seats of a sofa. */+export function sofaSeats(item: AgentsAmbienceItem): AmbiencePlace[] {+ return [-0.45, 0.45].map((lx) => ({ ...toFloor(item, lx, 0.05), facing: yawOf(item.facing) }));+}++/** Seats along a bench, one per 1.1 m, looking the way the bench faces. */+export function benchSeats(item: AgentsAmbienceItem): AmbiencePlace[] {+ const length = item.maxZ - item.minZ, count = Math.max(1, Math.floor(length / 1.1));+ const x = (item.minX + item.maxX) / 2;+ return Array.from({ length: count }, (_, i) => ({ x, z: item.minZ + (length * (i + 0.5)) / count, facing: yawOf(item.facing) }));+}++/** Standing places round a high table, each looking at it; `angles` are compass yaws from the table (0 = south of it). */+export function tableStands(item: AgentsAmbienceItem, angles: readonly number[]): AmbiencePlace[] {+ const cx = (item.minX + item.maxX) / 2, cz = (item.minZ + item.maxZ) / 2, reach = HIGH_TABLE.r + 0.42;+ return angles.map((a) => ({ x: cx + Math.sin(a) * reach, z: cz + Math.cos(a) * reach, facing: a + Math.PI }));+}++/** Seats on the lowest tier of step seating, 0.9 m apart. */+export function stepsSeats(item: AgentsAmbienceItem): AmbiencePlace[] {+ const { w, d } = ownSize(item), count = Math.max(1, Math.floor((w - 0.6) / 0.9));+ return Array.from({ length: count }, (_, i) => ({+ ...toFloor(item, (i - (count - 1) / 2) * 0.9, d / 2 - STEPS.tier / 2), facing: yawOf(item.facing),+ }));+}++/** Inside a focus booth, at its shelf. */+export function boothPlace(item: AgentsAmbienceItem): AmbiencePlace {+ return { ...toFloor(item, 0, 0.12), facing: yawOf(item.facing) + Math.PI };+}++/** Standing places in front of a counter or an island, each looking at it. */+export function counterStands(item: AgentsAmbienceItem, offsets: readonly number[]): AmbiencePlace[] {+ const { d } = ownSize(item);+ return offsets.map((lx) => ({ ...toFloor(item, lx, d / 2 + 0.55), facing: yawOf(item.facing) + Math.PI }));}diff --git a/jarvis/ui/web/frontend/src/components/society/office/campusLayout.test.ts b/jarvis/ui/web/frontend/src/components/society/office/campusLayout.test.tsnew file mode 100644index 0000000000..b62aba4007--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/campusLayout.test.ts@@ -0,0 +1,653 @@+import { describe, expect, it } from "vitest";+import { ambienceObstacles, type AgentsAmbienceKind } from "./agentsAmbience";+import { CAMPUS, MAX_STUDIOS, planStudios, STUDIO_SEAT_CAP, studioShape, studioWallRect } from "./campusLayout";+import {+ allDesks, ARCH, archPosts, benchPlanters, buildOfficeLayout, deskRect, FLOOR_EDGE, footprint, FURNITURE_SIZE, leadDesks, seatedCount, seatOf, standOf, STUDIO_BOARD_FACE, studioBoardFace,+ type OfficeAgentInput, type OfficeLayout, type OfficeTeamInput, type Point, type Rect,+} from "./officeLayout";+import { buildNavGrid, findPath, isWalkable } from "./officeNav";++const agent = (n: number, extra: Partial<OfficeAgentInput> = {}): OfficeAgentInput => ({+ agentId: `a${n}`, name: `Agent ${n}`, tier: "specialist", providerLabel: n % 2 ? "Codex" : "Claude", state: "idle", createdMs: n, ...extra,+});+const staff = (count: number): OfficeAgentInput[] => Array.from({ length: count }, (_, i) => agent(i + 1));+const team = (n: number, members: number[], extra: Partial<OfficeTeamInput> = {}): OfficeTeamInput => ({+ id: `team-${n}`, name: `Team ${n}`, members: members.map((m) => `a${m}`), createdMs: n * 10, ...extra,+});+/** `count` teams of `size`, filled with consecutive agents from a1 on. */+const teamsOf = (count: number, size: number): OfficeTeamInput[] =>+ Array.from({ length: count }, (_, t) => team(t + 1, Array.from({ length: size }, (_, i) => t * size + i + 1)));++const overlaps = (a: Rect, b: Rect) => a.minX < b.maxX - 1e-9 && b.minX < a.maxX - 1e-9 && a.minZ < b.maxZ - 1e-9 && b.minZ < a.maxZ - 1e-9;+const inside = (p: Point, r: Rect) => p.x >= r.minX && p.x <= r.maxX && p.z >= r.minZ && p.z <= r.maxZ;+const area = (r: Rect) => (r.maxX - r.minX) * (r.maxZ - r.minZ);+const size = (layout: OfficeLayout) => ({ w: layout.bounds.maxX - layout.bounds.minX, d: layout.bounds.maxZ - layout.bounds.minZ });+const seatOfAgent = (layout: OfficeLayout, id: string) => allDesks(layout).find((d) => d.agentId === id)?.id;+const kindsOf = (layout: OfficeLayout, ...kinds: string[]) => layout.zones!.filter((z) => kinds.includes(z.kind)).map((z) => z.kind);++/** The three sizes the floor must look right at: 5, 15 and 40 people. */+const SIZES: [string, OfficeAgentInput[], OfficeTeamInput[]][] = [+ ["5 agents, no team", staff(5), []],+ ["15 agents, 3 teams", staff(15), teamsOf(3, 4)],+ ["40 agents, 8 teams", staff(40), teamsOf(8, 4)],+];++describe("campus: who sits where", () => {+ it("gives every team a studio of its own and puts everyone else in the pool", () => {+ const layout = buildOfficeLayout(staff(9), { teams: [team(1, [1, 2, 3]), team(2, [4, 5])] });+ expect(layout.departments.map((d) => [d.id, d.label, d.teamId])).toEqual([+ ["studio-pool", "", null], ["studio-team-1", "Team 1", "team-1"], ["studio-team-2", "Team 2", "team-2"],+ ]);+ const studios = layout.studios!;+ expect(studios.map((s) => [s.deptId, s.teamId, s.name, s.members])).toEqual([+ ["studio-pool", null, "", ["a6", "a7", "a8", "a9"]],+ ["studio-team-1", "team-1", "Team 1", ["a1", "a2", "a3"]],+ ["studio-team-2", "team-2", "Team 2", ["a4", "a5"]],+ ]);+ // Each agent sits in its own studio's desks, in arrival order.+ for (const studio of studios) {+ const dept = layout.departments.find((d) => d.id === studio.deptId)!;+ expect(dept.desks.map((d) => d.agentId).filter(Boolean)).toEqual(studio.members);+ }+ expect(seatedCount(layout)).toBe(9);+ });++ it("seats an agent of several teams in the oldest one, ties by id", () => {+ const teams = [team(2, [1, 2], { createdMs: 50 }), team(1, [2, 3], { createdMs: 20 }), team(3, [3, 4], { createdMs: 20 })];+ const plans = planStudios(staff(4), teams);+ // Oldest first: team-1 and team-3 share an age, team-1 wins by id; team-2 is the youngest.+ expect(plans.map((p) => [p.teamId, p.members.map((a) => a.agentId)])).toEqual([+ [null, []], ["team-1", ["a2", "a3"]], ["team-3", ["a4"]], ["team-2", ["a1"]],+ ]);+ // The input order of the teams does not matter.+ expect(planStudios(staff(4), [...teams].reverse())).toEqual(plans);+ });++ it("keeps a studio for a team whose members are unknown, and never guesses a team lead", () => {+ const layout = buildOfficeLayout(staff(3), { teams: [team(1, [41, 42]), team(2, [1], { leadId: "a1" })] });+ const ghost = layout.studios!.find((s) => s.teamId === "team-1")!;+ expect(ghost.members).toEqual([]);+ expect(ghost.leadId).toBeNull();+ expect(layout.departments.find((d) => d.id === ghost.deptId)!.desks).toHaveLength(4);+ expect(layout.studios!.find((s) => s.teamId === "team-2")!.leadId).toBe("a1");+ expect(layout.studios![0].members).toEqual(["a2", "a3"]);+ });++ it("keeps lead-tier agents in the lead office even when a team lists them", () => {+ const roster = [agent(1, { tier: "lead" }), agent(2), agent(3)];+ const layout = buildOfficeLayout(roster, { teams: [team(1, [1, 2])] });+ expect(layout.lead.desks.map((d) => d.agentId)).toEqual(["a1"]);+ expect(layout.studios!.find((s) => s.teamId === "team-1")!.members).toEqual(["a2"]);+ // A third lead has no place in the office for two: it works from the pool.+ const three = buildOfficeLayout([1, 2, 3].map((n) => agent(n, { tier: "lead" })));+ expect(three.lead.desks.map((d) => d.agentId)).toEqual(["a1", "a2"]);+ expect(three.studios![0].members).toEqual(["a3"]);+ });++ it("never re-seats anyone while roster and teams are unchanged", () => {+ const roster = staff(23), teams = [team(1, [1, 2, 3, 4, 5]), team(2, [6, 7]), team(3, [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19])];+ const before = buildOfficeLayout(roster, { teams });+ // A refetch: other object identities, another order, other run states, members listed in another order.+ const again = buildOfficeLayout([...roster].reverse().map((a) => ({ ...a, state: "working" as const })),+ { teams: [...teams].reverse().map((t) => ({ ...t, members: [...t.members].reverse() })) });+ expect(again).toEqual(before);+ // A newcomer without a team takes a pool desk; nobody in a team moves.+ const grown = buildOfficeLayout([...roster, agent(24)], { teams });+ for (const id of teams.flatMap((t) => t.members)) expect(seatOfAgent(grown, id), id).toBe(seatOfAgent(before, id));+ for (const dept of before.departments.filter((d) => d.teamId)) {+ const now = grown.departments.find((d) => d.id === dept.id)!;+ expect([now.minX, now.minZ, now.maxX, now.maxZ]).toEqual([dept.minX, dept.minZ, dept.maxX, dept.maxZ]);+ }+ });++ it("folds teams beyond the last cell into the pool and a team too large for one studio spills there", () => {+ const many = buildOfficeLayout(staff(30), { teams: teamsOf(14, 2) });+ expect(many.departments).toHaveLength(MAX_STUDIOS);+ expect(many.departments.filter((d) => d.teamId !== null)).toHaveLength(MAX_STUDIOS - 1);+ expect(seatedCount(many)).toBe(30);+ expect(many.studios![0].members).toEqual(["a23", "a24", "a25", "a26", "a27", "a28", "a29", "a30"]);+ const huge = buildOfficeLayout(staff(40), { teams: [team(1, Array.from({ length: 40 }, (_, i) => i + 1))] });+ expect(huge.studios!.find((s) => s.teamId === "team-1")!.members).toHaveLength(STUDIO_SEAT_CAP);+ expect(huge.studios![0].members).toHaveLength(40 - STUDIO_SEAT_CAP);+ expect(seatedCount(huge)).toBe(40);+ });++ it("opens a second pool studio only when the pool outgrows one", () => {+ const layout = buildOfficeLayout(staff(40));+ expect(layout.departments.map((d) => [d.id, d.teamId])).toEqual([["studio-pool", null], ["studio-pool-2", null]]);+ expect(seatedCount(layout)).toBe(40);+ expect(buildOfficeLayout(staff(STUDIO_SEAT_CAP)).departments).toHaveLength(1);+ });+});++describe("campus: a studio", () => {+ it("sizes the desks to the team: one free desk, whole pairs, as few benches as hold them", () => {+ const shape = (n: number) => studioShape(n).benches;+ expect(shape(0)).toEqual([2]);+ expect(shape(2)).toEqual([2]);+ expect(shape(5)).toEqual([3]);+ expect(shape(7)).toEqual([4]);+ expect(shape(8)).toEqual([3, 2]);+ expect(shape(12)).toEqual([4, 3]);+ expect(shape(STUDIO_SEAT_CAP)).toEqual([4, 4, 4, 4]);+ for (let n = 0; n <= STUDIO_SEAT_CAP; n += 1) {+ const s = studioShape(n);+ expect(s.seats, `${n} members`).toBeGreaterThanOrEqual(n);+ // Never a row of empty benches: at most three free desks, and that only in the smallest studio.+ expect(s.seats - n, `${n} members`).toBeLessThanOrEqual(n === 0 ? 4 : n < STUDIO_SEAT_CAP ? 3 : 0);+ }+ // Only the desks grow with the team: the huddle zone and the front zone are the same in every studio.+ expect(studioShape(12).depth - studioShape(2).depth).toBeCloseTo(4.2, 9);+ expect(studioShape(2).depth).toBeCloseTo(CAMPUS.studioHeader + 4.2 + CAMPUS.studioFront, 9);+ });++ it("has a name wall, a board on it, huddle places in front of the board and its own colour", () => {+ const layout = buildOfficeLayout(staff(20), { teams: [team(1, [1, 2]), team(2, [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])] });+ const grid = buildNavGrid(layout);+ expect(new Set(layout.departments.map((d) => d.tint)).size).toBe(layout.departments.length);+ for (const studio of layout.studios!) {+ const dept = layout.departments.find((d) => d.id === studio.deptId)!;+ const board = layout.furniture.find((f) => f.id === studio.board!.id)!;+ expect(board.kind).toBe("studioBoard");+ expect(board.id).toBe(`studio-board:${dept.id}`);+ // The board stands inside the studio, right in front of the name wall, facing south.+ const box = footprint(board), wall = studioWallRect(dept);+ expect(box.minX).toBeGreaterThan(wall.minX);+ expect(box.maxX).toBeLessThan(wall.maxX);+ expect(box.minZ).toBeGreaterThanOrEqual(wall.maxZ);+ expect(box.minZ - wall.maxZ).toBeLessThan(0.1);+ expect(layout.obstacles.some((o) => o.minX === wall.minX && o.minZ === wall.minZ && o.maxX === wall.maxX)).toBe(true);+ // Its face is where the layout says, inside the board's footprint.+ const face = studioBoardFace(studio.board!);+ expect(face.rotationY).toBe(0);+ expect(face.size).toEqual([STUDIO_BOARD_FACE.w, STUDIO_BOARD_FACE.h]);+ expect(face.position[0]).toBe(board.x);+ expect(face.position[2] - board.z).toBeCloseTo(STUDIO_BOARD_FACE.z, 9);+ expect(face.position[2]).toBeLessThan(box.maxZ);+ // Huddle places: at least as many as the team (up to six), apart, walkable, facing the board, clear of the desks.+ const spots = studio.huddleSpotIds.map((id) => layout.spots.find((s) => s.id === id)!);+ expect(spots.length).toBeGreaterThanOrEqual(Math.max(4, Math.min(6, studio.members.length)));+ spots.forEach((spot, n) => {+ expect(spot.id).toBe(`huddle:${dept.id}:${n}`);+ expect([spot.kind, spot.pose, spot.room]).toEqual(["huddle", "stand", "floor"]);+ expect(isWalkable(grid, spot), spot.id).toBe(true);+ expect(inside(spot, dept), spot.id).toBe(true);+ const ahead = { x: spot.x + Math.sin(spot.facing) * 0.5, z: spot.z + Math.cos(spot.facing) * 0.5 };+ expect(Math.hypot(ahead.x - studio.board!.x, ahead.z - studio.board!.z)).toBeLessThan(Math.hypot(spot.x - studio.board!.x, spot.z - studio.board!.z));+ for (const other of spots) if (other !== spot) expect(Math.hypot(other.x - spot.x, other.z - spot.z)).toBeGreaterThanOrEqual(0.75);+ for (const desk of dept.desks) expect(Math.hypot(seatOf(desk).x - spot.x, seatOf(desk).z - spot.z)).toBeGreaterThan(1.5);+ });+ expect(inside(studio.centre, dept)).toBe(true);+ // Every desk stands inside its studio.+ for (const desk of dept.desks) expect(inside(desk, dept), desk.id).toBe(true);+ }+ });++ it("is a furnished room at every team size: screens on both sides, a planted front with the entrance, sofa, table, storage", () => {+ const layout = buildOfficeLayout(staff(15), { teams: [team(1, [1, 2, 3]), team(2, [4, 5, 6, 7, 8, 9, 10, 11, 12])] });+ const grid = buildNavGrid(layout);+ const item = (id: string) => layout.ambience!.find((i) => i.id === id);+ for (const dept of layout.departments) {+ const cx = (dept.minX + dept.maxX) / 2, cz = (dept.minZ + dept.maxZ) / 2;+ // A whole cell, whatever the head count.+ expect(dept.maxX - dept.minX).toBeCloseTo(CAMPUS.cellW, 9);+ for (const part of ["cabinet", "sofa", "table", "front-w", "front-e", "screen-e"]) expect(item(`${dept.id}-${part}`), `${dept.id}-${part}`).toBeDefined();+ for (const part of ["cabinet", "sofa", "table"]) {+ const piece = item(`${dept.id}-${part}`)!;+ expect(piece.minX >= dept.minX && piece.maxX <= dept.maxX && piece.minZ >= dept.minZ && piece.maxZ <= dept.maxZ, piece.id).toBe(true);+ // In the studio's own colour where the piece wears one.+ if (part !== "table") expect(piece.tint).toBe(dept.tint);+ }+ // Both sides are closed over the studio's whole depth; the middle of the front is the way in.+ for (const x of [dept.minX + 0.06, dept.maxX - 0.06]) {+ for (const z of [dept.minZ + 1, cz, dept.maxZ - 1]) expect(isWalkable(grid, { x, z }), `side ${x},${z}`).toBe(false);+ }+ for (const dz of [-0.9, -0.37, 0.6]) expect(isWalkable(grid, { x: cx, z: dept.maxZ + dz }), `entrance ${dz}`).toBe(true);+ for (const x of [dept.minX + 1.5, dept.maxX - 1.5]) expect(isWalkable(grid, { x, z: dept.maxZ - 0.37 }), `front ${x}`).toBe(false);+ // Somewhere to sit and somewhere to stand, each a spot of its own.+ for (const id of [`${dept.id}-sofa-0`, `${dept.id}-sofa-1`, `${dept.id}-table-0`, `${dept.id}-table-1`]) {+ const spot = layout.spots.find((s) => s.id === id)!;+ expect(spot, id).toBeDefined();+ expect(inside(spot, dept), id).toBe(true);+ }+ }+ // Two studios shoulder to shoulder share one screen: the pool (west of the boulevard) stands alone, the two+ // teams east of the boulevard... do not: the second team took the cell on the pool's other side.+ const [pool, first, second] = layout.departments;+ expect(first.minX).toBeCloseTo(CAMPUS.boulevard / 2, 9);+ expect(pool.maxX).toBeCloseTo(-CAMPUS.boulevard / 2, 9);+ expect(second.maxX).toBeCloseTo(pool.minX, 9);+ // The shared screen stands on the line between the two and wears neither colour.+ const shared = item(`${second.id}-screen-e`)!;+ expect((shared.minX + shared.maxX) / 2).toBeCloseTo(pool.minX, 9);+ expect(shared.tint).toBeUndefined();+ expect(item(`${pool.id}-screen-w`)).toBeUndefined();+ expect(item(`${second.id}-screen-w`)!.tint).toBe(second.tint);+ });+});++describe("campus: a team's lead", () => {+ const roster = staff(8);+ const members = [1, 2, 3, 4, 5];+ const plan = (leadId?: string | null, extra: OfficeTeamInput[] = []) =>+ buildOfficeLayout(roster, { teams: [team(1, members, leadId === undefined ? {} : { leadId }), ...extra] });+ const studioOf = (layout: OfficeLayout, teamId: string) => layout.studios!.find((s) => s.teamId === teamId)!;+ /** Agent id -> desk id, for everyone seated on the floor. */+ const seats = (layout: OfficeLayout) => new Map(allDesks(layout).filter((d) => d.agentId).map((d) => [d.agentId!, d.id] as const));+ const moved = (a: OfficeLayout, b: OfficeLayout) => [...seats(a)].filter(([id, desk]) => seats(b).get(id) !== desk).map(([id]) => id).sort();++ it("sits at the head desk: the first desk of the bench nearest the name wall", () => {+ const layout = plan("a3");+ const studio = studioOf(layout, "team-1");+ expect(studio.leadId).toBe("a3");+ // The lead first, the earliest arrival in the lead's place, everyone else by arrival.+ expect(studio.members).toEqual(["a3", "a2", "a1", "a4", "a5"]);+ const dept = layout.departments.find((d) => d.id === studio.deptId)!;+ const head = dept.desks[0];+ expect(head.id).toBe("studio-team-1:0:north:0");+ expect(head.agentId).toBe("a3");+ // It is on the bench nearest the name wall, and no desk of that bench stands further west.+ const nearest = Math.min(...dept.desks.map((d) => d.z));+ expect(head.z - nearest).toBeLessThan(1);+ expect(dept.desks.every((d) => d.x >= head.x - 1e-9)).toBe(true);+ expect(leadDesks(layout).map(({ desk, dept: of }) => [desk.id, of.id])).toEqual([["studio-team-1:0:north:0", "studio-team-1"]]);+ // The lead can be walked to like anyone else.+ expect(findPath(buildNavGrid(layout), layout.spawn, standOf(head))).not.toBeNull();+ });++ it("is the same plan for the same teams and lead, however the answer is ordered", () => {+ const other = team(2, [6, 7], { leadId: "a7" });+ const a = buildOfficeLayout(roster, { teams: [team(1, members, { leadId: "a3" }), other] });+ const b = buildOfficeLayout([...roster].reverse(), { teams: [other, team(1, [...members].reverse(), { leadId: "a3" })] });+ expect(b).toEqual(a);+ expect(studioOf(a, "team-2").members).toEqual(["a7", "a6"]);+ });++ it("is never guessed: a lead who is no member, not on the roster or in the lead office leaves the studio without one", () => {+ const plain = plan();+ for (const leadId of ["a7", "ghost", "", null]) {+ const layout = plan(leadId);+ expect(studioOf(layout, "team-1").leadId, String(leadId)).toBeNull();+ expect(layout, String(leadId)).toEqual(plain);+ expect(leadDesks(layout)).toEqual([]);+ }+ // A lead-tier agent sits in the lead office, whatever team names it lead.+ const boss = agent(0, { tier: "lead" });+ const withBoss = (leadId?: string) => buildOfficeLayout([boss, ...roster], { teams: [team(1, [0, ...members], leadId ? { leadId } : {})] });+ expect(studioOf(withBoss("a0"), "team-1").leadId).toBeNull();+ expect(withBoss("a0")).toEqual(withBoss());+ expect(withBoss("a0").lead.desks[0].agentId).toBe("a0");+ });++ it("moves only who has to move: two people when a lead is named, three at most when it changes", () => {+ const none = plan(), third = plan("a3"), fifth = plan("a5"), first = plan("a1");+ // Named: the lead and the earliest arrival change places.+ expect(moved(none, third)).toEqual(["a1", "a3"]);+ // The earliest arrival already sits at the head desk.+ expect(moved(none, first)).toEqual([]);+ expect(studioOf(first, "team-1").leadId).toBe("a1");+ // Changed: the old lead goes back to its own place, the new one to the head, the earliest arrival to the new lead's place.+ expect(moved(third, fifth)).toEqual(["a1", "a3", "a5"]);+ expect(moved(third, first)).toEqual(["a1", "a3"]);+ // Nobody outside the team moves, and the studio keeps its size.+ for (const next of [third, fifth, first]) {+ expect(next.bounds).toEqual(none.bounds);+ expect(next.departments.map((d) => [d.id, d.desks.length])).toEqual(none.departments.map((d) => [d.id, d.desks.length]));+ }+ });++ it("sits with the team it leads, not with an older team it is only a member of", () => {+ const older = team(1, [1, 2, 3]), younger = team(2, [3, 4], { leadId: "a3" });+ const layout = buildOfficeLayout(roster, { teams: [older, younger] });+ expect(studioOf(layout, "team-1").members).toEqual(["a1", "a2"]);+ expect(studioOf(layout, "team-2").members).toEqual(["a3", "a4"]);+ expect(studioOf(layout, "team-2").leadId).toBe("a3");+ // Named lead of two teams: at the head of the older one; the other has no lead on the floor.+ const both = buildOfficeLayout(roster, { teams: [{ ...older, leadId: "a3" }, younger] });+ expect(studioOf(both, "team-1").members).toEqual(["a3", "a2", "a1"]);+ expect(studioOf(both, "team-1").leadId).toBe("a3");+ expect(studioOf(both, "team-2").leadId).toBeNull();+ expect(studioOf(both, "team-2").members).toEqual(["a4"]);+ expect(seatedCount(both)).toBe(roster.length);+ });++ it("keeps its head desk in a studio that is full: the newest member sits in the pool instead", () => {+ const crowd = staff(STUDIO_SEAT_CAP + 3), newest = `a${STUDIO_SEAT_CAP + 3}`;+ const everyone = Array.from({ length: STUDIO_SEAT_CAP + 3 }, (_, i) => i + 1);+ const layout = buildOfficeLayout(crowd, { teams: [team(1, everyone, { leadId: newest })] });+ const studio = studioOf(layout, "team-1");+ expect(studio.members).toHaveLength(STUDIO_SEAT_CAP);+ expect(studio.members[0]).toBe(newest);+ expect(studio.leadId).toBe(newest);+ // Three do not fit: the newest three who are not the lead.+ expect(layout.studios![0].members).toEqual([`a${STUDIO_SEAT_CAP}`, `a${STUDIO_SEAT_CAP + 1}`, `a${STUDIO_SEAT_CAP + 2}`]);+ expect(seatedCount(layout)).toBe(crowd.length);+ });+});++describe("campus: the plan", () => {+ it("is four cells wide at every size and grows southwards by a row of studios", () => {+ const [small, mid, large] = SIZES.map(([, roster, teams]) => buildOfficeLayout(roster, { teams }));+ // Four cells, the boulevard, a walk along each window and the strip at the glass.+ expect(CAMPUS.cellsPerRow * CAMPUS.cellW + CAMPUS.boulevard + 2 * CAMPUS.promenade + 2 * FLOOR_EDGE).toBeCloseTo(55.0, 6);+ for (const layout of [small, mid, large]) expect(size(layout).w).toBeCloseTo(55.0, 6);+ expect(size(small).d).toBeCloseTo(47.0, 6);+ expect(size(mid).d).toBeCloseTo(47.0, 6);+ expect(size(large).d).toBeCloseTo(81.2, 6);+ // More than two and a half times the floor it replaces (24.4 m x 38.2 m for the same small roster).+ expect(size(small).w * size(small).d).toBeGreaterThan(2.5 * 24.4 * 38.2);+ // One row holds four studios; the fifth opens a second row.+ const rows = (layout: OfficeLayout) => new Set(layout.departments.map((d) => d.minZ)).size;+ expect(rows(buildOfficeLayout(staff(12), { teams: teamsOf(3, 3) }))).toBe(1);+ expect(rows(buildOfficeLayout(staff(12), { teams: teamsOf(4, 3) }))).toBe(2);+ expect(rows(large)).toBe(3);+ });++ for (const [name, roster, teams] of SIZES) {+ it(`is furnished, not circulation: rooms, studios and commons take most of the floor (${name})`, () => {+ const layout = buildOfficeLayout(roster, { teams });+ const plan = { minX: layout.bounds.minX + 1.6, maxX: layout.bounds.maxX - 1.6, minZ: layout.bounds.minZ + 1.6, maxZ: layout.bounds.maxZ - 1.6 };+ const places = [...layout.rooms, ...layout.departments, ...layout.zones!.filter((z) => z.kind !== "boulevard" && z.kind !== "plaza")];+ const furnished = places.reduce((sum, r) => sum + area(r), 0);+ expect(furnished / area(plan)).toBeGreaterThan(0.68);+ // Streets are streets: the boulevard and the streets between rows are a few metres wide, the plaza is the one wide one.+ expect(CAMPUS.boulevard).toBeLessThanOrEqual(5);+ expect(CAMPUS.street).toBeLessThan(4);+ // Studios of a row stand shoulder to shoulder, their fronts in one line.+ const rows = new Map<number, typeof layout.departments>();+ for (const dept of layout.departments) rows.set(dept.minZ, [...(rows.get(dept.minZ) ?? []), dept]);+ for (const row of rows.values()) {+ expect(new Set(row.map((d) => d.maxZ)).size).toBe(1);+ const sorted = [...row].sort((a, b) => a.minX - b.minX);+ for (let i = 1; i < sorted.length; i += 1) {+ const gap = sorted[i].minX - sorted[i - 1].maxX;+ expect(gap === 0 || Math.abs(gap - CAMPUS.boulevard) < 1e-9 || Math.abs(gap - CAMPUS.cellW) < 1e-9 || gap > CAMPUS.cellW, `gap ${gap}`).toBe(true);+ }+ }+ });++ it(`keeps studios, rooms, streets and fittings apart (${name})`, () => {+ const layout = buildOfficeLayout(roster, { teams });+ const zones = layout.zones!, streets = zones.filter((z) => z.kind === "boulevard" || z.kind === "plaza");+ const blocks: Rect[] = [...layout.departments, ...layout.rooms];+ for (const a of blocks) for (const b of blocks) if (a !== b) expect(overlaps(a, b)).toBe(false);+ // Nothing is built on the boulevards, and no commons or plot overlaps a studio, a room or another commons.+ for (const block of blocks) for (const street of streets) expect(overlaps(block, street)).toBe(false);+ const commons = zones.filter((z) => z.kind !== "boulevard" && z.kind !== "plaza" && z.kind !== "atrium");+ for (const zone of commons) {+ for (const block of blocks) expect(overlaps(zone, block), zone.id).toBe(false);+ for (const street of streets) expect(overlaps(zone, street), zone.id).toBe(false);+ for (const other of commons) if (other !== zone) expect(overlaps(zone, other), `${zone.id} x ${other.id}`).toBe(false);+ }+ // Fittings never stand in a room or on a desk, and each one is solid.+ const ambience = layout.ambience!;+ expect(new Set(ambience.map((i) => i.id)).size).toBe(ambience.length);+ const kinds: AgentsAmbienceKind[] = ["olive", "tree", "bench", "planter", "screen", "cabinet", "sofa", "hightable", "booth", "steps", "counter", "island"];+ // The free plot's crates are there while a plot is.+ expect(ambience.some((i) => i.kind === "crate")).toBe(layout.zones!.some((z) => z.kind === "plot"));+ for (const kind of kinds) expect(ambience.some((i) => i.kind === kind), kind).toBe(true);+ for (const item of ambience) {+ for (const room of layout.rooms) expect(overlaps(item, room), item.id).toBe(false);+ for (const desk of allDesks(layout)) expect(inside(desk, item), item.id).toBe(false);+ for (const solid of ambienceObstacles(item)) {+ expect(layout.obstacles.some((o) => o.minX === solid.minX && o.maxX === solid.maxX && o.minZ === solid.minZ && o.maxZ === solid.maxZ), item.id).toBe(true);+ }+ // The railing's base is 8 cm wide on a line 0.2 m in from the slab edge.+ expect(item.minX, item.id).toBeGreaterThan(layout.bounds.minX + 0.24);+ expect(item.maxX, item.id).toBeLessThan(layout.bounds.maxX - 0.24);+ expect(item.minZ, item.id).toBeGreaterThan(layout.bounds.minZ + 0.24);+ expect(item.maxZ, item.id).toBeLessThan(layout.bounds.maxZ - 0.24);+ }+ // Planting is a few deliberate groups, not rows: far fewer trees than studios and commons could hold.+ const trees = ambience.filter((i) => i.kind === "olive" || i.kind === "tree").length;+ expect(trees).toBeLessThanOrEqual(12 + 2 * layout.departments.length + 3 * kindsOf(layout, "garden").length);+ expect(ambience.some((i) => i.kind === "tree") && ambience.some((i) => i.kind === "olive")).toBe(true);+ });++ it(`never stands two solid things in the same place (${name})`, () => {+ const layout = buildOfficeLayout([agent(0, { tier: "lead" }), agent(99, { tier: "lead" }), ...roster], { teams });+ const solids: (Rect & { id: string })[] = [+ ...layout.furniture.filter((f) => FURNITURE_SIZE[f.kind].solid).map((f) => ({ id: f.id, ...footprint(f) })),+ ...layout.ambience!.map((i) => ({ ...i })),+ ...allDesks(layout).map((d) => ({ id: `desk ${d.id}`, ...deskRect(d) })),+ ...layout.departments.map((d) => ({ id: `wall ${d.id}`, ...studioWallRect(d) })),+ ...layout.departments.flatMap(benchPlanters).map((p) => ({ id: `planter ${p.key}`, ...p.rect })),+ ...layout.walls.map((w, n) => ({ id: `room wall ${n}`, minX: Math.min(w.x1, w.x2) - 0.06, maxX: Math.max(w.x1, w.x2) + 0.06, minZ: Math.min(w.z1, w.z2) - 0.06, maxZ: Math.max(w.z1, w.z2) + 0.06 })),+ ];+ const clashes: string[] = [];+ for (let i = 0; i < solids.length; i += 1) {+ for (let j = i + 1; j < solids.length; j += 1) {+ if (solids[i].id.startsWith("room wall") && solids[j].id.startsWith("room wall")) continue;+ if (overlaps(solids[i], solids[j])) clashes.push(`${solids[i].id} x ${solids[j].id}`);+ }+ }+ // By design: the team board hangs on the team room's slat wall, so their footprints touch. Nothing else does.+ expect(clashes).toEqual(["team-wall x team-board"]);+ // Nothing solid stands in a doorway: one step inside and one outside every door is free.+ const grid = buildNavGrid(layout);+ for (const room of layout.rooms) {+ for (const door of room.doors) {+ const horizontal = door.side === "north" || door.side === "south";+ const line = door.side === "north" ? room.minZ : door.side === "south" ? room.maxZ : door.side === "west" ? room.minX : room.maxX;+ for (const step of [-0.8, 0, 0.8]) {+ const p = horizontal ? { x: door.at, z: line + step } : { x: line + step, z: door.at };+ expect(isWalkable(grid, p), `${room.kind} ${door.side} door ${step}`).toBe(true);+ }+ }+ }+ });++ it(`puts the spawn point in the atrium, where the boulevards cross (${name})`, () => {+ const layout = buildOfficeLayout(roster, { teams });+ const stop = layout.checkpoints.find((c) => c.id === "spawn")!;+ const zone = (kind: string) => layout.zones!.find((z) => z.kind === kind)!;+ const pad = layout.furniture.find((f) => f.kind === "spawnPad")!, terminal = layout.furniture.find((f) => f.kind === "spawnTerminal")!;+ expect([pad.x, pad.z, terminal.x, terminal.z]).toEqual([stop.x, stop.z, stop.x, stop.z]);+ expect(stop.x).toBe(0);+ expect(stop.z).toBeCloseTo((zone("plaza").minZ + zone("plaza").maxZ) / 2, 9);+ expect(inside(stop, zone("atrium")) && inside(stop, zone("boulevard"))).toBe(true);+ // The plaza is the gap between two blocks nearest the floor's middle; the boulevard runs from the lobby to the team room's door.+ expect(Math.abs(stop.z)).toBeLessThan(size(layout).d / 4);+ const teamRoom = layout.rooms.find((r) => r.kind === "team")!, lobby = layout.rooms.find((r) => r.kind === "reception")!;+ expect(teamRoom.doors[0].at).toBe(0);+ expect(zone("boulevard").minZ).toBe(teamRoom.maxZ);+ expect(zone("boulevard").maxZ).toBe(lobby.minZ);+ expect((lobby.minX + lobby.maxX) / 2).toBe(0);+ // The heart of the campus: step seating either side of the pad, facing it, with seats; the pad itself stays clear.+ const padBox = footprint(pad);+ for (const item of layout.ambience!) expect(overlaps(item, padBox), item.id).toBe(false);+ const [west, east] = ["west", "east"].map((side) => layout.ambience!.find((i) => i.id === `atrium-steps-${side}`)!);+ expect([west.kind, west.facing, east.kind, east.facing]).toEqual(["steps", "east", "steps", "west"]);+ expect(inside({ x: (west.minX + west.maxX) / 2, z: (west.minZ + west.maxZ) / 2 }, zone("atrium"))).toBe(true);+ const seats = layout.spots.filter((s) => s.id.startsWith("atrium-steps-"));+ expect(seats.length).toBeGreaterThanOrEqual(8);+ for (const seat of seats) {+ expect([seat.kind, seat.pose]).toEqual(["couch", "sit"]);+ // Looking at the spawn point.+ expect(Math.sign(Math.sin(seat.facing))).toBe(seat.x < 0 ? 1 : -1);+ }+ expect(layout.arrival).toEqual(stop.approach);+ expect(isWalkable(buildNavGrid(layout), layout.arrival)).toBe(true);+ });+ }++ it("shows the next team's place as a free plot and makes the other empty cells garden courts", () => {+ const empty = buildOfficeLayout(staff(5));+ expect(kindsOf(empty, "plot", "garden")).toEqual(["plot", "garden", "garden"]);+ // The first team takes exactly the plot's cell; the plot moves on.+ const plot = empty.zones!.find((z) => z.kind === "plot")!;+ const one = buildOfficeLayout(staff(5), { teams: [team(1, [1, 2])] });+ const studio = one.departments.find((d) => d.teamId === "team-1")!;+ expect(overlaps(plot, studio) && plot.minX > studio.minX && plot.maxX < studio.maxX && plot.minZ > studio.minZ).toBe(true);+ expect(kindsOf(one, "plot", "garden")).toEqual(["plot", "garden"]);+ expect(kindsOf(buildOfficeLayout(staff(12), { teams: teamsOf(3, 3) }), "plot", "garden")).toEqual([]);+ });++ it("furnishes the free plot: the stand where a team is started faces the street, crates and a plant wait behind it", () => {+ const layout = buildOfficeLayout(staff(5));+ const grid = buildNavGrid(layout);+ const plot = layout.zones!.find((z) => z.kind === "plot")!;+ const stands = layout.furniture.filter((f) => f.kind === "teamStand");+ expect(stands.map((f) => [f.id, f.rotationY])).toEqual([["team-stand", 0]]);+ const stand = stands[0];+ expect(inside(stand, plot)).toBe(true);+ expect(isWalkable(grid, stand)).toBe(false);+ // The station layer stands the person 0.95 m in front of its face: on the plot, on open floor, within reach.+ const front = { x: stand.x, z: stand.z + FURNITURE_SIZE.teamStand.d / 2 + 0.95 };+ expect(inside(front, plot)).toBe(true);+ expect(isWalkable(grid, front)).toBe(true);+ expect(findPath(grid, layout.spawn, front)).not.toBeNull();+ const crates = layout.ambience!.filter((i) => i.kind === "crate");+ expect(crates.map((i) => i.id)).toEqual(["plot-crates"]);+ expect(overlaps(crates[0], plot)).toBe(true);+ expect(isWalkable(grid, { x: (crates[0].minX + crates[0].maxX) / 2, z: (crates[0].minZ + crates[0].maxZ) / 2 })).toBe(false);+ expect(inside(layout.furniture.find((f) => f.id === "plot-plant")!, plot)).toBe(true);+ // A full row has no plot: no stand, no crates.+ const full = buildOfficeLayout(staff(12), { teams: teamsOf(3, 3) });+ expect(full.furniture.some((f) => f.kind === "teamStand" || f.id === "plot-plant")).toBe(false);+ expect(full.ambience!.some((i) => i.kind === "crate")).toBe(false);+ });++ it("carries the lobby's name on an arch at the back of the reception desk, off the atrium", () => {+ for (const [, roster, teams] of SIZES) {+ const layout = buildOfficeLayout(roster, { teams });+ const reception = layout.rooms.find((r) => r.kind === "reception")!;+ const desk = footprint(layout.furniture.find((f) => f.kind === "receptionDesk")!);+ const posts = archPosts(reception);+ expect(posts).toHaveLength(2);+ for (const post of posts) {+ expect(inside(post, reception)).toBe(true);+ // Behind the desk's back, within its width: the board reads as the desk's own sign.+ expect(post.x).toBeGreaterThan(desk.minX);+ expect(post.x).toBeLessThan(desk.maxX);+ expect(desk.minZ - post.z).toBeGreaterThan(ARCH.post / 2);+ expect(desk.minZ - post.z).toBeLessThan(0.3);+ for (const zone of layout.zones!.filter((z) => z.kind === "atrium" || z.kind === "plaza")) expect(inside(post, zone)).toBe(false);+ expect(isWalkable(buildNavGrid(layout), post)).toBe(false);+ }+ }+ });++ for (const [name, roster, teams] of SIZES) {+ it(`keeps a real walk along both windows, between the benches at the glass and the outer studios (${name})`, () => {+ const layout = buildOfficeLayout(roster, { teams });+ const grid = buildNavGrid(layout);+ const band = layout.ambience!.filter((i) => /^(bench|planter)-(west|east)-\d+$/.test(i.id));+ expect(band.length).toBeGreaterThanOrEqual(4);+ for (const piece of band) {+ const west = piece.id.includes("-west-");+ // The nearest solid thing further into the floor, beside this piece.+ const beside = layout.obstacles.filter((o) => o.minZ < piece.maxZ && o.maxZ > piece.minZ && (west ? o.minX >= piece.maxX : o.maxX <= piece.minX));+ const clear = Math.min(...beside.map((o) => (west ? o.minX - piece.maxX : piece.minX - o.maxX)));+ expect(clear, piece.id).toBeGreaterThanOrEqual(1.2);+ }+ // And it is one walk from the first row of studios to the last, on both sides.+ const rows = [...layout.departments, ...layout.zones!.filter((z) => z.kind === "plot" || z.kind === "garden")];+ const z0 = Math.min(...rows.map((r) => r.minZ)), z1 = Math.max(...rows.map((r) => r.maxZ));+ for (const x of [layout.bounds.minX + FLOOR_EDGE + CAMPUS.promenade / 2, layout.bounds.maxX - FLOOR_EDGE - CAMPUS.promenade / 2]) {+ for (let z = z0; z <= z1; z += 0.4) expect(isWalkable(grid, { x, z }), `walk ${x} at ${z}`).toBe(true);+ }+ });+ }++ for (const [name, roster, teams] of SIZES) {+ it(`has its commons at every size, each with places to use it (${name})`, () => {+ const layout = buildOfficeLayout(roster, { teams });+ expect(kindsOf(layout, "booths", "library", "cafe")).toEqual(["booths", "library", "cafe"]);+ const grid = buildNavGrid(layout);+ const spotsIn = (kind: string) => {+ const zone = layout.zones!.find((z) => z.kind === kind)!;+ return layout.spots.filter((s) => s.room === "floor" && inside(s, zone));+ };+ // Somewhere to sit and somewhere to stand in the café and the library; a booth each for three people.+ for (const kind of ["cafe", "library", "booths"]) {+ const spots = spotsIn(kind);+ expect(spots.length, kind).toBeGreaterThanOrEqual(5);+ expect(spots.some((s) => s.pose === "sit") && spots.some((s) => s.pose === "stand"), kind).toBe(true);+ }+ const booths = layout.spots.filter((s) => /^booth-\d$/.test(s.id));+ expect(booths).toHaveLength(3);+ // A person walks into a booth and stands inside it.+ for (const spot of booths) {+ expect(isWalkable(grid, spot), spot.id).toBe(true);+ const box = layout.ambience!.find((i) => i.id === spot.id)!;+ expect(inside(spot, box)).toBe(true);+ expect(isWalkable(grid, { x: spot.x, z: box.minZ + 0.1 })).toBe(false);+ }+ // A garden court has a bench to sit on.+ for (const zone of layout.zones!.filter((z) => z.kind === "garden")) {+ expect(layout.spots.filter((s) => inside(s, zone) && s.pose === "sit").length, zone.id).toBeGreaterThanOrEqual(2);+ }+ // Every spot outside the rooms is a place a figure can be: on the open floor, or on a seat within a step of it.+ for (const spot of layout.spots.filter((s) => s.room === "floor")) {+ expect(findPath(grid, layout.spawn, spot), spot.id).not.toBeNull();+ }+ });+ }+});++describe("campus: walking it", () => {+ const cases: [string, OfficeAgentInput[], OfficeTeamInput[]][] = [+ ["no team", staff(5), []],+ ["one team of two", staff(6), [team(1, [1, 2])]],+ ["three teams, one of twelve", staff(20), [team(1, [1, 2]), team(2, [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]), team(3, [15, 16, 17])]],+ ["eight teams", staff(40), teamsOf(8, 4)],+ ["an agent in two teams and a team of unknown ids", staff(8), [team(1, [1, 2, 3]), team(2, [3, 4]), team(3, [90, 91])]],+ ];+ for (const [name, roster, teams] of cases) {+ it(`reaches every seat, spot, station and studio board from the elevator (${name})`, () => {+ const layout = buildOfficeLayout([agent(0, { tier: "lead" }), ...roster], { teams });+ const grid = buildNavGrid(layout);+ const elevator = layout.checkpoints.find((c) => c.id === "elevator")!;+ const targets: { name: string; p: Point }[] = [+ ...allDesks(layout).flatMap((d) => [{ name: `seat ${d.id}`, p: seatOf(d) }, { name: `stand ${d.id}`, p: standOf(d) }]),+ ...layout.spots.map((s) => ({ name: `spot ${s.id}`, p: s })),+ ...layout.checkpoints.map((c) => ({ name: `station ${c.id}`, p: c.approach ?? c })),+ // In front of every studio board, where the person reads it.+ ...layout.studios!.map((s) => ({ name: `board ${s.deptId}`, p: { x: s.board!.x, z: s.board!.z + 1.0 } })),+ ...layout.zones!.map((z) => ({ name: `zone ${z.id}`, p: { x: (z.minX + z.maxX) / 2 + 0.9, z: (z.minZ + z.maxZ) / 2 + 2.2 } })),+ ];+ for (const start of [layout.spawn, elevator]) {+ expect(isWalkable(grid, start)).toBe(true);+ for (const target of targets) {+ if (!findPath(grid, start, target.p)) throw new Error(`${target.name} at ${target.p.x.toFixed(2)},${target.p.z.toFixed(2)} is unreachable`);+ }+ }+ });++ it(`sends every route from the lobby to a studio or a room across the plaza (${name})`, () => {+ const layout = buildOfficeLayout(roster, { teams });+ const grid = buildNavGrid(layout);+ const plaza = layout.zones!.find((z) => z.kind === "plaza")!;+ const elevator = layout.checkpoints.find((c) => c.id === "elevator")!;+ const north = [+ ...layout.departments.filter((d) => d.maxZ <= plaza.minZ).map((d) => ({ x: (d.minX + d.maxX) / 2, z: d.minZ + 2.0 })),+ ...layout.checkpoints.filter((c) => ["team", "lead", "wardrobe"].includes(c.id)),+ ];+ expect(north.length).toBeGreaterThan(3);+ // The main boulevard runs from window to window: whoever goes north passes over it, in the middle or along a window.+ const band = { ...plaza, minX: layout.floor.minX, maxX: layout.floor.maxX };+ for (const target of north) {+ const path = [elevator, ...findPath(grid, elevator, target)!];+ expect(path.some((p, i) => i > 0 && (inside(p, band) || (path[i - 1].z > band.maxZ && p.z < band.minZ))), `${target.x},${target.z}`).toBe(true);+ expect(path.every((p) => inside(p, layout.floor))).toBe(true);+ }+ });+ }++ it("keeps the boulevard, the plaza and every street open from end to end", () => {+ const layout = buildOfficeLayout(staff(40), { teams: teamsOf(8, 4) });+ const grid = buildNavGrid(layout);+ const boulevard = layout.zones!.find((z) => z.kind === "boulevard")!, plaza = layout.zones!.find((z) => z.kind === "plaza")!;+ for (let z = boulevard.minZ + 0.3; z < boulevard.maxZ - 0.3; z += 0.4) {+ // The boulevard's middle is free all the way, except where the spawn terminal stands on it.+ if (Math.abs(z - (plaza.minZ + plaza.maxZ) / 2) < 1) continue;+ expect(isWalkable(grid, { x: 0, z }), `axis at ${z}`).toBe(true);+ }+ // Past the step seating on both sides of the plaza, and along the street in front of every row of studios.+ const streets = [plaza.minZ + 1.5, plaza.maxZ - 1.5, ...new Set(layout.departments.map((d) => d.maxZ + 1.2)), boulevard.minZ + CAMPUS.street / 2];+ for (const z of streets) {+ for (let x = layout.floor.minX + 1.5; x < layout.floor.maxX - 1.5; x += 0.4) expect(isWalkable(grid, { x, z }), `street ${z} at ${x}`).toBe(true);+ }+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/campusLayout.ts b/jarvis/ui/web/frontend/src/components/society/office/campusLayout.tsnew file mode 100644index 0000000000..496bf3dbcc--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/campusLayout.ts@@ -0,0 +1,690 @@+/**+ * The agents floor as a team campus.+ *+ * ┌ booths ┬── Lead office ──┬──── Team room ────┬─ Wardrobe ─┬─── library ───┐+ * │ north street │+ * │ studio ┃ studio ║ ║ studio ┃ studio │+ * │ ┃ ║ boulevard ║ ┃ a street of team rooms │+ * │═══════ main boulevard · ATRIUM: spawn point, step seating ═══════════════│+ * │ café │ Reception + lobby (elevator) │ │ Break room │+ * └─────────────────┴──────────────────────────────────┴─┴────────────────────┘+ *+ * Every team (a society chat group) has a studio: a room of its own with a+ * name wall and the studio board at its back, low screens on both sides, a+ * planted front with the entrance, the desks sized to the team, a huddle zone+ * in front of the board, a sofa, a standing table and a storage cabinet.+ * Agents without a team share the pool studio. Studios stand shoulder to+ * shoulder in rows of four, two either side of the boulevard that runs from+ * the lobby to the team room, and open onto the street in front of them. The+ * main boulevard crosses at the atrium: the spawn point between two flights+ * of step seating. Every route between the lobby, the rooms and the studios+ * crosses that plaza.+ *+ * What is not a studio or a room is a commons people use: the café beside the+ * lobby, the library and the focus booths in the north corners, and in a cell+ * without a studio the free plot (the next team's place) or a garden court.+ *+ * The plan is four cells wide at every size; it grows southwards by a row of+ * studios whenever a row is full. Pure and deterministic: the same roster and+ * the same teams always give the same plan and the same seats.+ */+import {+ ambienceObstacles, bench, benchSeats, booth, boothPlace, cabinet, counter, counterStands, crate, highTable, island, olive, planter,+ screen, sofa, sofaSeats, steps, stepsSeats, tableStands, tree, BENCH_DEPTH, PLANTER_DEPTH, SOFA,+ type AgentsAmbienceItem, type AmbiencePlace,+} from "./agentsAmbience";+import {+ ARCH, archPosts, BENCH_DEPTH_Z, benchPlanters, byArrival, chairRect, DESK_HALF_GAP, DESK_PITCH_X, deskRect,+ executiveChairRect, EXECUTIVE_DESK_SIZE, FLOOR_EDGE, footprint, FURNITURE_SIZE, PARTNER_DESK_SIZE, RAIL_CLEARANCE,+ seatOf, SPAWN, STUDIO_BOARD_FACE, wallRect, wallsOf,+ type CampusZone, type Checkpoint, type Department, type DeskSlot, type Furniture, type FurnitureKind,+ type OfficeAgentInput, type OfficeLayout, type OfficeTeamInput, type Point, type Rect, type Room, type RoomKind,+ type Spot, type SpotKind, type SpotPose, type Studio, type WallSegment,+} from "./officeLayout";++/**+ * The campus grid, in metres. A cell holds one studio; two cells stand+ * shoulder to shoulder on each side of the boulevard. A street separates two+ * rows, and the plaza is the main boulevard with the atrium at its heart.+ */+export const CAMPUS = {+ cellW: 11, boulevard: 5, street: 3.6, plaza: 9, atrium: 16,+ /** The walk along both windows, between the benches at the glass and the outer studios. */+ promenade: 1.4,+ northDepth: 9.4, southDepth: 10.4,+ /** A studio, north to south: the huddle zone between its name wall and the first desks, then the desks, then the front zone with the sofa and the entrance. */+ studioHeader: 4, studioFront: 3.2,+ /** The opening in a studio's planted front. */+ studioDoor: 4.8,+ cellsPerRow: 4,+} as const;++/** Desks come in facing pairs; a bench holds up to four pairs, a studio up to four benches. */+const PAIRS_PER_BENCH = 4;+const MAX_BENCHES = 4;+/** The most agents one studio seats; a larger team's newest members sit in the pool. */+export const STUDIO_SEAT_CAP = MAX_BENCHES * PAIRS_PER_BENCH * 2;+/** The most studios the campus builds (three rows); later teams fold into the pool. */+export const MAX_STUDIOS = 12;+/** A cell's column for each slot of a row: the two cells beside the boulevard fill first, west before east. */+const SLOT_COLUMNS = [1, 2, 0, 3] as const;+/** How far the walkable floor's west edge (the navigation grid's origin) is moved off the plan's 0.05 m raster. */+const GRID_NUDGE = 0.025;+/** Zone colour of the pool studio (neutral linen), and the cycle the team studios take theirs from. */+const POOL_TINT = 2;+const TEAM_TINTS = [0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11] as const;++/** Who sits in one studio, before it has a place on the floor. */+export interface StudioPlan {+ id: string;+ /** The team whose studio this is; null for the pool. */+ teamId: string | null;+ /** The team's name; "" for the pool (the renderer names it). */+ name: string;+ /** The team's lead when it sits here, at the head desk; see `Studio.leadId`. */+ leadId: string | null;+ /** Seated members in seating order: by arrival, with the lead (if any) and the earliest arrival having changed places. */+ members: OfficeAgentInput[];+}++function slug(id: string): string {+ return id.replace(/[^A-Za-z0-9_-]/g, "_");+}++/**+ * Sort the roster into studios. The first two lead-tier agents keep the lead+ * office. Teams are taken oldest first (then by id): an agent in several teams+ * sits in the oldest one. A team keeps its studio even when none of its+ * members can sit there (unknown ids, or everyone already seated elsewhere).+ * Whoever has no team, or no room left in theirs, sits in the pool, which+ * comes first and opens further pool studios only when it outgrows one.+ *+ * A team's lead sits at the head of the studio it leads: first in its seating+ * order, where the earliest arrival would sit, who takes the lead's place in+ * the order instead. So naming a lead moves two people, and changing one at+ * most three (the old lead back to its own place, the new one to the head,+ * the earliest arrival to the new lead's place); everyone else stays. Leading+ * a team comes before "the oldest team" for an agent in several, and before+ * the studio's seat cap. A lead must be a member the roster knows who is not+ * in the lead office; whoever is named lead of several teams sits with the+ * oldest of them, and the others have no lead on the floor.+ */+export function planStudios(agents: readonly OfficeAgentInput[], teams: readonly OfficeTeamInput[]): StudioPlan[] {+ const leads = agents.filter((a) => a.tier === "lead").sort(byArrival).slice(0, 2);+ const inOffice = new Set(leads.map((a) => a.agentId));+ const staff = agents.filter((a) => !inOffice.has(a.agentId)).sort(byArrival);+ const byId = new Map(staff.map((a) => [a.agentId, a]));+ const seen = new Set<string>();+ const ordered = [...teams]+ .sort((a, b) => a.createdMs - b.createdMs || a.id.localeCompare(b.id))+ .filter((team) => (seen.has(team.id) ? false : (seen.add(team.id), true)))+ .slice(0, MAX_STUDIOS - 1);++ // Agent id -> the team at whose head it sits.+ const heads = new Map<string, string>();+ for (const team of ordered) {+ const lead = team.leadId;+ if (lead && byId.has(lead) && team.members.includes(lead) && !heads.has(lead)) heads.set(lead, team.id);+ }++ const claimed = new Set<string>();+ const ids = new Set<string>(["studio-pool"]);+ const teamPlans: StudioPlan[] = ordered.map((team) => {+ const mine: OfficeAgentInput[] = [];+ for (const memberId of new Set(team.members)) {+ const agent = byId.get(memberId);+ const headOf = heads.get(memberId);+ // Whoever leads another team sits there.+ if (!agent || claimed.has(memberId) || (headOf !== undefined && headOf !== team.id)) continue;+ mine.push(agent);+ }+ mine.sort(byArrival);+ const lead = team.leadId && heads.get(team.leadId) === team.id ? byId.get(team.leadId) ?? null : null;+ let seated = mine.slice(0, STUDIO_SEAT_CAP);+ // A lead who arrived after the studio was full still sits in it, in place of its newest member.+ if (lead && !seated.includes(lead)) seated = [...seated.slice(0, STUDIO_SEAT_CAP - 1), lead];+ if (lead) {+ const at = seated.indexOf(lead);+ [seated[0], seated[at]] = [seated[at], seated[0]];+ }+ for (const agent of seated) claimed.add(agent.agentId);+ let id = `studio-${slug(team.id)}`;+ for (let n = 2; ids.has(id); n += 1) id = `studio-${slug(team.id)}-${n}`;+ ids.add(id);+ return { id, teamId: team.id, name: team.name.trim(), leadId: lead?.agentId ?? null, members: seated };+ });++ const pool = staff.filter((a) => !claimed.has(a.agentId));+ const poolStudios = Math.min(MAX_STUDIOS - teamPlans.length, Math.max(1, Math.ceil(pool.length / STUDIO_SEAT_CAP)));+ const pools: StudioPlan[] = Array.from({ length: poolStudios }, (_, n) => ({+ id: n === 0 ? "studio-pool" : `studio-pool-${n + 1}`, teamId: null, name: "", leadId: null,+ members: pool.slice(n * STUDIO_SEAT_CAP, (n + 1) * STUDIO_SEAT_CAP),+ }));+ return [pools[0], ...teamPlans, ...pools.slice(1)];+}++/** A studio's desk cluster and depth for a head count. */+export interface StudioShape {+ /** Facing desk pairs per bench, north bench first. */+ benches: number[];+ seats: number;+ /** North to south: huddle zone, benches, front zone. A studio is always one cell wide. */+ depth: number;+}++/**+ * The desk cluster a studio of `members` gets: one free desk to grow into,+ * rounded up to whole pairs, spread evenly over as few benches as hold them.+ * At least two pairs, so even a new team's studio is a place to work.+ */+export function studioShape(members: number): StudioShape {+ const want = Math.min(STUDIO_SEAT_CAP, Math.max(0, members) + 1);+ const pairs = Math.max(2, Math.ceil(want / 2));+ const count = Math.ceil(pairs / PAIRS_PER_BENCH);+ const benches = Array.from({ length: count }, (_, i) => Math.floor(pairs / count) + (i < pairs % count ? 1 : 0));+ return { benches, seats: pairs * 2, depth: CAMPUS.studioHeader + count * BENCH_DEPTH_Z + CAMPUS.studioFront };+}++/** The x-range of each of the four cells, west to east: two shoulder to shoulder on each side of the boulevard. */+function cellRanges(): [number, number][] {+ const half = CAMPUS.boulevard / 2, w = CAMPUS.cellW;+ return [[-half - 2 * w, -half - w], [-half - w, -half], [half, half + w], [half + w, half + 2 * w]];+}++/**+ * Desk slots of a studio: bench by bench, each pair facing across the bench, filled in seating order. The first+ * slot, on the bench nearest the name wall, is the head desk: the lead's when the team has one.+ */+function studioDesks(id: string, cx: number, minZ: number, shape: StudioShape, members: readonly OfficeAgentInput[]): DeskSlot[] {+ const desks: DeskSlot[] = [];+ let seat = 0;+ shape.benches.forEach((pairs, benchIndex) => {+ const centreZ = minZ + CAMPUS.studioHeader + benchIndex * BENCH_DEPTH_Z + BENCH_DEPTH_Z / 2;+ const west = cx - (pairs * DESK_PITCH_X) / 2;+ for (let col = 0; col < pairs; col += 1) {+ for (const facing of ["north", "south"] as const) {+ // A north-facing agent sits on the south side of the pair, looking at its monitor.+ const z = facing === "north" ? centreZ + DESK_HALF_GAP : centreZ - DESK_HALF_GAP;+ desks.push({ id: `${id}:${benchIndex}:${facing}:${col}`, x: west + DESK_PITCH_X * (col + 0.5), z, facing, agentId: members[seat]?.agentId ?? null });+ seat += 1;+ }+ }+ });+ return desks;+}++/** A studio's name wall along its north edge: solid, and what the studio board hangs in front of. */+export function studioWallRect(dept: Rect): Rect {+ return { minX: dept.minX + 0.2, maxX: dept.maxX - 0.2, minZ: dept.minZ + 0.02, maxZ: dept.minZ + 0.2 };+}++/** Where a studio's name is lettered on its wall and where its board hangs: the west and the east half. */+export function studioWallParts(dept: Rect): { nameX: number; boardX: number; span: number } {+ const span = dept.maxX - dept.minX - 0.4;+ const cx = (dept.minX + dept.maxX) / 2;+ return { nameX: cx - span / 4, boardX: cx + span / 4, span };+}++/** Standing places in front of a studio board: a front row of four and a back row of three. */+const HUDDLE_OFFSETS: readonly (readonly [number, number])[] = [+ [-0.4, 1.45], [0.4, 1.45], [-1.2, 1.45], [1.2, 1.45], [0, 2.3], [-0.8, 2.3], [0.8, 2.3],+];++/** Wall runs of all rooms, each run once: two rooms sharing a wall line would otherwise both draw (and both block) it. */+function uniqueWalls(rooms: readonly Room[]): WallSegment[] {+ const seen = new Set<string>();+ return rooms.flatMap(wallsOf).filter((wall) => {+ const key = [`${wall.x1.toFixed(3)},${wall.z1.toFixed(3)}`, `${wall.x2.toFixed(3)},${wall.z2.toFixed(3)}`].sort().join("|");+ return seen.has(key) ? false : (seen.add(key), true);+ });+}++/** Build the agents floor for a roster and its teams. */+export function buildCampusLayout(agents: readonly OfficeAgentInput[], teams: readonly OfficeTeamInput[]): OfficeLayout {+ const plans = planStudios(agents, teams);+ const shapes = plans.map((plan) => studioShape(plan.members.length));+ const cells = cellRanges();+ const planMinX = cells[0][0] - CAMPUS.promenade, planMaxX = cells[3][1] + CAMPUS.promenade;+ const perRow = CAMPUS.cellsPerRow;+ const rowCount = Math.max(1, Math.ceil(plans.length / perRow));+ const minRowDepth = studioShape(0).depth;+ // The studios of a row share its depth, so their fronts line up along the street.+ const rowDepth = Array.from({ length: rowCount }, (_, r) =>+ Math.max(minRowDepth, ...shapes.slice(r * perRow, (r + 1) * perRow).map((s) => s.depth)));++ // Depth: north strip, a street, the rows with a street after each — except one gap, which is the plaza.+ const depth = CAMPUS.northDepth + CAMPUS.street + rowDepth.reduce((sum, d) => sum + d, 0)+ + (rowCount - 1) * CAMPUS.street + CAMPUS.plaza + CAMPUS.southDepth;+ const topZ = -depth / 2, bottomZ = depth / 2;+ const northMaxZ = topZ + CAMPUS.northDepth, southMinZ = bottomZ - CAMPUS.southDepth;+ /** Row starts and the plaza's centre line when the plaza follows row `after` (0-based). */+ const place = (after: number) => {+ const starts: number[] = [];+ let z = northMaxZ + CAMPUS.street, plazaZ = 0;+ for (let r = 0; r < rowCount; r += 1) {+ starts.push(z);+ z += rowDepth[r];+ if (r === after) plazaZ = z + CAMPUS.plaza / 2;+ z += r === after ? CAMPUS.plaza : CAMPUS.street;+ }+ return { starts, plazaZ };+ };+ // The plaza takes the gap nearest the floor's middle (the earlier one on a tie): with one row, the one in front of the lobby.+ let plazaAfter = 0;+ for (let r = 1; r < rowCount; r += 1) if (Math.abs(place(r).plazaZ) < Math.abs(place(plazaAfter).plazaZ) - 1e-9) plazaAfter = r;+ const { starts: rowZ, plazaZ } = place(plazaAfter);+ const half = CAMPUS.boulevard / 2;+ const plaza: Point = { x: 0, z: plazaZ };+ const plazaRect: Rect = { minX: planMinX, maxX: planMaxX, minZ: plazaZ - CAMPUS.plaza / 2, maxZ: plazaZ + CAMPUS.plaza / 2 };++ // ------------------------------------------------------------------ rooms+ const lead: Room = { id: "lead", kind: "lead", walled: true, minX: -17.2, maxX: -6.2, minZ: topZ, maxZ: northMaxZ,+ doors: [{ side: "south", at: -11.7, width: 1.8 }] };+ // The team room closes the boulevard: its door stands on the axis.+ const team: Room = { id: "team", kind: "team", walled: true, minX: -6.2, maxX: 6.2, minZ: topZ, maxZ: northMaxZ,+ doors: [{ side: "south", at: 0, width: 2.4 }] };+ const wardrobe: Room = { id: "wardrobe", kind: "wardrobe", walled: true, minX: 6.2, maxX: 14, minZ: topZ, maxZ: northMaxZ,+ doors: [{ side: "south", at: 10.1, width: 1.6 }] };+ // The lobby straddles the boulevard; the elevator, the brand wall and the award case stand along its west edge.+ // Its name arch stands against the back of the reception desk and carries the name over it, instead of standing+ // at the lobby's edge on the atrium.+ const reception: Room = { id: "reception", kind: "reception", walled: false, minX: -10.6, maxX: 10.6, minZ: southMinZ, maxZ: bottomZ, doors: [],+ arch: { x: -6, z: southMinZ + 1.95 } };+ const breakRoom: Room = { id: "break", kind: "break", walled: true, minX: 13.1, maxX: planMaxX, minZ: southMinZ, maxZ: bottomZ,+ doors: [{ side: "north", at: (13.1 + planMaxX) / 2, width: 2.4 }, { side: "west", at: southMinZ + CAMPUS.southDepth / 2, width: 2 }] };+ const rooms = [lead, team, wardrobe, reception, breakRoom];++ const departments: Department[] = [];+ const studios: Studio[] = [];+ const furniture: Furniture[] = [];+ const spots: Spot[] = [];+ const ambience: AgentsAmbienceItem[] = [];+ const zones: CampusZone[] = [+ { id: "boulevard", kind: "boulevard", minX: -half, maxX: half, minZ: northMaxZ, maxZ: southMinZ },+ { id: "plaza", kind: "plaza", ...plazaRect },+ { id: "atrium", kind: "atrium", minX: -CAMPUS.atrium / 2, maxX: CAMPUS.atrium / 2, minZ: plazaRect.minZ, maxZ: plazaRect.maxZ },+ ];+ const piece = (id: string, kind: FurnitureKind, room: RoomKind | "floor", x: number, z: number, rotationY = 0, size?: { w: number; d: number }): Furniture =>+ ({ id, kind, x, z, rotationY, room, ...(size ? { size } : {}) });+ /** Places at a commons piece or in a studio become spots on the open floor. */+ const use = (prefix: string, kind: SpotKind, pose: SpotPose, places: readonly AmbiencePlace[]) => {+ places.forEach((p, n) => spots.push({ id: `${prefix}-${n}`, kind, pose, x: p.x, z: p.z, facing: p.facing, room: "floor" }));+ };+ const add = <T extends AgentsAmbienceItem>(item: T): T => { ambience.push(item); return item; };++ // --------------------------------------------------------------- studios+ let teamIndex = 0;+ let plotPlaced = false;+ for (let r = 0; r < rowCount; r += 1) {+ const z0 = rowZ[r], z1 = rowZ[r] + rowDepth[r];+ /** The studio plan standing in column c of this row, if any. */+ const planAt = (column: number) => plans[r * perRow + SLOT_COLUMNS.indexOf(column as 0 | 1 | 2 | 3)];+ for (let slot = 0; slot < perRow; slot += 1) {+ const column = SLOT_COLUMNS[slot];+ const [x0, x1] = cells[column];+ const cx = (x0 + x1) / 2, cz = (z0 + z1) / 2;+ const index = r * perRow + slot;+ const plan = plans[index];+ if (!plan) {+ // A cell without a studio: the first one is the free plot where the next team will stand, the others are garden courts.+ if (!plotPlaced) {+ plotPlaced = true;+ zones.push({ id: "plot", kind: "plot", minX: x0 + 0.6, maxX: x1 - 0.6, minZ: z0 + 0.6, maxZ: z1 - 0.6 });+ // A place a team could move into tomorrow: the stand where one is started, facing the street, a stack of+ // moving crates and a plant already waiting at the back.+ furniture.push(piece("team-stand", "teamStand", "floor", cx, z1 - 2.6));+ furniture.push(piece("plot-plant", "plant", "floor", x1 - 1.7, z0 + 1.6));+ add(crate("plot-crates", x0 + 1.9, z0 + 1.7, "south"));+ continue;+ }+ const id = `garden-${r}-${slot}`;+ zones.push({ id, kind: "garden", minX: x0, maxX: x1, minZ: z0, maxZ: z1 });+ // A lawn with one large tree and two olives off to its sides, a bed of grasses along the back and two+ // benches facing each other in the middle; mirrored on the east half of the floor.+ const m = column >= 2 ? -1 : 1;+ add(tree(`${id}-tree`, cx - m * 3.1, z0 + 2.7));+ add(olive(`${id}-olive-a`, cx + m * 3.4, z0 + 2.1));+ add(olive(`${id}-olive-b`, cx + m * 2.9, z1 - 2.3));+ add(planter(`${id}-bed`, { minX: cx - 1.6, maxX: cx + 1.9, minZ: z0 + 0.8, maxZ: z0 + 0.8 + PLANTER_DEPTH }));+ use(`${id}-bench-w`, "couch", "sit", benchSeats(add(bench(`${id}-bench-w`, cx - 0.95, cz - 0.4, cz + 2.0, "east"))));+ use(`${id}-bench-e`, "couch", "sit", benchSeats(add(bench(`${id}-bench-e`, cx + 0.95, cz - 0.4, cz + 2.0, "west"))));+ spots.push({ id: `${id}-stand`, kind: "window", pose: "stand", room: "floor", x: cx - m * 1.5, z: z0 + 3.2, facing: m > 0 ? -Math.PI / 2 : Math.PI / 2 });+ continue;+ }+ const shape = shapes[index];+ const tint = plan.teamId === null ? POOL_TINT : TEAM_TINTS[teamIndex % TEAM_TINTS.length];+ if (plan.teamId !== null) teamIndex += 1;+ const dept: Department = {+ id: plan.id, label: plan.name, teamId: plan.teamId, tint,+ minX: x0, maxX: x1, minZ: z0, maxZ: z1,+ desks: studioDesks(plan.id, cx, z0, shape, plan.members),+ };+ departments.push(dept);++ // The studio board hangs in front of the east half of the name wall; the team gathers south of it.+ const { boardX } = studioWallParts(dept);+ const boardId = `studio-board:${dept.id}`;+ const boardZ = z0 + 0.23 + FURNITURE_SIZE.studioBoard.d / 2;+ furniture.push(piece(boardId, "studioBoard", "floor", boardX, boardZ));+ const face: Point = { x: boardX, z: boardZ + STUDIO_BOARD_FACE.z };+ const huddle: Spot[] = HUDDLE_OFFSETS.slice(0, Math.min(HUDDLE_OFFSETS.length, Math.max(4, plan.members.length + 1))).map(([dx, dz], n) => ({+ id: `huddle:${dept.id}:${n}`, kind: "huddle", pose: "stand", room: "floor",+ x: face.x + dx, z: face.z + dz, facing: Math.atan2(-dx, -dz),+ }));+ spots.push(...huddle);+ studios.push({+ deptId: dept.id, teamId: plan.teamId, name: plan.name, members: plan.members.map((a) => a.agentId), leadId: plan.leadId,+ board: { id: boardId, x: face.x, z: face.z, facing: 0 }, huddleSpotIds: huddle.map((s) => s.id),+ centre: { x: cx, z: cz },+ });++ // Low screens close both sides. Two studios shoulder to shoulder share the one between them (the west+ // studio builds it, in neutral oak); a side on the boulevard, the window or an empty cell has the studio's own.+ const sideZ = [z0 + 0.22, z1 - 0.2] as const;+ const westShared = (column === 1 || column === 3) && !!planAt(column - 1);+ const eastShared = (column === 0 || column === 2) && !!planAt(column + 1);+ if (!westShared) add(screen(`${dept.id}-screen-w`, x0 + 0.06, sideZ[0], x0 + 0.06, sideZ[1], tint));+ if (eastShared) add(screen(`${dept.id}-screen-e`, x1, sideZ[0], x1, sideZ[1]));+ else add(screen(`${dept.id}-screen-e`, x1 - 0.06, sideZ[0], x1 - 0.06, sideZ[1], tint));+ // The front is planted, with the entrance in its middle.+ const frontZ = { minZ: z1 - 0.2 - PLANTER_DEPTH, maxZ: z1 - 0.2 };+ const wing = (CAMPUS.cellW - CAMPUS.studioDoor) / 2;+ add(planter(`${dept.id}-front-w`, { minX: x0 + 0.3, maxX: x0 + wing, ...frontZ }));+ add(planter(`${dept.id}-front-e`, { minX: x1 - wing, maxX: x1 - 0.3, ...frontZ }));+ // Inside: storage in the corner under the name, a sofa along the west screen by the entrance and a standing table opposite.+ add(cabinet(`${dept.id}-cabinet`, x0 + 0.42, z0 + 1.45, "east", tint));+ use(`${dept.id}-sofa`, "couch", "sit", sofaSeats(add(sofa(`${dept.id}-sofa`, x0 + 0.24 + SOFA.d / 2, z1 - 2.1, "east", tint))));+ use(`${dept.id}-table`, "coffee", "stand", tableStands(add(highTable(`${dept.id}-table`, x1 - 1.6, z1 - 2.1)), [-Math.PI / 2, Math.PI]));+ }+ }++ // ------------------------------------------------------ streets and plaza+ // An olive tree closes every street at both windows.+ const streetZ = [northMaxZ + CAMPUS.street / 2, ...rowZ.map((z, r) => (r === plazaAfter ? plazaZ : z + rowDepth[r] + CAMPUS.street / 2))];+ streetZ.forEach((z, i) => {+ add(olive(`olive-west-${i}`, planMinX - 0.8, z));+ add(olive(`olive-east-${i}`, planMaxX + 0.8, z));+ });+ rowZ.forEach((z, r) => {+ const z1 = z + rowDepth[r], zc = (z + z1) / 2;+ // Along both windows: a bench on one side of the window spot and a planter on the other (swapped between west and east).+ ([[z + 0.4, zc - 0.85], [zc + 0.85, z1 - 0.4]] as const).forEach(([a, b], run) => {+ const out = 0.95;+ if (run === 0) {+ add(bench(`bench-west-${r}`, planMinX - out - BENCH_DEPTH / 2, a, b, "east"));+ add(planter(`planter-east-${r}`, { minX: planMaxX + out, maxX: planMaxX + out + PLANTER_DEPTH, minZ: a, maxZ: b }));+ } else {+ add(planter(`planter-west-${r}`, { minX: planMinX - out - PLANTER_DEPTH, maxX: planMinX - out, minZ: a, maxZ: b }));+ add(bench(`bench-east-${r}`, planMaxX + out + BENCH_DEPTH / 2, a, b, "west"));+ }+ });+ spots.push({ id: `window-west-${r}`, kind: "window", pose: "stand", room: "floor", x: planMinX - FLOOR_EDGE + 0.9, z: zc, facing: -Math.PI / 2 });+ spots.push({ id: `window-east-${r}`, kind: "window", pose: "stand", room: "floor", x: planMaxX + FLOOR_EDGE - 0.9, z: zc, facing: Math.PI / 2 });+ });+ // The atrium, the campus's heart: the spawn point between two flights of step seating that face it, a large+ // tree behind each. Further out the main boulevard has a planted median with a standing table and an olive.+ for (const sx of [-1, 1] as const) {+ const name = sx < 0 ? "west" : "east";+ use(`atrium-steps-${name}`, "couch", "sit", stepsSeats(add(steps(`atrium-steps-${name}`, sx * 5.6, plazaZ, 5, sx < 0 ? "east" : "west"))));+ add(tree(`atrium-tree-${name}`, sx * 7.9, plazaZ));+ const [a, b] = [sx * 12.4, sx * 17.2].sort((p, q) => p - q);+ add(planter(`median-${name}`, { minX: a, maxX: b, minZ: plazaZ - PLANTER_DEPTH / 2, maxZ: plazaZ + PLANTER_DEPTH / 2 }));+ add(olive(`median-${name}-olive`, sx * 18.3, plazaZ));+ use(`median-${name}-table`, "coffee", "stand", tableStands(add(highTable(`median-${name}-table`, sx * 11.2, plazaZ)), [0, Math.PI]));+ }++ // -------------------------------------------------------------- the commons+ // North-west corner: the focus booths. Three booths under the window, a sofa on a rug and a standing table.+ const boothsZone: CampusZone = { id: "booths", kind: "booths", minX: planMinX, maxX: lead.minX, minZ: topZ, maxZ: northMaxZ };+ zones.push(boothsZone);+ [0, 1, 2].forEach((n) => {+ const item = add(booth(`booth-${n}`, planMinX + 1.0 + n * 1.65, topZ + 1.0, "south", [1, 3, 5][n]));+ spots.push({ id: `booth-${n}`, kind: "window", pose: "stand", room: "floor", ...boothPlace(item) });+ });+ furniture.push(piece("booths-rug", "rug", "floor", planMinX + 2.9, topZ + 5.9, 0, { w: 4.4, d: 3.4 }));+ use("booths-sofa", "couch", "sit", sofaSeats(add(sofa("booths-sofa", planMinX + 0.3 + SOFA.d / 2, topZ + 5.9, "east"))));+ use("booths-table", "coffee", "stand", tableStands(add(highTable("booths-table", planMinX + 4.4, topZ + 5.6)), [-Math.PI / 2, 0]));+ add(olive("booths-olive", lead.minX - 0.9, topZ + 1.2));++ // North-east corner: the library. Two bookcases under the window, reading chairs by the east window, a sofa and a+ // low table on a rug.+ const lx0 = wardrobe.maxX, lx1 = planMaxX;+ zones.push({ id: "library", kind: "library", minX: lx0, maxX: lx1, minZ: topZ, maxZ: northMaxZ });+ const nookSeat = (x: number, z: number): AmbiencePlace => ({ x: x - 0.14, z: z + 0.08, facing: -Math.PI / 2 });+ furniture.push(+ piece("library-shelf-w", "breakBookcase", "floor", lx0 + 2.3, topZ + 0.12 + FURNITURE_SIZE.breakBookcase.d / 2),+ piece("library-shelf-e", "breakBookcase", "floor", lx0 + 5.7, topZ + 0.12 + FURNITURE_SIZE.breakBookcase.d / 2),+ piece("library-rug", "rug", "floor", lx0 + 3.6, topZ + 4.7, 0, { w: 5.2, d: 3.6 }),+ piece("library-table", "lobbyTable", "floor", lx0 + 2.6, topZ + 4.7, Math.PI / 2),+ // The reading chairs turn their backs to the east window and face the room.+ piece("library-nook-n", "readingNook", "floor", lx1 - 0.75, topZ + 3.4, -Math.PI / 2),+ piece("library-nook-s", "readingNook", "floor", lx1 - 0.75, topZ + 6.0, -Math.PI / 2),+ piece("library-plant", "designerPlant", "floor", lx1 - 0.8, topZ + 0.9),+ );+ use("library-sofa", "couch", "sit", sofaSeats(add(sofa("library-sofa", lx0 + 0.3 + SOFA.d / 2, topZ + 4.7, "east"))));+ use("library-nook", "couch", "sit", [nookSeat(lx1 - 0.75, topZ + 3.4), nookSeat(lx1 - 0.75, topZ + 6.0)]);+ use("library-shelf", "shelf", "stand", [{ x: lx0 + 2.3, z: topZ + 1.25, facing: Math.PI }, { x: lx0 + 5.7, z: topZ + 1.25, facing: Math.PI }]);++ // South-west, beside the lobby: the café. The kitchen run under the west window with the island in front of it,+ // standing tables, two sofas along the south window, a large tree in two corners and grasses towards the plaza.+ const cx0 = planMinX, cx1 = reception.minX, cz0 = southMinZ;+ zones.push({ id: "cafe", kind: "cafe", minX: cx0, maxX: cx1, minZ: cz0, maxZ: bottomZ });+ use("cafe-counter", "coffee", "stand", counterStands(add(counter("cafe-counter", cx0 + 0.45, cz0 + 5.4, 4.6, "east")), [-1.1, 1.1]));+ use("cafe-island", "coffee", "stand", counterStands(add(island("cafe-island", cx0 + 2.7, cz0 + 5.4, "east")), [-0.7, 0.7]));+ ([[5.6, 2.7], [8.0, 5.2], [5.8, 7.6]] as const).forEach(([dx, dz], n) => {+ use(`cafe-table-${n}`, "coffee", "stand", tableStands(add(highTable(`cafe-table-${n}`, cx0 + dx, cz0 + dz)), [Math.PI / 2, -Math.PI / 2]));+ });+ use("cafe-sofa-w", "couch", "sit", sofaSeats(add(sofa("cafe-sofa-w", cx1 - 5.2, bottomZ - 0.25 - SOFA.d / 2, "north"))));+ use("cafe-sofa-e", "couch", "sit", sofaSeats(add(sofa("cafe-sofa-e", cx1 - 2.7, bottomZ - 0.25 - SOFA.d / 2, "north"))));+ add(tree("cafe-tree-n", cx1 - 1.4, cz0 + 1.3));+ add(tree("cafe-tree-s", cx0 + 1.0, bottomZ - 1.1));+ add(planter("cafe-bed", { minX: cx0 + 3.2, maxX: cx0 + 8.4, minZ: cz0 + 0.3, maxZ: cz0 + 0.3 + PLANTER_DEPTH }));++ // ------------------------------------------------------------- lead office+ const leadAgents = agents.filter((a) => a.tier === "lead").sort(byArrival).slice(0, 2);+ const ex0 = lead.minX, ex1 = lead.maxX, lcx = (ex0 + ex1) / 2, lz0 = topZ;+ const leadDeskZ = lz0 + 2.6;+ // The executive desk faces south, towards the door. A second lead gets a partner desk to its east; there is never an empty one.+ const leadDesks: DeskSlot[] = [+ { id: "lead:0", x: lcx, z: leadDeskZ, facing: "south", agentId: leadAgents[0]?.agentId ?? null, size: EXECUTIVE_DESK_SIZE },+ ...(leadAgents[1] ? [{ id: "lead:1", x: lcx + 2.65, z: leadDeskZ, facing: "south" as const, agentId: leadAgents[1].agentId, size: PARTNER_DESK_SIZE }] : []),+ ];+ furniture.push(+ // A panelled feature wall with lit bookcases and the star emblem, a rug under the executive desk, guest+ // armchairs, the bar and a leather lounge along the west wall, a globe and a lamp in the east, palms by the door.+ piece("lead-wall", "leadWall", "lead", lcx, lz0 + 0.1 + FURNITURE_SIZE.leadWall.d / 2),+ piece("lead-rug", "executiveRug", "lead", lcx, lz0 + 3.55, 0, { w: 4.6, d: 3.9 }),+ piece("lead-guest-w", "guestChair", "lead", lcx - 0.72, leadDeskZ + 1.2, Math.PI),+ piece("lead-guest-e", "guestChair", "lead", lcx + 0.72, leadDeskZ + 1.2, Math.PI),+ piece("lead-sofa", "chesterfield", "lead", ex0 + 0.6, lz0 + 4.55, Math.PI / 2),+ piece("lead-table", "loungeTable", "lead", ex0 + 1.62, lz0 + 4.55, Math.PI / 2),+ piece("lead-lamp", "floorLamp", "lead", ex0 + 0.4, lz0 + 3.1),+ piece("lead-bar", "executiveBar", "lead", ex0 + 0.36, lz0 + 1.85, Math.PI / 2),+ piece("lead-globe", "globe", "lead", ex1 - 0.75, lz0 + 4.3),+ piece("lead-lamp-e", "floorLamp", "lead", ex1 - 0.34, lz0 + 2.9),+ piece("lead-plant", "plant", "lead", ex0 + 0.55, northMaxZ - 0.55),+ piece("lead-plant-e", "plant", "lead", ex1 - 0.55, northMaxZ - 0.55),+ // The office dog's baskets: here beside the bookcase, in the team room and in the break room.+ piece("lead-dog", "dogBed", "lead", ex1 - 0.58, lz0 + 0.98),+ );+ spots.push({ id: "shelf-lead", kind: "shelf", pose: "stand", x: lcx + 2.65, z: topZ + 1.05, facing: Math.PI, room: "lead" });++ // --------------------------------------------------------------- team room+ const tableZ = topZ + 4.9;+ furniture.push(+ // A walnut table on a wool rug, the board on a slat wall, a credenza under the display and one along the+ // west wall, fiddle-leaf figs in both corners by the door.+ piece("team-rug", "teamRug", "team", 0, tableZ, 0, { w: 5.4, d: 4.0 }),+ piece("team-table", "meetingTable", "team", 0, tableZ),+ piece("team-wall", "teamWall", "team", 0, topZ + 0.06 + FURNITURE_SIZE.teamWall.d / 2),+ piece("team-board", "teamBoard", "team", 0, topZ + 0.25),+ piece("team-credenza", "credenza", "team", 2.7, topZ + 0.19 + FURNITURE_SIZE.credenza.d / 2),+ piece("team-credenza-w", "credenza", "team", team.minX + 0.07 + FURNITURE_SIZE.credenza.d / 2, tableZ, Math.PI / 2),+ piece("team-plant", "designerPlant", "team", team.maxX - 0.6, northMaxZ - 0.6),+ piece("team-plant-w", "designerPlant", "team", team.minX + 0.6, northMaxZ - 0.6, Math.PI / 2),+ piece("team-dog", "dogBed", "team", team.minX + 0.62, topZ + 0.95),+ );+ spots.push({ id: "board", kind: "board", pose: "stand", x: -0.6, z: topZ + 1.2, facing: Math.PI, room: "team" });+ // Meeting chairs: three per long side of the team table.+ for (let i = 0; i < 3; i += 1) {+ const x = -1.1 + i * 1.1;+ spots.push({ id: `meeting-n${i}`, kind: "meeting", pose: "sit", x, z: tableZ - 1.25, facing: 0, room: "team" });+ spots.push({ id: `meeting-s${i}`, kind: "meeting", pose: "sit", x, z: tableZ + 1.25, facing: Math.PI, room: "team" });+ }++ // ---------------------------------------------------------------- wardrobe+ const wx0 = wardrobe.minX, wx1 = wardrobe.maxX, wcx = (wx0 + wx1) / 2;+ const mirrorZ = topZ + 3.6;+ // Where the person stands to change: on the round rug in front of the mirror.+ const dressAt: Point = { x: wx0 + 2.0, z: mirrorZ };+ furniture.push(+ // An open oak wardrobe along the north wall, a bulb-lit mirror on the west wall with a round rug in front of+ // it, a tailor's dummy, a bench on the east side, a fig and a coat stand by the door.+ piece("wardrobe-wall", "wardrobeWall", "wardrobe", wcx, topZ + 0.06 + FURNITURE_SIZE.wardrobeWall.d / 2),+ piece("wardrobe-rug", "roundRug", "wardrobe", dressAt.x, dressAt.z, 0, { w: 2.8, d: 2.8 }),+ piece("wardrobe-mirror", "dressingMirror", "wardrobe", wx0 + 0.06 + FURNITURE_SIZE.dressingMirror.d / 2, mirrorZ, Math.PI / 2),+ piece("wardrobe-dummy", "tailorDummy", "wardrobe", wx1 - 0.6, topZ + 1.4, -Math.PI / 4),+ piece("wardrobe-bench", "dressingBench", "wardrobe", wx1 - 0.06 - FURNITURE_SIZE.dressingBench.d / 2, topZ + 3.9, -Math.PI / 2),+ piece("wardrobe-plant", "designerPlant", "wardrobe", wx0 + 0.5, northMaxZ - 0.5),+ piece("wardrobe-stand", "coatStand", "wardrobe", wx1 - 0.4, northMaxZ - 0.45),+ );+ spots.push({ id: "shelf-wardrobe", kind: "shelf", pose: "stand", x: wcx - 1.0, z: topZ + 1.3, facing: Math.PI, room: "wardrobe" });++ // ------------------------------------------------------------------- lobby+ const rx0 = reception.minX, rx1 = reception.maxX;+ const deskAt: Point = { x: reception.arch?.x ?? rx0 + 4.6, z: southMinZ + 2.5 };+ const loungeX = 5.4, loungeZ = southMinZ + 5.6;+ furniture.push(+ // West edge, north to south: the brand wall, the way into the café, the elevator with its mat and the award+ // case. The reception desk stands west of the boulevard's axis, the waiting lounge east of it.+ piece("elevator", "elevator", "reception", rx0 + 0.25, bottomZ - 2.6, Math.PI / 2),+ piece("reception-desk", "receptionDesk", "reception", deskAt.x, deskAt.z),+ piece("lobby-brand-wall", "brandWall", "reception", rx0 + 0.22, southMinZ + 2.55, Math.PI / 2),+ piece("lobby-awards", "awardCase", "reception", rx0 + 0.26, bottomZ - 0.7, Math.PI / 2),+ piece("lobby-mat", "entranceMat", "reception", rx0 + 1.3, bottomZ - 2.6, 0, { w: 1.1, d: 1.9 }),+ piece("lobby-olive-s", "oliveTree", "reception", rx0 + 2.9, bottomZ - 0.75),+ piece("lobby-olive-se", "oliveTree", "reception", rx1 - 0.75, bottomZ - 0.75),+ piece("lobby-rug", "lobbyRug", "reception", loungeX, loungeZ + 0.75, 0, { w: 4.8, d: 2.9 }),+ piece("lobby-sofa", "lobbySofa", "reception", loungeX, loungeZ),+ piece("lobby-table", "lobbyTable", "reception", loungeX, loungeZ + 1.05),+ piece("lobby-chair-w", "lobbyArmchair", "reception", loungeX - 1.8, loungeZ + 1.1, Math.PI / 2),+ piece("lobby-chair-e", "lobbyArmchair", "reception", loungeX + 1.8, loungeZ + 1.1, -Math.PI / 2),+ piece("lobby-side-table", "sideTable", "reception", loungeX - 1.5, loungeZ - 0.05),+ piece("lobby-lamp", "lobbyLamp", "reception", loungeX + 1.5, loungeZ - 0.1),+ );+ spots.push(+ // Two on the sofa (facing south), one in each armchair (facing the table).+ { id: "couch-lobby-1", kind: "couch", pose: "sit", x: loungeX - 0.55, z: loungeZ + 0.15, facing: 0, room: "reception" },+ { id: "couch-lobby-2", kind: "couch", pose: "sit", x: loungeX + 0.55, z: loungeZ + 0.15, facing: 0, room: "reception" },+ { id: "couch-lobby-w", kind: "couch", pose: "sit", x: loungeX - 1.78, z: loungeZ + 1.1, facing: Math.PI / 2, room: "reception" },+ { id: "couch-lobby-e", kind: "couch", pose: "sit", x: loungeX + 1.78, z: loungeZ + 1.1, facing: -Math.PI / 2, room: "reception" },+ );++ // -------------------------------------------------------------- break room+ const bx0 = breakRoom.minX, bx1 = breakRoom.maxX, bz0 = southMinZ;+ const barX = bx1 - 2.9;+ furniture.push(+ // An L-shaped sectional in the south-west round an oak coffee table on a kilim; the bookcase wall, the+ // reading nook and the dog's basket in the north-west; the coffee bar with the treat jar on the north wall;+ // foosball, beanbags, the water station and the arcade on its pixel mat in the east; monsteras in two corners.+ piece("break-rug", "breakRug", "break", bx0 + 3.4, bottomZ - 3.1, 0, { w: 5.2, d: 4.2 }),+ piece("break-sofa-a", "breakSofa", "break", bx0 + 3.3, bottomZ - 1.7, Math.PI),+ piece("break-sofa-b", "breakSofa", "break", bx0 + 1.75, bottomZ - 3.25, Math.PI / 2),+ piece("break-sofa-corner", "breakSofaCorner", "break", bx0 + 1.75, bottomZ - 1.7, Math.PI),+ piece("break-table", "breakTable", "break", bx0 + 3.35, bottomZ - 3.2),+ piece("coffee-bar", "coffeeBar", "break", barX, bz0 + 0.5),+ piece("break-treats", "treatJar", "break", barX + 2.05, bz0 + 0.5),+ piece("water-cooler", "waterCooler", "break", bx1 - 0.45, bz0 + 2.6, -Math.PI / 2),+ piece("arcade", "arcade", "break", bx1 - 0.6, bottomZ - 0.7, -Math.PI / 2),+ piece("arcade-mat", "arcadeMat", "break", bx1 - 1.5, bottomZ - 0.7, 0, { w: 1.1, d: 1.2 }),+ piece("foosball", "foosball", "break", bx1 - 3.0, bz0 + 4.8),+ piece("beanbag-a", "beanbag", "break", bx1 - 3.7, bottomZ - 1.9),+ piece("beanbag-b", "beanbag", "break", bx1 - 2.5, bottomZ - 1.25),+ piece("break-shelf", "breakBookcase", "break", bx0 + 2.4, bz0 + 0.06 + FURNITURE_SIZE.breakBookcase.d / 2),+ piece("break-nook", "readingNook", "break", bx0 + 0.53, bz0 + 0.58),+ piece("break-dog", "dogBed", "break", bx0 + 0.62, bz0 + 1.6),+ piece("break-plant", "breakPlant", "break", bx0 + 0.6, bottomZ - 0.6),+ piece("break-plant-e", "breakPlant", "break", bx1 - 0.45, bz0 + 7.0),+ );+ spots.push(+ // Sofa module A faces north, module B faces east; the reading nook's armchair faces south, into the room.+ { id: "couch-a1", kind: "couch", pose: "sit", x: bx0 + 2.7, z: bottomZ - 1.85, facing: Math.PI, room: "break" },+ { id: "couch-a2", kind: "couch", pose: "sit", x: bx0 + 3.7, z: bottomZ - 1.85, facing: Math.PI, room: "break" },+ { id: "couch-b1", kind: "couch", pose: "sit", x: bx0 + 1.9, z: bottomZ - 3.7, facing: Math.PI / 2, room: "break" },+ { id: "couch-b2", kind: "couch", pose: "sleep", x: bx0 + 1.9, z: bottomZ - 2.65, facing: Math.PI / 2, room: "break" },+ { id: "couch-nook", kind: "couch", pose: "sit", x: bx0 + 0.61, z: bz0 + 0.72, facing: 0, room: "break" },+ { id: "coffee-1", kind: "coffee", pose: "stand", x: barX - 0.6, z: bz0 + 1.4, facing: Math.PI, room: "break" },+ { id: "coffee-2", kind: "coffee", pose: "stand", x: barX + 0.6, z: bz0 + 1.4, facing: Math.PI, room: "break" },+ { id: "cooler", kind: "cooler", pose: "stand", x: bx1 - 1.2, z: bz0 + 2.6, facing: Math.PI / 2, room: "break" },+ { id: "arcade", kind: "arcade", pose: "stand", x: bx1 - 1.45, z: bottomZ - 0.7, facing: Math.PI / 2, room: "break" },+ { id: "beanbag-a", kind: "beanbag", pose: "sit", x: bx1 - 3.7, z: bottomZ - 1.9, facing: Math.PI * 1.25, room: "break" },+ { id: "beanbag-b", kind: "beanbag", pose: "sit", x: bx1 - 2.5, z: bottomZ - 1.25, facing: Math.PI * 1.25, room: "break" },+ { id: "shelf-break", kind: "shelf", pose: "stand", x: bx0 + 2.2, z: bz0 + 1.1, facing: Math.PI, room: "break" },+ );++ // ------------------------------------------------------------- spawn point+ furniture.push(+ // In the middle of the atrium: the pad, and the terminal on it facing the lobby.+ piece("spawn-pad", "spawnPad", "floor", plaza.x, plaza.z),+ piece("spawn-terminal", "spawnTerminal", "floor", plaza.x, plaza.z),+ );++ // ------------------------------------------------------------- checkpoints+ const elevator = furniture.find((f) => f.id === "elevator")!;+ // The spawn point's ring surrounds the terminal; "walk there" and newcomers stand south of it, facing the screen.+ const arrival: Point = { x: plaza.x, z: plaza.z + SPAWN.approach };+ // Every stop is the place in front of the thing the person uses there.+ const checkpoints: Checkpoint[] = [+ { id: "spawn", room: "floor", x: plaza.x, z: plaza.z, radius: SPAWN.reach, approach: arrival },+ // The reception desk is the one directory and help station.+ { id: "manage", room: "reception", x: deskAt.x, z: deskAt.z + 1.7, radius: 1.2 },+ // In front of the team board.+ { id: "team", room: "team", x: 0.9, z: topZ + 1.6, radius: 1.1 },+ // In front of the dressing mirror.+ { id: "wardrobe", room: "wardrobe", x: dressAt.x, z: dressAt.z, radius: 1.5 },+ // Across the executive desk, behind the guest chairs.+ { id: "lead", room: "lead", x: lcx, z: leadDeskZ + 2.4, radius: 1.3 },+ // At the coffee bar.+ { id: "break", room: "break", x: barX, z: bz0 + 2.0, radius: 1.6 },+ // The elevator's doors face east into the lobby; its checkpoint is the floor in front of them.+ { id: "elevator", room: "reception", x: elevator.x + 0.95, z: elevator.z, radius: 1.0 },+ ];++ // --------------------------------------------------------------- obstacles+ const walls = uniqueWalls(rooms);+ const benchDesks = departments.flatMap((d) => d.desks);+ const obstacles: Rect[] = [+ ...walls.map(wallRect),+ ...[...leadDesks, ...benchDesks].map(deskRect),+ ...leadDesks.map(executiveChairRect),+ // Bench desk chairs and the meeting chairs: nobody walks through a chair.+ ...benchDesks.map((d) => chairRect(seatOf(d))),+ ...spots.filter((s) => s.kind === "meeting").map((s) => chairRect(s)),+ ...departments.map(studioWallRect),+ ...furniture.filter((f) => FURNITURE_SIZE[f.kind].solid).map(footprint),+ // Oak planter boxes at the bench ends.+ ...departments.flatMap(benchPlanters).map((p) => p.rect),+ ...ambience.flatMap(ambienceObstacles),+ // The posts of the lobby'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,+ })),+ ];++ return {+ variant: "agents", departments, studios, zones, ambience,+ lead: { minX: lead.minX, maxX: lead.maxX, minZ: lead.minZ, maxZ: lead.maxZ, desks: leadDesks },+ rooms, walls, furniture, spots, checkpoints, obstacles,+ // The person starts in front of the elevator.+ spawn: { x: rx0 + 1.4, z: bottomZ - 2.6 },+ arrival,+ floor: {+ // The navigation grid starts at this corner. Desks stand on a 0.85 m raster from their studio's centre, so+ // the place beside a chair would fall exactly on a cell boundary for every other cluster width; an eighth+ // of a cell keeps all of them clear of one.+ minX: planMinX - FLOOR_EDGE + RAIL_CLEARANCE - GRID_NUDGE, maxX: planMaxX + FLOOR_EDGE - RAIL_CLEARANCE,+ minZ: topZ - FLOOR_EDGE + RAIL_CLEARANCE, maxZ: bottomZ + FLOOR_EDGE - RAIL_CLEARANCE,+ },+ bounds: { minX: planMinX - FLOOR_EDGE, maxX: planMaxX + FLOOR_EDGE, minZ: topZ - FLOOR_EDGE, maxZ: bottomZ + FLOOR_EDGE },+ };+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/canvasMaterials.ts b/jarvis/ui/web/frontend/src/components/society/office/canvasMaterials.tsindex 70099be8d0..340967536f 100644--- a/jarvis/ui/web/frontend/src/components/society/office/canvasMaterials.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/canvasMaterials.ts@@ -7,13 +7,29 @@ import { CanvasTexture, MeshStandardMaterial, SRGBColorSpace, type Texture } froconst textureCache = new Map<string, Texture | null>();/**- * A canvas-drawn texture, drawn once per key and cached. Returns null where no- * 2D canvas exists (SSR, tests without canvas); callers fall back to a colour.+ * A canvas-drawn texture, drawn once per key and cached for the session. Only+ * for keys from a fixed set (a kind, a palette entry, a locale's own text): a+ * key made from something the user names would grow the cache without end,+ * and belongs to `ownedCanvasTexture`. Returns null where no 2D canvas exists+ * (SSR, tests without canvas); callers fall back to a colour.*/export function cachedCanvasTexture(key: string, width: number, height: number, draw: (ctx: CanvasRenderingContext2D, w: number, h: number) => void,): Texture | null {if (textureCache.has(key)) return textureCache.get(key) ?? null;+ const texture = ownedCanvasTexture(width, height, draw);+ textureCache.set(key, texture);+ return texture;+}++/**+ * A canvas-drawn texture that belongs to its caller, who disposes it when the+ * thing it is drawn for goes: for text the user chose (a team's name).+ * Returns null where no 2D canvas exists.+ */+export function ownedCanvasTexture(+ width: number, height: number, draw: (ctx: CanvasRenderingContext2D, w: number, h: number) => void,+): Texture | null {const canvas = typeof document !== "undefined" ? document.createElement("canvas") : null;let ctx: CanvasRenderingContext2D | null = null;try {@@ -32,7 +48,6 @@ export function cachedCanvasTexture(made.anisotropy = 4;texture = made;}- textureCache.set(key, texture);return texture;}diff --git a/jarvis/ui/web/frontend/src/components/society/office/deskKit.test.ts b/jarvis/ui/web/frontend/src/components/society/office/deskKit.test.tsindex 8dccfd70a6..8ed7e3afd3 100644--- a/jarvis/ui/web/frontend/src/components/society/office/deskKit.test.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/deskKit.test.ts@@ -1,9 +1,27 @@import { describe, expect, it } from "vitest";-import { dressDesk, dressOfficeDesk, kitPlacements, oakPlanterPlacements, officeKitPlacements, planterPlacements } from "./deskKit";+import { dressDesk, dressOfficeDesk, kitPlacements, LEAD_CHAIR_COLOUR, leadMark, leadMarkPlacements, oakPlanterPlacements, officeKitPlacements, planterPlacements } from "./deskKit";import { allDesks, benchPlanters, buildOfficeLayout, chairRect, deskRect, seatOf, type Rect } from "./officeLayout";+import { DEPARTMENT_ZONES } from "./officePalette";const overlaps = (a: Rect, b: Rect) => a.minX < b.maxX && b.minX < a.maxX && a.minZ < b.maxZ && b.minZ < a.maxZ;+/** A hex colour in CIE L*a*b* (D65). */+function lab(hex: string): [number, number, number] {+ const [r, g, b] = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255)+ .map((v) => (v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4));+ const f = (t: number) => (t > 0.008856 ? Math.cbrt(t) : 7.787 * t + 16 / 116);+ const x = f((r * 0.4124 + g * 0.3576 + b * 0.1805) / 0.95047);+ const y = f(r * 0.2126 + g * 0.7152 + b * 0.0722);+ const z = f((r * 0.0193 + g * 0.1192 + b * 0.9505) / 1.08883);+ return [116 * y - 16, 500 * (x - y), 200 * (y - z)];+}++/** How far apart two colours look (CIE76); about 2 is just noticeable, 30 is unmistakable. */+function deltaE(a: string, b: string): number {+ const [l1, a1, b1] = lab(a), [l2, a2, b2] = lab(b);+ return Math.hypot(l1 - l2, a1 - a2, b1 - b2);+}+const roster = (n: number) => Array.from({ length: n }, (_, i) => ({agentId: `a${i}`, name: `A${i}`, tier: "specialist" as const, providerLabel: `ws${i % 3}`, state: "working" as const, createdMs: i,}));@@ -95,6 +113,32 @@ describe("agents floor office kit", () => {}});+ it("marks a team lead's place with a red chair and the team's colour, from parts the kit already draws and one plain box", () => {+ const mark = leadMark("#8aa391");+ const all = leadMarkPlacements("#8aa391");+ expect(all).toHaveLength(mark.chair.length + mark.mat.length + mark.stand.length);+ expect([...new Set(all.map((p) => p.part))].sort()).toEqual(["brassTrim", "felt", "oakSlat", "paper"]);+ // The chair is one deep red in every studio, so it never blends into chairs that already wear the team's colour;+ // mat and name plate wear the team's colour. The name line is paper, oak and bronze are their own.+ for (const part of mark.chair.filter((p) => p.part === "felt")) expect(part.c).toBe(LEAD_CHAIR_COLOUR);+ for (const part of [...mark.mat, ...mark.stand].filter((p) => p.part === "felt")) expect(part.c).toBe("#8aa391");+ // It keeps a clear distance (CIE76) from every studio's seat fabric, wall panel and rug and from the dark mesh back.+ for (const zone of DEPARTMENT_ZONES) {+ for (const colour of [zone.seat, zone.panel, zone.rug]) expect(deltaE(LEAD_CHAIR_COLOUR, colour)).toBeGreaterThan(30);+ }+ expect(deltaE(LEAD_CHAIR_COLOUR, "#1c1f24")).toBeGreaterThan(30);+ expect(leadMark("#c2a24c").mat[0].c).toBe("#c2a24c");+ // A shell of three panels with a cap each and a seat pad; one mat; a base, a plate, a name line and a top edge.+ expect(mark.chair.map((p) => p.part).sort()).toEqual(["brassTrim", "brassTrim", "brassTrim", "felt", "felt", "felt", "felt"]);+ expect(mark.mat.map((p) => p.part)).toEqual(["felt"]);+ expect(mark.stand.map((p) => p.part).sort()).toEqual(["brassTrim", "felt", "oakSlat", "paper"]);+ // The stand keeps clear of the takeaway cup (0.64, 0.07) and of the mouse (0.33, 0.22).+ for (const part of mark.stand) {+ expect(Math.hypot(part.p[0] - 0.64, part.p[2] - 0.07), part.part).toBeGreaterThan(0.15);+ expect(part.p[0] - 0.33, part.part).toBeGreaterThan(0.2);+ }+ });+it("never reaches into the monitor, and keeps clear of the desk's mug", () => {for (let i = 0; i < 80; i += 1) {for (const part of officeKitPlacements(dressOfficeDesk(`o:${i}`, true))) {diff --git a/jarvis/ui/web/frontend/src/components/society/office/deskKit.ts b/jarvis/ui/web/frontend/src/components/society/office/deskKit.tsindex 63dadf8190..9a4fc78ea0 100644--- a/jarvis/ui/web/frontend/src/components/society/office/deskKit.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/deskKit.ts@@ -35,7 +35,9 @@ export type DressingPart =| "letterTray" | "trayPost" | "paper" | "page" | "folder"| "tabletBody" | "tabletScreen" | "tabletStand" | "phoneBody" | "phoneScreen" | "dock"| "penCup" | "pencil" | "frame" | "photo" | "cup" | "cupLid" | "cupSleeve"- | "oakPlanter" | "oakSlat" | "brassTrim";+ | "oakPlanter" | "oakSlat" | "brassTrim"+ // A plain box in a team's colour: what marks a team lead's place.+ | "felt";/*** One part in place. `r` is an Euler rotation applied in YXZ order (a yaw,@@ -147,7 +149,7 @@ function laptop(): Placement[] {];}-/** An anglepoise desk lamp; its head reaches out along +z. */+/** A balanced-arm desk lamp; its head reaches out along +z. */function lamp(colour: string): Placement[] {return [{ part: "lampBase", p: [0, TOP + 0.0075, 0], s: [0.06, 0.015, 0.06], c: colour },@@ -529,6 +531,72 @@ export function officeKitPlacements(kit: OfficeKit): Placement[] {return out;}+/**+ * Where `DeskInstances` stands the task chair behind a desk, and the chair's backrest as `OfficeChairs` builds it:+ * a reclined cone segment half a metre high whose middle is 0.86 m up, 0.55 m from an axis in front of the seat.+ */+const LEAD_CHAIR = { z: 0.62, axisZ: -0.288, radius: 0.55, midY: 0.86, recline: 0.197, seatTop: 0.522 } as const;+/** The name stand's plate leans back this far from upright, so it faces a camera looking down at forty degrees. */+const STAND_TILT = -0.7;+/** The stand is turned towards the view from the south-east. */+const STAND_YAW = 0.66;+/**+ * The lead's chair wears one deep red in every studio. In the team's own colour it vanished among the studio's+ * chairs, which already wear that colour; this red keeps its distance from every studio's seat fabric, wall panel+ * and rug and from the chairs' dark mesh (deskKit.test.ts measures it).+ */+export const LEAD_CHAIR_COLOUR = "#a3202f";++/**+ * What marks a team lead's place, in desk-local space:+ * - `chair`: a deep red shell on the back of the task chair (three panels round its curve) with a bronze cap along+ * its top edge, and a pad on the seat in the same red. The chair is what the camera sees first, and it stays when the lead is away.+ * - `mat`: a chair mat in the team's colour on the floor under the chair, which is what reads from the overview.+ * - `stand`: a tent card on the desk's front right corner: an oak base and a plate in the team's colour leaning+ * back towards the camera, with a pale name line and a bronze top edge.+ * Made of parts the desk kit already draws, plus one plain coloured box; everything stays inside the desk and the+ * strip its chair rolls on.+ */+export function leadMark(colour: string): { chair: Placement[]; mat: Placement[]; stand: Placement[] } {+ const { recline } = LEAD_CHAIR;+ const r = LEAD_CHAIR.radius + 0.03;+ const chair: Placement[] = [];+ for (const [theta, h] of [[0, 0.44], [-0.29, 0.4], [0.29, 0.4]] as const) {+ const x = Math.sin(theta) * r, z = LEAD_CHAIR.z + LEAD_CHAIR.axisZ + Math.cos(theta) * r;+ const y = LEAD_CHAIR.midY - (theta === 0 ? 0 : 0.012);+ chair.push({ part: "felt", p: [x, y, z], r: [recline, theta, 0], s: [0.172, h, 0.02], c: LEAD_CHAIR_COLOUR });+ // The cap sits on the panel's top edge, in the panel's own lean.+ const up = h / 2 + 0.011;+ chair.push({+ part: "brassTrim", r: [recline, theta, 0], s: [0.176, 0.022, 0.034],+ p: [x + up * Math.sin(recline) * Math.sin(theta), y + up * Math.cos(recline), z + up * Math.sin(recline) * Math.cos(theta)],+ });+ }+ // The pad rests in the seat's dish and stands a few millimetres proud of its rim.+ chair.push({ part: "felt", p: [0, LEAD_CHAIR.seatTop + 0.007, LEAD_CHAIR.z - 0.02], s: [0.36, 0.018, 0.34], c: LEAD_CHAIR_COLOUR });++ // Above the studio's rug (its field lies at 7 mm), below the light pools (12 mm).+ const mat: Placement[] = [{ part: "felt", p: [0, 0.009, 0.725], s: [1.15, 0.003, 0.95], c: colour }];++ const half = 0.065, foot = TOP + 0.014;+ const up = Math.cos(STAND_TILT) * half, back = Math.sin(STAND_TILT) * half;+ // The plate's outward normal, for what lies on its face.+ const ny = -Math.sin(STAND_TILT), nz = Math.cos(STAND_TILT);+ const stand = assembly(0.66, 0.325, STAND_YAW, [+ { part: "oakSlat", p: [0, TOP + 0.007, -0.04], s: [0.17, 0.014, 0.1] },+ { part: "felt", p: [0, foot + up, back], r: [STAND_TILT, 0, 0], s: [0.16, half * 2, 0.006], c: colour },+ { part: "paper", p: [0, foot + up + ny * 0.0045, back + nz * 0.0045], r: [STAND_TILT, 0, 0], s: [0.11, 0.024, 0.003], c: "#f6f3ec" },+ { part: "brassTrim", p: [0, foot + up * 2, back * 2], r: [STAND_TILT, 0, 0], s: [0.164, 0.008, 0.012] },+ ]);+ return { chair, mat, stand };+}++/** Every part of a team lead's mark; see `leadMark`. */+export function leadMarkPlacements(colour: string): Placement[] {+ const { chair, mat, stand } = leadMark(colour);+ return [...chair, ...mat, ...stand];+}+/** The agents floor's planter: taller than the coding floor's box, so it also screens the bench end. */export const OAK_PLANTER_H = 0.52;diff --git a/jarvis/ui/web/frontend/src/components/society/office/hallFloorLayout.test.ts b/jarvis/ui/web/frontend/src/components/society/office/hallFloorLayout.test.tsnew file mode 100644index 0000000000..822e4eab9f--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/hallFloorLayout.test.ts@@ -0,0 +1,106 @@+import { describe, expect, it } from "vitest";+import { REWARD_IDS } from "../progression/levelCatalog";+import { arrivalPose } from "./officeFloors";+import { buildHallLayout, LEVEL_HALL } from "./hallFloorLayout";+import { buildOfficeLayout, FURNITURE_SIZE, footprint } from "./officeLayout";+import { buildNavGrid, findPath, isWalkable } from "./officeNav";+import { floorForKey, PANEL_FLOORS } from "./ElevatorPanel";+import { callDirection } from "./ElevatorCallButton";+import { floorLevel, OFFICE_FLOORS } from "./officeStore";++describe("Level Hall floor", () => {+ const layout = buildHallLayout();+ const hall = layout.rooms.find((r) => r.kind === "levels")!;+ const grid = buildNavGrid(layout);++ it("is a floor of its own: the hall behind a door, a foyer with the elevator, nobody's desk", () => {+ expect(layout.variant).toBe("hall");+ expect(layout.rooms.map((r) => r.kind)).toEqual(["levels"]);+ expect(layout.departments).toEqual([]);+ expect(layout.lead.desks).toEqual([]);+ expect(layout.checkpoints.map((c) => c.id)).toEqual(["studio", "levels", "elevator"]);+ expect(hall.walled).toBe(true);+ expect(hall.maxX - hall.minX).toBeCloseTo(LEVEL_HALL.width, 9);+ expect(hall.maxZ - hall.minZ).toBeCloseTo(LEVEL_HALL.depth, 9);+ expect(hall.doors).toEqual([{ side: "south", at: 0, width: LEVEL_HALL.door }]);+ // The same plan every time.+ expect(buildHallLayout()).toEqual(layout);+ // Nothing of it is left on the agents floor.+ const below = buildOfficeLayout([]);+ expect(below.rooms.some((r) => r.kind === "levels")).toBe(false);+ expect(below.checkpoints.some((c) => c.id === "studio" || c.id === "levels")).toBe(false);+ });++ it("keeps the hall's fittings: rank wall, dais, a display case per reward up the runner, the guide", () => {+ const pedestals = layout.furniture.filter((f) => f.kind === "rewardPedestal");+ expect(pedestals.map((p) => p.id)).toEqual(REWARD_IDS.map((_, n) => `level-pedestal-${n}`));+ const cx = (hall.minX + hall.maxX) / 2;+ pedestals.forEach((p, n) => {+ const box = footprint(p);+ expect(box.minX > hall.minX && box.maxX < hall.maxX && box.minZ > hall.minZ && box.maxZ < hall.maxZ, p.id).toBe(true);+ expect(Math.sign(p.x - cx)).toBe(n % 2 === 0 ? -1 : 1);+ if (n >= 2) {+ expect(p.z).toBeLessThan(pedestals[n - 2].z);+ // Room to walk between two cases on the same side.+ expect(pedestals[n - 2].z - p.z).toBeGreaterThan(FURNITURE_SIZE.rewardPedestal.d + 0.9);+ }+ });+ const stage = layout.furniture.find((f) => f.kind === "studioStage")!;+ const studio = layout.checkpoints.find((c) => c.id === "studio")!;+ expect([studio.x, studio.z]).toEqual([stage.x, stage.z]);+ expect(stage.z).toBeLessThan(Math.min(...pedestals.map((p) => p.z)));+ expect(layout.furniture.find((f) => f.kind === "levelWall")!.z).toBeLessThan(stage.z);+ const guide = layout.furniture.find((f) => f.kind === "levelGuide")!;+ const levels = layout.checkpoints.find((c) => c.id === "levels")!;+ expect(guide.z).toBeGreaterThan(Math.max(...pedestals.map((p) => p.z)));+ expect(levels.z).toBeLessThan(guide.z);+ for (const item of layout.furniture.filter((f) => f.room === "levels")) {+ expect(item.x > hall.minX && item.x < hall.maxX && item.z > hall.minZ && item.z < hall.maxZ, item.id).toBe(true);+ }+ expect(new Set(layout.furniture.map((f) => f.id)).size).toBe(layout.furniture.length);+ });++ it("lets the person step out of the elevator and walk to both stations through the door", () => {+ const elevator = layout.furniture.find((f) => f.kind === "elevator")!;+ const stop = layout.checkpoints.find((c) => c.id === "elevator")!;+ expect(stop.z).toBeCloseTo(elevator.z, 9);+ expect(stop.x).toBeGreaterThan(elevator.x);+ expect(stop.z).toBeGreaterThan(hall.maxZ);+ // Arriving by elevator: at its stop, facing away from the doors (east).+ const pose = arrivalPose(layout, "elevator");+ expect([pose.x, pose.z]).toEqual([stop.x, stop.z]);+ expect(pose.heading).toBeCloseTo(Math.PI / 2, 9);+ expect(isWalkable(grid, pose)).toBe(true);+ expect(isWalkable(grid, layout.spawn)).toBe(true);+ // The doorway is open, the wall beside it is not.+ expect(isWalkable(grid, { x: 0, z: hall.maxZ })).toBe(true);+ expect(isWalkable(grid, { x: hall.minX + 1.5, z: hall.maxZ })).toBe(false);+ const studio = layout.checkpoints.find((c) => c.id === "studio")!;+ const levels = layout.checkpoints.find((c) => c.id === "levels")!;+ for (const target of [studio.approach!, { x: levels.x, z: levels.z }]) {+ expect(isWalkable(grid, target)).toBe(true);+ const path = findPath(grid, pose, target)!;+ expect(path).not.toBeNull();+ // The only way in is the door.+ const crossing = [pose, ...path].findIndex((p) => p.z < hall.maxZ);+ expect(crossing).toBeGreaterThan(0);+ }+ for (const cp of layout.checkpoints) {+ const solid = layout.furniture.filter((f) => FURNITURE_SIZE[f.kind].solid).map(footprint);+ const at = cp.approach ?? cp;+ expect(solid.some((o) => at.x >= o.minX && at.x <= o.maxX && at.z >= o.minZ && at.z <= o.maxZ), cp.id).toBe(false);+ }+ });++ it("is the top floor of the elevator: listed, numbered, reachable by its key", () => {+ expect(OFFICE_FLOORS).toEqual(["agents", "coding", "arcade", "hall"]);+ expect(floorLevel("hall")).toBe(3);+ expect(PANEL_FLOORS[0]).toBe("hall");+ expect(floorForKey("3")).toBe("hall");+ expect(floorForKey("0")).toBe("agents");+ expect(floorForKey("4")).toBeNull();+ expect(callDirection("hall")).toBe("down");+ expect(callDirection("arcade")).toBe("both");+ expect(callDirection("agents")).toBe("up");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/hallFloorLayout.ts b/jarvis/ui/web/frontend/src/components/society/office/hallFloorLayout.tsnew file mode 100644index 0000000000..fedeee5e50--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/hallFloorLayout.ts@@ -0,0 +1,103 @@+/**+ * The Level Hall's own floor, on top of the building: a small foyer with the+ * elevator, and behind its door the hall of honour.+ *+ * ┌──────── Level Hall ────────┐+ * │ rank wall · studio dais │ north+ * │ display cases either side │+ * │ of the runner │+ * │ service guide │+ * ├────────── door ────────────┤+ * │ elevator foyer │ south+ * └────────────────────────────┘+ *+ * The hall's fittings, north to south: the rank wall on the north wall with+ * the studio's round dais in front of it (its checkpoint is the dais itself),+ * the runner down the middle with a display case per reward on either side —+ * the lowest unlock at the south end, the highest by the dais, so walking up+ * the runner is climbing the ranks — and at the runner's start the+ * double-sided service guide with its checkpoint on the runner side. Plants+ * frame the dais, olive trees the guide.+ *+ * Takes no input: the hall is the same for everyone; what it shows comes from+ * the level state at render time.+ */+import { REWARD_IDS } from "../progression/levelCatalog";+import {+ FLOOR_EDGE, footprint, FURNITURE_SIZE, RAIL_CLEARANCE, wallRect, wallsOf,+ type Checkpoint, type Furniture, type FurnitureKind, type OfficeLayout, type Rect, type Room, type Spot,+} from "./officeLayout";++/** The hall's width and depth, the foyer's depth, where the dais stands, and how far the runner stays from each end of the hall. */+export const LEVEL_HALL = { width: 9.2, depth: 34, foyer: 6.4, door: 2.4, stageZ: 4.5, stageR: 1.6, roadNorth: 8.2, roadSouth: 6.4, guideZ: 3.3 } as const;+/** The display cases stand this far either side of the hall's centre line, the runner between them. */+export const PEDESTAL_OFFSET_X = 1.8;++/** Build the Level Hall's floor. */+export function buildHallLayout(): OfficeLayout {+ const minX = -LEVEL_HALL.width / 2, maxX = LEVEL_HALL.width / 2;+ const total = LEVEL_HALL.depth + LEVEL_HALL.foyer;+ const topZ = -total / 2, bottomZ = total / 2;+ const hall: Room = { id: "levels", kind: "levels", walled: true, minX, maxX, minZ: topZ, maxZ: topZ + LEVEL_HALL.depth,+ doors: [{ side: "south", at: 0, width: LEVEL_HALL.door }] };+ const cx = 0;+ const piece = (id: string, kind: FurnitureKind, x: number, z: number, rotationY = 0, size?: { w: number; d: number }): Furniture =>+ ({ id, kind, x, z, rotationY, room: "levels", ...(size ? { size } : {}) });+ const stageZ = hall.minZ + LEVEL_HALL.stageZ;+ const roadMinZ = hall.minZ + LEVEL_HALL.roadNorth, roadMaxZ = hall.maxZ - LEVEL_HALL.roadSouth;+ const guideZ = hall.maxZ - LEVEL_HALL.guideZ;+ // Case n (0 = the lowest unlock) stands on the west side when n is even, the east side when odd, rising northwards.+ const rows = Math.ceil(REWARD_IDS.length / 2);+ const pitch = rows > 1 ? (roadMaxZ - roadMinZ - 1.2) / (rows - 1) : 0;+ const pedestals = REWARD_IDS.map((_, n) => piece(`level-pedestal-${n}`, "rewardPedestal",+ cx + (n % 2 === 0 ? -PEDESTAL_OFFSET_X : PEDESTAL_OFFSET_X), roadMaxZ - 0.6 - Math.floor(n / 2) * pitch, n % 2 === 0 ? Math.PI / 2 : -Math.PI / 2));+ // The foyer: the elevator on the west edge like on every floor (doors facing east), its mat, an olive tree in each south corner.+ const elevator: Furniture = { id: "elevator", kind: "elevator", x: minX + 0.25, z: bottomZ - 2.6, rotationY: Math.PI / 2, room: "floor" };+ const furniture: Furniture[] = [+ piece("level-wall", "levelWall", cx, hall.minZ + 0.08 + FURNITURE_SIZE.levelWall.d / 2),+ piece("level-stage", "studioStage", cx, stageZ),+ piece("level-road", "levelRoad", cx, (roadMinZ + roadMaxZ) / 2, 0, { w: 2.2, d: roadMaxZ - roadMinZ }),+ ...pedestals,+ // The guide faces up the runner; its back shows the same screen to whoever comes in through the door.+ piece("level-guide", "levelGuide", cx, guideZ, Math.PI),+ piece("level-plant-nw", "designerPlant", hall.minX + 0.6, hall.minZ + 0.7),+ piece("level-plant-ne", "designerPlant", hall.maxX - 0.6, hall.minZ + 0.7),+ piece("level-olive-sw", "oliveTree", hall.minX + 0.85, hall.maxZ - 0.85),+ piece("level-olive-se", "oliveTree", hall.maxX - 0.85, hall.maxZ - 0.85),+ elevator,+ { id: "foyer-mat", kind: "entranceMat", x: minX + 1.3, z: elevator.z, rotationY: 0, room: "floor", size: { w: 1.1, d: 1.9 } },+ { id: "foyer-olive", kind: "oliveTree", x: maxX - 0.8, z: bottomZ - 0.8, rotationY: 0, room: "floor" },+ ];+ const spots: Spot[] = [];+ const elevatorStop: Checkpoint = { id: "elevator", room: "floor", x: elevator.x + 0.95, z: elevator.z, radius: 1.0 };+ const checkpoints: Checkpoint[] = [+ { id: "studio", room: "levels", x: cx, z: stageZ, radius: LEVEL_HALL.stageR, approach: { x: cx, z: stageZ + 0.6 } },+ { id: "levels", room: "levels", x: cx, z: guideZ - 1.45, radius: 1.1 },+ elevatorStop,+ ];+ const walls = wallsOf(hall);+ const obstacles: Rect[] = [+ ...walls.map(wallRect),+ ...furniture.filter((f) => FURNITURE_SIZE[f.kind].solid).map(footprint),+ ];+ const start = { x: elevator.x + 1.15, z: elevator.z };+ return {+ variant: "hall",+ departments: [],+ // Nobody leads up here; the rect is the foyer so it stays a real place on the floor.+ lead: { minX, maxX, minZ: hall.maxZ, maxZ: bottomZ, desks: [] },+ rooms: [hall],+ walls,+ furniture,+ spots,+ checkpoints,+ obstacles,+ spawn: start,+ arrival: start,+ floor: {+ minX: minX - FLOOR_EDGE + RAIL_CLEARANCE, maxX: maxX + FLOOR_EDGE - RAIL_CLEARANCE,+ minZ: topZ - FLOOR_EDGE + RAIL_CLEARANCE, maxZ: bottomZ + FLOOR_EDGE - RAIL_CLEARANCE,+ },+ bounds: { minX: minX - FLOOR_EDGE, maxX: maxX + FLOOR_EDGE, minZ: topZ - FLOOR_EDGE, maxZ: bottomZ + FLOOR_EDGE },+ };+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/leadMark.test.tsx b/jarvis/ui/web/frontend/src/components/society/office/leadMark.test.tsxnew file mode 100644index 0000000000..824c898272--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/leadMark.test.tsx@@ -0,0 +1,237 @@+/**+ * A team lead's place must be found on screen, not only in the plan. These+ * tests put the mark (chair shell, chair mat, name stand) through the real+ * cameras: the default follow view and the campus overview, in a 1600 x 900+ * window, and check how many pixels each piece covers and that nothing on the+ * floor stands between it and the camera.+ */+import { describe, expect, it } from "vitest";+import { Box3, Matrix4, PerspectiveCamera, Vector3 } from "three";+import { pendantHousings } from "./AgentsFloorAmbience";+import { placementMatrix } from "./DeskDressing";+import { leadMark, type Placement } from "./deskKit";+import { TASK_CHAIR_PARTS } from "./OfficeChairs";+import { campusOverview, CAMERA_FOV, FOLLOW_DISTANCE_M, HOME_PITCH_RAD, HOME_YAW_RAD, type CameraPose } from "./officeCamera";+import { buildOfficeLayout, leadDesks, standOf, type DeskSlot, type OfficeAgentInput, type OfficeLayout, type OfficeTeamInput } from "./officeLayout";++const VIEW = { w: 1600, h: 900 } as const;+/** The height the follow view looks at (OfficeCameraRig's target height). */+const TARGET_HEIGHT = 0.8;++const staff = (count: number): OfficeAgentInput[] => Array.from({ length: count }, (_, i) => ({+ agentId: `a${i + 1}`, name: `Agent ${i + 1}`, tier: "specialist", providerLabel: "Codex", state: "idle", createdMs: i,+}));+const teamsOf = (count: number, size: number): OfficeTeamInput[] => Array.from({ length: count }, (_, t) => ({+ id: `team-${t}`, name: `Team ${t}`, createdMs: t, members: Array.from({ length: size }, (_, i) => `a${1 + t * size + i}`),+ // Not the earliest arrival: the lead had to be seated at the head desk.+ leadId: `a${2 + t * size}`,+}));++/** The view that follows the person standing at `at`, as the camera rig sets it. */+function followPose(at: { x: number; z: number }, distance = FOLLOW_DISTANCE_M): CameraPose {+ const horizontal = Math.cos(HOME_PITCH_RAD) * distance;+ return {+ target: [at.x, TARGET_HEIGHT, at.z],+ position: [at.x + Math.sin(HOME_YAW_RAD) * horizontal, Math.sin(HOME_PITCH_RAD) * distance + TARGET_HEIGHT, at.z + Math.cos(HOME_YAW_RAD) * horizontal],+ };+}++function cameraOf(pose: CameraPose): PerspectiveCamera {+ const camera = new PerspectiveCamera(CAMERA_FOV, VIEW.w / VIEW.h, 0.2, 800);+ camera.position.set(...pose.position);+ camera.lookAt(...pose.target);+ camera.updateMatrixWorld(true);+ camera.updateProjectionMatrix();+ return camera;+}++const pixel = (camera: PerspectiveCamera, point: Vector3): { x: number; y: number } => {+ const ndc = point.clone().project(camera);+ return { x: ((ndc.x + 1) / 2) * VIEW.w, y: ((1 - ndc.y) / 2) * VIEW.h };+};+const apart = (a: { x: number; y: number }, b: { x: number; y: number }) => Math.hypot(a.x - b.x, a.y - b.y);++/** A desk's own space in the world, as DeskDressing and DeskInstances place it. */+const deskWorld = (desk: DeskSlot) => new Matrix4().makeRotationY(desk.facing === "north" ? 0 : Math.PI).setPosition(desk.x, 0, desk.z);+const worldOf = (desk: DeskSlot, part: Placement) => deskWorld(desk).multiply(placementMatrix(part));++/** A point of a part's unit box (each side from -0.5 to 0.5) in the world. */+const corner = (matrix: Matrix4, x: number, y: number, z: number) => new Vector3(x, y, z).applyMatrix4(matrix);++/** On-screen length of a plate's two sides, measured across the middle of the face that looks along its local `normal`. */+function faceSides(camera: PerspectiveCamera, matrix: Matrix4, normal: "y" | "z"): [number, number] {+ const p = (u: number, v: number) => pixel(camera, normal === "z" ? corner(matrix, u, v, 0.5) : corner(matrix, u, 0.5, v));+ return [apart(p(-0.5, 0), p(0.5, 0)), apart(p(0, -0.5), p(0, 0.5))];+}++/** Points spread over a plate's visible face, a little inside its edges. */+function faceSamples(matrix: Matrix4, normal: "y" | "z", n = 5): Vector3[] {+ const out: Vector3[] = [];+ for (let i = 0; i < n; i += 1) {+ for (let j = 0; j < n; j += 1) {+ const u = -0.42 + (0.84 * i) / (n - 1), v = -0.42 + (0.84 * j) / (n - 1);+ out.push(normal === "z" ? corner(matrix, u, v, 0.52) : corner(matrix, u, 0.52, v));+ }+ }+ return out;+}++/** Does the straight line from `from` to `to` pass through `box`? */+function crosses(from: Vector3, to: Vector3, box: Box3): boolean {+ let near = 0, far = 1;+ for (const axis of ["x", "y", "z"] as const) {+ const d = to[axis] - from[axis];+ if (Math.abs(d) < 1e-9) {+ if (from[axis] < box.min[axis] || from[axis] > box.max[axis]) return false;+ continue;+ }+ const a = (box.min[axis] - from[axis]) / d, b = (box.max[axis] - from[axis]) / d;+ near = Math.max(near, Math.min(a, b));+ far = Math.min(far, Math.max(a, b));+ if (near > far) return false;+ }+ return true;+}++const boxAt = (desk: DeskSlot, centre: [number, number, number], size: [number, number, number]): Box3 => {+ const turn = desk.facing === "north" ? 1 : -1;+ return new Box3().setFromCenterAndSize(new Vector3(desk.x + turn * centre[0], centre[1], desk.z + turn * centre[2]), new Vector3(...size));+};++/**+ * What can stand in the way on the floor: every desk's monitor and felt screen, every chair's back and whoever sits+ * on it (as boxes a little larger than the things), and the pendant lights. `own` is the lead's desk, whose own+ * chair back the shell lies on: `withOwnChair` leaves that one out.+ */+function occluders(layout: OfficeLayout, own: DeskSlot, withOwnChair: boolean): Box3[] {+ const out: Box3[] = [];+ for (const desk of layout.departments.flatMap((d) => d.desks)) {+ out.push(boxAt(desk, [0, 1.18, -0.224], [0.74, 0.45, 0.04]));+ out.push(boxAt(desk, [0, 0.95, -0.41], [1.46, 0.36, 0.04]));+ // A seated figure: from the seat to the top of the head.+ out.push(boxAt(desk, [0, 0.98, 0.6], [0.5, 0.96, 0.36]));+ if (desk.id !== own.id || withOwnChair) out.push(boxAt(desk, [0, 0.86, 0.87], [0.5, 0.52, 0.1]));+ }+ for (const p of pendantHousings(layout.departments)) {+ out.push(new Box3().setFromCenterAndSize(new Vector3(p.x, p.y, p.z), new Vector3(p.length, p.h + 0.03, p.w + 0.02)));+ }+ return out;+}++/** The share of `points` the camera sees with nothing in `boxes` in front of them. */+function seen(camera: PerspectiveCamera, points: Vector3[], boxes: Box3[]): number {+ const clear = points.filter((point) => !boxes.some((box) => crosses(point, camera.position, box)));+ return clear.length / points.length;+}++const felt = (parts: Placement[]) => parts.filter((p) => p.part === "felt");++describe("a team lead's place", () => {+ const layout = buildOfficeLayout(staff(15), { teams: teamsOf(3, 4) });+ const leads = leadDesks(layout);+ const mark = leadMark("#8aa391");+ const shell = felt(mark.chair).slice(0, 3), plate = felt(mark.stand)[0], mat = mark.mat[0];++ it("is marked at every team's head desk, which faces north: its chair's back looks at the south-east camera", () => {+ expect(leads).toHaveLength(3);+ for (const { desk } of leads) expect(desk.facing).toBe("north");+ });++ it("hugs the real chair: the shell lies on the backrest, the pad on the seat, the mat under it", () => {+ const back = new Box3(), seat = new Box3();+ TASK_CHAIR_PARTS.forEach((part, i) => {+ part.geometry.computeBoundingBox();+ if (part.finish === "mesh") back.union(part.geometry.boundingBox!);+ if (part.finish === "fabric" && i === 2) seat.union(part.geometry.boundingBox!);+ });+ // DeskInstances stands the chair 0.62 m behind the desk's centre.+ const chairZ = 0.62;+ const shellBox = new Box3();+ for (const part of shell) {+ const m = placementMatrix(part);+ for (const x of [-0.5, 0.5]) for (const y of [-0.5, 0.5]) for (const z of [-0.5, 0.5]) shellBox.expandByPoint(corner(m, x, y, z));+ }+ // Behind the mesh (never in front of it, where the sitter is), by a few centimetres at most; inside its height; as wide as it.+ expect(shellBox.max.z - (back.max.z + chairZ)).toBeGreaterThan(0.015);+ expect(shellBox.max.z - (back.max.z + chairZ)).toBeLessThan(0.07);+ expect(shellBox.min.z).toBeGreaterThan(back.min.z + chairZ);+ expect(shellBox.min.y).toBeGreaterThan(back.min.y);+ expect(shellBox.max.y).toBeLessThan(back.max.y + 0.01);+ expect(Math.abs(shellBox.max.x - back.max.x)).toBeLessThan(0.05);+ expect(Math.abs(shellBox.min.x - back.min.x)).toBeLessThan(0.05);+ const pad = felt(mark.chair)[3];+ // The pad rests in the seat's dish and stands a few millimetres proud of its rim.+ expect(pad.p[1] - pad.s![1] / 2).toBeLessThan(seat.max.y);+ expect(pad.p[1] + pad.s![1] / 2).toBeGreaterThan(seat.max.y + 0.002);+ expect(pad.p[1] + pad.s![1] / 2).toBeLessThan(seat.max.y + 0.012);+ expect(pad.s![0]).toBeLessThan(seat.max.x - seat.min.x);+ // The mat is flat, above the rug's field (7 mm) and under the light pools (12 mm).+ expect(mat.p[1] - mat.s![1] / 2).toBeGreaterThan(0.007);+ expect(mat.p[1] + mat.s![1] / 2).toBeLessThan(0.012);+ });++ it("reads in the default follow view: chair shell and name plate cover more than ten pixels each way, with nothing in front", () => {+ for (const { desk, dept } of leads) {+ const centre = { x: (dept.minX + dept.maxX) / 2, z: (dept.minZ + dept.maxZ) / 2 };+ // Standing beside the lead, in the middle of its studio, and in its doorway.+ for (const person of [standOf(desk), centre, { x: centre.x, z: dept.maxZ - 0.5 }]) {+ const camera = cameraOf(followPose(person));+ const at = `${desk.id} from ${person.x.toFixed(1)},${person.z.toFixed(1)}`;++ // The chair's shell as one shape: its box on screen.+ const pixels = shell.flatMap((part) => {+ const m = worldOf(desk, part);+ return [-0.5, 0.5].flatMap((x) => [-0.5, 0.5].flatMap((y) => [-0.5, 0.5].map((z) => pixel(camera, corner(m, x, y, z)))));+ });+ const w = Math.max(...pixels.map((p) => p.x)) - Math.min(...pixels.map((p) => p.x));+ const h = Math.max(...pixels.map((p) => p.y)) - Math.min(...pixels.map((p) => p.y));+ expect(Math.min(w, h), `shell ${at}`).toBeGreaterThan(24);+ for (const p of pixels) {+ expect(p.x > 0 && p.x < VIEW.w && p.y > 0 && p.y < VIEW.h, `shell on screen ${at}`).toBe(true);+ }+ const blockers = occluders(layout, desk, false);+ // Its rear face looks away from the desk (local +z).+ for (const part of shell) expect(seen(camera, faceSamples(worldOf(desk, part), "z"), blockers), `shell seen ${at}`).toBe(1);++ // The name plate on the desk: both of its sides, and all of its face.+ const plateWorld = worldOf(desk, plate);+ const [pw, ph] = faceSides(camera, plateWorld, "z");+ expect(Math.min(pw, ph), `plate ${at}`).toBeGreaterThanOrEqual(10);+ expect(seen(camera, faceSamples(plateWorld, "z"), occluders(layout, desk, true)), `plate seen ${at}`).toBe(1);+ }+ }+ });++ it("reads from the overview: the chair mat is a patch of the team's colour ten pixels across, most of it in the open", () => {+ const camera = cameraOf(campusOverview(layout.bounds, VIEW.w / VIEW.h));+ for (const { desk } of leads) {+ const matWorld = worldOf(desk, mat);+ const [mw, md] = faceSides(camera, matWorld, "y");+ expect(Math.min(mw, md), desk.id).toBeGreaterThanOrEqual(10);+ // The chair and whoever sits on it stand on the mat; the rest of it lies open.+ expect(seen(camera, faceSamples(matWorld, "y", 7), occluders(layout, desk, true)), desk.id).toBeGreaterThan(0.55);+ // The shell is still there as a second patch above it.+ for (const part of shell) expect(seen(camera, faceSamples(worldOf(desk, part), "z"), occluders(layout, desk, false)), desk.id).toBe(1);+ }+ });++ it("stays inside the desk top and the strip the chair rolls on", () => {+ const TOP = 0.77;+ for (const part of mark.stand) {+ const m = placementMatrix(part);+ for (const x of [-0.5, 0.5]) for (const y of [-0.5, 0.5]) for (const z of [-0.5, 0.5]) {+ const p = corner(m, x, y, z);+ // On the desk top (1.5 m x 0.8 m), right of the keyboard and the mouse, lower than the monitor's lower edge.+ expect(p.x, part.part).toBeGreaterThan(0.4);+ expect(p.x, part.part).toBeLessThan(0.75);+ expect(p.z, part.part).toBeGreaterThan(0.15);+ expect(p.z, part.part).toBeLessThan(0.4);+ expect(p.y, part.part).toBeGreaterThanOrEqual(TOP - 1e-9);+ expect(p.y, part.part).toBeLessThan(0.96);+ }+ }+ // The mat: narrower than the desk pitch (1.7 m), and it ends well inside the bench's own depth (2.1 m from its middle).+ expect(mat.s![0]).toBeLessThan(1.5);+ expect(0.45 + mat.p[2] + mat.s![2] / 2).toBeLessThan(2.1);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/minimap.test.ts b/jarvis/ui/web/frontend/src/components/society/office/minimap.test.tsindex 65474a3c77..43c93ac6f4 100644--- a/jarvis/ui/web/frontend/src/components/society/office/minimap.test.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/minimap.test.ts@@ -2,8 +2,8 @@ import { describe, expect, it } from "vitest";import { buildOfficeLayout, type OfficeAgentInput } from "./officeLayout";import {MAP_PAINT, STATE_RING, ZOOM_DEFAULT_M, ZOOM_MAX_M, ZOOM_MIN_M, bearingOf, centredTransform, clampToEdge, clampToRect,- clampZoom, columnLabel, compassPosition, compassTicks, drawAgentToken, drawEdgeArrow, drawFloorArt, drawPlayerArrow,- fitTransform, gridLabel, initialOf, inkOn, mapGrid, mapToWorld, pickNearest, placeAt, relativeBearing, shade,+ clampZoom, columnLabel, compassPosition, compassTicks, drawAgentToken, drawEdgeArrow, drawFloorArt, drawMapLabel, drawPlayerArrow,+ fitSheet, fitTransform, minimapCentre, gridLabel, initialOf, inkOn, mapGrid, mapToWorld, pickNearest, placeAt, relativeBearing, shade,worldToMap, yawToBearing, zoomStep,} from "./minimap";@@ -185,15 +185,102 @@ describe("hit testing", () => {expect(pickNearest([{ id: "far", x: edge.x, y: edge.y }], { x: 186, y: 101 }, 10)?.id).toBe("far");});- it("names the place under a point: checkpoint, then room, then department", () => {- const layout = buildOfficeLayout([agent("a1", "codex"), agent("a2", "gemini")]);- const create = layout.checkpoints.find((c) => c.id === "create")!;- expect(placeAt(layout, create)).toEqual({ kind: "checkpoint", id: "create" });+ it("names the place under a point: checkpoint, then room, then studio, then the campus zone", () => {+ const layout = buildOfficeLayout([agent("a1", "codex"), agent("a2", "gemini")], {+ teams: [{ id: "t1", name: "Core", members: ["a1"], createdMs: 1 }],+ });+ const manage = layout.checkpoints.find((c) => c.id === "manage")!;+ expect(placeAt(layout, manage)).toEqual({ kind: "checkpoint", id: "manage" });const lead = layout.rooms.find((r) => r.kind === "lead")!;expect(placeAt(layout, { x: lead.minX + 0.3, z: lead.minZ + 0.3 })).toEqual({ kind: "room", id: "lead" });- const dept = layout.departments[0];- expect(placeAt(layout, { x: dept.minX + 0.2, z: dept.minZ + 0.2 })).toEqual({ kind: "department", label: dept.label });+ // The pool studio has no name of its own; a team's studio carries the team's.+ const [pool, core] = layout.departments;+ expect(placeAt(layout, { x: pool.minX + 0.2, z: pool.minZ + 0.2 })).toEqual({ kind: "department", label: "" });+ expect(placeAt(layout, { x: core.minX + 0.2, z: core.minZ + 0.2 })).toEqual({ kind: "department", label: "Core" });+ // Between the studios: the most specific zone wins where they overlap.+ const zone = (kind: string) => layout.zones!.find((z) => z.kind === kind)!;+ const mid = (kind: string) => ({ x: (zone(kind).minX + zone(kind).maxX) / 2, z: (zone(kind).minZ + zone(kind).maxZ) / 2 });+ const atrium = zone("atrium");+ expect(placeAt(layout, { x: atrium.minX + 0.5, z: atrium.minZ + 0.5 })).toEqual({ kind: "zone", id: "atrium" });+ expect(placeAt(layout, { x: zone("plaza").minX + 0.5, z: atrium.minZ + 0.5 })).toEqual({ kind: "zone", id: "plaza" });+ expect(placeAt(layout, { x: 0, z: zone("boulevard").minZ + 0.5 })).toEqual({ kind: "zone", id: "boulevard" });+ for (const kind of ["plot", "garden", "booths", "library", "cafe"] as const) expect(placeAt(layout, mid(kind)), kind).toEqual({ kind: "zone", id: kind });expect(placeAt(layout, { x: layout.bounds.minX + 0.01, z: 0 })).toBeNull();+ // The coding floor has no zones: open floor stays nameless.+ const coding = buildOfficeLayout([], { variant: "coding" });+ expect(placeAt(coding, coding.arrival)).toEqual({ kind: "checkpoint", id: "launch" });+ expect(placeAt(coding, { x: 0, z: coding.arrival.z + 1.4 })).toBeNull();+ });+});++describe("the minimap's framing", () => {+ const bounds = { minX: -26, maxX: 26, minZ: -23.5, maxZ: 23.5 };++ it("follows the person in the middle of the floor and stays on the floor at its edges", () => {+ // In the open: centred on the person.+ expect(minimapCentre({ x: 3, z: -2 }, bounds, 26)).toEqual({ x: 3, z: -2 });+ // At the elevator by the south window: the card stops a step past the edge instead of showing half a card of night.+ const south = minimapCentre({ x: -9, z: 20.9 }, bounds, 26);+ expect(south.x).toBe(-9);+ expect(south.z).toBeCloseTo(23.5 + 1.5 - 13, 9);+ // In a corner both axes hold.+ expect(minimapCentre({ x: 25, z: -23 }, bounds, 26)).toEqual({ x: 26 + 1.5 - 13, z: -23.5 - 1.5 + 13 });+ // The person is still on the card.+ const t = centredTransform(south, 26, 200, 200);+ const me = worldToMap(t, { x: -9, z: 20.9 });+ expect(me.y).toBeGreaterThan(100);+ expect(me.y).toBeLessThan(200);+ });++ it("centres a floor that is narrower than the view", () => {+ const hall = { minX: -6.2, maxX: 6.2, minZ: -21.8, maxZ: 21.8 };+ const centre = minimapCentre({ x: -3.4, z: 17 }, hall, 26);+ expect(centre.x).toBeCloseTo(0, 9);+ expect(centre.z).toBeCloseTo(21.8 + 1.5 - 13, 9);+ // Zoomed out past the whole floor, the floor sits in the middle whatever the person does.+ expect(minimapCentre({ x: 20, z: 20 }, bounds, 90)).toEqual({ x: 0, z: 0 });+ });+});++describe("the full map's sheet", () => {+ it("takes the plan's shape, so no band of the sheet stays empty", () => {+ const pad = 30, head = 46;+ // A nearly square plan in a wide space: full height, only as wide as the plan needs.+ const square = fitSheet({ minX: 0, maxX: 52, minZ: 0, maxZ: 47 }, 1400, 800, pad, head);+ expect(square.height).toBe(800);+ expect((square.width - pad * 2) / (square.height - head - pad * 2)).toBeCloseTo(52 / 47, 1);+ expect(square.width).toBeLessThan(1000);+ // A plan taller than wide gets a narrow sheet; a wide plan is held by the width instead.+ const tall = fitSheet({ minX: 0, maxX: 52, minZ: 0, maxZ: 81 }, 1400, 800, pad, head);+ expect(tall.width).toBeLessThan(square.width);+ const wide = fitSheet({ minX: 0, maxX: 120, minZ: 0, maxZ: 30 }, 900, 800, pad, head);+ expect(wide.width).toBe(900);+ expect(wide.height).toBeLessThan(800);+ expect((wide.width - pad * 2) / (wide.height - head - pad * 2)).toBeCloseTo(4, 1);+ // Never wider than the cap, never taller than the space.+ expect(fitSheet({ minX: 0, maxX: 100, minZ: 0, maxZ: 40 }, 3000, 900, pad, head).width).toBe(1200);+ });++ it("keeps a long name over its own place: smaller first, then cut", () => {+ const calls: string[] = [];+ let font = "";+ const ctx = {+ set font(value: string) { font = value; },+ get font() { return font; },+ // Seven pixels a letter at 12 px, scaling with the size.+ measureText: (text: string) => ({ width: text.length * 7 * (Number(/([0-9.]+)px/.exec(font)?.[1] ?? 12) / 12) }),+ strokeText: (text: string) => { calls.push(text); },+ fillText: (text: string) => { calls.push(text); },+ } as unknown as CanvasRenderingContext2D;+ drawMapLabel(ctx, "CORE", 0, 0, 12, 800, 80);+ expect(calls.at(-1)).toBe("CORE");+ expect(font).toContain("12px");+ drawMapLabel(ctx, "PLATFORM TEAM", 0, 0, 12, 800, 80);+ expect(calls.at(-1)).toBe("PLATFORM TEAM");+ expect(font).not.toContain(" 12px");+ drawMapLabel(ctx, "THE VERY LONG NAME OF A TEAM", 0, 0, 12, 800, 80);+ expect(calls.at(-1)!.endsWith("…")).toBe(true);+ expect(calls.at(-1)!.length).toBeLessThan(20);});});@@ -229,6 +316,26 @@ describe("drawing", () => {expect(log[log.length - 1]).not.toMatch(/^globalAlpha=0/);});+ it("paints the campus: paved boulevards, planted ground, the free plot, the atrium, trees and every studio's name wall", () => {+ const { ctx, log } = recorder();+ drawFloorArt(ctx, layout, fitTransform(layout.bounds, 420, 360), layout.bounds);+ for (const colour of [MAP_PAINT.paving, MAP_PAINT.moss, MAP_PAINT.felt, MAP_PAINT.tile, MAP_PAINT.plot, MAP_PAINT.atrium, MAP_PAINT.olive,+ MAP_PAINT.tree, MAP_PAINT.bench, MAP_PAINT.screen, MAP_PAINT.oak, MAP_PAINT.sofa, MAP_PAINT.counter]) {+ expect(log, colour).toContain(`fillStyle=${colour}`);+ }+ // The plot is outlined dashed, in the bronze of the atrium's ring.+ expect(log).toContain(`strokeStyle=${MAP_PAINT.inlay}`);+ expect(log.some((l) => l.startsWith("setLineDash(") && l !== "setLineDash()")).toBe(true);+ // A round mark per tree and per standing table, besides the atrium's disc.+ const round = layout.ambience!.filter((i) => i.kind === "olive" || i.kind === "tree" || i.kind === "hightable").length;+ expect(log.filter((l) => l.startsWith("arc(")).length).toBeGreaterThanOrEqual(round + 1);+ // The coding floor paints none of it.+ const above = recorder();+ const coding = buildOfficeLayout([agent("p1", "Website")], { variant: "coding" });+ drawFloorArt(above.ctx, coding, fitTransform(coding.bounds, 220, 300), coding.bounds);+ for (const colour of [MAP_PAINT.paving, MAP_PAINT.moss, MAP_PAINT.plot, MAP_PAINT.olive]) expect(above.log).not.toContain(`fillStyle=${colour}`);+ });+it("rings tokens by state, dashes the paused one and prints the initial", () => {const { ctx, log } = recorder();const base = { x: 50, y: 50, colour: "#336699", selected: false };diff --git a/jarvis/ui/web/frontend/src/components/society/office/minimap.ts b/jarvis/ui/web/frontend/src/components/society/office/minimap.tsindex 4b26d1fee9..eeef6c2096 100644--- a/jarvis/ui/web/frontend/src/components/society/office/minimap.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/minimap.ts@@ -13,7 +13,7 @@import { CHECKPOINT_GOLD, DEPARTMENT_TINTS, ROOM_FLOOR_COLOURS } from "./officePalette";import {FURNITURE_SIZE, allDesks, deskRect, footprint, roomAt,- type CheckpointKind, type FurnitureKind, type OfficeLayout, type Point, type Rect, type RoomKind,+ type CampusZoneKind, type CheckpointKind, type FurnitureKind, type OfficeLayout, type Point, type Rect, type RoomKind,} from "./officeLayout";export type MinimapAgentState = "idle" | "working" | "waiting" | "paused";@@ -50,6 +50,20 @@ export function centredTransform(centre: Point, metresAcross: number, widthPx: nreturn { scale, offsetX: widthPx / 2 - centre.x * scale, offsetY: heightPx / 2 - centre.z * scale, width: widthPx, height: heightPx };}+/**+ * Where the minimap looks: at the person, but never further than `margin` metres past the floor's edge — standing+ * at a window or by the elevator, the card shows the floor behind the person instead of half a card of night.+ * A floor narrower than the view on an axis is simply centred on it.+ */+export function minimapCentre(at: Point, bounds: Rect, metresAcross: number, margin = 1.5): Point {+ const half = metresAcross / 2;+ const hold = (value: number, min: number, max: number) => {+ const low = min - margin + half, high = max + margin - half;+ return low > high ? (min + max) / 2 : Math.min(high, Math.max(low, value));+ };+ return { x: hold(at.x, bounds.minX, bounds.maxX), z: hold(at.z, bounds.minZ, bounds.maxZ) };+}+export function worldToMap(t: MapTransform, p: Point): MapPoint {return { x: t.offsetX + p.x * t.scale, y: t.offsetY + p.z * t.scale };}@@ -58,6 +72,23 @@ export function mapToWorld(t: MapTransform, p: MapPoint): Point {return { x: (p.x - t.offsetX) / t.scale, z: (p.y - t.offsetY) / t.scale };}+/**+ * The size of the full map's sheet for a plan: as tall as the space allows, as wide as the plan's shape asks —+ * or, where that is too wide, the full width and less height. The sheet then holds the plan with `pad` px round+ * it and nothing else, whatever the floor's proportions. `chromeH` is the sheet's header.+ */+export function fitSheet(plan: Rect, availW: number, availH: number, pad: number, chromeH: number, maxW = 1200): { width: number; height: number } {+ const aspect = Math.max(1e-6, plan.maxX - plan.minX) / Math.max(1e-6, plan.maxZ - plan.minZ);+ const widest = Math.max(1, Math.min(availW, maxW));+ let bodyH = Math.max(pad * 2 + 1, availH - chromeH);+ let width = (bodyH - pad * 2) * aspect + pad * 2;+ if (width > widest) {+ width = widest;+ bodyH = (width - pad * 2) / aspect + pad * 2;+ }+ return { width: Math.round(width), height: Math.round(bodyH + chromeH) };+}+/** Clamp a world point onto the walkable floor (a click on the railing still means "over there"). */export function clampToRect(p: Point, r: Rect): Point {return { x: Math.min(r.maxX, Math.max(r.minX, p.x)), z: Math.min(r.maxZ, Math.max(r.minZ, p.z)) };@@ -65,9 +96,9 @@ export function clampToRect(p: Point, r: Rect): Point {// ---------------------------------------------------------------------- zoom-/** Minimap zoom: metres across the card. */+/** Minimap zoom: metres across the card. The widest step shows the agents floor's campus from window to window. */export const ZOOM_MIN_M = 16;-export const ZOOM_MAX_M = 60;+export const ZOOM_MAX_M = 90;export const ZOOM_DEFAULT_M = 26;export function clampZoom(metres: number): number {@@ -224,17 +255,28 @@ export function pickNearest<T extends MapPoint>(items: readonly T[], at: MapPoinexport type MinimapPlace =| { kind: "checkpoint"; id: CheckpointKind }| { kind: "room"; id: RoomKind }- | { kind: "department"; label: string };+ | { kind: "department"; label: string }+ | { kind: "zone"; id: CampusZoneKind };-/** What lies under a world point: a checkpoint (within its radius) beats a room, a room beats a department. */+/** Campus zones overlap (the atrium lies on the plaza, the plaza crosses the boulevard): the most specific one names a point. */+const ZONE_PRIORITY: readonly CampusZoneKind[] = ["atrium", "plot", "garden", "booths", "library", "cafe", "plaza", "boulevard"];++/**+ * What lies under a world point: a checkpoint (within its radius) beats a room, a room beats a department (on the+ * agents floor: a team studio), and a studio beats the campus zone round it.+ */export function placeAt(layout: OfficeLayout, p: Point): MinimapPlace | null {for (const cp of layout.checkpoints) {if ((cp.x - p.x) ** 2 + (cp.z - p.z) ** 2 <= cp.radius * cp.radius) return { kind: "checkpoint", id: cp.id };}const room = roomAt(layout, p);if (room) return { kind: "room", id: room.kind };- const dept = layout.departments.find((d) => p.x >= d.minX && p.x <= d.maxX && p.z >= d.minZ && p.z <= d.maxZ);- return dept ? { kind: "department", label: dept.label } : null;+ const within = (r: Rect) => p.x >= r.minX && p.x <= r.maxX && p.z >= r.minZ && p.z <= r.maxZ;+ const dept = layout.departments.find(within);+ if (dept) return { kind: "department", label: dept.label };+ const zones = (layout.zones ?? []).filter(within);+ for (const kind of ZONE_PRIORITY) if (zones.some((z) => z.kind === kind)) return { kind: "zone", id: kind };+ return null;}// -------------------------------------------------------------------- colour@@ -295,6 +337,22 @@ export const MAP_PAINT = {furniture: "#8d7a66",plant: "#5fa35a",rug: "#d8c8ae",+ // Agents floor: the boulevards' limestone, the atrium's disc and bronze ring, planted ground, a free plot, trees and benches.+ paving: "#e6dfd1",+ atrium: "#f3eee4",+ inlay: "#a8865a",+ moss: "#c3d0ae",+ felt: "#c3cbd3",+ tile: "#eadfcd",+ plot: "#f1eadc",+ olive: "#6f9a5f",+ tree: "#4f8a55",+ bench: "#c9a878",+ // A studio's screens, and the oak and white of built fittings (booths, step seating, kitchen, cabinets, tables).+ screen: "#6f675c",+ oak: "#d9bf97",+ sofa: "#bdb6aa",+ counter: "#f6f3ee",checkpoint: CHECKPOINT_GOLD.face,checkpointDeep: CHECKPOINT_GOLD.faceDeep,checkpointIcon: CHECKPOINT_GOLD.icon,@@ -315,10 +373,10 @@ const FURNITURE_PAINT: Partial<Record<FurnitureKind, string>> = {beanbag: "#e27d60", bookshelf: "#8a6240", plant: MAP_PAINT.plant, rug: MAP_PAINT.rug, elevator: "#c9ced6",breakSofa: "#d8cdb9", breakSofaCorner: "#d8cdb9", breakTable: "#d6b98f", breakRug: "#e2c9a8", breakBookcase: "#a88660",readingNook: "#93a58a", foosball: "#3f7d4a", breakPlant: MAP_PAINT.plant, arcadeMat: "#2a2548",- leadWall: "#3a2416", executiveRug: "#26335a", guestChair: "#a9683c", chesterfield: "#7a2c22", loungeTable: "#d8ae52",- executiveBar: "#5b3a25", globe: "#5f8f96", floorLamp: "#d8ae52", commandWall: "#3a2a20", commandDesk: "#c9b79c",+ leadWall: "#6a4f37", executiveRug: "#48515e", guestChair: "#b98558", chesterfield: "#8e5a3a", loungeTable: "#b08d5c",+ executiveBar: "#8b6b4a", globe: "#5f8f96", floorLamp: "#b08d5c", commandWall: "#3a2a20", commandDesk: "#c9b79c",serverRack: "#23272e", coldAisle: "#b3bac3", nocConsole: "#2b3038", statusWall: "#1a1d22", ups: "#2b3038", fireSuppression: "#c8262b",- teamWall: "#6a4631", credenza: "#6a4631", designerPlant: MAP_PAINT.plant, teamRug: "#e6dccb",+ teamWall: "#b99a72", credenza: "#b99a72", designerPlant: MAP_PAINT.plant, teamRug: "#e6dccb",wardrobeWall: "#d2b187", dressingMirror: "#e9edf0", tailorDummy: "#e8dfcf", dressingBench: "#7e9378", coatStand: "#a88660",roundRug: "#e6ddca",brandWall: "#d2b286", agentTotem: "#2b2f33", lobbySofa: "#efe9de", lobbyArmchair: "#a8653a", lobbyTable: "#e7ddcc",@@ -327,19 +385,20 @@ const FURNITURE_PAINT: Partial<Record<FurnitureKind, string>> = {retroCabinet: "#7c5cff", prizeCounter: "#d6457f", tokenMachine: "#e0b23a", clawMachine: "#ff5fa2", airHockey: "#3d8bff",pinball: "#9b5cff", snackCounter: "#c47a3a",levelWall: "#1d2b52", studioStage: "#e9c46a", rewardPedestal: "#f0e6cf", levelRoad: "#3a4f8f", levelGuide: "#1d2b52",+ studioBoard: "#2a2d33", teamStand: "#d9bf97",};export const STATE_RING: Record<MinimapAgentState, string> = {working: MAP_PAINT.working, waiting: MAP_PAINT.waiting, idle: MAP_PAINT.idle, paused: MAP_PAINT.paused,};-/** Checkpoint icon per checkpoint kind; the same pictures as the 3D tokens (CheckpointMarker). */+/** Checkpoint icon per checkpoint kind, for the maps' gold badges. */export const CHECKPOINT_ICON_KEYS: Record<CheckpointKind, "spawn" | "plus" | "list" | "team" | "shirt" | "star" | "coffee" | "elevator" | "target" | "sparkle" | "trophy"> = {spawn: "spawn", launch: "spawn", create: "plus", manage: "list", team: "team", wardrobe: "shirt", lead: "star", break: "coffee", elevator: "elevator", mission: "target",studio: "sparkle", levels: "trophy",};-/** Stroke-only icons in a 24 × 24 box; kept in sync with CheckpointMarker's paths. */+/** Stroke-only icons in a 24 × 24 box. */const ICON_PATHS: Record<(typeof CHECKPOINT_ICON_KEYS)[CheckpointKind], string> = {spawn: "M12 8.5v7M8.5 12h7M5.2 7.5A8 8 0 0 1 18.8 7.5M18.8 16.5A8 8 0 0 1 5.2 16.5",plus: "M12 5v14M5 12h14",@@ -453,6 +512,46 @@ export function drawFloorArt(ctx: Ctx, layout: OfficeLayout, t: MapTransform, arctx.globalAlpha = 1;}+ // Agents floor: the paved boulevards, planted courts, the free plot and the atrium, under everything built on them.+ const zones = layout.zones ?? [];+ if (zones.length > 0) {+ const paint = (kinds: readonly CampusZoneKind[], colour: string, radiusM: number) => {+ ctx.fillStyle = colour;+ for (const zone of zones) {+ if (!kinds.includes(zone.kind)) continue;+ rectPath(ctx, t, zone, radiusM);+ ctx.fill();+ }+ };+ paint(["boulevard", "plaza"], MAP_PAINT.paving, 0);+ paint(["garden"], MAP_PAINT.moss, 0.6);+ paint(["booths"], MAP_PAINT.felt, 0.6);+ paint(["cafe"], MAP_PAINT.tile, 0.6);+ const plot = zones.find((z) => z.kind === "plot");+ if (plot) {+ rectPath(ctx, t, plot, 0.3);+ ctx.fillStyle = MAP_PAINT.plot;+ ctx.fill();+ // A dashed outline: marked out, not built yet.+ ctx.setLineDash?.([Math.max(2, t.scale * 0.5), Math.max(2, t.scale * 0.35)]);+ ctx.strokeStyle = MAP_PAINT.inlay;+ ctx.lineWidth = Math.max(1, Math.min(2, t.scale * 0.12));+ ctx.stroke();+ ctx.setLineDash?.([]);+ }+ const atrium = zones.find((z) => z.kind === "atrium");+ if (atrium) {+ const c = worldToMap(t, { x: (atrium.minX + atrium.maxX) / 2, z: (atrium.minZ + atrium.maxZ) / 2 });+ ctx.beginPath();+ ctx.arc(c.x, c.y, 5 * t.scale, 0, Math.PI * 2);+ ctx.fillStyle = MAP_PAINT.atrium;+ ctx.fill();+ ctx.strokeStyle = MAP_PAINT.inlay;+ ctx.lineWidth = Math.max(1, t.scale * 0.14);+ ctx.stroke();+ }+ }+// Department carpets and rooms: painted areas with soft darker outlines.ctx.lineWidth = Math.max(1, Math.min(2, t.scale * 0.12));for (const dept of layout.departments) {@@ -502,6 +601,48 @@ export function drawFloorArt(ctx: Ctx, layout: OfficeLayout, t: MapTransform, ar}}+ // Agents floor: trees as round crowns (a large tree's spreads wider), standing tables as discs, everything else+ // as a block in its own tone: screens dark and slim, sofas soft, built fittings oak or white.+ const BLOCK: Record<string, string> = {+ bench: MAP_PAINT.bench, planter: MAP_PAINT.plant, screen: MAP_PAINT.screen, cabinet: MAP_PAINT.counter, sofa: MAP_PAINT.sofa,+ booth: MAP_PAINT.oak, steps: MAP_PAINT.oak, counter: MAP_PAINT.counter, island: MAP_PAINT.oak, crate: MAP_PAINT.oak,+ };+ for (const item of layout.ambience ?? []) {+ if (item.kind === "olive" || item.kind === "tree" || item.kind === "hightable") {+ const c = worldToMap(t, { x: (item.minX + item.maxX) / 2, z: (item.minZ + item.maxZ) / 2 });+ const radiusM = item.kind === "tree" ? 1.25 : item.kind === "olive" ? 0.62 : 0.4;+ ctx.beginPath();+ ctx.arc(c.x, c.y, Math.max(1.4, radiusM * t.scale), 0, Math.PI * 2);+ ctx.fillStyle = item.kind === "tree" ? MAP_PAINT.tree : item.kind === "olive" ? MAP_PAINT.olive : MAP_PAINT.oak;+ ctx.globalAlpha = item.kind === "hightable" ? 1 : 0.9;+ ctx.fill();+ ctx.globalAlpha = 1;+ } else {+ rectPath(ctx, t, item, 0.08);+ ctx.fillStyle = BLOCK[item.kind] ?? MAP_PAINT.furniture;+ ctx.fill();+ if (item.kind === "booth" || item.kind === "steps" || item.kind === "counter" || item.kind === "island" || item.kind === "sofa") {+ ctx.strokeStyle = shade(BLOCK[item.kind], -0.3);+ ctx.lineWidth = 0.8;+ ctx.stroke();+ }+ }+ }+ // Agents floor: every studio's name wall along its north edge, in the studio's colour.+ if (layout.studios && layout.studios.length > 0) {+ ctx.lineCap = "butt";+ ctx.lineWidth = Math.max(1.5, Math.min(4, t.scale * 0.22));+ for (const dept of layout.departments) {+ const a = worldToMap(t, { x: dept.minX + 0.2, z: dept.minZ + 0.11 });+ const b = worldToMap(t, { x: dept.maxX - 0.2, z: dept.minZ + 0.11 });+ ctx.strokeStyle = shade(DEPARTMENT_TINTS[dept.tint % DEPARTMENT_TINTS.length], -0.45);+ ctx.beginPath();+ ctx.moveTo(a.x, a.y);+ ctx.lineTo(b.x, b.y);+ ctx.stroke();+ }+ }+// Desks: tiny light blocks with the monitor on the far side from the chair.for (const desk of allDesks(layout)) {const c = worldToMap(t, desk);@@ -709,10 +850,28 @@ export function drawEdgeArrow(ctx: Ctx, x: number, y: number, angle: number, tokctx.stroke();}-/** A game-map label: white text with a dark halo, centred on (x, y). */-export function drawMapLabel(ctx: Ctx, text: string, x: number, y: number, px: number, weight = 700): void {+/**+ * A game-map label: white text with a dark halo, centred on (x, y). With `maxWidth` (px) a long name first+ * shrinks to three quarters of its size and is then cut with an ellipsis, so it stays over its own place.+ */+export function drawMapLabel(ctx: Ctx, text: string, x: number, y: number, px: number, weight = 700, maxWidth?: number): void {if (!text) return;- ctx.font = `${weight} ${px}px system-ui, -apple-system, "Segoe UI", sans-serif`;+ const font = (size: number) => `${weight} ${size}px system-ui, -apple-system, "Segoe UI", sans-serif`;+ ctx.font = font(px);+ if (maxWidth !== undefined && typeof ctx.measureText === "function") {+ const widthOf = (value: string) => ctx.measureText(value)?.width ?? 0;+ let size = px;+ while (size > px * 0.75 && widthOf(text) > maxWidth) {+ size -= 0.5;+ ctx.font = font(size);+ }+ px = size;+ if (widthOf(text) > maxWidth) {+ let cut = text;+ while (cut.length > 1 && widthOf(`${cut}…`) > maxWidth) cut = cut.slice(0, -1);+ text = `${cut.trimEnd()}…`;+ }+ }ctx.textAlign = "center";ctx.textBaseline = "middle";ctx.lineJoin = "round";diff --git a/jarvis/ui/web/frontend/src/components/society/office/namePlate.test.ts b/jarvis/ui/web/frontend/src/components/society/office/namePlate.test.tsnew file mode 100644index 0000000000..e49152e749--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/namePlate.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from "vitest";+import { PLATE_RANGE, plateDetail, type PlateDetail, type PlateInput } from "./namePlate";++const far: PlateInput = { cameraDistance: 40, personDistance: 30, pointed: false, selected: false };++describe("name plate detail", () => {+ it("is a dot from across the floor", () => {+ expect(plateDetail("dot", far)).toBe("dot");+ expect(plateDetail("full", far)).toBe("dot");+ });++ it("opens for the agent that is pointed at or selected, however far away", () => {+ expect(plateDetail("dot", { ...far, pointed: true })).toBe("full");+ expect(plateDetail("dot", { ...far, selected: true })).toBe("full");+ });++ it("opens when the camera comes near", () => {+ expect(plateDetail("dot", { ...far, cameraDistance: PLATE_RANGE.camera.open - 0.1 })).toBe("full");+ });++ it("opens for the people round the person, even in the overview", () => {+ expect(plateDetail("dot", { ...far, personDistance: PLATE_RANGE.person.open - 0.1 })).toBe("full");+ });++ it("stays as it is inside the gap, so a plate at the threshold never flickers", () => {+ const between = { ...far, cameraDistance: (PLATE_RANGE.camera.open + PLATE_RANGE.camera.close) / 2 };+ expect(plateDetail("dot", between)).toBe("dot");+ expect(plateDetail("full", between)).toBe("full");+ const strolling = { ...far, personDistance: (PLATE_RANGE.person.open + PLATE_RANGE.person.close) / 2 };+ expect(plateDetail("dot", strolling)).toBe("dot");+ expect(plateDetail("full", strolling)).toBe("full");+ });++ it("changes once, not on every step, while someone paces across the threshold", () => {+ // An agent wandering between 4.4 m and 5.8 m from the person: inside the gap except at the near end.+ const path = [5.8, 5.2, 4.7, 4.4, 4.7, 5.2, 5.8, 5.2, 4.7, 4.4, 4.9, 5.8];+ let detail: PlateDetail = "dot";+ let changes = 0;+ for (const personDistance of path) {+ const next = plateDetail(detail, { ...far, personDistance });+ if (next !== detail) changes += 1;+ detail = next;+ }+ expect(changes).toBe(1);+ expect(detail).toBe("full");+ });++ it("closes again only beyond the far edge", () => {+ expect(plateDetail("full", { ...far, cameraDistance: PLATE_RANGE.camera.close + 0.1 })).toBe("dot");+ expect(plateDetail("full", { ...far, personDistance: PLATE_RANGE.person.close + 0.1 })).toBe("dot");+ });++ it("keeps a real gap on both ranges", () => {+ expect(PLATE_RANGE.camera.close - PLATE_RANGE.camera.open).toBeGreaterThanOrEqual(1);+ expect(PLATE_RANGE.person.close - PLATE_RANGE.person.open).toBeGreaterThanOrEqual(1);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/namePlate.ts b/jarvis/ui/web/frontend/src/components/society/office/namePlate.tsnew file mode 100644index 0000000000..8f60f26094--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/namePlate.ts@@ -0,0 +1,38 @@+/**+ * How much of a name plate shows. From across the floor an agent is one small+ * state dot, so the overview is a calm field of dots and not of labels; the+ * whole plate (name, rank, activity) appears when the camera or the person+ * comes near, when the pointer or keyboard focus rests on the agent, or when+ * it is selected. Pure and tested.+ */++export type PlateDetail = "dot" | "full";++/**+ * Distances in metres, each as a pair: the plate opens inside the first and+ * closes again only beyond the second. The gap keeps a plate from flickering+ * while someone stands or strolls right at the threshold.+ */+export const PLATE_RANGE = {+ /** Camera to agent. The follow view keeps the camera 15 m from the person, so this is a deliberate zoom in. */+ camera: { open: 10.5, close: 12.5 },+ /** The person's character to agent: the people round you introduce themselves. */+ person: { open: 4.6, close: 6 },+} as const;++export interface PlateInput {+ /** Camera to the plate. */+ cameraDistance: number;+ /** The person's character to the agent, on the floor. */+ personDistance: number;+ /** The pointer or keyboard focus rests on the agent or its plate. */+ pointed: boolean;+ selected: boolean;+}++export function plateDetail(previous: PlateDetail, input: PlateInput): PlateDetail {+ if (input.selected || input.pointed) return "full";+ const edge = previous === "full" ? "close" : "open";+ const near = input.cameraDistance <= PLATE_RANGE.camera[edge] || input.personDistance <= PLATE_RANGE.person[edge];+ return near ? "full" : "dot";+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/office.css b/jarvis/ui/web/frontend/src/components/society/office/office.cssindex 634335df84..cc4308d65a 100644--- a/jarvis/ui/web/frontend/src/components/society/office/office.css+++ b/jarvis/ui/web/frontend/src/components/society/office/office.css@@ -1,42 +1,111 @@/* HUD over the office canvas: theme tokens, so it follows light and dark mode. */.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; }+/* In-world labels (name plates, bubbles) are positioned DOM in here with z-indexes of their own: one stacking+ context keeps all of them under every HUD card. */+.office-viewport { position:absolute; inset:0; touch-action:none; isolation:isolate; }.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)); }-/* A column to the left of the minimap (top-right, 204 px wide + 8 px gap). */-.office-hud-right { right:226px; top:14px; display:flex; flex-direction:column; align-items:flex-end; gap:6px; }-/* Narrow: under the minimap, wrapping within its width. */-@media (max-width:760px) { .office-hud-right { right:14px; top:256px; flex-direction:row; flex-wrap:wrap; justify-content:flex-end; max-width:204px; } }-/* No minimap (short or very narrow window): back to a wrapping row in the corner. */-@media (max-height:520px), (max-width:600px) { .office-hud-right { right:14px; top:14px; flex-direction:row; flex-wrap:wrap; justify-content:flex-end; max-width:max(180px, calc(100% - 370px)); } }+/* Top left: the floor card, the level card and whatever the floor has to say. It never reaches under the toolbar and the minimap (226 px) on the right. */+.office-hud-left { left:14px; top:14px; display:flex; flex-direction:column; align-items:flex-start; gap:8px; max-width:min(320px, calc(100% - 430px)); }.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: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-title { display:flex; flex-direction:column; gap:3px; max-width:100%; padding:8px 12px; font-size:14px; }+.office-title strong { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }+.office-title > span { font-size:11px; color:hsl(var(--muted-foreground)); }+/* Who is doing what, as one quiet line under the floor's name. */+.office-states { display:flex; flex-wrap:wrap; gap:2px 10px; }+.office-states span { display:inline-flex; align-items:center; gap:5px; white-space:nowrap; }+.office-states i { width:7px; height:7px; border-radius:50%; background:hsl(var(--muted-foreground)); }+.office-states [data-tone="working"] i { background:hsl(var(--success)); }+.office-states [data-tone="waiting"] i { background:hsl(var(--warning)); }+.office-states [data-tone="paused"] i { background:transparent; box-shadow:inset 0 0 0 1.5px hsl(var(--muted-foreground)); }.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; 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; 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. */+/* The toolbar and what opens from it: a dock left of the minimap (top right, 204 px wide + 8 px gap) that reaches+ down to the stage's lower edge, so the places card under the toolbar can never grow out of the stage. The dock+ itself takes no pointer; the toolbar and the card do. */+.office-tools-dock { right:226px; top:14px; bottom:16px; z-index:32; display:flex; flex-direction:column; align-items:flex-end; gap:9px; pointer-events:none; }+.office-tools-dock > * { pointer-events:auto; }+.office-tools { flex:none; display:flex; gap:2px; padding:3px; border:1px solid hsl(var(--border)); border-radius:11px; 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-tool { position:relative; display:inline-flex; align-items:center; justify-content:center; width:30px; height:30px; padding:0; border:0; border-radius:8px; background:none; color:inherit; cursor:pointer; }+.office-tool svg { width:16px; height:16px; }+.office-tool:hover { background:hsl(var(--secondary)); }+.office-tool[aria-pressed="true"], .office-tool[aria-expanded="true"] { background:hsl(var(--secondary)); color:hsl(var(--foreground)); box-shadow:inset 0 0 0 1px hsl(var(--border)); }+.office-tool:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:1px; }+/* Its label, on hover and on keyboard focus (the button carries the same text as its accessible name). */+.office-tool[data-tip]:hover::after, .office-tool[data-tip]:focus-visible::after { content:attr(data-tip); position:absolute; top:calc(100% + 9px); left:50%; transform:translateX(-50%); z-index:2; padding:4px 8px; border-radius:7px; border:1px solid hsl(var(--border)); background:hsl(var(--popover)); color:hsl(var(--popover-foreground)); font-size:11px; font-weight:500; line-height:1.3; white-space:nowrap; pointer-events:none; box-shadow:0 4px 14px rgb(0 0 0 / .22); }+/* The last button's label would leave the toolbar's right edge towards the minimap: keep it inside. */+.office-tools > .office-tool:last-child[data-tip]::after { left:auto; right:0; transform:none; }+/* The places card: an opaque floating surface (never see-through over the scene). It is as tall as its list and+ uses the room under the toolbar down to the stage's lower edge (the dock ends there), up to a cap for very tall+ stages; only what does not fit scrolls inside it. */+.office-places-card { position:relative; flex:0 1 auto; display:flex; flex-direction:column; min-height:0; width:min(320px, calc(100vw - 28px)); max-height:680px; overflow:hidden; border:1px solid hsl(var(--border)); border-radius:12px; background:hsl(var(--popover)); color:hsl(var(--popover-foreground)); box-shadow:0 10px 30px rgb(0 0 0 / .32); }+.office-places-scroll { flex:1 1 auto; min-height:0; overflow-y:auto; overscroll-behavior:contain; padding:6px; scrollbar-gutter:stable; }+/* More rows below: the lower edge fades, so a cut-off row reads as "scroll" and not as the end. */+.office-places-card[data-more]::after { content:""; position:absolute; left:0; right:0; bottom:0; height:30px; border-radius:0 0 11px 11px; background:linear-gradient(hsl(var(--popover) / 0), hsl(var(--popover))); pointer-events:none; }+/* Narrow: the toolbar sits under the minimap. */+@media (max-width:760px) { .office-tools-dock { right:14px; top:262px; } .office-hud-left { max-width:min(320px, calc(100% - 254px)); } }+/* No minimap (short or very narrow window): the toolbar takes its corner. */+@media (max-height:520px), (max-width:600px) { .office-tools-dock { right:14px; top:14px; } .office-hud-left { max-width:calc(100% - 28px - 190px); } }+/* The IDE side panel: no minimap; the toolbar is a column in the corner, its labels and the places card open to its left. */+.office-stage.office-stage-compact .office-tools-dock { right:8px; top:8px; bottom:8px; flex-direction:row-reverse; align-items:flex-start; }+.office-stage.office-stage-compact .office-tools { flex-direction:column; }+.office-stage.office-stage-compact .office-hud-left { max-width:calc(100% - 62px); }+.office-stage.office-stage-compact .office-tool[data-tip]::after { top:50%; left:auto; right:calc(100% + 9px); transform:translateY(-50%); }+.office-stage.office-stage-compact .office-places-card { width:min(280px, calc(100vw - 80px)); max-height:min(680px, 100%); }++/* Bottom centre: the one prompt, a station's short answer, the first-visit hints. */+.office-hud-bottom { left:50%; bottom:16px; transform:translateX(-50%); display:flex; flex-direction:column; align-items:center; gap:8px; width:max-content; max-width:calc(100% - 28px); pointer-events:none; }+.office-hud-bottom > * { pointer-events:auto; max-width:100%; }+.office-hud-bottom > [role="status"]:empty { display:none; }+.office-prompt { display:inline-flex; align-items:center; gap:8px; padding:6px 13px 6px 6px; border-radius:10px; border:1px solid hsl(var(--border)); background:hsl(var(--popover) / .94); color:hsl(var(--popover-foreground)); font:inherit; font-size:13px; cursor:pointer; box-shadow:0 6px 20px rgb(0 0 0 / .3); backdrop-filter:blur(6px); }+.office-prompt b { font-weight:600; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }+.office-prompt span { color:hsl(var(--muted-foreground)); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }+/* Narrow host: the action is never cut short; it wraps instead (the object's name is not shown there). */+.office-prompt[data-compact] { text-align:left; }+.office-prompt[data-compact] b { white-space:normal; overflow:visible; text-overflow:clip; overflow-wrap:anywhere; }+.office-prompt[data-compact] .office-key { flex:none; }+.office-prompt:hover { background:hsl(var(--popover)); }+.office-prompt:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:2px; }+.office-notice { margin:0; padding:6px 12px; font-size:12px; }+.office-hints { display:flex; align-items:center; gap:14px; padding:8px 8px 8px 14px; }+.office-hints ul { display:flex; flex-wrap:wrap; gap:6px 16px; margin:0; padding:0; list-style:none; }+.office-hints li { display:inline-flex; align-items:center; gap:7px; font-size:12px; color:hsl(var(--muted-foreground)); white-space:nowrap; }+.office-hints-dismiss { flex:none; padding:5px 11px; border:1px solid hsl(var(--border)); border-radius:8px; background:hsl(var(--background)); color:hsl(var(--foreground)); font:inherit; font-size:12px; font-weight:500; cursor:pointer; }+.office-hints-dismiss:hover { background:hsl(var(--secondary)); }+.office-hints-dismiss:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:2px; }+@media (max-width:700px) { .office-hints { flex-direction:column; align-items:stretch; padding:10px; } }++/* In-world name plates: part of the diorama, so they keep one dark look in both modes.+ From afar an agent is only its state dot; the plate fades in over it (see namePlate.ts). Dot and plate share+ one grid cell, so nothing moves when one takes over from the other. */+.office-plate-wrap { display:inline-grid; place-items:center; pointer-events:none; }+.office-plate-wrap > * { grid-area:1 / 1; }+.office-plate-dot { position:relative; width:9px; height:9px; border-radius:50%; background:#94a3b8; box-shadow:0 0 0 2px rgb(24 26 32 / .8); pointer-events:auto; cursor:pointer; transition:opacity .18s ease; }+/* A dot is small; its target is not. */+.office-plate-dot::after { content:""; position:absolute; inset:-7px; border-radius:50%; }+.office-plate-wrap[data-state="working"] .office-plate-dot { background:#4ade80; }+.office-plate-wrap[data-state="waiting"] .office-plate-dot { background:#fbbf24; }+.office-plate-wrap[data-state="paused"] .office-plate-dot { background:rgb(24 26 32 / .8); box-shadow:0 0 0 2px rgb(24 26 32 / .8), inset 0 0 0 1.5px #94a3b8; }+.office-plate-wrap .office-plate { transition:opacity .18s ease; }+/* The hidden plate stays in the tab order: keyboard focus on it opens it. */+.office-plate-wrap[data-detail="dot"] .office-plate { opacity:0; pointer-events:none; }+.office-plate-wrap[data-detail="full"] .office-plate { pointer-events:auto; }+.office-plate-wrap[data-detail="full"] .office-plate-dot { opacity:0; pointer-events:none; }+@media (prefers-reduced-motion:reduce) { .office-plate-dot, .office-plate-wrap .office-plate { transition:none; } }.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); }.office-plate:hover { background:rgb(36 39 48 / .95); }-.office-plate-name { max-width:16em; overflow:hidden; text-overflow:ellipsis; font-size:12px; font-weight:700; }+.office-plate-name { max-width:16em; overflow:hidden; text-overflow:ellipsis; font-size:12px; font-weight:600; }.office-plate-badge { display:inline-flex; align-items:center; justify-content:center; width:18px; height:18px; font-size:10px; font-weight:800; color:#fff; clip-path:polygon(25% 3%, 75% 3%, 100% 50%, 75% 97%, 25% 97%, 0 50%); }-.office-plate-state { display:inline-flex; align-items:center; gap:4px; font-size:10px; font-weight:600; color:#cbd5e1; }+.office-plate-state { display:inline-flex; align-items:center; gap:4px; font-size:10px; font-weight:500; color:#cbd5e1; }.office-plate-state em { font-style:normal; }.office-plate-state i { width:7px; height:7px; border-radius:50%; background:#94a3b8; }.office-plate[data-state="working"] .office-plate-state i { background:#4ade80; box-shadow:0 0 6px #4ade80; }.office-plate[data-state="waiting"] .office-plate-state i { background:#fbbf24; }.office-plate:focus-visible { outline:2px solid #93c5fd; outline-offset:2px; }-/* Coding plates keep the expanded title, call-sign and last ask visible without hover. */+.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); }+/* Coding plates carry the whole title (subject, then result) and the run state. */.office-plate[data-pane] { align-items:flex-start; gap:6px; padding:4px 10px 4px 4px; border-radius:12px; text-align:left; }.office-plate[data-pane] .office-plate-badge { flex:none; margin-top:1px; }/* The coding CLI's mark: ink marks masked in the plate's white, colour lockups on a dark tile. */@@ -54,20 +123,8 @@.office-plate[data-pane][data-open] .office-plate-name,.office-plate[data-pane][data-open] .office-plate-result { max-width:min(20em, 100%); white-space:normal; overflow:visible; overflow-wrap:anywhere; text-overflow:clip; }.office-plate[data-pane][data-open] .office-plate-line { max-width:100%; flex-wrap:wrap; }-/* Checkpoint label pills: same dark in-world pill as .office-plate, with a gold hexagon badge. */-.office-checkpoint { transform-origin:center center; display:inline-flex; align-items:center; gap:6px; padding:3px 11px 3px 3px; border:1px solid rgb(245 184 61 / .55); border-radius:999px; background:rgb(24 26 32 / .86); color:#fff7ec; cursor:pointer; font-family:inherit; font-size:12px; font-weight:700; white-space:nowrap; user-select:none; box-shadow:0 2px 8px rgb(0 0 0 / .35); transition:background .15s, border-color .15s, box-shadow .15s; }-.office-checkpoint:hover { background:rgb(36 39 48 / .95); border-color:#f5b83d; }-.office-checkpoint-badge { display:inline-flex; align-items:center; justify-content:center; flex:none; width:20px; height:20px; background:#f5b83d; color:#2a1d0a; clip-path:polygon(25% 3%, 75% 3%, 100% 50%, 75% 97%, 25% 97%, 0 50%); }-.office-checkpoint-badge svg { width:12px; height:12px; }-.office-checkpoint-label { max-width:12em; overflow:hidden; text-overflow:ellipsis; }-.office-checkpoint-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; } }-/* The executive chair's prompt: a wider pill with the E key and a short hint. */-.office-seat-prompt { padding:4px 12px 4px 4px; gap:7px; font-size:12px; font-weight:600; cursor:default; }-.office-seat-prompt kbd { display:inline-flex; align-items:center; justify-content:center; width:20px; height:20px; border-radius:6px; background:#f5b83d; color:#1f1300; font-family:inherit; font-size:11px; font-weight:800; }+/* A seat's or the dog's own prompt beside it: the same dark pill with a key cap and a short hint. */+.office-seat-prompt { padding:4px 12px 4px 4px; gap:7px; font-size:12px; font-weight:500; cursor:default; }+.office-seat-prompt kbd { display:inline-flex; align-items:center; justify-content:center; width:20px; height:20px; border-radius:6px; background:#f8fafc; color:#181a20; font-family:inherit; font-size:11px; font-weight:700; }+/* Seated first person at Mission Control: the dots step aside with the plates (officeCameraRig.css hides those). */+.office-viewport[data-first-person] .office-plate-dot { visibility:hidden; }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.tsindex bdc37080e5..1e44ddca1b 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@@ -1,13 +1,21 @@import { describe, expect, it } from "vitest";import type { AgentRunState } from "../data";-import { allDesks, buildOfficeLayout, seatOf, standOf, type DeskSlot, type OfficeAgentInput } from "./officeLayout";-import { buildNavGrid, isWalkable } from "./officeNav";-import { createRng, planFor, SpotBook, type ActivityKind, type PlanInput } from "./officeBehavior";+import { allDesks, buildOfficeLayout, seatOf, standOf, type DeskSlot, type OfficeAgentInput, type Point } from "./officeLayout";+import { BODY_SPACING, paceFor } from "./officeMotion";+import { buildNavGrid, findPath, isWalkable } from "./officeNav";+import {+ COMMONS_WEIGHTS, HANDOFF_DWELL_MS, PERSON_SPACE_M, POOL_IDLE_WEIGHTS, TEAM_IDLE_WEIGHTS, TRIP_REACH, createRng, dwellAfter, planFor, planStillValid, shownActivity, SpotBook,+ tripReach, type ActivityKind, type Plan, type PlanInput,+} from "./officeBehavior";+import { HUDDLE_SPACE_M, homeStudio, huddlePlaces, leadPlace, mateDesks, studioRect, studioOfTeam, visitSlots } from "./officeTeams";+import { pathLength } from "./officeWalk";+import { campusOf } from "./officeFixtures";const roster: OfficeAgentInput[] = Array.from({ length: 8 }, (_, i) => ({agentId: `a${i}`, name: `a${i}`, tier: "specialist", providerLabel: i % 2 ? "Codex" : "Gemini", state: "idle", createdMs: i,}));-const layout = buildOfficeLayout(roster);+// A floor without team studios (the coding floor): the plain idle day.+const layout = buildOfficeLayout(roster, { variant: "coding" });const grid = buildNavGrid(layout);const deskOf = (id: string): DeskSlot => allDesks(layout).find((d) => d.agentId === id)!;@@ -34,16 +42,18 @@ describe("SpotBook", () => {expect(book.claim("s1", "a")).toBe(true);expect(book.claim("s1", "b")).toBe(false);expect(book.holder("s1")).toBe("a");+ expect(book.spotOf("a")).toBe("s1");expect(book.claim("s2", "a")).toBe(true);expect(book.isFree("s1")).toBe(true);expect(book.holder("s2")).toBe("a");book.release("a");expect(book.isFree("s2")).toBe(true);expect(book.holder("s2")).toBeNull();+ expect(book.spotOf("a")).toBeNull();});});-describe("planFor", () => {+describe("planFor on a floor without studios", () => {it("seats a working agent at its desk, typing, until the state changes", () => {const plan = planFor(input("a1", "working"));const seat = seatOf(deskOf("a1"));@@ -81,7 +91,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 caller = layout.checkpoints.find((c) => c.id === "break")!;const plan = planFor(input("a3", "idle", { calledTo: caller }));expect(plan.kind).toBe("called");expect(plan.pose).toBe("talk");@@ -91,7 +101,7 @@ describe("planFor", () => {});it("keeps a working agent at its screen even when called", () => {- const caller = layout.checkpoints.find((c) => c.id === "create")!;+ const caller = layout.checkpoints.find((c) => c.id === "break")!;expect(planFor(input("a3", "working", { calledTo: caller })).kind).toBe("work");});@@ -120,18 +130,33 @@ describe("planFor", () => {if (first[i] !== "wander") expect(first[i]).not.toBe(first[i - 1]);}expect(new Set(first).size).toBeGreaterThan(6);+ // No studios, no team life.+ for (const kind of ["huddle", "mate", "studio", "handoff"]) expect(first).not.toContain(kind);});- it("visits a working colleague by standing next to their chair", () => {+ it("looks in on a working colleague from a place of its own beside their chair, without pretending to talk", () => {const colleague = { agentId: "a5", desk: deskOf("a5") };- for (let i = 0; i < 200; i += 1) {- const plan = planFor(input("a4", "idle", { rng: createRng(`visit-${i}`), workingColleagues: [colleague] }));- if (plan.kind !== "visit") continue;- const stand = standOf(colleague.desk);- expect(plan).toMatchObject({ with: "a5", pose: "talk", target: { x: stand.x, z: stand.z } });- return;+ const seat = seatOf(colleague.desk);+ const book = new SpotBook();+ const visits: Plan[] = [];+ for (let i = 0; i < 400 && visits.length < 2; i += 1) {+ const plan = planFor(input(`a${visits.length === 0 ? 4 : 6}`, "idle", { rng: createRng(`visit-${i}`), book, workingColleagues: [colleague] }));+ if (plan.kind === "visit") visits.push(plan); else book.release(`a${visits.length === 0 ? 4 : 6}`);+ }+ expect(visits).toHaveLength(2);+ for (const plan of visits) {+ expect(plan).toMatchObject({ with: "a5", pose: "stand" });+ expect(plan.spotId).toMatch(/^visit:/);+ expect(isWalkable(grid, plan.target)).toBe(true);+ // Beside the chair: within reach, outside the body spacing, looking at the colleague.+ const gap = Math.hypot(plan.target.x - seat.x, plan.target.z - seat.z);+ expect(gap).toBeGreaterThan(BODY_SPACING);+ expect(gap).toBeLessThan(1.3);+ expect(plan.facing).toBeCloseTo(Math.atan2(seat.x - plan.target.x, seat.z - plan.target.z));}- throw new Error("no visit in 200 seeds");+ // Two visitors never stand on each other.+ expect(Math.hypot(visits[0].target.x - visits[1].target.x, visits[0].target.z - visits[1].target.z)).toBeGreaterThanOrEqual(BODY_SPACING);+ expect(visits[0].spotId).not.toBe(visits[1].spotId);});it("falls back to wandering when every spot of the chosen kind is taken", () => {@@ -171,4 +196,539 @@ describe("SpotBook.retain", () => {// The dropped agent can claim again.expect(book.claim("couch-a2", "a2")).toBe(true);});++ it("keeps the places the plan does not list, so a rebuilt floor never hands an occupied one out again", () => {+ const book = new SpotBook();+ book.claim("fan:studio-team-0:0:1", "a1");+ book.claim("visit:6.32,-3.87", "a2");+ book.claim("couch-of-the-old-plan", "a3");+ book.retain(new Set(["couch-a1"]));+ expect(book.holder("fan:studio-team-0:0:1")).toBe("a1");+ expect(book.holder("visit:6.32,-3.87")).toBe("a2");+ expect(book.isFree("couch-of-the-old-plan")).toBe(true);+ // Nobody else is given the place at the board while a1 stands on it.+ expect(book.claim("fan:studio-team-0:0:1", "a4")).toBe(false);+ });+});++// ---------------------------------------------------------------------------+// Team studios: agents belong somewhere.+// ---------------------------------------------------------------------------++// 26 agents: teams of 7, 6 and 5, and 8 agents without a team (the pool).+const campus = campusOf(26, [7, 6, 5]);+const cDesk = (id: string): DeskSlot | null => allDesks(campus.layout).find((d) => d.agentId === id) ?? null;++function cInput(agentId: string, state: AgentRunState, extra: Partial<PlanInput> = {}): PlanInput {+ return {+ agentId, state, desk: cDesk(agentId), layout: campus.layout, grid: campus.grid, rng: createRng(agentId), book: new SpotBook(),+ previous: null, workingColleagues: [], calledTo: null, ...extra,+ };+}++/** A plan keeps the agent at home when it is in its studio or a few steps round the corner. */+function atHome(agentId: string, plan: Plan): boolean {+ const studio = homeStudio(campus.layout, agentId, cDesk(agentId))!;+ const rect = studioRect(campus.layout, studio);+ const reach = Math.hypot(rect.maxX - rect.minX, rect.maxZ - rect.minZ) / 2 + 3.5;+ return Math.hypot(plan.target.x - studio.centre.x, plan.target.z - studio.centre.z) <= reach;+}++function idleDay(agentId: string, steps: number, seed = agentId): Plan[] {+ const rng = createRng(seed);+ const book = new SpotBook();+ const studio = homeStudio(campus.layout, agentId, cDesk(agentId))!;+ const mates = mateDesks(campus.layout, studio, agentId).map((d) => ({ agentId: d.agentId as string, desk: d }));+ const plans: Plan[] = [];+ let previous: ActivityKind | null = null;+ let position: Point | null = null;+ for (let i = 0; i < steps; i += 1) {+ const plan = planFor(cInput(agentId, "idle", { rng, book, previous, position, matesAtDesk: mates }));+ plans.push(plan);+ previous = plan.kind;+ position = plan.target;+ }+ return plans;+}++describe("the campus", () => {+ it("gives every team a studio with a board and places to stand at it, and seats the rest in the pool", () => {+ const studios = campus.layout.studios ?? [];+ expect(studios.filter((s) => s.teamId !== null).map((s) => s.members.length)).toEqual([7, 6, 5]);+ expect(studios.filter((s) => s.teamId === null).flatMap((s) => s.members)).toHaveLength(8);+ for (const studio of studios.filter((s) => s.teamId !== null)) {+ expect(studio.board).not.toBeNull();+ const places = huddlePlaces(campus.layout, campus.grid, studio);+ // Room for the whole team at its board, in loose arcs: everybody has more than a metre to themselves.+ expect(places.length).toBeGreaterThanOrEqual(studio.members.length);+ for (const [i, p] of places.entries()) {+ expect(isWalkable(campus.grid, p), p.id).toBe(true);+ // Facing the board, from in front of it.+ expect(p.facing).toBeCloseTo(Math.atan2(studio.board!.x - p.x, studio.board!.z - p.z));+ for (const q of places.slice(i + 1)) expect(Math.hypot(p.x - q.x, p.z - q.z), `${p.id} ${q.id}`).toBeGreaterThanOrEqual(HUDDLE_SPACE_M);+ }+ }+ });++ it("offers a visitor a walkable place of its own at every occupied desk", () => {+ for (const desk of allDesks(campus.layout).filter((d) => d.agentId && !d.size)) {+ const slots = visitSlots(desk, campus.grid);+ expect(slots.length, desk.id).toBeGreaterThanOrEqual(1);+ const seat = seatOf(desk);+ for (const slot of slots) expect(Math.hypot(slot.x - seat.x, slot.z - seat.z), slot.id).toBeGreaterThan(BODY_SPACING);+ }+ });+});++describe("idle life with a home", () => {+ it("weights a team member four fifths at home and a pool agent far more towards the shared places", () => {+ const share = (table: readonly (readonly [string, number])[], keys: string[]) =>+ table.filter(([k]) => keys.includes(k)).reduce((s, [, w]) => s + w, 0) / table.reduce((s, [, w]) => s + w, 0);+ expect(share(TEAM_IDLE_WEIGHTS, ["desk", "mate", "huddle", "studio", "near"])).toBeCloseTo(0.8, 2);+ expect(share(TEAM_IDLE_WEIGHTS, ["commons"])).toBeCloseTo(0.14, 2);+ expect(share(POOL_IDLE_WEIGHTS, ["commons"])).toBeCloseTo(0.4, 2);+ expect(POOL_IDLE_WEIGHTS.map(([k]) => k)).not.toContain("huddle");+ expect(COMMONS_WEIGHTS.every(([, w]) => w > 0)).toBe(true);+ });++ it("keeps a team member mostly in and around its own studio", () => {+ const plans = idleDay("a1", 400);+ const home = plans.filter((p) => atHome("a1", p)).length / plans.length;+ expect(home).toBeGreaterThan(0.68);+ expect(home).toBeLessThan(0.95);+ const kinds = new Set(plans.map((p) => p.kind));+ for (const kind of ["desk", "mate", "huddle", "studio"] as const) expect(kinds, kind).toContain(kind);+ // It still gets out: a coffee or the couch now and then.+ expect(plans.some((p) => !atHome("a1", p))).toBe(true);+ });++ it("sends an agent without a team to the shared places far more often", () => {+ const member = idleDay("a1", 400).filter((p) => !atHome("a1", p)).length;+ const pooled = idleDay("a20", 400).filter((p) => !atHome("a20", p)).length;+ expect(homeStudio(campus.layout, "a20", cDesk("a20"))!.teamId).toBeNull();+ expect(pooled).toBeGreaterThan(member * 1.5);+ expect(idleDay("a20", 400).map((p) => p.kind)).not.toContain("huddle");+ });++ it("is the same day for the same agent, and a different one for another", () => {+ const day = idleDay("a3", 120).map((p) => [p.kind, p.spotId, p.target.x, p.target.z, p.dwellMs]);+ expect(idleDay("a3", 120).map((p) => [p.kind, p.spotId, p.target.x, p.target.z, p.dwellMs])).toEqual(day);+ expect(idleDay("a4", 120).map((p) => p.kind)).not.toEqual(day.map((d) => d[0]));+ });++ it("never takes the same home activity twice in a row, and every place is real floor or a real seat", () => {+ const plans = idleDay("a2", 300);+ for (let i = 1; i < plans.length; i += 1) {+ if (["desk", "mate", "huddle"].includes(plans[i].kind)) expect(plans[i].kind, `step ${i}`).not.toBe(plans[i - 1].kind);+ }+ for (const plan of plans) {+ if (plan.pose === "stand") expect(isWalkable(campus.grid, plan.target), `${plan.kind} ${plan.spotId}`).toBe(true);+ expect(findPath(campus.grid, campus.layout.spawn, plan.target), `${plan.kind} ${plan.spotId}`).not.toBeNull();+ }+ });++ it("stands at a teammate's desk only while that teammate sits there, and only watches", () => {+ const studio = homeStudio(campus.layout, "a1", cDesk("a1"))!;+ const mate = mateDesks(campus.layout, studio, "a1")[0];+ const seat = seatOf(mate);+ for (let i = 0; i < 300; i += 1) {+ const plan = planFor(cInput("a1", "idle", { rng: createRng(`mate-${i}`), matesAtDesk: [{ agentId: mate.agentId as string, desk: mate }] }));+ if (plan.kind !== "mate") continue;+ expect(plan).toMatchObject({ with: mate.agentId, pose: "stand" });+ expect(Math.hypot(plan.target.x - seat.x, plan.target.z - seat.z)).toBeLessThan(1.3);+ // Nobody at their desk: nobody to look in on.+ for (let j = 0; j < 200; j += 1) expect(planFor(cInput("a1", "idle", { rng: createRng(`alone-${j}`), matesAtDesk: [] })).kind).not.toBe("mate");+ return;+ }+ throw new Error("no visit to a teammate in 300 seeds");+ });++ it("gives everyone a place of their own, whatever they pick", () => {+ const book = new SpotBook();+ const taken = new Map<string, string>();+ for (let round = 0; round < 6; round += 1) {+ for (const agent of campus.roster) {+ const plan = planFor(cInput(agent.agentId, "idle", { rng: createRng(`${agent.agentId}:${round}`), book }));+ if (plan.spotId) {+ for (const [id, spot] of taken) if (id !== agent.agentId) expect(spot, `${agent.agentId} vs ${id}`).not.toBe(plan.spotId);+ taken.set(agent.agentId, plan.spotId);+ } else taken.delete(agent.agentId);+ }+ }+ });+});++describe("a round of the team", () => {+ const team = (campus.layout.studios ?? []).find((s) => s.teamId === "team-0")!;++ it("brings the free members to their own studio board, each on a place of its own, until it ends", () => {+ const book = new SpotBook();+ const plans = team.members.map((id) => planFor(cInput(id, "idle", { book, round: { speaker: false } })));+ const places = huddlePlaces(campus.layout, campus.grid, team);+ for (const plan of plans) {+ expect(plan).toMatchObject({ kind: "huddle", pose: "stand", dwellMs: Infinity });+ const place = places.find((p) => p.id === plan.spotId)!;+ expect(place).toBeDefined();+ // Facing the board.+ expect(plan.facing).toBeCloseTo(place.facing);+ expect(Math.hypot(plan.target.x - team.board!.x, plan.target.z - team.board!.z)).toBeLessThan(5);+ }+ expect(new Set(plans.map((p) => p.spotId)).size).toBe(team.members.length);+ });++ it("never pulls a working member away from its screen, nor a waiting or a resting one", () => {+ const id = team.members[2];+ const seat = seatOf(cDesk(id)!);+ expect(planFor(cInput(id, "working", { round: { speaker: false } }))).toMatchObject({ kind: "work", target: { x: seat.x, z: seat.z } });+ expect(planFor(cInput(id, "waiting", { round: { speaker: false } })).kind).toBe("wait");+ expect(planFor(cInput(id, "paused", { round: { speaker: false } })).kind).toBe("nap");+ });++ it("places the member contributing right now at the board, although its run state reads working", () => {+ const plan = planFor(cInput(team.members[1], "working", { round: { speaker: true } }));+ expect(plan.kind).toBe("huddle");+ expect(huddlePlaces(campus.layout, campus.grid, team).map((p) => p.id)).toContain(plan.spotId);+ });++ it("fills the arc nearest the board first, so nobody has to squeeze through the people already there", () => {+ const book = new SpotBook();+ const board = team.board!;+ const places = huddlePlaces(campus.layout, campus.grid, team);+ const depth = (id: string | null) => { const p = places.find((q) => q.id === id)!; return Math.hypot(p.x - board.x, p.z - board.z); };+ const depths = team.members.map((id) => depth(planFor(cInput(id, "idle", { book, round: { speaker: false } })).spotId));+ for (let i = 1; i < depths.length; i += 1) expect(depths[i]).toBeGreaterThanOrEqual(depths[i - 1] - 0.01);+ expect(depths[0]).toBeLessThan(depths[depths.length - 1]);+ });++ it("leaves the person room: nobody takes a place on the person's toes, and whoever stands there moves aside", () => {+ const places = huddlePlaces(campus.layout, campus.grid, team);+ const person = { x: places[0].x + 0.2, z: places[0].z };+ const book = new SpotBook();+ const plans = team.members.slice(0, 4).map((id) => planFor(cInput(id, "idle", { book, person, round: { speaker: false } })));+ for (const plan of plans) expect(Math.hypot(plan.target.x - person.x, plan.target.z - person.z)).toBeGreaterThanOrEqual(PERSON_SPACE_M);+ // An agent already standing where the person walks to gives the place up for another one.+ const mover = team.members[5];+ const before = planFor(cInput(mover, "idle", { book, round: { speaker: false } }));+ const here = { x: before.target.x, z: before.target.z + 0.3 };+ const after = planFor(cInput(mover, "idle", { book, person: here, round: { speaker: false } }));+ expect(after.kind).toBe("huddle");+ expect(after.spotId).not.toBe(before.spotId);+ expect(Math.hypot(after.target.x - here.x, after.target.z - here.z)).toBeGreaterThanOrEqual(PERSON_SPACE_M);+ // With no other place left it stays rather than leaving the round.+ const full = new SpotBook();+ for (const p of places) if (p.id !== before.spotId) full.claim(p.id, `holder-${p.id}`);+ full.claim(before.spotId!, mover);+ expect(planFor(cInput(mover, "idle", { book: full, person: here, round: { speaker: false } })).spotId).toBe(before.spotId);+ });++ it("keeps a member on its place when it is planned again mid-round", () => {+ const book = new SpotBook();+ const id = team.members[0];+ const first = planFor(cInput(id, "idle", { book, round: { speaker: false } }));+ for (let i = 0; i < 20; i += 1) {+ const again = planFor(cInput(id, i % 2 ? "working" : "idle", { book, rng: createRng(`again-${i}`), round: { speaker: true } }));+ expect(again.spotId).toBe(first.spotId);+ }+ });++ it("gathers a member that sits in another studio at the board of the team whose round it is", () => {+ const outsider = "a20";+ const plan = planFor(cInput(outsider, "idle", { round: { speaker: false, teamId: "team-0" } }));+ expect(plan.kind).toBe("huddle");+ expect(huddlePlaces(campus.layout, campus.grid, team).map((p) => p.id)).toContain(plan.spotId);+ });++ it("goes back to its desk first when the round has ended", () => {+ const id = team.members[3];+ const seat = seatOf(cDesk(id)!);+ for (let i = 0; i < 20; i += 1) {+ expect(planFor(cInput(id, "idle", { rng: createRng(`back-${i}`), backToDesk: true }))).toMatchObject({ kind: "desk", target: { x: seat.x, z: seat.z }, pose: "sit" });+ }+ });++ it("lets the person's call outrank a round", () => {+ const caller = campus.layout.checkpoints.find((c) => c.id === "break")!;+ expect(planFor(cInput(team.members[0], "idle", { calledTo: caller, round: { speaker: false } })).kind).toBe("called");+ });+});++describe("a team with a lead", () => {+ // The same campus, and the same with the first team led by its third member.+ const led = campusOf(26, [7, 6, 5], [2]);+ const team = studioOfTeam(led.layout, "team-0")!;+ const plain = studioOfTeam(campus.layout, "team-0")!;+ const places = huddlePlaces(led.layout, led.grid, team);+ const centre = leadPlace(places, team)!;+ const lInput = (agentId: string, state: AgentRunState, extra: Partial<PlanInput> = {}): PlanInput => ({+ agentId, state, desk: allDesks(led.layout).find((d) => d.agentId === agentId) ?? null, layout: led.layout, grid: led.grid,+ rng: createRng(agentId), book: new SpotBook(), previous: null, workingColleagues: [], calledTo: null, ...extra,+ });++ it("knows its lead, and the lead's place is the middle of the front arc", () => {+ expect(team.leadId).toBe(led.teams[0].members[2]);+ expect(plain.leadId).toBeNull();+ expect(centre.id).toBe(`fan:${team.deptId}:0:0`);+ const board = team.board!;+ const aside = (p: { x: number; z: number }) => Math.abs((p.x - board.x) * Math.cos(board.facing) - (p.z - board.z) * Math.sin(board.facing));+ const front = places.filter((p) => p.id.startsWith(`fan:${team.deptId}:0:`));+ for (const p of front) expect(aside(centre)).toBeLessThanOrEqual(aside(p) + 1e-6);+ // A studio without a lead has no special place.+ expect(leadPlace(huddlePlaces(campus.layout, campus.grid, plain), plain)).toBeNull();+ });++ it("stands the lead at the centre of the front arc in a round, whenever it comes", () => {+ const lead = team.leadId!;+ // First to arrive.+ expect(planFor(lInput(lead, "idle", { round: { speaker: false } })).spotId).toBe(centre.id);+ // Last to arrive: the others left the place free.+ const book = new SpotBook();+ const others = team.members.filter((id) => id !== lead).map((id) => planFor(lInput(id, "idle", { book, round: { speaker: false } })));+ expect(others.map((p) => p.spotId)).not.toContain(centre.id);+ expect(new Set(others.map((p) => p.spotId)).size).toBe(others.length);+ expect(planFor(lInput(lead, "idle", { book, round: { speaker: false } })).spotId).toBe(centre.id);+ // As the speaker, too.+ expect(planFor(lInput(lead, "working", { round: { speaker: true } })).spotId).toBe(centre.id);+ });++ it("does not move a working lead, and invents nothing for an idle one", () => {+ const lead = team.leadId!;+ expect(planFor(lInput(lead, "working", { round: { speaker: false } })).kind).toBe("work");+ expect(planFor(lInput(lead, "waiting", { round: { speaker: false } })).kind).toBe("wait");+ // No round: the lead's idle day is drawn exactly like a member's, place by place.+ const rng = () => createRng("same-seed");+ const asLead = Array.from({ length: 1 }, () => { const r = rng(); return Array.from({ length: 60 }, () => planFor(lInput(lead, "idle", { rng: r }))); })[0];+ const noLead = { ...led.layout, studios: (led.layout.studios ?? []).map((s) => ({ ...s, leadId: null })) };+ const r = rng();+ const asMember = Array.from({ length: 60 }, () => planFor(lInput(lead, "idle", { rng: r, layout: noLead })));+ expect(asLead.map((p) => [p.kind, p.spotId, p.target.x, p.target.z, p.dwellMs])).toEqual(asMember.map((p) => [p.kind, p.spotId, p.target.x, p.target.z, p.dwellMs]));+ });++ it("gives the lead's place to a member only when no other is left, and to the lead another when the person stands on it", () => {+ const lead = team.leadId!;+ const book = new SpotBook();+ for (const p of places) if (p.id !== centre.id) book.claim(p.id, `holder-${p.id}`);+ expect(planFor(lInput(team.members[0], "idle", { book, round: { speaker: false } })).spotId).toBe(centre.id);+ const plan = planFor(lInput(lead, "idle", { person: { x: centre.x, z: centre.z + 0.2 }, round: { speaker: false } }));+ expect(plan.kind).toBe("huddle");+ expect(plan.spotId).not.toBe(centre.id);+ });++ it("plans a team without a lead exactly as before", () => {+ // Round by round and seed by seed, the same places as on the campus that never heard of leads.+ const withNull = { ...campus.layout, studios: (campus.layout.studios ?? []).map((s) => ({ ...s, leadId: null })) };+ for (let seed = 0; seed < 20; seed += 1) {+ const a = new SpotBook(), b = new SpotBook();+ for (const id of plain.members) {+ const first = planFor(cInput(id, "idle", { book: a, rng: createRng(`${id}:${seed}`), round: { speaker: false } }));+ const second = planFor(cInput(id, "idle", { book: b, rng: createRng(`${id}:${seed}`), layout: withNull, round: { speaker: false } }));+ expect(second).toEqual(first);+ }+ }+ });+});++describe("a message walked over", () => {+ const giver = "a8", receiver = "a1";+ const receiverDesk = cDesk(receiver)!;++ it("takes the free sender to a place beside the receiver's chair, to talk for a moment", () => {+ const seat = seatOf(receiverDesk);+ const plan = planFor(cInput(giver, "idle", { handoff: { to: receiver, desk: receiverDesk, seated: true, at: seat } }));+ expect(plan).toMatchObject({ kind: "handoff", pose: "talk", with: receiver, dwellMs: HANDOFF_DWELL_MS });+ expect(plan.spotId).toMatch(/^visit:/);+ expect(isWalkable(campus.grid, plan.target)).toBe(true);+ const gap = Math.hypot(plan.target.x - seat.x, plan.target.z - seat.z);+ expect(gap).toBeGreaterThan(BODY_SPACING);+ expect(gap).toBeLessThan(1.3);+ });++ it("walks to where the receiver stands when it is away from its desk", () => {+ const at = campus.layout.spots.find((s) => s.kind === "coffee")!;+ const plan = planFor(cInput(giver, "idle", { position: campus.layout.spawn, handoff: { to: receiver, desk: receiverDesk, seated: false, at } }));+ expect(plan.kind).toBe("handoff");+ expect(isWalkable(campus.grid, plan.target)).toBe(true);+ const gap = Math.hypot(plan.target.x - at.x, plan.target.z - at.z);+ expect(gap).toBeGreaterThan(BODY_SPACING);+ expect(gap).toBeLessThan(1.6);+ expect(plan.facing).toBeCloseTo(Math.atan2(at.x - plan.target.x, at.z - plan.target.z));+ });++ it("never moves a sender that is working, waiting or resting", () => {+ const handoff = { to: receiver, desk: receiverDesk, seated: true, at: seatOf(receiverDesk) };+ expect(planFor(cInput(giver, "working", { handoff })).kind).toBe("work");+ expect(planFor(cInput(giver, "waiting", { handoff })).kind).toBe("wait");+ expect(planFor(cInput(giver, "paused", { handoff })).kind).toBe("nap");+ });++ it("is skipped when the receiver is nowhere to be found", () => {+ expect(planFor(cInput(giver, "idle", { handoff: { to: "gone", desk: null, seated: false, at: null } })).kind).not.toBe("handoff");+ });+});++describe("trips on a small roster", () => {+ it("reaches less far the fewer agents there are", () => {+ expect(tripReach(1)).toBe(TRIP_REACH.fewM);+ expect(tripReach(5)).toBe(TRIP_REACH.fewM);+ expect(tripReach(60)).toBe(TRIP_REACH.manyM);+ expect(tripReach(18)).toBeGreaterThan(TRIP_REACH.fewM);+ expect(tripReach(18)).toBeLessThan(TRIP_REACH.manyM);+ });++ it("keeps five agents round their studio and the commons near it instead of crossing the campus", () => {+ const small = campusOf(5, [3]);+ const desks = new Map(allDesks(small.layout).filter((d) => d.agentId).map((d) => [d.agentId as string, d]));+ const far: number[] = [];+ let trips = 0, longTrips = 0, plans = 0;+ for (const agent of small.roster) {+ const studio = homeStudio(small.layout, agent.agentId, desks.get(agent.agentId)!)!;+ const rng = createRng(agent.agentId);+ const book = new SpotBook();+ let previous: ActivityKind | null = null;+ for (let i = 0; i < 300; i += 1) {+ const plan = planFor({+ agentId: agent.agentId, state: "idle", desk: desks.get(agent.agentId)!, layout: small.layout, grid: small.grid, rng, book,+ previous, workingColleagues: [], calledTo: null,+ });+ previous = plan.kind;+ plans += 1;+ const away = Math.hypot(plan.target.x - studio.centre.x, plan.target.z - studio.centre.z);+ if (away > 14) { trips += 1; far.push(away); }+ if (away > 30) longTrips += 1;+ }+ }+ // The floor is far larger than that: without the bias its windows and far rooms would take a good share.+ const spread = Math.max(...small.layout.spots.map((s) => Math.hypot(s.x, s.z)));+ expect(spread).toBeGreaterThan(30);+ expect(trips).toBeGreaterThan(0);+ expect(longTrips / plans).toBeLessThan(0.03);+ expect(trips / plans).toBeLessThan(0.3);+ });++ it("still lets a full floor range further", () => {+ const share = (count: number, sizes: number[]) => {+ const floor = campusOf(count, sizes);+ const desks = new Map(allDesks(floor.layout).filter((d) => d.agentId).map((d) => [d.agentId as string, d]));+ let long = 0, plans = 0;+ for (const agent of floor.roster.slice(0, 5)) {+ const studio = homeStudio(floor.layout, agent.agentId, desks.get(agent.agentId)!)!;+ const rng = createRng(agent.agentId);+ const book = new SpotBook();+ for (let i = 0; i < 400; i += 1) {+ const plan = planFor({ agentId: agent.agentId, state: "idle", desk: desks.get(agent.agentId)!, layout: floor.layout, grid: floor.grid, rng, book, previous: null, workingColleagues: [], calledTo: null });+ plans += 1;+ if (Math.hypot(plan.target.x - studio.centre.x, plan.target.z - studio.centre.z) > 22) long += 1;+ }+ }+ return long / plans;+ };+ // The same five agents of the same first team, alone on the floor and among sixty.+ expect(share(60, [5, 9, 8, 7, 6, 6])).toBeGreaterThan(share(5, [5]));+ });+});++describe("what a name plate says", () => {+ it("calls idle life in the studio what it is, and keeps the team board for a real gathering", () => {+ // Standing at the board or beside a studio mate on an ordinary idle day says nothing about teamwork.+ expect(shownActivity("huddle", false)).toBe("studio");+ expect(shownActivity("mate", false)).toBe("studio");+ expect(shownActivity("mate", true)).toBe("studio");+ // A running round, or a meeting the person called at the board.+ expect(shownActivity("huddle", true)).toBe("huddle");+ // Everything else is itself.+ for (const kind of ["work", "wait", "desk", "coffee", "studio", "wander", "visit", "handoff", "called", "meeting"] as const) {+ expect(shownActivity(kind, false)).toBe(kind);+ expect(shownActivity(kind, true)).toBe(kind);+ }+ });++ it("is never the team board for an idle day without a round, whatever the agent picks", () => {+ for (const plan of idleDay("a1", 300)) expect(shownActivity(plan.kind, false)).not.toBe("huddle");+ });+});++describe("a rebuilt floor plan", () => {+ it("keeps a plan whose place is still there and drops one whose spot is gone or built over", () => {+ const spot = campus.layout.spots.find((s) => s.kind === "coffee")!;+ const atSpot: Plan = { kind: "coffee", target: { x: spot.x, z: spot.z }, facing: spot.facing, pose: "stand", dwellMs: 9000, spotId: spot.id, with: null };+ expect(planStillValid(atSpot, campus.layout, campus.grid)).toBe(true);+ expect(planStillValid({ ...atSpot, spotId: "coffee-of-another-floor" }, campus.layout, campus.grid)).toBe(false);+ expect(planStillValid({ ...atSpot, target: { x: spot.x + 2, z: spot.z } }, campus.layout, campus.grid)).toBe(false);+ const desk = cDesk("a1")!;+ const stroll: Plan = { kind: "studio", target: campus.layout.spawn, facing: null, pose: "stand", dwellMs: 8000, spotId: null, with: null };+ expect(planStillValid(stroll, campus.layout, campus.grid)).toBe(true);+ expect(planStillValid({ ...stroll, target: { x: desk.x, z: desk.z } }, campus.layout, campus.grid)).toBe(false);+ // A place of our own (at a board, beside a desk) holds while that board or desk still stands there.+ const studio = (campus.layout.studios ?? []).find((s) => s.teamId === "team-0")!;+ const place = huddlePlaces(campus.layout, campus.grid, studio)[0];+ const atBoard: Plan = { kind: "huddle", target: { x: place.x, z: place.z }, facing: place.facing, pose: "stand", dwellMs: Infinity, spotId: place.id, with: null };+ expect(planStillValid(atBoard, campus.layout, campus.grid)).toBe(true);+ const slot = visitSlots(desk, campus.grid)[0];+ const beside: Plan = { kind: "mate", target: { x: slot.x, z: slot.z }, facing: slot.facing, pose: "stand", dwellMs: 9000, spotId: slot.id, with: "a1" };+ expect(planStillValid(beside, campus.layout, campus.grid)).toBe(true);+ // The same plans on a floor where the team's studio stands elsewhere: the places are gone.+ const moved = campusOf(26, [5, 7, 6]);+ expect(planStillValid({ ...atBoard, spotId: "fan:studio-gone:0:0" }, moved.layout, moved.grid)).toBe(false);+ expect(planStillValid({ ...atBoard, target: { x: place.x + 3, z: place.z } }, campus.layout, campus.grid)).toBe(false);+ expect(planStillValid({ ...beside, spotId: "visit:999.00,999.00", target: { x: 999, z: 999 } }, campus.layout, campus.grid)).toBe(false);+ // Plans at the agent's own desk are checked by their desk, not here.+ expect(planStillValid({ ...stroll, kind: "work", target: { x: desk.x, z: desk.z } }, campus.layout, campus.grid)).toBe(true);+ });+});++describe("a floor several times larger", () => {+ it("stretches a stay after a long walk and leaves calls and open-ended stays alone", () => {+ const plan: Plan = { kind: "coffee", target: { x: 0, z: 0 }, facing: 0, pose: "stand", dwellMs: 10000, spotId: "coffee-1", with: null };+ expect(dwellAfter(plan, 3)).toBe(10000);+ expect(dwellAfter(plan, 54)).toBeCloseTo(128000, -2);+ expect(dwellAfter(plan, 500)).toBe(150000);+ expect(dwellAfter({ ...plan, dwellMs: Infinity }, 54)).toBe(Infinity);+ expect(dwellAfter({ ...plan, kind: "handoff" }, 54)).toBe(10000);+ expect(dwellAfter({ ...plan, kind: "called" }, 54)).toBe(10000);+ });++ it("shows people being somewhere: at any moment about one idle agent in six is on the move, the rest are somewhere", () => {+ // 60 idle agents over twenty simulated minutes, each living its seeded day on a shared reservation book.+ const big = campusOf(60, [10, 9, 8, 7, 6, 6]);+ const book = new SpotBook();+ const desks = new Map(allDesks(big.layout).filter((d) => d.agentId).map((d) => [d.agentId as string, d]));+ const people = big.roster.map((a) => ({+ id: a.agentId, rng: createRng(a.agentId), clock: 0, walked: 0, away: 0, at: seatOf(desks.get(a.agentId)!) as Point,+ previous: null as ActivityKind | null, seated: true,+ }));+ const END_S = 20 * 60;+ for (;;) {+ const person = people.reduce((a, b) => (a.clock <= b.clock ? a : b));+ if (person.clock >= END_S) break;+ const studio = homeStudio(big.layout, person.id, desks.get(person.id)!)!;+ const matesAtDesk = mateDesks(big.layout, studio, person.id)+ .filter((d) => people.find((p) => p.id === d.agentId)?.seated).map((d) => ({ agentId: d.agentId as string, desk: d }));+ const plan = planFor({+ agentId: person.id, state: "idle", desk: desks.get(person.id)!, layout: big.layout, grid: big.grid, rng: person.rng, book,+ previous: person.previous, workingColleagues: [], calledTo: null, position: person.at, matesAtDesk,+ });+ const path = findPath(big.grid, person.at, plan.target);+ expect(path, `${person.id} ${plan.kind}`).not.toBeNull();+ const metres = pathLength(person.at, path!);+ // The pace at the start of the leg is the fastest it gets; the walk is at least this long.+ const walkS = metres / paceFor(metres);+ const stayS = dwellAfter(plan, metres) / 1000;+ person.walked += walkS;+ if (Math.hypot(plan.target.x - studio.centre.x, plan.target.z - studio.centre.z) > 14) person.away += stayS;+ person.clock += walkS + stayS;+ person.at = plan.target;+ person.previous = plan.kind;+ person.seated = plan.kind === "desk";+ }+ const total = people.reduce((s, p) => s + p.clock, 0);+ const walking = people.reduce((s, p) => s + p.walked, 0) / total;+ expect(walking).toBeLessThan(0.22);+ expect(walking).toBeGreaterThan(0.05);+ // Nobody is a commuter, and the team members' time is spent near home.+ for (const p of people) expect(p.walked / p.clock, p.id).toBeLessThan(0.3);+ const members = people.filter((p) => homeStudio(big.layout, p.id, desks.get(p.id)!)!.teamId !== null);+ const awayShare = (list: typeof people) => list.reduce((s, p) => s + p.away, 0) / list.reduce((s, p) => s + p.clock, 0);+ expect(awayShare(members)).toBeLessThan(0.33);+ // Agents without a team are out and about clearly more.+ expect(awayShare(people.filter((p) => !members.includes(p)))).toBeGreaterThan(awayShare(members) * 1.25);+ });});diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeBehavior.ts b/jarvis/ui/web/frontend/src/components/society/office/officeBehavior.tsindex 427702bb8b..61301399c4 100644--- a/jarvis/ui/web/frontend/src/components/society/office/officeBehavior.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/officeBehavior.ts@@ -5,16 +5,28 @@* The map is a projection of the roster: it never starts work, and idle life* (coffee, couch, wandering) costs zero model calls. Working, waiting and* paused agents mirror their real run state; only idle agents pick hobbies.+ *+ * On a floor with team studios an agent belongs somewhere: its idle life+ * happens mostly in and around its own studio (its desk, the studio board, a+ * teammate's desk, a stroll between the benches), and only sometimes at the+ * shared places. Two things outrank idle life because they are real: a round+ * of its team (it stands at the studio board) and a message it sent a+ * colleague (it walks over). A floor without studios keeps the plain idle+ * day.*/import type { AgentRunState } from "../data";-import { seatOf, standOf, type DeskSlot, type OfficeLayout, type Point, type Rect, type Spot, type SpotKind } from "./officeLayout";-import { nearestWalkable, randomWalkablePoint, type NavGrid } from "./officeNav";+import { seatOf, standOf, type DeskSlot, type OfficeLayout, type Point, type Rect, type Spot, type SpotKind, type Studio } from "./officeLayout";+import { BODY_SPACING, clearOfBodies, WALK_SPEED } from "./officeMotion";+import { isWalkable, nearestWalkable, randomWalkablePoint, type NavGrid } from "./officeNav";+import { homeStudio, huddlePlaces, leadPlace, studioOfTeam, studioRect, visitSlots, type Place } from "./officeTeams";export type Pose = "sit" | "stand" | "sleep" | "wave" | "talk" | "work";export type ActivityKind =| "work" | "wait" | "desk" | "coffee" | "couch" | "nap" | "window" | "shelf" | "arcade"- | "cooler" | "beanbag" | "meeting" | "board" | "wander" | "visit" | "called";+ | "cooler" | "beanbag" | "meeting" | "board" | "wander" | "visit" | "called"+ // Team life: at the own studio board, at a teammate's desk, strolling in the own studio, walking a message over.+ | "huddle" | "mate" | "studio" | "handoff";export interface Plan {kind: ActivityKind;@@ -47,6 +59,11 @@ export function createRng(seed: string): () => number {};}+/** Ids of standing places the floor plan does not list: beside a desk (`visit:`) and at a studio board (`fan:`). */+export function isOwnPlace(spotId: string): boolean {+ return spotId.startsWith("visit:") || spotId.startsWith("fan:");+}+/** Exclusive claims on hangout spots: one agent per spot, one spot per agent. */export class SpotBook {private bySpot = new Map<string, string>();@@ -69,10 +86,17 @@ export class SpotBook {if (this.bySpot.get(spotId) === agentId) this.bySpot.delete(spotId);}- /** Keep only claims on spots that still exist (after the floor plan was rebuilt). */+ /**+ * Keep only claims on spots that still exist (after the floor plan was+ * rebuilt). Claims on places the plan does not list (beside a desk, at a+ * studio board) are kept: each belongs to a walker that checks its own+ * plan against the new floor (`planStillValid`) and lets go when the place+ * is gone. Dropping them here would hand an occupied place to the next+ * agent that plans.+ */retain(spotIds: ReadonlySet<string>): void {for (const [spotId, agentId] of [...this.bySpot]) {- if (!spotIds.has(spotId)) { this.bySpot.delete(spotId); this.byAgent.delete(agentId); }+ if (!spotIds.has(spotId) && !isOwnPlace(spotId)) { this.bySpot.delete(spotId); this.byAgent.delete(agentId); }}}@@ -80,6 +104,11 @@ export class SpotBook {return this.bySpot.get(spotId) ?? null;}+ /** The spot an agent holds right now, or null. */+ spotOf(agentId: string): string | null {+ return this.byAgent.get(agentId) ?? null;+ }+isFree(spotId: string): boolean {return !this.bySpot.has(spotId);}@@ -100,21 +129,101 @@ export interface PlanInput {position?: Point | null;/** A team meeting's chair for this agent (a `meeting-*` spot id); it sits there instead of standing by `calledTo`. */calledSeat?: string | null;+ /**+ * The agent's team runs a round right now and this agent takes part in it:+ * it stands at the studio board. `speaker` = it is the one contributing at+ * the moment (the only working member a round ever moves). `teamId` names+ * the team when it is not the agent's home studio (an agent in several teams).+ */+ round?: { speaker: boolean; teamId?: string | null } | null;+ /** A real message this agent sent a colleague and has not walked over yet: the receiver, its desk, and whether it sits there. */+ handoff?: { to: string; desk: DeskSlot | null; seated: boolean; at: Point | null } | null;+ /** Studio mates sitting at their own desk right now: worth walking over to. */+ matesAtDesk?: { agentId: string; desk: DeskSlot }[];+ /** The round this agent stood in has just ended: it goes back to its desk before anything else. */+ backToDesk?: boolean;+ /** Where everybody else stands right now; a place beside a desk that somebody already stands at is not offered. */+ bodies?: readonly Point[];+ /** Where the person's character stands: agents at a board leave it room. */+ person?: Point | null;}-/** Idle activities and their relative weights. */+/** Idle activities and their relative weights on a floor without studios. */const IDLE_WEIGHTS: readonly [ActivityKind, number][] = [["couch", 22], ["coffee", 18], ["window", 12], ["cooler", 8], ["arcade", 8], ["shelf", 7], ["beanbag", 8],["meeting", 5], ["board", 4], ["wander", 10], ["visit", 6], ["desk", 10],];+/**+ * What an idle agent with a home does next. `desk`, `mate`, `huddle`, `studio`+ * and `near` keep it in and around its studio; `commons` is a trip to a shared+ * place anywhere on the floor; `wander` a stroll in the neighbourhood;+ * `visit` a look at a busy colleague's desk.+ */+export type IdleChoice = "desk" | "mate" | "huddle" | "studio" | "near" | "commons" | "wander" | "visit";++/**+ * A team member: four in five of its idle choices keep it at home, one in seven is a trip to a shared place.+ * A trip earns a long stay (`dwellAfter`), so by the clock it weighs more than by the count; these numbers are+ * tuned for the clock, where a member still spends about two thirds of its idle time in and around its studio.+ */+export const TEAM_IDLE_WEIGHTS: readonly [IdleChoice, number][] = [+ ["desk", 30], ["mate", 14], ["huddle", 12], ["studio", 12], ["near", 12], ["commons", 14], ["wander", 6],+];++/** An agent without a team (the pool studio): its desk is home, but it uses the shared places far more. */+export const POOL_IDLE_WEIGHTS: readonly [IdleChoice, number][] = [+ ["desk", 20], ["studio", 10], ["near", 10], ["visit", 8], ["commons", 40], ["wander", 12],+];++/** Which shared place a trip goes to. */+export const COMMONS_WEIGHTS: readonly [SpotKind, number][] = [+ ["couch", 22], ["coffee", 18], ["window", 12], ["cooler", 8], ["arcade", 8], ["shelf", 7], ["beanbag", 8], ["meeting", 4], ["board", 3],+];+const SPOT_KIND: Partial<Record<ActivityKind, SpotKind>> = {couch: "couch", coffee: "coffee", window: "window", cooler: "cooler", arcade: "arcade",shelf: "shelf", beanbag: "beanbag", meeting: "meeting", board: "board",};+const HANGOUT_KINDS: ReadonlySet<SpotKind> = new Set(Object.values(SPOT_KIND));+const CALLED_DISTANCE = 1.2;const CALLED_DWELL_MS = 15000;+/** How long the sender of a message stays with its receiver. */+export const HANDOFF_DWELL_MS = 8000;+/** Places at the board within this much of the nearest free one count as the same row. */+const HUDDLE_ROW_M = 0.45;+/** An agent at a board keeps this far from the person's character, and makes room when the person comes closer than PERSON_CROWD_M. */+export const PERSON_SPACE_M = 1.25;+export const PERSON_CROWD_M = 0.95;+/** A spot this far beyond the studio's own floor still counts as "round the corner". */+const NEAR_MARGIN_M = 3.5;+/** A stroll in the neighbourhood stays within this distance of the studio's centre. */+const STROLL_RADIUS_M = 12;+/**+ * How far a trip to a shared place reaches: at this distance from the studio a place is half as likely as one+ * next door, at twice the distance a fifth. A handful of agents on a large campus keep to their neighbourhood+ * and the commons at its centre; a full floor ranges further.+ */+export const TRIP_REACH = { fewM: 10, manyM: 20, few: 6, many: 30 } as const;++/** The reach of a trip on a floor with `population` seated agents. */+export function tripReach(population: number): number {+ const t = Math.min(1, Math.max(0, (population - TRIP_REACH.few) / (TRIP_REACH.many - TRIP_REACH.few)));+ return TRIP_REACH.fewM + (TRIP_REACH.manyM - TRIP_REACH.fewM) * t;+}++const populationCache = new WeakMap<OfficeLayout, number>();+/** How many agents have a desk on this floor. */+function populationOf(layout: OfficeLayout): number {+ let count = populationCache.get(layout);+ if (count === undefined) {+ count = layout.lead.desks.filter((d) => d.agentId).length + layout.departments.reduce((n, dept) => n + dept.desks.filter((d) => d.agentId).length, 0);+ populationCache.set(layout, count);+ }+ return count;+}function between(rng: () => number, minMs: number, maxMs: number): number {return Math.round(minMs + rng() * (maxMs - minMs));@@ -124,6 +233,16 @@ function pick<T>(rng: () => number, items: readonly T[]): T {return items[Math.min(items.length - 1, Math.floor(rng() * items.length))];}+function weighted<T>(rng: () => number, options: readonly (readonly [T, number])[]): T {+ const total = options.reduce((sum, [, w]) => sum + w, 0);+ let roll = rng() * total;+ for (const [value, w] of options) {+ if (roll < w) return value;+ roll -= w;+ }+ return options[options.length - 1][0];+}+function poseOfSpot(spot: Spot): Pose {return spot.pose;}@@ -148,8 +267,28 @@ function openOffice(layout: OfficeLayout): Rect {};}+/** How often a stroll draws again when its place turns out to be somebody's, or a bottleneck. */+const STROLL_DRAWS = 6;+/** The ring of points round a place that must be floor for it to count as open ground. */+const STANDING_ROOM: readonly [number, number][] = [0, 1, 2, 3, 4, 5, 6, 7].map((i) => [Math.sin((i * Math.PI) / 4) * 0.7, Math.cos((i * Math.PI) / 4) * 0.7]);++/**+ * A free patch of floor inside `within` to stroll to: open ground, and not where somebody already stands or+ * sits. After a few draws it takes what it has (the walk stops beside whoever is there).+ */+function strollPoint(input: PlanInput, within?: Rect): Point | null {+ let point = randomWalkablePoint(input.grid, input.rng, within);+ const bodies = input.bodies ?? [];+ // Open ground: floor a body's width to every side, so nobody stops for a rest in a doorway or a gap between planters.+ const roomy = (p: Point) => STANDING_ROOM.every(([dx, dz]) => isWalkable(input.grid, { x: p.x + dx, z: p.z + dz }));+ for (let i = 1; i < STROLL_DRAWS && point && !(roomy(point) && clearOfBodies(point, bodies, BODY_SPACING * 1.3)); i += 1) {+ point = randomWalkablePoint(input.grid, input.rng, within);+ }+ return point;+}+function wanderPlan(input: PlanInput, pose: Pose, dwellMs: number): Plan {- const target = randomWalkablePoint(input.grid, input.rng, openOffice(input.layout))+ const target = strollPoint(input, openOffice(input.layout))?? randomWalkablePoint(input.grid, input.rng)?? input.layout.spawn;return { kind: "wander", target, facing: null, pose, dwellMs, spotId: null, with: null };@@ -159,6 +298,15 @@ function spotPlan(kind: ActivityKind, spot: Spot, pose: Pose, dwellMs: number):return { kind, target: { x: spot.x, z: spot.z }, facing: spot.facing, pose, dwellMs, spotId: spot.id, with: null };}+function placePlan(kind: ActivityKind, place: Place, pose: Pose, dwellMs: number, withId: string | null = null): Plan {+ return { kind, target: { x: place.x, z: place.z }, facing: place.facing, pose, dwellMs, spotId: place.id, with: withId };+}++function deskPlan(desk: DeskSlot, dwellMs: number): Plan {+ const seat = seatOf(desk);+ return { kind: "desk", target: { x: seat.x, z: seat.z }, facing: seat.facing, pose: "sit", dwellMs, spotId: null, with: null };+}+function calledPlan(input: PlanInput, caller: Point): Plan {const from = input.position;let angle: number;@@ -170,6 +318,83 @@ function calledPlan(input: PlanInput, caller: Point): Plan {return { kind: "called", target, facing, pose: "talk", dwellMs: CALLED_DWELL_MS, spotId: null, with: null };}+/** A free place for a visitor at `desk`, claimed; null when the desk has none left. */+function claimVisitSlot(input: PlanInput, desk: DeskSlot): Place | null {+ const free = visitSlots(desk, input.grid).filter((p) => input.book.isFree(p.id) && clearOfBodies(p, input.bodies ?? []));+ if (free.length === 0) return null;+ const place = pick(input.rng, free);+ input.book.claim(place.id, input.agentId);+ return place;+}++/**+ * Looking in on a colleague at their desk. The visitor stands and watches: no+ * talking pose and no bubble, because nothing was said. Talking is kept for+ * exchanges that really happened. Null when both places beside the chair are+ * taken: nobody queues up behind a visitor.+ */+function visitPlan(input: PlanInput, kind: "visit" | "mate", colleague: { agentId: string; desk: DeskSlot }, dwellMs: number): Plan | null {+ const place = claimVisitSlot(input, colleague.desk);+ return place ? placePlan(kind, place, "stand", dwellMs, colleague.agentId) : null;+}++/**+ * A place at the agent's own studio board, the one it already holds first;+ * null when the studio has none left. In a gathering (`gathered`: a round of+ * the team, not an idle look at the board) a team with a lead keeps the+ * centre of the front arc for it: the lead takes that place when it comes,+ * and the others leave it free while any other place is.+ */+function huddlePlan(input: PlanInput, studio: Studio, held: string | null, pose: Pose, dwellMs: number, gathered = false): Plan | null {+ const places = huddlePlaces(input.layout, input.grid, studio);+ const centre = gathered ? leadPlace(places, studio) : null;+ // The lead takes its place, unless the person is standing on it.+ const personThere = !!centre && !!input.person && Math.hypot(centre.x - input.person.x, centre.z - input.person.z) < PERSON_SPACE_M;+ if (centre && !personThere && studio.leadId === input.agentId && input.book.claim(centre.id, input.agentId)) return placePlan("huddle", centre, pose, dwellMs);+ const unclaimed = places.filter((p) => input.book.isFree(p.id));+ const others = centre && studio.leadId !== input.agentId ? unclaimed.filter((p) => p.id !== centre.id) : unclaimed;+ const open = others.length > 0 ? others : unclaimed;+ // Not on the person's toes: the places round where the person stands are left empty while there are others.+ const person = input.person;+ const roomy = person ? open.filter((p) => Math.hypot(p.x - person.x, p.z - person.z) >= PERSON_SPACE_M) : open;+ const free = roomy.length > 0 ? roomy : open;+ if (free.length === 0) return null;+ const kept = held ? free.find((p) => p.id === held) : undefined;+ // The row nearest the board fills up first, then the ones behind it: whoever comes later never has to squeeze+ // through the people already standing there. Within a row the place is the agent's own draw.+ const board = studio.board!;+ const fromBoard = (p: Place) => Math.hypot(p.x - board.x, p.z - board.z);+ const nearest = Math.min(...free.map(fromBoard));+ const row = free.filter((p) => fromBoard(p) <= nearest + HUDDLE_ROW_M);+ const place = kept ?? pick(input.rng, row);+ input.book.claim(place.id, input.agentId);+ return placePlan("huddle", place, pose, dwellMs);+}++/** Walking a real message over: beside the receiver's chair when it sits there, else a step from where it stands. */+function handoffPlan(input: PlanInput): Plan | null {+ const handoff = input.handoff;+ if (!handoff) return null;+ if (handoff.desk && handoff.seated) {+ const place = claimVisitSlot(input, handoff.desk);+ if (place) return placePlan("handoff", place, "talk", HANDOFF_DWELL_MS, handoff.to);+ }+ const at = handoff.at ?? (handoff.desk ? standOf(handoff.desk) : null);+ if (!at) return null;+ const from = input.position;+ const angle = from && Math.hypot(from.x - at.x, from.z - at.z) > 1e-3 ? Math.atan2(from.x - at.x, from.z - at.z) : input.rng() * Math.PI * 2;+ const wanted = { x: at.x + Math.sin(angle) * 0.95, z: at.z + Math.cos(angle) * 0.95 };+ const target = nearestWalkable(input.grid, wanted, 1.5) ?? nearestWalkable(input.grid, at);+ if (!target) return null;+ return { kind: "handoff", target, facing: Math.atan2(at.x - target.x, at.z - target.z), pose: "talk", dwellMs: HANDOFF_DWELL_MS, spotId: null, with: handoff.to };+}++function spotVisit(kind: ActivityKind, spot: Spot, rng: () => number, away: boolean): Plan {+ if (kind === "couch") return spotPlan(kind, spot, "sit", away ? between(rng, 30000, 60000) : between(rng, 20000, 45000));+ return spotPlan(kind, spot, poseOfSpot(spot) === "sleep" ? "sit" : poseOfSpot(spot), away ? between(rng, 15000, 35000) : between(rng, 8000, 25000));+}++/** The plain idle day of a floor without studios. */function idlePlan(input: PlanInput): Plan {const { rng, desk, previous } = input;const colleagues = input.workingColleagues.filter((c) => c.agentId !== input.agentId);@@ -179,44 +404,103 @@ function idlePlan(input: PlanInput): Plan {return true;});const options = available.length > 1 ? available.filter(([kind]) => kind !== previous) : available;- const total = options.reduce((sum, [, w]) => sum + w, 0);- let roll = rng() * total;- let kind: ActivityKind = options[options.length - 1][0];- for (const [k, w] of options) {- if (roll < w) { kind = k; break; }- roll -= w;- }+ const kind = weighted(rng, options);if (kind === "wander") return wanderPlan(input, "stand", between(rng, 6000, 12000));- if (kind === "desk" && desk) {- const seat = seatOf(desk);- return { kind: "desk", target: { x: seat.x, z: seat.z }, facing: seat.facing, pose: "sit", dwellMs: between(rng, 15000, 30000), spotId: null, with: null };- }+ if (kind === "desk" && desk) return deskPlan(desk, between(rng, 15000, 30000));if (kind === "visit") {- const colleague = pick(rng, colleagues);- const seat = seatOf(colleague.desk);- const stand = standOf(colleague.desk);- return {- kind: "visit", target: { x: stand.x, z: stand.z }, facing: Math.atan2(seat.x - stand.x, seat.z - stand.z),- pose: "talk", dwellMs: between(rng, 8000, 15000), spotId: null, with: colleague.agentId,- };+ return visitPlan(input, "visit", pick(rng, colleagues), between(rng, 8000, 15000)) ?? wanderPlan(input, "stand", between(rng, 6000, 12000));}const spotKind = SPOT_KIND[kind];const spot = spotKind ? claimSpot(input, (s) => s.kind === spotKind) : null;if (!spot) return wanderPlan(input, "stand", between(rng, 6000, 12000));- if (kind === "couch") return spotPlan(kind, spot, "sit", between(rng, 20000, 45000));- return spotPlan(kind, spot, poseOfSpot(spot) === "sleep" ? "sit" : poseOfSpot(spot), between(rng, 8000, 25000));+ return spotVisit(kind, spot, rng, false);+}++/** Which idle choice an activity came from, so the same one is not taken twice in a row. */+function choiceOf(kind: ActivityKind | null): IdleChoice | null {+ if (kind === null) return null;+ if (kind === "desk" || kind === "mate" || kind === "huddle" || kind === "studio" || kind === "wander" || kind === "visit") return kind;+ return SPOT_KIND[kind] ? "commons" : null;+}++function strollPlan(input: PlanInput, kind: "studio" | "wander", within: Rect): Plan {+ const target = strollPoint(input, within)+ ?? nearestWalkable(input.grid, { x: (within.minX + within.maxX) / 2, z: (within.minZ + within.maxZ) / 2 })+ ?? input.layout.spawn;+ return { kind, target, facing: null, pose: "stand", dwellMs: between(input.rng, 6000, 12000), spotId: null, with: null };+}++/** Idle life with a home: mostly in and around the studio, sometimes at the shared places. */+function homeIdlePlan(input: PlanInput, studio: Studio): Plan {+ const { rng, desk, previous, layout, book } = input;+ const rect = studioRect(layout, studio);+ const mates = (input.matesAtDesk ?? []).filter((m) => m.agentId !== input.agentId);+ const colleagues = input.workingColleagues.filter((c) => c.agentId !== input.agentId);+ const reach = Math.hypot(rect.maxX - rect.minX, rect.maxZ - rect.minZ) / 2 + NEAR_MARGIN_M;+ const fromHome = (s: Point) => Math.hypot(s.x - studio.centre.x, s.z - studio.centre.z);+ // Only kinds an activity exists for; a team room chair is a trip, not a place round the corner.+ const hangout = (s: Spot) => HANGOUT_KINDS.has(s.kind) && s.kind !== "meeting" && book.isFree(s.id);+ const nearby = layout.spots.filter((s) => hangout(s) && fromHome(s) <= reach);++ const table = studio.teamId === null ? POOL_IDLE_WEIGHTS : TEAM_IDLE_WEIGHTS;+ const available = table.filter(([choice]) => {+ if (choice === "desk") return desk !== null;+ if (choice === "mate") return mates.length > 0;+ if (choice === "huddle") return studio.board !== null;+ if (choice === "near") return nearby.length > 0;+ if (choice === "visit") return colleagues.length > 0;+ return true;+ });+ const last = choiceOf(previous);+ const options = available.length > 1 ? available.filter(([choice]) => choice !== last) : available;+ const choice = weighted(rng, options);+ const stroll = () => strollPlan(input, "studio", rect);++ // Its own desk is where an agent with a home spends its longest stretches.+ if (choice === "desk" && desk) return deskPlan(desk, between(rng, 40000, 90000));+ if (choice === "mate") return visitPlan(input, "mate", pick(rng, mates), between(rng, 12000, 24000)) ?? stroll();+ if (choice === "visit") return visitPlan(input, "visit", pick(rng, colleagues), between(rng, 8000, 15000)) ?? stroll();+ if (choice === "huddle") return huddlePlan(input, studio, null, "stand", between(rng, 12000, 25000)) ?? stroll();+ if (choice === "studio") return stroll();+ if (choice === "near") {+ const spot = pick(rng, nearby);+ book.claim(spot.id, input.agentId);+ return spotVisit(spot.kind as ActivityKind, spot, rng, false);+ }+ if (choice === "commons") {+ // Every free shared place is a candidate, weighted by what it is and by how far from home it lies: nobody+ // crosses the campus for a window when there is a coffee round the corner, and a small roster stays near.+ const reachM = tripReach(populationOf(layout));+ const kindWeight = new Map(COMMONS_WEIGHTS);+ const open = layout.spots.filter((s) => kindWeight.has(s.kind) && book.isFree(s.id));+ if (open.length === 0) return stroll();+ const perKind = new Map<SpotKind, number>();+ for (const s of open) perKind.set(s.kind, (perKind.get(s.kind) ?? 0) + 1);+ const spot = weighted(rng, open.map((s) => [s, ((kindWeight.get(s.kind) ?? 0) / (perKind.get(s.kind) ?? 1)) / (1 + (fromHome(s) / reachM) ** 2)] as const));+ book.claim(spot.id, input.agentId);+ return spotVisit(spot.kind as ActivityKind, spot, rng, true);+ }+ const c = studio.centre;+ return strollPlan(input, "wander", { minX: c.x - STROLL_RADIUS_M, maxX: c.x + STROLL_RADIUS_M, minZ: c.z - STROLL_RADIUS_M, maxZ: c.z + STROLL_RADIUS_M });}/** Decide the next activity for one agent. Releases its previous spot claim first. */export function planFor(input: PlanInput): Plan {const { agentId, state, desk, book } = input;+ const held = book.spotOf(agentId);book.release(agentId);// 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") {// A meeting seats its members: the assigned chair, else any free chair at the table, else standing by it.- if (input.calledSeat) {+ // A meeting at a studio's own board: the member stands on its place in the arcs.+ if (input.calledSeat?.startsWith("fan:")) {+ const seat = input.calledSeat;+ const at = (input.layout.studios ?? []).filter((s) => seat.startsWith(`fan:${s.deptId}:`))+ .flatMap((s) => huddlePlaces(input.layout, input.grid, s)).find((p) => p.id === seat);+ if (at && book.claim(at.id, agentId)) return placePlan("huddle", at, "stand", Infinity);+ } else if (input.calledSeat) {const assigned = input.layout.spots.find((s) => s.id === input.calledSeat);if (assigned && book.claim(assigned.id, agentId)) return spotPlan("meeting", assigned, "sit", Infinity);const other = claimSpot(input, (s) => s.kind === "meeting");@@ -225,6 +509,16 @@ export function planFor(input: PlanInput): Plan {return calledPlan(input, input.calledTo);}+ const studio = homeStudio(input.layout, agentId, desk);++ // A round of the agent's team: free members stand at the studio board until it ends. Working members stay at+ // their screen, with one exception that is the round itself: the member contributing right now.+ const roundStudio = (input.round?.teamId ? studioOfTeam(input.layout, input.round.teamId) : null) ?? studio;+ if (input.round && roundStudio && (state === "idle" || (state === "working" && input.round.speaker))) {+ const plan = huddlePlan(input, roundStudio, held, "stand", Infinity, true);+ if (plan) return plan;+ }+if (state === "working") {if (desk) {const seat = seatOf(desk);@@ -238,9 +532,12 @@ export function planFor(input: PlanInput): Plan {if (state === "waiting") {if (desk) {const stand = standOf(desk);- return { kind: "wait", target: { x: stand.x, z: stand.z }, facing: stand.facing, pose: "wave", dwellMs: Infinity, spotId: null, with: null };+ // It stands where a visitor to its desk would: holding that place keeps anyone from being sent there meanwhile.+ const beside = visitSlots(desk, input.grid).find((p) => p.x > stand.x - 0.3 && Math.hypot(p.x - stand.x, p.z - stand.z) < BODY_SPACING);+ const held = beside && book.claim(beside.id, agentId) ? beside.id : null;+ return { kind: "wait", target: { x: stand.x, z: stand.z }, facing: stand.facing, pose: "wave", dwellMs: Infinity, spotId: held, with: null };}- const spot = claimSpot(input, (s) => s.pose === "stand");+ const spot = claimSpot(input, (s) => s.pose === "stand" && s.kind !== "huddle");if (spot) return spotPlan("wait", spot, "wave", Infinity);return { ...wanderPlan(input, "wave", Infinity), kind: "wait" };}@@ -257,5 +554,60 @@ export function planFor(input: PlanInput): Plan {return { ...wanderPlan(input, "sit", Infinity), kind: "nap" };}- return idlePlan(input);+ const handoff = handoffPlan(input);+ if (handoff) return handoff;+ if (input.backToDesk && desk) return deskPlan(desk, between(input.rng, 12000, 24000));+ return studio ? homeIdlePlan(input, studio) : idlePlan(input);+}++/**+ * Does a plan made on an earlier floor plan still hold on this one? A spot+ * must still exist where it was; a place to stand must still be floor. Plans+ * bound to the agent's own desk are checked by their desk, not here.+ */+export function planStillValid(plan: Plan, layout: OfficeLayout, grid: NavGrid): boolean {+ if (plan.kind === "work" || plan.kind === "wait" || plan.kind === "desk") return true;+ if (plan.spotId && !isOwnPlace(plan.spotId)) {+ const spot = layout.spots.find((s) => s.id === plan.spotId);+ return !!spot && Math.hypot(spot.x - plan.target.x, spot.z - plan.target.z) < 0.05;+ }+ if (plan.spotId) {+ // A place of our own must still be one on this floor: at a studio's board, or beside a desk that stands there.+ const id = plan.spotId;+ const places = id.startsWith("fan:")+ ? (layout.studios ?? []).filter((s) => id.startsWith(`fan:${s.deptId}:`)).flatMap((s) => huddlePlaces(layout, grid, s))+ : layout.departments.flatMap((d) => d.desks).flatMap((d) => visitSlots(d, grid));+ return places.some((p) => p.id === id && Math.hypot(p.x - plan.target.x, p.z - plan.target.z) < 0.05);+ }+ if (plan.kind === "nap") return true;+ return isWalkable(grid, plan.target);+}++/**+ * What a name plate may say an agent is doing. Standing at the studio board+ * and looking in on a studio mate are part of an idle agent's day, and say+ * nothing about teamwork: both read as being in the studio. "At the team+ * board" is kept for a gathering that is real (`gathered`: a running round of+ * the team, or a meeting the person called there).+ */+export function shownActivity(kind: ActivityKind, gathered: boolean): ActivityKind {+ if (kind === "mate") return "studio";+ if (kind === "huddle" && !gathered) return "studio";+ return kind;+}++/** The longest an idle activity is stretched to. */+const LONGEST_DWELL_MS = 150_000;+/** A stay lasts at least this many times as long as the walk to it would take at walking pace. */+const STAY_PER_WALK = 3.2;++/**+ * How long to stay after walking `walkedM` metres to get there. A long way+ * earns a long stay — at least about three times the time the walk would+ * take at walking pace — so a large floor shows people being somewhere, not a+ * crowd in transit. Calls, hand-offs and open-ended stays keep their own time.+ */+export function dwellAfter(plan: Plan, walkedM: number): number {+ if (!Number.isFinite(plan.dwellMs) || plan.kind === "called" || plan.kind === "handoff") return plan.dwellMs;+ return Math.min(LONGEST_DWELL_MS, Math.max(plan.dwellMs, (walkedM / WALK_SPEED) * 1000 * STAY_PER_WALK));}diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeCamera.test.ts b/jarvis/ui/web/frontend/src/components/society/office/officeCamera.test.tsindex 246c88b5c7..7ed514b404 100644--- a/jarvis/ui/web/frontend/src/components/society/office/officeCamera.test.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/officeCamera.test.ts@@ -1,5 +1,7 @@import { describe, expect, it } from "vitest";-import { cameraHome, CAMERA_LIMITS, depthNear, wheelZoomSpeed } from "./officeCamera";+import {+ cameraHome, CAMERA_LIMITS, depthNear, farZoomBoost, FOLLOW_DISTANCE_M, followDistanceAfterOverview, frameDistance, settleView, WALK_VIEW_MAX_M, wheelZoomSpeed,+} from "./officeCamera";/** OrbitControls' dolly factor for one wheel event at this zoom speed. */const step = (speed: number) => 1 / Math.pow(0.95, speed);@@ -55,3 +57,71 @@ describe("office depth precision", () => {expect(depthNear(CAMERA_LIMITS.minDistance)).toBe(0.2);});});++describe("wheel zoom on a large floor", () => {+ /** Mouse notches from `from` metres until the camera is within `to`, each notch zooming for the distance it starts at. */+ const notches = (from: number, to: number) => {+ let distance = from, count = 0;+ while (distance > to && count < 100) { distance /= step(wheelZoomSpeed(100, 0, distance)); count += 1; }+ return count;+ };+ // The overview of a campus of sixty agents in six teams.+ const overview = frameDistance({ minX: -29.2, maxX: 29.2, minZ: -33.2, maxZ: 33.2 }, 16 / 9);++ it("comes down from the overview of a campus to a studio in a few notches", () => {+ expect(overview).toBeGreaterThan(80);+ expect(notches(overview, 30)).toBeLessThanOrEqual(5);+ expect(notches(overview, FOLLOW_DISTANCE_M)).toBeLessThanOrEqual(10);+ // The same way took more than twice as many notches at one fixed step.+ expect(Math.ceil(Math.log(overview / FOLLOW_DISTANCE_M) / Math.log(step(wheelZoomSpeed(100))))).toBeGreaterThan(14);+ });++ it("stays as fine as it was near the character", () => {+ expect(farZoomBoost(0)).toBe(1);+ expect(farZoomBoost(FOLLOW_DISTANCE_M)).toBe(1);+ expect(wheelZoomSpeed(100, 0, 10)).toBe(wheelZoomSpeed(100));+ expect(wheelZoomSpeed(4, 0, 10)).toBe(wheelZoomSpeed(4));+ // Further out each notch reaches further, smoothly, and no further than a third of the way.+ for (let d = 10; d < 200; d += 5) expect(farZoomBoost(d + 5)).toBeGreaterThanOrEqual(farZoomBoost(d));+ expect(step(wheelZoomSpeed(100, 0, 400))).toBeLessThan(1.6);+ // A trackpad's small steps stay small far out, too.+ expect(wheelZoomSpeed(4, 0, 100)).toBeLessThan(wheelZoomSpeed(100, 0, 100) / 10);+ });+});++describe("following after the overview", () => {+ it("returns to the distance the person walked at, or to the default when that was no walking view", () => {+ expect(followDistanceAfterOverview(11)).toBe(11);+ expect(followDistanceAfterOverview(WALK_VIEW_MAX_M)).toBe(WALK_VIEW_MAX_M);+ expect(followDistanceAfterOverview(80)).toBe(FOLLOW_DISTANCE_M);+ expect(followDistanceAfterOverview(null)).toBe(FOLLOW_DISTANCE_M);+ expect(followDistanceAfterOverview(0.5)).toBe(CAMERA_LIMITS.minDistance);+ });+});++describe("a remembered view on a rebuilt floor", () => {+ const bounds = { minX: -20, maxX: 20, minZ: -20, maxZ: 20 };+ const wall = { minX: 4.94, maxX: 5.06, minZ: -10, maxZ: 10 };++ it("is kept as it is when it still fits", () => {+ const pose = { position: [10, 9, 10] as [number, number, number], target: [0, 0.8, 0] as [number, number, number] };+ expect(settleView(pose, bounds, [wall])).toBe(pose);+ // High above a wall is not inside it.+ const above = { position: [5, 6, 0] as [number, number, number], target: [0, 0.8, 0] as [number, number, number] };+ expect(settleView(above, bounds, [wall])).toBe(above);+ });++ it("is dropped when it looks at a place the floor no longer has", () => {+ expect(settleView({ position: [40, 9, 40], target: [30, 0.8, 30] }, bounds, [])).toBeNull();+ });++ it("backs a camera out of a wall along its line of sight", () => {+ const settled = settleView({ position: [5, 2, 0], target: [1, 0.8, 0] }, bounds, [wall])!;+ expect(settled.target).toEqual([1, 0.8, 0]);+ // Outside the wall and its margin, further from the target, on the same line.+ expect(settled.position[0]).toBeGreaterThan(5.06 + 0.35);+ expect(settled.position[0]).toBeLessThan(7);+ expect(settled.position[2]).toBeCloseTo(0);+ expect((settled.position[1] - 0.8) / (settled.position[0] - 1)).toBeCloseTo((2 - 0.8) / (5 - 1), 6);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeCamera.testkit.ts b/jarvis/ui/web/frontend/src/components/society/office/officeCamera.testkit.tsnew file mode 100644index 0000000000..66f9b1327e--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/officeCamera.testkit.ts@@ -0,0 +1,41 @@+/**+ * Test support for the camera: projects a floor's corners through a camera+ * pose with three.js itself, independent of the fit maths under test.+ */+import { PerspectiveCamera, Vector3 } from "three";+import { CAMERA_FOV, cameraLimitsFor, type Bounds, type CameraPose } from "./officeCamera";++export interface ViewBox { minX: number; maxX: number; minY: number; maxY: number }++/**+ * Are all corners of `bounds` (on the floor and 3 m up) inside the view, how close to an edge does the floor+ * reach (0..1), and which box of the view (-1..1 on both axes) do they span?+ */+export function cornersInView(bounds: Bounds, pose: CameraPose, aspect: number): { inside: boolean; widest: number; box: ViewBox } {+ const camera = new PerspectiveCamera(CAMERA_FOV, aspect, 0.2, 5000);+ camera.position.set(...pose.position);+ camera.lookAt(new Vector3(...pose.target));+ camera.updateMatrixWorld(true);+ camera.updateProjectionMatrix();+ let widest = 0;+ let inside = true;+ const box: ViewBox = { minX: Infinity, maxX: -Infinity, minY: Infinity, maxY: -Infinity };+ for (const x of [bounds.minX, bounds.maxX]) {+ for (const z of [bounds.minZ, bounds.maxZ]) {+ for (const y of [0, 3]) {+ const p = new Vector3(x, y, z).project(camera);+ const reach = Math.max(Math.abs(p.x), Math.abs(p.y));+ if (reach > 1 || p.z > 1 || p.z < -1) inside = false;+ widest = Math.max(widest, reach);+ box.minX = Math.min(box.minX, p.x); box.maxX = Math.max(box.maxX, p.x);+ box.minY = Math.min(box.minY, p.y); box.maxY = Math.max(box.maxY, p.y);+ }+ }+ }+ return { inside, widest, box };+}++/** The limits for the most demanding common viewport (portrait side panel). */+export function campusLimits(bounds: Bounds) {+ return cameraLimitsFor(bounds, 0.62);+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeCamera.ts b/jarvis/ui/web/frontend/src/components/society/office/officeCamera.tsindex 2600c2115f..4012a2fee2 100644--- a/jarvis/ui/web/frontend/src/components/society/office/officeCamera.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/officeCamera.ts@@ -13,9 +13,9 @@ export const CAMERA_LIMITS = {maxDistance: 140,} as const;-/** Near clip plane up close, and the most it may grow to when zoomed out. */+/** Near clip plane up close, and the most it may grow to when zoomed out (a whole campus in view). */const NEAR_MIN = 0.2;-const NEAR_MAX = 6;+const NEAR_MAX = 20;/** Near plane per metre of orbit distance: the closest geometry is always far more than this in front. */const NEAR_PER_METRE = 0.04;@@ -41,16 +41,31 @@ export const DRAG_CLICK_PX = 6;const WHEEL_NOTCH_PX = 100;/** How far one notch zooms, as OrbitControls' zoomSpeed: 0.95^2.4 ≈ 12 % closer or further. */const ZOOM_SPEED_PER_NOTCH = 2.4;+/** From this orbit distance on a notch zooms further, up to FAR_ZOOM.boost times as far at FAR_ZOOM.full metres. */+const FAR_ZOOM = { from: 15, full: 90, boost: 3.5 } as const;++/** How much further one wheel notch zooms at this orbit distance than up close: 1 near the character, 3.5 from the overview of a campus. */+export function farZoomBoost(distance: number): number {+ const t = Math.min(1, Math.max(0, (distance - FAR_ZOOM.from) / (FAR_ZOOM.full - FAR_ZOOM.from)));+ return 1 + (FAR_ZOOM.boost - 1) * t;+}+/*** OrbitControls' zoomSpeed for one wheel event, proportional to how far the* wheel turned. The controls zoom a fixed step per event whatever its size:* a mouse notch crawled (~20 notches from the overview to the character) and* a trackpad, which sends dozens of tiny events, raced. `deltaMode` 1 is* lines, 2 pages (Firefox, some mice).+ *+ * `distance` is the camera's orbit distance: far out a notch covers more of+ * the way (12 % up close, 35 % from a campus overview), so zooming from the+ * overview of a large floor down to a studio takes a few notches, and the+ * last metres stay fine.*/-export function wheelZoomSpeed(deltaY: number, deltaMode = 0): number {+export function wheelZoomSpeed(deltaY: number, deltaMode = 0, distance = 0): number {const px = Math.abs(deltaY) * (deltaMode === 1 ? 40 : deltaMode === 2 ? 800 : 1);- return Math.min(ZOOM_SPEED_PER_NOTCH * 2.5, Math.max(0.02, (px / WHEEL_NOTCH_PX) * ZOOM_SPEED_PER_NOTCH));+ const perNotch = ZOOM_SPEED_PER_NOTCH * farZoomBoost(distance);+ return Math.min(perNotch * 2.5, Math.max(0.02, (px / WHEEL_NOTCH_PX) * perNotch));}/** Look-down angle below the horizon and yaw east of south for the home view. */@@ -61,7 +76,7 @@ export interface Bounds { minX: number; maxX: number; minZ: number; maxZ: numberexport interface CameraPose { position: [number, number, number]; target: [number, number, number] }/** Distance that fits a floor of this footprint into a viewport of this aspect. */-export function fitDistance(bounds: Bounds, aspect: number, fovDeg = CAMERA_FOV, tightness = 0.62): number {+export function fitDistance(bounds: Bounds, aspect: number, fovDeg = CAMERA_FOV, tightness = 0.62, maxDistance: number = CAMERA_LIMITS.maxDistance): number {const width = bounds.maxX - bounds.minX;const depth = bounds.maxZ - bounds.minZ;// Seen diagonally, the floor's screen width is roughly its diagonal; its@@ -71,7 +86,173 @@ export function fitDistance(bounds: Bounds, aspect: number, fovDeg = CAMERA_FOV,const hHalf = Math.atan(Math.tan(vHalf) * Math.max(0.3, aspect));const needH = (diagonal * 0.5) / Math.tan(hHalf);const needV = (diagonal * Math.sin(HOME_PITCH_RAD) * 0.5 + 1.5) / Math.tan(vHalf);- return Math.min(CAMERA_LIMITS.maxDistance, Math.max(CAMERA_LIMITS.minDistance, Math.max(needH, needV) * tightness));+ return Math.min(maxDistance, Math.max(CAMERA_LIMITS.minDistance, Math.max(needH, needV) * tightness));+}++/** How much of the viewport the overview fills: a margin stays for the HUD cards round the edge. */+const OVERVIEW_FILL = 0.9;+/** The overview also keeps what stands this high on the floor's edge in view (walls, signs, name plates). */+const OVERVIEW_HEADROOM_M = 3;++/** The home view's unit vectors: from the target towards the camera, and the camera's right and up. */+function homeAxes(): { back: [number, number, number]; right: [number, number, number]; up: [number, number, number] } {+ const cp = Math.cos(HOME_PITCH_RAD), sp = Math.sin(HOME_PITCH_RAD);+ const sy = Math.sin(HOME_YAW_RAD), cy = Math.cos(HOME_YAW_RAD);+ return { back: [sy * cp, sp, cy * cp], right: [cy, 0, -sy], up: [-sy * sp, cp, -cy * sp] };+}++/**+ * The distance from which the home view holds every corner of `bounds` (on+ * the floor and `headroom` above it) inside the viewport: the exact fit, by+ * projecting the corners, for a floor of any size and shape.+ */+export function frameDistance(bounds: Bounds, aspect: number, fovDeg = CAMERA_FOV, fill = OVERVIEW_FILL, headroom = OVERVIEW_HEADROOM_M): number {+ const { back, right, up } = homeAxes();+ const tanV = Math.tan((fovDeg * Math.PI) / 360) * fill;+ const tanH = Math.tan((fovDeg * Math.PI) / 360) * Math.max(0.3, aspect) * fill;+ const cx = (bounds.minX + bounds.maxX) / 2, cz = (bounds.minZ + bounds.maxZ) / 2;+ let need: number = CAMERA_LIMITS.minDistance;+ for (const x of [bounds.minX, bounds.maxX]) {+ for (const z of [bounds.minZ, bounds.maxZ]) {+ for (const y of [0, headroom]) {+ const p: [number, number, number] = [x - cx, y, z - cz];+ const dot = (a: [number, number, number]) => p[0] * a[0] + p[1] * a[1] + p[2] * a[2];+ // A point this far towards the camera is that much closer to it than the target is.+ const towards = dot(back);+ need = Math.max(need, Math.abs(dot(right)) / tanH + towards, Math.abs(dot(up)) / tanV + towards);+ }+ }+ }+ return need;+}++/** How much of the viewport's binding axis the floor spans in the overview. */+export const OVERVIEW_SPAN = 0.85;++/**+ * Where the corners of `bounds` (on the floor and `headroom` above it) land+ * in the view of a home-angle camera looking at `target` from `distance`:+ * the box they span, in viewport units from -1 to 1.+ */+function projectedBox(bounds: Bounds, target: readonly [number, number], distance: number, aspect: number, fovDeg: number, headroom: number) {+ const { back, right, up } = homeAxes();+ const tanV = Math.tan((fovDeg * Math.PI) / 360);+ const tanH = tanV * Math.max(0.3, aspect);+ let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;+ for (const x of [bounds.minX, bounds.maxX]) {+ for (const z of [bounds.minZ, bounds.maxZ]) {+ for (const y of [0, headroom]) {+ const p: [number, number, number] = [x - target[0], y, z - target[1]];+ const dot = (a: [number, number, number]) => p[0] * a[0] + p[1] * a[1] + p[2] * a[2];+ const depth = Math.max(0.01, distance - dot(back));+ const sx = dot(right) / (depth * tanH), sy = dot(up) / (depth * tanV);+ minX = Math.min(minX, sx); maxX = Math.max(maxX, sx); minY = Math.min(minY, sy); maxY = Math.max(maxY, sy);+ }+ }+ }+ return { minX, maxX, minY, maxY };+}++/**+ * The overview: the whole floor, railing included, from the home angle,+ * fitted to the viewport. The near corner of a floor seen at an angle looms+ * larger than the far one, so looking at the floor's middle leaves the upper+ * part of the view empty and the plan small; instead the look-at point is+ * moved until the plan sits in the middle of the view, and the camera comes+ * as close as the plan allows: it spans `OVERVIEW_SPAN` of whichever axis of+ * the viewport binds (the height in a wide window, the width in a narrow+ * panel).+ */+export function campusOverview(bounds: Bounds, aspect: number, fovDeg = CAMERA_FOV): CameraPose {+ const { back, right } = homeAxes();+ const tanV = Math.tan((fovDeg * Math.PI) / 360);+ const tanH = tanV * Math.max(0.3, aspect);+ // The horizontal direction the camera looks along: moving the look-at point this way slides the plan down the view.+ const ahead: [number, number] = [-Math.sin(HOME_YAW_RAD), -Math.cos(HOME_YAW_RAD)];+ const target: [number, number] = [(bounds.minX + bounds.maxX) / 2, (bounds.minZ + bounds.maxZ) / 2];+ let distance = frameDistance(bounds, aspect, fovDeg);+ for (let i = 0; i < 12; i += 1) {+ const box = projectedBox(bounds, target, distance, aspect, fovDeg, OVERVIEW_HEADROOM_M);+ // Centre the plan: sideways along the camera's right, up and down along the floor.+ const offX = (box.minX + box.maxX) / 2, offY = (box.minY + box.maxY) / 2;+ target[0] += right[0] * offX * distance * tanH + (ahead[0] * offY * distance * tanV) / Math.sin(HOME_PITCH_RAD);+ target[1] += right[2] * offX * distance * tanH + (ahead[1] * offY * distance * tanV) / Math.sin(HOME_PITCH_RAD);+ // Then come as close as the plan allows.+ const centred = projectedBox(bounds, target, distance, aspect, fovDeg, OVERVIEW_HEADROOM_M);+ const span = Math.max(centred.maxX - centred.minX, centred.maxY - centred.minY) / 2;+ distance = Math.max(CAMERA_LIMITS.minDistance, distance * (span / OVERVIEW_SPAN));+ }+ return {+ target: [target[0], 0, target[1]],+ position: [target[0] + back[0] * distance, back[1] * distance, target[1] + back[2] * distance],+ };+}++/**+ * Zoom limits for a floor: the wheel may always back away far enough for the+ * overview (and a little beyond), never less than the default. A small floor+ * keeps the default; a campus several times larger gets the room it needs.+ */+export function cameraLimitsFor(bounds: Bounds, aspect: number): { minPolar: number; maxPolar: number; minDistance: number; maxDistance: number } {+ return { ...CAMERA_LIMITS, maxDistance: Math.max(CAMERA_LIMITS.maxDistance, Math.ceil(frameDistance(bounds, aspect) * 1.15)) };+}++/** The distance the camera follows the character from when nothing else is known. */+export const FOLLOW_DISTANCE_M = 15;+/** A view from further away than this is an overview, not a view to walk in. */+export const WALK_VIEW_MAX_M = 36;++/**+ * The distance following glides back to after the overview: what it was+ * before the overview when that was a view to walk in, else the default.+ * Without this "follow me" re-centred on the character but stayed a campus+ * away from it.+ */+export function followDistanceAfterOverview(before: number | null): number {+ return before !== null && before <= WALK_VIEW_MAX_M ? Math.max(CAMERA_LIMITS.minDistance, before) : FOLLOW_DISTANCE_M;+}++/** A camera this low can stand inside a wall; higher it looks over every wall of the floor. */+const WALL_TOP_M = 3.8;+/** How close to a wall's footprint the camera may stand. */+const WALL_CLEAR_M = 0.35;++/**+ * A remembered view checked against the floor it is restored on (the plan+ * may have been rebuilt meanwhile): null when it looks at a point outside+ * the floor, so the caller starts from the character instead; otherwise the+ * view, with a camera that would stand inside a wall backed away from its+ * target until it is clear.+ */+export function settleView(pose: CameraPose, bounds: Bounds, walls: readonly Bounds[]): CameraPose | null {+ const [tx, , tz] = pose.target;+ if (tx < bounds.minX || tx > bounds.maxX || tz < bounds.minZ || tz > bounds.maxZ) return null;+ const inWall = (x: number, y: number, z: number) => y < WALL_TOP_M+ && walls.some((w) => x > w.minX - WALL_CLEAR_M && x < w.maxX + WALL_CLEAR_M && z > w.minZ - WALL_CLEAR_M && z < w.maxZ + WALL_CLEAR_M);+ let [x, y, z] = pose.position;+ if (!inWall(x, y, z)) return pose;+ const dx = x - pose.target[0], dy = y - pose.target[1], dz = z - pose.target[2];+ const length = Math.hypot(dx, dy, dz) || 1;+ for (let back = 0.5; back <= 12; back += 0.5) {+ const k = (length + back) / length;+ x = pose.target[0] + dx * k; y = pose.target[1] + dy * k; z = pose.target[2] + dz * k;+ if (!inWall(x, y, z)) break;+ }+ return { target: pose.target, position: [x, y, z] };+}++/** Further than this from the character, re-entering follow glides over like a fly-to instead of snapping across the floor. */+export const FOLLOW_CATCH_UP_M = 12;+/** How fast the view closes on the character while following (per second, exponential). */+export const FOLLOW_RATE = 8;++/**+ * One frame of following: the share of the remaining gap the view closes.+ * Exponential, so it is the same motion at any frame rate, and it eases out+ * instead of stopping dead when the character does.+ */+export function followBlend(dt: number): number {+ return 1 - Math.exp(-FOLLOW_RATE * Math.max(0, dt));}/** Smallest area the home view frames, so a lone agent still shows its neighbourhood. */diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeFixtures.ts b/jarvis/ui/web/frontend/src/components/society/office/officeFixtures.tsnew file mode 100644index 0000000000..ecfec33f24--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/officeFixtures.ts@@ -0,0 +1,51 @@+/**+ * Floors for the behaviour, teamwork and walking tests: a roster with teams+ * built through the public floor-plan builder, and small hand-made rooms for+ * the cases a real floor does not isolate (a door, a corridor, a dead end).+ * Test support only; nothing at runtime imports it.+ */+import { buildOfficeLayout, type OfficeAgentInput, type OfficeLayout, type OfficeTeamInput, type Rect } from "./officeLayout";+import { buildNavGrid, type NavGrid } from "./officeNav";++export function rosterOf(count: number): OfficeAgentInput[] {+ return Array.from({ length: count }, (_, i) => ({+ agentId: `a${i}`, name: `Agent ${i}`, tier: "specialist" as const, providerLabel: i % 2 ? "Codex" : "Gemini", state: "idle" as const, createdMs: i,+ }));+}++/**+ * Teams of the given sizes over the first agents of the roster, in order; whoever is left has no team.+ * `leads[i]` names team i's lead by its place among the team's members (absent or null: the team has none).+ */+export function teamsOf(roster: readonly OfficeAgentInput[], sizes: readonly number[], leads: readonly (number | null)[] = []): OfficeTeamInput[] {+ let next = 0;+ return sizes.map((size, i) => {+ const members = roster.slice(next, next + size).map((a) => a.agentId);+ next += size;+ const lead = leads[i];+ return { id: `team-${i}`, name: `Team ${i}`, members, createdMs: 100 + i, ...(lead != null ? { leadId: members[lead] } : {}) };+ });+}++export interface Campus { roster: OfficeAgentInput[]; teams: OfficeTeamInput[]; layout: OfficeLayout; grid: NavGrid }++/** The agents floor for `count` agents in teams of `sizes` (the rest sit in the pool). */+export function campusOf(count: number, sizes: readonly number[], leads: readonly (number | null)[] = []): Campus {+ const roster = rosterOf(count);+ const teams = teamsOf(roster, sizes, leads);+ const layout = buildOfficeLayout(roster, { teams });+ return { roster, teams, layout, grid: buildNavGrid(layout) };+}++/** A bare rectangular floor `w` × `d` metres from the origin with the given solid rectangles on it. */+export function roomGrid(w: number, d: number, obstacles: readonly Rect[] = []): NavGrid {+ return buildNavGrid({ floor: { minX: 0, maxX: w, minZ: 0, maxZ: d }, obstacles: [...obstacles] } as unknown as OfficeLayout);+}++/** A wall across a room at `x` (0.12 m thick) with one door: a gap `doorWidth` wide centred on `doorZ`. */+export function wallWithDoor(x: number, depth: number, doorZ: number, doorWidth: number): Rect[] {+ return [+ { minX: x - 0.06, maxX: x + 0.06, minZ: 0, maxZ: doorZ - doorWidth / 2 },+ { minX: x - 0.06, maxX: x + 0.06, minZ: doorZ + doorWidth / 2, maxZ: depth },+ ];+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeFloors.test.ts b/jarvis/ui/web/frontend/src/components/society/office/officeFloors.test.tsindex 07b16d6c02..5915fc9575 100644--- a/jarvis/ui/web/frontend/src/components/society/office/officeFloors.test.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/officeFloors.test.ts@@ -6,6 +6,7 @@ import { floorLevel, OFFICE_FLOORS, officeSession, player, switchFloor, useOfficimport { callDirection } from "./ElevatorCallButton";import { floorForKey, PANEL_FLOORS } from "./ElevatorPanel";import { buildArcadeLayout } from "../arcade/arcadeFloorLayout";+import { buildHallLayout } from "./hallFloorLayout";const AGENTS: OfficeAgentInput[] = [{ agentId: "a1", name: "One", tier: "specialist", providerLabel: "Codex", state: "working", createdMs: 1 },@@ -24,26 +25,28 @@ afterEach(resetBuilding);describe("floors", () => {it("stacks the floors bottom to top, and the elevator panel lists them top first", () => {- expect(OFFICE_FLOORS).toEqual(["agents", "coding", "arcade"]);- expect(OFFICE_FLOORS.map(floorLevel)).toEqual([0, 1, 2]);- expect(PANEL_FLOORS).toEqual(["arcade", "coding", "agents"]);+ expect(OFFICE_FLOORS).toEqual(["agents", "coding", "arcade", "hall"]);+ expect(OFFICE_FLOORS.map(floorLevel)).toEqual([0, 1, 2, 3]);+ expect(PANEL_FLOORS).toEqual(["hall", "arcade", "coding", "agents"]);expect(callDirection("agents")).toBe("up");expect(callDirection("coding")).toBe("both");- expect(callDirection("arcade")).toBe("down");+ expect(callDirection("arcade")).toBe("both");+ expect(callDirection("hall")).toBe("down");});it("picks a floor by its number key", () => {expect(floorForKey("0")).toBe("agents");expect(floorForKey("1")).toBe("coding");expect(floorForKey("2")).toBe("arcade");- expect(floorForKey("3")).toBeNull();+ expect(floorForKey("3")).toBe("hall");+ expect(floorForKey("4")).toBeNull();expect(floorForKey("e")).toBeNull();expect(floorForKey("12")).toBeNull();});it("steps out of the elevator onto walkable floor, facing away from the doors, on every floor", () => {- for (const variant of ["agents", "coding", "arcade"] as const) {- const layout = variant === "arcade" ? buildArcadeLayout() : buildOfficeLayout(AGENTS, { variant });+ for (const variant of ["agents", "coding", "arcade", "hall"] as const) {+ const layout = variant === "arcade" ? buildArcadeLayout() : variant === "hall" ? buildHallLayout() : buildOfficeLayout(AGENTS, { variant });const stop = layout.checkpoints.find((cp) => cp.id === "elevator");expect(stop, variant).toBeDefined();const pose = arrivalPose(layout, "elevator");@@ -72,6 +75,9 @@ describe("floors", () => {expect(noteArrivals(known, ["p2", "p3"])).toEqual([]);expect(noteArrivals(known, ["p1", "p2", "p3"])).toEqual(["p1"]);expect(knownOnFloor("agents")).not.toBe(knownOnFloor("coding"));+ // Nobody works in the arcade or the Level Hall: neither ever has a newcomer of the floors below.+ expect(knownOnFloor("hall")).not.toBe(knownOnFloor("agents"));+ expect(knownOnFloor("hall")).not.toBe(knownOnFloor("coding"));});it("switching floors forgets the old floor's panels and calls, and remembers where the character stood", () => {diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeFloors.ts b/jarvis/ui/web/frontend/src/components/society/office/officeFloors.tsindex 5859b7096f..ed9fdbb67b 100644--- a/jarvis/ui/web/frontend/src/components/society/office/officeFloors.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/officeFloors.ts@@ -1,8 +1,8 @@/**- * The building has three floors joined by an elevator: the Jarvis agents- * office, one ride up the coding floor with a figure per IDE coding session,- * and on top the arcade hall. Pure helpers for what differs per floor; the- * stage wires them.+ * The building has four floors joined by an elevator: the Jarvis agents'+ * campus, one ride up the coding floor with a figure per IDE coding session,+ * the arcade hall, and on top the Level Hall. Pure helpers for what differs+ * per floor; the stage wires them.*/import type { OfficeLayout } from "./officeLayout";import type { OfficeFloor } from "./officeStore";@@ -28,9 +28,10 @@ export function arrivalPose(layout: OfficeLayout, at: "elevator" | "remembered",/** Agent ids each floor has already seen; a newcomer on that floor arrives by the elevator. */const codingKnown = new Set<string>();-const arcadeKnown = new Set<string>();+/** The arcade and the Level Hall have no agents; they share one set that stays empty. */+const nobodyKnown = new Set<string>();export function knownOnFloor(floor: OfficeFloor): Set<string> {- return floor === "agents" ? knownAgents : floor === "coding" ? codingKnown : arcadeKnown;+ return floor === "agents" ? knownAgents : floor === "coding" ? codingKnown : nobodyKnown;}/**diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeHud.css b/jarvis/ui/web/frontend/src/components/society/office/officeHud.cssindex d544e31cae..87fc34c0f3 100644--- a/jarvis/ui/web/frontend/src/components/society/office/officeHud.css+++ b/jarvis/ui/web/frontend/src/components/society/office/officeHud.css@@ -1,69 +1,34 @@-/* Office HUD panels and prompts: theme tokens only, so light and dark mode both work. */+/* The panels docked beside the map (an agent's walkie-talkie, the wardrobe): theme tokens only, so light and dark mode both work. *//* Opens below the minimap card (14 + 236 px) in the top-right corner. */-.office-panel-slot { position:absolute; z-index:35; right:14px; top:258px; width:min(340px, calc(100% - 28px)); max-height:calc(100% - 310px); display:flex; }+.office-panel-slot { position:absolute; z-index:35; right:14px; top:258px; width:min(340px, calc(100% - 28px)); max-height:calc(100% - 276px); display:flex; }+/* A panel with a lot in it (the wardrobe) takes the whole edge and covers the minimap while it is open. */+.office-panel-slot[data-tall] { top:14px; width:min(360px, calc(100% - 28px)); max-height:calc(100% - 28px); }.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: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; }-/* A checkpoint panel wears its checkpoint's icon, gold like the token on the floor. */-.office-panel-head > div { flex:1; }-.office-panel-head .office-panel-badge { flex:none; display:inline-flex; align-items:center; justify-content:center; width:34px; height:34px; margin:0; border-radius:10px; background:linear-gradient(160deg, #ffd476, #f0a92b); color:#1f1300; box-shadow:0 4px 14px rgb(240 169 43 / .3); }-.office-panel-badge svg { width:18px; height:18px; }-.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 { display:flex; flex-direction:column; gap:12px; padding:14px 16px 16px; overflow:auto; font-size:13px; 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)); }-.office-action[aria-pressed="true"] { background:hsl(var(--secondary)); border-color:hsl(var(--ring)); }-.office-action:disabled { opacity:.5; cursor:not-allowed; }-.office-action-primary { background:hsl(var(--primary)); color:hsl(var(--primary-foreground)); border-color:transparent; font-weight:600; }-.office-action-primary:hover:not(:disabled) { background:hsl(var(--primary) / .88); }-.office-action:focus-visible, .office-mini:focus-visible, .office-chip:focus-visible, .office-link:focus-visible, .office-prompt:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:2px; }.office-link { border:0; background:none; padding:0; color:hsl(var(--primary)); font-size:12px; cursor:pointer; text-decoration:underline; text-underline-offset:2px; }-.office-list { list-style:none; margin:0; padding:0; display:flex; flex-direction:column; gap:3px; max-height:260px; overflow:auto; }-.office-list li { display:flex; align-items:center; gap:6px; padding:4px 6px; border-radius:7px; }-.office-list li:hover { background:hsl(var(--secondary) / .6); }-.office-list label { display:flex; align-items:center; gap:6px; width:100%; cursor:pointer; }-.office-list-name { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }-.office-mini { border:1px solid hsl(var(--border)); border-radius:6px; padding:2px 7px; background:hsl(var(--background)); color:hsl(var(--foreground)); font-size:11px; cursor:pointer; }-.office-mini:hover { background:hsl(var(--secondary)); }-.office-list li > .office-mini { flex:none; }+.office-link:focus-visible, .office-chip:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:2px; }.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-subhead { margin:0; font-size:12px; font-weight:600; color:hsl(var(--muted-foreground)); }+.office-chip { border:1px solid hsl(var(--border)); border-radius:999px; padding:3px 10px; background:hsl(var(--background)); color:hsl(var(--foreground)); font-size:12px; 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-hint { margin:0; font-size:12px; 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; 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:900px) { .office-prompt { bottom:64px; } }-/* Narrow: the buttons sit under the minimap; the panel covers the map card while open. */+.office-success { color:hsl(var(--foreground)); }+/* Narrow: the panel covers the map card while open. */@media (max-width:760px) { .office-panel-slot { top:14px; max-height:calc(100% - 80px); } }-/* No minimap on short windows: the panel goes back under the corner buttons. */+/* No minimap on short windows: the panel goes back under the toolbar. */@media (max-height:520px) { .office-panel-slot { top:60px; max-height:calc(100% - 100px); } }-@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); } }+@media (max-width:600px) { .office-panel-slot, .office-panel-slot[data-tall] { top:auto; bottom:12px; max-height:55%; } }/* The monitor dive ends in the chat view: the stage fades to the app background just before it opens. */.office-dive-fade { position:absolute; inset:0; z-index:60; pointer-events:none; background:hsl(var(--background)); opacity:0; animation:office-dive-fade 1.4s ease-in forwards; }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.tsindex 3ec5900350..498ce3dce5 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@@ -2,10 +2,9 @@ import { describe, expect, it } from "vitest";import { PRODUCT_NAME } from "@/lib/branding";import {allDesks, archPosts, buildOfficeLayout, countStates, departmentKey, FURNITURE_SIZE, footprint, groupDepartments,- MAX_DEPARTMENTS, MIN_DEPARTMENTS, COMMAND_DESK, COMMAND_REACH, LEVEL_HALL, SPAWN, type OfficeAgentInput,+ MAX_DEPARTMENTS, MAX_SEATED, MIN_DEPARTMENTS, COMMAND_DESK, COMMAND_REACH, seatedCount, SPAWN, type OfficeAgentInput,} from "./officeLayout";-import { buildNavGrid, findPath, isWalkable } from "./officeNav";-import { REWARD_IDS } from "../progression/levelCatalog";+import { buildNavGrid, isWalkable } from "./officeNav";import { cameraHome, fitDistance, focusBounds } from "./officeCamera";const agent = (id: string, provider: string, extra: Partial<OfficeAgentInput> = {}): OfficeAgentInput => ({@@ -13,11 +12,11 @@ const agent = (id: string, provider: string, extra: Partial<OfficeAgentInput> =});describe("office layout", () => {- it("groups agents by provider family and falls back to the product name", () => {+ it("groups the coding floor by workspace and falls back to the product name", () => {expect(departmentKey({ providerLabel: " " })).toBe(PRODUCT_NAME);const groups = groupDepartments([agent("a1", "codex"), agent("a2", ""), agent("a3", "codex")]);expect(groups.map((g) => g.label)).toEqual(["Codex", PRODUCT_NAME]);- expect(buildOfficeLayout([agent("a1", "codex")]).departments.map((d) => d.label)).toEqual(["Codex", "", "", ""]);+ expect(buildOfficeLayout([agent("a1", "codex")], { variant: "coding" }).departments.map((d) => d.label)).toEqual(["Codex", "", "", ""]);});it("gives every staff agent exactly one desk and the lead its own office", () => {@@ -27,19 +26,22 @@ describe("office layout", () => {expect(new Set(seated)).toEqual(new Set(["a1", "a2", "a3", "a4"]));expect(seated).toHaveLength(4);expect(layout.lead.desks[0].agentId).toBe("a4");+ expect(seatedCount(layout)).toBe(4);});- it("keeps seating stable when run state changes or the roster is reordered", () => {- const roster = [agent("a1", "Codex"), agent("a2", "Codex"), agent("a3", "Gemini")];- const before = allDesks(buildOfficeLayout(roster)).map((d) => `${d.id}=${d.agentId}`);- const after = allDesks(buildOfficeLayout([...roster].reverse().map((a) => ({ ...a, state: "working" as const }))))- .map((d) => `${d.id}=${d.agentId}`);- expect(after).toEqual(before);- });+ for (const variant of ["agents", "coding"] as const) {+ it(`keeps seating stable when run state changes or the roster is reordered (${variant})`, () => {+ const roster = [agent("a1", "Codex"), agent("a2", "Codex"), agent("a3", "Gemini")];+ const before = allDesks(buildOfficeLayout(roster, { variant })).map((d) => `${d.id}=${d.agentId}`);+ const after = allDesks(buildOfficeLayout([...roster].reverse().map((a) => ({ ...a, state: "working" as const })), { variant }))+ .map((d) => `${d.id}=${d.agentId}`);+ expect(after).toEqual(before);+ });+ }- it("folds surplus providers into one department and never overlaps departments", () => {+ it("folds surplus workspaces into one department on the coding floor and never overlaps departments", () => {const roster = Array.from({ length: 10 }, (_, i) => agent(`a${i}`, `P${i}`));- const layout = buildOfficeLayout(roster);+ const layout = buildOfficeLayout(roster, { variant: "coding" });expect(layout.departments).toHaveLength(MAX_DEPARTMENTS);expect(layout.departments.at(-1)?.label).toBe("Other");for (const a of layout.departments) for (const b of layout.departments) {@@ -56,22 +58,33 @@ describe("office layout", () => {});it("builds a furnished floor for an empty roster", () => {- const layout = buildOfficeLayout([]);- expect(layout.departments).toHaveLength(MIN_DEPARTMENTS);- expect(layout.departments.every((d) => d.label === "" && d.desks.length > 0)).toBe(true);+ const coding = buildOfficeLayout([], { variant: "coding" });+ expect(coding.departments).toHaveLength(MIN_DEPARTMENTS);+ expect(coding.departments.every((d) => d.label === "" && d.desks.length > 0)).toBe(true);+ // The agents floor: the pool studio with a few free desks, and nobody at the lead's desk yet.+ const agents = buildOfficeLayout([]);+ expect(agents.departments.map((d) => d.id)).toEqual(["studio-pool"]);+ expect(agents.departments[0].desks.length).toBeGreaterThan(0);+ expect(agents.lead.desks).toHaveLength(1);+ expect(seatedCount(agents)).toBe(0);});- 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("says how many desks the coding floor can hold", () => {+ const roster = Array.from({ length: MAX_SEATED + 5 }, (_, i) => agent(`a${i}`, `P${i % 6}`));+ expect(seatedCount(buildOfficeLayout(roster, { variant: "coding" }))).toBe(MAX_SEATED);});for (const variant of ["agents", "coding"] as const) {+ it(`makes the posts of an open room's name arch solid (${variant})`, () => {+ const layout = buildOfficeLayout([agent("a1", "Codex")], { variant });+ 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 (${variant})`, () => {const layout = buildOfficeLayout(Array.from({ length: 12 }, (_, i) => agent(`a${i}`, i % 2 ? "Codex" : "Gemini")), { variant });const solid = layout.furniture.filter((f) => FURNITURE_SIZE[f.kind].solid).map(footprint);@@ -92,10 +105,14 @@ describe("office layout", () => {expect(stop.x).toBeGreaterThan(elevator.x);expect(Math.hypot(stop.x - elevator.x, stop.z - elevator.z)).toBeLessThan(1.5);expect(new Set(layout.checkpoints.map((c) => c.id)).size).toBe(layout.checkpoints.length);+ // The person starts in front of the doors.+ expect(Math.hypot(layout.spawn.x - stop.x, layout.spawn.z - stop.z)).toBeLessThan(1);});it(`keeps room, furniture and spot ids unique and inside the floor (${variant})`, () => {- const layout = buildOfficeLayout(Array.from({ length: 20 }, (_, i) => agent(`a${i}`, `P${i % 3}`)), { variant });+ const layout = buildOfficeLayout(Array.from({ length: 20 }, (_, i) => agent(`a${i}`, `P${i % 3}`)), {+ variant, teams: [{ id: "t1", name: "Core", members: ["a1", "a2", "a3"], createdMs: 1 }, { id: "t2", name: "Web", members: ["a4", "a5"], createdMs: 2 }],+ });for (const list of [layout.rooms, layout.furniture, layout.spots]) {expect(new Set(list.map((x) => x.id)).size).toBe(list.length);}@@ -110,55 +127,39 @@ describe("office layout", () => {});}- it("keeps the agents office as it was when no variant is named", () => {+ it("builds the agents floor when no variant is named: its rooms and stations, no Level Hall", () => {const roster = [agent("a1", "Codex"), agent("a2", "", { tier: "lead" })];const plain = buildOfficeLayout(roster);expect(plain).toEqual(buildOfficeLayout(roster, { variant: "agents" }));expect(plain.variant).toBe("agents");- expect(plain.rooms.map((r) => r.kind)).toEqual(["lead", "team", "wardrobe", "reception", "break", "levels"]);- expect(plain.checkpoints.map((c) => c.id)).toEqual(["spawn", "create", "manage", "team", "wardrobe", "lead", "studio", "levels", "break", "elevator"]);+ expect(plain.rooms.map((r) => r.kind)).toEqual(["lead", "team", "wardrobe", "reception", "break"]);+ // The spawn point creates agents, the reception desk is the one directory and help station; the hall has its own floor.+ expect(plain.checkpoints.map((c) => c.id)).toEqual(["spawn", "manage", "team", "wardrobe", "lead", "break", "elevator"]);+ for (const kind of ["levelWall", "studioStage", "rewardPedestal", "levelGuide", "agentTotem"] as const) {+ expect(plain.furniture.some((f) => f.kind === kind), kind).toBe(false);+ }});- it.each([0, 12, 40])("builds the Level Hall as the agents floor's east wing (%i agents)", (count) => {- const roster = Array.from({ length: count }, (_, i) => agent(`a${i}`, `P${i % 6}`));- const layout = buildOfficeLayout(roster);- const hall = layout.rooms.find((r) => r.kind === "levels")!;- const office = Math.max(...layout.rooms.filter((r) => r.kind !== "levels").map((r) => r.maxX));- // One aisle east of the office, across the floor's whole depth, walled with its doors facing the office.- expect(hall.walled).toBe(true);- expect(hall.minX - office).toBeCloseTo(LEVEL_HALL.aisle, 9);- expect(hall.maxX - hall.minX).toBeCloseTo(LEVEL_HALL.width, 9);- expect(hall.minZ).toBe(Math.min(...layout.rooms.map((r) => r.minZ)));- expect(hall.maxZ).toBe(Math.max(...layout.rooms.map((r) => r.maxZ)));- expect(hall.doors.every((d) => d.side === "west")).toBe(true);- const spawn = layout.checkpoints.find((c) => c.id === "spawn")!;- expect(hall.doors[0].at).toBe(spawn.z);- // A pedestal per reward on either side of the road, inside the hall, rising towards the stage.- const pedestals = layout.furniture.filter((f) => f.kind === "rewardPedestal");- expect(pedestals.map((p) => p.id)).toEqual(REWARD_IDS.map((_, n) => `level-pedestal-${n}`));- const cx = (hall.minX + hall.maxX) / 2;- pedestals.forEach((p, n) => {- const box = footprint(p);- expect(box.minX > hall.minX && box.maxX < hall.maxX && box.minZ > hall.minZ && box.maxZ < hall.maxZ, p.id).toBe(true);- expect(Math.sign(p.x - cx)).toBe(n % 2 === 0 ? -1 : 1);- if (n >= 2) expect(p.z).toBeLessThan(pedestals[n - 2].z);- });- const stage = layout.furniture.find((f) => f.kind === "studioStage")!;- const studio = layout.checkpoints.find((c) => c.id === "studio")!;- expect([studio.x, studio.z]).toEqual([stage.x, stage.z]);- expect(stage.z).toBeLessThan(Math.min(...pedestals.map((p) => p.z)));- // Both checkpoints are reachable on foot from the spawn point, through each of the hall's doors.+ it("stands every agents-floor station in front of the thing the person uses there", () => {+ const layout = buildOfficeLayout([agent("a1", "Codex"), agent("a2", "", { tier: "lead" })]);const grid = buildNavGrid(layout);- const levels = layout.checkpoints.find((c) => c.id === "levels")!;- for (const target of [studio.approach!, { x: levels.x, z: levels.z }]) {- expect(isWalkable(grid, target)).toBe(true);- expect(findPath(grid, layout.arrival, target)).not.toBeNull();- }- for (const door of hall.doors) {- // The aisle in front of every door stays open: no olive tree closes it.- expect(isWalkable(grid, { x: office + LEVEL_HALL.aisle / 2, z: door.at }), `door at ${door.at}`).toBe(true);- expect(isWalkable(grid, { x: hall.minX + 0.6, z: door.at }), `inside door at ${door.at}`).toBe(true);- }+ const stop = (id: string) => layout.checkpoints.find((c) => c.id === id)!;+ const prop = (kind: string) => layout.furniture.find((f) => f.kind === kind)!;+ const near = (id: string, kind: string, reach: number) => {+ const cp = stop(id), box = footprint(prop(kind));+ const dx = Math.max(box.minX - cp.x, 0, cp.x - box.maxX), dz = Math.max(box.minZ - cp.z, 0, cp.z - box.maxZ);+ expect(Math.hypot(dx, dz), `${id} to ${kind}`).toBeLessThanOrEqual(reach);+ };+ near("manage", "receptionDesk", 1.5);+ near("team", "teamBoard", 1.5);+ near("wardrobe", "dressingMirror", 2.0);+ near("break", "coffeeBar", 1.5);+ near("spawn", "spawnTerminal", 0.1);+ // The reception desk's counter faces south: the person stands on that side.+ expect(stop("manage").z).toBeGreaterThan(prop("receptionDesk").z);+ const desk = layout.lead.desks[0];+ expect(Math.hypot(stop("lead").x - desk.x, stop("lead").z - desk.z)).toBeLessThan(2.6);+ for (const cp of layout.checkpoints) expect(isWalkable(grid, cp.approach ?? cp), cp.id).toBe(true);});it("builds the coding floor: workspaces as departments, Mission Control and server room, no lead desks", () => {@@ -172,16 +173,16 @@ describe("office layout", () => {expect(layout.furniture.some((f) => f.room === "lead" || f.room === "wardrobe")).toBe(false);expect(layout.spots.some((s) => s.room === "command")).toBe(true);expect(layout.spots.some((s) => s.room === "server")).toBe(true);- // Both floors share the office's footprint (the agents floor adds the Level Hall as an east wing),- // and the elevator stands at the same spot on each.- const below = buildOfficeLayout(roster);- expect(layout.rooms.some((r) => r.kind === "levels")).toBe(false);- expect({ ...layout.bounds, maxX: 0 }).toEqual({ ...below.bounds, maxX: 0 });- expect(below.bounds.maxX - layout.bounds.maxX).toBeCloseTo(LEVEL_HALL.aisle + LEVEL_HALL.width, 9);- const lift = (l: typeof layout) => l.checkpoints.find((c) => c.id === "elevator")!;- expect(lift(layout).z).toBe(lift(below).z);- expect(lift(layout).x - layout.bounds.minX).toBeCloseTo(lift(below).x - below.bounds.minX);- expect(layout.spawn.x - layout.bounds.minX).toBeCloseTo(below.spawn.x - below.bounds.minX);+ // It keeps its own compact footprint, with no team studios, zones or planting of the campus below.+ expect(layout.studios).toBeUndefined();+ expect(layout.zones).toBeUndefined();+ expect(layout.ambience).toBeUndefined();+ expect(layout.bounds.maxX - layout.bounds.minX).toBeCloseTo(24.4, 6);+ // The elevator stands on the lobby's west edge, by the south wall, like on every floor.+ const lift = layout.checkpoints.find((c) => c.id === "elevator")!;+ const lobby = layout.rooms.find((r) => r.kind === "reception")!;+ expect(lift.x - lobby.minX).toBeCloseTo(1.2, 9);+ expect(lobby.maxZ - lift.z).toBeCloseTo(2.6, 9);});it("builds Mission Control as its own office: slat wall, desk, lounge, and a ring round the desk", () => {@@ -226,57 +227,56 @@ describe("office layout", () => {expect(isWalkable(grid, stop.approach!)).toBe(true);});- for (const [variant, id] of [["agents", "spawn"], ["coding", "launch"]] as const) {- for (const count of [0, 12, 40]) {- it(`puts the spawn point on the aisle crossing in the middle of the floor (${variant}, ${count} agents)`, () => {- const roster = Array.from({ length: count }, (_, i) => agent(`a${i}`, `P${i % 6}`));- const layout = buildOfficeLayout(roster, { variant });- const stop = layout.checkpoints.find((c) => c.id === id)!;- const terminal = layout.furniture.find((f) => f.kind === "spawnTerminal")!;- const pad = layout.furniture.find((f) => f.kind === "spawnPad")!;- expect(stop.room).toBe("floor");- expect([terminal.x, terminal.z]).toEqual([stop.x, stop.z]);- expect([pad.x, pad.z]).toEqual([stop.x, stop.z]);- // On the centre line between the two department columns, in a cross aisle nearest the floor's middle.- const columns = { minX: Math.min(...layout.departments.map((d) => d.minX)), maxX: Math.max(...layout.departments.map((d) => d.maxX)) };- expect(stop.x).toBeCloseTo((columns.minX + columns.maxX) / 2, 9);- const rowStarts = [...new Set(layout.departments.map((d) => d.minZ))].sort((p, q) => p - q);- const crossings = rowStarts.slice(1).map((start, i) => {- const above = Math.max(...layout.departments.filter((d) => d.minZ === rowStarts[i]).map((d) => d.maxZ));- return (above + start) / 2;- });- expect(crossings.length).toBeGreaterThan(0);- const middle = (layout.bounds.minZ + layout.bounds.maxZ) / 2;- const nearest = Math.min(...crossings.map((c) => Math.abs(c - middle)));- expect(Math.abs(stop.z - middle)).toBeCloseTo(nearest, 6);- // The whole pad stays clear of every department, and the ring sits on the pad.- const padBox = footprint(pad);- for (const dept of layout.departments) {- const overlap = padBox.minX < dept.maxX && dept.minX < padBox.maxX && padBox.minZ < dept.maxZ && dept.minZ < padBox.maxZ;- expect(overlap, dept.id).toBe(false);- }- expect(stop.radius).toBeLessThanOrEqual(FURNITURE_SIZE.spawnPad.w / 2);- // The token floats above the terminal; newcomers appear where "walk there" ends, south of the screen.- expect(stop.tokenY).toBeGreaterThan(FURNITURE_SIZE.spawnTerminal.h);- expect(layout.arrival).toEqual(stop.approach);- expect(layout.arrival.z - stop.z).toBeCloseTo(SPAWN.approach, 9);- expect(isWalkable(buildNavGrid(layout), layout.arrival)).toBe(true);+ for (const count of [0, 12, 40]) {+ it(`puts the coding floor's spawn point on the aisle crossing in the middle of the floor (${count} agents)`, () => {+ const roster = Array.from({ length: count }, (_, i) => agent(`a${i}`, `P${i % 6}`));+ const layout = buildOfficeLayout(roster, { variant: "coding" });+ const stop = layout.checkpoints.find((c) => c.id === "launch")!;+ const terminal = layout.furniture.find((f) => f.kind === "spawnTerminal")!;+ const pad = layout.furniture.find((f) => f.kind === "spawnPad")!;+ expect(stop.room).toBe("floor");+ expect([terminal.x, terminal.z]).toEqual([stop.x, stop.z]);+ expect([pad.x, pad.z]).toEqual([stop.x, stop.z]);+ // On the centre line between the two department columns, in a cross aisle nearest the floor's middle.+ const columns = { minX: Math.min(...layout.departments.map((d) => d.minX)), maxX: Math.max(...layout.departments.map((d) => d.maxX)) };+ expect(stop.x).toBeCloseTo((columns.minX + columns.maxX) / 2, 9);+ const rowStarts = [...new Set(layout.departments.map((d) => d.minZ))].sort((p, q) => p - q);+ const crossings = rowStarts.slice(1).map((start, i) => {+ const above = Math.max(...layout.departments.filter((d) => d.minZ === rowStarts[i]).map((d) => d.maxZ));+ return (above + start) / 2;});- }+ expect(crossings.length).toBeGreaterThan(0);+ const middle = (layout.bounds.minZ + layout.bounds.maxZ) / 2;+ const nearest = Math.min(...crossings.map((c) => Math.abs(c - middle)));+ expect(Math.abs(stop.z - middle)).toBeCloseTo(nearest, 6);+ // The whole pad stays clear of every department, and the ring sits on the pad.+ const padBox = footprint(pad);+ for (const dept of layout.departments) {+ const overlap = padBox.minX < dept.maxX && dept.minX < padBox.maxX && padBox.minZ < dept.maxZ && dept.minZ < padBox.maxZ;+ expect(overlap, dept.id).toBe(false);+ }+ expect(stop.radius).toBeLessThanOrEqual(FURNITURE_SIZE.spawnPad.w / 2);+ // Newcomers appear where "walk there" ends, south of the screen.+ expect(layout.arrival).toEqual(stop.approach);+ expect(layout.arrival.z - stop.z).toBeCloseTo(SPAWN.approach, 9);+ expect(isWalkable(buildNavGrid(layout), layout.arrival)).toBe(true);+ });}- it("keeps only one spawn point per floor, and the agents floor's Agent board in the lobby", () => {+ it("keeps only one spawn point per floor, and the agents floor's directory at the reception desk", () => {const agents = buildOfficeLayout([agent("a1", "Codex")]);const coding = buildOfficeLayout([agent("p1", "Personal Jarvis")], { variant: "coding" });for (const layout of [agents, coding]) {expect(layout.furniture.filter((f) => f.kind === "spawnTerminal")).toHaveLength(1);expect(layout.furniture.filter((f) => f.kind === "spawnPad")).toHaveLength(1);}- const board = agents.furniture.find((f) => f.kind === "agentTotem")!;- expect(board.room).toBe("reception");+ const desk = agents.furniture.find((f) => f.kind === "receptionDesk")!;+ expect(desk.room).toBe("reception");const manage = agents.checkpoints.find((c) => c.id === "manage")!;- expect([manage.x, manage.z - 1.4]).toEqual([board.x, board.z]);- expect(coding.furniture.some((f) => f.kind === "agentTotem")).toBe(false);+ expect(manage.x).toBe(desk.x);+ expect(manage.z - desk.z).toBeCloseTo(1.7, 9);+ expect(agents.checkpoints.some((c) => c.id === "create")).toBe(false);+ expect(coding.checkpoints.some((c) => c.id === "manage")).toBe(false);});it("counts states", () => {diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeLayout.ts b/jarvis/ui/web/frontend/src/components/society/office/officeLayout.tsindex b0c54c1773..7e680fcdb6 100644--- a/jarvis/ui/web/frontend/src/components/society/office/officeLayout.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/officeLayout.ts@@ -1,5 +1,5 @@/**- * The office floor as data: rooms, departments, desks, furniture, hangout+ * The office floors as data: rooms, departments, desks, furniture, hangout* spots, checkpoints and the obstacles that navigation walks around.** Pure and deterministic — the same roster always produces the same floor and@@ -7,36 +7,31 @@* +x east, +z south, origin at the floor centre. The camera looks from the* south-east, so tall rooms stand in the north and the lobby lies in front.*- * ┌──────────── north strip: Lead office · Team room · Wardrobe ───────────┐ ┌───────┐- * │ departments (open office, 2 columns) · spawn point in the middle │ │ Level │- * └──── south strip: Reception + lobby (Agent board) · Break room ─────────┘ │ Hall │- * └───────┘+ * This module holds the shared vocabulary (types, footprints, desk and wall+ * helpers) and the coding floor's plan. `buildOfficeLayout` hands the agents+ * floor to `campusLayout.ts`: a team campus of studios round an atrium. The+ * Level Hall has a floor of its own (`hallFloorLayout.ts`), the arcade too+ * (`arcade/arcadeFloorLayout.ts`).*- * The agents floor adds the Level Hall as an east wing across the whole depth,- * one aisle beyond the office: the Upgrade Studio's stage under the Level Wall- * in the north, the Level Road lined with a pedestal per reward down the- * middle, and the level guide at its start in the south. Its doors open onto- * the north aisle, the spawn point's cross aisle and the south aisle.+ * ┌──── north strip: Mission Control · Team room · Server room ────┐+ * │ departments (open office, 2 columns) · spawn point between │+ * └──────── south strip: Reception + lobby · Break room ───────────┘*- * The coding floor (variant "coding", one elevator ride up) keeps the same- * frame: its departments are the Agentic IDE workspaces, and the north strip- * holds Mission Control · the team room · a server room instead of the lead- * office and the wardrobe. It has no lead desks. Mission Control is a modern- * office: a walnut slat wall with a live video wall, a desk with three live- * monitors and a lounge corner; working it starts new coding agents and- * briefs several at once. Only it, the spawn point, the elevator and the- * break room are checkpoints there.+ * The coding floor's departments are the Agentic IDE workspaces. It has no+ * lead desks. Mission Control is a modern office: a walnut slat wall with a+ * live video wall, a desk with three live monitors and a lounge corner;+ * working it starts new coding agents and briefs several at once. Only it,+ * the spawn point, the elevator and the break room are checkpoints there.*- * Both floors have a spawn point in their middle: a round pad with a- * terminal on the crossing of the centre aisle and the cross aisle nearest- * the floor's centre. It spawns new Jarvis agents downstairs and new coding+ * Both working floors have a spawn point: a round pad with a terminal. It+ * spawns new Jarvis agents downstairs (in the campus atrium) and new coding* agents upstairs, and everyone new to the floor appears on its pad.*/import { translate } from "@/i18n";import { PRODUCT_NAME } from "@/lib/branding";import type { AgentRunState, AgentTier } from "../data";-import { REWARD_IDS } from "../progression/levelCatalog";-import { agentsAmbience } from "./agentsAmbience";+import type { AgentsAmbienceItem } from "./agentsAmbience";+import { buildCampusLayout } from "./campusLayout";import { codingAmbience } from "./codingAmbience";export interface OfficeAgentInput {@@ -67,11 +62,46 @@ export interface DeskSlot {export interface Department extends Rect {id: string;- /** Provider family shown on the sign; "" for a spare open-space department. */+ /** The name on the sign: the team (agents floor, "" for the pool) or the workspace (coding floor, "" for a spare open-space department). */label: string;desks: DeskSlot[];/** Carpet tint index into the palette's department colours. */tint: number;+ /** Agents floor: the team whose studio this is; null = the pool of agents without a team. Absent on other floors. */+ teamId?: string | null;+}++/** A team as the floor plan needs it: a society chat group's id, name, members and age. */+export interface OfficeTeamInput {+ id: string;+ name: string;+ members: readonly string[];+ createdMs: number;+ /** The agent that leads the team, as the roster names it; never guessed. Absent or null = no lead. */+ leadId?: string | null;+}++/**+ * A team's neighbourhood on the agents floor: its desks (the department `deptId`), the wall board the team+ * gathers at and the standing places round it. The pool studio (`teamId` null) seats everyone without a team.+ */+export interface Studio {+ deptId: string;+ teamId: string | null;+ name: string;+ /** Member agent ids seated in this studio, in seating order: the lead first, at the head desk, then by arrival. */+ members: string[];+ /**+ * The team's lead, seated at this studio's head desk (the first desk of the bench nearest the name wall). Null+ * when the team has none, and when the agent named as its lead cannot sit here: not a member, not on the roster,+ * in the lead office, or already at the head of an older team it leads too.+ */+ leadId: string | null;+ /** The studio board (a `studioBoard` furniture piece): its id, where its face is and the yaw it faces. Null for a studio without one. */+ board: (Point & { id: string; facing: number }) | null;+ /** Ids of the `huddle` spots in front of the board. */+ huddleSpotIds: string[];+ centre: Point;}/**@@ -81,11 +111,11 @@ export interface Department extends Rect {*/export type RoomKind = "lead" | "team" | "wardrobe" | "reception" | "break" | "command" | "server"| "arcade" | "classics" | "puzzle" | "action" | "foyer" | "prizes" | "snack"- // The agents floor's east wing: the Level Hall.+ // The Level Hall, on its own floor.| "levels";-/** Which floor a layout draws: the society agents' office, the coding agents' floor above it, or the arcade floor on top. */-export type OfficeVariant = "agents" | "coding" | "arcade";+/** Which floor a layout draws: the society agents' campus, the coding agents' floor above it, the arcade floor, or the Level Hall on top. */+export type OfficeVariant = "agents" | "coding" | "arcade" | "hall";export interface Door { side: "north" | "south" | "east" | "west"; /** Centre of the gap along the wall. */ at: number; width: number }@@ -95,16 +125,20 @@ export interface Room extends Rect {/** Walled rooms get glass walls on every side except their doors; open rooms have none. */walled: boolean;doors: Door[];+ /** Where an open room's name arch stands (the middle between its posts); absent = the middle of its north edge. */+ arch?: Point;}export interface WallSegment { x1: number; z1: number; x2: number; z2: number; room: RoomKind }/**- * "elevator" rides between the floors and stands in front of the lobby elevator on both of them.+ * "elevator" rides between the floors and stands in front of the elevator on every one of them.* "mission" is Mission Control on the coding floor.* "spawn" (agents floor) and "launch" (coding floor) are the spawn point in the floor's middle:* a new Jarvis agent downstairs, a new coding agent upstairs.- * "studio" (the Upgrade Studio's stage) and "levels" (the level guide) are the Level Hall's.+ * "manage" is the agents floor's reception desk: the one directory and help station.+ * "studio" (the dais) and "levels" (the service guide) are the Level Hall floor's.+ * "create" is no longer placed on any floor; the kind stays for the maps' label tables.*/export type CheckpointKind = "spawn" | "launch" | "create" | "manage" | "team" | "wardrobe" | "lead" | "break" | "elevator" | "mission"| "studio" | "levels";@@ -114,8 +148,6 @@ export interface Checkpoint extends Point {id: CheckpointKind; room: RoomKind | "floor";/** Walk-in radius in metres. */radius: number;- /** Height of the floating token; absent = the standard height. Raised over tall props such as Mission Control's screen. */- tokenY?: number;/*** Where "walk there" goes when the checkpoint's centre is inside something* solid (Mission Control's ring is centred on its screen); absent = the centre.@@ -141,9 +173,13 @@ export type FurnitureKind =| "serverRack" | "coldAisle" | "nocConsole" | "statusWall" | "ups" | "fireSuppression"// Team room: the slat wall behind the board, a credenza, fiddle-leaf figs and a wool rug.| "teamWall" | "credenza" | "designerPlant" | "teamRug"+ // Agents floor: the board of one team studio (id `studio-board:<deptId>`), and the stand on the free plot where a+ // new team is started (id `team-stand`, at most one per plan).+ | "studioBoard" | "teamStand"// Wardrobe (agents floor): the oak wardrobe wall, a bulb-lit mirror, a tailor's dummy, a bench, a coat stand, a round rug.| "wardrobeWall" | "dressingMirror" | "tailorDummy" | "dressingBench" | "coatStand" | "roundRug"- // Lobby (agents floor): the brand wall, the Agent board totem, the waiting lounge, olive trees, the award vitrine, the mat.+ // Lobby (agents floor): the brand wall, the waiting lounge, olive trees, the award vitrine, the mat. The agent+ // totem is a prop no floor places any more: the reception desk is the directory.| "brandWall" | "agentTotem" | "lobbySofa" | "lobbyArmchair" | "lobbyTable" | "sideTable" | "lobbyLamp" | "oliveTree"| "awardCase" | "entranceMat" | "lobbyRug"// The spawn point in the middle of both floors: the flat pad and the terminal standing on it.@@ -164,6 +200,9 @@ export const FURNITURE_SIZE: Record<FurnitureKind, { w: number; d: number; h: nu// The top is at 0.76 m; a carafe stands on it.meetingTable: { w: 3.6, d: 1.6, h: 1.0, solid: true },teamBoard: { w: 2.6, d: 0.2, h: 1.9, solid: true },+ studioBoard: { w: 2.4, d: 0.16, h: 1.9, solid: true },+ // A lectern: a slanted sign on a post, its face towards the prop's front.+ teamStand: { w: 0.8, d: 0.5, h: 1.3, solid: true },// The counter is 1.1 m; its slatted back wall with the help display rises to 2.2 m.receptionDesk: { w: 2.8, d: 0.9, h: 2.2, solid: true },lockers: { w: 2.4, d: 0.5, h: 1.9, solid: true },@@ -225,7 +264,7 @@ export const FURNITURE_SIZE: Record<FurnitureKind, { w: number; d: number; h: nudressingBench: { w: 1.3, d: 0.5, h: 0.5, solid: true },coatStand: { w: 0.5, d: 0.5, h: 1.85, solid: true },roundRug: { w: 1, d: 1, h: 0.02, solid: false },- // Lobby: the ghost and the wordmark on the brand wall; the totem is the Agent board ("manage").+ // Lobby: the ghost and the wordmark on the brand wall; the totem is a touch-screen stele (unplaced).brandWall: { w: 3.2, d: 0.36, h: 2.9, solid: true },agentTotem: { w: 0.9, d: 0.5, h: 2.1, solid: true },lobbySofa: { w: 2.3, d: 0.95, h: 0.8, solid: true },@@ -260,13 +299,28 @@ export const FURNITURE_SIZE: Record<FurnitureKind, { w: number; d: number; h: nulevelGuide: { w: 3.4, d: 0.36, h: 2.45, solid: true },};+/**+ * The studio board's face, in the board's own frame (origin on the floor under its centre, front towards +z):+ * its size, the height of its centre and how far it stands in front of the board's centre plane. `Studio.board`+ * is this face's point on the plan; live content is drawn a few millimetres in front of it.+ */+export const STUDIO_BOARD_FACE = { w: 2.16, h: 1.16, y: 1.22, z: 0.059 } as const;++/**+ * Where a studio board's face is in the world: its centre, the yaw it looks along (0 = south) and its size in+ * metres. Takes a `Studio.board` (the face's point on the plan and its yaw).+ */+export function studioBoardFace(board: Point & { facing: number }): { position: [number, number, number]; rotationY: number; size: [number, number] } {+ return { position: [board.x, STUDIO_BOARD_FACE.y, board.z], rotationY: board.facing, size: [STUDIO_BOARD_FACE.w, STUDIO_BOARD_FACE.h] };+}+/*** The spawn point's numbers, shared by the layout, the renderer and the tests:* the walk-in radius round the terminal, how far south of it "walk there" and- * a newcomer's arrival stand, and the height of its floating token (above- * the terminal's crest).+ * a newcomer's arrival stand, and the height of the beacon turning above the+ * terminal's crest.*/-export const SPAWN = { reach: 1.15, approach: 0.95, tokenY: 2.85 } as const;+export const SPAWN = { reach: 1.15, approach: 0.95, beaconY: 2.85 } as const;export interface Furniture extends Point {id: string;@@ -278,15 +332,32 @@ export interface Furniture extends Point {size?: { w: number; d: number };}-export type SpotKind = "couch" | "coffee" | "cooler" | "window" | "shelf" | "arcade" | "meeting" | "beanbag" | "board";+export type SpotKind = "couch" | "coffee" | "cooler" | "window" | "shelf" | "arcade" | "meeting" | "beanbag" | "board"+ // A standing place in front of a studio board (id `huddle:<deptId>:<n>`).+ | "huddle";export type SpotPose = "sit" | "stand" | "sleep";/** Where an idle agent (or the person) can hang out. `facing` is the figure's rotation about +y. */export interface Spot extends Point { id: string; kind: SpotKind; pose: SpotPose; facing: number; room: RoomKind | "floor" }+/**+ * What a part of the campus between the studios is: a street (the boulevard, the main boulevard's plaza with the+ * atrium at its heart), a free plot, or one of the commons — a garden court, the focus booths, the library, the café.+ */+export type CampusZoneKind = "boulevard" | "plaza" | "atrium" | "plot" | "garden" | "booths" | "library" | "cafe";++/** A named area of the agents floor outside rooms and studios; flat, never an obstacle by itself. */+export interface CampusZone extends Rect { id: string; kind: CampusZoneKind }+export interface OfficeLayout {variant: OfficeVariant;departments: Department[];+ /** Team studios of the agents floor, one per department there; absent or empty on the other floors. */+ studios?: Studio[];+ /** Agents floor: the boulevard, the plaza and its atrium, the free plot and the commons. Absent on the other floors. */+ zones?: CampusZone[];+ /** Agents floor: every studio fitting, commons piece, tree, bench and planter; each one is also an obstacle. Absent on the other floors. */+ ambience?: AgentsAmbienceItem[];/** Lead desks live in the lead office; the coding floor has none (its rect is Mission Control). */lead: Rect & { desks: DeskSlot[] };/** Mission Control's desk on the coding floor, as a seat the person can take; absent downstairs. */@@ -328,14 +399,6 @@ const DEPT_MARGIN_X = 1.1;const DEPT_HEADER_Z = 1.8;const DEPT_FOOTER_Z = 0.8;const AISLE = 3.2;-/**- * The Level Hall (agents floor only): the aisle between the office and the- * hall, the hall's width, where the stage stands, and how far the Level Road- * runs from each end of the hall.- */-export const LEVEL_HALL = { aisle: AISLE, width: 9.2, stageZ: 4.5, stageR: 1.6, roadNorth: 8.2, roadSouth: 6.4, guideZ: 3.3 } as const;-/** The pedestals stand this far either side of the hall's centre line, the Level Road between them. */-export const PEDESTAL_OFFSET_X = 1.8;/*** Mission Control's desk, in its own space (origin = desk centre, +z = the* side where the chair stands): the desk top and the chair the person works@@ -348,34 +411,38 @@ export const COMMAND_DESK = { w: 2.6, d: 0.86, chairZ: 0.62 } as const;export const COMMAND_REACH = 1.9;/** The desk piece's origin sits this far from the desk's centre, towards the chair: its box covers desk and chair. */export const COMMAND_DESK_OFFSET = 0.5;-const EDGE = 1.6;+/** The window strip between the plan and the slab edge, on every floor. */+export const FLOOR_EDGE = 1.6;+const EDGE = FLOOR_EDGE;/*** How far a figure's centre stays from the slab edge. The railing stands 0.2 m* in and the toy head is ~0.31 m wide each side (plus hair), so anything less* lets the head poke through the glass and the handrail cap.*/-const RAIL_CLEARANCE = 0.65;+export const RAIL_CLEARANCE = 0.65;const NORTH_DEPTH = 7;const SOUTH_DEPTH = 8;const COLUMNS = 2;const WALL_THICKNESS = 0.12;-/** More departments than this fold into the last one — the floor stays one screen. */+/** Coding floor: more departments than this fold into the last one — the floor stays one screen. */export const MAX_DEPARTMENTS = 6;-/** The floor always shows at least this many departments; spare ones are open space with free desks. */+/** Coding floor: it always shows at least this many departments; spare ones are open space with free desks. */export const MIN_DEPARTMENTS = 4;+/** The most bench desks the coding floor can hold. The agents floor's capacity depends on its teams: see `seatedCount`. */export const MAX_SEATED = MAX_DEPARTMENTS * MAX_BENCHES * SEATS_PER_BENCH;-/** The department an agent works in: its provider family, or the product's own brain. */+/** Coding floor: the department an agent works in — its workspace, or the product's own brain. */export function departmentKey(agent: Pick<OfficeAgentInput, "providerLabel">): string {const label = agent.providerLabel.trim();return label.length > 0 ? label.charAt(0).toUpperCase() + label.slice(1) : PRODUCT_NAME;}-function byArrival(a: OfficeAgentInput, b: OfficeAgentInput): number {+/** Seating order: who arrived first sits first, so a refetch never re-seats anyone. */+export function byArrival(a: OfficeAgentInput, b: OfficeAgentInput): number {return a.createdMs - b.createdMs || a.agentId.localeCompare(b.agentId);}-/** Group staff (non-lead) agents into at most MAX_DEPARTMENTS stable departments. */+/** Coding floor: group staff (non-lead) agents into at most MAX_DEPARTMENTS stable departments. */export function groupDepartments(agents: readonly OfficeAgentInput[]): { label: string; members: OfficeAgentInput[] }[] {const groups = new Map<string, OfficeAgentInput[]>();for (const agent of agents) {@@ -537,10 +604,22 @@ export function wallsOf(room: Room): WallSegment[] {/** 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;+/** The desk every studio's lead sits at (its studio's head desk), with the studio's department. Empty off the agents floor. */+export function leadDesks(layout: Pick<OfficeLayout, "studios" | "departments">): { desk: DeskSlot; dept: Department }[] {+ const out: { desk: DeskSlot; dept: Department }[] = [];+ for (const studio of layout.studios ?? []) {+ if (!studio.leadId) continue;+ const dept = layout.departments.find((d) => d.id === studio.deptId);+ const desk = dept?.desks.find((d) => d.agentId === studio.leadId);+ if (dept && desk) out.push({ desk, dept });+ }+ return out;+}+/** 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;+export function archPosts(room: Rect & { arch?: Point }): Point[] {+ const cx = room.arch?.x ?? (room.minX + room.maxX) / 2;+ const z = room.arch?.z ?? room.minZ + ARCH.inset;return [{ x: cx - ARCH.halfSpan, z }, { x: cx + ARCH.halfSpan, z }];}@@ -550,19 +629,26 @@ export function wallRect(w: WallSegment): Rect {}export interface OfficeLayoutOptions {- /** "agents" (default) is the society office; "coding" the IDE sessions' floor, departments per workspace. */+ /** "agents" (default) is the society campus; "coding" the IDE sessions' floor, departments per workspace. */variant?: OfficeVariant;+ /** Agents floor: the teams (society chat groups). Every team gets a studio; agents without one share the pool. */+ teams?: readonly OfficeTeamInput[];}-/** Build the floor for a roster. Seating and the whole floor plan are stable for an unchanged roster. */+/**+ * Build a working floor for a roster: the agents floor's team campus (the default), or the coding floor.+ * Seating and the whole floor plan are stable for an unchanged roster and unchanged teams.+ */export function buildOfficeLayout(agents: readonly OfficeAgentInput[], options: OfficeLayoutOptions = {}): OfficeLayout {- const variant = options.variant ?? "agents";- const coding = variant === "coding";+ return (options.variant ?? "agents") === "coding" ? buildCodingLayout(agents) : buildCampusLayout(agents, options.teams ?? []);+}++/** The coding floor: one department per IDE workspace between Mission Control, the team room and the server room. */+function buildCodingLayout(agents: readonly OfficeAgentInput[]): OfficeLayout {const groups: { label: string; members: OfficeAgentInput[] }[] = groupDepartments(agents);if (groups.length === 1 && groups[0].members.length === 0) groups.length = 0;while (groups.length < MIN_DEPARTMENTS) groups.push({ label: "", members: [] });- // Both floors share one footprint: the elevator ride never changes the size of the world.// Mission Control's screen (1.4 m) fits the normal aisle with a walkway on each side.const centreAisle = AISLE;const floorWidth = COLUMNS * DEPT_WIDTH + (COLUMNS - 1) * centreAisle;@@ -578,17 +664,14 @@ export function buildOfficeLayout(agents: readonly OfficeAgentInput[], options:const topZ = -floorDepth / 2;const bottomZ = floorDepth / 2;- // North strip: lead office · team room · wardrobe, each with a door facing the office.- // The coding floor puts Mission Control and a server room on the same footprints.+ // North strip: Mission Control · team room · server room, each with a door facing the office.const leadW = 8.2, teamW = 8.4;const northMaxZ = topZ + NORTH_DEPTH;- const westKind: RoomKind = coding ? "command" : "lead";- const eastKind: RoomKind = coding ? "server" : "wardrobe";- const leadRoom: Room = { id: westKind, kind: westKind, walled: true, minX, maxX: minX + leadW, minZ: topZ, maxZ: northMaxZ,+ const leadRoom: Room = { id: "command", kind: "command", walled: true, minX, maxX: minX + leadW, minZ: topZ, maxZ: northMaxZ,doors: [{ side: "south", at: minX + leadW / 2, width: 1.6 }] };const teamRoom: Room = { id: "team", kind: "team", walled: true, minX: leadRoom.maxX, maxX: leadRoom.maxX + teamW, minZ: topZ, maxZ: northMaxZ,doors: [{ side: "south", at: leadRoom.maxX + teamW / 2, width: 1.8 }] };- const wardrobeRoom: Room = { id: eastKind, kind: eastKind, walled: true, minX: teamRoom.maxX, maxX, minZ: topZ, maxZ: northMaxZ,+ const serverRoom: Room = { id: "server", kind: "server", walled: true, minX: teamRoom.maxX, maxX, minZ: topZ, maxZ: northMaxZ,doors: [{ side: "south", at: (teamRoom.maxX + maxX) / 2, width: 1.5 }] };// Departments between the strips, and the centre line of each cross aisle between two rows.@@ -624,67 +707,26 @@ export function buildOfficeLayout(agents: readonly OfficeAgentInput[], options:const receptionRoom: Room = { id: "reception", kind: "reception", walled: false, minX, maxX: maxX - breakW, minZ: southMinZ, maxZ: bottomZ, doors: [] };const breakRoom: Room = { id: "break", kind: "break", walled: true, minX: maxX - breakW, maxX, minZ: southMinZ, maxZ: bottomZ,doors: [{ side: "north", at: maxX - breakW / 2, width: 2.2 }, { side: "west", at: southMinZ + SOUTH_DEPTH / 2, width: 2 }] };- // The Level Hall: the agents floor's east wing, one aisle beyond the office, across the whole depth.- const hallMinX = maxX + LEVEL_HALL.aisle;- const levelRoom: Room | null = coding ? null : {- id: "levels", kind: "levels", walled: true, minX: hallMinX, maxX: hallMinX + LEVEL_HALL.width, minZ: topZ, maxZ: bottomZ,- // The spawn point's cross aisle leads to the main door (it carries the sign); the north and south aisles have one each.- doors: [plazaZ, northMaxZ + AISLE / 2, southMinZ - AISLE / 2].map((at) => ({ side: "west" as const, at, width: 2 })),- };- const outerMaxX = levelRoom ? levelRoom.maxX : maxX;- const rooms = [leadRoom, teamRoom, wardrobeRoom, receptionRoom, breakRoom, ...(levelRoom ? [levelRoom] : [])];- const hall = levelRoom ? levelHall(levelRoom) : null;+ const rooms = [leadRoom, teamRoom, serverRoom, receptionRoom, breakRoom];- // The lead's executive desk faces south, towards the door and the office. A- // second lead gets a partner desk to its east; there is never an empty one.- const leadAgents = coding ? [] : agents.filter((a) => a.tier === "lead").sort(byArrival).slice(0, 2);const lx0 = leadRoom.minX, lz0 = leadRoom.minZ;- const leadDeskZ = lz0 + 2.6;- const lead = {- minX: leadRoom.minX, maxX: leadRoom.maxX, minZ: leadRoom.minZ, maxZ: leadRoom.maxZ,- desks: coding ? [] : [- { id: "lead:0", x: lx0 + leadW / 2, z: leadDeskZ, facing: "south", agentId: leadAgents[0]?.agentId ?? null, size: EXECUTIVE_DESK_SIZE },- ...(leadAgents[1] ? [{ id: "lead:1", x: lx0 + 6.75, z: leadDeskZ, facing: "south" as const, agentId: leadAgents[1].agentId, size: PARTNER_DESK_SIZE }] : []),- ] satisfies DeskSlot[],- };+ const lead = { minX: leadRoom.minX, maxX: leadRoom.maxX, minZ: leadRoom.minZ, maxZ: leadRoom.maxZ, desks: [] as DeskSlot[] };const tcx = (teamRoom.minX + teamRoom.maxX) / 2, tcz = (teamRoom.minZ + teamRoom.maxZ) / 2;- const wcx = (wardrobeRoom.minX + wardrobeRoom.maxX) / 2;+ const wcx = (serverRoom.minX + serverRoom.maxX) / 2;const bx0 = breakRoom.minX, bz0 = breakRoom.minZ;const rx0 = receptionRoom.minX;- const leadFurniture: Furniture[] = coding ? [] : [- // Lead office: a panelled feature wall with lit bookcases and the star emblem,- // a rug under the executive desk, guest armchairs, the bar and a leather- // lounge along the west wall (their fronts face the camera), a globe and a- // lamp in the east, palms beside the door.- { id: "lead-wall", kind: "leadWall", x: lx0 + leadW / 2, z: lz0 + 0.1 + FURNITURE_SIZE.leadWall.d / 2, rotationY: 0, room: "lead" },- { id: "lead-rug", kind: "executiveRug", x: lx0 + leadW / 2, z: lz0 + 3.55, rotationY: 0, room: "lead", size: { w: 4.6, d: 3.9 } },- { id: "lead-guest-w", kind: "guestChair", x: lx0 + leadW / 2 - 0.72, z: leadDeskZ + 1.2, rotationY: Math.PI, room: "lead" },- { id: "lead-guest-e", kind: "guestChair", x: lx0 + leadW / 2 + 0.72, z: leadDeskZ + 1.2, rotationY: Math.PI, room: "lead" },- { id: "lead-sofa", kind: "chesterfield", x: lx0 + 0.6, z: lz0 + 4.55, rotationY: Math.PI / 2, room: "lead" },- { id: "lead-table", kind: "loungeTable", x: lx0 + 1.62, z: lz0 + 4.55, rotationY: Math.PI / 2, room: "lead" },- { id: "lead-lamp", kind: "floorLamp", x: lx0 + 0.4, z: lz0 + 3.1, rotationY: 0, room: "lead" },- { id: "lead-bar", kind: "executiveBar", x: lx0 + 0.36, z: lz0 + 1.85, rotationY: Math.PI / 2, room: "lead" },- { id: "lead-globe", kind: "globe", x: leadRoom.maxX - 0.75, z: lz0 + 4.3, rotationY: 0, room: "lead" },- { id: "lead-lamp-e", kind: "floorLamp", x: leadRoom.maxX - 0.34, z: lz0 + 2.9, rotationY: 0, room: "lead" },- { id: "lead-plant", kind: "plant", x: lx0 + 0.55, z: northMaxZ - 0.55, rotationY: 0, room: "lead" },- { id: "lead-plant-e", kind: "plant", x: leadRoom.maxX - 0.55, z: northMaxZ - 0.55, rotationY: 0, room: "lead" },- // The office dog's baskets: the lead office's north-east corner beside the- // bookcase, the team room's north-west corner and the break room's corner- // by the bookshelf. It walks between them now and then.- { id: "lead-dog", kind: "dogBed", x: leadRoom.maxX - 0.58, z: lz0 + 0.98, rotationY: 0, room: "lead" },- { id: "team-dog", kind: "dogBed", x: teamRoom.minX + 0.62, z: topZ + 0.95, rotationY: 0, room: "team" },- { id: "break-dog", kind: "dogBed", x: breakRoom.minX + 0.62, z: breakRoom.minZ + 1.6, rotationY: 0, room: "break" },- // Easter egg: the jar of dog treats next to the coffee bar.- { id: "break-treats", kind: "treatJar", x: breakRoom.minX + 9.95, z: breakRoom.minZ + 0.5, rotationY: 0, room: "break" },- ];- // Coding floor, west: Mission Control. The slat wall with the video wall- // along the north side, the desk in front of it turned towards the door:- // the person sits between desk and wall, facing into the room, and the- // monitors face them. A lounge corner with a sofa facing east, an open- // shelf on the east wall.+ // West: Mission Control. The slat wall with the video wall along the north+ // side, the desk in front of it turned towards the door: the person sits+ // between desk and wall, facing into the room, and the monitors face them.+ // A lounge corner with a sofa facing east, an open shelf on the east wall.const commandDeskAt = { x: lx0 + leadW / 2, z: lz0 + 2.75 };- const commandFurniture: Furniture[] = coding ? [+ const wx0 = serverRoom.minX;+ // Server room: the rack rows' centre line and the cold aisle between their fronts.+ const serverRowZ = topZ + 3.5;+ const serverAisleMinX = wx0 + 0.06 + FURNITURE_SIZE.serverRack.d;+ const serverAisleMaxX = serverRoom.maxX - 0.06 - FURNITURE_SIZE.serverRack.d;+ const furniture: Furniture[] = [{ id: "command-wall", kind: "commandWall", x: lx0 + leadW / 2, z: lz0 + 0.1 + FURNITURE_SIZE.commandWall.d / 2, rotationY: 0, room: "command" },// The piece's box is desk + chair; its origin sits between them.{ id: "command-desk", kind: "commandDesk", x: commandDeskAt.x, z: commandDeskAt.z - COMMAND_DESK_OFFSET, rotationY: Math.PI, room: "command" },@@ -695,15 +737,6 @@ export function buildOfficeLayout(agents: readonly OfficeAgentInput[], options:{ id: "command-plant-w", kind: "plant", x: lx0 + 0.5, z: lz0 + 0.95, rotationY: 0, room: "command" },{ id: "command-plant-e", kind: "plant", x: leadRoom.maxX - 0.5, z: lz0 + 0.95, rotationY: 0, room: "command" },{ id: "command-plant-s", kind: "plant", x: leadRoom.maxX - 0.55, z: northMaxZ - 0.55, rotationY: 0, room: "command" },- ] : [];- const wx0 = wardrobeRoom.minX;- // Server room: the rack rows' centre line and the cold aisle between their fronts.- const serverRowZ = topZ + 3.5;- const serverAisleMinX = wx0 + 0.06 + FURNITURE_SIZE.serverRack.d;- const serverAisleMaxX = wardrobeRoom.maxX - 0.06 - FURNITURE_SIZE.serverRack.d;- const furniture: Furniture[] = [- ...leadFurniture,- ...commandFurniture,// Team room: a walnut table on a wool rug, the board on a slat wall with// felt panels and a video display, a credenza under the display and one// along the west wall, fiddle-leaf figs in both corners by the door.@@ -715,47 +748,31 @@ export function buildOfficeLayout(agents: readonly OfficeAgentInput[], options:{ id: "team-credenza-w", kind: "credenza", x: teamRoom.minX + 0.07 + FURNITURE_SIZE.credenza.d / 2, z: tcz + 0.4, rotationY: Math.PI / 2, room: "team" },{ id: "team-plant", kind: "designerPlant", x: teamRoom.maxX - 0.6, z: northMaxZ - 0.6, rotationY: 0, room: "team" },{ id: "team-plant-w", kind: "designerPlant", x: teamRoom.minX + 0.6, z: northMaxZ - 0.6, rotationY: Math.PI / 2, room: "team" },- ...(coding ? [- // Coding floor, east: a server room — two rack rows back to the side walls,- // fronts facing across a cold aisle that runs from the door to the NOC- // console and the status wall on the north side; the UPS and the- // fire-suppression bank stand in the corners by the door.- { id: "server-status", kind: "statusWall", x: wcx, z: topZ + 0.08 + FURNITURE_SIZE.statusWall.d / 2, rotationY: 0, room: "server" },- { id: "server-noc", kind: "nocConsole", x: wcx, z: topZ + 0.5 + FURNITURE_SIZE.nocConsole.d / 2, rotationY: 0, room: "server" },- { id: "server-rack-w", kind: "serverRack", x: wx0 + 0.06 + FURNITURE_SIZE.serverRack.d / 2, z: serverRowZ, rotationY: Math.PI / 2, room: "server" },- { id: "server-rack-e", kind: "serverRack", x: wardrobeRoom.maxX - 0.06 - FURNITURE_SIZE.serverRack.d / 2, z: serverRowZ, rotationY: -Math.PI / 2, room: "server" },- { id: "server-aisle", kind: "coldAisle", x: wcx, z: serverRowZ, rotationY: 0, room: "server" },- { id: "server-ups", kind: "ups", x: wx0 + 0.06 + FURNITURE_SIZE.ups.d / 2, z: topZ + 6.0, rotationY: Math.PI / 2, room: "server" },- { id: "server-fire", kind: "fireSuppression", x: wardrobeRoom.maxX - 0.06 - FURNITURE_SIZE.fireSuppression.d / 2, z: topZ + 6.0, rotationY: -Math.PI / 2, room: "server" },- ] satisfies Furniture[] : [- // Wardrobe: an open oak wardrobe along the north wall, a bulb-lit mirror- // on the west side facing the room, a tailor's dummy, a bench on the east- // side, a round rug under the checkpoint, a fig and a coat stand by the door.- { id: "wardrobe-wall", kind: "wardrobeWall", x: wcx, z: topZ + 0.06 + FURNITURE_SIZE.wardrobeWall.d / 2, rotationY: 0, room: "wardrobe" },- { id: "wardrobe-rug", kind: "roundRug", x: wcx, z: tcz + 0.3, rotationY: 0, room: "wardrobe", size: { w: 2.8, d: 2.8 } },- { id: "wardrobe-mirror", kind: "dressingMirror", x: wx0 + 0.06 + FURNITURE_SIZE.dressingMirror.d / 2, z: tcz - 0.6, rotationY: Math.PI / 2, room: "wardrobe" },- { id: "wardrobe-dummy", kind: "tailorDummy", x: wardrobeRoom.maxX - 0.6, z: topZ + 1.4, rotationY: -Math.PI / 4, room: "wardrobe" },- { id: "wardrobe-bench", kind: "dressingBench", x: wardrobeRoom.maxX - 0.06 - FURNITURE_SIZE.dressingBench.d / 2, z: tcz + 0.1, rotationY: -Math.PI / 2, room: "wardrobe" },- { id: "wardrobe-plant", kind: "designerPlant", x: wx0 + 0.5, z: northMaxZ - 0.5, rotationY: 0, room: "wardrobe" },- { id: "wardrobe-stand", kind: "coatStand", x: wardrobeRoom.maxX - 0.4, z: northMaxZ - 0.45, rotationY: 0, room: "wardrobe" },- ] satisfies Furniture[]),- // Reception and lobby.+ // East: a server room — two rack rows back to the side walls, fronts facing+ // across a cold aisle that runs from the door to the NOC console and the+ // status wall on the north side; the UPS and the fire-suppression bank+ // stand in the corners by the door.+ { id: "server-status", kind: "statusWall", x: wcx, z: topZ + 0.08 + FURNITURE_SIZE.statusWall.d / 2, rotationY: 0, room: "server" },+ { id: "server-noc", kind: "nocConsole", x: wcx, z: topZ + 0.5 + FURNITURE_SIZE.nocConsole.d / 2, rotationY: 0, room: "server" },+ { id: "server-rack-w", kind: "serverRack", x: wx0 + 0.06 + FURNITURE_SIZE.serverRack.d / 2, z: serverRowZ, rotationY: Math.PI / 2, room: "server" },+ { id: "server-rack-e", kind: "serverRack", x: serverRoom.maxX - 0.06 - FURNITURE_SIZE.serverRack.d / 2, z: serverRowZ, rotationY: -Math.PI / 2, room: "server" },+ { id: "server-aisle", kind: "coldAisle", x: wcx, z: serverRowZ, rotationY: 0, room: "server" },+ { id: "server-ups", kind: "ups", x: wx0 + 0.06 + FURNITURE_SIZE.ups.d / 2, z: topZ + 6.0, rotationY: Math.PI / 2, room: "server" },+ { id: "server-fire", kind: "fireSuppression", x: serverRoom.maxX - 0.06 - FURNITURE_SIZE.fireSuppression.d / 2, z: topZ + 6.0, rotationY: -Math.PI / 2, room: "server" },+ // Reception and lobby: only plants beside the elevator; new coding agents are spawned in the middle of the floor.{ id: "elevator", kind: "elevator", x: rx0 + 0.25, z: bottomZ - 2.6, rotationY: Math.PI / 2, room: "reception" },{ id: "reception-desk", kind: "receptionDesk", x: rx0 + 3.2, z: southMinZ + 2.6, rotationY: 0, room: "reception" },// The spawn point in the middle of the floor: the pad, and the terminal on it facing the lobby.{ id: "spawn-pad", kind: "spawnPad", x: plaza.x, z: plaza.z, rotationY: 0, room: "floor" },{ id: "spawn-terminal", kind: "spawnTerminal", x: plaza.x, z: plaza.z, rotationY: 0, room: "floor" },- ...(coding ? [- // The coding lobby keeps only its plants: new coding agents are spawned in the middle of the floor.- { id: "lobby-plant-a", kind: "plant", x: rx0 + 0.6, z: southMinZ + 0.8, rotationY: 0, room: "reception" },- { id: "lobby-plant-b", kind: "plant", x: receptionRoom.maxX - 0.8, z: bottomZ - 0.7, rotationY: 0, room: "reception" },- ] satisfies Furniture[] : lobbyFurniture(receptionRoom)),- // Break room lounge (both floors): an L-shaped sectional — module A along the- // south facing north, module B along the west facing east, the corner module- // joining them — round an oak coffee table on a kilim; the bookcase wall and- // the coffee bar on the north wall; the reading nook in the north-west corner- // by the dog's basket; foosball, beanbags, the water station and the arcade- // on its pixel mat in the east; monsteras in two corners.+ { id: "lobby-plant-a", kind: "plant", x: rx0 + 0.6, z: southMinZ + 0.8, rotationY: 0, room: "reception" },+ { id: "lobby-plant-b", kind: "plant", x: receptionRoom.maxX - 0.8, z: bottomZ - 0.7, rotationY: 0, room: "reception" },+ // Break room lounge: an L-shaped sectional — module A along the south facing+ // north, module B along the west facing east, the corner module joining+ // them — round an oak coffee table on a kilim; the bookcase wall and the+ // coffee bar on the north wall; the reading nook in the north-west corner;+ // foosball, beanbags, the water station and the arcade on its pixel mat in+ // the east; monsteras in two corners.{ id: "break-rug", kind: "breakRug", x: bx0 + 3.4, z: bz0 + 4.9, rotationY: 0, room: "break", size: { w: 5.2, d: 4.2 } },{ id: "break-sofa-a", kind: "breakSofa", x: bx0 + 3.3, z: bz0 + 6.3, rotationY: Math.PI, room: "break" },{ id: "break-sofa-b", kind: "breakSofa", x: bx0 + 1.75, z: bz0 + 4.75, rotationY: Math.PI / 2, room: "break" },@@ -772,7 +789,6 @@ export function buildOfficeLayout(agents: readonly OfficeAgentInput[], options:{ id: "break-nook", kind: "readingNook", x: bx0 + 0.53, z: bz0 + 0.58, rotationY: 0, room: "break" },{ id: "break-plant", kind: "breakPlant", x: bx0 + 0.6, z: bottomZ - 0.6, rotationY: 0, room: "break" },{ id: "break-plant-e", kind: "breakPlant", x: breakRoom.maxX - 0.45, z: bz0 + 5.9, rotationY: 0, room: "break" },- ...(hall?.furniture ?? []),];for (const dept of departments) {furniture.push({ id: `${dept.id}-plant-w`, kind: "plant", x: dept.minX + 0.45, z: dept.maxZ - 0.45, rotationY: 0, room: "floor" });@@ -795,23 +811,14 @@ export function buildOfficeLayout(agents: readonly OfficeAgentInput[], options:{ id: "beanbag-a", kind: "beanbag", pose: "sit", x: bx0 + 6.6, z: bz0 + 6.1, facing: Math.PI * 1.25, room: "break" },{ id: "beanbag-b", kind: "beanbag", pose: "sit", x: bx0 + 7.8, z: bz0 + 6.75, facing: Math.PI * 1.25, room: "break" },{ id: "shelf-break", kind: "shelf", pose: "stand", x: bx0 + 2.2, z: bz0 + 1.1, facing: Math.PI, room: "break" },- ...(coding ? [- // Mission Control: the sofa facing east, the open shelf on the east wall.- { id: "couch-command-1", kind: "couch", pose: "sit", x: lx0 + 0.75, z: lz0 + 4.55, facing: Math.PI / 2, room: "command" },- { id: "couch-command-2", kind: "couch", pose: "sit", x: lx0 + 0.75, z: lz0 + 5.65, facing: Math.PI / 2, room: "command" },- { id: "shelf-command", kind: "shelf", pose: "stand", x: leadRoom.maxX - 1.1, z: lz0 + 4.7, facing: Math.PI / 2, room: "command" },- // Server room: in the cold aisle, each looking at a rack row's glass fronts.- { id: "console-e", kind: "board", pose: "stand", x: serverAisleMaxX - 0.55, z: serverRowZ, facing: Math.PI / 2, room: "server" },- { id: "console-w", kind: "board", pose: "stand", x: serverAisleMinX + 0.55, z: serverRowZ, facing: -Math.PI / 2, room: "server" },- ] satisfies Spot[] : [- // In front of the feature wall's east bookcase.- { id: "shelf-lead", kind: "shelf", pose: "stand", x: leadRoom.maxX - 1.45, z: topZ + 1.05, facing: Math.PI, room: "lead" },- // Browsing the wardrobe's jacket rail.- { id: "shelf-wardrobe", kind: "shelf", pose: "stand", x: wcx - 1.0, z: topZ + 1.3, facing: Math.PI, room: "wardrobe" },- ...lobbySpots(receptionRoom),- ] satisfies Spot[]),+ // Mission Control: the sofa facing east, the open shelf on the east wall.+ { id: "couch-command-1", kind: "couch", pose: "sit", x: lx0 + 0.75, z: lz0 + 4.55, facing: Math.PI / 2, room: "command" },+ { id: "couch-command-2", kind: "couch", pose: "sit", x: lx0 + 0.75, z: lz0 + 5.65, facing: Math.PI / 2, room: "command" },+ { id: "shelf-command", kind: "shelf", pose: "stand", x: leadRoom.maxX - 1.1, z: lz0 + 4.7, facing: Math.PI / 2, room: "command" },+ // Server room: in the cold aisle, each looking at a rack row's glass fronts.+ { id: "console-e", kind: "board", pose: "stand", x: serverAisleMaxX - 0.55, z: serverRowZ, facing: Math.PI / 2, room: "server" },+ { id: "console-w", kind: "board", pose: "stand", x: serverAisleMinX + 0.55, z: serverRowZ, facing: -Math.PI / 2, room: "server" },{ id: "board", kind: "board", pose: "stand", x: tcx - 0.6, z: topZ + 1.2, facing: Math.PI, room: "team" },- ...(hall?.spots ?? []),];// Meeting chairs: three per long side of the team table.for (let i = 0; i < 3; i += 1) {@@ -819,7 +826,7 @@ export function buildOfficeLayout(agents: readonly OfficeAgentInput[], options:spots.push({ id: `meeting-n${i}`, kind: "meeting", pose: "sit", x, z: table.z - 1.25, facing: 0, room: "team" });spots.push({ id: `meeting-s${i}`, kind: "meeting", pose: "sit", x, z: table.z + 1.25, facing: Math.PI, room: "team" });}- // Window spots along the east and west railing, looking out at the stars (on the agents floor the east ones look into the Level Hall).+ // Window spots along the east and west railing, looking out at the stars.for (const dept of departments) {const side = dept.minX <= minX + 0.01 ? "west" : dept.maxX >= maxX - 0.01 ? "east" : null;if (!side) continue;@@ -830,165 +837,57 @@ export function buildOfficeLayout(agents: readonly OfficeAgentInput[], options:});}- const reception = furniture.find((f) => f.id === "reception-desk")!;const elevator = furniture.find((f) => f.id === "elevator")!;// The spawn point's ring surrounds the terminal; "walk there" and newcomers stand south of it, facing the screen.const arrival: Point = { x: plaza.x, z: plaza.z + SPAWN.approach };- const spawnStop: Checkpoint = { id: coding ? "launch" : "spawn", room: "floor", x: plaza.x, z: plaza.z, radius: SPAWN.reach,- tokenY: SPAWN.tokenY, approach: arrival };+ const spawnStop: Checkpoint = { id: "launch", room: "floor", x: plaza.x, z: plaza.z, radius: SPAWN.reach, approach: arrival };// The elevator's doors face east into the lobby; its checkpoint is the floor in front of them.const elevatorStop: Checkpoint = { id: "elevator", room: "reception", x: elevator.x + 0.95, z: elevator.z, radius: 1.0 };const breakStop: Checkpoint = { id: "break", room: "break", x: bx0 + 5.6, z: bz0 + 2.6, radius: 1.8 };// Mission Control's stop is a ring round the desk, usable from every side; "walk there" ends in front of the desk.const missionStop: Checkpoint = { id: "mission", room: "command", x: commandDeskAt.x, z: commandDeskAt.z - 0.3, radius: COMMAND_REACH,- tokenY: 2.25, approach: { x: commandDeskAt.x, z: commandDeskAt.z + COMMAND_DESK.d / 2 + 0.55 } };- const board = furniture.find((f) => f.id === AGENT_BOARD_ID);- const checkpoints: Checkpoint[] = coding ? [spawnStop, missionStop, elevatorStop, breakStop] : [- spawnStop,- { id: "create", room: "reception", x: reception.x, z: reception.z + 1.7, radius: 1.2 },- ...(board ? [{ id: "manage", room: "reception", x: board.x, z: board.z + 1.4, radius: 1.1 } satisfies Checkpoint] : []),- { id: "team", room: "team", x: tcx + 2.2, z: northMaxZ - 1.05, radius: 0.95 },- { id: "wardrobe", room: "wardrobe", x: wcx, z: tcz + 0.8, radius: 1.5 },- { id: "lead", room: "lead", x: minX + leadW / 2, z: northMaxZ - 1.5, radius: 1.3 },- ...(hall?.checkpoints ?? []),- breakStop,- elevatorStop,- ];+ approach: { x: commandDeskAt.x, z: commandDeskAt.z + COMMAND_DESK.d / 2 + 0.55 } };+ const checkpoints: Checkpoint[] = [spawnStop, missionStop, elevatorStop, breakStop];const walls = rooms.flatMap(wallsOf);- const desks = [...lead.desks, ...departments.flatMap((d) => d.desks)];+ const desks = departments.flatMap((d) => d.desks);const obstacles: Rect[] = [...walls.map(wallRect),...desks.map(deskRect),- ...lead.desks.filter((d) => d.size).map(executiveChairRect),// Bench desk chairs and the meeting chairs: nobody walks through a chair.- ...desks.filter((d) => !d.size).map((d) => chairRect(seatOf(d))),+ ...desks.map((d) => chairRect(seatOf(d))),...spots.filter((s) => s.kind === "meeting").map((s) => chairRect(s)),// 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),- ...(coding ? commandDeskObstacles(commandDeskAt) : []),- // Planter boxes at the bench ends (walnut on the coding floor, oak on the agents floor).+ ...commandDeskObstacles(commandDeskAt),+ // Walnut planter boxes at the bench ends....departments.flatMap(benchPlanters).map((p) => p.rect),- // The coding floor's tree planters, bookcases and troughs along the windows.- ...(coding ? codingAmbience({ departments, rooms }) : []).map(({ minX, maxX, minZ, maxZ }) => ({ minX, maxX, minZ, maxZ })),- // The agents floor's olive trees, window benches and planters along the windows.- ...(coding ? [] : agentsAmbience({ departments, rooms })).map(({ minX, maxX, minZ, maxZ }) => ({ minX, maxX, minZ, maxZ })),+ // The tree planters, bookcases and troughs along the windows.+ ...codingAmbience({ departments, rooms }).map(({ minX, maxX, minZ, maxZ }) => ({ minX, maxX, minZ, maxZ })),// 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 + RAIL_CLEARANCE, maxX: outerMaxX + EDGE - RAIL_CLEARANCE,- minZ: topZ - EDGE + RAIL_CLEARANCE, maxZ: bottomZ + EDGE - RAIL_CLEARANCE,- };return {- variant, departments, lead, rooms, walls, furniture, spots, checkpoints, obstacles,+ variant: "coding", departments, lead, rooms, walls, furniture, spots, checkpoints, obstacles,// Its chair faces south, towards the door: seatOf() puts the person north of the desk.- ...(coding ? { command: { id: "command", x: commandDeskAt.x, z: commandDeskAt.z, facing: "south" as const, agentId: null,- size: { w: COMMAND_DESK.w, d: COMMAND_DESK.d } } } : {}),+ command: { id: "command", x: commandDeskAt.x, z: commandDeskAt.z, facing: "south", agentId: null, size: { w: COMMAND_DESK.w, d: COMMAND_DESK.d } },spawn: { x: rx0 + 1.4, z: bottomZ - 2.6 },arrival,- floor,- bounds: { minX: minX - EDGE, maxX: outerMaxX + EDGE, minZ: topZ - EDGE, maxZ: bottomZ + EDGE },+ floor: {+ minX: minX - EDGE + RAIL_CLEARANCE, maxX: maxX + EDGE - RAIL_CLEARANCE,+ minZ: topZ - EDGE + RAIL_CLEARANCE, maxZ: bottomZ + EDGE - RAIL_CLEARANCE,+ },+ bounds: { minX: minX - EDGE, maxX: maxX + EDGE, minZ: topZ - EDGE, maxZ: bottomZ + EDGE },};}-/**- * The Level Hall's fittings, north to south: the Level Wall on the north wall- * with the Upgrade Studio's round stage in front of it (its checkpoint is the- * stage itself), the Level Road down the middle with a pedestal per reward on- * either side — the lowest unlock at the south end, the highest by the stage,- * so walking up the road is climbing the levels — and at the road's start the- * double-sided level guide with its checkpoint on the road side. Plants frame- * the stage, olive trees the guide.- */-function levelHall(room: Room): { furniture: Furniture[]; spots: Spot[]; checkpoints: Checkpoint[] } {- const cx = (room.minX + room.maxX) / 2;- const piece = (id: string, kind: FurnitureKind, x: number, z: number, rotationY = 0, size?: { w: number; d: number }): Furniture =>- ({ id, kind, x, z, rotationY, room: "levels", ...(size ? { size } : {}) });- const stageZ = room.minZ + LEVEL_HALL.stageZ;- const roadMinZ = room.minZ + LEVEL_HALL.roadNorth, roadMaxZ = room.maxZ - LEVEL_HALL.roadSouth;- const guideZ = room.maxZ - LEVEL_HALL.guideZ;- // Pedestal n (0 = the lowest unlock) stands on the west side when n is even, the east side when odd, rising northwards.- const rows = Math.ceil(REWARD_IDS.length / 2);- const pitch = rows > 1 ? (roadMaxZ - roadMinZ - 1.2) / (rows - 1) : 0;- const pedestals = REWARD_IDS.map((_, n) => piece(`level-pedestal-${n}`, "rewardPedestal",- cx + (n % 2 === 0 ? -PEDESTAL_OFFSET_X : PEDESTAL_OFFSET_X), roadMaxZ - 0.6 - Math.floor(n / 2) * pitch, n % 2 === 0 ? Math.PI / 2 : -Math.PI / 2));- const furniture: Furniture[] = [- piece("level-wall", "levelWall", cx, room.minZ + 0.08 + FURNITURE_SIZE.levelWall.d / 2),- piece("level-stage", "studioStage", cx, stageZ),- piece("level-road", "levelRoad", cx, (roadMinZ + roadMaxZ) / 2, 0, { w: 2.2, d: roadMaxZ - roadMinZ }),- ...pedestals,- // The guide faces up the road; its back shows the same screen to the lobby side.- piece("level-guide", "levelGuide", cx, guideZ, Math.PI),- piece("level-plant-nw", "designerPlant", room.minX + 0.6, room.minZ + 0.7),- piece("level-plant-ne", "designerPlant", room.maxX - 0.6, room.minZ + 0.7),- piece("level-olive-sw", "oliveTree", room.minX + 0.85, room.maxZ - 0.85),- piece("level-olive-se", "oliveTree", room.maxX - 0.85, room.maxZ - 0.85),- ];- const spots: Spot[] = [- // Agents come to look at the Level Wall and at the top of the road.- { id: "level-wall-w", kind: "shelf", pose: "stand", x: cx - 2.6, z: room.minZ + 1.5, facing: Math.PI, room: "levels" },- { id: "level-wall-e", kind: "shelf", pose: "stand", x: cx + 2.6, z: room.minZ + 1.5, facing: Math.PI, room: "levels" },- { id: "level-road-top", kind: "shelf", pose: "stand", x: cx, z: roadMinZ + 1.4, facing: Math.PI, room: "levels" },- ];- const checkpoints: Checkpoint[] = [- { id: "studio", room: "levels", x: cx, z: stageZ, radius: LEVEL_HALL.stageR, approach: { x: cx, z: stageZ + 0.6 } },- { id: "levels", room: "levels", x: cx, z: guideZ - 1.45, radius: 1.1 },- ];- return { furniture, spots, checkpoints };-}--/** The lobby lounge's sofa, relative to the reception room's west and north edges. */-const LOBBY_LOUNGE = { dx: 6.0, dz: 5.35 };-/** The agents floor's Agent board totem; the "manage" checkpoint stands in front of it. */-const AGENT_BOARD_ID = "agent-board";--/**- * The agents floor's lobby round the reception desk and the elevator: the- * brand wall on the west edge north of the elevator, an olive tree at each- * end of the room and one by the lounge, the award vitrine south of the- * elevator with the mat in front of its doors, and the waiting lounge — a- * sofa facing south, armchairs either side of the coffee table on a rug. The- * walk from the elevator north past the desk and east to the break room- * stays clear.- */-function lobbyFurniture(room: Rect): Furniture[] {- const x0 = room.minX, z0 = room.minZ;- const lx = x0 + LOBBY_LOUNGE.dx, lz = z0 + LOBBY_LOUNGE.dz;- const piece = (id: string, kind: FurnitureKind, x: number, z: number, rotationY = 0, size?: { w: number; d: number }): Furniture =>- ({ id, kind, x, z, rotationY, room: "reception", ...(size ? { size } : {}) });- return [- // The Agent board: a touch-screen totem in the lobby's north-east corner.- piece(AGENT_BOARD_ID, "agentTotem", room.maxX - 2.2, z0 + 2.2),- piece("lobby-brand-wall", "brandWall", x0 + 0.22, z0 + 2.55, Math.PI / 2),- piece("lobby-olive-nw", "oliveTree", x0 + 0.65, z0 + 0.35),- piece("lobby-olive-se", "oliveTree", room.maxX - 0.75, room.maxZ - 0.7),- piece("lobby-olive-s", "oliveTree", x0 + 2.7, room.maxZ - 0.55),- piece("lobby-awards", "awardCase", x0 + 0.26, room.maxZ - 0.62, Math.PI / 2),- piece("lobby-mat", "entranceMat", x0 + 1.3, room.maxZ - 2.6, 0, { w: 1.1, d: 1.9 }),- piece("lobby-rug", "lobbyRug", lx, lz + 0.75, 0, { w: 4.8, d: 2.9 }),- piece("lobby-sofa", "lobbySofa", lx, lz),- piece("lobby-table", "lobbyTable", lx, lz + 1.05),- piece("lobby-chair-w", "lobbyArmchair", lx - 1.8, lz + 1.1, Math.PI / 2),- piece("lobby-chair-e", "lobbyArmchair", lx + 1.8, lz + 1.1, -Math.PI / 2),- piece("lobby-side-table", "sideTable", lx - 1.5, lz - 0.05),- piece("lobby-lamp", "lobbyLamp", lx + 1.5, lz - 0.1),- ];-}--/** Seats in the lobby lounge: two on the sofa (facing south), one in each armchair (facing the table). */-function lobbySpots(room: Rect): Spot[] {- const lx = room.minX + LOBBY_LOUNGE.dx, lz = room.minZ + LOBBY_LOUNGE.dz;- return [- { id: "couch-lobby-1", kind: "couch", pose: "sit", x: lx - 0.55, z: lz + 0.15, facing: 0, room: "reception" },- { id: "couch-lobby-2", kind: "couch", pose: "sit", x: lx + 0.55, z: lz + 0.15, facing: 0, room: "reception" },- { id: "couch-lobby-w", kind: "couch", pose: "sit", x: lx - 1.78, z: lz + 1.1, facing: Math.PI / 2, room: "reception" },- { id: "couch-lobby-e", kind: "couch", pose: "sit", x: lx + 1.78, z: lz + 1.1, facing: -Math.PI / 2, room: "reception" },- ];+/** How many of the roster's agents have a desk on this floor plan. */+export function seatedCount(layout: OfficeLayout): number {+ return allDesks(layout).filter((desk) => desk.agentId !== null).length;}/** Every desk on the floor, lead office first. */diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeMotion.test.ts b/jarvis/ui/web/frontend/src/components/society/office/officeMotion.test.tsindex 51389b6467..85ea69dcc1 100644--- a/jarvis/ui/web/frontend/src/components/society/office/officeMotion.test.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/officeMotion.test.ts@@ -1,5 +1,8 @@import { describe, expect, it } from "vitest";-import { BODY_SPACING, WALK_SPEED, applySeparation, clearOfBodies, separation, stepClearOfBodies, stepMover, stepMoverAvoiding, turnToward, type Mover, wrapAngle } from "./officeMotion";+import {+ BODY_SPACING, BRISK_SPEED, STUCK, WALK_SPEED, applySeparation, clearOfBodies, clickPaceFor, hurryPaceFor, newStuckWatch, paceFor, segmentWalkable, separation, stepClearOfBodies, stepMover,+ stepMoverAvoiding, stepWalker, turnToward, watchProgress, type Mover, wrapAngle,+} from "./officeMotion";describe("office motion", () => {it("turns the short way and clamps the step", () => {@@ -95,3 +98,177 @@ describe("separation", () => {expect(b.path).toHaveLength(0);});});++const open = () => true;+const DT = 1 / 60;++describe("stepWalker", () => {+ it("lands exactly on the last waypoint and faces the way it walked", () => {+ for (const dt of [1 / 144, 1 / 60, 1 / 30, 0.1]) {+ const m: Mover = { x: 0, z: 0, heading: Math.PI / 2, path: [{ x: 3, z: 0 }, { x: 3, z: 2.37 }] };+ let ticks = 0;+ while (!stepWalker(m, WALK_SPEED, dt, [], open).arrived && ticks < 5000) ticks += 1;+ expect([m.x, m.z], `dt ${dt}`).toEqual([3, 2.37]);+ expect(m.heading, `dt ${dt}`).toBeCloseTo(0);+ }+ });++ it("turns before it walks instead of gliding sideways round a corner", () => {+ // Facing east, the route goes west: a U-turn.+ const m: Mover = { x: 0, z: 0, heading: Math.PI / 2, path: [{ x: -5, z: 0 }] };+ let sideways = 0;+ for (let i = 0; i < 120; i += 1) {+ const before = m.x;+ const { moved } = stepWalker(m, WALK_SPEED, DT, [], open);+ // Moving west while still facing away from west by more than 60°.+ if (Math.abs(wrapAngle(-Math.PI / 2 - m.heading)) > 1.05) sideways += Math.abs(m.x - before);+ expect(moved).toBeLessThanOrEqual(WALK_SPEED * DT + 1e-9);+ }+ expect(sideways).toBeLessThan(0.03);+ expect(m.heading).toBeCloseTo(-Math.PI / 2);+ expect(m.x).toBeLessThan(-2);+ });++ it("never steps onto blocked ground: it slides along a wall it is pushed against, or waits", () => {+ // A wall along z < 0; someone beside the walker pushes it towards the wall.+ const floor = (p: { x: number; z: number }) => p.z >= 0;+ const m: Mover = { x: 0, z: 0.05, heading: Math.PI / 2, path: [{ x: 6, z: 0.05 }] };+ const pusher = { x: 1.2, z: 0.75 };+ for (let i = 0; i < 400 && m.path.length > 0; i += 1) {+ stepWalker(m, WALK_SPEED, DT, [pusher], floor);+ expect(m.z).toBeGreaterThanOrEqual(0);+ expect(Math.hypot(m.x - pusher.x, m.z - pusher.z)).toBeGreaterThan(BODY_SPACING - 0.02);+ }+ expect([m.x, m.z]).toEqual([6, 0.05]);+ });++ it("never steps into anybody: with no way round it waits and says so", () => {+ // A corridor one body wide, someone standing in it.+ const corridor = (p: { x: number; z: number }) => Math.abs(p.z) <= 0.3;+ const m: Mover = { x: 0, z: 0, heading: Math.PI / 2, path: [{ x: 6, z: 0 }] };+ const body = { x: 3, z: 0 };+ let blocked = false;+ for (let i = 0; i < 600; i += 1) {+ const step = stepWalker(m, WALK_SPEED, DT, [body], corridor);+ blocked = step.blocked;+ expect(Math.hypot(m.x - body.x, m.z - body.z)).toBeGreaterThan(BODY_SPACING - 0.01);+ }+ expect(blocked).toBe(true);+ expect(m.x).toBeLessThan(3);+ expect(m.path).toHaveLength(1);+ });++ it("walks out of a seat and onto one although both lie inside a footprint", () => {+ // The chair's footprint covers x in [-0.5, 0.5]; a neighbour sits within arm's reach of the target seat.+ const floor = (p: { x: number; z: number }) => Math.abs(p.x) > 0.5 && Math.abs(p.x - 6) > 0.5;+ const m: Mover = { x: 0, z: 0, heading: 0, path: [{ x: 0.7, z: 0 }, { x: 5.3, z: 0 }, { x: 6, z: 0 }] };+ let ticks = 0;+ while (!stepWalker(m, WALK_SPEED, DT, [{ x: 6, z: 0.55 }], floor).arrived && ticks < 2000) ticks += 1;+ expect([m.x, m.z]).toEqual([6, 0]);+ });++ it("reports when steering carried it off its route", () => {+ // The straight line to the waypoint crosses a pillar the route went round.+ const pillar = (p: { x: number; z: number }) => !(p.x > 0.9 && p.x < 2 && Math.abs(p.z) < 0.3);+ const m: Mover = { x: 0.9, z: 0, heading: Math.PI / 2, path: [{ x: 3, z: 0 }] };+ const step = stepWalker(m, WALK_SPEED, DT, [], pillar);+ expect(step.offPath).toBe(true);+ expect(pillar(m)).toBe(true);+ });++ it("goes for the next waypoint once it is in plain view, never back to one it was pushed past", () => {+ const m: Mover = { x: 1.8, z: 0.4, heading: Math.PI / 2, path: [{ x: 2, z: 0 }, { x: 6, z: 0 }] };+ stepWalker(m, WALK_SPEED, DT, [{ x: 1.4, z: -0.3 }], open);+ expect(m.path).toEqual([{ x: 6, z: 0 }]);+ });+});++describe("segmentWalkable", () => {+ it("samples the first stretch of a line", () => {+ const wall = (p: { x: number; z: number }) => p.x < 1 || p.x > 1.2;+ expect(segmentWalkable({ x: 0, z: 0 }, { x: 0.9, z: 0 }, wall)).toBe(true);+ expect(segmentWalkable({ x: 0, z: 0 }, { x: 3, z: 0 }, wall)).toBe(false);+ // Only the first metres count: a wall far down the line is the route's business.+ expect(segmentWalkable({ x: -5, z: 0 }, { x: 3, z: 0 }, wall)).toBe(true);+ });+});++describe("paceFor", () => {+ it("strolls on short legs and walks briskly across the campus", () => {+ expect(paceFor(0)).toBe(WALK_SPEED);+ expect(paceFor(8)).toBe(WALK_SPEED);+ expect(paceFor(60)).toBe(BRISK_SPEED);+ expect(paceFor(17)).toBeGreaterThan(WALK_SPEED);+ expect(paceFor(17)).toBeLessThan(BRISK_SPEED);+ expect(paceFor(20)).toBeGreaterThan(paceFor(15));+ });+});++describe("hurryPaceFor", () => {+ it("is brisk on anything but the last steps, and never slower than the ordinary pace", () => {+ expect(hurryPaceFor(1)).toBe(WALK_SPEED);+ expect(hurryPaceFor(8)).toBe(BRISK_SPEED);+ expect(hurryPaceFor(40)).toBe(BRISK_SPEED);+ for (let m = 0; m < 40; m += 1) expect(hurryPaceFor(m)).toBeGreaterThanOrEqual(paceFor(m));+ });+});++describe("clickPaceFor", () => {+ it("jogs a long click-to-move route and settles to a walk before it arrives", () => {+ expect(clickPaceFor(60, 2, 4.4)).toBe(4.4);+ expect(clickPaceFor(22, 2, 4.4)).toBe(4.4);+ expect(clickPaceFor(7, 2, 4.4)).toBe(2);+ expect(clickPaceFor(0, 2, 4.4)).toBe(2);+ expect(clickPaceFor(14, 2, 4.4)).toBeGreaterThan(2);+ expect(clickPaceFor(14, 2, 4.4)).toBeLessThan(4.4);+ // Never a jump in pace: the change is spread over the metres in between.+ for (let m = 0; m < 30; m += 0.5) expect(Math.abs(clickPaceFor(m + 0.5, 2, 4.4) - clickPaceFor(m, 2, 4.4))).toBeLessThan(0.1);+ });++ it("crosses a campus in well under half the time a plain walk takes", () => {+ const time = (pace: (left: number) => number) => {+ const m: Mover = { x: 0, z: 0, heading: Math.PI / 2, path: [{ x: 70, z: 0 }] };+ let seconds = 0;+ while (seconds < 120 && !stepWalker(m, pace(70 - m.x), DT, [], open).arrived) seconds += DT;+ return seconds;+ };+ const walked = time(() => 2);+ const clicked = time((left) => clickPaceFor(left, 2, 4.4));+ expect(walked).toBeCloseTo(35, 0);+ expect(clicked).toBeLessThan(20);+ expect(clicked).toBeGreaterThan(70 / 4.4);+ });+});++describe("the stuck watch", () => {+ it("stays quiet while a figure makes progress, however slowly it queues", () => {+ const watch = newStuckWatch({ x: 0, z: 0 });+ let x = 0;+ for (let i = 0; i < 60 * 30; i += 1) {+ x += 0.34 * DT;+ expect(watchProgress(watch, { x, z: 0 }, DT)).toBe("ok");+ }+ });++ it("asks for a re-plan after 1.5 s without progress, twice, then for a rescue", () => {+ const watch = newStuckWatch({ x: 0, z: 0 });+ const verdicts: string[] = [];+ for (let i = 0; i < 60 * 6.2; i += 1) {+ // Shuffling on the spot is not progress.+ const verdict = watchProgress(watch, { x: Math.sin(i / 5) * 0.15, z: 0 }, DT);+ if (verdict !== "ok") verdicts.push(`${verdict}@${((i + 1) * DT).toFixed(1)}`);+ }+ // (Sixty frames of 1/60 s fall a hair short of a second, so each verdict comes a frame late.)+ expect(verdicts).toEqual(["[email protected]", "[email protected]", "[email protected]", "[email protected]"]);+ expect(STUCK.maxReplans).toBe(2);+ });++ it("starts over with every unit of progress", () => {+ const watch = newStuckWatch({ x: 0, z: 0 });+ for (let i = 0; i < 80; i += 1) watchProgress(watch, { x: 0, z: 0 }, DT);+ expect(watchProgress(watch, { x: 0, z: 0 }, 1)).toBe("replan");+ expect(watch.replans).toBe(1);+ expect(watchProgress(watch, { x: STUCK.progressM, z: 0 }, DT)).toBe("ok");+ expect(watch).toMatchObject({ idleS: 0, replans: 0, x: STUCK.progressM });+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeMotion.ts b/jarvis/ui/web/frontend/src/components/society/office/officeMotion.tsindex d7957693bc..094e08e0c1 100644--- a/jarvis/ui/web/frontend/src/components/society/office/officeMotion.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/officeMotion.ts@@ -153,3 +153,192 @@ export function stepMoverAvoiding(m: Mover, speed: number, dt: number, others: rm.heading = turnToward(m.heading, Math.atan2(ax, az), TURN_RATE * dt);return { moved: step, arrived: m.path.length === 0 };}++/** An agent's pace on a long leg: a walk across the campus is brisk, a few steps in the studio are not. */+export const BRISK_SPEED = 2.1;+const BRISK_FROM_M = 9;+const BRISK_FULL_M = 26;++/** Walking speed for a route with `remaining` metres left: WALK_SPEED on short legs, up to BRISK_SPEED on long ones. */+export function paceFor(remaining: number): number {+ const t = Math.min(1, Math.max(0, (remaining - BRISK_FROM_M) / (BRISK_FULL_M - BRISK_FROM_M)));+ return WALK_SPEED + (BRISK_SPEED - WALK_SPEED) * t;+}++/** An agent on its way to its screen walks briskly from this much route on. */+const HURRY_FROM_M = 3;+const HURRY_FULL_M = 8;++/**+ * The pace of an agent that has somewhere it must be (its screen, once it+ * works): brisk on anything but the last steps. A working agent that strolls+ * home from the far end of the campus is "working" and absent for too long.+ */+export function hurryPaceFor(remaining: number): number {+ const t = Math.min(1, Math.max(0, (remaining - HURRY_FROM_M) / (HURRY_FULL_M - HURRY_FROM_M)));+ return Math.max(paceFor(remaining), WALK_SPEED + (BRISK_SPEED - WALK_SPEED) * t);+}++/** The person's click-to-move jogs while more than this much route is left, and has settled to a walk by the last metres. */+const CLICK_JOG_FULL_M = 22;+const CLICK_WALK_WITHIN_M = 7;++/**+ * The pace of the person's character on a click-to-move route with+ * `remaining` metres left: `walk` near the target, `run` on a long way, a+ * smooth change in between. A long click crosses the campus at a jog; the+ * last steps are a walk, so the character does not overshoot what it was+ * sent to.+ */+export function clickPaceFor(remaining: number, walk: number, run: number): number {+ const t = Math.min(1, Math.max(0, (remaining - CLICK_WALK_WITHIN_M) / (CLICK_JOG_FULL_M - CLICK_WALK_WITHIN_M)));+ return walk + (run - walk) * t;+}++/** Above this angle between where a figure faces and where it must go, it turns before it walks. */+const TURN_FIRST_RAD = 0.5;+/** The crawl left while turning on the spot, as a share of the pace: feet never glide sideways. */+const TURN_CRAWL = 0.08;+/** Avoidance fades out this close to the route's end, so a figure can reach a place beside a seated colleague. */+const AVOID_FADE_M = 1.5;+/** A waypoint a steered figure passed this closely counts as reached. */+const WAYPOINT_REACH_M = 0.14;++export interface WalkStep {+ /** Metres actually covered this step. */+ moved: number;+ arrived: boolean;+ /** Nothing was free: a body or a wall is in the way. */+ blocked: boolean;+ /** Steering carried the figure off its route: the straight line to the next waypoint leaves the floor. */+ offPath: boolean;+}++/** True when the first `maxLen` metres of a→b lie on walkable ground (sampled every 0.1 m). */+export function segmentWalkable(a: Point, b: Point, walkable: (p: Point) => boolean, maxLen = 1.5): boolean {+ const dx = b.x - a.x, dz = b.z - a.z;+ const len = Math.hypot(dx, dz);+ if (len < 1e-6) return true;+ const reach = Math.min(len, maxLen);+ for (let d = 0.1; d <= reach + 1e-9; d += 0.1) {+ if (!walkable({ x: a.x + (dx / len) * d, z: a.z + (dz / len) * d })) return false;+ }+ return true;+}++/**+ * One step of a figure along its path among other bodies. Unlike+ * `stepMoverAvoiding` it never leaves walkable ground and never steps into+ * anybody: every candidate step (steered, straight, then a slide to the right+ * or left) is checked against the floor and the bodies, and when none is free+ * the figure waits. It turns before it walks, faces where it actually moves,+ * and lands exactly on the last waypoint.+ *+ * Two legs may cross blocked cells, as the route itself does: the first steps+ * out of a seat, and the final step onto a seat inside a footprint. Both go+ * straight along the route. Getting up, a figure still waits for whoever+ * stands in its way; the seat it walks to is reserved, so bodies do not veto+ * that last step.+ */+export function stepWalker(m: Mover, speed: number, dt: number, others: readonly Point[], walkable: (p: Point) => boolean): WalkStep {+ while (m.path.length > 0 && Math.hypot(m.path[0].x - m.x, m.path[0].z - m.z) < 1e-6) m.path.shift();+ if (m.path.length === 0) return { moved: 0, arrived: true, blocked: false, offPath: false };+ const next = m.path[0];+ const final = m.path.length === 1;+ const dx = next.x - m.x, dz = next.z - m.z;+ const dist = Math.hypot(dx, dz);+ const ux = dx / dist, uz = dz / dist;+ const here = walkable(m);+ const seatLeg = final && !walkable(next);+ // On the floor a figure steers; inside a footprint (leaving or taking a seat) it follows the route.+ const steering = here && !seatLeg;++ let sx = ux, sz = uz;+ let slow = 1;+ if (steering && others.length > 0) {+ const end = m.path[m.path.length - 1];+ const fade = Math.min(1, Math.max(0, (Math.hypot(end.x - m.x, end.z - m.z) - 0.3) / (AVOID_FADE_M - 0.3)));+ const push = separation(m, m.heading, others, 1.2);+ if (fade > 0 && Math.hypot(push.x, push.z) > 1e-3) {+ const ax = ux + push.x * 1.6 * fade, az = uz + push.z * 1.6 * fade;+ const len = Math.hypot(ax, az);+ if (len > 1e-6) { sx = ax / len; sz = az / len; }+ }+ // Slow down while someone blocks the way ahead.+ for (const o of others) {+ const ox = o.x - m.x, oz = o.z - m.z;+ const d = Math.hypot(ox, oz);+ if (d < 0.95 && d > 1e-6 && (ox * ux + oz * uz) / d > 0.7) slow = Math.min(slow, Math.max(0.25, (d - BODY_SPACING) / 0.4));+ }+ }+ const pace = Math.max(0, speed * slow * dt);+ const free = (p: Point) => (seatLeg ? true : (steering ? walkable(p) : true) && stepClearOfBodies(p, m, others));+ const at = (cx: number, cz: number, len: number): Point => ({ x: m.x + cx * len, z: m.z + cz * len });++ // The wanted direction first, then straight at the waypoint, then a slide past whatever is in the way (right before left).+ const rx = uz, rz = -ux;+ const candidates: [number, number][] = [[sx, sz]];+ if (sx !== ux || sz !== uz) candidates.push([ux, uz]);+ if (steering) {+ candidates.push([(ux + rx) * Math.SQRT1_2, (uz + rz) * Math.SQRT1_2], [(ux - rx) * Math.SQRT1_2, (uz - rz) * Math.SQRT1_2], [rx, rz], [-rx, -rz]);+ }+ const offPath = steering && !walkable(at(ux, uz, Math.min(pace, dist)));+ let chosen: [number, number] | null = null;+ for (const c of candidates) {+ const straight = c[0] === ux && c[1] === uz;+ if (free(at(c[0], c[1], straight ? Math.min(pace, dist) : pace))) { chosen = c; break; }+ }+ if (!chosen || pace <= 0) {+ m.heading = turnToward(m.heading, Math.atan2(sx, sz), TURN_RATE * dt);+ return { moved: 0, arrived: false, blocked: pace > 0, offPath };+ }+ const [cx, cz] = chosen;+ const straight = cx === ux && cz === uz;+ const off = Math.abs(wrapAngle(Math.atan2(cx, cz) - m.heading));+ m.heading = turnToward(m.heading, Math.atan2(cx, cz), TURN_RATE * dt);+ const align = off < TURN_FIRST_RAD ? 1 : Math.max(TURN_CRAWL, Math.cos(off) / Math.cos(TURN_FIRST_RAD));+ const step = straight ? Math.min(pace * align, dist) : pace * align;+ const to = at(cx, cz, step);+ if (step < pace && !free(to)) return { moved: 0, arrived: false, blocked: true, offPath };+ if (straight && step >= dist - 1e-9) { m.x = next.x; m.z = next.z; m.path.shift(); }+ else {+ m.x = to.x; m.z = to.z;+ if (!final && !straight) {+ const left = Math.hypot(next.x - m.x, next.z - m.z);+ // Pushed past a corner: head for the next waypoint as soon as it is in plain view, never back to this one.+ // A figure on its route takes every corner exactly where the route has it.+ if (left < WAYPOINT_REACH_M || (left < 0.6 && segmentWalkable(m, m.path[1], walkable))) m.path.shift();+ }+ }+ return { moved: step, arrived: m.path.length === 0, blocked: false, offPath };+}++/** Progress that counts as one unit of walking, how long without it before a re-plan, and how many re-plans before a rescue. */+export const STUCK = { progressM: 0.4, replanS: 1.5, maxReplans: 2 } as const;++/** Watches one walk for a figure that stopped getting anywhere. */+export interface StuckWatch { x: number; z: number; idleS: number; replans: number }++export function newStuckWatch(at: Point): StuckWatch {+ return { x: at.x, z: at.z, idleS: 0, replans: 0 };+}++export type StuckVerdict = "ok" | "replan" | "rescue";++/**+ * Feed the watch one frame. Every 0.4 m of real progress is a unit of work+ * and resets it; without progress for 1.5 s it asks for a re-plan, and after+ * two re-plans that did not help for a rescue (a safe placement).+ */+export function watchProgress(watch: StuckWatch, at: Point, dt: number): StuckVerdict {+ if (Math.hypot(at.x - watch.x, at.z - watch.z) >= STUCK.progressM) {+ watch.x = at.x; watch.z = at.z; watch.idleS = 0; watch.replans = 0;+ return "ok";+ }+ watch.idleS += dt;+ if (watch.idleS < STUCK.replanS) return "ok";+ watch.idleS = 0;+ if (watch.replans < STUCK.maxReplans) { watch.replans += 1; return "replan"; }+ watch.replans = 0;+ return "rescue";+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeNav.test.ts b/jarvis/ui/web/frontend/src/components/society/office/officeNav.test.tsindex ce3a87cf36..d0756097b7 100644--- a/jarvis/ui/web/frontend/src/components/society/office/officeNav.test.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/officeNav.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { allDesks, buildOfficeLayout, seatOf, standOf, type OfficeAgentInput, type OfficeLayout, type Point } from "./officeLayout";+import { allDesks, buildOfficeLayout, seatOf, standOf, type OfficeAgentInput, type OfficeLayout, type OfficeTeamInput, type Point } from "./officeLayout";import { buildNavGrid, findPath, hasLineOfSight, isWalkable, nearestWalkable, randomWalkablePoint, type NavGrid } from "./officeNav";import { createRng } from "./officeBehavior";@@ -12,6 +12,13 @@ function roster(count: number): OfficeAgentInput[] {}));}+/** `count` teams of `size` staff agents each (a0 is the lead), oldest first. */+function teamsOf(count: number, size: number): OfficeTeamInput[] {+ return Array.from({ length: count }, (_, t) => ({+ id: `team-${t}`, name: `Team ${t}`, createdMs: t, members: Array.from({ length: size }, (_, i) => `a${1 + t * size + i}`),+ }));+}+function targetsOf(layout: OfficeLayout): { name: string; p: Point }[] {return [...allDesks(layout).flatMap((d) => [{ name: `seat ${d.id}`, p: seatOf(d) }, { name: `stand ${d.id}`, p: standOf(d) }]),@@ -76,6 +83,35 @@ describe("office navigation", () => {});}+ // The agents floor is built from its teams: every studio's seats, huddle places and board must be reachable too.+ const TEAM_CASES: [string, number, OfficeTeamInput[]][] = [+ ["one team", 10, teamsOf(1, 4)],+ ["three teams", 16, teamsOf(3, 4)],+ ["eight teams", 40, teamsOf(8, 4)],+ ["teams of two and of twelve", 20, [...teamsOf(1, 12), { id: "duo", name: "Duo", createdMs: 99, members: ["a13", "a14"] }]],+ ["an agent in two teams and a team of unknown ids", 9, [+ { id: "x", name: "X", createdMs: 1, members: ["a1", "a2", "a3"] }, { id: "y", name: "Y", createdMs: 2, members: ["a3", "a4"] },+ { id: "ghosts", name: "Ghosts", createdMs: 3, members: ["nobody-1", "nobody-2"] },+ ]],+ ];+ for (const [name, count, teams] of TEAM_CASES) {+ it(`reaches every seat, spot and checkpoint of a team campus from the spawn and the elevator (${name})`, () => {+ const layout = buildOfficeLayout(roster(count), { teams });+ expect(layout.studios).toHaveLength(teams.length + 1);+ const grid = buildNavGrid(layout);+ const elevator = layout.checkpoints.find((c) => c.id === "elevator")!;+ for (const start of [layout.spawn, elevator]) {+ expect(isWalkable(grid, start)).toBe(true);+ for (const { name: target, p } of targetsOf(layout)) {+ const path = findPath(grid, start, p);+ if (!path) throw new Error(`${target} at ${p.x.toFixed(2)},${p.z.toFixed(2)} is unreachable`);+ if (path.length === 0) continue;+ assertClearPath(grid, start, p, path, target);+ }+ }+ });+ }+it("blocks obstacles and everything outside the floor", () => {const layout = buildOfficeLayout(roster(4));const grid = buildNavGrid(layout);@@ -92,7 +128,7 @@ describe("office navigation", () => {it("has no line of sight through a desk row", () => {const layout = buildOfficeLayout(roster(4));const grid = buildNavGrid(layout);- const desk = allDesks(layout).find((d) => d.id.startsWith("dept-0:0:south"))!;+ const desk = allDesks(layout).find((d) => d.id.includes(":0:south:"))!;const seat = seatOf(desk);const across = { x: seat.x, z: desk.z + 2 };expect(hasLineOfSight(grid, seat, across)).toBe(false);diff --git a/jarvis/ui/web/frontend/src/components/society/office/officePalette.ts b/jarvis/ui/web/frontend/src/components/society/office/officePalette.tsindex db4b83dcf8..9268a65f0e 100644--- a/jarvis/ui/web/frontend/src/components/society/office/officePalette.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/officePalette.ts@@ -62,6 +62,13 @@ export const DEPARTMENT_ZONES = [{ rug: "#e2cbc0", panel: "#c48e7a", seat: "#b0705b" },{ rug: "#c6c1d5", panel: "#918aad", seat: "#766e96" },{ rug: "#b8d0c9", panel: "#6f9f94", seat: "#528579" },+ // The agents floor's campus holds up to twelve studios: mustard, rose, sky, olive, cocoa and indigo follow.+ { rug: "#e2d3a2", panel: "#c2a24c", seat: "#a8873a" },+ { rug: "#d8bfc7", panel: "#b0728a", seat: "#955a72" },+ { rug: "#b5cbd8", panel: "#5e93b0", seat: "#467a96" },+ { rug: "#cbcfa6", panel: "#92975a", seat: "#787d44" },+ { rug: "#d5c0b0", panel: "#a67a5e", seat: "#8b624a" },+ { rug: "#bbc2d5", panel: "#6d7aac", seat: "#566392" },] as const;/** Rug tints per department (kept for callers that only need the floor colour). */@@ -183,34 +190,51 @@ export const ROOM_FLOOR_COLOURS = {levels: { base: "#e7e0d0", accents: ["#e7e0d0", "#2b2d33", "#bdb3a0", "#b8964f"] },} as const;+/**+ * The agents floor's rooms take their floors from the campus's own finishes instead: the plank oak of the open+ * floor (break room), the same oak a tone deeper and laid as a chevron (lead office), the limestone of the window+ * band (lobby, and as terrazzo with oak and stone chips in the wardrobe) and the slate felt of the focus booths+ * (team room). One floor family from the studios to the last room.+ */+export const CAMPUS_ROOM_FLOORS = {+ lead: { base: "#a98a64", accents: ["#b08f69", "#9f805b", "#a98964", "#b89872", "#967752"] },+ team: { base: "#c3cbd3", accents: ["#bac3cc", "#cbd2d9", "#bfc7cf"] },+ wardrobe: { base: "#e7e0d4", accents: ["#d3cabb", "#c9ad8c", "#b9b0a3", "#efe9df"] },+ reception: { base: "#e7e0d4", accents: ["#ddd5c7", "#efe9df", "#e2dace"] },+ break: { base: "#dcc6a1", accents: ["#e4d0ae", "#dcc6a1", "#e9d8ba", "#d8bf98"] },+} as const;+/** Checkpoint gold: floor ring, hexagon token and the label badge. */export const CHECKPOINT_GOLD = { ring: "#f5b83d", rim: "#e0a02a", face: "#f7c65a", faceDeep: "#e39b1f", icon: "#ffffff" } as const;/**- * The lead office's executive suite: dark walnut, brass, oxblood leather and a- * navy rug. Brass is the one deliberately metallic material outside the- * railings, so the boss's room reads as the most precious place on the floor.+ * The lead office's executive suite, in the campus's own materials a tone+ * deeper: smoked oak, bronze, cognac leather and a slate rug. (The keys keep+ * the names the suite was built with: `walnut*` is its timber, `brass` its+ * metal.) Bronze is the one metallic accent beside the floor's dark steel, so+ * the boss's room reads as the most precious place on the floor without+ * leaving its family.*/export const LEAD_SUITE = {- walnut: "#5b3a25",- walnutDark: "#3a2416",- walnutLight: "#80583a",- brass: "#d8ae52",- leather: "#7a2c22",- leatherDark: "#4e1a14",- leatherTan: "#a9683c",- velvetGold: "#d9a441",+ walnut: "#8b6b4a",+ walnutDark: "#6a4f37",+ walnutLight: "#ad8a63",+ brass: "#b08d5c",+ leather: "#8e5a3a",+ leatherDark: "#6b4129",+ leatherTan: "#b98558",+ velvetGold: "#c9a25a",chrome: "#c9ced6",blackGlass: "#12141a",marble: "#eeeae3",led: "#ffd08a",lampGlass: "#2f7a4f",shade: "#fff0d2",- backlight: "#8a5a36",+ backlight: "#a07a52",glass: "#e8d3a8",- rug: { field: "#1d2744", inner: "#26335a", border: "#c9a24a", accent: "#8f2f3a" },+ rug: { field: "#39414d", inner: "#48515e", border: "#b08d5c", accent: "#8e5a3a" },globe: { ocean: "#5f8f96", land: "#e2cd98", line: "#3d5c61" },bottles: ["#b8661e", "#4f7a3a", "#d9e6ea", "#8c2a2a", "#c79a3a"],trophy: "#e8b949",- dog: { basket: "#6d4a33", cushion: "#8f2f3a" },+ dog: { basket: "#8b6b4a", cushion: "#8e5a3a" },} as const;diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeSettings.ts b/jarvis/ui/web/frontend/src/components/society/office/officeSettings.tsindex 5805006a56..22081da8cc 100644--- a/jarvis/ui/web/frontend/src/components/society/office/officeSettings.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/officeSettings.ts@@ -8,11 +8,11 @@ import { create } from "zustand";export interface OfficeSettings {/** Walk at sprint pace by default; Shift then slows to a walk. */alwaysRun: boolean;- /** Show the one-line controls reminder at the bottom of the map. */- showHintBar: boolean;+ /** The first-visit control hints were dismissed; they stay away until the person asks for them again. */+ hintsSeen: boolean;}-export const DEFAULT_OFFICE_SETTINGS: OfficeSettings = { alwaysRun: false, showHintBar: true };+export const DEFAULT_OFFICE_SETTINGS: OfficeSettings = { alwaysRun: false, hintsSeen: false };const STORAGE_KEY = "jarvis.office.settings.v1";@@ -20,10 +20,11 @@ export function loadOfficeSettings(): OfficeSettings {try {const raw = typeof localStorage === "undefined" ? null : localStorage.getItem(STORAGE_KEY);if (!raw) return { ...DEFAULT_OFFICE_SETTINGS };- const parsed = JSON.parse(raw) as Partial<OfficeSettings>;+ const parsed = JSON.parse(raw) as Partial<OfficeSettings> & { showHintBar?: unknown };return {alwaysRun: typeof parsed.alwaysRun === "boolean" ? parsed.alwaysRun : DEFAULT_OFFICE_SETTINGS.alwaysRun,- showHintBar: typeof parsed.showHintBar === "boolean" ? parsed.showHintBar : DEFAULT_OFFICE_SETTINGS.showHintBar,+ // Someone who had switched the old permanent hint bar off has seen the hints.+ hintsSeen: typeof parsed.hintsSeen === "boolean" ? parsed.hintsSeen : parsed.showHintBar === false,};} catch (error) {// Blocked or corrupt storage: the defaults are a complete, working set.@@ -50,8 +51,8 @@ export const useOfficeSettings = create<OfficeSettingsState>((set, get) => ({...loadOfficeSettings(),set: (patch) => {set(patch);- const { alwaysRun, showHintBar } = get();- saveOfficeSettings({ alwaysRun, showHintBar });+ const { alwaysRun, hintsSeen } = get();+ saveOfficeSettings({ alwaysRun, hintsSeen });},reset: () => {set({ ...DEFAULT_OFFICE_SETTINGS });@@ -65,9 +66,9 @@ export function isRunning(shiftHeld: boolean, alwaysRun: boolean): boolean {}/** The reception's tabs; H opens reception on the controls tab from anywhere. */-export type ReceptionTab = "welcome" | "controls" | "settings";+export type ReceptionTab = "agents" | "places" | "controls" | "settings";export const useReceptionTab = create<{ tab: ReceptionTab; setTab: (tab: ReceptionTab) => void }>((set) => ({- tab: "welcome",+ tab: "agents",setTab: (tab) => set({ tab }),}));diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeStore.ts b/jarvis/ui/web/frontend/src/components/society/office/officeStore.tsindex a067de3ae7..0eb1e75f1a 100644--- a/jarvis/ui/web/frontend/src/components/society/office/officeStore.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/officeStore.ts@@ -8,16 +8,21 @@import { create } from "zustand";import type { CheckpointKind, Point } from "./officeLayout";-/** `arcade` is a playable arcade cabinet, by furniture id. */-export type Selection = { kind: "agent"; id: string } | { kind: "checkpoint"; id: CheckpointKind } | { kind: "arcade"; id: string };+/**+ * `arcade` is a playable arcade cabinet, by furniture id. `team` is a team studio's board, by its+ * `Studio.board.id` (`studio-board:<deptId>`); the stage resolves the team through `layout.studios`.+ */+export type Selection = { kind: "agent"; id: string } | { kind: "checkpoint"; id: CheckpointKind } | { kind: "arcade"; id: string }+ | { kind: "team"; id: string };/**- * The floors of the building, bottom to top: the Jarvis agents office, the- * coding agents one elevator ride up, and the arcade hall on the top floor.+ * The floors of the building, bottom to top: the Jarvis agents' campus, the+ * coding agents one elevator ride up, the arcade hall, and the Level Hall on+ * the top floor.*/-export type OfficeFloor = "agents" | "coding" | "arcade";+export type OfficeFloor = "agents" | "coding" | "arcade" | "hall";-export const OFFICE_FLOORS: readonly OfficeFloor[] = ["agents", "coding", "arcade"];+export const OFFICE_FLOORS: readonly OfficeFloor[] = ["agents", "coding", "arcade", "hall"];/** The floor number shown in the elevator (0 = ground floor). */export function floorLevel(floor: OfficeFloor): number {@@ -35,7 +40,11 @@ export interface Summon {}/** A team meeting at the team-room table; its members hold summons with a chair each until it ends. */-export interface TeamMeeting { groupId: string; name: string; members: string[]; untilMs: number }+export interface TeamMeeting {+ groupId: string; name: string; members: string[]; untilMs: number;+ /** The studio board the team gathers at (`Studio.board.id`); absent = the team room's table. */+ boardId?: string;+}interface OfficeState {/** The floor on screen; lives here so leaving the map and coming back keeps it. */@@ -49,6 +58,9 @@ interface OfficeState {selection: Selection | null;/** The closest thing the character can interact with (E), or null. */nearby: Selection | null;+ /** What the pointer rests on in the world (a station's object, an agent), or null. */+ hover: Selection | null;+ setHover: (hover: Selection | null) => void;/** Camera follows the character; any manual pan turns it off, moving turns it back on. */follow: boolean;/** One-shot camera fly-to request, consumed by the camera rig. */@@ -75,6 +87,8 @@ interface OfficeState {toggleDraft: (agentId: string) => void;clearDraft: () => void;clearSummons: () => void;+ /** Let these agents go back to their day; other calls and a running meeting stay. */+ release: (agentIds: readonly string[]) => void;select: (selection: Selection | null) => void;setNearby: (nearby: Selection | null) => void;setFollow: (follow: boolean) => void;@@ -91,10 +105,12 @@ let seq = 0;export const useOfficeStore = create<OfficeState>((set) => ({floor: "agents",setFloor: (floor) => set((s) => (s.floor === floor ? s : {- floor, selection: null, nearby: null, summons: {}, meeting: null, walkTo: null, zoom: null, sectionDive: null, focus: null, teamDraft: [], follow: true,+ floor, selection: null, nearby: null, hover: null, summons: {}, meeting: null, walkTo: null, zoom: null, sectionDive: null, focus: null, teamDraft: [], follow: true,})),selection: null,nearby: null,+ hover: null,+ setHover: (hover) => set((s) => (sameSelection(s.hover, hover) ? s : { hover })),follow: true,focus: null,summons: {},@@ -124,6 +140,10 @@ export const useOfficeStore = create<OfficeState>((set) => ({})),clearDraft: () => set({ teamDraft: [] }),clearSummons: () => set({ summons: {}, meeting: null }),+ release: (agentIds) => set((s) => {+ const gone = new Set(agentIds);+ return { summons: Object.fromEntries(Object.entries(s.summons).filter(([id]) => !gone.has(id))) };+ }),select: (selection) => set({ selection }),setNearby: (nearby) => set((s) => (sameSelection(s.nearby, nearby) ? s : { nearby })),setFollow: (follow) => set((s) => (s.follow === follow ? s : { follow })),diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeTeams.test.ts b/jarvis/ui/web/frontend/src/components/society/office/officeTeams.test.tsnew file mode 100644index 0000000000..f8c0ae6121--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/officeTeams.test.ts@@ -0,0 +1,123 @@+import { describe, expect, it } from "vitest";+import { allDesks, chairRect, deskRect, seatOf, type DeskSlot, type Point, type Rect } from "./officeLayout";+import { type Mover } from "./officeMotion";+import { isWalkable } from "./officeNav";+import { PERSON_CLEAR_M, standingPlaceFor } from "./officeTeams";+import { advanceWalk, beginWalk } from "./officeWalk";+import { SEAT_REACH } from "./leadSeat";+import { campusOf } from "./officeFixtures";++// Fourteen agents, a team of five and a team of four; everybody sits at their desk.+const campus = campusOf(14, [5, 4]);+const benchDesks = allDesks(campus.layout).filter((d) => !d.size);+const occupied = benchDesks.filter((d) => d.agentId);+const seated: Point[] = occupied.map((d) => { const seat = seatOf(d); return { x: seat.x, z: seat.z }; });+const inside = (rect: Rect, p: Point) => p.x > rect.minX && p.x < rect.maxX && p.z > rect.minZ && p.z < rect.maxZ;++/** A place the person may stand on: floor, outside every chair and desk, and beside everybody rather than in them. */+function expectStandingPlace(place: Point | null, label: string): asserts place is Point {+ expect(place, label).not.toBeNull();+ expect(isWalkable(campus.grid, place!), label).toBe(true);+ for (const desk of benchDesks) {+ expect(inside(chairRect(seatOf(desk)), place!), `${label} in the chair of ${desk.id}`).toBe(false);+ expect(inside(deskRect(desk), place!), `${label} in the desk ${desk.id}`).toBe(false);+ }+ for (const body of seated) expect(Math.hypot(body.x - place!.x, body.z - place!.z), label).toBeGreaterThanOrEqual(PERSON_CLEAR_M);+}++/** Walk the person's character to wherever a click on \`goal\` resolves, as OfficePlayer does; returns where it ends. */+function clickAndWalk(goal: Point, from: Point = campus.layout.spawn): Point {+ const place = standingPlaceFor(campus.layout, campus.grid, goal, seated)!;+ const m: Mover = { x: from.x, z: from.z, heading: 0, path: [] };+ const walk = beginWalk(campus.grid, m, place, seated)!;+ for (let i = 0; i < 60 * 240; i += 1) {+ const step = advanceWalk(walk, m, campus.grid, 1 / 60, seated, { speed: 2, place: false });+ if (step.arrived || step.event === "blocked" || step.event === "lost") break;+ }+ return { x: m.x, z: m.z };+}++describe("where a click sends the person", () => {+ it("is the clicked point itself on free floor", () => {+ const goal = campus.layout.arrival;+ expect(standingPlaceFor(campus.layout, campus.grid, goal, seated)).toEqual({ x: goal.x, z: goal.z });+ });++ it("is a place beside the chair for a click on a seated agent, never the chair or the agent", () => {+ for (const desk of occupied) {+ const seat = seatOf(desk);+ // On the figure, a little off its centre, as a click on it lands.+ for (const goal of [{ x: seat.x + 0.3, z: seat.z + 0.2 }, { x: seat.x, z: seat.z }, { x: seat.x - 0.2, z: seat.z - 0.1 }]) {+ const place = standingPlaceFor(campus.layout, campus.grid, goal, seated);+ expectStandingPlace(place, desk.id);+ // Beside this desk, within a step or two of what was clicked.+ expect(Math.hypot(place.x - seat.x, place.z - seat.z), desk.id).toBeLessThan(1.4);+ }+ }+ });++ it("walks there and ends beside the seated agent, on its feet", () => {+ for (const desk of occupied.slice(0, 6)) {+ const seat = seatOf(desk);+ const end = clickAndWalk({ x: seat.x + 0.3, z: seat.z + 0.2 });+ expectStandingPlace(end, desk.id);+ expect(Math.hypot(end.x - seat.x, end.z - seat.z), desk.id).toBeLessThan(1.4);+ }+ });++ it("is a place at the desk for a click on a desk top", () => {+ for (const desk of benchDesks.slice(0, 10)) {+ const place = standingPlaceFor(campus.layout, campus.grid, { x: desk.x + 0.1, z: desk.z }, seated);+ expectStandingPlace(place, desk.id);+ expect(Math.hypot(place.x - desk.x, place.z - desk.z), desk.id).toBeLessThan(2.2);+ expectStandingPlace(clickAndWalk({ x: desk.x + 0.1, z: desk.z }), desk.id);+ }+ });++ it("does not sit the person on an empty chair either: it stands beside it", () => {+ const empty: DeskSlot[] = benchDesks.filter((d) => !d.agentId);+ expect(empty.length).toBeGreaterThan(0);+ for (const desk of empty) {+ const seat = seatOf(desk);+ const place = standingPlaceFor(campus.layout, campus.grid, { x: seat.x, z: seat.z }, seated);+ expectStandingPlace(place, desk.id);+ expect(Math.hypot(place.x - seat.x, place.z - seat.z), desk.id).toBeGreaterThan(0.5);+ expect(Math.hypot(place.x - seat.x, place.z - seat.z), desk.id).toBeLessThan(1.4);+ expectStandingPlace(clickAndWalk({ x: seat.x, z: seat.z }), desk.id);+ }+ });++ it("steps aside when a visitor already stands in the place beside the chair", () => {+ const desk = occupied[0];+ const seat = seatOf(desk);+ const first = standingPlaceFor(campus.layout, campus.grid, seat, seated)!;+ const second = standingPlaceFor(campus.layout, campus.grid, seat, [...seated, first]);+ expectStandingPlace(second, desk.id);+ expect(Math.hypot(second.x - first.x, second.z - first.z)).toBeGreaterThanOrEqual(PERSON_CLEAR_M);+ });++ it("stops beside a standing agent instead of in it", () => {+ const agent = campus.layout.arrival;+ const place = standingPlaceFor(campus.layout, campus.grid, { x: agent.x + 0.1, z: agent.z }, [agent])!;+ expect(isWalkable(campus.grid, place)).toBe(true);+ expect(Math.hypot(place.x - agent.x, place.z - agent.z)).toBeGreaterThanOrEqual(PERSON_CLEAR_M);+ expect(Math.hypot(place.x - agent.x, place.z - agent.z)).toBeLessThan(1.3);+ });++ it("still brings the person within reach of the lead's chair, which has its own sit action", () => {+ for (const desk of campus.layout.lead.desks) {+ const seat = seatOf(desk);+ const place = standingPlaceFor(campus.layout, campus.grid, seat, seated)!;+ expect(isWalkable(campus.grid, place)).toBe(true);+ expect(Math.hypot(place.x - seat.x, place.z - seat.z)).toBeLessThanOrEqual(SEAT_REACH);+ }+ });++ it("finds floor beside any piece of furniture that was clicked", () => {+ for (const item of campus.layout.furniture.slice(0, 40)) {+ const place = standingPlaceFor(campus.layout, campus.grid, { x: item.x, z: item.z }, seated);+ expect(place, item.id).not.toBeNull();+ expect(isWalkable(campus.grid, place!), item.id).toBe(true);+ }+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeTeams.ts b/jarvis/ui/web/frontend/src/components/society/office/officeTeams.tsnew file mode 100644index 0000000000..6784229d96--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/officeTeams.ts@@ -0,0 +1,220 @@+/**+ * Where an agent belongs on the agents floor: its team's studio, the places+ * round the studio board, and where a visitor stands at a teammate's desk.+ *+ * Studios come from the floor plan (`layout.studios`); a floor without them+ * (the coding floor, the arcade) simply has no homes, and every caller keeps+ * its studio-less behaviour. Pure.+ */+import { chairRect, DESK_PITCH_X, deskRect, seatOf, type DeskSlot, type OfficeLayout, type Point, type Rect, type Studio } from "./officeLayout";+import { clearOfBodies } from "./officeMotion";+import { isWalkable, nearestWalkable, type NavGrid } from "./officeNav";++/** A place a figure can stand on that the floor plan does not list as a spot; reserved through the same book by its id. */+export interface Place extends Point { id: string; facing: number }++interface StudioIndex {+ studios: readonly Studio[];+ byAgent: Map<string, Studio>;+ byDept: Map<string, Studio>;+ byTeam: Map<string, Studio>;+ deptOfDesk: Map<string, string>;+}++const indexCache = new WeakMap<OfficeLayout, StudioIndex>();++function indexOf(layout: OfficeLayout): StudioIndex {+ let index = indexCache.get(layout);+ if (!index) {+ const studios = layout.studios ?? [];+ index = {+ studios,+ byAgent: new Map(studios.flatMap((s) => s.members.map((id) => [id, s] as const))),+ byDept: new Map(studios.map((s) => [s.deptId, s])),+ byTeam: new Map(studios.filter((s) => s.teamId !== null).map((s) => [s.teamId as string, s])),+ deptOfDesk: new Map(layout.departments.flatMap((d) => d.desks.map((desk) => [desk.id, d.id] as const))),+ };+ indexCache.set(layout, index);+ }+ return index;+}++/** The floor's studios; empty where the floor plan has none. */+export function studiosOf(layout: OfficeLayout): readonly Studio[] {+ return indexOf(layout).studios;+}++/** The studio an agent belongs to: the one that lists it, else the one its desk stands in. Null without studios. */+export function homeStudio(layout: OfficeLayout, agentId: string, desk: Pick<DeskSlot, "id"> | null): Studio | null {+ const index = indexOf(layout);+ if (index.studios.length === 0) return null;+ const listed = index.byAgent.get(agentId);+ if (listed) return listed;+ const dept = desk ? index.deptOfDesk.get(desk.id) : undefined;+ return dept ? index.byDept.get(dept) ?? null : null;+}++export function studioOfTeam(layout: OfficeLayout, teamId: string): Studio | null {+ return indexOf(layout).byTeam.get(teamId) ?? null;+}++/** The studio's floor: its department's rectangle, or a square round its centre when the department is gone. */+export function studioRect(layout: OfficeLayout, studio: Studio): Rect {+ const dept = layout.departments.find((d) => d.id === studio.deptId);+ if (dept) return { minX: dept.minX, maxX: dept.maxX, minZ: dept.minZ, maxZ: dept.maxZ };+ return { minX: studio.centre.x - 4, maxX: studio.centre.x + 4, minZ: studio.centre.z - 4, maxZ: studio.centre.z + 4 };+}++/** The desks of an agent's studio mates (everyone seated in the same studio, itself excluded). */+export function mateDesks(layout: OfficeLayout, studio: Studio, agentId: string): DeskSlot[] {+ const dept = layout.departments.find((d) => d.id === studio.deptId);+ if (!dept) return [];+ const members = new Set(studio.members);+ return dept.desks.filter((d) => d.agentId !== null && d.agentId !== agentId && members.has(d.agentId));+}++/**+ * Where a visitor stands relative to the chair: in the middle of the gap to the next chair, east or west, a+ * small step back from the chairs' line (the desk's clearance reaches just past that line). There it is out of+ * the aisle behind the chairs, which stays free for everyone walking to a seat, and out of the way the seated+ * colleague gets up (straight back), even with a visitor on either side.+ */+const VISIT_SIDE_M = DESK_PITCH_X / 2;+const VISIT_BACK_M = 0.3;++/**+ * Where visitors stand at a desk: between its chair and the next one, east+ * and west. Only places on walkable ground count. The gap between two chairs+ * belongs to both desks, so a place's id is its position (`visit:<x>,<z>`):+ * the visitors of two neighbouring desks can never be given the same patch of+ * floor. A place is a step from where the owner of the desk to its west stands+ * while it waits for the person; that owner holds the place meanwhile, and+ * callers skip one somebody already stands at.+ */+export function visitSlots(desk: DeskSlot, grid: NavGrid): Place[] {+ const seat = seatOf(desk);+ // Behind the chair is away from the desk.+ const back = desk.facing === "north" ? 1 : -1;+ const candidates: Point[] = [+ { x: seat.x + VISIT_SIDE_M, z: seat.z + back * VISIT_BACK_M },+ { x: seat.x - VISIT_SIDE_M, z: seat.z + back * VISIT_BACK_M },+ ];+ return candidates.flatMap((p) => (isWalkable(grid, p)+ ? [{ id: `visit:${p.x.toFixed(2)},${p.z.toFixed(2)}`, x: p.x, z: p.z, facing: Math.atan2(seat.x - p.x, seat.z - p.z) }]+ : []));+}++/** The person's character keeps this far from everybody when a click sends it somewhere: beside a figure, never in it. */+export const PERSON_CLEAR_M = 0.75;+/** A click this close to a bench desk's chair or top means that desk. */+const DESK_CLICK_MARGIN_M = 0.3;+/** How far behind a chair the person stands when both places beside it are taken. */+const BEHIND_CHAIR_M = 1.0;++function within(rect: Rect, p: Point, margin: number): boolean {+ return p.x >= rect.minX - margin && p.x <= rect.maxX + margin && p.z >= rect.minZ - margin && p.z <= rect.maxZ + margin;+}++/**+ * Where the person's character stands when a click (or "walk there") names+ * `goal`. Free floor is the goal itself. A click on a bench desk, on its+ * chair or on whoever sits there resolves to a standing place at that desk:+ * beside the chair where a visiting colleague would stand, else behind it.+ * Anything else solid or occupied (a couch, a counter, a standing agent)+ * resolves to the nearest free floor beside it. The person never ends up on a+ * chair, in a desk or inside a figure; taking a seat is its own action (the+ * executive chair and Mission Control's chair have one).+ *+ * `bodies` are everybody else's positions. Null only when there is no floor+ * within reach at all.+ */+export function standingPlaceFor(layout: OfficeLayout, grid: NavGrid, goal: Point, bodies: readonly Point[]): Point | null {+ const free = (p: Point) => isWalkable(grid, p) && clearOfBodies(p, bodies, PERSON_CLEAR_M);+ if (free(goal)) return { x: goal.x, z: goal.z };+ const nearest = (candidates: readonly Point[]): Point | null => candidates.filter(free)+ .reduce<Point | null>((best, p) => (!best || Math.hypot(p.x - goal.x, p.z - goal.z) < Math.hypot(best.x - goal.x, best.z - goal.z) ? p : best), null);++ // A bench desk (sittable desks carry a size and keep their own sit action).+ const desk = layout.departments.flatMap((d) => d.desks)+ .filter((d) => within(deskRect(d), goal, DESK_CLICK_MARGIN_M) || within(chairRect(seatOf(d)), goal, DESK_CLICK_MARGIN_M))+ .reduce<DeskSlot | null>((best, d) => {+ const seat = seatOf(d);+ return !best || Math.hypot(seat.x - goal.x, seat.z - goal.z) < Math.hypot(seatOf(best).x - goal.x, seatOf(best).z - goal.z) ? d : best;+ }, null);+ if (desk) {+ const seat = seatOf(desk);+ const back = desk.facing === "north" ? 1 : -1;+ const beside = nearest([...visitSlots(desk, grid), { x: seat.x, z: seat.z + back * BEHIND_CHAIR_M }]);+ if (beside) return { x: beside.x, z: beside.z };+ }+ // The nearest floor to the goal, when nobody is in the way there (the executive chair is sat on from it).+ const cell = nearestWalkable(grid, goal, 1.2);+ if (cell && free(cell)) return cell;+ // Else the nearest free floor round the goal, ring by ring.+ for (let radius = 0.2; radius <= 3.01; radius += 0.2) {+ const ring: Point[] = [];+ for (let i = 0; i < 16; i += 1) {+ const angle = (i / 16) * Math.PI * 2;+ ring.push({ x: goal.x + Math.sin(angle) * radius, z: goal.z + Math.cos(angle) * radius });+ }+ const found = nearest(ring);+ if (found) return found;+ }+ // Crowded all round: free ground at least; the walk stops beside whoever stands there.+ return nearestWalkable(grid, goal);+}++/**+ * The arcs a team stands in at its board: each row's distance from the board+ * and the angles (degrees off the board's centre line) of its places. Every+ * place is more than a metre from its neighbours in the row and from the rows+ * before and behind it, so name plates and bubbles stay apart and the person+ * can walk in between. The first row is a conversation's distance from the+ * board; the rows behind it look over its shoulders (the angles interleave).+ */+export const HUDDLE_ARCS: readonly { radius: number; angles: readonly number[] }[] = [+ { radius: 2.2, angles: [-14, 14, -42, 42] },+ { radius: 3.3, angles: [0, -20, 20, -40, 40, -60, 60] },+ { radius: 4.4, angles: [-7.5, 7.5, -22.5, 22.5, -37.5, 37.5] },+];+/**+ * The lead's place in a gathering at the board: the place of the front arc+ * nearest the board's centre line. Null for a studio without a lead (then the+ * arcs have no special place at all) or without a walkable front arc.+ */+export function leadPlace(places: readonly Place[], studio: Pick<Studio, "deptId" | "leadId" | "board">): Place | null {+ const board = studio.board;+ if (!studio.leadId || !board) return null;+ const front = places.filter((p) => p.id.startsWith(`fan:${studio.deptId}:0:`));+ // How far to the side of the board's centre line a place lies.+ const aside = (p: Place) => Math.abs((p.x - board.x) * Math.cos(board.facing) - (p.z - board.z) * Math.sin(board.facing));+ return front.reduce<Place | null>((best, p) => (!best || aside(p) < aside(best) - 1e-6 ? p : best), null);+}++/** The least two places of the arcs are apart; the tests hold the geometry to it. */+export const HUDDLE_SPACE_M = 1.05;++/**+ * Everywhere a team can stand at its board: loose arcs round it, each place+ * facing the board (ids `fan:<deptId>:<row>:<n>`), the row nearest the board+ * first. Only places on walkable ground count. Empty for a studio without a+ * board. The floor plan's own huddle spots mark where the huddle is; the arcs+ * are where people actually stand, with room between them.+ */+export function huddlePlaces(_layout: OfficeLayout, grid: NavGrid, studio: Studio): Place[] {+ if (!studio.board) return [];+ const { x: bx, z: bz, facing } = studio.board;+ const nx = Math.sin(facing), nz = Math.cos(facing);+ // The board's own right-hand direction on the floor.+ const tx = nz, tz = -nx;+ const places: Place[] = [];+ HUDDLE_ARCS.forEach((arc, row) => {+ arc.angles.forEach((degrees, n) => {+ const a = (degrees * Math.PI) / 180;+ const along = Math.cos(a) * arc.radius, across = Math.sin(a) * arc.radius;+ const p = { x: bx + nx * along + tx * across, z: bz + nz * along + tz * across };+ if (isWalkable(grid, p)) places.push({ id: `fan:${studio.deptId}:${row}:${n}`, x: p.x, z: p.z, facing: Math.atan2(bx - p.x, bz - p.z) });+ });+ });+ return places;+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeWalk.test.ts b/jarvis/ui/web/frontend/src/components/society/office/officeWalk.test.tsnew file mode 100644index 0000000000..fd7476a641--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/officeWalk.test.ts@@ -0,0 +1,312 @@+import { describe, expect, it } from "vitest";+import type { Point } from "./officeLayout";+import { BODY_SPACING, BRISK_SPEED, WALK_SPEED, wrapAngle, type Mover } from "./officeMotion";+import { findPath, isWalkable, type NavGrid } from "./officeNav";+import { advanceWalk, beginWalk, findDetour, pathLength, PLACE_WITHIN_M, routeMarks, safePlacement, type Walk, type WalkEvent } from "./officeWalk";+import { campusOf, roomGrid, wallWithDoor } from "./officeFixtures";++const DT = 1 / 60;++interface Trace { seconds: number; events: WalkEvent[]; offFloor: number; sideways: number; arrived: boolean }++/** Walk `m` to the end of `walk`, checking every frame that it stays on the floor and faces where it goes. */+function walkThrough(walk: Walk, m: Mover, grid: () => NavGrid, bodies: () => Point[], limitS = 400, options: { place?: boolean; far?: boolean } = {}): Trace {+ const trace: Trace = { seconds: 0, events: [], offFloor: 0, sideways: 0, arrived: false };+ const start = { x: m.x, z: m.z };+ while (trace.seconds < limitS) {+ const before = { x: m.x, z: m.z };+ const step = advanceWalk(walk, m, grid(), DT, bodies(), options);+ trace.seconds += DT;+ if (step.event) trace.events.push(step.event);+ if (step.event !== "rescue" && step.moved > 1e-6) {+ // Metres covered while facing more than about 60° away from the direction of travel: gliding.+ const off = Math.abs(wrapAngle(Math.atan2(m.x - before.x, m.z - before.z) - m.heading));+ if (off > 1.05) trace.sideways += step.moved;+ // The first steps out of a seat and the last onto one cross its footprint; everything between is floor.+ const nearEnds = Math.hypot(m.x - start.x, m.z - start.z) < 1.2 || Math.hypot(m.x - walk.target.x, m.z - walk.target.z) < 1.2;+ if (!nearEnds && !isWalkable(grid(), m)) trace.offFloor += 1;+ }+ if (step.arrived) { trace.arrived = true; break; }+ if (step.event === "lost" || step.event === "blocked") break;+ }+ return trace;+}++const mover = (at: Point): Mover => ({ x: at.x, z: at.z, heading: Math.PI, path: [] });++describe("an agent's pace on real routes", () => {+ it("covers a route from the lobby to a desk at the walking pace or better, corners and all", () => {+ const { layout, grid } = campusOf(14, [5, 4]);+ const desks = layout.departments.flatMap((d) => d.desks).filter((d) => d.agentId);+ const seats = desks.map((d) => ({ x: d.x, z: d.facing === "north" ? d.z + 0.62 : d.z - 0.62 }));+ for (const [i, seat] of seats.entries()) {+ // Everybody else sits at their desk while this one walks in.+ const others = seats.filter((_, j) => j !== i);+ const m = mover(layout.spawn);+ const walk = beginWalk(grid, m, seat, others)!;+ const trace = walkThrough(walk, m, () => grid, () => others);+ expect(trace.arrived, `desk ${i}`).toBe(true);+ // Metres of route per second of the walker's own clock.+ expect(walk.length / trace.seconds, `desk ${i}`).toBeGreaterThan(WALK_SPEED);+ expect(walk.length / trace.seconds, `desk ${i}`).toBeLessThanOrEqual(BRISK_SPEED);+ }+ });+});++describe("a walk across the campus", () => {+ it("takes a long diagonal route across a large floor without leaving it, gliding or getting stuck", () => {+ const { layout, grid } = campusOf(60, [10, 9, 8, 7, 6, 6]);+ // The two hangout places furthest apart: one corner of the campus to the other.+ const spots = layout.spots.filter((s) => s.kind !== "huddle");+ const from = spots.reduce((a, b) => (a.x + a.z < b.x + b.z ? a : b));+ const to = spots.reduce((a, b) => (a.x + a.z > b.x + b.z ? a : b));+ const m = mover(from);+ const walk = beginWalk(grid, m, to)!;+ expect(walk).not.toBeNull();+ expect(walk.length).toBeGreaterThan(40);+ const trace = walkThrough(walk, m, () => grid, () => []);+ expect(trace.arrived).toBe(true);+ expect(m.x).toBe(to.x);+ expect(m.z).toBe(to.z);+ expect(trace.offFloor).toBe(0);+ expect(trace.sideways).toBeLessThan(0.2);+ expect(trace.events.filter((e) => e === "rescue" || e === "replan")).toEqual([]);+ // Brisk on the long legs: clearly faster than a stroll, never faster than the brisk pace allows.+ expect(trace.seconds).toBeLessThan(walk.length / WALK_SPEED);+ expect(trace.seconds).toBeGreaterThan(walk.length / BRISK_SPEED);+ });++ it("reaches every desk seat of a large floor exactly, from the lobby", () => {+ const { layout, grid } = campusOf(48, [8, 8, 8, 8]);+ for (const desk of layout.departments.flatMap((d) => d.desks).filter((d) => d.agentId).slice(0, 12)) {+ const seat = { x: desk.x, z: desk.facing === "north" ? desk.z + 0.62 : desk.z - 0.62 };+ const m = mover(layout.spawn);+ const walk = beginWalk(grid, m, seat)!;+ const trace = walkThrough(walk, m, () => grid, () => []);+ expect(trace.arrived, desk.id).toBe(true);+ expect([m.x, m.z], desk.id).toEqual([seat.x, seat.z]);+ expect(trace.offFloor, desk.id).toBe(0);+ }+ });+});++/**+ * Two figures walking towards each other's start, each with somewhere it has to be (as an agent going to its+ * screen): a walk given up is begun again from where it stands, and after two of those it may be placed.+ * Returns how close they came and how each walk ended.+ */+function swap(grid: NavGrid, a0: Point, b0: Point) {+ const a = mover(a0), b = mover(b0);+ const walks = { a: beginWalk(grid, a, b0)!, b: beginWalk(grid, b, a0)! };+ const givenUp = { a: 0, b: 0 };+ let closest = Infinity, seconds = 0, doneA = false, doneB = false;+ const events: WalkEvent[] = [];+ const stepOne = (who: "a" | "b", m: Mover, other: Mover, goal: Point): boolean => {+ const s = advanceWalk(walks[who], m, grid, DT, [other], { far: givenUp[who] >= 2 });+ if (s.event) events.push(s.event);+ if (s.event === "blocked") { givenUp[who] += 1; walks[who] = beginWalk(grid, m, goal, [other])!; }+ return s.arrived;+ };+ while (seconds < 120 && !(doneA && doneB)) {+ if (!doneA) doneA = stepOne("a", a, b, b0);+ if (!doneB) doneB = stepOne("b", b, a, a0);+ seconds += DT;+ if (!doneA && !doneB) closest = Math.min(closest, Math.hypot(a.x - b.x, a.z - b.z));+ expect(isWalkable(grid, a) && isWalkable(grid, b)).toBe(true);+ }+ return { a, b, closest, seconds, events, done: doneA && doneB };+}++describe("two walkers meeting head-on", () => {+ it("swap places through a door without touching, each passing on its right", () => {+ const grid = roomGrid(12, 8, wallWithDoor(6, 8, 4, 1.6));+ const result = swap(grid, { x: 2, z: 4 }, { x: 10, z: 4 });+ expect(result.done).toBe(true);+ expect([result.a.x, result.a.z]).toEqual([10, 4]);+ expect([result.b.x, result.b.z]).toEqual([2, 4]);+ expect(result.closest).toBeGreaterThan(BODY_SPACING - 0.03);+ expect(result.events).not.toContain("rescue");+ // No standing about: both are through in little more than the plain walking time.+ expect(result.seconds).toBeLessThan(8 / WALK_SPEED + 6);+ });++ it("pass each other in a narrow aisle", () => {+ // A 1.6 m aisle between two benches: 1.04 m of floor for the two of them.+ const grid = roomGrid(14, 1.6);+ const result = swap(grid, { x: 1, z: 0.8 }, { x: 13, z: 0.8 });+ expect(result.done).toBe(true);+ expect(result.closest).toBeGreaterThan(BODY_SPACING - 0.03);+ expect(result.events).not.toContain("rescue");+ });++ it("still both arrive where a door is too narrow for two: nobody is left standing in it", () => {+ const grid = roomGrid(12, 8, wallWithDoor(6, 8, 4, 1.0));+ const result = swap(grid, { x: 2, z: 4 }, { x: 10, z: 4 });+ expect(result.done).toBe(true);+ expect([result.a.x, result.a.z]).toEqual([10, 4]);+ expect([result.b.x, result.b.z]).toEqual([2, 4]);+ });+});++describe("a floor plan that changes under a walker", () => {+ it("finds the new way when a studio is built on its route, and still arrives exactly", () => {+ const before = campusOf(30, [6, 6]);+ const after = campusOf(30, [6, 6, 6, 6]);+ // A walk the new studios stand in the way of: across the studio rows, between two places both plans share.+ const from = before.layout.spawn;+ const to = before.layout.checkpoints.find((c) => c.id === "lead")!;+ expect(isWalkable(after.grid, to)).toBe(true);+ const m = mover(from);+ const walk = beginWalk(before.grid, m, to)!;+ let grid = before.grid;+ for (let i = 0; i < 6 / DT; i += 1) advanceWalk(walk, m, grid, DT, []);+ expect(m.path.length).toBeGreaterThan(0);+ grid = after.grid;+ const trace = walkThrough(walk, m, () => grid, () => []);+ expect(trace.events[0]).toBe("repath");+ expect(trace.arrived).toBe(true);+ expect([m.x, m.z]).toEqual([to.x, to.z]);+ expect(trace.offFloor).toBe(0);+ expect(walk.grid).toBe(after.grid);+ });++ it("reports a target the new plan walls off, instead of walking at a wall for ever", () => {+ const open = roomGrid(12, 8);+ const walled = roomGrid(12, 8, [{ minX: 5.9, maxX: 6.1, minZ: 0, maxZ: 8 }]);+ const m = mover({ x: 2, z: 4 });+ const walk = beginWalk(open, m, { x: 10, z: 4 })!;+ for (let i = 0; i < 60; i += 1) advanceWalk(walk, m, open, DT, []);+ const step = advanceWalk(walk, m, walled, DT, []);+ expect(step).toMatchObject({ arrived: false, event: "lost" });+ expect(m.path).toEqual([]);+ });+});++describe("a walker that stops getting anywhere", () => {+ it("takes a detour round people standing in its way", () => {+ const grid = roomGrid(12, 8);+ // Three people standing shoulder to shoulder across the straight line.+ const standing = [{ x: 6, z: 3.4 }, { x: 6, z: 4 }, { x: 6, z: 4.6 }];+ const m = mover({ x: 2, z: 4 });+ const walk = beginWalk(grid, m, { x: 10, z: 4 })!;+ let closest = Infinity;+ const trace = walkThrough(walk, m, () => grid, () => { closest = Math.min(closest, ...standing.map((b) => Math.hypot(b.x - m.x, b.z - m.z))); return standing; });+ expect(trace.arrived).toBe(true);+ expect([m.x, m.z]).toEqual([10, 4]);+ expect(closest).toBeGreaterThan(BODY_SPACING - 0.03);+ expect(trace.events).not.toContain("rescue");+ });++ it("plans a detour that avoids the bodies, and none where they close the only way", () => {+ const grid = roomGrid(12, 8);+ const direct = findPath(grid, { x: 2, z: 4 }, { x: 10, z: 4 })!;+ const round = findDetour(grid, { x: 2, z: 4 }, { x: 10, z: 4 }, [{ x: 6, z: 4 }])!;+ expect(pathLength({ x: 2, z: 4 }, round)).toBeGreaterThan(pathLength({ x: 2, z: 4 }, direct));+ // A corridor one body wide: whoever stands in it closes it.+ const corridor = roomGrid(12, 1.2);+ expect(findDetour(corridor, { x: 2, z: 0.6 }, { x: 10, z: 0.6 }, [{ x: 6, z: 0.6 }])).toBeNull();+ });++ it("is placed at a target a few steps away after two detours that did not help, and never before", () => {+ const corridor = roomGrid(12, 1.2);+ const blocker = [{ x: 6, z: 0.6 }];+ const m = mover({ x: 4.5, z: 0.6 });+ const target = { x: 7.3, z: 0.6 };+ const walk = beginWalk(corridor, m, target)!;+ const trace = walkThrough(walk, m, () => corridor, () => blocker);+ expect(trace.events).toEqual(["replan", "replan", "rescue"]);+ expect(trace.arrived).toBe(true);+ expect([m.x, m.z]).toEqual([target.x, target.z]);+ // Never through the person in the way: it waited in front of them until it was placed.+ expect(trace.seconds).toBeGreaterThan(4.5);+ expect(walk.rescues).toBe(1);+ });++ it("gives a walk up rather than being moved across the floor, unless it has to be there", () => {+ const corridor = roomGrid(12, 1.2);+ const blocker = [{ x: 6, z: 0.6 }];+ const m = mover({ x: 2, z: 0.6 });+ const walk = beginWalk(corridor, m, { x: 10, z: 0.6 })!;+ const trace = walkThrough(walk, m, () => corridor, () => blocker);+ expect(trace.events).toEqual(["replan", "replan", "blocked"]);+ expect(trace.arrived).toBe(false);+ // It stands where it was stopped, with no route left: its owner plans again from here.+ expect(m.x).toBeLessThan(6);+ expect(Math.hypot(10 - m.x, 0.6 - m.z)).toBeGreaterThan(PLACE_WITHIN_M);+ expect(m.path).toEqual([]);+ expect(walk.rescues).toBe(0);+ // An agent that must be there (its screen while it works) and failed twice is placed after all.+ const again = beginWalk(corridor, m, { x: 10, z: 0.6 })!;+ const insisted = walkThrough(again, m, () => corridor, () => blocker, 400, { far: true });+ expect(insisted.events).toEqual(["replan", "replan", "rescue"]);+ expect([m.x, m.z]).toEqual([10, 0.6]);+ });++ it("stops where it is instead of being placed when it is the person's own character", () => {+ const corridor = roomGrid(12, 1.2);+ const m = mover({ x: 4.5, z: 0.6 });+ const walk = beginWalk(corridor, m, { x: 7.3, z: 0.6 })!;+ const trace = walkThrough(walk, m, () => corridor, () => [{ x: 6, z: 0.6 }], 60, { place: false });+ expect(trace.events).toEqual(["replan", "replan", "blocked"]);+ expect(trace.arrived).toBe(false);+ // In front of the person in its way, at arm's length: not through them, and not at its target.+ expect(m.x).toBeLessThan(6);+ expect(Math.hypot(m.x - 6, m.z - 0.6)).toBeGreaterThan(BODY_SPACING - 0.01);+ expect(m.path).toEqual([]);+ });++ it("stops beside someone who stands on the place it was heading for", () => {+ const grid = roomGrid(12, 8);+ const squatter = [{ x: 9, z: 4 }];+ const m = mover({ x: 2, z: 4 });+ const walk = beginWalk(grid, m, { x: 9, z: 4 })!;+ const trace = walkThrough(walk, m, () => grid, () => squatter);+ expect(trace.arrived).toBe(true);+ expect(trace.events).toContain("near");+ const gap = Math.hypot(m.x - 9, m.z - 4);+ expect(gap).toBeGreaterThan(BODY_SPACING - 0.03);+ expect(gap).toBeLessThan(1.2);+ });++ it("ends a walk that keeps moving without ever arriving: placed when nearly there, given up when not", () => {+ const grid = roomGrid(12, 8);+ const far = mover({ x: 2, z: 4 });+ const long = beginWalk(grid, far, { x: 10, z: 4 })!;+ long.budgetS = 1;+ expect(walkThrough(long, far, () => grid, () => []).events).toEqual(["blocked"]);+ expect(far.x).toBeLessThan(5);+ const near = mover({ x: 8, z: 4 });+ const short = beginWalk(grid, near, { x: 10, z: 4 })!;+ short.budgetS = 0.5;+ expect(walkThrough(short, near, () => grid, () => []).events).toEqual(["rescue"]);+ expect([near.x, near.z]).toEqual([10, 4]);+ });+});++describe("safePlacement", () => {+ const grid = roomGrid(12, 8, [{ minX: 5, maxX: 7, minZ: 3, maxZ: 5 }]);+ it("is the seat itself for a place inside a footprint, the place when free, else free ground beside it", () => {+ expect(safePlacement(grid, { x: 6, z: 4 }, [{ x: 6, z: 4.4 }])).toEqual({ x: 6, z: 4 });+ expect(safePlacement(grid, { x: 2, z: 2 }, [])).toEqual({ x: 2, z: 2 });+ const beside = safePlacement(grid, { x: 2, z: 2 }, [{ x: 2, z: 2 }]);+ expect(isWalkable(grid, beside)).toBe(true);+ expect(Math.hypot(beside.x - 2, beside.z - 2)).toBeGreaterThanOrEqual(BODY_SPACING);+ });+});++describe("routeMarks", () => {+ it("dots the route evenly, starts a step ahead and leaves the destination to its ring", () => {+ const marks = routeMarks({ x: 0, z: 0 }, [{ x: 9, z: 0 }, { x: 9, z: 9 }], 0.9, 40);+ expect(marks.length).toBeGreaterThan(15);+ expect(marks[0]).toEqual({ x: 0.9, z: 0 });+ const last = marks[marks.length - 1];+ expect(Math.hypot(last.x - 9, last.z - 9)).toBeGreaterThan(0.4);+ for (let i = 1; i < marks.length; i += 1) {+ expect(Math.abs(marks[i].x - marks[i - 1].x) + Math.abs(marks[i].z - marks[i - 1].z)).toBeCloseTo(0.9, 5);+ }+ });+ it("spreads its dots over a long route and draws none on a short one", () => {+ expect(routeMarks({ x: 0, z: 0 }, [{ x: 200, z: 0 }], 0.9, 40)).toHaveLength(40);+ expect(routeMarks({ x: 0, z: 0 }, [{ x: 1, z: 0 }])).toEqual([]);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeWalk.ts b/jarvis/ui/web/frontend/src/components/society/office/officeWalk.tsnew file mode 100644index 0000000000..142c441b52--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/officeWalk.ts@@ -0,0 +1,246 @@+/**+ * One walk of a figure to a place, from the first step to the arrival: the+ * route, the pace, and everything that can go wrong on the way.+ *+ * - The route is recomputed when steering carried the figure off it, and when+ * the floor plan changed under its feet (teams are created and deleted while+ * people walk).+ * - A figure that stops getting anywhere first takes a detour round whoever+ * stands in its way. After two detours that did not help it is placed when+ * its target is a few steps away (on its reserved seat, or on the nearest+ * free ground beside the target); further away it gives the walk up, and its+ * owner plans again from where it stands. Nobody is moved across the floor,+ * unless the caller insists (`far`: a place the agent's real state demands,+ * after it failed to get there twice).+ * - A walk has a time budget, so a figure that keeps moving without arriving+ * (back and forth in a doorway) ends the same way.+ *+ * Pure: the caller owns the mover, the clock and the list of other bodies.+ */+import type { Point } from "./officeLayout";+import { clearOfBodies, newStuckWatch, paceFor, stepWalker, watchProgress, WALK_SPEED, BODY_SPACING, type Mover, type StuckWatch } from "./officeMotion";+import { findPath, isWalkable, nearestWalkable, type NavGrid } from "./officeNav";++/** Blocked by a body this close to a place to stand, the figure has arrived: it stops beside whoever is there. */+const NEAR_ENOUGH_M = 0.5;+/** A figure is placed at a target this close; a target further away is given up instead. */+export const PLACE_WITHIN_M = 3;+/** A walk may take this many times its expected duration, plus a margin, before it ends by placement or is given up. */+const BUDGET_FACTOR = 3;+const BUDGET_MARGIN_S = 8;+/** Seconds between two route repairs after steering left the route. */+const REPATH_EVERY_S = 0.4;+/** Bodies further away than this play no part in a detour. */+const DETOUR_RANGE_M = 7;+/** A body blocks the cells this close to its centre while a detour is planned: the spacing two bodies keep, and a little more. */+const DETOUR_BODY_M = BODY_SPACING + 0.08;++/**+ * What happened on this step besides walking: a detour round a body+ * ("replan"), a placement ("rescue"), a repaired route ("repath"), an arrival+ * beside an occupied place ("near"), a walk given up because the way stays+ * closed ("blocked"), or a target that can no longer be reached on the new+ * floor plan ("lost"). After "blocked" and "lost" the walk is over without an+ * arrival: the caller plans again.+ */+export type WalkEvent = "replan" | "rescue" | "repath" | "near" | "blocked" | "lost" | null;++export interface Walk {+ target: Point;+ /** The floor plan the route was computed on. */+ grid: NavGrid;+ watch: StuckWatch;+ elapsedS: number;+ budgetS: number;+ /** Metres of route left, for the pace. */+ remaining: number;+ /** The whole route's length when the walk began. */+ length: number;+ sinceRepathS: number;+ /** Counters for the dev handle: detours, placements and route repairs on this walk. */+ replans: number;+ rescues: number;+ repaths: number;+}++export interface WalkResult { moved: number; arrived: boolean; event: WalkEvent }++export function pathLength(from: Point, path: readonly Point[]): number {+ let total = 0;+ let at = from;+ for (const p of path) { total += Math.hypot(p.x - at.x, p.z - at.z); at = p; }+ return total;+}++function budgetFor(length: number): number {+ return (length / WALK_SPEED) * BUDGET_FACTOR + BUDGET_MARGIN_S;+}++/** A figure getting up looks for a way out round anyone standing this close to its seat. */+const SEAT_EXIT_RANGE_M = 1.6;++/**+ * Start walking `m` to `target`. Null when no route exists; the caller places+ * the figure instead. A figure that starts inside a footprint (it gets up+ * from a seat) leaves on the side where nobody of `bodies` stands.+ */+export function beginWalk(grid: NavGrid, m: Mover, target: Point, bodies: readonly Point[] = []): Walk | null {+ const crowded = !isWalkable(grid, m) && bodies.some((b) => Math.hypot(b.x - m.x, b.z - m.z) <= SEAT_EXIT_RANGE_M);+ const path = (crowded ? findDetour(grid, m, target, bodies) : null) ?? findPath(grid, m, target);+ if (!path) return null;+ m.path = path;+ const length = pathLength(m, path);+ return {+ target: { x: target.x, z: target.z }, grid, watch: newStuckWatch(m), elapsedS: 0, budgetS: budgetFor(length),+ remaining: length, length, sinceRepathS: REPATH_EVERY_S, replans: 0, rescues: 0, repaths: 0,+ };+}++/**+ * A route to `to` that also walks round the bodies standing nearby. Null when+ * there is none (they close the only way), so the caller can keep its route.+ */+export function findDetour(grid: NavGrid, from: Point, to: Point, bodies: readonly Point[]): Point[] | null {+ const near = bodies.filter((b) => Math.hypot(b.x - from.x, b.z - from.z) <= DETOUR_RANGE_M+ // Whoever stands on the target itself is not walked round: the figure stops beside them.+ && Math.hypot(b.x - to.x, b.z - to.z) > DETOUR_BODY_M + grid.cell);+ if (near.length === 0) return null;+ // A copy with its own search buffers: the labelled regions of the real grid stay valid.+ const blocked = new Uint8Array(grid.blocked);+ const reach = Math.ceil(DETOUR_BODY_M / grid.cell);+ for (const body of near) {+ const bc = Math.floor((body.x - grid.originX) / grid.cell), br = Math.floor((body.z - grid.originZ) / grid.cell);+ for (let r = Math.max(0, br - reach); r <= Math.min(grid.rows - 1, br + reach); r += 1) {+ for (let c = Math.max(0, bc - reach); c <= Math.min(grid.cols - 1, bc + reach); c += 1) {+ const cx = grid.originX + (c + 0.5) * grid.cell, cz = grid.originZ + (r + 0.5) * grid.cell;+ // The figure's own cell stays free, however close the body stands.+ if (Math.hypot(cx - body.x, cz - body.z) <= DETOUR_BODY_M && Math.hypot(cx - from.x, cz - from.z) > grid.cell) blocked[r * grid.cols + c] = 1;+ }+ }+ }+ return findPath({ ...grid, blocked }, from, to);+}++/** Somebody this close to a seat is on it, however the seat was reserved. */+const ON_SEAT_M = 0.3;++/**+ * Where a figure that cannot walk to `target` is put. A seat inside a+ * footprint is reserved, so it is the place itself (the neighbours on a couch+ * sit closer than two walkers pass); a place to stand is taken when nobody is+ * on it. Otherwise it is the nearest free ground round the target: never on+ * top of anybody.+ */+export function safePlacement(grid: NavGrid, target: Point, bodies: readonly Point[]): Point {+ const free = isWalkable(grid, target) ? clearOfBodies(target, bodies) : clearOfBodies(target, bodies, ON_SEAT_M);+ if (free) return { x: target.x, z: target.z };+ for (const radius of [0.75, 1.1, 1.6, 2.4]) {+ for (let i = 0; i < 8; i += 1) {+ const angle = (i / 8) * Math.PI * 2;+ const p = { x: target.x + Math.sin(angle) * radius, z: target.z + Math.cos(angle) * radius };+ if (isWalkable(grid, p) && clearOfBodies(p, bodies)) return p;+ }+ }+ return nearestWalkable(grid, target) ?? { x: target.x, z: target.z };+}++/**+ * Marks along a route for the person to see where a click sends the+ * character: a dot every `spacing` metres from `from` along `path`, the+ * first one a step ahead, none on the destination itself (it has its own+ * ring). At most `max` dots; a longer route spreads them out.+ */+export function routeMarks(from: Point, path: readonly Point[], spacing = 0.9, max = 40): Point[] {+ const total = pathLength(from, path);+ if (total < spacing * 1.5) return [];+ const gap = Math.max(spacing, total / (max + 1));+ const marks: Point[] = [];+ let at = from;+ let next = gap;+ let walked = 0;+ for (const p of path) {+ const leg = Math.hypot(p.x - at.x, p.z - at.z);+ while (leg > 1e-9 && next <= walked + leg && next < total - gap * 0.5 && marks.length < max) {+ const t = (next - walked) / leg;+ marks.push({ x: at.x + (p.x - at.x) * t, z: at.z + (p.z - at.z) * t });+ next += gap;+ }+ walked += leg;+ at = p;+ }+ return marks;+}++function reroute(walk: Walk, m: Mover, path: Point[]): void {+ m.path = path;+ walk.remaining = pathLength(m, path);+}++function place(walk: Walk, m: Mover, grid: NavGrid, bodies: readonly Point[]): WalkResult {+ const spot = safePlacement(grid, walk.target, bodies);+ m.x = spot.x; m.z = spot.z; m.path = [];+ walk.rescues += 1;+ walk.remaining = 0;+ return { moved: 0, arrived: true, event: "rescue" };+}++/**+ * Advance a walk by one frame on the current floor plan `grid`. `bodies` are+ * the other figures (already without the walker itself). With `place: false`+ * (the person's own character) a walk that fails always stops where it is;+ * with `far: true` it is placed however far away its target is.+ */+export function advanceWalk(walk: Walk, m: Mover, grid: NavGrid, dt: number, bodies: readonly Point[],+ options: { speed?: number; place?: boolean; far?: boolean } = {}): WalkResult {+ const mayPlace = options.place !== false;+ const walkable = (p: Point) => isWalkable(grid, p);+ let event: WalkEvent = null;++ if (grid !== walk.grid) {+ // The floor plan changed under the walk: find the new way (a route out of anything that now stands here included).+ walk.grid = grid;+ const path = findPath(grid, m, walk.target);+ if (!path) { m.path = []; return { moved: 0, arrived: false, event: "lost" }; }+ reroute(walk, m, path);+ walk.watch = newStuckWatch(m);+ walk.budgetS = walk.elapsedS + budgetFor(walk.remaining);+ walk.repaths += 1;+ event = "repath";+ }++ walk.elapsedS += dt;+ walk.sinceRepathS += dt;+ const step = stepWalker(m, options.speed ?? paceFor(walk.remaining), dt, bodies, walkable);+ walk.remaining = Math.max(0, walk.remaining - step.moved);+ if (step.arrived) return { moved: step.moved, arrived: true, event };++ if (step.offPath && walk.sinceRepathS >= REPATH_EVERY_S) {+ const path = findPath(grid, m, walk.target);+ if (path) { reroute(walk, m, path); walk.repaths += 1; event = "repath"; }+ walk.sinceRepathS = 0;+ }++ const verdict = walk.elapsedS > walk.budgetS ? "rescue" : watchProgress(walk.watch, m, dt);+ if (verdict === "ok") return { moved: step.moved, arrived: false, event };++ // Someone stands on (or right beside) a place to stand: stop next to them, that is an arrival.+ const left = Math.hypot(walk.target.x - m.x, walk.target.z - m.z);+ if (walkable(walk.target) && walkable(m) && left <= NEAR_ENOUGH_M + BODY_SPACING+ && bodies.some((b) => Math.hypot(b.x - walk.target.x, b.z - walk.target.z) < BODY_SPACING)) {+ m.path = [];+ walk.remaining = 0;+ return { moved: step.moved, arrived: true, event: "near" };+ }+ if (verdict === "replan") {+ const path = findDetour(grid, m, walk.target, bodies) ?? findPath(grid, m, walk.target);+ if (path) reroute(walk, m, path);+ walk.replans += 1;+ return { moved: step.moved, arrived: false, event: "replan" };+ }+ if (!mayPlace || (!options.far && left > PLACE_WITHIN_M)) {+ m.path = [];+ walk.remaining = 0;+ return { moved: step.moved, arrived: false, event: "blocked" };+ }+ return place(walk, m, grid, bodies);+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/plateCrowd.test.ts b/jarvis/ui/web/frontend/src/components/society/office/plateCrowd.test.tsnew file mode 100644index 0000000000..1fa98b78e1--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/plateCrowd.test.ts@@ -0,0 +1,153 @@+import { beforeEach, describe, expect, it } from "vitest";+import {+ arrangePlates, BUBBLE_ROOM, joinPlates, PLATE_GAP, plateSeating, plateStages, reportPlate, resetPlateSeating, type PlateBox,+} from "./plateCrowd";++/** A plate 150 px wide and 22 px high, like a name plate with a rank chip. */+function plate(id: string, x: number, y: number, extra: Partial<PlateBox> = {}): PlateBox {+ return { id, x, y, w: 150, h: 22, pinned: false, speaker: false, shown: false, distance: 5, ...extra };+}++/** Five figures 60 px apart on screen: every plate covers its neighbours. */+function huddle(extra: Record<string, Partial<PlateBox>> = {}): PlateBox[] {+ return ["a", "b", "c", "d", "e"].map((id, i) => plate(id, 400 + i * 60, 300, { distance: 3 + i, ...extra[id] }));+}++function coversAnother(boxes: PlateBox[], open: Set<string>): boolean {+ const seated = boxes.filter((box) => open.has(box.id));+ return seated.some((a, i) => seated.slice(i + 1).some((b) => Math.abs(a.x - b.x) * 2 < a.w + b.w && Math.abs(a.y - b.y) * 2 < a.h + b.h));+}++describe("name plates in a crowd", () => {+ it("opens every plate when nobody stands in anybody's way", () => {+ const row = [plate("a", 100, 100), plate("b", 400, 100), plate("c", 700, 100), plate("d", 400, 200)];+ expect(arrangePlates(row)).toEqual(new Set(["a", "b", "c", "d"]));+ });++ it("keeps a huddle of five readable: open plates never cover one another", () => {+ const boxes = huddle();+ const open = arrangePlates(boxes);+ expect(open.size).toBeGreaterThan(0);+ expect(open.size).toBeLessThan(boxes.length);+ expect(coversAnother(boxes, open)).toBe(false);+ // Among equals the one nearest to the person is the one that opens.+ expect(open.has("a")).toBe(true);+ });++ it("always opens the selected or pointed-at agent, and seats the others round it", () => {+ const boxes = huddle({ c: { pinned: true } });+ const open = arrangePlates(boxes);+ expect(open.has("c")).toBe(true);+ // The neighbours its plate covers stay dots.+ expect(open.has("b")).toBe(false);+ expect(open.has("d")).toBe(false);+ expect(coversAnother(boxes, open)).toBe(false);+ });++ it("puts the speaker ahead of the bystanders, even the nearer ones", () => {+ const boxes = huddle({ d: { speaker: true } });+ const open = arrangePlates(boxes);+ expect(open.has("d")).toBe(true);+ expect(open.has("c")).toBe(false);+ expect(open.has("e")).toBe(false);+ });++ it("keeps a speaker's bubble clear: no plate opens in the room above it", () => {+ const speaker = plate("s", 400, 300, { speaker: true });+ const behind = plate("x", 400, 300 - BUBBLE_ROOM.h + 10);+ const far = plate("y", 400, 300 - BUBBLE_ROOM.h - 60);+ const open = arrangePlates([behind, far, speaker]);+ expect(open).toEqual(new Set(["s", "y"]));+ // Without a speaker the same two plates do not touch and both open.+ expect(arrangePlates([behind, plate("s", 400, 300)])).toEqual(new Set(["s", "x"]));+ });++ it("does not reshuffle while people shift: an open plate keeps its seat against a nearer newcomer", () => {+ const boxes = [plate("old", 400, 300, { shown: true, distance: 6 }), plate("new", 460, 300, { distance: 2 })];+ expect(arrangePlates(boxes)).toEqual(new Set(["old"]));+ });++ it("opens and closes at different gaps, so a plate at the edge of another does not flicker", () => {+ const gap = (PLATE_GAP.keep + PLATE_GAP.open) / 2;+ const anchor = plate("a", 400, 300, { shown: true, distance: 1 });+ const beside = (shown: boolean) => plate("b", 400 + 150 + gap, 300, { shown, distance: 2 });+ // Just outside the other plate: a closed one stays closed, an open one stays open.+ expect(arrangePlates([anchor, beside(false)]).has("b")).toBe(false);+ expect(arrangePlates([anchor, beside(true)]).has("b")).toBe(true);+ });++ it("keeps clear of the person's own plate", () => {+ const person = { x: 400, y: 300, w: 150, h: 26 };+ expect(arrangePlates([plate("a", 430, 300), plate("b", 700, 300)], [person])).toEqual(new Set(["b"]));+ // The agent the person points at opens all the same.+ expect(arrangePlates([plate("a", 430, 300, { pinned: true })], [person])).toEqual(new Set(["a"]));+ });++ it("is the same answer whatever order the plates report in", () => {+ const boxes = huddle({ b: { speaker: true } });+ expect(arrangePlates([...boxes].reverse())).toEqual(arrangePlates(boxes));+ });+});++describe("plate seating from frame to frame", () => {+ beforeEach(resetPlateSeating);+ const nothingTaken = () => [];+ const stage = {};++ it("seats this frame from what the plates reported in the frame before", () => {+ expect(plateSeating(stage, 1, nothingTaken).size).toBe(0);+ for (const box of huddle()) reportPlate(stage, box);+ // Still frame 1: the answer does not change under the plates that already asked.+ expect(plateSeating(stage, 1, nothingTaken).size).toBe(0);+ const next = plateSeating(stage, 2, nothingTaken);+ expect(next.has("a")).toBe(true);+ expect(next.size).toBeLessThan(5);+ });++ it("forgets a plate that stopped reporting", () => {+ reportPlate(stage, plate("gone", 100, 100));+ expect(plateSeating(stage, 1, nothingTaken).has("gone")).toBe(true);+ reportPlate(stage, plate("here", 100, 100));+ expect(plateSeating(stage, 2, nothingTaken)).toEqual(new Set(["here"]));+ });+});++describe("two offices awake at once", () => {+ beforeEach(resetPlateSeating);+ const nothingTaken = () => [];++ it("seat their plates apart: the same agent sits on different screens, on different clocks", () => {+ const agentsView = {}, idePanel = {};+ // The same agent id, far apart on one screen and under another plate on the other.+ reportPlate(agentsView, plate("a", 100, 100));+ reportPlate(agentsView, plate("b", 600, 100));+ reportPlate(idePanel, plate("b", 100, 100, { distance: 1 }));+ reportPlate(idePanel, plate("a", 130, 100, { distance: 9 }));+ expect(plateSeating(agentsView, 10.5, nothingTaken)).toEqual(new Set(["a", "b"]));+ expect(plateSeating(idePanel, 3.25, nothingTaken)).toEqual(new Set(["b"]));+ // One stage asking again on its own clock does not re-seat or empty the other.+ reportPlate(agentsView, plate("a", 100, 100, { shown: true }));+ expect(plateSeating(agentsView, 10.6, nothingTaken)).toEqual(new Set(["a"]));+ expect(plateSeating(idePanel, 3.25, nothingTaken)).toEqual(new Set(["b"]));+ });++ it("releases a stage's seating when its last plate has left", () => {+ const stage = {}, other = {};+ const leaveA = joinPlates(stage), leaveB = joinPlates(stage), leaveOther = joinPlates(other);+ reportPlate(stage, plate("a", 100, 100));+ expect(plateStages()).toBe(2);+ leaveA();+ expect(plateStages()).toBe(2);+ leaveB();+ // Leaving twice (an effect cleaned up again) must not take somebody else's count.+ leaveB();+ expect(plateStages()).toBe(1);+ leaveOther();+ expect(plateStages()).toBe(0);+ // A stage that mounts again starts clean: nothing of the old reports is seated.+ const leaveAgain = joinPlates(stage);+ expect(plateSeating(stage, 1, nothingTaken).size).toBe(0);+ leaveAgain();+ expect(plateStages()).toBe(0);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/plateCrowd.ts b/jarvis/ui/web/frontend/src/components/society/office/plateCrowd.tsnew file mode 100644index 0000000000..02268becbb--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/plateCrowd.ts@@ -0,0 +1,140 @@+/**+ * Name plates in a crowd. A plate is a good deal wider than the figure under+ * it, so a team huddled at its board would stack five plates into one+ * unreadable pile. Each frame every plate that wants to open reports where it+ * would sit on screen; the plates are then seated in order of importance, and+ * one that would cover a plate already seated stays a dot.+ *+ * Order: the agent the person selected or points at (always open), whoever is+ * speaking in a team round (its speech bubble gets room above the plate), a+ * plate that is already open (so the picture does not reshuffle while people+ * shift about), then whoever stands closest to the person. Pure and tested;+ * the small registry below only carries the reports from one frame to the+ * next.+ */++/** A plate's place on screen, in CSS pixels: centre and size. */+export interface PlateBox {+ id: string;+ x: number;+ y: number;+ w: number;+ h: number;+ /** Selected or pointed at: opens whatever it covers. */+ pinned: boolean;+ /** Speaking in a team round right now: ahead of the bystanders, with room for its bubble. */+ speaker: boolean;+ /** Open in the last frame. */+ shown: boolean;+ /** Metres to the person's character; the nearer one wins among equals. */+ distance: number;+}++export interface ScreenRect { x: number; y: number; w: number; h: number }++/** An open plate keeps its seat until something comes this close (px); a closed one needs this much clear space to open. */+export const PLATE_GAP = { keep: 2, open: 12 } as const;+/** A speaker's bubble sits above its plate: this much room (px) is kept free there. */+export const BUBBLE_ROOM = { w: 220, h: 84 } as const;++function overlaps(a: ScreenRect, b: ScreenRect, gap: number): boolean {+ return Math.abs(a.x - b.x) * 2 < a.w + b.w + gap * 2 && Math.abs(a.y - b.y) * 2 < a.h + b.h + gap * 2;+}++/** The space a plate claims: itself, plus the bubble above it while its agent speaks. */+function claim(box: PlateBox): ScreenRect {+ if (!box.speaker) return box;+ const h = box.h + BUBBLE_ROOM.h;+ return { x: box.x, y: box.y - BUBBLE_ROOM.h / 2, w: Math.max(box.w, BUBBLE_ROOM.w), h };+}++function rank(box: PlateBox): number {+ return box.pinned ? 0 : box.speaker ? 1 : box.shown ? 2 : 3;+}++/**+ * The plates that may open, given everyone who wants to. `taken` are places+ * that are occupied whatever happens (the person's own plate).+ */+export function arrangePlates(boxes: readonly PlateBox[], taken: readonly ScreenRect[] = []): Set<string> {+ const seated: ScreenRect[] = [...taken];+ const open = new Set<string>();+ const order = [...boxes].sort((a, b) => rank(a) - rank(b) || a.distance - b.distance || a.id.localeCompare(b.id));+ for (const box of order) {+ const space = claim(box);+ if (!box.pinned) {+ const gap = box.shown ? PLATE_GAP.keep : PLATE_GAP.open;+ // A bystander only has to keep its own plate clear of what is seated; a speaker also needs its bubble's room.+ if (seated.some((other) => overlaps(space, other, gap))) continue;+ }+ seated.push(space);+ open.add(box.id);+ }+ return open;+}++/**+ * One stage's seating: the reports of its running frame, and who was seated from the frame before. Every office+ * stage has its own (two can be awake at once: the Agents view and the IDE side panel's tab show the same agent+ * ids on different screens and clocks), keyed by the stage's scene.+ */+interface StageSeating { reports: Map<string, PlateBox>; seatedAt: number; open: Set<string>; plates: number }++const stages = new Map<object, StageSeating>();++function seatingOf(stage: object): StageSeating {+ let seating = stages.get(stage);+ if (!seating) {+ seating = { reports: new Map(), seatedAt: Number.NaN, open: new Set(), plates: 0 };+ stages.set(stage, seating);+ }+ return seating;+}++/**+ * A plate joins its stage's seating for as long as it is mounted. Returns the+ * leave function; when the stage's last plate has left, its seating is+ * released, so nothing of an unmounted stage is kept.+ */+export function joinPlates(stage: object): () => void {+ seatingOf(stage).plates += 1;+ let left = false;+ return () => {+ if (left) return;+ left = true;+ const seating = stages.get(stage);+ if (!seating) return;+ seating.plates -= 1;+ if (seating.plates <= 0) stages.delete(stage);+ };+}++/**+ * Who may be open on this stage this frame. The first plate that asks in a+ * frame seats everyone from the reports of the frame before; a plate that+ * stopped reporting (walked off, unmounted) drops out by itself.+ */+export function plateSeating(stage: object, frame: number, taken: () => readonly ScreenRect[]): ReadonlySet<string> {+ const seating = seatingOf(stage);+ if (frame !== seating.seatedAt) {+ seating.seatedAt = frame;+ seating.open = arrangePlates([...seating.reports.values()], taken());+ seating.reports.clear();+ }+ return seating.open;+}++/** A plate that wants to be open says where it would sit on its stage. */+export function reportPlate(stage: object, box: PlateBox): void {+ seatingOf(stage).reports.set(box.id, box);+}++/** How many stages hold a seating right now (for tests: an unmounted stage must leave none behind). */+export function plateStages(): number {+ return stages.size;+}++/** Forget everything (tests). */+export function resetPlateSeating(): void {+ stages.clear();+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/pollSignal.ts b/jarvis/ui/web/frontend/src/components/society/office/pollSignal.tsnew file mode 100644index 0000000000..3dda955af5--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/pollSignal.ts@@ -0,0 +1,48 @@+/**+ * One abort signal per scheduled read of the office's pollers (desk chats,+ * team rounds). A read ends when its answer comes, when the poller is cleaned+ * up (`parent` aborts), or after `ms`: a request hanging on a half-open+ * socket must never hold the next tick back.+ */++/** How long one read may take before it is given up. */+export const READ_TIMEOUT_MS = 8000;++export interface ReadSignal {+ signal: AbortSignal;+ /** Call when the read has settled: drops the timer and the link to the parent. */+ done: () => void;+}++export function readSignal(parent: AbortSignal, ms = READ_TIMEOUT_MS): ReadSignal {+ const controller = new AbortController();+ const abort = () => controller.abort();+ if (parent.aborted) abort();+ else parent.addEventListener("abort", abort, { once: true });+ const timer = setTimeout(abort, ms);+ return {+ signal: controller.signal,+ done: () => { clearTimeout(timer); parent.removeEventListener("abort", abort); },+ };+}++/**+ * Run `read` under a signal of its own. Resolves to its value, or rejects+ * when it fails, is aborted or takes longer than `ms`; the timeout rejects+ * even when the underlying request ignores the signal.+ */+export async function withReadSignal<T>(parent: AbortSignal, read: (signal: AbortSignal) => Promise<T>, ms = READ_TIMEOUT_MS): Promise<T> {+ const { signal, done } = readSignal(parent, ms);+ try {+ return await Promise.race([+ read(signal),+ new Promise<never>((_, reject) => {+ const fail = () => reject(new Error(parent.aborted ? "read cancelled" : "read timed out"));+ if (signal.aborted) fail();+ else signal.addEventListener("abort", fail, { once: true });+ }),+ ]);+ } finally {+ done();+ }+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/reception.css b/jarvis/ui/web/frontend/src/components/society/office/reception.cssindex 3a5770933f..4622b99196 100644--- a/jarvis/ui/web/frontend/src/components/society/office/reception.css+++ b/jarvis/ui/web/frontend/src/components/society/office/reception.css@@ -1,89 +1,8 @@-/* Reception: the office's help centre. Theme tokens only, so light and dark mode both work. */-.office-panel-slot[data-wide] { width:min(440px, calc(100% - 28px)); }-/* Focus lands on the panel when it opens (H); its tabs and fields show their own rings. */-.office-panel[data-panel="create"]:focus-visible { outline:none; }-.office-reception { display:flex; flex-direction:column; gap:12px; min-height:0; }-.office-reception svg { width:15px; height:15px; flex:none; }--/* Tabs: a segmented control with a sliding thumb. */-.office-rx-tabs { position:relative; display:grid; grid-template-columns:repeat(3, 1fr); padding:3px; border-radius:11px; background:hsl(var(--secondary) / .75); border:1px solid hsl(var(--border)); }-.office-rx-tab-thumb { position:absolute; top:3px; bottom:3px; left:3px; width:calc((100% - 6px) / 3); border-radius:8px; background:hsl(var(--background)); box-shadow:0 1px 2px rgb(0 0 0 / .12), 0 2px 8px rgb(0 0 0 / .12); transform:translateX(calc(var(--rx-tab, 0) * 100%)); transition:transform .22s cubic-bezier(.3, .7, .2, 1); }-.office-rx-tab { position:relative; display:inline-flex; align-items:center; justify-content:center; gap:6px; border:0; border-radius:8px; padding:7px 6px; background:transparent; color:hsl(var(--muted-foreground)); font-size:12px; font-weight:600; cursor:pointer; white-space:nowrap; min-width:0; transition:color .15s; }-.office-rx-tab svg { width:14px; height:14px; }-.office-rx-tab:hover, .office-rx-tab[aria-selected="true"] { color:hsl(var(--foreground)); }-.office-rx-tab:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:1px; }-.office-rx-body { display:flex; flex-direction:column; gap:10px; animation:office-rx-in .2s ease-out; }-@keyframes office-rx-in { from { opacity:0; transform:translateY(4px); } to { opacity:1; transform:none; } }--/* Icon tiles: a checkpoint's icon, as on its floor token. */-.office-rx-icon { flex:none; display:inline-flex; align-items:center; justify-content:center; width:32px; height:32px; border-radius:10px; background:hsl(var(--secondary)); color:hsl(var(--foreground)); border:1px solid hsl(var(--border)); }-.office-rx-icon svg { width:16px; height:16px; }-.office-rx-icon[data-tone="gold"] { background:linear-gradient(160deg, #ffd476, #f0a92b); color:#1f1300; border-color:transparent; box-shadow:0 4px 14px rgb(240 169 43 / .35); }--.office-rx-heading { margin:4px 2px -2px; font-size:10.5px; font-weight:700; letter-spacing:.07em; text-transform:uppercase; color:hsl(var(--muted-foreground)); }-.office-rx-lead { color:hsl(var(--muted-foreground)); }--/* Welcome: hiring first, then every place on the floor. */-.office-rx-hero { position:relative; overflow:hidden; display:flex; gap:12px; padding:13px; border-radius:13px; border:1px solid rgb(240 169 43 / .35); background:linear-gradient(135deg, rgb(245 184 61 / .16), rgb(245 184 61 / .03) 60%), hsl(var(--background) / .55); }-.office-rx-hero::after { content:""; position:absolute; right:-40px; top:-40px; width:130px; height:130px; border-radius:50%; background:radial-gradient(circle, rgb(245 184 61 / .22), transparent 70%); pointer-events:none; }-.office-rx-hero > div { position:relative; display:flex; flex-direction:column; align-items:flex-start; gap:6px; min-width:0; }-.office-rx-hero strong { font-size:13.5px; }-.office-rx-hero p { color:hsl(var(--muted-foreground)); }-.office-rx-hero .office-action-primary { margin-top:2px; padding:7px 14px; }-.office-rx-places { list-style:none; margin:0; padding:0; display:flex; flex-direction:column; gap:3px; }-.office-rx-place { display:flex; align-items:center; gap:10px; width:100%; padding:6px 8px 6px 6px; border:1px solid transparent; border-radius:11px; background:transparent; color:inherit; font:inherit; text-align:left; cursor:pointer; transition:background .15s, border-color .15s; }-.office-rx-place:hover { background:hsl(var(--secondary) / .7); border-color:hsl(var(--border)); }-.office-rx-place:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:1px; }-.office-rx-place-text { flex:1; min-width:0; display:flex; flex-direction:column; }-.office-rx-place-text strong { font-size:12.5px; }-.office-rx-place-text span { font-size:11px; color:hsl(var(--muted-foreground)); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }-.office-rx-go { flex:none; display:inline-flex; align-items:center; gap:2px; font-size:11px; font-weight:600; color:hsl(var(--muted-foreground)); opacity:.75; transition:opacity .15s, color .15s, transform .15s; }-.office-rx-go svg { width:13px; height:13px; }-.office-rx-place:hover .office-rx-go, .office-rx-place:focus-visible .office-rx-go { opacity:1; color:hsl(var(--foreground)); transform:translateX(2px); }-.office-rx-tip { display:flex; align-items:center; gap:9px; padding:9px 11px; border-radius:11px; background:hsl(var(--secondary) / .45); font-size:11px; color:hsl(var(--muted-foreground)); }--/* Key caps: a raised key for keys, a softer pill for mouse gestures. */-.office-rx-cap { display:inline-flex; align-items:center; justify-content:center; min-width:23px; height:23px; padding:0 6px; border-radius:6px; border:1px solid hsl(var(--border)); box-shadow:inset 0 -2px 0 hsl(var(--border)); background:linear-gradient(hsl(var(--background)), hsl(var(--secondary) / .6)); color:hsl(var(--foreground)); font-family:inherit; font-size:11px; font-weight:700; line-height:1; white-space:nowrap; }-.office-rx-cap svg { width:12px; height:12px; stroke-width:2.6; }-.office-rx-cap[data-mouse] { box-shadow:none; border-radius:999px; padding:0 9px; font-weight:600; background:hsl(var(--secondary) / .8); color:hsl(var(--muted-foreground)); }-.office-rx-keys { display:flex; flex-wrap:wrap; justify-content:flex-end; align-items:center; gap:4px; }-.office-rx-alt { display:inline-flex; align-items:center; gap:3px; }-.office-rx-or { margin:0 3px 0 1px; font-size:10.5px; color:hsl(var(--muted-foreground)); }-.office-rx-plus { font-size:11px; color:hsl(var(--muted-foreground)); }--/* Controls: a search, then one card per group with a row per action. */-.office-rx-search { display:flex; align-items:center; gap:8px; padding:0 10px; border-radius:10px; border:1px solid hsl(var(--border)); background:hsl(var(--background) / .7); color:hsl(var(--muted-foreground)); transition:border-color .15s, box-shadow .15s; }-.office-rx-search:focus-within { border-color:hsl(var(--ring)); box-shadow:0 0 0 3px hsl(var(--ring) / .18); }-.office-rx-search input { flex:1; min-width:0; height:32px; border:0; background:transparent; color:hsl(var(--foreground)); font-size:12px; outline:none; }-.office-rx-search input::placeholder { color:hsl(var(--muted-foreground)); }-.office-rx-empty { padding:18px 8px; text-align:center; color:hsl(var(--muted-foreground)); }-.office-rx-groups { display:flex; flex-direction:column; gap:8px; }-.office-rx-group { border:1px solid hsl(var(--border)); border-radius:12px; padding:9px 11px 4px; background:hsl(var(--background) / .5); }-.office-rx-group h3 { display:flex; align-items:center; gap:7px; margin:0 0 4px; font-size:10.5px; font-weight:700; letter-spacing:.07em; text-transform:uppercase; color:hsl(var(--muted-foreground)); }-.office-rx-group h3 svg { width:13px; height:13px; }-.office-rx-group ul { list-style:none; margin:0; padding:0; }-.office-rx-group li { display:flex; align-items:center; justify-content:space-between; gap:10px; padding:6px 0; border-top:1px solid hsl(var(--border) / .6); }-.office-rx-group li:first-child { border-top:0; }-.office-rx-what { min-width:0; }--/* Settings: sections of rows, each with an icon and a switch. */-.office-rx-settings { display:flex; flex-direction:column; border:1px solid hsl(var(--border)); border-radius:12px; overflow:hidden; background:hsl(var(--background) / .5); }-.office-rx-setting { display:flex; align-items:center; gap:11px; padding:11px; }-.office-rx-setting + .office-rx-setting { border-top:1px solid hsl(var(--border)); }-.office-rx-setting > div { flex:1; display:flex; flex-direction:column; gap:2px; min-width:0; }-.office-rx-setting strong { font-size:12.5px; }-.office-rx-setting span { font-size:11px; color:hsl(var(--muted-foreground)); }-.office-rx-switch { flex:none; position:relative; width:38px; height:22px; border-radius:999px; border:1px solid hsl(var(--border)); background:hsl(var(--secondary)); cursor:pointer; padding:0; transition:background .18s, border-color .18s; }-.office-rx-switch i { position:absolute; top:2px; left:2px; width:16px; height:16px; border-radius:50%; background:hsl(var(--background)); box-shadow:0 1px 3px rgb(0 0 0 / .3); transition:transform .18s cubic-bezier(.3, .7, .2, 1); }-.office-rx-switch[aria-checked="true"] { background:#f0a92b; border-color:transparent; }-.office-rx-switch[aria-checked="true"] i { transform:translateX(16px); background:#fff; }-.office-rx-switch:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:2px; }-.office-rx-reset { align-self:flex-start; display:inline-flex; align-items:center; gap:6px; border:1px solid hsl(var(--border)); border-radius:9px; padding:6px 11px; background:transparent; color:hsl(var(--muted-foreground)); font-size:11.5px; font-weight:600; cursor:pointer; }-.office-rx-reset svg { width:13px; height:13px; }-.office-rx-reset:hover { color:hsl(var(--foreground)); background:hsl(var(--secondary)); }-.office-rx-reset:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:2px; }--@media (prefers-reduced-motion: reduce) {- .office-rx-tab-thumb, .office-rx-tab, .office-rx-switch, .office-rx-switch i, .office-rx-place, .office-rx-go { transition:none; }- .office-rx-body { animation:none; }-}+/* Key caps, shared by the reception's controls guide, the HUD prompt and the first-visit hints. Theme tokens only. */+.office-key { display:inline-flex; align-items:center; justify-content:center; min-width:22px; height:22px; padding:0 6px; border-radius:6px; border:1px solid hsl(var(--border)); box-shadow:inset 0 -2px 0 hsl(var(--border)); background:hsl(var(--background)); color:hsl(var(--foreground)); font-family:inherit; font-size:11px; font-weight:600; line-height:1; white-space:nowrap; }+/* A mouse gesture is not a key: a flat pill. */+.office-key[data-mouse] { box-shadow:none; border-radius:999px; padding:0 9px; font-weight:500; background:hsl(var(--secondary)); color:hsl(var(--muted-foreground)); }+.office-keys { display:flex; flex-wrap:wrap; justify-content:flex-end; align-items:center; gap:4px; }+.office-keys-alt { display:inline-flex; align-items:center; gap:3px; }+.office-keys-or { margin:0 3px 0 1px; font-size:11px; color:hsl(var(--muted-foreground)); }+.office-keys-plus { font-size:11px; color:hsl(var(--muted-foreground)); }diff --git a/jarvis/ui/web/frontend/src/components/society/office/spawnPanel.css b/jarvis/ui/web/frontend/src/components/society/office/spawnPanel.cssdeleted file mode 100644index 536bdb1f31..0000000000--- a/jarvis/ui/web/frontend/src/components/society/office/spawnPanel.css+++ /dev/null@@ -1,29 +0,0 @@-/* The spawn point's panel. Theme tokens plus the checkpoints' gold, so light and dark mode both work. */-.office-panel[data-panel="spawn"]:focus-visible, .office-panel[data-panel="launch"]:focus-visible { outline:none; }-/* Nothing in it shrinks: a tall launcher scrolls the panel body instead of squashing the hero. */-.office-spawn { display:flex; flex-direction:column; gap:12px; }-.office-spawn > * { flex:none; }--/* The hero: the spawn mark on gold, a title and one line of what happens. */-.office-spawn-hero { position:relative; overflow:hidden; display:flex; align-items:flex-start; gap:12px; padding:14px; border-radius:14px; border:1px solid rgb(240 169 43 / .38); background:radial-gradient(120% 140% at 100% 0%, rgb(245 184 61 / .22), transparent 60%), hsl(var(--background) / .55); }-.office-spawn-mark { flex:none; display:inline-flex; align-items:center; justify-content:center; width:44px; height:44px; border-radius:14px; background:linear-gradient(160deg, #ffd476, #f0a92b); color:#1f1300; box-shadow:0 6px 18px rgb(240 169 43 / .4); }-.office-spawn-mark svg { width:24px; height:24px; }-.office-spawn-hero > div { min-width:0; }-.office-spawn-hero strong { display:block; margin-bottom:3px; font-size:14px; }-.office-spawn-hero p { margin:0; font-size:12px; line-height:1.45; color:hsl(var(--muted-foreground)); }--/* Three numbered steps side by side. */-.office-spawn-steps { list-style:none; margin:0; padding:0; display:grid; grid-template-columns:repeat(3, minmax(0, 1fr)); gap:6px; }-.office-spawn-steps li { display:flex; flex-direction:column; gap:6px; padding:9px 10px; border:1px solid hsl(var(--border)); border-radius:11px; background:hsl(var(--secondary) / .5); color:hsl(var(--foreground)); font-size:11.5px; line-height:1.35; }-.office-spawn-steps li span { display:inline-flex; align-items:center; justify-content:center; width:20px; height:20px; border-radius:50%; background:hsl(var(--foreground)); color:hsl(var(--background)); font-size:11px; font-weight:700; }--/* The one big action. */-.office-spawn-go { display:inline-flex; align-items:center; justify-content:center; gap:8px; height:40px; border:0; border-radius:12px; background:linear-gradient(160deg, #ffd476, #f0a92b); color:#1f1300; font:inherit; font-size:13.5px; font-weight:700; cursor:pointer; box-shadow:0 4px 14px rgb(240 169 43 / .35); transition:transform .12s, box-shadow .12s, opacity .12s; }-.office-spawn-go svg { width:16px; height:16px; }-.office-spawn-go:hover:not(:disabled) { transform:translateY(-1px); box-shadow:0 6px 20px rgb(240 169 43 / .5); }-.office-spawn-go:disabled { opacity:.45; cursor:not-allowed; }-.office-spawn-go:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:2px; }-.office-spawn-foot { margin:0; font-size:11px; text-align:center; color:hsl(var(--muted-foreground)); }--@media (prefers-reduced-motion:reduce) { .office-spawn-go { transition:none; } .office-spawn-go:hover:not(:disabled) { transform:none; } }-@media (max-width:420px) { .office-spawn-steps { grid-template-columns:1fr; } }diff --git a/jarvis/ui/web/frontend/src/components/society/office/stationIcons.tsx b/jarvis/ui/web/frontend/src/components/society/office/stationIcons.tsxnew file mode 100644index 0000000000..aa6c4531e5--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/stationIcons.tsx@@ -0,0 +1,13 @@+/** The icon each station wears in the HUD's places menu and in the reception's directory. */+import { ArrowUpDown, Coffee, ConciergeBell, Radar, Shirt, Sparkles, SquareTerminal, Star, Trophy, UserPlus, Users, type LucideIcon } from "lucide-react";+import type { StationIcon } from "./stations";++const ICONS: Record<StationIcon, LucideIcon> = {+ spawn: UserPlus, launch: SquareTerminal, reception: ConciergeBell, team: Users, wardrobe: Shirt, lead: Star, break: Coffee,+ elevator: ArrowUpDown, mission: Radar, studio: Sparkles, levels: Trophy,+};++export function StationGlyph({ icon, size = 16 }: { icon: StationIcon; size?: number }) {+ const Icon = ICONS[icon];+ return <Icon size={size} aria-hidden />;+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/stationRim.test.ts b/jarvis/ui/web/frontend/src/components/society/office/stationRim.test.tsnew file mode 100644index 0000000000..4c7370a1f2--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/stationRim.test.ts@@ -0,0 +1,65 @@+import { describe, expect, it } from "vitest";+import { BackSide, BoxGeometry, Group, InstancedMesh, Mesh, MeshBasicMaterial, PlaneGeometry, Scene } from "three";+import { attachRim, attachedTo, createRimMaterial, detachRim, rimTargets } from "./stationRim";++function prop() {+ const root = new Group();+ root.name = "prop:reception-desk";+ const counter = new Mesh(new BoxGeometry(2, 1, 0.8), new MeshBasicMaterial());+ const wall = new Mesh(new BoxGeometry(2.6, 2.2, 0.1), new MeshBasicMaterial());+ // A drawn face, a hidden hit box and an instanced detail: none of them has a silhouette to rim.+ const face = new Mesh(new PlaneGeometry(1, 0.6), new MeshBasicMaterial());+ const hidden = new Mesh(new BoxGeometry(1, 1, 1), new MeshBasicMaterial());+ hidden.visible = false;+ const slats = new InstancedMesh(new BoxGeometry(0.05, 2, 0.05), new MeshBasicMaterial(), 12);+ const inner = new Group();+ inner.add(wall, face);+ root.add(counter, inner, hidden, slats);+ return { root, counter, wall, face, hidden, slats };+}++describe("station rim", () => {+ it("draws only back faces, so the object hides all of it but its edge", () => {+ const material = createRimMaterial();+ expect(material.side).toBe(BackSide);+ expect(material.depthWrite).toBe(false);+ expect(material.uniforms.rimOpacity.value).toBe(0);+ });++ it("wraps the solid, visible meshes of an object and nothing else", () => {+ const { root, counter, wall } = prop();+ expect(rimTargets(root)).toEqual([counter, wall]);+ });++ it("puts a shell on each of them that shares their geometry and takes no clicks", () => {+ const { root, counter, wall } = prop();+ const material = createRimMaterial();+ const shells = attachRim(root, material);+ expect(shells.map((shell) => shell.parent)).toEqual([counter, wall]);+ expect(shells[0]!.geometry).toBe(counter.geometry);+ expect(shells.every((shell) => shell.material === material && !shell.castShadow)).toBe(true);+ const hits: unknown[] = [];+ shells[0]!.raycast(undefined as never, hits as never);+ expect(hits).toEqual([]);+ // Lighting it a second time must not rim the rim.+ expect(rimTargets(root)).toEqual([counter, wall]);+ });++ it("leaves the object exactly as it was when the rim comes off", () => {+ const { root, counter, wall } = prop();+ const before = [counter.children.length, wall.children.length];+ const shells = attachRim(root, createRimMaterial());+ detachRim(shells);+ expect([counter.children.length, wall.children.length]).toEqual(before);+ expect(shells.every((shell) => shell.parent === null)).toBe(true);+ });++ it("notices an object that was rebuilt and left the scene", () => {+ const scene = new Scene();+ const { root, wall } = prop();+ scene.add(root);+ expect(attachedTo(wall, scene)).toBe(true);+ scene.remove(root);+ expect(attachedTo(wall, scene)).toBe(false);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/stationRim.ts b/jarvis/ui/web/frontend/src/components/society/office/stationRim.tsnew file mode 100644index 0000000000..98062bbb3a--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/stationRim.ts@@ -0,0 +1,101 @@+/**+ * The rim a station's object wears while the person is near it or points at+ * it: a thin lit edge round the object's own silhouette. Every mesh under the+ * object gets a shell of the same geometry, pushed out along its normals and+ * drawn back faces only, so the object hides all of it but the edge. Nothing+ * is added to the room at rest.+ */+import { BackSide, Color, Mesh, ShaderMaterial, type InstancedMesh, type Object3D, type SkinnedMesh } from "three";++/**+ * One blue for "you can use this", the same family as a selected agent's ring. Mid-bright and saturated on+ * purpose: it has to read on the pale floor and light oak of the agents floor as well as on dark walnut and+ * the coding floor's night.+ */+export const STATION_RIM_COLOUR = "#3f8cff";+/** Edge width in metres up close; beyond `RIM_FAR_M` it grows with distance so it stays visible from the overview. */+const RIM_WIDTH_M = 0.016;+const RIM_FAR_M = 11;++/** Flat geometry has no silhouette to rim; its shell would only show as a stray sheet from behind. */+const FLAT_GEOMETRY = new Set(["PlaneGeometry", "CircleGeometry", "RingGeometry", "ShapeGeometry"]);++const RIM_FLAG = "stationRim";++export function createRimMaterial(): ShaderMaterial {+ return new ShaderMaterial({+ uniforms: {+ rimColour: { value: new Color(STATION_RIM_COLOUR) },+ rimOpacity: { value: 0 },+ rimWidth: { value: RIM_WIDTH_M },+ rimFar: { value: RIM_FAR_M },+ },+ vertexShader: /* glsl */ `+ uniform float rimWidth;+ uniform float rimFar;+ void main() {+ vec4 viewPosition = modelViewMatrix * vec4(position, 1.0);+ vec3 viewNormal = normalize(normalMatrix * normal);+ viewPosition.xyz += viewNormal * rimWidth * max(1.0, -viewPosition.z / rimFar);+ gl_Position = projectionMatrix * viewPosition;+ }+ `,+ fragmentShader: /* glsl */ `+ uniform vec3 rimColour;+ uniform float rimOpacity;+ void main() {+ gl_FragColor = vec4(rimColour, rimOpacity);+ }+ `,+ side: BackSide,+ transparent: true,+ depthWrite: false,+ toneMapped: false,+ });+}++/** Can this object carry a shell? Plain, visible meshes with normals only. */+function rimmable(object: Object3D): object is Mesh {+ const mesh = object as Mesh;+ if (!mesh.isMesh || mesh.userData[RIM_FLAG]) return false;+ if ((mesh as InstancedMesh).isInstancedMesh || (mesh as SkinnedMesh).isSkinnedMesh) return false;+ const geometry = mesh.geometry;+ if (!geometry?.attributes?.normal || !geometry.attributes.position) return false;+ // Text and other instanced-attribute geometry needs its own shader to make sense.+ if ((geometry as { isInstancedBufferGeometry?: boolean }).isInstancedBufferGeometry) return false;+ return !FLAT_GEOMETRY.has(geometry.type);+}++/** The visible meshes under `root` that get a shell. */+export function rimTargets(root: Object3D): Mesh[] {+ const targets: Mesh[] = [];+ root.traverseVisible((object) => { if (rimmable(object)) targets.push(object); });+ return targets;+}++/** Add a rim shell to every visible mesh under `root`; returns the shells so they can be taken off again. */+export function attachRim(root: Object3D, material: ShaderMaterial): Mesh[] {+ return rimTargets(root).map((mesh) => {+ const shell = new Mesh(mesh.geometry, material);+ shell.userData[RIM_FLAG] = true;+ shell.name = "station-rim";+ // The shell is light, not a thing: no clicks, no shadows.+ shell.raycast = () => undefined;+ shell.castShadow = false;+ shell.receiveShadow = false;+ shell.frustumCulled = mesh.frustumCulled;+ mesh.add(shell);+ return shell;+ });+}++/** Take the shells off again. Their geometry belongs to the meshes they copied, so nothing is disposed here. */+export function detachRim(shells: readonly Mesh[]): void {+ for (const shell of shells) shell.removeFromParent();+}++/** Is `object` still part of the scene under `scene`? A re-rendered prop leaves its old group detached. */+export function attachedTo(object: Object3D, scene: Object3D): boolean {+ for (let node: Object3D | null = object; node; node = node.parent) if (node === scene) return true;+ return false;+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/stationText.ts b/jarvis/ui/web/frontend/src/components/society/office/stationText.tsnew file mode 100644index 0000000000..e07708a714--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/stationText.ts@@ -0,0 +1,19 @@+/** A station in words: what it is called and what using it does. Shared by the prompt, the places menu and the directory. */+import type { Station } from "./stations";++type Translate = (key: string) => string;++/**+ * What a station is called. A team studio's board is called after its team;+ * the board of the studio for agents without a team says so, so no row of a+ * list is ever a bare "Team board".+ */+export function stationLabel(station: Pick<Station, "id" | "name">, t: Translate): string {+ if (station.name) return station.name;+ return t(station.id === "board" ? "society.office.team_pool" : `society.office.cp_${station.id}`);+}++/** The action a station offers, in words; the coffee bar's flips while a break is on. */+export function stationAction(station: Pick<Station, "id">, t: Translate, breakOn = false): string {+ return t(`society.office.use_${station.id === "break" && breakOn ? "break_end" : station.id}`);+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/stations.test.ts b/jarvis/ui/web/frontend/src/components/society/office/stations.test.tsnew file mode 100644index 0000000000..a21cb438c7--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/stations.test.ts@@ -0,0 +1,211 @@+import { describe, expect, it } from "vitest";+import { buildOfficeLayout, FURNITURE_SIZE, type OfficeAgentInput, type OfficeLayout, type Studio } from "./officeLayout";+import { buildNavGrid, isWalkable, nearestWalkable } from "./officeNav";+import {+ isReception, isTeamStand, loungeCentre, nearestInteractable, selectionKey, spawnScreenDive, stationOf, stationsFor, TEAM_STAND_ID, TEAM_STAND_STATION,+} from "./stations";++function roster(count: number): OfficeAgentInput[] {+ return Array.from({ length: count }, (_, i) => ({+ agentId: `a${i}`, name: `Agent ${i}`, tier: i === 0 ? "lead" as const : "specialist" as const,+ providerLabel: i % 2 ? "Codex" : "Gemini", state: "idle" as const, createdMs: i,+ }));+}++const REACH = { agent: 1.8, arcade: 0.9 };+const NOBODY: [string, { x: number; z: number }][] = [];+const NO_PETS = new Set<string>();++describe("stations", () => {+ const agentsFloor = buildOfficeLayout(roster(8));+ const codingFloor = buildOfficeLayout(roster(4), { variant: "coding" });++ it("turns every checkpoint of a floor into one station", () => {+ for (const layout of [agentsFloor, codingFloor]) {+ const stations = stationsFor(layout);+ const checkpoints = stations.filter((s) => s.selection.kind === "checkpoint");+ expect(checkpoints.map((s) => s.selection.id)).toEqual(layout.checkpoints.map((cp) => cp.id));+ expect(new Set(stations.map((s) => s.key)).size).toBe(stations.length);+ // The same plan gives the same list back, so a frame loop can ask every frame.+ expect(stationsFor(layout)).toBe(stations);+ }+ });++ it("binds each station to an object of the room, never to a marker of its own", () => {+ const props = new Map(agentsFloor.furniture.map((f) => [`prop:${f.id}`, f]));+ const kindOf = (id: string) => {+ const station = stationsFor(agentsFloor).find((s) => s.selection.id === id);+ expect(station, id).toBeTruthy();+ return station!.objects.map((name) => props.get(name)?.kind);+ };+ expect(kindOf("spawn")).toEqual(["spawnTerminal"]);+ expect(kindOf("team")).toEqual(["teamBoard"]);+ expect(kindOf("wardrobe")).toEqual(["dressingMirror"]);+ expect(kindOf("break")).toEqual(["coffeeBar"]);+ expect(kindOf("elevator")).toEqual(["elevator"]);+ const codingProps = new Map(codingFloor.furniture.map((f) => [`prop:${f.id}`, f.kind]));+ const codingKind = (id: string) => stationsFor(codingFloor).find((s) => s.selection.id === id)!.objects.map((name) => codingProps.get(name));+ expect(codingKind("launch")).toEqual(["spawnTerminal"]);+ expect(codingKind("mission")).toEqual(["commandWall"]);+ });++ it("gives the reception desk the directory, whatever the plan calls its checkpoint", () => {+ const desks = stationsFor(agentsFloor).filter((s) => isReception(s.selection));+ expect(desks.length).toBeGreaterThan(0);+ for (const desk of desks) {+ expect(desk.id).toBe("manage");+ expect(desk.icon).toBe("reception");+ }+ expect(desks.some((desk) => desk.objects.includes("prop:reception-desk"))).toBe(true);+ expect(isReception({ kind: "checkpoint", id: "team" })).toBe(false);+ expect(isReception({ kind: "agent", id: "manage" })).toBe(false);+ });++ it("sizes a click target to the object's own footprint", () => {+ const terminal = agentsFloor.furniture.find((f) => f.kind === "spawnTerminal")!;+ const spawn = stationsFor(agentsFloor).find((s) => s.selection.id === "spawn")!;+ expect(spawn.hits).toEqual([{+ x: terminal.x, z: terminal.z, y: FURNITURE_SIZE.spawnTerminal.h / 2, rotationY: terminal.rotationY,+ w: FURNITURE_SIZE.spawnTerminal.w, h: FURNITURE_SIZE.spawnTerminal.h, d: FURNITURE_SIZE.spawnTerminal.d,+ }]);+ });++ it("lights the lead's desks and puts their click target on the visitor side, clear of chair and monitors", () => {+ const lead = stationsFor(agentsFloor).find((s) => s.selection.id === "lead")!;+ const desks = agentsFloor.lead.desks;+ expect(desks.length).toBeGreaterThan(0);+ expect(lead.objects).toEqual(desks.map((d) => `desk:${d.id}`));+ lead.hits.forEach((hit, i) => {+ const desk = desks[i]!;+ const seatSide = desk.facing === "north" ? 1 : -1;+ // On the far side of the desk from the chair, and no taller than the desk top.+ expect(Math.sign(hit.z - desk.z)).toBe(-seatSide);+ expect(hit.y + hit.h / 2).toBeLessThan(0.76);+ });+ });++ it("stands the person somewhere they can actually walk to", () => {+ for (const layout of [agentsFloor, codingFloor]) {+ const grid = buildNavGrid(layout);+ for (const station of stationsFor(layout)) {+ const spot = isWalkable(grid, station.approach) ? station.approach : nearestWalkable(grid, station.approach);+ expect(spot, station.key).toBeTruthy();+ expect(Math.hypot(spot!.x - station.approach.x, spot!.z - station.approach.z), station.key).toBeLessThan(1.5);+ }+ }+ });++ it("adds a station for every team studio's board, selected by the board's id", () => {+ const board = { id: "studio-board:dept-0", x: 4, z: -6, facing: 0 };+ const studios: Studio[] = [+ { deptId: "dept-0", teamId: "g1", name: "Launch crew", members: ["a1", "a2"], leadId: null, board, huddleSpotIds: [], centre: { x: 4, z: -3 } },+ { deptId: "dept-1", teamId: null, name: "", members: ["a3"], leadId: null, board: null, huddleSpotIds: [], centre: { x: 9, z: -3 } },+ ];+ const layout: OfficeLayout = { ...agentsFloor, studios };+ const boards = stationsFor(layout).filter((s) => s.selection.kind === "team" && s.id !== TEAM_STAND_STATION);+ expect(boards).toHaveLength(1);+ const station = boards[0]!;+ expect(station.selection).toEqual({ kind: "team", id: board.id });+ expect(station.name).toBe("Launch crew");+ expect(station.objects).toEqual([`prop:${board.id}`]);+ // The person stands in front of the face, where the board looks.+ expect(station.z).toBeGreaterThan(board.z);+ expect(stationOf(layout, { kind: "team", id: board.id })).toBe(station);+ expect(stationOf(layout, { kind: "team", id: "studio-board:gone" })).toBeNull();+ expect(stationOf(layout, { kind: "agent", id: "a1" })).toBeNull();+ // Standing there, E reaches the board.+ expect(nearestInteractable(layout, station, NOBODY, NO_PETS, REACH)).toEqual(station.selection);+ });+});++describe("the free plot's stand", () => {+ // The plan's own stand is taken out, so the stand-in below is the only one.+ const plan = buildOfficeLayout(roster(4));+ const base: OfficeLayout = { ...plan, furniture: plan.furniture.filter((item) => !item.id.startsWith(TEAM_STAND_ID)) };+ // Any piece will do for the plan: the stand is found by its id, not by its kind.+ const stand = { id: `${TEAM_STAND_ID}`, kind: "lobbyLamp" as const, x: 6, z: 4, rotationY: Math.PI / 2, room: "floor" as const };+ const layout: OfficeLayout = { ...base, furniture: [...base.furniture, stand] };++ it("is a station that selects the stand like a board, lights it and takes clicks on it", () => {+ const station = stationsFor(layout).find((s) => s.id === TEAM_STAND_STATION)!;+ expect(station.selection).toEqual({ kind: "team", id: stand.id });+ expect(station.objects).toEqual([`prop:${stand.id}`]);+ expect(station.hits).toEqual([{+ x: stand.x, z: stand.z, y: FURNITURE_SIZE.lobbyLamp.h / 2, rotationY: stand.rotationY,+ w: FURNITURE_SIZE.lobbyLamp.w, h: FURNITURE_SIZE.lobbyLamp.h, d: FURNITURE_SIZE.lobbyLamp.d,+ }]);+ // The person stands in front of its face (rotated a quarter turn: to the east of it).+ expect(station.approach.x).toBeGreaterThan(stand.x + 0.9);+ expect(station.approach.z).toBeCloseTo(stand.z);+ expect(nearestInteractable(layout, station.approach, NOBODY, NO_PETS, REACH)).toEqual(station.selection);+ });++ it("is told apart from a studio's board, and from a plan without one", () => {+ expect(isTeamStand(layout, { kind: "team", id: stand.id })).toBe(true);+ expect(isTeamStand(layout, { kind: "team", id: "studio-board:dept-0" })).toBe(false);+ expect(isTeamStand(layout, { kind: "checkpoint", id: "team" })).toBe(false);+ expect(isTeamStand(base, { kind: "team", id: stand.id })).toBe(false);+ expect(stationsFor(base).some((s) => s.id === TEAM_STAND_STATION)).toBe(false);+ });+});++describe("nearest interactable", () => {+ const layout = buildOfficeLayout(roster(6));+ const spawn = stationsFor(layout).find((s) => s.selection.id === "spawn")!;++ it("is the station whose reach the person stands in", () => {+ expect(nearestInteractable(layout, spawn.approach, NOBODY, NO_PETS, REACH)).toEqual(spawn.selection);+ });++ it("is nothing in the open, outside every reach", () => {+ const far = { x: spawn.x + spawn.radius + 0.6, z: spawn.z };+ const clear = stationsFor(layout).every((s) => Math.hypot(s.x - far.x, s.z - far.z) > s.radius);+ expect(clear).toBe(true);+ expect(nearestInteractable(layout, far, NOBODY, NO_PETS, REACH)).toBeNull();+ });++ it("prefers whoever is closer: an agent at arm's length beats the station behind them", () => {+ const at = spawn.approach;+ const beside: [string, { x: number; z: number }][] = [["a2", { x: at.x + 0.3, z: at.z }]];+ expect(Math.hypot(spawn.x - at.x, spawn.z - at.z)).toBeGreaterThan(0.3);+ expect(nearestInteractable(layout, at, beside, NO_PETS, REACH)).toEqual({ kind: "agent", id: "a2" });+ // The person's own pet walks beside them and is never the target.+ expect(nearestInteractable(layout, at, beside, new Set(["a2"]), REACH)).toEqual(spawn.selection);+ });++ it("offers a game cabinet only from in front of its screen", () => {+ const cabinet = layout.furniture.find((f) => f.kind === "arcade")!;+ const front = { x: cabinet.x + Math.sin(cabinet.rotationY) * 0.85, z: cabinet.z + Math.cos(cabinet.rotationY) * 0.85 };+ expect(nearestInteractable(layout, front, NOBODY, NO_PETS, REACH)).toEqual({ kind: "arcade", id: cabinet.id });+ });+});++describe("station helpers", () => {+ const layout = buildOfficeLayout(roster(3));++ it("keys a selection by kind and id", () => {+ expect(selectionKey({ kind: "checkpoint", id: "team" })).toBe("checkpoint:team");+ expect(selectionKey({ kind: "team", id: "studio-board:d" })).toBe("team:studio-board:d");+ });++ it("dives into the terminal face on the viewer's side", () => {+ const terminal = layout.furniture.find((f) => f.kind === "spawnTerminal")!;+ const south = spawnScreenDive(layout, { x: terminal.x, z: terminal.z + 3 })!;+ const north = spawnScreenDive(layout, { x: terminal.x, z: terminal.z - 3 })!;+ expect(south.target[2]).toBeGreaterThan(terminal.z);+ expect(north.target[2]).toBeLessThan(terminal.z);+ expect(Math.abs(north.facing - south.facing)).toBeCloseTo(Math.PI);+ expect(south.target[1]).toBeLessThan(FURNITURE_SIZE.spawnTerminal.h);+ expect(spawnScreenDive({ ...layout, furniture: [] }, { x: 0, z: 0 })).toBeNull();+ });++ it("gathers a coffee break among the break room's couches", () => {+ const centre = loungeCentre(layout);+ const room = layout.rooms.find((r) => r.kind === "break")!;+ expect(centre.x).toBeGreaterThan(room.minX);+ expect(centre.x).toBeLessThan(room.maxX);+ expect(centre.z).toBeGreaterThan(room.minZ);+ expect(centre.z).toBeLessThan(room.maxZ);+ expect(loungeCentre({ ...layout, spots: [] })).toEqual(layout.spawn);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/stations.ts b/jarvis/ui/web/frontend/src/components/society/office/stations.tsnew file mode 100644index 0000000000..0d118a9e13--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/stations.ts@@ -0,0 +1,276 @@+/**+ * Stations: the things in the office the person can use. A station is never a+ * marker of its own — it IS an object of the room (the reception desk, the+ * spawn terminal, the team board, the wardrobe mirror, the coffee bar, a team+ * studio's board, …). This module binds every checkpoint and every studio+ * board of a floor plan to that object: which scene groups carry its rim,+ * where the invisible click target sits, and where the person stands to use+ * it. Pure and tested; the renderer (StationObjects), the HUD prompt and the+ * player's nearest-interactable test all read this one list.+ */+import { FURNITURE_SIZE, type Checkpoint, type Furniture, type FurnitureKind, type OfficeLayout, type Point } from "./officeLayout";+import type { Selection } from "./officeStore";++export type StationIcon = "spawn" | "launch" | "reception" | "team" | "wardrobe" | "lead" | "break" | "elevator" | "mission" | "studio" | "levels";++/** A box in world space: centre, size (x-extent × height × z-extent before rotation) and rotation about +y. */+export interface StationBox { x: number; y: number; z: number; w: number; h: number; d: number; rotationY: number }++export interface Station {+ /** Stable React key and lookup id: `<selection kind>:<selection id>`. */+ key: string;+ /** What using the station selects. */+ selection: Selection;+ icon: StationIcon;+ /** The i18n id of its name and action (`cp_<id>`, `use_<id>`): the checkpoint id, or `board` for a studio board. */+ id: string;+ /** A studio board is called after its team; every other station is named by its i18n key. */+ name: string | null;+ /** Centre and radius of the place where E reaches the station. */+ x: number;+ z: number;+ radius: number;+ /** Where "walk there" ends. */+ approach: Point;+ /** Names of the scene groups that are the station (`prop:<furniture id>`, `desk:<desk id>`); they light up. */+ objects: string[];+ /** Invisible click and hover targets; empty when nothing in the room stands for the station. */+ hits: StationBox[];+}++/**+ * The furniture kind that stands for each checkpoint, most typical first. The+ * piece of one of these kinds nearest to the checkpoint is the station, so a+ * floor plan may rename or move its pieces without touching this table.+ */+const STATION_PROPS: Readonly<Record<string, readonly FurnitureKind[]>> = {+ spawn: ["spawnTerminal"],+ launch: ["spawnTerminal"],+ manage: ["receptionDesk", "agentTotem"],+ create: ["receptionDesk"],+ team: ["teamBoard"],+ wardrobe: ["dressingMirror", "mirror"],+ break: ["coffeeBar"],+ elevator: ["elevator"],+ mission: ["commandWall"],+ studio: ["studioStage"],+ levels: ["levelGuide"],+};++const STATION_ICONS: Readonly<Record<string, StationIcon>> = {+ spawn: "spawn", launch: "launch", manage: "reception", team: "team", wardrobe: "wardrobe", lead: "lead", break: "break",+ elevator: "elevator", mission: "mission", studio: "studio", levels: "levels",+};++/** A flat piece (a stage, a pad) still needs something a pointer can hit. */+const MIN_HIT_HEIGHT = 0.12;+/** The lead desk's click target is its visitor-side front panel, so the monitors and the chair keep their own clicks. */+const DESK_FRONT = { h: 0.74, d: 0.1, gap: 0.04 } as const;+const DEFAULT_LEAD_DESK = { w: 2.4, d: 1.05 } as const;+/** How far in front of a studio board the person stands, and how far around that spot E reaches. */+export const BOARD_STAND_M = 1.05;+export const BOARD_REACH_M = 1.25;++export function selectionKey(selection: Selection): string {+ return `${selection.kind}:${selection.id}`;+}++function boxOf(item: Furniture): StationBox {+ const size = FURNITURE_SIZE[item.kind];+ const h = Math.max(size.h, MIN_HIT_HEIGHT);+ return { x: item.x, y: h / 2, z: item.z, w: item.size?.w ?? size.w, h, d: item.size?.d ?? size.d, rotationY: item.rotationY };+}++function propFor(layout: OfficeLayout, checkpoint: Checkpoint): Furniture | null {+ const kinds = STATION_PROPS[checkpoint.id];+ if (!kinds) return null;+ let best: Furniture | null = null;+ let bestDistance = Infinity;+ for (const item of layout.furniture) {+ if (!kinds.includes(item.kind)) continue;+ const d = Math.hypot(item.x - checkpoint.x, item.z - checkpoint.z);+ if (d < bestDistance) { best = item; bestDistance = d; }+ }+ return best;+}++/** The reception desk is one station whatever a floor plan calls its checkpoint. */+const RECEPTION_IDS: ReadonlySet<string> = new Set(["manage", "create"]);++/** Is this selection the reception (the directory)? */+export function isReception(selection: Selection | null): boolean {+ return selection?.kind === "checkpoint" && RECEPTION_IDS.has(selection.id);+}++function checkpointStation(layout: OfficeLayout, checkpoint: Checkpoint): Station {+ const id = RECEPTION_IDS.has(checkpoint.id) ? "manage" : checkpoint.id as string;+ const base = {+ key: `checkpoint:${checkpoint.id}`,+ selection: { kind: "checkpoint", id: checkpoint.id } as Selection,+ icon: STATION_ICONS[id] ?? "reception",+ id,+ name: null,+ x: checkpoint.x, z: checkpoint.z, radius: checkpoint.radius,+ approach: checkpoint.approach ?? { x: checkpoint.x, z: checkpoint.z },+ };+ if (checkpoint.id === "lead") {+ // The lead's desks are desk slots, not furniture: each one is drawn under a `desk:<id>` group.+ const desks = layout.lead.desks;+ return {+ ...base,+ objects: desks.map((desk) => `desk:${desk.id}`),+ hits: desks.map((desk) => {+ const size = desk.size ?? DEFAULT_LEAD_DESK;+ // The seated lead looks at its monitors; visitors stand on the far side of the desk from the chair.+ const towardsVisitor = desk.facing === "north" ? -1 : 1;+ return {+ x: desk.x, y: DESK_FRONT.h / 2, z: desk.z + towardsVisitor * (size.d / 2 + DESK_FRONT.gap),+ w: size.w, h: DESK_FRONT.h, d: DESK_FRONT.d, rotationY: 0,+ };+ }),+ };+ }+ const prop = propFor(layout, checkpoint);+ return { ...base, objects: prop ? [`prop:${prop.id}`] : [], hits: prop ? [boxOf(prop)] : [] };+}++function boardStations(layout: OfficeLayout): Station[] {+ const out: Station[] = [];+ for (const studio of layout.studios ?? []) {+ const board = studio.board;+ if (!board) continue;+ const item = layout.furniture.find((f) => f.id === board.id);+ const size = FURNITURE_SIZE.studioBoard;+ const front = { x: board.x + Math.sin(board.facing) * BOARD_STAND_M, z: board.z + Math.cos(board.facing) * BOARD_STAND_M };+ out.push({+ key: `team:${board.id}`,+ selection: { kind: "team", id: board.id },+ icon: "team",+ id: "board",+ name: studio.name || null,+ x: front.x, z: front.z, radius: BOARD_REACH_M,+ approach: front,+ objects: [`prop:${board.id}`],+ hits: [item ? boxOf(item) : { x: board.x, y: size.h / 2, z: board.z, w: size.w, h: size.h, d: size.d, rotationY: board.facing }],+ });+ }+ return out;+}++/**+ * The free plot's stand ("start a team here"): the furniture piece whose id starts with this, whatever its kind.+ * Its station selects `{ kind: "team", id: <furniture id> }` like a studio board, but there is no team behind it+ * yet: it opens the new-team form.+ */+export const TEAM_STAND_ID = "team-stand";+/** The i18n id of the stand's station (`cp_found`, `use_found`). */+export const TEAM_STAND_STATION = "found";+/** How far in front of the stand's face the person stands. */+const STAND_FRONT_M = 0.95;++function standStations(layout: OfficeLayout): Station[] {+ return layout.furniture.filter((item) => item.id.startsWith(TEAM_STAND_ID)).map((item) => {+ const box = boxOf(item);+ const reach = box.d / 2 + STAND_FRONT_M;+ // A piece's front faces its local +z (rotationY 0 = south, towards the camera).+ const front = { x: item.x + Math.sin(item.rotationY) * reach, z: item.z + Math.cos(item.rotationY) * reach };+ return {+ key: `team:${item.id}`,+ selection: { kind: "team", id: item.id } as Selection,+ icon: "team" as const,+ id: TEAM_STAND_STATION,+ name: null,+ x: front.x, z: front.z, radius: BOARD_REACH_M,+ approach: front,+ objects: [`prop:${item.id}`],+ hits: [box],+ };+ });+}++/** Is this selection the free plot's stand, where a new team is started? */+export function isTeamStand(layout: OfficeLayout, selection: Selection | null): boolean {+ return stationOf(layout, selection)?.id === TEAM_STAND_STATION;+}++const cache = new WeakMap<OfficeLayout, Station[]>();++/** Every station of a floor plan: its checkpoints first, then the team studios' boards and the free plot's stand. Cached per plan. */+export function stationsFor(layout: OfficeLayout): Station[] {+ let stations = cache.get(layout);+ if (!stations) {+ stations = [...layout.checkpoints.map((checkpoint) => checkpointStation(layout, checkpoint)), ...boardStations(layout), ...standStations(layout)];+ cache.set(layout, stations);+ }+ return stations;+}++export function stationOf(layout: OfficeLayout, selection: Selection | null): Station | null {+ if (!selection || (selection.kind !== "checkpoint" && selection.kind !== "team")) return null;+ const key = selectionKey(selection);+ return stationsFor(layout).find((station) => station.key === key) ?? null;+}++/** How long called agents (one called over, a coffee break) stay before they drift back to their day. */+export const CALL_MS = 25_000;++/** Game cabinets are played standing this far in front of the screen (it faces the cabinet's local +z). */+const CABINET_STAND_M = 0.85;++/**+ * The closest thing the person can use from where they stand (E): a station+ * whose reach they are in, an agent within talking range, or a game cabinet+ * they stand in front of. `agents` are the walkers' positions; `skip` are+ * agents that keep the person company (their pet), which are never a target.+ */+export function nearestInteractable(+ layout: OfficeLayout, at: Point, agents: Iterable<readonly [string, Point]>, skip: { has: (id: string) => boolean },+ ranges: { agent: number; arcade: number },+): Selection | null {+ let best: Selection | null = null;+ let bestDistance = Infinity;+ for (const station of stationsFor(layout)) {+ const d = Math.hypot(station.x - at.x, station.z - at.z);+ if (d <= station.radius && d < bestDistance) { best = station.selection; bestDistance = d; }+ }+ for (const [id, p] of agents) {+ if (skip.has(id)) continue;+ const d = Math.hypot(p.x - at.x, p.z - at.z);+ if (d <= ranges.agent && d < bestDistance) { best = { kind: "agent", id }; bestDistance = d; }+ }+ for (const item of layout.furniture) {+ // The break room's cabinet, and every game cabinet on the arcade floor.+ if (item.kind !== "arcade" && item.kind !== "retroCabinet") continue;+ const fx = item.x + Math.sin(item.rotationY) * CABINET_STAND_M, fz = item.z + Math.cos(item.rotationY) * CABINET_STAND_M;+ const d = Math.hypot(fx - at.x, fz - at.z);+ if (d <= ranges.arcade && d < bestDistance) { best = { kind: "arcade", id: item.id }; bestDistance = d; }+ }+ return best;+}++/**+ * The spawn terminal's screen, in the terminal's own frame (SpawnPoint.tsx+ * draws it there): the camera dives into it before the create dialog opens.+ */+export const SPAWN_SCREEN = { y: 1.42, z: 0.0355, w: 0.86, h: 0.58 } as const;++/** The screen face of the spawn terminal that looks at `viewer`, as a dive target; null on a floor without a terminal. */+export function spawnScreenDive(layout: OfficeLayout, viewer: Point): { target: [number, number, number]; facing: number; size: [number, number] } | null {+ const terminal = layout.furniture.find((f) => f.kind === "spawnTerminal");+ if (!terminal) return null;+ const sin = Math.sin(terminal.rotationY), cos = Math.cos(terminal.rotationY);+ // The terminal is double-sided: take the face on the viewer's side.+ const side = (viewer.x - terminal.x) * sin + (viewer.z - terminal.z) * cos >= 0 ? 1 : -1;+ return {+ target: [terminal.x + sin * SPAWN_SCREEN.z * side, SPAWN_SCREEN.y, terminal.z + cos * SPAWN_SCREEN.z * side],+ facing: terminal.rotationY + (side === 1 ? 0 : Math.PI),+ size: [SPAWN_SCREEN.w, SPAWN_SCREEN.h],+ };+}++/** The middle of the break room's couches, where a coffee break gathers; the floor's entrance on a floor without any. */+export function loungeCentre(layout: OfficeLayout): Point {+ const couches = layout.spots.filter((spot) => spot.kind === "couch" && spot.room === "break");+ if (couches.length === 0) return layout.spawn;+ return { x: couches.reduce((sum, p) => sum + p.x, 0) / couches.length, z: couches.reduce((sum, p) => sum + p.z, 0) / couches.length };+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/studioBoardContent.test.ts b/jarvis/ui/web/frontend/src/components/society/office/studioBoardContent.test.tsnew file mode 100644index 0000000000..f1b5c93bdd--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/studioBoardContent.test.ts@@ -0,0 +1,123 @@+import { describe, expect, it } from "vitest";+import type { AgentRunState } from "../data";+import { emptyRound, type TeamRound } from "./teamwork";+import {+ MAX_BOARD_LINES, MAX_BOARD_MEMBERS, MAX_LIVE_BOARDS, boardModel, boardSignature, pickBoards, type BoardLabels,+} from "./studioBoardContent";++const labels: BoardLabels = {+ pool: "Open studio", members: "{0} members", live: "Live", speaking: "Speaking", you: "You",+ empty: "Nothing has been said yet.", poolNote: "No team yet.", loading: "Reading…", unavailable: "Cannot be read.", lead: "Lead: {0}", more: "+{0} more",+ state: { working: "Working", waiting: "Waiting", idle: "Idle", paused: "Paused" },+};+const agent = (name: string, state: AgentRunState) => ({ name, state });+const agents = new Map([["nora", agent("Nora", "working")], ["ben", agent("Ben", "idle")], ["kai", agent("Kai", "waiting")], ["zoe", agent("Zoe", "paused")]]);+const studio = { name: "Launch crew", teamId: "t", members: ["nora", "ben", "kai"] };+const round = (extra: Partial<TeamRound>): TeamRound => ({ ...emptyRound("t"), loaded: true, ...extra });++describe("what a studio board shows", () => {+ it("names the team and lists its members with the state each is really in", () => {+ const model = boardModel(studio, agents, round({}), labels);+ expect(model).toMatchObject({ title: "Launch crew", count: "3 members", live: false, hidden: 0 });+ expect(model.members).toEqual([+ { id: "nora", name: "Nora", state: "working", speaking: false, lead: false },+ { id: "ben", name: "Ben", state: "idle", speaking: false, lead: false },+ { id: "kai", name: "Kai", state: "waiting", speaking: false, lead: false },+ ]);+ });++ it("marks a running round and the member contributing to it", () => {+ const model = boardModel(studio, agents, round({ running: true, speakerId: "nora" }), labels);+ expect(model.live).toBe(true);+ expect(model.members.map((m) => m.speaking)).toEqual([true, false, false]);+ // A speaker left over from a settled round is nobody's turn.+ expect(boardModel(studio, agents, round({ running: false, speakerId: "nora" }), labels).members.some((m) => m.speaking)).toBe(false);+ });++ it("shows the newest real lines of the team's chat, the person's as theirs, in plain text", () => {+ const lines = Array.from({ length: 9 }, (_, i) => ({ id: `e${i}`, speaker: i % 3 === 0 ? "user" : "nora", text: `**line** ${i} with a [link](https://example.test)` }));+ const model = boardModel(studio, agents, round({ lines }), labels);+ expect(model.lines).toHaveLength(MAX_BOARD_LINES);+ expect(model.lines[model.lines.length - 1]).toEqual({ id: "e8", who: "Nora", text: "line 8 with a link", fromPerson: false });+ expect(model.lines.find((l) => l.fromPerson)?.who).toBe("You");+ expect(model.note).toBeNull();+ });++ it("is honest when there is nothing to show", () => {+ expect(boardModel(studio, agents, round({}), labels).note).toBe(labels.empty);+ expect(boardModel(studio, agents, undefined, labels).note).toBe(labels.loading);+ expect(boardModel(studio, agents, { ...emptyRound("t") }, labels).note).toBe(labels.loading);+ // A team whose chat could never be read says so instead of "reading" for ever.+ expect(boardModel(studio, agents, { ...emptyRound("t"), unavailable: true }, labels).note).toBe(labels.unavailable);+ // What was read before a failure stays on the board.+ expect(boardModel(studio, agents, round({ unavailable: true, lines: [{ id: "e1", speaker: "nora", text: "hi" }] }), labels).note).toBeNull();+ // The pool has no team chat: it says so, and never borrows lines.+ const pool = boardModel({ name: "", teamId: null, members: ["zoe"] }, agents, round({ lines: [{ id: "e1", speaker: "nora", text: "hi" }] }), labels);+ expect(pool).toMatchObject({ title: "Open studio", note: labels.poolNote, lines: [], count: "1 members" });+ });++ it("adds team members who sit in another studio, skips who left the roster, and counts who does not fit", () => {+ const model = boardModel(studio, agents, round({ members: ["nora", "zoe", "gone"] }), labels);+ expect(model.members.map((m) => m.id)).toEqual(["nora", "ben", "kai", "zoe"]);+ const crowd = new Map(Array.from({ length: 9 }, (_, i) => [`m${i}`, agent(`M${i}`, "idle")] as const));+ const big = boardModel({ name: "Big", teamId: "t", members: [...crowd.keys()] }, crowd, round({}), labels);+ expect(big.members).toHaveLength(MAX_BOARD_MEMBERS);+ expect(big.hidden).toBe(9 - MAX_BOARD_MEMBERS);+ expect(big.count).toBe("9 members");+ });++ it("changes its signature only when the face would look different", () => {+ const a = boardModel(studio, agents, round({ lines: [{ id: "e1", speaker: "nora", text: "hi" }] }), labels);+ const same = boardModel(studio, new Map(agents), round({ lines: [{ id: "e1", speaker: "nora", text: "hi" }], fetchedMs: 999, dirty: true }), labels);+ expect(boardSignature(same, labels)).toBe(boardSignature(a, labels));+ const busy = new Map(agents).set("ben", agent("Ben", "working"));+ expect(boardSignature(boardModel(studio, busy, round({ lines: [{ id: "e1", speaker: "nora", text: "hi" }] }), labels), labels)).not.toBe(boardSignature(a, labels));+ expect(boardSignature(boardModel(studio, agents, round({ running: true, lines: [{ id: "e1", speaker: "nora", text: "hi" }] }), labels), labels)).not.toBe(boardSignature(a, labels));+ });+});++describe("a team with a lead", () => {+ it("lists the lead first and marks it, whatever its seat", () => {+ const model = boardModel({ ...studio, leadId: "kai" }, agents, round({}), labels);+ expect(model.members.map((m) => [m.id, m.lead])).toEqual([["kai", true], ["nora", false], ["ben", false]]);+ expect(model.count).toBe("3 members");+ // A lead that sits in another studio is still this team's lead while its round lists it.+ const elsewhere = boardModel({ ...studio, leadId: "zoe" }, agents, round({ members: ["nora", "zoe"] }), labels);+ expect(elsewhere.members.map((m) => [m.id, m.lead])).toEqual([["zoe", true], ["nora", false], ["ben", false], ["kai", false]]);+ // The mark changes the face.+ expect(boardSignature(model, labels)).not.toBe(boardSignature(boardModel(studio, agents, round({}), labels), labels));+ });++ it("keeps the lead in view on a team larger than the list", () => {+ const crowd = new Map(Array.from({ length: 9 }, (_, i) => [`m${i}`, agent(`M${i}`, "idle")] as const));+ const big = boardModel({ name: "Big", teamId: "t", members: [...crowd.keys()], leadId: "m8" }, crowd, round({}), labels);+ expect(big.members[0]).toMatchObject({ id: "m8", lead: true });+ expect(big.members).toHaveLength(MAX_BOARD_MEMBERS);+ });++ it("is the board it always was without one, or when the lead is not on the roster", () => {+ const plain = boardModel(studio, agents, round({}), labels);+ for (const leadId of [null, undefined, "stranger", ""]) {+ const model = boardModel({ ...studio, leadId }, agents, round({}), labels);+ expect(model).toEqual(plain);+ expect(boardSignature(model, labels)).toBe(boardSignature(plain, labels));+ }+ expect(plain.members.some((m) => m.lead)).toBe(false);+ });+});++describe("which boards are live", () => {+ it("draws the boards in view and keeps only the nearest few teams current", () => {+ const boards = [+ { id: "b-pool", teamId: null, distance: 5 }, { id: "b1", teamId: "t1", distance: 12 }, { id: "b2", teamId: "t2", distance: 8 },+ { id: "b3", teamId: "t3", distance: 20 }, { id: "b4", teamId: "t4", distance: 25 }, { id: "b5", teamId: "t5", distance: 45 }, { id: "b6", teamId: "t6", distance: 90 },+ ];+ const { drawn, live } = pickBoards(boards);+ expect([...drawn].sort()).toEqual(["b-pool", "b1", "b2", "b3", "b4", "b5"]);+ expect([...live]).toEqual(["t2", "t1", "t3"]);+ expect(live.size).toBe(MAX_LIVE_BOARDS);+ });+ it("keeps nothing live from the overview", () => {+ expect(pickBoards([{ id: "b1", teamId: "t1", distance: 120 }])).toEqual({ drawn: new Set(), live: new Set() });+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/studioBoardContent.ts b/jarvis/ui/web/frontend/src/components/society/office/studioBoardContent.tsnew file mode 100644index 0000000000..8c89e85d99--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/studioBoardContent.ts@@ -0,0 +1,216 @@+/**+ * What a studio board shows: the team's name, its members with their real+ * run state, and the newest real lines of the team's chat — or an honest+ * empty state. The model is pure and tested; the drawing puts it on a canvas.+ */+import type { AgentRunState, SocietyAgent } from "../data";+import type { Studio } from "./officeLayout";+import { bubbleText } from "./officeTalk";+import type { TeamRound } from "./teamwork";++/** The live content lies this far in front of the board's own paper face (`studioBoardFace` in the layout). */+export const BOARD_LIFT_M = 0.012;+/** The canvas, in the face's proportion (2.16 m × 1.16 m). */+export const BOARD_CANVAS = { w: 1024, h: 550 } as const;++/** Boards within this camera distance are drawn; nearer than BOARD_LIVE_RANGE_M they are also kept current. */+export const BOARD_DRAW_RANGE_M = 60;+export const BOARD_LIVE_RANGE_M = 30;+/** At most this many boards are live at once: the nearest ones. */+export const MAX_LIVE_BOARDS = 3;++/**+ * Which boards to draw (their ids) and which teams to keep live (their team ids), from each board's distance to+ * the camera. A pool studio's board is drawn but never live: it has no team chat to read.+ */+export function pickBoards(boards: readonly { id: string; teamId: string | null; distance: number }[]): { drawn: Set<string>; live: Set<string> } {+ const drawn = new Set(boards.filter((b) => b.distance <= BOARD_DRAW_RANGE_M).map((b) => b.id));+ const live = new Set(boards.filter((b) => b.teamId !== null && b.distance <= BOARD_LIVE_RANGE_M)+ .sort((a, b) => a.distance - b.distance || a.id.localeCompare(b.id)).slice(0, MAX_LIVE_BOARDS).map((b) => b.teamId as string));+ return { drawn, live };+}++/** Rows that fit the member column, and chat lines the model keeps for the other one. */+export const MAX_BOARD_MEMBERS = 6;+export const MAX_BOARD_LINES = 5;++export interface BoardLabels {+ /** Title of a studio without a name of its own (the pool). */+ pool: string;+ /** "{0} members" */+ members: string;+ live: string;+ speaking: string;+ you: string;+ /** A team whose chat holds nothing yet. */+ empty: string;+ /** The pool studio: there is no team chat to show. */+ poolNote: string;+ /** The transcript has not been read yet. */+ loading: string;+ /** The transcript cannot be read right now. */+ unavailable: string;+ /** How the team's lead is named in the member list: "Lead: {0}". */+ lead: string;+ /** "+{0} more" */+ more: string;+ state: Record<AgentRunState, string>;+}++export interface BoardMember { id: string; name: string; state: AgentRunState; speaking: boolean; /** The team's lead, listed first. */ lead: boolean }+export interface BoardLine { id: string; who: string; text: string; fromPerson: boolean }++export interface BoardModel {+ title: string;+ count: string;+ /** A round is answering right now. */+ live: boolean;+ members: BoardMember[];+ /** Members that did not fit the column. */+ hidden: number;+ lines: BoardLine[];+ /** Shown instead of chat lines when there are none. */+ note: string | null;+}++export function boardModel(+ studio: Pick<Studio, "name" | "teamId" | "members"> & { leadId?: string | null }, agents: ReadonlyMap<string, Pick<SocietyAgent, "name" | "state">>,+ round: TeamRound | undefined, labels: BoardLabels,+): BoardModel {+ // Everyone seated here, then team members who sit elsewhere (an agent can be in several teams).+ const listed = [...studio.members, ...(round?.members ?? []).filter((id) => !studio.members.includes(id))];+ // The team's lead, when it has one among its members, comes first.+ const leadId = studio.leadId && listed.includes(studio.leadId) ? studio.leadId : null;+ const ids = leadId ? [leadId, ...listed.filter((id) => id !== leadId)] : listed;+ const present = ids.flatMap((id) => {+ const agent = agents.get(id);+ return agent ? [{ id, name: agent.name, state: agent.state, speaking: !!round?.running && round.speakerId === id, lead: id === leadId }] : [];+ });+ const lines: BoardLine[] = (round?.lines ?? []).slice(-MAX_BOARD_LINES).map((line) => ({+ id: line.id, fromPerson: line.speaker === "user",+ who: line.speaker === "user" ? labels.you : agents.get(line.speaker)?.name ?? "—",+ text: bubbleText(line.text, 170),+ }));+ let note: string | null = null;+ if (studio.teamId === null) note = labels.poolNote;+ else if (!round?.loaded && lines.length === 0) note = round?.unavailable ? labels.unavailable : labels.loading;+ else if (lines.length === 0) note = labels.empty;+ return {+ title: studio.name.trim() || labels.pool,+ count: labels.members.replace("{0}", String(present.length)),+ live: !!round?.running,+ members: present.slice(0, MAX_BOARD_MEMBERS),+ hidden: Math.max(0, present.length - MAX_BOARD_MEMBERS),+ lines: studio.teamId === null ? [] : lines,+ note,+ };+}++/** A cheap identity for "does the face need a redraw". */+export function boardSignature(model: BoardModel, labels: BoardLabels): string {+ return JSON.stringify([model.title, model.count, model.live, model.hidden, model.note,+ model.members.map((m) => [m.name, m.state, m.speaking, m.lead]), model.lines.map((l) => [l.id, l.who, l.text]),+ labels.live, labels.speaking, labels.more, labels.state, labels.lead]);+}++/** Ink on the board's paper face: the same sheet the board shows at rest, now written on. */+const PAPER = { sheet: "#f6f3ec", dots: "rgba(60,56,50,0.16)", ink: "#1f2430", soft: "#5b6475", faint: "#8a8f98", rule: "#3b4250", live: "#2f9e5b", person: "#2f6fd0" } as const;+const STATE_COLOUR: Record<AgentRunState, string> = { working: "#2f9e5b", waiting: "#c98a12", idle: "#8a8f98", paused: "#b9bcc2" };+const FONT = "system-ui, -apple-system, 'Segoe UI', sans-serif";++function clipped(ctx: CanvasRenderingContext2D, text: string, maxWidth: number): string {+ if (ctx.measureText(text).width <= maxWidth) return text;+ let cut = text;+ while (cut.length > 1 && ctx.measureText(`${cut}…`).width > maxWidth) cut = cut.slice(0, -1);+ return `${cut.trimEnd()}…`;+}++function wrap(ctx: CanvasRenderingContext2D, text: string, width: number, maxRows: number): string[] {+ const rows: string[] = [];+ let row = "";+ for (const word of text.split(" ")) {+ 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);+ if (rows.length <= maxRows) return rows;+ const kept = rows.slice(0, maxRows);+ kept[maxRows - 1] = clipped(ctx, `${kept[maxRows - 1]} …`, width);+ return kept;+}++export function drawStudioBoard(ctx: CanvasRenderingContext2D, model: BoardModel, labels: BoardLabels): void {+ const { w: W, h: H } = BOARD_CANVAS;+ ctx.fillStyle = PAPER.sheet;+ ctx.fillRect(0, 0, W, H);+ ctx.fillStyle = PAPER.dots;+ for (let y = 28; y < H; y += 47) for (let x = 28; x < W; x += 47) ctx.fillRect(x, y, 4, 4);+ // Header: the team's name, and whether a round is answering.+ ctx.fillStyle = PAPER.rule;+ ctx.fillRect(36, 90, W - 72, 4);+ ctx.textBaseline = "middle";+ ctx.textAlign = "left";+ ctx.font = `600 28px ${FONT}`;+ const right = model.live ? labels.live : model.count;+ const rightW = ctx.measureText(right).width;+ if (model.live) {+ ctx.fillStyle = PAPER.live;+ ctx.beginPath();+ ctx.roundRect(W - 36 - rightW - 44, 24, rightW + 44, 44, 22);+ ctx.fill();+ ctx.fillStyle = "#ffffff";+ ctx.fillText(right, W - 36 - rightW - 22, 47);+ } else {+ ctx.fillStyle = PAPER.soft;+ ctx.fillText(right, W - 36 - rightW, 47);+ }+ ctx.fillStyle = PAPER.ink;+ ctx.font = `700 42px ${FONT}`;+ ctx.fillText(clipped(ctx, model.title, W - 72 - rightW - 80), 36, 48);++ // Left: the members and what each is really doing.+ const colW = 340, rowH = 68, top = 112;+ model.members.forEach((member, i) => {+ const y = top + i * rowH + rowH / 2;+ ctx.fillStyle = member.speaking ? PAPER.live : STATE_COLOUR[member.state];+ ctx.beginPath(); ctx.arc(50, y, 10, 0, Math.PI * 2); ctx.fill();+ ctx.fillStyle = PAPER.ink;+ ctx.font = `600 29px ${FONT}`;+ ctx.fillText(clipped(ctx, member.lead ? labels.lead.replace("{0}", member.name) : member.name, colW - 60), 76, y - 12);+ ctx.fillStyle = member.speaking ? PAPER.live : PAPER.soft;+ ctx.font = `500 21px ${FONT}`;+ ctx.fillText(clipped(ctx, member.speaking ? labels.speaking : labels.state[member.state], colW - 60), 76, y + 17);+ });+ if (model.hidden > 0) {+ ctx.fillStyle = PAPER.faint;+ ctx.font = `500 22px ${FONT}`;+ ctx.fillText(labels.more.replace("{0}", String(model.hidden)), 76, H - 22);+ }+ ctx.fillStyle = "rgba(59,66,80,0.28)";+ ctx.fillRect(colW + 44, 112, 2, H - 136);++ // Right: the newest lines of the team's chat, the latest at the bottom.+ const left = colW + 72, width = W - left - 36, lineH = 31;+ if (model.lines.length === 0) {+ if (!model.note) return;+ ctx.fillStyle = PAPER.soft;+ ctx.font = `500 27px ${FONT}`;+ wrap(ctx, model.note, width, 4).forEach((row, i) => ctx.fillText(row, left, 150 + i * 36));+ return;+ }+ ctx.font = `500 25px ${FONT}`;+ const blocks = model.lines.map((line) => ({ line, rows: wrap(ctx, line.text, width, 3) }));+ let y = H - 22;+ for (let i = blocks.length - 1; i >= 0; i -= 1) {+ const { line, rows } = blocks[i];+ const height = 30 + rows.length * lineH + 10;+ if (y - height < 104) break;+ y -= height;+ ctx.fillStyle = line.fromPerson ? PAPER.person : PAPER.ink;+ ctx.font = `700 23px ${FONT}`;+ ctx.fillText(clipped(ctx, line.who, width), left, y + 15);+ ctx.fillStyle = PAPER.soft;+ ctx.font = `500 25px ${FONT}`;+ rows.forEach((row, r) => ctx.fillText(row, left, y + 30 + r * lineH + lineH / 2));+ }+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/teamMeeting.test.ts b/jarvis/ui/web/frontend/src/components/society/office/teamMeeting.test.tsindex fbd70bc7b7..1cf2500e50 100644--- a/jarvis/ui/web/frontend/src/components/society/office/teamMeeting.test.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/teamMeeting.test.ts@@ -1,9 +1,11 @@import { describe, expect, it } from "vitest";+import { huddlePlaces, studioOfTeam } from "./officeTeams";+import { campusOf } from "./officeFixtures";import type { SocietyAgent } from "../data";import { allDesks, buildOfficeLayout, type OfficeAgentInput } from "./officeLayout";import { buildNavGrid, isWalkable } from "./officeNav";import { createRng, planFor, SpotBook, type PlanInput } from "./officeBehavior";-import { MEETING_MS, meetingProgress, meetingSeats, minutesLeft } from "./teamMeeting";+import { boardSeats, MEETING_MS, meetingProgress, meetingSeats, minutesLeft } from "./teamMeeting";import type { TeamMeeting } from "./officeStore";const roster: OfficeAgentInput[] = Array.from({ length: 9 }, (_, i) => ({@@ -92,3 +94,78 @@ describe("meetingProgress", () => {expect(minutesLeft(meeting, 2_000 + MEETING_MS)).toBe(0);});});++describe("a meeting at a studio's own board", () => {+ const campus = campusOf(12, [5]);+ const studio = studioOfTeam(campus.layout, "team-0")!;+ const places = huddlePlaces(campus.layout, campus.grid, studio);++ it("gives every member a place in the arcs, the arc nearest the board first", () => {+ const seats = boardSeats(campus.layout, studio, studio.members);+ expect(Object.keys(seats)).toEqual(studio.members);+ const ids = Object.values(seats).map((s) => s.spotId);+ expect(new Set(ids).size).toBe(studio.members.length);+ const from = (id: string) => { const seat = seats[id].target; return Math.hypot(seat.x - studio.board!.x, seat.z - studio.board!.z); };+ for (let i = 1; i < studio.members.length; i += 1) expect(from(studio.members[i])).toBeGreaterThanOrEqual(from(studio.members[i - 1]) - 0.11);+ for (const seat of Object.values(seats)) expect(places.some((p) => p.id === seat.spotId && p.x === seat.target.x && p.z === seat.target.z)).toBe(true);+ });++ it("leaves members beyond the places where they are, and has none for a studio without a board", () => {+ const crowd = Array.from({ length: places.length + 3 }, (_, i) => `m${i}`);+ expect(Object.keys(boardSeats(campus.layout, studio, crowd, campus.grid))).toHaveLength(places.length);+ // Both argument orders name the same places.+ expect(boardSeats(campus.layout, campus.grid, studio, studio.members)).toEqual(boardSeats(campus.layout, studio, studio.members, campus.grid));+ expect(boardSeats(campus.layout, null, studio, studio.members)).toEqual(boardSeats(campus.layout, studio, studio.members));+ expect(boardSeats(campus.layout, { ...studio, board: null }, studio.members, null)).toEqual({});+ });++ it("stands a called member on its place at the board, facing it, and leaves a working one at its screen", () => {+ const seats = boardSeats(campus.layout, studio, studio.members);+ const book = new SpotBook();+ const desks = campus.layout.departments.flatMap((d) => d.desks);+ const plan = (id: string, state: "idle" | "working") => planFor({+ agentId: id, state, desk: desks.find((d) => d.agentId === id) ?? null, layout: campus.layout, grid: campus.grid, rng: createRng(id), book,+ previous: null, workingColleagues: [], calledTo: seats[id].target, calledSeat: seats[id].spotId,+ });+ const first = plan(studio.members[0], "idle");+ const place = places.find((p) => p.id === seats[studio.members[0]].spotId)!;+ expect(first).toMatchObject({ kind: "huddle", pose: "stand", dwellMs: Infinity, spotId: place.id, target: { x: place.x, z: place.z } });+ expect(first.facing).toBeCloseTo(place.facing);+ expect(plan(studio.members[1], "working").kind).toBe("work");+ // The chairs at the team room's table stay free: this meeting is not there.+ expect(campus.layout.spots.filter((s) => s.kind === "meeting").every((s) => book.isFree(s.id))).toBe(true);+ });+});++describe("a board meeting of a team with a lead", () => {+ const led = campusOf(12, [5], [3]);+ const studio = studioOfTeam(led.layout, "team-0")!;+ const places = huddlePlaces(led.layout, led.grid, studio);++ it("gives the lead the centre of the front arc, wherever it comes in the list, and everybody else a place of their own", () => {+ const lead = studio.leadId!;+ expect(lead).toBe(led.teams[0].members[3]);+ const seats = boardSeats(led.layout, studio, studio.members);+ expect(seats[lead].spotId).toBe(`fan:${studio.deptId}:0:0`);+ const ids = Object.values(seats).map((s) => s.spotId);+ expect(new Set(ids).size).toBe(studio.members.length);+ expect(ids.every((id) => places.some((p) => p.id === id))).toBe(true);+ });++ it("uses the lead's place for somebody else when the lead is not among those called", () => {+ const withoutLead = studio.members.filter((id) => id !== studio.leadId);+ const seats = boardSeats(led.layout, studio, withoutLead);+ expect(Object.keys(seats)).toEqual(withoutLead);+ expect(Object.values(seats).map((s) => s.spotId)).toContain(`fan:${studio.deptId}:0:0`);+ });++ it("is the same seating as ever for a team without a lead", () => {+ const plain = { ...studio, leadId: null };+ const before = boardSeats(led.layout, plain, studio.members);+ // The first member takes the first place of the front arc, as it always did.+ expect(before[studio.members[0]].spotId).toBe(`fan:${studio.deptId}:0:0`);+ expect(Object.values(before).map((s) => s.spotId)).toEqual(places.slice(0, studio.members.length)+ .map((p, i) => ({ p, i, from: Math.hypot(p.x - studio.board!.x, p.z - studio.board!.z) }))+ .sort((a, b) => Math.round((a.from - b.from) * 10) || a.i - b.i).map((x) => x.p.id));+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/teamMeeting.ts b/jarvis/ui/web/frontend/src/components/society/office/teamMeeting.tsindex 34890f1c73..3acef3e81a 100644--- a/jarvis/ui/web/frontend/src/components/society/office/teamMeeting.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/teamMeeting.ts@@ -4,7 +4,9 @@* who keeps working at their desk). Pure, so the panel and tests share it.*/import type { SocietyAgent } from "../data";-import type { OfficeLayout, Point } from "./officeLayout";+import type { OfficeLayout, Point, Studio } from "./officeLayout";+import { buildNavGrid, type NavGrid } from "./officeNav";+import { huddlePlaces, leadPlace } from "./officeTeams";import type { Summon, TeamMeeting } from "./officeStore";/** A meeting holds its members at the table this long unless it is ended earlier. */@@ -38,6 +40,47 @@ export function meetingSeats(layout: OfficeLayout, members: readonly string[]):return seats;}+const gridCache = new WeakMap<OfficeLayout, NavGrid>();++/**+ * A place at a studio's own board for every member, the arc nearest the board+ * first: what "Meet" started from that studio's board hands to+ * `startMeeting` instead of the team room's chairs. Members beyond the places+ * of the arcs get none and stay where they are. The team's lead, when it is+ * among them, gets the centre of the front arc. Like every meeting, it never+ * moves a working member. `grid` is the floor's navigation grid when the+ * caller has it; without one it is built from the layout (once per layout).+ */+export function boardSeats(layout: OfficeLayout, studio: Studio, members: readonly string[], grid?: NavGrid | null): Record<string, MeetingSeat>;+/** The same, with the grid named before the studio; both orders are kept so no caller breaks. */+export function boardSeats(layout: OfficeLayout, grid: NavGrid | null | undefined, studio: Studio, members: readonly string[]): Record<string, MeetingSeat>;+export function boardSeats(+ layout: OfficeLayout, second: Studio | NavGrid | null | undefined, third: Studio | readonly string[], fourth?: NavGrid | null | readonly string[],+): Record<string, MeetingSeat> {+ // (layout, studio, members, grid?) has the member list third; (layout, grid, studio, members) has it last.+ const membersThird = Array.isArray(third);+ const studio = (membersThird ? second : third) as Studio;+ const members = (membersThird ? third : fourth) as readonly string[];+ const grid = (membersThird ? fourth : second) as NavGrid | null | undefined;+ const board = studio.board;+ if (!board) return {};+ let floor = grid ?? gridCache.get(layout);+ if (!floor) { floor = buildNavGrid(layout); gridCache.set(layout, floor); }+ const all = huddlePlaces(layout, floor, studio);+ // A team's lead, when it is among those called, stands at the centre of the front arc.+ const centre = studio.leadId && members.includes(studio.leadId) ? leadPlace(all, studio) : null;+ const places = all.filter((p) => p.id !== centre?.id)+ .map((p, i) => ({ p, i, from: Math.hypot(p.x - board.x, p.z - board.z) }))+ .sort((a, b) => Math.round((a.from - b.from) * 10) || a.i - b.i);+ const seats: Record<string, MeetingSeat> = {};+ let next = 0;+ for (const id of members) {+ const place = centre && id === studio.leadId ? centre : places[next++]?.p;+ if (place) seats[id] = { target: { x: place.x, z: place.z }, spotId: place.id };+ }+ return seats;+}+export interface MeetingProgress {/** Members sitting (or standing) at their place at the table. */seated: string[];diff --git a/jarvis/ui/web/frontend/src/components/society/office/teamRoom.css b/jarvis/ui/web/frontend/src/components/society/office/teamRoom.cssindex 26d8408c0c..beec4e8eaf 100644--- a/jarvis/ui/web/frontend/src/components/society/office/teamRoom.css+++ b/jarvis/ui/web/frontend/src/components/society/office/teamRoom.css@@ -1,24 +1,24 @@-/* Team room panel: theme tokens only, so light and dark mode both work. Member badges use each agent's own colour. */-.team-cards { list-style:none; margin:0; padding:0; display:flex; flex-direction:column; gap:7px; }-.team-card { display:flex; flex-direction:column; gap:7px; padding:9px 10px; border:1px solid hsl(var(--border)); border-radius:11px; background:hsl(var(--background) / .6); }-.team-card[data-meeting] { border-color:hsl(var(--success) / .7); box-shadow:inset 3px 0 0 hsl(var(--success)); }-.team-card-head { display:flex; flex-direction:column; gap:1px; min-width:0; }-.team-card-name { font-size:13px; font-weight:700; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }-.team-badges { display:flex; flex-wrap:wrap; gap:4px; }-.team-badge { position:relative; display:inline-flex; align-items:center; justify-content:center; width:26px; height:26px; border-radius:50%; color:#fff; font-size:10px; font-weight:700; letter-spacing:.02em; text-shadow:0 1px 1px rgb(0 0 0 / .35); box-shadow:inset 0 0 0 1px rgb(0 0 0 / .15); }-.team-badge .office-dot { position:absolute; right:-1px; bottom:-1px; width:9px; height:9px; box-shadow:0 0 0 2px hsl(var(--popover)); }-.team-badge .office-dot[data-state="paused"] { background:hsl(var(--popover)); box-shadow:0 0 0 2px hsl(var(--popover)), inset 0 0 0 1.5px hsl(var(--muted-foreground)); }-.team-editor, .team-composer, .team-picker { display:flex; flex-direction:column; gap:7px; }-.team-composer { padding-top:4px; border-top:1px solid hsl(var(--border)); }-.team-picker .office-actions { align-items:center; }-.team-picker .office-mini:disabled { opacity:.5; cursor:not-allowed; }-.team-picker-count { margin-left:auto; }-.team-picker-title { flex:none; max-width:45%; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-size:11px; color:hsl(var(--muted-foreground)); }-.team-picker .office-list { max-height:190px; }-.team-danger { border-color:hsl(var(--destructive)); color:hsl(var(--destructive)); font-weight:600; }-.team-danger:hover:not(:disabled) { background:hsl(var(--destructive) / .1); }-.team-meeting { display:flex; flex-direction:column; gap:5px; padding:9px 10px; border-radius:11px; border:1px solid hsl(var(--success) / .55); background:hsl(var(--success) / .1); }-.team-meeting-title { display:flex; align-items:center; gap:7px; font-weight:700; overflow-wrap:anywhere; }-.team-meeting-live { flex:none; width:8px; height:8px; border-radius:50%; background:hsl(var(--success)); animation:team-live 1.6s ease-in-out infinite; }-@keyframes team-live { 50% { opacity:.35; } }-@media (prefers-reduced-motion: reduce) { .team-meeting-live { animation:none; } }+/* Teams sheet: theme tokens only, so light and dark mode both work. */+/* Green is for a round that is really answering; a team the person merely called together gets a plain edge. */+.team-card[data-called] { border-color:hsl(var(--border-strong)); box-shadow:inset 3px 0 0 hsl(var(--border-strong)); }+.team-card[data-live] { border-color:hsl(var(--success) / .7); box-shadow:inset 3px 0 0 hsl(var(--success)); }+.team-live-mark { flex:none; display:inline-flex; align-items:center; gap:5px; padding:1px 8px; border-radius:999px; background:hsl(var(--success) / .12); color:hsl(var(--success)); font-size:11px; font-weight:600; }+.team-live-mark i { width:6px; height:6px; border-radius:50%; background:hsl(var(--success)); }+/* A team's members as overlapping faces; each carries its run state as a dot. */+.team-stack { display:inline-flex; align-items:center; padding-left:6px; }+/* The face brings its own tile (agentFace.css); here it only overlaps its neighbour, parted by a ring in the dialog's ground. */+.team-face { position:relative; display:inline-flex; margin-left:-6px; border-radius:50%; box-shadow:0 0 0 2px hsl(var(--background)); }+.team-face .office-dot { position:absolute; right:-1px; bottom:-1px; width:9px; height:9px; box-shadow:0 0 0 2px hsl(var(--background)); }+.team-face .office-dot[data-state="paused"] { background:hsl(var(--background)); box-shadow:0 0 0 2px hsl(var(--background)), inset 0 0 0 1.5px hsl(var(--muted-foreground)); }+.team-face-more { width:32px; height:32px; font-size:11px; font-weight:600; color:hsl(var(--muted-foreground)); box-shadow:0 0 0 2px hsl(var(--background)), inset 0 0 0 1px hsl(var(--border-strong) / .7); }+/* The member list scrolls on its own: up to 22 rem, less on a short window, so name, picks and buttons stay on screen with it. */+.team-picker-list { max-height:min(22rem, max(8rem, calc(90dvh - 29rem))); }+/* The new-team form's buttons stay at the sheet's lower edge while the form scrolls. The negative margins undo the+ sheet body's 1.25 rem padding so the bar spans it edge to edge. */+.team-footer { position:sticky; bottom:0; z-index:1; display:flex; flex-wrap:wrap; align-items:center; gap:8px; margin:0 -1.25rem -1.25rem; padding:12px 1.25rem; border-top:1px solid hsl(var(--border)); background:hsl(var(--background)); }+/* The team the person called together: a banner in the sheet, a small card in the HUD. Neutral on purpose — it is a+ gathering on the map, not a running round, so nothing here is green or pulses. */+.team-meeting { display:flex; flex-direction:column; gap:4px; padding:12px 14px; border-radius:12px; border:1px solid hsl(var(--border-strong)); background:hsl(var(--secondary) / .6); }+.team-meeting[data-compact] { width:100%; padding:9px 11px; border-color:hsl(var(--border)); background:hsl(var(--popover) / .92); }+.team-meeting-title { display:flex; align-items:center; gap:8px; margin:0; font-size:13px; font-weight:600; overflow-wrap:anywhere; }+.team-meeting-line { margin:0; font-size:12px; color:hsl(var(--muted-foreground)); }diff --git a/jarvis/ui/web/frontend/src/components/society/office/teamStatus.test.ts b/jarvis/ui/web/frontend/src/components/society/office/teamStatus.test.tsnew file mode 100644index 0000000000..7e693a24b3--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/teamStatus.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from "vitest";+import { teamMark } from "./teamStatus";++const NOW = 1_000_000;+const gathering = { groupId: "g1", untilMs: NOW + 60_000 };++describe("what a team's mark may claim", () => {+ it("is live only while the backend reports a running round", () => {+ expect(teamMark("g1", { g1: { running: true } }, null, NOW)).toBe("live");+ expect(teamMark("g1", { g1: { running: false } }, null, NOW)).toBeNull();+ expect(teamMark("g1", {}, null, NOW)).toBeNull();+ // Another team's round says nothing about this one.+ expect(teamMark("g1", { g2: { running: true } }, null, NOW)).toBeNull();+ });++ it("never calls the person's own gathering live", () => {+ expect(teamMark("g1", {}, gathering, NOW)).toBe("called");+ expect(teamMark("g1", { g1: { running: false } }, gathering, NOW)).toBe("called");+ expect(teamMark("g2", {}, gathering, NOW)).toBeNull();+ });++ it("drops the gathering once its time is up", () => {+ expect(teamMark("g1", {}, { groupId: "g1", untilMs: NOW }, NOW)).toBeNull();+ expect(teamMark("g1", {}, { groupId: "g1", untilMs: NOW - 1 }, NOW)).toBeNull();+ });++ it("shows the real round when a called team is also answering", () => {+ expect(teamMark("g1", { g1: { running: true } }, gathering, NOW)).toBe("live");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/teamStatus.ts b/jarvis/ui/web/frontend/src/components/society/office/teamStatus.tsnew file mode 100644index 0000000000..231592b638--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/teamStatus.ts@@ -0,0 +1,24 @@+/**+ * What may be said about a team at a glance, and where each claim comes from.+ *+ * "Live" means one thing only: a round of the team is answering right now,+ * as the backend reports it (teamwork's `TeamRound.running`). "Called" is the+ * person's own gathering on the map (officeStore's `meeting`): members walk+ * to the table or to their board, nothing is posted to the team and no agent+ * starts work. The two are never mixed, so a board or a card can never show+ * a gathering as a running round. Pure and tested.+ */++export type TeamMark = "live" | "called" | null;++export function teamMark(+ groupId: string,+ rounds: Readonly<Record<string, { running: boolean } | undefined>>,+ gathering: { groupId: string; untilMs: number } | null,+ now: number,+): TeamMark {+ // A real round outranks the gathering: if the team answers while it stands at its board, that is the news.+ if (rounds[groupId]?.running) return "live";+ if (gathering && gathering.groupId === groupId && gathering.untilMs > now) return "called";+ return null;+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/teamwork.test.ts b/jarvis/ui/web/frontend/src/components/society/office/teamwork.test.tsnew file mode 100644index 0000000000..dae301a7f1--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/teamwork.test.ts@@ -0,0 +1,301 @@+import { describe, expect, it } from "vitest";+import type { SocietyMeeting } from "@/lib/societyChatGroups";+import { bubbleText } from "./officeTalk";+import {+ HANDOFF_BUBBLE_MS, HANDOFF_FRESH_MS, MAX_ROUND_LINES, ROLE_GRACE_MS, SPOKE_LINGER_MS, applyRoomChange, applyRoomLine, applySnapshot, emptyRound,+ freshHandoffs, handoffFrom, isSpeaking, lastSpokeBy, meetingTeamId, pendingHandoff, queueHandoff, roundFor, roundRole, steadyRole, teamBubble, teamBubbleLive,+ type Handoff, type RoleMemory, type TeamRound,+} from "./teamwork";+import { BOARD_REFRESH_MS, MAX_READS_PER_TICK, SWEEP_MS, SWEEP_READS_PER_TICK, dueTeams } from "./useTeamRounds";++const meeting = (messages: [string, string, string][], running: boolean, next: string | null = null, members?: string[]): SocietyMeeting => ({+ messages: messages.map(([id, speaker, text]) => ({ id, speaker, text })),+ running,+ room: { state: running ? "running" : "settled", settle_reason: "", next_speaker: next, ...(members ? { members } : {}) } as SocietyMeeting["room"],+});++describe("meetingTeamId", () => {+ it("reads the team out of a meeting room id and ignores every other room", () => {+ expect(meetingTeamId("meeting:grp_42:9f3a")).toBe("grp_42");+ expect(meetingTeamId("meeting:a:b:c:9f3a")).toBe("a:b:c");+ expect(meetingTeamId("meeting:grp_42")).toBe("grp_42");+ expect(meetingTeamId("room:town-hall")).toBeNull();+ expect(meetingTeamId("")).toBeNull();+ expect(meetingTeamId(undefined)).toBeNull();+ });+});++describe("a team's round from its meeting", () => {+ it("takes state, speaker, members and the newest lines from a snapshot", () => {+ const round = applySnapshot(undefined, "t", meeting([["r1", "user", "Plan the launch"], ["e1", "nora", "I take the copy."]], true, "ben", ["nora", "ben"]), 1000);+ expect(round).toMatchObject({ teamId: "t", running: true, speakerId: "ben", members: ["nora", "ben"], loaded: true, fetchedMs: 1000, dirty: false });+ expect(round.lines.map((l) => l.speaker)).toEqual(["user", "nora"]);+ });++ it("never replays an old transcript as fresh speech when the office opens", () => {+ const first = applySnapshot(undefined, "t", meeting([["r1", "user", "Hi"], ["e1", "nora", "Hello."]], false), 1000);+ expect(first.spoke).toBeNull();+ expect(first.speakerId).toBeNull();+ });++ it("counts a line that is new since the last snapshot as just said, once", () => {+ const first = applySnapshot(undefined, "t", meeting([["r1", "user", "Hi"]], true, "nora"), 1000);+ const second = applySnapshot(first, "t", meeting([["r1", "user", "Hi"], ["e1", "nora", "Hello."]], true, "ben"), 4000);+ expect(second.spoke).toEqual({ id: "e1", speaker: "nora", text: "Hello.", atMs: 4000 });+ expect(second.speakerId).toBe("ben");+ const third = applySnapshot(second, "t", meeting([["r1", "user", "Hi"], ["e1", "nora", "Hello."]], false), 7000);+ expect(third.spoke?.atMs).toBe(4000);+ expect(third).toMatchObject({ running: false, speakerId: null });+ // The person's own line is on the board, never over an agent's head.+ const fourth = applySnapshot(third, "t", meeting([["e1", "nora", "Hello."], ["r2", "user", "Thanks"]], true, "nora"), 9000);+ expect(fourth.spoke?.id).toBe("e1");+ });++ it("keeps the newest lines only and drops empty ones (a silent pass says nothing)", () => {+ const many: [string, string, string][] = Array.from({ length: 30 }, (_, i) => [`e${i}`, "nora", i === 29 ? " " : `line ${i}`]);+ const round = applySnapshot(undefined, "t", meeting(many, false), 1);+ expect(round.lines).toHaveLength(MAX_ROUND_LINES);+ expect(round.lines[round.lines.length - 1].id).toBe("e28");+ });++ it("opens and settles on the socket's room events, and asks for a fresh read", () => {+ const opened = applyRoomChange(undefined, "t", "open", ["nora", "ben"]);+ expect(opened).toMatchObject({ running: true, dirty: true, members: ["nora", "ben"], loaded: false });+ const settled = applyRoomChange({ ...opened, speakerId: "nora" }, "t", "settle");+ expect(settled).toMatchObject({ running: false, speakerId: null, dirty: true, members: ["nora", "ben"] });+ expect(applyRoomChange(settled, "t", "something-else")).toBe(settled);+ });++ it("adds a line said on the socket once, as just said, and frees the speaker's turn", () => {+ const running: TeamRound = { ...emptyRound("t"), running: true, speakerId: "nora", loaded: true };+ const said = applyRoomLine(running, "t", { id: "e1", speaker: "nora", text: "Done with the copy." }, 5000);+ expect(said.lines).toEqual([{ id: "e1", speaker: "nora", text: "Done with the copy." }]);+ expect(said.spoke).toMatchObject({ id: "e1", atMs: 5000 });+ expect(said).toMatchObject({ speakerId: null, dirty: true });+ const again = applyRoomLine(said, "t", { id: "e1", speaker: "nora", text: "Done with the copy." }, 9000);+ expect(again.lines).toHaveLength(1);+ expect(again.spoke?.atMs).toBe(5000);+ expect(applyRoomLine(said, "t", { id: "e2", speaker: "ben", text: " " }, 9000).lines).toHaveLength(1);+ });+});++describe("an agent's part in a round", () => {+ const round: TeamRound = { ...emptyRound("t"), running: true, speakerId: "nora", members: ["nora", "ben", "kai"] };++ it("gathers the free, names the one contributing, and leaves the busy and the resting alone", () => {+ expect(roundRole({ agentId: "ben", state: "idle" }, round)).toBe("gather");+ // The speaker's run state reads working: that work is the round.+ expect(roundRole({ agentId: "nora", state: "working" }, round)).toBe("speaker");+ expect(roundRole({ agentId: "nora", state: "idle" }, round)).toBe("speaker");+ expect(roundRole({ agentId: "kai", state: "working" }, round)).toBe("busy");+ expect(roundRole({ agentId: "kai", state: "waiting" }, round)).toBe("busy");+ expect(roundRole({ agentId: "nora", state: "waiting" }, round)).toBe("busy");+ expect(roundRole({ agentId: "kai", state: "paused" }, round)).toBe("none");+ });++ it("is none without a running round: nobody gathers for a chat that is not answering", () => {+ expect(roundRole({ agentId: "ben", state: "idle" }, { ...round, running: false })).toBe("none");+ expect(roundRole({ agentId: "ben", state: "idle" }, undefined)).toBe("none");+ });++ it("finds the round an agent takes part in: its home team's, else one that lists it", () => {+ const rounds = { t: round, u: { ...emptyRound("u"), running: true, members: ["zoe"] }, v: { ...emptyRound("v"), members: ["ben"] } };+ expect(roundFor(rounds, "ben", "t")?.teamId).toBe("t");+ expect(roundFor(rounds, "zoe", null)?.teamId).toBe("u");+ expect(roundFor(rounds, "zoe", "v")?.teamId).toBe("u");+ expect(roundFor(rounds, "ben", "v")?.teamId).toBe("t");+ expect(roundFor(rounds, "stranger", null)).toBeUndefined();+ });++ it("holds a member at the board through the moments its state runs ahead of the meeting", () => {+ const memory: RoleMemory = { role: "none", busySinceMs: null };+ expect(steadyRole(memory, "gather", 0)).toBe("gather");+ // Its turn began: the roster already says working, the meeting has not named it yet.+ expect(steadyRole(memory, "busy", 1000)).toBe("gather");+ expect(steadyRole(memory, "busy", 1000 + ROLE_GRACE_MS - 1)).toBe("gather");+ expect(steadyRole(memory, "speaker", 3000)).toBe("speaker");+ // Its line is out, the roster still says working for a moment.+ expect(steadyRole(memory, "busy", 9000)).toBe("gather");+ expect(steadyRole(memory, "gather", 9500)).toBe("gather");+ // Really working on something else: after the grace it goes to its desk.+ expect(steadyRole(memory, "busy", 20000)).toBe("gather");+ expect(steadyRole(memory, "busy", 20000 + ROLE_GRACE_MS)).toBe("busy");+ expect(steadyRole(memory, "busy", 40000)).toBe("busy");+ expect(steadyRole(memory, "none", 41000)).toBe("none");+ });++ it("never holds back someone who was not at the board", () => {+ const memory: RoleMemory = { role: "none", busySinceMs: null };+ expect(steadyRole(memory, "busy", 0)).toBe("busy");+ });+});++const agents = new Map([+ ["jarvis", { tier: "lead" as const, name: "George" }],+ ["nora", { tier: "specialist" as const, name: "Nora" }],+ ["ben", { tier: "orchestrator" as const, name: "Ben" }],+]);++describe("a message from one agent to another", () => {+ const event = (extra: Record<string, unknown>) => ({ event_id: "ev1", msg_type: "ASSIGN", from_agent: "ben", to_agent: "nora", room_id: "", text: "Draft the release notes", ...extra });++ it("is read from the board's own event: sender, receiver, type and its real text", () => {+ expect(handoffFrom(event({}), agents, 500)).toEqual({+ id: "ev1", from: "ben", to: "nora", toName: "Nora", text: "Draft the release notes", msgType: "ASSIGN", atMs: 500, phase: "queued", untilMs: 500 + HANDOFF_FRESH_MS,+ });+ for (const msgType of ["SAY", "QUERY", "ANSWER", "PROPOSE"]) expect(handoffFrom(event({ msg_type: msgType }), agents, 1)?.msgType).toBe(msgType);+ });++ it("is not made up from anything else", () => {+ // A line said in a room, a result, a message to oneself, to nobody, to a stranger, or without words.+ expect(handoffFrom(event({ room_id: "meeting:t:1" }), agents, 1)).toBeNull();+ expect(handoffFrom(event({ msg_type: "RESULT" }), agents, 1)).toBeNull();+ expect(handoffFrom(event({ to_agent: "ben" }), agents, 1)).toBeNull();+ expect(handoffFrom(event({ to_agent: "" }), agents, 1)).toBeNull();+ expect(handoffFrom(event({ to_agent: "stranger" }), agents, 1)).toBeNull();+ expect(handoffFrom(event({ from_agent: "user" }), agents, 1)).toBeNull();+ expect(handoffFrom(event({ text: " " }), agents, 1)).toBeNull();+ expect(handoffFrom(null, agents, 1)).toBeNull();+ // The lead's own messages are its pet's errands, and nobody walks to the pet.+ expect(handoffFrom(event({ from_agent: "jarvis" }), agents, 1)).toBeNull();+ expect(handoffFrom(event({ to_agent: "jarvis" }), agents, 1)).toBeNull();+ });++ const handoff = (id: string, from = "ben", atMs = 0): Handoff => ({ id, from, to: "nora", toName: "Nora", text: id, msgType: "SAY", atMs, phase: "queued", untilMs: atMs + HANDOFF_FRESH_MS });++ it("queues without duplicates, two per sender at most, and forgets what went stale", () => {+ let list = queueHandoff([], handoff("h1"));+ expect(queueHandoff(list, handoff("h1"))).toBe(list);+ list = queueHandoff(list, handoff("h2"));+ list = queueHandoff(list, handoff("h3"));+ expect(list.map((h) => h.id)).toEqual(["h2", "h3"]);+ list = queueHandoff(list, handoff("x1", "nora"));+ expect(list).toHaveLength(3);+ expect(pendingHandoff(list, "ben", 10)?.id).toBe("h2");+ expect(pendingHandoff(list, "kai", 10)).toBeNull();+ expect(freshHandoffs(list, 10)).toBe(list);+ expect(freshHandoffs(list, HANDOFF_FRESH_MS + 1)).toEqual([]);+ expect(pendingHandoff(list, "ben", HANDOFF_FRESH_MS + 1)).toBeNull();+ });+});++describe("what teamwork puts over an agent's head", () => {+ const labels = { thinking: "Thinking", to: "To {0}: {1}" };+ const spoke = { id: "e1", speaker: "nora", text: "**Done** with the copy.", atMs: 1000 };+ const handoff: Handoff = { id: "h1", from: "ben", to: "nora", toName: "Nora", text: "Draft the release notes", msgType: "ASSIGN", atMs: 1000, phase: "queued", untilMs: 91000 };+ const bubble = (input: Partial<Parameters<typeof teamBubble>[0]>) => teamBubble({ spoke: null, speaking: false, handoff: null, now: 2000, labels, short: bubbleText, ...input });++ it("shows the line an agent just said, in its own words, for a few seconds", () => {+ expect(bubble({ spoke })).toEqual({ kind: "speech", text: "Done with the copy.", live: false, atMs: 1000 });+ expect(bubble({ spoke, now: 1000 + SPOKE_LINGER_MS })).toBeNull();+ });++ it("shows a thought, not invented words, while the speaker's line is not written yet", () => {+ expect(bubble({ speaking: true })).toEqual({ kind: "thought", text: "Thinking", live: true, atMs: 0 });+ expect(bubble({ speaking: true, spoke })?.kind).toBe("speech");+ });++ it("shows the message a sender handed over: briefly at its desk, and while it stands with the receiver", () => {+ expect(bubble({ handoff })).toEqual({ kind: "speech", text: "To Nora: Draft the release notes", live: false, atMs: 1000 });+ expect(bubble({ handoff, now: 1000 + HANDOFF_BUBBLE_MS })).toBeNull();+ const delivering: Handoff = { ...handoff, phase: "delivering", untilMs: 60000 };+ expect(bubble({ handoff: delivering, now: 59000 })?.text).toBe("To Nora: Draft the release notes");+ expect(bubble({ handoff: delivering, now: 60001 })).toBeNull();+ });++ it("says nothing when nothing happened", () => {+ expect(bubble({})).toBeNull();+ });++ it("needs a clock only while something still lingers", () => {+ expect(teamBubbleLive(null, null, 5000)).toBe(false);+ expect(teamBubbleLive(spoke, null, 1000 + SPOKE_LINGER_MS - 1)).toBe(true);+ // A line said long ago stays in the round; it must not keep a bubble ticking for the rest of the session.+ expect(teamBubbleLive(spoke, null, 1000 + SPOKE_LINGER_MS)).toBe(false);+ expect(teamBubbleLive(spoke, null, 3_600_000)).toBe(false);+ expect(teamBubbleLive(null, handoff, 1000 + HANDOFF_BUBBLE_MS - 1)).toBe(true);+ expect(teamBubbleLive(null, handoff, 1000 + HANDOFF_BUBBLE_MS)).toBe(false);+ const delivering: Handoff = { ...handoff, phase: "delivering", untilMs: 60000 };+ expect(teamBubbleLive(null, delivering, 59999)).toBe(true);+ expect(teamBubbleLive(null, delivering, 60000)).toBe(false);+ });++ it("finds an agent's newest line and whether it is the speaker across teams", () => {+ const rounds = {+ t: { ...emptyRound("t"), running: true, speakerId: "ben", spoke },+ u: { ...emptyRound("u"), spoke: { ...spoke, id: "e9", atMs: 5000 } },+ v: { ...emptyRound("v"), running: false, speakerId: "kai" },+ };+ expect(lastSpokeBy(rounds, "nora")?.id).toBe("e9");+ expect(lastSpokeBy(rounds, "ben")).toBeNull();+ // One voice at a time: nora's line in team t gives way now that ben has the word there.+ expect(lastSpokeBy({ t: rounds.t }, "nora")).toBeNull();+ expect(lastSpokeBy({ t: { ...rounds.t, speakerId: null } }, "nora")?.id).toBe("e1");+ expect(lastSpokeBy({ t: { ...rounds.t, speakerId: "nora" } }, "nora")?.id).toBe("e1");+ // After the round has settled the last line may linger.+ expect(lastSpokeBy({ t: { ...rounds.t, running: false } }, "nora")?.id).toBe("e1");+ expect(isSpeaking(rounds, "ben")).toBe(true);+ expect(isSpeaking(rounds, "kai")).toBe(false);+ });+});++describe("which meetings are read on a tick", () => {+ const round = (teamId: string, extra: Partial<TeamRound>): TeamRound => ({ ...emptyRound(teamId), loaded: true, fetchedMs: 100_000, ...extra });+ const base = { teamIds: ["a", "b", "c", "d", "e", "f"], near: new Set<string>(), inRoom: new Set<string>(), now: 100_500 };++ it("reads nothing while every team was read lately and nothing is running, changed or near", () => {+ expect(dueTeams({ ...base, rounds: Object.fromEntries(base.teamIds.map((id) => [id, round(id, {})])) })).toEqual([]);+ });++ it("finds what nobody announced: every team is read once after waking, two a tick, and again after about a minute", () => {+ // Nothing known yet (the office just opened, or a socket event was missed): the sweep starts at once.+ const rounds: Record<string, TeamRound> = {};+ const seen: string[] = [];+ let now = 100_500;+ for (let tick = 0; tick < 3; tick += 1) {+ const due = dueTeams({ ...base, rounds, now });+ expect(due).toHaveLength(SWEEP_READS_PER_TICK);+ for (const id of due) { seen.push(id); rounds[id] = round(id, { fetchedMs: now }); }+ now += 3000;+ }+ expect([...seen].sort()).toEqual(base.teamIds);+ expect(dueTeams({ ...base, rounds, now })).toEqual([]);+ // A minute on, the teams read first are due again, the longest unread first.+ expect(dueTeams({ ...base, rounds, now: 100_500 + SWEEP_MS })).toEqual(seen.slice(0, 2));+ expect(dueTeams({ ...base, rounds, now: 100_500 + SWEEP_MS - 1 })).toEqual([]);+ // The caller's jitter moves the period.+ expect(dueTeams({ ...base, rounds, now: 100_500 + SWEEP_MS - 5000, sweepMs: SWEEP_MS * 0.9 })).toEqual(seen.slice(0, 2));+ });++ it("keeps room for the sweep on a tick full of running rounds", () => {+ const rounds = Object.fromEntries(["a", "b", "c", "d", "e"].map((id) => [id, round(id, { running: true, fetchedMs: 99_000 })]));+ const due = dueTeams({ ...base, rounds });+ expect(due).toHaveLength(MAX_READS_PER_TICK);+ expect(due).toContain("f");+ expect(due.filter((id) => id !== "f")).toHaveLength(3);+ });++ it("reads running and freshly changed rounds first, longest unread first, capped", () => {+ const rounds = {+ a: round("a", { running: true, fetchedMs: 99_000 }), b: round("b", { dirty: true, fetchedMs: 98_000 }), c: round("c", { running: true, fetchedMs: 97_000 }),+ d: round("d", { running: true }), e: round("e", { running: true, fetchedMs: 96_000 }), f: round("f", {}),+ };+ const due = dueTeams({ ...base, rounds, near: new Set(["f"]) });+ expect(due).toEqual(["e", "c", "b", "a"]);+ // Nothing was left for the sweep here, so the running rounds take the whole tick.+ expect(due).toHaveLength(MAX_READS_PER_TICK);+ });++ const fresh = () => Object.fromEntries(base.teamIds.map((id) => [id, round(id, {})]));++ it("reads a board near the camera again once its transcript has aged, and a far one only with the sweep", () => {+ const rounds = { ...fresh(), b: round("b", { fetchedMs: 100_500 - BOARD_REFRESH_MS }) };+ expect(dueTeams({ ...base, rounds, near: new Set(["a", "b"]) })).toEqual(["b"]);+ expect(dueTeams({ ...base, rounds, near: new Set() })).toEqual([]);+ });++ it("checks a team the roster shows in a room, but not on every tick", () => {+ const rounds = { ...fresh(), a: round("a", { fetchedMs: 100_000 }), b: round("b", { fetchedMs: 90_000 }) };+ expect(dueTeams({ ...base, rounds, inRoom: new Set(["a", "b"]) })).toEqual(["b"]);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/teamwork.ts b/jarvis/ui/web/frontend/src/components/society/office/teamwork.tsnew file mode 100644index 0000000000..19fa3669d7--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/teamwork.ts@@ -0,0 +1,350 @@+/**+ * Real teamwork, as the office shows it. Two things, and only these two,+ * because they are what the app can actually see:+ *+ * - **A team's round.** A team is a chat group with one shared meeting. While+ * a round is answering, its free members stand at their studio board and the+ * member contributing right now is the speaker. The round's state and+ * transcript come from `GET /api/society/chat-groups/{id}/meeting`; that a+ * round opened or settled, and each line said in it, also arrive on the+ * socket (`SocietyRoomChanged`, `SocietyMessageSent` with a+ * `meeting:<group>:…` room id).+ * - **A message from one agent to another.** `SocietyMessageSent` without a+ * room, from one roster agent to another: a task handed over (ASSIGN) or a+ * direct line (SAY, QUERY, ANSWER, PROPOSE). Its sender walks over to the+ * receiver once it is free. The lead's own messages are Gigi's errands+ * (gigiErrands.ts) and are left to it.+ *+ * Nothing here is invented: no line is shown that was not said, nobody+ * gathers without a running round, and a working agent is never moved except+ * the one member whose work IS the round's current contribution.+ *+ * The reducers are pure and tested; the store holds what the walkers, the+ * bubbles and the studio boards read.+ */+import { create } from "zustand";+import type { SocietyMeeting } from "@/lib/societyChatGroups";+import type { AgentRunState, SocietyAgent } from "../data";+import type { Bubble } from "./officeTalk";++/** One line of a team's transcript; `speaker` is an agent id, or "user" for the person. */+export interface RoundLine { id: string; speaker: string; text: string }++export interface TeamRound {+ teamId: string;+ /** A round is answering right now. */+ running: boolean;+ /** The member contributing at the moment (the room's next speaker while it runs), or null. */+ speakerId: string | null;+ /** Everyone taking part in the round (the room's members); empty until a round was seen. */+ members: string[];+ /** The newest lines of the transcript, oldest first. */+ lines: RoundLine[];+ /** The last line a member said while the office was watching, and when it was seen. */+ spoke: (RoundLine & { atMs: number }) | null;+ /** The transcript has been fetched at least once. */+ loaded: boolean;+ fetchedMs: number;+ /** The socket reported something this snapshot does not hold yet: fetch again soon. */+ dirty: boolean;+ /** The last read of the meeting failed: what is shown is what was known before, or nothing. */+ unavailable?: boolean;+}++/** Lines kept per team; a board shows the newest that fit. */+export const MAX_ROUND_LINES = 12;+/** How long a line stays over its speaker's head after it was said. */+export const SPOKE_LINGER_MS = 9000;++export function emptyRound(teamId: string): TeamRound {+ return { teamId, running: false, speakerId: null, members: [], lines: [], spoke: null, loaded: false, fetchedMs: 0, dirty: false };+}++/** The team (chat group) a room belongs to, from its id `meeting:<group id>:<suffix>`; null for any other room. */+export function meetingTeamId(roomId: unknown): string | null {+ if (typeof roomId !== "string" || !roomId.startsWith("meeting:")) return null;+ const rest = roomId.slice("meeting:".length);+ const cut = rest.lastIndexOf(":");+ const teamId = cut > 0 ? rest.slice(0, cut) : rest;+ return teamId.length > 0 ? teamId : null;+}++function idList(value: unknown): string[] | null {+ return Array.isArray(value) ? value.filter((v): v is string => typeof v === "string" && v.length > 0) : null;+}++function tail(lines: RoundLine[]): RoundLine[] {+ return lines.filter((l) => l.text.trim().length > 0).slice(-MAX_ROUND_LINES);+}++/**+ * Fold a fetched meeting into a team's round. A line that is new since the+ * last snapshot counts as just said; the first snapshot never does, so an old+ * transcript is not replayed as fresh speech when the office opens.+ */+export function applySnapshot(prev: TeamRound | undefined, teamId: string, snapshot: SocietyMeeting, now: number): TeamRound {+ const lines = tail(snapshot.messages.map((m) => ({ id: m.id, speaker: m.speaker, text: m.text })));+ const running = snapshot.running === true;+ const speakerId = running && snapshot.room?.state === "running" ? snapshot.room.next_speaker ?? null : null;+ let spoke = prev?.spoke ?? null;+ if (prev?.loaded) {+ const known = new Set(prev.lines.map((l) => l.id));+ const fresh = [...lines].reverse().find((l) => l.speaker !== "user" && !known.has(l.id));+ if (fresh && fresh.id !== spoke?.id) spoke = { ...fresh, atMs: now };+ }+ // The room lists its members on the wire; the declared type names only what the chat view reads.+ const members = idList((snapshot.room as { members?: unknown } | null)?.members) ?? prev?.members ?? [];+ return { teamId, running, speakerId, members, lines, spoke, loaded: true, fetchedMs: now, dirty: false, unavailable: false };+}++/** A round opened or settled (the socket's `SocietyRoomChanged`). */+export function applyRoomChange(prev: TeamRound | undefined, teamId: string, phase: unknown, members?: unknown): TeamRound {+ const round = prev ?? emptyRound(teamId);+ const listed = idList(members);+ if (phase === "open") return { ...round, running: true, dirty: true, members: listed && listed.length > 0 ? listed : round.members };+ if (phase === "settle") return { ...round, running: false, speakerId: null, dirty: true };+ return round;+}++/** A line said in a round (the socket's `SocietyMessageSent` with a meeting room id). */+export function applyRoomLine(prev: TeamRound | undefined, teamId: string, line: RoundLine, now: number): TeamRound {+ const round = prev ?? emptyRound(teamId);+ if (!line.text.trim() || round.lines.some((l) => l.id === line.id)) return { ...round, dirty: true };+ return {+ ...round, lines: tail([...round.lines, line]), dirty: true,+ spoke: line.speaker === "user" ? round.spoke : { ...line, atMs: now },+ // Whoever just spoke is no longer the one contributing; the next fetch names the next speaker.+ speakerId: round.speakerId === line.speaker ? null : round.speakerId,+ };+}++/**+ * An agent's part in its team's round:+ * - `gather`: free, so it stands at the studio board;+ * - `speaker`: it is contributing right now (its run state says "working", and that work is the round);+ * - `busy`: working on something else, or waiting for the person: it stays where its state puts it;+ * - `none`: no round, or the agent rests.+ */+export type RoundRole = "none" | "gather" | "speaker" | "busy";++export function roundRole(agent: { agentId: string; state: AgentRunState }, round: TeamRound | undefined): RoundRole {+ if (!round?.running || agent.state === "paused") return "none";+ if (round.speakerId === agent.agentId && agent.state !== "waiting") return "speaker";+ if (agent.state === "idle") return "gather";+ return "busy";+}++/**+ * The running round an agent takes part in: its home team's first, else any round that lists it as a member+ * (an agent can be in several teams and sits in only one studio).+ */+export function roundFor(rounds: Record<string, TeamRound>, agentId: string, homeTeamId: string | null): TeamRound | undefined {+ const home = homeTeamId ? rounds[homeTeamId] : undefined;+ if (home?.running) return home;+ for (const round of Object.values(rounds)) if (round.running && round.members.includes(agentId)) return round;+ return undefined;+}++/**+ * A member at the board keeps its place this long after its part reads+ * "busy". The roster and the meeting are polled on different clocks: the next+ * speaker's run state turns "working" a few seconds before the meeting names+ * it, and the last speaker's stays "working" a moment after its line. Without+ * the grace both would walk to their desk and straight back.+ */+export const ROLE_GRACE_MS = 7000;++export interface RoleMemory { role: RoundRole; busySinceMs: number | null }++/** The part an agent plays for the walkers: `raw`, held steady through the grace above. Mutates `memory`. */+export function steadyRole(memory: RoleMemory, raw: RoundRole, now: number): RoundRole {+ const atBoard = memory.role === "gather" || memory.role === "speaker";+ if (raw === "busy" && atBoard) {+ memory.busySinceMs ??= now;+ if (now - memory.busySinceMs < ROLE_GRACE_MS) return "gather";+ }+ memory.role = raw;+ memory.busySinceMs = null;+ return raw;+}++/** A message one agent sent another, waiting to be walked over. */+export interface Handoff {+ id: string;+ from: string;+ to: string;+ /** The receiver's name, for the sender's bubble. */+ toName: string;+ /** The board's bubble-sized preview of what was sent. */+ text: string;+ /** ASSIGN = a task handed over; anything else is a direct line. */+ msgType: string;+ /** When the office saw it. */+ atMs: number;+ /** `queued` until the sender is free and has walked over; `delivering` while it stands with the receiver. */+ phase: "queued" | "delivering";+ untilMs: number;+}++/** Board message types that count as one agent addressing another. */+const HANDOFF_TYPES = new Set(["ASSIGN", "SAY", "QUERY", "ANSWER", "PROPOSE"]);+/** A message whose sender has not got free within this time is no longer walked over. */+export const HANDOFF_FRESH_MS = 90_000;+/** How long the line stays over a sender that keeps working at its desk. */+export const HANDOFF_BUBBLE_MS = 9000;+/** Pending messages kept per sender; older ones give way. */+const MAX_PER_SENDER = 2;++/**+ * The hand-off a board event describes, or null. Both ends must be roster+ * agents other than the lead (the lead is the person's pet, not a desk mate;+ * its own messages are Gigi's errands), and a line said in a room is not one.+ */+export function handoffFrom(payload: unknown, agents: ReadonlyMap<string, Pick<SocietyAgent, "tier" | "name">>, now: number): Handoff | null {+ if (!payload || typeof payload !== "object") return null;+ const p = payload as Record<string, unknown>;+ const from = typeof p.from_agent === "string" ? p.from_agent : "";+ const to = typeof p.to_agent === "string" ? p.to_agent : "";+ const msgType = typeof p.msg_type === "string" ? p.msg_type : "";+ if (!HANDOFF_TYPES.has(msgType) || !from || !to || from === to || p.room_id) return null;+ const sender = agents.get(from), receiver = agents.get(to);+ if (!sender || !receiver || sender.tier === "lead" || receiver.tier === "lead") return null;+ const text = typeof p.text === "string" ? p.text.trim() : "";+ if (!text) return null;+ const id = typeof p.event_id === "string" && p.event_id ? p.event_id : `${from}>${to}:${now}`;+ return { id, from, to, toName: receiver.name, text, msgType, atMs: now, phase: "queued", untilMs: now + HANDOFF_FRESH_MS };+}++/** Add a hand-off: no duplicates, and at most two pending per sender (the newest stay). */+export function queueHandoff(list: readonly Handoff[], handoff: Handoff): Handoff[] {+ if (list.some((h) => h.id === handoff.id)) return list as Handoff[];+ const own = list.filter((h) => h.from === handoff.from);+ const drop = own.length >= MAX_PER_SENDER ? own.find((h) => h.phase === "queued")?.id : undefined;+ return [...list.filter((h) => h.id !== drop), handoff];+}++/** Drop hand-offs whose time has passed. Returns the same array when nothing changed. */+export function freshHandoffs(list: readonly Handoff[], now: number): Handoff[] {+ const kept = list.filter((h) => h.untilMs > now);+ return kept.length === list.length ? (list as Handoff[]) : kept;+}++interface TeamworkState {+ rounds: Record<string, TeamRound>;+ handoffs: Handoff[];+ setRound: (round: TeamRound) => void;+ /** Forget teams that no longer exist. */+ keepTeams: (teamIds: ReadonlySet<string>) => void;+ /** Mark every round as due for a fetch (the office woke up: what it knows may be stale). */+ markStale: () => void;+ addHandoff: (handoff: Handoff) => void;+ /** The sender reached the receiver: it stays for `forMs`. */+ deliverHandoff: (id: string, now: number, forMs: number) => void;+ finishHandoff: (id: string) => void;+ prune: (now: number) => void;+ reset: () => void;+}++export const useTeamwork = create<TeamworkState>((set) => ({+ rounds: {},+ handoffs: [],+ setRound: (round) => set((s) => (s.rounds[round.teamId] === round ? s : { rounds: { ...s.rounds, [round.teamId]: round } })),+ keepTeams: (teamIds) => set((s) => {+ const kept = Object.entries(s.rounds).filter(([id]) => teamIds.has(id));+ return kept.length === Object.keys(s.rounds).length ? s : { rounds: Object.fromEntries(kept) };+ }),+ markStale: () => set((s) => ({ rounds: Object.fromEntries(Object.entries(s.rounds).map(([id, r]) => [id, { ...r, dirty: true }])) })),+ addHandoff: (handoff) => set((s) => {+ const handoffs = queueHandoff(s.handoffs, handoff);+ return handoffs === s.handoffs ? s : { handoffs };+ }),+ deliverHandoff: (id, now, forMs) => set((s) => ({+ handoffs: s.handoffs.map((h) => (h.id === id && h.phase === "queued" ? { ...h, phase: "delivering", untilMs: now + forMs } : h)),+ })),+ finishHandoff: (id) => set((s) => (s.handoffs.some((h) => h.id === id) ? { handoffs: s.handoffs.filter((h) => h.id !== id) } : s)),+ prune: (now) => set((s) => {+ const handoffs = freshHandoffs(s.handoffs, now);+ return handoffs === s.handoffs ? s : { handoffs };+ }),+ reset: () => set({ rounds: {}, handoffs: [] }),+}));++/** The message `agentId` still has to walk over, oldest first; null when there is none. */+export function pendingHandoff(handoffs: readonly Handoff[], agentId: string, now: number): Handoff | null {+ return handoffs.find((h) => h.from === agentId && h.untilMs > now) ?? null;+}++/**+ * The newest line an agent said in any round the office watched, or null. A+ * line gives way the moment somebody else has the word in that round: only+ * one member of a team carries a bubble at a time.+ */+export function lastSpokeBy(rounds: Record<string, TeamRound>, agentId: string): (RoundLine & { atMs: number }) | null {+ let last: (RoundLine & { atMs: number }) | null = null;+ for (const round of Object.values(rounds)) {+ if (round.spoke?.speaker !== agentId) continue;+ if (round.running && round.speakerId !== null && round.speakerId !== agentId) continue;+ if (!last || round.spoke.atMs > last.atMs) last = round.spoke;+ }+ return last;+}++/** True while the agent is the one contributing to a running round. */+export function isSpeaking(rounds: Record<string, TeamRound>, agentId: string): boolean {+ for (const round of Object.values(rounds)) if (round.running && round.speakerId === agentId) return true;+ return false;+}++/**+ * What teamwork puts over an agent's head, most telling first: the message it+ * is delivering to a colleague, the line it just said in its team's round, a+ * thought while it is the round's speaker (its line is not written yet), and+ * a message it sent while it keeps working at its desk. Every text is the+ * real one; `thinking` and `to` ("To {0}: {1}") are the only labels.+ */+export function teamBubble(input: {+ spoke: (RoundLine & { atMs: number }) | null; speaking: boolean; handoff: Handoff | null; now: number;+ labels: { thinking: string; to: string };+ /** Shortens a line to bubble size (officeTalk's `bubbleText`). */+ short: (text: string, max: number) => string;+}): Bubble | null {+ const { spoke, speaking, handoff, now, labels, short } = input;+ const sent = handoff ? labels.to.replace("{0}", handoff.toName || "…").replace("{1}", short(handoff.text, 130)) : "";+ if (handoff?.phase === "delivering" && handoff.untilMs > now) return { kind: "speech", text: sent, live: false, atMs: handoff.atMs };+ if (spoke && now - spoke.atMs < SPOKE_LINGER_MS) return { kind: "speech", text: short(spoke.text, 170), live: false, atMs: spoke.atMs };+ if (speaking) return { kind: "thought", text: labels.thinking, live: true, atMs: 0 };+ if (handoff && now - handoff.atMs < HANDOFF_BUBBLE_MS) return { kind: "speech", text: sent, live: false, atMs: handoff.atMs };+ return null;+}++/**+ * Is anything of this agent's teamwork still on its way out of view: a line+ * it said that still lingers, or a message it sent that is still shown? The+ * bubble's clock ticks only that long; a line said an hour ago must not keep+ * a bubble re-rendering every second for the rest of the session.+ */+export function teamBubbleLive(spoke: { atMs: number } | null, handoff: Handoff | null, now: number): boolean {+ if (spoke && now - spoke.atMs < SPOKE_LINGER_MS) return true;+ if (!handoff) return false;+ return handoff.phase === "delivering" ? handoff.untilMs > now : now - handoff.atMs < HANDOFF_BUBBLE_MS;+}++const watchers = new Map<symbol, ReadonlySet<string>>();++/**+ * Teams whose board a camera is close to right now. Every mounted floor+ * writes its own set under its own key (two floors can be awake at once: the+ * Agents view and the IDE's side panel), and the poll reads the union: one+ * floor going to sleep or unmounting never blinds the other.+ */+export const boardWatch = {+ set(stage: symbol, near: ReadonlySet<string>): void { watchers.set(stage, near); },+ clear(stage: symbol): void { watchers.delete(stage); },+ near(): Set<string> {+ const all = new Set<string>();+ for (const set of watchers.values()) for (const id of set) all.add(id);+ return all;+ },+ /** Forget every floor (tests). */+ reset(): void { watchers.clear(); },+};diff --git a/jarvis/ui/web/frontend/src/components/society/office/useDeskChats.test.tsx b/jarvis/ui/web/frontend/src/components/society/office/useDeskChats.test.tsxnew file mode 100644index 0000000000..c81f57f8dc--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/useDeskChats.test.tsx@@ -0,0 +1,156 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { act, cleanup, renderHook } from "@testing-library/react";+import { READ_TIMEOUT_MS, readSignal, withReadSignal } from "./pollSignal";+import { MAX_PER_TICK, dueDesks, keptChats, useDeskChats, type DeskChat } from "./useDeskChats";+import { seatedAtDesk } from "./walkerRegistry";++const reads = vi.hoisted(() => ({ calls: [] as string[], signals: [] as (AbortSignal | undefined)[], hang: new Set<string>(), fail: new Set<string>(), seq: 0 }));+vi.mock("@/lib/agentChatApi", () => ({+ fetchAgentChatSession: (sessionId: string, options: { tail?: number; signal?: AbortSignal } = {}) => {+ reads.calls.push(sessionId);+ reads.signals.push(options.signal);+ if (reads.hang.has(sessionId)) return new Promise(() => undefined);+ if (reads.fail.has(sessionId)) return Promise.reject(new Error("HTTP 500"));+ reads.seq += 1;+ return Promise.resolve({ session: {}, events: [{ seq: reads.seq, kind: "assistant_text", payload: { text: `line ${reads.seq} of ${sessionId}` } }] });+ },+}));++const sessionsFor = (count: number) => new Map(Array.from({ length: count }, (_, i) => [`a${i}`, `s${i}`] as const));+/** One scheduler tick, with the jitter pinned to its middle: the first after 0.6 s, then one every 3.1 s. */+const tick = async () => { await act(async () => { await vi.advanceTimersByTimeAsync(3100); }); };++beforeEach(() => {+ vi.useFakeTimers();+ vi.spyOn(Math, "random").mockReturnValue(0.5);+ vi.spyOn(console, "debug").mockImplementation(() => undefined);+ reads.calls.length = 0; reads.signals.length = 0; reads.hang.clear(); reads.fail.clear(); reads.seq = 0;+ seatedAtDesk.clear();+});++afterEach(() => {+ cleanup();+ seatedAtDesk.clear();+ vi.restoreAllMocks();+ vi.useRealTimers();+});++describe("which desks are read on a tick", () => {+ it("takes the longest unread first, never more than the cap, and only agents with a chat", () => {+ const sessions = sessionsFor(9);+ const seated = [...sessions.keys(), "no-session"];+ const first = dueDesks(seated, sessions, new Map());+ expect(first).toEqual(["a0", "a1", "a2", "a3", "a4", "a5"]);+ expect(first).toHaveLength(MAX_PER_TICK);+ // Those six were just read: the next tick belongs to the three that were not, then the oldest again.+ const lastRead = new Map<string, number>(first.map((id) => [id, 1000] as const));+ expect(dueDesks(seated, sessions, lastRead)).toEqual(["a6", "a7", "a8", "a0", "a1", "a2"]);+ lastRead.set("a6", 2000).set("a7", 2000).set("a8", 2000).set("a0", 2000).set("a1", 2000).set("a2", 2000);+ expect(dueDesks(seated, sessions, lastRead)).toEqual(["a3", "a4", "a5", "a0", "a1", "a2"]);+ // A read still under way is not asked again and takes one of the six places.+ expect(dueDesks(seated, sessions, lastRead, new Set(["a3", "a4"]))).toEqual(["a5", "a0", "a1", "a2"]);+ expect(dueDesks(seated, sessions, lastRead, new Set(first))).toEqual([]);+ });++ it("forgets the chats of agents that left, and keeps the same map when nobody did", () => {+ const chat: DeskChat = { lines: [], version: "1:1" };+ const chats = new Map([["a0", chat], ["a1", chat], ["gone", chat]]);+ const kept = keptChats(chats, sessionsFor(2));+ expect([...kept.keys()]).toEqual(["a0", "a1"]);+ expect(keptChats(kept, sessionsFor(2))).toBe(kept);+ });+});++describe("useDeskChats", () => {+ it("gives every seated agent its turn on a floor with more of them than one tick reads", async () => {+ const sessions = sessionsFor(14);+ for (const id of sessions.keys()) seatedAtDesk.add(id);+ const view = renderHook(() => useDeskChats(sessions, true));+ await tick();+ expect(reads.calls).toHaveLength(MAX_PER_TICK);+ await tick();+ await tick();+ // Three ticks, eighteen reads, and all fourteen monitors have something to show.+ expect(new Set(reads.calls).size).toBe(14);+ expect(view.result.current.size).toBe(14);+ expect(view.result.current.get("a13")?.lines[0].text).toContain("s13");+ });++ it("is not frozen by a read that never answers, and does not let it keep its place in every tick", async () => {+ const sessions = sessionsFor(8);+ for (const id of sessions.keys()) seatedAtDesk.add(id);+ reads.hang.add("s0");+ const view = renderHook(() => useDeskChats(sessions, true));+ await tick();+ expect(reads.calls).toContain("s0");+ // The five that answered are on their monitors at once: nobody waits for the one that hangs.+ expect(view.result.current.size).toBe(5);+ await tick();+ // The next tick came on time, read the two left over, and did not ask the hanging session again.+ expect(view.result.current.size).toBe(7);+ expect(view.result.current.has("a0")).toBe(false);+ expect(reads.calls.filter((c) => c === "s0")).toHaveLength(1);+ expect(reads.signals[0]?.aborted).toBe(false);+ // After its timeout the hanging read is given up, and only then tried again.+ await act(async () => { await vi.advanceTimersByTimeAsync(READ_TIMEOUT_MS); });+ expect(reads.signals[0]?.aborted).toBe(true);+ await tick();+ expect(reads.calls.filter((c) => c === "s0").length).toBeGreaterThanOrEqual(2);+ });++ it("aborts what is in flight when the stage sleeps, and drops the chat of an agent that left", async () => {+ const sessions = sessionsFor(3);+ for (const id of sessions.keys()) seatedAtDesk.add(id);+ const view = renderHook(({ list, awake }) => useDeskChats(list, awake), { initialProps: { list: sessions as ReadonlyMap<string, string>, awake: true } });+ await tick();+ expect(view.result.current.size).toBe(3);+ reads.hang.add("s1");+ await tick();+ const hanging = reads.signals[reads.calls.lastIndexOf("s1")];+ expect(hanging?.aborted).toBe(false);+ view.rerender({ list: sessions, awake: false });+ expect(hanging?.aborted).toBe(true);+ const calls = reads.calls.length;+ await act(async () => { await vi.advanceTimersByTimeAsync(20_000); });+ expect(reads.calls).toHaveLength(calls);+ // An agent leaves the roster: its chat goes with it.+ view.rerender({ list: sessionsFor(2), awake: false });+ expect([...view.result.current.keys()].sort()).toEqual(["a0", "a1"]);+ });+});++describe("a read's signal", () => {+ it("aborts with its parent or after its time, whichever comes first", () => {+ const parent = new AbortController();+ const first = readSignal(parent.signal, 1000);+ expect(first.signal.aborted).toBe(false);+ parent.abort();+ expect(first.signal.aborted).toBe(true);+ const other = new AbortController();+ const second = readSignal(other.signal, 1000);+ vi.advanceTimersByTime(999);+ expect(second.signal.aborted).toBe(false);+ vi.advanceTimersByTime(1);+ expect(second.signal.aborted).toBe(true);+ // Settled in time: the timer is gone and nothing aborts later.+ const third = readSignal(other.signal, 1000);+ third.done();+ vi.advanceTimersByTime(5000);+ expect(third.signal.aborted).toBe(false);+ // A parent that is already aborted aborts the read at once.+ expect(readSignal(parent.signal).signal.aborted).toBe(true);+ });++ it("rejects a read that ignores its signal once the time is up, and passes a good one through", async () => {+ const parent = new AbortController();+ const stuck = withReadSignal(parent.signal, () => new Promise<number>(() => undefined), 1000);+ const outcome = stuck.then(() => "resolved", (error: Error) => error.message);+ await vi.advanceTimersByTimeAsync(1000);+ expect(await outcome).toBe("read timed out");+ await expect(withReadSignal(parent.signal, () => Promise.resolve(7), 1000)).resolves.toBe(7);+ await expect(withReadSignal(parent.signal, () => Promise.reject(new Error("HTTP 500")), 1000)).rejects.toThrow("HTTP 500");+ const cancelled = withReadSignal(parent.signal, () => new Promise<number>(() => undefined), 1000).then(() => "resolved", (error: Error) => error.message);+ parent.abort();+ expect(await cancelled).toBe("read cancelled");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/useDeskChats.ts b/jarvis/ui/web/frontend/src/components/society/office/useDeskChats.tsindex 6260094c19..b4feb4e4ea 100644--- a/jarvis/ui/web/frontend/src/components/society/office/useDeskChats.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/useDeskChats.ts@@ -1,61 +1,95 @@/*** 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.+ * Polls the existing session endpoint only for seated agents, at most six per+ * tick, the longest unread first, so every monitor on a full floor gets its+ * turn. Jittered so windows and agents never fire in lockstep (AP-33). A+ * failed poll keeps the last good screen; it is logged, not shown. The ticks+ * do not wait for the reads: each read shows its answer when it comes, has a+ * timeout, and is aborted when the poller stops, so a request hanging on a+ * half-open socket costs one of the six places for a few seconds and nothing+ * else.*/import { useEffect, useRef, useState } from "react";import { fetchAgentChatSession } from "@/lib/agentChatApi";import { chatLines, chatVersion, type ChatLine } from "./deskChat";+import { withReadSignal } from "./pollSignal";+import { seatedAtDesk } from "./walkerRegistry";/** Events fetched per poll: enough for a full screen after tool noise is filtered out. */const TAIL_EVENTS = 60;-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 const MAX_PER_TICK = 6;export interface DeskChat { lines: ChatLine[]; version: string }+/**+ * Which seated agents to read on this tick: those with a chat session and no+ * read still under way (`inFlight`), the one read longest ago first (never+ * read = first of all). Reads under way count against the `cap`, so there are+ * never more than that many at once. With more seated agents than the cap the+ * reads rotate, so nobody's monitor starves. Pure.+ */+export function dueDesks(+ seated: Iterable<string>, sessions: ReadonlyMap<string, string>, lastRead: ReadonlyMap<string, number>,+ inFlight: ReadonlySet<string> = new Set(), cap = MAX_PER_TICK,+): string[] {+ return [...seated].filter((id) => sessions.has(id) && !inFlight.has(id))+ .sort((a, b) => (lastRead.get(a) ?? 0) - (lastRead.get(b) ?? 0) || a.localeCompare(b))+ .slice(0, Math.max(0, cap - inFlight.size));+}++/** The chats of agents that are still on the floor; the same map when nobody left. */+export function keptChats(chats: ReadonlyMap<string, DeskChat>, sessions: ReadonlyMap<string, string>): ReadonlyMap<string, DeskChat> {+ let kept: Map<string, DeskChat> | null = null;+ for (const id of chats.keys()) {+ if (sessions.has(id)) continue;+ kept ??= new Map(chats);+ kept.delete(id);+ }+ return kept ?? chats;+}+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;+ // An agent that left the floor takes its chat with it.+ useEffect(() => { setChats((prev) => keptChats(prev, sessions)); }, [sessions]);useEffect(() => {if (!awake) return;- let cancelled = false;+ const stop = new AbortController();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)!, { tail: TAIL_EVENTS });- 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);+ const lastRead = new Map<string, number>();+ const inFlight = new Set<string>();+ const read = async (agentId: string) => {+ // Counted as read whatever comes of it, so a session that keeps failing cannot keep its place in every tick.+ lastRead.set(agentId, Date.now());+ inFlight.add(agentId);+ try {+ const sessionId = sessionsRef.current.get(agentId)!;+ const detail = await withReadSignal(stop.signal, (signal) => fetchAgentChatSession(sessionId, { tail: TAIL_EVENTS, signal }));+ if (stop.signal.aborted || !sessionsRef.current.has(agentId)) return;+ const chat: DeskChat = { lines: chatLines(detail.events), version: chatVersion(detail.events) };+ setChats((prev) => (prev.get(agentId)?.version === chat.version ? prev : new Map(prev).set(agentId, chat)));+ } catch (error) {+ // The monitor keeps its last good frame; the chat view itself reports real failures.+ if (!stop.signal.aborted) console.debug("Desk chat poll failed", agentId, error);+ } finally {+ inFlight.delete(agentId);+ }+ };+ const tick = () => {+ for (const id of [...lastRead.keys()]) if (!sessionsRef.current.has(id)) lastRead.delete(id);+ for (const agentId of dueDesks(seatedAtDesk, sessionsRef.current, lastRead, inFlight)) void read(agentId);+ // The next tick does not wait for these reads: one that hangs holds nothing back.+ timer = setTimeout(tick, POLL_MS + Math.random() * JITTER_MS);};- timer = setTimeout(() => void tick(), Math.random() * JITTER_MS);- return () => { cancelled = true; clearTimeout(timer); };+ timer = setTimeout(tick, Math.random() * JITTER_MS);+ return () => { stop.abort(); clearTimeout(timer); };}, [awake]);return chats;}diff --git a/jarvis/ui/web/frontend/src/components/society/office/useTeamRounds.test.tsx b/jarvis/ui/web/frontend/src/components/society/office/useTeamRounds.test.tsxnew file mode 100644index 0000000000..e09e38c373--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/useTeamRounds.test.tsx@@ -0,0 +1,308 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { act, cleanup, renderHook } from "@testing-library/react";+import type { SocietyMeeting } from "@/lib/societyChatGroups";+import { useEventStore } from "@/store/events";+import type { SocietyAgent } from "../data";+import type { Studio } from "./officeLayout";+import { READ_TIMEOUT_MS } from "./pollSignal";+import { boardWatch, emptyRound, useTeamwork } from "./teamwork";+import { BOARD_REFRESH_MS, MAX_FAILED_READS, ROUND_POLL_MS, SWEEP_MS, afterFailedRead, useTeamRounds } from "./useTeamRounds";++const reads = vi.hoisted(() => ({ calls: [] as string[], answer: new Map<string, unknown>(), signals: [] as (AbortSignal | undefined)[] }));+/** An answer that never comes: a request hanging on a half-open socket. */+const HANGS = "hangs";+vi.mock("@/lib/societyChatGroups", () => ({+ fetchSocietyMeeting: (groupId: string, signal?: AbortSignal) => {+ reads.calls.push(groupId);+ reads.signals.push(signal);+ const answer = reads.answer.get(groupId);+ if (answer === "hangs") return new Promise(() => undefined);+ return answer instanceof Error ? Promise.reject(answer) : Promise.resolve(answer);+ },+}));+/** The key under which these tests say which boards a camera is near. */+const STAGE = Symbol("test-stage");++const agent = (agentId: string, tier = "specialist", checkpoint = "desk") => ({ agentId, name: agentId.toUpperCase(), tier, checkpoint } as unknown as SocietyAgent);+const roster = (extra: SocietyAgent[] = []) => new Map([agent("jarvis", "lead"), agent("nora"), agent("ben"), agent("kai"), ...extra].map((a) => [a.agentId, a]));+const studio = (teamId: string | null, members: string[]): Studio => ({+ deptId: `studio-${teamId ?? "pool"}`, teamId, name: teamId ?? "", members, leadId: null, board: null, huddleSpotIds: [], centre: { x: 0, z: 0 },+});+const studios = [studio(null, ["kai"]), studio("t1", ["nora", "ben"]), studio("t2", [])];+const meeting = (running: boolean, messages: [string, string, string][] = [], next: string | null = null): SocietyMeeting => ({+ messages: messages.map(([id, speaker, text]) => ({ id, speaker, text })), running, room: { state: running ? "running" : "settled", settle_reason: "", next_speaker: next },+});+let seq = 0;+const push = (name: string, payload: Record<string, unknown>) => act(() => {+ useEventStore.getState().pushEvent({ id: `ev-${seq += 1}`, name, layer: "society", ts: Date.now(), payload });+});+/** Let exactly one scheduled tick (and the reads it starts) run: with the jitter pinned to its middle, one every three seconds. */+const tick = async () => { await act(async () => { await vi.advanceTimersByTimeAsync(ROUND_POLL_MS + 600); }); };++beforeEach(() => {+ vi.useFakeTimers();+ vi.spyOn(Math, "random").mockReturnValue(0.5);+ reads.calls.length = 0;+ reads.signals.length = 0;+ reads.answer.clear();+ reads.answer.set("t1", meeting(false));+ reads.answer.set("t2", meeting(false));+ boardWatch.reset();+ useTeamwork.getState().reset();+ vi.spyOn(console, "debug").mockImplementation(() => undefined);+});++afterEach(() => {+ // Unmount, so the one poller's lease is free for the next test.+ cleanup();+ vi.restoreAllMocks();+ vi.useRealTimers();+ useTeamwork.getState().reset();+});++describe("useTeamRounds", () => {+ it("reads every team once after waking, then leaves a quiet campus alone until the sweep comes round", async () => {+ renderHook(() => useTeamRounds(studios, roster(), true));+ await tick();+ expect([...reads.calls].sort()).toEqual(["t1", "t2"]);+ for (let i = 0; i < 6; i += 1) await tick();+ expect(reads.calls).toHaveLength(2);+ // About a minute later each team is looked at again.+ await act(async () => { await vi.advanceTimersByTimeAsync(SWEEP_MS); });+ expect([...reads.calls].sort()).toEqual(["t1", "t1", "t2", "t2"]);+ });++ it("finds a round that was already running when the office opened, without any socket event", async () => {+ reads.answer.set("t1", meeting(true, [["r1", "user", "Plan the launch"], ["e1", "nora", "I take the copy."]], "ben"));+ renderHook(() => useTeamRounds(studios, roster(), true));+ expect(useTeamwork.getState().rounds).toEqual({});+ await tick();+ const round = useTeamwork.getState().rounds.t1;+ expect(round).toMatchObject({ running: true, speakerId: "ben", loaded: true });+ expect(round.lines.map((l) => l.id)).toEqual(["r1", "e1"]);+ // An old line is on the board, not replayed over anybody's head.+ expect(round.spoke).toBeNull();+ // From now on it is followed like any running round, tick by tick.+ reads.answer.set("t1", meeting(true, [["r1", "user", "Plan the launch"], ["e1", "nora", "I take the copy."], ["e2", "ben", "I book the room."]], "nora"));+ await tick();+ expect(useTeamwork.getState().rounds.t1).toMatchObject({ speakerId: "nora", spoke: { id: "e2", speaker: "ben" } });+ // And its end is found the same way.+ reads.answer.set("t1", meeting(false, [["r1", "user", "Plan the launch"], ["e1", "nora", "I take the copy."], ["e2", "ben", "I book the room."]]));+ await tick();+ expect(useTeamwork.getState().rounds.t1).toMatchObject({ running: false, speakerId: null });+ });++ it("follows a round from the socket: it opens, a member speaks, it settles", async () => {+ renderHook(() => useTeamRounds(studios, roster(), true));+ push("SocietyRoomChanged", { room_id: "meeting:t1:9f", phase: "open", members: ["nora", "ben"] });+ expect(useTeamwork.getState().rounds.t1).toMatchObject({ running: true, members: ["nora", "ben"] });++ reads.answer.set("t1", meeting(true, [["r1", "user", "Plan the launch"]], "nora"));+ await tick();+ expect(reads.calls).toContain("t1");+ expect(useTeamwork.getState().rounds.t1).toMatchObject({ running: true, speakerId: "nora", loaded: true });++ push("SocietyMessageSent", { event_id: "e1", msg_type: "SAY", from_agent: "nora", to_agent: "", room_id: "meeting:t1:9f", text: "I take the copy." });+ const said = useTeamwork.getState().rounds.t1;+ expect(said.spoke).toMatchObject({ id: "e1", speaker: "nora", text: "I take the copy." });+ expect(said.speakerId).toBeNull();+ // A line said in a room is never a message between two agents.+ expect(useTeamwork.getState().handoffs).toEqual([]);++ reads.answer.set("t1", meeting(true, [["r1", "user", "Plan the launch"], ["e1", "nora", "I take the copy."]], "ben"));+ await tick();+ expect(useTeamwork.getState().rounds.t1.speakerId).toBe("ben");++ push("SocietyRoomChanged", { room_id: "meeting:t1:9f", phase: "settle", reason: "user_round_complete" });+ expect(useTeamwork.getState().rounds.t1).toMatchObject({ running: false, speakerId: null });+ reads.answer.set("t1", meeting(false, [["r1", "user", "Plan the launch"], ["e1", "nora", "I take the copy."]]));+ await tick();+ const before = reads.calls.length;+ await tick();+ await tick();+ // Settled and read once more: it is left alone again.+ expect(reads.calls.length).toBe(before);+ });++ it("ignores rooms that are not a team's meeting, and teams the floor does not have", async () => {+ renderHook(() => useTeamRounds(studios, roster(), true));+ push("SocietyRoomChanged", { room_id: "town-hall:7", phase: "open", members: ["nora"] });+ push("SocietyRoomChanged", { room_id: "meeting:somebody-else:1", phase: "open", members: ["nora"] });+ push("SocietyMessageSent", { event_id: "e9", msg_type: "SAY", from_agent: "nora", to_agent: "", room_id: "meeting:somebody-else:1", text: "hi" });+ expect(useTeamwork.getState().rounds).toEqual({});+ await tick();+ expect(reads.calls).not.toContain("somebody-else");+ expect(Object.keys(useTeamwork.getState().rounds).sort()).toEqual(["t1", "t2"]);+ });++ it("queues a message one agent sent another, and leaves the lead's errands to its pet", () => {+ renderHook(() => useTeamRounds(studios, roster(), true));+ push("SocietyMessageSent", { event_id: "m1", msg_type: "ASSIGN", from_agent: "ben", to_agent: "nora", room_id: "", text: "Draft the notes" });+ push("SocietyMessageSent", { event_id: "m2", msg_type: "ASSIGN", from_agent: "jarvis", to_agent: "nora", room_id: "", text: "From the lead" });+ expect(useTeamwork.getState().handoffs.map((h) => [h.id, h.from, h.to, h.toName, h.text])).toEqual([["m1", "ben", "nora", "NORA", "Draft the notes"]]);+ });++ it("keeps a board near the camera current, slowly, and a far one not at all", async () => {+ boardWatch.set(STAGE, new Set(["t2"]));+ reads.answer.set("t2", meeting(false, [["r1", "user", "Hello team"]]));+ renderHook(() => useTeamRounds(studios, roster(), true));+ const of = (id: string) => reads.calls.filter((c) => c === id).length;+ await tick();+ expect(of("t2")).toBe(1);+ expect(useTeamwork.getState().rounds.t2).toMatchObject({ loaded: true, running: false });+ expect(useTeamwork.getState().rounds.t2.lines).toHaveLength(1);+ await tick();+ await tick();+ expect(of("t2")).toBe(1);+ await act(async () => { await vi.advanceTimersByTimeAsync(BOARD_REFRESH_MS); });+ // The near board was read again; the far team only once, by the sweep.+ expect(of("t2")).toBe(2);+ expect(of("t1")).toBe(1);+ });++ it("checks a team whose member the roster shows in a room", async () => {+ renderHook(() => useTeamRounds(studios, roster([agent("ben", "specialist", "meeting")]), true));+ reads.answer.set("t1", meeting(true, [], "ben"));+ await tick();+ expect(reads.calls[0]).toBe("t1");+ expect(useTeamwork.getState().rounds.t1).toMatchObject({ running: true, speakerId: "ben" });+ });++ it("stops showing a round it can no longer read, instead of leaving the team at the board", async () => {+ renderHook(() => useTeamRounds(studios, roster(), true));+ push("SocietyRoomChanged", { room_id: "meeting:t1:9f", phase: "open", members: ["nora", "ben"] });+ reads.answer.set("t1", new Error("HTTP 500"));+ // One failed read is a hiccup: the round stays.+ await act(async () => { await vi.advanceTimersByTimeAsync(1300); });+ expect(reads.calls.length).toBeGreaterThanOrEqual(1);+ expect(useTeamwork.getState().rounds.t1.running).toBe(true);+ // Five in a row are not.+ for (let i = 0; i < 6; i += 1) await tick();+ expect(reads.calls.length).toBeGreaterThanOrEqual(5);+ expect(useTeamwork.getState().rounds.t1.running).toBe(false);+ });++ it("is silent while the stage sleeps: no reads, no feed", async () => {+ boardWatch.set(STAGE, new Set(["t1", "t2"]));+ const view = renderHook(({ awake }) => useTeamRounds(studios, roster(), awake), { initialProps: { awake: false } });+ push("SocietyRoomChanged", { room_id: "meeting:t1:9f", phase: "open", members: ["nora"] });+ push("SocietyMessageSent", { event_id: "m1", msg_type: "SAY", from_agent: "ben", to_agent: "nora", room_id: "", text: "hi" });+ await tick();+ await tick();+ expect(reads.calls).toEqual([]);+ expect(useTeamwork.getState().rounds).toEqual({});+ expect(useTeamwork.getState().handoffs).toEqual([]);+ // Awake again: the boards in view are read, and nothing that happened meanwhile is replayed.+ view.rerender({ awake: true });+ await tick();+ expect([...reads.calls].sort()).toEqual(["t1", "t2"]);+ expect(useTeamwork.getState().handoffs).toEqual([]);+ });++ it("forgets the rounds of a team that was deleted", async () => {+ const view = renderHook(({ list }) => useTeamRounds(list, roster(), true), { initialProps: { list: studios } });+ push("SocietyRoomChanged", { room_id: "meeting:t1:9f", phase: "open", members: ["nora"] });+ expect(Object.keys(useTeamwork.getState().rounds)).toEqual(["t1"]);+ view.rerender({ list: [studios[0], studios[2]] });+ expect(useTeamwork.getState().rounds).toEqual({});+ });+});++describe("reads that go wrong", () => {+ it("gives a hanging read up after its timeout and keeps ticking meanwhile", async () => {+ reads.answer.set("t1", HANGS);+ reads.answer.set("t2", meeting(true, [], "nora"));+ renderHook(() => useTeamRounds(studios, roster(), true));+ await tick();+ // The team that answered is known at once: nobody waits for the read that hangs.+ expect(useTeamwork.getState().rounds.t2).toMatchObject({ running: true, speakerId: "nora" });+ expect(useTeamwork.getState().rounds.t1).toBeUndefined();+ // The next ticks come on time and follow the running round; the hanging team is not asked again meanwhile.+ await tick();+ await tick();+ expect(reads.calls.filter((c) => c === "t2").length).toBeGreaterThanOrEqual(3);+ expect(reads.calls.filter((c) => c === "t1")).toHaveLength(1);+ await act(async () => { await vi.advanceTimersByTimeAsync(READ_TIMEOUT_MS); });+ // After its timeout the hanging read was aborted and counted as failed.+ expect(reads.signals[reads.calls.indexOf("t1")]?.aborted).toBe(true);+ expect(useTeamwork.getState().rounds.t1).toMatchObject({ loaded: false, unavailable: true });+ // And the loop goes on: the running round is read again on the following ticks.+ const before = reads.calls.filter((c) => c === "t2").length;+ reads.answer.set("t1", meeting(false));+ for (let i = 0; i < 4; i += 1) await tick();+ expect(reads.calls.filter((c) => c === "t2").length).toBeGreaterThan(before);+ });++ it("aborts the reads in flight when the stage goes to sleep, and writes nothing afterwards", async () => {+ reads.answer.set("t1", HANGS);+ reads.answer.set("t2", HANGS);+ const view = renderHook(({ awake }) => useTeamRounds(studios, roster(), awake), { initialProps: { awake: true } });+ await tick();+ expect(reads.signals).toHaveLength(2);+ expect(reads.signals.every((s) => s && !s.aborted)).toBe(true);+ view.rerender({ awake: false });+ expect(reads.signals.every((s) => s?.aborted)).toBe(true);+ await act(async () => { await vi.advanceTimersByTimeAsync(READ_TIMEOUT_MS * 2); });+ expect(useTeamwork.getState().rounds).toEqual({});+ expect(reads.calls).toHaveLength(2);+ });++ it("says a team whose chat was never read is unavailable, and keeps what was read before a failure", () => {+ expect(afterFailedRead(undefined, "t", 1, 500)).toMatchObject({ teamId: "t", loaded: false, unavailable: true, fetchedMs: 500, running: false });+ const known = { ...emptyRound("t"), loaded: true, running: true, speakerId: "nora", lines: [{ id: "e1", speaker: "nora", text: "hi" }] };+ expect(afterFailedRead(known, "t", 1, 500)).toMatchObject({ running: true, speakerId: "nora", unavailable: true, lines: known.lines });+ expect(afterFailedRead(known, "t", MAX_FAILED_READS, 500)).toMatchObject({ running: false, speakerId: null, lines: known.lines });+ });++ it("clears the unavailable mark with the next good read", async () => {+ reads.answer.set("t1", new Error("HTTP 500"));+ renderHook(() => useTeamRounds(studios, roster(), true));+ await tick();+ expect(useTeamwork.getState().rounds.t1.unavailable).toBe(true);+ reads.answer.set("t1", meeting(false, [["r1", "user", "Hello"]]));+ await act(async () => { await vi.advanceTimersByTimeAsync(SWEEP_MS * 1.2); });+ expect(useTeamwork.getState().rounds.t1).toMatchObject({ loaded: true, unavailable: false });+ });+});++describe("one poller for the whole app", () => {+ it("reads once when two floors are awake at the same time, and the second takes over when the first sleeps", async () => {+ const first = renderHook(({ awake }) => useTeamRounds(studios, roster(), awake), { initialProps: { awake: true } });+ renderHook(() => useTeamRounds(studios, roster(), true));+ await tick();+ // Two teams, read once each: not once per floor.+ expect([...reads.calls].sort()).toEqual(["t1", "t2"]);+ push("SocietyMessageSent", { event_id: "m1", msg_type: "ASSIGN", from_agent: "ben", to_agent: "nora", room_id: "", text: "Draft the notes" });+ expect(useTeamwork.getState().handoffs).toHaveLength(1);++ first.rerender({ awake: false });+ reads.answer.set("t1", meeting(true, [], "ben"));+ push("SocietyRoomChanged", { room_id: "meeting:t1:9f", phase: "open", members: ["nora", "ben"] });+ expect(useTeamwork.getState().rounds.t1.running).toBe(true);+ await tick();+ await tick();+ expect(useTeamwork.getState().rounds.t1).toMatchObject({ running: true, speakerId: "ben", loaded: true });+ });++ it("clears out messages whose time has passed on a floor without any team", async () => {+ renderHook(() => useTeamRounds([studio(null, ["kai", "nora", "ben"])], roster(), true));+ push("SocietyMessageSent", { event_id: "m1", msg_type: "SAY", from_agent: "ben", to_agent: "nora", room_id: "", text: "Got a minute?" });+ expect(useTeamwork.getState().handoffs).toHaveLength(1);+ await act(async () => { await vi.advanceTimersByTimeAsync(95_000); });+ expect(useTeamwork.getState().handoffs).toEqual([]);+ expect(reads.calls).toEqual([]);+ });+});++describe("the boards a camera is near", () => {+ it("are kept per floor: one floor leaving does not blind the other", () => {+ const a = Symbol("a"), b = Symbol("b");+ boardWatch.set(a, new Set(["t1"]));+ boardWatch.set(b, new Set(["t2"]));+ expect([...boardWatch.near()].sort()).toEqual(["t1", "t2"]);+ boardWatch.clear(a);+ expect([...boardWatch.near()]).toEqual(["t2"]);+ boardWatch.set(b, new Set());+ expect(boardWatch.near().size).toBe(0);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/useTeamRounds.ts b/jarvis/ui/web/frontend/src/components/society/office/useTeamRounds.tsnew file mode 100644index 0000000000..49317d13d7--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/useTeamRounds.ts@@ -0,0 +1,239 @@+/**+ * Keeps the office's picture of team rounds and agent-to-agent messages+ * current (see teamwork.ts for what that picture is).+ *+ * The socket pushes the moments (a round opened or settled, a line was said,+ * one agent addressed another), but the office never depends on it: a round+ * that was already running when the office opened, or whose event was missed,+ * is found by reading. Reads of a team's meeting are scheduled here: every+ * team once after the stage wakes and again about once a minute (the sweep),+ * a running round every few seconds for who speaks next, and a team whose+ * board the camera is close to now and then for its transcript. Jittered so+ * windows never read in lockstep (AP-33), capped per tick, and silent while+ * the stage is asleep. The ticks do not wait for the reads: each read is+ * folded in when its answer comes, has a timeout, and is aborted when the+ * poller stops, so a request hanging on a half-open socket costs one of a+ * tick's places for a few seconds and nothing else. A failed read keeps what+ * is known; it is logged, not shown.+ *+ * The store is one for the whole app, so there is one poller: when two+ * floors are awake at once (the Agents view and the IDE's side panel), the+ * first holds the lease and the other takes over when it sleeps or unmounts.+ */+import { useEffect, useRef, useState } from "react";+import { fetchSocietyMeeting } from "@/lib/societyChatGroups";+import { useEventStore } from "@/store/events";+import type { SocietyAgent } from "../data";+import type { Studio } from "./officeLayout";+import { withReadSignal } from "./pollSignal";+import {+ applyRoomChange, applyRoomLine, applySnapshot, boardWatch, emptyRound, handoffFrom, meetingTeamId, useTeamwork, type TeamRound,+} from "./teamwork";++/** Time between two scheduling ticks, plus up to JITTER_MS. */+export const ROUND_POLL_MS = 2400;+const JITTER_MS = 1200;+/** A board near the camera refreshes its transcript this often while no round runs. */+export const BOARD_REFRESH_MS = 18_000;+/** A team whose member the roster shows in a room, without a known round, is checked this often. */+const SUSPECT_REFRESH_MS = 6000;+/** Every team is read again after about this long, wherever the camera is: the sweep that finds a round nobody announced. */+export const SWEEP_MS = 60_000;+/** The sweep's share of a tick, so it never crowds out the rounds that are running. */+export const SWEEP_READS_PER_TICK = 2;+/** Never more meeting reads per tick than this, however many teams there are. */+export const MAX_READS_PER_TICK = 4;+/** A running round that could not be read this many times in a row is no longer shown as running. */+export const MAX_FAILED_READS = 5;+/** Newest socket events inspected per update, the same bound as the errand feed. */+const MAX_CATCHUP = 64;++export interface DueInput {+ teamIds: readonly string[];+ rounds: Record<string, TeamRound>;+ /** Teams whose board is near the camera. */+ near: ReadonlySet<string>;+ /** Teams with a member the roster shows in a running room. */+ inRoom: ReadonlySet<string>;+ now: number;+ /** After how long a team is swept again; the caller jitters it. Default SWEEP_MS. */+ sweepMs?: number;+ /** Teams whose meeting is being read right now: not asked again, and counted against the cap. */+ inFlight?: ReadonlySet<string>;+}++/**+ * Which teams' meetings to read on this tick: running and freshly changed+ * rounds first (longest unread first), then teams the roster suggests are in+ * a round, then boards near the camera whose transcript has aged, then the+ * sweep: teams never read since the office opened, and teams not read for+ * about a minute. The sweep takes at most two reads of a tick, so a campus of+ * twelve teams is known within a few ticks and costs twelve reads a minute+ * while nothing happens. Pure.+ */+export function dueTeams({ teamIds: allTeams, rounds, near, inRoom, now, sweepMs = SWEEP_MS, inFlight }: DueInput, limit = MAX_READS_PER_TICK): string[] {+ const teamIds = inFlight && inFlight.size > 0 ? allTeams.filter((id) => !inFlight.has(id)) : allTeams;+ const cap = Math.max(0, limit - (inFlight?.size ?? 0));+ if (cap === 0) return [];+ const age = (id: string) => now - (rounds[id]?.fetchedMs ?? 0);+ const oldestFirst = (a: string, b: string) => age(b) - age(a) || a.localeCompare(b);+ const live = teamIds.filter((id) => rounds[id]?.running || rounds[id]?.dirty).sort(oldestFirst);+ const taken = new Set(live);+ const suspected = teamIds.filter((id) => !taken.has(id) && inRoom.has(id) && age(id) >= SUSPECT_REFRESH_MS).sort(oldestFirst);+ for (const id of suspected) taken.add(id);+ const boards = teamIds.filter((id) => !taken.has(id) && near.has(id) && age(id) >= BOARD_REFRESH_MS).sort(oldestFirst);+ for (const id of boards) taken.add(id);+ const sweep = teamIds.filter((id) => !taken.has(id) && age(id) >= sweepMs).sort(oldestFirst).slice(0, SWEEP_READS_PER_TICK);+ // The sweep's two places are kept even on a tick full of running rounds, or a busy campus would never look further.+ const first = [...live, ...suspected, ...boards];+ return [...first.slice(0, Math.max(0, cap - sweep.length)), ...sweep].slice(0, cap);+}++/**+ * A team's round after a read of its meeting failed for the `misses`-th time+ * in a row. The read counts as done, so one failing team cannot take every+ * tick's places. A round nobody can read any more is not shown as running,+ * or its members would stand at the board for ever; a team that has never+ * been read is marked unavailable, so its board can say so instead of+ * "reading" for ever. Pure.+ */+export function afterFailedRead(prev: TeamRound | undefined, teamId: string, misses: number, now: number): TeamRound {+ const round = prev ?? emptyRound(teamId);+ const lost = round.running && misses >= MAX_FAILED_READS;+ return { ...round, fetchedMs: now, dirty: false, unavailable: true, ...(lost ? { running: false, speakerId: null } : {}) };+}++/** The one poller of the app-wide teamwork store: who holds it, and who waits for it. */+const lease: { owner: symbol | null; waiting: Set<() => void> } = { owner: null, waiting: new Set() };++/** True while this caller is the one poller. Others wait and take over when the holder lets go. */+function usePollerLease(wanted: boolean): boolean {+ const [holds, setHolds] = useState(false);+ const [retry, setRetry] = useState(0);+ useEffect(() => {+ if (!wanted) return;+ const id = Symbol("team-rounds-poller");+ if (lease.owner !== null) {+ const again = () => setRetry((n) => n + 1);+ lease.waiting.add(again);+ return () => { lease.waiting.delete(again); };+ }+ lease.owner = id;+ setHolds(true);+ return () => {+ setHolds(false);+ if (lease.owner === id) lease.owner = null;+ for (const wake of [...lease.waiting]) wake();+ };+ }, [wanted, retry]);+ return wanted && holds;+}++/**+ * Feed the teamwork store while `awake`. `studios` are the floor's studios+ * (a team = a studio with a team id); `agents` is the roster.+ */+export function useTeamRounds(studios: readonly Studio[], agents: ReadonlyMap<string, SocietyAgent>, awake: boolean): void {+ const roster = useRef(agents);+ roster.current = agents;+ const teams = useRef(studios);+ teams.current = studios;+ const teamKey = studios.map((s) => s.teamId ?? "").filter(Boolean).join(",");+ const polls = usePollerLease(awake);++ // Teams that no longer exist take their rounds with them.+ useEffect(() => {+ if (!polls) return;+ useTeamwork.getState().keepTeams(new Set(teamKey ? teamKey.split(",") : []));+ }, [teamKey, polls]);++ // The moments, pushed: rounds opening and settling, lines said in them, and messages between two agents.+ useEffect(() => {+ if (!polls) return;+ let cursor: string | null = useEventStore.getState().events[0]?.id ?? null;+ return useEventStore.subscribe((state) => {+ const log = state.events;+ const top = log[0];+ if (!top || top.id === cursor) return;+ const fresh = [];+ for (let i = 0; i < log.length && i < MAX_CATCHUP; i += 1) {+ if (log[i].id === cursor) break;+ fresh.push(log[i]);+ }+ cursor = top.id;+ const now = Date.now();+ const store = useTeamwork.getState();+ const known = new Set(teams.current.map((s) => s.teamId).filter((id): id is string => id !== null));+ for (let i = fresh.length - 1; i >= 0; i -= 1) {+ const { name, payload } = fresh[i];+ if (name !== "SocietyMessageSent" && name !== "SocietyRoomChanged") continue;+ const p = (payload ?? {}) as Record<string, unknown>;+ const teamId = meetingTeamId(p.room_id);+ if (name === "SocietyRoomChanged") {+ if (teamId && known.has(teamId)) store.setRound(applyRoomChange(useTeamwork.getState().rounds[teamId], teamId, p.phase, p.members));+ continue;+ }+ if (teamId) {+ if (!known.has(teamId) || p.msg_type !== "SAY") continue;+ const id = typeof p.event_id === "string" ? p.event_id : "";+ const speaker = typeof p.from_agent === "string" ? p.from_agent : "";+ const text = typeof p.text === "string" ? p.text : "";+ if (id && speaker) store.setRound(applyRoomLine(useTeamwork.getState().rounds[teamId], teamId, { id, speaker, text }, now));+ continue;+ }+ const handoff = handoffFrom(p, roster.current, now);+ if (handoff) store.addHandoff(handoff);+ }+ });+ }, [polls]);++ // The reads, scheduled: jittered, capped, and only while the stage is awake. The loop also runs on a floor+ // without teams, where it only clears out messages whose time has passed.+ useEffect(() => {+ if (!polls) return;+ const stop = new AbortController();+ let timer: ReturnType<typeof setTimeout>;+ const failed = new Map<string, number>();+ const inFlight = new Set<string>();+ // What the office knew before it slept may be stale.+ useTeamwork.getState().markStale();+ const read = async (teamId: string) => {+ inFlight.add(teamId);+ try {+ const snapshot = await withReadSignal(stop.signal, (signal) => fetchSocietyMeeting(teamId, signal));+ if (stop.signal.aborted) return;+ failed.delete(teamId);+ useTeamwork.getState().setRound(applySnapshot(useTeamwork.getState().rounds[teamId], teamId, snapshot, Date.now()));+ } catch (error) {+ if (stop.signal.aborted) return;+ // The board keeps its last good transcript; the team's own chat view reports real failures.+ console.debug("Team round read failed", teamId, error);+ const misses = (failed.get(teamId) ?? 0) + 1;+ failed.set(teamId, misses);+ useTeamwork.getState().setRound(afterFailedRead(useTeamwork.getState().rounds[teamId], teamId, misses, Date.now()));+ } finally {+ inFlight.delete(teamId);+ }+ };+ const tick = () => {+ const now = Date.now();+ useTeamwork.getState().prune(now);+ const teamIds = teams.current.map((s) => s.teamId).filter((id): id is string => id !== null);+ for (const id of [...failed.keys()]) if (!teamIds.includes(id)) failed.delete(id);+ const inRoom = new Set<string>();+ for (const studio of teams.current) {+ if (studio.teamId && studio.members.some((id) => roster.current.get(id)?.checkpoint === "meeting")) inRoom.add(studio.teamId);+ }+ // The sweep's period is jittered per tick, so two windows never sweep in step.+ const due = dueTeams({+ teamIds, rounds: useTeamwork.getState().rounds, near: boardWatch.near(), inRoom, now, inFlight,+ sweepMs: SWEEP_MS * (0.9 + Math.random() * 0.25),+ });+ for (const teamId of due) void read(teamId);+ // The next tick does not wait for these reads: one that hangs holds nothing back.+ timer = setTimeout(tick, ROUND_POLL_MS + Math.random() * JITTER_MS);+ };+ timer = setTimeout(tick, Math.random() * JITTER_MS);+ return () => { stop.abort(); clearTimeout(timer); };+ }, [polls, teamKey]);+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/walkerRegistry.test.ts b/jarvis/ui/web/frontend/src/components/society/office/walkerRegistry.test.tsindex f9c497f989..9da803fc10 100644--- a/jarvis/ui/web/frontend/src/components/society/office/walkerRegistry.test.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/walkerRegistry.test.ts@@ -1,5 +1,5 @@import { afterEach, describe, expect, it } from "vitest";-import { agentPositions, bodiesExcept, extraBodies } from "./walkerRegistry";+import { agentPositions, bodiesExcept, bodiesNear, companions, extraBodies, placeAgent } from "./walkerRegistry";describe("bodiesExcept", () => {afterEach(() => { agentPositions.clear(); extraBodies.clear(); });@@ -17,3 +17,36 @@ describe("bodiesExcept", () => {expect(Array.from(bodiesExcept("office-dog", { x: 5, z: 5 }))).toEqual([{ x: 5, z: 5 }]);});});++describe("bodiesNear", () => {+ afterEach(() => { agentPositions.clear(); extraBodies.clear(); companions.clear(); });++ it("lists the same bodies as bodiesExcept within reach, into the caller's own array", () => {+ agentPositions.set("near", { x: 1, z: 1 });+ agentPositions.set("far", { x: 30, z: 1 });+ agentPositions.set("self", { x: 0, z: 0 });+ agentPositions.set("pet", { x: 0.5, z: 0.5 });+ companions.add("pet");+ extraBodies.set("office-dog", { x: -1, z: 2 });+ const person = { x: 2, z: -2 };+ const out: { x: number; z: number }[] = [{ x: 99, z: 99 }];+ const got = bodiesNear("self", { x: 0, z: 0 }, 7, person, out);+ expect(got).toBe(out);+ expect(got).toEqual([{ x: 1, z: 1 }, { x: -1, z: 2 }, person]);+ expect(new Set(bodiesNear("self", { x: 0, z: 0 }, Infinity, person))).toEqual(new Set(bodiesExcept("self", person)));+ expect(bodiesNear("office-dog", { x: 0, z: 0 }, 7, null)).toEqual([{ x: 1, z: 1 }, { x: 0, z: 0 }]);+ });+});++describe("placeAgent", () => {+ afterEach(() => { agentPositions.clear(); });++ it("moves an agent's entry in place instead of making a new one every frame", () => {+ placeAgent("a", 1, 2);+ const entry = agentPositions.get("a");+ expect(entry).toEqual({ x: 1, z: 2 });+ placeAgent("a", 3, 4);+ expect(agentPositions.get("a")).toBe(entry);+ expect(entry).toEqual({ x: 3, z: 4 });+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/walkerRegistry.ts b/jarvis/ui/web/frontend/src/components/society/office/walkerRegistry.tsindex f7334cade0..87b884d044 100644--- a/jarvis/ui/web/frontend/src/components/society/office/walkerRegistry.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/walkerRegistry.ts@@ -39,3 +39,68 @@ export function* bodiesExcept(selfId: string | null, player: Point | null): Gene* each frame; the level system's cosmetics and celebrations follow it.*/export const petBody = { x: 0, z: 0, y: 0, top: 0.5, sizeM: 0.5, active: false };++/**+ * The bodies within `radius` of `at`, without `selfId`: what a walker steers round. Fills and returns `out`,+ * so a walker reuses one array instead of allocating a list of the whole floor every frame.+ */+export function bodiesNear(selfId: string | null, at: Point, radius: number, player: Point | null, out: Point[] = []): Point[] {+ out.length = 0;+ // The same bodies as `bodiesExcept`, walked in place: this runs for every walker on every frame.+ for (const [id, p] of agentPositions) {+ if (id !== selfId && !companions.has(id) && Math.abs(p.x - at.x) <= radius && Math.abs(p.z - at.z) <= radius) out.push(p);+ }+ for (const [id, p] of extraBodies) {+ if (id !== selfId && Math.abs(p.x - at.x) <= radius && Math.abs(p.z - at.z) <= radius) out.push(p);+ }+ if (player && Math.abs(player.x - at.x) <= radius && Math.abs(player.z - at.z) <= radius) out.push(player);+ return out;+}++/** Write where an agent stands; its entry is moved in place, so a frame of forty walkers allocates nothing. */+export function placeAgent(agentId: string, x: number, z: number): void {+ const at = agentPositions.get(agentId);+ if (at) { at.x = x; at.z = z; } else agentPositions.set(agentId, { x, z });+}++/** What one walker is doing right now, for the dev handle (`window.__officeLife`); written in development builds only. */+export interface WalkerDebug {+ id: string;+ name: string;+ state: string;+ /** The team whose studio the agent sits in; null = the pool, or a floor without studios. */+ team: string | null;+ studio: string | null;+ /** Its part in a running round of its team: none, gather, speaker or busy. */+ role: string;+ plan: string | null;+ phase: "travel" | "dwell";+ target: Point | null;+ spot: string | null;+ with: string | null;+ at: Point;+ /** Waypoints and metres left on the current walk. */+ pathLength: number;+ remainingM: number;+ /**+ * The current walk by the walker's own clock (the frame time it was actually given, not wall time and not+ * what a stepping script assumes): seconds walked so far and the average speed along the route in m/s.+ * Both are 0 while it stands.+ */+ walkS: number;+ speed: number;+ /** Seconds without progress on the current walk (the stuck watch). */+ stuckS: number;+ /**+ * Since the walker mounted: detours round a body, safe placements, route repairs, arrivals beside an occupied+ * place, walks given up because the way stayed closed, targets a new floor plan walled off.+ */+ replans: number;+ rescues: number;+ repaths: number;+ near: number;+ blocked: number;+ lost: number;+}++export const walkerDebug = new Map<string, WalkerDebug>();diff --git a/jarvis/ui/web/frontend/src/components/society/office/wallCutaway.test.ts b/jarvis/ui/web/frontend/src/components/society/office/wallCutaway.test.tsnew file mode 100644index 0000000000..64a721e14b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/wallCutaway.test.ts@@ -0,0 +1,141 @@+import { describe, expect, it } from "vitest";+import { roomAt, wallsOf, type Room } from "./officeLayout";+import { campusLimits, cornersInView } from "./officeCamera.testkit";+import { CAMERA_LIMITS, OVERVIEW_SPAN, cameraLimitsFor, campusOverview, followBlend, frameDistance } from "./officeCamera";+import { buildOfficeLayout } from "./officeLayout";+import { rosterOf } from "./officeFixtures";+import { CUTAWAY_SCALE, cutawayStep, cutawayWalls, walledRoomAt, wallKey } from "./wallCutaway";+import { campusOf } from "./officeFixtures";++// Two walled rooms side by side sharing a wall line, and an open lobby south of them.+const west: Room = { id: "lead", kind: "lead", walled: true, minX: 0, maxX: 8, minZ: 0, maxZ: 6, doors: [{ side: "south", at: 4, width: 1.6 }] };+const east: Room = { id: "team", kind: "team", walled: true, minX: 8, maxX: 16, minZ: 0, maxZ: 6, doors: [{ side: "south", at: 12, width: 1.8 }] };+const lobby: Room = { id: "reception", kind: "reception", walled: false, minX: 0, maxX: 16, minZ: 10, maxZ: 16, doors: [] };+const rooms = [west, east, lobby];+const walls = rooms.flatMap(wallsOf);+/** Keys of the wall runs matching `test`; two rooms' runs along one shared line have one key. */+const keysOn = (test: (w: (typeof walls)[number]) => boolean) => [...new Set(walls.filter(test).map(wallKey))].sort();++describe("which walls step aside", () => {+ it("opens the sides of the person's room that the camera looks in through", () => {+ // The home view: the camera stands south-east of the room.+ const cut = cutawayWalls(rooms, walls, { x: 4, z: 3 }, { x: 20, z: 18 });+ const south = keysOn((w) => w.z1 === 6 && w.z2 === 6 && Math.max(w.x1, w.x2) <= 8);+ // The shared wall line x = 8 holds a run of each room: both step aside.+ const shared = keysOn((w) => w.x1 === 8 && w.x2 === 8);+ expect(walls.filter((w) => w.x1 === 8 && w.x2 === 8)).toHaveLength(2);+ expect([...cut].sort()).toEqual([...south, ...shared].sort());+ // The far sides stay up: they are the room's backdrop.+ expect(cut.has(wallKey(walls.find((w) => w.z1 === 0 && w.x1 === 0)!))).toBe(false);+ expect(cut.has(wallKey(walls.find((w) => w.x1 === 0 && w.x2 === 0)!))).toBe(false);+ });++ it("leaves every wall standing while the person is on the open floor or in an open room", () => {+ expect(cutawayWalls(rooms, walls, { x: 4, z: 8 }, { x: 20, z: 18 }).size).toBe(0);+ expect(cutawayWalls(rooms, walls, { x: 4, z: 12 }, { x: 20, z: 18 }).size).toBe(0);+ expect(walledRoomAt(rooms, { x: 4, z: 12 })).toBeNull();+ expect(walledRoomAt(rooms, { x: 4, z: 3 })?.kind).toBe("lead");+ });++ it("follows the camera round the room and never flickers while the person walks about inside", () => {+ const fromNorthWest = cutawayWalls(rooms, walls, { x: 12, z: 3 }, { x: -6, z: -9 });+ expect([...fromNorthWest].sort()).toEqual(keysOn((w) => (w.z1 === 0 && w.z2 === 0 && Math.min(w.x1, w.x2) >= 8) || (w.x1 === 8 && w.x2 === 8)));+ const here = cutawayWalls(rooms, walls, { x: 9, z: 1 }, { x: 20, z: 18 });+ const there = cutawayWalls(rooms, walls, { x: 15, z: 5.5 }, { x: 20, z: 18 });+ expect([...here].sort()).toEqual([...there].sort());+ // A camera straight above the room looks in through no side.+ expect(cutawayWalls(rooms, walls, { x: 12, z: 3 }, { x: 12, z: 3 }).size).toBe(0);+ });++ it("opens the rooms of the real campus for someone standing in them", () => {+ const { layout } = campusOf(20, [6, 5]);+ for (const room of layout.rooms.filter((r) => r.walled)) {+ const inside = { x: (room.minX + room.maxX) / 2, z: (room.minZ + room.maxZ) / 2 };+ expect(roomAt(layout, inside)?.kind).toBe(room.kind);+ const camera = { x: inside.x + 14, z: inside.z + 17 };+ const cut = cutawayWalls(layout.rooms, layout.walls, inside, camera);+ expect(cut.size, room.kind).toBeGreaterThan(0);+ // Only walls along this room's own sides are touched.+ for (const wall of layout.walls.filter((w) => cut.has(wallKey(w)))) {+ const onSide = Math.abs(wall.z1 - room.maxZ) < 0.2 || Math.abs(wall.x1 - room.maxX) < 0.2 || Math.abs(wall.z1 - room.minZ) < 0.2 || Math.abs(wall.x1 - room.minX) < 0.2;+ expect(onSide, room.kind).toBe(true);+ }+ }+ });++ it("glides a wall down to a kerb and back up, and places it at once for reduced motion", () => {+ let h = 1;+ for (let i = 0; i < 60; i += 1) h = cutawayStep(h, true, 1 / 60);+ expect(h).toBe(CUTAWAY_SCALE);+ const mid = cutawayStep(1, true, 1 / 60);+ expect(mid).toBeLessThan(1);+ expect(mid).toBeGreaterThan(CUTAWAY_SCALE);+ for (let i = 0; i < 60; i += 1) h = cutawayStep(h, false, 1 / 60);+ expect(h).toBe(1);+ expect(cutawayStep(1, true, 1 / 60, true)).toBe(CUTAWAY_SCALE);+ expect(cutawayStep(CUTAWAY_SCALE, false, 1 / 60, true)).toBe(1);+ });+});++describe("the camera on a campus", () => {+ it("fits the whole floor to the viewport in the overview, at any size and viewport shape", () => {+ const floors = [+ campusOf(4, []).layout.bounds, campusOf(14, [5, 4, 3]).layout.bounds,+ // The tall plan: forty agents in eight teams.+ campusOf(40, [5, 5, 5, 5, 5, 5, 5, 5]).layout.bounds, campusOf(90, [12, 11, 10, 9, 8, 8, 7, 7]).layout.bounds,+ buildOfficeLayout(rosterOf(10), { variant: "coding" }).bounds,+ ];+ for (const bounds of floors) {+ // A wide window, a squarer one, and the IDE's narrow side panel.+ for (const aspect of [16 / 9, 4 / 3, 0.62]) {+ const label = `${(bounds.maxX - bounds.minX).toFixed(0)} x ${(bounds.maxZ - bounds.minZ).toFixed(0)} m, aspect ${aspect.toFixed(2)}`;+ const pose = campusOverview(bounds, aspect);+ const { inside, box } = cornersInView(bounds, pose, aspect);+ expect(inside, label).toBe(true);+ // In the middle of the view, not in its lower half.+ expect(Math.abs(box.minX + box.maxX) / 2, label).toBeLessThan(0.02);+ expect(Math.abs(box.minY + box.maxY) / 2, label).toBeLessThan(0.02);+ // As large as it goes: it spans 85 % of whichever axis binds.+ const span = Math.max(box.maxX - box.minX, box.maxY - box.minY) / 2;+ expect(span, label).toBeGreaterThan(OVERVIEW_SPAN - 0.01);+ expect(span, label).toBeLessThan(OVERVIEW_SPAN + 0.01);+ // The look-at point stays on the floor, and the wheel can reach this view.+ expect(pose.target[1]).toBe(0);+ const distance = Math.hypot(pose.position[0] - pose.target[0], pose.position[1], pose.position[2] - pose.target[2]);+ expect(distance, label).toBeLessThanOrEqual(cameraLimitsFor(bounds, aspect).maxDistance);+ }+ }+ });++ it("stands much closer than a view that merely holds every corner", () => {+ const bounds = campusOf(14, [5, 4, 3]).layout.bounds;+ const pose = campusOverview(bounds, 16 / 9);+ const distance = Math.hypot(pose.position[0] - pose.target[0], pose.position[1], pose.position[2] - pose.target[2]);+ expect(distance).toBeLessThan(frameDistance(bounds, 16 / 9) * 0.9);+ });++ it("lets the wheel back away far enough for that overview, and never less than before", () => {+ const small = campusOf(4, []).layout.bounds;+ const large = campusOf(90, [12, 11, 10, 9, 8, 8, 7, 7]).layout.bounds;+ for (const bounds of [small, large]) {+ const limits = cameraLimitsFor(bounds, 16 / 9);+ expect(limits.maxDistance).toBeGreaterThanOrEqual(CAMERA_LIMITS.maxDistance);+ expect(limits.maxDistance).toBeGreaterThan(frameDistance(bounds, 16 / 9));+ expect(limits).toMatchObject({ minDistance: CAMERA_LIMITS.minDistance, minPolar: CAMERA_LIMITS.minPolar, maxPolar: CAMERA_LIMITS.maxPolar });+ }+ // A portrait viewport needs more room than a wide one.+ expect(frameDistance(large, 0.62)).toBeGreaterThan(frameDistance(large, 16 / 9));+ expect(campusLimits(large).maxDistance).toBeGreaterThanOrEqual(cameraLimitsFor(large, 16 / 9).maxDistance);+ });++ it("follows at the same pace whatever the frame rate, and eases out", () => {+ // One 33 ms frame closes as much of the gap as two 16.5 ms frames.+ const one = followBlend(0.033);+ const two = 1 - (1 - followBlend(0.0165)) ** 2;+ expect(one).toBeCloseTo(two, 9);+ expect(followBlend(0)).toBe(0);+ expect(followBlend(0.016)).toBeGreaterThan(0.1);+ expect(followBlend(0.016)).toBeLessThan(0.15);+ expect(followBlend(10)).toBeCloseTo(1, 6);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/wallCutaway.ts b/jarvis/ui/web/frontend/src/components/society/office/wallCutaway.tsnew file mode 100644index 0000000000..1d22da7b64--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/wallCutaway.ts@@ -0,0 +1,65 @@+/**+ * Which walls step out of the way while the person stands inside a walled+ * room: the sides of that room the camera looks in through. Like the open+ * front of a doll's house, they drop to a low kerb so the room stays+ * readable, and rise again when the person leaves or the camera turns.+ *+ * The rule is by side, not by sight line, so nothing flickers while the+ * person walks about inside: only crossing a doorway or orbiting the camera+ * changes the answer. Pure and tested; OfficeCameraRig applies it to every+ * object tagged `userData.officeWall` (see `wallKey`).+ */+import type { Point, Room, WallSegment } from "./officeLayout";++/** How close to a room's side line a wall run must lie to belong to that side. */+const ON_SIDE_M = 0.2;+/** The camera must stand this far beyond a side before that side is opened (no flicker when it is level with it). */+const BEYOND_M = 0.5;+/** A lowered wall keeps this share of its height: a kerb that still shows where the wall is. */+export const CUTAWAY_SCALE = 0.12;++/** The identity of a wall run, shared by the layout's segments and the tagged scene objects. */+export function wallKey(wall: Pick<WallSegment, "x1" | "z1" | "x2" | "z2">): string {+ return `${wall.x1.toFixed(2)}:${wall.z1.toFixed(2)}:${wall.x2.toFixed(2)}:${wall.z2.toFixed(2)}`;+}++/** The walled room the person stands in, or null (open rooms and the open office have nothing to open). */+export function walledRoomAt(rooms: readonly Room[], p: Point): Room | null {+ return rooms.find((r) => r.walled && p.x > r.minX && p.x < r.maxX && p.z > r.minZ && p.z < r.maxZ) ?? null;+}++/**+ * Keys of the wall runs to lower for a person at `person` seen by a camera+ * standing over `camera` (its position on the floor plane). Walls of the+ * neighbouring room that run along the same line are opened with it, or half+ * the side would stay up.+ */+export function cutawayWalls(rooms: readonly Room[], walls: readonly WallSegment[], person: Point, camera: Point): Set<string> {+ const cut = new Set<string>();+ const room = walledRoomAt(rooms, person);+ if (!room) return cut;+ const open = {+ north: camera.z < room.minZ - BEYOND_M, south: camera.z > room.maxZ + BEYOND_M,+ west: camera.x < room.minX - BEYOND_M, east: camera.x > room.maxX + BEYOND_M,+ };+ for (const wall of walls) {+ const horizontal = Math.abs(wall.z1 - wall.z2) < 1e-6;+ if (horizontal) {+ const overlaps = Math.min(Math.max(wall.x1, wall.x2), room.maxX) - Math.max(Math.min(wall.x1, wall.x2), room.minX) > 0.05;+ if (!overlaps) continue;+ if ((open.north && Math.abs(wall.z1 - room.minZ) < ON_SIDE_M) || (open.south && Math.abs(wall.z1 - room.maxZ) < ON_SIDE_M)) cut.add(wallKey(wall));+ } else {+ const overlaps = Math.min(Math.max(wall.z1, wall.z2), room.maxZ) - Math.max(Math.min(wall.z1, wall.z2), room.minZ) > 0.05;+ if (!overlaps) continue;+ if ((open.west && Math.abs(wall.x1 - room.minX) < ON_SIDE_M) || (open.east && Math.abs(wall.x1 - room.maxX) < ON_SIDE_M)) cut.add(wallKey(wall));+ }+ }+ return cut;+}++/** One frame of a wall's height towards its goal (1 = standing, CUTAWAY_SCALE = lowered); `snap` skips the glide. */+export function cutawayStep(current: number, lowered: boolean, dt: number, snap = false): number {+ const goal = lowered ? CUTAWAY_SCALE : 1;+ if (snap || Math.abs(goal - current) < 0.004) return goal;+ return goal + (current - goal) * Math.exp(-9 * dt);+}diff --git a/jarvis/ui/web/frontend/src/components/society/progression/progressionApi.ts b/jarvis/ui/web/frontend/src/components/society/progression/progressionApi.tsindex 71b7460681..63665e4d2c 100644--- a/jarvis/ui/web/frontend/src/components/society/progression/progressionApi.ts+++ b/jarvis/ui/web/frontend/src/components/society/progression/progressionApi.ts@@ -127,14 +127,16 @@ export async function fetchProgression(afterSeq = 0): Promise<ProgressionSnapshoreturn parseSnapshot((await res.json()) as Raw);}-/** Report a world action; the server decides whether it pays. Never throws. */+/** Report a world action; the server decides whether it pays. Never throws; a report the server refuses is logged. */export async function reportWorldAction(action: WorldAction, ref = ""): Promise<void> {try {- await fetch("/api/progression/actions", {+ const res = await fetch("/api/progression/actions", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ action, ref }),});+ // A refusal means this client and the server disagree about an action or a floor: say so, play on.+ if (!res.ok) console.warn("Level action refused", action, ref, res.status);} catch (error) {// XP is a garnish: an unreachable backend never disturbs the Verse.console.debug("Level action not reported", action, error);diff --git a/jarvis/ui/web/frontend/src/components/society/progression/useProgressionSync.ts b/jarvis/ui/web/frontend/src/components/society/progression/useProgressionSync.tsindex 18712a4f5d..75e27aab98 100644--- a/jarvis/ui/web/frontend/src/components/society/progression/useProgressionSync.ts+++ b/jarvis/ui/web/frontend/src/components/society/progression/useProgressionSync.ts@@ -22,6 +22,12 @@ const RESYNC_MS = 60_000;const RESYNC_JITTER_MS = 15_000;/** Ticks for "+XP" closer together than this are one sound. */const TICK_GAP_MS = 400;+/**+ * The floors the server pays a first visit for (`VERSE_FLOORS` in jarvis/progression/service.py). A backend+ * started before the Level Hall became a floor refuses "hall"; the report is best-effort, so that costs nothing+ * but a line in the console. `verseFloors.test.ts` holds this list, the server's and the elevator's together.+ */+export const METERED_FLOORS: ReadonlySet<OfficeFloor> = new Set<OfficeFloor>(["agents", "coding", "arcade", "hall"]);export function useProgressionSync(awake: boolean, floor: OfficeFloor): void {const seen = useRef<number>(0);@@ -78,7 +84,7 @@ export function useProgressionSync(awake: boolean, floor: OfficeFloor): void {// The day's first visit and every floor discovered.useEffect(() => { if (awake) void reportWorldAction("daily_visit"); }, [awake]);- useEffect(() => { if (awake) void reportWorldAction("floor_discovered", floor); }, [awake, floor]);+ useEffect(() => { if (awake && METERED_FLOORS.has(floor)) void reportWorldAction("floor_discovered", floor); }, [awake, floor]);// The office dog: a pat, a treat.useEffect(() => useOfficeDog.subscribe((state, prev) => {diff --git a/jarvis/ui/web/frontend/src/components/society/progression/verseFloors.test.ts b/jarvis/ui/web/frontend/src/components/society/progression/verseFloors.test.tsnew file mode 100644index 0000000000..a6eb23d39b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/progression/verseFloors.test.ts@@ -0,0 +1,77 @@+/**+ * The Verse's floors are listed in three places: the server's `VERSE_FLOORS`+ * (which floors a `floor_discovered` report may name), the client's+ * `METERED_FLOORS` (which floors it reports) and the elevator's+ * `OFFICE_FLOORS` (which floors exist). A floor missing from one of them is+ * either never paid or refused by the server, so they are held together here.+ */+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { OFFICE_FLOORS } from "../office/officeStore";+import { reportWorldAction } from "./progressionApi";+import { METERED_FLOORS } from "./useProgressionSync";++const SRC = join(__dirname, "..", "..", "..");++/** `VERSE_FLOORS` as the backend declares it. */+function serverFloors(): string[] {+ const py = readFileSync(join(SRC, "..", "..", "..", "..", "progression", "service.py"), "utf8");+ const block = /^VERSE_FLOORS\s*=\s*frozenset\(\{([^}]*)\}\)/m.exec(py);+ if (!block) throw new Error("VERSE_FLOORS is no longer a frozenset literal in jarvis/progression/service.py");+ return [...block[1].matchAll(/"([a-z_]+)"/g)].map((m) => m[1]);+}++describe("the Verse's floors", () => {+ it("are the same on the server, in the reports and in the elevator", () => {+ const server = serverFloors().sort();+ expect(server.length).toBeGreaterThan(0);+ expect([...METERED_FLOORS].sort()).toEqual(server);+ expect([...OFFICE_FLOORS].sort()).toEqual(server);+ // No floor is listed twice in the elevator.+ expect(new Set(OFFICE_FLOORS).size).toBe(OFFICE_FLOORS.length);+ });+});++describe("reporting a world action", () => {+ const realFetch = globalThis.fetch, realWarn = console.warn, realDebug = console.debug;+ afterEach(() => {+ globalThis.fetch = realFetch;+ console.warn = realWarn;+ console.debug = realDebug;+ });++ /** Answer every request with `status`, and collect what is logged. */+ function serverAnswering(status: number | Error) {+ const requests: { url: string; body: unknown }[] = [], warned: unknown[][] = [], debugged: unknown[][] = [];+ globalThis.fetch = (async (url: RequestInfo | URL, init?: RequestInit) => {+ requests.push({ url: String(url), body: JSON.parse(String(init?.body)) });+ if (status instanceof Error) throw status;+ return new Response("{}", { status });+ }) as typeof fetch;+ console.warn = (...args: unknown[]) => { warned.push(args); };+ console.debug = (...args: unknown[]) => { debugged.push(args); };+ return { requests, warned, debugged };+ }++ it("says nothing when the server takes it", async () => {+ const server = serverAnswering(200);+ await reportWorldAction("floor_discovered", "hall");+ expect(server.requests).toEqual([{ url: "/api/progression/actions", body: { action: "floor_discovered", ref: "hall" } }]);+ expect(server.warned).toEqual([]);+ });++ it("logs a report the server refuses instead of dropping it, and does not throw", async () => {+ const server = serverAnswering(400);+ await expect(reportWorldAction("floor_discovered", "attic")).resolves.toBeUndefined();+ expect(server.warned).toHaveLength(1);+ expect(server.warned[0]).toEqual(["Level action refused", "floor_discovered", "attic", 400]);+ });++ it("stays quiet about an unreachable backend, and does not throw", async () => {+ const server = serverAnswering(new TypeError("Failed to fetch"));+ await expect(reportWorldAction("daily_visit")).resolves.toBeUndefined();+ expect(server.warned).toEqual([]);+ expect(server.debugged).toHaveLength(1);+ });+});diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json b/jarvis/ui/web/frontend/src/i18n/locales/society/de.jsonindex 08ec43361f..768d8fcedf 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json@@ -976,6 +976,44 @@"look": "Aussehen","look_shape": "Form","look_pet": "Pet",+ "look_creature": "Pixel-Wesen",+ "creature": {+ "figure": "Figur",+ "roll": "Neu würfeln",+ "number": "Wesen Nr. {0}",+ "palette": "Farbwelt",+ "palettes": {+ "lava": "Lava",+ "ocean": "Ozean",+ "neon": "Neon",+ "moss": "Moos",+ "glacier": "Gletscher",+ "gold": "Gold",+ "candy": "Bonbon",+ "midnight": "Mitternacht"+ },+ "eye_kinds": {+ "dot": "Punkt",+ "tall": "Hoch",+ "wide": "Weit",+ "visor": "Visier"+ },+ "states": "Zustand ansehen",+ "states_hint": "Was das Wesen zeigt, während der Agent arbeitet. Wähle einen Zustand und sieh ihn dir oben an.",+ "state_names": {+ "idle": "Bereit",+ "listening": "Hört zu",+ "thinking": "Denkt nach",+ "working": "Arbeitet",+ "talking": "Spricht",+ "asking": "Fragt nach",+ "success": "Fertig",+ "error": "Fehler",+ "sleeping": "Schläft"+ },+ "everywhere": "Alle Agenten als Pixel-Wesen zeigen",+ "everywhere_hint": "Ein Testschalter für dieses Gerät. Agenten ohne eigenes Wesen bekommen eines aus ihrer Form und Farbe. Schaltest du ihn aus, ist jedes Aussehen wieder da."+ },"pet": "Pet","pet_hint": "Der Agent trägt dieses Pet überall: in Chats, bei der Arbeit und als Begleiter in der Verse.","no_pets": "Noch keine Pets. Lege eines unter „Meine Pets“ an.",@@ -1019,7 +1057,6 @@},"office": {"title": "Dodaios Verse",- "subtitle": "Agenten auf der Etage: {0}","viewport": "Dodaios Verse","loading": "Das Dodaios Verse wird geöffnet…","no_graphics": "3D-Darstellung ist hier nicht verfügbar. Den Status aller Agenten siehst du weiterhin in der Agentenliste.",@@ -1033,10 +1070,21 @@"open_agent": "{0} öffnen","overview": "Übersicht","ledger": "Agentenliste",- "help": "WASD laufen · Shift rennt · Leertaste springt · E benutzen · M Karte · H Hilfe & Einstellungen","sample": "Beispiel-Agenten – das Backend ist noch nicht erreichbar.","overflow": "Nur die ersten {0} Agenten haben einen Schreibtisch; die Liste zeigt alle.","open_space": "Open Space",+ "studio_pool": "Der Pool",+ "studio_sign_team": "Team-Studio",+ "studio_sign_pool": "Noch ohne Team",+ "plot_free": "Platz für dein nächstes Team",+ "plot_hint": "Gründe es am Pult",+ "zone_boulevard": "Boulevard",+ "zone_atrium": "Atrium",+ "zone_plot": "Freier Platz",+ "zone_garden": "Gartenhof",+ "zone_booths": "Fokuskabinen",+ "zone_library": "Bibliothek",+ "zone_cafe": "Café","close": "Schließen","action_chat": "Chat öffnen","action_walk": "Hingehen",@@ -1045,8 +1093,6 @@"action_draft": "Zum neuen Team","action_undraft": "Aus neuem Team entfernen","draft_count": "{0} für ein neues Team ausgewählt · Teamraum öffnen",- "create_body": "Stell einen neuen Agenten ein: Aufgabe, Gehirn und Aussehen. Er erscheint am Spawn-Punkt in der Mitte der Etage und nimmt einen freien Schreibtisch.",- "create_action": "Neuen Agenten erstellen","action_show": "Zeigen","action_open": "Öffnen","manage_action": "Agentenverwaltung öffnen",@@ -1056,12 +1102,12 @@"team_create": "Team erstellen und treffen ({0})","team_created": "Team „{0}“ ist bereit.","team_yours": "Deine Teams",- "team_none": "Noch keine Teams. Stell unten eins zusammen.","team_members": "{0} Mitglieder","team_lead": "Leitung: {0}","team_working": "{0} arbeiten","team_meet": "Am Tisch treffen",- "team_meeting_now": "Im Meeting",+ "team_called": "Gerufen",+ "team_meet_board": "An der Tafel treffen","team_chat": "Team-Chat","team_edit": "Bearbeiten","team_save": "Speichern",@@ -1076,66 +1122,50 @@"team_no_match": "Kein Agent passt.","team_edit_need_more": "Ein Team braucht mindestens zwei Agenten.","team_load_error": "Teams konnten nicht geladen werden: {0}",- "meeting_title": "Meeting: {0}","meeting_status": "{0} von {1} am Tisch · noch {2} Min.",+ "gather_table": "{0} · an den Tisch gerufen",+ "gather_board": "{0} · an die Tafel gerufen",+ "gather_note": "Nur ein Zusammenkommen auf der Karte: Im Team-Chat wird nichts gepostet.",+ "gather_end": "Zurückschicken",+ "meeting_status_board": "{0} von {1} an der Tafel · noch {2} Min.","meeting_busy": "Arbeiten gerade und bleiben am Platz: {0}","meeting_join": "Zum Tisch gehen",- "meeting_end": "Meeting beenden",+ "meeting_join_board": "Zur Tafel gehen","team_live": "Läuft","wardrobe_name": "Dein Name","you": "Du","wardrobe_body": "Kleide dich oder einen Agenten ein: Outfit, Farben, Frisur und Brille.","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 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",- "cp_create_hint": "Hilfe, Steuerung, Einstellungen und neue Agenten",- "cp_manage": "Agenten-Board",- "cp_manage_hint": "Alle Agenten sehen und verwalten",+ "cp_manage": "Empfang",+ "cp_manage_hint": "Agenten, Orte, Steuerung und Einstellungen","cp_team": "Teamraum","cp_team_hint": "Deine Teams und ihre Meetings","cp_wardrobe": "Garderobe",- "cp_wardrobe_hint": "Deine Figur ändern","cp_lead": "Chefbüro",- "cp_lead_hint": "Mit deinem Chef-Agenten sprechen",- "cp_break": "Pausenraum",- "cp_break_hint": "Kaffeepause ausrufen",+ "cp_break": "Kaffeebar","cp_elevator": "Aufzug",- "cp_elevator_hint": "Den Ruf-Knopf neben den Türen drücken","elevator_choose": "Etage wählen",- "elevator_keys": "0–2 wählt die Etage · Esc schließt",+ "elevator_keys": "0–3 wählt die Etage · Esc schließt","floor_name_agents": "Agenten-Etage","floor_name_coding": "Coding-Etage","floor_name_arcade": "Arcade-Etage",+ "floor_name_hall": "Level-Halle","riding_up_to": "Aufwärts · {0}","riding_down_to": "Abwärts · {0}","arcade_floor_title": "Arcade-Etage","arcade_floor_subtitle": "Spielbare Automaten: {0}",- "arcade_floor_hint": "Geh zu einem Automaten und drück E zum Spielen",+ "hall_floor_title": "Level-Halle",+ "hall_floor_subtitle": "Ränge, Belohnungen und dein eigener Look","cp_spawn": "Spawn-Punkt",- "cp_spawn_hint": "Einen neuen Dodaios-Agenten spawnen","cp_launch": "Spawn-Punkt",- "cp_launch_hint": "Einen neuen Coding-Agenten spawnen",- "spawn_title": "Ein neuer Agent für dein Team",- "spawn_body": "Er erscheint genau hier auf der Plattform und geht zu einem freien Schreibtisch.",- "spawn_step_job": "Namen und Aufgabe festlegen",- "spawn_step_brain": "Modell und Aussehen wählen",- "spawn_step_arrive": "Er erscheint auf dieser Plattform",- "spawn_action": "Agenten spawnen",- "spawn_team": "{0} Agenten auf dieser Etage · {1} arbeiten",- "launch_title": "Ein neuer Coding-Agent","launch_body": "Wähle ein Coding-CLI und, wenn du willst, einen ersten Auftrag. Er öffnet sich als Terminal in der Agentic IDE und erscheint hier auf der Plattform.","guide": {"tablist": "Bereiche des Empfangs",- "tab_welcome": "Willkommen","tab_controls": "Steuerung","tab_settings": "Einstellungen","hud_button": "Hilfe & Einstellungen",- "hero_title": "Dein Team erweitern",- "places": "Orte im Dodaios Verse","place_walk": "Hingehen","place_walk_label": "Zu {0} gehen","tip_guide": "öffnet diese Hilfe überall auf der Karte; noch einmal drücken schließt sie.",@@ -1184,17 +1214,17 @@"key_down": "Pfeil runter","key_left": "Pfeil links","key_right": "Pfeil rechts",- "set_section_move": "Bewegen",- "set_section_view": "Anzeige","settings_intro": "Deine Einstellungen für das Dodaios Verse, gespeichert auf diesem Gerät.","set_always_run": "Immer rennen","set_always_run_hint": "Standardmäßig rennen; Shift halten zum Gehen.",- "set_hint_bar": "Steuerungsleiste",- "set_hint_bar_hint": "Die kurze Tastenübersicht unten auf der Karte anzeigen.",- "set_reset": "Auf Standard zurücksetzen"+ "set_reset": "Auf Standard zurücksetzen",+ "tab_agents": "Agenten",+ "tab_places": "Orte",+ "set_hints": "Steuerungshinweise",+ "set_hints_hint": "Die kurze Einführung in die Steuerung wieder auf der Karte zeigen.",+ "set_hints_action": "Wieder zeigen"},"coding_title": "Coding-Etage",- "coding_subtitle": "Coding-Sessions auf der Etage: {0}","coding_empty": "Kein Coding-Agent läuft. Starte einen in der IDE, dann bekommt er hier einen Schreibtisch.","ledger_coding": "Session-Liste","open_ide": "IDE öffnen",@@ -1304,7 +1334,6 @@"fleet_stop": "{0} stoppen","fleet_result": "{0} von {1} erreicht.","fleet_result_missed": "Nicht erreicht: {0}",- "elevator_press": "Knopf anklicken","arcade_prompt": "Asteroid Run spielen","arcade_title": "Asteroid Run","arcade_score": "Punkte",@@ -1332,9 +1361,7 @@"room_prizes": "Preisshop","room_snack": "Snackbar","cp_studio": "Umkleide",- "cp_studio_hint": "Rüste dich und dein Pet mit deinen Belohnungen aus","cp_levels": "Level-Tafel",- "cp_levels_hint": "Dein Level, deine Belohnungen und wie du aufsteigst","room_levels": "Level-Halle","dog_treat": "Knochen geben","dog_take_bone": "Leckerli nehmen",@@ -1359,16 +1386,28 @@"activity_meeting": "Im Teamraum","activity_board": "Am Board","activity_wander": "Schlendert",- "activity_visit": "Plaudert",+ "activity_visit": "Schaut vorbei","activity_called": "Kommt rüber",+ "activity_huddle": "Am Teamboard",+ "activity_mate": "Im Studio",+ "activity_studio": "Im Studio",+ "activity_handoff": "Bringt eine Nachricht",+ "board_speaking": "Spricht",+ "board_empty": "Im Chat dieses Teams wurde noch nichts gesagt.",+ "board_pool_note": "Diese Agenten gehören noch zu keinem Team. Ein Team bekommt einen eigenen Chat, und der erscheint hier.",+ "board_loading": "Team-Chat wird gelesen …",+ "board_unavailable": "Der Team-Chat lässt sich gerade nicht lesen.",+ "board_more": "+{0} weitere",+ "handoff_to": "An {0}: {1}","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": "Mit {0} am Tisch treffen",+ "team_gather_board_label": "Mit {0} an der Tafel treffen","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.",+ "manage_empty": "Noch keine Agenten. Erstelle den ersten am Spawn-Punkt.","wardrobe_saved": "Nur in diesem Browser gespeichert.","count_paused": "{0} pausiert","hair_short": "Kurz",@@ -1388,15 +1427,7 @@"minimap_zoom_out": "Herauszoomen","minimap_open_map": "Karte (M)","minimap_open_map_label": "Große Karte öffnen (M)",- "compass_label": "Kompass: die Richtung, in die die Kamera schaut","compass_n": "N",- "compass_ne": "NO",- "compass_e": "O",- "compass_se": "SO",- "compass_s": "S",- "compass_sw": "SW",- "compass_w": "W",- "compass_nw": "NW","map_title": "Karte des Dodaios Verse","map_hint": "Klicke irgendwohin, um dorthin zu laufen. Esc oder M schließt die Karte.","map_close": "Karte schließen",@@ -1445,7 +1476,7 @@"wardrobe_save_agent": "Look für {0} speichern","wardrobe_saved_agent": "{0} trägt jetzt den neuen Look.","wardrobe_save_error": "Der Look konnte nicht gespeichert werden. Deine Änderungen bleiben erhalten – versuch es noch einmal.",- "wardrobe_sample_hint": "Beispiel-Agenten lassen sich nicht speichern. Lege am Empfang einen echten Agenten an.",+ "wardrobe_sample_hint": "Beispiel-Agenten lassen sich nicht speichern. Lege am Spawn-Punkt einen echten Agenten an.","outfit_tee": "T-Shirt","outfit_hoodie": "Hoodie","outfit_suit": "Anzug",@@ -1481,6 +1512,39 @@"errand_flying": "Bringt {0} eine Aufgabe","errand_task": "Hier ist eine neue Aufgabe für dich.","errand_ack": "Verstanden, bin dran!",+ "hud_tools": "Kartenwerkzeuge",+ "hud_places": "Orte",+ "places_teams": "Teams",+ "hints_label": "Steuerung",+ "hints_dismiss": "Verstanden",+ "hint_walk": "Gehen",+ "hint_rotate": "Umsehen",+ "hint_interact": "Benutzen, was in der Nähe ist",+ "hint_guide": "Alle Tasten",+ "use_spawn": "Agenten erstellen",+ "use_launch": "Coding-Agenten starten",+ "use_manage": "Verzeichnis öffnen",+ "use_team": "Teams verwalten",+ "use_wardrobe": "Aussehen ändern",+ "use_lead": "Mit deinem Lead sprechen",+ "use_break": "Kaffeepause ausrufen",+ "use_break_end": "Kaffeepause beenden",+ "use_elevator": "Aufzug rufen",+ "use_mission": "Mission Control öffnen",+ "use_studio": "Ausrüsten",+ "use_levels": "Deine Level ansehen",+ "use_board": "Team öffnen",+ "use_found": "Hier ein Team gründen",+ "cp_board": "Team-Tafel",+ "cp_found": "Freier Platz",+ "cp_board_hint": "Mitglieder, Chat und Meetings",+ "team_pool": "Ohne Team",+ "team_pool_body": "Die Agenten hier gehören noch zu keinem Team. Stell eines zusammen, dann bekommen sie einen gemeinsamen Chat.",+ "team_gone": "Dieses Team gibt es nicht mehr.",+ "team_this": "Dieses Team",+ "team_all": "Alle Teams ({0})",+ "team_members_label": "Mitglieder",+ "break_ended": "Alle sind zurück in ihrem Tag.","lobby_strapline": "AGENTEN-ZENTRALE","lobby_board_hint": "Tippe, um dein Team zu verwalten","lobby_new_agent": "Neuer Agent",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json b/jarvis/ui/web/frontend/src/i18n/locales/society/en.jsonindex 7b7b6208d9..d7695f76c6 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json@@ -976,6 +976,44 @@"look": "Look","look_shape": "Shape","look_pet": "Pet",+ "look_creature": "Pixel creature",+ "creature": {+ "figure": "Figure",+ "roll": "Roll again",+ "number": "Creature no. {0}",+ "palette": "Colour world",+ "palettes": {+ "lava": "Lava",+ "ocean": "Ocean",+ "neon": "Neon",+ "moss": "Moss",+ "glacier": "Glacier",+ "gold": "Gold",+ "candy": "Candy",+ "midnight": "Midnight"+ },+ "eye_kinds": {+ "dot": "Dot",+ "tall": "Tall",+ "wide": "Wide apart",+ "visor": "Visor"+ },+ "states": "Preview a state",+ "states_hint": "What the creature acts out while the agent works. Pick one to watch it above.",+ "state_names": {+ "idle": "Ready",+ "listening": "Listening",+ "thinking": "Thinking",+ "working": "Working",+ "talking": "Talking",+ "asking": "Asking",+ "success": "Done",+ "error": "Error",+ "sleeping": "Asleep"+ },+ "everywhere": "Show every agent as a pixel creature",+ "everywhere_hint": "A trial switch for this device. Agents without their own creature get one grown from their shape and colour. Switch it off and every look is back."+ },"pet": "Pet","pet_hint": "The agent wears this pet everywhere: in chats, while it works and as its companion in the Verse.","no_pets": "No pets yet. Add one under My Pets.",@@ -1019,7 +1057,6 @@},"office": {"title": "Dodaios Verse",- "subtitle": "Agents on the floor: {0}","viewport": "Dodaios Verse","loading": "Opening the Dodaios Verse…","no_graphics": "3D rendering is unavailable here. Every agent's status stays available in the agents list.",@@ -1033,10 +1070,21 @@"open_agent": "Open {0}","overview": "Overview","ledger": "Agents list",- "help": "WASD walk · Shift runs · Space jumps · E interacts · M map · H help & settings","sample": "Sample agents — the backend is not reachable yet.","overflow": "Only the first {0} agents have a desk; the list shows everyone.","open_space": "Open space",+ "studio_pool": "The Pool",+ "studio_sign_team": "Team studio",+ "studio_sign_pool": "No team yet",+ "plot_free": "Room for your next team",+ "plot_hint": "Start one at the stand",+ "zone_boulevard": "Boulevard",+ "zone_atrium": "Atrium",+ "zone_plot": "Free plot",+ "zone_garden": "Garden court",+ "zone_booths": "Focus booths",+ "zone_library": "Library",+ "zone_cafe": "Café","close": "Close","action_chat": "Open chat","action_walk": "Walk there",@@ -1045,8 +1093,6 @@"action_draft": "Add to new team","action_undraft": "Remove from new team","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 appears at the spawn point in the middle of the floor and takes a free desk.",- "create_action": "Create a new agent","action_show": "Show","action_open": "Open","manage_action": "Open agent management",@@ -1056,12 +1102,12 @@"team_create": "Create team and meet ({0})","team_created": "Team “{0}” is ready.","team_yours": "Your teams",- "team_none": "No teams yet. Put one together below.","team_members": "{0} members","team_lead": "Lead: {0}","team_working": "{0} working","team_meet": "Meet at the table",- "team_meeting_now": "In the meeting",+ "team_called": "Called",+ "team_meet_board": "Meet at the board","team_chat": "Team chat","team_edit": "Edit","team_save": "Save",@@ -1076,66 +1122,50 @@"team_no_match": "No agent matches.","team_edit_need_more": "A team needs at least two agents.","team_load_error": "Teams could not be loaded: {0}",- "meeting_title": "Meeting: {0}","meeting_status": "{0} of {1} at the table · {2} min left",+ "gather_table": "{0} · called to the table",+ "gather_board": "{0} · called to the board",+ "gather_note": "A gathering on the map only: nothing is posted to the team's chat.",+ "gather_end": "Send them back",+ "meeting_status_board": "{0} of {1} at the board · {2} min left","meeting_busy": "Working, so they stay at their desk: {0}","meeting_join": "Go to the table",- "meeting_end": "End meeting",+ "meeting_join_board": "Go to the board","team_live": "Live","wardrobe_name": "Your name","you": "You","wardrobe_body": "Dress yourself or an agent: outfit, colours, hair and glasses.","wardrobe_shuffle": "Shuffle colours","lead_empty": "No lead agent yet.",- "lead_body": "Your lead coordinates the other agents. Talk to it here.",- "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",- "cp_create_hint": "Help, controls, settings and new agents",- "cp_manage": "Agent board",- "cp_manage_hint": "See and manage every agent",+ "cp_manage": "Reception",+ "cp_manage_hint": "Agents, places, controls and settings","cp_team": "Team room","cp_team_hint": "Your teams and their meetings","cp_wardrobe": "Wardrobe",- "cp_wardrobe_hint": "Change your character","cp_lead": "Lead office",- "cp_lead_hint": "Talk to your lead agent",- "cp_break": "Break room",- "cp_break_hint": "Call a coffee break",+ "cp_break": "Coffee bar","cp_elevator": "Elevator",- "cp_elevator_hint": "Press the call button beside the doors","elevator_choose": "Choose a floor",- "elevator_keys": "0–2 picks a floor · Esc closes",+ "elevator_keys": "0–3 picks a floor · Esc closes","floor_name_agents": "Agents floor","floor_name_coding": "Coding floor","floor_name_arcade": "Arcade floor",+ "floor_name_hall": "Level Hall","riding_up_to": "Going up · {0}","riding_down_to": "Going down · {0}","arcade_floor_title": "Arcade floor","arcade_floor_subtitle": "Playable cabinets: {0}",- "arcade_floor_hint": "Walk up to a cabinet and press E to play",+ "hall_floor_title": "Level Hall",+ "hall_floor_subtitle": "Ranks, rewards and your own look","cp_spawn": "Spawn point",- "cp_spawn_hint": "Spawn a new Dodaios agent","cp_launch": "Spawn point",- "cp_launch_hint": "Spawn a new coding agent",- "spawn_title": "A new agent for your team",- "spawn_body": "It appears right here on the pad and walks to a free desk.",- "spawn_step_job": "Name it and describe its job",- "spawn_step_brain": "Pick its model and its look",- "spawn_step_arrive": "It appears on this pad",- "spawn_action": "Spawn an agent",- "spawn_team": "{0} agents on this floor · {1} working",- "launch_title": "A new coding agent","launch_body": "Pick a coding CLI and, if you like, a first task. It opens as a terminal in the Agentic IDE and appears here on the pad.","guide": {"tablist": "Reception sections",- "tab_welcome": "Welcome","tab_controls": "Controls","tab_settings": "Settings","hud_button": "Help & settings",- "hero_title": "Grow your team",- "places": "Places in the Dodaios Verse","place_walk": "Walk there","place_walk_label": "Walk to {0}","tip_guide": "opens this help from anywhere on the map; press it again to close.",@@ -1184,17 +1214,17 @@"key_down": "Arrow down","key_left": "Arrow left","key_right": "Arrow right",- "set_section_move": "Moving",- "set_section_view": "Display","settings_intro": "Your settings for the Dodaios Verse, saved on this device.","set_always_run": "Always run","set_always_run_hint": "Run by default; hold Shift to walk.",- "set_hint_bar": "Controls bar",- "set_hint_bar_hint": "Show the short controls reminder at the bottom of the map.",- "set_reset": "Reset to defaults"+ "set_reset": "Reset to defaults",+ "tab_agents": "Agents",+ "tab_places": "Places",+ "set_hints": "Control hints",+ "set_hints_hint": "Show the short introduction to the controls on the map again.",+ "set_hints_action": "Show again"},"coding_title": "Coding floor",- "coding_subtitle": "Coding sessions on the floor: {0}","coding_empty": "No coding agent is running. Start one in the IDE and it takes a desk here.","ledger_coding": "Sessions list","open_ide": "Open the IDE",@@ -1304,7 +1334,6 @@"fleet_stop": "Stop {0}","fleet_result": "Reached {0} of {1}.","fleet_result_missed": "Not reached: {0}",- "elevator_press": "Click the button","arcade_prompt": "Play Asteroid Run","arcade_title": "Asteroid Run","arcade_score": "Score",@@ -1332,9 +1361,7 @@"room_prizes": "Prize shop","room_snack": "Snack bar","cp_studio": "Studio",- "cp_studio_hint": "Gear up yourself and your pet with your rewards","cp_levels": "Level board",- "cp_levels_hint": "Your level, your rewards and how to level up","room_levels": "Level Hall","dog_treat": "Give the bone","dog_take_bone": "Take a dog treat",@@ -1359,16 +1386,28 @@"activity_meeting": "In the team room","activity_board": "At the board","activity_wander": "Strolling",- "activity_visit": "Chatting",+ "activity_visit": "Looking in","activity_called": "Coming over",+ "activity_huddle": "At the team board",+ "activity_mate": "In the studio",+ "activity_studio": "In the studio",+ "activity_handoff": "Bringing a message",+ "board_speaking": "Speaking",+ "board_empty": "Nothing has been said in this team's chat yet.",+ "board_pool_note": "These agents are not in a team yet. A team gets a chat of its own, and it shows up here.",+ "board_loading": "Reading the team chat…",+ "board_unavailable": "The team chat cannot be read right now.",+ "board_more": "+{0} more",+ "handoff_to": "To {0}: {1}","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": "Meet with {0} at the table",+ "team_gather_board_label": "Meet with {0} at the board","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.",+ "manage_empty": "No agents yet. Create the first one at the spawn point.","wardrobe_saved": "Saved in this browser only.","count_paused": "{0} paused","hair_short": "Short",@@ -1388,15 +1427,7 @@"minimap_zoom_out": "Zoom out","minimap_open_map": "Map (M)","minimap_open_map_label": "Open the full map (M)",- "compass_label": "Compass: the direction the camera faces","compass_n": "N",- "compass_ne": "NE",- "compass_e": "E",- "compass_se": "SE",- "compass_s": "S",- "compass_sw": "SW",- "compass_w": "W",- "compass_nw": "NW","map_title": "Dodaios Verse map","map_hint": "Click anywhere to walk there. Esc or M closes the map.","map_close": "Close map",@@ -1445,7 +1476,7 @@"wardrobe_save_agent": "Save look for {0}","wardrobe_saved_agent": "{0} is wearing the new look.","wardrobe_save_error": "Could not save the look. Your changes are kept; try again.",- "wardrobe_sample_hint": "Sample agents cannot be saved. Create a real agent at reception.",+ "wardrobe_sample_hint": "Sample agents cannot be saved. Create a real agent at the spawn point.","outfit_tee": "T-shirt","outfit_hoodie": "Hoodie","outfit_suit": "Suit",@@ -1481,6 +1512,39 @@"errand_flying": "Taking {0} a task","errand_task": "Here is a new task for you.","errand_ack": "Got it, on it!",+ "hud_tools": "Map tools",+ "hud_places": "Places",+ "places_teams": "Teams",+ "hints_label": "Controls",+ "hints_dismiss": "Got it",+ "hint_walk": "Walk",+ "hint_rotate": "Look around",+ "hint_interact": "Use what is near",+ "hint_guide": "All controls",+ "use_spawn": "Create an agent",+ "use_launch": "Start a coding agent",+ "use_manage": "Open the directory",+ "use_team": "Manage teams",+ "use_wardrobe": "Change your look",+ "use_lead": "Talk to your lead",+ "use_break": "Call a coffee break",+ "use_break_end": "End the coffee break",+ "use_elevator": "Call the elevator",+ "use_mission": "Open Mission Control",+ "use_studio": "Gear up",+ "use_levels": "View your levels",+ "use_board": "Open the team",+ "use_found": "Start a team here",+ "cp_board": "Team board",+ "cp_found": "Free plot",+ "cp_board_hint": "Its members, its chat and its meetings",+ "team_pool": "Without a team",+ "team_pool_body": "The agents sitting here are not in a team yet. Put one together to give them a shared chat.",+ "team_gone": "This team no longer exists.",+ "team_this": "This team",+ "team_all": "All teams ({0})",+ "team_members_label": "Members",+ "break_ended": "Everyone is back to their day.","lobby_strapline": "AGENT HEADQUARTERS","lobby_board_hint": "Tap to manage your team","lobby_new_agent": "New agent",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json b/jarvis/ui/web/frontend/src/i18n/locales/society/es.jsonindex 5a43506f34..7a1e6ce39e 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json@@ -976,6 +976,44 @@"look": "Aspecto","look_shape": "Forma","look_pet": "Mascota",+ "look_creature": "Criatura de píxeles",+ "creature": {+ "figure": "Figura",+ "roll": "Tirar de nuevo",+ "number": "Criatura n.º {0}",+ "palette": "Mundo de color",+ "palettes": {+ "lava": "Lava",+ "ocean": "Océano",+ "neon": "Neón",+ "moss": "Musgo",+ "glacier": "Glaciar",+ "gold": "Oro",+ "candy": "Caramelo",+ "midnight": "Medianoche"+ },+ "eye_kinds": {+ "dot": "Punto",+ "tall": "Alto",+ "wide": "Separados",+ "visor": "Visor"+ },+ "states": "Ver un estado",+ "states_hint": "Lo que la criatura muestra mientras el agente trabaja. Elige uno para verlo arriba.",+ "state_names": {+ "idle": "Listo",+ "listening": "Escuchando",+ "thinking": "Pensando",+ "working": "Trabajando",+ "talking": "Hablando",+ "asking": "Preguntando",+ "success": "Hecho",+ "error": "Error",+ "sleeping": "Dormido"+ },+ "everywhere": "Mostrar todos los agentes como criaturas de píxeles",+ "everywhere_hint": "Un interruptor de prueba para este dispositivo. Los agentes sin criatura propia reciben una creada a partir de su forma y su color. Al apagarlo, todos los aspectos vuelven."+ },"pet": "Mascota","pet_hint": "El agente lleva esta mascota en todas partes: en los chats, mientras trabaja y como compañero en el Verse.","no_pets": "Aún no hay mascotas. Añade una en Mis mascotas.",@@ -1019,7 +1057,6 @@},"office": {"title": "Dodaios Verse",- "subtitle": "Agentes en la planta: {0}","viewport": "Dodaios Verse","loading": "Abriendo el Dodaios Verse…","no_graphics": "El renderizado 3D no está disponible aquí. El estado de cada agente sigue en la lista de agentes.",@@ -1033,10 +1070,21 @@"open_agent": "Abrir {0}","overview": "Vista general","ledger": "Lista de agentes",- "help": "WASD caminar · Shift corre · Espacio salta · E usar · M mapa · H ayuda y ajustes","sample": "Agentes de ejemplo: el backend aún no está disponible.","overflow": "Solo los primeros {0} agentes tienen escritorio; la lista muestra a todos.","open_space": "Espacio abierto",+ "studio_pool": "El Pool",+ "studio_sign_team": "Estudio de equipo",+ "studio_sign_pool": "Aún sin equipo",+ "plot_free": "Sitio para tu próximo equipo",+ "plot_hint": "Créalo en el atril",+ "zone_boulevard": "Bulevar",+ "zone_atrium": "Atrio",+ "zone_plot": "Parcela libre",+ "zone_garden": "Patio ajardinado",+ "zone_booths": "Cabinas de concentración",+ "zone_library": "Biblioteca",+ "zone_cafe": "Café","close": "Cerrar","action_chat": "Abrir chat","action_walk": "Ir allí",@@ -1045,8 +1093,6 @@"action_draft": "Añadir al nuevo equipo","action_undraft": "Quitar del nuevo equipo","draft_count": "{0} elegidos para un equipo nuevo · abrir la sala de equipos",- "create_body": "Contrata un agente nuevo: tarea, cerebro y aspecto. Aparece en el punto de aparición, en el centro de la planta, y ocupa un escritorio libre.",- "create_action": "Crear un agente nuevo","action_show": "Mostrar","action_open": "Abrir","manage_action": "Abrir gestión de agentes",@@ -1056,12 +1102,12 @@"team_create": "Crear equipo y reunirse ({0})","team_created": "El equipo «{0}» está listo.","team_yours": "Tus equipos",- "team_none": "Aún no hay equipos. Forma uno abajo.","team_members": "{0} miembros","team_lead": "Líder: {0}","team_working": "{0} trabajando","team_meet": "Reunirse en la mesa",- "team_meeting_now": "En la reunión",+ "team_called": "Convocado",+ "team_meet_board": "Reunirse en el panel","team_chat": "Chat del equipo","team_edit": "Editar","team_save": "Guardar",@@ -1076,66 +1122,50 @@"team_no_match": "Ningún agente coincide.","team_edit_need_more": "Un equipo necesita al menos dos agentes.","team_load_error": "No se pudieron cargar los equipos: {0}",- "meeting_title": "Reunión: {0}","meeting_status": "{0} de {1} en la mesa · quedan {2} min",+ "gather_table": "{0} · convocado a la mesa",+ "gather_board": "{0} · convocado al panel",+ "gather_note": "Solo una reunión en el mapa: no se publica nada en el chat del equipo.",+ "gather_end": "Enviarlos de vuelta",+ "meeting_status_board": "{0} de {1} en el panel · quedan {2} min","meeting_busy": "Están trabajando y se quedan en su puesto: {0}","meeting_join": "Ir a la mesa",- "meeting_end": "Terminar la reunión",+ "meeting_join_board": "Ir al panel","team_live": "En curso","wardrobe_name": "Tu nombre","you": "Tú","wardrobe_body": "Viste a tu personaje o a un agente: atuendo, colores, peinado y gafas.","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": "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",- "cp_create_hint": "Ayuda, controles, ajustes y agentes nuevos",- "cp_manage": "Tablero de agentes",- "cp_manage_hint": "Ver y gestionar todos los agentes",+ "cp_manage": "Recepción",+ "cp_manage_hint": "Agentes, lugares, controles y ajustes","cp_team": "Sala de equipos","cp_team_hint": "Tus equipos y sus reuniones","cp_wardrobe": "Vestuario",- "cp_wardrobe_hint": "Cambiar tu personaje","cp_lead": "Despacho del líder",- "cp_lead_hint": "Hablar con tu agente líder",- "cp_break": "Sala de descanso",- "cp_break_hint": "Hacer una pausa de café",+ "cp_break": "Barra de café","cp_elevator": "Ascensor",- "cp_elevator_hint": "Pulsa el botón de llamada junto a las puertas","elevator_choose": "Elige una planta",- "elevator_keys": "0–2 elige planta · Esc cierra",+ "elevator_keys": "0–3 elige planta · Esc cierra","floor_name_agents": "Planta de agentes","floor_name_coding": "Planta de código","floor_name_arcade": "Planta arcade",+ "floor_name_hall": "Sala de niveles","riding_up_to": "Subiendo · {0}","riding_down_to": "Bajando · {0}","arcade_floor_title": "Planta arcade","arcade_floor_subtitle": "Máquinas jugables: {0}",- "arcade_floor_hint": "Acércate a una máquina y pulsa E para jugar",+ "hall_floor_title": "Sala de niveles",+ "hall_floor_subtitle": "Rangos, recompensas y tu propio aspecto","cp_spawn": "Punto de aparición",- "cp_spawn_hint": "Crea un nuevo agente de Dodaios","cp_launch": "Punto de aparición",- "cp_launch_hint": "Crea un nuevo agente de código",- "spawn_title": "Un agente nuevo para tu equipo",- "spawn_body": "Aparece justo aquí, en la plataforma, y va a un escritorio libre.",- "spawn_step_job": "Ponle nombre y describe su tarea",- "spawn_step_brain": "Elige su modelo y su aspecto",- "spawn_step_arrive": "Aparece en esta plataforma",- "spawn_action": "Crear un agente",- "spawn_team": "{0} agentes en esta planta · {1} trabajando",- "launch_title": "Un agente de código nuevo","launch_body": "Elige una CLI de código y, si quieres, una primera tarea. Se abre como terminal en el Agentic IDE y aparece aquí, en la plataforma.","guide": {"tablist": "Secciones de la recepción",- "tab_welcome": "Bienvenida","tab_controls": "Controles","tab_settings": "Ajustes","hud_button": "Ayuda y ajustes",- "hero_title": "Amplía tu equipo",- "places": "Lugares del Dodaios Verse","place_walk": "Ir","place_walk_label": "Ir a {0}","tip_guide": "abre esta ayuda desde cualquier punto del mapa; púlsala otra vez para cerrarla.",@@ -1184,17 +1214,17 @@"key_down": "Flecha abajo","key_left": "Flecha izquierda","key_right": "Flecha derecha",- "set_section_move": "Moverse",- "set_section_view": "Pantalla","settings_intro": "Tus ajustes del Dodaios Verse, guardados en este dispositivo.","set_always_run": "Correr siempre","set_always_run_hint": "Corre por defecto; mantén Shift para caminar.",- "set_hint_bar": "Barra de controles",- "set_hint_bar_hint": "Mostrar el breve recordatorio de controles abajo del mapa.",- "set_reset": "Restablecer valores"+ "set_reset": "Restablecer valores",+ "tab_agents": "Agentes",+ "tab_places": "Lugares",+ "set_hints": "Pistas de control",+ "set_hints_hint": "Volver a mostrar en el mapa la breve introducción a los controles.",+ "set_hints_action": "Mostrar de nuevo"},"coding_title": "Planta de código",- "coding_subtitle": "Sesiones de código en la planta: {0}","coding_empty": "No hay ningún agente de código en marcha. Inicia uno en el IDE y ocupará un escritorio aquí.","ledger_coding": "Lista de sesiones","open_ide": "Abrir el IDE",@@ -1304,7 +1334,6 @@"fleet_stop": "Detener {0}","fleet_result": "Alcanzados {0} de {1}.","fleet_result_missed": "No alcanzados: {0}",- "elevator_press": "Haz clic en el botón","arcade_prompt": "Jugar a Asteroid Run","arcade_title": "Asteroid Run","arcade_score": "Puntos",@@ -1332,9 +1361,7 @@"room_prizes": "Tienda de premios","room_snack": "Bar de aperitivos","cp_studio": "Probador",- "cp_studio_hint": "Equípate a ti y a tu mascota con tus recompensas","cp_levels": "Panel de niveles",- "cp_levels_hint": "Tu nivel, tus recompensas y cómo subir","room_levels": "Sala de niveles","dog_treat": "Darle el hueso","dog_take_bone": "Coger una golosina",@@ -1359,16 +1386,28 @@"activity_meeting": "En la sala de equipos","activity_board": "En el tablero","activity_wander": "Paseando",- "activity_visit": "Charlando",+ "activity_visit": "De visita","activity_called": "Viene hacia ti",+ "activity_huddle": "En el tablero del equipo",+ "activity_mate": "En el estudio",+ "activity_studio": "En el estudio",+ "activity_handoff": "Lleva un mensaje",+ "board_speaking": "Hablando",+ "board_empty": "Todavía no se ha dicho nada en el chat de este equipo.",+ "board_pool_note": "Estos agentes aún no están en ningún equipo. Un equipo tiene su propio chat, y aparece aquí.",+ "board_loading": "Leyendo el chat del equipo…",+ "board_unavailable": "El chat del equipo no se puede leer ahora mismo.",+ "board_more": "+{0} más",+ "handoff_to": "Para {0}: {1}","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": "Reunirse con {0} en la mesa",+ "team_gather_board_label": "Reunirse con {0} en el panel","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.",+ "manage_empty": "Aún no hay agentes. Crea el primero en el punto de aparición.","wardrobe_saved": "Guardado solo en este navegador.","count_paused": "{0} en pausa","hair_short": "Corto",@@ -1388,15 +1427,7 @@"minimap_zoom_out": "Alejar","minimap_open_map": "Mapa (M)","minimap_open_map_label": "Abrir el mapa completo (M)",- "compass_label": "Brújula: la dirección a la que mira la cámara","compass_n": "N",- "compass_ne": "NE",- "compass_e": "E",- "compass_se": "SE",- "compass_s": "S",- "compass_sw": "SO",- "compass_w": "O",- "compass_nw": "NO","map_title": "Mapa del Dodaios Verse","map_hint": "Haz clic en cualquier sitio para ir allí. Esc o M cierra el mapa.","map_close": "Cerrar mapa",@@ -1445,7 +1476,7 @@"wardrobe_save_agent": "Guardar look para {0}","wardrobe_saved_agent": "{0} ya lleva el nuevo look.","wardrobe_save_error": "No se pudo guardar el look. Tus cambios se conservan; inténtalo de nuevo.",- "wardrobe_sample_hint": "Los agentes de ejemplo no se pueden guardar. Crea un agente real en recepción.",+ "wardrobe_sample_hint": "Los agentes de ejemplo no se pueden guardar. Crea un agente real en el punto de aparición.","outfit_tee": "Camiseta","outfit_hoodie": "Sudadera","outfit_suit": "Traje",@@ -1481,6 +1512,39 @@"errand_flying": "Lleva una tarea a {0}","errand_task": "Aquí tienes una tarea nueva.","errand_ack": "¡Entendido, voy!",+ "hud_tools": "Herramientas del mapa",+ "hud_places": "Lugares",+ "places_teams": "Equipos",+ "hints_label": "Controles",+ "hints_dismiss": "Entendido",+ "hint_walk": "Caminar",+ "hint_rotate": "Mirar alrededor",+ "hint_interact": "Usar lo que tienes cerca",+ "hint_guide": "Todos los controles",+ "use_spawn": "Crear un agente",+ "use_launch": "Iniciar un agente de código",+ "use_manage": "Abrir el directorio",+ "use_team": "Gestionar equipos",+ "use_wardrobe": "Cambiar tu aspecto",+ "use_lead": "Hablar con tu líder",+ "use_break": "Convocar una pausa para el café",+ "use_break_end": "Terminar la pausa para el café",+ "use_elevator": "Llamar al ascensor",+ "use_mission": "Abrir Mission Control",+ "use_studio": "Equiparte",+ "use_levels": "Ver tus niveles",+ "use_board": "Abrir el equipo",+ "use_found": "Crear un equipo aquí",+ "cp_board": "Panel del equipo",+ "cp_found": "Parcela libre",+ "cp_board_hint": "Sus miembros, su chat y sus reuniones",+ "team_pool": "Sin equipo",+ "team_pool_body": "Los agentes sentados aquí aún no tienen equipo. Forma uno para darles un chat compartido.",+ "team_gone": "Este equipo ya no existe.",+ "team_this": "Este equipo",+ "team_all": "Todos los equipos ({0})",+ "team_members_label": "Miembros",+ "break_ended": "Todos han vuelto a lo suyo.","lobby_strapline": "SEDE DE AGENTES","lobby_board_hint": "Toca para gestionar tu equipo","lobby_new_agent": "Nuevo agente",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/pt.json b/jarvis/ui/web/frontend/src/i18n/locales/society/pt.jsonindex a9869303ed..3ecab70ed5 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/pt.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/pt.json@@ -976,6 +976,44 @@"look": "Aspeto","look_shape": "Forma","look_pet": "Animal",+ "look_creature": "Criatura de píxeis",+ "creature": {+ "figure": "Figura",+ "roll": "Sortear de novo",+ "number": "Criatura n.º {0}",+ "palette": "Mundo de cores",+ "palettes": {+ "lava": "Lava",+ "ocean": "Oceano",+ "neon": "Néon",+ "moss": "Musgo",+ "glacier": "Glaciar",+ "gold": "Ouro",+ "candy": "Rebuçado",+ "midnight": "Meia-noite"+ },+ "eye_kinds": {+ "dot": "Ponto",+ "tall": "Altos",+ "wide": "Afastados",+ "visor": "Viseira"+ },+ "states": "Pré-visualizar um estado",+ "states_hint": "O que a criatura representa enquanto o agente trabalha. Escolhe um para o veres acima.",+ "state_names": {+ "idle": "Pronto",+ "listening": "A ouvir",+ "thinking": "A pensar",+ "working": "A trabalhar",+ "talking": "A falar",+ "asking": "A perguntar",+ "success": "Concluído",+ "error": "Erro",+ "sleeping": "A dormir"+ },+ "everywhere": "Mostrar todos os agentes como criaturas de píxeis",+ "everywhere_hint": "Um interruptor experimental para este dispositivo. Os agentes sem criatura própria recebem uma criada a partir da sua forma e cor. Desliga-o e todos os aspetos voltam."+ },"pet": "Animal","pet_hint": "O agente leva este animal para todo o lado: nos chats, enquanto trabalha e como companheiro no Verse.","no_pets": "Ainda não há animais. Adiciona um em Os meus animais.",@@ -1019,7 +1057,6 @@},"office": {"title": "Dodaios Verse",- "subtitle": "Agentes no piso: {0}","viewport": "Dodaios Verse","loading": "A abrir o Dodaios Verse…","no_graphics": "A renderização 3D não está disponível aqui. O estado de cada agente continua disponível na lista de agentes.",@@ -1033,10 +1070,21 @@"open_agent": "Abrir {0}","overview": "Visão geral","ledger": "Lista de agentes",- "help": "WASD andar · Shift corre · Espaço salta · E interage · M mapa · H ajuda e definições","sample": "Agentes de exemplo — o backend ainda não está acessível.","overflow": "Só os primeiros {0} agentes têm secretária; a lista mostra todos.","open_space": "Open space",+ "studio_pool": "O Pool",+ "studio_sign_team": "Estúdio da equipa",+ "studio_sign_pool": "Ainda sem equipa",+ "plot_free": "Espaço para a tua próxima equipa",+ "plot_hint": "Começa uma no balcão",+ "zone_boulevard": "Avenida",+ "zone_atrium": "Átrio",+ "zone_plot": "Lote livre",+ "zone_garden": "Pátio ajardinado",+ "zone_booths": "Cabines de concentração",+ "zone_library": "Biblioteca",+ "zone_cafe": "Café","close": "Fechar","action_chat": "Abrir chat","action_walk": "Ir até lá",@@ -1045,8 +1093,6 @@"action_draft": "Adicionar à nova equipa","action_undraft": "Remover da nova equipa","draft_count": "{0} escolhidos para uma nova equipa · abre a sala da equipa",- "create_body": "Contrata um novo agente: dá-lhe um trabalho, um cérebro e um aspeto. Aparece no ponto de criação no meio do piso e ocupa uma secretária livre.",- "create_action": "Criar um novo agente","action_show": "Mostrar","action_open": "Abrir","manage_action": "Abrir a gestão de agentes",@@ -1056,12 +1102,12 @@"team_create": "Criar equipa e reunir ({0})","team_created": "A equipa “{0}” está pronta.","team_yours": "As tuas equipas",- "team_none": "Ainda não há equipas. Monta uma abaixo.","team_members": "{0} membros","team_lead": "Líder: {0}","team_working": "{0} a trabalhar","team_meet": "Reunir à mesa",- "team_meeting_now": "Em reunião",+ "team_called": "Chamada",+ "team_meet_board": "Reunir no quadro","team_chat": "Chat da equipa","team_edit": "Editar","team_save": "Guardar",@@ -1076,66 +1122,50 @@"team_no_match": "Nenhum agente corresponde.","team_edit_need_more": "Uma equipa precisa de pelo menos dois agentes.","team_load_error": "Não foi possível carregar as equipas: {0}",- "meeting_title": "Reunião: {0}","meeting_status": "{0} de {1} à mesa · faltam {2} min",+ "gather_table": "{0} · chamada à mesa",+ "gather_board": "{0} · chamada ao quadro",+ "gather_note": "Um encontro apenas no mapa: nada é publicado no chat da equipa.",+ "gather_end": "Mandá-los de volta",+ "meeting_status_board": "{0} de {1} no quadro · faltam {2} min","meeting_busy": "A trabalhar, por isso ficam na secretária: {0}","meeting_join": "Ir para a mesa",- "meeting_end": "Terminar reunião",+ "meeting_join_board": "Ir para o quadro","team_live": "Em direto","wardrobe_name": "O teu nome","you": "Tu","wardrobe_body": "Veste-te a ti ou a um agente: roupa, cores, cabelo e óculos.","wardrobe_shuffle": "Baralhar cores","lead_empty": "Ainda não há agente líder.",- "lead_body": "O teu líder coordena os outros agentes. Fala com ele aqui.",- "break_body": "Livres neste momento: {0}. Chama-os para uma pausa para café — é só para a vista, o trabalho deles não é afetado.",- "break_call": "Chamar para pausa para café",- "break_release": "Todos de volta ao trabalho","cp_create": "Receção",- "cp_create_hint": "Ajuda, controlos, definições e novos agentes",- "cp_manage": "Quadro de agentes",- "cp_manage_hint": "Vê e gere todos os agentes",+ "cp_manage": "Receção",+ "cp_manage_hint": "Agentes, locais, controlos e definições","cp_team": "Sala da equipa","cp_team_hint": "As tuas equipas e as suas reuniões","cp_wardrobe": "Guarda-roupa",- "cp_wardrobe_hint": "Muda a tua personagem","cp_lead": "Gabinete do líder",- "cp_lead_hint": "Fala com o teu agente líder",- "cp_break": "Sala de descanso",- "cp_break_hint": "Chamar para pausa para café",+ "cp_break": "Bar de café","cp_elevator": "Elevador",- "cp_elevator_hint": "Carrega no botão de chamada ao lado das portas","elevator_choose": "Escolhe um piso",- "elevator_keys": "0–2 escolhe um piso · Esc fecha",+ "elevator_keys": "0–3 escolhe um piso · Esc fecha","floor_name_agents": "Piso dos agentes","floor_name_coding": "Piso de programação","floor_name_arcade": "Piso de arcada",+ "floor_name_hall": "Salão dos Níveis","riding_up_to": "A subir · {0}","riding_down_to": "A descer · {0}","arcade_floor_title": "Piso de arcada","arcade_floor_subtitle": "Máquinas jogáveis: {0}",- "arcade_floor_hint": "Aproxima-te de uma máquina e prime E para jogar",+ "hall_floor_title": "Salão dos Níveis",+ "hall_floor_subtitle": "Patentes, recompensas e o teu próprio aspeto","cp_spawn": "Ponto de criação",- "cp_spawn_hint": "Criar um novo agente Dodaios","cp_launch": "Ponto de criação",- "cp_launch_hint": "Criar um novo agente de programação",- "spawn_title": "Um novo agente para a tua equipa",- "spawn_body": "Aparece aqui mesmo na plataforma e vai até uma secretária livre.",- "spawn_step_job": "Dá-lhe um nome e descreve o seu trabalho",- "spawn_step_brain": "Escolhe o modelo e o aspeto",- "spawn_step_arrive": "Aparece nesta plataforma",- "spawn_action": "Criar um agente",- "spawn_team": "{0} agentes neste piso · {1} a trabalhar",- "launch_title": "Um novo agente de programação","launch_body": "Escolhe uma CLI de programação e, se quiseres, uma primeira tarefa. Abre como terminal no Agentic IDE e aparece aqui na plataforma.","guide": {"tablist": "Secções da receção",- "tab_welcome": "Boas-vindas","tab_controls": "Controlos","tab_settings": "Definições","hud_button": "Ajuda e definições",- "hero_title": "Faz crescer a tua equipa",- "places": "Locais no Dodaios Verse","place_walk": "Ir até lá","place_walk_label": "Ir até {0}","tip_guide": "abre esta ajuda a partir de qualquer ponto do mapa; prime novamente para fechar.",@@ -1184,17 +1214,17 @@"key_down": "Seta para baixo","key_left": "Seta para a esquerda","key_right": "Seta para a direita",- "set_section_move": "Movimento",- "set_section_view": "Visualização","settings_intro": "As tuas definições para o Dodaios Verse, guardadas neste dispositivo.","set_always_run": "Correr sempre","set_always_run_hint": "Correr por predefinição; mantém Shift premido para andar.",- "set_hint_bar": "Barra de controlos",- "set_hint_bar_hint": "Mostrar o lembrete curto dos controlos na parte inferior do mapa.",- "set_reset": "Repor predefinições"+ "set_reset": "Repor predefinições",+ "tab_agents": "Agentes",+ "tab_places": "Locais",+ "set_hints": "Dicas de controlo",+ "set_hints_hint": "Mostrar de novo a breve introdução aos controlos no mapa.",+ "set_hints_action": "Mostrar de novo"},"coding_title": "Piso de programação",- "coding_subtitle": "Sessões de programação no piso: {0}","coding_empty": "Não há nenhum agente de programação a correr. Inicia um no IDE e ele ocupa aqui uma secretária.","ledger_coding": "Lista de sessões","open_ide": "Abrir o IDE",@@ -1304,7 +1334,6 @@"fleet_stop": "Parar {0}","fleet_result": "Chegou a {0} de {1}.","fleet_result_missed": "Não alcançados: {0}",- "elevator_press": "Clica no botão","arcade_prompt": "Jogar Asteroid Run","arcade_title": "Asteroid Run","arcade_score": "Pontuação",@@ -1332,9 +1361,7 @@"room_prizes": "Loja de prémios","room_snack": "Snack-bar","cp_studio": "Estúdio",- "cp_studio_hint": "Equipa-te a ti e ao teu animal com as tuas recompensas","cp_levels": "Quadro de níveis",- "cp_levels_hint": "O teu nível, as tuas recompensas e como subir de nível","room_levels": "Salão dos Níveis","dog_treat": "Dar o osso","dog_take_bone": "Pegar num biscoito para cão",@@ -1359,16 +1386,28 @@"activity_meeting": "Na sala da equipa","activity_board": "No quadro","activity_wander": "A passear",- "activity_visit": "A conversar",+ "activity_visit": "A dar uma vista de olhos","activity_called": "A caminho",+ "activity_huddle": "No quadro da equipa",+ "activity_mate": "No estúdio",+ "activity_studio": "No estúdio",+ "activity_handoff": "A levar uma mensagem",+ "board_speaking": "A falar",+ "board_empty": "Ainda não foi dito nada no chat desta equipa.",+ "board_pool_note": "Estes agentes ainda não estão numa equipa. Uma equipa tem um chat próprio, e ele aparece aqui.",+ "board_loading": "A ler o chat da equipa…",+ "board_unavailable": "Não é possível ler o chat da equipa neste momento.",+ "board_more": "+{0} mais",+ "handoff_to": "Para {0}: {1}","break_none": "Ninguém está livre neste momento.","break_called": "A caminho: {0}","call_sent": "{0} está a caminho.","show_agent": "Mostrar {0} no mapa","team_gather_label": "Reunir com {0} à mesa",+ "team_gather_board_label": "Reunir com {0} no quadro","team_open_label": "Abrir o chat de {0}","team_need_more": "Escolhe pelo menos dois agentes para criar uma equipa.",- "manage_empty": "Ainda não há agentes. A receção contrata o primeiro.",+ "manage_empty": "Ainda não há agentes. Cria o primeiro no ponto de criação.","wardrobe_saved": "Guardado apenas neste navegador.","count_paused": "{0} em pausa","hair_short": "Curto",@@ -1388,15 +1427,7 @@"minimap_zoom_out": "Afastar","minimap_open_map": "Mapa (M)","minimap_open_map_label": "Abrir o mapa completo (M)",- "compass_label": "Bússola: a direção para onde a câmara está virada","compass_n": "N",- "compass_ne": "NE",- "compass_e": "E",- "compass_se": "SE",- "compass_s": "S",- "compass_sw": "SO",- "compass_w": "O",- "compass_nw": "NO","map_title": "Mapa do Dodaios Verse","map_hint": "Clica em qualquer lado para ir até lá. Esc ou M fecha o mapa.","map_close": "Fechar mapa",@@ -1445,7 +1476,7 @@"wardrobe_save_agent": "Guardar aspeto para {0}","wardrobe_saved_agent": "{0} está com o novo aspeto.","wardrobe_save_error": "Não foi possível guardar o aspeto. As tuas alterações mantêm-se; tenta novamente.",- "wardrobe_sample_hint": "Os agentes de exemplo não podem ser guardados. Cria um agente real na receção.",+ "wardrobe_sample_hint": "Os agentes de exemplo não podem ser guardados. Cria um agente real no ponto de criação.","outfit_tee": "T-shirt","outfit_hoodie": "Hoodie","outfit_suit": "Fato",@@ -1481,6 +1512,39 @@"errand_flying": "A levar uma tarefa a {0}","errand_task": "Aqui tens uma nova tarefa.","errand_ack": "Entendido, vou tratar disso!",+ "hud_tools": "Ferramentas do mapa",+ "hud_places": "Locais",+ "places_teams": "Equipas",+ "hints_label": "Controlos",+ "hints_dismiss": "Entendido",+ "hint_walk": "Andar",+ "hint_rotate": "Olhar em volta",+ "hint_interact": "Usar o que está perto",+ "hint_guide": "Todos os controlos",+ "use_spawn": "Criar um agente",+ "use_launch": "Iniciar um agente de programação",+ "use_manage": "Abrir o diretório",+ "use_team": "Gerir equipas",+ "use_wardrobe": "Mudar o teu aspeto",+ "use_lead": "Falar com o teu líder",+ "use_break": "Chamar para uma pausa para café",+ "use_break_end": "Terminar a pausa para café",+ "use_elevator": "Chamar o elevador",+ "use_mission": "Abrir o Mission Control",+ "use_studio": "Equipar-se",+ "use_levels": "Ver os teus níveis",+ "use_board": "Abrir a equipa",+ "use_found": "Começar uma equipa aqui",+ "cp_board": "Quadro da equipa",+ "cp_found": "Lote livre",+ "cp_board_hint": "Os seus membros, o seu chat e as suas reuniões",+ "team_pool": "Sem equipa",+ "team_pool_body": "Os agentes sentados aqui ainda não estão numa equipa. Forma uma para lhes dares um chat partilhado.",+ "team_gone": "Esta equipa já não existe.",+ "team_this": "Esta equipa",+ "team_all": "Todas as equipas ({0})",+ "team_members_label": "Membros",+ "break_ended": "Todos voltaram ao seu dia.","lobby_strapline": "SEDE DOS AGENTES","lobby_board_hint": "Toca para gerir a tua equipa","lobby_new_agent": "Novo agente",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/society/zh.jsonindex 7ddda34508..a88725f3ac 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/zh.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/zh.json@@ -680,13 +680,13 @@"repair": "修复浏览器","off": "浏览器已关闭","off_hint": "浏览器仅在 {0} 需要时启动。",- "open": "打开浏览器",- "busy_task": "{0} 正在使用共享浏览器执行任务。{0} 完成后会立即在这里打开。","moved": "共享浏览器现在为 {0} 打开。它一次只能为一个智能体打开。",- "moved_status": "为 {0} 打开",- "open_here": "在这里打开",- "stop_holder": "停止 {0} 的任务",+ "moved_status": "已为 {0} 打开",+ "open_here": "在此打开","waiting_for": "正在等待 {0}",+ "busy_task": "{0} 正在使用共享浏览器执行任务。{0} 完成后会在此打开。",+ "stop_holder": "停止 {0} 的任务",+ "open": "打开浏览器","error_image": "无法解码浏览器图像","error_stream": "浏览器流返回了无效数据","error_connect": "浏览器连接失败",@@ -976,6 +976,44 @@"look": "外观","look_shape": "形状","look_pet": "宠物",+ "look_creature": "像素生物",+ "creature": {+ "figure": "形象",+ "roll": "重新掷骰",+ "number": "{0} 号生物",+ "palette": "色彩世界",+ "palettes": {+ "lava": "熔岩",+ "ocean": "海洋",+ "neon": "霓虹",+ "moss": "苔藓",+ "glacier": "冰川",+ "gold": "黄金",+ "candy": "糖果",+ "midnight": "午夜"+ },+ "eye_kinds": {+ "dot": "圆点",+ "tall": "竖长",+ "wide": "宽距",+ "visor": "护目镜"+ },+ "states": "预览状态",+ "states_hint": "智能体工作时生物的表现。选择一个状态,在上方查看。",+ "state_names": {+ "idle": "就绪",+ "listening": "聆听",+ "thinking": "思考",+ "working": "工作",+ "talking": "说话",+ "asking": "提问",+ "success": "完成",+ "error": "出错",+ "sleeping": "休眠"+ },+ "everywhere": "将所有智能体显示为像素生物",+ "everywhere_hint": "此设备的试用开关。没有专属生物的智能体会根据其形状和颜色生成一个。关闭后,所有外观恢复原样。"+ },"pet": "宠物","pet_hint": "这个智能体在所有地方都会以这只宠物出现:聊天中、工作时,以及在 Verse 中作为伙伴。","no_pets": "还没有宠物。请在“我的宠物”中添加。",@@ -1019,7 +1057,6 @@},"office": {"title": "Dodaios Verse",- "subtitle": "在场的智能体:{0}","viewport": "Dodaios Verse","loading": "正在打开 Dodaios Verse…","no_graphics": "此处无法进行 3D 渲染。每个智能体的状态仍可在智能体列表中查看。",@@ -1033,10 +1070,21 @@"open_agent": "打开 {0}","overview": "总览","ledger": "智能体列表",- "help": "WASD 行走 · Shift 奔跑 · 空格跳跃 · E 互动 · M 地图 · H 帮助与设置","sample": "示例智能体 — 暂时无法连接后端。","overflow": "只有前 {0} 个智能体有工位;列表中显示所有智能体。","open_space": "开放区域",+ "studio_pool": "人才池",+ "studio_sign_team": "团队工作室",+ "studio_sign_pool": "尚未加入团队",+ "plot_free": "留给你的下一支团队",+ "plot_hint": "在立牌处创建",+ "zone_boulevard": "林荫大道",+ "zone_atrium": "中庭",+ "zone_plot": "空地",+ "zone_garden": "花园庭院",+ "zone_booths": "专注舱",+ "zone_library": "图书角",+ "zone_cafe": "咖啡吧","close": "关闭","action_chat": "打开对话","action_walk": "走过去",@@ -1045,8 +1093,6 @@"action_draft": "加入新团队","action_undraft": "从新团队移除","draft_count": "已为新团队选择 {0} 个 · 打开团队室",- "create_body": "招募一个新智能体:给它一份职责、一个大脑和一副外观。它会出现在楼层中央的出生点,并找一个空工位坐下。",- "create_action": "创建新智能体","action_show": "显示","action_open": "打开","manage_action": "打开智能体管理",@@ -1056,12 +1102,12 @@"team_create": "创建团队并集合({0})","team_created": "团队“{0}”已就绪。","team_yours": "你的团队",- "team_none": "还没有团队。在下方组建一个吧。","team_members": "{0} 名成员","team_lead": "负责人:{0}","team_working": "{0} 个工作中","team_meet": "在桌边集合",- "team_meeting_now": "会议中",+ "team_called": "已召集",+ "team_meet_board": "在看板前集合","team_chat": "团队对话","team_edit": "编辑","team_save": "保存",@@ -1076,66 +1122,50 @@"team_no_match": "没有匹配的智能体。","team_edit_need_more": "一个团队至少需要两个智能体。","team_load_error": "无法加载团队:{0}",- "meeting_title": "会议:{0}","meeting_status": "{1} 人中有 {0} 人在桌边 · 还剩 {2} 分钟",+ "gather_table": "{0} · 已召集到桌边",+ "gather_board": "{0} · 已召集到看板前",+ "gather_note": "这只是地图上的集合:不会向团队聊天发送任何内容。",+ "gather_end": "让他们回去",+ "meeting_status_board": "{1} 人中有 {0} 人在看板前 · 还剩 {2} 分钟","meeting_busy": "正在工作,所以留在工位:{0}","meeting_join": "去桌边",- "meeting_end": "结束会议",+ "meeting_join_board": "去看板前","team_live": "实时","wardrobe_name": "你的名字","you": "你","wardrobe_body": "为自己或智能体打扮:服装、颜色、发型和眼镜。","wardrobe_shuffle": "随机配色","lead_empty": "还没有主管智能体。",- "lead_body": "你的主管负责协调其他智能体。在这里和它对话。",- "break_body": "当前空闲:{0}。叫他们来喝杯咖啡休息一下 — 纯属观赏,不影响他们的工作。",- "break_call": "召集咖啡休息",- "break_release": "大家各回各位","cp_create": "前台",- "cp_create_hint": "帮助、操作、设置和新智能体",- "cp_manage": "智能体看板",- "cp_manage_hint": "查看和管理所有智能体",+ "cp_manage": "前台",+ "cp_manage_hint": "智能体、地点、操作和设置","cp_team": "团队室","cp_team_hint": "你的团队及其会议","cp_wardrobe": "衣帽间",- "cp_wardrobe_hint": "更换你的角色造型","cp_lead": "主管办公室",- "cp_lead_hint": "和你的主管智能体对话",- "cp_break": "休息室",- "cp_break_hint": "召集咖啡休息",+ "cp_break": "咖啡吧","cp_elevator": "电梯",- "cp_elevator_hint": "按下门旁的呼叫按钮","elevator_choose": "选择楼层",- "elevator_keys": "0–2 选择楼层 · Esc 关闭",+ "elevator_keys": "0–3 选择楼层 · Esc 关闭","floor_name_agents": "智能体楼层","floor_name_coding": "编程楼层","floor_name_arcade": "街机楼层",+ "floor_name_hall": "等级大厅","riding_up_to": "上行 · {0}","riding_down_to": "下行 · {0}","arcade_floor_title": "街机楼层","arcade_floor_subtitle": "可玩的街机:{0}",- "arcade_floor_hint": "走到街机前按 E 开始游戏",+ "hall_floor_title": "等级大厅",+ "hall_floor_subtitle": "军衔、奖励和你自己的造型","cp_spawn": "出生点",- "cp_spawn_hint": "生成一个新的 Dodaios 智能体","cp_launch": "出生点",- "cp_launch_hint": "生成一个新的编程智能体",- "spawn_title": "为你的团队添加新智能体",- "spawn_body": "它会出现在这个平台上,然后走向一个空工位。",- "spawn_step_job": "给它起名并描述它的职责",- "spawn_step_brain": "选择它的模型和外观",- "spawn_step_arrive": "它会出现在这个平台上",- "spawn_action": "生成智能体",- "spawn_team": "本层 {0} 个智能体 · {1} 个工作中",- "launch_title": "新的编程智能体","launch_body": "选择一个编程 CLI,还可以给它一个初始任务。它会在 Agentic IDE 中以终端形式打开,并出现在这个平台上。","guide": {"tablist": "前台分区",- "tab_welcome": "欢迎","tab_controls": "操作","tab_settings": "设置","hud_button": "帮助与设置",- "hero_title": "壮大你的团队",- "places": "Dodaios Verse 中的地点","place_walk": "走过去","place_walk_label": "走到 {0}","tip_guide": "可在地图任意位置打开此帮助;再按一次即可关闭。",@@ -1184,17 +1214,17 @@"key_down": "下方向键","key_left": "左方向键","key_right": "右方向键",- "set_section_move": "移动",- "set_section_view": "显示","settings_intro": "你的 Dodaios Verse 设置,保存在此设备上。","set_always_run": "始终奔跑","set_always_run_hint": "默认奔跑;按住 Shift 行走。",- "set_hint_bar": "操作提示栏",- "set_hint_bar_hint": "在地图底部显示简短的操作提示。",- "set_reset": "恢复默认设置"+ "set_reset": "恢复默认设置",+ "tab_agents": "智能体",+ "tab_places": "地点",+ "set_hints": "操作提示",+ "set_hints_hint": "在地图上再次显示简短的操作介绍。",+ "set_hints_action": "再次显示"},"coding_title": "编程楼层",- "coding_subtitle": "楼层上的编程会话:{0}","coding_empty": "没有正在运行的编程智能体。在 IDE 中启动一个,它就会在这里占一个工位。","ledger_coding": "会话列表","open_ide": "打开 IDE",@@ -1304,7 +1334,6 @@"fleet_stop": "停止 {0}","fleet_result": "已送达 {1} 个中的 {0} 个。","fleet_result_missed": "未送达:{0}",- "elevator_press": "点击按钮","arcade_prompt": "玩 Asteroid Run","arcade_title": "Asteroid Run","arcade_score": "得分",@@ -1332,9 +1361,7 @@"room_prizes": "奖品店","room_snack": "小吃吧","cp_studio": "工作室",- "cp_studio_hint": "用你的奖励装扮自己和宠物","cp_levels": "等级看板",- "cp_levels_hint": "你的等级、奖励以及升级方法","room_levels": "等级大厅","dog_treat": "给它骨头","dog_take_bone": "拿一块狗零食",@@ -1359,16 +1386,28 @@"activity_meeting": "在团队室","activity_board": "在看板前","activity_wander": "闲逛",- "activity_visit": "聊天",+ "activity_visit": "串门","activity_called": "正在过来",+ "activity_huddle": "在团队看板前",+ "activity_mate": "在工作室里",+ "activity_studio": "在工作室里",+ "activity_handoff": "正在送消息",+ "board_speaking": "发言中",+ "board_empty": "这个团队的聊天里还没有人发言。",+ "board_pool_note": "这些代理还没有加入任何团队。团队有自己的聊天,会显示在这里。",+ "board_loading": "正在读取团队聊天…",+ "board_unavailable": "暂时无法读取团队聊天。",+ "board_more": "还有 {0} 位",+ "handoff_to": "致 {0}:{1}","break_none": "目前没人有空。","break_called": "正在赶来:{0}","call_sent": "{0} 正在过来。","show_agent": "在地图上显示 {0}","team_gather_label": "与 {0} 在桌边集合",+ "team_gather_board_label": "与 {0} 在看板前集合","team_open_label": "打开 {0} 的对话","team_need_more": "至少选择两个智能体才能创建团队。",- "manage_empty": "还没有智能体。去前台招募第一个吧。",+ "manage_empty": "还没有智能体。去出生点创建第一个吧。","wardrobe_saved": "仅保存在此浏览器中。","count_paused": "{0} 个已暂停","hair_short": "短发",@@ -1388,15 +1427,7 @@"minimap_zoom_out": "缩小","minimap_open_map": "地图 (M)","minimap_open_map_label": "打开完整地图 (M)",- "compass_label": "指南针:镜头朝向","compass_n": "北",- "compass_ne": "东北",- "compass_e": "东",- "compass_se": "东南",- "compass_s": "南",- "compass_sw": "西南",- "compass_w": "西",- "compass_nw": "西北","map_title": "Dodaios Verse 地图","map_hint": "点击任意位置即可走过去。按 Esc 或 M 关闭地图。","map_close": "关闭地图",@@ -1445,7 +1476,7 @@"wardrobe_save_agent": "为 {0} 保存造型","wardrobe_saved_agent": "{0} 换上了新造型。","wardrobe_save_error": "无法保存造型。你的更改已保留,请重试。",- "wardrobe_sample_hint": "示例智能体无法保存。请在前台创建一个真正的智能体。",+ "wardrobe_sample_hint": "示例智能体无法保存。请在出生点创建一个真正的智能体。","outfit_tee": "T 恤","outfit_hoodie": "连帽衫","outfit_suit": "西装",@@ -1481,6 +1512,39 @@"errand_flying": "正在给 {0} 送任务","errand_task": "这是给你的新任务。","errand_ack": "收到,马上办!",+ "hud_tools": "地图工具",+ "hud_places": "地点",+ "places_teams": "团队",+ "hints_label": "操作方式",+ "hints_dismiss": "知道了",+ "hint_walk": "行走",+ "hint_rotate": "环顾四周",+ "hint_interact": "使用附近的物件",+ "hint_guide": "全部操作",+ "use_spawn": "创建智能体",+ "use_launch": "启动编程智能体",+ "use_manage": "打开目录",+ "use_team": "管理团队",+ "use_wardrobe": "更换造型",+ "use_lead": "和主管对话",+ "use_break": "召集咖啡休息",+ "use_break_end": "结束咖啡休息",+ "use_elevator": "呼叫电梯",+ "use_mission": "打开行动控制中心",+ "use_studio": "整装",+ "use_levels": "查看等级",+ "use_board": "打开团队",+ "use_found": "在这里组建团队",+ "cp_board": "团队看板",+ "cp_found": "空地",+ "cp_board_hint": "成员、聊天和会议",+ "team_pool": "未加入团队",+ "team_pool_body": "坐在这里的智能体还没有团队。组建一个,他们就有共享聊天了。",+ "team_gone": "这个团队已不存在。",+ "team_this": "本团队",+ "team_all": "全部团队({0})",+ "team_members_label": "成员",+ "break_ended": "大家都回去忙自己的了。","lobby_strapline": "智能体总部","lobby_board_hint": "点按以管理你的团队","lobby_new_agent": "新建智能体",diff --git a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts b/jarvis/ui/web/frontend/src/lib/agentChatApi.tsindex a00e811910..cc3c69fa1b 100644--- a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts@@ -449,11 +449,13 @@ export async function deleteAgentChatSession(sessionId: string): Promise<void> {export async function fetchAgentChatSession(sessionId: string,- options: { tail?: number } = {},+ options: { tail?: number; signal?: AbortSignal } = {},): Promise<{ session: AgentChatSession; events: AgentChatEvent[] }> {const query = options.tail ? `?tail=${Math.max(1, Math.round(options.tail))}` : "";+ const url = `/api/agent-chat/sessions/${encodeURIComponent(sessionId)}${query}`;return json(- await fetch(`/api/agent-chat/sessions/${encodeURIComponent(sessionId)}${query}`),+ // A caller that schedules its own reads (the office's desk monitors) can give them a deadline.+ options.signal ? await fetch(url, { signal: options.signal }) : await fetch(url),"session-failed",);}diff --git a/jarvis/ui/web/frontend/src/lib/societyChatGroups.test.tsx b/jarvis/ui/web/frontend/src/lib/societyChatGroups.test.tsxnew file mode 100644index 0000000000..2dab9d1aeb--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/societyChatGroups.test.tsx@@ -0,0 +1,100 @@+import type { ReactNode } from "react";+import { QueryClient, QueryClientProvider, focusManager } from "@tanstack/react-query";+import { cleanup, renderHook, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { nextPollIn, useSocietyChatGroups, useSocietyMeeting } from "./societyChatGroups";++describe("when a polled query is due again", () => {+ const PERIOD = 10_000;++ it("keeps the period on average but never the same phase: half to one and a half periods", () => {+ const waits = Array.from({ length: 400 }, (_, i) => nextPollIn(1_700_000_000_000 + i * 37, PERIOD, 1_700_000_000_000 + i * 37));+ expect(Math.min(...waits)).toBeGreaterThanOrEqual(PERIOD / 2);+ expect(Math.max(...waits)).toBeLessThan(PERIOD * 1.5);+ // Spread, not one value: answers a few milliseconds apart are due at clearly different times.+ expect(new Set(waits).size).toBeGreaterThan(300);+ const mean = waits.reduce((sum, w) => sum + w, 0) / waits.length;+ expect(Math.abs(mean - PERIOD)).toBeLessThan(PERIOD * 0.1);+ });++ it("gives every watcher of one query the same moment, so their requests fold into one", () => {+ const answered = 1_700_000_123_456;+ const dueFor = (askedAt: number) => askedAt + nextPollIn(answered, PERIOD, askedAt);+ // Three components recompute at different times after the same answer: all are due at the same instant.+ expect(dueFor(answered + 5)).toBe(dueFor(answered + 900));+ expect(dueFor(answered + 900)).toBe(dueFor(answered + 3_000));+ expect(dueFor(answered + 3_000)).toBe(dueFor(answered + 4_700));+ });++ it("waits a whole period before the first answer, and a short beat when it is overdue", () => {+ expect(nextPollIn(0, PERIOD, 123)).toBe(PERIOD);+ const answered = 1_700_000_000_000;+ // Long overdue (a sleeping machine woke up): soon, but not a tight loop.+ expect(nextPollIn(answered, PERIOD, answered + 60_000)).toBe(250);+ });+});++describe("the society polls in a desktop window that reports itself hidden", () => {+ let client: QueryClient;+ const calls: string[] = [];+ const wrapper = ({ children }: { children: ReactNode }) => <QueryClientProvider client={client}>{children}</QueryClientProvider>;++ beforeEach(() => {+ calls.length = 0;+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ vi.stubGlobal("fetch", async (url: string) => {+ calls.push(url);+ return new Response(JSON.stringify(url.endsWith("/meeting") ? { messages: [], running: true, room: null } : { groups: [] }));+ });+ // What the desktop WebView tells the page about a window the person is looking at.+ focusManager.setFocused(false);+ });+ afterEach(() => {+ cleanup();+ client.clear();+ focusManager.setFocused(undefined);+ vi.unstubAllGlobals();+ vi.useRealTimers();+ });++ const observerOptions = (key: readonly unknown[]) => client.getQueryCache().find({ queryKey: key })!.observers[0]!.options;++ it("keeps refreshing the team list: jittered, and not paused by document visibility", async () => {+ const view = renderHook(() => useSocietyChatGroups(true), { wrapper });+ await waitFor(() => expect(view.result.current.isSuccess).toBe(true));+ const options = observerOptions(["society", "chat-groups"]);+ expect(options.refetchIntervalInBackground).toBe(true);+ expect(typeof options.refetchInterval).toBe("function");+ const query = client.getQueryCache().find({ queryKey: ["society", "chat-groups"] })!;+ const wait = (options.refetchInterval as (q: typeof query) => number)(query);+ expect(wait).toBeGreaterThan(4_000);+ expect(wait).toBeLessThanOrEqual(15_000);+ });++ it("really fetches again while hidden, and stays quiet while its caller is off", async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ const view = renderHook(({ on }) => useSocietyChatGroups(on), { wrapper, initialProps: { on: true } });+ await waitFor(() => expect(calls).toHaveLength(1));+ await vi.advanceTimersByTimeAsync(16_000);+ expect(calls.length).toBeGreaterThanOrEqual(2);+ // A sleeping stage passes `enabled: false`: nothing more is asked.+ view.rerender({ on: false });+ const asked = calls.length;+ await vi.advanceTimersByTimeAsync(40_000);+ expect(calls).toHaveLength(asked);+ });++ it("follows a running round the same way", async () => {+ const view = renderHook(() => useSocietyMeeting("g1"), { wrapper });+ await waitFor(() => expect(view.result.current.data?.running).toBe(true));+ const options = observerOptions(["society", "meeting", "g1"]);+ expect(options.refetchIntervalInBackground).toBe(true);+ const query = client.getQueryCache().find({ queryKey: ["society", "meeting", "g1"] })!;+ const wait = (options.refetchInterval as (q: typeof query) => number | false)(query);+ expect(wait).toBeGreaterThan(700);+ expect(wait).toBeLessThanOrEqual(3_000);+ // No round, no poll.+ query.setData({ messages: [], running: false, room: null });+ expect((options.refetchInterval as (q: typeof query) => number | false)(query)).toBe(false);+ });+});diff --git a/jarvis/ui/web/frontend/src/lib/societyChatGroups.ts b/jarvis/ui/web/frontend/src/lib/societyChatGroups.tsindex 37c897a347..34045a30b8 100644--- a/jarvis/ui/web/frontend/src/lib/societyChatGroups.ts+++ b/jarvis/ui/web/frontend/src/lib/societyChatGroups.ts@@ -1,6 +1,7 @@import { useEffect } from "react";import { useQuery, useQueryClient } from "@tanstack/react-query";import { useEventStore } from "@/store/events";+import { spreadDelay } from "@/lib/connectBudget";import type { TeamGoalState, TeamTaskState } from "@/lib/societyApi";export interface SocietyChatGroup {@@ -28,13 +29,45 @@ const body = (data: unknown): RequestInit => ({method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data),});+/**+ * How long until a polled query is due again, `periodMs` on average.+ *+ * The period is spread around itself (`spreadDelay`: half to one and a half+ * times), so windows and panes that started together do not knock together+ * for ever. The spread is taken from the time of the last answer instead of+ * a fresh random number, for one reason: several components watch the same+ * query (the office stage, the team board, the agents view), each with its+ * own timer. With a number of their own they would drift apart and send one+ * request each; with the same number they stay due at the same moment and+ * React Query folds them into one request.+ *+ * `lastMs` is when the query last answered, with data or with an error (so a+ * failing endpoint is asked again after a period, not at once); 0 = not yet.+ */+export function nextPollIn(lastMs: number, periodMs: number, now: number = Date.now()): number {+ if (lastMs <= 0) return periodMs;+ const phase = (lastMs % POLL_PHASE_MS) / POLL_PHASE_MS;+ return Math.max(POLL_FLOOR_MS, lastMs + spreadDelay(periodMs, () => phase) - now);+}+/** A prime number of milliseconds: answers a few ms apart land on unrelated phases. */+const POLL_PHASE_MS = 9973;+/** An overdue poll (the machine slept) is asked this soon, not in a tight loop; small, so watchers stay in step. */+const POLL_FLOOR_MS = 250;++const GROUPS_POLL_MS = 10_000;+const ROUND_POLL_MS = 2_000;+export function useSocietyChatGroups(enabled = true) {return useQuery({queryKey: ["society", "chat-groups"],queryFn: async () => (await json<{ groups: SocietyChatGroup[] }>("/api/society/chat-groups")).groups,enabled,staleTime: 15_000,- refetchInterval: 10_000,+ // Jittered (AP-33), and not tied to `document.visibilityState`: the desktop WebView reports a visible+ // window as hidden, which would stop this poll for good and leave a team made in chat without its studio.+ // `enabled` is what keeps a caller that is really off screen quiet.+ refetchInterval: (query) => nextPollIn(Math.max(query.state.dataUpdatedAt, query.state.errorUpdatedAt), GROUPS_POLL_MS),+ refetchIntervalInBackground: true,});}@@ -61,12 +94,20 @@ export interface SocietyMeeting {const meetingUrl = (groupId: string) => `/api/society/chat-groups/${encodeURIComponent(groupId)}/meeting`;+/** One read of a group's meeting, for callers that schedule their own reads (the office's studio boards). */+export function fetchSocietyMeeting(groupId: string, signal?: AbortSignal): Promise<SocietyMeeting> {+ return signal ? json<SocietyMeeting>(meetingUrl(groupId), { signal }) : json<SocietyMeeting>(meetingUrl(groupId));+}+export function useSocietyMeeting(groupId: string) {return useQuery({queryKey: ["society", "meeting", groupId],- queryFn: () => json<SocietyMeeting>(meetingUrl(groupId)),- // Poll only while a round runs; an idle transcript changes only when someone sends.- refetchInterval: (query) => (query.state.data?.running ? 2_000 : false),+ queryFn: () => fetchSocietyMeeting(groupId),+ // Poll only while a round runs; an idle transcript changes only when someone sends. Jittered, and not tied+ // to `document.visibilityState` (see useSocietyChatGroups): a running round must not freeze in the desktop window.+ refetchInterval: (query) => (query.state.data?.running+ ? nextPollIn(Math.max(query.state.dataUpdatedAt, query.state.errorUpdatedAt), ROUND_POLL_MS) : false),+ refetchIntervalInBackground: true,});}diff --git a/tests/unit/progression/test_service.py b/tests/unit/progression/test_service.pyindex 7beb106730..0b540f4163 100644--- a/tests/unit/progression/test_service.py+++ b/tests/unit/progression/test_service.py@@ -177,6 +177,9 @@ async def test_world_actions_are_metered_on_the_server(setup, clock):assert await service.report_action("daily_visit") is None # once per dayassert await service.report_action("floor_discovered", ref="arcade") is not Noneassert await service.report_action("floor_discovered", ref="arcade") is None+ # The Level Hall is a floor of its own and pays its first visit like the others.+ assert await service.report_action("floor_discovered", ref="hall") is not None+ assert await service.report_action("floor_discovered", ref="hall") is Nonewalked = await service.report_action("walk_together")assert walked is not None and walked.subject_id == "pet:ember"