Files
multica/packages/core/platform/core-provider.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

125 lines
3.7 KiB
TypeScript

"use client";
import { useMemo } from "react";
import { ApiClient } from "../api/client";
import { setApiInstance, setSchemaLogger } from "../api";
import { createAuthStore, registerAuthStore } from "../auth";
import { createChatStore, registerChatStore } from "../chat";
import {
I18nProvider,
LocaleAdapterProvider,
UserLocaleSync,
} from "../i18n/react";
import { WSProvider } from "../realtime";
import { QueryProvider } from "../provider";
import { createLogger } from "../logger";
import { defaultStorage } from "./storage";
import { AuthInitializer } from "./auth-initializer";
import type { CoreProviderProps, ClientIdentity } from "./types";
import type { StorageAdapter } from "../types/storage";
// Module-level singletons — created once at first render, never recreated.
// Vite HMR preserves module-level state, so these survive hot reloads.
let initialized = false;
let authStore: ReturnType<typeof createAuthStore>;
let chatStore: ReturnType<typeof createChatStore>;
function initCore(
apiBaseUrl: string,
storage: StorageAdapter,
onLogin?: () => void,
onLogout?: () => void,
cookieAuth?: boolean,
identity?: ClientIdentity,
) {
if (initialized) return;
const api = new ApiClient(apiBaseUrl, {
logger: createLogger("api"),
onUnauthorized: () => {
storage.removeItem("multica_token");
},
identity,
});
setApiInstance(api);
setSchemaLogger(createLogger("api-schema"));
// In token mode, hydrate token from storage.
if (!cookieAuth) {
const token = storage.getItem("multica_token");
if (token) api.setToken(token);
}
// Workspace identity is URL-driven: the [workspaceSlug] layout resolves
// the slug and calls setCurrentWorkspace(slug, wsId) on mount. The api
// client reads the slug from that singleton for the X-Workspace-Slug
// header. No boot-time hydration from storage is required.
authStore = createAuthStore({ api, storage, onLogin, onLogout, cookieAuth });
registerAuthStore(authStore);
chatStore = createChatStore({ storage });
registerChatStore(chatStore);
initialized = true;
}
export function CoreProvider({
children,
apiBaseUrl = "",
wsUrl = "ws://localhost:8080/ws",
storage = defaultStorage,
cookieAuth,
onLogin,
onLogout,
identity,
locale,
resources,
localeAdapter,
}: CoreProviderProps) {
// Initialize singletons on first render only. Dependencies are read-once:
// apiBaseUrl, storage, and callbacks are set at app boot and never change at runtime.
// eslint-disable-next-line react-hooks/exhaustive-deps
useMemo(() => initCore(apiBaseUrl, storage, onLogin, onLogout, cookieAuth, identity), []);
// I18nProvider wraps everything else: server and client must use the same
// (locale, resources) to avoid hydration mismatch. Language switching goes
// through window.location.reload(), never client-side changeLanguage.
const tree = (
<QueryProvider>
<AuthInitializer
onLogin={onLogin}
onLogout={onLogout}
storage={storage}
cookieAuth={cookieAuth}
identity={identity}
>
<WSProvider
wsUrl={wsUrl}
authStore={authStore}
storage={storage}
cookieAuth={cookieAuth}
identity={identity}
>
{children}
</WSProvider>
</AuthInitializer>
</QueryProvider>
);
// UserLocaleSync requires a LocaleAdapter to persist; only mount it when
// the host app provides one (web layout + desktop App both do).
const withAdapter = localeAdapter ? (
<LocaleAdapterProvider adapter={localeAdapter}>
<UserLocaleSync />
{tree}
</LocaleAdapterProvider>
) : (
tree
);
return (
<I18nProvider locale={locale} resources={resources}>
{withAdapter}
</I18nProvider>
);
}