TheYuchen commited on
Commit
ecfb151
·
1 Parent(s): 3089d9e

Theater overlay comparison (theater-overlay) + scenario F7

Browse files

New figure capability: when two archived runs share a config_hash and
both persisted per-batch traces, the Compare tab offers "overlay in
theater" — the evidence theater renders BOTH runs' funnels on one axis
pair (run A accent/blue, run B warn/amber, envelopes at .07 alpha,
constant ∓3.5px x-dodge on the shared batch grid, per-run stop
annotations in stacked top-band rows, a shared target corridor only
when both runs executed the same rule, per-run id+seed legend in the
context strip). The visual argument: the stopping rule is
deterministic, the draws are not — "two replays of one configuration —
same rule, different draws". The trace scrubber drives both series in
lockstep (scrubSeries clamps per series). Store: theaterOverlayIds;
closing the theater or starting a new run exits overlay mode; deleting
either record mid-view exits instead of rendering a stale pair. Figure
export takes the true-SVG path as evidence-theater-overlay_<slug>.svg
with both run_ids/root_seeds in the provenance (runsForView branch).
Scenario F7 (?scenario=F7): deterministic picker over the bundled
archive (largest traced budget with >=2 ok replicates = bell-2048),
A = 0b485ca23b88 (983/2048, 48.00% +/-2.16pp, seed 1892016523),
B = ca3a5193e0f1 (1032/2048, 50.39% +/-2.16pp, seed 2072686634);
expected visuals documented at the scenario definition.

frontend/src/components/CompareView.tsx CHANGED
@@ -12,7 +12,7 @@
12
  // is not evidence when both intervals span the difference.
13
 
14
  import { useEffect, useState } from "react";
15
- import { X } from "lucide-react";
16
  import type { StepResult } from "../lib/api";
17
  import { useApp } from "../lib/store";
18
  import { getRun, type RunRecord } from "../lib/runStore";
@@ -91,6 +91,18 @@ function CompareRow({
91
  );
92
  }
