TheYuchen commited on
Commit
f686793
·
1 Parent(s): e52951c

Evidence Theater: steering becomes the visual protagonist (+F0 teaser)

Browse files

The system's most novel contribution -- anytime evidence steering
(streaming CI narrowing + optional stopping, Wave I) -- was the
smallest element on screen. New EvidenceTheater overlay (auto-opens on
the first step_progress frame, dismissable, localStorage auto-open
pref, toolbar + fidelity-card reopen affordances): one big SVG funnel
per sampled node -- per-batch Wilson CIs on a linear shots axis with
convergence envelope, first-interval-anchored auto-zoom, dashed target
corridor + early-stop annotation with unspent-shots region, client-
timed cost row (caveat commented) with server-total fallback, and a
context strip (config hue chip, live root-seed via new runStream
onMeta hook, pooled prior-evidence archive band). Store retains per-
node stamped traces until the next run so the theater outlives the
step; true-SVG figure export with embedded provenance.

Scenario F0 (the teaser): bell_state on FakeFez, 4096 shots, sampled
fidelity, target +/-2pp, pinned seed 2026 (probed live: all candidate
seeds stop at 2560/4096; 2026 has the smoothest point path, max
inter-batch jump 0.34pp; result 1240/2560, point 0.484375,
+/-1.934pp), auto-run with the theater booted open.

tsc + both builds clean; 80 backend tests green.

docs/EVIDENCE_WORKBENCH.md CHANGED
@@ -403,7 +403,8 @@ here. Reviewers are vis people, not quantum people. Status per item:
403
  itself: rebuild the graph from the payload, pin the recorded
404
  seed, replay.
405
  3. **Scenario loader — shipped** (`lib/scenarios.ts`; boot hook in
406
- App.tsx). `?scenario=F1..F6`: F1 ribbon canvas post-run (QuCAD on
 
407
  vqc_2q_small, seed 336157917, auto-run), F2 multiverse board over
408
  the bundled archive, F3 evidence funnel with ±2pp optional stop
409
  (bell_state, 4096 shots, seed 424242, auto-run, early stop
@@ -501,3 +502,94 @@ lineage, statistical honesty, anonymity, encoding disclosures) found
501
  auth client block in api.ts, the pendingQuickStart store bridge +
502
  FlowCanvas consumer (its TrySlide producer died in Wave P), and
503
  stale tour comments.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
403
  itself: rebuild the graph from the payload, pin the recorded
404
  seed, replay.
405
  3. **Scenario loader — shipped** (`lib/scenarios.ts`; boot hook in
406
+ App.tsx). `?scenario=F0..F6` (F0 added with the Evidence Theater
407
+ wave, see its own section below): F1 ribbon canvas post-run (QuCAD on
408
  vqc_2q_small, seed 336157917, auto-run), F2 multiverse board over
409
  the bundled archive, F3 evidence funnel with ±2pp optional stop
