hivedesk 1.0.0 → 1.0.1

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 (89) hide show
  1. package/CHANGELOG.md +122 -111
  2. package/desktop/controller.js +85 -7
  3. package/desktop/native.js +4 -1
  4. package/desktop/release-notes/1.0.1.json +12 -0
  5. package/desktop/scripts/package.mjs +134 -123
  6. package/desktop/shell.html +5 -2
  7. package/desktop/workarea.js +440 -0
  8. package/i18n/de.json +247 -4
  9. package/i18n/en.json +247 -4
  10. package/i18n/es.json +247 -4
  11. package/i18n/fr.json +247 -4
  12. package/i18n/it.json +247 -4
  13. package/i18n/ja.json +247 -4
  14. package/i18n/ko.json +247 -4
  15. package/i18n/parts/downloads.de.json +29 -0
  16. package/i18n/parts/downloads.en.json +29 -0
  17. package/i18n/parts/downloads.es.json +29 -0
  18. package/i18n/parts/downloads.fr.json +29 -0
  19. package/i18n/parts/downloads.it.json +29 -0
  20. package/i18n/parts/downloads.ja.json +29 -0
  21. package/i18n/parts/downloads.ko.json +29 -0
  22. package/i18n/parts/downloads.pt-BR.json +29 -0
  23. package/i18n/parts/downloads.ru.json +29 -0
  24. package/i18n/parts/downloads.zh-CN.json +29 -0
  25. package/i18n/parts/office.de.json +184 -0
  26. package/i18n/parts/office.en.json +184 -0
  27. package/i18n/parts/office.es.json +184 -0
  28. package/i18n/parts/office.fr.json +184 -0
  29. package/i18n/parts/office.it.json +184 -0
  30. package/i18n/parts/office.ja.json +184 -0
  31. package/i18n/parts/office.ko.json +184 -0
  32. package/i18n/parts/office.pt-BR.json +184 -0
  33. package/i18n/parts/office.ru.json +184 -0
  34. package/i18n/parts/office.zh-CN.json +184 -0
  35. package/i18n/pt-BR.json +247 -4
  36. package/i18n/ru.json +247 -4
  37. package/i18n/zh-CN.json +247 -4
  38. package/package.json +3 -2
  39. package/src/brain/manager.js +23 -7
  40. package/src/brain/models.js +146 -30
  41. package/src/brain/runtime.js +61 -13
  42. package/src/crew/domains/flow.js +2 -1
  43. package/src/crew/engine.js +172 -22
  44. package/src/crew/legacy.js +72 -0
  45. package/src/crew/planner.js +14 -1
  46. package/src/crew/talk.js +110 -3
  47. package/src/crew/taskgraph.js +12 -2
  48. package/src/crew/worker.js +60 -2
  49. package/src/index.js +4 -1
  50. package/src/phone/hub.js +15 -3
  51. package/src/phone/port.js +1 -1
  52. package/src/replay/reduce.js +1 -0
  53. package/src/tools/check.js +2 -0
  54. package/src/voice/index.js +1 -1
  55. package/src/voice/piper.js +10 -4
  56. package/src/voice/store.js +2 -1
  57. package/src/voice/whisper.js +63 -25
  58. package/ui/city/activity.js +4 -1
  59. package/ui/city/city.js +5 -5
  60. package/ui/city/scene.js +2 -1
  61. package/ui/css/hive.css +20 -0
  62. package/ui/js/dock.js +2 -2
  63. package/ui/js/dom.js +23 -18
  64. package/ui/js/i18n.js +12 -0
  65. package/ui/js/main.js +43 -3
  66. package/ui/js/md.js +130 -0
  67. package/ui/js/net.js +6 -0
  68. package/ui/js/palette.js +2 -2
  69. package/ui/js/store.js +20 -2
  70. package/ui/js/topbar.js +2 -2
  71. package/ui/js/voice/index.js +3 -2
  72. package/ui/js/widgets/brief.js +28 -10
  73. package/ui/js/widgets/chat.js +16 -4
  74. package/ui/js/widgets/files.js +3 -3
  75. package/ui/js/widgets/memory.js +3 -3
  76. package/ui/js/widgets/replay.js +3 -3
  77. package/ui/js/widgets/settings.js +2 -2
  78. package/ui/js/widgets/timeline.js +2 -2
  79. package/ui/js/widgets/worker.js +17 -6
  80. package/ui/models/index.js +3 -2
  81. package/ui/models/window.js +2 -2
  82. package/ui/office/office.js +662 -623
  83. package/ui/office/popout.js +4 -3
  84. package/ui/office/scene.js +47 -28
  85. package/ui/phone/core/client.js +11 -5
  86. package/ui/phone/desktop.js +2 -1
  87. package/ui/widget.html +8 -8
  88. package/ui/widget.js +35 -20
  89. package/ui/workbench/searchview.js +3 -3
