neurastream 0.2.22 → 0.2.23

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/README.md CHANGED
@@ -113,7 +113,7 @@ A plan parked for the owner has one line: `WAITING on owner: <what>`. That line
113
113
 
114
114
  `neurastream ui on --login <tailscale login> [--port N]` does the whole setup in one sentence: it writes `ui.enabled: true` and `ui.owner_login` (plus `ui.port` with `--port`) into `~/.config/neurastream/config.yml` — every other line of the file is kept byte-for-byte — copies `templates/systemd/neurastream-ui.service` to `~/.config/systemd/user/neurastream-ui.service`, runs `systemctl --user daemon-reload`, `enable` and `restart`, then prints the phone link `http://<MagicDNS name>:<port>`. The login must be one the tailnet knows (`tailscale status --json`); when tailscale cannot answer, the check is skipped with a printed warning, never a refusal. `neurastream ui off` stops and disables the unit and sets `ui.enabled: false`, keeping `ui.owner_login` for the next `on`.
115
115
 
116
- With `ui.enabled: true` and `ui.owner_login` set (`neurastream config`, `docs/config.md`), `neurastream ui` serves one page bound to this machine's tailnet address only (port `ui.port`, default 7787; `templates/systemd/neurastream-ui.service` runs it as a user unit). The page reads top to bottom: a sticky status strip with the amber "needs you" count plus working/CI/disk signals that turn red only when something is actually wrong; one card per open `WAITING on owner:` plan — the plan's `#` title, the ask in plain words, the goal folded into a Background block, and named actions ("Yes, go ahead", "No", "Reply…") whose answer shows as a one-time receipt ("Sent to Main · 08:12"); a working-now row per running or waiting agent; and closed details blocks for the queue (one flat list in `INDEX.md` order — drag a card by its handle, or tap "↑ top"/"↑"/"↓"; the drop rewrites `INDEX.md`, Main gets the move as a message and the page confirms "Moved to #2"), merges/CI, incidents, agent scores (a real table) and machine health. A sticky bottom bar holds the guard unlock ("Unlock 15 min", "Unlock 30 min", "Lock now") and, when `guards.chat_unlock` is off, says so in plain words with the exact config line. Light and dark follow the OS; there are no external assets and no build step — one server-rendered HTML string, inline CSS and one small inline script under a per-response CSP nonce (`bun scripts/ui-preview.ts <out.html>` renders a preview without a server). No chat, no plan editing, no shell.
116
+ With `ui.enabled: true` and `ui.owner_login` set (`neurastream config`, `docs/config.md`), `neurastream ui` serves one page bound to this machine's tailnet address only (port `ui.port`, default 7787; `templates/systemd/neurastream-ui.service` runs it as a user unit). A sticky top bar holds the "ns" logo, four pill tabs — Now, Queue, Agents, Spend, each a server-rendered view (`/?tab=…`, an unknown value falls back to Now) — and the lock pill ("🔒 Off" / "🔓 12 min") that opens the guard unlock ("Unlock 15 min", "Unlock 30 min", "Lock now"; when `guards.chat_unlock` is off it says so in plain words with the exact config line). Now is the home tab: a Today tile card over the last 24 h (needs-you count in warn color, list-price spend with a sparkline and the Main/agents split, agent runs with running/died counts and a sparkline, open plans), then one card per open `WAITING on owner:` plan — the plan's `#` title, the ask in plain words, the goal folded into a Background block, and "Yes"/"No"/"Reply…" actions whose answer shows as a one-time receipt ("Sent to Main · 08:12"); once the owner inbox already holds an answer for a plan, the card says so ("You answered ‘yes' · 14:19 — Main is on it") with a small change-answer link. The queue is one flat ranked list in `INDEX.md` order — drag a card by its ≡ handle, or tap "↑ top"/"↑"/"↓"; the drop rewrites `INDEX.md`, Main gets the move as a message and the page confirms "Moved to #2" — shown on Now as the first 8 rows with a "Show all N ›" link to the Queue tab. The Agents tab lists working-now rows, the agent-score table, open incidents, recent merges/CI and machine health; the Spend tab pairs the spend tile with per-model spend over 24 h. Light and dark follow the OS; there are no external assets and no build step — one server-rendered HTML string, inline CSS and one small inline script under a per-response CSP nonce (`bun scripts/ui-preview.ts <out.html> [--tab <name>]` renders a preview without a server). No chat, no plan editing, no shell.
117
117
 
118
118
  A request is served only when the peer is a tailnet address that is neither loopback nor this machine's own tailnet IP, `tailscale whois` names the `ui.owner_login` login — and the Host header is this machine: the tailnet address or the MagicDNS name, with the served port. The Host check runs on every request before whois, and a POST's Origin must match it, so a DNS-rebinding page (foreign Host, matching Origin, owner's phone) gets a 403 like everyone else. Every request logs one `UI <method> <path> login=<l> → <code>` line to the guard log.
119
119
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.22",
3
+ "version": "0.2.23",
4
4
  "description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -93,6 +93,27 @@ export interface QuestionRow {
93
93
  waitingLine: string;
94
94
  goal: string[];
95
95
  waitingMin: number;
96
+ /** The last answer this plan already got (from the owner inbox), so the card can say so. */
97
+ answered: { answer: string; at: number } | null;
98
+ }
99
+
100
+ /** The newest inbox record that carries an answer for this plan, if any. A missing or torn inbox is simply "no answer". */
101
+ function lastAnswerFor(plan: string): { answer: string; at: number } | null {
102
+ let lines: string[];
103
+ try {
104
+ lines = readFileSync(inboxPath(), "utf8").split("\n");
105
+ } catch {
106
+ return null;
107
+ }
108
+ for (let i = lines.length - 1; i >= 0; i--) {
109
+ const line = lines[i]!.trim();
110
+ if (!line) continue;
111
+ try {
112
+ const rec = JSON.parse(line) as Record<string, unknown>;
113
+ if (rec.plan === plan && typeof rec.answer === "string" && rec.answer) return { answer: rec.answer, at: Number(rec.ts) || 0 };
114
+ } catch {}
115
+ }
116
+ return null;
96
117
  }
97
118
 
98
119
  export interface AgentRow {
@@ -155,6 +176,7 @@ export function questionRows(cfg: Config): QuestionRow[] {
155
176
  waitingLine: p.waitingLine ?? "",
156
177
  goal: p.goal,
157
178
  waitingMin,
179
+ answered: lastAnswerFor(p.file),
158
180
  };
159
181
  });
160
182
  }
@@ -216,35 +238,110 @@ export function machineRow(cfg: Config): MachineRow {
216
238
  return { freeGb, diskMin: cfg.machine.disk_min_gb, load, loadMax, cores };
217
239
  }
