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 an open alert when the next one shows; a dismissed
85 // request is declined rather than left holding an in-flight slot.
86 { cancelable: true, onDismiss: () => resolve(false) },
87 );
88 });
89
90const MAX_DOWNLOAD_BYTES = 25 * 1024 * 1024;
91
92/**
93 * A WebView cannot move between the two without reloading, so each is its own
94 * view of the app: the inline one is torn down before full screen opens, and
95 * comes back when it closes.
96 */
97export function ThreadMcpApp(props: {
98 readonly environmentId: EnvironmentId;
99 readonly threadId: ThreadId;
100 readonly conversationThreadId: ThreadId;
101 readonly itemId: TurnItemId;
102 readonly revision: string;
103 readonly app: McpAppReference;
104 readonly width: number;
105 readonly displayMode?: "inline" | "fullscreen";
106 readonly onExitFullscreen?: () => void;
107 readonly height?: number;
108}) {
109 // One reference per app: a new object with the same content (a refetch, a
110 // rerender) must not rebuild the host of a document that is already live.
111 const [height, setHeight] = useState(MCP_APP_INLINE_MAX_HEIGHT);
112 const [app, setApp] = useState(props.app);
113 if (!mcpAppReferencesEqual(app, props.app)) {
114 setApp(props.app);
115 setHeight(MCP_APP_INLINE_MAX_HEIGHT);
116 }
117 const fullscreen = props.displayMode === "fullscreen";
118 const navigation = useNavigation();
119 const insets = useSafeAreaInsets();
120 const [closed, setClosed] = useState(false);
121 const [presentedFullscreen, setPresentedFullscreen] = useState(false);
122 const [documentKey, setDocumentKeyState] = useState(0);
123
124 const { themeId, themeAppearance, themeVariables, systemColorsActive } =
125 useAppearancePreferences();
126 const theme = useMemo(
127 () =>
128 mobileHtmlRenderTheme({
129 themeId,
130 appearance: themeAppearance,
131 variables: themeVariables,
132 systemColors: systemColorsActive,
133 platform: Platform.OS,
134 }),
135 [themeId, themeAppearance, themeVariables, systemColorsActive],
136 );
137 const resource = useMemo(
138 () => ({
139 _tag: "attachment" as const,
140 attachmentId: app.attachmentId,
141 fileName: mcpAppFileName(app),
142 mimeType: "text/html",
143 disposition: "inline" as const,
144 renderIntent: "mcp-app" as const,
145 }),
146 [app],
147 );
148 const asset = useAssetUrlState(props.environmentId, resource);
149 // The view keeps its first URL: a re-minted one would reload the app.
150 const [uri, setUri] = useState<string | null>(null);
151 if (uri === null && asset._tag === "Success") setUri(asset.url);
152 const [loaded, setLoaded] = useState(false);
153 const [navigatedAway, setNavigatedAway] = useState(false);
154 const [generation, setGeneration] = useState(0);
155 const [crashed, setCrashed] = useState(false);
156 const restart = () => {
157 if (generation > 0) {
158 setCrashed(true);
159 return;
160 }
161 setLoaded(false);
162 setHeight(MCP_APP_INLINE_MAX_HEIGHT);
163 // The first URL's token may have expired by now; the asset query keeps
164 // a refreshed one, which this new view can load.
165 if (asset._tag === "Success") setUri(asset.url);
166 setGeneration(1);
167 };
168 const [secret] = useState(uuidv4);
169 const setDocumentKey = (next: (value: number) => number) => {
170 setLoaded(false);
171 setHeight(MCP_APP_INLINE_MAX_HEIGHT);
172 setNavigatedAway(false);
173 if (asset._tag === "Success") setUri(asset.url);
174 setDocumentKeyState(next);
175 };
176 const openNewDocument = useRef(setDocumentKey);
177 useEffect(() => {
178 openNewDocument.current = setDocumentKey;
179 });
180 useEffect(() => {
181 if (!presentedFullscreen) return;
182 return navigation.addListener("focus", () => {
183 openNewDocument.current((value) => value + 1);
184 setPresentedFullscreen(false);
185 });
186 }, [navigation, presentedFullscreen]);
187
188 // The feed omits tool input and output; the app needs both.
189 const detail = useEnvironmentQuery(
190 orchestrationEnvironment.turnItem({
191 environmentId: props.environmentId,
192 input: { threadId: props.threadId, itemId: props.itemId, revision: props.revision },
193 }),
194 );
195 const storedItem = detail.data?.item;
196 const toolCall = useMemo(() => {
197 if (storedItem?.type !== "dynamic_tool") return undefined;
198 const output = storedItem.output as { readonly result?: unknown } | undefined;
199 return {
200 arguments: storedItem.input,
201 result: output?.result as McpAppCallToolResult | undefined,
202 };
203 }, [storedItem]);
204
205 const callTool = useAtomCommand(mcpAppEnvironment.callTool, { reportFailure: false });
206 const toolInfo = useAtomCommand(mcpAppEnvironment.toolInfo, { reportFailure: false });
207 const readResource = useAtomCommand(mcpAppEnvironment.readResource, { reportFailure: false });
208 const updateModelContext = useAtomCommand(mcpAppEnvironment.updateModelContext, {
209 reportFailure: false,
210 });
211 const [toolDefinition, setToolDefinition] = useState<unknown>(undefined);
212 // Read by the host on every message, so it always sees current values
213 // without being rebuilt (which would drop the app's session).
214 const conversation = useThreadShell(
215 scopeThreadRef(props.environmentId, props.conversationThreadId),
216 );
217 const awaitingUser =
218 conversation?.hasPendingApprovals === true || conversation?.hasPendingUserInput === true;
219 const live = {
220 awaitingUser,
221 theme,
222 props,
223 callTool,
224 toolInfo,
225 readResource,
226 updateModelContext,
227 insets,
228 toolDefinition,
229 navigation,
230 };
231 const latest = useRef(live);
232 useEffect(() => {
233 latest.current = live;
234 });
235 useEffect(() => {
236 let cancelled = false;
237 void latest.current
238 .toolInfo({
239 environmentId: props.environmentId,
240 input: { threadId: props.threadId, itemId: props.itemId, name: app.tool },
241 })
242 .then((info) => {
243 if (!cancelled && info._tag === "Success" && info.value.tool !== undefined) {
244 setToolDefinition(info.value.tool);
245 }
246 });
247 return () => {
248 cancelled = true;
249 };
250 }, [props.environmentId, props.threadId, props.itemId, app.tool]);
251 const webView = useRef<WebView<object>>(null);
252 const hostRef = useRef<McpAppHost | null>(null);
253 const userActive = useRef(false);
254
255 useEffect(() => {
256 if (uri === null) return;
257 const scope = () => {
258 const { environmentId, threadId, itemId } = latest.current.props;
259 return { environmentId, input: { threadId, itemId } };
260 };
261 const hostContext = (): McpAppHostContext => {
262 const current = latest.current;
263 const isFullscreen = current.props.displayMode === "fullscreen";
264 return {
265 theme: current.theme.appearance,
266 styles: { variables: mcpAppStyleVariables(current.theme.variables) },
267 displayMode: isFullscreen ? "fullscreen" : "inline",
268 availableDisplayModes: ["inline", "fullscreen"],
269 containerDimensions: isFullscreen
270 ? {
271 width: current.props.width,
272 height: current.props.height ?? MCP_APP_INLINE_MAX_HEIGHT,
273 }
274 : { width: current.props.width, maxHeight: MCP_APP_INLINE_MAX_HEIGHT },
275 platform: "mobile",
276 locale: Intl.DateTimeFormat().resolvedOptions().locale,
277 timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
278 userAgent: `t3-code/${Constants.expoConfig?.version ?? "0.0.0"}`,
279 deviceCapabilities: { touch: true, hover: false },
280 safeAreaInsets: isFullscreen
281 ? { top: 0, right: current.insets.right, bottom: 0, left: current.insets.left }
282 : { top: 0, right: 0, bottom: 0, left: 0 },
283 ...(current.toolDefinition === undefined
284 ? {}
285 : { toolInfo: { tool: current.toolDefinition } }),
286 };
287 };
288 const next = makeMcpAppHost({
289 app,
290 hostVersion: Constants.expoConfig?.version ?? "0.0.0",
291 post: (message) =>
292 webView.current?.injectJavaScript(
293 `window.__t3McpAppReceive&&window.__t3McpAppReceive(${JSON.stringify(message)});true;`,
294 ),
295 hostContext,
296 callTool: async ({ name, arguments: args }) => {
297 const { environmentId, input } = scope();
298 const info = await latest.current.toolInfo({ environmentId, input: { ...input, name } });
299 if (info._tag !== "Success") throw commandFailure(info);
300 if (!info.value.callable) throw new McpAppHostRefusal("This app cannot call that tool.");
301 if (
302 !info.value.readOnly &&
303 !(await confirm(
304 `Allow ${app.server} to run ${info.value.title ?? name}?`,
305 JSON.stringify(args, null, 2),
306 "Allow",
307 ))
308 ) {
309 throw new McpAppHostRefusal("Declined by the user.");
310 }
311 const result = await latest.current.callTool({
312 environmentId,
313 input: { ...input, name, arguments: args },
314 });
315 if (result._tag !== "Success") throw commandFailure(result);
316 return result.value;
317 },
318 readResource: async ({ uri: resourceUri }) => {
319 const { environmentId, input } = scope();
320 const result = await latest.current.readResource({
321 environmentId,
322 input: { ...input, uri: resourceUri },
323 });
324 if (result._tag !== "Success") throw commandFailure(result);
325 return result.value;
326 },
327 openLink: async (url) => {
328 // A WebView cannot tell whether the reader just tapped the app, so it
329 // asks, rather than letting an app leave T3 on a timer.
330 if (!(await confirm(`Open a link from ${app.server}?`, url, "Open"))) {
331 throw new McpAppHostRefusal("Declined by the user.");
332 }
333 if (!(await tryOpenExternalUrl(url, "mcp-app"))) {
334 throw new McpAppHostRefusal("The link could not be opened.");
335 }
336 },
337 sendMessage: async (text) => {
338 if (!(await confirm(`Send this message from ${app.server}?`, text, "Send"))) {
339 throw new McpAppHostRefusal("Declined by the user.");
340 }
341 await enqueueThreadOutboxMessage({
342 environmentId: latest.current.props.environmentId,
343 threadId: latest.current.props.conversationThreadId,
344 messageId: MessageId.make(uuidv4()),
345 commandId: CommandId.make(uuidv4()),
346 text,
347 attachments: [],
348 dispatchMode: "queue",
349 createdAt: new Date().toISOString(),
350 });
351 },
352 updateModelContext: async (context) => {
353 const { environmentId, input } = scope();
354 const result = await latest.current.updateModelContext({
355 environmentId,
356 input: {
357 ...input,
358 ...context,
359 conversationThreadId: latest.current.props.conversationThreadId,
360 },
361 });
362 if (result._tag !== "Success") throw commandFailure(result);
363 },
364 requestDisplayMode: async (mode) => {
365 const current = latest.current.props;
366 // receive dispatches synchronously; read activation before awaiting teardown.
367 if (
368 mode === "fullscreen" &&
369 (!userActive.current ||
370 latest.current.awaitingUser ||
371 !latest.current.navigation.isFocused())
372 ) {
373 return current.displayMode ?? "inline";
374 }
375 if (mode === "fullscreen" && current.displayMode !== "fullscreen") {
376 await hostRef.current?.teardown();
377 // The wait may have let an approval arrive, or the user moved to
378 // another screen; either way the view reloads inline.
379 if (latest.current.awaitingUser || !latest.current.navigation.isFocused()) {
380 openNewDocument.current((value) => value + 1);
381 return "inline";
382 }
383 setPresentedFullscreen(true);
384 latest.current.navigation.navigate("ThreadMcpApp", {
385 environmentId: String(current.environmentId),
386 threadId: String(current.threadId),
387 conversationThreadId: String(current.conversationThreadId),
388 itemId: String(current.itemId),
389 revision: current.revision,
390 });
391 return "fullscreen";
392 }
393 if (mode === "inline" && current.displayMode === "fullscreen") {
394 await hostRef.current?.teardown();
395 current.onExitFullscreen?.();
396 return "inline";
397 }
398 return current.displayMode ?? "inline";
399 },
400 downloadFile: async (files) => {
401 const names = files.map((file) => file.name).join(", ");
402 if (!(await confirm(`Save a file from ${app.server}?`, names, "Save"))) {
403 throw new McpAppHostRefusal("Declined by the user.");
404 }
405 for (const file of files) {
406 let bytes: Uint8Array | undefined;
407 let mimeType = file.mimeType ?? "application/octet-stream";
408 if (file._tag === "embedded") {
409 bytes = file.bytes;
410 } else {
411 const { environmentId, input } = scope();
412 const read = await latest.current.readResource({
413 environmentId,
414 input: { ...input, uri: file.uri },
415 });
416 if (read._tag !== "Success") throw commandFailure(read);
417 const content = read.value.contents[0];
418 bytes = mcpResourceBytes(content);
419 const declared = (content as { readonly mimeType?: unknown } | undefined)?.mimeType;
420 if (typeof declared === "string") mimeType = declared;
421 }
422 if (bytes === undefined) throw new McpAppHostRefusal(`${file.name} has no contents.`);
423 if (bytes.byteLength > MAX_DOWNLOAD_BYTES) {
424 throw new McpAppHostRefusal(`${file.name} is too large to save.`);
425 }
426 const shared = await shareGeneratedAttachment({
427 bytes,
428 attachment: { name: file.name, mimeType },
429 signal: new AbortController().signal,
430 });
431 if (!shared) throw new McpAppHostRefusal("Sharing is not available on this device.");
432 }
433 },
434 onRequestTeardown: () => {
435 const current = latest.current.props;
436 if (current.displayMode === "fullscreen") {
437 void hostRef.current?.teardown().then(() => current.onExitFullscreen?.());
438 } else {
439 void hostRef.current?.teardown().then(() => setClosed(true));
440 }
441 },
442 onSizeChanged: (size) => {
443 if (latest.current.props.displayMode === "fullscreen") return;
444 const nextHeight = mcpAppInlineHeight(size.height);
445 if (nextHeight !== undefined) setHeight(nextHeight);
446 },
447 });
448 hostRef.current = next;
449 return () => {
450 // An unmount cannot wait: the request goes out before the view does.
451 void next.teardown();
452 hostRef.current = null;
453 };
454 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A restarted view needs a new host.
455 }, [uri, app, generation, documentKey]);
456
457 useEffect(() => {
458 hostRef.current?.updateHostContext();
459 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Context changes trigger a resend.
460 }, [theme, props.width, props.height, insets, toolDefinition]);
461 useEffect(() => {
462 if (toolCall !== undefined) hostRef.current?.setToolCall(toolCall);
463 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Each new document needs the call.
464 }, [toolCall, uri, generation, documentKey]);
465
466 const source = useMemo(
467 () =>
468 uri === null
469 ? null
470 : { html: outerDocument(uri, mcpAppAllowAttribute(app.permissions), secret) },
471 [uri, app.permissions, secret],
472 );
473
474 if (presentedFullscreen) {
475 return (
476 <View
477 style={{ height, marginBottom: ROW_BOTTOM_MARGIN }}
478 className="items-center justify-center rounded-lg border border-border"
479 >
480 <Text className="text-sm text-foreground-muted">
481 The {app.server} app is open full screen
482 </Text>
483 </View>
484 );
485 }
486
487 if (closed) {
488 return (
489 <View
490 style={{ height, marginBottom: ROW_BOTTOM_MARGIN }}
491 className="items-center justify-center gap-2 rounded-lg border border-border"
492 >
493 <Text className="text-sm text-foreground-muted">The {app.server} app was closed</Text>
494 <View className="items-center">
495 <Button
496 label="Show app"
497 tone="secondary"
498 onPress={() => {
499 setDocumentKey((value) => value + 1);
500 setClosed(false);
501 }}
502 />
503 </View>
504 </View>
505 );
506 }
507
508 return (
509 <View style={fullscreen ? { flex: 1 } : { height, marginBottom: ROW_BOTTOM_MARGIN }}>
510 {navigatedAway ? (
511 <View className="flex-1 items-center justify-center">
512 <Text className="text-sm text-foreground-muted">
513 The {app.server} app left its page and was stopped
514 </Text>
515 </View>
516 ) : uri !== null && !crashed ? (
517 <WebView<object>
518 key={`${documentKey}:${generation}`}
519 ref={webView}
520 onContentProcessDidTerminate={restart}
521 onRenderProcessGone={restart}
522 source={source!}
523 accessibilityLabel={`${app.server} app`}
524 style={{ flex: 1, backgroundColor: "transparent" }}
525 nestedScrollEnabled
526 originWhitelist={["*"]}
527 // Only the outer page loads at the top; the app opens links through
528 // the bridge. Android reports every navigation as top-frame, frames
529 // the app nests included, so it has no gate to apply: there the
530 // outer page never navigates, and the app frame's sandbox already
531 // forbids top navigation and popups.
532 onShouldStartLoadWithRequest={(request) =>
533 Platform.OS === "android" ||
534 request.isTopFrame === false ||
535 request.url === "about:blank"
536 }
537 setSupportMultipleWindows={false}
538 onLoadEnd={() => setLoaded(true)}
539 onError={() => setCrashed(true)}
540 onHttpError={() => setCrashed(true)}
541 onMessage={(event: WebViewMessageEvent) => {
542 let envelope: unknown;
543 try {
544 envelope = JSON.parse(event.nativeEvent.data);
545 } catch {
546 return;
547 }
548 if (!Predicate.isObject(envelope) || envelope.secret !== secret) return;
549 const message = envelope.message;
550 if (Predicate.isObject(message) && message.t3 === "navigated") {
551 hostRef.current?.dispose();
552 setNavigatedAway(true);
553 return;
554 }
555 userActive.current = envelope.active === true;
556 hostRef.current?.receive(message);
557 userActive.current = false;
558 }}
559 />
560 ) : asset._tag === "Failure" || crashed ? (
561 <View className="flex-1 items-center justify-center">
562 <Text className="text-sm text-foreground-muted">Unable to load the {app.server} app</Text>
563 </View>
564 ) : null}
565 {uri !== null && !loaded && !crashed && !navigatedAway ? (
566 <View pointerEvents="none" className="absolute inset-0 items-center justify-center">
567 <AppActivityIndicator />
568 </View>
569 ) : null}
570 </View>
571 );
572}