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