218
240
 
241
+ /** The numbers behind the top tiles: everything in the last 24 h plus the open-plan count. */
242
+ export interface NowStats {
243
+ /** Total list-price spend over the last 24 h. */
244
+ spend24: number;
245
+ /** The "main" kind's share of spend24. */
246
+ mainSpend: number;
247
+ /** The "sub" kind's share of spend24. */
248
+ agentSpend: number;
249
+ /** Runs seen in the last 24 h. */
250
+ runs24: number;
251
+ /** Of those, the ones still running. */
252
+ running: number;
253
+ /** Of those, the ones that died. */
254
+ died: number;
255
+ /** Spend per hour over the last 24 h: 24 buckets, oldest → newest. */
256
+ spendByHour: number[];
257
+ /** Runs started per hour over the last 24 h: 24 buckets, oldest → newest. */
258
+ runsByHour: number[];
259
+ /** Spend and run count per short model name (after the last /), costliest first. */
260
+ byModel: { model: string; spend: number; runs: number }[];
261
+ /** Open plans in INDEX.md. */
262
+ openPlans: number;
263
+ }
264
+
265
+ /**
266
+ * Pure tile math over `source.listRuns(now - 86400)`: a run is in the window when its
267
+ * bucket time — `startedAt`, else `lastWriteAt` — is newer than exactly 24 h ago, and it
268
+ * counts in the hourly bucket of that time. The run source pre-filters by its own mtime,
269
+ * so the strict window check here is the one rule that decides.
270
+ */
271
+ export function nowStats(cfg: Config, source: RunSource, now: number): NowStats {
272
+ const cut = now - 86400;
273
+ const spendByHour = Array.from({ length: 24 }, () => 0);
274
+ const runsByHour = Array.from({ length: 24 }, () => 0);
275
+ const models = new Map<string, { spend: number; runs: number }>();
276
+ let spend24 = 0;
277
+ let mainSpend = 0;
278
+ let agentSpend = 0;
279
+ let runs24 = 0;
280
+ let running = 0;
281
+ let died = 0;
282
+ for (const r of source.listRuns(cut)) {
283
+ const ts = r.startedAt ?? r.lastWriteAt;
284
+ if (ts <= cut) continue;
285
+ spend24 += r.cost;
286
+ runs24++;
287
+ if (r.kind === "main") mainSpend += r.cost;
288
+ else agentSpend += r.cost;
289
+ if (r.status === "running") running++;
290
+ if (r.status === "died") died++;
291
+ // A future clock (skew) clamps into the newest bucket, never out of the array.
292
+ const hoursAgo = Math.min(23, Math.max(0, Math.floor((now - ts) / 3600)));
293
+ const at = 23 - hoursAgo;
294
+ spendByHour[at]! += r.cost;
295
+ runsByHour[at]! += 1;
296
+ const short = r.model.slice(r.model.lastIndexOf("/") + 1);
297
+ const m = models.get(short) ?? { spend: 0, runs: 0 };
298
+ m.spend += r.cost;
299
+ m.runs += 1;
300
+ models.set(short, m);
301
+ }
302
+ const byModel = [...models.entries()].map(([model, v]) => ({ model, spend: v.spend, runs: v.runs })).sort((a, b) => b.spend - a.spend);
303
+ return { spend24, mainSpend, agentSpend, runs24, running, died, spendByHour, runsByHour, byModel, openPlans: queueRows(cfg).length };
304
+ }
305
+
219
306
  // ---- rendering (consumes the rows above, never the readers directly) ----
220
307
 
