Open History to see the last commit
1import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
2import * as Dialog from "../../components/ui/Dialog";
3import previewStreamScript from "@t3tools/mobile-preview-stream";
4import {
5 previewStreamControlLabel,
6 previewStreamHostSetupMessage,
7 type PreviewStreamControl,
8 type PreviewStreamDownload,
9 type PreviewStreamFileChooser,
10 type PreviewStreamInput,
11} from "@t3tools/client-runtime/preview/server-browser-stream";
12import type { EnvironmentId, PreviewStreamHostSetup } from "@t3tools/contracts";
13import {
14 useEffect,
15 useEffectEvent,
16 useImperativeHandle,
17 useLayoutEffect,
18 useMemo,
19 useRef,
20 useState,
21 type Ref,
22} from "react";
23import { Platform, Pressable, TextInput, View } from "react-native";
24import { WebView } from "react-native-webview";
25import * as Clipboard from "expo-clipboard";
26
27import { AppText } from "../../components/ui/AppText";
28import { downloadAndShareAttachment } from "../../lib/attachmentDownload";
29import { beginForegroundHandoff } from "../../lib/foreground-handoff";
30import { usePreviewStreamAccess } from "../../state/preview";
31import { previewPromptText } from "./previewPromptText";
32
33import {
34 previewStreamDocument,
35 previewStreamMessage,
36 type PreviewStreamConfiguration,
37} from "./preview-stream-document";
38
39export interface PreviewStreamRef {
40 /** Navigation requires current control of the browser. */
41 readonly command: (input: PreviewStreamInput) => void;
42 readonly togglePictureInPicture: () => void;
43}
44
45export interface PreviewPictureInPictureState {
46 readonly supported: boolean;
47 readonly active: boolean;
48}
49
50type NativeStreamBridge = {
51 readonly ref?: Ref<PreviewStreamRef>;
52 /** Refresh stream access; new access remounts the document with a fresh ticket. */
53 readonly onUnauthorized: () => void;
54 /** The tab was closed on the server. */
55 readonly onGone?: () => void;
56 readonly onViewport?: (viewport: { readonly width: number; readonly height: number }) => void;
57 readonly onControl?: (control: PreviewStreamControl | null) => void;
58 readonly onPictureInPicture?: (state: PreviewPictureInPictureState, detail?: string) => void;
59 /** True while frames show, so commands reach the page. Pass a stable function. */
60 readonly onStreamingChange?: (streaming: boolean) => void;
61 /** The floating player shows a spinner without text or a reconnect button. */
62 readonly compact?: boolean;
63};
64
65/** Picks files on this device and sends them to the page's open picker; none cancels it. */
66async function sendFilesToPage(chooser: PreviewStreamFileChooser, pick: boolean) {
67 const body = new FormData();
68 if (pick) {
69 const { getDocumentAsync } = await import("expo-document-picker");
70 const endHandoff = beginForegroundHandoff();
71 let result: Awaited<ReturnType<typeof getDocumentAsync>>;
72 try {
73 result = await getDocumentAsync({ multiple: chooser.multiple, copyToCacheDirectory: true });
74 } finally {
75 endHandoff();
76 }
77 for (const asset of result.canceled ? [] : result.assets) {
78 // React Native's FormData uploads a file part from its URI.
79 body.append("file", {
80 uri: asset.uri,
81 name: asset.name,
82 type: asset.mimeType ?? "application/octet-stream",
83 } as unknown as Blob);
84 }
85 }
86 const response = await fetch(chooser.uploadUrl, {
87 method: "POST",
88 body,
89 credentials: chooser.credentials ? "include" : "omit",
90 });
91 if (!response.ok) throw new Error((await response.text()) || "The upload was refused.");
92}
93
94/** The file is on the environment; saving it here goes through the share sheet. */
95function offerDownload(download: PreviewStreamDownload) {
96 Dialog.alert(`Downloaded ${download.fileName}`, undefined, [
97 { text: "Not now", style: "cancel" },
98 {
99 text: "Save or share",
100 onPress: () =>
101 void downloadAndShareAttachment({
102 url: download.url,
103 attachment: { name: download.fileName, mimeType: "application/octet-stream" },
104 signal: new AbortController().signal,
105 }).catch((cause: unknown) =>
106 Dialog.alert(
107 "Could not save the download",
108 cause instanceof Error ? cause.message : undefined,
109 ),
110 ),
111 },
112 ]);
113}
114
115// Consecutive refused tickets before the view stops and offers Reconnect, e.g. a
116// session without operate scope.
117const MAX_REFUSALS = 3;
118
119export function PreviewStreamWebView(
120 props: Omit<PreviewStreamConfiguration, "access"> &
121 Omit<NativeStreamBridge, "onUnauthorized"> & {
122 readonly environmentId: EnvironmentId;
123 readonly paused?: boolean;
124 },
125) {
126 const { access, error, refresh } = usePreviewStreamAccess(props.environmentId);
127 if (access && !props.paused) {
128 return <AuthorizedPreviewStream {...props} access={access} onUnauthorized={refresh} />;
129 }
130 return (
131 <View
132 className={
133 props.compact
134 ? "flex-1 items-center justify-center"
135 : "flex-1 items-center justify-center gap-4 px-6"
136 }
137 >
138 {props.compact || !error ? <AppActivityIndicator colorClassName="accent-icon" /> : null}
139 {!props.compact && (
140 <>
141 <AppText
142 selectable={!!error}
143 className={
144 error ? "text-center text-sm text-foreground-muted" : "text-sm text-foreground-muted"
145 }
146 >
147 {error || "Connecting to browser..."}
148 </AppText>
149 {error && (
150 <Pressable
151 accessibilityRole="button"
152 className="rounded-full border border-secondary-border bg-secondary px-6 py-3"
153 onPress={refresh}
154 >
155 <AppText className="text-secondary-foreground">Retry</AppText>
156 </Pressable>
157 )}
158 </>
159 )}
160 </View>
161 );
162}
163
164function AuthorizedPreviewStream({
165 ref,
166 ...props
167}: PreviewStreamConfiguration & NativeStreamBridge) {
168 const [attempt, setAttempt] = useState(0);
169 const [previousAccess, setPreviousAccess] = useState(props.access);
170 // Wait for refreshed access, including cookie credentials with unchanged JSON.
171 if (props.access !== previousAccess) {
172 setPreviousAccess(props.access);
173 setAttempt((current) => current + 1);
174 }
175 const processRetried = useRef(false);
176 const unauthorized = useRef(0);
177 const refreshTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
178 useEffect(
179 () => () => {
180 if (refreshTimer.current !== null) clearTimeout(refreshTimer.current);
181 },
182 [],
183 );
184 const configuration = JSON.stringify({
185 access: props.access,
186 threadId: props.threadId,
187 tabId: props.tabId,
188 interactive: props.interactive,
189 background: props.background,
190 } satisfies PreviewStreamConfiguration);
191 return (
192 <PreviewStreamDocumentView
193 key={`${attempt}:${configuration}`}
194 {...props}
195 ref={ref}
196 configuration={configuration}
197 onUnauthorized={() => {
198 // The client has stopped. Restart it with a fresh ticket, backing off between refusals.
199 const refusals = ++unauthorized.current;
200 if (refusals >= MAX_REFUSALS) return false;
201 if (refreshTimer.current !== null) clearTimeout(refreshTimer.current);
202 refreshTimer.current = setTimeout(
203 () => {
204 refreshTimer.current = null;
205 props.onUnauthorized();
206 },
207 refusals === 1 ? 0 : 1_000 * 2 ** (refusals - 1),
208 );
209 return true;
210 }}
211 onRetry={() => {
212 processRetried.current = false;
213 unauthorized.current = 0;
214 props.onUnauthorized();
215 }}
216 onStreaming={() => {
217 processRetried.current = false;
218 unauthorized.current = 0;
219 }}
220 onRecoverProcess={() => {
221 if (processRetried.current) return false;
222 processRetried.current = true;
223 setAttempt((current) => current + 1);
224 return true;
225 }}
226 />
227 );
228}
229
230function PreviewStreamDocumentView({
231 ref,
232 configuration,
233 background,
234 compact,
235 onUnauthorized,
236 onGone,
237 onViewport,
238 onControl,
239 onPictureInPicture,
240 onStreamingChange,
241 onRetry,
242 onStreaming,
243 onRecoverProcess,
244}: Omit<NativeStreamBridge, "onUnauthorized"> & {
245 readonly configuration: string;
246 readonly background: string;
247 /** False when the view should stop retrying and fail. */
248 readonly onUnauthorized: () => boolean;
249 readonly onRetry: () => void;
250 readonly onStreaming: () => void;
251 readonly onRecoverProcess: () => boolean;
252}) {
253 const webView = useRef<WebView<object>>(null);
254 const active = useRef(true);
255 const failed = useRef(false);
256 const [status, setStatus] = useState<"connecting" | "streaming" | "error">("connecting");
257 const [error, setError] = useState<string | null>(null);
258 const [gone, setGone] = useState(false);
259 const [hostSetup, setHostSetup] = useState<PreviewStreamHostSetup | null>(null);
260 const [started, setStarted] = useState(false);
261 const [control, setControl] = useState<PreviewStreamControl | null>(null);
262 const dialogRef = useRef<PreviewStreamControl["dialog"]>(null);
263 const [promptText, setPromptText] = useState("");
264 const [fileChooser, setFileChooser] = useState<PreviewStreamFileChooser | null>(null);
265 const answerFileChooser = (pick: boolean) => {
266 const chooser = fileChooser;
267 if (!chooser) return;
268 setFileChooser(null);
269 void sendFilesToPage(chooser, pick).catch((cause: unknown) =>
270 Dialog.alert(
271 "Could not send the files to the page",
272 cause instanceof Error ? cause.message : undefined,
273 ),
274 );
275 };
276 const controlChanged = useEffectEvent((next: PreviewStreamControl | null) => onControl?.(next));
277 const command = (input: PreviewStreamInput) =>
278 webView.current?.injectJavaScript(
279 `window.T3PreviewStream?.command(${JSON.stringify(input)}); true;`,
280 );
281 const fail = (message: string) => {
282 if (!active.current || failed.current) return;
283 failed.current = true;
284 webView.current?.injectJavaScript("window.T3PreviewStream?.stop(); true;");
285 onStreamingChange?.(false);
286 setControl(null);
287 setFileChooser(null);
288 onControl?.(null);
289 setError(message);
290 setStatus("error");
291 };
292 // The shared transport owns reconnects once the document acknowledges startup.
293 const bootstrapTimedOut = useEffectEvent(() =>
294 fail("Browser viewer could not start. Reconnect to try again."),
295 );
296 useEffect(() => {
297 if (started) return;
298 const timer = setTimeout(bootstrapTimedOut, 15_000);
299 return () => clearTimeout(timer);
300 }, [started]);
301 const source = useMemo(
302 () => ({
303 html: previewStreamDocument(configuration, previewStreamScript),
304 baseUrl: Platform.OS === "android" ? "https://localhost/" : "file:///",
305 }),
306 [configuration],
307 );
308 useImperativeHandle(ref, () => ({
309 command,
310 togglePictureInPicture: () =>
311 webView.current?.injectJavaScript("window.T3PreviewStream?.pictureInPicture(); true;"),
312 }));
313 useLayoutEffect(() => {
314 active.current = true;
315 const view = webView.current;
316 return () => {
317 active.current = false;
318 view?.injectJavaScript("window.T3PreviewStream?.stop(); true;");
319 };
320 }, []);
321 useEffect(() => () => onStreamingChange?.(false), [onStreamingChange]);
322 useEffect(() => () => controlChanged(null), []);
323 const processTerminated = () => {
324 if (!active.current || failed.current) return;
325 if (!onRecoverProcess()) fail("Browser viewer stopped. Reconnect to try again.");
326 };
327 return (
328 <View className="flex-1" style={{ backgroundColor: background }}>
329 {!compact ? (
330 <View className="flex-row items-center justify-between gap-2 border-b border-secondary-border px-3 py-2">
331 <AppText className="text-xs text-foreground-muted">
332 {previewStreamControlLabel(control)}
333 </AppText>
334 {control?.canOperate ? (
335 <Pressable
336 accessibilityRole="button"
337 disabled={control.controller === "another-viewer"}
338 accessibilityState={{ disabled: control.controller === "another-viewer" }}
339 className="rounded-full border border-secondary-border bg-secondary px-3 py-2"
340 onPress={() =>
341 command({ type: control.controller === "you" ? "releaseControl" : "takeControl" })
342 }
343 >
344 <AppText className="text-xs text-secondary-foreground">
345 {control.controller === "you" ? "Release control" : "Take control"}
346 </AppText>
347 </Pressable>
348 ) : null}
349 </View>
350 ) : null}
351 <WebView<object>
352 ref={webView}
353 source={source}
354 originWhitelist={["*"]}
355 scrollEnabled={false}
356 bounces={false}
357 mixedContentMode="always"
358 allowUniversalAccessFromFileURLs
359 contentInsetAdjustmentBehavior="never"
360 setSupportMultipleWindows={false}
361 // Picture in picture plays the canvas as an inline muted video, started from native chrome.
362 allowsInlineMediaPlayback
363 allowsPictureInPictureMediaPlayback
364 mediaPlaybackRequiresUserAction={false}
365 style={{ flex: 1, backgroundColor: background }}
366 onError={() => fail("Browser viewer could not load. Reconnect to try again.")}
367 onHttpError={() => fail("Browser viewer could not load. Reconnect to try again.")}
368 onContentProcessDidTerminate={processTerminated}
369 onRenderProcessGone={processTerminated}
370 onShouldStartLoadWithRequest={(request) =>
371 request.url === "about:blank" || request.url === source.baseUrl
372 }
373 onMessage={(event) => {
374 if (!active.current || failed.current) return;
375 const message = previewStreamMessage(event.nativeEvent.data);
376 if (message === null) return;
377 switch (message.type) {
378 case "control": {
379 setControl(message);
380 const previousDialog = dialogRef.current;
381 dialogRef.current = message.dialog;
382 setPromptText((draft) => previewPromptText(previousDialog, message.dialog, draft));
383 onControl?.(message);
384 return;
385 }
386 case "unauthorized":
387 if (!onUnauthorized()) {
388 fail("This session can't open the browser stream. Reconnect to try again.");
389 }
390 return;
391 case "gone":
392 setGone(true);
393 fail("This tab was closed.");
394 onGone?.();
395 return;
396 case "hostSetup":
397 setHostSetup({ need: message.need, command: message.command });
398 fail(previewStreamHostSetupMessage(message));
399 return;
400 case "viewport":
401 onViewport?.(message);
402 return;
403 case "clipboard":
404 void Clipboard.setStringAsync(message.text).catch(() => undefined);
405 return;
406 case "download":
407 offerDownload(message);
408 return;
409 case "fileChooser":
410 setFileChooser(message.chooser);
411 return;
412 case "pictureInPicture":
413 onPictureInPicture?.(message, message.detail);
414 return;
415 case "status":
416 setStarted(true);
417 if (message.status === "error") {
418 fail(message.detail ?? "Browser stream failed.");
419 return;
420 }
421 setStatus(message.status);
422 if (message.status === "connecting") {
423 // Dialogs may have closed and reopened while this viewer was disconnected.
424 dialogRef.current = null;
425 setControl(null);
426 onControl?.(null);
427 }
428 onStreamingChange?.(message.status === "streaming");
429 if (message.status === "streaming") onStreaming();
430 }
431 }}
432 />
433 {!compact && fileChooser && control?.controller === "you" ? (
434 <View className="absolute inset-x-3 top-16 gap-3 rounded-xl border border-secondary-border bg-secondary p-4">
435 <AppText className="text-sm text-secondary-foreground">
436 The page asks for {fileChooser.multiple ? "files" : "a file"}.
437 </AppText>
438 <View className="flex-row justify-end gap-3">
439 <Pressable
440 accessibilityRole="button"
441 className="px-3 py-2"
442 onPress={() => answerFileChooser(false)}
443 >
444 <AppText className="text-secondary-foreground">Cancel</AppText>
445 </Pressable>
446 <Pressable
447 accessibilityRole="button"
448 className="px-3 py-2"
449 onPress={() => answerFileChooser(true)}
450 >
451 <AppText className="text-secondary-foreground">
452 Choose {fileChooser.multiple ? "files" : "file"}
453 </AppText>
454 </Pressable>
455 </View>
456 </View>
457 ) : null}
458 {!compact && control?.dialog ? (
459 <View className="absolute inset-x-3 top-16 gap-3 rounded-xl border border-secondary-border bg-secondary p-4">
460 <AppText className="text-sm text-secondary-foreground">{control.dialog.message}</AppText>
461 {control.controller === "you" ? (
462 <>
463 {control.dialog.type === "prompt" ? (
464 <TextInput
465 accessibilityLabel="Dialog response"
466 className="rounded-lg border border-input-border bg-input px-3 py-2 text-foreground"
467 placeholderTextColorClassName="accent-placeholder"
468 selectionColorClassName="accent-focus/32"
469 value={promptText}
470 onChangeText={setPromptText}
471 />
472 ) : null}
473 <View className="flex-row justify-end gap-3">
474 <Pressable
475 accessibilityRole="button"
476 className="px-3 py-2"
477 onPress={() => command({ type: "dialog", accept: false })}
478 >
479 <AppText className="text-secondary-foreground">Dismiss</AppText>
480 </Pressable>
481 <Pressable
482 accessibilityRole="button"
483 className="px-3 py-2"
484 onPress={() =>
485 command({
486 type: "dialog",
487 accept: true,
488 ...(control.dialog?.type === "prompt" ? { promptText } : {}),
489 })
490 }
491 >
492 <AppText className="text-secondary-foreground">Accept</AppText>
493 </Pressable>
494 </View>
495 </>
496 ) : (
497 <AppText className="text-xs text-foreground-muted">Take control to respond.</AppText>
498 )}
499 </View>
500 ) : null}
501 {status !== "streaming" ? (
502 <View
503 className="absolute inset-0 items-center justify-center gap-4 px-6"
504 style={{ backgroundColor: background }}
505 >
506 {status === "connecting" ? <AppActivityIndicator colorClassName="accent-icon" /> : null}
507 {compact ? null : (
508 <AppText
509 accessibilityLiveRegion="polite"
510 className="text-center text-sm text-foreground-muted"
511 >
512 {status === "error" ? error : "Connecting to browser..."}
513 </AppText>
514 )}
515 {status === "error" && hostSetup && !compact ? (
516 <Pressable
517 accessibilityRole="button"
518 accessibilityLabel={`Copy ${hostSetup.command}`}
519 className="w-full flex-row items-center gap-2 rounded-xl border border-secondary-border bg-secondary px-4 py-3"
520 onPress={() => {
521 void Clipboard.setStringAsync(hostSetup.command).catch(() => undefined);
522 }}
523 >
524 <AppText selectable className="flex-1 font-mono text-sm text-secondary-foreground">
525 {hostSetup.command}
526 </AppText>
527 <AppText className="text-xs text-foreground-muted">Copy</AppText>
528 </Pressable>
529 ) : null}
530 {status === "error" && !gone && !compact ? (
531 <Pressable
532 accessibilityRole="button"
533 className="rounded-full border border-secondary-border bg-secondary px-6 py-3"
534 onPress={onRetry}
535 >
536 <AppText className="text-secondary-foreground">
537 {hostSetup ? "Try again" : "Reconnect"}
538 </AppText>
539 </Pressable>
540 ) : null}
541 </View>
542 ) : null}
543 </View>
544 );
545}