@@ -1,623 +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 } from '/js/dom.js';
7
- import { S, rev, ui, worker, onEvent, currentJob, jobTasks } from '/js/store.js';
8
- import * as net from '/js/net.js';
9
- import * as wm from '/js/wm.js';
10
- import * as menu from '/js/menu.js';
11
- import * as act from '/js/actions.js';
12
- import { beeAvatar } from '/js/bees.js';
13
- import { track, STATUS_LABEL, TASK_LABEL } from '/js/widgets/util.js';
14
- import { OfficeScene, levelOf, doneCount, dayPhase } from './scene.js';
15
- import * as audio from './audio.js';
16
- import { openWidget, openPip, pipSupported } from './popout.js';
17
-
18
- const VIEW_KEY = 'hivedesk.view.v2'; // v2: City became the default home in 0.2.0
19
- const MODE_LABEL = {
20
- idle: 'Idle', sleep: 'Napping (idle)', type: 'Typing', plan: 'Planning on the board', wait: 'In the queue for the model',
21
- stuck: 'Waiting for your approval', test: 'Running checks', read: 'Reading files', error: 'Error', celebrate: 'Celebrating',
22
- paused: 'Paused', fly: 'Flying over',
23
- };
24
-
25
- let layer;
26
- let scene;
27
- let canvas;
28
- let hud = {};
29
- let hitLayer;
30
- let tip;
31
- let bees = new Map();
32
- let notes = new Map();
33
- let mode = 'desktop';
34
- let hiddenWins = [];
35
- let deskEl;
36
- let seg;
37
- let hourOverride = null;
38
- let shownHoney = null;
39
- let honeyTimer = null;
40
- let drag = null;
41
-
42
- function linkCss() {
43
- if (document.querySelector('link[data-office]')) return;
44
- document.head.append(h('link', { rel: 'stylesheet', href: '/office/office.css', 'data-office': '' }));
45
- }
46
-
47
- function readHourOverride() {
48
- const q = new URLSearchParams(location.search).get('hour');
49
- if (q != null && q !== '' && !Number.isNaN(Number(q))) hourOverride = Math.max(0, Math.min(23.99, Number(q)));
50
- }
51
- const hourNow = () => {
52
- if (hourOverride != null) return hourOverride;
53
- const d = new Date();
54
- return d.getHours() + d.getMinutes() / 60;
55
- };
56
-
57
- /**
58
- * Mounts the Office. Hooks: a segmented toggle in the top bar and a dock entry for the
59
- * mini widget.
60
- * @param {{ desk: HTMLElement, barRight: HTMLElement|null, addDockItem?: Function }} opts
61
- */
62
- export function initOffice({ desk, barRight, addDockItem }) {
63
- linkCss();
64
- readHourOverride();
65
- deskEl = desk;
66
- layer = h('section', { class: 'of-layer', hidden: true, 'aria-label': 'Office. The crew at work. Tab to a bee or a note, Enter to open, Shift F10 for its menu.' });
67
- canvas = h('canvas', { class: 'of-canvas', 'aria-hidden': 'true' });
68
- hitLayer = h('div', { class: 'of-hits' });
69
- tip = h('div', { class: 'of-tip', role: 'tooltip', id: 'of-tip' });
70
- layer.append(canvas, hitLayer, buildHud(), tip);
71
- desk.append(layer);
72
-
73
- scene = new OfficeScene(canvas, {
74
- getState: S,
75
- reduced: reducedMotion,
76
- hour: hourNow,
77
- onSound: (n) => audio.fx(n),
78
- honeyTarget: () => {
79
- const r = hud.honey?.getBoundingClientRect();
80
- const lr = layer.getBoundingClientRect();
81
- return r ? { x: r.left - lr.left + 18, y: r.top - lr.top + r.height / 2 } : null;
82
- },
83
- onHoney: () => bumpHoney(),
84
- onFrame: (sc) => { syncHits(sc); audio.setLevels(sc.typingCount || 0, sc.flyingCount || 0); },
85
- });
86
- new ResizeObserver(() => { if (mode === 'office') scene.resize(layer.clientWidth, layer.clientHeight); }).observe(layer);
87
-
88
- // the toggle in the top bar
89
- seg = h('div', { class: 'of-seg', role: 'group', 'aria-label': 'View' },
90
- h('button', { type: 'button', dataset: { v: 'office' }, title: 'Office: the crew at work', on: { click: () => setMode('office') } }, officeGlyph(), h('span', { text: 'Office' })),
91
- h('button', { type: 'button', dataset: { v: 'desktop' }, title: 'Desktop: windows and widgets', on: { click: () => setMode('desktop') } }, icon('hive', 'ico-sm'), h('span', { text: 'Desktop' })));
92
- barRight?.prepend(seg);
93
-
94
- addDockItem?.({
95
- id: 'widget', label: 'Mini widget', sub: 'a small always on view',
96
- content: h('span', { class: 'dk-hex' }, miniGlyph()),
97
- onClick: () => openWidget(),
98
- menu: () => [
99
- { header: 'Mini widget' },
100
- { label: 'Pop out a window (360 by 480)', icon: 'preview', action: () => openWidget() },
101
- { label: 'Picture in picture', icon: 'preview', disabled: !pipSupported(), action: () => openPip() },
102
- { sep: true },
103
- { label: mode === 'office' ? 'Back to the desktop' : 'Open the Office', icon: 'hive', action: () => setMode(mode === 'office' ? 'desktop' : 'office') },
104
- ],
105
- });
106
-
107
- // engine wiring
108
- net.on('hello', () => { scene.reset(); shownHoney = null; paintHud(); });
109
- onEvent((ev) => {
110
- scene.handle(ev);
111
- feed(ev);
112
- if (ev.type === 'job.done' && mode === 'office') banner(ev);
113
- if (/^(brief|job)\./.test(ev.type)) paintHud();
114
- });
115
- track(() => [rev.jobs, rev.tasks, rev.queue, rev.crew, rev.workers, rev.chat, rev.approvals, ui.replay, ui.demo], () => paintHud());
116
- track(() => [rev.crew], () => scene.syncCrew(true));
117
-
118
- document.addEventListener('visibilitychange', () => {
119
- if (mode !== 'office') return;
120
- if (document.hidden) scene.stop(); else scene.start();
121
- });
122
- document.addEventListener('keydown', (e) => {
123
- if (e.key === 'Escape' && drag) cancelDrag();
124
- });
125
-
126
- // City is the default home when it is registered (ui/city/); Office and Desktop stay one click away.
127
- let start = 'city';
128
- try { start = localStorage.getItem(VIEW_KEY) || 'city'; } catch { /* ignore */ }
129
- const q = new URLSearchParams(location.search).get('view');
130
- if (q) start = q;
131
- // wait for the first layout of the windows before hiding them
132
- net.on('hello', once(() => requestAnimationFrame(() => {
133
- if (start === 'office' || views.has(start)) setMode(start, { quiet: true });
134
- })));
135
- paintSeg();
136
- setInterval(() => { if (mode === 'office') paintClock(); }, 20000);
137
- }
138
-
139
- function once(fn) { let done = false; return (...a) => { if (!done) { done = true; fn(...a); } }; }
140
-
141
- export function getMode() { return mode; }
142
-
143
- /* Other full screen views next to Office and Desktop (the City registers here). */
144
- const views = new Map();
145
-
146
- /**
147
- * Adds a view to the toggle. `enter({ quiet })` shows it; `leave({ quiet, done })` hides it and
148
- * calls done when it is gone. `first` puts it at the start of the toggle.
149
- * @param {{ id: string, labelKey: string, titleKey?: string, glyph: () => Node, enter: Function, leave: Function, first?: boolean }} v
150
- */
151
- export function addView(v) {
152
- views.set(v.id, v);
153
- 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 }));
154
- if (v.first) seg.prepend(b); else seg.append(b);
155
- seg.dataset.tour = 'office';
156
- paintSeg();
157
- }
158
-
159
- const isScene = (m) => m === 'office' || views.has(m);
160
-
161
- export function setMode(next, { quiet = false } = {}) {
162
- if (next === mode || !(next === 'desktop' || isScene(next))) return;
163
- const prev = mode;
164
- mode = next;
165
- try { localStorage.setItem(VIEW_KEY, mode); } catch { /* ignore */ }
166
- paintSeg();
167
- if (isScene(next) && !isScene(prev)) {
168
- // tuck the open windows into the dock, and bring them back on the desktop
169
- hiddenWins = wm.list().filter((w) => !w.min).map((w) => w.id);
170
- for (const id of hiddenWins) wm.minimize(id);
171
- deskEl.classList.add('of-on');
172
- }
173
- const toDesk = () => {
174
- if (mode !== 'desktop') return;
175
- deskEl.classList.remove('of-on');
176
- for (const id of hiddenWins) if (wm.get(id)?.min) wm.restore(id);
177
- hiddenWins = [];
178
- };
179
- if (views.has(prev)) views.get(prev).leave({ quiet: quiet || isScene(next), done: toDesk });
180
- if (views.has(next)) { if (prev === 'office') leaveOffice(true, () => {}); views.get(next).enter({ quiet }); return; }
181
- if (mode === 'office') {
182
- layer.hidden = false;
183
- scene.resize(layer.clientWidth, layer.clientHeight);
184
- scene.reset();
185
- scene.start();
186
- audio.setActive(true);
187
- paintHud();
188
- if (!quiet && !reducedMotion()) layer.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 200, easing: 'cubic-bezier(.2,0,0,1)' });
189
- } else if (prev === 'office') leaveOffice(quiet, toDesk);
190
- else toDesk();
191
- }
192
-
193
- function leaveOffice(quiet, after) {
194
- scene.stop();
195
- audio.setActive(false);
196
- hideTip();
197
- const done = () => { layer.hidden = true; after(); };
198
- if (reducedMotion() || quiet) done();
199
- else layer.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 150, easing: 'cubic-bezier(.4,0,1,1)' }).onfinish = done;
200
- }
201
-
202
- function paintSeg() {
203
- if (!seg) return;
204
- for (const b of seg.querySelectorAll('button')) b.setAttribute('aria-pressed', String(b.dataset.v === mode));
205
- }
206
-
207
- /* ---------- HUD ---------- */
208
- function buildHud() {
209
- const xpFill = h('i');
210
- hud.req = h('div', { class: 'of-req' });
211
- hud.xpText = h('span', { class: 'of-xp-t' });
212
- hud.xpLv = h('span', { class: 'of-xp-lv' });
213
- // progress is a segmented timeline: one segment per task, colored by its state
214
- hud.segs = h('span', { class: 'of-tl', 'aria-hidden': 'true' });
215
- hud.xp = h('div', { class: 'of-xp', role: 'progressbar', 'aria-label': 'Job progress', 'aria-valuemin': '0', 'aria-valuemax': '100' }, xpFill, hud.segs);
216
- hud.xpFill = xpFill;
217
- hud.state = h('span', { class: 'of-chip' });
218
- const job = h('div', { class: 'of-card of-job' },
219
- h('div', { class: 'of-row' }, h('span', { class: 'of-k', text: 'Current job' }), hud.state),
220
- hud.req,
221
- h('div', { class: 'of-row', style: 'gap:10px' }, hud.xpLv, hud.xp),
222
- hud.xpText);
223
-
224
- const doneMark = h('span', { class: 'of-jar', html: CHECK_SVG, 'aria-hidden': 'true' });
225
- hud.honeyN = h('b', { text: '0' });
226
- hud.honey = h('div', { class: 'of-pill of-honey', title: 'Finished tasks in this workspace' }, doneMark, hud.honeyN, h('span', { class: 'of-faint', text: 'tasks done' }));
227
- hud.clock = h('div', { class: 'of-pill of-clock' });
228
- hud.sound = h('button', { type: 'button', class: 'of-ib', on: { click: () => { audio.setAmbient(!audio.ambientOn()); paintSound(); } } });
229
- const pop = h('button', { type: 'button', class: 'of-ib', title: 'Pop out the mini widget', 'aria-label': 'Pop out the mini widget', on: { click: () => openWidget() } }, miniGlyph());
230
- const pip = h('button', { type: 'button', class: 'of-ib', title: 'Picture in picture', 'aria-label': 'Picture in picture mini window', hidden: !pipSupported(), on: { click: () => openPip() } }, pipGlyph());
231
- const stats = h('div', { class: 'of-stats' }, hud.honey, hud.clock, h('div', { class: 'of-pill of-tools' }, hud.sound, pop, pip));
232
-
233
- hud.queue = h('div', { class: 'of-card of-queue' });
234
- hud.feed = h('ol', { class: 'of-card of-feed', 'aria-label': 'Office activity', 'aria-live': 'polite' });
235
- hud.banner = h('div', { class: 'of-banner', role: 'status', hidden: true });
236
- hud.empty = h('div', { class: 'of-empty', hidden: true });
237
- paintSound();
238
- return h('div', { class: 'of-hud' }, job, stats, hud.queue, hud.feed, hud.banner, hud.empty);
239
- }
240
-
241
- function paintSound() {
242
- const on = audio.ambientOn();
243
- hud.sound.setAttribute('aria-pressed', String(on));
244
- hud.sound.setAttribute('aria-label', on ? 'Office sounds on' : 'Office sounds off');
245
- hud.sound.title = on ? 'Office sounds on (soft room tone, typing, wings)' : 'Office sounds off';
246
- hud.sound.innerHTML = on
247
- ? '<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>'
248
- : '<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>';
249
- }
250
-
251
- function paintHud() {
252
- if (!hud.req) return;
253
- const s = S();
254
- let j = [...(s.jobs || [])].reverse().find((x) => ['refining', 'awaiting_brief', 'planning', 'running'].includes(x.status)) || currentJob(s);
255
- if (j && scene?.briefWait && ['planning', 'refining'].includes(j.status)) j = { ...j, status: 'awaiting_brief' };
256
- else if (j && scene?.briefWrite && j.status === 'planning') j = { ...j, status: 'refining' };
257
- // job and XP
258
- if (j) {
259
- const tasks = jobTasks(s, j);
260
- // progress is completed tasks of all tasks, nothing weighted; the running task is told in words
261
- const done = tasks.filter((t) => t.status === 'done' || t.status === 'skipped').length;
262
- const runningTasks = tasks.filter((t) => t.status === 'running' || t.status === 'review');
263
- const running = runningTasks.length;
264
- const total = tasks.length;
265
- const pct = j.status === 'done' ? 100 : total ? Math.round((done / total) * 100) : 0;
266
- hud.req.textContent = j.request;
267
- hud.req.title = j.request;
268
- hud.xpFill.style.width = `${pct}%`;
269
- hud.xp.setAttribute('aria-valuenow', String(pct));
270
- hud.xpLv.textContent = `${pct}%`;
271
- paintTimeline(tasks);
272
- hud.xpText.textContent = {
273
- refining: 'Mel is writing a clear brief from your request',
274
- awaiting_brief: 'Mel waits for you: check the brief in its window',
275
- planning: 'Mel is writing the plan on the board',
276
- }[j.status] || `${done} of ${total} tasks done${running ? `. Now: ${nowLine(s, runningTasks[0])}${running > 1 ? ` (+${running - 1} more)` : ''}` : ''}`;
277
- hud.state.textContent = { refining: 'Brief', awaiting_brief: 'Waiting for you', planning: 'Planning', running: 'Working', done: 'Done', failed: 'Failed', cancelled: 'Cancelled' }[j.status] || j.status;
278
- hud.state.dataset.s = j.status;
279
- } else {
280
- hud.req.textContent = 'No job yet. Ask the crew in the box above.';
281
- hud.xpFill.style.width = '0%';
282
- hud.xpLv.textContent = '0%';
283
- hud.xpText.textContent = 'Each task of a job is one segment of the timeline.';
284
- paintTimeline([]);
285
- hud.state.textContent = 'Resting';
286
- hud.state.dataset.s = 'idle';
287
- }
288
- // honey
289
- const honey = doneCount(s);
290
- if (shownHoney == null || honey < shownHoney || reducedMotion() || mode !== 'office') shownHoney = honey;
291
- else if (honey > shownHoney) { clearTimeout(honeyTimer); honeyTimer = setTimeout(() => { shownHoney = doneCount(S()); paintHoney(); }, 1800); }
292
- paintHoney();
293
- paintClock();
294
- // queue, the honest part: one model, workers take turns
295
- clear(hud.queue);
296
- const running = s.queue.running || [];
297
- const waiting = s.queue.waiting || [];
298
- hud.queue.append(h('div', { class: 'of-k', text: 'Turn on the model' }));
299
- const row = h('div', { class: 'of-qrow' });
300
- if (running.length) {
301
- for (const q of running) row.append(h('span', { class: 'of-q of-q-on', title: `${worker(q.workerId).name} has the model now` }, beeAvatar(worker(q.workerId), 26, { ring: true, status: 'thinking' })));
302
- 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: s.tasks[running[0].taskId]?.title || 'thinking' })));
303
- }
304
- else row.append(h('span', { class: 'of-faint small', text: 'The model is free' }));
305
- if (waiting.length) {
306
- 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>' }));
307
- for (const q of waiting.slice(0, 6)) row.append(h('span', { class: 'of-q', title: `${worker(q.workerId).name} is in the queue` }, beeAvatar(worker(q.workerId), 22, { ring: true })));
308
- if (waiting.length > 6) row.append(h('span', { class: 'of-faint small', text: `+${waiting.length - 6}` }));
309
- }
310
- hud.queue.append(row, h('div', { class: 'of-faint tiny', text: (s.brains || []).length > 1 ? `${s.brains.length} brains attached, so ${s.brains.length} bees can think at once.` : 'One shared model: the bees take turns, so a job takes minutes.' }));
311
- // nothing hired yet / no state yet
312
- hud.empty.hidden = !!(s.crew || []).length;
313
- hud.empty.textContent = ui.hello ? 'The office is empty.' : 'Opening the office...';
314
- }
315
-
316
- /** The running task in words: who does what right now, from the worker's real status. */
317
- function nowLine(s, t) {
318
- if (!t) return '';
319
- const w = worker(t.assignee);
320
- const st = s.workers?.[t.assignee] || {};
321
- const what = { thinking: 'is thinking about', tool: 'is working on', queued: 'waits for the model for', waiting_approval: 'waits for your approval on' }[st.status] || (t.status === 'review' ? 'reviews' : 'works on');
322
- return `${w.name} ${what} "${t.title}"`;
323
- }
324
-
325
- function paintClock() {
326
- const hr = hourNow();
327
- const hh = Math.floor(hr); const mm = Math.floor((hr % 1) * 60);
328
- hud.clock.textContent = `${dayPhase(hr)} · ${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}`;
329
- }
330
-
331
- function paintHoney() { if (hud.honeyN) hud.honeyN.textContent = String(shownHoney ?? 0); }
332
- function bumpHoney() {
333
- const real = doneCount(S());
334
- shownHoney = Math.min(real, (shownHoney ?? 0) + 1);
335
- paintHoney();
336
- }
337
-
338
- /** The segmented timeline: one segment per task of the job, in order, colored by its state. */
339
- function paintTimeline(tasks) {
340
- if (!hud.segs) return;
341
- const key = tasks.map((t) => `${t.id}:${t.status}`).join('|');
342
- if (hud.segs._key === key) return;
343
- hud.segs._key = key;
344
- clear(hud.segs);
345
- for (const t of tasks) hud.segs.append(h('i', { dataset: { s: t.status }, title: `${t.title}: ${TASK_LABEL[t.status] || t.status}` }));
346
- }
347
-
348
- /* activity feed: short, human lines from real events */
349
- function feed(ev) {
350
- if (!hud.feed) return;
351
- const d = ev.data || {};
352
- const s = S();
353
- const name = (id) => worker(id).name;
354
- let line = null; let tone = '';
355
- switch (ev.type) {
356
- case 'job.created': line = 'New job on the board'; tone = 'honey'; break;
357
- case 'job.planned': line = `Mel planned ${d.tasks?.length || 0} tasks`; break;
358
- case 'brief.proposed': line = 'Mel wrote a brief: use it, edit it or keep yours'; tone = 'warn'; break;
359
- case 'brief.approved': line = d.source === 'original' ? 'Working from your words' : 'Brief approved, planning'; break;
360
- case 'task.status': {
361
- const t = s.tasks[d.taskId];
362
- if (!t) break;
363
- if (d.status === 'running') line = `${name(t.assignee)} started "${t.title}"`;
364
- else if (d.status === 'done') { line = `${name(t.assignee)} finished "${t.title}"`; tone = 'ok'; }
365
- else if (d.status === 'failed') { line = `${name(t.assignee)} is stuck on "${t.title}"`; tone = 'bad'; }
366
- break;
367
- }
368
- case 'file.changed': line = `${name(d.workerId)} ${d.op === 'create' ? 'wrote' : d.op === 'delete' ? 'deleted' : 'edited'} ${d.path}`; break;
369
- case 'approval.requested': line = `${name(d.approval?.workerId)} waits for your approval`; tone = 'warn'; break;
370
- case 'qa.report': line = d.passed ? 'QA: all checks passed' : `QA found ${d.issues?.length || 0} issue${d.issues?.length === 1 ? '' : 's'}`; tone = d.passed ? 'ok' : 'bad'; break;
371
- case 'task.updated': if (d.task?.assignee) line = `Task handed to ${name(d.task.assignee)}`; break;
372
- case 'crew.hired': if (ui.hello && !d.worker?.builtin) { line = `${d.worker?.name} joined the crew`; tone = 'honey'; } break;
373
- case 'job.done': line = 'Job complete'; tone = 'ok'; break;
374
- default: break;
375
- }
376
- if (!line) return;
377
- const li = h('li', { dataset: { tone } }, h('span', { class: 'of-dot' }), h('span', { text: line }));
378
- hud.feed.prepend(li);
379
- while (hud.feed.children.length > 5) hud.feed.lastChild.remove();
380
- if (!reducedMotion() && mode === 'office') li.animate([{ opacity: 0, transform: 'translateY(-4px)' }, { opacity: 1, transform: 'none' }], { duration: 200, easing: 'cubic-bezier(.2,0,0,1)' });
381
- }
382
-
383
- function banner(ev) {
384
- const b = hud.banner;
385
- clear(b);
386
- // a calm activity toast: a check, the summary and one action
387
- b.append(h('span', { class: 'of-jar of-jar-big', html: CHECK_SVG, 'aria-hidden': 'true' }),
388
- h('div', {}, h('strong', { text: 'Job complete' }), h('div', { class: 'of-faint', text: String(ev.data?.summary || 'The crew finished the job.').slice(0, 140) })),
389
- h('button', { type: 'button', class: 'btn btn-xs btn-quiet', text: 'Open preview', on: { click: () => { setMode('desktop'); wm.open('preview'); } } }));
390
- b.hidden = false;
391
- 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)' });
392
- clearTimeout(b._t);
393
- b._t = setTimeout(() => { b.hidden = true; }, 7000);
394
- }
395
-
396
- /* ---------- the DOM layer over the canvas: focus, hover, click, menus, drag ---------- */
397
- function syncHits(sc) {
398
- const s = S();
399
- // bees
400
- const seen = new Set();
401
- for (const hit of sc.hits) {
402
- seen.add(hit.id);
403
- let b = bees.get(hit.id);
404
- if (!b) b = makeBee(hit.id);
405
- const tx = Math.round(hit.x); const ty = Math.round(hit.y);
406
- if (b._x !== tx || b._y !== ty || b._w !== Math.round(hit.w)) {
407
- b._x = tx; b._y = ty; b._w = Math.round(hit.w);
408
- b.style.transform = `translate(${tx}px, ${ty}px)`;
409
- b.style.width = `${Math.round(hit.w)}px`;
410
- b.style.height = `${Math.round(hit.h)}px`;
411
- }
412
- const a = sc.actors.get(hit.id);
413
- const label = beeLabel(hit.id, a, s);
414
- if (b._label !== label) { b._label = label; b.setAttribute('aria-label', label); if (tip.dataset.for === `bee:${hit.id}`) showTip(b, hit.id); }
415
- }
416
- for (const [id, b] of bees) if (!seen.has(id)) { b.remove(); bees.delete(id); }
417
- // notes
418
- const nseen = new Set();
419
- for (const hit of sc.noteHits) {
420
- nseen.add(hit.id);
421
- let n = notes.get(hit.id);
422
- if (!n) n = makeNote(hit.id);
423
- const tx = Math.round(hit.x); const ty = Math.round(hit.y);
424
- if (n._x !== tx || n._y !== ty) {
425
- n._x = tx; n._y = ty;
426
- n.style.transform = `translate(${tx}px, ${ty}px)`;
427
- n.style.width = `${Math.round(hit.w)}px`;
428
- n.style.height = `${Math.round(hit.h)}px`;
429
- }
430
- const t = s.tasks[hit.id];
431
- const label = t ? `Task: ${t.title}. ${TASK_LABEL[t.status] || t.status}. Assigned to ${worker(t.assignee).name}. Enter to hand it to another bee.` : 'Task';
432
- if (n._label !== label) { n._label = label; n.setAttribute('aria-label', label); }
433
- }
434
- for (const [id, n] of notes) if (!nseen.has(id) && !(drag && drag.taskId === id)) { n.remove(); notes.delete(id); }
435
- }
436
-
437
- function beeLabel(id, a, s) {
438
- const w = worker(id);
439
- const st = s.workers[id] || { status: 'idle' };
440
- const t = st.taskId && s.tasks[st.taskId];
441
- const m = a ? (a.seg ? 'fly' : a.mode) : 'idle';
442
- const lv = levelOf(s, id);
443
- return `${w.name}, ${w.role || 'worker'}${lv != null ? `, level ${lv}` : ''}. ${w.paused ? 'Paused' : MODE_LABEL[m] || STATUS_LABEL[st.status] || st.status}${t ? `. Task: ${t.title}` : ''}. Enter to chat.`;
444
- }
445
-
446
- function makeBee(id) {
447
- const b = h('button', { type: 'button', class: 'of-bee', 'aria-describedby': 'of-tip', dataset: { id } });
448
- b.addEventListener('click', () => { if (!drag) wm.open('worker', id); });
449
- b.addEventListener('pointerenter', () => { scene.highlight = id; showTip(b, id); });
450
- b.addEventListener('pointerleave', () => { if (scene.highlight === id) scene.highlight = null; hideTip(); });
451
- b.addEventListener('focus', () => { scene.highlight = id; showTip(b, id); });
452
- b.addEventListener('blur', () => { if (scene.highlight === id) scene.highlight = null; hideTip(); });
453
- menu.provide(b, () => beeMenu(id));
454
- hitLayer.append(b);
455
- bees.set(id, b);
456
- return b;
457
- }
458
-
459
- function beeMenu(id) {
460
- const w = worker(id);
461
- const s = S();
462
- const st = s.workers[id] || {};
463
- const mine = Object.values(s.tasks).filter((t) => t.assignee === id);
464
- const retryable = mine.filter((t) => ['failed', 'blocked'].includes(t.status)).pop() || (st.taskId && s.tasks[st.taskId]);
465
- return [
466
- { header: `${w.name} · ${w.role || 'worker'}${levelOf(s, id) != null ? ` · level ${levelOf(s, id)}` : ''}` },
467
- { label: `Chat with ${w.name}`, icon: 'chat', action: () => wm.open('worker', id) },
468
- { label: w.paused ? 'Resume' : 'Pause', icon: w.paused ? 'arrow' : 'stop', disabled: !!ui.replay, action: () => act.pauseWorker(id, !w.paused) },
469
- { label: retryable ? `Retry "${retryable.title}"` : 'Retry (nothing to retry)', icon: 'replay', disabled: !retryable || !!ui.replay, action: () => act.retryTask(retryable.id) },
470
- { label: 'Open files', icon: 'folder', action: () => { setMode('desktop'); wm.open('files'); } },
471
- ];
472
- }
473
-
474
- function makeNote(id) {
475
- const n = h('button', { type: 'button', class: 'of-note', 'aria-describedby': 'of-tip', dataset: { id } });
476
- n.addEventListener('pointerenter', () => { scene.highlight = id; showNoteTip(n, id); });
477
- n.addEventListener('pointerleave', () => { if (scene.highlight === id) scene.highlight = null; hideTip(); });
478
- n.addEventListener('focus', () => { scene.highlight = id; showNoteTip(n, id); });
479
- n.addEventListener('blur', () => { if (scene.highlight === id) scene.highlight = null; hideTip(); });
480
- n.addEventListener('click', (e) => {
481
- if (n._dragged) { n._dragged = false; return; }
482
- const r = n.getBoundingClientRect();
483
- menu.open({ x: e.clientX || r.left + 10, y: e.clientY || r.bottom, items: noteMenu(id) });
484
- });
485
- n.addEventListener('pointerdown', (e) => startDrag(e, n, id));
486
- menu.provide(n, () => noteMenu(id));
487
- hitLayer.append(n);
488
- notes.set(id, n);
489
- return n;
490
- }
491
-
492
- function noteMenu(id) {
493
- const s = S();
494
- const t = s.tasks[id];
495
- if (!t) return null;
496
- const off = !!ui.replay || t.status === 'done';
497
- return [
498
- { header: t.title },
499
- { label: 'Hand to', icon: 'hire', disabled: off, items: s.crew.filter((w) => w.id !== t.assignee).map((w) => ({ label: `${w.name} (${w.role || 'worker'})`, iconEl: beeAvatar(w, 18, { ring: false }), action: () => reassign(id, w.id) })) },
500
- { label: 'Retry', icon: 'replay', disabled: !!ui.replay || !['failed', 'blocked', 'done', 'skipped'].includes(t.status), action: () => act.retryTask(id) },
501
- { label: 'Cancel task', icon: 'x', danger: true, disabled: !!ui.replay || ['done', 'skipped'].includes(t.status), action: () => act.cancelTask(id) },
502
- ];
503
- }
504
-
505
- function reassign(taskId, workerId) {
506
- const t = S().tasks[taskId];
507
- if (!t || t.assignee === workerId) return;
508
- act.reassignTask(taskId, workerId);
509
- }
510
-
511
- function startDrag(e, el, id) {
512
- if (e.button !== 0 || ui.replay) return;
513
- const t = S().tasks[id];
514
- if (!t || t.status === 'done') return;
515
- const x0 = e.clientX; const y0 = e.clientY;
516
- let ghost = null;
517
- const move = (ev) => {
518
- if (!drag && Math.hypot(ev.clientX - x0, ev.clientY - y0) < 6) return;
519
- if (!drag) {
520
- drag = { taskId: id, el };
521
- scene.dragTask = id;
522
- ghost = h('div', { class: 'of-drag', 'aria-hidden': 'true' }, h('i', { style: `background:${worker(t.assignee).color}` }), h('span', { text: t.title }));
523
- layer.append(ghost);
524
- layer.classList.add('of-dragging');
525
- hideTip();
526
- }
527
- const lr = layer.getBoundingClientRect();
528
- ghost.style.transform = `translate(${ev.clientX - lr.left + 8}px, ${ev.clientY - lr.top + 8}px) rotate(-4deg)`;
529
- const over = beeAt(ev.clientX, ev.clientY);
530
- scene.highlight = over || null;
531
- drag.over = over;
532
- };
533
- const up = () => {
534
- removeEventListener('pointermove', move);
535
- removeEventListener('pointerup', up);
536
- removeEventListener('pointercancel', up);
537
- if (!drag) return;
538
- el._dragged = true;
539
- const target = drag.over;
540
- ghost?.remove();
541
- layer.classList.remove('of-dragging');
542
- scene.dragTask = null;
543
- scene.highlight = null;
544
- drag = null;
545
- if (target) reassign(id, target);
546
- };
547
- addEventListener('pointermove', move);
548
- addEventListener('pointerup', up);
549
- addEventListener('pointercancel', up);
550
- }
551
-
552
- function cancelDrag() {
553
- layer.querySelector('.of-drag')?.remove();
554
- layer.classList.remove('of-dragging');
555
- scene.dragTask = null;
556
- scene.highlight = null;
557
- drag = null;
558
- }
559
-
560
- function beeAt(x, y) {
561
- for (const [id, b] of bees) {
562
- const r = b.getBoundingClientRect();
563
- if (x >= r.left - 6 && x <= r.right + 6 && y >= r.top - 6 && y <= r.bottom + 6) return id;
564
- }
565
- return null;
566
- }
567
-
568
- function showTip(el, id) {
569
- const s = S();
570
- const w = worker(id);
571
- const a = scene.actors.get(id);
572
- const st = s.workers[id] || { status: 'idle' };
573
- const t = st.taskId && s.tasks[st.taskId];
574
- const m = a ? (a.seg ? 'fly' : a.mode) : 'idle';
575
- const lastTask = t || Object.values(s.tasks).filter((x) => x.assignee === id && x.status === 'running').pop();
576
- const done = Object.values(s.tasks).filter((x) => x.assignee === id && x.status === 'done').length;
577
- clear(tip);
578
- tip.append(
579
- h('div', { class: 'of-tip-h' }, beeAvatar(w, 30, { ring: true }), h('div', {}, h('strong', { text: w.name }), h('div', { class: 'of-faint', text: w.role || 'worker' })), levelOf(s, id) != null ? h('span', { class: 'of-lv', text: `L${levelOf(s, id)}` }) : null),
580
- h('div', { class: 'of-tip-r' }, h('span', { class: 'of-faint', text: 'Status' }), h('span', { text: w.paused ? 'Paused' : MODE_LABEL[m] || STATUS_LABEL[st.status] || st.status })),
581
- h('div', { class: 'of-tip-r' }, h('span', { class: 'of-faint', text: 'Task' }), h('span', { text: lastTask ? lastTask.title : 'None right now' })),
582
- h('div', { class: 'of-tip-r' }, h('span', { class: 'of-faint', text: 'Done' }), h('span', { text: `${done} task${done === 1 ? '' : 's'}` })),
583
- h('div', { class: 'of-tip-f', text: 'Click to chat · right click for more' }));
584
- tip.dataset.for = `bee:${id}`;
585
- place(el);
586
- }
587
-
588
- function showNoteTip(el, id) {
589
- const s = S();
590
- const t = s.tasks[id];
591
- if (!t) return;
592
- clear(tip);
593
- tip.append(h('div', { class: 'of-tip-h' }, h('div', {}, h('strong', { text: t.title }), h('div', { class: 'of-faint', text: `${TASK_LABEL[t.status] || t.status} · ${worker(t.assignee).name}` }))),
594
- t.detail ? h('div', { class: 'of-tip-d', text: String(t.detail).slice(0, 180) }) : null,
595
- h('div', { class: 'of-tip-f', text: t.status === 'done' ? 'Done' : 'Drag onto a bee to hand it over · Enter for options' }));
596
- tip.dataset.for = `note:${id}`;
597
- place(el);
598
- }
599
-
600
- function place(el) {
601
- const r = el.getBoundingClientRect();
602
- const lr = layer.getBoundingClientRect();
603
- tip.classList.add('on');
604
- const tr = tip.getBoundingClientRect();
605
- let x = r.left - lr.left + r.width / 2 - tr.width / 2;
606
- let y = r.top - lr.top - tr.height - 10;
607
- if (y < 8) y = r.bottom - lr.top + 10;
608
- x = Math.max(8, Math.min(lr.width - tr.width - 8, x));
609
- tip.style.transform = `translate(${Math.round(x)}px, ${Math.round(y)}px)`;
610
- }
611
- function hideTip() { tip?.classList.remove('on'); if (tip) tip.dataset.for = ''; }
612
-
613
- /* ---------- glyphs ---------- */
614
- function officeGlyph() {
615
- 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>' });
616
- }
617
- function miniGlyph() {
618
- 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>' });
619
- }
620
- function pipGlyph() {
621
- 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>' });
622
- }
623
- 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>';