Skip to content

Error handling/3 preview resilience - #196

Merged
jgindin merged 20 commits into
mainfrom
error-handling/3-preview-resilience
Sep 22, 2026
Merged

jgindin merged 20 commits into
mainfrom
error-handling/3-preview-resilience

Conversation

@jgindin

@jgindin jgindin commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Description

This is the 3rd in a stack of 4 PRs to improve error handling.

  • When an error is encountered by the renderer, it will send a RENDER_ERROR message back to the shell.
  • Add an onError callback to the RendererConfig, allowing the renderer to display an appropriate message when an error is encountered.

Pre-launch Checklist

  • I signed the [CLA].
  • I read the [Contributors Guide].
  • I read the [Style Guide].
  • I have added updates to the [CHANGELOG].
  • I updated/added relevant documentation.
  • My code changes (if any) have tests.
  • If my branch is on fork, I have verified that scripts/e2e_test.sh passes.

@github-actions

github-actions Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

⚡ A2UI Composer PR Preview

Your automated preview is successfully live (commit 1cb766e):
👉 Launch PR Preview

Note: This environment will be wiped automatically when the PR is merged or closed.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request implements robust error propagation, logging, and display mechanisms across the A2UI adapters (Angular, Lit, React) and the shell. Key updates include a new ErrorLogger service in the shell, structured error parsing in parseAndHealJsonLines, and a debounced error overlay UI in the sandboxes. Feedback on these changes suggests extracting the duplicated error overlay HTML template in the Lit adapter into a helper method, and removing redundant inline styles in the React sample's error overlay to leverage the existing CSS class.

Comment thread bridge/src/lit/lit-bridge.ts Resolved
Comment thread samples/react-basic-catalog/src/App.tsx Resolved
@jgindin
jgindin force-pushed the error-handling/3-preview-resilience branch 3 times, most recently from 9d61aad to 7be7d34 Compare September 8, 2026 20:30
@jgindin
jgindin force-pushed the error-handling/3-preview-resilience branch 4 times, most recently from 77ae4e2 to bca38a2 Compare September 10, 2026 22:27

@suyangw-g suyangw-g left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Summary

Thanks for this — the direction is genuinely good. Replacing throw-based control flow with the JsonParseResult / ParseResult discriminated unions is a real improvement, onError on RendererConfig is a clean and backwards-compatible extension point, and the prototype-pollution guards in resolveJsonPointer (unescape → decode → hasOwnProperty check) are exactly right.

I'm requesting changes primarily because CI is red, plus four other issues I think are merge-blocking. Full detail is in the inline comments.

🔴 Blockers

  1. build-and-test is failing. Two raw-frame.spec.ts watchdog tests fail: commit da4a546 removed level: 'warn' and commit cd4bf37 never added the IFRAME_UNRESPONSIVE_ERROR: prefix the specs assert. → raw-frame.ts:245, raw-frame.ts:250
  2. ChatPanel.visibleChatHistory re-parses the entire transcript on every stream tick. It now calls cleanPayload() + parseAndHealJsonLines() for every message and depends on isProgrammaticStreamActive(). parseAndHealJsonLines can brute-force 23 JSON.parse calls over the full buffer. → chat-panel.ts:167
  3. Monaco's model URI became a process-wide singleton. inmemory://model/layout.json + getModel() ?? createModel() means concurrent editor instances share one model; the first to be destroyed disposes it out from under the other. → monaco-editor.ts:50
  4. onSurfaceReady fires even when the render threw — it sits outside the new try/catch, so a failed payload emits RENDER_ERROR and reports the surface as ready. The console.error diagnostics also became unreachable on that path. → preview-bridge.ts:645
  5. samples/ng-basic-catalog/src/app/app.component.spec.ts uses document.querySelector in 13 places, against the repo rule requiring CDK Component Harnesses. → app.component.spec.ts:75

