Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

studiobench: refuse the message that is still being written, and score the rest of the thread (#9575)

Daniel Han5cdeb9a73fca
diff --git a/tests/studio/studiobench/INTERFACES.md b/tests/studio/studiobench/INTERFACES.md
index 9471bce5ba8..7dfa56ae01d 100644
--- a/tests/studio/studiobench/INTERFACES.md
+++ b/tests/studio/studiobench/INTERFACES.md
@@ -498,6 +498,135 @@ id, so `r1K.base.rep0` and `r100K.base.rep0` collided: a payload carrying more t
silently overwrote one rung's rows with the other's and could pair a 1K base against a 100K
treatment.
+### A message that is still being written is refused, not scored
+
+The digest is taken at the CLOSE of an action window, which is a wall-clock offset in the film. The
+two arms are two cells run back to back against one pacer: the bytes on the wire are identical by
+construction, but each has its own send click, its own `t0` and its own paint clock. So a slot that
+lands inside a live reply digests two different points in the same stream, and the difference that
+comes back is wall clock wearing the shape of a UI change. Same family as every entry in
+`outputs/rp/INSTRUMENT-DEFECTS.md`: **measuring at a moment whose meaning is not stable across the
+things being compared.**
+
+You cannot recognise it by its size. Mid-stream Studio does not show a prefix of the finished
+reply: `parseIncompleteMarkdown` runs remend over the tail and closes the half-arrived construct,
+KaTeX renders the repaired formula and writes its parse error and character offset into a `title`,
+Shiki re-tokenises the repaired fence, and the trailing code block carries `data-incomplete`.
+Measured on the frozen corpus's streamed unit through the real remend, KaTeX and Shiki into the
+shipped `signature()`: stepping by the pacer's own 24-character chunk, **175 of 175 adjacent pairs
+differ**; at one-character resolution the signature gets SHORTER at 52 of 4,237 steps, 34 pairs of
+distinct stream positions serialise to exactly the same length with different digests, and 398
+steps move the digest not at all.
+
+So `scene/parity.js` names the in-flight messages from the app's own published state --
+assistant-ui's `data-status` on the text part, `aria-busy` on the reasoning content -- and the
+capture carries `in_flight`, `streaming`, `in_flight_unplaced`, and `digest_scaffold`: the thread
+with EVERY message replaced by a marker carrying its tag, role and position. `digest` is the
+scaffold plus the per-message rows, so comparing them separately is the same reading taken apart,
+and taken apart it can withhold one message.
+
+`analysis/parity.compare` then has three outcomes rather than two:
+
+| the settled document | the in-flight message | verdict |
+| --- | --- | --- |
+| differs | anything | `DIFFER`, localised to the settled things only. This is the case that used to be lost: the action was silenced wholesale by `UNSTABLE_ACTIONS` and a real regression elsewhere in the thread printed under "expected to vary" |
+| agrees | agrees | `MATCH`, unchanged. Two arms that landed on the same point serialised identically, which is the claim |
+| agrees | differs | `NOT COMPARABLE`. Not a pass. The claim quantifies over the whole thread and one message did not serialise identically, for a reason with no defined moment |
+
+Every message is elided from the scaffold, not only the streaming ones, because whether a message
+is in flight is a property of ONE arm at the moment ITS digest was taken and the ordinary case is
+that the arms disagree about it. Eliding all of them makes the walk identical on both sides by
+construction.
+
+`in_flight_unplaced` is the positive control and it is checked AFTER `mount_count_mismatch`: a
+reply that is running while no message publishes a streaming state means the selector hooks have
+gone quiet, and a scan that can return zero must not report "nothing was streaming" on the strength
+of never having looked. A build that drops a message while a reply runs is still a finding, because
+that reading does not depend on the stream split.
+
+It reads `dom.generating()` and NOT `dom.isRunning()`, and the two are different questions.
+`isRunning()` answers "is the composer refusing a fresh send", which every wait loop in
+`scene/actions.py` needs and which is why it accepts the Queue button: with text in the composer a
+running thread renders Queue and no Stop at all. But `ComposerRightControls` renders the same
+`aria-label="Queue message"` a second time, under `isQueueRunning && !thread.isRunning`, while a
+queued prompt waits to be dispatched and nothing whatever is generating -- reachable by one
+Cmd/Ctrl+Enter, and held for the pump's 50 ms and for 500 ms per indexing retry. Read there,
+`isRunning()` sets the control on a perfectly ordinary settled thread, `streaming_probe` refuses
+the pair before `compare()` reaches its settled digests, and `sweep/ui_parity` buckets that refusal
+as `blind` and still exits 0. So the queued-idle interval is separated from active streaming:
+`generating()` is `stopButton() || (queueButton() && !promptQueue())`, the queue surface being
+`PromptQueueStack`'s own accessible name, which is present in exactly the states that render the
+queued-idle button. The capture carries `queued_idle` so the distinction is in the record rather
+than only in the verdict. What that gives up, pinned in
+`scene/selftest/test_studiobench_queued_idle_live.py`: with a queue run holding a further prompt
+AND a reply streaming AND text in the composer, the control is not armed for that capture. It
+under-claims rather than over-claims, and probe blindness is a renamed selector, so it is global
+and the run's other captures still catch it.
+
+**A quiet scan has three causes and only one of them is a broken instrument.**
+`streamingMessages()` scans MOUNTED DOM, so it returns nothing when a windowed arm has unmounted
+the message it is writing into (which is what windowing is for, and is reachable the moment
+`scroll_during_generation` leaves the tail off screen while later slots run), and it returns nothing
+in the gap between a send being accepted and the reply's first part arriving, where the assistant
+message is mounted with zero parts and thread.tsx renders "Generating..." in place of any hook --
+`send_turn` returns the instant `isRunning()` flips, so a capture lands there twice a film. So the
+control asks for evidence of blindness rather than for silence:
+
+| the last assistant message | and | conclusion |
+| --- | --- | --- |
+| publishes parts, none running | the arm mounts the whole thread | **blind.** The row cannot be missing, so a quiet scan is the only explanation left. This is what catches a build that changed the status VALUE rather than the attribute. |
+| publishes parts, none running | the arm is windowing | not blind. The message being written may not be the last one mounted, and nothing here can tell that from a changed value. |
+| publishes nothing | some other assistant message does | not blind. It has no parts yet, which is ordinary. |
+| publishes nothing | no assistant message does | **blind.** `data-status` is one line in markdown-text.tsx, rendered for `complete` parts too, so a settled message would still be carrying it. Fires on a windowed arm as well. |
+
+All of it is scoped to ASSISTANT messages, because a user message never publishes `data-status` even
+on a working build -- only assistant parts render through `MarkdownText`. The capture carries
+`status_hook_present` so the readings are distinguishable in the record and not only in the verdict.
+What the second row gives up is pinned by `test_what_the_windowed_narrowing_gives_up`: a windowed arm
+whose status vocabulary changed is not caught, though the same build trips on any full-mount pair.
+It under-claims rather than over-claims.
+
+**The refusal covers the readings that depend on where the stream had got to, and nothing else.**
+A refusal is bucketed as `blind` by `structural_report` and `visible_report`, and neither consults
+it for the exit code, so anything swallowed by it leaves the run green. Three readings survive it:
+
+- **the overlays**, in `compare`. A dialog, a menu or the model picker is walked from `document`,
+ outside `.aui-thread-root`, so its digest carries neither the streamed message nor the composer.
+- **a user row**, in `compare_visible`, when BOTH arms call that ordinal the user's. A reply is
+ written into an assistant message, so that row cannot be the stream. The two arms having to agree
+ is what makes it provable rather than trusted.
+- **a role change**, in `compare_visible`, even on a row that is in flight. The role is captured
+ beside the digest, and how far a reply has arrived says nothing about whose message it is, so a
+ treatment that renders the live assistant row as `data-role="user"` is reported rather than
+ elided with the transient content digest.
+
+**The SCAFFOLD is readable only when the two arms rendered the same composer control.**
+`ThreadPrimitive.Root` wraps `ThreadComposerDock`, so the composer is inside the thread root and
+inside `digest_scaffold`, and `ComposerRightControls` puts exactly one control in its run-state slot:
+Send when nothing is happening, Stop while a reply is written, Queue while one is queued or while
+text sits in the box mid-reply, and the research pair. Those are different subtrees. Measured on two
+byte-identical threads differing only in that slot: Stop against Send moves the scaffold from 373 to
+381 characters and changes its digest, with no message content involved.
+
+So the capture carries `composer_control`, the token naming which control was in that slot, and the
+comparison asks whether the two arms agree on it. `streaming` is too coarse to ask with: it is
+`isRunning()`, true for Stop AND for Queue, so a queued-idle arm and a streaming arm agree on it
+while rendering two different subtrees.
+
+- **The arms agree on the token:** the scaffold is comparable, and a scaffolding change is reported
+ as it always was -- including inside the blind-probe refusal, alongside the overlays.
+- **They disagree, and the scaffold is the ONLY thing that moved:** `NOT_COMPARABLE`. The pair this
+ whole mode exists for is one arm that has finished its reply against one still writing it; its
+ messages are withheld correctly and its composer used to make it `DIFFER` with the single claim
+ `thread scaffolding outside any message (373->381c)`. Withheld rather than ignored: calling it
+ `MATCH` would hide a genuine composer regression, and `NOT_COMPARABLE` is not a pass.
+- **They disagree and something else also moved:** reported exactly as before. The withholding is
+ not a blanket.
+
+**The PR's own null battery could not see this**, which is why it survived a 15-of-15-to-0 null: the
+null is one build against itself at six points in ONE stream, so both arms are generating and both
+render Stop. The bias is symmetric within the control and cancels exactly. A flat null proves
+repeatability, never comparability.
### The two boundary decisions in visible-region parity
Written down because this is where a visible-region check goes wrong quietly.
@@ -553,6 +682,24 @@ vacancy at another cancel, and that reads a clean zero over a live collision. Th
collision that had resolved to one row by capture time is not visible here, and seeing it would need
the clash recorded when the position is stamped.
+
+**The streaming probe's positive control travels with the VISIBLE payload too, because
+`compare_visible` never sees the structural one.** A windowed pair is scored from
+`parityVisible.capture()` alone, and its per-row `in_flight` is read off the same
+`streamingMessages()` call the control counts. The two arms are two separately installed builds
+(`--ab REF` gives the treatment its own `UNSLOTH_STUDIO_HOME`), so a head that renames or moves the
+`data-status` / `aria-busy` hook is blinded on ONE arm only: nothing cancels out, every row on that
+arm reads settled, and a reply that is mid-tail on one side and finished on the other used to land
+in the per-ordinal loop as "N visible message(s) rendered differently" -- the wall-clock false alarm
+this mode exists to avoid, arriving through the one door left open. The null control cannot absorb
+it either, being base-vs-base: both arms are blinded or neither, `derive_unstable` counts the
+resulting `NOT_COMPARABLE` as blind rather than as an observation, and the action never becomes
+unstable. So the capture carries `streaming` and `in_flight_unplaced` (from `dom.generating()`, read
+GLOBALLY -- a reply streaming below the fold is an ordinary state and must refuse nothing), and
+`compare_visible` reuses `streaming_probe` to return `NOT_COMPARABLE`. It sits after the
+different-messages-on-screen and viewport-ended-empty findings and before the digest comparison, the
+same ordering `compare` uses around `mount_count_mismatch`: losing the thread stays a finding
+whether or not the stream could be placed.
**The visible-region noise floor is keyed by (rung, action), and needs more than one observation.**
`visible_unstable_set` derives it from a base-vs-base null control. It returned ACTION NAMES, so a
single differing null pair silenced that action for every rep and every rung -- and a payload
diff --git a/tests/studio/studiobench/analysis/parity.py b/tests/studio/studiobench/analysis/parity.py
index 507a593729d..2a89230c0bf 100644
--- a/tests/studio/studiobench/analysis/parity.py
+++ b/tests/studio/studiobench/analysis/parity.py
@@ -163,10 +163,67 @@ def _messages(capture: dict) -> dict[int, dict]:
return {m["i"]: m for m in (capture.get("messages") or []) if "i" in m}
+def in_flight(base: Optional[dict], treat: Optional[dict]) -> set[int]:
+ """Mounted indices of the messages that were still being WRITTEN on either arm.
+
+ THE UNION, not the intersection, and that is the whole point. The ordinary case is precisely
+ that one arm has finished the reply and the other has not: the two arms are two cells run back
+ to back against one pacer, each with its own send click and its own paint clock, so the digest
+ lands at two different points in the same stream. A message that is in flight on EITHER side
+ has no defined moment on that side, and differencing it measures wall clock.
+
+ Read from the capture rather than inferred. `scene/parity.js` takes it from the app's own
+ published state -- assistant-ui's `data-status` on the text part, `aria-busy` on the reasoning
+ content -- so this is the page's statement about itself and not the benchmark's guess.
+
+ A capture recorded before the field existed reports nothing, and is treated as nothing in
+ flight, which is what every such payload was scored as when it was written.
+ """
+ out: set[int] = set()
+ for side in (base, treat):
+ if isinstance(side, dict):
+ for i in side.get("in_flight") or []:
+ if isinstance(i, int):
+ out.add(i)
+ return out
+
+
+def _scaffold(capture: dict) -> tuple[Optional[str], Optional[int]]:
+ """The thread with every message elided, falling back to the whole-thread digest.
+
+ `digest` is this plus the per-message rows, so comparing the scaffold and the rows separately
+ is the same reading taken apart -- and taken apart it can withhold one message. The fallback is
+ what keeps an old payload comparable: a capture recorded before the scaffold existed carries
+ `digest` alone, and it also carries no `in_flight`, so for those two this IS the old comparison.
+ """
+ if "digest_scaffold" in capture:
+ return capture.get("digest_scaffold"), capture.get("chars_scaffold")
+ return capture.get("digest"), capture.get("chars")
+
+
def _overlays(capture: dict) -> list[dict]:
return list(capture.get("overlays") or [])
+def overlays_moved(base: dict, treat: dict) -> list[str]:
+ """The overlay rows that differ, as claims. Empty when the two arms agree about every overlay.
+
+ THE ONE SURFACE IN THE STRUCTURAL CAPTURE THAT A STREAM CANNOT REACH. An overlay -- an open
+ dialog, a menu, the model picker -- is walked from `document`, outside `.aui-thread-root`
+ entirely, so its digest carries neither the streamed message nor the composer that reflects
+ whether a reply is running. That makes it readable on a pair whose stream could not be placed,
+ which is why it is factored out of `localise` and consulted before the refusal in `compare`.
+ """
+ bo, to = _overlays(base), _overlays(treat)
+ if len(bo) != len(to):
+ return [f"overlays {len(bo)}->{len(to)}"]
+ return [
+ f"overlay{k}[{b.get('sel')}]:{b.get('chars')}->{t.get('chars')}c"
+ for k, (b, t) in enumerate(zip(bo, to))
+ if b.get("digest") != t.get("digest")
+ ]
+
+
def windowed_mount(capture: Optional[dict]) -> bool:
"""Did this capture come from a thread that mounts a WINDOW rather than the whole thing?
@@ -270,16 +327,61 @@ def comparability(base: Optional[dict], treat: Optional[dict]) -> Optional[str]:
return None
-def localise(base: dict, treat: dict) -> list[str]:
+def streaming_probe(base: dict, treat: dict) -> Optional[str]:
+ """Why the STREAMING PROBE could not be believed on this pair, or None.
+
+ THE POSITIVE CONTROL ON A SCAN THAT CAN RETURN ZERO. The elision below is only as good as its
+ ability to find the streamed message, and `streamingMessages()` walks selectors written against
+ Studio's markup: rename `data-status` and it goes quiet, matches nothing, and every capture then
+ reports the strongest thing it can say about the stream -- that there was none -- on the
+ strength of never having looked successfully. That is exactly the shape `compare_styles`
+ already refuses for the style probe and `compare_visible` for the visibility scan.
+
+ The app publishes the fact twice, through the Stop button and through `data-status`, and
+ `capture()` carries the disagreement out of the page rather than resolving it there.
+
+ NOT part of `comparability`, and the ordering is deliberate. This refusal is about the stream
+ split only; a pair whose arms mounted different NUMBERS of messages is a lost conversation and
+ is reported as a difference whether or not the stream could be placed, because that reading
+ does not depend on the split at all. Put here, after `mount_count_mismatch`, a build that drops
+ a message while a reply is running is still a finding rather than a shrug.
+ """
+ for label, side in (("base", base), ("treatment", treat)):
+ if isinstance(side, dict) and side.get("in_flight_unplaced"):
+ return (
+ f"a reply was running on the {label} arm and no message published a streaming "
+ "state, so the streamed message could not be identified and its digest cannot be "
+ "held apart from the settled thread. This is a probe that needs fixing (the "
+ "`data-status` / `aria-busy` hooks in scene/dom.js), not a settled thread"
+ )
+ return None
+
+
+def localise(
+ base: dict,
+ treat: dict,
+ skip: Optional[set[int]] = None,
+) -> list[str]:
"""WHERE the two captures differ, as short human-readable claims.
A whole-thread digest that differs is a fact nobody can act on. The per-message and per-overlay
rows are what turn it into a bug report, and an unlocalised difference is reported as exactly
that rather than left to look like a localised one.
+
+ `skip` names the messages that were still being written on one arm or the other. They are left
+ out of the list rather than quoted in it, because a mid-stream digest names a point in a stream
+ and not a rendering, and a reader handed `msg22(assistant):17334->17358c` has no way to tell the
+ two apart. What they were is reported separately, by the caller, as a residue.
"""
+ skip = skip or set()
moved: list[str] = []
bm, tm = _messages(base), _messages(treat)
for i in sorted(set(bm) | set(tm)):
+ if i in skip and i in bm and i in tm:
+ # In flight on BOTH sides of the comparison. A message present on one arm only is a
+ # different statement -- one arm is not rendering a message the other is -- and is
+ # reported below whatever its status.
+ continue
if i not in bm:
moved.append(f"msg{i}({tm[i].get('role', '?')}):only treatment")
elif i not in tm:
@@ -289,22 +391,14 @@ def localise(base: dict, treat: dict) -> list[str]:
f"msg{i}({bm[i].get('role', '?')}):" f"{bm[i].get('chars')}->{tm[i].get('chars')}c"
)
- bo, to = _overlays(base), _overlays(treat)
- if len(bo) != len(to):
- moved.append(f"overlays {len(bo)}->{len(to)}")
- else:
- for k, (b, t) in enumerate(zip(bo, to)):
- if b.get("digest") != t.get("digest"):
- moved.append(f"overlay{k}[{b.get('sel')}]:{b.get('chars')}->{t.get('chars')}c")
+ moved.extend(overlays_moved(base, treat))
if not moved:
# The whole-thread digest moved but no message and no overlay did. That is the thread
# scaffolding itself -- the viewport, the composer, the empty-state -- and saying so is
# more useful than an empty list, which reads as "nothing differs".
- moved.append(
- f"thread scaffolding outside any message "
- f"({base.get('chars')}->{treat.get('chars')}c)"
- )
+ bc, tc = _scaffold(base)[1], _scaffold(treat)[1]
+ moved.append(f"thread scaffolding outside any message ({bc}->{tc}c)")
return moved
@@ -336,6 +430,40 @@ def compare_styles(base: dict, treat: dict) -> tuple[str, str]:
"selector list is written against Studio's markup and does not survive a rename; "
"this is a probe that needs fixing, not two arms that agree"
)
+ # THE RUN-STATE CONTROL IS IN THE SELECTOR LIST, so this reading straddles the same composer
+ # swap the structural refusals below are about, and it has to be elided for the same reason.
+ # `STYLE_SELECTORS` (scene/parity.js) names `button[aria-label="Send message"]` and
+ # `button[aria-label="Stop generating"]`, and the signature carries the SELECTOR THAT MATCHED
+ # (`parts.push(sel + "#" + n)`) -- so an arm still generating and a settled arm walk two
+ # different entries for the one composer button. Measured on two byte-identical fixture threads
+ # differing only in that control: Send against Stop holds all three properties at
+ # `inline-block` / `visible` / `auto` on both arms and still moves the digest, and Send against
+ # either queue control -- neither of which is in the selector list at all -- moves the element
+ # COUNT from 7 to 6. Both come back DIFFER over identical CSS, and `sweep/ui_parity.report`
+ # prints that as a style-regression advisory for precisely the ordinary cross-stream-state
+ # timing the refusals exist to withhold.
+ #
+ # THE SAME CORROBORATION THE SCAFFOLD SUPPRESSION REQUIRES, and for the same reason: a
+ # differing `composer_control` alone is what a treatment that DROPS or renames the control
+ # produces, and that is a rendering regression this probe should still report. `streaming` and
+ # `queued_idle` are read off the thread's run state rather than off the composer, so they are
+ # evidence the composer cannot manufacture.
+ #
+ # NOT_COMPARABLE AND NOT MATCH. The probe reads ONE aggregate digest over up to `STYLE_CAP`
+ # elements, so a genuine CSS difference elsewhere on the page is inside the same number and
+ # cannot be separated from the swap here. This withholds the reading; it does not pass it.
+ if (bs.get("elements") != ts.get("elements") or bs.get("digest") != ts.get("digest")) and (
+ generation_disagrees(base, treat) and _run_state_disagrees(base, treat)
+ ):
+ return NOT_COMPARABLE, (
+ "the two arms rendered different composer run-state controls "
+ f"({base.get('composer_control')!r} against {treat.get('composer_control')!r}) and the "
+ "run state itself says why, so the style probe walked a different selector for that "
+ "one button -- its signature carries the selector that matched. The difference is the "
+ "control swap and not a stylesheet change. The digest is ONE aggregate over every "
+ "matched element, so a real CSS difference elsewhere cannot be separated from it here; "
+ "this is a reading withheld, not a pass"
+ )
if bs.get("elements") != ts.get("elements"):
return DIFFER, (
f"the probe matched a different number of elements "
@@ -346,7 +474,127 @@ def compare_styles(base: dict, treat: dict) -> tuple[str, str]:
return DIFFER, f"display/visibility/pointer-events differ over {bs.get('elements')} elements"
-def _any_moved(base: dict, treat: dict) -> bool:
+def generation_disagrees(base: dict, treat: dict) -> bool:
+ """Was one arm running a reply while the other was not, at the moment each was digested?
+
+ THE COMPOSER IS A FUNCTION OF THIS, and the composer is inside `.aui-thread-root`:
+ `ThreadPrimitive.Root` wraps `ThreadComposerDock`, so `digest_scaffold` carries whichever
+ control the run state selected. Stop, Queue and Send are different subtrees, so two arms that
+ disagree about generation disagree about the scaffold FOR THAT REASON, with no rendering
+ difference between them.
+
+ Read from `composer_control`, the TOKEN naming which control the composer put in that slot, and
+ not from `streaming`. `streaming` is `isRunning()`, which is true for Stop and for Queue alike,
+ so a queued-idle arm and a streaming arm agree on it while rendering two different subtrees --
+ and the scaffold is exactly what those subtrees are in. Captures taken before the token existed
+ fall back to `streaming`, and captures older than that report neither and are scored as they
+ always were.
+ """
+ bc, tc = base.get("composer_control"), treat.get("composer_control")
+ if bc is not None and tc is not None:
+ return bc != tc
+ return bool(base.get("streaming")) != bool(treat.get("streaming"))
+
+
+def _run_state_disagrees(base: dict, treat: dict) -> bool:
+ """Do the arms disagree about the run state, read OFF the run state rather than the composer?
+
+ `generation_disagrees` reads `composer_control`, which is the composer. Using it alone to
+ excuse a composer difference proves the premise with the conclusion, so this is the second,
+ independent half: `streaming` is `isRunning()` and `queued_idle` is the queue waiting to be
+ dispatched, both taken from the thread's own run state and neither derivable from which button
+ was drawn.
+
+ Captures older than these fields report neither, and two `False`s then read as agreement --
+ which is the conservative direction here, since it makes the pair a reported difference rather
+ than a silent refusal.
+ """
+ return bool(base.get("streaming")) != bool(treat.get("streaming")) or bool(
+ base.get("queued_idle")
+ ) != bool(treat.get("queued_idle"))
+
+
+def _messages_moved(
+ base: dict,
+ treat: dict,
+ skip: Optional[set[int]] = None,
+) -> bool:
+ """The message half of `_any_moved`, on its own."""
+ skip = skip or set()
+ bm, tm = _messages(base), _messages(treat)
+ # A message PRESENT ON ONE ARM ONLY is a difference whether or not it was streaming. Being
+ # mid-reply excuses a digest, never an absence.
+ if set(bm) != set(tm):
+ return True
+ return any(bm[i].get("digest") != tm[i].get("digest") for i in bm if i not in skip)
+
+
+def scaffold_moved(base: dict, treat: dict) -> bool:
+ """Did the thread scaffolding -- viewport, composer, empty state -- move?"""
+ return _scaffold(base)[0] != _scaffold(treat)[0]
+
+
+def settled_messages_moved(base: dict, treat: dict) -> list[str]:
+ """The per-message rows that differ and PROVABLY cannot be the reply being written.
+
+ THE SAME RULE `compare_visible` APPLIES TO ITS OWN ROWS, and it has to be the same rule: the
+ two modes must not disagree about which readings have a defined moment. Two shapes qualify.
+
+ A ROW BOTH ARMS CALL THE USER'S. A stream writes into an assistant message -- assistant-ui's
+ `status` (`running` / `complete` / ...) is defined on assistant messages only, and the
+ `data-status` hook `scene/dom.js` walks is on the assistant text part -- so a user row is never
+ the message being written, whether or not the probe could place that message. The two arms
+ AGREEING about the role is what makes it provable; a row whose role disagrees is reported as a
+ role change instead of being trusted as either.
+
+ A ROW WHOSE ROLE CHANGED. The role is captured beside the digest rather than inside it, and how
+ far a reply has arrived says nothing about whose message it is, so this is reported even for a
+ row that is in flight -- where the digest itself is still withheld.
+
+ Reached only past `mount_count_mismatch`, so the two arms mounted the same number of messages
+ and index `i` names the same position on both sides.
+ """
+ bm, tm = _messages(base), _messages(treat)
+ streaming = in_flight(base, treat)
+ out: list[str] = []
+ for i in sorted(set(bm) & set(tm)):
+ b, t = bm[i], tm[i]
+ if b.get("role") != t.get("role"):
+ out.append(f"msg{i}:role {b.get('role')}->{t.get('role')}")
+ continue
+ # Flagged in flight by the arm that COULD place its stream. Its digest is a point in a
+ # stream on that arm whatever role it carries, so it is withheld like any other.
+ if i in streaming:
+ continue
+ if b.get("role") == "user" and b.get("digest") != t.get("digest"):
+ out.append(f"msg{i}(user):{b.get('chars')}->{t.get('chars')}c")
+ # WHY THERE IS NO ASSISTANT-ROW RULE HERE, since it looks like the obvious next one to add.
+ #
+ # An earlier assistant row on a fully mounted thread really is settled while the tail is being
+ # written, and a counting argument even makes it provable without knowing WHICH row is in
+ # flight: a thread writes one reply at a time, so two differing assistant rows cannot both be
+ # it. Both readings are sound and both are still unusable, because of what BLINDS the probe in
+ # the first place.
+ #
+ # The reachable blind pair is a build that renamed the `data-status` hook. That attribute is on
+ # the assistant text part and the digest walks attributes, so the rename that blinds the probe
+ # ALSO moves the digest of every assistant row, by itself. Reporting those rows therefore turns
+ # every genuinely blind pair into a difference, which is the wall-clock false alarm this file
+ # exists to remove, wearing the other hat. Measured: implementing the counting rule flipped
+ # `test_a_settled_queued_idle_pair_is_scored_rather_than_refused`'s blind control from NOT
+ # COMPARABLE to DIFFER.
+ #
+ # A user row is not exposed to that, which is exactly why it is the one shape that qualifies:
+ # the hook is not on it. Separating "the hook attribute moved" from "the content moved" would
+ # need a digest that excludes the attribute, which is not something this capture carries.
+ return out
+
+
+def _any_moved(
+ base: dict,
+ treat: dict,
+ skip: Optional[set[int]] = None,
+) -> bool:
"""Did ANY digest in the capture move, not just the whole-thread one?
THE HOLE THIS CLOSES, found by the spike control and not by reading the code. An overlay --
@@ -358,17 +606,22 @@ def _any_moved(base: dict, treat: dict) -> bool:
never fire. Injecting a `role="menu"` element and watching the digest report a clean pass is
what surfaced it.
"""
- if base.get("digest") != treat.get("digest"):
+ skip = skip or set()
+ # THE SCAFFOLD, not the whole-thread digest. The whole-thread digest serialises the streamed
+ # message too, so with a reply in flight it differs on essentially every pair -- measured at
+ # 175 of 175 adjacent 24-character steps of the shipped corpus -- and every check below it
+ # would be unreachable behind it, exactly as the whole-thread digest once made the overlay walk
+ # unreachable. The scaffold plus the per-message rows is the same reading taken apart, so
+ # nothing is lost by decomposing it. On a payload with no scaffold this IS the whole-thread
+ # digest and the behaviour is the old one.
+ if _scaffold(base)[0] != _scaffold(treat)[0]:
return True
bo, to = _overlays(base), _overlays(treat)
if [(o.get("sel"), o.get("digest")) for o in bo] != [
(o.get("sel"), o.get("digest")) for o in to
]:
return True
- bm, tm = _messages(base), _messages(treat)
- if set(bm) != set(tm):
- return True
- return any(bm[i].get("digest") != tm[i].get("digest") for i in bm)
+ return _messages_moved(base, treat, skip)
def compare(base: Optional[dict], treat: Optional[dict]) -> dict:
@@ -406,18 +659,222 @@ def compare(base: Optional[dict], treat: Optional[dict]) -> dict:
"style_reason": style_reason,
}
style_verdict, style_reason = compare_styles(base, treat)
- if not _any_moved(base, treat):
+ blind = streaming_probe(base, treat)
+ if blind is not None:
+ # THE REFUSAL MUST NOT SWALLOW A READING THAT DOES NOT DEPEND ON THE STREAM. An overlay is
+ # walked from `document`, outside the thread root, so a dialog that mounted when it should
+ # not, or one whose contents were rewritten, is a finding whether or not the streamed
+ # message could be identified. Without this it went out with the refusal, and
+ # `structural_report` buckets a refusal as blind and never consults it for the exit code,
+ # so the run went green on it.
+ #
+ # THE SCAFFOLD IS DELIBERATELY NOT CONSULTED HERE, and this is the part of the review item
+ # that measurement does not support. `ThreadPrimitive.Root` wraps `ThreadComposerDock`
+ # (thread.tsx), so the composer is inside `.aui-thread-root` and inside the scaffold -- and
+ # the composer is exactly the surface that changes when a reply starts and stops. Measured
+ # on two byte-identical threads differing only in the composer control: Stop against Send
+ # moves the scaffold from 373 to 381 characters and changes its digest, with no message
+ # content involved at all. On the very pair this branch is about -- one arm generating with
+ # a quiet hook, the other finished -- the scaffold therefore differs BECAUSE one arm is
+ # generating, and reporting that as a rendering difference would manufacture the wall-clock
+ # false alarm this whole file exists to remove.
+ independent = overlays_moved(base, treat)
+ # AND THE SETTLED MESSAGE ROWS, which are the other half of what this refusal must not
+ # swallow. A row both arms call the user's, and a row whose role itself changed, cannot be
+ # the reply being written -- so their meaning does not depend on where the stream had got
+ # to, and discarding them costs exactly the finding this instrument exists to make. Without
+ # this a user message rendered differently by the treatment left here as NOT COMPARABLE
+ # with an empty `moved`, and `structural_report` buckets a refusal as blind and never
+ # consults it for the exit code, so the run went green on it. `compare_visible` already
+ # applies this rule to its own rows and says it is the same rule as this one; it has to be.
+ independent = independent + settled_messages_moved(base, treat)
+ # AND THE SCAFFOLD, but only when the two arms agree about whether a reply was running.
+ # The composer is inside the scaffold and is a function of exactly that, so the scaffold is
+ # readable here when they agree and meaningless when they do not. That is the correct form
+ # of the half of this refusal that measurement did not support.
+ #
+ # AND THE DISAGREEMENT HAS TO BE CORROBORATED OFF THE RUN STATE, exactly as the composer
+ # suppression below requires. `generation_disagrees` reads `composer_control`, which IS the
+ # composer, so on its own it excuses a composer difference with the composer -- and a
+ # treatment that DROPS the Stop control, renames it, or selects the wrong one makes the
+ # tokens differ for that reason and suppressed the whole scaffold with it, while `streaming`
+ # and `queued_idle` were saying the arms were in the same run state all along. That is a
+ # rendering regression withheld by the branch written to admit rendering regressions, and
+ # since a refusal is filed under `blind` the run goes green on it.
+ if scaffold_moved(base, treat) and not (
+ generation_disagrees(base, treat) and _run_state_disagrees(base, treat)
+ ):
+ bc, tc = _scaffold(base)[1], _scaffold(treat)[1]
+ independent = independent + [f"thread scaffolding outside any message ({bc}->{tc}c)"]
+ if independent:
+ return {
+ "verdict": DIFFER,
+ "reason": (
+ "the streamed message could not be identified on one arm, but surfaces that "
+ "CANNOT be the reply being written differ: an overlay is walked outside the "
+ "thread root, so its digest carries neither the stream nor the composer, and a "
+ "row both arms call the user's, or a row whose role changed, is not the "
+ f"message a stream writes into. {blind}"
+ ),
+ "moved": independent,
+ "style_verdict": style_verdict,
+ "style_reason": style_reason,
+ }
+ return {
+ "verdict": NOT_COMPARABLE,
+ "reason": blind,
+ "moved": [],
+ "style_verdict": style_verdict,
+ "style_reason": style_reason,
+ }
+ # ── THE STREAMED MESSAGE ────────────────────────────────────────────────────────────────────
+ #
+ # `streaming` holds the messages that were still being written on one arm or the other. They
+ # are scored on NOTHING, and that is a refusal rather than a normalisation: the digest of a
+ # half-written message names a point in a stream, the two arms are at two different points in
+ # the same stream by construction, and no amount of text normalisation can turn one into the
+ # other. See `in_flight`.
+ #
+ # THREE OUTCOMES, and the ordering between them is the load-bearing part.
+ #
+ # the settled document differs DIFFER. This is the case that used to be lost. An action
+ # landing inside a stream was silenced wholesale by
+ # UNSTABLE_ACTIONS, so a real regression anywhere else in
+ # the thread -- another message, an overlay, the composer --
+ # printed under "expected to vary" and the run exited 0.
+ # Now the streamed message is elided and the rest is scored.
+ # the settled document agrees and
+ # the in-flight message agrees MATCH, unchanged. Two arms that landed on the same point
+ # in the stream serialised identically, which is the claim
+ # this mode makes, and demoting it would cost coverage for
+ # nothing.
+ # the settled document agrees and
+ # the in-flight message differs NOT COMPARABLE. Not a pass. `CLAIM_STRUCTURAL` quantifies
+ # over the whole thread, one message did not serialise
+ # identically, and the reason it did not is a reading with
+ # no defined moment. Calling that MATCH would be the
+ # instrument certifying a surface it could not look at,
+ # which is the failure `compare_styles` and
+ # `compare_visible` each already refuse in their own way.
+ #
+ # WHAT THIS GIVES UP, plainly, and both of these are measured rather than reasoned about.
+ #
+ # 1. A genuine rendering regression INSIDE the message that happened to be streaming is no
+ # longer distinguishable here and lands as NOT COMPARABLE. It was not distinguishable before
+ # either -- every action that lands in a stream is on the declared unstable list -- so
+ # nothing that used to be caught stops being caught, and the outcome moves from "expected to
+ # vary, exit 0" to "not measured, not a pass".
+ # 2. A REORDER that moves the streamed message past another message of the same role is
+ # demoted from DIFFER to NOT COMPARABLE. The per-message rows are keyed by mounted index, so
+ # swapping two messages puts a streaming row at one index on one arm and at the other index
+ # on the other; both indices are then in flight on one side or the other, both are withheld,
+ # and the scaffold markers that survive carry the same role in both orders. Measured on the
+ # live-DOM battery: 11 injected rendering differences, 10 still reported DIFFER and this one
+ # demoted. It is a demotion and not a hole -- NOT COMPARABLE is not a pass and the run does
+ # not go green on it -- and the only shape that reaches it needs the streamed message not to
+ # be the last one, which the app does not do today.
+ streaming = in_flight(base, treat)
+ # ── THE COMPOSER IS NOT A RENDERING DIFFERENCE ──────────────────────────────────────────────
+ #
+ # The pair this whole change is about is one arm that has finished its reply against one that
+ # is still writing it. Its MESSAGES are withheld correctly. Its COMPOSER is not: the dock is
+ # inside `.aui-thread-root`, so `digest_scaffold` carries Stop on the arm that is generating
+ # and Send on the arm that is not, and `_any_moved` then reports the pair as DIFFER with the
+ # single claim `thread scaffolding outside any message (373->381c)`. Measured on exactly that
+ # pair, with every settled message row byte-identical across the two arms.
+ #
+ # THE NULL BATTERY CANNOT SEE THIS, which is why it survived a 15-of-15-to-0 null. The null is
+ # one build against itself at six points in ONE stream, so BOTH arms are generating and both
+ # render Stop; the bias is symmetric within the control and cancels exactly. A flat null proves
+ # repeatability, never comparability.
+ #
+ # WITHHELD RATHER THAN IGNORED. If a message or an overlay also moved, that is reported as
+ # usual and this never runs. It is only when the scaffold is the ONLY thing that moved, and the
+ # arms disagree about generation, that the reading has no defined moment -- and then the honest
+ # answer is a refusal, not a pass. Calling it MATCH would hide a genuine composer regression.
+ #
+ # AND THE RUN STATE HAS TO SAY SO INDEPENDENTLY, or the suppression argues in a circle.
+ # `generation_disagrees` reads `composer_control`, the token naming which control the composer
+ # rendered -- so "the arms were at different points in the turn" is being proved by the very
+ # surface whose difference is in question. A treatment that DROPS the Send button, renames it,
+ # or selects the wrong control reaches this branch with every message and overlay agreeing, and
+ # a refusal here is a green run: `report` files NOT COMPARABLE under `blind` and takes its exit
+ # code from `stable_bad or one_sided`. That is the regression the note above says must not be
+ # hidden, hidden by the branch written to say so.
+ #
+ # `streaming` and `queued_idle` are read off the run state rather than off the composer, so
+ # they are evidence the composer cannot manufacture. Every legitimate suppression still has
+ # one: Stop against Send differs in `streaming`, and Queue against Send in the queued-idle
+ # interval differs in `queued_idle`. What is left, the arms agreeing on both and still
+ # rendering different controls, has no run-state explanation and is a rendering difference.
+ if (
+ generation_disagrees(base, treat)
+ and _run_state_disagrees(base, treat)
+ and scaffold_moved(base, treat)
+ and not overlays_moved(base, treat)
+ and not _messages_moved(base, treat, streaming)
+ ):
+ bc, tc = _scaffold(base)[1], _scaffold(treat)[1]
+ return {
+ "verdict": NOT_COMPARABLE,
+ "reason": (
+ "the only difference is the thread scaffolding "
+ f"({bc}->{tc}c), and one arm was running a reply while the other was not. The "
+ "composer dock is inside the thread root and renders Stop or Queue while a reply "
+ "is running and Send when it is not, so the scaffolding differs BECAUSE the two "
+ "arms were at different points in the same turn. Every message and every overlay "
+ "agreed. The scaffold is read as ONE AGGREGATE digest -- viewport, composer dock "
+ "and empty state together -- so this cannot separate the composer swap from a "
+ "change elsewhere in the scaffold that happened at the same time, and it does not "
+ "claim to have: that is part of why it refuses. Nothing here is a pass"
+ ),
+ "moved": [],
+ "in_flight": sorted(streaming),
+ "style_verdict": style_verdict,
+ "style_reason": style_reason,
+ }
+ if not _any_moved(base, treat, streaming):
+ bm, tm = _messages(base), _messages(treat)
+ unsettled = sorted(
+ i
+ for i in streaming
+ if i in bm and i in tm and bm[i].get("digest") != tm[i].get("digest")
+ )
+ if unsettled:
+ names = ", ".join(
+ f"msg{i}({bm[i].get('role', '?')}):{bm[i].get('chars')}->{tm[i].get('chars')}c"
+ for i in unsettled[:4]
+ )
+ return {
+ "verdict": NOT_COMPARABLE,
+ "reason": (
+ f"the settled thread is identical on both arms and the only difference is in "
+ f"{len(unsettled)} message(s) that were STILL BEING WRITTEN when the digest "
+ f"was taken ({names}). The two arms are two cells against one pacer with their "
+ "own send clicks and their own paint clocks, so that digest names a point in a "
+ "stream rather than a rendering, and its size carries no information either: "
+ "the renderer repairs the half-arrived construct, so the serialisation is not "
+ "monotonic in how much text has landed. Nothing here is a pass"
+ ),
+ "moved": [],
+ "in_flight": sorted(streaming),
+ "not_digested": unsettled,
+ "style_verdict": style_verdict,
+ "style_reason": style_reason,
+ }
return {
"verdict": MATCH,
"reason": "",
"moved": [],
+ "in_flight": sorted(streaming),
"style_verdict": style_verdict,
"style_reason": style_reason,
}
return {
"verdict": DIFFER,
"reason": "",
- "moved": localise(base, treat),
+ "moved": localise(base, treat, streaming),
+ "in_flight": sorted(streaming),
"style_verdict": style_verdict,
"style_reason": style_reason,
}
@@ -873,13 +1330,46 @@ def compare_visible(base: Optional[dict], treat: Optional[dict]) -> dict:
# never counted as agreement: this is the residue of comparing a windowed arm at one instant.
uncomparable = sorted(int(o) for o in map(str, sorted(bev)) if o not in bmsg or o not in tmsg)
moved = []
+ # The subset of `moved` that CANNOT be a point in a stream, kept so the blind-probe refusal
+ # below does not take it out with the rest. See each `settled.append` for why that row is
+ # provably not the reply being written.
+ settled: list[str] = []
for ordinal in sorted(bev):
key = str(ordinal)
b, t = bmsg.get(key), tmsg.get(key)
if b is None or t is None:
continue
+ # A ROLE IS NOT A POSITION IN A STREAM. It is captured beside the digest rather than inside
+ # it, and how far a reply has arrived says nothing about whether it is the assistant's. So
+ # a row that changed role is reported even while that row is in flight, where the digest
+ # itself is withheld: a treatment that renders the live assistant row as `data-role="user"`
+ # is a structural regression that used to leave here as NOT COMPARABLE.
+ if b.get("role") != t.get("role"):
+ claim = f"ordinal {ordinal}:role {b.get('role')}->{t.get('role')}"
+ moved.append(claim)
+ settled.append(claim)
+ continue
if b.get("digest") != t.get("digest"):
- moved.append(f"ordinal {ordinal}({b.get('role')}):{b.get('chars')}->{t.get('chars')}c")
+ if b.get("in_flight") or t.get("in_flight"):
+ # STILL BEING WRITTEN ON ONE ARM OR THE OTHER, so its digest names a point in a
+ # stream. Residue, exactly like an ordinal that was unmounted before the capture:
+ # it cannot be a difference, and it cannot be an agreement either, so it joins the
+ # list that refuses the verdict below rather than the list that fails it. Same
+ # rule as `compare` applies to the structural digest; the two modes must not
+ # disagree about which readings have a defined moment.
+ uncomparable.append(ordinal)
+ continue
+ claim = f"ordinal {ordinal}({b.get('role')}):{b.get('chars')}->{t.get('chars')}c"
+ moved.append(claim)
+ # A USER ROW IS NEVER THE REPLY BEING WRITTEN. Both arms agree this ordinal is the
+ # user's, and a stream writes into an assistant message, so this difference survives
+ # the blind-probe refusal below. The two arms agreeing is what makes it provable: a
+ # row whose role DISAGREES is reported above as a role change, not silently trusted.
+ if b.get("role") == "user":
+ settled.append(claim)
+ # Ordinals that were unmounted before the capture and ordinals that were still streaming are
+ # the same kind of residue and are counted once each.
+ uncomparable = sorted(set(uncomparable))
# ONE VIEWPORT ENDED EMPTY AND THE OTHER DID NOT, which is as visible a difference as there is
# and used to be reported as NOT COMPARABLE -- a refusal, not a finding.
#
@@ -911,6 +1401,44 @@ def compare_visible(base: Optional[dict], treat: Optional[dict]) -> dict:
# conversation on the strength of unrelated jitter in the same action.
"severe": True,
}
+ # THE STREAMING PROBE, on the same footing it has in `compare`, because this mode is scored
+ # from its own payload and never sees the structural verdict. `in_flight` above walks the
+ # `data-status` / `aria-busy` hooks, so a build that renames them reports every row settled;
+ # the two arms are two different builds, so that can be true on ONE of them while the other's
+ # reply has genuinely finished, and the differing digests below are then two points in a stream
+ # scored as a rendering difference.
+ #
+ # AFTER the two lost-conversation findings above and BEFORE the digest comparison, for the
+ # reason `compare` puts it after `mount_count_mismatch`: different messages on screen, or one
+ # viewport emptied, are readings that do not depend on the stream split at all, and a build
+ # that loses the thread while a reply runs stays a finding rather than a shrug.
+ blind = streaming_probe(base, treat)
+ if blind is not None:
+ # SAME RULE AS `compare`: the refusal covers the rows whose meaning depends on where the
+ # stream had got to, and nothing else. `settled` holds the rows that provably cannot be the
+ # reply being written -- a row both arms call the user's, and a row whose role itself
+ # changed -- and those are reported rather than discarded. Without this a changed user
+ # message left here as NOT COMPARABLE with an empty `moved`, and `visible_report` buckets
+ # a refusal as blind and never consults it for the exit code.
+ if settled:
+ return {
+ "verdict": DIFFER,
+ "reason": (
+ f"{len(settled)} visible message(s) rendered differently on rows that cannot "
+ "be the reply being written (a user row, or a row whose role changed), so "
+ f"they are reported even though the stream could not be placed. {blind}"
+ ),
+ "moved": settled,
+ "claim": CLAIM_VISIBLE,
+ "not_digested": uncomparable,
+ }
+ return {
+ "verdict": NOT_COMPARABLE,
+ "reason": blind,
+ "moved": [],
+ "claim": CLAIM_VISIBLE,
+ "not_digested": uncomparable,
+ }
if moved:
return {
"verdict": DIFFER,
diff --git a/tests/studio/studiobench/fixture/selftest/test_studiobench_parity_digest.py b/tests/studio/studiobench/fixture/selftest/test_studiobench_parity_digest.py
index 88c731cab8b..288d98a0a1f 100644
--- a/tests/studio/studiobench/fixture/selftest/test_studiobench_parity_digest.py
+++ b/tests/studio/studiobench/fixture/selftest/test_studiobench_parity_digest.py
@@ -52,16 +52,32 @@ const document = { body: { tagName: "BODY", attributes: [], childNodes: [],
window.getComputedStyle = () => ({ getPropertyValue: () => "" });
(new Function("window", "document", src))(window, document);
+// `elide: true` on a node collects the BUILT element into a set, which is then handed to
+// `signature` as its third argument. That argument is what the streamed-message elision uses, and
+// it takes ELEMENTS rather than names, so a fixture cannot address it without building first.
+// Collected per call, so `signatures` (no set) and `elided` (the set) are the same trees digested
+// two ways and can be compared directly.
+let collected = null;
const build = (spec) => {
if (typeof spec === "string") return { nodeType: 3, nodeValue: spec };
const attrs = spec.attrs || {};
- return {
+ const el = {
nodeType: 1,
tagName: (spec.tag || "div").toUpperCase(),
attributes: Object.keys(attrs).map((name) => ({ name })),
getAttribute: (name) => (name in attrs ? attrs[name] : null),
childNodes: (spec.children || []).map(build),
};
+ if (spec.elide && collected) collected.add(el);
+ return el;
+};
+
+const withElision = (spec) => {
+ collected = new Set();
+ const root = build(spec);
+ const set = collected;
+ collected = null;
+ return parity.signature(root, undefined, set.size ? set : undefined);
};
const spec = JSON.parse(fs.readFileSync(process.argv[3], "utf8"));
@@ -70,6 +86,7 @@ console.log(JSON.stringify({
texts: (spec.texts || []).map((t) => parity.normText(t)),
urls: (spec.urls || []).map((u) => parity.normUrl(u)),
signatures: (spec.trees || []).map((t) => parity.signature(build(t))),
+ elided: (spec.elided || []).map(withElision),
hashes: (spec.hashes || []).map((s) => parity.hash(s)),
}));
"""
diff --git a/tests/studio/studiobench/fixture/selftest/test_studiobench_parity_streamed.py b/tests/studio/studiobench/fixture/selftest/test_studiobench_parity_streamed.py
new file mode 100644
index 00000000000..faf52b68400
--- /dev/null
+++ b/tests/studio/studiobench/fixture/selftest/test_studiobench_parity_streamed.py
@@ -0,0 +1,880 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+"""A message that is still being written has no defined moment, so it is refused rather than scored.
+
+THE DEFECT. studiobench drives both arms through the same scripted actions, and the parity digest
+is taken at the CLOSE of each action window -- a wall-clock offset in the film. The two arms are
+two cells run back to back against one pacer: the bytes on the wire are identical by construction,
+but each arm has its own send click, its own `t0` and its own paint clock. So when a slot lands
+inside a live reply the two digests are taken at two different points in the same stream, and the
+difference that comes back is wall clock wearing the shape of a UI change. It is the same mistake
+as every entry in the instrument-defect list this file is a response to: MEASURING AT A MOMENT
+WHOSE MEANING IS NOT STABLE ACROSS THE THINGS BEING COMPARED.
+
+WHY YOU CANNOT RECOGNISE IT BY ITS SIZE, which is the part that has misled people. Mid-stream,
+Studio does not show a prefix of the finished reply. `parseIncompleteMarkdown` runs remend over the
+tail and closes whatever construct is half-arrived, KaTeX renders the repaired formula and, while
+it will not parse, writes the parse error and its character offset into a `title`, Shiki
+re-tokenises the repaired fence, and the trailing code block carries `data-incomplete`. None of
+that is monotonic in how much text has arrived.
+
+MEASURED, out of tree, on the shipped frozen corpus (the streamed unit, 4,238 characters) driven
+through the real remend, the real KaTeX and the real Shiki into the shipped `signature()`:
+
+ stepping by the pacer's own 24-character chunk 175 of 175 adjacent pairs differ
+ 0 of them at the same serialised length
+ stepping one character at a time 52 of 4,237 steps make the signature SHORTER
+ 34 pairs of distinct stream positions serialise
+ to the same length with different digests
+ 398 of 4,237 steps move the digest not at all
+
+So at the shipped cadence the drift is total -- one chunk of skew fails a stable action outright --
+and the same-length variant, while real, needs sub-chunk skew to reach. Both are the same defect
+and the fix is deliberately blind to length: what is refused is the message that was in flight, not
+a difference of a particular size.
+
+WHAT THE FIX MUST NOT DO. A normaliser that quietened this by widening what it erases would be
+worse than the bug: it would pass a null control perfectly and detect nothing. So this file scores
+both directions on every change, as a MUTANT SCORE and a NULL SCORE rather than as "the tests pass".
+
+ NULL pairs that are the same build at two points in one stream. Every one must be refused.
+ MUTANT real, visible rendering differences, injected WHILE A REPLY IS IN FLIGHT. Every one must
+ still be caught, because a change that only shows up during a stream is still a change.
+
+The before/after comparison is free and needs no second checkout: a capture WITHOUT the streaming
+fields is exactly what the previous instrument produced, and `compare` falls back to the plain
+digest for it. `test_the_null_battery_scores_the_old_instrument_too` runs the same battery both
+ways and pins both numbers.
+
+THE SCORES THIS FILE HOLDS, and the same two scores taken out of tree against a real jsdom document
+built by the real renderers and digested by the shipped `capture()` rather than by these fixtures:
+
+ in tree NULL 0 of 6 reported as a difference (all 6 refused); MUTANT 13 of 13 detected, and
+ 0 of 13 reported as a MATCH.
+ live DOM NULL 15 of 15 -> 0 of 15 reported as a difference; MUTANT 10 of 11 still detected,
+ 11 of 11 never a MATCH. The one demotion is the reorder pinned below.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.analysis import parity as P # noqa: E402
+
+from tests.studio.studiobench.fixture.selftest.test_studiobench_parity_digest import ( # noqa: E402
+ run_js,
+)
+
+# ── building a capture out of the SHIPPED signature ──────────────────
+#
+# Not a hand-written digest. The whole point of the node harness is that the thing under test is
+# `scene/parity.js` as it ships, so these fixtures are DOM trees and every digest below is produced
+# by walking them with the real `signature()`.
+
+
+def message(
+ index: int,
+ *,
+ role: str = "assistant",
+ body: str = "settled text",
+ streaming: bool = False,
+ extra: list | None = None,
+ attrs: dict | None = None,
+) -> dict:
+ """One thread message, in the shape Studio renders.
+
+ `streaming` puts `data-status="running"` on the text part, which is assistant-ui's own
+ published state and what `scene/dom.js::streamingMessages` reads. A settled part reads
+ `"complete"`, so the attribute is present either way and its VALUE is what moves.
+ """
+ children: list = [
+ {
+ "tag": "div",
+ "attrs": {"data-status": "running" if streaming else "complete"},
+ "children": [{"tag": "p", "attrs": {"class": "aui-md-p"}, "children": [body]}],
+ }
+ ]
+ children.extend(extra or [])
+ return {
+ "tag": "div",
+ "attrs": dict({"data-role": role, "class": "aui-message-root"}, **(attrs or {})),
+ "children": children,
+ "_i": index,
+ "_streaming": streaming,
+ }
+
+
+def thread(messages: list[dict], overlays: list[dict] | None = None) -> dict:
+ return {
+ "tag": "div",
+ "attrs": {"class": "aui-thread-root"},
+ "children": [
+ {"tag": "div", "attrs": {"class": "aui-thread-viewport"}, "children": list(messages)}
+ ],
+ "_overlays": list(overlays or []),
+ }
+
+
+def _mark_elided(node: dict) -> dict:
+ """The same tree with every message marked for elision, which is what the scaffold digest is.
+
+ Recursive and keyed on `data-role`, because that is what `capture()` elides: `dom.messages()`
+ returns every `[data-role]` in the document, wherever it sits. A helper that only reached the
+ first branch would build a scaffold that quietly agreed about the branches it never walked.
+ """
+ if not isinstance(node, dict):
+ return node
+ if (node.get("attrs") or {}).get("data-role"):
+ return dict(node, elide = True)
+ return dict(node, children = [_mark_elided(c) for c in node.get("children") or []])
+
+
+def capture(tree: dict, *, streaming_fields: bool = True) -> dict:
+ """A parity capture for one arm, every digest taken by the shipped `signature()`.
+
+ `streaming_fields=False` produces exactly what the instrument produced before the streamed
+ message was named: digests only, no `in_flight`, no settled digest. That is the before-picture
+ and it is not a mock of one.
+ """
+ messages = tree["children"][0]["children"]
+ overlays = tree.get("_overlays") or []
+ # `elide` marks EVERY message, which is what `capture()` in parity.js does: the scaffold has to
+ # be the same walk on both arms, and which message is in flight is not.
+ scaffold_tree = _mark_elided(tree)
+ got = run_js(
+ {
+ "trees": [tree] + messages + [o["tree"] for o in overlays],
+ "elided": [scaffold_tree],
+ }
+ )
+ sigs = got["signatures"]
+ whole, msg_sigs = sigs[0], sigs[1 : 1 + len(messages)]
+ overlay_sigs = sigs[1 + len(messages) :]
+ settled = got["elided"][0]
+ hashes = run_js({"hashes": [whole, settled] + msg_sigs + overlay_sigs})["hashes"]
+ out: dict = {
+ "parity_attempted": True,
+ "root_kind": "thread",
+ "digest": hashes[0],
+ "chars": len(whole),
+ "messages": [
+ {"i": m["_i"], "role": m["attrs"]["data-role"], "digest": h, "chars": len(s)}
+ for m, h, s in zip(messages, hashes[2 : 2 + len(messages)], msg_sigs)
+ ],
+ "overlays": [
+ {"sel": o["sel"], "digest": h, "chars": len(s)}
+ for o, h, s in zip(overlays, hashes[2 + len(messages) :], overlay_sigs)
+ ],
+ "styles": {"digest": "s0", "chars": 5, "elements": 4, "capped": False},
+ "mounted_messages": len(messages),
+ "thread_total": len(messages),
+ }
+ if streaming_fields:
+ in_flight = [m["_i"] for m in messages if m["_streaming"]]
+ for row, m in zip(out["messages"], messages):
+ if m["_streaming"]:
+ row["in_flight"] = True
+ out.update(
+ digest_scaffold = hashes[1],
+ chars_scaffold = len(settled),
+ in_flight = in_flight,
+ streaming = bool(in_flight),
+ in_flight_unplaced = False,
+ )
+ return out
+
+
+# The body of the reply, at four points in one stream. Not four different documents: the same one,
+# with the trailing construct repaired differently at each point, which is what the renderer
+# actually does. The `title` is the KaTeX parse error rehype-katex writes while the formula will
+# not parse, and its character offset moves with every arriving character.
+def streamed_body(chars: int) -> list:
+ text = "The bounded shard coalesces the retained layout, except that the fibre stays inter"
+ return [
+ {"tag": "p", "children": [text[:chars]]},
+ {
+ "tag": "span",
+ "attrs": {
+ "class": "katex-error",
+ "title": f"ParseError: KaTeX parse error: Expected 'EOF' at position {chars}",
+ },
+ "children": [f"$$\\lambda_{{a{chars:04d}}}$$"],
+ },
+ ]
+
+
+def streaming_arm(
+ chars: int,
+ *,
+ settled_body: str = "settled text",
+ streaming_fields: bool = True,
+ overlays: list | None = None,
+) -> dict:
+ return capture(
+ thread(
+ [
+ message(0, role = "user", body = "the prompt"),
+ message(1, body = settled_body),
+ message(2, streaming = True, body = "reply so far", extra = streamed_body(chars)),
+ ],
+ overlays,
+ ),
+ streaming_fields = streaming_fields,
+ )
+
+
+#: Four points in one stream. Adjacent pairs are what two arms one paint apart look like.
+STREAM_POINTS = (12, 24, 48, 81)
+
+
+# ── 1. the reproduction, both cases ──────────────────────────────────
+
+
+def test_the_same_document_at_two_points_in_one_stream_moves_the_raw_digest():
+ """CASE ONE: the drift is real, and it is not the comparison layer inventing it.
+
+ Two arms, one build, one pacer, the same logical document -- and the digests disagree, because
+ the digest was taken at two different points in the same reply. This is the reading that has
+ been read as "this pull request changed the UI".
+ """
+ a, b = streaming_arm(24), streaming_arm(48)
+ assert a["digest"] != b["digest"], "no drift to fix; the fixture is not reproducing the defect"
+ # ...and the settled thread is byte-identical, which is what makes it a false alarm rather
+ # than a finding.
+ assert a["digest_scaffold"] == b["digest_scaffold"]
+
+
+def test_the_drift_is_refused_rather_than_reported_as_a_ui_change():
+ got = P.compare(streaming_arm(24), streaming_arm(48))
+ assert got["verdict"] == P.NOT_COMPARABLE, got
+ assert got["moved"] == []
+ assert got["not_digested"] == [2]
+ assert "STILL BEING WRITTEN" in got["reason"]
+
+
+def test_two_genuinely_different_documents_still_differ_while_a_reply_streams():
+ """CASE TWO, and it is the one a bad fix breaks.
+
+ Same point in the stream on both arms, but a SETTLED message renders different text. That is a
+ real difference and it has to survive the streamed message being excused.
+ """
+ got = P.compare(
+ streaming_arm(24, settled_body = "settled text"),
+ streaming_arm(24, settled_body = "settled text, rewritten"),
+ )
+ assert got["verdict"] == P.DIFFER, got
+ assert got["moved"] == ["msg1(assistant):120->131c"], got["moved"]
+
+
+def test_a_real_difference_survives_the_streamed_message_drifting_at_the_same_time():
+ # The realistic case: the arms are at different points in the stream AND something real
+ # changed. Excusing the first must not excuse the second, and the streamed message must not
+ # appear in `moved` and drown the finding.
+ got = P.compare(
+ streaming_arm(24, settled_body = "settled text"),
+ streaming_arm(81, settled_body = "settled text, rewritten"),
+ )
+ assert got["verdict"] == P.DIFFER, got
+ assert got["moved"] == ["msg1(assistant):120->131c"], got["moved"]
+ assert got["in_flight"] == [2]
+
+
+# ── 2. the null score ────────────────────────────────────────────────
+
+
+def null_battery(*, streaming_fields: bool) -> list[dict]:
+ """Every ordered pair of stream points: one build, one document, two moments."""
+ arms = {n: streaming_arm(n, streaming_fields = streaming_fields) for n in STREAM_POINTS}
+ return [
+ P.compare(arms[a], arms[b])
+ for i, a in enumerate(STREAM_POINTS)
+ for b in STREAM_POINTS[i + 1 :]
+ ]
+
+
+def test_the_null_score_is_zero():
+ results = null_battery(streaming_fields = True)
+ differing = [r for r in results if r["verdict"] == P.DIFFER]
+ assert len(results) == 6
+ assert not differing, f"NULL SCORE {len(differing)}/{len(results)}: {differing}"
+ # And they are refused, not passed. A null that reports MATCH on a pair whose digests plainly
+ # disagree would be the instrument certifying a surface it could not look at.
+ assert all(r["verdict"] == P.NOT_COMPARABLE for r in results)
+
+
+def test_the_null_battery_scores_the_old_instrument_too():
+ """The before-picture, on the same fixtures, in the same run.
+
+ A capture without the streaming fields is exactly what the previous instrument recorded, and
+ `compare` falls back to the plain digest for it. So this is not a claim about what used to
+ happen; it is the old behaviour, measured.
+ """
+ before = null_battery(streaming_fields = False)
+ assert all(r["verdict"] == P.DIFFER for r in before), before
+ # Every one of them localised to the streamed message and to nothing else, which is what made
+ # them read as a UI change rather than as a clock.
+ for r in before:
+ assert [m for m in r["moved"] if m.startswith("msg2(")] == r["moved"], r["moved"]
+
+
+def test_two_arms_that_landed_on_the_same_point_in_the_stream_still_match():
+ # The coverage this must NOT cost. Two arms at the same point serialise identically, which is
+ # exactly the claim this mode makes, so it stays a pass.
+ got = P.compare(streaming_arm(24), streaming_arm(24))
+ assert got["verdict"] == P.MATCH, got
+ assert got["in_flight"] == [2]
+
+
+def test_a_settled_thread_is_scored_exactly_as_it_was():
+ settled = capture(thread([message(0, role = "user", body = "hi"), message(1)]))
+ assert settled["in_flight"] == [] and settled["streaming"] is False
+ assert P.compare(settled, settled)["verdict"] == P.MATCH
+ # The scaffold is a SHORTER walk than the whole thread, not an equal one, and it has to be:
+ # every message is elided from it whether or not anything was streaming. What makes the reading
+ # complete again is the per-message rows, and the mutant battery is what shows they do.
+ assert settled["chars_scaffold"] < settled["chars"]
+
+
+# ── 3. the mutant score ──────────────────────────────────────────────
+#
+# Every mutant is a real, visible rendering difference, injected WHILE A REPLY IS IN FLIGHT and at
+# the SAME point in the stream on both arms, so the only thing the comparison can be reacting to is
+# the mutation. A normaliser that reports "identical" without ever having been shown a difference
+# is worthless, and one that stopped seeing these because a stream happened to be running would be
+# worse than the drift it was written to fix.
+
+
+def mutants() -> list[tuple[str, dict, dict]]:
+ at = 24
+
+ def base_tree(**kw) -> dict:
+ return thread(
+ [
+ message(0, role = "user", body = "the prompt"),
+ message(1, **kw),
+ message(2, streaming = True, body = "reply so far", extra = streamed_body(at)),
+ ]
+ )
+
+ out: list[tuple[str, dict, dict]] = []
+ base = capture(base_tree())
+
+ def add(name: str, tree: dict) -> None:
+ out.append((name, base, capture(tree)))
+
+ add(
+ "a settled message gains an element",
+ base_tree(extra = [{"tag": "span", "children": ["new"]}]),
+ )
+ add("a settled message's text changes", base_tree(body = "settled text, rewritten"))
+ add(
+ "a reasoning pane silently collapses",
+ base_tree(
+ extra = [{"tag": "div", "attrs": {"data-slot": "reasoning-root", "data-state": "closed"}}]
+ ),
+ )
+ add("a class list changes", base_tree(attrs = {"class": "aui-message-root flex-col"}))
+ add(
+ "a control becomes disabled",
+ base_tree(extra = [{"tag": "button", "attrs": {"disabled": ""}}]),
+ )
+ add("a message changes role", base_tree(role = "user"))
+
+ # Structural mutants that are not expressible as one message's attributes.
+ add(
+ "a settled message disappears",
+ thread(
+ [
+ message(0, role = "user", body = "the prompt"),
+ message(2, streaming = True, body = "reply so far", extra = streamed_body(at)),
+ ]
+ ),
+ )
+ add(
+ "the STREAMING message disappears",
+ thread([message(0, role = "user", body = "the prompt"), message(1)]),
+ )
+ add(
+ "the thread gains scaffolding outside every message",
+ {
+ "tag": "div",
+ "attrs": {"class": "aui-thread-root"},
+ "children": [
+ {
+ "tag": "div",
+ "attrs": {"class": "aui-thread-viewport"},
+ "children": base_tree()["children"][0]["children"],
+ },
+ {"tag": "div", "attrs": {"class": "aui-empty-state"}},
+ ],
+ },
+ )
+ add(
+ "siblings are reordered inside a settled message",
+ base_tree(extra = [{"tag": "b", "children": ["x"]}, {"tag": "i", "children": ["y"]}]),
+ )
+ out.append(
+ (
+ "siblings reordered the other way",
+ capture(
+ base_tree(extra = [{"tag": "b", "children": ["x"]}, {"tag": "i", "children": ["y"]}])
+ ),
+ capture(
+ base_tree(extra = [{"tag": "i", "children": ["y"]}, {"tag": "b", "children": ["x"]}])
+ ),
+ )
+ )
+ # An overlay lives outside the thread root, so it has its own walk and its own way of going
+ # unnoticed. Both shapes, because a menu that mounts and a menu that is rewritten are
+ # different regressions.
+ menu = {
+ "sel": '[role="menu"]',
+ "tree": {
+ "tag": "div",
+ "attrs": {"role": "menu"},
+ "children": [{"tag": "span", "children": ["Copy"]}],
+ },
+ }
+ other = {
+ "sel": '[role="menu"]',
+ "tree": {
+ "tag": "div",
+ "attrs": {"role": "menu"},
+ "children": [{"tag": "span", "children": ["Delete"]}],
+ },
+ }
+ at_tree = base_tree()
+ out.append(
+ (
+ "an overlay mounts on one arm only",
+ capture(at_tree),
+ capture(dict(at_tree, _overlays = [menu])),
+ )
+ )
+ out.append(
+ (
+ "an overlay's contents are rewritten",
+ capture(dict(at_tree, _overlays = [menu])),
+ capture(dict(at_tree, _overlays = [other])),
+ )
+ )
+ return out
+
+
+def test_the_mutant_score_is_total():
+ caught, missed = [], []
+ for name, before, after in mutants():
+ got = P.mutation_detected(before, after)
+ (caught if got["detected"] else missed).append(name)
+ assert not missed, f"MUTANT SCORE {len(caught)}/{len(caught) + len(missed)}, missed: {missed}"
+ assert len(caught) == 13, f"the battery shrank to {len(caught)}; mutants were removed"
+
+
+def test_no_mutant_is_ever_reported_as_a_match():
+ # The weaker bar, held separately, because it is the one that decides whether a change can ship
+ # green. DIFFER is the outcome that names the change; NOT COMPARABLE is the outcome that
+ # refuses to say; only MATCH lets it through, and nothing here may reach it.
+ for name, before, after in mutants():
+ assert P.compare(before, after)["verdict"] != P.MATCH, name
+
+
+def test_the_mutant_score_is_unchanged_by_the_streaming_fields():
+ # The same battery scored as the OLD instrument would score it. Identical, which is the claim:
+ # nothing that used to be caught stopped being caught. If this ever diverges from the test
+ # above, the elision has started hiding something.
+ for name, before, after in mutants():
+ old_before = {
+ k: v
+ for k, v in before.items()
+ if k
+ not in (
+ "digest_scaffold",
+ "chars_scaffold",
+ "in_flight",
+ "streaming",
+ "in_flight_unplaced",
+ )
+ }
+ old_after = {
+ k: v
+ for k, v in after.items()
+ if k
+ not in (
+ "digest_scaffold",
+ "chars_scaffold",
+ "in_flight",
+ "streaming",
+ "in_flight_unplaced",
+ )
+ }
+ assert P.mutation_detected(old_before, old_after)["detected"], name
+
+
+# ── 4. what the fix gives up, pinned rather than left implicit ───────
+
+
+def test_reordering_the_streamed_message_past_a_sibling_is_refused_not_passed():
+ """THE SECOND COST, and the one that had to be found by a mutant rather than by reading.
+
+ The per-message rows are keyed by mounted index. Swap the streamed message with the settled one
+ and the streaming row sits at index 2 on one arm and index 1 on the other, so BOTH indices are
+ in flight on one side or the other and both are withheld -- and the scaffold markers that
+ survive carry the same `assistant` role in either order. So a reorder of two same-role messages
+ involving the streamed one is demoted from a difference to a refusal.
+
+ Demoted, NOT hidden: NOT COMPARABLE is not a pass and nothing goes green on it. Pinned here so
+ the demotion is a known cost rather than something a later reader discovers.
+ """
+ a = streaming_arm(24)
+ b = capture(
+ thread(
+ [
+ message(0, role = "user", body = "the prompt"),
+ message(1, streaming = True, body = "reply so far", extra = streamed_body(24)),
+ message(2),
+ ]
+ )
+ )
+ got = P.compare(a, b)
+ assert got["verdict"] != P.MATCH
+ assert got["verdict"] == P.NOT_COMPARABLE, got
+
+
+def test_a_real_change_inside_the_streamed_message_is_refused_not_caught():
+ """THE COST, stated as a test so it cannot be forgotten.
+
+ A rendering regression that lands inside the message that happens to be streaming is no longer
+ distinguishable from stream progress, and comes back NOT COMPARABLE. It was not distinguishable
+ before either -- every action that lands in a stream is on the declared unstable list, so the
+ difference used to print under "expected to vary" and the run exited 0. The outcome moves from
+ a pass to "not measured", which is the honest one, but it is a give-up and it is written down.
+ """
+ a = streaming_arm(24)
+ b = capture(
+ thread(
+ [
+ message(0, role = "user", body = "the prompt"),
+ message(1),
+ message(
+ 2,
+ streaming = True,
+ body = "reply so far",
+ extra = streamed_body(24) + [{"tag": "span", "children": ["a real change"]}],
+ ),
+ ]
+ )
+ )
+ got = P.compare(a, b)
+ assert got["verdict"] == P.NOT_COMPARABLE
+ assert got["verdict"] != P.MATCH
+
+
+def test_a_message_that_is_in_flight_on_one_arm_only_is_still_excused():
+ # The ordinary case, and it must not read as a build difference: one arm finished the reply
+ # before its digest was taken and the other did not.
+ a = streaming_arm(81)
+ b = capture(
+ thread(
+ [
+ message(0, role = "user", body = "the prompt"),
+ message(1),
+ message(2, streaming = False, body = "reply so far", extra = streamed_body(81)),
+ ]
+ )
+ )
+ assert P.compare(a, b)["verdict"] == P.NOT_COMPARABLE
+
+
+def test_a_message_that_vanished_is_never_excused_by_being_in_flight():
+ # The elision withholds a subtree, never an element. A streamed message that is absent on one
+ # arm is a lost message, and no amount of "it was still arriving" makes that not a difference.
+ a = streaming_arm(24)
+ b = capture(thread([message(0, role = "user", body = "the prompt"), message(1)]))
+ got = P.compare(a, b)
+ assert got["verdict"] == P.DIFFER
+ # Caught one level earlier than `localise`, by the mount-count check: neither arm is windowing
+ # and they mounted different numbers of messages, which is a lost conversation and is reported
+ # as such rather than as a row that moved.
+ assert "different numbers of messages (3 vs 2)" in got["reason"], got
+
+
+# ── 5. the positive control on the streaming probe itself ────────────
+
+
+def test_a_running_reply_the_probe_could_not_place_refuses_the_pair():
+ """A scan that can return zero needs a control, and this one can.
+
+ `streamingMessages()` walks selectors written against Studio's markup. Rename `data-status` and
+ it matches nothing, every capture reads as "no reply was in flight", and the instrument returns
+ the strongest claim it has about the stream on the strength of never having looked. The app
+ publishes the same fact through the Stop button, so the disagreement is carried out of the page
+ and refused here rather than resolved into the reassuring answer.
+ """
+ a = streaming_arm(24)
+ blind = dict(streaming_arm(24), in_flight = [], in_flight_unplaced = True)
+ got = P.compare(a, blind)
+ assert got["verdict"] == P.NOT_COMPARABLE
+ assert "could not be identified" in got["reason"]
+ assert P.compare(blind, a)["verdict"] == P.NOT_COMPARABLE
+
+
+def _blind_arm(chars: int, *, prompt: str = "the prompt") -> dict:
+ """A streaming arm whose `data-status` hook went quiet, so it could not place its own stream.
+
+ The shape the treatment side of a hook-renaming build has: the app says a reply is running and
+ not one message published a streaming state.
+ """
+ arm = capture(
+ thread(
+ [
+ message(0, role = "user", body = prompt),
+ message(1, body = "settled text"),
+ message(2, streaming = True, body = "reply so far", extra = streamed_body(chars)),
+ ]
+ )
+ )
+ return dict(arm, in_flight = [], in_flight_unplaced = True)
+
+
+def test_a_settled_user_row_survives_the_blind_probe_refusal():
+ """A USER ROW IS NEVER THE REPLY BEING WRITTEN, so the refusal may not take it out.
+
+ The reachable pair is one build against another that renamed the `data-status` hook -- an
+ assistant-ui bump does exactly that -- and the same bump can restyle the user bubble. The
+ stream cannot be placed, so every assistant row is withheld correctly; the USER row is not,
+ because a stream writes into an assistant message and both arms agree this row is the user's.
+
+ Without this it left as NOT COMPARABLE with an empty `moved`, and `report` buckets a refusal as
+ blind and never consults it for the exit code, so a real rendering regression exited 0 with no
+ row on screen naming it. `compare_visible` already applies this rule to its own rows.
+ """
+ base = _blind_arm(24)
+ treat = _blind_arm(24, prompt = "the prompt, rendered differently")
+ assert treat["in_flight_unplaced"] is True
+ got = P.compare(base, treat)
+ assert got["verdict"] == P.DIFFER, got
+ assert got["moved"] == [
+ "msg0(user):%d->%dc" % (base["messages"][0]["chars"], treat["messages"][0]["chars"])
+ ], got["moved"]
+ assert "could not be identified" in got["reason"]
+ # And it is symmetric: which arm went blind cannot decide whether the finding is reported.
+ assert P.compare(treat, base)["verdict"] == P.DIFFER
+
+
+def test_a_role_that_changed_survives_the_blind_probe_refusal():
+ """The role is captured BESIDE the digest, so how far a reply has arrived cannot explain it.
+
+ A treatment that renders the live assistant row as `data-role="user"` is a structural
+ regression, and it is exactly the row the refusal is otherwise about.
+ """
+ base = _blind_arm(24)
+ treat = dict(
+ capture(
+ thread(
+ [
+ message(0, role = "user", body = "the prompt"),
+ message(1, body = "settled text"),
+ message(
+ 2,
+ role = "user",
+ streaming = True,
+ body = "reply so far",
+ extra = streamed_body(24),
+ ),
+ ]
+ )
+ ),
+ in_flight = [],
+ in_flight_unplaced = True,
+ )
+ got = P.compare(base, treat)
+ assert got["verdict"] == P.DIFFER, got
+ # The scaffold carries the role marker too, and both arms agree about generation here, so the
+ # existing scaffold rule quotes it as well. The row itself is what must not be lost.
+ assert "msg2:role assistant->user" in got["moved"], got["moved"]
+
+
+def test_the_blind_scaffold_rule_needs_run_state_evidence_the_composer_cannot_forge():
+ """SUPPRESSING A COMPOSER DIFFERENCE WITH THE COMPOSER IS ARGUING IN A CIRCLE.
+
+ The blind branch withheld the scaffold whenever `generation_disagrees` said the arms were at
+ different points in the turn -- and that predicate reads `composer_control`, the token naming
+ which control the composer rendered. So a treatment that DROPS the Stop button, renames it, or
+ selects the wrong control makes the tokens differ FOR THAT REASON, and the scaffold carrying
+ the regression went out with the refusal. `report` files a refusal under `blind` and takes its
+ exit code from `stable_bad or one_sided`, so the run went green on it.
+
+ `streaming` and `queued_idle` are read off the thread's run state, not off the composer, so
+ they are evidence the composer cannot manufacture. Here they AGREE -- both arms are generating
+ -- so there is no run-state explanation for the scaffold moving and it is a finding. This is
+ the same corroboration the settled-pair composer suppression already requires.
+ """
+ base = dict(_blind_arm(24), composer_control = "Stop generating", streaming = True)
+ treat = dict(
+ _blind_arm(24),
+ # The regression: the control is gone, so the composer renders a different subtree and the
+ # scaffold moves with it.
+ composer_control = "",
+ streaming = True,
+ digest_scaffold = "scaffold-with-no-stop-button",
+ chars_scaffold = base["chars_scaffold"] - 21,
+ )
+ # The run state itself says the two arms were doing the same thing.
+ assert P._run_state_disagrees(base, treat) is False
+ # ...while the composer-derived predicate says they were not, which is the circle.
+ assert P.generation_disagrees(base, treat) is True
+
+ got = P.compare(base, treat)
+ assert got["verdict"] == P.DIFFER, got
+ assert any("thread scaffolding outside any message" in m for m in got["moved"]), got["moved"]
+ # Symmetric: which arm lost the button cannot decide whether the finding is reported.
+ assert P.compare(treat, base)["verdict"] == P.DIFFER
+
+
+def test_the_blind_scaffold_rule_still_withholds_a_corroborated_run_state_difference():
+ """THE CONTROL. When the run state independently says one arm was generating and the other was
+ not, the composer differs BECAUSE of that, and quoting it would manufacture the wall-clock
+ false alarm this file exists to remove. The refusal is right there and must survive."""
+ base = dict(_blind_arm(24), composer_control = "Stop generating", streaming = True)
+ treat = dict(
+ _blind_arm(24),
+ composer_control = "Send message",
+ streaming = False,
+ digest_scaffold = "scaffold-with-send-button",
+ chars_scaffold = base["chars_scaffold"] + 8,
+ )
+ assert P._run_state_disagrees(base, treat) is True
+
+ got = P.compare(base, treat)
+ assert got["verdict"] == P.NOT_COMPARABLE, got
+ assert not any("thread scaffolding" in m for m in got["moved"]), got["moved"]
+
+
+def test_the_composer_refusal_says_the_scaffold_reading_is_an_aggregate():
+ """A REFUSAL THAT NAMES ONE CAUSE READS AS HAVING RULED OUT THE OTHERS.
+
+ `digest_scaffold` is one digest over the viewport, the composer dock and the empty state
+ together. The suppression is justified by the composer swap alone, but the reading it acts on
+ cannot tell that swap apart from a change to another scaffold surface in the same
+ cross-run-state capture, so such a change rides along inside the refusal.
+
+ That is a real limit of this capture and separating it needs a composer-scoped digest the
+ payload does not carry. What must not happen meanwhile is the sentence claiming more than the
+ reading supports: unqualified, it reads as "only the composer differed", which is what a reader
+ would act on. So the refusal states the aggregate and states what it could not separate.
+ """
+ settled = thread([message(0, role = "user", body = "the prompt"), message(1)])
+ base = dict(capture(settled), composer_control = "Stop generating", streaming = True)
+ treat = dict(
+ capture(settled),
+ composer_control = "Send message",
+ streaming = False,
+ digest_scaffold = "scaffold-with-send-button",
+ chars_scaffold = base["chars_scaffold"] + 8,
+ )
+ got = P.compare(base, treat)
+ # The pair really does take the composer suppression, not the blind one.
+ assert got["verdict"] == P.NOT_COMPARABLE, got
+ assert "composer dock is inside the thread root" in got["reason"], got["reason"]
+ assert "ONE AGGREGATE digest" in got["reason"], got["reason"]
+ assert "cannot separate the composer swap" in got["reason"], got["reason"]
+
+
+def test_the_streamed_row_itself_is_still_withheld_when_the_probe_is_blind():
+ """The narrowing is not a hole in the other direction.
+
+ An assistant row that differs is precisely the reading with no defined moment, and it stays
+ refused. Only rows that provably cannot be the reply being written are reported.
+ """
+ got = P.compare(_blind_arm(24), _blind_arm(48))
+ assert got["verdict"] == P.NOT_COMPARABLE, got
+ assert got["moved"] == []
+ # A SETTLED ASSISTANT row is withheld too: with the stream unplaceable, this instrument cannot
+ # prove which assistant row the reply is being written into.
+ base = _blind_arm(24)
+ treat = dict(
+ capture(
+ thread(
+ [
+ message(0, role = "user", body = "the prompt"),
+ message(1, body = "a different settled text"),
+ message(2, streaming = True, body = "reply so far", extra = streamed_body(24)),
+ ]
+ )
+ ),
+ in_flight = [],
+ in_flight_unplaced = True,
+ )
+ assert P.compare(base, treat)["verdict"] == P.NOT_COMPARABLE
+
+
+def test_a_user_row_flagged_in_flight_by_the_other_arm_is_still_withheld():
+ """The arm that COULD place its stream is believed about which rows have no defined moment."""
+ base = _blind_arm(24)
+ # The non-blind arm names index 0 as in flight. Whatever role it carries, its digest is a point
+ # in a stream on that arm, so it is not a settled row.
+ treat = dict(_blind_arm(24, prompt = "a different prompt"), in_flight = [0])
+ treat["in_flight_unplaced"] = True
+ got = P.compare(base, treat)
+ assert got["verdict"] == P.NOT_COMPARABLE, got
+ assert got["moved"] == []
+
+
+def test_an_old_payload_without_the_streaming_fields_is_scored_as_it_always_was():
+ # Not silently refused, and not silently excused: a capture recorded before the fields existed
+ # carries no claim about a stream, and falls back to the digest it does carry.
+ a = streaming_arm(24, streaming_fields = False)
+ b = streaming_arm(24, streaming_fields = False)
+ assert P.compare(a, b)["verdict"] == P.MATCH
+ assert P.compare(a, streaming_arm(48, streaming_fields = False))["verdict"] == P.DIFFER
+
+
+# ── 6. the elision itself, at the level of the shipped signature ─────
+
+
+def test_eliding_a_subtree_keeps_its_presence_its_position_and_its_role():
+ got = run_js(
+ {
+ "elided": [
+ _mark_elided(
+ thread(
+ [message(0, role = "user", body = "hi"), message(1, streaming = True, body = "a")]
+ )
+ ),
+ _mark_elided(
+ thread(
+ [
+ message(0, role = "user", body = "hi"),
+ message(1, streaming = True, body = "a completely different reply"),
+ ]
+ )
+ ),
+ _mark_elided(thread([message(0, role = "user", body = "hi")])),
+ _mark_elided(
+ thread(
+ [
+ message(0, role = "user", body = "hi"),
+ message(1, role = "user", streaming = True, body = "a"),
+ ]
+ )
+ ),
+ ]
+ }
+ )["elided"]
+ short, long_, absent, other_role = got
+ # The content inside is withheld...
+ assert short == long_
+ # ...but the element being there at all is not, and neither is what it is.
+ assert short != absent
+ assert short != other_role
+ assert "<!in-flight div role=assistant>" in short
+
+
+def test_elision_is_off_unless_asked_for():
+ tree = thread([message(0, role = "user", body = "hi"), message(1, streaming = True, body = "a")])
+ plain = run_js({"trees": [tree]})["signatures"][0]
+ assert "<!in-flight" not in plain
+ assert "a" in plain
diff --git a/tests/studio/studiobench/scene/dom.js b/tests/studio/studiobench/scene/dom.js
index 6843bb4414e..79012960040 100644
--- a/tests/studio/studiobench/scene/dom.js
+++ b/tests/studio/studiobench/scene/dom.js
@@ -42,6 +42,23 @@
return (el.textContent || "").trim();
};
+ // The two hooks the app publishes a part's progress through: assistant-ui's `data-status` on a
+ // text part (markdown-text.tsx) and `aria-busy` on the reasoning content (reasoning.tsx). Named
+ // once because the streaming scan and the control on it must never drift apart.
+ // Every control ComposerRightControls can put in the run-state slot, in no significant order.
+ // "Stop research" / "Stopping research" are included because they are the same slot, even though
+ // nothing in this benchmark can reach a research run today.
+ const RUN_STATE_CONTROLS = [
+ "Stop generating",
+ "Stop queued message",
+ "Stop research",
+ "Stopping research",
+ "Queue message",
+ "Send message",
+ ];
+
+ const STATUS_HOOK = '[data-status], [data-slot="reasoning-content"][aria-busy]';
+
const byName = (sel, name, root) =>
qa(sel, root).find((el) => nameOf(el) === name) || null;
@@ -70,9 +87,137 @@
queueButton() {
return q('button[aria-label="Queue message"]');
},
+ // THE DISPATCHED HALF OF A QUEUE RUN. `ComposerRightControls` renders this once the queued
+ // entry has been dispatched, under `isQueueRunning && !thread.isRunning` (thread.tsx), so the
+ // thread reports itself NOT running and neither `stopButton()` nor `queueButton()` matches.
+ // Read on its own, that transient came out as an ordinary idle composer: `streaming` and
+ // `queued_idle` both false, exactly as a settled Send arm reads. An arm caught here against a
+ // settled one then had a differing composer with no run-state difference to explain it, which
+ // is the shape the comparison layer treats as a rendering regression.
+ stopQueuedButton() {
+ return q('button[aria-label="Stop queued message"]');
+ },
isRunning() {
return Boolean(D.stopButton() || D.queueButton());
},
+ // WHICH RUN-STATE CONTROL THE COMPOSER IS RENDERING, as a token.
+ //
+ // `ComposerRightControls` renders exactly one of these at a time and which one is a function
+ // of the run state: Send when nothing is happening, Stop while a reply is being written, Queue
+ // while one is queued or while text sits in the box mid-reply, and the research pair while a
+ // research run is going. They are DIFFERENT SUBTREES, and the composer dock is inside
+ // `.aui-thread-root`, so `digest_scaffold` carries whichever one is up.
+ //
+ // Two arms showing different tokens differ in the scaffold FOR THAT REASON, with no rendering
+ // difference between them. `isRunning()` is too coarse to say so: it is true for Stop AND for
+ // Queue, so a queued-idle arm and a streaming arm agree on it while rendering different
+ // controls. The token is the thing the scaffold actually contains.
+ runStateControl() {
+ for (const name of RUN_STATE_CONTROLS) {
+ if (byName("button", name)) return name;
+ }
+ return "";
+ },
+ // THE PROMPT QUEUE'S OWN SURFACE. `PromptQueueStack` renders the waiting prompts inside the
+ // composer root with the accessible name "Prompt queue, <n> of <m>", and that is the only
+ // place the queue states its own existence in the DOM. Scoped to the thread root so a queue
+ // running on ANOTHER thread, which the sidebar also renders, is not read as this one's.
+ promptQueue() {
+ return q('[aria-label^="Prompt queue,"]', D.threadRoot());
+ },
+ // A REPLY IS ACTUALLY BEING WRITTEN, which is NOT the question `isRunning()` answers.
+ //
+ // `isRunning()` has to accept the Queue button: with text in the composer a running thread
+ // renders that button and NO Stop button (`queueDisabled` depends on the composer having a
+ // queueable prompt), so an action that waited for Stop would wait out its budget on a live
+ // stream. Every caller that asks "may I send now" wants exactly that broad reading.
+ //
+ // It is the wrong reading for a positive control on the streaming probe, because
+ // `ComposerRightControls` renders "Queue message" in a SECOND place: under
+ // `isQueueRunning && !thread.isRunning`, while a queued prompt waits to be dispatched and
+ // nothing at all is generating. `isRunning()` cannot tell that queued-idle interval from a
+ // live stream whose `data-status` hooks have gone quiet, and those two need opposite
+ // treatment -- one is an ordinary settled thread, the other is an instrument that has stopped
+ // working.
+ //
+ // The queued-idle button always comes with the queue surface: `syncPromptQueueUI` marks the
+ // entry `dispatched` from the active item, and `getPromptQueueUIItemsForRun` drops only
+ // DISPATCHED items, so an undispatched active item -- the one that renders "Queue message"
+ // rather than "Stop queued message" -- is always in the list the stack renders.
+ //
+ // WHAT THIS GIVES UP, pinned in scene/selftest/test_studiobench_queued_idle_live.py: while a
+ // queue run holds further prompts AND a reply is streaming AND the composer has text, the
+ // queue surface is up and the only control is the Queue button, so this reads false and the
+ // control is not armed for that capture. Under-claiming, and cheap: probe blindness is a
+ // renamed selector, which is global, so every other capture in the run still catches it.
+ // A RESEARCH RUN IS A GENERATION THIS PREDICATE CANNOT SEE, and deliberately so for now.
+ // `ComposerRightControls` renders "Stop research" / "Stopping research" under
+ // `isResearchActive`, which neither `stopButton()` nor `queueButton()` matches, and a research
+ // report renders through `MarkdownPreview` rather than the assistant text part, so
+ // `streamingMessages()` finds no `data-status` for it either. All THREE are blind to it
+ // together.
+ //
+ // Not patched, because nothing here can start one: `ResearchMessage` is gated on
+ // `message.metadata` and the seeder writes `None` for every message, and no action, corpus
+ // unit or scene touches the composer's research toggle. Fixing one of the three would leave
+ // two that still disagree with it. If a research scene is ever added, move all three in the
+ // same change, and add the report's own busy hook to `STATUS_HOOK` at the same time.
+ generating() {
+ if (D.stopButton()) return true;
+ if (!D.queueButton()) return false;
+ return !D.promptQueue();
+ },
+ // WHICH MESSAGES ARE STILL BEING WRITTEN, read from the app's own published state rather than
+ // guessed at from `isRunning()` plus "it is probably the last one".
+ //
+ // assistant-ui gives every text part a status and Studio serialises it: markdown-text.tsx
+ // renders `<div data-status={status.type}>` around the Streamdown tree, so a part that is
+ // still arriving reads `data-status="running"` and a finished one reads `"complete"`. The
+ // reasoning pane publishes the same fact as `aria-busy` on `[data-slot="reasoning-content"]`
+ // (reasoning.tsx), which is a separate part of the same message and can be running while the
+ // answer is not, or the other way round. Either one means this message's DOM is mid-flight.
+ //
+ // Both are the APP's statements about its own state. Nothing here reads a timer, a character
+ // count or "the last assistant message", all of which are the benchmark inventing a fact the
+ // page already publishes -- and inventing it is how you end up attributing a stream to the
+ // wrong message on the arm that renders faster.
+ streamingMessages() {
+ return qa("[data-role]").filter(
+ (m) => m.querySelector('[data-status="running"], [aria-busy="true"]') !== null,
+ );
+ },
+ // ── IS THE STREAMING PROBE BLIND, OR IS THERE SIMPLY NOTHING FOR IT TO SEE ──────────
+ //
+ // `streamingMessages()` returning nothing has three completely different causes, and the
+ // positive control on it is only worth having if they are told apart.
+ //
+ // THE HOOK IS GONE a build renamed or dropped `data-status`. It is one line in
+ // markdown-text.tsx and it is rendered for `complete` parts as
+ // well as `running` ones, so on a working build EVERY assistant
+ // message that has rendered a part carries it, and on a blinded
+ // build none does.
+ // THE ROW IS NOT MOUNTED a windowed arm scrolled away from the tail has unmounted the
+ // message it is writing into. That is what windowing is for.
+ // THE ROW HAS NO PARTS YET between the send being accepted and the reply's first part
+ // arriving, the assistant message is mounted with zero content
+ // parts and thread.tsx renders "Generating..." in its place. It
+ // publishes no status because it has nothing to publish yet, and
+ // `send_turn` returns the instant `isRunning()` flips, so a
+ // capture lands here twice a film.
+ //
+ // Scoped to ASSISTANT messages throughout: a user message never publishes `data-status` even
+ // on a perfectly working build, because only the assistant parts are rendered through
+ // `MarkdownText` (thread.tsx `ASSISTANT_PART_COMPONENTS`). A window holding only user rows
+ // would otherwise read as a build with no hook.
+ statusHookPresent() {
+ return D.assistantMessages().some((m) => m.querySelector(STATUS_HOOK) !== null);
+ },
+ // Whether the message a reply would be written INTO is publishing parts this probe can read.
+ // False means it has none yet, which is the third case above and not a broken instrument.
+ lastAssistantPublishesStatus() {
+ const last = D.lastAssistantMessage();
+ return Boolean(last && last.querySelector(STATUS_HOOK));
+ },
messages() {
return qa("[data-role]");
},
diff --git a/tests/studio/studiobench/scene/parity.js b/tests/studio/studiobench/scene/parity.js
index cdc467511d0..db3fdc24b1f 100644
--- a/tests/studio/studiobench/scene/parity.js
+++ b/tests/studio/studiobench/scene/parity.js
@@ -176,7 +176,15 @@
// neither presence nor value, unlike VOLATILE_ATTRS which keeps the presence. Optional and off
// by default: every existing caller (the whole-thread digest, the per-message rows, the overlays
// and the node-driven unit tests) passes nothing and gets exactly what it got before.
- const signature = (root, dropAttrs) => {
+ //
+ // `elide`, when given, is a Set of ELEMENTS whose subtree this digest does not serialise. It is
+ // not a way of ignoring them: a marker carrying the tag and the element's `data-role` is written
+ // in their place, so the element's PRESENCE, its position among its siblings and its role are
+ // still compared and a message that vanished still moves the digest. Only the content inside it
+ // is withheld. The one caller is the streamed-message elision in `capture()`; the whole argument
+ // for it is stated there. Optional and off by default, so every existing caller passes nothing
+ // and gets byte-for-byte what it got before.
+ const signature = (root, dropAttrs, elide) => {
if (!root) return "";
const parts = [];
const walk = (el, depth) => {
@@ -184,6 +192,15 @@
// exactly the silent false negative this instrument exists to rule out. The marker is left
// in the signature so anything deeper is visible as "not walked" rather than as "absent".
if (depth > 40) { parts.push("<!depth-cap>"); return; }
+ if (elide && elide.has(el)) {
+ // Named, not silent. A reader of the raw signature sees exactly which element was held
+ // back and why, rather than a hole they have to infer from a length.
+ parts.push(
+ "<!in-flight " + el.tagName.toLowerCase() +
+ " role=" + ((el.getAttribute && el.getAttribute("data-role")) || "?") + ">"
+ );
+ return;
+ }
parts.push("<" + el.tagName.toLowerCase());
const names = [];
for (const attr of el.attributes) {
@@ -604,7 +621,13 @@
VIS.ever.add(entry.target.__sbOrdinal);
}
}
- const nodes = (D().messages && D().messages()) || [];
+ const dom = D();
+ const nodes = (dom.messages && dom.messages()) || [];
+ // THE SAME NODE SET THE POSITIVE CONTROL BELOW COUNTS. The rows used to re-walk the
+ // `data-status` / `aria-busy` selectors inline, so "the rows read the same hooks as the
+ // control" was true only while two copies happened to agree. Read from one call and the
+ // control cannot fire while a row still claims to be in flight, or the reverse.
+ const live = new Set((dom.streamingMessages && dom.streamingMessages()) || []);
const byOrdinal = {};
let mounted_ever_visible = 0;
// TWO MOUNTED ROWS CANNOT BE ONE MESSAGE, and until this counter existed nothing said so.
@@ -660,11 +683,59 @@
role: el.getAttribute("data-role") || "?",
digest: hash(sig),
chars: sig.length,
+ // Still being written at capture time, so its digest names a point in a stream rather
+ // than a rendering. Carried here for the same reason as in the structural capture and
+ // handled the same way by `compare_visible`: residue, never a difference.
+ in_flight: live.has(el),
};
}
const ever = [...VIS.ever].sort((a, b) => a - b);
+ // THE SAME POSITIVE CONTROL THE STRUCTURAL CAPTURE CARRIES, because this payload is scored
+ // by `compare_visible` on its own and never consults the structural one. The per-row
+ // `in_flight` above is taken from the SAME `streamingMessages()` call, so it goes quiet in
+ // the same way and at the same moment, and the arms of an A/B are two DIFFERENT builds --
+ // `--ab REF` installs the treatment under its own `UNSLOTH_STUDIO_HOME` -- so a renamed
+ // hook on the treatment only is the asymmetric case rather than a symmetric one that
+ // cancels out. Both rows then read
+ // `in_flight: false`, one arm's reply is mid-tail and the other's has finished, and the
+ // loop in `compare_visible` scores that as a rendering difference: the wall-clock false
+ // alarm this whole change exists to remove.
+ //
+ // READ GLOBALLY, not over the visible rows. "Is a reply being written" and "is the message
+ // it is being written into on screen" are different questions, and a reply streaming below
+ // the fold is an ordinary state that must not refuse anything.
+ const generating = dom.generating
+ ? Boolean(dom.generating())
+ : Boolean(dom.isRunning && dom.isRunning());
+ // WHY THE PROBE IS QUIET, which is three questions and not one. See
+ // `dom.statusHookPresent` / `dom.lastAssistantPublishesStatus`.
+ //
+ // the last assistant message IS publishing parts and none of them says running
+ // -> the hook's VOCABULARY changed. Blind, unless this arm is windowing, in which case
+ // the message being written may not be the last one mounted and nothing here can
+ // tell the two apart.
+ // the last assistant message publishes NOTHING
+ // -> it has no parts yet, which is ordinary -- unless no assistant message anywhere
+ // publishes anything, and then the hook itself is gone. Blind on any arm, windowed
+ // or not, because a settled message would still be carrying it.
+ const lastPublishes = dom.lastAssistantPublishesStatus
+ ? Boolean(dom.lastAssistantPublishesStatus())
+ : false;
+ const anyPublishes = dom.statusHookPresent ? Boolean(dom.statusHookPresent()) : true;
+ const windowedArm = dom.isWindowed ? Boolean(dom.isWindowed()) : false;
+ const probeBlind = lastPublishes ? !windowedArm : !anyPublishes;
return {
visible_attempted: true,
+ streaming: generating,
+ // Carried so a reader can tell the two zero-in-flight readings apart in the record, not
+ // only in the verdict: a stream this capture could not see, versus a hook that is gone.
+ status_hook_present: anyPublishes,
+ // `hookGone` and not merely "nothing is running": see `dom.statusHookPresent`. A windowed
+ // arm scrolled away from the tail can UNMOUNT the message being written, and
+ // `streamingMessages()` can only scan mounted DOM, so `live.size` is zero on a build
+ // whose hooks are perfectly intact. That is the ordinary state this mode exists to
+ // score, and refusing it would discard the settled rows that WERE on screen.
+ in_flight_unplaced: Boolean(generating && live.size === 0 && probeBlind),
// Every ordinal the viewport ever showed during the window, INCLUDING any that have
// since been unmounted. The gap between this and `messages` is the honest measure of
// what a windowed arm could not be asked about at capture time.
@@ -727,9 +798,87 @@
const isThread = Boolean(found && found !== document.body &&
found.classList && found.classList.contains("aui-thread-root"));
const root = found || document.body;
+ const nodes = (dom.messages && dom.messages()) || [];
+ // ── THE STREAMED MESSAGE, AND WHY IT GETS ITS OWN DIGEST ────────────────────────────────
+ //
+ // A message that is still being written has no defined moment. The two arms of an A/B are
+ // two cells run back to back against ONE pacer: the bytes on the wire are identical by
+ // construction, but each arm has its own send click, its own `t0` and its own paint clock,
+ // and the digest is taken at a wall-clock offset in the film rather than at a character
+ // count in the stream. So the two arms are compared at two different points in the same
+ // reply, and the difference that comes back is wall clock wearing the shape of a UI change.
+ //
+ // That is the failure this whole file's neighbours were written against: measuring at a
+ // moment whose meaning is not stable across the things being compared. It is the same
+ // mistake as a census taken on a `data-state` flip, and it is worse here because the
+ // renderer amplifies it. Mid-stream, Studio does not show a PREFIX of the finished reply:
+ // `parseIncompleteMarkdown` runs remend over the tail and closes whatever construct is
+ // half-arrived, KaTeX renders the repaired formula (and, while it will not parse, writes
+ // the parse error and its character offset into a `title`), Shiki re-tokenises the repaired
+ // fence, and the trailing code block carries `data-incomplete`. None of that is monotonic
+ // in how much text has arrived, which is why the difference cannot be recognised by its
+ // size and why a same-length mismatch here is not evidence of a missed volatile.
+ //
+ // MEASURED, on the shipped corpus (unit 9, 4,238 characters) driven through remend, KaTeX
+ // and Shiki into the shipped `signature()`. Stepping the arrived text by the pacer's own
+ // 24-character chunk, 175 of the 175 adjacent pairs produce a different digest -- one chunk
+ // of skew is enough to fail a stable action outright. At one-character resolution the
+ // serialised length moves DOWNWARDS at 52 of 4,237 steps and 34 pairs of distinct stream
+ // positions serialise to exactly the same length with different digests, which is the
+ // same-length drift that reads as a normaliser gap. It also cuts the other way: 398 of the
+ // 4,237 one-character advances move nothing at all.
+ //
+ // WHAT IS DONE ABOUT IT. The in-flight message is named, and a SECOND whole-thread digest
+ // is taken with its subtree elided -- a marker in its place, so its presence, its position
+ // and its role are still compared and a message that vanished still moves the digest. The
+ // comparison layer scores the settled document on the settled digest and refuses a verdict
+ // on the in-flight message rather than calling it a difference. It is NOT normalised away
+ // and it is not folded into a pass: see `analysis/parity.compare`.
+ //
+ // THE SCAFFOLD DIGEST ELIDES EVERY MESSAGE, NOT ONLY THE STREAMING ONES, and that is not
+ // over-reach -- it is the only version of this that is comparable across arms. Whether a
+ // given message is in flight is a property of ONE arm at the moment ITS digest was taken,
+ // and the ordinary case is precisely that the arms disagree about it: one has finished the
+ // reply and the other has not. A thread digest that elided each arm's own in-flight set
+ // would then be two different walks, and the two would differ because of the elision
+ // itself. Eliding all of them makes the walk identical on both sides by construction.
+ //
+ // Nothing is given up by decomposing it this way. The whole-thread digest is the scaffold
+ // plus every message subtree in place; the scaffold keeps a marker carrying each message's
+ // tag, role and position, and every message subtree is digested on its own row below. So a
+ // message that moved, vanished, changed role or changed content still moves something, and
+ // the comparison layer can withhold ONE of those rows without losing the rest.
+ const inFlightNodes = (dom.streamingMessages && dom.streamingMessages()) || [];
+ const inFlight = new Set(inFlightNodes);
+ const running = Boolean(dom.isRunning && dom.isRunning());
+ // The narrower reading, and the positive control below is the one place that needs it.
+ // `isRunning()` is true whenever the composer is refusing a fresh send, and a prompt
+ // waiting in the queue on an IDLE thread refuses one too. See `dom.generating`.
+ const generating = dom.generating ? Boolean(dom.generating()) : running;
+ // Whether the app still publishes the status contract at all. See
+ // `dom.statusHookPresent`: a hook that is GONE is a blind instrument, a hook that is
+ // present with nothing running is an ordinary settled or not-yet-mounted thread.
+ // WHY THE PROBE IS QUIET, which is three questions and not one. See
+ // `dom.statusHookPresent` / `dom.lastAssistantPublishesStatus`.
+ //
+ // the last assistant message IS publishing parts and none of them says running
+ // -> the hook's VOCABULARY changed. Blind, unless this arm is windowing, in which case
+ // the message being written may not be the last one mounted and nothing here can
+ // tell the two apart.
+ // the last assistant message publishes NOTHING
+ // -> it has no parts yet, which is ordinary -- unless no assistant message anywhere
+ // publishes anything, and then the hook itself is gone. Blind on any arm, windowed
+ // or not, because a settled message would still be carrying it.
+ const lastPublishes = dom.lastAssistantPublishesStatus
+ ? Boolean(dom.lastAssistantPublishesStatus())
+ : false;
+ const anyPublishes = dom.statusHookPresent ? Boolean(dom.statusHookPresent()) : true;
+ const windowedArm = dom.isWindowed ? Boolean(dom.isWindowed()) : false;
+ const probeBlind = lastPublishes ? !windowedArm : !anyPublishes;
const whole = signature(root);
+ const scaffold = signature(root, undefined, new Set(nodes));
const messages = [];
- const nodes = (dom.messages && dom.messages()) || [];
+ const in_flight = [];
for (let i = 0; i < nodes.length; i++) {
const sig = signature(nodes[i]);
const row = {
@@ -738,6 +887,10 @@
digest: hash(sig),
chars: sig.length,
};
+ if (inFlight.has(nodes[i])) {
+ row.in_flight = true;
+ in_flight.push(i);
+ }
if (want_raw) row.raw = sig;
messages.push(row);
}
@@ -761,6 +914,58 @@
root_kind: isThread ? "thread" : "body",
digest: hash(whole),
chars: whole.length,
+ // The thread with every message replaced by a marker: the viewport, the composer, the
+ // empty state, and each message's tag, role and position. `digest` = this plus the
+ // per-message rows below, which is what lets a single message be withheld from the
+ // comparison without the other two thirds of the reading going with it.
+ digest_scaffold: hash(scaffold),
+ chars_scaffold: scaffold.length,
+ // Mounted indices of the messages that were still being written. An EMPTY list on a
+ // page where nothing is running is the ordinary case and means what it says.
+ in_flight,
+ streaming: running,
+ // THE POSITIVE CONTROL, and it is not decoration. `streamingMessages()` walks selectors
+ // written against Studio's markup: rename `data-status` and it goes quiet, matches
+ // nothing, and every reading silently becomes "nothing was streaming" -- which is the
+ // strongest claim this capture can make about the stream and would be supported by no
+ // observation at all. The app says a reply is running through a different control (the
+ // Stop button), so when the two disagree the disagreement is carried out rather than
+ // resolved here, and `analysis/parity.comparability` refuses the pair.
+ //
+ // IT IS `generating()` AND NOT `isRunning()` that is compared against, and that
+ // difference is most of this field's meaning. `isRunning()` is also true while a queued
+ // prompt waits on a thread that is doing NOTHING, and on that thread no message
+ // publishes a running status because none is running -- so reading it here would refuse
+ // an ordinary settled pair before `compare()` ever reached its settled digests, and
+ // would report the instrument as broken to say it. That is this file's own failure
+ // mode: reading at a moment whose meaning is not stable across the things being
+ // compared. See `dom.generating`.
+ //
+ // AND IT REQUIRES THE HOOK TO BE GONE, not merely quiet. `streamingMessages()` scans
+ // MOUNTED DOM, so it also returns nothing in the gap between a send being accepted and
+ // the reply's first part rendering, and on an arm that has unmounted the message it is
+ // writing into. Neither is a broken instrument. See `dom.statusHookPresent`.
+ in_flight_unplaced: Boolean(
+ generating && inFlightNodes.length === 0 && probeBlind
+ ),
+ status_hook_present: anyPublishes,
+ // The queued-idle interval itself, recorded rather than resolved away, so a reader can
+ // tell why a capture with `streaming: true` placed no message in flight.
+ // INCLUDING THE DISPATCHED WAIT. `isRunning()` matches "Stop generating" and
+ // "Queue message" only, so the interval where a dispatched queue entry renders
+ // "Stop queued message" recorded `streaming` and `queued_idle` both false -- identical
+ // to a settled Send arm. A pair straddling that transient then had a differing composer
+ // with no run-state difference to account for it, and the comparison layer is entitled
+ // to call that a rendering regression. It is queue timing.
+ queued_idle: Boolean(
+ (running || (dom.stopQueuedButton ? Boolean(dom.stopQueuedButton()) : false)) &&
+ !generating
+ ),
+ // The composer's run-state slot, as a token. Carried so the comparison layer can tell a
+ // scaffold that differs because the two arms were at different points in one turn from a
+ // scaffold that differs because something was rendered differently. See
+ // `dom.runStateControl` and `analysis/parity.generation_disagrees`.
+ composer_control: dom.runStateControl ? dom.runStateControl() : null,
messages,
overlays,
styles,
diff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_queued_idle_live.py b/tests/studio/studiobench/scene/selftest/test_studiobench_queued_idle_live.py
new file mode 100644
index 00000000000..ad1d623312a
--- /dev/null
+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_queued_idle_live.py
@@ -0,0 +1,731 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""THE POSITIVE CONTROL ON THE STREAMING PROBE, read off a real DOM instead of a fixture dict.
+
+`in_flight_unplaced` says "the app says a reply is running and not one message published a
+streaming state, so the probe has gone blind". It is checked offline in
+fixture/selftest/test_studiobench_parity_streamed.py by handing `compare()` a capture with the flag
+already set, which proves what the flag DOES and nothing at all about when `capture()` sets it --
+and when it is set is the whole of its value, because a control that fires on an ordinary settled
+thread costs exactly the coverage it was added to protect.
+
+The state that fires it wrongly is QUEUED-IDLE: a prompt waiting in the queue while the thread is
+doing nothing. `ComposerRightControls` renders `aria-label="Queue message"` there, under
+`isQueueRunning && !thread.isRunning`, and it renders the same button on a RUNNING thread whose
+composer has text -- `queueDisabled` swaps Stop for Queue. So the button alone cannot tell a
+waiting queue from a live stream, and `dom.isRunning()`, which accepts it because every action that
+asks "may I send now" needs the broad reading, cannot either.
+
+Three states, all of them rendered from the shipped markup, and the claim is about which pairs of
+them a reader can tell apart:
+
+ STREAMING a reply is being written; the last message publishes `data-status="running"`.
+ QUEUED-IDLE a prompt waits in the queue, nothing is being written, every message is settled.
+ BLIND a reply really is being written and the `data-status` hook was renamed, so
+ `streamingMessages()` matches nothing. This is what the control exists for.
+
+QUEUED-IDLE and BLIND are the pair that matters. Reading the queue button as "running" makes them
+the SAME observation -- both `in_flight_unplaced: true` -- and `compare()` then refuses a settled
+queued-idle pair, in front of its settled digests, as a broken instrument. That refusal is not a
+pass, but it is not a reading either, and a real difference elsewhere in the thread is lost with it.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+_HERE = Path(__file__).resolve()
+_STUDIO_TESTS = _HERE.parents[3]
+if str(_STUDIO_TESTS) not in sys.path:
+ sys.path.insert(0, str(_STUDIO_TESTS))
+
+from studiobench.analysis import parity as P # noqa: E402
+
+_DOM_JS = _STUDIO_TESTS / "studiobench" / "scene" / "dom.js"
+_PARITY_JS = _STUDIO_TESTS / "studiobench" / "scene" / "parity.js"
+_THREAD_TSX = (
+ _STUDIO_TESTS.parents[1]
+ / "studio"
+ / "frontend"
+ / "src"
+ / "components"
+ / "assistant-ui"
+ / "thread.tsx"
+)
+
+#: The running branch: `AuiIf thread.isRunning` renders Queue instead of Stop once the composer
+#: holds a queueable prompt, wrapped in a positioning div.
+_QUEUE_BUTTON_RUNNING = """
+<div class="ml-1.5 flex items-center">
+ <button class="aui-composer-send size-9 rounded-full" aria-label="Queue message">
+ <span class="aui-sr-only">Queue message</span>
+ </button>
+</div>
+"""
+
+#: The queued branch: `isQueueRunning && !thread.isRunning`, with the active item undispatched.
+_QUEUE_BUTTON_IDLE = """
+<button class="aui-composer-send ml-1.5 size-9 rounded-full" aria-label="Queue message">
+ <span class="aui-sr-only">Queue message</span>
+</button>
+"""
+
+_STOP_BUTTON = """
+<button class="aui-composer-cancel size-9 rounded-full" aria-label="Stop generating">
+ <span class="aui-sr-only">Stop generating</span>
+</button>
+"""
+
+#: The DISPATCHED queued branch: `isQueueRunning && !thread.isRunning` with `queueEntry.dispatched`,
+#: which renders a stop control the thread does not report itself running behind. Neither
+#: `stopButton()` nor `queueButton()` matches it, so on its own it reads exactly like a settled
+#: composer. `getPromptQueueUIItemsForRun` drops dispatched items, so the queue surface can be gone
+#: here too -- which is why this state has to be recognised from its own control.
+_STOP_QUEUED_BUTTON = """
+<button class="aui-composer-cancel ml-1.5 size-9 rounded-full" aria-label="Stop queued message">
+ <span class="aui-sr-only">Stop queued message</span>
+</button>
+"""
+
+#: `PromptQueueStack`, which renders inside the composer root whenever the run has an item left to
+#: show. An undispatched active item is always one of them, so this surface is up in every state
+#: that renders the queued-idle Queue button.
+_QUEUE_STACK = """
+<div aria-label="Prompt queue, 1 of 2">
+ <div>a prompt that has not been dispatched</div>
+</div>
+"""
+
+
+def _page(
+ *,
+ control: str,
+ queue_stack: bool,
+ statuses: list[str | None],
+ tail: str,
+ overlay: str = "",
+) -> str:
+ """A thread, a composer, and one composer control. `statuses` is per assistant message, and
+ None renames the hook the probe walks -- which is what going blind looks like.
+
+ THE HOOK IS ON ASSISTANT ROWS ONLY, and the rename is too, because that is where it lives:
+ only assistant parts are rendered through `MarkdownText`, which is the single component that
+ emits `<div data-status={status.type}>` (thread.tsx `ASSISTANT_PART_COMPONENTS`), and
+ `dom.statusHookPresent` is scoped to assistant messages for exactly that reason. A fixture that
+ also moved the attribute on the USER rows would make going blind change a surface the real
+ rename cannot touch, and any rule that reads settled user rows would score the fixture's own
+ artefact rather than the build.
+ """
+ messages = []
+ for i, status in enumerate(statuses):
+ role = "user" if i % 2 == 0 else "assistant"
+ if role == "user":
+ messages.append('<div data-role="user"><div>the prompt</div></div>')
+ continue
+ body = f"reply {i} {tail if i == len(statuses) - 1 else ''}"
+ attr = 'data-state="running"' if status is None else f'data-status="{status}"'
+ messages.append(f'<div data-role="{role}"><div {attr}>{body}</div></div>')
+ return f"""<!doctype html><meta charset="utf-8">
+<div class="aui-thread-root">
+ <div class="aui-thread-viewport">{"".join(messages)}</div>
+ <div class="aui-composer-root">
+ {_QUEUE_STACK if queue_stack else ""}
+ <textarea aria-label="Message input">typed while it ran</textarea>
+ {control}
+ </div>
+</div>{overlay}"""
+
+
+STREAMING = dict(
+ control = _QUEUE_BUTTON_RUNNING,
+ queue_stack = False,
+ statuses = ["complete", "complete", "complete", "running"],
+)
+QUEUED_IDLE = dict(
+ control = _QUEUE_BUTTON_IDLE,
+ queue_stack = True,
+ statuses = ["complete", "complete", "complete", "complete"],
+)
+BLIND = dict(
+ control = _STOP_BUTTON,
+ queue_stack = False,
+ statuses = [None, None, None, None],
+)
+#: The cost of reading the queue surface, pinned rather than left for a later reader to find: a
+#: queue run with a prompt still waiting, a reply genuinely streaming, and text in the composer.
+#: The surface is up and the Queue button is the only control, so the control is not armed.
+QUEUED_AND_STREAMING_BLIND = dict(
+ control = _QUEUE_BUTTON_RUNNING,
+ queue_stack = True,
+ statuses = [None, None, None, None],
+)
+
+
+def _skip_reason() -> str | None:
+ try:
+ from playwright.sync_api import sync_playwright # noqa: F401
+ except Exception as exc: # noqa: BLE001
+ return f"playwright is not installed: {exc}"
+ return None
+
+
+pytestmark = pytest.mark.skipif(_skip_reason() is not None, reason = _skip_reason() or "")
+
+
[email protected](scope = "module")
+def browser():
+ from playwright.sync_api import sync_playwright
+ with sync_playwright() as p:
+ try:
+ b = p.chromium.launch(args = ["--no-sandbox"])
+ except Exception as exc: # noqa: BLE001
+ pytest.skip(f"chromium could not be launched: {exc}")
+ yield b
+ b.close()
+
+
+def page(browser):
+ pg = browser.new_page(viewport = {"width": 900, "height": 700})
+ yield pg
+ pg.close()
+
+
+def _capture(
+ page,
+ state: dict,
+ tail: str = "settled",
+) -> dict:
+ page.set_content(_page(tail = tail, **state))
+ # After the content, not before it: `set_content` does not reliably run init scripts, and the
+ # symptom is `window.__sb` simply not existing, which reads like a broken instrument.
+ page.add_script_tag(content = _DOM_JS.read_text(encoding = "utf-8"))
+ page.add_script_tag(content = _PARITY_JS.read_text(encoding = "utf-8"))
+ got = page.evaluate("() => window.__sb.parity.capture()")
+ assert got.get("parity_attempted") is True, got
+ return got
+
+
+def _reading(cap: dict) -> dict:
+ return {k: cap.get(k) for k in ("streaming", "in_flight", "in_flight_unplaced", "queued_idle")}
+
+
+# ── the two states the instrument has to tell apart ──────────────────
+
+
+def test_a_waiting_queue_is_not_read_as_a_blind_probe(page):
+ """THE REGRESSION. Same button, same empty in-flight list, opposite meanings."""
+ idle = _capture(page, QUEUED_IDLE)
+ blind = _capture(page, BLIND)
+ # Both refuse a fresh send, which is what `isRunning()` is asked and why it cannot decide this.
+ assert idle["streaming"] is True and blind["streaming"] is True
+ assert idle["in_flight"] == [] and blind["in_flight"] == []
+ # And they are still two different readings.
+ assert _reading(idle) != _reading(blind)
+ assert idle["in_flight_unplaced"] is False, idle
+ assert idle["queued_idle"] is True, idle
+ assert blind["in_flight_unplaced"] is True, blind
+ assert blind["queued_idle"] is False, blind
+
+
+def test_a_settled_queued_idle_pair_is_scored_rather_than_refused(page):
+ """What the conflation cost, at the level of the verdict.
+
+ Two queued-idle arms whose settled threads genuinely differ. Reading the queue button as a
+ running reply sets the control on both, and `streaming_probe` refuses the pair inside
+ `compare()` BEFORE the per-message digests are reached, so the difference is never localised.
+ """
+ base = _capture(page, QUEUED_IDLE, tail = "alpha")
+ treat = _capture(page, QUEUED_IDLE, tail = "omega")
+ assert base["digest"] != treat["digest"]
+ got = P.compare(base, treat)
+ assert got["verdict"] == P.DIFFER, got
+ assert any(m.startswith("msg3(") for m in got["moved"]), got["moved"]
+ # The pair the control IS for still refuses, so this is a narrowing and not a removal.
+ refused = P.compare(base, _capture(page, BLIND))
+ assert refused["verdict"] == P.NOT_COMPARABLE
+ assert "could not be identified" in refused["reason"]
+
+
+def test_a_real_stream_is_still_placed_and_still_scored(page):
+ """The coverage this must not cost: the running branch renders the SAME button."""
+ cap = _capture(page, STREAMING)
+ assert cap["streaming"] is True
+ assert cap["in_flight"] == [3], cap
+ assert cap["in_flight_unplaced"] is False and cap["queued_idle"] is False
+
+
+def test_what_reading_the_queue_surface_gives_up(page):
+ """A queue with a prompt still waiting, a live stream, and text in the composer.
+
+ The surface is up and Stop is not rendered, so this reads as queued-idle and the control is not
+ armed for this capture. Under-claiming rather than over-claiming, and bounded: a probe goes
+ blind by a renamed selector, which is global, so the control still fires on the run's other
+ captures. Pinned so the cost is a known one.
+ """
+ cap = _capture(page, QUEUED_AND_STREAMING_BLIND)
+ assert cap["in_flight"] == []
+ assert cap["in_flight_unplaced"] is False, cap
+ assert cap["queued_idle"] is True, cap
+
+
+# ── the fixtures are the app's markup, not the test's ────────────────
+
+
+def test_the_shipped_composer_still_renders_the_two_queue_buttons():
+ """The fixtures above are hand-written, so they can drift into asserting themselves.
+
+ What makes them a claim about Studio is that the app still renders BOTH Queue buttons and still
+ names the queue surface, so this reads that out of the shipped TSX. If Studio stops rendering
+ the queued-idle button the conflation is gone and this file should go with it; if it renames
+ the queue surface, `dom.promptQueue()` goes quiet and the conflation is back.
+ """
+ if not _THREAD_TSX.exists():
+ pytest.skip(f"the shipped composer is not in this checkout: {_THREAD_TSX}")
+ src = _THREAD_TSX.read_text(encoding = "utf-8")
+ assert src.count('aria-label="Queue message"') == 2, (
+ "ComposerRightControls no longer renders the Queue button in exactly two places; "
+ "re-read which of them can appear on an idle thread"
+ )
+ assert "aria-label={`Prompt queue, ${current} of ${total}`}" in src, (
+ "PromptQueueStack no longer names itself, so dom.promptQueue() matches nothing and the "
+ "queued-idle interval is indistinguishable again"
+ )
+ assert 'aria-label="Stop queued message"' in src
+
+
+# ── what the blind-probe refusal may NOT take out with it ────────────
+
+#: An overlay is walked from `document`, OUTSIDE `.aui-thread-root`. Its digest therefore carries
+#: neither the streamed message nor the composer, which is what makes it readable on a pair whose
+#: stream could not be placed.
+_MENU = '<div role="menu"><div class="item">Rename</div></div>'
+_MENU_CHANGED = '<div role="menu"><div class="item">Rename thread</div></div>'
+#: The composer of a thread that is NOT generating. `_STOP_BUTTON` is the same composer generating.
+_SEND_BUTTON = (
+ '<button class="aui-composer-send" aria-label="Send message">'
+ '<span class="aui-sr-only">Send message</span></button>'
+)
+
+
+def _capture_html(page, html: str) -> dict:
+ """`_capture`, for a page built outside the `STATE` dictionaries."""
+ page.set_content(html)
+ page.add_script_tag(content = _DOM_JS.read_text(encoding = "utf-8"))
+ page.add_script_tag(content = _PARITY_JS.read_text(encoding = "utf-8"))
+ got = page.evaluate("() => window.__sb.parity.capture()")
+ assert got.get("parity_attempted") is True, got
+ return got
+
+
+def test_an_overlay_difference_survives_the_blind_probe_refusal(page):
+ """A menu that changed while the stream could not be placed is still a finding.
+
+ Without this the refusal took it out, and `structural_report` buckets a refusal as blind and
+ never consults it for the exit code, so a real menu or dialog regression went green.
+ """
+ base = _capture_html(page, _page(tail = "same", overlay = _MENU, **BLIND))
+ treat = _capture_html(page, _page(tail = "same", overlay = _MENU_CHANGED, **BLIND))
+ assert base["in_flight_unplaced"] is True and treat["in_flight_unplaced"] is True
+ assert len(base["overlays"]) == len(treat["overlays"]) == 1
+ got = P.compare(base, treat)
+ assert got["verdict"] == P.DIFFER, got
+ assert len(got["moved"]) == 1 and got["moved"][0].startswith('overlay0[[role="menu"]]'), got
+ assert "walked outside the thread root" in got["reason"]
+
+
+def test_a_settled_user_row_survives_the_blind_probe_refusal(page):
+ """A user row cannot be the reply being written, so the refusal may not take it out either.
+
+ Read off the real DOM rather than a fixture dict, and on the state the control is actually for:
+ both arms generating with the hook renamed. Only assistant parts publish `data-status`, so the
+ rename does not touch this row -- what moved it is the build.
+
+ Without this it left as NOT COMPARABLE with an empty `moved`, and `report` buckets a refusal as
+ blind and never consults it for the exit code, so the run went green on it.
+ """
+ base = _capture_html(page, _page(tail = "same", **BLIND))
+ treat = _capture_html(
+ page,
+ _page(tail = "same", **BLIND).replace(
+ "<div>the prompt</div>",
+ "<div>the prompt, rendered differently</div>",
+ 1,
+ ),
+ )
+ assert base["in_flight_unplaced"] is True and treat["in_flight_unplaced"] is True
+ got = P.compare(base, treat)
+ assert got["verdict"] == P.DIFFER, got
+ assert any(m.startswith("msg0(user)") for m in got["moved"]), got["moved"]
+
+
+def test_matching_overlays_still_leave_the_blind_pair_refused(page):
+ """The narrowing is not a hole: with nothing independent to say, the refusal stands."""
+ base = _capture_html(page, _page(tail = "alpha", overlay = _MENU, **BLIND))
+ treat = _capture_html(page, _page(tail = "omega", overlay = _MENU, **BLIND))
+ assert base["digest"] != treat["digest"]
+ got = P.compare(base, treat)
+ assert got["verdict"] == P.NOT_COMPARABLE, got
+ assert got["moved"] == []
+
+
+def test_the_scaffold_is_not_an_independent_surface_and_here_is_why(page):
+ """WHY the scaffold is deliberately NOT consulted beside the overlays.
+
+ `ThreadPrimitive.Root` wraps `ThreadComposerDock` (thread.tsx), so the composer is inside
+ `.aui-thread-root` and inside the scaffold, and the composer is exactly what changes when a
+ reply starts and stops. On the pair the refusal is about -- one arm generating with a quiet
+ hook, the other finished -- the scaffold therefore differs BECAUSE one arm is generating, and
+ reporting that as a rendering difference would manufacture the wall-clock false alarm this file
+ exists to remove.
+
+ Two threads with identical messages, differing only in the composer control.
+ """
+ settled = dict(QUEUED_IDLE, control = _SEND_BUTTON, queue_stack = False)
+ generating = dict(settled, control = _STOP_BUTTON)
+ a = _capture_html(page, _page(tail = "same", **settled))
+ b = _capture_html(page, _page(tail = "same", **generating))
+ assert [m["digest"] for m in a["messages"]] == [m["digest"] for m in b["messages"]]
+ assert a["digest_scaffold"] != b["digest_scaffold"], (
+ "if this ever holds, the composer has left the thread root and the scaffold may be "
+ "consulted beside the overlays"
+ )
+
+
+# ── the composer is not a rendering difference ───────────────────────
+#
+# The pair this whole change is about: one arm has finished its reply, the other is still writing
+# it. Its messages are withheld correctly. Its COMPOSER was not, because the dock is inside
+# `.aui-thread-root` and the scaffold therefore carries Stop on one arm and Send on the other.
+
+_SETTLED_STATUSES = ["complete", "complete", "complete", "complete"]
+_STREAMING_STATUSES = ["complete", "complete", "complete", "running"]
+
+
+def _finished(**kw):
+ return dict(control = _SEND_BUTTON, queue_stack = False, statuses = _SETTLED_STATUSES, **kw)
+
+
+def _writing(**kw):
+ return dict(control = _STOP_BUTTON, queue_stack = False, statuses = _STREAMING_STATUSES, **kw)
+
+
+def test_a_scaffold_only_difference_across_a_finished_and_a_running_arm_is_refused(page):
+ """THE REGRESSION, on the pair this mode exists for.
+
+ Every settled message row is byte-identical; the only thing that moved is the composer, and it
+ moved because one arm was generating. Reported as DIFFER this read as a rendering change, with
+ the single claim `thread scaffolding outside any message (373->381c)`.
+ """
+ base = _capture_html(page, _page(tail = "arrived at last", **_finished()))
+ treat = _capture_html(page, _page(tail = "arr", **_writing()))
+ assert base["streaming"] is False and treat["streaming"] is True
+ assert treat["in_flight"] == [3] and treat["in_flight_unplaced"] is False
+ assert [m["digest"] for m in base["messages"][:3]] == [
+ m["digest"] for m in treat["messages"][:3]
+ ]
+ assert base["digest_scaffold"] != treat["digest_scaffold"]
+ got = P.compare(base, treat)
+ assert got["verdict"] == P.NOT_COMPARABLE, got
+ assert "composer dock is inside the thread root" in got["reason"]
+ assert got["moved"] == []
+
+
+def test_the_same_two_stream_positions_with_both_arms_running_are_unchanged(page):
+ """WHY THE NULL COULD NOT SEE IT. One build against itself at two points in one stream: both
+ arms render Stop, the scaffolds match, and the bias cancels inside the control."""
+ a = _capture_html(page, _page(tail = "arrived at last", **_writing()))
+ b = _capture_html(page, _page(tail = "arr", **_writing()))
+ assert a["digest_scaffold"] == b["digest_scaffold"]
+ assert P.compare(a, b)["verdict"] == P.NOT_COMPARABLE
+
+
+def test_a_real_message_difference_is_still_reported_across_a_generation_disagreement(page):
+ """The withholding is not a blanket. It applies only when the scaffold is the ONLY thing that
+ moved; a settled message that differs is reported exactly as before."""
+ base = _capture_html(page, _page(tail = "arrived at last", **_finished()))
+ treat_statuses = list(_STREAMING_STATUSES)
+ treat = _capture_html(
+ page,
+ _page(
+ tail = "arr",
+ control = _STOP_BUTTON,
+ queue_stack = False,
+ statuses = treat_statuses,
+ overlay = "",
+ ),
+ )
+ # Change a SETTLED message on the treatment arm as well.
+ treat2 = _capture_html(
+ page,
+ _page(
+ tail = "arr",
+ control = _STOP_BUTTON,
+ queue_stack = False,
+ statuses = treat_statuses,
+ ).replace("reply 1 ", "reply 1 rewritten "),
+ )
+ assert treat["messages"][1]["digest"] != treat2["messages"][1]["digest"]
+ got = P.compare(base, treat2)
+ assert got["verdict"] == P.DIFFER, got
+ assert any(m.startswith("msg1(") for m in got["moved"]), got["moved"]
+
+
+def test_a_scaffold_difference_with_both_arms_agreeing_is_still_a_difference(page):
+ """And the coverage this must not cost: when the arms agree about generation, the composer is
+ comparable again and a scaffolding change is reported."""
+ base = _capture_html(page, _page(tail = "same", **_finished()))
+ treat = _capture_html(
+ page,
+ _page(tail = "same", **_finished()).replace(
+ ">typed while it ran<",
+ ">a different draft left in the box<",
+ ),
+ )
+ assert base["streaming"] == treat["streaming"]
+ got = P.compare(base, treat)
+ assert got["verdict"] == P.DIFFER, got
+ assert got["moved"] == [
+ "thread scaffolding outside any message (%d->%dc)"
+ % (base["chars_scaffold"], treat["chars_scaffold"])
+ ], got["moved"]
+
+
+def test_the_blind_branch_reads_the_scaffold_when_the_arms_agree_about_generation(page):
+ """The correct form of the scaffold half of the earlier review item.
+
+ Refused there because the composer is a function of generation. When both arms are generating,
+ that objection does not apply and a scaffolding change is a finding even though the stream
+ could not be placed.
+ """
+ base = _capture_html(page, _page(tail = "same", **BLIND))
+ treat = _capture_html(
+ page,
+ _page(tail = "same", **BLIND).replace(
+ '<textarea aria-label="Message input">typed while it ran</textarea>',
+ '<textarea aria-label="Message input">typed while it ran, differently</textarea>',
+ ),
+ )
+ assert base["in_flight_unplaced"] is True and treat["in_flight_unplaced"] is True
+ assert base["streaming"] == treat["streaming"]
+ got = P.compare(base, treat)
+ assert got["verdict"] == P.DIFFER, got
+ assert any("thread scaffolding" in m for m in got["moved"]), got["moved"]
+
+
+#: The composer regression this branch has to report rather than excuse: the run-state slot is
+#: empty because the treatment dropped its Send button. `runStateControl` finds none of the six
+#: controls and returns "", so `composer_control` differs while the thread's own run state does
+#: not.
+_NO_CONTROL = '<div class="ml-1.5 flex items-center"></div>'
+
+
+def test_a_composer_regression_between_two_settled_arms_is_reported(page):
+ """THE CIRCLE. `generation_disagrees` reads `composer_control`, so a composer that regressed
+ supplied its own excuse: the refusal said the arms were at different points in the turn on the
+ authority of the very surface whose difference was in question.
+
+ Both arms here are settled. Nothing is generating, nothing is queued, every message and overlay
+ agrees, and the treatment simply has no Send button. That is as plain a rendering regression as
+ this tool can be shown, and NOT COMPARABLE would take it out of the exit code entirely, since
+ `report` files a refusal under `blind` and scores only `stable_bad or one_sided`.
+ """
+ base = _capture_html(page, _page(tail = "same", **_finished()))
+ treat = _capture_html(
+ page,
+ _page(tail = "same", **dict(_finished(), control = _NO_CONTROL)),
+ )
+ # The run state agrees on both independent readings; only the composer moved.
+ assert base["streaming"] is False and treat["streaming"] is False
+ assert bool(base["queued_idle"]) is False and bool(treat["queued_idle"]) is False
+ assert base["composer_control"] == "Send message" and treat["composer_control"] == ""
+ assert P.generation_disagrees(base, treat) is True
+ assert base["digest_scaffold"] != treat["digest_scaffold"]
+ assert [m["digest"] for m in base["messages"]] == [m["digest"] for m in treat["messages"]]
+
+ got = P.compare(base, treat)
+ assert got["verdict"] == P.DIFFER, got
+ assert any("scaffolding" in m for m in got["moved"]), got["moved"]
+
+
+def test_a_finished_against_a_running_arm_is_still_refused_after_that(page):
+ """And the suppression this must not cost: `streaming` disagrees, so the run state itself says
+ the two arms were at different points in one turn and the composer is not evidence of a
+ change."""
+ base = _capture_html(page, _page(tail = "arrived at last", **_finished()))
+ treat = _capture_html(page, _page(tail = "arr", **_writing()))
+ assert base["streaming"] is False and treat["streaming"] is True
+ got = P.compare(base, treat)
+ assert got["verdict"] == P.NOT_COMPARABLE, got
+ assert "composer dock is inside the thread root" in got["reason"]
+
+
+def test_a_dispatched_queue_wait_is_a_run_state_not_a_rendering_difference(page):
+ """THE TRANSIENT THAT READ AS IDLE.
+
+ Once a queued entry is dispatched, `ComposerRightControls` renders "Stop queued message" under
+ `isQueueRunning && !thread.isRunning`, so the thread says it is not running and neither control
+ `isRunning()` matches is present. Both `streaming` and `queued_idle` therefore came back false,
+ which is exactly how a settled Send arm reads.
+
+ An arm caught in that interval against a settled one then had a differing composer and a
+ differing scaffold with NO run-state difference to account for it -- and that is precisely the
+ shape the comparison layer is entitled to call a rendering regression, now that the scaffold
+ suppression requires independent run-state evidence. It is queue timing, so it must refuse.
+ """
+ dispatched = _capture_html(
+ page,
+ _page(tail = "same", **dict(QUEUED_IDLE, control = _STOP_QUEUED_BUTTON, queue_stack = False)),
+ )
+ settled = _capture_html(
+ page,
+ _page(tail = "same", **dict(QUEUED_IDLE, control = _SEND_BUTTON, queue_stack = False)),
+ )
+ # The composer really does differ, which is what makes this the interesting pair.
+ assert dispatched["composer_control"] != settled["composer_control"]
+ # ...and the run state now says why, off the run state rather than off the composer token.
+ assert bool(dispatched["queued_idle"]) is True, dispatched
+ assert bool(settled["queued_idle"]) is False, settled
+ assert P._run_state_disagrees(dispatched, settled) is True
+
+ assert P.compare(dispatched, settled)["verdict"] == P.NOT_COMPARABLE
+ assert P.compare(settled, dispatched)["verdict"] == P.NOT_COMPARABLE
+
+
+def test_the_queued_idle_arm_against_a_settled_one_is_still_refused(page):
+ """The other legitimate suppression: `isRunning()` cannot separate queued-idle from settled, so
+ `queued_idle` is what carries this pair. Without it the Queue button would read as a
+ regression."""
+ base = _capture_html(page, _page(tail = "same", **QUEUED_IDLE))
+ treat = _capture_html(
+ page,
+ _page(tail = "same", **dict(QUEUED_IDLE, control = _SEND_BUTTON, queue_stack = False)),
+ )
+ assert base["composer_control"] != treat["composer_control"]
+ assert bool(base["queued_idle"]) != bool(treat["queued_idle"]), (
+ base["queued_idle"],
+ treat["queued_idle"],
+ )
+ assert P.compare(base, treat)["verdict"] == P.NOT_COMPARABLE
+
+
+# ── the style probe walks the run-state control too ──────────────────
+#
+# `report` now collects the style verdict BEFORE it buckets a structural refusal, because the
+# computed-style probe is an independent reading and the refusal is not about it. That makes the
+# probe's own reading of the composer swap visible for the first time, and the probe walks
+# `button[aria-label="Send message"]` and `button[aria-label="Stop generating"]` as SEPARATE
+# selectors whose names go into its signature. So the pairs the refusals above exist to withhold
+# arrived at the advisory line instead.
+
+
+def _capture_html_raw(page, html: str) -> dict:
+ """`_capture_html`, keeping `styles.sig` so a test can say WHY the digest moved."""
+ page.set_content(html)
+ page.add_script_tag(content = _DOM_JS.read_text(encoding = "utf-8"))
+ page.add_script_tag(content = _PARITY_JS.read_text(encoding = "utf-8"))
+ got = page.evaluate("() => window.__sb.parity.capture({ raw: true })")
+ assert got.get("parity_attempted") is True, got
+ return got
+
+
+def _style_values(cap: dict) -> list[str]:
+ """The probe's readings with the selector NAMES dropped: just the three properties, in order."""
+ return [entry.split(":", 1)[1] for entry in cap["styles"]["sig"].split(";") if ":" in entry]
+
+
+def test_the_style_probe_does_not_report_a_control_swap_as_a_css_regression(page):
+ """THE ADVISORY THAT WAS NOT ABOUT CSS.
+
+ One arm still generating, the other settled: the structural pair is refused as run-state
+ timing, and the style probe walks `Stop generating` on one side and `Send message` on the
+ other. Its signature carries the selector that matched, so the digest moves while `display`,
+ `visibility` and `pointer-events` are IDENTICAL on every element -- asserted here rather than
+ asserted about, off the raw signature.
+ """
+ settled = _capture_html_raw(page, _page(tail = "same", **_finished()))
+ writing = _capture_html_raw(page, _page(tail = "same", **_writing()))
+ # Same number of elements, same three properties on all of them, different digest.
+ assert settled["styles"]["elements"] == writing["styles"]["elements"]
+ assert _style_values(settled) == _style_values(writing), (
+ _style_values(settled),
+ _style_values(writing),
+ )
+ assert settled["styles"]["digest"] != writing["styles"]["digest"]
+ # ...and the run state says why, off the run state rather than off the composer.
+ assert settled["streaming"] is False and writing["streaming"] is True
+ verdict, reason = P.compare_styles(settled, writing)
+ assert verdict == P.NOT_COMPARABLE, (verdict, reason)
+ assert "run-state controls" in reason, reason
+ assert P.compare(settled, writing)["style_verdict"] == P.NOT_COMPARABLE
+
+
[email protected]("control", [_QUEUE_BUTTON_IDLE, _STOP_QUEUED_BUTTON])
+def test_a_queue_control_missing_from_the_selector_list_is_not_a_css_regression(page, control):
+ """The other flavour, and it does not even reach the digest.
+
+ Neither queue control is in `STYLE_SELECTORS`, so a queued arm matches one element FEWER than
+ a settled one and the probe reports "a different number of elements" -- over a page whose CSS
+ is byte-identical. Both the undispatched wait and the dispatched one.
+ """
+ settled = _capture_html_raw(page, _page(tail = "same", **_finished()))
+ queued = _capture_html_raw(
+ page,
+ _page(tail = "same", **dict(QUEUED_IDLE, control = control, queue_stack = False)),
+ )
+ assert settled["styles"]["elements"] != queued["styles"]["elements"]
+ assert bool(settled["queued_idle"]) != bool(queued["queued_idle"]) or (
+ settled["streaming"] != queued["streaming"]
+ )
+ assert P.compare_styles(settled, queued)[0] == P.NOT_COMPARABLE
+ assert P.compare(settled, queued)["style_verdict"] == P.NOT_COMPARABLE
+
+
+def test_a_real_style_regression_between_two_arms_in_one_run_state_is_still_reported(page):
+ """THE COVERAGE THIS MUST NOT COST. Same control on both arms, and the treatment hides the
+ viewport from CSS alone -- no structural trace whatever, which is the only thing this probe
+ exists to see."""
+ base = _capture_html_raw(page, _page(tail = "same", **_finished()))
+ treat = _capture_html_raw(
+ page,
+ "<style>.aui-thread-viewport { visibility: hidden }</style>"
+ + _page(tail = "same", **_finished()),
+ )
+ assert base["digest"] == treat["digest"], "the difference must be CSS only"
+ assert _style_values(base) != _style_values(treat)
+ verdict, reason = P.compare_styles(base, treat)
+ assert verdict == P.DIFFER, (verdict, reason)
+
+
+def test_a_composer_that_lost_its_control_is_still_a_style_finding(page):
+ """AND THE SUPPRESSION IS NOT KEYED ON THE COMPOSER TOKEN ALONE. The treatment simply has no
+ Send button: the token differs, the probe matches one element fewer, and the run state agrees
+ on both independent readings -- so this is a rendering regression and it is reported."""
+ base = _capture_html_raw(page, _page(tail = "same", **_finished()))
+ treat = _capture_html_raw(
+ page,
+ _page(tail = "same", **dict(_finished(), control = _NO_CONTROL)),
+ )
+ assert base["composer_control"] == "Send message" and treat["composer_control"] == ""
+ assert P._run_state_disagrees(base, treat) is False
+ verdict, reason = P.compare_styles(base, treat)
+ assert verdict == P.DIFFER, (verdict, reason)
+ assert "different number of elements" in reason
+
+
+def test_what_the_style_elision_gives_up(page):
+ """Pinned rather than left for a later reader: on a pair that DOES straddle the control swap,
+ a genuine CSS regression elsewhere goes with it. The probe reads ONE aggregate digest over
+ every matched element, so the swap cannot be separated from anything else inside it. The
+ verdict is a refusal and not a MATCH, so nothing here reads as a pass."""
+ settled = _capture_html_raw(page, _page(tail = "same", **_finished()))
+ writing_and_broken = _capture_html_raw(
+ page,
+ "<style>.aui-thread-viewport { visibility: hidden }</style>"
+ + _page(tail = "same", **_writing()),
+ )
+ assert P.compare_styles(settled, writing_and_broken)[0] == P.NOT_COMPARABLE
diff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_visible_blind_probe_live.py b/tests/studio/studiobench/scene/selftest/test_studiobench_visible_blind_probe_live.py
new file mode 100644
index 00000000000..803ad9528ed
--- /dev/null
+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_visible_blind_probe_live.py
@@ -0,0 +1,389 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""THE STREAMING PROBE'S POSITIVE CONTROL IN VISIBLE MODE, in a real browser.
+
+`compare_visible` scores windowed pairs from `parityVisible.capture()` alone. It never sees the
+structural capture, so `in_flight_unplaced` -- the control that catches a `data-status` hook that
+has gone quiet -- did not reach it, while the per-row `in_flight` it DOES read walks those exact
+selectors.
+
+That gap is asymmetric-by-construction, which is what makes it reachable rather than theoretical.
+The two arms of an A/B are two different builds: the merge base and the head. A head that renames
+or drops the status hook is precisely the change the control exists to catch, and it is renamed on
+ONE arm only, so nothing cancels out. Both rows then read `in_flight: false`, one arm's reply is
+mid-tail while the other's has finished, and the per-ordinal loop scores those two points in one
+stream as a rendering difference. That is the wall-clock false alarm this change exists to remove,
+arriving through the one door it had left open.
+
+Read GLOBALLY and not over the visible rows, which is the other half of the decision: "a reply is
+being written" and "the message it is being written into is on screen" are different questions, and
+a reply streaming below the fold is an ordinary state that must refuse nothing.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+_HERE = Path(__file__).resolve()
+_STUDIO_TESTS = _HERE.parents[3]
+if str(_STUDIO_TESTS) not in sys.path:
+ sys.path.insert(0, str(_STUDIO_TESTS))
+
+from studiobench.analysis import parity as P # noqa: E402
+
+_DOM_JS = _STUDIO_TESTS / "studiobench" / "scene" / "dom.js"
+_PARITY_JS = _STUDIO_TESTS / "studiobench" / "scene" / "parity.js"
+
+_STOP_BUTTON = (
+ '<button class="aui-composer-cancel" aria-label="Stop generating">'
+ '<span class="aui-sr-only">Stop generating</span></button>'
+)
+_SEND_BUTTON = (
+ '<button class="aui-composer-send" aria-label="Send message">'
+ '<span class="aui-sr-only">Send message</span></button>'
+)
+
+
+def _page(
+ *,
+ tail: str,
+ tail_running: bool,
+ generating: bool,
+ hook: str = "data-status",
+ running_value: str = "running",
+ tall: bool = False,
+ user_body: str = "message 3",
+ live_role: str = "assistant",
+ drop_tail: bool = False,
+ tail_has_parts: bool = True,
+) -> str:
+ """A four-message thread in a viewport that shows all of it.
+
+ `hook` is the attribute the last assistant message publishes its status through. The shipped
+ name is `data-status`; anything else is a build whose hook this instrument does not know, which
+ is what going blind looks like from the outside.
+ """
+ rows = []
+ for i in range(1, 5):
+ if drop_tail and i == 4:
+ # The windowed case: the arm still DECLARES four messages through `aria-setsize`, and
+ # has unmounted the one it is writing into. That is a thread the instrument can see
+ # three quarters of, not an instrument that has stopped working.
+ continue
+ role = "user" if i % 2 else "assistant"
+ last = i == 4
+ if last:
+ # `live_role` is what the arm CALLS the row it is writing into. The shipped build says
+ # assistant; a build that says otherwise is the regression ordinal-role parity exists
+ # to catch, and it is asked here rather than assumed.
+ role = live_role
+ body = tail if last else f"message {i}"
+ if i == 3:
+ body = user_body
+ if last and not tail_has_parts:
+ # The gap between the send being accepted and the reply's first part arriving. The
+ # assistant message is mounted and publishes nothing, because it has nothing to
+ # publish: thread.tsx renders "Generating..." in place of any part.
+ rows.append(
+ f'<div class="row" aria-posinset="{i}" aria-setsize="4">'
+ f'<div data-role="{role}"><span>Generating...</span></div></div>'
+ )
+ continue
+ status = running_value if (last and tail_running) else "complete"
+ # THE HOOK IS RENAMED ON EVERY MESSAGE, not only the streamed one. `data-status` is a single
+ # line in markdown-text.tsx and it is rendered for `complete` parts as well as `running`
+ # ones, so a build that renames it renames it everywhere. A fixture that renamed it on one
+ # message would be describing a build that does not exist, and would then be the only
+ # evidence that the control fires.
+ attr = f'{hook}="{status}"'
+ rows.append(
+ f'<div class="row" aria-posinset="{i}" aria-setsize="4">'
+ f'<div data-role="{role}"><div {attr}>{body}</div></div></div>'
+ )
+ height = "600px" if tall else "60px"
+ return f"""<!doctype html><meta charset="utf-8">
+<style>
+ body {{ margin: 0; }}
+ .aui-thread-viewport {{ height: 400px; overflow-y: auto; }}
+ [data-role] {{ height: {height}; }}
+</style>
+<div class="aui-thread-root">
+ <div class="aui-thread-viewport">{"".join(rows)}</div>
+ <div class="aui-composer-root">
+ <textarea aria-label="Message input"></textarea>
+ {_STOP_BUTTON if generating else _SEND_BUTTON}
+ </div>
+</div>"""
+
+
+def _skip_reason() -> str | None:
+ try:
+ from playwright.sync_api import sync_playwright # noqa: F401
+ except Exception as exc: # noqa: BLE001
+ return f"playwright is not installed: {exc}"
+ return None
+
+
+pytestmark = pytest.mark.skipif(_skip_reason() is not None, reason = _skip_reason() or "")
+
+
[email protected](scope = "module")
+def browser():
+ from playwright.sync_api import sync_playwright
+ with sync_playwright() as p:
+ try:
+ b = p.chromium.launch(args = ["--no-sandbox"])
+ except Exception as exc: # noqa: BLE001
+ pytest.skip(f"chromium could not be launched: {exc}")
+ yield b
+ b.close()
+
+
+def _capture(browser, **kw) -> dict:
+ """One capture, on a PAGE OF ITS OWN.
+
+ `set_content` rewrites the document through `document.write`, which keeps the JS context, so a
+ second call finds `window.__sb` already there, skips re-initialising it, and leaves the
+ observer bound to the previous document's viewport. The symptom is a capture that reports the
+ PREVIOUS page's visible set -- a fixture bug that would read as a finding.
+ """
+ page = browser.new_page(viewport = {"width": 900, "height": 700})
+ try:
+ page.set_content(_page(**kw))
+ page.add_script_tag(content = _DOM_JS.read_text(encoding = "utf-8"))
+ page.add_script_tag(content = _PARITY_JS.read_text(encoding = "utf-8"))
+ got = page.evaluate("() => window.__sb.parityVisible.watch()")
+ assert got.get("visible_attempted") is True, got
+ # IntersectionObserver's first delivery is asynchronous.
+ page.wait_for_timeout(150)
+ cap = page.evaluate("async () => await window.__sb.parityVisible.capture()")
+ assert cap.get("visible_attempted") is True, cap
+ return cap
+ finally:
+ page.close()
+
+
+#: The base arm: an ordinary settled thread on the shipped build.
+_SETTLED = dict(tail = "the whole reply, arrived", tail_running = False, generating = False)
+#: THE TREATMENT THAT WENT BLIND, and the shape matters. `data-status` is one line in
+#: markdown-text.tsx and it is rendered for `complete` parts as well as `running` ones, so a build
+#: that renames the ATTRIBUTE renames it on every message and every settled row differs too -- which
+#: is a rendering difference in its own right and is reported as one. The interesting blindness is a
+#: build that changed the status VOCABULARY: `complete` still reads `complete`, so every settled row
+#: is byte-identical, and the only thing lost is the ability to see that a reply is being written.
+_BLIND = dict(
+ tail = "the whole reply, arr", running_value = "streaming", tail_running = True, generating = True
+)
+#: The cruder form: the attribute itself is gone. Kept because it is the one blindness a WINDOWED
+#: arm can still be caught at, where a missing row is otherwise an ordinary state.
+_BLIND_ATTR = dict(
+ tail = "the whole reply, arr", hook = "data-state", tail_running = True, generating = True
+)
+#: The same mid-stream moment on a build whose hook IS known. Already handled, as residue.
+_MIDSTREAM = dict(tail = "the whole reply, arr", tail_running = True, generating = True)
+
+
+def test_a_blinded_treatment_is_refused_not_scored_as_a_rendering_difference(browser):
+ """THE REGRESSION, end to end: two points in one stream, scored as a difference."""
+ base = _capture(browser, **_SETTLED)
+ treat = _capture(browser, **_BLIND)
+ # Same messages on screen, so nothing above the digest comparison can refuse this pair.
+ assert base["ever_visible"] == treat["ever_visible"] == [1, 2, 3, 4]
+ # And every row on both arms claims to be settled, which is the false statement.
+ assert not any(r["in_flight"] for r in base["messages"].values())
+ assert not any(r["in_flight"] for r in treat["messages"].values())
+ assert base["messages"]["4"]["digest"] != treat["messages"]["4"]["digest"]
+
+ assert treat["in_flight_unplaced"] is True, treat
+ assert base["in_flight_unplaced"] is False, base
+ got = P.compare_visible(base, treat)
+ assert got["verdict"] == P.NOT_COMPARABLE, got
+ assert "could not be identified" in got["reason"]
+ assert P.compare_visible(treat, base)["verdict"] == P.NOT_COMPARABLE
+
+
+def test_the_same_moment_on_a_build_with_the_hook_is_still_residue(browser):
+ """The path that already worked must keep working, and by the route it already took."""
+ base = _capture(browser, **_SETTLED)
+ treat = _capture(browser, **_MIDSTREAM)
+ assert treat["messages"]["4"]["in_flight"] is True
+ assert treat["in_flight_unplaced"] is False, treat
+ got = P.compare_visible(base, treat)
+ assert got["verdict"] == P.NOT_COMPARABLE
+ assert got["not_digested"] == [4], got
+
+
+def test_a_settled_pair_is_not_refused(browser):
+ """The coverage this must not cost: nothing is generating, so nothing is withheld."""
+ base = _capture(browser, **_SETTLED)
+ treat = _capture(browser, **_SETTLED)
+ assert base["streaming"] is False and treat["streaming"] is False
+ assert P.compare_visible(base, treat)["verdict"] == P.MATCH
+
+
+def test_a_reply_streaming_below_the_fold_refuses_nothing(browser):
+ """Why the control is read globally rather than over the visible rows.
+
+ Tall messages, so the streamed last one is off screen. It is placed -- the hook is intact and
+ `streamingMessages()` finds it -- so the probe is not blind, and a capture that read only the
+ rows it could see would refuse a pair for being unable to see something it was never claiming
+ to have seen.
+ """
+ cap = _capture(browser, **dict(_MIDSTREAM, tall = True))
+ assert 4 not in cap["ever_visible"], cap["ever_visible"]
+ assert cap["streaming"] is True
+ assert cap["in_flight_unplaced"] is False, cap
+
+
+def test_a_lost_conversation_is_still_a_finding_while_a_reply_runs(browser):
+ """The ordering, held: the refusal sits AFTER the two lost-conversation findings.
+
+ A treatment that puts different messages on screen is a difference whether or not its stream
+ could be placed, exactly as `compare` keeps `mount_count_mismatch` ahead of the same refusal.
+ """
+ base = _capture(browser, **_SETTLED)
+ treat = _capture(browser, **dict(_BLIND, tall = True))
+ assert treat["in_flight_unplaced"] is True
+ assert base["ever_visible"] != treat["ever_visible"]
+ got = P.compare_visible(base, treat)
+ assert got["verdict"] == P.DIFFER, got
+ assert "DIFFERENT MESSAGES on screen" in got["reason"]
+
+
+# ── what the refusal may NOT take out with it ────────────────────────
+#
+# The blind-probe refusal is about rows whose meaning depends on where the stream had got to. Two
+# kinds of row in this payload provably do not: a row both arms call the user's, because a reply is
+# written into an assistant message; and a row whose ROLE changed, because a role is captured beside
+# the digest and how far a reply has arrived says nothing about whose it is. Both used to leave here
+# as NOT COMPARABLE with an empty `moved`, and `visible_report` buckets a refusal as blind and never
+# consults it for the exit code, so the run went green on them.
+
+
+def test_a_changed_user_row_survives_the_blind_refusal(browser):
+ base = _capture(browser, **_SETTLED)
+ treat = _capture(browser, **dict(_BLIND, user_body = "the user message, rewritten"))
+ assert treat["in_flight_unplaced"] is True, treat
+ # Row 3 is the user's on both arms and differs; row 4 is the one that cannot be read.
+ assert base["messages"]["3"]["role"] == treat["messages"]["3"]["role"] == "user"
+ assert base["messages"]["3"]["digest"] != treat["messages"]["3"]["digest"]
+ got = P.compare_visible(base, treat)
+ assert got["verdict"] == P.DIFFER, got
+ assert [m for m in got["moved"] if m.startswith("ordinal 3(user)")] == got["moved"], got[
+ "moved"
+ ]
+ assert "cannot be the reply being written" in got["reason"]
+
+
+def test_the_blind_refusal_still_covers_the_assistant_rows(browser):
+ """The narrowing must not become a hole: only the provable rows come through."""
+ base = _capture(browser, **_SETTLED)
+ treat = _capture(browser, **_BLIND)
+ assert treat["in_flight_unplaced"] is True
+ assert base["messages"]["4"]["digest"] != treat["messages"]["4"]["digest"]
+ got = P.compare_visible(base, treat)
+ assert got["verdict"] == P.NOT_COMPARABLE, got
+ assert got["moved"] == []
+
+
+def test_a_role_change_on_the_live_row_is_reported_not_elided(browser):
+ """The row is in flight on the treatment arm, so its DIGEST is withheld. Its role is not.
+
+ The digest and the role are two separate readings of the same row, and only one of them names a
+ point in a stream. Eliding both meant a treatment that renders the live assistant row as the
+ user's came back NOT COMPARABLE.
+ """
+ base = _capture(browser, **_SETTLED)
+ treat = _capture(browser, **dict(_MIDSTREAM, live_role = "user"))
+ assert treat["messages"]["4"]["in_flight"] is True, treat["messages"]["4"]
+ assert base["messages"]["4"]["role"] == "assistant"
+ assert treat["messages"]["4"]["role"] == "user"
+ got = P.compare_visible(base, treat)
+ assert got["verdict"] == P.DIFFER, got
+ assert "ordinal 4:role assistant->user" in got["moved"], got["moved"]
+
+
+def test_the_same_row_with_the_same_role_is_still_residue(browser):
+ """The control on the test above: without the role change it stays a refusal."""
+ base = _capture(browser, **_SETTLED)
+ treat = _capture(browser, **_MIDSTREAM)
+ got = P.compare_visible(base, treat)
+ assert got["verdict"] == P.NOT_COMPARABLE
+ assert got["not_digested"] == [4], got
+
+
+# ── a row that is not there is not an instrument that stopped working ─
+
+
+def test_a_windowed_arm_that_unmounted_the_live_row_is_not_read_as_blind(browser):
+ """THE FALSE POSITIVE THE CONTROL USED TO HAVE, and the one this mode exists for.
+
+ `streamingMessages()` scans MOUNTED DOM. A windowed arm scrolled away from the tail unmounts the
+ message it is writing into -- that is the whole point of windowing -- so the scan returns
+ nothing on a build whose hooks are perfectly intact. Refusing there discards the settled rows
+ that WERE on screen, which is the coverage visible mode is for.
+
+ The arm still declares four messages through `aria-setsize`, so the capture can tell the
+ difference between a thread it can see part of and a thread that has nothing to say.
+ """
+ cap = _capture(browser, **dict(_MIDSTREAM, drop_tail = True))
+ assert cap["streaming"] is True
+ assert cap["status_hook_present"] is True
+ assert 4 not in cap["ever_visible"], cap["ever_visible"]
+ assert cap["in_flight_unplaced"] is False, cap
+
+
+def test_a_windowed_arm_is_still_caught_when_the_hook_itself_is_gone(browser):
+ """The narrowing is not a hole. A missing ROW explains a quiet scan; a missing ATTRIBUTE does
+ not, because the settled rows would still be publishing it."""
+ cap = _capture(browser, **dict(_BLIND_ATTR, drop_tail = True))
+ assert cap["status_hook_present"] is False
+ assert cap["in_flight_unplaced"] is True, cap
+
+
+def test_a_full_mount_is_still_caught_when_only_the_STATUS_VALUE_changed(browser):
+ """And the reverse: on a full mount the row cannot be missing, so a quiet scan is blindness
+ even though the attribute is still there. This is the case a hook-presence test alone would
+ have lost, and it is the likelier build change of the two."""
+ cap = _capture(browser, **_BLIND)
+ assert cap["status_hook_present"] is True
+ assert cap["in_flight_unplaced"] is True, cap
+
+
+def test_what_the_windowed_narrowing_gives_up(browser):
+ """Pinned rather than left implicit: a WINDOWED arm whose status VALUE changed is not caught.
+
+ The row it is writing into may legitimately be absent, and the attribute is still published by
+ the settled rows, so nothing distinguishes it from an ordinary windowed capture. It under-claims
+ rather than over-claims, and the same build compared on any full-mount pair still trips.
+ """
+ cap = _capture(browser, **dict(_BLIND, drop_tail = True))
+ assert cap["status_hook_present"] is True
+ assert cap["in_flight_unplaced"] is False, cap
+
+
+def test_the_gap_before_the_first_part_arrives_is_not_a_blind_probe(browser):
+ """THE THIRD CAUSE, and `send_turn` returns exactly into it.
+
+ `send_turn` breaks the instant `isRunning()` flips (scene/actions.py), the window closes there
+ and the capture follows within milliseconds. At that moment the assistant message is mounted
+ with ZERO content parts -- thread.tsx renders "Generating..." in place of any part -- so it
+ publishes no status because it has none to publish. The older assistant messages still publish
+ theirs, which is what says the hook is intact and this is an ordinary interval.
+ """
+ cap = _capture(browser, **dict(_MIDSTREAM, tail_has_parts = False))
+ assert cap["streaming"] is True
+ assert cap["status_hook_present"] is True
+ assert cap["in_flight_unplaced"] is False, cap
+
+
+def test_that_gap_is_still_caught_if_no_message_publishes_a_status_at_all(browser):
+ """The other half: nothing to publish on the LAST message is ordinary, nothing to publish
+ ANYWHERE is a hook that is gone, and a settled message would still be carrying it."""
+ cap = _capture(browser, **dict(_BLIND_ATTR, tail_has_parts = False))
+ assert cap["status_hook_present"] is False
+ assert cap["in_flight_unplaced"] is True, cap
diff --git a/tests/studio/studiobench/sweep/selftest/test_studiobench_windowed_parity.py b/tests/studio/studiobench/sweep/selftest/test_studiobench_windowed_parity.py
index a6e7abb537d..4d75f8293b1 100644
--- a/tests/studio/studiobench/sweep/selftest/test_studiobench_windowed_parity.py
+++ b/tests/studio/studiobench/sweep/selftest/test_studiobench_windowed_parity.py
@@ -949,6 +949,37 @@ def _action(
return row
+def test_a_style_regression_survives_a_structural_refusal(tmp_path, capsys):
+ """THE ONLY THING HERE THAT SEES `display`, `visibility` OR `pointer-events`, dropped.
+
+ The style probe is an INDEPENDENT reading: it is computed styles, not the DOM digest, so a pair
+ refused for landing at two points in one live reply can still carry a real CSS regression on a
+ settled surface. The refusal bucket sat above it and `continue`d, so that verdict was computed,
+ attached to the row and then thrown away -- for exactly the pairs a streamed-parity refusal
+ creates most of.
+
+ The refusal itself is right and stays. What must not happen is losing the other reading with it.
+ """
+ from studiobench.sweep import ui_parity as U
+
+ base = _capture(mounted = 4, total = 4)
+ treat = _capture(mounted = 4, total = 4)
+ # Structurally unreadable: the stream could not be placed on one arm.
+ treat["in_flight_unplaced"] = True
+ treat["in_flight"] = []
+ base["streaming"] = treat["streaming"] = True
+ # ...while the style probe read both arms cleanly and they disagree.
+ treat["styles"] = {"elements": 4, "digest": "RESTYLED", "capped": False}
+
+ rows = [_row("select_text", base), _row("select_text", treat)]
+ rows[0]["cell_id"], rows[1]["cell_id"] = "r100K.base.rep0", "r100K.treatment.rep0"
+ _write(tmp_path, "stylerefuse", rows)
+
+ U.main([str(tmp_path / "stylerefuse"), "--mode", "structural", "--min-compared", "0"])
+ out = capsys.readouterr().out
+ assert "style probe differing: 1" in out, out
+
+
def test_a_visible_message_that_could_not_be_digested_is_printed_and_not_counted(tmp_path, capsys):
"""THE FALSE GREEN. `windowed` put ordinals 1 and 2 on screen during the action and had
unmounted 2 again by the time the capture ran, so only ordinal 1 was ever compared. That pair
diff --git a/tests/studio/studiobench/sweep/ui_parity.py b/tests/studio/studiobench/sweep/ui_parity.py
index fa2788179ca..c1cf0f46442 100644
--- a/tests/studio/studiobench/sweep/ui_parity.py
+++ b/tests/studio/studiobench/sweep/ui_parity.py
@@ -1776,11 +1776,17 @@ def report(
else:
idle.append(entry)
continue
+ # THE STYLE VERDICT IS COLLECTED BEFORE THE STRUCTURAL REFUSAL IS BUCKETED, because it is
+ # an INDEPENDENT reading and the refusal is not about it. The bounded computed-style probe
+ # is the only thing here that sees `display`, `visibility` or `pointer-events`, and a pair
+ # refused for landing at two points in one stream can still carry a real CSS regression on
+ # a settled surface. Sitting below the `continue`, that verdict was computed, attached to
+ # the row, and then dropped on the floor for exactly the pairs this PR creates most of.
+ if r.get("style_verdict") == P.DIFFER:
+ style_bad.append((action, shard, cell, [r.get("style_reason", "")]))
if r["verdict"] == P.NOT_COMPARABLE:
blind.append((action, shard, cell, [r.get("reason", "")]))
continue
- if r["style_verdict"] == P.DIFFER:
- style_bad.append((action, shard, cell, [r.get("style_reason", "")]))
if r["verdict"] == P.MATCH:
matched += 1
compared.add((action, shard, cell))