Skip to content

Frontend audit: fix React/state/CSS bugs in src/app and src/diagram - #713

Merged
bpowers merged 16 commits into
mainfrom
frontend-react-audit
Jun 4, 2026
Merged

bpowers merged 16 commits into
mainfrom
frontend-react-audit

Conversation

@bpowers

@bpowers bpowers commented Jun 4, 2026

Copy link
Copy Markdown
Owner

What this is

A systematic bug audit of the frontend TypeScript/React/CSS code in src/app and src/diagram, followed by fixes for everything confirmed. Eight area/dimension review agents swept the code; every finding was adversarially verified by an independent agent before being accepted (51 raw findings -> 29 confirmed, 10 refuted). The full findings list with per-item status lives in docs/dev/frontend-audit-2026-06.md, committed first on this branch so the fixes can be reviewed against it.

Every fix was done test-first where the behavior was testable (new pure helpers + component tests; 20+ new test files/cases), and each landed as its own commit through the full pre-commit suite.

Highlights (the bugs behind the glitches you reported)

  • Equation preview glitches: three compounding causes. (1) The details panels were keyed by projectVersion, which bumps on every pan frame and is reset by every autosave completion -- each bump remounted the open panel, discarding in-progress Slate edits and refiring the async LaTeX load. They are now keyed by a new projectGeneration that increments only on real content changes (edits, undo/redo). (2) While the engine LaTeX loaded (and whenever the engine couldn't produce LaTeX), the raw equation text was fed to katex.renderToString, rendering revenue_per_unit with _ as subscripts; raw text now renders as plain monospace. (3) Error highlighting treated Rust byte offsets as UTF-16 indices and only ever touched line 0; a new equation-highlight module converts offsets, shifts past the {apply-to-all:} prefix, and highlights across lines (caret placement from preview clicks got the same fix).
  • Long equation running off the card: KaTeX packs math into atomic inline-block .base spans with white-space: nowrap, which overflow-wrap on an ancestor can't break, and the flex container refused to shrink (min-width: auto). Fixed with a .base override (higher specificity than katex.css), min-width: 0, and overflow-x: auto as the unbreakable-content fallback.
  • Search bar / details card misalignment: reset.css (the universal box-sizing: border-box) is tree-shaken out of the production CSS bundle even though it's a side-effect import -- so the padded search bar rendered 16px wider than the card. Fixed two ways: an explicit import '@simlin/diagram/reset.css' in the app entry (verified present in the rebuilt bundle) and explicit box-sizing: border-box on every panel rule so alignment never depends on a global reset. The unexplained tree-shaking is tracked as rsbuild/rspack tree-shakes reset.css side-effect import out of src/app production CSS bundle #708.

Other high-severity fixes

  • Undo was broken two ways: editing after an undo kept the abandoned redo branch (undo then jumped to sibling states instead of the edit's parent), and every pan/zoom/momentum frame pushed a snapshot into the 5-entry undo buffer, evicting real edits. View-only updates no longer touch history; real edits go through a pure, tested advanceProjectHistory.
  • Creating a flow armed a delete trap: flowStillBeingCreated was never reset (the reset was a true-for-false typo), so a later Escape-cancel of any rename deleted that variable.
  • Logout did nothing -- the menu item only closed the menu, and the server's DELETE /session was a TODO stub that never even wrote a response. Both halves implemented (Firebase signOut + session invalidation via passport req.logout() + seshcookie rewrite, with an end-to-end server test).
  • A failed project load left a permanently blank editor (network error / non-JSON / missing fields all escaped as unhandled rejections); failures now render an error message.
  • NewUser onboarding could submit via backdrop click or Enter while bypassing the terms-agreement gate; Dialog gained disableBackdropClick and the gate is enforced on every entry path.

Plus mediums/lows: Login error handling and stale-error clearing, Autocomplete dropdown detaching on scroll/resize, flow/connector rendering geometry edge cases (fixed identically in the TS and Rust renderers -- the SVG parity test compares them byte-for-byte), LookupEditor NaN on a 1-point table, missing React keys, PureComponent memoization defeated by per-render closures, unmount guards, breakpoint-aware panel-width math, Checkbox/TextField contract fixes.

Decisions and tradeoffs

  • Remount-by-key kept, but on the right key. Rather than teaching VariableDetails to resync Slate state from props (Slate ignores post-mount initialValue changes, so prop-resync wouldn't reach the DOM and would need editor-instance recreation), I kept the constructor-seeding + key-remount design and made the key change exactly when content changes. Lower risk, preserves all existing refresh semantics, and the difference is observable in tests.
  • Undo after a view change restores the camera of the snapshot. Excluding pans from history means undo now jumps the viewport to where it was at edit time. I judged this standard editor behavior and better than view changes consuming undo slots.
  • Rust renderer changed in a "frontend" PR. The TS and Rust SVG renderers are parity-tested byte-for-byte, so the geometry fixes had to land in both (the Rust code even carried a "Matches TypeScript: tan, not atan" comment). One hardcoded golden string was updated for atan's rounding on ordinary arcs (third-decimal differences).
  • Unit warnings no longer force the raw editor open. This matches variableDetailsView (unit errors are non-fatal: they keep the chart) -- the warning list still renders under the chart, and clicking into the editor still shows the squiggle.
  • What I deliberately did not do: no class-to-function component conversion (per your instruction); no debounce of the per-frame engine round-trips (Canvas view changes trigger a full engine round-trip per frame during pan/zoom #707 -- removing the undo pollution fixed the worst symptom, persistence batching is a bigger change); dark-mode for the component library (diagram: component-library CSS modules hardcode light colors with no dark-mode overrides #709) and Menu anchor-tracking (diagram: Menu anchors Radix to a position:fixed proxy holding a stale getBoundingClientRect snapshot #710) deferred and tracked.

Verification

  • All new and existing tests pass; every commit went through the full pre-commit suite (Rust fmt/clippy/tests, TS lint/build/tsc/tests, WASM build, Python tests).
  • The CSS fixes are locked in by stylesheet-contract tests (panel-css.test.ts) and the rules were verified present in the rebuilt production bundle. I could not do a pixel-level browser check in this environment (headless Chromium lacks system libs here) -- worth a quick visual confirmation of the reliability model's details panel on your running app.
  • 12 of 51 raw findings lost their verifier mid-run; I recovered them from the workflow journal and confirmed they all duplicated already-confirmed findings before proceeding.

Follow-ups filed: #707 (per-frame engine round-trips), #708 (reset.css tree-shaking), #709 (component-library dark mode), #710 (Menu anchor tracking).

bpowers added 15 commits June 3, 2026 20:38
Multi-agent audit of the frontend React/TypeScript/CSS code with
adversarial verification of each finding. The doc enumerates confirmed
high/medium/low findings with status; subsequent commits on this branch
fix them individually.
The flag was set when a flow-creation drag entered name editing and never
cleared: the cancel branch re-set it to true (a typo for false) and
pointerStateReset() omitted it. Once any flow had been created, a later
Escape-cancel of an unrelated rename would see the stale flag and call
onDeleteSelection(), deleting the variable the user only meant to stop
renaming.

Clear the flag in pointerStateReset() so both the commit and cancel paths
(which funnel through clearPointerState) reset it, and drop the no-op
setState in the cancel branch.
Two related undo bugs in Editor.updateProject:

1. Editing after an undo kept the abandoned redo branch: priorHistory was
   the full newest-first array instead of history.slice(projectOffset), so
   a later undo jumped to sibling states the user had navigated away from
   rather than the edit's true parent. The truncation now lives in a pure
   advanceProjectHistory helper.

2. queueViewUpdate (pan/zoom/momentum frames, panel resizes) funneled into
   updateProject, which unconditionally prepended a snapshot. viewBox and
   zoom are serialized into the protobuf, so every momentum animation frame
   was a distinct snapshot; with MaxUndoSize = 5 a single flick evicted all
   real edits from the undo buffer. View-only updates now refresh the
   rendered project and bump the render version without touching the
   history or the undo cursor.
VariableDetails and ModuleDetails seed their Slate editors from props in
their constructors, so key-driven remounts are what refreshes them. The
key included projectVersion, which bumps +0.001 on every pan/zoom frame
and is reset to the integer server version when an autosave completes --
each of those remounted an open panel, discarding in-progress unsaved
edits, resetting editing state, and refiring the async LaTeX load (one of
the user-visible equation-preview glitches).

Introduce projectGeneration, incremented exactly when project content
changes: history-recording updateProject calls (real edits) and undo/redo.
View-only updates and save bookkeeping no longer remount the panels.
Three related equation-panel fixes in VariableDetails:

1. Raw equation text was fed to katex.renderToString while the engine's
   LaTeX was loading (and whenever the engine couldn't produce LaTeX),
   rendering identifiers like revenue_per_unit with underscores as
   subscripts. The preview now shows the raw text as plain monospace and
   only routes genuine engine LaTeX through KaTeX.

2. showPreview gated on the presence of unitErrors, forcing variables with
   only non-fatal unit warnings out of the rendered preview into the raw
   editor -- contradicting variableDetailsView, where unit warnings keep
   the chart. The preview (and the editor's exit-on-blur) now gate on
   equation errors only.

3. Error highlighting treated engine byte offsets as UTF-16 indices and
   only ever touched line 0, so multi-line equations (including the
   apply-to-all prefix line) and non-ASCII content mis-highlighted. The
   new equation-highlight module converts byte offsets to UTF-16, shifts
   past the apply-to-all prefix, and applies ranges across lines; caret
   placement from preview clicks gets the same conversion plus a proper
   (line, column) Slate point. Also drops a stray console.log.
Two CSS-layer bugs visible in the editor's right-hand panels:

1. The search bar's left edge sat 16px left of the details card's. Both
   are width: var(--panel-width-*) boxes anchored at right: 8px, but the
   universal box-sizing reset in reset.css -- a side-effect import in
   @simlin/diagram's index -- was tree-shaken out of the production CSS
   bundle, so the searchBar's 8px horizontal padding widened it under the
   default content-box. Import reset.css explicitly from the app entry
   (verified present in the rebuilt bundle) and declare border-box on each
   panel rule so alignment no longer depends on a global reset being
   present in any particular host bundle.

2. Long KaTeX equations ran off the card's right edge: KaTeX packs math
   into atomic inline-block .base spans carrying white-space: nowrap,
   which overflow-wrap on an ancestor cannot break, and .eqnPreview's flex
   items refused to shrink below content size (min-width: auto). Allow
   breaks inside .base, let flex children shrink, and add overflow-x: auto
   as the fallback for genuinely unbreakable content.

The stylesheet contracts are locked in by panel-css.test.ts.
loadProject() is invoked fire-and-forget from componentDidMount, but only
the resolved-with-4xx case was handled: a network-level fetch rejection, a
non-JSON body, or a response missing pb/version threw past the caller as
an unhandled rejection, leaving projectBinary unset and render() returning
an empty div forever with no message. Guard the whole load with try/catch
and validate the response shape, routing every failure through
appendModelError so the existing serviceErrors branch renders it.
The account menu's Logout item was wired to handleClose -- it dismissed
the menu and did nothing else, so there was no working way to sign out.
Two halves:

- server: DELETE /session was a TODO stub that never even wrote a
  response (an awaiting client would hang). Implement it via passport's
  req.logout(): with seshcookie there is no server-side store, so
  regenerating the session and letting seshcookie rewrite the Set-Cookie
  is the whole job. Handler lives in auth-helpers so the existing
  seshcookie+passport compat test can exercise it end-to-end.

- app: InnerApp.handleLogout clears the server session, signs out of
  Firebase, invalidates the cached /api/user singleton, and drops the
  local user so the auth gate renders Login. Each step is best-effort so
  a network failure can't leave the user stuck logged in. Home receives
  it as an onLogout prop.

Also hardens Home.getProjects while in the file: the fetch was kicked off
from the constructor (which StrictMode's discarded render-phase instance
also runs), had no error handling (network rejections escaped as
unhandled), and could setState after unmount. It now follows the
componentDidMount + tracked-timer + unmount-flag pattern used by
InnerApp and HostedWebEditor.
fetchSignInMethodsForEmail and sendPasswordResetEmail were the only two
auth calls in Login without try/catch: a rejection (network failure, rate
limiting, Firebase email-enumeration protection) escaped as an unhandled
rejection and the form sat inert with no feedback. Both now surface the
failure via emailError, and a failed recovery email no longer advances to
the password card as if it had been sent.

Also clear a field's error message as soon as the user edits that field;
previously a stale validation/auth message stayed red while the user
typed a corrected value.
Dialog exposed disableEscapeKeyDown but Radix still treated a click
outside the content as a close request, routing it to onClose. In
NewUser's mandatory onboarding dialog, a backdrop click with a non-empty
username invoked handleClose -> setUsername(), submitting the PATCH while
bypassing the agreed-to-terms gate that disables the Submit button (Enter
in the username field had the same bypass).

Add a disableBackdropClick prop (onPointerDownOutside/onInteractOutside
preventDefault) as the symmetric half of the modal guard, use it in
NewUser, and make NewUser's handleClose enforce the terms agreement so no
entry path can submit without it.
The listbox is portaled to document.body with a position computed once
when the dropdown opens. Scrolling the details panel (the wiring table's
host is overflow-y: auto) or resizing the window left the listbox frozen
at stale viewport coordinates, visibly detached from its input. While
open, recompute the position on capture-phase scroll (catching ancestor
scrolls, not just the window) and on resize.

Also ellipsize long variable names in the option rows, which are sized to
the input's width.
Three geometry bugs, each fixed identically in the TypeScript renderer and
the Rust SVG renderer (the cross-language parity test compares their
output byte-for-byte, so they must move together):

- Cloud-terminated flows retracted the endpoint by CloudRadius per axis
  independently, over-retracting diagonal final segments by sqrt(2)x and
  detaching the arrowhead from the cloud edge. The retraction now follows
  the segment's unit vector (identical for orthogonal segments).

- A zero-length final segment read as 'pointing right' via atan2(0, 0);
  the arrowhead direction now walks back past coincident points.

- The aux branch of intersect-element-arc used tan(r/circ.r) -- the same
  pi/2-asymptote hazard the stock/module branch was already fixed to
  avoid; a tight arc between nearby elements could swing the arrowhead to
  the wrong side. Now atan, matching the rect branch. The byte-identical
  golden in connector.rs is updated for atan's (slightly different)
  rounding on ordinary arcs.

Also key multi-line label tspans by index instead of line text, which
produced duplicate React keys for repeated lines.
- ErrorDetails: list items rendered without React keys (dev warning,
  index-based reconciliation).
- LookupEditor: a datapoint count of 1 divided by size-1 == 0, producing
  NaN x (and via lookup() NaN y) that could be saved into the table; the
  shared xAtTableIndex helper maps a single-point table to xMin.
- Editor: stable module-level no-op handlers for the read-only/embedded
  Canvas (fresh arrow functions per render defeated Canvas's PureComponent
  memoization); the module-navigation setTimeouts now short-circuit on
  unmounted like every other deferred callback; centerVariable and
  handleZoomChange use the breakpoint-aware panel width instead of
  hardcoding the small/large constants.
- TextField: the input id must survive the inputProps spread so a label's
  htmlFor association holds when used inside Autocomplete (downshift
  supplies its own id; its value/handlers still win).
- Checkbox: normalize Radix's boolean | 'indeterminate' CheckedState to
  the boolean the onChange contract promises.
Documents the two new Editor invariants from the audit fixes (view-only
updates never record undo history; details panels keyed by
projectGeneration) and drops the stale 'Last verified' line per the root
CLAUDE.md policy.
@bpowers

bpowers commented Jun 4, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d61b736980

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/app/App.tsx Outdated
} catch (err) {
console.error('logout: firebase signOut failed:', err);
}
await userInfo.invalidate();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep logout cleanup best-effort

When logout runs while userInfo still has an in-flight /api/user request and that request rejects (for example during a transient network failure), userInfo.invalidate() rethrows before the following setState, so the local user can remain populated and the async onLogout call from Home becomes an unhandled rejection. Since the server-session and Firebase steps are already best-effort, this cache invalidation should also be guarded or moved after clearing local state so logout cannot leave the UI stuck signed in.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in 344aadc: local state is now cleared before the cache refresh and the refresh is guarded, matching the handler's best-effort contract. Also fixed one layer deeper -- invalidate() starts a fetch nothing immediately awaits, so UserInfoSingleton's worker now catches network failures and reports status 0 (not authenticated) instead of leaving a rejecting promise to surface later as an unhandled rejection. Regression test added (logout with every network call rejecting still resolves and clears the user).

@claude

claude Bot commented Jun 4, 2026

Copy link
Copy Markdown

Reviewed all 52 files in the PR. No blocking issues found. The fixes are well-scoped and each lands with a matching regression test; nothing introduces new bugs that I can identify.

Notes from the review (none rise to a blocking concern):

  • Editor.handleUndoRedo bumps projectGeneration unconditionally, including the no-op case where undo at offset 0 (or redo at the newest snapshot) clamps and leaves projectOffset unchanged. The user-visible behavior is the same as before this PR (projectVersion already bumped here), so it isn't a regression — but it does slightly undermine the new invariant that projectGeneration only changes on real content changes. A guard that bumps generation only when the offset actually moves would make the invariant tight, at the cost of one tiny conditional.
  • noopMoveFlow/noopMoveSelection declare fewer parameters than the Canvas prop types (onMoveFlow has 6 args, onMoveSelection has 3). TypeScript's contravariance accepts this and extra args are dropped at runtime — fine for a no-op, just worth keeping in mind if these are ever extended.

Overall correctness: correct.

Review feedback on #713: handleLogout awaited userInfo.invalidate()
before clearing local state, and invalidate() rethrows a pending
/api/user request's rejection -- a transient network failure during
logout could leave the UI stuck signed in and escape Home's
fire-and-forget onLogout call as an unhandled rejection.

Clear local state first and guard the refresh, matching the rest of the
handler's best-effort steps. Also catch network failures inside
UserInfoSingleton's worker (status 0 == not authenticated): invalidate()
starts a fetch nothing immediately awaits, so a rejecting worker promise
could otherwise sit unconsumed and surface later as an unhandled
rejection regardless of the caller's guards.
@claude

claude Bot commented Jun 4, 2026

Copy link
Copy Markdown

Reviewed the frontend audit PR. I traced the key pieces (undo history bookkeeping, projectGeneration keying, byte→UTF-16 + apply-to-all prefix mapping in equation-highlight, the Flow/Connector geometry mirror between the TS and Rust renderers, req.logout(cb) with passport 0.7's regenerate shim, and the StrictMode-safe Home.getProjects lifecycle) and could not find a blocking bug. Edge cases I specifically checked: 2-/3-/4-byte sequences and clamping in byteOffsetToUtf16; multi-line ranges spanning the apply-to-all prefix line in highlightSpansForLines; slatePointForOffset at line ends and past EOL; updateProject's early-return interaction with the new recordHistory: false branch; the noop-handler types vs. Canvas's prop signatures; the breakpoint constants in panelWidth against the CSS media queries (900/1200 px) and --panel-width-md (420 px). The fixes are well-scoped and the test additions pin them.

Overall correctness: correct.

🤖 Generated with Claude Code

@bpowers
bpowers merged commit 569924f into main Jun 4, 2026
5 checks passed
@bpowers
bpowers deleted the frontend-react-audit branch June 4, 2026 13:29
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.

1 participant