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