hivedesk 1.0.1 → 1.0.2

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.
@@ -1,662 +1,662 @@
1
- // Office mode: the crew at work on a refined isometric floor (docs/1.0/DESIGN.md, section 6).
2
- // A full scene that replaces the window desktop (toggle in the top bar), driven by the
3
- // same engine events as every widget. Click a bee to chat, right click for its menu,
4
- // drag a sticky note from Mel's board onto a bee to hand the task over.
5
-
6
- import { h, icon, clear, reducedMotion, append } from '/js/dom.js';
7
- import { S, rev, ui, worker, onEvent, currentJob, jobTasks, roleName } from '/js/store.js';
8
- import { t, onLocale } from '/js/i18n.js';
9
- import { mdLine } from '/js/md.js';
10
- import { setTip } from '/js/tooltip.js';
11
- import * as net from '/js/net.js';
12
- import * as wm from '/js/wm.js';
13
- import * as menu from '/js/menu.js';
14
- import * as act from '/js/actions.js';
15
- import { beeAvatar } from '/js/bees.js';
16
- import { track, STATUS_LABEL, TASK_LABEL } from '/js/widgets/util.js';
17
- import { OfficeScene, levelOf, doneCount, dayPhase } from './scene.js';
18
- import * as audio from './audio.js';
19
- import { openWidget, openPip, pipSupported } from './popout.js';
20
-
21
- const VIEW_KEY = 'hivedesk.view.v2'; // v2: City became the default home in 0.2.0
22
- // What a bee is doing in the scene, read in the current language when shown (office.mode.*).
23
- export const MODES = ['idle', 'sleep', 'type', 'plan', 'wait', 'stuck', 'test', 'read', 'error', 'celebrate', 'paused', 'fly'];
24
- const modeLabel = (m) => (MODES.includes(m) ? t(`office.mode.${m}`) : '');
25
- export const JOB_STATES = ['refining', 'awaiting_brief', 'planning', 'running', 'done', 'failed', 'cancelled'];
26
- const roleOf = (w) => roleName(w) || t('office.worker');
27
- const statusOf = (w, m, st) => (w.paused ? t('office.mode.paused') : modeLabel(m) || STATUS_LABEL[st.status] || st.status);
28
-
29
- let layer;
30
- let scene;
31
- let canvas;
32
- let hud = {};
33
- let hitLayer;
34
- let tip;
35
- let bees = new Map();
36
- let notes = new Map();
37
- let mode = 'desktop';
38
- let hiddenWins = [];
39
- let deskEl;
40
- let seg;
41
- let hourOverride = null;
42
- let shownHoney = null;
43
- let honeyTimer = null;
44
- let drag = null;
45
-
46
- function linkCss() {
47
- if (document.querySelector('link[data-office]')) return;
48
- document.head.append(h('link', { rel: 'stylesheet', href: '/office/office.css', 'data-office': '' }));
49
- }
50
-
51
- function readHourOverride() {
52
- const q = new URLSearchParams(location.search).get('hour');
53
- if (q != null && q !== '' && !Number.isNaN(Number(q))) hourOverride = Math.max(0, Math.min(23.99, Number(q)));
54
- }
55
- const hourNow = () => {
56
- if (hourOverride != null) return hourOverride;
57
- const d = new Date();
58
- return d.getHours() + d.getMinutes() / 60;
59
- };
60
-
61
- /**
62
- * Mounts the Office. Hooks: a segmented toggle in the top bar and a dock entry for the
63
- * mini widget.
64
- * @param {{ desk: HTMLElement, barRight: HTMLElement|null, addDockItem?: Function }} opts
65
- */
66
- export function initOffice({ desk, barRight, addDockItem }) {
67
- linkCss();
68
- readHourOverride();
69
- deskEl = desk;
70
- layer = h('section', { class: 'of-layer', hidden: true, ta: 'office.view.aria' });
71
- canvas = h('canvas', { class: 'of-canvas', 'aria-hidden': 'true' });
72
- hitLayer = h('div', { class: 'of-hits' });
73
- tip = h('div', { class: 'of-tip', role: 'tooltip', id: 'of-tip' });
74
- layer.append(canvas, hitLayer, buildHud(), tip);
75
- desk.append(layer);
76
-
77
- scene = new OfficeScene(canvas, {
78
- getState: S,
79
- reduced: reducedMotion,
80
- hour: hourNow,
81
- onSound: (n) => audio.fx(n),
82
- honeyTarget: () => {
83
- const r = hud.honey?.getBoundingClientRect();
84
- const lr = layer.getBoundingClientRect();
85
- return r ? { x: r.left - lr.left + 18, y: r.top - lr.top + r.height / 2 } : null;
86
- },
87
- onHoney: () => bumpHoney(),
88
- onFrame: (sc) => { syncHits(sc); audio.setLevels(sc.typingCount || 0, sc.flyingCount || 0); },
89
- });
90
- new ResizeObserver(() => { if (mode === 'office') scene.resize(layer.clientWidth, layer.clientHeight); }).observe(layer);
91
-
92
- // the toggle in the top bar
93
- const segOffice = h('button', { type: 'button', dataset: { v: 'office' }, on: { click: () => setMode('office') } }, officeGlyph(), h('span', { tx: 'office.seg.office' }));
94
- const segDesk = h('button', { type: 'button', dataset: { v: 'desktop' }, on: { click: () => setMode('desktop') } }, icon('hive', 'ico-sm'), h('span', { tx: 'office.seg.desktop' }));
95
- seg = h('div', { class: 'of-seg', role: 'group', ta: 'office.seg.aria' }, segOffice, segDesk);
96
- barRight?.prepend(seg);
97
-
98
- const dockBtn = addDockItem?.({
99
- id: 'widget', label: t('office.dock.label'), sub: () => t('office.dock.sub'),
100
- content: h('span', { class: 'dk-hex' }, miniGlyph()),
101
- onClick: () => openWidget(),
102
- menu: () => [
103
- { header: t('office.dock.label') },
104
- { label: t('office.dock.popOut'), icon: 'preview', action: () => openWidget() },
105
- { label: t('office.dock.pip'), icon: 'preview', disabled: !pipSupported(), action: () => openPip() },
106
- { sep: true },
107
- { label: mode === 'office' ? t('office.dock.toDesktop') : t('office.dock.toOffice'), icon: 'hive', action: () => setMode(mode === 'office' ? 'desktop' : 'office') },
108
- ],
109
- });
110
- // the dock keeps the label it got: keep it in the current language
111
- const dockTip = () => { if (!dockBtn?.setAttribute) return; dockBtn.setAttribute('aria-label', t('office.dock.label')); setTip(dockBtn, { title: t('office.dock.label'), help: t('office.dock.sub') }); };
112
- dockBtn?.addEventListener?.('pointerenter', dockTip);
113
- dockBtn?.addEventListener?.('focus', dockTip);
114
- const paintStatic = () => {
115
- segOffice.title = t('office.seg.officeTitle');
116
- segDesk.title = t('office.seg.desktopTitle');
117
- dockTip();
118
- };
119
- paintStatic();
120
- onLocale(() => { paintStatic(); paintSound(); if (hud.segs) hud.segs._key = null; paintHud(); });
121
-
122
- // engine wiring
123
- net.on('hello', () => { scene.reset(); shownHoney = null; paintHud(); });
124
- onEvent((ev) => {
125
- scene.handle(ev);
126
- feed(ev);
127
- if (ev.type === 'job.done' && mode === 'office') banner(ev);
128
- if (/^(brief|job)\./.test(ev.type)) paintHud();
129
- });
130
- track(() => [rev.jobs, rev.tasks, rev.queue, rev.crew, rev.workers, rev.chat, rev.approvals, ui.replay, ui.demo], () => paintHud());
131
- track(() => [rev.crew], () => scene.syncCrew(true));
132
-
133
- document.addEventListener('visibilitychange', () => {
134
- if (mode !== 'office') return;
135
- if (document.hidden) scene.stop(); else scene.start();
136
- });
137
- document.addEventListener('keydown', (e) => {
138
- if (e.key === 'Escape' && drag) cancelDrag();
139
- });
140
-
141
- // City is the default home when it is registered (ui/city/); Office and Desktop stay one click away.
142
- let start = 'city';
143
- try { start = localStorage.getItem(VIEW_KEY) || 'city'; } catch { /* ignore */ }
144
- const q = new URLSearchParams(location.search).get('view');
145
- if (q) start = q;
146
- // wait for the first layout of the windows before hiding them
147
- net.on('hello', once(() => requestAnimationFrame(() => {
148
- if (start === 'office' || views.has(start)) setMode(start, { quiet: true });
149
- })));
150
- paintSeg();
151
- setInterval(() => { if (mode === 'office') paintClock(); }, 20000);
152
- }
153
-
154
- function once(fn) { let done = false; return (...a) => { if (!done) { done = true; fn(...a); } }; }
155
-
156
- export function getMode() { return mode; }
157
-
158
- /* Other full screen views next to Office and Desktop (the City registers here). */
159
- const views = new Map();
160
-
161
- /**
162
- * Adds a view to the toggle. `enter({ quiet })` shows it; `leave({ quiet, done })` hides it and
163
- * calls done when it is gone. `first` puts it at the start of the toggle.
164
- * @param {{ id: string, labelKey: string, titleKey?: string, glyph: () => Node, enter: Function, leave: Function, first?: boolean }} v
165
- */
166
- export function addView(v) {
167
- views.set(v.id, v);
168
- const b = h('button', { type: 'button', dataset: { v: v.id }, tip: v.titleKey, on: { click: () => setMode(v.id) } }, v.glyph(), h('span', { tx: v.labelKey }));
169
- if (v.first) seg.prepend(b); else seg.append(b);
170
- seg.dataset.tour = 'office';
171
- paintSeg();
172
- }
173
-
174
- const isScene = (m) => m === 'office' || views.has(m);
175
-
176
- export function setMode(next, { quiet = false } = {}) {
177
- if (next === mode || !(next === 'desktop' || isScene(next))) return;
178
- const prev = mode;
179
- mode = next;
180
- try { localStorage.setItem(VIEW_KEY, mode); } catch { /* ignore */ }
181
- paintSeg();
182
- if (isScene(next) && !isScene(prev)) {
183
- // tuck the open windows into the dock, and bring them back on the desktop
184
- hiddenWins = wm.list().filter((w) => !w.min).map((w) => w.id);
185
- for (const id of hiddenWins) wm.minimize(id);
186
- deskEl.classList.add('of-on');
187
- }
188
- const toDesk = () => {
189
- if (mode !== 'desktop') return;
190
- deskEl.classList.remove('of-on');
191
- for (const id of hiddenWins) if (wm.get(id)?.min) wm.restore(id);
192
- hiddenWins = [];
193
- };
194
- if (views.has(prev)) views.get(prev).leave({ quiet: quiet || isScene(next), done: toDesk });
195
- if (views.has(next)) { if (prev === 'office') leaveOffice(true, () => {}); views.get(next).enter({ quiet }); return; }
196
- if (mode === 'office') {
197
- layer.hidden = false;
198
- scene.resize(layer.clientWidth, layer.clientHeight);
199
- scene.reset();
200
- scene.start();
201
- audio.setActive(true);
202
- paintHud();
203
- if (!quiet && !reducedMotion()) layer.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 200, easing: 'cubic-bezier(.2,0,0,1)' });
204
- } else if (prev === 'office') leaveOffice(quiet, toDesk);
205
- else toDesk();
206
- }
207
-
208
- function leaveOffice(quiet, after) {
209
- scene.stop();
210
- audio.setActive(false);
211
- hideTip();
212
- const done = () => { layer.hidden = true; after(); };
213
- if (reducedMotion() || quiet) done();
214
- else layer.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 150, easing: 'cubic-bezier(.4,0,1,1)' }).onfinish = done;
215
- }
216
-
217
- function paintSeg() {
218
- if (!seg) return;
219
- for (const b of seg.querySelectorAll('button')) b.setAttribute('aria-pressed', String(b.dataset.v === mode));
220
- }
221
-
222
- /* ---------- HUD ---------- */
223
- function buildHud() {
224
- const xpFill = h('i');
225
- hud.req = h('div', { class: 'of-req' });
226
- hud.xpText = h('span', { class: 'of-xp-t' });
227
- hud.xpLv = h('span', { class: 'of-xp-lv' });
228
- // progress is a segmented timeline: one segment per task, colored by its state
229
- hud.segs = h('span', { class: 'of-tl', 'aria-hidden': 'true' });
230
- hud.xp = h('div', { class: 'of-xp', role: 'progressbar', ta: 'office.hud.progress', 'aria-valuemin': '0', 'aria-valuemax': '100' }, xpFill, hud.segs);
231
- hud.xpFill = xpFill;
232
- hud.state = h('span', { class: 'of-chip' });
233
- // waiting for the user's OK on Mel's brief: one clear way to it
234
- hud.openBrief = h('button', { type: 'button', class: 'btn btn-xs btn-primary of-brief-btn', style: 'justify-self:start', hidden: true, tx: 'office.hud.openBrief', on: { click: () => { setMode('desktop'); wm.open('brief'); } } });
235
- const job = h('div', { class: 'of-card of-job' },
236
- h('div', { class: 'of-row' }, h('span', { class: 'of-k', tx: 'office.hud.currentJob' }), hud.state),
237
- hud.req,
238
- h('div', { class: 'of-row', style: 'gap:10px' }, hud.xpLv, hud.xp),
239
- hud.xpText,
240
- hud.openBrief);
241
-
242
- const doneMark = h('span', { class: 'of-jar', html: CHECK_SVG, 'aria-hidden': 'true' });
243
- hud.honeyN = h('b', { text: '0' });
244
- hud.honeyT = h('span', { class: 'of-faint' });
245
- hud.honey = h('div', { class: 'of-pill of-honey' }, doneMark, hud.honeyN, hud.honeyT);
246
- hud.clock = h('div', { class: 'of-pill of-clock' });
247
- hud.sound = h('button', { type: 'button', class: 'of-ib', on: { click: () => { audio.setAmbient(!audio.ambientOn()); paintSound(); } } });
248
- hud.pop = h('button', { type: 'button', class: 'of-ib', ta: 'office.hud.popOut', on: { click: () => openWidget() } }, miniGlyph());
249
- hud.pip = h('button', { type: 'button', class: 'of-ib', ta: 'office.hud.pipAria', hidden: !pipSupported(), on: { click: () => openPip() } }, pipGlyph());
250
- const stats = h('div', { class: 'of-stats' }, hud.honey, hud.clock, h('div', { class: 'of-pill of-tools' }, hud.sound, hud.pop, hud.pip));
251
-
252
- hud.queue = h('div', { class: 'of-card of-queue' });
253
- hud.feed = h('ol', { class: 'of-card of-feed', ta: 'office.hud.feed', 'aria-live': 'polite' });
254
- hud.banner = h('div', { class: 'of-banner', role: 'status', hidden: true });
255
- hud.empty = h('div', { class: 'of-empty', hidden: true });
256
- paintSound();
257
- return h('div', { class: 'of-hud' }, job, stats, hud.queue, hud.feed, hud.banner, hud.empty);
258
- }
259
-
260
- function paintSound() {
261
- const on = audio.ambientOn();
262
- hud.sound.setAttribute('aria-pressed', String(on));
263
- hud.sound.setAttribute('aria-label', on ? t('office.hud.soundOn') : t('office.hud.soundOff'));
264
- hud.sound.title = on ? t('office.hud.soundOnTitle') : t('office.hud.soundOff');
265
- // the other fixed titles of the HUD, in the current language
266
- hud.honey.title = t('office.hud.honeyTitle');
267
- hud.pop.title = t('office.hud.popOut');
268
- hud.pip.title = t('office.hud.pip');
269
- hud.sound.innerHTML = on
270
- ? '<svg class="ico" viewBox="0 0 24 24"><path d="M4 9.5h3.5L12 5.5v13l-4.5-4H4z"/><path d="M15.5 9a4.2 4.2 0 0 1 0 6M18 6.5a8 8 0 0 1 0 11"/></svg>'
271
- : '<svg class="ico" viewBox="0 0 24 24"><path d="M4 9.5h3.5L12 5.5v13l-4.5-4H4z"/><path d="M16 9.5l5 5M21 9.5l-5 5"/></svg>';
272
- }
273
-
274
- function paintHud() {
275
- if (!hud.req) return;
276
- const s = S();
277
- let j = [...(s.jobs || [])].reverse().find((x) => ['refining', 'awaiting_brief', 'planning', 'running'].includes(x.status)) || currentJob(s);
278
- if (j && scene?.briefWait && ['planning', 'refining'].includes(j.status)) j = { ...j, status: 'awaiting_brief' };
279
- else if (j && scene?.briefWrite && j.status === 'planning') j = { ...j, status: 'refining' };
280
- // job and XP
281
- if (j) {
282
- const tasks = jobTasks(s, j);
283
- // progress is completed tasks of all tasks, nothing weighted; the running task is told in words
284
- const done = tasks.filter((t) => t.status === 'done' || t.status === 'skipped').length;
285
- const runningTasks = tasks.filter((t) => t.status === 'running' || t.status === 'review');
286
- const running = runningTasks.length;
287
- const total = tasks.length;
288
- const pct = j.status === 'done' ? 100 : total ? Math.round((done / total) * 100) : 0;
289
- hud.req.textContent = j.request;
290
- hud.req.title = j.request;
291
- hud.xpFill.style.width = `${pct}%`;
292
- hud.xp.setAttribute('aria-valuenow', String(pct));
293
- hud.xpLv.textContent = `${pct}%`;
294
- paintTimeline(tasks);
295
- if (['refining', 'awaiting_brief', 'planning'].includes(j.status)) hud.xpText.textContent = t(`office.hud.line.${j.status}`);
296
- else {
297
- const progress = t('office.hud.done', { done, total });
298
- let what = running ? nowLine(s, runningTasks[0]) : '';
299
- if (running > 1) what = t('office.hud.more', { what, count: running - 1 });
300
- hud.xpText.textContent = running ? t('office.hud.doneNow', { progress, what }) : progress;
301
- }
302
- hud.state.textContent = JOB_STATES.includes(j.status) ? t(`office.state.${j.status}`) : j.status;
303
- hud.state.dataset.s = j.status;
304
- hud.openBrief.hidden = j.status !== 'awaiting_brief';
305
- } else {
306
- hud.req.textContent = t('office.hud.noJob');
307
- hud.req.title = '';
308
- hud.xpFill.style.width = '0%';
309
- hud.xpLv.textContent = '0%';
310
- hud.xpText.textContent = t('office.hud.noJobHint');
311
- paintTimeline([]);
312
- hud.state.textContent = t('office.state.idle');
313
- hud.state.dataset.s = 'idle';
314
- hud.openBrief.hidden = true;
315
- }
316
- // honey
317
- const honey = doneCount(s);
318
- if (shownHoney == null || honey < shownHoney || reducedMotion() || mode !== 'office') shownHoney = honey;
319
- else if (honey > shownHoney) { clearTimeout(honeyTimer); honeyTimer = setTimeout(() => { shownHoney = doneCount(S()); paintHoney(); }, 1800); }
320
- paintHoney();
321
- paintClock();
322
- // queue, the honest part: one model, workers take turns
323
- clear(hud.queue);
324
- const running = s.queue.running || [];
325
- const waiting = s.queue.waiting || [];
326
- hud.queue.append(h('div', { class: 'of-k', text: t('office.queue.title') }));
327
- const row = h('div', { class: 'of-qrow' });
328
- if (running.length) {
329
- for (const q of running) row.append(h('span', { class: 'of-q of-q-on', title: t('office.queue.hasModel', { name: worker(q.workerId).name }) }, beeAvatar(worker(q.workerId), 26, { ring: true, status: 'thinking' })));
330
- if (running.length === 1) row.append(h('span', { class: 'of-qname' }, h('b', { text: worker(running[0].workerId).name }), h('span', { class: 'of-faint', text: mdLine(s.tasks[running[0].taskId]?.title || '', 80) || t('office.queue.thinking') })));
331
- }
332
- else row.append(h('span', { class: 'of-faint small', text: t('office.queue.free') }));
333
- if (waiting.length) {
334
- row.append(h('span', { class: 'of-qsep', html: '<svg viewBox="0 0 16 16" class="ico ico-sm"><circle cx="8" cy="8" r="6.2"/><path d="M8 4.6V8l2.4 1.6"/></svg>' }));
335
- for (const q of waiting.slice(0, 6)) row.append(h('span', { class: 'of-q', title: t('office.queue.inQueue', { name: worker(q.workerId).name }) }, beeAvatar(worker(q.workerId), 22, { ring: true })));
336
- if (waiting.length > 6) row.append(h('span', { class: 'of-faint small', text: `+${waiting.length - 6}` }));
337
- }
338
- hud.queue.append(row, h('div', { class: 'of-faint tiny', text: (s.brains || []).length > 1 ? t('office.queue.brains', { count: s.brains.length }) : t('office.queue.oneModel') }));
339
- // nothing hired yet / no state yet
340
- hud.empty.hidden = !!(s.crew || []).length;
341
- hud.empty.textContent = ui.hello ? t('office.empty') : t('office.opening');
342
- }
343
-
344
- /** The running task in words: who does what right now, from the worker's real status. */
345
- function nowLine(s, task) {
346
- if (!task) return '';
347
- const w = worker(task.assignee);
348
- const st = s.workers?.[task.assignee] || {};
349
- const what = NOW_KEYS.includes(st.status) ? st.status : task.status === 'review' ? 'review' : 'works';
350
- return t(`office.now.${what}`, { name: w.name, title: mdLine(task.title, 80) });
351
- }
352
- const NOW_KEYS = ['thinking', 'tool', 'queued', 'waiting_approval'];
353
-
354
- function paintClock() {
355
- const hr = hourNow();
356
- const hh = Math.floor(hr); const mm = Math.floor((hr % 1) * 60);
357
- hud.clock.textContent = `${dayPhase(hr)} · ${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}`;
358
- }
359
-
360
- function paintHoney() {
361
- if (hud.honeyN) hud.honeyN.textContent = String(shownHoney ?? 0);
362
- if (hud.honeyT) hud.honeyT.textContent = t('office.hud.tasksDone', { count: shownHoney ?? 0 });
363
- }
364
- function bumpHoney() {
365
- const real = doneCount(S());
366
- shownHoney = Math.min(real, (shownHoney ?? 0) + 1);
367
- paintHoney();
368
- }
369
-
370
- /** The segmented timeline: one segment per task of the job, in order, colored by its state. */
371
- function paintTimeline(tasks) {
372
- if (!hud.segs) return;
373
- const key = tasks.map((x) => `${x.id}:${x.status}`).join('|');
374
- if (hud.segs._key === key) return;
375
- hud.segs._key = key;
376
- clear(hud.segs);
377
- for (const x of tasks) hud.segs.append(h('i', { dataset: { s: x.status }, title: `${mdLine(x.title, 120)}: ${TASK_LABEL[x.status] || x.status}` }));
378
- }
379
-
380
- /* activity feed: short, human lines from real events (tx keys, so a language switch rewrites them) */
381
- function feed(ev) {
382
- if (!hud.feed) return;
383
- const d = ev.data || {};
384
- const s = S();
385
- const name = (id) => worker(id).name;
386
- const title = (task) => mdLine(task.title, 80);
387
- let line = null; let tone = '';
388
- switch (ev.type) {
389
- case 'job.created': line = ['office.feed.jobCreated']; tone = 'honey'; break;
390
- case 'job.planned': line = ['office.feed.jobPlanned', { count: d.tasks?.length || 0 }]; break;
391
- case 'brief.proposed': line = ['office.feed.briefProposed']; tone = 'warn'; break;
392
- case 'brief.approved': line = [d.source === 'original' ? 'office.feed.briefOriginal' : 'office.feed.briefApproved']; break;
393
- case 'task.status': {
394
- const task = s.tasks[d.taskId];
395
- if (!task) break;
396
- if (d.status === 'running') line = ['office.feed.started', { name: name(task.assignee), title: title(task) }];
397
- else if (d.status === 'done') { line = ['office.feed.finished', { name: name(task.assignee), title: title(task) }]; tone = 'ok'; }
398
- else if (d.status === 'failed') { line = ['office.feed.stuck', { name: name(task.assignee), title: title(task) }]; tone = 'bad'; }
399
- break;
400
- }
401
- case 'file.changed': line = [d.op === 'create' ? 'office.feed.fileCreate' : d.op === 'delete' ? 'office.feed.fileDelete' : 'office.feed.fileEdit', { name: name(d.workerId), path: String(d.path || '') }]; break;
402
- case 'approval.requested': line = ['office.feed.approval', { name: name(d.approval?.workerId) }]; tone = 'warn'; break;
403
- case 'qa.report': line = d.passed ? ['office.feed.qaPassed'] : ['office.feed.qaIssues', { count: d.issues?.length || 0 }]; tone = d.passed ? 'ok' : 'bad'; break;
404
- case 'task.updated': if (d.task?.assignee) line = ['office.feed.handed', { name: name(d.task.assignee) }]; break;
405
- case 'crew.hired': if (ui.hello && !d.worker?.builtin) { line = ['office.feed.joined', { name: d.worker?.name || '' }]; tone = 'honey'; } break;
406
- case 'job.done': line = ['office.feed.jobDone']; tone = 'ok'; break;
407
- default: break;
408
- }
409
- if (!line) return;
410
- const li = h('li', { dataset: { tone } }, h('span', { class: 'of-dot' }), h('span', { tx: line[0], txArgs: line[1] }));
411
- // the brief waits for the user's OK: the line opens it
412
- if (ev.type === 'brief.proposed') li.append(h('button', { type: 'button', class: 'btn btn-xs btn-quiet', style: 'margin-left:6px', tx: 'office.hud.openBrief', on: { click: () => { setMode('desktop'); wm.open('brief'); } } }));
413
- hud.feed.prepend(li);
414
- while (hud.feed.children.length > 5) hud.feed.lastChild.remove();
415
- if (!reducedMotion() && mode === 'office') li.animate([{ opacity: 0, transform: 'translateY(-4px)' }, { opacity: 1, transform: 'none' }], { duration: 200, easing: 'cubic-bezier(.2,0,0,1)' });
416
- }
417
-
418
- function banner(ev) {
419
- const b = hud.banner;
420
- clear(b);
421
- // a calm activity toast: a check, the summary and one action
422
- b.append(h('span', { class: 'of-jar of-jar-big', html: CHECK_SVG, 'aria-hidden': 'true' }),
423
- h('div', {}, h('strong', { tx: 'office.banner.title' }), h('div', { class: 'of-faint', text: mdLine(ev.data?.summary || '', 140) || t('office.banner.fallback') })),
424
- h('button', { type: 'button', class: 'btn btn-xs btn-quiet', tx: 'office.banner.preview', on: { click: () => { setMode('desktop'); wm.open('preview'); } } }));
425
- b.hidden = false;
426
- if (!reducedMotion()) b.animate([{ opacity: 0, transform: 'translate(-50%, 6px)' }, { opacity: 1, transform: 'translate(-50%, 0)' }], { duration: 200, easing: 'cubic-bezier(.2,0,0,1)' });
427
- clearTimeout(b._t);
428
- b._t = setTimeout(() => { b.hidden = true; }, 7000);
429
- }
430
-
431
- /* ---------- the DOM layer over the canvas: focus, hover, click, menus, drag ---------- */
432
- function syncHits(sc) {
433
- const s = S();
434
- // bees
435
- const seen = new Set();
436
- for (const hit of sc.hits) {
437
- seen.add(hit.id);
438
- let b = bees.get(hit.id);
439
- if (!b) b = makeBee(hit.id);
440
- const tx = Math.round(hit.x); const ty = Math.round(hit.y);
441
- if (b._x !== tx || b._y !== ty || b._w !== Math.round(hit.w)) {
442
- b._x = tx; b._y = ty; b._w = Math.round(hit.w);
443
- b.style.transform = `translate(${tx}px, ${ty}px)`;
444
- b.style.width = `${Math.round(hit.w)}px`;
445
- b.style.height = `${Math.round(hit.h)}px`;
446
- }
447
- const a = sc.actors.get(hit.id);
448
- const label = beeLabel(hit.id, a, s);
449
- if (b._label !== label) { b._label = label; b.setAttribute('aria-label', label); if (tip.dataset.for === `bee:${hit.id}`) showTip(b, hit.id); }
450
- }
451
- for (const [id, b] of bees) if (!seen.has(id)) { b.remove(); bees.delete(id); }
452
- // notes
453
- const nseen = new Set();
454
- for (const hit of sc.noteHits) {
455
- nseen.add(hit.id);
456
- let n = notes.get(hit.id);
457
- if (!n) n = makeNote(hit.id);
458
- const tx = Math.round(hit.x); const ty = Math.round(hit.y);
459
- if (n._x !== tx || n._y !== ty) {
460
- n._x = tx; n._y = ty;
461
- n.style.transform = `translate(${tx}px, ${ty}px)`;
462
- n.style.width = `${Math.round(hit.w)}px`;
463
- n.style.height = `${Math.round(hit.h)}px`;
464
- }
465
- const task = s.tasks[hit.id];
466
- const label = task ? t('office.note.aria', { title: mdLine(task.title, 120), status: TASK_LABEL[task.status] || task.status, name: worker(task.assignee).name }) : t('office.note.task');
467
- if (n._label !== label) { n._label = label; n.setAttribute('aria-label', label); }
468
- }
469
- for (const [id, n] of notes) if (!nseen.has(id) && !(drag && drag.taskId === id)) { n.remove(); notes.delete(id); }
470
- }
471
-
472
- function beeLabel(id, a, s) {
473
- const w = worker(id);
474
- const st = s.workers[id] || { status: 'idle' };
475
- const task = st.taskId && s.tasks[st.taskId];
476
- const m = a ? (a.seg ? 'fly' : a.mode) : 'idle';
477
- const lv = levelOf(s, id);
478
- const who = lv != null ? t('office.bee.whoLevel', { name: w.name, role: roleOf(w), level: lv }) : t('office.bee.who', { name: w.name, role: roleOf(w) });
479
- const status = statusOf(w, m, st);
480
- return task ? t('office.bee.ariaTask', { who, status, title: mdLine(task.title, 120) }) : t('office.bee.aria', { who, status });
481
- }
482
-
483
- function makeBee(id) {
484
- const b = h('button', { type: 'button', class: 'of-bee', 'aria-describedby': 'of-tip', dataset: { id } });
485
- b.addEventListener('click', () => { if (!drag) wm.open('worker', id); });
486
- b.addEventListener('pointerenter', () => { scene.highlight = id; showTip(b, id); });
487
- b.addEventListener('pointerleave', () => { if (scene.highlight === id) scene.highlight = null; hideTip(); });
488
- b.addEventListener('focus', () => { scene.highlight = id; showTip(b, id); });
489
- b.addEventListener('blur', () => { if (scene.highlight === id) scene.highlight = null; hideTip(); });
490
- menu.provide(b, () => beeMenu(id));
491
- hitLayer.append(b);
492
- bees.set(id, b);
493
- return b;
494
- }
495
-
496
- function beeMenu(id) {
497
- const w = worker(id);
498
- const s = S();
499
- const st = s.workers[id] || {};
500
- const mine = Object.values(s.tasks).filter((x) => x.assignee === id);
501
- const retryable = mine.filter((x) => ['failed', 'blocked'].includes(x.status)).pop() || (st.taskId && s.tasks[st.taskId]);
502
- const lv = levelOf(s, id);
503
- return [
504
- { header: lv != null ? t('office.menu.headerLevel', { name: w.name, role: roleOf(w), level: lv }) : t('office.menu.header', { name: w.name, role: roleOf(w) }) },
505
- { label: t('office.menu.chat', { name: w.name }), icon: 'chat', action: () => wm.open('worker', id) },
506
- { label: w.paused ? t('office.menu.resume') : t('office.menu.pause'), icon: w.paused ? 'arrow' : 'stop', disabled: !!ui.replay, action: () => act.pauseWorker(id, !w.paused) },
507
- { label: retryable ? t('office.menu.retryTask', { title: mdLine(retryable.title, 60) }) : t('office.menu.retryNone'), icon: 'replay', disabled: !retryable || !!ui.replay, action: () => act.retryTask(retryable.id) },
508
- { label: t('office.menu.files'), icon: 'folder', action: () => { setMode('desktop'); wm.open('files'); } },
509
- ];
510
- }
511
-
512
- function makeNote(id) {
513
- const n = h('button', { type: 'button', class: 'of-note', 'aria-describedby': 'of-tip', dataset: { id } });
514
- n.addEventListener('pointerenter', () => { scene.highlight = id; showNoteTip(n, id); });
515
- n.addEventListener('pointerleave', () => { if (scene.highlight === id) scene.highlight = null; hideTip(); });
516
- n.addEventListener('focus', () => { scene.highlight = id; showNoteTip(n, id); });
517
- n.addEventListener('blur', () => { if (scene.highlight === id) scene.highlight = null; hideTip(); });
518
- n.addEventListener('click', (e) => {
519
- if (n._dragged) { n._dragged = false; return; }
520
- const r = n.getBoundingClientRect();
521
- menu.open({ x: e.clientX || r.left + 10, y: e.clientY || r.bottom, items: noteMenu(id) });
522
- });
523
- n.addEventListener('pointerdown', (e) => startDrag(e, n, id));
524
- menu.provide(n, () => noteMenu(id));
525
- hitLayer.append(n);
526
- notes.set(id, n);
527
- return n;
528
- }
529
-
530
- function noteMenu(id) {
531
- const s = S();
532
- const task = s.tasks[id];
533
- if (!task) return null;
534
- const off = !!ui.replay || task.status === 'done';
535
- return [
536
- { header: mdLine(task.title, 60) },
537
- { label: t('office.menu.handTo'), icon: 'hire', disabled: off, items: s.crew.filter((w) => w.id !== task.assignee).map((w) => ({ label: t('office.menu.handToWho', { name: w.name, role: roleOf(w) }), iconEl: beeAvatar(w, 18, { ring: false }), action: () => reassign(id, w.id) })) },
538
- { label: t('office.menu.retry'), icon: 'replay', disabled: !!ui.replay || !['failed', 'blocked', 'done', 'skipped'].includes(task.status), action: () => act.retryTask(id) },
539
- { label: t('office.menu.cancel'), icon: 'x', danger: true, disabled: !!ui.replay || ['done', 'skipped'].includes(task.status), action: () => act.cancelTask(id) },
540
- ];
541
- }
542
-
543
- function reassign(taskId, workerId) {
544
- const task = S().tasks[taskId];
545
- if (!task || task.assignee === workerId) return;
546
- act.reassignTask(taskId, workerId);
547
- }
548
-
549
- function startDrag(e, el, id) {
550
- if (e.button !== 0 || ui.replay) return;
551
- const task = S().tasks[id];
552
- if (!task || task.status === 'done') return;
553
- const x0 = e.clientX; const y0 = e.clientY;
554
- let ghost = null;
555
- const move = (ev) => {
556
- if (!drag && Math.hypot(ev.clientX - x0, ev.clientY - y0) < 6) return;
557
- if (!drag) {
558
- drag = { taskId: id, el };
559
- scene.dragTask = id;
560
- ghost = h('div', { class: 'of-drag', 'aria-hidden': 'true' }, h('i', { style: `background:${worker(task.assignee).color}` }), h('span', { text: mdLine(task.title, 60) }));
561
- layer.append(ghost);
562
- layer.classList.add('of-dragging');
563
- hideTip();
564
- }
565
- const lr = layer.getBoundingClientRect();
566
- ghost.style.transform = `translate(${ev.clientX - lr.left + 8}px, ${ev.clientY - lr.top + 8}px) rotate(-4deg)`;
567
- const over = beeAt(ev.clientX, ev.clientY);
568
- scene.highlight = over || null;
569
- drag.over = over;
570
- };
571
- const up = () => {
572
- removeEventListener('pointermove', move);
573
- removeEventListener('pointerup', up);
574
- removeEventListener('pointercancel', up);
575
- if (!drag) return;
576
- el._dragged = true;
577
- const target = drag.over;
578
- ghost?.remove();
579
- layer.classList.remove('of-dragging');
580
- scene.dragTask = null;
581
- scene.highlight = null;
582
- drag = null;
583
- if (target) reassign(id, target);
584
- };
585
- addEventListener('pointermove', move);
586
- addEventListener('pointerup', up);
587
- addEventListener('pointercancel', up);
588
- }
589
-
590
- function cancelDrag() {
591
- layer.querySelector('.of-drag')?.remove();
592
- layer.classList.remove('of-dragging');
593
- scene.dragTask = null;
594
- scene.highlight = null;
595
- drag = null;
596
- }
597
-
598
- function beeAt(x, y) {
599
- for (const [id, b] of bees) {
600
- const r = b.getBoundingClientRect();
601
- if (x >= r.left - 6 && x <= r.right + 6 && y >= r.top - 6 && y <= r.bottom + 6) return id;
602
- }
603
- return null;
604
- }
605
-
606
- function showTip(el, id) {
607
- const s = S();
608
- const w = worker(id);
609
- const a = scene.actors.get(id);
610
- const st = s.workers[id] || { status: 'idle' };
611
- const task = st.taskId && s.tasks[st.taskId];
612
- const m = a ? (a.seg ? 'fly' : a.mode) : 'idle';
613
- const lastTask = task || Object.values(s.tasks).filter((x) => x.assignee === id && x.status === 'running').pop();
614
- const done = Object.values(s.tasks).filter((x) => x.assignee === id && x.status === 'done').length;
615
- const lv = levelOf(s, id);
616
- clear(tip);
617
- tip.append(
618
- h('div', { class: 'of-tip-h' }, beeAvatar(w, 30, { ring: true }), h('div', {}, h('strong', { text: w.name }), h('div', { class: 'of-faint', text: roleOf(w) })), lv != null ? h('span', { class: 'of-lv', text: t('office.level', { level: lv }) }) : null),
619
- h('div', { class: 'of-tip-r' }, h('span', { class: 'of-faint', tx: 'office.tip.status' }), h('span', { text: statusOf(w, m, st) })),
620
- h('div', { class: 'of-tip-r' }, h('span', { class: 'of-faint', tx: 'office.tip.task' }), h('span', { text: lastTask ? mdLine(lastTask.title, 80) : t('office.tip.none') })),
621
- h('div', { class: 'of-tip-r' }, h('span', { class: 'of-faint', tx: 'office.tip.done' }), h('span', { text: t('office.tip.doneCount', { count: done }) })),
622
- h('div', { class: 'of-tip-f', tx: 'office.tip.foot' }));
623
- tip.dataset.for = `bee:${id}`;
624
- place(el);
625
- }
626
-
627
- function showNoteTip(el, id) {
628
- const s = S();
629
- const task = s.tasks[id];
630
- if (!task) return;
631
- clear(tip);
632
- append(tip, [h('div', { class: 'of-tip-h' }, h('div', {}, h('strong', { text: mdLine(task.title, 120) }), h('div', { class: 'of-faint', text: t('office.tip.noteMeta', { status: TASK_LABEL[task.status] || task.status, name: worker(task.assignee).name }) }))),
633
- task.detail ? h('div', { class: 'of-tip-d', text: mdLine(task.detail, 180) }) : null,
634
- h('div', { class: 'of-tip-f', tx: task.status === 'done' ? 'office.tip.noteDone' : 'office.tip.noteFoot' })]);
635
- tip.dataset.for = `note:${id}`;
636
- place(el);
637
- }
638
-
639
- function place(el) {
640
- const r = el.getBoundingClientRect();
641
- const lr = layer.getBoundingClientRect();
642
- tip.classList.add('on');
643
- const tr = tip.getBoundingClientRect();
644
- let x = r.left - lr.left + r.width / 2 - tr.width / 2;
645
- let y = r.top - lr.top - tr.height - 10;
646
- if (y < 8) y = r.bottom - lr.top + 10;
647
- x = Math.max(8, Math.min(lr.width - tr.width - 8, x));
648
- tip.style.transform = `translate(${Math.round(x)}px, ${Math.round(y)}px)`;
649
- }
650
- function hideTip() { tip?.classList.remove('on'); if (tip) tip.dataset.for = ''; }
651
-
652
- /* ---------- glyphs ---------- */
653
- function officeGlyph() {
654
- return h('span', { class: 'of-gl', html: '<svg viewBox="0 0 24 24" class="ico ico-sm"><path d="M12 3 21 8v8l-9 5-9-5V8z"/><path d="M3 8l9 5 9-5M12 13v8"/></svg>' });
655
- }
656
- function miniGlyph() {
657
- return h('span', { class: 'of-gl', html: '<svg viewBox="0 0 24 24" class="ico"><rect x="3.5" y="4.5" width="17" height="15" rx="2.5"/><rect x="11.5" y="11.5" width="7" height="6" rx="1.2"/></svg>' });
658
- }
659
- function pipGlyph() {
660
- return h('span', { class: 'of-gl', html: '<svg viewBox="0 0 24 24" class="ico"><rect x="3.5" y="5" width="17" height="14" rx="2.5"/><path d="M13 12.5h5.5v4.5H13z"/><path d="M7 9l3 3M7 9h2.6M7 9v2.6"/></svg>' });
661
- }
662
- const CHECK_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="8.5"/><path d="M8.2 12.2l2.6 2.6 5-5.2"/></svg>';
1
+ // Office mode: the crew at work on a refined isometric floor (docs/1.0/DESIGN.md, section 6).
2
+ // A full scene that replaces the window desktop (toggle in the top bar), driven by the
3
+ // same engine events as every widget. Click a bee to chat, right click for its menu,
4
+ // drag a sticky note from Mel's board onto a bee to hand the task over.
5
+
6
+ import { h, icon, clear, reducedMotion, append } from '/js/dom.js';
7
+ import { S, rev, ui, worker, onEvent, currentJob, jobTasks, roleName } from '/js/store.js';
8
+ import { t, onLocale } from '/js/i18n.js';
9
+ import { mdLine } from '/js/md.js';
10
+ import { setTip } from '/js/tooltip.js';
11
+ import * as net from '/js/net.js';
12
+ import * as wm from '/js/wm.js';
13
+ import * as menu from '/js/menu.js';
14
+ import * as act from '/js/actions.js';
15
+ import { beeAvatar } from '/js/bees.js';
16
+ import { track, STATUS_LABEL, TASK_LABEL } from '/js/widgets/util.js';
17
+ import { OfficeScene, levelOf, doneCount, dayPhase } from './scene.js';
18
+ import * as audio from './audio.js';
19
+ import { openWidget, openPip, pipSupported } from './popout.js';
20
+
21
+ const VIEW_KEY = 'hivedesk.view.v2'; // v2: City became the default home in 0.2.0
22
+ // What a bee is doing in the scene, read in the current language when shown (office.mode.*).
23
+ export const MODES = ['idle', 'sleep', 'type', 'plan', 'wait', 'stuck', 'test', 'read', 'error', 'celebrate', 'paused', 'fly'];
24
+ const modeLabel = (m) => (MODES.includes(m) ? t(`office.mode.${m}`) : '');
25
+ export const JOB_STATES = ['refining', 'awaiting_brief', 'planning', 'running', 'done', 'failed', 'cancelled'];
26
+ const roleOf = (w) => roleName(w) || t('office.worker');
27
+ const statusOf = (w, m, st) => (w.paused ? t('office.mode.paused') : modeLabel(m) || STATUS_LABEL[st.status] || st.status);
28
+
29
+ let layer;
30
+ let scene;
31
+ let canvas;
32
+ let hud = {};
33
+ let hitLayer;
34
+ let tip;
35
+ let bees = new Map();
36
+ let notes = new Map();
37
+ let mode = 'desktop';
38
+ let hiddenWins = [];
39
+ let deskEl;
40
+ let seg;
41
+ let hourOverride = null;
42
+ let shownHoney = null;
43
+ let honeyTimer = null;
44
+ let drag = null;
45
+
46
+ function linkCss() {
47
+ if (document.querySelector('link[data-office]')) return;
48
+ document.head.append(h('link', { rel: 'stylesheet', href: '/office/office.css', 'data-office': '' }));
49
+ }
50
+
51
+ function readHourOverride() {
52
+ const q = new URLSearchParams(location.search).get('hour');
53
+ if (q != null && q !== '' && !Number.isNaN(Number(q))) hourOverride = Math.max(0, Math.min(23.99, Number(q)));
54
+ }
55
+ const hourNow = () => {
56
+ if (hourOverride != null) return hourOverride;
57
+ const d = new Date();
58
+ return d.getHours() + d.getMinutes() / 60;
59
+ };
60
+
61
+ /**
62
+ * Mounts the Office. Hooks: a segmented toggle in the top bar and a dock entry for the
63
+ * mini widget.
64
+ * @param {{ desk: HTMLElement, barRight: HTMLElement|null, addDockItem?: Function }} opts
65
+ */
66
+ export function initOffice({ desk, barRight, addDockItem }) {
67
+ linkCss();
68
+ readHourOverride();
69
+ deskEl = desk;
70
+ layer = h('section', { class: 'of-layer', hidden: true, ta: 'office.view.aria' });
71
+ canvas = h('canvas', { class: 'of-canvas', 'aria-hidden': 'true' });
72
+ hitLayer = h('div', { class: 'of-hits' });
73
+ tip = h('div', { class: 'of-tip', role: 'tooltip', id: 'of-tip' });
74
+ layer.append(canvas, hitLayer, buildHud(), tip);
75
+ desk.append(layer);
76
+
77
+ scene = new OfficeScene(canvas, {
78
+ getState: S,
79
+ reduced: reducedMotion,
80
+ hour: hourNow,
81
+ onSound: (n) => audio.fx(n),
82
+ honeyTarget: () => {
83
+ const r = hud.honey?.getBoundingClientRect();
84
+ const lr = layer.getBoundingClientRect();
85
+ return r ? { x: r.left - lr.left + 18, y: r.top - lr.top + r.height / 2 } : null;
86
+ },
87
+ onHoney: () => bumpHoney(),
88
+ onFrame: (sc) => { syncHits(sc); audio.setLevels(sc.typingCount || 0, sc.flyingCount || 0); },
89
+ });
90
+ new ResizeObserver(() => { if (mode === 'office') scene.resize(layer.clientWidth, layer.clientHeight); }).observe(layer);
91
+
92
+ // the toggle in the top bar
93
+ const segOffice = h('button', { type: 'button', dataset: { v: 'office' }, on: { click: () => setMode('office') } }, officeGlyph(), h('span', { tx: 'office.seg.office' }));
94
+ const segDesk = h('button', { type: 'button', dataset: { v: 'desktop' }, on: { click: () => setMode('desktop') } }, icon('hive', 'ico-sm'), h('span', { tx: 'office.seg.desktop' }));
95
+ seg = h('div', { class: 'of-seg', role: 'group', ta: 'office.seg.aria' }, segOffice, segDesk);
96
+ barRight?.prepend(seg);
97
+
98
+ const dockBtn = addDockItem?.({
99
+ id: 'widget', label: t('office.dock.label'), sub: () => t('office.dock.sub'),
100
+ content: h('span', { class: 'dk-hex' }, miniGlyph()),
101
+ onClick: () => openWidget(),
102
+ menu: () => [
103
+ { header: t('office.dock.label') },
104
+ { label: t('office.dock.popOut'), icon: 'preview', action: () => openWidget() },
105
+ { label: t('office.dock.pip'), icon: 'preview', disabled: !pipSupported(), action: () => openPip() },
106
+ { sep: true },
107
+ { label: mode === 'office' ? t('office.dock.toDesktop') : t('office.dock.toOffice'), icon: 'hive', action: () => setMode(mode === 'office' ? 'desktop' : 'office') },
108
+ ],
109
+ });
110
+ // the dock keeps the label it got: keep it in the current language
111
+ const dockTip = () => { if (!dockBtn?.setAttribute) return; dockBtn.setAttribute('aria-label', t('office.dock.label')); setTip(dockBtn, { title: t('office.dock.label'), help: t('office.dock.sub') }); };
112
+ dockBtn?.addEventListener?.('pointerenter', dockTip);
113
+ dockBtn?.addEventListener?.('focus', dockTip);
114
+ const paintStatic = () => {
115
+ segOffice.title = t('office.seg.officeTitle');
116
+ segDesk.title = t('office.seg.desktopTitle');
117
+ dockTip();
118
+ };
119
+ paintStatic();
120
+ onLocale(() => { paintStatic(); paintSound(); if (hud.segs) hud.segs._key = null; paintHud(); });
121
+
122
+ // engine wiring
123
+ net.on('hello', () => { scene.reset(); shownHoney = null; paintHud(); });
124
+ onEvent((ev) => {
125
+ scene.handle(ev);
126
+ feed(ev);
127
+ if (ev.type === 'job.done' && mode === 'office') banner(ev);
128
+ if (/^(brief|job)\./.test(ev.type)) paintHud();
129
+ });
130
+ track(() => [rev.jobs, rev.tasks, rev.queue, rev.crew, rev.workers, rev.chat, rev.approvals, ui.replay, ui.demo], () => paintHud());
131
+ track(() => [rev.crew], () => scene.syncCrew(true));
132
+
133
+ document.addEventListener('visibilitychange', () => {
134
+ if (mode !== 'office') return;
135
+ if (document.hidden) scene.stop(); else scene.start();
136
+ });
137
+ document.addEventListener('keydown', (e) => {
138
+ if (e.key === 'Escape' && drag) cancelDrag();
139
+ });
140
+
141
+ // City is the default home when it is registered (ui/city/); Office and Desktop stay one click away.
142
+ let start = 'city';
143
+ try { start = localStorage.getItem(VIEW_KEY) || 'city'; } catch { /* ignore */ }
144
+ const q = new URLSearchParams(location.search).get('view');
145
+ if (q) start = q;
146
+ // wait for the first layout of the windows before hiding them
147
+ net.on('hello', once(() => requestAnimationFrame(() => {
148
+ if (start === 'office' || views.has(start)) setMode(start, { quiet: true });
149
+ })));
150
+ paintSeg();
151
+ setInterval(() => { if (mode === 'office') paintClock(); }, 20000);
152
+ }
153
+
154
+ function once(fn) { let done = false; return (...a) => { if (!done) { done = true; fn(...a); } }; }
155
+
156
+ export function getMode() { return mode; }
157
+
158
+ /* Other full screen views next to Office and Desktop (the City registers here). */
159
+ const views = new Map();
160
+
161
+ /**
162
+ * Adds a view to the toggle. `enter({ quiet })` shows it; `leave({ quiet, done })` hides it and
163
+ * calls done when it is gone. `first` puts it at the start of the toggle.
164
+ * @param {{ id: string, labelKey: string, titleKey?: string, glyph: () => Node, enter: Function, leave: Function, first?: boolean }} v
165
+ */
166
+ export function addView(v) {
167
+ views.set(v.id, v);
168
+ const b = h('button', { type: 'button', dataset: { v: v.id }, tip: v.titleKey, on: { click: () => setMode(v.id) } }, v.glyph(), h('span', { tx: v.labelKey }));
169
+ if (v.first) seg.prepend(b); else seg.append(b);
170
+ seg.dataset.tour = 'office';
171
+ paintSeg();
172
+ }
173
+
174
+ const isScene = (m) => m === 'office' || views.has(m);
175
+
176
+ export function setMode(next, { quiet = false } = {}) {
177
+ if (next === mode || !(next === 'desktop' || isScene(next))) return;
178
+ const prev = mode;
179
+ mode = next;
180
+ try { localStorage.setItem(VIEW_KEY, mode); } catch { /* ignore */ }
181
+ paintSeg();
182
+ if (isScene(next) && !isScene(prev)) {
183
+ // tuck the open windows into the dock, and bring them back on the desktop
184
+ hiddenWins = wm.list().filter((w) => !w.min).map((w) => w.id);
185
+ for (const id of hiddenWins) wm.minimize(id);
186
+ deskEl.classList.add('of-on');
187
+ }
188
+ const toDesk = () => {
189
+ if (mode !== 'desktop') return;
190
+ deskEl.classList.remove('of-on');
191
+ for (const id of hiddenWins) if (wm.get(id)?.min) wm.restore(id);
192
+ hiddenWins = [];
193
+ };
194
+ if (views.has(prev)) views.get(prev).leave({ quiet: quiet || isScene(next), done: toDesk });
195
+ if (views.has(next)) { if (prev === 'office') leaveOffice(true, () => {}); views.get(next).enter({ quiet }); return; }
196
+ if (mode === 'office') {
197
+ layer.hidden = false;
198
+ scene.resize(layer.clientWidth, layer.clientHeight);
199
+ scene.reset();
200
+ scene.start();
201
+ audio.setActive(true);
202
+ paintHud();
203
+ if (!quiet && !reducedMotion()) layer.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 200, easing: 'cubic-bezier(.2,0,0,1)' });
204
+ } else if (prev === 'office') leaveOffice(quiet, toDesk);
205
+ else toDesk();
206
+ }
207
+
208
+ function leaveOffice(quiet, after) {
209
+ scene.stop();
210
+ audio.setActive(false);
211
+ hideTip();
212
+ const done = () => { layer.hidden = true; after(); };
213
+ if (reducedMotion() || quiet) done();
214
+ else layer.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 150, easing: 'cubic-bezier(.4,0,1,1)' }).onfinish = done;
215
+ }
216
+
217
+ function paintSeg() {
218
+ if (!seg) return;
219
+ for (const b of seg.querySelectorAll('button')) b.setAttribute('aria-pressed', String(b.dataset.v === mode));
220
+ }
221
+
222
+ /* ---------- HUD ---------- */
223
+ function buildHud() {
224
+ const xpFill = h('i');
225
+ hud.req = h('div', { class: 'of-req' });
226
+ hud.xpText = h('span', { class: 'of-xp-t' });
227
+ hud.xpLv = h('span', { class: 'of-xp-lv' });
228
+ // progress is a segmented timeline: one segment per task, colored by its state
229
+ hud.segs = h('span', { class: 'of-tl', 'aria-hidden': 'true' });
230
+ hud.xp = h('div', { class: 'of-xp', role: 'progressbar', ta: 'office.hud.progress', 'aria-valuemin': '0', 'aria-valuemax': '100' }, xpFill, hud.segs);
231
+ hud.xpFill = xpFill;
232
+ hud.state = h('span', { class: 'of-chip' });
233
+ // waiting for the user's OK on Mel's brief: one clear way to it
234
+ hud.openBrief = h('button', { type: 'button', class: 'btn btn-xs btn-primary of-brief-btn', style: 'justify-self:start', hidden: true, tx: 'office.hud.openBrief', on: { click: () => { setMode('desktop'); wm.open('brief'); } } });
235
+ const job = h('div', { class: 'of-card of-job' },
236
+ h('div', { class: 'of-row' }, h('span', { class: 'of-k', tx: 'office.hud.currentJob' }), hud.state),
237
+ hud.req,
238
+ h('div', { class: 'of-row', style: 'gap:10px' }, hud.xpLv, hud.xp),
239
+ hud.xpText,
240
+ hud.openBrief);
241
+
242
+ const doneMark = h('span', { class: 'of-jar', html: CHECK_SVG, 'aria-hidden': 'true' });
243
+ hud.honeyN = h('b', { text: '0' });
244
+ hud.honeyT = h('span', { class: 'of-faint' });
245
+ hud.honey = h('div', { class: 'of-pill of-honey' }, doneMark, hud.honeyN, hud.honeyT);
246
+ hud.clock = h('div', { class: 'of-pill of-clock' });
247
+ hud.sound = h('button', { type: 'button', class: 'of-ib', on: { click: () => { audio.setAmbient(!audio.ambientOn()); paintSound(); } } });
248
+ hud.pop = h('button', { type: 'button', class: 'of-ib', ta: 'office.hud.popOut', on: { click: () => openWidget() } }, miniGlyph());
249
+ hud.pip = h('button', { type: 'button', class: 'of-ib', ta: 'office.hud.pipAria', hidden: !pipSupported(), on: { click: () => openPip() } }, pipGlyph());
250
+ const stats = h('div', { class: 'of-stats' }, hud.honey, hud.clock, h('div', { class: 'of-pill of-tools' }, hud.sound, hud.pop, hud.pip));
251
+
252
+ hud.queue = h('div', { class: 'of-card of-queue' });
253
+ hud.feed = h('ol', { class: 'of-card of-feed', ta: 'office.hud.feed', 'aria-live': 'polite' });
254
+ hud.banner = h('div', { class: 'of-banner', role: 'status', hidden: true });
255
+ hud.empty = h('div', { class: 'of-empty', hidden: true });
256
+ paintSound();
257
+ return h('div', { class: 'of-hud' }, job, stats, hud.queue, hud.feed, hud.banner, hud.empty);
258
+ }
259
+
260
+ function paintSound() {
261
+ const on = audio.ambientOn();
262
+ hud.sound.setAttribute('aria-pressed', String(on));
263
+ hud.sound.setAttribute('aria-label', on ? t('office.hud.soundOn') : t('office.hud.soundOff'));
264
+ hud.sound.title = on ? t('office.hud.soundOnTitle') : t('office.hud.soundOff');
265
+ // the other fixed titles of the HUD, in the current language
266
+ hud.honey.title = t('office.hud.honeyTitle');
267
+ hud.pop.title = t('office.hud.popOut');
268
+ hud.pip.title = t('office.hud.pip');
269
+ hud.sound.innerHTML = on
270
+ ? '<svg class="ico" viewBox="0 0 24 24"><path d="M4 9.5h3.5L12 5.5v13l-4.5-4H4z"/><path d="M15.5 9a4.2 4.2 0 0 1 0 6M18 6.5a8 8 0 0 1 0 11"/></svg>'
271
+ : '<svg class="ico" viewBox="0 0 24 24"><path d="M4 9.5h3.5L12 5.5v13l-4.5-4H4z"/><path d="M16 9.5l5 5M21 9.5l-5 5"/></svg>';
272
+ }
273
+
274
+ function paintHud() {
275
+ if (!hud.req) return;
276
+ const s = S();
277
+ let j = [...(s.jobs || [])].reverse().find((x) => ['refining', 'awaiting_brief', 'planning', 'running'].includes(x.status)) || currentJob(s);
278
+ if (j && scene?.briefWait && ['planning', 'refining'].includes(j.status)) j = { ...j, status: 'awaiting_brief' };
279
+ else if (j && scene?.briefWrite && j.status === 'planning') j = { ...j, status: 'refining' };
280
+ // job and XP
281
+ if (j) {
282
+ const tasks = jobTasks(s, j);
283
+ // progress is completed tasks of all tasks, nothing weighted; the running task is told in words
284
+ const done = tasks.filter((t) => t.status === 'done' || t.status === 'skipped').length;
285
+ const runningTasks = tasks.filter((t) => t.status === 'running' || t.status === 'review');
286
+ const running = runningTasks.length;
287
+ const total = tasks.length;
288
+ const pct = j.status === 'done' ? 100 : total ? Math.round((done / total) * 100) : 0;
289
+ hud.req.textContent = j.request;
290
+ hud.req.title = j.request;
291
+ hud.xpFill.style.width = `${pct}%`;
292
+ hud.xp.setAttribute('aria-valuenow', String(pct));
293
+ hud.xpLv.textContent = `${pct}%`;
294
+ paintTimeline(tasks);
295
+ if (['refining', 'awaiting_brief', 'planning'].includes(j.status)) hud.xpText.textContent = t(`office.hud.line.${j.status}`);
296
+ else {
297
+ const progress = t('office.hud.done', { done, total });
298
+ let what = running ? nowLine(s, runningTasks[0]) : '';
299
+ if (running > 1) what = t('office.hud.more', { what, count: running - 1 });
300
+ hud.xpText.textContent = running ? t('office.hud.doneNow', { progress, what }) : progress;
301
+ }
302
+ hud.state.textContent = JOB_STATES.includes(j.status) ? t(`office.state.${j.status}`) : j.status;
303
+ hud.state.dataset.s = j.status;
304
+ hud.openBrief.hidden = j.status !== 'awaiting_brief';
305
+ } else {
306
+ hud.req.textContent = t('office.hud.noJob');
307
+ hud.req.title = '';
308
+ hud.xpFill.style.width = '0%';
309
+ hud.xpLv.textContent = '0%';
310
+ hud.xpText.textContent = t('office.hud.noJobHint');
311
+ paintTimeline([]);
312
+ hud.state.textContent = t('office.state.idle');
313
+ hud.state.dataset.s = 'idle';
314
+ hud.openBrief.hidden = true;
315
+ }
316
+ // honey
317
+ const honey = doneCount(s);
318
+ if (shownHoney == null || honey < shownHoney || reducedMotion() || mode !== 'office') shownHoney = honey;
319
+ else if (honey > shownHoney) { clearTimeout(honeyTimer); honeyTimer = setTimeout(() => { shownHoney = doneCount(S()); paintHoney(); }, 1800); }
320
+ paintHoney();
321
+ paintClock();
322
+ // queue, the honest part: one model, workers take turns
323
+ clear(hud.queue);
324
+ const running = s.queue.running || [];
325
+ const waiting = s.queue.waiting || [];
326
+ hud.queue.append(h('div', { class: 'of-k', text: t('office.queue.title') }));
327
+ const row = h('div', { class: 'of-qrow' });
328
+ if (running.length) {
329
+ for (const q of running) row.append(h('span', { class: 'of-q of-q-on', title: t('office.queue.hasModel', { name: worker(q.workerId).name }) }, beeAvatar(worker(q.workerId), 26, { ring: true, status: 'thinking' })));
330
+ if (running.length === 1) row.append(h('span', { class: 'of-qname' }, h('b', { text: worker(running[0].workerId).name }), h('span', { class: 'of-faint', text: mdLine(s.tasks[running[0].taskId]?.title || '', 80) || t('office.queue.thinking') })));
331
+ }
332
+ else row.append(h('span', { class: 'of-faint small', text: t('office.queue.free') }));
333
+ if (waiting.length) {
334
+ row.append(h('span', { class: 'of-qsep', html: '<svg viewBox="0 0 16 16" class="ico ico-sm"><circle cx="8" cy="8" r="6.2"/><path d="M8 4.6V8l2.4 1.6"/></svg>' }));
335
+ for (const q of waiting.slice(0, 6)) row.append(h('span', { class: 'of-q', title: t('office.queue.inQueue', { name: worker(q.workerId).name }) }, beeAvatar(worker(q.workerId), 22, { ring: true })));
336
+ if (waiting.length > 6) row.append(h('span', { class: 'of-faint small', text: `+${waiting.length - 6}` }));
337
+ }
338
+ hud.queue.append(row, h('div', { class: 'of-faint tiny', text: (s.brains || []).length > 1 ? t('office.queue.brains', { count: s.brains.length }) : t('office.queue.oneModel') }));
339
+ // nothing hired yet / no state yet
340
+ hud.empty.hidden = !!(s.crew || []).length;
341
+ hud.empty.textContent = ui.hello ? t('office.empty') : t('office.opening');
342
+ }
343
+
344
+ /** The running task in words: who does what right now, from the worker's real status. */
345
+ function nowLine(s, task) {
346
+ if (!task) return '';
347
+ const w = worker(task.assignee);
348
+ const st = s.workers?.[task.assignee] || {};
349
+ const what = NOW_KEYS.includes(st.status) ? st.status : task.status === 'review' ? 'review' : 'works';
350
+ return t(`office.now.${what}`, { name: w.name, title: mdLine(task.title, 80) });
351
+ }
352
+ const NOW_KEYS = ['thinking', 'tool', 'queued', 'waiting_approval'];
353
+
354
+ function paintClock() {
355
+ const hr = hourNow();
356
+ const hh = Math.floor(hr); const mm = Math.floor((hr % 1) * 60);
357
+ hud.clock.textContent = `${dayPhase(hr)} · ${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}`;
358
+ }
359
+
360
+ function paintHoney() {
361
+ if (hud.honeyN) hud.honeyN.textContent = String(shownHoney ?? 0);
362
+ if (hud.honeyT) hud.honeyT.textContent = t('office.hud.tasksDone', { count: shownHoney ?? 0 });
363
+ }
364
+ function bumpHoney() {
365
+ const real = doneCount(S());
366
+ shownHoney = Math.min(real, (shownHoney ?? 0) + 1);
367
+ paintHoney();
368
+ }
369
+
370
+ /** The segmented timeline: one segment per task of the job, in order, colored by its state. */
371
+ function paintTimeline(tasks) {
372
+ if (!hud.segs) return;
373
+ const key = tasks.map((x) => `${x.id}:${x.status}`).join('|');
374
+ if (hud.segs._key === key) return;
375
+ hud.segs._key = key;
376
+ clear(hud.segs);
377
+ for (const x of tasks) hud.segs.append(h('i', { dataset: { s: x.status }, title: `${mdLine(x.title, 120)}: ${TASK_LABEL[x.status] || x.status}` }));
378
+ }
379
+
380
+ /* activity feed: short, human lines from real events (tx keys, so a language switch rewrites them) */
381
+ function feed(ev) {
382
+ if (!hud.feed) return;
383
+ const d = ev.data || {};
384
+ const s = S();
385
+ const name = (id) => worker(id).name;
386
+ const title = (task) => mdLine(task.title, 80);
387
+ let line = null; let tone = '';
388
+ switch (ev.type) {
389
+ case 'job.created': line = ['office.feed.jobCreated']; tone = 'honey'; break;
390
+ case 'job.planned': line = ['office.feed.jobPlanned', { count: d.tasks?.length || 0 }]; break;
391
+ case 'brief.proposed': line = ['office.feed.briefProposed']; tone = 'warn'; break;
392
+ case 'brief.approved': line = [d.source === 'original' ? 'office.feed.briefOriginal' : 'office.feed.briefApproved']; break;
393
+ case 'task.status': {
394
+ const task = s.tasks[d.taskId];
395
+ if (!task) break;
396
+ if (d.status === 'running') line = ['office.feed.started', { name: name(task.assignee), title: title(task) }];
397
+ else if (d.status === 'done') { line = ['office.feed.finished', { name: name(task.assignee), title: title(task) }]; tone = 'ok'; }
398
+ else if (d.status === 'failed') { line = ['office.feed.stuck', { name: name(task.assignee), title: title(task) }]; tone = 'bad'; }
399
+ break;
400
+ }
401
+ case 'file.changed': line = [d.op === 'create' ? 'office.feed.fileCreate' : d.op === 'delete' ? 'office.feed.fileDelete' : 'office.feed.fileEdit', { name: name(d.workerId), path: String(d.path || '') }]; break;
402
+ case 'approval.requested': line = ['office.feed.approval', { name: name(d.approval?.workerId) }]; tone = 'warn'; break;
403
+ case 'qa.report': line = d.passed ? ['office.feed.qaPassed'] : ['office.feed.qaIssues', { count: d.issues?.length || 0 }]; tone = d.passed ? 'ok' : 'bad'; break;
404
+ case 'task.updated': if (d.task?.assignee) line = ['office.feed.handed', { name: name(d.task.assignee) }]; break;
405
+ case 'crew.hired': if (ui.hello && !d.worker?.builtin) { line = ['office.feed.joined', { name: d.worker?.name || '' }]; tone = 'honey'; } break;
406
+ case 'job.done': line = ['office.feed.jobDone']; tone = 'ok'; break;
407
+ default: break;
408
+ }
409
+ if (!line) return;
410
+ const li = h('li', { dataset: { tone } }, h('span', { class: 'of-dot' }), h('span', { tx: line[0], txArgs: line[1] }));
411
+ // the brief waits for the user's OK: the line opens it
412
+ if (ev.type === 'brief.proposed') li.append(h('button', { type: 'button', class: 'btn btn-xs btn-quiet', style: 'margin-left:6px', tx: 'office.hud.openBrief', on: { click: () => { setMode('desktop'); wm.open('brief'); } } }));
413
+ hud.feed.prepend(li);
414
+ while (hud.feed.children.length > 5) hud.feed.lastChild.remove();
415
+ if (!reducedMotion() && mode === 'office') li.animate([{ opacity: 0, transform: 'translateY(-4px)' }, { opacity: 1, transform: 'none' }], { duration: 200, easing: 'cubic-bezier(.2,0,0,1)' });
416
+ }
417
+
418
+ function banner(ev) {
419
+ const b = hud.banner;
420
+ clear(b);
421
+ // a calm activity toast: a check, the summary and one action
422
+ b.append(h('span', { class: 'of-jar of-jar-big', html: CHECK_SVG, 'aria-hidden': 'true' }),
423
+ h('div', {}, h('strong', { tx: 'office.banner.title' }), h('div', { class: 'of-faint', text: mdLine(ev.data?.summary || '', 140) || t('office.banner.fallback') })),
424
+ h('button', { type: 'button', class: 'btn btn-xs btn-quiet', tx: 'office.banner.preview', on: { click: () => { setMode('desktop'); wm.open('preview'); } } }));
425
+ b.hidden = false;
426
+ if (!reducedMotion()) b.animate([{ opacity: 0, transform: 'translate(-50%, 6px)' }, { opacity: 1, transform: 'translate(-50%, 0)' }], { duration: 200, easing: 'cubic-bezier(.2,0,0,1)' });
427
+ clearTimeout(b._t);
428
+ b._t = setTimeout(() => { b.hidden = true; }, 7000);
429
+ }
430
+
431
+ /* ---------- the DOM layer over the canvas: focus, hover, click, menus, drag ---------- */
432
+ function syncHits(sc) {
433
+ const s = S();
434
+ // bees
435
+ const seen = new Set();
436
+ for (const hit of sc.hits) {
437
+ seen.add(hit.id);
438
+ let b = bees.get(hit.id);
439
+ if (!b) b = makeBee(hit.id);
440
+ const tx = Math.round(hit.x); const ty = Math.round(hit.y);
441
+ if (b._x !== tx || b._y !== ty || b._w !== Math.round(hit.w)) {
442
+ b._x = tx; b._y = ty; b._w = Math.round(hit.w);
443
+ b.style.transform = `translate(${tx}px, ${ty}px)`;
444
+ b.style.width = `${Math.round(hit.w)}px`;
445
+ b.style.height = `${Math.round(hit.h)}px`;
446
+ }
447
+ const a = sc.actors.get(hit.id);
448
+ const label = beeLabel(hit.id, a, s);
449
+ if (b._label !== label) { b._label = label; b.setAttribute('aria-label', label); if (tip.dataset.for === `bee:${hit.id}`) showTip(b, hit.id); }
450
+ }
451
+ for (const [id, b] of bees) if (!seen.has(id)) { b.remove(); bees.delete(id); }
452
+ // notes
453
+ const nseen = new Set();
454
+ for (const hit of sc.noteHits) {
455
+ nseen.add(hit.id);
456
+ let n = notes.get(hit.id);
457
+ if (!n) n = makeNote(hit.id);
458
+ const tx = Math.round(hit.x); const ty = Math.round(hit.y);
459
+ if (n._x !== tx || n._y !== ty) {
460
+ n._x = tx; n._y = ty;
461
+ n.style.transform = `translate(${tx}px, ${ty}px)`;
462
+ n.style.width = `${Math.round(hit.w)}px`;
463
+ n.style.height = `${Math.round(hit.h)}px`;
464
+ }
465
+ const task = s.tasks[hit.id];
466
+ const label = task ? t('office.note.aria', { title: mdLine(task.title, 120), status: TASK_LABEL[task.status] || task.status, name: worker(task.assignee).name }) : t('office.note.task');
467
+ if (n._label !== label) { n._label = label; n.setAttribute('aria-label', label); }
468
+ }
469
+ for (const [id, n] of notes) if (!nseen.has(id) && !(drag && drag.taskId === id)) { n.remove(); notes.delete(id); }
470
+ }
471
+
472
+ function beeLabel(id, a, s) {
473
+ const w = worker(id);
474
+ const st = s.workers[id] || { status: 'idle' };
475
+ const task = st.taskId && s.tasks[st.taskId];
476
+ const m = a ? (a.seg ? 'fly' : a.mode) : 'idle';
477
+ const lv = levelOf(s, id);
478
+ const who = lv != null ? t('office.bee.whoLevel', { name: w.name, role: roleOf(w), level: lv }) : t('office.bee.who', { name: w.name, role: roleOf(w) });
479
+ const status = statusOf(w, m, st);
480
+ return task ? t('office.bee.ariaTask', { who, status, title: mdLine(task.title, 120) }) : t('office.bee.aria', { who, status });
481
+ }
482
+
483
+ function makeBee(id) {
484
+ const b = h('button', { type: 'button', class: 'of-bee', 'aria-describedby': 'of-tip', dataset: { id } });
485
+ b.addEventListener('click', () => { if (!drag) wm.open('worker', id); });
486
+ b.addEventListener('pointerenter', () => { scene.highlight = id; showTip(b, id); });
487
+ b.addEventListener('pointerleave', () => { if (scene.highlight === id) scene.highlight = null; hideTip(); });
488
+ b.addEventListener('focus', () => { scene.highlight = id; showTip(b, id); });
489
+ b.addEventListener('blur', () => { if (scene.highlight === id) scene.highlight = null; hideTip(); });
490
+ menu.provide(b, () => beeMenu(id));
491
+ hitLayer.append(b);
492
+ bees.set(id, b);
493
+ return b;
494
+ }
495
+
496
+ function beeMenu(id) {
497
+ const w = worker(id);
498
+ const s = S();
499
+ const st = s.workers[id] || {};
500
+ const mine = Object.values(s.tasks).filter((x) => x.assignee === id);
501
+ const retryable = mine.filter((x) => ['failed', 'blocked'].includes(x.status)).pop() || (st.taskId && s.tasks[st.taskId]);
502
+ const lv = levelOf(s, id);
503
+ return [
504
+ { header: lv != null ? t('office.menu.headerLevel', { name: w.name, role: roleOf(w), level: lv }) : t('office.menu.header', { name: w.name, role: roleOf(w) }) },
505
+ { label: t('office.menu.chat', { name: w.name }), icon: 'chat', action: () => wm.open('worker', id) },
506
+ { label: w.paused ? t('office.menu.resume') : t('office.menu.pause'), icon: w.paused ? 'arrow' : 'stop', disabled: !!ui.replay, action: () => act.pauseWorker(id, !w.paused) },
507
+ { label: retryable ? t('office.menu.retryTask', { title: mdLine(retryable.title, 60) }) : t('office.menu.retryNone'), icon: 'replay', disabled: !retryable || !!ui.replay, action: () => act.retryTask(retryable.id) },
508
+ { label: t('office.menu.files'), icon: 'folder', action: () => { setMode('desktop'); wm.open('files'); } },
509
+ ];
510
+ }
511
+
512
+ function makeNote(id) {
513
+ const n = h('button', { type: 'button', class: 'of-note', 'aria-describedby': 'of-tip', dataset: { id } });
514
+ n.addEventListener('pointerenter', () => { scene.highlight = id; showNoteTip(n, id); });
515
+ n.addEventListener('pointerleave', () => { if (scene.highlight === id) scene.highlight = null; hideTip(); });
516
+ n.addEventListener('focus', () => { scene.highlight = id; showNoteTip(n, id); });
517
+ n.addEventListener('blur', () => { if (scene.highlight === id) scene.highlight = null; hideTip(); });
518
+ n.addEventListener('click', (e) => {
519
+ if (n._dragged) { n._dragged = false; return; }
520
+ const r = n.getBoundingClientRect();
521
+ menu.open({ x: e.clientX || r.left + 10, y: e.clientY || r.bottom, items: noteMenu(id) });
522
+ });
523
+ n.addEventListener('pointerdown', (e) => startDrag(e, n, id));
524
+ menu.provide(n, () => noteMenu(id));
525
+ hitLayer.append(n);
526
+ notes.set(id, n);
527
+ return n;
528
+ }
529
+
530
+ function noteMenu(id) {
531
+ const s = S();
532
+ const task = s.tasks[id];
533
+ if (!task) return null;
534
+ const off = !!ui.replay || task.status === 'done';
535
+ return [
536
+ { header: mdLine(task.title, 60) },
537
+ { label: t('office.menu.handTo'), icon: 'hire', disabled: off, items: s.crew.filter((w) => w.id !== task.assignee).map((w) => ({ label: t('office.menu.handToWho', { name: w.name, role: roleOf(w) }), iconEl: beeAvatar(w, 18, { ring: false }), action: () => reassign(id, w.id) })) },
538
+ { label: t('office.menu.retry'), icon: 'replay', disabled: !!ui.replay || !['failed', 'blocked', 'done', 'skipped'].includes(task.status), action: () => act.retryTask(id) },
539
+ { label: t('office.menu.cancel'), icon: 'x', danger: true, disabled: !!ui.replay || ['done', 'skipped'].includes(task.status), action: () => act.cancelTask(id) },
540
+ ];
541
+ }
542
+
543
+ function reassign(taskId, workerId) {
544
+ const task = S().tasks[taskId];
545
+ if (!task || task.assignee === workerId) return;
546
+ act.reassignTask(taskId, workerId);
547
+ }
548
+
549
+ function startDrag(e, el, id) {
550
+ if (e.button !== 0 || ui.replay) return;
551
+ const task = S().tasks[id];
552
+ if (!task || task.status === 'done') return;
553
+ const x0 = e.clientX; const y0 = e.clientY;
554
+ let ghost = null;
555
+ const move = (ev) => {
556
+ if (!drag && Math.hypot(ev.clientX - x0, ev.clientY - y0) < 6) return;
557
+ if (!drag) {
558
+ drag = { taskId: id, el };
559
+ scene.dragTask = id;
560
+ ghost = h('div', { class: 'of-drag', 'aria-hidden': 'true' }, h('i', { style: `background:${worker(task.assignee).color}` }), h('span', { text: mdLine(task.title, 60) }));
561
+ layer.append(ghost);
562
+ layer.classList.add('of-dragging');
563
+ hideTip();
564
+ }
565
+ const lr = layer.getBoundingClientRect();
566
+ ghost.style.transform = `translate(${ev.clientX - lr.left + 8}px, ${ev.clientY - lr.top + 8}px) rotate(-4deg)`;
567
+ const over = beeAt(ev.clientX, ev.clientY);
568
+ scene.highlight = over || null;
569
+ drag.over = over;
570
+ };
571
+ const up = () => {
572
+ removeEventListener('pointermove', move);
573
+ removeEventListener('pointerup', up);
574
+ removeEventListener('pointercancel', up);
575
+ if (!drag) return;
576
+ el._dragged = true;
577
+ const target = drag.over;
578
+ ghost?.remove();
579
+ layer.classList.remove('of-dragging');
580
+ scene.dragTask = null;
581
+ scene.highlight = null;
582
+ drag = null;
583
+ if (target) reassign(id, target);
584
+ };
585
+ addEventListener('pointermove', move);
586
+ addEventListener('pointerup', up);
587
+ addEventListener('pointercancel', up);
588
+ }
589
+
590
+ function cancelDrag() {
591
+ layer.querySelector('.of-drag')?.remove();
592
+ layer.classList.remove('of-dragging');
593
+ scene.dragTask = null;
594
+ scene.highlight = null;
595
+ drag = null;
596
+ }
597
+
598
+ function beeAt(x, y) {
599
+ for (const [id, b] of bees) {
600
+ const r = b.getBoundingClientRect();
601
+ if (x >= r.left - 6 && x <= r.right + 6 && y >= r.top - 6 && y <= r.bottom + 6) return id;
602
+ }
603
+ return null;
604
+ }
605
+
606
+ function showTip(el, id) {
607
+ const s = S();
608
+ const w = worker(id);
609
+ const a = scene.actors.get(id);
610
+ const st = s.workers[id] || { status: 'idle' };
611
+ const task = st.taskId && s.tasks[st.taskId];
612
+ const m = a ? (a.seg ? 'fly' : a.mode) : 'idle';
613
+ const lastTask = task || Object.values(s.tasks).filter((x) => x.assignee === id && x.status === 'running').pop();
614
+ const done = Object.values(s.tasks).filter((x) => x.assignee === id && x.status === 'done').length;
615
+ const lv = levelOf(s, id);
616
+ clear(tip);
617
+ tip.append(
618
+ h('div', { class: 'of-tip-h' }, beeAvatar(w, 30, { ring: true }), h('div', {}, h('strong', { text: w.name }), h('div', { class: 'of-faint', text: roleOf(w) })), lv != null ? h('span', { class: 'of-lv', text: t('office.level', { level: lv }) }) : null),
619
+ h('div', { class: 'of-tip-r' }, h('span', { class: 'of-faint', tx: 'office.tip.status' }), h('span', { text: statusOf(w, m, st) })),
620
+ h('div', { class: 'of-tip-r' }, h('span', { class: 'of-faint', tx: 'office.tip.task' }), h('span', { text: lastTask ? mdLine(lastTask.title, 80) : t('office.tip.none') })),
621
+ h('div', { class: 'of-tip-r' }, h('span', { class: 'of-faint', tx: 'office.tip.done' }), h('span', { text: t('office.tip.doneCount', { count: done }) })),
622
+ h('div', { class: 'of-tip-f', tx: 'office.tip.foot' }));
623
+ tip.dataset.for = `bee:${id}`;
624
+ place(el);
625
+ }
626
+
627
+ function showNoteTip(el, id) {
628
+ const s = S();
629
+ const task = s.tasks[id];
630
+ if (!task) return;
631
+ clear(tip);
632
+ append(tip, [h('div', { class: 'of-tip-h' }, h('div', {}, h('strong', { text: mdLine(task.title, 120) }), h('div', { class: 'of-faint', text: t('office.tip.noteMeta', { status: TASK_LABEL[task.status] || task.status, name: worker(task.assignee).name }) }))),
633
+ task.detail ? h('div', { class: 'of-tip-d', text: mdLine(task.detail, 180) }) : null,
634
+ h('div', { class: 'of-tip-f', tx: task.status === 'done' ? 'office.tip.noteDone' : 'office.tip.noteFoot' })]);
635
+ tip.dataset.for = `note:${id}`;
636
+ place(el);
637
+ }
638
+
639
+ function place(el) {
640
+ const r = el.getBoundingClientRect();
641
+ const lr = layer.getBoundingClientRect();
642
+ tip.classList.add('on');
643
+ const tr = tip.getBoundingClientRect();
644
+ let x = r.left - lr.left + r.width / 2 - tr.width / 2;
645
+ let y = r.top - lr.top - tr.height - 10;
646
+ if (y < 8) y = r.bottom - lr.top + 10;
647
+ x = Math.max(8, Math.min(lr.width - tr.width - 8, x));
648
+ tip.style.transform = `translate(${Math.round(x)}px, ${Math.round(y)}px)`;
649
+ }
650
+ function hideTip() { tip?.classList.remove('on'); if (tip) tip.dataset.for = ''; }
651
+
652
+ /* ---------- glyphs ---------- */
653
+ function officeGlyph() {
654
+ return h('span', { class: 'of-gl', html: '<svg viewBox="0 0 24 24" class="ico ico-sm"><path d="M12 3 21 8v8l-9 5-9-5V8z"/><path d="M3 8l9 5 9-5M12 13v8"/></svg>' });
655
+ }
656
+ function miniGlyph() {
657
+ return h('span', { class: 'of-gl', html: '<svg viewBox="0 0 24 24" class="ico"><rect x="3.5" y="4.5" width="17" height="15" rx="2.5"/><rect x="11.5" y="11.5" width="7" height="6" rx="1.2"/></svg>' });
658
+ }
659
+ function pipGlyph() {
660
+ return h('span', { class: 'of-gl', html: '<svg viewBox="0 0 24 24" class="ico"><rect x="3.5" y="5" width="17" height="14" rx="2.5"/><path d="M13 12.5h5.5v4.5H13z"/><path d="M7 9l3 3M7 9h2.6M7 9v2.6"/></svg>' });
661
+ }
662
+ const CHECK_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="8.5"/><path d="M8.2 12.2l2.6 2.6 5-5.2"/></svg>';