Repository navigation
Frontend audit: fix React/state/CSS bugs in src/app and src/diagram - #713
Conversation
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.
|
@codex review |
There was a problem hiding this comment.
💡 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".
| } catch (err) { | ||
| console.error('logout: firebase signOut failed:', err); | ||
| } | ||
| await userInfo.invalidate(); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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).
|
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):
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.
|
Reviewed the frontend audit PR. I traced the key pieces (undo history bookkeeping, Overall correctness: correct. 🤖 Generated with Claude Code |
What this is
A systematic bug audit of the frontend TypeScript/React/CSS code in
src/appandsrc/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)
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 newprojectGenerationthat 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 tokatex.renderToString, renderingrevenue_per_unitwith_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 newequation-highlightmodule converts offsets, shifts past the{apply-to-all:}prefix, and highlights across lines (caret placement from preview clicks got the same fix)..basespans withwhite-space: nowrap, whichoverflow-wrapon an ancestor can't break, and the flex container refused to shrink (min-width: auto). Fixed with a.baseoverride (higher specificity than katex.css),min-width: 0, andoverflow-x: autoas the unbreakable-content fallback.reset.css(the universalbox-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 explicitimport '@simlin/diagram/reset.css'in the app entry (verified present in the rebuilt bundle) and explicitbox-sizing: border-boxon 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
advanceProjectHistory.flowStillBeingCreatedwas never reset (the reset was atrue-for-falsetypo), so a later Escape-cancel of any rename deleted that variable.DELETE /sessionwas a TODO stub that never even wrote a response. Both halves implemented (Firebase signOut + session invalidation via passportreq.logout()+ seshcookie rewrite, with an end-to-end server test).DialoggaineddisableBackdropClickand 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
initialValuechanges, 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.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.Verification
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.Follow-ups filed: #707 (per-frame engine round-trips), #708 (reset.css tree-shaking), #709 (component-library dark mode), #710 (Menu anchor tracking).