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

McpAppFrame.tsx

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