agenthall 0.0.0-stage → 1.0.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.
package/public/app.js ADDED
@@ -0,0 +1,4745 @@
1
+ 'use strict';
2
+
3
+ /* Agent Hall client: renders the office on a canvas, drives agent sprites
4
+ from server state and hosts the terminal panel and dialogs. */
5
+
6
+ const $ = (s, el = document) => el.querySelector(s);
7
+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
8
+
9
+ const ROLE_RANK = { lead: 0, senior: 1, mid: 2, junior: 3, intern: 4 };
10
+ const ROLE_BADGE = {
11
+ lead: { c: '#f4c430', s: '♛' },
12
+ senior: { c: '#b388ff', s: '★' },
13
+ mid: { c: '#5aa9ff', s: '◆' },
14
+ junior: { c: '#5fd3a5', s: '●' },
15
+ intern: { c: '#a0a8b8', s: '○' },
16
+ };
17
+ // Language: saved choice, else the browser's language.
18
+ let LANG = (() => {
19
+ try {
20
+ const saved = localStorage.getItem('ao-lang');
21
+ if (saved && I18N.LANGS.includes(saved)) return saved;
22
+ } catch {
23
+ /* storage unavailable */
24
+ }
25
+ return String(navigator.language || '').toLowerCase().startsWith('tr') ? 'tr' : 'en';
26
+ })();
27
+ const tx = (key, params) => I18N.translate(LANG, key, params);
28
+ const statusLabel = (s) => tx('status.' + s);
29
+ const pick = (key) => {
30
+ const list = tx(key);
31
+ return Array.isArray(list) ? list[Math.floor(Math.random() * list.length)] : list;
32
+ };
33
+ // Server messages arrive as { key, params } so they follow the boss's language.
34
+ const msgText = (m) => (m && typeof m === 'object' ? tx(m.key, m.params) : m || '');
35
+ const NAMES = ['Ayşe', 'Mehmet', 'Zeynep', 'Can', 'Elif', 'Burak', 'Deniz', 'Ece', 'Emre', 'Selin', 'Kerem', 'Defne', 'Mert', 'İrem', 'Ozan', 'Naz', 'Arda', 'Duru', 'Kaan', 'Lara', 'Barış', 'Ceren', 'Tolga', 'Yağmur', 'Onur', 'Melis'];
36
+ // Mixed team: appearance follows the name (or the agent's "look" setting);
37
+ // names that tell nothing (e.g. "getir-15") get a stable 50/50 pick.
38
+ const FEMALE_NAMES = new Set(['Ayşe', 'Zeynep', 'Elif', 'Ece', 'Selin', 'Defne', 'İrem', 'Naz', 'Duru', 'Lara', 'Ceren', 'Yağmur', 'Melis', 'Ayla', 'Dila', 'Ela', 'Işıl', 'Nil', 'Pelin', 'Zehra', 'İpek', 'Esra', 'Merve', 'Büşra', 'Gizem', 'Seda', 'Aslı', 'Ebru', 'Derya', 'Buse']);
39
+ const MALE_NAMES = new Set(['Mehmet', 'Can', 'Burak', 'Emre', 'Kerem', 'Mert', 'Ozan', 'Arda', 'Kaan', 'Barış', 'Tolga', 'Onur', 'Ali', 'Berk', 'Cem', 'Efe', 'Hakan', 'Sarp', 'Tuna', 'Umut', 'Bora', 'Oğuz', 'Ahmet', 'Mustafa', 'Volkan', 'Murat', 'Serkan', 'Emir']);
40
+ function lookOf(a) {
41
+ if (a.look === 'f' || a.look === 'm') return a.look;
42
+ const first = String(a.name || '').split(/[\s(·-]/)[0];
43
+ if (FEMALE_NAMES.has(first)) return 'f';
44
+ if (MALE_NAMES.has(first)) return 'm';
45
+ return hash(a.id + 'look') % 2 ? 'f' : 'm';
46
+ }
47
+ const HAIR_STYLES = { f: ['long', 'long', 'ponytail', 'bun', 'curlyLong', 'bob'], m: ['short', 'side', 'buzz', 'curly'] };
48
+ const hairStyleOf = (a, look) => HAIR_STYLES[look][hash(a.id + 'style') % HAIR_STYLES[look].length];
49
+
50
+ const SKIN = ['#f1c27d', '#e0ac69', '#c68642', '#ffdbac', '#d4a373', '#8d5524'];
51
+ const HAIR = ['#2b1d14', '#4a2f1b', '#121212', '#7a4b2a', '#b5651d', '#d8b26e', '#5b5b5b', '#8e3b2f'];
52
+
53
+ let S = { projects: [], agents: [], roles: [], roleLabels: {} };
54
+ let L = null; // layout
55
+ let firstState = true;
56
+ let employeeOfMonth = null;
57
+ let lastProjectCount = -1;
58
+ const sprites = new Map();
59
+ // Agents the boss just fired: they pack their things into a box before walking out.
60
+ const firedIds = new Set();
61
+ // A freshly hired agent's terminal opens as soon as it shows up in the state.
62
+ let openOnArrival = null;
63
+ const bubbles = new Map(); // agentId -> { text, until, kind }
64
+ const spotOf = new Map(); // agentId -> garden spot index
65
+
66
+ function hash(str) {
67
+ let h = 2166136261;
68
+ for (const ch of String(str)) h = Math.imul(h ^ ch.charCodeAt(0), 16777619);
69
+ return h >>> 0;
70
+ }
71
+ const agentById = (id) => S.agents.find((a) => a.id === id);
72
+ // Token counts and the API-price estimate, e.g. "1.2M token · ~$3.40".
73
+ const fmtTokens = (n) => (n >= 1e6 ? (n / 1e6).toFixed(1) + 'M' : n >= 1e3 ? Math.round(n / 1e3) + 'K' : String(n));
74
+ const fmtCost = (c) => '~$' + (c >= 100 ? Math.round(c) : c.toFixed(2));
75
+ const usageTokens = (u) => u.input + u.output + u.cacheWrite + u.cacheRead;
76
+ const fmtUsage = (u) => (u && usageTokens(u) ? tx('usage.line', { tokens: fmtTokens(usageTokens(u)), cost: fmtCost(u.cost) }) : '');
77
+ const stuckText = (a) =>
78
+ a.stuck.kind === 'loop'
79
+ ? tx('stuck.loop', { n: a.stuck.count, tool: a.stuck.tool })
80
+ : tx('stuck.slow', { n: Math.max(1, Math.round((Date.now() - a.stuck.since) / 60000)), tool: a.stuck.tool || '?' });
81
+ // Files this agent is changing together with someone else, as { file, short, others }.
82
+ function conflictsOf(a) {
83
+ const root = projectById(a.projectId)?.path || a.cwd || '';
84
+ return (S.conflicts || [])
85
+ .filter((c) => c.agents.includes(a.id))
86
+ .map((c) => ({ file: c.file, short: root && c.file.startsWith(root + '/') ? c.file.slice(root.length + 1) : c.file, others: c.agents.filter((x) => x !== a.id).map((x) => agentById(x)?.name || '?') }));
87
+ }
88
+ const agentUsage = (a) => S.usage?.agents?.[a.id];
89
+ const projectById = (id) => S.projects.find((p) => p.id === id);
90
+ const roleLabel = (r) => tx('role.' + r);
91
+
92
+ // ------------------------------------------------------------------ API / WS
93
+
94
+ async function api(method, url, body) {
95
+ const opts = { method, headers: { 'X-Lang': LANG } };
96
+ if (method !== 'GET') {
97
+ opts.headers['Content-Type'] = 'application/json';
98
+ opts.body = JSON.stringify(body || {});
99
+ }
100
+ const r = await fetch(url, opts);
101
+ const j = await r.json().catch(() => ({}));
102
+ if (!r.ok) throw new Error(j.error || r.statusText);
103
+ return j;
104
+ }
105
+
106
+ let ws;
107
+ function connect() {
108
+ ws = new WebSocket(`ws://${location.host}/ws`);
109
+ ws.onopen = () => {
110
+ $('#conn').classList.add('on');
111
+ if (panelId) attachTerm(panelId);
112
+ };
113
+ ws.onclose = () => {
114
+ $('#conn').classList.remove('on');
115
+ setTimeout(connect, 1500);
116
+ };
117
+ ws.onmessage = (ev) => handleMsg(JSON.parse(ev.data));
118
+ }
119
+ const wsSend = (o) => ws && ws.readyState === 1 && ws.send(JSON.stringify(o));
120
+
121
+ // Hot reload: keep the view (camera, open panel) across page reloads.
122
+ let bootId = null;
123
+ function reloadPage() {
124
+ try {
125
+ sessionStorage.setItem('ao-view', JSON.stringify({ cam, panelId, focus }));
126
+ } catch {
127
+ /* storage unavailable */
128
+ }
129
+ location.reload();
130
+ }
131
+ function restoreView() {
132
+ try {
133
+ const v = JSON.parse(sessionStorage.getItem('ao-view') || 'null');
134
+ sessionStorage.removeItem('ao-view');
135
+ return v;
136
+ } catch {
137
+ return null;
138
+ }
139
+ }
140
+ const savedView = restoreView();
141
+
142
+ function handleMsg(m) {
143
+ switch (m.t) {
144
+ case 'hello':
145
+ // A new server process may come with new client code too.
146
+ if (bootId && bootId !== m.bootId) return reloadPage();
147
+ bootId = m.bootId;
148
+ break;
149
+ case 'reload':
150
+ if (m.css) {
151
+ for (const l of document.querySelectorAll('link[rel=stylesheet][href^="style.css"]')) l.href = `style.css?v=${Date.now()}`;
152
+ } else reloadPage();
153
+ break;
154
+ case 'restarting':
155
+ toast(tx('toast.updating'), 'info');
156
+ break;
157
+ case 'state':
158
+ applyState(m.state);
159
+ break;
160
+ case 'out':
161
+ if (m.id === panelId && term) term.write(m.data);
162
+ break;
163
+ case 'replay':
164
+ if (m.id === panelId && term) {
165
+ term.reset();
166
+ term.write(m.data || '');
167
+ nudgeResize();
168
+ }
169
+ break;
170
+ case 'toast':
171
+ toast(msgText(m.key ? m : m.text), m.kind, m.agentId);
172
+ if (m.kind === 'warn') notify(msgText(m.key ? m : m.text));
173
+ break;
174
+ case 'bubble':
175
+ for (const id of m.ids) bubbles.set(id, { text: (m.kind === 'announce' ? '📢 ' : '💬 ') + (m.key ? tx(m.key) : m.text), until: performance.now() + 8000, kind: m.kind });
176
+ break;
177
+ case 'ask':
178
+ askDismissed.delete(m.agentId);
179
+ if (m.n === 1) notify(tx('notify.asking', { name: agentById(m.agentId)?.name || tx('notify.someone') }));
180
+ break;
181
+ case 'mail': {
182
+ const fromA = agentById(m.from);
183
+ const toA = agentById(m.to);
184
+ mails.push({ from: m.from, to: m.to, t0: performance.now() });
185
+ bubbles.set(m.to, { text: '📨 ' + m.text, until: performance.now() + 9000, kind: 'visit' });
186
+ if (fromA && toA) toast(tx('mail.sent', { from: fromA.name, to: toA.name, text: m.text.slice(0, 80) }), 'info', m.to);
187
+ break;
188
+ }
189
+ case 'levelup': {
190
+ const sp = sprites.get(m.agentId);
191
+ if (sp) burst(sp.x, sp.y - 40);
192
+ break;
193
+ }
194
+ case 'achievement':
195
+ {
196
+ const [title, desc] = tx('ach.' + m.id);
197
+ toast(tx('trophy.won', { icon: m.icon, title, desc }), 'ok');
198
+ }
199
+ burst(L.boss.x + L.boss.w / 2, L.boss.y + 80, 90);
200
+ break;
201
+ case 'exit':
202
+ if (m.id === panelId && term) term.write(`\r\n\x1b[90m${tx('panel.exit', { code: m.code })}\x1b[0m\r\n`);
203
+ break;
204
+ }
205
+ }
206
+
207
+ function applyState(state) {
208
+ S = state;
209
+ computeLayout();
210
+ if (focus && !L.roomsById[focus.id]) leaveFocus(); // the room was closed
211
+ else if (focus) showFocusBar();
212
+ if (S.projects.length !== lastProjectCount) {
213
+ lastProjectCount = S.projects.length;
214
+ if (savedView && lastProjectCount >= 0 && !savedView.used) {
215
+ Object.assign(cam, savedView.cam);
216
+ savedView.used = true;
217
+ if (savedView.focus && L.roomsById[savedView.focus.id]) {
218
+ focus = savedView.focus;
219
+ showFocusBar();
220
+ }
221
+ if (savedView.panelId) setTimeout(() => agentById(savedView.panelId) && openPanel(savedView.panelId), 50);
222
+ } else fitCamera();
223
+ }
224
+ $('#empty').hidden = S.projects.length > 0;
225
+ const ranked = S.agents.filter((a) => a.game && a.game.xp > 0).sort((p, q) => q.game.xp - p.game.xp);
226
+ employeeOfMonth = ranked[0]?.id || null;
227
+ syncSprites(firstState);
228
+ firstState = false;
229
+ renderStats();
230
+ renderAskCard();
231
+ if (queueOpen) renderQueue();
232
+ if (boardOpen) renderBoard();
233
+ if (meetingsOpen) renderMeetings();
234
+ if (openOnArrival && agentById(openOnArrival)) {
235
+ const id = openOnArrival;
236
+ openOnArrival = null;
237
+ openPanel(id);
238
+ } else if (panelId) {
239
+ if (!agentById(panelId)) closePanel();
240
+ else renderPanel();
241
+ }
242
+ }
243
+
244
+ function renderStats() {
245
+ const c = { working: 0, waiting: 0, idle: 0, offline: 0 };
246
+ for (const a of S.agents) c[a.status === 'starting' ? 'working' : a.status]++;
247
+ $('#stats').innerHTML = `
248
+ <span>🏢 ${tx('stats.rooms', { n: `<b>${S.projects.length}</b>` })}</span>
249
+ <span>💻 ${tx('stats.working', { n: `<b>${c.working}</b>` })}</span>
250
+ <button class="stat-link${c.waiting ? ' hot' : ''}" data-queue title="${tx('queue.open')}">⚠️ ${tx('stats.waiting', { n: `<b>${c.waiting}</b>` })}</button>
251
+ <span>☕ ${tx('stats.idle', { n: `<b>${c.idle}</b>` })}</span>
252
+ <span>🏠 ${tx('stats.offline', { n: `<b>${c.offline}</b>` })}</span>
253
+ ${S.usage?.total?.cost ? `<span title="${tx('usage.title')}">💰 ${tx('stats.cost', { cost: `<b>${fmtCost(S.usage.total.cost)}</b>` })}</span>` : ''}`;
254
+ document.title = c.waiting ? `(${c.waiting}) Agent Hall` : 'Agent Hall';
255
+ $('#btn-arcade').classList.toggle('locked', !canPlay());
256
+ }
257
+
258
+ // ------------------------------------------------------------------ layout
259
+
260
+ const ROOM_W = 640;
261
+ const GAP = 84;
262
+ const MARGIN = 60;
263
+ const BOSS_H = 190;
264
+ const HEADER = 70;
265
+ const BIG = { w: 156, h: 58, row: 132 };
266
+ const SMALL = { w: 116, h: 48, row: 118 };
267
+ const GARDEN_W = 720;
268
+ const ROAD_LANE = 36;
269
+
270
+ // The office is a small city: building blocks (HQ, park, any offices/teams
271
+ // the boss adds and an empty lot for the next one) on a grid of three columns. Each row of
272
+ // blocks has a four-lane road in front; pedestrian avenues run between the
273
+ // columns. Inside a building, rooms sit in two columns next to a corridor
274
+ // ("spine") that leads down to the building's entrance on the sidewalk.
275
+ const CITY_COLS = 3;
276
+ const BPAD = 30;
277
+ const AVENUE = 130;
278
+ const BLOCK_W = BPAD + GAP + 2 * ROOM_W + GAP + BPAD;
279
+ const ROAD_GAP_TOP = 150; // building bottom → road (sidewalk, then the parking strip)
280
+ const ROAD_GAP_BOTTOM = 70; // road → next row
281
+ const BAY_W = 30;
282
+ const RACK_W = 14;
283
+
284
+ function layoutRooms(projects, x0, top, seats) {
285
+ const cols = 2;
286
+ const measured = projects.map((p, i) => {
287
+ const ags = S.agents
288
+ .filter((a) => a.projectId === p.id)
289
+ .sort((a, b) => ROLE_RANK[a.role] - ROLE_RANK[b.role] || a.createdAt - b.createdAt);
290
+ const leads = ags.filter((a) => a.role === 'lead');
291
+ const others = ags.filter((a) => a.role !== 'lead');
292
+ // Free desks: one lead desk while there is no lead, one regular free chair,
293
+ // plus any desks the boss added from the room's right-click menu.
294
+ const leadSlots = Math.max(1, leads.length + (p.extraLeadDesks || 0));
295
+ const leadRows = Math.ceil(leadSlots / 3);
296
+ const otherSlots = others.length + 1 + (p.extraDesks || 0);
297
+ const otherRows = Math.ceil(otherSlots / 4);
298
+ const h = Math.max(400, HEADER + 34 + leadRows * BIG.row + otherRows * SMALL.row + 70);
299
+ return { p, leads, others, leadSlots, otherSlots, leadRows, otherRows, h, col: i % cols, row: Math.floor(i / cols) };
300
+ });
301
+ const rowH = [];
302
+ for (const m of measured) rowH[m.row] = Math.max(rowH[m.row] || 0, m.h);
303
+ const rowY = [];
304
+ let y = top;
305
+ rowH.forEach((h, i) => {
306
+ rowY[i] = y;
307
+ y += h + GAP;
308
+ });
309
+ const rooms = [];
310
+ for (const m of measured) {
311
+ const x = x0 + m.col * (ROOM_W + GAP);
312
+ const ry = rowY[m.row];
313
+ const h = rowH[m.row];
314
+ const room = { id: m.p.id, p: m.p, x, y: ry, w: ROOM_W, h, door: { x: x + ROOM_W / 2, y: ry + h }, hallY: ry + h + GAP / 2, desks: [] };
315
+ const addDesk = (a, cx, cy, big, emptyRole) => {
316
+ const d = big ? BIG : SMALL;
317
+ const desk = { agent: a, big, x: cx - d.w / 2, y: cy, w: d.w, h: d.h, room, emptyRole };
318
+ desk.seat = { x: cx + (big ? 22 : 16), y: cy + 9 };
319
+ room.desks.push(desk);
320
+ if (!a) return;
321
+ seats.set(a.id, { x: desk.seat.x, y: desk.seat.y, zone: 'room:' + room.id, act: 'desk', labelY: cy + d.h + 15, desk });
322
+ };
323
+ let cy = ry + HEADER + 44;
324
+ for (let r = 0; r < m.leadRows; r++) {
325
+ const n = Math.min(3, m.leadSlots - r * 3);
326
+ for (let i = 0; i < n; i++) addDesk(m.leads[r * 3 + i] || null, x + (ROOM_W * (i + 1)) / (n + 1), cy, true, 'lead');
327
+ cy += BIG.row;
328
+ }
329
+ for (let r = 0; r < m.otherRows; r++) {
330
+ for (let i = 0; i < Math.min(4, m.otherSlots - r * 4); i++) {
331
+ const a = m.others[r * 4 + i] || null;
332
+ // A free chair takes the seniority of the row it sits in.
333
+ const prev = m.others[Math.min(r * 4 + i, m.others.length) - 1];
334
+ addDesk(a, x + 50 + ((ROOM_W - 100) * (i + 0.5)) / 4, cy, false, prev ? prev.role : 'senior');
335
+ }
336
+ cy += SMALL.row;
337
+ }
338
+ rooms.push(room);
339
+ }
340
+ return { rooms, bottom: projects.length ? y - GAP : top };
341
+ }
342
+
343
+ function buildGarden(gx, gy, gw, gh) {
344
+ const garden = { x: gx, y: gy, w: gw, h: gh };
345
+ garden.smoke = { x: gx + 150, y: gy + 170 };
346
+ garden.cafe = { x: gx + gw - 190, y: gy + 120 };
347
+ garden.pond = { x: gx + gw / 2 + 10, y: gy + gh * 0.42 };
348
+ garden.benches = [
349
+ { x: gx + 140, y: gy + gh * 0.62 },
350
+ { x: gx + gw - 170, y: gy + gh * 0.62 },
351
+ ];
352
+ garden.picnic = { x: gx + gw / 2, y: gy + gh - 190 };
353
+ garden.swim = [[-55, -8], [-15, 14], [30, -14], [62, 10], [5, -30], [-40, 26]].map(([dx, dy]) => ({ x: gx + gw / 2 + 10 + dx, y: gy + gh * 0.42 + dy }));
354
+ const spots = [];
355
+ for (const [dx, dy] of [[-42, -6], [42, -6], [-30, 40], [34, 40], [0, -40], [0, 62]]) spots.push({ x: garden.smoke.x + dx, y: garden.smoke.y + dy, act: 'smoke' });
356
+ for (const dx of [-75, -25, 25, 75]) spots.push({ x: garden.cafe.x + dx, y: garden.cafe.y + 105, act: 'coffee' });
357
+ for (const dx of [-40, 75]) spots.push({ x: garden.cafe.x + dx, y: garden.cafe.y + 160, act: 'coffee' });
358
+ for (const b of garden.benches) for (const dx of [-38, 0, 38]) spots.push({ x: b.x + dx, y: b.y + 2, act: 'bench' });
359
+ for (const [dx, dy] of [[-60, -30], [0, -30], [60, -30], [-60, 50], [0, 50], [60, 50]]) spots.push({ x: garden.picnic.x + dx, y: garden.picnic.y + dy, act: 'picnic' });
360
+ for (let i = 0; i < 30; i++) {
361
+ const r = hash('stroll' + i);
362
+ spots.push({ x: gx + 70 + (r % (gw - 140)), y: gy + 300 + ((r >> 8) % Math.max(100, gh - 520)), act: i % 3 ? 'stroll' : 'phone' });
363
+ }
364
+ garden.spots = spots;
365
+ const trees = [];
366
+ const nt = Math.max(6, Math.round(gw / 90));
367
+ for (let i = 0; i < nt; i++) trees.push({ x: gx + 40 + i * ((gw - 80) / (nt - 1)), y: gy + 36, r: 26 + (hash('t' + i) % 10) });
368
+ for (let i = 0; i < nt; i++) if (Math.abs(gx + 40 + i * ((gw - 80) / (nt - 1)) - (gx + gw / 2)) > 70) trees.push({ x: gx + 40 + i * ((gw - 80) / (nt - 1)), y: gy + gh - 34, r: 24 + (hash('tb' + i) % 10) });
369
+ garden.trees = trees;
370
+ garden.sulk = { x: gx + gw - 80, y: gy + gh - 110 };
371
+ garden.gate = { x: gx + gw / 2, y: gy + gh };
372
+ return garden;
373
+ }
374
+
375
+ function computeLayout() {
376
+ const seats = new Map();
377
+ const buildings = S.buildings && S.buildings.length ? S.buildings : [{ id: 'main', name: 'Agent Hall', tool: 'claude' }];
378
+ const known = new Set(buildings.map((b) => b.id));
379
+ const bOf = (p) => (known.has(p.building) ? p.building : 'main');
380
+ const hq = buildings.find((b) => b.id === 'main') || buildings[0];
381
+ // blocks in reading order: HQ, park, the other buildings, then the empty lot for a new one
382
+ const others = buildings.filter((b) => b !== hq);
383
+ const order = [{ kind: 'building', b: hq }, { kind: 'park' }, ...others.map((b) => ({ kind: 'building', b })), { kind: 'lot' }];
384
+
385
+ // measure building heights
386
+ for (const blk of order) {
387
+ if (blk.kind !== 'building') continue;
388
+ const projects = S.projects.filter((p) => bOf(p) === blk.b.id);
389
+ blk.projects = projects;
390
+ const roomsH = layoutRooms(projects, 0, 0, new Map()).bottom;
391
+ const addRow = projects.length % 2 === 0 ? 220 + GAP : 0; // "+ room" spot under the rooms
392
+ blk.h = BPAD + BOSS_H + GAP + Math.max(roomsH, 0) + addRow + GAP + BPAD;
393
+ }
394
+ const rows = [];
395
+ order.forEach((blk, i) => {
396
+ blk.row = Math.floor(i / CITY_COLS);
397
+ blk.col = i % CITY_COLS;
398
+ rows[blk.row] = rows[blk.row] || { h: 0 };
399
+ if (blk.kind === 'building') rows[blk.row].h = Math.max(rows[blk.row].h, blk.h);
400
+ });
401
+ rows.forEach((r) => (r.h = Math.max(r.h, 900)));
402
+ const colX = [];
403
+ for (let c = 0; c < CITY_COLS; c++) colX[c] = AVENUE + c * (BLOCK_W + AVENUE);
404
+ let y = MARGIN;
405
+ for (const r of rows) {
406
+ r.y = y;
407
+ r.bottom = y + r.h;
408
+ r.sideY = r.bottom + 30;
409
+ r.road = { y: r.bottom + ROAD_GAP_TOP, h: ROAD_LANE * 4 };
410
+ y = r.road.y + r.road.h + ROAD_GAP_BOTTOM;
411
+ }
412
+ const avenues = [];
413
+ for (let c = 0; c <= CITY_COLS; c++) avenues.push(colX[0] - AVENUE / 2 + c * (BLOCK_W + AVENUE));
414
+
415
+ const rooms = [];
416
+ const bmap = {};
417
+ let garden = null;
418
+ let lot = null;
419
+ let boss = null;
420
+ let lobby = null;
421
+ for (const blk of order) {
422
+ const row = rows[blk.row];
423
+ const x = colX[blk.col];
424
+ if (blk.kind === 'park') {
425
+ garden = buildGarden(x + 10, row.y + 10, BLOCK_W - 20, row.h - 20);
426
+ garden.row = blk.row;
427
+ continue;
428
+ }
429
+ if (blk.kind === 'lot') {
430
+ lot = { x: x + 10, y: row.y + 10, w: BLOCK_W - 20, h: Math.min(row.h - 20, 560) };
431
+ continue;
432
+ }
433
+ const b = blk.b;
434
+ const rect = { x, y: row.y, w: BLOCK_W, h: row.h };
435
+ const spineX = x + BPAD + GAP / 2;
436
+ const x0 = x + BPAD + GAP;
437
+ const top = row.y + BPAD + BOSS_H + GAP;
438
+ const laid = layoutRooms(blk.projects, x0, top, seats);
439
+ for (const r of laid.rooms) {
440
+ r.building = b.id;
441
+ r.spineX = spineX;
442
+ }
443
+ rooms.push(...laid.rooms);
444
+ const n = blk.projects.length;
445
+ const last = laid.rooms[laid.rooms.length - 1];
446
+ const addRoom = n % 2 === 1 ? { x: x0 + ROOM_W + GAP, y: last.y, w: ROOM_W, h: 220 } : { x: x0, y: n ? laid.bottom + GAP : top, w: ROOM_W, h: 220 };
447
+ addRoom.building = b.id;
448
+ const sign = { x: x0, y: row.y + BPAD, w: 2 * ROOM_W + GAP, h: BOSS_H };
449
+ // In front of the building, between the sidewalk and the road: a bus stop,
450
+ // a bike rack and a car park with one bay per car or motorbike.
451
+ const roadY = row.bottom + ROAD_GAP_TOP;
452
+ const park = { top: row.bottom + 52, bottom: roadY - 16, x0: spineX + 330, x1: x + BLOCK_W - 30, stop: { x: spineX + 110, y: roadY - 30 } };
453
+ park.n = Math.floor((park.x1 - park.x0) / BAY_W);
454
+ park.rack = { x0: spineX + 190, x1: spineX + 300 };
455
+ park.rack.n = Math.floor((park.rack.x1 - park.rack.x0) / RACK_W);
456
+ bmap[b.id] = { b, rect, spineX, row: blk.row, entrance: { x: spineX, y: row.bottom + 10 }, sign, addRoom, hq: b === hq, park };
457
+ if (b === hq) {
458
+ boss = { x: x0, y: row.y + BPAD, w: ROOM_W, h: BOSS_H, building: b.id };
459
+ boss.door = { x: boss.x + ROOM_W / 2, y: boss.y + BOSS_H };
460
+ boss.hallY = boss.y + BOSS_H + GAP / 2;
461
+ boss.spineX = spineX;
462
+ boss.visitor = { x: boss.x + ROOM_W / 2 - 150, y: boss.y + 150 };
463
+ lobby = { x: x0 + ROOM_W + GAP, y: row.y + BPAD, w: ROOM_W, h: BOSS_H };
464
+ // the lobby doubles as the meeting room: a door to the corridor, seats round a table
465
+ lobby.door = { x: lobby.x + ROOM_W / 2, y: lobby.y + BOSS_H };
466
+ lobby.hallY = lobby.y + BOSS_H + GAP / 2;
467
+ const cx = lobby.x + ROOM_W / 2;
468
+ lobby.seats = [-1, 0, 1].flatMap((k) => [{ x: cx + k * 95, y: lobby.y + 182 }, { x: cx + k * 95 + 30, y: lobby.y + 118 }]);
469
+ }
470
+ }
471
+ // Bored agents line up on the sidewalk in front of the park, facing the boss (the screen).
472
+ const front = [];
473
+ for (let i = 0; i < 12; i++) front.push({ x: garden.x + 70 + i * 62, y: rows[garden.row].sideY });
474
+
475
+ const width = colX[CITY_COLS - 1] + BLOCK_W + AVENUE;
476
+ L = {
477
+ rooms,
478
+ roomsById: Object.fromEntries(rooms.map((r) => [r.id, r])),
479
+ seats,
480
+ rows,
481
+ avenues,
482
+ garden,
483
+ lot,
484
+ boss,
485
+ lobby,
486
+ buildings: bmap,
487
+ hqId: hq.id,
488
+ entrance: bmap[hq.id].entrance,
489
+ front,
490
+ roads: rows.map((r) => r.road),
491
+ road: rows[0].road,
492
+ bounds: { x: 0, y: 0, w: width, h: y },
493
+ };
494
+ }
495
+
496
+ // ------------------------------------------------------------------ sprites & movement
497
+
498
+ function pickSpot(agentId) {
499
+ const used = new Set([...spotOf.entries()].filter(([id]) => id !== agentId).map(([, i]) => i));
500
+ const free = L.garden.spots.map((s, i) => i).filter((i) => !used.has(i));
501
+ if (!free.length) return hash(agentId) % L.garden.spots.length;
502
+ // Prefer the social spots (smoking, coffee, benches) over strolling.
503
+ const social = free.filter((i) => L.garden.spots[i].act !== 'stroll' && L.garden.spots[i].act !== 'phone');
504
+ const pool = social.length && Math.random() < 0.85 ? social : free;
505
+ return pool[Math.floor(Math.random() * pool.length)];
506
+ }
507
+
508
+ function desiredFor(a, depth = 0) {
509
+ if (a.status === 'offline') return null;
510
+ const order = orders.get(a.id);
511
+ if (order && depth === 0) {
512
+ if (order.until > Date.now() && order.status === a.status && !BUSY.has(a.status)) return order.dest;
513
+ orders.delete(a.id);
514
+ }
515
+ const gm = a.game;
516
+ if (gm && depth === 0) {
517
+ if (gm.oneOnOne) return { zone: 'boss', x: L.boss.visitor.x, y: L.boss.visitor.y, act: 'oneonone', key: 'boss' };
518
+ if (gm.asking && Date.now() - (gm.askedAt || 0) < 60000) {
519
+ const askers = S.agents.filter((x) => x.game && x.game.asking && !x.game.oneOnOne && x.status === 'idle');
520
+ const i = Math.max(0, askers.findIndex((x) => x.id === a.id)) % L.front.length;
521
+ return { zone: 'front', x: L.front[i].x, y: L.front[i].y, act: 'ask', key: 'front' + i };
522
+ }
523
+ if (gm.sulking) {
524
+ const k = hash(a.id) % 5;
525
+ return { zone: 'garden', x: L.garden.sulk.x - k * 34, y: L.garden.sulk.y + (k % 2) * 20, act: 'sulk', key: 'sulk' + k };
526
+ }
527
+ }
528
+ const meeting = a.meeting && depth === 0 && (S.meetings || []).find((m) => m.id === a.meeting);
529
+ if (meeting) {
530
+ const i = Math.max(0, meeting.participants.indexOf(a.id)) % L.lobby.seats.length;
531
+ const s = L.lobby.seats[i];
532
+ return { zone: 'lobby', x: s.x, y: s.y, act: 'meeting', key: 'meet' + i };
533
+ }
534
+ if (a.visit && depth === 0) {
535
+ const t = agentById(a.visit.targetId);
536
+ const td = t && desiredFor(t, 1);
537
+ if (td) {
538
+ // Stand at the front-left corner of a colleague's desk, or beside them in the garden.
539
+ const pos = td.desk ? { x: td.desk.x - 6, y: td.desk.y + td.desk.h + 4 } : { x: td.x + 34, y: td.y + 6 };
540
+ return { zone: td.zone, x: pos.x, y: pos.y, act: 'visit', key: 'visit:' + a.visit.targetId + td.key };
541
+ }
542
+ }
543
+ // Right after finishing, an agent stays at its desk; the garden comes later.
544
+ const idleSince = a.game?.idleSince ?? a.idleSince;
545
+ const atDeskStill = a.status === 'idle' && idleSince && Date.now() - idleSince < (S.game?.gardenAfter ?? 300000);
546
+ if (a.status === 'idle' && !atDeskStill) {
547
+ if (!spotOf.has(a.id)) spotOf.set(a.id, pickSpot(a.id));
548
+ const s = L.garden.spots[spotOf.get(a.id)];
549
+ return { zone: 'garden', x: s.x, y: s.y, act: s.act, key: 'g' + spotOf.get(a.id) };
550
+ }
551
+ const seat = L.seats.get(a.id);
552
+ if (!seat) return null;
553
+ return { ...seat, key: `seat:${seat.zone}:${Math.round(seat.x)},${Math.round(seat.y)}` };
554
+ }
555
+
556
+ // Where a zone is: a room or corridor inside a building, the park, the sidewalk or an entrance.
557
+ function zoneInfo(zone) {
558
+ zone = zone || 'hall:' + L.hqId;
559
+ if (zone === 'boss') return { kind: 'room', building: L.hqId, room: L.boss };
560
+ if (zone === 'lobby') return { kind: 'room', building: L.hqId, room: L.lobby };
561
+ if (zone.startsWith('room:')) {
562
+ const r = L.roomsById[zone.slice(5)];
563
+ return r ? { kind: 'room', building: r.building, room: r } : { kind: 'hall', building: L.hqId };
564
+ }
565
+ if (zone === 'garden') return { kind: 'garden' };
566
+ if (zone === 'front' || zone === 'side') return { kind: 'side' };
567
+ const b = zone.split(':')[1];
568
+ return { kind: zone.startsWith('out') ? 'out' : 'hall', building: L.buildings[b] ? b : L.hqId };
569
+ }
570
+ const buildingOf = (a) => {
571
+ const id = projectById(a.projectId)?.building;
572
+ return L.buildings[id] ? id : L.hqId;
573
+ };
574
+ const nearestRow = (y) => L.rows.reduce((best, r, i) => (Math.abs(r.sideY - y) < Math.abs(L.rows[best].sideY - y) ? i : best), 0);
575
+
576
+ // Path from a zone to its door on the sidewalk (and the row of that sidewalk).
577
+ function exitPath(sp, info) {
578
+ const pts = [];
579
+ if (info.kind === 'side') return { pts, x: sp.x, row: nearestRow(sp.y) };
580
+ if (info.kind === 'garden') {
581
+ const g = L.garden;
582
+ pts.push({ x: g.gate.x, y: Math.max(sp.y, g.y + g.h - 60), zone: 'garden' });
583
+ pts.push({ x: g.gate.x, y: L.rows[g.row].sideY, zone: 'side' });
584
+ return { pts, x: g.gate.x, row: g.row };
585
+ }
586
+ const bl = L.buildings[info.building];
587
+ const hall = 'hall:' + info.building;
588
+ if (info.kind === 'room') {
589
+ const r = info.room;
590
+ pts.push({ x: r.door.x, y: r.door.y - 24, zone: 'room' });
591
+ pts.push({ x: r.door.x, y: r.hallY, zone: hall });
592
+ pts.push({ x: bl.spineX, y: r.hallY, zone: hall });
593
+ } else pts.push({ x: bl.spineX, y: sp.y, zone: hall });
594
+ pts.push({ x: bl.spineX, y: L.rows[bl.row].sideY, zone: 'side' });
595
+ return { pts, x: bl.spineX, row: bl.row };
596
+ }
597
+
598
+ // Waypoints from the sprite to dest through corridors, sidewalks and avenues.
599
+ function route(sp, dest) {
600
+ const loose = (z) => !z || z.startsWith('hall') || z.startsWith('out') || z === 'side' || z === 'front';
601
+ if (sp.zone === dest.zone && !loose(sp.zone)) return [{ x: dest.x, y: dest.y, zone: dest.zone }];
602
+ const from = zoneInfo(sp.zone);
603
+ const to = zoneInfo(dest.zone);
604
+ const inside = (i) => i.kind === 'room' || i.kind === 'hall';
605
+ // same building: stay inside, walk the corridor
606
+ if (inside(from) && inside(to) && from.building === to.building) {
607
+ const bl = L.buildings[from.building];
608
+ const hall = 'hall:' + from.building;
609
+ const pts = [];
610
+ if (from.kind === 'room') {
611
+ pts.push({ x: from.room.door.x, y: from.room.door.y - 24, zone: sp.zone });
612
+ pts.push({ x: from.room.door.x, y: from.room.hallY, zone: hall });
613
+ pts.push({ x: bl.spineX, y: from.room.hallY, zone: hall });
614
+ } else pts.push({ x: bl.spineX, y: sp.y, zone: hall });
615
+ if (to.kind === 'room') {
616
+ pts.push({ x: bl.spineX, y: to.room.hallY, zone: hall });
617
+ pts.push({ x: to.room.door.x, y: to.room.hallY, zone: hall });
618
+ pts.push({ x: to.room.door.x, y: to.room.door.y - 24, zone: dest.zone });
619
+ }
620
+ pts.push({ x: dest.x, y: dest.y, zone: dest.zone });
621
+ return pts;
622
+ }
623
+ const out = exitPath(sp, from);
624
+ out.pts.forEach((p, i) => (p.zone = p.zone === 'room' ? sp.zone : p.zone));
625
+ const inn = exitPath({ x: dest.x, y: dest.y }, to);
626
+ const back = inn.pts.reverse();
627
+ // the room door waypoint belongs to the destination room
628
+ back.forEach((p) => (p.zone = p.zone === 'room' ? dest.zone : p.zone));
629
+ const pts = [...out.pts];
630
+ if (out.row !== inn.row) {
631
+ // walk to the closest avenue, along it to the other row, then on
632
+ const mid = (out.x + inn.x) / 2;
633
+ const ave = L.avenues.reduce((best, x) => (Math.abs(x - mid) < Math.abs(best - mid) ? x : best), L.avenues[0]);
634
+ pts.push({ x: ave, y: L.rows[out.row].sideY, zone: 'side' });
635
+ pts.push({ x: ave, y: L.rows[inn.row].sideY, zone: 'side' });
636
+ }
637
+ pts.push(...back.filter((p) => p.zone !== 'side' || p === back[0]));
638
+ if (to.kind === 'side' && !back.length) pts.push({ x: dest.x, y: L.rows[inn.row].sideY, zone: 'side' });
639
+ pts.push({ x: dest.x, y: dest.y, zone: dest.zone });
640
+ return pts;
641
+ }
642
+
643
+ // Walk out of the building and disappear there. A fired agent first packs up at
644
+ // the spot, then carries the box out.
645
+ function walkOut(sp, a) {
646
+ if (sp.hidden) return cancelArrival(sp);
647
+ sp.leaving = true;
648
+ const slot = !a.subagent && slotOf(a.id);
649
+ const fired = firedIds.delete(a.id);
650
+ if (fired) {
651
+ sp.box = true;
652
+ sp.packUntil = performance.now() + 1800;
653
+ }
654
+ // Without a car or a motorbike there is no getaway scene: the box goes on the bike or the bus.
655
+ if (fired && (!slot || slot.kind === 'car' || slot.kind === 'moto')) {
656
+ const scene = startFireScene(sp, a);
657
+ sp.dest = { zone: 'side', x: scene.door.x, y: scene.door.y, act: 'walk', key: 'car' };
658
+ setPath(sp, route(sp, sp.dest));
659
+ sp.speed *= 1.25; // stomping off
660
+ return;
661
+ }
662
+ if (slot) return walkToVehicle(sp, a, slot);
663
+ const ent = L.buildings[buildingOf(a)].entrance;
664
+ sp.dest = { zone: 'out:' + buildingOf(a), x: ent.x, y: ent.y, act: 'walk', key: 'out' };
665
+ setPath(sp, route(sp, sp.dest));
666
+ }
667
+
668
+ function syncSprites(instant) {
669
+ const now = performance.now();
670
+ syncParking();
671
+ for (const a of S.agents) {
672
+ if (a.status !== 'idle' || !desiredFor(a)?.zone?.startsWith('garden')) spotOf.delete(a.id);
673
+ let sp = sprites.get(a.id);
674
+ const des = desiredFor(a);
675
+ if (!des) {
676
+ if (sp && !sp.leaving) walkOut(sp, a);
677
+ continue;
678
+ }
679
+ if (!sp) {
680
+ const ent = L.buildings[buildingOf(a)].entrance;
681
+ const start = instant ? des : { x: ent.x, y: ent.y, zone: 'out:' + buildingOf(a) };
682
+ sp = { id: a.id, x: start.x, y: start.y, zone: start.zone, path: [], phase: 0, facing: 1, dest: null, nextWander: now + 20000 + Math.random() * 40000 };
683
+ sprites.set(a.id, sp);
684
+ if (!instant) startArrival(sp, a);
685
+ }
686
+ if (sp.leaving || !sp.dest || sp.dest.key !== des.key) {
687
+ sp.leaving = false;
688
+ sp.waitingBus = null;
689
+ sp.onArrive = null;
690
+ sp.dest = des;
691
+ setPath(sp, route(sp, des));
692
+ }
693
+ }
694
+ for (const [id, sp] of sprites) {
695
+ const a = agentById(id);
696
+ if (a) {
697
+ sp.ghost = a;
698
+ continue;
699
+ }
700
+ // Gone from the office (e.g. a finished subagent): walk out, then disappear.
701
+ if (!sp.ghost) sprites.delete(id);
702
+ else if (!sp.leaving) walkOut(sp, sp.ghost);
703
+ }
704
+ for (const id of [...spotOf.keys()]) if (!agentById(id)) spotOf.delete(id);
705
+ }
706
+
707
+ const SPEED = 170;
708
+ // Long trips across the city are walked faster (up to a jog), short ones at a stroll.
709
+ function setPath(sp, pts) {
710
+ let len = 0;
711
+ let prev = { x: sp.x, y: sp.y };
712
+ for (const q of pts) {
713
+ len += Math.hypot(q.x - prev.x, q.y - prev.y);
714
+ prev = q;
715
+ }
716
+ sp.path = pts;
717
+ sp.speed = SPEED * Math.min(3.5, Math.max(1, len / 1500));
718
+ }
719
+ function stepSprites(dt, now) {
720
+ for (const [id, sp] of sprites) {
721
+ const a = agentById(id);
722
+ if (sp.hidden || (sp.waitingBus && !sp.path.length)) {
723
+ sp.walking = false;
724
+ continue;
725
+ }
726
+ if (sp.packUntil > now) {
727
+ sp.walking = false;
728
+ continue;
729
+ }
730
+ if (sp.path.length) {
731
+ const t = sp.path[0];
732
+ const dx = t.x - sp.x;
733
+ const dy = t.y - sp.y;
734
+ const d = Math.hypot(dx, dy);
735
+ const step = (sp.speed || SPEED) * dt;
736
+ if (d <= step) {
737
+ sp.x = t.x;
738
+ sp.y = t.y;
739
+ sp.zone = t.zone;
740
+ sp.path.shift();
741
+ } else {
742
+ sp.x += (dx / d) * step;
743
+ sp.y += (dy / d) * step;
744
+ if (Math.abs(dx) > 1) sp.facing = dx < 0 ? -1 : 1;
745
+ }
746
+ sp.walking = true;
747
+ sp.phase += dt * 11;
748
+ } else {
749
+ sp.walking = false;
750
+ if (sp.leaving) {
751
+ if (sp.scene) sp.scene.boarded = true;
752
+ const next = sp.onArrive;
753
+ sp.onArrive = null;
754
+ if (next && next()) continue;
755
+ sprites.delete(id);
756
+ continue;
757
+ }
758
+ }
759
+ // Idle agents drift between garden spots now and then.
760
+ if (a && a.status === 'idle' && !a.visit && !orders.has(id) && !sp.walking && now > sp.nextWander) {
761
+ sp.nextWander = now + 25000 + Math.random() * 50000;
762
+ spotOf.set(id, pickSpot(id));
763
+ const des = desiredFor(a);
764
+ sp.dest = des;
765
+ setPath(sp, route(sp, des));
766
+ }
767
+ }
768
+ }
769
+
770
+ // ------------------------------------------------------------------ camera & input
771
+
772
+ const canvas = $('#world');
773
+ let ctx = canvas.getContext('2d');
774
+ const cam = { x: 0, y: 0, s: 1 };
775
+ let viewW = 0;
776
+ let viewH = 0;
777
+ let dpr = 1;
778
+ let mouse = null; // world coords
779
+ let hover = null;
780
+
781
+ function resizeCanvas() {
782
+ const r = canvas.getBoundingClientRect();
783
+ dpr = window.devicePixelRatio || 1;
784
+ viewW = r.width;
785
+ viewH = r.height;
786
+ canvas.width = Math.round(r.width * dpr);
787
+ canvas.height = Math.round(r.height * dpr);
788
+ }
789
+
790
+ function fitCamera() {
791
+ if (!L || !viewW) return;
792
+ if (focus) {
793
+ focus = null;
794
+ $('#focus-bar').hidden = true;
795
+ }
796
+ const b = L.bounds;
797
+ cam.s = Math.min(viewW / b.w, viewH / b.h, 1.15);
798
+ cam.x = b.x + b.w / 2 - viewW / cam.s / 2;
799
+ cam.y = b.y + b.h / 2 - viewH / cam.s / 2;
800
+ }
801
+
802
+ // ---- room focus: a click on a room zooms into it and dims the rest of the
803
+ // city; ✕ (or Esc) flies back to where the camera was.
804
+ let focus = null; // { id, back: camera before the first focus }
805
+ let camAnim = null;
806
+ function flyTo(to, ms = 450) {
807
+ camAnim = { from: { ...cam }, to, t0: performance.now(), ms };
808
+ }
809
+ function stepCamera(now) {
810
+ if (!camAnim) return;
811
+ const k = Math.min(1, (now - camAnim.t0) / camAnim.ms);
812
+ const e = 1 - Math.pow(1 - k, 3);
813
+ const { from, to } = camAnim;
814
+ // interpolate the view centre and the scale so the zoom feels straight
815
+ const cx = from.x + viewW / from.s / 2 + (to.x + viewW / to.s / 2 - (from.x + viewW / from.s / 2)) * e;
816
+ const cy = from.y + viewH / from.s / 2 + (to.y + viewH / to.s / 2 - (from.y + viewH / from.s / 2)) * e;
817
+ cam.s = from.s * Math.pow(to.s / from.s, e);
818
+ cam.x = cx - viewW / cam.s / 2;
819
+ cam.y = cy - viewH / cam.s / 2;
820
+ if (k >= 1) camAnim = null;
821
+ }
822
+ function roomCamera(room) {
823
+ const pad = 50;
824
+ const s = Math.min(2.8, viewW / (room.w + pad * 2), viewH / (room.h + pad * 2));
825
+ return { s, x: room.x + room.w / 2 - viewW / s / 2, y: room.y + room.h / 2 - viewH / s / 2 };
826
+ }
827
+ function focusRoom(id) {
828
+ const room = L && L.roomsById[id];
829
+ if (!room) return;
830
+ focus = { id, back: focus ? focus.back : { ...cam } };
831
+ flyTo(roomCamera(room));
832
+ showFocusBar();
833
+ }
834
+ function showFocusBar() {
835
+ const p = projectById(focus.id);
836
+ $('#focus-name').textContent = p ? p.name : '';
837
+ $('#focus-bar').hidden = false;
838
+ }
839
+ function leaveFocus() {
840
+ if (!focus) return;
841
+ const back = focus.back;
842
+ focus = null;
843
+ $('#focus-bar').hidden = true;
844
+ if (back) flyTo(back);
845
+ }
846
+ $('#focus-close').onclick = leaveFocus;
847
+ // Everything but the focused room fades into the background.
848
+ function drawFocusDim() {
849
+ const room = focus && L.roomsById[focus.id];
850
+ if (!room) return;
851
+ ctx.save();
852
+ ctx.beginPath();
853
+ ctx.rect(cam.x - 20, cam.y - 20, viewW / cam.s + 40, viewH / cam.s + 40);
854
+ ctx.rect(room.x - 6, room.y - 6, room.w + 12, room.h + 12);
855
+ ctx.fillStyle = 'rgba(16,20,32,0.72)';
856
+ ctx.fill('evenodd');
857
+ ctx.restore();
858
+ }
859
+
860
+ const toWorld = (sx, sy) => ({ x: sx / cam.s + cam.x, y: sy / cam.s + cam.y });
861
+
862
+ let drag = null;
863
+ // ---- right-click menu: fun orders for idle agents, work actions for everyone
864
+ const orders = new Map(); // agentId -> { dest, until, status }
865
+ const BUSY = new Set(['working', 'waiting']);
866
+ const ORDER_MS = 3 * 60 * 1000;
867
+ const FUN = [
868
+ { id: 'swim', icon: '🏊' },
869
+ { id: 'smoke', icon: '🚬' },
870
+ { id: 'coffee', icon: '☕' },
871
+ { id: 'bench', icon: '🪑' },
872
+ { id: 'picnic', icon: '🧺' },
873
+ { id: 'stroll', icon: '🌳' },
874
+ { id: 'dance', icon: '💃' },
875
+ { id: 'desk', icon: '💻' },
876
+ ];
877
+
878
+ function freeSpot(list, agentId) {
879
+ const taken = new Set([...orders.entries()].filter(([id]) => id !== agentId).map(([, o]) => `${Math.round(o.dest.x)},${Math.round(o.dest.y)}`));
880
+ const free = list.filter((p) => !taken.has(`${Math.round(p.x)},${Math.round(p.y)}`));
881
+ const pool = free.length ? free : list;
882
+ return pool[Math.floor(Math.random() * pool.length)];
883
+ }
884
+
885
+ function giveOrder(a, kind) {
886
+ const sp = sprites.get(a.id);
887
+ let dest;
888
+ if (kind === 'swim') {
889
+ const p = freeSpot(L.garden.swim, a.id);
890
+ dest = { zone: 'garden', x: p.x, y: p.y, act: 'swim' };
891
+ } else if (kind === 'dance') {
892
+ dest = { zone: sp ? sp.zone : 'garden', x: sp ? sp.x : L.garden.x + 200, y: sp ? sp.y : L.garden.y + 300, act: 'dance' };
893
+ } else if (kind === 'desk') {
894
+ const seat = L.seats.get(a.id);
895
+ if (!seat) return toast(tx('menu.noDesk', { name: a.name }), 'err');
896
+ dest = { ...seat };
897
+ } else {
898
+ const p = freeSpot(L.garden.spots.filter((x) => x.act === kind || (kind === 'stroll' && (x.act === 'stroll' || x.act === 'phone'))), a.id);
899
+ dest = { zone: 'garden', x: p.x, y: p.y, act: kind === 'stroll' ? 'stroll' : p.act };
900
+ }
901
+ dest.key = `order:${kind}:${Math.round(dest.x)},${Math.round(dest.y)}`;
902
+ orders.set(a.id, { dest, until: Date.now() + ORDER_MS, status: a.status });
903
+ bubbles.set(a.id, { text: pick('say.' + kind), until: performance.now() + 6000, kind: 'visit' });
904
+ syncSprites(false);
905
+ }
906
+
907
+ function closeMenu() {
908
+ $('#ctx-menu').hidden = true;
909
+ }
910
+
911
+ function openMenu(a, clientX, clientY) {
912
+ const menu = $('#ctx-menu');
913
+ const online = a.status !== 'offline';
914
+ const canFun = online && !BUSY.has(a.status);
915
+ const item = (act, icon, label, enabled = true, cls = '') => `<button data-menu="${act}" ${cls ? `class="${cls}"` : ''} ${enabled ? '' : 'disabled'}><span>${icon}</span>${label}</button>`;
916
+ menu.innerHTML = `
917
+ <div class="m-head"><b>${esc(a.name)}</b><span>${esc(roleLabel(a.role))} · ${statusLabel(a.status)}</span></div>
918
+ ${canFun ? `<div class="m-sec">${tx('menu.fun')}</div>${FUN.map((f) => item('fun:' + f.id, f.icon, tx('fun.' + f.id))).join('')}` : ''}
919
+ <div class="m-sec">${tx('menu.work')}</div>
920
+ ${item('open', '🖥', a.external ? tx('menu.watch') : tx('menu.terminal'))}
921
+ ${a.game ? item('oneonone', '🤝', tx('menu.oneOnOne'), online) + item('praise', '👏', tx('menu.praise'), online) : ''}
922
+ ${!a.external ? item('visit', '🚶', tx('menu.visit'), online) : ''}
923
+ ${!a.external ? (online ? item('stop', '🏠', tx('menu.stop')) : item('start', '☀️', tx('menu.start'))) : ''}
924
+ ${!a.subagent ? `<div class="m-sep"></div>${item('fire', '🗑', tx('menu.fire'), true, 'danger')}` : ''}`;
925
+ menu.hidden = false;
926
+ // offsetWidth/Height ignore the pop-in scale animation.
927
+ menu.style.left = Math.max(8, Math.min(clientX, window.innerWidth - menu.offsetWidth - 8)) + 'px';
928
+ menu.style.top = Math.max(8, Math.min(clientY, window.innerHeight - menu.offsetHeight - 8)) + 'px';
929
+ menu.dataset.agent = a.id;
930
+ delete menu.dataset.room;
931
+ }
932
+
933
+ // ---- room right-click menu
934
+ const ROOM_COLORS = ['#e76f51', '#2a9d8f', '#e9c46a', '#8ab17d', '#9b5de5', '#f15bb5', '#00bbf9', '#f4a261', '#43aa8b', '#ef476f', '#118ab2', '#ffd166'];
935
+
936
+ function openRoomMenu(projectId, clientX, clientY, deskRole) {
937
+ const p = projectById(projectId);
938
+ if (!p) return;
939
+ const menu = $('#ctx-menu');
940
+ const ags = S.agents.filter((a) => a.projectId === p.id && !a.subagent);
941
+ const offline = ags.filter((a) => a.status === 'offline' && !a.external).length;
942
+ const removable = (p.extraDesks || 0) + (p.extraLeadDesks || 0) > 0;
943
+ const item = (act, icon, label, enabled = true) => `<button data-room="${act}" ${enabled ? '' : 'disabled'}><span>${icon}</span>${label}</button>`;
944
+ menu.innerHTML = `
945
+ <div class="m-head"><b>🏢 ${esc(p.name)}</b><span>${esc(p.path)}</span></div>
946
+ <div class="m-sec">${tx('rmenu.desks')}</div>
947
+ ${item('add-desk', '➕', tx('rmenu.addDesk'))}
948
+ ${item('add-lead', '👑', tx('rmenu.addLead'))}
949
+ ${item('remove-desk', '➖', tx('rmenu.removeDesk'), removable)}
950
+ <div class="m-sec">${tx('rmenu.room')}</div>
951
+ ${item('hire', '🧑‍💼', deskRole ? tx('rmenu.hireHere', { role: roleLabel(deskRole) }) : tx('rmenu.hire'))}
952
+ ${item('board', '📌', tx('board.title'), !p.auto)}
953
+ ${item('announce', '📢', tx('rmenu.announce'), !p.auto)}
954
+ ${offline ? item('wake', '☀️', tx('room.wake').replace(/^☀️\s*/, '')) : ''}
955
+ ${item('rename', '✏️', tx('rmenu.rename'))}
956
+ <div class="m-colors">${ROOM_COLORS.map((c) => `<button class="swatch ${c === p.color ? 'on' : ''}" data-color="${c}" style="background:${c}" title="${tx('rmenu.color')}"></button>`).join('')}</div>
957
+ ${S.buildings.filter((b) => b.id !== (p.building || 'main')).map((b) => item('move:' + b.id, '🚚', tx('rmenu.moveTo', { name: esc(b.name) }))).join('')}
958
+ ${item('folder', '📂', tx('rmenu.folder'))}
959
+ ${p.auto ? item('keep', '📌', tx('temp.save')) : item('close', '🗑', tx('room.close'))}`;
960
+ menu.hidden = false;
961
+ menu.style.left = Math.max(8, Math.min(clientX, window.innerWidth - menu.offsetWidth - 8)) + 'px';
962
+ menu.style.top = Math.max(8, Math.min(clientY, window.innerHeight - menu.offsetHeight - 8)) + 'px';
963
+ menu.dataset.room = p.id;
964
+ menu.dataset.deskRole = deskRole || '';
965
+ delete menu.dataset.agent;
966
+ }
967
+
968
+ async function roomAction(act, p, deskRole) {
969
+ const patch = (body) => api('PATCH', `/api/projects/${p.id}`, body);
970
+ if (act.startsWith('move:')) await patch({ building: act.slice(5) });
971
+ else if (act === 'add-desk') await patch({ extraDesks: (p.extraDesks || 0) + 1 });
972
+ else if (act === 'add-lead') await patch({ extraLeadDesks: (p.extraLeadDesks || 0) + 1 });
973
+ else if (act === 'remove-desk') {
974
+ if (p.extraDesks > 0) await patch({ extraDesks: p.extraDesks - 1 });
975
+ else await patch({ extraLeadDesks: Math.max(0, (p.extraLeadDesks || 0) - 1) });
976
+ } else if (act === 'hire') openHireModal(p.id, deskRole || null, true);
977
+ else if (act === 'announce') openRoomModal(p.id);
978
+ else if (act === 'board') openBoard(p.id);
979
+ else if (act === 'wake') {
980
+ for (const a of S.agents.filter((x) => x.projectId === p.id && x.status === 'offline' && !x.external)) {
981
+ await api('POST', `/api/agents/${a.id}/start`).catch((err) => toast(`${a.name}: ${err.message}`, 'err'));
982
+ }
983
+ } else if (act === 'rename') openRenameModal(p);
984
+ else if (act === 'folder') await api('POST', `/api/projects/${p.id}/open-folder`);
985
+ else if (act === 'keep') {
986
+ await api('POST', `/api/projects/${p.id}/save`);
987
+ toast(tx('temp.saved', { name: p.name }), 'ok');
988
+ } else if (act === 'close') {
989
+ const n = S.agents.filter((a) => a.projectId === p.id && !a.external).length;
990
+ if (confirm(tx('room.confirmClose', { name: p.name, n }))) await api('DELETE', `/api/projects/${p.id}`);
991
+ }
992
+ }
993
+
994
+ // Create or edit a building (an office / team of the city).
995
+ function openBuildingModal(id) {
996
+ const b = id ? S.buildings.find((x) => x.id === id) : null;
997
+ const tools = toolsCache || [];
998
+ const colors = ['#3b3447', '#2f3d4f', '#3d4a3a', '#4a3a3a', '#3a3f55', '#4a4334', '#2f4a4a', '#47354a', '#5a3d2b', '#25424f'];
999
+ let color = b ? b.color : colors[S.buildings.length % colors.length];
1000
+ const toolOpts = (tools.length ? tools : [{ id: 'claude', label: 'Claude Code', icon: '✳', installed: true }])
1001
+ .map((t) => `<option value="${t.id}" ${t.id === (b ? b.tool : 'claude') ? 'selected' : ''}>${t.icon} ${esc(t.label)}${t.installed ? '' : tx('hire.notInstalled')}</option>`)
1002
+ .join('');
1003
+ const rooms = b ? S.projects.filter((p) => (p.building || 'main') === b.id).length : 0;
1004
+ openModal(
1005
+ `<h3>${b ? tx('bmodal.editTitle', { name: esc(b.name) }) : tx('bmodal.newTitle')}</h3>
1006
+ <div class="sub">${tx('bmodal.sub')}</div>
1007
+ <div class="row">
1008
+ <div><label>${tx('bmodal.name')}</label><input id="f-bname" value="${esc(b ? b.name : '')}" placeholder="${tx('bmodal.namePh')}" autofocus></div>
1009
+ <div><label>${tx('bmodal.company')}</label><input id="f-bcompany" value="${esc(b ? b.company || '' : (S.buildings[0] && S.buildings[0].company) || 'Getir')}"></div>
1010
+ </div>
1011
+ <label>${tx('bmodal.tool')}</label>
1012
+ <select id="f-btool">${toolOpts}</select>
1013
+ <label>${tx('bmodal.color')}</label>
1014
+ <div class="m-colors big">${colors.map((c) => `<button type="button" class="swatch ${c === color ? 'on' : ''}" data-c="${c}" style="background:${c}"></button>`).join('')}</div>
1015
+ <div class="err"></div>
1016
+ <div class="foot">
1017
+ ${b && b.id !== 'main' ? `<button class="danger left" id="f-bdel">${tx('bmodal.delete')}</button>` : ''}
1018
+ ${b ? `<button id="f-broom">${tx('bmodal.addRoom')}</button>` : ''}
1019
+ <button data-close>${tx('common.cancel')}</button>
1020
+ <button class="primary" id="f-ok">${b ? tx('common.save') : tx('bmodal.create')}</button>
1021
+ </div>`,
1022
+ (m) => {
1023
+ m.querySelectorAll('[data-c]').forEach((el) =>
1024
+ el.addEventListener('click', () => {
1025
+ color = el.dataset.c;
1026
+ m.querySelectorAll('[data-c]').forEach((x) => x.classList.toggle('on', x === el));
1027
+ })
1028
+ );
1029
+ $('#f-ok', m).onclick = async () => {
1030
+ const body = { name: $('#f-bname', m).value.trim(), company: $('#f-bcompany', m).value.trim(), tool: $('#f-btool', m).value, color };
1031
+ if (!body.name) return formError(m, tx('bmodal.needName'));
1032
+ try {
1033
+ const saved = b ? await api('PATCH', `/api/buildings/${b.id}`, body) : await api('POST', '/api/buildings', body);
1034
+ closeModal();
1035
+ if (!b) {
1036
+ toast(tx('bmodal.created', { name: saved.name }), 'ok');
1037
+ setTimeout(() => openProjectModal(saved.id), 250);
1038
+ }
1039
+ } catch (err) {
1040
+ formError(m, err.message);
1041
+ }
1042
+ };
1043
+ const del = $('#f-bdel', m);
1044
+ if (del)
1045
+ del.onclick = async () => {
1046
+ if (!confirm(tx('bmodal.confirmDelete', { name: b.name, n: rooms }))) return;
1047
+ await api('DELETE', `/api/buildings/${b.id}`).catch((err) => toast(err.message, 'err'));
1048
+ closeModal();
1049
+ };
1050
+ const addRoom = $('#f-broom', m);
1051
+ if (addRoom) addRoom.onclick = () => openProjectModal(b.id);
1052
+ }
1053
+ );
1054
+ if (!toolsCache) loadTools().then(() => {});
1055
+ }
1056
+
1057
+ function openRenameModal(p) {
1058
+ openModal(
1059
+ `<h3>${tx('rmenu.renameTitle')}</h3>
1060
+ <div class="sub">${esc(p.path)}</div>
1061
+ <label>${tx('project.name')}</label>
1062
+ <input id="f-name" value="${esc(p.name)}" autofocus>
1063
+ <div class="err"></div>
1064
+ <div class="foot"><button data-close>${tx('common.cancel')}</button><button class="primary" id="f-ok">${tx('common.save')}</button></div>`,
1065
+ (m) => {
1066
+ const save = async () => {
1067
+ const name = $('#f-name', m).value.trim();
1068
+ if (!name) return;
1069
+ try {
1070
+ await api('PATCH', `/api/projects/${p.id}`, { name });
1071
+ closeModal();
1072
+ } catch (err) {
1073
+ formError(m, err.message);
1074
+ }
1075
+ };
1076
+ $('#f-ok', m).onclick = save;
1077
+ $('#f-name', m).addEventListener('keydown', (e) => e.key === 'Enter' && save());
1078
+ }
1079
+ );
1080
+ }
1081
+
1082
+ canvas.addEventListener('contextmenu', (e) => {
1083
+ e.preventDefault();
1084
+ const hit = hitTest(toWorld(e.offsetX, e.offsetY));
1085
+ if (hit?.type === 'room' || hit?.type === 'emptyDesk') return openRoomMenu(hit.type === 'room' ? hit.id : hit.projectId, e.clientX, e.clientY, hit.role);
1086
+ if (hit?.type !== 'agent') return closeMenu();
1087
+ const a = agentById(hit.id);
1088
+ if (!a) return;
1089
+ // A working agent must not be disturbed: no menu at all.
1090
+ if (BUSY.has(a.status)) {
1091
+ closeMenu();
1092
+ return toast(tx('menu.busy', { name: a.name }), 'info');
1093
+ }
1094
+ openMenu(a, e.clientX, e.clientY);
1095
+ });
1096
+
1097
+ $('#ctx-menu').addEventListener('click', async (e) => {
1098
+ const menu = $('#ctx-menu');
1099
+ const roomBtn = e.target.closest('[data-room], [data-color]');
1100
+ if (roomBtn && menu.dataset.room) {
1101
+ const p = projectById(menu.dataset.room);
1102
+ const deskRole = menu.dataset.deskRole;
1103
+ closeMenu();
1104
+ if (!p) return;
1105
+ try {
1106
+ if (roomBtn.dataset.color) await api('PATCH', `/api/projects/${p.id}`, { color: roomBtn.dataset.color });
1107
+ else await roomAction(roomBtn.dataset.room, p, deskRole);
1108
+ } catch (err) {
1109
+ toast(err.message, 'err');
1110
+ }
1111
+ return;
1112
+ }
1113
+ const b = e.target.closest('[data-menu]');
1114
+ if (!b) return;
1115
+ const a = agentById($('#ctx-menu').dataset.agent);
1116
+ closeMenu();
1117
+ if (!a) return;
1118
+ const act = b.dataset.menu;
1119
+ try {
1120
+ if (act.startsWith('fun:')) {
1121
+ if (BUSY.has(a.status)) return toast(tx('menu.becameBusy', { name: a.name }), 'info');
1122
+ giveOrder(a, act.slice(4));
1123
+ } else if (act === 'open') openPanel(a.id);
1124
+ else if (act === 'oneonone') openOneOnOne(a.id);
1125
+ else if (act === 'praise') await api('POST', `/api/agents/${a.id}/praise`);
1126
+ else if (act === 'visit') openVisitModal(a.id);
1127
+ else if (act === 'stop') await api('POST', `/api/agents/${a.id}/stop`);
1128
+ else if (act === 'start') await api('POST', `/api/agents/${a.id}/start`);
1129
+ else if (act === 'fire') await fireAgent(a);
1130
+ } catch (err) {
1131
+ toast(err.message, 'err');
1132
+ }
1133
+ });
1134
+ document.addEventListener('pointerdown', (e) => {
1135
+ if (!e.target.closest('#ctx-menu')) closeMenu();
1136
+ });
1137
+ document.addEventListener('keydown', (e) => e.key === 'Escape' && closeMenu());
1138
+
1139
+ // Dragging a room by its header swaps it with the room it is dropped on.
1140
+ let roomDrag = null;
1141
+ const roomHeaderAt = (p) => L && L.rooms.find((r) => p.x >= r.x && p.x <= r.x + r.w && p.y >= r.y && p.y <= r.y + HEADER);
1142
+ const roomAt = (p) => L && L.rooms.find((r) => inRect(p, r));
1143
+
1144
+ async function swapRooms(fromId, toId) {
1145
+ const ids = S.projects.map((p) => p.id);
1146
+ const a = ids.indexOf(fromId);
1147
+ const b = ids.indexOf(toId);
1148
+ if (a < 0 || b < 0) return;
1149
+ [ids[a], ids[b]] = [ids[b], ids[a]];
1150
+ const pa = projectById(fromId);
1151
+ const pb = projectById(toId);
1152
+ const ba = pa.building || 'main';
1153
+ const bb = pb.building || 'main';
1154
+ S.projects = ids.map((id) => projectById(id));
1155
+ // dropping on a room of another building moves the rooms between buildings
1156
+ if (ba !== bb) {
1157
+ pa.building = bb;
1158
+ pb.building = ba;
1159
+ }
1160
+ computeLayout();
1161
+ syncSprites(false);
1162
+ try {
1163
+ if (ba !== bb) {
1164
+ await api('PATCH', `/api/projects/${pa.id}`, { building: bb });
1165
+ await api('PATCH', `/api/projects/${pb.id}`, { building: ba });
1166
+ }
1167
+ await api('POST', '/api/rooms/order', { ids });
1168
+ } catch (err) {
1169
+ toast(err.message, 'err');
1170
+ }
1171
+ }
1172
+
1173
+ canvas.addEventListener('pointerdown', (e) => {
1174
+ if (e.button !== 0) return;
1175
+ canvas.setPointerCapture(e.pointerId);
1176
+ const header = roomHeaderAt(toWorld(e.offsetX, e.offsetY));
1177
+ if (header) {
1178
+ roomDrag = { id: header.id, sx: e.offsetX, sy: e.offsetY, moved: false, target: null };
1179
+ return;
1180
+ }
1181
+ camAnim = null;
1182
+ drag = { sx: e.offsetX, sy: e.offsetY, cx: cam.x, cy: cam.y, moved: false };
1183
+ });
1184
+ canvas.addEventListener('pointermove', (e) => {
1185
+ mouse = toWorld(e.offsetX, e.offsetY);
1186
+ if (roomDrag) {
1187
+ if (Math.hypot(e.offsetX - roomDrag.sx, e.offsetY - roomDrag.sy) > 6) roomDrag.moved = true;
1188
+ if (roomDrag.moved) {
1189
+ canvas.classList.add('dragging');
1190
+ const over = roomAt(mouse);
1191
+ roomDrag.target = over && over.id !== roomDrag.id ? over.id : null;
1192
+ $('#tooltip').hidden = true;
1193
+ return;
1194
+ }
1195
+ }
1196
+ if (drag) {
1197
+ const dx = e.offsetX - drag.sx;
1198
+ const dy = e.offsetY - drag.sy;
1199
+ if (Math.hypot(dx, dy) > 4) {
1200
+ drag.moved = true;
1201
+ canvas.classList.add('dragging');
1202
+ }
1203
+ if (drag.moved) {
1204
+ cam.x = drag.cx - dx / cam.s;
1205
+ cam.y = drag.cy - dy / cam.s;
1206
+ }
1207
+ }
1208
+ updateHover(e.offsetX, e.offsetY);
1209
+ });
1210
+ canvas.addEventListener('pointerup', (e) => {
1211
+ if (roomDrag) {
1212
+ const rd = roomDrag;
1213
+ roomDrag = null;
1214
+ canvas.classList.remove('dragging');
1215
+ if (rd.moved && rd.target) swapRooms(rd.id, rd.target);
1216
+ else if (!rd.moved) onClick(hitTest(toWorld(e.offsetX, e.offsetY)));
1217
+ return;
1218
+ }
1219
+ const d = drag;
1220
+ drag = null;
1221
+ canvas.classList.remove('dragging');
1222
+ if (d && !d.moved) onClick(hitTest(toWorld(e.offsetX, e.offsetY)));
1223
+ });
1224
+ canvas.addEventListener('pointerleave', () => {
1225
+ mouse = null;
1226
+ hover = null;
1227
+ $('#tooltip').hidden = true;
1228
+ });
1229
+ canvas.addEventListener(
1230
+ 'wheel',
1231
+ (e) => {
1232
+ e.preventDefault();
1233
+ camAnim = null;
1234
+ const before = toWorld(e.offsetX, e.offsetY);
1235
+ const k = Math.exp(-e.deltaY * (e.ctrlKey ? 0.01 : 0.0015));
1236
+ cam.s = Math.max(0.2, Math.min(2.8, cam.s * k));
1237
+ cam.x = before.x - e.offsetX / cam.s;
1238
+ cam.y = before.y - e.offsetY / cam.s;
1239
+ },
1240
+ { passive: false }
1241
+ );
1242
+
1243
+ const inRect = (p, r) => p.x >= r.x && p.x <= r.x + r.w && p.y >= r.y && p.y <= r.y + r.h;
1244
+
1245
+ function hitTest(p) {
1246
+ if (!L) return null;
1247
+ let best = null;
1248
+ let bestD = 26;
1249
+ for (const [id, sp] of sprites) {
1250
+ if (sp.hidden) continue;
1251
+ const d = Math.hypot(p.x - sp.x, p.y - (sp.y - 22));
1252
+ if (d < bestD) {
1253
+ bestD = d;
1254
+ best = { type: 'agent', id };
1255
+ }
1256
+ }
1257
+ if (best) return best;
1258
+ for (const room of L.rooms) {
1259
+ for (const desk of room.desks) {
1260
+ if (!inRect(p, { x: desk.x - 6, y: desk.y - 46, w: desk.w + 12, h: desk.h + 56 })) continue;
1261
+ if (desk.agent) return { type: 'agent', id: desk.agent.id };
1262
+ return { type: 'emptyDesk', projectId: room.id, role: desk.emptyRole, desk };
1263
+ }
1264
+ }
1265
+ if (inRect(p, L.boss)) return { type: 'boss' };
1266
+ if (L.lobby && inRect(p, L.lobby)) return { type: 'lobby' };
1267
+ if (inRect(p, L.lot)) return { type: 'addBuilding' };
1268
+ for (const bl of Object.values(L.buildings)) {
1269
+ if (inRect(p, bl.addRoom)) return { type: 'addRoom', building: bl.b.id };
1270
+ if (!bl.hq && inRect(p, bl.sign)) return { type: 'building', id: bl.b.id };
1271
+ }
1272
+ for (const room of L.rooms) if (inRect(p, boardRect(room))) return { type: 'board', id: room.id };
1273
+ for (const room of L.rooms) if (inRect(p, room)) return { type: 'room', id: room.id };
1274
+ if (inRect(p, L.garden)) return { type: 'garden' };
1275
+ if (L.roads.some((r) => p.y >= r.y && p.y <= r.y + r.h)) return { type: 'road' };
1276
+ return null;
1277
+ }
1278
+
1279
+ function updateHover(sx, sy) {
1280
+ if (drag && drag.moved) return;
1281
+ hover = mouse ? hitTest(mouse) : null;
1282
+ canvas.classList.remove('grab');
1283
+ canvas.classList.toggle('pointer', !!hover && hover.type !== 'garden');
1284
+ if (hover?.type === 'emptyDesk') canvas.classList.add('pointer');
1285
+ const tt = $('#tooltip');
1286
+ let html = '';
1287
+ if (hover?.type === 'agent') {
1288
+ const a = agentById(hover.id);
1289
+ if (a) {
1290
+ const p = projectById(a.projectId);
1291
+ html = `<b>${esc(a.name)}</b> · ${esc(roleLabel(a.role))}<div class="tt-line">${esc(p?.name)} · ${statusLabel(a.status)}</div>`;
1292
+ if (a.task) html += `<div class="tt-line">📝 ${esc(a.task.slice(0, 140))}</div>`;
1293
+ if (a.tool) html += `<div class="tt-line">🔧 ${esc(a.tool)}</div>`;
1294
+ if (a.stuck) html += `<div class="tt-line">⚠️ ${esc(stuckText(a))}</div>`;
1295
+ for (const c of conflictsOf(a)) html += `<div class="tt-line">⚔️ ${tx('conflict.line', { names: esc(c.others.join(', ')), file: esc(c.short) })}</div>`;
1296
+ if (agentUsage(a)) html += `<div class="tt-line">💰 ${tx('usage.today', { usage: fmtUsage(agentUsage(a)) })}</div>`;
1297
+ html += a.subagent
1298
+ ? `<div class="tt-line">${tx('tip.subagent', { parent: esc(a.parentName) })}</div>`
1299
+ : a.external
1300
+ ? `<div class="tt-line">${tx('tip.external', { pid: a.pid })}</div>`
1301
+ : `<div class="tt-line">${tx('tip.openTerminal')}</div>`;
1302
+ }
1303
+ } else if (hover?.type === 'emptyDesk') {
1304
+ html = `<b>${tx('tip.freeDesk')}</b> · ${esc(roleLabel(hover.role))}<div class="tt-line">${tx('tip.freeDeskHint')}</div>`;
1305
+ } else if (hover?.type === 'room') {
1306
+ const p = projectById(hover.id);
1307
+ if (mouse && roomHeaderAt(mouse)) canvas.classList.add('grab');
1308
+ html = `<b>${esc(p?.name)}</b><div class="tt-line">${esc(p?.path)}</div><div class="tt-line">${p?.auto ? tx('tip.tempRoom') : tx('tip.room')}</div><div class="tt-line">${tx('tip.dragRoom')}</div>`;
1309
+ } else if (hover?.type === 'board') {
1310
+ const c = boardCounts(hover.id);
1311
+ html = `<b>📌 ${tx('board.title')}</b><div class="tt-line">${tx('board.tip', { todo: c.todo, doing: c.doing })}</div>`;
1312
+ } else if (hover?.type === 'lobby') {
1313
+ const m = (S.meetings || []).find((x) => x.status === 'running');
1314
+ html = `<b>🗣 ${tx('meet.title')}</b><div class="tt-line">${m ? tx('meet.tipRunning', { topic: esc(m.topic.slice(0, 80)) }) : tx('meet.tip')}</div>`;
1315
+ } else if (hover?.type === 'boss') {
1316
+ html = `<b>${tx('tip.bossRoom')}</b><div class="tt-line">${tx('tip.bossHint')}</div>`;
1317
+ } else if (hover?.type === 'addRoom') {
1318
+ const b = S.buildings.find((x) => x.id === hover.building);
1319
+ html = `<b>${tx('world.addRoom')}</b><div class="tt-line">${tx('world.addRoomHint', { name: esc(b?.name || '') })}</div>`;
1320
+ } else if (hover?.type === 'addBuilding') {
1321
+ html = `<b>${tx('top.addBuilding')}</b>`;
1322
+ } else if (hover?.type === 'building') {
1323
+ const b = S.buildings.find((x) => x.id === hover.id);
1324
+ html = `<b>🏢 ${esc(b?.name || '')}</b><div class="tt-line">${esc(b?.company || '')}</div><div class="tt-line">${tx('tip.building')}</div>`;
1325
+ } else if (hover?.type === 'road') {
1326
+ html = `<b>🚗</b> <span class="tt-line">${canPlay() ? tx('arcade.roadHint') : tx('arcade.locked')}</span>`;
1327
+ } else if (hover?.type === 'garden') {
1328
+ const n = S.agents.filter((a) => a.status === 'idle').length;
1329
+ html = `<b>${tx('tip.garden')}</b><div class="tt-line">${n ? tx('tip.gardenN', { n }) : tx('tip.gardenNone')}</div>`;
1330
+ }
1331
+ if (html) {
1332
+ tt.innerHTML = html;
1333
+ tt.hidden = false;
1334
+ const r = canvas.getBoundingClientRect();
1335
+ tt.style.left = Math.min(sx + 16, r.width - 330) + 'px';
1336
+ tt.style.top = sy + 16 + 'px';
1337
+ } else tt.hidden = true;
1338
+ }
1339
+
1340
+ function onClick(hit) {
1341
+ if (!hit) return;
1342
+ if (hit.type === 'agent') openPanel(hit.id);
1343
+ else if (hit.type === 'emptyDesk') openHireModal(hit.projectId, hit.role, true);
1344
+ else if (hit.type === 'room') {
1345
+ if (!focus || focus.id !== hit.id) focusRoom(hit.id);
1346
+ }
1347
+ else if (hit.type === 'board') openBoard(hit.id);
1348
+ else if (hit.type === 'boss') openAnnounceModal(null);
1349
+ else if (hit.type === 'lobby') openMeetings();
1350
+ else if (hit.type === 'road') openArcade();
1351
+ else if (hit.type === 'addRoom') openProjectModal(hit.building);
1352
+ else if (hit.type === 'building') openBuildingModal(hit.id);
1353
+ else if (hit.type === 'addBuilding') openBuildingModal();
1354
+ }
1355
+
1356
+ // ------------------------------------------------------------------ drawing helpers
1357
+
1358
+ function rr(x, y, w, h, r, fill, stroke, lw = 1) {
1359
+ ctx.beginPath();
1360
+ ctx.roundRect(x, y, w, h, r);
1361
+ if (fill) {
1362
+ ctx.fillStyle = fill;
1363
+ ctx.fill();
1364
+ }
1365
+ if (stroke) {
1366
+ ctx.strokeStyle = stroke;
1367
+ ctx.lineWidth = lw;
1368
+ ctx.stroke();
1369
+ }
1370
+ }
1371
+ function circle(x, y, r, fill, stroke, lw = 1) {
1372
+ ctx.beginPath();
1373
+ ctx.arc(x, y, r, 0, Math.PI * 2);
1374
+ if (fill) {
1375
+ ctx.fillStyle = fill;
1376
+ ctx.fill();
1377
+ }
1378
+ if (stroke) {
1379
+ ctx.strokeStyle = stroke;
1380
+ ctx.lineWidth = lw;
1381
+ ctx.stroke();
1382
+ }
1383
+ }
1384
+ function text(str, x, y, { size = 12, color = '#222', weight = 400, align = 'center', base = 'middle', font = 'system-ui, -apple-system, sans-serif' } = {}) {
1385
+ ctx.font = `${weight} ${size}px ${font}`;
1386
+ ctx.fillStyle = color;
1387
+ ctx.textAlign = align;
1388
+ ctx.textBaseline = base;
1389
+ ctx.fillText(str, x, y);
1390
+ }
1391
+ function shade(hex, amt) {
1392
+ const n = parseInt(hex.slice(1), 16);
1393
+ const c = (v) => Math.max(0, Math.min(255, v + amt));
1394
+ return `rgb(${c(n >> 16)},${c((n >> 8) & 255)},${c(n & 255)})`;
1395
+ }
1396
+ function alpha(hex, a) {
1397
+ const n = parseInt(hex.slice(1), 16);
1398
+ return `rgba(${n >> 16},${(n >> 8) & 255},${n & 255},${a})`;
1399
+ }
1400
+
1401
+ let grassPattern = null;
1402
+ let tilePattern = null;
1403
+ let woodPattern = null;
1404
+ function makePatterns() {
1405
+ const mk = (w, h, fn) => {
1406
+ const c = document.createElement('canvas');
1407
+ c.width = w;
1408
+ c.height = h;
1409
+ fn(c.getContext('2d'));
1410
+ return ctx.createPattern(c, 'repeat');
1411
+ };
1412
+ grassPattern = mk(96, 96, (g) => {
1413
+ g.fillStyle = '#7fbf69';
1414
+ g.fillRect(0, 0, 96, 96);
1415
+ for (let i = 0; i < 90; i++) {
1416
+ const r = hash('g' + i);
1417
+ g.fillStyle = i % 3 ? 'rgba(60,120,50,.25)' : 'rgba(200,240,160,.25)';
1418
+ g.fillRect(r % 96, (r >> 8) % 96, 2, 3);
1419
+ }
1420
+ });
1421
+ tilePattern = mk(48, 48, (g) => {
1422
+ g.fillStyle = '#d9d4ca';
1423
+ g.fillRect(0, 0, 48, 48);
1424
+ g.strokeStyle = 'rgba(0,0,0,.06)';
1425
+ g.strokeRect(0.5, 0.5, 47, 47);
1426
+ });
1427
+ woodPattern = mk(120, 26, (g) => {
1428
+ g.fillStyle = '#e9d8b9';
1429
+ g.fillRect(0, 0, 120, 26);
1430
+ g.fillStyle = 'rgba(120,80,40,.10)';
1431
+ g.fillRect(0, 12, 120, 1);
1432
+ g.fillRect(0, 25, 120, 1);
1433
+ g.fillRect(70, 0, 1, 13);
1434
+ g.fillRect(25, 13, 1, 13);
1435
+ });
1436
+ }
1437
+
1438
+ // ------------------------------------------------------------------ scene
1439
+
1440
+ // Four-lane road in front of the office: two lanes each way, with traffic.
1441
+ const traffic = [];
1442
+ let nextCarAt = 0;
1443
+ const CAR_COLORS = ['#e63946', '#457b9d', '#f4a261', '#2a9d8f', '#e9c46a', '#8338ec', '#ffffff', '#1d3557', '#ff006e'];
1444
+
1445
+ function drawCar(x, y, dir, color, len = 46, wid = 22) {
1446
+ ctx.save();
1447
+ ctx.translate(x, y);
1448
+ if (dir < 0) ctx.rotate(Math.PI);
1449
+ rr(-len / 2 + 2, -wid / 2 + 3, len, wid, 6, 'rgba(0,0,0,.25)');
1450
+ rr(-len / 2, -wid / 2, len, wid, 6, color, shade(color.length === 7 ? color : '#888888', -40), 1.5);
1451
+ rr(len / 2 - 17, -wid / 2 + 3, 9, wid - 6, 2, 'rgba(160,210,255,.85)');
1452
+ rr(-len / 2 + 6, -wid / 2 + 3, 7, wid - 6, 2, 'rgba(160,210,255,.6)');
1453
+ ctx.fillStyle = '#fff6b0';
1454
+ ctx.fillRect(len / 2 - 3, -wid / 2 + 2, 3, 4);
1455
+ ctx.fillRect(len / 2 - 3, wid / 2 - 6, 3, 4);
1456
+ ctx.fillStyle = '#ff4d4f';
1457
+ ctx.fillRect(-len / 2, -wid / 2 + 2, 2, 4);
1458
+ ctx.fillRect(-len / 2, wid / 2 - 6, 2, 4);
1459
+ ctx.restore();
1460
+ }
1461
+
1462
+ const OUTER = { '-1': 0, 1: 3 }; // cruising lane per direction
1463
+ const INNER = { '-1': 1, 1: 2 }; // overtaking lane per direction
1464
+
1465
+ // Lanes a car occupies right now (two while it changes lanes).
1466
+ const occupies = (c, lane) => lane === Math.floor(c.laneF + 1e-6) || lane === Math.ceil(c.laneF - 1e-6) || lane === c.target;
1467
+
1468
+ // Nearest car ahead of c (in its direction) sharing any of the given lanes.
1469
+ function carAhead(c, lanes) {
1470
+ let best = null;
1471
+ let bestGap = Infinity;
1472
+ for (const o of traffic) {
1473
+ if (o === c || o.road !== c.road || o.dir !== c.dir || !lanes.some((l) => occupies(o, l))) continue;
1474
+ const d = (o.x - c.x) * c.dir;
1475
+ if (d <= 0) continue;
1476
+ const gap = d - (o.len + c.len) / 2;
1477
+ if (gap < bestGap) {
1478
+ bestGap = gap;
1479
+ best = o;
1480
+ }
1481
+ }
1482
+ return { car: best, gap: bestGap };
1483
+ }
1484
+
1485
+ // Is lane free around c, from `behind` px back to `ahead` px forward?
1486
+ function laneClear(c, lane, behind, ahead) {
1487
+ return !traffic.some((o) => {
1488
+ if (o === c || o.road !== c.road || o.dir !== c.dir || !occupies(o, lane)) return false;
1489
+ const d = (o.x - c.x) * c.dir;
1490
+ const half = (o.len + c.len) / 2;
1491
+ if (d >= 0) return d - half < ahead;
1492
+ // a faster car coming from behind needs extra room
1493
+ return -d - half < behind + Math.max(0, (o.cur - c.cur) * 1.5);
1494
+ });
1495
+ }
1496
+
1497
+ const isEmergency = (c) => c.kind === 'ambulance' || c.kind === 'police';
1498
+ let nextEmergencyAt = performance.now() + 8000;
1499
+
1500
+ function updateTraffic(dt) {
1501
+ if (!dt) return;
1502
+ const now = performance.now();
1503
+ if (now > nextEmergencyAt) {
1504
+ nextEmergencyAt = now + 18000 + Math.random() * 30000;
1505
+ const dir = Math.random() < 0.5 ? -1 : 1;
1506
+ const lane = INNER[dir];
1507
+ const span = roadSpan();
1508
+ const x = dir > 0 ? span.left - 140 : span.right + 140;
1509
+ const kind = Math.random() < 0.5 ? 'ambulance' : 'police';
1510
+ const len = kind === 'ambulance' ? 58 : 48;
1511
+ const road = Math.floor(Math.random() * L.roads.length);
1512
+ if (!traffic.some((o) => o.road === road && o.dir === dir && occupies(o, lane) && Math.abs(o.x - x) < (o.len + len) / 2 + 70)) {
1513
+ traffic.push({ road, kind, dir, lane, laneF: lane, target: lane, x, speed: 230 + Math.random() * 30, cur: 200, color: kind === 'ambulance' ? '#ffffff' : '#1d3557', len });
1514
+ }
1515
+ }
1516
+ if (now > nextCarAt) {
1517
+ // a longer visible road (zoomed out) gets proportionally more cars
1518
+ const spanNow = roadSpan();
1519
+ const stretch = Math.max(1, Math.min(4, (spanNow.right - spanNow.left) / L.bounds.w));
1520
+ nextCarAt = now + (700 + Math.random() * 1800) / stretch / Math.max(1, L.roads.length * 0.7);
1521
+ const dir = Math.random() < 0.5 ? -1 : 1;
1522
+ const lane = Math.random() < 0.8 ? OUTER[dir] : INNER[dir];
1523
+ const truck = Math.random() < 0.18;
1524
+ const len = truck ? 78 : 46;
1525
+ const span = roadSpan();
1526
+ const x = dir > 0 ? span.left - 120 : span.right + 120;
1527
+ // only spawn into a free entry point
1528
+ const road = Math.floor(Math.random() * L.roads.length);
1529
+ const blocked = traffic.some((o) => o.road === road && o.dir === dir && occupies(o, lane) && Math.abs(o.x - x) < (o.len + len) / 2 + 70);
1530
+ if (!blocked) {
1531
+ const speed = truck ? 70 + Math.random() * 25 : 95 + Math.random() * 95;
1532
+ traffic.push({ road, dir, lane, laneF: lane, target: lane, x, speed, cur: speed * 0.8, color: CAR_COLORS[Math.floor(Math.random() * CAR_COLORS.length)], len });
1533
+ }
1534
+ }
1535
+ for (const c of traffic) {
1536
+ if (c.scripted) continue;
1537
+ const lanes = c.target !== c.laneF ? [Math.round(c.laneF), c.target] : [c.target];
1538
+ const { car: ahead, gap } = carAhead(c, lanes);
1539
+ const safe = 22 + c.cur * 0.45;
1540
+ // an emergency vehicle coming up behind in the same direction?
1541
+ const siren = !isEmergency(c) && traffic.some((o) => isEmergency(o) && o.road === c.road && o.dir === c.dir && (c.x - o.x) * c.dir > 0 && (c.x - o.x) * c.dir < 320);
1542
+ // speed: follow the car ahead, otherwise cruise at the preferred speed
1543
+ let want = siren ? c.speed * 0.6 : c.speed;
1544
+ if (ahead && gap < safe * 2) want = Math.min(want, ahead.cur * (gap < safe ? 0.85 : 1));
1545
+ if (gap < 8) want = 0;
1546
+ const accel = want > c.cur ? 70 : 260;
1547
+ c.cur += Math.max(-accel * dt, Math.min(accel * dt, want - c.cur));
1548
+ c.x += c.dir * c.cur * dt;
1549
+
1550
+ if (c.target === c.laneF) {
1551
+ const outer = OUTER[c.dir];
1552
+ const inner = INNER[c.dir];
1553
+ if (isEmergency(c)) {
1554
+ // sirens on: use whichever lane is open
1555
+ const other = c.lane === inner ? outer : inner;
1556
+ if (ahead && gap < safe * 1.6 && laneClear(c, other, 40, safe * 1.8)) c.target = other;
1557
+ else if (c.lane === outer && laneClear(c, inner, 40, safe * 2.5)) c.target = inner;
1558
+ } else if (siren) {
1559
+ // pull over to the outer lane and let it pass
1560
+ if (c.lane === inner && laneClear(c, outer, 30 + c.len, 40 + c.len)) c.target = outer;
1561
+ } else if (c.lane === outer && ahead && gap < safe * 2.2 && ahead.speed < c.speed - 12 && laneClear(c, inner, 90, safe * 2.5)) {
1562
+ c.target = inner; // overtake on the inside (left) only
1563
+ } else if (c.lane === inner && laneClear(c, outer, 60 + c.len, 140 + safe)) {
1564
+ c.target = outer; // done overtaking: keep right again
1565
+ }
1566
+ }
1567
+ // smooth lane change
1568
+ if (c.target !== c.laneF) {
1569
+ const step = dt * 1.4 * Math.sign(c.target - c.laneF);
1570
+ c.laneF = Math.abs(c.target - c.laneF) <= Math.abs(step) ? c.target : c.laneF + step;
1571
+ if (c.laneF === c.target) c.lane = c.target;
1572
+ }
1573
+ }
1574
+ const span = roadSpan();
1575
+ for (let i = traffic.length - 1; i >= 0; i--) {
1576
+ const c = traffic[i];
1577
+ // remove a car only once it has left the visible road in its direction
1578
+ if ((c.dir > 0 && c.x > span.right + 220) || (c.dir < 0 && c.x < span.left - 220)) traffic.splice(i, 1);
1579
+ }
1580
+ }
1581
+
1582
+ // Horizontal world range covered by the road: the office plus whatever is on screen.
1583
+ function roadSpan() {
1584
+ const viewL = cam.x;
1585
+ const viewR = cam.x + viewW / cam.s;
1586
+ return { left: Math.min(L.bounds.x, viewL), right: Math.max(L.bounds.x + L.bounds.w, viewR) };
1587
+ }
1588
+
1589
+ function drawBackground(t) {
1590
+ const span = roadSpan();
1591
+ ctx.fillStyle = '#2a3142';
1592
+ ctx.fillRect(span.left - 400, Math.min(L.bounds.y, cam.y) - 400, span.right - span.left + 800, Math.max(L.bounds.h, cam.y + viewH / cam.s) + 4000);
1593
+ const x0 = span.left - 300;
1594
+ const x1 = span.right + 300;
1595
+ // pedestrian avenues between the columns
1596
+ for (const ax of L.avenues) {
1597
+ ctx.fillStyle = '#4a5166';
1598
+ ctx.fillRect(ax - AVENUE / 2 + 18, L.bounds.y - 20, AVENUE - 36, L.bounds.h + 40);
1599
+ ctx.fillStyle = 'rgba(255,255,255,.05)';
1600
+ for (let yy = L.bounds.y; yy < L.bounds.h; yy += 40) ctx.fillRect(ax - AVENUE / 2 + 18, yy, AVENUE - 36, 2);
1601
+ }
1602
+ for (const r of L.roads) {
1603
+ ctx.fillStyle = '#4a5166';
1604
+ ctx.fillRect(x0, r.y - 14, x1 - x0, 14);
1605
+ ctx.fillRect(x0, r.y + r.h, x1 - x0, 14);
1606
+ ctx.fillStyle = '#353c4f';
1607
+ ctx.fillRect(x0, r.y, x1 - x0, r.h);
1608
+ ctx.strokeStyle = 'rgba(255,255,255,.35)';
1609
+ ctx.lineWidth = 3;
1610
+ ctx.setLineDash([26, 22]);
1611
+ for (const k of [1, 3]) {
1612
+ ctx.beginPath();
1613
+ ctx.moveTo(x0, r.y + ROAD_LANE * k);
1614
+ ctx.lineTo(x1, r.y + ROAD_LANE * k);
1615
+ ctx.stroke();
1616
+ }
1617
+ ctx.setLineDash([]);
1618
+ ctx.strokeStyle = '#f4c430';
1619
+ ctx.lineWidth = 2;
1620
+ for (const off of [-3, 3]) {
1621
+ ctx.beginPath();
1622
+ ctx.moveTo(x0, r.y + ROAD_LANE * 2 + off);
1623
+ ctx.lineTo(x1, r.y + ROAD_LANE * 2 + off);
1624
+ ctx.stroke();
1625
+ }
1626
+ // zebra crossings where avenues meet the road
1627
+ ctx.fillStyle = 'rgba(255,255,255,.75)';
1628
+ for (const ax of L.avenues) for (let k = 0; k < 6; k++) ctx.fillRect(ax - 42 + k * 15, r.y + 4, 8, r.h - 8);
1629
+ }
1630
+ // Traffic drives on the right: top two lanes go left, bottom two go right.
1631
+ // The outer lane is for cruising; the inner lane (next to the yellow line) is
1632
+ // only for overtaking, so nobody passes on the right.
1633
+ updateCommutes(frameDt);
1634
+ drawParkingLots();
1635
+ updateTraffic(frameDt);
1636
+ for (const c of traffic) {
1637
+ const road = L.roads[c.road] || L.roads[0];
1638
+ const y = road.y + ROAD_LANE * (c.laneF + 0.5);
1639
+ const turning = c.target !== c.laneF ? Math.sign(c.target - c.laneF) * c.dir * 0.22 : 0;
1640
+ ctx.save();
1641
+ ctx.translate(c.x, y);
1642
+ ctx.rotate(turning + (c.angle || 0));
1643
+ if (isEmergency(c)) drawEmergency(c);
1644
+ else if (c.kind === 'fired') drawFiredCar(c);
1645
+ else if (c.kind === 'commute') drawVehicle(c);
1646
+ else drawCar(0, 0, c.dir, c.color, c.len, c.len > 60 ? 26 : 22);
1647
+ if (c.target !== c.laneF && Math.floor(performance.now() / 250) % 2 === 0) {
1648
+ const side = (c.target > c.laneF ? 1 : -1) * 11;
1649
+ circle(c.dir * (c.len / 2 - 4), side, 3, '#ffb000');
1650
+ circle(-c.dir * (c.len / 2 - 4), side, 3, '#ffb000');
1651
+ }
1652
+ ctx.restore();
1653
+ }
1654
+ // when everyone works, the boss's sports car waits at the curb
1655
+ if (canPlay()) {
1656
+ const px = L.entrance.x + 120;
1657
+ const py = L.road.y + ROAD_LANE * 3.5;
1658
+ const pulse = 0.5 + 0.5 * Math.sin(t / 250);
1659
+ ctx.strokeStyle = `rgba(255,179,71,${0.4 + 0.6 * pulse})`;
1660
+ ctx.lineWidth = 3;
1661
+ ctx.beginPath();
1662
+ ctx.ellipse(px, py, 40, 20, 0, 0, Math.PI * 2);
1663
+ ctx.stroke();
1664
+ drawCar(px, py, 1, '#ff3b30', 52, 24);
1665
+ drawBubble(px, py - 22, tx('arcade.roadHint'), { bg: '#fff7d6', size: 12, maxW: 260 });
1666
+ }
1667
+ }
1668
+
1669
+ function drawEmergency(c) {
1670
+ const amb = c.kind === 'ambulance';
1671
+ const wid = amb ? 26 : 22;
1672
+ const flash = Math.floor(performance.now() / 140) % 2 === 0;
1673
+ // flashing glow on the road
1674
+ ctx.fillStyle = amb ? (flash ? 'rgba(255,60,60,.22)' : 'rgba(255,255,255,.18)') : flash ? 'rgba(255,60,60,.22)' : 'rgba(60,120,255,.25)';
1675
+ ctx.beginPath();
1676
+ ctx.ellipse(0, 0, c.len * 0.9, wid * 1.5, 0, 0, Math.PI * 2);
1677
+ ctx.fill();
1678
+ drawCar(0, 0, c.dir, c.color, c.len, wid);
1679
+ ctx.save();
1680
+ if (c.dir < 0) ctx.rotate(Math.PI);
1681
+ if (amb) {
1682
+ ctx.fillStyle = '#e63946';
1683
+ ctx.fillRect(-c.len / 2 + 2, -1.5, c.len - 4, 3); // side stripe
1684
+ ctx.fillRect(-7, -6, 6, 12); // red cross on the roof
1685
+ ctx.fillRect(-10, -1.5, 12, 3);
1686
+ ctx.fillStyle = flash ? '#ff2d2d' : '#ffffff';
1687
+ ctx.fillRect(c.len / 2 - 22, -wid / 2 + 2, 4, wid - 4);
1688
+ } else {
1689
+ ctx.fillStyle = '#ffffff';
1690
+ ctx.fillRect(-c.len / 2 + 6, -wid / 2, c.len - 20, 4); // white doors
1691
+ ctx.fillRect(-c.len / 2 + 6, wid / 2 - 4, c.len - 20, 4);
1692
+ ctx.fillStyle = flash ? '#ff2d2d' : '#2d6bff';
1693
+ ctx.fillRect(-3, -wid / 2 + 2, 5, wid / 2 - 2);
1694
+ ctx.fillStyle = flash ? '#2d6bff' : '#ff2d2d';
1695
+ ctx.fillRect(-3, 0, 5, wid / 2 - 2);
1696
+ }
1697
+ ctx.restore();
1698
+ }
1699
+
1700
+ // ---- a fired agent storms off into their parked car and drives away. Now and
1701
+ // then (FIRE_CRASH_CHANCE) it ends in a crash into a lamppost, the police turn
1702
+ // up, a ticket, and off they drive with a smoking bonnet.
1703
+ const FIRE_CRASH_CHANCE = 0.25;
1704
+ const fireScenes = [];
1705
+ const trailPuffs = [];
1706
+
1707
+ function startFireScene(sp, a) {
1708
+ const bl = L.buildings[buildingOf(a)];
1709
+ const road = L.roads[bl.row];
1710
+ const laneY = road.y + ROAD_LANE * 0.5;
1711
+ // their own car (or motorbike), nose-in in its bay in front of the building
1712
+ const slot = slotOf(a.id) || { kind: 'car', x: bl.entrance.x + 380, y: road.y - 40 };
1713
+ const parkedLane = laneOfY(road, slot.y);
1714
+ const car = { road: bl.row, kind: 'fired', veh: slot.kind, dir: -1, lane: 0, laneF: parkedLane, target: parkedLane, x: slot.x, speed: 0, cur: 0, color: a.color, len: slot.kind === 'moto' ? 28 : 46, scripted: true, angle: Math.PI / 2 };
1715
+ traffic.push(car);
1716
+ vehicleAway.add(a.id);
1717
+ const scene = {
1718
+ a: { ...a, status: 'offline' },
1719
+ sp,
1720
+ car,
1721
+ road,
1722
+ laneY,
1723
+ door: { x: slot.x + 18, y: slot.y - 6 },
1724
+ post: { x: bl.entrance.x + 150, y: road.y - 4, bent: 0 },
1725
+ crash: Math.random() < FIRE_CRASH_CHANCE,
1726
+ phase: 'walk',
1727
+ t0: performance.now(),
1728
+ puffs: [],
1729
+ line: pick('fire.walk'),
1730
+ nextLine: performance.now() + 2600,
1731
+ };
1732
+ sp.scene = scene;
1733
+ fireScenes.push(scene);
1734
+ return scene;
1735
+ }
1736
+
1737
+ function puff(scene, x, y, { color = '200,200,200', r = 6, vy = -25, life = 1.2, spread = 20 } = {}) {
1738
+ scene.puffs.push({ x, y, vx: (Math.random() - 0.5) * spread, vy: vy * (0.6 + Math.random() * 0.8), r, life, age: 0, color });
1739
+ }
1740
+
1741
+ function updateFireScene(sc, now, dt) {
1742
+ const c = sc.car;
1743
+ const since = (now - sc.t0) / 1000;
1744
+ const go = (phase) => {
1745
+ sc.phase = phase;
1746
+ sc.t0 = now;
1747
+ };
1748
+ switch (sc.phase) {
1749
+ case 'walk':
1750
+ if (now > sc.nextLine) {
1751
+ sc.line = pick('fire.walk');
1752
+ sc.nextLine = now + 2600;
1753
+ }
1754
+ if (sc.boarded) {
1755
+ sc.line = pick('fire.board');
1756
+ go('board');
1757
+ }
1758
+ break;
1759
+ case 'board':
1760
+ // door slams, engine revs
1761
+ if (Math.random() < 0.5) puff(sc, c.x, sc.road.y + ROAD_LANE * (c.laneF + 0.5) + 24, { color: '120,120,120', r: 4, vy: -10, spread: 30 });
1762
+ if (since > 1.1) go('backout');
1763
+ break;
1764
+ case 'backout': {
1765
+ // reverse out of the bay into the near lane
1766
+ const k = Math.min(1, since / 1.1);
1767
+ const e = smooth(k);
1768
+ if (sc.fromLane === undefined) sc.fromLane = c.laneF;
1769
+ c.laneF = c.target = sc.fromLane * (1 - e);
1770
+ c.angle = (Math.PI / 2) * (1 - e);
1771
+ if (k < 1) break;
1772
+ c.laneF = c.target = 0;
1773
+ c.angle = 0;
1774
+ if (sc.crash) go('peel');
1775
+ else {
1776
+ // no drama this time: pull out into the near lane and join the traffic
1777
+ Object.assign(c, { scripted: false, lane: 0, target: 0, speed: c.veh === 'moto' ? 260 : 240, cur: 60 });
1778
+ go('drive');
1779
+ }
1780
+ break;
1781
+ }
1782
+ case 'drive':
1783
+ if (since < 0.8) puff(sc, c.x + 26, sc.laneY, { color: '90,90,90', r: 5, vy: -8, spread: 40, life: 0.9 });
1784
+ if (!traffic.includes(c)) sc.done = true;
1785
+ break;
1786
+ case 'peel': {
1787
+ // floor it, fishtailing, then swerve onto the curb into the lamppost
1788
+ c.cur = Math.min(420, c.cur + 520 * dt);
1789
+ c.x -= c.cur * dt;
1790
+ const left = c.x - sc.post.x;
1791
+ c.angle = Math.sin(since * 14) * 0.08;
1792
+ if (left < 90) {
1793
+ const k = 1 - Math.max(0, left) / 90;
1794
+ c.laneF = -0.55 * k;
1795
+ c.angle = -0.55 * k;
1796
+ }
1797
+ puff(sc, c.x + 26, sc.road.y + ROAD_LANE * (c.laneF + 0.5), { color: '90,90,90', r: 5, vy: -8, spread: 40, life: 0.9 });
1798
+ if (left <= 24) {
1799
+ c.x = sc.post.x + 24;
1800
+ c.cur = 0;
1801
+ sc.post.bent = 1;
1802
+ sc.crashAt = now;
1803
+ for (let i = 0; i < 14; i++) puff(sc, sc.post.x, sc.road.y - 4, { color: i % 3 ? '160,160,160' : '255,170,60', r: 7, vy: -50, spread: 140, life: 1.6 });
1804
+ go('crash');
1805
+ }
1806
+ break;
1807
+ }
1808
+ case 'crash':
1809
+ if (Math.random() < 0.3) puff(sc, c.x - 18, sc.road.y - 2, { color: '170,170,170', r: 6, vy: -30 });
1810
+ if (since > 1.6) {
1811
+ // the police arrive from the right in the inner lane
1812
+ const span = roadSpan();
1813
+ const x = Math.min(span.right + 140, c.x + 1500);
1814
+ sc.police = { road: c.road, kind: 'police', dir: -1, lane: 1, laneF: 1, target: 1, x, speed: 0, cur: 320, color: '#1d3557', len: 48, scripted: true };
1815
+ traffic.push(sc.police);
1816
+ go('police');
1817
+ }
1818
+ break;
1819
+ case 'police': {
1820
+ if (Math.random() < 0.2) puff(sc, c.x - 18, sc.road.y - 2, { color: '170,170,170', r: 6, vy: -30 });
1821
+ const pc = sc.police;
1822
+ const stopX = c.x + 80;
1823
+ const d = pc.x - stopX;
1824
+ // follow whatever is ahead in the inner lane, slow down near the wreck
1825
+ const { car: ahead, gap } = carAhead(pc, [1]);
1826
+ let want = d < 260 ? Math.max(40, d * 1.2) : 320;
1827
+ if (ahead && gap < 60) want = Math.min(want, ahead.cur);
1828
+ pc.cur += Math.max(-500 * dt, Math.min(300 * dt, want - pc.cur));
1829
+ pc.x -= Math.min(pc.cur * dt, Math.max(0, d));
1830
+ if (d < 140) pc.laneF = Math.max(0, 1 - (140 - d) / 120);
1831
+ if (d <= 1) {
1832
+ pc.laneF = 0;
1833
+ pc.lane = pc.target = 0;
1834
+ pc.cur = 0;
1835
+ go('talk');
1836
+ }
1837
+ break;
1838
+ }
1839
+ case 'talk': {
1840
+ if (Math.random() < 0.12) puff(sc, c.x - 18, sc.road.y - 2, { color: '170,170,170', r: 5, vy: -25 });
1841
+ const n = Math.floor(since / 2.2);
1842
+ sc.talkStep = n;
1843
+ if (n >= 5) go('leave');
1844
+ break;
1845
+ }
1846
+ case 'leave':
1847
+ // back on the road, limping along with a smoking bonnet; the police leave after
1848
+ if (!c.released) {
1849
+ c.angle = Math.min(0, c.angle + dt * 0.6);
1850
+ c.laneF = Math.min(0, c.laneF + dt * 0.6);
1851
+ if (c.angle === 0 && c.laneF === 0) {
1852
+ Object.assign(c, { scripted: false, lane: 0, target: 0, speed: 85, cur: 20, smoking: true, released: true });
1853
+ }
1854
+ }
1855
+ if (since > 2.2 && sc.police.scripted) Object.assign(sc.police, { scripted: false, lane: 0, target: 1, speed: 240, cur: 30 });
1856
+ if (c.released && !sc.police.scripted && !traffic.includes(c) && !traffic.includes(sc.police)) sc.done = true;
1857
+ break;
1858
+ }
1859
+ }
1860
+
1861
+ // The fired agent's car: dented bonnet after the crash, hazards blinking.
1862
+ function drawFiredCar(c) {
1863
+ if (c.veh === 'moto') return drawVehicle({ ...c, rider: !c.scripted || c.angle < Math.PI / 2 });
1864
+ drawCar(0, 0, c.dir, c.color, c.len, 22);
1865
+ if (c.crashed || c.smoking) {
1866
+ ctx.save();
1867
+ if (c.dir < 0) ctx.rotate(Math.PI);
1868
+ ctx.fillStyle = 'rgba(30,30,30,.55)';
1869
+ ctx.beginPath();
1870
+ ctx.moveTo(c.len / 2, -9);
1871
+ ctx.lineTo(c.len / 2 - 7, -4);
1872
+ ctx.lineTo(c.len / 2 - 3, 0);
1873
+ ctx.lineTo(c.len / 2 - 8, 5);
1874
+ ctx.lineTo(c.len / 2, 9);
1875
+ ctx.fill();
1876
+ if (Math.floor(performance.now() / 350) % 2 === 0) {
1877
+ ctx.fillStyle = '#ffb000';
1878
+ for (const [x, y] of [[c.len / 2 - 3, -9], [c.len / 2 - 3, 6], [-c.len / 2, -9], [-c.len / 2, 6]]) ctx.fillRect(x, y, 3, 3);
1879
+ }
1880
+ ctx.restore();
1881
+ }
1882
+ }
1883
+
1884
+ function drawLamppost(post) {
1885
+ const { x, y, bent } = post;
1886
+ ctx.save();
1887
+ ctx.translate(x, y);
1888
+ rr(-4, -3, 8, 5, 2, '#374151');
1889
+ ctx.rotate(-bent * 0.6);
1890
+ rr(-2, -58, 4, 56, 2, '#6b7280', '#4b5563', 1);
1891
+ rr(-2, -60, 16, 4, 2, '#6b7280');
1892
+ rr(10, -58, 8, 5, 2, bent ? '#4b5563' : '#fff3b0');
1893
+ ctx.restore();
1894
+ }
1895
+
1896
+ // A police officer: navy uniform, cap with a badge.
1897
+ function drawOfficer(x, y, t, facing) {
1898
+ const cop = { id: 'cop', name: 'Officer', color: '#1e3a8a', role: 'mid', status: 'offline', look: 'm' };
1899
+ drawPersonBody({ walking: false, facing, phase: 0 }, cop, t, { x, y, act: 'phone', seated: false, atDesk: false, skin: SKIN[0], hair: '#121212', bob: 0, isHover: false, isPanel: false });
1900
+ rr(x - 12, y - 53, 24, 7, 3, '#1e293b');
1901
+ rr(x - 9, y - 58, 18, 6, 3, '#1e293b');
1902
+ circle(x, y - 55, 2, '#fbbf24');
1903
+ }
1904
+
1905
+ function drawFireScenes(t) {
1906
+ const now = performance.now();
1907
+ for (let i = fireScenes.length - 1; i >= 0; i--) {
1908
+ const sc = fireScenes[i];
1909
+ updateFireScene(sc, now, frameDt);
1910
+ if (sc.done) {
1911
+ fireScenes.splice(i, 1);
1912
+ vehicleAway.delete(sc.a.id);
1913
+ continue;
1914
+ }
1915
+ const c = sc.car;
1916
+ c.crashed = !!sc.crashAt;
1917
+ if (sc.crash) drawLamppost(sc.post);
1918
+ const carY = sc.road.y + ROAD_LANE * (c.laneF + 0.5);
1919
+ const since = (now - sc.t0) / 1000;
1920
+ if (sc.phase === 'walk' && sprites.has(sc.a.id)) {
1921
+ const sp = sprites.get(sc.a.id);
1922
+ // fuming: red steam over the head
1923
+ for (let k = 0; k < 2; k++) {
1924
+ const f = (t / 700 + k / 2) % 1;
1925
+ circle(sp.x + (k ? 8 : -8), sp.y - 58 - f * 18, 3 + f * 4, `rgba(255,90,90,${0.7 * (1 - f)})`);
1926
+ }
1927
+ drawBubble(sp.x, sp.y - 66, sc.line, { bg: '#ffe4e4', maxW: 230 });
1928
+ }
1929
+ if (sc.phase === 'board') drawBubble(c.x, carY - 20, sc.line, { bg: '#ffe4e4', size: 12, maxW: 220 });
1930
+ if (sc.phase === 'crash') {
1931
+ const k = Math.min(1, since * 3);
1932
+ text('💥', sc.post.x - 4, sc.road.y - 30, { size: 30 + k * 16 });
1933
+ if (since > 0.6) drawBubble(c.x, carY - 24, tx('fire.crash'), { bg: '#fff7d6', size: 12, maxW: 220 });
1934
+ }
1935
+ if (sc.phase === 'talk' || (sc.phase === 'police' && sc.police && sc.police.x - c.x < 500)) {
1936
+ // the driver is out, waving their arms next to the car
1937
+ const ax = c.x - 6;
1938
+ const ay = sc.road.y - 4;
1939
+ drawPersonBody({ walking: false, facing: 1, phase: 0 }, sc.a, t, { x: ax, y: ay, act: 'ask', seated: false, atDesk: false, skin: SKIN[hash(sc.a.id) % SKIN.length], hair: HAIR[hash(sc.a.id + 'h') % HAIR.length], bob: Math.abs(Math.sin(t / 120)) * 2, isHover: false, isPanel: false });
1940
+ if (sc.phase === 'talk') {
1941
+ const ox = sc.police.x - 4;
1942
+ drawOfficer(ox, ay, t, -1);
1943
+ const step = sc.talkStep || 0;
1944
+ const cop = step % 2 === 0;
1945
+ drawBubble(cop ? ox : ax, ay - 66, tx('fire.talk' + step), { bg: cop ? '#dbeafe' : '#ffe4e4', maxW: 240 });
1946
+ if (step >= 4) {
1947
+ // the ticket changes hands
1948
+ const k = Math.min(1, (since - 4 * 2.2) / 1.2);
1949
+ rr(ox + (ax - ox) * k - 5, ay - 30 - Math.sin(k * Math.PI) * 14, 10, 13, 1, '#fffbe6', '#d97706', 1);
1950
+ }
1951
+ } else drawBubble(ax, ay - 66, '😤', { size: 13 });
1952
+ }
1953
+ if (sc.phase === 'leave' && !c.released) drawBubble(c.x, carY - 20, tx('fire.leave'), { bg: '#ffe4e4', size: 12, maxW: 220 });
1954
+ // smoke and dust
1955
+ for (let j = sc.puffs.length - 1; j >= 0; j--) {
1956
+ const p = sc.puffs[j];
1957
+ p.age += frameDt;
1958
+ if (p.age > p.life) {
1959
+ sc.puffs.splice(j, 1);
1960
+ continue;
1961
+ }
1962
+ p.x += p.vx * frameDt;
1963
+ p.y += p.vy * frameDt;
1964
+ const k = p.age / p.life;
1965
+ circle(p.x, p.y, p.r * (1 + k * 1.6), `rgba(${p.color},${0.55 * (1 - k)})`);
1966
+ }
1967
+ }
1968
+ // a car limping away keeps smoking until it leaves the road
1969
+ for (const c of traffic) {
1970
+ if (!c.smoking || Math.random() > 0.25) continue;
1971
+ const road = L.roads[c.road];
1972
+ const y = road.y + ROAD_LANE * (c.laneF + 0.5);
1973
+ const p = { x: c.x - c.dir * 20, y: y - 4, vx: 0, vy: -30, r: 5, life: 1.1, age: 0, color: '150,150,150' };
1974
+ if (trailPuffs.length < 200) trailPuffs.push(p);
1975
+ }
1976
+ for (let j = trailPuffs.length - 1; j >= 0; j--) {
1977
+ const p = trailPuffs[j];
1978
+ p.age += frameDt;
1979
+ if (p.age > p.life) {
1980
+ trailPuffs.splice(j, 1);
1981
+ continue;
1982
+ }
1983
+ p.y += p.vy * frameDt;
1984
+ const k = p.age / p.life;
1985
+ circle(p.x, p.y, p.r * (1 + k * 1.6), `rgba(${p.color},${0.5 * (1 - k)})`);
1986
+ }
1987
+ }
1988
+
1989
+ // ---- commuting: everyone comes in by car, motorbike, bicycle or bus, and goes
1990
+ // home the same way. Cars and motorbikes park nose-in in the bays in front of
1991
+ // the building, bicycles in the rack; the bus stops at the stop by the entrance.
1992
+ const COMMUTES = ['car', 'car', 'car', 'car', 'moto', 'moto', 'bike', 'bike', 'transit', 'transit'];
1993
+ const commuteOf = (a) => COMMUTES[hash(a.id + ':commute') % COMMUTES.length];
1994
+ const VEHICLES = {
1995
+ car: { len: 46, speed: 230, leave: 180 },
1996
+ moto: { len: 28, speed: 260, leave: 220 },
1997
+ bike: { len: 22, speed: 120, leave: 75 },
1998
+ bus: { len: 96, speed: 200, leave: 150 },
1999
+ };
2000
+ const parking = new Map(); // agentId -> { building, kind, idx }
2001
+ const vehicleAway = new Set(); // vehicles that are on the road instead of in their bay
2002
+ const commutes = []; // arrivals, departures and buses under way
2003
+ let lastCommuteSpawn = 0;
2004
+ const laneOfY = (road, y) => (y - road.y) / ROAD_LANE - 0.5;
2005
+ const smooth = (k) => k * k * (3 - 2 * k);
2006
+
2007
+ // Keep a bay for everyone in the office (and anyone still on the way out).
2008
+ function syncParking() {
2009
+ const keep = new Set([...S.agents.map((a) => a.id), ...sprites.keys(), ...fireScenes.map((sc) => sc.a.id), ...commutes.map((c) => c.id)]);
2010
+ for (const id of [...parking.keys()]) if (!keep.has(id)) parking.delete(id);
2011
+ for (const a of S.agents) {
2012
+ if (a.subagent) continue;
2013
+ const building = buildingOf(a);
2014
+ const had = parking.get(a.id);
2015
+ if (had && had.building === building) continue;
2016
+ if (had && (sprites.has(a.id) || vehicleAway.has(a.id))) continue; // moving house later
2017
+ let kind = commuteOf(a);
2018
+ let idx = -1;
2019
+ if (kind !== 'transit') {
2020
+ const bike = kind === 'bike';
2021
+ const used = new Set([...parking.values()].filter((q) => q.building === building && q.kind !== 'transit' && (q.kind === 'bike') === bike).map((q) => q.idx));
2022
+ const park = L.buildings[building].park;
2023
+ const cap = bike ? park.rack.n : park.n;
2024
+ for (let i = 0; i < cap && idx < 0; i++) if (!used.has(i)) idx = i;
2025
+ if (idx < 0) kind = 'transit'; // car park full: take the bus
2026
+ }
2027
+ parking.set(a.id, { building, kind, idx });
2028
+ }
2029
+ }
2030
+
2031
+ function slotOf(id) {
2032
+ const p = parking.get(id);
2033
+ const bl = p && L.buildings[p.building];
2034
+ if (!bl) return null;
2035
+ const pk = bl.park;
2036
+ const road = L.roads[bl.row];
2037
+ const base = { ...p, bl, road, sideY: L.rows[bl.row].sideY };
2038
+ if (p.kind === 'transit') return { ...base, x: pk.stop.x, y: pk.stop.y };
2039
+ if (p.kind === 'bike') return { ...base, x: pk.rack.x0 + RACK_W / 2 + p.idx * RACK_W, y: pk.top + 18 };
2040
+ return { ...base, x: pk.x0 + BAY_W / 2 + p.idx * BAY_W, y: (pk.top + pk.bottom) / 2 };
2041
+ }
2042
+
2043
+ function vehicleFor(a, slot, extra) {
2044
+ const veh = slot.kind === 'transit' ? 'bus' : slot.kind;
2045
+ return { road: slot.bl.row, kind: 'commute', veh, dir: -1, lane: 0, laneF: 0, target: 0, x: slot.x, speed: VEHICLES[veh].speed, cur: 0, color: a.color, len: VEHICLES[veh].len, scripted: true, angle: 0, rider: true, ...extra };
2046
+ }
2047
+
2048
+ // A new arrival stays hidden until their vehicle has parked (or the bus stopped).
2049
+ function startArrival(sp, a) {
2050
+ const slot = !a.subagent && slotOf(a.id);
2051
+ if (!slot) return;
2052
+ sp.hidden = true;
2053
+ if (slot.kind === 'transit') {
2054
+ requestBus(slot).riders.push(sp);
2055
+ return;
2056
+ }
2057
+ const now = performance.now();
2058
+ const startAt = Math.max(now + Math.random() * 1200, lastCommuteSpawn + 900);
2059
+ lastCommuteSpawn = startAt;
2060
+ vehicleAway.add(a.id);
2061
+ commutes.push({ type: 'arrive', id: a.id, sp, startAt, phase: 'wait' });
2062
+ }
2063
+
2064
+ function cancelArrival(sp) {
2065
+ for (const c of commutes) {
2066
+ if (c.type === 'bus') c.riders = c.riders.filter((r) => r !== sp);
2067
+ if (c.type === 'arrive' && c.sp === sp) {
2068
+ c.done = true;
2069
+ // never mind: the car just drives on by
2070
+ if (c.car) Object.assign(c.car, { scripted: false, laneF: 0, target: 0, angle: 0, cur: Math.max(60, c.car.cur) });
2071
+ vehicleAway.delete(c.id);
2072
+ }
2073
+ }
2074
+ sprites.delete(sp.id);
2075
+ }
2076
+
2077
+ // Out of the vehicle (or off the bus), along the sidewalk and in through the door.
2078
+ function walkIn(sp, a, x, y) {
2079
+ const b = buildingOf(a);
2080
+ const bl = L.buildings[b];
2081
+ const sideY = L.rows[bl.row].sideY;
2082
+ Object.assign(sp, { hidden: false, x, y, zone: 'side', leaving: false });
2083
+ const des = desiredFor(a);
2084
+ if (!des) return walkOut(sp, a);
2085
+ sp.dest = des;
2086
+ const door = { x: bl.entrance.x, y: bl.entrance.y, zone: 'out:' + b };
2087
+ setPath(sp, [{ x, y: sideY, zone: 'side' }, { x: door.x, y: sideY, zone: 'side' }, door, ...route(door, des)]);
2088
+ }
2089
+
2090
+ // Leaving: out of the building, along the sidewalk to the vehicle or the bus stop.
2091
+ function walkToVehicle(sp, a, slot) {
2092
+ const b = slot.building;
2093
+ const ent = slot.bl.entrance;
2094
+ const bus = slot.kind === 'transit';
2095
+ const spot = bus ? { x: slot.x - 34 + (hash(a.id) % 6) * 13, y: slot.y + 2 } : { x: slot.x + (slot.kind === 'bike' ? 9 : 18), y: slot.y - (slot.kind === 'bike' ? 0 : 6) };
2096
+ sp.dest = { zone: 'side', x: spot.x, y: spot.y, act: 'walk', key: 'commute' };
2097
+ setPath(sp, [...route(sp, { zone: 'out:' + b, x: ent.x, y: ent.y }), { x: ent.x, y: slot.sideY, zone: 'side' }, { x: spot.x, y: slot.sideY, zone: 'side' }, { x: spot.x, y: spot.y, zone: 'side' }]);
2098
+ sp.onArrive = () => {
2099
+ const now = slotOf(a.id) || slot;
2100
+ if (bus) {
2101
+ sp.waitingBus = b;
2102
+ requestBus(now);
2103
+ return true; // stays at the stop until the bus comes
2104
+ }
2105
+ const car = vehicleFor(a, now, { laneF: laneOfY(now.road, now.y), angle: Math.PI / 2 });
2106
+ car.target = car.laneF;
2107
+ traffic.push(car);
2108
+ vehicleAway.add(a.id);
2109
+ commutes.push({ type: 'leave', id: a.id, car, t0: performance.now(), from: car.laneF, x0: car.x });
2110
+ return false;
2111
+ };
2112
+ }
2113
+
2114
+ // One bus per building at a time: it brings riders in and takes the waiting ones away.
2115
+ function requestBus(slot) {
2116
+ const b = slot.building;
2117
+ const open = commutes.find((c) => c.type === 'bus' && c.building === b && !c.done && c.phase !== 'gone');
2118
+ if (open) return open;
2119
+ const now = performance.now();
2120
+ const startAt = Math.max(now + 600, lastCommuteSpawn + 900);
2121
+ lastCommuteSpawn = startAt;
2122
+ const bus = { type: 'bus', id: 'bus:' + b, building: b, riders: [], startAt, phase: 'wait' };
2123
+ commutes.push(bus);
2124
+ return bus;
2125
+ }
2126
+
2127
+ function updateCommutes(dt) {
2128
+ if (!dt) return;
2129
+ const now = performance.now();
2130
+ const span = roadSpan();
2131
+ // ease into a stop at stopX, keeping behind whatever drives ahead in the near lane
2132
+ const driveTo = (car, stopX) => {
2133
+ const d = car.x - stopX;
2134
+ let want = Math.min(car.speed, Math.max(30, d * 1.6));
2135
+ const { car: ahead, gap } = carAhead(car, [0]);
2136
+ if (ahead && gap < 40) want = Math.min(want, ahead.cur * 0.9);
2137
+ car.cur += Math.max(-420 * dt, Math.min(260 * dt, want - car.cur));
2138
+ car.x -= Math.min(car.cur * dt, Math.max(0, d));
2139
+ return d <= 1;
2140
+ };
2141
+ for (const c of commutes) {
2142
+ if (c.done) continue;
2143
+ const since = (now - (c.t0 || now)) / 1000;
2144
+ if (c.type === 'arrive') {
2145
+ const a = agentById(c.id);
2146
+ const slot = slotOf(c.id);
2147
+ if (!a || !slot) {
2148
+ cancelArrival(c.sp);
2149
+ continue;
2150
+ }
2151
+ const stopX = slot.x + (slot.kind === 'bike' ? 10 : 26);
2152
+ if (c.phase === 'wait' && now >= c.startAt) {
2153
+ const far = slot.kind === 'bike' ? 700 : 1800;
2154
+ c.car = vehicleFor(a, slot, { x: Math.min(span.right + 100, slot.x + far) });
2155
+ c.car.cur = c.car.speed;
2156
+ traffic.push(c.car);
2157
+ c.phase = 'drive';
2158
+ } else if (c.phase === 'drive' && driveTo(c.car, stopX)) {
2159
+ c.phase = 'park';
2160
+ c.t0 = now;
2161
+ } else if (c.phase === 'park') {
2162
+ // turn in, nose first
2163
+ const e = smooth(Math.min(1, since / 0.9));
2164
+ c.car.x = stopX + (slot.x - stopX) * e;
2165
+ c.car.laneF = c.car.target = laneOfY(slot.road, slot.y) * e;
2166
+ c.car.angle = (Math.PI / 2) * e;
2167
+ if (since >= 0.9) {
2168
+ c.done = true;
2169
+ traffic.splice(traffic.indexOf(c.car), 1);
2170
+ vehicleAway.delete(c.id);
2171
+ walkIn(c.sp, a, slot.x + (slot.kind === 'bike' ? 9 : 18), slot.y - (slot.kind === 'bike' ? 0 : 6));
2172
+ }
2173
+ }
2174
+ } else if (c.type === 'leave') {
2175
+ // reverse out of the bay, then off with the traffic
2176
+ const e = smooth(Math.min(1, since / 1.1));
2177
+ c.car.laneF = c.car.target = c.from * (1 - e);
2178
+ c.car.angle = (Math.PI / 2) * (1 - e);
2179
+ c.car.x = c.x0 - 14 * e;
2180
+ if (since >= 1.1) {
2181
+ c.done = true;
2182
+ Object.assign(c.car, { scripted: false, lane: 0, target: 0, laneF: 0, angle: 0, cur: 40, speed: VEHICLES[c.car.veh].leave });
2183
+ if (!commutes.some((o) => o.type === 'arrive' && o.id === c.id && !o.done)) vehicleAway.delete(c.id);
2184
+ }
2185
+ } else if (c.type === 'bus') {
2186
+ const bl = L.buildings[c.building];
2187
+ if (!bl) {
2188
+ c.done = true;
2189
+ continue;
2190
+ }
2191
+ const stop = bl.park.stop;
2192
+ if (c.phase === 'wait' && now >= c.startAt) {
2193
+ c.car = vehicleFor({ color: '#f4b400' }, { kind: 'transit', bl, x: Math.min(span.right + 140, stop.x + 1600) }, {});
2194
+ c.car.cur = c.car.speed;
2195
+ traffic.push(c.car);
2196
+ c.phase = 'drive';
2197
+ } else if (c.phase === 'drive' && driveTo(c.car, stop.x)) {
2198
+ c.phase = 'stop';
2199
+ c.t0 = now;
2200
+ // everyone off: out of the doors and up to the sidewalk
2201
+ c.riders.forEach((sp, i) => {
2202
+ const a = agentById(sp.id);
2203
+ if (a && sprites.get(sp.id) === sp) walkIn(sp, a, stop.x - 30 + i * 14, stop.y + 4);
2204
+ });
2205
+ c.riders = [];
2206
+ } else if (c.phase === 'stop' && since > 2.4) {
2207
+ // the waiting ones get on, and off it goes
2208
+ for (const [id, sp] of sprites) if (sp.waitingBus === c.building && !sp.path.length) sprites.delete(id);
2209
+ Object.assign(c.car, { scripted: false, lane: 0, target: 0, cur: 30, speed: VEHICLES.bus.leave });
2210
+ c.phase = 'gone';
2211
+ c.done = true;
2212
+ }
2213
+ }
2214
+ }
2215
+ for (let i = commutes.length - 1; i >= 0; i--) if (commutes[i].done) commutes.splice(i, 1);
2216
+ }
2217
+
2218
+ // A vehicle seen from above, facing +x (rotated by the caller) unless dir < 0.
2219
+ function drawVehicle(c) {
2220
+ if (c.veh === 'car' || !c.veh) return drawCar(0, 0, c.dir, c.color, c.len, 22);
2221
+ ctx.save();
2222
+ if (c.dir < 0) ctx.rotate(Math.PI);
2223
+ const dark = shade(c.color && c.color.length === 7 ? c.color : '#888888', -50);
2224
+ if (c.veh === 'bus') {
2225
+ rr(-46, -11, 96, 26, 6, 'rgba(0,0,0,.25)');
2226
+ rr(-48, -13, 96, 26, 6, c.color, shade(c.color, -40), 1.5);
2227
+ for (let k = 0; k < 6; k++) rr(-40 + k * 13, -11, 9, 4, 1, 'rgba(160,210,255,.85)');
2228
+ for (let k = 0; k < 6; k++) rr(-40 + k * 13, 7, 9, 4, 1, 'rgba(160,210,255,.85)');
2229
+ rr(40, -10, 6, 20, 2, 'rgba(160,210,255,.9)');
2230
+ ctx.fillStyle = '#1f2937';
2231
+ ctx.fillRect(-20, -3, 30, 6);
2232
+ } else if (c.veh === 'moto') {
2233
+ rr(-12, -3, 26, 8, 4, 'rgba(0,0,0,.25)');
2234
+ rr(-14, -2, 8, 4, 2, '#111');
2235
+ rr(7, -2, 8, 4, 2, '#111');
2236
+ rr(-8, -4, 17, 8, 4, c.color, dark, 1);
2237
+ rr(9, -6, 2, 12, 1, '#9ca3af');
2238
+ if (c.rider) circle(-1, 0, 5.5, '#1f2937', null);
2239
+ } else if (c.veh === 'bike') {
2240
+ rr(-11, -1.5, 7, 3, 1.5, '#111');
2241
+ rr(4, -1.5, 7, 3, 1.5, '#111');
2242
+ ctx.strokeStyle = c.color;
2243
+ ctx.lineWidth = 2;
2244
+ ctx.beginPath();
2245
+ ctx.moveTo(-7, 0);
2246
+ ctx.lineTo(7, 0);
2247
+ ctx.stroke();
2248
+ rr(6, -5, 2, 10, 1, '#6b7280');
2249
+ if (c.rider) {
2250
+ circle(-1, 0, 5, c.color, null);
2251
+ circle(1, 0, 3.2, '#f2c9a0', null);
2252
+ }
2253
+ }
2254
+ ctx.restore();
2255
+ }
2256
+
2257
+ // The bus stop, the bike rack and the car park, with the vehicles of whoever is in.
2258
+ function drawParkingLots() {
2259
+ for (const bl of Object.values(L.buildings)) {
2260
+ const pk = bl.park;
2261
+ const road = L.roads[bl.row];
2262
+ rr(pk.x0 - 8, pk.top, pk.x1 - pk.x0 + 16, pk.bottom - pk.top, 6, '#3a4154');
2263
+ ctx.strokeStyle = 'rgba(255,255,255,.45)';
2264
+ ctx.lineWidth = 2;
2265
+ ctx.beginPath();
2266
+ for (let i = 0; i <= pk.n; i++) {
2267
+ ctx.moveTo(pk.x0 + i * BAY_W, pk.top + 4);
2268
+ ctx.lineTo(pk.x0 + i * BAY_W, pk.top + 46);
2269
+ }
2270
+ ctx.stroke();
2271
+ rr(pk.x0 - 30, pk.top + 4, 18, 18, 3, '#2d6bff');
2272
+ text('P', pk.x0 - 21, pk.top + 13.5, { size: 13, weight: 800, color: '#fff' });
2273
+ // bike rack
2274
+ rr(pk.rack.x0 - 4, pk.top + 4, pk.rack.x1 - pk.rack.x0 + 8, 30, 4, '#424a5e');
2275
+ ctx.strokeStyle = '#9ca3af';
2276
+ ctx.lineWidth = 1.5;
2277
+ for (let i = 0; i < pk.rack.n; i++) {
2278
+ ctx.beginPath();
2279
+ ctx.arc(pk.rack.x0 + RACK_W / 2 + i * RACK_W, pk.top + 8, 4, Math.PI, 0);
2280
+ ctx.stroke();
2281
+ }
2282
+ // bus stop: shelter on the curb, BUS painted in the lane
2283
+ const st = pk.stop;
2284
+ rr(st.x - 44, st.y - 6, 88, 12, 3, '#5b6b8a', '#3d4a63', 1);
2285
+ rr(st.x + 48, st.y - 22, 3, 30, 1, '#9ca3af');
2286
+ rr(st.x + 42, st.y - 30, 16, 12, 3, '#f4b400');
2287
+ text('🚌', st.x + 50, st.y - 23.5, { size: 9 });
2288
+ text('BUS', st.x, road.y + ROAD_LANE * 0.5, { size: 13, weight: 800, color: 'rgba(255,255,255,.28)' });
2289
+ }
2290
+ for (const [id, p] of parking) {
2291
+ if (p.kind === 'transit' || vehicleAway.has(id)) continue;
2292
+ const a = agentById(id);
2293
+ const sp = sprites.get(id);
2294
+ if (!((a && a.status !== 'offline') || sp)) continue;
2295
+ const slot = slotOf(id);
2296
+ if (!slot) continue;
2297
+ ctx.save();
2298
+ ctx.translate(slot.x, slot.y);
2299
+ ctx.rotate(Math.PI / 2);
2300
+ drawVehicle({ veh: p.kind, dir: -1, color: (a || sp?.ghost)?.color || '#888888', len: VEHICLES[p.kind].len, rider: false });
2301
+ ctx.restore();
2302
+ }
2303
+ }
2304
+
2305
+ // ---- day and night follow the clock: dusk from 17:30, night 20:00–06:00, dawn
2306
+ // until 08:00. At night the lights are on where someone is at work, street
2307
+ // lamps glow along the roads and cars drive with their headlights on.
2308
+ const NIGHT = 0.58;
2309
+ let dayNightOn = (() => {
2310
+ try {
2311
+ return localStorage.getItem('dayNight') !== 'off';
2312
+ } catch {
2313
+ return true;
2314
+ }
2315
+ })();
2316
+ function hourNow() {
2317
+ if (window.OFFICE_HOUR != null) return window.OFFICE_HOUR; // for trying it out from the console
2318
+ const d = new Date();
2319
+ return d.getHours() + d.getMinutes() / 60;
2320
+ }
2321
+ function nightLevel(h) {
2322
+ if (h >= 8 && h < 17.5) return 0;
2323
+ if (h >= 17.5 && h < 20) return (NIGHT * (h - 17.5)) / 2.5;
2324
+ if (h >= 20 || h < 6) return NIGHT;
2325
+ return NIGHT * (1 - (h - 6) / 2);
2326
+ }
2327
+ function glow(x, y, r, rgb, a) {
2328
+ const g = ctx.createRadialGradient(x, y, 0, x, y, r);
2329
+ g.addColorStop(0, `rgba(${rgb},${a})`);
2330
+ g.addColorStop(1, `rgba(${rgb},0)`);
2331
+ ctx.fillStyle = g;
2332
+ ctx.fillRect(x - r, y - r, 2 * r, 2 * r);
2333
+ }
2334
+ function drawNight() {
2335
+ const k = dayNightOn ? nightLevel(hourNow()) : 0;
2336
+ if (k < 0.01) return;
2337
+ const vx = cam.x;
2338
+ const vy = cam.y;
2339
+ const vw = viewW / cam.s;
2340
+ const vh = viewH / cam.s;
2341
+ const lit = L.rooms.filter((room) => S.agents.some((a) => a.projectId === room.id && a.status !== 'offline'));
2342
+ lit.push(L.boss);
2343
+ if ((S.meetings || []).some((m) => m.status === 'running')) lit.push(L.lobby);
2344
+ ctx.save();
2345
+ // darkness everywhere except the rooms with the lights on
2346
+ ctx.beginPath();
2347
+ ctx.rect(vx - 20, vy - 20, vw + 40, vh + 40);
2348
+ for (const r of lit) ctx.rect(r.x, r.y, r.w, r.h);
2349
+ ctx.fillStyle = `rgba(12,18,48,${k})`;
2350
+ ctx.fill('evenodd');
2351
+ ctx.globalCompositeOperation = 'lighter';
2352
+ const s = k / NIGHT;
2353
+ ctx.fillStyle = `rgba(255,190,110,${0.07 * s})`;
2354
+ for (const r of lit) ctx.fillRect(r.x, r.y, r.w, r.h);
2355
+ // street lamps on the curb in front of the buildings
2356
+ for (const road of L.roads) {
2357
+ if (road.y + road.h < vy - 100 || road.y > vy + vh + 100) continue;
2358
+ for (let x = Math.floor(vx / 320) * 320 + 160; x < vx + vw + 320; x += 320) {
2359
+ glow(x, road.y - 6, 110, '255,214,140', 0.32 * s);
2360
+ circle(x, road.y - 6, 4, `rgba(255,236,180,${0.9 * s})`);
2361
+ }
2362
+ }
2363
+ // headlights ahead of every car on the road
2364
+ for (const c of traffic) {
2365
+ const road = L.roads[c.road] || L.roads[0];
2366
+ const y = road.y + ROAD_LANE * (c.laneF + 0.5);
2367
+ if (c.x < vx - 100 || c.x > vx + vw + 100 || c.angle) continue;
2368
+ glow(c.x + c.dir * (c.len / 2 + 34), y, c.veh === 'bike' ? 22 : 46, '255,244,214', 0.4 * s);
2369
+ }
2370
+ ctx.restore();
2371
+ }
2372
+
2373
+ // Agents changing the same file: a red dashed line between them, crossed swords in the middle.
2374
+ function drawConflicts(t) {
2375
+ const drawn = new Set();
2376
+ for (const c of S.conflicts || []) {
2377
+ for (let i = 0; i < c.agents.length; i++) {
2378
+ for (let j = i + 1; j < c.agents.length; j++) {
2379
+ const key = [c.agents[i], c.agents[j]].sort().join('|');
2380
+ const p = sprites.get(c.agents[i]);
2381
+ const q = sprites.get(c.agents[j]);
2382
+ if (drawn.has(key) || !p || !q || p.hidden || q.hidden) continue;
2383
+ drawn.add(key);
2384
+ ctx.save();
2385
+ ctx.strokeStyle = `rgba(255,77,79,${0.55 + 0.3 * Math.sin(t / 250)})`;
2386
+ ctx.lineWidth = 3;
2387
+ ctx.setLineDash([10, 8]);
2388
+ ctx.lineDashOffset = -t / 40;
2389
+ ctx.beginPath();
2390
+ ctx.moveTo(p.x, p.y - 30);
2391
+ ctx.lineTo(q.x, q.y - 30);
2392
+ ctx.stroke();
2393
+ ctx.restore();
2394
+ const mx = (p.x + q.x) / 2;
2395
+ const my = (p.y + q.y) / 2 - 30;
2396
+ circle(mx, my, 13, '#fff', '#ff4d4f', 2);
2397
+ text('⚔️', mx, my + 1, { size: 13 });
2398
+ }
2399
+ }
2400
+ }
2401
+ }
2402
+
2403
+ function drawRoomDrag() {
2404
+ const src = L.roomsById[roomDrag.id];
2405
+ const dst = roomDrag.target && L.roomsById[roomDrag.target];
2406
+ if (src) {
2407
+ ctx.fillStyle = 'rgba(20,24,34,.35)';
2408
+ ctx.fillRect(src.x, src.y, src.w, src.h);
2409
+ }
2410
+ if (dst) {
2411
+ ctx.setLineDash([14, 10]);
2412
+ rr(dst.x - 6, dst.y - 6, dst.w + 12, dst.h + 12, 10, 'rgba(79,124,255,.12)', '#4f7cff', 5);
2413
+ ctx.setLineDash([]);
2414
+ text('⇄', dst.x + dst.w / 2, dst.y + dst.h / 2, { size: 64, weight: 900, color: 'rgba(79,124,255,.8)' });
2415
+ }
2416
+ }
2417
+
2418
+ // The break game unlocks while every agent present is working.
2419
+ // The break game unlocks while everyone is busy. Idle sessions in the boss's
2420
+ // own terminals don't count: they are just waiting for the boss to type.
2421
+ function canPlay() {
2422
+ const present = S.agents.filter((a) => a.status !== 'offline' && !a.subagent && !(a.external && a.status === 'idle'));
2423
+ return present.length > 0 && present.every((a) => a.status === 'working');
2424
+ }
2425
+
2426
+ function drawBuilding() {
2427
+ for (const bl of Object.values(L.buildings)) {
2428
+ const b = bl.rect;
2429
+ const tint = bl.b.color || '#3b3447';
2430
+ rr(b.x - 8, b.y - 8, b.w + 16, b.h + 16, 18, tint);
2431
+ rr(b.x, b.y, b.w, b.h, 12, tilePattern);
2432
+ if (!bl.hq) rr(b.x, b.y, b.w, b.h, 12, alpha(tint.length === 7 ? tint : '#3b3447', 0.08));
2433
+ const e = bl.entrance;
2434
+ rr(e.x - 50, b.y + b.h - 6, 100, 18, 4, '#b8a58a');
2435
+ rr(e.x - 36, b.y + b.h - 2, 72, 30, 6, shade(tint.length === 7 ? tint : '#3b3447', 60));
2436
+ text(tx('world.entrance'), e.x, b.y + b.h + 14, { size: 11, color: '#f5ead8', weight: 700 });
2437
+ }
2438
+ }
2439
+
2440
+ // Building signs (except the HQ, which has the boss's office and lobby) and "+ room" spots.
2441
+ const TOOL_ICONS = { claude: '✳', cursor: '◆', codex: '◎', gemini: '✦', aider: '▲', opencode: '▣', custom: '⚙' };
2442
+ const TOOL_COLORS = { claude: '#d97757', cursor: '#7c8cff', codex: '#10a37f', gemini: '#4f8df5', aider: '#f2a93b', opencode: '#9aa4b2', custom: '#8d99ae' };
2443
+ function drawBuildingSigns() {
2444
+ for (const bl of Object.values(L.buildings)) {
2445
+ const tint = bl.b.color || '#3b3447';
2446
+ if (!bl.hq) {
2447
+ const r = bl.sign;
2448
+ const hov = hover?.type === 'building' && hover.id === bl.b.id;
2449
+ rr(r.x + 20, r.y + 30, r.w - 40, r.h - 50, 30, '#d3d7de', hov ? tint : null, 3);
2450
+ rr(r.x + 20, r.y + 30, 14, r.h - 50, [30, 0, 0, 30], tint);
2451
+ text(bl.b.name.toUpperCase(), r.x + r.w / 2, r.y + 70, { size: 28, weight: 900, color: '#2f3442' });
2452
+ const tool = bl.b.tool || 'claude';
2453
+ text(`${bl.b.company ? bl.b.company + ' · ' : ''}${tx('world.defaultTool')}: ${TOOL_ICONS[tool]} ${tool === 'claude' ? 'Claude Code' : tool}`, r.x + r.w / 2, r.y + 100, { size: 12, color: '#56657a' });
2454
+ circle(r.x + r.w / 2, r.y + 134, 17, TOOL_COLORS[tool] || '#888');
2455
+ text(TOOL_ICONS[tool] || '⚙', r.x + r.w / 2, r.y + 135, { size: 16, weight: 800, color: '#fff' });
2456
+ drawPlant(r.x + 60, r.y + 150);
2457
+ drawPlant(r.x + r.w - 60, r.y + 150);
2458
+ }
2459
+ const a = bl.addRoom;
2460
+ const hov = hover?.type === 'addRoom' && hover.building === bl.b.id;
2461
+ ctx.setLineDash([12, 10]);
2462
+ rr(a.x, a.y, a.w, a.h, 14, hov ? alpha('#7c8cff', 0.16) : 'rgba(255,255,255,.25)', hov ? '#7c8cff' : '#8c97a8', 3);
2463
+ ctx.setLineDash([]);
2464
+ text(tx('world.addRoom'), a.x + a.w / 2, a.y + a.h / 2 - 10, { size: 18, weight: 800, color: '#3d4a5c' });
2465
+ text(tx('world.addRoomHint', { name: bl.b.name }), a.x + a.w / 2, a.y + a.h / 2 + 18, { size: 12, color: '#5d6b80' });
2466
+ }
2467
+ }
2468
+
2469
+ // Empty lot at the end of the city: click it to open a new office / team.
2470
+ function drawLot() {
2471
+ const a = L.lot;
2472
+ const hov = hover?.type === 'addBuilding';
2473
+ ctx.setLineDash([16, 12]);
2474
+ rr(a.x, a.y, a.w, a.h, 18, hov ? alpha('#7c8cff', 0.18) : 'rgba(255,255,255,.06)', hov ? '#7c8cff' : '#8c97a8', 4);
2475
+ ctx.setLineDash([]);
2476
+ circle(a.x + a.w / 2, a.y + a.h / 2 - 30, 48, hov ? '#7c8cff' : '#6b7689');
2477
+ text('+', a.x + a.w / 2, a.y + a.h / 2 - 28, { size: 56, weight: 900, color: '#fff' });
2478
+ text(tx('top.addBuilding'), a.x + a.w / 2, a.y + a.h / 2 + 50, { size: 30, weight: 800, color: hov ? '#c9d1ff' : '#d5dbe5' });
2479
+ }
2480
+
2481
+ function drawWalls(r, color = '#3d3a4b', doorW = 70) {
2482
+ ctx.strokeStyle = color;
2483
+ ctx.lineWidth = 8;
2484
+ ctx.lineCap = 'round';
2485
+ ctx.beginPath();
2486
+ ctx.moveTo(r.x + r.w / 2 - doorW / 2, r.y + r.h);
2487
+ ctx.lineTo(r.x, r.y + r.h);
2488
+ ctx.lineTo(r.x, r.y);
2489
+ ctx.lineTo(r.x + r.w, r.y);
2490
+ ctx.lineTo(r.x + r.w, r.y + r.h);
2491
+ ctx.lineTo(r.x + r.w / 2 + doorW / 2, r.y + r.h);
2492
+ ctx.stroke();
2493
+ ctx.lineCap = 'butt';
2494
+ }
2495
+
2496
+ function drawPlant(x, y, s = 1) {
2497
+ rr(x - 9 * s, y - 2 * s, 18 * s, 16 * s, 3 * s, '#b5643c');
2498
+ circle(x, y - 10 * s, 13 * s, '#3f8f4f');
2499
+ circle(x - 8 * s, y - 4 * s, 8 * s, '#4ea35d');
2500
+ circle(x + 8 * s, y - 6 * s, 8 * s, '#367f45');
2501
+ }
2502
+
2503
+ function drawBoss(t) {
2504
+ const r = L.boss;
2505
+ rr(r.x, r.y, r.w, r.h, 4, '#e7dccb');
2506
+ rr(r.x + 90, r.y + 50, r.w - 180, r.h - 70, 10, '#8e3b46');
2507
+ rr(r.x + 98, r.y + 58, r.w - 196, r.h - 86, 8, null, 'rgba(255,215,140,.5)', 2);
2508
+ // windows
2509
+ for (let i = 0; i < 6; i++) rr(r.x + 30 + i * ((r.w - 60) / 6), r.y + 2, (r.w - 60) / 6 - 10, 8, 2, '#9fd3ff');
2510
+ // desk + chair
2511
+ const cx = r.x + r.w / 2;
2512
+ rr(cx - 34, r.y + 60, 68, 40, 14, '#2b2b2b');
2513
+ rr(cx - 110, r.y + 104, 220, 54, 6, '#5b3a29', '#3e2619', 2);
2514
+ rr(cx - 60, r.y + 110, 46, 30, 3, '#1f2937');
2515
+ rr(cx - 56, r.y + 113, 38, 22, 2, '#60a5fa');
2516
+ rr(cx + 30, r.y + 116, 40, 12, 2, '#f5f5f5');
2517
+ rr(cx - 40, r.y + 146, 80, 14, 3, '#c9a227');
2518
+ text(tx('world.bossPlate'), cx, r.y + 153, { size: 10, weight: 800, color: '#3a2a05' });
2519
+ drawPlant(r.x + 40, r.y + 150, 1.2);
2520
+ drawPlant(r.x + r.w - 40, r.y + 150, 1.2);
2521
+ text(tx('world.bossRoom'), r.x + 16, r.y + 28, { size: 16, weight: 700, color: '#3d3a4b', align: 'left' });
2522
+ text(tx('world.bossHint'), r.x + r.w - 16, r.y + 28, { size: 11, color: '#7a7280', align: 'right' });
2523
+ if (hover?.type === 'boss') rr(r.x + 4, r.y + 4, r.w - 8, r.h - 8, 4, null, 'rgba(255,179,71,.9)', 3);
2524
+ drawWalls(r, '#3d3a4b', 70);
2525
+ }
2526
+
2527
+ function drawLobby() {
2528
+ const r = L.lobby;
2529
+ if (!r) return;
2530
+ rr(r.x + 20, r.y + 30, r.w - 40, r.h - 50, 30, '#cfc6b5');
2531
+ text('AGENT HALL', r.x + r.w / 2, r.y + 75, { size: 30, weight: 900, color: '#3d3a4b' });
2532
+ text(tx('world.lobbyTag'), r.x + r.w / 2, r.y + 104, { size: 12, color: '#6c6474' });
2533
+ rr(r.x + r.w / 2 - 80, r.y + 124, 160, 32, 14, '#6b7fa8');
2534
+ rr(r.x + r.w / 2 - 74, r.y + 128, 148, 12, 6, '#8396c0');
2535
+ drawPlant(r.x + 50, r.y + 150);
2536
+ drawPlant(r.x + r.w - 50, r.y + 150);
2537
+ // a meeting is on: the table comes out
2538
+ if ((S.meetings || []).some((m) => m.status === 'running')) {
2539
+ rr(r.x + r.w / 2 - 150, r.y + 128, 300, 40, 12, '#8b5e3c', '#6d4529', 2);
2540
+ for (const k of [-1, 0, 1]) rr(r.x + r.w / 2 + k * 95 - 8, r.y + 140, 26, 16, 2, '#f5f5f4');
2541
+ }
2542
+ if (hover?.type === 'lobby') rr(r.x + 4, r.y + 4, r.w - 8, r.h - 8, 4, null, 'rgba(255,179,71,.9)', 3);
2543
+ }
2544
+
2545
+ const boardRect = (room) => ({ x: room.x + room.w - 150, y: room.y + 14, w: 130, h: 22 });
2546
+ function boardCounts(projectId) {
2547
+ const c = { todo: 0, doing: 0, done: 0 };
2548
+ for (const t of S.tasks || []) if (t.projectId === projectId) c[t.status]++;
2549
+ return c;
2550
+ }
2551
+
2552
+ function drawRoom(room, t) {
2553
+ const p = room.p;
2554
+ rr(room.x, room.y, room.w, room.h, 4, woodPattern);
2555
+ // header wall
2556
+ rr(room.x, room.y, room.w, HEADER, 0, '#efe7da');
2557
+ ctx.fillStyle = p.color;
2558
+ ctx.fillRect(room.x, room.y + HEADER - 6, room.w, 6);
2559
+ for (let i = 0; i < 5; i++) rr(room.x + 330 + i * 58, room.y + 2, 46, 8, 2, '#9fd3ff');
2560
+ text(p.name, room.x + 18, room.y + 28, { size: 19, weight: 800, color: '#2f2b3a', align: 'left' });
2561
+ const ags = S.agents.filter((a) => a.projectId === p.id);
2562
+ const w = ags.filter((a) => a.status === 'working' || a.status === 'waiting').length;
2563
+ const short = p.path.length > 52 ? '…' + p.path.slice(-51) : p.path;
2564
+ text(`${short}`, room.x + 18, room.y + 50, { size: 11, color: '#7a7280', align: 'left', font: 'ui-monospace, Menlo, monospace' });
2565
+ text(`${p.auto ? tx('world.tempRoom') : ''}${tx('world.roomCount', { n: ags.length, w })}`, room.x + room.w - 16, room.y + 50, { size: 11, color: '#7a7280', align: 'right' });
2566
+ // whiteboard: the room's task board
2567
+ const br = boardRect(room);
2568
+ const bc = boardCounts(p.id);
2569
+ const bhov = hover?.type === 'board' && hover.id === p.id;
2570
+ rr(br.x, br.y, br.w, br.h, 3, bhov ? '#fff7d6' : '#ffffff', bhov ? '#e0a800' : '#b8b0a4');
2571
+ if (bc.todo) rr(br.x + 4, br.y + 4, 14, 14, 2, '#ffd66b');
2572
+ text(bc.todo || bc.doing ? tx('board.short', { todo: bc.todo, doing: bc.doing }) : tx('board.empty'), br.x + br.w / 2 + (bc.todo ? 7 : 0), br.y + 11, { size: 10, color: '#6a6270' });
2573
+ drawPlant(room.x + 26, room.y + room.h - 26);
2574
+ drawPlant(room.x + room.w - 26, room.y + room.h - 26);
2575
+ rr(room.x + room.w / 2 - 34, room.y + room.h - 16, 68, 12, 3, alpha(p.color, 0.45));
2576
+ if (!ags.length) {
2577
+ text(tx('world.roomEmpty'), room.x + room.w / 2, room.y + room.h - 34, { size: 13, color: '#9a8f80' });
2578
+ }
2579
+ if (hover?.type === 'room' && hover.id === room.id) rr(room.x + 4, room.y + 4, room.w - 8, room.h - 8, 4, null, alpha(p.color, 0.9), 3);
2580
+ }
2581
+
2582
+ function drawChair(desk) {
2583
+ const s = desk.seat;
2584
+ const big = desk.big;
2585
+ const hov = !desk.agent && hover?.type === 'emptyDesk' && hover.desk === desk;
2586
+ if (!desk.agent) {
2587
+ // Pushed-back free chair with a "+" to hire someone.
2588
+ rr(s.x - 14, s.y - 40, 28, 30, 10, hov ? '#4f7cff' : big ? '#3a3a3a' : '#6b7280');
2589
+ rr(s.x - 12, s.y - 14, 24, 10, 4, hov ? '#3d6af0' : '#4b5563');
2590
+ text('+', s.x, s.y - 26, { size: 20, weight: 800, color: hov ? '#fff' : 'rgba(255,255,255,.55)' });
2591
+ return;
2592
+ }
2593
+ rr(s.x - (big ? 17 : 14), s.y - (big ? 50 : 44), big ? 34 : 28, big ? 40 : 34, 10, big ? '#2b2b2b' : '#4b5563');
2594
+ }
2595
+
2596
+ function drawDesk(desk, t) {
2597
+ const a = desk.agent || { id: 'free' + desk.x + desk.y, role: desk.emptyRole };
2598
+ const live = (desk.agent && agentById(a.id)) || { ...a, status: 'offline' };
2599
+ const status = live.status;
2600
+ rr(desk.x + 3, desk.y + 5, desk.w, desk.h, 6, 'rgba(0,0,0,.18)');
2601
+ rr(desk.x, desk.y, desk.w, desk.h, 6, desk.big ? '#6b4430' : '#a7794f', desk.big ? '#4a2d1f' : '#7d5a3a', 2);
2602
+ rr(desk.x + 4, desk.y + 4, desk.w - 8, 6, 3, 'rgba(255,255,255,.12)');
2603
+ // monitor
2604
+ const mx = desk.x + 10;
2605
+ const my = desk.y - 20;
2606
+ const mw = desk.big ? 44 : 36;
2607
+ const mh = desk.big ? 30 : 25;
2608
+ rr(mx + mw / 2 - 3, my + mh - 2, 6, 10, 1, '#333');
2609
+ rr(mx, my, mw, mh, 3, '#1f2937');
2610
+ const sx = mx + 3;
2611
+ const sy = my + 3;
2612
+ const sw = mw - 6;
2613
+ const sh = mh - 6;
2614
+ if (status === 'working') {
2615
+ rr(sx, sy, sw, sh, 1, '#0f172a');
2616
+ const shift = Math.floor(t / 180);
2617
+ for (let i = 0; i < 5; i++) {
2618
+ const r = hash(a.id + (i + shift));
2619
+ ctx.fillStyle = ['#7dd3fc', '#86efac', '#fca5a5', '#fde68a'][r % 4];
2620
+ ctx.fillRect(sx + 2 + (r % 4) * 2, sy + 2 + i * (sh / 5.2), 6 + (r >> 4) % (sw - 12), 2);
2621
+ }
2622
+ } else if (status === 'waiting') {
2623
+ const pulse = 0.5 + 0.5 * Math.sin(t / 200);
2624
+ rr(sx, sy, sw, sh, 1, `rgba(239,68,68,${0.55 + 0.4 * pulse})`);
2625
+ text('?', sx + sw / 2, sy + sh / 2 + 1, { size: 14, weight: 900, color: '#fff' });
2626
+ } else if (status === 'idle' || status === 'starting') {
2627
+ rr(sx, sy, sw, sh, 1, '#1e3a8a');
2628
+ circle(sx + ((t / 40) % sw), sy + sh / 2 + Math.sin(t / 300) * 4, 2, '#93c5fd');
2629
+ } else {
2630
+ rr(sx, sy, sw, sh, 1, '#111');
2631
+ }
2632
+ // keyboard, mug, papers
2633
+ rr(desk.seat.x - 14, desk.y + 12, 28, 8, 2, '#d1d5db');
2634
+ if (desk.big) {
2635
+ rr(desk.x + desk.w - 30, desk.y + 14, 18, 22, 2, '#f8fafc', '#cbd5e1');
2636
+ circle(desk.x + 66, desk.y + 40, 5, '#ef4444');
2637
+ } else {
2638
+ circle(desk.x + desk.w - 14, desk.y + 34, 5, '#f8fafc', '#94a3b8');
2639
+ }
2640
+ // nameplate
2641
+ const badge = ROLE_BADGE[live.role] || ROLE_BADGE.mid;
2642
+ rr(desk.x + desk.w / 2 - 34, desk.y + desk.h - 13, 68, 11, 2, !desk.agent ? '#d1d5db' : status === 'offline' ? '#9ca3af' : '#e5c27a');
2643
+ text(desk.agent ? `${badge.s} ${roleLabel(live.role)}` : tx('world.freeDesk'), desk.x + desk.w / 2, desk.y + desk.h - 7, { size: 8, weight: 700, color: '#3a2a05' });
2644
+ }
2645
+
2646
+ function drawGarden(t) {
2647
+ const g = L.garden;
2648
+ rr(g.x - 10, g.y - 10, g.w + 20, g.h + 20, 26, '#3c7a3a');
2649
+ rr(g.x, g.y, g.w, g.h, 20, grassPattern);
2650
+ // stone path from the gate
2651
+ ctx.fillStyle = '#d8ccb4';
2652
+ for (let x = g.x; x < g.pond.x - 70; x += 34) {
2653
+ ctx.beginPath();
2654
+ ctx.ellipse(x + 14, g.pond.y + Math.sin(x / 60) * 8, 13, 9, 0, 0, Math.PI * 2);
2655
+ ctx.fill();
2656
+ }
2657
+ // smoking area
2658
+ circle(g.smoke.x, g.smoke.y + 10, 78, '#b9b4aa');
2659
+ circle(g.smoke.x, g.smoke.y + 10, 78, null, '#a39d92', 3);
2660
+ text(tx('world.smoking'), g.smoke.x, g.smoke.y - 82, { size: 13, weight: 700, color: '#244c22' });
2661
+ // cafe terrace
2662
+ rr(g.cafe.x - 120, g.cafe.y + 50, 240, 150, 14, '#c9a77c');
2663
+ text(tx('world.coffee'), g.cafe.x, g.cafe.y - 62, { size: 13, weight: 700, color: '#244c22' });
2664
+ // pond
2665
+ ctx.fillStyle = '#5aa9d6';
2666
+ ctx.beginPath();
2667
+ ctx.ellipse(g.pond.x, g.pond.y, 110, 60, 0, 0, Math.PI * 2);
2668
+ ctx.fill();
2669
+ ctx.strokeStyle = '#a7d8f0';
2670
+ ctx.lineWidth = 5;
2671
+ ctx.stroke();
2672
+ for (let i = 0; i < 3; i++) {
2673
+ const r = ((t / 30 + i * 33) % 100) / 100;
2674
+ ctx.strokeStyle = `rgba(255,255,255,${0.5 * (1 - r)})`;
2675
+ ctx.lineWidth = 1.5;
2676
+ ctx.beginPath();
2677
+ ctx.ellipse(g.pond.x - 20, g.pond.y + 5, 10 + r * 40, 5 + r * 20, 0, 0, Math.PI * 2);
2678
+ ctx.stroke();
2679
+ }
2680
+ circle(g.pond.x + 40, g.pond.y - 18, 9, '#4f9d4a');
2681
+ circle(g.pond.x - 55, g.pond.y + 20, 7, '#4f9d4a');
2682
+ // picnic area
2683
+ rr(g.picnic.x - 110, g.picnic.y - 70, 220, 160, 20, '#d9c9a5');
2684
+ text(tx('world.garden'), g.x + g.w / 2, g.y + 86, { size: 22, weight: 900, color: 'rgba(30,70,30,.35)' });
2685
+ // fence / gate on the building side
2686
+ ctx.fillStyle = '#8a6a48';
2687
+ for (let y = g.y + 20; y < g.y + g.h - 20; y += 22) {
2688
+ if (Math.abs(y - g.pond.y) < 90) continue;
2689
+ ctx.fillRect(g.x - 4, y, 8, 14);
2690
+ ctx.fillRect(g.x + g.w - 4, y, 8, 14);
2691
+ }
2692
+ }
2693
+
2694
+ // Depth-sorted garden furniture.
2695
+ function gardenItems(items, t) {
2696
+ const g = L.garden;
2697
+ for (const tr of g.trees) {
2698
+ items.push({
2699
+ y: tr.y + 10,
2700
+ draw: () => {
2701
+ ctx.fillStyle = 'rgba(0,0,0,.18)';
2702
+ ctx.beginPath();
2703
+ ctx.ellipse(tr.x + 6, tr.y + 12, tr.r, tr.r * 0.4, 0, 0, Math.PI * 2);
2704
+ ctx.fill();
2705
+ rr(tr.x - 4, tr.y - 6, 8, 18, 2, '#6b4423');
2706
+ circle(tr.x, tr.y - tr.r * 0.7, tr.r, '#2f7d3a');
2707
+ circle(tr.x - tr.r * 0.4, tr.y - tr.r * 0.9, tr.r * 0.6, '#3c9447');
2708
+ circle(tr.x + tr.r * 0.35, tr.y - tr.r * 0.5, tr.r * 0.55, '#276b31');
2709
+ },
2710
+ });
2711
+ }
2712
+ items.push({
2713
+ y: g.smoke.y + 6,
2714
+ draw: () => {
2715
+ rr(g.smoke.x - 6, g.smoke.y - 30, 12, 38, 4, '#6b7280');
2716
+ ctx.fillStyle = '#4b5563';
2717
+ ctx.beginPath();
2718
+ ctx.ellipse(g.smoke.x, g.smoke.y - 30, 13, 5, 0, 0, Math.PI * 2);
2719
+ ctx.fill();
2720
+ },
2721
+ });
2722
+ items.push({
2723
+ y: g.cafe.y + 40,
2724
+ draw: () => {
2725
+ const c = g.cafe;
2726
+ rr(c.x - 100, c.y - 10, 200, 56, 6, '#7c4a2d', '#5a341f', 2);
2727
+ rr(c.x - 96, c.y - 6, 192, 10, 3, '#a5734f');
2728
+ for (let i = 0; i < 8; i++) {
2729
+ ctx.fillStyle = i % 2 ? '#ffffff' : '#e63946';
2730
+ ctx.fillRect(c.x - 110 + i * 27.5, c.y - 48, 27.5, 22);
2731
+ }
2732
+ rr(c.x - 60, c.y - 26, 26, 20, 3, '#9ca3af');
2733
+ rr(c.x + 30, c.y - 22, 14, 16, 2, '#f8fafc');
2734
+ circle(c.x + 60, c.y - 14, 7, '#f59e0b');
2735
+ const steam = (t / 400) % 1;
2736
+ ctx.strokeStyle = `rgba(255,255,255,${0.8 - steam * 0.8})`;
2737
+ ctx.lineWidth = 2;
2738
+ ctx.beginPath();
2739
+ ctx.moveTo(c.x - 47, c.y - 28);
2740
+ ctx.quadraticCurveTo(c.x - 40, c.y - 38 - steam * 10, c.x - 47, c.y - 46 - steam * 12);
2741
+ ctx.stroke();
2742
+ },
2743
+ });
2744
+ for (const tb of [{ x: g.cafe.x - 50, y: g.cafe.y + 132 }, { x: g.cafe.x + 50, y: g.cafe.y + 132 }]) {
2745
+ items.push({ y: tb.y, draw: () => { circle(tb.x, tb.y, 14, '#f5f5f4', '#a8a29e', 2); } });
2746
+ }
2747
+ for (const b of g.benches) {
2748
+ items.push({
2749
+ y: b.y - 12,
2750
+ draw: () => {
2751
+ rr(b.x - 62, b.y - 32, 124, 12, 3, '#8b5a2b');
2752
+ rr(b.x - 62, b.y - 14, 124, 16, 3, '#a0682f', '#6b4423', 1.5);
2753
+ },
2754
+ });
2755
+ }
2756
+ items.push({
2757
+ y: g.picnic.y + 12,
2758
+ draw: () => {
2759
+ const p = g.picnic;
2760
+ rr(p.x - 90, p.y - 6, 180, 30, 5, '#a0682f', '#6b4423', 2);
2761
+ circle(p.x, p.y + 8, 5, '#555');
2762
+ },
2763
+ });
2764
+ }
2765
+
2766
+ // ------------------------------------------------------------------ people
2767
+
2768
+ function drawPerson(sp, a, t) {
2769
+ const x = sp.x;
2770
+ const y = sp.y;
2771
+ const act = !sp.walking && sp.dest ? sp.dest.act : 'walk';
2772
+ const seated = !sp.walking && (act === 'desk' || act === 'bench' || act === 'picnic');
2773
+ const atDesk = seated && act === 'desk';
2774
+ const skin = SKIN[hash(a.id) % SKIN.length];
2775
+ const hair = HAIR[hash(a.id + 'h') % HAIR.length];
2776
+ const bob = sp.walking ? Math.abs(Math.sin(sp.phase)) * 2 : act === 'smoke' || act === 'coffee' ? Math.sin(t / 700 + hash(a.id)) * 0.6 : 0;
2777
+ const isHover = hover?.type === 'agent' && hover.id === a.id;
2778
+ const isPanel = panelId === a.id;
2779
+ // An agent asking for work steps closer to the screen: drawn larger.
2780
+ const zoom = act === 'ask' ? 1.45 + Math.sin(t / 400) * 0.03 : 1;
2781
+ if (act === 'swim') return drawSwimmer(sp, a, t, { x, y, skin, hair, isHover, isPanel });
2782
+ const dancing = act === 'dance';
2783
+ if (zoom !== 1 || dancing) {
2784
+ ctx.save();
2785
+ ctx.translate(x, y);
2786
+ if (dancing) {
2787
+ ctx.translate(0, -Math.abs(Math.sin(t / 180)) * 6);
2788
+ ctx.rotate(Math.sin(t / 260) * 0.22);
2789
+ }
2790
+ ctx.scale(zoom, zoom);
2791
+ ctx.translate(-x, -y);
2792
+ }
2793
+ drawPersonBody(sp, a, t, { x, y, act: dancing ? 'ask' : act, seated, atDesk, skin, hair, bob, isHover, isPanel });
2794
+ if (zoom !== 1 || dancing) ctx.restore();
2795
+ if (dancing) {
2796
+ for (let i = 0; i < 3; i++) {
2797
+ const k = (t / 1400 + i / 3) % 1;
2798
+ text(i % 2 ? '♫' : '♪', x - 18 + i * 18 + Math.sin(k * 6 + i) * 4, y - 50 - k * 30, { size: 14, weight: 700, color: `rgba(79,124,255,${1 - k})` });
2799
+ }
2800
+ }
2801
+ }
2802
+
2803
+ // A cardboard box of desk things (plant, mug, photo) held in front with both hands;
2804
+ // while packing, the things drop into the box one by one.
2805
+ function drawBox(sp, x, by, skin) {
2806
+ const bx = x - 15;
2807
+ const bw = 30;
2808
+ const top = by + 6;
2809
+ const packed = sp.packUntil ? 1 - Math.max(0, sp.packUntil - performance.now()) / 1800 : 1;
2810
+ // item i appears above the box during its third of the packing time and drops in
2811
+ const k = (i) => Math.min(1, Math.max(0, packed * 3 - i));
2812
+ const drop = (i) => (1 - k(i)) * 14;
2813
+ // things sticking out of the box
2814
+ if (k(0) > 0) {
2815
+ rr(x - 10, top - 9 - drop(0), 3, 10, 1, '#3f8f4e');
2816
+ circle(x - 9, top - 10 - drop(0), 4, '#4caf50');
2817
+ circle(x - 5, top - 8 - drop(0), 3, '#5cc96a');
2818
+ }
2819
+ if (k(1) > 0) rr(x - 1, top - 6 - drop(1), 7, 7, 2, '#e5e7eb', '#9ca3af', 1);
2820
+ if (k(2) > 0) {
2821
+ rr(x + 7, top - 10 - drop(2), 7, 10, 1, '#fbbf24', '#92400e', 1);
2822
+ rr(x + 8.5, top - 8.5 - drop(2), 4, 5, 1, '#93c5fd');
2823
+ }
2824
+ // the box
2825
+ rr(bx, top, bw, 18, 2, '#c8975a', '#8a6233', 1.5);
2826
+ rr(bx, top, bw, 4, [2, 2, 0, 0], '#b58548');
2827
+ rr(x - 5, top + 7, 10, 3, 1, 'rgba(0,0,0,.18)');
2828
+ circle(bx + 1, top + 11, 3.5, skin);
2829
+ circle(bx + bw - 1, top + 11, 3.5, skin);
2830
+ }
2831
+
2832
+ // Only head and shoulders above the water, with a rubber ring and ripples.
2833
+ function drawSwimmer(sp, a, t, { x, y, skin, hair, isHover, isPanel }) {
2834
+ const bobY = Math.sin(t / 500 + hash(a.id)) * 2;
2835
+ const water = y - 18 + bobY;
2836
+ ctx.save();
2837
+ ctx.beginPath();
2838
+ ctx.rect(x - 40, water - 80, 80, 80);
2839
+ ctx.clip();
2840
+ drawPersonBody({ ...sp, walking: false }, a, t, { x, y: y + bobY, act: 'stroll', seated: false, atDesk: false, skin, hair, bob: 0, isHover, isPanel });
2841
+ ctx.restore();
2842
+ for (let i = 0; i < 2; i++) {
2843
+ const k = ((t / 1200 + i / 2) % 1);
2844
+ ctx.strokeStyle = `rgba(255,255,255,${0.7 * (1 - k)})`;
2845
+ ctx.lineWidth = 1.5;
2846
+ ctx.beginPath();
2847
+ ctx.ellipse(x, water + 1, 14 + k * 16, 4 + k * 5, 0, 0, Math.PI * 2);
2848
+ ctx.stroke();
2849
+ }
2850
+ ctx.lineWidth = 5;
2851
+ ctx.strokeStyle = hash(a.id) % 2 ? '#ff6b6b' : '#ffd166';
2852
+ ctx.beginPath();
2853
+ ctx.ellipse(x, water + 1, 15, 5, 0, 0, Math.PI * 2);
2854
+ ctx.stroke();
2855
+ ctx.lineWidth = 5;
2856
+ ctx.strokeStyle = '#ffffff';
2857
+ ctx.setLineDash([6, 8]);
2858
+ ctx.beginPath();
2859
+ ctx.ellipse(x, water + 1, 15, 5, 0, 0, Math.PI * 2);
2860
+ ctx.stroke();
2861
+ ctx.setLineDash([]);
2862
+ }
2863
+
2864
+ function drawPersonBody(sp, a, t, { x, y, act, seated, atDesk, skin, hair, bob, isHover, isPanel }) {
2865
+ if (!atDesk) {
2866
+ ctx.fillStyle = 'rgba(0,0,0,.2)';
2867
+ ctx.beginPath();
2868
+ ctx.ellipse(x, y + 1, 13, 4.5, 0, 0, Math.PI * 2);
2869
+ ctx.fill();
2870
+ }
2871
+ if (isHover || isPanel || a.status === 'waiting') {
2872
+ const pulse = a.status === 'waiting' ? 0.5 + 0.5 * Math.sin(t / 180) : 1;
2873
+ ctx.strokeStyle = a.status === 'waiting' ? `rgba(255,77,79,${0.4 + 0.6 * pulse})` : isPanel ? '#4f7cff' : '#ffb347';
2874
+ ctx.lineWidth = 3;
2875
+ ctx.beginPath();
2876
+ ctx.ellipse(x, y - (atDesk ? 22 : 2), 19, atDesk ? 19 : 7, 0, 0, Math.PI * 2);
2877
+ ctx.stroke();
2878
+ }
2879
+ // legs
2880
+ if (!seated) {
2881
+ const sw = sp.walking ? Math.sin(sp.phase) * 4 : 0;
2882
+ rr(x - 7 + sw * 0.3, y - 12, 6, 12 + (sp.walking ? Math.max(0, sw) * 0.4 : 0), 2, '#374151');
2883
+ rr(x + 1 - sw * 0.3, y - 12, 6, 12 + (sp.walking ? Math.max(0, -sw) * 0.4 : 0), 2, '#374151');
2884
+ } else if (!atDesk) {
2885
+ rr(x - 8, y - 8, 7, 9, 2, '#374151');
2886
+ rr(x + 1, y - 8, 7, 9, 2, '#374151');
2887
+ }
2888
+ const by = y - 32 + bob + (seated && !atDesk ? 4 : 0);
2889
+ // body
2890
+ rr(x - 12, by, 24, 23, 9, a.color);
2891
+ rr(x - 12, by + 15, 24, 8, [0, 0, 9, 9], 'rgba(0,0,0,.12)');
2892
+ if (a.role === 'lead') {
2893
+ ctx.fillStyle = '#1f2937';
2894
+ ctx.beginPath();
2895
+ ctx.moveTo(x, by + 2);
2896
+ ctx.lineTo(x - 3, by + 12);
2897
+ ctx.lineTo(x, by + 15);
2898
+ ctx.lineTo(x + 3, by + 12);
2899
+ ctx.fill();
2900
+ }
2901
+ // arms
2902
+ if (sp.box) {
2903
+ drawBox(sp, x, by, skin);
2904
+ } else if (atDesk && a.status === 'working') {
2905
+ const k = Math.sin(t / 60 + hash(a.id)) * 2;
2906
+ circle(x - 9, by + 20 + k, 3.5, skin);
2907
+ circle(x + 9, by + 20 - k, 3.5, skin);
2908
+ } else if (act === 'ask') {
2909
+ circle(x - 13, by + 13, 3.5, skin);
2910
+ const wave = Math.sin(t / 160) * 3;
2911
+ ctx.strokeStyle = a.color;
2912
+ ctx.lineWidth = 5;
2913
+ ctx.lineCap = 'round';
2914
+ ctx.beginPath();
2915
+ ctx.moveTo(x + 10, by + 6);
2916
+ ctx.lineTo(x + 16 + wave, by - 12);
2917
+ ctx.stroke();
2918
+ ctx.lineCap = 'butt';
2919
+ circle(x + 16 + wave, by - 14, 4, skin);
2920
+ } else if (act === 'sulk') {
2921
+ rr(x - 13, by + 9, 26, 6, 3, shade(a.color, -30));
2922
+ } else {
2923
+ circle(x - 13, by + 13, 3.5, skin);
2924
+ circle(x + 13, by + 13 - (act === 'smoke' || act === 'coffee' || act === 'phone' ? 5 : 0), 3.5, skin);
2925
+ }
2926
+ // head
2927
+ const hx = x;
2928
+ const hy = by - 9;
2929
+ const look = lookOf(a);
2930
+ const style = hairStyleOf(a, look);
2931
+ // hair that falls behind the head and onto the shoulders
2932
+ if (style === 'long') rr(hx - 12.5, hy - 6, 25, 23, 8, hair);
2933
+ if (style === 'bob') rr(hx - 12.5, hy - 6, 25, 15, 6, hair);
2934
+ if (style === 'curlyLong') for (const [ox, oy] of [[-11, 2], [11, 2], [-11, 9], [11, 9], [-8, 14], [8, 14], [0, 15]]) circle(hx + ox, hy + oy, 4.6, hair);
2935
+ circle(hx, hy, 11, skin);
2936
+ ctx.fillStyle = hair;
2937
+ ctx.beginPath();
2938
+ if (style === 'buzz') ctx.arc(hx, hy - 1, 11.2, Math.PI * 1.12, Math.PI * 1.88);
2939
+ else ctx.arc(hx, hy - 1, 11.5, Math.PI * 1.05, Math.PI * 1.95);
2940
+ ctx.fill();
2941
+ if (style === 'curly' || style === 'curlyLong') for (let i = 0; i < 5; i++) circle(hx - 9 + i * 4.5, hy - 9 - (i % 2) * 1.5, 3.4, hair);
2942
+ if (style === 'side') rr(hx - 10, hy - 9, 12, 4, 2, hair);
2943
+ if (style === 'bun') {
2944
+ circle(hx, hy - 13, 5.5, hair);
2945
+ circle(hx, hy - 13, 5.5, null, shade(hair.length === 7 ? hair : '#333333', -20), 1);
2946
+ }
2947
+ if (style === 'ponytail') {
2948
+ rr(hx + 8, hy - 7, 6, 17, 3, hair);
2949
+ circle(hx + 10.5, hy - 6, 2, '#ef476f');
2950
+ }
2951
+ if (style === 'long' || style === 'bob') {
2952
+ const len = style === 'long' ? 19 : 13;
2953
+ rr(hx - 13.5, hy - 6, 5.5, len, 2.5, hair);
2954
+ rr(hx + 8, hy - 6, 5.5, len, 2.5, hair);
2955
+ rr(hx - 9, hy - 10, 10, 4, 2, hair); // fringe
2956
+ }
2957
+ if (look === 'f' && hash(a.id + 'ear') % 2 === 0) {
2958
+ circle(hx - 11, hy + 5, 1.5, '#f4c430');
2959
+ circle(hx + 11, hy + 5, 1.5, '#f4c430');
2960
+ }
2961
+ const blink = (t + hash(a.id)) % 4200 < 140;
2962
+ if (look === 'f' && !blink) {
2963
+ ctx.strokeStyle = '#1f2937';
2964
+ ctx.lineWidth = 1;
2965
+ for (const ex of [-4, 4]) {
2966
+ ctx.beginPath();
2967
+ ctx.moveTo(hx + ex - 2.4 + sp.facing * 0.8, hy - 1.2);
2968
+ ctx.lineTo(hx + ex - 3.6 + sp.facing * 0.8, hy - 2.6);
2969
+ ctx.moveTo(hx + ex + 2.4 + sp.facing * 0.8, hy - 1.2);
2970
+ ctx.lineTo(hx + ex + 3.6 + sp.facing * 0.8, hy - 2.6);
2971
+ ctx.stroke();
2972
+ }
2973
+ }
2974
+ ctx.fillStyle = '#1f2937';
2975
+ if (blink || act === 'bench') {
2976
+ ctx.fillRect(hx - 6, hy + 1, 4, 1.5);
2977
+ ctx.fillRect(hx + 2, hy + 1, 4, 1.5);
2978
+ } else {
2979
+ circle(hx - 4 + sp.facing * 0.8, hy + 1, 1.6, '#1f2937');
2980
+ circle(hx + 4 + sp.facing * 0.8, hy + 1, 1.6, '#1f2937');
2981
+ }
2982
+ if (act === 'sulk' && !sp.walking) {
2983
+ ctx.strokeStyle = '#7c2d12';
2984
+ ctx.lineWidth = 1.2;
2985
+ ctx.beginPath();
2986
+ ctx.arc(hx, hy + 7, 3, 1.15 * Math.PI, 1.85 * Math.PI);
2987
+ ctx.stroke();
2988
+ } else if (a.status === 'idle' && !sp.walking) {
2989
+ ctx.strokeStyle = '#7c2d12';
2990
+ ctx.lineWidth = 1.2;
2991
+ ctx.beginPath();
2992
+ ctx.arc(hx, hy + 4, 3, 0.15 * Math.PI, 0.85 * Math.PI);
2993
+ ctx.stroke();
2994
+ }
2995
+ // props
2996
+ if (!sp.walking) {
2997
+ const px = x + 13;
2998
+ const py = by + 8;
2999
+ if (act === 'smoke') {
3000
+ ctx.strokeStyle = '#f5f5f5';
3001
+ ctx.lineWidth = 2.2;
3002
+ ctx.beginPath();
3003
+ ctx.moveTo(px, py);
3004
+ ctx.lineTo(px + 8, py - 3);
3005
+ ctx.stroke();
3006
+ circle(px + 8.5, py - 3.2, 1.6, (t / 300) % 2 < 1 ? '#ff6b35' : '#ffa62b');
3007
+ for (let i = 0; i < 4; i++) {
3008
+ const k = ((t / 1600 + i / 4 + hash(a.id) / 1e9) % 1);
3009
+ circle(px + 9 + Math.sin(k * 6 + i) * 4, py - 6 - k * 30, 2 + k * 5, `rgba(220,220,220,${0.55 * (1 - k)})`);
3010
+ }
3011
+ } else if (act === 'coffee' || act === 'picnic') {
3012
+ rr(px - 2, py - 6, 8, 9, 2, '#fff', '#9ca3af');
3013
+ const k = (t / 1200 + hash(a.id) / 1e9) % 1;
3014
+ circle(px + 2, py - 9 - k * 12, 1.5 + k * 2, `rgba(255,255,255,${0.7 * (1 - k)})`);
3015
+ } else if (act === 'phone') {
3016
+ rr(px - 1, py - 8, 6, 10, 1.5, '#111827');
3017
+ rr(px, py - 7, 4, 7, 1, '#60a5fa');
3018
+ }
3019
+ }
3020
+ }
3021
+
3022
+ function drawLabel(sp, a) {
3023
+ const y = !sp.walking && sp.dest && sp.dest.labelY ? sp.dest.labelY : sp.y + 14;
3024
+ const badge = ROLE_BADGE[a.role] || ROLE_BADGE.mid;
3025
+ ctx.font = '700 12px system-ui, -apple-system, sans-serif';
3026
+ const toolMark = a.tool && a.tool !== 'claude' ? ` ${TOOL_ICONS[a.tool] || '⚙'}` : '';
3027
+ const mark = toolMark + (a.subagent ? ' ↳' : a.external ? ' 🖥' : '') + (a.game ? ` · Lv${a.game.level}` : '') + (a.id === employeeOfMonth ? ' 🏆' : '');
3028
+ const label = `${badge.s} ${a.name}${mark}`;
3029
+ const w = ctx.measureText(label).width + 14;
3030
+ rr(sp.x - w / 2, y - 9, w, 18, 9, 'rgba(20,22,30,.82)');
3031
+ const dot = { working: '#2ecc71', waiting: '#ff4d4f', idle: '#f4c430', starting: '#9ca3af' }[a.status] || '#9ca3af';
3032
+ circle(sp.x - w / 2 + 2, y - 7, 4, dot, 'rgba(20,22,30,.9)', 1.5);
3033
+ ctx.fillStyle = badge.c;
3034
+ ctx.textAlign = 'left';
3035
+ ctx.textBaseline = 'middle';
3036
+ ctx.fillText(badge.s, sp.x - w / 2 + 7, y + 0.5);
3037
+ ctx.fillStyle = '#fff';
3038
+ ctx.fillText(' ' + a.name + mark, sp.x - w / 2 + 7 + ctx.measureText(badge.s).width, y + 0.5);
3039
+ }
3040
+
3041
+ function drawBubble(x, y, str, { bg = '#fff', fg = '#1f2937', size = 11, maxW = 190 } = {}) {
3042
+ ctx.font = `600 ${size}px system-ui, -apple-system, sans-serif`;
3043
+ let s = str;
3044
+ while (ctx.measureText(s).width > maxW && s.length > 4) s = s.slice(0, -2);
3045
+ if (s !== str) s = s.trimEnd() + '…';
3046
+ const w = ctx.measureText(s).width + 16;
3047
+ const h = size + 12;
3048
+ rr(x - w / 2, y - h, w, h, 8, bg, 'rgba(0,0,0,.15)');
3049
+ ctx.fillStyle = bg;
3050
+ ctx.beginPath();
3051
+ ctx.moveTo(x - 5, y - 1);
3052
+ ctx.lineTo(x, y + 6);
3053
+ ctx.lineTo(x + 5, y - 1);
3054
+ ctx.fill();
3055
+ ctx.fillStyle = fg;
3056
+ ctx.textAlign = 'center';
3057
+ ctx.textBaseline = 'middle';
3058
+ ctx.fillText(s, x, y - h / 2);
3059
+ }
3060
+
3061
+ const ASK_LINES = [
3062
+ (a) => tx('ask.1', { min: idleMinutes(a) }),
3063
+ () => tx('ask.2'),
3064
+ () => tx('ask.3'),
3065
+ ];
3066
+ const idleMinutes = (a) => Math.max(1, Math.round((Date.now() - (a.game?.idleSince || Date.now())) / 60000));
3067
+ const moraleFace = (m) => (m >= 85 ? '😄' : m >= 65 ? '🙂' : m >= 45 ? '😐' : m >= 25 ? '😟' : '😤');
3068
+
3069
+ function drawCloud(x, y, t) {
3070
+ const dx = Math.sin(t / 900) * 3;
3071
+ ctx.fillStyle = '#6b7280';
3072
+ for (const [ox, oy, r] of [[-12, 0, 10], [0, -6, 13], [13, 0, 10], [0, 4, 10]]) circle(x + ox + dx, y + oy, r, '#6b7280');
3073
+ ctx.strokeStyle = '#60a5fa';
3074
+ ctx.lineWidth = 1.6;
3075
+ for (let i = 0; i < 4; i++) {
3076
+ const k = ((t / 500 + i / 4) % 1);
3077
+ ctx.beginPath();
3078
+ ctx.moveTo(x - 12 + i * 8 + dx, y + 12 + k * 18);
3079
+ ctx.lineTo(x - 14 + i * 8 + dx, y + 17 + k * 18);
3080
+ ctx.stroke();
3081
+ }
3082
+ text('😤', x + 24 + dx, y - 12, { size: 14 });
3083
+ }
3084
+
3085
+ // Envelopes flying from sender to receiver when agents message each other.
3086
+ const mails = [];
3087
+ function drawMails(t) {
3088
+ for (let i = mails.length - 1; i >= 0; i--) {
3089
+ const m = mails[i];
3090
+ const a = sprites.get(m.from);
3091
+ const b = sprites.get(m.to);
3092
+ const k = (t - m.t0) / 2200;
3093
+ if (!a || !b || k >= 1) {
3094
+ mails.splice(i, 1);
3095
+ continue;
3096
+ }
3097
+ const e = k < 0.5 ? 2 * k * k : 1 - Math.pow(-2 * k + 2, 2) / 2;
3098
+ const x = a.x + (b.x - a.x) * e;
3099
+ const y = a.y - 40 + (b.y - a.y) * e - Math.sin(Math.PI * e) * Math.min(260, Math.hypot(b.x - a.x, b.y - a.y) * 0.35);
3100
+ ctx.save();
3101
+ ctx.translate(x, y);
3102
+ ctx.rotate(Math.sin(t / 120) * 0.15);
3103
+ rr(-13, -9, 26, 18, 3, '#ffffff', '#94a3b8', 1.5);
3104
+ ctx.strokeStyle = '#94a3b8';
3105
+ ctx.lineWidth = 1.5;
3106
+ ctx.beginPath();
3107
+ ctx.moveTo(-13, -9);
3108
+ ctx.lineTo(0, 2);
3109
+ ctx.lineTo(13, -9);
3110
+ ctx.stroke();
3111
+ circle(0, 3, 3, '#ef476f');
3112
+ ctx.restore();
3113
+ }
3114
+ }
3115
+
3116
+ // Confetti bursts for level-ups and achievements, in world coordinates.
3117
+ const confetti = [];
3118
+ function burst(x, y, n = 60) {
3119
+ const colors = ['#f4c430', '#ef476f', '#4f7cff', '#2ecc71', '#ff9f1c', '#b388ff'];
3120
+ for (let i = 0; i < n; i++) {
3121
+ const ang = Math.random() * Math.PI * 2;
3122
+ const sp = 80 + Math.random() * 220;
3123
+ confetti.push({ x, y, vx: Math.cos(ang) * sp, vy: Math.sin(ang) * sp - 180, life: 1.6 + Math.random(), c: colors[i % colors.length], r: Math.random() * Math.PI });
3124
+ }
3125
+ }
3126
+ function drawConfetti(dt) {
3127
+ for (let i = confetti.length - 1; i >= 0; i--) {
3128
+ const p = confetti[i];
3129
+ p.life -= dt;
3130
+ if (p.life <= 0) {
3131
+ confetti.splice(i, 1);
3132
+ continue;
3133
+ }
3134
+ p.vy += 420 * dt;
3135
+ p.x += p.vx * dt;
3136
+ p.y += p.vy * dt;
3137
+ p.r += dt * 8;
3138
+ ctx.save();
3139
+ ctx.translate(p.x, p.y);
3140
+ ctx.rotate(p.r);
3141
+ ctx.globalAlpha = Math.min(1, p.life);
3142
+ ctx.fillStyle = p.c;
3143
+ ctx.fillRect(-4, -2, 8, 4);
3144
+ ctx.restore();
3145
+ }
3146
+ }
3147
+
3148
+ const idleChat = (i) => { const list = tx('chat'); return list[i % list.length]; };
3149
+
3150
+ // Overhead bubbles stay compact (an icon) so neighbours do not overlap; the
3151
+ // full text shows when the boss hovers the agent (or has its panel open).
3152
+ function drawOverhead(sp, a, t) {
3153
+ const top = sp.y - (sp.dest?.act === 'desk' && !sp.walking ? 66 : 62);
3154
+ const open = (hover?.type === 'agent' && hover.id === a.id) || panelId === a.id;
3155
+ const say = (icon, full, opts = {}) => {
3156
+ if (open && full) drawBubble(sp.x, top, full, { maxW: 260, ...opts });
3157
+ else drawBubble(sp.x, top, icon, { ...opts, size: 13 });
3158
+ };
3159
+ const b = bubbles.get(a.id);
3160
+ if (b && b.until > t) {
3161
+ say(b.kind === 'announce' ? '📢' : '💬', b.text, { bg: b.kind === 'announce' ? '#fff7d6' : '#e0f2fe' });
3162
+ return;
3163
+ }
3164
+ const gm = a.game;
3165
+ if (gm?.oneOnOne && !sp.walking) return say('🤝', tx('bubble.oneOnOne'));
3166
+ if (gm?.asking && !sp.walking) return say('🙋', ASK_LINES[Math.min(gm.asking, 3) - 1](a), { bg: '#fff7d6' });
3167
+ if (gm?.sulking && !sp.walking) {
3168
+ drawCloud(sp.x, top - 6, t);
3169
+ if (open) drawBubble(sp.x, top - 34, tx('bubble.sulk'), { maxW: 260 });
3170
+ return;
3171
+ }
3172
+ if (a.status === 'waiting') {
3173
+ const pulse = 1 + 0.12 * Math.sin(t / 150);
3174
+ circle(sp.x, top - 10, 12 * pulse, '#ff4d4f', '#fff', 2);
3175
+ text('!', sp.x, top - 9, { size: 16, weight: 900, color: '#fff' });
3176
+ if (open) drawBubble(sp.x, top - 26, tx('bubble.waiting'), { bg: '#ffe4e4', maxW: 260 });
3177
+ return;
3178
+ }
3179
+ if (a.meeting && !sp.walking) {
3180
+ const m = (S.meetings || []).find((x) => x.id === a.meeting);
3181
+ if (m) return say(a.status === 'working' ? '🗣' : '👂', tx('meet.bubble', { topic: m.topic.slice(0, 80) }), { bg: '#e0f2fe' });
3182
+ }
3183
+ if (a.visit && !sp.walking) return say('💬', tx('bubble.visit'));
3184
+ if (a.stuck && a.status === 'working') {
3185
+ // smoke rising from the desk, a warning sign above the head
3186
+ for (let i = 0; i < 4; i++) {
3187
+ const k = (t / 1400 + i / 4) % 1;
3188
+ circle(sp.x + 22 + Math.sin(k * 6 + i) * 5, top + 10 - k * 34, 4 + k * 7, `rgba(120,120,120,${0.55 * (1 - k)})`);
3189
+ }
3190
+ const pulse = 1 + 0.1 * Math.sin(t / 200);
3191
+ circle(sp.x, top - 10, 12 * pulse, '#f59e0b', '#fff', 2);
3192
+ text('⚠', sp.x, top - 10, { size: 13, weight: 900, color: '#fff' });
3193
+ if (open) drawBubble(sp.x, top - 26, stuckText(a), { bg: '#fff3d6', maxW: 280 });
3194
+ return;
3195
+ }
3196
+ if (a.status === 'working' && !sp.walking && sp.dest?.act === 'desk') {
3197
+ if (open && (a.tool || a.task)) return drawBubble(sp.x, top, a.tool ? `🔧 ${a.tool}` : `📝 ${a.task}`, { maxW: 280 });
3198
+ rr(sp.x - 18, top - 18, 36, 18, 9, '#fff', 'rgba(0,0,0,.15)');
3199
+ for (let i = 0; i < 3; i++) {
3200
+ const k = Math.sin(t / 180 - i * 0.9);
3201
+ circle(sp.x - 9 + i * 9, top - 9 - Math.max(0, k) * 3, 2.6, '#64748b');
3202
+ }
3203
+ return;
3204
+ }
3205
+ if (a.status === 'starting') return say('👋', tx('bubble.morning'));
3206
+ if (a.status === 'idle' && !sp.walking) {
3207
+ const slot = Math.floor((t + (hash(a.id) % 9000)) / 9000);
3208
+ const chatting = hash(a.id + slot) % 4 === 0 && (t + (hash(a.id) % 9000)) % 9000 < 4200;
3209
+ if (open) drawBubble(sp.x, top, chatting ? idleChat(hash(a.id + 'c' + slot)) : tx('bubble.break'), { maxW: 260 });
3210
+ else if (chatting) drawBubble(sp.x, top, '💬', { size: 13 });
3211
+ }
3212
+ }
3213
+
3214
+ function drawOfflineDesk(desk) {
3215
+ if (!desk.agent) return;
3216
+ const a = agentById(desk.agent.id);
3217
+ if (!a || a.status !== 'offline' || sprites.has(a.id)) return;
3218
+ const y = desk.y + desk.h + 15;
3219
+ ctx.font = '600 11px system-ui, -apple-system, sans-serif';
3220
+ const label = tx('world.atHome', { name: a.name });
3221
+ const w = ctx.measureText(label).width + 14;
3222
+ rr(desk.x + desk.w / 2 - w / 2, y - 9, w, 18, 9, 'rgba(60,60,70,.55)');
3223
+ text(label, desk.x + desk.w / 2, y + 0.5, { size: 11, weight: 600, color: '#f3f4f6' });
3224
+ }
3225
+
3226
+ // ------------------------------------------------------------------ frame
3227
+
3228
+ let lastT = performance.now();
3229
+ let frameDt = 0;
3230
+ function frame(t) {
3231
+ const dt = Math.min(0.05, (t - lastT) / 1000);
3232
+ frameDt = dt;
3233
+ lastT = t;
3234
+ if (L) {
3235
+ stepCamera(t);
3236
+ stepSprites(dt, t);
3237
+ render(t);
3238
+ }
3239
+ const askCv = !$('#ask-card').hidden && $('.ask-portrait');
3240
+ const asker = askCv && agentById(askCardId);
3241
+ if (asker) drawPortrait(askCv, asker, t);
3242
+ requestAnimationFrame(frame);
3243
+ }
3244
+
3245
+ function render(t) {
3246
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
3247
+ ctx.fillStyle = '#2a3142';
3248
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
3249
+ ctx.setTransform(dpr * cam.s, 0, 0, dpr * cam.s, -cam.x * cam.s * dpr, -cam.y * cam.s * dpr);
3250
+
3251
+ drawBackground(t);
3252
+ drawBuilding();
3253
+ drawGarden(t);
3254
+ drawBoss(t);
3255
+ drawLobby();
3256
+ drawBuildingSigns();
3257
+ drawLot();
3258
+ for (const room of L.rooms) drawRoom(room, t);
3259
+
3260
+ if (roomDrag && roomDrag.moved) drawRoomDrag();
3261
+
3262
+ const items = [];
3263
+ for (const room of L.rooms) {
3264
+ for (const desk of room.desks) {
3265
+ items.push({ y: desk.seat.y - 1, draw: () => drawChair(desk) });
3266
+ items.push({ y: desk.y + desk.h, draw: () => drawDesk(desk, t) });
3267
+ }
3268
+ items.push({ y: room.y + room.h, draw: () => drawWalls(room) });
3269
+ }
3270
+ gardenItems(items, t);
3271
+ for (const [id, sp] of sprites) {
3272
+ const a = agentById(id) || sp.ghost;
3273
+ if (a && !sp.hidden) items.push({ y: sp.y, draw: () => drawPerson(sp, a, t) });
3274
+ }
3275
+ items.sort((p, q) => p.y - q.y);
3276
+ for (const it of items) it.draw();
3277
+ drawNight();
3278
+
3279
+ drawFireScenes(t);
3280
+ drawConflicts(t);
3281
+ for (const room of L.rooms) for (const desk of room.desks) drawOfflineDesk(desk);
3282
+ for (const [id, sp] of sprites) {
3283
+ const a = agentById(id) || sp.ghost;
3284
+ if (a && !sp.hidden) drawLabel(sp, a);
3285
+ }
3286
+ const front = hover?.type === 'agent' ? hover.id : panelId;
3287
+ for (const [id, sp] of sprites) {
3288
+ const a = agentById(id);
3289
+ if (a && id !== front && !sp.hidden) drawOverhead(sp, a, t);
3290
+ }
3291
+ const fsp = front && sprites.get(front);
3292
+ if (fsp && !fsp.hidden && agentById(front)) drawOverhead(fsp, agentById(front), t);
3293
+ drawConfetti(frameDt);
3294
+ drawMails(t);
3295
+ drawFocusDim();
3296
+ if (roomDrag && roomDrag.moved && mouse) {
3297
+ const p = projectById(roomDrag.id);
3298
+ if (p) {
3299
+ ctx.font = '800 18px system-ui, -apple-system, sans-serif';
3300
+ const w = ctx.measureText(p.name).width + 40;
3301
+ rr(mouse.x - w / 2, mouse.y - 22, w, 44, 12, alpha(p.color, 0.92), '#ffffff', 2);
3302
+ text('🏢 ' + p.name, mouse.x, mouse.y, { size: 18, weight: 800, color: '#fff' });
3303
+ }
3304
+ }
3305
+ }
3306
+
3307
+ // ------------------------------------------------------------------ terminal panel
3308
+
3309
+ let term = null;
3310
+ let fitAddon = null;
3311
+ let panelId = null;
3312
+
3313
+ function initTerm() {
3314
+ term = new Terminal({
3315
+ fontFamily: 'Menlo, "SF Mono", Monaco, Consolas, "Liberation Mono", monospace',
3316
+ fontSize: 13,
3317
+ cursorBlink: true,
3318
+ scrollback: 8000,
3319
+ allowProposedApi: true,
3320
+ theme: { background: '#0b0d12', foreground: '#e5e7eb', cursor: '#ffb347', selectionBackground: '#334155' },
3321
+ });
3322
+ fitAddon = new FitAddon.FitAddon();
3323
+ term.loadAddon(fitAddon);
3324
+ term.open($('#term'));
3325
+ term.onData((d) => panelId && wsSend({ t: 'input', id: panelId, data: d }));
3326
+ new ResizeObserver(() => {
3327
+ if (!panelId) return;
3328
+ try {
3329
+ fitAddon.fit();
3330
+ wsSend({ t: 'resize', id: panelId, cols: term.cols, rows: term.rows });
3331
+ } catch {
3332
+ /* hidden */
3333
+ }
3334
+ }).observe($('#term-wrap'));
3335
+ }
3336
+
3337
+ function attachTerm(id) {
3338
+ wsSend({ t: 'attach', id });
3339
+ }
3340
+
3341
+ // Re-send the size so the TUI redraws itself at the panel's dimensions.
3342
+ function nudgeResize() {
3343
+ if (!panelId || !term) return;
3344
+ try {
3345
+ fitAddon.fit();
3346
+ } catch {
3347
+ return;
3348
+ }
3349
+ const { cols, rows } = term;
3350
+ const id = panelId;
3351
+ wsSend({ t: 'resize', id, cols: Math.max(20, cols - 1), rows });
3352
+ setTimeout(() => wsSend({ t: 'resize', id, cols, rows }), 90);
3353
+ }
3354
+
3355
+ function openPanel(id) {
3356
+ const switching = panelId !== id;
3357
+ panelId = id;
3358
+ document.body.classList.add('panel-open');
3359
+ $('#panel').hidden = false;
3360
+ if (!term) initTerm();
3361
+ renderPanel();
3362
+ const ext = agentById(id)?.external;
3363
+ askCardKey = '';
3364
+ renderAskCard();
3365
+ if (switching) {
3366
+ $('#p-log').innerHTML = '';
3367
+ logKey = '';
3368
+ }
3369
+ requestAnimationFrame(() => {
3370
+ resizeCanvas();
3371
+ if (ext) {
3372
+ wsSend({ t: 'detach' });
3373
+ refreshLog();
3374
+ return;
3375
+ }
3376
+ if (switching) {
3377
+ term.reset();
3378
+ attachTerm(id);
3379
+ }
3380
+ term.focus();
3381
+ });
3382
+ }
3383
+
3384
+ // Conversation view for sessions running in the boss's own terminals.
3385
+ let logKey = '';
3386
+ async function refreshLog() {
3387
+ const id = panelId;
3388
+ const a = agentById(id);
3389
+ if (!a || !a.external) return;
3390
+ try {
3391
+ const { messages } = await api('GET', `/api/agents/${id}/transcript`);
3392
+ if (panelId !== id) return;
3393
+ const key = messages.length + '|' + (messages.at(-1)?.ts || '') + (messages.at(-1)?.text || '').length;
3394
+ if (key === logKey) return;
3395
+ logKey = key;
3396
+ const box = $('#p-log');
3397
+ const atBottom = box.scrollHeight - box.scrollTop - box.clientHeight < 60;
3398
+ box.innerHTML = messages.length
3399
+ ? messages
3400
+ .map((m) =>
3401
+ m.who === 'tool'
3402
+ ? `<div class="msg tool">🔧 ${esc(m.text)}</div>`
3403
+ : `<div class="msg ${m.who}"><span class="who">${m.who === 'user' ? tx('panel.you') : esc(a.name)}</span>${esc(m.text.length > 4000 ? m.text.slice(0, 4000) + '…' : m.text)}</div>`
3404
+ )
3405
+ .join('')
3406
+ : `<div class="hint">${tx('panel.noConversation')}</div>`;
3407
+ if (atBottom || box.dataset.id !== id) box.scrollTop = box.scrollHeight;
3408
+ box.dataset.id = id;
3409
+ } catch {
3410
+ /* next tick */
3411
+ }
3412
+ }
3413
+ setInterval(() => panelId && refreshLog(), 2500);
3414
+
3415
+ function closePanel() {
3416
+ wsSend({ t: 'detach' });
3417
+ panelId = null;
3418
+ askCardKey = '';
3419
+ renderAskCard();
3420
+ $('#panel').hidden = true;
3421
+ document.body.classList.remove('panel-open');
3422
+ requestAnimationFrame(resizeCanvas);
3423
+ }
3424
+
3425
+ function renderPanel() {
3426
+ const a = agentById(panelId);
3427
+ if (!a) return;
3428
+ const p = projectById(a.projectId);
3429
+ const av = $('#p-avatar');
3430
+ av.style.background = a.color;
3431
+ av.textContent = a.name.slice(0, 1).toUpperCase();
3432
+ $('#p-name').textContent = a.name;
3433
+ const badge = ROLE_BADGE[a.role] || ROLE_BADGE.mid;
3434
+ $('#p-meta').innerHTML = `<span style="color:${badge.c}">${badge.s} ${esc(roleLabel(a.role))}</span><span>· ${esc(p?.name)}</span>${a.subagent ? `<span>· ${tx('panel.subagentOf', { parent: esc(a.parentName) })}</span>` : ''}<span class="pill ${a.status}">${statusLabel(a.status)}</span>${a.tool && a.tool !== 'claude' ? `<span>· ${TOOL_ICONS[a.tool] || '⚙'} ${esc((toolsCache || []).find((x) => x.id === a.tool)?.label || a.tool)}</span>` : ''}${a.model ? `<span>· ${esc(a.model)}</span>` : ''}${a.game ? `<span title="${tx('panel.levelMorale')}">· Lv ${a.game.level} · ${moraleFace(a.game.morale)} ${a.game.morale}${a.game.promotable ? tx('panel.promotable') : ''}</span>` : ''}`;
3435
+ const visitT = a.visit && agentById(a.visit.targetId);
3436
+ $('#p-info').innerHTML = [
3437
+ `<div title="${esc(p?.path)}">📁 <b>${esc(p?.path)}</b></div>`,
3438
+ a.worktree && a.branch ? `<div title="${esc(a.worktreePath || '')}">🌿 ${tx('wt.panel', { branch: `<b>${esc(a.branch)}</b>` })}</div>` : '',
3439
+ a.task ? `<div title="${esc(a.task)}">${tx('panel.lastTask')}<b>${esc(a.task)}</b></div>` : '',
3440
+ a.tool ? `<div>${tx('panel.now')}<b>${esc(a.tool)}</b></div>` : '',
3441
+ visitT ? `<div>${tx('panel.inVisit', { name: esc(visitT.name) })}</div>` : '',
3442
+ a.stuck ? `<div class="note">⚠️ ${esc(stuckText(a))}</div>` : '',
3443
+ ...conflictsOf(a).map((c) => `<div class="note">⚔️ ${tx('conflict.line', { names: esc(c.others.join(', ')), file: `<code>${esc(c.short)}</code>` })} <button class="ghost" data-notify="${esc(c.file)}" title="${tx('conflict.notifyTitle')}">${tx('conflict.notify')}</button></div>`),
3444
+ agentUsage(a) ? `<div title="${tx('usage.title')}">💰 ${tx('usage.today', { usage: fmtUsage(agentUsage(a)) })}</div>` : '',
3445
+ a.note ? `<div class="note">⚠️ ${esc(msgText(a.note))}</div>` : '',
3446
+ a.tool && a.tool !== 'claude' && !a.external ? `<div>${tx('panel.estimated')}</div>` : '',
3447
+ ].join('');
3448
+
3449
+ $('#term-wrap').hidden = !!a.external;
3450
+ $('#p-quick').hidden = !!a.external;
3451
+ $('#p-log').hidden = !a.external;
3452
+ $('#p-ext').hidden = !a.external;
3453
+ if (a.subagent) {
3454
+ $('#p-ext').innerHTML = `<span>${tx('panel.subagentNote', { parent: esc(a.parentName) })}</span>`;
3455
+ } else if (a.external) {
3456
+ $('#p-ext').innerHTML = `<span>${tx('panel.externalNote', { pid: a.pid })}</span>`;
3457
+ }
3458
+
3459
+ const online = a.status !== 'offline';
3460
+ const key = `${a.id}|${online}|${a.role}|${!!a.visit}`;
3461
+ const box = $('#p-actions');
3462
+ if (box.dataset.key === key) return;
3463
+ box.dataset.key = key;
3464
+ if (a.subagent) {
3465
+ const parent = agentById(a.parentId);
3466
+ box.innerHTML = parent ? `<button data-act="parent">${tx('panel.goParent', { name: esc(parent.name) })}</button>` : '';
3467
+ return;
3468
+ }
3469
+ if (a.external) {
3470
+ box.innerHTML = `
3471
+ <button data-act="takeover" class="primary">${tx('panel.takeover')}</button>
3472
+ <button data-act="oneonone">${tx('panel.oneOnOne')}</button>
3473
+ <button data-act="praise">${tx('panel.praise')}</button>
3474
+ <select data-act="role" title="${tx('panel.role')}">${S.roles.map((r) => `<option value="${r}" ${r === a.role ? 'selected' : ''}>${ROLE_BADGE[r].s} ${esc(roleLabel(r))}</option>`).join('')}</select>
3475
+ <button data-act="fire" class="danger">${tx('panel.fire')}</button>`;
3476
+ return;
3477
+ }
3478
+ box.innerHTML = `
3479
+ ${online ? `<button data-act="stop" class="danger">${tx('panel.stop')}</button>` : `<button data-act="start" class="primary">${tx('panel.start')}</button>`}
3480
+ ${a.status === 'working' && (!a.tool || a.tool === 'claude') ? `<button data-act="interrupt" class="${a.stuck ? 'danger' : ''}" title="${tx('panel.interruptTitle')}">⏹ ${tx('panel.interrupt')}</button>` : ''}
3481
+ <button data-act="visit" ${online ? '' : 'disabled'}>${tx('panel.visit')}</button>
3482
+ <button data-act="oneonone" ${online ? '' : 'disabled'}>${tx('panel.oneOnOne')}</button>
3483
+ <button data-act="praise" ${online ? '' : 'disabled'}>${tx('panel.praise')}</button>
3484
+ ${a.visit ? `<button data-act="return">${tx('panel.return')}</button>` : ''}
3485
+ <select data-act="role" title="${tx('panel.role')}">${S.roles.map((r) => `<option value="${r}" ${r === a.role ? 'selected' : ''}>${ROLE_BADGE[r].s} ${esc(roleLabel(r))}</option>`).join('')}</select>
3486
+ <button data-act="edit" ${online ? `disabled title="${tx('panel.settingsLocked')}"` : ''}>${tx('panel.settings')}</button>
3487
+ <button data-act="fire" class="danger">${tx('panel.fire')}</button>`;
3488
+ }
3489
+
3490
+ async function fireAgent(a) {
3491
+ if (!confirm(tx(a.external ? 'confirm.fireExternal' : 'confirm.fire', { name: a.name }))) return;
3492
+ firedIds.add(a.id);
3493
+ // offline agents have no figure yet: let them stand up at their desk to pack
3494
+ const seat = L.seats.get(a.id);
3495
+ if (!sprites.has(a.id) && seat) sprites.set(a.id, { id: a.id, x: seat.x, y: seat.y, zone: seat.zone, path: [], phase: 0, facing: 1, dest: null, ghost: a, nextWander: Infinity });
3496
+ await api('DELETE', `/api/agents/${a.id}`).catch((err) => {
3497
+ firedIds.delete(a.id);
3498
+ throw err;
3499
+ });
3500
+ toast(tx('toast.fired', { name: a.name }), 'ok');
3501
+ }
3502
+
3503
+ $('#p-info').addEventListener('click', async (e) => {
3504
+ const b = e.target.closest('[data-notify]');
3505
+ if (!b) return;
3506
+ try {
3507
+ const r = await api('POST', '/api/conflicts/notify', { file: b.dataset.notify });
3508
+ toast(tx(r.skipped ? 'conflict.notifiedSome' : 'conflict.notified', { n: r.sent, skipped: r.skipped }), 'ok');
3509
+ } catch (err) {
3510
+ toast(err.message, 'err');
3511
+ }
3512
+ });
3513
+ $('#p-actions').addEventListener('click', async (e) => {
3514
+ const btn = e.target.closest('button[data-act]');
3515
+ if (!btn || !panelId) return;
3516
+ const a = agentById(panelId);
3517
+ try {
3518
+ switch (btn.dataset.act) {
3519
+ case 'start':
3520
+ await api('POST', `/api/agents/${a.id}/start`);
3521
+ break;
3522
+ case 'interrupt':
3523
+ await api('POST', `/api/agents/${a.id}/interrupt`);
3524
+ break;
3525
+ case 'oneonone':
3526
+ openOneOnOne(a.id);
3527
+ break;
3528
+ case 'praise':
3529
+ await api('POST', `/api/agents/${a.id}/praise`);
3530
+ break;
3531
+ case 'parent':
3532
+ openPanel(a.parentId);
3533
+ break;
3534
+ case 'takeover': {
3535
+ if (!confirm(tx('confirm.takeover', { name: a.name }))) break;
3536
+ const r = await api('POST', `/api/agents/${a.id}/takeover`);
3537
+ if (r.error) toast(r.error, 'err');
3538
+ else {
3539
+ toast(tx(r.forked ? 'toast.takeoverFork' : 'toast.takeover', { name: a.name }), 'ok');
3540
+ setTimeout(() => openPanel(r.agent.id), 400);
3541
+ }
3542
+ break;
3543
+ }
3544
+ case 'stop':
3545
+ await api('POST', `/api/agents/${a.id}/stop`);
3546
+ break;
3547
+ case 'visit':
3548
+ openVisitModal(a.id);
3549
+ break;
3550
+ case 'return':
3551
+ await api('POST', `/api/agents/${a.id}/return`);
3552
+ break;
3553
+ case 'edit':
3554
+ openEditModal(a.id);
3555
+ break;
3556
+ case 'fire':
3557
+ await fireAgent(a);
3558
+ break;
3559
+ }
3560
+ } catch (err) {
3561
+ toast(err.message, 'err');
3562
+ }
3563
+ });
3564
+ $('#p-actions').addEventListener('change', async (e) => {
3565
+ if (e.target.dataset.act !== 'role' || !panelId) return;
3566
+ try {
3567
+ await api('PATCH', `/api/agents/${panelId}`, { role: e.target.value });
3568
+ toast(tx('toast.roleChanged'), 'ok');
3569
+ } catch (err) {
3570
+ toast(err.message, 'err');
3571
+ }
3572
+ });
3573
+ $('#p-close').addEventListener('click', closePanel);
3574
+
3575
+ // Drag the panel's left edge to resize it (double-click resets); the width is remembered.
3576
+ const PANEL_MIN_W = 360;
3577
+ function setPanelWidth(w) {
3578
+ if (w == null) document.documentElement.style.removeProperty('--panel-w');
3579
+ else document.documentElement.style.setProperty('--panel-w', `${Math.round(Math.max(PANEL_MIN_W, Math.min(w, innerWidth - 200)))}px`);
3580
+ }
3581
+ try {
3582
+ const w = +localStorage.getItem('ao-panel-w');
3583
+ if (w) setPanelWidth(w);
3584
+ } catch {
3585
+ /* storage unavailable */
3586
+ }
3587
+ $('#p-resize').addEventListener('pointerdown', (e) => {
3588
+ e.preventDefault();
3589
+ const handle = e.currentTarget;
3590
+ handle.setPointerCapture(e.pointerId);
3591
+ document.body.classList.add('panel-resizing');
3592
+ const move = (ev) => {
3593
+ setPanelWidth(innerWidth - ev.clientX);
3594
+ resizeCanvas();
3595
+ };
3596
+ const up = () => {
3597
+ handle.removeEventListener('pointermove', move);
3598
+ handle.removeEventListener('pointerup', up);
3599
+ handle.removeEventListener('pointercancel', up);
3600
+ document.body.classList.remove('panel-resizing');
3601
+ try {
3602
+ localStorage.setItem('ao-panel-w', String(Math.round($('#panel').getBoundingClientRect().width)));
3603
+ } catch {
3604
+ /* storage unavailable */
3605
+ }
3606
+ term?.focus();
3607
+ };
3608
+ handle.addEventListener('pointermove', move);
3609
+ handle.addEventListener('pointerup', up);
3610
+ handle.addEventListener('pointercancel', up);
3611
+ });
3612
+ $('#p-resize').addEventListener('dblclick', () => {
3613
+ setPanelWidth(null);
3614
+ try {
3615
+ localStorage.removeItem('ao-panel-w');
3616
+ } catch {
3617
+ /* storage unavailable */
3618
+ }
3619
+ resizeCanvas();
3620
+ });
3621
+ $('#p-quick').addEventListener('submit', async (e) => {
3622
+ e.preventDefault();
3623
+ const input = $('#p-quick-input');
3624
+ const text = input.value.trim();
3625
+ if (!text || !panelId) return;
3626
+ try {
3627
+ await api('POST', `/api/agents/${panelId}/message`, { text });
3628
+ input.value = '';
3629
+ } catch (err) {
3630
+ toast(err.message, 'err');
3631
+ }
3632
+ });
3633
+
3634
+ // ------------------------------------------------------------------ modals
3635
+
3636
+ function openModal(html, mount) {
3637
+ $('#modal').innerHTML = html;
3638
+ $('#backdrop').hidden = false;
3639
+ const m = $('#modal');
3640
+ m.querySelectorAll('[data-close]').forEach((b) => b.addEventListener('click', closeModal));
3641
+ mount && mount(m);
3642
+ const f = m.querySelector('[autofocus]');
3643
+ if (f) setTimeout(() => f.focus(), 30);
3644
+ }
3645
+ function closeModal() {
3646
+ queueOpen = false;
3647
+ meetingsOpen = false;
3648
+ boardOpen = null;
3649
+ endOneOnOne();
3650
+ $('#backdrop').hidden = true;
3651
+ $('#modal').innerHTML = '';
3652
+ }
3653
+ $('#backdrop').addEventListener('mousedown', (e) => {
3654
+ if (e.target.id === 'backdrop') closeModal();
3655
+ });
3656
+
3657
+ function formError(m, msg) {
3658
+ const el = m.querySelector('.err');
3659
+ if (el) el.textContent = msg;
3660
+ }
3661
+
3662
+ function openProjectModal(building = L ? L.hqId : 'main') {
3663
+ openModal(
3664
+ `<h3>${tx('project.title')}</h3>
3665
+ <div class="sub">${tx('project.sub')}</div>
3666
+ <label>${tx('project.building')}</label>
3667
+ <select id="f-building">
3668
+ ${S.buildings.map((b) => `<option value="${b.id}" ${b.id === building ? 'selected' : ''}>🏢 ${esc(b.name)}${b.company ? ' · ' + esc(b.company) : ''} (${TOOL_ICONS[b.tool] || '✳'} ${esc(b.tool || 'claude')})</option>`).join('')}
3669
+ </select>
3670
+ <label>${tx('project.folder')}</label>
3671
+ <div class="row pick-row">
3672
+ <button class="primary" id="f-pick">${tx('project.pick')}</button>
3673
+ <button id="f-browse">${tx('project.browse')}</button>
3674
+ </div>
3675
+ <div id="f-picked" class="picked" hidden></div>
3676
+ <div id="f-browser" class="browser" hidden></div>
3677
+ <input id="f-path" type="hidden">
3678
+ <label>${tx('project.name')}</label>
3679
+ <input id="f-name" placeholder="${tx('project.namePh')}">
3680
+ <label>${tx('project.recent')}</label>
3681
+ <div class="chips" id="f-sugg"><span class="hint">${tx('project.loading')}</span></div>
3682
+ <div class="err"></div>
3683
+ <div class="foot"><button data-close>${tx('common.cancel')}</button><button class="primary" id="f-ok">${tx('project.open')}</button></div>`,
3684
+ async (m) => {
3685
+ const pathEl = $('#f-path', m);
3686
+ const nameEl = $('#f-name', m);
3687
+ const choose = (dir) => {
3688
+ pathEl.value = dir;
3689
+ if (!nameEl.dataset.touched) nameEl.value = dir.split(/[\\/]/).filter(Boolean).pop() || dir;
3690
+ const box = $('#f-picked', m);
3691
+ box.hidden = false;
3692
+ box.innerHTML = `📁 <b>${esc(dir)}</b>`;
3693
+ formError(m, '');
3694
+ };
3695
+ nameEl.addEventListener('input', () => (nameEl.dataset.touched = '1'));
3696
+ $('#f-pick', m).onclick = async () => {
3697
+ const btn = $('#f-pick', m);
3698
+ btn.disabled = true;
3699
+ btn.textContent = tx('project.picking');
3700
+ try {
3701
+ const r = await api('POST', '/api/pick-folder');
3702
+ if (r.path) choose(r.path);
3703
+ else if (r.error) {
3704
+ formError(m, `${tx('project.noNative')} (${r.error})`);
3705
+ openBrowser(m, choose);
3706
+ }
3707
+ } catch (err) {
3708
+ formError(m, err.message);
3709
+ } finally {
3710
+ btn.disabled = false;
3711
+ btn.textContent = tx('project.pick');
3712
+ }
3713
+ };
3714
+ $('#f-browse', m).onclick = () => openBrowser(m, choose);
3715
+ const submit = async () => {
3716
+ if (!pathEl.value) return formError(m, tx('project.pickFirst'));
3717
+ try {
3718
+ const p = await api('POST', '/api/projects', { path: pathEl.value.trim(), name: nameEl.value.trim(), building: $('#f-building', m).value });
3719
+ closeModal();
3720
+ toast(tx('project.opened', { name: p.name }), 'ok');
3721
+ setTimeout(() => openHireModal(p.id), 200);
3722
+ } catch (err) {
3723
+ formError(m, err.message);
3724
+ }
3725
+ };
3726
+ $('#f-ok', m).onclick = submit;
3727
+ nameEl.addEventListener('keydown', (e) => e.key === 'Enter' && submit());
3728
+ try {
3729
+ const list = await api('GET', '/api/suggest-projects');
3730
+ const box = $('#f-sugg', m);
3731
+ if (!box) return;
3732
+ box.innerHTML = list.length
3733
+ ? list.map((s) => `<button class="chip" data-path="${esc(s.path)}" title="${esc(s.path)}">${esc(s.name)}<small>${esc(s.path.replace(/^\/Users\/[^/]+/, '~'))}</small></button>`).join('')
3734
+ : `<span class="hint">${tx('project.none')}</span>`;
3735
+ box.addEventListener('click', (e) => {
3736
+ const b = e.target.closest('[data-path]');
3737
+ if (b) choose(b.dataset.path);
3738
+ });
3739
+ } catch {
3740
+ /* optional */
3741
+ }
3742
+ }
3743
+ );
3744
+ }
3745
+
3746
+ const MODELS = [
3747
+ ['', 'model.default'],
3748
+ ['opus', 'model.opus'],
3749
+ ['sonnet', 'model.sonnet'],
3750
+ ['haiku', 'model.haiku'],
3751
+ ];
3752
+ function modelField(current = '') {
3753
+ const known = MODELS.some(([v]) => v === current);
3754
+ return `<select id="f-model">
3755
+ ${MODELS.map(([v, l]) => `<option value="${v}" ${v === current ? 'selected' : ''}>${tx(l)}</option>`).join('')}
3756
+ <option value="__custom" ${known ? '' : 'selected'}>${tx('model.custom')}</option>
3757
+ </select>
3758
+ <input id="f-model-custom" placeholder="${tx('model.customPh')}" value="${known ? '' : esc(current)}" style="margin-top:6px" ${known ? 'hidden' : ''}>`;
3759
+ }
3760
+ function readModel(m) {
3761
+ const el = $('#f-model', m);
3762
+ if (el.tagName !== 'SELECT') return el.value.trim();
3763
+ return el.value === '__custom' ? $('#f-model-custom', m).value.trim() : el.value;
3764
+ }
3765
+ document.addEventListener('change', (e) => {
3766
+ if (e.target.id !== 'f-model') return;
3767
+ const custom = $('#f-model-custom');
3768
+ if (custom) custom.hidden = e.target.value !== '__custom';
3769
+ });
3770
+
3771
+ async function openBrowser(m, choose, dir) {
3772
+ const box = $('#f-browser', m);
3773
+ box.hidden = false;
3774
+ try {
3775
+ const r = await api('GET', '/api/browse' + (dir ? `?path=${encodeURIComponent(dir)}` : ''));
3776
+ box.innerHTML = `
3777
+ <div class="b-head">
3778
+ <button data-go="${esc(r.home)}" title="${tx('browse.home')}">🏠</button>
3779
+ ${r.parent ? `<button data-go="${esc(r.parent)}" title="${tx('browse.up')}">⬆</button>` : ''}
3780
+ <span class="b-path" title="${esc(r.path)}">${esc(r.path)}</span>
3781
+ <button class="primary" data-pick="${esc(r.path)}">${tx('browse.choose')}${r.isProject ? ' ✓' : ''}</button>
3782
+ </div>
3783
+ <div class="b-list">${r.dirs.length ? r.dirs.map((d) => `<button class="b-item" data-go="${esc(r.path.replace(/[\\/]$/, '') + (r.path.includes('\\') ? '\\' : '/') + d)}">📁 ${esc(d)}</button>`).join('') : `<span class="hint">${tx('browse.empty')}</span>`}</div>`;
3784
+ box.onclick = (e) => {
3785
+ const go = e.target.closest('[data-go]');
3786
+ if (go) return openBrowser(m, choose, go.dataset.go);
3787
+ const pick = e.target.closest('[data-pick]');
3788
+ if (pick) {
3789
+ choose(pick.dataset.pick);
3790
+ box.hidden = true;
3791
+ }
3792
+ };
3793
+ } catch (err) {
3794
+ formError(m, err.message);
3795
+ }
3796
+ }
3797
+
3798
+ // Small canvas portrait of an agent, reusing the world drawing code.
3799
+ function drawPortrait(cv, a, t) {
3800
+ const c2 = cv.getContext('2d');
3801
+ const k = window.devicePixelRatio || 1;
3802
+ if (cv.width !== cv.clientWidth * k) {
3803
+ cv.width = cv.clientWidth * k;
3804
+ cv.height = cv.clientHeight * k;
3805
+ }
3806
+ c2.setTransform(1, 0, 0, 1, 0, 0);
3807
+ c2.clearRect(0, 0, cv.width, cv.height);
3808
+ const scale = (cv.height / k / 64) * k;
3809
+ c2.setTransform(scale, 0, 0, scale, (cv.width / 2) - 0 * scale, cv.height - 6 * k);
3810
+ const saved = ctx;
3811
+ ctx = c2;
3812
+ try {
3813
+ drawPersonBody({ walking: false, facing: 1, phase: 0, dest: { act: 'ask' } }, a, t, {
3814
+ x: 0, y: 0, act: 'ask', seated: false, atDesk: false,
3815
+ skin: SKIN[hash(a.id) % SKIN.length], hair: HAIR[hash(a.id + 'h') % HAIR.length],
3816
+ bob: Math.sin(t / 300) * 1, isHover: false, isPanel: false,
3817
+ });
3818
+ } finally {
3819
+ ctx = saved;
3820
+ }
3821
+ }
3822
+
3823
+ // ---- meetings in the lobby: a few agents discuss a topic in three rounds, the chair sums up.
3824
+ let meetingsOpen = false;
3825
+ let meetingPick = new Set();
3826
+ function openMeetings() {
3827
+ meetingPick = new Set();
3828
+ openModal(
3829
+ `<h3>🗣 ${tx('meet.title')}</h3>
3830
+ <div class="sub">${tx('meet.sub')}</div>
3831
+ <div id="m-run"></div>
3832
+ <div id="m-form">
3833
+ <label>${tx('meet.topic')}</label><textarea id="m-topic" placeholder="${tx('meet.topicPh')}" autofocus></textarea>
3834
+ <label>${tx('meet.people')} <span class="muted" id="m-count"></span></label>
3835
+ <div id="m-pick" class="m-pick"></div>
3836
+ <div class="foot"><button class="primary" data-m="start">${tx('meet.start')}</button></div>
3837
+ </div>
3838
+ <div id="m-past"></div>`,
3839
+ (m) => {
3840
+ m.addEventListener('click', async (e) => {
3841
+ const b = e.target.closest('[data-m]');
3842
+ if (!b) return;
3843
+ try {
3844
+ if (b.dataset.m === 'start') {
3845
+ const topic = $('#m-topic').value.trim();
3846
+ if (!topic) return $('#m-topic').focus();
3847
+ if (meetingPick.size < 2 || meetingPick.size > 6) return toast(tx('err.meetingTeam', { max: 6 }), 'err');
3848
+ await api('POST', '/api/meetings', { topic, agentIds: [...meetingPick] });
3849
+ meetingPick = new Set();
3850
+ $('#m-topic').value = '';
3851
+ toast(tx('meet.started'), 'ok');
3852
+ } else if (b.dataset.m === 'cancel' || b.dataset.m === 'del') {
3853
+ await api('DELETE', `/api/meetings/${b.dataset.id}`);
3854
+ } else if (b.dataset.m === 'copy') {
3855
+ await navigator.clipboard.writeText(meetingMarkdown(S.meetings.find((x) => x.id === b.dataset.id)));
3856
+ toast(tx('report.copied'), 'ok');
3857
+ }
3858
+ } catch (err) {
3859
+ toast(err.message, 'err');
3860
+ }
3861
+ });
3862
+ m.querySelector('#m-pick').addEventListener('change', (e) => {
3863
+ if (!e.target.matches('[data-pick]')) return;
3864
+ if (e.target.checked) meetingPick.add(e.target.dataset.pick);
3865
+ else meetingPick.delete(e.target.dataset.pick);
3866
+ $('#m-count').textContent = `(${meetingPick.size} · 2–6)`;
3867
+ });
3868
+ }
3869
+ );
3870
+ meetingsOpen = true;
3871
+ renderMeetings();
3872
+ }
3873
+ function meetingMarkdown(m) {
3874
+ const name = (id) => m.names[id] || '?';
3875
+ return [`# ${tx('meet.title')}: ${m.topic}`, '', `**${tx('meet.people')}:** ${m.participants.map(name).join(', ')}`, '', `## ${tx('meet.summary')}`, '', m.summary || '—', '', `## ${tx('meet.discussion')}`, '', ...m.rounds.flat().map((e) => `**${name(e.agentId)}:** ${e.text}\n`)].join('\n');
3876
+ }
3877
+ // Only the parts that changed are redrawn, so typing the topic is never interrupted.
3878
+ function setHtml(el, html) {
3879
+ if (!el || el._html === html) return;
3880
+ el._html = html;
3881
+ el.innerHTML = html;
3882
+ }
3883
+ function renderMeetings() {
3884
+ if (!$('#m-run')) return;
3885
+ const running = (S.meetings || []).find((m) => m.status === 'running');
3886
+ let run = '';
3887
+ if (running) {
3888
+ const step = running.round === 2 ? tx('meet.stepSummary', { name: esc(running.names[running.participants[0]]) }) : tx('meet.stepRound', { n: running.round + 1 });
3889
+ run = `<div class="q-item"><div class="q-head"><b>${esc(running.topic)}</b><span class="muted">${step}</span></div>
3890
+ <div class="q-msg muted">${tx('meet.waiting', { names: esc((running.waiting || []).map((id) => running.names[id]).join(', ') || '—') })}</div>
3891
+ <div class="q-actions"><button class="ghost danger" data-m="cancel" data-id="${running.id}">${tx('meet.cancel')}</button></div></div>`;
3892
+ }
3893
+ setHtml($('#m-run'), run);
3894
+ $('#m-form').hidden = !!running;
3895
+ const free = S.agents.filter((a) => !a.external && !a.subagent && (!a.tool || a.tool === 'claude') && a.status === 'idle' && !a.meeting);
3896
+ for (const id of [...meetingPick]) if (!free.some((a) => a.id === id)) meetingPick.delete(id);
3897
+ setHtml(
3898
+ $('#m-pick'),
3899
+ free.map((a) => `<label class="check"><input type="checkbox" data-pick="${a.id}" ${meetingPick.has(a.id) ? 'checked' : ''}> ${esc(a.name)} <span class="muted">· ${esc(projectById(a.projectId)?.name || '')}</span></label>`).join('') || `<div class="b-none">${tx('meet.nobody')}</div>`
3900
+ );
3901
+ $('#m-count').textContent = `(${meetingPick.size} · 2–6)`;
3902
+ const past = (S.meetings || []).filter((m) => m.status !== 'running');
3903
+ let html = past.length ? `<div class="r-sec">${tx('meet.past')}</div>` : '';
3904
+ for (const m of past) {
3905
+ const name = (id) => esc(m.names[id] || '?');
3906
+ html += `<div class="q-item"><div class="q-head"><b>${esc(m.topic)}</b><span class="muted">${m.participants.map(name).join(', ')} · ${hhmm(m.startedAt)}${m.status === 'cancelled' ? ' · ' + tx('meet.cancelled') : ''}</span></div>
3907
+ ${m.summary ? `<div class="r-last">${esc(m.summary)}</div>` : ''}
3908
+ ${m.rounds.flat().length ? `<details><summary>${tx('meet.discussion')} (${m.rounds.flat().length})</summary>${m.rounds.flat().map((e) => `<div class="m-line"><b>${name(e.agentId)}:</b> ${esc(e.text)}</div>`).join('')}</details>` : ''}
3909
+ <div class="q-actions"><button class="ghost" data-m="copy" data-id="${m.id}">📋 ${tx('report.copy')}</button><button class="ghost danger" data-m="del" data-id="${m.id}">✕</button></div></div>`;
3910
+ }
3911
+ setHtml($('#m-past'), html);
3912
+ }
3913
+
3914
+ // ---- task board: cards for a room; an idle agent there takes the oldest one.
3915
+ let boardOpen = null;
3916
+ function openBoard(projectId) {
3917
+ const p = projectById(projectId);
3918
+ if (!p) return;
3919
+ if (p.auto) return toast(tx('board.tempRoom'), 'info');
3920
+ openModal(
3921
+ `<h3>📌 ${tx('board.title')} · ${esc(p.name)}</h3>
3922
+ <div class="sub">${tx('board.sub')}</div>
3923
+ <textarea id="b-text" placeholder="${tx('board.ph')}" autofocus></textarea>
3924
+ <div class="foot"><button class="primary" id="b-add">${tx('board.add')}</button></div>
3925
+ <div id="b-list"></div>
3926
+ <div class="foot"><button class="ghost" data-close>${tx('queue.close')}</button></div>`,
3927
+ (m) => {
3928
+ const add = async () => {
3929
+ const text = m.querySelector('#b-text').value.trim();
3930
+ if (!text) return m.querySelector('#b-text').focus();
3931
+ try {
3932
+ await api('POST', `/api/projects/${p.id}/tasks`, { text });
3933
+ m.querySelector('#b-text').value = '';
3934
+ m.querySelector('#b-text').focus();
3935
+ } catch (err) {
3936
+ toast(err.message, 'err');
3937
+ }
3938
+ };
3939
+ m.querySelector('#b-add').addEventListener('click', add);
3940
+ m.querySelector('#b-text').addEventListener('keydown', (e) => e.key === 'Enter' && (e.metaKey || e.ctrlKey) && add());
3941
+ m.querySelector('#b-list').addEventListener('click', async (e) => {
3942
+ const b = e.target.closest('[data-b]');
3943
+ if (!b) return;
3944
+ const act = b.dataset.b;
3945
+ try {
3946
+ if (act === 'open') {
3947
+ closeModal();
3948
+ return openPanel(b.dataset.agent);
3949
+ }
3950
+ if (act === 'del') await api('DELETE', `/api/tasks/${b.dataset.id}`);
3951
+ else if (act === 'top') await api('PATCH', `/api/tasks/${b.dataset.id}`, { top: true });
3952
+ else if (act === 'again') await api('PATCH', `/api/tasks/${b.dataset.id}`, { status: 'todo' });
3953
+ } catch (err) {
3954
+ toast(err.message, 'err');
3955
+ }
3956
+ });
3957
+ }
3958
+ );
3959
+ boardOpen = p.id;
3960
+ renderBoard();
3961
+ }
3962
+ function renderBoard() {
3963
+ const list = $('#b-list');
3964
+ if (!list || !boardOpen) return;
3965
+ const mine = (S.tasks || []).filter((t) => t.projectId === boardOpen);
3966
+ const col = (status) => mine.filter((t) => t.status === status);
3967
+ const todo = col('todo').sort((p, q) => p.createdAt - q.createdAt);
3968
+ const doing = col('doing');
3969
+ const done = col('done').sort((p, q) => q.doneAt - p.doneAt).slice(0, 10);
3970
+ const idle = S.agents.some((a) => a.projectId === boardOpen && !a.external && a.status !== 'offline');
3971
+ const card = (t, extra) => `<div class="b-card ${t.status}"><div class="b-text">${esc(t.text)}</div><div class="b-meta">${extra}</div></div>`;
3972
+ const nameOf = (id) => esc(agentById(id)?.name || '?');
3973
+ list.innerHTML = `
3974
+ <div class="r-sec">${tx('board.todo', { n: todo.length })}</div>
3975
+ ${todo.map((t, i) => card(t, `${i ? `<button class="ghost" data-b="top" data-id="${t.id}" title="${tx('board.top')}">⬆</button>` : ''}<button class="ghost danger" data-b="del" data-id="${t.id}" title="${tx('board.del')}">✕</button>`)).join('') || `<div class="b-none">${tx('board.none')}</div>`}
3976
+ ${todo.length && !idle ? `<div class="b-none">${tx('board.nobody')}</div>` : ''}
3977
+ <div class="r-sec">${tx('board.doing', { n: doing.length })}</div>
3978
+ ${doing.map((t) => card(t, `<span>🧑‍💻 ${nameOf(t.agentId)}</span><button class="ghost" data-b="open" data-agent="${t.agentId}">🖥</button>`)).join('') || `<div class="b-none">—</div>`}
3979
+ ${done.length ? `<div class="r-sec">${tx('board.done')}</div>${done.map((t) => card(t, `<span>✅ ${nameOf(t.agentId)} · ${hhmm(t.doneAt)}</span><button class="ghost" data-b="again" data-id="${t.id}" title="${tx('board.again')}">↺</button><button class="ghost danger" data-b="del" data-id="${t.id}">✕</button>`)).join('')}` : ''}`;
3980
+ }
3981
+
3982
+ // ---- end-of-day report: what every session did on one day, from the transcripts.
3983
+ const localDay = (d = new Date()) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
3984
+ const hhmm = (ts) => new Date(ts).toTimeString().slice(0, 5);
3985
+ const reportName = (r) => r.name || tx('report.terminal', { room: r.room || '?' });
3986
+ let reportData = null;
3987
+ function openReport(day = localDay()) {
3988
+ openModal(
3989
+ `<h3>${tx('report.title')}</h3>
3990
+ <div class="r-bar">
3991
+ <input type="date" id="r-day" value="${day}" max="${localDay()}">
3992
+ <span id="r-sum" class="muted"></span>
3993
+ <button class="ghost" id="r-copy">📋 ${tx('report.copy')}</button>
3994
+ </div>
3995
+ <div id="r-list" class="r-list"><div class="q-empty">${tx('report.loading')}</div></div>
3996
+ <div class="foot"><button class="ghost" data-close>${tx('queue.close')}</button></div>`,
3997
+ (m) => {
3998
+ m.querySelector('#r-day').addEventListener('change', (e) => e.target.value && loadReport(e.target.value));
3999
+ m.querySelector('#r-copy').addEventListener('click', async () => {
4000
+ if (!reportData) return;
4001
+ try {
4002
+ await navigator.clipboard.writeText(reportMarkdown(reportData));
4003
+ toast(tx('report.copied'), 'ok');
4004
+ } catch (err) {
4005
+ toast(err.message, 'err');
4006
+ }
4007
+ });
4008
+ }
4009
+ );
4010
+ loadReport(day);
4011
+ }
4012
+ async function loadReport(day) {
4013
+ reportData = null;
4014
+ const list = $('#r-list');
4015
+ if (!list) return;
4016
+ list.innerHTML = `<div class="q-empty">${tx('report.loading')}</div>`;
4017
+ try {
4018
+ const data = await api('GET', `/api/report?day=${day}`);
4019
+ if (!$('#r-list') || $('#r-day').value !== data.day) return;
4020
+ reportData = data;
4021
+ renderReport(data);
4022
+ } catch (err) {
4023
+ list.innerHTML = `<div class="q-empty">${esc(err.message)}</div>`;
4024
+ }
4025
+ }
4026
+ function renderReport(data) {
4027
+ const ss = data.sessions;
4028
+ const sum = (k) => ss.reduce((n, r) => n + r[k].length, 0);
4029
+ $('#r-sum').textContent = ss.length ? tx('report.sum', { s: ss.length, t: sum('tasks'), c: sum('commits'), p: new Set(ss.flatMap((r) => r.prs)).size }) + (data.usage ? ' · ' + fmtUsage(data.usage) : '') : '';
4030
+ $('#r-sum').title = tx('usage.title');
4031
+ if (!ss.length) {
4032
+ $('#r-list').innerHTML = `<div class="q-empty">${tx('report.empty')}</div>`;
4033
+ return;
4034
+ }
4035
+ const more = (arr, n, fmt) => arr.slice(0, n).map(fmt).join('') + (arr.length > n ? `<details><summary>${tx('report.more', { n: arr.length - n })}</summary>${arr.slice(n).map(fmt).join('')}</details>` : '');
4036
+ $('#r-list').innerHTML = ss
4037
+ .map((r) => {
4038
+ const a = r.agentId && agentById(r.agentId);
4039
+ return `<div class="q-item">
4040
+ <div class="q-head"><b>${esc(reportName(r))}</b><span class="muted">${esc(r.room)} · ${hhmm(r.first)}–${hhmm(r.end)}${r.usage && usageTokens(r.usage) ? ' · ' + fmtUsage(r.usage) : ''}</span>${a ? `<button class="ghost r-open" data-open="${a.id}">🖥</button>` : ''}</div>
4041
+ ${r.tasks.length ? `<div class="r-sec">${tx('report.tasks', { n: r.tasks.length })}</div><ul class="r-ul">${more(r.tasks, 3, (t) => `<li>${esc(t)}</li>`)}</ul>` : ''}
4042
+ ${r.commits.length ? `<div class="r-sec">${tx('report.commits', { n: r.commits.length })}</div><ul class="r-ul">${more(r.commits, 5, (c) => `<li>${esc(c)}</li>`)}</ul>` : ''}
4043
+ ${r.prs.length ? `<div class="r-sec">${tx('report.prs')}</div><ul class="r-ul">${r.prs.map((u) => `<li><a href="${esc(u)}" target="_blank" rel="noopener">${esc(u.replace('https://github.com/', ''))}</a></li>`).join('')}</ul>` : ''}
4044
+ ${r.files.length ? `<details><summary>${tx('report.files', { n: r.files.length })}</summary><ul class="r-ul">${r.files.map((f) => `<li><code>${esc(f)}</code></li>`).join('')}</ul></details>` : ''}
4045
+ ${r.last ? `<div class="r-sec">${tx('report.last')}</div><div class="r-last">${esc(r.last)}</div>` : ''}
4046
+ </div>`;
4047
+ })
4048
+ .join('');
4049
+ $('#r-list').querySelectorAll('[data-open]').forEach((b) =>
4050
+ b.addEventListener('click', () => {
4051
+ closeModal();
4052
+ openPanel(b.dataset.open);
4053
+ })
4054
+ );
4055
+ }
4056
+ function reportMarkdown(data) {
4057
+ const out = [`# ${tx('report.title')} — ${data.day}`, ''];
4058
+ if (data.usage && usageTokens(data.usage)) out.push(`${fmtUsage(data.usage)} (${tx('usage.title')})`, '');
4059
+ for (const r of data.sessions) {
4060
+ out.push(`## ${reportName(r)} (${r.room}, ${hhmm(r.first)}–${hhmm(r.end)}${r.usage && usageTokens(r.usage) ? ', ' + fmtUsage(r.usage) : ''})`);
4061
+ if (r.tasks.length) out.push(`**${tx('report.tasks', { n: r.tasks.length })}**`, ...r.tasks.map((t) => `- ${t}`));
4062
+ if (r.commits.length) out.push(`**${tx('report.commits', { n: r.commits.length })}**`, ...r.commits.map((c) => `- ${c}`));
4063
+ if (r.prs.length) out.push(`**${tx('report.prs')}**`, ...r.prs.map((u) => `- ${u}`));
4064
+ if (r.files.length) out.push(`**${tx('report.files', { n: r.files.length })}**`, ...r.files.map((f) => `- \`${f}\``));
4065
+ if (r.last) out.push(`**${tx('report.last')}**`, '', r.last.split('\n').map((l) => `> ${l}`).join('\n'));
4066
+ out.push('');
4067
+ }
4068
+ return out.join('\n');
4069
+ }
4070
+
4071
+ // ---- approval queue: every agent waiting for a yes/no, answered in one place.
4072
+ let queueOpen = false;
4073
+ $('#stats').addEventListener('click', (e) => e.target.closest('[data-queue]') && openQueue());
4074
+ function openQueue() {
4075
+ openModal(
4076
+ `<h3>${tx('queue.title')}</h3>
4077
+ <div class="sub">${tx('queue.sub')}</div>
4078
+ <div id="q-list" class="q-list"></div>
4079
+ <div class="foot"><button class="ghost" data-close>${tx('queue.close')}</button></div>`,
4080
+ (m) => {
4081
+ m.querySelector('#q-list').addEventListener('click', async (e) => {
4082
+ const b = e.target.closest('[data-q]');
4083
+ if (!b) return;
4084
+ const a = agentById(b.dataset.id);
4085
+ if (!a) return;
4086
+ if (b.dataset.q === 'open') {
4087
+ closeModal();
4088
+ return openPanel(a.id);
4089
+ }
4090
+ b.closest('.q-item').classList.add('busy');
4091
+ try {
4092
+ await api('POST', `/api/agents/${a.id}/answer`, { allow: b.dataset.q === 'allow' });
4093
+ toast(tx(b.dataset.q === 'allow' ? 'queue.allowed' : 'queue.denied', { name: a.name }), 'ok');
4094
+ } catch (err) {
4095
+ toast(err.message, 'err');
4096
+ renderQueue();
4097
+ }
4098
+ });
4099
+ }
4100
+ );
4101
+ queueOpen = true;
4102
+ renderQueue();
4103
+ }
4104
+ function renderQueue() {
4105
+ const list = $('#q-list');
4106
+ if (!list) return;
4107
+ const waiting = S.agents.filter((a) => a.status === 'waiting').sort((p, q) => (p.ask?.at || 0) - (q.ask?.at || 0));
4108
+ if (!waiting.length) {
4109
+ list.innerHTML = `<div class="q-empty">${tx('queue.empty')}</div>`;
4110
+ return;
4111
+ }
4112
+ list.innerHTML = waiting
4113
+ .map((a) => {
4114
+ const ask = a.ask || {};
4115
+ const room = projectById(a.projectId)?.name || '';
4116
+ const since = ask.at ? tx('queue.since', { n: Math.max(1, Math.round((Date.now() - ask.at) / 60000)) }) : '';
4117
+ // Only real permission requests can be answered here; other prompts
4118
+ // (e.g. the folder trust question) need the terminal.
4119
+ const can = !a.external && !!a.ask;
4120
+ return `<div class="q-item">
4121
+ <div class="q-head"><b>${esc(a.name)}</b><span class="muted">${esc(room)}${since ? ' · ' + since : ''}</span>${ask.tool ? `<span class="q-tool">${esc(ask.tool)}</span>` : ''}</div>
4122
+ ${ask.message || a.note ? `<div class="q-msg">${esc(ask.message || msgText(a.note))}</div>` : ''}
4123
+ ${ask.detail ? `<pre class="q-detail">${esc(ask.detail)}</pre>` : ''}
4124
+ ${can ? '' : `<div class="q-msg muted">${tx(a.external ? 'queue.external' : 'queue.terminal')}</div>`}
4125
+ <div class="q-actions">
4126
+ <button class="ghost" data-q="open" data-id="${a.id}">🖥 ${tx(a.external ? 'menu.watch' : 'menu.terminal')}</button>
4127
+ ${can ? `<button class="danger" data-q="deny" data-id="${a.id}">✕ ${tx('queue.deny')}</button><button class="primary" data-q="allow" data-id="${a.id}">✓ ${tx('queue.allow')}</button>` : ''}
4128
+ </div>
4129
+ </div>`;
4130
+ })
4131
+ .join('');
4132
+ }
4133
+
4134
+ // ---- "What should I do?" card: a bored agent walks up to the screen.
4135
+ const askDismissed = new Map(); // agentId -> ask number dismissed with "later"
4136
+ let askCardId = null;
4137
+ let askCardKey = '';
4138
+ function currentAsker() {
4139
+ return S.agents.find((a) => a.game?.asking && askDismissed.get(a.id) !== a.game.asking && !(panelId === a.id));
4140
+ }
4141
+ function renderAskCard() {
4142
+ const card = $('#ask-card');
4143
+ const a = currentAsker();
4144
+ if (!a) {
4145
+ card.hidden = true;
4146
+ askCardId = null;
4147
+ askCardKey = '';
4148
+ return;
4149
+ }
4150
+ const key = a.id + '|' + a.game.asking;
4151
+ if (key === askCardKey) return;
4152
+ const fresh = askCardId !== a.id;
4153
+ askCardId = a.id;
4154
+ askCardKey = key;
4155
+ const others = S.agents.filter((x) => x.game?.asking && x.id !== a.id).length;
4156
+ const p = projectById(a.projectId);
4157
+ card.innerHTML = `
4158
+ <canvas class="ask-portrait"></canvas>
4159
+ <div class="ask-body">
4160
+ <div class="ask-who"><b>${esc(a.name)}</b> · ${esc(roleLabel(a.role))} · Lv ${a.game.level} · ${moraleFace(a.game.morale)} ${tx('askcard.morale', { n: a.game.morale })} <span class="muted">· ${esc(p?.name || '')}</span></div>
4161
+ <div class="ask-say">${esc(ASK_LINES[Math.min(a.game.asking, 3) - 1](a))}</div>
4162
+ <div class="ask-steps">${[1, 2, 3].map((i) => `<i class="${i <= a.game.asking ? 'on' : ''}"></i>`).join('')}<span>${tx('askcard.steps', { n: a.game.asking })}${others ? tx('askcard.queue', { n: others }) : ''}</span></div>
4163
+ <div class="ask-task">
4164
+ <input id="ask-input" placeholder="${a.external ? tx('askcard.phExternal') : tx('askcard.ph')}">
4165
+ </div>
4166
+ <div class="ask-actions">
4167
+ <button class="primary" data-ask="task">${tx('askcard.task')}</button>
4168
+ <button data-ask="oneonone">${tx('askcard.oneOnOne')}</button>
4169
+ <button data-ask="praise">${tx('askcard.praise')}</button>
4170
+ <button class="ghost" data-ask="later">${tx('askcard.later')}</button>
4171
+ </div>
4172
+ </div>`;
4173
+ card.hidden = false;
4174
+ if (fresh) {
4175
+ card.classList.remove('approach');
4176
+ void card.offsetWidth;
4177
+ card.classList.add('approach');
4178
+ }
4179
+ $('#ask-input').addEventListener('keydown', (e) => e.key === 'Enter' && askAction('task'));
4180
+ }
4181
+ async function giveTask(a, text) {
4182
+ if (a.external) {
4183
+ const r = await api('POST', `/api/agents/${a.id}/takeover`, { prompt: text });
4184
+ if (r.error) throw new Error(r.error);
4185
+ toast(tx('task.movedAndStarted', { name: a.name }), 'ok');
4186
+ } else {
4187
+ await api('POST', `/api/agents/${a.id}/message`, { text });
4188
+ toast(tx('task.started', { name: a.name }), 'ok');
4189
+ }
4190
+ }
4191
+ async function askAction(kind) {
4192
+ const a = agentById(askCardId);
4193
+ if (!a) return renderAskCard();
4194
+ try {
4195
+ if (kind === 'task') {
4196
+ const text = $('#ask-input').value.trim();
4197
+ if (!text) return $('#ask-input').focus();
4198
+ await giveTask(a, text);
4199
+ askDismissed.set(a.id, a.game.asking);
4200
+ } else if (kind === 'oneonone') {
4201
+ askDismissed.set(a.id, a.game.asking);
4202
+ openOneOnOne(a.id);
4203
+ } else if (kind === 'praise') {
4204
+ askDismissed.set(a.id, a.game.asking);
4205
+ await api('POST', `/api/agents/${a.id}/praise`);
4206
+ await api('POST', `/api/agents/${a.id}/ask-answer`);
4207
+ } else if (kind === 'later') {
4208
+ askDismissed.set(a.id, a.game.asking);
4209
+ await api('POST', `/api/agents/${a.id}/ask-answer`);
4210
+ }
4211
+ } catch (err) {
4212
+ toast(err.message, 'err');
4213
+ }
4214
+ askCardKey = '';
4215
+ renderAskCard();
4216
+ }
4217
+ $('#ask-card').addEventListener('click', (e) => {
4218
+ const b = e.target.closest('[data-ask]');
4219
+ if (b) askAction(b.dataset.ask);
4220
+ });
4221
+
4222
+ // ---- 1:1 meeting in the boss office
4223
+ let oneOnOneId = null;
4224
+ function openOneOnOne(id) {
4225
+ const a = agentById(id);
4226
+ if (!a) return;
4227
+ oneOnOneId = id;
4228
+ api('POST', `/api/agents/${id}/one-on-one`, { on: true }).catch(() => {});
4229
+ const gm = a.game || { level: 1, xp: 0, levelXp: 0, nextXp: 40, morale: 80, turns: 0 };
4230
+ const pct = Math.round(((gm.xp - gm.levelXp) / Math.max(1, gm.nextXp - gm.levelXp)) * 100);
4231
+ const nextRole = S.roles[S.roles.indexOf(a.role) - 1];
4232
+ openModal(
4233
+ `<div class="oo-head">
4234
+ <canvas class="oo-portrait"></canvas>
4235
+ <div>
4236
+ <h3>${tx('oo.title', { name: esc(a.name) })}</h3>
4237
+ <div class="sub">${esc(roleLabel(a.role))} · ${esc(projectById(a.projectId)?.name || '')}${a.external ? tx('oo.ownTerminal') : ''}</div>
4238
+ <div class="stat"><span>${tx('oo.level', { n: gm.level })}</span><div class="bar"><i style="width:${pct}%"></i></div><span class="muted">${gm.xp} XP</span></div>
4239
+ <div class="stat"><span>${tx('oo.morale')} ${moraleFace(gm.morale)}</span><div class="bar morale"><i style="width:${gm.morale}%"></i></div><span class="muted">${gm.morale}</span></div>
4240
+ <div class="sub">${tx('oo.done', { n: gm.turns })}${a.task ? tx('oo.last', { task: esc(a.task.slice(0, 80)) }) : ''}</div>
4241
+ </div>
4242
+ </div>
4243
+ <label>${tx('oo.newTask')}</label>
4244
+ <textarea id="oo-task" placeholder="${tx('oo.taskPh')}${a.external ? tx('oo.taskPhExternal') : ''}" autofocus></textarea>
4245
+ <div class="err"></div>
4246
+ <div class="foot">
4247
+ <button class="ghost left" data-oo="end">${tx('oo.end')}</button>
4248
+ <button data-oo="praise">${tx('askcard.praise')}</button>
4249
+ ${nextRole ? `<button data-oo="promote" class="${gm.promotable ? 'ready' : ''}" title="${gm.promotable ? tx('oo.promoteReady') : tx('oo.promoteEarly')}">${tx('oo.promote', { role: esc(roleLabel(nextRole)) })}${gm.promotable ? ' ✨' : ''}</button>` : ''}
4250
+ <button class="primary" data-oo="task">${tx('oo.give')}</button>
4251
+ </div>`,
4252
+ (m) => {
4253
+ const cv = $('.oo-portrait', m);
4254
+ const loop = (t) => {
4255
+ if (!cv.isConnected) return;
4256
+ const live = agentById(id);
4257
+ if (live) drawPortrait(cv, live, t);
4258
+ requestAnimationFrame(loop);
4259
+ };
4260
+ requestAnimationFrame(loop);
4261
+ m.addEventListener('click', async (e) => {
4262
+ const b = e.target.closest('[data-oo]');
4263
+ if (!b) return;
4264
+ const live = agentById(id) || a;
4265
+ try {
4266
+ if (b.dataset.oo === 'praise') {
4267
+ await api('POST', `/api/agents/${id}/praise`);
4268
+ toast(tx('oo.thanks', { name: live.name }), 'ok');
4269
+ } else if (b.dataset.oo === 'promote') {
4270
+ await api('PATCH', `/api/agents/${id}`, { role: nextRole });
4271
+ toast(tx('oo.promoted', { name: live.name, role: roleLabel(nextRole) }), 'ok');
4272
+ const sp = sprites.get(id);
4273
+ if (sp) burst(sp.x, sp.y - 40);
4274
+ closeModal();
4275
+ } else if (b.dataset.oo === 'task') {
4276
+ const text = $('#oo-task', m).value.trim();
4277
+ if (!text) return formError(m, tx('oo.needTask'));
4278
+ await giveTask(live, text);
4279
+ closeModal();
4280
+ } else if (b.dataset.oo === 'end') {
4281
+ closeModal();
4282
+ }
4283
+ } catch (err) {
4284
+ formError(m, err.message);
4285
+ }
4286
+ });
4287
+ }
4288
+ );
4289
+ }
4290
+ function endOneOnOne() {
4291
+ if (!oneOnOneId) return;
4292
+ const id = oneOnOneId;
4293
+ oneOnOneId = null;
4294
+ if (agentById(id)) api('POST', `/api/agents/${id}/one-on-one`, { on: false }).catch(() => {});
4295
+ }
4296
+
4297
+ // ---- trophies: leaderboard and achievements
4298
+ function openTrophies() {
4299
+ const g = S.game || { counters: {}, unlocked: [], achievements: [] };
4300
+ const board = S.agents.filter((a) => a.game).sort((p, q) => q.game.xp - p.game.xp).slice(0, 10);
4301
+ openModal(
4302
+ `<h3>${tx('trophy.title')}</h3>
4303
+ <div class="score-row">
4304
+ <div><b>${g.today}</b><span>${tx('trophy.today')}</span></div>
4305
+ <div><b>${g.counters.turns || 0}</b><span>${tx('trophy.total')}</span></div>
4306
+ <div><b>${g.unlocked.length}/${g.achievements.length}</b><span>${tx('trophy.badges')}</span></div>
4307
+ </div>
4308
+ <label>${tx('trophy.board')}</label>
4309
+ <div class="board">${board.length ? board.map((a, i) => `
4310
+ <button class="board-row" data-agent="${a.id}">
4311
+ <span class="rank">${i === 0 && a.game.xp > 0 ? '🏆' : i + 1}</span>
4312
+ <span class="nm">${esc(a.name)}${a.external ? ' 🖥' : ''}</span>
4313
+ <span class="muted">${esc(roleLabel(a.role))}</span>
4314
+ <span>Lv ${a.game.level}</span>
4315
+ <span class="muted">${a.game.xp} XP</span>
4316
+ <span>${moraleFace(a.game.morale)}</span>
4317
+ ${a.game.promotable ? `<span class="tag">${tx('trophy.promote')}</span>` : '<span></span>'}
4318
+ </button>`).join('') : `<div class="hint">${tx('trophy.nobody')}</div>`}</div>
4319
+ <label>${tx('trophy.badgesTitle')}</label>
4320
+ <div class="badges">${g.achievements.map((b) => `<div class="badge ${g.unlocked.includes(b.id) ? 'on' : ''}" title="${esc(tx('ach.' + b.id)[1])}"><span>${b.icon}</span><b>${esc(tx('ach.' + b.id)[0])}</b><small>${esc(tx('ach.' + b.id)[1])}</small></div>`).join('')}</div>
4321
+ <div class="foot"><button data-close>${tx('common.close')}</button></div>`,
4322
+ (m) => {
4323
+ m.addEventListener('click', (e) => {
4324
+ const r = e.target.closest('[data-agent]');
4325
+ if (r) {
4326
+ closeModal();
4327
+ openPanel(r.dataset.agent);
4328
+ }
4329
+ });
4330
+ }
4331
+ );
4332
+ }
4333
+
4334
+ // Permission choices each tool understands (Claude Code has the full set).
4335
+ const TOOL_PERMS = { claude: ['default', 'acceptEdits', 'plan', 'bypassPermissions'], cursor: ['default', 'plan', 'bypassPermissions'] };
4336
+ function toolFields(tool, a = {}) {
4337
+ const perms = TOOL_PERMS[tool] || ['default'];
4338
+ const model = tool === 'claude' ? modelField(a.model) : `<input id="f-model" placeholder="${tx('hire.modelPh')}" value="${esc(a.model || '')}">`;
4339
+ return `
4340
+ <div class="row">
4341
+ <div><label>${tx('form.model')}</label>${model}</div>
4342
+ <div ${perms.length > 1 ? '' : 'hidden'}><label>${tx('form.perm')}</label><select id="f-perm">
4343
+ ${perms.map((v) => `<option value="${v}" ${v === (a.permissionMode || 'default') ? 'selected' : ''}>${tx('perm.' + v)}</option>`).join('')}
4344
+ </select></div>
4345
+ </div>
4346
+ ${tool !== 'claude' ? `<div class="hint">${tx('panel.estimated')}</div>` : ''}`;
4347
+ }
4348
+ function agentFormFields(a = {}) {
4349
+ return `
4350
+ <label>${tx('form.look')}</label>
4351
+ <select id="f-look">
4352
+ ${['auto', 'f', 'm'].map((v) => `<option value="${v}" ${v === (a.look || 'auto') ? 'selected' : ''}>${tx('look.' + v)}</option>`).join('')}
4353
+ </select>
4354
+ <div id="f-toolfields">${toolFields(a.tool || 'claude', a)}</div>`;
4355
+ }
4356
+
4357
+ let toolsCache = null;
4358
+ async function loadTools() {
4359
+ if (!toolsCache) toolsCache = await api('GET', '/api/tools').catch(() => []);
4360
+ return toolsCache;
4361
+ }
4362
+
4363
+ function openHireModal(projectId, presetRole, lockProject = false) {
4364
+ if (!S.projects.length) return openProjectModal();
4365
+ const pid = projectId || S.projects[0].id;
4366
+ const used = new Set(S.agents.map((a) => a.name));
4367
+ const name = NAMES.find((n) => !used.has(n)) || `Agent ${S.agents.length + 1}`;
4368
+ const hasLead = (id) => S.agents.some((a) => a.projectId === id && a.role === 'lead');
4369
+ openModal(
4370
+ `<h3>${tx('hire.title')}</h3>
4371
+ <div class="sub">${lockProject ? tx('hire.freeDesk', { room: esc(projectById(pid)?.name), path: esc(projectById(pid)?.path) }) : tx('hire.sub')}</div>
4372
+ <div class="row">
4373
+ <div><label>${tx('hire.room')}</label><select id="f-project" ${lockProject ? 'disabled' : ''}>${S.projects.map((p) => `<option value="${p.id}" ${p.id === pid ? 'selected' : ''}>${esc(p.name)}</option>`).join('')}</select></div>
4374
+ <div><label>${tx('hire.name')}</label><input id="f-name" value="${esc(name)}"></div>
4375
+ </div>
4376
+ <div class="row">
4377
+ <div><label>${tx('hire.role')}</label>
4378
+ <select id="f-role">${S.roles.map((r) => `<option value="${r}">${ROLE_BADGE[r].s} ${esc(roleLabel(r))}</option>`).join('')}</select></div>
4379
+ <div><label>${tx('hire.tool')}</label><select id="f-tool"><option value="claude">✳ Claude Code</option></select></div>
4380
+ </div>
4381
+ ${agentFormFields()}
4382
+ <label>${tx('hire.task')}</label>
4383
+ <textarea id="f-task" placeholder="${tx('hire.taskPh')}" autofocus></textarea>
4384
+ <details><summary>${tx('hire.advanced')}</summary>
4385
+ <label>${tx('hire.command')}</label><input id="f-cmd" value="claude">
4386
+ <div class="hint">${tx('hire.commandHint')}</div>
4387
+ </details>
4388
+ <label class="check" title="${tx('wt.hint')}"><input type="checkbox" id="f-worktree" checked> ${tx('wt.option')}</label>
4389
+ <label class="check"><input type="checkbox" id="f-start" checked> ${tx('hire.startNow')}</label>
4390
+ <div class="err"></div>
4391
+ <div class="foot"><button data-close>${tx('common.cancel')}</button><button class="primary" id="f-ok">${tx('hire.ok')}</button></div>`,
4392
+ async (m) => {
4393
+ const roleEl = $('#f-role', m);
4394
+ const projEl = $('#f-project', m);
4395
+ const toolEl = $('#f-tool', m);
4396
+ const syncRole = () => (roleEl.value = hasLead(projEl.value) ? 'mid' : 'lead');
4397
+ if (presetRole) roleEl.value = presetRole;
4398
+ else syncRole();
4399
+ // Tools: Claude Code in the main office, other tools in the Partner office.
4400
+ const tools = await loadTools();
4401
+ if (!toolEl.isConnected) return;
4402
+ toolEl.innerHTML = tools.map((t) => `<option value="${t.id}">${t.icon} ${esc(t.label)}${t.installed ? '' : tx('hire.notInstalled')}</option>`).join('');
4403
+ const applyTool = () => {
4404
+ const t = tools.find((x) => x.id === toolEl.value) || { id: 'claude', cmd: 'claude' };
4405
+ $('#f-toolfields', m).innerHTML = toolFields(t.id);
4406
+ if (t.id !== 'custom') $('#f-cmd', m).value = t.cmd;
4407
+ if (t.id === 'custom') $('#f-cmd', m).closest('details').open = true;
4408
+ };
4409
+ const pickDefault = () => {
4410
+ const bTool = S.buildings.find((b) => b.id === projectById(projEl.value)?.building)?.tool || 'claude';
4411
+ const pref = tools.find((t) => t.id === bTool) || tools.find((t) => t.id === 'claude');
4412
+ if (pref) toolEl.value = pref.id;
4413
+ applyTool();
4414
+ };
4415
+ toolEl.onchange = applyTool;
4416
+ projEl.onchange = () => {
4417
+ syncRole();
4418
+ pickDefault();
4419
+ };
4420
+ pickDefault();
4421
+ $('#f-ok', m).onclick = async () => {
4422
+ try {
4423
+ const r = await api('POST', '/api/agents', {
4424
+ projectId: projEl.value,
4425
+ name: $('#f-name', m).value.trim(),
4426
+ role: roleEl.value,
4427
+ model: readModel(m),
4428
+ look: $('#f-look', m).value,
4429
+ permissionMode: $('#f-perm', m).value,
4430
+ tool: toolEl.value,
4431
+ command: $('#f-cmd', m).value.trim(),
4432
+ initialPrompt: $('#f-task', m).value.trim(),
4433
+ worktree: $('#f-worktree', m).checked,
4434
+ start: $('#f-start', m).checked,
4435
+ });
4436
+ closeModal();
4437
+ if (r.error) toast(tx('hire.failed', { name: r.agent.name, error: r.error }), 'err');
4438
+ else toast(tx('hire.done', { name: r.agent.name }), 'ok');
4439
+ if (agentById(r.agent.id)) openPanel(r.agent.id);
4440
+ else openOnArrival = r.agent.id;
4441
+ } catch (err) {
4442
+ formError(m, err.message);
4443
+ }
4444
+ };
4445
+ }
4446
+ );
4447
+ }
4448
+
4449
+ function openEditModal(id) {
4450
+ const a = agentById(id);
4451
+ openModal(
4452
+ `<h3>${tx('edit.title', { name: esc(a.name) })}</h3>
4453
+ <label>${tx('hire.name')}</label><input id="f-name" value="${esc(a.name)}">
4454
+ <label>${tx('hire.room')}</label><select id="f-project">${S.projects.map((p) => `<option value="${p.id}" ${p.id === a.projectId ? 'selected' : ''}>${esc(p.name)}</option>`).join('')}</select>
4455
+ ${agentFormFields(a)}
4456
+ <label class="check" title="${tx('wt.hint')}"><input type="checkbox" id="f-worktree" ${a.worktree ? 'checked' : ''}> ${tx('wt.option')}</label>
4457
+ <div class="hint">${tx('edit.roomHint')}</div>
4458
+ <div class="err"></div>
4459
+ <div class="foot"><button data-close>${tx('common.cancel')}</button><button class="primary" id="f-ok">${tx('common.save')}</button></div>`,
4460
+ (m) => {
4461
+ $('#f-ok', m).onclick = async () => {
4462
+ try {
4463
+ const projectId = $('#f-project', m).value;
4464
+ await api('PATCH', `/api/agents/${id}`, {
4465
+ name: $('#f-name', m).value.trim(),
4466
+ projectId,
4467
+ model: readModel(m),
4468
+ look: $('#f-look', m).value,
4469
+ permissionMode: $('#f-perm', m).value,
4470
+ worktree: $('#f-worktree', m).checked,
4471
+ });
4472
+ closeModal();
4473
+ } catch (err) {
4474
+ formError(m, err.message);
4475
+ }
4476
+ };
4477
+ }
4478
+ );
4479
+ }
4480
+
4481
+ function openRoomModal(projectId) {
4482
+ const p = projectById(projectId);
4483
+ if (p.auto) return openAutoRoomModal(p);
4484
+ const ags = S.agents.filter((a) => a.projectId === projectId);
4485
+ const online = ags.filter((a) => a.status !== 'offline');
4486
+ openModal(
4487
+ `<h3>${tx('room.title', { name: esc(p.name) })}</h3>
4488
+ <div class="sub">${esc(p.path)}</div>
4489
+ <label>${tx('room.announceLabel', { online: online.length, total: ags.length })}</label>
4490
+ <textarea id="f-text" placeholder="${tx('room.announcePh')}" autofocus></textarea>
4491
+ <div class="hint">${tx('room.announceHint')}</div>
4492
+ <div class="err"></div>
4493
+ <div class="foot">
4494
+ <button class="danger left" id="f-del">${tx('room.close')}</button>
4495
+ ${ags.length - online.length ? `<button id="f-wake">${tx('room.wake')}</button>` : ''}
4496
+ <button id="f-hire">${tx('room.hire')}</button>
4497
+ <button class="primary" id="f-ok">${tx('room.announce')}</button>
4498
+ </div>`,
4499
+ (m) => {
4500
+ $('#f-ok', m).onclick = async () => {
4501
+ const text = $('#f-text', m).value.trim();
4502
+ if (!text) return formError(m, tx('room.needText'));
4503
+ try {
4504
+ const r = await api('POST', `/api/projects/${projectId}/announce`, { text });
4505
+ closeModal();
4506
+ toast((r.sent ? tx('room.sent', { n: r.sent }) : tx('room.noneOnline')) + (r.skipped ? tx('room.skipped', { n: r.skipped }) : ''), r.sent ? 'ok' : 'err');
4507
+ } catch (err) {
4508
+ formError(m, err.message);
4509
+ }
4510
+ };
4511
+ $('#f-hire', m).onclick = () => openHireModal(projectId);
4512
+ const wake = $('#f-wake', m);
4513
+ if (wake)
4514
+ wake.onclick = async () => {
4515
+ for (const a of ags.filter((x) => x.status === 'offline')) {
4516
+ await api('POST', `/api/agents/${a.id}/start`).catch((err) => toast(`${a.name}: ${err.message}`, 'err'));
4517
+ }
4518
+ closeModal();
4519
+ };
4520
+ $('#f-del', m).onclick = async () => {
4521
+ if (!confirm(tx('room.confirmClose', { name: p.name, n: ags.length }))) return;
4522
+ await api('DELETE', `/api/projects/${projectId}`).catch((err) => toast(err.message, 'err'));
4523
+ closeModal();
4524
+ };
4525
+ }
4526
+ );
4527
+ }
4528
+
4529
+ function openAutoRoomModal(p) {
4530
+ const ags = S.agents.filter((a) => a.projectId === p.id);
4531
+ openModal(
4532
+ `<h3>${tx('temp.title', { name: esc(p.name) })}</h3>
4533
+ <div class="sub">${esc(p.path)}</div>
4534
+ <p class="hint">${tx('temp.text', { n: ags.length })}</p>
4535
+ <div class="err"></div>
4536
+ <div class="foot"><button data-close>${tx('common.close')}</button><button id="f-hire">${tx('room.hire')}</button><button class="primary" id="f-save">${tx('temp.save')}</button></div>`,
4537
+ (m) => {
4538
+ $('#f-save', m).onclick = async () => {
4539
+ try {
4540
+ await api('POST', `/api/projects/${p.id}/save`);
4541
+ closeModal();
4542
+ toast(tx('temp.saved', { name: p.name }), 'ok');
4543
+ } catch (err) {
4544
+ formError(m, err.message);
4545
+ }
4546
+ };
4547
+ $('#f-hire', m).onclick = () => openHireModal(p.id, null, true);
4548
+ }
4549
+ );
4550
+ }
4551
+
4552
+ function openAnnounceModal() {
4553
+ const online = S.agents.filter((a) => a.status !== 'offline').length;
4554
+ openModal(
4555
+ `<h3>${tx('all.title')}</h3>
4556
+ <div class="sub">${tx('all.sub', { n: online })}</div>
4557
+ <textarea id="f-text" placeholder="${tx('all.ph')}" autofocus></textarea>
4558
+ <div class="err"></div>
4559
+ <div class="foot"><button data-close>${tx('common.cancel')}</button><button class="primary" id="f-ok">${tx('room.announce')}</button></div>`,
4560
+ (m) => {
4561
+ $('#f-ok', m).onclick = async () => {
4562
+ const text = $('#f-text', m).value.trim();
4563
+ if (!text) return formError(m, tx('room.needText'));
4564
+ try {
4565
+ const r = await api('POST', '/api/announce', { text });
4566
+ closeModal();
4567
+ toast((r.sent ? tx('room.sent', { n: r.sent }) : tx('all.noneOnline')) + (r.skipped ? tx('room.skipped', { n: r.skipped }) : ''), r.sent ? 'ok' : 'err');
4568
+ } catch (err) {
4569
+ formError(m, err.message);
4570
+ }
4571
+ };
4572
+ }
4573
+ );
4574
+ }
4575
+
4576
+ function openVisitModal(fromId) {
4577
+ const a = agentById(fromId);
4578
+ const others = S.agents.filter((x) => x.id !== fromId);
4579
+ if (!others.length) return toast(tx('visit.none'), 'err');
4580
+ const groups = S.projects
4581
+ .map((p) => {
4582
+ const list = others.filter((x) => x.projectId === p.id);
4583
+ if (!list.length) return '';
4584
+ return `<optgroup label="${esc(p.name)}">${list.map((x) => `<option value="${x.id}">${esc(x.name)} · ${esc(roleLabel(x.role))} · ${statusLabel(x.status)}</option>`).join('')}</optgroup>`;
4585
+ })
4586
+ .join('');
4587
+ openModal(
4588
+ `<h3>${tx('visit.title', { name: esc(a.name) })}</h3>
4589
+ <div class="sub">${tx('visit.sub', { name: esc(a.name) })}</div>
4590
+ <label>${tx('visit.who')}</label>
4591
+ <select id="f-target">${groups}</select>
4592
+ <label>${tx('visit.topic')}</label>
4593
+ <textarea id="f-text" placeholder="${tx('visit.topicPh')}" autofocus></textarea>
4594
+ <label class="check"><input type="checkbox" id="f-notify" checked> ${tx('visit.notify')}</label>
4595
+ <div class="err"></div>
4596
+ <div class="foot"><button data-close>${tx('common.cancel')}</button><button class="primary" id="f-ok">${tx('common.send')}</button></div>`,
4597
+ (m) => {
4598
+ $('#f-ok', m).onclick = async () => {
4599
+ try {
4600
+ await api('POST', `/api/agents/${fromId}/visit`, {
4601
+ targetId: $('#f-target', m).value,
4602
+ text: $('#f-text', m).value.trim(),
4603
+ notifyTarget: $('#f-notify', m).checked,
4604
+ });
4605
+ closeModal();
4606
+ toast(tx('visit.sent', { name: a.name }), 'ok');
4607
+ } catch (err) {
4608
+ formError(m, err.message);
4609
+ }
4610
+ };
4611
+ }
4612
+ );
4613
+ }
4614
+
4615
+ // ------------------------------------------------------------------ toasts & notifications
4616
+
4617
+ function toast(msg, kind = 'info', agentId) {
4618
+ const el = document.createElement('div');
4619
+ el.className = `toast ${kind}`;
4620
+ el.textContent = msg;
4621
+ el.onclick = () => {
4622
+ if (agentId && agentById(agentId)) openPanel(agentId);
4623
+ el.remove();
4624
+ };
4625
+ $('#toasts').appendChild(el);
4626
+ setTimeout(() => el.remove(), kind === 'warn' ? 9000 : 4500);
4627
+ }
4628
+
4629
+ function notify(msg) {
4630
+ if (!('Notification' in window) || Notification.permission !== 'granted' || !document.hidden) return;
4631
+ try {
4632
+ new Notification('Agent Hall', { body: msg, icon: 'logo.svg' });
4633
+ } catch {
4634
+ /* unsupported */
4635
+ }
4636
+ }
4637
+ document.addEventListener(
4638
+ 'click',
4639
+ () => {
4640
+ if ('Notification' in window && Notification.permission === 'default') Notification.requestPermission();
4641
+ },
4642
+ { once: true }
4643
+ );
4644
+
4645
+ // ------------------------------------------------------------------ wiring
4646
+
4647
+ // Static page text and the language switch.
4648
+ function applyStaticText() {
4649
+ document.documentElement.lang = LANG;
4650
+ for (const el of document.querySelectorAll('[data-i18n]')) el.textContent = tx(el.dataset.i18n);
4651
+ for (const el of document.querySelectorAll('[data-i18n-title]')) el.title = tx(el.dataset.i18nTitle);
4652
+ for (const el of document.querySelectorAll('[data-i18n-ph]')) el.placeholder = tx(el.dataset.i18nPh);
4653
+ $('#btn-lang').textContent = LANG === 'tr' ? 'EN' : 'TR';
4654
+ }
4655
+ $('#btn-lang').onclick = () => {
4656
+ LANG = LANG === 'tr' ? 'en' : 'tr';
4657
+ try {
4658
+ localStorage.setItem('ao-lang', LANG);
4659
+ } catch {
4660
+ /* storage unavailable */
4661
+ }
4662
+ reloadPage();
4663
+ };
4664
+ applyStaticText();
4665
+
4666
+ $('#btn-add-project').onclick = () => openProjectModal();
4667
+ $('#btn-add-building').onclick = () => openBuildingModal();
4668
+ loadTools();
4669
+ $('#btn-empty-add').onclick = openProjectModal;
4670
+ $('#btn-hire').onclick = () => openHireModal();
4671
+ $('#btn-announce-all').onclick = () => openAnnounceModal();
4672
+ $('#btn-fit').onclick = fitCamera;
4673
+ $('#btn-trophy').onclick = openTrophies;
4674
+ $('#btn-report').onclick = () => openReport();
4675
+ $('#btn-workday').onclick = () => openWorkday();
4676
+ function openWorkday() {
4677
+ const w = S.workday || { autoHome: true, idleMin: 45, endHour: null, autoWake: true };
4678
+ const hours = [null, 16, 17, 18, 19, 20, 21, 22, 23];
4679
+ openModal(
4680
+ `<h3>⏰ ${tx('wd.title')}</h3>
4681
+ <div class="sub">${tx('wd.sub')}</div>
4682
+ <label class="check"><input type="checkbox" id="wd-home" ${w.autoHome ? 'checked' : ''}> ${tx('wd.autoHome')}</label>
4683
+ <div class="row">
4684
+ <div><label>${tx('wd.idleMin')}</label><input type="number" id="wd-min" min="5" max="480" step="5" value="${w.idleMin}"></div>
4685
+ <div><label>${tx('wd.endHour')}</label><select id="wd-end">${hours.map((h) => `<option value="${h ?? ''}" ${h === w.endHour ? 'selected' : ''}>${h === null ? tx('wd.noEnd') : `${String(h).padStart(2, '0')}:00`}</option>`).join('')}</select></div>
4686
+ </div>
4687
+ <div class="sub">${tx('wd.endHint')}</div>
4688
+ <label class="check"><input type="checkbox" id="wd-wake" ${w.autoWake ? 'checked' : ''}> ${tx('wd.autoWake')}</label>
4689
+ <label class="check"><input type="checkbox" id="wd-night" ${dayNightOn ? 'checked' : ''}> ${tx('wd.dayNight')}</label>
4690
+ <div class="err"></div>
4691
+ <div class="foot"><button class="ghost" data-close>${tx('queue.close')}</button><button class="primary" id="wd-save">${tx('wd.save')}</button></div>`,
4692
+ (m) => {
4693
+ m.querySelector('#wd-save').addEventListener('click', async () => {
4694
+ dayNightOn = m.querySelector('#wd-night').checked;
4695
+ try {
4696
+ localStorage.setItem('dayNight', dayNightOn ? 'on' : 'off');
4697
+ } catch {
4698
+ /* private window: just for this visit */
4699
+ }
4700
+ try {
4701
+ await api('PATCH', '/api/workday', {
4702
+ autoHome: m.querySelector('#wd-home').checked,
4703
+ idleMin: Number(m.querySelector('#wd-min').value),
4704
+ endHour: m.querySelector('#wd-end').value === '' ? null : Number(m.querySelector('#wd-end').value),
4705
+ autoWake: m.querySelector('#wd-wake').checked,
4706
+ });
4707
+ closeModal();
4708
+ toast(tx('wd.saved'), 'ok');
4709
+ } catch (err) {
4710
+ formError(m, err.message);
4711
+ }
4712
+ });
4713
+ }
4714
+ );
4715
+ }
4716
+ $('#btn-start-all').onclick = async () => {
4717
+ try {
4718
+ const r = await api('POST', '/api/start-all');
4719
+ if (r.errors.length) toast(r.errors.join('\n'), 'err');
4720
+ else toast(tx('toast.morning'), 'ok');
4721
+ } catch (err) {
4722
+ toast(err.message, 'err');
4723
+ }
4724
+ };
4725
+ document.addEventListener('keydown', (e) => {
4726
+ if (e.key !== 'Escape') return;
4727
+ if (!$('#backdrop').hidden) closeModal();
4728
+ else if (panelId && !(document.activeElement && document.activeElement.closest('#term'))) closePanel();
4729
+ else if (focus && !(document.activeElement && document.activeElement.closest('#term'))) leaveFocus();
4730
+ });
4731
+ window.addEventListener('resize', () => {
4732
+ const w = parseFloat(document.documentElement.style.getPropertyValue('--panel-w'));
4733
+ if (w) setPanelWidth(w);
4734
+ resizeCanvas();
4735
+ });
4736
+
4737
+ // Positions depend on time too (desk → garden after a while), not only on state updates.
4738
+ setInterval(() => L && syncSprites(false), 1000);
4739
+
4740
+ makePatterns();
4741
+ resizeCanvas();
4742
+ computeLayout();
4743
+ fitCamera();
4744
+ connect();
4745
+ requestAnimationFrame(frame);