jaxon-agents 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.agent.md +203 -168
  2. package/README.md +51 -34
  3. package/README.zh-CN.md +55 -38
  4. package/dist/BUILD_INFO.json +3 -3
  5. package/dist/PACKAGE_MANIFEST.json +63 -42
  6. package/dist/RELEASE_META.json +8 -2
  7. package/dist/agents/directory-store.js +66 -11
  8. package/dist/agents/jaxon-admin.entry.js +5 -3
  9. package/dist/agents/session-switch.js +6 -0
  10. package/dist/api/mcp-tools.js +76 -45
  11. package/dist/connections/health.js +4 -1
  12. package/dist/console/activity-client.js +644 -0
  13. package/dist/console/activity-page.js +24 -0
  14. package/dist/console/activity-topics.js +698 -0
  15. package/dist/console/activity.js +379 -0
  16. package/dist/console/assets.js +394 -241
  17. package/dist/console/chat-library.js +685 -0
  18. package/dist/console/console-info.js +30 -0
  19. package/dist/console/icons.js +14 -0
  20. package/dist/console/pages.js +94 -31
  21. package/dist/console/server.js +58 -8
  22. package/dist/console/station-pages.js +83 -25
  23. package/dist/daemon/client.js +1 -1
  24. package/dist/daemon/host.js +16 -3
  25. package/dist/environment/pi-launch-spec.js +1 -1
  26. package/dist/index.js +87 -8
  27. package/dist/launcher.js +17 -26
  28. package/dist/ops/catalog.js +18 -14
  29. package/dist/ops/core.js +157 -77
  30. package/dist/pi-host/history-reader.js +20 -0
  31. package/dist/pi-host/mcp-bridge.entry.js +55 -7
  32. package/dist/platform/index.js +22 -0
  33. package/dist/platform/linux.js +64 -0
  34. package/dist/release/handoff.js +6 -8
  35. package/dist/release/store.js +3 -13
  36. package/dist/sessions/dashboard-usage.js +5 -3
  37. package/dist/sessions/supervisor.js +449 -60
  38. package/dist/stations/activity.js +24 -28
  39. package/dist/stations/boards.js +10 -5
  40. package/dist/stations/cues.js +71 -48
  41. package/dist/stations/interactions.js +75 -0
  42. package/dist/stations/member-instructions.js +23 -0
  43. package/dist/stations/station-member.entry.js +31 -14
  44. package/examples/README.md +23 -8
  45. package/examples/agents/README.md +93 -35
  46. package/examples/agents/coder/README.md +37 -0
  47. package/examples/agents/custom-gateway/README.md +42 -0
  48. package/examples/agents/local-qwen/README.md +46 -0
  49. package/examples/agents/planner/README.md +39 -0
  50. package/examples/agents/reviewer/README.md +42 -0
  51. package/examples/mcp-clients/README.md +35 -16
  52. package/examples/stations/README.md +98 -21
  53. package/examples/stations/dev-loop/README.md +40 -0
  54. package/examples/stations/parallel-coders/README.md +40 -0
  55. package/examples/stations/parallel-coders/STATION.md +2 -2
  56. package/examples/stations/research-writer/README.md +39 -0
  57. package/examples/stations/research-writer/STATION.md +1 -1
  58. package/examples/workflows/01-dev-loop-e2e.md +27 -5
  59. package/examples/workflows/02-human-auth-and-roster-switch.md +25 -3
  60. package/examples/workflows/README.md +17 -0
  61. package/package.json +8 -2
  62. package/runtime/provenance.json +3 -3
  63. package/runtime/runtime-lock.json +2 -2
  64. package/runtime/runtime-package.json +1 -1
