| 1 | // chat-stream.js follows the person's event stream (GET /api/v1/events) on |
| 2 | // the conversation page: streamed drafts, committed replies, turn ends, |
| 3 | // cards, the thinking line (activity and an elapsed timer) and the |
| 4 | // runner's offline line. The page works without it; replies then |
| 5 | // appear on reload. Applies an event only if it is newer (cursor, and |
| 6 | // delta offsets), as person API v1 clients must. |
| 7 | // |
| 8 | // A task page's thread ([data-chat-stream][data-task]) uses the same |
| 9 | // pieces for questions to the specialists: a question's answer streams |
| 10 | // as delta and activity events whose resource is "question", under the |
| 11 | // question's id, and the answered question settles into its draft. The |
| 12 | // conversation ignores those; the thread ignores everything else. |
| 13 | (function () { |
| 14 | "use strict"; |
| 15 | var root = document.querySelector("[data-chat-stream]"); |
| 16 | if (!root || !window.EventSource || !window.fetch) return; |
| 17 | // thread is the task whose questions this page follows ("" in the chat); |
| 18 | // asked maps each of its questions to the specialist answering it. |
| 19 | var thread = root.dataset.task || "", asked = {}; |
| 20 | root.querySelectorAll("[data-turn], [data-turn-id]").forEach(function (el) { |
| 21 | var id = el.dataset.turn || el.dataset.turnId; |
| 22 | if (thread && id) asked[id] = asked[id] || ""; |
| 23 | }); |
| 24 | root.setAttribute("data-roster-enhanced", ""); |
| 25 | var feed = root.querySelector("[equipo-feed]"); |
| 26 | root.querySelectorAll("[data-card-form]").forEach(function(f){f.dataset.busy="false";}); |
| 27 | var offline = root.querySelector("[equipo-offline]"); |
| 28 | var form = document.getElementById("composer"); |
| 29 | var cursor = Number(root.dataset.cursor) || 0; |
| 30 | // Delta offsets count UTF-8 bytes, as the runner and the instance do. |
| 31 | var drafts = {}; |
| 32 | var utf8 = new TextEncoder(); |
| 33 | var source = null, failures = 0; |
| 34 | var box = root.querySelector("[equipo-scroll]"); |
| 35 | var composer = document.getElementById("chat-composer"); |
| 36 | // following is true while the reader is at the bottom; new content then |
| 37 | // stays in view above the composer. Reading back up is never yanked. |
| 38 | var following = true, lastSend = 0; |
| 39 | |
| 40 | function template(name) { |
| 41 | return root.querySelector("template[" + name + "]").content.firstElementChild.cloneNode(true); |
| 42 | } |
| 43 | function clearEmpty() { |
| 44 | var empty = feed.querySelector("[data-empty-state]"); |
| 45 | if (empty) empty.remove(); |
| 46 | } |
| 47 | // ── The thinking line ────────────────────────────────────────────── |
| 48 | // Its look is the shared Stardust (stardust.js); switching is the LOOK |
| 49 | // line below. |
| 50 | var STARDUST = window.EquipoStardust.looks; |
| 51 | // handoff: "gone" (the line fades where it sits as the reply's first |
| 52 | // words arrive), "caret" or "dot" (the same, then a thin caret or a |
| 53 | // soft dot ends the streaming text). |
| 54 | var LOOK = { star: window.EquipoStardust.look, handoff: "gone" }; |
| 55 | var still = window.matchMedia ? matchMedia("(prefers-reduced-motion: reduce)") : null; |
| 56 | function moving() { return !(still && still.matches); } |
| 57 | var STAR = window.EquipoStardust.star; |
| 58 | var motes = window.EquipoStardust.motes; |
| 59 | function el(tag, attr) { |
| 60 | var e = document.createElement(tag); |
| 61 | e.setAttribute(attr, ""); |
| 62 | return e; |
| 63 | } |
| 64 | // The visible phrase, letter by letter. keep: letters it shares with |
| 65 | // the phrase before, which stay still. |
| 66 | function letters(text, keep) { |
| 67 | var out = document.createElement("span"), word = 0; |
| 68 | Array.from(text).forEach(function (c, i) { |
| 69 | var s = document.createElement("span"); |
| 70 | s.textContent = c; |
| 71 | if (i < keep) s.setAttribute("data-keep", ""); |
| 72 | else if (/\s/.test(c)) word++; |
| 73 | s.style.setProperty("--n", LOOK.star.step === "word" ? word : Math.max(0, i - keep)); |
| 74 | s.style.setProperty("--j", i); |
| 75 | out.append(s); |
| 76 | }); |
| 77 | return out; |
| 78 | } |
| 79 | // Settings words fill thinking gaps. Tools always show the server's |
| 80 | // plain label, with the same transition and full accessible text. |
| 81 | var WORDS = {}; |
| 82 | try { WORDS = JSON.parse(root.dataset.thinkingWords || "{}"); } catch (_) { WORDS = {}; } |
| 83 | function situationOf(v) { |
| 84 | return !v || v.kind === "thinking" ? "think" : "tool"; |
| 85 | } |
| 86 | function setFor(li) { |
| 87 | var set = root.dataset.thinkingSet || "professional"; |
| 88 | if (set !== "random") return set; |
| 89 | var ids = Object.keys(WORDS).filter(function (k) { return k !== "random" && Object.keys(WORDS[k] || {}).length; }).sort(); |
| 90 | // An optimistic line keeps the seed it started with when its turn |
| 91 | // adopts it, so the words never switch mid-line. |
| 92 | var turn = li.seed || li.dataset.turn || "", h = 0; |
| 93 | for (var i = 0; i < turn.length; i++) h = (h * 31 + turn.charCodeAt(i)) >>> 0; |
| 94 | return ids.length ? ids[h % ids.length] : "professional"; |
| 95 | } |
| 96 | // The phrases a situation cycles through: its own, and when it has |
| 97 | // only one or two, the set's thinking phrases too. |
| 98 | function phrases(li) { |
| 99 | if (li.dataset.kind || li.situation === "tool") return []; |
| 100 | var set = WORDS[setFor(li)] || {}, own = set[li.situation || "think"] || []; |
| 101 | if (own.length > 2) return own; |
| 102 | return own.concat((set.think || []).filter(function (p) { return own.indexOf(p) < 0; })); |
| 103 | } |
| 104 | // Pace (Paul: "a touch less frequently, they're a bit frantic"): a |
| 105 | // situation's first phrase holds about 5 s, then a new one every 6 to |
| 106 | // 8 s. Words are content: they change under reduced motion too. |
| 107 | var FIRST = 5000; |
| 108 | function nextDelay() { return 6000 + Math.random() * 2000; } |
| 109 | // Decks (Paul: "it takes a while before I see the same ones again"): |
| 110 | // each set and situation is a shuffled deck, dealt one phrase at a time |
| 111 | // and never repeated until it runs out; the deck and its place are kept |
| 112 | // in localStorage, so a new turn (or a reload) goes on where the last |
| 113 | // left off. A new deck never starts with the last few of the old one. |
| 114 | var RECENT = 3, decks = {}; |
| 115 | function shuffled(n, avoid) { |
| 116 | var out = []; |
| 117 | for (var i = 0; i < n; i++) out.push(i); |
| 118 | for (var j = n - 1; j > 0; j--) { |
| 119 | var k = Math.floor(Math.random() * (j + 1)), t = out[j]; |
| 120 | out[j] = out[k]; |
| 121 | out[k] = t; |
| 122 | } |
| 123 | // The ones just shown go to the back half. |
| 124 | var front = Math.min(avoid.length, n - avoid.length); |
| 125 | for (var a = 0; a < front; a++) { |
| 126 | if (avoid.indexOf(out[a]) < 0) continue; |
| 127 | for (var b = n - 1; b >= front; b--) { |
| 128 | if (avoid.indexOf(out[b]) < 0) { |
| 129 | var x = out[a]; |
| 130 | out[a] = out[b]; |
| 131 | out[b] = x; |
| 132 | break; |
| 133 | } |
| 134 | } |
| 135 | } |
| 136 | return out; |
| 137 | } |
| 138 | function deal(key, n) { |
| 139 | var d = decks[key]; |
| 140 | try { d = JSON.parse(localStorage.getItem("equipo.thinking." + key) || "null") || d; } catch (_) { /* private mode */ } |
| 141 | if (!d || d.n !== n || !Array.isArray(d.order) || d.order.length !== n) d = { n: n, order: shuffled(n, []), pos: 0 }; |
| 142 | if (d.pos >= n) { |
| 143 | d.order = shuffled(n, d.order.slice(Math.max(0, n - RECENT))); |
| 144 | d.pos = 0; |
| 145 | } |
| 146 | var at = d.order[d.pos++]; |
| 147 | decks[key] = d; |
| 148 | try { localStorage.setItem("equipo.thinking." + key, JSON.stringify(d)); } catch (_) { /* kept in memory */ } |
| 149 | return at; |
| 150 | } |
| 151 | function themed(li, label) { |
| 152 | var list = phrases(li); |
| 153 | li.dataset.thinkingWords = setFor(li); |
| 154 | li.wordAt = Date.now(); |
| 155 | if (!list.length) { |
| 156 | li.wordKey = ""; |
| 157 | return label.replace(/‘(.*)’/u, function (_, subject) { |
| 158 | var chars = Array.from(subject); |
| 159 | return "‘" + (chars.length > 40 ? chars.slice(0, 39).join("") + "…" : subject) + "’"; |
| 160 | }); |
| 161 | } |
| 162 | var key = setFor(li) + "." + (li.situation || "think"); |
| 163 | if (li.wordKey !== key) { |
| 164 | // A new situation (or set): the deck's next phrase at once. |
| 165 | li.wordKey = key; |
| 166 | li.wordDelay = FIRST; |
| 167 | } |
| 168 | return list[deal(key, list.length) % list.length]; |
| 169 | } |
| 170 | // Each phrase stays at least DWELL ms (Paul, 2026-11-20: "the |
| 171 | // thinking kept flashing quite quickly"): a turn's first moments bring |
| 172 | // thinking, a tool's label and then its named one, all within a second. |
| 173 | // An activity that comes sooner waits, and only the latest waiting one |
| 174 | // is drawn; the accessible label and tooltip follow it at once. |
| 175 | var DWELL = 1500; |
| 176 | function want(li, label) { |
| 177 | li.wanted = label; |
| 178 | if (li.waiting) return; |
| 179 | var wait = DWELL - (Date.now() - (li.shownAt || 0)); |
| 180 | if (wait <= 0) return flush(li); |
| 181 | li.waiting = setTimeout(function () { flush(li); }, wait); |
| 182 | } |
| 183 | function flush(li) { |
| 184 | var label = li.wanted; |
| 185 | li.waiting = 0; |
| 186 | li.wanted = null; |
| 187 | if (label !== null && label !== undefined) draw(li, themed(li, label), false); |
| 188 | } |
| 189 | // The next phrase of the situation, when its time has come. |
| 190 | function cycle(li) { |
| 191 | var list = phrases(li); |
| 192 | if (li.waiting || list.length < 2 || !li.wordKey || Date.now() - (li.wordAt || 0) < li.wordDelay) return; |
| 193 | li.wordDelay = nextDelay(); |
| 194 | li.wordAt = Date.now(); |
| 195 | draw(li, list[deal(li.wordKey, list.length) % list.length], false); |
| 196 | } |
| 197 | // The thinking line comes alive: the sparkle, and the drawn phrase |
| 198 | // beside the label, which stays for screen readers. |
| 199 | function enliven(li) { |
| 200 | var line = li.querySelector("[equipo-activity-line]"); |
| 201 | if (!line || line.hasAttribute("data-live")) return; |
| 202 | line.setAttribute("data-live", ""); |
| 203 | line.style.setProperty("--stagger", LOOK.star.stagger + "ms"); |
| 204 | var spark = el("span", "equipo-sparkle"); |
| 205 | spark.setAttribute("aria-hidden", "true"); |
| 206 | spark.dataset.spin = LOOK.star.spin; |
| 207 | spark.dataset.drift = LOOK.star.drift; |
| 208 | if (LOOK.star.warm) spark.setAttribute("data-warm", ""); |
| 209 | spark.innerHTML = STAR; |
| 210 | motes(LOOK.star).forEach(function (m, i) { |
| 211 | var mote = document.createElement("i"); |
| 212 | mote.setAttribute("data-mote", m.kind); |
| 213 | if (i === 0 || i === 2) mote.setAttribute("data-wisp", ""); |
| 214 | mote.style.setProperty("--dx", m.dx.toFixed(2) + "em"); |
| 215 | mote.style.setProperty("--dy", m.dy.toFixed(2) + "em"); |
| 216 | mote.style.setProperty("--d", m.delay + "ms"); |
| 217 | mote.style.setProperty("--dur", m.dur.toFixed(2) + "s"); |
| 218 | spark.append(mote); |
| 219 | }); |
| 220 | var label = line.querySelector("[equipo-activity]"); |
| 221 | var phrase = el("span", "equipo-phrase"); |
| 222 | phrase.setAttribute("aria-hidden", "true"); |
| 223 | phrase.append(el("span", "data-measure")); |
| 224 | line.prepend(spark); |
| 225 | label.before(phrase); |
| 226 | label.setAttribute("equipo-visually-hidden", ""); |
| 227 | li.flourished = Date.now(); |
| 228 | line.title = label.textContent; |
| 229 | draw(li, themed(li, label.textContent), true); |
| 230 | } |
| 231 | // Draw a phrase: the window eases to its width, shared letters stay, |
| 232 | // the rest of the old phrase fades as the new one comes in. |
| 233 | function draw(li, text, first) { |
| 234 | var line = li.querySelector("[equipo-activity-line]"); |
| 235 | var phrase = line && line.querySelector("[equipo-phrase]"); |
| 236 | if (!phrase) return; |
| 237 | var before = li.phrase || "", keep = 0; |
| 238 | if (!first) { |
| 239 | var a = Array.from(before), b = Array.from(text); |
| 240 | while (keep < a.length && keep < b.length && a[keep] === b[keep]) keep++; |
| 241 | if (keep < b.length) while (keep > 0 && !/[\s…]/.test(b[keep - 1])) keep--; |
| 242 | } |
| 243 | li.phrase = text; |
| 244 | li.shownAt = Date.now(); |
| 245 | var measure = phrase.querySelector("[data-measure]"); |
| 246 | measure.textContent = text; |
| 247 | var natural = measure.offsetWidth + 1; |
| 248 | var cs = getComputedStyle(li).maxInlineSize; |
| 249 | var max = /%$/.test(cs) ? parseFloat(cs) / 100 * li.parentElement.clientWidth : parseFloat(cs) || li.parentElement.clientWidth; |
| 250 | var room = Math.floor(max - (line.offsetWidth - phrase.offsetWidth) - 8); |
| 251 | if (!thread) { |
| 252 | var elapsed=line.querySelector("[equipo-elapsed]"), sep=line.querySelector("[equipo-activity-sep]"); |
| 253 | var gap=parseFloat(getComputedStyle(line).columnGap)||0; |
| 254 | room=Math.floor(line.clientWidth-(elapsed?elapsed.offsetWidth:0)-(sep?sep.offsetWidth:0)-gap*3-8); |
| 255 | } |
| 256 | // One phrase at a time: the old one fades in .2 s, before the new |
| 257 | // one's letters start (equipo.css), and one still fading goes now. |
| 258 | phrase.querySelectorAll("[data-out]").forEach(function (old) { old.remove(); }); |
| 259 | phrase.querySelectorAll("[data-in]").forEach(function (old) { |
| 260 | old.removeAttribute("data-in"); |
| 261 | old.setAttribute("data-out", ""); |
| 262 | Array.from(old.children).forEach(function (c, i) { |
| 263 | if (i < keep) c.style.visibility = "hidden"; |
| 264 | else c.style.setProperty("--n", 0); |
| 265 | }); |
| 266 | setTimeout(function () { old.remove(); }, 250); |
| 267 | }); |
| 268 | var next = letters(text, keep); |
| 269 | next.setAttribute("data-in", ""); |
| 270 | phrase.append(next); |
| 271 | phrase.toggleAttribute("data-cut", natural > room); |
| 272 | phrase.style.inlineSize = Math.max(40, Math.min(natural, room)) + "px"; |
| 273 | if (!first) flourish(li); |
| 274 | } |
| 275 | function flourish(li) { |
| 276 | var spark = li.querySelector("[equipo-sparkle]"); |
| 277 | li.flourished = Date.now(); |
| 278 | if (!spark || !moving()) return; |
| 279 | spark.removeAttribute("data-flourish"); |
| 280 | void spark.offsetWidth; |
| 281 | spark.setAttribute("data-flourish", ""); |
| 282 | clearTimeout(spark.flourishing); |
| 283 | spark.flourishing = setTimeout(function () { spark.removeAttribute("data-flourish"); }, 1800); |
| 284 | } |
| 285 | function setActivity(li, label, situation) { |
| 286 | var span = li.querySelector("[equipo-activity]"); |
| 287 | situation = situation || "think"; |
| 288 | if (!span || !label || span.textContent === label && li.situation === situation) return; |
| 289 | li.situation = situation; |
| 290 | span.textContent = label; |
| 291 | var line = li.querySelector("[equipo-activity-line]"); |
| 292 | if (line) line.title = label; |
| 293 | want(li, label); |
| 294 | } |
| 295 | // The line gives way (the first words arrived) or comes back (a tool |
| 296 | // after text). |
| 297 | function leave(li, gone) { |
| 298 | var line = li.querySelector("[equipo-activity-line]"); |
| 299 | if (line) line.toggleAttribute("data-leaving", gone); |
| 300 | } |
| 301 | // ── The streaming draft ──────────────────────────────────────────── |
| 302 | // The draft is drawn by the renderer the committed reply uses: the |
| 303 | // server's (POST /conversation/draft, chatmarkdown.RenderDraft), so a |
| 304 | // list is a list as it streams and the end of the stream changes |
| 305 | // nothing but the last words. One request at a time per draft, always |
| 306 | // with the whole text so far; its answer is drawn at the next frame. |
| 307 | function drawDraft(li, text) { |
| 308 | var body = li.querySelector("[data-stream-text]"); |
| 309 | if (!body) return; |
| 310 | var d = body.draft || (body.draft = { want: "", asked: null, html: null, frame: 0, busy: false }); |
| 311 | d.want = text; |
| 312 | ask(body, d); |
| 313 | } |
| 314 | function ask(body, d) { |
| 315 | if (d.busy || d.want === d.asked || body.draft !== d || !body.isConnected) return; |
| 316 | d.asked = d.want; |
| 317 | d.busy = true; |
| 318 | fetch("/conversation/draft", { method: "POST", credentials: "same-origin", headers: { "Accept": "text/html" }, body: new URLSearchParams({ text: d.asked }) }) |
| 319 | .then(function (r) { if (!r.ok) throw new Error("draft"); return r.text(); }) |
| 320 | .then(function (html) { |
| 321 | d.busy = false; |
| 322 | d.html = html; |
| 323 | if (!d.frame) d.frame = requestAnimationFrame(function () { d.frame = 0; paint(body, d); }); |
| 324 | ask(body, d); |
| 325 | }, function () { |
| 326 | // The next words ask again, or a second from now; the committed |
| 327 | // reply replaces the draft either way. |
| 328 | d.busy = false; |
| 329 | d.asked = null; |
| 330 | setTimeout(function () { ask(body, d); }, 1000); |
| 331 | }); |
| 332 | } |
| 333 | // paint draws the latest render over what is on screen, keeping it: |
| 334 | // a block that is the same stays as it is, text that grew gets its new |
| 335 | // part as a [data-new] span (the words fade in, gently under reduced |
| 336 | // motion), and only what changed is replaced. Timed as "equipo-draft". |
| 337 | function paint(body, d) { |
| 338 | if (body.draft !== d || !body.hasAttribute("data-stream-text") || d.html === null) return; |
| 339 | var started = performance.now(); |
| 340 | var next = document.createElement("template"); |
| 341 | next.innerHTML = d.html; |
| 342 | var caret = body.querySelector("[equipo-stream-caret]"); |
| 343 | if (caret) caret.remove(); |
| 344 | patch(body, next.content); |
| 345 | if (LOOK.handoff !== "gone") { |
| 346 | // The caret or dot ends the last line of text. |
| 347 | var end = body; |
| 348 | while (end.lastElementChild && /^(P|UL|OL|LI|PRE|CODE|BLOCKQUOTE)$/.test(end.lastElementChild.tagName)) end = end.lastElementChild; |
| 349 | if (end !== body) { |
| 350 | if (!caret) { |
| 351 | caret = document.createElement("span"); |
| 352 | caret.setAttribute("equipo-stream-caret", LOOK.handoff); |
| 353 | caret.setAttribute("aria-hidden", "true"); |
| 354 | } |
| 355 | end.append(caret); |
| 356 | } |
| 357 | } |
| 358 | try { performance.measure("equipo-draft", { start: started }); } catch (_) { /* older browsers */ } |
| 359 | scroll(); |
| 360 | } |
| 361 | // Text on screen: plain text and the spans that faded in. |
| 362 | function textish(n) { return n instanceof Text || n.tagName === "SPAN" && n.hasAttribute("data-new"); } |
| 363 | function fresh(s) { |
| 364 | if (!/\S/.test(s)) return new Text(s); |
| 365 | var span = document.createElement("span"); |
| 366 | span.setAttribute("data-new", ""); |
| 367 | span.textContent = s; |
| 368 | return span; |
| 369 | } |
| 370 | function same(a, b) { |
| 371 | if (a.tagName !== b.tagName || a.attributes.length !== b.attributes.length) return false; |
| 372 | for (var i = 0; i < b.attributes.length; i++) if (a.getAttribute(b.attributes[i].name) !== b.attributes[i].value) return false; |
| 373 | return true; |
| 374 | } |
| 375 | // common is how much two texts share from the start, never splitting a |
| 376 | // surrogate pair. |
| 377 | function common(a, b) { |
| 378 | var k = 0, n = Math.min(a.length, b.length); |
| 379 | while (k < n && a.charCodeAt(k) === b.charCodeAt(k)) k++; |
| 380 | if (k > 0 && k < b.length && b.charCodeAt(k - 1) >= 0xD800 && b.charCodeAt(k - 1) < 0xDC00) k--; |
| 381 | return k; |
| 382 | } |
| 383 | // copy brings a piece of the render onto the page; the first seen.n |
| 384 | // characters of its text were on screen already and stay still. |
| 385 | function copy(w, seen) { |
| 386 | if (w instanceof Text) { |
| 387 | var out = document.createDocumentFragment(), n = Math.min(seen.n, w.data.length); |
| 388 | if (n) out.append(new Text(w.data.slice(0, n))); |
| 389 | if (n < w.data.length) out.append(fresh(w.data.slice(n))); |
| 390 | seen.n -= n; |
| 391 | return out; |
| 392 | } |
| 393 | // In the element's own namespace: a paste box's icons are SVG, which |
| 394 | // createElement would make unknown HTML elements that never draw. |
| 395 | var el = document.createElementNS(w.namespaceURI, w.localName); |
| 396 | for (var i = 0; i < w.attributes.length; i++) el.setAttribute(w.attributes[i].name, w.attributes[i].value); |
| 397 | for (var c = w.firstChild; c; c = c.nextSibling) el.append(copy(c, seen)); |
| 398 | return el; |
| 399 | } |
| 400 | // patch makes el's children the render's (next), keeping what is on |
| 401 | // screen: el's children are walked once, in step with the render's. |
| 402 | function patch(el, next) { |
| 403 | var at = el.firstChild; |
| 404 | // run takes the text on screen from at: its pieces and its words. |
| 405 | function run() { |
| 406 | var r = { parts: [], text: "" }; |
| 407 | while (at && textish(at)) { |
| 408 | r.parts.push(at); |
| 409 | r.text += at.textContent; |
| 410 | at = at.nextSibling; |
| 411 | } |
| 412 | return r; |
| 413 | } |
| 414 | // left puts back, still, what of a run the render did not take, for |
| 415 | // the next piece to take (a link that has just completed, say). |
| 416 | function left(r, k) { |
| 417 | r.parts.forEach(function (p) { p.remove(); }); |
| 418 | if (k < r.text.length) { |
| 419 | var rest = new Text(r.text.slice(k)); |
| 420 | el.insertBefore(rest, at); |
| 421 | at = rest; |
| 422 | } |
| 423 | } |
| 424 | for (var w = next.firstChild; w; w = w.nextSibling) { |
| 425 | if (w instanceof Text) { |
| 426 | var r = run(), k = common(r.text, w.data); |
| 427 | if (k === r.text.length) { |
| 428 | if (k < w.data.length) el.insertBefore(fresh(w.data.slice(k)), at); |
| 429 | continue; |
| 430 | } |
| 431 | // What was drawn changed: what they share stays still. |
| 432 | left(r, k); |
| 433 | if (k) el.insertBefore(new Text(w.data.slice(0, k)), at); |
| 434 | if (k < w.data.length) el.insertBefore(fresh(w.data.slice(k)), at); |
| 435 | } else if (at && !textish(at) && same(at, w)) { |
| 436 | patch(at, w); |
| 437 | at = at.nextSibling; |
| 438 | } else { |
| 439 | // A new element: the start of its words that were on screen as |
| 440 | // plain text in its place (an opener that just closed) stays still. |
| 441 | var seen = { n: 0 }; |
| 442 | if (at && textish(at)) { |
| 443 | var t = run(); |
| 444 | seen.n = common(t.text, w.textContent); |
| 445 | left(t, seen.n); |
| 446 | } |
| 447 | el.insertBefore(copy(w, seen), at); |
| 448 | } |
| 449 | } |
| 450 | while (at) { |
| 451 | var gone = at; |
| 452 | at = at.nextSibling; |
| 453 | gone.remove(); |
| 454 | } |
| 455 | } |
| 456 | // drawn: the draft shows the whole text it has been given (none asked |
| 457 | // for or waiting for a frame). The committed reply waits for that, up to |
| 458 | // two seconds, so the end of a long stream is drawn before it commits. |
| 459 | function drawn(live) { |
| 460 | var body = live.querySelector("[data-stream-text]"), d = body && body.draft; |
| 461 | return !live.holding && (!d || !d.busy && d.asked === d.want && !d.frame); |
| 462 | } |
| 463 | function whenDrawn(live, then) { |
| 464 | if (live.drawWait) return; |
| 465 | live.drawWait = true; |
| 466 | (function wait() { |
| 467 | if (live.isConnected && !drawn(live) && Date.now() < live.settleBy) return setTimeout(wait, 50); |
| 468 | live.drawWait = false; |
| 469 | then(); |
| 470 | })(); |
| 471 | } |
| 472 | // The committed reply takes over its draft in place: the same element, |
| 473 | // now with the server's attributes, time and markdown. No reflow. |
| 474 | function settle(live, server) { |
| 475 | clearTimeout(live.holding); |
| 476 | var stop=live.querySelector("[equipo-turn-stop]");if(stop)stop.remove(); |
| 477 | var line = live.querySelector("[equipo-activity-line]"); |
| 478 | Array.from(live.attributes).forEach(function (a) { live.removeAttribute(a.name); }); |
| 479 | Array.from(server.attributes).forEach(function (a) { live.setAttribute(a.name, a.value); }); |
| 480 | var time = live.querySelector("[equipo-message-meta] time"), done = server.querySelector("[equipo-message-meta] time"); |
| 481 | if (time && done) { |
| 482 | time.setAttribute("datetime", done.getAttribute("datetime") || ""); |
| 483 | time.textContent = done.textContent; |
| 484 | } |
| 485 | var body = live.querySelector("[equipo-message-body]"), final = server.querySelector("[equipo-message-body]"); |
| 486 | if (body && body.draft) { |
| 487 | cancelAnimationFrame(body.draft.frame); |
| 488 | delete body.draft; |
| 489 | } |
| 490 | if (body && final) { |
| 491 | Array.from(body.attributes).forEach(function (a) { body.removeAttribute(a.name); }); |
| 492 | Array.from(final.attributes).forEach(function (a) { body.setAttribute(a.name, a.value); }); |
| 493 | body.replaceChildren(); |
| 494 | while (final.firstChild) body.append(final.firstChild); |
| 495 | } |
| 496 | if (line) { |
| 497 | line.setAttribute("data-leaving", ""); |
| 498 | setTimeout(function () { line.remove(); }, moving() ? 900 : 0); |
| 499 | } |
| 500 | // The quiet line under a reply that moved connection. |
| 501 | var switched = server.querySelector("[data-switched]"); |
| 502 | if (switched && !live.querySelector("[data-switched]")) live.append(switched); |
| 503 | return live; |
| 504 | } |
| 505 | // kind is a turn the coordinator takes on its own (move_in, explore): |
| 506 | // its line says so before any activity arrives. |
| 507 | function bubble(turn, kind, waited) { |
| 508 | if (!turn) return null; |
| 509 | if (!thread) feed.querySelectorAll("[equipo-thinking]").forEach(function (line) { |
| 510 | if (line.dataset.turn !== turn && ended[line.dataset.turn]) drop(line); |
| 511 | }); |
| 512 | var el = lineFor(turn); |
| 513 | if (!el && !kind && pending.length) { |
| 514 | // The line shown since the send becomes this turn's, in place. |
| 515 | el = pending[0]; |
| 516 | adopt(el, turn); |
| 517 | return el; |
| 518 | } |
| 519 | if (!el) { |
| 520 | el = template("equipo-thinking-template"); |
| 521 | el.dataset.turn = turn; |
| 522 | var who = el.querySelector("[data-who]"); |
| 523 | if (who && asked[turn]) who.textContent = root.dataset["name" + asked[turn].charAt(0).toUpperCase() + asked[turn].slice(1)] || ""; |
| 524 | var label = kind && root.dataset[kind === "move_in" ? "movingIn" : "exploring"]; |
| 525 | if (label) { |
| 526 | el.dataset.kind = kind; |
| 527 | el.querySelector("[equipo-activity]").textContent = label; |
| 528 | } |
| 529 | // The timer counts from the send that started this turn (a turn |
| 530 | // that waited behind another, from now). |
| 531 | el.dataset.started = String(!kind && !waited && Date.now() - lastSend < 60000 ? lastSend : Date.now()); |
| 532 | feed.append(el); |
| 533 | enliven(el); |
| 534 | tick(); |
| 535 | scroll(); |
| 536 | } |
| 537 | return el; |
| 538 | } |
| 539 | // ── The line from the moment of sending ──────────────────────────── |
| 540 | // A send shows the coordinator's line at once, before the server has |
| 541 | // answered: the same element, sparkle, phrases and timer (from 0) that |
| 542 | // the turn then adopts in place. pending holds the lines no turn has |
| 543 | // adopted yet, oldest first; ended the turns that are over or held, so a |
| 544 | // late answer to the send never adopts a line for them. |
| 545 | var pending = [], ended = {}; |
| 546 | function lineFor(turn) { |
| 547 | return turn ? feed.querySelector('[equipo-thinking][data-turn="' + CSS.escape(turn) + '"]') : null; |
| 548 | } |
| 549 | // ── One line at a time ───────────────────────────────────────────── |
| 550 | // The person's turns go one at a time. A turn queued behind the running |
| 551 | // one has no line or timer of its own: a quiet note under the person's |
| 552 | // latest message says it waits (queued holds those turns; revs the |
| 553 | // newest turn revision seen, so a late answer to a send never undoes |
| 554 | // its turn's event). Turns the coordinator takes on its own never hold |
| 555 | // a person's turn back here: they give way. |
| 556 | var queued = {}, revs = {}; |
| 557 | feed.querySelectorAll("[data-queued]").forEach(function (n) { |
| 558 | var m = n.closest("[data-turn-id]"); |
| 559 | if (m && m.dataset.turnId) queued[m.dataset.turnId] = true; |
| 560 | }); |
| 561 | // behind: another person's turn holds the line (sending: or a line |
| 562 | // shown since a send that no turn has adopted yet). |
| 563 | function behind(turn, sending) { |
| 564 | if (thread) return false; |
| 565 | if (sending && pending.length) return true; |
| 566 | return Array.from(feed.querySelectorAll("[equipo-thinking]:not([data-optimistic])")).some(function (el) { |
| 567 | return el.dataset.turn && el.dataset.turn !== turn && !ended[el.dataset.turn]; |
| 568 | }); |
| 569 | } |
| 570 | function notes() { |
| 571 | if (thread) return; |
| 572 | var want = null; |
| 573 | feed.querySelectorAll('[equipo-message="own"]').forEach(function (m) { |
| 574 | var turn = m.dataset.turnId; |
| 575 | if (turn ? queued[turn] && !ended[turn] : m.queuedAtSend) want = m; |
| 576 | }); |
| 577 | feed.querySelectorAll("[data-queued]").forEach(function (n) { if (n.parentElement !== want) n.remove(); }); |
| 578 | if (want && !want.querySelector(":scope > [data-queued]")) { |
| 579 | var note = document.createElement("p"); |
| 580 | note.setAttribute("equipo-card-note", ""); |
| 581 | note.setAttribute("data-queued", ""); |
| 582 | note.textContent = root.dataset.queuedNote || ""; |
| 583 | want.append(note); |
| 584 | } |
| 585 | } |
| 586 | function optimistic(who) { |
| 587 | // Nothing can answer: the server's quiet status says so instead. |
| 588 | if (!thread && feed.querySelector("[data-no-connection]")) return null; |
| 589 | var el = template("equipo-thinking-template"); |
| 590 | el.dataset.turn = ""; |
| 591 | el.setAttribute("data-optimistic", ""); |
| 592 | el.seed = requestID(); |
| 593 | var name = el.querySelector("[data-who]"); |
| 594 | if (name && who) name.textContent = root.dataset["name" + who.charAt(0).toUpperCase() + who.slice(1)] || ""; |
| 595 | el.dataset.started = String(Date.now()); |
| 596 | pending.push(el); |
| 597 | feed.append(el); |
| 598 | enliven(el); |
| 599 | tick(); |
| 600 | scroll(true); |
| 601 | return el; |
| 602 | } |
| 603 | function adopt(el, turn) { |
| 604 | var at = pending.indexOf(el); |
| 605 | if (at >= 0) pending.splice(at, 1); |
| 606 | el.removeAttribute("data-optimistic"); |
| 607 | el.dataset.turn = turn; |
| 608 | } |
| 609 | function drop(el) { |
| 610 | if (!el) return; |
| 611 | var at = pending.indexOf(el); |
| 612 | if (at >= 0) pending.splice(at, 1); |
| 613 | el.remove(); |
| 614 | } |
| 615 | // claim: the server named the turn (or, in a thread, the question) the |
| 616 | // send belongs to. A line still waiting is adopted, or goes when the turn |
| 617 | // already has one (the message joined an earlier queued turn) or is over. |
| 618 | function claim(el, turn) { |
| 619 | if (!el || !turn || !el.isConnected || !el.hasAttribute("data-optimistic")) return; |
| 620 | if (lineFor(turn) || ended[turn] || queued[turn]) drop(el); |
| 621 | else adopt(el, turn); |
| 622 | } |
| 623 | // Who a thread question goes to, as ask-target.js shows it. |
| 624 | function askedOf() { |
| 625 | var chosen = form.querySelector("[data-ask-specialist]"); |
| 626 | if (!chosen) return ""; |
| 627 | if (chosen.value) return chosen.value; |
| 628 | var target = form.querySelector("[equipo-ask-target]"); |
| 629 | var choices = ((target && target.dataset.choices) || "").split(",").filter(Boolean); |
| 630 | if (choices.indexOf("review") >= 0 && /\breview(?:er|ers|ed|ing|s)?\b/i.test(input.value)) return "review"; |
| 631 | return choices[0] || ""; |
| 632 | } |
| 633 | function atBottom() { |
| 634 | return box.scrollHeight - box.scrollTop - box.clientHeight < 48; |
| 635 | } |
| 636 | function scroll(force) { |
| 637 | if (!box || !(following || force)) return; |
| 638 | box.scrollTop = box.scrollHeight; |
| 639 | following = true; |
| 640 | } |
| 641 | if (box) box.addEventListener("scroll", function () { following = atBottom(); }, { passive: true }); |
| 642 | // Elapsed time on each thinking line, in whole seconds, and the |
| 643 | // sparkle's flourish now and then. |
| 644 | function tick() { |
| 645 | var format = root.dataset.elapsed || "{n}s"; |
| 646 | feed.querySelectorAll("[equipo-thinking]").forEach(function (el) { |
| 647 | enliven(el); |
| 648 | var stop = el.querySelector("[equipo-turn-stop]"); |
| 649 | if (stop && el.dataset.turn && !el.hasAttribute("data-optimistic")) { stop.action="/conversation/turns/"+encodeURIComponent(el.dataset.turn)+"/stop"; stop.hidden=false; } |
| 650 | var out = el.querySelector("[equipo-elapsed]"); |
| 651 | var started = Number(el.dataset.started) || Date.now(); |
| 652 | if (out) out.textContent = format.replace("{n}", String(Math.max(0, Math.floor((Date.now() - started) / 1000)))); |
| 653 | if (LOOK.star.every && !el.hasAttribute("data-streaming") && Date.now() - (el.flourished || 0) > LOOK.star.every) flourish(el); |
| 654 | }); |
| 655 | } |
| 656 | setInterval(tick, 1000); |
| 657 | // The set's phrases take turns while the activity holds (words are |
| 658 | // content: they change under reduced motion too, without the motion). |
| 659 | setInterval(function () { |
| 660 | feed.querySelectorAll("[equipo-thinking]:not([data-streaming])").forEach(cycle); |
| 661 | }, 250); |
| 662 | function showDraft(turn) { |
| 663 | var sub = feed.querySelector('[data-roster-turn="' + CSS.escape(turn) + '"] [equipo-thread-draft]'); |
| 664 | if (sub) { sub.textContent = drafts[turn] ? drafts[turn].text : ""; return; } |
| 665 | var el = bubble(turn); |
| 666 | if (!el) return; |
| 667 | var text = drafts[turn] ? drafts[turn].text : ""; |
| 668 | if (!text) return; |
| 669 | // The first words: the line fades where it sits, and the text |
| 670 | // follows once it has gone. |
| 671 | if (!el.hasAttribute("data-streaming")) { |
| 672 | el.dataset.streaming = ""; |
| 673 | leave(el, true); |
| 674 | if (moving()) { |
| 675 | el.holding = setTimeout(function () { |
| 676 | el.holding = null; |
| 677 | drawDraft(el, drafts[turn] ? drafts[turn].text : text); |
| 678 | scroll(); |
| 679 | }, 260); |
| 680 | return; |
| 681 | } |
| 682 | } |
| 683 | if (el.holding) return; |
| 684 | drawDraft(el, text); |
| 685 | scroll(); |
| 686 | } |
| 687 | function showActivity(v) { |
| 688 | var el = bubble(v.turn_id); |
| 689 | if (!el) return; |
| 690 | if (drafts[v.turn_id] && drafts[v.turn_id].text) { |
| 691 | // A tool after text: show the line again under the draft. |
| 692 | delete el.dataset.streaming; |
| 693 | leave(el, false); |
| 694 | } |
| 695 | setActivity(el, v.label, situationOf(v)); |
| 696 | scroll(); |
| 697 | } |
| 698 | // A committed reply is rendered by the server (markdown), then running |
| 699 | // drafts are put back. Refreshes run one at a time (a request during one |
| 700 | // runs once after it), and a page older than the one shown is dropped. |
| 701 | var inflight = null, again = false; |
| 702 | // shape is the cursor of the newest event that changes what the page |
| 703 | // shows (a turn, a message, a card): a page rendered before it is |
| 704 | // stale, and is followed by another. |
| 705 | var pageCursor = cursor, shape = cursor; |
| 706 | function refresh() { |
| 707 | if (inflight) { |
| 708 | again = true; |
| 709 | return inflight; |
| 710 | } |
| 711 | inflight = load().finally(function () { |
| 712 | inflight = null; |
| 713 | if (again) { |
| 714 | again = false; |
| 715 | refreshSoon(); |
| 716 | } |
| 717 | }); |
| 718 | return inflight; |
| 719 | } |
| 720 | // A failed refresh is tried again shortly, then again: never a reload. |
| 721 | function refreshSoon() { |
| 722 | refresh().catch(function () { |
| 723 | setTimeout(function () { refresh().catch(function () { setTimeout(refreshSoon, 5000); }); }, 1500); |
| 724 | }); |
| 725 | } |
| 726 | // ── A page older than the server ──────────────────────────────────── |
| 727 | // Scripts and stylesheets are content-hashed, so a server page that |
| 728 | // names another hash of one this page has means a deploy came since |
| 729 | // this page loaded: its code is older than the replies the server |
| 730 | // renders into it. On 2026-11-11 a paste box in a |
| 731 | // page from before paste.js was a Copy that did nothing, over a block |
| 732 | // the old stylesheet did not wrap. Such a page reloads at the first |
| 733 | // quiet moment, keeping its place in the feed, and only once for each |
| 734 | // server build, so a cache that keeps serving the old page cannot loop. |
| 735 | var RELOADED = "equipo.reloaded-for", PLACE = "equipo.reload-place", reloading = false; |
| 736 | function builds(doc) { |
| 737 | var out = {}; |
| 738 | doc.querySelectorAll("link[rel~='stylesheet'][href], script[src]").forEach(function (el) { |
| 739 | var path = new URL(el.getAttribute("href") || el.getAttribute("src"), location.href).pathname; |
| 740 | out[path.replace(/\.[0-9a-f]{16}(\.[^./]*)?$/, "$1")] = path; |
| 741 | }); |
| 742 | return out; |
| 743 | } |
| 744 | // newer is the server page's build when this page's is not it ("" when |
| 745 | // they agree): the asset paths, as one key. Only assets both pages name |
| 746 | // count: a script one page has and the other lacks may be a card's |
| 747 | // (merge-ships.js), which comes and goes without a deploy. |
| 748 | function newer(doc) { |
| 749 | var mine = builds(document), theirs = builds(doc); |
| 750 | var both = Object.keys(theirs).filter(function (name) { return mine[name]; }).sort(); |
| 751 | var differs = both.some(function (name) { return mine[name] !== theirs[name]; }); |
| 752 | return differs ? both.map(function (name) { return theirs[name]; }).join(" ") : ""; |
| 753 | } |
| 754 | // quiet: nothing would be lost or interrupted by a reload. Nothing |
| 755 | // typed or attached, no unsaved field, no reply streaming, and no text |
| 756 | // selected (the person may be about to copy it). |
| 757 | function quiet() { |
| 758 | if (feed.querySelector("[equipo-thinking]") || document.querySelector("[equipo-chips] > :not(template), [data-dirty]")) return false; |
| 759 | var selection = getSelection(); |
| 760 | if (selection && !selection.isCollapsed && String(selection).trim()) return false; |
| 761 | return !Array.prototype.some.call(document.querySelectorAll("input, textarea, select"), function (el) { |
| 762 | if (el.tagName === "SELECT") return Array.prototype.some.call(el.options, function (o) { return o.selected !== o.defaultSelected; }); |
| 763 | if (el.type === "checkbox" || el.type === "radio") return el.checked !== el.defaultChecked; |
| 764 | if (el.type === "hidden" || el.type === "file") return false; |
| 765 | return el.value !== el.defaultValue; |
| 766 | }); |
| 767 | } |
| 768 | function reloadWhenQuiet(build) { |
| 769 | if (reloading) return; |
| 770 | reloading = true; |
| 771 | var tried = null; |
| 772 | try { tried = sessionStorage.getItem(RELOADED); } catch (_) { /* no storage: never reload, it could loop */ return; } |
| 773 | if (tried === build) { |
| 774 | console.warn("equipo: this page is older than the server's and a reload did not change that; not reloading again for this build."); |
| 775 | return; |
| 776 | } |
| 777 | (function wait() { |
| 778 | if (!quiet()) return setTimeout(wait, 1000); |
| 779 | try { |
| 780 | sessionStorage.setItem(RELOADED, build); |
| 781 | sessionStorage.setItem(PLACE, JSON.stringify({ path: location.pathname, top: box ? box.scrollTop : 0, following: following })); |
| 782 | } catch (_) { return; } |
| 783 | location.reload(); |
| 784 | })(); |
| 785 | } |
| 786 | // placeAfterReload puts the feed back where it was before a reload for |
| 787 | // a newer build; false when there is nothing to put back. |
| 788 | function placeAfterReload() { |
| 789 | var at = null; |
| 790 | try { |
| 791 | at = JSON.parse(sessionStorage.getItem(PLACE) || "null"); |
| 792 | sessionStorage.removeItem(PLACE); |
| 793 | } catch (_) { return false; } |
| 794 | if (!at || at.path !== location.pathname || at.following || !box) return false; |
| 795 | box.scrollTop = at.top; |
| 796 | following = atBottom(); |
| 797 | return true; |
| 798 | } |
| 799 | // Earlier days the reader opened stay open across refreshes: the page |
| 800 | // is asked for them (?day=), as the server rendered them. |
| 801 | var days = new Set(); |
| 802 | feed.querySelectorAll("[equipo-rollup][data-expanded]").forEach(function (el) { days.add(el.dataset.day); }); |
| 803 | function pageURL() { |
| 804 | if (!days.size) return location.pathname; |
| 805 | return location.pathname + "?" + Array.from(days).sort().map(function (d) { return "day=" + encodeURIComponent(d); }).join("&"); |
| 806 | } |
| 807 | // refreshed settles once a refresh started after this call has run. |
| 808 | function refreshed() { |
| 809 | return inflight ? inflight.then(refreshed, refreshed) : refresh(); |
| 810 | } |
| 811 | function load() { |
| 812 | return fetch(pageURL(), { credentials: "same-origin", headers: { "Accept": "text/html" } }) |
| 813 | .then(function (r) { if (!r.ok) throw new Error("refresh"); return r.text(); }) |
| 814 | .then(function (body) { |
| 815 | var doc = new DOMParser().parseFromString(body, "text/html"); |
| 816 | var next = doc.querySelector("[equipo-feed]"); |
| 817 | if (next) next.querySelectorAll("[data-card-form]").forEach(function(f){f.dataset.busy="false";}); |
| 818 | var page = doc.querySelector("[data-chat-stream]"); |
| 819 | if (!next || !page) return; |
| 820 | var pill=root.querySelector("[equipo-needs-pill]"), nextPill=doc.querySelector("[equipo-needs-pill]"); |
| 821 | if(pill && nextPill) pill.replaceWith(nextPill); |
| 822 | var build = newer(doc); |
| 823 | if (build) reloadWhenQuiet(build); |
| 824 | var at = Number(page.dataset.cursor) || 0; |
| 825 | if (at < pageCursor) return; |
| 826 | pageCursor = at; |
| 827 | // The names a step's maker gives the thread follow it (Design's |
| 828 | // work handed to Engineering): ask-target.js re-reads them. |
| 829 | ["nameEngineering", "nameReview"].forEach(function (k) { if (page.dataset[k]) root.dataset[k] = page.dataset[k]; }); |
| 830 | var askLine = document.querySelector("[equipo-ask-target]"), nextAsk = doc.querySelector("[equipo-ask-target]"); |
| 831 | if (askLine && nextAsk) askLine.dataset.choices = nextAsk.dataset.choices || ""; |
| 832 | root.dispatchEvent(new CustomEvent("equipo:names")); |
| 833 | var stale = at < shape; |
| 834 | if (stale) again = true; |
| 835 | // Keep live timers and activity lines across the re-render. |
| 836 | // A newly committed reply settles into its draft's element; a turn |
| 837 | // may already have earlier messages on the page. |
| 838 | var focused=document.activeElement, focusedCard=focused && focused.closest("[data-card]"); |
| 839 | var cardFocus=focusedCard && /^(TEXTAREA|INPUT)$/.test(focused.tagName) ? {id:focusedCard.dataset.card,name:focused.name,start:focused.selectionStart,end:focused.selectionEnd} : null; |
| 840 | var keep = {}, shown = {}, opened = {}; |
| 841 | feed.querySelectorAll("[equipo-thinking]:not([data-optimistic])").forEach(function (el) { keep[el.dataset.turn] = el; }); |
| 842 | // A receipt the person opened with ⋯ stays open. |
| 843 | feed.querySelectorAll("[equipo-receipt][data-open]").forEach(function (el) { opened[el.dataset.card] = true; }); |
| 844 | next.querySelectorAll("[equipo-receipt]").forEach(function (el) { |
| 845 | if (!opened[el.dataset.card]) return; |
| 846 | el.setAttribute("data-open", ""); |
| 847 | var more = el.querySelector("[equipo-receipt-more]"); |
| 848 | if (more) more.setAttribute("aria-expanded", "true"); |
| 849 | }); |
| 850 | feed.querySelectorAll("[data-card]").forEach(function (card) { |
| 851 | if (card.querySelector("[data-direction-thread][open]")) cardOpen.add(card.dataset.card); |
| 852 | var report = card.querySelector("[data-report-thread]"); if (report) reportOpen.set(card.dataset.card, report.open); |
| 853 | var inputs = {}; |
| 854 | card.querySelectorAll("textarea, input:not([type=hidden])").forEach(function (el) { if (el.value) inputs[el.name] = el.value; }); |
| 855 | if (Object.keys(inputs).length) cardDrafts.set(card.dataset.card, inputs); |
| 856 | }); |
| 857 | next.querySelectorAll("[data-card]").forEach(function (card) { |
| 858 | var old = cardBusy.get(card.dataset.card); if (old) { card.replaceWith(old); return; } |
| 859 | var drawer=card.querySelector("[data-direction-thread]"); if(drawer && cardOpen.has(card.dataset.card)) {drawer.dataset.restored="";drawer.open=true;} |
| 860 | var report = card.querySelector("[data-report-thread]"); |
| 861 | if (report && reportOpen.has(card.dataset.card)) { report.dataset.restored=""; report.open=reportOpen.get(card.dataset.card); } |
| 862 | card.querySelectorAll("[data-report-talk]").forEach(function(talk) { if (report) talk.setAttribute("aria-expanded", String(report.open)); }); |
| 863 | var success=cardSuccess.get(card.dataset.card); |
| 864 | if (success && success.state && success.state!==card.dataset.state) { cardSuccess.delete(card.dataset.card); success=null; } |
| 865 | if (success && card.querySelector("[equipo-roster-links]")) { |
| 866 | success.state=card.dataset.state; |
| 867 | var status=document.createElement("p"); status.setAttribute("equipo-card-done", ""); status.setAttribute("role", "status"); status.textContent=success.label; |
| 868 | card.querySelector("[equipo-roster-links]").after(status); |
| 869 | } |
| 870 | var values = cardDrafts.get(card.dataset.card); if (!values) return; |
| 871 | card.querySelectorAll("textarea, input:not([type=hidden])").forEach(function (el) { if (values[el.name]) { el.value = values[el.name]; el.closest("form").setAttribute("data-has-content", ""); } }); |
| 872 | }); |
| 873 | feed.querySelectorAll("[data-message]").forEach(function (el) { shown[el.dataset.message] = true; }); |
| 874 | var items = Array.from(next.children).map(function (el) { |
| 875 | var fresh = el.matches('[equipo-message="incoming"][data-turn-id]') && !shown[el.dataset.message]; |
| 876 | var turn = el.hasAttribute("equipo-thinking") ? el.dataset.turn : fresh ? el.dataset.turnId : ""; |
| 877 | var old = turn && keep[turn]; |
| 878 | // A page from before the turn ended never brings its line back. |
| 879 | if (!old && el.hasAttribute("equipo-thinking") && ended[turn]) return null; |
| 880 | if (el.hasAttribute("equipo-thinking") && !el.dataset.kind) delete queued[turn]; |
| 881 | if (!old && el.hasAttribute("equipo-thinking") && !el.dataset.kind && pending.length && !ended[turn]) { |
| 882 | // The server shows the turn before its event came: the line |
| 883 | // shown since the send takes it, with the server's words. |
| 884 | old = pending[0]; |
| 885 | adopt(old, turn); |
| 886 | var said = el.querySelector("[equipo-activity]"), mine = old.querySelector("[equipo-activity]"); |
| 887 | if (said && mine && said.textContent !== mine.textContent) { |
| 888 | mine.textContent = said.textContent; |
| 889 | var line = old.querySelector("[equipo-activity-line]"); |
| 890 | if (line) line.title = said.textContent; |
| 891 | } |
| 892 | var who = el.querySelector("[data-who]"), whoMine = old.querySelector("[data-who]"); |
| 893 | if (who && whoMine && who.textContent) whoMine.textContent = who.textContent; |
| 894 | return old; |
| 895 | } |
| 896 | if (!old) return el; |
| 897 | delete keep[turn]; |
| 898 | if (el.hasAttribute("equipo-thinking")) return old; |
| 899 | old.settleBy = old.settleBy || Date.now() + 2000; |
| 900 | if (!drawn(old) && Date.now() < old.settleBy) { |
| 901 | // The draft is still drawing its last words: the reply |
| 902 | // settles on the refresh after it has. |
| 903 | whenDrawn(old, refreshSoon); |
| 904 | return old; |
| 905 | } |
| 906 | return settle(old, el); |
| 907 | }).filter(Boolean); |
| 908 | // A stale page lacks lines for turns that started since: they stay. |
| 909 | if (stale) Object.keys(keep).forEach(function (turn) { if (!ended[turn] && !queued[turn]) items.push(keep[turn]); }); |
| 910 | // Lines shown since a send that no turn has adopted yet come last. |
| 911 | arrange(items.concat(pending)); |
| 912 | if (window.equipoPulse) window.equipoPulse(feed); |
| 913 | if(cardFocus) { |
| 914 | var target=feed.querySelector('[data-card="'+CSS.escape(cardFocus.id)+'"] [name="'+CSS.escape(cardFocus.name)+'"]'); |
| 915 | if(target) {target.focus({preventScroll:true});if(target.setSelectionRange)target.setSelectionRange(cardFocus.start,cardFocus.end);} |
| 916 | } |
| 917 | local.forEach(function (el) { place(el); }); |
| 918 | Object.keys(drafts).forEach(function (turn) { |
| 919 | if (feed.querySelector('[equipo-thinking][data-turn="' + CSS.escape(turn) + '"], [data-roster-turn="' + CSS.escape(turn) + '"] [equipo-thread-draft]')) showDraft(turn); |
| 920 | }); |
| 921 | notes(); |
| 922 | tick(); |
| 923 | scroll(); |
| 924 | }); |
| 925 | } |
| 926 | // arrange makes the feed the items, in order, moving only what must |
| 927 | // move: an element taken out and put back starts its animations again, |
| 928 | // so a thinking line kept across a refresh drew every fading phrase |
| 929 | // over the new one (Paul, 2026-11-20). |
| 930 | function arrange(items) { |
| 931 | var keep = new Set(items); |
| 932 | Array.from(feed.children).forEach(function (el) { if (!keep.has(el)) el.remove(); }); |
| 933 | var at = feed.firstElementChild; |
| 934 | items.forEach(function (el) { |
| 935 | if (el === at) at = at.nextElementSibling; |
| 936 | else feed.insertBefore(el, at); |
| 937 | }); |
| 938 | } |
| 939 | function apply(type, data) { |
| 940 | var e = JSON.parse(data); |
| 941 | if (e.cursor <= cursor) return; |
| 942 | cursor = e.cursor; |
| 943 | var v = e.data; |
| 944 | if (type === "turn" || type === "message" || type === "card" || type === "task" || type === "step") shape = cursor; |
| 945 | if (type === "thinking") { |
| 946 | root.dataset.thinkingSet = v.set; |
| 947 | return; |
| 948 | } |
| 949 | var question = e.resource === "question"; |
| 950 | if(type==="activity" && e.resource==="step" && v.step_id && feed.querySelector('[data-roster-step="'+CSS.escape(v.step_id)+'"]')) { refreshSoon(); return; } |
| 951 | if (thread) { |
| 952 | // The thread: its own questions' streams; everything else about |
| 953 | // the task is rendered by the server, like a committed reply. |
| 954 | if (type === "question") { |
| 955 | if (v.task_id !== thread) return; |
| 956 | asked[v.id] = v.specialist; |
| 957 | if (v.state === "answered" || v.state === "failed" || v.state === "cancelled") { |
| 958 | delete drafts[v.id]; |
| 959 | ended[v.id] = true; |
| 960 | // What the answer used: the page's spend regions follow. |
| 961 | document.dispatchEvent(new CustomEvent("equipo:work", { detail: { type: "question" } })); |
| 962 | } |
| 963 | if (v.state === "running") { |
| 964 | // Its turn came: the waiting line becomes the thinking line. |
| 965 | var waiting = feed.querySelector('[equipo-thinking][data-turn="' + CSS.escape(v.id) + '"]'); |
| 966 | if (waiting) setActivity(waiting, root.dataset.thinking); |
| 967 | } |
| 968 | refreshSoon(); |
| 969 | return; |
| 970 | } |
| 971 | if (type === "task" || type === "step") { |
| 972 | if (v.id === thread || v.task_id === thread) refreshSoon(); |
| 973 | return; |
| 974 | } |
| 975 | if ((type !== "delta" && type !== "activity") || !question || !(v.turn_id in asked)) return; |
| 976 | } else if (question || type === "question" || (type === "delta" || type === "activity") && (e.resource !== "turn" || !v.turn_id)) { |
| 977 | // A specialist's step reports activity on the same stream: it is |
| 978 | // not the coordinator's, and draws no line here. |
| 979 | return; |
| 980 | } |
| 981 | var subchat = (v.turn_id || v.id) && feed.querySelector('[data-roster-turn="' + CSS.escape(v.turn_id || v.id) + '"]'); |
| 982 | if (subchat && (type === "message" || type === "turn")) { if (type === "message" && v.role === "coordinator") delete drafts[v.turn_id]; refreshSoon(); return; } |
| 983 | if (type === "delta") { |
| 984 | var d = drafts[v.turn_id]; |
| 985 | // A new attempt (a failover, a recovery) starts its draft afresh. |
| 986 | if (!d || d.attempt !== e.attempt) d = { text: "", bytes: 0, attempt: e.attempt }; |
| 987 | if (v.offset !== d.bytes) return; |
| 988 | drafts[v.turn_id] = { text: d.text + v.text, bytes: d.bytes + utf8.encode(v.text).length, attempt: d.attempt }; |
| 989 | showDraft(v.turn_id); |
| 990 | } else if (type === "message") { |
| 991 | if (feed.querySelector('[data-message="' + CSS.escape(v.id) + '"]')) return; |
| 992 | clearEmpty(); |
| 993 | if (v.role === "coordinator") { |
| 994 | delete drafts[v.turn_id]; |
| 995 | ended[v.turn_id] = true; |
| 996 | notes(); |
| 997 | refreshSoon(); |
| 998 | return; |
| 999 | } |
| 1000 | // A send from this page still waiting for its answer: the event |
| 1001 | // names it in place, so the messages keep the order they were sent. |
| 1002 | var mine = Array.from(local).find(function (el) { return !el.dataset.message && el.isConnected && el.querySelector("[equipo-message-body]").textContent === v.text; }); |
| 1003 | if (mine) { |
| 1004 | mine.dataset.message = v.id; |
| 1005 | mine.dataset.turnId = v.turn_id || ""; |
| 1006 | notes(); |
| 1007 | return; |
| 1008 | } |
| 1009 | var own = template("equipo-own-template"); |
| 1010 | own.dataset.message = v.id; |
| 1011 | own.dataset.turnId = v.turn_id || ""; |
| 1012 | own.querySelector("[equipo-message-body]").textContent = v.text; |
| 1013 | sentFiles(own, served(v.attachments)); |
| 1014 | own.querySelector("time").textContent = new Date(v.created_at).toTimeString().slice(0, 5); |
| 1015 | var waiting = feed.querySelector("[equipo-thinking]"); |
| 1016 | feed.insertBefore(own, waiting); |
| 1017 | notes(); |
| 1018 | scroll(); |
| 1019 | } else if (type === "turn") { |
| 1020 | revs[v.id] = Math.max(revs[v.id] || 0, v.revision || 0); |
| 1021 | // A turn of the person's going (a message, or Try again): the note |
| 1022 | // under the one that ended unanswered, and its action, are history. |
| 1023 | if (!v.kind && (v.state === "queued" || v.state === "running" || v.state === "waiting")) { |
| 1024 | feed.querySelectorAll("[data-ended]").forEach(function (note) { if (note.dataset.ended !== v.id) note.remove(); }); |
| 1025 | } |
| 1026 | var heldNow = !!feed.querySelector("[data-no-connection]"); |
| 1027 | if (v.state === "waiting" && v.reason === "no_connection" || v.state === "queued" && heldNow) { |
| 1028 | // Nothing can answer yet: no thinking line, no timer; the quiet |
| 1029 | // status and the one card are the server's. |
| 1030 | delete drafts[v.id]; |
| 1031 | var thinking = lineFor(v.id); |
| 1032 | // The line shown since the send was this turn's: it goes too. |
| 1033 | if (!thinking && !v.kind) thinking = pending[0]; |
| 1034 | drop(thinking); |
| 1035 | ended[v.id] = true; |
| 1036 | refreshSoon(); |
| 1037 | } else if (v.state === "queued" && behind(v.id)) { |
| 1038 | // Behind the running turn: the note, and no line or timer. |
| 1039 | delete ended[v.id]; |
| 1040 | queued[v.id] = true; |
| 1041 | drop(lineFor(v.id)); |
| 1042 | notes(); |
| 1043 | } else if (v.state === "queued" || v.state === "running" || v.state === "waiting") { |
| 1044 | delete ended[v.id]; |
| 1045 | var waited = !!queued[v.id]; |
| 1046 | delete queued[v.id]; |
| 1047 | notes(); |
| 1048 | var shownDraft = bubble(v.id, v.kind, waited); |
| 1049 | if (drafts[v.id] && drafts[v.id].attempt !== v.attempt) { |
| 1050 | // The refused attempt's words go; the next attempt's follow. |
| 1051 | delete drafts[v.id]; |
| 1052 | var body = shownDraft && shownDraft.querySelector("[data-stream-text]"); |
| 1053 | if (body) { |
| 1054 | delete body.draft; |
| 1055 | body.textContent = ""; |
| 1056 | } |
| 1057 | } |
| 1058 | // Going again on a connection: the status and the card go. |
| 1059 | if (heldNow || feed.querySelector('[data-message] [data-waiting-connection]')) refreshSoon(); |
| 1060 | } else if (v.state === "replied" && v.reply_id) { |
| 1061 | ended[v.id] = true; |
| 1062 | delete queued[v.id]; |
| 1063 | notes(); |
| 1064 | } else if (v.state === "replied" && !v.reply_id) { |
| 1065 | // A turn that ended with nothing to say (an empty explore). |
| 1066 | delete drafts[v.id]; |
| 1067 | ended[v.id] = true; |
| 1068 | delete queued[v.id]; |
| 1069 | notes(); |
| 1070 | var quiet = feed.querySelector('[equipo-thinking][data-turn="' + CSS.escape(v.id) + '"]'); |
| 1071 | if (quiet) quiet.remove(); |
| 1072 | } else if (v.state === "failed" || v.state === "cancelled") { |
| 1073 | delete drafts[v.id]; |
| 1074 | ended[v.id] = true; |
| 1075 | delete queued[v.id]; |
| 1076 | notes(); |
| 1077 | var el = feed.querySelector('[equipo-thinking][data-turn="' + CSS.escape(v.id) + '"]'); |
| 1078 | if (el) el.remove(); |
| 1079 | // A move-in that gave way to the person, or stopped, is not the |
| 1080 | // person's turn: it says nothing and carries on later. |
| 1081 | if (v.kind) return; |
| 1082 | var note = template("equipo-ended-template"); |
| 1083 | note.dataset.ended = v.id; |
| 1084 | // A batch (messages sent while another turn ran) says them all. |
| 1085 | note.querySelector("p").textContent = v.state !== "failed" ? form.dataset.cancelled : v.reason === "runner_storage_full" && form.dataset.failedStorage ? form.dataset.failedStorage : (v.message_ids || []).length > 1 && form.dataset.failedMany ? form.dataset.failedMany : form.dataset.failed; |
| 1086 | feed.append(note); |
| 1087 | scroll(); |
| 1088 | // Why it failed, the account, and Try again are the server's. |
| 1089 | if (v.state === "failed") refreshSoon(); |
| 1090 | } |
| 1091 | } else if (type === "activity") { |
| 1092 | showActivity(v); |
| 1093 | } else if (type === "card" || type === "task" || type === "step") { |
| 1094 | // Cards (and the tasks on them) are rendered by the server, like |
| 1095 | // committed replies. A step that starts or stops starts or stops |
| 1096 | // its track's pulse at once; the refresh then has the last word |
| 1097 | // (a finished step may hand straight on to the next). |
| 1098 | if (type === "step" && v && v.task_id) { |
| 1099 | // A held step reports running while it waits: it is paused, not at work. |
| 1100 | var on = v.state === "running" && !v.hold && !v.paused; |
| 1101 | if (on || v.state === "failed" || v.state === "cancelled") { |
| 1102 | document.querySelectorAll('[data-track-task="' + CSS.escape(v.task_id) + '"] > [aria-current="step"]').forEach(function (li) { li.toggleAttribute("data-working", on); }); |
| 1103 | if (window.equipoPulse) window.equipoPulse(document.body); |
| 1104 | } |
| 1105 | } |
| 1106 | refreshSoon(); |
| 1107 | } else if (type === "runner" && offline && v.role !== "worker") { |
| 1108 | // The offline line is the primary's: a worker going offline is not |
| 1109 | // the coordinator going away. |
| 1110 | offline.hidden = !!v.online; |
| 1111 | } |
| 1112 | } |
| 1113 | // ⋯ on a receipt shows its actions (touch screens have no hover). |
| 1114 | feed.addEventListener("click", function (event) { |
| 1115 | var more = event.target.closest("[equipo-receipt-more]"); |
| 1116 | if (!more) return; |
| 1117 | var card = more.closest("[equipo-receipt]"); |
| 1118 | var open = !card.hasAttribute("data-open"); |
| 1119 | card.toggleAttribute("data-open", open); |
| 1120 | more.setAttribute("aria-expanded", String(open)); |
| 1121 | }); |
| 1122 | // "Show the conversation" opens an earlier day in place (its link, |
| 1123 | // ?day=, is the page without script); "Hide the conversation" closes |
| 1124 | // it. The day's box stays where the reader is looking. |
| 1125 | feed.addEventListener("click", function (event) { |
| 1126 | var toggle = event.target.closest("[data-day-toggle]"); |
| 1127 | if (!toggle || event.button || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; |
| 1128 | event.preventDefault(); |
| 1129 | var day = toggle.dataset.dayToggle; |
| 1130 | var opening = !days.has(day); |
| 1131 | if (opening) days.add(day); else days.delete(day); |
| 1132 | toggle.setAttribute("aria-busy", "true"); |
| 1133 | following = false; |
| 1134 | function place() { |
| 1135 | var li = feed.querySelector('[equipo-rollup][data-day="' + CSS.escape(day) + '"]'); |
| 1136 | if (!li) return; |
| 1137 | if (box) { |
| 1138 | box.scrollTop += li.getBoundingClientRect().top - box.getBoundingClientRect().top - 8; |
| 1139 | following = atBottom(); |
| 1140 | } |
| 1141 | var again = li.querySelector("[data-day-toggle]"); |
| 1142 | if (again) again.focus({ preventScroll: true }); |
| 1143 | } |
| 1144 | refreshed().then(place, function () { |
| 1145 | if (opening) days.delete(day); else days.add(day); |
| 1146 | toggle.removeAttribute("aria-busy"); |
| 1147 | }); |
| 1148 | }); |
| 1149 | // Card actions preserve the card on failure and expose the result in place. |
| 1150 | var cardBusy = new Map(), cardDrafts = new Map(), cardOpen = new Set(), reportOpen = new Map(), cardSuccess = new Map(), toastTimer; |
| 1151 | function cardSubmit(f, button) { |
| 1152 | var card = f.closest("[data-card]"), id = card && card.dataset.card; |
| 1153 | if (id && cardBusy.has(id)) return; |
| 1154 | var body = new URLSearchParams(new FormData(f, button)); |
| 1155 | var previous = button && button.innerHTML; |
| 1156 | var access = button && button.matches("[data-access-approve]"); |
| 1157 | if (access) { |
| 1158 | window.open(button.dataset.approveUrl, "_blank", "noopener,noreferrer"); |
| 1159 | button.hidden = true; |
| 1160 | card.querySelector("[data-access-waiting]").hidden = false; |
| 1161 | card.querySelector("[data-access-reopen]").hidden = false; |
| 1162 | } |
| 1163 | // An answer to a card (not a reply in a thread, which follows inside |
| 1164 | // the card) settles at the bottom, where what follows it shows, as a |
| 1165 | // send does (Paul, 2026-11-27). |
| 1166 | var answer = !access && /\/answer$/.test(new URL(f.action, location.href).pathname) && !f.closest("[equipo-subchat]"); |
| 1167 | var controls = card || f; |
| 1168 | if (id) cardBusy.set(id, card); |
| 1169 | controls.setAttribute("aria-busy", "true"); |
| 1170 | controls.querySelectorAll("button").forEach(function (b) { b.disabled = true; }); |
| 1171 | if (button) { button.setAttribute("aria-busy", "true"); button.textContent = button.dataset.busyLabel || root.dataset.cardBusy; } |
| 1172 | var error = controls.querySelector("[equipo-card-error]"); |
| 1173 | if (error) error.hidden = true; |
| 1174 | fetch(f.action, { method: "POST", credentials: "same-origin", headers: { "Accept": "application/json" }, body: body }) |
| 1175 | .then(function (r) { if (!r.ok) throw new Error(r.status === 409 ? "stale" : "card"); |
| 1176 | if (id) { cardBusy.delete(id); if (body.get("aside") === null) { cardDrafts.delete(id); f.querySelectorAll("textarea").forEach(function (el) { el.value=""; }); } } |
| 1177 | if (id && button && button.dataset.successLabel) cardSuccess.set(id, {label:button.dataset.successLabel, state:button.dataset.successState}); |
| 1178 | if (f.matches("[equipo-turn-stop]")) return; |
| 1179 | return refreshed(); |
| 1180 | }).then(function () { |
| 1181 | if (answer) scroll(true); |
| 1182 | else if (body.get("aside") === "true") { |
| 1183 | var stub = feed.querySelector('[data-card="' + CSS.escape(id) + '"] [equipo-aside-stub]'); |
| 1184 | var toast = root.querySelector("[equipo-roster-toast]"); |
| 1185 | if (stub && toast) { |
| 1186 | toast.replaceChildren(document.createTextNode(root.dataset.asideLabel), stub.querySelector("form").cloneNode(true)); |
| 1187 | toast.hidden = false; |
| 1188 | // Re-pin before the smaller scroll area can report a scroll |
| 1189 | // event and clear following. Stop stays above the composer. |
| 1190 | scroll(); |
| 1191 | clearTimeout(toastTimer); toastTimer = setTimeout(function () { toast.hidden = true; scroll(); }, 7000); |
| 1192 | var undo = stub.querySelector("button"); if (undo) undo.focus({preventScroll:true}); |
| 1193 | } |
| 1194 | } else if (body.get("aside") === "false") { |
| 1195 | var toast = root.querySelector("[equipo-roster-toast]"); if (toast) toast.hidden = true; |
| 1196 | var restored = feed.querySelector('[data-card="' + CSS.escape(id) + '"] [data-set-aside]'); if (restored) restored.focus({preventScroll:true}); |
| 1197 | } |
| 1198 | }).catch(function (e) { |
| 1199 | if (id) cardBusy.delete(id); |
| 1200 | controls.removeAttribute("aria-busy"); |
| 1201 | controls.querySelectorAll("button").forEach(function (b) { b.disabled = false; }); |
| 1202 | if (button) { button.removeAttribute("aria-busy"); button.innerHTML = previous; } |
| 1203 | if (access) { |
| 1204 | button.hidden = false; |
| 1205 | card.querySelector("[data-access-waiting]").hidden = true; |
| 1206 | card.querySelector("[data-access-reopen]").hidden = true; |
| 1207 | } |
| 1208 | if (!error) { error = document.createElement("p"); error.setAttribute("equipo-card-error", ""); error.setAttribute("role", "alert"); controls.append(error); } |
| 1209 | error.hidden = false; |
| 1210 | error.textContent = e.message === "stale" ? root.dataset.cardStale : root.dataset.cardFailed; |
| 1211 | var retry = document.createElement("button"); retry.type = "button"; retry.setAttribute("equipo-link", ""); retry.textContent = root.dataset.cardRetry; |
| 1212 | retry.addEventListener("click", function () { if (e.message === "stale") refreshed(); else cardSubmit(f, button); }); error.append(retry); |
| 1213 | }); |
| 1214 | } |
| 1215 | root.addEventListener("click", function(event) { |
| 1216 | var talk=event.target.closest("[data-report-talk]"); |
| 1217 | if (talk && !talk.disabled) { |
| 1218 | var report=document.getElementById(talk.getAttribute("aria-controls")); report.open=!report.open; |
| 1219 | talk.closest("[data-card]").querySelectorAll("[data-report-talk]").forEach(function(button) { button.setAttribute("aria-expanded", String(report.open)); }); |
| 1220 | if (report.open) { var input=report.querySelector("textarea"); if(input) input.focus({preventScroll:true}); } |
| 1221 | return; |
| 1222 | } |
| 1223 | var open=event.target.closest("[data-thread-open]"); if(!open || open.disabled)return; |
| 1224 | var drawer=open.closest("[data-card]").querySelector("[data-direction-thread]"); drawer.open=true; drawer.querySelector("textarea").focus(); |
| 1225 | }); |
| 1226 | root.addEventListener("submit", function (event) { |
| 1227 | var f = event.target.closest("[data-card-form]"); if (!f) return; |
| 1228 | event.preventDefault(); |
| 1229 | // A toast uses the live stub's form, so it has the card's revision. |
| 1230 | if (f.closest("[equipo-roster-toast]")) { |
| 1231 | var match = feed.querySelector('[equipo-aside-stub] form[action="' + CSS.escape(f.getAttribute("action")) + '"]'); |
| 1232 | if (match) cardSubmit(match, match.querySelector("button")); else f.closest("[equipo-roster-toast]").hidden=true; |
| 1233 | } else cardSubmit(f, event.submitter); |
| 1234 | }); |
| 1235 | // Sending stays on this page: no navigation, so no page transition. The |
| 1236 | // bubble shows at once; the background post uses the form's own action |
| 1237 | // (the person API's POST is for device bearers) with a fresh request id, |
| 1238 | // and the event stream's committed message reconciles it by id. |
| 1239 | var local = new Set(); |
| 1240 | var input = form.querySelector("textarea"); |
| 1241 | function requestID() { |
| 1242 | return window.crypto && crypto.randomUUID ? crypto.randomUUID() : Date.now().toString(36) + Math.random().toString(36).slice(2); |
| 1243 | } |
| 1244 | function place(el) { |
| 1245 | clearEmpty(); |
| 1246 | feed.insertBefore(el, feed.querySelector("[equipo-thinking]")); |
| 1247 | scroll(); |
| 1248 | } |
| 1249 | // served is a message's attachments as the server keeps them. |
| 1250 | function served(list) { |
| 1251 | return (list || []).map(function (a) { |
| 1252 | var at = "/conversation/attachments/" + encodeURIComponent(a.id); |
| 1253 | return { kind: a.kind, name: a.name, size: a.size, href: at, src: at + "/preview", width: a.width, height: a.height, id: a.id }; |
| 1254 | }); |
| 1255 | } |
| 1256 | // sentFiles draws a message's attachments inside the person's own |
| 1257 | // message, above the words: a thumbnail or a file chip. |
| 1258 | function sentFiles(el, files) { |
| 1259 | var box = el.querySelector("[equipo-message-files]"); |
| 1260 | if (!box || !files.length) return; |
| 1261 | files.forEach(function (f) { |
| 1262 | var a; |
| 1263 | if (f.kind === "image") { |
| 1264 | a = document.createElement("a"); |
| 1265 | a.setAttribute("equipo-file-thumb", ""); |
| 1266 | var img = document.createElement("img"); |
| 1267 | img.src = f.src; |
| 1268 | img.alt = f.name; |
| 1269 | if (f.width) { |
| 1270 | img.width = f.width; |
| 1271 | img.height = f.height; |
| 1272 | } |
| 1273 | a.append(img); |
| 1274 | } else { |
| 1275 | a = template("equipo-file-template"); |
| 1276 | a.querySelector("[equipo-file-name]").textContent = f.name; |
| 1277 | a.querySelector("[equipo-file-size]").textContent = f.size < 1024 ? f.size + " B" : f.size < 1048576 ? Math.round(f.size / 1024) + " KB" : (f.size / 1048576).toFixed(1) + " MB"; |
| 1278 | } |
| 1279 | a.href = f.href; |
| 1280 | a.target = "_blank"; |
| 1281 | a.rel = "noopener"; |
| 1282 | if (f.id) a.dataset.attachment = f.id; |
| 1283 | box.append(a); |
| 1284 | }); |
| 1285 | box.hidden = false; |
| 1286 | } |
| 1287 | // The coordinator's line for a send, or, sent while a turn runs, the |
| 1288 | // quiet note: the message waits its turn. |
| 1289 | function lineOrNote(el, who) { |
| 1290 | el.queuedAtSend = behind("", true); |
| 1291 | if (!el.queuedAtSend) return optimistic(who); |
| 1292 | notes(); |
| 1293 | return null; |
| 1294 | } |
| 1295 | function post(el, text, id, extra, files, line) { |
| 1296 | el.dataset.pending = ""; |
| 1297 | delete el.dataset.sendFailed; |
| 1298 | var old = el.querySelector("[data-retry-send]"); |
| 1299 | if (old) old.remove(); |
| 1300 | var said = el.querySelector("[data-send-error]"); |
| 1301 | if (said) said.remove(); |
| 1302 | var params = new URLSearchParams(extra || {}); |
| 1303 | params.set("body", text); |
| 1304 | params.set("request_id", id); |
| 1305 | (files || []).forEach(function (f) { params.append("attachment", f); }); |
| 1306 | fetch(form.action, { method: "POST", credentials: "same-origin", headers: { "Accept": "application/json" }, body: params }) |
| 1307 | .then(function (r) { |
| 1308 | if (r.ok) return r.json(); |
| 1309 | // The one refusal that says why (the runner holding the session is |
| 1310 | // offline, by name); any other is the plain retry. |
| 1311 | return r.json().catch(function () { return null; }).then(function (body) { |
| 1312 | var err = new Error("send"); |
| 1313 | var e = body && body.error; |
| 1314 | if (r.status === 409 && e && e.code === "runner_offline" && typeof e.message === "string") err.say = e.message; |
| 1315 | throw err; |
| 1316 | }); |
| 1317 | }) |
| 1318 | .then(function (sent) { |
| 1319 | local.delete(el); |
| 1320 | delete el.dataset.pending; |
| 1321 | if (!thread && sent.turn) { |
| 1322 | // The send's view of its turn, unless an event said more since. |
| 1323 | if ((sent.turn.revision || 0) > (revs[sent.turn.id] || 0)) { |
| 1324 | if (sent.turn.state === "queued" && behind(sent.turn.id)) queued[sent.turn.id] = true; |
| 1325 | else delete queued[sent.turn.id]; |
| 1326 | } |
| 1327 | el.dataset.turnId = sent.turn.id; |
| 1328 | } |
| 1329 | // A conversation send names its turn; a thread question is its own. |
| 1330 | claim(line, thread ? sent.message.id : sent.turn && sent.turn.id); |
| 1331 | notes(); |
| 1332 | var shown = feed.querySelector('[data-message="' + CSS.escape(sent.message.id) + '"]'); |
| 1333 | if (shown && shown !== el) { |
| 1334 | el.remove(); |
| 1335 | notes(); |
| 1336 | return; |
| 1337 | } |
| 1338 | el.dataset.message = sent.message.id; |
| 1339 | // The post landed before its event: the attachments become the |
| 1340 | // server's (links that work; an upload that failed meanwhile goes). |
| 1341 | var box = el.querySelector("[equipo-message-files]"); |
| 1342 | if (box && !box.hidden) { |
| 1343 | box.replaceChildren(); |
| 1344 | box.hidden = true; |
| 1345 | sentFiles(el, served(sent.message.attachments)); |
| 1346 | } |
| 1347 | }) |
| 1348 | .catch(function (err) { |
| 1349 | // Nothing was sent: no line waits for a reply, nor a note. |
| 1350 | drop(line); |
| 1351 | el.queuedAtSend = false; |
| 1352 | notes(); |
| 1353 | delete el.dataset.pending; |
| 1354 | el.dataset.sendFailed = ""; |
| 1355 | var retry = document.createElement("button"); |
| 1356 | retry.type = "button"; |
| 1357 | retry.setAttribute("rst-btn", ""); |
| 1358 | retry.dataset.retrySend = ""; |
| 1359 | retry.textContent = form.dataset.retry; |
| 1360 | retry.addEventListener("click", function () { post(el, text, id, extra, files, lineOrNote(el, extra.specialist)); }); |
| 1361 | var bubble = el.querySelector("[equipo-bubble]"); |
| 1362 | if (err && err.say) { |
| 1363 | // The server's line, as text only. |
| 1364 | var why = document.createElement("p"); |
| 1365 | why.dataset.sendError = ""; |
| 1366 | why.textContent = err.say; |
| 1367 | bubble.append(why); |
| 1368 | } |
| 1369 | bubble.append(retry); |
| 1370 | }); |
| 1371 | } |
| 1372 | function send() { |
| 1373 | // Attachments (chat-attach.js, loaded after this) belong to the |
| 1374 | // conversation's composer. |
| 1375 | var attach = form.hasAttribute("data-upload") ? window.EquipoAttach : null; |
| 1376 | var text = input.value.trim(); |
| 1377 | var waiting = attach ? attach.count() : 0; |
| 1378 | if (!text && !waiting) return; |
| 1379 | var taken = waiting ? attach.take() : null; |
| 1380 | var who = thread ? askedOf() : ""; |
| 1381 | input.value = ""; |
| 1382 | input.focus(); |
| 1383 | var el = template("equipo-own-template"); |
| 1384 | el.dataset.message = ""; |
| 1385 | el.querySelector("[equipo-message-body]").textContent = text; |
| 1386 | el.querySelector("time").textContent = new Date().toTimeString().slice(0, 5); |
| 1387 | // The attachments show at once, from this device's copies. |
| 1388 | if (taken) sentFiles(el, taken.items.map(function (i) { return { kind: i.preview ? "image" : "file", name: i.name, size: i.file.size, href: i.preview || "#", src: i.preview }; })); |
| 1389 | local.add(el); |
| 1390 | lastSend = Date.now(); |
| 1391 | place(el); |
| 1392 | // The coordinator's line, now: nothing waits on the network. Sent |
| 1393 | // while a turn runs, the message waits its turn: the note instead. |
| 1394 | var line = lineOrNote(el, who); |
| 1395 | scroll(true); |
| 1396 | // The form's other fields as they are now (who a question is for). |
| 1397 | var extra = {}; |
| 1398 | form.querySelectorAll("input[type=hidden][name]").forEach(function (i) { |
| 1399 | if (i.name !== "request_id") extra[i.name] = i.value; |
| 1400 | }); |
| 1401 | var id = requestID(); |
| 1402 | if (taken) { |
| 1403 | // The post waits for the uploads still going; one that failed stays |
| 1404 | // out (the composer says so), and nothing left to send sends nothing. |
| 1405 | el.dataset.pending = ""; |
| 1406 | taken.ready.then(function (files) { |
| 1407 | if (!files.length && !text) { |
| 1408 | local.delete(el); |
| 1409 | el.remove(); |
| 1410 | drop(line); |
| 1411 | return; |
| 1412 | } |
| 1413 | post(el, text, id, extra, files.map(function (f) { return f.id; }), line); |
| 1414 | }); |
| 1415 | } else { |
| 1416 | post(el, text, id, extra, undefined, line); |
| 1417 | } |
| 1418 | form.dispatchEvent(new CustomEvent("equipo:sent")); |
| 1419 | } |
| 1420 | form.addEventListener("submit", function (event) { event.preventDefault(); send(); }); |
| 1421 | // Enter sends on a keyboard and Shift+Enter starts a line. On a touch |
| 1422 | // screen Return starts a line and the arrow sends. |
| 1423 | var touch = window.matchMedia ? matchMedia("(hover: none) and (pointer: coarse)") : null; |
| 1424 | input.addEventListener("keydown", function (event) { |
| 1425 | if (event.key === "Enter" && !event.shiftKey && !event.isComposing && event.keyCode !== 229 && !(touch && touch.matches)) { |
| 1426 | event.preventDefault(); |
| 1427 | send(); |
| 1428 | } |
| 1429 | }); |
| 1430 | |
| 1431 | function open() { |
| 1432 | source = new EventSource("/api/v1/events?after=" + cursor); |
| 1433 | ["message", "turn", "delta", "runner", "activity", "card", "task", "step", "question", "thinking"].forEach(function (type) { |
| 1434 | source.addEventListener(type, function (event) { failures = 0; apply(type, event.data); }); |
| 1435 | }); |
| 1436 | source.addEventListener("ping", function () { failures = 0; }); |
| 1437 | source.onerror = function () { |
| 1438 | source.close(); |
| 1439 | // A cursor past retention (410) or a lost session: the page itself |
| 1440 | // is the snapshot. |
| 1441 | // Past retention (410) or a lost session: read the page again in |
| 1442 | // place, take its cursor, and follow from there. |
| 1443 | if (++failures > 4) { |
| 1444 | failures = 0; |
| 1445 | fetch(location.pathname, { credentials: "same-origin", headers: { "Accept": "text/html" } }) |
| 1446 | .then(function (r) { return r.text(); }) |
| 1447 | .then(function (body) { |
| 1448 | var page = new DOMParser().parseFromString(body, "text/html").querySelector("[data-chat-stream]"); |
| 1449 | if (page) cursor = Math.max(cursor, Number(page.dataset.cursor) || 0); |
| 1450 | refreshSoon(); |
| 1451 | open(); |
| 1452 | }) |
| 1453 | .catch(function () { setTimeout(open, 10000); }); |
| 1454 | return; |
| 1455 | } |
| 1456 | setTimeout(open, 1000 * failures); |
| 1457 | }; |
| 1458 | } |
| 1459 | // The keyboard on a phone shrinks the visual viewport, not the layout |
| 1460 | // one, and Safari pans the visual viewport down to the focused field. |
| 1461 | // The chat follows both: sized to what is visible and placed where it |
| 1462 | // is (--equipo-vvtop), with the window kept unscrolled, so the composer |
| 1463 | // sits on the keyboard. The newest item stays above the composer by |
| 1464 | // scrolling the feed, never the window. A growing composer re-pins too. |
| 1465 | // (Browsers that honour interactive-widget=resizes-content shrink the |
| 1466 | // layout viewport instead, and the offset stays 0.) |
| 1467 | var chat = document.querySelector("[equipo-conversation]"); |
| 1468 | function fit() { |
| 1469 | var vv = window.visualViewport, root = document.documentElement; |
| 1470 | if (vv) { |
| 1471 | if (chat && (window.scrollY || window.scrollX)) window.scrollTo(0, 0); |
| 1472 | if (chat && document.body.scrollTop) document.body.scrollTop = 0; |
| 1473 | root.style.setProperty("--equipo-vvh", vv.height + "px"); |
| 1474 | if (chat) root.style.setProperty("--equipo-vvtop", Math.max(0, vv.offsetTop + window.scrollY) + "px"); |
| 1475 | root.toggleAttribute("data-keyboard", vv.height < window.innerHeight - 120); |
| 1476 | } |
| 1477 | scroll(); |
| 1478 | } |
| 1479 | if (window.visualViewport) { |
| 1480 | window.visualViewport.addEventListener("resize", fit); |
| 1481 | window.visualViewport.addEventListener("scroll", fit); |
| 1482 | } |
| 1483 | if (window.ResizeObserver) { |
| 1484 | var observer = new ResizeObserver(function () { scroll(); }); |
| 1485 | if (composer) observer.observe(composer); |
| 1486 | observer.observe(feed); |
| 1487 | } |
| 1488 | fit(); |
| 1489 | open(); |
| 1490 | tick(); |
| 1491 | if (!placeAfterReload()) scroll(true); |
| 1492 | })(); |
| 1493 | |