Skip to content

Commit bf13cdf

Browse files
fix(mobile): recover from render errors in-place with scoped boundaries
A render error anywhere in the mobile app previously reached the global fatal handler, and expo-updates' ErrorRecovery killed the process. Wrap every root navigation route (navigator screenLayout) and the thread feed in their own error boundary: the failed subtree is replaced by a recovery view (retry, copy diagnostics, go back) while the native header, navigation, and the rest of the stack stay alive. Caught errors are recorded in a session-scoped render-error log (deduped by error identity so nested boundaries report once) and surfaced on the Settings > Diagnostics screen next to the existing expo-updates startup-crash log, which keeps covering only process fatals.
1 parent d7819c1 commit bf13cdf

6 files changed

Lines changed: 449 additions & 34 deletions

File tree

‎apps/mobile/src/Stack.tsx‎

Lines changed: 31 additions & 1 deletion
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,7 @@ import { useResolveClassNames } from "uniwind";
2323

2424
import { AppText as Text } from "./components/AppText";
2525
import { getCompactBrandHeaderOptions } from "./components/CompactBrandTitle";
26+
import { RenderErrorBoundary, RenderFailureView } from "./components/RenderErrorBoundary";
2627
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
2728
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
2829
import { ConnectOnboardingRouteScreen } from "./features/cloud/ConnectOnboardingRouteScreen";
@@ -777,13 +778,42 @@ const RootStackConfig = createNativeStackNavigator({
777778
},
778779
});
779780

