@zaferyalcin/agent-office 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1951 @@
1
+ // Studio: one floor of an office building. Every project gets its own glass-walled office off a central
2
+ // corridor, with a door sign, a whiteboard and a desk for every agent working on it. Agents sit in open-plan
3
+ // rows of desk clusters (2-desk facing pods and 4-desk blocks) with busy leads up front and each lead's
4
+ // subagents clustered beside them; arcs over the desks show who started whom, and small packets travel along
5
+ // them while a subagent works. Clicking an office smoothly flies the camera to frame it; clicking an agent
6
+ // desk or list entry focuses that agent and opens its details; Esc or the Overview button flies back out.
7
+ //
8
+ // Cost: this module is loaded only when the Studio view opens and is fully disposed when it closes.
9
+ // All character and furniture geometries and materials are shared, no shadows, no post-processing,
10
+ // pixel ratio capped at 1.25, and a frame is drawn only while something moves, at most 30 per second.
11
+ import * as THREE from './vendor/three/three.module.js';
12
+
13
+ const VENDOR = { anthropic: 0xdba46c, openai: 0xb9c6d2, google: 0x6fa2f6, other: 0xa8b38a };
14
+ const STATE = { working: 0x4fc08d, idle: 0x8d97a3, stalled: 0xe5a43c, failed: 0xe2655d, done: 0x59616b };
15
+
16
+ // Stylised worker palettes: 2-3 clothing colours per person, harmonised with vendor hue
17
+ const TOP_PALETTE = {
18
+ anthropic: [0xd89b62, 0xc77e4c, 0xdfb17d, 0xb86f46, 0xe2a86b, 0xab693e],
19
+ openai: [0xa8bac9, 0x8da4b8, 0xc1cdd8, 0x7a93a8, 0xb2c2cf, 0x6f879c],
20
+ google: [0x5f96ed, 0x4c7fd4, 0x78abfa, 0x4b6fb8, 0x6ba0f2, 0x3e6ec2],
21
+ other: [0x97a879, 0x7e9468, 0xadb88d, 0x6f8760, 0x8ea072, 0x647a56],
22
+ };
23
+ const ACCENT_PALETTE = [0xf2ede4, 0x2b313a, 0x364a63, 0x753c42, 0xdcc59e, 0x31524c, 0xe3d9c8, 0x4d3f59];
24
+ const PANTS_PALETTE = [0x2b3446, 0x343840, 0x6e604f, 0x36463b, 0x473c35, 0x3b4b5f];
25
+ const SHOE_PALETTE = [0x22252b, 0x4e392a, 0x2f3b4d, 0xd6d1c7];
26
+ const CHAIR_PALETTE = [0x2b3038, 0x334052, 0x2f433b, 0x4a3338, 0x474038, 0x2c424b];
27
+ const BOOK_PALETTE = [0x7b4540, 0x3d546d, 0x4b644a, 0x8d6e43, 0x5c4a6b, 0x6a5b4e];
28
+ const SOFA_PALETTE = [0x394554, 0x4a3d36, 0x384b44, 0x4b3b42, 0x3e424b];
29
+ const BODY_TYPES = [
30
+ { sx: 1.00, sy: 1.00, sz: 1.00, tx: 1.00, tz: 1.00 },
31
+ { sx: 0.94, sy: 1.07, sz: 0.95, tx: 0.94, tz: 0.95 },
32
+ { sx: 0.97, sy: 0.92, sz: 0.97, tx: 0.98, tz: 0.98 },
33
+ { sx: 1.08, sy: 1.00, sz: 1.06, tx: 1.12, tz: 1.08 },
34
+ { sx: 1.05, sy: 1.06, sz: 1.04, tx: 1.08, tz: 1.05 },
35
+ ];
36
+ const SKIN = [0xf0cfb5, 0xe3b895, 0xc9946e, 0xa7724f, 0x85553a, 0x66402c];
37
+ const HAIR = [0x241c16, 0x4c3320, 0x191a1d, 0x8c6840, 0x6c7178, 0xa6442c, 0x38281e];
38
+ // carpet tints, one per office: muted and distinct from the vendor colours
39
+ const CARPET = [0x2e4a48, 0x4a3a2c, 0x3b4630, 0x2f3d55, 0x4b3438, 0x3d3f46];
40
+ const WALL = 0xd9d4ca, WALL_H = 1.25, CORRIDOR = 3.2, ROOM_W_MIN = 6.2, ROOM_D_MIN = 7.5, MAX_PEOPLE = 70, RECENT = 2 * 3600e3;
41
+ // Open-plan desk cluster metrics (desk top is 1.44 x 0.76, chair back extends to local +0.74)
42
+ const DESK_W = 1.44, BLOCK_DX = 0.78, POD_DZ = 0.48, POD2_W = DESK_W, POD4_W = DESK_W + BLOCK_DX * 2;
43
+ const POD_GAP_X = 1.08, ROW_PITCH_Z = 3.50, SIDE_MARGIN = 0.95, Z_FRONT = 2.60, Z_BACK = 2.45;
44
+ const ROW_CANDIDATES = [
45
+ [1, POD4_W + 0.1],
46
+ [2, POD2_W * 2 + POD_GAP_X + 0.1],
47
+ [2, POD4_W + POD2_W + POD_GAP_X + 0.1],
48
+ [2, POD4_W * 2 + POD_GAP_X + 0.1],
49
+ [3, POD2_W * 3 + POD_GAP_X * 2 + 0.1],
50
+ [3, POD4_W * 2 + POD2_W + POD_GAP_X * 2 + 0.1],
51
+ [3, POD4_W * 3 + POD_GAP_X * 2 + 0.1],
52
+ [4, POD2_W * 4 + POD_GAP_X * 3 + 0.1],
53
+ [4, POD4_W * 3 + POD_GAP_X * 2 + 0.1],
54
+ ];
55
+ const ACTIVE_STATES = new Set(['working', 'idle', 'stalled']);
56
+
57
+ const POSES = {
58
+ working: { spineX: -0.07, spineZ: 0, headX: -0.03, headY: 0, headZ: 0, lArmX: 0.48, lArmZ: 0.04, lElbX: 1.24, lElbZ: 0.22, rArmX: 0.48, rArmZ: -0.04, rElbX: 1.24, rElbZ: -0.22 },
59
+ idle: { spineX: 0.11, spineZ: 0, headX: -0.02, headY: 0, headZ: 0, lArmX: 0.14, lArmZ: 0.08, lElbX: 1.08, lElbZ: 0.24, rArmX: 0.34, rArmZ: -0.04, rElbX: 1.26, rElbZ: -0.06 },
60
+ stalled: { spineX: -0.14, spineZ: 0.04, headX: 0.08, headY: -0.06, headZ: -0.15, lArmX: 0.44, lArmZ: 0.06, lElbX: 1.24, lElbZ: 0.20, rArmX: 0.82, rArmZ: -0.14, rElbX: 2.02, rElbZ: -0.28 },
61
+ failed: { spineX: -0.28, spineZ: 0, headX: 0.32, headY: 0, headZ: 0, lArmX: 0.90, lArmZ: 0.12, lElbX: 1.94, lElbZ: 0.26, rArmX: 0.90, rArmZ: -0.12, rElbX: 1.94, rElbZ: -0.26 },
62
+ done: { spineX: 0, spineZ: 0, headX: 0, headY: 0, headZ: 0, lArmX: 0.1, lArmZ: 0.06, lElbX: 1.0, lElbZ: 0.1, rArmX: 0.1, rArmZ: -0.06, rElbX: 1.0, rElbZ: -0.1 },
63
+ };
64
+ const REC_ACTIVE_POSE = { spineX: -0.05, spineZ: 0, headX: -0.02, headY: 0.04, headZ: 0, lArmX: 0.44, lArmZ: 0.05, lElbX: 1.22, lElbZ: 0.20, rArmX: 0.44, rArmZ: -0.05, rElbX: 1.22, rElbZ: -0.20 };
65
+ const REC_EMPTY_POSE = { spineX: 0.07, spineZ: 0, headX: 0.15, headY: 0.06, headZ: -0.04, lArmX: 0.40, lArmZ: 0.06, lElbX: 1.16, lElbZ: 0.18, rArmX: 0.72, rArmZ: -0.14, rElbX: 1.98, rElbZ: -0.32 };
66
+ const VISITOR_POSE = { spineX: 0.13, spineZ: 0, headX: 0.04, headY: -0.08, headZ: 0.02, lArmX: 0.22, lArmZ: 0.06, lElbX: 0.96, lElbZ: 0.24, rArmX: 0.28, rArmZ: -0.06, rElbX: 1.04, rElbZ: -0.22 };
67
+
68
+ export function mount(host, api) {
69
+ let renderer;
70
+ try { renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'low-power' }); } catch (e) { return null; }
71
+ if (!renderer.getContext()) return null;
72
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 1.25));
73
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
74
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
75
+ renderer.toneMappingExposure = 1.04;
76
+ renderer.setClearColor(0x14171b);
77
+ host.appendChild(renderer.domElement);
78
+ renderer.domElement.style.cssText = 'display:block;position:absolute;inset:0';
79
+
80
+ // ---------------------------------------------------------------- DOM overlay: side panel, focus bar, signs, detail card
81
+ const ui = document.createElement('div');
82
+ ui.className = 'st-ui';
83
+ ui.innerHTML = '<aside class="st-panel"><h2 class="st-h"></h2><div class="st-list"></div></aside>' +
84
+ '<div class="st-signs"></div>' +
85
+ '<div class="st-focus" hidden><button class="btn st-back" data-act="back"></button><span class="st-crumb"></span></div>' +
86
+ '<div class="st-toasts" aria-live="polite"></div>' +
87
+ '<div class="st-empty" role="status" hidden><h3 class="st-empty-t"></h3><p class="st-empty-b"></p></div>' +
88
+ '<section class="st-card" hidden></section>' +
89
+ '<div class="st-bar"><button class="btn" data-act="overview"></button><button class="btn" data-act="orbit" aria-pressed="false"></button><span class="st-hint"></span></div>' +
90
+ '<div class="st-tip" hidden></div>';
91
+ host.appendChild(ui);
92
+ const $ = (sel) => ui.querySelector(sel);
93
+ const tipEl = $('.st-tip');
94
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
95
+
96
+ // ---------------------------------------------------------------- scene & lighting
97
+ const scene = new THREE.Scene();
98
+ scene.fog = new THREE.Fog(0x14171b, 55, 140);
99
+ const camera = new THREE.PerspectiveCamera(36, 1, 0.1, 260);
100
+ scene.add(new THREE.HemisphereLight(0xdce7f5, 0x2a303a, 1.45));
101
+ const sun = new THREE.DirectionalLight(0xfff2e0, 1.45); sun.position.set(14, 22, 16); scene.add(sun);
102
+ const rim = new THREE.DirectionalLight(0x9fc2f0, 0.52); rim.position.set(-14, 12, -14); scene.add(rim);
103
+
104
+ // Sculpted torso lathe profile (hip -> tapered waist -> rounded chest -> shoulder slope)
105
+ const torsoPts = [
106
+ new THREE.Vector2(0.01, 0.00), new THREE.Vector2(0.145, 0.01), new THREE.Vector2(0.138, 0.10),
107
+ new THREE.Vector2(0.152, 0.22), new THREE.Vector2(0.175, 0.34), new THREE.Vector2(0.162, 0.415),
108
+ new THREE.Vector2(0.105, 0.45), new THREE.Vector2(0.052, 0.46),
109
+ ];
110
+
111
+ const G = {
112
+ plane: new THREE.PlaneGeometry(1, 1), box: new THREE.BoxGeometry(1, 1, 1),
113
+ // Desk & monitor
114
+ deskTop: new THREE.BoxGeometry(1.44, 0.055, 0.76), leg: new THREE.BoxGeometry(0.045, 0.72, 0.045),
115
+ deskCross: new THREE.BoxGeometry(1.26, 0.032, 0.032),
116
+ monitor: new THREE.BoxGeometry(0.66, 0.40, 0.032), screen: new THREE.PlaneGeometry(0.60, 0.34),
117
+ stand: new THREE.BoxGeometry(0.052, 0.22, 0.042), standBase: new THREE.BoxGeometry(0.24, 0.018, 0.16),
118
+ monitorSmall: new THREE.BoxGeometry(0.44, 0.30, 0.028), screenSmall: new THREE.PlaneGeometry(0.39, 0.25),
119
+ standSmall: new THREE.BoxGeometry(0.042, 0.16, 0.036), standBaseSmall: new THREE.BoxGeometry(0.16, 0.015, 0.12),
120
+ keyboard: new THREE.BoxGeometry(0.42, 0.018, 0.145), keyStrip: new THREE.BoxGeometry(0.38, 0.008, 0.105),
121
+ mousePad: new THREE.BoxGeometry(0.22, 0.006, 0.20), mouse: new THREE.CapsuleGeometry(0.025, 0.034, 4, 8),
122
+ notebook: new THREE.BoxGeometry(0.19, 0.016, 0.25),
123
+ book: new THREE.BoxGeometry(0.17, 0.028, 0.23),
124
+ lampBase: new THREE.CylinderGeometry(0.068, 0.075, 0.02, 10), lampArm: new THREE.CylinderGeometry(0.010, 0.010, 0.26, 6),
125
+ lampShade: new THREE.ConeGeometry(0.072, 0.09, 10), lampBulb: new THREE.CircleGeometry(0.052, 10),
126
+ miniPot: new THREE.CylinderGeometry(0.056, 0.042, 0.085, 8), miniLeaves: new THREE.DodecahedronGeometry(0.082, 0),
127
+ photoFrame: new THREE.BoxGeometry(0.13, 0.16, 0.018), photoInner: new THREE.PlaneGeometry(0.10, 0.13),
128
+ // Ergonomic swivel chair
129
+ chairSeat: new THREE.BoxGeometry(0.46, 0.068, 0.44), chairBack: new THREE.BoxGeometry(0.44, 0.46, 0.058),
130
+ chairSpine: new THREE.BoxGeometry(0.075, 0.36, 0.045), chairStem: new THREE.CylinderGeometry(0.028, 0.034, 0.37, 8),
131
+ chairFoot: new THREE.BoxGeometry(0.042, 0.028, 0.25), chairArm: new THREE.BoxGeometry(0.044, 0.028, 0.27),
132
+ chairArmPost: new THREE.BoxGeometry(0.032, 0.20, 0.032),
133
+ // Stylised person anatomy (streamlined to keep every worker under 35 meshes)
134
+ pelvis: new THREE.CapsuleGeometry(0.095, 0.14, 6, 10),
135
+ torso: new THREE.LatheGeometry(torsoPts, 16),
136
+ collar: new THREE.TorusGeometry(0.068, 0.022, 8, 14),
137
+ belt: new THREE.TorusGeometry(0.132, 0.015, 6, 16),
138
+ scarf: new THREE.TorusGeometry(0.084, 0.024, 8, 14),
139
+ neck: new THREE.CylinderGeometry(0.044, 0.052, 0.11, 10),
140
+ head: new THREE.SphereGeometry(0.128, 16, 12),
141
+ ear: new THREE.SphereGeometry(0.026, 8, 6),
142
+ eye: new THREE.SphereGeometry(0.014, 8, 6),
143
+ brow: new THREE.BoxGeometry(0.033, 0.008, 0.010),
144
+ nose: new THREE.SphereGeometry(0.014, 6, 6),
145
+ glassesRim: new THREE.TorusGeometry(0.031, 0.0055, 6, 12),
146
+ glassesBridge: new THREE.BoxGeometry(0.022, 0.0055, 0.0055),
147
+ hpBand: new THREE.TorusGeometry(0.136, 0.013, 6, 16, Math.PI),
148
+ hpCup: new THREE.CylinderGeometry(0.040, 0.040, 0.026, 10),
149
+ // Hairstyles & headwear
150
+ hairCap: new THREE.SphereGeometry(0.134, 16, 10, 0, Math.PI * 2, 0, Math.PI * 0.49),
151
+ hairBack: new THREE.SphereGeometry(0.128, 14, 10),
152
+ hairFringe: new THREE.CapsuleGeometry(0.028, 0.105, 5, 8),
153
+ hairBob: new THREE.CapsuleGeometry(0.038, 0.155, 6, 8),
154
+ hairPony: new THREE.CapsuleGeometry(0.040, 0.175, 6, 8),
155
+ hairBun: new THREE.SphereGeometry(0.062, 12, 10),
156
+ hairTie: new THREE.TorusGeometry(0.040, 0.010, 6, 10),
157
+ hairPuff: new THREE.SphereGeometry(0.052, 10, 8),
158
+ capVisor: new THREE.CylinderGeometry(0.115, 0.115, 0.015, 12),
159
+ // Articulated arms & hands
160
+ upperArm: new THREE.CapsuleGeometry(0.045, 0.145, 6, 10),
161
+ forearmFull: new THREE.CapsuleGeometry(0.038, 0.145, 6, 10),
162
+ forearmUpper: new THREE.CapsuleGeometry(0.041, 0.068, 6, 10),
163
+ forearmLower: new THREE.CapsuleGeometry(0.034, 0.105, 6, 10),
164
+ hand: new THREE.CapsuleGeometry(0.025, 0.048, 4, 8),
165
+ // Legs & shoes
166
+ thigh: new THREE.CapsuleGeometry(0.066, 0.24, 6, 10),
167
+ calf: new THREE.CapsuleGeometry(0.047, 0.30, 6, 10),
168
+ shoe: new THREE.CapsuleGeometry(0.045, 0.105, 6, 10),
169
+ // Office, lobby props & indicators
170
+ pot: new THREE.CylinderGeometry(0.22, 0.16, 0.36, 10), leaves: new THREE.DodecahedronGeometry(0.38, 1),
171
+ mug: new THREE.CylinderGeometry(0.044, 0.038, 0.095, 10), mugHandle: new THREE.TorusGeometry(0.024, 0.007, 6, 10, Math.PI),
172
+ bellBase: new THREE.CylinderGeometry(0.068, 0.075, 0.016, 12),
173
+ bellDome: new THREE.SphereGeometry(0.058, 12, 8, 0, Math.PI * 2, 0, Math.PI * 0.5),
174
+ bellBtn: new THREE.CylinderGeometry(0.014, 0.014, 0.016, 8),
175
+ coolerBody: new THREE.BoxGeometry(0.36, 0.72, 0.36),
176
+ coolerJug: new THREE.CylinderGeometry(0.13, 0.13, 0.34, 12),
177
+ coolerNeck: new THREE.CylinderGeometry(0.055, 0.12, 0.07, 10),
178
+ tableTop: new THREE.CylinderGeometry(0.42, 0.42, 0.042, 16),
179
+ tableStem: new THREE.CylinderGeometry(0.04, 0.048, 0.64, 8),
180
+ tableBase: new THREE.CylinderGeometry(0.24, 0.26, 0.028, 12),
181
+ stoolSeat: new THREE.CylinderGeometry(0.17, 0.17, 0.05, 12),
182
+ stoolLeg: new THREE.CylinderGeometry(0.025, 0.032, 0.42, 8),
183
+ ring: new THREE.RingGeometry(0.56, 0.72, 28), focusRing: new THREE.RingGeometry(0.50, 0.60, 32),
184
+ packet: new THREE.SphereGeometry(0.065, 8, 6),
185
+ };
186
+
187
+ const mats = new Map();
188
+ const mat = (color, kind, extra) => {
189
+ const k = (kind || 's') + ':' + color + (extra ? JSON.stringify(extra) : '');
190
+ if (!mats.has(k)) {
191
+ if (kind === 'b') mats.set(k, new THREE.MeshBasicMaterial({ color, ...(extra || {}) }));
192
+ else if (kind === 'f') mats.set(k, new THREE.MeshLambertMaterial({ color, flatShading: true, ...(extra || {}) }));
193
+ else mats.set(k, new THREE.MeshStandardMaterial({ color, roughness: 0.78, metalness: 0.04, ...(extra || {}) }));
194
+ }
195
+ return mats.get(k);
196
+ };
197
+ const lineMat = (color, opacity) => {
198
+ const k = 'line' + color + ':' + opacity;
199
+ if (!mats.has(k)) mats.set(k, new THREE.LineBasicMaterial({ color, transparent: true, opacity }));
200
+ return mats.get(k);
201
+ };
202
+ const M = {
203
+ desk: mat(0xb58f68, 's', { roughness: 0.68 }), leg: mat(0x363c45, 's', { roughness: 0.45, metalness: 0.35 }),
204
+ chair: mat(0x2b3038, 's', { roughness: 0.82 }), chairMetal: mat(0x4c5460, 's', { roughness: 0.38, metalness: 0.5 }),
205
+ keyboard: mat(0x23272e, 's', { roughness: 0.65 }), keycap: mat(0x474f5c, 's', { roughness: 0.7 }),
206
+ mousePad: mat(0x282d35, 's', { roughness: 0.9 }), notebook: mat(0xe3dccb, 's', { roughness: 0.85 }),
207
+ eye: mat(0x1b1e24, 's', { roughness: 0.3 }), glasses: mat(0x242830, 's', { roughness: 0.35, metalness: 0.5 }),
208
+ hp: mat(0x2b3038, 's', { roughness: 0.5, metalness: 0.2 }), hpPad: mat(0x4a525e, 's', { roughness: 0.85 }),
209
+ wall: mat(WALL, 's', { roughness: 0.88 }), trim: mat(0x8f8a80, 's', { roughness: 0.65, metalness: 0.15 }),
210
+ glass: mat(0xbfd8e6, 's', { transparent: true, opacity: 0.17, depthWrite: false, roughness: 0.15, metalness: 0.1 }),
211
+ corridor: mat(0x2a2e34, 's', { roughness: 0.9 }), lobby: mat(0x34312c, 's', { roughness: 0.88 }),
212
+ screenOff: mat(0x1b1e22, 'b'), screenAlarm: new THREE.MeshBasicMaterial({ color: 0xe2655d }),
213
+ ring: new THREE.MeshBasicMaterial({ color: 0xe2655d, transparent: true, opacity: 0.5, depthWrite: false, side: THREE.DoubleSide }),
214
+ focusRing: new THREE.MeshBasicMaterial({ color: 0x6fa2f6, transparent: true, opacity: 0.72, depthWrite: false, side: THREE.DoubleSide }),
215
+ hoverRing: new THREE.MeshBasicMaterial({ color: 0xece8e0, transparent: true, opacity: 0.35, depthWrite: false, side: THREE.DoubleSide }),
216
+ roomFocus: new THREE.LineBasicMaterial({ color: 0x6fa2f6, transparent: true, opacity: 0.9 }),
217
+ roomHover: new THREE.LineBasicMaterial({ color: 0xece8e0, transparent: true, opacity: 0.45 }),
218
+ pot: mat(0xc9c2b4, 's', { roughness: 0.85 }), leaves: mat(0x4b7a48, 's', { roughness: 0.82 }), mug: mat(0xece6da, 's', { roughness: 0.35 }),
219
+ miniPot: mat(0xb87654, 's', { roughness: 0.82 }), lampShade: mat(0x3a4350, 's', { roughness: 0.55, metalness: 0.25 }),
220
+ lampGlow: mat(0xffe8b8, 'b'), frameWood: mat(0x6b4e37, 's', { roughness: 0.72 }), photoCard: mat(0xd7e1e8, 's', { roughness: 0.85 }),
221
+ bellBrass: mat(0xd6b05c, 's', { roughness: 0.28, metalness: 0.65 }),
222
+ coolerBody: mat(0xdad7d0, 's', { roughness: 0.65 }), coolerJug: mat(0x7cbbe3, 's', { transparent: true, opacity: 0.65, roughness: 0.18 }),
223
+ shelfWood: mat(0x8e6f52, 's', { roughness: 0.75 }), tableTop: mat(0xc4a480, 's', { roughness: 0.68 }),
224
+ recScreen: mat(0x3a5d6e, 'b'), recScreenDim: mat(0x22303a, 'b'),
225
+ // Dark office material variants (shared via mat(), no per-mesh cloning)
226
+ wallDark: mat(darken(WALL, 0.34), 's', { roughness: 0.92 }), trimDark: mat(0x32302d, 's', { roughness: 0.78, metalness: 0.1 }),
227
+ glassDark: mat(0x4a667a, 's', { transparent: true, opacity: 0.25, depthWrite: false, roughness: 0.2, metalness: 0.1 }),
228
+ deskDark: mat(0x433528, 's', { roughness: 0.82 }), legDark: mat(0x191c21, 's', { roughness: 0.65, metalness: 0.2 }),
229
+ chairDark: mat(0x16191e, 's', { roughness: 0.9 }), chairMetalDark: mat(0x22262c, 's', { roughness: 0.55, metalness: 0.35 }),
230
+ keyboardDark: mat(0x13161a, 's', { roughness: 0.8 }), keycapDark: mat(0x21252c, 's', { roughness: 0.85 }),
231
+ mousePadDark: mat(0x14171c, 's', { roughness: 0.95 }), notebookDark: mat(0x524f49, 's', { roughness: 0.92 }),
232
+ potDark: mat(0x4a4842, 's', { roughness: 0.9 }), leavesDark: mat(0x213520, 's', { roughness: 0.9 }), mugDark: mat(0x54524e, 's', { roughness: 0.55 }),
233
+ miniPotDark: mat(0x442e22, 's', { roughness: 0.9 }), lampShadeDark: mat(0x1a1e24, 's', { roughness: 0.7 }),
234
+ frameWoodDark: mat(0x291f17, 's', { roughness: 0.85 }), photoCardDark: mat(0x4b5158, 's', { roughness: 0.92 }),
235
+ coolerBodyDark: mat(0x4c4b49, 's', { roughness: 0.85 }), coolerJugDark: mat(0x2c4557, 's', { transparent: true, opacity: 0.55, roughness: 0.3 }),
236
+ shelfWoodDark: mat(0x362b21, 's', { roughness: 0.88 }), tableTopDark: mat(0x483d30, 's', { roughness: 0.85 }),
237
+ // Active office warm unlit ceiling glow & wall-top strips (no real lights, no shadows)
238
+ ceilGlow: mat(0xfff0d4, 'b', { transparent: true, opacity: 0.055, depthWrite: false, side: THREE.DoubleSide }),
239
+ lightStrip: mat(0xffe9c2, 'b', { transparent: true, opacity: 0.72 }),
240
+ };
241
+
242
+ const textures = [];
243
+ function canvasTex(w, h, draw, track = true) {
244
+ const c = document.createElement('canvas'); c.width = w; c.height = h; draw(c.getContext('2d'), w, h);
245
+ const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 2;
246
+ if (track) textures.push(t);
247
+ return t;
248
+ }
249
+ // scrolling "code" for working screens, one texture per vendor
250
+ const codeTex = {};
251
+ for (const v of Object.keys(VENDOR)) {
252
+ const t = canvasTex(128, 128, (g, w, h) => {
253
+ g.fillStyle = '#16191e'; g.fillRect(0, 0, w, h);
254
+ const col = '#' + VENDOR[v].toString(16).padStart(6, '0');
255
+ for (let y = 4; y < h; y += 8) {
256
+ let x = 6 + ((y * 7) % 4) * 8;
257
+ while (x < w - 10) { const len = 6 + ((x * 13 + y * 5) % 26); g.fillStyle = (x + y) % 3 ? col : '#6c7682'; g.globalAlpha = 0.85; g.fillRect(x, y, len, 3); x += len + 5; if ((x + y) % 5 === 0) break; }
258
+ }
259
+ });
260
+ t.wrapS = t.wrapT = THREE.RepeatWrapping; t.repeat.set(1, 0.5);
261
+ codeTex[v] = { tex: t, mat: new THREE.MeshBasicMaterial({ map: t }) };
262
+ }
263
+ const codeTexList = Object.values(codeTex);
264
+ const sprite = (draw) => new THREE.SpriteMaterial({ map: canvasTex(64, 64, draw), depthWrite: false });
265
+ const SP = {
266
+ alert: sprite((g) => { g.fillStyle = '#e2655d'; g.beginPath(); g.moveTo(32, 4); g.lineTo(60, 56); g.lineTo(4, 56); g.closePath(); g.fill(); g.fillStyle = '#fff'; g.font = 'bold 34px sans-serif'; g.textAlign = 'center'; g.fillText('!', 32, 50); }),
267
+ warn: sprite((g) => { g.fillStyle = '#e5a43c'; g.beginPath(); g.arc(32, 32, 26, 0, 7); g.fill(); g.fillStyle = '#1b1f25'; g.font = 'bold 34px sans-serif'; g.textAlign = 'center'; g.fillText('!', 32, 44); }),
268
+ zz: sprite((g) => { g.fillStyle = '#c8d0da'; g.font = 'bold 26px sans-serif'; g.fillText('z', 14, 46); g.font = 'bold 18px sans-serif'; g.fillText('z', 36, 26); }),
269
+ };
270
+
271
+ const world = new THREE.Group(); scene.add(world);
272
+ const ground = new THREE.Mesh(new THREE.PlaneGeometry(500, 500), mat(0x191c21, 's', { roughness: 0.95 })); ground.rotation.x = -Math.PI / 2; ground.position.y = -0.02; scene.add(ground);
273
+ const building = new THREE.Group(); world.add(building);
274
+ const arcs = new THREE.Group(); world.add(arcs);
275
+
276
+ const desks = new Map(); // id -> desk
277
+ let rooms = []; // { key, name, group, el, door, center, w, d, side, size, border, arr, swaps }
278
+ let links = []; // { line, packet, curve, child, t }
279
+ let lobbyActors = null; // { rec, recScreen, handMug, counterMug, counterBook, visitor }
280
+ let layoutKey = null, lastState = null, selected = null, hovered = null, hoveredRoom = null;
281
+ let focusMode = 'overview', focusedRoomKey = null, isEmpty = false;
282
+ let autoOrbit = false, feedTimer = 0, feedFor = null, feed = null;
283
+ let taskExpanded = false;
284
+ const expandedFeed = new Set();
285
+ const CHEV = '<svg class="st-chev" viewBox="0 0 12 12" width="12" height="12" aria-hidden="true"><path d="M4 2.5 7.5 6 4 9.5" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>';
286
+ const isCmdTool = (name) => /bash|shell|command|exec/i.test(String(name || ''));
287
+ function feedRowKey(r) {
288
+ if (r.key != null && r.key !== '') return 'k:' + String(r.key).replace(/\r\n?/g, '\n');
289
+ if (r.id != null && r.id !== '') return 'id:' + String(r.id).replace(/\r\n?/g, '\n');
290
+ const body = String(r.arg || r.text || r.res || '').replace(/\r\n?/g, '\n');
291
+ return (r.ts || 0) + '|' + String(r.tool || '') + '|' + body;
292
+ }
293
+ function resetCardExpand() { expandedFeed.clear(); taskExpanded = false; }
294
+
295
+ // ---------------------------------------------------------------- props
296
+ function add(parent, geo, material, x, y, z, sx, sy, sz) {
297
+ const m = new THREE.Mesh(geo, material); m.position.set(x, y, z); if (sx != null) m.scale.set(sx, sy, sz); parent.add(m); return m;
298
+ }
299
+ function addSwap(swaps, parent, geo, litMat, darkMat, x, y, z, sx, sy, sz) {
300
+ const m = add(parent, geo, litMat, x, y, z, sx, sy, sz);
301
+ if (swaps) swaps.push([m, litMat, darkMat]);
302
+ return m;
303
+ }
304
+ function plant(parent, x, z, swaps) {
305
+ const pot = addSwap(swaps, parent, G.pot, M.pot, M.potDark, x, 0.18, z);
306
+ const l = addSwap(swaps, parent, G.leaves, M.leaves, M.leavesDark, x, 0.68, z, 0.95, 1.2, 0.95);
307
+ l.rotation.y = (x + z) * 0.7;
308
+ return { pot, leaves: l };
309
+ }
310
+ function addSwivelChair(parent, swaps, x, z, rotY, chairMat, chairDarkMat) {
311
+ const chair = new THREE.Group(); chair.position.set(x, 0, z); chair.rotation.y = rotY; parent.add(chair);
312
+ addSwap(swaps, chair, G.chairSeat, chairMat, chairDarkMat, 0, 0.475, 0);
313
+ addSwap(swaps, chair, G.chairBack, chairMat, chairDarkMat, 0, 0.79, 0.21);
314
+ addSwap(swaps, chair, G.chairSpine, M.chairMetal, M.chairMetalDark, 0, 0.59, 0.22);
315
+ addSwap(swaps, chair, G.chairStem, M.chairMetal, M.chairMetalDark, 0, 0.24, 0);
316
+ for (let i = 0; i < 5; i++) {
317
+ const a = (i / 5) * Math.PI * 2;
318
+ const f = addSwap(swaps, chair, G.chairFoot, M.chairMetal, M.chairMetalDark, Math.sin(a) * 0.12, 0.03, Math.cos(a) * 0.12);
319
+ f.rotation.y = a;
320
+ }
321
+ for (const sx of [-0.255, 0.255]) {
322
+ addSwap(swaps, chair, G.chairArmPost, M.chairMetal, M.chairMetalDark, sx, 0.57, 0.02);
323
+ addSwap(swaps, chair, G.chairArm, chairMat, chairDarkMat, sx, 0.675, 0.0);
324
+ }
325
+ return chair;
326
+ }
327
+ function addBookshelf(parent, swaps, x, z, rotY, seed) {
328
+ const sh = new THREE.Group(); sh.position.set(x, 0, z); sh.rotation.y = rotY; parent.add(sh);
329
+ addSwap(swaps, sh, G.box, M.shelfWood, M.shelfWoodDark, 0, 0.56, 0.135, 1.12, 1.12, 0.03);
330
+ addSwap(swaps, sh, G.box, M.shelfWood, M.shelfWoodDark, -0.54, 0.56, 0, 0.04, 1.12, 0.30);
331
+ addSwap(swaps, sh, G.box, M.shelfWood, M.shelfWoodDark, 0.54, 0.56, 0, 0.04, 1.12, 0.30);
332
+ for (const sy of [0.04, 0.38, 0.72, 1.08]) addSwap(swaps, sh, G.box, M.shelfWood, M.shelfWoodDark, 0, sy, 0, 1.12, 0.03, 0.30);
333
+ const rows = [[-0.26, 0.51, 0.32], [0.22, 0.50, 0.28], [-0.14, 0.85, 0.36], [0.30, 0.84, 0.22]];
334
+ for (let i = 0; i < rows.length; i++) {
335
+ const [bx, by, bw] = rows[i];
336
+ const col = BOOK_PALETTE[(seed + i) % BOOK_PALETTE.length];
337
+ addSwap(swaps, sh, G.box, mat(col, 's', { roughness: 0.82 }), mat(darken(col, 0.38), 's', { roughness: 0.9 }), bx, by, 0.02, bw, 0.22, 0.20);
338
+ }
339
+ }
340
+ function addWaterCooler(parent, swaps, x, z, rotY) {
341
+ const wc = new THREE.Group(); wc.position.set(x, 0, z); wc.rotation.y = rotY || 0; parent.add(wc);
342
+ addSwap(swaps, wc, G.coolerBody, M.coolerBody, M.coolerBodyDark, 0, 0.36, 0);
343
+ addSwap(swaps, wc, G.coolerNeck, M.coolerJug, M.coolerJugDark, 0, 0.755, 0);
344
+ addSwap(swaps, wc, G.coolerJug, M.coolerJug, M.coolerJugDark, 0, 0.96, 0);
345
+ addSwap(swaps, wc, G.box, M.leg, M.legDark, 0, 0.62, -0.18, 0.14, 0.06, 0.04);
346
+ }
347
+ function addSofaCorner(parent, swaps, x, z, rotY, colorHex) {
348
+ const sf = new THREE.Group(); sf.position.set(x, 0, z); sf.rotation.y = rotY || 0; parent.add(sf);
349
+ const lit = mat(colorHex, 's', { roughness: 0.86 }), dk = mat(darken(colorHex, 0.38), 's', { roughness: 0.92 });
350
+ addSwap(swaps, sf, G.box, lit, dk, 0, 0.22, 0, 1.26, 0.34, 0.54);
351
+ addSwap(swaps, sf, G.box, lit, dk, 0, 0.46, -0.22, 1.26, 0.44, 0.12);
352
+ addSwap(swaps, sf, G.box, lit, dk, -0.58, 0.38, 0, 0.11, 0.30, 0.54);
353
+ addSwap(swaps, sf, G.box, lit, dk, 0.58, 0.38, 0, 0.11, 0.30, 0.54);
354
+ }
355
+ function addMeetingTable(parent, swaps, x, z, stoolHex) {
356
+ const mt = new THREE.Group(); mt.position.set(x, 0, z); parent.add(mt);
357
+ addSwap(swaps, mt, G.tableTop, M.tableTop, M.tableTopDark, 0, 0.66, 0);
358
+ addSwap(swaps, mt, G.tableStem, M.chairMetal, M.chairMetalDark, 0, 0.33, 0);
359
+ addSwap(swaps, mt, G.tableBase, M.chairMetal, M.chairMetalDark, 0, 0.015, 0);
360
+ const sLit = mat(stoolHex, 's', { roughness: 0.82 }), sDk = mat(darken(stoolHex, 0.38), 's', { roughness: 0.9 });
361
+ for (const sx of [-0.54, 0.54]) {
362
+ addSwap(swaps, mt, G.stoolSeat, sLit, sDk, sx, 0.44, 0);
363
+ addSwap(swaps, mt, G.stoolLeg, M.chairMetal, M.chairMetalDark, sx, 0.21, 0);
364
+ }
365
+ }
366
+ function whiteboard(parent, x, y, z, rotY, title, lines) {
367
+ const t = canvasTex(256, 128, (g, w, h) => {
368
+ g.fillStyle = '#f2efe8'; g.fillRect(0, 0, w, h); g.strokeStyle = '#9a958b'; g.lineWidth = 4; g.strokeRect(2, 2, w - 4, h - 4);
369
+ g.fillStyle = '#26303a'; g.font = '600 22px "Segoe UI", sans-serif'; g.fillText(String(title).slice(0, 20), 12, 32);
370
+ g.font = '15px "Segoe UI", sans-serif'; g.fillStyle = '#4b5866';
371
+ lines.slice(0, 4).forEach((l, i) => g.fillText('• ' + String(l).slice(0, 28), 14, 58 + i * 19));
372
+ }, false);
373
+ const m = new THREE.Mesh(G.plane, new THREE.MeshBasicMaterial({ map: t })); m.scale.set(1.9, 0.95, 1); m.position.set(x, y, z); m.rotation.y = rotY; m.userData.own = true; parent.add(m); return m;
374
+ }
375
+
376
+ // ---------------------------------------------------------------- stylised worker & desk (faces -z in local space)
377
+ function buildHair(head, hairMat, accentMat, style) {
378
+ if (style === 5) return; // bald
379
+ if (style === 6) {
380
+ // Baseball cap (crown + visor + back tuft)
381
+ const crown = add(head, G.hairCap, accentMat, 0, 0.026, 0.010, 1.03, 1.08, 1.05);
382
+ crown.rotation.x = 0.20;
383
+ const visor = add(head, G.capVisor, accentMat, 0, 0.058, -0.095, 0.92, 1.0, 0.68);
384
+ visor.rotation.x = 0.12;
385
+ add(head, G.hairBack, hairMat, 0, -0.005, 0.052, 0.88, 0.76, 0.68);
386
+ return;
387
+ }
388
+ const cap = add(head, G.hairCap, hairMat, 0, 0.022, 0.012, 0.98, 1.04, 1.02);
389
+ cap.rotation.x = 0.28;
390
+ if (style === 2) {
391
+ // Long flowing hair past shoulders
392
+ add(head, G.hairBack, hairMat, 0, -0.075, 0.056, 1.04, 1.52, 0.80);
393
+ const bL = add(head, G.hairBob, hairMat, -0.096, -0.080, 0.025, 0.70, 1.32, 1.04); bL.rotation.z = 0.05;
394
+ const bR = add(head, G.hairBob, hairMat, 0.096, -0.080, 0.025, 0.70, 1.32, 1.04); bR.rotation.z = -0.05;
395
+ return;
396
+ }
397
+ add(head, G.hairBack, hairMat, 0, 0.018, 0.042, 0.94, 0.92, 0.78);
398
+ if (style === 0) {
399
+ // Neat short crop with soft upper forehead fringe
400
+ const f = add(head, G.hairFringe, hairMat, 0, 0.105, -0.062, 1.05, 0.72, 0.85);
401
+ f.rotation.z = Math.PI / 2; f.rotation.y = 0.08;
402
+ } else if (style === 1) {
403
+ // Side-parted swept short style
404
+ const f = add(head, G.hairFringe, hairMat, 0.025, 0.110, -0.056, 1.12, 0.78, 0.88);
405
+ f.rotation.set(0.12, 0.18, Math.PI / 2 - 0.18);
406
+ add(head, G.hairPuff, hairMat, -0.075, 0.082, 0.0, 0.88, 0.82, 1.02);
407
+ } else if (style === 3) {
408
+ // High ponytail with hair tie
409
+ const tie = add(head, G.hairTie, accentMat, 0, 0.055, 0.126); tie.rotation.x = 0.4;
410
+ const pony = add(head, G.hairPony, hairMat, 0, -0.035, 0.165, 1.0, 1.05, 0.95); pony.rotation.x = -0.35;
411
+ } else {
412
+ // Neat top bun (style === 4)
413
+ const tie = add(head, G.hairTie, accentMat, 0, 0.126, 0.055); tie.rotation.x = Math.PI / 2 + 0.35;
414
+ add(head, G.hairBun, hairMat, 0, 0.156, 0.064, 1.02, 0.92, 1.02);
415
+ }
416
+ }
417
+
418
+ function buildArm(side, sleeveMat, skinMat, rolled) {
419
+ const sign = side === 'L' ? -1 : 1;
420
+ const arm = new THREE.Group();
421
+ arm.position.set(sign * 0.174, 0.398, -0.005);
422
+ const up = add(arm, G.upperArm, sleeveMat, 0, -0.095, 0);
423
+ const elbow = new THREE.Group();
424
+ elbow.position.set(0, -0.210, 0);
425
+ arm.add(elbow);
426
+ const sleeveMeshes = [up];
427
+ if (rolled) {
428
+ sleeveMeshes.push(add(elbow, G.forearmUpper, sleeveMat, 0, -0.048, 0));
429
+ add(elbow, G.forearmLower, skinMat, 0, -0.140, 0);
430
+ } else {
431
+ sleeveMeshes.push(add(elbow, G.forearmFull, sleeveMat, 0, -0.095, 0));
432
+ }
433
+ const hand = new THREE.Group();
434
+ hand.position.set(0, -0.205, 0);
435
+ elbow.add(hand);
436
+ add(hand, G.hand, skinMat, 0, -0.036, 0, 1.05, 1.0, 0.58);
437
+ return { arm, elbow, hand, sleeveMeshes };
438
+ }
439
+
440
+ function outfitColors(id, vendor) {
441
+ const pal = TOP_PALETTE[vendor] || TOP_PALETTE.other;
442
+ const ti = hash(id + 'top') % pal.length;
443
+ const top = pal[ti];
444
+ const sleeve = pal[(ti + 1 + (hash(id + 'slv') % (pal.length - 1))) % pal.length];
445
+ const accent = ACCENT_PALETTE[hash(id + 'acc') % ACCENT_PALETTE.length];
446
+ const pants = PANTS_PALETTE[hash(id + 'pan') % PANTS_PALETTE.length];
447
+ const shoe = SHOE_PALETTE[hash(id + 'sho') % SHOE_PALETTE.length];
448
+ const style = hash(id + 'sty') % 4; // 0: solid + scarf, 1: two-tone vendor sleeves, 2: vest + vendor sleeves, 3: vendor jacket
449
+ return { top, sleeve, accent, pants, shoe, style };
450
+ }
451
+
452
+ function buildPerson(opts) {
453
+ const bt = opts.bodyType || BODY_TYPES[0];
454
+ const p = new THREE.Group();
455
+ p.scale.set(1.06 * bt.sx, 1.06, 1.06 * bt.sz);
456
+
457
+ const skinMat = mat(opts.skin, 's', { roughness: 0.72 });
458
+ const hairMat = mat(opts.hair, 's', { roughness: 0.65 });
459
+ const topMat = mat(opts.top, 's', { roughness: 0.80 });
460
+ const sleeveShadeMat = mat(opts.sleeve != null ? opts.sleeve : opts.top, 's', { roughness: 0.80 });
461
+ const accentMat = mat(opts.accent, 's', { roughness: 0.78 });
462
+ const pantsMat = mat(opts.pants, 's', { roughness: 0.85 });
463
+ const shoeMat = mat(opts.shoe, 's', { roughness: 0.62 });
464
+
465
+ // Pelvis, thighs, calves, shoes (grounded on seat & floor)
466
+ const pelv = add(p, G.pelvis, pantsMat, 0, 0.505, 0.02); pelv.rotation.z = Math.PI / 2;
467
+ for (const sx of [-0.092, 0.092]) {
468
+ const th = add(p, G.thigh, pantsMat, sx, 0.51, -0.14); th.rotation.x = Math.PI / 2;
469
+ add(p, G.calf, pantsMat, sx, 0.295, -0.315);
470
+ const sh = add(p, G.shoe, shoeMat, sx, 0.042, -0.37, 1.0, 0.75, 1.0); sh.rotation.x = Math.PI / 2;
471
+ }
472
+
473
+ // Articulated upper body (spine pivot at waist; vertical/width body variation here keeps feet grounded)
474
+ const spine = new THREE.Group();
475
+ spine.position.set(0, 0.54, 0.01);
476
+ spine.scale.set(bt.tx, bt.sy, bt.tz);
477
+ p.add(spine);
478
+
479
+ const st = opts.outfitStyle || 0;
480
+ const torsoMat = st === 2 ? accentMat : st === 3 ? sleeveShadeMat : topMat;
481
+ const sleeveMat = st === 1 ? sleeveShadeMat : topMat;
482
+ const innerMat = st === 2 ? topMat : accentMat;
483
+
484
+ const torso = add(spine, G.torso, torsoMat, 0, 0, 0, 1.18, 1.0, 0.80);
485
+ const collar = add(spine, G.collar, innerMat, 0, 0.448, 0); collar.rotation.x = Math.PI / 2;
486
+ if (st === 0) {
487
+ const sc = add(spine, G.scarf, innerMat, 0, 0.435, -0.006, 1.08, 0.92, 1.0); sc.rotation.x = Math.PI / 2 + 0.14;
488
+ } else {
489
+ const belt = add(spine, G.belt, shoeMat, 0, 0.025, 0, 1.16, 0.82, 1.0); belt.rotation.x = Math.PI / 2;
490
+ }
491
+
492
+ // Neck & head (counter-scaled gently so heads stay proportional across body types)
493
+ add(spine, G.neck, skinMat, 0, 0.485, 0);
494
+ const head = new THREE.Group();
495
+ head.position.set(0, 0.615, 0);
496
+ head.scale.set(1 / bt.tx, 1 / bt.sy, 1 / bt.tz);
497
+ spine.add(head);
498
+ add(head, G.head, skinMat, 0, 0, 0, 0.94, 1.07, 0.98);
499
+ add(head, G.ear, skinMat, -0.118, -0.005, 0.008, 0.55, 1.0, 0.85);
500
+ add(head, G.ear, skinMat, 0.118, -0.005, 0.008, 0.55, 1.0, 0.85);
501
+ add(head, G.eye, M.eye, -0.042, 0.012, -0.116);
502
+ add(head, G.eye, M.eye, 0.042, 0.012, -0.116);
503
+ add(head, G.brow, hairMat, -0.042, 0.042, -0.116);
504
+ add(head, G.brow, hairMat, 0.042, 0.042, -0.116);
505
+ add(head, G.nose, skinMat, 0, -0.016, -0.124, 0.8, 0.9, 0.8);
506
+
507
+ buildHair(head, hairMat, innerMat, opts.hairStyle);
508
+ if (opts.hasGlasses) {
509
+ add(head, G.glassesRim, M.glasses, -0.042, 0.012, -0.124);
510
+ add(head, G.glassesRim, M.glasses, 0.042, 0.012, -0.124);
511
+ add(head, G.glassesBridge, M.glasses, 0, 0.016, -0.125);
512
+ } else if (opts.hasHeadset && opts.hairStyle !== 6) {
513
+ add(head, G.hpBand, M.hp, 0, 0.025, 0.005);
514
+ const cL = add(head, G.hpCup, M.hp, -0.132, 0.0, 0.005); cL.rotation.z = Math.PI / 2;
515
+ const cR = add(head, G.hpCup, M.hp, 0.132, 0.0, 0.005); cR.rotation.z = Math.PI / 2;
516
+ }
517
+
518
+ const armL = buildArm('L', sleeveMat, skinMat, !!opts.rolled);
519
+ const armR = buildArm('R', sleeveMat, skinMat, !!opts.rolled);
520
+ spine.add(armL.arm); spine.add(armR.arm);
521
+
522
+ const topTargets = st === 2
523
+ ? [collar, ...armL.sleeveMeshes, ...armR.sleeveMeshes]
524
+ : st === 1
525
+ ? [torso]
526
+ : st === 3
527
+ ? [...armL.sleeveMeshes, ...armR.sleeveMeshes]
528
+ : [torso, ...armL.sleeveMeshes, ...armR.sleeveMeshes];
529
+ const sleeveTargets = st === 1
530
+ ? [...armL.sleeveMeshes, ...armR.sleeveMeshes]
531
+ : st === 3
532
+ ? [torso]
533
+ : [];
534
+
535
+ return { person: p, spine, head, armL, armR, topTargets, sleeveTargets, bodySy: bt.sy };
536
+ }
537
+
538
+ function makeDesk(s) {
539
+ const g = new THREE.Group();
540
+ const swaps = [];
541
+ // Desk & main monitor
542
+ addSwap(swaps, g, G.deskTop, M.desk, M.deskDark, 0, 0.74, 0);
543
+ for (const [x, z] of [[-0.65, -0.32], [0.65, -0.32], [-0.65, 0.32], [0.65, 0.32]]) addSwap(swaps, g, G.leg, M.leg, M.legDark, x, 0.36, z);
544
+ addSwap(swaps, g, G.deskCross, M.leg, M.legDark, 0, 0.66, -0.32);
545
+ addSwap(swaps, g, G.standBase, M.leg, M.legDark, 0, 0.775, -0.24);
546
+ addSwap(swaps, g, G.stand, M.leg, M.legDark, 0, 0.88, -0.25);
547
+ addSwap(swaps, g, G.monitor, M.leg, M.legDark, 0, 1.09, -0.24);
548
+ const screens = [add(g, G.screen, M.screenOff, 0, 1.09, -0.222)];
549
+ let lampBulb = null;
550
+
551
+ // Keyboard & mouse
552
+ addSwap(swaps, g, G.keyboard, M.keyboard, M.keyboardDark, -0.02, 0.777, 0.11);
553
+ addSwap(swaps, g, G.keyStrip, M.keycap, M.keycapDark, -0.02, 0.788, 0.105);
554
+ addSwap(swaps, g, G.mousePad, M.mousePad, M.mousePadDark, 0.34, 0.771, 0.12);
555
+ const mouse = addSwap(swaps, g, G.mouse, M.keyboard, M.keyboardDark, 0.34, 0.785, 0.12, 1, 1, 0.65); mouse.rotation.x = Math.PI / 2;
556
+
557
+ // Deterministic desk props in two non-overlapping zones
558
+ const addDeskMug = (mx, mz) => {
559
+ addSwap(swaps, g, G.mug, M.mug, M.mugDark, mx, 0.815, mz);
560
+ const mh = addSwap(swaps, g, G.mugHandle, M.mug, M.mugDark, mx + 0.042, 0.815, mz); mh.rotation.z = -Math.PI / 2;
561
+ };
562
+ const addDeskPlant = (px, pz) => {
563
+ addSwap(swaps, g, G.miniPot, M.miniPot, M.miniPotDark, px, 0.81, pz);
564
+ const lv = addSwap(swaps, g, G.miniLeaves, M.leaves, M.leavesDark, px, 0.89, pz); lv.rotation.y = (px + pz) * 2.1;
565
+ };
566
+ const addPhotoFrame = (fx, fz, rotY) => {
567
+ const pf = new THREE.Group(); pf.position.set(fx, 0.845, fz); pf.rotation.set(-0.18, rotY, 0); g.add(pf);
568
+ addSwap(swaps, pf, G.photoFrame, M.frameWood, M.frameWoodDark, 0, 0, 0);
569
+ addSwap(swaps, pf, G.photoInner, M.photoCard, M.photoCardDark, 0, 0, 0.011);
570
+ };
571
+ const addBooksStack = (bx, bz, count, seed) => {
572
+ for (let i = 0; i < count; i++) {
573
+ const col = BOOK_PALETTE[(seed + i) % BOOK_PALETTE.length];
574
+ const bk = addSwap(swaps, g, G.book, mat(col, 's', { roughness: 0.82 }), mat(darken(col, 0.38), 's', { roughness: 0.9 }), bx, 0.782 + i * 0.029, bz);
575
+ bk.rotation.y = (i - 1) * 0.11;
576
+ }
577
+ };
578
+
579
+ const dp1 = hash(s.id + 'dp1') % 5;
580
+ if (dp1 === 0) {
581
+ // Second angled side monitor
582
+ const m2 = new THREE.Group(); m2.position.set(-0.52, 0, -0.15); m2.rotation.y = 0.42; g.add(m2);
583
+ addSwap(swaps, m2, G.standBaseSmall, M.leg, M.legDark, 0, 0.774, 0);
584
+ addSwap(swaps, m2, G.standSmall, M.leg, M.legDark, 0, 0.855, -0.01);
585
+ addSwap(swaps, m2, G.monitorSmall, M.leg, M.legDark, 0, 1.03, 0);
586
+ screens.push(add(m2, G.screenSmall, M.screenOff, 0, 1.03, 0.016));
587
+ } else if (dp1 === 1) {
588
+ // Desk lamp
589
+ const lp = new THREE.Group(); lp.position.set(-0.54, 0.768, -0.20); g.add(lp);
590
+ addSwap(swaps, lp, G.lampBase, M.lampShade, M.lampShadeDark, 0, 0.01, 0);
591
+ const a1 = addSwap(swaps, lp, G.lampArm, M.chairMetal, M.chairMetalDark, -0.01, 0.13, -0.01); a1.rotation.z = 0.14;
592
+ const a2 = addSwap(swaps, lp, G.lampArm, M.chairMetal, M.chairMetalDark, 0.03, 0.27, 0.02, 0.85, 0.7, 0.85); a2.rotation.set(0.32, 0, -0.45);
593
+ const sh = addSwap(swaps, lp, G.lampShade, M.lampShade, M.lampShadeDark, 0.08, 0.30, 0.05); sh.rotation.set(0.25, 0, -0.35);
594
+ lampBulb = add(lp, G.lampBulb, M.lampGlow, 0.09, 0.26, 0.06); lampBulb.rotation.set(Math.PI / 2 + 0.25, 0, -0.35);
595
+ } else if (dp1 === 2) {
596
+ addDeskPlant(-0.54, -0.20);
597
+ } else if (dp1 === 3) {
598
+ addPhotoFrame(-0.52, -0.20, 0.35);
599
+ } else {
600
+ addBooksStack(-0.52, -0.17, 3, hash(s.id + 'bk'));
601
+ }
602
+
603
+ const dp2 = hash(s.id + 'dp2') % 5;
604
+ if (dp2 === 0) {
605
+ addDeskMug(0.55, -0.10);
606
+ } else if (dp2 === 1) {
607
+ addDeskMug(0.55, -0.12);
608
+ const nb = addSwap(swaps, g, G.notebook, M.notebook, M.notebookDark, -0.49, 0.776, 0.15); nb.rotation.y = 0.12;
609
+ } else if (dp2 === 2) {
610
+ addDeskPlant(0.55, -0.18);
611
+ const nb = addSwap(swaps, g, G.notebook, M.notebook, M.notebookDark, -0.49, 0.776, 0.15); nb.rotation.y = -0.10;
612
+ } else if (dp2 === 3) {
613
+ addPhotoFrame(0.54, -0.20, -0.38);
614
+ addDeskMug(0.56, 0.05);
615
+ } else {
616
+ addBooksStack(-0.50, 0.14, 2, hash(s.id + 'bk2'));
617
+ addDeskMug(0.55, -0.10);
618
+ }
619
+
620
+ // Swivel chair with deterministic colour variety
621
+ const chairCol = CHAIR_PALETTE[hash(s.id + 'ch') % CHAIR_PALETTE.length];
622
+ addSwivelChair(g, swaps, 0, 0.50, 0, mat(chairCol, 's', { roughness: 0.82 }), mat(darken(chairCol, 0.42), 's', { roughness: 0.9 }));
623
+
624
+ // Floor indicators (alarm pulse, focus halo, hover halo)
625
+ const ring = add(g, G.ring, M.ring, 0, 0.014, 0.30); ring.rotation.x = -Math.PI / 2; ring.visible = false;
626
+ const focusRing = add(g, G.focusRing, M.focusRing, 0, 0.016, 0.30); focusRing.rotation.x = -Math.PI / 2; focusRing.visible = false;
627
+ const hoverRing = add(g, G.focusRing, M.hoverRing, 0, 0.015, 0.30); hoverRing.rotation.x = -Math.PI / 2; hoverRing.visible = false;
628
+
629
+ // Stylised seated worker (local origin at chair center, faces -Z)
630
+ const oc = outfitColors(s.id, s.vendor);
631
+ const accRoll = hash(s.id + 'ac') % 6;
632
+ const bodyType = BODY_TYPES[hash(s.id + 'bt') % BODY_TYPES.length];
633
+ const worker = buildPerson({
634
+ skin: SKIN[hash(s.id + 'sk') % SKIN.length],
635
+ hair: HAIR[hash(s.id + 'hr') % HAIR.length],
636
+ top: oc.top, sleeve: oc.sleeve, accent: oc.accent, pants: oc.pants, shoe: oc.shoe,
637
+ outfitStyle: oc.style,
638
+ hairStyle: hash(s.id + 'hs') % 7,
639
+ hasGlasses: accRoll === 0 || accRoll === 3,
640
+ hasHeadset: accRoll === 1,
641
+ bodyType,
642
+ rolled: (hash(s.id + 'sl') % 2) === 0,
643
+ });
644
+ worker.person.position.set(0, 0, 0.47);
645
+ g.add(worker.person);
646
+
647
+ const badgeY = 1.58 + (worker.bodySy - 1) * 0.5;
648
+ const badge = new THREE.Sprite(SP.alert); badge.scale.set(0.42, 0.42, 1); badge.position.set(0, badgeY, 0); badge.visible = false; worker.person.add(badge);
649
+ const initPose = { ...(POSES[s.state] || POSES.idle) };
650
+
651
+ const d = {
652
+ id: s.id, group: g, person: worker.person, spine: worker.spine, head: worker.head, armL: worker.armL, armR: worker.armR,
653
+ screens, lampBulb, ring, focusRing, hoverRing, badge, badgeY,
654
+ topTargets: worker.topTargets, sleeveTargets: worker.sleeveTargets, swaps,
655
+ pose: initPose, phase: (hash(s.id) % 628) / 100, state: '', vendor: s.vendor, roomKey: null, dark: false, s,
656
+ };
657
+ g.traverse((o) => { o.userData.deskId = s.id; });
658
+ applyPose(d, initPose);
659
+ applyState(d, s);
660
+ return d;
661
+ }
662
+
663
+ function applyPose(d, p) {
664
+ d.spine.rotation.set(p.spineX, 0, p.spineZ);
665
+ d.head.rotation.set(p.headX, p.headY, p.headZ);
666
+ d.armL.arm.rotation.set(p.lArmX, 0, p.lArmZ);
667
+ d.armL.elbow.rotation.set(p.lElbX, 0, p.lElbZ);
668
+ d.armR.arm.rotation.set(p.rArmX, 0, p.rArmZ);
669
+ d.armR.elbow.rotation.set(p.rElbX, 0, p.rElbZ);
670
+ }
671
+
672
+ function applyDeskScreen(d) {
673
+ const st = d.state;
674
+ const sm = d.dark ? M.screenOff
675
+ : (st === 'working' || st === 'idle' ? (codeTex[d.vendor] || codeTex.other).mat : st === 'stalled' || st === 'failed' ? M.screenAlarm : M.screenOff);
676
+ for (let i = 0; i < d.screens.length; i++) d.screens[i].material = sm;
677
+ if (d.lampBulb) d.lampBulb.material = d.dark ? M.screenOff : M.lampGlow;
678
+ if (d.dark) {
679
+ d.ring.visible = false;
680
+ d.badge.visible = false;
681
+ } else {
682
+ d.ring.visible = st === 'stalled' || st === 'failed';
683
+ d.badge.visible = st === 'stalled' || st === 'failed' || st === 'idle';
684
+ }
685
+ }
686
+
687
+ function setDeskDark(d, dark) {
688
+ d.dark = dark;
689
+ for (let i = 0; i < d.swaps.length; i++) {
690
+ const sw = d.swaps[i];
691
+ sw[0].material = dark ? sw[2] : sw[1];
692
+ }
693
+ applyDeskScreen(d);
694
+ }
695
+
696
+ function applyState(d, s) {
697
+ d.s = s;
698
+ let vendorChanged = false;
699
+ if (d.vendor !== s.vendor) {
700
+ d.vendor = s.vendor;
701
+ vendorChanged = true;
702
+ const oc = outfitColors(s.id, s.vendor);
703
+ const topM = mat(oc.top, 's', { roughness: 0.80 });
704
+ const slvM = mat(oc.sleeve, 's', { roughness: 0.80 });
705
+ for (const mesh of d.topTargets) mesh.material = topM;
706
+ for (const mesh of d.sleeveTargets) mesh.material = slvM;
707
+ }
708
+ if (d.state === s.state) {
709
+ if (vendorChanged) applyDeskScreen(d);
710
+ return;
711
+ }
712
+ d.state = s.state;
713
+ const st = s.state;
714
+ d.person.visible = st !== 'done';
715
+ d.badge.material = st === 'failed' ? SP.alert : st === 'stalled' ? SP.warn : SP.zz;
716
+ d.badge.scale.setScalar(st === 'idle' ? 0.34 : 0.42);
717
+ applyDeskScreen(d);
718
+ }
719
+
720
+ // ---------------------------------------------------------------- lobby receptionist, waiting guest & empty state
721
+ function buildLobby(LOBBY, length) {
722
+ const corr = add(building, G.plane, M.corridor, length / 2, 0.003, 0, length, CORRIDOR, 1); corr.rotation.x = -Math.PI / 2;
723
+ const lob = add(building, G.plane, M.lobby, LOBBY / 2, 0.004, 0, LOBBY, 9, 1); lob.rotation.x = -Math.PI / 2;
724
+ // Reception counter & lobby wall
725
+ add(building, G.box, M.desk, 2.4, 0.43, 0, 0.82, 0.86, 2.6);
726
+ add(building, G.box, M.leg, 2.81, 0.06, 0, 0.02, 0.12, 2.6);
727
+ add(building, G.box, M.wall, 0.3, WALL_H / 2, 0, 0.2, WALL_H, 9);
728
+ const sign = canvasTex(512, 96, (g, w) => { g.fillStyle = '#1d2127'; g.fillRect(0, 0, w, 96); g.fillStyle = '#ece8e0'; g.font = '600 52px "Segoe UI", sans-serif'; g.fillText('Agent Office', 22, 66); g.fillStyle = '#4fc08d'; g.fillRect(w - 46, 38, 18, 18); }, false);
729
+ const sg = new THREE.Mesh(G.plane, new THREE.MeshBasicMaterial({ map: sign })); sg.userData.own = true; sg.scale.set(3.2, 0.6, 1); sg.position.set(0.42, 0.95, 0); sg.rotation.y = Math.PI / 2; building.add(sg);
730
+ plant(building, 1.0, 3.6); plant(building, 1.0, -3.6); plant(building, length - 0.6, 0.9);
731
+
732
+ // Counter props: small monitor, brass desk bell, mini plant, mug & book (non-interactive)
733
+ const counterProps = new THREE.Group(); building.add(counterProps);
734
+ const recMon = new THREE.Group(); recMon.position.set(2.24, 0.86, -0.44); recMon.rotation.y = -Math.PI / 2 + 0.54; counterProps.add(recMon);
735
+ add(recMon, G.standBaseSmall, M.leg, 0, 0.008, 0);
736
+ add(recMon, G.standSmall, M.leg, 0, 0.088, -0.01);
737
+ add(recMon, G.monitorSmall, M.leg, 0, 0.255, 0);
738
+ const recScreen = add(recMon, G.screenSmall, M.recScreen, 0, 0.255, 0.016);
739
+ // Desk bell on visitor side of counter
740
+ add(counterProps, G.bellBase, M.leg, 2.64, 0.868, 0.34);
741
+ add(counterProps, G.bellDome, M.bellBrass, 2.64, 0.875, 0.34);
742
+ add(counterProps, G.bellBtn, M.bellBrass, 2.64, 0.935, 0.34);
743
+ // Small plant on counter
744
+ add(counterProps, G.miniPot, M.miniPot, 2.56, 0.902, -0.98);
745
+ add(counterProps, G.miniLeaves, M.leaves, 2.56, 0.982, -0.98);
746
+ // Mug on counter (shown while active; hidden while receptionist holds it during empty state)
747
+ const counterMug = new THREE.Group(); counterMug.position.set(2.20, 0.86, 0.42); counterProps.add(counterMug);
748
+ add(counterMug, G.mug, M.mug, 0, 0.048, 0);
749
+ const cmh = add(counterMug, G.mugHandle, M.mug, 0.042, 0.048, 0); cmh.rotation.z = -Math.PI / 2;
750
+ // Open book on counter (shown while empty / reading)
751
+ const counterBook = new THREE.Group(); counterBook.position.set(2.14, 0.872, 0.04); counterBook.rotation.y = Math.PI / 2; counterProps.add(counterBook);
752
+ const pL = add(counterBook, G.notebook, M.notebook, -0.09, 0.004, 0, 0.9, 0.8, 0.9); pL.rotation.z = 0.08;
753
+ const pR = add(counterBook, G.notebook, M.notebook, 0.09, 0.004, 0, 0.9, 0.8, 0.9); pR.rotation.z = -0.08;
754
+ counterBook.visible = false;
755
+ counterProps.traverse((o) => { o.userData.noHit = true; });
756
+
757
+ // Receptionist chair & seated character behind counter (neutral colours, not an agent, not clickable)
758
+ const recChair = addSwivelChair(building, null, 1.46, 0, -Math.PI / 2, M.chair, M.chairDark);
759
+ recChair.traverse((o) => { o.userData.noHit = true; });
760
+ const rec = buildPerson({
761
+ skin: SKIN[1], hair: HAIR[0], top: 0x4b535e, sleeve: 0x4b535e, accent: 0xeae4d8, pants: 0x2c323b, shoe: 0x22252b,
762
+ outfitStyle: 0, hairStyle: 4, hasGlasses: true, hasHeadset: false, bodyType: BODY_TYPES[0], rolled: false,
763
+ });
764
+ rec.person.position.set(1.50, 0, 0);
765
+ rec.person.rotation.y = -Math.PI / 2;
766
+ // Hand-held coffee mug attached to right hand for the empty-office coffee break
767
+ const handMug = new THREE.Group(); handMug.position.set(0, -0.055, -0.035); handMug.rotation.x = Math.PI / 2; rec.armR.hand.add(handMug);
768
+ add(handMug, G.mug, M.mug, 0, 0, 0, 0.9, 0.9, 0.9);
769
+ const hmh = add(handMug, G.mugHandle, M.mug, 0.038, 0, 0, 0.9, 0.9, 0.9); hmh.rotation.z = -Math.PI / 2;
770
+ handMug.visible = false;
771
+ rec.person.traverse((o) => { o.userData.noHit = true; });
772
+ building.add(rec.person);
773
+
774
+ // Lobby sofa & waiting visitor (sitting, idle, not an agent, not clickable)
775
+ add(building, G.box, M.chair, 4.6, 0.25, 3.4, 2.0, 0.5, 0.8);
776
+ add(building, G.box, M.chair, 4.6, 0.6, 3.75, 2.0, 0.6, 0.15);
777
+ const visitor = buildPerson({
778
+ skin: SKIN[2], hair: HAIR[1], top: 0x67655e, sleeve: 0x585650, accent: 0xe3dcd0, pants: 0x353b45, shoe: 0x4e392a,
779
+ outfitStyle: 1, hairStyle: 0, hasGlasses: false, hasHeadset: false, bodyType: BODY_TYPES[2], rolled: true,
780
+ });
781
+ visitor.person.position.set(4.25, 0, 3.35);
782
+ visitor.person.rotation.y = 0.08;
783
+ visitor.person.traverse((o) => { o.userData.noHit = true; });
784
+ building.add(visitor.person);
785
+
786
+ applyPose(rec, isEmpty ? REC_EMPTY_POSE : REC_ACTIVE_POSE);
787
+ applyPose(visitor, VISITOR_POSE);
788
+ lobbyActors = { rec, recScreen, handMug, counterMug, counterBook, visitor };
789
+ syncLobbyEmpty();
790
+ }
791
+
792
+ function syncLobbyEmpty() {
793
+ if (!lobbyActors) return;
794
+ lobbyActors.handMug.visible = isEmpty;
795
+ lobbyActors.counterMug.visible = !isEmpty;
796
+ lobbyActors.counterBook.visible = isEmpty;
797
+ lobbyActors.recScreen.material = isEmpty ? M.recScreenDim : M.recScreen;
798
+ applyPose(lobbyActors.rec, isEmpty ? REC_EMPTY_POSE : REC_ACTIVE_POSE);
799
+ }
800
+
801
+ function setEmptyState(quiet) {
802
+ isEmpty = quiet;
803
+ $('.st-empty').hidden = !quiet;
804
+ syncLobbyEmpty();
805
+ }
806
+
807
+ // ---------------------------------------------------------------- who gets a desk, and the floor plan
808
+ function pick(state) {
809
+ const now = api.now();
810
+ return state.sessions.filter((s) => s.state === 'working' || s.state === 'idle' || s.state === 'stalled' || now - s.last < RECENT)
811
+ .sort((a, b) => a.started - b.started).slice(0, MAX_PEOPLE);
812
+ }
813
+ function clearBuilding() {
814
+ for (const d of desks.values()) if (d.group.parent) d.group.parent.remove(d.group);
815
+ for (const o of [...building.children]) {
816
+ building.remove(o);
817
+ o.traverse((c) => {
818
+ if (c.userData.ownGeo && c.geometry) c.geometry.dispose();
819
+ if (c.userData.own && c.material) { if (c.material.map) c.material.map.dispose(); c.material.dispose(); }
820
+ });
821
+ }
822
+ $('.st-signs').innerHTML = '';
823
+ rooms = [];
824
+ lobbyActors = null;
825
+ }
826
+ let hasFitted = false;
827
+ function layout(list, state) {
828
+ const firstLayout = !hasFitted;
829
+ hasFitted = true;
830
+ clearBuilding();
831
+ const byWs = new Map();
832
+ for (const s of list) { const k = s.workspace || '~'; if (!byWs.has(k)) byWs.set(k, []); byWs.get(k).push(s); }
833
+ const order = [...byWs.entries()].sort((a, b) => score(b[1]) - score(a[1]) || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
834
+ const plans = order.map(([key, arr], i) => {
835
+ const floorPlan = planOffice(arr);
836
+ const ws = state.workspaces.find((x) => x.id === key);
837
+ return {
838
+ idx: i, key, arr, placements: floorPlan.placements, w: floorPlan.w, d: floorPlan.d,
839
+ name: key === '~' ? '?' : (ws ? ws.name : key),
840
+ carpet: CARPET[i % CARPET.length],
841
+ branches: ws ? ws.branches.filter((b) => b !== 'HEAD') : [],
842
+ };
843
+ });
844
+ // lobby at the west end, offices on both sides of the corridor, filling whichever side is shorter
845
+ const LOBBY = 6.5;
846
+ let xN = LOBBY, xS = LOBBY;
847
+ for (const pl of plans) {
848
+ const north = xN <= xS;
849
+ pl.side = north ? -1 : 1; pl.x0 = north ? xN : xS;
850
+ if (north) xN += pl.w + 0.3; else xS += pl.w + 0.3;
851
+ }
852
+ const length = Math.max(xN, xS, LOBBY + 8);
853
+ buildLobby(LOBBY, length);
854
+ for (const pl of plans) buildRoom(pl);
855
+ world.updateMatrixWorld(true);
856
+ if (firstLayout || focusMode === 'overview') fit(firstLayout);
857
+ else if (focusedRoomKey && !rooms.some((r) => r.key === focusedRoomKey && r.active)) focusOverview(false);
858
+ syncFocusVisuals();
859
+ }
860
+ function score(arr) { return arr.reduce((n, s) => n + (s.state === 'working' ? 3 : s.state === 'stalled' || s.state === 'failed' ? 2 : s.state === 'idle' ? 1 : 0), 0); }
861
+
862
+ function isRoomActive(room) {
863
+ return room.arr.some((s) => {
864
+ const live = (desks.get(s.id) || {}).s || s;
865
+ return ACTIVE_STATES.has(live.state);
866
+ });
867
+ }
868
+
869
+ function syncRoomActive(room) {
870
+ const active = isRoomActive(room);
871
+ if (room.active === active) return false;
872
+ room.active = active;
873
+ room.floor.material = active ? mat(room.carpet, 's', { roughness: 0.94 }) : mat(darken(room.carpet, 0.34), 's', { roughness: 0.96 });
874
+ for (let i = 0; i < room.swaps.length; i++) {
875
+ const sw = room.swaps[i];
876
+ sw[0].material = active ? sw[1] : sw[2];
877
+ }
878
+ room.board.material.color.setHex(active ? 0xffffff : 0x4b515a);
879
+ room.glow.visible = active;
880
+ for (const s of room.arr) {
881
+ const d = desks.get(s.id);
882
+ if (d) setDeskDark(d, !active);
883
+ }
884
+ room.el.classList.toggle('dark', !active);
885
+ room.el.disabled = !active;
886
+ room.el.tabIndex = active ? 0 : -1;
887
+ if (!active) {
888
+ room.border.visible = false;
889
+ if (hoveredRoom === room) { hoveredRoom = null; tipEl.hidden = true; renderer.domElement.style.cursor = 'default'; }
890
+ if (hovered && hovered.roomKey === room.key) { hovered.hoverRing.visible = false; hovered = null; tipEl.hidden = true; renderer.domElement.style.cursor = 'default'; }
891
+ }
892
+ return true;
893
+ }
894
+
895
+ function buildRoom(pl) {
896
+ const g = new THREE.Group();
897
+ // local space: x across the room, z from the glass front (0) to the back wall (D). North offices are turned to face the corridor.
898
+ g.position.set(pl.x0 + (pl.side < 0 ? pl.w : 0), 0, pl.side * CORRIDOR / 2);
899
+ g.rotation.y = pl.side < 0 ? Math.PI : 0;
900
+ building.add(g);
901
+ const W = pl.w, D = pl.d;
902
+ const swaps = [];
903
+ const floor = add(g, G.plane, mat(pl.carpet, 's', { roughness: 0.94 }), W / 2, 0.006, D / 2, W, D, 1); floor.rotation.x = -Math.PI / 2;
904
+ addSwap(swaps, g, G.box, M.wall, M.wallDark, W / 2, WALL_H / 2, D, W, WALL_H, 0.12);
905
+ addSwap(swaps, g, G.box, M.wall, M.wallDark, 0, WALL_H / 2, D / 2, 0.12, WALL_H, D);
906
+ addSwap(swaps, g, G.box, M.wall, M.wallDark, W, WALL_H / 2, D / 2, 0.12, WALL_H, D);
907
+ const door = 1.3, seg = (W - door) / 2;
908
+ const gl1 = addSwap(swaps, g, G.box, M.glass, M.glassDark, seg / 2, WALL_H / 2, 0, seg, WALL_H, 0.05);
909
+ const gl2 = addSwap(swaps, g, G.box, M.glass, M.glassDark, W - seg / 2, WALL_H / 2, 0, seg, WALL_H, 0.05);
910
+ gl1.userData.isGlass = true; gl2.userData.isGlass = true;
911
+ addSwap(swaps, g, G.box, M.trim, M.trimDark, W / 2, WALL_H + 0.02, 0, W, 0.05, 0.08);
912
+ // Warm unlit ceiling light wash + wall-top light strips shown while the office is active
913
+ const glow = new THREE.Group();
914
+ const ceilWash = add(glow, G.plane, M.ceilGlow, W / 2, WALL_H + 0.01, D / 2, W - 0.16, D - 0.16, 1); ceilWash.rotation.x = -Math.PI / 2;
915
+ add(glow, G.box, M.lightStrip, W / 2, WALL_H - 0.04, D - 0.075, W - 0.16, 0.032, 0.025);
916
+ add(glow, G.box, M.lightStrip, 0.075, WALL_H - 0.04, D / 2, 0.025, 0.032, D - 0.16);
917
+ add(glow, G.box, M.lightStrip, W - 0.075, WALL_H - 0.04, D / 2, 0.025, 0.032, D - 0.16);
918
+ glow.traverse((o) => { o.userData.noHit = true; });
919
+ g.add(glow);
920
+ // Subtle architectural highlight border on the floor for hover / focus
921
+ const bPts = [new THREE.Vector3(0.08, 0.024, 0.08), new THREE.Vector3(W - 0.08, 0.024, 0.08), new THREE.Vector3(W - 0.08, 0.024, D - 0.08), new THREE.Vector3(0.08, 0.024, D - 0.08)];
922
+ const borderGeo = new THREE.BufferGeometry().setFromPoints(bPts);
923
+ const border = new THREE.LineLoop(borderGeo, M.roomFocus);
924
+ border.userData.ownGeo = true;
925
+ border.userData.noHit = true;
926
+ border.visible = false;
927
+ g.add(border);
928
+
929
+ // Distinct office props picked by office index, kept strictly inside walls and clear of desks & doors
930
+ const style = pl.idx % 5;
931
+ const sofaCol = SOFA_PALETTE[pl.idx % SOFA_PALETTE.length];
932
+ const stoolCol = CHAIR_PALETTE[pl.idx % CHAIR_PALETTE.length];
933
+ if (style === 0) {
934
+ plant(g, 0.50, D - 0.50, swaps);
935
+ plant(g, W - 0.50, 0.58, swaps);
936
+ addBookshelf(g, swaps, 0.22, D * 0.5, -Math.PI / 2, pl.idx);
937
+ } else if (style === 1) {
938
+ addSofaCorner(g, swaps, 0.95, 0.42, 0, sofaCol);
939
+ addWaterCooler(g, swaps, W - 0.48, D - 0.48, 0);
940
+ plant(g, 0.50, D - 0.50, swaps);
941
+ } else if (style === 2) {
942
+ addMeetingTable(g, swaps, W - 0.95, 0.60, stoolCol);
943
+ addBookshelf(g, swaps, W - 0.22, D * 0.5, Math.PI / 2, pl.idx + 2);
944
+ plant(g, 0.50, D - 0.50, swaps);
945
+ } else if (style === 3) {
946
+ addSofaCorner(g, swaps, W - 0.95, 0.42, 0, sofaCol);
947
+ addWaterCooler(g, swaps, 0.48, D - 0.48, 0);
948
+ plant(g, 0.50, 0.58, swaps);
949
+ } else {
950
+ addMeetingTable(g, swaps, 0.95, 0.60, stoolCol);
951
+ addBookshelf(g, swaps, W - 0.22, D * 0.5, Math.PI / 2, pl.idx + 1);
952
+ addWaterCooler(g, swaps, W - 0.48, D - 0.48, 0);
953
+ }
954
+
955
+ const board = whiteboard(g, W / 2, 0.9, D - 0.08, Math.PI, pl.name, pl.branches.length ? pl.branches : pl.arr.map((s) => s.label || s.name));
956
+ const place = (s, x, z, rotY) => {
957
+ const d0 = desks.get(s.id); if (!d0) return;
958
+ d0.group.position.set(x, 0, z); d0.group.rotation.y = rotY; d0.roomKey = pl.key;
959
+ g.add(d0.group);
960
+ };
961
+ // Open-plan rows of desk clusters (2-desk facing pods and 4-desk blocks), busy leads nearest the glass
962
+ for (const p of pl.placements) place(p.s, p.x, p.z, p.rotY);
963
+ // Tag every object in the office with roomKey so clicking anywhere in the office focuses it
964
+ g.traverse((o) => { o.userData.roomKey = pl.key; });
965
+
966
+ const el = document.createElement('button');
967
+ el.className = 'st-sign'; el.type = 'button';
968
+ $('.st-signs').appendChild(el);
969
+ g.updateMatrixWorld(true);
970
+ const doorWorld = g.localToWorld(new THREE.Vector3(W / 2, WALL_H + 0.35, 0));
971
+ const center = g.localToWorld(new THREE.Vector3(W / 2, 0, D / 2));
972
+ const room = {
973
+ key: pl.key, name: pl.name, group: g, el, door: doorWorld, center, w: W, d: D, side: pl.side, size: Math.max(W, D),
974
+ carpet: pl.carpet, floor, swaps, board, glow, border, active: null, arr: pl.arr,
975
+ };
976
+ el.onclick = () => { if (room.active) focusRoom(room.key); };
977
+ rooms.push(room);
978
+ syncRoomActive(room);
979
+ signText(room);
980
+ }
981
+ function signText(room) {
982
+ const arr = room.arr.map((s) => (desks.get(s.id) || {}).s || s);
983
+ const work = arr.filter((s) => s.state === 'working').length;
984
+ const stalled = arr.filter((s) => s.state === 'stalled').length;
985
+ const failed = arr.filter((s) => s.state === 'failed').length;
986
+ const bad = stalled + failed;
987
+ room.el.classList.toggle('alarm', !!room.active && bad > 0);
988
+ const h = '<b>' + esc(room.name) + '</b><span>' + (work ? '<i class="ok"></i>' + esc(api.t('room.working', { n: work })) : '') +
989
+ (stalled ? '<i class="bad"></i>' + esc(api.t('room.stalled', { n: stalled })) : '') +
990
+ (failed ? '<i class="bad"></i>' + esc(api.t('room.failed', { n: failed })) : '') +
991
+ (!work && !bad ? esc(arr.length === 1 ? api.t('room.agent') : api.t('room.agents', { n: arr.length })) : '') + '</span>';
992
+ if (room.el._h !== h) { room.el.innerHTML = h; room.el._h = h; }
993
+ }
994
+
995
+ // ---------------------------------------------------------------- links: arcs from a lead to each subagent
996
+ function buildLinks(list) {
997
+ for (const l of links) { arcs.remove(l.line); l.line.geometry.dispose(); if (l.packet) arcs.remove(l.packet); }
998
+ links = [];
999
+ for (const s of list) {
1000
+ if (!s.parent || !desks.has(s.parent) || !desks.has(s.id)) continue;
1001
+ const a = headPos(desks.get(s.parent)), b = headPos(desks.get(s.id));
1002
+ const mid = a.clone().lerp(b, 0.5); mid.y += 1.2 + a.distanceTo(b) * 0.2;
1003
+ const curve = new THREE.QuadraticBezierCurve3(a, mid, b);
1004
+ const geo = new THREE.BufferGeometry().setFromPoints(curve.getPoints(28));
1005
+ const color = s.state === 'stalled' ? STATE.stalled : s.state === 'failed' ? STATE.failed : s.state === 'working' ? 0x7fd6ad : 0x5a6470;
1006
+ const line = new THREE.Line(geo, lineMat(color, s.state === 'done' ? 0.25 : 0.8));
1007
+ arcs.add(line);
1008
+ let packet = null;
1009
+ if (s.state === 'working') { packet = new THREE.Mesh(G.packet, mat(VENDOR[s.vendor] || VENDOR.other, 'b')); arcs.add(packet); }
1010
+ links.push({ line, packet, curve, child: s.id, t: (hash(s.id) % 100) / 100 });
1011
+ }
1012
+ }
1013
+ function headPos(d) { return d.group.localToWorld(new THREE.Vector3(0, 1.48, 0.54)); }
1014
+
1015
+ // ---------------------------------------------------------------- update from the server state
1016
+ function update(state) {
1017
+ lastState = state;
1018
+ const list = pick(state);
1019
+ const ids = new Set(list.map((s) => s.id));
1020
+ for (const [id, d] of desks) if (!ids.has(id)) { if (d.group.parent) d.group.parent.remove(d.group); desks.delete(id); }
1021
+ for (const s of list) { let d = desks.get(s.id); if (!d) { d = makeDesk(s); desks.set(s.id, d); } applyState(d, s); }
1022
+ const key = list.map((s) => s.id + ':' + (s.workspace || '') + ':' + (s.parent || '')).join('|');
1023
+ if (key !== layoutKey) { layoutKey = key; layout(list, state); }
1024
+ world.updateMatrixWorld(true);
1025
+ let activeChanged = false;
1026
+ for (const r of rooms) if (syncRoomActive(r)) activeChanged = true;
1027
+ setEmptyState(!list.some((s) => ACTIVE_STATES.has(s.state)));
1028
+ buildLinks(list);
1029
+ for (const r of rooms) signText(r);
1030
+ if (selected && (!desks.has(selected) || desks.get(selected).dark)) closeCard(false);
1031
+ const focusedRoom = focusedRoomKey ? rooms.find((r) => r.key === focusedRoomKey) : null;
1032
+ if (focusedRoom && !focusedRoom.active) focusOverview(false);
1033
+ else if (activeChanged) syncFocusVisuals();
1034
+ renderPanel();
1035
+ renderFocusBar();
1036
+ toasts(list);
1037
+ if (selected && desks.has(selected) && !desks.get(selected).dark) renderCard();
1038
+ wake();
1039
+ }
1040
+
1041
+ // ---------------------------------------------------------------- side panel: everyone in the office, by room
1042
+ const rank = (st) => ({ stalled: 0, failed: 1, working: 2, idle: 3, done: 4 })[st];
1043
+ function renderPanel() {
1044
+ let h = '';
1045
+ for (const r of rooms) {
1046
+ const dark = !r.active;
1047
+ const cls = 'st-room' + (dark ? ' dark' : '') + (r.active && r.el.classList.contains('alarm') ? ' alarm' : '') + (r.active && focusedRoomKey === r.key ? ' focused' : '');
1048
+ h += '<div class="' + cls + '">' + (dark
1049
+ ? '<div class="st-rname">' + esc(r.name) + '</div>'
1050
+ : '<button class="st-rname" data-room="' + esc(r.key) + '">' + esc(r.name) + '</button>');
1051
+ const arr = r.arr.map((s) => desks.get(s.id) && desks.get(s.id).s).filter(Boolean).sort((a, b) => (rank(a.state) - rank(b.state)) || (a.started - b.started));
1052
+ for (const s of arr) {
1053
+ if (dark) {
1054
+ h += '<div class="st-agent ' + esc(s.state) + (s.parent ? ' sub' : '') + '">' +
1055
+ '<span class="dot ' + esc(s.state) + '"></span><span class="st-txt"><b>' + esc(s.label || s.name) + '</b><small>' + esc(s.last_action || s.task || '') + '</small></span></div>';
1056
+ } else {
1057
+ h += '<button class="st-agent ' + esc(s.state) + (selected === s.id ? ' sel' : '') + (s.parent ? ' sub' : '') + '" data-id="' + esc(s.id) + '">' +
1058
+ '<span class="dot ' + esc(s.state) + '"></span><span class="st-txt"><b>' + esc(s.label || s.name) + '</b><small>' + esc(s.last_action || s.task || '') + '</small></span></button>';
1059
+ }
1060
+ }
1061
+ h += '</div>';
1062
+ }
1063
+ const list$ = $('.st-list');
1064
+ if (list$._h !== h) { list$.innerHTML = h; list$._h = h; }
1065
+ }
1066
+ $('.st-list').addEventListener('click', (e) => {
1067
+ const a = e.target.closest('[data-id]'); if (a) { focusAgent(a.dataset.id); return; }
1068
+ const r = e.target.closest('[data-room]'); if (r) focusRoom(r.dataset.room);
1069
+ });
1070
+ $('.st-list').addEventListener('mouseover', (e) => {
1071
+ const a = e.target.closest('[data-id]');
1072
+ if (a) { const d = desks.get(a.dataset.id); setHover(d && !d.dark ? d : null, null); return; }
1073
+ const r = e.target.closest('[data-room]');
1074
+ const rm = r ? rooms.find((x) => x.key === r.dataset.room) : null;
1075
+ setHover(null, rm && rm.active ? rm : null);
1076
+ });
1077
+ $('.st-list').addEventListener('mouseleave', () => setHover(null, null));
1078
+
1079
+ // ---------------------------------------------------------------- focus bar & visuals
1080
+ function syncFocusVisuals() {
1081
+ const isFocused = focusMode !== 'overview';
1082
+ ui.classList.toggle('focused', isFocused);
1083
+ const barOv = $('.st-bar [data-act="overview"]');
1084
+ if (barOv) barOv.classList.toggle('st-ov-active', isFocused);
1085
+ for (const r of rooms) {
1086
+ const isF = !!r.active && r.key === focusedRoomKey;
1087
+ const isH = !!r.active && hoveredRoom === r && !isF;
1088
+ r.border.visible = isF || isH;
1089
+ r.border.material = isF ? M.roomFocus : M.roomHover;
1090
+ r.el.classList.toggle('focused', isF);
1091
+ r.el.classList.toggle('focus', isF);
1092
+ r.el.classList.toggle('dim', !!r.active && isFocused && !isF);
1093
+ }
1094
+ for (const d of desks.values()) {
1095
+ d.focusRing.visible = !d.dark && selected === d.id;
1096
+ d.hoverRing.visible = !d.dark && hovered === d && selected !== d.id;
1097
+ }
1098
+ renderFocusBar();
1099
+ renderPanel();
1100
+ wake();
1101
+ }
1102
+ function renderFocusBar() {
1103
+ const bar = $('.st-focus');
1104
+ if (focusMode === 'overview') { bar.hidden = true; return; }
1105
+ const room = rooms.find((r) => r.key === focusedRoomKey);
1106
+ const d = selected ? desks.get(selected) : null;
1107
+ const backBtn = $('.st-back');
1108
+ const backHtml = focusMode === 'agent' && room
1109
+ ? '← ' + esc(room.name) + ' <kbd>Esc</kbd>'
1110
+ : '← ' + esc(api.t('studio.overview')) + ' <kbd>Esc</kbd>';
1111
+ if (backBtn._h !== backHtml) { backBtn.innerHTML = backHtml; backBtn._h = backHtml; }
1112
+ let crumb = '';
1113
+ if (room) {
1114
+ crumb += '<button class="st-crumb-room" data-room="' + esc(room.key) + '">' + esc(room.name) + '</button>';
1115
+ }
1116
+ if (d) {
1117
+ crumb += (room ? '<span class="st-crumb-sep">›</span>' : '') + '<span class="st-crumb-agent">' + esc(d.s.label || d.s.name) + '</span>';
1118
+ }
1119
+ const cEl = $('.st-crumb');
1120
+ if (cEl._h !== crumb) { cEl.innerHTML = crumb; cEl._h = crumb; }
1121
+ bar.hidden = false;
1122
+ }
1123
+ $('.st-focus').addEventListener('click', (e) => {
1124
+ if (e.target.closest('[data-act="back"]')) { onEscape(); return; }
1125
+ const r = e.target.closest('[data-room]'); if (r) focusRoom(r.dataset.room);
1126
+ });
1127
+
1128
+ // ---------------------------------------------------------------- alerts
1129
+ function toasts(list) {
1130
+ let h = '';
1131
+ for (const s of list) {
1132
+ if (s.state !== 'stalled' && s.state !== 'failed') continue;
1133
+ const msg = s.state === 'failed' ? api.t('studio.failed', { n: s.label || s.name }) : api.t('studio.quiet', { n: s.label || s.name, d: api.dur(api.now() - s.last) });
1134
+ h += '<button class="st-toast ' + s.state + '" data-id="' + esc(s.id) + '">' + esc(msg) + '</button>';
1135
+ }
1136
+ const box = $('.st-toasts');
1137
+ if (box._h !== h) { box.innerHTML = h; box._h = h; }
1138
+ }
1139
+ $('.st-toasts').addEventListener('click', (e) => { const a = e.target.closest('[data-id]'); if (a) focusAgent(a.dataset.id); });
1140
+
1141
+ // ---------------------------------------------------------------- detail card with a live activity feed
1142
+ function roomTheta(room) { return room.side < 0 ? 0.24 : Math.PI - 0.24; }
1143
+ function panelOffset(radius, theta, cardOpen) {
1144
+ const cw = host.clientWidth || 1;
1145
+ const panelEl = $('.st-panel'), cardEl = $('.st-card');
1146
+ const leftPx = (panelEl && panelEl.offsetWidth ? panelEl.offsetWidth : 270) + 12;
1147
+ const rightPx = cardOpen ? ((cardEl && cardEl.offsetWidth ? cardEl.offsetWidth : 330) + 12) : 0;
1148
+ const shiftPx = (leftPx - rightPx) / 2;
1149
+ const vFov = THREE.MathUtils.degToRad(camera.fov);
1150
+ const visW = 2 * radius * Math.tan(vFov / 2) * camera.aspect;
1151
+ const shiftWorld = (shiftPx / cw) * visW;
1152
+ // Camera screen-right vector in XZ is (cos(theta), 0, -sin(theta)); shifting target opposite centres the subject in the free area
1153
+ return new THREE.Vector3(-Math.cos(theta) * shiftWorld, 0, Math.sin(theta) * shiftWorld);
1154
+ }
1155
+ function roomFraming(room, cardOpen) {
1156
+ const cw = host.clientWidth || 1, ch = host.clientHeight || 1;
1157
+ const panelEl = $('.st-panel'), cardEl = $('.st-card');
1158
+ const leftPx = (panelEl && panelEl.offsetWidth ? panelEl.offsetWidth : 270) + 12;
1159
+ const rightPx = cardOpen ? ((cardEl && cardEl.offsetWidth ? cardEl.offsetWidth : 330) + 12) : 0;
1160
+ const freeWFrac = Math.max(0.35, (cw - leftPx - rightPx) / cw);
1161
+ const freeHFrac = Math.max(0.5, (ch - 60) / ch);
1162
+ const theta = roomTheta(room), phi = 0.9;
1163
+ const cosT = Math.abs(Math.cos(theta)), sinT = Math.abs(Math.sin(theta));
1164
+ const spanW = room.w * cosT + room.d * sinT;
1165
+ const projD = room.d * cosT + room.w * sinT;
1166
+ const spanH = projD * Math.cos(phi) + 1.6 * Math.sin(phi);
1167
+ const tanHalf = Math.tan(THREE.MathUtils.degToRad(camera.fov) / 2);
1168
+ const fill = 1.0; // the span estimate is conservative (near edges look larger), so 1.0 fills about 80% of the free area
1169
+ const rH = spanH / (2 * tanHalf * fill * freeHFrac);
1170
+ const rW = spanW / (2 * tanHalf * camera.aspect * fill * freeWFrac);
1171
+ const radius = Math.max(8.5, Math.min(60, Math.max(rH, rW)));
1172
+ const target = room.center.clone().add(panelOffset(radius, theta, cardOpen));
1173
+ target.y = 0.45;
1174
+ return { target, radius, theta, phi };
1175
+ }
1176
+ function focusAgent(id) {
1177
+ const d = desks.get(id);
1178
+ if (!d) { closeCard(false); return; }
1179
+ if (d.dark) return;
1180
+ const prevRoomKey = focusedRoomKey;
1181
+ const prevSelected = selected;
1182
+ selected = id;
1183
+ if (prevSelected !== id) {
1184
+ resetCardExpand();
1185
+ const card = $('.st-card');
1186
+ if (card) card.scrollTop = 0;
1187
+ }
1188
+ focusMode = 'agent';
1189
+ focusedRoomKey = d.roomKey;
1190
+ stopOrbit();
1191
+ const room = rooms.find((r) => r.key === d.roomKey);
1192
+ const deskBase = d.group.localToWorld(new THREE.Vector3(0, 0.90, 0.16));
1193
+ const candA = d.group.localToWorld(new THREE.Vector3(2.8, 0, -1.05));
1194
+ const candB = d.group.localToWorld(new THREE.Vector3(-2.8, 0, -1.05));
1195
+ const pickPos = room && candB.distanceToSquared(room.center) < candA.distanceToSquared(room.center) ? candB : candA;
1196
+ const theta = Math.atan2(pickPos.x - deskBase.x, pickPos.z - deskBase.z);
1197
+ const deskR = 4.2;
1198
+ const deskTarget = deskBase.clone().add(panelOffset(deskR, theta, true));
1199
+ feedFor = null; renderCard(); loadFeed(); syncFocusVisuals();
1200
+ const flyDesk = () => flyTo(deskTarget, deskR, theta, 0.96, 12, 36, 520);
1201
+ if (room && prevRoomKey !== room.key) {
1202
+ const f = roomFraming(room, true);
1203
+ flyTo(f.target, f.radius, f.theta, f.phi, f.radius * 1.6, f.radius * 4.0, 480, flyDesk);
1204
+ } else {
1205
+ flyDesk();
1206
+ }
1207
+ }
1208
+ function focusRoom(roomKey) {
1209
+ const room = rooms.find((r) => r.key === roomKey);
1210
+ if (!room || !room.active) return;
1211
+ selected = null;
1212
+ resetCardExpand();
1213
+ $('.st-card').hidden = true;
1214
+ clearTimeout(feedTimer);
1215
+ focusMode = 'room';
1216
+ focusedRoomKey = room.key;
1217
+ stopOrbit();
1218
+ const f = roomFraming(room, false);
1219
+ flyTo(f.target, f.radius, f.theta, f.phi, f.radius * 1.6, f.radius * 4.0);
1220
+ syncFocusVisuals();
1221
+ }
1222
+ function focusOverview(instant) {
1223
+ selected = null;
1224
+ resetCardExpand();
1225
+ $('.st-card').hidden = true;
1226
+ clearTimeout(feedTimer);
1227
+ focusMode = 'overview';
1228
+ focusedRoomKey = null;
1229
+ stopOrbit();
1230
+ fit(instant);
1231
+ syncFocusVisuals();
1232
+ }
1233
+ function closeCard(pullBackToRoom = true) {
1234
+ selected = null;
1235
+ resetCardExpand();
1236
+ $('.st-card').hidden = true;
1237
+ clearTimeout(feedTimer);
1238
+ const room = focusedRoomKey ? rooms.find((r) => r.key === focusedRoomKey && r.active) : null;
1239
+ if (pullBackToRoom && focusMode === 'agent') {
1240
+ if (room) focusRoom(room.key);
1241
+ else focusOverview(false);
1242
+ } else {
1243
+ if (focusMode === 'agent') focusMode = room ? 'room' : 'overview';
1244
+ syncFocusVisuals();
1245
+ }
1246
+ }
1247
+ function stopOrbit() {
1248
+ if (!autoOrbit) return;
1249
+ autoOrbit = false;
1250
+ const b = $('[data-act="orbit"]');
1251
+ if (b) b.setAttribute('aria-pressed', 'false');
1252
+ }
1253
+ async function loadFeed() {
1254
+ clearTimeout(feedTimer);
1255
+ const id = selected; if (!id) return;
1256
+ if (!document.hidden) {
1257
+ try { const r = await fetch('api/trace/' + encodeURIComponent(id) + '?limit=12', { cache: 'no-store' }); if (r.ok && selected === id) { feed = await r.json(); feedFor = id; renderCard(); } } catch (e) { /* keep the last feed */ }
1258
+ }
1259
+ feedTimer = setTimeout(loadFeed, 4000);
1260
+ }
1261
+ function toggleFeedRow(key) {
1262
+ if (!key) return;
1263
+ if (expandedFeed.has(key)) expandedFeed.delete(key);
1264
+ else expandedFeed.add(key);
1265
+ renderCard();
1266
+ }
1267
+ function renderCard() {
1268
+ const d = desks.get(selected); if (!d) return;
1269
+ const s = d.s, card = $('.st-card');
1270
+ const parent = s.parent && desks.get(s.parent) ? desks.get(s.parent).s : null;
1271
+ const kids = lastState ? lastState.sessions.filter((x) => x.parent === s.id) : [];
1272
+ const hasFeed = feedFor === s.id && feed;
1273
+ let rows;
1274
+ if (hasFeed) {
1275
+ if (feed.rows.length) {
1276
+ const seenKeys = new Map();
1277
+ const items = feed.rows.slice(-10).map((r) => {
1278
+ const base = feedRowKey(r);
1279
+ const n = seenKeys.get(base) || 0;
1280
+ seenKeys.set(base, n + 1);
1281
+ return { r, key: n ? base + '#' + n : base };
1282
+ }).reverse();
1283
+ rows = items.map(({ r, key }) => {
1284
+ const open = expandedFeed.has(key);
1285
+ const label = r.kind === 'in' ? api.t('row.prompt') : (r.tool || '');
1286
+ const preview = r.arg || r.text || r.res || '';
1287
+ const cls = 'st-feed-row ' + esc(r.err ? 'err' : r.kind) + (open ? ' open' : '');
1288
+ let inner = CHEV + '<b>' + esc(label) + '</b>';
1289
+ if (open) {
1290
+ const parts = [];
1291
+ if (r.arg) parts.push('<div class="st-feed-arg' + (isCmdTool(r.tool) ? ' st-feed-cmd' : '') + '">' + esc(r.arg) + '</div>');
1292
+ if (r.text) parts.push('<div class="st-feed-text">' + esc(r.text) + '</div>');
1293
+ if (r.res) parts.push('<div class="st-feed-res">' + esc(r.res) + '</div>');
1294
+ if (parts.length) inner += '<div class="st-feed-body">' + parts.join('') + '</div>';
1295
+ } else {
1296
+ inner += '<span class="st-feed-preview">' + esc(preview) + '</span>';
1297
+ }
1298
+ return '<li class="' + cls + '" role="button" tabindex="0" aria-expanded="' + open + '" data-row-key="' + esc(key) + '">' + inner + '</li>';
1299
+ }).join('');
1300
+ } else {
1301
+ rows = '<li class="st-feed-empty"><span>' + esc(api.t('insp.noRows')) + '</span></li>';
1302
+ }
1303
+ } else {
1304
+ rows = '<li class="st-feed-empty"><span>' + esc(api.t('insp.loading')) + '</span></li>';
1305
+ }
1306
+ const taskText = (taskExpanded && hasFeed && feed.task_full) ? feed.task_full : s.task;
1307
+ const h = '<header><span class="dot ' + esc(s.state) + '"></span><h3>' + esc(s.label || s.name) + '</h3><button class="btn small" data-close>' + esc(api.t('studio.close')) + '</button></header>' +
1308
+ '<p class="st-state ' + esc(s.state) + '">' + esc(api.t('state.' + s.state) + (s.state_why ? ': ' + s.state_why : '')) + '</p>' +
1309
+ (taskText ? '<p class="st-task' + (taskExpanded ? ' open' : '') + '" role="button" tabindex="0" aria-expanded="' + taskExpanded + '" data-toggle-task>' + CHEV + '<span class="st-task-txt">' + esc(taskText) + '</span></p>' : '') +
1310
+ '<dl><div><dt>' + esc(api.t('insp.tool')) + '</dt><dd>' + esc(s.tool) + '</dd></div><div><dt>' + esc(api.t('insp.model')) + '</dt><dd>' + esc(api.modelName(s.model)) + '</dd></div>' +
1311
+ (s.user ? '<div><dt>' + esc(api.t('insp.user')) + '</dt><dd>' + esc(s.user) + '</dd></div>' : '') +
1312
+ (parent ? '<div><dt>' + esc(api.t('insp.parent')) + '</dt><dd><a href="#" data-goto="' + esc(parent.id) + '">' + esc(parent.label || parent.name) + '</a></dd></div>' : '') +
1313
+ (kids.length ? '<div><dt>' + esc(api.t('insp.children')) + '</dt><dd>' + kids.length + '</dd></div>' : '') +
1314
+ '<div><dt>' + esc(api.t('insp.tokens')) + '</dt><dd>' + esc(api.num(s.tokens.in + s.tokens.cache + s.tokens.out)) + '</dd></div></dl>' +
1315
+ '<h4>' + esc(api.t('studio.feed')) + '</h4><ul class="st-feed">' + rows + '</ul>' +
1316
+ '<button class="btn" data-open="' + esc(s.id) + '">' + esc(api.t('studio.open')) + '</button>';
1317
+ if (card._h !== h) {
1318
+ const active = card.contains(document.activeElement) ? document.activeElement : null;
1319
+ const focusKind = !active ? null
1320
+ : active.dataset && active.dataset.rowKey != null ? { type: 'row', key: active.dataset.rowKey }
1321
+ : active.hasAttribute('data-toggle-task') ? { type: 'task' }
1322
+ : active.hasAttribute('data-close') ? { type: 'sel', sel: '[data-close]' }
1323
+ : active.hasAttribute('data-open') ? { type: 'sel', sel: '[data-open]' }
1324
+ : active.hasAttribute('data-goto') ? { type: 'sel', sel: '[data-goto]' }
1325
+ : null;
1326
+ const prevScroll = card.scrollTop;
1327
+ card.innerHTML = h;
1328
+ card._h = h;
1329
+ card.scrollTop = prevScroll;
1330
+ if (focusKind) {
1331
+ let target = null;
1332
+ if (focusKind.type === 'row') {
1333
+ for (const node of card.querySelectorAll('[data-row-key]')) {
1334
+ if (node.dataset.rowKey === focusKind.key) { target = node; break; }
1335
+ }
1336
+ } else if (focusKind.type === 'task') {
1337
+ target = card.querySelector('[data-toggle-task]');
1338
+ } else if (focusKind.type === 'sel') {
1339
+ target = card.querySelector(focusKind.sel);
1340
+ }
1341
+ if (target) target.focus({ preventScroll: true });
1342
+ }
1343
+ }
1344
+ card.hidden = false;
1345
+ }
1346
+ $('.st-card').addEventListener('click', (e) => {
1347
+ if (e.target.closest('[data-close]')) { closeCard(true); return; }
1348
+ const o = e.target.closest('[data-open]'); if (o) { api.onOpen(o.dataset.open); return; }
1349
+ const g = e.target.closest('[data-goto]'); if (g) { e.preventDefault(); focusAgent(g.dataset.goto); return; }
1350
+ if (window.getSelection && !window.getSelection().isCollapsed) return;
1351
+ const tEl = e.target.closest('[data-toggle-task]');
1352
+ if (tEl) { taskExpanded = !taskExpanded; renderCard(); return; }
1353
+ const rEl = e.target.closest('[data-row-key]');
1354
+ if (rEl) toggleFeedRow(rEl.dataset.rowKey);
1355
+ });
1356
+ $('.st-card').addEventListener('keydown', (e) => {
1357
+ if (e.key !== 'Enter' && e.key !== ' ') return;
1358
+ const tEl = e.target.closest('[data-toggle-task]');
1359
+ if (tEl) { e.preventDefault(); taskExpanded = !taskExpanded; renderCard(); return; }
1360
+ const rEl = e.target.closest('[data-row-key]');
1361
+ if (rEl) { e.preventDefault(); toggleFeedRow(rEl.dataset.rowKey); }
1362
+ });
1363
+
1364
+ // ---------------------------------------------------------------- camera
1365
+ const orbit = { theta: 0.48, phi: 0.88, radius: 30, target: new THREE.Vector3() };
1366
+ let fly = null;
1367
+ function fit(instant) {
1368
+ const box = new THREE.Box3().setFromObject(building);
1369
+ if (box.isEmpty()) box.set(new THREE.Vector3(-4, 0, -4), new THREE.Vector3(4, 0, 4));
1370
+ const c = box.getCenter(new THREE.Vector3()); c.y = 0;
1371
+ const size = box.getSize(new THREE.Vector3());
1372
+ const r = Math.min(95, Math.max(13, Math.max(size.x * 0.85, size.z * 1.32) + 3.5));
1373
+ if (instant) {
1374
+ orbit.target.copy(c); orbit.radius = r; orbit.theta = 0.48; orbit.phi = 0.88;
1375
+ scene.fog.near = 55; scene.fog.far = 140;
1376
+ placeCamera();
1377
+ } else {
1378
+ flyTo(c, r, 0.48, 0.88, 55, 140);
1379
+ }
1380
+ }
1381
+ function shortestDelta(from, to) {
1382
+ let d = (to - from) % (Math.PI * 2);
1383
+ if (d > Math.PI) d -= Math.PI * 2;
1384
+ if (d < -Math.PI) d += Math.PI * 2;
1385
+ return d;
1386
+ }
1387
+ function flyTo(target, radius, theta, phi, fogNear, fogFar, dur, onDone) {
1388
+ const th1 = theta != null ? orbit.theta + shortestDelta(orbit.theta, theta) : orbit.theta;
1389
+ const ph1 = phi != null ? phi : orbit.phi;
1390
+ fly = {
1391
+ t0: performance.now(), dur: dur || 760,
1392
+ from: orbit.target.clone(), to: target.clone(),
1393
+ r0: orbit.radius, r1: radius,
1394
+ th0: orbit.theta, th1, ph0: orbit.phi, ph1,
1395
+ fn0: scene.fog.near, fn1: fogNear != null ? fogNear : 55,
1396
+ ff0: scene.fog.far, ff1: fogFar != null ? fogFar : 140,
1397
+ onDone: onDone || null,
1398
+ };
1399
+ wake();
1400
+ }
1401
+ function placeCamera() {
1402
+ orbit.phi = Math.max(0.28, Math.min(1.34, orbit.phi));
1403
+ const r = orbit.radius;
1404
+ camera.position.set(
1405
+ orbit.target.x + r * Math.sin(orbit.phi) * Math.sin(orbit.theta),
1406
+ orbit.target.y + r * Math.cos(orbit.phi),
1407
+ orbit.target.z + r * Math.sin(orbit.phi) * Math.cos(orbit.theta)
1408
+ );
1409
+ camera.lookAt(orbit.target);
1410
+ }
1411
+
1412
+ const el = renderer.domElement;
1413
+ const vPanF = new THREE.Vector3(), vPanS = new THREE.Vector3();
1414
+ let drag = null;
1415
+ el.addEventListener('pointerdown', (e) => { drag = { x: e.clientX, y: e.clientY, moved: false, pan: e.button === 2 || e.shiftKey }; el.setPointerCapture(e.pointerId); fly = null; });
1416
+ el.addEventListener('pointermove', (e) => {
1417
+ if (!drag) { const hit = pickAt(e); setHover(hit.desk, hit.room); return; }
1418
+ const dx = e.clientX - drag.x, dy = e.clientY - drag.y;
1419
+ if (Math.abs(dx) + Math.abs(dy) > 3) drag.moved = true;
1420
+ if (drag.pan) {
1421
+ const k = orbit.radius * 0.0016;
1422
+ vPanF.set(Math.sin(orbit.theta), 0, Math.cos(orbit.theta));
1423
+ vPanS.set(vPanF.z, 0, -vPanF.x);
1424
+ orbit.target.addScaledVector(vPanS, -dx * k).addScaledVector(vPanF, -dy * k);
1425
+ } else { orbit.theta -= dx * 0.005; orbit.phi -= dy * 0.005; }
1426
+ drag.x = e.clientX; drag.y = e.clientY; placeCamera(); wake();
1427
+ });
1428
+ el.addEventListener('pointerup', (e) => {
1429
+ if (drag && !drag.moved) {
1430
+ const hit = pickAt(e);
1431
+ if (hit.dark) {
1432
+ // Dark offices are not interactive
1433
+ } else if (hit.desk) {
1434
+ focusAgent(hit.desk.id);
1435
+ } else if (hit.room) {
1436
+ focusRoom(hit.room.key);
1437
+ } else if (selected) {
1438
+ closeCard(false);
1439
+ }
1440
+ }
1441
+ drag = null;
1442
+ });
1443
+ el.addEventListener('contextmenu', (e) => e.preventDefault());
1444
+ el.addEventListener('wheel', (e) => { e.preventDefault(); fly = null; orbit.radius = Math.max(2.6, Math.min(115, orbit.radius * (e.deltaY > 0 ? 1.1 : 0.9))); placeCamera(); wake(); }, { passive: false });
1445
+ $('.st-bar').addEventListener('click', (e) => {
1446
+ const b = e.target.closest('[data-act]'); if (!b) return;
1447
+ if (b.dataset.act === 'overview') focusOverview(false);
1448
+ else { autoOrbit = !autoOrbit; b.setAttribute('aria-pressed', autoOrbit); wake(); }
1449
+ });
1450
+
1451
+ // ---------------------------------------------------------------- picking and hover (desks and glass offices)
1452
+ const ray = new THREE.Raycaster(), ndc = new THREE.Vector2();
1453
+ function isVisible(o) { while (o) { if (!o.visible) return false; o = o.parent; } return true; }
1454
+ function pickAt(e) {
1455
+ const r = el.getBoundingClientRect();
1456
+ ndc.set(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1);
1457
+ ray.setFromCamera(ndc, camera);
1458
+ const hits = ray.intersectObjects(building.children, true);
1459
+ let glassRoom = null;
1460
+ for (const h of hits) {
1461
+ if (h.object.userData.noHit || !isVisible(h.object)) continue;
1462
+ if (h.object.userData.deskId) {
1463
+ const d = desks.get(h.object.userData.deskId);
1464
+ if (d) {
1465
+ const rm = rooms.find((x) => x.key === d.roomKey) || null;
1466
+ if (glassRoom && rm !== glassRoom) return { desk: null, room: glassRoom, dark: false };
1467
+ if (d.dark || (rm && !rm.active)) return { desk: null, room: null, dark: true };
1468
+ return { desk: d, room: rm, dark: false };
1469
+ }
1470
+ }
1471
+ if (h.object.userData.roomKey) {
1472
+ const rm = rooms.find((x) => x.key === h.object.userData.roomKey) || null;
1473
+ if (glassRoom && rm !== glassRoom) return { desk: null, room: glassRoom, dark: false };
1474
+ if (h.object.userData.isGlass) {
1475
+ if (rm && !rm.active) return { desk: null, room: null, dark: true };
1476
+ if (!glassRoom) glassRoom = rm;
1477
+ continue;
1478
+ }
1479
+ if (rm && !rm.active) return { desk: null, room: null, dark: true };
1480
+ return { desk: null, room: rm, dark: false };
1481
+ }
1482
+ break;
1483
+ }
1484
+ if (glassRoom) {
1485
+ if (!glassRoom.active) return { desk: null, room: null, dark: true };
1486
+ return { desk: null, room: glassRoom, dark: false };
1487
+ }
1488
+ return { desk: null, room: null, dark: false };
1489
+ }
1490
+ function setHover(d, r) {
1491
+ if (d && d.dark) d = null;
1492
+ if (r && !r.active) r = null;
1493
+ const room = d ? null : r;
1494
+ if (d === hovered && room === hoveredRoom) return;
1495
+ if (hovered) hovered.hoverRing.visible = false;
1496
+ hovered = d;
1497
+ hoveredRoom = room;
1498
+ if (d && selected !== d.id) d.hoverRing.visible = true;
1499
+ for (const rm of rooms) {
1500
+ const isF = !!rm.active && rm.key === focusedRoomKey;
1501
+ const isH = !!rm.active && hoveredRoom === rm && !isF;
1502
+ rm.border.visible = isF || isH;
1503
+ rm.border.material = isF ? M.roomFocus : M.roomHover;
1504
+ }
1505
+ el.style.cursor = (d || room) ? 'pointer' : 'default';
1506
+ if (d) {
1507
+ tipEl.textContent = (d.s.label || d.s.name) + ': ' + api.t('state.' + d.s.state);
1508
+ tipEl.hidden = false;
1509
+ } else if (room && room.key !== focusedRoomKey) {
1510
+ tipEl.textContent = room.name + ' — ' + api.t('studio.clickRoom');
1511
+ tipEl.hidden = false;
1512
+ } else {
1513
+ tipEl.hidden = true;
1514
+ }
1515
+ wake();
1516
+ }
1517
+
1518
+ // ---------------------------------------------------------------- frame loop, on demand
1519
+ let raf = 0, lastFrame = 0, idleUntil = 0, disposed = false, prevTs = 0, viewW = 1, viewH = 1;
1520
+ const v = new THREE.Vector3();
1521
+ const poseKeys = Object.keys(POSES.working);
1522
+ const targetPose = { ...POSES.working };
1523
+ function wake() { idleUntil = performance.now() + 500; if (!raf && !disposed) raf = requestAnimationFrame(frame); }
1524
+ function frame(ts) {
1525
+ raf = 0;
1526
+ if (disposed) return;
1527
+ let moving = autoOrbit || !!fly;
1528
+ if (ts - lastFrame >= 33) {
1529
+ const dt = Math.min(0.1, (ts - (prevTs || ts)) / 1000); prevTs = ts; lastFrame = ts;
1530
+ const t = ts / 1000;
1531
+ const damp = 1 - Math.exp(-8 * dt);
1532
+ if (fly) {
1533
+ const k = Math.min(1, (ts - fly.t0) / fly.dur);
1534
+ const e = k < 0.5 ? 4 * k * k * k : 1 - Math.pow(-2 * k + 2, 3) / 2;
1535
+ orbit.target.lerpVectors(fly.from, fly.to, e);
1536
+ orbit.radius = fly.r0 + (fly.r1 - fly.r0) * e;
1537
+ orbit.theta = fly.th0 + (fly.th1 - fly.th0) * e;
1538
+ orbit.phi = fly.ph0 + (fly.ph1 - fly.ph0) * e;
1539
+ scene.fog.near = fly.fn0 + (fly.fn1 - fly.fn0) * e;
1540
+ scene.fog.far = fly.ff0 + (fly.ff1 - fly.ff0) * e;
1541
+ placeCamera();
1542
+ if (k >= 1) { const next = fly.onDone; fly = null; if (next) next(); }
1543
+ }
1544
+ if (autoOrbit) { orbit.theta += dt * 0.08; placeCamera(); }
1545
+ let alarm = false, hasCodeScroll = false;
1546
+ for (const d of desks.values()) {
1547
+ if (d.dark || !d.person.visible) continue;
1548
+ const base = POSES[d.state] || POSES.idle;
1549
+ const ph = d.phase;
1550
+ // Blend current pose smoothly toward the target state pose + organic motion (zero allocations)
1551
+ let maxDiff = 0;
1552
+ for (let i = 0; i < poseKeys.length; i++) { const k = poseKeys[i]; targetPose[k] = base[k]; }
1553
+ if (d.state === 'working') {
1554
+ moving = true; hasCodeScroll = true;
1555
+ const burst = 0.55 + 0.45 * Math.sin(t * 1.4 + ph * 2.1);
1556
+ const typeL = Math.sin(t * 11.5 + ph) * 0.09 * burst;
1557
+ const typeR = Math.sin(t * 12.2 + ph + 1.9) * 0.09 * burst;
1558
+ const mouseShift = Math.max(0, Math.sin(t * 0.55 + ph) - 0.72) * 0.7;
1559
+ targetPose.spineX += Math.sin(t * 2.1 + ph) * 0.015;
1560
+ targetPose.headY = Math.sin(t * 0.85 + ph) * 0.16;
1561
+ targetPose.headX += Math.sin(t * 0.42 + ph * 1.7) * 0.05;
1562
+ targetPose.lArmX += typeL * 0.35;
1563
+ targetPose.lElbX += typeL;
1564
+ targetPose.rArmX += typeR * 0.35;
1565
+ targetPose.rElbX += typeR * (1 - mouseShift);
1566
+ targetPose.rElbZ -= mouseShift * 0.25;
1567
+ d.armL.hand.rotation.x = typeL * 1.4;
1568
+ d.armR.hand.rotation.x = typeR * 1.4 * (1 - mouseShift);
1569
+ } else if (d.state === 'idle') {
1570
+ moving = true; hasCodeScroll = true;
1571
+ targetPose.spineX += Math.sin(t * 1.3 + ph) * 0.016;
1572
+ targetPose.headY = Math.sin(t * 0.45 + ph) * 0.26;
1573
+ targetPose.headZ = Math.sin(t * 0.35 + ph) * 0.05;
1574
+ d.armL.hand.rotation.x = 0; d.armR.hand.rotation.x = 0;
1575
+ d.badge.position.y = d.badgeY + 0.02 + Math.sin(t * 1.5 + ph) * 0.045;
1576
+ } else if (d.state === 'stalled') {
1577
+ alarm = true;
1578
+ targetPose.spineX += Math.sin(t * 1.1 + ph) * 0.018;
1579
+ targetPose.headZ += Math.sin(t * 0.9 + ph) * 0.04;
1580
+ targetPose.headY += Math.sin(t * 0.65 + ph) * 0.08;
1581
+ d.armL.hand.rotation.x = 0; d.armR.hand.rotation.x = 0.25;
1582
+ d.badge.position.y = d.badgeY + 0.06 + Math.sin(t * 4 + ph) * 0.055;
1583
+ d.ring.scale.setScalar(1 + ((t * 0.8 + ph) % 1) * 0.48);
1584
+ } else if (d.state === 'failed') {
1585
+ alarm = true;
1586
+ targetPose.spineX += Math.sin(t * 1.4 + ph) * 0.022;
1587
+ d.armL.hand.rotation.x = 0.2; d.armR.hand.rotation.x = 0.2;
1588
+ d.badge.position.y = d.badgeY + Math.sin(t * 4 + ph) * 0.055;
1589
+ d.ring.scale.setScalar(1 + ((t * 0.8 + ph) % 1) * 0.48);
1590
+ }
1591
+ for (let i = 0; i < poseKeys.length; i++) {
1592
+ const k = poseKeys[i];
1593
+ const diff = targetPose[k] - d.pose[k];
1594
+ if (Math.abs(diff) > maxDiff) maxDiff = Math.abs(diff);
1595
+ d.pose[k] += diff * damp;
1596
+ }
1597
+ if (maxDiff > 0.002) moving = true;
1598
+ applyPose(d, d.pose);
1599
+ }
1600
+ if (alarm) { moving = true; const p = 0.5 + 0.5 * Math.sin(t * 5); M.screenAlarm.color.setRGB(0.55 + 0.4 * p, 0.16 + 0.1 * p, 0.14); M.ring.opacity = 0.25 + 0.35 * p; }
1601
+ if (hasCodeScroll) {
1602
+ for (let i = 0; i < codeTexList.length; i++) codeTexList[i].tex.offset.y -= dt * 0.12;
1603
+ }
1604
+ for (let i = 0; i < links.length; i++) {
1605
+ const l = links[i];
1606
+ if (l.packet) { moving = true; l.t = (l.t + dt * 0.45) % 1; l.curve.getPoint(l.t, l.packet.position); }
1607
+ }
1608
+ // Lobby idle animation piggybacks only while the frame loop is already active (never sets moving = true)
1609
+ if (moving && lobbyActors) {
1610
+ const rec = lobbyActors.rec;
1611
+ if (isEmpty) {
1612
+ rec.spine.rotation.x = REC_EMPTY_POSE.spineX + Math.sin(t * 1.1) * 0.012;
1613
+ rec.head.rotation.y = REC_EMPTY_POSE.headY + Math.sin(t * 0.45) * 0.08;
1614
+ rec.armR.elbow.rotation.x = REC_EMPTY_POSE.rElbX + Math.sin(t * 0.65) * 0.06;
1615
+ } else {
1616
+ const burst = Math.max(0, Math.sin(t * 0.65) - 0.35);
1617
+ const tapL = Math.sin(t * 9.5) * 0.07 * burst;
1618
+ const tapR = Math.sin(t * 10.2 + 1.4) * 0.07 * burst;
1619
+ rec.spine.rotation.x = REC_ACTIVE_POSE.spineX + Math.sin(t * 1.5) * 0.012;
1620
+ rec.head.rotation.y = REC_ACTIVE_POSE.headY + Math.sin(t * 0.55) * 0.22;
1621
+ rec.armL.elbow.rotation.x = REC_ACTIVE_POSE.lElbX + tapL;
1622
+ rec.armR.elbow.rotation.x = REC_ACTIVE_POSE.rElbX + tapR;
1623
+ }
1624
+ const vis = lobbyActors.visitor;
1625
+ vis.spine.rotation.x = VISITOR_POSE.spineX + Math.sin(t * 1.05 + 1.2) * 0.012;
1626
+ vis.head.rotation.y = VISITOR_POSE.headY + Math.sin(t * 0.35 + 1.2) * 0.16;
1627
+ }
1628
+ renderer.render(scene, camera);
1629
+ // DOM: door signs and the hover tip follow the scene
1630
+ for (let i = 0; i < rooms.length; i++) {
1631
+ const room = rooms[i];
1632
+ v.copy(room.door).project(camera);
1633
+ const vis = v.z < 1 && Math.abs(v.x) < 1.2 && Math.abs(v.y) < 1.2;
1634
+ room.el.style.display = vis ? '' : 'none';
1635
+ if (vis) room.el.style.transform = 'translate(' + (((v.x + 1) / 2) * viewW).toFixed(1) + 'px,' + (((1 - v.y) / 2) * viewH).toFixed(1) + 'px) translate(-50%,-100%)';
1636
+ }
1637
+ if (hovered) {
1638
+ hovered.group.getWorldPosition(v); v.y += 1.9; v.project(camera);
1639
+ tipEl.style.left = ((v.x + 1) / 2) * viewW + 'px'; tipEl.style.top = ((1 - v.y) / 2) * viewH + 'px';
1640
+ } else if (hoveredRoom && hoveredRoom.key !== focusedRoomKey) {
1641
+ v.copy(hoveredRoom.center); v.y += 1.5; v.project(camera);
1642
+ tipEl.style.left = ((v.x + 1) / 2) * viewW + 'px'; tipEl.style.top = ((1 - v.y) / 2) * viewH + 'px';
1643
+ }
1644
+ } else moving = true;
1645
+ if (moving || ts < idleUntil) raf = requestAnimationFrame(frame);
1646
+ }
1647
+
1648
+ function relabel() {
1649
+ $('.st-panel').setAttribute('aria-label', api.t('studio.agents'));
1650
+ $('.st-h').textContent = api.t('studio.agents');
1651
+ $('.st-empty-t').textContent = api.t('studio.emptyTitle');
1652
+ $('.st-empty-b').textContent = api.t('studio.emptyBody');
1653
+ $('.st-back')._h = null;
1654
+ $('.st-bar [data-act="overview"]').textContent = api.t('studio.overview');
1655
+ $('[data-act="orbit"]').textContent = api.t('studio.orbit');
1656
+ $('.st-hint').textContent = api.t('studio.hint');
1657
+ $('.st-list')._h = null; $('.st-toasts')._h = null; $('.st-card')._h = null; $('.st-crumb')._h = null;
1658
+ for (const r of rooms) r.el._h = null;
1659
+ renderFocusBar();
1660
+ if (lastState) update(lastState);
1661
+ }
1662
+ function onEscape() {
1663
+ if (selected || focusMode === 'agent') {
1664
+ closeCard(true);
1665
+ } else if (focusMode === 'room') {
1666
+ focusOverview(false);
1667
+ } else if (autoOrbit) {
1668
+ stopOrbit();
1669
+ } else {
1670
+ fit(false);
1671
+ }
1672
+ }
1673
+ function resize() {
1674
+ const w = host.clientWidth || 1, h = host.clientHeight || 1;
1675
+ viewW = w; viewH = h;
1676
+ renderer.setSize(w, h, false); renderer.domElement.style.width = w + 'px'; renderer.domElement.style.height = h + 'px';
1677
+ camera.aspect = w / h; camera.updateProjectionMatrix(); wake();
1678
+ }
1679
+ const ro = new ResizeObserver(resize); ro.observe(host);
1680
+ const onVis = () => { if (!document.hidden) wake(); };
1681
+ document.addEventListener('visibilitychange', onVis);
1682
+ relabel(); resize(); placeCamera();
1683
+
1684
+ function dispose() {
1685
+ disposed = true; cancelAnimationFrame(raf); ro.disconnect(); clearTimeout(feedTimer);
1686
+ resetCardExpand();
1687
+ document.removeEventListener('visibilitychange', onVis);
1688
+ clearBuilding();
1689
+ desks.clear();
1690
+ for (const l of links) l.line.geometry.dispose();
1691
+ for (const g of Object.values(G)) g.dispose();
1692
+ for (const m of mats.values()) m.dispose();
1693
+ for (const m of [M.screenAlarm, M.ring, M.focusRing, M.hoverRing, M.roomFocus, M.roomHover, ...Object.values(SP), ...Object.values(codeTex).map((c) => c.mat)]) m.dispose();
1694
+ for (const t of textures) t.dispose();
1695
+ ground.geometry.dispose();
1696
+ renderer.dispose(); renderer.forceContextLoss();
1697
+ host.innerHTML = '';
1698
+ }
1699
+ return { update, dispose, relabel, onEscape };
1700
+ }
1701
+
1702
+ function hash(s) { let h = 0; for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0; return Math.abs(h); }
1703
+ function darken(hex, f) {
1704
+ const r = Math.round(((hex >> 16) & 255) * f);
1705
+ const g = Math.round(((hex >> 8) & 255) * f);
1706
+ const b = Math.round((hex & 255) * f);
1707
+ return (r << 16) | (g << 8) | b;
1708
+ }
1709
+
1710
+ function stateRank(st) {
1711
+ if (st === 'working') return 0;
1712
+ if (st === 'stalled') return 1;
1713
+ if (st === 'failed') return 2;
1714
+ if (st === 'idle') return 3;
1715
+ return 4;
1716
+ }
1717
+ function activityTier(st) {
1718
+ if (st === 'working' || st === 'stalled' || st === 'failed') return 0;
1719
+ if (st === 'idle') return 1;
1720
+ return 2;
1721
+ }
1722
+ function cmpSession(a, b) {
1723
+ return (stateRank(a.state) - stateRank(b.state)) ||
1724
+ ((a.started || 0) - (b.started || 0)) ||
1725
+ (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
1726
+ }
1727
+ function makePod2(a, b) {
1728
+ if (!b) return { w: POD2_W, seats: [{ s: a, dx: 0, dz: 0, rotY: 0 }] };
1729
+ return {
1730
+ w: POD2_W,
1731
+ seats: [
1732
+ { s: a, dx: 0, dz: POD_DZ, rotY: 0 },
1733
+ { s: b, dx: 0, dz: -POD_DZ, rotY: Math.PI },
1734
+ ],
1735
+ };
1736
+ }
1737
+ function makePod4(list, isTeamLeadPod) {
1738
+ const slots = isTeamLeadPod
1739
+ ? [
1740
+ [-BLOCK_DX, POD_DZ, 0],
1741
+ [-BLOCK_DX, -POD_DZ, Math.PI],
1742
+ [BLOCK_DX, -POD_DZ, Math.PI],
1743
+ [BLOCK_DX, POD_DZ, 0],
1744
+ ]
1745
+ : [
1746
+ [-BLOCK_DX, POD_DZ, 0],
1747
+ [BLOCK_DX, POD_DZ, 0],
1748
+ [-BLOCK_DX, -POD_DZ, Math.PI],
1749
+ [BLOCK_DX, -POD_DZ, Math.PI],
1750
+ ];
1751
+ const seats = [];
1752
+ for (let i = 0; i < list.length && i < 4; i++) {
1753
+ seats.push({ s: list[i], dx: slots[i][0], dz: slots[i][1], rotY: slots[i][2] });
1754
+ }
1755
+ return { w: POD4_W, seats };
1756
+ }
1757
+ function rowWidth(pods) {
1758
+ if (!pods.length) return 0;
1759
+ let w = 0;
1760
+ for (let i = 0; i < pods.length; i++) w += pods[i].w;
1761
+ return w + (pods.length - 1) * POD_GAP_X;
1762
+ }
1763
+ function packRows(units, maxPods, maxW) {
1764
+ const rows = [];
1765
+ let cur = [];
1766
+ let curW = 0;
1767
+ let splits = 0;
1768
+ const flush = () => { if (cur.length) { rows.push(cur); cur = []; curW = 0; } };
1769
+ const addPod = (p) => {
1770
+ curW = cur.length ? curW + POD_GAP_X + p.w : p.w;
1771
+ cur.push(p);
1772
+ };
1773
+ for (let i = 0; i < units.length; i++) {
1774
+ const uPods = units[i].pods;
1775
+ const uW = rowWidth(uPods);
1776
+ if (uPods.length <= maxPods && uW <= maxW + 1e-6) {
1777
+ if (cur.length && (cur.length + uPods.length > maxPods || curW + POD_GAP_X + uW > maxW + 1e-6)) flush();
1778
+ for (let j = 0; j < uPods.length; j++) addPod(uPods[j]);
1779
+ } else {
1780
+ flush();
1781
+ for (let j = 0; j < uPods.length; j++) {
1782
+ const p = uPods[j];
1783
+ if (cur.length && (cur.length + 1 > maxPods || curW + POD_GAP_X + p.w > maxW + 1e-6)) {
1784
+ flush();
1785
+ splits++;
1786
+ }
1787
+ addPod(p);
1788
+ }
1789
+ }
1790
+ }
1791
+ flush();
1792
+ return { rows, splits };
1793
+ }
1794
+ function planOffice(arr) {
1795
+ if (!arr.length) return { w: ROOM_W_MIN, d: ROOM_D_MIN, placements: [] };
1796
+
1797
+ const ids = new Set(arr.map((s) => s.id));
1798
+ const childrenOf = new Map();
1799
+ for (let i = 0; i < arr.length; i++) {
1800
+ const s = arr[i];
1801
+ if (s.parent && ids.has(s.parent) && s.parent !== s.id) {
1802
+ if (!childrenOf.has(s.parent)) childrenOf.set(s.parent, []);
1803
+ childrenOf.get(s.parent).push(s);
1804
+ }
1805
+ }
1806
+ for (const kids of childrenOf.values()) kids.sort(cmpSession);
1807
+
1808
+ const visited = new Set();
1809
+ const collectSubs = (lead) => {
1810
+ const subs = [];
1811
+ const walk = (p, depth) => {
1812
+ const kids = childrenOf.get(p.id);
1813
+ if (!kids) return;
1814
+ for (let i = 0; i < kids.length; i++) {
1815
+ const c = kids[i];
1816
+ if (visited.has(c.id)) continue;
1817
+ visited.add(c.id);
1818
+ subs.push(c);
1819
+ if (depth < 6) walk(c, depth + 1);
1820
+ }
1821
+ };
1822
+ walk(lead, 0);
1823
+ return subs;
1824
+ };
1825
+
1826
+ const groups = [];
1827
+ const rawLeads = arr.filter((s) => !s.parent || !ids.has(s.parent) || s.parent === s.id).sort(cmpSession);
1828
+ for (let i = 0; i < rawLeads.length; i++) {
1829
+ const l = rawLeads[i];
1830
+ if (visited.has(l.id)) continue;
1831
+ visited.add(l.id);
1832
+ groups.push({ lead: l, subs: collectSubs(l) });
1833
+ }
1834
+ const leftovers = arr.filter((s) => !visited.has(s.id)).sort(cmpSession);
1835
+ for (let i = 0; i < leftovers.length; i++) {
1836
+ const l = leftovers[i];
1837
+ if (visited.has(l.id)) continue;
1838
+ visited.add(l.id);
1839
+ groups.push({ lead: l, subs: collectSubs(l) });
1840
+ }
1841
+
1842
+ for (let i = 0; i < groups.length; i++) {
1843
+ const g = groups[i];
1844
+ let tier = activityTier(g.lead.state);
1845
+ let bestRank = stateRank(g.lead.state);
1846
+ for (let j = 0; j < g.subs.length; j++) {
1847
+ const ct = activityTier(g.subs[j].state);
1848
+ const cr = stateRank(g.subs[j].state);
1849
+ if (ct < tier) tier = ct;
1850
+ if (cr < bestRank) bestRank = cr;
1851
+ }
1852
+ g.tier = tier;
1853
+ g.bestRank = bestRank;
1854
+ g.leadRank = stateRank(g.lead.state);
1855
+ }
1856
+ groups.sort((a, b) =>
1857
+ (a.tier - b.tier) ||
1858
+ (a.bestRank - b.bestRank) ||
1859
+ (a.leadRank - b.leadRank) ||
1860
+ ((a.lead.started || 0) - (b.lead.started || 0)) ||
1861
+ (a.lead.id < b.lead.id ? -1 : a.lead.id > b.lead.id ? 1 : 0)
1862
+ );
1863
+
1864
+ const soloEntries = [];
1865
+ const units = [];
1866
+ for (let i = 0; i < groups.length; i++) {
1867
+ const g = groups[i];
1868
+ if (!g.subs.length) {
1869
+ soloEntries.push({ s: g.lead, ord: i });
1870
+ } else {
1871
+ const members = [g.lead, ...g.subs];
1872
+ const pods = [];
1873
+ if (members.length === 2) {
1874
+ pods.push(makePod2(members[0], members[1]));
1875
+ } else {
1876
+ pods.push(makePod4(members.slice(0, 4), true));
1877
+ for (let j = 4; j < members.length; ) {
1878
+ const rem = members.length - j;
1879
+ if (rem >= 3) {
1880
+ pods.push(makePod4(members.slice(j, j + 4), false));
1881
+ j += Math.min(4, rem);
1882
+ } else {
1883
+ pods.push(makePod2(members[j], members[j + 1]));
1884
+ j += rem;
1885
+ }
1886
+ }
1887
+ }
1888
+ units.push({ ord: i, pods });
1889
+ }
1890
+ }
1891
+ const soloPodSize = soloEntries.length >= 13 ? 4 : 2;
1892
+ for (let i = 0; i < soloEntries.length; i += soloPodSize) {
1893
+ const chunk = soloEntries.slice(i, i + soloPodSize);
1894
+ const list = chunk.map((e) => e.s);
1895
+ const pod = list.length >= 3 ? makePod4(list, false) : makePod2(list[0], list[1]);
1896
+ units.push({ ord: chunk[0].ord, pods: [pod] });
1897
+ }
1898
+ units.sort((a, b) => a.ord - b.ord);
1899
+
1900
+ const byRowCount = new Map();
1901
+ for (let i = 0; i < ROW_CANDIDATES.length; i++) {
1902
+ const [maxPods, maxW] = ROW_CANDIDATES[i];
1903
+ const res = packRows(units, maxPods, maxW);
1904
+ let maxActualW = 0;
1905
+ for (let r = 0; r < res.rows.length; r++) {
1906
+ const rw = rowWidth(res.rows[r]);
1907
+ if (rw > maxActualW) maxActualW = rw;
1908
+ }
1909
+ const w = Math.max(ROOM_W_MIN, maxActualW + SIDE_MARGIN * 2);
1910
+ const reqD = Z_FRONT + Math.max(0, res.rows.length - 1) * ROW_PITCH_Z + Z_BACK;
1911
+ const d = Math.max(ROOM_D_MIN, reqD);
1912
+ const cand = { rows: res.rows, splits: res.splits, w, d, reqD };
1913
+ const rc = res.rows.length;
1914
+ const prev = byRowCount.get(rc);
1915
+ if (!prev || cand.splits < prev.splits || (cand.splits === prev.splits && cand.w < prev.w - 1e-6)) {
1916
+ byRowCount.set(rc, cand);
1917
+ }
1918
+ }
1919
+ let best = null;
1920
+ let bestScore = Infinity;
1921
+ for (const cand of byRowCount.values()) {
1922
+ const aspect = Math.max(cand.w / cand.d, cand.d / cand.w);
1923
+ const sc = aspect + cand.splits * 0.22;
1924
+ if (
1925
+ sc < bestScore - 1e-6 ||
1926
+ (Math.abs(sc - bestScore) <= 1e-6 && best && cand.w * cand.d < best.w * best.d)
1927
+ ) {
1928
+ best = cand;
1929
+ bestScore = sc;
1930
+ }
1931
+ }
1932
+
1933
+ const placements = [];
1934
+ const z0 = Z_FRONT + (best.d - best.reqD) * 0.5;
1935
+ for (let r = 0; r < best.rows.length; r++) {
1936
+ const row = best.rows[r];
1937
+ const zc = z0 + r * ROW_PITCH_Z;
1938
+ const rw = rowWidth(row);
1939
+ let xCursor = (best.w - rw) * 0.5;
1940
+ for (let c = 0; c < row.length; c++) {
1941
+ const pod = row[c];
1942
+ const xc = xCursor + pod.w * 0.5;
1943
+ for (let k = 0; k < pod.seats.length; k++) {
1944
+ const seat = pod.seats[k];
1945
+ placements.push({ s: seat.s, x: xc + seat.dx, z: zc + seat.dz, rotY: seat.rotY });
1946
+ }
1947
+ xCursor += pod.w + POD_GAP_X;
1948
+ }
1949
+ }
1950
+ return { w: best.w, d: best.d, placements };
1951
+ }