93
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  function fidelityStep(r: RunRecord): StepResult | undefined {
95
  for (let i = r.response.steps.length - 1; i >= 0; i--) {
96
  const s = r.response.steps[i];
@@ -167,6 +179,7 @@ function ciOf(s: StepResult | undefined): [number, number] | null {
167
  export function CompareView() {
168
  const compareIds = useApp((s) => s.compareIds);
169
  const clearCompare = useApp((s) => s.clearCompare);
 
170
  // historyVersion: a selected run can be DELETED from the archive
171
  // while it is being compared. The bump re-runs the lookup below, and
172
  // the missing-record branch clears the stale pair — without this the
@@ -273,6 +286,24 @@ export function CompareView() {
273
  {diffs.length} setting{diffs.length === 1 ? "" : "s"} differ
274
  </span>
275
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
276
  <button
277
  type="button"
278
  className="ml-auto p-0.5 text-mute hover:text-ink rounded hover:bg-surfaceAlt"
 
12
  // is not evidence when both intervals span the difference.
13
 
14
  import { useEffect, useState } from "react";
15
+ import { Presentation, X } from "lucide-react";
16
  import type { StepResult } from "../lib/api";
17
  import { useApp } from "../lib/store";
18
  import { getRun, type RunRecord } from "../lib/runStore";
 
91
  );
92
  }
93
 
94
+ /** Does the record carry at least one sampled per-batch trace? The
95
+ * theater overlay needs the funnel data, not just a final interval. */
96
+ function hasSampledTrace(r: RunRecord): boolean {
97
+ return r.response.steps.some((st) => {
98
+ const d = st.distribution as
99
+ | { kind?: string; trace?: unknown[] }
100
+ | null
101
+ | undefined;
102
+ return d?.kind === "binomial" && Array.isArray(d.trace) && d.trace.length > 0;
103
+ });
104
+ }
105
+
106
  function fidelityStep(r: RunRecord): StepResult | undefined {
107
  for (let i = r.response.steps.length - 1; i >= 0; i--) {
108
  const s = r.response.steps[i];
 
179
  export function CompareView() {
180
  const compareIds = useApp((s) => s.compareIds);
181
  const clearCompare = useApp((s) => s.clearCompare);
182
+ const setTheaterOverlay = useApp((s) => s.setTheaterOverlay);
183
  // historyVersion: a selected run can be DELETED from the archive
184
  // while it is being compared. The bump re-runs the lookup below, and
185
  // the missing-record branch clears the stale pair — without this the
 
286
  {diffs.length} setting{diffs.length === 1 ? "" : "s"} differ
287
  </span>
288
  )}
289
+ {/* Theater overlay (marker: theater-overlay): only offered when
290
+ the pair is genuinely overlayable — same configuration (so
291
+ "one rule, two draws" is a true statement) AND both runs
292
+ persisted a per-batch trace (the funnel data). */}
293
+ {A.config_hash === B.config_hash &&
294
+ hasSampledTrace(A) &&
295
+ hasSampledTrace(B) && (
296
+ <button
297
+ type="button"
298
+ data-marker="theater-overlay"
299
+ className="chip !border-accent/50 !text-accent hover:bg-accent/10 flex items-center gap-1"
300
+ title="Open the evidence theater with both runs' shot-batch funnels overlaid on one axis pair — two replays of one configuration, same rule, different draws."
301
+ onClick={() => setTheaterOverlay([A.run_id, B.run_id])}
302
+ >
303
+ <Presentation className="w-3 h-3" />
304
+ overlay in theater ↗
305
+ </button>
306
+ )}
307
  <button
308
  type="button"
309
  className="ml-auto p-0.5 text-mute hover:text-ink rounded hover:bg-surfaceAlt"
frontend/src/components/EvidenceTheater.tsx CHANGED
@@ -89,7 +89,7 @@ import {
89
  useApp,
90
  type TheaterFrame,
91
  } from "../lib/store";
92
- import { listRunsByConfig } from "../lib/runStore";
93
  import {
94
  poolEvidence,
95
  runEvidence,
@@ -245,6 +245,18 @@ function scrubSeries(s: Series, k: number): Series {
245
  };
246
  }
247
 
 
 
 
 
 
 
 
 
 
 
 
 
248
  // ---------------------------------------------------------------------------
249
  // formatting + scales
250
  // ---------------------------------------------------------------------------
@@ -672,6 +684,291 @@ function Panel({
672
  );
673
  }
674
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
675
  // ---------------------------------------------------------------------------
676
  // the theater
677
  // ---------------------------------------------------------------------------
@@ -685,6 +982,8 @@ export function EvidenceTheater() {
685
  const circuit = useApp((st) => st.circuit);
686
  const sampleKey = useApp((st) => st.sampleKey);
687
  const setTheaterOpen = useApp((st) => st.setTheaterOpen);
 
 
688
  // Archive changes (a run archived elsewhere, a record deleted from
689
  // History) must refresh the pooled prior-evidence band below — the
690
  // created_at < startedAt cutoff keeps the streaming run's own
@@ -721,24 +1020,78 @@ export function EvidenceTheater() {
721
  return out;
722
  }, [run, running, theaterTraces, storeTarget, timesTrusted]);
723
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
724
  // Trace scrubbing (filmstrip support). Only when the trace is fully
725
  // known — every series done, nothing streaming — so the live-run
726
- // path is untouched. null = final state.
 
 
 
727
  const [scrub, setScrub] = useState<number | null>(null);
728
- const canScrub =
729
- !running && series.length > 0 && series.every((sr) => sr.done);
730
- const maxB = series.reduce((m, sr) => Math.max(m, sr.frames.length), 0);
 
 
 
 
 
 
731
  const cur = scrub == null ? maxB : Math.min(scrub, maxB);
732
  useEffect(() => {
733
- // A new run (or a restored one) gets a fresh, unscrubbed theater.
 
734
  setScrub(null);
735
- }, [run?.run_id, running]);
736
  const shown = useMemo(
737
  () =>
738
- canScrub && scrub != null
739
  ? series.map((sr) => scrubSeries(sr, scrub))
740
  : series,
741
- [series, scrub, canScrub],
 
 
 
 
 
 
 
 
 
 
742
  );
743
 
744
  // Pooled archive evidence for this configuration, restricted to
@@ -774,15 +1127,25 @@ export function EvidenceTheater() {
774
  // eslint-disable-next-line react-hooks/exhaustive-deps
775
  }, [theaterRun?.configHash, theaterRun?.startedAt, theaterRun?.runId, timesTrusted, historyVersion]);
776
 
777
- const configHash = timesTrusted ? theaterRun?.configHash ?? null : null;
778
- const rootSeed = timesTrusted
779
- ? theaterRun?.rootSeed ?? run?.root_seed ?? null
780
- : run?.root_seed ?? null;
 
 
 
 
 
 
781
 
782
- const panelH = series.length > 1 ? 250 : 460;
783
- const headH = 34;
784
- const svgH = headH + Math.max(1, series.length) * panelH;
785
- const circuitLabel = sampleKey ?? circuit?.name ?? "circuit";
 
 
 
 
786
 
787
  return (
788
  <div
@@ -803,6 +1166,14 @@ export function EvidenceTheater() {
803
  streaming
804
  </span>
805
  )}
 
 
 
 
 
 
 
 
806
  <div className="flex-1" />
807
  <label
808
  className="flex items-center gap-1.5 text-[11px] text-mute cursor-pointer select-none"
@@ -820,7 +1191,7 @@ export function EvidenceTheater() {
820
  </label>
821
  <FigureExportButton
822
  getTarget={() => svgRef.current}
823
- name="evidence-theater"
824
  view="evidence-theater"
825
  getTracePosition={() =>
826
  canScrub && scrub != null && cur < maxB ? cur : null
@@ -904,20 +1275,36 @@ export function EvidenceTheater() {
904
  </div>
905
  )}
906
 
907
- {series.length === 0 ? (
908
  <div className="flex-1 flex items-center justify-center p-8">
909
  <div className="max-w-md text-center space-y-2">
910
  <div className="text-sm text-ink font-medium">
911
- {running
912
- ? "Waiting for the first shot batch…"
913
- : "No sampled evidence to stage yet"}
914
- </div>
915
- <div className="text-xs text-mute">
916
- Run a pipeline with a <em>sampled</em> fidelity step and every
917
- shot batch will land here as it happens — the 95% interval
918
- narrows live, and a precision target (toolbar: “target ±pp”)
919
- lets the run stop itself once the evidence is tight enough.
920
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
921
  </div>
922
  </div>
923
  ) : (
@@ -937,9 +1324,26 @@ export function EvidenceTheater() {
937
  <text x={M.l} y={20} fontSize={12} fill="rgb(var(--color-ink))">
938
  <tspan fontWeight={600}>{circuitLabel}</tspan>
939
  <tspan fill="rgb(var(--color-mute))">
940
- {" · anytime evidence — every shot batch redraws the 95% interval"}
 
 
941
  </tspan>
942
  </text>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
943
  {configHash && (
944
  <g>
945
  <circle cx={W - M.r + 16} cy={16} r={4} fill={hueCss(hashHue(configHash), 0.9)}>
@@ -958,16 +1362,25 @@ export function EvidenceTheater() {
958
  </text>
959
  )}
960
  </g>
961
- {shown.map((s, i) => (
962
- <Panel
963
- key={s.nodeId}
964
- s={s}
965
- pool={shown.length === 1 && pool ? pool.p : null}
966
- poolRuns={pool?.n ?? 0}
967
- top={headH + i * panelH}
968
- height={panelH}
969
- />
970
- ))}
 
 
 
 
 
 
 
 
 
971
  </svg>
972
  </div>
973
  )}
 
89
  useApp,
90
  type TheaterFrame,
91
  } from "../lib/store";
92
+ import { getRun, listRunsByConfig, type RunRecord } from "../lib/runStore";
93
  import {
94
  poolEvidence,
95
  runEvidence,
 
245
  };
246
  }
247
 
248
+ /** First sampled-with-trace series of an archived record — the
249
+ * overlay comparison stages ONE funnel per run. Multi-sampled-node
250
+ * pipelines overlay their first sampled step only (paired panels
251
+ * would be the honest extension if a case study ever needs it). */
252
+ function firstSampledSeries(rec: RunRecord): Series | null {
253
+ for (const step of rec.response.steps) {
254
+ const sr = seriesFromStep(step, undefined, false);
255
+ if (sr) return sr;
256
+ }
257
+ return null;
258
+ }
259
+
260
  // ---------------------------------------------------------------------------
261
  // formatting + scales
262
  // ---------------------------------------------------------------------------
 
684
  );
685
  }
686
 
687
+ // ---------------------------------------------------------------------------
688
+ // overlay comparison panel (marker: theater-overlay)
689
+ // ---------------------------------------------------------------------------
690
+ //
691
+ // Two archived runs of ONE configuration on a single axis pair — the
692
+ // visual argument that the stopping RULE is deterministic while the
693
+ // DRAWS are not: both funnels narrow on the same 1/√n schedule, land
694
+ // inside each other's intervals (or visibly don't), and any early
695
+ // stop is that run's own draw meeting the shared rule.
696
+ //
697
+ // Encoding deltas vs the single-run Panel (everything else reuses its
698
+ // vocabulary — same axes, same interval/envelope/point marks):
699
+ // * run A = accent/blue, run B = warn/amber; hue is doubled by the
700
+ // A/B legend and per-mark tooltips, and the two series never rely
701
+ // on hue alone (they are also x-dodged, see next).
702
+ // * both runs share the batch grid (same configuration ⇒ same batch
703
+ // plan), so coincident intervals would overprint; each series is
704
+ // x-dodged by a constant ∓3.5 px — sub-batch-width, identical for
705
+ // every batch, so shapes and convergence rates compare honestly.
706
+ // * envelopes drop to opacity .07 (two overlapping .1 fills would
707
+ // read as a third hue).
708
+ // * shared y domain = union of both runs' single-run domains — the
709
+ // overlay never zooms tighter than either run would alone.
710
+ // * target corridor only when BOTH runs executed the SAME rule,
711
+ // anchored at the midpoint of the two final points (the corridor
712
+ // states the rule's width; per-run anchoring would draw two
713
+ // nearly-coincident dashed pairs and imply two rules).
714
+ // * stop annotations dodge into stacked top-band rows (A above B)
715
+ // instead of the single-run flip logic.
716
+ function OverlayPanel({
717
+ a,
718
+ b,
719
+ top,
720
+ height,
721
+ }: {
722
+ a: Series;
723
+ b: Series;
724
+ top: number;
725
+ height: number;
726
+ }) {
727
+ const plotW = W - M.l - M.r;
728
+ const plotH = height - M.t - M.b;
729
+ const shotsRequested = Math.max(a.shotsRequested, b.shotsRequested);
730
+ const sharedTarget =
731
+ a.precisionTarget != null && a.precisionTarget === b.precisionTarget
732
+ ? a.precisionTarget
733
+ : null;
734
+ const [aLo, aHi] = yDomain(a.frames, sharedTarget, null);
735
+ const [bLo, bHi] = yDomain(b.frames, sharedTarget, null);
736
+ const dLo = Math.min(aLo, bLo);
737
+ const dHi = Math.max(aHi, bHi);
738
+ const x = (shots: number) =>
739
+ M.l + (Math.min(shots, shotsRequested) / Math.max(1, shotsRequested)) * plotW;
740
+ const y = (v: number) => M.t + (1 - (v - dLo) / (dHi - dLo)) * plotH;
741
+ const axisY = M.t + plotH;
742
+ const lastA = a.frames[a.frames.length - 1];
743
+ const lastB = b.frames[b.frames.length - 1];
744
+
745
+ const step = tickStep(dHi - dLo);
746
+ const gridVals: number[] = [];
747
+ for (let v = Math.ceil(dLo / step) * step; v <= dHi + 1e-9; v += step)
748
+ gridVals.push(v);
749
+
750
+ const COLORS = {
751
+ A: "rgb(var(--color-accent))",
752
+ B: "rgb(var(--color-warn))",
753
+ } as const;
754
+
755
+ // Right-margin readout column: A final, B final, shared-target tag —
756
+ // same dodge contract as the single-run Panel.
757
+ const midFinal = (lastA.point + lastB.point) / 2;
758
+ const anyStop = a.stoppedEarly || b.stoppedEarly;
759
+ const bandTop = M.t + (anyStop ? 66 : 8);
760
+ const blocks: Array<{ anchor: number; h: number }> = [
761
+ { anchor: y(lastA.point) + 3, h: 26 },
762
+ { anchor: y(lastB.point) + 3, h: 26 },
763
+ ];
764
+ if (sharedTarget != null)
765
+ blocks.push({ anchor: y(midFinal + sharedTarget) + 3, h: 10 });
766
+ const dodged = dodgeMarginLabels(blocks, bandTop, axisY - 2);
767
+
768
+ // Union of both runs' batch ticks (identical grids collapse; an
769
+ // early-stopped run simply contributes a prefix).
770
+ const tickShots = [
771
+ ...new Set([...a.frames, ...b.frames].map((f) => f.shots)),
772
+ ].sort((p2, q) => p2 - q);
773
+ const maxShown = Math.max(lastA.shots, lastB.shots);
774
+
775
+ const seriesMarks = (s2: Series, key: "A" | "B", dx: number) => {
776
+ const color = COLORS[key];
777
+ const env2 =
778
+ s2.frames.map((f) => `${x(f.shots) + dx},${y(f.hi)}`).join(" ") +
779
+ " " +
780
+ [...s2.frames]
781
+ .reverse()
782
+ .map((f) => `${x(f.shots) + dx},${y(f.lo)}`)
783
+ .join(" ");
784
+ return (
785
+ <g>
786
+ {s2.frames.length > 1 && (
787
+ <polygon points={env2} fill={color} opacity={0.07} />
788
+ )}
789
+ {s2.frames.map((f, i) => (
790
+ <line
791
+ key={f.shots}
792
+ x1={x(f.shots) + dx}
793
+ x2={x(f.shots) + dx}
794
+ y1={y(f.hi)}
795
+ y2={y(f.lo)}
796
+ stroke={color}
797
+ strokeWidth={2.5}
798
+ strokeLinecap="round"
799
+ opacity={0.35 + (0.55 * (i + 1)) / s2.frames.length}
800
+ >
801
+ <title>
802
+ {`run ${key}, 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)})`}
803
+ </title>
804
+ </line>
805
+ ))}
806
+ {s2.frames.length > 1 && (
807
+ <polyline
808
+ points={s2.frames
809
+ .map((f) => `${x(f.shots) + dx},${y(f.point)}`)
810
+ .join(" ")}
811
+ fill="none"
812
+ stroke={color}
813
+ strokeWidth={1}
814
+ opacity={0.6}
815
+ />
816
+ )}
817
+ {s2.frames.map((f, i) => (
818
+ <circle
819
+ key={f.shots}
820
+ cx={x(f.shots) + dx}
821
+ cy={y(f.point)}
822
+ r={i === s2.frames.length - 1 ? 3.5 : 2.2}
823
+ fill={color}
824
+ />
825
+ ))}
826
+ </g>
827
+ );
828
+ };
829
+
830
+ const stopAnnotation = (s2: Series, key: "A" | "B", row: number) => {
831
+ if (!s2.stoppedEarly || s2.shotsExecuted == null) return null;
832
+ const sx = x(s2.shotsExecuted);
833
+ const ty = M.t + 12 + row * 30;
834
+ return (
835
+ <g>
836
+ <line
837
+ x1={sx}
838
+ x2={sx}
839
+ y1={M.t - 4}
840
+ y2={axisY}
841
+ stroke={COLORS[key]}
842
+ strokeWidth={1.5}
843
+ strokeDasharray="5 3"
844
+ />
845
+ <text
846
+ x={sx - 8}
847
+ textAnchor="end"
848
+ y={ty}
849
+ fontSize={11}
850
+ fontWeight={600}
851
+ fill={COLORS[key]}
852
+ >
853
+ ⏹ {key} stopped at {fmtShots(s2.shotsExecuted)} of {fmtShots(s2.shotsRequested)} shots
854
+ <title>{GLOSSARY.precisionTarget}</title>
855
+ </text>
856
+ </g>
857
+ );
858
+ };
859
+
860
+ const readout = (s2: Series, key: "A" | "B", labelY: number) => {
861
+ const last2 = s2.frames[s2.frames.length - 1];
862
+ const half2 = (last2.hi - last2.lo) / 2;
863
+ return (
864
+ <text x={W - M.r + 10} y={labelY} fontSize={11} fontWeight={600} fill={COLORS[key]}>
865
+ <tspan x={W - M.r + 10}>
866
+ {key} {s2.done ? "final" : "so far"}: {fmtPct(last2.point, 2)} ±{fmtPp(half2, 2)}
867
+ </tspan>
868
+ <tspan x={W - M.r + 10} dy={13} fontWeight={400} fill="rgb(var(--color-mute))">
869
+ {s2.successes != null
870
+ ? `${fmtShots(s2.successes)}/${fmtShots(s2.shotsExecuted ?? last2.shots)} ideal`
871
+ : ""}
872
+ </tspan>
873
+ <title>{GLOSSARY.ci}</title>
874
+ </text>
875
+ );
876
+ };
877
+
878
+ const spent = (s2: Series) =>
879
+ `${fmtShots(s2.shotsExecuted ?? s2.frames[s2.frames.length - 1].shots)}${
880
+ s2.shotsRequested > (s2.shotsExecuted ?? 0) && s2.stoppedEarly
881
+ ? ` of ${fmtShots(s2.shotsRequested)}`
882
+ : ""
883
+ } shots${s2.serverSeconds != null ? ` · ${s2.serverSeconds.toFixed(1)} s` : ""}`;
884
+
885
+ return (
886
+ <g
887
+ transform={`translate(0 ${top})`}
888
+ role="img"
889
+ data-marker="theater-overlay"
890
+ aria-label={`overlaid evidence funnels of two runs of one configuration: run A ${fmtPct(lastA.point, 2)}, run B ${fmtPct(lastB.point, 2)}`}
891
+ >
892
+ <text x={M.l} y={22} fontSize={14} fontWeight={600} fill="rgb(var(--color-ink))">
893
+ {a.label}
894
+ <title>{GLOSSARY.fidelity}</title>
895
+ </text>
896
+ <text x={M.l} y={22} dx={8 * a.label.length + 14} fontSize={11} fill="rgb(var(--color-mute))">
897
+ overlay — A {fmtPct(lastA.point, 2)} ±{fmtPp((lastA.hi - lastA.lo) / 2, 2)} · B {fmtPct(lastB.point, 2)} ±{fmtPp((lastB.hi - lastB.lo) / 2, 2)}
898
+ </text>
899
+
900
+ {/* y grid + labels */}
901
+ {gridVals.map((v) => (
902
+ <g key={v}>
903
+ <line x1={M.l} x2={M.l + plotW} y1={y(v)} y2={y(v)} stroke="rgb(var(--color-edge))" strokeWidth={1} opacity={0.6} />
904
+ <text x={M.l - 8} y={y(v) + 3} fontSize={10} textAnchor="end" fill="rgb(var(--color-mute))">
905
+ {fmtPct(v, step < 0.01 ? 1 : 0)}
906
+ </text>
907
+ </g>
908
+ ))}
909
+ <text
910
+ transform={`translate(${M.l - 46} ${M.t + plotH / 2}) rotate(-90)`}
911
+ fontSize={11}
912
+ textAnchor="middle"
913
+ fill="rgb(var(--color-mute))"
914
+ >
915
+ fidelity estimate
916
+ <title>{GLOSSARY.fidelity}</title>
917
+ </text>
918
+
919
+ {/* shared target corridor: only when both runs executed the SAME rule */}
920
+ {sharedTarget != null && (
921
+ <g>
922
+ {[midFinal - sharedTarget, midFinal + sharedTarget]
923
+ .filter((v) => v >= dLo && v <= dHi)
924
+ .map((v, i) => (
925
+ <line key={i} x1={M.l} x2={M.l + plotW} y1={y(v)} y2={y(v)} stroke="rgb(var(--color-ink))" strokeWidth={1.2} strokeDasharray="7 4" opacity={0.45} />
926
+ ))}
927
+ <text x={W - M.r + 10} y={dodged[2]} fontSize={10} fill="rgb(var(--color-ink))" opacity={0.8}>
928
+ target ±{fmtPp(sharedTarget, 1)} (both runs)
929
+ <title>{GLOSSARY.precisionTarget}</title>
930
+ </text>
931
+ </g>
932
+ )}
933
+
934
+ {/* the two funnels, constant ∓3.5px x-dodge (see module comment) */}
935
+ {seriesMarks(a, "A", -3.5)}
936
+ {seriesMarks(b, "B", 3.5)}
937
+ {stopAnnotation(a, "A", 0)}
938
+ {stopAnnotation(b, "B", a.stoppedEarly ? 1 : 0)}
939
+
940
+ {/* final readouts, dodged into the right-margin column */}
941
+ {readout(a, "A", dodged[0])}
942
+ {readout(b, "B", dodged[1])}
943
+
944
+ {/* x axis */}
945
+ <line x1={M.l} x2={M.l + plotW} y1={axisY} y2={axisY} stroke="rgb(var(--color-mute))" strokeWidth={1} />
946
+ {tickShots.map((sh) => (
947
+ <g key={sh}>
948
+ <line x1={x(sh)} x2={x(sh)} y1={axisY} y2={axisY + 4} stroke="rgb(var(--color-mute))" strokeWidth={1} />
949
+ <text x={x(sh)} y={axisY + 15} fontSize={9.5} textAnchor="middle" fill="rgb(var(--color-mute))">
950
+ {fmtShots(sh)}
951
+ </text>
952
+ </g>
953
+ ))}
954
+ {maxShown < shotsRequested && (
955
+ <g>
956
+ <line x1={x(shotsRequested)} x2={x(shotsRequested)} y1={axisY} y2={axisY + 4} stroke="rgb(var(--color-mute))" strokeWidth={1} opacity={0.6} />
957
+ <text x={x(shotsRequested)} y={axisY + 15} fontSize={9.5} textAnchor="middle" fill="rgb(var(--color-mute))" opacity={0.7}>
958
+ {fmtShots(shotsRequested)}
959
+ </text>
960
+ </g>
961
+ )}
962
+ <text x={M.l + plotW / 2} y={axisY + 30} fontSize={11} textAnchor="middle" fill="rgb(var(--color-mute))">
963
+ shots executed (evidence bought) →<title>{GLOSSARY.shots}</title>
964
+ </text>
965
+ <text x={M.l} y={axisY + 45} fontSize={10.5} fontWeight={600} fill="rgb(var(--color-ink))">
966
+ evidence spent — A: {spent(a)} · B: {spent(b)}
967
+ </text>
968
+ </g>
969
+ );
970
+ }
971
+
972
  // ---------------------------------------------------------------------------
973
  // the theater
974
  // ---------------------------------------------------------------------------
 
982
  const circuit = useApp((st) => st.circuit);
983
  const sampleKey = useApp((st) => st.sampleKey);
984
  const setTheaterOpen = useApp((st) => st.setTheaterOpen);
985
+ const overlayIds = useApp((st) => st.theaterOverlayIds);
986
+ const setTheaterOverlay = useApp((st) => st.setTheaterOverlay);
987
  // Archive changes (a run archived elsewhere, a record deleted from
988
  // History) must refresh the pooled prior-evidence band below — the
989
  // created_at < startedAt cutoff keeps the streaming run's own
 
1020
  return out;
1021
  }, [run, running, theaterTraces, storeTarget, timesTrusted]);
