Open History to see the last commit
1import { Button } from "../../components/ui/Button";
2import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
3import * as Dialog from "../../components/ui/Dialog";
4import type { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";
5import {
6 makeMcpAppHost,
7 McpAppHostRefusal,
8 mcpAppStyleVariables,
9 mcpResourceBytes,
10 type McpAppCallToolResult,
11 type McpAppHost,
12 type McpAppHostContext,
13} from "@t3tools/client-runtime/mcp-apps";
14import { scopeThreadRef } from "@t3tools/client-runtime/environment";
15import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
16import { CommandId, MessageId } from "@t3tools/contracts";
17import {
18 MCP_APP_DOCUMENT_MESSAGE,
19 mcpAppAllowAttribute,
20 mcpAppFileName,
21 mcpAppReferencesEqual,
22 type McpAppReference,
23} from "@t3tools/shared/mcpApp";
24import * as Predicate from "effect/Predicate";
25import { AsyncResult } from "effect/reactivity";
26import Constants from "expo-constants";
27import { msg, T, useGT, Var } from "gt-react-native";
28import { useNavigation } from "@react-navigation/native";
29import { useEffect, useEffectEvent, useRef, useState } from "react";
30import { Platform, View } from "react-native";
31import { useSafeAreaInsets } from "react-native-safe-area-context";
32import { WebView, type WebViewMessageEvent } from "react-native-webview";
33
34import { AppText as Text } from "../../components/ui/AppText";
35import { m } from "../../i18n/messages";
36import { shareGeneratedAttachment } from "../../lib/attachmentDownload";
37import { mobileHtmlRenderTheme } from "../../lib/htmlRenderTheme";
38import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
39import { uuidv4 } from "../../lib/uuid";
40import { webViewDecelerationRate } from "../../lib/webViewDecelerationRate";
41import { useAssetUrlState } from "../../state/assets";
42import { appAtomRegistry } from "../../state/atom-registry";
43import { useThreadShell } from "../../state/entities";
44import { mcpAppEnvironment } from "../../state/mcpApps";
45import { orchestrationEnvironment } from "../../state/orchestration";
46import { useEnvironmentQuery } from "../../state/query";
47import { enqueueThreadOutboxMessage } from "../../state/thread-outbox";
48import { useAtomCommand } from "../../state/use-atom-command";
49import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
50import { MCP_APP_INLINE_MAX_HEIGHT, mcpAppInlineHeight } from "./mcpAppSizing";
51
52const ROW_BOTTOM_MARGIN = 8;
53
54// Android exposes `ReactNativeWebView` to every frame, so a frame nested in the
55// app could post to React Native directly. The outer page therefore wraps what
56// it relays with a secret only it holds, and React Native drops anything else.
57// The relay also attests activation; the sandboxed app cannot set that flag.
58function outerDocument(src: string, allow: string, secret: string) {
59 const attribute = (value: string) =>
60 value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");
61 // The frame's window outlives its document, so the relay trusts only the port the app
62 // document's bootstrap sends first, and relays a message once that document confirms it is
63 // alive. Servers without the bootstrap keep the plain window relay.
64 return `<!doctype html><html><head><meta name="viewport" content="width=device-width, initial-scale=1">
65<style>html,body{margin:0;height:100%;background:transparent}iframe{border:0;display:block;width:100%;height:100%}</style></head>
66<body><iframe id="app" sandbox="allow-scripts allow-forms" allow="${attribute(allow)}"></iframe>
67<script>(function(){var frame=document.getElementById("app"),secret=${JSON.stringify(secret)},loads=0,live=true;
68var send=function(m){var u=navigator.userActivation;window.ReactNativeWebView.postMessage(JSON.stringify({secret:secret,active:!!(u&&u.isActive)&&document.activeElement===frame,message:m}));};
69frame.addEventListener("load",function(){loads+=1;if(loads>1&&live){live=false;send({t3:"navigated"});}});
70var port=null,plain=false,unconfirmed=Object.create(null),waiting=0,probe=0;
71window.addEventListener("message",function(e){if(!live||e.source!==frame.contentWindow)return;
72if(!port&&!plain){if(e.data&&e.data.t3===${JSON.stringify(MCP_APP_DOCUMENT_MESSAGE)}&&e.ports[0]){port=e.ports[0];
73port.onmessage=function(r){var k=r.data&&r.data.alive;if(live&&k in unconfirmed){var m=unconfirmed[k];delete unconfirmed[k];waiting-=1;send(m);}};return;}plain=true;}
74if(plain)send(e.data);else if(waiting<256){unconfirmed[probe]=e.data;waiting+=1;port.postMessage({alive:probe++});}});
75window.__t3McpAppReceive=function(m){if(!live)return;if(port)port.postMessage({message:m,origin:location.origin});else if(plain&&frame.contentWindow)frame.contentWindow.postMessage(m,"*");};
76frame.src=${JSON.stringify(src).replace(/</g, "\\u003c")};})();</script></body></html>`;
77}
78
79const commandFailure = (result: {
80 readonly cause: Parameters<typeof squashAtomCommandFailure>[0]["cause"];
81}) => {
82 const error = squashAtomCommandFailure(result);
83 return new McpAppHostRefusal({
84 message:
85 error instanceof Error && error.message.trim() !== "" ? error.message : "Request failed.",
86 });
87};
88
89const confirm = (title: string, message: string, action: string) =>
90 new Promise<boolean>((resolve) => {
91 Dialog.alert(
92 title,
93 message,
94 [
95 { text: m(msg("Cancel")), style: "cancel", onPress: () => resolve(false) },
96 { text: action, onPress: () => resolve(true) },
97 ],
98 // Android dismisses earlier alerts when showing another; decline dismissed requests to release their slots.
99 { cancelable: true, onDismiss: () => resolve(false) },
100 );
101 });
102
103const MAX_DOWNLOAD_BYTES = 25 * 1024 * 1024;
104
105// The feed omits tool input and output; the app needs both.
106function storedToolCall(
107 item: { readonly type: string; readonly input?: unknown; readonly output?: unknown } | null,
108) {
109 if (item?.type !== "dynamic_tool") return undefined;
110 const output = item.output as { readonly result?: unknown } | undefined;
111 return {
112 arguments: item.input,
113 result: output?.result as McpAppCallToolResult | undefined,
114 };
115}
116
117/** WebViews reload when moved; tear down inline before opening fullscreen and recreate it on return. */
118export function ThreadMcpApp(props: {
119 readonly environmentId: EnvironmentId;
120 readonly threadId: ThreadId;
121 readonly conversationThreadId: ThreadId;
122 readonly itemId: TurnItemId;
123 readonly revision: string;
124 readonly app: McpAppReference;
125 readonly width: number;
126 readonly displayMode?: "inline" | "fullscreen";
127 readonly onExitFullscreen?: () => void;
128 readonly height?: number;
129}) {
130 const gt = useGT();
131 const [height, setHeight] = useState(MCP_APP_INLINE_MAX_HEIGHT);
132 const [documentKey, setDocumentKeyState] = useState(0);
133 // The view keeps its first URL: a re-minted one would reload the app.
134 const [uri, setUri] = useState<string | null>(null);
135 const [loaded, setLoaded] = useState(false);
136 const [navigatedAway, setNavigatedAway] = useState(false);
137 // Equal app content must retain its reference to preserve the live document host.
138 // A different app needs a new document even when its asset URL is unchanged,
139 // so the WebView key moves on with the document key, not only the URL.
140 const [app, setApp] = useState(props.app);
141 if (!mcpAppReferencesEqual(app, props.app)) {
142 setApp(props.app);
143 setHeight(MCP_APP_INLINE_MAX_HEIGHT);
144 setUri(null);
145 setLoaded(false);
146 setNavigatedAway(false);
147 setDocumentKeyState((value) => value + 1);
148 }
149 const fullscreen = props.displayMode === "fullscreen";
150 const navigation = useNavigation();
151 const insets = useSafeAreaInsets();
152 const [closed, setClosed] = useState(false);
153 const [presentedFullscreen, setPresentedFullscreen] = useState(false);
154
155 const { themeId, themeAppearance, themeVariables, systemColorsActive } =
156 useAppearancePreferences();
157 const theme = mobileHtmlRenderTheme({
158 themeId,
159 appearance: themeAppearance,
160 variables: themeVariables,
161 systemColors: systemColorsActive,
162 platform: Platform.OS,
163 });
164 const resource = {
165 _tag: "attachment" as const,
166 attachmentId: app.attachmentId,
167 fileName: mcpAppFileName(app),
168 mimeType: "text/html",
169 disposition: "inline" as const,
170 renderIntent: "mcp-app" as const,
171 };
172 const asset = useAssetUrlState(props.environmentId, resource);
173 if (uri === null && asset._tag === "Success") setUri(asset.url);
174 const [generation, setGeneration] = useState(0);
175 const [crashed, setCrashed] = useState(false);
176 const restart = () => {
177 if (generation > 0) {
178 setCrashed(true);
179 return;
180 }
181 setLoaded(false);
182 setHeight(MCP_APP_INLINE_MAX_HEIGHT);
183 // Use the asset query's refreshed token when creating a replacement view.
184 if (asset._tag === "Success") setUri(asset.url);
185 setGeneration(1);
186 };
187 const [secret] = useState(uuidv4);
188 const reopenDocument = () => {
189 setLoaded(false);
190 setHeight(MCP_APP_INLINE_MAX_HEIGHT);
191 setNavigatedAway(false);
192 if (asset._tag === "Success") setUri(asset.url);
193 setDocumentKeyState((value) => value + 1);
194 };
195 const returnedFromFullscreen = useEffectEvent(() => {
196 reopenDocument();
197 setPresentedFullscreen(false);
198 });
199 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Navigation focus is outside React; listen only while the app is presented full screen, and stop on unmount.
200 useEffect(() => {
201 if (!presentedFullscreen) return;
202 return navigation.addListener("focus", () => returnedFromFullscreen());
203 }, [navigation, presentedFullscreen]);
204
205 const detailAtom = orchestrationEnvironment.turnItem({
206 environmentId: props.environmentId,
207 input: { threadId: props.threadId, itemId: props.itemId, revision: props.revision },
208 });
209 const toolInfo = useEnvironmentQuery(
210 mcpAppEnvironment.toolInfoQuery({
211 environmentId: props.environmentId,
212 input: { threadId: props.threadId, itemId: props.itemId, name: app.tool },
213 }),
214 );
215 const toolDefinition = toolInfo.data?.tool;
216
217 const callTool = useAtomCommand(mcpAppEnvironment.callTool, { reportFailure: false });
218 const toolInfoCommand = useAtomCommand(mcpAppEnvironment.toolInfo, { reportFailure: false });
219 const readResource = useAtomCommand(mcpAppEnvironment.readResource, { reportFailure: false });
220 const updateModelContext = useAtomCommand(mcpAppEnvironment.updateModelContext, {
221 reportFailure: false,
222 });
223 // Read current context per message without rebuilding the host and losing its session.
224 const conversation = useThreadShell(
225 scopeThreadRef(props.environmentId, props.conversationThreadId),
226 );
227 const awaitingUser =
228 conversation?.hasPendingApprovals === true || conversation?.hasPendingUserInput === true;
229 const live = {
230 awaitingUser,
231 theme,
232 props,
233 asset,
234 callTool,
235 toolInfo: toolInfoCommand,
236 readResource,
237 updateModelContext,
238 insets,
239 toolDefinition,
240 navigation,
241 };
242 const latest = useRef(live);
243 // The attached WebView owns its host; state lets the tool-call effect pair
244 // a host only with an atom from a render after that host existed.
245 const [host, setHost] = useState<McpAppHost | null>(null);
246 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- resends host context to the MCP app host after commits that change theme, insets, tool or size
247 useEffect(() => {
248 const previous = latest.current;
249 latest.current = live;
250 // Building the context is not free, so resend only when one of its inputs changed.
251 if (
252 previous.theme !== live.theme ||
253 previous.insets !== live.insets ||
254 previous.toolDefinition !== live.toolDefinition ||
255 previous.props.width !== live.props.width ||
256 previous.props.height !== live.props.height ||
257 previous.props.displayMode !== live.props.displayMode
258 ) {
259 host?.updateHostContext();
260 }
261 });
262 // The host sends the call once the app initializes, so a stored item that
263 // lands late still reaches it. A completed call can arrive under a new
264 // revision, which is a new atom, so the host follows the current one.
265 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes the MCP host to the current tool call
266 useEffect(() => {
267 if (host === null) return;
268 return appAtomRegistry.subscribe(
269 detailAtom,
270 (result) => {
271 const call = AsyncResult.isSuccess(result) ? storedToolCall(result.value.item) : undefined;
272 if (call !== undefined) host.setToolCall(call);
273 },
274 { immediate: true },
275 );
276 }, [host, detailAtom]);
277 const userActive = useRef(false);
278 // Teardown completions check this so a replaced document's late callback is ignored.
279 const currentHost = useRef<McpAppHost | null>(null);
280
281 // Each WebView document gets its own host: the view is keyed by document,
282 // restart generation and URL, and a changed app re-attaches this callback.
283 // Any other identity change would tear the host down, so per-render values
284 // are read through `latest`, never captured.
285 const attachWebView = (view: WebView<object> | null) => {
286 if (view === null) return;
287 const reloadInline = () => {
288 setLoaded(false);
289 setHeight(MCP_APP_INLINE_MAX_HEIGHT);
290 setNavigatedAway(false);
291 const current = latest.current.asset;
292 if (current._tag === "Success") setUri(current.url);
293 setDocumentKeyState((value) => value + 1);
294 };
295 const scope = () => {
296 const { environmentId, threadId, itemId } = latest.current.props;
297 return { environmentId, input: { threadId, itemId } };
298 };
299 const hostContext = (): McpAppHostContext => {
300 const current = latest.current;
301 const isFullscreen = current.props.displayMode === "fullscreen";
302 return {
303 theme: current.theme.appearance,
304 styles: { variables: mcpAppStyleVariables(current.theme.variables) },
305 displayMode: isFullscreen ? "fullscreen" : "inline",
306 availableDisplayModes: ["inline", "fullscreen"],
307 containerDimensions: isFullscreen
308 ? {
309 width: current.props.width,
310 height: current.props.height ?? MCP_APP_INLINE_MAX_HEIGHT,
311 }
312 : { width: current.props.width, maxHeight: MCP_APP_INLINE_MAX_HEIGHT },
313 platform: "mobile",
314 locale: Intl.DateTimeFormat().resolvedOptions().locale,
315 timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
316 userAgent: `t3-code/${Constants.expoConfig?.version ?? "0.0.0"}`,
317 deviceCapabilities: { touch: true, hover: false },
318 safeAreaInsets: isFullscreen
319 ? { top: 0, right: current.insets.right, bottom: 0, left: current.insets.left }
320 : { top: 0, right: 0, bottom: 0, left: 0 },
321 ...(current.toolDefinition === undefined
322 ? {}
323 : { toolInfo: { tool: current.toolDefinition } }),
324 };
325 };
326 const documentHost: McpAppHost = makeMcpAppHost({
327 app,
328 hostVersion: Constants.expoConfig?.version ?? "0.0.0",
329 post: (message) =>
330 view.injectJavaScript(
331 `window.__t3McpAppReceive&&window.__t3McpAppReceive(${JSON.stringify(message)});true;`,
332 ),
333 hostContext,
334 callTool: async ({ name, arguments: args }) => {
335 const { environmentId, input } = scope();
336 const info = await latest.current.toolInfo({ environmentId, input: { ...input, name } });
337 if (info._tag !== "Success") throw commandFailure(info);
338 if (!info.value.callable)
339 throw new McpAppHostRefusal({ message: "This app cannot call that tool." });
340 if (
341 !info.value.readOnly &&
342 !(await confirm(
343 m(
344 msg("Allow {server} to run {tool}?", {
345 server: app.server,
346 tool: info.value.title ?? name,
347 }),
348 ),
349 JSON.stringify(args, null, 2),
350 m(msg("Allow", { $context: "verb, confirm button" })),
351 ))
352 ) {
353 throw new McpAppHostRefusal({ message: "Declined by the user." });
354 }
355 const result = await latest.current.callTool({
356 environmentId,
357 input: { ...input, name, arguments: args },
358 });
359 if (result._tag !== "Success") throw commandFailure(result);
360 return result.value;
361 },
362 readResource: async ({ uri: resourceUri }) => {
363 const { environmentId, input } = scope();
364 const result = await latest.current.readResource({
365 environmentId,
366 input: { ...input, uri: resourceUri },
367 });
368 if (result._tag !== "Success") throw commandFailure(result);
369 return result.value;
370 },
371 openLink: async (url) => {
372 // WebViews cannot prove user activation; confirm links to prevent timer-driven navigation out of T3.
373 if (
374 !(await confirm(
375 m(msg("Open a link from {server}?", { server: app.server })),
376 url,
377 m(msg("Open", { $context: "verb, opens a link" })),
378 ))
379 ) {
380 throw new McpAppHostRefusal({ message: "Declined by the user." });
381 }
382 if (!(await tryOpenExternalUrl(url, "mcp-app"))) {
383 throw new McpAppHostRefusal({ message: "The link could not be opened." });
384 }
385 },
386 sendMessage: async (text) => {
387 if (
388 !(await confirm(
389 m(msg("Send this message from {server}?", { server: app.server })),
390 text,
391 m(msg("Send", { $context: "verb, sends the message" })),
392 ))
393 ) {
394 throw new McpAppHostRefusal({ message: "Declined by the user." });
395 }
396 await enqueueThreadOutboxMessage({
397 environmentId: latest.current.props.environmentId,
398 threadId: latest.current.props.conversationThreadId,
399 messageId: MessageId.make(uuidv4()),
400 commandId: CommandId.make(uuidv4()),
401 text,
402 attachments: [],
403 dispatchMode: "queue",
404 createdAt: new Date().toISOString(),
405 });
406 },
407 updateModelContext: async (context) => {
408 const { environmentId, input } = scope();
409 const result = await latest.current.updateModelContext({
410 environmentId,
411 input: {
412 ...input,
413 ...context,
414 conversationThreadId: latest.current.props.conversationThreadId,
415 },
416 });
417 if (result._tag !== "Success") throw commandFailure(result);
418 },
419 requestDisplayMode: async (mode) => {
420 const current = latest.current.props;
421 // receive dispatches synchronously; read activation before awaiting teardown.
422 if (
423 mode === "fullscreen" &&
424 (!userActive.current ||
425 latest.current.awaitingUser ||
426 !latest.current.navigation.isFocused())
427 ) {
428 return current.displayMode ?? "inline";
429 }
430 if (mode === "fullscreen" && current.displayMode !== "fullscreen") {
431 await documentHost.teardown();
432 // A crash restart or reload during the wait already replaced this document.
433 if (currentHost.current !== documentHost) return "inline";
434 // Approval arrival or navigation during the wait requires reloading inline.
435 const navigation = latest.current.navigation;
436 if (latest.current.awaitingUser || !navigation.isFocused()) {
437 reloadInline();
438 return "inline";
439 }
440 setPresentedFullscreen(true);
441 navigation.navigate("ThreadMcpApp", {
442 environmentId: String(current.environmentId),
443 threadId: String(current.threadId),
444 conversationThreadId: String(current.conversationThreadId),
445 itemId: String(current.itemId),
446 revision: current.revision,
447 });
448 return "fullscreen";
449 }
450 if (mode === "inline" && current.displayMode === "fullscreen") {
451 await documentHost.teardown();
452 if (currentHost.current === documentHost) current.onExitFullscreen?.();
453 return "inline";
454 }
455 return current.displayMode ?? "inline";
456 },
457 downloadFile: async (files) => {
458 const names = files.map((file) => file.name).join(", ");
459 if (
460 !(await confirm(
461 m(msg("Save a file from {server}?", { server: app.server })),
462 names,
463 m(msg("Save", { $context: "verb, confirm button" })),
464 ))
465 ) {
466 throw new McpAppHostRefusal({ message: "Declined by the user." });
467 }
468 for (const file of files) {
469 let bytes: Uint8Array | undefined;
470 let mimeType = file.mimeType ?? "application/octet-stream";
471 if (file._tag === "embedded") {
472 bytes = file.bytes;
473 } else {
474 const { environmentId, input } = scope();
475 const read = await latest.current.readResource({
476 environmentId,
477 input: { ...input, uri: file.uri },
478 });
479 if (read._tag !== "Success") throw commandFailure(read);
480 const content = read.value.contents[0];
481 bytes = mcpResourceBytes(content);
482 const declared = (content as { readonly mimeType?: unknown } | undefined)?.mimeType;
483 if (typeof declared === "string") mimeType = declared;
484 }
485 if (bytes === undefined)
486 throw new McpAppHostRefusal({ message: `${file.name} has no contents.` });
487 if (bytes.byteLength > MAX_DOWNLOAD_BYTES) {
488 throw new McpAppHostRefusal({ message: `${file.name} is too large to save.` });
489 }
490 const shared = await shareGeneratedAttachment({
491 bytes,
492 attachment: { name: file.name, mimeType },
493 signal: new AbortController().signal,
494 });
495 if (!shared)
496 throw new McpAppHostRefusal({ message: "Sharing is not available on this device." });
497 }
498 },
499 onRequestTeardown: () => {
500 const current = latest.current.props;
501 void documentHost.teardown().then(() => {
502 if (currentHost.current !== documentHost) return;
503 if (current.displayMode === "fullscreen") current.onExitFullscreen?.();
504 else setClosed(true);
505 });
506 },
507 onSizeChanged: (size) => {
508 if (latest.current.props.displayMode === "fullscreen") return;
509 const nextHeight = mcpAppInlineHeight(size.height);
510 if (nextHeight !== undefined) setHeight(nextHeight);
511 },
512 });
513 setHost(documentHost);
514 currentHost.current = documentHost;
515 return () => {
516 if (currentHost.current === documentHost) currentHost.current = null;
517 // An unmount cannot wait: the request goes out before the view does.
518 void documentHost.teardown();
519 setHost((current) => (current === documentHost ? null : current));
520 };
521 };
522
523 const source =
524 uri === null
525 ? null
526 : { html: outerDocument(uri, mcpAppAllowAttribute(app.permissions), secret) };
527
528 if (presentedFullscreen) {
529 return (
530 <View
531 style={{ height, marginBottom: ROW_BOTTOM_MARGIN }}
532 className="items-center justify-center rounded-lg border border-border"
533 >
534 <Text className="text-sm text-foreground-muted">
535 <T>
536 The <Var>{app.server}</Var> app is open full screen
537 </T>
538 </Text>
539 </View>
540 );
541 }
542
543 if (closed) {
544 return (
545 <View
546 style={{ height, marginBottom: ROW_BOTTOM_MARGIN }}
547 className="items-center justify-center gap-2 rounded-lg border border-border"
548 >
549 <Text className="text-sm text-foreground-muted">
550 <T>
551 The <Var>{app.server}</Var> app was closed
552 </T>
553 </Text>
554 <View className="items-center">
555 <Button
556 label={gt("Show app")}
557 tone="secondary"
558 onPress={() => {
559 reopenDocument();
560 setClosed(false);
561 }}
562 />
563 </View>
564 </View>
565 );
566 }
567
568 return (
569 <View style={fullscreen ? { flex: 1 } : { height, marginBottom: ROW_BOTTOM_MARGIN }}>
570 {navigatedAway ? (
571 <View className="flex-1 items-center justify-center">
572 <Text className="text-sm text-foreground-muted">
573 <T>
574 The <Var>{app.server}</Var> app left its page and was stopped
575 </T>
576 </Text>
577 </View>
578 ) : uri !== null && !crashed ? (
579 <WebView<object>
580 key={`${documentKey}:${generation}:${uri}`}
581 ref={attachWebView}
582 onContentProcessDidTerminate={restart}
583 onRenderProcessGone={restart}
584 source={source!}
585 accessibilityLabel={gt("{server} app", { server: app.server })}
586 style={{ flex: 1, backgroundColor: "transparent" }}
587 nestedScrollEnabled
588 decelerationRate={webViewDecelerationRate}
589 originWhitelist={["*"]}
590 // Android misreports nested frames as top-level; rely on iframe sandboxing there and gate navigation elsewhere.
591 onShouldStartLoadWithRequest={(request) =>
592 Platform.OS === "android" ||
593 request.isTopFrame === false ||
594 request.url === "about:blank"
595 }
596 setSupportMultipleWindows={false}
597 onLoadEnd={() => setLoaded(true)}
598 onError={() => setCrashed(true)}
599 onHttpError={() => setCrashed(true)}
600 onMessage={(event: WebViewMessageEvent) => {
601 let envelope: unknown;
602 try {
603 envelope = JSON.parse(event.nativeEvent.data);
604 } catch {
605 return;
606 }
607 if (!Predicate.isObject(envelope) || envelope.secret !== secret) return;
608 const message = envelope.message;
609 if (Predicate.isObject(message) && message.t3 === "navigated") {
610 host?.dispose();
611 setNavigatedAway(true);
612 return;
613 }
614 userActive.current = envelope.active === true;
615 host?.receive(message);
616 userActive.current = false;
617 }}
618 />
619 ) : asset._tag === "Failure" || crashed ? (
620 <View className="flex-1 items-center justify-center">
621 <Text className="text-sm text-foreground-muted">
622 <T>
623 Unable to load the <Var>{app.server}</Var> app
624 </T>
625 </Text>
626 </View>
627 ) : null}
628 {uri !== null && !loaded && !crashed && !navigatedAway ? (
629 <View pointerEvents="none" className="absolute inset-0 items-center justify-center">
630 <AppActivityIndicator />
631 </View>
632 ) : null}
633 </View>
634 );
635}