Repository navigation
fix(apps): typed API error for four app clients instead of a bare Error - #7074
Conversation
Design Review (Fable 5) — ✅ PASSDesign-level review of Design-Verdict: PASS Real four-way duplication fixed at the shared layer, with the extraction kept side-effect-light, back-compat pinned by a class-identity test, and both behavior changes declared and tested. [DESIGN-REVIEWED] e4be4dc |
UX Review (Fable 5) — ✅ PASSUX-level review of All lenses check out. This is a strictly-improving change: raw JSON envelopes ( UX-Verdict: PASS Refusals in four apps now render the backend's human sentence instead of a raw JSON envelope — strictly better copy, no new UX surface introduced. [UX-REVIEWED] e4be4dc |
GPT 5.6 Review — ✅ no blocking findingsGPT 5.6 completed its review of This comment is updated in place on each push. Review detailsNo findings. False positive or not applicable? A repository writer can comment: |
Opus 4.8 Review — ✅ no blocking findingsReviewed Review detailsNo findings that block; one advisory. FINDING — website/temp-screenshots/app-api-typed-errors.png:1 — a throwaway screenshot binary ( [OPUS-REVIEWED] e4be4dc Verdict parsed from the review's SHA-scoped output markers for commit False positive or not applicable? A repository writer can comment: |
First Principles Review (Fable 5) — 🟡 CONCERNSPremise-level review of All evidence is gathered. The change checks out against its description: the four files are fully converted (grep for First-Principles-Verdict: CONCERNS The shared error module earns its place, but the duplication it cites as motivation — crew-companion's and md-notebook's own What this change shipsIntent: make refusals from four app clients render the backend's sentence, not the wire JSON, and carry the HTTP status. This is a FIX.
Watch
[FIRST-PRINCIPLES-REVIEWED] e4be4dc |
0b55ef9 to
bff943d
Compare
bff943d to
ba14471
Compare
Disposition -- First Principles CONCERNS on
|
…Error
design-tweak, file-explorer, design-critique and mochi each threw
`new Error(body || \`HTTP <status>\`)` on a non-2xx response. Two consequences:
* the raw response body became the error MESSAGE, so a backend refusal such as
{"error": "path is outside the sandbox"} reached the UI as that JSON envelope
verbatim -- escaped quotes, no real newlines -- wherever the app renders
e.message; and
* the status was thrown away, so no caller could branch on it (404 vs 409 vs a
403 auth expiry) without regex-matching prose. Latent today because none of
the four callers branches yet; it bites the first one that needs to, which is
how the Dev Fleet version of this bug was originally found.
The dashboard already solved both halves in api/client.ts: ApiError carries
status + raw body, and friendlyErrText unwraps {error|detail|message} for
display. The fix reuses those rather than adding a fourth and fifth app-local
copy of the same class (crew-companion and md-notebook already have their own).
They could not simply be imported: client.ts is ~3.5k lines whose module graph
pulls in queryClient, installApiTransport, artifact-write bookkeeping and the
error journal. file-explorer already imports it for other reasons, but
design-tweak, design-critique and mochi do not, and making an app depend on the
dashboard's transport just to name an error type is what the Bundle Size Gate
exists to catch. So ApiError and friendlyErrText move to a new side-effect-free
api/apiError.ts, and client.ts re-exports both -- every existing import path,
and every test that mocks '../api/client', is unchanged by the move.
The new toApiError(Response) is the piece the four clients actually needed: read
the body once, unwrap the human message, keep the envelope in .body, set
authRequired from 403 + X-Auth-Required, and fall back to `HTTP <status>` on an
empty body so an empty-body refusal reads exactly as it did before. It
deliberately does NOT journal to utils/errorReport and does NOT raise the
stale-owner prompt, both of which client.ts::apiFailure layers on top: those are
dashboard-session concerns and they are the side effects this split exists to
keep out of app bundles.
Behaviour change worth naming: mochi's message loses its `mochi api <path>:`
prefix. That prefix was diagnostic text in a user-facing string; the status and
body now travel on the error, and the request path is in the network panel.
Tests: per-client assertions (not one shared-helper test) because the bug was
four independent copies of the same mistake, so a single client drifting back
must fail on its own. Each of the four reverted to the bare Error individually
reddens exactly its own case. Also covered: JSON unwrapping, the empty-body
fallback, the auth-expiry flag, an unreadable body, and that client.ts re-exports
the SAME class identity so dashboard instanceof checks still match app errors.
toApiError reads the auth header defensively (`r.headers?.get?.`) because it runs
ON the failure path: anything it throws REPLACES the real error with a misleading
one. FileExplorerApiCov80's own fetch stub omits `headers`, and an unguarded read
surfaced "Cannot read properties of undefined" where the backend had said "zzz
outside the allowed roots" -- strictly worse than the raw-JSON message this
change set out to fix. That pre-existing test passes unchanged with the guard,
and a new case pins it.
Evidence: website/temp-screenshots/app-api-typed-errors.png shows the real
FileViewer error surface with both messages, each computed by its own code path
from the same refusal body rather than transcribed.
ba14471 to
e4be4dc
Compare
Disposition -- First Principles CONCERNS on
|
bolichen97
left a comment
There was a problem hiding this comment.
Readiness passed on the current head, all checks green, mergeable against main, and no outstanding change requests from any reviewer. Approving as part of a maintainer sweep of fix-type PRs.
Open PR relationship auditThis is a consolidated, point-in-time code-level audit note. It compares complete merge-base diffs and current/merged code; it does not treat a shared topic as duplication or partial coverage as completion. Relationship findings
No PR, Issue, label, branch, or review state was changed by the relationship-note portion of this audit. |
1. What is the problem?
Four app API clients threw a bare
Errorcarrying the raw response body:website/src/apps/design-tweak/api.tsparse()website/src/apps/file-explorer/api.tsget()website/src/apps/design-critique/api.tsjsonFetch()website/src/apps/mochi/api.tsrequest()The first three were the identical
throw new Error(body || \HTTP ${r.status}`)`;mochi's variant put the status and a 200-char body slice into the message text.
Two things fall out of that:
{"error": "path is outside the sandbox"}, so wherever the app renderse.messagethe user sees that JSON envelope verbatim -- escaped quotes,\ninstead of real newlines.
a 403 auth expiry, without regex-matching prose. No caller of these four
branches on status today, so this is latent -- but it bites the first one that
needs to, which is exactly how the Dev Fleet version of this bug was found.
This is a sibling of the ErrorPanel work: same root cause, four clients that were
never converted.
2. Why this issue matters to the user
Any refusal from these four apps renders as unstructured wire JSON. That is the
whole visible failure mode -- a user asking File Explorer for a path outside the
sandbox gets
{"error":"path is outside the sandbox"}rather than the sentenceinside it.
For contributors, the cost is the next person to need status branching in one of
these apps. With the status thrown away there is no correct way to add it locally,
so they either re-derive the typed error a fifth time or match on message text --
and message text is localized prose, so matching it is a bug waiting to happen.
3. How our fix solves it
The dashboard already solved both halves in
api/client.ts:ApiErrorcarriesstatus+ the rawbody, andfriendlyErrTextunwraps{error|detail|message}for display. The fix reuses those rather than adding a fifth and sixth app-local
copy of the same idea.
To be precise about what that does and does not achieve: two app-local
ApiErrorclasses already exist (
crew-companion/api.ts,md-notebook/api.ts) and thisPR removes neither. Each carries a field the shared class lacks
(
code,staleBackend), so converging them needs those fields to have a homefirst -- a separate change with its own review. The claim here is narrower: a
side-effect-free shared module now EXISTS, so the four clients in this diff did
not have to mint a third and fourth spelling, and a future consolidation has
somewhere to land.
They could not simply be imported.
client.tsis ~3.5k lines and its module graphpulls in
queryClient,installApiTransport, artifact-write bookkeeping and theerror journal.
file-exploreralready imports it for other reasons, butdesign-tweak, design-critique and mochi do not -- and making a standalone app
depend on the dashboard's transport just to name an error type is the kind of
regression the Bundle Size Gate exists to catch.
So the two symbols move to a new side-effect-free
api/apiError.ts, andclient.tsre-exports both. Every existing import path is unchanged, includingpages/devFleetApi.tsand the seven test files that mock../api/client-- themove is invisible to them.
The new
toApiError(Response)is the piece the four clients actually needed:Each client's error branch becomes
throw await toApiError(r).All bare throws in these four files are converted, not just the shared helpers.
The first draft converted only the four central
parse/get/jsonFetch/requestfunctions, which left four sibling
throw new Error(...)calls behind in the samefiles -- a point patch inside its own blast radius. Now also converted:
design-tweak/api.ts(the chat-API helper, which discarded the body entirely),mochi/api.ts(probeEnabled, whose 403/503 -> disabled/starting mapping isuntouched, and
enableMochi), anddesign-critique/api.ts(uploadFiles).Grepping
throw new Erroracross all four files now returns nothing.Three deliberate choices:
HTTP <status>fallback is preserved, because that is whatbody || \HTTP ${status}`` did. An empty-body refusal reads exactly as it didbefore.
.catch(() => ''),matching the previous calls), so a refusal that fails mid-stream still yields
the status instead of throwing something unrelated out of the error path. The
auth-header read is guarded for the same reason -- see section 4.
utils/errorReportand does NOT raise the stale-ownerprompt.
client.ts::apiFailurelayers both on top for dashboard calls. Thoseare dashboard-session concerns, and they are precisely the side effects this
split exists to keep out of app bundles.
Two behaviour changes, both intended, neither silent:
mochi api <path>:prefix. That prefix wasdiagnostic text living in a user-facing string; the status and body now travel
on the error object, and the request path is in the browser's network panel.
Uniformity across the four clients is the point, so keeping one bespoke message
shape would have defeated it.
friendlyErrText's 429 branchreplaces the body with the tunnel-edge rate-limit sentence, because a dashboard
behind API Gateway receives the opaque
{"message":"Rate exceeded","throttlingReasons":null}and rendering thatverbatim is useless. So a 429 through these four clients now reads as that
sentence where it previously showed the raw throttle envelope. This is the one
case that is NOT purely additive; it is pinned by its own test, and the original
envelope stays on
.body. (Caught by review -- an earlier draft of thisdescription claimed the change was "strictly additive for every existing
caller", which this contradicts.)
4. What tests we did
Visual evidence
The user-visible delta is the message text itself. Both panels below are the real
FileViewererror surface (FileExplorerPage.tsx:446passes the caughte.messagestraight into it), rendered with the two strings the two code pathsproduce for the SAME 403 body -- each computed by its own expression in the
harness rather than transcribed, so the image cannot drift from what the code
does:
Committed at
website/temp-screenshots/app-api-typed-errors.png. The capturescript asserts both messages are present and differ before it will save, so a
blank or stale bundle cannot be shipped as evidence.
The other three clients share the identical code path and are covered by the
per-client assertions below rather than by three more near-identical images.
Automated tests
src/test/appApiTypedErrors.test.tsasserts the contract per client ratherthan once against the shared helper. That is deliberate: the bug was four
independent copies of the same mistake, so a single client drifting back must fail
on its own. Verified by reverting each of the four individually -- each reddens
exactly its own case and leaves the other three green:
design-tweak(+ the shared empty-body case)file-explorer(+ the shared empty-body case)design-critique(+ the shared empty-body case)mochi(+ the shared empty-body case)src/test/apiError.test.tscovers the helper, each assertion mutation-verified:authRequiredhardcoded falseflags an auth-expiry refusal...|| HTTP <status>fallbackfalls back to HTTP <status>...,survives a body that cannot be read, and the shared per-client caser.headers.get)survives a Response-like object with no headersAND the pre-existingFileExplorerApiCov80caseOne thing CI caught that local runs had not.
Frontend Tests (1)failed onthe first push:
FileExplorerApiCov80.test.ts's own fetch stub omitsheaders,so an unguarded
r.headers.get(...)threw aTypeErrorinside the error path --surfacing "Cannot read properties of undefined" where the backend had said "zzz
outside the allowed roots". That is strictly worse than the raw-JSON message this
PR exists to fix, so the header read is now defensive (
r.headers?.get?.). Thisis a real robustness property, not test appeasement: a factory that builds errors
must never throw, or it destroys the failure it was called to describe. The
pre-existing test passes unchanged with the guard in place -- it was not edited.
Also covered: JSON unwrapping (with an explicit assertion that
{"error"doesnot survive into the message), a non-JSON body passing through, the envelope
staying reachable on
.body, andApiErrorstill being anErrorwhosenameis
ApiErrorso existinge instanceof Error ? e.message : String(e)fallbackskeep working.
One test guards the move itself:
client.ApiErrormust be the same classidentity as the defining module's. If the re-export ever became a second class,
instanceof ApiErrorchecks in the dashboard would silently stop matching errorsthrown by app clients -- a failure that would otherwise be invisible until
something misbehaved at runtime.
Run targeted (this host cannot take a full vitest run; CI covers the rest): the
three new/related error suites,
mochiApiSeam,ApiClient.coverage(682 tests),errorToAgent,SecurityPanel,FolderConfigModal, the six suites that mockApiError, and the DesignCritique page suites -- 863 + 156 + 52 passing.tsc --noEmitandeslintclean on all eight touched files.5. Any other suggestions on the work
the four clients named in the backlog finding; it is not the end of the pattern.
grep "throw new Error" src/apps/**/api.tsstill returns 56 sites in otherapp clients:
issue-radar/api.ts(50, all the single shapethrow new Error(await parseErrorBody(r))),md-notebook(4),personal-shopper/api.ts:19,ops-mission-control/api.ts:1087. Accepted anddeferred deliberately: issue-radar's 50 share one helper and would convert as a
single mechanical change of their own, and md-notebook's throw
body.error--an already-extracted human message, not raw wire JSON -- so they are a milder
grade of the same problem. Rolling any of them in here would make this diff
unreviewable.
ApiErrorclasses survive this PR (crew-companion/api.ts:16carrying
code,md-notebook/api.ts:16carryingstaleBackend). Now that aside-effect-free shared module exists they could collapse onto it, but each needs
its extra field to have a home on the shared type first, so that is its own
change. Flagged rather than buried, because leaving them indefinitely is how a
third spelling gets minted.
friendlyErrTextmoved with its existing 429 key intact.