@mcpjam/widget-react 0.1.0 → 0.1.2

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.d.ts CHANGED
@@ -778,6 +778,12 @@ interface SandboxedIframeProps {
778
778
  cspDirectives?: Record<string, string[]>;
779
779
  /** Skip CSP injection entirely (for permissive/testing mode) */
780
780
  permissive?: boolean;
781
+ /**
782
+ * Tier 2 recorder: when true, the proxy injects a recorder shim into the
783
+ * guest that posts `recorder:step` / `recorder:ready` messages (forwarded via
784
+ * `onMessage`). Default off — only the eval authoring preview sets it.
785
+ */
786
+ recordMode?: boolean;
781
787
  /** Callback when sandbox proxy is ready */
782
788
  onProxyReady?: () => void;
783
789
  /** Callback for messages from guest UI (excluding sandbox-internal messages) */
@@ -843,6 +849,28 @@ interface MCPAppsRendererProps {
843
849
  onCallTool?: (toolName: string, params: Record<string, unknown>) => Promise<unknown>;
844
850
  onAppToolInvocationChange?: (invocation: AppToolInvocationUpdate) => void;
845
851
  onWidgetStateChange?: (toolCallId: string, state: unknown) => void;
852
+ /**
853
+ * Tier 2 recorder. When `recordMode` is on, the sandbox proxy injects a
854
+ * recorder shim into the guest; `onRecorderStep` fires for each captured
855
+ * click/type (the raw `{ kind, target, ... }` step), and `onRecorderReady`
856
+ * fires once when the shim installs (so the host can detect a strict-CSP
857
+ * guest that silently blocked it). Default off — only the eval authoring
858
+ * preview sets these.
859
+ */
860
+ recordMode?: boolean;
861
+ onRecorderStep?: (step: unknown) => void;
862
+ onRecorderReady?: () => void;
863
+ /**
864
+ * Replay (inverse of recording): published when the guest shim is record-capable
865
+ * so the host can drive the live widget. The host calls `replay(step)` with one
866
+ * scripted step; the renderer relays it to the guest and resolves with the
867
+ * step's result. Published as `null` on unmount so the host drops the handle.
868
+ */
869
+ onReplayControllerReady?: (replay: ((step: unknown) => Promise<{
870
+ ok: boolean;
871
+ reason?: string;
872
+ deferred?: string;
873
+ }>) | null) => void;
846
874
  pipWidgetId?: string | null;
847
875
  fullscreenWidgetId?: string | null;
848
876
  onRequestPip?: (toolCallId: string) => void;
@@ -869,6 +897,19 @@ interface MCPAppsRendererProps {
869
897
  * collapse the inline view).
870
898
  */
871
899
  onRequestTeardown?: (toolCallId: string, displayWidgetId?: string) => void;
900
+ /**
901
+ * Ask the host to confirm a widget-initiated `ui/download-file` before the
902
+ * download runs (SEP-1865: host SHOULD confirm). Resolve `true` to proceed,
903
+ * `false` to deny (the widget then receives a JSON-RPC "Download denied by
904
+ * user" error). When omitted, downloads proceed unprompted — so embedders of
905
+ * the published package keep the prior behavior.
906
+ */
907
+ onConfirmDownload?: (info: {
908
+ kind: "resource" | "resource_link";
909
+ filename?: string;
910
+ mimeType?: string;
911
+ uri?: string;
912
+ }) => Promise<boolean>;
872
913
  /** Whether the server is offline (for using cached content) */
873
914
  isOffline?: boolean;
874
915
  /** URL to cached widget HTML for offline rendering */
@@ -932,7 +973,7 @@ interface MCPAppsRendererProps {
932
973
  persistentSurfaceInitialToolCallId?: string;
933
974
  }
934
975
  declare function MCPAppsRenderer(props: MCPAppsRendererProps): react_jsx_runtime.JSX.Element;
935
- declare function MCPAppsRendererSurface({ chatSessionId, serverId, serverName, toolCallId, toolName, toolState, toolInput, toolOutput, toolResponseMetadata, toolErrorText, resourceUri, toolMetadata, toolsMetadata, onSendFollowUp, onCallTool, onAppToolInvocationChange, onWidgetStateChange, pipWidgetId, fullscreenWidgetId, onRequestPip, onExitPip, displayMode: displayModeProp, onDisplayModeChange, onRequestFullscreen, onExitFullscreen, onModelContextUpdate, onAppSupportedDisplayModesChange, onRequestTeardown, isOffline, cachedWidgetHtmlUrl, liveFetchPreferred, widgetCsp: initialWidgetCsp, widgetPermissions: initialWidgetPermissions, widgetPermissive: initialWidgetPermissive, prefersBorder: initialPrefersBorder, injectedOpenAiCompat: initialInjectedOpenAiCompat, injectedOpenAiCompatCapabilities: initialInjectedOpenAiCompatCapabilities, initialWidgetState, minimalMode, persistentSurfaceId, persistentSurfaceInitialToolCallId, }: MCPAppsRendererProps): react_jsx_runtime.JSX.Element | null;
976
+ declare function MCPAppsRendererSurface({ chatSessionId, serverId, serverName, toolCallId, toolName, toolState, toolInput, toolOutput, toolResponseMetadata, toolErrorText, resourceUri, toolMetadata, toolsMetadata, onSendFollowUp, onCallTool, onAppToolInvocationChange, onWidgetStateChange, recordMode, onRecorderStep, onRecorderReady, onReplayControllerReady, pipWidgetId, fullscreenWidgetId, onRequestPip, onExitPip, displayMode: displayModeProp, onDisplayModeChange, onRequestFullscreen, onExitFullscreen, onModelContextUpdate, onAppSupportedDisplayModesChange, onRequestTeardown, onConfirmDownload, isOffline, cachedWidgetHtmlUrl, liveFetchPreferred, widgetCsp: initialWidgetCsp, widgetPermissions: initialWidgetPermissions, widgetPermissive: initialWidgetPermissive, prefersBorder: initialPrefersBorder, injectedOpenAiCompat: initialInjectedOpenAiCompat, injectedOpenAiCompatCapabilities: initialInjectedOpenAiCompatCapabilities, initialWidgetState, minimalMode, persistentSurfaceId, persistentSurfaceInitialToolCallId, }: MCPAppsRendererProps): react_jsx_runtime.JSX.Element | null;
936
977
 
937
978
  declare function WidgetSurfaceHostProvider({ children, }: {
938
979
  children: ReactNode;
package/dist/index.js CHANGED
@@ -806,6 +806,21 @@ function useToolInputStreaming({
806
806
  resetStreamingState
807
807
  };
808
808
  }
809
+ function isRecorderDebugEnabled() {
810
+ try {
811
+ return typeof window !== "undefined" && window.localStorage?.getItem("mcpjam:recorder-debug") === "1";
812
+ } catch {
813
+ return false;
814
+ }
815
+ }
816
+ function recorderDebug(message, details) {
817
+ try {
818
+ if (isRecorderDebugEnabled()) {
819
+ console.info(`[recorder:sandboxed-iframe] ${message}`, details ?? {});
820
+ }
821
+ } catch {
822
+ }
823
+ }
809
824
  var SandboxedIframe = forwardRef(function SandboxedIframe2({
810
825
  html,
811
826
  sandbox = "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",
@@ -815,6 +830,7 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
815
830
  allowFeatures,
816
831
  cspDirectives,
817
832
  permissive,
833
+ recordMode,
818
834
  onProxyReady,
819
835
  onMessage,
820
836
  className,
@@ -827,6 +843,10 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
827
843
  const outerRef = useRef(null);
828
844
  const [proxyReady, setProxyReady] = useState(false);
829
845
  const lastResourceReadyKeyRef = useRef(null);
846
+ const onMessageRef = useRef(onMessage);
847
+ const onProxyReadyRef = useRef(onProxyReady);
848
+ onMessageRef.current = onMessage;
849
+ onProxyReadyRef.current = onProxyReady;
830
850
  const [sandboxProxyUrl] = useState(() => {
831
851
  const proxyPath = hostedMode ? "/api/web/apps/mcp-apps/sandbox-proxy" : "/api/apps/mcp-apps/sandbox-proxy";
832
852
  if (hostedMode && sandboxOrigin) {
@@ -881,26 +901,31 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
881
901
  }
882
902
  if (event.source !== outerRef.current?.contentWindow) return;
883
903
  if (event.data?.type === "mcp-apps:csp-violation") {
884
- onMessage(event);
904
+ onMessageRef.current(event);
885
905
  return;
886
906
  }
887
907
  if (event.data?.type === "openai:uploadFile" || event.data?.type === "openai:getFileDownloadUrl" || event.data?.type === "openai:setWidgetState" || event.data?.type === "openai:setOpenInAppUrl") {
888
- onMessage(event);
908
+ onMessageRef.current(event);
909
+ return;
910
+ }
911
+ if (event.data?.type === "recorder:step" || event.data?.type === "recorder:ready" || event.data?.type === "recorder:replay-result") {
912
+ recorderDebug(`forward ${event.data.type}`);
913
+ onMessageRef.current(event);
889
914
  return;
890
915
  }
891
916
  const { jsonrpc, method } = event.data || {};
892
917
  if (jsonrpc !== "2.0") return;
893
918
  if (method === "ui/notifications/sandbox-proxy-ready") {
894
919
  setProxyReady(true);
895
- onProxyReady?.();
920
+ onProxyReadyRef.current?.();
896
921
  return;
897
922
  }
898
923
  if (method?.startsWith("ui/notifications/sandbox-")) {
899
924
  return;
900
925
  }
901
- onMessage(event);
926
+ onMessageRef.current(event);
902
927
  },
903
- [onMessage, onProxyReady, sandboxProxyOrigin]
928
+ [sandboxProxyOrigin]
904
929
  );
905
930
  useEffect(() => {
906
931
  window.addEventListener("message", handleMessage);
@@ -922,7 +947,10 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
922
947
  permissive: permissive ?? null,
923
948
  permissions: permissions ?? null,
924
949
  sandbox,
925
- sandboxAttrs: sandboxAttrs ?? null
950
+ sandboxAttrs: sandboxAttrs ?? null,
951
+ // Include recordMode so record-capable surfaces receive the recorder
952
+ // shim, and stale/non-recordable surfaces reload without it.
953
+ recordMode: recordMode ?? null
926
954
  }),
927
955
  [
928
956
  csp,
@@ -931,7 +959,8 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
931
959
  permissive,
932
960
  permissions,
933
961
  sandbox,
934
- sandboxAttrs
962
+ sandboxAttrs,
963
+ recordMode
935
964
  ]
936
965
  );
937
966
  useEffect(() => {
@@ -961,17 +990,21 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
961
990
  // field.
962
991
  cspDirectives,
963
992
  permissive,
964
- colorScheme
993
+ colorScheme,
994
+ recordMode,
995
+ recorderDebug: isRecorderDebugEnabled()
965
996
  }
966
997
  },
967
998
  sandboxProxyOrigin
968
999
  );
969
- }, [
970
- proxyReady,
971
- html,
972
- resourceReadyKey,
973
- sandboxProxyOrigin
974
- ]);
1000
+ recorderDebug("sent resource ready", {
1001
+ recordMode: !!recordMode,
1002
+ recorderDebug: isRecorderDebugEnabled(),
1003
+ proxyReady,
1004
+ hasHtml: !!html,
1005
+ sandboxProxyOrigin
1006
+ });
1007
+ }, [proxyReady, html, resourceReadyKey, sandboxProxyOrigin]);
975
1008
  useEffect(() => {
976
1009
  if (!proxyReady || !colorScheme) return;
977
1010
  outerRef.current?.contentWindow?.postMessage(
@@ -1501,6 +1534,14 @@ function toSafeOpenInAppUrl(value) {
1501
1534
  return null;
1502
1535
  }
1503
1536
  }
1537
+ function toSafeDownloadLinkUrl(uri) {
1538
+ try {
1539
+ const parsed = new URL(uri, window.location.href);
1540
+ return SAFE_OPEN_IN_APP_PROTOCOLS.has(parsed.protocol) ? parsed.href : null;
1541
+ } catch {
1542
+ return null;
1543
+ }
1544
+ }
1504
1545
  function readExplicitBaseHref(html) {
1505
1546
  if (!html) return null;
1506
1547
  if (typeof DOMParser !== "undefined") {
@@ -1596,6 +1637,14 @@ function mapLogToLifecycle(method, details) {
1596
1637
  const message = typeof details.error === "string" ? details.error : typeof details.reason === "string" ? details.reason : void 0;
1597
1638
  return { kind, status, message, timestamp: Date.now() };
1598
1639
  }
1640
+ function recorderDebug2(message, details) {
1641
+ try {
1642
+ if (typeof window !== "undefined" && window.localStorage?.getItem("mcpjam:recorder-debug") === "1") {
1643
+ console.info(`[recorder:renderer] ${message}`, details ?? {});
1644
+ }
1645
+ } catch {
1646
+ }
1647
+ }
1599
1648
  var FETCH_SOURCE_KEY_SEGMENTS = [
1600
1649
  "resourceUri",
1601
1650
  "cachedReplayWidgetHtmlUrl",
@@ -1722,7 +1771,10 @@ function PersistentMCPAppsRendererRegistration(props) {
1722
1771
  function MCPAppsRenderer(props) {
1723
1772
  const persistentHostEnabled = usePersistentWidgetSurfaceHost();
1724
1773
  const isCachedReplay = !!props.cachedWidgetHtmlUrl && !props.liveFetchPreferred;
1725
- const shouldUsePersistentSurface = persistentHostEnabled && !props.isOffline && !isCachedReplay;
1774
+ const wantPersistentSurface = persistentHostEnabled && !props.isOffline && !isCachedReplay;
1775
+ const everPersistentRef = useRef(false);
1776
+ if (wantPersistentSurface) everPersistentRef.current = true;
1777
+ const shouldUsePersistentSurface = everPersistentRef.current && !props.isOffline ? true : wantPersistentSurface;
1726
1778
  if (!shouldUsePersistentSurface) {
1727
1779
  return /* @__PURE__ */ jsx(MCPAppsRendererSurface, { ...props });
1728
1780
  }
@@ -1746,6 +1798,10 @@ function MCPAppsRendererSurface({
1746
1798
  onCallTool,
1747
1799
  onAppToolInvocationChange,
1748
1800
  onWidgetStateChange,
1801
+ recordMode,
1802
+ onRecorderStep,
1803
+ onRecorderReady,
1804
+ onReplayControllerReady,
1749
1805
  pipWidgetId,
1750
1806
  fullscreenWidgetId,
1751
1807
  onRequestPip,
@@ -1757,6 +1813,7 @@ function MCPAppsRendererSurface({
1757
1813
  onModelContextUpdate,
1758
1814
  onAppSupportedDisplayModesChange,
1759
1815
  onRequestTeardown,
1816
+ onConfirmDownload,
1760
1817
  isOffline,
1761
1818
  cachedWidgetHtmlUrl,
1762
1819
  liveFetchPreferred,
@@ -1772,6 +1829,44 @@ function MCPAppsRendererSurface({
1772
1829
  persistentSurfaceInitialToolCallId
1773
1830
  }) {
1774
1831
  const sandboxRef = useRef(null);
1832
+ const replayIdRef = useRef(0);
1833
+ const pendingReplaysRef = useRef(/* @__PURE__ */ new Map());
1834
+ const REPLAY_STEP_TIMEOUT_MS = 8e3;
1835
+ const replayStep = useCallback(
1836
+ (step) => new Promise((resolve) => {
1837
+ const id = replayIdRef.current += 1;
1838
+ const timer = setTimeout(() => {
1839
+ pendingReplaysRef.current.delete(id);
1840
+ resolve({ ok: false, reason: "replay step timed out" });
1841
+ }, REPLAY_STEP_TIMEOUT_MS);
1842
+ pendingReplaysRef.current.set(id, { resolve, timer });
1843
+ sandboxRef.current?.postMessage({
1844
+ type: "recorder:replay-step",
1845
+ id,
1846
+ step
1847
+ });
1848
+ }),
1849
+ []
1850
+ );
1851
+ const onReplayControllerReadyRef = useRef(onReplayControllerReady);
1852
+ onReplayControllerReadyRef.current = onReplayControllerReady;
1853
+ useEffect(() => {
1854
+ const publish = onReplayControllerReadyRef.current;
1855
+ if (!recordMode) {
1856
+ publish?.(null);
1857
+ return;
1858
+ }
1859
+ publish?.(replayStep);
1860
+ return () => {
1861
+ onReplayControllerReadyRef.current?.(null);
1862
+ const pending = pendingReplaysRef.current;
1863
+ for (const { resolve, timer } of pending.values()) {
1864
+ clearTimeout(timer);
1865
+ resolve({ ok: false, reason: "widget unmounted" });
1866
+ }
1867
+ pending.clear();
1868
+ };
1869
+ }, [recordMode, replayStep]);
1775
1870
  const host = useWidgetHost();
1776
1871
  const Checkout = host.components?.Checkout;
1777
1872
  const debug = host.debug ?? NOOP_WIDGET_DEBUG_SINK;
@@ -2026,7 +2121,24 @@ function MCPAppsRendererSurface({
2026
2121
  const [checkoutOpen, setCheckoutOpen] = useState(false);
2027
2122
  const [checkoutSession, setCheckoutSession] = useState(null);
2028
2123
  const [checkoutCallId, setCheckoutCallId] = useState(null);
2124
+ const hasRenderedLiveRef = useRef(false);
2125
+ const liveRenderIdentityKey = useMemo(
2126
+ () => stableStringifyJson({
2127
+ chatSessionId: chatSessionId ?? null,
2128
+ serverId,
2129
+ resourceUri
2130
+ }),
2131
+ [chatSessionId, serverId, resourceUri]
2132
+ );
2133
+ const liveRenderIdentityRef = useRef(null);
2134
+ const hasRenderedLiveForCurrentIdentity = useCallback(
2135
+ () => hasRenderedLiveRef.current && liveRenderIdentityRef.current === liveRenderIdentityKey,
2136
+ [liveRenderIdentityKey]
2137
+ );
2029
2138
  useEffect(() => {
2139
+ if (isCachedReplay && hasRenderedLiveForCurrentIdentity()) return;
2140
+ hasRenderedLiveRef.current = false;
2141
+ liveRenderIdentityRef.current = null;
2030
2142
  setWidgetHtml(null);
2031
2143
  setBridgeTransportReady(false);
2032
2144
  setLoadedCspMode(null);
@@ -2037,7 +2149,12 @@ function MCPAppsRendererSurface({
2037
2149
  setWidgetPermissions(void 0);
2038
2150
  setWidgetPermissive(isCachedReplay ? true : false);
2039
2151
  setPrefersBorder(cachedReplayPrefersBorder ?? true);
2040
- }, [cachedReplayWidgetHtmlUrl, cachedReplayPrefersBorder, isCachedReplay]);
2152
+ }, [
2153
+ cachedReplayWidgetHtmlUrl,
2154
+ cachedReplayPrefersBorder,
2155
+ hasRenderedLiveForCurrentIdentity,
2156
+ isCachedReplay
2157
+ ]);
2041
2158
  const bridgeRef = useRef(null);
2042
2159
  const hostContextRef = useRef(null);
2043
2160
  const isReadyRef = useRef(false);
@@ -2069,6 +2186,7 @@ function MCPAppsRendererSurface({
2069
2186
  const onRequestPipRef = useRef(onRequestPip);
2070
2187
  const onExitPipRef = useRef(onExitPip);
2071
2188
  const onRequestTeardownRef = useRef(onRequestTeardown);
2189
+ const onConfirmDownloadRef = useRef(onConfirmDownload);
2072
2190
  const setDisplayModeRef = useRef(setDisplayMode);
2073
2191
  const isPlaygroundActiveRef = useRef(isPlaygroundActive);
2074
2192
  const playgroundDeviceTypeRef = useRef(playgroundDeviceType);
@@ -2117,6 +2235,9 @@ function MCPAppsRendererSurface({
2117
2235
  const isActiveToolState = toolState === "input-streaming" || toolState === "input-available" || toolState === "output-available";
2118
2236
  if (!isActiveToolState) return;
2119
2237
  if (shouldWaitForCompatToolOutput) return;
2238
+ if (widgetHtml && isCachedReplay && hasRenderedLiveForCurrentIdentity()) {
2239
+ return;
2240
+ }
2120
2241
  if (widgetHtml && loadedCspMode === cspMode && loadedInjectOpenAiCompat === widgetInjectOpenAiCompatReloadKey && loadedCompatCapabilitiesHash === widgetCompatCapabilitiesReloadKey && loadedMcpAppsCapabilitiesHash === widgetMcpAppsCapabilitiesReloadKey)
2121
2242
  return;
2122
2243
  const fetchSourceKey = [
@@ -2148,6 +2269,8 @@ function MCPAppsRendererSurface({
2148
2269
  const html = await cachedResponse.text();
2149
2270
  if (!isStillCurrent()) return;
2150
2271
  setBridgeTransportReady(false);
2272
+ hasRenderedLiveRef.current = false;
2273
+ liveRenderIdentityRef.current = null;
2151
2274
  setWidgetHtml(html);
2152
2275
  setWidgetCsp(void 0);
2153
2276
  setWidgetPermissions(void 0);
@@ -2228,6 +2351,8 @@ function MCPAppsRendererSurface({
2228
2351
  return false;
2229
2352
  }
2230
2353
  setBridgeTransportReady(false);
2354
+ hasRenderedLiveRef.current = true;
2355
+ liveRenderIdentityRef.current = liveRenderIdentityKey;
2231
2356
  setWidgetHtml(html);
2232
2357
  setWidgetCsp(csp);
2233
2358
  setWidgetPermissions(permissions);
@@ -2340,6 +2465,8 @@ function MCPAppsRendererSurface({
2340
2465
  initialPrefersBorder,
2341
2466
  cachedReplayInjectOpenAiCompat,
2342
2467
  initialInjectedOpenAiCompatCapabilities,
2468
+ hasRenderedLiveForCurrentIdentity,
2469
+ liveRenderIdentityKey,
2343
2470
  shouldWaitForCompatToolOutput,
2344
2471
  recordMountStore
2345
2472
  ]);
@@ -2453,6 +2580,8 @@ function MCPAppsRendererSurface({
2453
2580
  const appendLifecycleStore = debug.appendLifecycle;
2454
2581
  const appendLifecycleRef = useRef(appendLifecycleStore);
2455
2582
  appendLifecycleRef.current = appendLifecycleStore;
2583
+ const setWidgetModelContextRef = useRef(setWidgetModelContext);
2584
+ setWidgetModelContextRef.current = setWidgetModelContext;
2456
2585
  useEffect(() => {
2457
2586
  if (loadedCspMode !== null && loadedCspMode !== cspMode) {
2458
2587
  clearCspViolations(toolCallId);
@@ -2580,6 +2709,10 @@ function MCPAppsRendererSurface({
2580
2709
  }),
2581
2710
  [effectiveHostStyle, activeMcpProfileKey, hostCapabilitiesOverrideKey]
2582
2711
  );
2712
+ const effectiveHostCapabilitiesKey = useMemo(
2713
+ () => stableStringifyJson(effectiveHostCapabilities),
2714
+ [effectiveHostCapabilities]
2715
+ );
2583
2716
  const effectiveMcpAppsCapabilities = earlyEffectiveMcpAppsCapabilities;
2584
2717
  mcpAppsCapabilitiesRef.current = effectiveMcpAppsCapabilities;
2585
2718
  themeModeRef.current = resolvedTheme;
@@ -2873,6 +3006,10 @@ function MCPAppsRendererSurface({
2873
3006
  allowFeaturesPolicy,
2874
3007
  cspDirectivesEffective
2875
3008
  ]);
3009
+ const effectiveSandboxKey = useMemo(
3010
+ () => stableStringifyJson(effectiveSandbox),
3011
+ [effectiveSandbox]
3012
+ );
2876
3013
  const sandboxHostInfo = useMemo(() => {
2877
3014
  const raw = profileHostInfo;
2878
3015
  if (!raw || typeof raw !== "object") return null;
@@ -2889,6 +3026,10 @@ function MCPAppsRendererSurface({
2889
3026
  },
2890
3027
  [activeMcpProfileKey]
2891
3028
  );
3029
+ const resolvedBridgeHostInfoKey = useMemo(
3030
+ () => stableStringifyJson(resolvedBridgeHostInfo),
3031
+ [resolvedBridgeHostInfo]
3032
+ );
2892
3033
  useEffect(() => {
2893
3034
  if (!toolCallId) return;
2894
3035
  setSandboxAppliedStore(
@@ -2932,6 +3073,7 @@ function MCPAppsRendererSurface({
2932
3073
  onModelContextUpdateRef.current = onModelContextUpdate;
2933
3074
  onAppSupportedDisplayModesChangeRef.current = onAppSupportedDisplayModesChange;
2934
3075
  onRequestTeardownRef.current = onRequestTeardown;
3076
+ onConfirmDownloadRef.current = onConfirmDownload;
2935
3077
  }, [
2936
3078
  onSendFollowUp,
2937
3079
  onCallTool,
@@ -2950,7 +3092,8 @@ function MCPAppsRendererSurface({
2950
3092
  toolsMetadata,
2951
3093
  onModelContextUpdate,
2952
3094
  onAppSupportedDisplayModesChange,
2953
- onRequestTeardown
3095
+ onRequestTeardown,
3096
+ onConfirmDownload
2954
3097
  ]);
2955
3098
  const registerBridgeHandlers = useCallback(
2956
3099
  (bridge) => {
@@ -3024,7 +3167,9 @@ function MCPAppsRendererSurface({
3024
3167
  );
3025
3168
  },
3026
3169
  onListResourceTemplates: async () => {
3027
- const resourceTemplates = await host.services.listResourceTemplates(serverIdRef.current);
3170
+ const resourceTemplates = await host.services.listResourceTemplates(
3171
+ serverIdRef.current
3172
+ );
3028
3173
  return { resourceTemplates };
3029
3174
  },
3030
3175
  onListPrompts: async () => {
@@ -3110,7 +3255,7 @@ function MCPAppsRendererSurface({
3110
3255
  return { mode: actualMode };
3111
3256
  },
3112
3257
  onUpdateModelContext: (ctxToolCallId, { content, structuredContent }) => {
3113
- setWidgetModelContext(ctxToolCallId, {
3258
+ setWidgetModelContextRef.current(ctxToolCallId, {
3114
3259
  content,
3115
3260
  structuredContent
3116
3261
  });
@@ -3120,6 +3265,38 @@ function MCPAppsRendererSurface({
3120
3265
  });
3121
3266
  },
3122
3267
  onDownloadFile: async ({ contents }) => {
3268
+ const confirmDownload = onConfirmDownloadRef.current;
3269
+ if (confirmDownload) {
3270
+ for (const item of contents) {
3271
+ let info;
3272
+ if (item.type === "resource" && item.resource) {
3273
+ const res = item.resource;
3274
+ info = {
3275
+ kind: "resource",
3276
+ filename: res.uri.split("/").pop() || void 0,
3277
+ mimeType: res.mimeType,
3278
+ uri: res.uri
3279
+ };
3280
+ } else if (item.type === "resource_link") {
3281
+ const link = item;
3282
+ if (toSafeDownloadLinkUrl(link.uri) === null) {
3283
+ return { isError: true };
3284
+ }
3285
+ info = {
3286
+ kind: "resource_link",
3287
+ filename: link.uri.split("/").pop() || void 0,
3288
+ mimeType: link.mimeType,
3289
+ uri: link.uri
3290
+ };
3291
+ } else {
3292
+ continue;
3293
+ }
3294
+ const approved = await confirmDownload(info);
3295
+ if (!approved) {
3296
+ return { isError: true };
3297
+ }
3298
+ }
3299
+ }
3123
3300
  try {
3124
3301
  for (const item of contents) {
3125
3302
  if (item.type === "resource" && item.resource) {
@@ -3150,13 +3327,13 @@ function MCPAppsRendererSurface({
3150
3327
  }
3151
3328
  } else if (item.type === "resource_link") {
3152
3329
  const link = item;
3153
- const parsed = new URL(link.uri, window.location.href);
3154
- if (!["http:", "https:"].includes(parsed.protocol)) {
3330
+ const safeHref = toSafeDownloadLinkUrl(link.uri);
3331
+ if (safeHref === null) {
3155
3332
  throw new Error(
3156
- `Unsupported download URI protocol: ${parsed.protocol}`
3333
+ `Unsupported download URI: ${link.uri}`
3157
3334
  );
3158
3335
  }
3159
- window.open(parsed.href, "_blank", "noopener,noreferrer");
3336
+ window.open(safeHref, "_blank", "noopener,noreferrer");
3160
3337
  }
3161
3338
  }
3162
3339
  return {};
@@ -3178,10 +3355,9 @@ function MCPAppsRendererSurface({
3178
3355
  },
3179
3356
  [
3180
3357
  setIsReady,
3181
- setWidgetModelContext,
3182
3358
  logWidgetDebug,
3183
3359
  refreshAppProvidedTools,
3184
- effectiveHostCapabilities
3360
+ effectiveHostCapabilitiesKey
3185
3361
  ]
3186
3362
  );
3187
3363
  useEffect(() => {
@@ -3238,7 +3414,7 @@ function MCPAppsRendererSurface({
3238
3414
  pendingRpcMethods.set(request.id, request.method);
3239
3415
  }
3240
3416
  if (SUPPRESSED_UI_LOG_METHODS.has(method)) return;
3241
- logUiEvent({
3417
+ logUiEventRef.current({
3242
3418
  widgetId: toolCallIdRef.current,
3243
3419
  serverId: serverIdRef.current,
3244
3420
  direction: "host-to-ui",
@@ -3264,7 +3440,7 @@ function MCPAppsRendererSurface({
3264
3440
  }
3265
3441
  }
3266
3442
  if (SUPPRESSED_UI_LOG_METHODS.has(method)) return;
3267
- logUiEvent({
3443
+ logUiEventRef.current({
3268
3444
  widgetId: toolCallIdRef.current,
3269
3445
  serverId: serverIdRef.current,
3270
3446
  direction: "ui-to-host",
@@ -3314,32 +3490,28 @@ function MCPAppsRendererSurface({
3314
3490
  }
3315
3491
  bridge.close().catch(() => {
3316
3492
  });
3317
- setWidgetModelContext(toolCallIdRef.current, null);
3493
+ setWidgetModelContextRef.current(toolCallIdRef.current, null);
3318
3494
  };
3319
3495
  }, [
3320
- logUiEvent,
3321
- minimalMode,
3322
- serverId,
3323
3496
  widgetHtml,
3324
3497
  sandboxProxyReady,
3325
3498
  registerBridgeHandlers,
3326
3499
  refreshAppProvidedTools,
3327
- setWidgetModelContext,
3328
- cspMode,
3329
3500
  // Bridge must rebuild when the resolved sandbox policy changes — a host
3330
3501
  // toggling sandbox policy at runtime needs the new handshake. The memo
3331
- // identity captures `widgetCsp`/`widgetPermissions`/`widgetPermissive`
3332
- // and the sandbox slice of mcpProfile transitively.
3333
- effectiveSandbox,
3502
+ // identity key captures `widgetCsp`/`widgetPermissions`/`widgetPermissive`
3503
+ // and the sandbox slice of mcpProfile transitively without treating
3504
+ // reference-only object churn as a reload signal.
3505
+ effectiveSandboxKey,
3334
3506
  logWidgetDebug,
3335
3507
  // Bridge must rebuild when the advertised host capabilities change
3336
3508
  // (host style switch or override edit) so the new handshake reflects
3337
3509
  // the new contract.
3338
- effectiveHostCapabilities,
3510
+ effectiveHostCapabilitiesKey,
3339
3511
  // Bridge must rebuild when the host identity advertised in
3340
3512
  // ui/initialize changes — switching to a template that overrides
3341
3513
  // hostInfo (e.g. ChatGPT) is observable to the View.
3342
- resolvedBridgeHostInfo
3514
+ resolvedBridgeHostInfoKey
3343
3515
  ]);
3344
3516
  useEffect(() => {
3345
3517
  const bridge = bridgeRef.current;
@@ -3394,6 +3566,37 @@ function MCPAppsRendererSurface({
3394
3566
  handleCspViolation(event);
3395
3567
  return;
3396
3568
  }
3569
+ if (data.type === "recorder:step") {
3570
+ recorderDebug2("step from sandbox", {
3571
+ toolName,
3572
+ toolCallId,
3573
+ recordMode: !!recordMode
3574
+ });
3575
+ onRecorderStep?.(data.step);
3576
+ return;
3577
+ }
3578
+ if (data.type === "recorder:ready") {
3579
+ recorderDebug2("ready from sandbox", {
3580
+ toolName,
3581
+ toolCallId,
3582
+ recordMode: !!recordMode
3583
+ });
3584
+ onRecorderReady?.();
3585
+ return;
3586
+ }
3587
+ if (data.type === "recorder:replay-result") {
3588
+ const pending = typeof data.id === "number" ? pendingReplaysRef.current.get(data.id) : void 0;
3589
+ if (pending) {
3590
+ clearTimeout(pending.timer);
3591
+ pendingReplaysRef.current.delete(data.id);
3592
+ pending.resolve({
3593
+ ok: !!data.ok,
3594
+ reason: data.reason,
3595
+ deferred: data.deferred
3596
+ });
3597
+ }
3598
+ return;
3599
+ }
3397
3600
  const liveCaps = liveOpenAiCompatCapabilitiesRef.current;
3398
3601
  const policyError = (callId, method) => {
3399
3602
  sandboxRef.current?.postMessage({
@@ -3443,10 +3646,7 @@ function MCPAppsRendererSurface({
3443
3646
  }
3444
3647
  if (data.type === "openai:setOpenInAppUrl") {
3445
3648
  if (liveCaps !== null && liveCaps.setOpenInAppUrl === false) return;
3446
- const nextUrl = resolveOpenInAppHref(
3447
- data.href,
3448
- explicitOpenInAppBaseUrl
3449
- );
3649
+ const nextUrl = resolveOpenInAppHref(data.href, explicitOpenInAppBaseUrl);
3450
3650
  if (nextUrl) {
3451
3651
  setOpenInAppUrlOverride(nextUrl);
3452
3652
  }
@@ -3618,6 +3818,7 @@ function MCPAppsRendererSurface({
3618
3818
  allowFeatures: effectiveSandbox.allowFeatures,
3619
3819
  cspDirectives: effectiveSandbox.cspDirectives,
3620
3820
  colorScheme: resolvedTheme,
3821
+ recordMode,
3621
3822
  onProxyReady: () => {
3622
3823
  setSandboxProxyReady(true);
3623
3824
  logWidgetDebug("ui-to-host", "debug/sandbox-proxy-ready", {