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