1022
 
1023
+ // Overlay comparison mode (marker: theater-overlay): two archived
1024
+ // runs of one configuration, loaded fresh from the archive on every
1025
+ // historyVersion bump (either record can be deleted mid-view — the
1026
+ // overlay then exits instead of rendering a stale pair).
1027
+ const [overlayRecs, setOverlayRecs] = useState<
1028
+ [RunRecord, RunRecord] | null
1029
+ >(null);
1030
+ useEffect(() => {
1031
+ if (!overlayIds) {
1032
+ setOverlayRecs(null);
1033
+ return;
1034
+ }
1035
+ let cancelled = false;
1036
+ Promise.all([getRun(overlayIds[0]), getRun(overlayIds[1])])
1037
+ .then(([ra, rb]) => {
1038
+ if (cancelled) return;
1039
+ if (ra && rb) setOverlayRecs([ra, rb]);
1040
+ else setTheaterOverlay(null);
1041
+ })
1042
+ .catch(() => {
1043
+ if (!cancelled) setTheaterOverlay(null);
1044
+ });
1045
+ return () => {
1046
+ cancelled = true;
1047
+ };
1048
+ }, [overlayIds, historyVersion, setTheaterOverlay]);
1049
+ const overlayActive = overlayIds != null;
1050
+ const overlayPair = useMemo(() => {
1051
+ if (!overlayRecs) return null;
1052
+ const a = firstSampledSeries(overlayRecs[0]);
1053
+ const b = firstSampledSeries(overlayRecs[1]);
1054
+ return a && b ? { a, b } : null;
1055
+ }, [overlayRecs]);
1056
+
1057
  // Trace scrubbing (filmstrip support). Only when the trace is fully
