@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 452 lines 16.5 KB
Raw
1 import { SheetCloseButton } from "../../components/ui/SheetHeader";
2 import { Button } from "../../components/ui/Button";
3 import * as Dialog from "../../components/ui/Dialog";
4 import {
5 deviceToolVersionLabels,
6 deviceToolUpdateOwnership,
7 deviceToolUpdatePolicy,
8 } from "@t3tools/client-runtime/state/device";
9 import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
10 import { EnvironmentId, ThreadId } from "@t3tools/contracts";
11 import * as Cause from "effect/Cause";
12 import { msg, T, useGT } from "gt-react-native";
13 import { useEffect, useRef, useState, type RefObject } from "react";
14 import * as Haptics from "expo-haptics";
15 import { Accelerometer } from "expo-sensors";
16 import { Pressable, View } from "react-native";
17 import Animated, { FadeIn, FadeOut, ReduceMotion } from "react-native-reanimated";
18 import { useSafeAreaInsets } from "react-native-safe-area-context";
19
20 import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
21 import { AppText } from "../../components/ui/AppText";
22 import { ControlPill } from "../../components/ui/ControlPill";
23 import { Menu } from "../../components/ui/Menu";
24 import { GlassSurface } from "../../components/ui/GlassSurface";
25 import {
26 findAppBarMenuItem,
27 menuActionsFromAppBarItems,
28 } from "../../components/ui/menuActionItems";
29 import { AppBar } from "../../components/ui/AppBar";
30 import { m } from "../../i18n/messages";
31 import { useBarOverlap } from "../../components/ui/useBarInset";
32 import type { AppBarMenuItem } from "../../components/ui/AppBar.types";
33 import { useAppForeground } from "../../lib/appState";
34 import { useHardwareBack } from "../../lib/backHandler";
35 import { deriveBottomControlInsets } from "../../lib/reserved-regions";
36 import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
37 import { uuidv4 } from "../../lib/uuid";
38 import { deviceEnvironment, useDeviceHubAccess } from "../../state/device";
39 import { useEnvironmentQuery } from "../../state/query";
40 import { useAtomCommand } from "../../state/use-atom-command";
41 import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
42 import { DeviceStreamWebView, type DeviceStreamRef } from "./DeviceStreamWebView";
43 import {
44 selectedThreadDevicePreview,
45 threadDevicePreviews,
46 type ThreadDevicePreview,
47 } from "./threadDevicePreviews";
48 import { createShakeDetector } from "./shakeDetector";
49
50 const OVERLAY_ENTERING = FadeIn.duration(160).reduceMotion(ReduceMotion.System);
51 const OVERLAY_EXITING = FadeOut.duration(120).reduceMotion(ReduceMotion.System);
52
53 type DevicePreviewRouteScreenProps = StaticScreenProps<{
54 readonly environmentId: string;
55 readonly threadId: string;
56 readonly deviceKey?: string;
57 }>;
58
59 export function DevicePreviewRouteScreen({ route }: DevicePreviewRouteScreenProps) {
60 const navigation = useNavigation();
61 const onClose = () => navigation.goBack();
62 const { environmentId, threadId } = route.params;
63 const isBlankLink = environmentId.trim().length === 0 || threadId.trim().length === 0;
64 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pops a deep-linked route with a blank environment or thread off the navigator
65 useEffect(() => {
66 if (isBlankLink) onClose();
67 }, [isBlankLink, onClose]);
68 if (isBlankLink) return null;
69 return (
70 <DevicePreviewScreen
71 environmentId={EnvironmentId.make(environmentId)}
72 threadId={ThreadId.make(threadId)}
73 initialDeviceKey={route.params.deviceKey}
74 onClose={onClose}
75 />
76 );
77 }
78
79 export function DevicePreviewScreen({
80 environmentId,
81 threadId,
82 onClose,
83 onMaximize,
84 initialDeviceKey,
85 }: {
86 readonly environmentId: EnvironmentId;
87 readonly threadId: ThreadId;
88 readonly onClose: () => void;
89 readonly onMaximize?: (deviceKey: string | null) => void;
90 readonly initialDeviceKey?: string;
91 }) {
92 const embedded = onMaximize !== undefined;
93 const insets = useSafeAreaInsets();
94 // In a pane the stream sits below the pane's bar, which content otherwise slides under.
95 const barOverlap = useBarOverlap();
96 // NativeColumnContent already insets the sides, so only a book fold moves the hidden-controls pill.
97 const handleBounds = deriveBottomControlInsets(useNativeColumnLayoutMetrics());
98 const { themeVariables } = useAppearancePreferences();
99 const focused = useIsFocused();
100 const foreground = useAppForeground();
101 const [selectedKey, setSelectedKey] = useState<string | null>(initialDeviceKey ?? null);
102 const [inputConnected, setInputConnected] = useState(false);
103 const gt = useGT();
104 const [streamAttempt, setStreamAttempt] = useState(0);
105 const [shuttingDown, setShuttingDown] = useState(false);
106 const [controlsVisible, setControlsVisible] = useState(true);
107 const retryHost = useAtomCommand(deviceEnvironment.list);
108 const shutdown = useAtomCommand(deviceEnvironment.shutdown, { reportFailure: false });
109 const streamRef = useRef<DeviceStreamRef>(null);
110 const state = useEnvironmentQuery(deviceEnvironment.state({ environmentId, input: {} }));
111 const previews = threadDevicePreviews(state.data, threadId);
112 const preview = selectedThreadDevicePreview(previews, selectedKey);
113 const onInputConnected = async (connected: boolean) => {
114 setInputConnected(connected);
115 if (!connected) setControlsVisible(true);
116 };
117 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- closes the focused route through the navigator once the thread has no device previews
118 useEffect(() => {
119 if (focused && state.data !== null && previews.length === 0) onClose();
120 }, [focused, state.data, previews.length, onClose]);
121 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the Accelerometer while focused to toggle controls on a shake
122 useEffect(() => {
123 if (!focused || !foreground || embedded) return;
124 const shaken = createShakeDetector();
125 Accelerometer.setUpdateInterval(50);
126 const subscription = Accelerometer.addListener((sample) => {
127 if (!shaken({ ...sample, timestamp: sample.timestamp * 1000 })) return;
128 void Haptics.selectionAsync();
129 setControlsVisible((visible) => !visible);
130 });
131 return () => subscription.remove();
132 }, [focused, foreground, embedded]);
133 useHardwareBack(!controlsVisible, () => {
134 setControlsVisible(true);
135 return true;
136 });
137
138 const shutDownDevice = async () => {
139 if (!preview || shuttingDown) return;
140 setShuttingDown(true);
141 const result = await shutdown({
142 environmentId,
143 input: {
144 hostId: preview.session.hostId,
145 deviceId: preview.session.deviceId,
146 platform: preview.session.platform,
147 },
148 }).finally(() => setShuttingDown(false));
149 if (result._tag === "Failure") {
150 Dialog.alert(m(msg("Could not shut down device")), String(Cause.squash(result.cause)));
151 }
152 };
153
154 const controls: AppBarMenuItem[] = [
155 ...(state.data?.hosts
156 .filter(
157 (host) =>
158 state.data?.supportsHostRetry && state.data.hostStatuses[host.id]?.status === "failed",
159 )
160 .map((host) => ({
161 id: `retry-${host.id}`,
162 title: gt("Retry {host}", { host: host.label }),
163 icon: "arrow.clockwise" as const,
164 onPress: () => {
165 void retryHost({ environmentId, input: { retryHostId: host.id } });
166 },
167 })) ?? []),
168 ...(state.data?.supportsToolInspection
169 ? [
170 {
171 id: "check-device-tools",
172 title: gt("Check device tool versions"),
173 icon: "arrow.clockwise" as const,
174 onPress: () => {
175 void retryHost({ environmentId, input: { inspectOnly: true } });
176 },
177 },
178 ]
179 : []),
180 {
181 id: "device-tools",
182 title: gt("Device tool versions"),
183 icon: "info.circle",
184 onPress: () =>
185 Dialog.alert(
186 m(msg("Device tool versions")),
187 m(deviceToolUpdateOwnership) +
188 "\n\n" +
189 deviceToolUpdatePolicy(
190 state.data?.hosts.find((host) => host.id === preview?.session.hostId)?.tools,
191 m,
192 ) +
193 "\n\n" +
194 deviceToolVersionLabels(
195 state.data?.hosts.find((host) => host.id === preview?.session.hostId)?.tools,
196 m,
197 ).join("\n") +
198 "\n" +
199 (state.data?.hosts.find((host) => host.id === preview?.session.hostId)
200 ?.toolInspectionError ??
201 state.data?.hostStatuses[preview?.session.hostId ?? ""]?.detail ??
202 ""),
203 ),
204 },
205 {
206 id: "reload",
207 title: gt("Reload stream"),
208 icon: "arrow.clockwise" as const,
209 disabled: !preview || shuttingDown,
210 onPress: () => {
211 setInputConnected(false);
212 setStreamAttempt((attempt) => attempt + 1);
213 },
214 },
215 ...(preview?.session.platform === "android"
216 ? [
217 {
218 id: "back",
219 title: gt("Back", { $context: "Android back button" }),
220 icon: "arrow.left",
221 disabled: !inputConnected,
222 onPress: () => streamRef.current?.back(),
223 },
224 ]
225 : []),
226 {
227 id: "app-switcher",
228 title: gt("App switcher"),
229 icon: "square.on.square",
230 disabled: !inputConnected,
231 onPress: () => streamRef.current?.appSwitcher(),
232 },
233 ...(preview?.session.platform === "ios"
234 ? [
235 {
236 id: "rotate",
237 title: gt("Rotate device"),
238 icon: "arrow.clockwise" as const,
239 disabled: !inputConnected,
240 onPress: () => streamRef.current?.rotate(),
241 },
242 ]
243 : []),
244 {
245 id: "shutdown",
246 title: shuttingDown ? gt("Shutting down…") : gt("Shut down device"),
247 icon: "power",
248 disabled: !preview || shuttingDown,
249 onPress: () => void shutDownDevice(),
250 },
251 ];
252 const pressHome = () => streamRef.current?.home();
253 const menuItems: AppBarMenuItem[] = [
254 ...(previews.length > 1
255 ? [
256 {
257 id: "devices",
258 title: gt("Devices", { $context: "device list heading" }),
259 inline: true,
260 items: previews.map((device) => ({
261 id: device.key,
262 title: device.name,
263 subtitle: device.description,
264 selected: device.key === preview?.key,
265 onPress: () => setSelectedKey(device.key),
266 })),
267 },
268 ]
269 : []),
270 ...controls,
271 ];
272 return (
273 <View className="flex-1" style={{ backgroundColor: themeVariables["--color-sheet-solid"] }}>
274 {embedded ? (
275 <>
276 <AppBar
277 title={preview?.name ?? gt("Devices", { $context: "screen title" })}
278 actions={[
279 {
280 accessibilityLabel: gt("Maximize device"),
281 icon: "arrow.up.left.and.arrow.down.right",
282 onPress: () => onMaximize(preview?.key ?? null),
283 },
284 ]}
285 />
286 <View style={{ height: barOverlap }} />
287 </>
288 ) : null}
289 {preview && focused && foreground ? (
290 <OpenDevicePreview
291 key={`${preview.key}:${streamAttempt}`}
292 environmentId={environmentId}
293 preview={preview}
294 streamRef={streamRef}
295 onInputConnected={onInputConnected}
296 />
297 ) : (
298 <View className="flex-1 items-center justify-center gap-4 px-6">
299 {state.error ? (
300 <>
301 <AppText selectable className="text-center text-sm text-foreground-muted">
302 {state.error}
303 </AppText>
304 <View className="items-center">
305 <Button label={gt("Retry")} tone="secondary" onPress={state.refresh} />
306 </View>
307 </>
308 ) : focused && foreground ? (
309 <AppActivityIndicator color={themeVariables["--color-icon"]} />
310 ) : null}
311 </View>
312 )}
313 {embedded ? (
314 <View
315 className="flex-row items-center justify-center gap-2 px-3 py-2"
316 style={{ paddingBottom: Math.max(insets.bottom, 8) }}
317 >
318 <ControlPill
319 accessibilityLabel={gt("Home", { $context: "device home button" })}
320 icon="house"
321 disabled={!inputConnected}
322 onPress={pressHome}
323 />
324 <DeviceOptionsMenu items={menuItems} />
325 </View>
326 ) : controlsVisible ? (
327 <Animated.View
328 entering={OVERLAY_ENTERING}
329 exiting={OVERLAY_EXITING}
330 pointerEvents="box-none"
331 className="absolute inset-0"
332 >
333 {inputConnected ? (
334 <Pressable
335 accessibilityLabel={gt("Hide device controls")}
336 className="absolute inset-0 bg-black/30"
337 onPress={() => setControlsVisible(false)}
338 />
339 ) : null}
340 <View className="px-3" style={{ paddingTop: Math.max(insets.top, 12) }}>
341 <GlassSurface className="flex-row items-center gap-1 p-1">
342 <SheetCloseButton accessibilityLabel={gt("Close device preview")} onClose={onClose} />
343 <AppText numberOfLines={1} className="flex-1 text-center font-t3-medium text-base">
344 {preview?.name ?? gt("Devices", { $context: "screen title" })}
345 </AppText>
346 <ControlPill
347 accessibilityLabel={gt("Home", { $context: "device home button" })}
348 icon="house"
349 disabled={!inputConnected}
350 onPress={pressHome}
351 />
352 <DeviceOptionsMenu items={menuItems} />
353 </GlassSurface>
354 </View>
355 </Animated.View>
356 ) : (
357 <View
358 pointerEvents="box-none"
359 className="absolute self-center"
360 style={{
361 top: Math.max(insets.top, 12),
362 transform: [{ translateX: (handleBounds.left - handleBounds.right) / 2 }],
363 }}
364 >
365 <GlassSurface className="flex-row items-center gap-1 p-1">
366 <SheetCloseButton accessibilityLabel={gt("Close device preview")} onClose={onClose} />
367 <ControlPill
368 accessibilityLabel={gt("Show device controls")}
369 icon="chevron.down"
370 onPress={() => setControlsVisible(true)}
371 />
372 </GlassSurface>
373 </View>
374 )}
375 </View>
376 );
377 }
378
379 function DeviceOptionsMenu({ items }: { readonly items: ReadonlyArray<AppBarMenuItem> }) {
380 const gt = useGT();
381 return (
382 <Menu
383 actions={menuActionsFromAppBarItems(items)}
384 isAnchoredToRight
385 title={gt("Device options")}
386 onPressAction={({ nativeEvent }) => {
387 const action = findAppBarMenuItem(items, nativeEvent.event);
388 if (action && !action.disabled) action.onPress();
389 }}
390 >
391 <ControlPill icon="ellipsis" accessibilityLabel={gt("Device options")} />
392 </Menu>
393 );
394 }
395
396 function OpenDevicePreview({
397 environmentId,
398 preview,
399 streamRef,
400 onInputConnected,
401 }: {
402 readonly environmentId: EnvironmentId;
403 readonly preview: ThreadDevicePreview;
404 readonly streamRef: RefObject<DeviceStreamRef | null>;
405 readonly onInputConnected: (connected: boolean) => Promise<void>;
406 }) {
407 const { session } = preview;
408 const { themeVariables } = useAppearancePreferences();
409 const gt = useGT();
410 const [viewer] = useState(uuidv4);
411 const { access, error, refresh } = useDeviceHubAccess(environmentId, session.hostId, viewer);
412 const onUnauthorized = async () => refresh();
413 return access ? (
414 <DeviceStreamWebView
415 ref={streamRef}
416 access={access}
417 platform={session.platform}
418 deviceId={session.deviceId}
419 serveSimOnly={preview.serveSimOnly}
420 colors={{
421 background: themeVariables["--color-sheet-solid"],
422 foreground: themeVariables["--color-foreground"],
423 muted: themeVariables["--color-foreground-muted"],
424 buttonBackground: themeVariables["--color-secondary"],
425 buttonForeground: themeVariables["--color-secondary-foreground"],
426 buttonBorder: themeVariables["--color-secondary-border"],
427 }}
428 onUnauthorized={onUnauthorized}
429 onInputConnected={onInputConnected}
430 />
431 ) : (
432 <View className="flex-1 items-center justify-center gap-4 px-6">
433 {error ? (
434 <>
435 <AppText selectable className="text-center text-sm text-foreground-muted">
436 {error}
437 </AppText>
438 <View className="items-center">
439 <Button label={gt("Retry")} tone="secondary" onPress={refresh} />
440 </View>
441 </>
442 ) : (
443 <>
444 <AppActivityIndicator color={themeVariables["--color-icon"]} />
445 <AppText className="text-sm text-foreground-muted">
446 <T>Connecting to device...</T>
447 </AppText>
448 </>
449 )}
450 </View>
451 );
452 }