@intentius/behold 0.29.32 → 0.29.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,162 @@
1
+ // behold#571: event-help's events, from what the kiosk already reads. A cycle
2
+ // told as facts in order, the news since the last look, the Tips switch, and
3
+ // the queues that keep tips and modals calm.
4
+ import { describe, expect, it } from "vitest";
5
+ import { stripFromSteps } from "./kiosk.js";
6
+ import { EH_STORE, cycleFacts, ehSnapshot, ehStore, ehStored, modalQueue, newEvents, storyTrail, tipsQueue, yodelRefusal } from "./kiosk-event-help.js";
7
+
8
+ const C = "9f3c2a71d04e5b8c6a1f2e3d4c5b6a7980716253";
9
+ const P = "1111111111111111111111111111111111111111";
10
+ const waves = [{ job: "apply-wave-1", wave: 1, roots: ["network", "other"] }, { job: "apply-wave-2", wave: 2, roots: ["app"] }, { job: "apply-wave-3", wave: 3, roots: ["edge"] }];
11
+ const demo = (step, more = {}) => ({ cycle: 7, scenario: "b-waves", step, label: `the ${step} line`, started_at: "2026-10-16T10:00:00Z", pull: 12, commit: step === "pull-request" || step === "planned" ? P : C, ...more });
12
+ const answer = { roots: [], pull_request: { run: { pull_request: 12, commit: P }, roots: ["network", "app"], totals: { create: 5 }, reads: [{ root: "app", upstream: "network", outputs: "planned", unknown: ["subnet_id"] }], waves: [] } };
13
+ const progress = (states) => ({ run: { present: true, commit: C, updated: "2026-10-16T10:01:00Z" }, states, reads: [] });
14
+ const st = (number, state, roots, totals = {}) => ({ number, state, roots, changed: roots.filter((r) => r !== "other"), totals });
15
+ const facts = (step, states = [], more = {}) => cycleFacts(ehSnapshot({ demo: demo(step), answer, progress: states.length ? progress(states) : null, waves, ...more }));
16
+ const texts = (fs) => storyTrail(fs).map((f) => f.text);
17
+
18
+ describe("event-help: the Tips switch", () => {
19
+ it("is on by default, off once a viewer turns it off, and on when storage refuses", () => {
20
+ const mem = () => {
21
+ const m = new Map();
22
+ return { getItem: (k) => (m.has(k) ? m.get(k) : null), setItem: (k, v) => m.set(k, v) };
23
+ };
24
+ const shelf = mem();
25
+ expect(ehStored(shelf)).toBe(true);
26
+ ehStore(shelf, false);
27
+ expect(shelf.getItem(EH_STORE)).toBe("off");
28
+ expect(ehStored(shelf)).toBe(false);
29
+ ehStore(shelf, true);
30
+ expect(ehStored(shelf)).toBe(true);
31
+ expect(ehStored({ getItem: () => { throw new Error("denied"); } })).toBe(true);
32
+ expect(() => ehStore({ setItem: () => { throw new Error("denied"); } }, false)).not.toThrow();
33
+ expect(ehStored(null)).toBe(true);
34
+ });
35
+ });
36
+
37
+ describe("event-help: a cycle told in order", () => {
38
+ it("tells the subnet's story, beat by beat, as the steps move", () => {
39
+ expect(texts(facts("pull-request"))).toEqual(["pull request #12 opened"]);
40
+ expect(texts(facts("planned"))).toEqual(["pull request #12 opened", "the plan creates 5"]);
41
+ const held = facts("waiting", [st(1, "applied", ["network", "other"], { create: 1 }), st(2, "waiting", ["app"]), st(3, "not-started", ["edge"])]);
42
+ expect(texts(held)).toEqual(["pull request #12 opened", "the plan creates 5", "pull request #12 merged", "wave 1 applied: 1 created", "subnet_id now known", "wave 2 held, since app's plan uses subnet_id"]);
43
+ const approval = { wave: 2, rows: [{ id: "requested", state: "lit" }, { id: "approved", state: "lit", text: "demo-reviewer approved exactly this plan.", seal: { ok: true, text: "signed; matches the repo's allowed signers" } }, { id: "resumed", state: "lit" }, { id: "spent", state: "dim" }] };
44
+ const done = facts("applied", [st(1, "applied", ["network", "other"], { create: 1 }), st(2, "applied", ["app"], { create: 4 }), st(3, "applied", ["edge"])], { approval });
45
+ expect(texts(done)).toEqual([
46
+ "pull request #12 opened",
47
+ "the plan creates 5",
48
+ "pull request #12 merged",
49
+ "wave 1 applied: 1 created",
50
+ "subnet_id now known",
51
+ "wave 2 held, since app's plan uses subnet_id",
52
+ "approved by demo-reviewer, signed",
53
+ "/terragucci apply ran the waves again",
54
+ "wave 2 applied under demo-reviewer's approval",
55
+ "wave 3 applied",
56
+ "all 3 waves applied",
57
+ ]);
58
+ });
59
+
60
+ it("holds the whole change when the gate names no wave (chant's pull-request loop)", () => {
61
+ expect(cycleFacts(ehSnapshot({ demo: demo("waiting"), answer })).find((f) => f.kind === "held")).toMatchObject({ text: "the plan waits for an approval", critical: true });
62
+ // A repo with declared waves waits for the run view to name the held wave: no second, vaguer hold first.
63
+ expect(facts("waiting").some((f) => f.kind === "held")).toBe(false);
64
+ });
65
+
66
+ it("counts every wave at applied, even one the run view has not caught up on (behold#571)", () => {
67
+ const behind = facts("applied", [st(1, "applied", ["network", "other"]), st(2, "applied", ["app"]), st(3, "not-started", ["edge"])]);
68
+ expect(behind.find((f) => f.kind === "applied").text).toBe("all 3 waves applied");
69
+ expect(facts("applied", [st(1, "applied", ["network", "other"])]).find((f) => f.kind === "applied").text).toBe("the wave applied");
70
+ });
71
+
72
+ it("tells chant's pull-request loop in its own order: the approval before the merge (#631)", () => {
73
+ const strip = stripFromSteps(["pull-request", "planned", "waiting", "approved", "merged", "applying", "applied", "reset"]);
74
+ const chant = (step, approval = null) => cycleFacts(ehSnapshot({ demo: { ...demo(step), scenario: "chant-pr-loop", tool: "chant" }, answer: null, approval, strip }));
75
+ // Waiting for the approval: the pull request is open, not merged.
76
+ expect(storyTrail(chant("waiting")).map((f) => f.text)).toEqual(["pull request #12 opened", "the plan waits for an approval"]);
77
+ const approval = { wave: null, rows: [{ id: "approved", state: "lit", text: "demo-reviewer approved exactly this plan.", seal: { ok: true, text: "signed; matches the repo's allowed signers" } }] };
78
+ expect(storyTrail(chant("applied", approval)).map((f) => f.text)).toEqual(["pull request #12 opened", "the plan waits for an approval", "approved by demo-reviewer, signed", "pull request #12 merged", "the change applied"]);
79
+ // terragucci's waves keep theirs: a wave's hold after the merge.
80
+ expect(storyTrail(facts("waiting", [st(1, "applied", ["network", "other"]), st(2, "waiting", ["app"])])).map((f) => f.kind)).toEqual(["pull-request", "planned", "merged", "applied-wave", "known", "held"]);
81
+ });
82
+
83
+ it("names each event's subjects, so the kiosk can place it", () => {
84
+ const held = facts("waiting", [st(1, "applied", ["network", "other"]), st(2, "waiting", ["app"])], { runDoc: { id: 4801, cycle: 7, jobs: [{ name: "apply-wave-2", status: "waiting", steps: [] }] } });
85
+ expect(held.find((f) => f.kind === "held")).toMatchObject({ critical: true, subjects: { roots: ["app"], wave: 2, job: "apply-wave-2", run: 4801 } });
86
+ expect(held.find((f) => f.kind === "known").subjects.roots).toEqual(["network", "app"]);
87
+ });
88
+
89
+ it("says SQL Yodeler's refusal from the failed job's own log, and the re-run", () => {
90
+ const log = ["yodel apply: refused: a pre-migration check of 20261016T0521-unique-email failed under the lock", " step 0, CREATE UNIQUE INDEX CONCURRENTLY users_email_key ON app.users (email), would fail: 1 values of (email) held by more than one row, which a unique index fails on"];
91
+ expect(yodelRefusal(log)).toBe("SQL Yodeler refused, since an email is shared by more than one row");
92
+ expect(yodelRefusal(["dev: apply failed"])).toBeNull();
93
+ const runDoc = { id: 4826, cycle: 7, jobs: [{ name: "apply-wave-2", status: "failure", steps: [{ name: "Apply", status: "failure", log }] }] };
94
+ const failed = facts("failed", [st(1, "applied", ["network", "other"]), st(2, "failed", ["app"])], { runDoc });
95
+ expect(failed.find((f) => f.kind === "refused")).toMatchObject({ text: "SQL Yodeler refused, since an email is shared by more than one row", critical: true, subjects: { wave: 2, job: "apply-wave-2" } });
96
+ // The re-run, once the run view shows the wave applying again in a run where its job no longer failed.
97
+ const again = cycleFacts(ehSnapshot({ demo: demo("resumed"), answer, progress: progress([st(1, "applied", ["network", "other"]), st(2, "applying", ["app"])]), runDoc: { id: 4830, cycle: 7, jobs: [{ name: "apply-wave-2", status: "running", steps: [] }] }, waves }));
98
+ expect(again.some((f) => f.kind === "rerun")).toBe(false); // this snapshot never saw the failure
99
+ // A viewer who arrives after the re-run still gets the refusal, from the cycle's earlier run.
100
+ const later = cycleFacts(ehSnapshot({ demo: demo("waiting"), answer, progress: progress([st(1, "applied", ["network", "other"]), st(2, "waiting", ["app"])]), runDoc: { id: 4830, cycle: 7, jobs: [{ name: "apply-wave-2", status: "waiting", steps: [] }] }, runDocs: [runDoc], waves }));
101
+ expect(storyTrail(later).map((f) => f.kind)).toContain("refused");
102
+ expect(later.find((f) => f.kind === "refused").subjects).toMatchObject({ wave: 2, job: "apply-wave-2", run: 4826 });
103
+ const seenFailing = cycleFacts(ehSnapshot({ demo: demo("resumed"), answer, progress: progress([st(1, "applied", ["network", "other"]), st(2, "applying", ["app"])]), runDoc: { id: 4830, cycle: 7, jobs: [{ name: "apply-wave-2", status: "running", steps: [] }] }, waves, failed: [2] }));
104
+ expect(seenFailing.find((f) => f.kind === "rerun")).toMatchObject({ text: "wave 2 runs again", subjects: { wave: 2 } });
105
+ });
106
+
107
+ it("pops a tip when a wave starts or its numbers land, and tells the story's beat when its trace is ready", () => {
108
+ const metrics = { run: { current: true, label: `This run · ${C.slice(0, 8)}`, waves: [{ wave: 1, seconds: "1.6 s", held: null, changed: "1 created" }] } };
109
+ const waveTraces = { 1: { run: "9", job: "apply-wave-1", trace: { wave: 1, ms: 1600, start: 0, spans: [{ id: "r", parent: null, name: "tf-apply", start: 0, ms: 1600, attrs: {} }, { id: "p", parent: "r", name: "plan", start: 0, ms: 1200, attrs: { "terragucci.phase": "plan" } }] } } };
110
+ const fs = facts("applying", [st(1, "applying", ["network", "other"])], { metrics, waveTraces, runDoc: { id: 9, cycle: 7, jobs: [] } });
111
+ expect(fs.filter((f) => !f.trail).map((f) => f.text)).toEqual(["wave 1 started", "wave 1: 1.6 s · 1 created"]);
112
+ // A wave's trace is a beat of the story, its tip saying what the trace shows; a click on it opens the trace.
113
+ expect(fs.find((f) => f.kind === "trace")).toMatchObject({ trail: true, text: "wave 1's trace is ready; it took 1.6 s, 1.2 s of it in the plan", subjects: { wave: 1, job: "apply-wave-1", run: "9" } });
114
+ expect(fs.find((f) => f.kind === "metrics").subjects.wave).toBe(1);
115
+ // An older run's numbers are not this cycle's news.
116
+ expect(facts("applying", [], { metrics: { run: { current: false, waves: metrics.run.waves } } }).some((f) => f.kind === "metrics")).toBe(false);
117
+ // Nor are the last cycle's, still on screen as a new one opens its pull request.
118
+ expect(facts("pull-request", [], { metrics }).some((f) => f.kind === "metrics")).toBe(false);
119
+ expect(facts("applying", [], { metrics: { run: { ...metrics.run, label: "This run · 0badc0de" } } }).some((f) => f.kind === "metrics")).toBe(false);
120
+ });
121
+ });
122
+
123
+ describe("event-help: what is news", () => {
124
+ it("is nothing on a page's first look (the trail has it), then each fact the first time it shows", () => {
125
+ const a = facts("planned");
126
+ expect(newEvents(null, a)).toEqual([]);
127
+ const seen = new Set(a.map((f) => f.id));
128
+ const b = facts("waiting", [st(1, "applied", ["network", "other"]), st(2, "waiting", ["app"])]);
129
+ // A wave's start beside its own next beat is said by the beat.
130
+ expect(newEvents(seen, b).map((f) => f.kind)).toEqual(["merged", "applied-wave", "known", "held"]);
131
+ const c = facts("applying", [st(1, "applying", ["network", "other"])]);
132
+ expect(newEvents(new Set(), c).map((f) => f.text)).toEqual(["pull request #12 opened", "the plan creates 5", "pull request #12 merged", "wave 1 started"]);
133
+ });
134
+
135
+ it("keeps a fact that turns up late, behind the story already told, for the trail alone", () => {
136
+ const b = facts("waiting", [st(1, "applied", ["network", "other"]), st(2, "waiting", ["app"])]);
137
+ const after = Math.max(...b.map((f) => f.order)) - 10;
138
+ expect(newEvents(new Set(), b, { after }).map((f) => f.kind)).toEqual(["applied-wave", "known", "held"]);
139
+ });
140
+ });
141
+
142
+ describe("event-help: calm queues", () => {
143
+ const ev = (id, critical = false, kind = "applied-wave") => ({ id, kind, critical });
144
+ it("shows two tips at once, each its time, and the rest wait their turn", () => {
145
+ let q = tipsQueue(null, { add: [ev("a"), ev("b"), ev("c")], now: 0 });
146
+ expect(q.shown.map((s) => s.event.id)).toEqual(["a", "b"]);
147
+ expect(q.waiting.map((e) => e.id)).toEqual(["c"]);
148
+ q = tipsQueue(q, { now: 4_999 });
149
+ expect(q.shown.map((s) => s.event.id)).toEqual(["a", "b"]);
150
+ q = tipsQueue(q, { now: 5_000 });
151
+ expect(q.shown.map((s) => s.event.id)).toEqual(["c"]);
152
+ expect(tipsQueue(q, { add: [ev("c")], now: 5_001 }).waiting).toEqual([]);
153
+ });
154
+
155
+ it("opens one modal at a time, never while a viewer is at the page, newest of each kind", () => {
156
+ const held = ev("held", true, "held");
157
+ const held2 = ev("held2", true, "held");
158
+ expect(modalQueue(null, { add: [ev("x"), held], now: 10_000, lastInput: 9_000 })).toEqual({ next: null, waiting: [held] });
159
+ expect(modalQueue({ waiting: [held] }, { add: [held2], now: 30_000 }).next).toBe(held2);
160
+ expect(modalQueue({ waiting: [held] }, { now: 30_000, open: true }).next).toBeNull();
161
+ });
162
+ });
package/web/kiosk-runs.js CHANGED
@@ -604,14 +604,21 @@ export function renderRun(host, answer, ui, { now = new Date(), pickJob = () =>
604
604
  if (!job) return { log: null, steps: null, key: null };
605
605
  // behold#571: a job with a trace in Tempo offers it beside its steps (web/kiosk-trace.js).
606
606
  if (trace && trace.has(job.name)) {
607
+ // behold#571: the job's header carries the toggle between its steps and its trace, so it reads as a choice, not one more chip.
607
608
  const tabs = el("div", "t-tabs");
609
+ const head = el("span", "t-tabs-job");
610
+ head.append(statusIcon(job.status), el("span", "r-steps-job", job.name));
611
+ const seg = el("div", "t-seg");
612
+ seg.setAttribute("role", "group");
613
+ seg.setAttribute("aria-label", `${job.name}: steps or trace`);
608
614
  for (const [view, words] of [["steps", "Steps"], ["trace", "Trace"]]) {
609
615
  const b = el("button", "t-tab", words);
610
616
  b.type = "button";
611
617
  b.setAttribute("aria-pressed", String((jobView === "trace") === (view === "trace")));
612
618
  b.addEventListener("click", () => pickView(view));
613
- tabs.appendChild(b);
619
+ seg.appendChild(b);
614
620
  }
621
+ tabs.append(head, seg);
615
622
  host.appendChild(tabs);
616
623
  if (jobView === "trace") {
617
624
  const box = el("div", "r-steps r-trace");
@@ -1095,6 +1102,16 @@ export function startRuns(
1095
1102
  if (s.run && s.run.doc && s.run.doc.id === run) draw();
1096
1103
  else void readRun();
1097
1104
  };
1105
+ /** behold#571: a job of a run from elsewhere (Watch's wave boxes, event-help's tips): its steps, or its trace. */
1106
+ s.showJob = (run, job, view = "steps") => {
1107
+ if (run !== null && run !== undefined) s.selected = Number.isNaN(Number(run)) ? run : Number(run);
1108
+ follow = false;
1109
+ s.picked = now().getTime();
1110
+ s.ui = { job, open: null, setup: null };
1111
+ jobView = view;
1112
+ if (s.run && s.run.doc && String(s.run.doc.id) === String(run)) draw();
1113
+ else void readRun();
1114
+ };
1098
1115
  return s;
1099
1116
  }
1100
1117
 
@@ -192,9 +192,16 @@ export function runStrip(traces) {
192
192
 
193
193
  const STYLE = `
194
194
  .t-trace { padding: 0.2em 0 0.6em; font-size: 0.86em; }
195
- .t-tabs { display: flex; gap: 0.3em; padding: 0.5em 1em 0.1em; flex-wrap: wrap; }
196
- .t-tab { font: 600 0.78em var(--font-mono); text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); background: transparent; border: 1px solid var(--rule); border-radius: 999px; padding: 0.2em 0.8em; cursor: pointer; }
197
- .t-tab[aria-pressed="true"] { color: var(--fg); background: var(--active); border-color: var(--focus); }
195
+ .t-tabs { display: flex; align-items: center; justify-content: space-between; gap: 0.6em; padding: 0.45em 1em 0.35em; flex-wrap: wrap; border-bottom: 1px solid color-mix(in srgb, var(--rule) 55%, transparent); }
196
+ .t-tabs-job { display: inline-flex; align-items: center; gap: 0.5em; min-width: 0; }
197
+ .t-tabs-job .r-icon { margin: 0; }
198
+ .t-seg { display: inline-flex; border: 1px solid var(--rule); border-radius: 999px; overflow: hidden; flex: none; }
199
+ .t-tab { font: 600 0.9em var(--font-ui); color: var(--muted); background: transparent; border: 0; padding: 0.25em 1em; cursor: pointer; }
200
+ .t-tab + .t-tab { border-left: 1px solid var(--rule); }
201
+ .t-attempts { display: flex; align-items: center; justify-content: space-between; gap: 0.6em; }
202
+ .t-seg-small .t-tab { font: 600 0.85em var(--font-mono); padding: 0.05em 0.7em; letter-spacing: 0; }
203
+ .t-tab:hover { color: var(--fg); }
204
+ .t-tab[aria-pressed="true"], .t-tab[aria-pressed="true"]:hover { color: var(--bg); background: var(--pending); }
198
205
  .t-sec { font: 600 0.8em var(--font-mono); text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); padding: 0.6em 1em 0.25em; }
199
206
  .t-strip, .t-rows { display: flex; flex-direction: column; }
200
207
  .t-row { display: grid; grid-template-columns: minmax(10em, 38%) minmax(0, 1fr) 4.6em; align-items: center; gap: 0.6em; padding: 0.08em 1em; min-height: 1.55em; cursor: default; }
@@ -260,7 +267,34 @@ function bar(doc, at, width) {
260
267
  * the viewer's folds (`open`, `shut`, sets of span ids) and calls `toggle(id)`
261
268
  * and `pickJob(name)`.
262
269
  */
263
- export function renderTrace(host, { traces, run = [], job }, { doc = document, toggle = () => {}, pickJob = null, open = new Set(), shut = new Set() } = {}) {
270
+ /**
271
+ * behold#571: which of a job's traces is the one asked about: the trace that
272
+ * started at `start` (the wave's own, as the kiosk picked it), else the
273
+ * newest of `wave`'s, else the newest. A resumed run's job applies several
274
+ * waves, and a wave may run twice, so its traces are attempts.
275
+ */
276
+ export function attemptFor(traces, { wave = null, start = null } = {}) {
277
+ if (!traces || !traces.length) return -1;
278
+ if (start !== null) {
279
+ const i = traces.findIndex((t) => Math.abs(t.start - start) < 1);
280
+ if (i >= 0) return i;
281
+ }
282
+ if (wave !== null) {
283
+ let best = -1;
284
+ traces.forEach((t, i) => {
285
+ if (Number(t.wave) === Number(wave) && (best < 0 || traces[best].start < t.start)) best = i;
286
+ });
287
+ if (best >= 0) return best;
288
+ }
289
+ return traces.reduce((b, t, i) => (traces[b].start < t.start ? i : b), 0);
290
+ }
291
+
292
+ /** behold#571: the words over one attempt of several, and the switch's label. */
293
+ export function attemptWords(i, n, start) {
294
+ return `Attempt ${i + 1} of ${n}, started at ${new Date(start).toISOString().slice(11, 16)} UTC`;
295
+ }
296
+
297
+ export function renderTrace(host, { traces, run = [], job }, { doc = document, toggle = () => {}, pickJob = null, open = new Set(), shut = new Set(), attempt = null, pickAttempt = null } = {}) {
264
298
  traceStyle(doc);
265
299
  const box = el(doc, "div", "t-trace");
266
300
  const strip = runStrip(run);
@@ -279,10 +313,29 @@ export function renderTrace(host, { traces, run = [], job }, { doc = document, t
279
313
  }
280
314
  box.appendChild(rows);
281
315
  }
282
- traces.forEach((t, i) => {
283
- const when = new Date(t.start);
284
- const head = traces.length > 1 ? `Attempt ${i + 1} of ${traces.length}, ${when.toISOString().slice(11, 19)} UTC` : `This job · ${msWords(t.ms)}`;
285
- box.appendChild(el(doc, "div", "t-sec", head));
316
+ // behold#571: asked about one attempt of several, it shows that one, with a switch to the others.
317
+ const one = attempt !== null && attempt >= 0 && attempt < traces.length && traces.length > 1;
318
+ const shown = one ? [traces[attempt]] : traces;
319
+ shown.forEach((t, k) => {
320
+ const i = one ? attempt : k;
321
+ const head = traces.length > 1 ? attemptWords(i, traces.length, t.start) : `This job · ${msWords(t.ms)}`;
322
+ if (one) {
323
+ const sec = el(doc, "div", "t-sec t-attempts");
324
+ sec.appendChild(el(doc, "span", null, head));
325
+ const seg = el(doc, "span", "t-seg t-seg-small");
326
+ seg.setAttribute("role", "group");
327
+ seg.setAttribute("aria-label", "attempt");
328
+ traces.forEach((x, j) => {
329
+ const b = el(doc, "button", "t-tab", String(j + 1));
330
+ b.type = "button";
331
+ b.title = attemptWords(j, traces.length, x.start);
332
+ b.setAttribute("aria-pressed", String(j === i));
333
+ if (pickAttempt) b.addEventListener("click", () => pickAttempt(j));
334
+ seg.appendChild(b);
335
+ });
336
+ sec.appendChild(seg);
337
+ box.appendChild(sec);
338
+ } else box.appendChild(el(doc, "div", "t-sec", head));
286
339
  const rows = el(doc, "div", "t-rows");
287
340
  for (const r of waterfallRows(t, { open, shut })) {
288
341
  const cls = ["t-row", r.kids ? "t-can" : "", r.service !== "terragucci" ? "t-bin" : "", r.critical ? "t-crit" : "", r.wait ? "t-wait" : "", r.error ? "t-err" : ""].filter(Boolean).join(" ");
@@ -372,8 +425,8 @@ export function traceSource({ fetchJson, onChange = () => {}, now = () => Date.n
372
425
  has: (repo, run, job) => of(repo, run, job).length > 0,
373
426
  traces: of,
374
427
  all: (repo, run) => (read(repo, run) || { traces: [] }).traces,
375
- draw(host, { repo, run, job, pickJob = null, doc = document }) {
376
- return renderTrace(host, { traces: of(repo, run, job), run: this.all(repo, run), job }, { doc, pickJob, open: folds.open, shut: folds.shut, toggle: (id, depth) => { folds.toggle(id, depth); onChange(); } });
428
+ draw(host, { repo, run, job, pickJob = null, doc = document, attempt = null, pickAttempt = null }) {
429
+ return renderTrace(host, { traces: of(repo, run, job), run: this.all(repo, run), job }, { doc, pickJob, attempt, pickAttempt, open: folds.open, shut: folds.shut, toggle: (id, depth) => { folds.toggle(id, depth); onChange(); } });
377
430
  },
378
431
  };
379
432
  }
@@ -384,19 +437,25 @@ export function traceSource({ fetchJson, onChange = () => {}, now = () => Date.n
384
437
  * it at another job; `stop` ends its reads. With no trace for the job it
385
438
  * draws nothing.
386
439
  */
387
- export function mountTrace(host, { project, run, job, fetchJson = defaultFetch, doc = document, setTimer = setInterval, clearTimer = clearInterval, pickJob = null } = {}) {
388
- let target = { project, run, job };
440
+ export function mountTrace(host, { project, run, job, wave = null, start = null, fetchJson = defaultFetch, doc = document, setTimer = setInterval, clearTimer = clearInterval, pickJob = null } = {}) {
441
+ let target = { project, run, job, wave, start };
442
+ // behold#571: with a wave named, the attempt that is its; a viewer's pick of another holds until the target moves.
443
+ let picked = null;
389
444
  const draw = () => {
390
445
  host.replaceChildren();
391
446
  if (!source.has(target.project, target.run, target.job)) return;
392
- source.draw(host, { repo: target.project, run: target.run, job: target.job, pickJob, doc });
447
+ const traces = source.traces(target.project, target.run, target.job);
448
+ const attempt = target.wave === null && target.start === null ? null : picked !== null && picked < traces.length ? picked : attemptFor(traces, target);
449
+ source.draw(host, { repo: target.project, run: target.run, job: target.job, pickJob, doc, attempt, pickAttempt: (i) => ((picked = i), draw()) });
393
450
  };
394
451
  const source = traceSource({ fetchJson, onChange: draw });
395
452
  draw();
396
453
  const timer = setTimer(draw, TRACE_POLL_MS);
397
454
  return {
398
455
  update(next) {
456
+ const was = JSON.stringify(target);
399
457
  target = { ...target, ...next };
458
+ if (JSON.stringify(target) !== was) picked = null;
400
459
  draw();
401
460
  },
402
461
  stop() {
@@ -155,3 +155,17 @@ describe("the strip's left bars (behold#571)", () => {
155
155
  expect(["failed", "changed-after-approval", "waiting", "applied", "planned", undefined, "other"].map(stripTone)).toEqual(["bad", "bad", "wait", "ok", "ok", "idle", "idle"]);
156
156
  });
157
157
  });
158
+
159
+ describe("kiosk trace: one attempt of several (behold#571)", () => {
160
+ const t = (wave, start) => ({ wave, start, ms: 10, spans: [] });
161
+ it("picks the attempt that is the asked-about wave's: its own start, else that wave's newest, else the newest", async () => {
162
+ const { attemptFor, attemptWords } = await import("./kiosk-trace.js");
163
+ const traces = [t(1, 100), t(2, 200), t(2, 300)];
164
+ expect(attemptFor(traces, { wave: 2, start: 200 })).toBe(1);
165
+ expect(attemptFor(traces, { wave: 2 })).toBe(2);
166
+ expect(attemptFor(traces, { wave: 1 })).toBe(0);
167
+ expect(attemptFor(traces, { wave: 9 })).toBe(2);
168
+ expect(attemptFor([], { wave: 1 })).toBe(-1);
169
+ expect(attemptWords(0, 2, Date.parse("2026-10-16T19:25:38Z"))).toBe("Attempt 1 of 2, started at 19:25 UTC");
170
+ });
171
+ });
@@ -190,9 +190,11 @@ function roundedWeek(v) {
190
190
  export function resultModel(demo, metrics, progress = null) {
191
191
  if (!demo || demo.step !== "applied") return null;
192
192
  const run = matchingRun(progress, demo);
193
- const states = run ? (progress.states || []).filter((w) => w.state === "applied") : [];
193
+ // The step says the run applied: every wave the run view names counts, even one a read has not caught up on yet.
194
+ const all = run ? progress.states || [] : [];
195
+ const states = all.filter((w) => w.state === "applied");
194
196
  const m = metrics && metrics.run && metrics.run.current ? metrics.run.waves : [];
195
- const n = states.length || m.length;
197
+ const n = all.length || m.length;
196
198
  if (!n) return null;
197
199
  const counts = [`${n} ${n === 1 ? "wave" : "waves"} applied`];
198
200
  const changed = states.length ? mergeChanges(states.map((w) => w.totals)) : mergeChanges(m.map((w) => w.changesRaw));
@@ -204,10 +206,48 @@ export function resultModel(demo, metrics, progress = null) {
204
206
  const held = m.reduce((a, w) => a + (Number.isFinite(w.heldRaw) ? w.heldRaw : 0), 0);
205
207
  if (held > 0) counts.push(`${secondsShort(held)} held for an approval`);
206
208
  }
207
- const waves = [...m].sort((a, b) => a.wave - b.wave).map((w) => ({ wave: w.wave, words: badgeWords(w) })).filter((w) => w.words);
209
+ // A row for every wave, its numbers when they have landed; never fewer rows than the count says.
210
+ const numbers = new Map(m.map((w) => [w.wave, badgeWords(w)]));
211
+ const numbered = [...new Set([...all.map((w) => w.number), ...m.map((w) => w.wave)])].sort((a, b) => a - b);
212
+ const waves = numbered.map((w) => ({ wave: w, words: numbers.get(w) || null }));
208
213
  return { head: "Applied", line: typeof demo.label === "string" ? demo.label : "", counts, waves };
209
214
  }
210
215
 
216
+ /**
217
+ * behold#571: the run view as the cycle has seen it, for the result card and
218
+ * the trail. Reads land one by one and a read can lag behind the last: within
219
+ * one cycle's commit, a wave once read as applied stays applied, a wave a
220
+ * read leaves out keeps what it was, and the run stays the last one that
221
+ * matched. `{ memo, progress }`; pass the memo back in with the next read.
222
+ */
223
+ export function steadyRun(memo, progress, demo) {
224
+ const key = demo ? `${demo.cycle}|${demo.commit}` : null;
225
+ const run = demo ? matchingRun(progress, demo) : null;
226
+ const was = memo && memo.key === key ? memo : { key, run: null, states: {} };
227
+ const next = { key, run: run || was.run, states: { ...was.states } };
228
+ if (run) {
229
+ for (const st of progress.states || []) {
230
+ const had = next.states[st.number];
231
+ if (had && had.state === "applied" && st.state !== "applied") continue;
232
+ // A re-run's run view says nothing changed for a wave an earlier run applied: the change stays the one that landed.
233
+ if (had && had.state === "applied" && st.state === "applied" && changeCount(had.totals) > 0 && changeCount(st.totals) === 0) continue;
234
+ next.states[st.number] = st;
235
+ }
236
+ }
237
+ const states = Object.values(next.states).sort((a, b) => a.number - b.number);
238
+ if (!next.run || !states.length) return { memo: next, progress };
239
+ return { memo: next, progress: { ...(run ? progress : {}), reads: run ? progress.reads || [] : [], run: next.run, states } };
240
+ }
241
+
242
+ const changeCount = (totals) => ACTION_ORDER.reduce((a, k) => a + (totals && typeof totals[k] === "number" ? totals[k] : 0), 0);
243
+
244
+ /** behold#571: whether a run view is behind the step: the step says applied, and a wave in it still says otherwise. */
245
+ export function behindStep(demo, progress) {
246
+ if (!demo || demo.step !== "applied") return false;
247
+ const run = matchingRun(progress, demo);
248
+ return !!run && (progress.states || []).some((w) => w.state !== "applied");
249
+ }
250
+
211
251
  const ACTION_ORDER = ["create", "update", "delete", "replace", "forget", "import", "move"];
212
252
  const ACTION_WORDS = { create: "created", update: "updated", delete: "deleted", replace: "replaced", forget: "forgotten", import: "imported", move: "moved" };
213
253
  function mergeChanges(list) {
@@ -2,7 +2,7 @@
2
2
  // takes, what the caption leads with, the badges, the delivery line, the
3
3
  // result card, the drawer's folded lines, and where an overlay goes.
4
4
  import { describe, expect, it } from "vitest";
5
- import { MODE_STORE, activeWave, badgeTitle, badgeWords, badges, captionModel, changeRoots, doraLine, modeStored, placeBeside, resultModel, shotFor, stepTone, tailLines } from "./kiosk-watch.js";
5
+ import { MODE_STORE, activeWave, badgeTitle, badgeWords, badges, behindStep, steadyRun, captionModel, changeRoots, doraLine, modeStored, placeBeside, resultModel, shotFor, stepTone, tailLines } from "./kiosk-watch.js";
6
6
 
7
7
  const C = "9f3c2a71d04e5b8c6a1f2e3d4c5b6a7980716253";
8
8
  const P = "1111111111111111111111111111111111111111";
@@ -144,6 +144,36 @@ describe("kiosk watch: the numbers", () => {
144
144
  expect(resultModel(demo("applying"), metrics, p)).toBeNull();
145
145
  expect(resultModel(demo("applied"), null, null)).toBeNull();
146
146
  });
147
+
148
+ it("never counts fewer waves than the step says, nor lists fewer than it counts (behold#571)", () => {
149
+ // The step says applied while the run view still has wave 3 queued: three waves applied, three rows, the third's numbers to come.
150
+ const behind = progress([st(1, "applied", ["network"], { update: 1 }), st(2, "applied", ["app"], { create: 4 }), st(3, "not-started", ["edge"])]);
151
+ const r = resultModel(demo("applied"), metrics, behind);
152
+ expect(r.counts[0]).toBe("3 waves applied");
153
+ expect(r.waves).toEqual([{ wave: 1, words: "1.6 s · 1 updated" }, { wave: 2, words: "9.5 s · held 25 s · 4 created" }, { wave: 3, words: null }]);
154
+ expect(behindStep(demo("applied"), behind)).toBe(true);
155
+ expect(behindStep(demo("applied"), progress([st(1, "applied", ["network"])]))).toBe(false);
156
+ expect(behindStep(demo("applying"), behind)).toBe(false);
157
+ });
158
+
159
+ it("keeps the run view as the cycle has seen it: an applied wave stays applied, a wave a read leaves out stays, a read for another run is set aside", () => {
160
+ const d = demo("applied");
161
+ let { memo, progress: p1 } = steadyRun(null, progress([st(1, "applied", ["network"]), st(2, "applied", ["app"]), st(3, "applied", ["edge"])]), d);
162
+ expect(p1.states.map((w) => w.state)).toEqual(["applied", "applied", "applied"]);
163
+ // A lagging read: the resume's run view, not yet caught up.
164
+ const lag = steadyRun(memo, progress([st(1, "applied", ["network"]), st(2, "not-started", ["app"])]), d);
165
+ expect(lag.progress.states.map((w) => [w.number, w.state])).toEqual([[1, "applied"], [2, "applied"], [3, "applied"]]);
166
+ // A read of another commit (the reset's push): the cycle's run stays.
167
+ const other = steadyRun(lag.memo, { run: { present: true, commit: "0000000000000000000000000000000000000000", updated: "2026-10-16T09:00:00Z" }, states: [st(1, "planned", ["network"])], reads: [] }, d);
168
+ expect(other.progress.states).toHaveLength(3);
169
+ expect(resultModel(d, null, other.progress).counts[0]).toBe("3 waves applied");
170
+ // The resume's run view says the waves an earlier run applied changed nothing now: the changes that landed stay.
171
+ const first = steadyRun(null, progress([st(1, "applied", ["network"], { update: 1 }), st(2, "applied", ["app"], { create: 4 })]), d);
172
+ const resumed = steadyRun(first.memo, progress([st(1, "applied", ["network"], { "no-op": 3 }), st(2, "applied", ["app"], { create: 4 })]), d);
173
+ expect(resultModel(d, null, resumed.progress).counts).toEqual(["2 waves applied", "4 created, 1 updated"]);
174
+ // A new cycle starts over.
175
+ expect(steadyRun(other.memo, null, demo("pull-request", { cycle: 13 })).progress).toBeNull();
176
+ });
147
177
  });
148
178
 
149
179
  describe("kiosk watch: the drawer's folded lines", () => {
@@ -0,0 +1,104 @@
1
+ // behold#571: each wave's trace, for the places Watch already shows a wave's
2
+ // numbers: the badge on its box, the applied result card (a mini waterfall
3
+ // per wave), the drawer, and event-help's "trace ready" tip. Pure: it reads
4
+ // /api/traces answers (src/tempo-traces.ts) the kiosk already fetches, one
5
+ // per run of the cycle, and keeps the newest trace of each wave.
6
+
7
+ /** The phases a wave's job runs, in order, as terragucci names them on its stage's spans. */
8
+ export const PHASES = ["plan", "gate", "apply", "report", "upload"];
9
+
10
+ /**
11
+ * The newest trace of each wave across the cycle's runs' answers:
12
+ * `{ [wave]: { run, job, trace } }`. A trace names its wave (`wave`) and its
13
+ * job; a resumed run applies several waves in one job, each its own trace.
14
+ */
15
+ export function waveTraces(answers) {
16
+ const out = {};
17
+ for (const a of answers || []) {
18
+ if (!a || a.error || !Array.isArray(a.traces)) continue;
19
+ for (const t of a.traces) {
20
+ const w = Number(t.wave);
21
+ if (!Number.isInteger(w) || !Array.isArray(t.spans) || !t.spans.length) continue;
22
+ if (!out[w] || out[w].trace.start < t.start) out[w] = { run: String(a.run), job: t.job, trace: t };
23
+ }
24
+ }
25
+ return out;
26
+ }
27
+
28
+ const attrs = (s) => s.attrs || {};
29
+
30
+ /**
31
+ * One wave's trace as phase bars: `[{ phase, ms, at, width, wait }]`, `at` and
32
+ * `width` 0..1 across the stage, in time order. A gate that held a wave for an
33
+ * approval is split: the hold (`phase: "held"`, a wait) and the rest of the
34
+ * gate. Only the phases the trace has; nothing for a trace without them.
35
+ */
36
+ export function phaseBars(trace) {
37
+ const spans = trace && Array.isArray(trace.spans) ? trace.spans : [];
38
+ const root = spans.find((s) => !s.parent) || null;
39
+ if (!root || !(root.ms > 0)) return [];
40
+ const t0 = root.start;
41
+ const span = root.ms;
42
+ const bar = (phase, start, ms, wait = false) => ({ phase, ms, at: Math.max(0, (start - t0) / span), width: Math.max(0, Math.min(1, ms / span)), wait });
43
+ const out = [];
44
+ for (const s of spans.filter((x) => x.parent === root.id && attrs(x)["terragucci.phase"]).sort((a, b) => a.start - b.start)) {
45
+ const phase = String(attrs(s)["terragucci.phase"]);
46
+ const held = attrs(s)["terragucci.gate.held_seconds"];
47
+ if (phase === "gate" && typeof held === "number" && held > 0) {
48
+ const heldMs = Math.min(s.ms, held * 1000);
49
+ out.push(bar("held", s.start, heldMs, true));
50
+ if (s.ms - heldMs > 0) out.push(bar("gate", s.start + heldMs, s.ms - heldMs));
51
+ } else out.push(bar(phase, s.start, s.ms, phase === "gate" && attrs(s)["terragucci.gate.status"] === "waiting"));
52
+ }
53
+ return out;
54
+ }
55
+
56
+ /** "70 ms", "1.6 s", "25 s", "2 min 5 s". */
57
+ export function msShort(ms) {
58
+ if (!(ms >= 0)) return null;
59
+ if (ms < 1000) return `${Math.max(1, Math.round(ms))} ms`;
60
+ const s = ms / 1000;
61
+ if (s < 10) return `${Math.round(s * 10) / 10} s`;
62
+ if (s < 60) return `${Math.round(s)} s`;
63
+ const m = Math.floor(s / 60);
64
+ const r = Math.round(s - m * 60);
65
+ return r ? `${m} min ${r} s` : `${m} min`;
66
+ }
67
+
68
+ /** The words a phase bar carries: "plan 1.2 s", "held 25 s for an approval". */
69
+ export function phaseWords(b) {
70
+ if (b.phase === "held") return `held ${msShort(b.ms)} for an approval`;
71
+ return `${b.phase} ${msShort(b.ms)}`;
72
+ }
73
+
74
+ /**
75
+ * What a wave's trace shows, in one line, for its "trace ready" tip: how long
76
+ * the job took, and where the time went: the hold when an approval held it,
77
+ * else the longest phase. "wave 2 took 1.6 s, 1.2 s of it in the plan".
78
+ */
79
+ export function traceReadyWords(wave, trace) {
80
+ if (!trace || !(trace.ms > 0)) return null;
81
+ const bars = phaseBars(trace);
82
+ const took = `wave ${wave}'s trace is ready; it took ${msShort(trace.ms)}`;
83
+ const held = bars.find((b) => b.phase === "held");
84
+ if (held) return `${took}, ${msShort(held.ms)} of it held for an approval`;
85
+ const longest = bars.filter((b) => !b.wait).sort((a, b) => b.ms - a.ms)[0];
86
+ return longest ? `${took}, ${msShort(longest.ms)} of it in the ${longest.phase}` : took;
87
+ }
88
+
89
+ /**
90
+ * The applied card's mini waterfall: one row per wave that has a trace, in
91
+ * wave order: `{ wave, run, job, ms, words, bars }`. No row for a wave
92
+ * without one.
93
+ */
94
+ export function miniWaterfall(traces) {
95
+ return Object.keys(traces || {})
96
+ .map(Number)
97
+ .sort((a, b) => a - b)
98
+ .map((w) => {
99
+ const { run, job, trace } = traces[w];
100
+ const bars = phaseBars(trace);
101
+ return bars.length ? { wave: w, run, job, ms: trace.ms, words: msShort(trace.ms), bars } : null;
102
+ })
103
+ .filter(Boolean);
104
+ }
@@ -0,0 +1,53 @@
1
+ // behold#571: each wave's trace for Watch: which trace is a wave's, its
2
+ // phases as bars, the "trace ready" line, and the applied card's rows.
3
+ import { describe, expect, it } from "vitest";
4
+ import { miniWaterfall, msShort, phaseBars, phaseWords, traceReadyWords, waveTraces } from "./kiosk-wave-traces.js";
5
+
6
+ const span = (id, parent, start, ms, attrs = {}, name = id) => ({ id, parent, name, service: "terragucci", start, ms, attrs });
7
+ const trace = (wave, start, phases, job = `apply-wave-${wave}`) => {
8
+ const ms = phases.reduce((a, p) => a + p.ms, 0);
9
+ let t = start;
10
+ const spans = [span(`root${wave}`, null, start, ms, { "terragucci.stage": "tf-apply", "terragucci.wave": wave })];
11
+ for (const p of phases) {
12
+ spans.push(span(`${p.phase}${wave}`, `root${wave}`, t, p.ms, { "terragucci.phase": p.phase, ...(p.held ? { "terragucci.gate.held_seconds": p.held } : {}) }));
13
+ t += p.ms;
14
+ }
15
+ return { wave, job, start, ms, spans };
16
+ };
17
+
18
+ describe("wave traces: whose trace is it", () => {
19
+ it("keeps each wave's newest trace across the cycle's runs, a resumed run's job applying several waves", () => {
20
+ const merge = { run: "4855", traces: [trace(1, 1000, [{ phase: "plan", ms: 400 }]), trace(2, 2000, [{ phase: "plan", ms: 300 }])] };
21
+ const resume = { run: "4856", traces: [trace(2, 9000, [{ phase: "plan", ms: 200 }], "apply-comment")] };
22
+ const w = waveTraces([merge, resume, { error: "no tempo" }, null]);
23
+ expect(Object.keys(w)).toEqual(["1", "2"]);
24
+ expect(w[1]).toMatchObject({ run: "4855", job: "apply-wave-1" });
25
+ expect(w[2]).toMatchObject({ run: "4856", job: "apply-comment" });
26
+ });
27
+ });
28
+
29
+ describe("wave traces: the phases", () => {
30
+ it("lays the stage's phases out in time, and splits a gate's hold from its check", () => {
31
+ const t = trace(2, 0, [{ phase: "plan", ms: 1000 }, { phase: "gate", ms: 26_000, held: 25 }, { phase: "apply", ms: 2000 }, { phase: "report", ms: 500 }, { phase: "upload", ms: 500 }]);
32
+ const bars = phaseBars(t);
33
+ expect(bars.map((b) => [b.phase, b.ms, b.wait])).toEqual([["plan", 1000, false], ["held", 25_000, true], ["gate", 1000, false], ["apply", 2000, false], ["report", 500, false], ["upload", 500, false]]);
34
+ expect(bars[1].at).toBeCloseTo(1000 / 30_000);
35
+ expect(bars.reduce((a, b) => a + b.width, 0)).toBeCloseTo(1);
36
+ expect(bars.map(phaseWords)).toEqual(["plan 1 s", "held 25 s for an approval", "gate 1 s", "apply 2 s", "report 500 ms", "upload 500 ms"]);
37
+ expect(phaseBars({ spans: [] })).toEqual([]);
38
+ });
39
+
40
+ it("says what a trace shows: the hold when an approval held the wave, else its longest phase", () => {
41
+ expect(traceReadyWords(2, trace(2, 0, [{ phase: "plan", ms: 1200 }, { phase: "apply", ms: 400 }]))).toBe("wave 2's trace is ready; it took 1.6 s, 1.2 s of it in the plan");
42
+ expect(traceReadyWords(2, trace(2, 0, [{ phase: "plan", ms: 1000 }, { phase: "gate", ms: 26_000, held: 25 }]))).toBe("wave 2's trace is ready; it took 27 s, 25 s of it held for an approval");
43
+ expect(traceReadyWords(2, null)).toBeNull();
44
+ expect([msShort(70), msShort(1600), msShort(48_400), msShort(125_000)]).toEqual(["70 ms", "1.6 s", "48 s", "2 min 5 s"]);
45
+ });
46
+
47
+ it("gives the applied card one row per wave that has a trace, and none for one that hasn't", () => {
48
+ const w = waveTraces([{ run: "1", traces: [trace(3, 0, [{ phase: "apply", ms: 900 }]), trace(1, 0, [{ phase: "plan", ms: 300 }])] }]);
49
+ const rows = miniWaterfall(w);
50
+ expect(rows.map((r) => [r.wave, r.words, r.bars.length])).toEqual([[1, "300 ms", 1], [3, "900 ms", 1]]);
51
+ expect(miniWaterfall({})).toEqual([]);
52
+ });
53
+ });