1058
  // known — every series done, nothing streaming — so the live-run
1059
+ // path is untouched. null = final state. In overlay mode the traces
1060
+ // are archived by construction, and one scrub position drives BOTH
1061
+ // series in lockstep (scrubSeries clamps per series, so a pair with
1062
+ // different executed-batch counts stays valid at every k).
1063
  const [scrub, setScrub] = useState<number | null>(null);
1064
+ const canScrub = overlayActive
1065
+ ? overlayPair != null
1066
+ : !running && series.length > 0 && series.every((sr) => sr.done);
1067
+ const maxB = overlayActive
1068
+ ? Math.max(
1069
+ overlayPair?.a.frames.length ?? 0,
1070
+ overlayPair?.b.frames.length ?? 0,
1071
+ )
1072
+ : series.reduce((m, sr) => Math.max(m, sr.frames.length), 0);
1073
  const cur = scrub == null ? maxB : Math.min(scrub, maxB);
1074
  useEffect(() => {
1075
+ // A new run (or a restored one, or a new overlay pair) gets a
1076
+ // fresh, unscrubbed theater.
1077
  setScrub(null);
1078
+ }, [run?.run_id, running, overlayIds]);
1079
  const shown = useMemo(
1080
  () =>
1081
+ canScrub && scrub != null && !overlayActive
1082
  ? series.map((sr) => scrubSeries(sr, scrub))
1083
  : series,
1084
+ [series, scrub, canScrub, overlayActive],
1085
+ );
1086
+ const shownOverlay = useMemo(
1087
+ () =>
1088
+ overlayPair && scrub != null
1089
+ ? {
1090
+ a: scrubSeries(overlayPair.a, scrub),
1091
+ b: scrubSeries(overlayPair.b, scrub),
1092
+ }
1093
+ : overlayPair,
1094
+ [overlayPair, scrub],
1095
  );
