Open History to see the last commit
1import { Button } from "../../components/ui/Button";
2import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
3import * as Dialog from "../../components/ui/Dialog";
4import type { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";
5import {
6 makeMcpAppHost,
7 McpAppHostRefusal,
8 mcpAppStyleVariables,
9 mcpResourceBytes,
10 type McpAppCallToolResult,
11 type McpAppHost,
12 type McpAppHostContext,
13} from "@t3tools/client-runtime/mcp-apps";
14import { scopeThreadRef } from "@t3tools/client-runtime/environment";
15import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
16import { CommandId, MessageId } from "@t3tools/contracts";
17import {
18 mcpAppAllowAttribute,
19 mcpAppFileName,
20 mcpAppReferencesEqual,
21 type McpAppReference,
22} from "@t3tools/shared/mcpApp";
23import * as Predicate from "effect/Predicate";
24import { 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 };
91}
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(
322 msg("Allow {server} to run {tool}?", {
323 server: app.server,
324 tool: info.value.title ?? name,
325 }),
326 ),
327 JSON.stringify(args, null, 2),
328 m(msg("Allow", { $context: "verb, confirm button" })),
329 ))
330 ) {
331 throw new McpAppHostRefusal({ message: "Declined by the user." });
332 }
333 const result = await latest.current.callTool({
334 environmentId,
335 input: { ...input, name, arguments: args },
336 });
337 if (result._tag !== "Success") throw commandFailure(result);
338 return result.value;
339 },
340 readResource: async ({ uri: resourceUri }) => {
341 const { environmentId, input } = scope();
342 const result = await latest.current.readResource({
343 environmentId,
344 input: { ...input, uri: resourceUri },
345 });
346 if (result._tag !== "Success") throw commandFailure(result);
347 return result.value;
348 },
349 openLink: async (url) => {
350 // WebViews cannot prove user activation; confirm links to prevent timer-driven navigation out of T3.
351 if (
352 !(await confirm(
353 m(msg("Open a link from {server}?", { server: app.server })),
354 url,
355 m(msg("Open", { $context: "verb, opens a link" })),
356 ))
357 ) {
358 throw new McpAppHostRefusal({ message: "Declined by the user." });
359 }
360 if (!(await tryOpenExternalUrl(url, "mcp-app"))) {
361 throw new McpAppHostRefusal({ message: "The link could not be opened." });
362 }
363 },
364 sendMessage: async (text) => {
365 if (
366 !(await confirm(
367 m(msg("Send this message from {server}?", { server: app.server })),
368 text,
369 m(msg("Send", { $context: "verb, sends the message" })),
370 ))
371 ) {
372 throw new McpAppHostRefusal({ message: "Declined by the user." });
373 }
374 await enqueueThreadOutboxMessage({
375 environmentId: latest.current.props.environmentId,
376 threadId: latest.current.props.conversationThreadId,
377 messageId: MessageId.make(uuidv4()),
378 commandId: CommandId.make(uuidv4()),
379 text,
380 attachments: [],
381 dispatchMode: "queue",
382 createdAt: new Date().toISOString(),
383 });
384 },
385 updateModelContext: async (context) => {
386 const { environmentId, input } = scope();
387 const result = await latest.current.updateModelContext({
388 environmentId,
389 input: {
390 ...input,
391 ...context,
392 conversationThreadId: latest.current.props.conversationThreadId,
393 },
394 });
395 if (result._tag !== "Success") throw commandFailure(result);
396 },
397 requestDisplayMode: async (mode) => {
398 const current = latest.current.props;
399 // receive dispatches synchronously; read activation before awaiting teardown.
400 if (
401 mode === "fullscreen" &&
402 (!userActive.current ||
403 latest.current.awaitingUser ||
404 !latest.current.navigation.isFocused())
405 ) {
406 return current.displayMode ?? "inline";
407 }
408 if (mode === "fullscreen" && current.displayMode !== "fullscreen") {
409 await documentHost.teardown();
410 // A crash restart or reload during the wait already replaced this document.
411 if (currentHost.current !== documentHost) return "inline";
412 // Approval arrival or navigation during the wait requires reloading inline.
413 const navigation = latest.current.navigation;
414 if (latest.current.awaitingUser || !navigation.isFocused()) {
415 reloadInline();
416 return "inline";
417 }
418 setPresentedFullscreen(true);
419 navigation.navigate("ThreadMcpApp", {
420 environmentId: String(current.environmentId),
421 threadId: String(current.threadId),
422 conversationThreadId: String(current.conversationThreadId),
423 itemId: String(current.itemId),
424 revision: current.revision,
425 });
426 return "fullscreen";
427 }
428 if (mode === "inline" && current.displayMode === "fullscreen") {
429 await documentHost.teardown();
430 if (currentHost.current === documentHost) current.onExitFullscreen?.();
431 return "inline";
432 }
433 return current.displayMode ?? "inline";
434 },
435 downloadFile: async (files) => {
436 const names = files.map((file) => file.name).join(", ");
437 if (
438 !(await confirm(
439 m(msg("Save a file from {server}?", { server: app.server })),
440 names,
441 m(msg("Save", { $context: "verb, confirm button" })),
442 ))
443 ) {
444 throw new McpAppHostRefusal({ message: "Declined by the user." });
445 }
446 for (const file of files) {
447 let bytes: Uint8Array | undefined;
448 let mimeType = file.mimeType ?? "application/octet-stream";
449 if (file._tag === "embedded") {
450 bytes = file.bytes;
451 } else {
452 const { environmentId, input } = scope();
453 const read = await latest.current.readResource({
454 environmentId,
455 input: { ...input, uri: file.uri },
456 });
457 if (read._tag !== "Success") throw commandFailure(read);
458 const content = read.value.contents[0];
459 bytes = mcpResourceBytes(content);
460 const declared = (content as { readonly mimeType?: unknown } | undefined)?.mimeType;
461 if (typeof declared === "string") mimeType = declared;
462 }
463 if (bytes === undefined)
464 throw new McpAppHostRefusal({ message: `${file.name} has no contents.` });
465 if (bytes.byteLength > MAX_DOWNLOAD_BYTES) {
466 throw new McpAppHostRefusal({ message: `${file.name} is too large to save.` });
467 }
468 const shared = await shareGeneratedAttachment({
469 bytes,
470 attachment: { name: file.name, mimeType },
471 signal: new AbortController().signal,
472 });
473 if (!shared)
474 throw new McpAppHostRefusal({ message: "Sharing is not available on this device." });
475 }
476 },
477 onRequestTeardown: () => {
478 const current = latest.current.props;
479 void documentHost.teardown().then(() => {
480 if (currentHost.current !== documentHost) return;
481 if (current.displayMode === "fullscreen") current.onExitFullscreen?.();
482 else setClosed(true);
483 });
484 },
485 onSizeChanged: (size) => {
486 if (latest.current.props.displayMode === "fullscreen") return;
487 const nextHeight = mcpAppInlineHeight(size.height);
488 if (nextHeight !== undefined) setHeight(nextHeight);
489 },
490 });
491 setHost(documentHost);
492 currentHost.current = documentHost;
493 return () => {
494 if (currentHost.current === documentHost) currentHost.current = null;
495 // An unmount cannot wait: the request goes out before the view does.
496 void documentHost.teardown();
497 setHost((current) => (current === documentHost ? null : current));
498 };
499 };
500
501 const source =
502 uri === null
503 ? null
504 : { html: mcpAppRelayDocument(uri, mcpAppAllowAttribute(app.permissions), secret) };
505
506 if (presentedFullscreen) {
507 return (
508 <View
509 style={{ height, marginBottom: ROW_BOTTOM_MARGIN }}
510 className="items-center justify-center rounded-lg border border-border"
511 >
512 <Text className="text-sm text-foreground-muted">
513 <T>
514 The <Var>{app.server}</Var> app is open full screen
515 </T>
516 </Text>
517 </View>
518 );
519 }
520
521 if (closed) {
522 return (
523 <View
524 style={{ height, marginBottom: ROW_BOTTOM_MARGIN }}
525 className="items-center justify-center gap-2 rounded-lg border border-border"
526 >
527 <Text className="text-sm text-foreground-muted">
528 <T>
529 The <Var>{app.server}</Var> app was closed
530 </T>
531 </Text>
532 <View className="items-center">
533 <Button
534 label={gt("Show app")}
535 tone="secondary"
536 onPress={() => {
537 reopenDocument();
538 setClosed(false);
539 }}
540 />
541 </View>
542 </View>
543 );
544 }
545
546 return (
547 <View style={fullscreen ? { flex: 1 } : { height, marginBottom: ROW_BOTTOM_MARGIN }}>
548 {bridgeMissing ? (
549 // Only a server that binds the app to its document gets a bridge; without one the app cannot run.
550 <View className="flex-1 items-center justify-center rounded-lg border border-border px-4">
551 <Text className="text-center text-sm text-foreground-muted">
552 <T>
553 The <Var>{app.server}</Var> app needs a newer <Var>{PRODUCT_NAME}</Var> server on this
554 environment. Update the server to use it.
555 </T>
556 </Text>
557 </View>
558 ) : navigatedAway ? (
559 <View className="flex-1 items-center justify-center">
560 <Text className="text-sm text-foreground-muted">
561 <T>
562 The <Var>{app.server}</Var> app left its page and was stopped
563 </T>
564 </Text>
565 </View>
566 ) : uri !== null && !crashed ? (
567 <WebView<object>
568 key={`${documentKey}:${generation}:${uri}`}
569 ref={attachWebView}
570 onContentProcessDidTerminate={restart}
571 onRenderProcessGone={restart}
572 source={source!}
573 accessibilityLabel={gt("{server} app", { server: app.server })}
574 style={{ flex: 1, backgroundColor: "transparent" }}
575 nestedScrollEnabled
576 decelerationRate={webViewDecelerationRate}
577 originWhitelist={["*"]}
578 // Android misreports nested frames as top-level; rely on iframe sandboxing there and gate navigation elsewhere.
579 onShouldStartLoadWithRequest={(request) =>
580 Platform.OS === "android" ||
581 request.isTopFrame === false ||
582 request.url === "about:blank"
583 }
584 setSupportMultipleWindows={false}
585 onLoadEnd={() => setLoaded(true)}
586 onError={() => setCrashed(true)}
587 onHttpError={() => setCrashed(true)}
588 onMessage={(event: WebViewMessageEvent) => {
589 let envelope: unknown;
590 try {
591 envelope = JSON.parse(event.nativeEvent.data);
592 } catch {
593 return;
594 }
595 if (!Predicate.isObject(envelope) || envelope.secret !== secret) return;
596 const message = envelope.message;
597 if (Predicate.isObject(message) && message.t3 === "navigated") {
598 host?.dispose();
599 setNavigatedAway(true);
600 return;
601 }
602 if (Predicate.isObject(message) && message.t3 === "unlinked") {
603 host?.dispose();
604 setBridgeMissing(true);
605 return;
606 }
607 userActive.current = envelope.active === true;
608 host?.receive(message);
609 userActive.current = false;
610 }}
611 />
612 ) : asset._tag === "Failure" || crashed ? (
613 <View className="flex-1 items-center justify-center">
614 <Text className="text-sm text-foreground-muted">
615 <T>
616 Unable to load the <Var>{app.server}</Var> app
617 </T>
618 </Text>
619 </View>
620 ) : null}
621 {uri !== null && !loaded && !crashed && !navigatedAway && !bridgeMissing ? (
622 <View pointerEvents="none" className="absolute inset-0 items-center justify-center">
623 <AppActivityIndicator />
624 </View>
625 ) : null}
626 </View>
627 );
628}