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

McpAppFrame.browser.test.tsx

130 lines5.1 KB

1import { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";
2import { describe, expect, it, vi } from "vite-plus/test";
3import { userEvent } from "vite-plus/test/browser";
4​
5import { injectMcpAppDocumentBootstrap } from "@t3tools/shared/mcpApp";
6​
7import "~/index.css";
8import { act, fakeTimers, render } from "../../../test/render";
9​
10// Asks to close twice when told to, and answers only the first teardown, so
11// the second one is left to finish on the host's timeout.
12const APP_HTML = `<script>
13let answered = false;
14addEventListener("message", (event) => {
15 const message = event.data;
16 if (message === "close") {
17 parent.postMessage({ jsonrpc: "2.0", method: "ui/notifications/request-teardown" }, "*");
18 parent.postMessage({ jsonrpc: "2.0", method: "ui/notifications/request-teardown" }, "*");
19 } else if (message?.method === "ui/resource-teardown" && !answered) {
20 answered = true;
21 parent.postMessage({ jsonrpc: "2.0", id: message.id, result: {} }, "*");
22 }
23});
24parent.postMessage({ jsonrpc: "2.0", method: "ui/notifications/initialized" }, "*");
25</script>`;
26​
27const sizeChanged = (height: number) =>
28 `parent.postMessage({ jsonrpc: "2.0", method: "ui/notifications/size-changed", params: { height: ${height} } }, "*");`;
29// What the app's frame shows after the app follows a link: another page in the same window.
30// Its nested frame keeps `load`, which stops the app, from firing before its message arrives.
31const REPLACEMENT_URL = `data:text/html,${encodeURIComponent(`<script>${sizeChanged(777)}</script><iframe srcdoc="x"></iframe>`)}`;
32// Served as the server serves an app: the document bootstrap is its first script.
33const NAVIGATING_APP_HTML = injectMcpAppDocumentBootstrap(`<script>
34addEventListener("message", (event) => {
35 if (event.data === "leave") location.href = ${JSON.stringify(REPLACEMENT_URL)};
36 else if (event.data?.id === "init") ${sizeChanged(321)}
37});
38parent.postMessage({ jsonrpc: "2.0", id: "init", method: "ui/initialize", params: {} }, "*");
39</script>`);
40​
41const asset = vi.hoisted(() => ({ html: "" }));
42const setup = (html: string) => {
43 asset.html = html;
44};
45​
46vi.mock(import("~/assets/longLivedAssetUrls"), () => ({
47 useLongLivedAssetUrl: () => ({
48 _tag: "Success",
49 url: `data:text/html,${encodeURIComponent(asset.html)}`,
50 expiresAt: Date.now() + 60 * 60_000,
51 }),
52}));
53​
54import { McpAppFrame } from "./McpAppFrame";
55​
56const nextInitializedFrom = () =>
57 new Promise<MessageEventSource>((resolve) => {
58 const listen = (event: MessageEvent) => {
59 if (event.source === null || event.data?.method !== "ui/notifications/initialized") return;
60 window.removeEventListener("message", listen);
61 resolve(event.source);
62 };
63 window.addEventListener("message", listen);
64 });
65​
66describe("McpAppFrame", () => {
67 it("keeps a reopened app when the old document's second teardown finishes late", async () => {
68 setup(APP_HTML);
69 const firstInitialized = nextInitializedFrom();
70 await using screen = await render(
71 <McpAppFrame
72 environmentId={EnvironmentId.make("environment")}
73 threadId={ThreadId.make("thread")}
74 conversationThreadId={ThreadId.make("thread")}
75 itemId={TurnItemId.make("item")}
76 revision="1"
77 app={{
78 attachmentId: "attachment",
79 server: "Demo",
80 tool: "show",
81 resourceUri: "ui://demo/app",
82 }}
83 onSendMessage={undefined}
84 />,
85 );
86 const firstApp = await firstInitialized;
87 using _timers = fakeTimers();
88​
89 (firstApp as Window).postMessage("close", "*");
90 await userEvent.click(screen.getByRole("button", { name: "Show app" }));
91 await expect.element(screen.getByTitle("Demo app")).toBeInTheDocument();
92​
93 await act(() => vi.advanceTimersByTimeAsync(2_000));
94 expect(screen.getByRole("button", { name: "Show app" }).query()).toBeNull();
95 await expect.element(screen.getByTitle("Demo app")).toBeInTheDocument();
96 });
97​
98 it("ignores a page the app's frame navigated to", async () => {
99 setup(NAVIGATING_APP_HTML);
100 const element = () => (
101 <McpAppFrame
102 environmentId={EnvironmentId.make("environment")}
103 threadId={ThreadId.make("thread")}
104 conversationThreadId={ThreadId.make("thread")}
105 itemId={TurnItemId.make("item")}
106 revision="1"
107 app={{
108 attachmentId: "attachment",
109 server: "Demo",
110 tool: "show",
111 resourceUri: "ui://demo/app",
112 }}
113 onSendMessage={undefined}
114 />
115 );
116 await using screen = await render(element());
117 const frame = screen.getByTitle("Demo app").element() as HTMLIFrameElement;
118 const row = frame.parentElement!.parentElement!;
119 // The app resizes only after the host's answer reached it, so the bridge works both ways.
120 await expect.element(row).toHaveStyle({ height: "321px" });
121​
122 // A tool update hands the row an equal app in a new object, which re-attaches the host.
123 await screen.rerender(element());
124 frame.contentWindow!.postMessage("leave", "*");
125 await expect
126 .element(screen.getByText("The Demo app left its page and was stopped"))
127 .toBeInTheDocument();
128 expect(row.style.height).toBe("321px");
129 });
130});