🟠 Significant, non-blocking

  • Semantics: empty/whitespace input is now classified as a parse failure, so an empty model turn surfaces a red "JSON Syntax Error" card to the user. It should take the conversational branch. (a2ui-payload-parser.ts:61)
  • Accessibility: the new parse-error card and all three sandbox .error-overlays lack role="alert" / aria-live, the mat-icon needs aria-hidden="true", and the overlays are position: fixed; inset: 0; z-index: 9999 at 95 % opacity with no dismiss affordance or focus management.
  • Missing styles: .parse-error-card and .error-notice are referenced in the template but defined nowhere — the card renders unstyled.
  • Typing: LlmMessage.parseError?: unknown forces getParseErrorMessage() into runtime shape sniffing; FailureParseResult is already exported and would make this type-safe (and would let the UI actually show the line/column/snippet the parser now computes but nothing displays).
  • Test hygiene: six new raw-frame.spec.ts tests call vi.useFakeTimers() with no useRealTimers() teardown, and document.hidden is restored inline rather than in afterEach.
  • Test locality: the parser tests in chat-panel.spec.ts:952 belong in a2ui-payload-parser.spec.ts; meanwhile the component behaviour this PR actually adds (the error card, viewParseErrorDetails()) is untested. One of those tests also silently bakes in a regression — partially-corrupt JSONL used to yield a component count of 3 and now yields a hard failure.
  • Duplication: the 350 ms debounce is implemented three times (Lit / RxJS / React hook) and the .error-overlay CSS block is copy-pasted four times. Both should be exported once from a2ui-bridge.
  • Double subscription: events.ts consumes messageStream$ and keeps an effect() on messageStream(), deduped by identity via a WeakSet. Pick one channel.

📋 Visual & documentation gaps

This PR adds four user-visible surfaces (chat error card, three sandbox overlays, schema-error snackbar) but has no screenshots, no GIF, and no Playwright coverage for any of them — while it does edit the e2e specs. .agents/rules/testing_and_qa_workflow.md asks for CUJs to be captured with yarn e2e-headless. Dark mode is also worth a check: the Lit overlay hard-codes a #d32f2f fallback that will be hard to read on a dark surface.

The description is also missing a Fixes #… link, and the CHANGELOG / documentation boxes are unchecked even though this changes public a2ui-bridge API (RendererConfig.onError, RENDER_ERROR, RENDER_SUCCESS, safeSerialize) and the tryParseJsonArray signature.

📦 Scope

The description says "3rd in a stack of 4" and lists two bullets, but the diff against main carries the whole stack — the Monaco Draft-07 flattener, the host watchdog, the JSON diagnostics refactor, Events-tab hydration, and e2e stabilisation. Six of nine commits are titled "Address PR 195 feedback". Retargeting the base branch to PR 195's branch would cut the reviewable surface by more than half and make the incremental change legible.


Happy to re-review as soon as CI is green and the blockers are addressed — the nits can absolutely be batched or deferred.

Comment thread shell/src/app/preview/raw/raw-frame.ts Resolved
Comment thread shell/src/app/preview/raw/raw-frame.ts Resolved
Comment thread shell/src/app/debug/events/events.ts Resolved
Comment thread samples/react-basic-catalog/src/App.tsx Resolved
@suyangw-g suyangw-g mentioned this pull request Sep 11, 2026
4 of 7 tasks
@jgindin
jgindin force-pushed the error-handling/3-preview-resilience branch 4 times, most recently from 9e27c99 to 797891a Compare September 14, 2026 20:15
@jgindin
jgindin requested a review from suyangw-g September 14, 2026 20:28
@jgindin
jgindin force-pushed the error-handling/3-preview-resilience branch 2 times, most recently from 20d44ee to 45ae2c8 Compare September 18, 2026 16:39

@suyangw-g suyangw-g left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One blocker in the new e2e work. The rest of my original review verified as addressed — the JSONL resilience regression was fixed rather than just justified, and the CDK harness migration is clean.

@jgindin
jgindin force-pushed the error-handling/3-preview-resilience branch from ed90d18 to 313ad78 Compare September 22, 2026 17:16
Extract error overlay rendering in Lit bridge sandbox root. Remove
redundant inline styles in React catalog App component. Stabilize
Playwright raw messages and events telemetry assertions by replacing
hardcoded timeouts with web-first assertions. Eliminate redundant
MappedEventLogItem alias in favor of DisplayEventLogItem.