1096
 
1097
  // Pooled archive evidence for this configuration, restricted to
 
1127
  // eslint-disable-next-line react-hooks/exhaustive-deps
1128
  }, [theaterRun?.configHash, theaterRun?.startedAt, theaterRun?.runId, timesTrusted, historyVersion]);
1129
 
1130
+ const configHash = overlayActive
1131
+ ? overlayRecs?.[0].config_hash ?? null
1132
+ : timesTrusted
1133
+ ? theaterRun?.configHash ?? null
1134
+ : null;
1135
+ const rootSeed = overlayActive
1136
+ ? null // overlay legend names both seeds per run instead
1137
+ : timesTrusted
1138
+ ? theaterRun?.rootSeed ?? run?.root_seed ?? null
1139
+ : run?.root_seed ?? null;
1140
 
1141
+ const panelH = overlayActive ? 460 : series.length > 1 ? 250 : 460;
1142
+ // Overlay header carries a second line (the per-run A/B legend).
1143
+ const headH = overlayActive ? 52 : 34;
1144
+ const svgH = headH + (overlayActive ? 1 : Math.max(1, series.length)) * panelH;
1145
+ const circuitLabel = overlayActive
1146
+ ? overlayRecs?.[0].sample_key ?? overlayRecs?.[0].circuit_name ?? "circuit"
1147
+ : sampleKey ?? circuit?.name ?? "circuit";
1148
+ const hasContent = overlayActive ? shownOverlay != null : series.length > 0;
1149
 
