Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat: harden desktop frontend against API response drift (MUL-1828) (#2208)
Naiyuan Qing48e3131bf91b
diff --git a/CLAUDE.md b/CLAUDE.mdindex c2669747b3..69fbee1920 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -146,11 +146,27 @@ make start-worktree # Start using .env.worktree- Go code follows standard Go conventions (gofmt, go vet).- Keep comments in code **English only**.- Prefer existing patterns/components over introducing parallel abstractions.-- Unless the user explicitly asks for backwards compatibility, do **not** add compatibility layers, fallback paths, dual-write logic, legacy adapters, or temporary shims.+- Unless the user explicitly asks for backwards compatibility, do **not** add compatibility layers, fallback paths, dual-write logic, legacy adapters, or temporary shims **for internal, non-boundary code** (a function calling another function in the same package, a component reading its own state, a store helper, etc.).+- This rule does **not** apply at API boundaries: the desktop app cannot assume the backend it talks to has the same shape as the one it was built against (older desktop installs will outlive any given server build). API response handling must follow the rules in **API Response Compatibility** below — that is a defensive boundary, not a legacy shim.- If a flow or API is being replaced and the product is not yet live, prefer removing the old path instead of preserving both old and new behavior.- Avoid broad refactors unless required by the task.- New global (pre-workspace) routes MUST use a single word (`/login`, `/inbox`) or a `/{noun}/{verb}` pair (`/workspaces/new`). NEVER add hyphenated word-group root routes (`/new-workspace`, `/create-team`) — they collide with common user workspace names and force endless reserved-slug audits. Reserving the noun (`workspaces`) automatically protects the entire `/workspaces/*` subtree.+### API Response Compatibility++The desktop app installed on a user's machine is older than any backend it talks to: a user on 0.2.26 will hit a server running 0.3.x, then 0.4.x, then beyond. Every response shape is a contract that **will** drift, and the frontend must survive drift without white-screening. Three concrete incidents already happened from violating this — #2143, #2147, #2192.++When writing code that consumes an API response, follow these rules:++- **Parse, don't cast.** Untyped JSON crossing the network is not `T`. Use `parseWithFallback` in `packages/core/api/schema.ts` with a `zod` schema and an explicit fallback. On validation failure it logs a warning and returns the fallback; it never throws into the UI.+- **No bare `as` casts on response bodies.** Every endpoint method whose response is consumed by UI logic must run through a schema before returning.+- **Optional-chain and default everywhere downstream.** Treat every field as possibly missing. Use explicit boolean checks (`=== true`) over truthy/falsy negation, which silently treats `undefined` and `null` as `false`.+- **Don't pin a UI affordance to a single backend field.** If a button or indicator depends on exactly one boolean from the server, a backend bug deletes it. Combine signals (cursor presence, page length, etc.) so the affordance stays available in the worst case.+- **Enum drift downgrades, not crashes.** A new server-side enum value should render a generic fallback. `switch` statements on server-driven strings must have a `default` branch.+- **When you add or change an endpoint:** add the schema in the same PR, and write at least one test that feeds a malformed response through it (missing field, wrong type, `null` array). The test fails closed if a future change breaks the contract.++This is not premature defense — it is the *only* defense for an installed-app architecture. CSR-only browser apps can ship a fix in minutes; an Electron build sitting on a developer's laptop cannot.+### Backend Handler UUID Parsing ConventionEvery Go handler in `server/internal/handler/` follows these rules. The convention exists because `util.ParseUUID` used to silently return a zero UUID on invalid input, which caused #1661 — a `DELETE` returning 204 success while the SQL `DELETE` matched zero rows.diff --git a/apps/desktop/src/renderer/src/pages/issue-detail-page.tsx b/apps/desktop/src/renderer/src/pages/issue-detail-page.tsxindex b0403d981b..31d1d5a831 100644--- a/apps/desktop/src/renderer/src/pages/issue-detail-page.tsx+++ b/apps/desktop/src/renderer/src/pages/issue-detail-page.tsx@@ -1,6 +1,7 @@import { useParams } from "react-router-dom";import { useQuery } from "@tanstack/react-query";import { IssueDetail } from "@multica/views/issues/components";+import { ErrorBoundary } from "@multica/ui/components/common/error-boundary";import { useWorkspaceId } from "@multica/core/hooks";import { issueDetailOptions } from "@multica/core/issues/queries";import { useDocumentTitle } from "@/hooks/use-document-title";@@ -13,5 +14,9 @@ export function IssueDetailPage() {useDocumentTitle(issue ? `${issue.identifier}: ${issue.title}` : "Issue");if (!id) return null;- return <IssueDetail issueId={id} />;+ return (+ <ErrorBoundary resetKeys={[id]}>+ <IssueDetail issueId={id} />+ </ErrorBoundary>+ );}diff --git a/apps/desktop/src/renderer/src/routes.tsx b/apps/desktop/src/renderer/src/routes.tsxindex 09f65415b5..2d21cb3ba7 100644--- a/apps/desktop/src/renderer/src/routes.tsx+++ b/apps/desktop/src/renderer/src/routes.tsx@@ -21,6 +21,7 @@ import { DesktopRuntimesPage } from "./components/desktop-runtimes-page";import { AgentsPage } from "@multica/views/agents";import { InboxPage } from "@multica/views/inbox";import { SettingsPage } from "@multica/views/settings";+import { ErrorBoundary } from "@multica/ui/components/common/error-boundary";import { Download, Server } from "lucide-react";import { DaemonSettingsTab } from "./components/daemon-settings-tab";import { UpdatesSettingsTab } from "./components/updates-settings-tab";@@ -83,7 +84,15 @@ export const appRoutes: RouteObject[] = [element: <WorkspaceRouteLayout />,children: [{ index: true, element: <Navigate to="issues" replace /> },- { path: "issues", element: <IssuesPage />, handle: { title: "Issues" } },+ {+ path: "issues",+ element: (+ <ErrorBoundary>+ <IssuesPage />+ </ErrorBoundary>+ ),+ handle: { title: "Issues" },+ },{path: "issues/:id",element: <IssueDetailPage />,diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/issues/[id]/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/issues/[id]/page.tsxindex a60ac2228d..6f90958db8 100644--- a/apps/web/app/[workspaceSlug]/(dashboard)/issues/[id]/page.tsx+++ b/apps/web/app/[workspaceSlug]/(dashboard)/issues/[id]/page.tsx@@ -2,6 +2,7 @@import { use } from "react";import { IssueDetail } from "@multica/views/issues/components";+import { ErrorBoundary } from "@multica/ui/components/common/error-boundary";export default function IssueDetailPage({params,@@ -9,5 +10,9 @@ export default function IssueDetailPage({params: Promise<{ id: string }>;}) {const { id } = use(params);- return <IssueDetail issueId={id} />;+ return (+ <ErrorBoundary resetKeys={[id]}>+ <IssueDetail issueId={id} />+ </ErrorBoundary>+ );}diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/issues/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/issues/page.tsxindex af5cbb2909..0892c7753b 100644--- a/apps/web/app/[workspaceSlug]/(dashboard)/issues/page.tsx+++ b/apps/web/app/[workspaceSlug]/(dashboard)/issues/page.tsx@@ -1,7 +1,12 @@"use client";import { IssuesPage } from "@multica/views/issues/components";+import { ErrorBoundary } from "@multica/ui/components/common/error-boundary";export default function Page() {- return <IssuesPage />;+ return (+ <ErrorBoundary>+ <IssuesPage />+ </ErrorBoundary>+ );}diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex b0c8d79e8f..efc37f42bb 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -87,6 +87,16 @@ import type { OnboardingCompletionPath } from "../onboarding/types";import { type Logger, noopLogger } from "../logger";import { createRequestId } from "../utils";import { getCurrentSlug } from "../platform/workspace-storage";+import { parseWithFallback } from "./schema";+import {+ ChildIssuesResponseSchema,+ CommentsListSchema,+ EMPTY_LIST_ISSUES_RESPONSE,+ EMPTY_TIMELINE_PAGE,+ ListIssuesResponseSchema,+ SubscribersListSchema,+ TimelinePageSchema,+} from "./schemas";/** Identifies the calling client to the server.* Sent on every HTTP request as X-Client-Platform / X-Client-Version /@@ -398,7 +408,11 @@ export class ApiClient {if (params?.creator_id) search.set("creator_id", params.creator_id);if (params?.project_id) search.set("project_id", params.project_id);if (params?.open_only) search.set("open_only", "true");- return this.fetch(`/api/issues?${search}`);+ const path = `/api/issues?${search}`;+ const raw = await this.fetch<unknown>(path);+ return parseWithFallback(raw, ListIssuesResponseSchema, EMPTY_LIST_ISSUES_RESPONSE, {+ endpoint: "GET /api/issues",+ });}async searchIssues(params: { q: string; limit?: number; offset?: number; include_closed?: boolean; signal?: AbortSignal }): Promise<SearchIssuesResponse> {@@ -454,7 +468,10 @@ export class ApiClient {}async listChildIssues(id: string): Promise<{ issues: Issue[] }> {- return this.fetch(`/api/issues/${id}/children`);+ const raw = await this.fetch<unknown>(`/api/issues/${id}/children`);+ return parseWithFallback(raw, ChildIssuesResponseSchema, { issues: [] }, {+ endpoint: "GET /api/issues/:id/children",+ });}async getChildIssueProgress(): Promise<{ progress: { parent_issue_id: string; total: number; done: number }[] }> {@@ -481,7 +498,10 @@ export class ApiClient {// Commentsasync listComments(issueId: string): Promise<Comment[]> {- return this.fetch(`/api/issues/${issueId}/comments`);+ const raw = await this.fetch<unknown>(`/api/issues/${issueId}/comments`);+ return parseWithFallback(raw, CommentsListSchema, [], {+ endpoint: "GET /api/issues/:id/comments",+ });}async createComment(issueId: string, content: string, type?: string, parentId?: string, attachmentIds?: string[]): Promise<Comment> {@@ -506,7 +526,12 @@ export class ApiClient {if (pageParam.mode === "before") params.set("before", pageParam.cursor);else if (pageParam.mode === "after") params.set("after", pageParam.cursor);else if (pageParam.mode === "around") params.set("around", pageParam.id);- return this.fetch(`/api/issues/${issueId}/timeline?${params.toString()}`);+ const raw = await this.fetch<unknown>(+ `/api/issues/${issueId}/timeline?${params.toString()}`,+ );+ return parseWithFallback(raw, TimelinePageSchema, EMPTY_TIMELINE_PAGE, {+ endpoint: "GET /api/issues/:id/timeline",+ });}async getAssigneeFrequency(): Promise<AssigneeFrequencyEntry[]> {@@ -554,7 +579,10 @@ export class ApiClient {// Subscribersasync listIssueSubscribers(issueId: string): Promise<IssueSubscriber[]> {- return this.fetch(`/api/issues/${issueId}/subscribers`);+ const raw = await this.fetch<unknown>(`/api/issues/${issueId}/subscribers`);+ return parseWithFallback(raw, SubscribersListSchema, [], {+ endpoint: "GET /api/issues/:id/subscribers",+ });}async subscribeToIssue(issueId: string, userId?: string, userType?: string): Promise<void> {diff --git a/packages/core/api/index.ts b/packages/core/api/index.tsindex 3d26b86188..10d43337d9 100644--- a/packages/core/api/index.ts+++ b/packages/core/api/index.ts@@ -6,6 +6,8 @@ export type {ImportStarterIssuePayload,ImportStarterWelcomeIssueTemplate,} from "./client";+export { parseWithFallback, setSchemaLogger } from "./schema";+export type { ParseOptions } from "./schema";export { WSClient } from "./ws-client";import type { ApiClient as ApiClientType } from "./client";diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.tsnew file mode 100644index 0000000000..680f8c4318--- /dev/null+++ b/packages/core/api/schema.test.ts@@ -0,0 +1,195 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { z } from "zod";+import { ApiClient } from "./client";+import { parseWithFallback } from "./schema";++// Helper: stub fetch with a single JSON response. Status defaults to 200.+function stubFetchJson(body: unknown, status = 200) {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ new Response(typeof body === "string" ? body : JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" },+ }),+ ),+ );+}++afterEach(() => {+ vi.unstubAllGlobals();+});++// These tests cover the five failure modes that white-screened the desktop+// app in past incidents. The contract is: a malformed response degrades to+// an empty/safe shape, never throws into React.+describe("ApiClient schema fallback", () => {+ describe("listTimeline", () => {+ it("falls back to an empty page when required fields are missing", async () => {+ stubFetchJson({});+ const client = new ApiClient("https://api.example.test");+ const page = await client.listTimeline("issue-1");+ expect(page).toEqual({+ entries: [],+ next_cursor: null,+ prev_cursor: null,+ has_more_before: false,+ has_more_after: false,+ });+ });++ it("falls back when a field has the wrong type", async () => {+ stubFetchJson({+ entries: "not-an-array",+ next_cursor: null,+ prev_cursor: null,+ has_more_before: false,+ has_more_after: false,+ });+ const client = new ApiClient("https://api.example.test");+ const page = await client.listTimeline("issue-1");+ expect(page.entries).toEqual([]);+ expect(page.has_more_after).toBe(false);+ });++ it("accepts a new entry type rather than crashing on enum drift", async () => {+ stubFetchJson({+ entries: [+ {+ type: "future_kind", // not in TS union+ id: "e-1",+ actor_type: "member",+ actor_id: "u-1",+ created_at: "2026-01-01T00:00:00Z",+ },+ ],+ next_cursor: null,+ prev_cursor: null,+ has_more_before: false,+ has_more_after: false,+ });+ const client = new ApiClient("https://api.example.test");+ const page = await client.listTimeline("issue-1");+ expect(page.entries).toHaveLength(1);+ expect(page.entries[0]?.type).toBe("future_kind");+ });++ // Forward-compat: when the server adds a new field to an existing+ // shape, `.loose()` lets it pass through unchanged. Without `.loose()`+ // zod 4 strips it, which would silently break a future TS type that+ // adopts the field — see schemas.ts header comment.+ it("preserves unknown fields the schema didn't list", async () => {+ stubFetchJson({+ entries: [+ {+ type: "comment",+ id: "e-1",+ actor_type: "member",+ actor_id: "u-1",+ created_at: "2026-01-01T00:00:00Z",+ // New server-side field not present in TimelineEntrySchema:+ future_field: { nested: "value" },+ },+ ],+ next_cursor: null,+ prev_cursor: null,+ has_more_before: false,+ has_more_after: false,+ // New top-level field not present in TimelinePageSchema:+ page_metadata: { took_ms: 42 },+ });+ const client = new ApiClient("https://api.example.test");+ const page = await client.listTimeline("issue-1");+ const raw = page as unknown as Record<string, unknown>;+ const entry = page.entries[0] as unknown as Record<string, unknown>;+ expect(entry.future_field).toEqual({ nested: "value" });+ expect(raw.page_metadata).toEqual({ took_ms: 42 });+ });++ it("returns an empty page when the body is null", async () => {+ stubFetchJson(null);+ const client = new ApiClient("https://api.example.test");+ const page = await client.listTimeline("issue-1");+ expect(page.entries).toEqual([]);+ });++ it("treats null arrays as empty arrays", async () => {+ stubFetchJson({+ entries: null,+ next_cursor: null,+ prev_cursor: null,+ has_more_before: false,+ has_more_after: false,+ });+ const client = new ApiClient("https://api.example.test");+ const page = await client.listTimeline("issue-1");+ expect(page.entries).toEqual([]);+ });+ });++ describe("listIssues", () => {+ it("falls back to an empty list when the response is malformed", async () => {+ // `issues` having the wrong type triggers the fallback. An object+ // with only unexpected keys would *succeed* parsing now (every+ // declared field has a default) and just pass the extras through+ // via `.loose()`, so we use a wrong-type payload here instead.+ stubFetchJson({ issues: "not-an-array", total: 0 });+ const client = new ApiClient("https://api.example.test");+ const res = await client.listIssues();+ expect(res).toEqual({ issues: [], total: 0 });+ });+ });++ describe("listComments", () => {+ it("returns [] when the response is not an array", async () => {+ stubFetchJson({ wrong: "shape" });+ const client = new ApiClient("https://api.example.test");+ const comments = await client.listComments("issue-1");+ expect(comments).toEqual([]);+ });+ });++ describe("listIssueSubscribers", () => {+ it("returns [] when the response is null", async () => {+ stubFetchJson(null);+ const client = new ApiClient("https://api.example.test");+ const subs = await client.listIssueSubscribers("issue-1");+ expect(subs).toEqual([]);+ });+ });++ describe("listChildIssues", () => {+ it("returns { issues: [] } when the issues field is missing", async () => {+ stubFetchJson({});+ const client = new ApiClient("https://api.example.test");+ const res = await client.listChildIssues("issue-1");+ expect(res).toEqual({ issues: [] });+ });+ });+});++// Direct tests for the helper, decoupled from any specific endpoint —+// guards against an endpoint refactor masking a regression in the helper.+describe("parseWithFallback", () => {+ const opts = { endpoint: "TEST /unit" };++ it("returns parsed data on success", () => {+ const schema = z.object({ id: z.string() });+ const out = parseWithFallback({ id: "x" }, schema, { id: "fallback" }, opts);+ expect(out).toEqual({ id: "x" });+ });++ it("returns the fallback when validation fails", () => {+ const schema = z.object({ id: z.string() });+ const fallback = { id: "fallback" };+ const out = parseWithFallback({ id: 123 }, schema, fallback, opts);+ expect(out).toBe(fallback);+ });++ it("returns the fallback when data is null", () => {+ const schema = z.object({ id: z.string() });+ const fallback = { id: "fallback" };+ const out = parseWithFallback(null, schema, fallback, opts);+ expect(out).toBe(fallback);+ });+});diff --git a/packages/core/api/schema.ts b/packages/core/api/schema.tsnew file mode 100644index 0000000000..37047f5b4b--- /dev/null+++ b/packages/core/api/schema.ts@@ -0,0 +1,55 @@+import type { ZodType } from "zod";+import { type Logger, noopLogger } from "../logger";++// Module-level logger for schema warnings. Defaults to no-op so test+// runs don't spam stderr; the platform layer wires a real logger via+// `setSchemaLogger` at app boot.+let schemaLogger: Logger = noopLogger;++export function setSchemaLogger(logger: Logger): void {+ schemaLogger = logger;+}++export interface ParseOptions {+ /** Endpoint identifier used in the warning log so we can grep for which+ * contract drifted in production telemetry. */+ endpoint: string;+}++/**+ * Validate a JSON value parsed from an API response against a zod schema,+ * returning the parsed value on success or `fallback` on failure.+ *+ * On failure we log a warning with the endpoint and zod's structured error,+ * but never throw — the UI layer must keep rendering. This is the boundary+ * defense that turns "API contract drifted" from a white-screen incident+ * into a degraded-but-rendering page.+ *+ * The return type is anchored to `T` (inferred from `fallback`), not to the+ * schema's `z.infer` type. Schemas are intentionally **lenient** — string+ * enums kept as `z.string()` so an unknown enum value still parses, etc. —+ * so the parsed runtime value can be wider than the strict TS type at the+ * call site. The caller asserts compatibility by typing the fallback to the+ * expected `T`; downstream code is already responsible for handling unknown+ * enum values via `default`-bearing switches and optional chaining.+ *+ * See CLAUDE.md "API Response Compatibility" for when to reach for this.+ */+export function parseWithFallback<T>(+ data: unknown,+ schema: ZodType,+ fallback: T,+ opts: ParseOptions,+): T {+ const result = schema.safeParse(data);+ if (result.success) return result.data as T;+ schemaLogger.warn(+ `API response failed schema validation: ${opts.endpoint}`,+ {+ endpoint: opts.endpoint,+ issues: result.error.issues,+ received: data,+ },+ );+ return fallback;+}diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsnew file mode 100644index 0000000000..5010e80cd5--- /dev/null+++ b/packages/core/api/schemas.ts@@ -0,0 +1,147 @@+import { z } from "zod";+import type { ListIssuesResponse, TimelinePage } from "../types";++// ---------------------------------------------------------------------------+// Schemas for the highest-risk API endpoints — those whose responses drive+// the issue detail page (timeline, comments, subscribers) and the issues+// list. These are the surfaces that white-screened in #2143 / #2147 / #2192.+//+// These schemas are intentionally LENIENT:+// - String enums are stored as `z.string()` rather than `z.enum([...])`.+// A new server-side enum value should render as a generic fallback in+// the UI, never crash a `safeParse`.+// - Optional fields are unioned with `null` and given fallbacks where+// existing UI code already coerces them.+// - Arrays default to `[]` so a missing `reactions` / `attachments` /+// `entries` field doesn't take the page down.+// - Every object schema ends with `.loose()` so unknown server-side+// fields pass through unchanged. zod 4's `.object()` defaults to STRIP,+// which would silently delete fields the schema didn't explicitly list+// — fine while the TS type doesn't claim them, but the moment a future+// PR adds a TS field without updating the schema, the cast `as T` lies+// and the field shows up as `undefined` at runtime. `.loose()` removes+// that synchronisation hazard.+//+// These schemas are deliberately not typed as `z.ZodType<TimelineEntry>` /+// `z.ZodType<Issue>` etc. — the strict TS types narrow string fields to+// literal unions, which would defeat the leniency above. `parseWithFallback`+// returns the parsed value cast to the caller-supplied `T`, so the strict+// type still flows out at the call site; the schema only guards shape.+// ---------------------------------------------------------------------------++const ReactionSchema = z.object({+ id: z.string(),+ comment_id: z.string(),+ actor_type: z.string(),+ actor_id: z.string(),+ emoji: z.string(),+ created_at: z.string(),+});++const AttachmentSchema = z.object({+ id: z.string(),+}).loose();++// All object schemas use `.loose()` so unknown server-side fields pass+// through unchanged. zod 4's `.object()` defaults to STRIP, which would+// silently drop new fields and surface as a "field neither showed up in+// the UI" mystery the next time the TS type adopted them but the schema+// wasn't updated in lock-step. `.loose()` removes that synchronisation+// hazard — the schema validates the shape it knows about and leaves the+// rest alone.+const TimelineEntrySchema = z.object({+ type: z.string(),+ id: z.string(),+ actor_type: z.string(),+ actor_id: z.string(),+ created_at: z.string(),+ action: z.string().optional(),+ details: z.record(z.string(), z.unknown()).optional(),+ content: z.string().optional(),+ parent_id: z.string().nullable().optional(),+ updated_at: z.string().optional(),+ comment_type: z.string().optional(),+ reactions: z.array(ReactionSchema).optional(),+ attachments: z.array(AttachmentSchema).optional(),+ coalesced_count: z.number().optional(),+}).loose();++export const TimelinePageSchema = z.object({+ entries: z.array(TimelineEntrySchema).default([]),+ next_cursor: z.string().nullable().default(null),+ prev_cursor: z.string().nullable().default(null),+ has_more_before: z.boolean().default(false),+ has_more_after: z.boolean().default(false),+ target_index: z.number().optional(),+}).loose();++export const EMPTY_TIMELINE_PAGE: TimelinePage = {+ entries: [],+ next_cursor: null,+ prev_cursor: null,+ has_more_before: false,+ has_more_after: false,+};++export const CommentSchema = z.object({+ id: z.string(),+ issue_id: z.string(),+ author_type: z.string(),+ author_id: z.string(),+ content: z.string(),+ type: z.string(),+ parent_id: z.string().nullable(),+ reactions: z.array(ReactionSchema).default([]),+ attachments: z.array(AttachmentSchema).default([]),+ created_at: z.string(),+ updated_at: z.string(),+}).loose();++export const CommentsListSchema = z.array(CommentSchema);++const IssueSchema = z.object({+ id: z.string(),+ workspace_id: z.string(),+ number: z.number(),+ identifier: z.string(),+ title: z.string(),+ description: z.string().nullable(),+ status: z.string(),+ priority: z.string(),+ assignee_type: z.string().nullable(),+ assignee_id: z.string().nullable(),+ creator_type: z.string(),+ creator_id: z.string(),+ parent_issue_id: z.string().nullable(),+ project_id: z.string().nullable(),+ position: z.number(),+ due_date: z.string().nullable(),+ reactions: z.array(z.unknown()).optional(),+ labels: z.array(z.unknown()).optional(),+ created_at: z.string(),+ updated_at: z.string(),+}).loose();++export const ListIssuesResponseSchema = z.object({+ issues: z.array(IssueSchema).default([]),+ total: z.number().default(0),+}).loose();++export const EMPTY_LIST_ISSUES_RESPONSE: ListIssuesResponse = {+ issues: [],+ total: 0,+};++const SubscriberSchema = z.object({+ issue_id: z.string(),+ user_type: z.string(),+ user_id: z.string(),+ reason: z.string(),+ created_at: z.string(),+}).loose();++export const SubscribersListSchema = z.array(SubscriberSchema);++export const ChildIssuesResponseSchema = z.object({+ issues: z.array(IssueSchema).default([]),+}).loose();diff --git a/packages/core/package.json b/packages/core/package.jsonindex 004c9fac45..c23dd1c5b6 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -14,6 +14,7 @@"./types/*": "./types/*.ts","./api": "./api/index.ts","./api/client": "./api/client.ts",+ "./api/schema": "./api/schema.ts","./api/ws-client": "./api/ws-client.ts","./config": "./config/index.ts","./auth": "./auth/index.ts",@@ -92,6 +93,7 @@"i18next": "catalog:","posthog-js": "catalog:","react-i18next": "catalog:",+ "zod": "catalog:","zustand": "catalog:"},"peerDependencies": {diff --git a/packages/core/platform/core-provider.tsx b/packages/core/platform/core-provider.tsxindex a8b2b2990e..508964eeec 100644--- a/packages/core/platform/core-provider.tsx+++ b/packages/core/platform/core-provider.tsx@@ -2,7 +2,7 @@import { useMemo } from "react";import { ApiClient } from "../api/client";-import { setApiInstance } from "../api";+import { setApiInstance, setSchemaLogger } from "../api";import { createAuthStore, registerAuthStore } from "../auth";import { createChatStore, registerChatStore } from "../chat";import {@@ -41,6 +41,7 @@ function initCore(identity,});setApiInstance(api);+ setSchemaLogger(createLogger("api-schema"));// In token mode, hydrate token from storage.if (!cookieAuth) {diff --git a/packages/ui/components/common/error-boundary.tsx b/packages/ui/components/common/error-boundary.tsxnew file mode 100644index 0000000000..63f458a403--- /dev/null+++ b/packages/ui/components/common/error-boundary.tsx@@ -0,0 +1,99 @@+"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>+ );+}diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsxindex dad2b17de3..e627f49596 100644--- a/packages/views/inbox/components/inbox-page.tsx+++ b/packages/views/inbox/components/inbox-page.tsx@@ -22,6 +22,7 @@ import {} from "@multica/core/inbox/mutations";import { IssueDetail } from "../../issues/components";+import { ErrorBoundary } from "@multica/ui/components/common/error-boundary";import { useNavigation } from "../../navigation";import { toast } from "sonner";import {@@ -260,23 +261,25 @@ export function InboxPage() {// new inbox notification for the same issue, and the dedup helper picks the// newest one — keying on its id would remount IssueDetail on every event,// wiping the comment composer draft and resetting scroll position.- <IssueDetail- key={selected.issue_id}- issueId={selected.issue_id}- defaultSidebarOpen={false}- layoutId="multica_inbox_issue_detail_layout"- highlightCommentId={selected.details?.comment_id ?? undefined}- onDelete={() => {- // Issue deletion CASCADE-deletes the inbox item server-side, and the- // issue:deleted WS event prunes it from the inbox cache. Just clear- // the selection — calling archive here would 404 on a row that no- // longer exists.- setSelectedKey("");- }}- onDone={() => {- handleArchive(selected.id);- }}- />+ <ErrorBoundary resetKeys={[selected.issue_id]}>+ <IssueDetail+ key={selected.issue_id}+ issueId={selected.issue_id}+ defaultSidebarOpen={false}+ layoutId="multica_inbox_issue_detail_layout"+ highlightCommentId={selected.details?.comment_id ?? undefined}+ onDelete={() => {+ // Issue deletion CASCADE-deletes the inbox item server-side, and the+ // issue:deleted WS event prunes it from the inbox cache. Just clear+ // the selection — calling archive here would 404 on a row that no+ // longer exists.+ setSelectedKey("");+ }}+ onDone={() => {+ handleArchive(selected.id);+ }}+ />+ </ErrorBoundary>) : selected ? (<div className="p-6"><h2 className="text-lg font-semibold">{getInboxDisplayTitle(selected)}</h2>diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b8f4628ab2..6a87bf259c 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -90,6 +90,9 @@ catalogs:vitest:specifier: ^4.1.0version: 4.1.0+ zod:+ specifier: ^4.1.5+ version: 4.3.6zustand:specifier: ^5.0.0version: 5.0.12@@ -510,6 +513,9 @@ importers:react-i18next:specifier: 'catalog:'version: 17.0.6([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])+ zod:+ specifier: 'catalog:'+ version: 4.3.6zustand:specifier: 'catalog:'version: 5.0.12(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex ac64de304a..4fe10ef80b 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -18,6 +18,10 @@ catalog:"@tanstack/react-query": "^5.96.2""@tanstack/react-table": "^8.21.3"+ # Runtime schema validation (defensive boundary against API drift —+ # see CLAUDE.md "API Response Compatibility")+ zod: "^4.1.5"+# UI & Stylingtailwindcss: "^4""@tailwindcss/postcss": "^4"