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