Files
multica/packages/ui/components/common/error-boundary.tsx
Naiyuan Qing 48e3131bf9 feat: harden desktop frontend against API response drift (MUL-1828) (#2208)
* docs(claude): add API Response Compatibility section

Narrows the existing "no backwards compat" rule to internal code only,
and adds a new section that codifies the defensive boundary at API
edges: parse-don't-cast, never pin UI to a single field, enum drift
must downgrade not crash.

Driven by #2143/#2147/#2192 — all three were the desktop client white-
screening on backend response shape changes the client wasn't built
against.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(core): add zod-based API response validation layer

Introduces a defensive boundary so a malformed backend response
degrades into a safe fallback (empty page, [], etc.) instead of
throwing inside React render.

- Adds zod to the pnpm catalog and as a @multica/core dependency.
- New parseWithFallback helper in core/api/schema.ts that runs
  safeParse, logs a warn with the endpoint + zod issues on failure,
  and returns the caller-supplied fallback. Never throws.
- Schemas in core/api/schemas.ts are deliberately lenient (string
  enums kept as z.string() so unknown values still parse, optional
  fields default, nested records use .loose() for unknown keys).
- Wires setSchemaLogger from CoreProvider so warnings flow through
  the same logger as the rest of the API client.

This is the primitive — see the next commit for the call-site wiring.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(api): guard top 5 high-risk endpoints with parseWithFallback

Wraps the response of the five endpoints whose UIs white-screened in
past incidents (#2143/#2147/#2192) so a contract drift returns a safe
fallback instead of crashing the consumer:

- listIssues          → ListIssuesResponseSchema, fallback { issues: [], total: 0 }
- listTimeline        → TimelinePageSchema,        fallback empty page
- listComments        → CommentsListSchema,        fallback []
- listIssueSubscribers → SubscribersListSchema,    fallback []
- listChildIssues     → ChildIssuesResponseSchema, fallback { issues: [] }

getIssue is intentionally NOT wrapped: there is no sensible "empty
issue" — the entire detail page depends on real fields. The page-level
ErrorBoundary (separate commit) catches that case.

Adds schema.test.ts with 9 cases covering the five failure modes
listed in MUL-1828: missing fields, wrong types, enum drift, null
body, and null arrays.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(ui): add ErrorBoundary and wrap high-risk pages

Section-level error boundary (no third-party dep — class component +
default fallback in @multica/ui). Supports a fallback render prop and
resetKeys for auto-recovery on resource navigation.

Wraps the surfaces that white-screened in past incidents:

- IssueDetail (web + desktop + inbox split-pane) — keyed on issueId
  so navigating to a different issue clears the boundary automatically.
- IssuesPage (web + desktop).

Boundaries are placed at consumer call sites rather than inside
IssueDetail itself so we don't have to refactor the 1100-line
component, and so a crash inside one inbox split-pane doesn't take
down the inbox list next to it.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(core): make all API schemas .loose() to preserve unknown fields

zod 4 z.object() defaults to STRIP, which silently drops fields the
schema didn't list. That makes the schema layer a sync point: a future
PR adding a TS field but forgetting the schema would have the field
disappear at runtime while TS still claims it exists — the exact bug-
class this PR is meant to prevent, just inverted.

Apply .loose() to every object schema (TimelineEntry, TimelinePage,
Comment, Issue, ListIssuesResponse, Subscriber, ChildIssuesResponse)
so unknown server-side fields pass through unchanged. Add a regression
test that feeds a payload with extra fields at both entry and page
level, and a direct unit test for parseWithFallback decoupled from any
endpoint. Update the listIssues fallback test to use a wrong-type
payload — under .loose() the previous "{ unexpected: true }" payload
parses successfully (every declared field has a default) instead of
triggering the fallback path it was meant to exercise.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs(claude): strip field-specific examples from API Compatibility section

The original wording embedded current schema field names (entries,
has_more_before, has_more_after, cursor, status, type) directly in the
rules. CLAUDE.md should state the rule, not the implementation — once a
field is renamed the doc drifts out of sync with the code, and the
specific names don't add anything the abstract rule doesn't.

Keep the rule, drop the field-level archaeology.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>
2026-05-07 15:09:55 +08:00

100 lines
3.3 KiB
TypeScript

"use client";
import { Component, type ErrorInfo, type ReactNode } from "react";
import { Button } from "../ui/button";
export interface ErrorBoundaryProps {
children: ReactNode;
/** Element rendered when the boundary catches. Receives `reset` so the
* fallback can offer a "try again" button. Defaults to a small inline
* panel suitable for a section, not a full-page takeover. */
fallback?: (args: { error: Error; reset: () => void }) => ReactNode;
/** Hook for telemetry/logging. Called with the captured error and the
* React error info (component stack). */
onError?: (error: Error, info: ErrorInfo) => void;
/** When any value in this array changes between renders, the boundary
* resets. Use this to auto-recover when navigating to a new resource
* (e.g. a different issueId) without forcing the user to click "retry". */
resetKeys?: ReadonlyArray<unknown>;
}
interface ErrorBoundaryState {
error: Error | null;
}
const INITIAL_STATE: ErrorBoundaryState = { error: null };
/**
* Section-level error boundary. Wrap individual UI sections (the timeline,
* the comment list, a sidebar panel) so a render-time crash in one section
* does not blank the whole page. See CLAUDE.md "API Response Compatibility".
*
* For full-page takeovers prefer route-level error UIs (Next.js error.tsx,
* router error elements). This component is for the in-page recovery case.
*/
export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
state: ErrorBoundaryState = INITIAL_STATE;
static getDerivedStateFromError(error: Error): ErrorBoundaryState {
return { error };
}
override componentDidCatch(error: Error, info: ErrorInfo): void {
this.props.onError?.(error, info);
// Log unconditionally so a missing onError doesn't swallow the trace.
// Console is fine here — the platform logger isn't bound to UI yet.
console.error("ErrorBoundary caught:", error, info.componentStack);
}
override componentDidUpdate(prevProps: ErrorBoundaryProps): void {
if (this.state.error == null) return;
const prev = prevProps.resetKeys;
const next = this.props.resetKeys;
if (!prev || !next) return;
if (prev.length !== next.length) {
this.reset();
return;
}
for (let i = 0; i < prev.length; i++) {
if (!Object.is(prev[i], next[i])) {
this.reset();
return;
}
}
}
reset = (): void => {
this.setState(INITIAL_STATE);
};
override render(): ReactNode {
const { error } = this.state;
if (error == null) return this.props.children;
if (this.props.fallback) {
return this.props.fallback({ error, reset: this.reset });
}
return <DefaultFallback error={error} reset={this.reset} />;
}
}
function DefaultFallback({ error, reset }: { error: Error; reset: () => void }) {
return (
<div
role="alert"
className="flex flex-col items-start gap-3 rounded-md border border-dashed border-border bg-muted/30 p-4 text-sm"
>
<div className="space-y-1">
<p className="font-medium text-foreground">
Something went wrong displaying this section.
</p>
<p className="text-muted-foreground">
{error.message || "An unexpected error occurred."}
</p>
</div>
<Button size="sm" variant="outline" onClick={reset}>
Try again
</Button>
</div>
);
}