Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

McpAppFrame.tsx

488 lines19.1 KB

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