@polycode-projects/the-mechanical-code-talker 5.0.33 → 5.0.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polycode-projects/the-mechanical-code-talker",
3
- "version": "5.0.33",
3
+ "version": "5.0.34",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "The Mechanical Code Talker (tmct) — a tolerant, offline, $0 chat surface that guides you toward precision queries about a software repository. ELIZA/PARRY-style but domain-obsessed with code. No model calls; indexes a repo on request (tmct index) or reads any producer's graph.",
@@ -50,11 +50,20 @@ function rowObservedMs(row) {
50
50
  return toMs(row.createdAt || "");
51
51
  }
52
52
 
53
+ /** Does this provenance carry a news/research tag anywhere in it? True for a
54
+ * bare `news:…` and for both ingest wrappers (`extracted:news:…`,
55
+ * `optimistic-extract:news:…`), which is what the live poll path writes. The
56
+ * window filter below and any surface counting "facts from news" read the
57
+ * same rule from here, so a tile can never drift from the feed. */
58
+ export function isNewsProvenance(provenance) {
59
+ return NEWS_WINDOW_PROVENANCE_RE.test(String(provenance || ""));
60
+ }
61
+
53
62
  export function newsWindowRows(rows, { now, windowMs }) {
54
63
  const nowMs = toMs(now);
55
64
  const startMs = nowMs - windowMs;
56
65
  return rows.filter((row) => {
57
- if (!NEWS_WINDOW_PROVENANCE_RE.test(String(row.provenance || ""))) return false;
66
+ if (!isNewsProvenance(row.provenance)) return false;
58
67
  const t = rowObservedMs(row);
59
68
  return Number.isFinite(t) && t >= startMs && t <= nowMs;
60
69
  });
@@ -56,7 +56,7 @@ import { basename, join, resolve } from "node:path";
56
56
  import { runTurn, uuidv7, stripLeadingDiscourseAdverb } from "./chat.mjs";
57
57
  import { beginsWithVowelSound, grammarRules } from "./finish.mjs";
58
58
  import { splitSentencesPreservingPaths, stripCitationResidue } from "./sentences.mjs";
59
- import { loadMemory, readFactRows, appendFact } from "../adapters/memory/core.mjs";
59
+ import { loadMemory, readFactRows, appendFact, removeFacts } from "../adapters/memory/core.mjs";
60
60
  import { loadConfig } from "../adapters/config.mjs";
61
61
  import { touchedFactRows } from "../domain/memory/touched-facts.mjs";
62
62
  import { normFactTerm } from "../domain/hash.mjs";
@@ -86,16 +86,28 @@ export function parseArgs(argv) {
86
86
 
87
87
  /**
88
88
  * Run one already-split sentence through runTurn against `memoryDir`, and
89
- * report the Fact rows THIS turn actually touched. Returns { recognized, rows }
90
- * — `recognized` true iff runTurn's own record called this a stored assertion,
91
- * `rows` the Fact rows it touched (possibly empty for a Rule-only write).
89
+ * report the Fact rows THIS turn actually touched. Returns { recognized, rows,
90
+ * afterRows } — `recognized` true iff runTurn's own record called this a
91
+ * stored assertion, `rows` the Fact rows it touched (possibly empty for a
92
+ * Rule-only write), `afterRows` the post-turn fold when one was taken.
93
+ *
94
+ * `beforeRows` is the caller's already-folded view of the store. Folding is
95
+ * the single most expensive thing an ingest does — three quarters of a second
96
+ * on a browser-sized graph — so the caller threads one fold from sentence to
97
+ * sentence instead of paying a fresh one per candidate.
92
98
  */
93
- async function runSentence(sentence, { config, memoryDir, env }) {
94
- const before = readFactRows(await loadMemory(memoryDir));
99
+ async function runSentence(sentence, { config, memoryDir, env, beforeRows }) {
100
+ const before = beforeRows || readFactRows(await loadMemory(memoryDir));
101
+ if (ingestYield) await ingestYield();
95
102
  const { record, answer } = await runTurn(sentence, { config, memoryDir, sessionId: uuidv7(), env });
96
- if (record?.via !== "assert" || record?.miss) return { recognized: false, rows: [], decline: String(answer || "") };
103
+ // Only an assert turn can have written a Fact, so only an assert turn earns
104
+ // the post-turn fold; every other turn hands the caller's own view straight
105
+ // back untouched.
106
+ if (record?.via !== "assert") return { recognized: false, rows: [], afterRows: before, decline: String(answer || "") };
107
+ if (ingestYield) await ingestYield();
97
108
  const after = readFactRows(await loadMemory(memoryDir));
98
- return { recognized: true, rows: touchedFactRows(before, after) };
109
+ if (record?.miss) return { recognized: false, rows: [], afterRows: after, decline: String(answer || "") };
110
+ return { recognized: true, rows: touchedFactRows(before, after), afterRows: after };
99
111
  }
100
112
 
101
113
  /** The recognizer's own words for why it turned a sentence down, when it named
@@ -551,6 +563,66 @@ export function clauseCandidates(sentence, { nlp } = {}) {
551
563
  return out;
552
564
  }
553
565
 
566
+ // A stored term names a thing. These words open a predicate remainder or a new
567
+ // clause, so a term that STARTS with one is the tail of a sentence a recognizer
568
+ // frame over-read, never an entity — "has a population of 1,683,115" and "and
569
+ // killed his two grandparents" are both that shape, and both surface as a feed
570
+ // card's own title once they reach the graph.
571
+ const FRAGMENT_LEAD_WORDS = new Set([
572
+ "and", "or", "but", "because", "since", "although", "though", "whereas", "while", "so",
573
+ "that", "which", "who", "whom", "whose", "if", "when", "then", "also", "however",
574
+ "is", "are", "was", "were", "be", "been", "being", "am", "has", "have", "had",
575
+ "do", "does", "did", "can", "could", "will", "would", "should", "may", "might", "must",
576
+ "of", "in", "on", "at", "for", "to", "with", "from", "by", "as", "into", "onto",
577
+ "over", "under", "after", "before", "between", "during", "about", "near", "through",
578
+ "against", "among", "within", "without", "per",
579
+ ]);
580
+ // Longest a stored term may run. Real multi-word entities are short compounds
581
+ // ("string instrument", "american guitarist"); past this a "term" is a clause
582
+ // the split lost the subject of.
583
+ const MAX_TERM_WORDS = 6;
584
+ // The tags a MULTI-WORD term's leading token may not carry — the POS reading
585
+ // of the same rule FRAGMENT_LEAD_WORDS states lexically, so an unlisted verb
586
+ // ("killed", "borders") is caught the same way a listed auxiliary is. A
587
+ // one-word term is exempt: a bare verb is a perfectly good object for a
588
+ // capability or relation fact ("a cell is capable of grow"), and a single word
589
+ // is never the clause fragment this rule exists to catch.
590
+ const FRAGMENT_LEAD_TAGS = new Set(["VERB", "AUX", "ADP", "CCONJ", "SCONJ", "PART"]);
591
+
592
+ /** Does `term` read as a thing's name rather than a clause fragment? Bounds
593
+ * the word count and rejects a leading conjunction, auxiliary or preposition.
594
+ * Used to keep an over-read recognizer frame's predicate remainder out of the
595
+ * graph, where it would otherwise hub a feed card. */
596
+ export function readsAsEntityTerm(term, nlp) {
597
+ const text = String(term ?? "").trim();
598
+ if (!text) return false;
599
+ const words = text.split(/\s+/);
600
+ if (words.length > MAX_TERM_WORDS) return false;
601
+ const first = words[0].toLowerCase().replace(/^[^a-z0-9]+/, "");
602
+ if (!first) return false;
603
+ if (FRAGMENT_LEAD_WORDS.has(first)) return false;
604
+ if (words.length === 1) return true;
605
+ const engine = nlp === undefined ? winkInstance() : nlp;
606
+ if (!engine) return true;
607
+ try {
608
+ const pos = engine.readDoc(text).tokens().out(engine.its.pos);
609
+ if (pos.length && FRAGMENT_LEAD_TAGS.has(pos[0])) return false;
610
+ } catch { /* an untaggable term falls back to the lexical rule above */ }
611
+ return true;
612
+ }
613
+
614
+ const readsAsEntityFact = (fact, nlp) => readsAsEntityTerm(fact.subject, nlp) && readsAsEntityTerm(fact.object, nlp);
615
+
616
+ // A host that shares one thread with a UI hands the thread back through this;
617
+ // a Node run leaves it unset and pays nothing.
618
+ let ingestYield = null;
619
+
620
+ /** Sets the function `ingestText` awaits between sentences so a browser can
621
+ * paint and answer input while a long article grounds. Pass null to clear. */
622
+ export function setIngestYield(fn) {
623
+ ingestYield = typeof fn === "function" ? fn : null;
624
+ }
625
+
554
626
  // The pronoun subjects a bounded carry substitutes with the paragraph's last
555
627
  // grounded subject. Ingest only — a chat turn resolves "it"/"they" against the
556
628
  // live focus, never a stale paragraph carry.
@@ -663,13 +735,41 @@ export async function ingestText(text, {
663
735
  // landed.
664
736
  const cleanedSentences = [];
665
737
 
738
+ // One fold, threaded through every candidate below. A fold costs about a
739
+ // second on a browser-sized graph and the old shape paid two per candidate,
740
+ // which is what made a poll block the page for minutes.
741
+ let currentRows = readFactRows(await loadMemory(dir));
742
+ // Facts this call has already written its own tag onto. Their provenance in
743
+ // `currentRows` is a tag behind, so a later sentence would otherwise read
744
+ // them back as freshly touched; skipping them is what a re-fold would have
745
+ // said, without the re-fold.
746
+ const taggedIds = new Set();
747
+
666
748
  // One recognized read of some text form: null when the strict recognizer
667
- // grounds nothing, else the Fact rows it touched.
749
+ // grounds nothing, else the Fact rows it touched. A row whose subject or
750
+ // object reads as a clause fragment rather than an entity is retracted here
751
+ // — the recognizer has already written it by the time this sees it — and
752
+ // the sentence falls through to the optimistic tier instead.
668
753
  let lastDecline = "";
669
754
  const strictRows = async (form) => {
670
- const { recognized, rows, decline } = await runSentence(form, { config: cfg, memoryDir: dir, env: runEnv });
671
- if (!recognized) lastDecline = decline || lastDecline;
672
- return recognized && rows.length ? rows : null;
755
+ if (ingestYield) await ingestYield();
756
+ const knownIds = new Set(currentRows.map((r) => r.id));
757
+ const { recognized, rows, afterRows, decline } = await runSentence(form, {
758
+ config: cfg, memoryDir: dir, env: runEnv, beforeRows: currentRows,
759
+ });
760
+ currentRows = afterRows;
761
+ if (!recognized) { lastDecline = decline || lastDecline; return null; }
762
+ const fresh = rows.filter((row) => !taggedIds.has(row.id));
763
+ const kept = fresh.filter((row) => readsAsEntityFact(row, termNlp));
764
+ if (kept.length !== fresh.length) {
765
+ const retractIds = fresh.filter((row) => !kept.includes(row) && !knownIds.has(row.id)).map((row) => row.id);
766
+ if (retractIds.length) {
767
+ await removeFacts(dir, retractIds);
768
+ const retracted = new Set(retractIds);
769
+ currentRows = currentRows.filter((row) => !retracted.has(row.id));
770
+ }
771
+ }
772
+ return kept.length ? kept : null;
673
773
  };
674
774
 
675
775
  try {
@@ -714,26 +814,35 @@ export async function ingestText(text, {
714
814
  subject: row.subject, predicate: row.predicate, object: row.object,
715
815
  provenance: tag, quantifier: row.quantifier || "", sentence,
716
816
  });
817
+ taggedIds.add(row.id);
717
818
  }
718
819
  continue;
719
820
  }
720
821
  const ungrounded = ungroundedTermsIn(lastDecline);
721
822
  if (ungrounded) for (const term of ungrounded) ungroundedTerms.add(term);
722
823
  if (!optimistic) continue;
723
- const candidates = optimisticTriples(cleaned, { lexicon: lex, nlp });
824
+ const candidates = optimisticTriples(cleaned, { lexicon: lex, nlp }).filter((t) => readsAsEntityFact(t, termNlp));
724
825
  if (!candidates.length) continue;
725
826
  optimisticSentences += 1;
726
827
  const tag = `optimistic-extract:${sourceTag}`;
727
828
  for (const t of candidates) {
728
- await appendFact(dir, {
829
+ const written = await appendFact(dir, {
729
830
  subject: t.subject, predicate: t.predicate, object: t.object, provenance: tag, observedAt,
730
831
  });
731
832
  optimisticFacts.push({ ...t, provenance: tag, sentence });
833
+ taggedIds.add(written.id);
732
834
  }
733
835
  }
734
836
  }
735
837
 
736
- const finalRows = readFactRows(await loadMemory(dir));
838
+ // The fact-degree scan below only reads each row's subject and object, so
839
+ // the threaded fold plus this call's own writes answers it exactly.
840
+ // `canonical` prices every endpoint's degree instead, which needs the
841
+ // store's real row set.
842
+ if (ingestYield) await ingestYield();
843
+ const finalRows = canonical
844
+ ? readFactRows(await loadMemory(dir))
845
+ : currentRows.concat(extracted, optimisticFacts);
737
846
  // ungroundedCounts widens the legacy ungroundedTerms rule (a lexicon-miss
738
847
  // named in a decline) to the fact-degree rule: every term with zero fact
739
848
  // rows, lexicon-known or not. ungroundedTerms stays a subset by
@@ -104,6 +104,11 @@ ${THEME_TOKENS_CSS}
104
104
  .btn:hover { color: var(--ink); border-color: var(--ink); }
105
105
  .btn.primary { background: var(--ink); color: var(--bg); border-color: var(--ink); }
106
106
  .btn.ghost { border-color: transparent; color: var(--muted); text-decoration: underline; text-underline-offset: 2px; }
107
+ .btn[disabled] { opacity: .55; cursor: progress; }
108
+ .btn[aria-busy="true"] { opacity: .55; cursor: progress; }
109
+ .btn[aria-busy="true"]::after { content: ""; display: inline-block; width: .5em; height: .5em; margin-left: .45em; border-radius: 50%; background: currentColor; animation: pulse 1s ease-in-out infinite; }
110
+ @keyframes pulse { 0%, 100% { opacity: .25; } 50% { opacity: 1; } }
111
+ @media (prefers-reduced-motion: reduce) { .btn[aria-busy="true"]::after { animation: none; opacity: .7; } }
107
112
  select, .urlinput { font-family: ${MONO_STACK}; font-size: .72rem; background: var(--bg); color: var(--ink); border: 1px solid var(--line); border-radius: 6px; padding: .3rem .55rem; }
108
113
  .urlinput { flex: 1 1 12rem; min-width: 8rem; }
109
114
  .sources { display: flex; flex-direction: column; gap: .3rem; margin: .6rem 0; }
@@ -117,7 +122,16 @@ ${THEME_TOKENS_CSS}
117
122
  .reqlog table { width: 100%; border-collapse: collapse; font-family: ${MONO_STACK}; font-size: .7rem; }
118
123
  .reqlog th, .reqlog td { text-align: left; padding: .2rem .4rem; border-bottom: 1px solid var(--line); }
119
124
  .reqlog tbody:empty::after { content: "no requests yet — nothing has fetched before you press start"; }
120
- .feed { display: flex; flex-direction: column; gap: .7rem; margin-bottom: 1.2rem; }
125
+ .feedwrap { margin-bottom: 1.2rem; }
126
+ .feedbar { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; margin-bottom: .45rem; }
127
+ .feedbar label { font-family: ${MONO_STACK}; font-size: .66rem; letter-spacing: .07em; text-transform: uppercase; color: var(--muted); }
128
+ .feedcount { font-family: ${MONO_STACK}; font-size: .66rem; color: var(--muted); margin-left: auto; }
129
+ .pills { display: flex; flex-wrap: wrap; gap: .3rem; margin-bottom: .5rem; }
130
+ .pill { font-family: ${MONO_STACK}; font-size: .66rem; color: var(--muted); background: var(--bg); border: 1px solid var(--line); border-radius: 99px; padding: .15rem .6rem; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
131
+ .pill:hover { color: var(--ink); border-color: var(--ink); }
132
+ .pill[aria-pressed="true"] { background: var(--ink); color: var(--bg); border-color: var(--ink); }
133
+ .feed { display: flex; flex-direction: column; gap: .7rem; max-height: 62vh; overflow-y: auto; overscroll-behavior: contain; padding-right: .25rem; }
134
+ @media (max-width: 480px) { .feedcount { margin-left: 0; flex-basis: 100%; } .feed { max-height: 70vh; } }
121
135
  .item { background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: .8rem 1rem; }
122
136
  .item .hub { font-weight: 700; font-size: 1.05rem; }
123
137
  .item .tier { font-family: ${MONO_STACK}; font-size: .64rem; padding: .05rem .5rem; border-radius: 99px; border: 1px solid var(--line); margin-left: .5rem; }
@@ -206,8 +220,20 @@ ${NEWS_STYLE}
206
220
  </table>
207
221
  </section>
208
222
 
209
- <section class="feed" id="feed" aria-label="News feed">
210
- <div class="empty" id="feedEmpty">no news items yet — the seed graph builds the first ones once it finishes loading.</div>
223
+ <section class="feedwrap" aria-label="News feed">
224
+ <div class="feedbar">
225
+ <label for="feedSort">sort</label>
226
+ <select id="feedSort">
227
+ <option value="newest" selected>newest first</option>
228
+ <option value="facts">most facts first</option>
229
+ <option value="changed">most changed first</option>
230
+ </select>
231
+ <span class="feedcount" id="feedCount" aria-live="polite"></span>
232
+ </div>
233
+ <div class="pills" id="feedPills" aria-label="Filter the feed by key term"></div>
234
+ <div class="feed" id="feed" tabindex="0">
235
+ <div class="empty" id="feedEmpty">no news items yet — the seed graph builds the first ones once it finishes loading.</div>
236
+ </div>
211
237
  </section>
212
238
 
213
239
  <section class="teach" id="teachPanel">
@@ -324,13 +350,80 @@ const SEED_BYTES = ${Number(seedBytes) || 0};
324
350
  }).join("");
325
351
  }
326
352
 
327
- async function renderFeed() {
353
+ // The last built feed and one rendered card per item, so a sort change or a
354
+ // pill toggle re-orders what is already on screen instead of rebuilding
355
+ // every card's fact list from the store again.
356
+ let feedItems = [];
357
+ const cardsByItemId = new Map();
358
+ const activePillTerms = new Set();
359
+
360
+ const MAX_PILLS = 12;
361
+
362
+ function itemMatchesActivePills(item) {
363
+ if (!activePillTerms.size) return true;
364
+ const haystack = (item.hub + " " + item.paragraph).toLowerCase();
365
+ for (const term of activePillTerms) {
366
+ if (item.hub === term || haystack.indexOf(term) !== -1) return true;
367
+ }
368
+ return false;
369
+ }
370
+
371
+ function sortedFeedItems() {
372
+ const mode = el("feedSort").value;
373
+ const items = feedItems.slice();
374
+ if (mode === "facts") items.sort((a, b) => b.factIds.length - a.factIds.length || (a.hub < b.hub ? -1 : 1));
375
+ else if (mode === "changed") items.sort((a, b) => b.changedCount - a.changedCount || (a.hub < b.hub ? -1 : 1));
376
+ return items;
377
+ }
378
+
379
+ function renderPills() {
380
+ const pillsEl = el("feedPills");
381
+ const terms = feedItems
382
+ .slice()
383
+ .sort((a, b) => b.changedCount - a.changedCount || (a.hub < b.hub ? -1 : 1))
384
+ .map((it) => it.hub)
385
+ .slice(0, MAX_PILLS);
386
+ for (const term of [...activePillTerms]) if (terms.indexOf(term) === -1) activePillTerms.delete(term);
387
+ pillsEl.innerHTML = terms.map((term) =>
388
+ '<button type="button" class="pill" data-pill-term="' + esc(term) + '" aria-pressed="'
389
+ + (activePillTerms.has(term) ? "true" : "false") + '">' + esc(term) + '</button>',
390
+ ).join("");
391
+ pillsEl.querySelectorAll("[data-pill-term]").forEach(function (btn) {
392
+ btn.addEventListener("click", function () {
393
+ const term = btn.getAttribute("data-pill-term");
394
+ if (activePillTerms.has(term)) activePillTerms.delete(term); else activePillTerms.add(term);
395
+ btn.setAttribute("aria-pressed", activePillTerms.has(term) ? "true" : "false");
396
+ paintFeed();
397
+ });
398
+ });
399
+ }
400
+
401
+ function paintFeed() {
328
402
  const feedEl = el("feed");
329
403
  const emptyEl = el("feedEmpty");
404
+ feedEl.querySelectorAll(".item").forEach((n) => n.remove());
405
+ const shown = sortedFeedItems().filter(itemMatchesActivePills);
406
+ for (const item of shown) {
407
+ const card = cardsByItemId.get(item.id);
408
+ if (card) feedEl.appendChild(card);
409
+ }
410
+ emptyEl.hidden = shown.length > 0;
411
+ if (!shown.length) {
412
+ emptyEl.textContent = feedItems.length
413
+ ? "no article matches the terms you picked — unpick a pill to see the rest."
414
+ : "no news items yet — the seed graph builds the first ones once it finishes loading.";
415
+ }
416
+ el("feedCount").textContent = shown.length === feedItems.length
417
+ ? (feedItems.length + " article" + (feedItems.length === 1 ? "" : "s"))
418
+ : (shown.length + " of " + feedItems.length + " articles");
419
+ }
420
+
421
+ async function renderFeed() {
422
+ const feedEl = el("feed");
330
423
  const feed = await window.tmct.session.buildFeed();
424
+ feedItems = feed.items;
425
+ cardsByItemId.clear();
331
426
  feedEl.querySelectorAll(".item").forEach((n) => n.remove());
332
- if (!feed.items.length) { emptyEl.hidden = false; setTile("tileFeedItems", 0, "nothing yet"); return; }
333
- emptyEl.hidden = true;
334
427
  for (const item of feed.items) {
335
428
  // One yield per card keeps the page clickable while a long feed renders.
336
429
  await new Promise((resolve) => setTimeout(resolve, 0));
@@ -344,11 +437,22 @@ const SEED_BYTES = ${Number(seedBytes) || 0};
344
437
  + '<p class="paragraph">' + esc(item.paragraph) + '</p>'
345
438
  + (sourcesText ? '<p class="sources-links">sources: ' + sourcesText + '</p>' : "")
346
439
  + '<details class="facts"><summary>' + item.factIds.length + ' facts</summary>' + facts + '</details>';
347
- feedEl.appendChild(card);
440
+ cardsByItemId.set(item.id, card);
441
+ // Each card shows the moment it is built; the paint below re-orders and
442
+ // filters what is already on screen.
443
+ if (itemMatchesActivePills(item)) { el("feedEmpty").hidden = true; feedEl.appendChild(card); }
348
444
  }
445
+ renderPills();
446
+ paintFeed();
349
447
  setTile("tileFeedItems", feed.items.length, feed.seedFallback ? "from the seed graph" : "live");
350
448
  }
351
449
 
450
+ async function renderGraphTiles() {
451
+ const stats = await window.tmct.session.stats();
452
+ setTile("tileFactsFromNews", stats.factsFromNews, stats.factsFromNews ? "polled, replayed or enriched" : "nothing ingested yet");
453
+ setTile("tileGraphSize", stats.graphSize, "facts in this session's graph");
454
+ }
455
+
352
456
  async function renderRank() {
353
457
  const rows = await window.tmct.session.rank({ limit: 8 });
354
458
  setTile("tileTermsUngrounded", rows.length, rows.length ? "ranked by occurrence" : "none yet");
@@ -371,7 +475,7 @@ const SEED_BYTES = ${Number(seedBytes) || 0};
371
475
  // just-finished poll reads back immediately while the feed's own slower,
372
476
  // yielding render catches up behind it.
373
477
  renderSourcesPanel();
374
- await Promise.all([renderFeed(), renderRank(), renderRequestLog()]);
478
+ await Promise.all([renderFeed(), renderRank(), renderRequestLog(), renderGraphTiles()]);
375
479
  renderSourcesPanel();
376
480
  window.tmct.news = Object.assign({}, window.tmct.news, {
377
481
  phase: window.tmct.session.phase,
@@ -409,15 +513,44 @@ const SEED_BYTES = ${Number(seedBytes) || 0};
409
513
  // render is deliberately slow (it yields per card), and a click that
410
514
  // lands in that window must already have its listener.
411
515
  const startBtn = el("newsStart");
412
- startBtn.textContent = window.tmct.session.consented ? "poll now" : "start polling live sources";
516
+ // Read once, here. The first render below takes a while, a visitor can
517
+ // press start inside it, and that press grants consent — so re-reading
518
+ // the flag afterwards to decide whether to replay a returning visit's
519
+ // poll would poll a second time on top of the one already running.
520
+ const returningVisit = window.tmct.session.consented;
521
+ startBtn.textContent = returningVisit ? "poll now" : "start polling live sources";
522
+
523
+ el("feedSort").addEventListener("change", paintFeed);
524
+
525
+ // A poll can run for a while, so the button reads back its own state the
526
+ // moment it is pressed and the status line follows the session's phase
527
+ // until it settles.
528
+ function markBusy(button, label) {
529
+ button.dataset.idleLabel = button.textContent;
530
+ button.textContent = label;
531
+ button.disabled = true;
532
+ button.setAttribute("aria-busy", "true");
533
+ }
534
+ function markIdle(button, label) {
535
+ button.textContent = label || button.dataset.idleLabel || button.textContent;
536
+ button.disabled = false;
537
+ button.removeAttribute("aria-busy");
538
+ }
539
+ function followPhase(label) {
540
+ el("controlsStatus").textContent = label;
541
+ const id = setInterval(function () { el("controlsStatus").textContent = window.tmct.session.phase + "…"; }, 400);
542
+ return function () { clearInterval(id); el("controlsStatus").textContent = ""; };
543
+ }
413
544
 
414
545
  startBtn.addEventListener("click", async function () {
415
- startBtn.disabled = true;
416
- el("controlsStatus").textContent = "polling…";
417
- await window.tmct.session.start();
418
- startBtn.textContent = "poll now";
419
- startBtn.disabled = false;
420
- el("controlsStatus").textContent = "";
546
+ markBusy(startBtn, "polling…");
547
+ const stopFollowing = followPhase("polling…");
548
+ try {
549
+ await window.tmct.session.start();
550
+ } finally {
551
+ stopFollowing();
552
+ markIdle(startBtn, "poll now");
553
+ }
421
554
  await renderAll();
422
555
  });
423
556
 
@@ -433,9 +566,15 @@ const SEED_BYTES = ${Number(seedBytes) || 0};
433
566
  });
434
567
 
435
568
  el("enrichNow").addEventListener("click", async function () {
436
- el("controlsStatus").textContent = "enriching…";
437
- await window.tmct.session.enrich();
438
- el("controlsStatus").textContent = "";
569
+ const enrichBtn = el("enrichNow");
570
+ markBusy(enrichBtn, "enriching…");
571
+ const stopFollowing = followPhase("enriching…");
572
+ try {
573
+ await window.tmct.session.enrich();
574
+ } finally {
575
+ stopFollowing();
576
+ markIdle(enrichBtn);
577
+ }
439
578
  await renderAll();
440
579
  });
441
580
 
@@ -494,7 +633,7 @@ const SEED_BYTES = ${Number(seedBytes) || 0};
494
633
  window.tmct.news.phase = "seeded";
495
634
  appendLog("phase: seeded");
496
635
  await renderAll();
497
- if (window.tmct.session.consented) {
636
+ if (returningVisit) {
498
637
  await window.tmct.session.start();
499
638
  await renderAll();
500
639
  }