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

McpAppFrame.tsx

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