Open History to see the last commit
1import { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";
2import { act } from "react";
3import { createRoot, type Root } from "react-dom/client";
4import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
5import { page, userEvent } from "vite-plus/test/browser";
6
7import "~/index.css";
8
9// The app asks for full screen from its button. It also focuses its own frame
10// and asks on load, right after it is told it left full screen, and whenever
11// it loses focus while inline. It reports each answer to the page with a
12// message the host ignores.
13const APP_HTML = `<!doctype html><button>Open full screen</button><script>
14let nextId = 0;
15const pending = new Map();
16const request = (method, params) =>
17 new Promise((resolve) => {
18 nextId += 1;
19 pending.set(nextId, resolve);
20 parent.postMessage({ jsonrpc: "2.0", id: nextId, method, params }, "*");
21 });
22let mode = "inline";
23const askFullscreen = async (source) => {
24 const answer = await request("ui/request-display-mode", { mode: "fullscreen" });
25 mode = answer.mode;
26 parent.postMessage({ probe: source + ":" + answer.mode }, "*");
27};
28const button = document.querySelector("button");
29button.onclick = () => askFullscreen("tap");
30const refocusAndAsk = (source) => {
31 button.focus();
32 void askFullscreen(source);
33};
34addEventListener("message", ({ data }) => {
35 if (data === "retry") return refocusAndAsk("retry");
36 if (pending.has(data.id)) {
37 pending.get(data.id)(data.result);
38 pending.delete(data.id);
39 return;
40 }
41 if (data.method !== "ui/notifications/host-context-changed") return;
42 const left = mode === "fullscreen" && data.params.displayMode === "inline";
43 mode = data.params.displayMode ?? mode;
44 if (left) refocusAndAsk("exit");
45});
46// Focus can only be taken back once the browser has finished moving it away.
47addEventListener("blur", () => {
48 if (mode === "inline") setTimeout(() => refocusAndAsk("blur"));
49});
50void request("ui/initialize", { protocolVersion: "2026-01-26", appCapabilities: {} }).then(() => {
51 parent.postMessage({ jsonrpc: "2.0", method: "ui/notifications/initialized", params: {} }, "*");
52 refocusAndAsk("load");
53});
54</script>`;
55
56vi.mock(import("../../assets/assetUrls"), async (original) => ({
57 ...(await original()),
58 useAssetUrlState: (() => ({
59 _tag: "Success",
60 url: `data:text/html,${encodeURIComponent(APP_HTML)}`,
61 expiresAt: Date.now() + 60 * 60_000,
62 })) as never,
63 useAssetUrlRefresh: (() => async () => null) as never,
64}));
65vi.mock(import("../../state/queries"), async (original) => ({
66 ...(await original()),
67 useTurnItemDetail: (() => ({ data: undefined })) as never,
68}));
69vi.mock(import("../../state/use-atom-command"), async (original) => ({
70 ...(await original()),
71 useAtomCommand: (() => async () => ({ _tag: "Failure", cause: undefined })) as never,
72}));
73vi.mock(import("../../hooks/useHtmlRenderTheme"), async (original) => ({
74 ...(await original()),
75 useHtmlRenderTheme: (() => ({ appearance: "light", variables: {} })) as never,
76}));
77
78import { McpAppFrame } from "./McpAppFrame";
79
80let root: Root | undefined;
81let skew = 0;
82let answers: string[] = [];
83let answered: (() => void) | undefined;
84const onProbe = (event: MessageEvent) => {
85 const probe = (event.data as { readonly probe?: unknown } | null)?.probe;
86 if (typeof probe !== "string") return;
87 answers.push(probe);
88 answered?.();
89};
90const nextAnswer = async (action: () => Promise<unknown>) => {
91 const seen = answers.length;
92 const answer = new Promise<string>((resolve) => {
93 answered = () => {
94 if (answers.length > seen) resolve(answers[seen]!);
95 };
96 });
97 await action();
98 return answer;
99};
100
101beforeEach(() => {
102 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
103 answers = [];
104 answered = undefined;
105 skew = 0;
106 // Advance the host cooldown without manufacturing browser user activation.
107 const now = performance.now.bind(performance);
108 vi.spyOn(performance, "now").mockImplementation(() => now() + skew);
109 window.addEventListener("message", onProbe);
110});
111afterEach(async () => {
112 window.removeEventListener("message", onProbe);
113 if (root !== undefined) await act(async () => root?.unmount());
114 root = undefined;
115 document.body.replaceChildren();
116 vi.restoreAllMocks();
117 vi.unstubAllGlobals();
118});
119
120const isFullscreen = () => document.querySelector("[data-mcp-app-fullscreen]") !== null;
121
122const renderApp = async () => {
123 const container = document.body.appendChild(document.createElement("div"));
124 root = createRoot(container);
125 await act(async () =>
126 root?.render(
127 <McpAppFrame
128 environmentId={EnvironmentId.make("env")}
129 threadId={ThreadId.make("thread")}
130 conversationThreadId={ThreadId.make("thread")}
131 itemId={TurnItemId.make("item")}
132 revision="1"
133 app={{ attachmentId: "app", server: "srv", tool: "show", resourceUri: "ui://srv/app" }}
134 onSendMessage={undefined}
135 />,
136 ),
137 );
138};
139
140const retry = () =>
141 nextAnswer(async () => {
142 document.querySelector("iframe")!.contentWindow!.postMessage("retry", "*");
143 });
144
145it("keeps load and idle retries inline even after the page-input cooldown", async () => {
146 expect(await nextAnswer(renderApp)).toBe("load:inline");
147 skew += 5_000;
148 expect(await retry()).toBe("retry:inline");
149 expect(await retry()).toBe("retry:inline");
150 expect(isFullscreen()).toBe(false);
151});
152
153it("allows an app click immediately after loading on an idle page", async () => {
154 expect(await nextAnswer(renderApp)).toBe("load:inline");
155 const appButton = page
156 .frameLocator(page.getByTitle("srv app"))
157 .getByRole("button", { name: "Open full screen" });
158 expect(await nextAnswer(() => userEvent.click(appButton))).toBe("tap:fullscreen");
159 expect(isFullscreen()).toBe(true);
160});
161
162it("opens full screen only from a tap in the app, never from activation the page got elsewhere", async () => {
163 const appButton = page
164 .frameLocator(page.getByTitle("srv app"))
165 .getByRole("button", { name: "Open full screen" });
166 const elsewhere = document.body.appendChild(document.createElement("button"));
167 elsewhere.textContent = "Elsewhere";
168 const tapApp = async () => {
169 skew += 5_000;
170 expect(await nextAnswer(() => userEvent.click(appButton))).toBe("tap:fullscreen");
171 expect(isFullscreen()).toBe(true);
172 };
173
174 // The click that opens a thread still activates the page as its app loads.
175 const load = nextAnswer(async () => {
176 await userEvent.click(elsewhere);
177 await renderApp();
178 });
179 expect(await load).toBe("load:inline");
180 expect(isFullscreen()).toBe(false);
181
182 await tapApp();
183 const exit = page.getByRole("button", { name: "Exit full screen" });
184 expect(await nextAnswer(() => userEvent.click(exit))).toBe("exit:inline");
185 expect(isFullscreen()).toBe(false);
186
187 skew += 5_000;
188 expect(await nextAnswer(() => userEvent.click(elsewhere))).toBe("blur:inline");
189 expect(isFullscreen()).toBe(false);
190
191 // Escape activates nothing, but the tap that opened full screen still does.
192 await tapApp();
193 (await exit.element()).focus();
194 expect(await nextAnswer(() => userEvent.keyboard("{Escape}"))).toBe("exit:inline");
195 expect(isFullscreen()).toBe(false);
196});