@mcpjam/widget-react 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/widget-host-context.tsx","../src/mcp-apps-utils.ts","../src/tool-result-utils.ts","../src/app-tools-registry.ts","../src/useToolInputStreaming.ts","../src/sandboxed-iframe.tsx","../src/mcp-apps-modal.tsx","../src/widget-file-messages.ts","../src/widget-surface-context.tsx","../src/widget-surface-store.ts","../src/mcp-apps-renderer.tsx","../src/widget-surface-host.tsx"],"names":["UIType","useCallback","SandboxedIframe","useRef","useState","useMemo","useEffect","jsx","createContext","useContext","create","recorderDebug","stableStringifyJson","useLayoutEffect","prefersBorder","toolCallId","resolvedPermissions","iframe","AppBridge","LoggingTransport","PostMessageTransport","extractMethod","toolName","jsxs","Fragment"],"mappings":";;;;;;;;;;;;;AASA,IAAM,iBAAA,GAAoB,cAAiC,IAAI,CAAA;AAQxD,SAAS,kBAAA,CAAmB;AAAA,EACjC,KAAA;AAAA,EACA;AACF,CAAA,EAA4B;AAC1B,EAAA,uBACE,GAAA,CAAC,iBAAA,CAAkB,QAAA,EAAlB,EAA2B,OACzB,QAAA,EACH,CAAA;AAEJ;AAOO,SAAS,aAAA,GAA4B;AAC1C,EAAA,MAAM,IAAA,GAAO,WAAW,iBAAiB,CAAA;AACzC,EAAA,IAAI,SAAS,IAAA,EAAM;AACjB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KAEF;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT;ACfO,IAAK,MAAA,qBAAAA,OAAAA,KAAL;AACL,EAAAA,QAAA,UAAA,CAAA,GAAW,UAAA;AACX,EAAAA,QAAA,YAAA,CAAA,GAAa,YAAA;AACb,EAAAA,QAAA,yBAAA,CAAA,GAA0B,yBAAA;AAC1B,EAAAA,QAAA,QAAA,CAAA,GAAS,QAAA;AAJC,EAAA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QACL,8BAAA,EAA4B,IAAA;AAAA,QAC5B,KAAA,EAAO;AAAA,UACL,MAAA,EAAQ,CAAA;AAAA,UACR,QAAA,EAAU,QAAA;AAAA,UACV,aAAA,EAAe,MAAA;AAAA,UACf,QAAA,EAAU,UAAA;AAAA,UACV,KAAA,EAAO;AAAA;AACT;AAAA,KACF;AAAA,IACC,OAAA,CAAQ,IAAI,CAAC,EAAE,WAAW,aAAA,EAAe,iBAAA,EAAmB,KAAA,EAAM,qBACjEA,GAAAA;AAAA,MAAC,mBAAA;AAAA,MAAA;AAAA,QAEC,aAAA;AAAA,QACA,iBAAA;AAAA,QACA,cAAA;AAAA,QACA,KAAA;AAAA,QACA;AAAA,OAAA;AAAA,MALK;AAAA,KAOR;AAAA,GAAA,EACH,CAAA;AAEJ","file":"index.js","sourcesContent":["import { createContext, useContext, type ReactNode } from \"react\";\nimport type { WidgetHost } from \"./widget-host\";\n\n// The package owns the `WidgetHost` React context + hook contract. The inspector\n// keeps the concrete host implementation (`use-widget-host.ts`, which reads its\n// stores/contexts) and feeds it through `<WidgetHostProvider>`. This is the\n// inversion the renderer relocation (3d) relies on: the moved renderer calls the\n// package's `useWidgetHost()` instead of the inspector's composite hook.\n\nconst WidgetHostContext = createContext<WidgetHost | null>(null);\n\nexport interface WidgetHostProviderProps {\n /** The concrete host the inspector builds from its stores/contexts. */\n value: WidgetHost;\n children: ReactNode;\n}\n\nexport function WidgetHostProvider({\n value,\n children,\n}: WidgetHostProviderProps) {\n return (\n <WidgetHostContext.Provider value={value}>\n {children}\n </WidgetHostContext.Provider>\n );\n}\n\n/**\n * Read the injected {@link WidgetHost}. Throws if no `<WidgetHostProvider>` is\n * mounted above — the package never reaches into inspector state itself, so a\n * missing provider is a wiring bug, not a fallback.\n */\nexport function useWidgetHost(): WidgetHost {\n const host = useContext(WidgetHostContext);\n if (host === null) {\n throw new Error(\n \"useWidgetHost must be used within a <WidgetHostProvider>. The inspector \" +\n \"supplies the concrete host via its use-widget-host adapter.\",\n );\n }\n return host;\n}\n","// UI-type detection for widget-bearing tool calls. Relocated from the inspector\n// (`@/lib/mcp-ui/mcp-apps-utils`) in Phase 3d-ii; depends only on ext-apps +\n// @mcp-ui/client + the SDK tool-visibility leaf. The inspector keeps the\n// `ListToolsResultWithMetadata`-typed `isMCPApp`/`isOpenAIApp` helpers (they\n// need an inspector api type) and re-exports this core.\nimport { isUIResource } from \"@mcp-ui/client\";\nimport { getToolUiResourceUri } from \"@modelcontextprotocol/ext-apps/app-bridge\";\n\n/**\n * Minimal structural shape `detectUiTypeFromTool` needs — just the `_meta` bag.\n * Kept structural (rather than importing `Tool` from\n * `@modelcontextprotocol/client`) so the package's public detection surface\n * doesn't pin a specific MCP SDK Tool type; any `{ _meta }`-bearing tool works.\n */\nexport interface ToolLike {\n _meta?: Record<string, unknown>;\n}\n\n// SEP-1865 tool-visibility helpers live in the framework-free SDK leaf so the\n// host bridge and the renderer share one model-only visibility check. Re-exported\n// here to preserve the existing `mcp-apps-utils` import surface.\nexport {\n getToolVisibility,\n isVisibleToModelOnly,\n isVisibleToAppOnly,\n} from \"@mcpjam/sdk/widget-runtime\";\n\nexport enum UIType {\n MCP_APPS = \"mcp-apps\",\n OPENAI_SDK = \"openai-sdk\",\n OPENAI_SDK_AND_MCP_APPS = \"openai-sdk-and-mcp-apps\",\n MCP_UI = \"mcp-ui\",\n}\n\nexport function detectUiTypeFromTool(tool: ToolLike): UIType | null {\n const toolMeta = tool._meta;\n if (!toolMeta) return null;\n return detectUIType(toolMeta, undefined);\n}\n\nexport function detectUIType(\n toolMeta: Record<string, unknown> | undefined,\n toolResult: unknown,\n): UIType | null {\n // 1. OpenAI SDK and MCP Apps: openai/outputTemplate AND ui.resourceUri\n if (\n toolMeta?.[\"openai/outputTemplate\"] &&\n getToolUiResourceUri({ _meta: toolMeta })\n ) {\n return UIType.OPENAI_SDK_AND_MCP_APPS;\n }\n\n // 2. OpenAI SDK: openai/outputTemplate\n if (toolMeta?.[\"openai/outputTemplate\"]) {\n return UIType.OPENAI_SDK;\n }\n\n // 3. MCP Apps (SEP-1865): ui.resourceUri\n if (getToolUiResourceUri({ _meta: toolMeta })) {\n return UIType.MCP_APPS;\n }\n\n // 4. MCP-UI: inline ui:// resource in result\n const directResource = (toolResult as { resource?: { uri?: string } })\n ?.resource;\n if (directResource?.uri?.startsWith(\"ui://\")) {\n return UIType.MCP_UI;\n }\n\n const content = (toolResult as { content?: unknown[] })?.content;\n if (Array.isArray(content)) {\n for (const item of content) {\n // isUIResource is a type guard; cast to any for the runtime check.\n if (isUIResource(item as any)) {\n return UIType.MCP_UI;\n }\n }\n }\n return null;\n}\n\nexport function getUIResourceUri(\n uiType: UIType | null,\n toolMeta: Record<string, unknown> | undefined,\n): string | null {\n switch (uiType) {\n case UIType.MCP_APPS:\n case UIType.OPENAI_SDK_AND_MCP_APPS:\n return getToolUiResourceUri({ _meta: toolMeta }) ?? null;\n case UIType.OPENAI_SDK:\n return (toolMeta?.[\"openai/outputTemplate\"] as string) ?? null;\n default:\n return null;\n }\n}\n","/**\n * Shared helpers for reading metadata and server IDs from tool results.\n *\n * Tool results may carry `_meta` and `_serverId` either at the top level or\n * nested under a `.value` wrapper. These utilities normalise access across both\n * shapes. Pure (no deps) — relocated from the inspector in Phase 3d-ii.\n */\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nexport function readToolResultObject(\n result: unknown,\n): Record<string, unknown> | undefined {\n if (!isRecord(result)) return undefined;\n return result;\n}\n\nexport function readToolResultMeta(\n result: unknown,\n): Record<string, unknown> | undefined {\n if (!isRecord(result)) return undefined;\n\n if (isRecord(result._meta)) {\n return result._meta;\n }\n\n if (isRecord(result.value) && isRecord(result.value._meta)) {\n return result.value._meta;\n }\n\n return undefined;\n}\n\nexport function readToolResultServerId(result: unknown): string | undefined {\n if (!isRecord(result)) return undefined;\n\n if (typeof result._serverId === \"string\") {\n return result._serverId;\n }\n\n if (isRecord(result.value) && typeof result.value._serverId === \"string\") {\n return result.value._serverId;\n }\n\n const meta = readToolResultMeta(result);\n return typeof meta?._serverId === \"string\" ? meta._serverId : undefined;\n}\n","/**\n * App-Provided Tools registry (SEP-1865).\n *\n * Each mounted MCP app iframe gets one entry here, keyed by a per-instance\n * `BridgeId`. Entries hold:\n * - The `AppBridge` ref used to dispatch `tools/call` into the iframe.\n * - The tools the app advertised via `tools/list` after `ui/initialize`.\n * - Opaque aliases (`app_<8hex>`) that act as the model-facing tool names.\n *\n * The registry serves two callers:\n * - `snapshotForChatBody()` — drained at chat POST time so the server can\n * register no-execute AI SDK tools that the model can pick.\n * - `resolve(alias)` — looked up by `useChat.onToolCall` to find the right\n * bridge to dispatch into.\n *\n * App-provided tools are exposed exactly as the app lists them. MCPJam keeps\n * the readonly bit for attribution and future policy, but does not force its\n * server-tool approval flow onto app-provided tools.\n */\n\nimport { useCallback } from \"react\";\nimport { create } from \"zustand\";\nimport { useShallow } from \"zustand/react/shallow\";\nimport type { AppBridge } from \"@modelcontextprotocol/ext-apps/app-bridge\";\nimport type { CallToolResult } from \"@modelcontextprotocol/client\";\n// Traffic logging is injected by the caller (the inspector chat/playground\n// dispatch hooks) rather than reached for via `@/stores`, so this registry\n// carries no inspector telemetry into the widget package (Tier-B).\nimport type { WidgetDebugSink } from \"./widget-host\";\n\n/** Injected traffic-log sink — `WidgetDebugSink[\"addTrafficLog\"]`. */\nexport type AddTrafficLog = WidgetDebugSink[\"addTrafficLog\"];\n\n/** Per-AppBridge instance identifier (independent of parentToolCallId). */\nexport type BridgeId = string;\n\nexport type AppToolDescriptor = NonNullable<\n Awaited<ReturnType<AppBridge[\"listTools\"]>>[\"tools\"]\n>[number];\n\nexport interface AppInstance {\n bridgeId: BridgeId;\n /** Chat session/lane that owns this rendered iframe. */\n chatSessionId?: string;\n /** The host tool call whose render mounted this iframe. */\n parentToolCallId: string;\n serverId: string;\n appName: string;\n appVersion?: string;\n surface: \"inline\" | \"modal\";\n bridge: AppBridge;\n tools: AppToolDescriptor[];\n registeredAtMs: number;\n /**\n * Accessor for the iframe DOM node that hosts this app instance. Lets\n * callers (e.g. `onToolCall`) scroll the iframe into view before\n * dispatching `tools/call`. Optional because legacy callers and tests\n * may not set it.\n */\n getIframeElement?: () => HTMLIFrameElement | null;\n}\n\nexport interface AppToolAlias {\n alias: string;\n bridgeId: BridgeId;\n rawName: string;\n /** Cached from `annotations.readOnlyHint === true`. */\n readOnly: boolean;\n}\n\n/** What the snapshot ships to the server in the chat POST body. */\nexport interface AppToolSnapshotEntry {\n alias: string;\n appName: string;\n appVersion?: string;\n serverId: string;\n parentToolCallId: string;\n rawName: string;\n description?: string;\n inputSchema?: Record<string, unknown>;\n readOnly: boolean;\n}\n\n// Server-mirrored limits for the chat POST snapshot.\nconst MAX_SNAPSHOT_ENTRIES = 64;\nconst MAX_DESCRIPTION_CHARS = 512;\nconst MAX_INPUT_SCHEMA_BYTES = 8 * 1024;\nconst ALIAS_REGEX = /^app_[a-z0-9]{8}$/i;\n\nexport interface AppToolAttribution {\n rawName: string;\n appName: string;\n}\n\ninterface AppToolsRegistryState {\n instancesByBridgeId: Map<BridgeId, AppInstance>;\n aliases: Map<string, AppToolAlias>;\n /** Active app-tool provider per chat-scoped host tool call. */\n activeBridgeByParent: Map<string, BridgeId>;\n /**\n * AbortControllers for in-flight `bridge.callTool(...)` dispatches, keyed\n * by the dispatching bridge's id. `unregisterInstance` aborts every\n * controller in the matching set so a torn-down iframe never leaves a\n * paused server stream waiting forever. Each set is also the source of\n * truth for the per-iframe busy indicator.\n */\n pendingControllers: Map<BridgeId, Set<AbortController>>;\n\n registerInstance: (inst: AppInstance) => Promise<void>;\n unregisterInstance: (bridgeId: BridgeId) => void;\n pushActive: (\n parentToolCallId: string,\n bridgeId: BridgeId,\n chatSessionId?: string,\n ) => void;\n popActive: (\n parentToolCallId: string,\n bridgeId: BridgeId,\n chatSessionId?: string,\n ) => void;\n\n /** Adds `controller` to the bridge's pending set and bumps the busy count. */\n registerPendingCall: (\n bridgeId: BridgeId,\n controller: AbortController,\n ) => void;\n /** Removes `controller` from the bridge's pending set (no-op if absent). */\n unregisterPendingCall: (\n bridgeId: BridgeId,\n controller: AbortController,\n ) => void;\n\n snapshotForChatBody: (chatSessionId?: string) => AppToolSnapshotEntry[];\n resolve: (\n alias: string,\n chatSessionId?: string,\n ) => {\n bridge: AppBridge;\n rawName: string;\n readOnly: boolean;\n instance: AppInstance;\n } | null;\n}\n\n/**\n * Produce an opaque alias for a rendered app tool. SHA-256 hashed over stable\n * identity-bearing inputs and truncated to 8 hex chars so the wire\n * name is always 12 chars: well under Anthropic's 64-char tool-name limit\n * and never collides with the `getInvalidAnthropicToolNames` charset.\n *\n * Deliberately exclude `bridgeId`: a live app can reconnect/re-register its\n * bridge without changing the rendered host tool call or raw app-tool name.\n * The alias must stay stable across that churn so the model does not see the\n * same app tool under a fresh name.\n *\n * Collision retry: if a generated alias is already in use, the caller\n * (`registerInstance`) re-rolls with a numeric salt appended to the\n * preimage. In practice 8 hex chars over the joined inputs has negligible\n * collision risk; the retry is a belt-and-suspenders guard.\n */\nasync function generateAlias(\n chatSessionId: string | undefined,\n serverId: string,\n parentToolCallId: string,\n surface: AppInstance[\"surface\"],\n rawName: string,\n salt = 0,\n): Promise<string> {\n const preimage = `${\n chatSessionId ?? \"\"\n }\\0${serverId}\\0${parentToolCallId}\\0${surface}\\0${rawName}\\0${salt}`;\n const bytes = new TextEncoder().encode(preimage);\n const digest = await crypto.subtle.digest(\"SHA-256\", bytes);\n const hex = Array.from(new Uint8Array(digest))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n return `app_${hex.slice(0, 8)}`;\n}\n\nfunction isReadOnly(tool: AppToolDescriptor): boolean {\n return tool.annotations?.readOnlyHint === true;\n}\n\nfunction getActiveParentKey(\n parentToolCallId: string,\n chatSessionId?: string,\n): string {\n return chatSessionId\n ? `${chatSessionId}\\0${parentToolCallId}`\n : parentToolCallId;\n}\n\nfunction isSameAppSlot(a: AppInstance, b: AppInstance): boolean {\n return (\n a.parentToolCallId === b.parentToolCallId &&\n a.surface === b.surface &&\n a.chatSessionId === b.chatSessionId\n );\n}\n\nexport const useAppToolsRegistry = create<AppToolsRegistryState>(\n (set, get) => ({\n instancesByBridgeId: new Map(),\n aliases: new Map(),\n activeBridgeByParent: new Map(),\n pendingControllers: new Map(),\n\n // Returns a Promise so callers (and tests) can await the alias-hash\n // round-trip. The renderer uses `void registerInstance(...)` because\n // there's nothing to do until the next chat POST. Tests await so\n // resolved microtasks don't bleed into the next test's reset store.\n registerInstance: async (inst) => {\n // Identify bridges this registration supersedes: same chat session,\n // same parent + same surface, different bridgeId. We mirror this set\n // across instance purge, alias purge, and pendingControllers cleanup so\n // the three stay in lockstep. A modal opening over a still-mounted\n // inline app (different surfaces) does NOT supersede the inline bridge —\n // its instance, aliases, and pending controllers all survive.\n const supersededBridgeIds = new Set<BridgeId>();\n for (const [bridgeId, oldInst] of get().instancesByBridgeId) {\n if (bridgeId !== inst.bridgeId && isSameAppSlot(oldInst, inst)) {\n supersededBridgeIds.add(bridgeId);\n }\n }\n\n // Generate aliases for every tool the app listed. `readOnly` is cached\n // from annotations, but it is not an inclusion gate.\n const aliasesForInst: AppToolAlias[] = [];\n const existing = new Set(\n [...get().aliases.entries()]\n .filter(([, alias]) => {\n if (alias.bridgeId === inst.bridgeId) return false;\n return !supersededBridgeIds.has(alias.bridgeId);\n })\n .map(([alias]) => alias),\n );\n for (const tool of inst.tools) {\n let salt = 0;\n let alias = await generateAlias(\n inst.chatSessionId,\n inst.serverId,\n inst.parentToolCallId,\n inst.surface,\n tool.name,\n salt,\n );\n while (existing.has(alias)) {\n salt += 1;\n alias = await generateAlias(\n inst.chatSessionId,\n inst.serverId,\n inst.parentToolCallId,\n inst.surface,\n tool.name,\n salt,\n );\n }\n existing.add(alias);\n aliasesForInst.push({\n alias,\n bridgeId: inst.bridgeId,\n rawName: tool.name,\n readOnly: isReadOnly(tool),\n });\n }\n // Abort in-flight bridge.callTool dispatches against any superseded\n // bridge BEFORE we drop its instance entry. Same reasoning as\n // `unregisterInstance`: a fresh bridgeId taking over the same\n // (parent, surface) slot is an implicit teardown of the prior one,\n // and the chat stream will hang on the dead iframe if we skip this.\n for (const bridgeId of supersededBridgeIds) {\n const pending = get().pendingControllers.get(bridgeId);\n if (!pending) continue;\n for (const controller of pending) {\n try {\n controller.abort();\n } catch {\n // Ignore — abort() should never throw, but defensively continue.\n }\n }\n }\n set((s) => {\n const instancesByBridgeId = new Map(s.instancesByBridgeId);\n for (const bridgeId of supersededBridgeIds) {\n instancesByBridgeId.delete(bridgeId);\n }\n instancesByBridgeId.set(inst.bridgeId, inst);\n const aliases = new Map(s.aliases);\n for (const [alias, a] of s.aliases) {\n // Only drop aliases for the new bridge itself (replacement) or\n // for bridges actually being instance-removed. Crucially, we do\n // NOT drop aliases owned by a sibling instance under the same\n // parent but on a different surface (e.g. inline aliases when a\n // modal opens) — that bug left inline tools unresolvable until\n // re-initialization even after the modal closed.\n if (\n a.bridgeId === inst.bridgeId ||\n supersededBridgeIds.has(a.bridgeId)\n ) {\n aliases.delete(alias);\n }\n }\n for (const a of aliasesForInst) aliases.set(a.alias, a);\n const activeBridgeByParent = new Map(s.activeBridgeByParent);\n activeBridgeByParent.set(\n getActiveParentKey(inst.parentToolCallId, inst.chatSessionId),\n inst.bridgeId,\n );\n let pendingControllers = s.pendingControllers;\n if (supersededBridgeIds.size > 0) {\n pendingControllers = new Map(s.pendingControllers);\n for (const bridgeId of supersededBridgeIds) {\n pendingControllers.delete(bridgeId);\n }\n }\n return {\n instancesByBridgeId,\n aliases,\n activeBridgeByParent,\n pendingControllers,\n };\n });\n },\n\n unregisterInstance: (bridgeId) => {\n // Abort any in-flight `bridge.callTool` dispatches against this bridge\n // BEFORE we drop the instance entry. The catch branch in\n // `useChat.onToolCall` picks up the abort and resolves the tool call\n // with `isError: true`, which is what lets the paused server stream\n // continue. Skipping this leaves the chat hanging when an iframe is\n // torn down mid-dispatch.\n const pending = get().pendingControllers.get(bridgeId);\n if (pending) {\n for (const controller of pending) {\n try {\n controller.abort();\n } catch {\n // Ignore — abort() should never throw, but defensively continue.\n }\n }\n }\n set((s) => {\n const inst = s.instancesByBridgeId.get(bridgeId);\n if (!inst) return {};\n const instancesByBridgeId = new Map(s.instancesByBridgeId);\n instancesByBridgeId.delete(bridgeId);\n const aliases = new Map(s.aliases);\n for (const [alias, a] of s.aliases) {\n if (a.bridgeId === bridgeId) aliases.delete(alias);\n }\n const activeBridgeByParent = new Map(s.activeBridgeByParent);\n const activeParentKey = getActiveParentKey(\n inst.parentToolCallId,\n inst.chatSessionId,\n );\n if (activeBridgeByParent.get(activeParentKey) === bridgeId) {\n // Promote any other still-mounted instance under this parent so\n // its aliases stay resolvable and visible to the model. Without\n // this fallback, closing a modal that opened over a still-\n // mounted inline app leaves the inline app's tools unreachable\n // (both `resolve()` and `snapshotForChatBody()` gate on the\n // active bridge match). Mirrors the fallback search in\n // `popActive`.\n let fallback: BridgeId | undefined;\n for (const other of instancesByBridgeId.values()) {\n if (\n other.parentToolCallId === inst.parentToolCallId &&\n other.chatSessionId === inst.chatSessionId\n ) {\n fallback = other.bridgeId;\n break;\n }\n }\n if (fallback) {\n activeBridgeByParent.set(activeParentKey, fallback);\n } else {\n activeBridgeByParent.delete(activeParentKey);\n }\n }\n const pendingControllers = new Map(s.pendingControllers);\n pendingControllers.delete(bridgeId);\n return {\n instancesByBridgeId,\n aliases,\n activeBridgeByParent,\n pendingControllers,\n };\n });\n },\n\n registerPendingCall: (bridgeId, controller) => {\n set((s) => {\n const pendingControllers = new Map(s.pendingControllers);\n const next = new Set(pendingControllers.get(bridgeId));\n next.add(controller);\n pendingControllers.set(bridgeId, next);\n return { pendingControllers };\n });\n },\n\n unregisterPendingCall: (bridgeId, controller) => {\n set((s) => {\n const existing = s.pendingControllers.get(bridgeId);\n if (!existing || !existing.has(controller)) return {};\n const pendingControllers = new Map(s.pendingControllers);\n if (existing.size === 1) {\n pendingControllers.delete(bridgeId);\n } else {\n const next = new Set(existing);\n next.delete(controller);\n pendingControllers.set(bridgeId, next);\n }\n return { pendingControllers };\n });\n },\n\n pushActive: (parentToolCallId, bridgeId, chatSessionId) => {\n set((s) => {\n const next = new Map(s.activeBridgeByParent);\n next.set(getActiveParentKey(parentToolCallId, chatSessionId), bridgeId);\n return { activeBridgeByParent: next };\n });\n },\n\n popActive: (parentToolCallId, bridgeId, chatSessionId) => {\n set((s) => {\n const activeParentKey = getActiveParentKey(\n parentToolCallId,\n chatSessionId,\n );\n const current = s.activeBridgeByParent.get(activeParentKey);\n if (current !== bridgeId) return {};\n const next = new Map(s.activeBridgeByParent);\n // Fall back to any other registered instance under this parent.\n let fallback: BridgeId | undefined;\n for (const inst of s.instancesByBridgeId.values()) {\n if (\n inst.parentToolCallId === parentToolCallId &&\n inst.chatSessionId === chatSessionId &&\n inst.bridgeId !== bridgeId\n ) {\n fallback = inst.bridgeId;\n break;\n }\n }\n if (fallback) next.set(activeParentKey, fallback);\n else next.delete(activeParentKey);\n return { activeBridgeByParent: next };\n });\n },\n\n snapshotForChatBody: (chatSessionId) => {\n const { instancesByBridgeId, aliases, activeBridgeByParent } = get();\n const out: AppToolSnapshotEntry[] = [];\n let dropped = 0;\n for (const [alias, a] of aliases) {\n if (out.length >= MAX_SNAPSHOT_ENTRIES) {\n dropped += 1;\n continue;\n }\n if (!ALIAS_REGEX.test(alias)) continue;\n const inst = instancesByBridgeId.get(a.bridgeId);\n if (!inst) continue;\n if (chatSessionId && inst.chatSessionId !== chatSessionId) continue;\n // Only the active instance per parent contributes. This prevents stale\n // iframe instances from advertising tools after a modal or replay wins.\n if (\n activeBridgeByParent.get(\n getActiveParentKey(inst.parentToolCallId, inst.chatSessionId),\n ) !== inst.bridgeId\n ) {\n continue;\n }\n const tool = inst.tools.find((t) => t.name === a.rawName);\n if (!tool) continue;\n let inputSchema = tool.inputSchema;\n if (inputSchema) {\n let size = 0;\n try {\n size = new TextEncoder().encode(JSON.stringify(inputSchema)).length;\n } catch {\n continue; // unserializable\n }\n if (size > MAX_INPUT_SCHEMA_BYTES) continue;\n }\n const description = tool.description\n ? tool.description.slice(0, MAX_DESCRIPTION_CHARS)\n : undefined;\n out.push({\n alias,\n appName: inst.appName,\n appVersion: inst.appVersion,\n serverId: inst.serverId,\n parentToolCallId: inst.parentToolCallId,\n rawName: a.rawName,\n description,\n inputSchema,\n readOnly: a.readOnly,\n });\n }\n if (dropped > 0) {\n console.warn(\n `[app-tools] snapshot capped at ${MAX_SNAPSHOT_ENTRIES} entries; dropped ${dropped}.`,\n );\n }\n // Multi-instance disambiguation: when the same app is mounted more\n // than once concurrently (e.g. two tic-tac-toe boards from two\n // separate `tools/call` results), `tools/list` returns identical\n // `rawName`s and the model sees N tools with the same description.\n // Wire-level routing is already correct (aliases differ per\n // parentToolCallId), but the model can't tell which instance to\n // pick. Append `(from tool call <id>; instance N of M)` to the\n // description for any group with size > 1 so the model can\n // distinguish them via the visible tool-call history in the\n // transcript. Singletons stay untouched.\n const groupCounts = new Map<string, number>();\n for (const entry of out) {\n const key = `${entry.appName}\\0${entry.rawName}`;\n groupCounts.set(key, (groupCounts.get(key) ?? 0) + 1);\n }\n const groupIndex = new Map<string, number>();\n for (const entry of out) {\n const key = `${entry.appName}\\0${entry.rawName}`;\n const total = groupCounts.get(key) ?? 1;\n if (total <= 1) continue;\n const n = (groupIndex.get(key) ?? 0) + 1;\n groupIndex.set(key, n);\n const hint = ` (from tool call ${entry.parentToolCallId}; instance ${n} of ${total})`;\n const base = entry.description ?? \"\";\n entry.description = (base + hint).slice(0, MAX_DESCRIPTION_CHARS);\n }\n return out;\n },\n\n resolve: (alias, chatSessionId) => {\n const a = get().aliases.get(alias);\n if (!a) return null;\n const inst = get().instancesByBridgeId.get(a.bridgeId);\n if (!inst) return null;\n if (chatSessionId && inst.chatSessionId !== chatSessionId) return null;\n if (\n get().activeBridgeByParent.get(\n getActiveParentKey(inst.parentToolCallId, inst.chatSessionId),\n ) !== inst.bridgeId\n ) {\n return null;\n }\n return {\n bridge: inst.bridge,\n rawName: a.rawName,\n readOnly: a.readOnly,\n instance: inst,\n };\n },\n }),\n);\n\n/**\n * Side-channel log of every app-tool invocation for debugging and future UI.\n * Mirrors the widget-html debug store pattern. The full untouched\n * `CallToolResult` is stored here so the UI can later display\n * `structuredContent` / `_meta` that were intentionally stripped from model\n * context.\n */\nexport interface AppToolInvocationRecord {\n alias: string;\n rawName: string;\n appName: string;\n serverId: string;\n parentToolCallId: string;\n bridgeId: BridgeId;\n input: unknown;\n raw: CallToolResult;\n invokedAtMs: number;\n}\n\ninterface AppToolInvocationLogState {\n records: AppToolInvocationRecord[];\n append: (r: AppToolInvocationRecord) => void;\n clear: () => void;\n}\n\nconst MAX_INVOCATION_RECORDS = 200;\n\nexport const useAppToolInvocationLog = create<AppToolInvocationLogState>(\n (set) => ({\n records: [],\n append: (r) =>\n set((s) => {\n const next = s.records.concat(r);\n if (next.length > MAX_INVOCATION_RECORDS) {\n next.splice(0, next.length - MAX_INVOCATION_RECORDS);\n }\n return { records: next };\n }),\n clear: () => set({ records: [] }),\n }),\n);\n\nexport function recordAppToolInvocation(\n args: Omit<AppToolInvocationRecord, \"invokedAtMs\">,\n addTrafficLog?: AddTrafficLog,\n): void {\n useAppToolInvocationLog.getState().append({\n ...args,\n invokedAtMs: Date.now(),\n });\n // Mirror the invocation into the shared traffic-log via the injected sink so\n // it surfaces in `LoggerView` alongside the rest of the iframe ↔ host\n // traffic. `direction: \"host-to-ui\"` because the host dispatched the\n // call into the iframe via `bridge.callTool`. `widgetId` matches the\n // parent host tool call so existing logger filters scope correctly.\n // Only the model-safe scrubbed payload is shipped here — the full\n // `CallToolResult` (including `structuredContent` and `_meta`) lives\n // in `useAppToolInvocationLog` for richer debug UIs. When no sink is\n // injected (non-inspector host), the invocation log still records.\n if (!addTrafficLog) return;\n try {\n addTrafficLog({\n widgetId: args.parentToolCallId,\n serverId: args.serverId,\n direction: \"host-to-ui\",\n protocol: \"mcp-apps\",\n method: \"tools/call\",\n message: {\n alias: args.alias,\n toolName: args.rawName,\n appName: args.appName,\n arguments: args.input,\n result: {\n content: args.raw.content,\n ...(args.raw.isError ? { isError: true } : {}),\n },\n },\n });\n } catch {\n // Defensive: the traffic-log sink is best-effort observability;\n // never let a logger failure bubble into the dispatch path.\n }\n}\n\nexport function useAppToolAttributionResolver(chatSessionId?: string) {\n const registrySnapshot = useAppToolsRegistry(\n useShallow((s) => ({\n activeBridgeByParent: s.activeBridgeByParent,\n aliases: s.aliases,\n instancesByBridgeId: s.instancesByBridgeId,\n })),\n );\n const resolve = useAppToolsRegistry((s) => s.resolve);\n const invocationRecords = useAppToolInvocationLog((s) => s.records);\n\n return useCallback(\n (label: string): AppToolAttribution | null => {\n if (!ALIAS_REGEX.test(label)) return null;\n\n const resolved = resolve(label, chatSessionId);\n if (resolved) {\n return {\n rawName: resolved.rawName,\n appName: resolved.instance.appName,\n };\n }\n\n for (let i = invocationRecords.length - 1; i >= 0; i -= 1) {\n const record = invocationRecords[i];\n if (record.alias === label) {\n return { rawName: record.rawName, appName: record.appName };\n }\n }\n\n return null;\n },\n [chatSessionId, invocationRecords, registrySnapshot, resolve],\n );\n}\n\nexport function useAppToolAttribution(\n label: string,\n chatSessionId?: string,\n): AppToolAttribution | null {\n const resolveAppToolAttribution =\n useAppToolAttributionResolver(chatSessionId);\n return resolveAppToolAttribution(label);\n}\n\n// Exports for tests.\nexport const __internal = { generateAlias, isReadOnly, ALIAS_REGEX };\n","/**\n * useToolInputStreaming – manages the streaming delivery of tool input to\n * an MCP App bridge.\n *\n * Extracted from mcp-apps-renderer.tsx so the streaming logic can be tested\n * in isolation and extended with debug tooling (e.g. a streaming slider)\n * without touching the renderer component.\n */\n\nimport {\n useRef,\n useState,\n useMemo,\n useCallback,\n useEffect,\n useLayoutEffect,\n} from \"react\";\nimport type { AppBridge } from \"@modelcontextprotocol/ext-apps/app-bridge\";\n// Re-exported from the WidgetHost contract module so this cluster file stays\n// free of `@/lib/client-styles` (Tier-B guard).\nimport type { ResolvedMcpAppsCapabilities } from \"./widget-host\";\n\n// ── Constants ────────────────────────────────────────────────────────────────\n\nexport const PARTIAL_INPUT_THROTTLE_MS = 120;\nexport const STREAMING_REVEAL_FALLBACK_MS = 700;\nexport const SIGNATURE_MAX_DEPTH = 4;\nexport const SIGNATURE_MAX_ARRAY_ITEMS = 24;\nexport const SIGNATURE_MAX_OBJECT_KEYS = 32;\nexport const SIGNATURE_STRING_EDGE_LENGTH = 24;\n\n// ── Types ────────────────────────────────────────────────────────────────────\n\nexport type ToolState =\n | \"input-streaming\"\n | \"input-available\"\n | \"approval-requested\"\n | \"output-available\"\n | \"output-denied\"\n | \"output-error\";\n\n// ── Signature helper ─────────────────────────────────────────────────────────\n\n/**\n * Produce a compact structural fingerprint of `input` so we can cheaply\n * detect whether a new streaming partial is meaningfully different from the\n * last one we sent to the bridge.\n */\nexport function getToolInputSignature(\n input: Record<string, unknown> | undefined,\n): string {\n if (!input) return \"\";\n const seen = new WeakSet<object>();\n\n const getValueSignature = (value: unknown, depth: number): string => {\n if (value == null) return \"null\";\n\n const valueType = typeof value;\n if (valueType === \"string\") {\n const text = value as string;\n const head = text.slice(0, SIGNATURE_STRING_EDGE_LENGTH);\n const tail = text.slice(-SIGNATURE_STRING_EDGE_LENGTH);\n return `str:${text.length}:${JSON.stringify(head)}:${JSON.stringify(tail)}`;\n }\n if (valueType === \"number\") {\n if (Number.isNaN(value)) return \"num:NaN\";\n if (value === Infinity) return \"num:Infinity\";\n if (value === -Infinity) return \"num:-Infinity\";\n if (Object.is(value, -0)) return \"num:-0\";\n return `num:${value as number}`;\n }\n if (valueType === \"boolean\") return `bool:${String(value)}`;\n if (valueType === \"bigint\") return `bigint:${String(value)}`;\n if (valueType === \"undefined\") return \"undefined\";\n if (valueType === \"function\") return \"function\";\n if (valueType === \"symbol\") return `symbol:${String(value)}`;\n\n if (depth >= SIGNATURE_MAX_DEPTH) {\n if (Array.isArray(value)) return `arr:max-depth:${value.length}`;\n return `obj:max-depth:${Object.keys(value as Record<string, unknown>).length}`;\n }\n\n if (Array.isArray(value)) {\n const length = value.length;\n if (length === 0) return \"arr:0\";\n\n const headCount = Math.min(length, SIGNATURE_MAX_ARRAY_ITEMS);\n const headSignatures: string[] = [];\n for (let index = 0; index < headCount; index += 1) {\n headSignatures.push(\n `${index}:${getValueSignature(value[index], depth + 1)}`,\n );\n }\n\n if (length <= SIGNATURE_MAX_ARRAY_ITEMS) {\n return `arr:${length}:[${headSignatures.join(\",\")}]`;\n }\n\n const tailStart = Math.max(headCount, length - 2);\n const tailSignatures: string[] = [];\n for (let index = tailStart; index < length; index += 1) {\n tailSignatures.push(\n `${index}:${getValueSignature(value[index], depth + 1)}`,\n );\n }\n\n return `arr:${length}:[${headSignatures.join(\",\")}]|tail:[${tailSignatures.join(\",\")}]`;\n }\n\n if (valueType === \"object\") {\n const record = value as Record<string, unknown>;\n if (seen.has(record)) return \"obj:circular\";\n seen.add(record);\n\n const keys = Object.keys(record).sort();\n const keyCount = Math.min(keys.length, SIGNATURE_MAX_OBJECT_KEYS);\n const entries: string[] = [];\n\n for (let index = 0; index < keyCount; index += 1) {\n const key = keys[index];\n entries.push(`${key}:${getValueSignature(record[key], depth + 1)}`);\n }\n\n if (keys.length > SIGNATURE_MAX_OBJECT_KEYS) {\n const omitted = keys.length - SIGNATURE_MAX_OBJECT_KEYS;\n const tailKeys = keys.slice(-2).join(\",\");\n entries.push(`omitted:${omitted}:tail-keys:${tailKeys}`);\n }\n\n seen.delete(record);\n return `obj:${keys.length}:{${entries.join(\"|\")}}`;\n }\n\n return `other:${valueType}`;\n };\n\n return getValueSignature(input, 0);\n}\n\n// ── Hook interface ───────────────────────────────────────────────────────────\n\nexport interface UseToolInputStreamingParams {\n bridgeRef: React.RefObject<AppBridge | null>;\n isReady: boolean;\n isReadyRef: React.RefObject<boolean>;\n toolState: ToolState | undefined;\n toolInput: Record<string, unknown> | undefined;\n toolOutput: unknown;\n toolErrorText: string | undefined;\n toolCallId: string;\n /**\n * Whether this View should receive the one-shot complete tool-input\n * notification for the current render. Resource-scoped persistent Views\n * keep the iframe alive across tool calls, but each new tool call still\n * gets a complete input notification before its result.\n */\n sendToolInput: boolean;\n onToolInputSent?: () => void;\n /** Incremented when the guest re-initializes (e.g. SDK app after openai-compat shim) */\n reinitCount: number;\n /**\n * Resolved SEP-1865 MCP Apps spec-bridge matrix. Gates the\n * notifications this hook emits to the View:\n * - `toolInputPartial: false` → suppress\n * `bridge.sendToolInputPartial` (Microsoft 365 Copilot does\n * not deliver this notification — widgets running under that\n * simulated surface must not see partials).\n * - `toolCancelled: false` → suppress `bridge.sendToolCancelled`\n * (Copilot does not deliver this either).\n *\n * Passed as a ref so the hook reads the latest resolved value\n * without rebuilding the effect closures on every host-style /\n * profile change. Null while the renderer is still resolving the\n * matrix (e.g. before host context is wired) — null reads as\n * \"default on\" so the inspector keeps emitting notifications by\n * default, matching the pre-matrix behavior for any host the\n * renderer hasn't classified yet.\n */\n mcpAppsCapabilitiesRef: React.RefObject<ResolvedMcpAppsCapabilities | null>;\n}\n\nexport interface UseToolInputStreamingReturn {\n canRenderStreamingInput: boolean;\n /** Called by LoggingTransport onReceive when a size-changed notification arrives. */\n signalStreamingRender: () => void;\n /** Called on CSP mode change (or externally) to clear all streaming state. */\n resetStreamingState: () => void;\n}\n\n// ── Hook ─────────────────────────────────────────────────────────────────────\n\nexport function useToolInputStreaming({\n bridgeRef,\n isReady,\n isReadyRef,\n toolState,\n toolInput,\n toolOutput,\n toolErrorText,\n toolCallId,\n sendToolInput,\n onToolInputSent,\n reinitCount,\n mcpAppsCapabilitiesRef,\n}: UseToolInputStreamingParams): UseToolInputStreamingReturn {\n // ── Internal refs ────────────────────────────────────────────────────────\n\n const lastToolInputRef = useRef<string | null>(null);\n const lastToolInputPartialRef = useRef<string | null>(null);\n const lastToolInputPartialSentAtRef = useRef(0);\n const pendingToolInputPartialRef = useRef<Record<string, unknown> | null>(\n null,\n );\n const partialInputTimerRef = useRef<number | null>(null);\n const streamingRevealTimerRef = useRef<number | null>(null);\n const lastToolOutputRef = useRef<string | null>(null);\n const lastToolErrorRef = useRef<string | null>(null);\n const toolInputSentRef = useRef(false);\n const previousToolStateRef = useRef<ToolState | undefined>(toolState);\n const previousToolCallIdRef = useRef(toolCallId);\n\n // ── Internal state ───────────────────────────────────────────────────────\n\n const [streamingRenderSignaled, setStreamingRenderSignaled] = useState(false);\n const [streamingRevealFallbackElapsed, setStreamingRevealFallbackElapsed] =\n useState(false);\n const [hasDeliveredStreamingInput, setHasDeliveredStreamingInput] =\n useState(false);\n\n // ── Derived values ───────────────────────────────────────────────────────\n\n const hasToolInputData = useMemo(\n () => !!toolInput && Object.keys(toolInput).length > 0,\n [toolInput],\n );\n\n const canRenderStreamingInput = useMemo(() => {\n if (toolState !== \"input-streaming\") return true;\n if (!sendToolInput) return true;\n // Prefer revealing after the first delivered partial, but do not keep the\n // iframe hidden forever when a provider streams no parseable partial args.\n return (\n streamingRevealFallbackElapsed ||\n (streamingRenderSignaled && hasDeliveredStreamingInput)\n );\n }, [\n hasDeliveredStreamingInput,\n sendToolInput,\n streamingRevealFallbackElapsed,\n streamingRenderSignaled,\n toolState,\n ]);\n\n // ── Callbacks ────────────────────────────────────────────────────────────\n\n const resetStreamingState = useCallback(() => {\n lastToolInputRef.current = null;\n lastToolInputPartialRef.current = null;\n lastToolInputPartialSentAtRef.current = 0;\n pendingToolInputPartialRef.current = null;\n if (partialInputTimerRef.current !== null) {\n window.clearTimeout(partialInputTimerRef.current);\n partialInputTimerRef.current = null;\n }\n if (streamingRevealTimerRef.current !== null) {\n window.clearTimeout(streamingRevealTimerRef.current);\n streamingRevealTimerRef.current = null;\n }\n lastToolOutputRef.current = null;\n lastToolErrorRef.current = null;\n toolInputSentRef.current = false;\n setStreamingRenderSignaled(false);\n setStreamingRevealFallbackElapsed(false);\n setHasDeliveredStreamingInput(false);\n }, []);\n\n const signalStreamingRender = useCallback(() => {\n setStreamingRenderSignaled(true);\n }, []);\n\n // ── Effects ──────────────────────────────────────────────────────────────\n\n // 0. Reset dedup refs on guest re-initialization (e.g. SDK app init after\n // openai-compat shim already completed the handshake). This must run\n // before the delivery effects so they see the cleared refs and re-send.\n useEffect(() => {\n if (reinitCount === 0) return; // skip initial mount\n lastToolInputRef.current = null;\n lastToolInputPartialRef.current = null;\n lastToolOutputRef.current = null;\n lastToolErrorRef.current = null;\n toolInputSentRef.current = false;\n }, [reinitCount]);\n\n // 1. Clear reveal timer once the iframe is allowed to become visible. A\n // render signal alone can come from size-changed before any parseable streamed\n // args arrive, so keep the fallback alive for that case.\n useEffect(() => {\n if (!hasDeliveredStreamingInput && !streamingRevealFallbackElapsed) return;\n if (streamingRevealTimerRef.current !== null) {\n window.clearTimeout(streamingRevealTimerRef.current);\n streamingRevealTimerRef.current = null;\n }\n }, [hasDeliveredStreamingInput, streamingRevealFallbackElapsed]);\n\n // 2. Fallback reveal timer\n useEffect(() => {\n if (!sendToolInput) return;\n if (\n !isReady ||\n toolState !== \"input-streaming\" ||\n hasDeliveredStreamingInput ||\n streamingRevealFallbackElapsed\n )\n return;\n if (streamingRevealTimerRef.current !== null) return;\n\n streamingRevealTimerRef.current = window.setTimeout(() => {\n streamingRevealTimerRef.current = null;\n setStreamingRenderSignaled(true);\n setStreamingRevealFallbackElapsed(true);\n }, STREAMING_REVEAL_FALLBACK_MS);\n }, [\n hasDeliveredStreamingInput,\n isReady,\n sendToolInput,\n streamingRevealFallbackElapsed,\n toolState,\n ]);\n\n // 3. Re-entry detection\n useEffect(() => {\n const prevToolState = previousToolStateRef.current;\n\n // Some providers may re-enter input-streaming for a new call while reusing\n // the same toolCallId. Reset send guards so we can stream/send fresh input.\n if (\n toolState === \"input-streaming\" &&\n prevToolState &&\n prevToolState !== \"input-streaming\"\n ) {\n resetStreamingState();\n }\n\n previousToolStateRef.current = toolState;\n }, [resetStreamingState, toolState]);\n\n // 4. Partial input throttled delivery\n useEffect(() => {\n if (\n !sendToolInput ||\n !isReady ||\n toolState !== \"input-streaming\" ||\n toolInputSentRef.current\n )\n return;\n if (!hasToolInputData) return;\n const resolvedToolInput = toolInput ?? {};\n pendingToolInputPartialRef.current = resolvedToolInput;\n\n const flushPartialInput = () => {\n const bridge = bridgeRef.current;\n if (!bridge || !isReadyRef.current || toolInputSentRef.current) return;\n const pending = pendingToolInputPartialRef.current;\n if (!pending) return;\n\n const signature = getToolInputSignature(pending);\n if (lastToolInputPartialRef.current === signature) return;\n lastToolInputPartialRef.current = signature;\n lastToolInputPartialSentAtRef.current = Date.now();\n setHasDeliveredStreamingInput(true);\n setStreamingRenderSignaled(true);\n // Matrix gate: SEP-1865 hosts that don't deliver\n // `ui/notifications/tool-input-partial` (notably Microsoft 365\n // Copilot per its published Component-bridge table) flip this\n // dimension off in the matrix. Null ref → default on (matches\n // pre-matrix behavior for any host the renderer hasn't\n // classified yet). The streaming signature / streaming-render\n // gating above still fires regardless so the inspector's\n // internal streaming UX (which mirrors the bridge\n // notification cadence) doesn't go silent on Copilot-style\n // hosts — it's only the wire emission that's suppressed.\n const matrix = mcpAppsCapabilitiesRef.current;\n if (matrix !== null && matrix.toolInputPartial === false) return;\n Promise.resolve(\n bridge.sendToolInputPartial({ arguments: pending }),\n ).catch(() => {});\n };\n\n const now = Date.now();\n const elapsed = now - lastToolInputPartialSentAtRef.current;\n if (\n lastToolInputPartialSentAtRef.current === 0 ||\n elapsed >= PARTIAL_INPUT_THROTTLE_MS\n ) {\n if (partialInputTimerRef.current !== null) {\n window.clearTimeout(partialInputTimerRef.current);\n partialInputTimerRef.current = null;\n }\n flushPartialInput();\n return;\n }\n\n if (partialInputTimerRef.current !== null) {\n window.clearTimeout(partialInputTimerRef.current);\n }\n partialInputTimerRef.current = window.setTimeout(() => {\n partialInputTimerRef.current = null;\n flushPartialInput();\n }, PARTIAL_INPUT_THROTTLE_MS - elapsed);\n }, [\n hasToolInputData,\n isReady,\n sendToolInput,\n toolCallId,\n toolInput,\n toolState,\n bridgeRef,\n isReadyRef,\n ]);\n\n // 5. Complete input delivery\n useEffect(() => {\n if (!isReady) return;\n if (toolState !== \"input-available\" && toolState !== \"output-available\")\n return;\n if (partialInputTimerRef.current !== null) {\n window.clearTimeout(partialInputTimerRef.current);\n partialInputTimerRef.current = null;\n }\n if (streamingRevealTimerRef.current !== null) {\n window.clearTimeout(streamingRevealTimerRef.current);\n streamingRevealTimerRef.current = null;\n }\n pendingToolInputPartialRef.current = null;\n if (!sendToolInput) return;\n const bridge = bridgeRef.current;\n if (!bridge) return;\n\n const resolvedToolInput = toolInput ?? {};\n const serialized = JSON.stringify(resolvedToolInput);\n // Allow live editors/previews to update tool input repeatedly while keeping\n // duplicate sends suppressed for identical payloads.\n if (lastToolInputRef.current === serialized) {\n toolInputSentRef.current = true;\n return;\n }\n lastToolInputRef.current = serialized;\n toolInputSentRef.current = true;\n onToolInputSent?.();\n Promise.resolve(\n bridge.sendToolInput({ arguments: resolvedToolInput }),\n ).catch(() => {\n toolInputSentRef.current = false;\n lastToolInputRef.current = null;\n });\n }, [\n isReady,\n toolCallId,\n toolInput,\n toolState,\n bridgeRef,\n reinitCount,\n sendToolInput,\n onToolInputSent,\n ]);\n\n // 6. Tool result delivery\n useEffect(() => {\n if (!isReady || toolState !== \"output-available\") return;\n const bridge = bridgeRef.current;\n if (!bridge || !toolOutput) return;\n\n const serialized = JSON.stringify(toolOutput);\n const outputKey = `${toolCallId}:${serialized}`;\n if (lastToolOutputRef.current === outputKey) return;\n lastToolOutputRef.current = outputKey;\n // Apps-compat seam (§1D): cast to the bridge's own CallToolResult\n // (ext-apps v1-sdk peer) rather than the v2 client's nominal type.\n bridge.sendToolResult(\n toolOutput as Parameters<typeof bridge.sendToolResult>[0],\n );\n }, [isReady, toolCallId, toolOutput, toolState, bridgeRef, reinitCount]);\n\n // 7. Tool error/cancellation delivery\n useEffect(() => {\n if (!isReady || toolState !== \"output-error\") return;\n const bridge = bridgeRef.current;\n if (!bridge) return;\n\n const errorMessage =\n toolErrorText ??\n (toolOutput instanceof Error\n ? toolOutput.message\n : typeof toolOutput === \"string\"\n ? toolOutput\n : \"Tool execution failed\");\n\n const errorKey = `${toolCallId}:${errorMessage}`;\n if (lastToolErrorRef.current === errorKey) return;\n lastToolErrorRef.current = errorKey;\n\n // SEP-1865: Send tool-cancelled for errors instead of tool-result\n // with isError. Matrix gate: Microsoft 365 Copilot does not\n // deliver this notification per its published Component-bridge\n // table; widgets running under that simulated surface must not\n // see a cancelled callback. Null matrix ref → default on (same\n // fail-open contract as the partial-input gate above).\n const matrix = mcpAppsCapabilitiesRef.current;\n if (matrix !== null && matrix.toolCancelled === false) return;\n bridge.sendToolCancelled({ reason: errorMessage });\n }, [\n isReady,\n toolCallId,\n toolErrorText,\n toolOutput,\n toolState,\n bridgeRef,\n reinitCount,\n mcpAppsCapabilitiesRef,\n ]);\n\n // 8. Reset on toolCallId change. Do this before paint so a recycled renderer\n // cannot briefly expose the previous call's delivery guards.\n useLayoutEffect(() => {\n if (previousToolCallIdRef.current === toolCallId) return;\n previousToolCallIdRef.current = toolCallId;\n resetStreamingState();\n }, [toolCallId, resetStreamingState]);\n\n // 9. Cleanup on unmount\n useEffect(() => {\n return () => resetStreamingState();\n }, [resetStreamingState]);\n\n return {\n canRenderStreamingInput,\n signalStreamingRender,\n resetStreamingState,\n };\n}\n","/**\n * SandboxedIframe - DRY Double-Iframe Sandbox Component\n *\n * Provides a secure double-iframe architecture for rendering untrusted HTML:\n * Host Page → Sandbox Proxy (different origin) → Guest UI\n *\n * The sandbox proxy:\n * 1. Runs in a different origin for security isolation\n * 2. Loads guest HTML via srcdoc when ready\n * 3. Forwards messages between host and guest (except sandbox-internal)\n *\n * Per SEP-1865, this component is designed to be reusable for MCP Apps\n * and potentially future OpenAI SDK consolidation.\n */\n\nimport {\n stableStringifyJson,\n buildOuterAllowAttribute,\n buildOuterSandboxAttribute,\n} from \"@mcpjam/sdk/widget-runtime\";\nimport {\n useRef,\n useState,\n useEffect,\n useCallback,\n useImperativeHandle,\n forwardRef,\n useMemo,\n} from \"react\";\nimport type {\n McpUiResourceCsp,\n McpUiResourcePermissions,\n} from \"@modelcontextprotocol/ext-apps/app-bridge\";\n\nfunction isRecorderDebugEnabled() {\n try {\n return (\n typeof window !== \"undefined\" &&\n window.localStorage?.getItem(\"mcpjam:recorder-debug\") === \"1\"\n );\n } catch {\n return false;\n }\n}\n\nfunction recorderDebug(message: string, details?: Record<string, unknown>) {\n try {\n if (isRecorderDebugEnabled()) {\n console.info(`[recorder:sandboxed-iframe] ${message}`, details ?? {});\n }\n } catch {\n // best-effort debug logging only\n }\n}\n\nexport interface SandboxedIframeHandle {\n postMessage: (data: unknown) => void;\n getIframeElement: () => HTMLIFrameElement | null;\n}\n\ninterface SandboxedIframeProps {\n /** HTML content to render in the sandbox */\n html: string | null;\n /** Sandbox attribute for the inner iframe */\n sandbox?: string;\n /** CSP metadata from resource _meta.ui.csp (SEP-1865) */\n csp?: McpUiResourceCsp;\n /** Permissions metadata from resource _meta.ui.permissions (SEP-1865) */\n permissions?: McpUiResourcePermissions;\n /**\n * Inspector-only: extra `sandbox=` tokens unioned with the spec-mandated\n * `allow-scripts allow-same-origin` on both outer and inner iframes.\n * Models tokens real hosts emit (e.g. `allow-forms`) that aren't part of\n * SEP-1865 metadata.\n */\n sandboxAttrs?: string[];\n /**\n * Inspector-only: extra Permissions Policy entries appended to outer/inner\n * iframe `allow=`. Keys are kebab Permissions Policy tokens\n * (`fullscreen`, `web-share`); the 4 spec features\n * (camera/microphone/geolocation/clipboard-write) live in `permissions`\n * and are NOT permitted here.\n */\n allowFeatures?: Record<string, string>;\n /**\n * Inspector-only: per-directive CSP source-expression overrides merged\n * into the inner doc's `<meta http-equiv=\"Content-Security-Policy\">`.\n * Keys are CSP directive names (`script-src`, …); values are token arrays\n * (`[\"'unsafe-eval'\", \"'wasm-unsafe-eval'\"]`).\n */\n cspDirectives?: Record<string, string[]>;\n /** Skip CSP injection entirely (for permissive/testing mode) */\n permissive?: boolean;\n /**\n * Tier 2 recorder: when true, the proxy injects a recorder shim into the\n * guest that posts `recorder:step` / `recorder:ready` messages (forwarded via\n * `onMessage`). Default off — only the eval authoring preview sets it.\n */\n recordMode?: boolean;\n /** Callback when sandbox proxy is ready */\n onProxyReady?: () => void;\n /** Callback for messages from guest UI (excluding sandbox-internal messages) */\n onMessage: (event: MessageEvent) => void;\n /** CSS class for the outer iframe */\n className?: string;\n /** Inline styles for the outer iframe */\n style?: React.CSSProperties;\n /** Host color scheme used to keep transparent iframe canvas rendering aligned */\n colorScheme?: \"light\" | \"dark\";\n /** Title for accessibility */\n title?: string;\n /**\n * Whether the app runs against the hosted backend (the inspector's\n * `HOSTED_MODE`). Selects the hosted vs. local sandbox-proxy path and the\n * same-origin security warning. Supplied by the host (`host.surface.hostedMode`)\n * so this component carries no inspector config import.\n */\n hostedMode?: boolean;\n /**\n * Operator-configured sandbox origin (the inspector's `SANDBOX_ORIGIN` /\n * `VITE_MCPJAM_SANDBOX_ORIGIN`); \"\" when unset. Used in hosted mode to load\n * the sandbox proxy from a distinct origin. Supplied by the host\n * (`host.surface.sandboxOrigin`).\n */\n sandboxOrigin?: string;\n}\n\n/**\n * SandboxedIframe provides a secure double-iframe architecture per SEP-1865.\n *\n * Message flow:\n * 1. Proxy sends ui/notifications/sandbox-proxy-ready when loaded\n * 2. Host sends ui/notifications/sandbox-resource-ready with HTML\n * 3. Guest UI initializes and communicates via JSON-RPC 2.0\n */\nexport const SandboxedIframe = forwardRef<\n SandboxedIframeHandle,\n SandboxedIframeProps\n>(function SandboxedIframe(\n {\n html,\n sandbox = \"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox\",\n csp,\n permissions,\n sandboxAttrs,\n allowFeatures,\n cspDirectives,\n permissive,\n recordMode,\n onProxyReady,\n onMessage,\n className,\n style,\n colorScheme,\n title = \"Sandboxed Content\",\n hostedMode = false,\n sandboxOrigin = \"\",\n },\n ref\n) {\n const outerRef = useRef<HTMLIFrameElement>(null);\n const [proxyReady, setProxyReady] = useState(false);\n const lastResourceReadyKeyRef = useRef<string | null>(null);\n const onMessageRef = useRef(onMessage);\n const onProxyReadyRef = useRef(onProxyReady);\n onMessageRef.current = onMessage;\n onProxyReadyRef.current = onProxyReady;\n\n // SEP-1865: Host and Sandbox MUST have different origins.\n //\n // Hosted: prefer the operator-configured SANDBOX_ORIGIN\n // (`VITE_MCPJAM_SANDBOX_ORIGIN`). It MUST be a distinct origin from the\n // host app so the sandboxed iframe cannot reach host cookies or storage\n // even when its sandbox carries `allow-same-origin`.\n //\n // Local: keep the localhost ↔ 127.0.0.1 swap so dev gets the same\n // origin-separation property without operator config.\n //\n // Same-origin fallback exists only as a soft-fail for misconfigured\n // hosted deploys; it emits a loud security warning.\n const [sandboxProxyUrl] = useState(() => {\n const proxyPath = hostedMode\n ? \"/api/web/apps/mcp-apps/sandbox-proxy\"\n : \"/api/apps/mcp-apps/sandbox-proxy\";\n\n if (hostedMode && sandboxOrigin) {\n return `${sandboxOrigin}${proxyPath}?v=${Date.now()}`;\n }\n\n const currentHost = window.location.hostname;\n const currentPort = window.location.port;\n const protocol = window.location.protocol;\n\n let sandboxHost: string;\n if (currentHost === \"localhost\") {\n sandboxHost = \"127.0.0.1\";\n } else if (currentHost === \"127.0.0.1\") {\n sandboxHost = \"localhost\";\n } else {\n if (hostedMode) {\n console.warn(\n \"[SandboxedIframe] VITE_MCPJAM_SANDBOX_ORIGIN is not configured;\" +\n \" sandbox iframe is falling back to same-origin.\" +\n \" This is a security regression — the sandbox shares cookies and\" +\n \" storage with the host app. Configure a distinct origin\" +\n \" (e.g. https://sandbox.mcpjam.com) and redeploy.\"\n );\n } else {\n console.warn(\n \"[SandboxedIframe] Cross-origin isolation not available for hostname:\",\n currentHost,\n \"- falling back to same-origin sandbox\"\n );\n }\n sandboxHost = currentHost;\n }\n\n const portSuffix = currentPort ? `:${currentPort}` : \"\";\n return `${protocol}//${sandboxHost}${portSuffix}${proxyPath}?v=${Date.now()}`;\n });\n\n const sandboxProxyOrigin = useMemo(() => {\n try {\n return new URL(sandboxProxyUrl).origin;\n } catch {\n return \"*\";\n }\n }, [sandboxProxyUrl]);\n\n useImperativeHandle(\n ref,\n () => ({\n postMessage: (data: unknown) => {\n outerRef.current?.contentWindow?.postMessage(data, sandboxProxyOrigin);\n },\n getIframeElement: () => outerRef.current,\n }),\n [sandboxProxyOrigin]\n );\n\n const handleMessage = useCallback(\n (event: MessageEvent) => {\n if (event.origin !== sandboxProxyOrigin && sandboxProxyOrigin !== \"*\") {\n return;\n }\n if (event.source !== outerRef.current?.contentWindow) return;\n\n // CSP violation messages (not JSON-RPC) - forward directly\n if (event.data?.type === \"mcp-apps:csp-violation\") {\n onMessageRef.current(event);\n return;\n }\n\n // Whitelisted OpenAI compat messages (not JSON-RPC) - forward directly\n if (\n event.data?.type === \"openai:uploadFile\" ||\n event.data?.type === \"openai:getFileDownloadUrl\" ||\n event.data?.type === \"openai:setWidgetState\" ||\n event.data?.type === \"openai:setOpenInAppUrl\"\n ) {\n onMessageRef.current(event);\n return;\n }\n\n // Tier 2 recorder messages (not JSON-RPC) — forward to the host so the\n // eval authoring preview can capture recorded steps / detect readiness,\n // and receive per-step results from a host-driven replay.\n if (\n event.data?.type === \"recorder:step\" ||\n event.data?.type === \"recorder:ready\" ||\n event.data?.type === \"recorder:replay-result\"\n ) {\n recorderDebug(`forward ${event.data.type}`);\n onMessageRef.current(event);\n return;\n }\n\n const { jsonrpc, method } =\n (event.data as { jsonrpc?: string; method?: string }) || {};\n if (jsonrpc !== \"2.0\") return;\n\n if (method === \"ui/notifications/sandbox-proxy-ready\") {\n setProxyReady(true);\n onProxyReadyRef.current?.();\n return;\n }\n\n if (method?.startsWith(\"ui/notifications/sandbox-\")) {\n return;\n }\n\n onMessageRef.current(event);\n },\n [sandboxProxyOrigin]\n );\n\n useEffect(() => {\n window.addEventListener(\"message\", handleMessage);\n return () => window.removeEventListener(\"message\", handleMessage);\n }, [handleMessage]);\n\n // Build allow attribute for outer iframe based on requested permissions.\n //\n // Same authoritative-profile semantic as `sandboxAttrs` above: when\n // `allowFeatures` is provided (even as `{}`), the profile is the\n // source of truth for non-spec Permissions Policy features, and the\n // renderer's legacy defaults (`local-network-access *`, `midi *`) are\n // dropped. A profile that doesn't list those features models a real\n // host that doesn't emit them — and the iframe must match, or\n // experiments using Web MIDI / Local Network Access would pass in\n // MCPJam while the real host blocks them.\n //\n // The 4 SEP-1865 spec permissions (camera/microphone/geolocation/\n // clipboard-write) ALWAYS flow through from `permissions` regardless\n // of `allowFeatures` — they're orthogonal user-facing knobs. Only the\n // inspector-only legacy defaults are conditional.\n //\n // Per Permissions Policy spec, `;` separates features.\n const outerAllowAttribute = useMemo(\n () => buildOuterAllowAttribute({ permissions, allowFeatures }),\n [permissions, allowFeatures]\n );\n\n // Outer iframe `sandbox=` value.\n //\n // When `sandboxAttrs` is provided (even as `[]`), the profile is the\n // authoritative source: the iframe gets `allow-scripts allow-same-origin`\n // plus exactly what the profile lists. This is what makes \"model the\n // real host's emitted tokens\" actually work — e.g. a Claude-modeled\n // profile with `sandboxAttrs: [\"allow-forms\"]` gets exactly those three\n // tokens, not those PLUS the renderer's legacy permissive default.\n //\n // When `sandboxAttrs` is undefined (no profile opinion), fall back to\n // the caller's `sandbox` prop so existing call sites — which pass a\n // wider permissive baseline — behave unchanged.\n //\n // `undefined` vs `[]` matters here: `[]` is the explicit \"spec-minimum\n // only\" intent, mirroring the canonicalizer's preservation contract.\n const outerSandboxAttribute = useMemo(\n () => buildOuterSandboxAttribute({ sandbox, sandboxAttrs }),\n [sandbox, sandboxAttrs]\n );\n\n const resourceReadyKey = useMemo(\n () =>\n stableStringifyJson({\n csp: csp ?? null,\n cspDirectives: cspDirectives ?? null,\n html: html ?? null,\n permissive: permissive ?? null,\n permissions: permissions ?? null,\n sandbox,\n sandboxAttrs: sandboxAttrs ?? null,\n // Include recordMode so record-capable surfaces receive the recorder\n // shim, and stale/non-recordable surfaces reload without it.\n recordMode: recordMode ?? null,\n }),\n [\n csp,\n cspDirectives,\n html,\n permissive,\n permissions,\n sandbox,\n sandboxAttrs,\n recordMode,\n ]\n );\n\n useEffect(() => {\n if (!proxyReady) lastResourceReadyKeyRef.current = null;\n }, [proxyReady]);\n\n // Send HTML, CSP, and permissions to sandbox when ready (SEP-1865)\n useEffect(() => {\n if (!proxyReady || !html) return;\n const resourceTargetKey = `${sandboxProxyOrigin}\\0${resourceReadyKey}`;\n if (lastResourceReadyKeyRef.current === resourceTargetKey) return;\n lastResourceReadyKeyRef.current = resourceTargetKey;\n\n outerRef.current?.contentWindow?.postMessage(\n {\n jsonrpc: \"2.0\",\n method: \"ui/notifications/sandbox-resource-ready\",\n params: {\n html,\n sandbox,\n csp,\n permissions,\n sandboxAttrs,\n // `allowFeatures` is intentionally NOT forwarded to the proxy:\n // it applies to the OUTER iframe only. The inner iframe gets the\n // 4 spec permissions (via `permissions`) and nothing else, matching\n // real claude.ai's outer-grants-fullscreen / inner-trims-to-spec\n // pattern. Centralizing the outer/inner split here means the proxy\n // can't accidentally widen the inner grant by reading a stale\n // field.\n cspDirectives,\n permissive,\n colorScheme,\n recordMode,\n recorderDebug: isRecorderDebugEnabled(),\n },\n },\n sandboxProxyOrigin\n );\n recorderDebug(\"sent resource ready\", {\n recordMode: !!recordMode,\n recorderDebug: isRecorderDebugEnabled(),\n proxyReady,\n hasHtml: !!html,\n sandboxProxyOrigin,\n });\n // This effect intentionally depends on the semantic payload key instead\n // of raw object props. Re-sending `sandbox-resource-ready` makes the\n // proxy assign inner `srcdoc` again, which restarts the app even when the\n // HTML/CSP/permission payload is unchanged.\n // `colorScheme` and `allowFeatures` are intentionally OMITTED from\n // this dep list. The proxy handles `sandbox-resource-ready` by\n // rebuilding the CSP and assigning `inner.srcdoc`, which reloads the\n // widget and drops any in-iframe state — so we MUST NOT re-fire this\n // effect for props that don't actually affect the inner iframe.\n //\n // - `colorScheme`: flows through the dedicated\n // `sandbox-color-scheme-changed` effect below, which updates the\n // inner document's color-scheme without a reload.\n // - `allowFeatures`: applies only to the OUTER iframe's `allow=`\n // attribute (computed in `outerAllowAttribute` above and applied\n // declaratively via JSX, so React reconciliation handles the\n // update without a reload). It's not forwarded in the params\n // payload at all (see the comment above the field). Re-including\n // it here would silently full-reload the widget every time a\n // user toggles an entry in the AppExtensionTab editor.\n }, [proxyReady, html, resourceReadyKey, sandboxProxyOrigin]);\n\n // Keep iframe color-scheme in sync without reloading the widget document.\n useEffect(() => {\n if (!proxyReady || !colorScheme) return;\n\n outerRef.current?.contentWindow?.postMessage(\n {\n jsonrpc: \"2.0\",\n method: \"ui/notifications/sandbox-color-scheme-changed\",\n params: { colorScheme },\n },\n sandboxProxyOrigin\n );\n }, [proxyReady, colorScheme, sandboxProxyOrigin]);\n\n const iframeStyle = colorScheme ? { ...style, colorScheme } : style;\n\n // Browsers apply iframe `sandbox=` only on navigation, not when the\n // attribute mutates on an already-loaded frame. If the user edits a\n // profile from permissive tokens to `[]` while the widget is mounted,\n // React updates the attribute but the live iframe keeps the OLD\n // grants until something forces a navigation — so the matrix/editor\n // can show stricter modeling while the running widget still has\n // popups/forms/etc. enabled. Key the outer iframe on\n // outerSandboxAttribute so React unmounts + remounts (= fresh\n // navigation) whenever the effective sandbox flags change. Resetting\n // proxyReady below ensures the resource-ready effect re-fires after\n // the new proxy load completes (otherwise proxyReady would stay\n // `true` from the prior iframe and the widget wouldn't get re-sent\n // to the new proxy).\n useEffect(() => {\n setProxyReady(false);\n }, [outerSandboxAttribute]);\n\n return (\n <iframe\n key={outerSandboxAttribute}\n ref={outerRef}\n src={sandboxProxyUrl}\n sandbox={outerSandboxAttribute}\n allow={outerAllowAttribute}\n title={title}\n className={className}\n style={iframeStyle}\n />\n );\n});\n","import { useRef, useState, useEffect } from \"react\";\nimport { SandboxedIframe, SandboxedIframeHandle } from \"./sandboxed-iframe\";\nimport {\n AppBridge,\n PostMessageTransport,\n type McpUiHostCapabilities,\n type McpUiHostContext,\n type McpUiResourceCsp,\n type McpUiResourcePermissions,\n} from \"@modelcontextprotocol/ext-apps/app-bridge\";\n// Pure JSON-RPC parser + logging transport are shared, framework-free runtime\n// helpers in the SDK.\nimport { extractMethod, LoggingTransport } from \"@mcpjam/sdk/widget-runtime\";\n// The `CspMode` type comes from the package's `WidgetHost` contract.\nimport { type CspMode } from \"./widget-host\";\n// The package owns lifecycle + bridge; the inspector injects modal CHROME\n// (its design-system <Dialog>) + the widget-content fetch via the WidgetHost.\nimport { useWidgetHost } from \"./widget-host-context\";\nimport { useAppToolsRegistry } from \"./app-tools-registry\";\n\nexport interface McpAppsModalProps {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n title: string;\n template: string | null;\n params: Record<string, unknown>;\n registerBridgeHandlers: (bridge: AppBridge) => void;\n /**\n * SEP-1865 App-Provided Tools: the modal mounts its own AppBridge\n * against a fresh iframe. Because the modal overrides\n * `bridge.oninitialized` to suppress inline-only side effects, the\n * inline registration path (which lives inside that handler) is\n * skipped. The modal calls this helper directly after handshake — and\n * again on every `notifications/tools/list_changed` — so the model\n * sees the app's tools while the modal is the active surface for this\n * tool call. Inline + modal coexist in `useAppToolsRegistry` via\n * `surface`-keyed dedup; the registry's active-bridge fallback\n * restores inline when the modal unregisters on teardown.\n */\n refreshAppProvidedTools: (\n bridge: AppBridge,\n bridgeId: string,\n options?: {\n force?: boolean;\n surface?: \"inline\" | \"modal\";\n getIframeElement?: () => HTMLIFrameElement | null;\n isLive?: () => boolean;\n }\n ) => Promise<void>;\n widgetCsp: McpUiResourceCsp | undefined;\n widgetPermissions: McpUiResourcePermissions | undefined;\n widgetPermissive: boolean;\n widgetSandboxAttrs: string[] | undefined;\n widgetAllowFeatures: Record<string, string> | undefined;\n widgetCspDirectives: Record<string, string[]> | undefined;\n hostContextRef: React.RefObject<McpUiHostContext | null>;\n serverId: string;\n resourceUri: string;\n toolCallId: string;\n toolName: string;\n cspMode: CspMode;\n /**\n * Resolved compat-runtime flag the inline renderer already computed\n * for this host. The modal mounts its own iframe and fetches its own\n * HTML; passing the flag down (rather than re-resolving here) keeps\n * the modal and inline fetches in lockstep so the modal can't end up\n * shimmed while the inline view isn't (or vice versa).\n */\n injectOpenAiCompat: boolean;\n /**\n * Resolved MCP Apps `HostCapabilities` blob the inline renderer\n * already computed via `resolveEffectiveHostCapabilities`. Pass-down\n * mirrors {@link injectOpenAiCompat}: the modal mounts its own\n * AppBridge and we want inline + modal to advertise an identical\n * surface to the widget. Previously the modal hardcoded `{ openLinks,\n * serverTools, serverResources, logging, updateModelContext, message }`\n * — that masked Copilot's M365-published subset (which strips\n * `serverResources` / `logging`) and any user override in\n * `mcpProfile.apps.mcpAppsOverrides`. The `sandbox` slice is composed\n * separately at AppBridge construction from the widget-level CSP /\n * permissions props.\n */\n effectiveHostCapabilities: Omit<McpUiHostCapabilities, \"sandbox\">;\n /**\n * Resolved AppBridge `hostInfo` the inline renderer already computed\n * (`resolvers.resolveHostInfo(activeMcpProfile)` with the inspector\n * fallback). Passed down rather than re-resolved here so the modal and\n * inline bridges hand the widget an identical `hostInfo`, and so the modal\n * holds no inspector-app-state coupling (`useActiveMcpProfile` /\n * `resolveHostInfo` now live only in the renderer's `useWidgetHost()`).\n */\n hostInfo: { name: string; version: string };\n /**\n * Whether the active surface routes through web-managed (hosted) servers.\n * Sourced from the renderer's `host.surface.webManagedServers` so the modal's\n * widget-content fetch hits the same endpoint as the inline view.\n */\n webManagedServers: boolean;\n toolInputRef: React.RefObject<Record<string, unknown> | undefined>;\n toolOutputRef: React.RefObject<unknown>;\n themeModeRef: React.RefObject<string>;\n addUiLog: (log: {\n widgetId: string;\n serverId: string;\n direction: \"host-to-ui\" | \"ui-to-host\";\n protocol: string;\n method: string;\n message: unknown;\n }) => void;\n onCspViolation: (event: MessageEvent) => void;\n}\n\nexport function McpAppsModal({\n open,\n onOpenChange,\n title,\n template,\n params,\n registerBridgeHandlers,\n refreshAppProvidedTools,\n widgetCsp,\n widgetPermissions,\n widgetPermissive,\n widgetSandboxAttrs,\n widgetAllowFeatures,\n widgetCspDirectives,\n hostContextRef,\n serverId,\n resourceUri,\n toolCallId,\n toolName,\n cspMode,\n injectOpenAiCompat,\n effectiveHostCapabilities,\n hostInfo,\n webManagedServers,\n toolInputRef,\n toolOutputRef,\n themeModeRef,\n addUiLog,\n onCspViolation,\n}: McpAppsModalProps) {\n const host = useWidgetHost();\n const Modal = host.components?.Modal;\n const [modalHtml, setModalHtml] = useState<string | null>(null);\n const modalSandboxRef = useRef<SandboxedIframeHandle>(null);\n const modalBridgeRef = useRef<AppBridge | null>(null);\n // SEP-1865 App-Provided Tools: per-modal-bridge identity. Distinct\n // from the renderer's inline ref so inline + modal can coexist in\n // `useAppToolsRegistry` and `surface`-keyed dedup keeps each surface's\n // tools separate. Cleared on teardown so `isLive` short-circuits any\n // in-flight `listTools` after the modal closes.\n const modalAppToolsBridgeIdRef = useRef<string | null>(null);\n const modalColorScheme =\n hostContextRef.current?.theme === \"light\" ||\n hostContextRef.current?.theme === \"dark\"\n ? hostContextRef.current.theme\n : themeModeRef.current === \"light\" || themeModeRef.current === \"dark\"\n ? themeModeRef.current\n : undefined;\n\n // Fetch modal HTML when modal opens\n useEffect(() => {\n if (!open) {\n // Clean up when modal closes\n modalBridgeRef.current?.close().catch(() => {});\n modalBridgeRef.current = null;\n // SEP-1865 App-Provided Tools: drop this modal's registration so\n // the next chat POST snapshot omits its aliases and the registry's\n // active-bridge fallback restores any coexisting inline surface.\n if (modalAppToolsBridgeIdRef.current) {\n useAppToolsRegistry\n .getState()\n .unregisterInstance(modalAppToolsBridgeIdRef.current);\n modalAppToolsBridgeIdRef.current = null;\n }\n setModalHtml(null);\n return;\n }\n\n const fetchModalHtml = async () => {\n try {\n const { html } = await host.services.fetchWidgetContent({\n serverId,\n forceWebEndpoint: webManagedServers,\n resourceUri,\n toolInput: toolInputRef.current,\n toolOutput: toolOutputRef.current,\n toolId: toolCallId,\n toolName,\n theme: themeModeRef.current,\n cspMode,\n injectOpenAiCompat,\n template: template ?? undefined,\n viewMode: \"modal\",\n viewParams: params,\n });\n setModalHtml(html);\n } catch (err) {\n console.error(\"[MCP Apps] Failed to fetch modal HTML\", err);\n }\n };\n\n fetchModalHtml();\n }, [\n open,\n template,\n params,\n serverId,\n resourceUri,\n toolCallId,\n toolName,\n cspMode,\n injectOpenAiCompat,\n webManagedServers,\n toolInputRef,\n toolOutputRef,\n themeModeRef,\n ]);\n\n // Initialize modal bridge when modal HTML is ready\n useEffect(() => {\n if (!modalHtml || !open) return;\n const iframe = modalSandboxRef.current?.getIframeElement();\n if (!iframe?.contentWindow) return;\n\n // Vendor-trait HostCapabilities come from the inline renderer's\n // resolver (matrix-derived + user override). Sandbox is composed\n // here from the widget-level resource CSP / permissions per\n // SEP-1865 (sandbox is per-resource, not a vendor trait — see\n // HostMcpProfile.mcpAppsCapabilities doc). `hostInfo` is the same\n // resolved blob the inline renderer hands its bridge (ChatGPT-like\n // templates may override it via mcpProfile.apps.uiInitialize.hostInfo);\n // passing it down keeps inline + modal in lockstep.\n const bridge = new AppBridge(\n null,\n hostInfo,\n {\n ...effectiveHostCapabilities,\n sandbox: {\n csp: widgetPermissive ? undefined : widgetCsp,\n permissions: widgetPermissions,\n },\n },\n { hostContext: hostContextRef.current ?? {} },\n );\n\n // Reuse the same handlers as the inline bridge\n registerBridgeHandlers(bridge);\n\n // Override onsizechange to target modal iframe instead of main widget\n bridge.onsizechange = ({ width, height }) => {\n const modalIframe = modalSandboxRef.current?.getIframeElement();\n if (!modalIframe) return;\n\n if (height !== undefined) {\n const style = getComputedStyle(modalIframe);\n const isBorderBox = style.boxSizing === \"border-box\";\n\n let adjustedHeight = height;\n if (isBorderBox) {\n adjustedHeight +=\n parseFloat(style.borderTopWidth) +\n parseFloat(style.borderBottomWidth);\n }\n\n modalIframe.style.height = `${adjustedHeight}px`;\n }\n\n if (width !== undefined) {\n modalIframe.style.width = `${width}px`;\n }\n };\n\n // Override oninitialized so it doesn't set the main isReady state.\n // SEP-1865 App-Provided Tools: this replaces (not wraps) the\n // inline handler set by `registerBridgeHandlers`, so we have to\n // re-run the parts of that handler that matter for the modal\n // bridge — currently the app-tools registration. Inline state\n // mutations (setIsReady, setReinitCount, display-mode publish,\n // etc.) intentionally stay skipped: the modal has its own\n // lifecycle and must not steer the inline renderer's React state.\n bridge.oninitialized = () => {\n // Send tool input/output to the modal bridge after initialization\n const resolvedToolInput = toolInputRef.current ?? {};\n bridge.sendToolInput({ arguments: resolvedToolInput });\n if (toolOutputRef.current) {\n // ext-apps (v1-sdk peer) and the v2 client each declare a structurally\n // identical but nominally distinct CallToolResult; cast to exactly what\n // the bridge accepts at this Apps-compat seam (§1D).\n bridge.sendToolResult(\n toolOutputRef.current as Parameters<typeof bridge.sendToolResult>[0],\n );\n }\n\n const appCaps = bridge.getAppCapabilities();\n if (appCaps?.tools) {\n const bridgeId =\n modalAppToolsBridgeIdRef.current ?? crypto.randomUUID();\n modalAppToolsBridgeIdRef.current = bridgeId;\n void refreshAppProvidedTools(bridge, bridgeId, {\n surface: \"modal\",\n getIframeElement: () =>\n modalSandboxRef.current?.getIframeElement() ?? null,\n isLive: () => modalAppToolsBridgeIdRef.current === bridgeId,\n });\n }\n };\n\n modalBridgeRef.current = bridge;\n const pendingRpcMethods = new Map<string | number, string>();\n\n const transport = new LoggingTransport(\n new PostMessageTransport(iframe.contentWindow, iframe.contentWindow),\n {\n onSend: (message) => {\n const request = message as { id?: string | number; method?: string };\n if (\n typeof request.method === \"string\" &&\n (typeof request.id === \"string\" || typeof request.id === \"number\")\n ) {\n pendingRpcMethods.set(request.id, request.method);\n }\n addUiLog({\n widgetId: `${toolCallId}-modal`,\n serverId,\n direction: \"host-to-ui\",\n protocol: \"mcp-apps\",\n method: extractMethod(message, \"mcp-apps\"),\n message,\n });\n },\n onReceive: (message) => {\n const response = message as {\n id?: string | number;\n result?: unknown;\n error?: unknown;\n };\n const correlatedMethod =\n (response.result !== undefined || response.error !== undefined) &&\n (typeof response.id === \"string\" || typeof response.id === \"number\")\n ? pendingRpcMethods.get(response.id)\n : undefined;\n if (correlatedMethod && response.id !== undefined) {\n pendingRpcMethods.delete(response.id);\n }\n const method =\n correlatedMethod ?? extractMethod(message, \"mcp-apps\");\n // SEP-1865 App-Provided Tools: re-list when the modal app\n // signals a tools-list change. Mirrors the inline renderer's\n // `onReceive` hook so a `tool.update()` / `enable()` /\n // `disable()` from the modal app is reflected in the chat\n // snapshot's advertised aliases.\n if (method === \"notifications/tools/list_changed\") {\n const bridgeId = modalAppToolsBridgeIdRef.current;\n if (bridgeId) {\n void refreshAppProvidedTools(bridge, bridgeId, {\n force: true,\n surface: \"modal\",\n getIframeElement: () =>\n modalSandboxRef.current?.getIframeElement() ?? null,\n isLive: () => modalAppToolsBridgeIdRef.current === bridgeId,\n });\n }\n }\n addUiLog({\n widgetId: `${toolCallId}-modal`,\n serverId,\n direction: \"ui-to-host\",\n protocol: \"mcp-apps\",\n method,\n message,\n });\n },\n },\n );\n\n let isActive = true;\n bridge.connect(transport).catch((error) => {\n if (!isActive) return;\n console.error(\"[MCP Apps] Modal bridge connection failed\", error);\n });\n\n return () => {\n isActive = false;\n modalBridgeRef.current = null;\n // SEP-1865 App-Provided Tools: unregister on effect teardown\n // (component unmount or modalHtml refetch). Clearing the ref\n // first ensures any in-flight `listTools` short-circuits via\n // `isLive` and doesn't re-register after we've torn down.\n if (modalAppToolsBridgeIdRef.current) {\n const bridgeId = modalAppToolsBridgeIdRef.current;\n modalAppToolsBridgeIdRef.current = null;\n useAppToolsRegistry.getState().unregisterInstance(bridgeId);\n }\n bridge.close().catch(() => {});\n };\n }, [\n modalHtml,\n open,\n addUiLog,\n serverId,\n toolCallId,\n registerBridgeHandlers,\n refreshAppProvidedTools,\n widgetPermissive,\n widgetCsp,\n widgetPermissions,\n hostContextRef,\n toolInputRef,\n toolOutputRef,\n hostInfo,\n effectiveHostCapabilities,\n ]);\n\n const handleModalMessage = (event: MessageEvent) => {\n const data = event.data;\n if (!data) return;\n\n // Forward CSP violations to parent handler\n if (data.type === \"mcp-apps:csp-violation\") {\n onCspViolation(event);\n }\n };\n\n // Modal chrome is host-injected (the inspector's design-system <Dialog>). A\n // host that doesn't supply `components.Modal` opts out of the modal surface.\n if (!Modal) return null;\n\n return (\n <Modal open={open} onClose={() => onOpenChange(false)} title={title}>\n <div className=\"flex-1 w-full h-full min-h-0 overflow-auto\">\n {modalHtml && (\n <SandboxedIframe\n ref={modalSandboxRef}\n html={modalHtml}\n sandbox=\"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox\"\n csp={widgetCsp}\n permissions={widgetPermissions}\n permissive={widgetPermissive}\n sandboxAttrs={widgetSandboxAttrs}\n allowFeatures={widgetAllowFeatures}\n cspDirectives={widgetCspDirectives}\n colorScheme={modalColorScheme}\n onMessage={handleModalMessage}\n title={`MCP App Modal: ${title}`}\n hostedMode={host.surface.hostedMode}\n sandboxOrigin={host.surface.sandboxOrigin}\n className=\"min-w-full border-0 rounded-md bg-transparent overflow-hidden\"\n style={{\n height: \"100%\",\n minHeight: \"400px\",\n backgroundColor: \"transparent\",\n }}\n />\n )}\n </div>\n </Modal>\n );\n}\n","// Tier-B (Phase 3d-ii-c): the file-message bridge moved into @mcpjam/widget-react\n// alongside the renderer. The inspector-supplied `authFetch` (session-token auth)\n// and `hostedMode` flag are passed in as a `WidgetFileMessageContext` rather than\n// imported from `@/lib/*`, so this module carries no inspector internals.\n\n/** Validates the inspector's uploaded-file id format (`file_<hex/uuid>`). */\nconst UPLOADED_FILE_ID_PATTERN = /^file_[0-9a-f-]+$/;\nfunction isValidUploadedFileId(fileId: unknown): fileId is string {\n return typeof fileId === \"string\" && UPLOADED_FILE_ID_PATTERN.test(fileId);\n}\n\n/** Host-supplied capabilities the file-message handlers need. */\nexport interface WidgetFileMessageContext {\n /** Session-authenticated fetch (`host.services.authFetch`). */\n authFetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n /** Whether the app runs against the hosted backend (`host.surface.hostedMode`). */\n hostedMode: boolean;\n}\n\ntype UploadFileMessage = {\n type: \"openai:uploadFile\";\n callId: unknown;\n data?: unknown;\n mimeType?: unknown;\n fileName?: unknown;\n};\n\ntype GetFileDownloadUrlMessage = {\n type: \"openai:getFileDownloadUrl\";\n callId: unknown;\n fileId: unknown;\n};\n\ntype UploadFileResponseMessage = {\n type: \"openai:uploadFile:response\";\n callId: unknown;\n result?: { fileId: string };\n error?: string;\n};\n\ntype GetFileDownloadUrlResponseMessage = {\n type: \"openai:getFileDownloadUrl:response\";\n callId: unknown;\n result?: { downloadUrl: string };\n error?: string;\n};\n\nexport type WidgetFileResponseMessage =\n | UploadFileResponseMessage\n | GetFileDownloadUrlResponseMessage;\n\nexport type SendWidgetFileResponse = (\n message: WidgetFileResponseMessage,\n) => void;\n\nfunction buildWidgetDownloadUrl(fileId: string, hostedMode: boolean): string {\n const loc = window.location;\n const widgetHost = loc.hostname === \"localhost\" ? \"127.0.0.1\" : \"localhost\";\n const basePath = hostedMode\n ? \"/api/web/apps/files/file\"\n : \"/api/apps/files/file\";\n return `${loc.protocol}//${widgetHost}:${loc.port}${basePath}/${fileId}`;\n}\n\nexport async function handleUploadFileMessage(\n data: UploadFileMessage,\n sendResponse: SendWidgetFileResponse,\n { authFetch, hostedMode }: WidgetFileMessageContext,\n): Promise<void> {\n const uploadCallId = data.callId;\n if (hostedMode) {\n sendResponse({\n type: \"openai:uploadFile:response\",\n callId: uploadCallId,\n error: \"File upload is not supported in hosted mode\",\n });\n return;\n }\n\n try {\n const resp = await authFetch(\"/api/apps/files/upload-file\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n data: data.data,\n mimeType: data.mimeType,\n fileName: data.fileName,\n }),\n });\n if (!resp.ok) {\n const body = (await resp\n .json()\n .catch(() => ({ error: resp.statusText }))) as {\n error?: string;\n };\n sendResponse({\n type: \"openai:uploadFile:response\",\n callId: uploadCallId,\n error: body.error || \"Upload failed\",\n });\n return;\n }\n\n const { fileId } = (await resp.json()) as { fileId: string };\n sendResponse({\n type: \"openai:uploadFile:response\",\n callId: uploadCallId,\n result: { fileId },\n });\n } catch (err) {\n sendResponse({\n type: \"openai:uploadFile:response\",\n callId: uploadCallId,\n error: err instanceof Error ? err.message : \"Upload failed\",\n });\n }\n}\n\nexport function handleGetFileDownloadUrlMessage(\n data: GetFileDownloadUrlMessage,\n sendResponse: SendWidgetFileResponse,\n { hostedMode }: Pick<WidgetFileMessageContext, \"hostedMode\">,\n): void {\n const dlCallId = data.callId;\n if (hostedMode) {\n sendResponse({\n type: \"openai:getFileDownloadUrl:response\",\n callId: dlCallId,\n error: \"File download is not supported in hosted mode\",\n });\n return;\n }\n\n const fileId = data.fileId;\n if (!isValidUploadedFileId(fileId)) {\n sendResponse({\n type: \"openai:getFileDownloadUrl:response\",\n callId: dlCallId,\n error: \"Invalid fileId\",\n });\n return;\n }\n\n sendResponse({\n type: \"openai:getFileDownloadUrl:response\",\n callId: dlCallId,\n result: { downloadUrl: buildWidgetDownloadUrl(fileId, hostedMode) },\n });\n}\n","import { createContext, useContext, type ReactNode } from \"react\";\n\nconst WidgetSurfaceHostContext = createContext(false);\n\nexport function WidgetSurfaceHostProvider({\n children,\n}: {\n children: ReactNode;\n}) {\n return (\n <WidgetSurfaceHostContext.Provider value={true}>\n {children}\n </WidgetSurfaceHostContext.Provider>\n );\n}\n\nexport function usePersistentWidgetSurfaceHost() {\n return useContext(WidgetSurfaceHostContext);\n}\n","import { create } from \"zustand\";\nimport type { MCPAppsRendererProps } from \"./mcp-apps-renderer\";\n\nexport type WidgetSurfaceId = string;\n\ninterface WidgetSurfaceRegistration {\n toolCallId: string;\n order: number;\n props: MCPAppsRendererProps;\n anchorElement: HTMLDivElement | null;\n}\n\nexport interface WidgetSurfaceRecord {\n surfaceId: WidgetSurfaceId;\n chatSessionId?: string;\n initialToolCallId: string;\n latestToolCallId: string;\n registrations: Map<string, WidgetSurfaceRegistration>;\n}\n\ninterface WidgetSurfaceStoreState {\n surfaces: Map<WidgetSurfaceId, WidgetSurfaceRecord>;\n nextOrder: number;\n upsertRegistration: (\n surfaceId: WidgetSurfaceId,\n toolCallId: string,\n props: MCPAppsRendererProps\n ) => void;\n setAnchor: (\n surfaceId: WidgetSurfaceId,\n toolCallId: string,\n anchorElement: HTMLDivElement | null\n ) => void;\n releaseRegistration: (surfaceId: WidgetSurfaceId, toolCallId: string) => void;\n clearChatSession: (chatSessionId?: string) => void;\n}\n\nexport const useWidgetSurfaceStore = create<WidgetSurfaceStoreState>((set) => ({\n surfaces: new Map(),\n nextOrder: 0,\n\n upsertRegistration: (surfaceId, toolCallId, props) => {\n set((state) => {\n const surfaces = new Map(state.surfaces);\n const existing = surfaces.get(surfaceId);\n const registrations = new Map(existing?.registrations);\n const currentRegistration = registrations.get(toolCallId);\n const isNewRegistration = !currentRegistration;\n const order = currentRegistration?.order ?? state.nextOrder;\n const latestRegistration = existing?.registrations.get(\n existing.latestToolCallId\n );\n const shouldBecomeLatest =\n !existing ||\n !latestRegistration ||\n (isNewRegistration && order > latestRegistration.order);\n\n registrations.set(toolCallId, {\n toolCallId,\n order,\n props,\n anchorElement: currentRegistration?.anchorElement ?? null,\n });\n\n surfaces.set(surfaceId, {\n surfaceId,\n chatSessionId: props.chatSessionId,\n initialToolCallId: existing?.initialToolCallId ?? toolCallId,\n latestToolCallId: shouldBecomeLatest\n ? toolCallId\n : existing.latestToolCallId,\n registrations,\n });\n\n return {\n surfaces,\n nextOrder: isNewRegistration ? state.nextOrder + 1 : state.nextOrder,\n };\n });\n },\n\n setAnchor: (surfaceId, toolCallId, anchorElement) => {\n set((state) => {\n const existing = state.surfaces.get(surfaceId);\n const registration = existing?.registrations.get(toolCallId);\n if (!existing || !registration) return {};\n if (registration.anchorElement === anchorElement) return {};\n\n const registrations = new Map(existing.registrations);\n registrations.set(toolCallId, {\n ...registration,\n anchorElement,\n });\n const surfaces = new Map(state.surfaces);\n surfaces.set(surfaceId, {\n ...existing,\n registrations,\n });\n return { surfaces };\n });\n },\n\n releaseRegistration: (surfaceId, toolCallId) => {\n set((state) => {\n const existing = state.surfaces.get(surfaceId);\n if (!existing || !existing.registrations.has(toolCallId)) return {};\n\n const surfaces = new Map(state.surfaces);\n const registrations = new Map(existing.registrations);\n registrations.delete(toolCallId);\n\n if (registrations.size === 0) {\n surfaces.delete(surfaceId);\n return { surfaces };\n }\n\n let latestRegistration: WidgetSurfaceRegistration | null = null;\n for (const registration of registrations.values()) {\n if (\n latestRegistration === null ||\n registration.order > latestRegistration.order\n ) {\n latestRegistration = registration;\n }\n }\n\n surfaces.set(surfaceId, {\n ...existing,\n latestToolCallId:\n existing.latestToolCallId === toolCallId\n ? latestRegistration?.toolCallId ?? existing.latestToolCallId\n : existing.latestToolCallId,\n registrations,\n });\n return { surfaces };\n });\n },\n\n clearChatSession: (chatSessionId) => {\n set((state) => {\n // Skip the Map allocation + subscriber notification when no surface\n // belongs to this session (the common case on Thread unmount).\n let hasMatch = false;\n for (const surface of state.surfaces.values()) {\n if (surface.chatSessionId === chatSessionId) {\n hasMatch = true;\n break;\n }\n }\n if (!hasMatch) return {};\n\n const surfaces = new Map(state.surfaces);\n for (const [surfaceId, surface] of state.surfaces) {\n if (surface.chatSessionId === chatSessionId) {\n surfaces.delete(surfaceId);\n }\n }\n return { surfaces };\n });\n },\n}));\n\nexport function getRenderableSurfaceEntries(\n surfaces: Map<WidgetSurfaceId, WidgetSurfaceRecord>,\n chatSessionId?: string\n) {\n const entries: Array<{\n surfaceId: WidgetSurfaceId;\n anchorElement: HTMLDivElement | null;\n initialToolCallId: string;\n props: MCPAppsRendererProps;\n }> = [];\n\n for (const surface of surfaces.values()) {\n if (surface.chatSessionId !== chatSessionId) continue;\n const latestRegistration = surface.registrations.get(\n surface.latestToolCallId\n );\n if (!latestRegistration) continue;\n // Keep the mounted iframe under its original row. Reparenting a live\n // iframe can reload its browsing context in real browsers, which wipes\n // in-memory app state for stateful widgets like games.\n const initialRegistration = surface.registrations.get(\n surface.initialToolCallId\n );\n const fallbackAnchor =\n Array.from(surface.registrations.values()).find(\n (registration) => registration.anchorElement !== null\n )?.anchorElement ?? null;\n\n entries.push({\n surfaceId: surface.surfaceId,\n anchorElement: initialRegistration?.anchorElement ?? fallbackAnchor,\n initialToolCallId: surface.initialToolCallId,\n props: latestRegistration.props,\n });\n }\n\n return entries;\n}\n","/**\n * MCPAppsRenderer - SEP-1865 MCP Apps Renderer\n *\n * Renders MCP Apps widgets using the SEP-1865 protocol:\n * - JSON-RPC 2.0 over postMessage\n * - Double-iframe sandbox architecture\n * - tools/call, resources/read, ui/message, ui/open-link support\n *\n * Uses SandboxedIframe for DRY double-iframe setup.\n */\n\nimport {\n useRef,\n useState,\n useEffect,\n useLayoutEffect,\n useMemo,\n useCallback,\n type CSSProperties,\n} from \"react\";\nimport { useToolInputStreaming, type ToolState } from \"./useToolInputStreaming\";\nimport { ExternalLink, Loader2, X } from \"lucide-react\";\nimport { SandboxedIframe, SandboxedIframeHandle } from \"./sandboxed-iframe\";\nimport {\n resolveSandboxCsp,\n resolveSandboxPermissions,\n} from \"@mcpjam/sdk/browser\";\nimport {\n AppBridge,\n PostMessageTransport,\n type McpUiHostContext,\n type McpUiResourceCsp,\n type McpUiResourcePermissions,\n} from \"@modelcontextprotocol/ext-apps/app-bridge\";\nimport type { ContentBlock } from \"@modelcontextprotocol/client\";\n// Framework-free runtime helpers shared with the inspector + eval harness.\nimport {\n registerHostBridgeHandlers,\n LoggingTransport,\n extractMethod,\n stableStringifyJson,\n type AppToolInvocationUpdate,\n} from \"@mcpjam/sdk/widget-runtime\";\nimport { McpAppsModal } from \"./mcp-apps-modal\";\nimport {\n handleGetFileDownloadUrlMessage,\n handleUploadFileMessage,\n} from \"./widget-file-messages\";\nimport {\n useAppToolsRegistry,\n type AppToolDescriptor,\n} from \"./app-tools-registry\";\nimport { readToolResultMeta } from \"./tool-result-utils\";\nimport { usePersistentWidgetSurfaceHost } from \"./widget-surface-context\";\nimport { useWidgetSurfaceStore } from \"./widget-surface-store\";\n// The renderer reads its ambient ENV inputs, resolver fns, services, surface\n// flags, debug sink and injected chrome through the package's `useWidgetHost()`\n// context (supplied by the inspector's adapter via `<WidgetHostProvider>`). The\n// contract type-only symbols come from the package's `WidgetHost` module.\nimport { useWidgetHost } from \"./widget-host-context\";\nimport {\n type UiProtocol,\n type CspMode,\n type DisplayMode,\n type OpenAiAppsCapabilities,\n type ResolvedMcpAppsCapabilities,\n type WidgetLifecycleEvent,\n type WidgetHostResolvers,\n type WidgetDebugSink,\n} from \"./widget-host\";\n\n// The debug sink is OPTIONAL on the contract — a non-inspector host can omit it\n// and lose only the Sandbox/Network debug panels. The renderer routes every\n// instrumentation call through this no-op fallback so those call sites stay\n// branch-free when no sink is injected.\nconst NOOP_WIDGET_DEBUG_SINK: WidgetDebugSink = {\n recordMount: () => {},\n setWidgetDebugInfo: () => {},\n setWidgetState: () => {},\n setWidgetGlobals: () => {},\n setWidgetCsp: () => {},\n addCspViolation: () => {},\n clearCspViolations: () => {},\n setWidgetModelContext: () => {},\n setWidgetHtml: () => {},\n setSandboxApplied: () => {},\n appendLifecycle: () => {},\n addTrafficLog: () => {},\n};\n\n// Injected by Vite at build time from package.json\ndeclare const __APP_VERSION__: string;\n\n// Default input schema for tools without metadata\nconst DEFAULT_INPUT_SCHEMA = { type: \"object\" } as const;\n\nconst SUPPRESSED_UI_LOG_METHODS = new Set([\"ui/notifications/size-changed\"]);\nconst PIP_MAX_HEIGHT = \"min(40vh, 600px)\";\nconst SAFE_OPEN_IN_APP_PROTOCOLS = new Set([\"http:\", \"https:\"]);\n\nfunction toSafeOpenInAppUrl(value: string): string | null {\n try {\n const parsed = new URL(value);\n return SAFE_OPEN_IN_APP_PROTOCOLS.has(parsed.protocol) ? parsed.href : null;\n } catch {\n return null;\n }\n}\n\n/**\n * A widget-supplied `ui/download-file` `resource_link` may only target http(s):\n * that gate is what keeps `javascript:`/`data:`/`file:` URLs out of the\n * `window.open` the host performs on the widget's behalf. Resolves relative URIs\n * against the host document. Returns the absolute href when allowed, else null —\n * a single predicate shared by the pre-prompt reject and the download loop so\n * the two can't drift apart and silently weaken the gate.\n */\nfunction toSafeDownloadLinkUrl(uri: string): string | null {\n try {\n const parsed = new URL(uri, window.location.href);\n return SAFE_OPEN_IN_APP_PROTOCOLS.has(parsed.protocol) ? parsed.href : null;\n } catch {\n return null;\n }\n}\n\nfunction readExplicitBaseHref(html: string | null): string | null {\n if (!html) return null;\n\n if (typeof DOMParser !== \"undefined\") {\n try {\n const parsed = new DOMParser().parseFromString(html, \"text/html\");\n const href = parsed.querySelector(\"base[href]\")?.getAttribute(\"href\");\n if (href?.trim()) return href.trim();\n } catch {\n // Fall through to the lightweight parser below.\n }\n }\n\n const match = html.match(/<base\\b[^>]*\\bhref\\s*=\\s*[\"']([^\"']+)[\"']/i);\n return match?.[1]?.trim() || null;\n}\n\nfunction resolveExplicitBaseUrl(\n html: string | null,\n resourceUri: string\n): string | null {\n const baseHref = readExplicitBaseHref(html);\n if (!baseHref) return null;\n\n const absolute = toSafeOpenInAppUrl(baseHref);\n if (absolute) return absolute;\n\n const resourceUrl = toSafeOpenInAppUrl(resourceUri);\n if (!resourceUrl) return null;\n\n try {\n return toSafeOpenInAppUrl(new URL(baseHref, resourceUrl).href);\n } catch {\n return null;\n }\n}\n\nfunction resolveOpenInAppHref(\n href: unknown,\n explicitBaseUrl: string | null\n): string | null {\n if (typeof href !== \"string\") return null;\n const trimmed = href.trim();\n if (!trimmed) return null;\n\n const absolute = toSafeOpenInAppUrl(trimmed);\n if (absolute) return absolute;\n if (!explicitBaseUrl) return null;\n\n try {\n return toSafeOpenInAppUrl(new URL(trimmed, explicitBaseUrl).href);\n } catch {\n return null;\n }\n}\n\n/**\n * Origins the hosted-mode sandbox clamp must strip from any widget-\n * declared CSP. A hosted widget could otherwise declare an MCPJam\n * origin in `connectDomains` and use the user's authenticated session\n * to exfiltrate data through the iframe. Forwarded into the SDK via\n * `resolveSandboxCsp`'s `hostedClampExtraDeny` — an SDK-internal API\n * for hosted-mode origin stripping, distinct from anything the user can\n * configure (SEP-1865 host policies are allowlist-only).\n *\n * Wildcards cover all subdomains (api, staging, www, etc.) without\n * having to enumerate them. The bare-host entry catches widgets that\n * declare the apex domain directly.\n */\nconst MCPJAM_HOSTED_CLAMP_ORIGINS: ReadonlyArray<string> = [\n \"https://*.mcpjam.com\",\n \"https://mcpjam.com\",\n];\n\ntype HostStyleVariables = NonNullable<\n NonNullable<McpUiHostContext[\"styles\"]>[\"variables\"]\n>;\n\n// SEP-1865 fixes the set of style variable keys ui/initialize accepts. Every\n// HostStyleDefinition returns McpUiStyles from resolveStyleVariables, so a\n// legitimate built-in's key set is exactly the SEP enum; pinning the allowlist\n// to it both honors the protocol and strips any extra keys a runtime-registered\n// host might smuggle in via `as any`, which the SDK would reject downstream.\n//\n// The key set derives from `DEFAULT_HOST_STYLE`, now sourced through the\n// WidgetHost boundary (a hook value) rather than a module import. It's\n// deterministic for a given `DEFAULT_HOST_STYLE`, so compute it once lazily and\n// cache it per definition — preserving the old module-constant semantics while\n// keeping the renderer free of `@/lib/client-styles`.\nconst sepHostStyleVariableKeysCache = new WeakMap<\n object,\n ReadonlySet<string>\n>();\nfunction getSepHostStyleVariableKeys(\n defaultHostStyle: WidgetHostResolvers[\"DEFAULT_HOST_STYLE\"]\n): ReadonlySet<string> {\n const cached = sepHostStyleVariableKeysCache.get(defaultHostStyle);\n if (cached) return cached;\n const keys: ReadonlySet<string> = new Set([\n ...Object.keys(defaultHostStyle.mcp.resolveStyleVariables(\"light\")),\n ...Object.keys(defaultHostStyle.mcp.resolveStyleVariables(\"dark\")),\n ]);\n sepHostStyleVariableKeysCache.set(defaultHostStyle, keys);\n return keys;\n}\n\nfunction sanitizeHostStyleVariables(\n variables: unknown,\n sepHostStyleVariableKeys: ReadonlySet<string>\n): HostStyleVariables | undefined {\n if (!variables || typeof variables !== \"object\" || Array.isArray(variables)) {\n return undefined;\n }\n\n const sanitized: Record<string, string | undefined> = {};\n for (const [key, value] of Object.entries(variables)) {\n if (!sepHostStyleVariableKeys.has(key)) {\n continue;\n }\n if (typeof value === \"string\" || value === undefined) {\n sanitized[key] = value;\n }\n }\n\n return Object.keys(sanitized).length > 0\n ? (sanitized as HostStyleVariables)\n : undefined;\n}\n\n// CSP and permissions metadata types are now imported from SDK\n\nexport interface MCPAppsRendererProps {\n chatSessionId?: string;\n serverId: string;\n serverName?: string;\n toolCallId: string;\n toolName: string;\n toolState?: ToolState;\n toolInput?: Record<string, unknown>;\n toolOutput?: unknown;\n /**\n * Tool response `_meta`, pre-extracted by the caller from the raw\n * (still-wrapped) tool result. Required because `toolOutput` is\n * typically the *unwrapped* value (e.g. `result.value`), at which\n * point `_meta` from the wrapper is no longer reachable from the\n * value alone. Passing this explicitly preserves Apps SDK's\n * `window.openai.toolResponseMetadata` surface for widgets relying\n * on it (timestamps, source IDs, etc.).\n */\n toolResponseMetadata?: Record<string, unknown> | null;\n toolErrorText?: string;\n resourceUri: string;\n toolMetadata?: Record<string, unknown>;\n /** All tools metadata for visibility checking when widget calls tools */\n toolsMetadata?: Record<string, Record<string, unknown>>;\n onSendFollowUp?: (text: string) => void;\n onCallTool?: (\n toolName: string,\n params: Record<string, unknown>\n ) => Promise<unknown>;\n onAppToolInvocationChange?: (invocation: AppToolInvocationUpdate) => void;\n onWidgetStateChange?: (toolCallId: string, state: unknown) => void;\n /**\n * Tier 2 recorder. When `recordMode` is on, the sandbox proxy injects a\n * recorder shim into the guest; `onRecorderStep` fires for each captured\n * click/type (the raw `{ kind, target, ... }` step), and `onRecorderReady`\n * fires once when the shim installs (so the host can detect a strict-CSP\n * guest that silently blocked it). Default off — only the eval authoring\n * preview sets these.\n */\n recordMode?: boolean;\n onRecorderStep?: (step: unknown) => void;\n onRecorderReady?: () => void;\n /**\n * Replay (inverse of recording): published when the guest shim is record-capable\n * so the host can drive the live widget. The host calls `replay(step)` with one\n * scripted step; the renderer relays it to the guest and resolves with the\n * step's result. Published as `null` on unmount so the host drops the handle.\n */\n onReplayControllerReady?: (\n replay:\n | ((step: unknown) => Promise<{\n ok: boolean;\n reason?: string;\n deferred?: string;\n }>)\n | null\n ) => void;\n pipWidgetId?: string | null;\n fullscreenWidgetId?: string | null;\n onRequestPip?: (toolCallId: string) => void;\n onExitPip?: (toolCallId: string) => void;\n /** Controlled display mode - when provided, component uses this instead of internal state */\n displayMode?: DisplayMode;\n /** Callback when display mode changes - required when displayMode is controlled */\n onDisplayModeChange?: (mode: DisplayMode) => void;\n onRequestFullscreen?: (toolCallId: string) => void;\n onExitFullscreen?: (toolCallId: string) => void;\n /** Callback when widget updates model context (SEP-1865 ui/update-model-context) */\n onModelContextUpdate?: (\n toolCallId: string,\n context: {\n content?: ContentBlock[];\n structuredContent?: Record<string, unknown>;\n }\n ) => void;\n /** Callback when app declares its supported display modes during ui/initialize */\n onAppSupportedDisplayModesChange?: (modes: DisplayMode[] | undefined) => void;\n /**\n * Called when the widget sends `ui/notifications/request-teardown`\n * and the host has agreed to honor it (matrix `requestTeardown !==\n * false`). The renderer has already attempted a graceful\n * `ui/resource-teardown` round-trip; the parent is now expected to\n * unmount this tool call's MCP app surface (e.g. dismiss the modal,\n * collapse the inline view).\n */\n onRequestTeardown?: (toolCallId: string, displayWidgetId?: string) => void;\n /**\n * Ask the host to confirm a widget-initiated `ui/download-file` before the\n * download runs (SEP-1865: host SHOULD confirm). Resolve `true` to proceed,\n * `false` to deny (the widget then receives a JSON-RPC \"Download denied by\n * user\" error). When omitted, downloads proceed unprompted — so embedders of\n * the published package keep the prior behavior.\n */\n onConfirmDownload?: (info: {\n kind: \"resource\" | \"resource_link\";\n filename?: string;\n mimeType?: string;\n uri?: string;\n }) => Promise<boolean>;\n /** Whether the server is offline (for using cached content) */\n isOffline?: boolean;\n /** URL to cached widget HTML for offline rendering */\n cachedWidgetHtmlUrl?: string;\n /**\n * If true, attempt the live MCP Apps fetch first and only fall back to\n * `cachedWidgetHtmlUrl` if the live fetch fails (e.g. the server is no\n * longer connected). Used by in-flow session revisit; persisted offline\n * replay (Views tab, eval traces) leaves this unset so the cached path\n * stays primary.\n */\n liveFetchPreferred?: boolean;\n /** Persisted CSP metadata for cached/offline replay */\n widgetCsp?: McpUiResourceCsp | null;\n /** Persisted permissions metadata for cached/offline replay */\n widgetPermissions?: McpUiResourcePermissions | null;\n /** Persisted permissive flag for cached/offline replay */\n widgetPermissive?: boolean;\n /** Persisted prefersBorder value for cached/offline replay */\n prefersBorder?: boolean;\n /**\n * Persisted compat-runtime flag from a saved view or eval snapshot.\n * When set, the renderer trusts the cached blob as the source of\n * truth for whether `window.openai` was injected at capture time —\n * the live profile's flag is ignored for cached replay because the\n * HTML is byte-frozen. When undefined (no snapshot metadata), the\n * renderer falls back to the resolved live flag for fresh fetches.\n */\n injectedOpenAiCompat?: boolean;\n /**\n * Persisted per-method `window.openai.*` surface that was injected\n * into the cached HTML blob. Threads through the saved-view replay\n * path so the SDK runtime reproduces the same set of methods on\n * `window.openai` that the original capture had, even after the\n * active host config has flipped. Absent for pre-feature snapshots\n * — those replay against the runtime's full ChatGPT surface\n * default (matches behavior at capture time).\n */\n injectedOpenAiCompatCapabilities?: OpenAiAppsCapabilities;\n /**\n * Persisted widget state from a saved view or fork. When set, the\n * compat runtime seeds `window.openai.widgetState` with this value so\n * the widget boots in the same state it was when the view was saved\n * (Apps SDK parity — the legacy ChatGPTAppRenderer wired this the same\n * way).\n */\n initialWidgetState?: unknown;\n /** Minimal mode hides diagnostics and metadata surfaces */\n minimalMode?: boolean;\n /**\n * Stable identity assigned by WidgetSurfaceHost. Present only when the\n * renderer is mounted as a persistent, resource-scoped surface.\n */\n persistentSurfaceId?: string;\n /**\n * The first tool call registered for a resource-scoped persistent surface.\n * Kept for host/debug attribution; complete tool-input is still gated by\n * the surface's one-shot delivery latch so restored transcripts cannot skip\n * input when multiple rows register before the host mounts.\n */\n persistentSurfaceInitialToolCallId?: string;\n}\n\n/**\n * Map a `logWidgetDebug` emission to a `WidgetLifecycleEvent` for the\n * Sandbox debug panel, or return `null` for methods we don't track.\n *\n * Constraints:\n * - We only fan out methods that already exist in the renderer. No\n * invented events; no synthetic `pending` placeholders. Absence is\n * semantic — a stage that hasn't fired stays absent from the array.\n * - Status comes from the method itself (e.g. `*-error` → \"error\",\n * `*-ready` / `*-initialized` → \"ok\", `*-start` / `*-requested` →\n * \"pending\").\n * - The store's `appendLifecycle` setter dedupes consecutive same-\n * kind same-status entries, so a retry loop doesn't smear the panel.\n */\nfunction mapLogToLifecycle(\n method: string,\n details: Record<string, unknown>\n): WidgetLifecycleEvent | null {\n const kindByMethod: Record<string, WidgetLifecycleEvent[\"kind\"]> = {\n \"debug/sandbox-proxy-ready\": \"sandbox-proxy-ready\",\n \"debug/widget-content-requested\": \"widget-content-requested\",\n \"debug/widget-content-ready\": \"widget-content-ready\",\n \"debug/widget-content-error\": \"widget-content-error\",\n \"debug/widget-content-invalid-mimetype\": \"widget-content-invalid-mimetype\",\n \"debug/bridge-connect-start\": \"bridge-connect-start\",\n \"debug/bridge-connect-ready\": \"bridge-connect-ready\",\n \"debug/bridge-connect-error\": \"bridge-connect-error\",\n \"debug/bridge-connect-skipped\": \"bridge-connect-skipped\",\n \"debug/app-initialized\": \"app-initialized\",\n };\n const kind = kindByMethod[method];\n if (!kind) return null;\n let status: WidgetLifecycleEvent[\"status\"];\n if (\n method.endsWith(\"-error\") ||\n method === \"debug/widget-content-invalid-mimetype\"\n ) {\n status = \"error\";\n } else if (\n method.endsWith(\"-ready\") ||\n method === \"debug/app-initialized\" ||\n method === \"debug/bridge-connect-skipped\"\n ) {\n status = \"ok\";\n } else {\n status = \"pending\";\n }\n const message =\n typeof details.error === \"string\"\n ? details.error\n : typeof details.reason === \"string\"\n ? details.reason\n : undefined;\n return { kind, status, message, timestamp: Date.now() };\n}\n\nfunction recorderDebug(message: string, details?: Record<string, unknown>) {\n try {\n if (\n typeof window !== \"undefined\" &&\n window.localStorage?.getItem(\"mcpjam:recorder-debug\") === \"1\"\n ) {\n console.info(`[recorder:renderer] ${message}`, details ?? {});\n }\n } catch {\n // best-effort debug logging only\n }\n}\n\n/**\n * Segments of the fetch-source key, in the same order as the renderer\n * builds it below. Used to describe re-mount reasons for the Sandbox\n * debug panel — e.g. \"cachedReplayWidgetHtmlUrl, fetchMode\" when a saved\n * view swaps in a byte-frozen snapshot.\n */\nconst FETCH_SOURCE_KEY_SEGMENTS = [\n \"resourceUri\",\n \"cachedReplayWidgetHtmlUrl\",\n \"cspMode\",\n \"fetchMode\",\n // `injectOpenAiCompat` boolean and the per-method capability hash\n // are part of the rendering recipe: a host swap from ChatGPT-full\n // to Copilot-subset (or a master-toggle flip) changes the bytes\n // baked into the iframe, so a fetch issued under the old recipe\n // is stale by the time it resolves and must NOT overwrite the\n // newer commit's state. See plan §5.5 +\n // feedback_capability_in_render_recipe memory.\n \"injectOpenAiCompat\",\n \"compatCapabilitiesHash\",\n \"mcpAppsCapabilitiesHash\",\n] as const;\n\nfunction describeFetchSourceKeyDiff(prev: string, next: string): string {\n const prevSegs = prev.split(\"|\");\n const nextSegs = next.split(\"|\");\n const changes: string[] = [];\n for (let i = 0; i < FETCH_SOURCE_KEY_SEGMENTS.length; i += 1) {\n if (prevSegs[i] !== nextSegs[i]) changes.push(FETCH_SOURCE_KEY_SEGMENTS[i]);\n }\n return changes.length === 0 ? \"remount\" : changes.join(\", \");\n}\n\nfunction hashSurfaceIdentity(value: string): string {\n let hash = 2166136261;\n for (let i = 0; i < value.length; i += 1) {\n hash ^= value.charCodeAt(i);\n hash = Math.imul(hash, 16777619);\n }\n return (hash >>> 0).toString(36);\n}\n\nfunction getPersistentSurfaceId(props: MCPAppsRendererProps): string {\n // Identity is per-tool-call, not per-resource. The persistent surface's\n // job is to keep one iframe alive across re-renders of the same row\n // (e.g. fullscreen toggle, transcript reshuffles) — the `toolCallId`\n // is stable across all of those. Two distinct `tools/call` invocations\n // on the same resource are semantically two separate Views per\n // SEP-1865's lifecycle, so they must get their own surface; otherwise\n // the second tool-call row renders empty because the lone iframe is\n // anchored under the first row.\n const identity = stableStringifyJson({\n chatSessionId: props.chatSessionId ?? null,\n serverId: props.serverId,\n resourceUri: props.resourceUri,\n toolCallId: props.toolCallId,\n surface: \"inline\",\n });\n return `mcp-app:${hashSurfaceIdentity(identity)}`;\n}\n\nconst pendingSurfaceReleaseTimers = new Map<string, number>();\nconst pendingAnchorClearTimers = new Map<string, number>();\n\nfunction getSurfaceRegistrationKey(surfaceId: string, toolCallId: string) {\n return `${surfaceId}\\0${toolCallId}`;\n}\n\nfunction cancelPendingAnchorClear(surfaceId: string, toolCallId: string) {\n const key = getSurfaceRegistrationKey(surfaceId, toolCallId);\n const timer = pendingAnchorClearTimers.get(key);\n if (timer === undefined) return;\n window.clearTimeout(timer);\n pendingAnchorClearTimers.delete(key);\n}\n\nfunction scheduleAnchorClear(surfaceId: string, toolCallId: string) {\n const key = getSurfaceRegistrationKey(surfaceId, toolCallId);\n const existing = pendingAnchorClearTimers.get(key);\n if (existing !== undefined) window.clearTimeout(existing);\n const timer = window.setTimeout(() => {\n pendingAnchorClearTimers.delete(key);\n useWidgetSurfaceStore.getState().setAnchor(surfaceId, toolCallId, null);\n }, 0);\n pendingAnchorClearTimers.set(key, timer);\n}\n\nfunction cancelPendingSurfaceRelease(surfaceId: string, toolCallId: string) {\n const key = getSurfaceRegistrationKey(surfaceId, toolCallId);\n const timer = pendingSurfaceReleaseTimers.get(key);\n if (timer === undefined) return;\n window.clearTimeout(timer);\n pendingSurfaceReleaseTimers.delete(key);\n}\n\nfunction scheduleSurfaceRelease(surfaceId: string, toolCallId: string) {\n const key = getSurfaceRegistrationKey(surfaceId, toolCallId);\n const existing = pendingSurfaceReleaseTimers.get(key);\n if (existing !== undefined) window.clearTimeout(existing);\n const timer = window.setTimeout(() => {\n pendingSurfaceReleaseTimers.delete(key);\n useWidgetSurfaceStore.getState().releaseRegistration(surfaceId, toolCallId);\n }, 0);\n pendingSurfaceReleaseTimers.set(key, timer);\n}\n\nfunction PersistentMCPAppsRendererRegistration(props: MCPAppsRendererProps) {\n const surfaceId = useMemo(\n () => getPersistentSurfaceId(props),\n [props.chatSessionId, props.resourceUri, props.serverId, props.toolCallId]\n );\n const anchorRef = useRef<HTMLDivElement | null>(null);\n\n useLayoutEffect(() => {\n cancelPendingAnchorClear(surfaceId, props.toolCallId);\n cancelPendingSurfaceRelease(surfaceId, props.toolCallId);\n return () => {\n scheduleSurfaceRelease(surfaceId, props.toolCallId);\n };\n }, [surfaceId, props.toolCallId]);\n\n useLayoutEffect(() => {\n cancelPendingAnchorClear(surfaceId, props.toolCallId);\n cancelPendingSurfaceRelease(surfaceId, props.toolCallId);\n const store = useWidgetSurfaceStore.getState();\n store.upsertRegistration(surfaceId, props.toolCallId, props);\n store.setAnchor(surfaceId, props.toolCallId, anchorRef.current);\n });\n\n const setAnchor = useCallback(\n (node: HTMLDivElement | null) => {\n anchorRef.current = node;\n if (node === null) {\n scheduleAnchorClear(surfaceId, props.toolCallId);\n return;\n }\n cancelPendingAnchorClear(surfaceId, props.toolCallId);\n useWidgetSurfaceStore\n .getState()\n .setAnchor(surfaceId, props.toolCallId, node);\n },\n [surfaceId, props.toolCallId]\n );\n\n return (\n <div\n ref={setAnchor}\n data-mcp-app-surface-id={surfaceId}\n data-mcp-app-surface-anchor={props.toolCallId}\n />\n );\n}\n\nexport function MCPAppsRenderer(props: MCPAppsRendererProps) {\n // Read directly (not via useWidgetHost) because this wrapper gates\n // persistent-vs-ephemeral routing before MCPAppsRendererSurface mounts;\n // routing it through the host hook here would widen this wrapper's\n // subscription set. Centralizing is deferred to the relocation PR — this is a\n // relative-import context, so it does not affect the Tier-B import guard. See\n // use-widget-host.ts.\n const persistentHostEnabled = usePersistentWidgetSurfaceHost();\n const isCachedReplay =\n !!props.cachedWidgetHtmlUrl && !props.liveFetchPreferred;\n const wantPersistentSurface =\n persistentHostEnabled && !props.isOffline && !isCachedReplay;\n\n // Latch the surface choice. This wrapper picks between the persistent and\n // ephemeral surfaces, which are different component types. If an already-live\n // eval widget later receives a cached snapshot URL, keep it on the persistent\n // surface instead of routing it through a fresh cached replay surface.\n const everPersistentRef = useRef(false);\n if (wantPersistentSurface) everPersistentRef.current = true;\n const shouldUsePersistentSurface =\n everPersistentRef.current && !props.isOffline\n ? true\n : wantPersistentSurface;\n\n if (!shouldUsePersistentSurface) {\n return <MCPAppsRendererSurface {...props} />;\n }\n\n return <PersistentMCPAppsRendererRegistration {...props} />;\n}\n\nexport function MCPAppsRendererSurface({\n chatSessionId,\n serverId,\n serverName,\n toolCallId,\n toolName,\n toolState,\n toolInput,\n toolOutput,\n toolResponseMetadata,\n toolErrorText,\n resourceUri,\n toolMetadata,\n toolsMetadata,\n onSendFollowUp,\n onCallTool,\n onAppToolInvocationChange,\n onWidgetStateChange,\n recordMode,\n onRecorderStep,\n onRecorderReady,\n onReplayControllerReady,\n pipWidgetId,\n fullscreenWidgetId,\n onRequestPip,\n onExitPip,\n displayMode: displayModeProp,\n onDisplayModeChange,\n onRequestFullscreen,\n onExitFullscreen,\n onModelContextUpdate,\n onAppSupportedDisplayModesChange,\n onRequestTeardown,\n onConfirmDownload,\n isOffline,\n cachedWidgetHtmlUrl,\n liveFetchPreferred,\n widgetCsp: initialWidgetCsp,\n widgetPermissions: initialWidgetPermissions,\n widgetPermissive: initialWidgetPermissive,\n prefersBorder: initialPrefersBorder,\n injectedOpenAiCompat: initialInjectedOpenAiCompat,\n injectedOpenAiCompatCapabilities: initialInjectedOpenAiCompatCapabilities,\n initialWidgetState,\n minimalMode = false,\n persistentSurfaceId,\n persistentSurfaceInitialToolCallId,\n}: MCPAppsRendererProps) {\n const sandboxRef = useRef<SandboxedIframeHandle>(null);\n\n // Replay (host → guest): pending step requests keyed by a monotonic id. The\n // guest posts `recorder:replay-result` back with the same id (handled in\n // `handleSandboxMessage`), which resolves the matching promise. A timeout\n // resolves a missing reply as a failed step so a stuck guest can't hang Run.\n const replayIdRef = useRef(0);\n const pendingReplaysRef = useRef<\n Map<\n number,\n {\n resolve: (r: {\n ok: boolean;\n reason?: string;\n deferred?: string;\n }) => void;\n timer: ReturnType<typeof setTimeout>;\n }\n >\n >(new Map());\n const REPLAY_STEP_TIMEOUT_MS = 8000;\n const replayStep = useCallback(\n (\n step: unknown\n ): Promise<{ ok: boolean; reason?: string; deferred?: string }> =>\n new Promise((resolve) => {\n const id = (replayIdRef.current += 1);\n const timer = setTimeout(() => {\n pendingReplaysRef.current.delete(id);\n resolve({ ok: false, reason: \"replay step timed out\" });\n }, REPLAY_STEP_TIMEOUT_MS);\n pendingReplaysRef.current.set(id, { resolve, timer });\n sandboxRef.current?.postMessage({\n type: \"recorder:replay-step\",\n id,\n step,\n });\n }),\n []\n );\n // Publish the replay controller to the host while record-capable; retract it\n // (null) when recording turns off or the widget truly unmounts, failing any\n // in-flight steps so the orchestrator doesn't wait on a torn-down guest.\n //\n // `onReplayControllerReady` is recreated by the host on every render (it's an\n // inline tagging wrapper), so it CANNOT be an effect dep — that would re-run\n // the cleanup on every benign re-render (e.g. the thread updating after a\n // replayed click fires a tool call) and abort the replay mid-sequence\n // (\"widget unmounted\"). Read it through a ref; depend only on the actual\n // lifecycle inputs (`recordMode`, the stable `replayStep`).\n const onReplayControllerReadyRef = useRef(onReplayControllerReady);\n onReplayControllerReadyRef.current = onReplayControllerReady;\n useEffect(() => {\n const publish = onReplayControllerReadyRef.current;\n if (!recordMode) {\n publish?.(null);\n return;\n }\n publish?.(replayStep);\n return () => {\n onReplayControllerReadyRef.current?.(null);\n const pending = pendingReplaysRef.current;\n for (const { resolve, timer } of pending.values()) {\n clearTimeout(timer);\n resolve({ ok: false, reason: \"widget unmounted\" });\n }\n pending.clear();\n };\n }, [recordMode, replayStep]);\n // Inspector adapter for the WidgetHost contract (environment + resolvers +\n // services + surface + debug). The renderer's ambient ENV reads and resolver\n // imports are routed through this boundary; all derivation below is unchanged.\n const host = useWidgetHost();\n // Host-injected checkout chrome (the inspector's CheckoutDialogV2). Absent for\n // hosts that don't supply it — the checkout branch then renders nothing.\n const Checkout = host.components?.Checkout;\n // Optional instrumentation sink → no-op fallback (see NOOP_WIDGET_DEBUG_SINK).\n const debug = host.debug ?? NOOP_WIDGET_DEBUG_SINK;\n const { environment, resolvers } = host;\n const themeMode = environment.themeMode;\n const sharedHostStyle = environment.sharedHostStyle;\n const chatboxHostStyle = environment.chatboxHostStyle;\n const chatboxHostTheme = environment.chatboxHostTheme;\n const hostCapabilitiesOverride = environment.hostCapabilitiesOverride;\n // Active hostConfig.mcpProfile from the surrounding scope (chatbox session,\n // project default, eval suite) is bound inside the adapter's resolvers (3d-iii);\n // the renderer keys its capability memos on `profileKey` and reads only the\n // minimal projections it inspects (sandbox overrides + hostInfo override).\n const activeMcpProfileKey = environment.profileKey;\n const profileSandbox = environment.profileSandbox;\n const profileHostInfo = environment.profileHostInfo;\n const hostCapabilitiesOverrideKey = useMemo(\n () => resolvers.stableStringifyJson(hostCapabilitiesOverride ?? null),\n [hostCapabilitiesOverride]\n );\n // Resolved compat-runtime flag for the active host. Claude/Cursor/\n // Codex-style hosts leave it off; ChatGPT/Copilot and MCPJam's dev\n // surface enable it. User override on the profile wins. The resolved\n // boolean travels into the widget-content request body and into the\n // renderer's reload-key so toggling the flag forces a refetch instead\n // of silently reusing the old HTML.\n const liveEffectiveCompatRuntime = useMemo(\n () =>\n resolvers.resolveEffectiveCompatRuntime({\n hostStyle: chatboxHostStyle ?? sharedHostStyle,\n }),\n [activeMcpProfileKey, chatboxHostStyle, sharedHostStyle]\n );\n const liveInjectOpenAiCompat = liveEffectiveCompatRuntime.injected;\n // Capability surface accompanying `liveInjectOpenAiCompat`. Travels\n // into the widget-content request alongside the boolean so the SDK\n // runtime omits methods that the active host's resolved matrix has\n // disabled (feature-detection truthfulness — see plan §4).\n // Null when injection is off (no surface to advertise).\n const liveOpenAiCompatCapabilities = liveEffectiveCompatRuntime.injected\n ? liveEffectiveCompatRuntime.capabilities\n : null;\n // A cached URL can exist during an in-flow revisit while the renderer still\n // prefers live HTML. Treat only cached-only renders as replay; live compat\n // fetches still need completed tool output baked into window.openai at boot.\n const isCachedReplay = !!cachedWidgetHtmlUrl && !liveFetchPreferred;\n const cachedReplayWidgetHtmlUrl = isCachedReplay\n ? cachedWidgetHtmlUrl\n : undefined;\n const widgetFetchModeKey = isCachedReplay ? \"cached\" : \"live\";\n const cachedReplayPrefersBorder = isCachedReplay\n ? initialPrefersBorder\n : undefined;\n // Cached replay: when a saved view / eval snapshot persisted the flag, trust\n // it because the HTML is byte-frozen at capture time. Live-preferred revisits\n // must use the current host config so a cached fallback does not create a\n // distinct render recipe from the next live tool call.\n const effectiveInjectOpenAiCompat =\n isCachedReplay && typeof initialInjectedOpenAiCompat === \"boolean\"\n ? initialInjectedOpenAiCompat\n : liveInjectOpenAiCompat;\n const draftHostContext = environment.draftHostContext;\n const baseHostContext = useMemo(\n () =>\n draftHostContext &&\n typeof draftHostContext === \"object\" &&\n !Array.isArray(draftHostContext)\n ? draftHostContext\n : {},\n [draftHostContext]\n );\n\n // Get CSP mode and host style from playground store when in playground\n const isPlaygroundActive = environment.isPlaygroundActive;\n const configuredHostTheme = resolvers.extractHostTheme(baseHostContext);\n const resolvedTheme = isPlaygroundActive\n ? configuredHostTheme ?? chatboxHostTheme ?? themeMode\n : chatboxHostTheme ?? themeMode;\n // Redeemed chatbox sessions resolve servers via Convex on every\n // platform; widget-content fetches and bridge resource/prompt calls\n // must take the hosted API branch even on local builds. Mirrored into\n // a ref because the bridge handlers close over long-lived callbacks.\n const webManagedServers = host.surface.webManagedServers;\n const webManagedServersRef = useRef(webManagedServers);\n webManagedServersRef.current = webManagedServers;\n // CSP mode is derived from the surface kind + minimalMode + the playground's\n // selected mode (see WidgetHost). Chatbox surfaces (published runtime,\n // Preview, Sessions transcript) and minimal mode default to `permissive` —\n // end-user-facing demo surfaces where an incomplete `_meta.ui.csp`\n // declaration would render a blank widget; the playground uses its selected\n // `mcpAppsCspMode`; everything else is `widget-declared`. Hosts that need\n // strict enforcement still pin it via the host config's `apps.sandbox.csp`\n // policy, applied per-resource below by `resolveSandboxCsp` regardless of\n // this default.\n //\n // `surface.kind` is sourced from the WidgetSurfaceContext (NOT\n // `isPlaygroundActive`), so it is stable from the first render — the\n // iframe-creation-time policy does not flip and tear down/rebuild the iframe\n // (and \"chatbox\" wins over \"playground\", as before).\n const cspMode: CspMode =\n host.surface.kind === \"chatbox\" || minimalMode\n ? \"permissive\"\n : host.surface.kind === \"playground\"\n ? host.surface.playgroundCspMode\n : \"widget-declared\";\n\n // Get locale and timeZone from playground store when active, fallback to browser defaults\n const playgroundLocale = environment.playgroundLocale;\n const playgroundTimeZone = environment.playgroundTimeZone;\n const fallbackLocale = isPlaygroundActive\n ? playgroundLocale\n : navigator.language || \"en-US\";\n const fallbackTimeZone = isPlaygroundActive\n ? playgroundTimeZone\n : Intl.DateTimeFormat().resolvedOptions().timeZone || \"UTC\";\n const locale =\n typeof draftHostContext?.locale === \"string\"\n ? draftHostContext.locale\n : fallbackLocale;\n const timeZone =\n typeof draftHostContext?.timeZone === \"string\"\n ? draftHostContext.timeZone\n : fallbackTimeZone;\n\n // Get displayMode from playground store when active (SEP-1865)\n const playgroundDisplayMode = environment.playgroundDisplayMode;\n const configuredDisplayMode = useMemo(\n () => resolvers.extractHostDisplayMode(draftHostContext),\n [draftHostContext]\n );\n const configuredAvailableDisplayModes = useMemo(\n () => resolvers.extractHostDisplayModes(draftHostContext),\n [draftHostContext]\n );\n // Resolve `effectiveHostStyle` early (it's a 3-way ternary on values\n // already available above) so the SEP-1865 matrix can be computed\n // before the display-mode clamp at `effectiveDisplayMode` below. The\n // duplicate-looking `effectiveHostStyle = ...` further down (around\n // the original `hostStyleDefinition`) reads the same value; both\n // assignments produce identical strings because the dependencies are\n // identical, so the bridge handshake / sandbox composition see the\n // same host style id.\n //\n // Matrix-resolved `availableDisplayModes` is what we advertise in\n // `HostContext.availableDisplayModes` AND what we clamp the\n // current/initial `effectiveDisplayMode` against. Without this\n // earlier clamp, a Copilot-preset host could initialize in (or\n // remain in) `pip` because the parent's `displayMode === \"pip\"`,\n // while advertising `availableDisplayModes: [\"fullscreen\"]` —\n // the View would see inconsistent HostContext.\n const earlyEffectiveHostStyle = isPlaygroundActive\n ? sharedHostStyle\n : chatboxHostStyle;\n const earlyEffectiveMcpAppsCapabilities = useMemo(\n () =>\n resolvers.resolveEffectiveMcpAppsCapabilities({\n hostStyle: earlyEffectiveHostStyle,\n }),\n [activeMcpProfileKey, earlyEffectiveHostStyle]\n );\n\n // Intersection of the matrix's allowed modes with the playground /\n // draft host context's configured modes — single source of truth for\n // both the runtime clamp at `effectiveDisplayMode` below AND the\n // value advertised in `HostContext.availableDisplayModes`. Computed\n // here (early) so the clamp can use it.\n //\n // Without sharing the intersection between the two consumers, the\n // matrix-only clamp inside `effectiveDisplayMode` could land on\n // `matrix[0]` while `HostContext.availableDisplayModes` advertised a\n // strict subset (the intersection). E.g. matrix=[\"pip\",\"fullscreen\"],\n // configured=[\"inline\",\"fullscreen\"], requested=\"inline\" →\n // matrix-only clamp produced \"pip\" (matrix[0]) while advertised list\n // was [\"fullscreen\"]. Fix: clamp against the intersection itself.\n //\n // Fallback to matrix alone when the intersection would be empty —\n // matches the matrix invariant (`length >= 1`) and avoids advertising\n // an unrenderable empty array. `configuredAvailableDisplayModes` is\n // always a non-empty array (see `extractHostDisplayModes` fallbacks)\n // so the only way intersection is empty is when the playground asks\n // for modes the simulated host doesn't advertise.\n // SEP-1865: after `ui/initialize` the view declares\n // `appCapabilities.availableDisplayModes` — the modes it can render in.\n // The host uses this to narrow what it ADVERTISES to the view in\n // `HostContext.availableDisplayModes`, NOT to coerce the current\n // display mode. A widget that only renders in fullscreen (e.g. a\n // canvas-heavy app) is expected to call `ui/request-display-mode`\n // itself after init — the host won't auto-switch the user out of the\n // mode they (or the parent) picked. Coercing here was a real\n // regression: every tool call snapped to fullscreen the moment the\n // widget initialized.\n const [appSupportedDisplayModes, setAppSupportedDisplayModes] = useState<\n DisplayMode[] | undefined\n >(undefined);\n\n // Host-supported modes only. Drives the current-mode clamp and the\n // `ui/request-display-mode` handler — both of which must stay\n // independent of the app's declaration so the user-visible mode is\n // never auto-coerced.\n const effectiveAvailableDisplayModes = useMemo(() => {\n const matrixModes = earlyEffectiveMcpAppsCapabilities.availableDisplayModes;\n const hostIntersection = matrixModes.filter((m) =>\n configuredAvailableDisplayModes.includes(m as DisplayMode)\n );\n const baseHostModes =\n hostIntersection.length > 0 ? hostIntersection : matrixModes;\n if (!appSupportedDisplayModes || appSupportedDisplayModes.length === 0) {\n return baseHostModes;\n }\n const appIntersection = baseHostModes.filter((m) =>\n appSupportedDisplayModes.includes(m as DisplayMode)\n );\n // SEP-1865: when the intersection is empty (the app advertises modes\n // the host doesn't support at all) we fall back to host-supported\n // rather than advertising nothing — the renderer will still clamp\n // the actual mode to the host's set, and the empty case is a\n // misconfigured app the host can't render anyway.\n return appIntersection.length > 0 ? appIntersection : baseHostModes;\n }, [\n earlyEffectiveMcpAppsCapabilities.availableDisplayModes,\n configuredAvailableDisplayModes,\n appSupportedDisplayModes,\n ]);\n\n // Advertised intersection — published in `HostContext.availableDisplayModes`\n // so the view knows which modes the host will honor on\n // `requestDisplayMode`. Falls back to host modes when the app\n // declaration is absent or the intersection would be empty\n // (a misconfigured app that doesn't overlap the host shouldn't\n // make the host advertise nothing).\n const advertisedAvailableDisplayModes = useMemo(() => {\n if (!appSupportedDisplayModes || appSupportedDisplayModes.length === 0) {\n return effectiveAvailableDisplayModes;\n }\n const intersection = effectiveAvailableDisplayModes.filter((m) =>\n appSupportedDisplayModes.includes(m as DisplayMode)\n );\n return intersection.length > 0\n ? intersection\n : effectiveAvailableDisplayModes;\n }, [effectiveAvailableDisplayModes, appSupportedDisplayModes]);\n\n // Get device capabilities from playground store (SEP-1865)\n const playgroundCapabilities = environment.playgroundCapabilities;\n const deviceCapabilities = useMemo(() => {\n const configuredCapabilities =\n draftHostContext?.deviceCapabilities &&\n typeof draftHostContext.deviceCapabilities === \"object\" &&\n !Array.isArray(draftHostContext.deviceCapabilities)\n ? (draftHostContext.deviceCapabilities as {\n hover?: boolean;\n touch?: boolean;\n })\n : undefined;\n\n if (configuredCapabilities) {\n return {\n hover: configuredCapabilities.hover ?? true,\n touch: configuredCapabilities.touch ?? false,\n };\n }\n\n return isPlaygroundActive\n ? playgroundCapabilities\n : { hover: true, touch: false };\n }, [draftHostContext, isPlaygroundActive, playgroundCapabilities]);\n\n // Get safe area insets from playground store (SEP-1865)\n const playgroundSafeAreaInsets = environment.playgroundSafeAreaInsets;\n const safeAreaInsets = useMemo(() => {\n const configuredSafeAreaInsets =\n draftHostContext?.safeAreaInsets &&\n typeof draftHostContext.safeAreaInsets === \"object\" &&\n !Array.isArray(draftHostContext.safeAreaInsets)\n ? (draftHostContext.safeAreaInsets as {\n top?: number;\n right?: number;\n bottom?: number;\n left?: number;\n })\n : undefined;\n\n if (configuredSafeAreaInsets) {\n return {\n top: configuredSafeAreaInsets.top ?? 0,\n right: configuredSafeAreaInsets.right ?? 0,\n bottom: configuredSafeAreaInsets.bottom ?? 0,\n left: configuredSafeAreaInsets.left ?? 0,\n };\n }\n\n return isPlaygroundActive\n ? playgroundSafeAreaInsets\n : { top: 0, right: 0, bottom: 0, left: 0 };\n }, [draftHostContext, isPlaygroundActive, playgroundSafeAreaInsets]);\n\n // Get device type from playground store for platform derivation (SEP-1865)\n const playgroundDeviceType = environment.playgroundDeviceType;\n\n // Display mode: controlled (via props) or uncontrolled (internal state)\n const isControlled = displayModeProp !== undefined;\n const [internalDisplayMode, setInternalDisplayMode] = useState<DisplayMode>(\n resolvers.clampDisplayModeToAvailableModes(\n configuredDisplayMode ??\n (isPlaygroundActive ? playgroundDisplayMode : \"inline\"),\n configuredAvailableDisplayModes\n )\n );\n const displayMode = isControlled ? displayModeProp : internalDisplayMode;\n const displayWidgetId = persistentSurfaceId ?? toolCallId;\n const ownsFullscreenDisplayMode =\n fullscreenWidgetId === displayWidgetId || fullscreenWidgetId === toolCallId;\n const ownsPipDisplayMode =\n pipWidgetId === displayWidgetId || pipWidgetId === toolCallId;\n const requestedDisplayMode = useMemo<DisplayMode>(() => {\n if (!isControlled) return displayMode;\n if (displayMode === \"fullscreen\" && ownsFullscreenDisplayMode) {\n return \"fullscreen\";\n }\n if (displayMode === \"pip\" && ownsPipDisplayMode) return \"pip\";\n return \"inline\";\n }, [\n displayMode,\n isControlled,\n ownsFullscreenDisplayMode,\n ownsPipDisplayMode,\n ]);\n // Clamp the requested display mode against the same intersection\n // that gets advertised in `HostContext.availableDisplayModes` so\n // the runtime mode is always a member of the advertised set. A\n // Copilot host initializing in `pip` (parent's `displayMode` is\n // sticky from a previous widget) coerces down to `fullscreen`\n // because the intersection resolves to `[\"fullscreen\"]`.\n const effectiveDisplayMode = useMemo<DisplayMode>(\n () =>\n resolvers.clampDisplayModeToAvailableModes(\n requestedDisplayMode,\n effectiveAvailableDisplayModes\n ),\n [requestedDisplayMode, effectiveAvailableDisplayModes]\n );\n\n // Clear the sticky inline-preference flag the moment the effective\n // mode moves off \"inline\". Under `user-initiated-only` — the policy\n // the flag actually gates — that transition can only come from the\n // user, since close-button paths set the flag true and switch to\n // inline while the widget's `request-display-mode` is declined. So a\n // non-inline mode means the user re-opted into fullscreen / PIP via\n // the host's display-mode picker, and the widget should be free to\n // keep its preferred mode again. Under `accept` a widget-driven\n // transition also clears it, which is harmless: the handler doesn't\n // consult the flag under that policy.\n useEffect(() => {\n if (effectiveDisplayMode !== \"inline\") {\n userPreferInlineRef.current = false;\n }\n }, [effectiveDisplayMode]);\n const setDisplayMode = useCallback(\n (mode: DisplayMode) => {\n if (isControlled) {\n onDisplayModeChange?.(mode);\n } else {\n setInternalDisplayMode(mode);\n }\n\n // Notify parent about fullscreen state changes regardless of controlled\n // mode. Always forward this widget's own id (`displayWidgetId`); the\n // parent runs an ownership check, which safely no-ops if our local\n // `displayMode` was stale at \"fullscreen\" because another widget took\n // over the global slot.\n if (mode === \"fullscreen\") {\n onRequestFullscreen?.(displayWidgetId);\n } else if (displayMode === \"fullscreen\") {\n onExitFullscreen?.(displayWidgetId);\n }\n },\n [\n isControlled,\n onDisplayModeChange,\n displayWidgetId,\n onRequestFullscreen,\n onExitFullscreen,\n displayMode,\n ]\n );\n const lastForcedDisplayModeRef = useRef<DisplayMode | null>(null);\n\n useEffect(() => {\n if (requestedDisplayMode === effectiveDisplayMode) {\n lastForcedDisplayModeRef.current = null;\n return;\n }\n\n if (lastForcedDisplayModeRef.current === effectiveDisplayMode) {\n return;\n }\n\n lastForcedDisplayModeRef.current = effectiveDisplayMode;\n setDisplayMode(effectiveDisplayMode);\n }, [effectiveDisplayMode, requestedDisplayMode, setDisplayMode]);\n\n const [isReady, setIsReady] = useState(false);\n const [reinitCount, setReinitCount] = useState(0);\n const [loadError, setLoadError] = useState<string | null>(null);\n const [widgetHtml, setWidgetHtml] = useState<string | null>(null);\n const [openInAppUrlOverride, setOpenInAppUrlOverride] = useState<\n string | null\n >(null);\n const [sandboxProxyReady, setSandboxProxyReady] = useState(false);\n const [bridgeTransportReady, setBridgeTransportReady] = useState(false);\n const explicitOpenInAppBaseUrl = useMemo(\n () => resolveExplicitBaseUrl(widgetHtml, resourceUri),\n [widgetHtml, resourceUri]\n );\n const defaultOpenInAppUrl = useMemo(\n () => explicitOpenInAppBaseUrl ?? toSafeOpenInAppUrl(resourceUri),\n [explicitOpenInAppBaseUrl, resourceUri]\n );\n const openInAppUrl = openInAppUrlOverride ?? defaultOpenInAppUrl;\n const openInAppLabel = serverName?.trim() || serverId.trim() || \"App\";\n const handleOpenInApp = useCallback(() => {\n if (!openInAppUrl) return;\n window.open(openInAppUrl, \"_blank\", \"noopener,noreferrer\");\n }, [openInAppUrl]);\n\n useEffect(() => {\n setOpenInAppUrlOverride(null);\n }, [toolCallId, resourceUri]);\n const cachedReplayInjectOpenAiCompat =\n typeof initialInjectedOpenAiCompat === \"boolean\"\n ? initialInjectedOpenAiCompat\n : null;\n const widgetInjectOpenAiCompatReloadKey = isCachedReplay\n ? cachedReplayInjectOpenAiCompat\n : effectiveInjectOpenAiCompat;\n // Companion reload key carrying the per-method capability surface.\n // The boolean reload key above only catches injection on/off changes;\n // a user flipping the active host from ChatGPT-full to Copilot-subset\n // (or toggling a single method in the matrix) leaves the boolean at\n // `true` but changes the surface the runtime should expose. Folding\n // a stable hash of the capability record into the reload key forces\n // the iframe to refetch on per-method changes too. See\n // feedback_capability_in_render_recipe memory.\n // Cached replays read the hash from PERSISTED capabilities (what the\n // byte-frozen HTML was built against). Critical: this MUST match\n // what `loadFromCachedUrl` later stamps into\n // `loadedCompatCapabilitiesHash` — if the two diverge, the\n // \"already loaded\" guard at the top of the fetch effect fails on\n // every render, fires a second cached fetch, and that fetch's\n // `setBridgeTransportReady(false)` blanks the iframe out from\n // under an already-connected bridge.\n //\n // Legacy snapshots (no persisted caps) use `null` on both sides so\n // live host per-method changes don't trigger spurious refetches\n // against byte-frozen HTML.\n const widgetCompatCapabilitiesReloadKey = isCachedReplay\n ? initialInjectedOpenAiCompatCapabilities\n ? resolvers.stableStringifyJson(initialInjectedOpenAiCompatCapabilities)\n : null\n : effectiveInjectOpenAiCompat\n ? resolvers.stableStringifyJson(liveOpenAiCompatCapabilities ?? null)\n : null;\n // Sibling reload key for the MCP Apps spec-bridge matrix. The OpenAI\n // shim caps above bake into the iframe HTML at fetch time; MCP Apps\n // caps don't, but they drive the `HostCapabilities` blob in\n // `ui/initialize` and gate runtime bridge behavior (e.g. the\n // `widgetDisplayModeRequests` policy and the `userPreferInlineRef`\n // seed). Hashing the resolved record into the reload key forces a\n // remount when the user toggles a row in the matrix, so the new\n // policy takes effect on the live widget without a manual reload.\n // Cached replays use `null` for the same reason the OpenAI sibling\n // does — byte-frozen snapshots shouldn't churn on live host edits.\n const widgetMcpAppsCapabilitiesReloadKey = isCachedReplay\n ? null\n : resolvers.stableStringifyJson(earlyEffectiveMcpAppsCapabilities);\n // The OpenAI Apps SDK compatibility runtime bakes toolInput/toolOutput into\n // `window.openai` during HTML injection. Pure SEP-1865 views can boot while\n // input is still streaming and receive the final result via\n // ui/notifications/tool-result. Legacy Apps SDK templates declared through\n // `openai/outputTemplate` are different: many read window.openai.toolOutput\n // once on mount, so they still need the completed output before boot.\n const requiresCompatOutputAtBoot =\n effectiveInjectOpenAiCompat &&\n typeof toolMetadata?.[\"openai/outputTemplate\"] === \"string\";\n const shouldWaitForCompatToolOutput =\n !isCachedReplay &&\n requiresCompatOutputAtBoot &&\n toolState !== \"output-available\";\n const [widgetCsp, setWidgetCsp] = useState<McpUiResourceCsp | undefined>(\n isCachedReplay ? undefined : initialWidgetCsp ?? undefined\n );\n const [widgetPermissions, setWidgetPermissions] = useState<\n McpUiResourcePermissions | undefined\n >(isCachedReplay ? undefined : initialWidgetPermissions ?? undefined);\n const [widgetPermissive, setWidgetPermissive] = useState<boolean>(\n isCachedReplay ? true : initialWidgetPermissive ?? false\n );\n const [prefersBorder, setPrefersBorder] = useState<boolean>(\n initialPrefersBorder ?? true\n );\n // PR D matrix-gated resource-meta interpretation. The matrix\n // dimensions `cspFrameDomains`, `cspBaseUriDomains`,\n // `sandboxPermissions`, and `resourcePrefersBorder` model whether\n // the simulated host HONORS the corresponding resource `_meta.ui`\n // fields. Microsoft 365 Copilot's published Component-bridge table\n // marks all four as ❌; on a simulated Copilot host these fields\n // are silently ignored even when a widget declares them.\n //\n // We post-process the resource's `widgetCsp` / `widgetPermissions`\n // / `prefersBorder` after fetch — the SDK's `resolveSandboxCsp` /\n // `resolveSandboxPermissions` and the renderer's iframe-chrome\n // logic all read these gated values transparently. Per the\n // foundation plan's D3 decision, no SDK API change.\n const matrixGatedWidgetCsp = useMemo<McpUiResourceCsp | undefined>(() => {\n if (!widgetCsp) return widgetCsp;\n const m = earlyEffectiveMcpAppsCapabilities;\n if (m.cspFrameDomains && m.cspBaseUriDomains) return widgetCsp;\n // Spread + selectively strip the gated sub-fields. Connect /\n // resource domains are NOT matrix-gated today (no host's\n // published table tracks them at this granularity); only frame\n // and baseUri are.\n const next: McpUiResourceCsp = { ...widgetCsp };\n if (!m.cspFrameDomains) delete next.frameDomains;\n if (!m.cspBaseUriDomains) delete next.baseUriDomains;\n return next;\n }, [widgetCsp, earlyEffectiveMcpAppsCapabilities]);\n const matrixGatedWidgetPermissions = useMemo<\n McpUiResourcePermissions | undefined\n >(() => {\n // `sandboxPermissions: false` means the simulated host doesn't\n // honor the resource's permissions declarations AT ALL — return\n // undefined so the downstream resolver behaves as if the widget\n // declared no permissions. Spec-compliant simulation: the\n // widget asked for the camera, the host doesn't grant it.\n if (!earlyEffectiveMcpAppsCapabilities.sandboxPermissions) return undefined;\n return widgetPermissions;\n }, [widgetPermissions, earlyEffectiveMcpAppsCapabilities.sandboxPermissions]);\n const matrixGatedPrefersBorder = useMemo(() => {\n // `resourcePrefersBorder: false` means the simulated host\n // ignores the resource's `_meta.ui.prefersBorder` hint. Iframe\n // chrome falls back to host-default rendering (no border) for\n // every widget on that host.\n if (!earlyEffectiveMcpAppsCapabilities.resourcePrefersBorder) return false;\n return prefersBorder;\n }, [prefersBorder, earlyEffectiveMcpAppsCapabilities.resourcePrefersBorder]);\n const [loadedCspMode, setLoadedCspMode] = useState<CspMode | null>(null);\n // Reload-key sibling to `loadedCspMode`: tracks the compat-runtime\n // flag the currently-loaded HTML was fetched with. Toggling the live\n // flag must force a refetch, otherwise the short-circuit at the top\n // of the fetch effect would silently reuse already-shimmed (or\n // already-non-shimmed) HTML. Set to the effective flag in both the\n // cached and the live branches. Cached replays use the persisted\n // provenance flag as the reload key; legacy cached blobs without that\n // metadata use `null` so live host toggles don't rewrite byte-frozen\n // HTML provenance.\n const [loadedInjectOpenAiCompat, setLoadedInjectOpenAiCompat] = useState<\n boolean | null\n >(null);\n // Sibling of `loadedInjectOpenAiCompat`: tracks the stable hash of\n // the per-method capability surface the currently-loaded HTML was\n // fetched with. Set to `null` for legacy cached replays (no persisted\n // capability provenance) so live host toggles don't churn the iframe\n // on byte-frozen snapshots. Compared against\n // `widgetCompatCapabilitiesReloadKey` to detect per-method surface\n // changes that the boolean key would miss.\n const [loadedCompatCapabilitiesHash, setLoadedCompatCapabilitiesHash] =\n useState<string | null>(null);\n // Sibling of `loadedCompatCapabilitiesHash` for the MCP Apps\n // spec-bridge matrix. Tracks the resolved-caps hash the iframe was\n // last initialized against so a matrix toggle (e.g.\n // `widgetDisplayModeRequests`) forces a remount on the next render.\n const [loadedMcpAppsCapabilitiesHash, setLoadedMcpAppsCapabilitiesHash] =\n useState<string | null>(null);\n // Modal state\n const [modalOpen, setModalOpen] = useState(false);\n const [modalParams, setModalParams] = useState<Record<string, unknown>>({});\n const [modalTitle, setModalTitle] = useState(\"\");\n const [modalTemplate, setModalTemplate] = useState<string | null>(null);\n\n // Checkout state. The checkout-session payload is opaque to the package\n // (the inspector's injected `components.Checkout` narrows it to its own\n // `CheckoutSession` shape), so it is held as `unknown`.\n const [checkoutOpen, setCheckoutOpen] = useState(false);\n const [checkoutSession, setCheckoutSession] = useState<unknown>(null);\n const [checkoutCallId, setCheckoutCallId] = useState<number | null>(null);\n\n // True once this widget has rendered from a LIVE fetch. Used to keep a live\n // surface mounted when a persisted cached-replay snapshot arrives AFTER it\n // (the eval streaming→completed trace swap): wiping/reloading the live iframe\n // into the byte-frozen cached template would lose in-flight widget state (e.g.\n // a populated cart). A fresh cached-first replay (saved-view switch) never\n // sets this, so it still resets and loads its snapshot normally.\n const hasRenderedLiveRef = useRef(false);\n const liveRenderIdentityKey = useMemo(\n () =>\n stableStringifyJson({\n chatSessionId: chatSessionId ?? null,\n serverId,\n resourceUri,\n }),\n [chatSessionId, serverId, resourceUri]\n );\n const liveRenderIdentityRef = useRef<string | null>(null);\n const hasRenderedLiveForCurrentIdentity = useCallback(\n () =>\n hasRenderedLiveRef.current &&\n liveRenderIdentityRef.current === liveRenderIdentityKey,\n [liveRenderIdentityKey]\n );\n\n // Reset widget HTML when the actual replay source changes (e.g., different\n // saved view selected). A live-preferred cached URL is only a fallback; it\n // must not churn a persistent live surface when the next tool call has no\n // cached fallback.\n useEffect(() => {\n // A live render is already on screen and a cached snapshot just became\n // available for the same widget at run completion. Keep the live surface\n // and its in-flight state instead of wiping it into the static snapshot.\n if (isCachedReplay && hasRenderedLiveForCurrentIdentity()) return;\n hasRenderedLiveRef.current = false;\n liveRenderIdentityRef.current = null;\n setWidgetHtml(null);\n setBridgeTransportReady(false);\n setLoadedCspMode(null);\n setLoadedInjectOpenAiCompat(null);\n setLoadedCompatCapabilitiesHash(null);\n setLoadError(null);\n setWidgetCsp(undefined);\n setWidgetPermissions(undefined);\n setWidgetPermissive(isCachedReplay ? true : false);\n setPrefersBorder(cachedReplayPrefersBorder ?? true);\n }, [\n cachedReplayWidgetHtmlUrl,\n cachedReplayPrefersBorder,\n hasRenderedLiveForCurrentIdentity,\n isCachedReplay,\n ]);\n\n const bridgeRef = useRef<AppBridge | null>(null);\n const hostContextRef = useRef<McpUiHostContext | null>(null);\n const isReadyRef = useRef(false);\n const lastInlineHeightRef = useRef<string>(\"400px\");\n // Sticky flag set when the user explicitly returned to inline (X\n // click in fullscreen / PIP). Cleared whenever the user explicitly\n // picks a non-inline mode again (display-mode picker).\n //\n // Gates widget-driven `ui/request-display-mode` under the\n // `\"user-initiated-only\"` policy ONLY — there, a widget that\n // re-requests its preferred mode on every `host-context-changed`\n // would otherwise trap the user in a mode they just dismissed. Under\n // `\"accept\"` the host honors widget requests and this flag is not\n // consulted, so closing PIP / fullscreen never mutes the widget's\n // later requests. See the handler in `onRequestDisplayMode`.\n //\n // Seeded from the `widgetDisplayModeRequests` host policy so the\n // `\"user-initiated-only\"` mode kicks in from the first mount: a widget\n // that requests fullscreen on init is treated the same as one\n // re-requesting it after the user dismissed once.\n //\n // Also gates the app-tools auto-promote below, which is host-initiated\n // UX rather than a widget request: a user who dismissed fullscreen\n // shouldn't be yanked back into it by the host under any policy.\n const userPreferInlineRef = useRef(\n earlyEffectiveMcpAppsCapabilities.widgetDisplayModeRequests ===\n \"user-initiated-only\"\n );\n // SEP-1865 host UX: one-shot guard for the app-tools auto-promote to\n // `displayMode = \"fullscreen\"`. When the inline bridge reports\n // `appCapabilities.tools` in `ui/initialize`, the renderer flips the\n // widget to fullscreen so the existing fullscreen overlay (composer\n // pinned + chevron-toggle chat history) mounts — the dev gets a\n // chat-with-app surface without manual mode switching. Gated by\n // `userPreferInlineRef` (auto-promote is treated as host-initiated\n // and respects the same dismissal + `user-initiated-only` policy\n // that blocks widget-initiated `ui/request-display-mode`). One-shot\n // so a shim re-init or a widget's own re-handshake doesn't fire\n // again. Refs reset across renderer instances, so teardown + a new\n // tool-call mount re-arms the promote — a fresh chat with the same\n // app gets the same affordance.\n const hasAutoPromotedForAppToolsRef = useRef(false);\n // SEP-1865 App-Provided Tools: per-bridge identity used to register and\n // unregister this iframe's tools in `useAppToolsRegistry`.\n const appToolsBridgeIdRef = useRef<string | null>(null);\n const appToolsListedBridgeIdsRef = useRef<Set<string>>(new Set());\n const appToolsListInFlightBridgeIdsRef = useRef<Set<string>>(new Set());\n const appToolsListRefreshPendingBridgeIdsRef = useRef<Set<string>>(new Set());\n // Reactive mirror of `appToolsBridgeIdRef` so the in-flight busy\n // indicator can subscribe to `useAppToolsRegistry.pendingControllers`\n // by bridge id. Refs alone don't trigger re-renders.\n const [appToolsBridgeIdState, setAppToolsBridgeIdState] = useState<\n string | null\n >(null);\n const pendingAppToolCalls = useAppToolsRegistry((s) =>\n appToolsBridgeIdState\n ? s.pendingControllers.get(appToolsBridgeIdState)?.size ?? 0\n : 0\n );\n\n // Reset widget-identity-scoped state when the renderer is reused for a\n // different resource / widget bundle. Without this the next widget\n // inherits the previous widget's intersected display modes and (if the user\n // had dismissed to inline) its sticky inline preference. Also re-seeds the\n // sticky flag from the\n // current `widgetDisplayModeRequests` policy so flipping the Apps tab\n // tri-state on an already-mounted renderer takes effect on the next\n // identity change instead of waiting for an unmount.\n useEffect(() => {\n setAppSupportedDisplayModes(undefined);\n userPreferInlineRef.current =\n earlyEffectiveMcpAppsCapabilities.widgetDisplayModeRequests ===\n \"user-initiated-only\";\n }, [\n resourceUri,\n cachedWidgetHtmlUrl,\n earlyEffectiveMcpAppsCapabilities.widgetDisplayModeRequests,\n ]);\n\n const onSendFollowUpRef = useRef(onSendFollowUp);\n const onCallToolRef = useRef(onCallTool);\n const onAppToolInvocationChangeRef = useRef(onAppToolInvocationChange);\n const appToolInvocationSequenceRef = useRef(0);\n const onRequestPipRef = useRef(onRequestPip);\n const onExitPipRef = useRef(onExitPip);\n const onRequestTeardownRef = useRef(onRequestTeardown);\n const onConfirmDownloadRef = useRef(onConfirmDownload);\n const setDisplayModeRef = useRef(setDisplayMode);\n const isPlaygroundActiveRef = useRef(isPlaygroundActive);\n const playgroundDeviceTypeRef = useRef(playgroundDeviceType);\n const effectiveDisplayModeRef = useRef(effectiveDisplayMode);\n const serverIdRef = useRef(serverId);\n const toolCallIdRef = useRef(toolCallId);\n const displayWidgetIdRef = useRef(displayWidgetId);\n const pipWidgetIdRef = useRef(pipWidgetId);\n const ownsPipDisplayModeRef = useRef(ownsPipDisplayMode);\n const toolsMetadataRef = useRef(toolsMetadata);\n const onModelContextUpdateRef = useRef(onModelContextUpdate);\n const onAppSupportedDisplayModesChangeRef = useRef(\n onAppSupportedDisplayModesChange\n );\n\n // Refs for values consumed inside the async fetchWidgetHtml function.\n // These change reference on every streaming chunk (AI SDK recreates part objects),\n // but we don't want to re-trigger the fetch effect for reference-only changes.\n const toolInputRef = useRef(toolInput);\n toolInputRef.current = toolInput;\n const toolOutputRef = useRef(toolOutput);\n toolOutputRef.current = toolOutput;\n const themeModeRef = useRef(themeMode);\n\n // Source-identity guard for the async fetch effect. The renderer can be\n // reused across session swaps and prop changes, so an older fetch can\n // resolve after `{ resourceUri, cachedReplayWidgetHtmlUrl, cspMode,\n // widgetFetchModeKey }` has moved on. Each effect run sets this ref to its\n // own key; the helpers below drop any state writes that don't still match\n // the latest key.\n const latestFetchSourceKeyRef = useRef<string>(\"\");\n /**\n * Previous fetch-source key, kept for the debug-panel mount log. We\n * can't reuse `latestFetchSourceKeyRef` because it's bumped before the\n * fetch starts; this one only advances after the mount has been\n * recorded so the diff is always prev→current.\n */\n const prevLoggedFetchSourceKeyRef = useRef<string | null>(null);\n // Bound before the fetch effect below references it in its deps array —\n // the other widget-debug-store bindings live further down because they\n // only fire from async callbacks, but `recordMountStore` is called\n // synchronously inside the effect body, so it has to be in scope here.\n const recordMountStore = debug.recordMount;\n\n // SEP-1865 MCP Apps spec-bridge matrix ref. Populated further down\n // in the render (after `effectiveHostStyle` / `activeMcpProfile`\n // resolve), but declared here so `useToolInputStreaming` below can\n // read it without forward-reference issues. Null reads as \"default\n // on\" — matches pre-matrix behavior during the brief initial-mount\n // window before the matrix resolver runs.\n const mcpAppsCapabilitiesRef = useRef<ResolvedMcpAppsCapabilities | null>(\n null\n );\n const {\n canRenderStreamingInput,\n signalStreamingRender,\n resetStreamingState,\n } = useToolInputStreaming({\n bridgeRef,\n isReady,\n isReadyRef,\n toolState,\n toolInput,\n toolOutput,\n toolErrorText,\n toolCallId,\n sendToolInput: true,\n reinitCount,\n mcpAppsCapabilitiesRef,\n });\n const hasWidgetHtml = widgetHtml !== null;\n const widgetHtmlLength = widgetHtml?.length ?? 0;\n\n // Fetch widget HTML when tool is active (streaming, input ready, or output available) or CSP mode changes\n useEffect(() => {\n const isActiveToolState =\n toolState === \"input-streaming\" ||\n toolState === \"input-available\" ||\n toolState === \"output-available\";\n if (!isActiveToolState) return;\n if (shouldWaitForCompatToolOutput) return;\n // Already showing a live render and a persisted cached snapshot just became\n // available for the same widget (eval streaming -> completed swap): keep the\n // live iframe (and its in-flight state) instead of reloading the frozen,\n // empty-state cached template. The captured snapshot still backs the\n // Browser/replay tabs; only this live surface stays live.\n if (widgetHtml && isCachedReplay && hasRenderedLiveForCurrentIdentity()) {\n return;\n }\n // Re-fetch if CSP mode changed (widget needs to reload with new CSP\n // policy) OR if the compat-runtime flag changed (HTML needs to be\n // rebuilt with/without the `window.openai` shim). Both belong in\n // the reload key — silently keeping HTML across a flag flip would\n // leave the wrong shape baked into the bytes.\n if (\n widgetHtml &&\n loadedCspMode === cspMode &&\n loadedInjectOpenAiCompat === widgetInjectOpenAiCompatReloadKey &&\n loadedCompatCapabilitiesHash === widgetCompatCapabilitiesReloadKey &&\n loadedMcpAppsCapabilitiesHash === widgetMcpAppsCapabilitiesReloadKey\n )\n return;\n\n // Source-identity key for this run. Any in-flight fetch whose key no\n // longer matches `latestFetchSourceKeyRef.current` when it resolves is\n // stale and MUST NOT mutate state.\n const fetchSourceKey = [\n resourceUri ?? \"\",\n cachedReplayWidgetHtmlUrl ?? \"\",\n cspMode,\n widgetFetchModeKey,\n // String() so `null` (cached-replay sentinel), `true`, and\n // `false` all serialize distinctly into the pipe-joined key.\n String(widgetInjectOpenAiCompatReloadKey),\n widgetCompatCapabilitiesReloadKey ?? \"\",\n widgetMcpAppsCapabilitiesReloadKey ?? \"\",\n ].join(\"|\");\n latestFetchSourceKeyRef.current = fetchSourceKey;\n // Mount log for the Sandbox debug panel. Record one entry per real\n // key change (not per effect re-run) so devs can spot self-induced\n // reloads — e.g. a saved view replay swapping in a different cached\n // snapshot, which remounts the iframe and visually wipes the previous\n // render.\n if (prevLoggedFetchSourceKeyRef.current !== fetchSourceKey) {\n const prev = prevLoggedFetchSourceKeyRef.current;\n const reason =\n prev === null\n ? \"initial\"\n : describeFetchSourceKeyDiff(prev, fetchSourceKey);\n prevLoggedFetchSourceKeyRef.current = fetchSourceKey;\n recordMountStore(toolCallIdRef.current, reason);\n }\n const isStillCurrent = () =>\n latestFetchSourceKeyRef.current === fetchSourceKey;\n\n // Throws on failure. Caller is responsible for surfacing the error.\n const loadFromCachedUrl = async (cachedUrl: string) => {\n const cachedResponse = await fetch(cachedUrl);\n if (!cachedResponse.ok) {\n throw new Error(\n `Failed to fetch cached widget HTML: ${cachedResponse.statusText}`\n );\n }\n const html = await cachedResponse.text();\n if (!isStillCurrent()) return;\n // Reset readiness so the previous bridge's transport doesn't\n // get reused with the new HTML before its connect resolves.\n setBridgeTransportReady(false);\n // Now showing cached HTML, not a live render.\n hasRenderedLiveRef.current = false;\n liveRenderIdentityRef.current = null;\n setWidgetHtml(html);\n setWidgetCsp(undefined);\n setWidgetPermissions(undefined);\n setWidgetPermissive(true);\n setPrefersBorder(initialPrefersBorder ?? true);\n setLoadedCspMode(cspMode);\n // Cached replay: HTML is byte-frozen at capture time. Trust persisted\n // provenance when available; otherwise keep it unknown instead of\n // inferring from the current live host. When this is the fallback path\n // after a preferred live fetch failed, mark the loaded fallback as\n // satisfying the current reload key so the effect doesn't immediately\n // retry live and overwrite the cached render.\n const loadedCachedCompatKey = isCachedReplay\n ? cachedReplayInjectOpenAiCompat\n : widgetInjectOpenAiCompatReloadKey;\n setLoadedInjectOpenAiCompat(loadedCachedCompatKey);\n // `widgetCompatCapabilitiesReloadKey` already encodes the right\n // value for both branches: cached replays compute it from the\n // persisted `initialInjectedOpenAiCompatCapabilities` (matches\n // the byte-frozen HTML), live fetches compute it from the\n // resolver. Stamp it verbatim so the fetch effect's\n // \"already loaded\" guard passes — earlier divergence between\n // this stamp and the reload key triggered a second cached\n // fetch that called `setBridgeTransportReady(false)` after the\n // bridge had already connected.\n setLoadedCompatCapabilitiesHash(widgetCompatCapabilitiesReloadKey);\n // MCP Apps caps don't bake into byte-frozen HTML; cached replays\n // stamp `null` (matching the reload key's cached-replay sentinel)\n // so live host edits don't churn the snapshot.\n setLoadedMcpAppsCapabilitiesHash(widgetMcpAppsCapabilitiesReloadKey);\n setWidgetHtmlStore(\n toolCallIdRef.current,\n html,\n loadedCachedCompatKey ?? undefined,\n // Persisted capabilities flow into the debug store so a\n // \"save view\" round-trip from a cached replay (e.g. user\n // duplicates an old view) carries the original surface\n // forward instead of stamping the current live matrix.\n isCachedReplay\n ? initialInjectedOpenAiCompatCapabilities\n : liveOpenAiCompatCapabilities ?? undefined\n );\n logWidgetDebug(\"host-to-ui\", \"debug/widget-content-ready\", {\n cached: true,\n cspMode,\n htmlLength: html.length,\n injectOpenAiCompat: loadedCachedCompatKey,\n permissive: true,\n });\n };\n\n // Throws on failure. Returns true on success, false if the server\n // returned an invalid mimetype (which is a content error — caller\n // should surface it and NOT fall back to a cached blob).\n const loadFromLiveFetch = async (): Promise<boolean> => {\n const {\n html,\n csp,\n permissions,\n permissive,\n mimeTypeWarning: warning,\n mimeTypeValid: valid,\n prefersBorder,\n injectedOpenAiCompat: serverInjectedOpenAiCompat,\n injectedOpenAiCompatCapabilities:\n serverInjectedOpenAiCompatCapabilities,\n } = await host.services.fetchWidgetContent({\n serverId,\n forceWebEndpoint: webManagedServersRef.current,\n resourceUri,\n toolInput: toolInputRef.current,\n toolOutput: toolOutputRef.current,\n // Surface `_meta` from the tool response so the compat runtime\n // can expose it as `window.openai.toolResponseMetadata`. Prefer\n // the explicit `toolResponseMetadata` prop (which the caller\n // computes from rawOutput where the `{ value, _meta }` wrapper\n // is still intact); fall back to deriving from the resolved\n // output for callers that don't pass it.\n toolResponseMetadata:\n toolResponseMetadata ??\n readToolResultMeta(toolOutputRef.current) ??\n null,\n initialWidgetState,\n toolId: toolCallIdRef.current,\n toolName,\n theme: themeModeRef.current,\n cspMode,\n injectOpenAiCompat: effectiveInjectOpenAiCompat,\n // Per-method capability surface forwarded to the SDK runtime.\n // Sending this alongside `injectOpenAiCompat: true` is what\n // makes disabled methods omitted from `window.openai` in the\n // widget — without it, the runtime falls back to its full\n // surface default and feature detection lies. Send only when\n // we're actually injecting (capabilities are meaningless\n // without the shim).\n openAiCompatCapabilities:\n effectiveInjectOpenAiCompat && liveOpenAiCompatCapabilities\n ? liveOpenAiCompatCapabilities\n : undefined,\n });\n const resolvedInjectedOpenAiCompat =\n typeof serverInjectedOpenAiCompat === \"boolean\"\n ? serverInjectedOpenAiCompat\n : effectiveInjectOpenAiCompat;\n // Server echoes the resolved capability surface (per plan §6.5)\n // so the renderer doesn't need to re-resolve to know exactly\n // what was baked into the HTML. Falls back to the live caps the\n // request sent — covers older servers that don't echo yet.\n const resolvedInjectedOpenAiCompatCapabilities =\n serverInjectedOpenAiCompatCapabilities ??\n (resolvedInjectedOpenAiCompat\n ? liveOpenAiCompatCapabilities ?? undefined\n : undefined);\n\n // Stale fetch: source key moved on (e.g. session swap, CSP toggle,\n // or resource change) while this request was in flight. Drop the\n // result so it can't overwrite the newer commit's state.\n if (!isStillCurrent()) return true;\n\n if (!valid) {\n const errorMessage =\n warning ||\n `Invalid mimetype - SEP-1865 requires \"text/html;profile=mcp-app\"`;\n setLoadError(errorMessage);\n logWidgetDebug(\"host-to-ui\", \"debug/widget-content-invalid-mimetype\", {\n cspMode,\n error: errorMessage,\n });\n return false;\n }\n\n // Reset readiness so the previous bridge's transport doesn't get\n // reused with the new HTML before its connect resolves.\n setBridgeTransportReady(false);\n // Mark that a live render exists so a later persisted cached snapshot\n // doesn't reload (and wipe) this iframe — see the fetch-effect guard.\n hasRenderedLiveRef.current = true;\n liveRenderIdentityRef.current = liveRenderIdentityKey;\n setWidgetHtml(html);\n setWidgetCsp(csp);\n setWidgetPermissions(permissions);\n setWidgetPermissive(permissive ?? false);\n setPrefersBorder(prefersBorder ?? true);\n setLoadedCspMode(cspMode);\n setLoadedInjectOpenAiCompat(resolvedInjectedOpenAiCompat);\n // Capability hash for the fetched HTML — pair with the boolean\n // so future per-method changes detect this snapshot as stale and\n // force a refetch.\n setLoadedCompatCapabilitiesHash(widgetCompatCapabilitiesReloadKey);\n // Sibling stamp for the MCP Apps spec-bridge matrix.\n setLoadedMcpAppsCapabilitiesHash(widgetMcpAppsCapabilitiesReloadKey);\n\n // Store widget HTML in debug store for save view feature. Stamp the\n // resolved flag + per-method capability surface alongside it so\n // saved views and eval snapshots can persist what was actually\n // injected at fetch time. Replay reads both back when reproducing\n // the original render.\n setWidgetHtmlStore(\n toolCallIdRef.current,\n html,\n resolvedInjectedOpenAiCompat,\n resolvedInjectedOpenAiCompatCapabilities\n );\n\n // Update the widget debug store with CSP and permissions info\n if (csp || permissions || !permissive) {\n setWidgetCspStore(toolCallIdRef.current, {\n mode: permissive ? \"permissive\" : \"widget-declared\",\n connectDomains: csp?.connectDomains || [],\n resourceDomains: csp?.resourceDomains || [],\n frameDomains: csp?.frameDomains || [],\n baseUriDomains: csp?.baseUriDomains || [],\n permissions: permissions,\n widgetDeclared: csp\n ? {\n connectDomains: csp.connectDomains,\n resourceDomains: csp.resourceDomains,\n frameDomains: csp.frameDomains,\n baseUriDomains: csp.baseUriDomains,\n }\n : null,\n });\n }\n logWidgetDebug(\"host-to-ui\", \"debug/widget-content-ready\", {\n cached: false,\n cspMode,\n hasCsp: !!csp,\n hasPermissions: !!permissions,\n htmlLength: html.length,\n injectOpenAiCompat: resolvedInjectedOpenAiCompat,\n permissive: permissive ?? false,\n prefersBorder: prefersBorder ?? true,\n });\n return true;\n };\n\n const fetchWidgetHtml = async () => {\n try {\n logWidgetDebug(\"host-to-ui\", \"debug/widget-content-requested\", {\n cachedWidgetHtmlUrl: cachedWidgetHtmlUrl ?? null,\n cspMode,\n isOffline: !!isOffline,\n liveFetchPreferred: !!liveFetchPreferred,\n resourceUri,\n toolState: toolState ?? null,\n });\n\n // In-flow session revisit: try the live MCP Apps fetch first so the\n // widget re-renders against the active host's current CSP / bridge\n // state. If the server is no longer connected (or live fetch fails\n // for any reason), fall back to the cached snapshot HTML.\n if (liveFetchPreferred && cachedWidgetHtmlUrl) {\n try {\n await loadFromLiveFetch();\n return;\n } catch (liveErr) {\n logWidgetDebug(\"host-to-ui\", \"debug/widget-content-live-fallback\", {\n error:\n liveErr instanceof Error ? liveErr.message : String(liveErr),\n });\n await loadFromCachedUrl(cachedWidgetHtmlUrl);\n return;\n }\n }\n\n // Persisted offline replay (Views tab, eval traces, openai-apps\n // revisit): cached HTML is the only source.\n if (cachedWidgetHtmlUrl) {\n await loadFromCachedUrl(cachedWidgetHtmlUrl);\n return;\n }\n\n // If server is offline and no cached HTML, show helpful error\n if (isOffline) {\n const errorMessage =\n \"Server is offline and this view was saved without cached HTML. \" +\n \"Connect the server and re-save the view to enable offline rendering.\";\n setLoadError(errorMessage);\n logWidgetDebug(\"host-to-ui\", \"debug/widget-content-error\", {\n error: errorMessage,\n });\n return;\n }\n\n await loadFromLiveFetch();\n } catch (err) {\n if (!isStillCurrent()) return;\n const errorMessage =\n err instanceof Error ? err.message : \"Failed to prepare widget\";\n setLoadError(errorMessage);\n logWidgetDebug(\"host-to-ui\", \"debug/widget-content-error\", {\n error: errorMessage,\n });\n }\n };\n\n fetchWidgetHtml();\n // logWidgetDebug is intentionally omitted: it has stable identity (reads\n // serverId/toolCallId via refs) and is declared after this effect.\n }, [\n toolState,\n widgetHtml,\n loadedCspMode,\n loadedInjectOpenAiCompat,\n widgetInjectOpenAiCompatReloadKey,\n loadedCompatCapabilitiesHash,\n widgetCompatCapabilitiesReloadKey,\n loadedMcpAppsCapabilitiesHash,\n widgetMcpAppsCapabilitiesReloadKey,\n effectiveInjectOpenAiCompat,\n liveOpenAiCompatCapabilities,\n serverId,\n resourceUri,\n toolName,\n cspMode,\n isOffline,\n cachedWidgetHtmlUrl,\n cachedReplayWidgetHtmlUrl,\n liveFetchPreferred,\n widgetFetchModeKey,\n initialPrefersBorder,\n cachedReplayInjectOpenAiCompat,\n initialInjectedOpenAiCompatCapabilities,\n hasRenderedLiveForCurrentIdentity,\n liveRenderIdentityKey,\n shouldWaitForCompatToolOutput,\n recordMountStore,\n ]);\n\n // UI logging\n const addUiLog = debug.addTrafficLog;\n const logUiEvent = useCallback(\n (payload: Parameters<typeof addUiLog>[0]) => {\n if (minimalMode) return;\n addUiLog(payload);\n },\n [addUiLog, minimalMode]\n );\n const logUiEventRef = useRef(logUiEvent);\n logUiEventRef.current = logUiEvent;\n // Stable identity so this can be safely included in any effect deps without\n // causing reruns. Reads serverId/toolCallId from refs that are kept current\n // by the ref-sync effect below.\n const logWidgetDebug = useCallback(\n (\n direction: \"host-to-ui\" | \"ui-to-host\",\n method: string,\n details: Record<string, unknown>\n ) => {\n logUiEventRef.current({\n widgetId: toolCallIdRef.current,\n serverId: serverIdRef.current,\n direction,\n protocol: \"mcp-apps\",\n method,\n message: details,\n });\n // Also mirror this event into the widget-debug-store's lifecycle\n // array when the method matches one of our tracked stages. This is\n // the Sandbox debug panel's source of truth for \"how far did the\n // widget get before something went wrong\" — driven by the renderer's\n // existing log emissions so we never invent events.\n const mapped = mapLogToLifecycle(method, details);\n if (mapped !== null) {\n const toolCallId = toolCallIdRef.current;\n if (toolCallId) appendLifecycleRef.current(toolCallId, mapped);\n }\n },\n []\n );\n\n const refreshAppProvidedTools = useCallback(\n async (\n bridge: AppBridge,\n bridgeId: string,\n options: {\n force?: boolean;\n // SEP-1865 App-Provided Tools: the modal mounts a second\n // AppBridge against its own iframe, so callers (mcp-apps-modal)\n // pass `surface: \"modal\"`, their own `getIframeElement`, and an\n // `isLive` predicate tied to their own bridge-id ref. Inline\n // callers omit them and get the historical inline behavior.\n surface?: \"inline\" | \"modal\";\n getIframeElement?: () => HTMLIFrameElement | null;\n isLive?: () => boolean;\n } = {}\n ) => {\n const surface = options.surface ?? \"inline\";\n const getIframeElement =\n options.getIframeElement ??\n (() => sandboxRef.current?.getIframeElement() ?? null);\n const isLive =\n options.isLive ?? (() => appToolsBridgeIdRef.current === bridgeId);\n\n const alreadyListed = appToolsListedBridgeIdsRef.current.has(bridgeId);\n const inFlight = appToolsListInFlightBridgeIdsRef.current.has(bridgeId);\n if (inFlight) {\n if (options.force) {\n appToolsListRefreshPendingBridgeIdsRef.current.add(bridgeId);\n }\n return;\n }\n if (!options.force && alreadyListed) return;\n\n appToolsListInFlightBridgeIdsRef.current.add(bridgeId);\n try {\n let needsRefresh = true;\n while (needsRefresh) {\n appToolsListRefreshPendingBridgeIdsRef.current.delete(bridgeId);\n const tools: AppToolDescriptor[] = [];\n let cursor: string | undefined;\n for (let page = 0; page < 8; page += 1) {\n const result = await bridge.listTools(\n cursor === undefined ? {} : { cursor }\n );\n tools.push(\n ...(result.tools ?? []).filter((t): t is AppToolDescriptor =>\n Boolean(t && typeof t.name === \"string\" && t.name.length > 0)\n )\n );\n cursor = result.nextCursor;\n if (!cursor) break;\n }\n\n appToolsListedBridgeIdsRef.current.add(bridgeId);\n // `listTools()` crosses the iframe boundary. If the caller\n // unmounted or rebuilt while it was pending, the live ref has\n // been cleared and any late registration would leak stale\n // aliases.\n if (!isLive()) return;\n\n const appVersion = bridge.getAppVersion();\n await useAppToolsRegistry.getState().registerInstance({\n bridgeId,\n chatSessionId,\n parentToolCallId: toolCallIdRef.current,\n serverId: serverIdRef.current,\n appName: appVersion?.name ?? serverIdRef.current,\n appVersion: appVersion?.version,\n surface,\n bridge,\n tools,\n registeredAtMs: Date.now(),\n // Stable closure: the inline default reads `sandboxRef.current`\n // which is React-managed and tracks the live SandboxedIframe\n // across re-renders. The modal passes its own accessor against\n // `modalSandboxRef`.\n getIframeElement,\n });\n if (!isLive()) {\n useAppToolsRegistry.getState().unregisterInstance(bridgeId);\n return;\n }\n needsRefresh =\n appToolsListRefreshPendingBridgeIdsRef.current.has(bridgeId);\n }\n } catch (err) {\n appToolsListedBridgeIdsRef.current.delete(bridgeId);\n logWidgetDebug(\"ui-to-host\", \"debug/app-tools-list-failed\", {\n error: err instanceof Error ? err.message : String(err),\n });\n } finally {\n appToolsListInFlightBridgeIdsRef.current.delete(bridgeId);\n }\n },\n [chatSessionId, logWidgetDebug]\n );\n\n // Widget debug store\n const setWidgetDebugInfo = debug.setWidgetDebugInfo;\n const setWidgetGlobals = debug.setWidgetGlobals;\n const setWidgetStateStore = debug.setWidgetState;\n const setWidgetCspStore = debug.setWidgetCsp;\n const addCspViolation = debug.addCspViolation;\n const clearCspViolations = debug.clearCspViolations;\n const setWidgetModelContext = debug.setWidgetModelContext;\n const setWidgetHtmlStore = debug.setWidgetHtml;\n const setSandboxAppliedStore = debug.setSandboxApplied;\n const appendLifecycleStore = debug.appendLifecycle;\n // Ref-route the lifecycle setter so logWidgetDebug stays stable-identity\n // without listing the store setter in its deps (matches the logUiEvent\n // pattern above).\n const appendLifecycleRef = useRef(appendLifecycleStore);\n appendLifecycleRef.current = appendLifecycleStore;\n const setWidgetModelContextRef = useRef(setWidgetModelContext);\n setWidgetModelContextRef.current = setWidgetModelContext;\n\n // Clear CSP violations when CSP mode OR compat flag changes (stale\n // data from previous load — both reload-key axes trigger a refetch\n // so violation history from the prior bytes is no longer relevant).\n useEffect(() => {\n if (loadedCspMode !== null && loadedCspMode !== cspMode) {\n clearCspViolations(toolCallId);\n }\n }, [cspMode, loadedCspMode, toolCallId, clearCspViolations]);\n useEffect(() => {\n const injectionChanged =\n loadedInjectOpenAiCompat !== null &&\n loadedInjectOpenAiCompat !== widgetInjectOpenAiCompatReloadKey;\n const capabilitiesChanged =\n (loadedCompatCapabilitiesHash !== null &&\n loadedCompatCapabilitiesHash !== widgetCompatCapabilitiesReloadKey) ||\n (loadedMcpAppsCapabilitiesHash !== null &&\n loadedMcpAppsCapabilitiesHash !== widgetMcpAppsCapabilitiesReloadKey);\n if (injectionChanged || capabilitiesChanged) {\n clearCspViolations(toolCallId);\n }\n }, [\n widgetInjectOpenAiCompatReloadKey,\n loadedInjectOpenAiCompat,\n widgetCompatCapabilitiesReloadKey,\n loadedCompatCapabilitiesHash,\n widgetMcpAppsCapabilitiesReloadKey,\n loadedMcpAppsCapabilitiesHash,\n toolCallId,\n clearCspViolations,\n ]);\n\n // Reset ready state and refs when CSP mode OR compat flag changes\n // (widget will reinitialize — tool input/output must be re-sent).\n useEffect(() => {\n if (loadedCspMode !== null && loadedCspMode !== cspMode) {\n setIsReady(false);\n isReadyRef.current = false;\n resetStreamingState();\n }\n }, [cspMode, loadedCspMode, resetStreamingState]);\n useEffect(() => {\n const injectionChanged =\n loadedInjectOpenAiCompat !== null &&\n loadedInjectOpenAiCompat !== widgetInjectOpenAiCompatReloadKey;\n const capabilitiesChanged =\n (loadedCompatCapabilitiesHash !== null &&\n loadedCompatCapabilitiesHash !== widgetCompatCapabilitiesReloadKey) ||\n (loadedMcpAppsCapabilitiesHash !== null &&\n loadedMcpAppsCapabilitiesHash !== widgetMcpAppsCapabilitiesReloadKey);\n if (injectionChanged || capabilitiesChanged) {\n setIsReady(false);\n isReadyRef.current = false;\n resetStreamingState();\n }\n }, [\n widgetInjectOpenAiCompatReloadKey,\n loadedInjectOpenAiCompat,\n widgetCompatCapabilitiesReloadKey,\n loadedCompatCapabilitiesHash,\n widgetMcpAppsCapabilitiesReloadKey,\n loadedMcpAppsCapabilitiesHash,\n resetStreamingState,\n ]);\n\n // Sync displayMode from playground store when it changes (SEP-1865)\n // Only sync when not in controlled mode (parent controls displayMode via props)\n useEffect(() => {\n if (isPlaygroundActive && !isControlled) {\n setInternalDisplayMode(\n resolvers.clampDisplayModeToAvailableModes(\n configuredDisplayMode ?? playgroundDisplayMode,\n configuredAvailableDisplayModes\n )\n );\n }\n }, [\n configuredAvailableDisplayModes,\n configuredDisplayMode,\n isPlaygroundActive,\n playgroundDisplayMode,\n isControlled,\n ]);\n\n // Initialize widget debug info\n useEffect(() => {\n setWidgetDebugInfo(toolCallId, {\n toolName,\n protocol: \"mcp-apps\",\n // Seed from persisted state when a saved view / fork supplied one,\n // so the Debug \"Widget State\" tab shows the restored value on\n // first render instead of `null`. Apps SDK widgets that call\n // window.openai.setWidgetState() later will overwrite this via\n // setWidgetStateStore in the openai:setWidgetState handler below.\n widgetState: initialWidgetState ?? null,\n prefersBorder,\n globals: {\n theme: resolvedTheme,\n displayMode: effectiveDisplayMode,\n locale,\n timeZone,\n deviceCapabilities,\n safeAreaInsets,\n },\n });\n }, [\n toolCallId,\n toolName,\n setWidgetDebugInfo,\n resolvedTheme,\n effectiveDisplayMode,\n locale,\n timeZone,\n deviceCapabilities,\n safeAreaInsets,\n prefersBorder,\n initialWidgetState,\n ]);\n\n // Update globals in debug store when they change\n useEffect(() => {\n setWidgetGlobals(toolCallId, {\n theme: resolvedTheme,\n displayMode: effectiveDisplayMode,\n locale,\n timeZone,\n deviceCapabilities,\n safeAreaInsets,\n });\n }, [\n toolCallId,\n resolvedTheme,\n effectiveDisplayMode,\n locale,\n timeZone,\n deviceCapabilities,\n safeAreaInsets,\n setWidgetGlobals,\n ]);\n\n // CSS Variables for theming (SEP-1865 styles.variables)\n // These are sent via hostContext.styles.variables - the SDK should pass them through\n const effectiveHostStyle = isPlaygroundActive\n ? sharedHostStyle\n : chatboxHostStyle;\n const hostStyleDefinition =\n resolvers.getHostStyleOrDefault(effectiveHostStyle);\n // Single source of truth for what `hostCapabilities` this view will\n // advertise. The bridge-creation effect (`new AppBridge(...)`) spreads this\n // value into the handshake, and `registerBridgeHandlers` gates each\n // chip-bound handler on the matching field — same blob drives both\n // advertise and enforce, no drift.\n //\n // Stability matters: this memo is a dep of both the bridge-construction\n // useEffect and the registerBridgeHandlers useCallback, so a fresh\n // reference per render would tear down + re-attach the bridge on every\n // commit. Both inputs are stable — `effectiveHostStyle` resolves to a\n // string|null derived from Zustand+context selectors, and\n // `hostCapabilitiesOverride` comes from a context whose Providers (see\n // ClientStyledChatTabV2 / PlaygroundTab / ChatboxChatPage) read from\n // Zustand selectors that return stable refs until the underlying field\n // mutates.\n // Ref-route the active `window.openai` shim capability surface so\n // the host-side `openai:*` postMessage handlers (uploadFile,\n // getFileDownloadUrl, setWidgetState, requestModal, requestClose,\n // requestCheckout) can read the current value without forcing\n // their closures to rebuild on every host swap. These gates are\n // defense-in-depth for the shim surface — the SDK runtime already\n // omits the corresponding methods on `window.openai`, but a widget\n // that captured a method reference before a host swap, or a\n // hand-crafted postMessage, would still arrive here.\n //\n // Cached replays use the PERSISTED capabilities (what was baked\n // into the HTML bytes) instead of the live profile's matrix — the\n // byte-frozen runtime config inside the iframe is the source of\n // truth for which methods the widget can call.\n //\n // SCOPED TO THE SHIM ONLY. The SEP-1865 `bridge.on*` handlers are\n // a distinct surface and follow `effectiveHostCapabilities`\n // exclusively — see the comment in `registerBridgeHandlers`. Null\n // when the shim isn't injected.\n // Sparse `OpenAiAppsCapabilities` (not Required) because the\n // cached-replay branch reads a persisted value that may be missing\n // fields added after capture time. Consumers of this ref\n // (postMessage gates) read each field with `caps[key] === false` /\n // `caps[key] !== true`, so missing → treated as \"default on\", which\n // matches the SDK runtime's FULL_SURFACE_DEFAULT fallback baked\n // into the original capture.\n const activeShimCapabilities: OpenAiAppsCapabilities | null = isCachedReplay\n ? initialInjectedOpenAiCompatCapabilities ?? null\n : liveOpenAiCompatCapabilities;\n const liveOpenAiCompatCapabilitiesRef = useRef<OpenAiAppsCapabilities | null>(\n activeShimCapabilities\n );\n liveOpenAiCompatCapabilitiesRef.current = activeShimCapabilities;\n\n const effectiveHostCapabilities = useMemo(\n () =>\n resolvers.resolveEffectiveHostCapabilities({\n hostStyle: effectiveHostStyle,\n hostCapabilitiesOverride,\n }),\n [effectiveHostStyle, activeMcpProfileKey, hostCapabilitiesOverrideKey]\n );\n const effectiveHostCapabilitiesKey = useMemo(\n () => stableStringifyJson(effectiveHostCapabilities),\n [effectiveHostCapabilities]\n );\n // SEP-1865 spec-bridge matrix resolved from the live profile +\n // host style. Gates notification emissions (`tool-input-partial`,\n // `tool-cancelled`, `host-context-changed`) so simulated hosts\n // like Microsoft 365 Copilot match their published Component-\n // bridge table. Sibling to `effectiveHostCapabilities` — the wire\n // shape advertised in `ui/initialize` is derived from this matrix\n // via `buildHostCapabilities`, but the matrix itself is what\n // runtime notification gates read.\n //\n // INDEPENDENT from the OpenAI shim's `activeShimCapabilities`\n // ref. Two-matrix architecture (see\n // feedback_two_matrix_architecture memory): toggling a row on one\n // matrix never reads the other.\n //\n // The ref is declared above (with initial `null`) so it's visible\n // to `useToolInputStreaming` earlier in the render. We populate\n // `.current` here — same one-step-behind-during-mount caveat the\n // `liveOpenAiCompatCapabilitiesRef` pattern has, and the gate\n // contract reads `null` as \"default on\" so the brief window emits\n // notifications (matches pre-matrix behavior).\n //\n // The matrix itself is computed earlier in the render\n // (`earlyEffectiveMcpAppsCapabilities` near the display-mode\n // resolution) so the `effectiveDisplayMode` clamp can use it. We\n // alias the same value here for downstream consumers.\n const effectiveMcpAppsCapabilities = earlyEffectiveMcpAppsCapabilities;\n mcpAppsCapabilitiesRef.current = effectiveMcpAppsCapabilities;\n themeModeRef.current = resolvedTheme;\n const styleVariables = useMemo(\n () => hostStyleDefinition.mcp.resolveStyleVariables(resolvedTheme),\n [resolvedTheme, hostStyleDefinition]\n );\n const hostChatBackground = useMemo(\n () => hostStyleDefinition.chatUi.resolveChatBackground(resolvedTheme),\n [hostStyleDefinition, resolvedTheme]\n );\n const defaultFontCss = hostStyleDefinition.mcp.fontCss;\n const configuredStyles =\n baseHostContext.styles &&\n typeof baseHostContext.styles === \"object\" &&\n !Array.isArray(baseHostContext.styles)\n ? (baseHostContext.styles as McpUiHostContext[\"styles\"])\n : undefined;\n // The SDK validates styles.variables against the SEP key enum, so strip\n // host-specific custom properties before they enter ui/initialize. The\n // allowlist is fixed to the SEP enum (derived from `DEFAULT_HOST_STYLE`,\n // sourced via the host boundary and cached per definition by\n // `getSepHostStyleVariableKeys`), so this memo only depends on the inbound\n // configured variables (plus the stable `DEFAULT_HOST_STYLE` identity).\n const sepHostStyleVariableKeys = getSepHostStyleVariableKeys(\n resolvers.DEFAULT_HOST_STYLE\n );\n const configuredStyleVariables = useMemo(\n () =>\n sanitizeHostStyleVariables(\n configuredStyles?.variables,\n sepHostStyleVariableKeys\n ),\n [configuredStyles?.variables, sepHostStyleVariableKeys]\n );\n const mergedStyleVariables = useMemo(() => {\n return {\n ...styleVariables,\n ...(configuredStyleVariables &&\n Object.keys(configuredStyleVariables).length > 0\n ? configuredStyleVariables\n : {}),\n };\n }, [configuredStyleVariables, styleVariables]);\n const mergedStyles = useMemo<McpUiHostContext[\"styles\"]>(\n () => ({\n ...configuredStyles,\n variables: mergedStyleVariables,\n css: {\n ...configuredStyles?.css,\n fonts: configuredStyles?.css?.fonts ?? defaultFontCss,\n },\n }),\n [configuredStyles, defaultFontCss, mergedStyleVariables]\n );\n\n // containerDimensions (maxWidth/maxHeight) was previously sent here but\n // removed — width is now fully host-controlled.\n //\n // Matrix-gated HostContext fields (PR C of the foundation series):\n //\n // - `availableDisplayModes`: intersection of the matrix's allowed\n // modes with playground / draft configured modes, computed earlier\n // as `effectiveAvailableDisplayModes` so the runtime\n // `effectiveDisplayMode` clamp and the advertised list agree.\n //\n // - `toolInfo`: omitted entirely when `matrix.toolInfo === false`\n // (Microsoft 365 Copilot doesn't deliver this HostContext field\n // per its published Component-bridge table). A widget that\n // probes `app.getHostContext()?.toolInfo` on a simulated Copilot\n // host now correctly sees undefined — same as real Copilot. The\n // gate strips any inherited `toolInfo` from `baseHostContext`\n // too: a draft host context that pre-populates `toolInfo` would\n // otherwise leak through the spread and defeat the gate.\n const hostContext = useMemo<McpUiHostContext>(() => {\n // Strip toolInfo from the spread source so the matrix gate is\n // authoritative — if the matrix says off, no upstream value\n // (drafts, playground state) can reintroduce it via inheritance.\n const { toolInfo: _toolInfoFromBase, ...baseWithoutToolInfo } =\n baseHostContext as McpUiHostContext & { toolInfo?: unknown };\n const base: McpUiHostContext = {\n ...baseWithoutToolInfo,\n theme: resolvedTheme,\n displayMode: effectiveDisplayMode,\n // Publish the (host ∩ app) intersection here so the view sees the\n // narrowed set it can `requestDisplayMode` against. The current\n // `displayMode` above stays clamped to host-supported only.\n availableDisplayModes: advertisedAvailableDisplayModes,\n locale,\n timeZone,\n platform:\n baseHostContext.platform === \"web\" ||\n baseHostContext.platform === \"desktop\" ||\n baseHostContext.platform === \"mobile\"\n ? baseHostContext.platform\n : hostStyleDefinition.mcp.platform,\n userAgent: navigator.userAgent,\n deviceCapabilities,\n safeAreaInsets,\n styles: mergedStyles,\n };\n if (effectiveMcpAppsCapabilities.toolInfo) {\n base.toolInfo = {\n id: toolCallId,\n tool: {\n name: toolName,\n inputSchema:\n (toolMetadata?.inputSchema as {\n type: \"object\";\n properties?: Record<string, object>;\n required?: string[];\n }) ?? DEFAULT_INPUT_SCHEMA,\n description: toolMetadata?.description as string | undefined,\n },\n };\n }\n return base;\n }, [\n baseHostContext,\n resolvedTheme,\n effectiveDisplayMode,\n advertisedAvailableDisplayModes,\n locale,\n timeZone,\n deviceCapabilities,\n safeAreaInsets,\n mergedStyles,\n hostStyleDefinition,\n toolCallId,\n toolName,\n toolMetadata,\n effectiveMcpAppsCapabilities.toolInfo,\n ]);\n\n useEffect(() => {\n hostContextRef.current = hostContext;\n }, [hostContext]);\n\n // Resolve the effective sandbox policy ONCE, at component scope, so the\n // same value reaches three independent consumers without drift:\n // - the AppBridge constructor below (capability handshake)\n // - the <SandboxedIframe> below (browser-enforced CSP / Permission-Policy)\n // - the <McpAppsModal> below (its own sandboxed iframe for view_mode=modal)\n //\n // Computing this inside the bridge useEffect (the old shape) leaked the\n // policy into ONE consumer only — the iframe got the raw resource\n // declaration and the browser ignored the host clamp, which is exactly the\n // failure the shared resolver was supposed to prevent. The resolver is the\n // single source of truth; everything that mounts untrusted UI reads from\n // here.\n //\n // `effectivePermissive` collapses to `false` whenever a host policy applies\n // — SandboxedIframe treats `permissive: true` as \"skip CSP injection\n // entirely\", which would silently neuter the resolver output.\n const sandboxCspPolicy = useMemo(\n () => profileSandbox?.csp,\n [activeMcpProfileKey]\n );\n const sandboxPermissionsPolicy = useMemo(\n () => profileSandbox?.permissions,\n [activeMcpProfileKey]\n );\n // Inspector-only emission knobs sourced directly from the profile. They\n // bypass the SEP-1865 resolver because they model browser-emission state\n // that has no spec slot (raw `sandbox=`/`allow=` tokens, CSP source\n // expressions). Passed through unchanged to <SandboxedIframe>.\n const sandboxAttrsPolicy = useMemo(\n () => profileSandbox?.sandboxAttrs,\n [activeMcpProfileKey]\n );\n const allowFeaturesPolicy = useMemo(\n () => profileSandbox?.allowFeatures,\n [activeMcpProfileKey]\n );\n const cspDirectivesPolicy = useMemo(\n () => profileSandbox?.csp?.cspDirectives,\n [activeMcpProfileKey]\n );\n // Hosted-mode clamp for cspDirectives. The resolver's\n // `hostedClampExtraDeny` strips MCPJam app/API origins from the\n // widget-declared CSP (`restrictTo` + resource declaration), but\n // cspDirectives is inspector-only — it bypasses the resolver and the\n // proxy merges its tokens AFTER the resolver output, so without a\n // mirrored clamp here a hosted profile with e.g.\n // `cspDirectives: { \"connect-src\": [\"https://app.mcpjam.com\"] }`\n // re-adds the same-origin access the clamp is meant to make\n // non-bypassable. Strip any host-bearing token that resolves to the\n // mcpjam.com namespace AND scheme-wide tokens that would otherwise\n // cover MCPJam endpoints (`*`, `https:`, `http:`, `wss:`, `ws:`); CSP\n // keyword tokens (`'unsafe-eval'`, hashes, nonces — quoted with `'…'`)\n // and safe scheme-only tokens (`data:`, `blob:`, `about:`,\n // `filesystem:`, `mediastream:`) pass through unchanged.\n const cspDirectivesEffective = useMemo(() => {\n if (!cspDirectivesPolicy) return cspDirectivesPolicy;\n if (!host.surface.hostedMode) return cspDirectivesPolicy;\n const isClampBypass = (token: string) => {\n // `'self'` is a clamp bypass in hosted mode. The proxy is served\n // from the MCPJam origin and the inner srcdoc iframe carries\n // `allow-same-origin` (so its document origin = parent's =\n // MCPJam). `'self'` in the inner doc's CSP therefore resolves\n // to the MCPJam app origin, which lets an untrusted widget\n // fetch authenticated MCPJam endpoints — exactly what the clamp\n // is meant to make unreachable. Templates that need actual\n // same-origin access in production hosts (e.g. real Claude\n // where `'self'` resolves to claude.ai) should list the host\n // explicitly so the modeling is faithful in hosted mode too.\n if (token === \"'self'\") return true;\n if (token.startsWith(\"'\")) return false; // other CSP keywords\n // Scheme-wide tokens that cover MCPJam-namespace origins. The\n // clamp's purpose is to keep MCPJam app/API endpoints unreachable\n // from the iframe; `https:` (and friends) covers them just as\n // effectively as naming `https://app.mcpjam.com` directly.\n // Templates that need broad access should list specific origins\n // (e.g. Claude lists `https://esm.sh`, `https://assets.claude.ai`).\n if (token === \"*\") return true;\n if (/^(https?|wss?):$/i.test(token)) return true;\n // Other scheme-only tokens (data:, blob:, about:, filesystem:,\n // mediastream:) don't reach MCPJam origins — let through.\n if (/^[a-z]+:$/.test(token)) return false;\n // Host-bearing token: match mcpjam.com as a host component,\n // covering MCPJAM_HOSTED_CLAMP_ORIGINS (`https://*.mcpjam.com`\n // and `https://mcpjam.com`).\n return /(?:^|[/.@])mcpjam\\.com(?:[:/]|$)/i.test(token);\n };\n const out: Record<string, string[]> = {};\n for (const [k, tokens] of Object.entries(cspDirectivesPolicy)) {\n // Trim BEFORE the bypass check: an imported/saved profile can\n // carry \" https:\" or \" https://app.mcpjam.com\" with leading\n // whitespace, and the proxy's mergeDirective trims tokens before\n // emitting them — so the untrimmed string sneaks past\n // isClampBypass while the trimmed version still lands in the\n // output CSP, reintroducing the access the clamp is supposed to\n // remove. Normalize here so the filter and the proxy see the same\n // token shape.\n const clamped = tokens\n .map((t) => t.trim())\n .filter((t) => t.length > 0 && !isClampBypass(t));\n if (clamped.length > 0) out[k] = clamped;\n }\n return Object.keys(out).length > 0 ? out : undefined;\n }, [cspDirectivesPolicy]);\n const effectiveSandbox = useMemo<{\n csp: McpUiResourceCsp | undefined;\n permissions: McpUiResourcePermissions | undefined;\n permissive: boolean;\n hostPolicyApplied: boolean;\n sandboxAttrs: string[] | undefined;\n allowFeatures: Record<string, string> | undefined;\n cspDirectives: Record<string, string[]> | undefined;\n }>(() => {\n // Detect whether the host explicitly configured CSP hardening signals.\n // Hoisted above the permissive short-circuit so the permissive branch\n // can honor host-explicit `restrictTo` instead of silently dropping it;\n // the relaxed branch below reuses the same calculation. SEP-1865 host\n // policies are allowlist-only, so `restrictTo` and the hosted clamp are\n // the only hardening levers.\n const restrictToConfigured =\n sandboxCspPolicy?.restrictTo !== undefined &&\n Object.values(sandboxCspPolicy.restrictTo).some(\n (list) => Array.isArray(list) && list.length > 0\n );\n // cspDirectives is an inspector-only emission knob, but a populated\n // value is still an explicit \"I want this CSP shape\" signal. The\n // permissive shortcut below bypasses the proxy's `buildCSP(csp,\n // cspDirectives)` path (it builds its own fixed permissive CSP), so\n // without treating cspDirectives as hardening the configured\n // directives get silently dropped on the chatbox/preview surfaces\n // where host profiles are most meant to apply.\n //\n // Only count entries that contribute at least one token that would\n // survive the proxy's mergeDirective filter (trim, plus `;,\\n\\r\"<>`\n // rejection — kept in lockstep with the predicate in\n // sandbox-proxy.html). An entry like `{ \"frame-src\": [] }` or\n // `{ \"frame-src\": [\" \"] }` is a semantic no-op and must not flip\n // a permissive surface into the resolver path (which would then\n // enforce the widget-declared CSP even though the named directive\n // contributes nothing).\n const cspDirectivesConfigured =\n sandboxCspPolicy?.cspDirectives !== undefined &&\n Object.values(sandboxCspPolicy.cspDirectives).some(\n (tokens) =>\n Array.isArray(tokens) &&\n tokens.some((t) => {\n if (typeof t !== \"string\") return false;\n const trimmed = t.trim();\n if (trimmed.length === 0) return false;\n if (/[;,\\n\\r\"<>]/.test(trimmed)) return false;\n return true;\n })\n );\n // Permissive means permissive — when the user explicitly toggles it in\n // the playground toolbar — ignore the saved profile's CSP hardening\n // (restrictTo, cspDirectives) and skip CSP injection entirely. Strict\n // applies the host profile.\n //\n // Chatbox / minimal-mode surfaces also hardcode `cspMode = \"permissive\"`\n // (line 405) as a UX-friendliness default for end-user demos, NOT as a\n // user choice. The host's `restrictTo` / `cspDirectives` MUST still apply\n // there — otherwise a developer who configures `restrictTo: { connectDomains: [\"https://api.acme\"] }`\n // on their chatbox host would have it honored on Connect → Chat but\n // silently dropped on the public chatbox runtime / Sessions transcript.\n //\n // We can't gate on `isPlaygroundActive` alone: the Playground store is\n // localStorage and leaks across browsing contexts on the same origin\n // (see line 396), so a chatbox preview iframe can read\n // `isPlaygroundActive = true` from the parent inspector tab even though\n // it's a chatbox surface. Require `!isChatboxSurface && !minimalMode` so\n // the short-circuit is gated on the actual rendering surface, not just\n // the (leakable) playground flag.\n //\n // No HOSTED_MODE carve-out: PR #2164 moves the sandbox proxy to a separate\n // origin so the iframe is no longer same-origin with mcpjam.com, and a\n // permissive CSP can't be used to fetch /api/* with the user's session\n // cookies.\n //\n // Permissions policy still resolves below — it's orthogonal to CSP.\n const userTogglePermissive =\n cspMode === \"permissive\" &&\n isPlaygroundActive &&\n host.surface.kind !== \"chatbox\" &&\n !minimalMode;\n if (userTogglePermissive) {\n let resolvedPermissions: McpUiResourcePermissions | undefined;\n if (sandboxPermissionsPolicy) {\n const resourcePermsMap: Record<string, boolean> = {};\n // Matrix-gated: `sandboxPermissions: false` means the\n // simulated host doesn't honor `_meta.ui.permissions`. Use\n // the gated value here too — the playground's permissive\n // CSP escape hatch is NOT a license to bypass host-level\n // permission gating. Three bots converged on this miss in\n // review of PR #2242.\n if (\n matrixGatedWidgetPermissions &&\n typeof matrixGatedWidgetPermissions === \"object\"\n ) {\n for (const [k, v] of Object.entries(\n matrixGatedWidgetPermissions as Record<string, unknown>\n )) {\n if (v) resourcePermsMap[k] = true;\n }\n }\n const resolved = resolveSandboxPermissions({\n resourcePermissions: resourcePermsMap,\n policy: sandboxPermissionsPolicy,\n hostedMode: host.surface.hostedMode,\n });\n const out: Record<string, Record<string, never>> = {};\n for (const name of Object.keys(resolved.granted)) {\n out[name] = {};\n }\n resolvedPermissions = out as McpUiResourcePermissions;\n }\n return {\n csp: undefined,\n // Same gate on the pass-through fallback: when no sandbox\n // policy applies, the playground's permissive surface MUST\n // NOT propagate widget-declared permissions that the host\n // matrix says to ignore.\n permissions: resolvedPermissions ?? matrixGatedWidgetPermissions,\n permissive: true,\n hostPolicyApplied: !!resolvedPermissions,\n sandboxAttrs: sandboxAttrsPolicy,\n allowFeatures: allowFeaturesPolicy,\n cspDirectives: cspDirectivesEffective,\n };\n }\n\n // \"relaxed\" CSP mode is an explicit dev escape hatch. The resolver\n // can't represent \"no restrictions\" as a domain list (CSP allow-\n // lists can't carry `*` without inviting the hosted clamp to strip\n // it), so PURE relaxed (no restrictTo, not hosted) short-circuits\n // the resolver and emits no CSP — preserves the dev experience.\n //\n // Any tightening signal — restrictTo or hostedMode — falls through\n // INTO the resolver so the documented guarantees hold:\n // * \"restrictTo applies in every mode\" — intersects in every mode\n // * \"hosted clamp is non-bypassable\" — the MCPJam-origin SDK-\n // internal strip must run in hosted mode regardless of saved profile\n //\n // The previous shape (`if (sandboxCspPolicy && !isRelaxedCsp)`)\n // skipped the resolver entirely on mode===\"relaxed\". A hosted user\n // could save a relaxed profile and silently opt out of the hosted\n // clamp's MCPJam-origin strip — P1 in production.\n const isPureRelaxedCsp =\n sandboxCspPolicy?.mode === \"relaxed\" &&\n !restrictToConfigured &&\n !cspDirectivesConfigured &&\n !host.surface.hostedMode;\n\n let resolvedCsp: McpUiResourceCsp | undefined;\n if (sandboxCspPolicy && !isPureRelaxedCsp) {\n const resolved = resolveSandboxCsp({\n // Matrix-gated: `cspFrameDomains` / `cspBaseUriDomains` off\n // strips those sub-fields from the widget-declared CSP before\n // the resolver sees them, simulating hosts (Microsoft 365\n // Copilot) that don't honor those `_meta.ui.csp.*` fields.\n resourceCsp: matrixGatedWidgetCsp,\n policy: sandboxCspPolicy,\n // \"host-default\" mode falls back to an EMPTY allowlist inside\n // the resolver when `hostDefaultBaseline` is omitted (per\n // SEP-1865 secure-default). For the inspector, the only sensible\n // default baseline we have is the resource's own declaration —\n // passing it here means \"host-default\" is restrictive only as\n // much as the resource itself asked for (never more, possibly\n // less if restrictTo narrows it). Without this, picking\n // \"host-default\" would silently emit `connect-src 'none'` and\n // break any widget that fetches external assets.\n hostDefaultBaseline: matrixGatedWidgetCsp,\n hostedMode: host.surface.hostedMode,\n // Defense in depth: in hosted mode strip any widget-declared\n // domain matching MCPJam's own app/API origins. A hosted widget\n // that declares `https://app.mcpjam.com/api/...` in\n // connectDomains could otherwise use the iframe as an\n // exfiltration channel via the user's authenticated session.\n // The list is hardcoded here (and not in the SDK) because\n // \"which origins count as MCPJam\" is an inspector concern, not\n // a shared SDK concern; the SDK just enforces what we pass.\n // Wildcard pattern strips all subdomains incl. staging/api.\n hostedClampExtraDeny: host.surface.hostedMode\n ? {\n // Spread the readonly constant into mutable arrays — the\n // SDK's `SandboxCspDomainSet` shape declares them as\n // `string[]`. Spreading per directive avoids accidental\n // aliasing if the SDK ever mutates internally.\n connectDomains: [...MCPJAM_HOSTED_CLAMP_ORIGINS],\n resourceDomains: [...MCPJAM_HOSTED_CLAMP_ORIGINS],\n frameDomains: [...MCPJAM_HOSTED_CLAMP_ORIGINS],\n baseUriDomains: [...MCPJAM_HOSTED_CLAMP_ORIGINS],\n }\n : undefined,\n });\n resolvedCsp = {\n connectDomains: resolved.connectDomains,\n resourceDomains: resolved.resourceDomains,\n frameDomains: resolved.frameDomains,\n baseUriDomains: resolved.baseUriDomains,\n };\n }\n let resolvedPermissions: McpUiResourcePermissions | undefined;\n if (sandboxPermissionsPolicy) {\n const resourcePermsMap: Record<string, boolean> = {};\n // Matrix-gated: `sandboxPermissions: false` means the simulated\n // host doesn't honor resource permissions at all. The gated\n // value is `undefined`, so the loop never runs and the\n // resolver's policy alone decides what's granted (typically\n // nothing, matching real Copilot which doesn't pipe widget-\n // declared permissions to the iframe).\n if (\n matrixGatedWidgetPermissions &&\n typeof matrixGatedWidgetPermissions === \"object\"\n ) {\n for (const [k, v] of Object.entries(\n matrixGatedWidgetPermissions as Record<string, unknown>\n )) {\n // SEP-1865 declares each permission as an empty object (`{}`)\n // when requested — i.e. a truthy value. Older shape gated on\n // `v !== undefined && v !== null` which would also accept\n // `false` / `0` / `\"\"` and silently coerce them to GRANTED.\n // Tighten to a truthiness check so a malformed widget that\n // declares `{ camera: false }` doesn't end up with camera\n // granted in the resolved permission set.\n if (v) resourcePermsMap[k] = true;\n }\n }\n const resolved = resolveSandboxPermissions({\n resourcePermissions: resourcePermsMap,\n policy: sandboxPermissionsPolicy,\n hostedMode: host.surface.hostedMode,\n });\n const out: Record<string, Record<string, never>> = {};\n for (const name of Object.keys(resolved.granted)) {\n out[name] = {};\n }\n resolvedPermissions = out as McpUiResourcePermissions;\n }\n const hostPolicyApplied =\n !!resolvedCsp || !!resolvedPermissions || isPureRelaxedCsp;\n return {\n // Pure relaxed → no CSP at all (caller's `permissive: true` below\n // tells SandboxedIframe to skip CSP injection). Otherwise pass\n // the resolver output through, falling back to the widget's own\n // derivation when no host CSP policy is in force.\n // Use matrix-gated CSP / permissions as the fallback too, so a\n // Copilot host whose matrix turns frameDomains off doesn't\n // accidentally pass the un-gated value to the iframe via the\n // `?? widgetCsp` branch.\n csp: isPureRelaxedCsp\n ? undefined\n : resolvedCsp ?? (widgetPermissive ? undefined : matrixGatedWidgetCsp),\n permissions: resolvedPermissions ?? matrixGatedWidgetPermissions,\n // A host-applied CSP MUST be honored at the browser layer. When\n // a restrictive host policy is in force, force `permissive: false`\n // so the SandboxedIframe injects the meta-CSP. In pure-relaxed\n // mode the host policy is \"permissive on purpose\" → force\n // `permissive: true` so the iframe doesn't inject any meta-CSP\n // at all. Without host-side CSP policy, pass the widget-derived\n // flag through.\n //\n // Gate ONLY on `resolvedCsp` (not `resolvedPermissions`): a\n // permissions-only profile (e.g. `mode: \"deny-all\"` for camera/\n // mic) used to flip `permissive: false` while `csp` stayed\n // undefined, which the sandbox proxy interprets as the SEP-1865\n // secure-default CSP (`default-src 'none'`, `connect-src 'none'`)\n // — silently breaking network access for permissive widgets.\n // Permissions and CSP are orthogonal user-facing knobs; tweaking\n // one must not reshape the other.\n permissive: isPureRelaxedCsp\n ? true\n : resolvedCsp\n ? false\n : widgetPermissive,\n hostPolicyApplied,\n sandboxAttrs: sandboxAttrsPolicy,\n allowFeatures: allowFeaturesPolicy,\n cspDirectives: cspDirectivesEffective,\n };\n }, [\n cspMode,\n isPlaygroundActive,\n host.surface.kind,\n minimalMode,\n sandboxCspPolicy,\n sandboxPermissionsPolicy,\n matrixGatedWidgetCsp,\n matrixGatedWidgetPermissions,\n widgetPermissive,\n sandboxAttrsPolicy,\n allowFeaturesPolicy,\n cspDirectivesEffective,\n ]);\n const effectiveSandboxKey = useMemo(\n () => stableStringifyJson(effectiveSandbox),\n [effectiveSandbox]\n );\n\n // Publish the resolved sandbox payload into the widget-debug store so the\n // Sandbox debug panel can render it. `restrictTo` and `cspMode` come from\n // the source profile because the resolver intersects them in but doesn't\n // echo them back verbatim — surfacing both lets the matrix-shared grid show\n // the narrowing knobs even when they collapsed into an intersection.\n //\n // Follow-up: `sandboxAttrs` / `allowFeatures` are policy inputs to\n // `SandboxedIframe`; the literal emitted `sandbox=` / `allow=` strings are\n // joined and filtered inside that component and are NOT exposed here.\n // Exposing the final emitted attributes (via a ref or callback on\n // SandboxedIframe) is left as a follow-up; the resolved policy is enough\n // for \"why isn't this view rendering\" in the vast majority of cases.\n // hostInfo advertised in `ui/initialize` per SEP-1865. Sourced from the\n // active host profile's `mcpProfile.apps.uiInitialize.hostInfo` so the\n // panel's \"View iframe\" sub-card shows what a view actually receives.\n // Null when the host hasn't customized it — same fallback contract as\n // the matrix (canvasBuilder.ts:708).\n const sandboxHostInfo = useMemo<{\n name: string;\n version: string;\n } | null>(() => {\n const raw = profileHostInfo;\n if (!raw || typeof raw !== \"object\") return null;\n const name = (raw as { name?: unknown }).name;\n const version = (raw as { version?: unknown }).version;\n if (typeof name !== \"string\" || typeof version !== \"string\") return null;\n if (name.trim() === \"\" || version.trim() === \"\") return null;\n return { name, version };\n }, [activeMcpProfileKey]);\n const resolvedBridgeHostInfo = useMemo(\n () =>\n (resolvers.resolveHostInfo() ?? {\n name: \"mcpjam-inspector\",\n version: __APP_VERSION__,\n }) as { name: string; version: string },\n [activeMcpProfileKey]\n );\n const resolvedBridgeHostInfoKey = useMemo(\n () => stableStringifyJson(resolvedBridgeHostInfo),\n [resolvedBridgeHostInfo]\n );\n\n useEffect(() => {\n if (!toolCallId) return;\n setSandboxAppliedStore(\n toolCallId,\n {\n sandboxAttrs: effectiveSandbox.sandboxAttrs,\n allowFeatures: effectiveSandbox.allowFeatures,\n cspDirectives: effectiveSandbox.cspDirectives,\n permissive: effectiveSandbox.permissive,\n hostPolicyApplied: effectiveSandbox.hostPolicyApplied,\n restrictTo: sandboxCspPolicy?.restrictTo,\n cspMode: sandboxCspPolicy?.mode,\n permissions: effectiveSandbox.permissions,\n },\n undefined,\n sandboxHostInfo\n );\n }, [\n toolCallId,\n effectiveSandbox,\n sandboxCspPolicy,\n sandboxHostInfo,\n setSandboxAppliedStore,\n ]);\n\n // Keep bridge callbacks in sync before ResizeObserver/rAF-driven widget\n // messages can fire after a display-mode commit.\n useLayoutEffect(() => {\n onSendFollowUpRef.current = onSendFollowUp;\n onCallToolRef.current = onCallTool;\n onAppToolInvocationChangeRef.current = onAppToolInvocationChange;\n onRequestPipRef.current = onRequestPip;\n onExitPipRef.current = onExitPip;\n setDisplayModeRef.current = setDisplayMode;\n isPlaygroundActiveRef.current = isPlaygroundActive;\n playgroundDeviceTypeRef.current = playgroundDeviceType;\n effectiveDisplayModeRef.current = effectiveDisplayMode;\n serverIdRef.current = serverId;\n toolCallIdRef.current = toolCallId;\n displayWidgetIdRef.current = displayWidgetId;\n pipWidgetIdRef.current = pipWidgetId;\n ownsPipDisplayModeRef.current = ownsPipDisplayMode;\n toolsMetadataRef.current = toolsMetadata;\n onModelContextUpdateRef.current = onModelContextUpdate;\n onAppSupportedDisplayModesChangeRef.current =\n onAppSupportedDisplayModesChange;\n onRequestTeardownRef.current = onRequestTeardown;\n onConfirmDownloadRef.current = onConfirmDownload;\n }, [\n onSendFollowUp,\n onCallTool,\n onAppToolInvocationChange,\n onRequestPip,\n onExitPip,\n setDisplayMode,\n isPlaygroundActive,\n playgroundDeviceType,\n effectiveDisplayMode,\n serverId,\n toolCallId,\n displayWidgetId,\n pipWidgetId,\n ownsPipDisplayMode,\n toolsMetadata,\n onModelContextUpdate,\n onAppSupportedDisplayModesChange,\n onRequestTeardown,\n onConfirmDownload,\n ]);\n\n // Adapter: bind the renderer's refs / state setters / store callbacks to the\n // framework-free host bridge surface (`host-app-bridge.ts`). The shared\n // module owns the SEP-1865 correctness surface (capability gating,\n // model-only visibility, matrix-gated `sendToolCancelled`, the app-tool\n // invocation lifecycle); the renderer-specific effects below stay here.\n // The eval browser harness binds the same surface to its own callbacks.\n const registerBridgeHandlers = useCallback(\n (bridge: AppBridge) => {\n registerHostBridgeHandlers(bridge, {\n effectiveHostCapabilities,\n getMatrix: () => mcpAppsCapabilitiesRef.current,\n getToolMetadata: (name) => toolsMetadataRef.current?.[name],\n getToolCallId: () => toolCallIdRef.current,\n nextInvocationSequence: () => appToolInvocationSequenceRef.current++,\n onWidgetDebug: logWidgetDebug,\n callbacks: {\n onAppInitialized: (b) => {\n const wasReady = isReadyRef.current;\n setIsReady(true);\n isReadyRef.current = true;\n const appCaps = b.getAppCapabilities();\n logWidgetDebug(\"ui-to-host\", \"debug/app-initialized\", {\n availableDisplayModes:\n (appCaps?.availableDisplayModes as DisplayMode[] | undefined) ??\n null,\n wasReady,\n });\n const declaredAppModes = appCaps?.availableDisplayModes as\n | DisplayMode[]\n | undefined;\n onAppSupportedDisplayModesChangeRef.current?.(declaredAppModes);\n // SEP-1865: clamp the advertised + runtime mode set against the\n // app's declaration. The next render of `hostContext` will pick\n // up the new intersection and the post-init `setHostContext`\n // effect will publish `host-context-changed` with the updated\n // `availableDisplayModes` (matrix-gated by hostContextChanged).\n setAppSupportedDisplayModes(declaredAppModes);\n // If the guest re-initialized (e.g. an SDK-based app completing\n // its own handshake after the openai-compat shim already\n // initialized), bump reinitCount so the delivery effects re-send\n // tool data.\n if (wasReady) {\n setReinitCount((c) => c + 1);\n }\n\n // SEP-1865 App-Provided Tools: when the app advertises `tools`\n // capability, fetch its tool list with the SDK bridge and register\n // it so the next chat POST can advertise no-execute AI SDK tools.\n if (appCaps?.tools) {\n const bridgeId =\n appToolsBridgeIdRef.current ?? crypto.randomUUID();\n appToolsBridgeIdRef.current = bridgeId;\n setAppToolsBridgeIdState(bridgeId);\n void refreshAppProvidedTools(b, bridgeId);\n\n // SEP-1865 host UX: app-tools widgets are interactive — auto-\n // promote to fullscreen so the existing fullscreen overlay\n // becomes the chat surface. Gates: the app renders fullscreen,\n // the user hasn't dismissed fullscreen, and this is one-shot.\n if (\n !hasAutoPromotedForAppToolsRef.current &&\n !userPreferInlineRef.current &&\n declaredAppModes?.includes(\"fullscreen\")\n ) {\n hasAutoPromotedForAppToolsRef.current = true;\n setDisplayModeRef.current?.(\"fullscreen\");\n }\n }\n },\n onSendFollowUp: (text) => {\n onSendFollowUpRef.current?.(text);\n },\n onOpenLink: (url) => {\n window.open(url, \"_blank\", \"noopener,noreferrer\");\n },\n onCallTool: async (name, invocationInput) => {\n if (!onCallToolRef.current) {\n throw new Error(\"Tool calls not supported\");\n }\n // Apps-compat seam (§1D): the host returns a v2-client\n // CallToolResult; the bridge's onCallTool expects its own nominal\n // type (ext-apps v1-sdk peer). Erase across the version boundary.\n return (await onCallToolRef.current(\n name,\n invocationInput\n )) as never;\n },\n onAppToolInvocation: (update) => {\n onAppToolInvocationChangeRef.current?.(update);\n },\n onReadResource: async (uri) => {\n const result = await host.services.readResource(\n serverIdRef.current,\n uri,\n {\n forceHosted: webManagedServersRef.current,\n }\n );\n return result.content;\n },\n onListResources: async (params) => {\n return host.services.listResources(\n serverIdRef.current,\n (params as { cursor?: string } | undefined)?.cursor,\n { forceHosted: webManagedServersRef.current }\n );\n },\n onListResourceTemplates: async () => {\n // Routed through the WidgetHost boundary; the host service owns the\n // hosted / web-managed guard. Wrap the array to preserve the\n // bridge's `{ resourceTemplates }` response shape.\n const resourceTemplates = await host.services.listResourceTemplates(\n serverIdRef.current\n );\n return { resourceTemplates };\n },\n onListPrompts: async () => {\n const prompts = await host.services.listPrompts(\n serverIdRef.current,\n {\n forceHosted: webManagedServersRef.current,\n }\n );\n return { prompts };\n },\n onLoggingMessage: ({ level, data, logger }) => {\n if (minimalMode) return;\n const prefix = logger ? `[${logger}]` : \"[MCP Apps]\";\n const message = `${prefix} ${level.toUpperCase()}:`;\n if (\n level === \"error\" ||\n level === \"critical\" ||\n level === \"alert\"\n ) {\n console.error(message, data);\n return;\n }\n if (level === \"warning\") {\n console.warn(message, data);\n return;\n }\n console.info(message, data);\n },\n onSizeChange: ({ height }) => {\n // Inline width is owned by the host shell; height stays app-driven\n // for natural inline layout while PIP/fullscreen keep fixed sizing.\n if (effectiveDisplayModeRef.current !== \"inline\") return;\n const iframe = sandboxRef.current?.getIframeElement();\n if (!iframe) return;\n if (height === undefined) return;\n\n // If `box-sizing: border-box` applies to the outer iframe, add\n // border thickness to `height` to avoid a resize feedback loop.\n const style = getComputedStyle(iframe);\n const isBorderBox = style.boxSizing === \"border-box\";\n\n // Animate the change for a smooth transition.\n const from: Keyframe = {};\n const to: Keyframe = {};\n\n let adjustedHeight = height;\n\n if (adjustedHeight !== undefined) {\n if (isBorderBox) {\n adjustedHeight +=\n parseFloat(style.borderTopWidth) +\n parseFloat(style.borderBottomWidth);\n }\n from.height = `${iframe.offsetHeight}px`;\n iframe.style.height = to.height = `${adjustedHeight}px`;\n lastInlineHeightRef.current = `${adjustedHeight}px`;\n }\n\n iframe.animate([from, to], { duration: 300, easing: \"ease-out\" });\n },\n onRequestDisplayMode: async ({ mode }) => {\n const requestedMode = mode ?? \"inline\";\n // Host policy gate: SEP-1865 allows the host to decline\n // widget-initiated `ui/request-display-mode`.\n const policy =\n mcpAppsCapabilitiesRef.current?.widgetDisplayModeRequests ??\n \"accept\";\n if (requestedMode !== \"inline\" && policy === \"decline\") {\n const granted = effectiveDisplayModeRef.current;\n logWidgetDebug(\"ui-to-host\", \"ui/request-display-mode\", {\n requested: requestedMode,\n granted,\n reason: \"policy-decline\",\n });\n return { mode: granted };\n }\n // Sticky inline-preference override — `user-initiated-only` ONLY.\n // Under that policy a user dismissal (or the mount seed) pins the\n // widget to inline until the user re-opens a non-inline mode from\n // the host picker, so a view can't re-grab fullscreen on every\n // `host-context-changed`.\n //\n // `accept` deliberately skips this gate: that policy means the\n // host honors widget-initiated requests, and the flag is also set\n // by the host's own close chrome. Applying it here let a single X\n // click mute `ui/request-display-mode` for the rest of the\n // widget's life — an app's own display-mode buttons went dead\n // after the user closed PIP or fullscreen once, with no way back\n // except the host picker.\n if (\n requestedMode !== \"inline\" &&\n policy === \"user-initiated-only\" &&\n userPreferInlineRef.current\n ) {\n logWidgetDebug(\"ui-to-host\", \"ui/request-display-mode\", {\n requested: requestedMode,\n granted: \"inline\",\n reason: \"user-prefers-inline\",\n });\n return { mode: \"inline\" };\n }\n const hostAvailableModes = resolvers.extractHostDisplayModes(\n hostContextRef.current as Record<string, unknown> | undefined\n );\n // Use device type for mobile detection (defaults to mobile-like\n // behavior when not in playground).\n const isMobile = isPlaygroundActiveRef.current\n ? playgroundDeviceTypeRef.current === \"mobile\" ||\n playgroundDeviceTypeRef.current === \"tablet\"\n : true;\n const mobileAdjustedMode: DisplayMode =\n isMobile && requestedMode === \"pip\"\n ? \"fullscreen\"\n : requestedMode;\n // A request for a mode the host doesn't advertise is REFUSED,\n // not silently rewritten. `clampDisplayModeToAvailableModes`\n // falls back to `availableDisplayModes[0]` — \"inline\" in every\n // preset — which turned an unavailable-mode request into a\n // forced mode CHANGE: a widget sitting in PIP that asked for\n // fullscreen (e.g. because its declared\n // `appCapabilities.availableDisplayModes` omits fullscreen, so\n // the advertised host ∩ app set does too) got dropped to inline\n // instead of staying where it was. Hold the current mode, the\n // same shape the `decline` policy branch above uses.\n if (!hostAvailableModes.includes(mobileAdjustedMode)) {\n const granted = effectiveDisplayModeRef.current;\n logWidgetDebug(\"ui-to-host\", \"ui/request-display-mode\", {\n requested: requestedMode,\n granted,\n reason: \"mode-unavailable\",\n });\n return { mode: granted };\n }\n const actualMode = mobileAdjustedMode;\n\n setDisplayModeRef.current(actualMode);\n\n if (actualMode === \"pip\") {\n onRequestPipRef.current?.(displayWidgetIdRef.current);\n } else if (\n (actualMode === \"inline\" || actualMode === \"fullscreen\") &&\n ownsPipDisplayModeRef.current\n ) {\n onExitPipRef.current?.(\n pipWidgetIdRef.current ?? displayWidgetIdRef.current\n );\n }\n\n return { mode: actualMode };\n },\n onUpdateModelContext: (\n ctxToolCallId,\n { content, structuredContent }\n ) => {\n // Store in debug store for UI display.\n setWidgetModelContextRef.current(ctxToolCallId, {\n content,\n structuredContent,\n });\n // Notify parent component to queue for next model turn.\n onModelContextUpdateRef.current?.(ctxToolCallId, {\n content,\n structuredContent,\n });\n },\n onDownloadFile: async ({ contents }) => {\n // SEP-1865 `ui/download-file`: the host mediates the download\n // since the iframe sandbox blocks direct anchor-clicks. Blob +\n // object-URL anchor.\n //\n // Confirmation runs BEFORE the try/catch below. Per the ext-apps\n // `App.downloadFile` contract, a user cancellation / host denial\n // resolves `{ isError: true }` (the widget's documented\n // `if (result.isError)` path) — a throw is reserved for\n // transport/timeout, so a denial must RETURN isError, not throw, or\n // the widget skips its denial handling and may surface an unhandled\n // rejection. When the host supplies no confirmer, downloads proceed\n // unprompted (back-compat for other embedders of the package).\n const confirmDownload = onConfirmDownloadRef.current;\n if (confirmDownload) {\n for (const item of contents) {\n let info: {\n kind: \"resource\" | \"resource_link\";\n filename?: string;\n mimeType?: string;\n uri?: string;\n };\n if (item.type === \"resource\" && item.resource) {\n const res = item.resource as {\n uri: string;\n mimeType?: string;\n };\n info = {\n kind: \"resource\",\n filename: res.uri.split(\"/\").pop() || undefined,\n mimeType: res.mimeType,\n uri: res.uri,\n };\n } else if (item.type === \"resource_link\") {\n const link = item as { uri: string; mimeType?: string };\n // Reject a non-http(s) resource_link up front, before\n // prompting — the download loop below enforces the same\n // scheme gate, so prompting for a link we'll refuse anyway\n // would show the user a misleading confirmation.\n if (toSafeDownloadLinkUrl(link.uri) === null) {\n return { isError: true };\n }\n info = {\n kind: \"resource_link\",\n filename: link.uri.split(\"/\").pop() || undefined,\n mimeType: link.mimeType,\n uri: link.uri,\n };\n } else {\n continue;\n }\n const approved = await confirmDownload(info);\n if (!approved) {\n return { isError: true };\n }\n }\n }\n try {\n for (const item of contents) {\n if (item.type === \"resource\" && item.resource) {\n const res = item.resource as {\n uri: string;\n text?: string;\n blob?: string;\n mimeType?: string;\n };\n const mimeType = res.mimeType ?? \"application/octet-stream\";\n let blob: Blob;\n if (typeof res.blob === \"string\") {\n const binary = atob(res.blob);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n blob = new Blob([bytes], { type: mimeType });\n } else {\n blob = new Blob([res.text ?? \"\"], { type: mimeType });\n }\n const url = URL.createObjectURL(blob);\n try {\n const anchor = document.createElement(\"a\");\n anchor.href = url;\n anchor.download = res.uri.split(\"/\").pop() ?? \"download\";\n anchor.rel = \"noopener\";\n document.body.appendChild(anchor);\n anchor.click();\n anchor.remove();\n } finally {\n // Defer revocation so the browser can start the download\n // before the object URL goes away.\n setTimeout(() => URL.revokeObjectURL(url), 1000);\n }\n } else if (item.type === \"resource_link\") {\n const link = item as { uri: string };\n // Refuse navigations that aren't a browser-fetchable scheme\n // (shared gate with the pre-prompt check above).\n const safeHref = toSafeDownloadLinkUrl(link.uri);\n if (safeHref === null) {\n throw new Error(\n `Unsupported download URI: ${link.uri}`\n );\n }\n window.open(safeHref, \"_blank\", \"noopener,noreferrer\");\n }\n }\n return {};\n } catch (err) {\n logWidgetDebug(\"ui-to-host\", \"ui/download-file\", {\n error: err instanceof Error ? err.message : String(err),\n });\n return { isError: true };\n }\n },\n onRequestTeardown: (ctxToolCallId) => {\n onRequestTeardownRef.current?.(\n ctxToolCallId,\n displayWidgetIdRef.current\n );\n },\n },\n });\n },\n [\n setIsReady,\n logWidgetDebug,\n refreshAppProvidedTools,\n effectiveHostCapabilitiesKey,\n ]\n );\n\n useEffect(() => {\n if (!widgetHtml) return;\n if (!sandboxProxyReady) {\n logWidgetDebug(\"host-to-ui\", \"debug/bridge-connect-skipped\", {\n reason: \"sandbox-proxy-not-ready\",\n });\n return;\n }\n const iframe = sandboxRef.current?.getIframeElement();\n if (!iframe?.contentWindow) {\n logWidgetDebug(\"host-to-ui\", \"debug/bridge-connect-skipped\", {\n reason: \"missing-iframe-content-window\",\n });\n return;\n }\n\n setBridgeTransportReady(false);\n setIsReady(false);\n isReadyRef.current = false;\n logWidgetDebug(\"host-to-ui\", \"debug/bridge-connect-start\", {\n cspMode,\n // Reflect the resolved (host-policy-applied) sandbox so the debug\n // panel matches what the iframe and bridge will actually see.\n hasCsp: !!effectiveSandbox.csp,\n hasPermissions: !!effectiveSandbox.permissions,\n htmlLength: widgetHtml.length,\n permissive: effectiveSandbox.permissive,\n hostPolicyApplied: effectiveSandbox.hostPolicyApplied,\n toolState: toolState ?? null,\n });\n\n // Sandbox policy is resolved once at component scope (see\n // `effectiveSandbox` above) and reused here so the AppBridge handshake\n // and the rendered <SandboxedIframe> stay in lockstep. Computing this\n // inline used to be the canonical correctness bug: the bridge got the\n // resolved policy while the iframe still got the raw resource\n // declaration, so the browser-enforced CSP didn't honor the host clamp.\n // Host identity advertised in ui/initialize. Templates that emulate\n // another host (e.g. ChatGPT) override this via\n // `mcpProfile.apps.uiInitialize.hostInfo`; backend soft-validates\n // name+version when set so the cast below is safe.\n const bridge = new AppBridge(\n null,\n resolvedBridgeHostInfo,\n {\n ...effectiveHostCapabilities,\n sandbox: {\n csp: effectiveSandbox.csp,\n permissions: effectiveSandbox.permissions,\n },\n },\n { hostContext: hostContextRef.current ?? {} }\n );\n\n registerBridgeHandlers(bridge);\n bridgeRef.current = bridge;\n const pendingRpcMethods = new Map<string | number, string>();\n\n const transport = new LoggingTransport(\n new PostMessageTransport(iframe.contentWindow, iframe.contentWindow),\n {\n onSend: (message) => {\n const method = extractMethod(message, \"mcp-apps\");\n const request = message as { id?: string | number; method?: string };\n if (\n typeof request.method === \"string\" &&\n (typeof request.id === \"string\" || typeof request.id === \"number\")\n ) {\n pendingRpcMethods.set(request.id, request.method);\n }\n if (SUPPRESSED_UI_LOG_METHODS.has(method)) return;\n logUiEventRef.current({\n widgetId: toolCallIdRef.current,\n serverId: serverIdRef.current,\n direction: \"host-to-ui\",\n protocol: \"mcp-apps\",\n method,\n message,\n });\n },\n onReceive: (message) => {\n const response = message as {\n id?: string | number;\n result?: unknown;\n error?: unknown;\n };\n const correlatedMethod =\n (response.result !== undefined || response.error !== undefined) &&\n (typeof response.id === \"string\" || typeof response.id === \"number\")\n ? pendingRpcMethods.get(response.id)\n : undefined;\n if (correlatedMethod && response.id !== undefined) {\n pendingRpcMethods.delete(response.id);\n }\n const method = correlatedMethod ?? extractMethod(message, \"mcp-apps\");\n if (method === \"ui/notifications/size-changed\") {\n signalStreamingRender();\n }\n if (method === \"notifications/tools/list_changed\") {\n const bridgeId = appToolsBridgeIdRef.current;\n if (bridgeId) {\n void refreshAppProvidedTools(bridge, bridgeId, { force: true });\n }\n }\n if (SUPPRESSED_UI_LOG_METHODS.has(method)) return;\n logUiEventRef.current({\n widgetId: toolCallIdRef.current,\n serverId: serverIdRef.current,\n direction: \"ui-to-host\",\n protocol: \"mcp-apps\",\n method,\n message,\n });\n },\n }\n );\n\n let isActive = true;\n bridge\n .connect(transport)\n .then(() => {\n if (!isActive) return;\n setBridgeTransportReady(true);\n logWidgetDebug(\"host-to-ui\", \"debug/bridge-connect-ready\", {\n htmlLength: widgetHtml.length,\n });\n })\n .catch((error) => {\n if (!isActive) return;\n const errorMessage =\n error instanceof Error ? error.message : \"Failed to connect MCP App\";\n setLoadError(errorMessage);\n logWidgetDebug(\"host-to-ui\", \"debug/bridge-connect-error\", {\n error: errorMessage,\n });\n });\n\n return () => {\n isActive = false;\n logWidgetDebug(\"host-to-ui\", \"debug/bridge-connect-cleanup\", {\n wasReady: isReadyRef.current,\n });\n bridgeRef.current = null;\n // SEP-1865 App-Provided Tools: drop this bridge's registration so\n // the next chat POST snapshot omits its aliases. Per spec: \"Calling\n // a tool from a closed app MUST return an error\" — once the bridge\n // is closed, any in-flight `useChat.onToolCall` dispatch resolves\n // to null in `useAppToolsRegistry.resolve()`.\n if (appToolsBridgeIdRef.current) {\n useAppToolsRegistry\n .getState()\n .unregisterInstance(appToolsBridgeIdRef.current);\n appToolsListedBridgeIdsRef.current.delete(appToolsBridgeIdRef.current);\n appToolsListInFlightBridgeIdsRef.current.delete(\n appToolsBridgeIdRef.current\n );\n appToolsListRefreshPendingBridgeIdsRef.current.delete(\n appToolsBridgeIdRef.current\n );\n appToolsBridgeIdRef.current = null;\n setAppToolsBridgeIdState(null);\n }\n // SEP-1865: the host MUST send `ui/resource-teardown` before tearing the\n // view down (so it can flush/persist), and SHOULD wait for the ack. We\n // send the teardown request — the outbound message is posted before\n // close() — but deliberately DO NOT await the ack: this cleanup also runs\n // when the widget is reloaded/replaced, and the outer sandbox-proxy\n // iframe is reused for the next resource. Keeping this (now stale) bridge\n // subscribed while a replacement bridge attaches to the SAME proxy window\n // would let both answer the new widget's JSON-RPC (duplicate `ui/initialize`\n // / stale responses). Detaching synchronously is the only way to guarantee\n // the stale transport stops handling messages before the new one starts;\n // the ack, if it arrives, lands after close() and is harmlessly dropped.\n if (isReadyRef.current) {\n bridge.teardownResource({}).catch(() => {});\n }\n bridge.close().catch(() => {});\n // Clear model context on widget teardown\n setWidgetModelContextRef.current(toolCallIdRef.current, null);\n };\n }, [\n widgetHtml,\n sandboxProxyReady,\n registerBridgeHandlers,\n refreshAppProvidedTools,\n // Bridge must rebuild when the resolved sandbox policy changes — a host\n // toggling sandbox policy at runtime needs the new handshake. The memo\n // identity key captures `widgetCsp`/`widgetPermissions`/`widgetPermissive`\n // and the sandbox slice of mcpProfile transitively without treating\n // reference-only object churn as a reload signal.\n effectiveSandboxKey,\n logWidgetDebug,\n // Bridge must rebuild when the advertised host capabilities change\n // (host style switch or override edit) so the new handshake reflects\n // the new contract.\n effectiveHostCapabilitiesKey,\n // Bridge must rebuild when the host identity advertised in\n // ui/initialize changes — switching to a template that overrides\n // hostInfo (e.g. ChatGPT) is observable to the View.\n resolvedBridgeHostInfoKey,\n ]);\n\n useEffect(() => {\n const bridge = bridgeRef.current;\n if (!bridge || !isReady) return;\n // `bridge.setHostContext` updates the AppBridge's cached\n // `_hostContext` AND emits `ui/notifications/host-context-changed`\n // to the View. Matrix gate: Microsoft 365 Copilot does not\n // deliver this notification per its published Component-bridge\n // table (theme / displayMode updates are one-shot at\n // `ui/initialize` time on that host). Null matrix → default on.\n //\n // We still skip the call entirely when gated rather than only\n // suppressing the wire notification — the bridge's internal\n // cache also tracks `_hostContext`, but on Copilot-style hosts\n // the spec says it doesn't update mid-session, so keeping the\n // cache frozen matches the simulated host's behavior. (If a\n // future host wants the cache to update without emitting the\n // notification, we'll split this gate.)\n const matrix = mcpAppsCapabilitiesRef.current;\n if (matrix !== null && matrix.hostContextChanged === false) return;\n bridge.setHostContext(hostContext);\n }, [hostContext, isReady]);\n\n const handleCspViolation = useCallback(\n (event: MessageEvent) => {\n const data = event.data;\n if (!data) return;\n\n const {\n directive,\n blockedUri,\n sourceFile,\n lineNumber,\n columnNumber,\n effectiveDirective,\n timestamp,\n } = data;\n\n logUiEvent({\n widgetId: toolCallId,\n serverId,\n direction: \"ui-to-host\",\n protocol: \"mcp-apps\",\n method: \"csp-violation\",\n message: data,\n });\n\n addCspViolation(toolCallId, {\n directive,\n effectiveDirective,\n blockedUri,\n sourceFile,\n lineNumber,\n columnNumber,\n timestamp: timestamp || Date.now(),\n });\n\n if (!minimalMode) {\n console.warn(\n `[MCP Apps CSP Violation] ${directive}: Blocked ${blockedUri}`,\n sourceFile ? `at ${sourceFile}:${lineNumber}:${columnNumber}` : \"\"\n );\n }\n },\n [addCspViolation, logUiEvent, minimalMode, serverId, toolCallId]\n );\n\n const handleSandboxMessage = (event: MessageEvent) => {\n const data = event.data;\n if (!data) return;\n\n // Handle CSP violation messages (custom type)\n if (data.type === \"mcp-apps:csp-violation\") {\n handleCspViolation(event);\n return;\n }\n\n // Tier 2 recorder: forward captured steps + readiness to the host.\n if (data.type === \"recorder:step\") {\n recorderDebug(\"step from sandbox\", {\n toolName,\n toolCallId,\n recordMode: !!recordMode,\n });\n onRecorderStep?.(data.step);\n return;\n }\n if (data.type === \"recorder:ready\") {\n recorderDebug(\"ready from sandbox\", {\n toolName,\n toolCallId,\n recordMode: !!recordMode,\n });\n onRecorderReady?.();\n return;\n }\n // Replay: resolve the pending step promise the guest is answering.\n if (data.type === \"recorder:replay-result\") {\n const pending =\n typeof data.id === \"number\"\n ? pendingReplaysRef.current.get(data.id)\n : undefined;\n if (pending) {\n clearTimeout(pending.timer);\n pendingReplaysRef.current.delete(data.id);\n pending.resolve({\n ok: !!data.ok,\n reason: data.reason,\n deferred: data.deferred,\n });\n }\n return;\n }\n\n // Defense-in-depth: if the live capability matrix has the file ops\n // disabled, drop incoming `openai:uploadFile` / `getFileDownloadUrl`\n // messages from the iframe. Other fire-and-forget `openai:*`\n // messages below use the same live matrix gate. The SDK runtime\n // should already be omitting disabled methods (so widgets that\n // feature-detect take the fallback path), but a widget that captured\n // a method reference before a host swap, or hand-crafted the\n // postMessage, would still reach here. Send a clear policy error\n // back for pending-call file helpers so the widget's resolver\n // rejects rather than hanging.\n //\n // STRICT `=== false` semantics: the persisted/sparse\n // `OpenAiAppsCapabilities` shape omits fields added after capture\n // time, and the SDK runtime treats missing as \"default on\"\n // (FULL_SURFACE_DEFAULT). Mirroring that here means an absent\n // field is allowed, not denied — only an explicit `false` triggers\n // the gate. `!liveCaps.foo` would lock out forward-compatible\n // legacy snapshots; `liveCaps.foo === false` matches the runtime.\n const liveCaps = liveOpenAiCompatCapabilitiesRef.current;\n const policyError = (\n callId: number,\n method: \"openai:uploadFile\" | \"openai:getFileDownloadUrl\"\n ) => {\n sandboxRef.current?.postMessage({\n type: `${method}:response`,\n callId,\n error: `${method} denied by host capability policy`,\n });\n };\n\n // Handle file upload messages (non-JSON-RPC, same protocol as ChatGPT widget)\n if (data.type === \"openai:uploadFile\") {\n if (liveCaps !== null && liveCaps.uploadFile === false) {\n policyError(data.callId, \"openai:uploadFile\");\n return;\n }\n void handleUploadFileMessage(\n data,\n (message) => {\n sandboxRef.current?.postMessage(message);\n },\n {\n authFetch: host.services.authFetch,\n hostedMode: host.surface.hostedMode,\n }\n );\n return;\n }\n\n if (data.type === \"openai:getFileDownloadUrl\") {\n if (liveCaps !== null && liveCaps.getFileDownloadUrl === false) {\n policyError(data.callId, \"openai:getFileDownloadUrl\");\n return;\n }\n handleGetFileDownloadUrlMessage(\n data,\n (message) => {\n sandboxRef.current?.postMessage(message);\n },\n { hostedMode: host.surface.hostedMode }\n );\n return;\n }\n\n // Apps SDK widget-state persistence (forwarded from the compat\n // runtime in the inner iframe). Two destinations:\n // 1) onWidgetStateChange — propagates upward for saved-view /\n // replay / fork persistence (matches the legacy\n // ChatGPTAppRenderer contract).\n // 2) setWidgetStateStore — keeps the Debug \"Widget State\" panel\n // live; without it, Apps SDK setWidgetState updates silently\n // bypass the diagnostics surface that reads from\n // widgetDebugInfo.widgetState.\n if (data.type === \"openai:setWidgetState\") {\n // Defense-in-depth: drop persistence + propagation when the\n // matrix has setWidgetState disabled. Silent drop (no response\n // message) — setWidgetState is fire-and-forget in the spec, so\n // there's nothing to reject. Mirrors the runtime-level omission.\n if (liveCaps !== null && liveCaps.setWidgetState === false) return;\n if (onWidgetStateChange) {\n onWidgetStateChange(toolCallId, data.state);\n }\n setWidgetStateStore(toolCallId, data.state);\n return;\n }\n\n if (data.type === \"openai:setOpenInAppUrl\") {\n if (liveCaps !== null && liveCaps.setOpenInAppUrl === false) return;\n const nextUrl = resolveOpenInAppHref(data.href, explicitOpenInAppBaseUrl);\n if (nextUrl) {\n setOpenInAppUrlOverride(nextUrl);\n }\n return;\n }\n\n // Handle openai/* JSON-RPC notifications from the compat layer\n if (\n data.jsonrpc === \"2.0\" &&\n typeof data.method === \"string\" &&\n data.method.startsWith(\"openai/\")\n ) {\n logUiEvent({\n widgetId: toolCallId,\n serverId,\n direction: \"ui-to-host\",\n protocol: \"mcp-apps\",\n method: data.method,\n message: data,\n });\n\n // Defense-in-depth for the openai/* JSON-RPC notification family.\n // Same rationale as the file-op branch above: SDK runtime should\n // omit these methods, but a stale closure or hand-crafted\n // postMessage would still arrive. Silent drop on notifications;\n // requestCheckout uses a callId pattern so we respond with an\n // error so the widget's pending resolver doesn't hang.\n if (data.method === \"openai/requestModal\") {\n if (liveCaps !== null && liveCaps.requestModal === false) return;\n const params = data.params ?? {};\n setModalTitle(params.title || \"Modal\");\n setModalParams(params.params || {});\n setModalTemplate(params.template || null);\n setModalOpen(true);\n } else if (data.method === \"openai/requestClose\") {\n if (liveCaps !== null && liveCaps.requestClose === false) return;\n setModalOpen(false);\n } else if (data.method === \"openai/requestCheckout\") {\n const params = data.params ?? {};\n const { callId: cId, ...sessionData } = params;\n if (liveCaps !== null && liveCaps.requestCheckout === false) {\n sandboxRef.current?.postMessage({\n jsonrpc: \"2.0\",\n method: \"openai/requestCheckout:response\",\n params: {\n callId: cId,\n error: \"openai/requestCheckout denied by host capability policy\",\n },\n });\n return;\n }\n setCheckoutCallId(cId as number);\n setCheckoutSession(sessionData);\n setCheckoutOpen(true);\n }\n }\n };\n const showWidget = isReady && canRenderStreamingInput;\n\n useEffect(() => {\n logWidgetDebug(\"host-to-ui\", \"debug/widget-visibility\", {\n bridgeTransportReady,\n canRenderStreamingInput,\n hasWidgetHtml,\n isReady,\n loadError,\n showWidget,\n toolState: toolState ?? null,\n widgetHtmlLength,\n });\n }, [\n bridgeTransportReady,\n canRenderStreamingInput,\n hasWidgetHtml,\n isReady,\n loadError,\n showWidget,\n toolState,\n widgetHtmlLength,\n logWidgetDebug,\n ]);\n\n useEffect(() => {\n if (!bridgeTransportReady || !widgetHtml) return;\n logWidgetDebug(\"host-to-ui\", \"debug/sandbox-html-ready\", {\n hasCsp: !!effectiveSandbox.csp,\n hasPermissions: !!effectiveSandbox.permissions,\n htmlLength: widgetHtml.length,\n permissive: effectiveSandbox.permissive,\n hostPolicyApplied: effectiveSandbox.hostPolicyApplied,\n });\n }, [bridgeTransportReady, widgetHtml, effectiveSandbox, logWidgetDebug]);\n\n const respondToCheckout = useCallback(\n (result: unknown, error?: string) => {\n if (checkoutCallId == null) return;\n const params: Record<string, unknown> = { callId: checkoutCallId };\n if (error) {\n params.error = error;\n } else {\n params.result = result;\n }\n sandboxRef.current?.postMessage({\n jsonrpc: \"2.0\",\n method: \"openai/requestCheckout:response\",\n params,\n });\n setCheckoutOpen(false);\n setCheckoutSession(null);\n setCheckoutCallId(null);\n },\n [checkoutCallId]\n );\n\n // Denied state\n if (toolState === \"output-denied\") {\n return (\n <div className=\"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2\">\n Tool execution was denied.\n </div>\n );\n }\n\n if (loadError) {\n return (\n <div className=\"border border-destructive/40 bg-destructive/10 text-destructive text-xs rounded-md px-3 py-2\">\n Failed to load MCP App: {loadError}\n </div>\n );\n }\n\n if (!widgetHtml) {\n return null;\n }\n\n const isPip = effectiveDisplayMode === \"pip\";\n const isFullscreen = effectiveDisplayMode === \"fullscreen\";\n const isMobilePlaygroundMode =\n isPlaygroundActive && playgroundDeviceType === \"mobile\";\n const isContainedFullscreenMode =\n isPlaygroundActive &&\n (playgroundDeviceType === \"mobile\" || playgroundDeviceType === \"tablet\");\n const showOpenInAppButton =\n isFullscreen && !!openInAppUrl && !isMobilePlaygroundMode;\n\n const containerClassName = (() => {\n if (isFullscreen) {\n if (isContainedFullscreenMode) {\n return \"absolute inset-0 z-10 w-full h-full bg-background flex flex-col\";\n }\n return \"fixed inset-0 z-40 w-full h-full bg-background flex flex-col\";\n }\n\n if (isPip) {\n if (isMobilePlaygroundMode) {\n return \"absolute inset-0 z-10 w-full h-full bg-background flex flex-col\";\n }\n if (isPlaygroundActive) {\n return [\n \"absolute top-4 left-1/2 -translate-x-1/2 z-40 w-full min-w-[300px] max-w-[min(90vw,1200px)] space-y-2\",\n \"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80\",\n \"shadow-xl border border-border/60 rounded-xl p-3\",\n ].join(\" \");\n }\n return [\n \"fixed top-4 left-1/2 -translate-x-1/2 z-40 w-full min-w-[300px] max-w-[min(90vw,1200px)] space-y-2\",\n \"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80\",\n \"shadow-xl border border-border/60 rounded-xl p-3\",\n ].join(\" \");\n }\n\n return \"mt-3 space-y-2 relative group\";\n })();\n const canTransitionHeight =\n !isFullscreen && effectiveDisplayModeRef.current === effectiveDisplayMode;\n const iframeStyle: CSSProperties = {\n height: isFullscreen\n ? \"100%\"\n : isPip\n ? PIP_MAX_HEIGHT\n : lastInlineHeightRef.current,\n width: \"100%\",\n maxWidth: \"100%\",\n backgroundColor:\n !isFullscreen && matrixGatedPrefersBorder\n ? mergedStyleVariables[\"--color-background-primary\"]\n : hostChatBackground ?? \"transparent\",\n opacity: showWidget ? 1 : 0,\n transition: [\n \"opacity 150ms ease-in\",\n canTransitionHeight ? \"height 300ms ease-out\" : \"\",\n ]\n .filter(Boolean)\n .join(\", \"),\n // Keep iframe in the layout but invisible while not ready\n ...(!showWidget\n ? { position: \"absolute\" as const, pointerEvents: \"none\" as const }\n : {}),\n };\n const showHostChrome = !isFullscreen && matrixGatedPrefersBorder;\n const hostChromeStyle: CSSProperties | undefined = showHostChrome\n ? {\n backgroundColor: mergedStyleVariables[\"--color-background-primary\"],\n }\n : undefined;\n const iframe = (\n <SandboxedIframe\n ref={sandboxRef}\n html={bridgeTransportReady ? widgetHtml : null}\n sandbox=\"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox\"\n // Browser-enforced CSP / Permission Policy MUST receive the resolved\n // values, not the raw resource declaration. `effectiveSandbox` runs the\n // shared resolver (mode → restrictTo intersect → hosted-mode clamp);\n // when a host policy applies it forces\n // `permissive: false` so SandboxedIframe injects the meta-CSP rather\n // than skipping it. Passing `widgetCsp` here directly is the canonical\n // regression — keep the resolver path.\n csp={effectiveSandbox.csp}\n permissions={effectiveSandbox.permissions}\n permissive={effectiveSandbox.permissive}\n sandboxAttrs={effectiveSandbox.sandboxAttrs}\n allowFeatures={effectiveSandbox.allowFeatures}\n cspDirectives={effectiveSandbox.cspDirectives}\n colorScheme={resolvedTheme}\n recordMode={recordMode}\n onProxyReady={() => {\n setSandboxProxyReady(true);\n logWidgetDebug(\"ui-to-host\", \"debug/sandbox-proxy-ready\", {\n bridgeTransportReady,\n hasWidgetHtml,\n });\n }}\n onMessage={handleSandboxMessage}\n title={`MCP App: ${toolName}`}\n hostedMode={host.surface.hostedMode}\n sandboxOrigin={host.surface.sandboxOrigin}\n className={`bg-transparent overflow-hidden ${\n isFullscreen\n ? \"flex-1 border-0 rounded-none\"\n : `rounded-md ${\n matrixGatedPrefersBorder ? \"border border-border/40\" : \"\"\n }`\n }`}\n style={iframeStyle}\n />\n );\n\n return (\n <div\n className={containerClassName}\n data-mcp-app-persistent-initial-tool-call-id={\n persistentSurfaceInitialToolCallId\n }\n data-mcp-app-persistent-surface-id={persistentSurfaceId}\n >\n {((isFullscreen && isContainedFullscreenMode) ||\n (isPip && isMobilePlaygroundMode)) && (\n <>\n <button\n onClick={() => {\n userPreferInlineRef.current = true;\n setDisplayMode(\"inline\");\n if (isPip) {\n onExitPip?.(pipWidgetId ?? displayWidgetId);\n }\n // onExitFullscreen is called within setDisplayMode when leaving fullscreen\n }}\n className=\"absolute left-3 top-3 z-20 flex h-8 w-8 items-center justify-center rounded-full bg-black/20 hover:bg-black/40 text-white transition-colors cursor-pointer\"\n aria-label=\"Close\"\n >\n <X className=\"w-5 h-5\" />\n </button>\n {showOpenInAppButton && (\n <button\n onClick={handleOpenInApp}\n className=\"absolute right-3 top-3 z-20 flex h-8 w-8 items-center justify-center rounded-full bg-black/20 hover:bg-black/40 text-white transition-colors cursor-pointer\"\n aria-label={`Open in ${openInAppLabel}`}\n title={`Open in ${openInAppLabel}`}\n >\n <ExternalLink className=\"w-4 h-4\" />\n </button>\n )}\n </>\n )}\n\n {isFullscreen && !isContainedFullscreenMode && (\n <div className=\"grid grid-cols-[1fr_auto_1fr] items-center gap-3 px-4 h-14 border-b border-border/40 bg-background/95 backdrop-blur z-40 shrink-0\">\n <div />\n <div className=\"font-medium text-sm text-muted-foreground min-w-0 max-w-[40vw] truncate\">\n {openInAppLabel}\n </div>\n <div className=\"flex items-center justify-end gap-2 min-w-0\">\n {showOpenInAppButton && (\n <button\n onClick={handleOpenInApp}\n className=\"inline-flex items-center justify-center gap-1.5 h-8 max-w-[16rem] rounded-full border border-border/60 px-2 sm:px-3 text-xs font-medium text-foreground hover:bg-muted transition-colors\"\n aria-label={`Open in ${openInAppLabel}`}\n title={`Open in ${openInAppLabel}`}\n >\n <ExternalLink className=\"w-3.5 h-3.5 shrink-0\" />\n <span className=\"hidden sm:inline min-w-0 truncate\">\n Open in {openInAppLabel}\n </span>\n </button>\n )}\n <button\n onClick={() => {\n userPreferInlineRef.current = true;\n setDisplayMode(\"inline\");\n if (ownsPipDisplayMode) {\n onExitPip?.(pipWidgetId ?? displayWidgetId);\n }\n }}\n className=\"p-2 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors\"\n aria-label=\"Exit fullscreen\"\n >\n <X className=\"w-5 h-5\" />\n </button>\n </div>\n </div>\n )}\n\n {isPip && !isMobilePlaygroundMode && (\n <button\n onClick={() => {\n userPreferInlineRef.current = true;\n setDisplayMode(\"inline\");\n onExitPip?.(pipWidgetId ?? displayWidgetId);\n }}\n className=\"absolute left-2 top-2 z-10 flex h-6 w-6 items-center justify-center rounded-md bg-background/80 hover:bg-background border border-border/50 text-muted-foreground hover:text-foreground transition-colors cursor-pointer\"\n aria-label=\"Close PiP mode\"\n title=\"Close PiP mode\"\n >\n <X className=\"w-4 h-4\" />\n </button>\n )}\n {/* Keep this wrapper mounted so display-mode changes don't remount the\n * sandbox iframe and strand the bridge on the old contentWindow. */}\n <div\n data-testid={showHostChrome ? \"mcp-app-host-chrome\" : undefined}\n className={showHostChrome ? \"rounded-md\" : \"contents\"}\n style={hostChromeStyle}\n >\n {iframe}\n </div>\n {/* SEP-1865 App-Provided Tools: per-iframe busy indicator. Surfaces\n * when the host is dispatching `tools/call` into this iframe (the\n * count comes from `useAppToolsRegistry.pendingControllers`). Sits\n * in the top-right of the inline container; suppressed in\n * fullscreen because the fullscreen header already names the tool\n * and would crowd this overlay. */}\n {pendingAppToolCalls > 0 && !isFullscreen && (\n <div\n className=\"pointer-events-none absolute right-2 top-2 z-20 flex h-6 w-6 items-center justify-center rounded-md bg-background/80 border border-border/50 text-muted-foreground shadow-sm\"\n aria-label=\"App tool call in progress\"\n title=\"App tool call in progress\"\n data-testid=\"mcp-app-busy-indicator\"\n >\n <Loader2 className=\"w-3.5 h-3.5 animate-spin\" />\n </div>\n )}\n\n <McpAppsModal\n open={modalOpen}\n onOpenChange={setModalOpen}\n title={modalTitle}\n template={modalTemplate}\n params={modalParams}\n registerBridgeHandlers={registerBridgeHandlers}\n // SEP-1865 App-Provided Tools: the modal bridge replaces\n // `oninitialized` to suppress inline-state side effects, which\n // also drops the inline registration call. The modal owns its\n // own bridge-id and `surface: \"modal\"` registration; pass the\n // shared refresh helper down so the modal can advertise/refresh\n // its iframe's tools without re-implementing the listTools loop.\n refreshAppProvidedTools={refreshAppProvidedTools}\n // The modal mounts its own SandboxedIframe via `fetchMcpAppsWidgetContent`.\n // Pass the resolved values so the modal's CSP enforcement matches the\n // inline iframe — otherwise a host restrictTo intersection applies to\n // inline but not to a modal-mode widget reading the same resource.\n widgetCsp={effectiveSandbox.csp}\n widgetPermissions={effectiveSandbox.permissions}\n widgetPermissive={effectiveSandbox.permissive}\n widgetSandboxAttrs={effectiveSandbox.sandboxAttrs}\n widgetAllowFeatures={effectiveSandbox.allowFeatures}\n widgetCspDirectives={effectiveSandbox.cspDirectives}\n hostContextRef={hostContextRef}\n serverId={serverId}\n resourceUri={resourceUri}\n toolCallId={toolCallId}\n toolName={toolName}\n cspMode={cspMode}\n injectOpenAiCompat={effectiveInjectOpenAiCompat}\n // Same resolved blob the inline AppBridge advertises. Inline +\n // modal must speak an identical surface to the widget so\n // app.getHostCapabilities() returns the same record regardless\n // of which iframe the widget is mounted in.\n effectiveHostCapabilities={effectiveHostCapabilities}\n // Resolved hostInfo + web-managed flag passed down (the modal no longer\n // reads useActiveMcpProfile/useWebManagedServers/resolveHostInfo\n // directly) so inline + modal stay in lockstep and the modal holds no\n // inspector-app-state coupling.\n hostInfo={resolvedBridgeHostInfo}\n webManagedServers={webManagedServers}\n toolInputRef={toolInputRef}\n toolOutputRef={toolOutputRef}\n themeModeRef={themeModeRef}\n addUiLog={(log) =>\n logUiEvent({\n ...log,\n protocol: \"mcp-apps\" as UiProtocol,\n })\n }\n onCspViolation={handleCspViolation}\n />\n\n {checkoutSession != null && Checkout && (\n <Checkout\n session={checkoutSession}\n open={checkoutOpen}\n onOpenChange={setCheckoutOpen}\n onComplete={(result) => respondToCheckout(result)}\n onError={(error) => respondToCheckout(null, error)}\n onCancel={() => respondToCheckout(null, \"User cancelled checkout\")}\n onCallTool={async (toolName, params) => {\n if (!onCallTool) {\n throw new Error(\"Tool calls not supported\");\n }\n return onCallTool(toolName, params);\n }}\n />\n )}\n </div>\n );\n}\n","import { useEffect, useLayoutEffect, useMemo, useState } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport {\n MCPAppsRendererSurface,\n type MCPAppsRendererProps,\n} from \"./mcp-apps-renderer\";\nimport {\n getRenderableSurfaceEntries,\n useWidgetSurfaceStore,\n type WidgetSurfaceId,\n} from \"./widget-surface-store\";\nexport { WidgetSurfaceHostProvider } from \"./widget-surface-context\";\n\nfunction createSurfaceContainer(surfaceId: WidgetSurfaceId) {\n const container = document.createElement(\"div\");\n container.dataset.mcpAppSurfaceContainer = surfaceId;\n container.style.display = \"contents\";\n return container;\n}\n\nfunction WidgetSurfacePortal({\n anchorElement,\n initialToolCallId,\n parkingElement,\n props,\n surfaceId,\n}: {\n anchorElement: HTMLDivElement | null;\n initialToolCallId: string;\n parkingElement: HTMLDivElement | null;\n props: MCPAppsRendererProps;\n surfaceId: WidgetSurfaceId;\n}) {\n const [container] = useState(() => createSurfaceContainer(surfaceId));\n const targetElement = anchorElement ?? parkingElement;\n\n useLayoutEffect(() => {\n if (!targetElement) return;\n if (container.parentElement !== targetElement) {\n targetElement.appendChild(container);\n }\n }, [container, targetElement]);\n\n useEffect(() => {\n return () => {\n container.remove();\n };\n }, [container]);\n\n return createPortal(\n <MCPAppsRendererSurface\n {...props}\n persistentSurfaceInitialToolCallId={initialToolCallId}\n persistentSurfaceId={surfaceId}\n />,\n container,\n surfaceId\n );\n}\n\nexport function WidgetSurfaceHost({\n chatSessionId,\n}: {\n chatSessionId?: string;\n}) {\n const [parkingElement, setParkingElement] = useState<HTMLDivElement | null>(\n null\n );\n const surfaces = useWidgetSurfaceStore((state) => state.surfaces);\n const entries = useMemo(\n () => getRenderableSurfaceEntries(surfaces, chatSessionId),\n [chatSessionId, surfaces]\n );\n\n useEffect(() => {\n return () => {\n useWidgetSurfaceStore.getState().clearChatSession(chatSessionId);\n };\n }, [chatSessionId]);\n\n return (\n <>\n <div\n ref={setParkingElement}\n data-mcp-app-surface-parking\n style={{\n height: 0,\n overflow: \"hidden\",\n pointerEvents: \"none\",\n position: \"absolute\",\n width: 0,\n }}\n />\n {entries.map(({ surfaceId, anchorElement, initialToolCallId, props }) => (\n <WidgetSurfacePortal\n key={surfaceId}\n anchorElement={anchorElement}\n initialToolCallId={initialToolCallId}\n parkingElement={parkingElement}\n props={props}\n surfaceId={surfaceId}\n />\n ))}\n </>\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/widget-host-context.tsx","../src/mcp-apps-utils.ts","../src/tool-result-utils.ts","../src/app-tools-registry.ts","../src/useToolInputStreaming.ts","../src/sandboxed-iframe.tsx","../src/mcp-apps-modal.tsx","../src/widget-file-messages.ts","../src/widget-surface-context.tsx","../src/widget-surface-store.ts","../src/mcp-apps-renderer.tsx","../src/widget-surface-host.tsx"],"names":["UIType","useCallback","SandboxedIframe","useRef","useState","useMemo","useEffect","jsx","createContext","useContext","create","recorderDebug","stableStringifyJson","useLayoutEffect","prefersBorder","toolCallId","resolvedPermissions","iframe","AppBridge","LoggingTransport","PostMessageTransport","extractMethod","toolName","jsxs","Fragment"],"mappings":";;;;;;;;;;;;;AASA,IAAM,iBAAA,GAAoB,cAAiC,IAAI,CAAA;AAQxD,SAAS,kBAAA,CAAmB;AAAA,EACjC,KAAA;AAAA,EACA;AACF,CAAA,EAA4B;AAC1B,EAAA,uBACE,GAAA,CAAC,iBAAA,CAAkB,QAAA,EAAlB,EAA2B,OACzB,QAAA,EACH,CAAA;AAEJ;AAOO,SAAS,aAAA,GAA4B;AAC1C,EAAA,MAAM,IAAA,GAAO,WAAW,iBAAiB,CAAA;AACzC,EAAA,IAAI,SAAS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AAe,MAAA;AAAA,UACf,QAAA,EAAU,UAAA;AAAA,UACV,KAAA,EAAO;AAAA;AACT;AAAA,KACF;AAAA,IACC,OAAA,CAAQ,IAAI,CAAC,EAAE,WAAW,aAAA,EAAe,iBAAA,EAAmB,KAAA,EAAM,qBACjEA,GAAAA;AAAA,MAAC,mBAAA;AAAA,MAAA;AAAA,QAEC,aAAA;AAAA,QACA,iBAAA;AAAA,QACA,cAAA;AAAA,QACA,KAAA;AAAA,QACA;AAAA,OAAA;AAAA,MALK;AAAA,KAOR;AAAA,GAAA,EACH,CAAA;AAEJ","file":"index.js","sourcesContent":["import { createContext, useContext, type ReactNode } from \"react\";\nimport type { WidgetHost } from \"./widget-host\";\n\n// The package owns the `WidgetHost` React context + hook contract. The inspector\n// keeps the concrete host implementation (`use-widget-host.ts`, which reads its\n// stores/contexts) and feeds it through `<WidgetHostProvider>`. This is the\n// inversion the renderer relocation (3d) relies on: the moved renderer calls the\n// package's `useWidgetHost()` instead of the inspector's composite hook.\n\nconst WidgetHostContext = createContext<WidgetHost | null>(null);\n\nexport interface WidgetHostProviderProps {\n /** The concrete host the inspector builds from its stores/contexts. */\n value: WidgetHost;\n children: ReactNode;\n}\n\nexport function WidgetHostProvider({\n value,\n children,\n}: WidgetHostProviderProps) {\n return (\n <WidgetHostContext.Provider value={value}>\n {children}\n </WidgetHostContext.Provider>\n );\n}\n\n/**\n * Read the injected {@link WidgetHost}. Throws if no `<WidgetHostProvider>` is\n * mounted above — the package never reaches into inspector state itself, so a\n * missing provider is a wiring bug, not a fallback.\n */\nexport function useWidgetHost(): WidgetHost {\n const host = useContext(WidgetHostContext);\n if (host === null) {\n throw new Error(\n \"useWidgetHost must be used within a <WidgetHostProvider>. The inspector \" +\n \"supplies the concrete host via its use-widget-host adapter.\",\n );\n }\n return host;\n}\n","// UI-type detection for widget-bearing tool calls. Relocated from the inspector\n// (`@/lib/mcp-ui/mcp-apps-utils`) in Phase 3d-ii; depends only on ext-apps +\n// @mcp-ui/client + the SDK tool-visibility leaf. The inspector keeps the\n// `ListToolsResultWithMetadata`-typed `isMCPApp`/`isOpenAIApp` helpers (they\n// need an inspector api type) and re-exports this core.\nimport { isUIResource } from \"@mcp-ui/client\";\nimport { getToolUiResourceUri } from \"@modelcontextprotocol/ext-apps/app-bridge\";\n\n/**\n * Minimal structural shape `detectUiTypeFromTool` needs — just the `_meta` bag.\n * Kept structural (rather than importing `Tool` from\n * `@modelcontextprotocol/client`) so the package's public detection surface\n * doesn't pin a specific MCP SDK Tool type; any `{ _meta }`-bearing tool works.\n */\nexport interface ToolLike {\n _meta?: Record<string, unknown>;\n}\n\n// SEP-1865 tool-visibility helpers live in the framework-free SDK leaf so the\n// host bridge and the renderer share one model-only visibility check. Re-exported\n// here to preserve the existing `mcp-apps-utils` import surface.\nexport {\n getToolVisibility,\n isVisibleToModelOnly,\n isVisibleToAppOnly,\n} from \"@mcpjam/sdk/widget-runtime\";\n\nexport enum UIType {\n MCP_APPS = \"mcp-apps\",\n OPENAI_SDK = \"openai-sdk\",\n OPENAI_SDK_AND_MCP_APPS = \"openai-sdk-and-mcp-apps\",\n MCP_UI = \"mcp-ui\",\n}\n\nexport function detectUiTypeFromTool(tool: ToolLike): UIType | null {\n const toolMeta = tool._meta;\n if (!toolMeta) return null;\n return detectUIType(toolMeta, undefined);\n}\n\nexport function detectUIType(\n toolMeta: Record<string, unknown> | undefined,\n toolResult: unknown,\n): UIType | null {\n // 1. OpenAI SDK and MCP Apps: openai/outputTemplate AND ui.resourceUri\n if (\n toolMeta?.[\"openai/outputTemplate\"] &&\n getToolUiResourceUri({ _meta: toolMeta })\n ) {\n return UIType.OPENAI_SDK_AND_MCP_APPS;\n }\n\n // 2. OpenAI SDK: openai/outputTemplate\n if (toolMeta?.[\"openai/outputTemplate\"]) {\n return UIType.OPENAI_SDK;\n }\n\n // 3. MCP Apps (SEP-1865): ui.resourceUri\n if (getToolUiResourceUri({ _meta: toolMeta })) {\n return UIType.MCP_APPS;\n }\n\n // 4. MCP-UI: inline ui:// resource in result\n const directResource = (toolResult as { resource?: { uri?: string } })\n ?.resource;\n if (directResource?.uri?.startsWith(\"ui://\")) {\n return UIType.MCP_UI;\n }\n\n const content = (toolResult as { content?: unknown[] })?.content;\n if (Array.isArray(content)) {\n for (const item of content) {\n // isUIResource is a type guard; cast to any for the runtime check.\n if (isUIResource(item as any)) {\n return UIType.MCP_UI;\n }\n }\n }\n return null;\n}\n\nexport function getUIResourceUri(\n uiType: UIType | null,\n toolMeta: Record<string, unknown> | undefined,\n): string | null {\n switch (uiType) {\n case UIType.MCP_APPS:\n case UIType.OPENAI_SDK_AND_MCP_APPS:\n return getToolUiResourceUri({ _meta: toolMeta }) ?? null;\n case UIType.OPENAI_SDK:\n return (toolMeta?.[\"openai/outputTemplate\"] as string) ?? null;\n default:\n return null;\n }\n}\n","/**\n * Shared helpers for reading metadata and server IDs from tool results.\n *\n * Tool results may carry `_meta` and `_serverId` either at the top level or\n * nested under a `.value` wrapper. These utilities normalise access across both\n * shapes. Pure (no deps) — relocated from the inspector in Phase 3d-ii.\n */\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nexport function readToolResultObject(\n result: unknown,\n): Record<string, unknown> | undefined {\n if (!isRecord(result)) return undefined;\n return result;\n}\n\nexport function readToolResultMeta(\n result: unknown,\n): Record<string, unknown> | undefined {\n if (!isRecord(result)) return undefined;\n\n if (isRecord(result._meta)) {\n return result._meta;\n }\n\n if (isRecord(result.value) && isRecord(result.value._meta)) {\n return result.value._meta;\n }\n\n return undefined;\n}\n\nexport function readToolResultServerId(result: unknown): string | undefined {\n if (!isRecord(result)) return undefined;\n\n if (typeof result._serverId === \"string\") {\n return result._serverId;\n }\n\n if (isRecord(result.value) && typeof result.value._serverId === \"string\") {\n return result.value._serverId;\n }\n\n const meta = readToolResultMeta(result);\n return typeof meta?._serverId === \"string\" ? meta._serverId : undefined;\n}\n","/**\n * App-Provided Tools registry (SEP-1865).\n *\n * Each mounted MCP app iframe gets one entry here, keyed by a per-instance\n * `BridgeId`. Entries hold:\n * - The `AppBridge` ref used to dispatch `tools/call` into the iframe.\n * - The tools the app advertised via `tools/list` after `ui/initialize`.\n * - Opaque aliases (`app_<8hex>`) that act as the model-facing tool names.\n *\n * The registry serves two callers:\n * - `snapshotForChatBody()` — drained at chat POST time so the server can\n * register no-execute AI SDK tools that the model can pick.\n * - `resolve(alias)` — looked up by `useChat.onToolCall` to find the right\n * bridge to dispatch into.\n *\n * App-provided tools are exposed exactly as the app lists them. MCPJam keeps\n * the readonly bit for attribution and future policy, but does not force its\n * server-tool approval flow onto app-provided tools.\n */\n\nimport { useCallback } from \"react\";\nimport { create } from \"zustand\";\nimport { useShallow } from \"zustand/react/shallow\";\nimport type { AppBridge } from \"@modelcontextprotocol/ext-apps/app-bridge\";\nimport type { CallToolResult } from \"@modelcontextprotocol/client\";\n// Traffic logging is injected by the caller (the inspector chat/playground\n// dispatch hooks) rather than reached for via `@/stores`, so this registry\n// carries no inspector telemetry into the widget package (Tier-B).\nimport type { WidgetDebugSink } from \"./widget-host\";\n\n/** Injected traffic-log sink — `WidgetDebugSink[\"addTrafficLog\"]`. */\nexport type AddTrafficLog = WidgetDebugSink[\"addTrafficLog\"];\n\n/** Per-AppBridge instance identifier (independent of parentToolCallId). */\nexport type BridgeId = string;\n\nexport type AppToolDescriptor = NonNullable<\n Awaited<ReturnType<AppBridge[\"listTools\"]>>[\"tools\"]\n>[number];\n\nexport interface AppInstance {\n bridgeId: BridgeId;\n /** Chat session/lane that owns this rendered iframe. */\n chatSessionId?: string;\n /** The host tool call whose render mounted this iframe. */\n parentToolCallId: string;\n serverId: string;\n appName: string;\n appVersion?: string;\n surface: \"inline\" | \"modal\";\n bridge: AppBridge;\n tools: AppToolDescriptor[];\n registeredAtMs: number;\n /**\n * Accessor for the iframe DOM node that hosts this app instance. Lets\n * callers (e.g. `onToolCall`) scroll the iframe into view before\n * dispatching `tools/call`. Optional because legacy callers and tests\n * may not set it.\n */\n getIframeElement?: () => HTMLIFrameElement | null;\n}\n\nexport interface AppToolAlias {\n alias: string;\n bridgeId: BridgeId;\n rawName: string;\n /** Cached from `annotations.readOnlyHint === true`. */\n readOnly: boolean;\n}\n\n/** What the snapshot ships to the server in the chat POST body. */\nexport interface AppToolSnapshotEntry {\n alias: string;\n appName: string;\n appVersion?: string;\n serverId: string;\n parentToolCallId: string;\n rawName: string;\n description?: string;\n inputSchema?: Record<string, unknown>;\n readOnly: boolean;\n}\n\n// Server-mirrored limits for the chat POST snapshot.\nconst MAX_SNAPSHOT_ENTRIES = 64;\nconst MAX_DESCRIPTION_CHARS = 512;\nconst MAX_INPUT_SCHEMA_BYTES = 8 * 1024;\nconst ALIAS_REGEX = /^app_[a-z0-9]{8}$/i;\n\nexport interface AppToolAttribution {\n rawName: string;\n appName: string;\n}\n\ninterface AppToolsRegistryState {\n instancesByBridgeId: Map<BridgeId, AppInstance>;\n aliases: Map<string, AppToolAlias>;\n /** Active app-tool provider per chat-scoped host tool call. */\n activeBridgeByParent: Map<string, BridgeId>;\n /**\n * AbortControllers for in-flight `bridge.callTool(...)` dispatches, keyed\n * by the dispatching bridge's id. `unregisterInstance` aborts every\n * controller in the matching set so a torn-down iframe never leaves a\n * paused server stream waiting forever. Each set is also the source of\n * truth for the per-iframe busy indicator.\n */\n pendingControllers: Map<BridgeId, Set<AbortController>>;\n\n registerInstance: (inst: AppInstance) => Promise<void>;\n unregisterInstance: (bridgeId: BridgeId) => void;\n pushActive: (\n parentToolCallId: string,\n bridgeId: BridgeId,\n chatSessionId?: string,\n ) => void;\n popActive: (\n parentToolCallId: string,\n bridgeId: BridgeId,\n chatSessionId?: string,\n ) => void;\n\n /** Adds `controller` to the bridge's pending set and bumps the busy count. */\n registerPendingCall: (\n bridgeId: BridgeId,\n controller: AbortController,\n ) => void;\n /** Removes `controller` from the bridge's pending set (no-op if absent). */\n unregisterPendingCall: (\n bridgeId: BridgeId,\n controller: AbortController,\n ) => void;\n\n snapshotForChatBody: (chatSessionId?: string) => AppToolSnapshotEntry[];\n resolve: (\n alias: string,\n chatSessionId?: string,\n ) => {\n bridge: AppBridge;\n rawName: string;\n readOnly: boolean;\n instance: AppInstance;\n } | null;\n}\n\n/**\n * Produce an opaque alias for a rendered app tool. SHA-256 hashed over stable\n * identity-bearing inputs and truncated to 8 hex chars so the wire\n * name is always 12 chars: well under Anthropic's 64-char tool-name limit\n * and never collides with the `getInvalidAnthropicToolNames` charset.\n *\n * Deliberately exclude `bridgeId`: a live app can reconnect/re-register its\n * bridge without changing the rendered host tool call or raw app-tool name.\n * The alias must stay stable across that churn so the model does not see the\n * same app tool under a fresh name.\n *\n * Collision retry: if a generated alias is already in use, the caller\n * (`registerInstance`) re-rolls with a numeric salt appended to the\n * preimage. In practice 8 hex chars over the joined inputs has negligible\n * collision risk; the retry is a belt-and-suspenders guard.\n */\nasync function generateAlias(\n chatSessionId: string | undefined,\n serverId: string,\n parentToolCallId: string,\n surface: AppInstance[\"surface\"],\n rawName: string,\n salt = 0,\n): Promise<string> {\n const preimage = `${\n chatSessionId ?? \"\"\n }\\0${serverId}\\0${parentToolCallId}\\0${surface}\\0${rawName}\\0${salt}`;\n const bytes = new TextEncoder().encode(preimage);\n const digest = await crypto.subtle.digest(\"SHA-256\", bytes);\n const hex = Array.from(new Uint8Array(digest))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n return `app_${hex.slice(0, 8)}`;\n}\n\nfunction isReadOnly(tool: AppToolDescriptor): boolean {\n return tool.annotations?.readOnlyHint === true;\n}\n\nfunction getActiveParentKey(\n parentToolCallId: string,\n chatSessionId?: string,\n): string {\n return chatSessionId\n ? `${chatSessionId}\\0${parentToolCallId}`\n : parentToolCallId;\n}\n\nfunction isSameAppSlot(a: AppInstance, b: AppInstance): boolean {\n return (\n a.parentToolCallId === b.parentToolCallId &&\n a.surface === b.surface &&\n a.chatSessionId === b.chatSessionId\n );\n}\n\nexport const useAppToolsRegistry = create<AppToolsRegistryState>(\n (set, get) => ({\n instancesByBridgeId: new Map(),\n aliases: new Map(),\n activeBridgeByParent: new Map(),\n pendingControllers: new Map(),\n\n // Returns a Promise so callers (and tests) can await the alias-hash\n // round-trip. The renderer uses `void registerInstance(...)` because\n // there's nothing to do until the next chat POST. Tests await so\n // resolved microtasks don't bleed into the next test's reset store.\n registerInstance: async (inst) => {\n // Identify bridges this registration supersedes: same chat session,\n // same parent + same surface, different bridgeId. We mirror this set\n // across instance purge, alias purge, and pendingControllers cleanup so\n // the three stay in lockstep. A modal opening over a still-mounted\n // inline app (different surfaces) does NOT supersede the inline bridge —\n // its instance, aliases, and pending controllers all survive.\n const supersededBridgeIds = new Set<BridgeId>();\n for (const [bridgeId, oldInst] of get().instancesByBridgeId) {\n if (bridgeId !== inst.bridgeId && isSameAppSlot(oldInst, inst)) {\n supersededBridgeIds.add(bridgeId);\n }\n }\n\n // Generate aliases for every tool the app listed. `readOnly` is cached\n // from annotations, but it is not an inclusion gate.\n const aliasesForInst: AppToolAlias[] = [];\n const existing = new Set(\n [...get().aliases.entries()]\n .filter(([, alias]) => {\n if (alias.bridgeId === inst.bridgeId) return false;\n return !supersededBridgeIds.has(alias.bridgeId);\n })\n .map(([alias]) => alias),\n );\n for (const tool of inst.tools) {\n let salt = 0;\n let alias = await generateAlias(\n inst.chatSessionId,\n inst.serverId,\n inst.parentToolCallId,\n inst.surface,\n tool.name,\n salt,\n );\n while (existing.has(alias)) {\n salt += 1;\n alias = await generateAlias(\n inst.chatSessionId,\n inst.serverId,\n inst.parentToolCallId,\n inst.surface,\n tool.name,\n salt,\n );\n }\n existing.add(alias);\n aliasesForInst.push({\n alias,\n bridgeId: inst.bridgeId,\n rawName: tool.name,\n readOnly: isReadOnly(tool),\n });\n }\n // Abort in-flight bridge.callTool dispatches against any superseded\n // bridge BEFORE we drop its instance entry. Same reasoning as\n // `unregisterInstance`: a fresh bridgeId taking over the same\n // (parent, surface) slot is an implicit teardown of the prior one,\n // and the chat stream will hang on the dead iframe if we skip this.\n for (const bridgeId of supersededBridgeIds) {\n const pending = get().pendingControllers.get(bridgeId);\n if (!pending) continue;\n for (const controller of pending) {\n try {\n controller.abort();\n } catch {\n // Ignore — abort() should never throw, but defensively continue.\n }\n }\n }\n set((s) => {\n const instancesByBridgeId = new Map(s.instancesByBridgeId);\n for (const bridgeId of supersededBridgeIds) {\n instancesByBridgeId.delete(bridgeId);\n }\n instancesByBridgeId.set(inst.bridgeId, inst);\n const aliases = new Map(s.aliases);\n for (const [alias, a] of s.aliases) {\n // Only drop aliases for the new bridge itself (replacement) or\n // for bridges actually being instance-removed. Crucially, we do\n // NOT drop aliases owned by a sibling instance under the same\n // parent but on a different surface (e.g. inline aliases when a\n // modal opens) — that bug left inline tools unresolvable until\n // re-initialization even after the modal closed.\n if (\n a.bridgeId === inst.bridgeId ||\n supersededBridgeIds.has(a.bridgeId)\n ) {\n aliases.delete(alias);\n }\n }\n for (const a of aliasesForInst) aliases.set(a.alias, a);\n const activeBridgeByParent = new Map(s.activeBridgeByParent);\n activeBridgeByParent.set(\n getActiveParentKey(inst.parentToolCallId, inst.chatSessionId),\n inst.bridgeId,\n );\n let pendingControllers = s.pendingControllers;\n if (supersededBridgeIds.size > 0) {\n pendingControllers = new Map(s.pendingControllers);\n for (const bridgeId of supersededBridgeIds) {\n pendingControllers.delete(bridgeId);\n }\n }\n return {\n instancesByBridgeId,\n aliases,\n activeBridgeByParent,\n pendingControllers,\n };\n });\n },\n\n unregisterInstance: (bridgeId) => {\n // Abort any in-flight `bridge.callTool` dispatches against this bridge\n // BEFORE we drop the instance entry. The catch branch in\n // `useChat.onToolCall` picks up the abort and resolves the tool call\n // with `isError: true`, which is what lets the paused server stream\n // continue. Skipping this leaves the chat hanging when an iframe is\n // torn down mid-dispatch.\n const pending = get().pendingControllers.get(bridgeId);\n if (pending) {\n for (const controller of pending) {\n try {\n controller.abort();\n } catch {\n // Ignore — abort() should never throw, but defensively continue.\n }\n }\n }\n set((s) => {\n const inst = s.instancesByBridgeId.get(bridgeId);\n if (!inst) return {};\n const instancesByBridgeId = new Map(s.instancesByBridgeId);\n instancesByBridgeId.delete(bridgeId);\n const aliases = new Map(s.aliases);\n for (const [alias, a] of s.aliases) {\n if (a.bridgeId === bridgeId) aliases.delete(alias);\n }\n const activeBridgeByParent = new Map(s.activeBridgeByParent);\n const activeParentKey = getActiveParentKey(\n inst.parentToolCallId,\n inst.chatSessionId,\n );\n if (activeBridgeByParent.get(activeParentKey) === bridgeId) {\n // Promote any other still-mounted instance under this parent so\n // its aliases stay resolvable and visible to the model. Without\n // this fallback, closing a modal that opened over a still-\n // mounted inline app leaves the inline app's tools unreachable\n // (both `resolve()` and `snapshotForChatBody()` gate on the\n // active bridge match). Mirrors the fallback search in\n // `popActive`.\n let fallback: BridgeId | undefined;\n for (const other of instancesByBridgeId.values()) {\n if (\n other.parentToolCallId === inst.parentToolCallId &&\n other.chatSessionId === inst.chatSessionId\n ) {\n fallback = other.bridgeId;\n break;\n }\n }\n if (fallback) {\n activeBridgeByParent.set(activeParentKey, fallback);\n } else {\n activeBridgeByParent.delete(activeParentKey);\n }\n }\n const pendingControllers = new Map(s.pendingControllers);\n pendingControllers.delete(bridgeId);\n return {\n instancesByBridgeId,\n aliases,\n activeBridgeByParent,\n pendingControllers,\n };\n });\n },\n\n registerPendingCall: (bridgeId, controller) => {\n set((s) => {\n const pendingControllers = new Map(s.pendingControllers);\n const next = new Set(pendingControllers.get(bridgeId));\n next.add(controller);\n pendingControllers.set(bridgeId, next);\n return { pendingControllers };\n });\n },\n\n unregisterPendingCall: (bridgeId, controller) => {\n set((s) => {\n const existing = s.pendingControllers.get(bridgeId);\n if (!existing || !existing.has(controller)) return {};\n const pendingControllers = new Map(s.pendingControllers);\n if (existing.size === 1) {\n pendingControllers.delete(bridgeId);\n } else {\n const next = new Set(existing);\n next.delete(controller);\n pendingControllers.set(bridgeId, next);\n }\n return { pendingControllers };\n });\n },\n\n pushActive: (parentToolCallId, bridgeId, chatSessionId) => {\n set((s) => {\n const next = new Map(s.activeBridgeByParent);\n next.set(getActiveParentKey(parentToolCallId, chatSessionId), bridgeId);\n return { activeBridgeByParent: next };\n });\n },\n\n popActive: (parentToolCallId, bridgeId, chatSessionId) => {\n set((s) => {\n const activeParentKey = getActiveParentKey(\n parentToolCallId,\n chatSessionId,\n );\n const current = s.activeBridgeByParent.get(activeParentKey);\n if (current !== bridgeId) return {};\n const next = new Map(s.activeBridgeByParent);\n // Fall back to any other registered instance under this parent.\n let fallback: BridgeId | undefined;\n for (const inst of s.instancesByBridgeId.values()) {\n if (\n inst.parentToolCallId === parentToolCallId &&\n inst.chatSessionId === chatSessionId &&\n inst.bridgeId !== bridgeId\n ) {\n fallback = inst.bridgeId;\n break;\n }\n }\n if (fallback) next.set(activeParentKey, fallback);\n else next.delete(activeParentKey);\n return { activeBridgeByParent: next };\n });\n },\n\n snapshotForChatBody: (chatSessionId) => {\n const { instancesByBridgeId, aliases, activeBridgeByParent } = get();\n const out: AppToolSnapshotEntry[] = [];\n let dropped = 0;\n for (const [alias, a] of aliases) {\n if (out.length >= MAX_SNAPSHOT_ENTRIES) {\n dropped += 1;\n continue;\n }\n if (!ALIAS_REGEX.test(alias)) continue;\n const inst = instancesByBridgeId.get(a.bridgeId);\n if (!inst) continue;\n if (chatSessionId && inst.chatSessionId !== chatSessionId) continue;\n // Only the active instance per parent contributes. This prevents stale\n // iframe instances from advertising tools after a modal or replay wins.\n if (\n activeBridgeByParent.get(\n getActiveParentKey(inst.parentToolCallId, inst.chatSessionId),\n ) !== inst.bridgeId\n ) {\n continue;\n }\n const tool = inst.tools.find((t) => t.name === a.rawName);\n if (!tool) continue;\n let inputSchema = tool.inputSchema;\n if (inputSchema) {\n let size = 0;\n try {\n size = new TextEncoder().encode(JSON.stringify(inputSchema)).length;\n } catch {\n continue; // unserializable\n }\n if (size > MAX_INPUT_SCHEMA_BYTES) continue;\n }\n const description = tool.description\n ? tool.description.slice(0, MAX_DESCRIPTION_CHARS)\n : undefined;\n out.push({\n alias,\n appName: inst.appName,\n appVersion: inst.appVersion,\n serverId: inst.serverId,\n parentToolCallId: inst.parentToolCallId,\n rawName: a.rawName,\n description,\n inputSchema,\n readOnly: a.readOnly,\n });\n }\n if (dropped > 0) {\n console.warn(\n `[app-tools] snapshot capped at ${MAX_SNAPSHOT_ENTRIES} entries; dropped ${dropped}.`,\n );\n }\n // Multi-instance disambiguation: when the same app is mounted more\n // than once concurrently (e.g. two tic-tac-toe boards from two\n // separate `tools/call` results), `tools/list` returns identical\n // `rawName`s and the model sees N tools with the same description.\n // Wire-level routing is already correct (aliases differ per\n // parentToolCallId), but the model can't tell which instance to\n // pick. Append `(from tool call <id>; instance N of M)` to the\n // description for any group with size > 1 so the model can\n // distinguish them via the visible tool-call history in the\n // transcript. Singletons stay untouched.\n const groupCounts = new Map<string, number>();\n for (const entry of out) {\n const key = `${entry.appName}\\0${entry.rawName}`;\n groupCounts.set(key, (groupCounts.get(key) ?? 0) + 1);\n }\n const groupIndex = new Map<string, number>();\n for (const entry of out) {\n const key = `${entry.appName}\\0${entry.rawName}`;\n const total = groupCounts.get(key) ?? 1;\n if (total <= 1) continue;\n const n = (groupIndex.get(key) ?? 0) + 1;\n groupIndex.set(key, n);\n const hint = ` (from tool call ${entry.parentToolCallId}; instance ${n} of ${total})`;\n const base = entry.description ?? \"\";\n entry.description = (base + hint).slice(0, MAX_DESCRIPTION_CHARS);\n }\n return out;\n },\n\n resolve: (alias, chatSessionId) => {\n const a = get().aliases.get(alias);\n if (!a) return null;\n const inst = get().instancesByBridgeId.get(a.bridgeId);\n if (!inst) return null;\n if (chatSessionId && inst.chatSessionId !== chatSessionId) return null;\n if (\n get().activeBridgeByParent.get(\n getActiveParentKey(inst.parentToolCallId, inst.chatSessionId),\n ) !== inst.bridgeId\n ) {\n return null;\n }\n return {\n bridge: inst.bridge,\n rawName: a.rawName,\n readOnly: a.readOnly,\n instance: inst,\n };\n },\n }),\n);\n\n/**\n * Side-channel log of every app-tool invocation for debugging and future UI.\n * Mirrors the widget-html debug store pattern. The full untouched\n * `CallToolResult` is stored here so the UI can later display\n * `structuredContent` / `_meta` that were intentionally stripped from model\n * context.\n */\nexport interface AppToolInvocationRecord {\n alias: string;\n rawName: string;\n appName: string;\n serverId: string;\n parentToolCallId: string;\n bridgeId: BridgeId;\n input: unknown;\n raw: CallToolResult;\n invokedAtMs: number;\n}\n\ninterface AppToolInvocationLogState {\n records: AppToolInvocationRecord[];\n append: (r: AppToolInvocationRecord) => void;\n clear: () => void;\n}\n\nconst MAX_INVOCATION_RECORDS = 200;\n\nexport const useAppToolInvocationLog = create<AppToolInvocationLogState>(\n (set) => ({\n records: [],\n append: (r) =>\n set((s) => {\n const next = s.records.concat(r);\n if (next.length > MAX_INVOCATION_RECORDS) {\n next.splice(0, next.length - MAX_INVOCATION_RECORDS);\n }\n return { records: next };\n }),\n clear: () => set({ records: [] }),\n }),\n);\n\nexport function recordAppToolInvocation(\n args: Omit<AppToolInvocationRecord, \"invokedAtMs\">,\n addTrafficLog?: AddTrafficLog,\n): void {\n useAppToolInvocationLog.getState().append({\n ...args,\n invokedAtMs: Date.now(),\n });\n // Mirror the invocation into the shared traffic-log via the injected sink so\n // it surfaces in `LoggerView` alongside the rest of the iframe ↔ host\n // traffic. `direction: \"host-to-ui\"` because the host dispatched the\n // call into the iframe via `bridge.callTool`. `widgetId` matches the\n // parent host tool call so existing logger filters scope correctly.\n // Only the model-safe scrubbed payload is shipped here — the full\n // `CallToolResult` (including `structuredContent` and `_meta`) lives\n // in `useAppToolInvocationLog` for richer debug UIs. When no sink is\n // injected (non-inspector host), the invocation log still records.\n if (!addTrafficLog) return;\n try {\n addTrafficLog({\n widgetId: args.parentToolCallId,\n serverId: args.serverId,\n direction: \"host-to-ui\",\n protocol: \"mcp-apps\",\n method: \"tools/call\",\n message: {\n alias: args.alias,\n toolName: args.rawName,\n appName: args.appName,\n arguments: args.input,\n result: {\n content: args.raw.content,\n ...(args.raw.isError ? { isError: true } : {}),\n },\n },\n });\n } catch {\n // Defensive: the traffic-log sink is best-effort observability;\n // never let a logger failure bubble into the dispatch path.\n }\n}\n\nexport function useAppToolAttributionResolver(chatSessionId?: string) {\n const registrySnapshot = useAppToolsRegistry(\n useShallow((s) => ({\n activeBridgeByParent: s.activeBridgeByParent,\n aliases: s.aliases,\n instancesByBridgeId: s.instancesByBridgeId,\n })),\n );\n const resolve = useAppToolsRegistry((s) => s.resolve);\n const invocationRecords = useAppToolInvocationLog((s) => s.records);\n\n return useCallback(\n (label: string): AppToolAttribution | null => {\n if (!ALIAS_REGEX.test(label)) return null;\n\n const resolved = resolve(label, chatSessionId);\n if (resolved) {\n return {\n rawName: resolved.rawName,\n appName: resolved.instance.appName,\n };\n }\n\n for (let i = invocationRecords.length - 1; i >= 0; i -= 1) {\n const record = invocationRecords[i];\n if (record.alias === label) {\n return { rawName: record.rawName, appName: record.appName };\n }\n }\n\n return null;\n },\n [chatSessionId, invocationRecords, registrySnapshot, resolve],\n );\n}\n\nexport function useAppToolAttribution(\n label: string,\n chatSessionId?: string,\n): AppToolAttribution | null {\n const resolveAppToolAttribution =\n useAppToolAttributionResolver(chatSessionId);\n return resolveAppToolAttribution(label);\n}\n\n// Exports for tests.\nexport const __internal = { generateAlias, isReadOnly, ALIAS_REGEX };\n","/**\n * useToolInputStreaming – manages the streaming delivery of tool input to\n * an MCP App bridge.\n *\n * Extracted from mcp-apps-renderer.tsx so the streaming logic can be tested\n * in isolation and extended with debug tooling (e.g. a streaming slider)\n * without touching the renderer component.\n */\n\nimport {\n useRef,\n useState,\n useMemo,\n useCallback,\n useEffect,\n useLayoutEffect,\n} from \"react\";\nimport type { AppBridge } from \"@modelcontextprotocol/ext-apps/app-bridge\";\n// Re-exported from the WidgetHost contract module so this cluster file stays\n// free of `@/lib/client-styles` (Tier-B guard).\nimport type { ResolvedMcpAppsCapabilities } from \"./widget-host\";\n\n// ── Constants ────────────────────────────────────────────────────────────────\n\nexport const PARTIAL_INPUT_THROTTLE_MS = 120;\nexport const STREAMING_REVEAL_FALLBACK_MS = 700;\nexport const SIGNATURE_MAX_DEPTH = 4;\nexport const SIGNATURE_MAX_ARRAY_ITEMS = 24;\nexport const SIGNATURE_MAX_OBJECT_KEYS = 32;\nexport const SIGNATURE_STRING_EDGE_LENGTH = 24;\n\n// ── Types ────────────────────────────────────────────────────────────────────\n\nexport type ToolState =\n | \"input-streaming\"\n | \"input-available\"\n | \"approval-requested\"\n | \"output-available\"\n | \"output-denied\"\n | \"output-error\";\n\n// ── Signature helper ─────────────────────────────────────────────────────────\n\n/**\n * Produce a compact structural fingerprint of `input` so we can cheaply\n * detect whether a new streaming partial is meaningfully different from the\n * last one we sent to the bridge.\n */\nexport function getToolInputSignature(\n input: Record<string, unknown> | undefined,\n): string {\n if (!input) return \"\";\n const seen = new WeakSet<object>();\n\n const getValueSignature = (value: unknown, depth: number): string => {\n if (value == null) return \"null\";\n\n const valueType = typeof value;\n if (valueType === \"string\") {\n const text = value as string;\n const head = text.slice(0, SIGNATURE_STRING_EDGE_LENGTH);\n const tail = text.slice(-SIGNATURE_STRING_EDGE_LENGTH);\n return `str:${text.length}:${JSON.stringify(head)}:${JSON.stringify(tail)}`;\n }\n if (valueType === \"number\") {\n if (Number.isNaN(value)) return \"num:NaN\";\n if (value === Infinity) return \"num:Infinity\";\n if (value === -Infinity) return \"num:-Infinity\";\n if (Object.is(value, -0)) return \"num:-0\";\n return `num:${value as number}`;\n }\n if (valueType === \"boolean\") return `bool:${String(value)}`;\n if (valueType === \"bigint\") return `bigint:${String(value)}`;\n if (valueType === \"undefined\") return \"undefined\";\n if (valueType === \"function\") return \"function\";\n if (valueType === \"symbol\") return `symbol:${String(value)}`;\n\n if (depth >= SIGNATURE_MAX_DEPTH) {\n if (Array.isArray(value)) return `arr:max-depth:${value.length}`;\n return `obj:max-depth:${Object.keys(value as Record<string, unknown>).length}`;\n }\n\n if (Array.isArray(value)) {\n const length = value.length;\n if (length === 0) return \"arr:0\";\n\n const headCount = Math.min(length, SIGNATURE_MAX_ARRAY_ITEMS);\n const headSignatures: string[] = [];\n for (let index = 0; index < headCount; index += 1) {\n headSignatures.push(\n `${index}:${getValueSignature(value[index], depth + 1)}`,\n );\n }\n\n if (length <= SIGNATURE_MAX_ARRAY_ITEMS) {\n return `arr:${length}:[${headSignatures.join(\",\")}]`;\n }\n\n const tailStart = Math.max(headCount, length - 2);\n const tailSignatures: string[] = [];\n for (let index = tailStart; index < length; index += 1) {\n tailSignatures.push(\n `${index}:${getValueSignature(value[index], depth + 1)}`,\n );\n }\n\n return `arr:${length}:[${headSignatures.join(\",\")}]|tail:[${tailSignatures.join(\",\")}]`;\n }\n\n if (valueType === \"object\") {\n const record = value as Record<string, unknown>;\n if (seen.has(record)) return \"obj:circular\";\n seen.add(record);\n\n const keys = Object.keys(record).sort();\n const keyCount = Math.min(keys.length, SIGNATURE_MAX_OBJECT_KEYS);\n const entries: string[] = [];\n\n for (let index = 0; index < keyCount; index += 1) {\n const key = keys[index];\n entries.push(`${key}:${getValueSignature(record[key], depth + 1)}`);\n }\n\n if (keys.length > SIGNATURE_MAX_OBJECT_KEYS) {\n const omitted = keys.length - SIGNATURE_MAX_OBJECT_KEYS;\n const tailKeys = keys.slice(-2).join(\",\");\n entries.push(`omitted:${omitted}:tail-keys:${tailKeys}`);\n }\n\n seen.delete(record);\n return `obj:${keys.length}:{${entries.join(\"|\")}}`;\n }\n\n return `other:${valueType}`;\n };\n\n return getValueSignature(input, 0);\n}\n\n// ── Hook interface ───────────────────────────────────────────────────────────\n\nexport interface UseToolInputStreamingParams {\n bridgeRef: React.RefObject<AppBridge | null>;\n isReady: boolean;\n isReadyRef: React.RefObject<boolean>;\n toolState: ToolState | undefined;\n toolInput: Record<string, unknown> | undefined;\n toolOutput: unknown;\n toolErrorText: string | undefined;\n toolCallId: string;\n /**\n * Whether this View should receive the one-shot complete tool-input\n * notification for the current render. Resource-scoped persistent Views\n * keep the iframe alive across tool calls, but each new tool call still\n * gets a complete input notification before its result.\n */\n sendToolInput: boolean;\n onToolInputSent?: () => void;\n /** Incremented when the guest re-initializes (e.g. SDK app after openai-compat shim) */\n reinitCount: number;\n /**\n * Resolved SEP-1865 MCP Apps spec-bridge matrix. Gates the\n * notifications this hook emits to the View:\n * - `toolInputPartial: false` → suppress\n * `bridge.sendToolInputPartial` (Microsoft 365 Copilot does\n * not deliver this notification — widgets running under that\n * simulated surface must not see partials).\n * - `toolCancelled: false` → suppress `bridge.sendToolCancelled`\n * (Copilot does not deliver this either).\n *\n * Passed as a ref so the hook reads the latest resolved value\n * without rebuilding the effect closures on every host-style /\n * profile change. Null while the renderer is still resolving the\n * matrix (e.g. before host context is wired) — null reads as\n * \"default on\" so the inspector keeps emitting notifications by\n * default, matching the pre-matrix behavior for any host the\n * renderer hasn't classified yet.\n */\n mcpAppsCapabilitiesRef: React.RefObject<ResolvedMcpAppsCapabilities | null>;\n}\n\nexport interface UseToolInputStreamingReturn {\n canRenderStreamingInput: boolean;\n /** Called by LoggingTransport onReceive when a size-changed notification arrives. */\n signalStreamingRender: () => void;\n /** Called on CSP mode change (or externally) to clear all streaming state. */\n resetStreamingState: () => void;\n}\n\n// ── Hook ─────────────────────────────────────────────────────────────────────\n\nexport function useToolInputStreaming({\n bridgeRef,\n isReady,\n isReadyRef,\n toolState,\n toolInput,\n toolOutput,\n toolErrorText,\n toolCallId,\n sendToolInput,\n onToolInputSent,\n reinitCount,\n mcpAppsCapabilitiesRef,\n}: UseToolInputStreamingParams): UseToolInputStreamingReturn {\n // ── Internal refs ────────────────────────────────────────────────────────\n\n const lastToolInputRef = useRef<string | null>(null);\n const lastToolInputPartialRef = useRef<string | null>(null);\n const lastToolInputPartialSentAtRef = useRef(0);\n const pendingToolInputPartialRef = useRef<Record<string, unknown> | null>(\n null,\n );\n const partialInputTimerRef = useRef<number | null>(null);\n const streamingRevealTimerRef = useRef<number | null>(null);\n const lastToolOutputRef = useRef<string | null>(null);\n const lastToolErrorRef = useRef<string | null>(null);\n const toolInputSentRef = useRef(false);\n const previousToolStateRef = useRef<ToolState | undefined>(toolState);\n const previousToolCallIdRef = useRef(toolCallId);\n\n // ── Internal state ───────────────────────────────────────────────────────\n\n const [streamingRenderSignaled, setStreamingRenderSignaled] = useState(false);\n const [streamingRevealFallbackElapsed, setStreamingRevealFallbackElapsed] =\n useState(false);\n const [hasDeliveredStreamingInput, setHasDeliveredStreamingInput] =\n useState(false);\n\n // ── Derived values ───────────────────────────────────────────────────────\n\n const hasToolInputData = useMemo(\n () => !!toolInput && Object.keys(toolInput).length > 0,\n [toolInput],\n );\n\n const canRenderStreamingInput = useMemo(() => {\n if (toolState !== \"input-streaming\") return true;\n if (!sendToolInput) return true;\n // Prefer revealing after the first delivered partial, but do not keep the\n // iframe hidden forever when a provider streams no parseable partial args.\n return (\n streamingRevealFallbackElapsed ||\n (streamingRenderSignaled && hasDeliveredStreamingInput)\n );\n }, [\n hasDeliveredStreamingInput,\n sendToolInput,\n streamingRevealFallbackElapsed,\n streamingRenderSignaled,\n toolState,\n ]);\n\n // ── Callbacks ────────────────────────────────────────────────────────────\n\n const resetStreamingState = useCallback(() => {\n lastToolInputRef.current = null;\n lastToolInputPartialRef.current = null;\n lastToolInputPartialSentAtRef.current = 0;\n pendingToolInputPartialRef.current = null;\n if (partialInputTimerRef.current !== null) {\n window.clearTimeout(partialInputTimerRef.current);\n partialInputTimerRef.current = null;\n }\n if (streamingRevealTimerRef.current !== null) {\n window.clearTimeout(streamingRevealTimerRef.current);\n streamingRevealTimerRef.current = null;\n }\n lastToolOutputRef.current = null;\n lastToolErrorRef.current = null;\n toolInputSentRef.current = false;\n setStreamingRenderSignaled(false);\n setStreamingRevealFallbackElapsed(false);\n setHasDeliveredStreamingInput(false);\n }, []);\n\n const signalStreamingRender = useCallback(() => {\n setStreamingRenderSignaled(true);\n }, []);\n\n // ── Effects ──────────────────────────────────────────────────────────────\n\n // 0. Reset dedup refs on guest re-initialization (e.g. SDK app init after\n // openai-compat shim already completed the handshake). This must run\n // before the delivery effects so they see the cleared refs and re-send.\n useEffect(() => {\n if (reinitCount === 0) return; // skip initial mount\n lastToolInputRef.current = null;\n lastToolInputPartialRef.current = null;\n lastToolOutputRef.current = null;\n lastToolErrorRef.current = null;\n toolInputSentRef.current = false;\n }, [reinitCount]);\n\n // 1. Clear reveal timer once the iframe is allowed to become visible. A\n // render signal alone can come from size-changed before any parseable streamed\n // args arrive, so keep the fallback alive for that case.\n useEffect(() => {\n if (!hasDeliveredStreamingInput && !streamingRevealFallbackElapsed) return;\n if (streamingRevealTimerRef.current !== null) {\n window.clearTimeout(streamingRevealTimerRef.current);\n streamingRevealTimerRef.current = null;\n }\n }, [hasDeliveredStreamingInput, streamingRevealFallbackElapsed]);\n\n // 2. Fallback reveal timer\n useEffect(() => {\n if (!sendToolInput) return;\n if (\n !isReady ||\n toolState !== \"input-streaming\" ||\n hasDeliveredStreamingInput ||\n streamingRevealFallbackElapsed\n )\n return;\n if (streamingRevealTimerRef.current !== null) return;\n\n streamingRevealTimerRef.current = window.setTimeout(() => {\n streamingRevealTimerRef.current = null;\n setStreamingRenderSignaled(true);\n setStreamingRevealFallbackElapsed(true);\n }, STREAMING_REVEAL_FALLBACK_MS);\n }, [\n hasDeliveredStreamingInput,\n isReady,\n sendToolInput,\n streamingRevealFallbackElapsed,\n toolState,\n ]);\n\n // 3. Re-entry detection\n useEffect(() => {\n const prevToolState = previousToolStateRef.current;\n\n // Some providers may re-enter input-streaming for a new call while reusing\n // the same toolCallId. Reset send guards so we can stream/send fresh input.\n if (\n toolState === \"input-streaming\" &&\n prevToolState &&\n prevToolState !== \"input-streaming\"\n ) {\n resetStreamingState();\n }\n\n previousToolStateRef.current = toolState;\n }, [resetStreamingState, toolState]);\n\n // 4. Partial input throttled delivery\n useEffect(() => {\n if (\n !sendToolInput ||\n !isReady ||\n toolState !== \"input-streaming\" ||\n toolInputSentRef.current\n )\n return;\n if (!hasToolInputData) return;\n const resolvedToolInput = toolInput ?? {};\n pendingToolInputPartialRef.current = resolvedToolInput;\n\n const flushPartialInput = () => {\n const bridge = bridgeRef.current;\n if (!bridge || !isReadyRef.current || toolInputSentRef.current) return;\n const pending = pendingToolInputPartialRef.current;\n if (!pending) return;\n\n const signature = getToolInputSignature(pending);\n if (lastToolInputPartialRef.current === signature) return;\n lastToolInputPartialRef.current = signature;\n lastToolInputPartialSentAtRef.current = Date.now();\n setHasDeliveredStreamingInput(true);\n setStreamingRenderSignaled(true);\n // Matrix gate: SEP-1865 hosts that don't deliver\n // `ui/notifications/tool-input-partial` (notably Microsoft 365\n // Copilot per its published Component-bridge table) flip this\n // dimension off in the matrix. Null ref → default on (matches\n // pre-matrix behavior for any host the renderer hasn't\n // classified yet). The streaming signature / streaming-render\n // gating above still fires regardless so the inspector's\n // internal streaming UX (which mirrors the bridge\n // notification cadence) doesn't go silent on Copilot-style\n // hosts — it's only the wire emission that's suppressed.\n const matrix = mcpAppsCapabilitiesRef.current;\n if (matrix !== null && matrix.toolInputPartial === false) return;\n Promise.resolve(\n bridge.sendToolInputPartial({ arguments: pending }),\n ).catch(() => {});\n };\n\n const now = Date.now();\n const elapsed = now - lastToolInputPartialSentAtRef.current;\n if (\n lastToolInputPartialSentAtRef.current === 0 ||\n elapsed >= PARTIAL_INPUT_THROTTLE_MS\n ) {\n if (partialInputTimerRef.current !== null) {\n window.clearTimeout(partialInputTimerRef.current);\n partialInputTimerRef.current = null;\n }\n flushPartialInput();\n return;\n }\n\n if (partialInputTimerRef.current !== null) {\n window.clearTimeout(partialInputTimerRef.current);\n }\n partialInputTimerRef.current = window.setTimeout(() => {\n partialInputTimerRef.current = null;\n flushPartialInput();\n }, PARTIAL_INPUT_THROTTLE_MS - elapsed);\n }, [\n hasToolInputData,\n isReady,\n sendToolInput,\n toolCallId,\n toolInput,\n toolState,\n bridgeRef,\n isReadyRef,\n ]);\n\n // 5. Complete input delivery\n useEffect(() => {\n if (!isReady) return;\n if (toolState !== \"input-available\" && toolState !== \"output-available\")\n return;\n if (partialInputTimerRef.current !== null) {\n window.clearTimeout(partialInputTimerRef.current);\n partialInputTimerRef.current = null;\n }\n if (streamingRevealTimerRef.current !== null) {\n window.clearTimeout(streamingRevealTimerRef.current);\n streamingRevealTimerRef.current = null;\n }\n pendingToolInputPartialRef.current = null;\n if (!sendToolInput) return;\n const bridge = bridgeRef.current;\n if (!bridge) return;\n\n const resolvedToolInput = toolInput ?? {};\n const serialized = JSON.stringify(resolvedToolInput);\n // Allow live editors/previews to update tool input repeatedly while keeping\n // duplicate sends suppressed for identical payloads.\n if (lastToolInputRef.current === serialized) {\n toolInputSentRef.current = true;\n return;\n }\n lastToolInputRef.current = serialized;\n toolInputSentRef.current = true;\n onToolInputSent?.();\n Promise.resolve(\n bridge.sendToolInput({ arguments: resolvedToolInput }),\n ).catch(() => {\n toolInputSentRef.current = false;\n lastToolInputRef.current = null;\n });\n }, [\n isReady,\n toolCallId,\n toolInput,\n toolState,\n bridgeRef,\n reinitCount,\n sendToolInput,\n onToolInputSent,\n ]);\n\n // 6. Tool result delivery\n useEffect(() => {\n if (!isReady || toolState !== \"output-available\") return;\n const bridge = bridgeRef.current;\n if (!bridge || !toolOutput) return;\n\n const serialized = JSON.stringify(toolOutput);\n const outputKey = `${toolCallId}:${serialized}`;\n if (lastToolOutputRef.current === outputKey) return;\n lastToolOutputRef.current = outputKey;\n // Apps-compat seam (§1D): cast to the bridge's own CallToolResult\n // (ext-apps v1-sdk peer) rather than the v2 client's nominal type.\n bridge.sendToolResult(\n toolOutput as Parameters<typeof bridge.sendToolResult>[0],\n );\n }, [isReady, toolCallId, toolOutput, toolState, bridgeRef, reinitCount]);\n\n // 7. Tool error/cancellation delivery\n useEffect(() => {\n if (!isReady || toolState !== \"output-error\") return;\n const bridge = bridgeRef.current;\n if (!bridge) return;\n\n const errorMessage =\n toolErrorText ??\n (toolOutput instanceof Error\n ? toolOutput.message\n : typeof toolOutput === \"string\"\n ? toolOutput\n : \"Tool execution failed\");\n\n const errorKey = `${toolCallId}:${errorMessage}`;\n if (lastToolErrorRef.current === errorKey) return;\n lastToolErrorRef.current = errorKey;\n\n // SEP-1865: Send tool-cancelled for errors instead of tool-result\n // with isError. Matrix gate: Microsoft 365 Copilot does not\n // deliver this notification per its published Component-bridge\n // table; widgets running under that simulated surface must not\n // see a cancelled callback. Null matrix ref → default on (same\n // fail-open contract as the partial-input gate above).\n const matrix = mcpAppsCapabilitiesRef.current;\n if (matrix !== null && matrix.toolCancelled === false) return;\n bridge.sendToolCancelled({ reason: errorMessage });\n }, [\n isReady,\n toolCallId,\n toolErrorText,\n toolOutput,\n toolState,\n bridgeRef,\n reinitCount,\n mcpAppsCapabilitiesRef,\n ]);\n\n // 8. Reset on toolCallId change. Do this before paint so a recycled renderer\n // cannot briefly expose the previous call's delivery guards.\n useLayoutEffect(() => {\n if (previousToolCallIdRef.current === toolCallId) return;\n previousToolCallIdRef.current = toolCallId;\n resetStreamingState();\n }, [toolCallId, resetStreamingState]);\n\n // 9. Cleanup on unmount\n useEffect(() => {\n return () => resetStreamingState();\n }, [resetStreamingState]);\n\n return {\n canRenderStreamingInput,\n signalStreamingRender,\n resetStreamingState,\n };\n}\n","/**\n * SandboxedIframe - DRY Double-Iframe Sandbox Component\n *\n * Provides a secure double-iframe architecture for rendering untrusted HTML:\n * Host Page → Sandbox Proxy (different origin) → Guest UI\n *\n * The sandbox proxy:\n * 1. Runs in a different origin for security isolation\n * 2. Loads guest HTML via srcdoc when ready\n * 3. Forwards messages between host and guest (except sandbox-internal)\n *\n * Per SEP-1865, this component is designed to be reusable for MCP Apps\n * and potentially future OpenAI SDK consolidation.\n */\n\nimport {\n stableStringifyJson,\n buildOuterAllowAttribute,\n buildOuterSandboxAttribute,\n} from \"@mcpjam/sdk/widget-runtime\";\nimport {\n useRef,\n useState,\n useEffect,\n useCallback,\n useImperativeHandle,\n forwardRef,\n useMemo,\n} from \"react\";\nimport type {\n McpUiResourceCsp,\n McpUiResourcePermissions,\n} from \"@modelcontextprotocol/ext-apps/app-bridge\";\n\nfunction isRecorderDebugEnabled() {\n try {\n return (\n typeof window !== \"undefined\" &&\n window.localStorage?.getItem(\"mcpjam:recorder-debug\") === \"1\"\n );\n } catch {\n return false;\n }\n}\n\nfunction recorderDebug(message: string, details?: Record<string, unknown>) {\n try {\n if (isRecorderDebugEnabled()) {\n console.info(`[recorder:sandboxed-iframe] ${message}`, details ?? {});\n }\n } catch {\n // best-effort debug logging only\n }\n}\n\nexport interface SandboxedIframeHandle {\n postMessage: (data: unknown) => void;\n getIframeElement: () => HTMLIFrameElement | null;\n}\n\ninterface SandboxedIframeProps {\n /** HTML content to render in the sandbox */\n html: string | null;\n /** Sandbox attribute for the inner iframe */\n sandbox?: string;\n /** CSP metadata from resource _meta.ui.csp (SEP-1865) */\n csp?: McpUiResourceCsp;\n /** Permissions metadata from resource _meta.ui.permissions (SEP-1865) */\n permissions?: McpUiResourcePermissions;\n /**\n * Inspector-only: extra `sandbox=` tokens unioned with the spec-mandated\n * `allow-scripts allow-same-origin` on both outer and inner iframes.\n * Models tokens real hosts emit (e.g. `allow-forms`) that aren't part of\n * SEP-1865 metadata.\n */\n sandboxAttrs?: string[];\n /**\n * Inspector-only: extra Permissions Policy entries appended to outer/inner\n * iframe `allow=`. Keys are kebab Permissions Policy tokens\n * (`fullscreen`, `web-share`); the 4 spec features\n * (camera/microphone/geolocation/clipboard-write) live in `permissions`\n * and are NOT permitted here.\n */\n allowFeatures?: Record<string, string>;\n /**\n * Inspector-only: per-directive CSP source-expression overrides merged\n * into the inner doc's `<meta http-equiv=\"Content-Security-Policy\">`.\n * Keys are CSP directive names (`script-src`, …); values are token arrays\n * (`[\"'unsafe-eval'\", \"'wasm-unsafe-eval'\"]`).\n */\n cspDirectives?: Record<string, string[]>;\n /** Skip CSP injection entirely (for permissive/testing mode) */\n permissive?: boolean;\n /**\n * Tier 2 recorder: when true, the proxy injects a recorder shim into the\n * guest that posts `recorder:step` / `recorder:ready` messages (forwarded via\n * `onMessage`). Default off — only the eval authoring preview sets it.\n */\n recordMode?: boolean;\n /** Callback when sandbox proxy is ready */\n onProxyReady?: () => void;\n /** Callback for messages from guest UI (excluding sandbox-internal messages) */\n onMessage: (event: MessageEvent) => void;\n /** CSS class for the outer iframe */\n className?: string;\n /** Inline styles for the outer iframe */\n style?: React.CSSProperties;\n /** Host color scheme used to keep transparent iframe canvas rendering aligned */\n colorScheme?: \"light\" | \"dark\";\n /** Title for accessibility */\n title?: string;\n /**\n * Whether the app runs against the hosted backend (the inspector's\n * `HOSTED_MODE`). Selects the hosted vs. local sandbox-proxy path and the\n * same-origin security warning. Supplied by the host (`host.surface.hostedMode`)\n * so this component carries no inspector config import.\n */\n hostedMode?: boolean;\n /**\n * Operator-configured sandbox origin (the inspector's `SANDBOX_ORIGIN` /\n * `VITE_MCPJAM_SANDBOX_ORIGIN`); \"\" when unset. Used in hosted mode to load\n * the sandbox proxy from a distinct origin. Supplied by the host\n * (`host.surface.sandboxOrigin`).\n */\n sandboxOrigin?: string;\n}\n\n/**\n * SandboxedIframe provides a secure double-iframe architecture per SEP-1865.\n *\n * Message flow:\n * 1. Proxy sends ui/notifications/sandbox-proxy-ready when loaded\n * 2. Host sends ui/notifications/sandbox-resource-ready with HTML\n * 3. Guest UI initializes and communicates via JSON-RPC 2.0\n */\nexport const SandboxedIframe = forwardRef<\n SandboxedIframeHandle,\n SandboxedIframeProps\n>(function SandboxedIframe(\n {\n html,\n sandbox = \"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox\",\n csp,\n permissions,\n sandboxAttrs,\n allowFeatures,\n cspDirectives,\n permissive,\n recordMode,\n onProxyReady,\n onMessage,\n className,\n style,\n colorScheme,\n title = \"Sandboxed Content\",\n hostedMode = false,\n sandboxOrigin = \"\",\n },\n ref\n) {\n const outerRef = useRef<HTMLIFrameElement>(null);\n const [proxyReady, setProxyReady] = useState(false);\n const lastResourceReadyKeyRef = useRef<string | null>(null);\n const onMessageRef = useRef(onMessage);\n const onProxyReadyRef = useRef(onProxyReady);\n onMessageRef.current = onMessage;\n onProxyReadyRef.current = onProxyReady;\n\n // SEP-1865: Host and Sandbox MUST have different origins.\n //\n // Hosted: prefer the operator-configured SANDBOX_ORIGIN\n // (`VITE_MCPJAM_SANDBOX_ORIGIN`). It MUST be a distinct origin from the\n // host app so the sandboxed iframe cannot reach host cookies or storage\n // even when its sandbox carries `allow-same-origin`.\n //\n // Local: keep the localhost ↔ 127.0.0.1 swap so dev gets the same\n // origin-separation property without operator config.\n //\n // Same-origin fallback exists only as a soft-fail for misconfigured\n // hosted deploys; it emits a loud security warning.\n const [sandboxProxyUrl] = useState(() => {\n const proxyPath = hostedMode\n ? \"/api/web/apps/mcp-apps/sandbox-proxy\"\n : \"/api/apps/mcp-apps/sandbox-proxy\";\n\n if (hostedMode && sandboxOrigin) {\n return `${sandboxOrigin}${proxyPath}?v=${Date.now()}`;\n }\n\n const currentHost = window.location.hostname;\n const currentPort = window.location.port;\n const protocol = window.location.protocol;\n\n let sandboxHost: string;\n if (currentHost === \"localhost\") {\n sandboxHost = \"127.0.0.1\";\n } else if (currentHost === \"127.0.0.1\") {\n sandboxHost = \"localhost\";\n } else {\n if (hostedMode) {\n console.warn(\n \"[SandboxedIframe] VITE_MCPJAM_SANDBOX_ORIGIN is not configured;\" +\n \" sandbox iframe is falling back to same-origin.\" +\n \" This is a security regression — the sandbox shares cookies and\" +\n \" storage with the host app. Configure a distinct origin\" +\n \" (e.g. https://sandbox.mcpjam.com) and redeploy.\"\n );\n } else {\n console.warn(\n \"[SandboxedIframe] Cross-origin isolation not available for hostname:\",\n currentHost,\n \"- falling back to same-origin sandbox\"\n );\n }\n sandboxHost = currentHost;\n }\n\n const portSuffix = currentPort ? `:${currentPort}` : \"\";\n return `${protocol}//${sandboxHost}${portSuffix}${proxyPath}?v=${Date.now()}`;\n });\n\n const sandboxProxyOrigin = useMemo(() => {\n try {\n return new URL(sandboxProxyUrl).origin;\n } catch {\n return \"*\";\n }\n }, [sandboxProxyUrl]);\n\n useImperativeHandle(\n ref,\n () => ({\n postMessage: (data: unknown) => {\n outerRef.current?.contentWindow?.postMessage(data, sandboxProxyOrigin);\n },\n getIframeElement: () => outerRef.current,\n }),\n [sandboxProxyOrigin]\n );\n\n const handleMessage = useCallback(\n (event: MessageEvent) => {\n if (event.origin !== sandboxProxyOrigin && sandboxProxyOrigin !== \"*\") {\n return;\n }\n if (event.source !== outerRef.current?.contentWindow) return;\n\n // CSP violation messages (not JSON-RPC) - forward directly\n if (event.data?.type === \"mcp-apps:csp-violation\") {\n onMessageRef.current(event);\n return;\n }\n\n // Whitelisted OpenAI compat messages (not JSON-RPC) - forward directly\n if (\n event.data?.type === \"openai:uploadFile\" ||\n event.data?.type === \"openai:getFileDownloadUrl\" ||\n event.data?.type === \"openai:setWidgetState\" ||\n event.data?.type === \"openai:setOpenInAppUrl\"\n ) {\n onMessageRef.current(event);\n return;\n }\n\n // Tier 2 recorder messages (not JSON-RPC) — forward to the host so the\n // eval authoring preview can capture recorded steps / detect readiness,\n // and receive per-step results from a host-driven replay.\n if (\n event.data?.type === \"recorder:step\" ||\n event.data?.type === \"recorder:ready\" ||\n event.data?.type === \"recorder:replay-result\"\n ) {\n recorderDebug(`forward ${event.data.type}`);\n onMessageRef.current(event);\n return;\n }\n\n const { jsonrpc, method } =\n (event.data as { jsonrpc?: string; method?: string }) || {};\n if (jsonrpc !== \"2.0\") return;\n\n if (method === \"ui/notifications/sandbox-proxy-ready\") {\n setProxyReady(true);\n onProxyReadyRef.current?.();\n return;\n }\n\n if (method?.startsWith(\"ui/notifications/sandbox-\")) {\n return;\n }\n\n onMessageRef.current(event);\n },\n [sandboxProxyOrigin]\n );\n\n useEffect(() => {\n window.addEventListener(\"message\", handleMessage);\n return () => window.removeEventListener(\"message\", handleMessage);\n }, [handleMessage]);\n\n // Build allow attribute for outer iframe based on requested permissions.\n //\n // Same authoritative-profile semantic as `sandboxAttrs` above: when\n // `allowFeatures` is provided (even as `{}`), the profile is the\n // source of truth for non-spec Permissions Policy features, and the\n // renderer's legacy defaults (`local-network-access *`, `midi *`) are\n // dropped. A profile that doesn't list those features models a real\n // host that doesn't emit them — and the iframe must match, or\n // experiments using Web MIDI / Local Network Access would pass in\n // MCPJam while the real host blocks them.\n //\n // The 4 SEP-1865 spec permissions (camera/microphone/geolocation/\n // clipboard-write) ALWAYS flow through from `permissions` regardless\n // of `allowFeatures` — they're orthogonal user-facing knobs. Only the\n // inspector-only legacy defaults are conditional.\n //\n // Per Permissions Policy spec, `;` separates features.\n const outerAllowAttribute = useMemo(\n () => buildOuterAllowAttribute({ permissions, allowFeatures }),\n [permissions, allowFeatures]\n );\n\n // Outer iframe `sandbox=` value.\n //\n // When `sandboxAttrs` is provided (even as `[]`), the profile is the\n // authoritative source: the iframe gets `allow-scripts allow-same-origin`\n // plus exactly what the profile lists. This is what makes \"model the\n // real host's emitted tokens\" actually work — e.g. a Claude-modeled\n // profile with `sandboxAttrs: [\"allow-forms\"]` gets exactly those three\n // tokens, not those PLUS the renderer's legacy permissive default.\n //\n // When `sandboxAttrs` is undefined (no profile opinion), fall back to\n // the caller's `sandbox` prop so existing call sites — which pass a\n // wider permissive baseline — behave unchanged.\n //\n // `undefined` vs `[]` matters here: `[]` is the explicit \"spec-minimum\n // only\" intent, mirroring the canonicalizer's preservation contract.\n const outerSandboxAttribute = useMemo(\n () => buildOuterSandboxAttribute({ sandbox, sandboxAttrs }),\n [sandbox, sandboxAttrs]\n );\n\n const resourceReadyKey = useMemo(\n () =>\n stableStringifyJson({\n csp: csp ?? null,\n cspDirectives: cspDirectives ?? null,\n html: html ?? null,\n permissive: permissive ?? null,\n permissions: permissions ?? null,\n sandbox,\n sandboxAttrs: sandboxAttrs ?? null,\n // Include recordMode so record-capable surfaces receive the recorder\n // shim, and stale/non-recordable surfaces reload without it.\n recordMode: recordMode ?? null,\n }),\n [\n csp,\n cspDirectives,\n html,\n permissive,\n permissions,\n sandbox,\n sandboxAttrs,\n recordMode,\n ]\n );\n\n useEffect(() => {\n if (!proxyReady) lastResourceReadyKeyRef.current = null;\n }, [proxyReady]);\n\n // Send HTML, CSP, and permissions to sandbox when ready (SEP-1865)\n useEffect(() => {\n if (!proxyReady || !html) return;\n const resourceTargetKey = `${sandboxProxyOrigin}\\0${resourceReadyKey}`;\n if (lastResourceReadyKeyRef.current === resourceTargetKey) return;\n lastResourceReadyKeyRef.current = resourceTargetKey;\n\n outerRef.current?.contentWindow?.postMessage(\n {\n jsonrpc: \"2.0\",\n method: \"ui/notifications/sandbox-resource-ready\",\n params: {\n html,\n sandbox,\n csp,\n permissions,\n sandboxAttrs,\n // `allowFeatures` is intentionally NOT forwarded to the proxy:\n // it applies to the OUTER iframe only. The inner iframe gets the\n // 4 spec permissions (via `permissions`) and nothing else, matching\n // real claude.ai's outer-grants-fullscreen / inner-trims-to-spec\n // pattern. Centralizing the outer/inner split here means the proxy\n // can't accidentally widen the inner grant by reading a stale\n // field.\n cspDirectives,\n permissive,\n colorScheme,\n recordMode,\n recorderDebug: isRecorderDebugEnabled(),\n },\n },\n sandboxProxyOrigin\n );\n recorderDebug(\"sent resource ready\", {\n recordMode: !!recordMode,\n recorderDebug: isRecorderDebugEnabled(),\n proxyReady,\n hasHtml: !!html,\n sandboxProxyOrigin,\n });\n // This effect intentionally depends on the semantic payload key instead\n // of raw object props. Re-sending `sandbox-resource-ready` makes the\n // proxy assign inner `srcdoc` again, which restarts the app even when the\n // HTML/CSP/permission payload is unchanged.\n // `colorScheme` and `allowFeatures` are intentionally OMITTED from\n // this dep list. The proxy handles `sandbox-resource-ready` by\n // rebuilding the CSP and assigning `inner.srcdoc`, which reloads the\n // widget and drops any in-iframe state — so we MUST NOT re-fire this\n // effect for props that don't actually affect the inner iframe.\n //\n // - `colorScheme`: flows through the dedicated\n // `sandbox-color-scheme-changed` effect below, which updates the\n // inner document's color-scheme without a reload.\n // - `allowFeatures`: applies only to the OUTER iframe's `allow=`\n // attribute (computed in `outerAllowAttribute` above and applied\n // declaratively via JSX, so React reconciliation handles the\n // update without a reload). It's not forwarded in the params\n // payload at all (see the comment above the field). Re-including\n // it here would silently full-reload the widget every time a\n // user toggles an entry in the AppExtensionTab editor.\n }, [proxyReady, html, resourceReadyKey, sandboxProxyOrigin]);\n\n // Keep iframe color-scheme in sync without reloading the widget document.\n useEffect(() => {\n if (!proxyReady || !colorScheme) return;\n\n outerRef.current?.contentWindow?.postMessage(\n {\n jsonrpc: \"2.0\",\n method: \"ui/notifications/sandbox-color-scheme-changed\",\n params: { colorScheme },\n },\n sandboxProxyOrigin\n );\n }, [proxyReady, colorScheme, sandboxProxyOrigin]);\n\n const iframeStyle = colorScheme ? { ...style, colorScheme } : style;\n\n // Browsers apply iframe `sandbox=` only on navigation, not when the\n // attribute mutates on an already-loaded frame. If the user edits a\n // profile from permissive tokens to `[]` while the widget is mounted,\n // React updates the attribute but the live iframe keeps the OLD\n // grants until something forces a navigation — so the matrix/editor\n // can show stricter modeling while the running widget still has\n // popups/forms/etc. enabled. Key the outer iframe on\n // outerSandboxAttribute so React unmounts + remounts (= fresh\n // navigation) whenever the effective sandbox flags change. Resetting\n // proxyReady below ensures the resource-ready effect re-fires after\n // the new proxy load completes (otherwise proxyReady would stay\n // `true` from the prior iframe and the widget wouldn't get re-sent\n // to the new proxy).\n useEffect(() => {\n setProxyReady(false);\n }, [outerSandboxAttribute]);\n\n return (\n <iframe\n key={outerSandboxAttribute}\n ref={outerRef}\n src={sandboxProxyUrl}\n sandbox={outerSandboxAttribute}\n allow={outerAllowAttribute}\n title={title}\n className={className}\n style={iframeStyle}\n />\n );\n});\n","import { useRef, useState, useEffect } from \"react\";\nimport { SandboxedIframe, SandboxedIframeHandle } from \"./sandboxed-iframe\";\nimport {\n AppBridge,\n PostMessageTransport,\n type McpUiHostCapabilities,\n type McpUiHostContext,\n type McpUiResourceCsp,\n type McpUiResourcePermissions,\n} from \"@modelcontextprotocol/ext-apps/app-bridge\";\n// Pure JSON-RPC parser + logging transport are shared, framework-free runtime\n// helpers in the SDK.\nimport { extractMethod, LoggingTransport } from \"@mcpjam/sdk/widget-runtime\";\n// The `CspMode` type comes from the package's `WidgetHost` contract.\nimport { type CspMode } from \"./widget-host\";\n// The package owns lifecycle + bridge; the inspector injects modal CHROME\n// (its design-system <Dialog>) + the widget-content fetch via the WidgetHost.\nimport { useWidgetHost } from \"./widget-host-context\";\nimport { useAppToolsRegistry } from \"./app-tools-registry\";\n\nexport interface McpAppsModalProps {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n title: string;\n template: string | null;\n params: Record<string, unknown>;\n registerBridgeHandlers: (bridge: AppBridge) => void;\n /**\n * SEP-1865 App-Provided Tools: the modal mounts its own AppBridge\n * against a fresh iframe. Because the modal overrides\n * `bridge.oninitialized` to suppress inline-only side effects, the\n * inline registration path (which lives inside that handler) is\n * skipped. The modal calls this helper directly after handshake — and\n * again on every `notifications/tools/list_changed` — so the model\n * sees the app's tools while the modal is the active surface for this\n * tool call. Inline + modal coexist in `useAppToolsRegistry` via\n * `surface`-keyed dedup; the registry's active-bridge fallback\n * restores inline when the modal unregisters on teardown.\n */\n refreshAppProvidedTools: (\n bridge: AppBridge,\n bridgeId: string,\n options?: {\n force?: boolean;\n surface?: \"inline\" | \"modal\";\n getIframeElement?: () => HTMLIFrameElement | null;\n isLive?: () => boolean;\n }\n ) => Promise<void>;\n widgetCsp: McpUiResourceCsp | undefined;\n widgetPermissions: McpUiResourcePermissions | undefined;\n widgetPermissive: boolean;\n widgetSandboxAttrs: string[] | undefined;\n widgetAllowFeatures: Record<string, string> | undefined;\n widgetCspDirectives: Record<string, string[]> | undefined;\n hostContextRef: React.RefObject<McpUiHostContext | null>;\n serverId: string;\n resourceUri: string;\n toolCallId: string;\n toolName: string;\n cspMode: CspMode;\n /**\n * Resolved compat-runtime flag the inline renderer already computed\n * for this host. The modal mounts its own iframe and fetches its own\n * HTML; passing the flag down (rather than re-resolving here) keeps\n * the modal and inline fetches in lockstep so the modal can't end up\n * shimmed while the inline view isn't (or vice versa).\n */\n injectOpenAiCompat: boolean;\n /**\n * Resolved MCP Apps `HostCapabilities` blob the inline renderer\n * already computed via `resolveEffectiveHostCapabilities`. Pass-down\n * mirrors {@link injectOpenAiCompat}: the modal mounts its own\n * AppBridge and we want inline + modal to advertise an identical\n * surface to the widget. Previously the modal hardcoded `{ openLinks,\n * serverTools, serverResources, logging, updateModelContext, message }`\n * — that masked Copilot's M365-published subset (which strips\n * `serverResources` / `logging`) and any user override in\n * `mcpProfile.apps.mcpAppsOverrides`. The `sandbox` slice is composed\n * separately at AppBridge construction from the widget-level CSP /\n * permissions props.\n */\n effectiveHostCapabilities: Omit<McpUiHostCapabilities, \"sandbox\">;\n /**\n * Resolved AppBridge `hostInfo` the inline renderer already computed\n * (`resolvers.resolveHostInfo(activeMcpProfile)` with the inspector\n * fallback). Passed down rather than re-resolved here so the modal and\n * inline bridges hand the widget an identical `hostInfo`, and so the modal\n * holds no inspector-app-state coupling (`useActiveMcpProfile` /\n * `resolveHostInfo` now live only in the renderer's `useWidgetHost()`).\n */\n hostInfo: { name: string; version: string };\n /**\n * Whether the active surface routes through web-managed (hosted) servers.\n * Sourced from the renderer's `host.surface.webManagedServers` so the modal's\n * widget-content fetch hits the same endpoint as the inline view.\n */\n webManagedServers: boolean;\n toolInputRef: React.RefObject<Record<string, unknown> | undefined>;\n toolOutputRef: React.RefObject<unknown>;\n themeModeRef: React.RefObject<string>;\n addUiLog: (log: {\n widgetId: string;\n serverId: string;\n direction: \"host-to-ui\" | \"ui-to-host\";\n protocol: string;\n method: string;\n message: unknown;\n }) => void;\n onCspViolation: (event: MessageEvent) => void;\n}\n\nexport function McpAppsModal({\n open,\n onOpenChange,\n title,\n template,\n params,\n registerBridgeHandlers,\n refreshAppProvidedTools,\n widgetCsp,\n widgetPermissions,\n widgetPermissive,\n widgetSandboxAttrs,\n widgetAllowFeatures,\n widgetCspDirectives,\n hostContextRef,\n serverId,\n resourceUri,\n toolCallId,\n toolName,\n cspMode,\n injectOpenAiCompat,\n effectiveHostCapabilities,\n hostInfo,\n webManagedServers,\n toolInputRef,\n toolOutputRef,\n themeModeRef,\n addUiLog,\n onCspViolation,\n}: McpAppsModalProps) {\n const host = useWidgetHost();\n const Modal = host.components?.Modal;\n const [modalHtml, setModalHtml] = useState<string | null>(null);\n const modalSandboxRef = useRef<SandboxedIframeHandle>(null);\n const modalBridgeRef = useRef<AppBridge | null>(null);\n // SEP-1865 App-Provided Tools: per-modal-bridge identity. Distinct\n // from the renderer's inline ref so inline + modal can coexist in\n // `useAppToolsRegistry` and `surface`-keyed dedup keeps each surface's\n // tools separate. Cleared on teardown so `isLive` short-circuits any\n // in-flight `listTools` after the modal closes.\n const modalAppToolsBridgeIdRef = useRef<string | null>(null);\n const modalColorScheme =\n hostContextRef.current?.theme === \"light\" ||\n hostContextRef.current?.theme === \"dark\"\n ? hostContextRef.current.theme\n : themeModeRef.current === \"light\" || themeModeRef.current === \"dark\"\n ? themeModeRef.current\n : undefined;\n\n // Fetch modal HTML when modal opens\n useEffect(() => {\n if (!open) {\n // Clean up when modal closes\n modalBridgeRef.current?.close().catch(() => {});\n modalBridgeRef.current = null;\n // SEP-1865 App-Provided Tools: drop this modal's registration so\n // the next chat POST snapshot omits its aliases and the registry's\n // active-bridge fallback restores any coexisting inline surface.\n if (modalAppToolsBridgeIdRef.current) {\n useAppToolsRegistry\n .getState()\n .unregisterInstance(modalAppToolsBridgeIdRef.current);\n modalAppToolsBridgeIdRef.current = null;\n }\n setModalHtml(null);\n return;\n }\n\n const fetchModalHtml = async () => {\n try {\n const { html } = await host.services.fetchWidgetContent({\n serverId,\n forceWebEndpoint: webManagedServers,\n resourceUri,\n toolInput: toolInputRef.current,\n toolOutput: toolOutputRef.current,\n toolId: toolCallId,\n toolName,\n theme: themeModeRef.current,\n cspMode,\n injectOpenAiCompat,\n template: template ?? undefined,\n viewMode: \"modal\",\n viewParams: params,\n });\n setModalHtml(html);\n } catch (err) {\n console.error(\"[MCP Apps] Failed to fetch modal HTML\", err);\n }\n };\n\n fetchModalHtml();\n }, [\n open,\n template,\n params,\n serverId,\n resourceUri,\n toolCallId,\n toolName,\n cspMode,\n injectOpenAiCompat,\n webManagedServers,\n toolInputRef,\n toolOutputRef,\n themeModeRef,\n ]);\n\n // Initialize modal bridge when modal HTML is ready\n useEffect(() => {\n if (!modalHtml || !open) return;\n const iframe = modalSandboxRef.current?.getIframeElement();\n if (!iframe?.contentWindow) return;\n\n // Vendor-trait HostCapabilities come from the inline renderer's\n // resolver (matrix-derived + user override). Sandbox is composed\n // here from the widget-level resource CSP / permissions per\n // SEP-1865 (sandbox is per-resource, not a vendor trait — see\n // HostMcpProfile.mcpAppsCapabilities doc). `hostInfo` is the same\n // resolved blob the inline renderer hands its bridge (ChatGPT-like\n // templates may override it via mcpProfile.apps.uiInitialize.hostInfo);\n // passing it down keeps inline + modal in lockstep.\n const bridge = new AppBridge(\n null,\n hostInfo,\n {\n ...effectiveHostCapabilities,\n sandbox: {\n csp: widgetPermissive ? undefined : widgetCsp,\n permissions: widgetPermissions,\n },\n },\n { hostContext: hostContextRef.current ?? {} },\n );\n\n // Reuse the same handlers as the inline bridge\n registerBridgeHandlers(bridge);\n\n // Override onsizechange to target modal iframe instead of main widget\n bridge.onsizechange = ({ width, height }) => {\n const modalIframe = modalSandboxRef.current?.getIframeElement();\n if (!modalIframe) return;\n\n if (height !== undefined) {\n const style = getComputedStyle(modalIframe);\n const isBorderBox = style.boxSizing === \"border-box\";\n\n let adjustedHeight = height;\n if (isBorderBox) {\n adjustedHeight +=\n parseFloat(style.borderTopWidth) +\n parseFloat(style.borderBottomWidth);\n }\n\n modalIframe.style.height = `${adjustedHeight}px`;\n }\n\n if (width !== undefined) {\n modalIframe.style.width = `${width}px`;\n }\n };\n\n // Override oninitialized so it doesn't set the main isReady state.\n // SEP-1865 App-Provided Tools: this replaces (not wraps) the\n // inline handler set by `registerBridgeHandlers`, so we have to\n // re-run the parts of that handler that matter for the modal\n // bridge — currently the app-tools registration. Inline state\n // mutations (setIsReady, setReinitCount, display-mode publish,\n // etc.) intentionally stay skipped: the modal has its own\n // lifecycle and must not steer the inline renderer's React state.\n bridge.oninitialized = () => {\n // Send tool input/output to the modal bridge after initialization\n const resolvedToolInput = toolInputRef.current ?? {};\n bridge.sendToolInput({ arguments: resolvedToolInput });\n if (toolOutputRef.current) {\n // ext-apps (v1-sdk peer) and the v2 client each declare a structurally\n // identical but nominally distinct CallToolResult; cast to exactly what\n // the bridge accepts at this Apps-compat seam (§1D).\n bridge.sendToolResult(\n toolOutputRef.current as Parameters<typeof bridge.sendToolResult>[0],\n );\n }\n\n const appCaps = bridge.getAppCapabilities();\n if (appCaps?.tools) {\n const bridgeId =\n modalAppToolsBridgeIdRef.current ?? crypto.randomUUID();\n modalAppToolsBridgeIdRef.current = bridgeId;\n void refreshAppProvidedTools(bridge, bridgeId, {\n surface: \"modal\",\n getIframeElement: () =>\n modalSandboxRef.current?.getIframeElement() ?? null,\n isLive: () => modalAppToolsBridgeIdRef.current === bridgeId,\n });\n }\n };\n\n modalBridgeRef.current = bridge;\n const pendingRpcMethods = new Map<string | number, string>();\n\n const transport = new LoggingTransport(\n new PostMessageTransport(iframe.contentWindow, iframe.contentWindow),\n {\n onSend: (message) => {\n const request = message as { id?: string | number; method?: string };\n if (\n typeof request.method === \"string\" &&\n (typeof request.id === \"string\" || typeof request.id === \"number\")\n ) {\n pendingRpcMethods.set(request.id, request.method);\n }\n addUiLog({\n widgetId: `${toolCallId}-modal`,\n serverId,\n direction: \"host-to-ui\",\n protocol: \"mcp-apps\",\n method: extractMethod(message, \"mcp-apps\"),\n message,\n });\n },\n onReceive: (message) => {\n const response = message as {\n id?: string | number;\n result?: unknown;\n error?: unknown;\n };\n const correlatedMethod =\n (response.result !== undefined || response.error !== undefined) &&\n (typeof response.id === \"string\" || typeof response.id === \"number\")\n ? pendingRpcMethods.get(response.id)\n : undefined;\n if (correlatedMethod && response.id !== undefined) {\n pendingRpcMethods.delete(response.id);\n }\n const method =\n correlatedMethod ?? extractMethod(message, \"mcp-apps\");\n // SEP-1865 App-Provided Tools: re-list when the modal app\n // signals a tools-list change. Mirrors the inline renderer's\n // `onReceive` hook so a `tool.update()` / `enable()` /\n // `disable()` from the modal app is reflected in the chat\n // snapshot's advertised aliases.\n if (method === \"notifications/tools/list_changed\") {\n const bridgeId = modalAppToolsBridgeIdRef.current;\n if (bridgeId) {\n void refreshAppProvidedTools(bridge, bridgeId, {\n force: true,\n surface: \"modal\",\n getIframeElement: () =>\n modalSandboxRef.current?.getIframeElement() ?? null,\n isLive: () => modalAppToolsBridgeIdRef.current === bridgeId,\n });\n }\n }\n addUiLog({\n widgetId: `${toolCallId}-modal`,\n serverId,\n direction: \"ui-to-host\",\n protocol: \"mcp-apps\",\n method,\n message,\n });\n },\n },\n );\n\n let isActive = true;\n bridge.connect(transport).catch((error) => {\n if (!isActive) return;\n console.error(\"[MCP Apps] Modal bridge connection failed\", error);\n });\n\n return () => {\n isActive = false;\n modalBridgeRef.current = null;\n // SEP-1865 App-Provided Tools: unregister on effect teardown\n // (component unmount or modalHtml refetch). Clearing the ref\n // first ensures any in-flight `listTools` short-circuits via\n // `isLive` and doesn't re-register after we've torn down.\n if (modalAppToolsBridgeIdRef.current) {\n const bridgeId = modalAppToolsBridgeIdRef.current;\n modalAppToolsBridgeIdRef.current = null;\n useAppToolsRegistry.getState().unregisterInstance(bridgeId);\n }\n bridge.close().catch(() => {});\n };\n }, [\n modalHtml,\n open,\n addUiLog,\n serverId,\n toolCallId,\n registerBridgeHandlers,\n refreshAppProvidedTools,\n widgetPermissive,\n widgetCsp,\n widgetPermissions,\n hostContextRef,\n toolInputRef,\n toolOutputRef,\n hostInfo,\n effectiveHostCapabilities,\n ]);\n\n const handleModalMessage = (event: MessageEvent) => {\n const data = event.data;\n if (!data) return;\n\n // Forward CSP violations to parent handler\n if (data.type === \"mcp-apps:csp-violation\") {\n onCspViolation(event);\n }\n };\n\n // Modal chrome is host-injected (the inspector's design-system <Dialog>). A\n // host that doesn't supply `components.Modal` opts out of the modal surface.\n if (!Modal) return null;\n\n return (\n <Modal open={open} onClose={() => onOpenChange(false)} title={title}>\n <div className=\"flex-1 w-full h-full min-h-0 overflow-auto\">\n {modalHtml && (\n <SandboxedIframe\n ref={modalSandboxRef}\n html={modalHtml}\n sandbox=\"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox\"\n csp={widgetCsp}\n permissions={widgetPermissions}\n permissive={widgetPermissive}\n sandboxAttrs={widgetSandboxAttrs}\n allowFeatures={widgetAllowFeatures}\n cspDirectives={widgetCspDirectives}\n colorScheme={modalColorScheme}\n onMessage={handleModalMessage}\n title={`MCP App Modal: ${title}`}\n hostedMode={host.surface.hostedMode}\n sandboxOrigin={host.surface.sandboxOrigin}\n className=\"min-w-full border-0 rounded-md bg-transparent overflow-hidden\"\n style={{\n height: \"100%\",\n minHeight: \"400px\",\n backgroundColor: \"transparent\",\n }}\n />\n )}\n </div>\n </Modal>\n );\n}\n","// Tier-B (Phase 3d-ii-c): the file-message bridge moved into @mcpjam/widget-react\n// alongside the renderer. The inspector-supplied `authFetch` (session-token auth)\n// and `hostedMode` flag are passed in as a `WidgetFileMessageContext` rather than\n// imported from `@/lib/*`, so this module carries no inspector internals.\n\n/** Validates the inspector's uploaded-file id format (`file_<hex/uuid>`). */\nconst UPLOADED_FILE_ID_PATTERN = /^file_[0-9a-f-]+$/;\nfunction isValidUploadedFileId(fileId: unknown): fileId is string {\n return typeof fileId === \"string\" && UPLOADED_FILE_ID_PATTERN.test(fileId);\n}\n\n/** Host-supplied capabilities the file-message handlers need. */\nexport interface WidgetFileMessageContext {\n /** Session-authenticated fetch (`host.services.authFetch`). */\n authFetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n /** Whether the app runs against the hosted backend (`host.surface.hostedMode`). */\n hostedMode: boolean;\n}\n\ntype UploadFileMessage = {\n type: \"openai:uploadFile\";\n callId: unknown;\n data?: unknown;\n mimeType?: unknown;\n fileName?: unknown;\n};\n\ntype GetFileDownloadUrlMessage = {\n type: \"openai:getFileDownloadUrl\";\n callId: unknown;\n fileId: unknown;\n};\n\ntype UploadFileResponseMessage = {\n type: \"openai:uploadFile:response\";\n callId: unknown;\n result?: { fileId: string };\n error?: string;\n};\n\ntype GetFileDownloadUrlResponseMessage = {\n type: \"openai:getFileDownloadUrl:response\";\n callId: unknown;\n result?: { downloadUrl: string };\n error?: string;\n};\n\nexport type WidgetFileResponseMessage =\n | UploadFileResponseMessage\n | GetFileDownloadUrlResponseMessage;\n\nexport type SendWidgetFileResponse = (\n message: WidgetFileResponseMessage,\n) => void;\n\nfunction buildWidgetDownloadUrl(fileId: string, hostedMode: boolean): string {\n const loc = window.location;\n const widgetHost = loc.hostname === \"localhost\" ? \"127.0.0.1\" : \"localhost\";\n const basePath = hostedMode\n ? \"/api/web/apps/files/file\"\n : \"/api/apps/files/file\";\n return `${loc.protocol}//${widgetHost}:${loc.port}${basePath}/${fileId}`;\n}\n\nexport async function handleUploadFileMessage(\n data: UploadFileMessage,\n sendResponse: SendWidgetFileResponse,\n { authFetch, hostedMode }: WidgetFileMessageContext,\n): Promise<void> {\n const uploadCallId = data.callId;\n if (hostedMode) {\n sendResponse({\n type: \"openai:uploadFile:response\",\n callId: uploadCallId,\n error: \"File upload is not supported in hosted mode\",\n });\n return;\n }\n\n try {\n const resp = await authFetch(\"/api/apps/files/upload-file\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n data: data.data,\n mimeType: data.mimeType,\n fileName: data.fileName,\n }),\n });\n if (!resp.ok) {\n const body = (await resp\n .json()\n .catch(() => ({ error: resp.statusText }))) as {\n error?: string;\n };\n sendResponse({\n type: \"openai:uploadFile:response\",\n callId: uploadCallId,\n error: body.error || \"Upload failed\",\n });\n return;\n }\n\n const { fileId } = (await resp.json()) as { fileId: string };\n sendResponse({\n type: \"openai:uploadFile:response\",\n callId: uploadCallId,\n result: { fileId },\n });\n } catch (err) {\n sendResponse({\n type: \"openai:uploadFile:response\",\n callId: uploadCallId,\n error: err instanceof Error ? err.message : \"Upload failed\",\n });\n }\n}\n\nexport function handleGetFileDownloadUrlMessage(\n data: GetFileDownloadUrlMessage,\n sendResponse: SendWidgetFileResponse,\n { hostedMode }: Pick<WidgetFileMessageContext, \"hostedMode\">,\n): void {\n const dlCallId = data.callId;\n if (hostedMode) {\n sendResponse({\n type: \"openai:getFileDownloadUrl:response\",\n callId: dlCallId,\n error: \"File download is not supported in hosted mode\",\n });\n return;\n }\n\n const fileId = data.fileId;\n if (!isValidUploadedFileId(fileId)) {\n sendResponse({\n type: \"openai:getFileDownloadUrl:response\",\n callId: dlCallId,\n error: \"Invalid fileId\",\n });\n return;\n }\n\n sendResponse({\n type: \"openai:getFileDownloadUrl:response\",\n callId: dlCallId,\n result: { downloadUrl: buildWidgetDownloadUrl(fileId, hostedMode) },\n });\n}\n","import { createContext, useContext, type ReactNode } from \"react\";\n\nconst WidgetSurfaceHostContext = createContext(false);\n\nexport function WidgetSurfaceHostProvider({\n children,\n}: {\n children: ReactNode;\n}) {\n return (\n <WidgetSurfaceHostContext.Provider value={true}>\n {children}\n </WidgetSurfaceHostContext.Provider>\n );\n}\n\nexport function usePersistentWidgetSurfaceHost() {\n return useContext(WidgetSurfaceHostContext);\n}\n","import { create } from \"zustand\";\nimport type { MCPAppsRendererProps } from \"./mcp-apps-renderer\";\n\nexport type WidgetSurfaceId = string;\n\ninterface WidgetSurfaceRegistration {\n toolCallId: string;\n order: number;\n props: MCPAppsRendererProps;\n anchorElement: HTMLDivElement | null;\n}\n\nexport interface WidgetSurfaceRecord {\n surfaceId: WidgetSurfaceId;\n chatSessionId?: string;\n initialToolCallId: string;\n latestToolCallId: string;\n registrations: Map<string, WidgetSurfaceRegistration>;\n}\n\ninterface WidgetSurfaceStoreState {\n surfaces: Map<WidgetSurfaceId, WidgetSurfaceRecord>;\n nextOrder: number;\n upsertRegistration: (\n surfaceId: WidgetSurfaceId,\n toolCallId: string,\n props: MCPAppsRendererProps\n ) => void;\n setAnchor: (\n surfaceId: WidgetSurfaceId,\n toolCallId: string,\n anchorElement: HTMLDivElement | null\n ) => void;\n releaseRegistration: (surfaceId: WidgetSurfaceId, toolCallId: string) => void;\n clearChatSession: (chatSessionId?: string) => void;\n}\n\nexport const useWidgetSurfaceStore = create<WidgetSurfaceStoreState>((set) => ({\n surfaces: new Map(),\n nextOrder: 0,\n\n upsertRegistration: (surfaceId, toolCallId, props) => {\n set((state) => {\n const surfaces = new Map(state.surfaces);\n const existing = surfaces.get(surfaceId);\n const registrations = new Map(existing?.registrations);\n const currentRegistration = registrations.get(toolCallId);\n const isNewRegistration = !currentRegistration;\n const order = currentRegistration?.order ?? state.nextOrder;\n const latestRegistration = existing?.registrations.get(\n existing.latestToolCallId\n );\n const shouldBecomeLatest =\n !existing ||\n !latestRegistration ||\n (isNewRegistration && order > latestRegistration.order);\n\n registrations.set(toolCallId, {\n toolCallId,\n order,\n props,\n anchorElement: currentRegistration?.anchorElement ?? null,\n });\n\n surfaces.set(surfaceId, {\n surfaceId,\n chatSessionId: props.chatSessionId,\n initialToolCallId: existing?.initialToolCallId ?? toolCallId,\n latestToolCallId: shouldBecomeLatest\n ? toolCallId\n : existing.latestToolCallId,\n registrations,\n });\n\n return {\n surfaces,\n nextOrder: isNewRegistration ? state.nextOrder + 1 : state.nextOrder,\n };\n });\n },\n\n setAnchor: (surfaceId, toolCallId, anchorElement) => {\n set((state) => {\n const existing = state.surfaces.get(surfaceId);\n const registration = existing?.registrations.get(toolCallId);\n if (!existing || !registration) return {};\n if (registration.anchorElement === anchorElement) return {};\n\n const registrations = new Map(existing.registrations);\n registrations.set(toolCallId, {\n ...registration,\n anchorElement,\n });\n const surfaces = new Map(state.surfaces);\n surfaces.set(surfaceId, {\n ...existing,\n registrations,\n });\n return { surfaces };\n });\n },\n\n releaseRegistration: (surfaceId, toolCallId) => {\n set((state) => {\n const existing = state.surfaces.get(surfaceId);\n if (!existing || !existing.registrations.has(toolCallId)) return {};\n\n const surfaces = new Map(state.surfaces);\n const registrations = new Map(existing.registrations);\n registrations.delete(toolCallId);\n\n if (registrations.size === 0) {\n surfaces.delete(surfaceId);\n return { surfaces };\n }\n\n let latestRegistration: WidgetSurfaceRegistration | null = null;\n for (const registration of registrations.values()) {\n if (\n latestRegistration === null ||\n registration.order > latestRegistration.order\n ) {\n latestRegistration = registration;\n }\n }\n\n surfaces.set(surfaceId, {\n ...existing,\n latestToolCallId:\n existing.latestToolCallId === toolCallId\n ? latestRegistration?.toolCallId ?? existing.latestToolCallId\n : existing.latestToolCallId,\n registrations,\n });\n return { surfaces };\n });\n },\n\n clearChatSession: (chatSessionId) => {\n set((state) => {\n // Skip the Map allocation + subscriber notification when no surface\n // belongs to this session (the common case on Thread unmount).\n let hasMatch = false;\n for (const surface of state.surfaces.values()) {\n if (surface.chatSessionId === chatSessionId) {\n hasMatch = true;\n break;\n }\n }\n if (!hasMatch) return {};\n\n const surfaces = new Map(state.surfaces);\n for (const [surfaceId, surface] of state.surfaces) {\n if (surface.chatSessionId === chatSessionId) {\n surfaces.delete(surfaceId);\n }\n }\n return { surfaces };\n });\n },\n}));\n\nexport function getRenderableSurfaceEntries(\n surfaces: Map<WidgetSurfaceId, WidgetSurfaceRecord>,\n chatSessionId?: string\n) {\n const entries: Array<{\n surfaceId: WidgetSurfaceId;\n anchorElement: HTMLDivElement | null;\n initialToolCallId: string;\n props: MCPAppsRendererProps;\n }> = [];\n\n for (const surface of surfaces.values()) {\n if (surface.chatSessionId !== chatSessionId) continue;\n const latestRegistration = surface.registrations.get(\n surface.latestToolCallId\n );\n if (!latestRegistration) continue;\n // Keep the mounted iframe under its original row. Reparenting a live\n // iframe can reload its browsing context in real browsers, which wipes\n // in-memory app state for stateful widgets like games.\n const initialRegistration = surface.registrations.get(\n surface.initialToolCallId\n );\n const fallbackAnchor =\n Array.from(surface.registrations.values()).find(\n (registration) => registration.anchorElement !== null\n )?.anchorElement ?? null;\n\n entries.push({\n surfaceId: surface.surfaceId,\n anchorElement: initialRegistration?.anchorElement ?? fallbackAnchor,\n initialToolCallId: surface.initialToolCallId,\n props: latestRegistration.props,\n });\n }\n\n return entries;\n}\n","/**\n * MCPAppsRenderer - SEP-1865 MCP Apps Renderer\n *\n * Renders MCP Apps widgets using the SEP-1865 protocol:\n * - JSON-RPC 2.0 over postMessage\n * - Double-iframe sandbox architecture\n * - tools/call, resources/read, ui/message, ui/open-link support\n *\n * Uses SandboxedIframe for DRY double-iframe setup.\n */\n\nimport {\n useRef,\n useState,\n useEffect,\n useLayoutEffect,\n useMemo,\n useCallback,\n type CSSProperties,\n} from \"react\";\nimport { useToolInputStreaming, type ToolState } from \"./useToolInputStreaming\";\nimport { ExternalLink, Loader2, X } from \"lucide-react\";\nimport { SandboxedIframe, SandboxedIframeHandle } from \"./sandboxed-iframe\";\nimport {\n resolveSandboxCsp,\n resolveSandboxPermissions,\n} from \"@mcpjam/sdk/browser\";\nimport {\n AppBridge,\n PostMessageTransport,\n type McpUiHostContext,\n type McpUiResourceCsp,\n type McpUiResourcePermissions,\n} from \"@modelcontextprotocol/ext-apps/app-bridge\";\nimport type { ContentBlock } from \"@modelcontextprotocol/client\";\n// Framework-free runtime helpers shared with the inspector + eval harness.\nimport {\n registerHostBridgeHandlers,\n LoggingTransport,\n extractMethod,\n stableStringifyJson,\n type AppToolInvocationUpdate,\n} from \"@mcpjam/sdk/widget-runtime\";\nimport { McpAppsModal } from \"./mcp-apps-modal\";\nimport {\n handleGetFileDownloadUrlMessage,\n handleUploadFileMessage,\n} from \"./widget-file-messages\";\nimport {\n useAppToolsRegistry,\n type AppToolDescriptor,\n} from \"./app-tools-registry\";\nimport { readToolResultMeta } from \"./tool-result-utils\";\nimport { usePersistentWidgetSurfaceHost } from \"./widget-surface-context\";\nimport { useWidgetSurfaceStore } from \"./widget-surface-store\";\n// The renderer reads its ambient ENV inputs, resolver fns, services, surface\n// flags, debug sink and injected chrome through the package's `useWidgetHost()`\n// context (supplied by the inspector's adapter via `<WidgetHostProvider>`). The\n// contract type-only symbols come from the package's `WidgetHost` module.\nimport { useWidgetHost } from \"./widget-host-context\";\nimport {\n type UiProtocol,\n type CspMode,\n type DisplayMode,\n type OpenAiAppsCapabilities,\n type ResolvedMcpAppsCapabilities,\n type WidgetLifecycleEvent,\n type WidgetHostResolvers,\n type WidgetDebugSink,\n} from \"./widget-host\";\n\n// The debug sink is OPTIONAL on the contract — a non-inspector host can omit it\n// and lose only the Sandbox/Network debug panels. The renderer routes every\n// instrumentation call through this no-op fallback so those call sites stay\n// branch-free when no sink is injected.\nconst NOOP_WIDGET_DEBUG_SINK: WidgetDebugSink = {\n recordMount: () => {},\n setWidgetDebugInfo: () => {},\n setWidgetState: () => {},\n setWidgetGlobals: () => {},\n setWidgetCsp: () => {},\n addCspViolation: () => {},\n clearCspViolations: () => {},\n setWidgetModelContext: () => {},\n setWidgetHtml: () => {},\n setSandboxApplied: () => {},\n appendLifecycle: () => {},\n addTrafficLog: () => {},\n};\n\n// Injected by Vite at build time from package.json\ndeclare const __APP_VERSION__: string;\n\n// Default input schema for tools without metadata\nconst DEFAULT_INPUT_SCHEMA = { type: \"object\" } as const;\n\nconst SUPPRESSED_UI_LOG_METHODS = new Set([\"ui/notifications/size-changed\"]);\nconst PIP_MAX_HEIGHT = \"min(40vh, 600px)\";\n/**\n * Grace period before an App that reported a CSP violation but hasn't\n * signalled `ui/initialize` is declared blocked. A View that loads a\n * blocked-but-optional asset (an analytics beacon, a font) still boots, so\n * the notice must not flash in front of a widget that is merely slow.\n */\nconst CSP_BLOCKED_NOTICE_DELAY_MS = 1500;\nconst SAFE_OPEN_IN_APP_PROTOCOLS = new Set([\"http:\", \"https:\"]);\n\nfunction toSafeOpenInAppUrl(value: string): string | null {\n try {\n const parsed = new URL(value);\n return SAFE_OPEN_IN_APP_PROTOCOLS.has(parsed.protocol) ? parsed.href : null;\n } catch {\n return null;\n }\n}\n\n/**\n * A widget-supplied `ui/download-file` `resource_link` may only target http(s):\n * that gate is what keeps `javascript:`/`data:`/`file:` URLs out of the\n * `window.open` the host performs on the widget's behalf. Resolves relative URIs\n * against the host document. Returns the absolute href when allowed, else null —\n * a single predicate shared by the pre-prompt reject and the download loop so\n * the two can't drift apart and silently weaken the gate.\n */\nfunction toSafeDownloadLinkUrl(uri: string): string | null {\n try {\n const parsed = new URL(uri, window.location.href);\n return SAFE_OPEN_IN_APP_PROTOCOLS.has(parsed.protocol) ? parsed.href : null;\n } catch {\n return null;\n }\n}\n\nfunction readExplicitBaseHref(html: string | null): string | null {\n if (!html) return null;\n\n if (typeof DOMParser !== \"undefined\") {\n try {\n const parsed = new DOMParser().parseFromString(html, \"text/html\");\n const href = parsed.querySelector(\"base[href]\")?.getAttribute(\"href\");\n if (href?.trim()) return href.trim();\n } catch {\n // Fall through to the lightweight parser below.\n }\n }\n\n const match = html.match(/<base\\b[^>]*\\bhref\\s*=\\s*[\"']([^\"']+)[\"']/i);\n return match?.[1]?.trim() || null;\n}\n\nfunction resolveExplicitBaseUrl(\n html: string | null,\n resourceUri: string\n): string | null {\n const baseHref = readExplicitBaseHref(html);\n if (!baseHref) return null;\n\n const absolute = toSafeOpenInAppUrl(baseHref);\n if (absolute) return absolute;\n\n const resourceUrl = toSafeOpenInAppUrl(resourceUri);\n if (!resourceUrl) return null;\n\n try {\n return toSafeOpenInAppUrl(new URL(baseHref, resourceUrl).href);\n } catch {\n return null;\n }\n}\n\nfunction resolveOpenInAppHref(\n href: unknown,\n explicitBaseUrl: string | null\n): string | null {\n if (typeof href !== \"string\") return null;\n const trimmed = href.trim();\n if (!trimmed) return null;\n\n const absolute = toSafeOpenInAppUrl(trimmed);\n if (absolute) return absolute;\n if (!explicitBaseUrl) return null;\n\n try {\n return toSafeOpenInAppUrl(new URL(trimmed, explicitBaseUrl).href);\n } catch {\n return null;\n }\n}\n\n/**\n * Origins the hosted-mode sandbox clamp must strip from any widget-\n * declared CSP. A hosted widget could otherwise declare an MCPJam\n * origin in `connectDomains` and use the user's authenticated session\n * to exfiltrate data through the iframe. Forwarded into the SDK via\n * `resolveSandboxCsp`'s `hostedClampExtraDeny` — an SDK-internal API\n * for hosted-mode origin stripping, distinct from anything the user can\n * configure (SEP-1865 host policies are allowlist-only).\n *\n * Wildcards cover all subdomains (api, staging, www, etc.) without\n * having to enumerate them. The bare-host entry catches widgets that\n * declare the apex domain directly.\n */\nconst MCPJAM_HOSTED_CLAMP_ORIGINS: ReadonlyArray<string> = [\n \"https://*.mcpjam.com\",\n \"https://mcpjam.com\",\n];\n\ntype HostStyleVariables = NonNullable<\n NonNullable<McpUiHostContext[\"styles\"]>[\"variables\"]\n>;\n\n// SEP-1865 fixes the set of style variable keys ui/initialize accepts. Every\n// HostStyleDefinition returns McpUiStyles from resolveStyleVariables, so a\n// legitimate built-in's key set is exactly the SEP enum; pinning the allowlist\n// to it both honors the protocol and strips any extra keys a runtime-registered\n// host might smuggle in via `as any`, which the SDK would reject downstream.\n//\n// The key set derives from `DEFAULT_HOST_STYLE`, now sourced through the\n// WidgetHost boundary (a hook value) rather than a module import. It's\n// deterministic for a given `DEFAULT_HOST_STYLE`, so compute it once lazily and\n// cache it per definition — preserving the old module-constant semantics while\n// keeping the renderer free of `@/lib/client-styles`.\nconst sepHostStyleVariableKeysCache = new WeakMap<\n object,\n ReadonlySet<string>\n>();\nfunction getSepHostStyleVariableKeys(\n defaultHostStyle: WidgetHostResolvers[\"DEFAULT_HOST_STYLE\"]\n): ReadonlySet<string> {\n const cached = sepHostStyleVariableKeysCache.get(defaultHostStyle);\n if (cached) return cached;\n const keys: ReadonlySet<string> = new Set([\n ...Object.keys(defaultHostStyle.mcp.resolveStyleVariables(\"light\")),\n ...Object.keys(defaultHostStyle.mcp.resolveStyleVariables(\"dark\")),\n ]);\n sepHostStyleVariableKeysCache.set(defaultHostStyle, keys);\n return keys;\n}\n\nfunction sanitizeHostStyleVariables(\n variables: unknown,\n sepHostStyleVariableKeys: ReadonlySet<string>\n): HostStyleVariables | undefined {\n if (!variables || typeof variables !== \"object\" || Array.isArray(variables)) {\n return undefined;\n }\n\n const sanitized: Record<string, string | undefined> = {};\n for (const [key, value] of Object.entries(variables)) {\n if (!sepHostStyleVariableKeys.has(key)) {\n continue;\n }\n if (typeof value === \"string\" || value === undefined) {\n sanitized[key] = value;\n }\n }\n\n return Object.keys(sanitized).length > 0\n ? (sanitized as HostStyleVariables)\n : undefined;\n}\n\n// CSP and permissions metadata types are now imported from SDK\n\nexport interface MCPAppsRendererProps {\n chatSessionId?: string;\n serverId: string;\n serverName?: string;\n toolCallId: string;\n toolName: string;\n toolState?: ToolState;\n toolInput?: Record<string, unknown>;\n toolOutput?: unknown;\n /**\n * Tool response `_meta`, pre-extracted by the caller from the raw\n * (still-wrapped) tool result. Required because `toolOutput` is\n * typically the *unwrapped* value (e.g. `result.value`), at which\n * point `_meta` from the wrapper is no longer reachable from the\n * value alone. Passing this explicitly preserves Apps SDK's\n * `window.openai.toolResponseMetadata` surface for widgets relying\n * on it (timestamps, source IDs, etc.).\n */\n toolResponseMetadata?: Record<string, unknown> | null;\n toolErrorText?: string;\n resourceUri: string;\n toolMetadata?: Record<string, unknown>;\n /** All tools metadata for visibility checking when widget calls tools */\n toolsMetadata?: Record<string, Record<string, unknown>>;\n onSendFollowUp?: (text: string) => void;\n onCallTool?: (\n toolName: string,\n params: Record<string, unknown>\n ) => Promise<unknown>;\n onAppToolInvocationChange?: (invocation: AppToolInvocationUpdate) => void;\n onWidgetStateChange?: (toolCallId: string, state: unknown) => void;\n /**\n * Tier 2 recorder. When `recordMode` is on, the sandbox proxy injects a\n * recorder shim into the guest; `onRecorderStep` fires for each captured\n * click/type (the raw `{ kind, target, ... }` step), and `onRecorderReady`\n * fires once when the shim installs (so the host can detect a strict-CSP\n * guest that silently blocked it). Default off — only the eval authoring\n * preview sets these.\n */\n recordMode?: boolean;\n onRecorderStep?: (step: unknown) => void;\n onRecorderReady?: () => void;\n /**\n * Replay (inverse of recording): published when the guest shim is record-capable\n * so the host can drive the live widget. The host calls `replay(step)` with one\n * scripted step; the renderer relays it to the guest and resolves with the\n * step's result. Published as `null` on unmount so the host drops the handle.\n */\n onReplayControllerReady?: (\n replay:\n | ((step: unknown) => Promise<{\n ok: boolean;\n reason?: string;\n deferred?: string;\n }>)\n | null\n ) => void;\n pipWidgetId?: string | null;\n fullscreenWidgetId?: string | null;\n onRequestPip?: (toolCallId: string) => void;\n onExitPip?: (toolCallId: string) => void;\n /** Controlled display mode - when provided, component uses this instead of internal state */\n displayMode?: DisplayMode;\n /** Callback when display mode changes - required when displayMode is controlled */\n onDisplayModeChange?: (mode: DisplayMode) => void;\n onRequestFullscreen?: (toolCallId: string) => void;\n onExitFullscreen?: (toolCallId: string) => void;\n /** Callback when widget updates model context (SEP-1865 ui/update-model-context) */\n onModelContextUpdate?: (\n toolCallId: string,\n context: {\n content?: ContentBlock[];\n structuredContent?: Record<string, unknown>;\n }\n ) => void;\n /** Callback when app declares its supported display modes during ui/initialize */\n onAppSupportedDisplayModesChange?: (modes: DisplayMode[] | undefined) => void;\n /**\n * Called when the widget sends `ui/notifications/request-teardown`\n * and the host has agreed to honor it (matrix `requestTeardown !==\n * false`). The renderer has already attempted a graceful\n * `ui/resource-teardown` round-trip; the parent is now expected to\n * unmount this tool call's MCP app surface (e.g. dismiss the modal,\n * collapse the inline view).\n */\n onRequestTeardown?: (toolCallId: string, displayWidgetId?: string) => void;\n /**\n * Ask the host to confirm a widget-initiated `ui/download-file` before the\n * download runs (SEP-1865: host SHOULD confirm). Resolve `true` to proceed,\n * `false` to deny (the widget then receives a JSON-RPC \"Download denied by\n * user\" error). When omitted, downloads proceed unprompted — so embedders of\n * the published package keep the prior behavior.\n */\n onConfirmDownload?: (info: {\n kind: \"resource\" | \"resource_link\";\n filename?: string;\n mimeType?: string;\n uri?: string;\n }) => Promise<boolean>;\n /** Whether the server is offline (for using cached content) */\n isOffline?: boolean;\n /** URL to cached widget HTML for offline rendering */\n cachedWidgetHtmlUrl?: string;\n /**\n * If true, attempt the live MCP Apps fetch first and only fall back to\n * `cachedWidgetHtmlUrl` if the live fetch fails (e.g. the server is no\n * longer connected). Used by in-flow session revisit; persisted offline\n * replay (Views tab, eval traces) leaves this unset so the cached path\n * stays primary.\n */\n liveFetchPreferred?: boolean;\n /** Persisted CSP metadata for cached/offline replay */\n widgetCsp?: McpUiResourceCsp | null;\n /** Persisted permissions metadata for cached/offline replay */\n widgetPermissions?: McpUiResourcePermissions | null;\n /** Persisted permissive flag for cached/offline replay */\n widgetPermissive?: boolean;\n /** Persisted prefersBorder value for cached/offline replay */\n prefersBorder?: boolean;\n /**\n * Persisted compat-runtime flag from a saved view or eval snapshot.\n * When set, the renderer trusts the cached blob as the source of\n * truth for whether `window.openai` was injected at capture time —\n * the live profile's flag is ignored for cached replay because the\n * HTML is byte-frozen. When undefined (no snapshot metadata), the\n * renderer falls back to the resolved live flag for fresh fetches.\n */\n injectedOpenAiCompat?: boolean;\n /**\n * Persisted per-method `window.openai.*` surface that was injected\n * into the cached HTML blob. Threads through the saved-view replay\n * path so the SDK runtime reproduces the same set of methods on\n * `window.openai` that the original capture had, even after the\n * active host config has flipped. Absent for pre-feature snapshots\n * — those replay against the runtime's full ChatGPT surface\n * default (matches behavior at capture time).\n */\n injectedOpenAiCompatCapabilities?: OpenAiAppsCapabilities;\n /**\n * Persisted widget state from a saved view or fork. When set, the\n * compat runtime seeds `window.openai.widgetState` with this value so\n * the widget boots in the same state it was when the view was saved\n * (Apps SDK parity — the legacy ChatGPTAppRenderer wired this the same\n * way).\n */\n initialWidgetState?: unknown;\n /** Minimal mode hides diagnostics and metadata surfaces */\n minimalMode?: boolean;\n /**\n * Stable identity assigned by WidgetSurfaceHost. Present only when the\n * renderer is mounted as a persistent, resource-scoped surface.\n */\n persistentSurfaceId?: string;\n /**\n * The first tool call registered for a resource-scoped persistent surface.\n * Kept for host/debug attribution; complete tool-input is still gated by\n * the surface's one-shot delivery latch so restored transcripts cannot skip\n * input when multiple rows register before the host mounts.\n */\n persistentSurfaceInitialToolCallId?: string;\n}\n\n/**\n * Map a `logWidgetDebug` emission to a `WidgetLifecycleEvent` for the\n * Sandbox debug panel, or return `null` for methods we don't track.\n *\n * Constraints:\n * - We only fan out methods that already exist in the renderer. No\n * invented events; no synthetic `pending` placeholders. Absence is\n * semantic — a stage that hasn't fired stays absent from the array.\n * - Status comes from the method itself (e.g. `*-error` → \"error\",\n * `*-ready` / `*-initialized` → \"ok\", `*-start` / `*-requested` →\n * \"pending\").\n * - The store's `appendLifecycle` setter dedupes consecutive same-\n * kind same-status entries, so a retry loop doesn't smear the panel.\n */\nfunction mapLogToLifecycle(\n method: string,\n details: Record<string, unknown>\n): WidgetLifecycleEvent | null {\n const kindByMethod: Record<string, WidgetLifecycleEvent[\"kind\"]> = {\n \"debug/sandbox-proxy-ready\": \"sandbox-proxy-ready\",\n \"debug/widget-content-requested\": \"widget-content-requested\",\n \"debug/widget-content-ready\": \"widget-content-ready\",\n \"debug/widget-content-error\": \"widget-content-error\",\n \"debug/widget-content-invalid-mimetype\": \"widget-content-invalid-mimetype\",\n \"debug/bridge-connect-start\": \"bridge-connect-start\",\n \"debug/bridge-connect-ready\": \"bridge-connect-ready\",\n \"debug/bridge-connect-error\": \"bridge-connect-error\",\n \"debug/bridge-connect-skipped\": \"bridge-connect-skipped\",\n \"debug/app-initialized\": \"app-initialized\",\n };\n const kind = kindByMethod[method];\n if (!kind) return null;\n let status: WidgetLifecycleEvent[\"status\"];\n if (\n method.endsWith(\"-error\") ||\n method === \"debug/widget-content-invalid-mimetype\"\n ) {\n status = \"error\";\n } else if (\n method.endsWith(\"-ready\") ||\n method === \"debug/app-initialized\" ||\n method === \"debug/bridge-connect-skipped\"\n ) {\n status = \"ok\";\n } else {\n status = \"pending\";\n }\n const message =\n typeof details.error === \"string\"\n ? details.error\n : typeof details.reason === \"string\"\n ? details.reason\n : undefined;\n return { kind, status, message, timestamp: Date.now() };\n}\n\nfunction recorderDebug(message: string, details?: Record<string, unknown>) {\n try {\n if (\n typeof window !== \"undefined\" &&\n window.localStorage?.getItem(\"mcpjam:recorder-debug\") === \"1\"\n ) {\n console.info(`[recorder:renderer] ${message}`, details ?? {});\n }\n } catch {\n // best-effort debug logging only\n }\n}\n\n/**\n * Segments of the fetch-source key, in the same order as the renderer\n * builds it below. Used to describe re-mount reasons for the Sandbox\n * debug panel — e.g. \"cachedReplayWidgetHtmlUrl, fetchMode\" when a saved\n * view swaps in a byte-frozen snapshot.\n */\nconst FETCH_SOURCE_KEY_SEGMENTS = [\n \"resourceUri\",\n \"cachedReplayWidgetHtmlUrl\",\n \"cspMode\",\n \"fetchMode\",\n // `injectOpenAiCompat` boolean and the per-method capability hash\n // are part of the rendering recipe: a host swap from ChatGPT-full\n // to Copilot-subset (or a master-toggle flip) changes the bytes\n // baked into the iframe, so a fetch issued under the old recipe\n // is stale by the time it resolves and must NOT overwrite the\n // newer commit's state. See plan §5.5 +\n // feedback_capability_in_render_recipe memory.\n \"injectOpenAiCompat\",\n \"compatCapabilitiesHash\",\n \"mcpAppsCapabilitiesHash\",\n] as const;\n\nfunction describeFetchSourceKeyDiff(prev: string, next: string): string {\n const prevSegs = prev.split(\"|\");\n const nextSegs = next.split(\"|\");\n const changes: string[] = [];\n for (let i = 0; i < FETCH_SOURCE_KEY_SEGMENTS.length; i += 1) {\n if (prevSegs[i] !== nextSegs[i]) changes.push(FETCH_SOURCE_KEY_SEGMENTS[i]);\n }\n return changes.length === 0 ? \"remount\" : changes.join(\", \");\n}\n\nfunction hashSurfaceIdentity(value: string): string {\n let hash = 2166136261;\n for (let i = 0; i < value.length; i += 1) {\n hash ^= value.charCodeAt(i);\n hash = Math.imul(hash, 16777619);\n }\n return (hash >>> 0).toString(36);\n}\n\nfunction getPersistentSurfaceId(props: MCPAppsRendererProps): string {\n // Identity is per-tool-call, not per-resource. The persistent surface's\n // job is to keep one iframe alive across re-renders of the same row\n // (e.g. fullscreen toggle, transcript reshuffles) — the `toolCallId`\n // is stable across all of those. Two distinct `tools/call` invocations\n // on the same resource are semantically two separate Views per\n // SEP-1865's lifecycle, so they must get their own surface; otherwise\n // the second tool-call row renders empty because the lone iframe is\n // anchored under the first row.\n const identity = stableStringifyJson({\n chatSessionId: props.chatSessionId ?? null,\n serverId: props.serverId,\n resourceUri: props.resourceUri,\n toolCallId: props.toolCallId,\n surface: \"inline\",\n });\n return `mcp-app:${hashSurfaceIdentity(identity)}`;\n}\n\nconst pendingSurfaceReleaseTimers = new Map<string, number>();\nconst pendingAnchorClearTimers = new Map<string, number>();\n\nfunction getSurfaceRegistrationKey(surfaceId: string, toolCallId: string) {\n return `${surfaceId}\\0${toolCallId}`;\n}\n\nfunction cancelPendingAnchorClear(surfaceId: string, toolCallId: string) {\n const key = getSurfaceRegistrationKey(surfaceId, toolCallId);\n const timer = pendingAnchorClearTimers.get(key);\n if (timer === undefined) return;\n window.clearTimeout(timer);\n pendingAnchorClearTimers.delete(key);\n}\n\nfunction scheduleAnchorClear(surfaceId: string, toolCallId: string) {\n const key = getSurfaceRegistrationKey(surfaceId, toolCallId);\n const existing = pendingAnchorClearTimers.get(key);\n if (existing !== undefined) window.clearTimeout(existing);\n const timer = window.setTimeout(() => {\n pendingAnchorClearTimers.delete(key);\n useWidgetSurfaceStore.getState().setAnchor(surfaceId, toolCallId, null);\n }, 0);\n pendingAnchorClearTimers.set(key, timer);\n}\n\nfunction cancelPendingSurfaceRelease(surfaceId: string, toolCallId: string) {\n const key = getSurfaceRegistrationKey(surfaceId, toolCallId);\n const timer = pendingSurfaceReleaseTimers.get(key);\n if (timer === undefined) return;\n window.clearTimeout(timer);\n pendingSurfaceReleaseTimers.delete(key);\n}\n\nfunction scheduleSurfaceRelease(surfaceId: string, toolCallId: string) {\n const key = getSurfaceRegistrationKey(surfaceId, toolCallId);\n const existing = pendingSurfaceReleaseTimers.get(key);\n if (existing !== undefined) window.clearTimeout(existing);\n const timer = window.setTimeout(() => {\n pendingSurfaceReleaseTimers.delete(key);\n useWidgetSurfaceStore.getState().releaseRegistration(surfaceId, toolCallId);\n }, 0);\n pendingSurfaceReleaseTimers.set(key, timer);\n}\n\nfunction PersistentMCPAppsRendererRegistration(props: MCPAppsRendererProps) {\n const surfaceId = useMemo(\n () => getPersistentSurfaceId(props),\n [props.chatSessionId, props.resourceUri, props.serverId, props.toolCallId]\n );\n const anchorRef = useRef<HTMLDivElement | null>(null);\n\n useLayoutEffect(() => {\n cancelPendingAnchorClear(surfaceId, props.toolCallId);\n cancelPendingSurfaceRelease(surfaceId, props.toolCallId);\n return () => {\n scheduleSurfaceRelease(surfaceId, props.toolCallId);\n };\n }, [surfaceId, props.toolCallId]);\n\n useLayoutEffect(() => {\n cancelPendingAnchorClear(surfaceId, props.toolCallId);\n cancelPendingSurfaceRelease(surfaceId, props.toolCallId);\n const store = useWidgetSurfaceStore.getState();\n store.upsertRegistration(surfaceId, props.toolCallId, props);\n store.setAnchor(surfaceId, props.toolCallId, anchorRef.current);\n });\n\n const setAnchor = useCallback(\n (node: HTMLDivElement | null) => {\n anchorRef.current = node;\n if (node === null) {\n scheduleAnchorClear(surfaceId, props.toolCallId);\n return;\n }\n cancelPendingAnchorClear(surfaceId, props.toolCallId);\n useWidgetSurfaceStore\n .getState()\n .setAnchor(surfaceId, props.toolCallId, node);\n },\n [surfaceId, props.toolCallId]\n );\n\n return (\n <div\n ref={setAnchor}\n data-mcp-app-surface-id={surfaceId}\n data-mcp-app-surface-anchor={props.toolCallId}\n />\n );\n}\n\nexport function MCPAppsRenderer(props: MCPAppsRendererProps) {\n // Read directly (not via useWidgetHost) because this wrapper gates\n // persistent-vs-ephemeral routing before MCPAppsRendererSurface mounts;\n // routing it through the host hook here would widen this wrapper's\n // subscription set. Centralizing is deferred to the relocation PR — this is a\n // relative-import context, so it does not affect the Tier-B import guard. See\n // use-widget-host.ts.\n const persistentHostEnabled = usePersistentWidgetSurfaceHost();\n const isCachedReplay =\n !!props.cachedWidgetHtmlUrl && !props.liveFetchPreferred;\n const wantPersistentSurface =\n persistentHostEnabled && !props.isOffline && !isCachedReplay;\n\n // Latch the surface choice. This wrapper picks between the persistent and\n // ephemeral surfaces, which are different component types. If an already-live\n // eval widget later receives a cached snapshot URL, keep it on the persistent\n // surface instead of routing it through a fresh cached replay surface.\n const everPersistentRef = useRef(false);\n if (wantPersistentSurface) everPersistentRef.current = true;\n const shouldUsePersistentSurface =\n everPersistentRef.current && !props.isOffline\n ? true\n : wantPersistentSurface;\n\n if (!shouldUsePersistentSurface) {\n return <MCPAppsRendererSurface {...props} />;\n }\n\n return <PersistentMCPAppsRendererRegistration {...props} />;\n}\n\nexport function MCPAppsRendererSurface({\n chatSessionId,\n serverId,\n serverName,\n toolCallId,\n toolName,\n toolState,\n toolInput,\n toolOutput,\n toolResponseMetadata,\n toolErrorText,\n resourceUri,\n toolMetadata,\n toolsMetadata,\n onSendFollowUp,\n onCallTool,\n onAppToolInvocationChange,\n onWidgetStateChange,\n recordMode,\n onRecorderStep,\n onRecorderReady,\n onReplayControllerReady,\n pipWidgetId,\n fullscreenWidgetId,\n onRequestPip,\n onExitPip,\n displayMode: displayModeProp,\n onDisplayModeChange,\n onRequestFullscreen,\n onExitFullscreen,\n onModelContextUpdate,\n onAppSupportedDisplayModesChange,\n onRequestTeardown,\n onConfirmDownload,\n isOffline,\n cachedWidgetHtmlUrl,\n liveFetchPreferred,\n widgetCsp: initialWidgetCsp,\n widgetPermissions: initialWidgetPermissions,\n widgetPermissive: initialWidgetPermissive,\n prefersBorder: initialPrefersBorder,\n injectedOpenAiCompat: initialInjectedOpenAiCompat,\n injectedOpenAiCompatCapabilities: initialInjectedOpenAiCompatCapabilities,\n initialWidgetState,\n minimalMode = false,\n persistentSurfaceId,\n persistentSurfaceInitialToolCallId,\n}: MCPAppsRendererProps) {\n const sandboxRef = useRef<SandboxedIframeHandle>(null);\n\n // Replay (host → guest): pending step requests keyed by a monotonic id. The\n // guest posts `recorder:replay-result` back with the same id (handled in\n // `handleSandboxMessage`), which resolves the matching promise. A timeout\n // resolves a missing reply as a failed step so a stuck guest can't hang Run.\n const replayIdRef = useRef(0);\n const pendingReplaysRef = useRef<\n Map<\n number,\n {\n resolve: (r: {\n ok: boolean;\n reason?: string;\n deferred?: string;\n }) => void;\n timer: ReturnType<typeof setTimeout>;\n }\n >\n >(new Map());\n const REPLAY_STEP_TIMEOUT_MS = 8000;\n const replayStep = useCallback(\n (\n step: unknown\n ): Promise<{ ok: boolean; reason?: string; deferred?: string }> =>\n new Promise((resolve) => {\n const id = (replayIdRef.current += 1);\n const timer = setTimeout(() => {\n pendingReplaysRef.current.delete(id);\n resolve({ ok: false, reason: \"replay step timed out\" });\n }, REPLAY_STEP_TIMEOUT_MS);\n pendingReplaysRef.current.set(id, { resolve, timer });\n sandboxRef.current?.postMessage({\n type: \"recorder:replay-step\",\n id,\n step,\n });\n }),\n []\n );\n // Publish the replay controller to the host while record-capable; retract it\n // (null) when recording turns off or the widget truly unmounts, failing any\n // in-flight steps so the orchestrator doesn't wait on a torn-down guest.\n //\n // `onReplayControllerReady` is recreated by the host on every render (it's an\n // inline tagging wrapper), so it CANNOT be an effect dep — that would re-run\n // the cleanup on every benign re-render (e.g. the thread updating after a\n // replayed click fires a tool call) and abort the replay mid-sequence\n // (\"widget unmounted\"). Read it through a ref; depend only on the actual\n // lifecycle inputs (`recordMode`, the stable `replayStep`).\n const onReplayControllerReadyRef = useRef(onReplayControllerReady);\n onReplayControllerReadyRef.current = onReplayControllerReady;\n useEffect(() => {\n const publish = onReplayControllerReadyRef.current;\n if (!recordMode) {\n publish?.(null);\n return;\n }\n publish?.(replayStep);\n return () => {\n onReplayControllerReadyRef.current?.(null);\n const pending = pendingReplaysRef.current;\n for (const { resolve, timer } of pending.values()) {\n clearTimeout(timer);\n resolve({ ok: false, reason: \"widget unmounted\" });\n }\n pending.clear();\n };\n }, [recordMode, replayStep]);\n // Inspector adapter for the WidgetHost contract (environment + resolvers +\n // services + surface + debug). The renderer's ambient ENV reads and resolver\n // imports are routed through this boundary; all derivation below is unchanged.\n const host = useWidgetHost();\n // Host-injected checkout chrome (the inspector's CheckoutDialogV2). Absent for\n // hosts that don't supply it — the checkout branch then renders nothing.\n const Checkout = host.components?.Checkout;\n // Optional instrumentation sink → no-op fallback (see NOOP_WIDGET_DEBUG_SINK).\n const debug = host.debug ?? NOOP_WIDGET_DEBUG_SINK;\n const { environment, resolvers } = host;\n const themeMode = environment.themeMode;\n const sharedHostStyle = environment.sharedHostStyle;\n const scenarioHostStyle = environment.scenarioHostStyle;\n const scenarioHostTheme = environment.scenarioHostTheme;\n const hostCapabilitiesOverride = environment.hostCapabilitiesOverride;\n // Active hostConfig.mcpProfile from the surrounding scope (scenario session,\n // project default, eval suite) is bound inside the adapter's resolvers (3d-iii);\n // the renderer keys its capability memos on `profileKey` and reads only the\n // minimal projections it inspects (sandbox overrides + hostInfo override).\n const activeMcpProfileKey = environment.profileKey;\n const profileSandbox = environment.profileSandbox;\n const profileHostInfo = environment.profileHostInfo;\n const hostCapabilitiesOverrideKey = useMemo(\n () => resolvers.stableStringifyJson(hostCapabilitiesOverride ?? null),\n [hostCapabilitiesOverride]\n );\n // Resolved compat-runtime flag for the active host. Claude/Cursor/\n // Codex-style hosts leave it off; ChatGPT/Copilot and MCPJam's dev\n // surface enable it. User override on the profile wins. The resolved\n // boolean travels into the widget-content request body and into the\n // renderer's reload-key so toggling the flag forces a refetch instead\n // of silently reusing the old HTML.\n const liveEffectiveCompatRuntime = useMemo(\n () =>\n resolvers.resolveEffectiveCompatRuntime({\n hostStyle: scenarioHostStyle ?? sharedHostStyle,\n }),\n [activeMcpProfileKey, scenarioHostStyle, sharedHostStyle]\n );\n const liveInjectOpenAiCompat = liveEffectiveCompatRuntime.injected;\n // Capability surface accompanying `liveInjectOpenAiCompat`. Travels\n // into the widget-content request alongside the boolean so the SDK\n // runtime omits methods that the active host's resolved matrix has\n // disabled (feature-detection truthfulness — see plan §4).\n // Null when injection is off (no surface to advertise).\n const liveOpenAiCompatCapabilities = liveEffectiveCompatRuntime.injected\n ? liveEffectiveCompatRuntime.capabilities\n : null;\n // A cached URL can exist during an in-flow revisit while the renderer still\n // prefers live HTML. Treat only cached-only renders as replay; live compat\n // fetches still need completed tool output baked into window.openai at boot.\n const isCachedReplay = !!cachedWidgetHtmlUrl && !liveFetchPreferred;\n const cachedReplayWidgetHtmlUrl = isCachedReplay\n ? cachedWidgetHtmlUrl\n : undefined;\n const widgetFetchModeKey = isCachedReplay ? \"cached\" : \"live\";\n const cachedReplayPrefersBorder = isCachedReplay\n ? initialPrefersBorder\n : undefined;\n // Cached replay: when a saved view / eval snapshot persisted the flag, trust\n // it because the HTML is byte-frozen at capture time. Live-preferred revisits\n // must use the current host config so a cached fallback does not create a\n // distinct render recipe from the next live tool call.\n const effectiveInjectOpenAiCompat =\n isCachedReplay && typeof initialInjectedOpenAiCompat === \"boolean\"\n ? initialInjectedOpenAiCompat\n : liveInjectOpenAiCompat;\n const draftHostContext = environment.draftHostContext;\n const baseHostContext = useMemo(\n () =>\n draftHostContext &&\n typeof draftHostContext === \"object\" &&\n !Array.isArray(draftHostContext)\n ? draftHostContext\n : {},\n [draftHostContext]\n );\n\n // Get CSP mode and host style from playground store when in playground\n const isPlaygroundActive = environment.isPlaygroundActive;\n const configuredHostTheme = resolvers.extractHostTheme(baseHostContext);\n const resolvedTheme = isPlaygroundActive\n ? configuredHostTheme ?? scenarioHostTheme ?? themeMode\n : scenarioHostTheme ?? themeMode;\n // Redeemed scenario sessions resolve servers via Convex on every\n // platform; widget-content fetches and bridge resource/prompt calls\n // must take the hosted API branch even on local builds. Mirrored into\n // a ref because the bridge handlers close over long-lived callbacks.\n const webManagedServers = host.surface.webManagedServers;\n const webManagedServersRef = useRef(webManagedServers);\n webManagedServersRef.current = webManagedServers;\n // CSP mode is derived from the surface kind + minimalMode + the playground's\n // selected mode (see WidgetHost). Scenario surfaces (published runtime,\n // Preview, Sessions transcript) and minimal mode default to `permissive` —\n // end-user-facing demo surfaces where an incomplete `_meta.ui.csp`\n // declaration would render a blank widget; the playground uses its selected\n // `mcpAppsCspMode`; everything else is `widget-declared`. Hosts that need\n // strict enforcement still pin it via the host config's `apps.sandbox.csp`\n // policy, applied per-resource below by `resolveSandboxCsp` regardless of\n // this default.\n //\n // `surface.kind` is sourced from the WidgetSurfaceContext (NOT\n // `isPlaygroundActive`), so it is stable from the first render — the\n // iframe-creation-time policy does not flip and tear down/rebuild the iframe\n // (and \"scenario\" wins over \"playground\", as before).\n const cspMode: CspMode =\n host.surface.kind === \"scenario\" || minimalMode\n ? \"permissive\"\n : host.surface.kind === \"playground\"\n ? host.surface.playgroundCspMode\n : \"widget-declared\";\n\n // Get locale and timeZone from playground store when active, fallback to browser defaults\n const playgroundLocale = environment.playgroundLocale;\n const playgroundTimeZone = environment.playgroundTimeZone;\n const fallbackLocale = isPlaygroundActive\n ? playgroundLocale\n : navigator.language || \"en-US\";\n const fallbackTimeZone = isPlaygroundActive\n ? playgroundTimeZone\n : Intl.DateTimeFormat().resolvedOptions().timeZone || \"UTC\";\n const locale =\n typeof draftHostContext?.locale === \"string\"\n ? draftHostContext.locale\n : fallbackLocale;\n const timeZone =\n typeof draftHostContext?.timeZone === \"string\"\n ? draftHostContext.timeZone\n : fallbackTimeZone;\n\n // Get displayMode from playground store when active (SEP-1865)\n const playgroundDisplayMode = environment.playgroundDisplayMode;\n const configuredDisplayMode = useMemo(\n () => resolvers.extractHostDisplayMode(draftHostContext),\n [draftHostContext]\n );\n const configuredAvailableDisplayModes = useMemo(\n () => resolvers.extractHostDisplayModes(draftHostContext),\n [draftHostContext]\n );\n // Resolve `effectiveHostStyle` early (it's a 3-way ternary on values\n // already available above) so the SEP-1865 matrix can be computed\n // before the display-mode clamp at `effectiveDisplayMode` below. The\n // duplicate-looking `effectiveHostStyle = ...` further down (around\n // the original `hostStyleDefinition`) reads the same value; both\n // assignments produce identical strings because the dependencies are\n // identical, so the bridge handshake / sandbox composition see the\n // same host style id.\n //\n // Matrix-resolved `availableDisplayModes` is what we advertise in\n // `HostContext.availableDisplayModes` AND what we clamp the\n // current/initial `effectiveDisplayMode` against. Without this\n // earlier clamp, a Copilot-preset host could initialize in (or\n // remain in) `pip` because the parent's `displayMode === \"pip\"`,\n // while advertising `availableDisplayModes: [\"fullscreen\"]` —\n // the View would see inconsistent HostContext.\n const earlyEffectiveHostStyle = isPlaygroundActive\n ? sharedHostStyle\n : scenarioHostStyle;\n const earlyEffectiveMcpAppsCapabilities = useMemo(\n () =>\n resolvers.resolveEffectiveMcpAppsCapabilities({\n hostStyle: earlyEffectiveHostStyle,\n }),\n [activeMcpProfileKey, earlyEffectiveHostStyle]\n );\n\n // Intersection of the matrix's allowed modes with the playground /\n // draft host context's configured modes — single source of truth for\n // both the runtime clamp at `effectiveDisplayMode` below AND the\n // value advertised in `HostContext.availableDisplayModes`. Computed\n // here (early) so the clamp can use it.\n //\n // Without sharing the intersection between the two consumers, the\n // matrix-only clamp inside `effectiveDisplayMode` could land on\n // `matrix[0]` while `HostContext.availableDisplayModes` advertised a\n // strict subset (the intersection). E.g. matrix=[\"pip\",\"fullscreen\"],\n // configured=[\"inline\",\"fullscreen\"], requested=\"inline\" →\n // matrix-only clamp produced \"pip\" (matrix[0]) while advertised list\n // was [\"fullscreen\"]. Fix: clamp against the intersection itself.\n //\n // Fallback to matrix alone when the intersection would be empty —\n // matches the matrix invariant (`length >= 1`) and avoids advertising\n // an unrenderable empty array. `configuredAvailableDisplayModes` is\n // always a non-empty array (see `extractHostDisplayModes` fallbacks)\n // so the only way intersection is empty is when the playground asks\n // for modes the simulated host doesn't advertise.\n // SEP-1865: after `ui/initialize` the view declares\n // `appCapabilities.availableDisplayModes` — the modes it can render in.\n // The host uses this to narrow what it ADVERTISES to the view in\n // `HostContext.availableDisplayModes`, NOT to coerce the current\n // display mode. A widget that only renders in fullscreen (e.g. a\n // canvas-heavy app) is expected to call `ui/request-display-mode`\n // itself after init — the host won't auto-switch the user out of the\n // mode they (or the parent) picked. Coercing here was a real\n // regression: every tool call snapped to fullscreen the moment the\n // widget initialized.\n const [appSupportedDisplayModes, setAppSupportedDisplayModes] = useState<\n DisplayMode[] | undefined\n >(undefined);\n\n // Host-supported modes only. Drives the current-mode clamp and the\n // `ui/request-display-mode` handler — both of which must stay\n // independent of the app's declaration so the user-visible mode is\n // never auto-coerced.\n const effectiveAvailableDisplayModes = useMemo(() => {\n const matrixModes = earlyEffectiveMcpAppsCapabilities.availableDisplayModes;\n const hostIntersection = matrixModes.filter((m) =>\n configuredAvailableDisplayModes.includes(m as DisplayMode)\n );\n const baseHostModes =\n hostIntersection.length > 0 ? hostIntersection : matrixModes;\n if (!appSupportedDisplayModes || appSupportedDisplayModes.length === 0) {\n return baseHostModes;\n }\n const appIntersection = baseHostModes.filter((m) =>\n appSupportedDisplayModes.includes(m as DisplayMode)\n );\n // SEP-1865: when the intersection is empty (the app advertises modes\n // the host doesn't support at all) we fall back to host-supported\n // rather than advertising nothing — the renderer will still clamp\n // the actual mode to the host's set, and the empty case is a\n // misconfigured app the host can't render anyway.\n return appIntersection.length > 0 ? appIntersection : baseHostModes;\n }, [\n earlyEffectiveMcpAppsCapabilities.availableDisplayModes,\n configuredAvailableDisplayModes,\n appSupportedDisplayModes,\n ]);\n\n // Advertised intersection — published in `HostContext.availableDisplayModes`\n // so the view knows which modes the host will honor on\n // `requestDisplayMode`. Falls back to host modes when the app\n // declaration is absent or the intersection would be empty\n // (a misconfigured app that doesn't overlap the host shouldn't\n // make the host advertise nothing).\n const advertisedAvailableDisplayModes = useMemo(() => {\n if (!appSupportedDisplayModes || appSupportedDisplayModes.length === 0) {\n return effectiveAvailableDisplayModes;\n }\n const intersection = effectiveAvailableDisplayModes.filter((m) =>\n appSupportedDisplayModes.includes(m as DisplayMode)\n );\n return intersection.length > 0\n ? intersection\n : effectiveAvailableDisplayModes;\n }, [effectiveAvailableDisplayModes, appSupportedDisplayModes]);\n\n // Get device capabilities from playground store (SEP-1865)\n const playgroundCapabilities = environment.playgroundCapabilities;\n const deviceCapabilities = useMemo(() => {\n const configuredCapabilities =\n draftHostContext?.deviceCapabilities &&\n typeof draftHostContext.deviceCapabilities === \"object\" &&\n !Array.isArray(draftHostContext.deviceCapabilities)\n ? (draftHostContext.deviceCapabilities as {\n hover?: boolean;\n touch?: boolean;\n })\n : undefined;\n\n if (configuredCapabilities) {\n return {\n hover: configuredCapabilities.hover ?? true,\n touch: configuredCapabilities.touch ?? false,\n };\n }\n\n return isPlaygroundActive\n ? playgroundCapabilities\n : { hover: true, touch: false };\n }, [draftHostContext, isPlaygroundActive, playgroundCapabilities]);\n\n // Get safe area insets from playground store (SEP-1865)\n const playgroundSafeAreaInsets = environment.playgroundSafeAreaInsets;\n const safeAreaInsets = useMemo(() => {\n const configuredSafeAreaInsets =\n draftHostContext?.safeAreaInsets &&\n typeof draftHostContext.safeAreaInsets === \"object\" &&\n !Array.isArray(draftHostContext.safeAreaInsets)\n ? (draftHostContext.safeAreaInsets as {\n top?: number;\n right?: number;\n bottom?: number;\n left?: number;\n })\n : undefined;\n\n if (configuredSafeAreaInsets) {\n return {\n top: configuredSafeAreaInsets.top ?? 0,\n right: configuredSafeAreaInsets.right ?? 0,\n bottom: configuredSafeAreaInsets.bottom ?? 0,\n left: configuredSafeAreaInsets.left ?? 0,\n };\n }\n\n return isPlaygroundActive\n ? playgroundSafeAreaInsets\n : { top: 0, right: 0, bottom: 0, left: 0 };\n }, [draftHostContext, isPlaygroundActive, playgroundSafeAreaInsets]);\n\n // Get device type from playground store for platform derivation (SEP-1865)\n const playgroundDeviceType = environment.playgroundDeviceType;\n\n // Display mode: controlled (via props) or uncontrolled (internal state)\n const isControlled = displayModeProp !== undefined;\n const [internalDisplayMode, setInternalDisplayMode] = useState<DisplayMode>(\n resolvers.clampDisplayModeToAvailableModes(\n configuredDisplayMode ??\n (isPlaygroundActive ? playgroundDisplayMode : \"inline\"),\n configuredAvailableDisplayModes\n )\n );\n const displayMode = isControlled ? displayModeProp : internalDisplayMode;\n const displayWidgetId = persistentSurfaceId ?? toolCallId;\n const ownsFullscreenDisplayMode =\n fullscreenWidgetId === displayWidgetId || fullscreenWidgetId === toolCallId;\n const ownsPipDisplayMode =\n pipWidgetId === displayWidgetId || pipWidgetId === toolCallId;\n const requestedDisplayMode = useMemo<DisplayMode>(() => {\n if (!isControlled) return displayMode;\n if (displayMode === \"fullscreen\" && ownsFullscreenDisplayMode) {\n return \"fullscreen\";\n }\n if (displayMode === \"pip\" && ownsPipDisplayMode) return \"pip\";\n return \"inline\";\n }, [\n displayMode,\n isControlled,\n ownsFullscreenDisplayMode,\n ownsPipDisplayMode,\n ]);\n // Clamp the requested display mode against the same intersection\n // that gets advertised in `HostContext.availableDisplayModes` so\n // the runtime mode is always a member of the advertised set. A\n // Copilot host initializing in `pip` (parent's `displayMode` is\n // sticky from a previous widget) coerces down to `fullscreen`\n // because the intersection resolves to `[\"fullscreen\"]`.\n const effectiveDisplayMode = useMemo<DisplayMode>(\n () =>\n resolvers.clampDisplayModeToAvailableModes(\n requestedDisplayMode,\n effectiveAvailableDisplayModes\n ),\n [requestedDisplayMode, effectiveAvailableDisplayModes]\n );\n\n // Clear the sticky inline-preference flag the moment the effective\n // mode moves off \"inline\". Under `user-initiated-only` — the policy\n // the flag actually gates — that transition can only come from the\n // user, since close-button paths set the flag true and switch to\n // inline while the widget's `request-display-mode` is declined. So a\n // non-inline mode means the user re-opted into fullscreen / PIP via\n // the host's display-mode picker, and the widget should be free to\n // keep its preferred mode again. Under `accept` a widget-driven\n // transition also clears it, which is harmless: the handler doesn't\n // consult the flag under that policy.\n useEffect(() => {\n if (effectiveDisplayMode !== \"inline\") {\n userPreferInlineRef.current = false;\n }\n }, [effectiveDisplayMode]);\n const setDisplayMode = useCallback(\n (mode: DisplayMode) => {\n if (isControlled) {\n onDisplayModeChange?.(mode);\n } else {\n setInternalDisplayMode(mode);\n }\n\n // Notify parent about fullscreen state changes regardless of controlled\n // mode. Always forward this widget's own id (`displayWidgetId`); the\n // parent runs an ownership check, which safely no-ops if our local\n // `displayMode` was stale at \"fullscreen\" because another widget took\n // over the global slot.\n if (mode === \"fullscreen\") {\n onRequestFullscreen?.(displayWidgetId);\n } else if (displayMode === \"fullscreen\") {\n onExitFullscreen?.(displayWidgetId);\n }\n },\n [\n isControlled,\n onDisplayModeChange,\n displayWidgetId,\n onRequestFullscreen,\n onExitFullscreen,\n displayMode,\n ]\n );\n const lastForcedDisplayModeRef = useRef<DisplayMode | null>(null);\n\n useEffect(() => {\n if (requestedDisplayMode === effectiveDisplayMode) {\n lastForcedDisplayModeRef.current = null;\n return;\n }\n\n if (lastForcedDisplayModeRef.current === effectiveDisplayMode) {\n return;\n }\n\n lastForcedDisplayModeRef.current = effectiveDisplayMode;\n setDisplayMode(effectiveDisplayMode);\n }, [effectiveDisplayMode, requestedDisplayMode, setDisplayMode]);\n\n const [isReady, setIsReady] = useState(false);\n const [reinitCount, setReinitCount] = useState(0);\n const [loadError, setLoadError] = useState<string | null>(null);\n // First CSP violation reported by the sandbox proxy for the current bytes.\n // Kept locally (the debug sink is write-only) so a View that never boots\n // because its own resources were blocked can say so instead of rendering\n // an empty box. First violation wins — it is the one that explains the\n // failure; later ones are usually cascade noise from the same block.\n const [firstCspBlock, setFirstCspBlock] = useState<{\n directive?: string;\n blockedUri?: string;\n } | null>(null);\n const [widgetHtml, setWidgetHtml] = useState<string | null>(null);\n const [openInAppUrlOverride, setOpenInAppUrlOverride] = useState<\n string | null\n >(null);\n const [sandboxProxyReady, setSandboxProxyReady] = useState(false);\n const [bridgeTransportReady, setBridgeTransportReady] = useState(false);\n const explicitOpenInAppBaseUrl = useMemo(\n () => resolveExplicitBaseUrl(widgetHtml, resourceUri),\n [widgetHtml, resourceUri]\n );\n const defaultOpenInAppUrl = useMemo(\n () => explicitOpenInAppBaseUrl ?? toSafeOpenInAppUrl(resourceUri),\n [explicitOpenInAppBaseUrl, resourceUri]\n );\n const openInAppUrl = openInAppUrlOverride ?? defaultOpenInAppUrl;\n const openInAppLabel = serverName?.trim() || serverId.trim() || \"App\";\n const handleOpenInApp = useCallback(() => {\n if (!openInAppUrl) return;\n window.open(openInAppUrl, \"_blank\", \"noopener,noreferrer\");\n }, [openInAppUrl]);\n\n useEffect(() => {\n setOpenInAppUrlOverride(null);\n }, [toolCallId, resourceUri]);\n const cachedReplayInjectOpenAiCompat =\n typeof initialInjectedOpenAiCompat === \"boolean\"\n ? initialInjectedOpenAiCompat\n : null;\n const widgetInjectOpenAiCompatReloadKey = isCachedReplay\n ? cachedReplayInjectOpenAiCompat\n : effectiveInjectOpenAiCompat;\n // Companion reload key carrying the per-method capability surface.\n // The boolean reload key above only catches injection on/off changes;\n // a user flipping the active host from ChatGPT-full to Copilot-subset\n // (or toggling a single method in the matrix) leaves the boolean at\n // `true` but changes the surface the runtime should expose. Folding\n // a stable hash of the capability record into the reload key forces\n // the iframe to refetch on per-method changes too. See\n // feedback_capability_in_render_recipe memory.\n // Cached replays read the hash from PERSISTED capabilities (what the\n // byte-frozen HTML was built against). Critical: this MUST match\n // what `loadFromCachedUrl` later stamps into\n // `loadedCompatCapabilitiesHash` — if the two diverge, the\n // \"already loaded\" guard at the top of the fetch effect fails on\n // every render, fires a second cached fetch, and that fetch's\n // `setBridgeTransportReady(false)` blanks the iframe out from\n // under an already-connected bridge.\n //\n // Legacy snapshots (no persisted caps) use `null` on both sides so\n // live host per-method changes don't trigger spurious refetches\n // against byte-frozen HTML.\n const widgetCompatCapabilitiesReloadKey = isCachedReplay\n ? initialInjectedOpenAiCompatCapabilities\n ? resolvers.stableStringifyJson(initialInjectedOpenAiCompatCapabilities)\n : null\n : effectiveInjectOpenAiCompat\n ? resolvers.stableStringifyJson(liveOpenAiCompatCapabilities ?? null)\n : null;\n // Sibling reload key for the MCP Apps spec-bridge matrix. The OpenAI\n // shim caps above bake into the iframe HTML at fetch time; MCP Apps\n // caps don't, but they drive the `HostCapabilities` blob in\n // `ui/initialize` and gate runtime bridge behavior (e.g. the\n // `widgetDisplayModeRequests` policy and the `userPreferInlineRef`\n // seed). Hashing the resolved record into the reload key forces a\n // remount when the user toggles a row in the matrix, so the new\n // policy takes effect on the live widget without a manual reload.\n // Cached replays use `null` for the same reason the OpenAI sibling\n // does — byte-frozen snapshots shouldn't churn on live host edits.\n const widgetMcpAppsCapabilitiesReloadKey = isCachedReplay\n ? null\n : resolvers.stableStringifyJson(earlyEffectiveMcpAppsCapabilities);\n // The OpenAI Apps SDK compatibility runtime bakes toolInput/toolOutput into\n // `window.openai` during HTML injection. Pure SEP-1865 views can boot while\n // input is still streaming and receive the final result via\n // ui/notifications/tool-result. Legacy Apps SDK templates declared through\n // `openai/outputTemplate` are different: many read window.openai.toolOutput\n // once on mount, so they still need the completed output before boot.\n const requiresCompatOutputAtBoot =\n effectiveInjectOpenAiCompat &&\n typeof toolMetadata?.[\"openai/outputTemplate\"] === \"string\";\n const shouldWaitForCompatToolOutput =\n !isCachedReplay &&\n requiresCompatOutputAtBoot &&\n toolState !== \"output-available\";\n const [widgetCsp, setWidgetCsp] = useState<McpUiResourceCsp | undefined>(\n isCachedReplay ? undefined : initialWidgetCsp ?? undefined\n );\n const [widgetPermissions, setWidgetPermissions] = useState<\n McpUiResourcePermissions | undefined\n >(isCachedReplay ? undefined : initialWidgetPermissions ?? undefined);\n const [widgetPermissive, setWidgetPermissive] = useState<boolean>(\n isCachedReplay ? true : initialWidgetPermissive ?? false\n );\n const [prefersBorder, setPrefersBorder] = useState<boolean>(\n initialPrefersBorder ?? true\n );\n // PR D matrix-gated resource-meta interpretation. The matrix\n // dimensions `cspFrameDomains`, `cspBaseUriDomains`,\n // `sandboxPermissions`, and `resourcePrefersBorder` model whether\n // the simulated host HONORS the corresponding resource `_meta.ui`\n // fields. Microsoft 365 Copilot's published Component-bridge table\n // marks all four as ❌; on a simulated Copilot host these fields\n // are silently ignored even when a widget declares them.\n //\n // We post-process the resource's `widgetCsp` / `widgetPermissions`\n // / `prefersBorder` after fetch — the SDK's `resolveSandboxCsp` /\n // `resolveSandboxPermissions` and the renderer's iframe-chrome\n // logic all read these gated values transparently. Per the\n // foundation plan's D3 decision, no SDK API change.\n const matrixGatedWidgetCsp = useMemo<McpUiResourceCsp | undefined>(() => {\n if (!widgetCsp) return widgetCsp;\n const m = earlyEffectiveMcpAppsCapabilities;\n if (m.cspFrameDomains && m.cspBaseUriDomains) return widgetCsp;\n // Spread + selectively strip the gated sub-fields. Connect /\n // resource domains are NOT matrix-gated today (no host's\n // published table tracks them at this granularity); only frame\n // and baseUri are.\n const next: McpUiResourceCsp = { ...widgetCsp };\n if (!m.cspFrameDomains) delete next.frameDomains;\n if (!m.cspBaseUriDomains) delete next.baseUriDomains;\n return next;\n }, [widgetCsp, earlyEffectiveMcpAppsCapabilities]);\n const matrixGatedWidgetPermissions = useMemo<\n McpUiResourcePermissions | undefined\n >(() => {\n // `sandboxPermissions: false` means the simulated host doesn't\n // honor the resource's permissions declarations AT ALL — return\n // undefined so the downstream resolver behaves as if the widget\n // declared no permissions. Spec-compliant simulation: the\n // widget asked for the camera, the host doesn't grant it.\n if (!earlyEffectiveMcpAppsCapabilities.sandboxPermissions) return undefined;\n return widgetPermissions;\n }, [widgetPermissions, earlyEffectiveMcpAppsCapabilities.sandboxPermissions]);\n const matrixGatedPrefersBorder = useMemo(() => {\n // `resourcePrefersBorder: false` means the simulated host\n // ignores the resource's `_meta.ui.prefersBorder` hint. Iframe\n // chrome falls back to host-default rendering (no border) for\n // every widget on that host.\n if (!earlyEffectiveMcpAppsCapabilities.resourcePrefersBorder) return false;\n return prefersBorder;\n }, [prefersBorder, earlyEffectiveMcpAppsCapabilities.resourcePrefersBorder]);\n const [loadedCspMode, setLoadedCspMode] = useState<CspMode | null>(null);\n // Reload-key sibling to `loadedCspMode`: tracks the compat-runtime\n // flag the currently-loaded HTML was fetched with. Toggling the live\n // flag must force a refetch, otherwise the short-circuit at the top\n // of the fetch effect would silently reuse already-shimmed (or\n // already-non-shimmed) HTML. Set to the effective flag in both the\n // cached and the live branches. Cached replays use the persisted\n // provenance flag as the reload key; legacy cached blobs without that\n // metadata use `null` so live host toggles don't rewrite byte-frozen\n // HTML provenance.\n const [loadedInjectOpenAiCompat, setLoadedInjectOpenAiCompat] = useState<\n boolean | null\n >(null);\n // Sibling of `loadedInjectOpenAiCompat`: tracks the stable hash of\n // the per-method capability surface the currently-loaded HTML was\n // fetched with. Set to `null` for legacy cached replays (no persisted\n // capability provenance) so live host toggles don't churn the iframe\n // on byte-frozen snapshots. Compared against\n // `widgetCompatCapabilitiesReloadKey` to detect per-method surface\n // changes that the boolean key would miss.\n const [loadedCompatCapabilitiesHash, setLoadedCompatCapabilitiesHash] =\n useState<string | null>(null);\n // Sibling of `loadedCompatCapabilitiesHash` for the MCP Apps\n // spec-bridge matrix. Tracks the resolved-caps hash the iframe was\n // last initialized against so a matrix toggle (e.g.\n // `widgetDisplayModeRequests`) forces a remount on the next render.\n const [loadedMcpAppsCapabilitiesHash, setLoadedMcpAppsCapabilitiesHash] =\n useState<string | null>(null);\n // Modal state\n const [modalOpen, setModalOpen] = useState(false);\n const [modalParams, setModalParams] = useState<Record<string, unknown>>({});\n const [modalTitle, setModalTitle] = useState(\"\");\n const [modalTemplate, setModalTemplate] = useState<string | null>(null);\n\n // Checkout state. The checkout-session payload is opaque to the package\n // (the inspector's injected `components.Checkout` narrows it to its own\n // `CheckoutSession` shape), so it is held as `unknown`.\n const [checkoutOpen, setCheckoutOpen] = useState(false);\n const [checkoutSession, setCheckoutSession] = useState<unknown>(null);\n const [checkoutCallId, setCheckoutCallId] = useState<number | null>(null);\n\n // True once this widget has rendered from a LIVE fetch. Used to keep a live\n // surface mounted when a persisted cached-replay snapshot arrives AFTER it\n // (the eval streaming→completed trace swap): wiping/reloading the live iframe\n // into the byte-frozen cached template would lose in-flight widget state (e.g.\n // a populated cart). A fresh cached-first replay (saved-view switch) never\n // sets this, so it still resets and loads its snapshot normally.\n const hasRenderedLiveRef = useRef(false);\n const liveRenderIdentityKey = useMemo(\n () =>\n stableStringifyJson({\n chatSessionId: chatSessionId ?? null,\n serverId,\n resourceUri,\n }),\n [chatSessionId, serverId, resourceUri]\n );\n const liveRenderIdentityRef = useRef<string | null>(null);\n const hasRenderedLiveForCurrentIdentity = useCallback(\n () =>\n hasRenderedLiveRef.current &&\n liveRenderIdentityRef.current === liveRenderIdentityKey,\n [liveRenderIdentityKey]\n );\n\n // Reset widget HTML when the actual replay source changes (e.g., different\n // saved view selected). A live-preferred cached URL is only a fallback; it\n // must not churn a persistent live surface when the next tool call has no\n // cached fallback.\n useEffect(() => {\n // A live render is already on screen and a cached snapshot just became\n // available for the same widget at run completion. Keep the live surface\n // and its in-flight state instead of wiping it into the static snapshot.\n if (isCachedReplay && hasRenderedLiveForCurrentIdentity()) return;\n hasRenderedLiveRef.current = false;\n liveRenderIdentityRef.current = null;\n setWidgetHtml(null);\n setBridgeTransportReady(false);\n setLoadedCspMode(null);\n setLoadedInjectOpenAiCompat(null);\n setLoadedCompatCapabilitiesHash(null);\n setLoadError(null);\n setWidgetCsp(undefined);\n setWidgetPermissions(undefined);\n setWidgetPermissive(isCachedReplay ? true : false);\n setPrefersBorder(cachedReplayPrefersBorder ?? true);\n // New bytes incoming — violations recorded against the old ones no\n // longer describe what is on screen.\n setFirstCspBlock(null);\n }, [\n cachedReplayWidgetHtmlUrl,\n cachedReplayPrefersBorder,\n hasRenderedLiveForCurrentIdentity,\n isCachedReplay,\n ]);\n\n const bridgeRef = useRef<AppBridge | null>(null);\n const hostContextRef = useRef<McpUiHostContext | null>(null);\n const isReadyRef = useRef(false);\n const lastInlineHeightRef = useRef<string>(\"400px\");\n // Sticky flag set when the user explicitly returned to inline (X\n // click in fullscreen / PIP). Cleared whenever the user explicitly\n // picks a non-inline mode again (display-mode picker).\n //\n // Gates widget-driven `ui/request-display-mode` under the\n // `\"user-initiated-only\"` policy ONLY — there, a widget that\n // re-requests its preferred mode on every `host-context-changed`\n // would otherwise trap the user in a mode they just dismissed. Under\n // `\"accept\"` the host honors widget requests and this flag is not\n // consulted, so closing PIP / fullscreen never mutes the widget's\n // later requests. See the handler in `onRequestDisplayMode`.\n //\n // Seeded from the `widgetDisplayModeRequests` host policy so the\n // `\"user-initiated-only\"` mode kicks in from the first mount: a widget\n // that requests fullscreen on init is treated the same as one\n // re-requesting it after the user dismissed once.\n //\n // Also gates the app-tools auto-promote below, which is host-initiated\n // UX rather than a widget request: a user who dismissed fullscreen\n // shouldn't be yanked back into it by the host under any policy.\n const userPreferInlineRef = useRef(\n earlyEffectiveMcpAppsCapabilities.widgetDisplayModeRequests ===\n \"user-initiated-only\"\n );\n // SEP-1865 host UX: one-shot guard for the app-tools auto-promote to\n // `displayMode = \"fullscreen\"`. When the inline bridge reports\n // `appCapabilities.tools` in `ui/initialize`, the renderer flips the\n // widget to fullscreen so the existing fullscreen overlay (composer\n // pinned + chevron-toggle chat history) mounts — the dev gets a\n // chat-with-app surface without manual mode switching. Gated by\n // `userPreferInlineRef` (auto-promote is treated as host-initiated\n // and respects the same dismissal + `user-initiated-only` policy\n // that blocks widget-initiated `ui/request-display-mode`). One-shot\n // so a shim re-init or a widget's own re-handshake doesn't fire\n // again. Refs reset across renderer instances, so teardown + a new\n // tool-call mount re-arms the promote — a fresh chat with the same\n // app gets the same affordance.\n const hasAutoPromotedForAppToolsRef = useRef(false);\n // SEP-1865 App-Provided Tools: per-bridge identity used to register and\n // unregister this iframe's tools in `useAppToolsRegistry`.\n const appToolsBridgeIdRef = useRef<string | null>(null);\n const appToolsListedBridgeIdsRef = useRef<Set<string>>(new Set());\n const appToolsListInFlightBridgeIdsRef = useRef<Set<string>>(new Set());\n const appToolsListRefreshPendingBridgeIdsRef = useRef<Set<string>>(new Set());\n // Reactive mirror of `appToolsBridgeIdRef` so the in-flight busy\n // indicator can subscribe to `useAppToolsRegistry.pendingControllers`\n // by bridge id. Refs alone don't trigger re-renders.\n const [appToolsBridgeIdState, setAppToolsBridgeIdState] = useState<\n string | null\n >(null);\n const pendingAppToolCalls = useAppToolsRegistry((s) =>\n appToolsBridgeIdState\n ? s.pendingControllers.get(appToolsBridgeIdState)?.size ?? 0\n : 0\n );\n\n // Reset widget-identity-scoped state when the renderer is reused for a\n // different resource / widget bundle. Without this the next widget\n // inherits the previous widget's intersected display modes and (if the user\n // had dismissed to inline) its sticky inline preference. Also re-seeds the\n // sticky flag from the\n // current `widgetDisplayModeRequests` policy so flipping the Apps tab\n // tri-state on an already-mounted renderer takes effect on the next\n // identity change instead of waiting for an unmount.\n useEffect(() => {\n setAppSupportedDisplayModes(undefined);\n userPreferInlineRef.current =\n earlyEffectiveMcpAppsCapabilities.widgetDisplayModeRequests ===\n \"user-initiated-only\";\n }, [\n resourceUri,\n cachedWidgetHtmlUrl,\n earlyEffectiveMcpAppsCapabilities.widgetDisplayModeRequests,\n ]);\n\n const onSendFollowUpRef = useRef(onSendFollowUp);\n const onCallToolRef = useRef(onCallTool);\n const onAppToolInvocationChangeRef = useRef(onAppToolInvocationChange);\n const appToolInvocationSequenceRef = useRef(0);\n const onRequestPipRef = useRef(onRequestPip);\n const onExitPipRef = useRef(onExitPip);\n const onRequestTeardownRef = useRef(onRequestTeardown);\n const onConfirmDownloadRef = useRef(onConfirmDownload);\n const setDisplayModeRef = useRef(setDisplayMode);\n const isPlaygroundActiveRef = useRef(isPlaygroundActive);\n const playgroundDeviceTypeRef = useRef(playgroundDeviceType);\n const effectiveDisplayModeRef = useRef(effectiveDisplayMode);\n const serverIdRef = useRef(serverId);\n const toolCallIdRef = useRef(toolCallId);\n const displayWidgetIdRef = useRef(displayWidgetId);\n const pipWidgetIdRef = useRef(pipWidgetId);\n const ownsPipDisplayModeRef = useRef(ownsPipDisplayMode);\n const toolsMetadataRef = useRef(toolsMetadata);\n const onModelContextUpdateRef = useRef(onModelContextUpdate);\n const onAppSupportedDisplayModesChangeRef = useRef(\n onAppSupportedDisplayModesChange\n );\n\n // Refs for values consumed inside the async fetchWidgetHtml function.\n // These change reference on every streaming chunk (AI SDK recreates part objects),\n // but we don't want to re-trigger the fetch effect for reference-only changes.\n const toolInputRef = useRef(toolInput);\n toolInputRef.current = toolInput;\n const toolOutputRef = useRef(toolOutput);\n toolOutputRef.current = toolOutput;\n const themeModeRef = useRef(themeMode);\n\n // Source-identity guard for the async fetch effect. The renderer can be\n // reused across session swaps and prop changes, so an older fetch can\n // resolve after `{ resourceUri, cachedReplayWidgetHtmlUrl, cspMode,\n // widgetFetchModeKey }` has moved on. Each effect run sets this ref to its\n // own key; the helpers below drop any state writes that don't still match\n // the latest key.\n const latestFetchSourceKeyRef = useRef<string>(\"\");\n /**\n * Previous fetch-source key, kept for the debug-panel mount log. We\n * can't reuse `latestFetchSourceKeyRef` because it's bumped before the\n * fetch starts; this one only advances after the mount has been\n * recorded so the diff is always prev→current.\n */\n const prevLoggedFetchSourceKeyRef = useRef<string | null>(null);\n // Bound before the fetch effect below references it in its deps array —\n // the other widget-debug-store bindings live further down because they\n // only fire from async callbacks, but `recordMountStore` is called\n // synchronously inside the effect body, so it has to be in scope here.\n const recordMountStore = debug.recordMount;\n\n // SEP-1865 MCP Apps spec-bridge matrix ref. Populated further down\n // in the render (after `effectiveHostStyle` / `activeMcpProfile`\n // resolve), but declared here so `useToolInputStreaming` below can\n // read it without forward-reference issues. Null reads as \"default\n // on\" — matches pre-matrix behavior during the brief initial-mount\n // window before the matrix resolver runs.\n const mcpAppsCapabilitiesRef = useRef<ResolvedMcpAppsCapabilities | null>(\n null\n );\n const {\n canRenderStreamingInput,\n signalStreamingRender,\n resetStreamingState,\n } = useToolInputStreaming({\n bridgeRef,\n isReady,\n isReadyRef,\n toolState,\n toolInput,\n toolOutput,\n toolErrorText,\n toolCallId,\n sendToolInput: true,\n reinitCount,\n mcpAppsCapabilitiesRef,\n });\n const hasWidgetHtml = widgetHtml !== null;\n const widgetHtmlLength = widgetHtml?.length ?? 0;\n\n // Fetch widget HTML when tool is active (streaming, input ready, or output available) or CSP mode changes\n useEffect(() => {\n const isActiveToolState =\n toolState === \"input-streaming\" ||\n toolState === \"input-available\" ||\n toolState === \"output-available\";\n if (!isActiveToolState) return;\n if (shouldWaitForCompatToolOutput) return;\n // Already showing a live render and a persisted cached snapshot just became\n // available for the same widget (eval streaming -> completed swap): keep the\n // live iframe (and its in-flight state) instead of reloading the frozen,\n // empty-state cached template. The captured snapshot still backs the\n // Browser/replay tabs; only this live surface stays live.\n if (widgetHtml && isCachedReplay && hasRenderedLiveForCurrentIdentity()) {\n return;\n }\n // Re-fetch if CSP mode changed (widget needs to reload with new CSP\n // policy) OR if the compat-runtime flag changed (HTML needs to be\n // rebuilt with/without the `window.openai` shim). Both belong in\n // the reload key — silently keeping HTML across a flag flip would\n // leave the wrong shape baked into the bytes.\n if (\n widgetHtml &&\n loadedCspMode === cspMode &&\n loadedInjectOpenAiCompat === widgetInjectOpenAiCompatReloadKey &&\n loadedCompatCapabilitiesHash === widgetCompatCapabilitiesReloadKey &&\n loadedMcpAppsCapabilitiesHash === widgetMcpAppsCapabilitiesReloadKey\n )\n return;\n\n // Source-identity key for this run. Any in-flight fetch whose key no\n // longer matches `latestFetchSourceKeyRef.current` when it resolves is\n // stale and MUST NOT mutate state.\n const fetchSourceKey = [\n resourceUri ?? \"\",\n cachedReplayWidgetHtmlUrl ?? \"\",\n cspMode,\n widgetFetchModeKey,\n // String() so `null` (cached-replay sentinel), `true`, and\n // `false` all serialize distinctly into the pipe-joined key.\n String(widgetInjectOpenAiCompatReloadKey),\n widgetCompatCapabilitiesReloadKey ?? \"\",\n widgetMcpAppsCapabilitiesReloadKey ?? \"\",\n ].join(\"|\");\n latestFetchSourceKeyRef.current = fetchSourceKey;\n // Mount log for the Sandbox debug panel. Record one entry per real\n // key change (not per effect re-run) so devs can spot self-induced\n // reloads — e.g. a saved view replay swapping in a different cached\n // snapshot, which remounts the iframe and visually wipes the previous\n // render.\n if (prevLoggedFetchSourceKeyRef.current !== fetchSourceKey) {\n const prev = prevLoggedFetchSourceKeyRef.current;\n const reason =\n prev === null\n ? \"initial\"\n : describeFetchSourceKeyDiff(prev, fetchSourceKey);\n prevLoggedFetchSourceKeyRef.current = fetchSourceKey;\n recordMountStore(toolCallIdRef.current, reason);\n }\n const isStillCurrent = () =>\n latestFetchSourceKeyRef.current === fetchSourceKey;\n\n // Throws on failure. Caller is responsible for surfacing the error.\n const loadFromCachedUrl = async (cachedUrl: string) => {\n const cachedResponse = await fetch(cachedUrl);\n if (!cachedResponse.ok) {\n throw new Error(\n `Failed to fetch cached widget HTML: ${cachedResponse.statusText}`\n );\n }\n const html = await cachedResponse.text();\n if (!isStillCurrent()) return;\n // Reset readiness so the previous bridge's transport doesn't\n // get reused with the new HTML before its connect resolves.\n setBridgeTransportReady(false);\n // Now showing cached HTML, not a live render.\n hasRenderedLiveRef.current = false;\n liveRenderIdentityRef.current = null;\n setWidgetHtml(html);\n setWidgetCsp(undefined);\n // Same reasoning as the live commit below: new bytes, so a violation\n // held from the previous resource no longer describes the screen.\n setFirstCspBlock(null);\n setWidgetPermissions(undefined);\n setWidgetPermissive(true);\n setPrefersBorder(initialPrefersBorder ?? true);\n setLoadedCspMode(cspMode);\n // Cached replay: HTML is byte-frozen at capture time. Trust persisted\n // provenance when available; otherwise keep it unknown instead of\n // inferring from the current live host. When this is the fallback path\n // after a preferred live fetch failed, mark the loaded fallback as\n // satisfying the current reload key so the effect doesn't immediately\n // retry live and overwrite the cached render.\n const loadedCachedCompatKey = isCachedReplay\n ? cachedReplayInjectOpenAiCompat\n : widgetInjectOpenAiCompatReloadKey;\n setLoadedInjectOpenAiCompat(loadedCachedCompatKey);\n // `widgetCompatCapabilitiesReloadKey` already encodes the right\n // value for both branches: cached replays compute it from the\n // persisted `initialInjectedOpenAiCompatCapabilities` (matches\n // the byte-frozen HTML), live fetches compute it from the\n // resolver. Stamp it verbatim so the fetch effect's\n // \"already loaded\" guard passes — earlier divergence between\n // this stamp and the reload key triggered a second cached\n // fetch that called `setBridgeTransportReady(false)` after the\n // bridge had already connected.\n setLoadedCompatCapabilitiesHash(widgetCompatCapabilitiesReloadKey);\n // MCP Apps caps don't bake into byte-frozen HTML; cached replays\n // stamp `null` (matching the reload key's cached-replay sentinel)\n // so live host edits don't churn the snapshot.\n setLoadedMcpAppsCapabilitiesHash(widgetMcpAppsCapabilitiesReloadKey);\n setWidgetHtmlStore(\n toolCallIdRef.current,\n html,\n loadedCachedCompatKey ?? undefined,\n // Persisted capabilities flow into the debug store so a\n // \"save view\" round-trip from a cached replay (e.g. user\n // duplicates an old view) carries the original surface\n // forward instead of stamping the current live matrix.\n isCachedReplay\n ? initialInjectedOpenAiCompatCapabilities\n : liveOpenAiCompatCapabilities ?? undefined\n );\n logWidgetDebug(\"host-to-ui\", \"debug/widget-content-ready\", {\n cached: true,\n cspMode,\n htmlLength: html.length,\n injectOpenAiCompat: loadedCachedCompatKey,\n permissive: true,\n });\n };\n\n // Throws on failure. Returns true on success, false if the server\n // returned an invalid mimetype (which is a content error — caller\n // should surface it and NOT fall back to a cached blob).\n const loadFromLiveFetch = async (): Promise<boolean> => {\n const {\n html,\n csp,\n permissions,\n permissive,\n mimeTypeWarning: warning,\n mimeTypeValid: valid,\n prefersBorder,\n injectedOpenAiCompat: serverInjectedOpenAiCompat,\n injectedOpenAiCompatCapabilities:\n serverInjectedOpenAiCompatCapabilities,\n } = await host.services.fetchWidgetContent({\n serverId,\n forceWebEndpoint: webManagedServersRef.current,\n resourceUri,\n toolInput: toolInputRef.current,\n toolOutput: toolOutputRef.current,\n // Surface `_meta` from the tool response so the compat runtime\n // can expose it as `window.openai.toolResponseMetadata`. Prefer\n // the explicit `toolResponseMetadata` prop (which the caller\n // computes from rawOutput where the `{ value, _meta }` wrapper\n // is still intact); fall back to deriving from the resolved\n // output for callers that don't pass it.\n toolResponseMetadata:\n toolResponseMetadata ??\n readToolResultMeta(toolOutputRef.current) ??\n null,\n initialWidgetState,\n toolId: toolCallIdRef.current,\n toolName,\n theme: themeModeRef.current,\n cspMode,\n injectOpenAiCompat: effectiveInjectOpenAiCompat,\n // Per-method capability surface forwarded to the SDK runtime.\n // Sending this alongside `injectOpenAiCompat: true` is what\n // makes disabled methods omitted from `window.openai` in the\n // widget — without it, the runtime falls back to its full\n // surface default and feature detection lies. Send only when\n // we're actually injecting (capabilities are meaningless\n // without the shim).\n openAiCompatCapabilities:\n effectiveInjectOpenAiCompat && liveOpenAiCompatCapabilities\n ? liveOpenAiCompatCapabilities\n : undefined,\n });\n const resolvedInjectedOpenAiCompat =\n typeof serverInjectedOpenAiCompat === \"boolean\"\n ? serverInjectedOpenAiCompat\n : effectiveInjectOpenAiCompat;\n // Server echoes the resolved capability surface (per plan §6.5)\n // so the renderer doesn't need to re-resolve to know exactly\n // what was baked into the HTML. Falls back to the live caps the\n // request sent — covers older servers that don't echo yet.\n const resolvedInjectedOpenAiCompatCapabilities =\n serverInjectedOpenAiCompatCapabilities ??\n (resolvedInjectedOpenAiCompat\n ? liveOpenAiCompatCapabilities ?? undefined\n : undefined);\n\n // Stale fetch: source key moved on (e.g. session swap, CSP toggle,\n // or resource change) while this request was in flight. Drop the\n // result so it can't overwrite the newer commit's state.\n if (!isStillCurrent()) return true;\n\n if (!valid) {\n const errorMessage =\n warning ||\n `Invalid mimetype - SEP-1865 requires \"text/html;profile=mcp-app\"`;\n setLoadError(errorMessage);\n logWidgetDebug(\"host-to-ui\", \"debug/widget-content-invalid-mimetype\", {\n cspMode,\n error: errorMessage,\n });\n return false;\n }\n\n // Reset readiness so the previous bridge's transport doesn't get\n // reused with the new HTML before its connect resolves.\n setBridgeTransportReady(false);\n // Mark that a live render exists so a later persisted cached snapshot\n // doesn't reload (and wipe) this iframe — see the fetch-effect guard.\n hasRenderedLiveRef.current = true;\n liveRenderIdentityRef.current = liveRenderIdentityKey;\n setWidgetHtml(html);\n setWidgetCsp(csp);\n // New bytes are going on screen, so a violation still held here was\n // reported against the previous ones. The identity-keyed reset effect\n // above covers a resourceUri/session change; this covers the case it\n // cannot see — a refetch that commits fresh HTML under the SAME\n // identity. Stating the invariant at the commit site keeps it local:\n // new bytes, no stale block.\n setFirstCspBlock(null);\n setWidgetPermissions(permissions);\n setWidgetPermissive(permissive ?? false);\n setPrefersBorder(prefersBorder ?? true);\n setLoadedCspMode(cspMode);\n setLoadedInjectOpenAiCompat(resolvedInjectedOpenAiCompat);\n // Capability hash for the fetched HTML — pair with the boolean\n // so future per-method changes detect this snapshot as stale and\n // force a refetch.\n setLoadedCompatCapabilitiesHash(widgetCompatCapabilitiesReloadKey);\n // Sibling stamp for the MCP Apps spec-bridge matrix.\n setLoadedMcpAppsCapabilitiesHash(widgetMcpAppsCapabilitiesReloadKey);\n\n // Store widget HTML in debug store for save view feature. Stamp the\n // resolved flag + per-method capability surface alongside it so\n // saved views and eval snapshots can persist what was actually\n // injected at fetch time. Replay reads both back when reproducing\n // the original render.\n setWidgetHtmlStore(\n toolCallIdRef.current,\n html,\n resolvedInjectedOpenAiCompat,\n resolvedInjectedOpenAiCompatCapabilities\n );\n\n // Update the widget debug store with CSP and permissions info\n if (csp || permissions || !permissive) {\n setWidgetCspStore(toolCallIdRef.current, {\n mode: permissive ? \"permissive\" : \"widget-declared\",\n connectDomains: csp?.connectDomains || [],\n resourceDomains: csp?.resourceDomains || [],\n frameDomains: csp?.frameDomains || [],\n baseUriDomains: csp?.baseUriDomains || [],\n permissions: permissions,\n widgetDeclared: csp\n ? {\n connectDomains: csp.connectDomains,\n resourceDomains: csp.resourceDomains,\n frameDomains: csp.frameDomains,\n baseUriDomains: csp.baseUriDomains,\n }\n : null,\n });\n }\n logWidgetDebug(\"host-to-ui\", \"debug/widget-content-ready\", {\n cached: false,\n cspMode,\n hasCsp: !!csp,\n hasPermissions: !!permissions,\n htmlLength: html.length,\n injectOpenAiCompat: resolvedInjectedOpenAiCompat,\n permissive: permissive ?? false,\n prefersBorder: prefersBorder ?? true,\n });\n return true;\n };\n\n const fetchWidgetHtml = async () => {\n try {\n logWidgetDebug(\"host-to-ui\", \"debug/widget-content-requested\", {\n cachedWidgetHtmlUrl: cachedWidgetHtmlUrl ?? null,\n cspMode,\n isOffline: !!isOffline,\n liveFetchPreferred: !!liveFetchPreferred,\n resourceUri,\n toolState: toolState ?? null,\n });\n\n // In-flow session revisit: try the live MCP Apps fetch first so the\n // widget re-renders against the active host's current CSP / bridge\n // state. If the server is no longer connected (or live fetch fails\n // for any reason), fall back to the cached snapshot HTML.\n if (liveFetchPreferred && cachedWidgetHtmlUrl) {\n try {\n await loadFromLiveFetch();\n return;\n } catch (liveErr) {\n logWidgetDebug(\"host-to-ui\", \"debug/widget-content-live-fallback\", {\n error:\n liveErr instanceof Error ? liveErr.message : String(liveErr),\n });\n await loadFromCachedUrl(cachedWidgetHtmlUrl);\n return;\n }\n }\n\n // Persisted offline replay (Views tab, eval traces, openai-apps\n // revisit): cached HTML is the only source.\n if (cachedWidgetHtmlUrl) {\n await loadFromCachedUrl(cachedWidgetHtmlUrl);\n return;\n }\n\n // If server is offline and no cached HTML, show helpful error\n if (isOffline) {\n const errorMessage =\n \"Server is offline and this view was saved without cached HTML. \" +\n \"Connect the server and re-save the view to enable offline rendering.\";\n setLoadError(errorMessage);\n logWidgetDebug(\"host-to-ui\", \"debug/widget-content-error\", {\n error: errorMessage,\n });\n return;\n }\n\n await loadFromLiveFetch();\n } catch (err) {\n if (!isStillCurrent()) return;\n const errorMessage =\n err instanceof Error ? err.message : \"Failed to prepare widget\";\n setLoadError(errorMessage);\n logWidgetDebug(\"host-to-ui\", \"debug/widget-content-error\", {\n error: errorMessage,\n });\n }\n };\n\n fetchWidgetHtml();\n // logWidgetDebug is intentionally omitted: it has stable identity (reads\n // serverId/toolCallId via refs) and is declared after this effect.\n }, [\n toolState,\n widgetHtml,\n loadedCspMode,\n loadedInjectOpenAiCompat,\n widgetInjectOpenAiCompatReloadKey,\n loadedCompatCapabilitiesHash,\n widgetCompatCapabilitiesReloadKey,\n loadedMcpAppsCapabilitiesHash,\n widgetMcpAppsCapabilitiesReloadKey,\n effectiveInjectOpenAiCompat,\n liveOpenAiCompatCapabilities,\n serverId,\n resourceUri,\n toolName,\n cspMode,\n isOffline,\n cachedWidgetHtmlUrl,\n cachedReplayWidgetHtmlUrl,\n liveFetchPreferred,\n widgetFetchModeKey,\n initialPrefersBorder,\n cachedReplayInjectOpenAiCompat,\n initialInjectedOpenAiCompatCapabilities,\n hasRenderedLiveForCurrentIdentity,\n liveRenderIdentityKey,\n shouldWaitForCompatToolOutput,\n recordMountStore,\n ]);\n\n // UI logging\n const addUiLog = debug.addTrafficLog;\n const logUiEvent = useCallback(\n (payload: Parameters<typeof addUiLog>[0]) => {\n if (minimalMode) return;\n addUiLog(payload);\n },\n [addUiLog, minimalMode]\n );\n const logUiEventRef = useRef(logUiEvent);\n logUiEventRef.current = logUiEvent;\n // Stable identity so this can be safely included in any effect deps without\n // causing reruns. Reads serverId/toolCallId from refs that are kept current\n // by the ref-sync effect below.\n const logWidgetDebug = useCallback(\n (\n direction: \"host-to-ui\" | \"ui-to-host\",\n method: string,\n details: Record<string, unknown>\n ) => {\n logUiEventRef.current({\n widgetId: toolCallIdRef.current,\n serverId: serverIdRef.current,\n direction,\n protocol: \"mcp-apps\",\n method,\n message: details,\n });\n // Also mirror this event into the widget-debug-store's lifecycle\n // array when the method matches one of our tracked stages. This is\n // the Sandbox debug panel's source of truth for \"how far did the\n // widget get before something went wrong\" — driven by the renderer's\n // existing log emissions so we never invent events.\n const mapped = mapLogToLifecycle(method, details);\n if (mapped !== null) {\n const toolCallId = toolCallIdRef.current;\n if (toolCallId) appendLifecycleRef.current(toolCallId, mapped);\n }\n },\n []\n );\n\n const refreshAppProvidedTools = useCallback(\n async (\n bridge: AppBridge,\n bridgeId: string,\n options: {\n force?: boolean;\n // SEP-1865 App-Provided Tools: the modal mounts a second\n // AppBridge against its own iframe, so callers (mcp-apps-modal)\n // pass `surface: \"modal\"`, their own `getIframeElement`, and an\n // `isLive` predicate tied to their own bridge-id ref. Inline\n // callers omit them and get the historical inline behavior.\n surface?: \"inline\" | \"modal\";\n getIframeElement?: () => HTMLIFrameElement | null;\n isLive?: () => boolean;\n } = {}\n ) => {\n const surface = options.surface ?? \"inline\";\n const getIframeElement =\n options.getIframeElement ??\n (() => sandboxRef.current?.getIframeElement() ?? null);\n const isLive =\n options.isLive ?? (() => appToolsBridgeIdRef.current === bridgeId);\n\n const alreadyListed = appToolsListedBridgeIdsRef.current.has(bridgeId);\n const inFlight = appToolsListInFlightBridgeIdsRef.current.has(bridgeId);\n if (inFlight) {\n if (options.force) {\n appToolsListRefreshPendingBridgeIdsRef.current.add(bridgeId);\n }\n return;\n }\n if (!options.force && alreadyListed) return;\n\n appToolsListInFlightBridgeIdsRef.current.add(bridgeId);\n try {\n let needsRefresh = true;\n while (needsRefresh) {\n appToolsListRefreshPendingBridgeIdsRef.current.delete(bridgeId);\n const tools: AppToolDescriptor[] = [];\n let cursor: string | undefined;\n for (let page = 0; page < 8; page += 1) {\n const result = await bridge.listTools(\n cursor === undefined ? {} : { cursor }\n );\n tools.push(\n ...(result.tools ?? []).filter((t): t is AppToolDescriptor =>\n Boolean(t && typeof t.name === \"string\" && t.name.length > 0)\n )\n );\n cursor = result.nextCursor;\n if (!cursor) break;\n }\n\n appToolsListedBridgeIdsRef.current.add(bridgeId);\n // `listTools()` crosses the iframe boundary. If the caller\n // unmounted or rebuilt while it was pending, the live ref has\n // been cleared and any late registration would leak stale\n // aliases.\n if (!isLive()) return;\n\n const appVersion = bridge.getAppVersion();\n await useAppToolsRegistry.getState().registerInstance({\n bridgeId,\n chatSessionId,\n parentToolCallId: toolCallIdRef.current,\n serverId: serverIdRef.current,\n appName: appVersion?.name ?? serverIdRef.current,\n appVersion: appVersion?.version,\n surface,\n bridge,\n tools,\n registeredAtMs: Date.now(),\n // Stable closure: the inline default reads `sandboxRef.current`\n // which is React-managed and tracks the live SandboxedIframe\n // across re-renders. The modal passes its own accessor against\n // `modalSandboxRef`.\n getIframeElement,\n });\n if (!isLive()) {\n useAppToolsRegistry.getState().unregisterInstance(bridgeId);\n return;\n }\n needsRefresh =\n appToolsListRefreshPendingBridgeIdsRef.current.has(bridgeId);\n }\n } catch (err) {\n appToolsListedBridgeIdsRef.current.delete(bridgeId);\n logWidgetDebug(\"ui-to-host\", \"debug/app-tools-list-failed\", {\n error: err instanceof Error ? err.message : String(err),\n });\n } finally {\n appToolsListInFlightBridgeIdsRef.current.delete(bridgeId);\n }\n },\n [chatSessionId, logWidgetDebug]\n );\n\n // Widget debug store\n const setWidgetDebugInfo = debug.setWidgetDebugInfo;\n const setWidgetGlobals = debug.setWidgetGlobals;\n const setWidgetStateStore = debug.setWidgetState;\n const setWidgetCspStore = debug.setWidgetCsp;\n const addCspViolation = debug.addCspViolation;\n const clearCspViolations = debug.clearCspViolations;\n const setWidgetModelContext = debug.setWidgetModelContext;\n const setWidgetHtmlStore = debug.setWidgetHtml;\n const setSandboxAppliedStore = debug.setSandboxApplied;\n const appendLifecycleStore = debug.appendLifecycle;\n // Ref-route the lifecycle setter so logWidgetDebug stays stable-identity\n // without listing the store setter in its deps (matches the logUiEvent\n // pattern above).\n const appendLifecycleRef = useRef(appendLifecycleStore);\n appendLifecycleRef.current = appendLifecycleStore;\n const setWidgetModelContextRef = useRef(setWidgetModelContext);\n setWidgetModelContextRef.current = setWidgetModelContext;\n\n // Clear CSP violations when CSP mode OR compat flag changes (stale\n // data from previous load — both reload-key axes trigger a refetch\n // so violation history from the prior bytes is no longer relevant).\n useEffect(() => {\n if (loadedCspMode !== null && loadedCspMode !== cspMode) {\n clearCspViolations(toolCallId);\n setFirstCspBlock(null);\n }\n }, [cspMode, loadedCspMode, toolCallId, clearCspViolations]);\n useEffect(() => {\n const injectionChanged =\n loadedInjectOpenAiCompat !== null &&\n loadedInjectOpenAiCompat !== widgetInjectOpenAiCompatReloadKey;\n const capabilitiesChanged =\n (loadedCompatCapabilitiesHash !== null &&\n loadedCompatCapabilitiesHash !== widgetCompatCapabilitiesReloadKey) ||\n (loadedMcpAppsCapabilitiesHash !== null &&\n loadedMcpAppsCapabilitiesHash !== widgetMcpAppsCapabilitiesReloadKey);\n if (injectionChanged || capabilitiesChanged) {\n clearCspViolations(toolCallId);\n setFirstCspBlock(null);\n }\n }, [\n widgetInjectOpenAiCompatReloadKey,\n loadedInjectOpenAiCompat,\n widgetCompatCapabilitiesReloadKey,\n loadedCompatCapabilitiesHash,\n widgetMcpAppsCapabilitiesReloadKey,\n loadedMcpAppsCapabilitiesHash,\n toolCallId,\n clearCspViolations,\n ]);\n\n // Reset ready state and refs when CSP mode OR compat flag changes\n // (widget will reinitialize — tool input/output must be re-sent).\n useEffect(() => {\n if (loadedCspMode !== null && loadedCspMode !== cspMode) {\n setIsReady(false);\n isReadyRef.current = false;\n resetStreamingState();\n }\n }, [cspMode, loadedCspMode, resetStreamingState]);\n useEffect(() => {\n const injectionChanged =\n loadedInjectOpenAiCompat !== null &&\n loadedInjectOpenAiCompat !== widgetInjectOpenAiCompatReloadKey;\n const capabilitiesChanged =\n (loadedCompatCapabilitiesHash !== null &&\n loadedCompatCapabilitiesHash !== widgetCompatCapabilitiesReloadKey) ||\n (loadedMcpAppsCapabilitiesHash !== null &&\n loadedMcpAppsCapabilitiesHash !== widgetMcpAppsCapabilitiesReloadKey);\n if (injectionChanged || capabilitiesChanged) {\n setIsReady(false);\n isReadyRef.current = false;\n resetStreamingState();\n }\n }, [\n widgetInjectOpenAiCompatReloadKey,\n loadedInjectOpenAiCompat,\n widgetCompatCapabilitiesReloadKey,\n loadedCompatCapabilitiesHash,\n widgetMcpAppsCapabilitiesReloadKey,\n loadedMcpAppsCapabilitiesHash,\n resetStreamingState,\n ]);\n\n // Sync displayMode from playground store when it changes (SEP-1865)\n // Only sync when not in controlled mode (parent controls displayMode via props)\n useEffect(() => {\n if (isPlaygroundActive && !isControlled) {\n setInternalDisplayMode(\n resolvers.clampDisplayModeToAvailableModes(\n configuredDisplayMode ?? playgroundDisplayMode,\n configuredAvailableDisplayModes\n )\n );\n }\n }, [\n configuredAvailableDisplayModes,\n configuredDisplayMode,\n isPlaygroundActive,\n playgroundDisplayMode,\n isControlled,\n ]);\n\n // Initialize widget debug info\n useEffect(() => {\n setWidgetDebugInfo(toolCallId, {\n toolName,\n protocol: \"mcp-apps\",\n // Seed from persisted state when a saved view / fork supplied one,\n // so the Debug \"Widget State\" tab shows the restored value on\n // first render instead of `null`. Apps SDK widgets that call\n // window.openai.setWidgetState() later will overwrite this via\n // setWidgetStateStore in the openai:setWidgetState handler below.\n widgetState: initialWidgetState ?? null,\n prefersBorder,\n globals: {\n theme: resolvedTheme,\n displayMode: effectiveDisplayMode,\n locale,\n timeZone,\n deviceCapabilities,\n safeAreaInsets,\n },\n });\n }, [\n toolCallId,\n toolName,\n setWidgetDebugInfo,\n resolvedTheme,\n effectiveDisplayMode,\n locale,\n timeZone,\n deviceCapabilities,\n safeAreaInsets,\n prefersBorder,\n initialWidgetState,\n ]);\n\n // Update globals in debug store when they change\n useEffect(() => {\n setWidgetGlobals(toolCallId, {\n theme: resolvedTheme,\n displayMode: effectiveDisplayMode,\n locale,\n timeZone,\n deviceCapabilities,\n safeAreaInsets,\n });\n }, [\n toolCallId,\n resolvedTheme,\n effectiveDisplayMode,\n locale,\n timeZone,\n deviceCapabilities,\n safeAreaInsets,\n setWidgetGlobals,\n ]);\n\n // CSS Variables for theming (SEP-1865 styles.variables)\n // These are sent via hostContext.styles.variables - the SDK should pass them through\n const effectiveHostStyle = isPlaygroundActive\n ? sharedHostStyle\n : scenarioHostStyle;\n const hostStyleDefinition =\n resolvers.getHostStyleOrDefault(effectiveHostStyle);\n // Single source of truth for what `hostCapabilities` this view will\n // advertise. The bridge-creation effect (`new AppBridge(...)`) spreads this\n // value into the handshake, and `registerBridgeHandlers` gates each\n // chip-bound handler on the matching field — same blob drives both\n // advertise and enforce, no drift.\n //\n // Stability matters: this memo is a dep of both the bridge-construction\n // useEffect and the registerBridgeHandlers useCallback, so a fresh\n // reference per render would tear down + re-attach the bridge on every\n // commit. Both inputs are stable — `effectiveHostStyle` resolves to a\n // string|null derived from Zustand+context selectors, and\n // `hostCapabilitiesOverride` comes from a context whose Providers (see\n // ClientStyledChatTabV2 / PlaygroundTab / ScenarioChatPage) read from\n // Zustand selectors that return stable refs until the underlying field\n // mutates.\n // Ref-route the active `window.openai` shim capability surface so\n // the host-side `openai:*` postMessage handlers (uploadFile,\n // getFileDownloadUrl, setWidgetState, requestModal, requestClose,\n // requestCheckout) can read the current value without forcing\n // their closures to rebuild on every host swap. These gates are\n // defense-in-depth for the shim surface — the SDK runtime already\n // omits the corresponding methods on `window.openai`, but a widget\n // that captured a method reference before a host swap, or a\n // hand-crafted postMessage, would still arrive here.\n //\n // Cached replays use the PERSISTED capabilities (what was baked\n // into the HTML bytes) instead of the live profile's matrix — the\n // byte-frozen runtime config inside the iframe is the source of\n // truth for which methods the widget can call.\n //\n // SCOPED TO THE SHIM ONLY. The SEP-1865 `bridge.on*` handlers are\n // a distinct surface and follow `effectiveHostCapabilities`\n // exclusively — see the comment in `registerBridgeHandlers`. Null\n // when the shim isn't injected.\n // Sparse `OpenAiAppsCapabilities` (not Required) because the\n // cached-replay branch reads a persisted value that may be missing\n // fields added after capture time. Consumers of this ref\n // (postMessage gates) read each field with `caps[key] === false` /\n // `caps[key] !== true`, so missing → treated as \"default on\", which\n // matches the SDK runtime's FULL_SURFACE_DEFAULT fallback baked\n // into the original capture.\n const activeShimCapabilities: OpenAiAppsCapabilities | null = isCachedReplay\n ? initialInjectedOpenAiCompatCapabilities ?? null\n : liveOpenAiCompatCapabilities;\n const liveOpenAiCompatCapabilitiesRef = useRef<OpenAiAppsCapabilities | null>(\n activeShimCapabilities\n );\n liveOpenAiCompatCapabilitiesRef.current = activeShimCapabilities;\n\n const effectiveHostCapabilities = useMemo(\n () =>\n resolvers.resolveEffectiveHostCapabilities({\n hostStyle: effectiveHostStyle,\n hostCapabilitiesOverride,\n }),\n [effectiveHostStyle, activeMcpProfileKey, hostCapabilitiesOverrideKey]\n );\n const effectiveHostCapabilitiesKey = useMemo(\n () => stableStringifyJson(effectiveHostCapabilities),\n [effectiveHostCapabilities]\n );\n // SEP-1865 spec-bridge matrix resolved from the live profile +\n // host style. Gates notification emissions (`tool-input-partial`,\n // `tool-cancelled`, `host-context-changed`) so simulated hosts\n // like Microsoft 365 Copilot match their published Component-\n // bridge table. Sibling to `effectiveHostCapabilities` — the wire\n // shape advertised in `ui/initialize` is derived from this matrix\n // via `buildHostCapabilities`, but the matrix itself is what\n // runtime notification gates read.\n //\n // INDEPENDENT from the OpenAI shim's `activeShimCapabilities`\n // ref. Two-matrix architecture (see\n // feedback_two_matrix_architecture memory): toggling a row on one\n // matrix never reads the other.\n //\n // The ref is declared above (with initial `null`) so it's visible\n // to `useToolInputStreaming` earlier in the render. We populate\n // `.current` here — same one-step-behind-during-mount caveat the\n // `liveOpenAiCompatCapabilitiesRef` pattern has, and the gate\n // contract reads `null` as \"default on\" so the brief window emits\n // notifications (matches pre-matrix behavior).\n //\n // The matrix itself is computed earlier in the render\n // (`earlyEffectiveMcpAppsCapabilities` near the display-mode\n // resolution) so the `effectiveDisplayMode` clamp can use it. We\n // alias the same value here for downstream consumers.\n const effectiveMcpAppsCapabilities = earlyEffectiveMcpAppsCapabilities;\n mcpAppsCapabilitiesRef.current = effectiveMcpAppsCapabilities;\n themeModeRef.current = resolvedTheme;\n const styleVariables = useMemo(\n () => hostStyleDefinition.mcp.resolveStyleVariables(resolvedTheme),\n [resolvedTheme, hostStyleDefinition]\n );\n const hostChatBackground = useMemo(\n () => hostStyleDefinition.chatUi.resolveChatBackground(resolvedTheme),\n [hostStyleDefinition, resolvedTheme]\n );\n const defaultFontCss = hostStyleDefinition.mcp.fontCss;\n const configuredStyles =\n baseHostContext.styles &&\n typeof baseHostContext.styles === \"object\" &&\n !Array.isArray(baseHostContext.styles)\n ? (baseHostContext.styles as McpUiHostContext[\"styles\"])\n : undefined;\n // The SDK validates styles.variables against the SEP key enum, so strip\n // host-specific custom properties before they enter ui/initialize. The\n // allowlist is fixed to the SEP enum (derived from `DEFAULT_HOST_STYLE`,\n // sourced via the host boundary and cached per definition by\n // `getSepHostStyleVariableKeys`), so this memo only depends on the inbound\n // configured variables (plus the stable `DEFAULT_HOST_STYLE` identity).\n const sepHostStyleVariableKeys = getSepHostStyleVariableKeys(\n resolvers.DEFAULT_HOST_STYLE\n );\n const configuredStyleVariables = useMemo(\n () =>\n sanitizeHostStyleVariables(\n configuredStyles?.variables,\n sepHostStyleVariableKeys\n ),\n [configuredStyles?.variables, sepHostStyleVariableKeys]\n );\n const mergedStyleVariables = useMemo(() => {\n return {\n ...styleVariables,\n ...(configuredStyleVariables &&\n Object.keys(configuredStyleVariables).length > 0\n ? configuredStyleVariables\n : {}),\n };\n }, [configuredStyleVariables, styleVariables]);\n const mergedStyles = useMemo<McpUiHostContext[\"styles\"]>(\n () => ({\n ...configuredStyles,\n variables: mergedStyleVariables,\n css: {\n ...configuredStyles?.css,\n fonts: configuredStyles?.css?.fonts ?? defaultFontCss,\n },\n }),\n [configuredStyles, defaultFontCss, mergedStyleVariables]\n );\n\n // containerDimensions (maxWidth/maxHeight) was previously sent here but\n // removed — width is now fully host-controlled.\n //\n // Matrix-gated HostContext fields (PR C of the foundation series):\n //\n // - `availableDisplayModes`: intersection of the matrix's allowed\n // modes with playground / draft configured modes, computed earlier\n // as `effectiveAvailableDisplayModes` so the runtime\n // `effectiveDisplayMode` clamp and the advertised list agree.\n //\n // - `toolInfo`: omitted entirely when `matrix.toolInfo === false`\n // (Microsoft 365 Copilot doesn't deliver this HostContext field\n // per its published Component-bridge table). A widget that\n // probes `app.getHostContext()?.toolInfo` on a simulated Copilot\n // host now correctly sees undefined — same as real Copilot. The\n // gate strips any inherited `toolInfo` from `baseHostContext`\n // too: a draft host context that pre-populates `toolInfo` would\n // otherwise leak through the spread and defeat the gate.\n const hostContext = useMemo<McpUiHostContext>(() => {\n // Strip toolInfo from the spread source so the matrix gate is\n // authoritative — if the matrix says off, no upstream value\n // (drafts, playground state) can reintroduce it via inheritance.\n const { toolInfo: _toolInfoFromBase, ...baseWithoutToolInfo } =\n baseHostContext as McpUiHostContext & { toolInfo?: unknown };\n const base: McpUiHostContext = {\n ...baseWithoutToolInfo,\n theme: resolvedTheme,\n displayMode: effectiveDisplayMode,\n // Publish the (host ∩ app) intersection here so the view sees the\n // narrowed set it can `requestDisplayMode` against. The current\n // `displayMode` above stays clamped to host-supported only.\n availableDisplayModes: advertisedAvailableDisplayModes,\n locale,\n timeZone,\n platform:\n baseHostContext.platform === \"web\" ||\n baseHostContext.platform === \"desktop\" ||\n baseHostContext.platform === \"mobile\"\n ? baseHostContext.platform\n : hostStyleDefinition.mcp.platform,\n userAgent: navigator.userAgent,\n deviceCapabilities,\n safeAreaInsets,\n styles: mergedStyles,\n };\n if (effectiveMcpAppsCapabilities.toolInfo) {\n base.toolInfo = {\n id: toolCallId,\n tool: {\n name: toolName,\n inputSchema:\n (toolMetadata?.inputSchema as {\n type: \"object\";\n properties?: Record<string, object>;\n required?: string[];\n }) ?? DEFAULT_INPUT_SCHEMA,\n description: toolMetadata?.description as string | undefined,\n },\n };\n }\n return base;\n }, [\n baseHostContext,\n resolvedTheme,\n effectiveDisplayMode,\n advertisedAvailableDisplayModes,\n locale,\n timeZone,\n deviceCapabilities,\n safeAreaInsets,\n mergedStyles,\n hostStyleDefinition,\n toolCallId,\n toolName,\n toolMetadata,\n effectiveMcpAppsCapabilities.toolInfo,\n ]);\n\n useEffect(() => {\n hostContextRef.current = hostContext;\n }, [hostContext]);\n\n // Resolve the effective sandbox policy ONCE, at component scope, so the\n // same value reaches three independent consumers without drift:\n // - the AppBridge constructor below (capability handshake)\n // - the <SandboxedIframe> below (browser-enforced CSP / Permission-Policy)\n // - the <McpAppsModal> below (its own sandboxed iframe for view_mode=modal)\n //\n // Computing this inside the bridge useEffect (the old shape) leaked the\n // policy into ONE consumer only — the iframe got the raw resource\n // declaration and the browser ignored the host clamp, which is exactly the\n // failure the shared resolver was supposed to prevent. The resolver is the\n // single source of truth; everything that mounts untrusted UI reads from\n // here.\n //\n // `effectivePermissive` collapses to `false` whenever a host policy applies\n // — SandboxedIframe treats `permissive: true` as \"skip CSP injection\n // entirely\", which would silently neuter the resolver output.\n const sandboxCspPolicy = useMemo(\n () => profileSandbox?.csp,\n [activeMcpProfileKey]\n );\n const sandboxPermissionsPolicy = useMemo(\n () => profileSandbox?.permissions,\n [activeMcpProfileKey]\n );\n // Inspector-only emission knobs sourced directly from the profile. They\n // bypass the SEP-1865 resolver because they model browser-emission state\n // that has no spec slot (raw `sandbox=`/`allow=` tokens, CSP source\n // expressions). Passed through unchanged to <SandboxedIframe>.\n const sandboxAttrsPolicy = useMemo(\n () => profileSandbox?.sandboxAttrs,\n [activeMcpProfileKey]\n );\n const allowFeaturesPolicy = useMemo(\n () => profileSandbox?.allowFeatures,\n [activeMcpProfileKey]\n );\n const cspDirectivesPolicy = useMemo(\n () => profileSandbox?.csp?.cspDirectives,\n [activeMcpProfileKey]\n );\n // Hosted-mode clamp for cspDirectives. The resolver's\n // `hostedClampExtraDeny` strips MCPJam app/API origins from the\n // widget-declared CSP (`restrictTo` + resource declaration), but\n // cspDirectives is inspector-only — it bypasses the resolver and the\n // proxy merges its tokens AFTER the resolver output, so without a\n // mirrored clamp here a hosted profile with e.g.\n // `cspDirectives: { \"connect-src\": [\"https://app.mcpjam.com\"] }`\n // re-adds the same-origin access the clamp is meant to make\n // non-bypassable. Strip any host-bearing token that resolves to the\n // mcpjam.com namespace AND scheme-wide tokens that would otherwise\n // cover MCPJam endpoints (`*`, `https:`, `http:`, `wss:`, `ws:`); CSP\n // keyword tokens (`'unsafe-eval'`, hashes, nonces — quoted with `'…'`)\n // and safe scheme-only tokens (`data:`, `blob:`, `about:`,\n // `filesystem:`, `mediastream:`) pass through unchanged.\n const cspDirectivesEffective = useMemo(() => {\n if (!cspDirectivesPolicy) return cspDirectivesPolicy;\n if (!host.surface.hostedMode) return cspDirectivesPolicy;\n const isClampBypass = (token: string) => {\n // `'self'` is a clamp bypass in hosted mode. The proxy is served\n // from the MCPJam origin and the inner srcdoc iframe carries\n // `allow-same-origin` (so its document origin = parent's =\n // MCPJam). `'self'` in the inner doc's CSP therefore resolves\n // to the MCPJam app origin, which lets an untrusted widget\n // fetch authenticated MCPJam endpoints — exactly what the clamp\n // is meant to make unreachable. Templates that need actual\n // same-origin access in production hosts (e.g. real Claude\n // where `'self'` resolves to claude.ai) should list the host\n // explicitly so the modeling is faithful in hosted mode too.\n if (token === \"'self'\") return true;\n if (token.startsWith(\"'\")) return false; // other CSP keywords\n // Scheme-wide tokens that cover MCPJam-namespace origins. The\n // clamp's purpose is to keep MCPJam app/API endpoints unreachable\n // from the iframe; `https:` (and friends) covers them just as\n // effectively as naming `https://app.mcpjam.com` directly.\n // Templates that need broad access should list specific origins\n // (e.g. Claude lists `https://esm.sh`, `https://assets.claude.ai`).\n if (token === \"*\") return true;\n if (/^(https?|wss?):$/i.test(token)) return true;\n // Other scheme-only tokens (data:, blob:, about:, filesystem:,\n // mediastream:) don't reach MCPJam origins — let through.\n if (/^[a-z]+:$/.test(token)) return false;\n // Host-bearing token: match mcpjam.com as a host component,\n // covering MCPJAM_HOSTED_CLAMP_ORIGINS (`https://*.mcpjam.com`\n // and `https://mcpjam.com`).\n return /(?:^|[/.@])mcpjam\\.com(?:[:/]|$)/i.test(token);\n };\n const out: Record<string, string[]> = {};\n for (const [k, tokens] of Object.entries(cspDirectivesPolicy)) {\n // Trim BEFORE the bypass check: an imported/saved profile can\n // carry \" https:\" or \" https://app.mcpjam.com\" with leading\n // whitespace, and the proxy's mergeDirective trims tokens before\n // emitting them — so the untrimmed string sneaks past\n // isClampBypass while the trimmed version still lands in the\n // output CSP, reintroducing the access the clamp is supposed to\n // remove. Normalize here so the filter and the proxy see the same\n // token shape.\n const clamped = tokens\n .map((t) => t.trim())\n .filter((t) => t.length > 0 && !isClampBypass(t));\n if (clamped.length > 0) out[k] = clamped;\n }\n return Object.keys(out).length > 0 ? out : undefined;\n }, [cspDirectivesPolicy]);\n const effectiveSandbox = useMemo<{\n csp: McpUiResourceCsp | undefined;\n permissions: McpUiResourcePermissions | undefined;\n permissive: boolean;\n hostPolicyApplied: boolean;\n sandboxAttrs: string[] | undefined;\n allowFeatures: Record<string, string> | undefined;\n cspDirectives: Record<string, string[]> | undefined;\n }>(() => {\n // Detect whether the host explicitly configured CSP hardening signals.\n // Hoisted above the permissive short-circuit so the permissive branch\n // can honor host-explicit `restrictTo` instead of silently dropping it;\n // the relaxed branch below reuses the same calculation. SEP-1865 host\n // policies are allowlist-only, so `restrictTo` and the hosted clamp are\n // the only hardening levers.\n const restrictToConfigured =\n sandboxCspPolicy?.restrictTo !== undefined &&\n Object.values(sandboxCspPolicy.restrictTo).some(\n (list) => Array.isArray(list) && list.length > 0\n );\n // cspDirectives is an inspector-only emission knob, but a populated\n // value is still an explicit \"I want this CSP shape\" signal. The\n // permissive shortcut below bypasses the proxy's `buildCSP(csp,\n // cspDirectives)` path (it builds its own fixed permissive CSP), so\n // without treating cspDirectives as hardening the configured\n // directives get silently dropped on the scenario/preview surfaces\n // where host profiles are most meant to apply.\n //\n // Only count entries that contribute at least one token that would\n // survive the proxy's mergeDirective filter (trim, plus `;,\\n\\r\"<>`\n // rejection — kept in lockstep with the predicate in\n // sandbox-proxy.html). An entry like `{ \"frame-src\": [] }` or\n // `{ \"frame-src\": [\" \"] }` is a semantic no-op and must not flip\n // a permissive surface into the resolver path (which would then\n // enforce the widget-declared CSP even though the named directive\n // contributes nothing).\n const cspDirectivesConfigured =\n sandboxCspPolicy?.cspDirectives !== undefined &&\n Object.values(sandboxCspPolicy.cspDirectives).some(\n (tokens) =>\n Array.isArray(tokens) &&\n tokens.some((t) => {\n if (typeof t !== \"string\") return false;\n const trimmed = t.trim();\n if (trimmed.length === 0) return false;\n if (/[;,\\n\\r\"<>]/.test(trimmed)) return false;\n return true;\n })\n );\n // Permissive means permissive — when the user explicitly toggles it in\n // the playground toolbar — ignore the saved profile's CSP hardening\n // (restrictTo, cspDirectives) and skip CSP injection entirely. Strict\n // applies the host profile.\n //\n // Scenario / minimal-mode surfaces also hardcode `cspMode = \"permissive\"`\n // (line 405) as a UX-friendliness default for end-user demos, NOT as a\n // user choice. The host's `restrictTo` / `cspDirectives` MUST still apply\n // there — otherwise a developer who configures `restrictTo: { connectDomains: [\"https://api.acme\"] }`\n // on their scenario host would have it honored on Connect → Chat but\n // silently dropped on the public scenario runtime / Sessions transcript.\n //\n // We can't gate on `isPlaygroundActive` alone: the Playground store is\n // localStorage and leaks across browsing contexts on the same origin\n // (see line 396), so a scenario preview iframe can read\n // `isPlaygroundActive = true` from the parent inspector tab even though\n // it's a scenario surface. Require `!isScenarioSurface && !minimalMode` so\n // the short-circuit is gated on the actual rendering surface, not just\n // the (leakable) playground flag.\n //\n // No HOSTED_MODE carve-out: PR #2164 moves the sandbox proxy to a separate\n // origin so the iframe is no longer same-origin with mcpjam.com, and a\n // permissive CSP can't be used to fetch /api/* with the user's session\n // cookies.\n //\n // Permissions policy still resolves below — it's orthogonal to CSP.\n const userTogglePermissive =\n cspMode === \"permissive\" &&\n isPlaygroundActive &&\n host.surface.kind !== \"scenario\" &&\n !minimalMode;\n if (userTogglePermissive) {\n let resolvedPermissions: McpUiResourcePermissions | undefined;\n if (sandboxPermissionsPolicy) {\n const resourcePermsMap: Record<string, boolean> = {};\n // Matrix-gated: `sandboxPermissions: false` means the\n // simulated host doesn't honor `_meta.ui.permissions`. Use\n // the gated value here too — the playground's permissive\n // CSP escape hatch is NOT a license to bypass host-level\n // permission gating. Three bots converged on this miss in\n // review of PR #2242.\n if (\n matrixGatedWidgetPermissions &&\n typeof matrixGatedWidgetPermissions === \"object\"\n ) {\n for (const [k, v] of Object.entries(\n matrixGatedWidgetPermissions as Record<string, unknown>\n )) {\n if (v) resourcePermsMap[k] = true;\n }\n }\n const resolved = resolveSandboxPermissions({\n resourcePermissions: resourcePermsMap,\n policy: sandboxPermissionsPolicy,\n hostedMode: host.surface.hostedMode,\n });\n const out: Record<string, Record<string, never>> = {};\n for (const name of Object.keys(resolved.granted)) {\n out[name] = {};\n }\n resolvedPermissions = out as McpUiResourcePermissions;\n }\n return {\n csp: undefined,\n // Same gate on the pass-through fallback: when no sandbox\n // policy applies, the playground's permissive surface MUST\n // NOT propagate widget-declared permissions that the host\n // matrix says to ignore.\n permissions: resolvedPermissions ?? matrixGatedWidgetPermissions,\n permissive: true,\n hostPolicyApplied: !!resolvedPermissions,\n sandboxAttrs: sandboxAttrsPolicy,\n allowFeatures: allowFeaturesPolicy,\n cspDirectives: cspDirectivesEffective,\n };\n }\n\n // \"relaxed\" CSP mode is an explicit dev escape hatch. The resolver\n // can't represent \"no restrictions\" as a domain list (CSP allow-\n // lists can't carry `*` without inviting the hosted clamp to strip\n // it), so PURE relaxed (no restrictTo, not hosted) short-circuits\n // the resolver and emits no CSP — preserves the dev experience.\n //\n // Any tightening signal — restrictTo or hostedMode — falls through\n // INTO the resolver so the documented guarantees hold:\n // * \"restrictTo applies in every mode\" — intersects in every mode\n // * \"hosted clamp is non-bypassable\" — the MCPJam-origin SDK-\n // internal strip must run in hosted mode regardless of saved profile\n //\n // The previous shape (`if (sandboxCspPolicy && !isRelaxedCsp)`)\n // skipped the resolver entirely on mode===\"relaxed\". A hosted user\n // could save a relaxed profile and silently opt out of the hosted\n // clamp's MCPJam-origin strip — P1 in production.\n const isPureRelaxedCsp =\n sandboxCspPolicy?.mode === \"relaxed\" &&\n !restrictToConfigured &&\n !cspDirectivesConfigured &&\n !host.surface.hostedMode;\n\n let resolvedCsp: McpUiResourceCsp | undefined;\n if (sandboxCspPolicy && !isPureRelaxedCsp) {\n const resolved = resolveSandboxCsp({\n // Matrix-gated: `cspFrameDomains` / `cspBaseUriDomains` off\n // strips those sub-fields from the widget-declared CSP before\n // the resolver sees them, simulating hosts (Microsoft 365\n // Copilot) that don't honor those `_meta.ui.csp.*` fields.\n resourceCsp: matrixGatedWidgetCsp,\n policy: sandboxCspPolicy,\n // \"host-default\" mode falls back to an EMPTY allowlist inside\n // the resolver when `hostDefaultBaseline` is omitted (per\n // SEP-1865 secure-default). For the inspector, the only sensible\n // default baseline we have is the resource's own declaration —\n // passing it here means \"host-default\" is restrictive only as\n // much as the resource itself asked for (never more, possibly\n // less if restrictTo narrows it). Without this, picking\n // \"host-default\" would silently emit `connect-src 'none'` and\n // break any widget that fetches external assets.\n hostDefaultBaseline: matrixGatedWidgetCsp,\n hostedMode: host.surface.hostedMode,\n // Defense in depth: in hosted mode strip any widget-declared\n // domain matching MCPJam's own app/API origins. A hosted widget\n // that declares `https://app.mcpjam.com/api/...` in\n // connectDomains could otherwise use the iframe as an\n // exfiltration channel via the user's authenticated session.\n // The list is hardcoded here (and not in the SDK) because\n // \"which origins count as MCPJam\" is an inspector concern, not\n // a shared SDK concern; the SDK just enforces what we pass.\n // Wildcard pattern strips all subdomains incl. staging/api.\n hostedClampExtraDeny: host.surface.hostedMode\n ? {\n // Spread the readonly constant into mutable arrays — the\n // SDK's `SandboxCspDomainSet` shape declares them as\n // `string[]`. Spreading per directive avoids accidental\n // aliasing if the SDK ever mutates internally.\n connectDomains: [...MCPJAM_HOSTED_CLAMP_ORIGINS],\n resourceDomains: [...MCPJAM_HOSTED_CLAMP_ORIGINS],\n frameDomains: [...MCPJAM_HOSTED_CLAMP_ORIGINS],\n baseUriDomains: [...MCPJAM_HOSTED_CLAMP_ORIGINS],\n }\n : undefined,\n });\n resolvedCsp = {\n connectDomains: resolved.connectDomains,\n resourceDomains: resolved.resourceDomains,\n frameDomains: resolved.frameDomains,\n baseUriDomains: resolved.baseUriDomains,\n };\n }\n let resolvedPermissions: McpUiResourcePermissions | undefined;\n if (sandboxPermissionsPolicy) {\n const resourcePermsMap: Record<string, boolean> = {};\n // Matrix-gated: `sandboxPermissions: false` means the simulated\n // host doesn't honor resource permissions at all. The gated\n // value is `undefined`, so the loop never runs and the\n // resolver's policy alone decides what's granted (typically\n // nothing, matching real Copilot which doesn't pipe widget-\n // declared permissions to the iframe).\n if (\n matrixGatedWidgetPermissions &&\n typeof matrixGatedWidgetPermissions === \"object\"\n ) {\n for (const [k, v] of Object.entries(\n matrixGatedWidgetPermissions as Record<string, unknown>\n )) {\n // SEP-1865 declares each permission as an empty object (`{}`)\n // when requested — i.e. a truthy value. Older shape gated on\n // `v !== undefined && v !== null` which would also accept\n // `false` / `0` / `\"\"` and silently coerce them to GRANTED.\n // Tighten to a truthiness check so a malformed widget that\n // declares `{ camera: false }` doesn't end up with camera\n // granted in the resolved permission set.\n if (v) resourcePermsMap[k] = true;\n }\n }\n const resolved = resolveSandboxPermissions({\n resourcePermissions: resourcePermsMap,\n policy: sandboxPermissionsPolicy,\n hostedMode: host.surface.hostedMode,\n });\n const out: Record<string, Record<string, never>> = {};\n for (const name of Object.keys(resolved.granted)) {\n out[name] = {};\n }\n resolvedPermissions = out as McpUiResourcePermissions;\n }\n const hostPolicyApplied =\n !!resolvedCsp || !!resolvedPermissions || isPureRelaxedCsp;\n return {\n // Pure relaxed → no CSP at all (caller's `permissive: true` below\n // tells SandboxedIframe to skip CSP injection). Otherwise pass\n // the resolver output through, falling back to the widget's own\n // derivation when no host CSP policy is in force.\n // Use matrix-gated CSP / permissions as the fallback too, so a\n // Copilot host whose matrix turns frameDomains off doesn't\n // accidentally pass the un-gated value to the iframe via the\n // `?? widgetCsp` branch.\n csp: isPureRelaxedCsp\n ? undefined\n : resolvedCsp ?? (widgetPermissive ? undefined : matrixGatedWidgetCsp),\n permissions: resolvedPermissions ?? matrixGatedWidgetPermissions,\n // A host-applied CSP MUST be honored at the browser layer. When\n // a restrictive host policy is in force, force `permissive: false`\n // so the SandboxedIframe injects the meta-CSP. In pure-relaxed\n // mode the host policy is \"permissive on purpose\" → force\n // `permissive: true` so the iframe doesn't inject any meta-CSP\n // at all. Without host-side CSP policy, pass the widget-derived\n // flag through.\n //\n // Gate ONLY on `resolvedCsp` (not `resolvedPermissions`): a\n // permissions-only profile (e.g. `mode: \"deny-all\"` for camera/\n // mic) used to flip `permissive: false` while `csp` stayed\n // undefined, which the sandbox proxy interprets as the SEP-1865\n // secure-default CSP (`default-src 'none'`, `connect-src 'none'`)\n // — silently breaking network access for permissive widgets.\n // Permissions and CSP are orthogonal user-facing knobs; tweaking\n // one must not reshape the other.\n permissive: isPureRelaxedCsp\n ? true\n : resolvedCsp\n ? false\n : widgetPermissive,\n hostPolicyApplied,\n sandboxAttrs: sandboxAttrsPolicy,\n allowFeatures: allowFeaturesPolicy,\n cspDirectives: cspDirectivesEffective,\n };\n }, [\n cspMode,\n isPlaygroundActive,\n host.surface.kind,\n minimalMode,\n sandboxCspPolicy,\n sandboxPermissionsPolicy,\n matrixGatedWidgetCsp,\n matrixGatedWidgetPermissions,\n widgetPermissive,\n sandboxAttrsPolicy,\n allowFeaturesPolicy,\n cspDirectivesEffective,\n ]);\n const effectiveSandboxKey = useMemo(\n () => stableStringifyJson(effectiveSandbox),\n [effectiveSandbox]\n );\n\n // `SandboxedIframe` keys its resource-ready payload on the resolved csp /\n // permissions / sandbox attrs, so any change here re-posts the HTML and the\n // View boots again. A violation recorded against the PREVIOUS policy no\n // longer describes what is on screen — without this, widening a profile to\n // unblock an App would leave the notice naming the origin that is now\n // allowed. Skip the first commit: the initial resolution is not a reload.\n const lastEffectiveSandboxKeyRef = useRef<string | null>(null);\n useEffect(() => {\n const previous = lastEffectiveSandboxKeyRef.current;\n lastEffectiveSandboxKeyRef.current = effectiveSandboxKey;\n if (previous === null || previous === effectiveSandboxKey) return;\n clearCspViolations(toolCallId);\n setFirstCspBlock(null);\n // Readiness deliberately NOT reset here. `effectiveSandboxKey` is also a\n // dependency of the bridge-connect effect below, which already does\n // `setIsReady(false)` when it re-runs — so a policy change resets\n // readiness exactly once, on the path that owns it. Duplicating it here\n // would be dead code that reads like a second source of truth.\n }, [effectiveSandboxKey, toolCallId, clearCspViolations]);\n\n // Publish the resolved sandbox payload into the widget-debug store so the\n // Sandbox debug panel can render it. `restrictTo` and `cspMode` come from\n // the source profile because the resolver intersects them in but doesn't\n // echo them back verbatim — surfacing both lets the matrix-shared grid show\n // the narrowing knobs even when they collapsed into an intersection.\n //\n // Follow-up: `sandboxAttrs` / `allowFeatures` are policy inputs to\n // `SandboxedIframe`; the literal emitted `sandbox=` / `allow=` strings are\n // joined and filtered inside that component and are NOT exposed here.\n // Exposing the final emitted attributes (via a ref or callback on\n // SandboxedIframe) is left as a follow-up; the resolved policy is enough\n // for \"why isn't this view rendering\" in the vast majority of cases.\n // hostInfo advertised in `ui/initialize` per SEP-1865. Sourced from the\n // active host profile's `mcpProfile.apps.uiInitialize.hostInfo` so the\n // panel's \"View iframe\" sub-card shows what a view actually receives.\n // Null when the host hasn't customized it — same fallback contract as\n // the matrix (canvasBuilder.ts:708).\n const sandboxHostInfo = useMemo<{\n name: string;\n version: string;\n } | null>(() => {\n const raw = profileHostInfo;\n if (!raw || typeof raw !== \"object\") return null;\n const name = (raw as { name?: unknown }).name;\n const version = (raw as { version?: unknown }).version;\n if (typeof name !== \"string\" || typeof version !== \"string\") return null;\n if (name.trim() === \"\" || version.trim() === \"\") return null;\n return { name, version };\n }, [activeMcpProfileKey]);\n const resolvedBridgeHostInfo = useMemo(\n () =>\n (resolvers.resolveHostInfo() ?? {\n name: \"mcpjam-inspector\",\n version: __APP_VERSION__,\n }) as { name: string; version: string },\n [activeMcpProfileKey]\n );\n const resolvedBridgeHostInfoKey = useMemo(\n () => stableStringifyJson(resolvedBridgeHostInfo),\n [resolvedBridgeHostInfo]\n );\n\n useEffect(() => {\n if (!toolCallId) return;\n setSandboxAppliedStore(\n toolCallId,\n {\n sandboxAttrs: effectiveSandbox.sandboxAttrs,\n allowFeatures: effectiveSandbox.allowFeatures,\n cspDirectives: effectiveSandbox.cspDirectives,\n permissive: effectiveSandbox.permissive,\n hostPolicyApplied: effectiveSandbox.hostPolicyApplied,\n restrictTo: sandboxCspPolicy?.restrictTo,\n cspMode: sandboxCspPolicy?.mode,\n permissions: effectiveSandbox.permissions,\n },\n undefined,\n sandboxHostInfo\n );\n }, [\n toolCallId,\n effectiveSandbox,\n sandboxCspPolicy,\n sandboxHostInfo,\n setSandboxAppliedStore,\n ]);\n\n // Keep bridge callbacks in sync before ResizeObserver/rAF-driven widget\n // messages can fire after a display-mode commit.\n useLayoutEffect(() => {\n onSendFollowUpRef.current = onSendFollowUp;\n onCallToolRef.current = onCallTool;\n onAppToolInvocationChangeRef.current = onAppToolInvocationChange;\n onRequestPipRef.current = onRequestPip;\n onExitPipRef.current = onExitPip;\n setDisplayModeRef.current = setDisplayMode;\n isPlaygroundActiveRef.current = isPlaygroundActive;\n playgroundDeviceTypeRef.current = playgroundDeviceType;\n effectiveDisplayModeRef.current = effectiveDisplayMode;\n serverIdRef.current = serverId;\n toolCallIdRef.current = toolCallId;\n displayWidgetIdRef.current = displayWidgetId;\n pipWidgetIdRef.current = pipWidgetId;\n ownsPipDisplayModeRef.current = ownsPipDisplayMode;\n toolsMetadataRef.current = toolsMetadata;\n onModelContextUpdateRef.current = onModelContextUpdate;\n onAppSupportedDisplayModesChangeRef.current =\n onAppSupportedDisplayModesChange;\n onRequestTeardownRef.current = onRequestTeardown;\n onConfirmDownloadRef.current = onConfirmDownload;\n }, [\n onSendFollowUp,\n onCallTool,\n onAppToolInvocationChange,\n onRequestPip,\n onExitPip,\n setDisplayMode,\n isPlaygroundActive,\n playgroundDeviceType,\n effectiveDisplayMode,\n serverId,\n toolCallId,\n displayWidgetId,\n pipWidgetId,\n ownsPipDisplayMode,\n toolsMetadata,\n onModelContextUpdate,\n onAppSupportedDisplayModesChange,\n onRequestTeardown,\n onConfirmDownload,\n ]);\n\n // Adapter: bind the renderer's refs / state setters / store callbacks to the\n // framework-free host bridge surface (`host-app-bridge.ts`). The shared\n // module owns the SEP-1865 correctness surface (capability gating,\n // model-only visibility, matrix-gated `sendToolCancelled`, the app-tool\n // invocation lifecycle); the renderer-specific effects below stay here.\n // The eval browser harness binds the same surface to its own callbacks.\n const registerBridgeHandlers = useCallback(\n (bridge: AppBridge) => {\n registerHostBridgeHandlers(bridge, {\n effectiveHostCapabilities,\n getMatrix: () => mcpAppsCapabilitiesRef.current,\n getToolMetadata: (name) => toolsMetadataRef.current?.[name],\n getToolCallId: () => toolCallIdRef.current,\n nextInvocationSequence: () => appToolInvocationSequenceRef.current++,\n onWidgetDebug: logWidgetDebug,\n callbacks: {\n onAppInitialized: (b) => {\n const wasReady = isReadyRef.current;\n setIsReady(true);\n isReadyRef.current = true;\n const appCaps = b.getAppCapabilities();\n logWidgetDebug(\"ui-to-host\", \"debug/app-initialized\", {\n availableDisplayModes:\n (appCaps?.availableDisplayModes as DisplayMode[] | undefined) ??\n null,\n wasReady,\n });\n const declaredAppModes = appCaps?.availableDisplayModes as\n | DisplayMode[]\n | undefined;\n onAppSupportedDisplayModesChangeRef.current?.(declaredAppModes);\n // SEP-1865: clamp the advertised + runtime mode set against the\n // app's declaration. The next render of `hostContext` will pick\n // up the new intersection and the post-init `setHostContext`\n // effect will publish `host-context-changed` with the updated\n // `availableDisplayModes` (matrix-gated by hostContextChanged).\n setAppSupportedDisplayModes(declaredAppModes);\n // If the guest re-initialized (e.g. an SDK-based app completing\n // its own handshake after the openai-compat shim already\n // initialized), bump reinitCount so the delivery effects re-send\n // tool data.\n if (wasReady) {\n setReinitCount((c) => c + 1);\n }\n\n // SEP-1865 App-Provided Tools: when the app advertises `tools`\n // capability, fetch its tool list with the SDK bridge and register\n // it so the next chat POST can advertise no-execute AI SDK tools.\n if (appCaps?.tools) {\n const bridgeId =\n appToolsBridgeIdRef.current ?? crypto.randomUUID();\n appToolsBridgeIdRef.current = bridgeId;\n setAppToolsBridgeIdState(bridgeId);\n void refreshAppProvidedTools(b, bridgeId);\n\n // SEP-1865 host UX: app-tools widgets are interactive — auto-\n // promote to fullscreen so the existing fullscreen overlay\n // becomes the chat surface. Gates: the app renders fullscreen,\n // the user hasn't dismissed fullscreen, and this is one-shot.\n if (\n !hasAutoPromotedForAppToolsRef.current &&\n !userPreferInlineRef.current &&\n declaredAppModes?.includes(\"fullscreen\")\n ) {\n hasAutoPromotedForAppToolsRef.current = true;\n setDisplayModeRef.current?.(\"fullscreen\");\n }\n }\n },\n onSendFollowUp: (text) => {\n onSendFollowUpRef.current?.(text);\n },\n onOpenLink: (url) => {\n window.open(url, \"_blank\", \"noopener,noreferrer\");\n },\n onCallTool: async (name, invocationInput) => {\n if (!onCallToolRef.current) {\n throw new Error(\"Tool calls not supported\");\n }\n // Apps-compat seam (§1D): the host returns a v2-client\n // CallToolResult; the bridge's onCallTool expects its own nominal\n // type (ext-apps v1-sdk peer). Erase across the version boundary.\n return (await onCallToolRef.current(\n name,\n invocationInput\n )) as never;\n },\n onAppToolInvocation: (update) => {\n onAppToolInvocationChangeRef.current?.(update);\n },\n onReadResource: async (uri) => {\n const result = await host.services.readResource(\n serverIdRef.current,\n uri,\n {\n forceHosted: webManagedServersRef.current,\n }\n );\n return result.content;\n },\n onListResources: async (params) => {\n return host.services.listResources(\n serverIdRef.current,\n (params as { cursor?: string } | undefined)?.cursor,\n { forceHosted: webManagedServersRef.current }\n );\n },\n onListResourceTemplates: async () => {\n // Routed through the WidgetHost boundary; the host service owns the\n // hosted / web-managed guard. Wrap the array to preserve the\n // bridge's `{ resourceTemplates }` response shape.\n const resourceTemplates = await host.services.listResourceTemplates(\n serverIdRef.current\n );\n return { resourceTemplates };\n },\n onListPrompts: async () => {\n const prompts = await host.services.listPrompts(\n serverIdRef.current,\n {\n forceHosted: webManagedServersRef.current,\n }\n );\n return { prompts };\n },\n onLoggingMessage: ({ level, data, logger }) => {\n if (minimalMode) return;\n const prefix = logger ? `[${logger}]` : \"[MCP Apps]\";\n const message = `${prefix} ${level.toUpperCase()}:`;\n if (\n level === \"error\" ||\n level === \"critical\" ||\n level === \"alert\"\n ) {\n console.error(message, data);\n return;\n }\n if (level === \"warning\") {\n console.warn(message, data);\n return;\n }\n console.info(message, data);\n },\n onSizeChange: ({ height }) => {\n // Inline width is owned by the host shell; height stays app-driven\n // for natural inline layout while PIP/fullscreen keep fixed sizing.\n if (effectiveDisplayModeRef.current !== \"inline\") return;\n const iframe = sandboxRef.current?.getIframeElement();\n if (!iframe) return;\n if (height === undefined) return;\n\n // If `box-sizing: border-box` applies to the outer iframe, add\n // border thickness to `height` to avoid a resize feedback loop.\n const style = getComputedStyle(iframe);\n const isBorderBox = style.boxSizing === \"border-box\";\n\n // Animate the change for a smooth transition.\n const from: Keyframe = {};\n const to: Keyframe = {};\n\n let adjustedHeight = height;\n\n if (adjustedHeight !== undefined) {\n if (isBorderBox) {\n adjustedHeight +=\n parseFloat(style.borderTopWidth) +\n parseFloat(style.borderBottomWidth);\n }\n from.height = `${iframe.offsetHeight}px`;\n iframe.style.height = to.height = `${adjustedHeight}px`;\n lastInlineHeightRef.current = `${adjustedHeight}px`;\n }\n\n iframe.animate([from, to], { duration: 300, easing: \"ease-out\" });\n },\n onRequestDisplayMode: async ({ mode }) => {\n const requestedMode = mode ?? \"inline\";\n // Host policy gate: SEP-1865 allows the host to decline\n // widget-initiated `ui/request-display-mode`.\n const policy =\n mcpAppsCapabilitiesRef.current?.widgetDisplayModeRequests ??\n \"accept\";\n if (requestedMode !== \"inline\" && policy === \"decline\") {\n const granted = effectiveDisplayModeRef.current;\n logWidgetDebug(\"ui-to-host\", \"ui/request-display-mode\", {\n requested: requestedMode,\n granted,\n reason: \"policy-decline\",\n });\n return { mode: granted };\n }\n // Sticky inline-preference override — `user-initiated-only` ONLY.\n // Under that policy a user dismissal (or the mount seed) pins the\n // widget to inline until the user re-opens a non-inline mode from\n // the host picker, so a view can't re-grab fullscreen on every\n // `host-context-changed`.\n //\n // `accept` deliberately skips this gate: that policy means the\n // host honors widget-initiated requests, and the flag is also set\n // by the host's own close chrome. Applying it here let a single X\n // click mute `ui/request-display-mode` for the rest of the\n // widget's life — an app's own display-mode buttons went dead\n // after the user closed PIP or fullscreen once, with no way back\n // except the host picker.\n if (\n requestedMode !== \"inline\" &&\n policy === \"user-initiated-only\" &&\n userPreferInlineRef.current\n ) {\n logWidgetDebug(\"ui-to-host\", \"ui/request-display-mode\", {\n requested: requestedMode,\n granted: \"inline\",\n reason: \"user-prefers-inline\",\n });\n return { mode: \"inline\" };\n }\n const hostAvailableModes = resolvers.extractHostDisplayModes(\n hostContextRef.current as Record<string, unknown> | undefined\n );\n // Use device type for mobile detection (defaults to mobile-like\n // behavior when not in playground).\n const isMobile = isPlaygroundActiveRef.current\n ? playgroundDeviceTypeRef.current === \"mobile\" ||\n playgroundDeviceTypeRef.current === \"tablet\"\n : true;\n const mobileAdjustedMode: DisplayMode =\n isMobile && requestedMode === \"pip\"\n ? \"fullscreen\"\n : requestedMode;\n // A request for a mode the host doesn't advertise is REFUSED,\n // not silently rewritten. `clampDisplayModeToAvailableModes`\n // falls back to `availableDisplayModes[0]` — \"inline\" in every\n // preset — which turned an unavailable-mode request into a\n // forced mode CHANGE: a widget sitting in PIP that asked for\n // fullscreen (e.g. because its declared\n // `appCapabilities.availableDisplayModes` omits fullscreen, so\n // the advertised host ∩ app set does too) got dropped to inline\n // instead of staying where it was. Hold the current mode, the\n // same shape the `decline` policy branch above uses.\n if (!hostAvailableModes.includes(mobileAdjustedMode)) {\n const granted = effectiveDisplayModeRef.current;\n logWidgetDebug(\"ui-to-host\", \"ui/request-display-mode\", {\n requested: requestedMode,\n granted,\n reason: \"mode-unavailable\",\n });\n return { mode: granted };\n }\n const actualMode = mobileAdjustedMode;\n\n setDisplayModeRef.current(actualMode);\n\n if (actualMode === \"pip\") {\n onRequestPipRef.current?.(displayWidgetIdRef.current);\n } else if (\n (actualMode === \"inline\" || actualMode === \"fullscreen\") &&\n ownsPipDisplayModeRef.current\n ) {\n onExitPipRef.current?.(\n pipWidgetIdRef.current ?? displayWidgetIdRef.current\n );\n }\n\n return { mode: actualMode };\n },\n onUpdateModelContext: (\n ctxToolCallId,\n { content, structuredContent }\n ) => {\n // Store in debug store for UI display.\n setWidgetModelContextRef.current(ctxToolCallId, {\n content,\n structuredContent,\n });\n // Notify parent component to queue for next model turn.\n onModelContextUpdateRef.current?.(ctxToolCallId, {\n content,\n structuredContent,\n });\n },\n onDownloadFile: async ({ contents }) => {\n // SEP-1865 `ui/download-file`: the host mediates the download\n // since the iframe sandbox blocks direct anchor-clicks. Blob +\n // object-URL anchor.\n //\n // Confirmation runs BEFORE the try/catch below. Per the ext-apps\n // `App.downloadFile` contract, a user cancellation / host denial\n // resolves `{ isError: true }` (the widget's documented\n // `if (result.isError)` path) — a throw is reserved for\n // transport/timeout, so a denial must RETURN isError, not throw, or\n // the widget skips its denial handling and may surface an unhandled\n // rejection. When the host supplies no confirmer, downloads proceed\n // unprompted (back-compat for other embedders of the package).\n const confirmDownload = onConfirmDownloadRef.current;\n if (confirmDownload) {\n for (const item of contents) {\n let info: {\n kind: \"resource\" | \"resource_link\";\n filename?: string;\n mimeType?: string;\n uri?: string;\n };\n if (item.type === \"resource\" && item.resource) {\n const res = item.resource as {\n uri: string;\n mimeType?: string;\n };\n info = {\n kind: \"resource\",\n filename: res.uri.split(\"/\").pop() || undefined,\n mimeType: res.mimeType,\n uri: res.uri,\n };\n } else if (item.type === \"resource_link\") {\n const link = item as { uri: string; mimeType?: string };\n // Reject a non-http(s) resource_link up front, before\n // prompting — the download loop below enforces the same\n // scheme gate, so prompting for a link we'll refuse anyway\n // would show the user a misleading confirmation.\n if (toSafeDownloadLinkUrl(link.uri) === null) {\n return { isError: true };\n }\n info = {\n kind: \"resource_link\",\n filename: link.uri.split(\"/\").pop() || undefined,\n mimeType: link.mimeType,\n uri: link.uri,\n };\n } else {\n continue;\n }\n const approved = await confirmDownload(info);\n if (!approved) {\n return { isError: true };\n }\n }\n }\n try {\n for (const item of contents) {\n if (item.type === \"resource\" && item.resource) {\n const res = item.resource as {\n uri: string;\n text?: string;\n blob?: string;\n mimeType?: string;\n };\n const mimeType = res.mimeType ?? \"application/octet-stream\";\n let blob: Blob;\n if (typeof res.blob === \"string\") {\n const binary = atob(res.blob);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n blob = new Blob([bytes], { type: mimeType });\n } else {\n blob = new Blob([res.text ?? \"\"], { type: mimeType });\n }\n const url = URL.createObjectURL(blob);\n try {\n const anchor = document.createElement(\"a\");\n anchor.href = url;\n anchor.download = res.uri.split(\"/\").pop() ?? \"download\";\n anchor.rel = \"noopener\";\n document.body.appendChild(anchor);\n anchor.click();\n anchor.remove();\n } finally {\n // Defer revocation so the browser can start the download\n // before the object URL goes away.\n setTimeout(() => URL.revokeObjectURL(url), 1000);\n }\n } else if (item.type === \"resource_link\") {\n const link = item as { uri: string };\n // Refuse navigations that aren't a browser-fetchable scheme\n // (shared gate with the pre-prompt check above).\n const safeHref = toSafeDownloadLinkUrl(link.uri);\n if (safeHref === null) {\n throw new Error(`Unsupported download URI: ${link.uri}`);\n }\n window.open(safeHref, \"_blank\", \"noopener,noreferrer\");\n }\n }\n return {};\n } catch (err) {\n logWidgetDebug(\"ui-to-host\", \"ui/download-file\", {\n error: err instanceof Error ? err.message : String(err),\n });\n return { isError: true };\n }\n },\n onRequestTeardown: (ctxToolCallId) => {\n onRequestTeardownRef.current?.(\n ctxToolCallId,\n displayWidgetIdRef.current\n );\n },\n },\n });\n },\n [\n setIsReady,\n logWidgetDebug,\n refreshAppProvidedTools,\n effectiveHostCapabilitiesKey,\n ]\n );\n\n useEffect(() => {\n if (!widgetHtml) return;\n if (!sandboxProxyReady) {\n logWidgetDebug(\"host-to-ui\", \"debug/bridge-connect-skipped\", {\n reason: \"sandbox-proxy-not-ready\",\n });\n return;\n }\n const iframe = sandboxRef.current?.getIframeElement();\n if (!iframe?.contentWindow) {\n logWidgetDebug(\"host-to-ui\", \"debug/bridge-connect-skipped\", {\n reason: \"missing-iframe-content-window\",\n });\n return;\n }\n\n setBridgeTransportReady(false);\n setIsReady(false);\n isReadyRef.current = false;\n logWidgetDebug(\"host-to-ui\", \"debug/bridge-connect-start\", {\n cspMode,\n // Reflect the resolved (host-policy-applied) sandbox so the debug\n // panel matches what the iframe and bridge will actually see.\n hasCsp: !!effectiveSandbox.csp,\n hasPermissions: !!effectiveSandbox.permissions,\n htmlLength: widgetHtml.length,\n permissive: effectiveSandbox.permissive,\n hostPolicyApplied: effectiveSandbox.hostPolicyApplied,\n toolState: toolState ?? null,\n });\n\n // Sandbox policy is resolved once at component scope (see\n // `effectiveSandbox` above) and reused here so the AppBridge handshake\n // and the rendered <SandboxedIframe> stay in lockstep. Computing this\n // inline used to be the canonical correctness bug: the bridge got the\n // resolved policy while the iframe still got the raw resource\n // declaration, so the browser-enforced CSP didn't honor the host clamp.\n // Host identity advertised in ui/initialize. Templates that emulate\n // another host (e.g. ChatGPT) override this via\n // `mcpProfile.apps.uiInitialize.hostInfo`; backend soft-validates\n // name+version when set so the cast below is safe.\n const bridge = new AppBridge(\n null,\n resolvedBridgeHostInfo,\n {\n ...effectiveHostCapabilities,\n sandbox: {\n csp: effectiveSandbox.csp,\n permissions: effectiveSandbox.permissions,\n },\n },\n { hostContext: hostContextRef.current ?? {} }\n );\n\n registerBridgeHandlers(bridge);\n bridgeRef.current = bridge;\n const pendingRpcMethods = new Map<string | number, string>();\n\n const transport = new LoggingTransport(\n new PostMessageTransport(iframe.contentWindow, iframe.contentWindow),\n {\n onSend: (message) => {\n const method = extractMethod(message, \"mcp-apps\");\n const request = message as { id?: string | number; method?: string };\n if (\n typeof request.method === \"string\" &&\n (typeof request.id === \"string\" || typeof request.id === \"number\")\n ) {\n pendingRpcMethods.set(request.id, request.method);\n }\n if (SUPPRESSED_UI_LOG_METHODS.has(method)) return;\n logUiEventRef.current({\n widgetId: toolCallIdRef.current,\n serverId: serverIdRef.current,\n direction: \"host-to-ui\",\n protocol: \"mcp-apps\",\n method,\n message,\n });\n },\n onReceive: (message) => {\n const response = message as {\n id?: string | number;\n result?: unknown;\n error?: unknown;\n };\n const correlatedMethod =\n (response.result !== undefined || response.error !== undefined) &&\n (typeof response.id === \"string\" || typeof response.id === \"number\")\n ? pendingRpcMethods.get(response.id)\n : undefined;\n if (correlatedMethod && response.id !== undefined) {\n pendingRpcMethods.delete(response.id);\n }\n const method = correlatedMethod ?? extractMethod(message, \"mcp-apps\");\n if (method === \"ui/notifications/size-changed\") {\n signalStreamingRender();\n }\n if (method === \"notifications/tools/list_changed\") {\n const bridgeId = appToolsBridgeIdRef.current;\n if (bridgeId) {\n void refreshAppProvidedTools(bridge, bridgeId, { force: true });\n }\n }\n if (SUPPRESSED_UI_LOG_METHODS.has(method)) return;\n logUiEventRef.current({\n widgetId: toolCallIdRef.current,\n serverId: serverIdRef.current,\n direction: \"ui-to-host\",\n protocol: \"mcp-apps\",\n method,\n message,\n });\n },\n }\n );\n\n let isActive = true;\n bridge\n .connect(transport)\n .then(() => {\n if (!isActive) return;\n setBridgeTransportReady(true);\n logWidgetDebug(\"host-to-ui\", \"debug/bridge-connect-ready\", {\n htmlLength: widgetHtml.length,\n });\n })\n .catch((error) => {\n if (!isActive) return;\n const errorMessage =\n error instanceof Error ? error.message : \"Failed to connect MCP App\";\n setLoadError(errorMessage);\n logWidgetDebug(\"host-to-ui\", \"debug/bridge-connect-error\", {\n error: errorMessage,\n });\n });\n\n return () => {\n isActive = false;\n logWidgetDebug(\"host-to-ui\", \"debug/bridge-connect-cleanup\", {\n wasReady: isReadyRef.current,\n });\n bridgeRef.current = null;\n // SEP-1865 App-Provided Tools: drop this bridge's registration so\n // the next chat POST snapshot omits its aliases. Per spec: \"Calling\n // a tool from a closed app MUST return an error\" — once the bridge\n // is closed, any in-flight `useChat.onToolCall` dispatch resolves\n // to null in `useAppToolsRegistry.resolve()`.\n if (appToolsBridgeIdRef.current) {\n useAppToolsRegistry\n .getState()\n .unregisterInstance(appToolsBridgeIdRef.current);\n appToolsListedBridgeIdsRef.current.delete(appToolsBridgeIdRef.current);\n appToolsListInFlightBridgeIdsRef.current.delete(\n appToolsBridgeIdRef.current\n );\n appToolsListRefreshPendingBridgeIdsRef.current.delete(\n appToolsBridgeIdRef.current\n );\n appToolsBridgeIdRef.current = null;\n setAppToolsBridgeIdState(null);\n }\n // SEP-1865: the host MUST send `ui/resource-teardown` before tearing the\n // view down (so it can flush/persist), and SHOULD wait for the ack. We\n // send the teardown request — the outbound message is posted before\n // close() — but deliberately DO NOT await the ack: this cleanup also runs\n // when the widget is reloaded/replaced, and the outer sandbox-proxy\n // iframe is reused for the next resource. Keeping this (now stale) bridge\n // subscribed while a replacement bridge attaches to the SAME proxy window\n // would let both answer the new widget's JSON-RPC (duplicate `ui/initialize`\n // / stale responses). Detaching synchronously is the only way to guarantee\n // the stale transport stops handling messages before the new one starts;\n // the ack, if it arrives, lands after close() and is harmlessly dropped.\n if (isReadyRef.current) {\n bridge.teardownResource({}).catch(() => {});\n }\n bridge.close().catch(() => {});\n // Clear model context on widget teardown\n setWidgetModelContextRef.current(toolCallIdRef.current, null);\n };\n }, [\n widgetHtml,\n sandboxProxyReady,\n registerBridgeHandlers,\n refreshAppProvidedTools,\n // Bridge must rebuild when the resolved sandbox policy changes — a host\n // toggling sandbox policy at runtime needs the new handshake. The memo\n // identity key captures `widgetCsp`/`widgetPermissions`/`widgetPermissive`\n // and the sandbox slice of mcpProfile transitively without treating\n // reference-only object churn as a reload signal.\n effectiveSandboxKey,\n logWidgetDebug,\n // Bridge must rebuild when the advertised host capabilities change\n // (host style switch or override edit) so the new handshake reflects\n // the new contract.\n effectiveHostCapabilitiesKey,\n // Bridge must rebuild when the host identity advertised in\n // ui/initialize changes — switching to a template that overrides\n // hostInfo (e.g. ChatGPT) is observable to the View.\n resolvedBridgeHostInfoKey,\n ]);\n\n useEffect(() => {\n const bridge = bridgeRef.current;\n if (!bridge || !isReady) return;\n // `bridge.setHostContext` updates the AppBridge's cached\n // `_hostContext` AND emits `ui/notifications/host-context-changed`\n // to the View. Matrix gate: Microsoft 365 Copilot does not\n // deliver this notification per its published Component-bridge\n // table (theme / displayMode updates are one-shot at\n // `ui/initialize` time on that host). Null matrix → default on.\n //\n // We still skip the call entirely when gated rather than only\n // suppressing the wire notification — the bridge's internal\n // cache also tracks `_hostContext`, but on Copilot-style hosts\n // the spec says it doesn't update mid-session, so keeping the\n // cache frozen matches the simulated host's behavior. (If a\n // future host wants the cache to update without emitting the\n // notification, we'll split this gate.)\n const matrix = mcpAppsCapabilitiesRef.current;\n if (matrix !== null && matrix.hostContextChanged === false) return;\n bridge.setHostContext(hostContext);\n }, [hostContext, isReady]);\n\n const handleCspViolation = useCallback(\n (event: MessageEvent) => {\n const data = event.data;\n if (!data) return;\n\n const {\n directive,\n blockedUri,\n sourceFile,\n lineNumber,\n columnNumber,\n effectiveDirective,\n timestamp,\n } = data;\n\n logUiEvent({\n widgetId: toolCallId,\n serverId,\n direction: \"ui-to-host\",\n protocol: \"mcp-apps\",\n method: \"csp-violation\",\n message: data,\n });\n\n addCspViolation(toolCallId, {\n directive,\n effectiveDirective,\n blockedUri,\n sourceFile,\n lineNumber,\n columnNumber,\n timestamp: timestamp || Date.now(),\n });\n\n // Remember the first block so the render path can explain a View\n // that never boots. Cleared on every reload alongside the debug\n // store's violation list.\n setFirstCspBlock(\n (prev) =>\n prev ?? {\n directive:\n typeof effectiveDirective === \"string\" && effectiveDirective\n ? effectiveDirective\n : typeof directive === \"string\"\n ? directive\n : undefined,\n blockedUri: typeof blockedUri === \"string\" ? blockedUri : undefined,\n }\n );\n\n if (!minimalMode) {\n console.warn(\n `[MCP Apps CSP Violation] ${directive}: Blocked ${blockedUri}`,\n sourceFile ? `at ${sourceFile}:${lineNumber}:${columnNumber}` : \"\"\n );\n }\n },\n [addCspViolation, logUiEvent, minimalMode, serverId, toolCallId]\n );\n\n const handleSandboxMessage = (event: MessageEvent) => {\n const data = event.data;\n if (!data) return;\n\n // Handle CSP violation messages (custom type)\n if (data.type === \"mcp-apps:csp-violation\") {\n handleCspViolation(event);\n return;\n }\n\n // Tier 2 recorder: forward captured steps + readiness to the host.\n if (data.type === \"recorder:step\") {\n recorderDebug(\"step from sandbox\", {\n toolName,\n toolCallId,\n recordMode: !!recordMode,\n });\n onRecorderStep?.(data.step);\n return;\n }\n if (data.type === \"recorder:ready\") {\n recorderDebug(\"ready from sandbox\", {\n toolName,\n toolCallId,\n recordMode: !!recordMode,\n });\n onRecorderReady?.();\n return;\n }\n // Replay: resolve the pending step promise the guest is answering.\n if (data.type === \"recorder:replay-result\") {\n const pending =\n typeof data.id === \"number\"\n ? pendingReplaysRef.current.get(data.id)\n : undefined;\n if (pending) {\n clearTimeout(pending.timer);\n pendingReplaysRef.current.delete(data.id);\n pending.resolve({\n ok: !!data.ok,\n reason: data.reason,\n deferred: data.deferred,\n });\n }\n return;\n }\n\n // Defense-in-depth: if the live capability matrix has the file ops\n // disabled, drop incoming `openai:uploadFile` / `getFileDownloadUrl`\n // messages from the iframe. Other fire-and-forget `openai:*`\n // messages below use the same live matrix gate. The SDK runtime\n // should already be omitting disabled methods (so widgets that\n // feature-detect take the fallback path), but a widget that captured\n // a method reference before a host swap, or hand-crafted the\n // postMessage, would still reach here. Send a clear policy error\n // back for pending-call file helpers so the widget's resolver\n // rejects rather than hanging.\n //\n // STRICT `=== false` semantics: the persisted/sparse\n // `OpenAiAppsCapabilities` shape omits fields added after capture\n // time, and the SDK runtime treats missing as \"default on\"\n // (FULL_SURFACE_DEFAULT). Mirroring that here means an absent\n // field is allowed, not denied — only an explicit `false` triggers\n // the gate. `!liveCaps.foo` would lock out forward-compatible\n // legacy snapshots; `liveCaps.foo === false` matches the runtime.\n const liveCaps = liveOpenAiCompatCapabilitiesRef.current;\n const policyError = (\n callId: number,\n method: \"openai:uploadFile\" | \"openai:getFileDownloadUrl\"\n ) => {\n sandboxRef.current?.postMessage({\n type: `${method}:response`,\n callId,\n error: `${method} denied by host capability policy`,\n });\n };\n\n // Handle file upload messages (non-JSON-RPC, same protocol as ChatGPT widget)\n if (data.type === \"openai:uploadFile\") {\n if (liveCaps !== null && liveCaps.uploadFile === false) {\n policyError(data.callId, \"openai:uploadFile\");\n return;\n }\n void handleUploadFileMessage(\n data,\n (message) => {\n sandboxRef.current?.postMessage(message);\n },\n {\n authFetch: host.services.authFetch,\n hostedMode: host.surface.hostedMode,\n }\n );\n return;\n }\n\n if (data.type === \"openai:getFileDownloadUrl\") {\n if (liveCaps !== null && liveCaps.getFileDownloadUrl === false) {\n policyError(data.callId, \"openai:getFileDownloadUrl\");\n return;\n }\n handleGetFileDownloadUrlMessage(\n data,\n (message) => {\n sandboxRef.current?.postMessage(message);\n },\n { hostedMode: host.surface.hostedMode }\n );\n return;\n }\n\n // Apps SDK widget-state persistence (forwarded from the compat\n // runtime in the inner iframe). Two destinations:\n // 1) onWidgetStateChange — propagates upward for saved-view /\n // replay / fork persistence (matches the legacy\n // ChatGPTAppRenderer contract).\n // 2) setWidgetStateStore — keeps the Debug \"Widget State\" panel\n // live; without it, Apps SDK setWidgetState updates silently\n // bypass the diagnostics surface that reads from\n // widgetDebugInfo.widgetState.\n if (data.type === \"openai:setWidgetState\") {\n // Defense-in-depth: drop persistence + propagation when the\n // matrix has setWidgetState disabled. Silent drop (no response\n // message) — setWidgetState is fire-and-forget in the spec, so\n // there's nothing to reject. Mirrors the runtime-level omission.\n if (liveCaps !== null && liveCaps.setWidgetState === false) return;\n if (onWidgetStateChange) {\n onWidgetStateChange(toolCallId, data.state);\n }\n setWidgetStateStore(toolCallId, data.state);\n return;\n }\n\n if (data.type === \"openai:setOpenInAppUrl\") {\n if (liveCaps !== null && liveCaps.setOpenInAppUrl === false) return;\n const nextUrl = resolveOpenInAppHref(data.href, explicitOpenInAppBaseUrl);\n if (nextUrl) {\n setOpenInAppUrlOverride(nextUrl);\n }\n return;\n }\n\n // Handle openai/* JSON-RPC notifications from the compat layer\n if (\n data.jsonrpc === \"2.0\" &&\n typeof data.method === \"string\" &&\n data.method.startsWith(\"openai/\")\n ) {\n logUiEvent({\n widgetId: toolCallId,\n serverId,\n direction: \"ui-to-host\",\n protocol: \"mcp-apps\",\n method: data.method,\n message: data,\n });\n\n // Defense-in-depth for the openai/* JSON-RPC notification family.\n // Same rationale as the file-op branch above: SDK runtime should\n // omit these methods, but a stale closure or hand-crafted\n // postMessage would still arrive. Silent drop on notifications;\n // requestCheckout uses a callId pattern so we respond with an\n // error so the widget's pending resolver doesn't hang.\n if (data.method === \"openai/requestModal\") {\n if (liveCaps !== null && liveCaps.requestModal === false) return;\n const params = data.params ?? {};\n setModalTitle(params.title || \"Modal\");\n setModalParams(params.params || {});\n setModalTemplate(params.template || null);\n setModalOpen(true);\n } else if (data.method === \"openai/requestClose\") {\n if (liveCaps !== null && liveCaps.requestClose === false) return;\n setModalOpen(false);\n } else if (data.method === \"openai/requestCheckout\") {\n const params = data.params ?? {};\n const { callId: cId, ...sessionData } = params;\n if (liveCaps !== null && liveCaps.requestCheckout === false) {\n sandboxRef.current?.postMessage({\n jsonrpc: \"2.0\",\n method: \"openai/requestCheckout:response\",\n params: {\n callId: cId,\n error: \"openai/requestCheckout denied by host capability policy\",\n },\n });\n return;\n }\n setCheckoutCallId(cId as number);\n setCheckoutSession(sessionData);\n setCheckoutOpen(true);\n }\n }\n };\n const showWidget = isReady && canRenderStreamingInput;\n\n // An App whose own resources were blocked by CSP never signals ready, so\n // the iframe sits at `opacity: 0` forever — indistinguishable from a hang.\n // Surface the block instead, after a grace period so a View that boots\n // despite a blocked optional asset never flashes the notice.\n const [cspBlockedNoticeVisible, setCspBlockedNoticeVisible] = useState(false);\n useEffect(() => {\n if (!firstCspBlock || isReady) {\n setCspBlockedNoticeVisible(false);\n return;\n }\n const timer = window.setTimeout(\n () => setCspBlockedNoticeVisible(true),\n CSP_BLOCKED_NOTICE_DELAY_MS\n );\n return () => window.clearTimeout(timer);\n }, [firstCspBlock, isReady]);\n const showCspBlockedNotice = cspBlockedNoticeVisible && !showWidget;\n\n useEffect(() => {\n logWidgetDebug(\"host-to-ui\", \"debug/widget-visibility\", {\n bridgeTransportReady,\n canRenderStreamingInput,\n hasWidgetHtml,\n isReady,\n loadError,\n showWidget,\n toolState: toolState ?? null,\n widgetHtmlLength,\n });\n }, [\n bridgeTransportReady,\n canRenderStreamingInput,\n hasWidgetHtml,\n isReady,\n loadError,\n showWidget,\n toolState,\n widgetHtmlLength,\n logWidgetDebug,\n ]);\n\n useEffect(() => {\n if (!bridgeTransportReady || !widgetHtml) return;\n logWidgetDebug(\"host-to-ui\", \"debug/sandbox-html-ready\", {\n hasCsp: !!effectiveSandbox.csp,\n hasPermissions: !!effectiveSandbox.permissions,\n htmlLength: widgetHtml.length,\n permissive: effectiveSandbox.permissive,\n hostPolicyApplied: effectiveSandbox.hostPolicyApplied,\n });\n }, [bridgeTransportReady, widgetHtml, effectiveSandbox, logWidgetDebug]);\n\n const respondToCheckout = useCallback(\n (result: unknown, error?: string) => {\n if (checkoutCallId == null) return;\n const params: Record<string, unknown> = { callId: checkoutCallId };\n if (error) {\n params.error = error;\n } else {\n params.result = result;\n }\n sandboxRef.current?.postMessage({\n jsonrpc: \"2.0\",\n method: \"openai/requestCheckout:response\",\n params,\n });\n setCheckoutOpen(false);\n setCheckoutSession(null);\n setCheckoutCallId(null);\n },\n [checkoutCallId]\n );\n\n // Denied state\n if (toolState === \"output-denied\") {\n return (\n <div className=\"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2\">\n Tool execution was denied.\n </div>\n );\n }\n\n if (loadError) {\n return (\n <div className=\"border border-destructive/40 bg-destructive/10 text-destructive text-xs rounded-md px-3 py-2\">\n Failed to load MCP App: {loadError}\n </div>\n );\n }\n\n if (!widgetHtml) {\n return null;\n }\n\n const isPip = effectiveDisplayMode === \"pip\";\n const isFullscreen = effectiveDisplayMode === \"fullscreen\";\n const isMobilePlaygroundMode =\n isPlaygroundActive && playgroundDeviceType === \"mobile\";\n const isContainedFullscreenMode =\n isPlaygroundActive &&\n (playgroundDeviceType === \"mobile\" || playgroundDeviceType === \"tablet\");\n const showOpenInAppButton =\n isFullscreen && !!openInAppUrl && !isMobilePlaygroundMode;\n\n const containerClassName = (() => {\n if (isFullscreen) {\n if (isContainedFullscreenMode) {\n return \"absolute inset-0 z-10 w-full h-full bg-background flex flex-col\";\n }\n return \"fixed inset-0 z-40 w-full h-full bg-background flex flex-col\";\n }\n\n if (isPip) {\n if (isMobilePlaygroundMode) {\n return \"absolute inset-0 z-10 w-full h-full bg-background flex flex-col\";\n }\n if (isPlaygroundActive) {\n return [\n \"absolute top-4 left-1/2 -translate-x-1/2 z-40 w-full min-w-[300px] max-w-[min(90vw,1200px)] space-y-2\",\n \"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80\",\n \"shadow-xl border border-border/60 rounded-xl p-3\",\n ].join(\" \");\n }\n return [\n \"fixed top-4 left-1/2 -translate-x-1/2 z-40 w-full min-w-[300px] max-w-[min(90vw,1200px)] space-y-2\",\n \"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80\",\n \"shadow-xl border border-border/60 rounded-xl p-3\",\n ].join(\" \");\n }\n\n return \"mt-3 space-y-2 relative group\";\n })();\n const canTransitionHeight =\n !isFullscreen && effectiveDisplayModeRef.current === effectiveDisplayMode;\n const iframeStyle: CSSProperties = {\n height: isFullscreen\n ? \"100%\"\n : isPip\n ? PIP_MAX_HEIGHT\n : lastInlineHeightRef.current,\n width: \"100%\",\n maxWidth: \"100%\",\n backgroundColor:\n !isFullscreen && matrixGatedPrefersBorder\n ? mergedStyleVariables[\"--color-background-primary\"]\n : hostChatBackground ?? \"transparent\",\n opacity: showWidget ? 1 : 0,\n transition: [\n \"opacity 150ms ease-in\",\n canTransitionHeight ? \"height 300ms ease-out\" : \"\",\n ]\n .filter(Boolean)\n .join(\", \"),\n // Keep iframe in the layout but invisible while not ready\n ...(!showWidget\n ? { position: \"absolute\" as const, pointerEvents: \"none\" as const }\n : {}),\n };\n // Suppress the empty bordered box while the blocked-App notice stands in\n // for it — otherwise the notice renders *below* the blank box it explains.\n const showHostChrome =\n !isFullscreen && matrixGatedPrefersBorder && !showCspBlockedNotice;\n const hostChromeStyle: CSSProperties | undefined = showHostChrome\n ? {\n backgroundColor: mergedStyleVariables[\"--color-background-primary\"],\n }\n : undefined;\n const iframe = (\n <SandboxedIframe\n ref={sandboxRef}\n html={bridgeTransportReady ? widgetHtml : null}\n sandbox=\"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox\"\n // Browser-enforced CSP / Permission Policy MUST receive the resolved\n // values, not the raw resource declaration. `effectiveSandbox` runs the\n // shared resolver (mode → restrictTo intersect → hosted-mode clamp);\n // when a host policy applies it forces\n // `permissive: false` so SandboxedIframe injects the meta-CSP rather\n // than skipping it. Passing `widgetCsp` here directly is the canonical\n // regression — keep the resolver path.\n csp={effectiveSandbox.csp}\n permissions={effectiveSandbox.permissions}\n permissive={effectiveSandbox.permissive}\n sandboxAttrs={effectiveSandbox.sandboxAttrs}\n allowFeatures={effectiveSandbox.allowFeatures}\n cspDirectives={effectiveSandbox.cspDirectives}\n colorScheme={resolvedTheme}\n recordMode={recordMode}\n onProxyReady={() => {\n setSandboxProxyReady(true);\n logWidgetDebug(\"ui-to-host\", \"debug/sandbox-proxy-ready\", {\n bridgeTransportReady,\n hasWidgetHtml,\n });\n }}\n onMessage={handleSandboxMessage}\n title={`MCP App: ${toolName}`}\n hostedMode={host.surface.hostedMode}\n sandboxOrigin={host.surface.sandboxOrigin}\n className={`bg-transparent overflow-hidden ${\n isFullscreen\n ? \"flex-1 border-0 rounded-none\"\n : `rounded-md ${\n matrixGatedPrefersBorder ? \"border border-border/40\" : \"\"\n }`\n }`}\n style={iframeStyle}\n />\n );\n\n return (\n <div\n className={containerClassName}\n data-mcp-app-persistent-initial-tool-call-id={\n persistentSurfaceInitialToolCallId\n }\n data-mcp-app-persistent-surface-id={persistentSurfaceId}\n >\n {((isFullscreen && isContainedFullscreenMode) ||\n (isPip && isMobilePlaygroundMode)) && (\n <>\n <button\n onClick={() => {\n userPreferInlineRef.current = true;\n setDisplayMode(\"inline\");\n if (isPip) {\n onExitPip?.(pipWidgetId ?? displayWidgetId);\n }\n // onExitFullscreen is called within setDisplayMode when leaving fullscreen\n }}\n className=\"absolute left-3 top-3 z-20 flex h-8 w-8 items-center justify-center rounded-full bg-black/20 hover:bg-black/40 text-white transition-colors cursor-pointer\"\n aria-label=\"Close\"\n >\n <X className=\"w-5 h-5\" />\n </button>\n {showOpenInAppButton && (\n <button\n onClick={handleOpenInApp}\n className=\"absolute right-3 top-3 z-20 flex h-8 w-8 items-center justify-center rounded-full bg-black/20 hover:bg-black/40 text-white transition-colors cursor-pointer\"\n aria-label={`Open in ${openInAppLabel}`}\n title={`Open in ${openInAppLabel}`}\n >\n <ExternalLink className=\"w-4 h-4\" />\n </button>\n )}\n </>\n )}\n\n {isFullscreen && !isContainedFullscreenMode && (\n <div className=\"grid grid-cols-[1fr_auto_1fr] items-center gap-3 px-4 h-14 border-b border-border/40 bg-background/95 backdrop-blur z-40 shrink-0\">\n <div />\n <div className=\"font-medium text-sm text-muted-foreground min-w-0 max-w-[40vw] truncate\">\n {openInAppLabel}\n </div>\n <div className=\"flex items-center justify-end gap-2 min-w-0\">\n {showOpenInAppButton && (\n <button\n onClick={handleOpenInApp}\n className=\"inline-flex items-center justify-center gap-1.5 h-8 max-w-[16rem] rounded-full border border-border/60 px-2 sm:px-3 text-xs font-medium text-foreground hover:bg-muted transition-colors\"\n aria-label={`Open in ${openInAppLabel}`}\n title={`Open in ${openInAppLabel}`}\n >\n <ExternalLink className=\"w-3.5 h-3.5 shrink-0\" />\n <span className=\"hidden sm:inline min-w-0 truncate\">\n Open in {openInAppLabel}\n </span>\n </button>\n )}\n <button\n onClick={() => {\n userPreferInlineRef.current = true;\n setDisplayMode(\"inline\");\n if (ownsPipDisplayMode) {\n onExitPip?.(pipWidgetId ?? displayWidgetId);\n }\n }}\n className=\"p-2 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors\"\n aria-label=\"Exit fullscreen\"\n >\n <X className=\"w-5 h-5\" />\n </button>\n </div>\n </div>\n )}\n\n {isPip && !isMobilePlaygroundMode && (\n <button\n onClick={() => {\n userPreferInlineRef.current = true;\n setDisplayMode(\"inline\");\n onExitPip?.(pipWidgetId ?? displayWidgetId);\n }}\n className=\"absolute left-2 top-2 z-10 flex h-6 w-6 items-center justify-center rounded-md bg-background/80 hover:bg-background border border-border/50 text-muted-foreground hover:text-foreground transition-colors cursor-pointer\"\n aria-label=\"Close PiP mode\"\n title=\"Close PiP mode\"\n >\n <X className=\"w-4 h-4\" />\n </button>\n )}\n {/* Keep this wrapper mounted so display-mode changes don't remount the\n * sandbox iframe and strand the bridge on the old contentWindow. */}\n <div\n data-testid={showHostChrome ? \"mcp-app-host-chrome\" : undefined}\n className={showHostChrome ? \"rounded-md\" : \"contents\"}\n style={hostChromeStyle}\n >\n {iframe}\n </div>\n {/* The App reported a CSP violation and never signalled ready — its\n * own resources were blocked, so the iframe would otherwise stay an\n * empty box. Name the blocked directive and the first blocked origin\n * for developer surfaces; testers get the plain-language line. */}\n {showCspBlockedNotice && (\n <div\n data-testid=\"mcp-app-csp-blocked-notice\"\n role=\"status\"\n className=\"border border-destructive/40 bg-destructive/10 text-destructive text-xs rounded-md px-3 py-2\"\n >\n <span>\n {minimalMode\n ? \"This app couldn't load its resources.\"\n : `MCP App blocked by Content Security Policy${\n firstCspBlock?.directive\n ? ` (${firstCspBlock.directive})`\n : \"\"\n }.`}\n </span>\n {firstCspBlock?.blockedUri ? (\n <span className=\"mt-0.5 block font-mono break-all opacity-80\">\n {firstCspBlock.blockedUri}\n </span>\n ) : null}\n </div>\n )}\n {/* SEP-1865 App-Provided Tools: per-iframe busy indicator. Surfaces\n * when the host is dispatching `tools/call` into this iframe (the\n * count comes from `useAppToolsRegistry.pendingControllers`). Sits\n * in the top-right of the inline container; suppressed in\n * fullscreen because the fullscreen header already names the tool\n * and would crowd this overlay. */}\n {pendingAppToolCalls > 0 && !isFullscreen && (\n <div\n className=\"pointer-events-none absolute right-2 top-2 z-20 flex h-6 w-6 items-center justify-center rounded-md bg-background/80 border border-border/50 text-muted-foreground shadow-sm\"\n aria-label=\"App tool call in progress\"\n title=\"App tool call in progress\"\n data-testid=\"mcp-app-busy-indicator\"\n >\n <Loader2 className=\"w-3.5 h-3.5 animate-spin\" />\n </div>\n )}\n\n <McpAppsModal\n open={modalOpen}\n onOpenChange={setModalOpen}\n title={modalTitle}\n template={modalTemplate}\n params={modalParams}\n registerBridgeHandlers={registerBridgeHandlers}\n // SEP-1865 App-Provided Tools: the modal bridge replaces\n // `oninitialized` to suppress inline-state side effects, which\n // also drops the inline registration call. The modal owns its\n // own bridge-id and `surface: \"modal\"` registration; pass the\n // shared refresh helper down so the modal can advertise/refresh\n // its iframe's tools without re-implementing the listTools loop.\n refreshAppProvidedTools={refreshAppProvidedTools}\n // The modal mounts its own SandboxedIframe via `fetchMcpAppsWidgetContent`.\n // Pass the resolved values so the modal's CSP enforcement matches the\n // inline iframe — otherwise a host restrictTo intersection applies to\n // inline but not to a modal-mode widget reading the same resource.\n widgetCsp={effectiveSandbox.csp}\n widgetPermissions={effectiveSandbox.permissions}\n widgetPermissive={effectiveSandbox.permissive}\n widgetSandboxAttrs={effectiveSandbox.sandboxAttrs}\n widgetAllowFeatures={effectiveSandbox.allowFeatures}\n widgetCspDirectives={effectiveSandbox.cspDirectives}\n hostContextRef={hostContextRef}\n serverId={serverId}\n resourceUri={resourceUri}\n toolCallId={toolCallId}\n toolName={toolName}\n cspMode={cspMode}\n injectOpenAiCompat={effectiveInjectOpenAiCompat}\n // Same resolved blob the inline AppBridge advertises. Inline +\n // modal must speak an identical surface to the widget so\n // app.getHostCapabilities() returns the same record regardless\n // of which iframe the widget is mounted in.\n effectiveHostCapabilities={effectiveHostCapabilities}\n // Resolved hostInfo + web-managed flag passed down (the modal no longer\n // reads useActiveMcpProfile/useWebManagedServers/resolveHostInfo\n // directly) so inline + modal stay in lockstep and the modal holds no\n // inspector-app-state coupling.\n hostInfo={resolvedBridgeHostInfo}\n webManagedServers={webManagedServers}\n toolInputRef={toolInputRef}\n toolOutputRef={toolOutputRef}\n themeModeRef={themeModeRef}\n addUiLog={(log) =>\n logUiEvent({\n ...log,\n protocol: \"mcp-apps\" as UiProtocol,\n })\n }\n onCspViolation={handleCspViolation}\n />\n\n {checkoutSession != null && Checkout && (\n <Checkout\n session={checkoutSession}\n open={checkoutOpen}\n onOpenChange={setCheckoutOpen}\n onComplete={(result) => respondToCheckout(result)}\n onError={(error) => respondToCheckout(null, error)}\n onCancel={() => respondToCheckout(null, \"User cancelled checkout\")}\n onCallTool={async (toolName, params) => {\n if (!onCallTool) {\n throw new Error(\"Tool calls not supported\");\n }\n return onCallTool(toolName, params);\n }}\n />\n )}\n </div>\n );\n}\n","import { useEffect, useLayoutEffect, useMemo, useState } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport {\n MCPAppsRendererSurface,\n type MCPAppsRendererProps,\n} from \"./mcp-apps-renderer\";\nimport {\n getRenderableSurfaceEntries,\n useWidgetSurfaceStore,\n type WidgetSurfaceId,\n} from \"./widget-surface-store\";\nexport { WidgetSurfaceHostProvider } from \"./widget-surface-context\";\n\nfunction createSurfaceContainer(surfaceId: WidgetSurfaceId) {\n const container = document.createElement(\"div\");\n container.dataset.mcpAppSurfaceContainer = surfaceId;\n container.style.display = \"contents\";\n return container;\n}\n\nfunction WidgetSurfacePortal({\n anchorElement,\n initialToolCallId,\n parkingElement,\n props,\n surfaceId,\n}: {\n anchorElement: HTMLDivElement | null;\n initialToolCallId: string;\n parkingElement: HTMLDivElement | null;\n props: MCPAppsRendererProps;\n surfaceId: WidgetSurfaceId;\n}) {\n const [container] = useState(() => createSurfaceContainer(surfaceId));\n const targetElement = anchorElement ?? parkingElement;\n\n useLayoutEffect(() => {\n if (!targetElement) return;\n if (container.parentElement !== targetElement) {\n targetElement.appendChild(container);\n }\n }, [container, targetElement]);\n\n useEffect(() => {\n return () => {\n container.remove();\n };\n }, [container]);\n\n return createPortal(\n <MCPAppsRendererSurface\n {...props}\n persistentSurfaceInitialToolCallId={initialToolCallId}\n persistentSurfaceId={surfaceId}\n />,\n container,\n surfaceId\n );\n}\n\nexport function WidgetSurfaceHost({\n chatSessionId,\n}: {\n chatSessionId?: string;\n}) {\n const [parkingElement, setParkingElement] = useState<HTMLDivElement | null>(\n null\n );\n const surfaces = useWidgetSurfaceStore((state) => state.surfaces);\n const entries = useMemo(\n () => getRenderableSurfaceEntries(surfaces, chatSessionId),\n [chatSessionId, surfaces]\n );\n\n useEffect(() => {\n return () => {\n useWidgetSurfaceStore.getState().clearChatSession(chatSessionId);\n };\n }, [chatSessionId]);\n\n return (\n <>\n <div\n ref={setParkingElement}\n data-mcp-app-surface-parking\n style={{\n height: 0,\n overflow: \"hidden\",\n pointerEvents: \"none\",\n position: \"absolute\",\n width: 0,\n }}\n />\n {entries.map(({ surfaceId, anchorElement, initialToolCallId, props }) => (\n <WidgetSurfacePortal\n key={surfaceId}\n anchorElement={anchorElement}\n initialToolCallId={initialToolCallId}\n parkingElement={parkingElement}\n props={props}\n surfaceId={surfaceId}\n />\n ))}\n </>\n );\n}\n"]}