1150
  return (
1151
  <div
 
1166
  streaming
1167
  </span>
1168
  )}
1169
+ {overlayActive && (
1170
+ <span
1171
+ className="chip !border-warn/50 !text-warn"
1172
+ title="Comparing two archived replays of one configuration, overlaid on one axis pair. Close the theater (or start a new run) to exit."
1173
+ >
1174
+ overlay comparison
1175
+ </span>
1176
+ )}
1177
  <div className="flex-1" />
1178
  <label
1179
  className="flex items-center gap-1.5 text-[11px] text-mute cursor-pointer select-none"
 
1191
  </label>
1192
  <FigureExportButton
1193
  getTarget={() => svgRef.current}
1194
+ name={overlayActive ? "evidence-theater-overlay" : "evidence-theater"}
1195
  view="evidence-theater"
1196
  getTracePosition={() =>
1197
  canScrub && scrub != null && cur < maxB ? cur : null
 
1275
  </div>
1276
  )}
1277
 
1278
+ {!hasContent ? (
1279
  <div className="flex-1 flex items-center justify-center p-8">
1280
  <div className="max-w-md text-center space-y-2">
1281
  <div className="text-sm text-ink font-medium">
1282
+ {overlayActive
1283
+ ? overlayRecs == null
1284
+ ? "Loading the two runs…"
1285
+ : "These runs carry no sampled per-batch trace to overlay"
1286
+ : running
1287
+ ? "Waiting for the first shot batch…"
1288
+ : "No sampled evidence to stage yet"}
 
 
1289
  </div>
1290
+ {overlayActive ? (
1291
+ overlayRecs != null && (
1292
+ <button
1293
+ type="button"
1294
+ className="btn"
1295
+ onClick={() => setTheaterOverlay(null)}
1296
+ >
1297
+ exit overlay
1298
+ </button>
1299
+ )
1300
+ ) : (
1301
+ <div className="text-xs text-mute">
1302
+ Run a pipeline with a <em>sampled</em> fidelity step and every
1303
+ shot batch will land here as it happens — the 95% interval
1304
+ narrows live, and a precision target (toolbar: “target ±pp”)
1305
+ lets the run stop itself once the evidence is tight enough.
1306
+ </div>
1307
+ )}
1308
  </div>
1309
  </div>
1310
  ) : (
 
1324
  <text x={M.l} y={20} fontSize={12} fill="rgb(var(--color-ink))">
1325
  <tspan fontWeight={600}>{circuitLabel}</tspan>
1326
  <tspan fill="rgb(var(--color-mute))">
1327
+ {overlayActive
1328
+ ? " · two replays of one configuration — same rule, different draws"
1329
+ : " · anytime evidence — every shot batch redraws the 95% interval"}
1330
  </tspan>
1331
  </text>
1332
+ {overlayActive && overlayRecs && (
1333
+ /* per-run legend: hue keyed to the funnels below; run ids
1334
+ + seeds make the figure self-identifying (which two
1335
+ draws, replayable from which seeds) */
1336
+ <text x={M.l} y={40} fontSize={11} fontFamily="ui-monospace, monospace">
1337
+ <tspan fill="rgb(var(--color-accent))" fontWeight={600}>
1338
+ ● A {overlayRecs[0].run_id}
1339
+ {overlayRecs[0].root_seed != null ? ` · seed ${overlayRecs[0].root_seed}` : ""}
1340
+ </tspan>
1341
+ <tspan dx={20} fill="rgb(var(--color-warn))" fontWeight={600}>
1342
+ ● B {overlayRecs[1].run_id}
1343
+ {overlayRecs[1].root_seed != null ? ` · seed ${overlayRecs[1].root_seed}` : ""}
1344
+ </tspan>
1345
+ </text>
1346
+ )}
1347
  {configHash && (
1348
  <g>
1349
  <circle cx={W - M.r + 16} cy={16} r={4} fill={hueCss(hashHue(configHash), 0.9)}>
 
1362
  </text>
1363
  )}
1364
  </g>
1365
+ {overlayActive
1366
+ ? shownOverlay && (
1367
+ <OverlayPanel
1368
+ a={shownOverlay.a}
1369
+ b={shownOverlay.b}
1370
+ top={headH}
1371
+ height={panelH}
1372
+ />
1373
+ )
1374
+ : shown.map((s, i) => (
1375
+ <Panel
1376
+ key={s.nodeId}
1377
+ s={s}
1378
+ pool={shown.length === 1 && pool ? pool.p : null}
1379
+ poolRuns={pool?.n ?? 0}
1380
+ top={headH + i * panelH}
1381
+ height={panelH}
1382
+ />
1383
+ ))}
1384
  </svg>
1385
  </div>
1386
  )}
