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

McpAppFrame.tsx

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