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