hivedesk 0.1.1 → 0.2.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.
Files changed (51) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/FIRST-RUN.md +14 -0
  3. package/PROTOCOL.md +16 -3
  4. package/README.md +45 -5
  5. package/assets/illustrations/hive-city.svg +113 -0
  6. package/assets/video-poster.webp +0 -0
  7. package/i18n/README.pt-BR.md +39 -5
  8. package/i18n/de.json +174 -0
  9. package/i18n/en.json +174 -0
  10. package/i18n/es.json +174 -0
  11. package/i18n/fr.json +174 -0
  12. package/i18n/it.json +174 -0
  13. package/i18n/ja.json +174 -0
  14. package/i18n/ko.json +174 -0
  15. package/i18n/pt-BR.json +174 -0
  16. package/i18n/ru.json +174 -0
  17. package/i18n/zh-CN.json +174 -0
  18. package/package.json +1 -1
  19. package/src/bus.js +7 -1
  20. package/src/city/demo.js +75 -0
  21. package/src/city/hops.js +95 -0
  22. package/src/city/index.js +1507 -0
  23. package/src/city/router.js +53 -0
  24. package/src/city/state.js +313 -0
  25. package/src/city/store.js +91 -0
  26. package/src/cli.js +3 -0
  27. package/src/crew/engine.js +40 -3
  28. package/src/demo.js +30 -2
  29. package/src/index.js +23 -2
  30. package/src/server.js +4 -1
  31. package/ui/city/city.css +204 -0
  32. package/ui/city/city.js +933 -0
  33. package/ui/city/collab.js +64 -0
  34. package/ui/city/layout.js +142 -0
  35. package/ui/city/mock.js +358 -0
  36. package/ui/city/model.js +195 -0
  37. package/ui/city/scene.js +2033 -0
  38. package/ui/js/main.js +3 -1
  39. package/ui/lend/collab/roles.js +8 -2
  40. package/ui/office/office.js +51 -21
  41. package/ui/office/scene.js +3 -0
  42. package/ui/screenshots/city-agent-card-1440.png +0 -0
  43. package/ui/screenshots/city-agent-card-1920.png +0 -0
  44. package/ui/screenshots/city-bridge-gpu-borrow-1440.png +0 -0
  45. package/ui/screenshots/city-bridge-gpu-borrow-1920.png +0 -0
  46. package/ui/screenshots/city-friend-rising-1440.png +0 -0
  47. package/ui/screenshots/city-friend-rising-1920.png +0 -0
  48. package/ui/screenshots/city-overview-1440.png +0 -0
  49. package/ui/screenshots/city-overview-1920.png +0 -0
  50. package/ui/screenshots/city-review-room-1440.png +0 -0
  51. package/ui/screenshots/city-review-room-1920.png +0 -0