TAG=agy
CONV=28b993f1-8dc7-4320-8ac3-2ba70da6f758
The preview host resizes the iframe to the height the guest reports.
The guest documents floored their own height at 100vh and chained
height: 100%, so every measurement returned the size the host had
just applied plus the body padding. The guest then reported a larger
height, the host grew the frame again, and the cycle repeated every
~24ms until the frame reached the 20,000px dimension cap while
showing ~280px of content.

Remove viewport-coupled sizing from the Lit, Angular and React guest
surface hosts. The error overlays are position: fixed with inset: 0
and no ancestor establishes a containing block, so they still cover
the iframe viewport without a full-height ancestor.

Invert the two specs that asserted min-height: 100vh, add per-sample
guards over the guest stylesheets, and add an e2e regression test
covering all three guests. The test samples the frame height and
reads SURFACE_RESIZE traffic off the postMessage wire instead of the
Raw Messages drawer, whose rows can be collapsed.

Exclude spec files from the Angular sample browser build and declare
Node types in the Lit and React samples so the guards type-check.
documentElement.scrollHeight reports the document scrolling area,
which is floored at the initial containing block. Inside an iframe it
can therefore never report less than the guest viewport. Because the
host derives the iframe height from the height the guest reports,
including this term makes the measurement self-referential: once the
frame grows, it can never shrink back.

Measured in the Angular sample with viewport-coupled guest CSS
already removed (f954ac8d):

  body.scrollHeight             312   content
  documentElement.scrollHeight  917   floored at viewport
  body.offsetHeight             312   content
  documentElement.offsetHeight  312   content
  window.innerHeight            917

Math.max returns 917, so the frame stays pinned at 917px while
holding 280px of content. Dropping the floored term returns 312 and
the frame settles on content height after one further message.

This change does not affect the SURFACE_RESIZE feedback loop. While
the guest sets min-height:100vh, all four terms are tied at
innerHeight + 32, so removing any one of them changes nothing.
Conversely, f954ac8d alone stops the loop but leaves the frame
pinned. Both changes are required; neither is sufficient alone.

User-visible behaviour changes:
- Preview frames shrink when their content shrinks.
- Frames render 21-44px shorter at rest depending on renderer.
- Surfaces below 280px still render at 280px via host min-height.
- Tall surfaces render without clipping; scrollHeight is respected.

Accepted limitation: absolutely-positioned content overflowing the
body no longer extends the frame, as it contributes to
documentElement.scrollHeight rather than the body box.

End-to-end coverage for surface sizing is consolidated in
shell/e2e/surface-auto-resize.e2e.ts, which asserts shrink-to-content
for all three sample renderers. The resize-message bound is asserted
in renderer-integration-and-telemetry.e2e.ts from the postMessage
wire rather than from the debug drawer, which folds repeated
messages into a single row.

(cherry picked from commit a26b80b66aaf31f2bc2db57a11105336a70736d3)
A guest that couples its own height to the iframe viewport drives an
unbounded resize loop: the host sizes the iframe from the height the
guest reports, so the guest measures larger and reports again.
f954ac8d and 0d9ffde0 remove that coupling from the bundled samples,
but nothing stops a third-party renderer from reintroducing it, and
min-height:100vh is an entirely natural thing to write.

The only terminating condition was MAX_SURFACE_DIMENSION in
CrossFrameValidator, which ends the loop in the worst available state:
the frame pinned at 19,992px with roughly 280px of content scrolled
out of view, and the RawFrame hang watchdog kept alive by the loop
traffic so a genuinely hung renderer stops being reported.

RenderedFrame now counts consecutive growing SURFACE_RESIZE reports
that arrive within 500ms of each other. After 8 it latches, logs once
with the held height and the run length, and stops applying growth.
Shrinking reports are still applied, so a guest that recovers is not
stuck. The latch clears on RENDERER_READY and on a renderer switch;
the run counter also restarts on payload dispatch and on any report
that does not grow.

