Open History to see the last commit
1import type { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";
2import {
3 makeMcpAppHost,
4 McpAppHostRefusal,
5 mcpAppStyleVariables,
6 mcpResourceBytes,
7 type McpAppCallToolResult,
8 type McpAppDisplayMode,
9 type McpAppHost,
10 type McpAppHostContext,
11} from "@t3tools/client-runtime/mcp-apps";
12import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
13import {
14 clampMcpAppHeight,
15 MCP_APP_DEFAULT_HEIGHT,
16 MCP_APP_MAX_HEIGHT,
17 mcpAppAllowAttribute,
18 mcpAppFileName,
19 type McpAppReference,
20} from "@t3tools/shared/mcpApp";
21import { Minimize2Icon } from "lucide-react";
22import { useEffect, useLayoutEffect, useRef, useState } from "react";
23import { flushSync } from "react-dom";
24
25import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";
26import { APP_VERSION } from "~/branding";
27import { isConfirmDialogActive, requestConfirmDialog } from "~/confirmDialog";
28import { useHtmlRenderTheme } from "~/hooks/useHtmlRenderTheme";
29import { Button } from "~/components/ui/button";
30import { isElectron } from "~/env";
31import { cn } from "~/lib/utils";
32import { useTurnItemDetail } from "~/state/queries";
33import { mcpAppEnvironment } from "~/state/mcpApps";
34import { useAtomCommand } from "~/state/use-atom-command";
35import { observeResize } from "~/lib/observeResize";
36
37const commandFailure = (result: {
38 readonly cause: Parameters<typeof squashAtomCommandFailure>[0]["cause"];
39}) => {
40 const error = squashAtomCommandFailure(result);
41 return new McpAppHostRefusal(
42 error instanceof Error && error.message.trim() !== "" ? error.message : "Request failed.",
43 );
44};
45
46const MIN_URL_LIFE_MS = 5 * 60_000;
47const fullscreenSupported =
48 typeof HTMLElement !== "undefined" && "popover" in HTMLElement.prototype;
49
50const MAX_DOWNLOAD_BYTES = 25 * 1024 * 1024;
51// Exclude activation left by input elsewhere in T3.
52const PAGE_ACTIVATION_MS = 5_000;
53
54function saveBlob(blob: Blob, name: string) {
55 const url = URL.createObjectURL(blob);
56 const link = document.createElement("a");
57 link.href = url;
58 link.download = name;
59 link.click();
60 // Browsers may start downloading after the click's task; defer revocation.
61 setTimeout(() => URL.revokeObjectURL(url), 60_000);
62}
63
64export function McpAppFrame(props: {
65 readonly environmentId: EnvironmentId;
66 readonly threadId: ThreadId;
67 readonly conversationThreadId: ThreadId;
68 readonly itemId: TurnItemId;
69 readonly revision: string;
70 readonly app: McpAppReference;
71 readonly onSendMessage: ((text: string) => Promise<void>) | undefined;
72 readonly awaitingUser?: boolean;
73 readonly onFullscreenChange?: (fullscreen: boolean) => void;
74}) {
75 const { app } = props;
76 const theme = useHtmlRenderTheme();
77 const frameRef = useRef<HTMLIFrameElement>(null);
78 const boxRef = useRef<HTMLDivElement>(null);
79 const [width, setWidth] = useState(0);
80 const [height, setHeight] = useState(MCP_APP_DEFAULT_HEIGHT);
81 const [navigatedAway, setNavigatedAway] = useState(false);
82 const [displayMode, setDisplayMode] = useState<McpAppDisplayMode>("inline");
83 const [closed, setClosed] = useState(false);
84 const [documentGeneration, setDocumentGeneration] = useState(0);
85 useLayoutEffect(() => {
86 const box = boxRef.current;
87 if (!box) return;
88 setWidth(box.clientWidth);
89 return observeResize(box, ([entry]) => {
90 if (entry) setWidth(Math.round(entry.contentRect.width));
91 });
92 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Closing and reopening replaces the box.
93 }, [closed]);
94
95 const resource = {
96 _tag: "attachment" as const,
97 attachmentId: app.attachmentId,
98 fileName: mcpAppFileName(app),
99 mimeType: "text/html",
100 disposition: "inline" as const,
101 renderIntent: "mcp-app" as const,
102 };
103 const asset = useAssetUrlState(props.environmentId, resource);
104 const refreshAsset = useAssetUrlRefresh(props.environmentId, resource);
105 // Retain the URL to avoid reloads. Re-mint near expiry; frames cannot report failed loads.
106 const [src, setSrc] = useState<string | null>(null);
107 const [mintFailed, setMintFailed] = useState(false);
108 const minting = useRef(false);
109 const cachedUrl = asset._tag === "Success" ? asset.url : null;
110 const cachedExpiresAt = asset._tag === "Success" ? asset.expiresAt : 0;
111 useEffect(() => {
112 if (src !== null || cachedUrl === null || minting.current) return;
113 if (cachedExpiresAt - Date.now() > MIN_URL_LIFE_MS) {
114 // oxlint-disable-next-line react/set-state-in-effect -- Adopts the cached URL once it is known to last.
115 setSrc(cachedUrl);
116 return;
117 }
118 minting.current = true;
119 void refreshAsset().then(
120 (url) => (url === null ? setMintFailed(true) : setSrc(url)),
121 () => setMintFailed(true),
122 );
123 }, [src, cachedUrl, cachedExpiresAt, refreshAsset]);
124
125 const detail = useTurnItemDetail({
126 environmentId: props.environmentId,
127 threadId: props.threadId,
128 itemId: props.itemId,
129 revision: props.revision,
130 });
131 const storedItem = detail.data?.item;
132 // Keep tool-call identity stable for the host's delivery effect.
133 const toolCall =
134 storedItem?.type === "dynamic_tool"
135 ? {
136 arguments: storedItem.input,
137 result: (storedItem.output as { readonly result?: unknown } | undefined)?.result as
138 | McpAppCallToolResult
139 | undefined,
140 }
141 : undefined;
142
143 const callTool = useAtomCommand(mcpAppEnvironment.callTool, { reportFailure: false });
144 const toolInfo = useAtomCommand(mcpAppEnvironment.toolInfo, { reportFailure: false });
145 const readResource = useAtomCommand(mcpAppEnvironment.readResource, { reportFailure: false });
146 const updateModelContext = useAtomCommand(mcpAppEnvironment.updateModelContext, {
147 reportFailure: false,
148 });
149 const [toolDefinition, setToolDefinition] = useState<unknown>(undefined);
150
151 // Read live values without rebuilding the host and losing the app session.
152 const live = {
153 theme,
154 width,
155 props,
156 callTool,
157 toolInfo,
158 readResource,
159 updateModelContext,
160 displayMode,
161 toolDefinition,
162 };
163 const hostRef = useRef<McpAppHost | null>(null);
164 const latest = useRef(live);
165 useEffect(() => {
166 latest.current = live;
167 });
168
169 // Frame input does not bubble here. An app can refocus itself, so focus
170 // alone cannot exclude activation from input elsewhere in T3.
171 const lastPageInputAt = useRef(Number.NEGATIVE_INFINITY);
172 useEffect(() => {
173 const note = () => {
174 lastPageInputAt.current = performance.now();
175 };
176 if (navigator.userActivation?.isActive) note();
177 const types = ["pointerdown", "pointerup", "touchend", "keydown"] as const;
178 for (const type of types) window.addEventListener(type, note, true);
179 return () => {
180 for (const type of types) window.removeEventListener(type, note, true);
181 };
182 }, []);
183
184 useEffect(() => {
185 const box = boxRef.current;
186 if (box === null || !fullscreenSupported) return;
187 const shown = box.matches(":popover-open");
188 if (displayMode === "fullscreen" && !shown) box.showPopover();
189 if (displayMode !== "fullscreen" && shown) box.hidePopover();
190 if (displayMode === "fullscreen") {
191 latest.current.props.onFullscreenChange?.(true);
192 return () => latest.current.props.onFullscreenChange?.(false);
193 }
194 }, [displayMode]);
195 const [stepAsideFor, setStepAsideFor] = useState(props.awaitingUser);
196 if (stepAsideFor !== props.awaitingUser) {
197 setStepAsideFor(props.awaitingUser);
198 if (props.awaitingUser === true) setDisplayMode("inline");
199 }
200 useEffect(() => {
201 if (displayMode !== "fullscreen") return;
202 const leave = () => setDisplayMode("inline");
203 const onFocus = (event: FocusEvent) => {
204 if (event.target instanceof Node && !boxRef.current?.contains(event.target)) leave();
205 };
206 const onKey = (event: KeyboardEvent) => {
207 if (event.key === "Escape") leave();
208 };
209 const onResize = () => hostRef.current?.updateHostContext();
210 document.addEventListener("focusin", onFocus);
211 window.addEventListener("keydown", onKey);
212 window.addEventListener("resize", onResize);
213 return () => {
214 document.removeEventListener("focusin", onFocus);
215 window.removeEventListener("keydown", onKey);
216 window.removeEventListener("resize", onResize);
217 };
218 }, [displayMode]);
219
220 useEffect(() => {
221 let cancelled = false;
222 void latest.current
223 .toolInfo({
224 environmentId: props.environmentId,
225 input: { threadId: props.threadId, itemId: props.itemId, name: app.tool },
226 })
227 .then((info) => {
228 if (!cancelled && info._tag === "Success" && info.value.tool !== undefined) {
229 setToolDefinition(info.value.tool);
230 }
231 });
232 return () => {
233 cancelled = true;
234 };
235 }, [props.environmentId, props.threadId, props.itemId, app.tool]);
236 // Navigation retains the frame window; reject second loads to prevent impersonation.
237 const loads = useRef({ generation: 0, count: 0 });
238 const onFrameLoad = () => {
239 if (loads.current.generation !== documentGeneration) {
240 loads.current = { generation: documentGeneration, count: 0 };
241 }
242 loads.current.count += 1;
243 if (loads.current.count > 1) {
244 hostRef.current?.dispose();
245 setNavigatedAway(true);
246 }
247 };
248
249 useEffect(() => {
250 if (src === null) return;
251 const hostContext = (): McpAppHostContext => {
252 const current = latest.current;
253 return {
254 theme: current.theme.appearance,
255 styles: { variables: mcpAppStyleVariables(current.theme.variables) },
256 displayMode: current.displayMode,
257 availableDisplayModes: fullscreenSupported ? ["inline", "fullscreen"] : ["inline"],
258 containerDimensions:
259 current.displayMode === "fullscreen"
260 ? {
261 width: frameRef.current?.clientWidth || window.innerWidth,
262 height: frameRef.current?.clientHeight || window.innerHeight,
263 }
264 : { width: current.width, maxHeight: MCP_APP_MAX_HEIGHT },
265 platform: isElectron ? "desktop" : "web",
266 locale: navigator.language,
267 timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
268 userAgent: `t3-code/${APP_VERSION}`,
269 deviceCapabilities: {
270 touch: window.matchMedia("(pointer: coarse)").matches,
271 hover: window.matchMedia("(hover: hover)").matches,
272 },
273 safeAreaInsets: { top: 0, right: 0, bottom: 0, left: 0 },
274 ...(current.toolDefinition === undefined
275 ? {}
276 : { toolInfo: { tool: current.toolDefinition } }),
277 };
278 };
279 // Return inline so approvals stay visible above the app.
280 const ask = async (message: string) => {
281 flushSync(() => setDisplayMode("inline"));
282 const approved = await requestConfirmDialog(message);
283 if (approved === undefined) {
284 throw new McpAppHostRefusal("T3 could not ask for approval here.");
285 }
286 return approved;
287 };
288 const target = () => frameRef.current?.contentWindow ?? null;
289 const scope = () => {
290 const { environmentId, threadId, itemId } = latest.current.props;
291 return { environmentId, input: { threadId, itemId } };
292 };
293 const host = makeMcpAppHost({
294 app,
295 hostVersion: APP_VERSION,
296 // Opaque origins require "*"; the window reference scopes delivery to this frame.
297 post: (message) => target()?.postMessage(message, "*"),
298 hostContext,
299 callTool: async ({ name, arguments: args }) => {
300 const { environmentId, input } = scope();
301 const info = await latest.current.toolInfo({ environmentId, input: { ...input, name } });
302 if (info._tag !== "Success") throw commandFailure(info);
303 if (!info.value.callable) throw new McpAppHostRefusal("This app cannot call that tool.");
304 if (!info.value.readOnly) {
305 const approved = await ask(
306 `Allow ${app.server} to run ${info.value.title ?? name}?\n${JSON.stringify(args, null, 2)}`,
307 );
308 if (approved !== true) throw new McpAppHostRefusal("Declined by the user.");
309 }
310 const result = await latest.current.callTool({
311 environmentId,
312 input: { ...input, name, arguments: args },
313 });
314 if (result._tag !== "Success") throw commandFailure(result);
315 return result.value;
316 },
317 readResource: async ({ uri }) => {
318 const { environmentId, input } = scope();
319 const result = await latest.current.readResource({
320 environmentId,
321 input: { ...input, uri },
322 });
323 if (result._tag !== "Success") throw commandFailure(result);
324 return result.value;
325 },
326 openLink: async (url) => {
327 if (document.activeElement !== frameRef.current || !navigator.userActivation?.isActive) {
328 throw new McpAppHostRefusal("Links open only from a click in the app.");
329 }
330 window.open(url, "_blank", "noopener,noreferrer");
331 },
332 sendMessage: async (text) => {
333 const send = latest.current.props.onSendMessage;
334 if (send === undefined) throw new McpAppHostRefusal("Messages are not available here.");
335 const approved = await ask(`Send this message from ${app.server}?\n${text}`);
336 if (approved !== true) throw new McpAppHostRefusal("Declined by the user.");
337 await send(text);
338 },
339 updateModelContext: async (context) => {
340 const { environmentId, input } = scope();
341 const result = await latest.current.updateModelContext({
342 environmentId,
343 input: {
344 ...input,
345 ...context,
346 conversationThreadId: latest.current.props.conversationThreadId,
347 },
348 });
349 if (result._tag !== "Success") throw commandFailure(result);
350 },
351 requestDisplayMode: async (mode) => {
352 const otherFullscreen = document.querySelector("[data-mcp-app-fullscreen]");
353 if (
354 mode === "fullscreen" &&
355 (document.activeElement !== frameRef.current ||
356 !navigator.userActivation?.isActive ||
357 performance.now() - lastPageInputAt.current < PAGE_ACTIVATION_MS ||
358 latest.current.props.awaitingUser === true ||
359 isConfirmDialogActive() ||
360 (otherFullscreen !== null && otherFullscreen !== boxRef.current))
361 ) {
362 return latest.current.displayMode;
363 }
364 setDisplayMode(mode);
365 return mode;
366 },
367 downloadFile: async (files) => {
368 const names = files.map((file) => file.name).join(", ");
369 const approved = await ask(`Save ${names} from ${app.server}?`);
370 if (approved !== true) throw new McpAppHostRefusal("Declined by the user.");
371 for (const file of files) {
372 let bytes: Uint8Array | undefined;
373 let mimeType = file.mimeType ?? "application/octet-stream";
374 if (file._tag === "embedded") {
375 bytes = file.bytes;
376 } else {
377 const { environmentId, input } = scope();
378 const read = await latest.current.readResource({
379 environmentId,
380 input: { ...input, uri: file.uri },
381 });
382 if (read._tag !== "Success") throw commandFailure(read);
383 const content = read.value.contents[0];
384 bytes = mcpResourceBytes(content);
385 const declared = (content as { readonly mimeType?: unknown } | undefined)?.mimeType;
386 if (typeof declared === "string") mimeType = declared;
387 }
388 if (bytes === undefined) throw new McpAppHostRefusal(`${file.name} has no contents.`);
389 if (bytes.byteLength > MAX_DOWNLOAD_BYTES) {
390 throw new McpAppHostRefusal(`${file.name} is too large to save.`);
391 }
392 saveBlob(new Blob([bytes.slice()], { type: mimeType }), file.name);
393 }
394 },
395 onRequestTeardown: () => {
396 if (latest.current.displayMode === "fullscreen") {
397 setDisplayMode("inline");
398 return;
399 }
400 void host.teardown().then(() => setClosed(true));
401 },
402 onSizeChanged: (size) => {
403 // Ignore fullscreen height when restoring inline sizing.
404 if (latest.current.displayMode === "fullscreen") return;
405 if (size.height !== undefined) setHeight(clampMcpAppHeight(size.height));
406 },
407 });
408 hostRef.current = host;
409 const receive = (event: MessageEvent) => {
410 if (event.source !== null && event.source === target()) host.receive(event.data);
411 };
412 window.addEventListener("message", receive);
413 return () => {
414 window.removeEventListener("message", receive);
415 void host.teardown();
416 hostRef.current = null;
417 };
418 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A reopened document needs a new host.
419 }, [src, app, documentGeneration]);
420
421 useEffect(() => {
422 hostRef.current?.updateHostContext();
423 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Context changes trigger a resend.
424 }, [theme, width, displayMode, toolDefinition]);
425
426 useEffect(() => {
427 if (toolCall !== undefined) hostRef.current?.setToolCall(toolCall);
428 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Each new document needs the call.
429 }, [toolCall, src, documentGeneration]);
430
431 if (closed) {
432 return (
433 <div className="flex items-center justify-between gap-2 rounded-lg border border-border px-3 py-2 text-muted-foreground text-xs">
434 <span>The {app.server} app was closed</span>
435 <Button
436 size="xs"
437 variant="ghost"
438 onClick={() => {
439 minting.current = false;
440 setSrc(null);
441 setDocumentGeneration((value) => value + 1);
442 setClosed(false);
443 }}
444 >
445 Show app
446 </Button>
447 </div>
448 );
449 }
450
451 const fullscreen = displayMode === "fullscreen";
452 return (
453 // Preserve inline row height during fullscreen to prevent timeline jumps.
454 <div style={{ height }}>
455 <div
456 ref={boxRef}
457 // Preserve the frame's parent to avoid reloads; the top layer escapes timeline containment.
458 {...(fullscreenSupported ? { popover: "manual" as const } : {})}
459 data-mcp-app-fullscreen={fullscreen ? "" : undefined}
460 className={cn(
461 "relative size-full overflow-hidden",
462 app.prefersBorder === true && !fullscreen && "rounded-lg border border-border",
463 fullscreen
464 ? "fixed inset-0 m-0 flex h-dvh max-h-none w-dvw max-w-none flex-col border-0 bg-background p-0"
465 : "block! static! m-0 border-0 bg-transparent p-0 text-inherit",
466 )}
467 >
468 {fullscreen ? (
469 <div className="flex h-10 shrink-0 items-center justify-between border-border border-b px-3 text-sm">
470 <span className="truncate">{app.server}</span>
471 <Button
472 aria-label="Exit full screen"
473 size="icon-sm"
474 variant="ghost"
475 onClick={() => setDisplayMode("inline")}
476 >
477 <Minimize2Icon className="size-4" />
478 </Button>
479 </div>
480 ) : null}
481 {navigatedAway ? (
482 <p className="flex size-full items-center justify-center text-muted-foreground text-xs">
483 The {app.server} app left its page and was stopped
484 </p>
485 ) : src !== null ? (
486 <iframe
487 ref={frameRef}
488 src={src}
489 title={`${app.server} app`}
490 // Omitting allow-same-origin isolates the app from the session.
491 sandbox="allow-scripts allow-forms"
492 allow={mcpAppAllowAttribute(app.permissions)}
493 onLoad={onFrameLoad}
494 className={cn("block w-full border-0", fullscreen ? "min-h-0 flex-1" : "h-full")}
495 style={{ colorScheme: theme.appearance }}
496 />
497 ) : asset._tag === "Failure" || mintFailed ? (
498 <p className="flex size-full items-center justify-center text-muted-foreground text-xs">
499 Unable to load the {app.server} app
500 </p>
501 ) : null}
502 </div>
503 </div>
504 );
505}