@@ -0,0 +1,933 @@
1
+ // City mode: the default home. One canvas (ui/city/scene.js) under a light DOM layer for the
2
+ // HUD, the task board, the agent card, the machine and room panels and everyone's cursor.
3
+ // State: the engine's CityState reduced by the engine's own reducer (/lib/city.js), or the local
4
+ // mock (?city=mock, ui/city/mock.js), or, on an engine without a city, a city derived from the crew.
5
+
6
+ import { h, clear, append, reducedMotion } from '/js/dom.js';
7
+ import * as net from '/js/net.js';
8
+ import * as wm from '/js/wm.js';
9
+ import * as menu from '/js/menu.js';
10
+ import { S, ui, extra, onEvent } from '/js/store.js';
11
+ import { t, onLocale, fmtNumber } from '/js/i18n.js';
12
+ import { notify } from '/js/notify.js';
13
+ import { beeAvatar } from '/js/bees.js';
14
+ import * as audio from '/office/audio.js';
15
+ import { CityScene } from './scene.js';
16
+ import { viewOf, blankLive, noteEvent, applyLive, deriveCity, xpProgress, xpFor, fmtVram, borrowOf, pendingOf, ROOM_KINDS, ROOM_COLOR } from './model.js';
17
+ import { roomAt, ROOMS } from './layout.js';
18
+ import { wireCollab, onCityEvent as collabEvent } from './collab.js';
19
+
20
+ const st = { mode: 'none', lib: null, city: null, live: blankLive(), view: viewOf(null), mock: null };
21
+ let layer; let canvas; let scene; let hitLayer; let cursorLayer; let hud = {};
22
+ let active = false;
23
+ let office = null;
24
+ const bees = new Map();
25
+ const cursors = new Map();
26
+ let side = null; // { kind: 'agent' | 'machine' | 'room', id }
27
+ let drag = null;
28
+ let pending = false;
29
+ let lastPresence = 0;
30
+ let memoryEdit = null; // { agentId, entries }
31
+ let hourOverride = null;
32
+
33
+ const tr = (k, p) => t(k, p);
34
+ const roomName = (k) => (ROOMS[k] || ROOM_KINDS.includes(k) ? tr(`city.room.${k}`) : (st.view.rooms[k]?.name || k));
35
+ const agentName = (id) => st.view.agents[id]?.name || id || '';
36
+ const machineName = (id) => st.view.machines[id]?.name || id || '';
37
+
38
+ function linkCss() {
39
+ if (document.querySelector('link[data-city]')) return;
40
+ document.head.append(h('link', { rel: 'stylesheet', href: '/city/city.css', 'data-city': '' }));
41
+ }
42
+
43
+ function readHour() {
44
+ const q = new URLSearchParams(location.search).get('hour');
45
+ if (q != null && q !== '' && !Number.isNaN(Number(q))) hourOverride = Math.max(0, Math.min(23.99, Number(q)));
46
+ }
47
+ const hourNow = () => { if (hourOverride != null) return hourOverride; const d = new Date(); return d.getHours() + d.getMinutes() / 60; };
48
+
49
+ /* ---------- state ---------- */
50
+ function refresh() {
51
+ st.view = viewOf(st.city, st.live);
52
+ if (pending) return;
53
+ pending = true;
54
+ requestAnimationFrame(() => {
55
+ pending = false;
56
+ scene?.sync();
57
+ paintHud();
58
+ });
59
+ }
60
+
61
+ function useDerived() {
62
+ st.mode = 'derived';
63
+ st.city = deriveCity(S(), { hardware: extra.hardware, label: tr('city.machine.thisPc') });
64
+ refresh();
65
+ }
66
+
67
+ async function loadLib() {
68
+ try { st.lib = await import('/lib/city.js'); } catch { st.lib = null; }
69
+ return st.lib;
70
+ }
71
+
72
+ async function startMock() {
73
+ const { MockCity } = await import('./mock.js');
74
+ if (!st.lib) await loadLib();
75
+ st.mode = 'mock';
76
+ st.mock = new MockCity({
77
+ emit: (ev) => onCityEvent(ev),
78
+ live: (frame) => { if (applyLive(st.live, frame)) refresh(); },
79
+ speed: Number(new URLSearchParams(location.search).get('cityspeed')) || 1,
80
+ });
81
+ st.city = st.mock.snapshot();
82
+ refresh();
83
+ st.mock.start();
84
+ }
85
+
86
+ function onCityEvent(ev) {
87
+ if (!st.city) return;
88
+ if (st.lib) st.lib.reduceCity(st.city, ev);
89
+ else return;
90
+ noteEvent(st.live, st.city, ev);
91
+ collabEvent(ev, globalThis.hivedeskCollab);
92
+ feed(ev);
93
+ refresh();
94
+ }
95
+
96
+ /** Sends a city command to the engine (or the mock). Errors become a short notification. */
97
+ async function cmd(type, data = {}) {
98
+ try {
99
+ if (st.mode === 'mock') return await st.mock.command(type, data);
100
+ if (st.mode !== 'engine') throw Object.assign(new Error(tr('city.err.noCity')), { code: 'no_city' });
101
+ return await net.command(type, data);
102
+ } catch (err) {
103
+ if (type !== 'city.presence') notify({ title: tr('city.err.generic'), body: err.message, tone: 'bad', timeout: 5000 });
104
+ throw err;
105
+ }
106
+ }
107
+
108
+ async function resync() {
109
+ const r = await net.command('city.sync', { since: st.city?.lastSeq || 0 });
110
+ if (r.snapshot) st.city = JSON.parse(JSON.stringify(r.snapshot));
111
+ for (const ev of r.tail || []) if (ev.seq > (st.city.lastSeq || 0) || r.snapshot) st.lib.reduceCity(st.city, ev);
112
+ refresh();
113
+ }
114
+
115
+ /* ---------- mount ---------- */
116
+ /**
117
+ * Mounts the City and registers it as a view next to Office and Desktop.
118
+ * @param {{ desk: HTMLElement, addDockItem?: Function, office: { addView: Function, setMode: Function, getMode: Function } }} opts
119
+ */
120
+ export async function initCity({ desk, addDockItem, office: off }) {
121
+ office = off;
122
+ linkCss();
123
+ readHour();
124
+ layer = h('section', { class: 'of-layer ct-layer', hidden: true, ta: 'city.aria.layer' });
125
+ canvas = h('canvas', { class: 'of-canvas ct-canvas', 'aria-hidden': 'true' });
126
+ hitLayer = h('div', { class: 'of-hits' });
127
+ cursorLayer = h('div', { class: 'ct-cursors', 'aria-hidden': 'true' });
128
+ layer.append(canvas, hitLayer, cursorLayer, buildHud());
129
+ desk.append(layer);
130
+
131
+ scene = new CityScene(canvas, {
132
+ getCity: () => st.view,
133
+ reduced: reducedMotion,
134
+ hour: hourNow,
135
+ t: tr,
136
+ onSound: (n) => audio.fx(n),
137
+ onFrame: (sc) => { syncHits(sc); syncCursors(sc); levels(sc); roomWatch(sc); },
138
+ });
139
+ new ResizeObserver(() => { if (active) scene.resize(layer.clientWidth, layer.clientHeight); }).observe(layer);
140
+ wireCanvas();
141
+
142
+ office.addView({
143
+ id: 'city', first: true, glyph: cityGlyph, labelKey: 'city.view', titleKey: 'tip.city.view',
144
+ enter: (o) => enter(o), leave: (o) => leave(o),
145
+ });
146
+
147
+ addDockItem?.({
148
+ id: 'city', label: tr('city.dock'), sub: tr('city.dock.sub'),
149
+ content: h('span', { class: 'dk-hex' }, cityGlyph()),
150
+ onClick: () => office.setMode(office.getMode() === 'city' ? 'desktop' : 'city'),
151
+ menu: () => [
152
+ { header: tr('city.title') },
153
+ { label: tr('city.fit'), icon: 'hive', action: () => { office.setMode('city'); scene.fit(); closeSide(); } },
154
+ { label: tr('city.machines'), icon: 'gpu', action: () => { office.setMode('city'); openSide({ kind: 'machine' }); } },
155
+ { label: tr('city.invite'), icon: 'lend', action: () => invite() },
156
+ ],
157
+ });
158
+
159
+ // engine wiring
160
+ const q = new URLSearchParams(location.search).get('city');
161
+ if (q === 'mock') startMock();
162
+ net.on('hello', async (f) => {
163
+ if (st.mode === 'mock') return;
164
+ const city = f.state?.city;
165
+ if ((f.city === 1 || city) && (st.lib || await loadLib())) {
166
+ st.mode = 'engine';
167
+ st.city = city ? JSON.parse(JSON.stringify(city)) : st.lib.initialCity();
168
+ st.live = blankLive();
169
+ refresh();
170
+ } else useDerived();
171
+ });
172
+ net.on('event', (f) => {
173
+ const ev = f.event;
174
+ if (!ev || st.mode !== 'engine') return;
175
+ if (!(st.lib.isCityEvent ? st.lib.isCityEvent(ev) : /^(city\.|worker\.status$|turn\.started$)/.test(ev.type))) return;
176
+ onCityEvent(ev);
177
+ });
178
+ net.on('live', (f) => {
179
+ if (st.mode !== 'engine' || !String(f.type || '').startsWith('city.')) return;
180
+ if (applyLive(st.live, f)) refresh();
181
+ });
182
+ // a dropped link: catch up with city.sync and the tail of events
183
+ let lost = false;
184
+ net.on('connection', (c) => {
185
+ if (c.state !== 'open') { lost = true; return; }
186
+ if (!lost || st.mode !== 'engine') return;
187
+ lost = false;
188
+ resync().catch(() => {});
189
+ });
190
+ const tryWire = () => { if (!wireCollab(() => st.city)) setTimeout(tryWire, 2000); };
191
+ tryWire();
192
+ onEvent((ev) => { if (st.mode === 'derived' && /^(crew|task|job|worker)\./.test(ev.type)) useDerived(); });
193
+ onLocale(() => { scene.palAt = -1; paintHud(); if (side) paintSide(); });
194
+ document.addEventListener('visibilitychange', () => { if (!active) return; if (document.hidden) scene.stop(); else scene.start(); });
195
+ document.addEventListener('keydown', onKey);
196
+ setInterval(() => { if (active) { paintClock(); pruneCursors(); } }, 15000);
197
+ }
198
+
199
+ function enter({ quiet } = {}) {
200
+ active = true;
201
+ layer.hidden = false;
202
+ scene.resize(layer.clientWidth, layer.clientHeight);
203
+ scene.sync();
204
+ scene.start();
205
+ audio.setActive(true);
206
+ paintHud();
207
+ if (!quiet && !reducedMotion()) layer.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 260, easing: 'ease-out' });
208
+ }
209
+
210
+ function leave({ quiet, done } = {}) {
211
+ active = false;
212
+ scene.stop();
213
+ audio.setActive(false);
214
+ cancelDrag();
215
+ const end = () => { layer.hidden = true; done?.(); };
216
+ if (reducedMotion() || quiet) end();
217
+ else layer.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 180, easing: 'ease-in' }).onfinish = end;
218
+ }
219
+
220
+ /** The room panel lists who is in the room on screen: repaint it when a bee arrives or leaves. */
221
+ let roomSig = '';
222
+ function roomWatch(sc) {
223
+ if (side?.kind !== 'room') return;
224
+ let sig = '';
225
+ for (const a of sc.actors.values()) if (a.place.kind === 'room' && a.place.room === side.id && !a.path.length) sig += `${a.id},`;
226
+ if (sig !== roomSig) { roomSig = sig; paintSide(); }
227
+ }
228
+
229
+ function levels(sc) {
230
+ let working = 0; let walking = 0;
231
+ for (const a of sc.actors.values()) { if (a.path.length) walking++; else if (a.mode === 'working') working++; }
232
+ audio.setLevels(working, walking);
233
+ }
234
+
235
+ /* ---------- HUD ---------- */
236
+ function buildHud() {
237
+ hud.title = h('div', { class: 'ct-title' }, h('span', { class: 'ct-logo', html: CITY_SVG, 'aria-hidden': 'true' }), h('strong', { tx: 'city.title' }));
238
+ hud.demo = h('span', { class: 'ct-chip ct-demo', hidden: true });
239
+ hud.stats = h('div', { class: 'ct-stats' });
240
+ hud.caption = h('div', { class: 'ct-caption', hidden: true, role: 'status' });
241
+ const inviteBtn = h('button', { type: 'button', class: 'btn btn-xs ct-invite', on: { click: () => invite() } }, h('span', { class: 'ct-gl', html: '<svg viewBox="0 0 24 24" class="ico ico-sm"><circle cx="9" cy="8" r="3.4"/><path d="M3 19c.6-3.3 3-5.2 6-5.2s5.4 1.9 6 5.2M18 7v6M15 10h6"/></svg>' }), h('span', { tx: 'city.invite' }));
242
+ const cityCard = h('div', { class: 'of-card ct-card' }, h('div', { class: 'of-row' }, hud.title, hud.demo), hud.stats, hud.caption, inviteBtn);
243
+
244
+ // the task board (the Lobby board, mirrored here so notes can be dragged anywhere)
245
+ hud.input = h('input', { class: 'ct-input', type: 'text', maxLength: 200, tp: 'city.board.placeholder', ta: 'city.board.placeholder', on: { keydown: (e) => { if (e.key === 'Enter') addTask(); }, input: () => paintDraft() } });
246
+ hud.draft = h('div', { class: 'ct-note ct-draft', hidden: true, tabindex: '0', role: 'button' });
247
+ hud.draft.addEventListener('pointerdown', (e) => startDrag(e, hud.draft, { draft: true }));
248
+ const addBtn = h('button', { type: 'button', class: 'btn btn-xs btn-primary', tx: 'city.board.add', on: { click: () => addTask() } });
249
+ hud.notes = h('div', { class: 'ct-notes' });
250
+ hud.boardCount = h('span', { class: 'ct-count' });
251
+ hud.board = h('section', { class: 'of-card ct-board', 'aria-labelledby': 'ct-board-h' },
252
+ h('div', { class: 'of-row' }, h('span', { class: 'of-k', id: 'ct-board-h', tx: 'city.board.title' }), hud.boardCount),
253
+ h('div', { class: 'ct-faint', tx: 'city.board.sub' }),
254
+ h('div', { class: 'ct-add' }, hud.input, addBtn),
255
+ hud.draft,
256
+ hud.notes);
257
+
258
+ // top right: people, clock, machines
259
+ hud.people = h('div', { class: 'ct-people' });
260
+ hud.clock = h('div', { class: 'of-pill ct-clock' });
261
+ const machinesBtn = h('button', { type: 'button', class: 'of-pill ct-pill-btn', on: { click: () => toggleSide({ kind: 'machine' }) } }, h('span', { class: 'ct-gl', html: '<svg viewBox="0 0 24 24" class="ico ico-sm"><rect x="4" y="6" width="16" height="12" rx="2"/><path d="M8 10h3v4H8zM14 10h2M14 13h2M8 3v3M12 3v3M16 3v3M8 18v3M12 18v3M16 18v3"/></svg>' }), h('span', { tx: 'city.machines' }));
262
+ hud.top = h('div', { class: 'ct-top' }, hud.people, hud.clock, machinesBtn);
263
+
264
+ // bottom: room bar, zoom, feed
265
+ hud.rooms = h('nav', { class: 'ct-rooms', ta: 'city.rooms' });
266
+ const zb = (txt, key, fn) => h('button', { type: 'button', class: 'of-ib', ta: key, title: tr(key), on: { click: fn } }, h('span', { class: 'ct-gl', html: txt }));
267
+ hud.zoom = h('div', { class: 'of-pill ct-zoom' },
268
+ zb('<svg viewBox="0 0 24 24" class="ico"><path d="M12 6v12M6 12h12"/></svg>', 'city.zoomIn', () => scene.zoomAt(1.35, layer.clientWidth / 2, layer.clientHeight / 2)),
269
+ zb('<svg viewBox="0 0 24 24" class="ico"><path d="M6 12h12"/></svg>', 'city.zoomOut', () => scene.zoomAt(1 / 1.35, layer.clientWidth / 2, layer.clientHeight / 2)),
270
+ zb('<svg viewBox="0 0 24 24" class="ico"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/></svg>', 'city.fit', () => { closeSide(); scene.fit(); }));
271
+ hud.feed = h('ol', { class: 'of-card of-feed ct-feed', 'aria-live': 'polite', ta: 'city.feed' });
272
+ hud.side = h('aside', { class: 'of-card ct-side', hidden: true });
273
+ hud.tip = h('div', { class: 'ct-droptip', hidden: true });
274
+ return h('div', { class: 'of-hud ct-hud' }, cityCard, hud.board, hud.top, hud.side, hud.rooms, hud.zoom, hud.feed, hud.tip);
275
+ }
276
+
277
+ function paintHud() {
278
+ if (!hud.stats || !active) return;
279
+ const v = st.view;
280
+ const machines = Object.values(v.machines);
281
+ const agents = Object.values(v.agents);
282
+ const moving = Object.values(v.tasks).filter((x) => !['open', 'done', 'blocked'].includes(x.status)).length;
283
+ clear(hud.stats);
284
+ hud.stats.append(
285
+ stat(fmtNumber(machines.length), tr('city.stat.machines', { n: machines.length })),
286
+ stat(fmtNumber(agents.length), tr('city.stat.agents', { n: agents.length })),
287
+ stat(fmtNumber(moving), tr('city.stat.moving', { n: moving })));
288
+ const isDemo = st.mode === 'mock' || ui.demo;
289
+ hud.demo.hidden = !isDemo;
290
+ hud.demo.textContent = st.mode === 'mock' ? tr('city.mock') : tr('city.demo');
291
+ // demo captions
292
+ const cap = v.caption;
293
+ if (cap && Date.now() - cap.at < 9000) {
294
+ hud.caption.hidden = false;
295
+ hud.caption.textContent = DEMO_STEPS.includes(cap.step) ? tr(`city.demo.${cap.step}`) : cap.text;
296
+ clearTimeout(hud.caption._t);
297
+ hud.caption._t = setTimeout(() => { hud.caption.hidden = true; }, 9000 - (Date.now() - cap.at));
298
+ }
299
+ paintBoard();
300
+ paintPeople();
301
+ paintClock();
302
+ paintRooms();
303
+ if (side) paintSide();
304
+ }
305
+
306
+ function stat(n, label) { return h('div', { class: 'ct-stat' }, h('b', { text: n }), h('span', { text: label })); }
307
+
308
+ function paintClock() {
309
+ const hr = hourNow();
310
+ const hh = Math.floor(hr); const mm = Math.floor((hr % 1) * 60);
311
+ const phase = hr >= 5 && hr < 8 ? 'morning' : hr < 12 && hr >= 8 ? 'day' : hr >= 12 && hr < 17 ? 'afternoon' : hr >= 17 && hr < 20 ? 'evening' : 'night';
312
+ clear(hud.clock);
313
+ hud.clock.append(h('span', { class: 'ct-gl', html: phase === 'night' || phase === 'evening' ? '<svg viewBox="0 0 24 24" class="ico ico-sm"><path d="M19 14.5A7.5 7.5 0 0 1 9.5 5a7.5 7.5 0 1 0 9.5 9.5z"/></svg>' : '<svg viewBox="0 0 24 24" class="ico ico-sm"><circle cx="12" cy="12" r="4"/><path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M5.6 18.4 7 17M17 7l1.4-1.4"/></svg>' }),
314
+ h('span', { text: tr(`city.phase.${phase}`) }), h('b', { text: `${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}` }));
315
+ }
316
+
317
+ function paintPeople() {
318
+ const people = Object.values(st.view.people || {}).filter((p) => !isMe(p) && Date.now() - (p.seen || 0) < 20000);
319
+ clear(hud.people);
320
+ hud.people.hidden = !people.length;
321
+ const me = h('span', { class: 'ct-person ct-me', title: tr('city.you') }, h('i', { style: 'background:#FFB531' }), h('span', { tx: 'city.you' }));
322
+ hud.people.append(me);
323
+ for (const p of people.slice(0, 5)) hud.people.append(h('span', { class: 'ct-person', title: p.name }, h('i', { style: `background:${safeColor(p.color)}` }), h('span', { text: String(p.name || '').slice(0, 20) })));
324
+ }
325
+
326
+ function isMe(p) { return !net.isRemote() && p.id === 'h'; }
327
+ const safeColor = (c) => (/^#[0-9a-f]{6}$/i.test(c || '') ? c : '#86A9D6');
328
+
329
+ function paintRooms() {
330
+ const counts = {};
331
+ for (const x of Object.values(st.view.tasks)) if (x.status !== 'done') counts[x.room] = (counts[x.room] || 0) + 1;
332
+ const focus = scene.focus?.kind === 'room' ? scene.focus.id : null;
333
+ const items = [{ id: '', city: true }, ...Object.keys(st.view.rooms).filter((k) => ROOMS[k]).map((id) => ({ id }))];
334
+ clear(hud.rooms);
335
+ for (const it of items) {
336
+ const on = it.city ? !focus : focus === it.id;
337
+ const b = h('button', { type: 'button', class: 'ct-room', 'aria-pressed': String(on), on: { click: () => (it.city ? (closeSide(), scene.fit()) : openRoom(it.id)) } },
338
+ it.city ? h('span', { class: 'ct-gl', html: CITY_SVG }) : h('i', { style: `background:${ROOM_COLOR[it.id] || '#FFB531'}` }),
339
+ h('span', { text: it.city ? tr('city.fit') : roomName(it.id) }),
340
+ !it.city && counts[it.id] ? h('b', { text: String(counts[it.id]) }) : null);
341
+ if (!it.city) { b.dataset.room = it.id; b.addEventListener('pointerenter', () => { scene.highlight = { kind: 'room', id: it.id }; }); b.addEventListener('pointerleave', () => { scene.highlight = null; }); }
342
+ hud.rooms.append(b);
343
+ }
344
+ }
345
+
346
+ /* ---------- the task board ---------- */
347
+ const DEMO_STEPS = ['friend', 'borrow', 'lent', 'task', 'done'];
348
+ const STATUS_ORDER = { in_progress: 0, in_review: 0, in_test: 0, claimed: 0, open: 1, blocked: 2, done: 3 };
349
+
350
+ function paintBoard() {
351
+ const tasks = Object.values(st.view.tasks).sort((a, b) => (STATUS_ORDER[a.status] ?? 1) - (STATUS_ORDER[b.status] ?? 1) || String(b.updatedAt || '').localeCompare(String(a.updatedAt || '')) || a.id.localeCompare(b.id));
352
+ const done = tasks.filter((x) => x.status === 'done');
353
+ const list = [...tasks.filter((x) => x.status !== 'done'), ...done.slice(0, 3)];
354
+ hud.boardCount.textContent = tr('city.board.count', { n: tasks.length - done.length });
355
+ const keep = new Set();
356
+ const frag = [];
357
+ for (const x of list) {
358
+ keep.add(x.id);
359
+ let n = hud.notes.querySelector(`[data-id="${CSS.escape(x.id)}"]`);
360
+ if (!n) n = makeNote(x.id);
361
+ paintNote(n, x);
362
+ frag.push(n);
363
+ }
364
+ for (const n of [...hud.notes.children]) if (!keep.has(n.dataset.id)) n.remove();
365
+ frag.forEach((n, i) => { if (hud.notes.children[i] !== n) hud.notes.insertBefore(n, hud.notes.children[i] || null); });
366
+ if (!list.length && !hud.notes.querySelector('.ct-empty')) hud.notes.append(h('div', { class: 'ct-empty', tx: 'city.board.empty' }));
367
+ else if (list.length) hud.notes.querySelector('.ct-empty')?.remove();
368
+ }
369
+
370
+ function makeNote(id) {
371
+ const n = h('div', { class: 'ct-note', tabindex: '0', role: 'button', dataset: { id } });
372
+ n.addEventListener('pointerdown', (e) => startDrag(e, n, { taskId: id }));
373
+ n.addEventListener('click', () => { if (n._dragged) { n._dragged = false; return; } const x = st.view.tasks[id]; if (x && ROOMS[x.room]) openRoom(x.room); });
374
+ n.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); const r = n.getBoundingClientRect(); menu.open({ x: r.left + 12, y: r.bottom, items: noteMenu(id) }); } });
375
+ menu.provide(n, () => noteMenu(id));
376
+ return n;
377
+ }
378
+
379
+ function paintNote(n, x) {
380
+ const a = x.assignee && st.view.agents[x.assignee];
381
+ const key = `${x.title}|${x.status}|${x.room}|${x.assignee}|${x.loops}|${x.awaiting}`;
382
+ if (n._key === key) return;
383
+ n._key = key;
384
+ n.dataset.s = x.status;
385
+ n.style.setProperty('--strip', a?.color || ROOM_COLOR[x.room] || '#FFB531');
386
+ clear(n);
387
+ n.append(
388
+ h('div', { class: 'ct-note-t', text: x.title }),
389
+ h('div', { class: 'ct-note-m' },
390
+ h('span', { class: 'ct-tag', style: `--c:${ROOM_COLOR[x.room] || '#FFB531'}`, text: roomName(x.room) }),
391
+ h('span', { class: 'ct-faint', text: tr(`city.task.status.${x.status}`) }),
392
+ a ? h('span', { class: 'ct-who' }, beeAvatar(avatarOf(a), 16, { ring: false }), h('span', { text: a.name })) : null,
393
+ x.awaiting ? h('span', { class: 'ct-tag ct-warn', tx: 'city.task.awaiting' }) : null,
394
+ x.loops ? h('span', { class: 'ct-faint', text: tr('city.task.loops', { n: x.loops, max: x.maxLoops }) }) : null));
395
+ n.setAttribute('aria-label', `${x.title}. ${tr(`city.task.status.${x.status}`)}. ${roomName(x.room)}${a ? `. ${a.name}` : ''}. ${tr('city.board.sub')}`);
396
+ }
397
+
398
+ function noteMenu(id) {
399
+ const x = st.view.tasks[id];
400
+ if (!x) return null;
401
+ const off = x.status === 'done';
402
+ return [
403
+ { header: x.title },
404
+ { label: tr('city.menu.handTo'), icon: 'hire', disabled: off, items: Object.values(st.view.agents).map((a) => ({ label: `${a.name} (${a.role})`, iconEl: beeAvatar(avatarOf(a), 18, { ring: false }), action: () => cmd('city.task.assign', { taskId: id, agentId: a.id }).catch(() => {}) })) },
405
+ { label: tr('city.menu.sendTo'), icon: 'arrow', disabled: off, items: Object.keys(st.view.rooms).map((k) => ({ label: roomName(k), action: () => cmd('city.task.move', { taskId: id, room: k }).catch(() => {}) })) },
406
+ { sep: true },
407
+ { label: tr('city.task.approve'), icon: 'check', disabled: !x.awaiting, action: () => cmd('city.task.approve', { taskId: id }).catch(() => {}) },
408
+ { label: tr('city.task.retry'), icon: 'replay', disabled: x.status !== 'blocked', action: () => cmd('city.task.retry', { taskId: id }).catch(() => {}) },
409
+ { label: tr('city.task.cancel'), icon: 'x', danger: true, disabled: off, action: () => cmd('city.task.cancel', { taskId: id }).catch(() => {}) },
410
+ ];
411
+ }
412
+
413
+ function paintDraft() {
414
+ const text = hud.input.value.trim();
415
+ hud.draft.hidden = !text;
416
+ clear(hud.draft);
417
+ if (text) hud.draft.append(h('div', { class: 'ct-note-t', text }), h('div', { class: 'ct-faint', tx: 'city.board.draft' }));
418
+ }
419
+
420
+ async function addTask(target = {}) {
421
+ const title = hud.input.value.trim();
422
+ if (!title) { hud.input.focus(); return; }
423
+ hud.input.value = '';
424
+ paintDraft();
425
+ await cmd('city.task.create', { title, ...(target.agentId ? { agentId: target.agentId } : { room: target.room || 'lobby' }) }).catch(() => { hud.input.value = title; paintDraft(); });
426
+ }
427
+
428
+ /* ---------- drag a note onto a bee or a room ---------- */
429
+ function startDrag(e, el, what) {
430
+ if (e.button !== 0 || ui.replay) return;
431
+ if (what.taskId && st.view.tasks[what.taskId]?.status === 'done') return;
432
+ const x0 = e.clientX; const y0 = e.clientY;
433
+ let ghost = null;
434
+ const move = (ev) => {
435
+ if (!drag && Math.hypot(ev.clientX - x0, ev.clientY - y0) < 6) return;
436
+ if (!drag) {
437
+ drag = { ...what, el };
438
+ scene.dragTask = what.taskId || null;
439
+ const title = what.draft ? hud.input.value.trim() : st.view.tasks[what.taskId]?.title;
440
+ ghost = h('div', { class: 'of-drag ct-ghost', 'aria-hidden': 'true' }, h('i', { style: `background:${getComputedStyle(el).getPropertyValue('--strip') || '#FFB531'}` }), h('span', { text: title || '' }));
441
+ layer.append(ghost);
442
+ layer.classList.add('of-dragging');
443
+ el.classList.add('ct-lifted');
444
+ }
445
+ const lr = layer.getBoundingClientRect();
446
+ ghost.style.transform = `translate(${ev.clientX - lr.left + 10}px, ${ev.clientY - lr.top + 10}px) rotate(-4deg)`;
447
+ const target = targetAt(ev.clientX, ev.clientY);
448
+ drag.target = target;
449
+ scene.dropTarget = target;
450
+ if (target) {
451
+ hud.tip.hidden = false;
452
+ hud.tip.textContent = target.kind === 'agent' ? tr('city.drop.agent', { name: agentName(target.id) }) : tr('city.drop.room', { room: roomName(target.id) });
453
+ hud.tip.style.transform = `translate(${ev.clientX - lr.left + 14}px, ${ev.clientY - lr.top - 34}px)`;
454
+ } else hud.tip.hidden = true;
455
+ };
456
+ const up = () => {
457
+ removeEventListener('pointermove', move);
458
+ removeEventListener('pointerup', up);
459
+ removeEventListener('pointercancel', up);
460
+ if (!drag) return;
461
+ el._dragged = true;
462
+ const { target } = drag;
463
+ const w = drag;
464
+ ghost?.remove();
465
+ cancelDrag();
466
+ if (!target) return;
467
+ audio.fx('stick');
468
+ if (w.draft) addTask(target.kind === 'agent' ? { agentId: target.id } : { room: target.id });
469
+ else if (target.kind === 'agent') cmd('city.task.assign', { taskId: w.taskId, agentId: target.id }).catch(() => {});
470
+ else cmd('city.task.move', { taskId: w.taskId, room: target.id }).catch(() => {});
471
+ };
472
+ addEventListener('pointermove', move);
473
+ addEventListener('pointerup', up);
474
+ addEventListener('pointercancel', up);
475
+ }
476
+
477
+ function cancelDrag() {
478
+ layer?.querySelector('.ct-ghost')?.remove();
479
+ layer?.classList.remove('of-dragging');
480
+ for (const n of layer?.querySelectorAll('.ct-lifted') || []) n.classList.remove('ct-lifted');
481
+ if (hud.tip) hud.tip.hidden = true;
482
+ if (scene) { scene.dragTask = null; scene.dropTarget = null; }
483
+ drag = null;
484
+ }
485
+
486
+ function targetAt(x, y) {
487
+ for (const [id, b] of bees) {
488
+ const r = b.getBoundingClientRect();
489
+ if (x >= r.left - 4 && x <= r.right + 4 && y >= r.top - 4 && y <= r.bottom + 4) return { kind: 'agent', id };
490
+ }
491
+ const chip = document.elementFromPoint(x, y)?.closest?.('.ct-room[data-room]');
492
+ if (chip) return { kind: 'room', id: chip.dataset.room };
493
+ const lr = canvas.getBoundingClientRect();
494
+ if (x < lr.left || y < lr.top || x > lr.right || y > lr.bottom) return null;
495
+ const w = scene.unproject(x - lr.left, y - lr.top + scene.cam.A * 0.3 * 1.12);
496
+ const k = roomAt(w.x, w.y);
497
+ return k && st.view.rooms[k] ? { kind: 'room', id: k } : null;
498
+ }
499
+
500
+ /* ---------- canvas: pan, zoom, click, presence ---------- */
501
+ function wireCanvas() {
502
+ let down = null;
503
+ canvas.addEventListener('pointerdown', (e) => {
504
+ if (e.button !== 0) return;
505
+ down = { x: e.clientX, y: e.clientY, lx: e.clientX, ly: e.clientY, moved: false, id: e.pointerId };
506
+ canvas.setPointerCapture(e.pointerId);
507
+ });
508
+ canvas.addEventListener('pointermove', (e) => {
509
+ const lr = canvas.getBoundingClientRect();
510
+ const sx = e.clientX - lr.left; const sy = e.clientY - lr.top;
511
+ if (down) {
512
+ if (!down.moved && Math.hypot(e.clientX - down.x, e.clientY - down.y) > 5) { down.moved = true; layer.classList.add('ct-panning'); }
513
+ if (down.moved) { scene.panBy(e.clientX - down.lx, e.clientY - down.ly); down.lx = e.clientX; down.ly = e.clientY; if (scene.focus && Math.hypot(e.clientX - down.x, e.clientY - down.y) > 120) scene.focus = null; }
514
+ return;
515
+ }
516
+ // hover: rooms and buildings light up
517
+ const m = scene.machineHits.find((r) => sx >= r.x && sx <= r.x + r.w && sy >= r.y && sy <= r.y + r.h);
518
+ const w = scene.unproject(sx, sy + scene.cam.A * 0.3 * 1.12);
519
+ const room = roomAt(w.x, w.y);
520
+ const hl = m ? { kind: 'machine', id: m.id } : room ? { kind: 'room', id: room } : null;
521
+ if (!drag && (scene.highlight?.kind !== 'agent')) scene.highlight = hl;
522
+ canvas.style.cursor = hl ? 'pointer' : 'grab';
523
+ presence(w, room);
524
+ });
525
+ const end = (e) => {
526
+ if (!down) return;
527
+ const wasMove = down.moved;
528
+ down = null;
529
+ layer.classList.remove('ct-panning');
530
+ try { canvas.releasePointerCapture(e.pointerId); } catch { /* ignore */ }
531
+ if (wasMove) return;
532
+ const lr = canvas.getBoundingClientRect();
533
+ const sx = e.clientX - lr.left; const sy = e.clientY - lr.top;
534
+ const m = scene.machineHits.find((r) => sx >= r.x && sx <= r.x + r.w && sy >= r.y && sy <= r.y + r.h);
535
+ if (m) { openSide({ kind: 'machine', id: m.id }); scene.focusMachine(m.id); paintRooms(); return; }
536
+ const w = scene.unproject(sx, sy + scene.cam.A * 0.3 * 1.12);
537
+ const room = roomAt(w.x, w.y);
538
+ if (room) openRoom(room);
539
+ else if (Math.hypot(w.x + 1.6, w.y + 1.4) < 2.4) openSide({ kind: 'machine', id: st.view.selfId });
540
+ };
541
+ canvas.addEventListener('pointerup', end);
542
+ canvas.addEventListener('pointercancel', () => { down = null; layer.classList.remove('ct-panning'); });
543
+ canvas.addEventListener('dblclick', () => { closeSide(); scene.fit(); paintRooms(); });
544
+ canvas.addEventListener('wheel', (e) => {
545
+ e.preventDefault();
546
+ const lr = canvas.getBoundingClientRect();
547
+ scene.zoomAt(Math.exp(-e.deltaY * 0.0015), e.clientX - lr.left, e.clientY - lr.top);
548
+ paintRooms();
549
+ }, { passive: false });
550
+ canvas.addEventListener('pointerleave', () => { if (!drag) scene.highlight = null; });
551
+ }
552
+
553
+ function presence(w, room) {
554
+ const now = performance.now();
555
+ if (now - lastPresence < 100 || st.mode !== 'engine') return;
556
+ const others = Object.values(st.view.people || {}).some((p) => !isMe(p));
557
+ if (!others && !net.isRemote()) return;
558
+ lastPresence = now;
559
+ cmd('city.presence', { x: Math.round(w.x * 100) / 100, y: Math.round(w.y * 100) / 100, room: room || undefined }).catch(() => {});
560
+ }
561
+
562
+ function syncCursors(sc) {
563
+ const seen = new Set();
564
+ for (const p of Object.values(st.view.people || {})) {
565
+ if (isMe(p) || !Number.isFinite(p.x) || !Number.isFinite(p.y)) continue;
566
+ if (Date.now() - (p.seen || 0) > 20000) continue;
567
+ seen.add(p.id);
568
+ let c = cursors.get(p.id);
569
+ if (!c) {
570
+ c = h('div', { class: 'ct-cursor' }, h('span', { class: 'ct-arrow', html: '<svg viewBox="0 0 20 22"><path d="M2 2l15 8.2-6.4 1.6-3.2 6.4z"/></svg>' }), h('span', { class: 'ct-cname' }));
571
+ cursorLayer.append(c);
572
+ cursors.set(p.id, c);
573
+ c._x = null;
574
+ }
575
+ const col = safeColor(p.color);
576
+ if (c._col !== col) { c._col = col; c.style.setProperty('--c', col); }
577
+ if (c._name !== p.name) { c._name = p.name; c.querySelector('.ct-cname').textContent = String(p.name || '').slice(0, 24); }
578
+ const [x, y] = sc.P(p.x, p.y, 0.3);
579
+ // ease toward the reported point so 10 updates a second still glide
580
+ const k = reducedMotion() || c._x == null ? 1 : 0.35;
581
+ c._x = c._x == null ? x : c._x + (x - c._x) * k;
582
+ c._y = c._y == null ? y : c._y + (y - c._y) * k;
583
+ c.style.transform = `translate(${Math.round(c._x)}px, ${Math.round(c._y)}px)`;
584
+ c.classList.toggle('ct-stale', Date.now() - (p.seen || 0) > 6000);
585
+ }
586
+ for (const [id, c] of cursors) if (!seen.has(id)) { c.remove(); cursors.delete(id); }
587
+ }
588
+
589
+ function pruneCursors() {
590
+ for (const [id, p] of Object.entries(st.live.people)) if (Date.now() - (p.seen || 0) > 60000) delete st.live.people[id];
591
+ paintPeople();
592
+ }
593
+
594
+ /* ---------- bees: the DOM layer over the canvas for focus, click and drop ---------- */
595
+ function syncHits(sc) {
596
+ const seen = new Set();
597
+ for (const hit of sc.hits) {
598
+ seen.add(hit.id);
599
+ let b = bees.get(hit.id);
600
+ if (!b) b = makeBee(hit.id);
601
+ const tx = Math.round(hit.x); const ty = Math.round(hit.y);
602
+ if (b._x !== tx || b._y !== ty || b._w !== Math.round(hit.w)) {
603
+ b._x = tx; b._y = ty; b._w = Math.round(hit.w);
604
+ b.style.transform = `translate(${tx}px, ${ty}px)`;
605
+ b.style.width = `${Math.round(hit.w)}px`;
606
+ b.style.height = `${Math.round(hit.h)}px`;
607
+ }
608
+ const a = st.view.agents[hit.id];
609
+ const label = a ? `${a.name}, ${a.role}, ${tr('city.card.level', { n: a.level })}. ${tr(`city.agent.status.${a.status}`)}. ${roomName(a.room)}.` : hit.id;
610
+ if (b._label !== label) { b._label = label; b.setAttribute('aria-label', label); }
611
+ }
612
+ for (const [id, b] of bees) if (!seen.has(id)) { b.remove(); bees.delete(id); }
613
+ }
614
+
615
+ function makeBee(id) {
616
+ const b = h('button', { type: 'button', class: 'of-bee', dataset: { id } });
617
+ b.addEventListener('click', () => { if (!drag) openSide({ kind: 'agent', id }); });
618
+ b.addEventListener('pointerenter', () => { scene.highlight = { kind: 'agent', id }; });
619
+ b.addEventListener('pointerleave', () => { if (scene.highlight?.id === id) scene.highlight = null; });
620
+ b.addEventListener('focus', () => { scene.highlight = { kind: 'agent', id }; });
621
+ b.addEventListener('blur', () => { if (scene.highlight?.id === id) scene.highlight = null; });
622
+ b.addEventListener('wheel', (e) => { e.preventDefault(); const lr = canvas.getBoundingClientRect(); scene.zoomAt(Math.exp(-e.deltaY * 0.0015), e.clientX - lr.left, e.clientY - lr.top); }, { passive: false });
623
+ menu.provide(b, () => agentMenu(id));
624
+ hitLayer.append(b);
625
+ bees.set(id, b);
626
+ return b;
627
+ }
628
+
629
+ function agentMenu(id) {
630
+ const a = st.view.agents[id];
631
+ if (!a) return null;
632
+ return [
633
+ { header: `${a.name} · ${a.role} · ${tr('city.card.level', { n: a.level })}` },
634
+ { label: tr('city.card.open'), icon: 'hire', action: () => openSide({ kind: 'agent', id }) },
635
+ { label: tr('city.card.moveTo'), icon: 'arrow', items: Object.keys(st.view.rooms).map((k) => ({ label: roomName(k), checked: a.room === k, action: () => cmd('city.agent.move', { agentId: id, room: k }).catch(() => {}) })) },
636
+ { label: tr('city.card.chat'), icon: 'chat', action: () => chatWith(a) },
637
+ ];
638
+ }
639
+
640
+ const avatarOf = (a) => ({ id: a.workerId || a.id, name: a.name, role: a.role, color: a.color });
641
+
642
+ /* ---------- side panel: agent card, machines, room ---------- */
643
+ function openSide(s) {
644
+ side = s;
645
+ memoryEdit = null;
646
+ hud.side.hidden = false;
647
+ paintSide();
648
+ scene.panelRight = true;
649
+ if (!scene.focus && !scene.userMoved) scene.fit();
650
+ if (!reducedMotion()) hud.side.animate([{ opacity: 0, transform: 'translateX(14px)' }, { opacity: 1, transform: 'none' }], { duration: 220, easing: 'cubic-bezier(.16,1,.3,1)' });
651
+ if (s.kind === 'agent') scene.highlight = { kind: 'agent', id: s.id };
652
+ }
653
+ function toggleSide(s) { if (side && side.kind === s.kind && side.id === s.id) closeSide(); else openSide(s); }
654
+ function closeSide() {
655
+ side = null; memoryEdit = null;
656
+ if (hud.side) hud.side.hidden = true;
657
+ if (scene) { scene.panelRight = false; if (!scene.focus && !scene.userMoved) scene.fit(); }
658
+ if (scene?.focus?.kind === 'room' || scene?.focus?.kind === 'machine') scene.fit();
659
+ paintRooms();
660
+ }
661
+
662
+ function openRoom(id) {
663
+ scene.focusRoom(id);
664
+ openSide({ kind: 'room', id });
665
+ paintRooms();
666
+ audio.fx('whoosh');
667
+ }
668
+
669
+ function paintSide() {
670
+ if (!side || !hud.side) return;
671
+ clear(hud.side);
672
+ const close = h('button', { type: 'button', class: 'of-ib ct-close', ta: 'city.card.close', title: tr('city.card.close'), on: { click: () => closeSide() } }, h('span', { class: 'ct-gl', html: '<svg viewBox="0 0 24 24" class="ico"><path d="M6 6l12 12M18 6 6 18"/></svg>' }));
673
+ let body = null;
674
+ if (side.kind === 'agent') body = agentCard(side.id);
675
+ else if (side.kind === 'machine') body = machinePanel(side.id);
676
+ else if (side.kind === 'room') body = roomPanel(side.id);
677
+ if (!body) { closeSide(); return; }
678
+ hud.side.dataset.kind = side.kind;
679
+ hud.side.append(close, body);
680
+ }
681
+
682
+ function agentCard(id) {
683
+ const a = st.view.agents[id];
684
+ if (!a) return null;
685
+ const v = st.view;
686
+ const task = a.taskId && v.tasks[a.taskId];
687
+ const home = v.machines[a.home];
688
+ const mine = !home || home.self || st.mode === 'mock';
689
+ const lv = a.level;
690
+ const next = xpFor(lv + 1);
691
+ const borrow = borrowOf(v, a.id);
692
+ const ask = pendingOf(v, a.id);
693
+ const brain = borrow ? { kind: 'lent', label: machineName(borrow.to) } : a.brain || { kind: 'local' };
694
+ const card = h('div', { class: 'ct-agent' });
695
+ card.append(
696
+ h('div', { class: 'ct-agent-h' },
697
+ h('div', { class: 'ct-av', style: `--c:${a.color}` }, beeAvatar(avatarOf(a), 58, { ring: true, status: a.status === 'working' ? 'thinking' : undefined })),
698
+ h('div', { class: 'ct-agent-n' },
699
+ h('strong', { text: a.name }),
700
+ h('div', { class: 'ct-faint', text: a.role }),
701
+ h('div', { class: 'ct-lvrow' }, h('span', { class: 'ct-lv', text: tr('city.card.level', { n: lv }) }),
702
+ h('div', { class: 'of-xp ct-xp', role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': '100', 'aria-valuenow': String(Math.round(xpProgress(a) * 100)) }, h('i', { style: `width:${Math.round(xpProgress(a) * 100)}%` }), h('b'))),
703
+ h('div', { class: 'ct-faint tiny', text: tr('city.card.xp', { xp: fmtNumber(a.xp), left: fmtNumber(Math.max(0, next - a.xp)), next: lv + 1 }) }))),
704
+ h('div', { class: 'ct-status', dataset: { s: a.status } }, h('i'), h('span', { text: tr(`city.agent.status.${a.status}`) }), ask ? h('span', { class: 'ct-tag ct-info', tx: 'city.borrow.asking' }) : null),
705
+ );
706
+ const grid = h('dl', { class: 'ct-grid' });
707
+ const roomSel = h('select', { class: 'ct-select', ta: 'city.card.moveTo', on: { change: (e) => cmd('city.agent.move', { agentId: id, room: e.target.value }).catch(() => paintSide()) } },
708
+ ...Object.keys(v.rooms).map((k) => h('option', { value: k, text: roomName(k), selected: a.room === k })));
709
+ grid.append(
710
+ h('dt', { tx: 'city.card.room' }), h('dd', {}, roomSel),
711
+ h('dt', { tx: 'city.card.task' }), h('dd', { text: task ? task.title : tr('city.card.none') }),
712
+ h('dt', { tx: 'city.card.brain' }), h('dd', {}, h('span', { class: `ct-brain ct-brain-${brain.kind}`, text: tr(`city.brain.${brain.kind}`) || brain.kind }), brain.label ? h('span', { class: 'ct-faint', text: ` ${brain.label}` }) : null),
713
+ h('dt', { tx: 'city.card.home' }), h('dd', {}, h('i', { class: 'ct-dot', style: `background:${home?.color || '#FFB531'}` }), h('span', { text: home ? home.name : '' })),
714
+ h('dt', { tx: 'city.card.spec' }), h('dd', {}, ...(a.specialization || []).map((k) => h('span', { class: 'ct-tag', style: `--c:${ROOM_COLOR[k] || '#FFB531'}`, text: roomName(k) }))));
715
+ card.append(grid);
716
+ if (a.stats && (a.stats.done || a.stats.reviews || a.stats.tests)) card.append(h('div', { class: 'ct-faint small', text: tr('city.card.stats', { done: a.stats.done || 0, reviews: a.stats.reviews || 0, tests: a.stats.tests || 0 }) }));
717
+
718
+ // memory
719
+ const memBox = h('section', { class: 'ct-sec' }, h('div', { class: 'of-row' }, h('span', { class: 'of-k', tx: 'city.card.memory' }), h('span', { class: 'ct-faint small', text: tr('city.card.memoryCount', { n: a.memoryCount }) })));
720
+ if (memoryEdit?.agentId === id) memBox.append(memoryEditor(a));
721
+ else {
722
+ const ul = h('ul', { class: 'ct-mem' });
723
+ for (const m of a.memory.slice(0, 4)) ul.append(h('li', { dataset: { k: m.kind } }, h('span', { class: 'ct-mk', text: tr(`city.memory.kind.${m.kind}`) || m.kind }), h('span', { text: m.text })));
724
+ if (!a.memory.length) ul.append(h('li', { class: 'ct-faint', tx: 'city.card.memoryEmpty' }));
725
+ memBox.append(ul);
726
+ if (mine) memBox.append(h('button', { type: 'button', class: 'btn btn-xs btn-quiet', tx: 'city.card.editMemory', on: { click: () => loadMemory(id) } }));
727
+ }
728
+ card.append(memBox);
729
+
730
+ // tools
731
+ const all = new Set([...(a.tools || []), ...Object.values(v.rooms).flatMap((r) => r.tools || [])]);
732
+ const tools = h('div', { class: 'ct-tools' });
733
+ for (const tool of [...all].sort()) {
734
+ const on = (a.tools || []).includes(tool);
735
+ tools.append(h('button', { type: 'button', class: 'ct-tool', 'aria-pressed': String(on), disabled: !mine, text: tool, on: { click: () => { const next = on ? a.tools.filter((x) => x !== tool) : [...a.tools, tool]; cmd('city.agent.update', { agentId: id, tools: next }).catch(() => {}); } } }));
736
+ }
737
+ card.append(h('section', { class: 'ct-sec' }, h('span', { class: 'of-k', tx: 'city.card.tools' }), h('div', { class: 'ct-faint small', tx: mine ? 'city.card.toolsHelp' : 'city.card.friendAgent' }), tools));
738
+
739
+ // actions
740
+ const acts = h('div', { class: 'ct-acts' });
741
+ acts.append(h('button', { type: 'button', class: 'btn btn-xs', tx: 'city.card.chat', on: { click: () => chatWith(a) } }));
742
+ const lenders = Object.values(v.machines).filter((m) => m.id !== a.home && m.online);
743
+ if (borrow) acts.append(h('button', { type: 'button', class: 'btn btn-xs', tx: 'city.borrow.stop', on: { click: () => cmd('city.borrow.stop', { borrowId: borrow.id }).catch(() => {}) } }));
744
+ else if (lenders.length && !ask) acts.append(h('button', { type: 'button', class: 'btn btn-xs', text: tr('city.card.borrow', { name: lenders[0].name }), on: { click: () => cmd('city.borrow.request', { agentId: id, machineId: lenders[0].id }).catch(() => {}) } }));
745
+ if (mine) {
746
+ if (a.status === 'sleeping') acts.append(h('button', { type: 'button', class: 'btn btn-xs', tx: 'city.card.wake', on: { click: () => cmd('city.agent.wake', { agentId: id }).catch(() => {}) } }));
747
+ else acts.append(h('button', { type: 'button', class: 'btn btn-xs btn-quiet', tx: a.builtin ? 'city.card.sleep' : 'city.card.retire', on: { click: () => cmd('city.agent.retire', { agentId: id }).then(() => { if (!a.builtin) closeSide(); }).catch(() => {}) } }));
748
+ }
749
+ card.append(acts);
750
+ return card;
751
+ }
752
+
753
+ async function loadMemory(agentId) {
754
+ try {
755
+ const r = await cmd('city.agent.memory.list', { agentId });
756
+ memoryEdit = { agentId, entries: r.entries || [] };
757
+ } catch { memoryEdit = null; }
758
+ paintSide();
759
+ }
760
+
761
+ function memoryEditor(a) {
762
+ const box = h('div', { class: 'ct-memedit' });
763
+ const reload = () => loadMemory(a.id);
764
+ for (const m of memoryEdit.entries) {
765
+ const input = h('input', { class: 'ct-input', type: 'text', value: m.text, maxLength: 300, 'aria-label': tr('city.card.memory') });
766
+ input.addEventListener('change', () => cmd('city.agent.memory.update', { agentId: a.id, id: m.id, text: input.value }).then(reload).catch(() => {}));
767
+ box.append(h('div', { class: 'ct-memrow' },
768
+ h('button', { type: 'button', class: 'ct-pin', 'aria-pressed': String(!!m.pinned), title: tr(m.pinned ? 'city.card.unpin' : 'city.card.pin'), ta: m.pinned ? 'city.card.unpin' : 'city.card.pin', on: { click: () => cmd('city.agent.memory.update', { agentId: a.id, id: m.id, pinned: !m.pinned }).then(reload).catch(() => {}) } }, h('span', { class: 'ct-gl', html: '<svg viewBox="0 0 24 24" class="ico ico-sm"><path d="M9 4h6l-1 6 3 3H7l3-3zM12 13v7"/></svg>' })),
769
+ input,
770
+ h('button', { type: 'button', class: 'of-ib', title: tr('city.card.delete'), ta: 'city.card.delete', on: { click: () => cmd('city.agent.memory.delete', { agentId: a.id, id: m.id }).then(reload).catch(() => {}) } }, h('span', { class: 'ct-gl', html: '<svg viewBox="0 0 24 24" class="ico ico-sm"><path d="M6 6l12 12M18 6 6 18"/></svg>' }))));
771
+ }
772
+ const add = h('input', { class: 'ct-input', type: 'text', maxLength: 300, tp: 'city.card.addMemory', ta: 'city.card.addMemory' });
773
+ const save = () => { const text = add.value.trim(); if (!text) return; cmd('city.agent.memory.add', { agentId: a.id, text }).then(reload).catch(() => {}); };
774
+ add.addEventListener('keydown', (e) => { if (e.key === 'Enter') save(); });
775
+ box.append(h('div', { class: 'ct-memrow' }, add, h('button', { type: 'button', class: 'btn btn-xs btn-primary', tx: 'city.card.save', on: { click: save } })),
776
+ h('button', { type: 'button', class: 'btn btn-xs btn-quiet', tx: 'city.card.doneEditing', on: { click: () => { memoryEdit = null; paintSide(); } } }));
777
+ return box;
778
+ }
779
+
780
+ function machinePanel(focusId) {
781
+ const v = st.view;
782
+ const box = h('div', { class: 'ct-machines' }, h('div', { class: 'ct-panel-h' }, h('strong', { tx: 'city.machine.title' }), h('span', { class: 'ct-faint small', tx: 'city.machine.limits' })));
783
+ const list = Object.values(v.machines).sort((a, b) => (b.self - a.self) || String(a.joinedAt || '').localeCompare(String(b.joinedAt || '')));
784
+ for (const m of list) {
785
+ const agents = Object.values(v.agents).filter((x) => x.home === m.id);
786
+ const borrowsHere = Object.values(v.borrows).filter((b) => b.to === m.id || b.from === m.id);
787
+ const asks = v.pending.filter((b) => b.to === m.id);
788
+ const card = h('section', { class: 'ct-mcard', dataset: { focus: String(m.id === focusId) }, style: `--c:${m.color}` });
789
+ append(card, [
790
+ h('div', { class: 'ct-mhead' }, h('i', { class: 'ct-hexdot' }), h('strong', { text: m.name }),
791
+ h('span', { class: 'ct-tag', style: `--c:${m.self ? '#FFB531' : m.color}`, text: tr(m.self ? 'city.machine.host' : 'city.machine.friend') }),
792
+ h('span', { class: `ct-online ${m.online ? 'on' : ''}`, text: tr(m.online ? 'city.machine.online' : 'city.machine.offline') })),
793
+ m.via && m.via !== 'local' ? h('div', { class: 'ct-faint small', text: tr(`city.machine.via.${m.via}`) }) : null]);
794
+ const grid = h('dl', { class: 'ct-grid' });
795
+ grid.append(
796
+ h('dt', { tx: 'city.machine.gpu' }), h('dd', { text: m.gpu?.name || tr('city.machine.noGpu') }),
797
+ h('dt', { tx: 'city.machine.vram' }), h('dd', { text: fmtVram(m.gpu?.vramBytes) || '-' }),
798
+ h('dt', { tx: 'city.machine.model' }), h('dd', { text: m.model || '-' }),
799
+ h('dt', { tx: 'city.machine.load' }), h('dd', {}, h('div', { class: 'ct-bar', style: `--v:${Math.round(m.load * 100)}%` }, h('i')), h('span', { class: 'ct-faint small', text: `${Math.round(m.load * 100)}%${m.tps ? ` · ${m.tps} tok/s` : ''}` })),
800
+ h('dt', { tx: 'city.machine.lent' }), h('dd', { text: tr('city.machine.lentValue', { turns: m.lending.turns, active: m.lending.active }) }));
801
+ card.append(grid);
802
+ for (const b of borrowsHere) {
803
+ card.append(h('div', { class: 'ct-borrow' }, h('span', { class: 'ct-gl ct-cable', html: '<svg viewBox="0 0 24 24" class="ico ico-sm"><path d="M4 12h5l2-4 3 8 2-4h4"/></svg>' }),
804
+ h('span', { text: tr('city.borrow.active', { agent: agentName(b.agentId), machine: machineName(b.to) }) }),
805
+ h('span', { class: 'ct-faint small', text: tr('city.borrow.turns', { used: b.used?.turns || 0, limit: b.limit?.turns || '?' }) }),
806
+ h('button', { type: 'button', class: 'btn btn-xs btn-quiet', tx: 'city.borrow.stop', on: { click: () => cmd('city.borrow.stop', { borrowId: b.id }).catch(() => {}) } })));
807
+ }
808
+ for (const b of asks) {
809
+ const mineLender = m.self || st.mode === 'mock';
810
+ card.append(h('div', { class: 'ct-borrow ct-ask' }, h('span', { text: tr('city.borrow.request', { agent: agentName(b.agentId), machine: m.name }) }),
811
+ mineLender ? h('button', { type: 'button', class: 'btn btn-xs btn-primary', tx: 'city.borrow.accept', on: { click: () => cmd('city.borrow.answer', { borrowId: b.id, accept: true }).catch(() => {}) } }) : null,
812
+ mineLender ? h('button', { type: 'button', class: 'btn btn-xs btn-quiet', tx: 'city.borrow.refuse', on: { click: () => cmd('city.borrow.answer', { borrowId: b.id, accept: false }).catch(() => {}) } }) : null));
813
+ }
814
+ const row = h('div', { class: 'ct-avs' });
815
+ for (const a of agents) row.append(h('button', { type: 'button', class: 'ct-avbtn', title: a.name, 'aria-label': a.name, on: { click: () => openSide({ kind: 'agent', id: a.id }) } }, beeAvatar(avatarOf(a), 28, { ring: true })));
816
+ card.append(h('div', { class: 'ct-faint small', tx: 'city.machine.agents' }), row);
817
+ box.append(card);
818
+ }
819
+ box.append(h('button', { type: 'button', class: 'btn btn-xs', tx: 'city.invite', on: { click: () => invite() } }));
820
+ requestAnimationFrame(() => box.querySelector('[data-focus="true"]')?.scrollIntoView({ block: 'nearest' }));
821
+ return box;
822
+ }
823
+
824
+ function roomPanel(id) {
825
+ const v = st.view;
826
+ const r = v.rooms[id] || { id, tools: [], accepts: [] };
827
+ // who is in the room on screen: a friend's agent only once it has walked over the bridge
828
+ const agents = Object.values(v.agents).filter((a) => { const act = scene.actors.get(a.id); return act ? act.place.kind === 'room' && act.place.room === id : a.room === id; });
829
+ const tasks = Object.values(v.tasks).filter((x) => x.room === id && x.status !== 'done');
830
+ const box = h('div', { class: 'ct-roompanel', style: `--c:${ROOM_COLOR[id] || r.color || '#FFB531'}` });
831
+ box.append(
832
+ h('div', { class: 'ct-panel-h' }, h('i', { class: 'ct-hexdot' }), h('strong', { text: roomName(id) })),
833
+ h('p', { class: 'ct-about', text: ROOMS[id] ? tr(`city.room.about.${id}`) : '' }),
834
+ h('div', { class: 'of-k', tx: 'city.roomPanel.rules' }),
835
+ h('div', { class: 'ct-rules' },
836
+ r.requireApproval ? h('span', { class: 'ct-tag ct-warn', tx: 'city.roomPanel.approval' }) : null,
837
+ r.hostOnly ? h('span', { class: 'ct-tag ct-info', tx: 'city.roomPanel.hostOnly' }) : null,
838
+ r.mode ? h('span', { class: 'ct-tag', text: tr(`city.roomPanel.mode.${r.mode}`) }) : null),
839
+ h('div', { class: 'ct-faint small', tx: 'city.roomPanel.tools' }),
840
+ r.tools.length ? h('div', { class: 'ct-tools' }, ...r.tools.map((x) => h('span', { class: 'ct-tool', 'aria-pressed': 'true', text: x }))) : h('div', { class: 'ct-faint small', tx: 'city.roomPanel.noTools' }),
841
+ h('div', { class: 'of-k', tx: 'city.roomPanel.agents' }));
842
+ const row = h('div', { class: 'ct-avs' });
843
+ for (const a of agents) row.append(h('button', { type: 'button', class: 'ct-avbtn ct-avname', on: { click: () => openSide({ kind: 'agent', id: a.id }) } }, beeAvatar(avatarOf(a), 26, { ring: true }), h('span', {}, h('b', { text: a.name }), h('span', { class: 'ct-faint', text: tr(`city.agent.status.${a.status}`) }))));
844
+ if (!agents.length) row.append(h('span', { class: 'ct-faint small', tx: 'city.roomPanel.empty' }));
845
+ box.append(row, h('div', { class: 'of-k', tx: 'city.roomPanel.tasks' }));
846
+ const tl = h('div', { class: 'ct-rtasks' });
847
+ for (const x of tasks) {
848
+ const a = x.assignee && v.agents[x.assignee];
849
+ tl.append(h('div', { class: 'ct-rtask', dataset: { s: x.status } },
850
+ h('div', { class: 'ct-note-t', text: x.title }),
851
+ h('div', { class: 'ct-note-m' }, h('span', { class: 'ct-faint', text: tr(`city.task.status.${x.status}`) }), a ? h('span', { class: 'ct-who' }, beeAvatar(avatarOf(a), 16, { ring: false }), h('span', { text: a.name })) : null,
852
+ x.loops ? h('span', { class: 'ct-faint', text: tr('city.task.loops', { n: x.loops, max: x.maxLoops }) }) : null),
853
+ x.issues?.length ? h('div', { class: 'ct-issues', text: x.issues.slice(0, 2).join(' · ') }) : null,
854
+ h('div', { class: 'ct-acts' },
855
+ x.awaiting ? h('button', { type: 'button', class: 'btn btn-xs btn-primary', tx: 'city.task.approve', on: { click: () => cmd('city.task.approve', { taskId: x.id }).catch(() => {}) } }) : null,
856
+ x.awaiting ? h('button', { type: 'button', class: 'btn btn-xs', tx: 'city.task.reject', on: { click: () => cmd('city.task.reject', { taskId: x.id, note: tr('city.task.rejectNote') }).catch(() => {}) } }) : null,
857
+ x.status === 'blocked' ? h('button', { type: 'button', class: 'btn btn-xs', tx: 'city.task.retry', on: { click: () => cmd('city.task.retry', { taskId: x.id }).catch(() => {}) } }) : null)));
858
+ }
859
+ if (!tasks.length) tl.append(h('span', { class: 'ct-faint small', tx: 'city.roomPanel.noTasks' }));
860
+ box.append(tl, h('button', { type: 'button', class: 'btn btn-xs', tx: 'city.roomPanel.back', on: { click: () => closeSide() } }));
861
+ return box;
862
+ }
863
+
864
+ function chatWith(a) {
865
+ office.setMode('desktop');
866
+ wm.open('worker', a.workerId || a.id);
867
+ }
868
+
869
+ function invite() {
870
+ office.setMode('desktop');
871
+ wm.open('lend');
872
+ }
873
+
874
+ /* ---------- activity feed: short lines from real events ---------- */
875
+ function feed(ev) {
876
+ if (!hud.feed) return;
877
+ const d = ev.data || {};
878
+ const v = viewOf(st.city, st.live);
879
+ const title = (id) => v.tasks[id]?.title || st.city.tasks?.[id]?.title || '';
880
+ let line = null; let tone = '';
881
+ switch (ev.type) {
882
+ case 'city.machine.joined': if (!d.machine?.host) { line = tr('city.feed.machineJoined', { name: d.machine?.name || '' }); tone = 'honey'; } break;
883
+ case 'city.machine.left': line = tr('city.feed.machineLeft', { name: machineName(d.machineId) }); break;
884
+ case 'city.agent.joined': line = tr('city.feed.agentJoined', { name: d.agent?.name || '' }); tone = 'honey'; break;
885
+ case 'city.task.created': line = tr('city.feed.taskCreated', { title: d.task?.title || '' }); break;
886
+ case 'city.task.claimed': line = tr('city.feed.claimed', { agent: v.agents[d.agentId]?.name || d.agentId, title: title(d.taskId) }); break;
887
+ case 'city.task.hop': if (d.hop && d.hop.from !== d.hop.to && d.hop.from) line = tr('city.feed.hop', { title: title(d.task?.id), room: roomName(d.hop.to) }); break;
888
+ case 'city.task.verdict': line = tr(d.passed ? 'city.feed.verdictOk' : 'city.feed.verdictBad', { agent: v.agents[d.agentId]?.name || '', title: title(d.taskId) }); tone = d.passed ? 'ok' : 'bad'; break;
889
+ case 'city.task.done': line = tr('city.feed.done', { title: title(d.taskId) }); tone = 'ok'; break;
890
+ case 'city.task.blocked': line = tr('city.feed.blocked', { title: title(d.taskId) }); tone = 'bad'; break;
891
+ case 'city.borrow.requested': line = tr('city.feed.borrowAsk', { agent: v.agents[d.borrow?.agentId]?.name || '', machine: machineName(d.borrow?.to) }); tone = 'info'; break;
892
+ case 'city.borrow.answered': if (d.accepted) { const b = st.city.borrows?.[d.borrowId]; line = tr('city.feed.borrowStart', { agent: v.agents[b?.agentId]?.name || '', machine: machineName(b?.to) }); tone = 'info'; } break;
893
+ case 'city.borrow.ended': { const b = st.city.borrows?.[d.borrowId]; line = tr('city.feed.borrowEnd', { agent: v.agents[b?.agentId]?.name || '' }); break; }
894
+ case 'city.agent.leveled': if ((d.level || 1) < 2) break; line = tr('city.feed.leveled', { agent: v.agents[d.agentId]?.name || '', n: d.level }); tone = 'honey'; break;
895
+ default: break;
896
+ }
897
+ if (!line) return;
898
+ const li = h('li', { dataset: { tone } }, h('span', { class: 'of-dot' }), h('span', { text: line }));
899
+ hud.feed.prepend(li);
900
+ while (hud.feed.children.length > 5) hud.feed.lastChild.remove();
901
+ if (!reducedMotion() && active) li.animate([{ opacity: 0, transform: 'translateY(-6px)' }, { opacity: 1, transform: 'none' }], { duration: 260, easing: 'ease-out' });
902
+ }
903
+
904
+ /* ---------- keyboard ---------- */
905
+ function onKey(e) {
906
+ if (!active) return;
907
+ if (e.key === 'Escape') {
908
+ if (drag) { cancelDrag(); return; }
909
+ if (side || scene.focus) { closeSide(); scene.fit(); paintRooms(); }
910
+ return;
911
+ }
912
+ const tag = (e.target?.tagName || '').toLowerCase();
913
+ if (tag === 'input' || tag === 'textarea' || tag === 'select' || e.ctrlKey || e.metaKey || e.altKey) return;
914
+ if (e.key === '+' || e.key === '=') scene.zoomAt(1.25, layer.clientWidth / 2, layer.clientHeight / 2);
915
+ else if (e.key === '-') scene.zoomAt(0.8, layer.clientWidth / 2, layer.clientHeight / 2);
916
+ else if (e.key === '0') { closeSide(); scene.fit(); }
917
+ }
918
+
919
+ /* ---------- debug and test hooks ---------- */
920
+ window.hivedeskCity = {
921
+ get mode() { return st.mode; },
922
+ view: () => st.view,
923
+ scene: () => scene,
924
+ openAgent: (id) => openSide({ kind: 'agent', id }),
925
+ openRoom: (id) => openRoom(id),
926
+ openMachines: (id) => { openSide({ kind: 'machine', id }); if (id) scene.focusMachine(id); },
927
+ fit: () => { closeSide(); scene.fit(); },
928
+ focusMachine: (id) => scene.focusMachine(id),
929
+ };
930
+
931
+ /* ---------- glyphs ---------- */
932
+ const CITY_SVG = '<svg viewBox="0 0 24 24" class="ico ico-sm"><path d="M3 20h18"/><path d="M5 20V10l4-2.5V20M9 20V5l5 3v12M14 20v-8l5-2.5V20"/><path d="M11 9.5h1M11 12.5h1M16 13h1M16 16h1M6.6 13h1M6.6 16h1"/></svg>';
933
+ function cityGlyph() { return h('span', { class: 'of-gl', html: CITY_SVG }); }