781+
// NAVIGATION SEAM: every root route renders inside its own error boundary.
782+
// A crashing screen shows the recovery UI in place — the native header, back
783+
// gesture, and the rest of the stack stay alive, so recovery works without
784+
// killing the app. Each route renders this layout within its own screen slot
785+
// (keyed by the navigator), so a popped route tears its boundary down. Screens
786+
// nested inside a sheet/stack route share that route's boundary.
787+
function GuardedScreenLayout(props: {
788+
readonly children: ReactNode;
789+
readonly route: { readonly name: string };
790+
}) {
791+
return (
792+
<RenderErrorBoundary scope={`screen:${props.route.name}`} fallback={ScreenRenderFallback}>
793+
{props.children}
794+
</RenderErrorBoundary>
795+
);
796+
}
797+
798+
function ScreenRenderFallback(props: { readonly error: unknown; readonly retry: () => void }) {
799+
const navigation = useNavigation();
800+
return (
801+
<RenderFailureView
802+
error={props.error}
803+
retry={props.retry}
804+
onGoBack={navigation.canGoBack() ? () => navigation.goBack() : undefined}
805+
/>
806+
);
807+
}
808+
780809
export const RootStack = RootStackConfig.with(function AdaptiveRootStack({ Navigator }) {
781810
const { width, height } = useWindowDimensions();
782811
const usesWorkspaceFlowScreens =
783812
Platform.OS === "android" || deriveLayout({ width, height }).usesSplitView;
784813

785814
return (
786815
<Navigator
816+
screenLayout={GuardedScreenLayout}
787817
screenOptions={({ route }) => {
788818
if (route.name !== "SettingsSheet" && route.name !== "NewTaskSheet") {
789819
return {};
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
import { Component, type ComponentType, type ReactNode } from "react";
2+
import { View } from "react-native";
3+
4+
import { SymbolView } from "./AppSymbol";
5+
import { AppText as Text } from "./AppText";
6+
import { MaterialButton } from "./MaterialButton";
7+
import { tryCopyTextWithHaptic } from "../lib/copyTextWithHaptic";
8+
import { recordRenderError } from "../features/diagnostics/render-error-log";
9+
10+
interface RenderErrorBoundaryProps {
11+
readonly children: ReactNode;
12+
/** Where the error was caught, recorded into the diagnostics render-error log. */
13+
readonly scope: string;
14+
/** Changed inputs reset a failed subtree without remounting the boundary. */
15+
readonly resetKeys?: ReadonlyArray<unknown> | undefined;
16+
/** Subject noun for the default fallback's headline, e.g. "The conversation". */
17+
readonly subject?: string;
18+
/**
19+
* Recovery UI override, rendered as its own component so it can use hooks
20+
* (e.g. navigation) even though the boundary itself is a class.
21+
*/
22+
readonly fallback?: ComponentType<RenderFallbackProps> | undefined;
23+
}
24+
25+
export interface RenderFallbackProps {
26+
readonly error: unknown;
27+
readonly retry: () => void;
28+
}
29+
30+
interface RenderErrorBoundaryState {
31+
readonly failedWith: unknown | undefined;
32+
readonly resetKeys?: ReadonlyArray<unknown> | undefined;
33+
}
34+
35+
/**
36+
* Catches render errors in one subtree, records them for diagnostics, and
37+
* shows an in-session recovery UI instead of letting the app die. Retrying
38+
* unmounts the failed subtree and mounts a fresh one; changed `resetKeys`
39+
* (e.g. a thread switch) clear the failure on their own.
40+
*
41+
* A caught error never reaches the global fatal handler, so expo-updates'
42+
* ErrorRecovery startup log stays exclusively for process-ending fatals —
43+
* `recordRenderError` is the sole report path here, deduped by error identity
44+
* so an inner and outer boundary catching the same throw record it once.
45+
*/
46+
export class RenderErrorBoundary extends Component<
47+
RenderErrorBoundaryProps,
48+
RenderErrorBoundaryState
49+
> {
50+
override state = { failedWith: undefined, resetKeys: this.props.resetKeys };
51+
52+
// A changed thread/environment underneath a persistent boundary is new input:
53+
// retry without waiting for the user to press Try again.
54+
static getDerivedStateFromProps(
55+
{ resetKeys }: RenderErrorBoundaryProps,
56+
state: RenderErrorBoundaryState,
57+
) {
58+
if (
59+
resetKeys?.length !== state.resetKeys?.length ||
60+
resetKeys?.some((key, index) => !Object.is(key, state.resetKeys?.[index]))
61+
) {
62+
return { failedWith: undefined, resetKeys };
63+
}
64+
return null;
65+
}
66+
67+
static getDerivedStateFromError(error: unknown) {
68+
return { failedWith: error };
69+
}
70+
71+
override componentDidCatch(error: unknown, info: { componentStack?: string }) {
72+
recordRenderError(error, this.props.scope, { componentStack: info.componentStack });
73+
}
74+
75+
private readonly retry = () => {
76+
this.setState({ failedWith: undefined });
77+
};
78+
79+
override render() {
80+
const { failedWith } = this.state;
81+
if (failedWith !== undefined) {
82+
if (this.props.fallback) {
83+
const Fallback = this.props.fallback;
84+
return <Fallback error={failedWith} retry={this.retry} />;
85+
}
86+
return (
87+
<RenderFailureView subject={this.props.subject} error={failedWith} retry={this.retry} />
88+
);
89+
}
90+
return this.props.children;
91+
}
92+
}
93+
94+
/**
95+
* The recovery UI itself: retry, copy diagnostics, and (where navigation gives
96+
* a way out) go back. It renders without a connection — recovery must work the
97+
* same locally and over a tunnel, where the crash itself may have arrived with
98+
* remote data.
99+
*/
100+
export function RenderFailureView(props: {
101+
readonly subject?: string;
102+
readonly error: unknown;
103+
readonly retry: () => void;
104+
readonly onGoBack?: (() => void) | undefined;
105+
}) {
106+
const message =
107+
props.error instanceof Error ? props.error.message || props.error.name : String(props.error);
108+
const copy = async () => {
109+
const detail = props.error instanceof Error ? (props.error.stack ?? message) : message;
110+
await tryCopyTextWithHaptic(detail, { target: "render error details" });
111+
};
112+
return (
113+
<View className="flex-1 items-center justify-center gap-4 px-8 py-10">
114+
<SymbolView
115+
name="exclamationmark.triangle"
116+
size={30}
117+
tintColorClassName="accent-icon"
118+
type="monochrome"
119+
weight="regular"
120+
/>
121+
<View className="items-center gap-2">
122+
<Text className="text-center text-xl font-t3-bold text-foreground">
123+
{props.subject ?? "This screen"} couldn’t be displayed
124+
</Text>
125+
<Text className="text-center font-sans text-sm leading-relaxed text-foreground-muted">
126+
Try again to re-render it. If it keeps happening, copy the details — they help us fix it.
127+
</Text>
128+
<Text
129+
selectable
130+
className="text-center font-mono text-xs leading-snug text-danger-foreground"
131+
>
132+
{message.slice(0, 300)}
133+
</Text>
134+
</View>
135+
<View className="w-full max-w-xs items-stretch gap-2">
136+
<MaterialButton label="Try again" onPress={props.retry} tone="primary" fullWidth />
137+
<MaterialButton label="Copy details" onPress={() => void copy()} fullWidth />
138+
{props.onGoBack ? (
139+
<MaterialButton label="Go back" onPress={props.onGoBack} tone="text" fullWidth />
140+
) : null}
141+
</View>
142+
</View>
143+
);
144+
}

‎apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,11 @@ import {
1616
parseStartupCrashRecords,
1717
type StartupCrashRecord,
1818
} from "./crash-log-model";
19+
import {
20+
formatRenderErrorReport,
21+
getRenderErrorRecords,
22+
type RenderErrorRecord,
23+
} from "./render-error-log";
1924

2025
// expo-updates keeps its persistent log this long. Reading any further back
2126
// returns nothing, so this is the whole available window.
@@ -47,6 +52,10 @@ export function SettingsDiagnosticsRouteScreen() {
4752
Updates.isEnabled ? { status: "loading" } : { status: "unavailable" },
4853
);
4954
const [copied, setCopied] = useState(false);
55+
const [renderCopied, setRenderCopied] = useState(false);
56+
// Render errors live only for the session (in memory, no persistence), and
57+
// this screen mounts fresh each time it opens.
58+
const [renderRecords] = useState<ReadonlyArray<RenderErrorRecord>>(getRenderErrorRecords);
5059

5160
useEffect(() => {
5261
if (!Updates.isEnabled) return;
@@ -72,6 +81,12 @@ export function SettingsDiagnosticsRouteScreen() {
7281
});
7382
if (ok) setCopied(true);
7483
};
84+
const copyRenderReport = async () => {
85+
const ok = await tryCopyTextWithHaptic(formatRenderErrorReport(renderRecords, appIdentity()), {
86+
target: "render error report",
87+
});
88+
if (ok) setRenderCopied(true);
89+
};
7590

7691
return (
7792
<SettingsScreen title="Diagnostics">
@@ -107,6 +122,24 @@ export function SettingsDiagnosticsRouteScreen() {
107122
)}
108123
</SettingsSection>
109124

125+
<SettingsSection title="Recovered render errors">
126+
{renderRecords.length === 0 ? (
127+
<EmptyState
128+
icon="checkmark.circle"
129+
title="No recovered render errors"
130+
detail="Nothing was caught and recovered since this launch. Recovered errors are kept in memory only — check here before restarting the app."
131+
/>
132+
) : (
133+
renderRecords.map((record, index) => (
134+
<RenderErrorRow
135+
key={record.timestamp + record.scope}
136+
record={record}
137+
first={index === 0}
138+
/>
139+
))
140+
)}
141+
</SettingsSection>
142+
110143
<View className="gap-3">
111144
<SettingsSection title="Actions">
112145
<SettingsActionRow
@@ -115,6 +148,12 @@ export function SettingsDiagnosticsRouteScreen() {
115148
disabled={state.status !== "ready"}
116149
onPress={() => void copyReport()}
117150
/>
151+
<SettingsActionRow
152+
icon={renderCopied ? "checkmark" : "doc.on.doc"}
153+
label={renderCopied ? "Copied" : "Copy render error report"}
154+
disabled={renderRecords.length === 0}
155+
onPress={() => void copyRenderReport()}
156+
/>
118157
</SettingsSection>
119158
<Text className="px-2 text-sm leading-normal text-foreground-muted">
120159
Paste the report into a GitHub issue. It contains the app version, the JavaScript error
@@ -147,6 +186,20 @@ function EmptyState(props: {
147186
);
148187
}
149188

189+
function RenderErrorRow(props: { readonly record: RenderErrorRecord; readonly first: boolean }) {
190+
const { record } = props;
191+
return (
192+
<View className={props.first ? "gap-1.5 p-4" : "gap-1.5 border-t border-border-subtle p-4"}>
193+
<Text className="text-xs text-foreground-muted">
194+
{new Date(record.timestamp).toLocaleString()} · {record.scope}
195+
</Text>
196+
<Text selectable className="text-base leading-snug text-danger-foreground">
197+
{record.message}
198+
</Text>
199+
</View>
200+
);
201+
}
202+
150203
function CrashRow(props: { readonly record: StartupCrashRecord; readonly first: boolean }) {
151204
const { record } = props;
152205
return (
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import { beforeEach, describe, expect, it } from "vite-plus/test";
2+
3+
import {
4+
clearRenderErrorRecords,
5+
describeRenderError,
6+
formatRenderErrorReport,
7+
getRenderErrorRecords,
8+
recordRenderError,
9+
} from "./render-error-log";
10+
11+
beforeEach(() => {
12+
clearRenderErrorRecords();
13+
});
14+
15+
describe("recordRenderError", () => {
16+
it("records the message, stack, scope, and timestamp, newest first", () => {
17+
const first = new Error("first broke");
18+
const second = new Error("second broke");
19+
expect(recordRenderError(first, "thread-feed", { timestamp: 100 })).toBe(true);
20+
expect(recordRenderError(second, "screen:Thread", { timestamp: 200 })).toBe(true);
21+
22+
const records = getRenderErrorRecords();
23+
expect(records.map((record) => record.message)).toEqual(["second broke", "first broke"]);
24+
expect(records[0]?.scope).toBe("screen:Thread");
25+
expect(records[1]?.detail).toContain("first broke");
26+
expect(records[1]?.detail).toContain("Error: first broke");
27+
});
28+
29+
it("records one throw once when several boundaries on the path catch it", () => {
30+
const error = new Error("bubble through everything");
31+
expect(recordRenderError(error, "thread-feed")).toBe(true);
32+
// The same object keeps bubbling; the outer screen boundary must not add
33+
// a second report of the identical crash.
34+
expect(recordRenderError(error, "screen:Thread")).toBe(false);
35+
expect(getRenderErrorRecords()).toHaveLength(1);
36+
37+
// A fresh throw with the same message (e.g. after a failed retry) is a
38+
// distinct crash and is recorded.
39+
expect(recordRenderError(new Error("bubble through everything"), "thread-feed")).toBe(true);
40+
expect(getRenderErrorRecords()).toHaveLength(2);
41+
});
42+
43+
it("keeps the newest records when the log overflows", () => {
44+
for (let index = 0; index < 25; index += 1) {
45+
recordRenderError(new Error(`error ${index}`), "screen:Home", { timestamp: index });
46+
}
47+
const records = getRenderErrorRecords();
48+
expect(records).toHaveLength(20);
49+
expect(records[0]?.message).toBe("error 24");
50+
expect(records[19]?.message).toBe("error 5");
51+
});
52+
53+
it("appends the component stack when the runtime provides one", () => {
54+
recordRenderError(new Error("bad render"), "thread-feed", {
55+
componentStack: "\n in ThreadFeed\n in View",
56+
});
57+
expect(getRenderErrorRecords()[0]?.detail).toContain("Component stack:\n in ThreadFeed");
58+
});
59+
});
60+
61+
describe("describeRenderError", () => {
62+
it("falls back to the error name when the message is empty", () => {
63+
expect(describeRenderError(new TypeError(""))).toBe("TypeError");
64+
});
65+
66+
it("stringifies non-error throws", () => {
67+
expect(describeRenderError("boom")).toBe("boom");
68+
const thrown = { toString: () => "custom" };
69+
expect(describeRenderError(thrown)).toBe("custom");
70+
});
71+
});
72+
73+
describe("formatRenderErrorReport", () => {
74+
it("labels an empty session without pretending a crash happened", () => {
75+
const report = formatRenderErrorReport([], { version: "1.2.3", build: "45" });
76+
expect(report).toContain("T3 Code 1.2.3 (45)");
77+
expect(report).toContain("No recovered render errors this session.");
78+
});
79+
80+
it("renders one section per record with scope and detail", () => {
81+
recordRenderError(new Error("feed exploded"), "thread-feed", { timestamp: 1789277752000 });
82+
const report = formatRenderErrorReport(getRenderErrorRecords(), {
83+
version: "1.2.3",
84+
build: "45",
85+
});
86+
expect(report).toContain("recovered render errors");
87+
expect(report).toContain("2026-09-13T05:35:52.000Z [thread-feed]");
88+
expect(report).toContain("feed exploded");
89+
});
90+
});

0 commit comments

Comments
 (0)