frontend/src/lib/figureExport.ts CHANGED
@@ -94,6 +94,19 @@ async function runsForView(
94
  config_hash: r.config_hash,
95
  }));
96
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  if (view === "evidence-compare") {
98
  const all = await listRuns(500);
99
  return all
@@ -134,7 +147,7 @@ export async function collectProvenance(
134
  regenerate:
135
  "Rebuild the pipeline via '#s=' + base64url(graph) on any deployment; " +
136
  "pin a run's root_seed to replay its draws bit-exactly; " +
137
- "?scenario=F0..F6 boots the paper's scripted figure states.",
138
  };
139
  }
140
 
 
94
  config_hash: r.config_hash,
95
  }));
96
  }
97
+ if (view === "evidence-theater" && st.theaterOverlayIds) {
98
+ // Theater in overlay-comparison mode: the two staged archived
99
+ // runs, not the store's current run.
100
+ const ids = st.theaterOverlayIds;
101
+ const all = await listRuns(500);
102
+ return all
103
+ .filter((r) => ids.includes(r.run_id))
104
+ .map((r) => ({
105
+ run_id: r.run_id,
106
+ root_seed: r.root_seed,
107
+ config_hash: r.config_hash,
108
+ }));
109
+ }
110
  if (view === "evidence-compare") {
111
  const all = await listRuns(500);
112
  return all
 
147
  regenerate:
148
  "Rebuild the pipeline via '#s=' + base64url(graph) on any deployment; " +
149
  "pin a run's root_seed to replay its draws bit-exactly; " +
150
+ "?scenario=F0..F7 boots the paper's scripted figure states.",
151
  };
152
  }
153
 
frontend/src/lib/scenarios.ts CHANGED
@@ -136,6 +136,9 @@ export interface Scenario {
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> = {
@@ -273,6 +276,36 @@ export const SCENARIOS: Record<string, Scenario> = {
273
  needsArchive: true,
274
  compareTopConfigs: true,
275
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
276
  };
277
 
278
  // -- activation --------------------------------------------------------------
@@ -307,6 +340,49 @@ async function pickTopTwoRunIds(): Promise<string[]> {
307
  return groups.slice(0, 2).map((g) => g.latestOk.run_id);
308
  }
309
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
310
  /**
311
  * Activate a scenario by key (case-insensitive). Returns false for
312
  * unknown keys so the caller can fall through to normal boot.
@@ -338,6 +414,16 @@ export async function activateScenario(rawKey: string): Promise<boolean> {
338
  if (ids.length === 2) useApp.setState({ compareIds: ids });
339
  }
340
 
 
 
 
 
 
 
 
 
 
 
341
  if (sc.evidenceTab) app.setPendingEvidenceTab(sc.evidenceTab);
342
  if (sc.expandEvidence) app.bumpHintExpandRightPane();
343
  return true;
 
136
  * renders from the persisted trace, so it must be opened
137
  * explicitly). */
138
  openTheater?: boolean;
139
+ /** F7: stage two same-configuration archived runs in the theater's
140
+ * overlay-comparison mode (marker: theater-overlay). */
141
+ overlayPair?: boolean;
142
  }
143
 
144
  export const SCENARIOS: Record<string, Scenario> = {
 
276
  needsArchive: true,
277
  compareTopConfigs: true,
278
  },
279
+ // F7 — theater overlay comparison: two archived replays of ONE
280
+ // configuration on one axis pair ("same rule, different draws").
281
+ // The deterministic picker below lands on the bundled archive's
282
+ // bell-state 2048-shot config (the largest traced budget with ≥2
283
+ // replicates) and takes its two most recent runs:
284
+ // A = run 0b485ca23b88 (seed 1892016523): 983/2048 ideal, point
285
+ // 48.00% ±2.16pp, 8 batches ±6.08pp → ±2.16pp;
286
+ // B = run ca3a5193e0f1 (seed 2072686634): 1032/2048 ideal, point
287
+ // 50.39% ±2.16pp, 8 batches ±6.06pp → ±2.16pp.
288
+ // Expected visuals: blue (A) and amber (B) funnels on the shared
289
+ // 256-shot batch grid (x-dodged ∓3.5 px), envelopes at low alpha
290
+ // crossing through each other's intervals, per-run id+seed legend
291
+ // in the context strip, final readouts dodged in the right margin
292
+ // (A 48.00%, B 50.39% — final intervals overlap: consistent with
293
+ // one underlying configuration), Compare tab open behind the
294
+ // theater with the "overlay in theater" chip visible. No target
295
+ // corridor (these archive runs executed their full budget with no
296
+ // stopping rule). Scrubbing to batch k truncates BOTH funnels in
297
+ // lockstep. Export: evidence-theater-overlay_F7.svg (true-SVG,
298
+ // AI-editable), provenance carries both run_ids + root_seeds.
299
+ F7: {
300
+ key: "F7",
301
+ expect:
302
+ "Theater overlay: two bell-2048 replays on one axis pair — A 983/2048 (48.00% ±2.16pp, seed 1892016523) vs B 1032/2048 (50.39% ±2.16pp, seed 2072686634); overlapping funnels, per-run legend, lockstep scrubber.",
303
+ workspaceMode: "compose",
304
+ evidenceTab: "compare",
305
+ expandEvidence: true,
306
+ needsArchive: true,
307
+ overlayPair: true,
308
+ },
309
  };