The counter subscribes to HostCommunication.messageStream$ rather than
living in the signal effect that applies the height. Signal effects
coalesce: a burst arriving inside one change detection tick runs the
effect once, for the last value only, so a counter inside it would
undercount and might never latch. RawFrame already consumes the same
observable for the same reason.

Scope: this detects monotonic divergence, not oscillation. Healthy
renderers oscillate too - the Lit sample reports
32,148,288,312,148,288,312 for one ordinary re-render - so alternation
carries no signal at this layer. The e2e settle assertion covers it.

MAX_IDLE_RESIZE_MESSAGES drops from 25 to 10. With the breaker active
a flood is cut short, so 25 no longer separates a broken session from
a healthy one. Measured from the postMessage wire at 1280x800:
healthy Angular 4, React 5, Lit 7; guest CSS reverted, 13 and 15;
guest CSS reverted with no breaker, 212 and 239. The bound cannot sit
below the 8-report latch because healthy Lit traffic reaches 7.
Several of the resize regression assertions could be satisfied for the
wrong reason. An empty log passed both wire bounds - `length < 10` is
true of zero, and longestIncreasingRun([]) returns 0 - so the wire tap
could die silently on a renamed message type, an added envelope, a
clobbered __a2uiResizeLog or a failed init script, and the test would
stay green. The growth breaker added in e82245cc then cut a broken
session short enough that three more bounds stopped discriminating.

- Add a hard tripwire: the log must contain at least one report.
- Add a cadence bound on the longest burst of reports arriving within
  50ms of each other.
- Promote the frame-versus-content check from soft to hard. It has the
  largest margin and cannot be satisfied by the 280px floor, by
  MAX_SURFACE_DIMENSION, by the growth breaker, or by panel geometry.
- Derive the shrink test's growth target from the frame's own starting
  height rather than a 2000px literal that depended on where text
  wrapped, and assert the final height against the guest content box
  rather than `>= 280`, which rendered-frame.scss makes unconditional.
- Give both surface-auto-resize tests a 60s timeout. They poll for up
  to 20s against a possibly cold dev server, where a timeout reads
  exactly like a real height latch.

Measured at 1280x800, healthy versus guest CSS reverted:

  longest burst at <=50ms    2, 2, 3   vs   8, 8, 3
  longest increasing run     4, 3, 4   vs   9, 5, 9
  messages per session       4, 5, 7   vs   13, 14, 15
  frame minus content        0px       vs   16-32px

Cadence does not give the order of magnitude one might expect, because
healthy renderers also emit sub-20ms pairs during first render; the
signal is burst length, not gap size. The run-length bound has no
margin at all, which is now recorded at its definition along with the
reason it is kept: it is the only bound the growth breaker cannot
mask, and raising it to 5 would stop detecting a broken React guest.

With the guest CSS reverted the shrink test now fails on its shrink
assertion (frame 2328px, bound 1164px) instead of timing out on its
growth precondition, so it once again exercises what it was written
to exercise.
The Lit sandbox root rendered
`<main style="position: relative; width: 100%; height: 100%;">` and the
React sample rendered `<main style={{position: 'relative'}}>`. None of
it does anything. Height and width resolve to auto now that every
ancestor is auto-height, and position:relative had no effect either:
the only positioned descendant is the error overlay, which is
position:fixed and ignores relative ancestors. Nothing in bridge/src or
samples/ uses absolute or sticky positioning. Inert code that looks
load-bearing invites someone to build on it, so it is deleted rather
than annotated. Both hosts now match the Angular sample.

The guards missed exactly the files that carried this. The Lit
assertion reads A2uiSandboxRoot.styles.cssText, which is the static
stylesheet only and never sees the render() template literal. The
Angular guard read two stylesheets but not the template, which already
carries an inline style attribute and is therefore a plausible place
for viewport sizing to reappear. Both gaps are closed:

- lit-bridge.spec.ts renders the surface-present branch and asserts on
  shadowRoot.innerHTML.
