The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { Button } from "../../components/ui/Button"; |
| 2 | import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; |
| 3 | import * as Dialog from "../../components/ui/Dialog"; |
| 4 | import type { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts"; |
| 5 | import { |
| 6 | makeMcpAppHost, |
| 7 | McpAppHostRefusal, |
| 8 | mcpAppStyleVariables, |
| 9 | mcpResourceBytes, |
| 10 | type McpAppCallToolResult, |
| 11 | type McpAppHost, |
| 12 | type McpAppHostContext, |
| 13 | } from "@t3tools/client-runtime/mcp-apps"; |
| 14 | import { scopeThreadRef } from "@t3tools/client-runtime/environment"; |
| 15 | import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; |
| 16 | import { CommandId, MessageId } from "@t3tools/contracts"; |
| 17 | import { |
| 18 | mcpAppAllowAttribute, |
| 19 | mcpAppFileName, |
| 20 | mcpAppReferencesEqual, |
| 21 | type McpAppReference, |
| 22 | } from "@t3tools/shared/mcpApp"; |
| 23 | import * as Predicate from "effect/Predicate"; |
| 24 | import { AsyncResult } from "effect/reactivity"; |
| 25 | import Constants from "expo-constants"; |
| 26 | import { msg, T, useGT, Var } from "gt-react-native"; |
| 27 | import { useNavigation } from "@react-navigation/native"; |
| 28 | import { useEffect, useEffectEvent, useRef, useState } from "react"; |
| 29 | import { Platform, View } from "react-native"; |
| 30 | import { useSafeAreaInsets } from "react-native-safe-area-context"; |
| 31 | import { WebView, type WebViewMessageEvent } from "react-native-webview"; |
| 32 | |
| 33 | import { AppText as Text } from "../../components/ui/AppText"; |
| 34 | import { m } from "../../i18n/messages"; |
| 35 | import { shareGeneratedAttachment } from "../../lib/attachmentDownload"; |
| 36 | import { mobileHtmlRenderTheme } from "../../lib/htmlRenderTheme"; |
| 37 | import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; |
| 38 | import { uuidv4 } from "../../lib/uuid"; |
| 39 | import { webViewDecelerationRate } from "../../lib/webViewDecelerationRate"; |
| 40 | import { useAssetUrlState } from "../../state/assets"; |
| 41 | import { appAtomRegistry } from "../../state/atom-registry"; |
| 42 | import { useThreadShell } from "../../state/entities"; |
| 43 | import { mcpAppEnvironment } from "../../state/mcpApps"; |
| 44 | import { orchestrationEnvironment } from "../../state/orchestration"; |
| 45 | import { useEnvironmentQuery } from "../../state/query"; |
| 46 | import { enqueueThreadOutboxMessage } from "../../state/thread-outbox"; |
| 47 | import { useAtomCommand } from "../../state/use-atom-command"; |
| 48 | import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; |
| 49 | import { MCP_APP_INLINE_MAX_HEIGHT, mcpAppInlineHeight } from "./mcpAppSizing"; |
| 50 | |
| 51 | const ROW_BOTTOM_MARGIN = 8; |
| 52 | |
| 53 | // Android exposes `ReactNativeWebView` to every frame, so a frame nested in the |
| 54 | // app could post to React Native directly. The outer page therefore wraps what |
| 55 | // it relays with a secret only it holds, and React Native drops anything else. |
| 56 | // The relay also attests activation; the sandboxed app cannot set that flag. |
| 57 | function outerDocument(src: string, allow: string, secret: string) { |
| 58 | const attribute = (value: string) => |
| 59 | value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<"); |
| 60 | return `<!doctype html><html><head><meta name="viewport" content="width=device-width, initial-scale=1"> |
| 61 | <style>html,body{margin:0;height:100%;background:transparent}iframe{border:0;display:block;width:100%;height:100%}</style></head> |
| 62 | <body><iframe id="app" sandbox="allow-scripts allow-forms" allow="${attribute(allow)}"></iframe> |
| 63 | <script>(function(){var frame=document.getElementById("app"),secret=${JSON.stringify(secret)},loads=0,live=true; |
| 64 | var send=function(m){var u=navigator.userActivation;window.ReactNativeWebView.postMessage(JSON.stringify({secret:secret,active:!!(u&&u.isActive)&&document.activeElement===frame,message:m}));}; |
| 65 | frame.addEventListener("load",function(){loads+=1;if(loads>1&&live){live=false;send({t3:"navigated"});}}); |
| 66 | window.addEventListener("message",function(e){if(live&&e.source===frame.contentWindow)send(e.data);}); |
| 67 | window.__t3McpAppReceive=function(m){live&&frame.contentWindow&&frame.contentWindow.postMessage(m,"*");}; |
| 68 | frame.src=${JSON.stringify(src).replace(/</g, "\\u003c")};})();</script></body></html>`; |
| 69 | } |
| 70 | |
| 71 | const commandFailure = (result: { |
| 72 | readonly cause: Parameters<typeof squashAtomCommandFailure>[0]["cause"]; |
| 73 | }) => { |
| 74 | const error = squashAtomCommandFailure(result); |
| 75 | return new McpAppHostRefusal({ |
| 76 | message: |
| 77 | error instanceof Error && error.message.trim() !== "" ? error.message : "Request failed.", |
| 78 | }); |
| 79 | }; |
| 80 | |
| 81 | const confirm = (title: string, message: string, action: string) => |
| 82 | new Promise<boolean>((resolve) => { |
| 83 | Dialog.alert( |
| 84 | title, |
| 85 | message, |
| 86 | [ |
| 87 | { text: m(msg("Cancel")), style: "cancel", onPress: () => resolve(false) }, |
| 88 | { text: action, onPress: () => resolve(true) }, |
| 89 | ], |
| 90 | // Android dismisses earlier alerts when showing another; decline dismissed requests to release their slots. |
| 91 | { cancelable: true, onDismiss: () => resolve(false) }, |
| 92 | ); |
| 93 | }); |
| 94 | |
| 95 | const MAX_DOWNLOAD_BYTES = 25 * 1024 * 1024; |
| 96 | |
| 97 | // The feed omits tool input and output; the app needs both. |
| 98 | function storedToolCall( |
| 99 | item: { readonly type: string; readonly input?: unknown; readonly output?: unknown } | null, |
| 100 | ) { |
| 101 | if (item?.type !== "dynamic_tool") return undefined; |
| 102 | const output = item.output as { readonly result?: unknown } | undefined; |
| 103 | return { |
| 104 | arguments: item.input, |
| 105 | result: output?.result as McpAppCallToolResult | undefined, |
| 106 | }; |
| 107 | } |
| 108 | |
| 109 | /** WebViews reload when moved; tear down inline before opening fullscreen and recreate it on return. */ |
| 110 | export function ThreadMcpApp(props: { |
| 111 | readonly environmentId: EnvironmentId; |
| 112 | readonly threadId: ThreadId; |
| 113 | readonly conversationThreadId: ThreadId; |
| 114 | readonly itemId: TurnItemId; |
| 115 | readonly revision: string; |
| 116 | readonly app: McpAppReference; |
| 117 | readonly width: number; |
| 118 | readonly displayMode?: "inline" | "fullscreen"; |
| 119 | readonly onExitFullscreen?: () => void; |
| 120 | readonly height?: number; |
| 121 | }) { |
| 122 | const gt = useGT(); |
| 123 | const [height, setHeight] = useState(MCP_APP_INLINE_MAX_HEIGHT); |
| 124 | const [documentKey, setDocumentKeyState] = useState(0); |
| 125 | // The view keeps its first URL: a re-minted one would reload the app. |
| 126 | const [uri, setUri] = useState<string | null>(null); |
| 127 | const [loaded, setLoaded] = useState(false); |
| 128 | const [navigatedAway, setNavigatedAway] = useState(false); |
| 129 | // Equal app content must retain its reference to preserve the live document host. |
| 130 | // A different app needs a new document even when its asset URL is unchanged, |
| 131 | // so the WebView key moves on with the document key, not only the URL. |
| 132 | const [app, setApp] = useState(props.app); |
| 133 | if (!mcpAppReferencesEqual(app, props.app)) { |
| 134 | setApp(props.app); |
| 135 | setHeight(MCP_APP_INLINE_MAX_HEIGHT); |
| 136 | setUri(null); |
| 137 | setLoaded(false); |
| 138 | setNavigatedAway(false); |
| 139 | setDocumentKeyState((value) => value + 1); |
| 140 | } |
| 141 | const fullscreen = props.displayMode === "fullscreen"; |
| 142 | const navigation = useNavigation(); |
| 143 | const insets = useSafeAreaInsets(); |
| 144 | const [closed, setClosed] = useState(false); |
| 145 | const [presentedFullscreen, setPresentedFullscreen] = useState(false); |
| 146 | |
| 147 | const { themeId, themeAppearance, themeVariables, systemColorsActive } = |
| 148 | useAppearancePreferences(); |
| 149 | const theme = mobileHtmlRenderTheme({ |
| 150 | themeId, |
| 151 | appearance: themeAppearance, |
| 152 | variables: themeVariables, |
| 153 | systemColors: systemColorsActive, |
| 154 | platform: Platform.OS, |
| 155 | }); |
| 156 | const resource = { |
| 157 | _tag: "attachment" as const, |
| 158 | attachmentId: app.attachmentId, |
| 159 | fileName: mcpAppFileName(app), |
| 160 | mimeType: "text/html", |
| 161 | disposition: "inline" as const, |
| 162 | renderIntent: "mcp-app" as const, |
| 163 | }; |
| 164 | const asset = useAssetUrlState(props.environmentId, resource); |
| 165 | if (uri === null && asset._tag === "Success") setUri(asset.url); |
| 166 | const [generation, setGeneration] = useState(0); |
| 167 | const [crashed, setCrashed] = useState(false); |
| 168 | const restart = () => { |
| 169 | if (generation > 0) { |
| 170 | setCrashed(true); |
| 171 | return; |
| 172 | } |
| 173 | setLoaded(false); |
| 174 | setHeight(MCP_APP_INLINE_MAX_HEIGHT); |
| 175 | // Use the asset query's refreshed token when creating a replacement view. |
| 176 | if (asset._tag === "Success") setUri(asset.url); |
| 177 | setGeneration(1); |
| 178 | }; |
| 179 | const [secret] = useState(uuidv4); |
| 180 | const reopenDocument = () => { |
| 181 | setLoaded(false); |
| 182 | setHeight(MCP_APP_INLINE_MAX_HEIGHT); |
| 183 | setNavigatedAway(false); |
| 184 | if (asset._tag === "Success") setUri(asset.url); |
| 185 | setDocumentKeyState((value) => value + 1); |
| 186 | }; |
| 187 | const returnedFromFullscreen = useEffectEvent(() => { |
| 188 | reopenDocument(); |
| 189 | setPresentedFullscreen(false); |
| 190 | }); |
| 191 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Navigation focus is outside React; listen only while the app is presented full screen, and stop on unmount. |
| 192 | useEffect(() => { |
| 193 | if (!presentedFullscreen) return; |
| 194 | return navigation.addListener("focus", () => returnedFromFullscreen()); |
| 195 | }, [navigation, presentedFullscreen]); |
| 196 | |
| 197 | const detailAtom = orchestrationEnvironment.turnItem({ |
| 198 | environmentId: props.environmentId, |
| 199 | input: { threadId: props.threadId, itemId: props.itemId, revision: props.revision }, |
| 200 | }); |
| 201 | const toolInfo = useEnvironmentQuery( |
| 202 | mcpAppEnvironment.toolInfoQuery({ |
| 203 | environmentId: props.environmentId, |
| 204 | input: { threadId: props.threadId, itemId: props.itemId, name: app.tool }, |
| 205 | }), |
| 206 | ); |
| 207 | const toolDefinition = toolInfo.data?.tool; |
| 208 | |
| 209 | const callTool = useAtomCommand(mcpAppEnvironment.callTool, { reportFailure: false }); |
| 210 | const toolInfoCommand = useAtomCommand(mcpAppEnvironment.toolInfo, { reportFailure: false }); |
| 211 | const readResource = useAtomCommand(mcpAppEnvironment.readResource, { reportFailure: false }); |
| 212 | const updateModelContext = useAtomCommand(mcpAppEnvironment.updateModelContext, { |
| 213 | reportFailure: false, |
| 214 | }); |
| 215 | // Read current context per message without rebuilding the host and losing its session. |
| 216 | const conversation = useThreadShell( |
| 217 | scopeThreadRef(props.environmentId, props.conversationThreadId), |
| 218 | ); |
| 219 | const awaitingUser = |
| 220 | conversation?.hasPendingApprovals === true || conversation?.hasPendingUserInput === true; |
| 221 | const live = { |
| 222 | awaitingUser, |
| 223 | theme, |
| 224 | props, |
| 225 | asset, |
| 226 | callTool, |
| 227 | toolInfo: toolInfoCommand, |
| 228 | readResource, |
| 229 | updateModelContext, |
| 230 | insets, |
| 231 | toolDefinition, |
| 232 | navigation, |
| 233 | }; |
| 234 | const latest = useRef(live); |
| 235 | // The attached WebView owns its host; state lets the tool-call effect pair |
| 236 | // a host only with an atom from a render after that host existed. |
| 237 | const [host, setHost] = useState<McpAppHost | null>(null); |
| 238 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- resends host context to the MCP app host after commits that change theme, insets, tool or size |
| 239 | useEffect(() => { |
| 240 | const previous = latest.current; |
| 241 | latest.current = live; |
| 242 | // Building the context is not free, so resend only when one of its inputs changed. |
| 243 | if ( |
| 244 | previous.theme !== live.theme || |
| 245 | previous.insets !== live.insets || |
| 246 | previous.toolDefinition !== live.toolDefinition || |
| 247 | previous.props.width !== live.props.width || |
| 248 | previous.props.height !== live.props.height || |
| 249 | previous.props.displayMode !== live.props.displayMode |
| 250 | ) { |
| 251 | host?.updateHostContext(); |
| 252 | } |
| 253 | }); |
| 254 | // The host sends the call once the app initializes, so a stored item that |
| 255 | // lands late still reaches it. A completed call can arrive under a new |
| 256 | // revision, which is a new atom, so the host follows the current one. |
| 257 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes the MCP host to the current tool call |
| 258 | useEffect(() => { |
| 259 | if (host === null) return; |
| 260 | return appAtomRegistry.subscribe( |
| 261 | detailAtom, |
| 262 | (result) => { |
| 263 | const call = AsyncResult.isSuccess(result) ? storedToolCall(result.value.item) : undefined; |
| 264 | if (call !== undefined) host.setToolCall(call); |
| 265 | }, |
| 266 | { immediate: true }, |
| 267 | ); |
| 268 | }, [host, detailAtom]); |
| 269 | const userActive = useRef(false); |
| 270 | // Teardown completions check this so a replaced document's late callback is ignored. |
| 271 | const currentHost = useRef<McpAppHost | null>(null); |
| 272 | |
| 273 | // Each WebView document gets its own host: the view is keyed by document, |
| 274 | // restart generation and URL, and a changed app re-attaches this callback. |
| 275 | // Any other identity change would tear the host down, so per-render values |
| 276 | // are read through `latest`, never captured. |
| 277 | const attachWebView = (view: WebView<object> | null) => { |
| 278 | if (view === null) return; |
| 279 | const reloadInline = () => { |
| 280 | setLoaded(false); |
| 281 | setHeight(MCP_APP_INLINE_MAX_HEIGHT); |
| 282 | setNavigatedAway(false); |
| 283 | const current = latest.current.asset; |
| 284 | if (current._tag === "Success") setUri(current.url); |
| 285 | setDocumentKeyState((value) => value + 1); |
| 286 | }; |
| 287 | const scope = () => { |
| 288 | const { environmentId, threadId, itemId } = latest.current.props; |
| 289 | return { environmentId, input: { threadId, itemId } }; |
| 290 | }; |
| 291 | const hostContext = (): McpAppHostContext => { |
| 292 | const current = latest.current; |
| 293 | const isFullscreen = current.props.displayMode === "fullscreen"; |
| 294 | return { |
| 295 | theme: current.theme.appearance, |
| 296 | styles: { variables: mcpAppStyleVariables(current.theme.variables) }, |
| 297 | displayMode: isFullscreen ? "fullscreen" : "inline", |
| 298 | availableDisplayModes: ["inline", "fullscreen"], |
| 299 | containerDimensions: isFullscreen |
| 300 | ? { |
| 301 | width: current.props.width, |
| 302 | height: current.props.height ?? MCP_APP_INLINE_MAX_HEIGHT, |
| 303 | } |
| 304 | : { width: current.props.width, maxHeight: MCP_APP_INLINE_MAX_HEIGHT }, |
| 305 | platform: "mobile", |
| 306 | locale: Intl.DateTimeFormat().resolvedOptions().locale, |
| 307 | timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone, |
| 308 | userAgent: `t3-code/${Constants.expoConfig?.version ?? "0.0.0"}`, |
| 309 | deviceCapabilities: { touch: true, hover: false }, |
| 310 | safeAreaInsets: isFullscreen |
| 311 | ? { top: 0, right: current.insets.right, bottom: 0, left: current.insets.left } |
| 312 | : { top: 0, right: 0, bottom: 0, left: 0 }, |
| 313 | ...(current.toolDefinition === undefined |
| 314 | ? {} |
| 315 | : { toolInfo: { tool: current.toolDefinition } }), |
| 316 | }; |
| 317 | }; |
| 318 | const documentHost: McpAppHost = makeMcpAppHost({ |
| 319 | app, |
| 320 | hostVersion: Constants.expoConfig?.version ?? "0.0.0", |
| 321 | post: (message) => |
| 322 | view.injectJavaScript( |
| 323 | `window.__t3McpAppReceive&&window.__t3McpAppReceive(${JSON.stringify(message)});true;`, |
| 324 | ), |
| 325 | hostContext, |
| 326 | callTool: async ({ name, arguments: args }) => { |
| 327 | const { environmentId, input } = scope(); |
| 328 | const info = await latest.current.toolInfo({ environmentId, input: { ...input, name } }); |
| 329 | if (info._tag !== "Success") throw commandFailure(info); |
| 330 | if (!info.value.callable) |
| 331 | throw new McpAppHostRefusal({ message: "This app cannot call that tool." }); |
| 332 | if ( |
| 333 | !info.value.readOnly && |
| 334 | !(await confirm( |
| 335 | m( |
| 336 | msg("Allow {server} to run {tool}?", { |
| 337 | server: app.server, |
| 338 | tool: info.value.title ?? name, |
| 339 | }), |
| 340 | ), |
| 341 | JSON.stringify(args, null, 2), |
| 342 | m(msg("Allow", { $context: "verb, confirm button" })), |
| 343 | )) |
| 344 | ) { |
| 345 | throw new McpAppHostRefusal({ message: "Declined by the user." }); |
| 346 | } |
| 347 | const result = await latest.current.callTool({ |
| 348 | environmentId, |
| 349 | input: { ...input, name, arguments: args }, |
| 350 | }); |
| 351 | if (result._tag !== "Success") throw commandFailure(result); |
| 352 | return result.value; |
| 353 | }, |
| 354 | readResource: async ({ uri: resourceUri }) => { |
| 355 | const { environmentId, input } = scope(); |
| 356 | const result = await latest.current.readResource({ |
| 357 | environmentId, |
| 358 | input: { ...input, uri: resourceUri }, |
| 359 | }); |
| 360 | if (result._tag !== "Success") throw commandFailure(result); |
| 361 | return result.value; |
| 362 | }, |
| 363 | openLink: async (url) => { |
| 364 | // WebViews cannot prove user activation; confirm links to prevent timer-driven navigation out of T3. |
| 365 | if ( |
| 366 | !(await confirm( |
| 367 | m(msg("Open a link from {server}?", { server: app.server })), |
| 368 | url, |
| 369 | m(msg("Open", { $context: "verb, opens a link" })), |
| 370 | )) |
| 371 | ) { |
| 372 | throw new McpAppHostRefusal({ message: "Declined by the user." }); |
| 373 | } |
| 374 | if (!(await tryOpenExternalUrl(url, "mcp-app"))) { |
| 375 | throw new McpAppHostRefusal({ message: "The link could not be opened." }); |
| 376 | } |
| 377 | }, |
| 378 | sendMessage: async (text) => { |
| 379 | if ( |
| 380 | !(await confirm( |
| 381 | m(msg("Send this message from {server}?", { server: app.server })), |
| 382 | text, |
| 383 | m(msg("Send", { $context: "verb, sends the message" })), |
| 384 | )) |
| 385 | ) { |
| 386 | throw new McpAppHostRefusal({ message: "Declined by the user." }); |
| 387 | } |
| 388 | await enqueueThreadOutboxMessage({ |
| 389 | environmentId: latest.current.props.environmentId, |
| 390 | threadId: latest.current.props.conversationThreadId, |
| 391 | messageId: MessageId.make(uuidv4()), |
| 392 | commandId: CommandId.make(uuidv4()), |
| 393 | text, |
| 394 | attachments: [], |
| 395 | dispatchMode: "queue", |
| 396 | createdAt: new Date().toISOString(), |
| 397 | }); |
| 398 | }, |
| 399 | updateModelContext: async (context) => { |
| 400 | const { environmentId, input } = scope(); |
| 401 | const result = await latest.current.updateModelContext({ |
| 402 | environmentId, |
| 403 | input: { |
| 404 | ...input, |
| 405 | ...context, |
| 406 | conversationThreadId: latest.current.props.conversationThreadId, |
| 407 | }, |
| 408 | }); |
| 409 | if (result._tag !== "Success") throw commandFailure(result); |
| 410 | }, |
| 411 | requestDisplayMode: async (mode) => { |
| 412 | const current = latest.current.props; |
| 413 | // receive dispatches synchronously; read activation before awaiting teardown. |
| 414 | if ( |
| 415 | mode === "fullscreen" && |
| 416 | (!userActive.current || |
| 417 | latest.current.awaitingUser || |
| 418 | !latest.current.navigation.isFocused()) |
| 419 | ) { |
| 420 | return current.displayMode ?? "inline"; |
| 421 | } |
| 422 | if (mode === "fullscreen" && current.displayMode !== "fullscreen") { |
| 423 | await documentHost.teardown(); |
| 424 | // A crash restart or reload during the wait already replaced this document. |
| 425 | if (currentHost.current !== documentHost) return "inline"; |
| 426 | // Approval arrival or navigation during the wait requires reloading inline. |
| 427 | const navigation = latest.current.navigation; |
| 428 | if (latest.current.awaitingUser || !navigation.isFocused()) { |
| 429 | reloadInline(); |
| 430 | return "inline"; |
| 431 | } |
| 432 | setPresentedFullscreen(true); |
| 433 | navigation.navigate("ThreadMcpApp", { |
| 434 | environmentId: String(current.environmentId), |
| 435 | threadId: String(current.threadId), |
| 436 | conversationThreadId: String(current.conversationThreadId), |
| 437 | itemId: String(current.itemId), |
| 438 | revision: current.revision, |
| 439 | }); |
| 440 | return "fullscreen"; |
| 441 | } |
| 442 | if (mode === "inline" && current.displayMode === "fullscreen") { |
| 443 | await documentHost.teardown(); |
| 444 | if (currentHost.current === documentHost) current.onExitFullscreen?.(); |
| 445 | return "inline"; |
| 446 | } |
| 447 | return current.displayMode ?? "inline"; |
| 448 | }, |
| 449 | downloadFile: async (files) => { |
| 450 | const names = files.map((file) => file.name).join(", "); |
| 451 | if ( |
| 452 | !(await confirm( |
| 453 | m(msg("Save a file from {server}?", { server: app.server })), |
| 454 | names, |
| 455 | m(msg("Save", { $context: "verb, confirm button" })), |
| 456 | )) |
| 457 | ) { |
| 458 | throw new McpAppHostRefusal({ message: "Declined by the user." }); |
| 459 | } |
| 460 | for (const file of files) { |
| 461 | let bytes: Uint8Array | undefined; |
| 462 | let mimeType = file.mimeType ?? "application/octet-stream"; |
| 463 | if (file._tag === "embedded") { |
| 464 | bytes = file.bytes; |
| 465 | } else { |
| 466 | const { environmentId, input } = scope(); |
| 467 | const read = await latest.current.readResource({ |
| 468 | environmentId, |
| 469 | input: { ...input, uri: file.uri }, |
| 470 | }); |
| 471 | if (read._tag !== "Success") throw commandFailure(read); |
| 472 | const content = read.value.contents[0]; |
| 473 | bytes = mcpResourceBytes(content); |
| 474 | const declared = (content as { readonly mimeType?: unknown } | undefined)?.mimeType; |
| 475 | if (typeof declared === "string") mimeType = declared; |
| 476 | } |
| 477 | if (bytes === undefined) |
| 478 | throw new McpAppHostRefusal({ message: `${file.name} has no contents.` }); |
| 479 | if (bytes.byteLength > MAX_DOWNLOAD_BYTES) { |
| 480 | throw new McpAppHostRefusal({ message: `${file.name} is too large to save.` }); |
| 481 | } |
| 482 | const shared = await shareGeneratedAttachment({ |
| 483 | bytes, |
| 484 | attachment: { name: file.name, mimeType }, |
| 485 | signal: new AbortController().signal, |
| 486 | }); |
| 487 | if (!shared) |
| 488 | throw new McpAppHostRefusal({ message: "Sharing is not available on this device." }); |
| 489 | } |
| 490 | }, |
| 491 | onRequestTeardown: () => { |
| 492 | const current = latest.current.props; |
| 493 | void documentHost.teardown().then(() => { |
| 494 | if (currentHost.current !== documentHost) return; |
| 495 | if (current.displayMode === "fullscreen") current.onExitFullscreen?.(); |
| 496 | else setClosed(true); |
| 497 | }); |
| 498 | }, |
| 499 | onSizeChanged: (size) => { |
| 500 | if (latest.current.props.displayMode === "fullscreen") return; |
| 501 | const nextHeight = mcpAppInlineHeight(size.height); |
| 502 | if (nextHeight !== undefined) setHeight(nextHeight); |
| 503 | }, |
| 504 | }); |
| 505 | setHost(documentHost); |
| 506 | currentHost.current = documentHost; |
| 507 | return () => { |
| 508 | if (currentHost.current === documentHost) currentHost.current = null; |
| 509 | // An unmount cannot wait: the request goes out before the view does. |
| 510 | void documentHost.teardown(); |
| 511 | setHost((current) => (current === documentHost ? null : current)); |
| 512 | }; |
| 513 | }; |
| 514 | |
| 515 | const source = |
| 516 | uri === null |
| 517 | ? null |
| 518 | : { html: outerDocument(uri, mcpAppAllowAttribute(app.permissions), secret) }; |
| 519 | |
| 520 | if (presentedFullscreen) { |
| 521 | return ( |
| 522 | <View |
| 523 | style={{ height, marginBottom: ROW_BOTTOM_MARGIN }} |
| 524 | className="items-center justify-center rounded-lg border border-border" |
| 525 | > |
| 526 | <Text className="text-sm text-foreground-muted"> |
| 527 | <T> |
| 528 | The <Var>{app.server}</Var> app is open full screen |
| 529 | </T> |
| 530 | </Text> |
| 531 | </View> |
| 532 | ); |
| 533 | } |
| 534 | |
| 535 | if (closed) { |
| 536 | return ( |
| 537 | <View |
| 538 | style={{ height, marginBottom: ROW_BOTTOM_MARGIN }} |
| 539 | className="items-center justify-center gap-2 rounded-lg border border-border" |
| 540 | > |
| 541 | <Text className="text-sm text-foreground-muted"> |
| 542 | <T> |
| 543 | The <Var>{app.server}</Var> app was closed |
| 544 | </T> |
| 545 | </Text> |
| 546 | <View className="items-center"> |
| 547 | <Button |
| 548 | label={gt("Show app")} |
| 549 | tone="secondary" |
| 550 | onPress={() => { |
| 551 | reopenDocument(); |
| 552 | setClosed(false); |
| 553 | }} |
| 554 | /> |
| 555 | </View> |
| 556 | </View> |
| 557 | ); |
| 558 | } |
| 559 | |
| 560 | return ( |
| 561 | <View style={fullscreen ? { flex: 1 } : { height, marginBottom: ROW_BOTTOM_MARGIN }}> |
| 562 | {navigatedAway ? ( |
| 563 | <View className="flex-1 items-center justify-center"> |
| 564 | <Text className="text-sm text-foreground-muted"> |
| 565 | <T> |
| 566 | The <Var>{app.server}</Var> app left its page and was stopped |
| 567 | </T> |
| 568 | </Text> |
| 569 | </View> |
| 570 | ) : uri !== null && !crashed ? ( |
| 571 | <WebView<object> |
| 572 | key={`${documentKey}:${generation}:${uri}`} |
| 573 | ref={attachWebView} |
| 574 | onContentProcessDidTerminate={restart} |
| 575 | onRenderProcessGone={restart} |
| 576 | source={source!} |
| 577 | accessibilityLabel={gt("{server} app", { server: app.server })} |
| 578 | style={{ flex: 1, backgroundColor: "transparent" }} |
| 579 | nestedScrollEnabled |
| 580 | decelerationRate={webViewDecelerationRate} |
| 581 | originWhitelist={["*"]} |
| 582 | // Android misreports nested frames as top-level; rely on iframe sandboxing there and gate navigation elsewhere. |
| 583 | onShouldStartLoadWithRequest={(request) => |
| 584 | Platform.OS === "android" || |
| 585 | request.isTopFrame === false || |
| 586 | request.url === "about:blank" |
| 587 | } |
| 588 | setSupportMultipleWindows={false} |
| 589 | onLoadEnd={() => setLoaded(true)} |
| 590 | onError={() => setCrashed(true)} |
| 591 | onHttpError={() => setCrashed(true)} |
| 592 | onMessage={(event: WebViewMessageEvent) => { |
| 593 | let envelope: unknown; |
| 594 | try { |
| 595 | envelope = JSON.parse(event.nativeEvent.data); |
| 596 | } catch { |
| 597 | return; |
| 598 | } |
| 599 | if (!Predicate.isObject(envelope) || envelope.secret !== secret) return; |
| 600 | const message = envelope.message; |
| 601 | if (Predicate.isObject(message) && message.t3 === "navigated") { |
| 602 | host?.dispose(); |
| 603 | setNavigatedAway(true); |
| 604 | return; |
| 605 | } |
| 606 | userActive.current = envelope.active === true; |
| 607 | host?.receive(message); |
| 608 | userActive.current = false; |
| 609 | }} |
| 610 | /> |
| 611 | ) : asset._tag === "Failure" || crashed ? ( |
| 612 | <View className="flex-1 items-center justify-center"> |
| 613 | <Text className="text-sm text-foreground-muted"> |
| 614 | <T> |
| 615 | Unable to load the <Var>{app.server}</Var> app |
| 616 | </T> |
| 617 | </Text> |
| 618 | </View> |
| 619 | ) : null} |
| 620 | {uri !== null && !loaded && !crashed && !navigatedAway ? ( |
| 621 | <View pointerEvents="none" className="absolute inset-0 items-center justify-center"> |
| 622 | <AppActivityIndicator /> |
| 623 | </View> |
| 624 | ) : null} |
| 625 | </View> |
| 626 | ); |
| 627 | } |