TypeScript
fix(client): MCP apps can no longer trap you in full screen; it opens only after a tap (#18548)
shivame52bdf430b1d
diff --git a/apps/mobile/src/features/threads/McpAppWebView.tsx b/apps/mobile/src/features/threads/McpAppWebView.tsxindex 10c50e0aaf1..9e99f29864c 100644--- a/apps/mobile/src/features/threads/McpAppWebView.tsx+++ b/apps/mobile/src/features/threads/McpAppWebView.tsx@@ -47,6 +47,7 @@ const ROW_BOTTOM_MARGIN = 8;// Android exposes `ReactNativeWebView` to every frame, so a frame nested in the// app could post to React Native directly. The outer page therefore wraps what// it relays with a secret only it holds, and React Native drops anything else.+// The relay also attests activation; the sandboxed app cannot set that flag.function outerDocument(src: string, allow: string, secret: string) {const attribute = (value: string) =>value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");@@ -54,7 +55,7 @@ function outerDocument(src: string, allow: string, secret: string) {<style>html,body{margin:0;height:100%;background:transparent}iframe{border:0;display:block;width:100%;height:100%}</style></head><body><iframe id="app" sandbox="allow-scripts allow-forms" allow="${attribute(allow)}"></iframe><script>(function(){var frame=document.getElementById("app"),secret=${JSON.stringify(secret)},loads=0,live=true;-var send=function(m){window.ReactNativeWebView.postMessage(JSON.stringify({secret:secret,message:m}));};+var send=function(m){var u=navigator.userActivation;window.ReactNativeWebView.postMessage(JSON.stringify({secret:secret,active:!!(u&&u.isActive)&&document.activeElement===frame,message:m}));};frame.addEventListener("load",function(){loads+=1;if(loads>1&&live){live=false;send({t3:"navigated"});}});window.addEventListener("message",function(e){if(live&&e.source===frame.contentWindow)send(e.data);});window.__t3McpAppReceive=function(m){live&&frame.contentWindow&&frame.contentWindow.postMessage(m,"*");};@@ -248,6 +249,7 @@ export function ThreadMcpApp(props: {}, [props.environmentId, props.threadId, props.itemId, app.tool]);const webView = useRef<WebView<object>>(null);const hostRef = useRef<McpAppHost | null>(null);+ const userActive = useRef(false);useEffect(() => {if (uri === null) return;@@ -360,9 +362,12 @@ export function ThreadMcpApp(props: {},requestDisplayMode: async (mode) => {const current = latest.current.props;+ // receive dispatches synchronously; read activation before awaiting teardown.if (mode === "fullscreen" &&- (latest.current.awaitingUser || !latest.current.navigation.isFocused())+ (!userActive.current ||+ latest.current.awaitingUser ||+ !latest.current.navigation.isFocused())) {return current.displayMode ?? "inline";}@@ -545,7 +550,9 @@ export function ThreadMcpApp(props: {setNavigatedAway(true);return;}+ userActive.current = envelope.active === true;hostRef.current?.receive(message);+ userActive.current = false;}}/>) : asset._tag === "Failure" || crashed ? (diff --git a/apps/web/src/components/chat/McpAppFrame.browser.test.tsx b/apps/web/src/components/chat/McpAppFrame.browser.test.tsxnew file mode 100644index 00000000000..7af9130dc13--- /dev/null+++ b/apps/web/src/components/chat/McpAppFrame.browser.test.tsx@@ -0,0 +1,196 @@+import { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";+import { page, userEvent } from "vite-plus/test/browser";++import "~/index.css";++// The app asks for full screen from its button. It also focuses its own frame+// and asks on load, right after it is told it left full screen, and whenever+// it loses focus while inline. It reports each answer to the page with a+// message the host ignores.+const APP_HTML = `<!doctype html><button>Open full screen</button><script>+let nextId = 0;+const pending = new Map();+const request = (method, params) =>+ new Promise((resolve) => {+ nextId += 1;+ pending.set(nextId, resolve);+ parent.postMessage({ jsonrpc: "2.0", id: nextId, method, params }, "*");+ });+let mode = "inline";+const askFullscreen = async (source) => {+ const answer = await request("ui/request-display-mode", { mode: "fullscreen" });+ mode = answer.mode;+ parent.postMessage({ probe: source + ":" + answer.mode }, "*");+};+const button = document.querySelector("button");+button.onclick = () => askFullscreen("tap");+const refocusAndAsk = (source) => {+ button.focus();+ void askFullscreen(source);+};+addEventListener("message", ({ data }) => {+ if (data === "retry") return refocusAndAsk("retry");+ if (pending.has(data.id)) {+ pending.get(data.id)(data.result);+ pending.delete(data.id);+ return;+ }+ if (data.method !== "ui/notifications/host-context-changed") return;+ const left = mode === "fullscreen" && data.params.displayMode === "inline";+ mode = data.params.displayMode ?? mode;+ if (left) refocusAndAsk("exit");+});+// Focus can only be taken back once the browser has finished moving it away.+addEventListener("blur", () => {+ if (mode === "inline") setTimeout(() => refocusAndAsk("blur"));+});+void request("ui/initialize", { protocolVersion: "2026-01-26", appCapabilities: {} }).then(() => {+ parent.postMessage({ jsonrpc: "2.0", method: "ui/notifications/initialized", params: {} }, "*");+ refocusAndAsk("load");+});+</script>`;++vi.mock(import("../../assets/assetUrls"), async (original) => ({+ ...(await original()),+ useAssetUrlState: (() => ({+ _tag: "Success",+ url: `data:text/html,${encodeURIComponent(APP_HTML)}`,+ expiresAt: Date.now() + 60 * 60_000,+ })) as never,+ useAssetUrlRefresh: (() => async () => null) as never,+}));+vi.mock(import("../../state/queries"), async (original) => ({+ ...(await original()),+ useTurnItemDetail: (() => ({ data: undefined })) as never,+}));+vi.mock(import("../../state/use-atom-command"), async (original) => ({+ ...(await original()),+ useAtomCommand: (() => async () => ({ _tag: "Failure", cause: undefined })) as never,+}));+vi.mock(import("../../hooks/useHtmlRenderTheme"), async (original) => ({+ ...(await original()),+ useHtmlRenderTheme: (() => ({ appearance: "light", variables: {} })) as never,+}));++import { McpAppFrame } from "./McpAppFrame";++let root: Root | undefined;+let skew = 0;+let answers: string[] = [];+let answered: (() => void) | undefined;+const onProbe = (event: MessageEvent) => {+ const probe = (event.data as { readonly probe?: unknown } | null)?.probe;+ if (typeof probe !== "string") return;+ answers.push(probe);+ answered?.();+};+const nextAnswer = async (action: () => Promise<unknown>) => {+ const seen = answers.length;+ const answer = new Promise<string>((resolve) => {+ answered = () => {+ if (answers.length > seen) resolve(answers[seen]!);+ };+ });+ await action();+ return answer;+};++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ answers = [];+ answered = undefined;+ skew = 0;+ // Advance the host cooldown without manufacturing browser user activation.+ const now = performance.now.bind(performance);+ vi.spyOn(performance, "now").mockImplementation(() => now() + skew);+ window.addEventListener("message", onProbe);+});+afterEach(async () => {+ window.removeEventListener("message", onProbe);+ if (root !== undefined) await act(async () => root?.unmount());+ root = undefined;+ document.body.replaceChildren();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++const isFullscreen = () => document.querySelector("[data-mcp-app-fullscreen]") !== null;++const renderApp = async () => {+ const container = document.body.appendChild(document.createElement("div"));+ root = createRoot(container);+ await act(async () =>+ root?.render(+ <McpAppFrame+ environmentId={EnvironmentId.make("env")}+ threadId={ThreadId.make("thread")}+ conversationThreadId={ThreadId.make("thread")}+ itemId={TurnItemId.make("item")}+ revision="1"+ app={{ attachmentId: "app", server: "srv", tool: "show", resourceUri: "ui://srv/app" }}+ onSendMessage={undefined}+ />,+ ),+ );+};++const retry = () =>+ nextAnswer(async () => {+ document.querySelector("iframe")!.contentWindow!.postMessage("retry", "*");+ });++it("keeps load and idle retries inline even after the page-input cooldown", async () => {+ expect(await nextAnswer(renderApp)).toBe("load:inline");+ skew += 5_000;+ expect(await retry()).toBe("retry:inline");+ expect(await retry()).toBe("retry:inline");+ expect(isFullscreen()).toBe(false);+});++it("allows an app click immediately after loading on an idle page", async () => {+ expect(await nextAnswer(renderApp)).toBe("load:inline");+ const appButton = page+ .frameLocator(page.getByTitle("srv app"))+ .getByRole("button", { name: "Open full screen" });+ expect(await nextAnswer(() => userEvent.click(appButton))).toBe("tap:fullscreen");+ expect(isFullscreen()).toBe(true);+});++it("opens full screen only from a tap in the app, never from activation the page got elsewhere", async () => {+ const appButton = page+ .frameLocator(page.getByTitle("srv app"))+ .getByRole("button", { name: "Open full screen" });+ const elsewhere = document.body.appendChild(document.createElement("button"));+ elsewhere.textContent = "Elsewhere";+ const tapApp = async () => {+ skew += 5_000;+ expect(await nextAnswer(() => userEvent.click(appButton))).toBe("tap:fullscreen");+ expect(isFullscreen()).toBe(true);+ };++ // The click that opens a thread still activates the page as its app loads.+ const load = nextAnswer(async () => {+ await userEvent.click(elsewhere);+ await renderApp();+ });+ expect(await load).toBe("load:inline");+ expect(isFullscreen()).toBe(false);++ await tapApp();+ const exit = page.getByRole("button", { name: "Exit full screen" });+ expect(await nextAnswer(() => userEvent.click(exit))).toBe("exit:inline");+ expect(isFullscreen()).toBe(false);++ skew += 5_000;+ expect(await nextAnswer(() => userEvent.click(elsewhere))).toBe("blur:inline");+ expect(isFullscreen()).toBe(false);++ // Escape activates nothing, but the tap that opened full screen still does.+ await tapApp();+ (await exit.element()).focus();+ expect(await nextAnswer(() => userEvent.keyboard("{Escape}"))).toBe("exit:inline");+ expect(isFullscreen()).toBe(false);+});diff --git a/apps/web/src/components/chat/McpAppFrame.tsx b/apps/web/src/components/chat/McpAppFrame.tsxindex 4dad28983cd..ff54f21960a 100644--- a/apps/web/src/components/chat/McpAppFrame.tsx+++ b/apps/web/src/components/chat/McpAppFrame.tsx@@ -48,6 +48,8 @@ const fullscreenSupported =typeof HTMLElement !== "undefined" && "popover" in HTMLElement.prototype;const MAX_DOWNLOAD_BYTES = 25 * 1024 * 1024;+// Exclude activation left by input elsewhere in T3.+const PAGE_ACTIVATION_MS = 5_000;function saveBlob(blob: Blob, name: string) {const url = URL.createObjectURL(blob);@@ -168,6 +170,21 @@ export function McpAppFrame(props: {latest.current = live;});+ // Frame input does not bubble here. An app can refocus itself, so focus+ // alone cannot exclude activation from input elsewhere in T3.+ const lastPageInputAt = useRef(Number.NEGATIVE_INFINITY);+ useEffect(() => {+ const note = () => {+ lastPageInputAt.current = performance.now();+ };+ if (navigator.userActivation?.isActive) note();+ const types = ["pointerdown", "pointerup", "touchend", "keydown"] as const;+ for (const type of types) window.addEventListener(type, note, true);+ return () => {+ for (const type of types) window.removeEventListener(type, note, true);+ };+ }, []);+useEffect(() => {const box = boxRef.current;if (box === null || !fullscreenSupported) return;@@ -343,7 +360,10 @@ export function McpAppFrame(props: {const otherFullscreen = document.querySelector("[data-mcp-app-fullscreen]");if (mode === "fullscreen" &&- (latest.current.props.awaitingUser === true ||+ (document.activeElement !== frameRef.current ||+ !navigator.userActivation?.isActive ||+ performance.now() - lastPageInputAt.current < PAGE_ACTIVATION_MS ||+ latest.current.props.awaitingUser === true ||isConfirmDialogActive() ||(otherFullscreen !== null && otherFullscreen !== boxRef.current))) {diff --git a/docs/user/html-renders.md b/docs/user/html-renders.mdindex f7e076a0f98..ac1ca0ef048 100644--- a/docs/user/html-renders.md+++ b/docs/user/html-renders.md@@ -14,4 +14,4 @@ Some MCP servers return an interactive app with their tool results, following thApps follow your theme. An app can call tools on its own server and post a message to the thread; T3 Code asks first unless the server marks the tool as read-only, and it asks before every message. On mobile, an app also asks before opening a link, and T3 Code asks before saving a file an app offers. An app stays viewable after its agent stops, but using it needs the agent of the thread that created it running, so send a message in that thread first if the app says it is unavailable. An app that navigates away from its own page is stopped.-An app can open full screen; use the button in its top corner, or press Escape outside the app, to return it to the thread. Anything else that needs your attention, such as an approval, also returns it to the thread. On mobile, full screen opens the app again in its own screen, so anything the app does not save itself starts over. An app can also keep the agent informed of what you did in it, such as a filter you picked; T3 Code sends the latest note from each app with your next message.+An app can open full screen right after you tap or click in it. On web and desktop, a tap in the app within five seconds of a click or key press elsewhere in T3 Code doesn't count, so tap it again after that. Use the button in its top corner, or press Escape outside the app, to return it to the thread. Anything else that needs your attention, such as an approval, also returns it to the thread. On mobile, full screen opens the app again in its own screen, so anything the app does not save itself starts over. An app can also keep the agent informed of what you did in it, such as a filter you picked; T3 Code sends the latest note from each app with your next message.