- The Angular guard scans app.component.ng.html and index.html as well
  as the two stylesheets.
- All three sample guards now use the same case-insensitive patterns
  and cover vmin, vmax, vb and vi. Two were case-sensitive, so
  `min-height: 100VH` would have slipped past.

Both new guards were confirmed to fail against the pre-fix content
before being kept: the Lit one against the old inline main style, the
Angular one against `style="min-height: 100VH"` in the template.
The filesystem-based guest sizing guards need @types/node, and adding
"types": ["node"] to the Lit and React sample tsconfig.json put those
globals in scope for the browser sources the same config compiles:
`yarn build` runs `tsc` over src/**/*, so Buffer, process.env and
__dirname type-checked inside components that ship into the preview
iframe. Verified before this change with a probe file in src/ that
used Buffer and process.env: it compiled cleanly in both samples.

Mirror the split the Angular sample already uses, where
tsconfig.app.json excludes specs and tsconfig.spec.json carries the
Node types. The build config now declares "types": [] and excludes
specs, and a new tsconfig.spec.json extends it with the Node types.
The same probe now fails with TS2591 in both samples, which is what
the Angular sample already did.

Since the build config no longer covers the specs, both build scripts
type-check tsconfig.spec.json explicitly to keep the coverage `tsc`
previously gave them. `ng build` offers no equivalent hook, so the
Angular specs stay covered by the editor only.
`documentElement.scrollWidth` is floored at the guest viewport, the
same defect that removing `documentElement.scrollHeight` fixed on the
height axis: it reports the frame the host just applied rather than
the content inside it.

Nothing breaks today because the host discards `width` from
SURFACE_RESIZE, but the term has two live consequences. Driving the
frame width from this payload would silently reopen the feedback loop
on the width axis. And because the dedupe keys on both dimensions, a
root scroll box that follows the frame emits a SURFACE_RESIZE even
when the height has not moved.

The comment now covers both axes so the height term is not restored
later for symmetry.
The two height specs read component signals, so a broken
[style.height] binding would have left them green while the iframe
kept its old size. They now go through RenderedFrameHarness and
assert the height the template applies, which is the value the guest
measures itself inside.

Adds the two boundary cases neither the component nor the validator
covered. A zero height, which CrossFrameValidator admits, leaves the
frame filling its panel instead of collapsing. A height above
MAX_SURFACE_DIMENSION is dropped by the validator, so the last good
height stays applied; that ceiling is where the frame was pinned
during the resize feedback loop.

Hoists the SURFACE_RESIZE envelope builder to module scope so the
height specs and the circuit breaker specs build messages the same
way.
The settle test derived its expected frame height from
body.scrollHeight alone, while measureAndDispatch() reports
max(body.scrollHeight, body.offsetHeight,
documentElement.offsetHeight). Those diverge whenever the root
element is the taller box: body margins escaping through it are
pinned at body 290 against documentElement 390 in the bridge unit
test. The oracle now mirrors the implementation instead of demanding
a height it never sends.

Sampling also began as soon as the Search Cars button was visible.
Webfonts swap in after first paint and can move the content by more
than the 1px settle tolerance, so a late swap could be recorded as
instability. The test now waits for document.fonts.ready and for one
repeated height reading. The wait is bounded at 5s and does not
throw, so a frame that never settles is still judged by the bounds
rather than by a timeout.

Also records the panel geometry the bounds were measured against,
and corrects the sampling comment: the wire tap is installed before
navigation, so the SURFACE_RESIZE log covers startup rather than an
idle preview.
setMonacoContent existed three times over (surface-auto-resize, the
raw JSON test in renderer-integration, and four sites in
user-journey), and the renderer dev server addresses four times. The
copies had already drifted: some waited for the editor to be visible
before waiting for a model, others only waited for the model.
shell/e2e/helpers.ts now holds waitForMonacoEditor,
setMonacoContent, getMonacoContent and RENDERER_URLS.

samples.ts was not used for this. It holds A2UI payload fixtures and
imports nothing, while these helpers need @playwright/test.

