Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

McpAppWebView.tsx

611 lines25.8 KB

1import type { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";
2import {
3 makeMcpAppHost,
4 McpAppHostRefusal,
5 mcpAppStyleVariables,
6 mcpResourceBytes,
7 type McpAppCallToolResult,
8 type McpAppHost,
9 type McpAppHostContext,
10} from "@t3tools/client-runtime/mcp-apps";
11import { scopeThreadRef } from "@t3tools/client-runtime/environment";
12import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
13import { CommandId, MessageId } from "@t3tools/contracts";
14import {
15 mcpAppAllowAttribute,
16 mcpAppFileName,
17 mcpAppReferencesEqual,
18 type McpAppReference,
19} from "@t3tools/shared/mcpApp";
20import * as Predicate from "effect/Predicate";
21import Constants from "expo-constants";
22import { useNavigation } from "@react-navigation/native";
23import { useEffect, useMemo, useRef, useState } from "react";
24import { ActivityIndicator, Alert, Platform, Pressable, View } from "react-native";
25import { useSafeAreaInsets } from "react-native-safe-area-context";
26import { WebView, type WebViewMessageEvent } from "react-native-webview";
27​
28import { AppText as Text } from "../../components/AppText";
29import { shareGeneratedAttachment } from "../../lib/attachmentDownload";
30import { mobileHtmlRenderTheme } from "../../lib/htmlRenderTheme";
31import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
32import { uuidv4 } from "../../lib/uuid";
33import { useAssetUrlState } from "../../state/assets";
34import { useThreadShell } from "../../state/entities";
35import { mcpAppEnvironment } from "../../state/mcpApps";
36import { orchestrationEnvironment } from "../../state/orchestration";
37import { useEnvironmentQuery } from "../../state/query";
38import { enqueueThreadOutboxMessage } from "../../state/thread-outbox";
39import { useAtomCommand } from "../../state/use-atom-command";
40import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
41​
42/** The feed reserves a fixed box for an app; a taller app scrolls inside it. */
43const MCP_APP_ROW_HEIGHT = 420;
44const ROW_BOTTOM_MARGIN = 8;
45​
46export function mcpAppRowHeight() {
47 return MCP_APP_ROW_HEIGHT + ROW_BOTTOM_MARGIN;
49​
50// The WebView loads a tiny outer page that hosts the app in a real
51// opaque-origin iframe, as web does, so the app's `window.parent` and the
52// `event.source` of host replies are a real window, which the MCP Apps SDK
53// requires. The outer page only relays: app → React Native, and host
54// replies (injected as `__t3McpAppReceive(...)`) → app.
55//
56// Android exposes `ReactNativeWebView` to every frame, so a frame nested in
57// the app could post to React Native directly. The outer page therefore wraps
58// what it relays with a secret only it holds, and React Native drops anything
59// else. The bridge belongs to the captured document: once the app frame loads
60// a second time (it navigated itself), the outer page stops relaying and says
61// so, rather than letting a page T3 never served pose as the app. This is not
62// a confidentiality boundary: a frame can always navigate itself, so the app
63// could carry anything it read out in a URL either way.
64function outerDocument(src: string, allow: string, secret: string) {
65 const attribute = (value: string) =>
66 value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
67 return `<!doctype html><html><head><meta name="viewport" content="width=device-width, initial-scale=1">
68<style>html,body{margin:0;height:100%;background:transparent}iframe{border:0;display:block;width:100%;height:100%}</style></head>
69<body><iframe id="app" sandbox="allow-scripts allow-forms" allow="${attribute(allow)}"></iframe>
70<script>(function(){var frame=document.getElementById("app"),secret=${JSON.stringify(secret)},loads=0,live=true;
71var send=function(m){window.ReactNativeWebView.postMessage(JSON.stringify({secret:secret,message:m}));};
72frame.addEventListener("load",function(){loads+=1;if(loads>1&&live){live=false;send({t3:"navigated"});}});
73window.addEventListener("message",function(e){if(live&&e.source===frame.contentWindow)send(e.data);});
74window.__t3McpAppReceive=function(m){live&&frame.contentWindow&&frame.contentWindow.postMessage(m,"*");};
75frame.src=${JSON.stringify(src).replace(/</g, "\\u003c")};})();</script></body></html>`;
77​
78const commandFailure = (result: {
79 readonly cause: Parameters<typeof squashAtomCommandFailure>[0]["cause"];
80}) => {
81 const error = squashAtomCommandFailure(result);
82 return new McpAppHostRefusal(
83 error instanceof Error && error.message.trim() !== "" ? error.message : "Request failed.",
84 );
85};
86​
87const confirm = (title: string, message: string, action: string) =>
88 new Promise<boolean>((resolve) => {
89 Alert.alert(
90 title,
91 message,
92 [
93 { text: "Cancel", style: "cancel", onPress: () => resolve(false) },
94 { text: action, onPress: () => resolve(true) },
95 ],
96 // Android dismisses an open alert when the next one shows; a dismissed
97 // request is declined rather than left holding an in-flight slot.
98 { cancelable: true, onDismiss: () => resolve(false) },
99 );
100 });
101​
102/** Largest file an app may hand the user through `ui/download-file`. */
103const MAX_DOWNLOAD_BYTES = 25 * 1024 * 1024;
104​
105/**
106 * A captured MCP App, hosted in a WebView over the MCP Apps bridge: inline as
107 * a fixed row of the thread feed, or full screen in its own modal screen. A
108 * WebView cannot move between the two without reloading, so each is its own
109 * view of the app: the inline one is torn down before full screen opens, and
110 * comes back when it closes.
111 */
112export function ThreadMcpApp(props: {
113 readonly environmentId: EnvironmentId;
114 /** The thread that produced the app, which its requests run against. */
115 readonly threadId: ThreadId;
116 /** The thread on screen, which approved app messages are sent to. */
117 readonly conversationThreadId: ThreadId;
118 readonly itemId: TurnItemId;
119 readonly revision: string;
120 readonly app: McpAppReference;
121 readonly width: number;
122 /** Full screen fills its screen; inline is the feed's fixed row. */
123 readonly displayMode?: "inline" | "fullscreen";
124 /** Full screen only: leaves it, back to the inline row. */
125 readonly onExitFullscreen?: () => void;
126 /** Full screen only: the screen's height, which the app is told it fills. */
127 readonly height?: number;
128}) {
129 // One reference per app: a new object with the same content (a refetch, a
130 // rerender) must not rebuild the host of a document that is already live.
131 const [app, setApp] = useState(props.app);
132 if (!mcpAppReferencesEqual(app, props.app)) setApp(props.app);
133 const fullscreen = props.displayMode === "fullscreen";
134 const navigation = useNavigation();
135 const insets = useSafeAreaInsets();
136 // The app asked to be closed; the row falls back to a note that brings it back.
137 const [closed, setClosed] = useState(false);
138 // Full screen is a separate view of the app, so the inline one steps aside
139 // (and is torn down) while it is open, and comes back when the thread is
140 // shown again.
141 const [presentedFullscreen, setPresentedFullscreen] = useState(false);
142 // Counts the documents this row has shown on purpose (back from full screen,
143 // or reopened after closing); each gets its own view and host.
144 const [documentKey, setDocumentKeyState] = useState(0);
145​
146 const { themeId, themeAppearance, themeVariables, systemColorsActive } =
147 useAppearancePreferences();
148 const theme = useMemo(
149 () =>
150 mobileHtmlRenderTheme({
151 themeId,
152 appearance: themeAppearance,
153 variables: themeVariables,
154 systemColors: systemColorsActive,
155 platform: Platform.OS,
156 }),
157 [themeId, themeAppearance, themeVariables, systemColorsActive],
158 );
159 const resource = useMemo(
160 () => ({
161 _tag: "attachment" as const,
162 attachmentId: app.attachmentId,
163 fileName: mcpAppFileName(app),
164 mimeType: "text/html",
165 disposition: "inline" as const,
166 }),
167 [app],
168 );
169 const asset = useAssetUrlState(props.environmentId, resource);
170 // The view keeps its first URL: a re-minted one would reload the app.
171 const [uri, setUri] = useState<string | null>(null);
172 if (uri === null && asset._tag === "Success") setUri(asset.url);
173 const [loaded, setLoaded] = useState(false);
174 const [navigatedAway, setNavigatedAway] = useState(false);
175 // Bumped when the OS reclaims the web process: a fresh view, document and
176 // host, so the reloaded app is initialized and replayed again. Once only, so
177 // an app that keeps crashing its process is not reloaded forever.
178 const [generation, setGeneration] = useState(0);
179 const [crashed, setCrashed] = useState(false);
180 const restart = () => {
181 if (generation > 0) {
182 setCrashed(true);
183 return;
184 }
185 setLoaded(false);
186 // The first URL's token may have expired by now; the asset query keeps
187 // a refreshed one, which this new view can load.
188 if (asset._tag === "Success") setUri(asset.url);
189 setGeneration(1);
190 };
191 // Minted per view, so only this view's outer page can speak for its app.
192 const [secret] = useState(uuidv4);
193 // A new document starts loading, is not yet one that navigated away, and
194 // loads the asset query's current URL: the first one's token may be gone.
195 const setDocumentKey = (next: (value: number) => number) => {
196 setLoaded(false);
197 setNavigatedAway(false);
198 if (asset._tag === "Success") setUri(asset.url);
199 setDocumentKeyState(next);
200 };
201 // Back from full screen: the thread shows a fresh inline view of the app.
202 // The listener reads the latest helper, whose URL comes from this render.
203 const openNewDocument = useRef(setDocumentKey);
204 useEffect(() => {
205 openNewDocument.current = setDocumentKey;
206 });
207 useEffect(() => {
208 if (!presentedFullscreen) return;
209 return navigation.addListener("focus", () => {
210 openNewDocument.current((value) => value + 1);
211 setPresentedFullscreen(false);
212 });
213 }, [navigation, presentedFullscreen]);
214​
215 // The feed omits tool input and output; the app needs both.
216 const detail = useEnvironmentQuery(
217 orchestrationEnvironment.turnItem({
218 environmentId: props.environmentId,
219 input: { threadId: props.threadId, itemId: props.itemId, revision: props.revision },
220 }),
221 );
222 const storedItem = detail.data?.item;
223 const toolCall = useMemo(() => {
224 if (storedItem?.type !== "dynamic_tool") return undefined;
225 const output = storedItem.output as { readonly result?: unknown } | undefined;
226 return {
227 arguments: storedItem.input,
228 result: output?.result as McpAppCallToolResult | undefined,
229 };
230 }, [storedItem]);
231​
232 const callTool = useAtomCommand(mcpAppEnvironment.callTool, { reportFailure: false });
233 const toolInfo = useAtomCommand(mcpAppEnvironment.toolInfo, { reportFailure: false });
234 const readResource = useAtomCommand(mcpAppEnvironment.readResource, { reportFailure: false });
235 const updateModelContext = useAtomCommand(mcpAppEnvironment.updateModelContext, {
236 reportFailure: false,
237 });
238 // The tool's definition, which the app receives as `toolInfo` at initialize.
239 const [toolDefinition, setToolDefinition] = useState<unknown>(undefined);
240 // Read by the host on every message, so it always sees current values
241 // without being rebuilt (which would drop the app's session).
242 // The approval or question the agent waits on renders on this thread, and a
243 // full-screen app would cover it.
244 const conversation = useThreadShell(
245 scopeThreadRef(props.environmentId, props.conversationThreadId),
246 );
247 const awaitingUser =
248 conversation?.hasPendingApprovals === true || conversation?.hasPendingUserInput === true;
249 const live = {
250 awaitingUser,
251 theme,
252 props,
253 callTool,
254 toolInfo,
255 readResource,
256 updateModelContext,
257 insets,
258 toolDefinition,
259 navigation,
260 };
261 const latest = useRef(live);
262 useEffect(() => {
263 latest.current = live;
264 });
265 useEffect(() => {
266 let cancelled = false;
267 void latest.current
268 .toolInfo({
269 environmentId: props.environmentId,
270 input: { threadId: props.threadId, itemId: props.itemId, name: app.tool },
271 })
272 .then((info) => {
273 if (!cancelled && info._tag === "Success" && info.value.tool !== undefined) {
274 setToolDefinition(info.value.tool);
275 }
276 });
277 return () => {
278 cancelled = true;
279 };
280 }, [props.environmentId, props.threadId, props.itemId, app.tool]);
281 const webView = useRef<WebView<object>>(null);
282 const hostRef = useRef<McpAppHost | null>(null);
283​
284 // One host per loaded document.
285 useEffect(() => {
286 if (uri === null) return;
287 const scope = () => {
288 const { environmentId, threadId, itemId } = latest.current.props;
289 return { environmentId, input: { threadId, itemId } };
290 };
291 const hostContext = (): McpAppHostContext => {
292 const current = latest.current;
293 const isFullscreen = current.props.displayMode === "fullscreen";
294 return {
295 theme: current.theme.appearance,
296 styles: { variables: mcpAppStyleVariables(current.theme.variables) },
297 displayMode: isFullscreen ? "fullscreen" : "inline",
298 availableDisplayModes: ["inline", "fullscreen"],
299 // Both are fixed boxes, so the app is told its exact size.
300 containerDimensions: {
301 width: current.props.width,
302 height: isFullscreen ? (current.props.height ?? MCP_APP_ROW_HEIGHT) : MCP_APP_ROW_HEIGHT,
303 },
304 platform: "mobile",
305 locale: Intl.DateTimeFormat().resolvedOptions().locale,
306 timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
307 userAgent: `t3-code/${Constants.expoConfig?.version ?? "0.0.0"}`,
308 deviceCapabilities: { touch: true, hover: false },
309 // The full-screen modal keeps the top and bottom insets for its
310 // header and the home indicator; only the sides reach the app.
311 safeAreaInsets: isFullscreen
312 ? { top: 0, right: current.insets.right, bottom: 0, left: current.insets.left }
313 : { top: 0, right: 0, bottom: 0, left: 0 },
314 ...(current.toolDefinition === undefined
315 ? {}
316 : { toolInfo: { tool: current.toolDefinition } }),
317 };
318 };
319 const next = makeMcpAppHost({
320 app,
321 hostVersion: Constants.expoConfig?.version ?? "0.0.0",
322 post: (message) =>
323 webView.current?.injectJavaScript(
324 `window.__t3McpAppReceive&&window.__t3McpAppReceive(${JSON.stringify(message)});true;`,
325 ),
326 hostContext,
327 callTool: async ({ name, arguments: args }) => {
328 const { environmentId, input } = scope();
329 const info = await latest.current.toolInfo({ environmentId, input: { ...input, name } });
330 if (info._tag !== "Success") throw commandFailure(info);
331 if (!info.value.callable) throw new McpAppHostRefusal("This app cannot call that tool.");
332 if (
333 !info.value.readOnly &&
334 !(await confirm(
335 `Allow ${app.server} to run ${info.value.title ?? name}?`,
336 JSON.stringify(args, null, 2),
337 "Allow",
338 ))
339 ) {
340 throw new McpAppHostRefusal("Declined by the user.");
341 }
342 const result = await latest.current.callTool({
343 environmentId,
344 input: { ...input, name, arguments: args },
345 });
346 if (result._tag !== "Success") throw commandFailure(result);
347 return result.value;
348 },
349 readResource: async ({ uri: resourceUri }) => {
350 const { environmentId, input } = scope();
351 const result = await latest.current.readResource({
352 environmentId,
353 input: { ...input, uri: resourceUri },
354 });
355 if (result._tag !== "Success") throw commandFailure(result);
356 return result.value;
357 },
358 openLink: async (url) => {
359 // A WebView cannot tell whether the reader just tapped the app, so it
360 // asks, rather than letting an app leave T3 on a timer.
361 if (!(await confirm(`Open a link from ${app.server}?`, url, "Open"))) {
362 throw new McpAppHostRefusal("Declined by the user.");
363 }
364 if (!(await tryOpenExternalUrl(url, "mcp-app"))) {
365 throw new McpAppHostRefusal("The link could not be opened.");
366 }
367 },
368 sendMessage: async (text) => {
369 if (!(await confirm(`Send this message from ${app.server}?`, text, "Send"))) {
370 throw new McpAppHostRefusal("Declined by the user.");
371 }
372 // Through the outbox like a typed message, so it survives a dropped
373 // connection; the thread's own settings fill in when it sends.
374 await enqueueThreadOutboxMessage({
375 environmentId: latest.current.props.environmentId,
376 threadId: latest.current.props.conversationThreadId,
377 messageId: MessageId.make(uuidv4()),
378 commandId: CommandId.make(uuidv4()),
379 text,
380 attachments: [],
381 dispatchMode: "queue",
382 createdAt: new Date().toISOString(),
383 });
384 },
385 updateModelContext: async (context) => {
386 const { environmentId, input } = scope();
387 const result = await latest.current.updateModelContext({
388 environmentId,
389 input: {
390 ...input,
391 ...context,
392 conversationThreadId: latest.current.props.conversationThreadId,
393 },
394 });
395 if (result._tag !== "Success") throw commandFailure(result);
396 },
397 requestDisplayMode: async (mode) => {
398 const current = latest.current.props;
399 // Full screen would cover the approval or question the agent waits
400 // on, or a screen the user moved to.
401 if (
402 mode === "fullscreen" &&
403 (latest.current.awaitingUser || !latest.current.navigation.isFocused())
404 ) {
405 return current.displayMode ?? "inline";
406 }
407 if (mode === "fullscreen" && current.displayMode !== "fullscreen") {
408 // The inline view is torn down by the switch (this row unmounts
409 // while the modal covers it); the modal opens a fresh view.
410 // The inline view steps aside for the modal; it gets its teardown first.
411 await hostRef.current?.teardown();
412 // The wait may have let an approval arrive, or the user moved to
413 // another screen; either way the view reloads inline.
414 if (latest.current.awaitingUser || !latest.current.navigation.isFocused()) {
415 openNewDocument.current((value) => value + 1);
416 return "inline";
417 }
418 setPresentedFullscreen(true);
419 latest.current.navigation.navigate("ThreadMcpApp", {
420 environmentId: String(current.environmentId),
421 threadId: String(current.threadId),
422 conversationThreadId: String(current.conversationThreadId),
423 itemId: String(current.itemId),
424 revision: current.revision,
425 });
426 return "fullscreen";
427 }
428 if (mode === "inline" && current.displayMode === "fullscreen") {
429 await hostRef.current?.teardown();
430 current.onExitFullscreen?.();
431 return "inline";
432 }
433 return current.displayMode ?? "inline";
434 },
435 downloadFile: async (files) => {
436 const names = files.map((file) => file.name).join(", ");
437 if (!(await confirm(`Save a file from ${app.server}?`, names, "Save"))) {
438 throw new McpAppHostRefusal("Declined by the user.");
439 }
440 for (const file of files) {
441 // A linked file is read from the app's own server, like its other reads.
442 let bytes: Uint8Array | undefined;
443 let mimeType = file.mimeType ?? "application/octet-stream";
444 if (file._tag === "embedded") {
445 bytes = file.bytes;
446 } else {
447 const { environmentId, input } = scope();
448 const read = await latest.current.readResource({
449 environmentId,
450 input: { ...input, uri: file.uri },
451 });
452 if (read._tag !== "Success") throw commandFailure(read);
453 const content = read.value.contents[0];
454 bytes = mcpResourceBytes(content);
455 const declared = (content as { readonly mimeType?: unknown } | undefined)?.mimeType;
456 if (typeof declared === "string") mimeType = declared;
457 }
458 if (bytes === undefined) throw new McpAppHostRefusal(`${file.name} has no contents.`);
459 if (bytes.byteLength > MAX_DOWNLOAD_BYTES) {
460 throw new McpAppHostRefusal(`${file.name} is too large to save.`);
461 }
462 const shared = await shareGeneratedAttachment({
463 bytes,
464 attachment: { name: file.name, mimeType },
465 signal: new AbortController().signal,
466 });
467 if (!shared) throw new McpAppHostRefusal("Sharing is not available on this device.");
468 }
469 },
470 onRequestTeardown: () => {
471 const current = latest.current.props;
472 if (current.displayMode === "fullscreen") {
473 void hostRef.current?.teardown().then(() => current.onExitFullscreen?.());
474 } else {
475 void hostRef.current?.teardown().then(() => setClosed(true));
476 }
477 },
478 // Both modes are fixed boxes, so the app's own height only decides
479 // whether it scrolls inside one.
480 onSizeChanged: () => undefined,
481 });
482 hostRef.current = next;
483 return () => {
484 // An unmount cannot wait: the request goes out before the view does.
485 void next.teardown();
486 hostRef.current = null;
487 };
488 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A restarted view needs a new host.
489 }, [uri, app, generation, documentKey]);
490​
491 // The host reads the context through `latest`; these only say when to resend.
492 useEffect(() => {
493 hostRef.current?.updateHostContext();
494 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Context changes trigger a resend.
495 }, [theme, props.width, props.height, insets, toolDefinition]);
496 // A new document gets a new host, which needs the call again.
497 useEffect(() => {
498 if (toolCall !== undefined) hostRef.current?.setToolCall(toolCall);
499 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Each new document needs the call.
500 }, [toolCall, uri, generation, documentKey]);
501​
502 const source = useMemo(
503 () =>
504 uri === null
505 ? null
506 : { html: outerDocument(uri, mcpAppAllowAttribute(app.permissions), secret) },
507 [uri, app.permissions, secret],
508 );
509​
510 if (presentedFullscreen) {
511 return (
512 <View
513 style={{ height: MCP_APP_ROW_HEIGHT, marginBottom: ROW_BOTTOM_MARGIN }}
514 className="items-center justify-center rounded-lg border border-border"
515 >
516 <Text className="text-sm text-foreground-muted">
517 The {app.server} app is open full screen
518 </Text>
519 </View>
520 );
521 }
522​
523 if (closed) {
524 return (
525 <View
526 style={{ height: MCP_APP_ROW_HEIGHT, marginBottom: ROW_BOTTOM_MARGIN }}
527 className="items-center justify-center gap-2 rounded-lg border border-border"
528 >
529 <Text className="text-sm text-foreground-muted">The {app.server} app was closed</Text>
530 <Pressable
531 accessibilityRole="button"
532 onPress={() => {
533 setDocumentKey((value) => value + 1);
534 setClosed(false);
535 }}
536 >
537 <Text className="text-sm text-foreground">Show app</Text>
538 </Pressable>
539 </View>
540 );
541 }
542​
543 return (
544 <View
545 style={
546 fullscreen ? { flex: 1 } : { height: MCP_APP_ROW_HEIGHT, marginBottom: ROW_BOTTOM_MARGIN }
547 }
548 >
549 {navigatedAway ? (
550 <View className="flex-1 items-center justify-center">
551 <Text className="text-sm text-foreground-muted">
552 The {app.server} app left its page and was stopped
553 </Text>
554 </View>
555 ) : uri !== null && !crashed ? (
556 <WebView<object>
557 key={`${documentKey}:${generation}`}
558 ref={webView}
559 onContentProcessDidTerminate={restart}
560 onRenderProcessGone={restart}
561 source={source!}
562 accessibilityLabel={`${app.server} app`}
563 style={{ flex: 1, backgroundColor: "transparent" }}
564 nestedScrollEnabled
565 originWhitelist={["*"]}
566 // Only the outer page loads at the top; the app opens links through
567 // the bridge. Android reports every navigation as top-frame, frames
568 // the app nests included, so it has no gate to apply: there the
569 // outer page never navigates, and the app frame's sandbox already
570 // forbids top navigation and popups.
571 onShouldStartLoadWithRequest={(request) =>
572 Platform.OS === "android" ||
573 request.isTopFrame === false ||
574 request.url === "about:blank"
575 }
576 setSupportMultipleWindows={false}
577 onLoadEnd={() => setLoaded(true)}
578 // The outer page is inline HTML, so these report a broken view, not
579 // an app page; the row shows the failure instead of a blank box.
580 onError={() => setCrashed(true)}
581 onHttpError={() => setCrashed(true)}
582 onMessage={(event: WebViewMessageEvent) => {
583 let envelope: unknown;
584 try {
585 envelope = JSON.parse(event.nativeEvent.data);
586 } catch {
587 return; // Not JSON: not a bridge message.
588 }
589 if (!Predicate.isObject(envelope) || envelope.secret !== secret) return;
590 const message = envelope.message;
591 if (Predicate.isObject(message) && message.t3 === "navigated") {
592 hostRef.current?.dispose();
593 setNavigatedAway(true);
594 return;
595 }
596 hostRef.current?.receive(message);
597 }}
598 />
599 ) : asset._tag === "Failure" || crashed ? (
600 <View className="flex-1 items-center justify-center">
601 <Text className="text-sm text-foreground-muted">Unable to load the {app.server} app</Text>
602 </View>
603 ) : null}
604 {uri !== null && !loaded && !crashed && !navigatedAway ? (
605 <View pointerEvents="none" className="absolute inset-0 items-center justify-center">
606 <ActivityIndicator />
607 </View>
608 ) : null}
609 </View>
610 );