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 { EnvironmentId, ThreadId } from "@t3tools/contracts";
8import * as Cause from "effect/Cause";
9import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
10import * as Haptics from "expo-haptics";
11import { Accelerometer } from "expo-sensors";
12import {
13 ActivityIndicator,
14 Alert,
15 AppState,
16 BackHandler,
17 Pressable,
18 StatusBar,
19 View,
20} from "react-native";
21import Animated, { FadeIn, FadeOut, ReduceMotion } from "react-native-reanimated";
22import { useSafeAreaInsets } from "react-native-safe-area-context";
23
24import { SymbolView } from "../../components/AppSymbol";
25import { AppText } from "../../components/AppText";
26import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
27import { GlassSurface } from "../../components/GlassSurface";
28import {
29 androidHeaderMenuActions,
30 findHeaderMenuAction,
31} from "../../components/headerMenu.android";
32import type { ScreenHeaderMenuItem } from "../../components/ScreenHeader.types";
33import { deviceEnvironment, refreshDeviceHubAccess, useDeviceHubAccess } from "../../state/device";
34import { useEnvironmentQuery } from "../../state/query";
35import { useAtomCommand } from "../../state/use-atom-command";
36import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
37import { DeviceStreamWebView, type DeviceStreamRef } from "./DeviceStreamWebView";
38import {
39 selectedThreadDevicePreview,
40 threadDevicePreviews,
41 type ThreadDevicePreview,
42} from "./threadDevicePreviews";
43import { createShakeDetector } from "./shakeDetector";
44
45const OVERLAY_ENTERING = FadeIn.duration(160).reduceMotion(ReduceMotion.System);
46const OVERLAY_EXITING = FadeOut.duration(120).reduceMotion(ReduceMotion.System);
47
48type DevicePreviewRouteScreenProps = StaticScreenProps<{
49 readonly environmentId: string;
50 readonly threadId: string;
51}>;
52
53/** Full-screen viewer; controls live in an overlay toggled by the handle or a shake. */
54export function DevicePreviewRouteScreen({ route }: DevicePreviewRouteScreenProps) {
55 const navigation = useNavigation();
56 const onClose = useCallback(() => navigation.goBack(), [navigation]);
57 const { environmentId, threadId } = route.params;
58 // A hand-typed deep link can carry a blank ID, which the branded IDs reject.
59 const isBlankLink = environmentId.trim().length === 0 || threadId.trim().length === 0;
60 useEffect(() => {
61 if (isBlankLink) onClose();
62 }, [isBlankLink, onClose]);
63 if (isBlankLink) return null;
64 return (
65 <DevicePreviewScreen
66 environmentId={EnvironmentId.make(environmentId)}
67 threadId={ThreadId.make(threadId)}
68 onClose={onClose}
69 />
70 );
71}
72
73function DevicePreviewScreen({
74 environmentId,
75 threadId,
76 onClose,
77}: {
78 readonly environmentId: EnvironmentId;
79 readonly threadId: ThreadId;
80 readonly onClose: () => void;
81}) {
82 const insets = useSafeAreaInsets();
83 const { themeVariables } = useAppearancePreferences();
84 const focused = useIsFocused();
85 const [foreground, setForeground] = useState(AppState.currentState !== "background");
86 const [selectedKey, setSelectedKey] = useState<string | null>(null);
87 const [inputConnected, setInputConnected] = useState(false);
88 const [streamAttempt, setStreamAttempt] = useState(0);
89 const [shuttingDown, setShuttingDown] = useState(false);
90 const [controlsVisible, setControlsVisible] = useState(true);
91 const retryHost = useAtomCommand(deviceEnvironment.list);
92 const shutdown = useAtomCommand(deviceEnvironment.shutdown, { reportFailure: false });
93 const streamRef = useRef<DeviceStreamRef>(null);
94 const state = useEnvironmentQuery(deviceEnvironment.state({ environmentId, input: {} }));
95 const previews = useMemo(
96 () => threadDevicePreviews(state.data, threadId),
97 [state.data, threadId],
98 );
99 const preview = selectedThreadDevicePreview(previews, selectedKey);
100 const onInputConnected = useCallback(async (connected: boolean) => {
101 setInputConnected(connected);
102 // Controls greet the user while connecting, then get out of the stream's way.
103 if (connected) setControlsVisible(false);
104 }, []);
105 useEffect(() => {
106 const subscription = AppState.addEventListener("change", (state) =>
107 setForeground(state !== "background"),
108 );
109 return () => subscription.remove();
110 }, []);
111 useEffect(() => {
112 if (focused && state.data !== null && previews.length === 0) onClose();
113 }, [focused, state.data, previews.length, onClose]);
114 useEffect(() => {
115 if (!focused || !foreground) return;
116 const shaken = createShakeDetector();
117 Accelerometer.setUpdateInterval(50);
118 const subscription = Accelerometer.addListener((sample) => {
119 if (!shaken({ ...sample, timestamp: sample.timestamp * 1000 })) return;
120 void Haptics.selectionAsync();
121 setControlsVisible((visible) => !visible);
122 });
123 return () => subscription.remove();
124 }, [focused, foreground]);
125 // Android back reveals the controls first, so leaving takes a deliberate second press.
126 useEffect(() => {
127 if (controlsVisible) return;
128 const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
129 setControlsVisible(true);
130 return true;
131 });
132 return () => subscription.remove();
133 }, [controlsVisible]);
134
135 const shutDownDevice = async () => {
136 if (!preview || shuttingDown) return;
137 setShuttingDown(true);
138 try {
139 const result = await shutdown({
140 environmentId,
141 input: {
142 hostId: preview.session.hostId,
143 deviceId: preview.session.deviceId,
144 platform: preview.session.platform,
145 },
146 });
147 if (result._tag === "Failure") {
148 Alert.alert("Could not shut down device", String(Cause.squash(result.cause)));
149 }
150 } finally {
151 setShuttingDown(false);
152 }
153 };
154
155 const controls: ScreenHeaderMenuItem[] = [
156 ...(state.data?.hosts
157 .filter(
158 (host) =>
159 state.data?.supportsHostRetry && state.data.hostStatuses[host.id]?.status === "failed",
160 )
161 .map((host) => ({
162 id: `retry-${host.id}`,
163 title: `Retry ${host.label}`,
164 icon: "arrow.clockwise" as const,
165 onPress: () => {
166 void retryHost({ environmentId, input: { retryHostId: host.id } });
167 },
168 })) ?? []),
169 ...(state.data?.supportsToolInspection
170 ? [
171 {
172 id: "check-device-tools",
173 title: "Check device tool versions",
174 icon: "arrow.clockwise" as const,
175 onPress: () => {
176 void retryHost({ environmentId, input: { inspectOnly: true } });
177 },
178 },
179 ]
180 : []),
181 {
182 id: "device-tools",
183 title: "Device tool versions",
184 icon: "info.circle",
185 onPress: () =>
186 Alert.alert(
187 "Device tool versions",
188 deviceToolUpdateOwnership +
189 "\n\n" +
190 deviceToolUpdatePolicy(
191 state.data?.hosts.find((host) => host.id === preview?.session.hostId)?.tools,
192 ) +
193 "\n\n" +
194 deviceToolVersionLabels(
195 state.data?.hosts.find((host) => host.id === preview?.session.hostId)?.tools,
196 ).join("\n") +
197 "\n" +
198 (state.data?.hosts.find((host) => host.id === preview?.session.hostId)
199 ?.toolInspectionError ??
200 state.data?.hostStatuses[preview?.session.hostId ?? ""]?.detail ??
201 ""),
202 ),
203 },
204 {
205 id: "reload",
206 title: "Reload stream",
207 icon: "arrow.clockwise" as const,
208 disabled: !preview || shuttingDown,
209 onPress: () => {
210 setInputConnected(false);
211 setStreamAttempt((attempt) => attempt + 1);
212 },
213 },
214 ...(preview?.session.platform === "android"
215 ? [
216 {
217 id: "back",
218 title: "Back",
219 icon: "arrow.left",
220 disabled: !inputConnected,
221 onPress: () => streamRef.current?.back(),
222 },
223 ]
224 : []),
225 {
226 id: "app-switcher",
227 title: "App switcher",
228 icon: "square.on.square",
229 disabled: !inputConnected,
230 onPress: () => streamRef.current?.appSwitcher(),
231 },
232 ...(preview?.session.platform === "ios"
233 ? [
234 {
235 id: "rotate",
236 title: "Rotate device",
237 icon: "arrow.clockwise" as const,
238 disabled: !inputConnected,
239 onPress: () => streamRef.current?.rotate(),
240 },
241 ]
242 : []),
243 {
244 id: "shutdown",
245 title: shuttingDown ? "Shutting down…" : "Shut down device",
246 icon: "power",
247 disabled: !preview || shuttingDown,
248 onPress: () => void shutDownDevice(),
249 },
250 ];
251 const pressHome = () => streamRef.current?.home();
252 const menuItems: ScreenHeaderMenuItem[] = [
253 ...(previews.length > 1
254 ? [
255 {
256 id: "devices",
257 title: "Devices",
258 inline: true,
259 items: previews.map((device) => ({
260 id: device.key,
261 title: device.name,
262 subtitle: device.description,
263 selected: device.key === preview?.key,
264 onPress: () => setSelectedKey(device.key),
265 })),
266 },
267 ]
268 : []),
269 ...controls,
270 ];
271 return (
272 <View className="flex-1" style={{ backgroundColor: themeVariables["--color-sheet-solid"] }}>
273 <StatusBar hidden animated />
274 {preview && focused && foreground ? (
275 <OpenDevicePreview
276 key={`${preview.key}:${streamAttempt}`}
277 environmentId={environmentId}
278 preview={preview}
279 streamRef={streamRef}
280 onInputConnected={onInputConnected}
281 />
282 ) : (
283 <View className="flex-1 items-center justify-center gap-4 px-6">
284 {state.error ? (
285 <>
286 <AppText selectable className="text-center text-sm text-foreground-muted">
287 {state.error}
288 </AppText>
289 <Pressable
290 accessibilityRole="button"
291 className="rounded-full border border-secondary-border bg-secondary px-6 py-3"
292 onPress={state.refresh}
293 >
294 <AppText className="text-secondary-foreground">Retry</AppText>
295 </Pressable>
296 </>
297 ) : focused && foreground ? (
298 <ActivityIndicator color={themeVariables["--color-icon"]} />
299 ) : null}
300 </View>
301 )}
302 {controlsVisible ? (
303 <Animated.View
304 entering={OVERLAY_ENTERING}
305 exiting={OVERLAY_EXITING}
306 pointerEvents="box-none"
307 className="absolute inset-0"
308 >
309 {inputConnected ? (
310 <Pressable
311 accessibilityLabel="Hide device controls"
312 className="absolute inset-0 bg-black/30"
313 onPress={() => setControlsVisible(false)}
314 />
315 ) : null}
316 <View className="px-3" style={{ paddingTop: Math.max(insets.top, 12) }}>
317 <GlassSurface className="flex-row items-center gap-1 p-1">
318 <ControlPill
319 accessibilityLabel="Close device preview"
320 icon="xmark"
321 onPress={onClose}
322 />
323 <AppText numberOfLines={1} className="flex-1 text-center font-t3-medium text-base">
324 {preview?.name ?? "Devices"}
325 </AppText>
326 <ControlPill
327 accessibilityLabel="Home"
328 icon="house"
329 disabled={!inputConnected}
330 onPress={pressHome}
331 />
332 <DeviceOptionsMenu items={menuItems} />
333 </GlassSurface>
334 </View>
335 </Animated.View>
336 ) : (
337 <Pressable
338 accessibilityRole="button"
339 accessibilityLabel="Show device controls"
340 accessibilityHint="Shaking the phone also shows them"
341 hitSlop={12}
342 className="absolute h-6 w-16 items-center justify-center self-center"
343 style={{ top: Math.max(insets.top - 18, 4) }}
344 onPress={() => setControlsVisible(true)}
345 >
346 <View className="h-1.5 w-10 rounded-full bg-white/40" />
347 </Pressable>
348 )}
349 </View>
350 );
351}
352
353function DeviceOptionsMenu({ items }: { readonly items: ReadonlyArray<ScreenHeaderMenuItem> }) {
354 return (
355 <ControlPillMenu
356 actions={androidHeaderMenuActions(items)}
357 isAnchoredToRight
358 title="Device options"
359 onPressAction={({ nativeEvent }) => {
360 const action = findHeaderMenuAction(items, nativeEvent.event);
361 if (action && !action.disabled) action.onPress();
362 }}
363 >
364 <Pressable
365 accessibilityLabel="Device options"
366 accessibilityRole="button"
367 className="size-11 items-center justify-center rounded-full bg-subtle"
368 >
369 <SymbolView name="ellipsis" size={18} tintColorClassName="accent-icon" />
370 </Pressable>
371 </ControlPillMenu>
372 );
373}
374
375function OpenDevicePreview({
376 environmentId,
377 preview,
378 streamRef,
379 onInputConnected,
380}: {
381 readonly environmentId: EnvironmentId;
382 readonly preview: ThreadDevicePreview;
383 readonly streamRef: RefObject<DeviceStreamRef | null>;
384 readonly onInputConnected: (connected: boolean) => Promise<void>;
385}) {
386 const { session } = preview;
387 const { themeVariables } = useAppearancePreferences();
388 const { access, error, refresh } = useDeviceHubAccess(environmentId, session.hostId);
389 const onUnauthorized = useCallback(
390 async () => refreshDeviceHubAccess(environmentId),
391 [environmentId],
392 );
393 useEffect(() => {
394 refreshDeviceHubAccess(environmentId);
395 return () => void onInputConnected(false);
396 }, [environmentId, onInputConnected]);
397 return access ? (
398 <DeviceStreamWebView
399 ref={streamRef}
400 access={access}
401 platform={session.platform}
402 deviceId={session.deviceId}
403 colors={{
404 background: themeVariables["--color-sheet-solid"],
405 foreground: themeVariables["--color-foreground"],
406 muted: themeVariables["--color-foreground-muted"],
407 buttonBackground: themeVariables["--color-secondary"],
408 buttonForeground: themeVariables["--color-secondary-foreground"],
409 buttonBorder: themeVariables["--color-secondary-border"],
410 }}
411 onUnauthorized={onUnauthorized}
412 onInputConnected={onInputConnected}
413 />
414 ) : (
415 <View className="flex-1 items-center justify-center gap-4 px-6">
416 {error ? (
417 <>
418 <AppText selectable className="text-center text-sm text-foreground-muted">
419 {error}
420 </AppText>
421 <Pressable
422 accessibilityRole="button"
423 className="rounded-full border border-secondary-border bg-secondary px-6 py-3"
424 onPress={refresh}
425 >
426 <AppText className="text-secondary-foreground">Retry</AppText>
427 </Pressable>
428 </>
429 ) : (
430 <>
431 <ActivityIndicator color={themeVariables["--color-icon"]} />
432 <AppText className="text-sm text-foreground-muted">Connecting to device...</AppText>
433 </>
434 )}
435 </View>
436 );
437}