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