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

McpAppWebView.tsx

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