Open History to see the last commit
1import {
2 deviceToolVersionLabels,
3 deviceToolUpdateOwnership,
4 deviceToolUpdatePolicy,
5} from "@t3tools/client-runtime/state/device";
6import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
7import { createNativeStackNavigator } from "@react-navigation/native-stack";
8import { EnvironmentId, ThreadId } from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
11import { ActivityIndicator, Alert, AppState, Platform, Pressable, View } from "react-native";
12import { useSafeAreaInsets } from "react-native-safe-area-context";
13
14import { AppText } from "../../components/AppText";
15import { ScreenHeader, type ScreenHeaderMenuItem } from "../../components/ScreenHeader";
16import { NativeHeaderToolbar } from "../../native/StackHeader";
17import { deviceEnvironment, refreshDeviceHubAccess, useDeviceHubAccess } from "../../state/device";
18import { useEnvironmentQuery } from "../../state/query";
19import { useAtomCommand } from "../../state/use-atom-command";
20import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
21import { DeviceStreamWebView, type DeviceStreamRef } from "./DeviceStreamWebView";
22import {
23 selectedThreadDevicePreview,
24 threadDevicePreviews,
25 type ThreadDevicePreview,
26} from "./threadDevicePreviews";
27
28const DevicePreviewStack = createNativeStackNavigator<{ DevicePreview: undefined }>();
29
30type DevicePreviewRouteScreenProps = StaticScreenProps<{
31 readonly environmentId: string;
32 readonly threadId: string;
33}>;
34
35/** The nested native stack supplies the navigation bar inside the modal. */
36export function DevicePreviewRouteScreen({ route }: DevicePreviewRouteScreenProps) {
37 const navigation = useNavigation();
38 const onClose = useCallback(() => navigation.goBack(), [navigation]);
39 return (
40 <View collapsable={false} className="flex-1 bg-sheet">
41 <DevicePreviewStack.Navigator
42 screenOptions={{
43 headerShown: Platform.OS === "ios",
44 headerBackVisible: false,
45 headerShadowVisible: false,
46 headerTransparent: false,
47 headerTitleStyle: { fontSize: 17, fontWeight: "600" },
48 }}
49 >
50 <DevicePreviewStack.Screen name="DevicePreview">
51 {() => (
52 <DevicePreviewScreen
53 environmentId={EnvironmentId.make(route.params.environmentId)}
54 threadId={ThreadId.make(route.params.threadId)}
55 onClose={onClose}
56 />
57 )}
58 </DevicePreviewStack.Screen>
59 </DevicePreviewStack.Navigator>
60 </View>
61 );
62}
63
64function DevicePreviewScreen({
65 environmentId,
66 threadId,
67 onClose,
68}: {
69 readonly environmentId: EnvironmentId;
70 readonly threadId: ThreadId;
71 readonly onClose: () => void;
72}) {
73 const insets = useSafeAreaInsets();
74 const { themeVariables } = useAppearancePreferences();
75 const focused = useIsFocused();
76 const [foreground, setForeground] = useState(AppState.currentState !== "background");
77 const [selectedKey, setSelectedKey] = useState<string | null>(null);
78 const [inputConnected, setInputConnected] = useState(false);
79 const [streamAttempt, setStreamAttempt] = useState(0);
80 const [shuttingDown, setShuttingDown] = useState(false);
81 const retryHost = useAtomCommand(deviceEnvironment.list);
82 const shutdown = useAtomCommand(deviceEnvironment.shutdown, { reportFailure: false });
83 const streamRef = useRef<DeviceStreamRef>(null);
84 const state = useEnvironmentQuery(deviceEnvironment.state({ environmentId, input: {} }));
85 const previews = useMemo(
86 () => threadDevicePreviews(state.data, threadId),
87 [state.data, threadId],
88 );
89 const preview = selectedThreadDevicePreview(previews, selectedKey);
90 const onInputConnected = useCallback(
91 async (connected: boolean) => setInputConnected(connected),
92 [],
93 );
94 useEffect(() => {
95 const subscription = AppState.addEventListener("change", (state) =>
96 setForeground(state !== "background"),
97 );
98 return () => subscription.remove();
99 }, []);
100 useEffect(() => {
101 if (focused && state.data !== null && previews.length === 0) onClose();
102 }, [focused, state.data, previews.length, onClose]);
103
104 const shutDownDevice = async () => {
105 if (!preview || shuttingDown) return;
106 setShuttingDown(true);
107 try {
108 const result = await shutdown({
109 environmentId,
110 input: {
111 hostId: preview.session.hostId,
112 deviceId: preview.session.deviceId,
113 platform: preview.session.platform,
114 },
115 });
116 if (result._tag === "Failure") {
117 Alert.alert("Could not shut down device", String(Cause.squash(result.cause)));
118 }
119 } finally {
120 setShuttingDown(false);
121 }
122 };
123
124 const controls: ScreenHeaderMenuItem[] = [
125 ...(state.data?.hosts
126 .filter(
127 (host) =>
128 state.data?.supportsHostRetry && state.data.hostStatuses[host.id]?.status === "failed",
129 )
130 .map((host) => ({
131 id: `retry-${host.id}`,
132 title: `Retry ${host.label}`,
133 icon: "arrow.clockwise" as const,
134 onPress: () => {
135 void retryHost({ environmentId, input: { retryHostId: host.id } });
136 },
137 })) ?? []),
138 ...(state.data?.supportsToolInspection
139 ? [
140 {
141 id: "check-device-tools",
142 title: "Check device tool versions",
143 icon: "arrow.clockwise" as const,
144 onPress: () => {
145 void retryHost({ environmentId, input: { inspectOnly: true } });
146 },
147 },
148 ]
149 : []),
150 {
151 id: "device-tools",
152 title: "Device tool versions",
153 icon: "info.circle",
154 onPress: () =>
155 Alert.alert(
156 "Device tool versions",
157 deviceToolUpdateOwnership +
158 "\n\n" +
159 deviceToolUpdatePolicy(
160 state.data?.hosts.find((host) => host.id === preview?.session.hostId)?.tools,
161 ) +
162 "\n\n" +
163 deviceToolVersionLabels(
164 state.data?.hosts.find((host) => host.id === preview?.session.hostId)?.tools,
165 ).join("\n") +
166 "\n" +
167 (state.data?.hosts.find((host) => host.id === preview?.session.hostId)
168 ?.toolInspectionError ??
169 state.data?.hostStatuses[preview?.session.hostId ?? ""]?.detail ??
170 ""),
171 ),
172 },
173 {
174 id: "reload",
175 title: "Reload stream",
176 icon: "arrow.clockwise" as const,
177 disabled: !preview || shuttingDown,
178 onPress: () => {
179 setInputConnected(false);
180 setStreamAttempt((attempt) => attempt + 1);
181 },
182 },
183 ...(preview?.session.platform === "android"
184 ? [
185 {
186 id: "back",
187 title: "Back",
188 icon: "arrow.left",
189 disabled: !inputConnected,
190 onPress: () => streamRef.current?.back(),
191 },
192 ]
193 : []),
194 {
195 id: "app-switcher",
196 title: "App switcher",
197 icon: "square.on.square",
198 disabled: !inputConnected,
199 onPress: () => streamRef.current?.appSwitcher(),
200 },
201 ...(preview?.session.platform === "ios"
202 ? [
203 {
204 id: "rotate",
205 title: "Rotate device",
206 icon: "arrow.clockwise" as const,
207 disabled: !inputConnected,
208 onPress: () => streamRef.current?.rotate(),
209 },
210 ]
211 : []),
212 {
213 id: "shutdown",
214 title: shuttingDown ? "Shutting down…" : "Shut down device",
215 icon: "power",
216 disabled: !preview || shuttingDown,
217 onPress: () => void shutDownDevice(),
218 },
219 ];
220 return (
221 <View className="flex-1 bg-sheet" style={{ paddingBottom: insets.bottom }}>
222 <ScreenHeader
223 title={preview?.name ?? "Devices"}
224 sidebar={false}
225 onBack={onClose}
226 options={{ headerBackVisible: false }}
227 actions={[
228 {
229 accessibilityLabel: "Home",
230 icon: "house",
231 disabled: !inputConnected,
232 onPress: () => streamRef.current?.home(),
233 },
234 ]}
235 menus={[
236 {
237 title: "Device options",
238 icon: "ellipsis",
239 items: [
240 ...(previews.length > 1
241 ? [
242 {
243 id: "devices",
244 title: "Devices",
245 inline: true,
246 items: previews.map((device) => ({
247 id: device.key,
248 title: device.name,
249 subtitle: device.description,
250 selected: device.key === preview?.key,
251 onPress: () => setSelectedKey(device.key),
252 })),
253 },
254 ]
255 : []),
256 ...controls,
257 ],
258 },
259 ]}
260 />
261 {Platform.OS === "ios" ? (
262 <NativeHeaderToolbar placement="left">
263 <NativeHeaderToolbar.Button
264 icon="xmark"
265 accessibilityLabel="Close device preview"
266 onPress={onClose}
267 separateBackground
268 />
269 </NativeHeaderToolbar>
270 ) : null}
271 {preview && focused && foreground ? (
272 <OpenDevicePreview
273 key={`${preview.key}:${streamAttempt}`}
274 environmentId={environmentId}
275 preview={preview}
276 streamRef={streamRef}
277 onInputConnected={onInputConnected}
278 />
279 ) : (
280 <View className="flex-1 items-center justify-center gap-4 px-6">
281 {state.error ? (
282 <>
283 <AppText selectable className="text-center text-sm text-foreground-muted">
284 {state.error}
285 </AppText>
286 <Pressable
287 accessibilityRole="button"
288 className="rounded-full border border-secondary-border bg-secondary px-6 py-3"
289 onPress={state.refresh}
290 >
291 <AppText className="text-secondary-foreground">Retry</AppText>
292 </Pressable>
293 </>
294 ) : focused && foreground ? (
295 <ActivityIndicator color={themeVariables["--color-icon"]} />
296 ) : null}
297 </View>
298 )}
299 </View>
300 );
301}
302
303function OpenDevicePreview({
304 environmentId,
305 preview,
306 streamRef,
307 onInputConnected,
308}: {
309 readonly environmentId: EnvironmentId;
310 readonly preview: ThreadDevicePreview;
311 readonly streamRef: RefObject<DeviceStreamRef | null>;
312 readonly onInputConnected: (connected: boolean) => Promise<void>;
313}) {
314 const { session } = preview;
315 const { themeVariables } = useAppearancePreferences();
316 const { access, error, refresh } = useDeviceHubAccess(environmentId, session.hostId);
317 const onUnauthorized = useCallback(
318 async () => refreshDeviceHubAccess(environmentId),
319 [environmentId],
320 );
321 useEffect(() => {
322 refreshDeviceHubAccess(environmentId);
323 return () => void onInputConnected(false);
324 }, [environmentId, onInputConnected]);
325 return access ? (
326 <DeviceStreamWebView
327 ref={streamRef}
328 access={access}
329 platform={session.platform}
330 deviceId={session.deviceId}
331 colors={{
332 background: themeVariables["--color-sheet-solid"],
333 foreground: themeVariables["--color-foreground"],
334 muted: themeVariables["--color-foreground-muted"],
335 buttonBackground: themeVariables["--color-secondary"],
336 buttonForeground: themeVariables["--color-secondary-foreground"],
337 buttonBorder: themeVariables["--color-secondary-border"],
338 }}
339 onUnauthorized={onUnauthorized}
340 onInputConnected={onInputConnected}
341 />
342 ) : (
343 <View className="flex-1 items-center justify-center gap-4 px-6">
344 {error ? (
345 <>
346 <AppText selectable className="text-center text-sm text-foreground-muted">
347 {error}
348 </AppText>
349 <Pressable
350 accessibilityRole="button"
351 className="rounded-full border border-secondary-border bg-secondary px-6 py-3"
352 onPress={refresh}
353 >
354 <AppText className="text-secondary-foreground">Retry</AppText>
355 </Pressable>
356 </>
357 ) : (
358 <>
359 <ActivityIndicator color={themeVariables["--color-icon"]} />
360 <AppText className="text-sm text-foreground-muted">Connecting to device...</AppText>
361 </>
362 )}
363 </View>
364 );
365}