diff --git a/packages/app/src/components/render-error-boundary.tsx b/packages/app/src/components/render-error-boundary.tsx new file mode 100644 index 0000000000..0d6bb13790 --- /dev/null +++ b/packages/app/src/components/render-error-boundary.tsx @@ -0,0 +1,52 @@ +import { Component, type ErrorInfo, type ReactNode } from "react"; + +interface RenderErrorBoundaryProps { + children: ReactNode; + /** A caught error is cleared when any of these values change, so new content renders. */ + resetKeys: readonly unknown[]; + /** The error state shown in place of the children. `retry` renders the children again. */ + renderError(error: string, retry: () => void): ReactNode; + onError(error: unknown, componentStack: string | null | undefined): void; +} + +interface RenderErrorBoundaryState { + error: string | null; +} + +/** + * Keeps a render error inside one surface. Without it the error reaches the root boundary, + * which replaces the whole app. + */ +export class RenderErrorBoundary extends Component< + RenderErrorBoundaryProps, + RenderErrorBoundaryState +> { + state: RenderErrorBoundaryState = { error: null }; + + static getDerivedStateFromError(error: unknown): RenderErrorBoundaryState { + return { error: error instanceof Error ? error.message : String(error) }; + } + + componentDidCatch(error: unknown, info: ErrorInfo): void { + this.props.onError(error, info.componentStack); + } + + componentDidUpdate(previous: RenderErrorBoundaryProps): void { + if (this.state.error !== null && resetKeysChanged(previous.resetKeys, this.props.resetKeys)) { + this.retry(); + } + } + + retry = (): void => { + this.setState({ error: null }); + }; + + render() { + if (this.state.error !== null) return this.props.renderError(this.state.error, this.retry); + return this.props.children; + } +} + +function resetKeysChanged(previous: readonly unknown[], next: readonly unknown[]): boolean { + return previous.length !== next.length || previous.some((key, index) => key !== next[index]); +} diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index afff2bca5f..3785be87b2 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -2183,6 +2183,9 @@ export const ar: TranslationResources = { archiveFinishedRetry: "إعادة المحاولة ({{failed}}/{{total}})", }, panels: { + renderError: { + title: "تعذّر عرض هذه اللوحة", + }, draft: { newAgent: "وكيل جديد", creatingAgent: "وكيل الخلق", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index 2f434d7ba5..7f937da068 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -2213,6 +2213,9 @@ export const en = { archiveFinishedRetry: "Retry ({{failed}}/{{total}})", }, panels: { + renderError: { + title: "Unable to show this panel", + }, draft: { newAgent: "New Agent", creatingAgent: "Creating agent", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index 15788d7c1f..659ddc777e 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -2239,6 +2239,9 @@ export const es: TranslationResources = { archiveFinishedRetry: "Reintentar ({{failed}}/{{total}})", }, panels: { + renderError: { + title: "No se puede mostrar este panel", + }, draft: { newAgent: "Nuevo agente", creatingAgent: "Agente creador", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index b6db0c3763..9c7aa2b96d 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -2236,6 +2236,9 @@ export const fr: TranslationResources = { archiveFinishedRetry: "Réessayer ({{failed}}/{{total}})", }, panels: { + renderError: { + title: "Impossible d'afficher ce panneau", + }, draft: { newAgent: "Nouvel agent", creatingAgent: "Création de l’agent", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index cfe1070012..13247503d2 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -2206,6 +2206,9 @@ export const ja: TranslationResources = { archiveFinishedRetry: "再試行 ({{failed}}/{{total}})", }, panels: { + renderError: { + title: "このパネルを表示できません", + }, draft: { newAgent: "新しいエージェント", creatingAgent: "エージェントを作成中", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index 0235a64f2f..aefd319f0c 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -2195,6 +2195,9 @@ export const ko: TranslationResources = { archiveFinishedRetry: "다시 시도 ({{failed}}/{{total}})", }, panels: { + renderError: { + title: "이 패널을 표시할 수 없습니다", + }, draft: { newAgent: "새 에이전트", creatingAgent: "에이전트 생성 중", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index 8f4787bae4..0e91fda9b2 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -2223,6 +2223,9 @@ export const ptBR: TranslationResources = { archiveFinishedRetry: "Tentar novamente ({{failed}}/{{total}})", }, panels: { + renderError: { + title: "Não foi possível exibir este painel", + }, draft: { newAgent: "Novo Agente", creatingAgent: "Criando agente", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index 447ebd9a44..1f53764a29 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -2223,6 +2223,9 @@ export const ru: TranslationResources = { archiveFinishedRetry: "Повторить ({{failed}}/{{total}})", }, panels: { + renderError: { + title: "Не удалось показать эту панель", + }, draft: { newAgent: "Новый агент", creatingAgent: "Создание агента", diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index 3e9d0478b7..7369d7d8df 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -2160,6 +2160,9 @@ export const zhCN: TranslationResources = { archiveFinishedRetry: "重试 ({{failed}}/{{total}})", }, panels: { + renderError: { + title: "无法显示此面板", + }, draft: { newAgent: "新建 Agent", creatingAgent: "正在创建 Agent", diff --git a/packages/app/src/plugins/surface-error-boundary.tsx b/packages/app/src/plugins/surface-error-boundary.tsx index 89c6f6b468..b4b073e34d 100644 --- a/packages/app/src/plugins/surface-error-boundary.tsx +++ b/packages/app/src/plugins/surface-error-boundary.tsx @@ -1,6 +1,7 @@ -import React, { Component, type ErrorInfo, type ReactNode } from "react"; +import type { ReactNode } from "react"; import { Text } from "react-native"; import { StyleSheet } from "react-native-unistyles"; +import { RenderErrorBoundary } from "@/components/render-error-boundary"; interface SurfaceErrorBoundaryProps { children: ReactNode; @@ -10,42 +11,30 @@ interface SurfaceErrorBoundaryProps { renderError?(error: string): ReactNode; } -interface SurfaceErrorBoundaryState { - error: string | null; +export function SurfaceErrorBoundary({ + children, + installation, + resetKey, + Surface, + renderError, +}: SurfaceErrorBoundaryProps) { + return ( + + {children} + + ); } -export class SurfaceErrorBoundary extends Component< - SurfaceErrorBoundaryProps, - SurfaceErrorBoundaryState -> { - state: SurfaceErrorBoundaryState = { error: null }; +function renderPluginFailed(error: string) { + return Plugin failed: {error}; +} - static getDerivedStateFromError(error: unknown): SurfaceErrorBoundaryState { - return { error: error instanceof Error ? error.message : String(error) }; - } - - componentDidCatch(error: Error, info: ErrorInfo): void { - console.warn("[Plugins] Surface render failed", error, info.componentStack); - } - - componentDidUpdate(previous: SurfaceErrorBoundaryProps): void { - if ( - this.state.error && - (previous.installation !== this.props.installation || - previous.resetKey !== this.props.resetKey || - previous.Surface !== this.props.Surface) - ) { - this.setState({ error: null }); - } - } - - render() { - if (this.state.error) { - if (this.props.renderError) return this.props.renderError(this.state.error); - return Plugin failed: {this.state.error}; - } - return this.props.children; - } +function warnSurfaceRenderFailed(error: unknown, componentStack: string | null | undefined): void { + console.warn("[Plugins] Surface render failed", error, componentStack); } const styles = StyleSheet.create((theme) => ({ diff --git a/packages/app/src/screens/workspace/workspace-panel-host.test.tsx b/packages/app/src/screens/workspace/workspace-panel-host.test.tsx new file mode 100644 index 0000000000..8ed8878de5 --- /dev/null +++ b/packages/app/src/screens/workspace/workspace-panel-host.test.tsx @@ -0,0 +1,131 @@ +/** + * @vitest-environment jsdom + */ +import { act } from "@testing-library/react"; +import React from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { Text, View } from "react-native"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { definePanel, registerPanel } from "@/panels/panel-registry"; +import { buildWorkspacePaneContentModel } from "@/screens/workspace/workspace-pane-content"; +import { WorkspacePanelHost } from "@/screens/workspace/workspace-panel-host"; +import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types"; + +let panelFails = true; + +function FailingPanel() { + if (panelFails) throw new Error("Changes exploded"); + return Changes recovered; +} + +function HealthyPanel() { + return Draft panel; +} + +// The workspace screen registers the real panels; these stand in for the two kinds the test opens. +registerPanel( + definePanel("agent", { + component: FailingPanel, + useDescriptor: () => { + throw new Error("The test panel has no descriptor"); + }, + }), +); +registerPanel( + definePanel("draft", { + component: HealthyPanel, + useDescriptor: () => { + throw new Error("The test panel has no descriptor"); + }, + }), +); + +const failingTab: WorkspaceTabDescriptor = { + key: "agent_agent-a", + tabId: "agent_agent-a", + kind: "agent", + target: { kind: "agent", agentId: "agent-a" }, +}; +const healthyTab: WorkspaceTabDescriptor = { + key: "draft_draft-a", + tabId: "draft_draft-a", + kind: "draft", + target: { kind: "draft", draftId: "draft-a" }, +}; + +function buildContent({ tab }: { paneId: string; tab: WorkspaceTabDescriptor }) { + return buildWorkspacePaneContentModel({ + tab, + normalizedServerId: "server-a", + normalizedWorkspaceId: "workspace-a", + host: "main", + onOpenTab: vi.fn(), + onOpenPreferredTarget: vi.fn(), + onOpenTargetToSide: vi.fn(), + onCloseCurrentTab: vi.fn(), + onRetargetCurrentTab: vi.fn(), + onSetCurrentTabState: vi.fn(), + onOpenWorkspaceFile: vi.fn(), + onOpenImportSheet: vi.fn(), + }); +} + +function Workspace({ activeTabId }: { activeTabId: string }) { + return ( + + Sidebar + + + ); +} + +function byTestId(container: HTMLElement, testID: string): HTMLElement | null { + return container.querySelector(`[data-testid="${testID}"]`); +} + +describe("WorkspacePanelHost", () => { + let root: Root | null = null; + let container: HTMLElement | null = null; + + afterEach(() => { + if (root) act(() => root?.unmount()); + root = null; + container?.remove(); + container = null; + panelFails = true; + vi.restoreAllMocks(); + }); + + it("keeps a panel's render error inside that panel and retries it", () => { + vi.spyOn(console, "error").mockImplementation(() => undefined); + vi.spyOn(console, "warn").mockImplementation(() => undefined); + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + + act(() => root?.render()); + expect(container.textContent).toContain("Sidebar"); + expect(byTestId(container, "panel-render-error")?.textContent).toContain("Changes exploded"); + + act(() => root?.render()); + expect(container.textContent).toContain("Draft panel"); + + panelFails = false; + act(() => root?.render()); + const retry = byTestId(container, "panel-render-error-retry"); + expect(retry).not.toBeNull(); + act(() => retry?.click()); + expect(byTestId(container, "panel-render-error")).toBeNull(); + expect(container.textContent).toContain("Changes recovered"); + expect(container.textContent).toContain("Sidebar"); + }); +}); diff --git a/packages/app/src/screens/workspace/workspace-panel-host.tsx b/packages/app/src/screens/workspace/workspace-panel-host.tsx index 9851fe610c..678ff1eec0 100644 --- a/packages/app/src/screens/workspace/workspace-panel-host.tsx +++ b/packages/app/src/screens/workspace/workspace-panel-host.tsx @@ -1,5 +1,11 @@ import { memo, useCallback, useEffect, useMemo, useRef } from "react"; +import { useTranslation } from "react-i18next"; +import { View } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import { RenderErrorBoundary } from "@/components/render-error-boundary"; import { RetainedPanel } from "@/components/retained-panel"; +import { Alert } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; import { useModifiedPanelTabIds } from "@/panels/panel-instance-attributes"; import { WorkspacePaneContent, @@ -52,17 +58,44 @@ const MountedTab = memo(function MountedTab({ return ( - + + + ); }); +function logPanelRenderError(error: unknown, componentStack: string | null | undefined): void { + console.error("[WorkspacePanel] Render failed", error, componentStack); +} + +function renderPanelError(error: string, retry: () => void) { + return ; +} + +function PanelRenderError({ error, onRetry }: { error: string; onRetry: () => void }) { + const { t } = useTranslation(); + return ( + + + + + + ); +} + function useStableTabs(tabs: WorkspaceTabDescriptor[]) { const cacheRef = useRef(new Map()); const stableTabs = useMemo(() => { @@ -136,3 +169,9 @@ export function WorkspacePanelHost({ ); }); } + +const styles = StyleSheet.create((theme) => ({ + renderError: { + padding: theme.spacing[4], + }, +}));