@cotal-ai/web 0.138.2 → 0.139.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 (48) hide show
  1. package/dist/web/assets/AgentPage-CpDkKMSj.js +1 -0
  2. package/dist/web/assets/FailedTip-DfF85PmB.js +1 -0
  3. package/dist/web/assets/bash-CLZ0U2zV.js +1 -0
  4. package/dist/web/assets/characters-BsW4RWhl.js +9 -0
  5. package/dist/web/assets/controller-D_lQfVDy.js +70 -0
  6. package/dist/web/assets/core-Bfff_dYO.js +12 -0
  7. package/dist/web/assets/diff-woXpYk--.js +1 -0
  8. package/dist/web/assets/dist-BB9Crw5c.js +1 -0
  9. package/dist/web/assets/dist-DktEa9vr.js +1 -0
  10. package/dist/web/assets/engine-javascript-C30F4iNc.js +141 -0
  11. package/dist/web/assets/index-DQdr6c2w.css +1 -0
  12. package/dist/web/assets/index-Dfeh4Ewy.js +13 -0
  13. package/dist/web/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  14. package/dist/web/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  15. package/dist/web/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  16. package/dist/web/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  17. package/dist/web/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  18. package/dist/web/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  19. package/dist/web/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  20. package/dist/web/assets/javascript-BgS3c2Ky.js +1 -0
  21. package/dist/web/assets/json-qhed-kSA.js +1 -0
  22. package/dist/web/assets/markdown-BYOwaDjH.js +1 -0
  23. package/dist/web/assets/python-gzcpVVnB.js +1 -0
  24. package/dist/web/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  25. package/dist/web/assets/typescript-bsJCZSQ-.js +1 -0
  26. package/dist/web/assets/yaml-rwi0_p6S.js +1 -0
  27. package/dist/web/bundle-licenses.json +389 -0
  28. package/dist/web/index.html +9 -513
  29. package/dist/web/theme-boot.js +8 -0
  30. package/dist/web.d.ts +312 -21
  31. package/dist/web.d.ts.map +1 -1
  32. package/dist/web.js +647 -121
  33. package/dist/web.js.map +1 -1
  34. package/package.json +30 -6
  35. package/dist/web/agui-frame.js +0 -210
  36. package/dist/web/app.js +0 -1428
  37. package/dist/web/event-order.js +0 -283
  38. package/dist/web/graph.html +0 -225
  39. package/dist/web/graph.js +0 -868
  40. package/dist/web/harness.js +0 -46
  41. package/dist/web/md.js +0 -31
  42. package/dist/web/parts.js +0 -114
  43. package/dist/web/presence-ages.js +0 -33
  44. package/dist/web/presence.js +0 -17
  45. package/dist/web/snapshot.js +0 -99
  46. package/dist/web/vendor/marked.umd.js +0 -79
  47. package/dist/web/vendor/purify.min.js +0 -3
  48. package/dist/web/vendor/vendor-manifest.json +0 -18