221
308
  function needCard(row: QuestionRow, i: number): string {
222
309
  const goals = row.goal.map(g => `<li>${esc(g)}</li>`).join("");
223
310
  const wait = row.waitingMin < 60 ? `waiting ${row.waitingMin} min` : `waiting ${Math.max(1, Math.round(row.waitingMin / 60))} h`;
224
311
  const bg = row.goal.length ? `<details class="bg" id="bg-${i}"><summary>Background</summary><ul>${goals}</ul></details>` : "";
225
- return `<article class="card need">
312
+ let said = "";
313
+ if (row.answered) {
314
+ const text = row.answered.answer;
315
+ const quote = text.length > 80 ? `${text.slice(0, 80)}…` : text;
316
+ const verb = text.toLowerCase() === "yes" || text.toLowerCase() === "no" ? "answered" : "replied";
317
+ said = `<p class="answered">You ${verb} "${esc(quote)}" · ${esc(strftime(row.answered.at, "%H:%M"))} — Main is on it</p>
318
+ <button type="button" class="replybtn link">change answer</button>`;
319
+ }
320
+ const acts = row.answered
321
+ ? said
322
+ : `<div class="acts">
323
+ <button class="btn pri" type="submit" name="answer" value="yes">Yes</button>
324
+ <button class="btn" type="submit" name="answer" value="no">No</button>
325
+ <button type="button" class="btn replybtn">Reply…</button>
326
+ </div>`;
327
+ return `<article class="ask">
226
328
  <p class="eyebrow">${esc(row.repo)} · ${esc(wait)}</p>
227
- <h3>${esc(row.title)}</h3>
228
- <p class="ask">What I need from you</p>
329
+ <b>${esc(row.title)}</b>
229
330
  <p class="q">${esc(row.waitingLine)}</p>
230
331
  ${bg}
231
332
  <form method="post" action="/answer">
232
333
  <input type="hidden" name="plan" value="${esc(row.plan)}">
233
- <div class="acts">
234
- <button class="primary" type="submit" name="answer" value="yes">Yes, go ahead</button>
235
- <button type="submit" name="answer" value="no">No</button>
236
- <button type="button" class="replybtn">Reply…</button>
237
- </div>
334
+ ${acts}
238
335
  <div class="reply" hidden>
239
336
  <textarea name="answer_text" maxlength="${ANSWER_MAX}" rows="3" placeholder="Type your reply"></textarea>
240
- <button class="primary" type="submit">Send reply</button>
337
+ <button class="btn pri" type="submit">Send reply</button>
241
338
  </div>
242
339
  </form>
243
340
  </article>`;
244
341
  }
245
342
 
246
343
  function agentRowHtml(r: AgentRow): string {
247
- const dot = r.status === "running" ? "ok" : "warn";
344
+ const dot = r.status === "running" ? "ok" : r.status === "waiting" ? "warn" : "bad";
248
345
  const mins = r.minutes > 0 ? ` · ${r.minutes} min` : "";
249
346
  return `<li class="agent"><span class="dot ${dot}" aria-hidden="true"></span><span class="aid">${esc(r.id)}</span><span class="model">${esc(r.model)}</span><span class="detail">${esc(r.detail)}${mins}</span></li>`;
250
347
  }
@@ -253,11 +350,10 @@ function queueHtml(rows: QueueRow[]): string {
253
350
  const cards = rows
254
351
  .map(
255
352
  (r, i) => `<li class="qcard" data-plan="${esc(r.file)}">
353
+ <span class="qhandle" title="Drag to reorder" aria-label="Drag ${esc(r.title)}">≡</span>
256
354
  <span class="qrank">${i + 1}</span>
257
- <span class="qhandle" title="Drag to reorder" aria-label="Drag ${esc(r.title)}">⠿</span>
258
355
  <span class="qtitle">${esc(r.title)}</span>
259
- <span class="chip repo">${esc(r.repo)}</span>
260
- ${r.waiting ? `<span class="chip wait">waiting</span>` : ""}
356
+ ${r.waiting ? `<span class="chip c-wait">waits you</span>` : `<span class="chip c-ready">ready</span>`}
261
357
  <span class="qbtns"><button type="button" class="qmove" data-move="top">↑ top</button><button type="button" class="qmove" data-move="up">↑</button><button type="button" class="qmove" data-move="down">↓</button></span>
262
358
  </li>`,
263
359
  )
@@ -305,8 +401,71 @@ function machineHtml(cfg: Config, m: MachineRow): string {
305
401
  ].join("");
306
402
  }
307
403
 
308
- function detailsBlock(id: string, label: string, count: string, inner: string): string {
309
- return `<details id="${id}"><summary>${esc(label)} <span class="chip">${esc(count)}</span></summary><div class="dbody">${inner}</div></details>`;
404
+ /** Inline SVG sparkline (mockup: a 130×40 polyline, oldest → newest, left → right). */
405
+ function sparkSvg(points: number[], stroke: string): string {
406
+ const max = Math.max(...points, 0);
407
+ const n = points.length;
408
+ const pts = points
409
+ .map((v, i) => {
410
+ const x = n <= 1 ? 0 : (i / (n - 1)) * 130;
411
+ const y = max > 0 ? 34 - (v / max) * 28 : 34;
412
+ return `${x.toFixed(1)},${y.toFixed(1)}`;
413
+ })
414
+ .join(" ");
415
+ return `<svg class="spark" viewBox="0 0 130 40" aria-hidden="true"><polyline points="${pts}" fill="none" stroke="${stroke}" stroke-width="2"/></svg>`;
416
+ }
417
+
418
+ function tile(label: string, num: string, numStyle: string, note: string, spark = ""): string {
419
+ return `<div class="tile"><div><div class="lbl">${esc(label)}</div><div class="num"${numStyle ? ` style="${numStyle}"` : ""}>${num}</div><div class="note">${note}</div></div>${spark}</div>`;
420
+ }
421
+
422
+ function spendTileHtml(data: PageData): string {
423
+ const s = data.stats;
424
+ return s
425
+ ? tile("Spend (list price)", `$${s.spend24.toFixed(2)}`, "", `Main $${s.mainSpend.toFixed(2)} · agents $${s.agentSpend.toFixed(2)}`, sparkSvg(s.spendByHour, "var(--acc)"))
426
+ : tile("Spend (list price)", "–", "", "–");
427
+ }
428
+
429
+ /** The mockup's Today tile card: needs-you, spend, agent runs, open plans. */
430
+ function tilesHtml(data: PageData): string {
431
+ const needs = data.questions === null ? null : data.questions.length;
432
+ const needsTile = needs === null ? tile("Needs you", "–", "", "–") : needs > 0 ? tile("Needs you", String(needs), "color:var(--warn)", "answer below ↓") : tile("Needs you", "0", "", "all clear");
433
+ const runs = data.stats ? tile("Agent runs", String(data.stats.runs24), "", `${data.stats.running} running · ${data.stats.died} died`, sparkSvg(data.stats.runsByHour, "var(--teal)")) : tile("Agent runs", "–", "", "–");
434
+ const plans = data.stats ? tile("Plans", String(data.stats.openPlans), "", `<span style="color:var(--ok)">open</span>`) : tile("Plans", "–", "", "–");
435
+ return [needsTile, spendTileHtml(data), runs, plans].join("\n");
436
+ }
437
+
438
+ /** The sticky mockup top bar: logo, pill tabs, and the lock pill that posts the unlock/lock forms. */
439
+ function topBarHtml(tab: string, lockMinutesLeft: number | null, cfg: Config): string {
440
+ const tabs: [string, string][] = [["now", "Now"], ["queue", "Queue"], ["agents", "Agents"], ["spend", "Spend"]];
441
+ const pills = tabs.map(([id, label]) => `<a href="/?tab=${id}"${tab === id ? ` class="on"` : ""}>${label}</a>`).join("");
442
+ const lockLabel = lockMinutesLeft === null ? "🔒 Off" : `🔓 ${lockMinutesLeft} min`;
443
+ const unlockForm = (minutes: number) =>
444
+ `<form method="post" action="/unlock"><input type="hidden" name="minutes" value="${minutes}"><button class="btn" type="submit">Unlock ${minutes} min</button></form>`;
445
+ const off = cfg.guards.chat_unlock
446
+ ? ""
447
+ : `<p class="offnote">Unlocking from the page is switched off in the config. To turn it on, set:</p><code class="offcfg">guards: chat_unlock: true</code>`;
448
+ return `<div class="top"><span class="logo">ns</span>
449
+ <nav class="pills" aria-label="Sections">${pills}</nav>
450
+ <details class="lock" id="lock-pill"><summary>${lockLabel}</summary><div class="lockmenu">${unlockForm(15)}${unlockForm(30)}<form method="post" action="/lock"><button class="btn" type="submit">Lock now</button></form>${off}</div></details>
451
+ </div>`;
452
+ }
453
+
454
+ /** The queue card. Full on the Queue tab; the Now tab shows the first 8 rows plus the "Show all" link — the drag script merges the hidden rest from the form's before field, so a drag still posts the complete order. */
455
+ function queueCard(rows: QueueRow[] | null, full: boolean): string {
456
+ const head = full ? "" : `<h2>Queue <small>drag ≡ to sort</small></h2>`;
457
+ if (rows === null) return `${head}<div class="card">${na("Queue")}</div>`;
458
+ if (!rows.length) return `${head}<div class="card"><p class="empty">The queue is empty</p></div>`;
459
+ const body = queueHtml(full ? rows : rows.slice(0, 8));
460
+ const more = !full && rows.length > 8 ? `<a class="more" href="/?tab=queue">Show all ${rows.length} ›</a>` : "";
461
+ return `${head}<div class="card">${body}${more}</div>`;
462
+ }
463
+
464
+ function modelSpendTable(stats: NowStats | null): string {
465
+ if (stats === null) return na("Spend");
466
+ if (!stats.byModel.length) return `<p class="empty">No spend recorded in the last 24 hours</p>`;
467
+ const rows = stats.byModel.map(m => `<tr><td>${esc(m.model)}</td><td>$${m.spend.toFixed(2)}</td><td>${m.runs}</td></tr>`).join("");
468
+ return `<table><thead><tr><th>Model</th><th>Spend</th><th>Runs</th></tr></thead><tbody>${rows}</tbody></table>`;
310
469
  }
311
470
 
312
471
  function na(label: string): string {
@@ -336,22 +495,15 @@ function receiptHtml(sent: string | null, params: URLSearchParams): string {
336
495
  case "unlock-off":
337
496
  text = "Refused — chat unlock is off";
338
497
  break;
498
+ case "stale":
499
+ text = "Already handled — Main cleared this question before your answer; your answer was still passed on.";
500
+ break;
339
501
  default:
340
502
  return "";
341
503
  }
342
504
  return `<div class="receipt" role="status">${esc(text)}</div>`;
343
505
  }
344
506
 
345
- function bottomBar(cfg: Config, lockMinutesLeft: number | null): string {
346
- const state = lockMinutesLeft === null ? "Locked" : `Unlocked · ${lockMinutesLeft} min left`;
347
- const unlockBtn = (minutes: number) =>
348
- `<form method="post" action="/unlock"><input type="hidden" name="minutes" value="${minutes}"><button type="submit">Unlock ${minutes} min</button></form>`;
349
- const off = cfg.guards.chat_unlock
350
- ? ""
351
- : `<p class="offnote">Unlocking from the page is switched off in the config. To turn it on, set:</p><code class="offcfg">guards: chat_unlock: true</code>`;
352
- return `<footer class="bar"><div class="barline"><div class="barinner"><p class="lockstate${lockMinutesLeft === null ? "" : " on"}">${esc(state)}</p><div class="barbtns">${unlockBtn(15)}${unlockBtn(30)}<form method="post" action="/lock"><button type="submit">Lock now</button></form></div></div></div>${off}</footer>`;
353
- }
354
-
355
507
  // ---- page assembly: one unreadable source never takes the page down ----
356
508
 
357
509
  export interface PageData {
@@ -362,6 +514,8 @@ export interface PageData {
362
514
  incidents: IncidentRow[] | null;
363
515
  scores: ScoresData | null;
364
516
  machine: MachineRow | null;
517
+ /** The 24 h tile numbers; null when the run source is unreadable. */
518
+ stats: NowStats | null;
365
519
  /** Minutes left in the guard unlock; null = locked. */
366
520
  lockMinutesLeft: number | null;
367
521
  }
@@ -394,37 +548,11 @@ export function buildPageData(cfg: Config, source: RunSource): PageData {
394
548
  incidents: safe(() => incidentRows(cfg)),
395
549
  scores: safe(() => scoresData(cfg)),
396
550
  machine: safe(() => machineRow(cfg)),
551
+ stats: safe(() => nowStats(cfg, source, nowSec())),
397
552
  lockMinutesLeft: lockMinutesLeft(cfg),
398
553
  };
399
554
  }
400
555
 
401
- function stripHtml(data: PageData): string {
402
- const n = data.questions?.length ?? null;
403
- const left =
404
- n === null
405
- ? `<span class="count na">–</span>`
406
- : n === 0
407
- ? `<span class="count clear">All clear</span>`
408
- : `<a class="count" href="#needs" aria-label="${n} plans need you">${n}</a>`;
409
- const working = data.agents === null ? "working –" : `${data.agents.length} working`;
410
- const ci =
411
- data.incidents === null
412
- ? "CI –"
413
- : data.incidents.length
414
- ? `<span class="bad">${data.incidents.length === 1 ? "1 incident" : `${data.incidents.length} incidents`}</span>`
415
- : `<span class="fine">CI ok</span>`;
416
- const m = data.machine;
417
- const disk =
418
- m === null
419
- ? "disk –"
420
- : m.freeGb < m.diskMin
421
- ? `<span class="bad">disk ${m.freeGb.toFixed(0)} GB</span>`
422
- : m.load > m.loadMax
423
- ? `<span class="bad">load ${m.load.toFixed(1)}</span>`
424
- : `disk ${m.freeGb.toFixed(0)} GB`;
425
- return `<header class="strip"><div class="barinner stripinner">${left}<div class="signals"><span>${esc(working)}</span><span>${ci}</span><span>${disk}</span></div></div></header>`;
426
- }
427
-
428
556
  const FAVICON =
429
557
  "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect width='16' height='16' rx='4' fill='%23D98E04'/%3E%3C/svg%3E";
430
558
 
@@ -440,7 +568,7 @@ var dragging=false;
440
568
  if(qlist){
441
569
  var rform=document.getElementById("reorder-form");
442
570
  var qcards=function(){return Array.prototype.slice.call(qlist.querySelectorAll(".qcard"));};
443
- var submitReorder=function(moved){if(!rform)return;var o=qcards().map(function(c){return c.getAttribute("data-plan");}).join("\\n");rform.querySelector("[name=order]").value=o;rform.querySelector("[name=moved]").value=moved;dragging=false;rform.submit();};
571
+ var submitReorder=function(moved){if(!rform)return;var shown=qcards().map(function(c){return c.getAttribute("data-plan");});var bf=(rform.querySelector("[name=before]").value||"").split("\\n").filter(function(x){return x;});var o=shown.slice();for(var i=0;i<bf.length;i++){if(shown.indexOf(bf[i])<0)o.push(bf[i]);}rform.querySelector("[name=order]").value=o.join("\\n");rform.querySelector("[name=moved]").value=moved;dragging=false;rform.submit();};
444
572
  var moveCard=function(card,how){if(how==="top"){var f=qcards()[0];if(f&&f!==card)qlist.insertBefore(card,f);}else if(how==="up"){var p=card.previousElementSibling;if(p&&p.classList.contains("qcard"))qlist.insertBefore(card,p);}else if(how==="down"){var n=card.nextElementSibling;if(n&&n.classList.contains("qcard"))qlist.insertBefore(card,n.nextSibling);}};
445
573
  qlist.addEventListener("click",function(e){var t=e.target;if(!t||!t.closest)return;var b=t.closest(".qmove");if(!b)return;var card=t.closest(".qcard");if(!card)return;moveCard(card,b.getAttribute("data-move"));submitReorder(card.getAttribute("data-plan"));});
446
574
  var drag=null;
@@ -456,39 +584,69 @@ setInterval(function(){if(!busy())location.reload();},${REFRESH_SEC}000);
456
584
 
457
585
  /** The whole page as one HTML string. Exported for scripts/ui-preview.ts (no server). */
458
586
  export function renderPage(cfg: Config, data: PageData, params: URLSearchParams, nonce: string): string {
459
- const needs = data.questions === null ? na("Waiting on you") : data.questions.length ? data.questions.map(needCard).join("\n") : `<p class="empty">Nothing needs you right now</p>`;
587
+ const req = params.get("tab") ?? "";
588
+ // Server-rendered tabs: the pill links carry ?tab=; anything unknown renders Now.
589
+ const tab = req === "queue" || req === "agents" || req === "spend" ? req : "now";
590
+ const needsBody =
591
+ data.questions === null
592
+ ? na("Waiting on you")
593
+ : data.questions.length
594
+ ? data.questions.map(needCard).join("\n")
595
+ : `<p class="empty">Nothing needs you right now</p>`;
460
596
  const working =
461
597
  data.agents === null ? na("Working now") : data.agents.length ? `<ul class="agents">${data.agents.map(agentRowHtml).join("")}</ul>` : `<p class="empty">No agents running</p>`;
462
- const queue = detailsBlock(
463
- "d-queue",
464
- "Queue",
465
- data.queue === null ? "–" : String(data.queue.length),
466
- data.queue === null ? na("Queue") : data.queue.length ? queueHtml(data.queue) : `<p class="empty">The queue is empty</p>`,
467
- );
468
- const merges = detailsBlock(
469
- "d-merges",
470
- "Merges",
471
- data.ci === null ? "–" : String(data.ci.length),
472
- data.ci === null ? na("Merges") : data.ci.length ? ciHtml(data.ci) : `<p class="empty">No CI runs recorded</p>`,
473
- );
474
- const incidents = detailsBlock(
475
- "d-incidents",
476
- "Incidents",
477
- data.incidents === null ? "–" : String(data.incidents.length),
478
- data.incidents === null ? na("Incidents") : data.incidents.length ? incidentsHtml(data.incidents) : `<p class="empty">No open incidents</p>`,
479
- );
480
- const scores = detailsBlock(
481
- "d-scores",
482
- "Agent scores",
483
- data.scores === null ? "–" : String(data.scores.rows.length + data.scores.text.length),
484
- data.scores === null ? na("Agent scores") : scoresHtml(data.scores),
485
- );
486
- const machine = detailsBlock(
487
- "d-machine",
488
- "Machine",
489
- data.machine === null ? "–" : `${data.machine.freeGb.toFixed(0)} GB`,
490
- data.machine === null ? na("Machine") : machineHtml(cfg, data.machine),
491
- );
598
+ const scores = data.scores === null ? na("Agent scores") : scoresHtml(data.scores);
599
+ const incidents = data.incidents === null ? na("Incidents") : data.incidents.length ? incidentsHtml(data.incidents) : `<p class="empty">No open incidents</p>`;
600
+ const merges = data.ci === null ? na("Merges") : data.ci.length ? ciHtml(data.ci) : `<p class="empty">No CI runs recorded</p>`;
601
+ const machine = data.machine === null ? na("Machine") : machineHtml(cfg, data.machine);
602
+ const body =
603
+ tab === "now"
604
+ ? `<h1>Today</h1>
605
+ <p class="sub">What your agents did in the last 24 hours.</p>
606
+ <div class="card">
607
+ ${tilesHtml(data)}
608
+ </div>
609
+ <h2>Needs you</h2>
610
+ <div class="card">
611
+ ${needsBody}
612
+ </div>
613
+ ${queueCard(data.queue, false)}`
614
+ : tab === "queue"
615
+ ? `<h1>Queue</h1>
616
+ <p class="sub">Drag ≡ to sort — Main works by the new order on its next turn.</p>
617
+ ${queueCard(data.queue, true)}`
618
+ : tab === "agents"
619
+ ? `<h1>Agents</h1>
620
+ <p class="sub">Who is working right now, how they score, and what went wrong.</p>
621
+ <h2>Working now</h2>
622
+ <div class="card">
623
+ ${working}
624
+ </div>
625
+ <h2>Agent scores</h2>
626
+ <div class="card">
627
+ ${scores}
628
+ </div>
629
+ <h2>Incidents</h2>
630
+ <div class="card">
631
+ ${incidents}
632
+ </div>
633
+ <h2>Merges</h2>
634
+ <div class="card">
635
+ ${merges}
636
+ </div>
637
+ <h2>Machine</h2>
638
+ <div class="card">
639
+ ${machine}
640
+ </div>`
641
+ : `<h1>Spend</h1>
642
+ <p class="sub">List price over the last 24 hours.</p>
643
+ <div class="card">
644
+ ${spendTileHtml(data)}
645
+ </div>
646
+ <h2>By model</h2>
647
+ <div class="card">
648
+ ${modelSpendTable(data.stats)}
649
+ </div>`;
492
650
  return `<!doctype html>
493
651
  <html lang="en">
494
652
  <head>
@@ -498,102 +656,97 @@ export function renderPage(cfg: Config, data: PageData, params: URLSearchParams,
498
656
  <title>neurastream</title>
499
657
  <link rel="icon" href="${FAVICON}">
500
658
  <style>
501
- :root { color-scheme: light dark; --ink:#1C2430; --page:#EEF1F5; --card:#FFFFFF; --line:#D5DBE3; --muted:#5E6A7A; --amber:#D98E04; --teal:#0F8A8A; --red:#C8382F; --on-amber:#10141A; }
502
- @media (prefers-color-scheme: dark) { :root { --ink:#E6EAF0; --page:#10141A; --card:#1A2029; --line:#2A323D; --muted:#94A0B0; } }
503
- * { box-sizing: border-box; }
504
- html { scroll-padding-top: 72px; }
505
- body { margin: 0; background: var(--page); color: var(--ink); font: 17px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
506
- .barinner { max-width: 36rem; margin: 0 auto; padding: 0 16px; }
507
- .mono, .aid, .model { font-family: ui-monospace, "SF Mono", "Roboto Mono", monospace; font-size: 14px; }
508
- .strip { position: sticky; top: 0; z-index: 5; background: var(--page); border-bottom: 1px solid var(--line); }
509
- .stripinner { display: flex; align-items: center; justify-content: space-between; min-height: 64px; }
510
- .count { color: var(--amber); font-size: 34px; font-weight: 800; font-variant-numeric: tabular-nums; text-decoration: none; }
511
- .count.clear { color: var(--teal); font-size: 20px; font-weight: 700; }
512
- .count.na { color: var(--muted); font-size: 20px; }
513
- .signals { display: flex; gap: 12px; color: var(--muted); font-size: 14px; text-align: right; }
514
- .bad { color: var(--red); font-weight: 600; }
515
- .fine { color: var(--teal); }
516
- main { padding-bottom: 96px; }
517
- .receipt { max-width: 36rem; margin: 12px auto 0; padding: 10px 16px; background: var(--card); border: 1px solid var(--teal); border-radius: 14px; color: var(--teal); font-weight: 600; }
518
- .card { background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: 14px 16px; margin: 16px 0; }
519
- .need { border-left: 4px solid var(--amber); }
520
- .eyebrow { margin: 0 0 2px; color: var(--muted); font-size: 14px; }
521
- .need .eyebrow { color: var(--amber); }
522
- .card h3 { margin: 2px 0 8px; font-size: 20px; font-weight: 650; }
523
- .ask { margin: 0 0 2px; color: var(--muted); font-size: 14px; }
524
- .q { margin: 0 0 10px; }
525
- details.bg { margin: 8px 0; border-top: 1px solid var(--line); padding-top: 6px; }
526
- details.bg summary, details.block summary { min-height: 48px; display: flex; align-items: center; gap: 8px; color: var(--muted); }
527
- details.bg ul { margin: 4px 0 8px; padding-left: 20px; }
528
- .acts { display: flex; gap: 8px; flex-wrap: wrap; }
529
- button { min-height: 48px; padding: 8px 14px; border-radius: 10px; border: 1px solid var(--line); background: var(--card); color: var(--ink); font: inherit; }
530
- button.primary { background: var(--amber); border-color: var(--amber); color: var(--on-amber); font-weight: 650; }
531
- :focus-visible { outline: 2px solid var(--amber); outline-offset: 2px; }
532
- .reply { margin-top: 8px; }
533
- .reply textarea { width: 100%; padding: 10px; border-radius: 10px; border: 1px solid var(--line); background: var(--page); color: var(--ink); font: inherit; }
534
- .agents { list-style: none; margin: 0; padding: 0; }
535
- .agent { display: flex; align-items: baseline; gap: 8px; padding: 8px 0; border-bottom: 1px solid var(--line); flex-wrap: wrap; }
536
- .agent:last-child { border-bottom: none; }
537
- .dot { width: 10px; height: 10px; border-radius: 50%; align-self: center; flex: none; }
538
- .dot.ok { background: var(--teal); }
539
- .dot.warn { background: var(--amber); }
540
- .model { color: var(--muted); }
541
- .detail { color: var(--muted); }
542
- details.block { background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: 4px 16px; margin: 12px 0; }
543
- details.block .dbody { border-top: 1px solid var(--line); padding: 10px 0 12px; }
544
- .chip { display: inline-block; padding: 1px 8px; border: 1px solid var(--line); border-radius: 999px; font-size: 13px; color: var(--muted); }
545
- .chip.bad { color: var(--red); border-color: var(--red); }
546
- .chip.wait { color: var(--amber); border-color: var(--amber); }
547
- .qlist { list-style: none; margin: 0; padding: 0; }
548
- .qcard { display: flex; align-items: center; gap: 8px; padding: 8px 0; border-bottom: 1px solid var(--line); flex-wrap: wrap; }
549
- .qcard:last-child { border-bottom: none; }
550
- .qcard.dragging { position: fixed; z-index: 20; background: var(--card); border: 1px solid var(--amber); border-radius: 14px; padding: 10px 12px; margin: 0; user-select: none; opacity: 0.96; }
551
- .qph { list-style: none; border: 2px dashed var(--line); border-radius: 14px; margin: 4px 0; }
552
- .qrank { font-family: ui-monospace, "SF Mono", "Roboto Mono", monospace; font-size: 14px; color: var(--muted); min-width: 1.6em; text-align: right; font-variant-numeric: tabular-nums; }
553
- .qhandle { touch-action: none; padding: 12px 10px; color: var(--muted); font-size: 18px; user-select: none; }
554
- .qtitle { flex: 1 1 12em; min-width: 0; }
555
- .chip.repo { color: var(--teal); border-color: var(--teal); }
556
- .qbtns { display: flex; gap: 6px; flex-wrap: wrap; margin-left: auto; }
557
- .qbtns button { min-height: 48px; padding: 4px 10px; font-size: 14px; }
558
- .merges, .incidents { margin: 0; padding-left: 20px; }
559
- .merges li, .incidents li { margin: 6px 0; }
560
- table { border-collapse: collapse; width: 100%; font-size: 14px; }
561
- th, td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--line); font-variant-numeric: tabular-nums; }
562
- th { color: var(--muted); font-weight: 600; }
563
- .mrow { display: flex; justify-content: space-between; gap: 12px; padding: 6px 0; border-bottom: 1px solid var(--line); }
564
- .mrow:last-child { border-bottom: none; }
565
- .empty { color: var(--muted); }
566
- .na { color: var(--muted); font-style: italic; }
567
- .bar { position: sticky; bottom: 0; z-index: 5; background: var(--page); border-top: 1px solid var(--line); padding-bottom: env(safe-area-inset-bottom); }
568
- .barline { display: flex; align-items: center; justify-content: space-between; gap: 12px; min-height: 64px; flex-wrap: wrap; padding-top: 6px; padding-bottom: 6px; }
569
- .lockstate { margin: 0; font-weight: 650; color: var(--muted); }
570
- .lockstate.on { color: var(--teal); }
571
- .barbtns { display: flex; gap: 8px; flex-wrap: wrap; }
572
- .barbtns button { min-height: 40px; padding: 6px 10px; font-size: 15px; }
573
- .offnote { margin: 0; color: var(--muted); font-size: 14px; }
574
- .offcfg { display: block; font-family: ui-monospace, "SF Mono", "Roboto Mono", monospace; font-size: 14px; padding: 4px 0 10px; }
575
- @media (max-width: 360px) { .signals { display: none; } }
659
+ :root{--bg:#f4f4f6;--card:#fff;--fg:#111;--mut:#6b6b76;--bd:#e4e4ea;--acc:#c026d3;--teal:#0d9488;--warn:#d97706;--ok:#16a34a;--red:#dc2626}
660
+ @media(prefers-color-scheme:dark){:root{--bg:#0e0e11;--card:#18181c;--fg:#f2f2f4;--mut:#9a9aa6;--bd:#2a2a31}}
661
+ *{box-sizing:border-box}
662
+ html{scroll-padding-top:64px}
663
+ body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.4 system-ui,-apple-system,sans-serif}
664
+ .top{position:sticky;top:0;display:flex;align-items:center;gap:8px;padding:10px 12px;background:var(--bg);z-index:2}
665
+ .logo{font-weight:800;color:var(--acc)}
666
+ .pills{display:flex;background:var(--card);border:1px solid var(--bd);border-radius:999px;padding:3px;flex:1}
667
+ .pills a{flex:1;text-align:center;padding:5px 0;border-radius:999px;color:var(--mut);text-decoration:none;font-size:13px}
668
+ .pills a.on{background:var(--bg);color:var(--fg);font-weight:600;box-shadow:0 0 0 1px var(--bd)}
669
+ .lock{border:1px solid var(--bd);background:var(--card);border-radius:999px;padding:6px 10px;font-size:13px;color:var(--fg);position:relative;flex:none}
670
+ .lock summary{list-style:none;white-space:nowrap}
671
+ .lock summary::-webkit-details-marker{display:none}
672
+ .lockmenu{position:absolute;right:0;top:calc(100% + 6px);background:var(--card);border:1px solid var(--bd);border-radius:14px;padding:10px;display:flex;flex-direction:column;gap:6px;min-width:170px;z-index:10}
673
+ .lockmenu .btn{margin:0}
674
+ .offnote{margin:0;color:var(--mut);font-size:12px}
675
+ .offcfg{font-family:ui-monospace,"SF Mono","Roboto Mono",monospace;font-size:12px}
676
+ main{padding:4px 12px 40px}
677
+ h1{font-size:26px;margin:8px 0 2px}
678
+ h2{font-size:17px;margin:22px 4px 8px;display:flex;justify-content:space-between;align-items:baseline}
679
+ h2 small{font-size:12px;color:var(--mut);font-weight:400}
680
+ .sub{color:var(--mut);font-size:13px;margin:0 0 12px}
681
+ .card{background:var(--card);border:1px solid var(--bd);border-radius:14px;overflow:hidden}
682
+ .tile{padding:14px 16px;border-top:1px solid var(--bd);display:flex;justify-content:space-between;align-items:flex-end;gap:8px}
683
+ .tile:first-child{border-top:0}
684
+ .lbl{font-size:13px;color:var(--mut)}
685
+ .num{font-size:30px;font-weight:700;line-height:1.1;font-variant-numeric:tabular-nums}
686
+ .note{font-size:12px;color:var(--mut)}
687
+ svg.spark{width:130px;height:40px;flex:none}
688
+ .receipt{margin:12px 12px 0;padding:10px 16px;background:var(--card);border:1px solid var(--teal);border-radius:14px;color:var(--teal);font-weight:600}
689
+ .eyebrow{margin:0 0 2px;color:var(--mut);font-size:13px}
690
+ .ask{padding:14px 16px;border-top:1px solid var(--bd)}
691
+ .ask:first-child{border-top:0}
692
+ .ask b{display:block;font-size:16px}
693
+ .ask p{margin:2px 0 10px;color:var(--mut);font-size:13px}
694
+ .ask .q{color:var(--fg);font-size:14px;margin:0 0 8px}
695
+ .answered{color:var(--ok)!important;margin:0 0 4px!important}
696
+ .link{border:0;background:none;color:var(--mut);text-decoration:underline;padding:0;font:inherit;font-size:13px}
697
+ .acts{display:flex;gap:6px;flex-wrap:wrap}
698
+ .btn{border:1px solid var(--bd);background:var(--card);color:var(--fg);border-radius:999px;padding:6px 16px;font-size:14px;margin-right:6px;font-family:inherit}
699
+ .btn.pri{background:var(--acc);border-color:var(--acc);color:#fff}
700
+ :focus-visible{outline:2px solid var(--acc);outline-offset:2px}
701
+ .reply{margin-top:8px}
702
+ .reply textarea{width:100%;padding:10px;border-radius:10px;border:1px solid var(--bd);background:var(--bg);color:var(--fg);font:inherit}
703
+ details.bg{margin:8px 0;border-top:1px solid var(--bd);padding-top:6px}
704
+ details.bg summary{color:var(--mut)}
705
+ details.bg ul{margin:4px 0 8px;padding-left:20px;color:var(--mut);font-size:13px}
706
+ .qlist{list-style:none;margin:0;padding:0}
707
+ .qcard{display:flex;align-items:center;gap:10px;padding:12px 14px;border-top:1px solid var(--bd);flex-wrap:wrap}
708
+ .qcard:first-child{border-top:0}
709
+ .qcard.dragging{position:fixed;z-index:20;background:var(--card);border:1px solid var(--acc);border-radius:14px;margin:0;user-select:none;opacity:0.96}
710
+ .qph{list-style:none;border:2px dashed var(--bd);margin:4px 0}
711
+ .qhandle{color:var(--mut);font-size:18px;touch-action:none;padding:2px 2px;user-select:none;flex:none}
712
+ .qrank{color:var(--mut);width:18px;font-size:13px;text-align:right;font-variant-numeric:tabular-nums;flex:none}
713
+ .qtitle{flex:1 1 12em;min-width:0}
714
+ .chip{font-size:11px;padding:2px 8px;border-radius:999px;white-space:nowrap;flex:none}
715
+ .c-wait{background:color-mix(in srgb,var(--warn) 18%,transparent);color:var(--warn)}
716
+ .c-run{background:color-mix(in srgb,var(--teal) 18%,transparent);color:var(--teal)}
717
+ .c-ready{background:color-mix(in srgb,var(--mut) 15%,transparent);color:var(--mut)}
718
+ .chip.bad{color:var(--red)}
719
+ .qbtns{display:flex;gap:4px;flex-wrap:wrap;margin-left:auto}
720
+ .qbtns button{min-height:32px;padding:2px 10px;font-size:12px;border-radius:999px;border:1px solid var(--bd);background:var(--card);color:var(--mut)}
721
+ .more{display:block;text-align:center;padding:12px;color:var(--acc);text-decoration:none;border-top:1px solid var(--bd);font-size:14px}
722
+ .agents{list-style:none;margin:0;padding:8px 14px}
723
+ .agent{display:flex;align-items:baseline;gap:8px;padding:8px 0;border-bottom:1px solid var(--bd);flex-wrap:wrap}
724
+ .agent:last-child{border-bottom:none}
725
+ .dot{width:10px;height:10px;border-radius:50%;align-self:center;flex:none}
726
+ .dot.ok{background:var(--teal)}
727
+ .dot.warn{background:var(--warn)}
728
+ .dot.bad{background:var(--red)}
729
+ .mono,.aid,.model{font-family:ui-monospace,"SF Mono","Roboto Mono",monospace;font-size:13px}
730
+ .model,.detail{color:var(--mut)}
731
+ table{border-collapse:collapse;width:100%;font-size:13px}
732
+ th,td{text-align:left;padding:6px 8px;border-bottom:1px solid var(--bd);font-variant-numeric:tabular-nums}
733
+ th{color:var(--mut);font-weight:600}
734
+ tr:last-child td{border-bottom:none}
735
+ .merges,.incidents{margin:0;padding:8px 14px 8px 32px}
736
+ .merges li,.incidents li{margin:6px 0}
737
+ .mrow{display:flex;justify-content:space-between;gap:12px;padding:6px 0;border-bottom:1px solid var(--bd)}
738
+ .mrow:last-child{border-bottom:none}
739
+ .bad{color:var(--red);font-weight:600}
740
+ .empty{color:var(--mut);padding:14px 16px;margin:0}
741
+ .na{color:var(--mut);font-style:italic;padding:14px 16px;margin:0}
576
742
  </style>
577
743
  </head>
578
744
  <body>
579
- ${stripHtml(data)}
745
+ ${topBarHtml(tab, data.lockMinutesLeft, cfg)}
580
746
  ${receiptHtml(params.get("sent"), params)}
581
747
  <main>
582
- <section id="needs"><h2 class="srt">Needs you</h2>
583
- ${needs}
584
- </section>
585
- <section id="working"><h2 class="srt">Working now</h2>
586
- ${working}
587
- </section>
588
- <div class="barinner">
589
- ${queue}
590
- ${merges}
591
- ${incidents}
592
- ${scores}
593
- ${machine}
594
- </div>
748
+ ${body}
595
749
  </main>
596
- ${bottomBar(cfg, data.lockMinutesLeft)}
597
750
  <script nonce="${nonce}">${SCRIPT}</script>
598
751
  </body>
599
752
  </html>`;
@@ -620,17 +773,45 @@ function redirect(target: string): Response {
620
773
  return new Response(null, { status: 303, headers: { location: target } });
621
774
  }
622
775
 
623
- function handleAnswer(cfg: Config, fields: Record<string, string>, login: string): Response {
776
+ /** The normal page (the GET layout) as a POST reply; the stale-answer reply is this with sent=stale. */
777
+ function pageRes(cfg: Config, source: RunSource, params: URLSearchParams): Response {
778
+ const nonce = randomUUID().replaceAll("-", "");
779
+ return new Response(renderPage(cfg, buildPageData(cfg, source), params, nonce), {
780
+ status: 200,
781
+ headers: {
782
+ "content-type": "text/html; charset=utf-8",
783
+ "content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${nonce}'; img-src data:; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`,
784
+ },
785
+ });
786
+ }
787
+
788
+ /** The last answer appended per plan, for the double-press guard (P8c): memory only, no file. */
789
+ const lastAnswerByPlan = new Map<string, { answer: string; ts: number }>();
790
+ const DOUBLE_PRESS_SEC = 10;
791
+
792
+ /** Appends the answer to the owner inbox unless this plan got the same trimmed answer in the last 10 s (P8c). */
793
+ function appendAnswer(plan: string, question: string, answer: string, login: string): void {
794
+ const now = nowSec();
795
+ const last = lastAnswerByPlan.get(plan);
796
+ if (last !== undefined && last.answer === answer && now - last.ts < DOUBLE_PRESS_SEC) return;
797
+ mkdirSync(stateDirPath(), { recursive: true });
798
+ appendFileSync(inboxPath(), `${JSON.stringify({ ts: now, plan, question, answer, login })}\n`);
799
+ lastAnswerByPlan.set(plan, { answer, ts: now });
800
+ }
801
+
802
+ function handleAnswer(cfg: Config, source: RunSource, fields: Record<string, string>, login: string): Response {
624
803
  const planFile = (fields.plan ?? "").trim();
625
804
  const answer = (fields.answer_text ?? "").trim() || (fields.answer ?? "").trim();
626
805
  if (!planFile || !answer) return textRes("plan and answer are required", 400);
627
806
  if (answer.length > ANSWER_MAX) return textRes(`answer is longer than ${ANSWER_MAX} chars`, 400);
628
807
  const plan = activePlans(cfg.paths.queue_index).find(p => p.file === planFile);
629
- if (!plan || plan.status !== "open" || !plan.waiting || !plan.waitingLine) {
630
- return textRes("plan is not open and waiting", 409);
808
+ if (!plan) return textRes("plan is not open and waiting", 409);
809
+ if (plan.status !== "open" || !plan.waiting || !plan.waitingLine) {
810
+ // Stale answer (P8b): Main cleared the question before the answer arrived; pass it on anyway.
811
+ appendAnswer(planFile, "(already cleared)", answer, login);
812
+ return pageRes(cfg, source, new URLSearchParams({ sent: "stale" }));
631
813
  }
632
- mkdirSync(stateDirPath(), { recursive: true });
633
- appendFileSync(inboxPath(), `${JSON.stringify({ ts: nowSec(), plan: planFile, question: plan.waitingLine, answer, login })}\n`);
814
+ appendAnswer(planFile, plan.waitingLine, answer, login);
634
815
  return redirect("/?sent=answer");
635
816
  }
636
817
 
@@ -757,6 +938,9 @@ function handleReorder(cfg: Config, fields: Record<string, string>, login: strin
757
938
  /** Starts the page. Refuses to start when ui.enabled is false or ui.owner_login is empty, and on the default hostname when tailscale does not answer. */
758
939
  export function startOwnerUi(opts: OwnerUiOptions): OwnerUiServer {
759
940
  const { cfg, tailscale, source } = opts;
941
+ // The double-press guard (P8c) is per-server memory: a fresh server starts empty, which also
942
+ // keeps the tests (one server per test) hermetic.
943
+ lastAnswerByPlan.clear();
760
944
  if (!cfg.ui.enabled) throw new Error("owner ui: ui.enabled is false — set it in the config first");
761
945
  if (!cfg.ui.owner_login) throw new Error("owner ui: ui.owner_login is empty — set the tailscale login that may open the page");
762
946
  const hostname = opts.hostname ?? tailscale.ip4();
@@ -801,17 +985,10 @@ export function startOwnerUi(opts: OwnerUiOptions): OwnerUiServer {
801
985
  res = textRes("forbidden: origin is not this page", 403);
802
986
  code = 403;
803
987
  } else if (req.method === "GET" && url.pathname === "/") {
804
- const nonce = randomUUID().replaceAll("-", "");
805
- res = new Response(renderPage(cfg, buildPageData(cfg, source), url.searchParams, nonce), {
806
- status: 200,
807
- headers: {
808
- "content-type": "text/html; charset=utf-8",
809
- "content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${nonce}'; img-src data:; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`,
810
- },
811
- });
988
+ res = pageRes(cfg, source, url.searchParams);
812
989
  code = 200;
813
990
  } else if (req.method === "POST" && url.pathname === "/answer") {
814
- res = handleAnswer(cfg, await fieldsOf(req), login);
991
+ res = handleAnswer(cfg, source, await fieldsOf(req), login);
815
992
  code = res.status;
816
993
  } else if (req.method === "POST" && url.pathname === "/unlock") {
817
994
  res = handleUnlock(cfg, await fieldsOf(req), login);