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