Open History to see the last commit
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 = injectMcpAppDocumentBootstrap(`<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
41// What an app asks its host for: a resource, a tool call and a model-context update.
42const HOST_REQUESTS = `
43const ask = (id, method, params) => parent.postMessage({ jsonrpc: "2.0", id, method, params }, "*");
44ask("init", "ui/initialize", {});
45ask(1, "resources/read", { uri: "ui://demo/other" });
46ask(2, "tools/call", { name: "list", arguments: {} });
47ask(3, "ui/update-model-context", { content: [{ type: "text", text: "note" }] });
48${sizeChanged(777)}`;
49const REQUESTING_URL = `data:text/html,${encodeURIComponent(`<script>${HOST_REQUESTS}</script><iframe srcdoc="x"></iframe>`)}`;
50
51const asset = vi.hoisted(() => ({ html: "" }));
52const commands = vi.hoisted(() => ({ labels: [] as Array<string> }));
53const setup = (html: string) => {
54 asset.html = html;
55 commands.labels = [];
56};
57
58vi.mock(import("~/state/use-atom-command"), () => ({
59 useAtomCommand: ((command: { readonly label: string }) => async () => {
60 commands.labels.push(command.label);
61 return {
62 _tag: "Success",
63 value: { callable: true, readOnly: true, content: [], contents: [] },
64 };
65 }) as never,
66}));
67
68vi.mock(import("~/assets/longLivedAssetUrls"), () => ({
69 useLongLivedAssetUrl: () => ({
70 _tag: "Success",
71 url: `data:text/html,${encodeURIComponent(asset.html)}`,
72 expiresAt: Date.now() + 60 * 60_000,
73 }),
74}));
75
76import { McpAppFrame } from "./McpAppFrame";
77
78const nextInitializedFrom = () =>
79 new Promise<MessageEventSource>((resolve) => {
80 const listen = (event: MessageEvent) => {
81 if (event.source === null || event.data?.method !== "ui/notifications/initialized") return;
82 window.removeEventListener("message", listen);
83 resolve(event.source);
84 };
85 window.addEventListener("message", listen);
86 });
87
88describe("McpAppFrame", () => {
89 it("keeps a reopened app when the old document's second teardown finishes late", async () => {
90 setup(APP_HTML);
91 const firstInitialized = nextInitializedFrom();
92 await using screen = await render(
93 <McpAppFrame
94 environmentId={EnvironmentId.make("environment")}
95 threadId={ThreadId.make("thread")}
96 conversationThreadId={ThreadId.make("thread")}
97 itemId={TurnItemId.make("item")}
98 revision="1"
99 app={{
100 attachmentId: "attachment",
101 server: "Demo",
102 tool: "show",
103 resourceUri: "ui://demo/app",
104 }}
105 onSendMessage={undefined}
106 />,
107 );
108 const firstApp = await firstInitialized;
109 using _timers = fakeTimers();
110
111 (firstApp as Window).postMessage("close", "*");
112 await userEvent.click(screen.getByRole("button", { name: "Show app" }));
113 await expect.element(screen.getByTitle("Demo app")).toBeInTheDocument();
114
115 await act(() => vi.advanceTimersByTimeAsync(2_000));
116 expect(screen.getByRole("button", { name: "Show app" }).query()).toBeNull();
117 await expect.element(screen.getByTitle("Demo app")).toBeInTheDocument();
118 });
119
120 it("ignores a page the app's frame navigated to", async () => {
121 setup(NAVIGATING_APP_HTML);
122 const element = () => (
123 <McpAppFrame
124 environmentId={EnvironmentId.make("environment")}
125 threadId={ThreadId.make("thread")}
126 conversationThreadId={ThreadId.make("thread")}
127 itemId={TurnItemId.make("item")}
128 revision="1"
129 app={{
130 attachmentId: "attachment",
131 server: "Demo",
132 tool: "show",
133 resourceUri: "ui://demo/app",
134 }}
135 onSendMessage={undefined}
136 />
137 );
138 await using screen = await render(element());
139 const frame = screen.getByTitle("Demo app").element() as HTMLIFrameElement;
140 const row = frame.parentElement!.parentElement!;
141 // The app resizes only after the host's answer reached it, so the bridge works both ways.
142 await expect.element(row).toHaveStyle({ height: "321px" });
143
144 // A tool update hands the row an equal app in a new object, which re-attaches the host.
145 await screen.rerender(element());
146 frame.contentWindow!.postMessage("leave", "*");
147 await expect
148 .element(screen.getByText("The Demo app left its page and was stopped"))
149 .toBeInTheDocument();
150 expect(row.style.height).toBe("321px");
151 });
152
153 // A server that predates the document bootstrap serves the app without it.
154 it.each([
155 ["the app's own page", `<script>${HOST_REQUESTS}</script>`],
156 [
157 "a page the app navigated to",
158 `<script>location.href = ${JSON.stringify(REQUESTING_URL)};</script>`,
159 ],
160 ])("gives no bridge to %s when the document bootstrap is missing", async (_page, html) => {
161 setup(html);
162 await using screen = await render(
163 <McpAppFrame
164 environmentId={EnvironmentId.make("environment")}
165 threadId={ThreadId.make("thread")}
166 conversationThreadId={ThreadId.make("thread")}
167 itemId={TurnItemId.make("item")}
168 revision="1"
169 app={{
170 attachmentId: "attachment",
171 server: "Demo",
172 tool: "show",
173 resourceUri: "ui://demo/app",
174 }}
175 onSendMessage={undefined}
176 />,
177 );
178
179 await expect
180 .element(
181 screen.getByText(
182 "The Demo app needs a newer T3 Code server on this environment. Update the server to use it.",
183 ),
184 )
185 .toBeInTheDocument();
186 expect(screen.getByTitle("Demo app").query()).toBeNull();
187 expect(commands.labels).toEqual([]);
188 });
189
190 it("answers an app whose document carries the bootstrap", async () => {
191 setup(injectMcpAppDocumentBootstrap(`<script>${HOST_REQUESTS}</script>`));
192 await using screen = await render(
193 <McpAppFrame
194 environmentId={EnvironmentId.make("environment")}
195 threadId={ThreadId.make("thread")}
196 conversationThreadId={ThreadId.make("thread")}
197 itemId={TurnItemId.make("item")}
198 revision="1"
199 app={{
200 attachmentId: "attachment",
201 server: "Demo",
202 tool: "show",
203 resourceUri: "ui://demo/app",
204 }}
205 onSendMessage={undefined}
206 />,
207 );
208 const frame = screen.getByTitle("Demo app").element() as HTMLIFrameElement;
209 await expect.element(frame.parentElement!.parentElement!).toHaveStyle({ height: "777px" });
210 await vi.waitFor(() =>
211 expect(commands.labels.toSorted()).toEqual([
212 "environment-command:mcp-apps:call-tool",
213 "environment-command:mcp-apps:read-resource",
214 "environment-command:mcp-apps:tool-info",
215 "environment-command:mcp-apps:update-model-context",
216 ]),
217 );
218 });
219});