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

McpAppWebView.tsx

581 lines23.8 KB

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