310
 
311
  // -- activation --------------------------------------------------------------
 
340
  return groups.slice(0, 2).map((g) => g.latestOk.run_id);
341
  }
342
 
343
+ /** F7: two archived replays of ONE configuration, both carrying
344
+ * per-batch traces — deterministic over the bundled archive: among
345
+ * config groups with ≥2 ok traced runs, pick the group with the
346
+ * largest requested shot budget (bell-2048 in the bundled archive),
347
+ * then its two most recent runs, older one as A. */
348
+ async function pickOverlayPairRunIds(): Promise<string[]> {
349
+ const runs = await listRuns(500);
350
+ const tracedBudget = (r: (typeof runs)[number]): number => {
351
+ let req = 0;
352
+ for (const st of r.response.steps) {
353
+ const d = st.distribution as
354
+ | { kind?: string; trace?: unknown[]; shots_requested?: number; shots?: number }
355
+ | null
356
+ | undefined;
357
+ if (d?.kind === "binomial" && Array.isArray(d.trace) && d.trace.length > 0)
358
+ req = Math.max(req, d.shots_requested ?? d.shots ?? 0);
359
+ }
360
+ return req;
361
+ };
362
+ const byHash = new Map<string, Array<{ r: (typeof runs)[number]; req: number }>>();
363
+ for (const r of runs) {
364
+ if (!r.ok) continue;
365
+ const req = tracedBudget(r);
366
+ if (req === 0) continue;
367
+ const arr = byHash.get(r.config_hash) ?? [];
368
+ arr.push({ r, req });
369
+ byHash.set(r.config_hash, arr);
370
+ }
371
+ const groups = [...byHash.values()].filter((g) => g.length >= 2);
372
+ groups.sort(
373
+ (a, b) =>
374
+ Math.max(...b.map((x) => x.req)) - Math.max(...a.map((x) => x.req)),
375
+ );
376
+ const g = groups[0];
377
+ if (!g) return [];
378
+ const latestTwo = g
379
+ .map((x) => x.r)
380
+ .sort((a, b) => b.created_at - a.created_at)
381
+ .slice(0, 2)
382
+ .sort((a, b) => a.created_at - b.created_at); // A = the older one
383
+ return latestTwo.map((r) => r.run_id);
384
+ }
385
+
386
  /**
387
  * Activate a scenario by key (case-insensitive). Returns false for
388
  * unknown keys so the caller can fall through to normal boot.
 
414
  if (ids.length === 2) useApp.setState({ compareIds: ids });
415
  }
416
 
417
+ if (sc.overlayPair) {
418
+ const ids = await pickOverlayPairRunIds();
419
+ if (ids.length === 2) {
420
+ // Compare tab shows the pair (with the overlay chip); the
421
+ // theater opens on top in overlay-comparison mode.
422
+ useApp.setState({ compareIds: ids });
423
+ app.setTheaterOverlay([ids[0], ids[1]]);
424
+ }
425
+ }
426
+
427
  if (sc.evidenceTab) app.setPendingEvidenceTab(sc.evidenceTab);
428
  if (sc.expandEvidence) app.bumpHintExpandRightPane();
429
  return true;
frontend/src/lib/store.ts CHANGED
@@ -128,6 +128,16 @@ interface AppState {
128
  */
129
  theaterOpen: boolean;
130
  setTheaterOpen: (v: boolean) => void;
 
 
 
 
 
 
 
 
 
 
131
  theaterTraces: Record<string, TheaterFrame[]>;
132
  theaterRun: {
133
  configHash: string | null;
@@ -334,13 +344,24 @@ export const useApp = create<AppState>((set) => ({
334
  }),
335
  clearLiveProgress: () => set({ liveProgress: null }),
336
  theaterOpen: false,
337
- setTheaterOpen: (v) => set({ theaterOpen: v }),
 
 
 
 
 
 
 
 
 
338
  theaterTraces: {},
339
  theaterRun: null,
340
  beginTheaterRun: (configHash) =>
341
  set({
342
  theaterTraces: {},
343
  liveProgress: null,
 
 
344
  theaterRun: {
345
  configHash,
346
  startedAt: Date.now(),
 
128
  */
129
  theaterOpen: boolean;
130
  setTheaterOpen: (v: boolean) => void;
131
+ /**
132
+ * Theater overlay comparison (marker: theater-overlay). When two
133
+ * archived runs of the SAME configuration both carry sampled traces,
134
+ * the Compare tab can stage them in the theater overlaid on one
135
+ * axis pair — two replays of one rule, different draws. Non-null
136
+ * switches the theater to comparison mode (and opens it); closing
137
+ * the theater or starting a new run clears it.
138
+ */
139
+ theaterOverlayIds: [string, string] | null;
140
+ setTheaterOverlay: (ids: [string, string] | null) => void;
141
  theaterTraces: Record<string, TheaterFrame[]>;
142
  theaterRun: {
143
  configHash: string | null;
 
344
  }),
345
  clearLiveProgress: () => set({ liveProgress: null }),
346
  theaterOpen: false,
347
+ // Closing the theater also exits overlay mode: reopening from the
348
+ // toolbar should show the current run's stage, not a stale pair.
349
+ setTheaterOpen: (v) =>
350
+ set({
351
+ theaterOpen: v,
352
+ ...(v ? {} : { theaterOverlayIds: null }),
353
+ }),
354
+ theaterOverlayIds: null,
355
+ setTheaterOverlay: (ids) =>
356
+ set({ theaterOverlayIds: ids, ...(ids ? { theaterOpen: true } : {}) }),
357
  theaterTraces: {},
358
  theaterRun: null,
359
  beginTheaterRun: (configHash) =>
360
  set({
361
  theaterTraces: {},
362
  liveProgress: null,
363
+ // A new run reclaims the stage — live streaming beats a replayed pair.
364
+ theaterOverlayIds: null,
365
  theaterRun: {
366
  configHash,
367
  startedAt: Date.now(),