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