neurastream 0.2.86 → 0.3.1

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.
@@ -13,7 +13,8 @@ import os from "node:os";
13
13
  import { basename, resolve } from "node:path";
14
14
  import type { RunSource } from "./adapter.ts";
15
15
  import { chatTier, currentTier, type Tier } from "./autonomy.ts";
16
- import { fileClaimStore } from "./claims.ts";
16
+ import { summaryHolder, postTeamAnswer, teamPlans, teamViews, type TeamEarlier, type TeamPlanRow, type TeamView } from "./team-client.ts";
17
+ import type { Unreachable } from "./claims.ts";
17
18
  import type { Config } from "./config.ts";
18
19
  import { nowSec, strftime } from "./clock.ts";
19
20
  import { cpuCount } from "./host.ts";
@@ -28,7 +29,7 @@ import { featuresReport, gatherTags, loadPlans, releasesReport, type FeaturesRep
28
29
  import type { Tailscale } from "./tailscale.ts";
29
30
  import { recheckHolds, staleFiles, type HoldRunner } from "./waiting-check.ts";
30
31
 
31
- const ANSWER_MAX = 2000;
32
+ export const ANSWER_MAX = 2000;
32
33
  const MESSAGE_MAX = 4000;
33
34
  const MESSAGE_IMAGES_MAX = 4;
34
35
  const MESSAGE_IMAGE_MAX_BYTES = 10 * 1024 * 1024;
@@ -58,7 +59,7 @@ export interface OwnerUiOptions {
58
59
  source: RunSource;
59
60
  /** Bind address. Default: the tailnet address from `tailscale ip -4`. Tests bind 127.0.0.1. */
60
61
  hostname?: string;
61
- /** Bind port. Default: ui.port; 0 picks a free port (tests). */
62
+ /** Bind port. Default: workspace.port; 0 picks a free port (tests). */
62
63
  port?: number;
63
64
  /** The peer address of a request. Default: the socket address. Tests inject fixture peers. */
64
65
  peerOf?: (req: Request, server: UiHttpServer) => string;
@@ -83,16 +84,16 @@ export function isTailnet(peer: string): boolean {
83
84
  return TAILNET6.test(peer);
84
85
  }
85
86
 
86
- /** Serve only the owner's phone: a tailnet peer that is not this machine and not loopback, whose tailscale whois login equals ui.owner_login. Everything else is a 403. With `ui.allow_this_machine`, this machine itself (loopback and its own tailnet IP) is served as the owner too — any local process can then press the buttons. */
87
+ /** Serve only the owner's phone: a tailnet peer that is not this machine and not loopback, whose tailscale whois login equals workspace.owner_login. Everything else is a 403. With `workspace.allow_this_machine`, this machine itself (loopback and its own tailnet IP) is served as the owner too — any local process can then press the buttons. */
87
88
  export function authenticate(cfg: Config, tailscale: Tailscale, peer: string): Auth {
88
- if (!cfg.ui.owner_login) return { ok: false, why: "ui.owner_login is empty" };
89
- if (cfg.ui.allow_this_machine && (isLoopback(peer) || peer === tailscale.ip4())) return { ok: true, login: cfg.ui.owner_login };
89
+ if (!cfg.workspace.owner_login) return { ok: false, why: "workspace.owner_login is empty" };
90
+ if (cfg.workspace.allow_this_machine && (isLoopback(peer) || peer === tailscale.ip4())) return { ok: true, login: cfg.workspace.owner_login };
90
91
  if (isLoopback(peer)) return { ok: false, why: "loopback peer" };
91
92
  if (!isTailnet(peer)) return { ok: false, why: "peer is not a tailnet address" };
92
93
  if (peer === tailscale.ip4()) return { ok: false, why: "this machine's own tailnet address" };
93
94
  const login = tailscale.whois(peer);
94
95
  if (!login) return { ok: false, why: "tailscale whois failed" };
95
- if (login !== cfg.ui.owner_login) return { ok: false, why: "not the owner's login" };
96
+ if (login !== cfg.workspace.owner_login) return { ok: false, why: "not the owner's login" };
96
97
  return { ok: true, login };
97
98
  }
98
99
 
@@ -119,8 +120,10 @@ export interface QuestionRow {
119
120
  unblocks: string[];
120
121
  goal: string[];
121
122
  waitingMin: number;
122
- /** The last answer this plan already got (from the owner inbox), so the card can say so. */
123
- answered: { answer: string; at: number } | null;
123
+ /** The last answer this plan already got (from the owner inbox, so the card can say so; for a team plan, the newest server answer). */
124
+ answered: { answer: string; at: number; login?: string } | null;
125
+ /** The team this card belongs to; `plan` is then the server plan id, not a local path (P4). */
126
+ team?: string;
124
127
  }
125
128
 
126
129
  /** The newest inbox record that carries an answer for this plan, if any. A missing or torn inbox is simply "no answer". */
@@ -258,11 +261,11 @@ function queueState(p: Plan, plans: Plan[]): string {
258
261
  return `phase ${Math.min(done + 1, total)} of ${total}`;
259
262
  }
260
263
 
261
- export function queueRows(cfg: Config): QueueRow[] {
264
+ export function queueRows(cfg: Config, views?: Map<string, TeamView | Unreachable>): QueueRow[] {
262
265
  const plans = activePlans(cfg.paths.queue_index).filter(p => p.status === "open");
263
- const claims = fileClaimStore(cfg.paths.queue_state, nowSec, cfg.queue.claim_ttl_min);
266
+ const claims = summaryHolder(cfg, {}, views);
264
267
  return plans.map(p => {
265
- const holder = claims.holder(p.file)?.main ?? null;
268
+ const holder = claims.holder(p.file);
266
269
  return {
267
270
  repo: basename(p.repo),
268
271
  file: p.file,
@@ -271,11 +274,71 @@ export function queueRows(cfg: Config): QueueRow[] {
271
274
  waiting: p.waiting,
272
275
  summary: p.summary ?? (goalSummary(p.goal[0] ?? "") || null),
273
276
  state: queueState(p, plans),
274
- holder,
277
+ holder: holder === null ? null : "unreachable" in holder ? "team server unreachable" : holder.main,
275
278
  };
276
279
  });
277
280
  }
278
281
 
282
+ /** One team's card on the phone page: its plans as queue rows and its open WAITING lines. */
283
+ export interface TeamSection {
284
+ name: string;
285
+ server: string;
286
+ /** False when the team server did not answer: the card says so instead of listing plans. */
287
+ reachable: boolean;
288
+ rows: QueueRow[];
289
+ questions: QuestionRow[];
290
+ }
291
+
292
+ /**
293
+ * The team half of the phone page (P4): each team's already-read view mapped to the page's own
294
+ * row types, so the render stays one shape. A plan is a QueueRow whose `file` is the server id
295
+ * (team order is not INDEX order, so no drag and no /reorder) and whose state is queueState over
296
+ * the team's own parsed plans; each open plan with a WAITING line is a QuestionRow whose newest
297
+ * server answer fills `answered`. Sends nothing.
298
+ */
299
+ export function teamSections(cfg: Config, views: Map<string, TeamView | Unreachable>): TeamSection[] {
300
+ return cfg.teams.map(team => {
301
+ const view = views.get(team.name);
302
+ if (view === undefined || "unreachable" in view) return { name: team.name, server: team.server, reachable: false, rows: [], questions: [] };
303
+ return teamSection(team.name, team.server, teamPlans(cfg, team, view));
304
+ });
305
+ }
306
+
307
+ /** One reachable team's card from its parsed plans: the phone page and the team page both build it here. */
308
+ export function teamSection(name: string, server: string, plans: TeamPlanRow[]): TeamSection {
309
+ const parsed = plans.map(p => p.plan);
310
+ const rows: QueueRow[] = plans.map(p => ({
311
+ repo: p.relPath,
312
+ file: p.id,
313
+ title: p.plan.title,
314
+ status: p.plan.status ?? "?",
315
+ waiting: p.plan.waiting,
316
+ summary: p.plan.summary ?? (goalSummary(p.plan.goal[0] ?? "") || null),
317
+ holder: p.holder ? `${p.holder.main} (${p.holder.login})` : null,
318
+ state: queueState(p.plan, parsed),
319
+ }));
320
+ const questions: QuestionRow[] = plans
321
+ .filter(p => p.plan.status === "open" && p.plan.waiting && p.plan.waitingLine)
322
+ .map(p => {
323
+ const first = p.answered;
324
+ return {
325
+ plan: p.id,
326
+ team: name,
327
+ title: p.plan.title,
328
+ repo: p.relPath,
329
+ waitingLine: p.plan.waitingLine ?? "",
330
+ waitingAsk: p.plan.waitingAsk ?? p.plan.waitingLine ?? "",
331
+ waitingBlocked: p.plan.waitingBlocked,
332
+ waitingWhy: p.plan.waitingWhy,
333
+ unblocks: [],
334
+ goal: p.plan.goal,
335
+ waitingMin: 0,
336
+ answered: first ? { answer: first.answer, at: first.time, login: first.login } : null,
337
+ };
338
+ });
339
+ return { name, server, reachable: true, rows, questions };
340
+ }
341
+
279
342
  export function ciRows(cfg: Config): CiRow[] {
280
343
  return readMetricEvents(cfg)
281
344
  .filter(e => e.type === "ci")
@@ -381,7 +444,9 @@ export function nowStats(cfg: Config, source: RunSource, now: number): NowStats
381
444
  models.set(short, m);
382
445
  }
383
446
  const byModel = [...models.entries()].map(([model, v]) => ({ model, spend: v.spend, runs: v.runs })).sort((a, b) => b.spend - a.spend);
384
- return { spend24, mainSpend, agentSpend, runs24, running, died, spendByHour, runsByHour, byModel, openPlans: queueRows(cfg).length };
447
+ // The tile counts the open plans the queue card renders; a holder read here would ask every
448
+ // team server a second time on a page that already read one view per team (P4).
449
+ return { spend24, mainSpend, agentSpend, runs24, running, died, spendByHour, runsByHour, byModel, openPlans: activePlans(cfg.paths.queue_index).filter(p => p.status === "open").length };
385
450
  }
386
451
 
387
452
  // ---- owner messages (plan P13): a one-way note plus images, kept for 12 h ----
@@ -540,7 +605,7 @@ function needCard(row: QuestionRow, i: number, tab: string): string {
540
605
  const text = row.answered.answer;
541
606
  const quote = text.length > 80 ? `${text.slice(0, 80)}…` : text;
542
607
  const verb = text.toLowerCase() === "yes" || text.toLowerCase() === "no" ? "answered" : "replied";
543
- said = `<p class="answered">You ${verb} "${esc(quote)}" · ${esc(strftime(row.answered.at, "%H:%M"))} — Main is on it</p>
608
+ said = `<p class="answered">${row.answered.login ? esc(row.answered.login) : "You"} ${verb} "${esc(quote)}" · ${esc(strftime(row.answered.at, "%H:%M"))} — Main is on it</p>
544
609
  <button type="button" class="replybtn link">change answer</button>`;
545
610
  }
546
611
  const question = ask.endsWith("?");
@@ -563,7 +628,7 @@ ${parts.join("\n")}
563
628
  ${bg}
564
629
  <form method="post" action="/answer">
565
630
  <input type="hidden" name="plan" value="${esc(row.plan)}">
566
- <input type="hidden" name="tab" value="${esc(tab)}">
631
+ ${row.team ? `<input type="hidden" name="team" value="${esc(row.team)}">\n` : ""}<input type="hidden" name="tab" value="${esc(tab)}">
567
632
  ${acts}
568
633
  <div class="reply" hidden>
569
634
  <textarea name="answer_text" maxlength="${ANSWER_MAX}" rows="3" placeholder="Type your reply"></textarea>
@@ -579,30 +644,34 @@ function agentRowHtml(r: AgentRow): string {
579
644
  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>`;
580
645
  }
581
646
 
582
- function queueHtml(rows: QueueRow[], tab: string): string {
647
+ /** The queue list. `reorder` false is a team card (P4): no drag handle, no ↑/↓ buttons and no /reorder form — team order is the server's, not INDEX order. */
648
+ function queueHtml(rows: QueueRow[], tab: string, reorder = true): string {
649
+ const handle = (r: QueueRow): string => `<span class="qhandle" title="Drag to reorder" aria-label="Drag ${esc(r.title)}">≡</span>
650
+ `;
651
+ const btns = `<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>`;
583
652
  const cards = rows
584
653
  .map(
585
654
  (r, i) => `<li class="qcard" data-plan="${esc(r.file)}">
586
- <span class="qhandle" title="Drag to reorder" aria-label="Drag ${esc(r.title)}">≡</span>
587
- <span class="qrank">${i + 1}</span>
655
+ ${reorder ? handle(r) : ""}<span class="qrank">${i + 1}</span>
588
656
  <span class="qtitle">${esc(r.title)}${r.summary ? `<span class="qsum">${esc(r.summary)}</span>` : ""}</span>
589
- ${r.holder ? `<span class="chip c-held">Main ${esc(r.holder)}</span>` : ""}<span class="chip ${r.state.startsWith("waits") ? "c-wait" : "c-ready"}">${esc(r.state)}</span>
590
- <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>
657
+ ${r.holder ? `<span class="chip c-held">${r.holder === "team server unreachable" ? esc(r.holder) : `Main ${esc(r.holder)}`}</span>` : ""}<span class="chip ${r.state.startsWith("waits") ? "c-wait" : "c-ready"}">${esc(r.state)}</span>
658
+ ${reorder ? btns : ""}
591
659
  </li>`,
592
660
  )
593
661
  .join("\n");
594
662
  // before = the order this page was rendered with; the server refuses the move when the real
595
663
  // order has drifted (409), so a stale page can never reorder on a guess.
596
664
  const before = rows.map(r => r.file).join("\n");
597
- return `<ul class="qlist" id="qlist">
598
- ${cards}
599
- </ul>
600
- <form id="reorder-form" method="post" action="/reorder" hidden>
665
+ const form = `<form id="reorder-form" method="post" action="/reorder" hidden>
601
666
  <input type="hidden" name="before" value="${esc(before)}">
602
667
  <input type="hidden" name="order" value="">
603
668
  <input type="hidden" name="moved" value="">
604
669
  <input type="hidden" name="tab" value="${esc(tab)}">
605
670
  </form>`;
671
+ return `<ul class="qlist"${reorder ? ` id="qlist"` : ""}>
672
+ ${cards}
673
+ </ul>
674
+ ${reorder ? form : ""}`;
606
675
  }
607
676
 
608
677
  function ciHtml(rows: CiRow[]): string {
@@ -708,6 +777,25 @@ function queueCard(rows: QueueRow[] | null, full: boolean, tab: string): string
708
777
  return `${head}<div class="card">${body}${more}</div>`;
709
778
  }
710
779
 
780
+ /**
781
+ * Each team as its own card under the queue card (P4): its plans through queueHtml with
782
+ * `reorder` off, then one question card per open WAITING line. A team the server did not answer
783
+ * says so instead of showing a stale list. Nothing here counts in the "Needs you" tile.
784
+ */
785
+ function teamCardsHtml(sections: TeamSection[] | null, tab: string): string {
786
+ if (sections === null) return `<h2>Team queue</h2><div class="card">${na("Team queue")}</div>`;
787
+ return sections
788
+ .map(s => {
789
+ const body = s.reachable ? (s.rows.length ? queueHtml(s.rows, tab, false) : `<p class="empty">No team plans</p>`) : `<p class="empty">team server ${esc(s.server)} unreachable</p>`;
790
+ const asks = s.questions.map((row, i) => needCard(row, i, tab)).join("\n");
791
+ return `<h2>Team ${esc(s.name)}</h2>
792
+ <div class="card">
793
+ ${body}${asks ? `\n${asks}` : ""}
794
+ </div>`;
795
+ })
796
+ .join("\n");
797
+ }
798
+
711
799
  function modelSpendTable(stats: NowStats | null): string {
712
800
  if (stats === null) return na("Spend");
713
801
  if (!stats.byModel.length) return `<p class="empty">No spend recorded in the last 24 hours</p>`;
@@ -726,6 +814,11 @@ function receiptText(sent: string, params: URLSearchParams): string | null {
726
814
  case "message":
727
815
  text = `Sent to Main · ${strftime(nowSec(), "%H:%M")}`;
728
816
  break;
817
+ case "team-answer": {
818
+ const team = params.get("team") ?? "";
819
+ text = `Sent to team ${team} · ${strftime(nowSec(), "%H:%M")}`;
820
+ break;
821
+ }
729
822
  case "incident-closed":
730
823
  text = `Marked as a false alarm · ${strftime(nowSec(), "%H:%M")}`;
731
824
  break;
@@ -765,11 +858,11 @@ function receiptHtml(sent: string | null, params: URLSearchParams): string {
765
858
  }
766
859
 
767
860
  /** The JSON POST replies (P11b): the receipt text rides along so the page script never re-derives it. */
768
- function jsonSent(sent: string, receipt?: string | null): Response {
861
+ export function jsonSent(sent: string, receipt?: string | null): Response {
769
862
  return Response.json(receipt ? { ok: true, sent, receipt } : { ok: true, sent });
770
863
  }
771
864
 
772
- function jsonFail(error: string, status: number): Response {
865
+ export function jsonFail(error: string, status: number): Response {
773
866
  return Response.json({ ok: false, error }, { status });
774
867
  }
775
868
 
@@ -792,6 +885,8 @@ export interface PageData {
792
885
  pages: PublishedPageRow[] | null;
793
886
  /** The 24 h tile numbers; null when the run source is unreadable. */
794
887
  stats: NowStats | null;
888
+ /** Each team's card, built from one already-read view per team (P4); absent or null when the views could not be read. */
889
+ teams?: TeamSection[] | null;
795
890
  /** The Results tab's saved numbers and build state; absent on every other tab. The numbers come from a background process (computeResults), never from the request. */
796
891
  results?: ResultsView | null;
797
892
  /** The owner's messages newer than the keep window, newest first; null when unreadable. */
@@ -824,10 +919,13 @@ function lockMinutesLeft(cfg: Config): number | null {
824
919
  }
825
920
 
826
921
  export function buildPageData(cfg: Config, source: RunSource, tab: string, build: ResultsBuild = spawnResultsBuild, pagesHost = "tailnet"): PageData {
922
+ // P4: one GET /view per team, read once and handed to the queue rows' holder and the team
923
+ // cards, so a render makes no second request per team.
924
+ const views = safe(() => teamViews(cfg));
827
925
  return {
828
926
  questions: safe(() => questionRows(cfg)),
829
927
  agents: safe(() => agentRows(cfg, source)),
830
- queue: safe(() => queueRows(cfg)),
928
+ queue: safe(() => queueRows(cfg, views ?? undefined)),
831
929
  ci: safe(() => ciRows(cfg)),
832
930
  incidents: safe(() => incidentRows(cfg)),
833
931
  scores: safe(() => scoresData(cfg)),
@@ -835,6 +933,7 @@ export function buildPageData(cfg: Config, source: RunSource, tab: string, build
835
933
  knowledge: safe(() => knowledgeManifest(cfg)),
836
934
  pages: safe(() => publishedRows(cfg, pagesHost)),
837
935
  stats: safe(() => nowStats(cfg, source, nowSec())),
936
+ teams: views === null ? null : safe(() => teamSections(cfg, views)),
838
937
  results: tab === "results" ? safe(() => resultsView(nowSec(), build)) : undefined,
839
938
  messages: safe(() => recentOwnerMessages(nowSec())),
840
939
  lockMinutesLeft: lockMinutesLeft(cfg),
@@ -1269,85 +1368,8 @@ ${resultsTable(d.releases, all)}
1269
1368
  <p class="sub">${RESULTS_CAVEAT}</p>`;
1270
1369
  }
1271
1370
 
1272
- /** The whole page as one HTML string. Exported for scripts/ui-preview.ts (no server). */
1273
- export function renderPage(cfg: Config, data: PageData, params: URLSearchParams, nonce: string): string {
1274
- const req = params.get("tab") ?? "";
1275
- // Server-rendered tabs: the pill links carry ?tab=; anything unknown renders Now.
1276
- const tab = TAB_IDS.includes(req) ? req : "now";
1277
- const needsBody =
1278
- data.questions === null
1279
- ? na("Waiting on you")
1280
- : data.questions.length
1281
- ? data.questions.map((row, i) => needCard(row, i, tab)).join("\n")
1282
- : `<p class="empty">Nothing needs you right now</p>`;
1283
- const working =
1284
- 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>`;
1285
- const scores = data.scores === null ? na("Agent scores") : scoresHtml(data.scores);
1286
- const incidents = data.incidents === null ? na("Incidents") : data.incidents.length ? incidentsHtml(data.incidents, tab) : `<p class="empty">No open incidents</p>`;
1287
- const merges = data.ci === null ? na("Merges") : data.ci.length ? ciHtml(data.ci) : `<p class="empty">No CI runs recorded</p>`;
1288
- const machine = data.machine === null ? na("Machine") : machineHtml(cfg, data.machine);
1289
- const body =
1290
- tab === "now"
1291
- ? `${messageCard(data.messages, runningMains(cfg))}
1292
- <h1>Today</h1>
1293
- <p class="sub">What your agents did in the last 24 hours.</p>
1294
- <div class="card">
1295
- ${tilesHtml(data)}
1296
- </div>
1297
- <h2>Needs you</h2>
1298
- <div class="card">
1299
- ${needsBody}
1300
- </div>
1301
- ${queueCard(data.queue, false, tab)}`
1302
- : tab === "queue"
1303
- ? `<h1>Queue</h1>
1304
- <p class="sub">Drag ≡ to sort — Main works by the new order on its next turn.</p>
1305
- ${queueCard(data.queue, true, tab)}`
1306
- : tab === "agents"
1307
- ? `<h1>Agents</h1>
1308
- <p class="sub">Who is working right now, how they score, and what went wrong.</p>
1309
- <h2>Working now</h2>
1310
- <div class="card">
1311
- ${working}
1312
- </div>
1313
- <h2>Agent scores</h2>
1314
- <div class="card">
1315
- ${scores}
1316
- </div>
1317
- <h2>Incidents</h2>
1318
- <div class="card">
1319
- ${incidents}
1320
- </div>
1321
- <h2>Merges</h2>
1322
- <div class="card">
1323
- ${merges}
1324
- </div>
1325
- <h2>Machine</h2>
1326
- <div class="card">
1327
- ${machine}
1328
- </div>`
1329
- : tab === "knowledge"
1330
- ? `${data.knowledge === null ? na("Base") : knowledgeHtml(data.knowledge, params.get("repo") ?? "", params.get("topic") ?? "", data.pages ?? [])}`
1331
- : tab === "spend"
1332
- ? `<h1>Spend</h1
1333
- <p class="sub">List price over the last 24 hours.</p>
1334
- <div class="card">
1335
- ${spendTileHtml(data)}
1336
- </div>
1337
- <h2>By model</h2>
1338
- <div class="card">
1339
- ${modelSpendTable(data.stats)}
1340
- </div>`
1341
- : resultsTabHtml(data.results, params);
1342
- return `<!doctype html>
1343
- <html lang="en">
1344
- <head>
1345
- <meta charset="utf-8">
1346
- <meta name="viewport" content="width=device-width, initial-scale=1">
1347
- <meta name="color-scheme" content="light dark">
1348
- <title>neurastream</title>
1349
- <link rel="icon" href="${FAVICON}">
1350
- <style>
1371
+ /** The owner page's stylesheet (P5 lift): one string shared by the phone page (renderPage) and the team page (renderTeamPage). */
1372
+ const PAGE_CSS = `
1351
1373
  :root{--bg:#f4f4f6;--card:#fff;--fg:#111;--mut:#6b6b76;--bd:#e4e4ea;--acc:#c026d3;--teal:#0d9488;--warn:#d97706;--ok:#16a34a;--red:#dc2626}
1352
1374
  @media(prefers-color-scheme:dark){:root{--bg:#0e0e11;--card:#18181c;--fg:#f2f2f4;--mut:#9a9aa6;--bd:#2a2a31}}
1353
1375
  *{box-sizing:border-box}
@@ -1453,7 +1475,89 @@ span.badv{color:var(--red);font-weight:600}
1453
1475
  .empty{color:var(--mut);padding:14px 16px;margin:0}
1454
1476
  .knowframe{display:block;width:100%;height:calc(100vh - 220px);min-height:360px;border:0;background:#fff}
1455
1477
  .na{color:var(--mut);font-style:italic;padding:14px 16px;margin:0}
1456
- </style>
1478
+ `;
1479
+
1480
+ /** The whole page as one HTML string. Exported for scripts/ui-preview.ts (no server). */
1481
+ export function renderPage(cfg: Config, data: PageData, params: URLSearchParams, nonce: string): string {
1482
+ const req = params.get("tab") ?? "";
1483
+ // Server-rendered tabs: the pill links carry ?tab=; anything unknown renders Now.
1484
+ const tab = TAB_IDS.includes(req) ? req : "now";
1485
+ const needsBody =
1486
+ data.questions === null
1487
+ ? na("Waiting on you")
1488
+ : data.questions.length
1489
+ ? data.questions.map((row, i) => needCard(row, i, tab)).join("\n")
1490
+ : `<p class="empty">Nothing needs you right now</p>`;
1491
+ const working =
1492
+ 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>`;
1493
+ const scores = data.scores === null ? na("Agent scores") : scoresHtml(data.scores);
1494
+ const incidents = data.incidents === null ? na("Incidents") : data.incidents.length ? incidentsHtml(data.incidents, tab) : `<p class="empty">No open incidents</p>`;
1495
+ const merges = data.ci === null ? na("Merges") : data.ci.length ? ciHtml(data.ci) : `<p class="empty">No CI runs recorded</p>`;
1496
+ const machine = data.machine === null ? na("Machine") : machineHtml(cfg, data.machine);
1497
+ // P4: one card per team, under the queue card on the two tabs that show the queue.
1498
+ const teams = tab === "now" || tab === "queue" ? teamCardsHtml(data.teams ?? null, tab) : "";
1499
+ const body =
1500
+ tab === "now"
1501
+ ? `${messageCard(data.messages, runningMains(cfg))}
1502
+ <h1>Today</h1>
1503
+ <p class="sub">What your agents did in the last 24 hours.</p>
1504
+ <div class="card">
1505
+ ${tilesHtml(data)}
1506
+ </div>
1507
+ <h2>Needs you</h2>
1508
+ <div class="card">
1509
+ ${needsBody}
1510
+ </div>
1511
+ ${queueCard(data.queue, false, tab)}${teams ? `\n${teams}` : ""}`
1512
+ : tab === "queue"
1513
+ ? `<h1>Queue</h1>
1514
+ <p class="sub">Drag ≡ to sort — Main works by the new order on its next turn.</p>
1515
+ ${queueCard(data.queue, true, tab)}${teams ? `\n${teams}` : ""}`
1516
+ : tab === "agents"
1517
+ ? `<h1>Agents</h1>
1518
+ <p class="sub">Who is working right now, how they score, and what went wrong.</p>
1519
+ <h2>Working now</h2>
1520
+ <div class="card">
1521
+ ${working}
1522
+ </div>
1523
+ <h2>Agent scores</h2>
1524
+ <div class="card">
1525
+ ${scores}
1526
+ </div>
1527
+ <h2>Incidents</h2>
1528
+ <div class="card">
1529
+ ${incidents}
1530
+ </div>
1531
+ <h2>Merges</h2>
1532
+ <div class="card">
1533
+ ${merges}
1534
+ </div>
1535
+ <h2>Machine</h2>
1536
+ <div class="card">
1537
+ ${machine}
1538
+ </div>`
1539
+ : tab === "knowledge"
1540
+ ? `${data.knowledge === null ? na("Base") : knowledgeHtml(data.knowledge, params.get("repo") ?? "", params.get("topic") ?? "", data.pages ?? [])}`
1541
+ : tab === "spend"
1542
+ ? `<h1>Spend</h1
1543
+ <p class="sub">List price over the last 24 hours.</p>
1544
+ <div class="card">
1545
+ ${spendTileHtml(data)}
1546
+ </div>
1547
+ <h2>By model</h2>
1548
+ <div class="card">
1549
+ ${modelSpendTable(data.stats)}
1550
+ </div>`
1551
+ : resultsTabHtml(data.results, params);
1552
+ return `<!doctype html>
1553
+ <html lang="en">
1554
+ <head>
1555
+ <meta charset="utf-8">
1556
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1557
+ <meta name="color-scheme" content="light dark">
1558
+ <title>neurastream</title>
1559
+ <link rel="icon" href="${FAVICON}">
1560
+ <style>${PAGE_CSS}</style>
1457
1561
  </head>
1458
1562
  <body>
1459
1563
  ${topBarHtml(tab, data.lockMinutesLeft, cfg)}
@@ -1468,7 +1572,7 @@ ${body}
1468
1572
 
1469
1573
  // ---- request plumbing ----
1470
1574
 
1471
- async function fieldsOf(req: Request): Promise<Record<string, string>> {
1575
+ export async function fieldsOf(req: Request): Promise<Record<string, string>> {
1472
1576
  const ct = req.headers.get("content-type") ?? "";
1473
1577
  if (ct.includes("application/json")) {
1474
1578
  const raw: unknown = await req.json();
@@ -1479,7 +1583,7 @@ async function fieldsOf(req: Request): Promise<Record<string, string>> {
1479
1583
  return Object.fromEntries([...form.entries()].map(([k, v]) => [k, typeof v === "string" ? v : ""]));
1480
1584
  }
1481
1585
 
1482
- function textRes(body: string, status: number): Response {
1586
+ export function textRes(body: string, status: number): Response {
1483
1587
  return new Response(`${body}\n`, { status, headers: { "content-type": "text/plain; charset=utf-8" } });
1484
1588
  }
1485
1589
 
@@ -1493,6 +1597,11 @@ function sentTo(tab: string, sent: string): string {
1493
1597
  return t === "now" ? `/?${sent}` : `/?tab=${t}&${sent}`;
1494
1598
  }
1495
1599
 
1600
+ /** The owner pages' CSP: the one inline script takes this response's nonce; the team page shares it. */
1601
+ export function pageCsp(nonce: string): string {
1602
+ return `default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${nonce}'; img-src 'self' data:; connect-src 'self'; frame-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`;
1603
+ }
1604
+
1496
1605
  /** The normal page (the GET layout) as a POST reply; the stale-answer reply is this with sent=stale. */
1497
1606
  function pageRes(cfg: Config, source: RunSource, params: URLSearchParams, build: ResultsBuild = spawnResultsBuild, pagesHost = "tailnet"): Response {
1498
1607
  const nonce = randomUUID().replaceAll("-", "");
@@ -1500,11 +1609,79 @@ function pageRes(cfg: Config, source: RunSource, params: URLSearchParams, build:
1500
1609
  status: 200,
1501
1610
  headers: {
1502
1611
  "content-type": "text/html; charset=utf-8",
1503
- "content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${nonce}'; img-src 'self' data:; connect-src 'self'; frame-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`,
1612
+ "content-security-policy": pageCsp(nonce),
1504
1613
  },
1505
1614
  });
1506
1615
  }
1507
1616
 
1617
+ /** What the team page shows: one team's section (shared with the phone page), its plans' approvals, members, and audit. */
1618
+ export interface TeamPageData {
1619
+ team: string;
1620
+ login: string;
1621
+ admin: boolean;
1622
+ leader: boolean;
1623
+ adminLogin: string;
1624
+ section: TeamSection;
1625
+ plans: { id: string; relPath: string; title: string; approvals: string[] }[];
1626
+ members: string[];
1627
+ /** Newest first, already formatted; null for a viewer who may not read the audit. */
1628
+ audit: { at: string; login: string; route: string }[] | null;
1629
+ }
1630
+
1631
+ /** The team page (P5): plain forms that POST to the team server's routes; no script, so no nonce. */
1632
+ export function renderTeamPage(data: TeamPageData): string {
1633
+ const waiting = data.section.questions.length
1634
+ ? data.section.questions.map(row => `<div class="ask"><b>${esc(row.title)}</b><p class="q">${esc(row.waitingAsk || row.waitingLine || "")}</p>${row.answered ? `<p class="answered">${row.answered.login ? esc(row.answered.login) : "You"} answered "${esc(row.answered.answer)}"</p>` : ""}<form method="post" action="/answer"><input type="hidden" name="plan" value="${esc(row.plan)}"><textarea name="answer_text" rows="2" required maxlength="2000"></textarea><div class="acts"><button class="btn pri" type="submit">Send</button></div></form></div>`).join("")
1635
+ : `<p class="empty">Nothing waiting</p>`;
1636
+ const approve = data.plans.length
1637
+ ? data.plans.map(p => {
1638
+ const chip = p.approvals.length ? ` <span class="chip c-ready">approved by ${p.approvals.map(a => esc(a)).join(", ")}</span>` : "";
1639
+ const form = p.approvals.includes(data.login) ? "" : `<form method="post" action="/approve"><input type="hidden" name="plan" value="${esc(p.id)}"><button class="btn pri" type="submit">Approve</button></form>`;
1640
+ return `<div class="ask"><b>${esc(p.title)}</b><p>${esc(p.relPath)}${chip}</p>${form}</div>`;
1641
+ }).join("")
1642
+ : `<p class="empty">No team plans to approve</p>`;
1643
+ const ranking = data.plans.length
1644
+ ? `<form method="post" action="/vote">${data.plans.map(p => `<div class="mrow"><span>${esc(p.title)}</span><input name="rank:${esc(p.id)}" inputmode="numeric" size="4" placeholder="rank"></div>`).join("")}<div class="acts"><button class="btn pri" type="submit">Save ranks</button></div></form>`
1645
+ : `<p class="empty">No team plans to rank</p>`;
1646
+ const override = data.leader && data.plans.length
1647
+ ? `<h2>Override<small>leader: this order wins over the ranks</small></h2><div class="card"><form method="post" action="/override">${data.plans.map((p, i) => `<div class="mrow"><span>${esc(p.title)}</span><input name="pos:${esc(p.id)}" inputmode="numeric" size="4" value="${i + 1}"></div>`).join("")}<div class="acts"><button class="btn pri" type="submit">Save override</button></div></form></div>`
1648
+ : "";
1649
+ const members = data.members.map(m => {
1650
+ const remove = data.admin && m !== data.adminLogin ? `<form method="post" action="/member"><input type="hidden" name="op" value="remove"><input type="hidden" name="login" value="${esc(m)}"><button class="btn" type="submit">Remove</button></form>` : "";
1651
+ return `<div class="tile"><span>${esc(m)}</span>${remove}</div>`;
1652
+ }).join("");
1653
+ const addMember = data.admin ? `<form class="msgform" method="post" action="/member"><input type="hidden" name="op" value="add"><input name="login" required placeholder="login"><div class="acts"><button class="btn pri" type="submit">Add member</button></div></form>` : "";
1654
+ const audit = data.audit === null ? "" : `<h2>Audit<small>newest 20</small></h2><div class="card">${data.audit.slice(0, 20).map(a => `<div class="mrow"><span>${esc(a.at)} ${esc(a.login)}</span><span class="mono">${esc(a.route)}</span></div>`).join("") || `<p class="empty">No audit rows</p>`}</div>`;
1655
+ return `<!doctype html>
1656
+ <html lang="en">
1657
+ <head>
1658
+ <meta charset="utf-8">
1659
+ <meta name="viewport" content="width=device-width,initial-scale=1">
1660
+ <title>neurastream · team ${esc(data.team)}</title>
1661
+ <link rel="icon" href="${FAVICON}">
1662
+ <style>${PAGE_CSS}</style>
1663
+ </head>
1664
+ <body>
1665
+ <div class="top"><span class="logo">ns</span><span class="sub">Team ${esc(data.team)} · ${esc(data.login)}</span></div>
1666
+ <main>
1667
+ <h2>Queue<small>team order</small></h2>
1668
+ <div class="card">${data.section.rows.length ? queueHtml(data.section.rows, "now", false) : `<p class="empty">No team plans</p>`}</div>
1669
+ <h2>Rank<small>your order for the team</small></h2>
1670
+ <div class="card">${ranking}</div>
1671
+ ${override}
1672
+ <h2>Waiting</h2>
1673
+ <div class="card">${waiting}</div>
1674
+ <h2>Approve</h2>
1675
+ <div class="card">${approve}</div>
1676
+ <h2>Members</h2>
1677
+ <div class="card">${members}${addMember}</div>
1678
+ ${audit}
1679
+ </main>
1680
+ </body>
1681
+ </html>
1682
+ `;
1683
+ }
1684
+
1508
1685
  /** The last answer appended per plan, for the double-press guard (P8c): memory only, no file. */
1509
1686
  const lastAnswerByPlan = new Map<string, { answer: string; ts: number }>();
1510
1687
  const DOUBLE_PRESS_SEC = 10;
@@ -1524,6 +1701,9 @@ function handleAnswer(cfg: Config, source: RunSource, fields: Record<string, str
1524
1701
  const answer = (fields.answer_text ?? "").trim() || (fields.answer ?? "").trim();
1525
1702
  if (!planFile || !answer) return wantsJson ? jsonFail("plan and answer are required", 400) : textRes("plan and answer are required", 400);
1526
1703
  if (answer.length > ANSWER_MAX) return wantsJson ? jsonFail(`answer is longer than ${ANSWER_MAX} chars`, 400) : textRes(`answer is longer than ${ANSWER_MAX} chars`, 400);
1704
+ // P4: a team plan is answered on its server, never in this machine's inbox; the branch sits
1705
+ // before the INDEX lookup, which knows only this machine's own plans.
1706
+ if ((fields.team ?? "").trim()) return handleTeamAnswer(cfg, fields, planFile, answer, wantsJson);
1527
1707
  const plan = activePlans(cfg.paths.queue_index).find(p => p.file === planFile);
1528
1708
  if (!plan) return wantsJson ? jsonFail("plan is not open and waiting", 409) : textRes("plan is not open and waiting", 409);
1529
1709
  if (plan.status !== "open" || !plan.waiting || !plan.waitingLine) {
@@ -1537,8 +1717,38 @@ function handleAnswer(cfg: Config, source: RunSource, fields: Record<string, str
1537
1717
  return redirect(sentTo(fields.tab ?? "", "sent=answer"));
1538
1718
  }
1539
1719
 
1540
- // ---- POST /incident (plan P3): the owner's tap on a finding: "false alarm" closes it, "bug" plans it ----
1720
+ /**
1721
+ * An answer to a team plan (P4): `POST /answer/<id>` on that team's server with the answer
1722
+ * alone — the server stores the whois login — and nothing is written to this machine's inbox,
1723
+ * which belongs to its own Main. The double-press guard is the page's own memory, keyed
1724
+ * `<team>/<id>`; a repeated press within 10 s sends nothing again.
1725
+ */
1726
+ function handleTeamAnswer(cfg: Config, fields: Record<string, string>, planId: string, answer: string, wantsJson: boolean): Response {
1727
+ const name = (fields.team ?? "").trim();
1728
+ const team = cfg.teams.find(t => t.name === name);
1729
+ if (!team) return wantsJson ? jsonFail("unknown team", 400) : textRes("unknown team", 400);
1730
+ const key = `${team.name}/${planId}`;
1731
+ const now = nowSec();
1732
+ const last = lastAnswerByPlan.get(key);
1733
+ const repeat = last !== undefined && last.answer === answer && now - last.ts < DOUBLE_PRESS_SEC;
1734
+ let earlier: TeamEarlier | null = null;
1735
+ if (!repeat) {
1736
+ const out = postTeamAnswer(team, planId, answer);
1737
+ if ("unreachable" in out) return wantsJson ? jsonFail(`team server ${out.unreachable} unreachable`, 503) : textRes(`team server ${out.unreachable} unreachable`, 503);
1738
+ if (!out.ok) {
1739
+ const error = out.status === 404 ? "plan is not on the team server" : out.error;
1740
+ return wantsJson ? jsonFail(error, out.status === 404 ? 409 : out.status) : textRes(error, out.status === 404 ? 409 : out.status);
1741
+ }
1742
+ lastAnswerByPlan.set(key, { answer, ts: now });
1743
+ earlier = out.earlier;
1744
+ }
1745
+ const note = earlier ? `answer kept; an earlier answer by ${earlier.login} at ${strftime(earlier.time, "%H:%M")} won: "${earlier.answer}"` : null;
1746
+ if (wantsJson) return jsonSent("team-answer", note ?? receiptText("team-answer", new URLSearchParams({ team: team.name })));
1747
+ if (note) return textRes(note, 200);
1748
+ return redirect(sentTo(fields.tab ?? "", `sent=team-answer&team=${encodeURIComponent(team.name)}`));
1749
+ }
1541
1750
 
1751
+ // ---- POST /incident (plan P3): the owner's tap on a finding: "false alarm" closes it, "bug" plans it ----
1542
1752
  function handleIncident(cfg: Config, fields: Record<string, string>, login: string, wantsJson: boolean): Response {
1543
1753
  const id = (fields.id ?? "").trim();
1544
1754
  const choice = (fields.choice ?? "").trim();
@@ -1782,7 +1992,32 @@ function handleReorder(cfg: Config, fields: Record<string, string>, login: strin
1782
1992
  return redirect(sentTo(fields.tab ?? "", `sent=reorder&to=${to + 1}`));
1783
1993
  }
1784
1994
 
1785
- /** 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. */
1995
+ /**
1996
+ * DNS-rebinding guard, built once per server. A page on another host sends that Host with a
1997
+ * matching Origin, so the peer and Origin checks alone would pass it. The Host header must
1998
+ * name this server — the tailnet address or the MagicDNS name (dnsName(), trailing dot already
1999
+ * stripped) — with the served port. No bound port: nothing is allowed. The phone page and the
2000
+ * team server both call this.
2001
+ */
2002
+ export function hostAllowlist(tailscale: { ip4(): string | null; dnsName(): string | null }): (hostHeader: string, port: number | undefined) => boolean {
2003
+ let allowedHosts: string[] | null = null;
2004
+ return (hostHeader, port) => {
2005
+ // No bound port (never expected): nothing is allowed — fail closed.
2006
+ if (port === undefined) return false;
2007
+ if (allowedHosts === null) {
2008
+ const dns = tailscale.dnsName();
2009
+ allowedHosts = [tailscale.ip4(), dns].filter((h): h is string => Boolean(h)).map(h => `${h}:${port}`);
2010
+ }
2011
+ return allowedHosts.includes(hostHeader);
2012
+ };
2013
+ }
2014
+
2015
+ /** True when Origin is exactly `http://` plus the Host header. Callers apply it to the methods they write. */
2016
+ export function originIsHost(origin: string | null, hostHeader: string): boolean {
2017
+ return origin === `http://${hostHeader}`;
2018
+ }
2019
+
2020
+ /** Starts the page. Refuses to start when workspace.enabled is false or workspace.owner_login is empty, and on the default hostname when tailscale does not answer. */
1786
2021
  export function startOwnerUi(opts: OwnerUiOptions): OwnerUiServer {
1787
2022
  const { cfg, tailscale, source } = opts;
1788
2023
  const resultsBuild = opts.resultsBuild ?? spawnResultsBuild;
@@ -1791,29 +2026,15 @@ export function startOwnerUi(opts: OwnerUiOptions): OwnerUiServer {
1791
2026
  // The double-press guard (P8c) is per-server memory: a fresh server starts empty, which also
1792
2027
  // keeps the tests (one server per test) hermetic.
1793
2028
  lastAnswerByPlan.clear();
1794
- if (!cfg.ui.enabled) throw new Error("owner ui: ui.enabled is false — set it in the config first");
1795
- if (!cfg.ui.owner_login) throw new Error("owner ui: ui.owner_login is empty — set the tailscale login that may open the page");
2029
+ if (!cfg.workspace.enabled) throw new Error("owner ui: workspace.enabled is false — set it in the config first");
2030
+ if (!cfg.workspace.owner_login) throw new Error("owner ui: workspace.owner_login is empty — set the tailscale login that may open the page");
1796
2031
  const hostname = opts.hostname ?? tailscale.ip4();
1797
2032
  if (!hostname) throw new Error("owner ui: tailscale ip -4 did not answer — is tailscale up?");
1798
2033
  const peerOf = opts.peerOf ?? ((req: Request, server: UiHttpServer) => server.requestIP(req)?.address ?? "");
1799
- // Host allowlist (plan P3a): a DNS-rebinding page sends evil.example's Host with a matching
1800
- // Origin from the owner's own phone, so the peer and Origin checks alone pass it. On every
1801
- // request, before whois, the Host header must name this page — the tailnet address or the
1802
- // MagicDNS name (dnsName(), trailing dot stripped) — with the served port. Anything else is a
1803
- // 403 no matter whose peer it is. Built once, against the bound port (tests bind 0).
1804
- let allowedHosts: string[] | null = null;
1805
- const hostAllowed = (hostHeader: string, port: number | undefined): boolean => {
1806
- // No bound port (never expected): nothing is allowed — fail closed.
1807
- if (port === undefined) return false;
1808
- if (allowedHosts === null) {
1809
- const dns = tailscale.dnsName();
1810
- allowedHosts = [tailscale.ip4(), dns].filter((h): h is string => Boolean(h)).map(h => `${h}:${port}`);
1811
- }
1812
- return allowedHosts.includes(hostHeader);
1813
- };
2034
+ const hostAllowed = hostAllowlist(tailscale);
1814
2035
  const server = Bun.serve({
1815
2036
  hostname,
1816
- port: opts.port ?? cfg.ui.port,
2037
+ port: opts.port ?? cfg.workspace.port,
1817
2038
  fetch: async (req, srv) => {
1818
2039
  const url = new URL(req.url);
1819
2040
  let code = 500;
@@ -1831,7 +2052,7 @@ export function startOwnerUi(opts: OwnerUiOptions): OwnerUiServer {
1831
2052
  code = 403;
1832
2053
  } else {
1833
2054
  login = auth.login;
1834
- if (req.method === "POST" && req.headers.get("origin") !== `http://${hostHeader}`) {
2055
+ if (req.method === "POST" && !originIsHost(req.headers.get("origin"), hostHeader)) {
1835
2056
  res = textRes("forbidden: origin is not this page", 403);
1836
2057
  code = 403;
1837
2058
  } else if (req.method === "GET" && url.pathname === "/") {