Skip to content

Commit 23c7ab9

Browse files
fix(mobile): recover from screen render errors (pingdotgg#13197)
1 parent 10882be commit 23c7ab9

7 files changed

Lines changed: 281 additions & 55 deletions

File tree

‎apps/mobile/src/Stack.tsx‎

Lines changed: 41 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import {
1010
createNativeStackScreen,
1111
type NativeStackNavigationOptions,
1212
} from "@react-navigation/native-stack";
13-
import { useEffect, useRef } from "react";
13+
import { useEffect, useRef, type ReactNode } from "react";
1414
import {
1515
Platform,
1616
Pressable,
@@ -23,6 +23,11 @@ import { useResolveClassNames } from "uniwind";
2323

2424
import { AppText as Text } from "./components/AppText";
2525
import { getCompactBrandHeaderOptions } from "./components/CompactBrandTitle";
26+
import {
27+
RenderErrorBoundary,
28+
RenderFailureView,
29+
type RenderFailureProps,
30+
} from "./components/RenderErrorBoundary";
2631
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
2732
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
2833
import { ConnectOnboardingRouteScreen } from "./features/cloud/ConnectOnboardingRouteScreen";
@@ -777,10 +782,13 @@ const RootStackConfig = createNativeStackNavigator({
777782
// The whole new-task flow (choose project → draft → add project) shares
778783
// draft state via NewTaskFlowProvider. The expo-router era mounted it in
779784
// app/new/_layout.tsx; this layout wrapper is the native-stack equivalent.
780-
layout: ({ children }) => (
781-
<NewTaskFlowProvider>
782-
<View className="flex-1 bg-sheet-solid">{children}</View>
783-
</NewTaskFlowProvider>
785+
// A screen's layout replaces the navigator's screenLayout.
786+
layout: ({ children, route }) => (
787+
<GuardedScreenLayout route={route}>
788+
<NewTaskFlowProvider>
789+
<View className="flex-1 bg-sheet-solid">{children}</View>
790+
</NewTaskFlowProvider>
791+
</GuardedScreenLayout>
784792
),
785793
options: {
786794
gestureEnabled: true,
@@ -794,13 +802,41 @@ const RootStackConfig = createNativeStackNavigator({
794802
},
795803
});
796804

805+
function GuardedScreenLayout(props: {
806+
readonly children: ReactNode;
807+
readonly route: { readonly name: string; readonly params?: object | undefined };
808+
}) {
809+
return (
810+
<RenderErrorBoundary
811+
resetKeys={[props.route.params]}
812+
renderFallback={(fallback) => (
813+
<ScreenRenderFallback {...fallback} routeName={props.route.name} />
814+
)}
815+
>
816+
{props.children}
817+
</RenderErrorBoundary>
818+
);
819+
}
820+
821+
function ScreenRenderFallback(props: RenderFailureProps & { readonly routeName: string }) {
822+
const navigation = useNavigation();
823+
const exit = navigation.canGoBack()
824+
? { label: "Go back", onPress: () => navigation.goBack() }
825+
: props.routeName === "Home"
826+
? { label: "Open settings", onPress: () => navigation.navigate("SettingsSheet") }
827+
: { label: "Return home", onPress: () => navigation.dispatch(StackActions.replace("Home")) };
828+
829+
return <RenderFailureView {...props} exit={exit} />;
830+
}
831+
797832
export const RootStack = RootStackConfig.with(function AdaptiveRootStack({ Navigator }) {
798833
const { width, height } = useWindowDimensions();
799834
const usesWorkspaceFlowScreens =
800835
Platform.OS === "android" || deriveLayout({ width, height }).usesSplitView;
801836

802837
return (
803838
<Navigator
839+
screenLayout={GuardedScreenLayout}
804840
screenOptions={({ route }) => {
805841
if (route.name !== "SettingsSheet" && route.name !== "NewTaskSheet") {
806842
return {};
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
import { Component, type ReactNode } from "react";
2+
import { ScrollView, View } from "react-native";
3+
4+
import { AppText as Text } from "./AppText";
5+
import { MaterialButton } from "./MaterialButton";
6+
import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
7+
8+
interface RenderErrorBoundaryProps {
9+
readonly children: ReactNode;
10+
readonly resetKeys?: ReadonlyArray<unknown>;
11+
readonly renderFallback?: (props: RenderFailureProps) => ReactNode;
12+
}
13+
14+
interface RenderErrorBoundaryState {
15+
readonly failed: boolean;
16+
readonly error: unknown;
17+
readonly componentStack?: string;
18+
readonly resetKeys?: ReadonlyArray<unknown>;
19+
}
20+
21+
export interface RenderFailureProps {
22+
readonly details: string;
23+
readonly retry: () => void;
24+
}
25+
26+
function errorDetails(error: unknown, componentStack?: string): string {
27+
let description: string;
28+
try {
29+
description = error instanceof Error ? (error.stack ?? error.message) : String(error);
30+
} catch {
31+
description = "Unknown render error";
32+
}
33+
return componentStack ? `${description}\nComponent stack:\n${componentStack}` : description;
34+
}
35+
36+
/** A failed subtree remounts on retry or when its identifying inputs change. */
37+
export class RenderErrorBoundary extends Component<
38+
RenderErrorBoundaryProps,
39+
RenderErrorBoundaryState
40+
> {
41+
override state: RenderErrorBoundaryState = {
42+
failed: false,
43+
error: null,
44+
resetKeys: this.props.resetKeys,
45+
};
46+
47+
static getDerivedStateFromProps(
48+
{ resetKeys }: RenderErrorBoundaryProps,
49+
state: RenderErrorBoundaryState,
50+
): Partial<RenderErrorBoundaryState> | null {
51+
if (
52+
resetKeys?.length !== state.resetKeys?.length ||
53+
resetKeys?.some((key, index) => !Object.is(key, state.resetKeys?.[index]))
54+
) {
55+
return { failed: false, error: null, componentStack: undefined, resetKeys };
56+
}
57+
return null;
58+
}
59+
60+
static getDerivedStateFromError(error: unknown): Partial<RenderErrorBoundaryState> {
61+
return { failed: true, error };
62+
}
63+
64+
override componentDidCatch(_error: unknown, info: { componentStack?: string }) {
65+
this.setState({ componentStack: info.componentStack });
66+
}
67+
68+
private readonly retry = () => {
69+
this.setState({ failed: false, error: null, componentStack: undefined });
70+
};
71+
72+
override render() {
73+
if (!this.state.failed) return this.props.children;
74+
const fallback =
75+
this.props.renderFallback ??
76+
((props: RenderFailureProps) => <RenderFailureView {...props} />);
77+
return fallback({
78+
details: errorDetails(this.state.error, this.state.componentStack),
79+
retry: this.retry,
80+
});
81+
}
82+
}
83+
84+
export function RenderFailureView(
85+
props: RenderFailureProps & {
86+
readonly title?: string;
87+
readonly bottomInset?: number;
88+
readonly exit?: { readonly label: string; readonly onPress: () => void };
89+
},
90+
) {
91+
const title = props.title ?? "This screen couldn't be displayed";
92+
return (
93+
<ScrollView
94+
className="flex-1 bg-screen"
95+
contentContainerClassName="flex-grow items-center justify-center gap-5 px-6 py-8"
96+
contentContainerStyle={
97+
props.bottomInset ? { paddingBottom: 32 + props.bottomInset } : undefined
98+
}
99+
>
100+
<Text accessibilityRole="header" className="text-center text-xl font-t3-bold">
101+
{title}
102+
</Text>
103+
<Text className="text-center text-sm text-foreground-muted">
104+
Try again. If it keeps happening, copy the details for a bug report.
105+
</Text>
106+
<Text selectable className="text-center font-mono text-xs text-danger-foreground">
107+
{props.details.split("\n", 1)[0]?.slice(0, 300)}
108+
</Text>
109+
<View className="w-full max-w-xs gap-2">
110+
<MaterialButton label="Try again" onPress={props.retry} tone="primary" fullWidth />
111+
<MaterialButton
112+
label="Copy details"
113+
onPress={() => copyTextWithHaptic(props.details, { target: "error details" })}
114+
fullWidth
115+
/>
116+
{props.exit ? (
117+
<MaterialButton
118+
label={props.exit.label}
119+
onPress={props.exit.onPress}
120+
tone="text"
121+
fullWidth
122+
/>
123+
) : null}
124+
</View>
125+
</ScrollView>
126+
);
127+
}

‎apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx‎

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ import {
5757
import { AndroidHomeFabLayout } from "../home/AndroidHomeFab";
5858
import { HomeListOptionsProvider } from "../home/home-list-options";
5959
import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar";
60+
import { RenderErrorBoundary, RenderFailureView } from "../../components/RenderErrorBoundary";
6061
import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation";
6162
import { WorkspaceInspectorPane } from "./workspace-inspector-pane";
6263
import { WorkspaceContentWidthContext } from "./workspace-content-width";
@@ -580,21 +581,31 @@ function AdaptiveWorkspaceLayoutContent(
580581
style={sidebarAnimatedStyle}
581582
>
582583
<View className="flex-1" style={{ width: layout.listPaneWidth }}>
583-
<AndroidHomeFabLayout sidebar onStartNewTask={handleStartNewTask}>
584-
<ThreadNavigationSidebar
585-
width={layout.listPaneWidth}
586-
visible={panes.primarySidebarVisible}
587-
onRequestVisibility={revealPrimarySidebar}
588-
selectedThreadKey={selectedThreadKey}
589-
onOpenSettings={handleOpenSettings}
590-
onOpenEnvironmentSettings={handleOpenEnvironmentSettings}
591-
onNewThreadInProject={handleNewThreadInProject}
592-
onNewThreadOnBranch={handleNewThreadOnBranch}
593-
onSelectThread={handleSelectThread}
594-
onSearchQueryChange={setPrimarySidebarSearchQuery}
595-
searchQuery={primarySidebarSearchQuery}
596-
/>
597-
</AndroidHomeFabLayout>
584+
<RenderErrorBoundary
585+
renderFallback={(fallback) => (
586+
<RenderFailureView
587+
{...fallback}
588+
title="The sidebar couldn't be displayed"
589+
exit={{ label: "Open settings", onPress: handleOpenSettings }}
590+
/>
591+
)}
592+
>
593+
<AndroidHomeFabLayout sidebar onStartNewTask={handleStartNewTask}>
594+
<ThreadNavigationSidebar
595+
width={layout.listPaneWidth}
596+
visible={panes.primarySidebarVisible}
597+
onRequestVisibility={revealPrimarySidebar}
598+
selectedThreadKey={selectedThreadKey}
599+
onOpenSettings={handleOpenSettings}
600+
onOpenEnvironmentSettings={handleOpenEnvironmentSettings}
601+
onNewThreadInProject={handleNewThreadInProject}
602+
onNewThreadOnBranch={handleNewThreadOnBranch}
603+
onSelectThread={handleSelectThread}
604+
onSearchQueryChange={setPrimarySidebarSearchQuery}
605+
searchQuery={primarySidebarSearchQuery}
606+
/>
607+
</AndroidHomeFabLayout>
608+
</RenderErrorBoundary>
598609
</View>
599610
</Animated.View>
600611
) : null}
@@ -625,6 +636,7 @@ function AdaptiveWorkspaceLayoutContent(
625636
</View>
626637
</View>
627638
<WorkspaceInspectorPane
639+
pathname={props.pathname}
628640
renderedInspectorWidth={renderedInspectorWidth}
629641
active={workspaceInspector?.active ?? false}
630642
panes={panes}

‎apps/mobile/src/features/layout/workspace-inspector-pane.tsx‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import Animated, {
88
} from "react-native-reanimated";
99

1010
import { constrainAuxiliaryPaneWidth, type WorkspacePaneLayout } from "../../lib/layout";
11+
import { RenderErrorBoundary, RenderFailureView } from "../../components/RenderErrorBoundary";
1112
import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation";
1213
import { WorkspacePaneDivider } from "./workspace-pane-divider";
1314

@@ -23,6 +24,7 @@ import { WorkspacePaneDivider } from "./workspace-pane-divider";
2324
* module stays import-cycle-free with AdaptiveWorkspaceLayout.
2425
*/
2526
export function WorkspaceInspectorPane(props: {
27+
readonly pathname: string;
2628
readonly renderedInspectorWidth: SharedValue<number>;
2729
/**
2830
* When false the pane animates closed but keeps its content mounted for the
@@ -139,10 +141,23 @@ export function WorkspaceInspectorPane(props: {
139141
style={inspectorStyle}
140142
>
141143
<Animated.View className="flex-1" style={inspectorContentStyle}>
142-
{props.renderInspector?.()}
144+
<RenderErrorBoundary
145+
resetKeys={[props.pathname]}
146+
renderFallback={(fallback) => (
147+
<RenderFailureView {...fallback} title="The inspector couldn't be displayed" />
148+
)}
149+
>
150+
<InspectorRenderer render={props.renderInspector} />
151+
</RenderErrorBoundary>
143152
</Animated.View>
144153
</Animated.View>
145154
) : null}
146155
</>
147156
);
148157
}
158+
159+
// The render callback must run inside the boundary's child, not while its
160+
// parent constructs the boundary element.
161+
function InspectorRenderer(props: { readonly render?: () => ReactNode }) {
162+
return <>{props.render?.()}</>;
163+
}

0 commit comments

Comments
 (0)