@@ -0,0 +1,644 @@
1
+ import { consoleIcon } from "./icons.js";
2
+ export const ACTIVITY_JS = String.raw `
3
+ function mountStationActivity() {
4
+ const root = document.querySelector('[data-station-activity]');
5
+ if (!root || root.dataset.mounted) return;
6
+ root.dataset.mounted = 'true';
7
+ const overview = root.hasAttribute('data-overview-activity');
8
+ const find = selector => root.querySelector(selector);
9
+ const stage = find('[data-activity-stage]'), scene = stage.parentElement;
10
+ const hub = find('.activity-hub'), lanes = [...root.querySelectorAll('.activity-lane')];
11
+ const svg = find('[data-activity-edges]'), trails = find('[data-activity-trails]'), pulseLayer = find('[data-activity-pulses]');
12
+ const status = find('[data-activity-status]'), empty = find('[data-activity-empty]'), title = find('[data-activity-title]');
13
+ const buttons = [...root.querySelectorAll('[data-activity-window]')];
14
+ const motion = matchMedia('(prefers-reduced-motion: reduce)');
15
+ const cards = new Map(), edges = new Map(), watchTopics = new Map(), departures = new Map(), moves = new Map(), pulses = new Set();
16
+ const animated = new Set(), cueArrivals = new Map();
17
+ let windowName = '10m', snapshot, cursor, clock = 0, offline = false, ghost, tooltipOwner;
18
+ let generation = 0, controller, timer, lastStart = -Infinity, failures = 0, frame = 0, needsLayout = false, motionUntil = 0;
19
+ const svgNode = name => document.createElementNS('http://www.w3.org/2000/svg', name);
20
+ const icons = {
21
+ spark: ${JSON.stringify(consoleIcon("spark"))},
22
+ settings: ${JSON.stringify(consoleIcon("settings"))},
23
+ cue: ${JSON.stringify(consoleIcon("cue"))},
24
+ };
25
+ const icon = name => {
26
+ const template = document.createElement('template');
27
+ template.innerHTML = icons[name];
28
+ return template.content.firstElementChild;
29
+ };
30
+ const setText = (node, text) => { if (node.textContent !== text) node.textContent = text; };
31
+ const dates = value => Date.parse(value) || 0;
32
+ const edgeKey = edge => [edge.from, edge.to, edge.kind].join('\0');
33
+ const running = new Set(['starting', 'running', 'stopping']);
34
+ const hues = [204, 266, 172, 325, 218, 28];
35
+ const hueFor = id => hues[[...id].reduce((hash, ch) => (31 * hash + ch.codePointAt(0)) >>> 0, 0) % hues.length];
36
+ const tooltip = el('div', {className:'activity-tooltip', attrs:{'aria-hidden':'true'}});
37
+ tooltip.hidden = true;
38
+ root.append(tooltip);
39
+
40
+ function animate(element, keyframes, options, finish) {
41
+ if (motion.matches) { finish?.(); return; }
42
+ const animation = element.animate(keyframes, options);
43
+ animated.add(animation);
44
+ animation.onfinish = () => { animated.delete(animation); finish?.(); };
45
+ animation.oncancel = () => animated.delete(animation);
46
+ return animation;
47
+ }
48
+ const restOpacity = element => element.classList.contains('activity-node')
49
+ ? Number(getComputedStyle(element).getPropertyValue('--card-opacity')) : 1;
50
+ function fadeIn(element) { animate(element, [{opacity:0}, {opacity:restOpacity(element)}], {duration:420, easing:'ease-out'}); }
51
+ function leave(element, remove) {
52
+ if (departures.has(element)) return;
53
+ if (motion.matches) { remove(); return; }
54
+ element.inert = true;
55
+ const finish = () => { departures.delete(element); remove(); };
56
+ departures.set(element, {finish, animation:animate(element, [{opacity:getComputedStyle(element).opacity}, {opacity:0}],
57
+ {duration:380, easing:'ease-in', fill:'forwards'}, finish)});
58
+ }
59
+ function revive(element) {
60
+ const departure = departures.get(element);
61
+ if (!departure) return;
62
+ const opacity = getComputedStyle(element).opacity;
63
+ departure.animation.cancel(); departures.delete(element);
64
+ element.inert = false;
65
+ animate(element, [{opacity}, {opacity:restOpacity(element)}], {duration:350, easing:'ease-out'});
66
+ }
67
+
68
+ function toggleTopic(row, over, focus) {
69
+ if (over !== undefined) row.over = over;
70
+ if (focus !== undefined) row.focus = focus;
71
+ if (row.scroll) {
72
+ if (row.over || row.focus || document.hidden) row.scroll.pause();
73
+ else if (row.scroll.playState === 'paused') row.scroll.play();
74
+ }
75
+ if ((row.over || row.focus) && row.text) {
76
+ tooltipOwner = row;
77
+ setText(tooltip, row.description);
78
+ tooltip.hidden = false;
79
+ locateTooltip();
80
+ } else if (tooltipOwner === row) hideTooltip();
81
+ }
82
+ function hideTooltip() { tooltip.hidden = true; tooltipOwner = undefined; }
83
+ function locateTooltip() {
84
+ if (!tooltipOwner) return;
85
+ const box = tooltipOwner.trigger.getBoundingClientRect(), bounds = root.getBoundingClientRect();
86
+ const clip = tooltipOwner.trigger.closest('.activity-sessions').getBoundingClientRect();
87
+ if (box.bottom < clip.top || box.top > clip.bottom) { hideTooltip(); return; }
88
+ tooltip.style.left = Math.max(10, Math.min(box.left - bounds.left, bounds.width - tooltip.offsetWidth - 10)) + 'px';
89
+ tooltip.style.top = Math.min(bounds.height - tooltip.offsetHeight - 8, box.bottom - bounds.top + 6) + 'px';
90
+ }
91
+ function measureTopic(row) {
92
+ const distance = Math.ceil(row.track.offsetWidth - row.viewport.clientWidth);
93
+ if (row.distance === distance && row.reduced === motion.matches) return;
94
+ row.distance = distance; row.reduced = motion.matches;
95
+ row.scroll?.cancel(); row.scroll = null;
96
+ row.viewport.classList.toggle('overflowing', distance > 2);
97
+ if (motion.matches || distance <= 2) return;
98
+ const leg = distance / 45 * 1000, pause = 850, duration = (leg + pause) * 2;
99
+ row.scroll = row.track.animate([
100
+ {transform:'translateX(0px)', offset:0}, {transform:'translateX(0px)', offset:pause / duration},
101
+ {transform:'translateX(-' + distance + 'px)', offset:(pause + leg) / duration},
102
+ {transform:'translateX(-' + distance + 'px)', offset:(2 * pause + leg) / duration},
103
+ {transform:'translateX(0px)', offset:1},
104
+ ], {duration, iterations:Infinity});
105
+ if (row.over || row.focus || document.hidden) row.scroll.pause();
106
+ }
107
+ const resize = new ResizeObserver(entries => {
108
+ for (const entry of entries) {
109
+ const row = watchTopics.get(entry.target);
110
+ if (row) measureTopic(row);
111
+ else scheduleFrame(true);
112
+ }
113
+ });
114
+ resize.observe(stage);
115
+
116
+ function sessionState(session) {
117
+ if (session.status === 'closed') return ['closed', 'Closed'];
118
+ if (session.status === 'waiting_input') return ['waiting_input', 'Waiting for input'];
119
+ if (running.has(session.status)) return ['running', 'Running'];
120
+ if (session.queued_turns > 0) return ['queued', 'Queued'];
121
+ if (session.status === 'failed') return ['failed', 'Failed'];
122
+ return ['idle', 'Idle'];
123
+ }
124
+ const cueLabels = {
125
+ scheduled: 'Will be delivered on the next turn', cooldown: 'Wake cooling down',
126
+ rate_limited: 'Wake limit reached', deferred_cap: 'Wake deferred',
127
+ hop_limit: 'No wake: relay limit', blocked: 'Wake blocked',
128
+ not_runnable: 'Session cannot run',
129
+ };
130
+ const unread = count => count + ' unread cues';
131
+ function cueDescription(cue) {
132
+ if (!cue?.count) return '';
133
+ const state = cueLabels[cue.wake];
134
+ return [unread(cue.count), cue.senders?.join(', '), state].filter(Boolean).join(' · ');
135
+ }
136
+
137
+ function setChatTarget(trigger, agent, session) {
138
+ trigger.href = '/sessions/' + encodeURIComponent(session.session_id);
139
+ trigger.dataset.jaxonChat = session.session_id;
140
+ trigger.dataset.jaxonChatAgent = agent;
141
+ }
142
+ function sessionRow(session) {
143
+ const badge = el('span', {className:'activity-state-dot', attrs:{'aria-hidden':'true'}});
144
+ const track = el('span', {className:'activity-topic-track'});
145
+ const viewport = el('span', {className:'activity-topic-viewport'}, [track]);
146
+ const cueBadge = el('span', {className:'cue-badge activity-cue-count'}); cueBadge.hidden = true;
147
+ const cueIcon = el('span', {className:'activity-cue-origin'}, [icon('cue')]); cueIcon.hidden = true;
148
+ const trigger = el('a', {className:'activity-session', attrs:{
149
+ 'data-session-id':session.session_id, 'aria-haspopup':'dialog'}}, [badge, cueBadge, cueIcon, viewport]);
150
+ const row = {trigger, badge, cueBadge, cueIcon, track, viewport};
151
+ trigger.addEventListener('pointerenter', () => toggleTopic(row, true));
152
+ trigger.addEventListener('pointerleave', () => toggleTopic(row, false));
153
+ trigger.addEventListener('focus', () => toggleTopic(row, undefined, true));
154
+ trigger.addEventListener('blur', () => toggleTopic(row, undefined, false));
155
+ trigger.addEventListener('click', () => { if (tooltipOwner === row) hideTooltip(); });
156
+ watchTopics.set(viewport, row); resize.observe(viewport);
157
+ return row;
158
+ }
159
+ function clearRow(row) {
160
+ if (tooltipOwner === row) hideTooltip();
161
+ resize.unobserve(row.viewport); watchTopics.delete(row.viewport);
162
+ row.scroll?.cancel(); row.trigger.remove();
163
+ }
164
+ function updateRow(row, session, arriving = false) {
165
+ row.latestSession = session;
166
+ const cue = session.pending_cues;
167
+ const rise = (cue?.count ?? 0) > (row.cueCount ?? 0);
168
+ const arrival = cueArrivals.get(session.session_id);
169
+ const startingCue = session.origin === 'cue' && !row.cueOrigin;
170
+ if (arrival && row.text !== undefined && (rise || startingCue)) {
171
+ arrival.startsTurn = startingCue;
172
+ arrival.row = row;
173
+ return false;
174
+ }
175
+ const [state, name] = sessionState(session), topic = session.topic;
176
+ const topicText = topic?.text || 'Session';
177
+ const summary = topic?.state === 'generating' || topic?.stale ? 'Updating summary'
178
+ : topic?.source === 'fallback' ? 'No model summary yet' : '';
179
+ row.trigger.dataset.state = row.badge.dataset.state = state;
180
+ row.trigger.classList.toggle('closed', state === 'closed');
181
+ row.trigger.classList.toggle('activity-fallback', topic?.source === 'fallback');
182
+ row.trigger.dataset.topicSource = topic?.source ?? 'fallback';
183
+ row.cueCount = cue?.count ?? 0;
184
+ row.cueOrigin = session.origin === 'cue';
185
+ row.cueBadge.hidden = !row.cueCount;
186
+ if (row.cueCount) setText(row.cueBadge, String(row.cueCount));
187
+ row.cueIcon.hidden = !row.cueOrigin;
188
+ const cueText = cueDescription(cue);
189
+ const origin = row.cueOrigin ? 'Woken by a cue' : '';
190
+ row.cueBadge.title = cueText; row.cueIcon.title = origin;
191
+ if (arriving && rise) animate(row.cueBadge, [{transform:'scale(1.22)', color:'#fff'}, {transform:'scale(1)'}], {duration:340, easing:'ease-out'});
192
+ row.description = [topicText, name, cueText, origin, summary, session.session_id].filter(Boolean).join(' · ');
193
+ row.trigger.setAttribute('aria-label', ['Open chat', topicText, name, cueText, origin].filter(Boolean).join(' · '));
194
+ if (row.text !== topicText) {
195
+ row.text = topicText;
196
+ setText(row.track, topicText);
197
+ row.distance = undefined;
198
+ }
199
+ if (tooltipOwner === row) setText(tooltip, row.description);
200
+ return true;
201
+ }
202
+
203
+ function createCard(node) {
204
+ const master = node.kind === 'master';
205
+ const light = el('div', {className:'activity-light', attrs:{'aria-hidden':'true'}});
206
+ const badge = el('span', {className:'activity-emblem', attrs:{'aria-hidden':'true'}},
207
+ [master ? icon('spark') : el('span', {text:[...node.id][0]?.toUpperCase() ?? ''})]);
208
+ const name = el('span', {text:master ? 'Master' : node.id});
209
+ const heading = el('h3', {className:'activity-name'}, [name]);
210
+ const count = el('small', {className:'activity-count'});
211
+ const identity = el('div', {className:'activity-identity'}, [heading, count]);
212
+ const top = el('div', {className:'activity-node-head'}, [badge, identity]);
213
+ const card = el('article', {className:'activity-node' + (master ? ' master' : ''), attrs:{'data-agent-id':node.id}}, [light, top]);
214
+ card.style.setProperty('--role-hue', String(master ? 42 : hueFor(node.id)));
215
+ const rows = new Map();
216
+ if (master) { hub.append(card); return {card, name, count, rows}; }
217
+ const openSession = el('a', {className:'activity-name-chat', text:node.id,
218
+ attrs:{'aria-haspopup':'dialog'}});
219
+ openSession.hidden = true;
220
+ heading.append(openSession);
221
+ const gear = el('a', {className:'activity-gear', attrs:{href:node.url}}, [icon('settings')]);
222
+ const cueCount = el('span', {className:'cue-badge'}); cueCount.hidden = true;
223
+ top.append(cueCount, gear);
224
+ const list = el('div', {className:'activity-sessions'});
225
+ const more = el('a', {className:'activity-more', attrs:{href:'/sessions?' + new URLSearchParams({station:snapshot.station_id, agent:node.id})}});
226
+ const stack = el('div', {className:'activity-session-stack'}, [more]);
227
+ list.append(stack); card.append(list);
228
+ const lane = lanes[0].childElementCount <= lanes[1].childElementCount ? lanes[0] : lanes[1];
229
+ lane.append(card);
230
+ return {card, name, openSession, count, cueCount, gear, list, stack, more, rows};
231
+ }
232
+ function fitSessions(view, change, first = false) {
233
+ const before = view.list.getBoundingClientRect().height;
234
+ const previous = view.listMotion;
235
+ change();
236
+ const max = parseFloat(getComputedStyle(view.list).maxHeight) || Infinity;
237
+ const after = Math.min(view.stack.offsetHeight, max);
238
+ if (previous && previous.target === after) return;
239
+ previous?.animation.cancel(); view.listMotion = undefined;
240
+ if (first || motion.matches || Math.abs(before - after) < 1) return;
241
+ // Resize in flow so the cards below move without crossing each other.
242
+ const animation = animate(view.list, [{height:before + 'px'}, {height:after + 'px'}],
243
+ {duration:460, easing:'cubic-bezier(.25,.7,.25,1)'}, () => { view.listMotion = undefined; scheduleFrame(true); });
244
+ view.listMotion = {animation, target:after};
245
+ motionUntil = performance.now() + 475;
246
+ scheduleFrame(true);
247
+ }
248
+ function updateCard(view, node, first) {
249
+ view.node = node;
250
+ if (node.kind === 'master') {
251
+ setText(view.name, 'Master');
252
+ setText(view.count, 'Station coordinator');
253
+ return;
254
+ }
255
+ view.card.classList.toggle('former', !node.in_roster);
256
+ const count = node.active_sessions + ' active' + ' / ' + node.window_sessions + ' in window';
257
+ setText(view.count, count + (node.in_roster ? '' : ' · former'));
258
+ const single = node.window_sessions === 1 && node.sessions.length === 1;
259
+ view.openSession.hidden = !single; view.name.hidden = single;
260
+ if (single) {
261
+ setChatTarget(view.openSession, node.id, node.sessions[0]);
262
+ view.openSession.setAttribute('aria-label', 'Open chat with ' + node.id);
263
+ } else {
264
+ delete view.openSession.dataset.jaxonChat;
265
+ view.openSession.removeAttribute('href');
266
+ }
267
+ view.gear.title = 'Open agent settings';
268
+ view.gear.setAttribute('aria-label', view.gear.title + ': ' + node.id);
269
+ view.cueCount.hidden = !node.pending_cues;
270
+ if (node.pending_cues) {
271
+ setText(view.cueCount, String(node.pending_cues)); view.cueCount.title = unread(node.pending_cues);
272
+ view.cueCount.setAttribute('aria-label', view.cueCount.title);
273
+ }
274
+ fitSessions(view, () => {
275
+ const truncated = node.window_sessions - node.sessions.length;
276
+ view.more.hidden = truncated <= 0;
277
+ if (truncated > 0) setText(view.more, 'View all sessions →');
278
+ const ids = new Set(node.sessions.map(session => session.session_id));
279
+ for (const [id, row] of view.rows) {
280
+ if (!ids.has(id)) {
281
+ const clear = () => { clearRow(row); view.rows.delete(id); };
282
+ if (motion.matches) clear();
283
+ else leave(row.trigger, () => fitSessions(view, clear));
284
+ }
285
+ }
286
+ for (const session of node.sessions) {
287
+ let row = view.rows.get(session.session_id);
288
+ const fresh = !row;
289
+ if (fresh) { row = sessionRow(session); view.rows.set(session.session_id, row); }
290
+ revive(row.trigger);
291
+ setChatTarget(row.trigger, node.id, session);
292
+ if (!updateRow(row, session)) cueArrivals.get(session.session_id).view = view;
293
+ // Keep the relative order of existing rows; scrolling and focus stay in place.
294
+ if (fresh) { view.stack.insertBefore(row.trigger, view.more); fadeIn(row.trigger); measureTopic(row); }
295
+ else if (row.distance === undefined) measureTopic(row);
296
+ }
297
+ }, first);
298
+ cueCardActivity(view);
299
+ }
300
+ function cueCardActivity(view) {
301
+ const delayed = view.node.sessions.filter(session => session.origin === 'cue' &&
302
+ cueArrivals.get(session.session_id)?.startsTurn).length;
303
+ view.card.classList.toggle('active', view.node.active_sessions > delayed);
304
+ }
305
+ function compactCard(view) {
306
+ const before = new Map([...cards.values()].filter(other => other !== view && other.node.kind !== 'master')
307
+ .map(other => [other.card, other.card.getBoundingClientRect().top]));
308
+ disposeCard(view);
309
+ const after = [...before].map(([card, y]) => [card, y - (card.getBoundingClientRect().top - (moves.get(card) ? translateY(card) : 0))]);
310
+ if (!motion.matches) for (const [card, delta] of after) {
311
+ if (Math.abs(delta) < .5) continue;
312
+ moves.get(card)?.cancel();
313
+ moves.set(card, animate(card, [{transform:'translateY(' + delta + 'px)'}, {transform:'translateY(0px)'}],
314
+ {duration:520, easing:'cubic-bezier(.25,.7,.25,1)'}, () => { moves.delete(card); scheduleFrame(true); }));
315
+ motionUntil = performance.now() + 530;
316
+ }
317
+ scheduleFrame(true);
318
+ }
319
+ function translateY(card) {
320
+ const transform = getComputedStyle(card).transform;
321
+ return transform === 'none' ? 0 : new DOMMatrixReadOnly(transform).m42;
322
+ }
323
+ function disposeCard(view) {
324
+ for (const row of view.rows.values()) { departures.get(row.trigger)?.animation.cancel(); departures.delete(row.trigger); clearRow(row); }
325
+ view.listMotion?.animation.cancel();
326
+ moves.get(view.card)?.cancel(); moves.delete(view.card);
327
+ view.card.remove(); cards.delete(view.node.id);
328
+ }
329
+
330
+ function route(edge, boxes) {
331
+ const a = boxes.get(edge.from), b = boxes.get(edge.to);
332
+ if (!a || !b) return null;
333
+ const report = edge.kind === 'report';
334
+ const port = box => Math.min(box.bottom - 6, box.top + (edge.kind === 'cue' ? 25 : report ? 20 : 11));
335
+ const master = boxes.get('master');
336
+ if (edge.from === edge.to || (a.lane !== hub && b.lane !== hub && Math.abs(a.left - b.left) < 2)) {
337
+ // Same-column cues stay outside the lane rather than crossing other cards.
338
+ const left = master && a.right <= master.left;
339
+ const outer = box => left ? box.left : box.right;
340
+ const side = left ? -1 : 1;
341
+ const x = outer(a), y = port(a);
342
+ if (edge.from === edge.to) return [x, y - 12, x + side * 21, y - 14, x + side * 21, y + 15, x, y + 9];
343
+ const end = port(b);
344
+ return [x, y, x + side * 23, y, outer(b) + side * 23, end, outer(b), end];
345
+ }
346
+ const toMaster = edge.to === 'master';
347
+ const agent = toMaster ? a : b;
348
+ if (master && (toMaster || edge.from === 'master') && master.left < agent.right && master.right > agent.left) {
349
+ // The stacked mobile layout has a left gutter for dispatch and report.
350
+ const x = master.left + (report ? 17 : 8), y = master.bottom, end = port(agent);
351
+ const rail = agent.left - (report ? 11 : 18);
352
+ const curve = [x, y, rail, y + 9, rail, end, agent.left, end];
353
+ return toMaster ? [curve[6], curve[7], curve[4], curve[5], curve[2], curve[3], x, y] : curve;
354
+ }
355
+ const direction = a.left < b.left ? 1 : -1;
356
+ const x1 = direction > 0 ? a.right : a.left, x2 = direction > 0 ? b.left : b.right;
357
+ const y1 = port(a), y2 = port(b);
358
+ const bend = direction * Math.min(100, Math.abs(x1 - x2) * .45);
359
+ const bypassHub = edge.kind === 'cue' && master && master.left > Math.min(x1, x2) && master.right < Math.max(x1, x2);
360
+ const under = bypassHub ? (master.bottom + 10 - .125 * (y1 + y2)) / .75 : -Infinity;
361
+ return [x1, y1, x1 + bend, Math.max(y1, under), x2 - bend, Math.max(y2, under), x2, y2];
362
+ }
363
+ function layoutEdges() {
364
+ if (stage.hidden) return;
365
+ const rect = stage.getBoundingClientRect();
366
+ const boxes = new Map();
367
+ for (const [id, view] of cards) {
368
+ const box = view.card.getBoundingClientRect();
369
+ boxes.set(id, {left:box.left - rect.left, right:box.right - rect.left,
370
+ top:box.top - rect.top, bottom:box.bottom - rect.top, lane:view.card.parentNode});
371
+ }
372
+ for (const item of edges.values()) {
373
+ const next = route(item.edge, boxes);
374
+ if (!next) { item.curve = null; continue; }
375
+ item.curve = next;
376
+ const d = 'M ' + next[0] + ' ' + next[1] + ' C ' + next.slice(2).join(' ');
377
+ if (item.d !== d) { item.d = d; item.path.setAttribute('d', d); }
378
+ }
379
+ }
380
+ function flash(view, kind) {
381
+ if (!view || !view.card.isConnected) return;
382
+ view.flash?.cancel();
383
+ const color = kind === 'cue' ? '#cbafff' : kind === 'steer' ? '#ffb97c' : kind === 'dispatch' ? '#ffd592' : '#9ceceb';
384
+ view.flash = animate(view.card, [{outline:'2px solid ' + color, outlineOffset:'-1px'},
385
+ {outline:'2px solid transparent', outlineOffset:'5px'}], {duration:490, easing:'ease-out'});
386
+ }
387
+ function finishCueArrival(arrival, highlight = true) {
388
+ if (!arrival || cueArrivals.get(arrival.sessionId) !== arrival) return;
389
+ cueArrivals.delete(arrival.sessionId);
390
+ const { row, view } = arrival;
391
+ if (row?.trigger.isConnected) {
392
+ updateRow(row, row.latestSession, highlight);
393
+ if (row.distance === undefined) measureTopic(row);
394
+ }
395
+ if (view?.card.isConnected) { cueCardActivity(view); decay(); }
396
+ }
397
+ function clearPulses() {
398
+ for (const {point} of pulses) point.remove();
399
+ pulses.clear();
400
+ for (const arrival of cueArrivals.values()) finishCueArrival(arrival, false);
401
+ }
402
+ function launch(item, count) {
403
+ const edge = item.edge;
404
+ const arrival = edge.kind === 'cue' ? cueArrivals.get(edge.last?.to_session) : undefined;
405
+ const matchingArrival = arrival?.cueId === edge.last?.cue_id ? arrival : undefined;
406
+ const kind = edge.kind === 'dispatch' && edge.last?.delivery === 'steered' ? 'steer' : edge.kind;
407
+ for (let i = 0; i < count; i++) {
408
+ const point = svgNode('circle');
409
+ point.setAttribute('class', 'activity-pulse ' + kind);
410
+ point.setAttribute('r', kind === 'cue' ? '3.5' : '3');
411
+ point.setAttribute('visibility', 'hidden');
412
+ pulseLayer.append(point);
413
+ pulses.add({point, item, target:cards.get(edge.to), kind, start:performance.now() + i * 135, last:i === count - 1,
414
+ arrival:i === 0 ? matchingArrival : undefined});
415
+ }
416
+ scheduleFrame(true);
417
+ }
418
+ function movePulses(now) {
419
+ for (const pulse of pulses) {
420
+ const {point, item, target, kind, last, arrival} = pulse, p = item.curve;
421
+ const t = (now - pulse.start) / 890;
422
+ if (t < 0) continue;
423
+ if (t >= 1 || !p || !item.path.isConnected) {
424
+ point.remove(); pulses.delete(pulse);
425
+ finishCueArrival(arrival, t >= 1 && !!p);
426
+ if (t >= 1 && last) flash(target, kind);
427
+ continue;
428
+ }
429
+ const u = 1 - t;
430
+ point.setAttribute('visibility', 'visible');
431
+ point.setAttribute('transform', 'translate(' + (u*u*u*p[0] + 3*u*u*t*p[2] + 3*u*t*t*p[4] + t*t*t*p[6]) + ' '
432
+ + (u*u*u*p[1] + 3*u*u*t*p[3] + 3*u*t*t*p[5] + t*t*t*p[7]) + ')');
433
+ }
434
+ }
435
+ function scheduleFrame(layout = false) {
436
+ needsLayout ||= layout;
437
+ if (frame || document.hidden) return;
438
+ frame = requestAnimationFrame(now => {
439
+ frame = 0;
440
+ if (needsLayout || now < motionUntil) { needsLayout = false; layoutEdges(); locateTooltip(); }
441
+ movePulses(now);
442
+ if (pulses.size || now < motionUntil) scheduleFrame();
443
+ });
444
+ }
445
+ function newEdgeEvent(edge, old, previous) {
446
+ return old ? dates(edge.last_at) > dates(old.last_at) || edge.count > old.count
447
+ : dates(edge.last_at) >= dates(previous.now);
448
+ }
449
+ function syncEdges(previous, effects) {
450
+ const nextKeys = new Set(snapshot.edges.map(edgeKey));
451
+ for (const [key, item] of edges) {
452
+ if (!nextKeys.has(key)) leave(item.path, () => { item.path.remove(); edges.delete(key); });
453
+ }
454
+ const prior = new Map((previous?.edges ?? []).map(edge => [edgeKey(edge), edge]));
455
+ for (const edge of snapshot.edges) {
456
+ const key = edgeKey(edge);
457
+ let item = edges.get(key);
458
+ const fresh = !item;
459
+ if (fresh) {
460
+ const path = svgNode('path');
461
+ path.setAttribute('class', 'activity-edge ' + edge.kind);
462
+ trails.append(path);
463
+ item = {edge, path}; edges.set(key, item);
464
+ }
465
+ revive(item.path); item.edge = edge;
466
+ if (fresh) fadeIn(item.path);
467
+ if (!effects || motion.matches) continue;
468
+ const old = prior.get(key);
469
+ if (newEdgeEvent(edge, old, previous)) launch(item, old ? Math.min(3, Math.max(1, edge.count - old.count)) : 1);
470
+ }
471
+ scheduleFrame(true);
472
+ }
473
+
474
+ function brightness(at, now) {
475
+ const delta = Math.max(0, now - at);
476
+ return delta >= snapshot.window_ms ? 0 : Math.max(.08, Math.exp(-4 * delta / snapshot.window_ms));
477
+ }
478
+ function decay() {
479
+ if (!snapshot || document.hidden) return;
480
+ const now = Date.now() - clock;
481
+ let master = 0;
482
+ for (const edge of snapshot.edges) {
483
+ const value = brightness(dates(edge.last_at), now);
484
+ const item = edges.get(edgeKey(edge));
485
+ if (item) setHeat(item.path, value);
486
+ if (edge.to === 'master' || edge.from === 'master') master = Math.max(master, value);
487
+ }
488
+ for (const view of cards.values()) {
489
+ if (departures.has(view.card)) continue;
490
+ const node = view.node;
491
+ const value = node.kind === 'master' ? master : view.card.classList.contains('active') ? 1
492
+ : node.window_sessions ? brightness(dates(node.last_activity_at ?? node.sessions[0]?.last_activity_at), now) : .15;
493
+ setHeat(view.card, value);
494
+ }
495
+ }
496
+ function setHeat(element, value) {
497
+ const next = value.toFixed(4);
498
+ if (element.style.getPropertyValue('--heat') !== next) element.style.setProperty('--heat', next);
499
+ }
500
+
501
+ function crossFade() {
502
+ hideTooltip(); ghost?.remove();
503
+ if (!stage.hidden && !motion.matches) {
504
+ const old = stage.cloneNode(true);
505
+ old.classList.add('activity-outgoing'); old.setAttribute('aria-hidden', 'true'); old.inert = true;
506
+ old.style.height = stage.offsetHeight + 'px';
507
+ old.querySelector('[data-activity-pulses]').replaceChildren();
508
+ const oldRows = old.querySelectorAll('.activity-sessions');
509
+ stage.querySelectorAll('.activity-sessions').forEach((list, index) => { oldRows[index].dataset.scrollTop = list.scrollTop; });
510
+ scene.append(old); ghost = old;
511
+ for (const list of oldRows) list.scrollTop = Number(list.dataset.scrollTop);
512
+ animate(old, [{opacity:1}, {opacity:0}], {duration:460, easing:'ease-in-out'}, () => { old.remove(); if (ghost === old) ghost = null; });
513
+ }
514
+ for (const departure of departures.values()) departure.animation.cancel();
515
+ departures.clear();
516
+ for (const view of cards.values()) disposeCard(view);
517
+ clearPulses();
518
+ edges.clear(); trails.replaceChildren();
519
+ if (!stage.hidden) fadeIn(stage);
520
+ }
521
+ function updateStatus() {
522
+ const batch = snapshot?.topics_batch;
523
+ setText(status, offline ? 'Offline · retrying' : batch?.pending
524
+ ? 'Updating topics' + ' · ' + batch.pending : batch?.state === 'off'
525
+ ? 'Topics off' : '');
526
+ root.classList.toggle('activity-offline', offline);
527
+ }
528
+ function render(previous, effects) {
529
+ if (overview && previous && snapshot._selected?.station_id !== previous._selected?.station_id) crossFade();
530
+ updateStatus();
531
+ if (overview) {
532
+ setText(title, snapshot._selected?.name ?? 'Activity');
533
+ title.href = snapshot._selected?.url ?? '/stations';
534
+ }
535
+ stage.hidden = !snapshot.nodes.length;
536
+ empty.hidden = false;
537
+ if (!snapshot.nodes.length) empty.replaceChildren('No Stations yet. ',
538
+ el('a', {text:'Create a Station →', attrs:{href:'/stations?view=new'}}));
539
+ else if (!snapshot.edges.length && !snapshot.nodes.some(node => node.window_sessions)) {
540
+ setText(empty, 'No activity in this window.');
541
+ } else empty.hidden = true;
542
+ if (effects && !motion.matches) {
543
+ const prior = new Map(previous.edges.map(edge => [edgeKey(edge), edge]));
544
+ const visible = new Set(snapshot.nodes.map(node => node.id));
545
+ for (const edge of snapshot.edges) {
546
+ const sessionId = edge.last?.to_session, cueId = edge.last?.cue_id;
547
+ if (edge.kind !== 'cue' || !sessionId || !visible.has(edge.from) || !visible.has(edge.to)
548
+ || !newEdgeEvent(edge, prior.get(edgeKey(edge)), previous) || cueArrivals.has(sessionId)) continue;
549
+ cueArrivals.set(sessionId, { sessionId, cueId });
550
+ }
551
+ }
552
+ const ids = new Set(snapshot.nodes.map(node => node.id));
553
+ for (const [id, view] of cards) {
554
+ if (!ids.has(id)) leave(view.card, () => compactCard(view));
555
+ }
556
+ for (const node of snapshot.nodes) {
557
+ let view = cards.get(node.id);
558
+ const fresh = !view;
559
+ if (fresh) { view = createCard(node); cards.set(node.id, view); }
560
+ revive(view.card); updateCard(view, node, fresh);
561
+ if (fresh) fadeIn(view.card);
562
+ }
563
+ syncEdges(previous, effects);
564
+ decay();
565
+ }
566
+
567
+ const interval = () => windowName === '1m' || windowName === '10m' ? 5000 : 30000;
568
+ function queue(wait = 0) {
569
+ clearTimeout(timer);
570
+ if (!document.hidden) timer = setTimeout(requestActivity, Math.max(wait, lastStart + interval() + 12 - performance.now(), 0));
571
+ }
572
+ async function requestActivity() {
573
+ if (document.hidden) return;
574
+ const version = ++generation;
575
+ controller?.abort(); controller = new AbortController();
576
+ lastStart = performance.now();
577
+ const query = new URLSearchParams({window:windowName});
578
+ if (cursor) { query.set('since', cursor); query.set('wait_ms', interval() === 5000 ? '25000' : '55000'); }
579
+ const endpoint = overview ? '/api/overview/activity' : '/api/stations/' + encodeURIComponent(root.dataset.stationActivity) + '/activity';
580
+ try {
581
+ const response = await fetch(endpoint + '?' + query, {signal:controller.signal, cache:'no-store'});
582
+ if (!response.ok) throw new Error('activity_unavailable');
583
+ const body = await response.json();
584
+ if (version !== generation) return;
585
+ const next = overview ? {...(body.snapshot ?? {nodes:[], edges:[], topic_language:body.topic_language}), _selected:body.selected} : body;
586
+ const changed = !snapshot || body.changed !== false;
587
+ const recovered = offline;
588
+ offline = false; failures = 0;
589
+ if (next.now) clock = Date.now() - dates(next.now);
590
+ if (changed) {
591
+ const previous = snapshot;
592
+ const effects = Boolean(cursor && previous && previous.window === next.window &&
593
+ (!overview || previous._selected?.station_id === next._selected?.station_id));
594
+ snapshot = next;
595
+ render(previous, effects);
596
+ } else if (recovered) updateStatus();
597
+ cursor = body.cursor ?? next.cursor;
598
+ queue();
599
+ } catch (error) {
600
+ if (version !== generation || error.name === 'AbortError') return;
601
+ offline = true; updateStatus();
602
+ if (!snapshot) {
603
+ empty.hidden = false;
604
+ setText(empty, 'Activity is temporarily unavailable.');
605
+ }
606
+ queue([5000, 15000, 60000][Math.min(2, failures++)]);
607
+ }
608
+ }
609
+ for (const button of buttons) button.addEventListener('click', () => {
610
+ if (windowName === button.dataset.activityWindow) return;
611
+ windowName = button.dataset.activityWindow;
612
+ for (const choice of buttons) choice.setAttribute('aria-pressed', String(choice === button));
613
+ generation++; controller?.abort(); cursor = undefined; lastStart = -Infinity;
614
+ queue();
615
+ });
616
+ document.addEventListener('visibilitychange', () => {
617
+ if (document.hidden) {
618
+ generation++; clearTimeout(timer); controller?.abort();
619
+ cancelAnimationFrame(frame); frame = 0;
620
+ clearPulses(); hideTooltip();
621
+ for (const row of watchTopics.values()) row.scroll?.pause();
622
+ } else {
623
+ for (const row of watchTopics.values()) if (!row.focus && !row.over) row.scroll?.play();
624
+ decay(); scheduleFrame(true); queue();
625
+ }
626
+ });
627
+ motion.addEventListener('change', () => {
628
+ if (motion.matches) {
629
+ for (const {animation, finish} of [...departures.values()]) { animation.cancel(); finish(); }
630
+ for (const animation of animated) animation.cancel();
631
+ animated.clear(); moves.clear(); motionUntil = 0;
632
+ for (const view of cards.values()) view.listMotion = undefined;
633
+ clearPulses();
634
+ ghost?.remove();
635
+ }
636
+ for (const row of watchTopics.values()) measureTopic(row);
637
+ scheduleFrame(true);
638
+ });
639
+ root.addEventListener('scroll', () => { if (tooltipOwner) hideTooltip(); }, true);
640
+ root.addEventListener('keydown', event => { if (event.key === 'Escape') hideTooltip(); });
641
+ setInterval(decay, 250);
642
+ queue();
643
+ }
644
+ `;
@@ -0,0 +1,24 @@
1
+ import { esc } from "./util.js";
2
+ export function activityPanel(stationId = '', overview = false) {
3
+ return `<section class="activity-panel" id="${overview ? 'overview-activity' : 'station-activity'}" data-station-activity="${esc(stationId)}"${overview ? ' data-overview-activity="true"' : ''}>
4
+ <header class="activity-header">
5
+ <div class="activity-heading"><div class="activity-kicker"><span></span> Station activity</div>
6
+ <h2>${overview ? '<a data-activity-title href="/stations">Activity</a>' : 'Activity map'}</h2>
7
+ </div>
8
+ <div class="activity-tools">${overview ? '<a class="activity-all" href="/stations">All stations →</a>' : ''}
9
+ <div class="activity-window" role="group" aria-label="Activity window">${['1m', '10m', '1h', '1d'].map(window => `<button type="button" class="secondary" data-activity-window="${window}" aria-pressed="${window === '10m'}">${window}</button>`).join('')}</div>
10
+ </div>
11
+ </header>
12
+ <div class="activity-meta">
13
+ <div class="activity-legend" aria-label="Connection types"><span data-link="dispatch">Dispatch</span><span data-link="report">Report</span><span data-link="cue">Cue</span></div>
14
+ <div class="activity-batch" data-activity-status role="status">Loading activity…</div>
15
+ </div>
16
+ <p class="activity-empty" data-activity-empty hidden></p>
17
+ <div class="activity-scene">
18
+ <div class="activity-stage" data-activity-stage hidden>
19
+ <svg class="activity-edges" data-activity-edges aria-hidden="true"><g data-activity-trails></g><g data-activity-pulses></g></svg>
20
+ <div class="activity-nodes" data-activity-nodes><div class="activity-hub"></div><div class="activity-agent-lanes"><div class="activity-lane"></div><div class="activity-lane"></div></div></div>
21
+ </div>
22
+ </div>
23
+ </section>`;
24
+ }