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

McpAppFrame.tsx

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