410
  (bell_state, 4096 shots, seed 424242, auto-run, early stop
 
502
  auth client block in api.ts, the pendingQuickStart store bridge +
503
  FlowCanvas consumer (its TrySlide producer died in Wave P), and
504
  stale tour comments.
505
+
506
+ ## Evidence Theater (teaser view) — shipped 2026-07-05
507
+
508
+ Diagnosis: anytime evidence steering (Wave I) is the system's most
509
+ novel contribution, yet visually it was the SMALLEST element on
510
+ screen — a thin funnel strip inside a side-panel card, a 3-px live
511
+ band on a node face — while ordinary views owned the pixels. The
512
+ theater makes steering the visual protagonist: a dedicated, large,
513
+ self-explanatory view (`components/EvidenceTheater.tsx`, marker/class
514
+ `evidence-theater`) that the paper's teaser figure and the demo video
515
+ open with.
516
+
517
+ Mechanics: overlay over the center column (same pattern as the
518
+ Multiverse board, z-30 above its z-20 so it also works from the
519
+ board), auto-opens on the FIRST `step_progress` frame of a run —
520
+ i.e. the moment a sampled step starts streaming — dismissable, with a
521
+ "don't auto-open" preference persisted in localStorage
522
+ (`quda.theaterAutoOpen`, toggled inside the theater) and a toolbar
523
+ Theater button (marker `evidence-theater-open`) plus an "open
524
+ theater ↗" affordance on the fidelity card's uncertainty block to
525
+ reopen it. The store retains per-node progress frames WITH client
526
+ arrival timestamps (`theaterTraces`) from run start until the next
527
+ run starts, so the theater keeps the full live trace (including
528
+ timing) after the step completes; `theaterRun` records the streaming
529
+ run's config hash (computed at Run-click) and its run_id/root_seed
530
+ (delivered live by a new `onMeta` hook on `api.runStream`, fired on
531
+ the stream's opening run_meta event).
532
+
533
+ Encoding rationale (full version in the component's module comment):
534
+
535
+ * **X = shots executed, 0 → shots_requested, linear.** Shots are the
536
+ costly resource; evidence bought reads as horizontal distance, and
537
+ an early stop leaves visibly unspent axis (lightly tinted region +
538
+ "N shots not spent") — the reward for steering stated in the cost
539
+ currency. Batch-index or log axes would hide exactly that.
540
+ * **Y = fidelity estimate, auto-zoomed** to the first batch's point ±
541
+ 3× its half-width (extended to cover every interval, the target
542
+ corridor and the archive band; clamped [0,1]). The cards' fixed 0-1
543
+ scale is right for cross-run comparison but wrong for the
544
+ protagonist view (a ±2pp target is ~4 px there). Anchoring the zoom
545
+ on the FIRST interval keeps the axis stable while frames stream.
546
+ * **Funnel = per-batch Wilson CIs as vertical intervals** at their
547
+ cumulative-shots x (opacity ramping toward now), connected by a
548
+ shaded convergence envelope + a thin point-estimate path. Live runs
549
+ grow it frame by frame; archived/replayed runs render the identical
550
+ drawing instantly from the persisted `distribution.trace` — the
551
+ trace IS provenance, so the figure never depends on having watched
552
+ the run.
553
+ * **Target corridor** = two dashed warn-colored lines at point ±
554
+ target with an early-stop vertical annotation ("⏹ stopped here —
555
+ target reached at N of M shots"); with no target set, a ghost line
556
+ of copy points at the toolbar affordance.
557
+ * **Cost axis** = secondary tick row under the X axis with the
558
+ wall-clock gap between consecutive batch arrivals (CLIENT-side
559
+ Date.now() at SSE arrival — server compute + network jitter, honest
560
+ as a price tag, not a benchmark; first batch unlabeled because its
561
+ gap includes worker spin-up), plus "evidence spent: N shots · T s"
562
+ (total prefers the server's own step duration once the step
563
+ completes).
564
+ * **Context strip** (inside the SVG so exports carry it): circuit
565
+ label, config-hash chip (archive hue), root-seed chip — live from
566
+ run_meta — and the pooled archive band: the Wilson interval this
567
+ exact configuration has ALREADY accumulated (runs archived before
568
+ this run started; pooling valid per lib/stats.ts; drawn only for
569
+ single-sampled-node runs because `runEvidence` pools a whole run's
570
+ counts). The streaming run visibly adds to a body of evidence.
571
+ * **Color**: accent/blue solid = this run's evidence; warn/amber
572
+ dashed = the stopping rule; accent4/green filled band = archived
573
+ evidence. Every hue doubled by a mark-type difference (colorblind
574
+ safety). Multiple sampled nodes stack as ~250-px small multiples
575
+ (scroll past 3).
576
+
577
+ The whole chart is ONE `<svg>` (context header included), so the
578
+ figure-export camera on the theater takes the TRUE-SVG path: vector
579
+ output with the provenance `<metadata>` embedded, correct under the
580
+ forced-light paper transform. Export view key: `evidence-theater`.
581
+
582
+ **F0 — the teaser scenario** (`?scenario=F0`): bell_state on FakeFez,
583
+ 4096 requested shots (8×512 batches), sampled fidelity, target ±2pp,
584
+ seed pinned to **2026**, auto-run with the theater booted open (the
585
+ explicit open matters: a pinned replay can be served from cache with
586
+ no progress frames, in which case the theater renders from the
587
+ persisted trace). Seed choice, probed live 2026-07-05: at bell's
588
+ p≈0.47-0.50 the width trajectory is effectively seed-independent
589
+ (±4.31 → ±1.93pp over batches 1→5) so every candidate stops at 2,560
590
+ of 4,096 shots; candidates differed only in point-path jitter — seed
591
+ 7: 1.01pp max inter-batch jump, 42: 1.17pp, 99: 1.33pp, 31415: 2.93pp
592
+ (jagged), 2026: **0.34pp** (path 0.4902, 0.4893, 0.4909, 0.4878,
593
+ 0.4844 — a clean symmetric convergence). Pinned result: 1240/2560
594
+ ideal, point 0.484375, final half-width ±1.934pp ≤ ±2pp, 1,536 shots
595
+ unspent. The F0 theater export is the intended teaser figure.
frontend/src/App.tsx CHANGED
@@ -12,6 +12,7 @@ import { NodePalette } from "./components/NodePalette";
12
  import { FlowCanvas } from "./components/FlowCanvas";
13
  import { ResultsPane } from "./components/ResultsPane";
14
  import { MultiverseBoard } from "./components/MultiverseBoard";
 
15
  import { CircuitPicker } from "./components/CircuitPicker";
16
  import { MobileDrawer } from "./components/MobileDrawer";
17
  import { activateScenario } from "./lib/scenarios";
@@ -68,6 +69,7 @@ export default function App() {
68
  const setHealth = useApp((s) => s.setHealth);
69
  const running = useApp((s) => s.running);
70
  const workspaceMode = useApp((s) => s.workspaceMode);
 
71
  const [ready, setReady] = useState(false);
72
  const isDesktop = useIsDesktop();
73
 
@@ -329,6 +331,16 @@ export default function App() {
329
  <MultiverseBoard />
330
  </div>
331
  )}
 
 
 
 
 
 
 
 
 
 
332
  </main>
333
  {!rightCollapsed && (
334
  <PaneResizer
@@ -387,6 +399,16 @@ export default function App() {
387
  <MultiverseBoard />
388
  </div>
389
  )}
 
 
 
 
 
 
 
 
 
 
390
  </main>
391
  <MobileDrawer
392
  open={leftDrawerOpen}
 
12
  import { FlowCanvas } from "./components/FlowCanvas";
13
  import { ResultsPane } from "./components/ResultsPane";
14
  import { MultiverseBoard } from "./components/MultiverseBoard";
15
+ import { EvidenceTheater } from "./components/EvidenceTheater";
16
  import { CircuitPicker } from "./components/CircuitPicker";
17
  import { MobileDrawer } from "./components/MobileDrawer";
18
  import { activateScenario } from "./lib/scenarios";
 
69
  const setHealth = useApp((s) => s.setHealth);
70
  const running = useApp((s) => s.running);
71
  const workspaceMode = useApp((s) => s.workspaceMode);
72
+ const theaterOpen = useApp((s) => s.theaterOpen);
73
  const [ready, setReady] = useState(false);
74
  const isDesktop = useIsDesktop();
75
 
 
331
  <MultiverseBoard />
332
  </div>
333
  )}
334
+ {/* Evidence theater: the steering view, overlaid above BOTH
335
+ the canvas and the multiverse board (z-30 > z-20) —
336
+ auto-opens on the first progress frame of a streaming
337
+ sampled step; the canvas stays mounted underneath so the
338
+ run keeps streaming into it. */}
339
+ {theaterOpen && (
340
+ <div className="absolute inset-0 z-30 bg-canvas flex flex-col min-h-0">
341
+ <EvidenceTheater />
342
+ </div>
343
+ )}
344
  </main>
345
  {!rightCollapsed && (
346
  <PaneResizer
 
399
  <MultiverseBoard />
400
  </div>
401
  )}
402
+ {/* Evidence theater: the steering view, overlaid above BOTH
403
+ the canvas and the multiverse board (z-30 > z-20) —
404
+ auto-opens on the first progress frame of a streaming
405
+ sampled step; the canvas stays mounted underneath so the
406
+ run keeps streaming into it. */}
407
+ {theaterOpen && (
408
+ <div className="absolute inset-0 z-30 bg-canvas flex flex-col min-h-0">
409
+ <EvidenceTheater />
410
+ </div>
411
+ )}
412
  </main>
413
  <MobileDrawer
414
  open={leftDrawerOpen}
frontend/src/components/EvidenceTheater.tsx ADDED
@@ -0,0 +1,723 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Evidence theater — the steering view, promoted to protagonist.
2
+ //
3
+ // Diagnosis this view fixes: anytime evidence steering (streaming CI
4
+ // narrowing + optional stopping, Wave I) is the system's most novel
5
+ // contribution, yet it lived as a thin strip inside a side-panel card
6
+ // while ordinary views owned the screen. The theater gives steering a
7
+ // dedicated, large, self-explanatory stage: it auto-opens the moment a
8
+ // sampled step starts streaming (first step_progress frame), overlays
9
+ // the center column (same overlay pattern as the Multiverse board),
10
+ // and is the view a paper teaser figure / demo video opens with
11
+ // (?scenario=F0 boots straight into it).
12
+ //
13
+ // Encoding rationale (each choice justified by the steering task):
14
+ // * X = shots executed, 0 → shots_requested, LINEAR. Shots are the
15
+ // costly resource being spent; a linear shot axis makes "evidence
16
+ // bought" read as horizontal distance, and an early stop leaves
17
+ // visibly UNSPENT axis — the whole point of steering. (A batch-
18
+ // index axis would hide cost; a log axis would flatter the early
19
+ // narrowing and hide that precision gets ever more expensive.)
20
+ // * Y = fidelity-estimate scale, auto-zoomed to the first batch's
21
+ // point ± 3× its half-width (clamped to [0,1], then extended to
22
+ // cover every interval, the target band and the archive band).
23
+ // The fixed 0-1 scale the cards use is right for cross-run
24
+ // comparison but wrong for the protagonist view: at 0-1 scale a
25
+ // ±2pp target is 4 pixels tall. Anchoring the zoom on the FIRST
26
+ // interval keeps the axis stable while frames stream (no
27
+ // re-zooming under the viewer's eyes) and makes the funnel's
28
+ // 3:1-ish convergence fill the panel by construction.
29
+ // * Each batch draws its Wilson CI as a vertical interval at its
30
+ // cumulative-shots x; a shaded envelope (the funnel silhouette)
31
+ // connects them; a thin line links the point estimates. Live runs
32
+ // grow the drawing frame by frame as events arrive; archived /
33
+ // replayed runs render the identical drawing instantly from the
34
+ // persisted distribution.trace — the trace IS provenance, so the
35
+ // figure never depends on having watched the run.
36
+ // * Target band = two dashed warn-colored lines at point ± target
37
+ // ("the corridor the interval must fit inside"), with the early
38
+ // stop annotated as a vertical line at the stop x plus the
39
+ // unspent-shots region lightly hatched — the reward for steering,
40
+ // stated in the cost currency (shots not spent).
41
+ // * Cost axis: a secondary tick row under the X axis with the
42
+ // wall-clock gap between consecutive batch arrivals, plus a total
43
+ // "evidence spent: N shots · T s". CAVEAT: per-batch times are
44
+ // CLIENT-SIDE ARRIVAL timestamps (Date.now() when the SSE frame
45
+ // landed) — server compute + network jitter, honest enough to
46
+ // show that shots cost time, not a benchmark. The total prefers
47
+ // the server's own step duration once the step completes. The
48
+ // first batch gets no "+Δs" label (its arrival gap includes
49
+ // worker spin-up and noise-model fetch, not marginal batch cost).
50
+ // * Context strip: which node/config/seed this is, plus the pooled
51
+ // Wilson interval this configuration has ALREADY accumulated in
52
+ // the archive (faint band + "archive: pooled ±Xpp over N shots
53
+ // from k runs") — the streaming run visibly adds to a body of
54
+ // evidence rather than starting from zero. Pooling is valid
55
+ // within one configuration (see lib/stats.ts); the band is only
56
+ // drawn on single-sampled-node runs because runEvidence pools a
57
+ // whole run's counts (a per-node split would be dishonest for
58
+ // multi-node pipelines).
59
+ // * Color: accent (blue) = this run's evidence; warn (amber,
60
+ // DASHED) = the stopping rule; accent4 (green, FILLED band) =
61
+ // archived evidence. Three hues that survive deuteranopia checks,
62
+ // and each hue is doubled by a mark-type difference (solid
63
+ // interval / dashed line / filled band) so hue is never the only
64
+ // channel.
65
+ // * Multiple sampled nodes stack as small multiples (~230px each,
66
+ // scroll past 3) — same vocabulary, one panel per node.
67
+ //
68
+ // The chart is ONE <svg> (context header included) so the figure
69
+ // export takes the TRUE-SVG path: vector output with the provenance
70
+ // <metadata> embedded, correct under the forced-light paper transform.
71
+
72
+ import { useEffect, useMemo, useRef, useState } from "react";
73
+ import { X } from "lucide-react";
74
+ import type { StepResult } from "../lib/api";
75
+ import {
76
+ setTheaterAutoOpenEnabled,
77
+ theaterAutoOpenEnabled,
78
+ useApp,
79
+ type TheaterFrame,
80
+ } from "../lib/store";
81
+ import { listRunsByConfig } from "../lib/runStore";
82
+ import {
83
+ poolEvidence,
84
+ runEvidence,
85
+ type Evidence,
86
+ type PooledEvidence,
87
+ } from "../lib/stats";
88
+ import { hashHue, hueCss } from "../lib/hues";
89
+ import { GLOSSARY } from "../lib/glossary";
90
+ import { FigureExportButton } from "./FigureExportButton";
91
+ import { TipIcon } from "./TipIcon";
92
+
93
+ // ---------------------------------------------------------------------------
94
+ // data assembly
95
+ // ---------------------------------------------------------------------------
96
+
97
+ interface Frame {
98
+ shots: number;
99
+ point: number;
100
+ lo: number;
101
+ hi: number;
102
+ /** Client arrival time (ms epoch) — null for frames reconstructed
103
+ * from a persisted trace (archived/replayed runs carry no timing). */
104
+ at: number | null;
105
+ }
106
+
107
+ interface Series {
108
+ nodeId: string;
109
+ label: string;
110
+ frames: Frame[];
111
+ shotsRequested: number;
112
+ nBatches: number;
113
+ precisionTarget: number | null;
114
+ stoppedEarly: boolean;
115
+ /** StepResult landed (vs still streaming). */
116
+ done: boolean;
117
+ /** Server-authoritative step duration in seconds, once done. */
118
+ serverSeconds: number | null;
119
+ seedUsed: number | null;
120
+ successes: number | null;
121
+ shotsExecuted: number | null;
122
+ }
123
+
124
+ interface TraceDist {
125
+ kind?: string;
126
+ shots?: number;
127
+ successes?: number;
128
+ shots_requested?: number;
129
+ stopped_early?: boolean;
130
+ precision_target?: number;
131
+ n_batches?: number;
132
+ trace?: Array<{ shots_done: number; point: number; ci95: [number, number] }>;
133
+ }
134
+
135
+ /** Merge a completed step's persisted trace with the live frames'
136
+ * client timestamps (matched by cumulative shots — bit-identical by
137
+ * the Wave-I stream-vs-eager guarantee, so a mismatch means the
138
+ * trace belongs to a different run and gets no timing). */
139
+ function seriesFromStep(
140
+ step: StepResult,
141
+ live: TheaterFrame[] | undefined,
142
+ timesTrusted: boolean,
143
+ ): Series | null {
144
+ const d = step.distribution as TraceDist | null | undefined;
145
+ if (d?.kind !== "binomial" || !Array.isArray(d.trace) || d.trace.length === 0)
146
+ return null;
147
+ const byShots = new Map<number, number>();
148
+ if (timesTrusted && live) live.forEach((f) => byShots.set(f.shots_done, f.at));
149
+ return {
150
+ nodeId: step.node_id,
151
+ label: step.label || "sampled fidelity",
152
+ frames: d.trace.map((t) => ({
153
+ shots: t.shots_done,
154
+ point: t.point,
155
+ lo: t.ci95[0],
156
+ hi: t.ci95[1],
157
+ at: byShots.get(t.shots_done) ?? null,
158
+ })),
159
+ shotsRequested: d.shots_requested ?? d.shots ?? 0,
160
+ nBatches: d.n_batches ?? d.trace.length,
161
+ precisionTarget: d.precision_target ?? null,
162
+ stoppedEarly: d.stopped_early === true,
163
+ done: true,
164
+ serverSeconds:
165
+ Number.isFinite(step.finished_at) && Number.isFinite(step.started_at)
166
+ ? Math.max(0, step.finished_at - step.started_at)
167
+ : null,
168
+ seedUsed: step.seed_used ?? null,
169
+ successes: d.successes ?? null,
170
+ shotsExecuted: d.shots ?? null,
171
+ };
172
+ }
173
+
174
+ /** A node that is streaming RIGHT NOW but has no StepResult yet:
175
+ * build the series straight from the live frames. shots_requested is
176
+ * estimated from equal-batch arithmetic until the server states it. */
177
+ function seriesFromLive(
178
+ nodeId: string,
179
+ frames: TheaterFrame[],
180
+ target: number | null,
181
+ ): Series | null {
182
+ if (frames.length === 0) return null;
183
+ const last = frames[frames.length - 1];
184
+ const est =
185
+ last.batch_i > 0
186
+ ? Math.round((last.shots_done / last.batch_i) * last.n_batches)
187
+ : last.shots_done;
188
+ return {
189
+ nodeId,
190
+ label: "sampled fidelity",
191
+ frames: frames.map((f) => ({
192
+ shots: f.shots_done,
193
+ point: f.point,
194
+ lo: f.ci95[0],
195
+ hi: f.ci95[1],
196
+ at: f.at,
197
+ })),
198
+ shotsRequested: est,
199
+ nBatches: last.n_batches,
200
+ precisionTarget: target,
201
+ stoppedEarly: false,
202
+ done: false,
203
+ serverSeconds: null,
204
+ seedUsed: null,
205
+ successes: last.successes,
206
+ shotsExecuted: last.shots_done,
207
+ };
208
+ }
209
+
210
+ // ---------------------------------------------------------------------------
211
+ // formatting + scales
212
+ // ---------------------------------------------------------------------------
213
+
214
+ const fmtShots = (n: number) => Math.round(n).toLocaleString("en-US");
215
+ const fmtPct = (v: number, dp = 1) => `${(v * 100).toFixed(dp)}%`;
216
+ const fmtPp = (v: number, dp = 1) => `${(v * 100).toFixed(dp)}pp`;
217
+
218
+ /** Y domain: first-interval anchor (point ± 3× half-width) extended
219
+ * to cover everything drawn, padded, clamped to [0,1]. Anchoring on
220
+ * the FIRST batch keeps the axis stable while later frames stream. */
221
+ function yDomain(
222
+ frames: Frame[],
223
+ target: number | null,
224
+ pool: PooledEvidence | null,
225
+ ): [number, number] {
226
+ const f0 = frames[0];
227
+ const half0 = Math.max((f0.hi - f0.lo) / 2, 0.002);
228
+ let lo = f0.point - 3 * half0;
229
+ let hi = f0.point + 3 * half0;
230
+ for (const f of frames) {
231
+ lo = Math.min(lo, f.lo);
232
+ hi = Math.max(hi, f.hi);
233
+ }
234
+ const anchor = frames[frames.length - 1].point;
235
+ if (target != null) {
236
+ lo = Math.min(lo, anchor - target * 1.6);
237
+ hi = Math.max(hi, anchor + target * 1.6);
238
+ }
239
+ if (pool) {
240
+ lo = Math.min(lo, pool.ci95[0] - half0 * 0.3);
241
+ hi = Math.max(hi, pool.ci95[1] + half0 * 0.3);
242
+ }
243
+ const pad = (hi - lo) * 0.06;
244
+ return [Math.max(0, lo - pad), Math.min(1, hi + pad)];
245
+ }
246
+
247
+ /** Percent-tick step giving 3–7 gridlines over the domain. */
248
+ function tickStep(span: number): number {
249
+ for (const s of [0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2])
250
+ if (span / s <= 7) return s;
251
+ return 0.25;
252
+ }
253
+
254
+ // ---------------------------------------------------------------------------
255
+ // one funnel panel (pure SVG subtree)
256
+ // ---------------------------------------------------------------------------
257
+
258
+ const W = 1000;
259
+ const M = { l: 66, r: 208, t: 40, b: 66 };
260
+
261
+ function Panel({
262
+ s,
263
+ pool,
264
+ poolRuns,
265
+ top,
266
+ height,
267
+ }: {
268
+ s: Series;
269
+ pool: PooledEvidence | null;
270
+ poolRuns: number;
271
+ top: number;
272
+ height: number;
273
+ }) {
274
+ const plotW = W - M.l - M.r;
275
+ const plotH = height - M.t - M.b;
276
+ const [dLo, dHi] = yDomain(s.frames, s.precisionTarget, pool);
277
+ const x = (shots: number) =>
278
+ M.l + (Math.min(shots, s.shotsRequested) / Math.max(1, s.shotsRequested)) * plotW;
279
+ const y = (v: number) => M.t + (1 - (v - dLo) / (dHi - dLo)) * plotH;
280
+ const axisY = M.t + plotH;
281
+ const last = s.frames[s.frames.length - 1];
282
+ const first = s.frames[0];
283
+ const lastHalf = (last.hi - last.lo) / 2;
284
+
285
+ // y gridlines on round percent values
286
+ const step = tickStep(dHi - dLo);
287
+ const gridVals: number[] = [];
288
+ for (let v = Math.ceil(dLo / step) * step; v <= dHi + 1e-9; v += step)
289
+ gridVals.push(v);
290
+
291
+ const env =
292
+ s.frames.map((f) => `${x(f.shots)},${y(f.hi)}`).join(" ") +
293
+ " " +
294
+ [...s.frames].reverse().map((f) => `${x(f.shots)},${y(f.lo)}`).join(" ");
295
+
296
+ // Cost row: Δt between consecutive CLIENT arrivals (see module
297
+ // comment for the caveat); first batch intentionally unlabeled.
298
+ const gaps: Array<{ xPos: number; label: string }> = [];
299
+ for (let i = 1; i < s.frames.length; i++) {
300
+ const a = s.frames[i - 1].at;
301
+ const b = s.frames[i].at;
302
+ if (a != null && b != null)
303
+ gaps.push({
304
+ xPos: x(s.frames[i].shots),
305
+ label: `+${((b - a) / 1000).toFixed(1)}s`,
306
+ });
307
+ }
308
+ const clientSpan =
309
+ first.at != null && last.at != null && s.frames.length > 1
310
+ ? (last.at - first.at) / 1000
311
+ : null;
312
+ const totalSeconds = s.serverSeconds ?? clientSpan;
313
+
314
+ const stopX = s.stoppedEarly && s.shotsExecuted != null ? x(s.shotsExecuted) : null;
315
+ const shotsSaved =
316
+ s.stoppedEarly && s.shotsExecuted != null
317
+ ? s.shotsRequested - s.shotsExecuted
318
+ : 0;
319
+
320
+ const titleBits = s.done
321
+ ? `${s.successes ?? "?"}/${fmtShots(s.shotsExecuted ?? 0)} hit the ideal outcome · point ${fmtPct(last.point, 2)} ± ${fmtPp(lastHalf, 2)}`
322
+ : `streaming — batch ${s.frames.length} of ${s.nBatches} · interval ± ${fmtPp(lastHalf, 2)} so far`;
323
+
324
+ return (
325
+ <g
326
+ transform={`translate(0 ${top})`}
327
+ role="img"
328
+ aria-label={`evidence funnel for ${s.label}: ${s.frames.length} shot batches, interval ± ${fmtPp((first.hi - first.lo) / 2, 1)} narrowing to ± ${fmtPp(lastHalf, 1)}${s.stoppedEarly ? `, stopped early at ${fmtShots(s.shotsExecuted ?? 0)} of ${fmtShots(s.shotsRequested)} shots` : ""}`}
329
+ >
330
+ {/* panel title */}
331
+ <text x={M.l} y={22} fontSize={14} fontWeight={600} fill="rgb(var(--color-ink))">
332
+ {s.label}
333
+ <title>{GLOSSARY.fidelity}</title>
334
+ </text>
335
+ <text x={M.l} y={22} dx={8 * s.label.length + 14} fontSize={11} fill="rgb(var(--color-mute))">
336
+ {titleBits}
337
+ </text>
338
+
339
+ {/* archived-evidence band (green + FILLED = different hue AND
340
+ mark than this run's blue solid intervals) */}
341
+ {pool && (
342
+ <g>
343
+ <rect
344
+ x={M.l}
345
+ y={y(pool.ci95[1])}
346
+ width={plotW}
347
+ height={Math.max(1, y(pool.ci95[0]) - y(pool.ci95[1]))}
348
+ fill="rgb(var(--color-accent4))"
349
+ opacity={0.09}
350
+ />
351
+ <line x1={M.l} x2={M.l + plotW} y1={y(pool.ci95[1])} y2={y(pool.ci95[1])} stroke="rgb(var(--color-accent4))" strokeWidth={1} strokeDasharray="2 4" opacity={0.55} />
352
+ <line x1={M.l} x2={M.l + plotW} y1={y(pool.ci95[0])} y2={y(pool.ci95[0])} stroke="rgb(var(--color-accent4))" strokeWidth={1} strokeDasharray="2 4" opacity={0.55} />
353
+ <text x={W - M.r + 10} y={y(pool.point) + 3} fontSize={10} fill="rgb(var(--color-accent4))">
354
+ <tspan x={W - M.r + 10}>archive: pooled ±{fmtPp(pool.halfWidth, 1)}</tspan>
355
+ <tspan x={W - M.r + 10} dy={12}>
356
+ over {fmtShots(pool.shots)} shots from {poolRuns} run{poolRuns === 1 ? "" : "s"}
357
+ </tspan>
358
+ <title>Evidence this exact configuration already accumulated in your run archive (pooled Wilson interval over all archived shots — valid because replicates of one configuration share the same underlying probability). The streaming run adds to this.</title>
359
+ </text>
360
+ </g>
361
+ )}
362
+
363
+ {/* y grid + labels */}
364
+ {gridVals.map((v) => (
365
+ <g key={v}>
366
+ <line x1={M.l} x2={M.l + plotW} y1={y(v)} y2={y(v)} stroke="rgb(var(--color-edge))" strokeWidth={1} opacity={0.6} />
367
+ <text x={M.l - 8} y={y(v) + 3} fontSize={10} textAnchor="end" fill="rgb(var(--color-mute))">
368
+ {fmtPct(v, step < 0.01 ? 1 : 0)}
369
+ </text>
370
+ </g>
371
+ ))}
372
+ <text
373
+ transform={`translate(${M.l - 46} ${M.t + plotH / 2}) rotate(-90)`}
374
+ fontSize={11}
375
+ textAnchor="middle"
376
+ fill="rgb(var(--color-mute))"
377
+ >
378
+ fidelity estimate
379
+ <title>{GLOSSARY.fidelity}</title>
380
+ </text>
381
+
382
+ {/* unspent budget: the visual reward for stopping early */}
383
+ {stopX != null && (
384
+ <g>
385
+ <rect x={stopX} y={M.t} width={M.l + plotW - stopX} height={plotH} fill="rgb(var(--color-mute))" opacity={0.05} />
386
+ <line x1={stopX} x2={stopX} y1={M.t - 4} y2={axisY} stroke="rgb(var(--color-warn))" strokeWidth={1.5} strokeDasharray="5 3" />
387
+ <text x={stopX + 8} y={M.t + 12} fontSize={11} fontWeight={600} fill="rgb(var(--color-warn))">
388
+ ⏹ stopped here — target reached at {fmtShots(s.shotsExecuted ?? 0)} of {fmtShots(s.shotsRequested)} shots
389
+ <title>{GLOSSARY.precisionTarget}</title>
390
+ </text>
391
+ <text x={stopX + 8} y={M.t + 26} fontSize={10} fill="rgb(var(--color-mute))">
392
+ {fmtShots(shotsSaved)} shots not spent
393
+ </text>
394
+ </g>
395
+ )}
396
+
397
+ {/* optional-stopping target corridor (amber + DASHED) */}
398
+ {s.precisionTarget != null ? (
399
+ <g>
400
+ {[last.point - s.precisionTarget, last.point + s.precisionTarget].map(
401
+ (v, i) => (
402
+ <line key={i} x1={M.l} x2={M.l + plotW} y1={y(v)} y2={y(v)} stroke="rgb(var(--color-warn))" strokeWidth={1.2} strokeDasharray="7 4" opacity={0.9} />
403
+ ),
404
+ )}
405
+ <text x={W - M.r + 10} y={y(last.point + s.precisionTarget) + 3} fontSize={10} fill="rgb(var(--color-warn))">
406
+ target ±{fmtPp(s.precisionTarget, 1)}
407
+ <title>{GLOSSARY.precisionTarget}</title>
408
+ </text>
409
+ </g>
410
+ ) : (
411
+ /* ghost affordance: the stopping rule exists even when unused */
412
+ <text x={M.l + plotW - 6} y={M.t + 14} fontSize={10} fontStyle="italic" textAnchor="end" fill="rgb(var(--color-mute))" opacity={0.85}>
413
+ no stopping target — set “target ±pp” in the toolbar and the run stops itself once the interval is this tight
414
+ <title>{GLOSSARY.precisionTarget}</title>
415
+ </text>
416
+ )}
417
+
418
+ {/* convergence envelope: the funnel silhouette */}
419
+ {s.frames.length > 1 && (
420
+ <polygon points={env} fill="rgb(var(--color-accent))" opacity={0.1} />
421
+ )}
422
+
423
+ {/* per-batch Wilson intervals (vertical), opacity ramps toward now */}
424
+ {s.frames.map((f, i) => (
425
+ <g key={f.shots}>
426
+ <line
427
+ x1={x(f.shots)}
428
+ x2={x(f.shots)}
429
+ y1={y(f.hi)}
430
+ y2={y(f.lo)}
431
+ stroke="rgb(var(--color-accent))"
432
+ strokeWidth={2.5}
433
+ strokeLinecap="round"
434
+ opacity={0.35 + (0.55 * (i + 1)) / s.frames.length}
435
+ >
436
+ <title>
437
+ {`batch ${i + 1}: after ${fmtShots(f.shots)} shots — point ${fmtPct(f.point, 2)}, 95% CI ${fmtPct(f.lo, 2)}–${fmtPct(f.hi, 2)} (±${fmtPp((f.hi - f.lo) / 2, 2)})`}
438
+ </title>
439
+ </line>
440
+ </g>
441
+ ))}
442
+
443
+ {/* point-estimate path */}
444
+ {s.frames.length > 1 && (
445
+ <polyline
446
+ points={s.frames.map((f) => `${x(f.shots)},${y(f.point)}`).join(" ")}
447
+ fill="none"
448
+ stroke="rgb(var(--color-ink))"
449
+ strokeWidth={1}
450
+ opacity={0.55}
451
+ />
452
+ )}
453
+ {s.frames.map((f, i) => (
454
+ <circle
455
+ key={f.shots}
456
+ cx={x(f.shots)}
457
+ cy={y(f.point)}
458
+ r={i === s.frames.length - 1 ? 3.5 : 2.2}
459
+ fill="rgb(var(--color-accent))"
460
+ />
461
+ ))}
462
+
463
+ {/* final-interval readout in the right margin */}
464
+ <text x={W - M.r + 10} y={y(last.point) - (pool && Math.abs(y(pool.point) - y(last.point)) < 30 ? 24 : 0) + 3} fontSize={11} fontWeight={600} fill="rgb(var(--color-accent))">
465
+ <tspan x={W - M.r + 10}>{s.done ? "final" : "so far"}: {fmtPct(last.point, 2)} ±{fmtPp(lastHalf, 2)}</tspan>
466
+ <tspan x={W - M.r + 10} dy={13} fontWeight={400} fill="rgb(var(--color-mute))">
467
+ {s.successes != null ? `${fmtShots(s.successes)}/${fmtShots(s.shotsExecuted ?? last.shots)} ideal` : ""}
468
+ </tspan>
469
+ <title>{GLOSSARY.ci}</title>
470
+ </text>
471
+
472
+ {/* x axis: shot ticks per batch + the full requested budget */}
473
+ <line x1={M.l} x2={M.l + plotW} y1={axisY} y2={axisY} stroke="rgb(var(--color-mute))" strokeWidth={1} />
474
+ {s.frames.map((f) => (
475
+ <g key={f.shots}>
476
+ <line x1={x(f.shots)} x2={x(f.shots)} y1={axisY} y2={axisY + 4} stroke="rgb(var(--color-mute))" strokeWidth={1} />
477
+ <text x={x(f.shots)} y={axisY + 15} fontSize={9.5} textAnchor="middle" fill="rgb(var(--color-mute))">
478
+ {fmtShots(f.shots)}
479
+ </text>
480
+ </g>
481
+ ))}
482
+ {last.shots < s.shotsRequested && (
483
+ <g>
484
+ <line x1={x(s.shotsRequested)} x2={x(s.shotsRequested)} y1={axisY} y2={axisY + 4} stroke="rgb(var(--color-mute))" strokeWidth={1} opacity={0.6} />
485
+ <text x={x(s.shotsRequested)} y={axisY + 15} fontSize={9.5} textAnchor="middle" fill="rgb(var(--color-mute))" opacity={0.7}>
486
+ {fmtShots(s.shotsRequested)}
487
+ </text>
488
+ </g>
489
+ )}
490
+ <text x={M.l + plotW / 2} y={axisY + 30} fontSize={11} textAnchor="middle" fill="rgb(var(--color-mute))">
491
+ shots executed (evidence bought) →<title>{GLOSSARY.shots}</title>
492
+ </text>
493
+
494
+ {/* cost row: client-arrival Δt per batch (caveat in module doc) */}
495
+ {gaps.length > 0 && (
496
+ <g>
497
+ {gaps.map((g2, i) => (
498
+ <text key={i} x={g2.xPos} y={axisY + 45} fontSize={9} textAnchor="middle" fill="rgb(var(--color-mute))" opacity={0.85}>
499
+ {g2.label}
500
+ </text>
501
+ ))}
502
+ <text x={M.l - 8} y={axisY + 45} fontSize={9} textAnchor="end" fill="rgb(var(--color-mute))" opacity={0.85}>
503
+ wall time
504
+ <title>Gap between consecutive batch arrivals in this browser — server compute plus network, measured client-side. Shots cost time; this row is the price tag, not a benchmark.</title>
505
+ </text>
506
+ </g>
507
+ )}
508
+ <text x={M.l} y={axisY + (gaps.length > 0 ? 60 : 45)} fontSize={10.5} fontWeight={600} fill="rgb(var(--color-ink))">
509
+ evidence spent: {fmtShots(s.shotsExecuted ?? last.shots)}
510
+ {s.shotsRequested > (s.shotsExecuted ?? last.shots) ? ` of ${fmtShots(s.shotsRequested)}` : ""} shots
511
+ {totalSeconds != null ? ` · ${totalSeconds.toFixed(1)} s` : ""}
512
+ </text>
513
+ </g>
514
+ );
515
+ }
516
+
517
+ // ---------------------------------------------------------------------------
518
+ // the theater
519
+ // ---------------------------------------------------------------------------
520
+
521
+ export function EvidenceTheater() {
522
+ const run = useApp((st) => st.run);
523
+ const running = useApp((st) => st.running);
524
+ const theaterTraces = useApp((st) => st.theaterTraces);
525
+ const theaterRun = useApp((st) => st.theaterRun);
526
+ const storeTarget = useApp((st) => st.precisionTarget);
527
+ const circuit = useApp((st) => st.circuit);
528
+ const sampleKey = useApp((st) => st.sampleKey);
529
+ const setTheaterOpen = useApp((st) => st.setTheaterOpen);
530
+ const svgRef = useRef<SVGSVGElement>(null);
531
+ const [autoOpenPref, setAutoOpenPref] = useState(theaterAutoOpenEnabled());
532
+
533
+ // Do the displayed run and the retained traces describe the same
534
+ // run? While streaming the partial RunResponse has no run_id yet;
535
+ // once finished it must match the run_meta the stream announced.
536
+ // A restored OLD run must not inherit another run's timings/pool.
537
+ const timesTrusted =
538
+ theaterRun != null && (run?.run_id == null || run.run_id === theaterRun.runId);
539
+
540
+ const series = useMemo(() => {
541
+ const out: Series[] = [];
542
+ const seen = new Set<string>();
543
+ for (const step of run?.steps ?? []) {
544
+ const s = seriesFromStep(step, theaterTraces[step.node_id], timesTrusted);
545
+ if (s) {
546
+ out.push(s);
547
+ seen.add(s.nodeId);
548
+ }
549
+ }
550
+ // Nodes streaming right now (no StepResult yet).
551
+ if (running) {
552
+ for (const [nodeId, frames] of Object.entries(theaterTraces)) {
553
+ if (seen.has(nodeId) || frames.length === 0) continue;
554
+ const s = seriesFromLive(nodeId, frames, storeTarget);
555
+ if (s) out.push(s);
556
+ }
557
+ }
558
+ return out;
559
+ }, [run, running, theaterTraces, storeTarget, timesTrusted]);
560
+
561
+ // Pooled archive evidence for this configuration, restricted to
562
+ // runs archived BEFORE this run started (the band is "prior
563
+ // evidence"; the new run's own record must not pool with itself).
564
+ const [pool, setPool] = useState<{ p: PooledEvidence; n: number } | null>(null);
565
+ useEffect(() => {
566
+ const ch = timesTrusted ? theaterRun?.configHash : null;
567
+ if (!ch) {
568
+ setPool(null);
569
+ return;
570
+ }
571
+ let cancelled = false;
572
+ listRunsByConfig(ch)
573
+ .then((rs) => {
574
+ if (cancelled) return;
575
+ const evs = rs
576
+ .filter(
577
+ (r) =>
578
+ r.ok &&
579
+ r.created_at < (theaterRun?.startedAt ?? 0) &&
580
+ r.run_id !== theaterRun?.runId,
581
+ )
582
+ .map((r) => runEvidence(r.response))
583
+ .filter((e): e is Evidence => e != null);
584
+ const p = evs.length > 0 ? poolEvidence(evs) : null;
585
+ setPool(p ? { p, n: evs.length } : null);
586
+ })
587
+ .catch(() => setPool(null));
588
+ return () => {
589
+ cancelled = true;
590
+ };
591
+ // eslint-disable-next-line react-hooks/exhaustive-deps
592
+ }, [theaterRun?.configHash, theaterRun?.startedAt, theaterRun?.runId, timesTrusted]);
593
+
594
+ const configHash = timesTrusted ? theaterRun?.configHash ?? null : null;
595
+ const rootSeed = timesTrusted
596
+ ? theaterRun?.rootSeed ?? run?.root_seed ?? null
597
+ : run?.root_seed ?? null;
598
+
599
+ const panelH = series.length > 1 ? 250 : 460;
600
+ const headH = 34;
601
+ const svgH = headH + Math.max(1, series.length) * panelH;
602
+ const circuitLabel = sampleKey ?? circuit?.name ?? "circuit";
603
+
604
+ return (
605
+ <div
606
+ className="evidence-theater h-full flex flex-col min-h-0"
607
+ data-marker="evidence-theater"
608
+ >
609
+ {/* chrome (never exported: buttons/inputs are stripped, and the
610
+ export target is the <svg> below anyway) */}
611
+ <div className="flex items-center gap-2 px-4 py-2 border-b border-edge shrink-0">
612
+ <span className="text-sm font-semibold text-ink">Evidence theater</span>
613
+ <TipIcon
614
+ size={13}
615
+ position="below"
616
+ hint="Watch evidence accumulate while you pay for it: each shot batch tightens the 95% interval; an optional precision target stops the run the moment the interval is tight enough. The trace is recorded per batch server-side, so archived and replayed runs draw the identical picture."
617
+ />
618
+ {running && (
619
+ <span className="chip !border-accent/50 !text-accent animate-pulse">
620
+ streaming
621
+ </span>
622
+ )}
623
+ <div className="flex-1" />
624
+ <label
625
+ className="flex items-center gap-1.5 text-[11px] text-mute cursor-pointer select-none"
626
+ title="When enabled, this view opens by itself the moment a run with a sampled step starts streaming shot batches."
627
+ >
628
+ <input
629
+ type="checkbox"
630
+ checked={autoOpenPref}
631
+ onChange={(e) => {
632
+ setAutoOpenPref(e.target.checked);
633
+ setTheaterAutoOpenEnabled(e.target.checked);
634
+ }}
635
+ />
636
+ auto-open on streaming runs
637
+ </label>
638
+ <FigureExportButton
639
+ getTarget={() => svgRef.current}
640
+ name="evidence-theater"
641
+ view="evidence-theater"
642
+ />
643
+ <button
644
+ type="button"
645
+ className="btn"
646
+ onClick={() => setTheaterOpen(false)}
647
+ aria-label="Close evidence theater"
648
+ title="Close (the toolbar’s theater button reopens it)"
649
+ >
650
+ <X className="w-3.5 h-3.5" />
651
+ </button>
652
+ </div>
653
+
654
+ {series.length === 0 ? (
655
+ <div className="flex-1 flex items-center justify-center p-8">
656
+ <div className="max-w-md text-center space-y-2">
657
+ <div className="text-sm text-ink font-medium">
658
+ {running
659
+ ? "Waiting for the first shot batch…"
660
+ : "No sampled evidence to stage yet"}
661
+ </div>
662
+ <div className="text-xs text-mute">
663
+ Run a pipeline with a <em>sampled</em> fidelity step and every
664
+ shot batch will land here as it happens — the 95% interval
665
+ narrows live, and a precision target (toolbar: “target ±pp”)
666
+ lets the run stop itself once the evidence is tight enough.
667
+ </div>
668
+ </div>
669
+ </div>
670
+ ) : (
671
+ <div className="flex-1 min-h-0 overflow-y-auto px-2 py-1">
672
+ {/* ONE svg = true-SVG figure export path. maxHeight keeps
673
+ ≤3 small multiples visible; the container scrolls. */}
674
+ <svg
675
+ ref={svgRef}
676
+ viewBox={`0 0 ${W} ${svgH}`}
677
+ width="100%"
678
+ style={{ maxWidth: 1400, display: "block", margin: "0 auto" }}
679
+ xmlns="http://www.w3.org/2000/svg"
680
+ aria-label="Evidence theater: streaming confidence-interval funnel"
681
+ >
682
+ {/* context strip (inside the svg so exports carry it) */}
683
+ <g>
684
+ <text x={M.l} y={20} fontSize={12} fill="rgb(var(--color-ink))">
685
+ <tspan fontWeight={600}>{circuitLabel}</tspan>
686
+ <tspan fill="rgb(var(--color-mute))">
687
+ {" · anytime evidence — every shot batch redraws the 95% interval"}
688
+ </tspan>
689
+ </text>
690
+ {configHash && (
691
+ <g>
692
+ <circle cx={W - M.r + 16} cy={16} r={4} fill={hueCss(hashHue(configHash), 0.9)}>
693
+ <title>{GLOSSARY.configuration}</title>
694
+ </circle>
695
+ <text x={W - M.r + 26} y={20} fontSize={11} fill="rgb(var(--color-mute))" fontFamily="ui-monospace, monospace">
696
+ {configHash}
697
+ <title>{GLOSSARY.configuration}</title>
698
+ </text>
699
+ </g>
700
+ )}
701
+ {rootSeed != null && (
702
+ <text x={W - M.r + 110} y={20} fontSize={11} fill="rgb(var(--color-mute))" fontFamily="ui-monospace, monospace">
703
+ seed {rootSeed}
704
+ <title>{GLOSSARY.seed}</title>
705
+ </text>
706
+ )}
707
+ </g>
708
+ {series.map((s, i) => (
709
+ <Panel
710
+ key={s.nodeId}
711
+ s={s}
712
+ pool={series.length === 1 && pool ? pool.p : null}
713
+ poolRuns={pool?.n ?? 0}
714
+ top={headH + i * panelH}
715
+ height={panelH}
716
+ />
717
+ ))}
718
+ </svg>
719
+ </div>
720
+ )}
721
+ </div>
722
+ );
723
+ }
frontend/src/components/FlowCanvas.tsx CHANGED
@@ -21,6 +21,7 @@ import {
21
  AlertTriangle,
22
  Box,
23
  Check,
 
24
  Code2,
25
  Link2,
26
  Loader2,
@@ -54,7 +55,12 @@ import {
54
  readHashPayload,
55
  type SharePayload,
56
  } from "../lib/share";
57
- import { buildRunRecord, listRuns, saveRun } from "../lib/runStore";
 
 
 
 
 
58
  import { GLOSSARY } from "../lib/glossary";
59
  import {
60
  estimatePipeline,
@@ -934,7 +940,18 @@ export function FlowCanvas() {
934
  setRunning(true);
935
  setRun(null);
936
  setNotice(null);
937
- useApp.getState().clearLiveProgress();
 
 
 
 
 
 
 
 
 
 
 
938
 
939
  const makeBody = () => ({
940
  circuit_id: circuit.circuit_id,
@@ -977,6 +994,14 @@ export function FlowCanvas() {
977
  // narrowing CI bar. Kept in the store (not component state)
978
  // because QNode renders far from this callback.
979
  (progress) => useApp.getState().updateLiveProgress(progress),
 
 
 
 
 
 
 
 
980
  );
981
  });
982
 
@@ -1014,6 +1039,14 @@ export function FlowCanvas() {
1014
  }
1015
  const response = await runOnce();
1016
  setRun(response);
 
 
 
 
 
 
 
 
1017
  await archive(response);
1018
  if (!response.ok) break; // don't burn replicates on a broken graph
1019
  }
@@ -1220,6 +1253,21 @@ export function FlowCanvas() {
1220
  <option value={0.02}>±2pp</option>
1221
  <option value={0.01}>±1pp</option>
1222
  </select>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1223
  {/* cost-estimate chip: what will pressing Run cost, judged
1224
  from this browser's own archived step timings. Sits next
1225
  to Run so the price tag is read together with the
 
21
  AlertTriangle,
22
  Box,
23
  Check,
24
+ Clapperboard,
25
  Code2,
26
  Link2,
27
  Loader2,
 
55
  readHashPayload,
56
  type SharePayload,
57
  } from "../lib/share";
58
+ import {
59
+ buildRunRecord,
60
+ computeConfigHash,
61
+ listRuns,
62
+ saveRun,
63
+ } from "../lib/runStore";
64
  import { GLOSSARY } from "../lib/glossary";
65
  import {
66
  estimatePipeline,
 
940
  setRunning(true);
941
  setRun(null);
942
  setNotice(null);
943
+ // Theater bookkeeping: drop the PREVIOUS run's retained traces
944
+ // (they are kept after a run ends so the theater can keep showing
945
+ // the last trace) and record the streaming run's configuration —
946
+ // the theater's context strip + archive-pool band key off it.
947
+ useApp.getState().beginTheaterRun(
948
+ computeConfigHash(
949
+ sampleKey,
950
+ circuit.name ?? null,
951
+ buildSharePayload(nodes, edges, sampleKey),
952
+ useLiveIbm,
953
+ ),
954
+ );
955
 
956
  const makeBody = () => ({
957
  circuit_id: circuit.circuit_id,
 
994
  // narrowing CI bar. Kept in the store (not component state)
995
  // because QNode renders far from this callback.
996
  (progress) => useApp.getState().updateLiveProgress(progress),
997
+ // Run identity (run_id / root_seed) arrives as the stream's
998
+ // first event — the theater shows the seed chip live, long
999
+ // before the RunResponse assembles.
1000
+ (meta) =>
1001
+ useApp.getState().setTheaterRunMeta({
1002
+ runId: meta.run_id ?? null,
1003
+ rootSeed: meta.root_seed ?? null,
1004
+ }),
1005
  );
1006
  });
1007
 
 
1039
  }
1040
  const response = await runOnce();
1041
  setRun(response);
1042
+ // Re-stamp the theater's run identity from the final response:
1043
+ // a cache-served run can complete without a run_meta stream
1044
+ // event, and the theater's context strip / archive-pool band
1045
+ // key on this matching the displayed run's id.
1046
+ useApp.getState().setTheaterRunMeta({
1047
+ runId: response.run_id ?? null,
1048
+ rootSeed: response.root_seed ?? null,
1049
+ });
1050
  await archive(response);
1051
  if (!response.ok) break; // don't burn replicates on a broken graph
1052
  }
 
1253
  <option value={0.02}>±2pp</option>
1254
  <option value={0.01}>±1pp</option>
1255
  </select>
1256
+ {/* Evidence theater reopen: the theater auto-opens when a
1257
+ sampled step starts streaming (dismissable); this button
1258
+ brings it back — also for archived/replayed runs, whose
1259
+ persisted per-batch trace renders the same funnel. */}
1260
+ <button
1261
+ type="button"
1262
+ data-marker="evidence-theater-open"
1263
+ onClick={() => useApp.getState().setTheaterOpen(true)}
1264
+ className="btn hidden md:inline-flex"
1265
+ title="Evidence theater — a large live view of the 95% interval narrowing as shot batches stream in (opens by itself when a run streams; reopen it here)"
1266
+ aria-label="Open evidence theater"
1267
+ >
1268
+ <Clapperboard className="w-3.5 h-3.5" />
1269
+ <span className="hidden lg:inline">Theater</span>
1270
+ </button>
1271
  {/* cost-estimate chip: what will pressing Run cost, judged
1272
  from this browser's own archived step timings. Sits next
1273
  to Run so the price tag is read together with the
frontend/src/components/results/cards.tsx CHANGED
@@ -446,11 +446,22 @@ function UncertaintyBlock({
446
  95% interval: {(lo * 100).toFixed(1)}–{(hi * 100).toFixed(1)}% ·{" "}
447
  {successes}/{shots} measurements hit the ideal outcome
448
  </span>
449
- {seedUsed != null && (
450
- <span className="font-mono" title="Simulator seed consumed by this draw — part of the run's provenance record.">
451
- seed {seedUsed}
452
- </span>
453
- )}
 
 
 
 
 
 
 
 
 
 
 
454
  </div>
455
  {/* Evidence funnel — the run's whole uncertainty trajectory, not
456
  just its endpoint. One thin line per shot batch, oldest at
 
446
  95% interval: {(lo * 100).toFixed(1)}–{(hi * 100).toFixed(1)}% ·{" "}
447
  {successes}/{shots} measurements hit the ideal outcome
448
  </span>
449
+ <span className="flex items-center gap-2">
450
+ {seedUsed != null && (
451
+ <span className="font-mono" title="Simulator seed consumed by this draw — part of the run's provenance record.">
452
+ seed {seedUsed}
453
+ </span>
454
+ )}
455
+ <button
456
+ type="button"
457
+ data-marker="open-theater"
458
+ className="text-accent hover:underline"
459
+ onClick={() => useApp.getState().setTheaterOpen(true)}
460
+ title="Open the evidence theater — this funnel, large: per-batch intervals on a shots axis, stopping target, cost row."
461
+ >
462
+ open theater ↗
463
+ </button>
464
+ </span>
465
  </div>
466
  {/* Evidence funnel — the run's whole uncertainty trajectory, not
467
  just its endpoint. One thin line per shot batch, oldest at
frontend/src/lib/api.ts CHANGED
@@ -325,6 +325,10 @@ export const api = {
325
  onDone: (response: RunResponse) => void,
326
  onError: (err: Error) => void,
327
  onProgress?: (progress: StepProgress) => void,
 
 
 
 
328
  ) => {
329
  try {
330
  const res = await authedFetch(`${BASE}/workflow/run-stream`, {
@@ -359,6 +363,7 @@ export const api = {
359
  // Run-level provenance envelope, sent as the first event.
360
  if (parsed.run_meta) {
361
  runMeta = parsed.run_meta as Partial<RunResponse>;
 
362
  continue;
363
  }
364
  // Anytime-evidence frame: a shot batch landed mid-step.
 
325
  onDone: (response: RunResponse) => void,
326
  onError: (err: Error) => void,
327
  onProgress?: (progress: StepProgress) => void,
328
+ /** Called as soon as the stream's opening run_meta event lands —
329
+ * hands the run's identity (run_id / root_seed) to live views
330
+ * (the evidence theater) BEFORE the run finishes. */
331
+ onMeta?: (meta: Partial<RunResponse>) => void,
332
  ) => {
333
  try {
334
  const res = await authedFetch(`${BASE}/workflow/run-stream`, {
 
363
  // Run-level provenance envelope, sent as the first event.
364
  if (parsed.run_meta) {
365
  runMeta = parsed.run_meta as Partial<RunResponse>;
366
+ onMeta?.(runMeta);
367
  continue;
368
  }
369
  // Anytime-evidence frame: a shot batch landed mid-step.
frontend/src/lib/figureExport.ts CHANGED
@@ -109,7 +109,7 @@ export async function collectProvenance(
109
  regenerate:
110
  "Rebuild the pipeline via '#s=' + base64url(graph) on any deployment; " +
111
  "pin a run's root_seed to replay its draws bit-exactly; " +
112
- "?scenario=F1..F6 boots the paper's scripted figure states.",
113
  };
114
  }
115
 
 
109
  regenerate:
110
  "Rebuild the pipeline via '#s=' + base64url(graph) on any deployment; " +
111
  "pin a run's root_seed to replay its draws bit-exactly; " +
112
+ "?scenario=F0..F6 boots the paper's scripted figure states.",
113
  };
114
  }
115
 
frontend/src/lib/scenarios.ts CHANGED
@@ -1,5 +1,6 @@
1
  // Scenario loader — scripted, seed-reproducible UI states for the
2
- // paper's figures (Wave P). One URL each: `?scenario=F3` boots the app
 
3
  // straight into the state figure F3 is captured from, so any figure
4
  // can be regenerated bit-exactly at any time (pinned seeds make the
5
  // stochastic steps replay the identical draw; archive-backed scenarios
@@ -129,9 +130,43 @@ export interface Scenario {
129
  /** F6: auto-select the two most-replicated configurations' latest
130
  * successful runs for the interval comparison. */
131
  compareTopConfigs?: boolean;
 
 
 
 
 
 
132
  }
133
 
134
  export const SCENARIOS: Record<string, Scenario> = {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  // F1 — ribbon canvas after a run: tapered ribbons (width ∝ √gates),
136
  // green shrink taper on the QuCAD edge, delta-strip glyphs on node
137
  // faces, legend chip bottom-left. Pinned seed 336157917 is the
@@ -256,6 +291,7 @@ export async function activateScenario(rawKey: string): Promise<boolean> {
256
 
257
  if (sc.needsArchive) await ensureDemoArchive({ force: true });
258
  if (sc.openGateDiff) app.setGateDiffDefaultOpen(true);
 
259
  app.setWorkspaceMode(sc.workspaceMode);
260
 
261
  if (sc.graph) {
 
1
  // Scenario loader — scripted, seed-reproducible UI states for the
2
+ // paper's figures (Wave P; F0 teaser added with the Evidence Theater
3
+ // wave). One URL each: `?scenario=F3` boots the app
4
  // straight into the state figure F3 is captured from, so any figure
5
  // can be regenerated bit-exactly at any time (pinned seeds make the
6
  // stochastic steps replay the identical draw; archive-backed scenarios
 
130
  /** F6: auto-select the two most-replicated configurations' latest
131
  * successful runs for the interval comparison. */
132
  compareTopConfigs?: boolean;
133
+ /** F0: boot with the evidence theater overlay open (it would also
134
+ * auto-open on the first progress frame, but a pinned replay can
135
+ * be served from cache with NO progress frames — the theater then
136
+ * renders from the persisted trace, so it must be opened
137
+ * explicitly). */
138
+ openTheater?: boolean;
139
  }
140
 
141
  export const SCENARIOS: Record<string, Scenario> = {
142
+ // F0 — THE TEASER: the evidence theater over an optional-stopping
143
+ // run. bell_state on FakeFez, 4096 requested shots (8 batches of
144
+ // 512), sampled fidelity, target ±2pp, seed pinned to 2026.
145
+ //
146
+ // Seed choice (probed against the live API, 2026-07-05): with
147
+ // bell_state's sampled point ≈ 0.47-0.50 on FakeFez the Wilson
148
+ // width trajectory is essentially seed-independent (±4.31pp →
149
+ // ±1.93pp over batches 1→5), so EVERY candidate stops at 2,560 of
150
+ // 4,096 shots — mid-run, at batch 5 of 8. What differs is the point
151
+ // path. Candidates: 7 (max inter-batch jump 1.01pp), 42 (1.17pp),
152
+ // 99 (1.33pp), 31415 (2.93pp — jagged), 2026 (0.34pp). Seed 2026
153
+ // wins: the point path [0.4902, 0.4893, 0.4909, 0.4878, 0.4844]
154
+ // drifts gently, so the funnel reads as a clean symmetric
155
+ // convergence rather than a random walk. Pinned result: 1240/2560
156
+ // hit the ideal outcome, point 0.484375, final half-width ±1.934pp
157
+ // ≤ the ±2pp target; 1,536 shots unspent.
158
+ F0: {
159
+ key: "F0",
160
+ expect:
161
+ "Evidence theater teaser: streaming CI funnel on bell_state, ±2pp target reached at 2,560 of 4,096 shots (seed 2026, point 0.484375), cost row + unspent budget visible.",
162
+ graph: FUNNEL_GRAPH,
163
+ sampleKey: "bell_state",
164
+ pinSeed: 2026,
165
+ precisionTarget: 0.02,
166
+ autoRun: true,
167
+ workspaceMode: "compose",
168
+ openTheater: true,
169
+ },
170
  // F1 — ribbon canvas after a run: tapered ribbons (width ∝ √gates),
171
  // green shrink taper on the QuCAD edge, delta-strip glyphs on node
172
  // faces, legend chip bottom-left. Pinned seed 336157917 is the
 
291
 
292
  if (sc.needsArchive) await ensureDemoArchive({ force: true });
293
  if (sc.openGateDiff) app.setGateDiffDefaultOpen(true);
294
+ if (sc.openTheater) app.setTheaterOpen(true);
295
  app.setWorkspaceMode(sc.workspaceMode);
296
 
297
  if (sc.graph) {
frontend/src/lib/store.ts CHANGED
@@ -13,6 +13,35 @@ import type { NodeKind } from "./nodeCatalog";
13
  import type { SharePayload } from "./share";
14
 
15
  const LS_USE_LIVE_IBM = "quda.useLiveIbm";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  function loadUseLiveIbm(): boolean {
18
  if (typeof window === "undefined") return false;
@@ -82,6 +111,35 @@ interface AppState {
82
  liveProgress: Record<string, StepProgress> | null;
83
  updateLiveProgress: (p: StepProgress) => void;
84
  clearLiveProgress: () => void;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  lastConfigHash: string | null;
86
  setLastConfigHash: (h: string | null) => void;
87
 
@@ -244,10 +302,56 @@ export const useApp = create<AppState>((set) => ({
244
  setPrecisionTarget: (v) => set({ precisionTarget: v }),
245
  liveProgress: null,
246
  updateLiveProgress: (p) =>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
  set((s) => ({
248
- liveProgress: { ...(s.liveProgress ?? {}), [p.node_id]: p },
 
 
 
 
 
 
249
  })),
250
- clearLiveProgress: () => set({ liveProgress: null }),
251
  lastConfigHash: null,
252
  setLastConfigHash: (h) => set({ lastConfigHash: h }),
253
  pendingRestore: null,
 
13
  import type { SharePayload } from "./share";
14
 
15
  const LS_USE_LIVE_IBM = "quda.useLiveIbm";
16
+ const LS_THEATER_AUTO_OPEN = "quda.theaterAutoOpen";
17
+
18
+ /** Evidence-theater auto-open preference (default ON). Read lazily on
19
+ * every progress frame instead of cached in the store so a toggle in
20
+ * one tab is honoured by the next run without a reload. */
21
+ export function theaterAutoOpenEnabled(): boolean {
22
+ if (typeof window === "undefined") return true;
23
+ try {
24
+ return window.localStorage.getItem(LS_THEATER_AUTO_OPEN) !== "0";
25
+ } catch {
26
+ return true;
27
+ }
28
+ }
29
+
30
+ export function setTheaterAutoOpenEnabled(v: boolean): void {
31
+ try {
32
+ window.localStorage.setItem(LS_THEATER_AUTO_OPEN, v ? "1" : "0");
33
+ } catch {
34
+ /* ignore */
35
+ }
36
+ }
37
+
38
+ /** One anytime-evidence progress frame plus its client arrival time.
39
+ * `at` (Date.now()) is what the theater's cost axis is built from —
40
+ * client-side arrival, not server compute time (see EvidenceTheater
41
+ * for the caveat). */
42
+ export interface TheaterFrame extends StepProgress {
43
+ at: number;
44
+ }
45
 
46
  function loadUseLiveIbm(): boolean {
47
  if (typeof window === "undefined") return false;
 
111
  liveProgress: Record<string, StepProgress> | null;
112
  updateLiveProgress: (p: StepProgress) => void;
113
  clearLiveProgress: () => void;
114
+
115
+ /**
116
+ * Evidence theater (the steering view). theaterOpen mounts the
117
+ * center-column overlay; it auto-opens on the FIRST progress frame
118
+ * of a run (i.e. the moment a sampled step starts streaming) unless
119
+ * the user disabled auto-open (localStorage, toggled inside the
120
+ * theater). theaterTraces retains EVERY progress frame per node —
121
+ * with client arrival timestamps — from run start until the NEXT
122
+ * run starts, so the theater can keep showing the full live trace
123
+ * (including its timing) after the step completes, when
124
+ * liveProgress has already been cleared. theaterRun records which
125
+ * run the traces belong to (config hash for the archive-pool band,
126
+ * run_id/root_seed from the stream's run_meta event, startedAt for
127
+ * "evidence archived before this run" cutoffs).
128
+ */
129
+ theaterOpen: boolean;
130
+ setTheaterOpen: (v: boolean) => void;
131
+ theaterTraces: Record<string, TheaterFrame[]>;
132
+ theaterRun: {
133
+ configHash: string | null;
134
+ startedAt: number;
135
+ runId: string | null;
136
+ rootSeed: number | null;
137
+ } | null;
138
+ beginTheaterRun: (configHash: string | null) => void;
139
+ setTheaterRunMeta: (m: {
140
+ runId?: string | null;
141
+ rootSeed?: number | null;
142
+ }) => void;
143
  lastConfigHash: string | null;
144
  setLastConfigHash: (h: string | null) => void;
145
 
 
302
  setPrecisionTarget: (v) => set({ precisionTarget: v }),
303
  liveProgress: null,
304
  updateLiveProgress: (p) =>
305
+ set((s) => {
306
+ const at = Date.now();
307
+ const prev = s.theaterTraces[p.node_id] ?? [];
308
+ const last = prev.length > 0 ? prev[prev.length - 1] : null;
309
+ // A batch index that fails to advance means a NEW run's first
310
+ // frame for this node (replicate loops reuse node ids without
311
+ // passing through beginTheaterRun) — restart that node's trace.
312
+ const frames =
313
+ last && p.batch_i <= last.batch_i
314
+ ? [{ ...p, at }]
315
+ : [...prev, { ...p, at }];
316
+ // Auto-open exactly once per run: on the very first frame of
317
+ // the run (theaterTraces was empty), unless the user opted out.
318
+ // After that first frame a dismissal sticks for the whole run.
319
+ const hadAny = Object.values(s.theaterTraces).some(
320
+ (f) => f.length > 0,
321
+ );
322
+ const autoOpen = !hadAny && !s.theaterOpen && theaterAutoOpenEnabled();
323
+ return {
324
+ liveProgress: { ...(s.liveProgress ?? {}), [p.node_id]: p },
325
+ theaterTraces: { ...s.theaterTraces, [p.node_id]: frames },
326
+ ...(autoOpen ? { theaterOpen: true } : {}),
327
+ };
328
+ }),
329
+ clearLiveProgress: () => set({ liveProgress: null }),
330
+ theaterOpen: false,
331
+ setTheaterOpen: (v) => set({ theaterOpen: v }),
332
+ theaterTraces: {},
333
+ theaterRun: null,
334
+ beginTheaterRun: (configHash) =>
335
+ set({
336
+ theaterTraces: {},
337
+ liveProgress: null,
338
+ theaterRun: {
339
+ configHash,
340
+ startedAt: Date.now(),
341
+ runId: null,
342
+ rootSeed: null,
343
+ },
344
+ }),
345
+ setTheaterRunMeta: (m) =>
346
  set((s) => ({
347
+ theaterRun: s.theaterRun
348
+ ? {
349
+ ...s.theaterRun,
350
+ ...(m.runId !== undefined ? { runId: m.runId } : {}),
351
+ ...(m.rootSeed !== undefined ? { rootSeed: m.rootSeed } : {}),
352
+ }
353
+ : s.theaterRun,
354
  })),
 
355
  lastConfigHash: null,
356
  setLastConfigHash: (h) => set({ lastConfigHash: h }),
357
  pendingRestore: null,