@zaferyalcin/agent-office 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/public/app.js ADDED
@@ -0,0 +1,2034 @@
1
+ // Agent Office front end. No framework, no build step. Polls /api/state every 3 s while the tab is visible.
2
+ (() => {
3
+ 'use strict';
4
+ const $ = (id) => document.getElementById(id);
5
+ const ESC = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
6
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ESC[c]);
7
+ const POLL_MS = 3000, TRACE_MS = 5000, HISTORY_MS = 60000, REPORT_MS = 60000;
8
+ const ACTIVE = new Set(['working', 'idle', 'stalled']);
9
+ const STATE_ORDER = { working: 0, idle: 1, stalled: 2, failed: 3, done: 4 };
10
+ const CHART_COLORS = ['var(--c-1)', 'var(--c-2)', 'var(--c-3)', 'var(--c-4)', 'var(--c-5)', 'var(--c-6)'];
11
+
12
+ function safeGet(key) {
13
+ try { return localStorage.getItem(key); } catch (e) { return null; }
14
+ }
15
+ function safeSet(key, val) {
16
+ try { localStorage.setItem(key, val); } catch (e) { /* storage blocked */ }
17
+ }
18
+ function savedView() {
19
+ const v = safeGet('ao.view');
20
+ return v === 'office' || v === 'studio' || v === 'reports' ? v : 'office';
21
+ }
22
+ function loadSet(key) {
23
+ try { const v = JSON.parse(localStorage.getItem(key) || '[]'); return new Set(Array.isArray(v) ? v : []); }
24
+ catch (e) { return new Set(); }
25
+ }
26
+ function saveSet(key, set) {
27
+ try { localStorage.setItem(key, JSON.stringify([...set])); } catch (e) { /* storage blocked */ }
28
+ }
29
+ function loadMap(key) {
30
+ try {
31
+ const v = JSON.parse(localStorage.getItem(key) || '{}');
32
+ return v && typeof v === 'object' && !Array.isArray(v) ? v : {};
33
+ } catch (e) { return {}; }
34
+ }
35
+ function saveMap(key, obj) {
36
+ try { localStorage.setItem(key, JSON.stringify(obj)); } catch (e) { /* storage blocked */ }
37
+ }
38
+ const S = {
39
+ data: null, lastOk: 0, error: false, paused: false, view: savedView(),
40
+ hours: +(safeGet('ao.hours') || 24), showDone: safeGet('ao.done') === '1',
41
+ q: '', tool: 'all', openRooms: new Set(), openRows: new Set(), openKids: new Set(),
42
+ closedRooms: loadSet('ao.closed'), openQuiet: loadSet('ao.open'), closedQuiet: new Set(),
43
+ dismissed: loadMap('ao.dismissed'), dismissedQuotas: loadMap('ao.quotaDismiss'),
44
+ notify: safeGet('ao.notify') === '1',
45
+ sel: null, trace: null, traceFor: null, tab: 'activity',
46
+ lang: (window.LANGS.some((l) => l.id === safeGet('ao.lang')) && safeGet('ao.lang')) || 'en',
47
+ topo: safeGet('ao.topo') !== '0',
48
+ history: null, historyAt: 0, historyErr: false, historyLoading: false,
49
+ report: null, reportDay: '', reportAt: 0, reportErr: false, reportLoading: false,
50
+ reportClosedWs: new Set(),
51
+ };
52
+ function isDismissed(s) {
53
+ if (!s || s.state !== 'failed') return false;
54
+ const ts = S.dismissed[s.id];
55
+ return typeof ts === 'number' && (s.last || 0) <= ts;
56
+ }
57
+ const effState = (s) => (isDismissed(s) ? 'done' : s.state);
58
+ function pruneDismissed() {
59
+ if (!S.data) return;
60
+ let changed = false;
61
+ for (const s of S.data.sessions) {
62
+ if (typeof S.dismissed[s.id] === 'number' && (s.last || 0) > S.dismissed[s.id]) {
63
+ delete S.dismissed[s.id];
64
+ changed = true;
65
+ }
66
+ }
67
+ if (changed) saveMap('ao.dismissed', S.dismissed);
68
+ }
69
+ function dismissSession(id) {
70
+ const s = byId(id);
71
+ if (!s) return;
72
+ S.dismissed[id] = s.last || now();
73
+ saveMap('ao.dismissed', S.dismissed);
74
+ S.openRows.delete(id);
75
+ render();
76
+ }
77
+ function studioData() {
78
+ if (!S.data) return null;
79
+ if (!S.data.sessions.some(isDismissed)) return S.data;
80
+ const sessions = S.data.sessions.map((s) => (isDismissed(s) ? { ...s, state: 'done', ended_badly: true } : s));
81
+ return { ...S.data, sessions };
82
+ }
83
+ let studio = null, studioLoading = false, pollTimer = null, traceTimer = null, reportsTimer = null;
84
+ let prevStates = null, prevLowQuotas = null;
85
+ const notifiedKeys = new Set();
86
+ let demoSimScheduled = false, demoSimDone = false, demoSimTimer = null;
87
+ let copiedTimer = null, repCopied = false;
88
+ let quotaPlotMeta = null;
89
+
90
+ // ---------------------------------------------------------------- text and formatting
91
+ function t(key, vars) {
92
+ const d = window.I18N[S.lang] || window.I18N.en;
93
+ let s = d[key] != null ? d[key] : (window.I18N.en[key] != null ? window.I18N.en[key] : key);
94
+ if (vars) for (const k in vars) s = s.split('{' + k + '}').join(vars[k]);
95
+ return s;
96
+ }
97
+ const locale = () => (window.LANGS.find((l) => l.id === S.lang) || window.LANGS[0]).locale;
98
+ function num(n) {
99
+ n = n || 0;
100
+ if (n >= 1e9) return (n / 1e9).toFixed(2) + ' B';
101
+ if (n >= 1e6) return (n / 1e6).toFixed(n >= 1e8 ? 0 : 1) + ' M';
102
+ if (n >= 1e4) return Math.round(n / 1e3) + ' k';
103
+ if (n >= 1e3) return (n / 1e3).toFixed(1) + ' k';
104
+ return String(Math.round(n));
105
+ }
106
+ function dur(ms) {
107
+ ms = Math.max(0, ms || 0);
108
+ const s = Math.floor(ms / 1000), m = Math.floor(s / 60), h = Math.floor(m / 60), d = Math.floor(h / 24);
109
+ const u = (k) => t('unit.' + k);
110
+ if (d) return d + u('d') + ' ' + (h % 24) + u('h');
111
+ if (h) return h + u('h') + ' ' + (m % 60) + u('m');
112
+ if (m) return m + u('m');
113
+ return s + u('s');
114
+ }
115
+ function shortDur(ms) {
116
+ ms = Math.max(0, ms || 0);
117
+ const s = Math.floor(ms / 1000), m = Math.floor(s / 60), h = Math.floor(m / 60), d = Math.floor(h / 24);
118
+ const u = (k) => t('unit.' + k);
119
+ if (d) return d + u('d');
120
+ if (h) return h + u('h');
121
+ if (m) return m + u('m');
122
+ return s + u('s');
123
+ }
124
+ const now = () => (S.data ? S.data.now + (Date.now() - S.lastOk) : Date.now());
125
+ const ago = (ts) => (ts ? t('insp.ago', { d: dur(now() - ts) }) : '');
126
+ const hhmm = (d) => d.toLocaleTimeString(locale(), { hour: '2-digit', minute: '2-digit', hour12: false });
127
+ // exact local reset time: "today 23:51", "tomorrow 03:40", or "Thu 10 Dec 23:17"
128
+ function when(ts) {
129
+ const d = new Date(ts), n = new Date(now());
130
+ const day = (x) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();
131
+ const diff = Math.round((day(d) - day(n)) / 864e5);
132
+ if (diff === 0) return t('quota.today') + ' ' + hhmm(d);
133
+ if (diff === 1) return t('quota.tomorrow') + ' ' + hhmm(d);
134
+ return d.toLocaleDateString(locale(), { weekday: 'short', day: 'numeric', month: 'short' }) + ' ' + hhmm(d);
135
+ }
136
+ // past reset time: "07:40" if today, otherwise "Sat 5 Dec 07:40"
137
+ function resetTime(ts) {
138
+ const d = new Date(ts), n = new Date(now());
139
+ const day = (x) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();
140
+ if (day(d) === day(n)) return hhmm(d);
141
+ return d.toLocaleDateString(locale(), { weekday: 'short', day: 'numeric', month: 'short' }) + ' ' + hhmm(d);
142
+ }
143
+ function fullTime(ts) { return ts ? new Date(ts).toLocaleString(locale(), { dateStyle: 'medium', timeStyle: 'short', hour12: false }) : ''; }
144
+ // "claude-opus-5-5" -> "Claude Opus 5.5", "gemini-4-neon-high" -> "Gemini 4 Neon High", "gpt-5-codex" -> "GPT-5 Codex"
145
+ function modelName(m) {
146
+ if (!m) return '';
147
+ const parts = String(m).replace(/\[.*\]$/, '').split(/[-_ ]/).filter(Boolean);
148
+ const out = [];
149
+ for (let i = 0; i < parts.length; i++) {
150
+ const p = parts[i];
151
+ if (/^\d+$/.test(p) && out.length && /^\d+(\.\d+)?$/.test(out[out.length - 1]) && p.length <= 2 && !/\./.test(out[out.length - 1])) { out[out.length - 1] += '.' + p; continue; }
152
+ if (/^gpt$/i.test(p)) { out.push('GPT'); continue; }
153
+ if (/^o\d/i.test(p) || /^\d{8}$/.test(p)) { out.push(p); continue; }
154
+ out.push(p.charAt(0).toUpperCase() + p.slice(1));
155
+ }
156
+ return out.join(' ').replace(/^GPT (\d)/, 'GPT-$1');
157
+ }
158
+ const vClass = (v) => 'v-' + (['anthropic', 'openai', 'google'].includes(v) ? v : 'other');
159
+ function vendorOfModel(m) {
160
+ m = String(m || '').toLowerCase();
161
+ if (m.includes('claude')) return 'anthropic';
162
+ if (/^(gpt|o\d|codex)/.test(m)) return 'openai';
163
+ if (m.includes('gemini') || /neon|carbon|hydrogen/.test(m)) return 'google';
164
+ return 'other';
165
+ }
166
+
167
+ // ---------------------------------------------------------------- data
168
+ async function poll() {
169
+ clearTimeout(pollTimer);
170
+ if (!S.paused && !document.hidden) {
171
+ try {
172
+ const r = await fetch('api/state', { cache: 'no-store' });
173
+ if (!r.ok) throw new Error(r.status);
174
+ S.data = await r.json(); S.lastOk = Date.now(); S.error = false;
175
+ pruneDismissed();
176
+ checkNotifications();
177
+ render();
178
+ } catch (e) { S.error = true; renderLive(); }
179
+ }
180
+ pollTimer = setTimeout(poll, POLL_MS);
181
+ }
182
+ document.addEventListener('visibilitychange', () => {
183
+ if (!document.hidden) {
184
+ poll();
185
+ if (S.view === 'reports') loadReports();
186
+ }
187
+ });
188
+ setInterval(renderLive, 1000);
189
+
190
+ function byId(id) { return S.data && S.data.sessions.find((s) => s.id === id); }
191
+ function visible(s) {
192
+ if (S.tool !== 'all' && s.tool !== S.tool) return false;
193
+ if (S.q) {
194
+ const hay = [s.label, s.name, s.role, s.task, s.tool, s.model, modelName(s.model), s.cwd, s.branch, s.user, s.last_action].join(' ').toLowerCase();
195
+ if (!hay.includes(S.q)) return false;
196
+ }
197
+ return ACTIVE.has(effState(s)) || s.last >= now() - S.hours * 3600e3;
198
+ }
199
+
200
+ // ---------------------------------------------------------------- render
201
+ function render() {
202
+ renderLive(); renderKpis(); renderQuotaBanner(); renderUpdateBanner(); renderChips(); renderTopo(); renderRooms(); renderSide();
203
+ if (studio) studio.update(studioData());
204
+ if (S.view === 'reports') renderReports();
205
+ }
206
+ function renderLive() {
207
+ const el = $('live');
208
+ el.classList.toggle('off', S.error); el.classList.toggle('paused', S.paused);
209
+ $('liveText').textContent = S.paused ? t('live.paused') : S.error ? t('live.off') : S.lastOk ? t('live.updated', { s: dur(Date.now() - S.lastOk) }) : t('live.connecting');
210
+ }
211
+ function renderKpis() {
212
+ const T = S.data.totals;
213
+ // short label under the number, the full explanation in the tooltip
214
+ const k = (v, key, cls) => '<div class="kpi' + (cls ? ' ' + cls : '') + '" title="' + esc(t(key + '.tip')) + '"><b>' + esc(v) + '</b><span>' + esc(t(key)) + '</span></div>';
215
+ setHTML($('kpis'), k(T.working, 'kpi.working') + k(T.idle, 'kpi.idle') + k(T.stalled.length, 'kpi.stalled', T.stalled.length ? 'alert' : '') +
216
+ k(num(T.tokens_today), 'kpi.today') + k(num(T.rate_per_min), 'kpi.rate'));
217
+ }
218
+ function renderChips() {
219
+ const tools = S.data.providers.filter((p) => p.available && p.sessions);
220
+ if (tools.length < 2) { setHTML($('toolChips'), ''); return; }
221
+ const chip = (id, label, n) => '<button class="chip" data-tool="' + esc(id) + '" aria-pressed="' + (S.tool === id) + '">' + esc(label) + (n != null ? '<span class="n">' + n + '</span>' : '') + '</button>';
222
+ const counts = {};
223
+ for (const s of S.data.sessions) if (ACTIVE.has(effState(s))) counts[s.tool] = (counts[s.tool] || 0) + 1;
224
+ setHTML($('toolChips'), chip('all', t('all')) + ' ' + tools.map((p) => chip(p.label, p.label, counts[p.label] || 0)).join(' '));
225
+ }
226
+
227
+ function userInitials(name) {
228
+ const clean = String(name || '').split('@')[0].trim();
229
+ const parts = clean.split(/[\s._-]+/).filter(Boolean);
230
+ if (!parts.length) return '?';
231
+ if (parts.length >= 2) return (Array.from(parts[0])[0] + Array.from(parts[parts.length - 1])[0]).toUpperCase();
232
+ return Array.from(parts[0]).slice(0, 2).join('').toUpperCase();
233
+ }
234
+ function peopleHtml(users) {
235
+ if (!users.length) return '';
236
+ const tip = users.join(', ');
237
+ if (users.length === 1) {
238
+ return '<span class="room-people" title="' + esc(tip) + '">' +
239
+ '<span class="avatar-init" aria-hidden="true">' + esc(userInitials(users[0])) + '</span>' +
240
+ '<span class="person-name">' + esc(users[0]) + '</span></span>';
241
+ }
242
+ const shown = users.slice(0, 4);
243
+ const extra = users.length > 4 ? '<span class="avatar-more">+' + (users.length - 4) + '</span>' : '';
244
+ return '<span class="room-people" title="' + esc(tip) + '" aria-label="' + esc(tip) + '">' +
245
+ '<span class="avatar-stack" aria-hidden="true">' +
246
+ shown.map((u) => '<span class="avatar-init">' + esc(userInitials(u)) + '</span>').join('') +
247
+ '</span>' + extra + '</span>';
248
+ }
249
+ function toolAbbr(tool) {
250
+ const l = String(tool || '').toLowerCase();
251
+ if (l.includes('claude')) return 'CC';
252
+ if (l.includes('codex')) return 'CX';
253
+ if (l.includes('gemini')) return 'GC';
254
+ if (l.includes('antigravity') || l.includes('agy')) return 'AG';
255
+ const parts = String(tool || '').trim().split(/[\s_-]+/).filter(Boolean);
256
+ if (parts.length >= 2) return (Array.from(parts[0])[0] + Array.from(parts[1])[0]).toUpperCase();
257
+ return Array.from(String(tool || '?')).slice(0, 2).join('').toUpperCase();
258
+ }
259
+ function vendorStripHtml(own) {
260
+ const order = ['anthropic', 'openai', 'google', 'other'];
261
+ const counts = { anthropic: 0, openai: 0, google: 0, other: 0 };
262
+ for (const s of own) {
263
+ const v = s.vendor || vendorOfModel(s.model);
264
+ counts[order.includes(v) ? v : 'other']++;
265
+ }
266
+ const segs = order.filter((v) => counts[v] > 0)
267
+ .map((v) => '<i class="' + vClass(v) + '" style="flex:' + counts[v] + '"></i>').join('');
268
+ return segs ? '<span class="tile-strip" aria-hidden="true">' + segs + '</span>' : '';
269
+ }
270
+ function toolTagsHtml(own) {
271
+ const seen = new Map();
272
+ for (const s of own) {
273
+ const tool = s.tool || '';
274
+ if (!tool || seen.has(tool)) continue;
275
+ seen.set(tool, s.vendor || vendorOfModel(s.model));
276
+ }
277
+ const list = [...seen.entries()].slice(0, 4);
278
+ if (!list.length) return '';
279
+ return '<span class="tile-tools">' + list.map(([tool, v]) =>
280
+ '<span class="tile-tool ' + vClass(v) + '" title="' + esc(tool) + '">' + esc(toolAbbr(tool)) + '</span>'
281
+ ).join('') + '</span>';
282
+ }
283
+ function sessionTitle(s) {
284
+ return s.label || (s.kind === 'session' ? (s.task || s.tool) : s.name) || s.tool || '';
285
+ }
286
+ function roomAlertReasons(own) {
287
+ const out = [];
288
+ const stalled = own.filter((s) => effState(s) === 'stalled').sort((a, b) => (a.last || 0) - (b.last || 0));
289
+ const failed = own.filter((s) => effState(s) === 'failed').sort((a, b) => (b.last || 0) - (a.last || 0));
290
+ if (stalled.length) {
291
+ const s = stalled[0];
292
+ const perm = /permission/i.test(String(s.last_action || '') + ' ' + String(s.state_why || ''));
293
+ const why = perm ? t('room.why.perm') : t('room.why.quiet', { d: shortDur(Math.max(0, now() - (s.last || s.started || now()))) });
294
+ const who = sessionTitle(s);
295
+ out.push({ cls: 'stalled', text: who ? who + ': ' + why : why, short: why });
296
+ }
297
+ if (failed.length) {
298
+ const s = failed[0];
299
+ const rawWhy = String(s.state_why || '');
300
+ const shortWhy = /abandoned/i.test(rawWhy) ? t('room.why.stopped') : t('room.why.error');
301
+ const why = /^last step failed:/i.test(rawWhy) ? rawWhy : shortWhy;
302
+ const who = sessionTitle(s);
303
+ out.push({ cls: 'failed', text: who ? who + ': ' + why : why, short: shortWhy });
304
+ }
305
+ return out;
306
+ }
307
+ function roomSummaryHtml(c, isQuiet) {
308
+ const parts = [];
309
+ if (c.working) parts.push('<span class="st-w">' + esc(t('room.working', { n: c.working })) + '</span>');
310
+ if (c.idle) parts.push('<span class="st-i">' + esc(t('room.waiting', { n: c.idle })) + '</span>');
311
+ if (c.stalled) parts.push('<span class="st-s">' + esc(t('room.stalled', { n: c.stalled })) + '</span>');
312
+ if (c.failed) parts.push('<span class="st-f">' + esc(t('room.failed', { n: c.failed })) + '</span>');
313
+ if (isQuiet && c.done) parts.push('<span class="st-d">' + esc(t('room.finished', { n: c.done })) + '</span>');
314
+ if (!parts.length) parts.push('<span class="st-d">' + esc(c.total === 1 ? t('room.agent') : t('room.agents', { n: c.total })) + '</span>');
315
+ return parts.join('<span class="room-sep">' + esc(t('list.sep')) + '</span>');
316
+ }
317
+ function roomHeaderHtml(r, kind, expanded, reasons) {
318
+ const name = r.w.id === '~' ? t('room.unknown') : r.w.name;
319
+ const tip = [r.w.path || '', r.branches.length ? t('room.branches') + ': ' + r.branches.join(', ') : ''].filter(Boolean).join('\n');
320
+ const age = r.last ? Math.max(0, now() - r.last) : 0;
321
+ const timeTxt = !r.last ? '' : age < 60e3
322
+ ? (kind === 'quiet' ? t('room.lastActiveNow') : t('room.justNow'))
323
+ : (kind === 'quiet' ? t('room.lastActive', { d: shortDur(age) }) : t('insp.ago', { d: shortDur(age) }));
324
+ const whyHtml = reasons.map((x) => '<span class="room-why ' + x.cls + '">' + mq(esc(x.text)) + '</span>').join('');
325
+ return '<button type="button" class="room-head mqs" data-toggle-room="' + esc(r.w.id) + '" data-room-kind="' + kind + '" aria-expanded="' + expanded + '">' +
326
+ '<span class="room-head-main">' +
327
+ '<span class="room-name"' + (tip ? ' title="' + esc(tip) + '"' : '') + '>' + mq(esc(name)) + '</span>' +
328
+ '<span class="room-summary">' + roomSummaryHtml(r.counts, kind === 'quiet') + '</span>' +
329
+ whyHtml +
330
+ '</span>' +
331
+ '<span class="room-head-meta">' +
332
+ peopleHtml(r.users) +
333
+ (timeTxt ? '<span class="room-time" title="' + esc(fullTime(r.last)) + '">' + esc(timeTxt) + '</span>' : '') +
334
+ '<span class="room-chev" aria-hidden="true" title="' + esc(t(expanded ? 'room.collapse' : 'room.expand')) + '">' + CHEV + '</span>' +
335
+ '</span>' +
336
+ '</button>';
337
+ }
338
+ function renderQuietTile(r, reasons) {
339
+ const name = r.w.id === '~' ? t('room.unknown') : r.w.name;
340
+ const tip = [r.w.path || '', r.branches.length ? t('room.branches') + ': ' + r.branches.join(', ') : ''].filter(Boolean).join('\n');
341
+ const age = r.last ? Math.max(0, now() - r.last) : 0;
342
+ const lastTxt = !r.last ? '' : age < 60e3 ? t('room.lastActiveNow') : t('room.lastActive', { d: shortDur(age) });
343
+ const countTxt = r.own.length === 1 ? t('room.agent') : t('room.agents', { n: r.own.length });
344
+ const metaTxt = [lastTxt, countTxt].filter(Boolean).join(' · ');
345
+ const latest = [...r.own].sort((a, b) => (b.last || 0) - (a.last || 0)).find((s) => s.task || s.label);
346
+ const taskTxt = latest ? (latest.task || latest.label) : '';
347
+ const failReason = reasons.find((x) => x.cls === 'failed');
348
+ const alertCls = r.counts.failed ? ' has-failed' : '';
349
+ return '<section class="room quiet closed' + alertCls + '" data-room="' + esc(r.w.id) + '" aria-label="' + esc(name) + '">' +
350
+ '<button type="button" class="room-head tile-btn mqs" data-toggle-room="' + esc(r.w.id) + '" data-room-kind="quiet" aria-expanded="false">' +
351
+ vendorStripHtml(r.own) +
352
+ '<span class="tile-body">' +
353
+ '<span class="tile-top">' +
354
+ '<span class="room-name"' + (tip ? ' title="' + esc(tip) + '"' : '') + '>' + mq(esc(name)) + '</span>' +
355
+ '<span class="room-chev" aria-hidden="true">' + CHEV + '</span>' +
356
+ '</span>' +
357
+ (failReason ? '<span class="tile-alert failed">' + mq(esc(t('room.failed', { n: r.counts.failed }) + ' · ' + failReason.short)) + '</span>' : '') +
358
+ (taskTxt ? '<span class="tile-task">' + mq(esc(taskTxt)) + '</span>' : '') +
359
+ '<span class="tile-foot">' +
360
+ '<span class="tile-meta"' + (r.last ? ' title="' + esc(fullTime(r.last)) + '"' : '') + '>' + esc(metaTxt) + '</span>' +
361
+ toolTagsHtml(r.own) +
362
+ '</span>' +
363
+ '</span>' +
364
+ '</button>' +
365
+ '</section>';
366
+ }
367
+ function renderRoomRows(roots, kids, sortFn) {
368
+ let rows = '';
369
+ const add = (s, depth) => {
370
+ const list = (kids.get(s.id) || []).sort(sortFn);
371
+ const kOpen = S.openKids.has(s.id) || !!S.q;
372
+ rows += row(s, depth, list, kOpen);
373
+ if (kOpen) for (const k of list) add(k, depth + 1);
374
+ };
375
+ for (const s of roots) add(s, 0);
376
+ return rows;
377
+ }
378
+
379
+ function renderRooms() {
380
+ const D = S.data;
381
+ const missing = D.providers.filter((p) => p.error).map((p) => p.label + ': ' + p.error);
382
+ const notice = $('notice'); notice.hidden = !missing.length; notice.textContent = missing.join(' ');
383
+ const sessions = D.sessions.filter(visible);
384
+ const ids = new Set(sessions.map((s) => s.id));
385
+ if (!D.sessions.length) {
386
+ setHTML($('rooms'), '<div class="empty"><b>' + esc(t('empty.title')) + '</b><p>' + esc(t('empty.body')) + '</p><p><button class="btn" data-help>' + esc(t('help.btn')) + '</button></p></div>');
387
+ return;
388
+ }
389
+ if (!sessions.length) {
390
+ const canClear = !!S.q || S.tool !== 'all';
391
+ setHTML($('rooms'), '<div class="empty"><b>' + esc(t('empty.filtered')) + '</b><p>' + esc(t('empty.filteredHint')) + '</p>' +
392
+ (canClear ? '<p><button class="btn" data-clear>' + esc(t('empty.clear')) + '</button></p>' : '') + '</div>');
393
+ return;
394
+ }
395
+ const kids = new Map();
396
+ for (const s of sessions) if (s.parent && ids.has(s.parent)) { if (!kids.has(s.parent)) kids.set(s.parent, []); kids.get(s.parent).push(s); }
397
+ const treeActive = (s, d) => ACTIVE.has(effState(s)) || (d < 20 && (kids.get(s.id) || []).some((k) => treeActive(k, d + 1)));
398
+ const treeFailed = (s, d) => effState(s) === 'failed' || (d < 20 && (kids.get(s.id) || []).some((k) => treeFailed(k, d + 1)));
399
+ const sortFn = (a, b) => (STATE_ORDER[effState(a)] - STATE_ORDER[effState(b)]) || (b.last - a.last);
400
+ const roomSort = (a, b) => ((a.w.id === '~' ? 1 : 0) - (b.w.id === '~' ? 1 : 0)) || (b.last - a.last);
401
+ const todayStart = new Date(now()); todayStart.setHours(0, 0, 0, 0);
402
+ const todayMs = todayStart.getTime();
403
+ const rooms = D.workspaces.map((w) => {
404
+ const own = sessions.filter((s) => (s.workspace || '~') === w.id);
405
+ const roots = own.filter((s) => !s.parent || !ids.has(s.parent)).sort(sortFn);
406
+ const activeRoots = roots.filter((r) => treeActive(r, 0));
407
+ const failedRoots = roots.filter((r) => !treeActive(r, 0) && treeFailed(r, 0));
408
+ const doneRoots = roots.filter((r) => !treeActive(r, 0) && !treeFailed(r, 0));
409
+ const counts = { working: 0, idle: 0, stalled: 0, failed: 0, done: 0, total: own.length };
410
+ let last = 0;
411
+ for (const s of own) {
412
+ const st = effState(s);
413
+ if (counts[st] != null) counts[st]++;
414
+ if ((s.last || 0) > last) last = s.last;
415
+ }
416
+ if (!last) last = w.last || 0;
417
+ const users = [...new Set(own.map((s) => s.user).filter(Boolean))];
418
+ const branches = [...new Set(own.map((s) => s.branch).filter((b) => b && b !== 'HEAD'))];
419
+ return { w, own, roots, activeRoots, failedRoots, doneRoots, isActive: activeRoots.length > 0, counts, last, users, branches };
420
+ }).filter((r) => r.own.length);
421
+ const activeRooms = rooms.filter((r) => r.isActive).sort(roomSort);
422
+ const quietRooms = rooms.filter((r) => !r.isActive).sort(roomSort);
423
+ let html = '';
424
+ if (activeRooms.length) {
425
+ let cards = '';
426
+ for (const r of activeRooms) {
427
+ const expanded = !!S.q || !S.closedRooms.has(r.w.id);
428
+ const showFinished = S.showDone || S.openRooms.has(r.w.id) || !!S.q;
429
+ const reasons = roomAlertReasons(r.own);
430
+ const alertCls = r.counts.stalled ? ' alarm' : (r.counts.failed ? ' has-failed' : '');
431
+ const visibleRoots = [...r.activeRoots, ...r.failedRoots, ...(showFinished ? r.doneRoots : [])];
432
+ const rows = expanded ? renderRoomRows(visibleRoots, kids, sortFn) : '';
433
+ const doneCount = r.doneRoots.length;
434
+ const allToday = doneCount > 0 && r.doneRoots.every((s) => (s.last || 0) >= todayMs);
435
+ const moreLabel = showFinished
436
+ ? (doneCount === 1 ? t('room.doneHide1') : t('room.doneHide', { n: doneCount }))
437
+ : allToday
438
+ ? (doneCount === 1 ? t('room.doneTodayShow1') : t('room.doneTodayShow', { n: doneCount }))
439
+ : (doneCount === 1 ? t('room.doneShow1') : t('room.doneShow', { n: doneCount }));
440
+ const name = r.w.id === '~' ? t('room.unknown') : r.w.name;
441
+ cards += '<section class="room active ' + (expanded ? 'open' : 'closed') + alertCls + '" data-room="' + esc(r.w.id) + '" aria-label="' + esc(name) + '">' +
442
+ roomHeaderHtml(r, 'active', expanded, reasons) +
443
+ (rows ? '<div class="rows" role="list">' + rows + '</div>' : '') +
444
+ (expanded && doneCount && !S.showDone && !S.q ? '<button class="room-more" type="button" data-more="' + esc(r.w.id) + '">' + esc(moreLabel) + '</button>' : '') +
445
+ '</section>';
446
+ }
447
+ html += '<div class="rooms-group rooms-group-active" role="region" aria-labelledby="grpActive">' +
448
+ '<div class="rooms-group-head"><h3 id="grpActive">' + esc(t('rooms.active')) + '</h3><span class="rooms-group-n">' + activeRooms.length + '</span></div>' +
449
+ '<div class="rooms-active-list">' + cards + '</div></div>';
450
+ }
451
+ if (quietRooms.length) {
452
+ let tiles = '';
453
+ for (const r of quietRooms) {
454
+ const expanded = !!S.q || (S.showDone ? !S.closedQuiet.has(r.w.id) : S.openQuiet.has(r.w.id));
455
+ const reasons = roomAlertReasons(r.own);
456
+ if (!expanded) {
457
+ tiles += renderQuietTile(r, reasons);
458
+ } else {
459
+ const alertCls = r.counts.failed ? ' has-failed' : '';
460
+ const name = r.w.id === '~' ? t('room.unknown') : r.w.name;
461
+ const rows = renderRoomRows(r.roots, kids, sortFn);
462
+ tiles += '<section class="room quiet open expanded' + alertCls + '" data-room="' + esc(r.w.id) + '" aria-label="' + esc(name) + '">' +
463
+ roomHeaderHtml(r, 'quiet', true, reasons) +
464
+ (rows ? '<div class="rows" role="list">' + rows + '</div>' : '') +
465
+ '</section>';
466
+ }
467
+ }
468
+ html += '<div class="rooms-group rooms-group-quiet" role="region" aria-labelledby="grpQuiet">' +
469
+ '<div class="rooms-group-head"><h3 id="grpQuiet">' + esc(t('rooms.quiet')) + '</h3><span class="rooms-group-n">' + quietRooms.length + '</span></div>' +
470
+ '<div class="rooms-quiet-grid">' + tiles + '</div></div>';
471
+ }
472
+ setHTML($('rooms'), html);
473
+ }
474
+ // ---------------------------------------------------------------- topology: one band per workspace, nodes with tool avatars
475
+ const NW = 184, NH = 60, HG = 16, VG = 44, PAD = 14, HEAD = 30;
476
+ function toolGlyph(s, cx, cy) {
477
+ const tool = String(s.tool || '').toLowerCase();
478
+ const kind = tool.includes('claude') ? 'claude'
479
+ : tool.includes('codex') ? 'codex'
480
+ : (tool.includes('antigravity') || tool.includes('agy')) ? 'antigravity'
481
+ : tool.includes('gemini') ? 'gemini'
482
+ : s.vendor === 'anthropic' ? 'claude'
483
+ : s.vendor === 'openai' ? 'codex'
484
+ : s.vendor === 'google' ? 'gemini'
485
+ : 'other';
486
+ if (kind === 'claude') {
487
+ // terminal prompt chevron + cursor
488
+ return '<path d="M' + (cx - 5.5) + ' ' + (cy - 3.5) + 'L' + (cx - 1.5) + ' ' + cy + 'L' + (cx - 5.5) + ' ' + (cy + 3.5) +
489
+ 'M' + (cx + 0.5) + ' ' + (cy + 3.5) + 'H' + (cx + 5.5) + '" class="glyph"/>';
490
+ }
491
+ if (kind === 'codex') {
492
+ // geometric code brackets with slash
493
+ return '<path d="M' + (cx - 3) + ' ' + (cy - 4) + 'L' + (cx - 6.5) + ' ' + cy + 'L' + (cx - 3) + ' ' + (cy + 4) +
494
+ 'M' + (cx + 3) + ' ' + (cy - 4) + 'L' + (cx + 6.5) + ' ' + cy + 'L' + (cx + 3) + ' ' + (cy + 4) +
495
+ 'M' + (cx + 1.2) + ' ' + (cy - 4.5) + 'L' + (cx - 1.2) + ' ' + (cy + 4.5) + '" class="glyph"/>';
496
+ }
497
+ if (kind === 'gemini') {
498
+ // architectural twin pillars
499
+ return '<path d="M' + (cx - 5) + ' ' + (cy - 4.5) + 'H' + (cx + 5) +
500
+ 'M' + (cx - 5) + ' ' + (cy + 4.5) + 'H' + (cx + 5) +
501
+ 'M' + (cx - 2.2) + ' ' + (cy - 4.5) + 'V' + (cy + 4.5) +
502
+ 'M' + (cx + 2.2) + ' ' + (cy - 4.5) + 'V' + (cy + 4.5) + '" class="glyph"/>';
503
+ }
504
+ if (kind === 'antigravity') {
505
+ // upward lift chevron + floating orb above a horizon line
506
+ return '<path d="M' + (cx - 4.5) + ' ' + (cy - 0.5) + 'L' + cx + ' ' + (cy - 5) + 'L' + (cx + 4.5) + ' ' + (cy - 0.5) +
507
+ 'M' + (cx - 5) + ' ' + (cy + 5) + 'H' + (cx + 5) + '" class="glyph"/>' +
508
+ '<circle cx="' + cx + '" cy="' + (cy + 1) + '" r="1.4" class="glyph-dot"/>';
509
+ }
510
+ // generic geometric agent node
511
+ return '<path d="M' + cx + ' ' + (cy - 5.5) + 'L' + (cx + 5.5) + ' ' + cy + 'L' + cx + ' ' + (cy + 5.5) + 'L' + (cx - 5.5) + ' ' + cy + 'Z" class="glyph"/>' +
512
+ '<circle cx="' + cx + '" cy="' + cy + '" r="1.4" class="glyph-dot"/>';
513
+ }
514
+ function avatar(s, x, y) {
515
+ // rounded-square vendor tile with geometric tool glyph and corner state badge
516
+ const cx = x + 22, cy = y + NH / 2, bx = cx + 13, by = cy + 13, st = effState(s);
517
+ let badge;
518
+ if (st === 'working') {
519
+ badge = '<circle cx="' + bx + '" cy="' + by + '" r="5" class="badge-cut"/>' +
520
+ '<circle cx="' + bx + '" cy="' + by + '" r="5.4" class="badge-ring"/>' +
521
+ '<circle cx="' + bx + '" cy="' + by + '" r="3.3" class="badge-dot"/>';
522
+ } else if (st === 'stalled') {
523
+ badge = '<circle cx="' + bx + '" cy="' + by + '" r="6.3" class="badge-cut"/>' +
524
+ '<circle cx="' + bx + '" cy="' + by + '" r="5" class="badge-dot"/>' +
525
+ '<path d="M' + bx + ' ' + (by - 2.6) + 'v2.9" class="badge-mark"/>' +
526
+ '<circle cx="' + bx + '" cy="' + (by + 2.3) + '" r="0.85" class="badge-mark-dot"/>';
527
+ } else if (st === 'failed') {
528
+ badge = '<circle cx="' + bx + '" cy="' + by + '" r="6.3" class="badge-cut"/>' +
529
+ '<circle cx="' + bx + '" cy="' + by + '" r="5" class="badge-dot"/>' +
530
+ '<path d="M' + (bx - 2) + ' ' + (by - 2) + 'l4 4m0-4l-4 4" class="badge-mark"/>';
531
+ } else {
532
+ badge = '<circle cx="' + bx + '" cy="' + by + '" r="4.8" class="badge-cut"/>' +
533
+ '<circle cx="' + bx + '" cy="' + by + '" r="3.3" class="badge-dot"/>';
534
+ }
535
+ return '<g class="avatar ' + vClass(s.vendor) + '">' +
536
+ '<rect x="' + (cx - 15) + '" y="' + (cy - 15) + '" width="30" height="30" rx="8" class="avatar-tile"/>' +
537
+ toolGlyph(s, cx, cy) + '</g>' + badge;
538
+ }
539
+ function renderTopo() {
540
+ const wrap = $('topoWrap');
541
+ $('topoBtn').textContent = S.topo ? t('topo.hide') : t('topo.show');
542
+ wrap.classList.toggle('closed', !S.topo);
543
+ if (!S.topo) { setHTML($('topo'), ''); return; }
544
+ const D = S.data, W = Math.max(320, $('topo').clientWidth || 800);
545
+ const perRow = Math.max(1, Math.floor((W - PAD * 2 + HG) / (NW + HG)));
546
+ const all = D.sessions.filter(visible);
547
+ const ids = new Set(all.map((s) => s.id));
548
+ const kids = new Map();
549
+ for (const s of all) if (s.parent && ids.has(s.parent)) { if (!kids.has(s.parent)) kids.set(s.parent, []); kids.get(s.parent).push(s); }
550
+ const live = (s, d) => ACTIVE.has(effState(s)) || (d < 20 && (kids.get(s.id) || []).some((k) => live(k, d + 1)));
551
+ let html = '', shown = 0;
552
+ for (const w of D.workspaces) {
553
+ const roots = all.filter((s) => (s.workspace || '~') === w.id && (!s.parent || !ids.has(s.parent)) && live(s, 0))
554
+ .sort((a, b) => (STATE_ORDER[effState(a)] - STATE_ORDER[effState(b)]) || (a.started - b.started));
555
+ if (!roots.length || shown > 48) continue;
556
+ // levels: roots, their children, grandchildren...; each level wraps into rows that fit the width
557
+ const levels = []; let cur = roots; const parentOf = new Map();
558
+ while (cur.length && levels.length < 6) {
559
+ levels.push(cur);
560
+ const next = [];
561
+ for (const p of cur) for (const k of (kids.get(p.id) || []).filter((k) => ACTIVE.has(effState(k)) || Date.now() - k.last < 3600e3).sort((a, b) => a.started - b.started)) { parentOf.set(k.id, p.id); next.push(k); }
562
+ cur = next;
563
+ }
564
+ const pos = new Map(); let y = HEAD;
565
+ for (const lv of levels) {
566
+ for (let i = 0; i < lv.length; i += perRow) {
567
+ const rowItems = lv.slice(i, i + perRow);
568
+ const rowW = rowItems.length * NW + (rowItems.length - 1) * HG;
569
+ let x = Math.max(PAD, (W - rowW) / 2);
570
+ for (const s of rowItems) { pos.set(s.id, { x, y }); x += NW + HG; shown++; }
571
+ y += NH + (i + perRow < lv.length ? 18 : VG);
572
+ }
573
+ }
574
+ const H = y - VG + PAD + 4;
575
+ let edges = '', nodes = '';
576
+ for (const [cid, pid] of parentOf) {
577
+ const a = pos.get(pid), b = pos.get(cid); if (!a || !b) continue;
578
+ const c = byId(cid), cst = effState(c), x1 = a.x + NW / 2, y1 = a.y + NH, x2 = b.x + NW / 2, y2 = b.y, my = (y1 + y2) / 2;
579
+ const d = 'M' + x1 + ' ' + y1 + ' C' + x1 + ' ' + my + ' ' + x2 + ' ' + my + ' ' + x2 + ' ' + y2;
580
+ const pid2 = 'e' + Math.abs(hashStr(cid));
581
+ edges += '<path id="' + pid2 + '" d="' + d + '" class="edge ' + esc(cst) + '"/>';
582
+ if (cst === 'working') edges += '<circle r="3" class="packet ' + vClass(c.vendor) + '"><animateMotion dur="' + (1.6 + (hashStr(cid) % 10) / 10) + 's" repeatCount="indefinite"><mpath href="#' + pid2 + '"/></animateMotion></circle>';
583
+
584
+ }
585
+ for (const [id, p] of pos) {
586
+ const s = byId(id), st = effState(s);
587
+ // names are trimmed to the card by fitSvgText() after render; the full text is in the node's <title>
588
+ const name = String(s.label || s.name || '').slice(0, 80), sub = String(s.role || modelName(s.model) || s.tool || '').slice(0, 80);
589
+ const alert = st === 'stalled' || st === 'failed';
590
+ const tip = name + (sub ? ' · ' + sub : '') + '\n' + t('state.' + st) + (s.state_why ? ': ' + s.state_why : '') + (s.task ? '\n' + String(s.task).slice(0, 300) : '');
591
+ nodes += '<g class="node ' + esc(st) + (S.sel === id ? ' sel' : '') + '" data-id="' + esc(id) + '" tabindex="0" role="button" aria-label="' + esc((s.label || s.name) + ', ' + t('state.' + st)) + '">' +
592
+ '<title>' + esc(tip) + '</title>' +
593
+ '<rect x="' + p.x + '" y="' + p.y + '" width="' + NW + '" height="' + NH + '" rx="12" class="card"/>' + avatar(s, p.x, p.y) +
594
+ '<text x="' + (p.x + 46) + '" y="' + (p.y + 24) + '" class="nname"><tspan data-fit="' + (NW - 46 - (alert ? 22 : 12)) + '" data-full="' + esc(name) + '">' + esc(name) + '</tspan></text>' +
595
+ '<text x="' + (p.x + 46) + '" y="' + (p.y + 41) + '" class="nsub ' + vClass(s.vendor) + '"><tspan data-fit="' + (NW - 46 - 12) + '" data-full="' + esc(sub) + '">' + esc(sub) + '</tspan></text>' +
596
+ (alert ? '<g class="alert"><circle cx="' + (p.x + NW - 6) + '" cy="' + (p.y + 6) + '" r="9"/><text x="' + (p.x + NW - 6) + '" y="' + (p.y + 10.5) + '" text-anchor="middle">!</text></g>' : '') +
597
+ '</g>';
598
+ }
599
+ html += '<svg class="band" viewBox="0 0 ' + W + ' ' + H + '" width="100%" height="' + H + '" role="group" aria-label="' + esc(w.name) + '">' +
600
+ '<rect x="1" y="1" width="' + (W - 2) + '" height="' + (H - 2) + '" rx="14" class="bandbg"/>' +
601
+ '<text x="' + PAD + '" y="20" class="bandname">' + esc(w.id === '~' ? t('room.unknown') : w.name) + '</text>' + edges + nodes + '</svg>';
602
+ }
603
+ if (setHTML($('topo'), html || '<div class="hint" style="padding:6px 2px 4px">' + esc(t('topo.empty')) + '</div>')) fitSvgText($('topo'));
604
+ }
605
+ function hashStr(s) { let h = 0; for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0; return Math.abs(h); }
606
+ // Trim SVG names to the room left on their card, cutting at a clean point (no trailing space or punctuation
607
+ // before the ellipsis). Measured, so wide scripts (CJK) are trimmed correctly too. Skipped while hidden.
608
+ function fitSvgText(root) {
609
+ for (const ts of root.querySelectorAll('tspan[data-fit]')) {
610
+ const max = +ts.getAttribute('data-fit'), full = ts.getAttribute('data-full') || '';
611
+ if (ts.textContent !== full) ts.textContent = full;
612
+ const w = ts.getComputedTextLength();
613
+ if (!w || w <= max) continue;
614
+ const chars = Array.from(full);
615
+ let n = Math.max(1, Math.floor(chars.length * max / w));
616
+ for (;;) {
617
+ ts.textContent = chars.slice(0, n).join('').replace(/[\s.,;:·\-–—_\/\\|]+$/, '') + '…';
618
+ if (n <= 1 || ts.getComputedTextLength() <= max) break;
619
+ n--;
620
+ }
621
+ }
622
+ }
623
+
624
+ const CHEV = '<svg class="chev" viewBox="0 0 12 12" width="12" height="12" aria-hidden="true"><path d="M4 2.5 7.5 6 4 9.5" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>';
625
+ const WARN_IC = '<svg class="warn-ic" viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><path d="M8 2.2 14.2 13.2H1.8Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/><path d="M8 6.2v3.3" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/><circle cx="8" cy="11.4" r="0.85" fill="currentColor"/></svg>';
626
+ const FOLDER_IC = '<svg viewBox="0 0 16 16" width="15" height="15" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M2 4.2A1.2 1.2 0 0 1 3.2 3h3l1.3 1.5h5.3A1.2 1.2 0 0 1 14 5.7v6.1A1.2 1.2 0 0 1 12.8 13H3.2A1.2 1.2 0 0 1 2 11.8Z"/></svg>';
627
+ const TERM_IC = '<svg viewBox="0 0 16 16" width="15" height="15" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="12" height="10" rx="1.6"/><path d="M5 6.5 7.2 8.2 5 9.9M8.5 10h2.5"/></svg>';
628
+ const CLOSE_IC = '<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"><path d="M4.2 4.2l7.6 7.6M11.8 4.2l-7.6 7.6"/></svg>';
629
+ const PREV_IC = '<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M10 3.5 5.5 8 10 12.5"/></svg>';
630
+ const NEXT_IC = '<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M6 3.5 10.5 8 6 12.5"/></svg>';
631
+ function canOpenSession(s) {
632
+ return !!(S.data && S.data.can_open && s && (s.cwd || (s.workspace && s.workspace !== '~')));
633
+ }
634
+ function openBtnsHtml(s, cls) {
635
+ if (!canOpenSession(s)) return '';
636
+ const fLbl = t('open.folder'), tLbl = t('open.terminal');
637
+ return '<button type="button" class="' + cls + '" data-open-id="' + esc(s.id) + '" data-open-what="folder" aria-label="' + esc(fLbl) + '" title="' + esc(fLbl) + '">' + FOLDER_IC + '</button>' +
638
+ '<button type="button" class="' + cls + '" data-open-id="' + esc(s.id) + '" data-open-what="terminal" aria-label="' + esc(tLbl) + '" title="' + esc(tLbl) + '">' + TERM_IC + '</button>';
639
+ }
640
+ // wrap already-escaped single-line text so fitMarquees() can slide it when it overflows
641
+ const mq = (html) => '<span class="mq">' + html + '</span>';
642
+ function subsPill(list, open) {
643
+ if (!list.length) return '';
644
+ const bad = list.some((k) => { const ks = effState(k); return ks === 'stalled' || ks === 'failed'; });
645
+ const label = list.length === 1 ? t('row.subPlus') : t('row.subsPlus', { n: list.length });
646
+ return '<button class="subs' + (open ? ' open' : '') + (bad ? ' bad' : '') + '" type="button" data-kids="' + esc(list[0].parent) + '" aria-expanded="' + open + '">' +
647
+ esc(label) + '</button>';
648
+ }
649
+ function sameStart(a, b) { const x = String(a || '').replace(/[.…]+$/, '').trim().toLowerCase(); return !!x && String(b || '').trim().toLowerCase().startsWith(x); }
650
+ function detailCell(labelKey, valHtml, title, cls) {
651
+ return '<div class="detail-item"><dt>' + esc(t(labelKey)) + '</dt><dd' +
652
+ (cls ? ' class="' + cls + '"' : '') + (title ? ' title="' + esc(title) + '"' : '') + '>' + valHtml + '</dd></div>';
653
+ }
654
+ function rowDetails(s, stateTxt) {
655
+ const beat = s.activity || [];
656
+ const max = Math.max(1, ...beat);
657
+ const ticks = beat.map((v) => '<i' + (v ? ' class="on" style="height:' + (3 + Math.round((v / max) * 15)) + 'px"' : '') + '></i>').join('');
658
+ const tokSum = (x) => (x ? x.in + x.cache + x.out : 0);
659
+ const treeTok = tokSum(s.tokens_tree), ownTok = tokSum(s.tokens);
660
+ const tokVal = num(treeTok || ownTok);
661
+ const tokTip = s.children && s.children.length && ownTok !== treeTok
662
+ ? t('insp.tokens') + ': ' + num(ownTok) + ' · ' + t('insp.tokensTree') + ': ' + num(treeTok)
663
+ : t('col.tokens.tip');
664
+ const toolText = s.tool ? s.tool + (s.client && s.client !== 'cli' ? ' (' + s.client + ')' : '') : '';
665
+ const mName = modelName(s.model);
666
+ const branch = s.branch && s.branch !== 'HEAD' ? s.branch : '';
667
+ const grid = '<dl class="details-grid">' +
668
+ detailCell('insp.tool', toolText ? mq(esc(toolText)) : '–', toolText, toolText ? '' : 'muted') +
669
+ detailCell('insp.model', mName ? mq(esc(mName)) : '–', s.model || '', mName ? vClass(s.vendor) : 'muted') +
670
+ detailCell('insp.user', s.user ? mq(esc(s.user)) : '–', s.account || s.user || '', s.user ? '' : 'muted') +
671
+ detailCell('insp.branch', branch ? mq(esc(branch)) : '–', branch, branch ? '' : 'muted') +
672
+ detailCell('insp.folder', s.cwd ? mq(esc(s.cwd)) : '–', s.cwd || '', s.cwd ? '' : 'muted') +
673
+ detailCell('insp.started', s.started ? esc(fullTime(s.started)) : '–', s.last ? t('insp.last') + ': ' + ago(s.last) : '', s.started ? '' : 'muted') +
674
+ detailCell('insp.tokens', esc(tokVal), tokTip, '') +
675
+ detailCell('col.beat', beat.length ? '<div class="beat ' + vClass(s.vendor) + '" title="' + esc(t('usage.beat')) + '">' + ticks + '</div>' : '–', beat.length ? t('usage.beat') : '', beat.length ? 'detail-beat' : 'muted') +
676
+ '</dl>';
677
+ const st = effState(s);
678
+ const endedBadly = st === 'done' && (s.ended_badly || isDismissed(s));
679
+ const dismissBtn = st === 'failed'
680
+ ? '<button class="btn small dismiss-btn" type="button" data-dismiss="' + esc(s.id) + '" title="' + esc(t('row.dismiss.tip')) + '">' + esc(t('row.dismiss')) + '</button>'
681
+ : '';
682
+ const whyHtml = (s.state_why || st === 'failed')
683
+ ? '<div class="why ' + esc(st) + (endedBadly ? ' ended-badly' : '') + '">' + (endedBadly ? WARN_IC : '') + '<span>' + esc(stateTxt) + '</span>' + dismissBtn + '</div>'
684
+ : '';
685
+ return '<div class="more">' +
686
+ whyHtml +
687
+ (s.task ? '<div class="more-text"><span class="more-lbl">' + esc(t('row.task')) + '</span><div class="task">' + esc(s.task) + '</div></div>' : '') +
688
+ (s.last_action && s.last_action !== s.task ? '<div class="more-text"><span class="more-lbl">' + esc(t('row.lastAction')) + '</span><div class="act">' + esc(s.last_action) + '</div></div>' : '') +
689
+ grid + '</div>';
690
+ }
691
+ function row(s, depth, list, kOpen) {
692
+ list = list || [];
693
+ const st = effState(s);
694
+ const exp = S.openRows.has(s.id);
695
+ const isSession = s.kind === 'session';
696
+ const title = s.label || (isSession ? (s.task || s.tool) : s.name);
697
+ const second = isSession ? (s.label && s.label !== s.task ? s.task : s.last_action) : s.task;
698
+ const third = isSession && s.label && s.label !== s.task ? s.last_action : (isSession ? '' : s.last_action);
699
+ const nowLine = (!sameStart(title, second) && second) || (!sameStart(title, third) && third) || '';
700
+ const running = (st === 'done' || st === 'failed' ? s.last : now()) - (s.started || s.last);
701
+ const quietDur = dur(Math.max(0, now() - (s.last || s.started || now())));
702
+ const stateTxt = t('state.' + st) + (s.state_why ? ': ' + s.state_why : '');
703
+ const alertState = st === 'stalled' || st === 'failed';
704
+ const why = s.state_why ? String(s.state_why).trim() : '';
705
+ const whyHasQuiet = /\b(quiet|silent|no activity|inactive)\b/i.test(why);
706
+ const quietRight = st === 'stalled' && !whyHasQuiet;
707
+ const subText = alertState && why ? why : nowLine;
708
+ const subCls = alertState && why ? ' ' + esc(st) : '';
709
+ const mName = modelName(s.model);
710
+ const timeText = quietRight ? t('row.quietFor', { d: quietDur }) : dur(running);
711
+ const timeTip = quietRight ? (s.started ? t('insp.started') + ': ' + fullTime(s.started) : '') : (ago(s.last) || t('col.running.tip'));
712
+ return '<div class="agent mqs ' + esc(st) + (depth ? ' child' : '') + (exp ? ' open' : '') + '" role="listitem" tabindex="0" aria-expanded="' + exp + '" data-id="' + esc(s.id) + '" aria-selected="' + (S.sel === s.id) + '"' + (depth ? ' style="--depth:' + depth + '"' : '') + '>' +
713
+ '<span class="mark ' + esc(st) + '" title="' + esc(stateTxt) + '"><span class="sr">' + esc(stateTxt) + '</span></span>' +
714
+ '<div class="who"><div class="agent-head"><b class="agent-name">' + mq(esc(title)) + '</b>' +
715
+ (!isSession && s.role && s.role !== s.task ? '<span class="role">' + esc(s.role) + '</span>' : '') +
716
+ (alertState ? '<span class="state-tag ' + esc(st) + '">' + esc(t('state.' + st)) + '</span>' : '') +
717
+ subsPill(list, kOpen) + '</div>' +
718
+ (!exp && subText ? '<div class="agent-now' + subCls + '">' + mq(esc(subText)) + '</div>' : '') +
719
+ '</div>' +
720
+ '<div class="agent-facts">' +
721
+ (canOpenSession(s) ? '<span class="row-acts">' + openBtnsHtml(s, 'row-act-btn') + '</span>' : '') +
722
+ (mName ? '<span class="fact-model ' + vClass(s.vendor) + '" title="' + esc(s.model) + '">' + mq(esc(mName)) + '</span>' : '') +
723
+ '<span class="fact-time' + (quietRight ? ' stalled' : '') + '" title="' + esc(timeTip) + '">' + esc(timeText) + '</span>' +
724
+ '</div>' +
725
+ (exp ? rowDetails(s, stateTxt) : '') +
726
+ '</div>';
727
+ }
728
+
729
+ // ---------------------------------------------------------------- right column
730
+ function renderSide() {
731
+ if (S.sel && byId(S.sel)) return renderInspector();
732
+ S.sel = null;
733
+ const U = S.data.usage;
734
+ const head = (key, subKey) => '<h2>' + esc(t(key)) + '</h2><p class="sect-sub">' + esc(t(subKey)) + '</p>';
735
+ let h = '<section class="sect">' + head('quota.title', 'quota.help');
736
+ h += S.data.quotas.length ? S.data.quotas.map(quotaCard).join('') : '<div class="card empty-card">' + esc(t('quota.none')) + '</div>';
737
+ h += '</section><section class="sect">' + head('usage.title', 'usage.help');
738
+ h += U.vendors.length ? U.vendors.map(vendorCard).join('') : '<div class="card empty-card">' + esc(t('usage.none')) + '</div>';
739
+ h += '</section>';
740
+ setHTML($('side'), h);
741
+ }
742
+ function quotaNote(w) {
743
+ if (w.note === 'reset') return w.resets_at ? t('quota.resetWaiting', { time: resetTime(w.resets_at) }) : t('quota.waiting');
744
+ if (w.note === 'window not started') return t('quota.notStarted');
745
+ if (w.note === 'not exposed in local files') return t('quota.notLocal');
746
+ if (w.note === 'checking') return t('quota.checking');
747
+ if (w.note === 'unavailable') return t('quota.unavailable');
748
+ return w.note || '';
749
+ }
750
+ function quotaReason(q) {
751
+ if (!q.error && !q.error_code) return '';
752
+ const rem = q.next_try ? q.next_try - now() : 0;
753
+ if (q.error_code === 'expired') return t('quota.err.expired');
754
+ if (q.error_code === 'no_creds') return t('quota.err.noCreds');
755
+ if (q.error_code === 'rate_limit') return rem >= 1000 ? t('quota.err.rateLimitNext', { d: dur(rem) }) : t('quota.err.rateLimit');
756
+ if (q.error_code === 'server_error' || q.error_code === 'failed') return rem >= 1000 ? t('quota.err.failedNext', { d: dur(rem) }) : (q.error || '');
757
+ return q.error || '';
758
+ }
759
+ function quotaCard(q) {
760
+ const order = { '5h': 0, day: 1, week: 2, other: 3 };
761
+ const wins = [...q.windows].sort((a, b) => (order[a.window] - order[b.window]));
762
+ const vnames = (q.vendors || []).map((v) => ({ anthropic: 'Claude', openai: 'GPT', google: 'Gemini' })[v] || v);
763
+ const stale = !!q.stale;
764
+ const srcParts = [];
765
+ if (q.shared && vnames.length > 1) srcParts.push(esc(t('quota.shared', { v: vnames.join(', ') })));
766
+ if (q.checked) {
767
+ const age = dur(now() - q.checked);
768
+ srcParts.push(stale
769
+ ? '<span class="stale-age" title="' + esc(fullTime(q.checked)) + '">' + esc(t('quota.lastReading', { s: age })) + '</span>'
770
+ : '<span title="' + esc(fullTime(q.checked)) + '">' + esc(t('quota.checked', { s: age })) + '</span>');
771
+ }
772
+ let h = '<div class="card quota mqs' + (stale ? ' stale' : '') + '"><h3>' + mq(esc(q.tool + (q.label && q.label !== q.tool ? ': ' + q.label : ''))) + '</h3><div class="src">' +
773
+ srcParts.join('. ') + '</div>';
774
+ let needOptin = false;
775
+ for (const w of wins) {
776
+ const name = w.label || t('quota.' + w.window);
777
+ const pct = w.left_pct;
778
+ const isLow = !!w.low;
779
+ const isCrit = pct != null && (pct <= 0 || (isLow && pct < 3));
780
+ h += '<div class="win' + (isLow ? ' win-low' : '') + (isCrit ? ' win-crit' : '') + '"><div class="name">' +
781
+ (isLow ? '<span title="' + esc(t('quota.lowBadge')) + '">' + WARN_IC + '</span>' : '') +
782
+ '<span>' + esc(name) + '</span></div>';
783
+ if (pct != null) {
784
+ const cls = isCrit ? 'out' : (isLow || pct < 20) ? 'low' : '';
785
+ h += '<div style="display:grid;grid-template-columns:1fr 70px;gap:10px;align-items:center"><div class="meter"><i class="' + cls + '" style="width:' + Math.max(0, Math.min(100, pct)) + '%"></i></div><div class="pct">' +
786
+ esc(pct <= 0 ? t('quota.reached') : t('quota.left', { p: Math.round(pct) })) + '</div></div>';
787
+ } else {
788
+ const noteTitle = w.note === 'reset' && w.resets_at ? ' title="' + esc(fullTime(w.resets_at)) + '"' : '';
789
+ h += '<div class="note"' + noteTitle + '>' + esc(quotaNote(w)) + '</div>';
790
+ }
791
+ if (w.note === 'reset') {
792
+ // reset time is already shown in the note above
793
+ } else if (w.resets_at) {
794
+ const rem = w.resets_at - now();
795
+ if (rem >= 1000) h += '<div class="reset" title="' + esc(fullTime(w.resets_at)) + '">' + esc(t('quota.resets', { when: when(w.resets_at) })) + ' <em>(' + esc(t('quota.in', { d: dur(rem) })) + ')</em></div>';
796
+ else h += '<div class="reset" title="' + esc(fullTime(w.resets_at)) + '">' + esc(t('quota.resetAt', { time: resetTime(w.resets_at) })) + '</div>';
797
+ } else if (pct != null) h += '<div class="note">' + esc(t('quota.noReset')) + '</div>';
798
+ if (w.note === 'not exposed in local files') needOptin = true;
799
+ h += '</div>';
800
+ }
801
+ const reason = !needOptin ? quotaReason(q) : '';
802
+ if (reason) h += '<div class="hint' + (stale || q.error_code ? ' quota-err' : '') + '">' + esc(reason) + '</div>';
803
+ if (needOptin && q.optin) h += '<div class="hint">' + esc(t('quota.optin')) + '</div>';
804
+ return h + '</div>';
805
+ }
806
+ function vendorCard(V) {
807
+ const max = Math.max(1, ...V.series);
808
+ const spark = V.series.map((v) => '<i style="height:' + (v ? Math.max(2, Math.round((v / max) * 34)) : 1) + 'px;' + (v ? '' : 'opacity:.25') + '"></i>').join('');
809
+ let rows = '<div class="h">' + esc(t('usage.model')) + '</div><div class="h r">' + esc(t('usage.h5')) + '</div><div class="h r">' + esc(t('usage.today')) + '</div>';
810
+ for (const M of V.models.slice(0, 12)) {
811
+ rows += '<div class="m mqs" title="' + esc(M.model) + '"><b>' + mq(esc(modelName(M.model))) + '</b><span>' + esc(t('usage.via', { t: M.tools.join(', ') })) + '</span></div>' +
812
+ '<div class="r">' + esc(num(M.h5)) + '</div><div class="r">' + esc(num(M.today)) + '</div>';
813
+ }
814
+ return '<div class="card"><div class="vhead mqs"><h3 class="' + vClass(V.vendor) + '">' + mq(esc(t('usage.vendor', { v: V.label }))) + '</h3><span class="big">' + esc(num(V.today)) + '</span></div>' +
815
+ '<div class="vsub"><span>' + esc(t('usage.spark')) + '</span><span>' + esc(t('usage.week')) + ': ' + esc(num(V.week)) + '</span></div>' +
816
+ '<div class="spark ' + vClass(V.vendor) + '">' + spark + '</div><div class="models">' + rows + '</div></div>';
817
+ }
818
+
819
+ // ---------------------------------------------------------------- inspector
820
+ function renderInspector() {
821
+ const s = byId(S.sel);
822
+ const st = effState(s);
823
+ const endedBadly = st === 'done' && (s.ended_badly || isDismissed(s));
824
+ const fact = (k, v, title) => v || v === 0 ? '<div class="mqs"><dt>' + esc(t(k)) + '</dt><dd title="' + esc(title || v) + '">' + mq(esc(v)) + '</dd></div>' : '';
825
+ const parent = s.parent && byId(s.parent);
826
+ const tok = (x) => x ? num(x.in + x.cache + x.out) : '';
827
+ const dismissBtn = st === 'failed'
828
+ ? '<button class="btn small dismiss-btn" type="button" data-dismiss="' + esc(s.id) + '" title="' + esc(t('row.dismiss.tip')) + '">' + esc(t('row.dismiss')) + '</button>'
829
+ : '';
830
+ let h = '<div class="insp-top"><button class="btn" id="back">← ' + esc(t('insp.back')) + '</button>' +
831
+ (canOpenSession(s) ? '<div class="insp-acts">' + openBtnsHtml(s, 'btn icon') + '</div>' : '') + '</div>' +
832
+ '<div class="insp-head" style="margin-top:14px"><span class="dot ' + esc(st) + '" style="margin-top:8px"></span><h2>' + esc(s.label || s.name) + (s.role ? ' <span style="color:var(--ink-2);font-weight:400">' + esc(s.role) + '</span>' : '') + '</h2></div>' +
833
+ '<div class="insp-state' + (endedBadly ? ' ended-badly' : '') + '">' + (endedBadly ? WARN_IC : '') + '<span>' + esc(t('state.' + st) + (s.state_why ? ': ' + s.state_why : '')) + '</span>' + dismissBtn + '</div>' +
834
+ (s.task ? '<div class="insp-task">' + esc(S.trace && S.traceFor === s.id && S.trace.task_full ? S.trace.task_full : s.task) + '</div>' : '') +
835
+ '<dl class="facts">' + fact('insp.tool', s.tool + (s.client && s.client !== 'cli' ? ' (' + s.client + ')' : '')) + fact('insp.model', modelName(s.model), s.model) +
836
+ fact('insp.user', s.user || '', s.account) + fact('insp.branch', s.branch && s.branch !== 'HEAD' ? s.branch : '') +
837
+ fact('insp.folder', s.cwd || '') + fact('insp.parent', parent ? parent.label || parent.name : '') +
838
+ fact('insp.started', fullTime(s.started)) + fact('insp.last', ago(s.last), fullTime(s.last)) + fact('insp.steps', s.steps) +
839
+ fact('insp.tokens', tok(s.tokens)) + (s.children.length ? fact('insp.tokensTree', tok(s.tokens_tree)) + fact('insp.children', s.children.length) : '') + '</dl>';
840
+ const tabs = [['activity', 'insp.activity'], ['files', 'insp.files'], ['result', 'insp.result']];
841
+ h += '<div class="tabs" role="tablist">' + tabs.map(([id, k]) => '<button role="tab" data-tab="' + id + '" aria-selected="' + (S.tab === id) + '">' + esc(t(k)) + '</button>').join('') + '</div>';
842
+ h += '<div id="tabBody">' + tabBody(s) + '</div>';
843
+ setHTML($('side'), h);
844
+ }
845
+ function tabBody(s) {
846
+ const tr = S.traceFor === s.id ? S.trace : null;
847
+ if (!tr) return '<div class="hint">' + esc(t('insp.loading')) + '</div>';
848
+ if (S.tab === 'files') return tr.files && tr.files.length ? '<div class="files">' + tr.files.map((f) => '<div><em>' + esc(f.op) + '</em>' + esc(f.path) + '</div>').join('') + '</div>' : '<div class="hint">' + esc(t('insp.noFiles')) + '</div>';
849
+ if (S.tab === 'result') return tr.result ? '<div class="pre">' + esc(tr.result) + '</div>' : '<div class="hint">' + esc(t('insp.noResult')) + '</div>';
850
+ if (!tr.rows.length) return '<div class="hint">' + esc(t('insp.noRows')) + '</div>';
851
+ const rows = [...tr.rows].reverse().map((r) => {
852
+ const label = r.kind === 'in' ? t('row.prompt') : r.tool;
853
+ const tk = r.tout != null ? num((r.tin || 0) + (r.tc || 0)) + ' / ' + num(r.tout) : '';
854
+ return '<div class="row ' + esc(r.err ? 'err' : r.kind) + '"><div class="rh"><b>' + esc(label) + '</b>' + (r.from ? '<span style="color:var(--ink-3)">' + esc(r.from) + '</span>' : '') +
855
+ '<span class="t" title="' + esc(fullTime(r.ts)) + '">' + esc(tk ? tk + ' ' : '') + esc(r.ts ? hhmm(new Date(r.ts)) : '') + (r.dur ? ' · ' + esc(dur(r.dur)) : '') + (r.running ? ' · …' : '') + '</span></div>' +
856
+ (r.arg ? '<div class="arg">' + esc(r.arg) + '</div>' : '') + (r.text ? '<div class="arg">' + esc(r.text) + '</div>' : '') + (r.res ? '<div class="res">' + esc(r.res) + '</div>' : '') + '</div>';
857
+ }).join('');
858
+ return (tr.partial ? '<div class="hint">' + esc(t('insp.partial')) + '</div>' : '') + rows;
859
+ }
860
+ async function loadTrace() {
861
+ clearTimeout(traceTimer);
862
+ const id = S.sel; if (!id) return;
863
+ if (!S.paused && !document.hidden) {
864
+ try {
865
+ const r = await fetch('api/trace/' + encodeURIComponent(id) + '?limit=40', { cache: 'no-store' });
866
+ if (r.ok && S.sel === id) { S.trace = await r.json(); S.traceFor = id; if (S.view === 'office') renderSide(); }
867
+ } catch (e) { /* keep the last trace */ }
868
+ }
869
+ traceTimer = setTimeout(loadTrace, TRACE_MS);
870
+ }
871
+ function select(id) {
872
+ if (S.sel === id) return;
873
+ S.sel = id; S.tab = 'activity';
874
+ if (S.traceFor !== id) { S.trace = null; S.traceFor = null; }
875
+ renderTopo(); renderRooms(); renderSide(); loadTrace();
876
+ if (id) $('side').scrollTop = 0;
877
+ }
878
+
879
+ // set innerHTML only when it changed, so scroll position and focus survive a refresh; returns true when it did
880
+ function setHTML(el, html) {
881
+ if (el._html === html) return false;
882
+ const ae = document.activeElement, ds = ae && ae.dataset;
883
+ let sel = null;
884
+ if (ds && el.contains(ae)) {
885
+ if (ds.openId && ds.openWhat) sel = '[data-open-id="' + CSS.escape(ds.openId) + '"][data-open-what="' + CSS.escape(ds.openWhat) + '"]';
886
+ else if (ds.id) sel = '[data-id="' + CSS.escape(ds.id) + '"]';
887
+ else if (ds.toggleRoom) sel = '[data-toggle-room="' + CSS.escape(ds.toggleRoom) + '"]';
888
+ else if (ds.more) sel = '[data-more="' + CSS.escape(ds.more) + '"]';
889
+ else if (ds.kids) sel = '[data-kids="' + CSS.escape(ds.kids) + '"]';
890
+ else if (ds.repWs) sel = '[data-rep-ws="' + CSS.escape(ds.repWs) + '"]';
891
+ else if (ds.repAgent) sel = '[data-rep-agent="' + CSS.escape(ds.repAgent) + '"]';
892
+ else if (ds.dayStep) sel = '[data-day-step="' + CSS.escape(ds.dayStep) + '"]';
893
+ }
894
+ el.innerHTML = html; el._html = html;
895
+ if (sel) {
896
+ const f = el.querySelector(sel); if (f) f.focus({ preventScroll: true });
897
+ }
898
+ fitMarquees(el);
899
+ return true;
900
+ }
901
+ // Overflowing single-line text (.mq inside a clipping box): one cheap measure per render, all reads first and
902
+ // then all writes. Marks the box .mq-on with the signed distance (right-to-left text is cut on the left, so it
903
+ // slides the other way) and a duration; CSS animates it only while its row or card is hovered or focused.
904
+ // The full text also goes into the title attribute, which is what reduced-motion users get.
905
+ function fitMarquees(root) {
906
+ const spans = root.querySelectorAll('.mq');
907
+ if (!spans.length) return;
908
+ const found = [];
909
+ for (const s of spans) {
910
+ const box = s.parentElement, over = box.scrollWidth - box.clientWidth;
911
+ if (over > 1) found.push([box, over, s.getBoundingClientRect().left < box.getBoundingClientRect().left - 1 ? 1 : -1, s.textContent]);
912
+ else if (box.classList.contains('mq-on')) found.push([box, 0, 0, '']);
913
+ }
914
+ for (const [box, over, sign, text] of found) {
915
+ box.classList.toggle('mq-on', over > 0);
916
+ if (over > 0) {
917
+ box.style.setProperty('--mq', sign * over + 'px');
918
+ box.style.setProperty('--mq-t', (Math.max(1.2, over / 40) * 2 + 2.4).toFixed(1) + 's');
919
+ if (!box.closest('[title]')) { box.title = text; box.dataset.mqTitle = '1'; }
920
+ } else if (box.dataset.mqTitle) { box.removeAttribute('title'); delete box.dataset.mqTitle; }
921
+ }
922
+ }
923
+ // re-measure after the layout width changes or a view comes back (hidden elements measure as zero)
924
+ function refit() {
925
+ if (S.view === 'office') {
926
+ fitMarquees($('rooms')); fitMarquees($('side')); fitSvgText($('topo'));
927
+ } else if (S.view === 'reports') {
928
+ fitMarquees($('reports')); fitSvgText($('reports'));
929
+ }
930
+ }
931
+ let refitTimer = 0;
932
+ window.addEventListener('resize', () => { clearTimeout(refitTimer); refitTimer = setTimeout(refit, 150); });
933
+
934
+ function focusAgent(id) {
935
+ if (!id || !S.data) return;
936
+ if (S.view !== 'office') setView('office');
937
+ if (S.sel === id) { renderSide(); $('side').scrollTop = 0; }
938
+ else select(id);
939
+ }
940
+
941
+ // ---------------------------------------------------------------- toasts & desktop notifications
942
+ function showToast(opts) {
943
+ const o = typeof opts === 'string' ? { msg: opts } : (opts || {});
944
+ const host = $('toasts');
945
+ if (!host) return;
946
+ while (host.children.length >= 4) host.firstElementChild.remove();
947
+ const el = document.createElement('div');
948
+ el.className = 'toast' + (o.tone ? ' ' + o.tone : '') + (o.onClick ? ' clickable' : '');
949
+ el.setAttribute('role', 'status');
950
+ const body = document.createElement('div');
951
+ body.className = 'toast-body';
952
+ if (o.title) {
953
+ const b = document.createElement('span');
954
+ b.className = 'toast-title';
955
+ b.textContent = o.title;
956
+ body.appendChild(b);
957
+ }
958
+ if (o.msg) {
959
+ const sp = document.createElement('span');
960
+ sp.className = 'toast-msg';
961
+ sp.textContent = o.msg;
962
+ body.appendChild(sp);
963
+ }
964
+ const close = document.createElement('button');
965
+ close.type = 'button';
966
+ close.className = 'toast-close';
967
+ close.setAttribute('aria-label', t('studio.close'));
968
+ close.innerHTML = CLOSE_IC;
969
+ let timer = null;
970
+ const remove = () => { clearTimeout(timer); if (el.parentNode) el.remove(); };
971
+ close.onclick = (e) => { e.stopPropagation(); remove(); };
972
+ if (o.onClick) {
973
+ el.tabIndex = 0;
974
+ el.onclick = () => { o.onClick(); remove(); };
975
+ el.onkeydown = (e) => {
976
+ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); o.onClick(); remove(); }
977
+ else if (e.key === 'Escape') { e.preventDefault(); remove(); }
978
+ };
979
+ }
980
+ el.appendChild(body);
981
+ el.appendChild(close);
982
+ host.appendChild(el);
983
+ timer = setTimeout(remove, o.duration || 6500);
984
+ }
985
+
986
+ function notifPerm() {
987
+ return typeof Notification !== 'undefined' ? Notification.permission : 'unsupported';
988
+ }
989
+ function notifActive() {
990
+ // in-page toasts still work when the browser blocks system notifications
991
+ return !!S.notify;
992
+ }
993
+ function renderNotifyBtn() {
994
+ const btn = $('notifyBtn');
995
+ if (!btn) return;
996
+ const perm = notifPerm();
997
+ const denied = perm === 'denied';
998
+ const on = !!S.notify;
999
+ btn.setAttribute('aria-pressed', String(on));
1000
+ btn.classList.toggle('denied', denied);
1001
+ btn.setAttribute('aria-label', t('notify.label'));
1002
+ btn.title = denied ? t('notify.deniedTip') : on ? t('notify.onTip') : t('notify.offTip');
1003
+ }
1004
+ function fireNotification(ev) {
1005
+ if (typeof Notification !== 'undefined' && Notification.permission === 'granted') {
1006
+ try {
1007
+ const n = new Notification(ev.title, { body: ev.body, tag: ev.tag });
1008
+ n.onclick = () => {
1009
+ try { window.focus(); } catch (e) { /* ignore */ }
1010
+ if (ev.id) focusAgent(ev.id);
1011
+ try { n.close(); } catch (e) { /* ignore */ }
1012
+ };
1013
+ } catch (e) { /* Notification blocked */ }
1014
+ }
1015
+ if (!document.hidden) {
1016
+ showToast({
1017
+ title: ev.title,
1018
+ msg: ev.body,
1019
+ tone: ev.tone || '',
1020
+ onClick: ev.id ? () => focusAgent(ev.id) : null,
1021
+ });
1022
+ }
1023
+ }
1024
+ function runDemoNotification() {
1025
+ if (demoSimDone || !S.data || !S.data.demo || !notifActive()) return;
1026
+ demoSimDone = true;
1027
+ const s = S.data.sessions.find((x) => !x.parent && effState(x) === 'working') || S.data.sessions[0];
1028
+ if (!s) return;
1029
+ const w = S.data.workspaces.find((x) => x.id === (s.workspace || '~'));
1030
+ const ws = !w || w.id === '~' ? t('room.unknown') : w.name;
1031
+ const body = t('notify.bodyWhy', { ws, state: t('state.stalled'), why: t('room.why.perm') });
1032
+ fireNotification({ tag: s.id, title: sessionTitle(s), body, id: s.id, tone: 'warn' });
1033
+ }
1034
+ function checkNotifications() {
1035
+ if (!S.data) return;
1036
+ const curStates = new Map();
1037
+ for (const s of S.data.sessions) curStates.set(s.id, effState(s));
1038
+ const lowEntries = lowQuotaEntries();
1039
+ const curLow = new Set(lowEntries.map((e) => e.key));
1040
+ if (prevStates === null) {
1041
+ prevStates = curStates;
1042
+ prevLowQuotas = curLow;
1043
+ if (S.data.demo && !demoSimScheduled) {
1044
+ demoSimScheduled = true;
1045
+ demoSimTimer = setTimeout(runDemoNotification, 6000);
1046
+ }
1047
+ return;
1048
+ }
1049
+ const events = [];
1050
+ const wsNames = new Map(S.data.workspaces.map((w) => [w.id, w.id === '~' ? t('room.unknown') : w.name]));
1051
+ for (const s of S.data.sessions) {
1052
+ const st = effState(s);
1053
+ const prev = prevStates.get(s.id);
1054
+ if (prev !== st && (st === 'stalled' || st === 'idle' || st === 'failed')) {
1055
+ const nKey = s.id + ':' + st;
1056
+ if (!notifiedKeys.has(nKey)) {
1057
+ const ws = wsNames.get(s.workspace || '~') || t('room.unknown');
1058
+ const why = String(s.state_why || '').trim();
1059
+ const body = why
1060
+ ? t('notify.bodyWhy', { ws, state: t('state.' + st), why })
1061
+ : t('notify.bodyState', { ws, state: t('state.' + st) });
1062
+ events.push({
1063
+ nKey, tag: s.id, title: sessionTitle(s), body, id: s.id,
1064
+ tone: st === 'failed' ? 'failed' : st === 'stalled' ? 'warn' : '',
1065
+ });
1066
+ }
1067
+ }
1068
+ }
1069
+ for (const e of lowEntries) {
1070
+ if (!prevLowQuotas.has(e.key)) {
1071
+ const nKey = 'quota:' + e.key + ':' + e.resetsAt;
1072
+ if (!notifiedKeys.has(nKey)) {
1073
+ events.push({
1074
+ nKey, tag: 'quota:' + e.key, title: quotaWinLabel(e.q, e.w),
1075
+ body: quotaWarnMessage(e.q, e.w), id: null,
1076
+ tone: e.pct != null && e.pct < 3 ? 'failed' : 'warn',
1077
+ });
1078
+ }
1079
+ }
1080
+ }
1081
+ prevStates = curStates;
1082
+ prevLowQuotas = curLow;
1083
+ if (!notifActive() || !events.length) return;
1084
+ for (const ev of events) notifiedKeys.add(ev.nKey);
1085
+ const shown = events.slice(0, 3);
1086
+ for (const ev of shown) fireNotification(ev);
1087
+ if (events.length > 3) {
1088
+ fireNotification({
1089
+ tag: 'ao-more', title: 'Agent Office',
1090
+ body: t('notify.more', { n: events.length - 3 }), id: null, tone: 'warn',
1091
+ });
1092
+ }
1093
+ }
1094
+
1095
+ // ---------------------------------------------------------------- quota warning banner
1096
+ function quotaWinKey(q, w, seen) {
1097
+ const base = String(q.id || q.tool || 'quota') + ':' + String(w.window || 'other');
1098
+ if (!seen || !seen.has(base)) return base;
1099
+ const extra = String(w.label || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
1100
+ if (extra && !seen.has(base + ':' + extra)) return base + ':' + extra;
1101
+ let n = 2;
1102
+ while (seen.has(base + ':' + n)) n++;
1103
+ return base + ':' + n;
1104
+ }
1105
+ function quotaWinLabel(q, w) {
1106
+ const winLabel = w.label || t('quota.' + (w.window || 'other'));
1107
+ const provLabel = q.tool && q.label && q.label !== q.tool && String(q.id || '').includes(':')
1108
+ ? q.tool + ' ' + q.label
1109
+ : (q.tool || q.label || q.id || '');
1110
+ return (provLabel ? provLabel + ' ' : '') + winLabel;
1111
+ }
1112
+ function quotaWarnMessage(q, w) {
1113
+ const pct = Math.max(0, Math.round(w.left_pct || 0));
1114
+ const rem = w.resets_at ? w.resets_at - now() : 0;
1115
+ if (w.resets_at && rem >= 1000) {
1116
+ return t('quota.warn', {
1117
+ label: quotaWinLabel(q, w), p: pct,
1118
+ time: resetTime(w.resets_at), in: t('quota.in', { d: dur(rem) }),
1119
+ });
1120
+ }
1121
+ return t('quota.warnNoReset', { label: quotaWinLabel(q, w), p: pct });
1122
+ }
1123
+ function lowQuotaEntries() {
1124
+ if (!S.data || !Array.isArray(S.data.quotas)) return [];
1125
+ const out = [];
1126
+ for (const q of S.data.quotas) {
1127
+ const seen = new Set();
1128
+ for (const w of q.windows || []) {
1129
+ const key = quotaWinKey(q, w, seen);
1130
+ seen.add(key);
1131
+ if (w.low && w.left_pct != null) {
1132
+ out.push({ key, q, w, resetsAt: w.resets_at || 0, pct: w.left_pct });
1133
+ }
1134
+ }
1135
+ }
1136
+ return out;
1137
+ }
1138
+ function pruneDismissedQuotas(entries) {
1139
+ const activeByKey = new Map(entries.map((e) => [e.key, e]));
1140
+ let changed = false;
1141
+ const tNow = now();
1142
+ for (const k of Object.keys(S.dismissedQuotas)) {
1143
+ const savedTs = S.dismissedQuotas[k];
1144
+ const cur = activeByKey.get(k);
1145
+ if (!cur || (savedTs > 0 && (tNow >= savedTs || (cur.resetsAt && cur.resetsAt !== savedTs)))) {
1146
+ delete S.dismissedQuotas[k];
1147
+ changed = true;
1148
+ }
1149
+ }
1150
+ if (changed) saveMap('ao.quotaDismiss', S.dismissedQuotas);
1151
+ }
1152
+ function isQuotaDismissed(e) {
1153
+ if (!Object.prototype.hasOwnProperty.call(S.dismissedQuotas, e.key)) return false;
1154
+ const saved = S.dismissedQuotas[e.key];
1155
+ if (e.resetsAt) return saved === e.resetsAt && now() < e.resetsAt;
1156
+ return saved === 0;
1157
+ }
1158
+ function renderQuotaBanner() {
1159
+ const el = $('quotaBanner');
1160
+ if (!el) return;
1161
+ if (!S.data || S.view === 'reports') { el.hidden = true; return; }
1162
+ const entries = lowQuotaEntries();
1163
+ pruneDismissedQuotas(entries);
1164
+ const active = entries.filter((e) => !isQuotaDismissed(e)).sort((a, b) => a.pct - b.pct);
1165
+ if (!active.length) { el.hidden = true; return; }
1166
+ const top = active[0];
1167
+ const crit = top.pct != null && top.pct < 3;
1168
+ el.classList.toggle('crit', crit);
1169
+ const html = WARN_IC +
1170
+ '<span class="qb-text">' + esc(quotaWarnMessage(top.q, top.w)) +
1171
+ (active.length > 1 ? '<span class="qb-more">(+' + (active.length - 1) + ')</span>' : '') + '</span>' +
1172
+ '<button type="button" class="qb-close" data-dismiss-quota="' + esc(top.key) + '" data-resets-at="' + esc(top.resetsAt) +
1173
+ '" aria-label="' + esc(t('quota.dismiss')) + '" title="' + esc(t('quota.dismiss')) + '">' + CLOSE_IC + '</button>';
1174
+ setHTML(el, html);
1175
+ el.hidden = false;
1176
+ }
1177
+
1178
+ // ---------------------------------------------------------------- update notice
1179
+ function renderUpdateBanner() {
1180
+ const el = $('updateBanner');
1181
+ if (!el) return;
1182
+ const u = S.data && S.data.update;
1183
+ let hidden = '';
1184
+ try { hidden = localStorage.getItem('ao.updateDismiss') || ''; } catch (e) { /* ignore */ }
1185
+ if (!u || !u.latest || hidden === u.latest) { el.hidden = true; return; }
1186
+ const cmd = u.how === 'git' ? 'git pull' : 'npx @zaferyalcin/agent-office@latest';
1187
+ const url = typeof u.url === 'string' && /^https:\/\/github\.com\//.test(u.url) ? u.url : '';
1188
+ const html = '<span class="ub-text">' + esc(t('update.available', { v: u.latest, cur: u.current })) +
1189
+ ' <span class="ub-how">' + esc(t('update.how')) + ' <code>' + esc(cmd) + '</code></span>' +
1190
+ (url ? ' <a href="' + esc(url) + '" target="_blank" rel="noopener noreferrer">' + esc(t('update.notes')) + '</a>' : '') + '</span>' +
1191
+ '<button type="button" class="qb-close" data-dismiss-update="' + esc(u.latest) + '" aria-label="' + esc(t('update.dismiss')) +
1192
+ '" title="' + esc(t('update.dismiss')) + '">' + CLOSE_IC + '</button>';
1193
+ setHTML(el, html);
1194
+ el.hidden = false;
1195
+ }
1196
+
1197
+ // ---------------------------------------------------------------- open folder / terminal
1198
+ async function openAgentPath(id, what) {
1199
+ if (!id || (what !== 'folder' && what !== 'terminal')) return;
1200
+ try {
1201
+ const r = await fetch('api/open', {
1202
+ method: 'POST',
1203
+ headers: { 'Content-Type': 'application/json', 'X-Agent-Office': '1' },
1204
+ body: JSON.stringify({ id, what }),
1205
+ });
1206
+ let data = null;
1207
+ try { data = await r.json(); } catch (e) { /* non-json */ }
1208
+ if (r.ok && data && data.ok) {
1209
+ const msg = t(data.demo ? 'open.demo' : 'open.ok', { path: data.path || '' });
1210
+ showToast({ msg, tone: data.demo ? '' : 'ok' });
1211
+ } else {
1212
+ showToast({ msg: t('open.err', { err: (data && data.error) || String(r.status) }), tone: 'failed' });
1213
+ }
1214
+ } catch (e) {
1215
+ showToast({ msg: t('open.err', { err: (e && e.message) || String(e) }), tone: 'failed' });
1216
+ }
1217
+ }
1218
+
1219
+ // ---------------------------------------------------------------- Reports view (daily summary + weekly SVG charts)
1220
+ function parseLocalDay(str) {
1221
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(str || ''));
1222
+ return m ? new Date(+m[1], +m[2] - 1, +m[3]) : null;
1223
+ }
1224
+ function formatLocalDayStr(d) {
1225
+ return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
1226
+ }
1227
+ function localDays7() {
1228
+ if (S.history && Array.isArray(S.history.days) && S.history.days.length) return S.history.days;
1229
+ const base = new Date(now());
1230
+ const out = [];
1231
+ for (let i = 6; i >= 0; i--) out.push(formatLocalDayStr(new Date(base.getFullYear(), base.getMonth(), base.getDate() - i)));
1232
+ return out;
1233
+ }
1234
+ function fmtDayShort(str) {
1235
+ const d = parseLocalDay(str);
1236
+ return d ? d.toLocaleDateString(locale(), { weekday: 'short', day: 'numeric' }) : str;
1237
+ }
1238
+ function fmtDayMedium(str) {
1239
+ const d = parseLocalDay(str);
1240
+ return d ? d.toLocaleDateString(locale(), { weekday: 'short', day: 'numeric', month: 'short' }) : str;
1241
+ }
1242
+ function niceMax(v) {
1243
+ if (!v || v <= 0) return 1;
1244
+ const exp = Math.pow(10, Math.floor(Math.log10(v)));
1245
+ const f = v / exp;
1246
+ for (const s of [1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10]) if (f <= s) return s * exp;
1247
+ return 10 * exp;
1248
+ }
1249
+ function vendorColor(vendor, idx) {
1250
+ if (vendor === 'anthropic') return 'var(--v-anthropic)';
1251
+ if (vendor === 'openai') return 'var(--v-openai)';
1252
+ if (vendor === 'google') return 'var(--v-google)';
1253
+ if (vendor === 'other') return 'var(--v-other)';
1254
+ return CHART_COLORS[(idx || 0) % CHART_COLORS.length];
1255
+ }
1256
+
1257
+ async function loadReports(opts) {
1258
+ clearTimeout(reportsTimer);
1259
+ if (S.view !== 'reports') return;
1260
+ opts = opts || {};
1261
+ const nowMs = Date.now();
1262
+ const allowBg = !S.paused && !document.hidden;
1263
+ const needHistory = !S.historyLoading && (!S.history || (allowBg && nowMs - S.historyAt >= HISTORY_MS));
1264
+ const days = localDays7();
1265
+ const targetDay = (S.reportDay && days.includes(S.reportDay)) ? S.reportDay : days[days.length - 1];
1266
+ if (!S.reportDay) S.reportDay = targetDay;
1267
+ const needReport = !S.reportLoading && (opts.forceReport || !S.report || S.report.day !== targetDay || (allowBg && nowMs - S.reportAt >= REPORT_MS));
1268
+
1269
+ if (needHistory) {
1270
+ S.historyLoading = true;
1271
+ fetch('api/history', { cache: 'no-store' })
1272
+ .then((r) => { if (!r.ok) throw new Error(r.status); return r.json(); })
1273
+ .then((h) => {
1274
+ S.history = h; S.historyAt = Date.now(); S.historyErr = false;
1275
+ if (h && Array.isArray(h.days) && h.days.length && (!S.reportDay || !h.days.includes(S.reportDay))) {
1276
+ S.reportDay = h.days[h.days.length - 1];
1277
+ }
1278
+ })
1279
+ .catch(() => { S.historyErr = true; })
1280
+ .finally(() => { S.historyLoading = false; if (S.view === 'reports') renderReports(); });
1281
+ }
1282
+ if (needReport) {
1283
+ S.reportLoading = true;
1284
+ const reqDay = targetDay;
1285
+ fetch('api/report?day=' + encodeURIComponent(reqDay), { cache: 'no-store' })
1286
+ .then((r) => { if (!r.ok) throw new Error(r.status); return r.json(); })
1287
+ .then((rep) => {
1288
+ if (S.reportDay === reqDay || !S.reportDay) {
1289
+ S.report = rep; S.reportDay = rep.day; S.reportAt = Date.now(); S.reportErr = false;
1290
+ }
1291
+ })
1292
+ .catch(() => { if (S.reportDay === reqDay) S.reportErr = true; })
1293
+ .finally(() => { S.reportLoading = false; if (S.view === 'reports') renderReports(); });
1294
+ }
1295
+ if (S.view === 'reports') {
1296
+ reportsTimer = setTimeout(() => {
1297
+ if (S.view === 'reports' && !S.paused && !document.hidden) loadReports();
1298
+ }, REPORT_MS);
1299
+ }
1300
+ }
1301
+ function stepReportDay(delta) {
1302
+ const days = localDays7();
1303
+ const cur = S.reportDay || (S.report && S.report.day) || days[days.length - 1];
1304
+ let idx = days.indexOf(cur);
1305
+ if (idx < 0) idx = days.length - 1;
1306
+ const next = idx + delta;
1307
+ if (next < 0 || next >= days.length) return;
1308
+ S.reportDay = days[next];
1309
+ repCopied = false;
1310
+ clearTimeout(copiedTimer);
1311
+ renderReports();
1312
+ loadReports({ forceReport: true });
1313
+ }
1314
+ async function copyReportMarkdown() {
1315
+ if (!S.report || !S.report.markdown) return;
1316
+ const text = S.report.markdown;
1317
+ let ok = false;
1318
+ if (navigator.clipboard && navigator.clipboard.writeText) {
1319
+ try { await navigator.clipboard.writeText(text); ok = true; } catch (e) { /* fallback */ }
1320
+ }
1321
+ if (!ok) {
1322
+ try {
1323
+ const ta = document.createElement('textarea');
1324
+ ta.value = text;
1325
+ ta.setAttribute('readonly', '');
1326
+ ta.style.position = 'fixed';
1327
+ ta.style.opacity = '0';
1328
+ document.body.appendChild(ta);
1329
+ ta.select();
1330
+ ok = document.execCommand('copy');
1331
+ ta.remove();
1332
+ } catch (e) { ok = false; }
1333
+ }
1334
+ if (ok) {
1335
+ repCopied = true;
1336
+ clearTimeout(copiedTimer);
1337
+ renderReports();
1338
+ copiedTimer = setTimeout(() => { repCopied = false; if (S.view === 'reports') renderReports(); }, 2000);
1339
+ }
1340
+ }
1341
+ function downloadReportMarkdown() {
1342
+ if (!S.report || !S.report.markdown) return;
1343
+ const blob = new Blob([S.report.markdown], { type: 'text/markdown;charset=utf-8' });
1344
+ const url = URL.createObjectURL(blob);
1345
+ const a = document.createElement('a');
1346
+ a.href = url;
1347
+ a.download = 'agent-office-' + (S.report.day || 'report') + '.md';
1348
+ document.body.appendChild(a);
1349
+ a.click();
1350
+ a.remove();
1351
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
1352
+ }
1353
+
1354
+ function renderDailyReport() {
1355
+ const days = localDays7();
1356
+ const curDay = S.reportDay || (S.report && S.report.day) || days[days.length - 1];
1357
+ const idx = Math.max(0, days.indexOf(curDay));
1358
+ const isToday = idx === days.length - 1;
1359
+ const canPrev = idx > 0;
1360
+ const canNext = idx < days.length - 1;
1361
+ const R = S.report && S.report.day === curDay ? S.report : null;
1362
+ const hasMd = !!(R && R.markdown);
1363
+
1364
+ let h = '<div class="rep-head"><h2>' + esc(t('rep.daily')) + '</h2>' +
1365
+ '<div class="rep-controls">' +
1366
+ '<div class="rep-day-nav" role="group" aria-label="' + esc(t('rep.dayNav')) + '">' +
1367
+ '<button type="button" data-day-step="-1" aria-label="' + esc(t('rep.prevDay')) + '" title="' + esc(t('rep.prevDay')) + '"' + (canPrev ? '' : ' disabled') + '>' + PREV_IC + '</button>' +
1368
+ '<span class="rep-day-label" title="' + esc(curDay) + '">' + esc(fmtDayMedium(curDay)) +
1369
+ (isToday ? '<span class="rep-today-tag">' + esc(t('rep.today')) + '</span>' : '') + '</span>' +
1370
+ '<button type="button" data-day-step="1" aria-label="' + esc(t('rep.nextDay')) + '" title="' + esc(t('rep.nextDay')) + '"' + (canNext ? '' : ' disabled') + '>' + NEXT_IC + '</button>' +
1371
+ '</div>' +
1372
+ '<div class="rep-export">' +
1373
+ '<button type="button" class="btn small' + (repCopied ? ' copied' : '') + '" id="repCopyMd"' + (hasMd ? '' : ' disabled') + '>' + esc(t(repCopied ? 'rep.copied' : 'rep.copyMd')) + '</button>' +
1374
+ '<button type="button" class="btn small" id="repDlMd"' + (hasMd ? '' : ' disabled') + '>' + esc(t('rep.downloadMd')) + '</button>' +
1375
+ '</div>' +
1376
+ '</div></div>';
1377
+
1378
+ if (S.reportErr && !R) {
1379
+ return h + '<div class="card empty-card">' + esc(t('rep.error')) + '</div>';
1380
+ }
1381
+ if (!R) {
1382
+ return h + '<div class="card empty-card">' + esc(t('rep.loading')) + '</div>';
1383
+ }
1384
+ const T = R.totals || { tokens: 0, agents: 0, workspaces: 0, done: 0, failed: 0, active: 0 };
1385
+ h += '<div class="rep-summary-strip">' +
1386
+ '<p class="rep-summary-line">' + esc(t('rep.totals', { tokens: num(T.tokens), agents: T.agents, projects: T.workspaces })) + '</p>' +
1387
+ '<div class="rep-figures">' +
1388
+ '<div class="rep-fig"><b>' + esc(num(T.tokens)) + '</b><span>' + esc(t('rep.statTokens')) + '</span></div>' +
1389
+ '<div class="rep-fig"><b>' + esc(T.agents) + '</b><span>' + esc(t('rep.statAgents')) + '</span></div>' +
1390
+ '<div class="rep-fig"><b>' + esc(T.workspaces) + '</b><span>' + esc(t('rep.statProjects')) + '</span></div>' +
1391
+ '<div class="rep-fig done"><b>' + esc(T.done) + '</b><span>' + esc(t('rep.statDone')) + '</span></div>' +
1392
+ '<div class="rep-fig' + (T.failed ? ' failed' : '') + '"><b>' + esc(T.failed) + '</b><span>' + esc(t('rep.statFailed')) + '</span></div>' +
1393
+ '</div></div>';
1394
+
1395
+ if (!R.workspaces || !R.workspaces.length) {
1396
+ return h + '<div class="card empty-card">' + esc(t('rep.noActivity')) + '</div>';
1397
+ }
1398
+
1399
+ let wsHtml = '';
1400
+ for (const w of R.workspaces) {
1401
+ const wsName = w.id === '~' ? t('room.unknown') : w.name;
1402
+ const expanded = !S.reportClosedWs.has(w.id);
1403
+ const countLbl = w.agents.length === 1 ? t('room.agent') : t('room.agents', { n: w.agents.length });
1404
+ let agentsHtml = '';
1405
+ if (expanded) {
1406
+ for (const a of w.agents) {
1407
+ const mName = modelName(a.model);
1408
+ const toolModel = mName ? a.tool + ' · ' + mName : a.tool;
1409
+ const vCls = vClass(vendorOfModel(a.model));
1410
+ const t1 = a.first ? hhmm(new Date(a.first)) : '';
1411
+ const t2 = a.last ? hhmm(new Date(a.last)) : '';
1412
+ const range = t1 && t2 && t1 !== t2 ? t1 + '–' + t2 : (t2 || t1);
1413
+ const rangeTip = [a.first ? fullTime(a.first) : '', a.last && a.last !== a.first ? fullTime(a.last) : ''].filter(Boolean).join(' – ');
1414
+ const stateLbl = t('state.' + a.state);
1415
+ agentsHtml += '<button type="button" class="rep-agent mqs" data-rep-agent="' + esc(a.id) + '">' +
1416
+ '<span class="rep-agent-top">' +
1417
+ '<span class="mark ' + esc(a.state) + '" aria-hidden="true"></span>' +
1418
+ '<span class="rep-agent-name">' + mq(esc(a.label || a.tool)) + '</span>' +
1419
+ '<span class="rep-state-chip ' + esc(a.state) + '">' + esc(stateLbl) + '</span>' +
1420
+ '<span class="rep-agent-meta">' +
1421
+ '<span class="rep-agent-tool ' + vCls + '" title="' + esc(a.model || a.tool) + '">' + esc(toolModel) + '</span>' +
1422
+ '<span class="rep-agent-tok">' + esc(num(a.tokens)) + '</span>' +
1423
+ (range ? '<span title="' + esc(rangeTip) + '">' + esc(range) + '</span>' : '') +
1424
+ '</span>' +
1425
+ '</span>' +
1426
+ (a.task ? '<span class="rep-agent-task">' + mq(esc(a.task)) + '</span>' : '') +
1427
+ (a.state === 'failed' && a.why ? '<span class="rep-agent-why">' + mq(esc(a.why)) + '</span>' : '') +
1428
+ '</button>';
1429
+ }
1430
+ }
1431
+ wsHtml += '<section class="rep-ws ' + (expanded ? 'open' : 'closed') + '">' +
1432
+ '<button type="button" class="rep-ws-head" data-rep-ws="' + esc(w.id) + '" aria-expanded="' + expanded + '">' +
1433
+ '<span class="rep-ws-title">' +
1434
+ '<span class="rep-ws-chev" aria-hidden="true">' + CHEV + '</span>' +
1435
+ '<span class="rep-ws-name">' + esc(wsName) + '</span>' +
1436
+ '</span>' +
1437
+ '<span class="rep-ws-meta"><span>' + esc(countLbl) + '</span><span class="rep-ws-tok">' + esc(num(w.tokens)) + '</span></span>' +
1438
+ '</button>' +
1439
+ (expanded ? '<div class="rep-agents" role="list">' + agentsHtml + '</div>' : '') +
1440
+ '</section>';
1441
+ }
1442
+ return h + '<div class="rep-ws-list">' + wsHtml + '</div>';
1443
+ }
1444
+
1445
+ function svgStackedByProject(H) {
1446
+ const days = H.days || [];
1447
+ const list = (H.by_workspace || []).filter((w) => w.total > 0);
1448
+ if (!days.length || !list.length) return '<p class="rep-empty">' + esc(t('rep.emptyWeek')) + '</p>';
1449
+ const series = list.slice(0, 6).map((w, i) => ({
1450
+ name: w.id === '~' ? t('room.unknown') : w.name,
1451
+ tokens: w.tokens || [],
1452
+ total: w.total || 0,
1453
+ color: CHART_COLORS[i % CHART_COLORS.length],
1454
+ }));
1455
+ if (list.length > 6) {
1456
+ const otherTok = new Array(days.length).fill(0);
1457
+ let otherTot = 0;
1458
+ for (const w of list.slice(6)) {
1459
+ for (let i = 0; i < days.length; i++) otherTok[i] += (w.tokens && w.tokens[i]) || 0;
1460
+ otherTot += w.total || 0;
1461
+ }
1462
+ if (otherTot > 0) series.push({ name: t('rep.other'), tokens: otherTok, total: otherTot, color: 'var(--c-other)' });
1463
+ }
1464
+ const dayTotals = days.map((_, i) => series.reduce((acc, s) => acc + (s.tokens[i] || 0), 0));
1465
+ const maxY = niceMax(Math.max(...dayTotals, 1));
1466
+ const W = 560, Hh = 216, L = 52, R = 12, T = 14, B = 30, pw = W - L - R, ph = Hh - T - B;
1467
+ const slotW = pw / days.length;
1468
+ const barW = Math.min(42, Math.max(14, slotW * 0.6));
1469
+ let svg = '<svg viewBox="0 0 ' + W + ' ' + Hh + '" role="img" aria-label="' + esc(t('rep.chartWs')) + '">';
1470
+ for (const frac of [0, 0.5, 1]) {
1471
+ const y = T + ph * (1 - frac);
1472
+ svg += '<line x1="' + L + '" y1="' + y.toFixed(1) + '" x2="' + (W - R) + '" y2="' + y.toFixed(1) + '" class="ch-grid"/>' +
1473
+ '<text x="' + (L - 7) + '" y="' + (y + 3.5).toFixed(1) + '" text-anchor="end" class="ch-axis">' + esc(num(maxY * frac)) + '</text>';
1474
+ }
1475
+ for (let i = 0; i < days.length; i++) {
1476
+ const cx = L + slotW * (i + 0.5);
1477
+ const bx = cx - barW / 2;
1478
+ let yCur = T + ph;
1479
+ const dayLbl = fmtDayMedium(days[i]);
1480
+ for (let j = 0; j < series.length; j++) {
1481
+ const val = series[j].tokens[i] || 0;
1482
+ if (!val) continue;
1483
+ const bh = Math.max(1.5, (val / maxY) * ph);
1484
+ yCur -= bh;
1485
+ const tip = series[j].name + '\n' + dayLbl + ': ' + num(val) + '\n' + t('rep.total') + ': ' + num(dayTotals[i]);
1486
+ svg += '<rect class="ch-seg" tabindex="0" role="img" aria-label="' + esc(tip.replace(/\n/g, ', ')) + '" data-tip="' + esc(tip) +
1487
+ '" x="' + bx.toFixed(1) + '" y="' + yCur.toFixed(1) + '" width="' + barW.toFixed(1) + '" height="' + bh.toFixed(1) +
1488
+ '" rx="1.5" fill="' + series[j].color + '"/>';
1489
+ }
1490
+ svg += '<text x="' + cx.toFixed(1) + '" y="' + (Hh - 10) + '" text-anchor="middle" class="ch-axis">' + esc(fmtDayShort(days[i])) + '</text>';
1491
+ }
1492
+ svg += '</svg>';
1493
+ const leg = '<div class="rep-legend">' + series.map((s) =>
1494
+ '<span class="rep-leg-item"><i class="rep-leg-sw" style="background:' + s.color + '"></i>' +
1495
+ '<span class="rep-leg-name" title="' + esc(s.name) + '">' + esc(s.name) + '</span>' +
1496
+ '<span class="rep-leg-val">' + esc(num(s.total)) + '</span></span>'
1497
+ ).join('') + '</div>';
1498
+ return '<div class="rep-chart">' + svg + '</div>' + leg;
1499
+ }
1500
+
1501
+ function svgTopAgents(H) {
1502
+ const items = (H.top_agents || []).filter((a) => a.total > 0).slice(0, 10);
1503
+ if (!items.length) return '<p class="rep-empty">' + esc(t('rep.emptyAgents')) + '</p>';
1504
+ const maxX = niceMax(Math.max(...items.map((a) => a.total), 1));
1505
+ const W = 560, L = 148, R = 56, T = 8, B = 28, rowH = 26, pw = W - L - R;
1506
+ const ph = items.length * rowH;
1507
+ const Hh = T + ph + B;
1508
+ let svg = '<svg viewBox="0 0 ' + W + ' ' + Hh + '" role="img" aria-label="' + esc(t('rep.chartAgents')) + '">';
1509
+ for (const frac of [0, 0.5, 1]) {
1510
+ const x = L + pw * frac;
1511
+ svg += '<line x1="' + x.toFixed(1) + '" y1="' + T + '" x2="' + x.toFixed(1) + '" y2="' + (T + ph) + '" class="ch-grid"/>' +
1512
+ '<text x="' + x.toFixed(1) + '" y="' + (Hh - 8) + '" text-anchor="middle" class="ch-axis">' + esc(num(maxX * frac)) + '</text>';
1513
+ }
1514
+ const vendorsSeen = new Map();
1515
+ items.forEach((a, idx) => {
1516
+ const y = T + idx * rowH;
1517
+ const bw = Math.max(2, (a.total / maxX) * pw);
1518
+ const v = vendorOfModel(a.model);
1519
+ const col = vendorColor(v, idx);
1520
+ if (!vendorsSeen.has(v)) vendorsSeen.set(v, col);
1521
+ const wsName = a.workspace === '~' ? t('room.unknown') : (a.workspace_name || '');
1522
+ const mName = modelName(a.model);
1523
+ const tip = (a.label || a.tool) + (wsName ? ' · ' + wsName : '') + '\n' +
1524
+ (mName ? a.tool + ' · ' + mName : a.tool) + '\n' + num(a.total) + ' ' + t('row.tokens');
1525
+ svg += '<g class="ch-bar-row" tabindex="0" role="button" data-rep-agent="' + esc(a.id) + '" data-tip="' + esc(tip) +
1526
+ '" aria-label="' + esc((a.label || a.tool) + ', ' + num(a.total)) + '">' +
1527
+ '<text x="' + (L - 8) + '" y="' + (y + 16.5) + '" text-anchor="end" class="ch-label"><tspan data-fit="' + (L - 14) + '" data-full="' + esc(a.label || a.tool) + '">' + esc(a.label || a.tool) + '</tspan></text>' +
1528
+ '<rect x="' + L + '" y="' + (y + 5) + '" width="' + bw.toFixed(1) + '" height="15" rx="3" fill="' + col + '"/>' +
1529
+ '<text x="' + (L + bw + 6).toFixed(1) + '" y="' + (y + 16.5) + '" class="ch-val">' + esc(num(a.total)) + '</text>' +
1530
+ '</g>';
1531
+ });
1532
+ svg += '</svg>';
1533
+ const vLbl = { anthropic: 'Claude', openai: 'GPT', google: 'Gemini', other: t('rep.other') };
1534
+ const leg = '<div class="rep-legend">' + [...vendorsSeen.entries()].map(([v, col]) =>
1535
+ '<span class="rep-leg-item"><i class="rep-leg-sw" style="background:' + col + '"></i><span class="rep-leg-name">' + esc(vLbl[v] || v) + '</span></span>'
1536
+ ).join('') + '</div>';
1537
+ return '<div class="rep-chart">' + svg + '</div>' + leg;
1538
+ }
1539
+
1540
+ function svgByVendor(H) {
1541
+ const days = H.days || [];
1542
+ const vendors = (H.by_vendor || []).filter((v) => v.total > 0);
1543
+ if (!days.length || !vendors.length) return '<p class="rep-empty">' + esc(t('rep.emptyWeek')) + '</p>';
1544
+ let maxVal = 1;
1545
+ for (const v of vendors) for (const x of v.tokens || []) if (x > maxVal) maxVal = x;
1546
+ const maxY = niceMax(maxVal);
1547
+ const W = 560, Hh = 216, L = 52, R = 12, T = 14, B = 30, pw = W - L - R, ph = Hh - T - B;
1548
+ const slotW = pw / days.length;
1549
+ const grpW = Math.min(54, slotW * 0.74);
1550
+ const gap = vendors.length > 1 ? 2 : 0;
1551
+ const barW = Math.max(4, (grpW - gap * (vendors.length - 1)) / vendors.length);
1552
+ let svg = '<svg viewBox="0 0 ' + W + ' ' + Hh + '" role="img" aria-label="' + esc(t('rep.chartVendor')) + '">';
1553
+ for (const frac of [0, 0.5, 1]) {
1554
+ const y = T + ph * (1 - frac);
1555
+ svg += '<line x1="' + L + '" y1="' + y.toFixed(1) + '" x2="' + (W - R) + '" y2="' + y.toFixed(1) + '" class="ch-grid"/>' +
1556
+ '<text x="' + (L - 7) + '" y="' + (y + 3.5).toFixed(1) + '" text-anchor="end" class="ch-axis">' + esc(num(maxY * frac)) + '</text>';
1557
+ }
1558
+ for (let i = 0; i < days.length; i++) {
1559
+ const cx = L + slotW * (i + 0.5);
1560
+ const startX = cx - grpW / 2;
1561
+ const dayLbl = fmtDayMedium(days[i]);
1562
+ vendors.forEach((v, j) => {
1563
+ const val = (v.tokens && v.tokens[i]) || 0;
1564
+ if (!val) return;
1565
+ const bh = Math.max(1.5, (val / maxY) * ph);
1566
+ const bx = startX + j * (barW + gap);
1567
+ const by = T + ph - bh;
1568
+ const col = vendorColor(v.vendor, j);
1569
+ const tip = v.label + '\n' + dayLbl + ': ' + num(val);
1570
+ svg += '<rect class="ch-seg" tabindex="0" role="img" aria-label="' + esc(v.label + ', ' + dayLbl + ': ' + num(val)) + '" data-tip="' + esc(tip) +
1571
+ '" x="' + bx.toFixed(1) + '" y="' + by.toFixed(1) + '" width="' + barW.toFixed(1) + '" height="' + bh.toFixed(1) +
1572
+ '" rx="1.5" fill="' + col + '"/>';
1573
+ });
1574
+ svg += '<text x="' + cx.toFixed(1) + '" y="' + (Hh - 10) + '" text-anchor="middle" class="ch-axis">' + esc(fmtDayShort(days[i])) + '</text>';
1575
+ }
1576
+ svg += '</svg>';
1577
+ const leg = '<div class="rep-legend">' + vendors.map((v, j) =>
1578
+ '<span class="rep-leg-item"><i class="rep-leg-sw" style="background:' + vendorColor(v.vendor, j) + '"></i>' +
1579
+ '<span class="rep-leg-name">' + esc(v.label) + '</span>' +
1580
+ '<span class="rep-leg-val">' + esc(num(v.total)) + '</span></span>'
1581
+ ).join('') + '</div>';
1582
+ return '<div class="rep-chart">' + svg + '</div>' + leg;
1583
+ }
1584
+
1585
+ function svgQuotaHistory(H) {
1586
+ quotaPlotMeta = null;
1587
+ const all = (H.quota || []).filter((q) => Array.isArray(q.points) && q.points.length);
1588
+ // A week view reads best with the long windows; 5-hour windows reset 30+ times a week and turn into noise.
1589
+ // They stay in the Limits panel. Fall back to every window when a tool reports only short ones.
1590
+ const longOnly = all.filter((q) => !/:5h$/.test(String(q.key || '')));
1591
+ const raw = longOnly.length ? longOnly : all;
1592
+ if (!raw.length) return '<p class="rep-empty">' + esc(t('rep.emptyQuota')) + '</p>';
1593
+ const days = H.days || localDays7();
1594
+ const d0 = parseLocalDay(days[0]);
1595
+ let minPt = Infinity, maxPt = -Infinity;
1596
+ for (const q of raw) {
1597
+ for (const pt of q.points) {
1598
+ if (pt[0] < minPt) minPt = pt[0];
1599
+ if (pt[0] > maxPt) maxPt = pt[0];
1600
+ }
1601
+ }
1602
+ const tMax = Math.max(S.historyAt || 0, maxPt);
1603
+ const tMin = d0 ? Math.min(d0.getTime(), minPt) : Math.min(tMax - 7 * 864e5, minPt);
1604
+ const span = Math.max(3600e3, tMax - tMin);
1605
+ const warnPct = S.data && typeof S.data.quota_warn_pct === 'number' ? Math.max(0, Math.min(100, S.data.quota_warn_pct)) : 10;
1606
+ const W = 560, Hh = 220, L = 44, R = 14, T = 14, B = 30, pw = W - L - R, ph = Hh - T - B;
1607
+ const xOf = (ts) => L + Math.max(0, Math.min(1, (ts - tMin) / span)) * pw;
1608
+ const yOf = (pct) => T + (1 - Math.max(0, Math.min(100, pct)) / 100) * ph;
1609
+
1610
+ let svg = '<svg viewBox="0 0 ' + W + ' ' + Hh + '" role="img" aria-label="' + esc(t('rep.chartQuota')) + '">';
1611
+ for (const p of [0, 50, 100]) {
1612
+ const y = yOf(p);
1613
+ svg += '<line x1="' + L + '" y1="' + y.toFixed(1) + '" x2="' + (W - R) + '" y2="' + y.toFixed(1) + '" class="ch-grid"/>' +
1614
+ '<text x="' + (L - 7) + '" y="' + (y + 3.5).toFixed(1) + '" text-anchor="end" class="ch-axis">' + p + '%</text>';
1615
+ }
1616
+ // day ticks along bottom
1617
+ for (let i = 0; i < days.length; i++) {
1618
+ const dd = parseLocalDay(days[i]);
1619
+ if (!dd) continue;
1620
+ const x = xOf(dd.getTime() + 12 * 3600e3);
1621
+ svg += '<text x="' + x.toFixed(1) + '" y="' + (Hh - 10) + '" text-anchor="middle" class="ch-axis">' + esc(fmtDayShort(days[i])) + '</text>';
1622
+ }
1623
+ // warning threshold dashed line
1624
+ const yWarn = yOf(warnPct);
1625
+ svg += '<line x1="' + L + '" y1="' + yWarn.toFixed(1) + '" x2="' + (W - R) + '" y2="' + yWarn.toFixed(1) + '" class="ch-warn-line"/>' +
1626
+ '<text x="' + (W - R) + '" y="' + Math.max(T + 10, yWarn - 4).toFixed(1) + '" text-anchor="end" class="ch-warn-lbl">' + esc(t('rep.warnLine', { p: warnPct })) + '</text>';
1627
+
1628
+ const seriesMeta = [];
1629
+ let paths = '', dots = '';
1630
+ raw.forEach((q, idx) => {
1631
+ const col = CHART_COLORS[idx % CHART_COLORS.length];
1632
+ const dash = idx >= CHART_COLORS.length ? ' stroke-dasharray="5 3"' : '';
1633
+ const pts = [...q.points].sort((a, b) => a[0] - b[0]);
1634
+ seriesMeta.push({ label: q.label || q.key, color: col, points: pts });
1635
+ let d = 'M' + xOf(pts[0][0]).toFixed(1) + ' ' + yOf(pts[0][1]).toFixed(1);
1636
+ for (let k = 1; k < pts.length; k++) {
1637
+ d += ' H' + xOf(pts[k][0]).toFixed(1) + ' V' + yOf(pts[k][1]).toFixed(1);
1638
+ }
1639
+ paths += '<path d="' + d + '" class="ch-step" stroke="' + col + '"' + dash + '/>';
1640
+ // expose keyboard-focusable anchor points (latest + lowest point if distinct)
1641
+ const last = pts[pts.length - 1];
1642
+ let lowPt = pts[0];
1643
+ for (const p of pts) if (p[1] < lowPt[1]) lowPt = p;
1644
+ const keyPts = lowPt[0] !== last[0] ? [lowPt, last] : [last];
1645
+ for (const p of keyPts) {
1646
+ const tip = (q.label || q.key) + '\n' + fullTime(p[0]) + ': ' + Math.round(p[1]) + '%';
1647
+ dots += '<circle class="ch-pt" tabindex="0" role="img" aria-label="' + esc(tip.replace(/\n/g, ', ')) + '" data-tip="' + esc(tip) +
1648
+ '" cx="' + xOf(p[0]).toFixed(1) + '" cy="' + yOf(p[1]).toFixed(1) + '" r="3.2" fill="' + col + '"/>';
1649
+ }
1650
+ });
1651
+ quotaPlotMeta = { tMin, tMax, span, L, T, pw, ph, W, Hh, series: seriesMeta };
1652
+ svg += paths +
1653
+ '<line id="chQuotaCursor" class="ch-cursor" x1="0" y1="' + T + '" x2="0" y2="' + (T + ph) + '" visibility="hidden"/>' +
1654
+ '<rect class="ch-hit" data-quota-plot="1" x="' + L + '" y="' + T + '" width="' + pw + '" height="' + ph + '"/>' +
1655
+ dots + '</svg>';
1656
+
1657
+ const leg = '<div class="rep-legend">' + seriesMeta.map((s) => {
1658
+ const last = s.points[s.points.length - 1];
1659
+ return '<span class="rep-leg-item"><i class="rep-leg-line" style="background:' + s.color + '"></i>' +
1660
+ '<span class="rep-leg-name" title="' + esc(s.label) + '">' + esc(s.label) + '</span>' +
1661
+ '<span class="rep-leg-val">' + Math.round(last[1]) + '%</span></span>';
1662
+ }).join('') + '</div>';
1663
+ return '<div class="rep-chart">' + svg + '</div>' + leg;
1664
+ }
1665
+
1666
+ function renderWeeklyCharts() {
1667
+ let h = '<div class="rep-head"><h2>' + esc(t('rep.weekly')) + '</h2></div>';
1668
+ if (S.historyErr && !S.history) {
1669
+ return h + '<div class="card empty-card">' + esc(t('rep.error')) + '</div>';
1670
+ }
1671
+ if (!S.history) {
1672
+ return h + '<div class="card empty-card">' + esc(t('rep.loading')) + '</div>';
1673
+ }
1674
+ const H = S.history;
1675
+ const card = (titleKey, body) => '<section class="rep-chart-card"><h3>' + esc(t(titleKey)) + '</h3>' + body + '</section>';
1676
+ h += '<div class="rep-charts">' +
1677
+ card('rep.chartWs', svgStackedByProject(H)) +
1678
+ card('rep.chartAgents', svgTopAgents(H)) +
1679
+ card('rep.chartVendor', svgByVendor(H)) +
1680
+ card('rep.chartQuota', svgQuotaHistory(H)) +
1681
+ '</div>';
1682
+ return h;
1683
+ }
1684
+
1685
+ function renderReports() {
1686
+ const el = $('reports');
1687
+ if (!el || S.view !== 'reports') return;
1688
+ const html = '<div class="reports-grid">' +
1689
+ '<div class="rep-col rep-col-daily">' + renderDailyReport() + '</div>' +
1690
+ '<div class="rep-col rep-col-weekly">' + renderWeeklyCharts() + '</div>' +
1691
+ '</div>';
1692
+ if (setHTML(el, html)) fitSvgText(el);
1693
+ }
1694
+
1695
+ function showChartTip(text, x, y) {
1696
+ const tip = $('chartTip');
1697
+ if (!tip || !text) return;
1698
+ tip.textContent = text;
1699
+ tip.hidden = false;
1700
+ const pad = 12;
1701
+ const r = tip.getBoundingClientRect();
1702
+ let left = x + pad;
1703
+ let top = y - r.height - pad;
1704
+ if (left + r.width > window.innerWidth - 8) left = Math.max(8, x - r.width - pad);
1705
+ if (top < 8) top = Math.min(window.innerHeight - r.height - 8, y + pad);
1706
+ tip.style.left = Math.round(left) + 'px';
1707
+ tip.style.top = Math.round(top) + 'px';
1708
+ }
1709
+ function hideChartTip() {
1710
+ const tip = $('chartTip');
1711
+ if (tip) tip.hidden = true;
1712
+ const cur = $('chQuotaCursor');
1713
+ if (cur) cur.setAttribute('visibility', 'hidden');
1714
+ }
1715
+ function updateQuotaHover(e, rectEl) {
1716
+ if (!quotaPlotMeta) return;
1717
+ const svg = rectEl.ownerSVGElement;
1718
+ if (!svg) return;
1719
+ const box = svg.getBoundingClientRect();
1720
+ if (!box.width) return;
1721
+ const svgX = ((e.clientX - box.left) / box.width) * quotaPlotMeta.W;
1722
+ const frac = Math.max(0, Math.min(1, (svgX - quotaPlotMeta.L) / quotaPlotMeta.pw));
1723
+ const ts = quotaPlotMeta.tMin + frac * quotaPlotMeta.span;
1724
+ const cur = $('chQuotaCursor');
1725
+ if (cur) {
1726
+ const cx = (quotaPlotMeta.L + frac * quotaPlotMeta.pw).toFixed(1);
1727
+ cur.setAttribute('x1', cx);
1728
+ cur.setAttribute('x2', cx);
1729
+ cur.setAttribute('visibility', 'visible');
1730
+ }
1731
+ const lines = [fullTime(ts)];
1732
+ for (const s of quotaPlotMeta.series) {
1733
+ let chosen = null;
1734
+ for (let i = s.points.length - 1; i >= 0; i--) {
1735
+ if (s.points[i][0] <= ts) { chosen = s.points[i]; break; }
1736
+ }
1737
+ if (!chosen && s.points.length && s.points[0][0] - ts < 3600e3) chosen = s.points[0];
1738
+ if (chosen) lines.push(s.label + ': ' + Math.round(chosen[1]) + '%');
1739
+ }
1740
+ showChartTip(lines.join('\n'), e.clientX, e.clientY);
1741
+ }
1742
+
1743
+ // ---------------------------------------------------------------- views (studio loaded only while shown)
1744
+ async function setView(v) {
1745
+ if (v !== 'office' && v !== 'studio' && v !== 'reports') v = 'office';
1746
+ S.view = v;
1747
+ safeSet('ao.view', v);
1748
+ $('vOffice').setAttribute('aria-pressed', String(v === 'office'));
1749
+ $('vStudio').setAttribute('aria-pressed', String(v === 'studio'));
1750
+ $('vReports').setAttribute('aria-pressed', String(v === 'reports'));
1751
+ document.body.classList.toggle('view-studio', v === 'studio');
1752
+ document.body.classList.toggle('view-reports', v === 'reports');
1753
+ $('reports').hidden = v !== 'reports';
1754
+ hideChartTip();
1755
+ renderQuotaBanner(); renderUpdateBanner();
1756
+ if (v !== 'reports') clearTimeout(reportsTimer);
1757
+ if (v === 'office') refit();
1758
+ if (v === 'reports') {
1759
+ renderReports();
1760
+ loadReports();
1761
+ refit();
1762
+ }
1763
+ if (v === 'studio') {
1764
+ if (studio || studioLoading) return;
1765
+ studioLoading = true;
1766
+ $('studio').innerHTML = '<div class="empty" style="padding:40px">' + esc(t('studio.loading')) + '</div>';
1767
+ try {
1768
+ const mod = await import('./studio.js');
1769
+ if (S.view !== 'studio') { studioLoading = false; return; }
1770
+ $('studio').innerHTML = '';
1771
+ studio = mod.mount($('studio'), {
1772
+ t, modelName, num, dur, now,
1773
+ onOpen: (id) => { focusAgent(id); },
1774
+ });
1775
+ if (!studio) $('studio').innerHTML = '<div class="empty" style="padding:40px">' + esc(t('studio.nogl')) + '</div>';
1776
+ else if (S.data) studio.update(studioData());
1777
+ } catch (e) { console.error(e); $('studio').innerHTML = '<div class="empty" style="padding:40px">' + esc(t('studio.nogl')) + '</div>'; }
1778
+ studioLoading = false;
1779
+ } else if (studio) { studio.dispose(); studio = null; $('studio').innerHTML = ''; }
1780
+ }
1781
+
1782
+ // ---------------------------------------------------------------- events
1783
+ function applyStatic() {
1784
+ document.documentElement.lang = S.lang;
1785
+ document.documentElement.dir = (window.LANGS.find((l) => l.id === S.lang) || {}).dir || 'ltr';
1786
+ document.querySelectorAll('[data-i18n]').forEach((el) => { el.textContent = t(el.dataset.i18n); });
1787
+ document.querySelectorAll('[data-i18n-ph]').forEach((el) => { el.placeholder = t(el.dataset.i18nPh); });
1788
+ const label = (id, key, tipKey) => { $(id).setAttribute('aria-label', t(key)); $(id).title = t(tipKey || key); };
1789
+ label('langBtn', 'lang.label'); label('themeBtn', 'theme.label', 'theme.tip'); label('helpBtn', 'help.btn'); label('helpClose', 'studio.close');
1790
+ $('reports').setAttribute('aria-label', t('rep.title'));
1791
+ renderNotifyBtn();
1792
+ $('langMenu').innerHTML = window.LANGS.map((l) => '<button role="menuitemradio" aria-checked="' + (l.id === S.lang) + '" data-lang="' + l.id + '" lang="' + l.id + '">' + esc(l.name) + '</button>').join('');
1793
+ $('pauseBtn').textContent = S.paused ? t('resume') : t('pause');
1794
+ $('hours').value = String(S.hours); $('showDone').checked = S.showDone;
1795
+ }
1796
+ $('vOffice').onclick = () => setView('office');
1797
+ $('vStudio').onclick = () => setView('studio');
1798
+ $('vReports').onclick = () => setView('reports');
1799
+
1800
+ $('notifyBtn').onclick = async () => {
1801
+ const perm = notifPerm();
1802
+ if (perm === 'denied') {
1803
+ renderNotifyBtn();
1804
+ showToast({ msg: t('notify.deniedTip'), tone: 'warn' });
1805
+ return;
1806
+ }
1807
+ if (S.notify) {
1808
+ S.notify = false;
1809
+ safeSet('ao.notify', '0');
1810
+ renderNotifyBtn();
1811
+ return;
1812
+ }
1813
+ if (perm === 'default' && typeof Notification !== 'undefined' && typeof Notification.requestPermission === 'function') {
1814
+ try {
1815
+ const res = await Notification.requestPermission();
1816
+ if (res === 'granted') {
1817
+ S.notify = true;
1818
+ safeSet('ao.notify', '1');
1819
+ } else {
1820
+ S.notify = false;
1821
+ safeSet('ao.notify', '0');
1822
+ if (res === 'denied') showToast({ msg: t('notify.deniedTip'), tone: 'warn' });
1823
+ }
1824
+ } catch (e) {
1825
+ S.notify = false;
1826
+ safeSet('ao.notify', '0');
1827
+ }
1828
+ } else {
1829
+ S.notify = true;
1830
+ safeSet('ao.notify', '1');
1831
+ }
1832
+ renderNotifyBtn();
1833
+ };
1834
+
1835
+ $('updateBanner').onclick = (e) => {
1836
+ const btn = e.target.closest('[data-dismiss-update]');
1837
+ if (!btn) return;
1838
+ try { localStorage.setItem('ao.updateDismiss', btn.dataset.dismissUpdate); } catch (err) { /* ignore */ }
1839
+ $('updateBanner').hidden = true;
1840
+ };
1841
+ $('quotaBanner').onclick = (e) => {
1842
+ const btn = e.target.closest('[data-dismiss-quota]');
1843
+ if (!btn) return;
1844
+ S.dismissedQuotas[btn.dataset.dismissQuota] = Number(btn.dataset.resetsAt) || 0;
1845
+ saveMap('ao.quotaDismiss', S.dismissedQuotas);
1846
+ renderQuotaBanner(); renderUpdateBanner();
1847
+ };
1848
+
1849
+ // theme: follows the system until the person picks one, then the choice is kept in localStorage
1850
+ const lightQuery = window.matchMedia ? window.matchMedia('(prefers-color-scheme: light)') : null;
1851
+ function savedTheme() { const v = safeGet('ao.theme'); return v === 'day' || v === 'night' ? v : null; }
1852
+ function applyTheme() {
1853
+ const th = savedTheme() || (lightQuery && lightQuery.matches ? 'day' : 'night');
1854
+ document.documentElement.setAttribute('data-theme', th);
1855
+ $('themeBtn').setAttribute('aria-pressed', String(th === 'day'));
1856
+ }
1857
+ if (lightQuery) {
1858
+ const onScheme = () => { if (!savedTheme()) applyTheme(); };
1859
+ if (lightQuery.addEventListener) lightQuery.addEventListener('change', onScheme); else if (lightQuery.addListener) lightQuery.addListener(onScheme);
1860
+ }
1861
+ $('themeBtn').onclick = () => { safeSet('ao.theme', document.documentElement.getAttribute('data-theme') === 'day' ? 'night' : 'day'); applyTheme(); };
1862
+
1863
+ // "How it works": a modal <dialog>. showModal() makes the page behind it inert and Esc closes it natively;
1864
+ // the keydown handler keeps Tab inside the dialog and covers browsers without showModal().
1865
+ const help = $('help');
1866
+ let helpOpener = null;
1867
+ function openHelp() {
1868
+ if (help.open) return;
1869
+ helpOpener = document.activeElement;
1870
+ if (typeof help.showModal === 'function') help.showModal(); else help.setAttribute('open', '');
1871
+ $('helpClose').focus();
1872
+ }
1873
+ // focus goes back to whatever opened the dialog (header button or the empty-state button)
1874
+ function restoreFocus() { (helpOpener && document.contains(helpOpener) ? helpOpener : $('helpBtn')).focus(); helpOpener = null; }
1875
+ function closeHelp() {
1876
+ if (!help.open) return;
1877
+ if (typeof help.close === 'function') help.close(); else { help.removeAttribute('open'); restoreFocus(); }
1878
+ }
1879
+ $('helpBtn').onclick = openHelp;
1880
+ $('helpClose').onclick = closeHelp;
1881
+ help.addEventListener('close', restoreFocus);
1882
+ help.addEventListener('click', (e) => { if (e.target === help) closeHelp(); });
1883
+ help.addEventListener('keydown', (e) => {
1884
+ if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); closeHelp(); return; }
1885
+ if (e.key !== 'Tab') return;
1886
+ const items = [...help.querySelectorAll('button, [href], input, select, [tabindex]:not([tabindex="-1"])')];
1887
+ if (!items.length) return;
1888
+ const first = items[0], last = items[items.length - 1];
1889
+ if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
1890
+ else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
1891
+ });
1892
+ $('pauseBtn').onclick = () => {
1893
+ S.paused = !S.paused; $('pauseBtn').setAttribute('aria-pressed', S.paused); applyStatic(); renderLive();
1894
+ if (!S.paused) { poll(); loadTrace(); if (S.view === 'reports') loadReports(); }
1895
+ };
1896
+ const langMenu = (open) => { $('langMenu').hidden = !open; $('langBtn').setAttribute('aria-expanded', open); if (open) { const c = $('langMenu').querySelector('[aria-checked="true"]'); if (c) c.focus(); } };
1897
+ $('langBtn').onclick = (e) => { e.stopPropagation(); langMenu($('langMenu').hidden); };
1898
+ $('langMenu').onclick = (e) => {
1899
+ const b = e.target.closest('[data-lang]'); if (!b) return;
1900
+ S.lang = b.dataset.lang; safeSet('ao.lang', S.lang); langMenu(false); applyStatic();
1901
+ for (const id of ['kpis', 'rooms', 'side', 'toolChips', 'topo', 'quotaBanner', 'updateBanner', 'reports']) if ($(id)) $(id)._html = null;
1902
+ if (S.data) render();
1903
+ else if (S.view === 'reports') renderReports();
1904
+ if (studio) studio.relabel();
1905
+ $('langBtn').focus();
1906
+ };
1907
+ $('langMenu').onkeydown = (e) => {
1908
+ const items = [...$('langMenu').querySelectorAll('button')], i = items.indexOf(document.activeElement);
1909
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); items[(i + (e.key === 'ArrowDown' ? 1 : items.length - 1)) % items.length].focus(); }
1910
+ else if (e.key === 'Escape') { e.stopPropagation(); langMenu(false); $('langBtn').focus(); }
1911
+ };
1912
+ document.addEventListener('click', (e) => { if (!$('langMenu').hidden && !e.target.closest('.lang')) langMenu(false); });
1913
+ $('hours').onchange = (e) => { S.hours = +e.target.value; safeSet('ao.hours', S.hours); renderRooms(); };
1914
+ $('showDone').onchange = (e) => { S.showDone = e.target.checked; S.closedQuiet.clear(); safeSet('ao.done', S.showDone ? '1' : '0'); renderRooms(); };
1915
+ $('q').oninput = (e) => { S.q = e.target.value.trim().toLowerCase(); renderRooms(); };
1916
+ $('toolChips').onclick = (e) => { const b = e.target.closest('[data-tool]'); if (!b) return; S.tool = b.dataset.tool; renderChips(); renderRooms(); };
1917
+ $('rooms').onclick = (e) => {
1918
+ if (e.target.closest('[data-help]')) { openHelp(); return; }
1919
+ if (e.target.closest('[data-clear]')) { S.q = ''; $('q').value = ''; S.tool = 'all'; renderChips(); renderRooms(); return; }
1920
+ const op = e.target.closest('[data-open-id]');
1921
+ if (op) { e.stopPropagation(); openAgentPath(op.dataset.openId, op.dataset.openWhat); return; }
1922
+ const dis = e.target.closest('[data-dismiss]');
1923
+ if (dis) { dismissSession(dis.dataset.dismiss); return; }
1924
+ const more = e.target.closest('[data-more]');
1925
+ if (more) { toggleSet(S.openRooms, more.dataset.more); renderRooms(); return; }
1926
+ const k = e.target.closest('[data-kids]');
1927
+ if (k) { toggleSet(S.openKids, k.dataset.kids); renderRooms(); renderTopo(); return; }
1928
+ const rh = e.target.closest('[data-toggle-room]');
1929
+ if (rh) { toggleRoom(rh.dataset.toggleRoom, rh.dataset.roomKind); return; }
1930
+ const a = e.target.closest('.agent'); if (a) toggleRow(a.dataset.id);
1931
+ };
1932
+ $('topoBtn').onclick = () => { S.topo = !S.topo; safeSet('ao.topo', S.topo ? '1' : '0'); renderTopo(); };
1933
+ $('topo').onclick = (e) => { const n = e.target.closest('.node'); if (n) select(S.sel === n.dataset.id ? null : n.dataset.id); };
1934
+ $('topo').onkeydown = (e) => { if (e.key === 'Enter' || e.key === ' ') { const n = e.target.closest('.node'); if (n) { e.preventDefault(); select(n.dataset.id); } } };
1935
+ let topoW = 0;
1936
+ new ResizeObserver(() => { const w = $('topo').clientWidth; if (S.data && Math.abs(w - topoW) > 30) { topoW = w; renderTopo(); } }).observe($('topo'));
1937
+ $('rooms').onkeydown = (e) => {
1938
+ if (e.key !== 'Enter' && e.key !== ' ') return;
1939
+ if (e.target.matches('button')) return;
1940
+ const rh = e.target.closest('[data-toggle-room]'); if (rh) { e.preventDefault(); toggleRoom(rh.dataset.toggleRoom, rh.dataset.roomKind); return; }
1941
+ const a = e.target.closest('.agent'); if (a) { e.preventDefault(); toggleRow(a.dataset.id); }
1942
+ };
1943
+ function toggleSet(set, id) { if (set.has(id)) set.delete(id); else set.add(id); }
1944
+ function toggleRoom(id, kind) {
1945
+ if (kind === 'quiet') {
1946
+ if (S.showDone) toggleSet(S.closedQuiet, id);
1947
+ else { toggleSet(S.openQuiet, id); saveSet('ao.open', S.openQuiet); }
1948
+ } else {
1949
+ toggleSet(S.closedRooms, id); saveSet('ao.closed', S.closedRooms);
1950
+ }
1951
+ renderRooms();
1952
+ }
1953
+ function toggleRow(id) {
1954
+ if (S.openRows.has(id)) { S.openRows.delete(id); if (S.sel === id) select(null); }
1955
+ else { S.openRows.add(id); select(id); }
1956
+ renderRooms();
1957
+ }
1958
+ $('side').onclick = (e) => {
1959
+ if (e.target.closest('#back')) { select(null); return; }
1960
+ const op = e.target.closest('[data-open-id]');
1961
+ if (op) { e.stopPropagation(); openAgentPath(op.dataset.openId, op.dataset.openWhat); return; }
1962
+ const dis = e.target.closest('[data-dismiss]');
1963
+ if (dis) { dismissSession(dis.dataset.dismiss); return; }
1964
+ const tab = e.target.closest('[data-tab]');
1965
+ if (tab) { S.tab = tab.dataset.tab; renderSide(); }
1966
+ };
1967
+
1968
+ $('reports').onclick = (e) => {
1969
+ const step = e.target.closest('[data-day-step]');
1970
+ if (step) { stepReportDay(+step.dataset.dayStep); return; }
1971
+ if (e.target.closest('#repCopyMd')) { copyReportMarkdown(); return; }
1972
+ if (e.target.closest('#repDlMd')) { downloadReportMarkdown(); return; }
1973
+ const ws = e.target.closest('[data-rep-ws]');
1974
+ if (ws) { toggleSet(S.reportClosedWs, ws.dataset.repWs); renderReports(); return; }
1975
+ const ag = e.target.closest('[data-rep-agent]');
1976
+ if (ag) { focusAgent(ag.dataset.repAgent); return; }
1977
+ };
1978
+ $('reports').onkeydown = (e) => {
1979
+ if (e.key === 'Enter' || e.key === ' ') {
1980
+ const ag = e.target.closest('g[data-rep-agent]');
1981
+ if (ag) { e.preventDefault(); focusAgent(ag.dataset.repAgent); }
1982
+ }
1983
+ };
1984
+ $('reports').addEventListener('mousemove', (e) => {
1985
+ const qPlot = e.target.closest('[data-quota-plot]');
1986
+ if (qPlot) { updateQuotaHover(e, qPlot); return; }
1987
+ const tEl = e.target.closest('[data-tip]');
1988
+ if (tEl) { showChartTip(tEl.dataset.tip, e.clientX, e.clientY); return; }
1989
+ hideChartTip();
1990
+ });
1991
+ $('reports').addEventListener('mouseleave', hideChartTip);
1992
+ $('reports').addEventListener('scroll', hideChartTip);
1993
+ $('reports').addEventListener('focusin', (e) => {
1994
+ const tEl = e.target.closest('[data-tip]');
1995
+ if (!tEl) return;
1996
+ const r = tEl.getBoundingClientRect();
1997
+ showChartTip(tEl.dataset.tip, r.left + r.width / 2, r.top);
1998
+ });
1999
+ $('reports').addEventListener('focusout', (e) => {
2000
+ if (e.target.closest('[data-tip]')) hideChartTip();
2001
+ });
2002
+
2003
+ document.addEventListener('keydown', (e) => {
2004
+ if (help.open) return;
2005
+ if (e.target.matches && e.target.matches('input, select, textarea')) { if (e.key === 'Escape') e.target.blur(); return; }
2006
+ if (e.key === '/' && S.view === 'office') { e.preventDefault(); $('q').focus(); }
2007
+ else if (e.key === 'Escape') {
2008
+ hideChartTip();
2009
+ if (S.view === 'studio' && studio && studio.onEscape) studio.onEscape();
2010
+ else if (S.view === 'office') select(null);
2011
+ }
2012
+ else if (e.key === 'v' || e.key === 'V') {
2013
+ const order = ['office', 'studio', 'reports'];
2014
+ setView(order[(order.indexOf(S.view) + 1) % order.length]);
2015
+ }
2016
+ else if ((e.key === 'ArrowLeft' || e.key === 'ArrowRight') && S.view === 'reports' && !e.altKey && !e.ctrlKey && !e.metaKey) {
2017
+ e.preventDefault();
2018
+ const rtl = document.documentElement.dir === 'rtl';
2019
+ const step = e.key === 'ArrowLeft' ? (rtl ? 1 : -1) : (rtl ? -1 : 1);
2020
+ stepReportDay(step);
2021
+ }
2022
+ else if ((e.key === 'j' || e.key === 'k') && S.view === 'office') {
2023
+ const rows = [...document.querySelectorAll('.agent')]; if (!rows.length) return;
2024
+ const i = rows.findIndex((r) => r.dataset.id === S.sel);
2025
+ const n = rows[Math.max(0, Math.min(rows.length - 1, i < 0 ? 0 : i + (e.key === 'j' ? 1 : -1)))];
2026
+ select(n.dataset.id); n.scrollIntoView({ block: 'nearest' }); n.focus({ preventScroll: true });
2027
+ }
2028
+ });
2029
+
2030
+ applyTheme();
2031
+ applyStatic();
2032
+ setView(S.view);
2033
+ poll();
2034
+ })();