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

McpAppWebView.tsx

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