@polycode-projects/the-mechanical-code-talker 6.0.1 → 6.0.3

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.
@@ -1,40 +1,35 @@
1
- // news-viz.mjs — news.html: a dashboard over the news capability
2
- // (PLAN_NEWS_FEED.md section 13), on the ledger.html dashboard precedent
3
- // (src/services/ledger-viz.mjs: `.dash`/`.kpirow`/`.tile`/`.tile-bars`, the
4
- // same THEME_TOKENS_CSS palette) with chat.html's seed-loading shell
5
- // (src/services/chat-page-viz.mjs: SEED_STAMP/SEED_BYTES, the tmct.seed
6
- // phase pill, loadSeedPayload/fetchWithProgress).
1
+ // news-viz.mjs — news.html: a thin client over the row service's news
2
+ // routes (PLAN_MEMORY_BACKEND.md's news.html-goes-thin revision), on the
3
+ // ledger.html dashboard precedent (src/services/ledger-viz.mjs: `.dash`/
4
+ // `.kpirow`/`.tile`/`.tile-bars`, the same THEME_TOKENS_CSS palette).
7
5
  //
8
- // The page's one behavioural promise, restated everywhere it matters: NO
9
- // third-party request fires before the visitor presses start (or, on a
10
- // returning visit, before the page replays that same consent). Every
11
- // `https://` string this renderer emits — every source's homepage link, the
12
- // embedded source-registry JSON the source-toggle list reads — sits inside
13
- // the ONE fenced block `<!-- sources:start -->` … `<!-- sources:end -->`, so
14
- // that promise is mechanically checkable: nothing outside that block ever
15
- // names a third party.
6
+ // This page carries no engine and no seed. Every card, tile, bar, source
7
+ // status line and request-log row it ever shows is read straight off one
8
+ // document — `GET /api/feed` — and nothing here recomputes any of it. The
9
+ // only client-side work is: mint a session key at the first press, POST the
10
+ // three trigger routes (poll/enrich/ingest) on their own press, wait for the
11
+ // cycle each one starts to materialize, and render the document that comes
12
+ // back. src/surfaces/web/news-browser-entry.mjs is the whole of that; this
13
+ // file is markup, CSS and the inline script wiring DOM to it.
16
14
  //
17
- // Every fetched or user-supplied string this page will ever show (a feed
18
- // item's title/summary, a source's display name, an uploaded fact row) goes
19
- // through escapeHtml at render time — the second half of the two-layer
20
- // sanitisation rule (constitution, PLAN_NEWS_FEED.md section 3); the first
21
- // half (stripMarkup at parse time) already ran in the domain/adapter layers
22
- // this page's engine calls.
15
+ // Every fetched or user-supplied string this page ever shows (a card's
16
+ // paragraph, a fact line, a source name, teach-panel text) goes through
17
+ // escapeHtml at render time — the page's one sanitisation layer, since
18
+ // nothing here parses raw prose itself; that already happened server-side,
19
+ // in the worker, before the string ever reached this document.
23
20
  import {
24
21
  THEME_TOKENS_CSS, MONO_STACK, escapeHtml, embedJson, demoEyebrowHtml, EYEBROW_LINKS_CSS,
25
22
  } from "./viz-theme.mjs";
26
- import { loadSeedPayload, fetchWithProgress, factTripleParts } from "./memory-panel-viz.mjs";
27
- import { phraseRendererSource, FACT_PREDICATE_PHRASES } from "../domain/fact-phrase.mjs";
28
23
  import { NEWS_SOURCE_RECORDS } from "../adapters/corpus/news-sources.mjs";
29
24
 
30
- const DEFAULT_TITLE = "tmct news — a dashboard over the graph, fed on your say-so";
25
+ const DEFAULT_TITLE = "tmct news — a feed the graph only shows what it can ground";
31
26
 
32
27
  const DASH_SANS_STACK = `-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif`;
33
28
 