Narrows the Lit sandbox style guard, which banned the whole
min-height property and so also blocked a pixel min-height. A pixel
value is derived from content and cannot feed the frame back into
the guest measurement. The guard now bans `height: 100%` in either
form, and its viewport-unit pattern covers the same units as the
sample guards, case-insensitively. Verified by injecting
`min-height: 100%` and `min-height: 100VH`, both of which fail it,
and `min-height: 280px`, which passes.

Each sample guard now records that these patterns are duplicated
across workspaces that have no shared test-only module to hold them.

Finally, a note next to the search form telemetry test: it depends
on full-suite ordering, failing on two of three renderers when run
filtered. That reproduces on a clean tree and is not addressed here.
Independent verification could not reproduce the claim that a broken
React guest produces an increasing run of 5. In that run React's
longest run was 4, and earlier runs here measured 5 and 6, so the
run-length bound does not reliably detect React at all. It remains
decisive for Angular and Lit (9 against a healthy 4). The comment
now says that, and the cadence comment no longer credits the
run-length bound with catching React.

The delete-rather-than-raise guidance stands: raising the bound to 5
would give up Angular and Lit and buys nothing for React.

Records next to the frame-versus-content assertion that on a
reverted React guest it was the only assertion in the test that
fired; the count, run-length and cadence bounds all passed. Making
it soft would leave React uncovered.

FULL_HEIGHT had already drifted between the copies: the samples
allowed an optional quote, the bridge did not. All four are now
byte-identical and accept a quote or a backtick, so template literal
styling in the Lit file this guard protects is covered too. The
bridge guard uses named constants like the sample guards, and the
cross-reference comments claim only what is true.

Verified that the unified pattern still rejects every pre-fix file
that carried the defect: both sample index.html files, App.tsx,
app.component.scss and lit-bridge.ts. The other three files in the
Angular guard list never carried it; they are covered by injection
instead.
Synchronize preview frame interaction with catalog handshake settlement
to eliminate race conditions where background re-renders overwrite form inputs.
Dispatch native input and change events for React date fields in tests.

TAG=agy
CONV=28b993f1-8dc7-4320-8ac3-2ba70da6f758
@jgindin
jgindin force-pushed the error-handling/3-preview-resilience branch from 87e83da to fa73eb6 Compare September 22, 2026 20:53
- Export ERROR_OVERLAY_DEBOUNCE_MS and deduplicate isErrorLike in
  a2ui-bridge
- Add IFRAME_UNRESPONSIVE_ERROR and warn/error distinction in raw-frame
- Unique Monaco schema modelUri, recursion depth clamp, and preserve
  open schemas
- Syntax healing length limit, multiline line-skipping, and error card
  a11y in chat
- Validate panelId before opening in workspace and streamline events
  stream
- Add Angular CDK harness to ng-basic-catalog and extract React
  debounce hook

TAG=agy
CONV=28b993f1-8dc7-4320-8ac3-2ba70da6f758
Restore HEIGHT_SAMPLE_INTERVAL_MS and STABILITY_PROBE_INTERVAL_MS
constants in renderer integration e2e test. Replace no-op expect.poll
calls with page.evaluate setTimeout delays to ensure proper sampling
and stability probe intervals.
Remove the obsolete 280px minimum frame height floor in
renderer-integration-and-telemetry.e2e.ts and
surface-auto-resize.e2e.ts. RenderedFrame overrides stylesheet
min-height once real content height is reported, which caused
assertions to fail when guest content rendered under 280px.

Wait for the initial DATA_MODEL_CHANGE bridge envelope before editing
the data model tab to prevent late initial envelopes from clobbering
user edits in e2e tests.
@jgindin
jgindin force-pushed the error-handling/3-preview-resilience branch from fa73eb6 to 1cb766e Compare September 22, 2026 21:12
@jgindin
jgindin merged commit f95459c into main Sep 22, 2026
12 of 21 checks passed
@jgindin
jgindin deleted the error-handling/3-preview-resilience branch September 22, 2026 22:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants