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

main
tsx 248 lines 8.42 KB
Raw
1 import { Button } from "../../components/ui/Button";
2 import deviceStreamScript from "@t3tools/mobile-device-stream";
3 import {
4 useEffectEvent,
5 useImperativeHandle,
6 useLayoutEffect,
7 useRef,
8 useState,
9 type Ref,
10 } from "react";
11 import { decodeOptions, msg, useGT } from "gt-react-native";
12 import { Platform, View } from "react-native";
13 import { WebView } from "react-native-webview";
14 import type { DeviceStreamStatus } from "@t3tools/client-runtime/device/stream";
15
16 import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
17 import { AppText } from "../../components/ui/AppText";
18 import { m, type MessageResolver } from "../../i18n/messages";
19
20 import {
21 deviceStreamBaseUrl,
22 deviceStreamDocument,
23 deviceStreamMessage,
24 type DeviceStreamConfiguration,
25 } from "./device-stream-document";
26
27 /** Resolves a status detail the WebView left marked, including marked variables inside it. */
28 function streamDetailText(detail: string, resolve: MessageResolver): string {
29 const options = decodeOptions(detail);
30 if (typeof options?.$_source !== "string") return detail;
31 const { $_source: source, ...variables } = options;
32 return resolve(
33 source,
34 Object.fromEntries(
35 Object.entries(variables).map(([key, value]) => [
36 key,
37 typeof value === "string" && !key.startsWith("$")
38 ? streamDetailText(value, resolve)
39 : value,
40 ]),
41 ),
42 );
43 }
44
45 export interface DeviceStreamRef {
46 home: () => void;
47 back: () => void;
48 appSwitcher: () => void;
49 rotate: () => void;
50 }
51
52 type NativeStreamBridge = {
53 readonly ref?: Ref<DeviceStreamRef>;
54 readonly onUnauthorized: () => Promise<void>;
55 readonly onInputConnected: (connected: boolean) => Promise<void>;
56 };
57
58 export function DeviceStreamWebView({
59 ref,
60 ...props
61 }: Omit<DeviceStreamConfiguration, "labels"> & NativeStreamBridge) {
62 const gt = useGT();
63 const [attempt, setAttempt] = useState(0);
64 const processRetried = useRef(false);
65 const configuration = JSON.stringify({
66 access: props.access,
67 platform: props.platform,
68 deviceId: props.deviceId,
69 ...(props.serveSimOnly ? { serveSimOnly: true } : {}),
70 colors: props.colors,
71 labels: {
72 screen: props.platform === "ios" ? gt("iOS Simulator screen") : gt("Android Emulator screen"),
73 reconnectingControls: gt("Reconnecting device controls..."),
74 },
75 } satisfies DeviceStreamConfiguration);
76 return (
77 <DeviceStreamDocumentView
78 key={`${attempt}:${configuration}`}
79 ref={ref}
80 configuration={configuration}
81 baseUrl={deviceStreamBaseUrl(Platform.OS, props.platform, props.access.httpBase)}
82 background={props.colors.background}
83 onUnauthorized={props.onUnauthorized}
84 onInputConnected={props.onInputConnected}
85 onRetry={() => {
86 processRetried.current = false;
87 setAttempt((attempt) => attempt + 1);
88 void props.onUnauthorized();
89 }}
90 onStreaming={() => {
91 processRetried.current = false;
92 }}
93 onRecoverProcess={() => {
94 if (processRetried.current) return false;
95 processRetried.current = true;
96 setAttempt((attempt) => attempt + 1);
97 void props.onUnauthorized();
98 return true;
99 }}
100 />
101 );
102 }
103
104 function DeviceStreamDocumentView({
105 ref,
106 configuration,
107 baseUrl,
108 background,
109 onUnauthorized,
110 onInputConnected,
111 onRetry,
112 onStreaming,
113 onRecoverProcess,
114 }: NativeStreamBridge & {
115 readonly configuration: string;
116 readonly baseUrl: string;
117 readonly background: string;
118 readonly onRetry: () => void;
119 readonly onStreaming: () => void;
120 readonly onRecoverProcess: () => boolean;
121 }) {
122 const webView = useRef<WebView<object>>(null);
123 const gt = useGT();
124 const active = useRef(false);
125 const failed = useRef(false);
126 const bootstrapTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
127 const [status, setStatus] = useState<DeviceStreamStatus>("connecting");
128 const [error, setError] = useState<string | null>(null);
129 const clearBootstrapTimer = () => {
130 if (bootstrapTimer.current === null) return;
131 clearTimeout(bootstrapTimer.current);
132 bootstrapTimer.current = null;
133 };
134 const fail = (message: string) => {
135 if (!active.current || failed.current) return;
136 failed.current = true;
137 clearBootstrapTimer();
138 void onInputConnected(false);
139 webView.current?.injectJavaScript("window.T3DeviceStream?.stop(); true;");
140 setError(message);
141 setStatus("error");
142 };
143 const bootstrapTimedOut = useEffectEvent(() =>
144 fail(m(msg("Device viewer could not start. Reconnect to try again."))),
145 );
146 const resetInput = useEffectEvent(() => void onInputConnected(false));
147 // The stream lives exactly as long as this view.
148 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- starts the bootstrap timeout and stops the WebView device stream when this view unmounts
149 useLayoutEffect(() => {
150 active.current = true;
151 resetInput();
152 const view = webView.current;
153 bootstrapTimer.current = setTimeout(bootstrapTimedOut, 15_000);
154 return () => {
155 if (bootstrapTimer.current !== null) clearTimeout(bootstrapTimer.current);
156 bootstrapTimer.current = null;
157 active.current = false;
158 view?.injectJavaScript("window.T3DeviceStream?.stop(); true;");
159 resetInput();
160 };
161 }, []);
162 const source = {
163 html: deviceStreamDocument(
164 configuration,
165 deviceStreamScript,
166 gt("Device viewer stopped unexpectedly."),
167 ),
168 baseUrl,
169 };
170 const command = (button: keyof DeviceStreamRef) => {
171 webView.current?.injectJavaScript(
172 `window.T3DeviceStream?.command(${JSON.stringify(button)}); true;`,
173 );
174 };
175 useImperativeHandle(ref, () => ({
176 home: () => command("home"),
177 back: () => command("back"),
178 appSwitcher: () => command("appSwitcher"),
179 rotate: () => command("rotate"),
180 }));
181 const processTerminated = () => {
182 if (!active.current || failed.current) return;
183 void onInputConnected(false);
184 if (!onRecoverProcess()) fail(m(msg("Device viewer stopped. Reconnect to try again.")));
185 };
186 return (
187 <View className="flex-1" style={{ backgroundColor: background }}>
188 <WebView<object>
189 ref={webView}
190 source={source}
191 originWhitelist={["*"]}
192 scrollEnabled={false}
193 bounces={false}
194 mixedContentMode="always"
195 allowUniversalAccessFromFileURLs
196 contentInsetAdjustmentBehavior="never"
197 setSupportMultipleWindows={false}
198 style={{ flex: 1, backgroundColor: background }}
199 onError={() => fail(m(msg("Device viewer could not load. Reconnect to try again.")))}
200 onHttpError={() => fail(m(msg("Device viewer could not load. Reconnect to try again.")))}
201 onContentProcessDidTerminate={processTerminated}
202 onRenderProcessGone={processTerminated}
203 onShouldStartLoadWithRequest={(request) =>
204 request.url === "about:blank" || request.url === source.baseUrl
205 }
206 onMessage={(event) => {
207 if (!active.current || failed.current) return;
208 const message = deviceStreamMessage(event.nativeEvent.data);
209 if (message?.type === "unauthorized") void onUnauthorized();
210 else if (message?.type === "input") void onInputConnected(message.connected);
211 else if (message?.type === "retry") onRetry();
212 else if (message?.type === "status") {
213 clearBootstrapTimer();
214 if (message.status === "error")
215 fail(
216 message.detail === undefined
217 ? m(msg("Device stream failed."))
218 : streamDetailText(message.detail, m),
219 );
220 else {
221 setStatus(message.status);
222 if (message.status === "streaming") onStreaming();
223 }
224 }
225 }}
226 />
227 {status !== "streaming" ? (
228 <View
229 className="absolute inset-0 items-center justify-center gap-4 px-6"
230 style={{ backgroundColor: background }}
231 >
232 {status === "connecting" ? <AppActivityIndicator colorClassName="accent-icon" /> : null}
233 <AppText
234 accessibilityLiveRegion="polite"
235 className="text-center text-sm text-foreground-muted"
236 >
237 {status === "error" ? error : gt("Connecting to device...")}
238 </AppText>
239 {status === "error" ? (
240 <View className="items-center">
241 <Button label={gt("Reconnect")} tone="secondary" onPress={onRetry} />
242 </View>
243 ) : null}
244 </View>
245 ) : null}
246 </View>
247 );
248 }