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

McpAppWebView.tsx

614 lines26.0 KB

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