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

McpAppWebView.tsx

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