@cotal-ai/web 0.138.1 → 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/app.js DELETED
@@ -1,1428 +0,0 @@
1
- // Cotal observability client: a read-only god-view of one space. Presence + channel
2
- // list + DM history come over HTTP; the live stream (roster + every chat/unicast/anycast
3
- // message) arrives via SSE (/feed). This page never publishes to the mesh.
4
- //
5
- // Three centre views, one consistent skeleton (left = navigation, centre = content,
6
- // right = NEEDS YOU, always): the Monitor (all-activity feed), a Channel view (message
7
- // list; members fold into the header), and a Direct-messages lens (per-peer roll-up in
8
- // the sidebar → a thread in the centre). `?demo` renders the fixed reference scene.
9
-
10
- import { ago, presenceFacts } from "./presence.js";
11
-
12
- const $ = (id) => document.getElementById(id);
13
- const STATUS = ["working", "waiting", "idle", "offline"];
14
- // Status as shape *and* colour (never colour alone).
15
- const GLYPH = { working: "●", waiting: "◐", idle: "○", offline: "⊘" };
16
- const MODES = ["chat", "unicast", "anycast"];
17
- const isDemo = new URLSearchParams(location.search).has("demo");
18
-
19
- let channelDeleteSupported = false;
20
- let roster = [];
21
- let channels = new Map(); // name -> { messages, description?, replay, replayWindow?, deliveryClass }
22
- let unread = new Map(); // name -> messages seen since last viewed
23
- let dms = []; // raw DM messages (god-view), grouped client-side
24
- let selected = "*"; // "*" = all activity, else a channel name (null when a DM is open)
25
- let dmSel = null; // { peer, with } when a Direct-messages thread is open
26
- let agentSel = null; // peer id when an Agent Detail drill-down is open (else selected/dmSel drive the view)
27
- let activity = []; // {mode, msg} ring buffer for the all-activity view
28
- let channelMsgs = []; // messages for the selected channel
29
- // The shape-B bootstrap for each of the two merge sites: this page opens the live feed and only then
30
- // fetches the backfill, so a frame's `seq` order is the consumer's problem. One machine per
31
- // bootstrap, re-armed BEFORE its fetch starts, so frames arriving during the fetch are held rather
32
- // than ordered against a baseline that has not been established yet.
33
- let feedOrder = window.COTAL_EVENT_ORDER.create();
34
- let channelOrder = window.COTAL_EVENT_ORDER.create();
35
- // Gap and prefix notes, newest last, keyed for the surface that draws them. Kept rather than logged:
36
- // a gap that only reaches the console is a gap nobody sees.
37
- let orderNotes = [];
38
- function noteOrder(notes) {
39
- for (const n of notes) orderNotes.push(n);
40
- if (orderNotes.length > 50) orderNotes = orderNotes.slice(-50);
41
- }
42
- /** In-flight bootstrap, so a second caller shares it instead of arming a rival machine. */
43
- let refreshing = null;
44
-
45
- /** The notes, as the banner the feed views draw above their rows.
46
- *
47
- * THIS EXISTS BECAUSE COMPUTING A GAP AND DRAWING ONE ARE DIFFERENT CLAIMS. The notes were collected
48
- * into an array that nothing read, so the machine detected a missing frame and the page said nothing:
49
- * a gap that reaches only an unused variable is a gap nobody sees, which is the same silence this
50
- * lane exists to remove, one layer up. A reader has to be able to act differently on a lost frame, an
51
- * evicted prefix and an ordinary feed.
52
- *
53
- * The three kinds are drawn as three different statements, because collapsing them would put the one
54
- * that always happens on a late join next to the one that must never be ignored. */
55
- function orderNoticeHtml() {
56
- if (!orderNotes.length) return "";
57
- const gaps = orderNotes.filter((n) => n.type === "gap");
58
- const races = orderNotes.filter((n) => n.type === "boundary-hole");
59
- const prefixes = orderNotes.filter((n) => n.type === "prefix-incomplete");
60
- const failures = orderNotes.filter((n) => n.type === "backfill-failed");
61
- const parts = [];
62
- if (gaps.length) {
63
- const missing = gaps.reduce((sum, g) => sum + (g.missing || 0), 0);
64
- parts.push(`<b>${missing} event frame${missing === 1 ? "" : "s"} missing</b> (${gaps.length} break${gaps.length === 1 ? "" : "s"} in the stream)`);
65
- }
66
- if (races.length) parts.push(`${races.length} possible ordering race${races.length === 1 ? "" : "s"} at start-up, unconfirmed`);
67
- if (prefixes.length) parts.push(`${prefixes.length} stream${prefixes.length === 1 ? "" : "s"} joined after the start, earlier frames not retained`);
68
- if (failures.length) parts.push(`history unavailable, so ordering is based on live frames only`);
69
- if (!parts.length) return "";
70
- return `<div class="order-notice${gaps.length ? " fault" : ""}">${parts.join(" · ")}</div>`;
71
- }
72
- let modes = new Set(MODES); // delivery modes currently shown
73
- let paused = false; // freeze auto-scroll so a value can be read
74
- let expandAll = false; // channel-wide: expand every clamped message body (else per-message toggle)
75
-
76
- const esc = window.COTAL_PARTS.esc;
77
- const time = (ts) => new Date(ts).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
78
- // Shared with graph.js via parts.js (loaded before this file). It names a part kind it cannot
79
- // draw instead of rendering it as the empty string, which read as "nothing arrived".
80
- const bodyText = (msg) => window.COTAL_PARTS.partsToText(msg.parts);
81
- const agoShort = ago;
82
- const plural = (n, w) => `${n} ${w}${n === 1 ? "" : "s"}`;
83
-
84
- // Markdown rendering lives in md.js (window.COTAL_MD) — marked + DOMPurify, one source for every
85
- // message body. render() escapes+sanitizes untrusted agent text; never pass raw text to innerHTML.
86
- const MD = window.COTAL_MD;
87
- // Harness branding lives in harness.js (window.COTAL_HARNESS) — one source for monitor + graph.
88
- const HARNESS = window.COTAL_HARNESS || {};
89
- // Render the harness badge: a branded pill (svg + label) by default, or `{compact:true}` for a
90
- // bare colour icon (the roster row). Style values only ever come from HARNESS, never raw card input.
91
- function harnessBadge(connector, opts = {}) {
92
- if (!connector) return "";
93
- const h = HARNESS[connector];
94
- const color = h ? h.color : "var(--dim)";
95
- const text = h ? h.label : connector;
96
- if (opts.compact)
97
- return h ? `<span class="harness-ico" style="color:${color}" title="harness · ${esc(text)}">${h.svg}</span>` : "";
98
- return `<span class="harness-badge" style="--hc:${color}" title="agent harness · ${esc(text)}">${h ? h.svg : ""}<span class="hl">${esc(text)}</span></span>`;
99
- }
100
- // Attention is advisory presence: open/absent are the same ("receives all") — only dnd/focus surface.
101
- // Shape + label (never colour alone). Returns "" for open/absent.
102
- function attentionChip(attention, opts = {}) {
103
- if (attention !== "dnd" && attention !== "focus") return "";
104
- const label = attention === "dnd" ? "dnd" : "focus";
105
- const glyph = attention === "dnd" ? "◼" : "◉";
106
- const title = attention === "dnd" ? "do not disturb — untagged channel chatter won't wake" : "focus — only DMs/anycast reach context";
107
- if (opts.compact) return `<span class="att ${label}" title="${title}">${glyph}</span>`;
108
- return `<span class="att-badge ${label}" title="${title}"><span class="att ${label}">${glyph}</span>${label}</span>`;
109
- }
110
-
111
- function setConn(live) {
112
- const el = $("conn");
113
- el.className = "pill" + (live ? "" : " down");
114
- el.querySelector(".t").textContent = live ? "live" : "disconnected";
115
- }
116
-
117
- /** What the marker is currently saying, so a source read OUTSIDE the poll can add to it without
118
- * erasing the poll's own findings. `refresh()` sets the four polled sources; the open channel's
119
- * history is read later, inside `select()`, and a bare `setStale([channel])` there would drop the
120
- * roster/channels/dms/activity refusals from the same label. */
121
- let staleNow = [];
122
- /** Say WHICH sources are showing their last good value, and why. Visible, not a console line: the
123
- * whole point of keeping the snapshot is that the reader knows they are looking at it. Cleared by
124
- * the next refresh in which everything landed, which is what recovery looks like from here. */
125
- function setStale(stale) {
126
- staleNow = stale;
127
- renderStale();
128
- }
129
- /** Mark ONE source, or clear it, leaving every other source's mark alone. A successful read clears
130
- * its own mark and nobody else's, which is what makes recovery per source rather than all-or-nothing. */
131
- function markStale(name, entry) {
132
- const rest = staleNow.filter((s) => s.name !== name);
133
- setStale(entry ? [...rest, entry] : rest);
134
- }
135
-
136
- /** The observer's own presence watch, not a peer. A stall past TTL is "the window went
137
- * blind", not "everyone left". Keep last-known online rows and name the view stale. */
138
- function applyPresenceView(view) {
139
- if (!view || view.fresh) {
140
- markStale("roster", null);
141
- return;
142
- }
143
- if (view.state === "unpopulated") {
144
- markStale("roster", { name: "roster", reason: "observer presence snapshot still loading" });
145
- return;
146
- }
147
- const since = typeof view.staleSince === "number" ? new Date(view.staleSince).toISOString() : "unknown";
148
- markStale("roster", { name: "roster", reason: `observer presence watch silent since ${since}` });
149
- }
150
-
151
- function renderStale() {
152
- const el = $("stale");
153
- if (!el) return;
154
- const label = window.COTAL_SNAPSHOT.staleLabel(staleNow);
155
- el.hidden = !label;
156
- // CLEARED, NOT JUST HIDDEN. Returning early on recovery left the previous label and its tooltip
157
- // sitting in the element. Hidden text is invisible until something else unhides it, and then the
158
- // reader is told a source is stale that recovered some time ago. Recovery has to erase the claim,
159
- // not park it.
160
- el.querySelector(".t").textContent = label;
161
- el.title = staleNow.map((s) => `${s.name}: ${s.reason}`).join("\n");
162
- }
163
-
164
- // ── Header: golden-signal tiles ───────────────────────────────────────────────
165
- // Fifth tile is last-heartbeat freshness (Presence.ts), NOT blocked-duration: statusSince dates the
166
- // last change of status or activity, and a seat can change its activity while it stays blocked.
167
- // Label it honestly.
168
- function renderTiles(counts, stalest) {
169
- const tiles = [
170
- ["working", counts.working],
171
- ["waiting", counts.waiting],
172
- ["idle", counts.idle],
173
- ["offline", counts.offline],
174
- ["oldest", stalest, "stalest live heartbeat"],
175
- ];
176
- $("tiles").innerHTML = tiles
177
- .map(([k, n, lbl]) => {
178
- // Amber only when waiting > 0 — a zero-count alert is pure alarm fatigue.
179
- const alert = k === "waiting" && Number(n) > 0 ? " alert" : "";
180
- return `<div class="tile ${k}${alert}">
181
- <span class="bar"></span>
182
- <div class="c"><span class="n">${n}</span><span class="lbl">${lbl ?? k}</span></div>
183
- </div>`;
184
- })
185
- .join("");
186
- }
187
-
188
- // ── Sidebar: roster ───────────────────────────────────────────────────────────
189
- function peerRow(p) {
190
- // A peer with an id is a click-through into its Agent Detail card; demo rows have no id.
191
- const nav = p.id ? ` nav${p.id === agentSel ? " sel" : ""}` : "";
192
- const attrs = p.id ? ` data-agent="${esc(p.id)}" tabindex="0" role="button"` : "";
193
- return `<div class="peer ${p.status}${nav}"${attrs}>
194
- <span class="dot ${p.status}">${GLYPH[p.status] ?? "○"}</span>
195
- <div class="c">
196
- <div class="l1">
197
- <span class="name">${esc(p.name)}</span>
198
- ${p.harness ? harnessBadge(p.harness, { compact: true }) : ""}
199
- ${p.role ? `<span class="role">${esc(p.role)}</span>` : ""}
200
- ${attentionChip(p.attention, { compact: true })}
201
- ${p.tag ? `<span class="tag">${esc(p.tag)}</span>` : ""}
202
- </div>
203
- ${p.act ? `<div class="act" title="${esc(p.act)}">${esc(p.act)}</div>` : ""}
204
- ${p.facts ? `<div class="presence-facts">${esc(p.facts)}</div>` : ""}
205
- </div>
206
- </div>`;
207
- }
208
- // Grouped by the machine each peer reports in `card.meta.host`, so placement across a multi-machine
209
- // mesh reads at a glance. A peer that reports no host (a manager card carries none) groups last
210
- // instead of being guessed onto a machine. Seats do not name the manager they run under, so there
211
- // is no manager grouping to draw from this feed.
212
- function renderRoster(list) {
213
- const machines = new Map();
214
- for (const p of list) {
215
- const host = typeof p.host === "string" ? p.host : "";
216
- if (!machines.has(host)) machines.set(host, []);
217
- machines.get(host).push(p);
218
- }
219
- $("roster").innerHTML = list.length
220
- ? [...machines.keys()]
221
- .sort((a, b) => !a - !b || a.localeCompare(b))
222
- .map((host) => {
223
- const peers = machines.get(host);
224
- return `<div class="machine"><span class="h">${host ? esc(host) : "host not reported"}</span><span class="c">${peers.length}</span></div>${peers.map(peerRow).join("")}`;
225
- })
226
- .join("")
227
- : `<div class="empty">no peers</div>`;
228
- for (const el of $("roster").querySelectorAll(".peer[data-agent]")) {
229
- el.onclick = () => selectAgent(el.dataset.agent);
230
- el.onkeydown = (e) => {
231
- if (e.key === "Enter" || e.key === " ") (e.preventDefault(), selectAgent(el.dataset.agent));
232
- };
233
- }
234
- }
235
- // The online roster, shaped for the sidebar: offline peers drop out (their count still rides the
236
- // header tiles), live peers sort by status then name. Re-rendered on its own when a selection
237
- // changes so the row highlight tracks the open Agent Detail.
238
- function rosterRows() {
239
- return [...roster]
240
- .filter((p) => p.status !== "offline")
241
- .sort(
242
- (a, b) =>
243
- STATUS.indexOf(a.status) - STATUS.indexOf(b.status) ||
244
- a.card.name.localeCompare(b.card.name),
245
- )
246
- .map((p) => ({
247
- id: p.card.id,
248
- name: p.card.name,
249
- role: p.card.role,
250
- status: p.status,
251
- act: p.activity,
252
- facts: presenceFacts(p),
253
- harness: p.card.meta?.connector,
254
- host: p.card.meta?.host,
255
- attention: p.attention, // open/absent both render as nothing
256
- tag: p.status === "waiting" ? "needs input" : null,
257
- }));
258
- }
259
-
260
- // ── Sidebar: channels ─────────────────────────────────────────────────────────
261
- // deliveryClass as shape+letter (never colour alone): D = durable, L = live.
262
- function deliveryGlyph(dc) {
263
- if (dc === "live") return `<span class="dclass live" title="live delivery — at-most-once">L</span>`;
264
- if (dc === "durable") return `<span class="dclass durable" title="durable delivery — at-least-once for members">D</span>`;
265
- return "";
266
- }
267
- // Replay state at a glance (shape, not colour alone): ↻ = on, struck ↻ = off. Unknown (a live
268
- // message that beat the registry) shows nothing rather than guessing a default.
269
- function replayGlyph(replay) {
270
- if (replay === true) return `<span class="replay on" title="replay on — a join backfills retained history">↻</span>`;
271
- if (replay === false) return `<span class="replay off" title="replay off — a join does not backfill history">↻</span>`;
272
- return "";
273
- }
274
- function chanRow(ch) {
275
- const sel = !dmSel && ch.key === selected;
276
- const lead = ch.all ? `<span class="glyph">✸</span>` : `<span class="hash">#</span>`;
277
- return `<div class="chan${sel ? " sel" : ""}" data-ch="${esc(ch.key)}">
278
- <span class="l">${lead}<span class="name">${esc(ch.label)}</span>${ch.dclass ? deliveryGlyph(ch.dclass) : ""}${replayGlyph(ch.replay)}</span>
279
- ${ch.mention ? `<span class="mention">${ch.mention}</span>` : ""}
280
- <span class="count">${ch.count}</span>
281
- </div>`;
282
- }
283
- function renderChannels() {
284
- const names = [...channels.keys()]; // insertion order (curated in demo, server order live)
285
- const total = [...channels.values()].reduce((sum, ch) => sum + (ch.messages || 0), 0);
286
- const rows = [{ key: "*", all: true, label: "all activity", count: total }].concat(
287
- names.map((n) => {
288
- const c = channels.get(n) || {};
289
- return {
290
- key: n,
291
- label: n,
292
- count: c.messages || 0,
293
- mention: unread.get(n) || 0,
294
- dclass: c.deliveryClass,
295
- replay: c.replay,
296
- };
297
- }),
298
- );
299
- $("channels").innerHTML = rows.map(chanRow).join("");
300
- for (const el of $("channels").querySelectorAll(".chan")) el.onclick = () => select(el.dataset.ch);
301
- }
302
-
303
- // ── Sidebar: direct messages (per-peer roll-up → drill) ───────────────────────
304
- const SEP = "\u0001";
305
- function peerById(id) {
306
- return roster.find((x) => x.card?.id === id);
307
- }
308
- function roleOf(id) {
309
- const r = peerById(id);
310
- return r?.card?.role;
311
- }
312
- function rosterStatus(id) {
313
- const r = peerById(id);
314
- return r ? r.status : "offline";
315
- }
316
- // id→name resolution shared by the DM lens and the all-activity feed. `from` carries a full
317
- // card (id+name), but a unicast `to` is the bare recipient identity id (a pubkey) — without this
318
- // it renders raw. Source: live roster cards ONLY. A message payload's from.name is sender-chosen
319
- // display text, not identity (#1399): writing it here would let one peer relabel another.
320
- function nameIndex() {
321
- const idName = new Map();
322
- for (const p of roster) if (p.card?.id) idName.set(p.card.id, p.card.name);
323
- return idName;
324
- }
325
- // Resolve an EndpointRef object or a bare id to a display name; an unknown id shrinks to a short
326
- // prefix, and a string that isn't an identity (already a name) passes through unchanged. An object
327
- // resolves through its AUTHENTICATED id — its .name is payload text and is never rendered.
328
- function displayNameOf(x, idx) {
329
- if (!x) return "?";
330
- if (typeof x === "object") return displayNameOf(x.id, idx);
331
- if (idx.has(x)) return idx.get(x);
332
- // Principal ids are exactly two NATS-safe tokens, owner.actor. Keep the opaque owner for
333
- // namespace disambiguation, but require a long actor so ordinary dotted display names survive.
334
- const principal = /^([A-Za-z0-9_]+)\.([A-Za-z0-9_]+)$/.exec(x);
335
- if (principal && principal[2].length >= 32)
336
- return `${principal[1]}.${principal[2].slice(0, 6)}…`;
337
- return /^[A-Z2-7]{32,}$/.test(x) ? x.slice(0, 6) + "…" : x; // legacy bare identity
338
- }
339
-
340
- // Group raw DMs into per-peer rows; each peer lists its counterparties (conversations).
341
- // O(peers-with-DMs), never the n² pair cross-product — only pairs that actually talked.
342
- function dmPeers() {
343
- if (isDemo) return DEMO.dmPeers;
344
- const idx = nameIndex();
345
- const conv = new Map();
346
- for (const m of dms) {
347
- const from = m.from?.id;
348
- const to = typeof m.to === "string" ? m.to : m.to?.id;
349
- if (!from || !to || from === to) continue;
350
- const parts = [from, to].sort();
351
- const key = parts.join(SEP);
352
- if (!conv.has(key)) conv.set(key, { parts, msgs: [] });
353
- conv.get(key).msgs.push({
354
- ts: time(m.ts),
355
- who: from,
356
- whoName: displayNameOf(from, idx),
357
- status: rosterStatus(from),
358
- body: bodyText(m),
359
- _ts: m.ts,
360
- });
361
- }
362
- const peers = new Map();
363
- for (const c of conv.values()) {
364
- c.msgs.sort((x, y) => x._ts - y._ts);
365
- const last = c.msgs.length ? c.msgs[c.msgs.length - 1]._ts : 0;
366
- for (const p of c.parts) {
367
- const other = c.parts[0] === p ? c.parts[1] : c.parts[0];
368
- if (!peers.has(p)) peers.set(p, { id: p, name: displayNameOf(p, idx), conversations: [], last: 0 });
369
- const pe = peers.get(p);
370
- pe.conversations.push({
371
- with: other,
372
- withName: displayNameOf(other, idx),
373
- role: roleOf(other),
374
- status: rosterStatus(other),
375
- unread: 0,
376
- last,
377
- msgs: c.msgs,
378
- });
379
- pe.last = Math.max(pe.last, last);
380
- }
381
- }
382
- return [...peers.values()]
383
- .map((p) => ({
384
- id: p.id,
385
- name: p.name,
386
- role: roleOf(p.id),
387
- status: rosterStatus(p.id),
388
- unread: 0,
389
- threads: p.conversations.length,
390
- conversations: p.conversations.sort((a, b) => b.last - a.last),
391
- last: p.last,
392
- }))
393
- .sort((a, b) => b.last - a.last);
394
- }
395
- function dmPeerRow(p, expanded) {
396
- return `<div class="dm${expanded ? " sel" : ""}" data-dm="${esc(p.id)}">
397
- <span class="caret">${expanded ? "▾" : "▸"}</span>
398
- <span class="l">
399
- <span class="dot ${p.status}">${GLYPH[p.status] ?? "○"}</span>
400
- <span class="nm">${esc(p.name)}</span>
401
- ${p.role ? `<span class="role">${esc(p.role)}</span>` : ""}
402
- </span>
403
- ${p.unread ? `<span class="mention">${p.unread}</span>` : ""}
404
- ${expanded ? "" : `<span class="threads">${plural(p.threads, "thread")}</span>`}
405
- </div>`;
406
- }
407
- function dmSubRow(peer, c) {
408
- const sel = dmSel && dmSel.peer === peer && dmSel.with === c.with;
409
- return `<div class="dm sub${sel ? " sel" : ""}" data-dm="${esc(peer)}${SEP}${esc(c.with)}">
410
- <span class="ln">↳</span>
411
- <span class="l">
412
- <span class="dot ${c.status}">${GLYPH[c.status] ?? "○"}</span>
413
- <span class="nm">${esc(c.withName ?? c.with)}</span>
414
- ${c.role ? `<span class="role">${esc(c.role)}</span>` : ""}
415
- </span>
416
- ${c.unread ? `<span class="mention">${c.unread}</span>` : ""}
417
- </div>`;
418
- }
419
- function renderDMs() {
420
- const peers = dmPeers();
421
- if (!peers.length) {
422
- $("dms").innerHTML = `<div class="empty">no direct messages</div>`;
423
- return;
424
- }
425
- let html = "";
426
- for (const p of peers) {
427
- const expanded = !!dmSel && dmSel.peer === p.id;
428
- html += dmPeerRow(p, expanded);
429
- if (expanded) for (const c of p.conversations) html += dmSubRow(p.id, c);
430
- }
431
- $("dms").innerHTML = html;
432
- for (const el of $("dms").querySelectorAll("[data-dm]")) {
433
- el.onclick = () => {
434
- const [peer, w] = el.dataset.dm.split(SEP);
435
- selectDM(peer, w || null);
436
- };
437
- }
438
- }
439
- function renderSidebarNav() {
440
- renderChannels();
441
- renderDMs();
442
- }
443
-
444
- // ── Feed rows (all-activity) ──────────────────────────────────────────────────
445
- // Progressive disclosure: long agent essays collapse to a few lines; full text one click away.
446
- // Never silently truncate — the expand control is the only path to the rest. Bodies render markdown
447
- // (md.js), so the clamp caps rendered height, not raw characters. `expandAll` opens every body at
448
- // once (the channel-wide toggle); an individual "show more" still flips one.
449
- const BODY_CLAMP_CHARS = 280;
450
- const isLong = (text) => !!text && text.length > BODY_CLAMP_CHARS;
451
- function bodyBlock(text) {
452
- const html = MD.render(text || "");
453
- if (!isLong(text)) return `<div class="body md">${html}</div>`;
454
- const open = expandAll ? " open" : "";
455
- const label = expandAll ? "show less" : "show more";
456
- return `<div class="body md clamp${open}">
457
- <div class="body-text">${html}</div>
458
- <button type="button" class="body-more">${label}</button>
459
- </div>`;
460
- }
461
- // The channel-wide expand/collapse-all control — rendered only when a list actually has clamped
462
- // bodies (nothing to toggle otherwise). Reuses the mode-chip look.
463
- function toggleAllChip(items, bodyOf = (x) => x.body) {
464
- if (!items.some((x) => isLong(bodyOf(x)))) return "";
465
- return `<span class="chip toggle-all" id="toggle-all" title="${expandAll ? "collapse every message" : "expand every message"}">${expandAll ? "⊟ collapse all" : "⊞ expand all"}</span>`;
466
- }
467
- function bindToggleAll(root) {
468
- const el = root.querySelector("#toggle-all");
469
- if (el) el.onclick = () => ((expandAll = !expandAll), renderCenter());
470
- }
471
- function bindBodyToggles(root) {
472
- for (const btn of root.querySelectorAll(".body-more")) {
473
- btn.onclick = (ev) => {
474
- ev.stopPropagation();
475
- const block = btn.closest(".body");
476
- const open = block.classList.toggle("open");
477
- btn.textContent = open ? "show less" : "show more";
478
- };
479
- }
480
- }
481
- function rowHTML(e) {
482
- if (e.type === "sys") return `<div class="sys">${esc(e.text)}</div>`;
483
- if (e.type === "rollup")
484
- return `<div class="rollup"><span class="ar">⌄</span><span class="t">${esc(e.text)}</span></div>`;
485
- const intent = e.type === "intent";
486
- const badgeClass = intent ? "intent" : e.mode;
487
- const badgeText = intent ? "⟶ intent" : e.mode;
488
- const tgt = intent ? e.note : e.target;
489
- return `<div class="msg${intent ? " intent" : ""}">
490
- <span class="ts">${esc(e.ts)}</span>
491
- <span class="badge ${badgeClass}">${esc(badgeText)}</span>
492
- <div class="c">
493
- <div class="l1">
494
- <span class="who">${esc(e.who)}</span>
495
- ${e.role ? `<span class="role">${esc(e.role)}</span>` : ""}
496
- ${tgt ? `<span class="tgt">${esc(tgt)}</span>` : ""}
497
- ${e.sub ? `<span class="subpill">${esc(e.sub)}</span>` : ""}
498
- </div>
499
- ${bodyBlock(e.body)}
500
- </div>
501
- </div>`;
502
- }
503
- function liveEntry(mode, msg, idx) {
504
- const fromId = msg.from?.id;
505
- const target =
506
- mode === "chat"
507
- ? `#${msg.channel ?? ""}`
508
- : mode === "unicast"
509
- ? `→ ${displayNameOf(msg.to, idx)}`
510
- : `→ @${msg.toService ?? ""}`;
511
- return {
512
- type: "msg",
513
- mode,
514
- ts: time(msg.ts),
515
- // who/role come from the roster by authenticated id; the payload's from.name/from.role are
516
- // sender-chosen display text and are never rendered (#1399).
517
- who: fromId ? displayNameOf(fromId, idx) : "?",
518
- role: fromId ? roleOf(fromId) : undefined,
519
- target,
520
- body: bodyText(msg),
521
- };
522
- }
523
-
524
- function renderAllActivity() {
525
- const center = $("center");
526
- const prev = center.querySelector(".feed");
527
- const atBottom = prev ? prev.scrollHeight - prev.scrollTop - prev.clientHeight < 40 : true;
528
- const idx = nameIndex();
529
- const rows = (isDemo ? DEMO.activity : activity.map((e) => liveEntry(e.mode, e.msg, idx))).filter(
530
- (e) => !e.mode || modes.has(e.mode),
531
- );
532
- const sub = isDemo ? "112 recent · live" : `${rows.length} recent · live`;
533
- center.innerHTML = `
534
- <div class="feed-head">
535
- <span class="h">✸ All activity</span>
536
- <span class="sub">${esc(sub)}</span>
537
- <span class="ctrls">
538
- ${toggleAllChip(rows)}
539
- ${MODES.map((m) => `<span class="chip mode${modes.has(m) ? " on" : ""}" data-mode="${m}">${m}</span>`).join("")}
540
- <span class="chip pause${paused ? " on" : ""}" id="pause">${paused ? "▶ resume" : "⏸ pause"}</span>
541
- </span>
542
- </div>
543
- ${orderNoticeHtml()}
544
- <div class="feed">${rows.length ? rows.map(rowHTML).join("") : `<div class="empty">waiting for messages…</div>`}</div>`;
545
- for (const chip of center.querySelectorAll(".chip[data-mode]"))
546
- chip.onclick = () => {
547
- const m = chip.dataset.mode;
548
- modes.has(m) ? modes.delete(m) : modes.add(m);
549
- renderAllActivity();
550
- };
551
- const pause = center.querySelector("#pause");
552
- if (pause) pause.onclick = () => ((paused = !paused), renderAllActivity());
553
- bindToggleAll(center);
554
- bindBodyToggles(center);
555
- const feed = center.querySelector(".feed");
556
- if (atBottom && !paused) feed.scrollTop = feed.scrollHeight;
557
- }
558
-
559
- // ── Channel view (centre; members fold into the header) ───────────────────────
560
- function cmsgHTML(m) {
561
- if (m.type === "unread")
562
- return `<div class="unread-mark"><span class="line"></span><span class="t">${esc(m.text)}</span><span class="line"></span></div>`;
563
- return `<div class="cmsg">
564
- <span class="ts">${esc(m.ts)}</span>
565
- <span class="dot ${m.status}">${GLYPH[m.status] ?? "●"}</span>
566
- <div class="c">
567
- <div class="l1"><span class="who">${esc(m.who)}</span>${m.role ? `<span class="role">${esc(m.role)}</span>` : ""}</div>
568
- ${bodyBlock(m.body)}
569
- ${m.thread ? `<span class="thread">${esc(m.thread)}</span>` : ""}
570
- </div>
571
- </div>`;
572
- }
573
- function channelMembers(msgs) {
574
- const seen = new Map();
575
- for (const msg of msgs) {
576
- const id = msg.from?.id;
577
- if (!id || seen.has(id)) continue;
578
- seen.set(id, { name: msg.from?.name ?? "?", role: msg.from?.role, status: rosterStatus(id) });
579
- }
580
- return [...seen.values()];
581
- }
582
- function renderChannel() {
583
- const name = selected;
584
- const meta = channels.get(name) || {};
585
- let items, memberCount, msgCount, desc;
586
- if (isDemo) {
587
- items = DEMO.cv.messages;
588
- memberCount = DEMO.cv.members.length;
589
- msgCount = meta.messages ?? 51;
590
- desc = name === "team.backend" ? "Backend coordination — channels, endpoint, NATS." : meta.description || "";
591
- } else {
592
- items = channelMsgs.map((msg) => ({
593
- ts: time(msg.ts),
594
- status: rosterStatus(msg.from?.id),
595
- who: msg.from?.name ?? "?",
596
- role: msg.from?.role,
597
- body: bodyText(msg),
598
- }));
599
- memberCount = channelMembers(channelMsgs).length;
600
- msgCount = meta.messages ?? items.length;
601
- desc = meta.description || "";
602
- }
603
- // Effective policy chips from /api/channels (server-resolved; never re-derived in the browser).
604
- const policy = [];
605
- if (meta.deliveryClass) policy.push(`<span class="chip policy" title="effective delivery class">${esc(meta.deliveryClass)}</span>`);
606
- if (meta.replay === false) policy.push(`<span class="chip policy" title="join does not backfill history">replay off</span>`);
607
- else if (meta.replay === true)
608
- policy.push(`<span class="chip policy" title="join backfills retained history">${meta.replayWindow ? `replay ${esc(meta.replayWindow)}` : "replay on"}</span>`);
609
- const sub = name.includes(".") ? `subtree of ${name.split(".")[0]}.>` : "";
610
- const purpose = [desc, `${plural(memberCount, "member")}`, `${plural(msgCount, "message")}`]
611
- .filter(Boolean)
612
- .map((b) => esc(String(b)))
613
- .join(" · ");
614
- $("center").innerHTML = `
615
- <div class="ch-head">
616
- <div class="row">
617
- <div class="title"><span class="h"># ${esc(name)}</span>${sub ? `<span class="sub">${esc(sub)}</span>` : ""}</div>
618
- <div class="ctrls">
619
- ${toggleAllChip(items)}
620
- <span class="chip mode on">👥 ${plural(memberCount, "member")}</span>
621
- ${policy.join("")}
622
- ${isDemo ? `<span class="chip static" title="demo only">✦ summarize</span><span class="chip static" title="demo only">🔕 mute</span>` : ""}
623
- ${isDemo || !channelDeleteSupported ? "" : `<span class="chip danger" id="ch-del" title="Delete this channel and all its messages">🗑 delete</span>`}
624
- </div>
625
- </div>
626
- <div class="purpose">${purpose}</div>
627
- </div>
628
- ${orderNoticeHtml()}
629
- <div class="clist">${items.length ? items.map(cmsgHTML).join("") : `<div class="empty">no messages</div>`}</div>`;
630
- const list = $("center").querySelector(".clist");
631
- list.scrollTop = list.scrollHeight;
632
- bindToggleAll($("center"));
633
- bindBodyToggles($("center"));
634
- const del = $("center").querySelector("#ch-del");
635
- if (del) del.onclick = () => deleteChannel(name);
636
- }
637
-
638
- // Delete the channel and its content (steward action). Confirm first — purging the chat
639
- // stream is irreversible. On success the channel drops from the sidebar and the view falls
640
- // back to all-activity; a stray live message would recreate it (deletion clears, not bans).
641
- async function deleteChannel(name) {
642
- if (!channelDeleteSupported || !name || name === "*") return;
643
- if (!confirm(`Delete #${name} and all its messages?\n\nThis purges the channel's history and cannot be undone.`)) return;
644
- try {
645
- const r = await fetch("/api/channel/delete", {
646
- method: "POST",
647
- headers: { "content-type": "application/json" },
648
- body: JSON.stringify({ channel: name }),
649
- });
650
- if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || `HTTP ${r.status}`);
651
- channels.delete(name);
652
- unread.delete(name);
653
- activity = activity.filter((e) => e.msg.channel !== name); // drop its rows from all-activity
654
- select("*");
655
- } catch (e) {
656
- alert(`Couldn't delete #${name}: ${e.message}`);
657
- }
658
- }
659
-
660
- // ── Direct-messages thread (centre) ───────────────────────────────────────────
661
- function dmMsgHTML(m, peer, peerName, withName) {
662
- const to = m.who === peer ? withName : peerName;
663
- return `<div class="cmsg">
664
- <span class="ts">${esc(m.ts)}</span>
665
- <span class="dot ${m.status}">${GLYPH[m.status] ?? "●"}</span>
666
- <div class="c">
667
- <div class="l1"><span class="who">${esc(m.whoName ?? m.who)}</span><span class="dir">→ ${esc(to)}</span></div>
668
- <div class="body md">${MD.render(m.body)}</div>
669
- </div>
670
- </div>`;
671
- }
672
- function renderDMThread() {
673
- const peer = dmSel.peer;
674
- const pe = dmPeers().find((p) => p.id === peer);
675
- const conv = pe && (pe.conversations.find((c) => c.with === dmSel.with) || pe.conversations[0]);
676
- const peerName = pe?.name ?? displayNameOf(peer, nameIndex());
677
- const withName = conv?.withName ?? displayNameOf(dmSel.with, nameIndex());
678
- const msgs = conv ? conv.msgs : []; // display-ready (ts, who, status, body) for demo + live
679
- $("center").innerHTML = `
680
- <div class="ch-head">
681
- <div class="row">
682
- <div class="title"><span class="h">${esc(peerName)} ↔ ${esc(withName)}</span><span class="dtag">direct</span></div>
683
- <div class="ctrls"></div>
684
- </div>
685
- <div class="purpose">unicast · private to the two of them · ${plural(msgs.length, "message")}</div>
686
- </div>
687
- <div class="clist">${msgs.length ? msgs.map((m) => dmMsgHTML(m, peer, peerName, withName)).join("") : `<div class="empty">no messages</div>`}</div>`;
688
- const list = $("center").querySelector(".clist");
689
- list.scrollTop = list.scrollHeight;
690
- }
691
-
692
- // ── NEEDS YOU rail (always on the right) ──────────────────────────────────────
693
- function cardHTML(c) {
694
- const nav = c.id ? ` nav${c.id === agentSel ? " sel" : ""}` : "";
695
- return `<div class="card tone-${c.tone}${nav}"${c.id ? ` data-agent="${esc(c.id)}"` : ""}>
696
- <div class="top">
697
- <div class="cat-l"><span class="cdot"></span><span class="cat">${esc(c.cat)}</span></div>
698
- <span class="age">${esc(c.age)}</span>
699
- </div>
700
- <div class="title">${esc(c.title)}${c.role ? `<span class="crole">${esc(c.role)}</span>` : ""}</div>
701
- <div class="desc">${esc(c.desc)}</div>
702
- ${c.facts ? `<div class="presence-facts">${esc(c.facts)}</div>` : ""}
703
- ${c.primary ? `<div class="btns"><span class="btn primary">${esc(c.primary)}</span>${c.secondary ? `<span class="btn secondary">${esc(c.secondary)}</span>` : ""}</div>` : ""}
704
- </div>`;
705
- }
706
- function waitingCards() {
707
- // Sort by name (stable, honest) — p.ts is last heartbeat, not time-entered-waiting, so we
708
- // must not present heartbeat order as an age-ordered priority queue.
709
- return roster
710
- .filter((p) => p.status === "waiting")
711
- .sort(
712
- (a, b) =>
713
- a.card.name.localeCompare(b.card.name) || a.card.id.localeCompare(b.card.id),
714
- )
715
- .map((p) => ({
716
- tone: "amber",
717
- cat: "WAITING",
718
- age: `seen ${ago(p.ts)}`, // Presence.ts = last heartbeat, not blocked-duration
719
- title: `${p.card.name} is waiting`,
720
- role: p.card.role,
721
- // p.activity is the Claude Code Notification text (the actual blocking prompt/permission).
722
- desc: p.activity || "waiting for input",
723
- facts: presenceFacts(p),
724
- id: p.card.id, // makes the card a clickable drill-down into the Agent Detail view
725
- }));
726
- }
727
- function renderRail() {
728
- const cards = isDemo ? DEMO.cards : waitingCards();
729
- const main = $("main");
730
- const rail = $("rail");
731
- // Always-present lane, not always full width: collapse to a strip when nothing needs a human.
732
- if (!cards.length) {
733
- main.classList.add("rail-thin");
734
- rail.className = "rail collapsed";
735
- rail.innerHTML = `<div class="rail-collapsed" title="nothing waiting">NEEDS YOU · all clear</div>`;
736
- return;
737
- }
738
- main.classList.remove("rail-thin");
739
- rail.className = "rail";
740
- rail.innerHTML =
741
- `<div class="rail-head"><span class="t">NEEDS YOU</span><span class="n">${cards.length}</span></div>` +
742
- cards.map(cardHTML).join("") +
743
- `<div class="rail-foot">Everything else stays quiet in the feed.</div>`;
744
- for (const el of rail.querySelectorAll(".card[data-agent]"))
745
- el.onclick = () => selectAgent(el.dataset.agent);
746
- }
747
-
748
- // ── Agent Detail drill-down (centre) — per-agent frame, rendered from the peer's card (docs/watch-a-mesh.mdx) ──
749
- function selectAgent(id) {
750
- agentSel = id;
751
- dmSel = null;
752
- selected = null;
753
- renderSidebarNav();
754
- renderRoster(rosterRows()); // light up the clicked peer (only reached live — demo rows have no id)
755
- renderCenter();
756
- renderRail();
757
- }
758
- function renderAgentDetail() {
759
- const p = roster.find((x) => x.card.id === agentSel);
760
- if (!p) {
761
- $("center").innerHTML = `<div class="detail"><div class="empty">agent no longer present — pick another from the roster or NEEDS YOU.</div></div>`;
762
- return;
763
- }
764
- // The AgentCard is the legibility contract: who, in what role, what it can do, on what harness.
765
- // Render only fields the card actually carries (skills/protocolVersion aren't populated yet).
766
- const card = p.card;
767
- const meta = card.meta || {};
768
- const waiting = p.status === "waiting";
769
- const who = card.role ? `${esc(card.name)}<span class="crole">${esc(card.role)}</span>` : esc(card.name);
770
- // p.ts is last heartbeat (Presence.ts), not work progress or status-entered-at.
771
- const progress = p.status === "working" && p.progress?.kind === "unknown" ? "working · progress unknown" : p.status;
772
- const since = `${esc(progress)} · heartbeat ${esc(ago(p.ts))} ago`;
773
-
774
- // Model when known; harness agent with no model → "not reported"; no harness and no model → nothing.
775
- const modelBadge = meta.model
776
- ? `<span class="d-badge model" title="model">${esc(meta.model)}${meta.variant ? `<span class="var"> · ${esc(meta.variant)}</span>` : ""}</span>`
777
- : meta.connector
778
- ? `<span class="d-badge model muted" title="host did not report a model">not reported</span>`
779
- : "";
780
- const badges = [
781
- card.kind ? `<span class="d-badge">${esc(card.kind)}</span>` : "",
782
- harnessBadge(meta.connector),
783
- modelBadge,
784
- attentionChip(p.attention), // open/absent → ""
785
- ].join("");
786
- const desc = card.description ? `<div class="d-desc">${esc(card.description)}</div>` : "";
787
- const blocked = waiting
788
- ? `<div class="d-label">Blocked on</div><div class="d-block">${esc(p.activity || "waiting for input")}</div>`
789
- : `<div class="d-label">Activity</div><div class="d-block muted">${esc(p.activity || "no current activity")}</div>`;
790
-
791
- const sec = (label, body) => (body ? `<div class="d-sec"><div class="d-label">${esc(label)}</div>${body}</div>` : "");
792
- const tags = (card.tags || []).length
793
- ? `<div class="d-chips">${card.tags.map((t) => `<span class="d-chip">${esc(t)}</span>`).join("")}</div>`
794
- : "";
795
- const skills = (card.skills || []).length
796
- ? `<div class="d-skills">${card.skills
797
- .map((s) => `<div class="d-skill"><span class="nm">${esc(s.name || s.id)}</span>${s.description ? `<span class="dsc">${esc(s.description)}</span>` : ""}</div>`)
798
- .join("")}</div>`
799
- : "";
800
- // Per-channel attention overrides (quiet/muted). Advisory receive-side presentation, not ACL.
801
- const modeEntries = Object.entries(p.channelModes || {}).sort(([a], [b]) => a.localeCompare(b));
802
- const channelModes = modeEntries.length
803
- ? `<div class="d-chips">${modeEntries
804
- .map(([ch, m]) => `<span class="d-chip mode-${esc(m)}" title="per-channel attention">#${esc(ch)} · ${esc(m)}</span>`)
805
- .join("")}</div>`
806
- : "";
807
- // Any other meta beyond the badges (connector/model/variant already first-class), generically rendered.
808
- const extra = Object.entries(meta)
809
- .filter(([k]) => k !== "connector" && k !== "model" && k !== "variant")
810
- .sort(([a], [b]) => a.localeCompare(b));
811
- const metaKv = extra.length
812
- ? `<div class="d-kv">${extra
813
- .map(([k, v]) => `<div class="row"><span class="k">${esc(k)}</span><span class="v">${esc(typeof v === "string" ? v : JSON.stringify(v))}</span></div>`)
814
- .join("")}</div>`
815
- : "";
816
- const proto = card.protocolVersion ? `<span class="d-foot-item">protocol ${esc(card.protocolVersion)}</span>` : "";
817
-
818
- $("center").innerHTML = `
819
- <div class="detail${waiting ? " amber" : ""}">
820
- <div class="d-head">
821
- <span class="dot ${p.status}">${GLYPH[p.status] ?? "●"}</span>
822
- <span class="d-status">${esc(waiting ? "WAITING" : p.status)}</span>
823
- <span class="d-age">${since}</span>
824
- </div>
825
- <div class="d-who">${who}</div>
826
- ${badges ? `<div class="d-badges">${badges}</div>` : ""}
827
- ${desc}
828
- ${presenceFacts(p) ? `<div class="presence-facts">${esc(presenceFacts(p))}</div>` : ""}
829
- ${blocked}
830
- ${sec("Channel attention", channelModes)}
831
- ${sec("Tags", tags)}
832
- ${sec("Skills", skills)}
833
- ${sec("Metadata", metaKv)}
834
- <div class="d-foot"><span class="d-foot-item id">${esc(card.id)}</span>${proto}</div>
835
- </div>`;
836
- }
837
-
838
- // ── View dispatch ─────────────────────────────────────────────────────────────
839
- function renderCenter() {
840
- if (agentSel) return renderAgentDetail();
841
- if (dmSel) return renderDMThread();
842
- if (selected === "*") return renderAllActivity();
843
- return renderChannel();
844
- }
845
-
846
- function refreshDerived() {
847
- const counts = { working: 0, waiting: 0, idle: 0, offline: 0 };
848
- for (const p of roster) counts[p.status] = (counts[p.status] ?? 0) + 1;
849
- // Stalest heartbeat among LIVE peers only — offline ages grow forever and are pure noise in a
850
- // golden-signal slot. Among live peers this catches a lapsed heartbeat before the offline flip.
851
- const live = roster.filter((p) => p.status !== "offline" && typeof p.ts === "number");
852
- const stalest = live.length ? agoShort(Math.min(...live.map((p) => p.ts))) : "—";
853
- renderTiles(counts, stalest);
854
- $("online-c").textContent = roster.filter((p) => p.status !== "offline").length;
855
- renderRoster(rosterRows()); // online list; offline peers drop out but still ride the header tiles
856
- renderDMs(); // peer statuses may have changed
857
- renderRail();
858
- if (agentSel) renderCenter(); // keep an open Agent Detail live as the peer's status/activity changes
859
- }
860
-
861
- let loadSeq = 0;
862
- /** The channel `channelMsgs` currently holds, so a refused re-read of THE SAME channel can keep what
863
- * is on screen. `selected` cannot answer this: `select()` assigns it before the clear below, so by
864
- * then it already names the channel being opened rather than the one being displayed. Without this,
865
- * retention would show the previous channel's messages under the new channel's name, which is worse
866
- * than an empty view. */
867
- let shownChannel = null;
868
- /** The in-flight channel bootstrap: `{key, promise}`, so a second call for the same channel shares it. */
869
- let selecting = null;
870
- async function select(key) {
871
- agentSel = null;
872
- dmSel = null;
873
- selected = key;
874
- if (key !== "*") unread.set(key, 0);
875
- renderSidebarNav();
876
- if (!isDemo) renderRoster(rosterRows()); // clear any stale Agent Detail highlight
877
- if (isDemo) return (renderCenter(), renderRail());
878
- if (key !== "*") {
879
- // SINGLE FLIGHT PER CHANNEL, for the reason the feed has one. `refresh()` calls `select(selected)`
880
- // on every poll, so two bootstraps for the SAME open channel overlapped routinely: the second
881
- // re-armed `channelOrder` while the first was still fetching, and the first machine, holding every
882
- // frame that arrived in that window, became unreachable. The staleness guard did not save it,
883
- // because returning early is exactly what left the buffer undrained.
884
- if (selecting && selecting.key === key) return selecting.promise;
885
- const seq = ++loadSeq;
886
- // HELD BEFORE THE CLEAR, and only when it belongs to THIS channel. A fresh selection must not
887
- // inherit the last channel's messages, so a switch holds nothing and starts empty as before.
888
- const held = shownChannel === key ? channelMsgs : [];
889
- channelMsgs = [];
890
- // ARMED BEFORE THE FETCH IS ISSUED, which is the whole ordering. Re-armed on every selection
891
- // because each one is a fresh two-phase bootstrap: a new history read, and a live tap that is
892
- // already delivering into it. Held in a LOCAL as well, so this bootstrap settles the machine it
893
- // armed even if a selection of a different channel has since rebound the global.
894
- const order = window.COTAL_EVENT_ORDER.create();
895
- channelOrder = order;
896
- let release;
897
- selecting = { key, promise: new Promise((r) => (release = r)) };
898
- renderCenter();
899
- // Same reason as the activity feed: a failed history read must not leave the boundary unpassed
900
- // and the frames of this channel held out of the view that was opened to look at them. On a
901
- // refused poll of the open channel, the batch is the last history that was actually read, so
902
- // what is on screen is kept instead of emptied.
903
- let msgs = [];
904
- let refused = null;
905
- try {
906
- // READ THROUGH THE SAME GATE AS EVERY OTHER SOURCE. A 500 here answers `{"error":"..."}`,
907
- // which is valid JSON that `fetch` does not reject; reading through `readJson` turns a
908
- // non-200 into a throw so the refusal reaches the catch below instead of being handed to the
909
- // order machine as a history.
910
- msgs = await window.COTAL_SNAPSHOT.readJson(
911
- await fetch(`/api/channels/${encodeURIComponent(key)}/history?limit=200`),
912
- `#${key} history`,
913
- );
914
- } catch (err) {
915
- // A REFUSED READ KEEPS WHAT THE READER ALREADY HAD, for the same reason the four polled
916
- // sources do. `refresh()` re-selects the open channel on EVERY poll, so the held messages
917
- // take the place of the history that could not be read, keeping the merge and the ordering
918
- // below identical to the successful path instead of emptying the open channel on each missed
919
- // poll.
920
- refused = err && err.message ? err.message : String(err);
921
- msgs = held;
922
- noteOrder([{ type: "backfill-failed", channel: key, reason: refused }]);
923
- } finally {
924
- // SETTLED ON EVERY PATH, INCLUDING THE STALE ONE. A superseded load must not rebind the view it
925
- // no longer owns, and it must still drain the machine it armed; skipping the settle is what
926
- // orphaned frames. When the selection has moved on, the released rows are dropped with the rest
927
- // of that view, which is correct because the reader is no longer looking at that channel.
928
- const settled = order.backfill(msgs);
929
- if (seq === loadSeq) {
930
- noteOrder(settled.notes);
931
- // Same merge as the activity feed and for the same reason: chat that arrived live during this
932
- // fetch is only in `channelMsgs`, released frames are only in `settled.emit`, and an assignment
933
- // either way round drops one of them.
934
- const merged = settled.emit.slice();
935
- const ids = new Set(merged.map((m) => m && m.id));
936
- for (const m of channelMsgs) if (m && !ids.has(m.id)) merged.push(m);
937
- channelMsgs = merged.slice(-500);
938
- shownChannel = key;
939
- // SAID, NOT JUST KEPT. Retention without the mark shows old messages as though they were
940
- // current, which is the half of this rule that turns a silent wipe into a silent lie. Marked
941
- // per source: a refused history does not erase the poll's other marks, and a read that lands
942
- // clears this one without touching theirs.
943
- markStale(`#${key} history`, refused ? { kind: "refused", name: `#${key} history`, reason: refused } : null);
944
- }
945
- if (selecting && selecting.key === key) selecting = null;
946
- release();
947
- }
948
- }
949
- renderCenter();
950
- renderRail();
951
- }
952
- function selectDM(peer, w) {
953
- agentSel = null;
954
- const pe = dmPeers().find((p) => p.id === peer);
955
- dmSel = { peer, with: w || (pe && pe.conversations[0] ? pe.conversations[0].with : null) };
956
- selected = null;
957
- renderSidebarNav();
958
- if (!isDemo) renderRoster(rosterRows()); // clear any stale Agent Detail highlight
959
- renderCenter();
960
- renderRail();
961
- }
962
-
963
- async function refresh() {
964
- // ── ONE BOOTSTRAP AT A TIME, AND IT ALWAYS ENDS ─────────────────────────────────────────────────
965
- //
966
- // SINGLE FLIGHT. Arming a machine and settling it are two ends of ONE bootstrap. The file ends
967
- // with `refresh(); connect();`, and `connect()`'s open handler calls `refresh()` again (as does a
968
- // reconnect), so overlapping callers share the in-flight bootstrap instead of starting a rival one:
969
- // a second call that re-armed `feedOrder` while the first was still fetching would run its settle
970
- // on the new binding and leave the frames held on the first machine unreachable. A concurrent
971
- // duplicate would fetch the same pages anyway, so nothing is lost by coalescing.
972
- if (refreshing) return refreshing;
973
- let release;
974
- refreshing = new Promise((r) => (release = r));
975
- // Captured before the first await: `onMessage` appends here while every request below is in flight,
976
- // and the settle rebinds `activity`.
977
- const live = activity;
978
- feedOrder = window.COTAL_EVENT_ORDER.create();
979
- // The batch the settle will use. Only the all-activity path fills it; every other path settles on
980
- // empty, which is the machine's specified empty-history arm rather than a shortcut.
981
- let batch = [];
982
- let activityPage = null;
983
- try {
984
- // ── A FAILED READ KEEPS WHAT IS ON SCREEN ─────────────────────────────────────────────────────
985
- //
986
- // A 500 body is valid JSON and `fetch` does not reject on one, so a bare `(await fetch(u)).json()`
987
- // chain would store a refusal into `roster` / `channels` / `dms` as if it were the snapshot, and
988
- // the first read that threw would skip every read after it. `refreshAll` reads all four
989
- // concurrently through `readJson`, applies ONLY the ones that succeeded, and returns what did not
990
- // land. `apply` is the only writer, so a refusal cannot reach page state at all.
991
- const SNAP = window.COTAL_SNAPSHOT;
992
- // The all-activity backfill is a source ONLY when the reader is on all-activity. The other three
993
- // lenses settle the order machine on an empty batch, its specified empty-history arm, instead of
994
- // asking for a page nobody will draw.
995
- const onAllActivity = !agentSel && !dmSel && selected === "*";
996
- const stale = await SNAP.refreshAll([
997
- // The space name is a polled source like the rest, so it is gated on status, named when it is
998
- // stale, and replaced by the next poll that lands; a one-shot boot read with a bare
999
- // `fetch().then((r) => r.json())` would accept a refusal as data and leave the header reading
1000
- // `· undefined` for the rest of the session. `/api/meta` is `{space, pid}` computed in process,
1001
- // so reading it every poll costs no broker work.
1002
- {
1003
- name: "space",
1004
- read: async () => SNAP.readJson(await fetch("/api/meta"), "space"),
1005
- apply: (meta) => { channelDeleteSupported = meta.channelDeleteSupported === true; $("space").textContent = `· ${meta.space}${channelDeleteSupported ? "" : " · read-only"}`; document.title = `Cotal · ${meta.space}`; },
1006
- },
1007
- {
1008
- name: "peers",
1009
- read: async () => SNAP.readJson(await fetch("/api/roster"), "peers"),
1010
- apply: (v) => { roster = v; refreshDerived(); },
1011
- },
1012
- {
1013
- name: "channels",
1014
- read: async () => SNAP.readJson(await fetch("/api/channels"), "channels"),
1015
- // L2 shape is flat {channel,messages,description?,replay,replayWindow?,deliveryClass}.
1016
- // Tolerate a nested-config server briefly (pre-restart) without re-deriving defaults.
1017
- apply: (list) => {
1018
- channels = new Map(
1019
- list.map((c) => {
1020
- if (c.replay !== undefined || c.deliveryClass !== undefined || (c.description && !c.config))
1021
- return [c.channel, c];
1022
- const cfg = c.config || {};
1023
- return [
1024
- c.channel,
1025
- {
1026
- messages: c.messages,
1027
- description: cfg.description,
1028
- replay: cfg.replay,
1029
- replayWindow: cfg.replayWindow,
1030
- deliveryClass: cfg.deliveryClass,
1031
- },
1032
- ];
1033
- }),
1034
- );
1035
- },
1036
- },
1037
- {
1038
- name: "direct messages",
1039
- read: async () => SNAP.readJson(await fetch("/api/dms?limit=500"), "direct messages"),
1040
- apply: (v) => { dms = v; },
1041
- },
1042
- // Read alongside the other three rather than after them, so a refusal on it is reported in the
1043
- // same place instead of being swallowed, and so it does not wait for them on a slow link.
1044
- //
1045
- // `/api/activity` answers an ENVELOPE, never a bare array, so a caller that ignores `partial`
1046
- // breaks here instead of rendering a short page as a complete one. NO TOLERANCE FOR A BARE
1047
- // ARRAY either, and that is not pedantry: `[].entries` is a real Array METHOD, so a
1048
- // `page.entries ?? page` tolerance quietly hands a FUNCTION to the merge when the answer is a
1049
- // list. It is read one way.
1050
- ...(onAllActivity
1051
- ? [{
1052
- name: "activity",
1053
- read: async () => SNAP.readJson(await fetch(`/api/activity?limit=200`), "activity"),
1054
- apply: (page) => { batch = page.entries; activityPage = page; },
1055
- }]
1056
- : []),
1057
- ]);
1058
- // A PARTIAL PAGE IS NOT A REFUSAL AND IS NOT SILENCE. The entries it carries are real and are
1059
- // applied; what the reader is told is that some sources did not answer in time, which sources,
1060
- // and how many did. Reported on the same marker as a refusal so there is one place to look.
1061
- if (activityPage && activityPage.partial)
1062
- stale.push({
1063
- kind: "partial",
1064
- name: "activity",
1065
- reason: `${activityPage.read} of ${activityPage.of} sources answered within ${activityPage.deadlineMs}ms; missing ${activityPage.missing.map((m) => `${m} (${activityPage.reasons[m]})`).join(", ")}`,
1066
- });
1067
- const rosterView = staleNow.find((s) => s.name === "roster");
1068
- if (rosterView && !stale.some((s) => s.name === "roster")) stale.push(rosterView);
1069
- setStale(stale);
1070
- // The order machine's own failure arm keeps its own note: a refused history read is what makes a
1071
- // backfill incomplete, and the notice that draws it is about ordering. The other three sources
1072
- // are carried by the stale pill and are not backfill failures, so they are not reported as ones.
1073
- const backfillRefused = stale.find((s) => s.name === "activity" && s.kind !== "partial");
1074
- if (backfillRefused) noteOrder([{ type: "backfill-failed", reason: backfillRefused.reason }]);
1075
- renderSidebarNav();
1076
- // THE BOUNDARY MUST PASS EVEN WHEN THE FETCH DOES NOT. `pending` is drained only by the settle;
1077
- // an unsettled machine holds every frame that arrived during the fetch invisible for the life of
1078
- // the page, with nothing on screen saying so.
1079
- //
1080
- // A failed history read IS an empty history batch: the machine already specifies that case, and
1081
- // specifies that the baseline then comes from the earliest BUFFERED frame. So the boundary is
1082
- // settled on empty rather than skipped, and the refusal is SURFACED (as a stale mark above and a
1083
- // note here) instead of being swallowed. Reporting it is what keeps this from being a silent degrade.
1084
- if (agentSel || dmSel) {
1085
- renderCenter();
1086
- } else if (selected !== "*") {
1087
- select(selected);
1088
- }
1089
- } finally {
1090
- // ── THE SETTLE, ON EVERY EXIT PATH ────────────────────────────────────────────────────────────
1091
- //
1092
- // The arm runs unconditionally at the top, so the settle must run across all four branches as
1093
- // well: settling only on the all-activity branch would leave every live frame that arrived while
1094
- // the reader was on a channel, a DM or an agent held in an unsettled machine until the next
1095
- // refresh replaced it and discarded its buffer. A `finally` is the only placement that survives
1096
- // all four branches plus a throw from anything between the arm and here; the source reads report
1097
- // a refusal rather than throwing, while the renders below the reads still can.
1098
- activity = batch;
1099
- // Same trust rule as the live feed: the backfill is tagged with the channel the SERVER
1100
- // requested, so the payload claim is overwritten at ingress rather than downstream.
1101
- for (const e of activity) if (e?.msg) e.msg.channel = e.channel;
1102
- // MERGED, NOT ASSIGNED OVER. Assigning the fetched page over `activity` would discard every live
1103
- // entry `onMessage` appended while the fetch was in flight. Event channels are excluded from
1104
- // `/api/activity` by the server's filter, so a live frame overwritten during the fetch is not in
1105
- // the backfill and would be lost rather than re-read from the broker.
1106
- const settled = feedOrder.backfill(activity);
1107
- noteOrder(settled.notes);
1108
- // Live frames were HELD by the machine and come back inside `settled.emit` in seq order; live
1109
- // chat passed straight through and is only in `live`. Both have to survive, so the backfill is
1110
- // the BASE and unseen live arrivals are appended after it, newest last, deduped by id against
1111
- // what the backfill already carried.
1112
- //
1113
- // WHAT THIS ORDER DOES AND DOES NOT CLAIM. Frames of one chain are exactly ordered, by `seq`,
1114
- // which is the claim this file exists to make. Where a released frame sits relative to a chat
1115
- // message that arrived during the same fetch is approximate. It is deliberately not fixed by
1116
- // sorting the merged rows on `ts`: a producer's clock is not its sequence, so two frames whose
1117
- // timestamps disagree with their sequence numbers would be swapped back by that sort, trading the
1118
- // guarantee for the cosmetic.
1119
- const merged = settled.emit.slice();
1120
- const ids = new Set(merged.map((e) => e && e.msg && e.msg.id));
1121
- for (const e of live) if (e && e.msg && !ids.has(e.msg.id)) merged.push(e);
1122
- activity = merged.slice(-500);
1123
- renderCenter();
1124
- refreshing = null;
1125
- release();
1126
- }
1127
- }
1128
-
1129
- function onMessage(entry) {
1130
- const { mode, msg } = entry;
1131
- // TRUST IS DECIDED ONCE, HERE. The server sends the channel it took from the SUBJECT (a publish
1132
- // grant is per-channel, so that token is covered by the minted grant); `msg.channel` is the
1133
- // publisher's own claim and is backed by nothing. Overwrite the claim at this boundary so no
1134
- // downstream reader — the channel list, the counts, the unread badges, the transcript — has to
1135
- // know which of the two it is holding.
1136
- //
1137
- // THE ASSIGNMENT IS UNCONDITIONAL, AND THAT IS THE WHOLE FIX. This first read
1138
- // `if (entry.channel) msg.channel = entry.channel;`, which FAILS OPEN: on `inst` and `svc` there
1139
- // is no authoritative channel, so the guard was false and the publisher's claim SURVIVED. `tap()`
1140
- // only JSON-decodes, so a DM or anycast payload can carry any `channel` string it likes — and
1141
- // `msg.channel` is consumed below with NO MODE GATE, which filed that message into the named
1142
- // channel's transcript and incremented its count. A sender could appear to post into a channel it
1143
- // holds no publish grant for. Assigning unconditionally leaves a non-chat message with
1144
- // `undefined`, which is the truth: it has no channel.
1145
- //
1146
- // A conditional trust rule is not a trust rule. "Overwrite when I have something better" leaves
1147
- // the untrusted value in place exactly when the trusted one is missing.
1148
- msg.channel = entry.channel;
1149
- // ORDERED, NOT JUST DEDUPED. Message-id dedupe answers "have I seen this exact message"; it cannot
1150
- // answer "is a frame missing between these two", because the thing that would say so is `seq`. A
1151
- // frame arriving before the backfill it belongs after is HELD here and released by `backfill()` in
1152
- // `seq` order; everything else passes through and is deduped by id exactly as before.
1153
- const fed = feedOrder.live(entry);
1154
- noteOrder(fed.notes);
1155
- for (const e of fed.emit) {
1156
- if (activity.some((a) => a.msg.id === e.msg.id)) continue;
1157
- activity.push(e);
1158
- if (activity.length > 500) activity.shift();
1159
- }
1160
- if (mode === "unicast" && !dms.some((m) => m.id === msg.id)) {
1161
- dms.push(msg);
1162
- renderDMs();
1163
- }
1164
- if (msg.channel) {
1165
- // A live message can beat the next channel-registry refresh. Keep its count but leave the
1166
- // effective policy unknown until the server supplies the resolved L2 row.
1167
- const ch = channels.get(msg.channel);
1168
- channels.set(msg.channel, { ...(ch ?? {}), messages: (ch?.messages ?? 0) + 1 });
1169
- if (!dmSel && selected === msg.channel) {
1170
- // The selected-channel view runs the same race: `select()` fetches this channel's history with
1171
- // the feed already open, so a live frame can arrive before the retained range it follows.
1172
- const sel = channelOrder.live(msg);
1173
- noteOrder(sel.notes);
1174
- for (const m of sel.emit) {
1175
- channelMsgs.push(m);
1176
- if (channelMsgs.length > 500) channelMsgs.shift();
1177
- }
1178
- } else {
1179
- unread.set(msg.channel, (unread.get(msg.channel) ?? 0) + 1);
1180
- }
1181
- renderChannels();
1182
- }
1183
- if (dmSel ? mode === "unicast" : selected === "*" || selected === msg.channel) renderCenter();
1184
- }
1185
-
1186
- function connect() {
1187
- const es = new EventSource("/feed");
1188
- es.addEventListener("open", () => {
1189
- setConn(true);
1190
- refresh();
1191
- });
1192
- es.addEventListener("roster", (e) => {
1193
- roster = JSON.parse(e.data);
1194
- refreshDerived();
1195
- });
1196
- es.addEventListener("presence-view", (e) => applyPresenceView(JSON.parse(e.data)));
1197
- es.addEventListener("message", (e) => onMessage(JSON.parse(e.data)));
1198
- es.addEventListener("error", () => setConn(false));
1199
- }
1200
-
1201
- // ── Demo scene (the Penpot reference frames) ──────────────────────────────────
1202
- const ab = [
1203
- { ts: "10:47", who: "alice", status: "waiting", body: "can you take the API-key wiring while I'm blocked?" },
1204
- { ts: "10:48", who: "bob", status: "working", body: "on it — grabbing the OPENAI_API_KEY wiring now" },
1205
- { ts: "10:50", who: "alice", status: "waiting", body: "🙏 thanks — I'll keep drafting the auth outline" },
1206
- ];
1207
- const ad = [
1208
- { ts: "10:42", who: "dave", status: "working", body: "want me to stub the key so you can keep planning?" },
1209
- { ts: "10:43", who: "alice", status: "waiting", body: "yes please — a no-op stub is perfect for now" },
1210
- ];
1211
- const as = [{ ts: "10:40", who: "scout", status: "idle", body: "logged your block in #incidents" }];
1212
- const bd = [
1213
- { ts: "10:09", who: "bob", status: "working", body: "merged your filter-subjects change" },
1214
- { ts: "10:10", who: "dave", status: "working", body: "ty — running the suite now" },
1215
- ];
1216
- const lm = [{ ts: "10:15", who: "maya", status: "idle", body: "sent the NATS v3 notes your way" }];
1217
- const DEMO = {
1218
- roster: [
1219
- { name: "alice", role: "planner", status: "waiting", tag: "needs input", act: "blocked — needs OPENAI_API_KEY", harness: "claude", host: "studio" },
1220
- { name: "linus", role: "reviewer", status: "working", act: "reviewing PR #42 · auth guards", harness: "opencode", host: "build-01" },
1221
- { name: "bob", role: "builder", status: "working", act: "writing tests · channels.ts", harness: "claude", host: "build-01" },
1222
- { name: "dave", role: "builder", status: "working", act: "refactoring endpoint.ts", harness: "hermes", host: "build-01" },
1223
- { name: "maya", role: "researcher", status: "idle", act: "—", harness: "opencode", host: "studio" },
1224
- { name: "scout", role: "observer", status: "idle", act: "watching #team.>", harness: "claude", host: "studio" },
1225
- ],
1226
- activity: [
1227
- { type: "sys", text: "— scout joined · observer —" },
1228
- { type: "msg", mode: "chat", ts: "10:38", who: "dave", role: "builder", target: "#general", body: "anyone else hit the flaky CI test on channels.ts?" },
1229
- { type: "rollup", text: "14 status updates · bob, dave, linus, maya" },
1230
- { type: "msg", mode: "chat", ts: "10:41", who: "bob", role: "builder", target: "#team.backend", body: "pushed channels.ts tests — 12 green ✓" },
1231
- { type: "intent", ts: "10:46", who: "linus", note: "about to act", body: "will merge PR #42 once the review check passes" },
1232
- { type: "msg", mode: "unicast", ts: "10:47", who: "alice", role: "planner", target: "→ bob", body: "can you take the API-key wiring while I'm blocked?" },
1233
- { type: "msg", mode: "anycast", ts: "10:49", who: "—", target: "→ @reviewer", sub: "unclaimed · 3m", body: "review needed on PR #51 (channels hierarchy)" },
1234
- { type: "msg", mode: "chat", ts: "10:51", who: "linus", role: "reviewer", target: "#team.review", body: "left 2 comments on PR #42 — small nits" },
1235
- ],
1236
- cards: [
1237
- { tone: "amber", cat: "WAITING", age: "seen 4m", title: "alice is blocked", desc: "Needs OPENAI_API_KEY to keep planning the auth module.", primary: "Provide key", secondary: "Open thread" },
1238
- { tone: "red", cat: "FAILED", age: "seen 1m", title: "bob's task failed", desc: "2 tests failing in channels.ts after the refactor.", primary: "Inspect", secondary: "Retry" },
1239
- { tone: "orange", cat: "UNCLAIMED", age: "seen 3m", title: "Anycast request unhandled", desc: "@reviewer · review PR #51 — no peer has claimed it.", primary: "Assign…", secondary: "Claim" },
1240
- { tone: "blue", cat: "APPROVAL", age: "seen just now", title: "dave requests approval", desc: "Wants to force-push to main — irreversible.", primary: "Approve", secondary: "Deny" },
1241
- ],
1242
- cv: {
1243
- messages: [
1244
- { ts: "09:58", status: "working", who: "bob", role: "builder", body: "scaffolded the hierarchical channel matcher — wildcard subtree works" },
1245
- { ts: "10:05", status: "working", who: "dave", role: "builder", body: "endpoint.ts: collapsed the filter subjects, tests pass", thread: "💬 3 replies · last 2m" },
1246
- { ts: "10:12", status: "idle", who: "maya", role: "researcher", body: "NATS v3 split transports cleanly — notes in #planning" },
1247
- { type: "unread", text: "new since you were away · 4 messages" },
1248
- { ts: "10:39", status: "working", who: "dave", role: "builder", body: "anyone seen the flaky CI test on channels.ts?" },
1249
- { ts: "10:41", status: "working", who: "bob", role: "builder", body: "pushed channels.ts tests — 12 green ✓" },
1250
- { ts: "10:44", status: "waiting", who: "alice", role: "planner", body: "drafted the auth outline; blocked on the API key though" },
1251
- ],
1252
- members: [
1253
- { status: "working", name: "bob", role: "builder" },
1254
- { status: "working", name: "dave", role: "builder" },
1255
- { status: "waiting", name: "alice", role: "planner" },
1256
- { status: "idle", name: "maya", role: "researcher" },
1257
- { status: "idle", name: "scout", role: "observer" },
1258
- ],
1259
- },
1260
- dmPeers: [
1261
- { id: "alice", name: "alice", role: "planner", status: "waiting", unread: 2, threads: 3, conversations: [
1262
- { with: "bob", role: "builder", status: "working", unread: 0, msgs: ab },
1263
- { with: "dave", role: "builder", status: "working", unread: 1, msgs: ad },
1264
- { with: "scout", role: "observer", status: "idle", unread: 1, msgs: as },
1265
- ] },
1266
- { id: "bob", name: "bob", role: "builder", status: "working", unread: 0, threads: 2, conversations: [
1267
- { with: "alice", role: "planner", status: "waiting", unread: 0, msgs: ab },
1268
- { with: "dave", role: "builder", status: "working", unread: 0, msgs: bd },
1269
- ] },
1270
- { id: "dave", name: "dave", role: "builder", status: "working", unread: 1, threads: 2, conversations: [
1271
- { with: "alice", role: "planner", status: "waiting", unread: 1, msgs: ad },
1272
- { with: "bob", role: "builder", status: "working", unread: 0, msgs: bd },
1273
- ] },
1274
- { id: "linus", name: "linus", role: "reviewer", status: "working", unread: 0, threads: 1, conversations: [
1275
- { with: "maya", role: "researcher", status: "idle", unread: 0, msgs: lm },
1276
- ] },
1277
- { id: "maya", name: "maya", role: "researcher", status: "idle", unread: 0, threads: 1, conversations: [
1278
- { with: "linus", role: "reviewer", status: "working", unread: 0, msgs: lm },
1279
- ] },
1280
- ],
1281
- };
1282
-
1283
- function renderDemo() {
1284
- $("space").textContent = "· demo";
1285
- setConn(true);
1286
- renderTiles({ working: 4, waiting: 1, idle: 2, offline: 1 }, "6m");
1287
- $("online-c").textContent = "6";
1288
- renderRoster(DEMO.roster);
1289
- // Counts sum to 112 → the "all activity" total matches the reference.
1290
- channels = new Map([
1291
- ["general", { messages: 24, replay: true, deliveryClass: "durable" }],
1292
- ["planning", { messages: 12, replay: true, deliveryClass: "durable" }],
1293
- ["team.backend", { messages: 51, replay: true, deliveryClass: "durable" }],
1294
- ["team.frontend", { messages: 18, replay: true, deliveryClass: "durable" }],
1295
- ["team.review", { messages: 7, replay: true, deliveryClass: "durable" }],
1296
- ["incidents", { messages: 0, replay: true, deliveryClass: "durable" }],
1297
- ]);
1298
- unread = new Map([["planning", 2], ["team.review", 1]]);
1299
- renderSidebarNav();
1300
- renderCenter();
1301
- renderRail();
1302
- }
1303
-
1304
- // ── Resizable sidebars ─────────────────────────────────────────────────────────
1305
- // Left nav + right rail widths are drag-adjustable and persisted per browser. The centre column is
1306
- // minmax(0,1fr), so it just absorbs the remainder; we only clamp the sides so the centre can't be
1307
- // squeezed away. Double-click a handle to reset that side.
1308
- const SIDES = {
1309
- left: { cssVar: "--nav-w", key: "cotal.navW", def: 300, min: 200, max: 520, other: "right" },
1310
- right: { cssVar: "--rail-w", key: "cotal.railW", def: 340, min: 240, max: 560, other: "left" },
1311
- };
1312
- const sideW = (side) =>
1313
- parseInt(getComputedStyle(document.documentElement).getPropertyValue(SIDES[side].cssVar)) || SIDES[side].def;
1314
- function clampSide(side, px) {
1315
- const s = SIDES[side];
1316
- const hardMax = Math.min(s.max, window.innerWidth - sideW(s.other) - 360); // keep the centre ≥ 360px
1317
- return Math.round(Math.max(s.min, Math.min(Math.max(hardMax, s.min), px)));
1318
- }
1319
- const applySide = (side, px) => document.documentElement.style.setProperty(SIDES[side].cssVar, px + "px");
1320
- function setupResizers() {
1321
- for (const side of Object.keys(SIDES)) {
1322
- const saved = Number(localStorage.getItem(SIDES[side].key));
1323
- if (saved) applySide(side, clampSide(side, saved));
1324
- }
1325
- const bind = (id, side) => {
1326
- const el = $(id);
1327
- if (!el) return;
1328
- el.onpointerdown = (e) => {
1329
- e.preventDefault();
1330
- el.setPointerCapture(e.pointerId);
1331
- el.classList.add("drag");
1332
- const startX = e.clientX, startW = sideW(side);
1333
- const move = (ev) => applySide(side, clampSide(side, side === "left" ? startW + (ev.clientX - startX) : startW - (ev.clientX - startX)));
1334
- const up = () => {
1335
- el.classList.remove("drag");
1336
- el.removeEventListener("pointermove", move);
1337
- el.removeEventListener("pointerup", up);
1338
- localStorage.setItem(SIDES[side].key, String(sideW(side)));
1339
- };
1340
- el.addEventListener("pointermove", move);
1341
- el.addEventListener("pointerup", up);
1342
- };
1343
- el.ondblclick = () => (applySide(side, SIDES[side].def), localStorage.removeItem(SIDES[side].key));
1344
- };
1345
- bind("rz-left", "left");
1346
- bind("rz-right", "right");
1347
- // A shrinking window can leave a side too wide for the new centre floor — re-clamp both.
1348
- window.addEventListener("resize", () => { for (const side of Object.keys(SIDES)) applySide(side, clampSide(side, sideW(side))); });
1349
- }
1350
-
1351
- // ── Resizable nav sections (ONLINE / CHANNELS / DIRECT MESSAGES) ─────────────────
1352
- // Two vertical handles split the three stacked sections. Roster + channels carry explicit heights
1353
- // (persisted per browser); dms takes the remainder. Handle 1 (roster|channels) trades height
1354
- // between those two and leaves dms fixed; handle 2 (channels|dms) grows channels and shrinks the
1355
- // dms remainder. Double-click either handle to reset the split.
1356
- const NAV_MIN = { roster: 90, channels: 110, dms: 90 };
1357
- const NAV_HANDLES = 14; // two 7px handles
1358
- function setupNavResizers() {
1359
- const nav = document.querySelector("aside.nav");
1360
- const rosterSec = $("sec-roster"), channelsSec = $("sec-channels");
1361
- if (!nav || !rosterSec || !channelsSec) return;
1362
- const hOf = (el) => el.getBoundingClientRect().height;
1363
- const setH = (cssVar, px) => document.documentElement.style.setProperty(cssVar, Math.round(px) + "px");
1364
-
1365
- // Handle 1: keep roster+channels sum constant so dms stays put.
1366
- const dragRoster = (dy, r0, c0) => {
1367
- const sum = r0 + c0;
1368
- const roster = Math.max(NAV_MIN.roster, Math.min(sum - NAV_MIN.channels, r0 + dy));
1369
- setH("--roster-h", roster);
1370
- setH("--channels-h", sum - roster);
1371
- };
1372
- // Handle 2: grow channels; the dms remainder shrinks (floored at its min).
1373
- const dragChannels = (dy, c0) => {
1374
- const room = nav.clientHeight - hOf(rosterSec) - NAV_HANDLES - NAV_MIN.dms;
1375
- setH("--channels-h", Math.max(NAV_MIN.channels, Math.min(room, c0 + dy)));
1376
- };
1377
- const persist = () => {
1378
- localStorage.setItem("cotal.rosterH", String(Math.round(hOf(rosterSec))));
1379
- localStorage.setItem("cotal.channelsH", String(Math.round(hOf(channelsSec))));
1380
- };
1381
- const reset = () => {
1382
- document.documentElement.style.removeProperty("--roster-h");
1383
- document.documentElement.style.removeProperty("--channels-h");
1384
- localStorage.removeItem("cotal.rosterH");
1385
- localStorage.removeItem("cotal.channelsH");
1386
- };
1387
- const bind = (id, onDrag, startVals) => {
1388
- const el = $(id);
1389
- if (!el) return;
1390
- el.onpointerdown = (e) => {
1391
- e.preventDefault();
1392
- el.setPointerCapture(e.pointerId);
1393
- el.classList.add("drag");
1394
- const startY = e.clientY, vals = startVals();
1395
- const move = (ev) => onDrag(ev.clientY - startY, ...vals);
1396
- const up = () => {
1397
- el.classList.remove("drag");
1398
- el.removeEventListener("pointermove", move);
1399
- el.removeEventListener("pointerup", up);
1400
- persist();
1401
- };
1402
- el.addEventListener("pointermove", move);
1403
- el.addEventListener("pointerup", up);
1404
- };
1405
- el.ondblclick = reset;
1406
- };
1407
- bind("rz-roster", dragRoster, () => [hOf(rosterSec), hOf(channelsSec)]);
1408
- bind("rz-channels", dragChannels, () => [hOf(channelsSec)]);
1409
-
1410
- // Restore persisted heights (px), clamped to the current nav height.
1411
- const savedR = Number(localStorage.getItem("cotal.rosterH")), savedC = Number(localStorage.getItem("cotal.channelsH"));
1412
- if (savedR || savedC)
1413
- requestAnimationFrame(() => {
1414
- const navH = nav.clientHeight;
1415
- if (savedR) setH("--roster-h", Math.max(NAV_MIN.roster, Math.min(savedR, navH - NAV_MIN.channels - NAV_MIN.dms - NAV_HANDLES)));
1416
- if (savedC) setH("--channels-h", Math.max(NAV_MIN.channels, Math.min(savedC, navH - hOf(rosterSec) - NAV_MIN.dms - NAV_HANDLES)));
1417
- });
1418
- }
1419
-
1420
- setupResizers();
1421
- setupNavResizers();
1422
- if (isDemo) {
1423
- document.title = "Cotal · demo";
1424
- renderDemo();
1425
- } else {
1426
- refresh();
1427
- connect();
1428
- }