Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SettingsDiagnosticsRouteScreen.tsx

225 lines8.5 KB

1import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
2import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
3import * as Application from "expo-application";
4import Constants from "expo-constants";
5import * as Updates from "expo-updates";
6import { useAtomSet, useAtomValue } from "@effect/atom-react";
7import * as Effect from "effect/Effect";
8import * as Exit from "effect/Exit";
9import { AsyncResult, Atom } from "effect/reactivity";
10import { useState } from "react";
11import { View } from "react-native";
12import { useSafeAreaInsets } from "react-native-safe-area-context";
13​
14import { SymbolView } from "../../components/ui/AppSymbol";
15import { AppText as Text } from "../../components/ui/AppText";
16import { tryCopyTextWithHaptic } from "../../lib/copyTextWithHaptic";
17import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
18import { crashReportingAvailable, setCrashReportsEnabled } from "../observability/observe";
19import { SettingsActionRow } from "../settings/components/SettingsActionRow";
20import { SettingsScreen } from "../settings/components/SettingsScreen";
21import { SettingsSection } from "../settings/components/SettingsSection";
22import { SettingsSwitchRow } from "../settings/components/SettingsSwitchRow";
23import {
24 formatStartupCrashReport,
25 parseStartupCrashRecords,
26 type StartupCrashRecord,
27} from "./crash-log-model";
28​
29// expo-updates retains only seven days of logs.
30const LOG_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
31​
32type CrashLogState =
33 | { readonly status: "loading" }
34 | { readonly status: "unavailable" }
35 | { readonly status: "ready"; readonly records: ReadonlyArray<StartupCrashRecord> };
36​
37// Not kept alive: each visit to the screen re-reads the log.
38const crashLogAtom = Atom.make(
39 Effect.tryPromise(() => Updates.readLogEntriesAsync(LOG_WINDOW_MS)).pipe(
40 Effect.map((entries): CrashLogState => ({
41 status: "ready",
42 records: parseStartupCrashRecords(entries),
43 })),
44 Effect.catch((error) =>
45 Effect.sync((): CrashLogState => {
46 console.warn("[diagnostics] could not read the expo-updates log", error);
47 return { status: "unavailable" };
48 }),
49 ),
50 ),
51).pipe(Atom.withLabel("mobile:diagnostics-crash-log"));
52​
53const UNAVAILABLE_CRASH_LOG_ATOM = Atom.make(
54 AsyncResult.success<CrashLogState>({ status: "unavailable" }),
55);
56​
57function useCrashLogState(): CrashLogState {
58 const result = useAtomValue(Updates.isEnabled ? crashLogAtom : UNAVAILABLE_CRASH_LOG_ATOM);
59 return AsyncResult.isSuccess(result) ? result.value : { status: "loading" };
61​
62function appIdentity() {
63 return {
64 version: Constants.expoConfig?.version ?? "0.0.0",
65 // EAS assigns build numbers remotely, so expo-constants never sees them;
66 // only the installed binary knows its own.
67 build: Application.nativeBuildVersion ?? "dev",
68 };
70​
71export function SettingsDiagnosticsRouteScreen() {
72 const insets = useSafeAreaInsets();
73 const state = useCrashLogState();
74 const [copied, setCopied] = useState(false);
75​
76 const records = state.status === "ready" ? state.records : [];
77 const copyReport = async () => {
78 const ok = await tryCopyTextWithHaptic(formatStartupCrashReport(records, appIdentity()), {
79 target: "crash report",
80 });
81 if (ok) setCopied(true);
82 };
83​
84 return (
85 <SettingsScreen title="Diagnostics">
86 <ScrollView
87 contentInsetAdjustmentBehavior="automatic"
88 contentInset={{ bottom: Math.max(insets.bottom, 18) }}
89 showsVerticalScrollIndicator={false}
90 className="flex-1"
91 contentContainerClassName="gap-6 px-5 pt-4 pb-[18px]"
92 >
93 {crashReportingAvailable ? <CrashReportsSetting /> : null}
94​
95 <SettingsSection title="Startup crashes">
96 {state.status === "loading" ? (
97 <View className="items-center gap-3 px-6 py-8">
98 <AppActivityIndicator />
99 <Text className="text-center text-sm text-foreground-muted">Reading crash log…</Text>
100 </View>
101 ) : state.status === "unavailable" ? (
102 <EmptyState
103 icon="exclamationmark.triangle"
104 title="Crash log unavailable"
105 detail="Startup crash records are only kept in store and TestFlight builds."
106 />
107 ) : records.length === 0 ? (
108 <EmptyState
109 icon="checkmark.circle"
110 title="No startup crashes"
111 detail="Nothing has taken the app down during launch in the last 7 days."
112 />
113 ) : (
114 records.map((record, index) => (
115 <CrashRow key={record.timestamp} record={record} first={index === 0} />
116 ))
117 )}
118 </SettingsSection>
119​
120 <View className="gap-3">
121 <SettingsSection title="Actions">
122 <SettingsActionRow
123 icon={copied ? "checkmark" : "doc.on.doc"}
124 label={copied ? "Copied" : "Copy crash report"}
125 disabled={state.status !== "ready"}
126 onPress={() => void copyReport()}
127 />
128 </SettingsSection>
129 <Text className="px-2 text-sm leading-normal text-foreground-muted">
130 Paste the report into a GitHub issue. It contains the app version, the JavaScript error
131 message, and the component stack. Error messages can quote values from the app, so read
132 it over before sharing.
133 </Text>
134 </View>
135 </ScrollView>
136 </SettingsScreen>
137 );
139​
140function CrashReportsSetting() {
141 const preferences = useAtomValue(mobilePreferencesAtom);
142 const savePreferences = useAtomSet(updateMobilePreferencesAtom, { mode: "promiseExit" });
143 // One change at a time, so a slow save never turns sending back on after a later opt-out.
144 const [saving, setSaving] = useState(false);
145 const ready = AsyncResult.isSuccess(preferences) && !preferences.waiting;
146 const enabled = AsyncResult.isSuccess(preferences)
147 ? preferences.value.crashReportsEnabled !== false
148 : true;
149​
150 const change = (value: boolean) => {
151 setSaving(true);
152 // Sending stops before the save and starts only after it.
153 if (!value) void setCrashReportsEnabled(false);
154 savePreferences({ crashReportsEnabled: value })
155 .then((exit) => {
156 if (Exit.isFailure(exit)) {
157 console.warn("[diagnostics] could not save the crash report setting", exit.cause);
158 return value ? undefined : setCrashReportsEnabled(true);
159 }
160 return value ? setCrashReportsEnabled(true) : undefined;
161 })
162 .catch((error: unknown) => {
163 console.warn("[diagnostics] could not apply the crash report setting", error);
164 })
165 .finally(() => setSaving(false));
166 };
167​
168 return (
169 <View className="gap-3">
170 <SettingsSection title="Crash reports">
171 <SettingsSwitchRow
172 icon="tray.and.arrow.up"
173 label="Send crash reports"
174 disabled={!ready || saving}
175 value={enabled}
176 onValueChange={change}
177 />
178 </SettingsSection>
179 <Text className="px-2 text-sm leading-normal text-foreground-muted">
180 When the app crashes or hits an error, it sends the error message, the stack trace, the app
181 version, and the device model and OS version to the T3 Code team. Each launch also sends
182 startup timings. Reports carry a random ID for this install.
183 </Text>
184 </View>
185 );
187​
188function EmptyState(props: {
189 readonly icon: "exclamationmark.triangle" | "checkmark.circle";
190 readonly title: string;
191 readonly detail: string;
192}) {
193 return (
194 <View className="items-center gap-2 px-6 py-8">
195 <SymbolView
196 name={props.icon}
197 size={28}
198 tintColorClassName="accent-icon"
199 type="monochrome"
200 weight="regular"
201 />
202 <Text className="text-center text-base text-foreground">{props.title}</Text>
203 <Text className="text-center text-sm text-foreground-muted">{props.detail}</Text>
204 </View>
205 );
207​
208function CrashRow(props: { readonly record: StartupCrashRecord; readonly first: boolean }) {
209 const { record } = props;
210 return (
211 <View className={props.first ? "gap-1.5 p-4" : "gap-1.5 border-t border-border-subtle p-4"}>
212 <Text className="text-xs text-foreground-muted">
213 {new Date(record.timestamp).toLocaleString()}
214 </Text>
215 <Text selectable className="text-base leading-snug text-danger-foreground">
216 {record.description}
217 </Text>
218 {record.frames.length > 0 ? (
219 <Text selectable className="font-mono text-xs leading-snug text-foreground-muted">
220 {record.frames.slice(0, 4).join("\n")}
221 </Text>
222 ) : null}
223 </View>
224 );