package/dist/web/graph.js DELETED
@@ -1,868 +0,0 @@
1
- /* Cotal — live mesh graph. Channels and agents are nodes in a force-directed constellation:
2
- * channel "spokes" pull an agent toward the channels it's subscribed to (so an agent on two channels
3
- * floats between both hubs), DM springs pull peers together, and charge spreads everything out. A wire
4
- * glows + fires a comet when a message flows. Fed by the same /feed SSE + REST the Monitor uses.
5
- *
6
- * Membership is AUTHORITATIVE and broker-sourced (not self-reported): the delivery daemon reads the
7
- * broker's connection view (CONNZ) ∪ the durable members registry and publishes a derived feed; the
8
- * observer serves it at /api/membership + a `membership` SSE event. So a spoke is drawn for every channel
9
- * an agent is actually subscribed to — including SILENT readers and `live` channels that keep no
10
- * enumerable roster. A `live` (connected) member draws solid-faint; a member that's only durable while its
11
- * presence is offline draws dashed-dim ("member, currently offline"). Traffic glow rides on top: a post
12
- * sends a comet to the hub, the hub blooms, then fans out to every other member. If the feed is absent
13
- * (no daemon / a space provisioned before this feature), the graph degrades to traffic-only and says so.
14
- *
15
- * Stability: messages drive *glow*, not layout. The simulation cools to a rest state (alpha decay) and
16
- * only gently re-heats when the node/edge SET changes — so nodes don't wander on every message. */
17
- import { presenceFacts } from "./presence.js";
18
-
19
- (() => {
20
- const $ = (id) => document.getElementById(id);
21
- const canvas = $("graph");
22
- const ctx = canvas.getContext("2d");
23
-
24
- // ── palette ──
25
- const MODE = { chat: "#58a6ff", unicast: "#d29922", anycast: "#3fb950" };
26
- const STAT = { working: "#46d35e", waiting: "#e9bf52", idle: "#9aa6b5", offline: "#5a6472" };
27
- const MEM_LIVE = "#8493a8"; // a live (connected) membership spoke
28
- const MEM_OFF = "#5a6472"; // a durable member whose presence is offline ("member, currently offline")
29
- const TRAFFIC_COLD = 0.02; // heat below which a NON-member (traffic-only) spoke is pruned
30
- const FEED_STALE_MS = 45000; // membership feed older than this reads "stale" (daemon polls ~15s)
31
- // Harness branding from harness.js (one source with the monitor). Canvas uses .glyph; DOM uses .svg.
32
- const HARNESS = window.COTAL_HARNESS || {};
33
- const harnessLabel = (k) => (HARNESS[k] ? HARNESS[k].label : k);
34
- const harnessColor = (k) => (HARNESS[k] ? HARNESS[k].color : "#8b949e");
35
- const harnessGlyph = (k) => (HARNESS[k] ? HARNESS[k].glyph : "·");
36
- // Attention: open/absent are identical (receives all) — only dnd/focus surface.
37
- const attMark = (a) => (a === "dnd" ? "◼" : a === "focus" ? "◉" : "");
38
- /** Fit `provider/model · variant` into maxChars. Prefer dropping the provider prefix over the
39
- * variant — "gpt-5.6-sol · xhigh" carries more per pixel than "openai/gpt-5.6-sol ·…". */
40
- function fitModelLabel(model, variant, maxChars) {
41
- let core = String(model);
42
- const withVar = (m) => (variant ? `${m} · ${variant}` : m);
43
- let s = withVar(core);
44
- if (s.length <= maxChars) return s;
45
- if (core.includes("/")) {
46
- core = core.slice(core.lastIndexOf("/") + 1);
47
- s = withVar(core);
48
- if (s.length <= maxChars) return s;
49
- }
50
- if (variant) {
51
- const suf = ` · ${variant}`;
52
- const room = maxChars - suf.length;
53
- if (room >= 4) return `${core.slice(0, room - 1)}…${suf}`;
54
- return String(variant).length <= maxChars ? String(variant) : `${String(variant).slice(0, maxChars - 1)}…`;
55
- }
56
- return core.length <= maxChars ? core : `${core.slice(0, maxChars - 1)}…`;
57
- }
58
-
59
- // ── state ──
60
- const hubs = new Map(); // channel -> hub node
61
- const agents = new Map(); // id -> agent node
62
- const edges = new Map(); // `${agentId}|${chan}` -> { a, chan, last, heat, mem, durableOnly }
63
- const dms = new Map(); // `${idA}|${idB}` (sorted) -> { a, b, last, heat }
64
- const particles = [];
65
- const blooms = [];
66
- const recent = [];
67
- // `available` is "there is a feed and it said something"; `unreadable` is "the last attempt to read
68
- // it failed". They are independent, and `unreadable` is declared here rather than sprung into
69
- // existence on first failure so the shape of the state is readable in one place.
70
- const feed = { asOf: undefined, available: false, unreadable: false }; // membership-feed freshness
71
- const cam = { x: 0, y: 0, scale: 1, ready: false, user: false };
72
- const filter = { chat: true, unicast: true, anycast: true, window: 30, paused: false, hideOffline: true, hideEmpty: true };
73
- let W = 0, H = 0, DPR = 1, hover = null, sel = null, lastT = 0, alpha = 1;
74
-
75
- // ── utils ──
76
- // Shared with app.js via parts.js (loaded before this file). It names a part kind it cannot
77
- // draw instead of rendering it as the empty string, which read as "nothing arrived".
78
- const partsText = (m) => window.COTAL_PARTS.partsToText(m.parts);
79
- const ease = (t) => (t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2);
80
- const esc = window.COTAL_PARTS.esc;
81
- const shortId = (x) => (/^[A-Z2-7]{32,}$/.test(x) ? x.slice(0, 6) + "…" : x);
82
- const hash = (s) => { let h = 0; for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0; return h; };
83
- const hex = (h) => [parseInt(h.slice(1, 3), 16), parseInt(h.slice(3, 5), 16), parseInt(h.slice(5, 7), 16)];
84
- const rgba = (h, a) => { const [r, g, b] = hex(h); return `rgba(${r},${g},${b},${a})`; };
85
- const now = () => Date.now();
86
- const reheat = () => { alpha = Math.max(alpha, 0.55); };
87
-
88
- // ── channel-subscription matching (ports core subjectMatches; `live` patterns keep wildcards) ──
89
- const isWild = (ch) => ch.split(".").some((s) => s === "*" || s === ">");
90
- function patternMatches(pattern, subject) {
91
- const p = pattern.split("."), s = subject.split(".");
92
- for (let i = 0; i < p.length; i++) { if (p[i] === ">") return i < s.length; if (i >= s.length) return false; if (p[i] === "*") continue; if (p[i] !== s[i]) return false; }
93
- return p.length === s.length;
94
- }
95
- /** Expand an agent's {live patterns, durable channels} → { channels: channel→kind, wide }. Bounded
96
- * wildcards (`team.>`) expand against the KNOWN channel set (registry hubs); concrete patterns stand
97
- * alone; `live` wins over `durable`. A durable family row (`team.>`) expands only over the known hubs
98
- * whose class is durable, the channels it stores copies for. A WHOLE-BREADTH pattern (`>` or `*` — e.g. the default persona's
99
- * read-everything grant) is NOT expanded to a spoke per hub (that's a dandelion); it sets `wide`, and
100
- * the agent renders as a "reads-all" node badge instead — truthful without per-channel noise. */
101
- function memberChannels(live, durable, known) {
102
- const out = new Map();
103
- let wide = false;
104
- for (const pat of live || []) {
105
- if (pat === ">" || pat === "*") { wide = true; continue; }
106
- if (isWild(pat)) { for (const ch of known) if (patternMatches(pat, ch)) out.set(ch, "live"); }
107
- else out.set(pat, "live");
108
- }
109
- for (const ch of durable || []) {
110
- if (!isWild(ch)) { if (!out.has(ch)) out.set(ch, "durable"); }
111
- else for (const k of known) if (!out.has(k) && hubs.get(k)?.deliveryClass === "durable" && patternMatches(ch, k)) out.set(k, "durable");
112
- }
113
- return { channels: out, wide };
114
- }
115
-
116
- // ── nodes ──
117
- function spawn(id, seedR) { const a = (hash(id) % 628) / 100, r = seedR + (Math.abs(hash(id)) % 120); return { x: Math.cos(a) * r, y: Math.sin(a) * r, vx: 0, vy: 0 }; }
118
- function ensureHub(name) {
119
- if (!name) return null;
120
- let h = hubs.get(name);
121
- if (!h) { h = Object.assign({ kind: "hub", name, r: 14, charge: -560, mass: 3, msgs: 0, desc: "" }, spawn("#" + name, 150)); hubs.set(name, h); reheat(); onNewChannel(name); }
122
- return h;
123
- }
124
- function ensureAgent(ref) {
125
- if (!ref) return null;
126
- const id = typeof ref === "object" ? ref.id || ref.name : ref;
127
- if (!id) return null;
128
- let a = agents.get(id);
129
- if (!a) { a = Object.assign({ kind: "agent", id, name: (typeof ref === "object" && ref.name) || shortId(id), role: typeof ref === "object" ? ref.role : undefined, status: "idle", present: false, activity: "", harness: undefined, model: undefined, variant: undefined, attention: undefined, ts: 0, live: [], durable: [], memberOf: new Map(), r: 6.5, charge: -190, mass: 1, phase: (hash(id) % 1000) / 1000 * 6.283 }, spawn(id, 70)); agents.set(id, a); reheat(); }
130
- else if (typeof ref === "object" && ref.name) a.name = ref.name;
131
- return a;
132
- }
133
- const edgeKey = (id, chan) => id + "|" + chan;
134
- const dmKey = (a, b) => [a, b].sort().join("|");
135
- function ensureEdge(a, chan) { const k = edgeKey(a.id, chan); let e = edges.get(k); if (!e) { edges.set(k, (e = { a, chan, last: 0, heat: 0, mem: false, durableOnly: false })); reheat(); } return e; }
136
- function chatHit(a, chan, ts) { const e = ensureEdge(a, chan); e.last = Math.max(e.last, ts); return e; }
137
- function dmHit(a, b, ts) { const k = dmKey(a.id, b.id); let d = dms.get(k); if (!d) { dms.set(k, (d = { a, b, last: 0, heat: 0 })); reheat(); } d.last = Math.max(d.last, ts); return d; }
138
- function primaryChan(a) { let best = null, bt = 0; for (const e of edges.values()) if (e.a === a && e.last > bt) { bt = e.last; best = e.chan; } return best; }
139
-
140
- // When a channel first appears, retro-link any agent whose live WILDCARD covers it (so a `team.>`
141
- // subscriber gains a spoke to a newly-created `team.backend` with no membership-feed round-trip).
142
- function onNewChannel(name) {
143
- for (const a of agents.values()) for (const pat of a.live || []) { if (pat === ">" || pat === "*") continue; if (isWild(pat) && patternMatches(pat, name)) { const e = ensureEdge(a, name); e.mem = true; e.durableOnly = false; a.memberOf.set(name, "live"); } }
144
- }
145
-
146
- // ── force simulation (cooling; re-heated only on structural change) ──
147
- function link(a, b, len, k) { let dx = b.x - a.x, dy = b.y - a.y, d = Math.hypot(dx, dy) || 1; const f = (d - len) * k * alpha, fx = (dx / d) * f, fy = (dy / d) * f; a.vx += fx; a.vy += fy; b.vx -= fx; b.vy -= fy; }
148
- function physics() {
149
- if (alpha < 0.004 || filter.paused) return;
150
- // while hiding, ghosts leave the sim entirely so the visible graph isn't laid out around invisible nodes (reheat on toggle re-settles)
151
- const ns = [...hubs.values(), ...agents.values()].filter((n) => !isHidden(n));
152
- for (let i = 0; i < ns.length; i++) {
153
- const a = ns[i];
154
- for (let j = i + 1; j < ns.length; j++) {
155
- const b = ns[j];
156
- let dx = a.x - b.x, dy = a.y - b.y, d2 = dx * dx + dy * dy;
157
- if (d2 < 1) { dx = (hash(a.name + i) % 11) - 5; dy = (hash(b.name + j) % 11) - 5; d2 = dx * dx + dy * dy || 1; }
158
- const d = Math.sqrt(d2), q = ((a.charge * b.charge) / d2) * alpha;
159
- a.vx += (dx / d) * q; a.vy += (dy / d) * q; b.vx -= (dx / d) * q; b.vy -= (dy / d) * q;
160
- }
161
- }
162
- for (const e of edges.values()) { const h = hubs.get(e.chan); if (h && !isHidden(h) && !isHiddenMember(e)) link(e.a, h, 105, 0.08); }
163
- for (const d of dms.values()) if (!isHidden(d.a) && !isHidden(d.b)) link(d.a, d.b, 165, 0.03);
164
- // small graphs: faint tangential nudge so agents form a loose ring around their hub instead of a line (decays with alpha)
165
- if (hubs.size <= 2) for (const a of agents.values()) { if (isHidden(a)) continue; const h = (primaryChan(a) && hubs.get(primaryChan(a))) || [...hubs.values()][0]; if (h) { const dx = a.x - h.x, dy = a.y - h.y, d = Math.hypot(dx, dy) || 1; a.vx += (-dy / d) * 0.4 * alpha; a.vy += (dx / d) * 0.4 * alpha; } }
166
- // collision: position-based min-distance — prevents the 1/d² charge singularity + node overlap
167
- const pad = 10;
168
- for (let i = 0; i < ns.length; i++) {
169
- const a = ns[i];
170
- for (let j = i + 1; j < ns.length; j++) {
171
- const b = ns[j];
172
- let dx = b.x - a.x, dy = b.y - a.y, d = Math.hypot(dx, dy) || 0.01;
173
- const min = a.r + b.r + pad;
174
- if (d < min) { const push = (min - d) / 2, ux = dx / d, uy = dy / d; a.x -= ux * push; a.y -= uy * push; b.x += ux * push; b.y += uy * push; const va = a.vx * ux + a.vy * uy, vb = b.vx * ux + b.vy * uy; a.vx -= va * ux; a.vy -= va * uy; b.vx -= vb * ux; b.vy -= vb * uy; }
175
- }
176
- }
177
- for (const n of ns) {
178
- n.vx += -n.x * 0.014 * alpha; n.vy += -n.y * 0.014 * alpha; // gravity toward center
179
- n.vx *= 0.6; n.vy *= 0.6; n.x += n.vx / (n.mass || 1); n.y += n.vy / (n.mass || 1); // heavier hubs resist the kick
180
- }
181
- alpha += (0 - alpha) * 0.0228;
182
- }
183
-
184
- // ── traffic (visuals are decoration; graph STATE is not) ──
185
- // Particle/bloom arrays are bounded. A backgrounded tab stops rAF, so an unbounded queue + the
186
- // chat onArrive fan-out (one comet per other member) detonates into thousands of particles on
187
- // return — measured peak 8042 from 120 backlogged chats. Gate enqueue on visibility; hard-cap
188
- // both arrays (drop oldest; dropped onArrive is skipped — heat already applied on the state path).
189
- const PARTICLE_CAP = 240;
190
- const BLOOM_CAP = 80;
191
- const tabVisible = () => document.visibilityState === "visible";
192
- const mk = (a, b, color, onArrive, curve) => ({ a, b, t: 0, dur: curve ? 1.4 : 1.1, color, onArrive: onArrive || null, curve: !!curve, trail: [] });
193
- function pushParticle(p) {
194
- if (!tabVisible()) return false;
195
- particles.push(p);
196
- while (particles.length > PARTICLE_CAP) particles.shift(); // drop oldest; skip its onArrive
197
- return true;
198
- }
199
- function pushBloom(b) {
200
- if (!tabVisible()) return false;
201
- blooms.push(b);
202
- while (blooms.length > BLOOM_CAP) blooms.shift();
203
- return true;
204
- }
205
- /** Apply fan-out spoke heat without enqueueing comets (used when visuals are gated off). */
206
- function heatFanOut(channel, from) {
207
- for (const e of edges.values()) if (e.chan === channel && e.a !== from) e.heat = 1;
208
- }
209
- function onMessage({ mode, senderId, channel, msg }) {
210
- if (!msg) return;
211
- // Trust decided once (see app.js): the subject-derived channel replaces the payload claim,
212
- // UNCONDITIONALLY. A guarded overwrite fails open on `inst`/`svc`, where there is no
213
- // authoritative channel and the publisher's forged one would survive.
214
- msg.channel = channel;
215
- const from = ensureAgent(senderId ? { id: senderId, name: msg.from?.name, role: msg.from?.role } : msg.from);
216
- if (from) { from.ts = now(); from.present = true; } // a live sender is a live presence (roster event may lag)
217
- // Visual gate: pause chip, mode filter, AND tab visibility. State (heat/recent/roster) always applies.
218
- const animate = !filter.paused && filter[mode] && tabVisible();
219
- let toName = null;
220
- if (mode === "chat" && msg.channel) {
221
- const h = ensureHub(msg.channel);
222
- if (h) {
223
- if (!h.deliveryClass && !h.heard) rereadChannels();
224
- h.heard = true;
225
- }
226
- if (from) chatHit(from, msg.channel, now()).heat = 1;
227
- // inbound: sender → hub, then the hub flashes and fans the post back out to every other member on
228
- // the channel (their spokes glow as the wave reaches them) — a real broadcast.
229
- if (animate && from && h) {
230
- pushParticle(mk(from, h, MODE.chat, () => {
231
- pushBloom({ x: h.x, y: h.y, t: 0, dur: 0.95, color: MODE.chat, r0: h.r });
232
- for (const e of edges.values()) if (e.chan === msg.channel && e.a !== from) {
233
- e.heat = 1;
234
- pushParticle(mk(h, e.a, MODE.chat, null, false));
235
- }
236
- }));
237
- } else if (from && h) {
238
- // No comet: still heat every member spoke so the skeleton reflects the broadcast on return.
239
- heatFanOut(msg.channel, from);
240
- }
241
- } else if (mode === "unicast") {
242
- const to = typeof msg.to === "string" ? agents.get(msg.to) : msg.to && agents.get(msg.to.id);
243
- toName = to?.name || (typeof msg.to === "string" ? shortId(msg.to) : msg.to?.name);
244
- if (from && to && from !== to) {
245
- dmHit(from, to, now()).heat = 1;
246
- if (animate) pushParticle(mk(from, to, MODE.unicast, null, true));
247
- }
248
- } else if (mode === "anycast") {
249
- toName = "@" + (msg.toService || "");
250
- if (animate && from) pushBloom({ x: from.x, y: from.y, t: 0, dur: 1.0, color: MODE.anycast, r0: from.r });
251
- }
252
- recent.push({ mode, from: from?.name, fromId: from?.id, to: toName, chan: msg.channel, text: partsText(msg), ts: msg.ts || now() });
253
- if (recent.length > 80) recent.shift();
254
- if (sel) renderDetail();
255
- }
256
- function updateRoster(list) {
257
- const seen = new Set();
258
- for (const p of list) {
259
- if (p.card?.kind === "endpoint") continue;
260
- const a = ensureAgent({ id: p.card.id, name: p.card.name, role: p.card.role });
261
- a.status = p.status; a.progress = p.progress; a.activity = p.activity || ""; a.role = p.card.role;
262
- a.harness = p.card.meta?.connector; a.model = p.card.meta?.model; a.variant = p.card.meta?.variant;
263
- a.attention = p.attention; // open/absent both mean receives-all; only dnd/focus render
264
- // Card legibility fields the detail panel renders (same source as the Monitor's Agent Detail).
265
- a.description = p.card.description; a.tags = p.card.tags; a.channelModes = p.channelModes;
266
- a.condition = p.condition; a.statusSince = p.statusSince;
267
- a.activitySince = p.activitySince; a.activeAt = p.activeAt;
268
- a.ts = p.ts;
269
- a.present = true; // in the roster = a live presence (the authority for isOffline)
270
- seen.add(a.id);
271
- }
272
- // Drop an agent as soon as it goes offline OR leaves the roster (main's ghost fix, c9e9000) — EXCEPT
273
- // keep it if it's still a feed member: a durable member whose presence is offline must persist to
274
- // render as "member, currently offline" (the feed's durable arm survives offline). Membership is
275
- // broker-truth, applied separately; presence no longer carries channels.
276
- for (const [id, a] of agents) { if (!seen.has(id)) a.present = false; if ((!seen.has(id) || a.status === "offline") && !(a.wideReader || (a.memberOf && a.memberOf.size))) { agents.delete(id); for (const k of [...edges.keys()]) if (edges.get(k).a === a) edges.delete(k); for (const k of [...dms.keys()]) { const d = dms.get(k); if (d.a === a || d.b === a) dms.delete(k); } reheat(); if (sel === a) closeDetail(); } }
277
- }
278
-
279
- // ── membership (authoritative spokes) ──
280
- // The server said it could not read membership. Kept separate from `available` rather than folded
281
- // into it: they are different facts and the pill has to say which one.
282
- function membershipUnreadable() { feed.unreadable = true; setFeed(); }
283
-
284
- // ── THE BOOTSTRAP MUST NOT OUTRANK THE LIVE FEED ────────────────────────────────────────────
285
- //
286
- // Every bootstrap read is ISSUED before its value is applied: `refreshAll` starts all six, awaits
287
- // all six, and only then applies each. So a snapshot is always at least as old as the moment the
288
- // page asked for it, while an SSE event is by definition newer than that moment. Now that the feed
289
- // opens FIRST, a live `roster` or `membership` can land while those reads are still in flight, and
290
- // applying the older snapshot afterwards silently reverts it: `updateRoster` on an empty list marks
291
- // every unseen agent `present = false` and deletes it outright unless it is still a feed member,
292
- // and `applyMembership` on an empty set clears `memberOf`. The agent the feed just announced
293
- // vanishes from the graph.
294
- //
295
- // Both channels carry a FULL snapshot through the SAME apply function, so a live event does not
296
- // need merging with the older read, it REPLACES it. Once the feed has spoken for a source, that
297
- // source's bootstrap value is stale on arrival and is dropped rather than applied.
298
- //
299
- // WHAT IS SUPERSEDED IS THE SOURCE, NOT THE SNAPSHOT. `membership` speaks in two sentences, a
300
- // snapshot and a REFUSAL, and each side can say either one. Writing the rule only onto the apply
301
- // wrappers covered the snapshots and left both refusals loose, in opposite directions: a live
302
- // refusal erased by an older successful read, and a successful live snapshot overruled by a
303
- // bootstrap read that refused after it. Both end in the header pill making a claim about the mesh
304
- // that is really a claim about one read, which is the one thing this pill exists not to do.
305
- const liveApplied = new Set();
306
- const supersededByFeed = (name, apply) => (value) => { if (!liveApplied.has(name)) apply(value); };
307
-
308
- function applyMembership(snap) {
309
- if (!snap) return;
310
- feed.unreadable = false; // a snapshot arrived, whatever it contains
311
- feed.asOf = snap.asOf;
312
- feed.available = snap.asOf !== undefined || (Array.isArray(snap.members) && snap.members.length > 0);
313
- setFeed();
314
- lastMembers = snap.members || [];
315
- drawMembers(lastMembers);
316
- }
317
- // A durable family row reaches only the hubs whose class is durable (`memberChannels`), and a class can
318
- // land after the snapshot naming the family: the feed's first snapshot comes before `/api/channels`
319
- // answers, and a channel first seen in a member's row or a message has no class until that read runs
320
- // again. So the last snapshot's members are kept and drawn again whenever classes land.
321
- let lastMembers = null;
322
- function drawMembers(members) {
323
- const known = [...hubs.keys()];
324
- const present = new Set();
325
- for (const m of members) {
326
- const a = ensureAgent({ id: m.id });
327
- present.add(a.id);
328
- a.live = m.live || []; a.durable = m.durable || [];
329
- const mc = memberChannels(a.live, a.durable, known);
330
- a.memberOf = mc.channels; a.wideReader = mc.wide;
331
- for (const [ch, kind] of mc.channels) { if (!hubs.has(ch)) rereadChannels(); ensureHub(ch); const e = ensureEdge(a, ch); e.mem = true; e.durableOnly = kind === "durable"; }
332
- pruneMemberEdges(a, mc.channels);
333
- }
334
- // An agent that dropped out of the feed entirely is no longer a member of anything (incl. a wide reader,
335
- // which carries the flag but no concrete edges).
336
- for (const a of agents.values()) if (!present.has(a.id) && (a.wideReader || (a.memberOf && a.memberOf.size))) { a.live = []; a.durable = []; a.wideReader = false; const empty = new Map(); pruneMemberEdges(a, empty); a.memberOf = empty; }
337
- recomputeHubEmpty(); // these mutations change hub visibility — refresh before the detail/selection check below
338
- if (sel) { if (isHidden(sel)) closeDetail(); else renderDetail(); }
339
- }
340
- // Drop this agent's membership edges that are no longer in `keep`; a still-warm one stays as a fading
341
- // traffic-only edge (mem:false) and is pruned later when cold, so a comet in flight isn't orphaned.
342
- function pruneMemberEdges(a, keep) {
343
- for (const [k, e] of edges) if (e.a === a && e.mem && !keep.has(e.chan)) { if (e.heat <= TRAFFIC_COLD) edges.delete(k); else { e.mem = false; e.durableOnly = false; } reheat(); }
344
- }
345
-
346
- // ── render loop ──
347
- function frame(t) {
348
- const dt = Math.min(0.05, (t - lastT) / 1000 || 0); lastT = t;
349
- // Prune cold traffic-only spokes (a non-member's post that has faded). Membership spokes persist by
350
- // membership, never on a timer — they're the resting skeleton, faint at rest, glowing on traffic.
351
- for (const [k, e] of edges) if (!e.mem && e.heat <= TRAFFIC_COLD && now() - e.last > 1000) { edges.delete(k); reheat(); }
352
- recomputeHubEmpty(); // no VISIBLE members = dormant (hidden offline ghosts don't keep it lit); drives hub hide + dim
353
- if (sel && isHidden(sel)) closeDetail(); // a selection hidden by a membership/roster change (not just the toggle) closes its card
354
- physics();
355
- // re-frame only once the sim has cooled, so the camera doesn't chase the re-settle wobble
356
- if (!cam.user && alpha < 0.12) { const f = fitTarget(); const e = 1 - Math.pow(0.02, dt); cam.x += (f.x - cam.x) * e; cam.y += (f.y - cam.y) * e; cam.scale += (f.scale - cam.scale) * e; }
357
- if (!filter.paused) { const k = Math.exp(-dt / filter.window); for (const e of edges.values()) e.heat *= k; for (const d of dms.values()) d.heat *= k; }
358
-
359
- ctx.setTransform(DPR, 0, 0, DPR, 0, 0);
360
- ctx.clearRect(0, 0, W, H);
361
- drawStarfield(ctx, W, H, cam);
362
- ctx.translate(cam.x, cam.y); ctx.scale(cam.scale, cam.scale);
363
- drawSpokes(); drawDmEdges(); drawBlooms(dt); drawParticles(dt); drawNodes();
364
- requestAnimationFrame(frame);
365
- }
366
-
367
- // Hover/select a hub or agent → highlight its membership fan, dim the rest (dandelion mitigation).
368
- function fanFocus() { return hover && hover.kind === "hub" ? hover : sel && sel.kind === "hub" ? sel : hover && hover.kind === "agent" ? hover : sel && sel.kind === "agent" ? sel : null; }
369
- function inFan(e, f) { if (!f) return true; return f.kind === "hub" ? e.chan === f.name : e.a === f; }
370
- // Core offline-ness of an AGENT (toggle-INDEPENDENT): it is NOT a live presence — either presence reports it
371
- // explicitly `offline`, or it is absent from the presence roster entirely (`present === false`). Presence is
372
- // the authority here, NOT the membership feed. This is what fixes the "ghost flashes back for ~1s" report: a
373
- // ghost that left EARLIER (its roster-absence already observed, `present === false`) stays hidden when a later
374
- // snapshot empties its memberOf — there is no per-node `memberOf.size` heuristic to flip it back to VISIBLE on
375
- // a membership change. (Membership and roster are independent SSE events; this covers the reported case, where
376
- // a peer's channel join drops a long-departed ghost. A near-simultaneous disconnect whose membership-drop is
377
- // processed before its roster-absence can still show the node for one roster interval — presence stays the
378
- // authority and it self-resolves on the next roster event; review-ux/critic R2.) It also does NOT false-hide a
379
- // genuinely-connected agent that just sits in no channel (e.g.
380
- // `manager`/DM-only: roster-present, but absent from the channel feed, so its `live` is an empty DEFAULT, not
381
- // proof of disconnection — review-freelance R2). `present` is set from the roster in updateRoster; a live
382
- // message sender is marked present too.
383
- const isOffline = (n) => n.kind === "agent" && (n.status === "offline" || !n.present);
384
- // A membership edge that is offline FOR ITS channel: durable-only here, or the agent itself is offline.
385
- const isOfflineMember = (e) => e.durableOnly || isOffline(e.a);
386
- // Render/sim visibility. `hide offline` (on by default) collapses offline AGENTS. `hide empty` (on by
387
- // default) collapses a HUB with no VISIBLE member under the current filters — it reads the cached `h.empty`
388
- // (kept current by recomputeHubEmpty). So when `hide offline` is ON this
389
- // means "no ONLINE member"; when it's OFF a channel that still shows offline members keeps its hub — the two
390
- // toggles don't fight (review-critic R2). Gated on the feed being AUTHORITATIVE: without the
391
- // authoritative feed there are no membership edges, so every hub would read empty — we can't tell a
392
- // quiet channel from an unknown one, so we don't hide. Reading the cached flag keeps isHidden(hub)
393
- // O(1), not an all-edges scan per call.
394
- // Hiding suppresses node/spoke rendering, hit-testing, camera framing, and physics participation; the node
395
- // stays in the model, so toggling reveals it instantly.
396
- //
397
- // `feedAuthoritative()` rather than `feed.available` alone. Those came apart the moment the feed
398
- // could report that it could not be READ: the last snapshot is still the last thing we KNEW, but it
399
- // is no longer what IS, and `hide empty` asserts a hub has no member NOW. That is the gate's own
400
- // stated reason applied to the case where we hold stale edges rather than none — otherwise the pill
401
- // says "unreadable" while the page keeps acting on the reading it just disowned.
402
- //
403
- // The snapshot itself is deliberately NOT discarded: `asOf` and the spokes remain the honest record
404
- // of the last successful read, which is true and worth showing. What stops is treating it as current.
405
- const feedAuthoritative = () => feed.available && !feed.unreadable;
406
- const isHidden = (n) => n.kind === "hub"
407
- ? filter.hideEmpty && feedAuthoritative() && n.empty
408
- : filter.hideOffline && isOffline(n);
409
- // Per-CHANNEL visibility of a membership spoke: hidden when `hide offline` is on AND this edge is offline
410
- // for its channel (durable-only, or the agent is offline) — so "hide offline" holds per channel, not just
411
- // per node (an agent live elsewhere keeps its node, but its dashed offline spokes + roster seats drop).
412
- const isHiddenMember = (e) => filter.hideOffline && isOfflineMember(e);
413
- // Recompute every hub's `empty` (no VISIBLE member under the current filters) in ONE O(hubs+edges) pass.
414
- // isHidden(hub) reads this cached flag, so call this synchronously anywhere a hub's visibility is consulted
415
- // outside the render loop — toggle cleanup + after applyMembership — so detail/selection logic never reads a
416
- // stale flag (review-critic/freelance/ux R2). The frame loop calls it too, for roster/traffic-driven changes.
417
- function recomputeHubEmpty() {
418
- for (const h of hubs.values()) h.empty = true;
419
- for (const e of edges.values()) if (e.mem && !isHiddenMember(e)) { const h = hubs.get(e.chan); if (h) h.empty = false; }
420
- }
421
-
422
- function drawSpokes() {
423
- ctx.lineCap = "round";
424
- const f = fanFocus();
425
- // structure layer: a constant-faint spoke per membership (solid = live, dashed-dim = member-offline)
426
- for (const e of edges.values()) {
427
- if (!e.mem || isHiddenMember(e)) continue;
428
- const h = hubs.get(e.chan); if (!h || isHidden(h)) continue;
429
- const off = e.durableOnly || e.a.status === "offline";
430
- const lit = inFan(e, f);
431
- ctx.beginPath(); ctx.moveTo(e.a.x, e.a.y); ctx.lineTo(h.x, h.y);
432
- ctx.setLineDash(off ? [3, 4] : []);
433
- ctx.strokeStyle = rgba(off ? MEM_OFF : MEM_LIVE, (off ? 0.3 : 0.42) * (lit ? 1 : 0.28));
434
- ctx.lineWidth = 1.4; ctx.stroke();
435
- }
436
- ctx.setLineDash([]);
437
- // activity layer: traffic glow on top (members + transient non-member posts)
438
- ctx.globalCompositeOperation = "lighter";
439
- for (const e of edges.values()) { const h = hubs.get(e.chan); if (!filter.chat || !h || isHidden(h) || e.heat <= 0.02 || isHiddenMember(e)) continue; const lit = inFan(e, f); ctx.beginPath(); ctx.moveTo(e.a.x, e.a.y); ctx.lineTo(h.x, h.y); ctx.strokeStyle = rgba(MODE.chat, Math.min(0.55, e.heat * 0.55) * (lit ? 1 : 0.35)); ctx.lineWidth = 1 + e.heat * 1.6; ctx.stroke(); }
440
- ctx.globalCompositeOperation = "source-over"; ctx.globalAlpha = 1;
441
- }
442
- // Perpendicular control point for a DM arc, computed in a direction-INDEPENDENT canonical order (by id)
443
- // so the traveling comet rides the exact same dashed curve no matter which peer sent this message — a
444
- // reply in the opposite direction otherwise flips the bulge to the wrong side and the comet peels off.
445
- function dmControl(a, b) {
446
- const [p, q] = a.id < b.id ? [a, b] : [b, a];
447
- const mx = (p.x + q.x) / 2, my = (p.y + q.y) / 2, nx = -(q.y - p.y), ny = q.x - p.x, len = Math.hypot(nx, ny) || 1;
448
- return { x: mx + (nx / len) * 24, y: my + (ny / len) * 24 };
449
- }
450
- function drawDmEdges() {
451
- if (!filter.unicast) return; // the `direct` chip filters DM traffic — including the persistent DM curves
452
- ctx.setLineDash([3, 4]);
453
- for (const d of dms.values()) {
454
- if (isHidden(d.a) || isHidden(d.b)) continue;
455
- const c = dmControl(d.a, d.b);
456
- ctx.beginPath(); ctx.moveTo(d.a.x, d.a.y); ctx.quadraticCurveTo(c.x, c.y, d.b.x, d.b.y);
457
- ctx.strokeStyle = rgba(MODE.unicast, 0.5 + d.heat * 0.45); ctx.lineWidth = 1.7 + d.heat * 1.6; ctx.stroke();
458
- }
459
- ctx.setLineDash([]); ctx.globalAlpha = 1;
460
- }
461
- function drawNodes() {
462
- ctx.textAlign = "center"; ctx.textBaseline = "middle";
463
- const t = performance.now() / 1000;
464
- for (const h of hubs.values()) {
465
- if (isHidden(h)) continue;
466
- const focus = h === hover || h === sel, dim = h.empty ? 0.55 : 1; // dormant hubs read quieter, not gone
467
- ctx.save(); ctx.shadowColor = MODE.chat; ctx.shadowBlur = (focus ? 28 : 16) * dim;
468
- const g = ctx.createRadialGradient(h.x, h.y, 0, h.x, h.y, h.r); g.addColorStop(0, h.empty ? "#16314f" : "#2b5a8f"); g.addColorStop(1, "#0c1726");
469
- ctx.fillStyle = g; ctx.beginPath(); ctx.arc(h.x, h.y, h.r, 0, 2 * Math.PI); ctx.fill(); ctx.restore();
470
- ctx.lineWidth = 1.5; ctx.strokeStyle = rgba(MODE.chat, 0.95 * dim); ctx.stroke();
471
- ctx.fillStyle = rgba("#cfe2ff", dim); ctx.font = "600 12.5px var(--font), sans-serif"; ctx.fillText("#" + h.name, h.x, h.y + h.r + 13);
472
- }
473
- for (const a of agents.values()) {
474
- if (isHidden(a)) continue;
475
- const col = STAT[a.status] || STAT.idle, focus = a === hover || a === sel, off = a.status === "offline", idle = a.status === "idle";
476
- const r = a.r + Math.sin(t * 0.8 + a.phase) * 0.4;
477
- if (a.status === "waiting") { const pulse = 0.5 + 0.5 * Math.sin(t * 1.7); for (const o of [0, 0.5]) { ctx.beginPath(); ctx.arc(a.x, a.y, r + 5 + ((pulse + o) % 1) * 9, 0, 2 * Math.PI); ctx.strokeStyle = rgba(STAT.waiting, (1 - ((pulse + o) % 1)) * 0.45); ctx.lineWidth = 1.6; ctx.stroke(); } }
478
- // wide reader (subscribes `>`/`*`): a faint dashed halo — "reads all channels" without a spoke per hub
479
- if (a.wideReader) { ctx.save(); ctx.setLineDash([2, 3]); ctx.beginPath(); ctx.arc(a.x, a.y, r + 4.5, 0, 2 * Math.PI); ctx.strokeStyle = rgba(MEM_LIVE, off ? 0.3 : 0.6); ctx.lineWidth = 1.2; ctx.stroke(); ctx.restore(); }
480
- // Shape channel (never colour alone): offline = hollow ring; idle = filled disc; working/waiting = filled + glow.
481
- ctx.save(); ctx.shadowColor = col; ctx.shadowBlur = focus ? 20 : off ? 0 : idle ? 6 : 13;
482
- if (off) {
483
- ctx.beginPath(); ctx.arc(a.x, a.y, r, 0, 2 * Math.PI);
484
- ctx.fillStyle = "#141b26"; ctx.fill();
485
- ctx.lineWidth = 2; ctx.strokeStyle = rgba(col, 0.85); ctx.setLineDash([2.5, 2]); ctx.stroke(); ctx.setLineDash([]);
486
- } else {
487
- const g = ctx.createRadialGradient(a.x, a.y, 0, a.x, a.y, r); g.addColorStop(0, rgba(col, 1)); g.addColorStop(0.55, rgba(col, 0.55)); g.addColorStop(1, "#141b26");
488
- ctx.fillStyle = g; ctx.beginPath(); ctx.arc(a.x, a.y, r, 0, 2 * Math.PI); ctx.fill();
489
- ctx.lineWidth = 2; ctx.strokeStyle = rgba(col, 1); ctx.stroke();
490
- }
491
- ctx.restore();
492
- // Attention mark (dnd/focus only) — glyph at node rim, sized for rest-scale legibility.
493
- const am = attMark(a.attention);
494
- if (am && !off) {
495
- ctx.fillStyle = a.attention === "dnd" ? "#db6d28" : MODE.chat;
496
- ctx.font = "700 11px var(--font), sans-serif";
497
- ctx.fillText(am, a.x + r + 2, a.y - r - 1);
498
- }
499
- // Labels track SCREEN SPACE, not global node count. A count gate hid every name on a real
500
- // 19-agent mesh (David's "don't hide model names") and zoom never helped. Rule:
501
- // • viewport cull — off-screen nodes cost nothing
502
- // • name when the node's on-screen footprint can hold text (or focus/waiting)
503
- // • model/harness when zoomed further (or focus) — density follows cam.scale
504
- const sx = cam.x + a.x * cam.scale, sy = cam.y + a.y * cam.scale;
505
- const inView = sx >= -40 && sx <= W + 40 && sy >= -40 && sy <= H + 40;
506
- const foot = 2 * r * cam.scale; // on-screen diameter in CSS px
507
- const showName = focus || a.status === "waiting" || (inView && foot >= 8);
508
- const showModel = focus || (inView && foot >= 16);
509
- if (showName) {
510
- ctx.fillStyle = focus ? "#ffffff" : "#cdd6e2";
511
- ctx.font = (focus ? "600 " : "500 ") + "11px var(--font), sans-serif";
512
- ctx.fillText(a.name, a.x, a.y - r - 8);
513
- }
514
- if (showModel) {
515
- // Budget scales with on-screen footprint (same axis as the label gate). Never eat the
516
- // variant to save chars — if we must shorten, drop the provider prefix first
517
- // ("openai/gpt-5.6-sol · xhigh" → "gpt-5.6-sol · xhigh"), then trim the model id.
518
- const maxChars = focus ? 56 : Math.max(20, Math.min(56, Math.round(foot * 2.2)));
519
- let sub = "";
520
- if (a.model) sub = fitModelLabel(a.model, a.variant, maxChars);
521
- else if (a.harness) sub = harnessLabel(a.harness);
522
- if (sub) {
523
- ctx.fillStyle = focus ? "#b6c2d1" : "#8b949e";
524
- ctx.font = "500 9.5px var(--font), sans-serif";
525
- ctx.fillText(sub, a.x, a.y - r - (showName ? 19 : 8));
526
- }
527
- }
528
- }
529
- ctx.globalAlpha = 1;
530
- }
531
-
532
- // ── atmosphere + motion ──
533
- const prng = (seed) => { let s = seed >>> 0; return () => { s = (s + 0x6d2b79f5) | 0; let t = Math.imul(s ^ (s >>> 15), 1 | s); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; };
534
- let stars = null, starW = 0, starH = 0;
535
- function buildStars(W, H) { const r = prng(0x9e3779b1); const arr = new Array(300); for (let i = 0; i < 300; i++) arr[i] = { x: r() * W, y: r() * H, size: 0.3 + r() * 1.0, alpha: 0.04 + r() * 0.26, depth: 0.04 + r() * 0.12, tw: r() < 0.2, ph: r() * Math.PI * 2, sp: 0.4 + r() * 0.9 }; stars = arr; starW = W; starH = H; }
536
- const drawStarfield = (ctx, W, H, cam) => {
537
- if (!stars || starW !== W || starH !== H) buildStars(W, H);
538
- const t = performance.now() / 1000;
539
- const g = ctx.createRadialGradient(W / 2, H / 2, 0, W / 2, H / 2, Math.max(W, H) * 0.75); g.addColorStop(0, "#202c40"); g.addColorStop(0.55, "#172030"); g.addColorStop(1, "#10161f"); ctx.fillStyle = g; ctx.fillRect(0, 0, W, H);
540
- ctx.globalCompositeOperation = "lighter";
541
- const blob = (fx, fy, rad, color) => { const ng = ctx.createRadialGradient(W * fx, H * fy, 0, W * fx, H * fy, rad); ng.addColorStop(0, color); ng.addColorStop(1, "transparent"); ctx.globalAlpha = 0.04; ctx.fillStyle = ng; ctx.fillRect(0, 0, W, H); };
542
- blob(0.28, 0.32, Math.max(W, H) * 0.45, "#1a3a5c"); blob(0.72, 0.68, Math.max(W, H) * 0.4, "#2a1a4a");
543
- for (const s of stars) { let sx = s.x + cam.x * s.depth, sy = s.y + cam.y * s.depth; sx = ((sx % W) + W) % W; sy = ((sy % H) + H) % H; let a = s.alpha; if (s.tw) a *= 0.35 + 0.65 * (0.5 + 0.5 * Math.sin(t * s.sp + s.ph)); ctx.globalAlpha = a; ctx.fillStyle = "#cfe0ff"; ctx.beginPath(); ctx.arc(sx, sy, s.size, 0, 2 * Math.PI); ctx.fill(); }
544
- ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over";
545
- };
546
- function drawParticles(dt) {
547
- ctx.globalCompositeOperation = "lighter"; ctx.lineCap = "round";
548
- for (let i = particles.length - 1; i >= 0; i--) {
549
- const p = particles[i]; if (!filter.paused) p.t += dt / p.dur;
550
- // a fan-out comet to a hidden offline member would fly to empty space — still tick + retire it, just don't draw
551
- if (isHidden(p.a) || isHidden(p.b)) { if (p.t >= 1) { if (p.onArrive) p.onArrive(); particles.splice(i, 1); } continue; }
552
- const t = ease(Math.min(1, p.t)); let x, y;
553
- if (p.curve) { const c = dmControl(p.a, p.b), u = 1 - t; x = u * u * p.a.x + 2 * u * t * c.x + t * t * p.b.x; y = u * u * p.a.y + 2 * u * t * c.y + t * t * p.b.y; }
554
- else { x = p.a.x + (p.b.x - p.a.x) * t; y = p.a.y + (p.b.y - p.a.y) * t; }
555
- if (!filter.paused) { p.trail.push(x, y); if (p.trail.length > 12) p.trail.splice(0, p.trail.length - 12); }
556
- const n = p.trail.length >> 1;
557
- for (let k = 0; k < n; k++) { const f = k / Math.max(1, n - 1); ctx.globalAlpha = f * f * 0.6; ctx.fillStyle = p.color; ctx.beginPath(); ctx.arc(p.trail[k * 2], p.trail[k * 2 + 1], 1 + f * 2.2, 0, 2 * Math.PI); ctx.fill(); }
558
- ctx.save(); ctx.shadowColor = p.color; ctx.shadowBlur = 20; ctx.globalAlpha = 1; ctx.fillStyle = "#ffffff"; ctx.beginPath(); ctx.arc(x, y, 2, 0, 2 * Math.PI); ctx.fill(); ctx.fillStyle = p.color; ctx.beginPath(); ctx.arc(x, y, 4.4, 0, 2 * Math.PI); ctx.fill(); ctx.restore();
559
- if (p.t >= 1) { if (p.onArrive) p.onArrive(); particles.splice(i, 1); }
560
- }
561
- ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over";
562
- }
563
- function drawBlooms(dt) {
564
- ctx.globalCompositeOperation = "lighter";
565
- for (let i = blooms.length - 1; i >= 0; i--) {
566
- const b = blooms[i]; b.t += dt / b.dur; if (b.t >= 1) { blooms.splice(i, 1); continue; }
567
- const flash = Math.max(0, 1 - b.t / 0.35);
568
- if (flash > 0) { const fg = ctx.createRadialGradient(b.x, b.y, 0, b.x, b.y, b.r0 + 18); fg.addColorStop(0, b.color); fg.addColorStop(1, "transparent"); ctx.globalAlpha = flash * 0.5; ctx.fillStyle = fg; ctx.beginPath(); ctx.arc(b.x, b.y, b.r0 + 18, 0, 2 * Math.PI); ctx.fill(); }
569
- const ring = (off) => { const tt = b.t - off; if (tt <= 0 || tt >= 1) return; ctx.beginPath(); ctx.arc(b.x, b.y, b.r0 + ease(tt) * 28, 0, 2 * Math.PI); ctx.strokeStyle = b.color; ctx.globalAlpha = (1 - tt) * 0.7; ctx.lineWidth = 2; ctx.stroke(); };
570
- ring(0); ring(0.15);
571
- }
572
- ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over";
573
- }
574
-
575
- // ── camera + hit-testing ──
576
- function fitTarget() {
577
- const ns = [...hubs.values(), ...agents.values()]; if (!ns.length) return { x: W / 2, y: H / 2, scale: 1 };
578
- // content nodes drive the frame; empty hubs only nudge the padding so one stray node can't shrink the live graph
579
- const content = ns.filter((n) => !(n.kind === "hub" && n.empty) && !isHidden(n)), frame = content.length ? content : ns;
580
- let a = 1e9, b = 1e9, c = -1e9, d = -1e9;
581
- for (const n of frame) { const r = n.r + 40; a = Math.min(a, n.x - r); c = Math.max(c, n.x + r); b = Math.min(b, n.y - r); d = Math.max(d, n.y + r); }
582
- for (const h of hubs.values()) if (h.empty && !isHidden(h)) { a = Math.min(a, h.x - 20); c = Math.max(c, h.x + 20); b = Math.min(b, h.y - 20); d = Math.max(d, h.y + 20); }
583
- const bw = c - a || 1, bh = d - b || 1, pad = 90, maxScale = ns.length <= 6 ? 2.4 : 1.6;
584
- const scale = Math.max(0.35, Math.min(maxScale, Math.min((W - pad * 2) / bw, (H - pad * 2) / bh)));
585
- return { x: W / 2 - ((a + c) / 2) * scale, y: H / 2 - ((b + d) / 2) * scale, scale };
586
- }
587
- const toWorld = (sx, sy) => ({ x: (sx - cam.x) / cam.scale, y: (sy - cam.y) / cam.scale });
588
- function pick(sx, sy) { const w = toWorld(sx, sy); let best = null, bd = 1e9; for (const n of [...hubs.values(), ...agents.values()]) { if (isHidden(n)) continue; const d = Math.hypot(n.x - w.x, n.y - w.y); if (d < n.r + 8 && d < bd) { bd = d; best = n; } } return best; }
589
-
590
- // ── membership freshness pill ──
591
- function setFeed() {
592
- const el = $("feed"); if (!el) return;
593
- el.hidden = false;
594
- let cls, text;
595
- // UNREADABLE IS ITS OWN STATE, and it must be checked before `available`. "traffic-only" is a
596
- // CLAIM ABOUT THE MESH — that no membership feed is being published — and it was being shown for
597
- // a failed read, which is a claim about US. The operator's own viewer reported traffic-only
598
- // against a mesh that had a feed, and nothing on the page could have revealed the difference.
599
- if (feed.unreadable) { cls = "off"; text = "membership: unreadable"; }
600
- else if (!feed.available) { cls = "off"; text = "membership: traffic-only"; }
601
- else { const age = feed.asOf ? now() - feed.asOf : Infinity; if (age < FEED_STALE_MS) { cls = ""; text = "membership: live"; } else { cls = "stale"; text = "membership: stale"; } }
602
- el.className = "pill" + (cls ? " " + cls : "");
603
- el.querySelector(".t").textContent = text;
604
- }
605
-
606
- // ── detail panel ──
607
- function closeDetail() { sel = null; $("detail").classList.remove("open"); }
608
- function recentRows(test) {
609
- const ms = recent.filter(test).slice(-6).reverse();
610
- return ms.length ? ms.map((m) => `<div class="d-msg" style="border-color:${MODE[m.mode] || "#2a313c"}"><div class="mhead"><span class="m" style="color:${MODE[m.mode] || "#8b949e"}">${m.mode}</span><span class="who">${esc(m.from)}</span>${m.chan ? `<span class="tgt">#${esc(m.chan)}</span>` : m.to ? `<span class="tgt">→ ${esc(m.to)}</span>` : ""}</div><div class="body">${esc(m.text).slice(0, 160) || "—"}</div></div>`).join("") : `<div class="d-msg empty">no recent traffic</div>`;
611
- }
612
- function renderDetail() {
613
- const el = $("detail"); if (!sel) { el.classList.remove("open"); return; }
614
- if (sel.kind === "hub") {
615
- // members from the broker feed (subscribed), split into live vs member-currently-offline; plus a
616
- // "recently active" subset (who actually posted here) vs just-subscribed.
617
- const memEdges = [...edges.values()].filter((e) => e.chan === sel.name && e.mem);
618
- // hide per MEMBERSHIP edge: an agent live elsewhere but durable-only here is offline FOR THIS channel
619
- const mem = memEdges.filter((e) => !isHiddenMember(e)).map((e) => e.a).sort((x, y) => x.name.localeCompare(y.name));
620
- const hiddenOff = memEdges.length - mem.length;
621
- const activeIds = new Set(recent.filter((m) => m.chan === sel.name && m.fromId).map((m) => m.fromId));
622
- const memberRow = (a) => { const off = a.status === "offline" || (a.memberOf && a.memberOf.get(sel.name) === "durable"); const dotCol = STAT[a.status] || STAT.idle; return `<span class="mtag"><span class="dot" style="background:${off ? MEM_OFF : dotCol}"></span>${esc(a.name)}${activeIds.has(a.id) ? '<span class="act">active</span>' : ""}${off ? '<span class="off">offline</span>' : ""}</span>`; };
623
- const memberList = mem.length ? `<div class="d-tags">${mem.map(memberRow).join("")}</div>` : `<div class="d-block muted">${hiddenOff ? `${hiddenOff} member${hiddenOff === 1 ? "" : "s"} offline (hidden)` : "no subscribers yet"}</div>`;
624
- // Effective channel policy (from /api/channels, server-resolved). Delivery class = durability;
625
- // replay = whether a join backfills. Omit a row the feed didn't carry (never guess a default).
626
- const deliveryRow = sel.deliveryClass
627
- ? `<div class="d-row"><span class="k">delivery</span><span class="v">${esc(sel.deliveryClass)} · ${sel.deliveryClass === "durable" ? "at-least-once for members" : "at-most-once"}</span></div>`
628
- : "";
629
- const replayRow = sel.replay === true
630
- ? `<div class="d-row"><span class="k">replay</span><span class="v">${sel.replayWindow ? "on · " + esc(sel.replayWindow) : "on"}</span></div>`
631
- : sel.replay === false
632
- ? `<div class="d-row"><span class="k">replay</span><span class="v muted">off</span></div>`
633
- : "";
634
- el.innerHTML = `<span class="x" id="dx">✕</span>
635
- <div class="d-kind">channel</div>
636
- <div class="d-who">#${esc(sel.name)}</div>
637
- ${sel.desc ? `<div class="d-block">${esc(sel.desc)}</div>` : ""}
638
- <div class="d-rows">
639
- <div class="d-row"><span class="k">subscribers</span><span class="v">${hiddenOff ? `${mem.length} shown <span style="color:var(--faint)">+${hiddenOff} offline hidden</span>` : `${mem.length} agent${mem.length === 1 ? "" : "s"}`}</span></div>
640
- <div class="d-row"><span class="k">messages</span><span class="v">${sel.msgs || 0}</span></div>
641
- ${deliveryRow}
642
- ${replayRow}
643
- </div>
644
- <div class="d-section"><div class="d-label">members</div>${memberList}</div>
645
- <div class="d-section"><div class="d-label">recent</div><div class="d-msgs">${recentRows((m) => m.chan === sel.name)}</div></div>`;
646
- } else {
647
- // an agent's FULL subscription set from the feed: live patterns + durable. A whole-breadth `>`/`*`
648
- // grant shows as a single "all channels" chip, not literal `#>`; bounded subtrees show literally.
649
- const wideChip = sel.wideReader ? `<span class="ctag">all channels</span>` : "";
650
- const liveSet = (sel.live || []).filter((c) => c !== ">" && c !== "*").map((c) => `<span class="ctag">#${esc(c)}</span>`).join("");
651
- const durOnly = (sel.durable || []).filter((c) => !(sel.live || []).includes(c)).map((c) => `<span class="ctag off">#${esc(c)}</span>`).join("");
652
- const subs = wideChip || liveSet || durOnly ? `<div class="d-tags">${wideChip}${liveSet}${durOnly}</div>` : `<div class="d-block muted">no channel subscriptions</div>`;
653
- // Identity rows: branded harness (not raw key); model · variant when known; "not reported" only for harness agents.
654
- const hLabel = sel.harness ? harnessLabel(sel.harness) : "";
655
- const hColor = sel.harness ? harnessColor(sel.harness) : "";
656
- const harnessRow = sel.harness
657
- ? `<div class="d-row"><span class="k">harness</span><span class="v"><span class="hmark" style="color:${hColor}">${esc(harnessGlyph(sel.harness))}</span> ${esc(hLabel)}</span></div>`
658
- : "";
659
- const modelRow = sel.harness
660
- ? `<div class="d-row"><span class="k">model</span><span class="v${sel.model ? "" : " muted"}">${sel.model ? esc(sel.model) + (sel.variant ? ` · ${esc(sel.variant)}` : "") : "not reported"}</span></div>`
661
- : sel.model
662
- ? `<div class="d-row"><span class="k">model</span><span class="v">${esc(sel.model)}${sel.variant ? ` · ${esc(sel.variant)}` : ""}</span></div>`
663
- : "";
664
- const att = attMark(sel.attention);
665
- const attRow = att
666
- ? `<div class="d-row"><span class="k">attention</span><span class="v att-${esc(sel.attention)}">${att} ${esc(sel.attention)}</span></div>`
667
- : "";
668
- // The card's own description (AgentCard.description) — the same legibility text the Monitor shows.
669
- const descBlock = sel.description ? `<div class="d-block">${esc(sel.description)}</div>` : "";
670
- const tagsSection = (sel.tags || []).length
671
- ? `<div class="d-section"><div class="d-label">tags</div><div class="d-tags">${sel.tags.map((t) => `<span class="ctag">${esc(t)}</span>`).join("")}</div></div>`
672
- : "";
673
- // Per-channel attention overrides (quiet / muted) — advisory receive-side, not ACL.
674
- const modeEntries = Object.entries(sel.channelModes || {}).sort(([a], [b]) => a.localeCompare(b));
675
- const modesSection = modeEntries.length
676
- ? `<div class="d-section"><div class="d-label">channel modes</div><div class="d-tags">${modeEntries.map(([ch, m]) => `<span class="ctag${m === "muted" ? " off" : ""}">#${esc(ch)} · ${esc(m)}</span>`).join("")}</div></div>`
677
- : "";
678
- el.innerHTML = `<span class="x" id="dx">✕</span>
679
- <div class="d-kind">agent</div>
680
- <div class="d-who">${esc(sel.name)}${sel.role ? `<span class="role">${esc(sel.role)}</span>` : ""}</div>
681
- <div class="d-status ${sel.status}"><span class="dot"></span>${esc(sel.status === "working" && sel.progress?.kind === "unknown" ? "working · progress unknown" : sel.status)}</div>
682
- ${presenceFacts(sel) ? `<div class="presence-facts">${esc(presenceFacts(sel))}</div>` : ""}
683
- ${descBlock}
684
- <div class="d-section"><div class="d-label">activity</div><div class="d-block ${sel.activity ? "" : "muted"}">${esc(sel.activity || "no current activity")}</div></div>
685
- ${(harnessRow || modelRow || attRow) ? `<div class="d-rows">${harnessRow}${modelRow}${attRow}</div>` : ""}
686
- <div class="d-section"><div class="d-label">subscribes</div>${subs}</div>
687
- ${modesSection}
688
- ${tagsSection}
689
- <div class="d-section"><div class="d-label">recent</div><div class="d-msgs">${recentRows((m) => m.from === sel.name || m.to === sel.name)}</div></div>`;
690
- }
691
- el.classList.add("open"); $("dx").onclick = closeDetail;
692
- }
693
-
694
- // ── events ──
695
- // A <canvas> is a REPLACED element: `inset:0` does NOT stretch it the way it stretches a block. Without
696
- // an explicit CSS size it renders at its intrinsic (= backing) size — W*DPR × H*DPR — so on a retina Mac
697
- // (DPR 2) it overflows the viewport at 2× and pointer coords no longer map to the drawing's coordinate
698
- // space (zoom/hover/click anchor low-and-right of the cursor). Pin the CSS size to the viewport so backing
699
- // stays crisp at DPR while clientX/clientY line up 1:1 with the world transform.
700
- function resize() { DPR = window.devicePixelRatio || 1; W = window.innerWidth; H = window.innerHeight; canvas.width = W * DPR; canvas.height = H * DPR; canvas.style.width = W + "px"; canvas.style.height = H + "px"; if (!cam.ready) { cam.x = W / 2; cam.y = H / 2; cam.ready = true; } }
701
- window.addEventListener("resize", resize);
702
- let drag = null;
703
- canvas.addEventListener("mousemove", (e) => { if (drag) { cam.x = drag.cx + (e.clientX - drag.sx); cam.y = drag.cy + (e.clientY - drag.sy); drag.moved = drag.moved || Math.hypot(e.clientX - drag.sx, e.clientY - drag.sy) > 4; if (drag.moved) cam.user = true; return; } hover = pick(e.clientX, e.clientY); canvas.classList.toggle("hover", !!hover); });
704
- canvas.addEventListener("mousedown", (e) => { drag = { sx: e.clientX, sy: e.clientY, cx: cam.x, cy: cam.y, moved: false }; });
705
- window.addEventListener("mouseup", (e) => { if (drag && !drag.moved) { const n = pick(e.clientX, e.clientY); if (n) { sel = n; renderDetail(); $("hint").style.opacity = 0; } else closeDetail(); } drag = null; });
706
- // Zoom-to-cursor. The factor is PROPORTIONAL to the wheel delta (exp), not a fixed step per event: a
707
- // trackpad fires a burst of tiny wheel events per gesture, and a fixed 1.1×-each slammed the scale
708
- // straight to the clamp — flinging the graph off-screen around the (correctly anchored) cursor. deltaMode
709
- // is normalized to px so a mouse notch and a trackpad swipe both feel right.
710
- canvas.addEventListener("wheel", (e) => { e.preventDefault(); cam.user = true; const px = e.deltaY * (e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? H : 1), f = Math.exp(-px * 0.0015), ns = Math.max(0.3, Math.min(3, cam.scale * f)), w = toWorld(e.clientX, e.clientY); cam.scale = ns; cam.x = e.clientX - w.x * ns; cam.y = e.clientY - w.y * ns; }, { passive: false });
711
- window.addEventListener("keydown", (e) => { if (e.key === "Escape") closeDetail(); });
712
- // Backgrounded tab: drop in-flight decoration (rAF is frozen, so mid-flight comets would otherwise
713
- // detonate their onArrive fan-out on return). State (edges/roster/recent) is untouched. On return:
714
- // reset lastT so the first frame doesn't integrate a multi-minute dt, and reheat physics so a node
715
- // set that changed while hidden can re-settle instead of sitting cold.
716
- document.addEventListener("visibilitychange", () => {
717
- if (document.visibilityState === "hidden") {
718
- particles.length = 0;
719
- blooms.length = 0;
720
- } else {
721
- lastT = performance.now();
722
- reheat();
723
- }
724
- });
725
- $("modes").onclick = (e) => { const c = e.target.closest(".chip"); if (!c) return; const m = c.dataset.mode; filter[m] = !filter[m]; c.classList.toggle("on", filter[m]); };
726
- $("pause").onclick = () => { filter.paused = !filter.paused; $("pause").classList.toggle("on", filter.paused); $("pause").textContent = filter.paused ? "▶ resume" : "⏸ pause"; };
727
- $("hideOffline").onclick = () => { filter.hideOffline = !filter.hideOffline; $("hideOffline").classList.toggle("on", filter.hideOffline); recomputeHubEmpty(); if (sel && isHidden(sel)) closeDetail(); if (hover && isHidden(hover)) hover = null; reheat(); if (sel) renderDetail(); };
728
- $("hideEmpty").onclick = () => { filter.hideEmpty = !filter.hideEmpty; $("hideEmpty").classList.toggle("on", filter.hideEmpty); recomputeHubEmpty(); if (sel && isHidden(sel)) closeDetail(); if (hover && isHidden(hover)) hover = null; reheat(); if (sel) renderDetail(); };
729
- $("legendToggle").onclick = () => $("legend").classList.toggle("collapsed");
730
- function setConn(live) { const el = $("conn"); el.classList.toggle("down", !live); el.querySelector(".t").textContent = live ? "live" : "disconnected"; }
731
-
732
- /** Say which sources are showing their last good value. Visible, not a console line. */
733
- function setStale(stale) {
734
- const el = $("stale");
735
- if (!el) return;
736
- staleNow = stale;
737
- const label = window.COTAL_SNAPSHOT.staleLabel(stale);
738
- el.hidden = !label;
739
- el.querySelector(".t").textContent = label;
740
- el.title = stale.map((s) => `${s.name}: ${s.reason}`).join("\n");
741
- }
742
- let staleNow = [];
743
- function markStale(name, entry) {
744
- const rest = staleNow.filter((s) => s.name !== name);
745
- staleNow = entry ? [...rest, entry] : rest;
746
- setStale(staleNow);
747
- }
748
- function applyPresenceView(view) {
749
- if (!view || view.fresh) {
750
- markStale("roster", null);
751
- return;
752
- }
753
- if (view.state === "unpopulated") {
754
- markStale("roster", { name: "roster", reason: "observer presence snapshot still loading" });
755
- return;
756
- }
757
- const since = typeof view.staleSince === "number" ? new Date(view.staleSince).toISOString() : "unknown";
758
- markStale("roster", { name: "roster", reason: `observer presence watch silent since ${since}` });
759
- }
760
-
761
- // ── boot ──
762
- const channelsSource = { name: "channels", read: async () => window.COTAL_SNAPSHOT.readJson(await fetch("/api/channels"), "channels"),
763
- apply: (chans) => {
764
- for (const c of chans) { const h = ensureHub(c.channel); h.msgs = c.messages || 0; h.desc = c.description || ""; h.deliveryClass = c.deliveryClass; h.replay = c.replay; h.replayWindow = c.replayWindow; }
765
- if (lastMembers) drawMembers(lastMembers);
766
- } };
767
- // A hub that appears in a member's row or a message reads `/api/channels` again for its class, and so
768
- // does the first post on a hub still without one, since a post can put a channel on that list. A
769
- // channel the list never names is read for once, not once per post. One read answers for every hub
770
- // that appears within the wait.
771
- let channelsReread = 0;
772
- function rereadChannels() {
773
- if (channelsReread) return;
774
- channelsReread = setTimeout(async () => {
775
- channelsReread = 0;
776
- const stale = await window.COTAL_SNAPSHOT.refreshAll([channelsSource]);
777
- markStale("channels", stale[0] || null);
778
- }, 250);
779
- }
780
- async function load() {
781
- // ── ONE REFUSED READ MUST NOT EMPTY THE PAGE ────────────────────────────────────────────────
782
- //
783
- // This was a six-way `Promise.all` of `fetch(u).then((r) => r.json())`. `fetch` does not reject
784
- // on a 500 and this server's 500 body is `{"error": "..."}`, which parses, so the refusal
785
- // arrived as DATA and the first `for (const c of chans)` threw `chans is not iterable` out of
786
- // the whole bootstrap. The `.catch(() => [])` guards on activity and dms never fired for the
787
- // same reason: there was nothing to catch. Because `load()` rejected, `connect()`, which runs
788
- // as `load().then(connect)`, was never called, so the page sat at `disconnected` with no peers
789
- // and no channel hubs and could not recover without a reload. Measured against a broker behind
790
- // a 160ms link, where `/api/channels` and `/api/activity` both returned 500 `timeout`.
791
- //
792
- // Now every source is read independently, only successful reads are applied, and what did not
793
- // land is named on screen. Nothing here can prevent `connect()` from running.
794
- const SNAP = window.COTAL_SNAPSHOT;
795
- let activityPage = null;
796
- const stale = await SNAP.refreshAll([
797
- { name: "space", read: async () => SNAP.readJson(await fetch("/api/meta"), "space"),
798
- apply: (meta) => { $("space").textContent = "· " + meta.space; } },
799
- channelsSource,
800
- { name: "peers", read: async () => SNAP.readJson(await fetch("/api/roster"), "peers"),
801
- apply: supersededByFeed("peers", (roster) => updateRoster(roster)) },
802
- // `.catch(() => ({members: []}))` here turned a failed fetch into an empty snapshot, which the
803
- // pill then reported as "traffic-only" — the client half of the same defect the server had.
804
- // A non-200 is not a snapshot either: `r.json()` on the refusal body would parse fine and
805
- // arrive as data, so the status is checked before the body is trusted. That check now lives in
806
- // `readJson`, and an unreadable feed reaches `membershipUnreadable()` through the stale path.
807
- { name: "membership", read: async () => SNAP.readJson(await fetch("/api/membership"), "membership"),
808
- apply: supersededByFeed("membership", (m) => applyMembership(m)) },
809
- // `/api/activity` answers an ENVELOPE, never a bare array; a caller that ignored `partial`
810
- // would break here rather than seed a short page as though it were the whole backfill.
811
- { name: "activity", read: async () => SNAP.readJson(await fetch("/api/activity?limit=400"), "activity"),
812
- apply: (page) => { activityPage = page; seedActivity(page.entries); } },
813
- { name: "direct messages", read: async () => SNAP.readJson(await fetch("/api/dms?limit=400"), "direct messages"),
814
- apply: (dmHist) => seedDms(dmHist) },
815
- ]);
816
- if (activityPage && activityPage.partial)
817
- stale.push({
818
- kind: "partial",
819
- name: "activity",
820
- reason: `${activityPage.read} of ${activityPage.of} sources answered within ${activityPage.deadlineMs}ms; missing ${activityPage.missing.map((m) => `${m} (${activityPage.reasons[m]})`).join(", ")}`,
821
- });
822
- const rosterView = staleNow.find((s) => s.name === "roster");
823
- if (rosterView && !stale.some((s) => s.name === "roster")) stale.push(rosterView);
824
- setStale(stale);
825
- // A bootstrap read that REFUSED is a sentence about the membership source like any other, so it
826
- // obeys the same rule as the snapshot beside it: it is a fact about that one read, and the live
827
- // feed may already have said something newer. Routed through `supersededByFeed` rather than a
828
- // second copy of the condition, because two spellings of one rule is how two halves drift apart.
829
- if (stale.some((s) => s.name === "membership")) supersededByFeed("membership", membershipUnreadable)();
830
- alpha = 1; for (let i = 0; i < 200; i++) physics(); // pre-warm to a settled layout
831
- const f = fitTarget(); cam.x = f.x; cam.y = f.y; cam.scale = f.scale;
832
- }
833
-
834
- /** Seed traffic glow + the `recent` buffer from the activity backfill so the channel detail's
835
- * "recently active" tags and the "recent" section aren't empty until the first live SSE message
836
- * arrives. Its own function so the read that feeds it can fail without taking the boot with it. */
837
- function seedActivity(activity) {
838
- for (const e of activity) { const m = e.msg; if (m) m.channel = e.channel; const a = m?.from?.id && agents.get(m.from.id); if (e.mode === "chat" && m?.channel && a) chatHit(a, m.channel, m.ts || now()); }
839
- for (const e of activity.slice(-80)) {
840
- const m = e.msg; if (!m) continue;
841
- const to = e.mode === "unicast" ? (typeof m.to === "string" ? (agents.get(m.to)?.name || shortId(m.to)) : m.to?.name) : e.mode === "anycast" ? "@" + (m.toService || "") : null;
842
- recent.push({ mode: e.mode, from: m.from?.name, fromId: m.from?.id, to, chan: m.channel, text: partsText(m), ts: m.ts || now() });
843
- }
844
- recent.sort((a, b) => a.ts - b.ts);
845
- if (recent.length > 80) recent.splice(0, recent.length - 80);
846
- }
847
-
848
- function seedDms(dmHist) {
849
- for (const m of dmHist) { const a = m.from?.id && agents.get(m.from.id), b = typeof m.to === "string" && agents.get(m.to); if (a && b && a !== b) dmHit(a, b, m.ts || now()); }
850
- }
851
- function connect() { const es = new EventSource("/feed"); es.onopen = () => setConn(true); es.onerror = () => setConn(false); es.addEventListener("roster", (e) => { liveApplied.add("peers"); updateRoster(JSON.parse(e.data)); }); es.addEventListener("presence-view", (e) => { applyPresenceView(JSON.parse(e.data)); }); es.addEventListener("membership", (e) => { liveApplied.add("membership"); applyMembership(JSON.parse(e.data)); }); es.addEventListener("membership-read-failed", () => { liveApplied.add("membership"); membershipUnreadable(); }); es.addEventListener("message", (e) => onMessage(JSON.parse(e.data))); }
852
-
853
- resize();
854
- setInterval(setFeed, 5000); // age "live" → "stale" even without new events
855
- // THE FEED IS NOT GATED ON THE BOOTSTRAP, IN EITHER SENSE. It was once chained behind `load()`
856
- // RESOLVING, so a single refused read left the page permanently disconnected with nothing on it.
857
- // That was fixed by making `load()` never reject, which guaranteed `connect()` would RUN but not
858
- // that it would run SOON: chained with `.then`, it still waited for the whole bootstrap, and that
859
- // bootstrap reads `/api/activity?limit=400` and `/api/dms?limit=400`, both bounded by the
860
- // aggregation deadline. On a slow link the page therefore read `disconnected` for the entire load
861
- // window. Observed across a WAN link as "always showing disconnected, and taking long to show the
862
- // graph". The live feed is exactly what a page showing stale data needs most, so it opens FIRST
863
- // and the bootstrap fills in around it. The Monitor page has always done this: `app.js` ends with
864
- // `refresh(); connect();`, concurrent, not chained.
865
- connect();
866
- load().catch((err) => console.error(err));
867
- requestAnimationFrame(frame);
868
- })();