34
29
  /** One `.tile` cell for the KPI row — the zero-state every tile renders in
35
- * before the first poll, since the dashboard's own JS overwrites every
36
- * number once the session opens. Static markup only; the live numbers are
37
- * a client-side re-render (see the inline script's `renderAll`). */
30
+ * before the first render call, since the page's own JS overwrites every
31
+ * number the moment a feed document (real or empty) is in hand. Static
32
+ * markup only. */
38
33
  function kpiTileHtml(label, id) {
39
34
  return `<div class="tile" id="${escapeHtml(id)}">
40
35
  <span class="tile-label">${escapeHtml(label)}</span>
@@ -53,8 +48,13 @@ function barPanelHtml(label, id) {
53
48
  function sourceRowsHtml(kind) {
54
49
  return NEWS_SOURCE_RECORDS.filter((r) => (kind === "kb" ? r.kind === "kb" : r.kind !== "kb")).map((r) => {
55
50
  const cls = r.kind === "kb" ? "kb" : "contemporary";
51
+ // Only the contemporary group offers a checkbox: it narrows the NEXT
52
+ // poll trigger's own `{sources:[...]}` body, never a fetch of its own.
53
+ // The kb group has no client-supplied roster in the hosted worker, so
54
+ // it renders as plain status, not a control.
55
+ const toggle = kind === "kb" ? "" : `<input type="checkbox" data-source-toggle value="${escapeHtml(r.id)}" ${r.enabledByDefault ? "checked" : ""}>`;
56
56
  return `<label class="sourcerow ${cls}" data-source-id="${escapeHtml(r.id)}">
57
- <input type="checkbox" data-source-toggle value="${escapeHtml(r.id)}" ${r.enabledByDefault ? "checked" : ""}>
57
+ ${toggle}
58
58
  <span class="sourcename">${escapeHtml(r.name)}</span>
59
59
  <a class="sourcehome" href="${escapeHtml(r.homepage)}" target="_blank" rel="noopener">homepage</a>
60
60
  <span class="sourcestatus" data-source-status>not yet polled</span>
@@ -63,18 +63,18 @@ function sourceRowsHtml(kind) {
63
63
  }
64
64
 
65
65
  /** The one fenced region carrying every third-party URL this page ever
66
- * names, in two groups the visitor can tell apart: the news feeds a poll
67
- * fetches, and the reference works enrichment looks unknown terms up in. A
68
- * reference work is never polled — ticking it arms the lookup, nothing
69
- * else. Nothing fetches merely because this markup rendered. */
66
+ * names — every source's own homepage link, and the embedded source
67
+ * registry the panel reads. No fetch happens because this markup rendered;
68
+ * the worker does the fetching, server-side, and only after a trigger this
69
+ * page's own click sent it. */
70
70
  function sourcesConfigBlockHtml() {
71
71
  return `<!-- sources:start -->
72
72
  <div class="sources" id="sourcesConfig" aria-label="News sources">
73
- <h2 class="tile-label" id="pollRosterLabel">news feeds — polled when you press start or poll once</h2>
73
+ <h2 class="tile-label" id="pollRosterLabel">news feeds — the worker polls these when you press start, narrowed to what's checked</h2>
74
74
  <div class="sourcegroup" id="pollRoster" aria-labelledby="pollRosterLabel">
75
75
  ${sourceRowsHtml("contemporary")}
76
76
  </div>
77
- <h2 class="tile-label" id="lookupRosterLabel">reference works — looked up to explain a term, never polled</h2>
77
+ <h2 class="tile-label" id="lookupRosterLabel">reference works — the worker looks a term up here to explain it, never polled</h2>
78
78
  <div class="sourcegroup" id="lookupRoster" aria-labelledby="lookupRosterLabel">
79
79
  ${sourceRowsHtml("kb")}
80
80
  </div>
@@ -108,6 +108,9 @@ ${THEME_TOKENS_CSS}
108
108
  .bbtrack { background: var(--line); border-radius: 99px; height: 5px; overflow: hidden; }
109
109
  .bbfill { display: block; height: 100%; background: var(--ink); opacity: .6; border-radius: 99px; }
110
110
  .bbn { color: var(--muted); text-align: right; font-variant-numeric: tabular-nums; }
111
+ .privacy { font-size: .78rem; color: var(--muted); margin: 0 0 .8rem; max-width: 46rem; }
112
+ .unavailable { display: none; background: var(--alert-soft); border: 1px solid var(--alert); border-radius: 6px; padding: .6rem .8rem; margin-bottom: 1rem; font-size: .84rem; }
113
+ .unavailable.shown { display: block; }
111
114
  .controls { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; background: var(--card); border: 1px solid var(--line); border-radius: 6px; padding: .6rem .7rem; margin-bottom: 1rem; }
112
115
  .btn { font-family: ${MONO_STACK}; font-size: .72rem; color: var(--muted); border: 1px solid var(--line); border-radius: 6px; padding: .3rem .65rem; background: var(--bg); }
113
116
  .btn:hover { color: var(--ink); border-color: var(--ink); }
@@ -118,8 +121,8 @@ ${THEME_TOKENS_CSS}
118
121
  .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; }
119
122
  @keyframes pulse { 0%, 100% { opacity: .25; } 50% { opacity: 1; } }
120
123
  @media (prefers-reduced-motion: reduce) { .btn[aria-busy="true"]::after { animation: none; opacity: .7; } }
121
- 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; }
122
- .urlinput { flex: 1 1 12rem; min-width: 8rem; }
124
+ select { font-family: ${MONO_STACK}; font-size: .72rem; background: var(--bg); color: var(--ink); border: 1px solid var(--line); border-radius: 6px; padding: .3rem .55rem; }
125
+ .fuzzytoggle { display: inline-flex; align-items: center; gap: .35rem; font-family: ${MONO_STACK}; font-size: .68rem; color: var(--muted); cursor: pointer; }
123
126
  .sources { display: flex; flex-direction: column; gap: .3rem; margin: .6rem 0; }
124
127
  .sources h2 { margin: .6rem 0 .1rem; }
125
128
  .sourcegroup { display: flex; flex-direction: column; gap: .3rem; }
@@ -132,7 +135,7 @@ ${THEME_TOKENS_CSS}
132
135
  .reqlog { margin-bottom: 1rem; max-width: 100%; overflow-x: auto; }
133
136
  .reqlog table { width: 100%; table-layout: fixed; border-collapse: collapse; font-family: ${MONO_STACK}; font-size: .7rem; }
134
137
  .reqlog th, .reqlog td { text-align: left; padding: .2rem .4rem; border-bottom: 1px solid var(--line); overflow-wrap: anywhere; }
135
- .reqlog tbody:empty::after { content: "no requests yet — nothing has fetched before you press start"; }
138
+ .reqlog tbody:empty::after { content: "no requests yet — nothing has been polled before you press start"; }
136
139
  .feedwrap { margin-bottom: 1.2rem; }
137
140
  .feedbar { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; margin-bottom: .45rem; }
138
141
  .feedbar label { font-family: ${MONO_STACK}; font-size: .66rem; letter-spacing: .07em; text-transform: uppercase; color: var(--muted); }
@@ -146,33 +149,47 @@ ${THEME_TOKENS_CSS}
146
149
  .item { background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: .8rem 1rem; }
147
150
  .item .hub { font-weight: 700; font-size: 1.05rem; }
148
151
  .item .tier { font-family: ${MONO_STACK}; font-size: .64rem; padding: .05rem .5rem; border-radius: 99px; border: 1px solid var(--line); margin-left: .5rem; }
149
- .item .seedtag { font-family: ${MONO_STACK}; font-size: .64rem; color: var(--muted); margin-left: .5rem; }
152
+ .item .newtag { font-family: ${MONO_STACK}; font-size: .64rem; color: var(--taught); margin-left: .5rem; }
150
153
  .item .paragraph { margin: .4rem 0; }
151
154
  .item .sources-links { font-size: .74rem; color: var(--muted); }
152
155
  .item details.facts summary { font-family: ${MONO_STACK}; font-size: .68rem; color: var(--corpus); cursor: pointer; }
153
156
  .item details.background summary { font-family: ${MONO_STACK}; font-size: .68rem; color: var(--muted); cursor: pointer; }
154
157
  .item details.background p { margin: .35rem 0 0; color: var(--muted); }
155
158
  .item .factrow { font-family: ${MONO_STACK}; font-size: .68rem; padding: .15rem 0; border-bottom: 1px dotted var(--line); }
156
- .item .facttriple { font-family: ${MONO_STACK}; font-size: .62rem; color: var(--muted); padding-left: .6rem; }
159
+ .item .factrow.factmore { color: var(--muted); border-bottom: none; }
157
160
  .empty { color: var(--muted); font-size: .85rem; border: 1px dashed var(--line); border-radius: 6px; padding: .8rem 1rem; }
158
161
  .teach { background: var(--card); border: 1px solid var(--line); border-radius: 6px; padding: .7rem .85rem; margin-bottom: 1rem; }
159
162
  .teach textarea { width: 100%; box-sizing: border-box; min-height: 90px; font-family: ${MONO_STACK}; font-size: .76rem; background: var(--bg); color: var(--ink); border: 1px solid var(--line); border-radius: 6px; padding: .5rem .6rem; }
160
163
  .teach .teachrow { display: flex; flex-wrap: wrap; gap: .5rem; margin-top: .5rem; align-items: center; }
164
+ .chat { background: var(--card); border: 1px solid var(--line); border-radius: 6px; padding: .7rem .85rem; margin-bottom: 1rem; }
165
+ .chatlog { display: flex; flex-direction: column; gap: .5rem; max-height: 40vh; overflow-y: auto; margin: .5rem 0; padding-right: .25rem; }
166
+ .chatlog:empty::after { content: "ask the graph what it knows, or teach it something new"; color: var(--muted); font-size: .8rem; }
167
+ .chatturn { display: flex; flex-direction: column; gap: .2rem; }
168
+ .chatbubble { border: 1px solid var(--line); border-radius: 6px; padding: .4rem .6rem; font-size: .84rem; max-width: 42rem; white-space: pre-wrap; }
169
+ .chatturn.you { align-items: flex-end; }
170
+ .chatturn.you .chatbubble { background: var(--bg); }
171
+ .chatturn.graph .chatbubble { background: var(--bg); }
172
+ .chatturn.error .chatbubble { border-color: var(--alert); color: var(--alert); background: var(--alert-soft); }
173
+ .chatlearned { font-family: ${MONO_STACK}; font-size: .68rem; color: var(--muted); }
174
+ .chatlearned ul { margin: .15rem 0 0; padding-left: 1.1rem; }
175
+ .chattrace summary { font-family: ${MONO_STACK}; font-size: .64rem; color: var(--muted); cursor: pointer; }
176
+ .chattrace pre { font-family: ${MONO_STACK}; font-size: .64rem; color: var(--muted); white-space: pre-wrap; margin: .3rem 0 0; }
177
+ .chatform { display: flex; gap: .4rem; }
178
+ .chatform input[type="text"] { flex: 1; font: inherit; font-family: ${MONO_STACK}; font-size: .8rem; background: var(--bg); color: var(--ink); border: 1px solid var(--line); border-radius: 6px; padding: .4rem .6rem; }
179
+ .chatform input[disabled] { opacity: .55; }
161
180
  .pagelog { font-family: ${MONO_STACK}; font-size: .68rem; color: var(--muted); max-height: 140px; overflow-y: auto; border-top: 1px solid var(--line); padding-top: .4rem; }
162
181
  `;
163
182
 
164
- /** `renderNewsHtml({ title, seedStamp, seedBytes, digestStructures })` — one
165
- * self-contained document: the dashboard, the controls row (start / poll
166
- * interval / stop & forget / source toggles / add-by-URL / enrich now / the
167
- * two fixture-replay demo buttons), the request log, the feed, and the
168
- * teach panel. `seedStamp`/`seedBytes` feed the same chat-seed.json loading
169
- * contract chat.html's own shell uses (chat-page-viz.mjs); `digestStructures`
170
- * rides through unused today, the same build-time plumbing every other
171
- * generated page threads even before it has its own digest affordance. */
172
- export function renderNewsHtml({ title = DEFAULT_TITLE, seedStamp = "", seedBytes = 0, digestStructures = [] } = {}) {
173
- const digestJson = embedJson(Array.isArray(digestStructures) ? digestStructures : []);
174
- const factPhrasesJson = embedJson(FACT_PREDICATE_PHRASES);
175
-
183
+ /** `renderNewsHtml({ title })` — one self-contained document: the dashboard,
184
+ * the controls row (start/poll, enrich now, stop & forget), the source
185
+ * panel, the request log, the feed, the teach panel, and the chat area.
186
+ * The chat area is the turn endpoint's page consumer: one input, one send,
187
+ * one transcript, over the same session UUID the feed already holds. A
188
+ * reply's text and any citation or trace text land through `textContent`/
189
+ * `createTextNode` only, never through markup built from a string — this
190
+ * page's answer text is the one thing on it never HTML-escaped-then-
191
+ * interpolated, because it never needs to be. */
192
+ export function renderNewsHtml({ title = DEFAULT_TITLE } = {}) {
176
193
  return `<!doctype html>
177
194
  <html lang="en">
178
195
  <head>
@@ -188,8 +205,12 @@ ${NEWS_STYLE}
188
205
  </head>
189
206
  <body>
190
207
  <main>
191
- <div class="eyebrow"><span>${demoEyebrowHtml("news", "news")}</span><span id="seedPill" data-sub></span></div>
192
- <h1 class="visually-hidden">news — a dashboard over the graph, fed on your say-so</h1>
208
+ <div class="eyebrow"><span>${demoEyebrowHtml("news", "news")}</span><span id="sessionPill" data-sub></span></div>
209
+ <h1 class="visually-hidden">news — a feed the graph only shows what it can ground</h1>
210
+
211
+ <p class="privacy">This session is anonymous. Pressing start keeps a random key for it in this browser; everything you poll or teach here is stored against that key on the server for seven days. Stop &amp; forget hides all of it at once, and the stored copies are gone for good within that same week.</p>
212
+
213
+ <div class="unavailable" id="serviceUnavailable" role="alert">The news service isn't answering right now, so there's nothing to show. Reload the page to try again.</div>
193
214
 
194
215
  <section class="dash" id="dash" aria-label="News metrics">
195
216
  <div class="kpirow">
@@ -197,7 +218,7 @@ ${NEWS_STYLE}
197
218
  ${kpiTileHtml("terms.ungrounded", "tileTermsUngrounded")}
198
219
  ${kpiTileHtml("facts.from-news", "tileFactsFromNews")}
199
220
  ${kpiTileHtml("graph.size", "tileGraphSize")}
200
- ${kpiTileHtml("sources.live", "tileSourcesLive")}
221
+ ${kpiTileHtml("sources.reporting", "tileSourcesLive")}
201
222
  </div>
202
223
  <div class="barpanels">
203
224
  ${barPanelHtml("terms.ranked", "panelTermsRanked")}
@@ -207,28 +228,16 @@ ${NEWS_STYLE}
207
228
 
208
229
  <div class="controls" id="controls">
209
230
  <button type="button" class="btn primary" id="newsStart">start polling live sources</button>
210
- <button type="button" class="btn" id="pollOnce">poll once</button>
211
- <button type="button" class="btn" id="stopPolling" disabled>stop polling</button>
212
- <label class="mono" for="pollInterval">poll every</label>
213
- <select id="pollInterval">
214
- <option value="0">off</option>
215
- <option value="5">5 min</option>
216
- <option value="15" selected>15 min</option>
217
- <option value="60">60 min</option>
218
- </select>
219
- <button type="button" class="btn ghost" id="stopForget">stop &amp; forget</button>
220
231
  <button type="button" class="btn" id="enrichNow">enrich now</button>
221
- <input type="text" class="urlinput" id="addSourceUrl" placeholder="add a source by url (https only)" autocomplete="off" spellcheck="false">
222
- <button type="button" class="btn" id="addSourceBtn">add</button>
223
- <button type="button" class="btn" id="replayNyt">replay recorded NYT sample</button>
224
- <button type="button" class="btn" id="replayWikipedia">replay recorded Wikipedia sample</button>
232
+ <label class="fuzzytoggle" for="fuzzyToggle"><input type="checkbox" id="fuzzyToggle" checked> fuzzy corpus match</label>
233
+ <button type="button" class="btn ghost" id="stopForget">stop &amp; forget</button>
225
234
  <span class="mono" id="controlsStatus" aria-live="polite"></span>
226
235
  </div>
227
236
 
228
237
  ${sourcesConfigBlockHtml()}
229
238
 
230
239
  <section class="reqlog" id="requestLog" aria-label="Request log">
231
- <h2 class="tile-label">request log</h2>
240
+ <h2 class="tile-label">the worker's own request log</h2>
232
241
  <table>
233
242
  <thead><tr><th>url</th><th>at</th><th>bytes</th><th>status</th></tr></thead>
234
243
  <tbody id="requestLogBody"></tbody>
@@ -247,38 +256,44 @@ ${NEWS_STYLE}
247
256
  </div>
248
257
  <div class="pills" id="feedPills" aria-label="Filter the feed by key term"></div>
249
258
  <div class="feed" id="feed" tabindex="0">
250
- <div class="empty" id="feedEmpty">no news yet — the feed only shows named people, places and events from polled sources. press poll once to fetch some.</div>
259
+ <div class="empty" id="feedEmpty">no news yet — the feed only shows named people, places and events the worker has reported. press start to fetch some.</div>
251
260
  </div>
252
261
  </section>
253
262
 
254
263
  <section class="teach" id="teachPanel">
255
264
  <h2 class="tile-label">teach the graph</h2>
256
- <textarea id="teachText" spellcheck="false" aria-label="Text or fact rows to ingest" placeholder="Paste prose, or drop a .txt/.md/.json/.jsonl file below."></textarea>
265
+ <textarea id="teachText" spellcheck="false" aria-label="Text or fact rows to ingest" placeholder="Paste prose, or drop a .txt/.md/.jsonl file below."></textarea>
257
266
  <div class="teachrow">
258
267
  <button type="button" class="btn" id="exampleProse">example: prose</button>
259
268
  <button type="button" class="btn" id="exampleJsonl">example: facts (.jsonl)</button>
260
269
  <button type="button" class="btn" id="teachBrowse">browse&hellip;</button>
261
- <input type="file" id="teachFile" accept=".txt,.md,.json,.jsonl" hidden>
270
+ <input type="file" id="teachFile" accept=".txt,.md,.jsonl" hidden>
262
271
  <button type="button" class="btn primary" id="teachIngest">ingest</button>
263
272
  <span class="mono" id="teachStatus" aria-live="polite"></span>
264
273
  </div>
265
274
  </section>
266
275
 
276
+ <section id="chatMount" aria-label="Chat">
277
+ <h2 class="tile-label">chat with the graph</h2>
278
+ <div class="chat">
279
+ <div class="chatlog" id="chatLog" aria-live="polite"></div>
280
+ <form class="chatform" id="chatForm">
281
+ <input type="text" id="chatInput" autocomplete="off" placeholder="press start above to chat with the graph" aria-label="Message to the graph" disabled>
282
+ <button type="submit" class="btn primary" id="chatSend" disabled>send</button>
283
+ </form>
284
+ </div>
285
+ </section>
286
+
267
287
  <div class="pagelog" id="pageLog" aria-live="polite"></div>
268
288
  </main>
269
- <script>
270
- const DIGEST_STRUCTURES = ${digestJson};
271
- const SEED_STAMP = ${JSON.stringify(seedStamp)};
272
- const SEED_QUERY = SEED_STAMP ? "?b=" + SEED_STAMP : "";
273
- const SEED_BYTES = ${Number(seedBytes) || 0};
274
- </script>
275
289
  <!--
276
290
  news-browser.bundle.js (built by scripts/build-news-bundle.mjs) publishes
277
291
  window.tmct — createNewsSession as tmct.open(), every session verb as
278
292
  tmct.session.<verb>(). The inline script below only wires DOM to that
279
- surface; it never touches the network, the memory store, or the news
280
- engine directly, so every third-party request this page ever makes is
281
- traceable to one of the session's own consent-gated methods.
293
+ surface; it never touches the network directly (createHttpRowBackend
294
+ inside the session does, over the row service's own routes), so every
295
+ request this page ever makes is traceable to one of the session's own
296
+ methods, each reached only from a click this script handles.
282
297
  -->
283
298
  <script src="./news-browser.bundle.js"></script>
284
299
  <script>
@@ -286,11 +301,13 @@ const SEED_BYTES = ${Number(seedBytes) || 0};
286
301
  "use strict";
287
302
  const el = (id) => document.getElementById(id);
288
303
  const esc = ${escapeHtml.toString()};
289
- const FACT_PREDICATE_PHRASES = ${factPhrasesJson};
290
- ${phraseRendererSource()}
291
- const factTripleParts = ${factTripleParts.toString()};
292
- const fetchWithProgress = ${fetchWithProgress.toString()};
293
- const loadSeedPayload = ${loadSeedPayload.toString()};
304
+
305
+ const EMPTY_FEED = { items: [], rankedTerms: [], stats: { graphSize: 0, factsFromNews: 0 }, sourceStatus: [], requestLog: [], builtAt: null };
306
+
307
+ // Set once boot() opens the session; read by setUnavailable/
308
+ // updateChatAvailability below, which both live outside boot()'s own
309
+ // closure and never call the network themselves.
310
+ let session = null;
294
311
 
295
312
  function appendLog(text) {
296
313
  const line = document.createElement("div");
@@ -321,79 +338,193 @@ const SEED_BYTES = ${Number(seedBytes) || 0};
321
338
  node.querySelector("[data-bars]").innerHTML = microbars(items);
322
339
  }
323
340
 
324
- async function renderRequestLog() {
341
+ // Every network-facing control disables together the moment the service
342
+ // stops answering — none of them has anything left to do until it comes
343
+ // back. Enrich and teach each mint their own session independently of the
344
+ // "start" press, the same way the old page's add-source-by-url ran its
345
+ // own preflight regardless of poll consent — pressing any of them first
346
+ // is exactly what "the page mints the session, at consent" means.
347
+ function setUnavailable(isUnavailable) {
348
+ el("serviceUnavailable").classList.toggle("shown", isUnavailable);
349
+ ["newsStart", "enrichNow", "stopForget", "teachIngest", "teachBrowse"].forEach(function (id) {
350
+ el(id).disabled = isUnavailable;
351
+ });
352
+ updateChatAvailability();
353
+ }
354
+
355
+ // Chat joins the same disabled-together posture as every other
356
+ // network-facing control once the service goes unreachable, and carries
357
+ // its OWN gate besides: it stays disabled until the visitor has pressed
358
+ // start at least once, the one control on this page that waits for that
359
+ // specific press rather than minting its own session on first use.
360
+ function updateChatAvailability() {
361
+ const blocked = !session || !session.consented || session.unavailable;
362
+ el("chatInput").disabled = blocked;
363
+ el("chatSend").disabled = blocked;
364
+ el("chatInput").placeholder = (session && session.consented)
365
+ ? "ask or teach the graph a fact"
366
+ : "press start above to chat with the graph";
367
+ }
368
+
369
+ /** One chat-log row: ".chatturn <kind>" wrapping one ".chatbubble" whose
370
+ * text lands through textContent alone — never HTML built from a
371
+ * string, matching the answer-text posture no other text on this page
372
+ * needs, since a chat reply is the one string here nobody has read or
373
+ * sanitised before it arrives. */
374
+ function chatBubble(kind, text) {
375
+ const row = document.createElement("div");
376
+ row.className = "chatturn " + kind;
377
+ const bubble = document.createElement("div");
378
+ bubble.className = "chatbubble";
379
+ bubble.textContent = text;
380
+ row.appendChild(bubble);
381
+ return row;
382
+ }
383
+
384
+ function appendChatTurn(kind, text) {
385
+ const row = chatBubble(kind, text);
386
+ el("chatLog").appendChild(row);
387
+ el("chatLog").scrollTop = el("chatLog").scrollHeight;
388
+ return row;
389
+ }
390
+
391
+ /** The graph's own turn, plus what it touched: result.citations (already
392
+ * phrase-layer English, from session.turn()) as a plain list under the
393
+ * reply, and result.narration as a collapsible trace — the same
394
+ * disclosure shape a fact card's own "what the graph already knew"
395
+ * details block uses. Both are optional; a plain answer with no writes
396
+ * and no trace text renders as just the one bubble. Says nothing about
397
+ * the feed either way — a taught fact reaches it at the next
398
+ * materialization, whenever that runs. */
399
+ function appendChatReply(result) {
400
+ const row = chatBubble("graph", result.reply);
401
+ if (result.citations && result.citations.length) {
402
+ const learned = document.createElement("div");
403
+ learned.className = "chatlearned";
404
+ learned.appendChild(document.createTextNode("learned this turn:"));
405
+ const list = document.createElement("ul");
406
+ for (const line of result.citations) {
407
+ const li = document.createElement("li");
408
+ li.textContent = line;
409
+ list.appendChild(li);
410
+ }
411
+ learned.appendChild(list);
412
+ row.appendChild(learned);
413
+ }
414
+ if (result.narration) {
415
+ const trace = document.createElement("details");
416
+ trace.className = "chattrace";
417
+ const summary = document.createElement("summary");
418
+ summary.textContent = "trace";
419
+ const pre = document.createElement("pre");
420
+ pre.textContent = result.narration;
421
+ trace.appendChild(summary);
422
+ trace.appendChild(pre);
423
+ row.appendChild(trace);
424
+ }
425
+ el("chatLog").appendChild(row);
426
+ el("chatLog").scrollTop = el("chatLog").scrollHeight;
427
+ }
428
+
429
+ function renderRequestLog(feed) {
325
430
  const body = el("requestLogBody");
326
431
  body.innerHTML = "";
327
- for (const row of (window.tmct.session ? window.tmct.session.requestLog : []).slice(0, 50)) {
432
+ for (const row of (feed.requestLog || [])) {
328
433
  const tr = document.createElement("tr");
329
434
  tr.innerHTML = "<td>" + esc(row.url) + "</td><td>" + esc(row.at) + "</td><td>" + esc(String(row.bytes)) + "</td><td>" + esc(row.status) + "</td>";
330
435
  body.appendChild(tr);
331
436
  }
332
437
  }
333
438
 
334
- function renderSourceStatus() {
335
- const health = window.tmct.session ? window.tmct.session.health : [];
336
- const byId = new Map(health.map((h) => [h.sourceId, h]));
337
- const config = window.tmct.session ? window.tmct.session.config : { sources: [] };
338
- const enabled = new Set(config.sources);
339
- document.querySelectorAll("[data-source-id]").forEach((row) => {
340
- const id = row.getAttribute("data-source-id");
341
- const h = byId.get(id);
439
+ function renderSourcesPanel(feed) {
440
+ const byId = new Map((feed.sourceStatus || []).map(function (h) { return [h.sourceId, h]; }));
441
+ const nowMs = Date.now();
442
+ document.querySelectorAll("[data-source-id]").forEach(function (row) {
443
+ const health = byId.get(row.getAttribute("data-source-id"));
342
444
  const statusEl = row.querySelector("[data-source-status]");
343
- let text = "off";
344
- if (enabled.has(id)) {
345
- if (h && h.autoDisabled) text = "auto-disabled";
346
- else if (h && h.browserBlocked) text = "source does not permit browser access";
347
- else if (h && h.lastStatus) text = h.lastStatus;
348
- else text = "not yet polled";
445
+ let text = "not yet polled";
446
+ if (health) {
447
+ if (health.autoDisabled) text = "auto-disabled";
448
+ else if (health.browserBlocked) text = "source does not permit browser access";
449
+ // A source can be skipped without being auto-disabled yet — one or
450
+ // two failures back off for a while rather than giving up on it —
451
+ // and that reads as nothing without its own note; left to fall
452
+ // through to lastStatus, a merely-cooling-down source would show
453
+ // "failed" forever, which understates what actually happened.
454
+ else if (health.backoffUntil && Date.parse(health.backoffUntil) > nowMs) text = "skipped — backing off";
455
+ else if (health.lastStatus) text = health.lastStatus;
349
456
  }
350
457
  statusEl.textContent = text;
351
458
  });
352
- return { byId, enabled };
459
+ setTile("tileSourcesLive", (feed.sourceStatus || []).length, "reported in the last cycle");
460
+ setBars("panelSourcesPerSource", (feed.sourceStatus || []).map(function (h) {
461
+ return { label: h.sourceId, count: h.consecutiveFailures ? 0 : 1 };
462
+ }));
463
+ }
464
+
465
+ // Live progress during a running cycle, read off the marker each button
466
+ // press reports through its own onCycle callback — a poll cycle's own
467
+ // per-source entries as they land, or "polling…" for a roster member the
468
+ // marker hasn't reached yet. renderSourcesPanel overwrites all of this the
469
+ // moment the press's own promise resolves with the finished feed; this is
470
+ // only what a visitor sees while it's still running.
471
+ function renderCycleProgress(marker) {
472
+ if (!marker) return;
473
+ const perSource = marker.sources || {};
474
+ document.querySelectorAll("[data-source-id]").forEach(function (row) {
475
+ if (row.classList.contains("kb")) return;
476
+ const id = row.getAttribute("data-source-id");
477
+ const statusEl = row.querySelector("[data-source-status]");
478
+ if (Object.prototype.hasOwnProperty.call(perSource, id)) {
479
+ statusEl.textContent = perSource[id].status;
480
+ } else if (marker.state === "running" && marker.kind === "poll") {
481
+ statusEl.textContent = "polling…";
482
+ }
483
+ });
353
484
  }
354
485
 
355
- async function factListHtml(factIds) {
356
- const rows = await window.tmct.session.factRows(factIds);
357
- return rows.map((row) => {
358
- const triple = factTripleParts(row);
359
- return '<div class="factrow">' + esc(factSentence(row))
360
- + '<details><summary>triple</summary><div class="facttriple">'
361
- + esc(triple.subject) + " | " + esc(triple.predicate) + " | " + esc(triple.object)
362
- + " (" + esc(row.provenance || "") + ", trust " + esc(String(row.trust || 0)) + ")"
363
- + '</div></details></div>';
364
- }).join("");
486
+ function cardHtml(item) {
487
+ const factLines = item.factLines || [];
488
+ const factsHtml = factLines.map(function (line) { return '<div class="factrow">' + esc(line) + '</div>'; }).join("");
489
+ const moreCount = (item.factCount || 0) - factLines.length;
490
+ const moreHtml = moreCount > 0 ? '<div class="factrow factmore">&hellip;and ' + moreCount + ' more</div>' : "";
491
+ const sourcesText = (item.sources || []).map(function (s) { return esc(s.title || s.url || ""); }).filter(Boolean).join(", ");
492
+ const background = item.backgroundParagraph
493
+ ? '<details class="background"><summary>what the graph already knew</summary><p>' + esc(item.backgroundParagraph) + '</p></details>'
494
+ : "";
495
+ const newTag = item.newName ? '<span class="newtag">new</span>' : "";
496
+ return '<div class="item" data-item-id="' + esc(item.id) + '">'
497
+ + '<span class="hub">' + esc(item.hub) + '</span><span class="tier">' + esc(item.tier || "unranked") + '</span>' + newTag
498
+ + '<p class="paragraph">' + esc(item.paragraph) + '</p>'
499
+ + background
500
+ + (sourcesText ? '<p class="sources-links">sources: ' + sourcesText + '</p>' : "")
501
+ + '<details class="facts"><summary>' + (item.factCount || 0) + ' fact' + (item.factCount === 1 ? "" : "s") + '</summary>' + factsHtml + moreHtml + '</details>'
502
+ + '</div>';
365
503
  }
366
504
 
367
- // The last built feed and one rendered card per item, so a sort change or a
368
- // pill toggle re-orders what is already on screen instead of rebuilding
369
- // every card's fact list from the store again.
505
+ // The last-rendered feed's own items and one built card per item, so a
506
+ // sort change or a pill toggle re-orders what is already on screen
507
+ // without asking the server for anything again.
370
508
  let feedItems = [];
371
509
  const cardsByItemId = new Map();
372
510
  const activePillTerms = new Set();
373
- // What an empty feed says: this line before a poll, or after one that
374
- // reported nothing newsworthy; the purge line once "stop & forget" has
375
- // emptied the graph of articles, until the next poll (start or poll once)
376
- // puts content back and reverts it — the same "next action that puts
377
- // content back" rule the session's own forgotten flag follows.
378
- const DEFAULT_EMPTY_FEED_TEXT = "no news yet — the feed only shows named people, places and events from polled sources. press poll once to fetch some.";
511
+ const DEFAULT_EMPTY_FEED_TEXT = "no news yet — the feed only shows named people, places and events the worker has reported. press start to fetch some.";
379
512
  let emptyFeedText = DEFAULT_EMPTY_FEED_TEXT;
380
-
381
513
  const MAX_PILLS = 12;
382
514
 
383
515
  function itemMatchesActivePills(item) {
384
516
  if (!activePillTerms.size) return true;
385
517
  const haystack = (item.hub + " " + item.paragraph).toLowerCase();
386
- for (const term of activePillTerms) {
387
- if (item.hub === term || haystack.indexOf(term) !== -1) return true;
388
- }
518
+ for (const term of activePillTerms) { if (item.hub === term || haystack.indexOf(term) !== -1) return true; }
389
519
  return false;
390
520
  }
391
521
 
392
522
  function sortedFeedItems() {
393
523
  const mode = el("feedSort").value;
394
524
  const items = feedItems.slice();
395
- if (mode === "facts") items.sort((a, b) => b.factIds.length - a.factIds.length || (a.hub < b.hub ? -1 : 1));
396
- else if (mode === "changed") items.sort((a, b) => b.changedCount - a.changedCount || (a.hub < b.hub ? -1 : 1));
525
+ if (mode === "facts") items.sort((a, b) => (b.factCount - a.factCount) || (a.hub < b.hub ? -1 : 1));
526
+ else if (mode === "changed") items.sort((a, b) => (b.changedCount - a.changedCount) || (a.hub < b.hub ? -1 : 1));
527
+ else items.sort((a, b) => (b.observedMs - a.observedMs) || (a.hub < b.hub ? -1 : 1));
397
528
  return items;
398
529
  }
399
530
 
@@ -401,7 +532,7 @@ const SEED_BYTES = ${Number(seedBytes) || 0};
401
532
  const pillsEl = el("feedPills");
402
533
  const terms = feedItems
403
534
  .slice()
404
- .sort((a, b) => b.changedCount - a.changedCount || (a.hub < b.hub ? -1 : 1))
535
+ .sort((a, b) => (b.changedCount - a.changedCount) || (a.hub < b.hub ? -1 : 1))
405
536
  .map((it) => it.hub)
406
537
  .slice(0, MAX_PILLS);
407
538
  for (const term of [...activePillTerms]) if (terms.indexOf(term) === -1) activePillTerms.delete(term);
@@ -439,117 +570,62 @@ const SEED_BYTES = ${Number(seedBytes) || 0};
439
570
  : (shown.length + " of " + feedItems.length + " articles");
440
571
  }
441
572
 
442
- async function renderFeed() {
443
- const feedEl = el("feed");
444
- const feed = await window.tmct.session.buildFeed();
445
- feedItems = feed.items;
573
+ function renderFeed(feed) {
574
+ feedItems = feed.items || [];
446
575
  cardsByItemId.clear();
447
- feedEl.querySelectorAll(".item").forEach((n) => n.remove());
448
- for (const item of feed.items) {
449
- // One yield per card keeps the page clickable while a long feed renders.
450
- await new Promise((resolve) => setTimeout(resolve, 0));
451
- const card = document.createElement("div");
452
- card.className = "item";
453
- const seedTag = feed.seedFallback ? '<span class="seedtag">from the seed graph — start to poll live sources</span>' : "";
454
- const sourcesText = item.sources.map((s) => esc(s.title || s.url)).join(", ");
455
- const facts = await factListHtml(item.factIds);
456
- const background = item.backgroundParagraph
457
- ? '<details class="background"><summary>what the graph already knew</summary><p>' + esc(item.backgroundParagraph) + '</p></details>'
458
- : "";
459
- card.innerHTML =
460
- '<span class="hub">' + esc(item.hub) + '</span><span class="tier">' + esc(item.tier || "unranked") + '</span>' + seedTag
461
- + '<p class="paragraph">' + esc(item.paragraph) + '</p>'
462
- + background
463
- + (sourcesText ? '<p class="sources-links">sources: ' + sourcesText + '</p>' : "")
464
- + '<details class="facts"><summary>' + item.factIds.length + ' facts</summary>' + facts + '</details>';
465
- cardsByItemId.set(item.id, card);
466
- // Each card shows the moment it is built; the paint below re-orders and
467
- // filters what is already on screen.
468
- if (itemMatchesActivePills(item)) { el("feedEmpty").hidden = true; feedEl.appendChild(card); }
576
+ for (const item of feedItems) {
577
+ const wrapper = document.createElement("div");
578
+ wrapper.innerHTML = cardHtml(item);
579
+ cardsByItemId.set(item.id, wrapper.firstElementChild);
469
580
  }
470
581
  renderPills();
471
582
  paintFeed();
472
- setTile("tileFeedItems", feed.items.length, feed.seedFallback ? "from the seed graph" : "live");
583
+ setTile("tileFeedItems", feedItems.length, feed.trimmed ? "trimmed to fit — each card's own count says how much" : "");
473
584
  }
474
585
 
475
- async function renderGraphTiles() {
476
- const stats = await window.tmct.session.stats();
477
- setTile("tileFactsFromNews", stats.factsFromNews, stats.factsFromNews ? "polled, replayed or enriched" : "nothing ingested yet");
478
- setTile("tileGraphSize", stats.graphSize, "facts in this session's graph");
479
- }
480
-
481
- async function renderRank() {
482
- const rows = await window.tmct.session.rank({ limit: 8 });
483
- setTile("tileTermsUngrounded", rows.length, rows.length ? "ranked by occurrence" : "none yet");
484
- setBars("panelTermsRanked", rows.map((r) => ({
586
+ function renderAll(feed) {
587
+ renderFeed(feed);
588
+ renderSourcesPanel(feed);
589
+ renderRequestLog(feed);
590
+ const ranked = feed.rankedTerms || [];
591
+ setTile("tileTermsUngrounded", ranked.length, ranked.length ? "ranked by occurrence" : "none yet");
592
+ setBars("panelTermsRanked", ranked.map((r) => ({
485
593
  label: r.term + (r.vocabGrounded ? " (parseable but knowledge-free)" : " (unknown word)"),
486
594
  count: r.count,
487
595
  })));
596
+ const stats = feed.stats || { graphSize: 0, factsFromNews: 0 };
597
+ setTile("tileFactsFromNews", stats.factsFromNews, stats.factsFromNews ? "polled or taught" : "nothing ingested yet");
598
+ setTile("tileGraphSize", stats.graphSize, "facts in this session's graph");
488
599
  }
489
600
 
490
- function renderSourcesPanel() {
491
- const { enabled } = renderSourceStatus();
492
- const config = window.tmct.session ? window.tmct.session.config : { sources: [] };
493
- setTile("tileSourcesLive", enabled.size, config.pollMinutes ? ("every " + config.pollMinutes + " min") : "on demand");
494
- const health = window.tmct.session ? window.tmct.session.health : [];
495
- setBars("panelSourcesPerSource", health.map((h) => ({ label: h.sourceId, count: h.consecutiveFailures ? 0 : 1 })));
496
- }
497
-
498
- async function renderAll() {
499
- // Chips and tiles are cheap synchronous text writes; they lead so a
500
- // just-finished poll reads back immediately while the feed's own slower,
501
- // yielding render catches up behind it.
502
- renderSourcesPanel();
503
- await Promise.all([renderFeed(), renderRank(), renderRequestLog(), renderGraphTiles()]);
504
- renderSourcesPanel();
505
- window.tmct.news = Object.assign({}, window.tmct.news, {
506
- phase: window.tmct.session.phase,
507
- metrics: window.tmct.session.metrics,
508
- nextPollAt: window.tmct.session.nextPollAt,
601
+ function looksLikeFactRows(text) {
602
+ const lines = String(text || "").split("\\n").map(function (l) { return l.trim(); }).filter(Boolean);
603
+ if (!lines.length) return false;
604
+ return lines.every(function (line) {
605
+ try {
606
+ const row = JSON.parse(line);
607
+ return row && typeof row === "object" && row.subject && row.predicate && row.object;
608
+ } catch { return false; }
509
609
  });
510
- appendLog("phase: " + window.tmct.session.phase);
511
610
  }
512
611
 
513
612
  async function boot() {
514
- window.tmct.news = { phase: "seeding", metrics: { timeToFirstArticleMs: null, timeToFirstCompletePollMs: null }, nextPollAt: "" };
515
- appendLog("phase: seeding");
516
- // The wink vendor is what lets ingested prose ground at all — without it
517
- // every extract runs lexicon-blind and the whole enrich loop misses.
518
- // Loaded alongside the seed, tolerated as absent the same way chat.html
519
- // tolerates it, never blocking the page.
520
- const winkLoad = (async function () {
521
- try {
522
- const mod = await Promise.race([
523
- import("./vendor/wink.js"),
524
- new Promise(function (resolve, reject) { setTimeout(function () { reject(new Error("wink vendor load timed out")); }, 20000); }),
525
- ]);
526
- window.tmct.page.registerWinkModel(function () { return { winkNLP: mod.winkNLP, model: mod.model }; });
527
- appendLog("wink vendor loaded — prose grounding armed");
528
- } catch (err) {
529
- appendLog("wink vendor unavailable — prose grounding runs lexicon-blind");
530
- }
531
- })();
532
- const outcome = await loadSeedPayload(fetchWithProgress, "./chat-seed.json", SEED_QUERY, function () {});
533
- window.tmct.seed = { state: outcome.status.state, facts: outcome.status.facts };
534
- await winkLoad;
535
- await window.tmct.open({ seedPayload: outcome.payload, vocabSeeded: Boolean(outcome.payload) });
536
-
537
- // Every control binds before the phase flips to "seeded": the first feed
538
- // render is deliberately slow (it yields per card), and a click that
539
- // lands in that window must already have its listener.
613
+ session = await window.tmct.open({});
614
+ window.tmct.news = { phase: "seeded" };
615
+
616
+ // The standing refresh loop lives inside the session, started already —
617
+ // this just subscribes to it. A cycle another tab (or a reload-surviving
618
+ // trigger) finishes reaches this page the same way a press's own cycle
619
+ // does, without this page having asked for anything.
620
+ session.onFeedUpdate(function (feed) {
621
+ renderAll(feed);
622
+ appendLog("the feed updated in the background");
623
+ });
624
+
540
625
  const startBtn = el("newsStart");
541
- // Read once, here. The first render below takes a while, a visitor can
542
- // press start inside it, and that press grants consent — so re-reading
543
- // the flag afterwards to decide whether to replay a returning visit's
544
- // poll would poll a second time on top of the one already running.
545
- const returningVisit = window.tmct.session.consented;
546
- startBtn.textContent = returningVisit ? "poll now" : "start polling live sources";
547
-
548
- el("feedSort").addEventListener("change", paintFeed);
549
-
550
- // A poll can run for a while, so the button reads back its own state the
551
- // moment it is pressed and the status line follows the session's phase
552
- // until it settles.
626
+ startBtn.textContent = session.consented ? "poll now" : "start polling live sources";
627
+ updateChatAvailability(); // a restored, already-consented session unlocks chat right away
628
+
553
629
  function markBusy(button, label) {
554
630
  button.dataset.idleLabel = button.textContent;
555
631
  button.textContent = label;
@@ -561,133 +637,61 @@ const SEED_BYTES = ${Number(seedBytes) || 0};
561
637
  button.disabled = false;
562
638
  button.removeAttribute("aria-busy");
563
639
  }
564
- // "stop polling" is live whenever there is something to stop: a press
565
- // still in flight, a cycle running, or a timer armed for the next one.
566
- // The press counter leads the session's own busy flag — a click must be
567
- // able to stop the cycle it just started, from the same tick.
568
- let pressesInFlight = 0;
569
- function syncStopPolling() {
570
- const session = window.tmct.session;
571
- el("stopPolling").disabled = !(pressesInFlight > 0 || (session && (session.busy || session.nextPollAt)));
572
- }
573
- function followPhase(label) {
574
- el("controlsStatus").textContent = label;
575
- const id = setInterval(function () {
576
- el("controlsStatus").textContent = window.tmct.session.phase + "…";
577
- syncStopPolling();
578
- }, 400);
579
- return function () { clearInterval(id); el("controlsStatus").textContent = ""; syncStopPolling(); };
580
- }
581
640
 
582
- /** One press that fetches: the button reads back busy at once, the
583
- * status line follows the phase, and everything re-renders after. */
584
- async function runFetchingPress(button, busyLabel, idleLabel, work) {
641
+ /** One press that talks to the service: the button reads back busy at
642
+ * once, the status line carries the outcome, and a network failure
643
+ * flips the page into the unavailable state rather than leaving the
644
+ * button stuck. */
645
+ async function runPress(button, busyLabel, idleLabelFn, work) {
585
646
  markBusy(button, busyLabel);
586
- pressesInFlight += 1;
587
- syncStopPolling();
588
- const stopFollowing = followPhase(busyLabel);
647
+ el("controlsStatus").textContent = busyLabel;
589
648
  try {
590
- await work();
649
+ const feed = await work();
650
+ setUnavailable(false);
651
+ renderAll(feed);
652
+ el("controlsStatus").textContent = "";
653
+ return feed;
654
+ } catch (err) {
655
+ el("controlsStatus").textContent = (err && err.message) ? err.message : String(err);
656
+ if (session.unavailable) setUnavailable(true);
657
+ throw err;
591
658
  } finally {
592
- pressesInFlight -= 1;
593
- stopFollowing();
594
- markIdle(button, idleLabel);
595
- syncStopPolling();
659
+ markIdle(button, idleLabelFn());
596
660
  }
597
- await renderAll();
598
661
  }
599
662
 
600
663
  startBtn.addEventListener("click", function () {
601
664
  emptyFeedText = DEFAULT_EMPTY_FEED_TEXT;
602
- return runFetchingPress(startBtn, "polling…", "poll now", function () { return window.tmct.session.start(); });
603
- });
604
-
605
- el("pollOnce").addEventListener("click", function () {
606
- emptyFeedText = DEFAULT_EMPTY_FEED_TEXT;
607
- const pollOnceBtn = el("pollOnce");
608
- return runFetchingPress(pollOnceBtn, "polling…", "poll once", function () { return window.tmct.session.pollOnce(); });
609
- });
610
-
611
- el("stopPolling").addEventListener("click", function () {
612
- const result = window.tmct.session.stopPolling();
613
- el("controlsStatus").textContent = result.wasRunning ? "stopping…" : "polling stopped";
614
- appendLog(result.wasRunning
615
- ? "stopping — the running cycle finishes the article it is on and stops there"
616
- : "polling stopped — no cycle was running, the next scheduled poll is cancelled");
617
- syncStopPolling();
618
- renderSourcesPanel();
619
- });
620
-
621
- // The button stays busy until the purge is finished on screen as well as
622
- // in the store, so "enabled again" really does mean "the articles are
623
- // gone" rather than "the store call returned".
624
- el("stopForget").addEventListener("click", async function () {
625
- const stopForgetBtn = el("stopForget");
626
- markBusy(stopForgetBtn, "forgetting…");
627
- try {
628
- const result = await window.tmct.session.revokeConsent();
629
- const removed = (result && result.factsRemoved) || 0;
630
- startBtn.textContent = "start polling live sources";
631
- feedItems = [];
632
- cardsByItemId.clear();
633
- activePillTerms.clear();
634
- el("feed").querySelectorAll(".item").forEach(function (n) { n.remove(); });
635
- emptyFeedText = "the articles are gone — press start or poll once to gather news again.";
636
- renderPills();
637
- paintFeed();
638
- appendLog("stopped and forgot: " + removed + " fact(s) from news dropped, articles cleared, this page reads as first-visit next load");
639
- await renderAll();
640
- } finally {
641
- markIdle(stopForgetBtn, "stop & forget");
642
- syncStopPolling();
643
- }
644
- });
645
-
646
- el("pollInterval").addEventListener("change", function (ev) {
647
- const minutes = window.tmct.session.setInterval(Number(ev.target.value));
648
- ev.target.value = String(minutes);
649
- syncStopPolling();
665
+ const ids = [].slice.call(document.querySelectorAll("[data-source-toggle]:checked")).map(function (b) { return b.value; });
666
+ runPress(startBtn, "polling…", function () { return session.consented ? "poll now" : "start polling live sources"; }, function () { return session.start(ids, { onCycle: renderCycleProgress }); })
667
+ .catch(function () {});
650
668
  });
651
669
 
652
670
  el("enrichNow").addEventListener("click", function () {
653
- const enrichBtn = el("enrichNow");
654
- return runFetchingPress(enrichBtn, "enriching…", "enrich now", function () { return window.tmct.session.enrich(); });
655
- });
656
-
657
- document.querySelectorAll("[data-source-toggle]").forEach(function (box) {
658
- box.addEventListener("change", function () {
659
- const ids = [].slice.call(document.querySelectorAll("[data-source-toggle]:checked")).map(function (b) { return b.value; });
660
- window.tmct.session.setSources(ids);
661
- renderSourcesPanel();
662
- });
671
+ const fuzzy = el("fuzzyToggle").checked;
672
+ runPress(el("enrichNow"), "enriching…", function () { return "enrich now"; }, function () { return session.enrich({ fuzzy: fuzzy, onCycle: renderCycleProgress }); })
673
+ .catch(function () {});
663
674
  });
664
675
 
665
- el("addSourceBtn").addEventListener("click", async function () {
666
- const url = el("addSourceUrl").value.trim();
667
- if (!url) return;
668
- el("controlsStatus").textContent = "checking…";
669
- const result = await window.tmct.session.addSource(url);
670
- el("controlsStatus").textContent = result.ok ? ("added as " + result.format) : ("couldn't add: " + result.reason);
671
- if (result.ok) renderSourcesPanel();
676
+ el("stopForget").addEventListener("click", async function () {
677
+ const btn = el("stopForget");
678
+ markBusy(btn, "forgetting…");
679
+ el("controlsStatus").textContent = "forgetting…";
680
+ const result = await session.revokeConsent();
681
+ startBtn.textContent = "start polling live sources";
682
+ feedItems = [];
683
+ cardsByItemId.clear();
684
+ activePillTerms.clear();
685
+ emptyFeedText = "the articles are gone — press start to fetch news again.";
686
+ renderAll(EMPTY_FEED);
687
+ document.querySelectorAll("[data-source-status]").forEach(function (n) { n.textContent = "not yet polled"; });
688
+ appendLog(result.ok
689
+ ? "stopped and forgot — this page reads as first-visit on the next load"
690
+ : "stopped and forgot locally; the server-side purge reported: " + result.error);
691
+ markIdle(btn, "stop & forget");
692
+ el("controlsStatus").textContent = "";
672
693
  });
673
694
 
674
- async function replayFrom(sourceId, fixtureKey) {
675
- el("controlsStatus").textContent = "replaying…";
676
- try {
677
- const res = await fetch("./news-fixtures.json");
678
- const bundle = res.ok ? await res.json() : null;
679
- const fixture = bundle && bundle[fixtureKey];
680
- if (!fixture) { el("controlsStatus").textContent = "fixture unavailable"; return; }
681
- await window.tmct.session.replayFixture(sourceId, fixture);
682
- el("controlsStatus").textContent = "replayed " + fixtureKey;
683
- await renderAll();
684
- } catch (err) {
685
- el("controlsStatus").textContent = "fixture unavailable";
686
- }
687
- }
688
- el("replayNyt").addEventListener("click", function () { replayFrom("nyt-world", "nyt-world"); });
689
- el("replayWikipedia").addEventListener("click", function () { replayFrom("wikimedia-featured", "wikimedia-featured"); });
690
-
691
695
  el("exampleProse").addEventListener("click", function () {
692
696
  el("teachText").value = "A ceasefire is a formal agreement to stop fighting. A tariff is a tax on imported goods.";
693
697
  });
@@ -703,26 +707,62 @@ const SEED_BYTES = ${Number(seedBytes) || 0};
703
707
  if (!file) return;
704
708
  el("teachText").value = await file.text();
705
709
  el("teachStatus").textContent = "loaded " + file.name + " — press ingest";
706
- el("teachFile").dataset.name = file.name;
707
710
  });
708
711
 
709
- window.tmct.news.phase = "seeded";
710
- appendLog("phase: seeded");
711
- await renderAll();
712
- syncStopPolling();
713
- if (returningVisit) {
714
- await window.tmct.session.start();
715
- await renderAll();
716
- syncStopPolling();
717
- }
718
712
  el("teachIngest").addEventListener("click", async function () {
719
713
  const text = el("teachText").value;
720
714
  if (!text.trim()) return;
721
- const name = el("teachFile").dataset.name || "";
722
- const result = await window.tmct.session.ingestFile({ name: name, text: text });
723
- el("teachStatus").textContent = result.error ? result.error : (result.facts + " fact(s), " + result.vocabAdded + " vocab hint(s)");
724
- await renderAll();
715
+ const btn = el("teachIngest");
716
+ const graphSizeBefore = Number((el("tileGraphSize").querySelector("[data-value]") || {}).textContent) || 0;
717
+ await runPress(btn, "ingesting…", function () { return "ingest"; }, async function () {
718
+ const feed = looksLikeFactRows(text)
719
+ ? await session.ingestRows(window.tmct.page.parseJsonlRows(text), { onCycle: renderCycleProgress })
720
+ : await session.ingestText(text, { onCycle: renderCycleProgress });
721
+ const added = Math.max(0, (feed.stats.graphSize || 0) - graphSizeBefore);
722
+ el("teachStatus").textContent = added + " fact(s) added to the graph";
723
+ return feed;
724
+ }).catch(function (err) { el("teachStatus").textContent = err.message || String(err); });
725
725
  });
726
+
727
+ el("chatForm").addEventListener("submit", async function (ev) {
728
+ ev.preventDefault();
729
+ const input = el("chatInput");
730
+ const text = input.value.trim();
731
+ if (!text || input.disabled) return;
732
+ appendChatTurn("you", text);
733
+ input.value = "";
734
+ const sendBtn = el("chatSend");
735
+ input.disabled = true;
736
+ sendBtn.disabled = true;
737
+ sendBtn.setAttribute("aria-busy", "true");
738
+ try {
739
+ const fuzzy = el("fuzzyToggle").checked;
740
+ const result = await session.turn(text, { fuzzy: fuzzy });
741
+ setUnavailable(false);
742
+ appendChatReply(result);
743
+ } catch (err) {
744
+ appendChatTurn("error", err && err.message ? err.message : String(err));
745
+ if (session.unavailable) setUnavailable(true);
746
+ } finally {
747
+ sendBtn.removeAttribute("aria-busy");
748
+ updateChatAvailability();
749
+ input.focus();
750
+ }
751
+ });
752
+
753
+ if (session.sessionKey) {
754
+ try {
755
+ const feed = await session.fetchFeed();
756
+ renderAll(feed);
757
+ appendLog("restored the session's last materialized feed");
758
+ } catch (err) {
759
+ setUnavailable(true);
760
+ appendLog("could not load the saved session: " + (err && err.message ? err.message : String(err)));
761
+ }
762
+ } else {
763
+ renderAll(EMPTY_FEED);
764
+ appendLog("ready — nothing has been requested yet");
765
+ }
726
766
  }
727
767
 
728
768
  boot().catch(function (err) { appendLog("boot failed: " + (err && err.message ? err.message : String(err))); });