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

McpAppFrame.tsx

528 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: app.server }} to run ${{ 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: 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(m(msg`Save ${{ names }} from ${{ server: app.server }}?`));
364 if (approved !== true) throw new McpAppHostRefusal({ message: "Declined by the user." });
365 for (const file of files) {
366 let bytes: Uint8Array | undefined;
367 let mimeType = file.mimeType ?? "application/octet-stream";
368 if (file._tag === "embedded") {
369 bytes = file.bytes;
370 } else {
371 const { environmentId, input } = scope();
372 const read = await readLive().readResource({
373 environmentId,
374 input: { ...input, uri: file.uri },
375 });
376 if (read._tag !== "Success") throw commandFailure(read);
377 const content = read.value.contents[0];
378 bytes = mcpResourceBytes(content);
379 const declared = (content as { readonly mimeType?: unknown } | undefined)?.mimeType;
380 if (typeof declared === "string") mimeType = declared;
381 }
382 if (bytes === undefined)
383 throw new McpAppHostRefusal({ message: `${file.name} has no contents.` });
384 if (bytes.byteLength > MAX_DOWNLOAD_BYTES) {
385 throw new McpAppHostRefusal({ message: `${file.name} is too large to save.` });
386 }
387 saveBlob(new Blob([bytes.slice()], { type: mimeType }), file.name);
388 }
389 },
390 onRequestTeardown: () => {
391 if (readLive().displayMode === "fullscreen") {
392 setDisplayMode("inline");
393 return;
394 }
395 // A replacement document may have mounted while this one wound down.
396 void host.teardown().then(() => {
397 if (hostRef.current === host) setClosed(true);
398 });
399 },
400 onSizeChanged: (size) => {
401 // Ignore fullscreen height when restoring inline sizing.
402 if (readLive().displayMode === "fullscreen") return;
403 if (size.height !== undefined) setHeight(clampMcpAppHeight(size.height));
404 },
405 });
406 hostRef.current = host;
407 window.addEventListener("message", documentLink.receive);
408 return () => {
409 window.removeEventListener("message", documentLink.receive);
410 void host.teardown();
411 hostRef.current = null;
412 frameRef.current = null;
413 };
414 };
415​
416 // 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
417 useEffect(() => {
418 hostRef.current?.updateHostContext();
419 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Context changes trigger a resend.
420 }, [theme, width, displayMode, toolDefinition]);
421​
422 // 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
423 useEffect(() => {
424 if (toolCall !== undefined) hostRef.current?.setToolCall(toolCall);
425 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Each new document needs the call.
426 }, [toolCall, src, documentGeneration]);
427​
428 if (closed) {
429 return (
430 <div className="flex items-center justify-between gap-2 rounded-lg border border-border px-3 py-2 text-muted-foreground text-xs">
431 <span>
432 <T>
433 The <Var>{app.server}</Var> app was closed
434 </T>
435 </span>
436 <Button
437 size="xs"
438 variant="ghost"
439 onClick={() => {
440 setSrc(null);
441 setDocumentGeneration((value) => value + 1);
442 setClosed(false);
443 }}
444 >
445 <T>Show app</T>
446 </Button>
447 </div>
448 );
449 }
450​
451 // Only a server that binds the app to its document gets a bridge; without one the app cannot run.
452 if (bridgeMissing) {
453 return (
454 <p className="rounded-lg border border-border px-3 py-2 text-muted-foreground text-xs">
455 <T>
456 The <Var>{app.server}</Var> app needs a newer <Var>{APP_BASE_NAME}</Var> server on this
457 environment. Update the server to use it.
458 </T>
459 </p>
460 );
461 }
462​
463 const fullscreen = displayMode === "fullscreen";
464 return (
465 // Preserve inline row height during fullscreen to prevent timeline jumps.
466 <div style={{ height }}>
467 <div
468 ref={attachBox}
469 // Preserve the frame's parent to avoid reloads; the top layer escapes timeline containment.
470 {...(fullscreenSupported
471 ? { popover: "auto" as const, onToggle: onBoxToggle, onBlur: onBoxBlur }
472 : {})}
473 data-mcp-app-fullscreen={fullscreen ? "" : undefined}
474 className={cn(
475 "relative size-full overflow-hidden",
476 app.prefersBorder === true && !fullscreen && "rounded-lg border border-border",
477 fullscreen
478 ? "fixed inset-0 m-0 flex h-dvh max-h-none w-dvw max-w-none flex-col border-0 bg-background p-0"
479 : "block! static! m-0 border-0 bg-transparent p-0 text-inherit",
480 )}
481 // Keep the header clear of the native window controls.
482 style={fullscreen ? { paddingTop: nativeTitlebarHeight } : undefined}
483 >
484 {fullscreen ? (
485 <div
486 ref={attachFullscreenChrome}
487 className="flex h-10 shrink-0 items-center justify-between border-border border-b px-3 text-sm"
488 >
489 <span className="truncate">{app.server}</span>
490 <Button
491 aria-label={gt`Exit full screen`}
492 size="icon-sm"
493 variant="ghost"
494 onClick={() => setDisplayMode("inline")}
495 >
496 <Minimize2Icon className="size-4" />
497 </Button>
498 </div>
499 ) : null}
500 {navigatedAway ? (
501 <p className="flex size-full items-center justify-center text-muted-foreground text-xs">
502 <T>
503 The <Var>{app.server}</Var> app left its page and was stopped
504 </T>
505 </p>
506 ) : src !== null ? (
507 <iframe
508 ref={attachFrame}
509 src={src}
510 title={gt`${{ server: app.server }} app`}
511 // Omitting allow-same-origin isolates the app from the session.
512 sandbox="allow-scripts allow-forms"
513 allow={mcpAppAllowAttribute(app.permissions)}
514 onLoad={onFrameLoad}
515 className={cn("block w-full border-0", fullscreen ? "min-h-0 flex-1" : "h-full")}
516 style={{ colorScheme: theme.appearance }}
517 />
518 ) : asset._tag === "Failure" ? (
519 <p className="flex size-full items-center justify-center text-muted-foreground text-xs">
520 <T>
521 Unable to load the <Var>{app.server}</Var> app
522 </T>
523 </p>
524 ) : null}
525 </div>
526 </div>
527 );