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

McpAppFrame.tsx

530 lines20.5 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_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_BASE_NAME, 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 }
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);
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 [bridgeMissing, setBridgeMissing] = useState(false);
105 const [displayMode, setDisplayMode] = useState<McpAppDisplayMode>("inline");
106 const [closed, setClosed] = useState(false);
107 const [documentGeneration, setDocumentGeneration] = useState(0);
108 // Closing and reopening replaces the box, which re-attaches this.
109 const attachBox = (box: HTMLDivElement) => {
110 boxRef.current = box;
111 setWidth(box.clientWidth);
112 const stopResize = observeResize(box, ([entry]) => {
113 if (entry) setWidth(Math.round(entry.contentRect.width));
114 // Full screen reports the viewport, which can change height alone.
115 if (fullscreenSupported && box.matches(":popover-open")) {
116 hostRef.current?.updateHostContext();
117 }
118 });
119 return () => {
120 stopResize();
121 boxRef.current = null;
122 };
123 };
124​
125 const resource = {
126 _tag: "attachment" as const,
127 attachmentId: app.attachmentId,
128 fileName: mcpAppFileName(app),
129 mimeType: "text/html",
130 disposition: "inline" as const,
131 renderIntent: "mcp-app" as const,
132 };
133 // The frame keeps its first URL: a re-minted one would reload the app.
134 const [src, setSrc] = useState<string | null>(null);
135 const asset = useLongLivedAssetUrl(src === null ? props.environmentId : null, resource);
136 if (src === null && asset._tag === "Success") {
137 // The app paints before `ui/initialize`, so it reads the initial scheme from its URL.
138 const url = new URL(asset.url);
139 url.searchParams.set(MCP_APP_COLOR_SCHEME_PARAM, theme.appearance);
140 setSrc(url.toString());
141 }
142​
143 const detail = useTurnItemDetail({
144 environmentId: props.environmentId,
145 threadId: props.threadId,
146 itemId: props.itemId,
147 revision: props.revision,
148 });
149 const storedItem = detail.data?.item;
150 // Keep tool-call identity stable for the host's delivery effect.
151 const toolCall =
152 storedItem?.type === "dynamic_tool"
153 ? {
154 arguments: storedItem.input,
155 result: (storedItem.output as { readonly result?: unknown } | undefined)?.result as
156 | McpAppCallToolResult
157 | undefined,
158 }
159 : undefined;
160​
161 const callTool = useAtomCommand(mcpAppEnvironment.callTool, { reportFailure: false });
162 const toolInfo = useAtomCommand(mcpAppEnvironment.toolInfo, { reportFailure: false });
163 const toolDefinition = useEnvironmentQuery(
164 mcpAppEnvironment.toolInfoQuery({
165 environmentId: props.environmentId,
166 input: { threadId: props.threadId, itemId: props.itemId, name: app.tool },
167 }),
168 ).data?.tool;
169 const readResource = useAtomCommand(mcpAppEnvironment.readResource, { reportFailure: false });
170 const updateModelContext = useAtomCommand(mcpAppEnvironment.updateModelContext, {
171 reportFailure: false,
172 });
173​
174 // Read live values without rebuilding the host and losing the app session.
175 const readLive = useStableCallback(() => ({
176 theme,
177 width,
178 props,
179 callTool,
180 toolInfo,
181 readResource,
182 updateModelContext,
183 displayMode,
184 toolDefinition,
185 }));
186 const hostRef = useRef<McpAppHost | null>(null);
187​
188 const [stepAsideFor, setStepAsideFor] = useState(props.awaitingUser);
189 if (stepAsideFor !== props.awaitingUser) {
190 setStepAsideFor(props.awaitingUser);
191 if (props.awaitingUser === true) setDisplayMode("inline");
192 }
193 // The box is in the top layer exactly while its full-screen chrome is
194 // mounted, so every way out of full screen (including the step-aside above,
195 // decided during render) closes the popover and releases the timeline pin.
196 const attachFullscreenChrome = (chrome: HTMLDivElement) => {
197 const box = chrome.parentElement;
198 if (box === null) return;
199 if (!box.matches(":popover-open")) box.showPopover();
200 readLive().props.onFullscreenChange?.(true);
201 return () => {
202 if (box.matches(":popover-open")) box.hidePopover();
203 readLive().props.onFullscreenChange?.(false);
204 };
205 };
206 // Light dismiss (Escape) closes the popover without React.
207 const onBoxToggle = (event: ToggleEvent<HTMLDivElement>) => {
208 if (event.newState === "closed") setDisplayMode("inline");
209 };
210 const onBoxBlur = (event: FocusEvent<HTMLDivElement>) => {
211 const next = event.relatedTarget;
212 if (
213 displayMode === "fullscreen" &&
214 next instanceof Node &&
215 !event.currentTarget.contains(next)
216 ) {
217 setDisplayMode("inline");
218 }
219 };
220​
221 // Navigation retains the frame window; reject second loads to prevent impersonation.
222 const loads = useRef({ generation: 0, count: 0 });
223 const onFrameLoad = () => {
224 if (loads.current.generation !== documentGeneration) {
225 loads.current = { generation: documentGeneration, count: 0 };
226 }
227 loads.current.count += 1;
228 if (loads.current.count > 1) {
229 hostRef.current?.dispose();
230 setNavigatedAway(true);
231 }
232 };
233​
234 // The host belongs to this frame element, which is replaced when the document is reopened.
235 const attachFrame = (frame: HTMLIFrameElement) => {
236 frameRef.current = frame;
237 const hostContext = (): McpAppHostContext => {
238 const current = readLive();
239 return {
240 theme: current.theme.appearance,
241 styles: { variables: mcpAppStyleVariables(current.theme.variables) },
242 displayMode: current.displayMode,
243 availableDisplayModes: fullscreenSupported ? ["inline", "fullscreen"] : ["inline"],
244 containerDimensions:
245 current.displayMode === "fullscreen"
246 ? {
247 width: frameRef.current?.clientWidth || window.innerWidth,
248 height: frameRef.current?.clientHeight || window.innerHeight,
249 }
250 : { width: current.width, maxHeight: MCP_APP_MAX_HEIGHT },
251 platform: isElectron ? "desktop" : "web",
252 locale: navigator.language,
253 timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
254 userAgent: `t3-code/${APP_VERSION}`,
255 deviceCapabilities: {
256 touch: window.matchMedia("(pointer: coarse)").matches,
257 hover: window.matchMedia("(hover: hover)").matches,
258 },
259 safeAreaInsets: { top: 0, right: 0, bottom: 0, left: 0 },
260 ...(current.toolDefinition === undefined
261 ? {}
262 : { toolInfo: { tool: current.toolDefinition } }),
263 };
264 };
265 // Return inline so approvals stay visible above the app.
266 const ask = async (message: string) => {
267 flushSync(() => setDisplayMode("inline"));
268 const approved = await requestConfirmDialog(message);
269 if (approved === undefined) {
270 throw new McpAppHostRefusal({ message: "T3 could not ask for approval here." });
271 }
272 return approved;
273 };
274 const scope = () => {
275 const { environmentId, threadId, itemId } = readLive().props;
276 return { environmentId, input: { threadId, itemId } };
277 };
278 const documentLink = attachMcpAppDocumentLink(
279 frame,
280 (data) => host.receive(data),
281 () => setBridgeMissing(true),
282 );
283 const host = makeMcpAppHost({
284 app,
285 hostVersion: APP_VERSION,
286 post: documentLink.post,
287 hostContext,
288 callTool: async ({ name, arguments: args }) => {
289 const { environmentId, input } = scope();
290 const info = await readLive().toolInfo({ environmentId, input: { ...input, name } });
291 if (info._tag !== "Success") throw commandFailure(info);
292 if (!info.value.callable)
293 throw new McpAppHostRefusal({ message: "This app cannot call that tool." });
294 if (!info.value.readOnly) {
295 const approved = await ask(
296 `${m(msg("Allow {server} to run {tool}?", { server: app.server, tool: info.value.title ?? name }))}\n${JSON.stringify(args, null, 2)}`,
297 );
298 if (approved !== true) throw new McpAppHostRefusal({ message: "Declined by the user." });
299 }
300 const result = await readLive().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 readLive().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({ message: "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 = readLive().props.onSendMessage;
324 if (send === undefined)
325 throw new McpAppHostRefusal({ message: "Messages are not available here." });
326 const approved = await ask(
327 `${m(msg("Send this message from {server}?", { server: app.server }))}\n${text}`,
328 );
329 if (approved !== true) throw new McpAppHostRefusal({ message: "Declined by the user." });
330 await send(text);
331 },
332 updateModelContext: async (context) => {
333 const { environmentId, input } = scope();
334 const result = await readLive().updateModelContext({
335 environmentId,
336 input: {
337 ...input,
338 ...context,
339 conversationThreadId: readLive().props.conversationThreadId,
340 },
341 });
342 if (result._tag !== "Success") throw commandFailure(result);
343 },
344 requestDisplayMode: async (mode) => {
345 const otherFullscreen = document.querySelector("[data-mcp-app-fullscreen]");
346 if (
347 mode === "fullscreen" &&
348 (!fullscreenSupported ||
349 document.activeElement !== frameRef.current ||
350 !navigator.userActivation?.isActive ||
351 performance.now() - lastPageInputAt < PAGE_ACTIVATION_MS ||
352 readLive().props.awaitingUser === true ||
353 isConfirmDialogActive() ||
354 (otherFullscreen !== null && otherFullscreen !== boxRef.current))
355 ) {
356 return readLive().displayMode;
357 }
358 setDisplayMode(mode);
359 return mode;
360 },
361 downloadFile: async (files) => {
362 const names = files.map((file) => file.name).join(", ");
363 const approved = await ask(
364 m(msg("Save {names} from {server}?", { names, server: app.server })),
365 );
366 if (approved !== true) throw new McpAppHostRefusal({ message: "Declined by the user." });
367 for (const file of files) {
368 let bytes: Uint8Array | undefined;
369 let mimeType = file.mimeType ?? "application/octet-stream";
370 if (file._tag === "embedded") {
371 bytes = file.bytes;
372 } else {
373 const { environmentId, input } = scope();
374 const read = await readLive().readResource({
375 environmentId,
376 input: { ...input, uri: file.uri },
377 });
378 if (read._tag !== "Success") throw commandFailure(read);
379 const content = read.value.contents[0];
380 bytes = mcpResourceBytes(content);
381 const declared = (content as { readonly mimeType?: unknown } | undefined)?.mimeType;
382 if (typeof declared === "string") mimeType = declared;
383 }
384 if (bytes === undefined)
385 throw new McpAppHostRefusal({ message: `${file.name} has no contents.` });
386 if (bytes.byteLength > MAX_DOWNLOAD_BYTES) {
387 throw new McpAppHostRefusal({ message: `${file.name} is too large to save.` });
388 }
389 saveBlob(new Blob([bytes.slice()], { type: mimeType }), file.name);
390 }
391 },
392 onRequestTeardown: () => {
393 if (readLive().displayMode === "fullscreen") {
394 setDisplayMode("inline");
395 return;
396 }
397 // A replacement document may have mounted while this one wound down.
398 void host.teardown().then(() => {
399 if (hostRef.current === host) setClosed(true);
400 });
401 },
402 onSizeChanged: (size) => {
403 // Ignore fullscreen height when restoring inline sizing.
404 if (readLive().displayMode === "fullscreen") return;
405 if (size.height !== undefined) setHeight(clampMcpAppHeight(size.height));
406 },
407 });
408 hostRef.current = host;
409 window.addEventListener("message", documentLink.receive);
410 return () => {
411 window.removeEventListener("message", documentLink.receive);
412 void host.teardown();
413 hostRef.current = null;
414 frameRef.current = null;
415 };
416 };
417​
418 // 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
419 useEffect(() => {
420 hostRef.current?.updateHostContext();
421 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Context changes trigger a resend.
422 }, [theme, width, displayMode, toolDefinition]);
423​
424 // 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
425 useEffect(() => {
426 if (toolCall !== undefined) hostRef.current?.setToolCall(toolCall);
427 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Each new document needs the call.
428 }, [toolCall, src, documentGeneration]);
429​
430 if (closed) {
431 return (
432 <div className="flex items-center justify-between gap-2 rounded-lg border border-border px-3 py-2 text-muted-foreground text-xs">
433 <span>
434 <T>
435 The <Var>{app.server}</Var> app was closed
436 </T>
437 </span>
438 <Button
439 size="xs"
440 variant="ghost"
441 onClick={() => {
442 setSrc(null);
443 setDocumentGeneration((value) => value + 1);
444 setClosed(false);
445 }}
446 >
447 <T>Show app</T>
448 </Button>
449 </div>
450 );
451 }
452​
453 // Only a server that binds the app to its document gets a bridge; without one the app cannot run.
454 if (bridgeMissing) {
455 return (
456 <p className="rounded-lg border border-border px-3 py-2 text-muted-foreground text-xs">
457 <T>
458 The <Var>{app.server}</Var> app needs a newer <Var>{APP_BASE_NAME}</Var> server on this
459 environment. Update the server to use it.
460 </T>
461 </p>
462 );
463 }
464​
465 const fullscreen = displayMode === "fullscreen";
466 return (
467 // Preserve inline row height during fullscreen to prevent timeline jumps.
468 <div style={{ height }}>
469 <div
470 ref={attachBox}
471 // Preserve the frame's parent to avoid reloads; the top layer escapes timeline containment.
472 {...(fullscreenSupported
473 ? { popover: "auto" as const, onToggle: onBoxToggle, onBlur: onBoxBlur }
474 : {})}
475 data-mcp-app-fullscreen={fullscreen ? "" : undefined}
476 className={cn(
477 "relative size-full overflow-hidden",
478 app.prefersBorder === true && !fullscreen && "rounded-lg border border-border",
479 fullscreen
480 ? "fixed inset-0 m-0 flex h-dvh max-h-none w-dvw max-w-none flex-col border-0 bg-background p-0"
481 : "block! static! m-0 border-0 bg-transparent p-0 text-inherit",
482 )}
483 // Keep the header clear of the native window controls.
484 style={fullscreen ? { paddingTop: nativeTitlebarHeight } : undefined}
485 >
486 {fullscreen ? (
487 <div
488 ref={attachFullscreenChrome}
489 className="flex h-10 shrink-0 items-center justify-between border-border border-b px-3 text-sm"
490 >
491 <span className="truncate">{app.server}</span>
492 <Button
493 aria-label={gt("Exit full screen")}
494 size="icon-sm"
495 variant="ghost"
496 onClick={() => setDisplayMode("inline")}
497 >
498 <Minimize2Icon className="size-4" />
499 </Button>
500 </div>
501 ) : null}
502 {navigatedAway ? (
503 <p className="flex size-full items-center justify-center text-muted-foreground text-xs">
504 <T>
505 The <Var>{app.server}</Var> app left its page and was stopped
506 </T>
507 </p>
508 ) : src !== null ? (
509 <iframe
510 ref={attachFrame}
511 src={src}
512 title={gt("{server} app", { server: app.server })}
513 // Omitting allow-same-origin isolates the app from the session.
514 sandbox="allow-scripts allow-forms"
515 allow={mcpAppAllowAttribute(app.permissions)}
516 onLoad={onFrameLoad}
517 className={cn("block w-full border-0", fullscreen ? "min-h-0 flex-1" : "h-full")}
518 style={{ colorScheme: theme.appearance }}
519 />
520 ) : asset._tag === "Failure" ? (
521 <p className="flex size-full items-center justify-center text-muted-foreground text-xs">
522 <T>
523 Unable to load the <Var>{app.server}</Var> app
524 </T>
525 </p>
526 ) : null}
527 </div>
528 </div>
529 );