@mcpjam/widget-react 0.2.1 → 0.2.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.js CHANGED
@@ -108,11 +108,65 @@ function readToolResultServerId(result) {
108
108
  return typeof meta?._serverId === "string" ? meta._serverId : void 0;
109
109
  }
110
110
  var WidgetWorkspaceContext = createContext(null);
111
+ function updateAppPresentation(instances, bridgeId, presentation) {
112
+ const instance = instances.get(bridgeId);
113
+ if (!instance || JSON.stringify(instance.presentation) === JSON.stringify(presentation))
114
+ return instances;
115
+ const next = new Map(instances);
116
+ next.set(bridgeId, { ...instance, presentation });
117
+ return next;
118
+ }
119
+ function appToolPresentation(label, element) {
120
+ const presentation = label ? { label: label.replace(/\s+/g, " ").trim().slice(0, 200) } : {};
121
+ if (!element) return presentation;
122
+ presentation.visibility = element.isConnected ? "visible" : "hidden";
123
+ const visibility = getComputedStyle(element).visibility;
124
+ if (visibility === "hidden" || visibility === "collapse")
125
+ presentation.visibility = "hidden";
126
+ for (let node = element; node; node = node.parentElement) {
127
+ const style = getComputedStyle(node);
128
+ if (node.hidden || style.display === "none" || style.contentVisibility === "hidden") {
129
+ presentation.visibility = "hidden";
130
+ break;
131
+ }
132
+ }
133
+ return presentation;
134
+ }
135
+ function useAppToolPresentation(registry, bridgeId, label, getElement) {
136
+ const current = useRef({ label, getElement });
137
+ useLayoutEffect(() => {
138
+ current.current = { label, getElement };
139
+ });
140
+ const read = useCallback(
141
+ () => appToolPresentation(current.current.label, current.current.getElement()),
142
+ []
143
+ );
144
+ useLayoutEffect(() => {
145
+ if (!bridgeId) return;
146
+ const observer = new MutationObserver(() => update());
147
+ function update() {
148
+ observer.disconnect();
149
+ registry.getState().updatePresentation(bridgeId, read());
150
+ for (let node = current.current.getElement(); node; node = node.parentElement)
151
+ observer.observe(node, {
152
+ attributes: true,
153
+ attributeFilter: ["hidden", "class", "style"],
154
+ childList: true
155
+ });
156
+ }
157
+ update();
158
+ return () => observer.disconnect();
159
+ });
160
+ return read;
161
+ }
111
162
 
112
163
  // src/app-tools-catalog.ts
113
164
  var MAX_SNAPSHOT_ENTRIES = 64;
114
165
  var MAX_DESCRIPTION_CHARS = 512;
115
166
  var MAX_INPUT_SCHEMA_BYTES = 8 * 1024;
167
+ function modelChatSessionId(instance) {
168
+ return instance.getModelChatSessionId ? instance.getModelChatSessionId() : instance.chatSessionId;
169
+ }
116
170
  function listAppToolCatalog(state, chatSessionId) {
117
171
  const offered = [];
118
172
  const dropped = [];
@@ -120,9 +174,9 @@ function listAppToolCatalog(state, chatSessionId) {
120
174
  for (const [alias, reference] of state.aliases) {
121
175
  if (!/^app_[a-z0-9]{8}$/i.test(alias)) continue;
122
176
  const instance = state.instancesByBridgeId.get(reference.bridgeId);
123
- if (!instance || instance.chatSessionId !== chatSessionId) continue;
177
+ if (!instance || modelChatSessionId(instance) !== chatSessionId) continue;
124
178
  if (state.activeBridgeByParent.get(
125
- `${chatSessionId}\0${instance.parentToolCallId}`
179
+ instance.chatSessionId ? `${instance.chatSessionId}\0${instance.parentToolCallId}` : instance.parentToolCallId
126
180
  ) !== instance.bridgeId)
127
181
  continue;
128
182
  const tool = instance.tools.find((tool2) => tool2.name === reference.rawName);
@@ -156,6 +210,15 @@ function listAppToolCatalog(state, chatSessionId) {
156
210
  for (const entry of offered) {
157
211
  const key = `${entry.instance.appName}\0${entry.rawName}`;
158
212
  const total = counts.get(key) ?? 1;
213
+ const presentation = entry.instance.presentation;
214
+ if (presentation?.label || presentation?.visibility) {
215
+ const label = presentation.label?.replace(/\s+/g, " ").trim().slice(0, 200).replace(/[\[\];]/g, (character) => ({ "[": "\uFF3B", "]": "\uFF3D", ";": "\uFF1B" })[character]);
216
+ const prefix = `[${[label, presentation.visibility].filter(Boolean).join("; ")}] `;
217
+ const hint2 = total > 1 ? ` (instance ${(indices.get(key) ?? 0) + 1} of ${total})` : "";
218
+ entry.description = prefix + (entry.description ?? "").slice(0, Math.max(0, MAX_DESCRIPTION_CHARS - prefix.length - hint2.length)) + hint2;
219
+ indices.set(key, (indices.get(key) ?? 0) + 1);
220
+ continue;
221
+ }
159
222
  if (total <= 1) continue;
160
223
  const index = (indices.get(key) ?? 0) + 1;
161
224
  indices.set(key, index);
@@ -432,6 +495,10 @@ function createAppToolsRegistry(options = {}) {
432
495
  return { activeBridgeByParent: next };
433
496
  });
434
497
  },
498
+ updatePresentation: (bridgeId, presentation) => set((state) => {
499
+ const instancesByBridgeId = updateAppPresentation(state.instancesByBridgeId, bridgeId, presentation);
500
+ return instancesByBridgeId === state.instancesByBridgeId ? state : { instancesByBridgeId };
501
+ }),
435
502
  snapshotForChatBody: (chatSessionId) => {
436
503
  const catalog = listAppToolCatalog(get(), chatSessionId);
437
504
  const capped = catalog.dropped.filter(
@@ -446,6 +513,7 @@ function createAppToolsRegistry(options = {}) {
446
513
  ({ alias, instance, rawName, description, inputSchema, readOnly }) => ({
447
514
  alias,
448
515
  appName: instance.appName,
516
+ bridgeId: instance.bridgeId,
449
517
  appVersion: instance.appVersion,
450
518
  serverId: instance.serverId,
451
519
  parentToolCallId: instance.parentToolCallId,
@@ -476,7 +544,7 @@ function createAppToolsRegistry(options = {}) {
476
544
  if (!a) return null;
477
545
  const inst = get().instancesByBridgeId.get(a.bridgeId);
478
546
  if (!inst) return null;
479
- if (chatSessionId && inst.chatSessionId !== chatSessionId) return null;
547
+ if (chatSessionId && modelChatSessionId(inst) !== chatSessionId) return null;
480
548
  if (get().activeBridgeByParent.get(
481
549
  getActiveParentKey(inst.parentToolCallId, inst.chatSessionId)
482
550
  ) !== inst.bridgeId) {
@@ -948,6 +1016,121 @@ function useToolInputStreaming({
948
1016
  resetStreamingState
949
1017
  };
950
1018
  }
1019
+
1020
+ // src/sandbox-view-error.ts
1021
+ var SandboxViewAdmissionError = class extends Error {
1022
+ constructor(retryable = false) {
1023
+ super("Could not open this App securely. Close it and try again.");
1024
+ this.retryable = retryable;
1025
+ this.name = "SandboxViewAdmissionError";
1026
+ }
1027
+ };
1028
+
1029
+ // src/use-sandbox-view.ts
1030
+ function releaseEntry(entry) {
1031
+ if (entry.disposed) return;
1032
+ entry.disposed = true;
1033
+ clearTimeout(entry.timer);
1034
+ clearTimeout(entry.expiryTimer);
1035
+ if (entry.result) {
1036
+ entry.controller.abort();
1037
+ void entry.release({ admissionId: entry.result.admissionId }).catch(() => {
1038
+ });
1039
+ }
1040
+ }
1041
+ function useSandboxView(admission) {
1042
+ const html = admission?.request.html;
1043
+ const recipe = stableStringifyJson({
1044
+ source: admission?.request.source,
1045
+ sourceReceipt: admission?.request.sourceReceipt,
1046
+ policy: admission?.request.policy,
1047
+ mode: admission?.request.mode
1048
+ });
1049
+ const key = useMemo(
1050
+ () => html === void 0 ? null : stableStringifyJson({ html, recipe }),
1051
+ [html, recipe]
1052
+ );
1053
+ const latest = useRef(admission);
1054
+ latest.current = admission;
1055
+ const entryRef = useRef(null);
1056
+ const [state, setState] = useState(null);
1057
+ const prepare = admission?.services.prepareSandboxView;
1058
+ const release = admission?.services.releaseSandboxView;
1059
+ useEffect(() => {
1060
+ if (!key || !prepare || !release || !latest.current?.request.html) return;
1061
+ let entry = entryRef.current;
1062
+ if (!entry || entry.disposed || entry.key !== key || entry.prepare !== prepare) {
1063
+ if (entry) releaseEntry(entry);
1064
+ const request = {
1065
+ ...latest.current.request,
1066
+ viewInstanceId: crypto.randomUUID(),
1067
+ hostOrigin: window.location.origin
1068
+ };
1069
+ const controller = new AbortController();
1070
+ entry = {
1071
+ key,
1072
+ prepare,
1073
+ release,
1074
+ request,
1075
+ controller,
1076
+ users: 0,
1077
+ disposed: false,
1078
+ pending: prepare(request, controller.signal)
1079
+ };
1080
+ entryRef.current = entry;
1081
+ }
1082
+ const owned = entry;
1083
+ owned.users++;
1084
+ let active = true;
1085
+ const renew = () => {
1086
+ if (owned.disposed || !owned.result) return;
1087
+ owned.pending = owned.prepare(
1088
+ { ...owned.request, admissionId: owned.result.admissionId },
1089
+ owned.controller.signal
1090
+ );
1091
+ void owned.pending.then(accept, fail);
1092
+ };
1093
+ const fail = (error) => {
1094
+ if (active && !owned.disposed) {
1095
+ const remaining = (owned.result?.expiresAt ?? 0) - Date.now();
1096
+ if (remaining > 0 && !(error instanceof SandboxViewAdmissionError && !error.retryable)) {
1097
+ owned.timer = setTimeout(renew, Math.min(3e4, remaining));
1098
+ return;
1099
+ }
1100
+ releaseEntry(owned);
1101
+ setState({ key, error: new SandboxViewAdmissionError().message });
1102
+ }
1103
+ };
1104
+ const accept = (result) => {
1105
+ owned.result = result;
1106
+ if (owned.disposed) {
1107
+ owned.controller.abort();
1108
+ void owned.release({ admissionId: result.admissionId }).catch(() => {
1109
+ });
1110
+ return;
1111
+ }
1112
+ if (!active) return;
1113
+ setState({ key, result });
1114
+ clearTimeout(owned.timer);
1115
+ clearTimeout(owned.expiryTimer);
1116
+ owned.expiryTimer = setTimeout(() => fail(new SandboxViewAdmissionError()), Math.max(1, result.expiresAt - Date.now()));
1117
+ owned.timer = setTimeout(renew, Math.max(1e3, Math.min(30 * 6e4, result.expiresAt - Date.now() - 6e4)));
1118
+ };
1119
+ void owned.pending.then(accept, fail);
1120
+ return () => {
1121
+ active = false;
1122
+ owned.users--;
1123
+ queueMicrotask(() => {
1124
+ if (owned.users === 0) releaseEntry(owned);
1125
+ });
1126
+ };
1127
+ }, [key, prepare, release]);
1128
+ return {
1129
+ required: Boolean(admission),
1130
+ result: state?.key === key ? state.result : void 0,
1131
+ error: state?.key === key ? state.error : void 0
1132
+ };
1133
+ }
951
1134
  function isRecorderDebugEnabled() {
952
1135
  try {
953
1136
  return typeof window !== "undefined" && window.localStorage?.getItem("mcpjam:recorder-debug") === "1";
@@ -1037,6 +1220,7 @@ function resolveSandboxProxyUrl({
1037
1220
  }
1038
1221
  var SandboxedIframe = forwardRef(function SandboxedIframe2({
1039
1222
  html,
1223
+ viewAdmission,
1040
1224
  sandbox = "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",
1041
1225
  csp,
1042
1226
  permissions,
@@ -1068,7 +1252,8 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
1068
1252
  const onProxyReadyRef = useRef(onProxyReady);
1069
1253
  onMessageRef.current = onMessage;
1070
1254
  onProxyReadyRef.current = onProxyReady;
1071
- const sandboxProxyUrl = useMemo(
1255
+ const preparedView = useSandboxView(viewAdmission);
1256
+ const legacyProxyUrl = useMemo(
1072
1257
  () => resolveSandboxProxyUrl({
1073
1258
  hostedMode,
1074
1259
  sandboxOrigin,
@@ -1080,9 +1265,10 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
1080
1265
  // eslint-disable-next-line react-hooks/exhaustive-deps
1081
1266
  [hostedMode, sandboxOrigin, viewOriginLabel, viewSubdomainsEnabled]
1082
1267
  );
1268
+ const sandboxProxyUrl = preparedView.required ? preparedView.result?.proxyUrl : legacyProxyUrl;
1083
1269
  const sandboxProxyOrigin = useMemo(() => {
1084
1270
  try {
1085
- return new URL(sandboxProxyUrl).origin;
1271
+ return new URL(sandboxProxyUrl ?? "about:blank").origin;
1086
1272
  } catch {
1087
1273
  return "*";
1088
1274
  }
@@ -1091,14 +1277,15 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
1091
1277
  ref,
1092
1278
  () => ({
1093
1279
  postMessage: (data) => {
1094
- outerRef.current?.contentWindow?.postMessage(data, sandboxProxyOrigin);
1280
+ if (sandboxProxyUrl) outerRef.current?.contentWindow?.postMessage(data, sandboxProxyOrigin);
1095
1281
  },
1096
1282
  getIframeElement: () => outerRef.current
1097
1283
  }),
1098
- [sandboxProxyOrigin]
1284
+ [sandboxProxyOrigin, sandboxProxyUrl]
1099
1285
  );
1100
1286
  const handleMessage = useCallback(
1101
1287
  (event) => {
1288
+ if (!sandboxProxyUrl) return;
1102
1289
  if (event.origin !== sandboxProxyOrigin && sandboxProxyOrigin !== "*") {
1103
1290
  return;
1104
1291
  }
@@ -1140,7 +1327,7 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
1140
1327
  }
1141
1328
  onMessageRef.current(event);
1142
1329
  },
1143
- [sandboxProxyOrigin]
1330
+ [sandboxProxyOrigin, sandboxProxyUrl]
1144
1331
  );
1145
1332
  useEffect(() => {
1146
1333
  window.addEventListener("message", handleMessage);
@@ -1252,24 +1439,49 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
1252
1439
  const iframeStyle = colorScheme ? { ...style, colorScheme } : style;
1253
1440
  useEffect(() => {
1254
1441
  setProxyReady(false);
1255
- }, [outerSandboxAttribute, sandboxProxyOrigin]);
1442
+ }, [outerSandboxAttribute, sandboxProxyUrl]);
1443
+ if (preparedView.error) return /* @__PURE__ */ jsx("div", { role: "alert", children: preparedView.error });
1256
1444
  return /* @__PURE__ */ jsx(
1257
1445
  "iframe",
1258
1446
  {
1259
1447
  ref: outerRef,
1260
- src: sandboxProxyUrl,
1448
+ src: sandboxProxyUrl ?? "about:blank",
1261
1449
  sandbox: outerSandboxAttribute,
1262
1450
  allow: outerAllowAttribute,
1263
1451
  title,
1264
1452
  className,
1265
1453
  style: iframeStyle
1266
1454
  },
1267
- `${sandboxProxyOrigin}\0${outerSandboxAttribute}`
1455
+ `${preparedView.required ? "admitted" : sandboxProxyOrigin}\0${outerSandboxAttribute}`
1268
1456
  );
1269
1457
  });
1458
+ var SANDBOX_READY_TIMEOUT_MS = 3e4;
1459
+ function useSandboxReadyDeadline({
1460
+ waiting,
1461
+ identity,
1462
+ onTimeout
1463
+ }) {
1464
+ const callback = useRef(onTimeout);
1465
+ callback.current = onTimeout;
1466
+ useEffect(() => {
1467
+ if (!waiting) return;
1468
+ const timer = window.setTimeout(
1469
+ () => callback.current(),
1470
+ SANDBOX_READY_TIMEOUT_MS
1471
+ );
1472
+ return () => window.clearTimeout(timer);
1473
+ }, [waiting, identity]);
1474
+ }
1270
1475
  function createAppToolDiscovery(config) {
1271
1476
  const states = /* @__PURE__ */ new WeakMap();
1272
1477
  return function refresh(bridge, bridgeId, options) {
1478
+ const readContext = () => {
1479
+ const context = config.context();
1480
+ return options.getIframeElement ? {
1481
+ ...context,
1482
+ presentation: appToolPresentation(context.presentation?.label, options.getIframeElement())
1483
+ } : context;
1484
+ };
1273
1485
  let state = states.get(bridge);
1274
1486
  if (!state) {
1275
1487
  state = {
@@ -1326,7 +1538,7 @@ function createAppToolDiscovery(config) {
1326
1538
  if (result.source === "webmcp" && result.tools.length === 0) {
1327
1539
  config.registry.getState().unregisterInstance(bridgeId);
1328
1540
  } else {
1329
- const context = config.context();
1541
+ const context = readContext();
1330
1542
  const version = bridge.getAppVersion();
1331
1543
  await config.registry.getState().registerInstance({
1332
1544
  ...context,
@@ -1342,6 +1554,7 @@ function createAppToolDiscovery(config) {
1342
1554
  });
1343
1555
  if (!options.isLive())
1344
1556
  config.registry.getState().unregisterInstance(bridgeId);
1557
+ else config.registry.getState().updatePresentation(bridgeId, readContext().presentation ?? {});
1345
1558
  }
1346
1559
  } while (current.dirty && options.isLive());
1347
1560
  } catch (error) {
@@ -1357,6 +1570,87 @@ function createAppToolDiscovery(config) {
1357
1570
  return current.pending;
1358
1571
  };
1359
1572
  }
1573
+ function useFullscreenDismissal(args) {
1574
+ const current = useRef(args);
1575
+ useLayoutEffect(() => {
1576
+ current.current = args;
1577
+ });
1578
+ const [dismissed, setDismissed] = useState(false);
1579
+ const [pendingCount, setPendingCount] = useState(0);
1580
+ const pending = useRef(/* @__PURE__ */ new Set());
1581
+ const collapsed = args.enabled && args.fullscreen && (dismissed || !args.canInline && args.unowned);
1582
+ const conceal = useCallback(() => {
1583
+ const value = current.current;
1584
+ if (!value.enabled || !value.fullscreen) return;
1585
+ setDismissed(true);
1586
+ value.exit();
1587
+ }, []);
1588
+ const dismiss = useCallback(() => {
1589
+ const value = current.current;
1590
+ if (!value.enabled || !value.fullscreen) return;
1591
+ if (value.canInline) value.inline();
1592
+ else conceal();
1593
+ }, [conceal]);
1594
+ const open = useCallback(() => {
1595
+ if (pending.current.size || current.current.hostInputPending) return;
1596
+ setDismissed(false);
1597
+ current.current.open();
1598
+ }, []);
1599
+ useEffect(() => {
1600
+ if (!args.fullscreen || !args.enabled) setDismissed(false);
1601
+ }, [args.fullscreen, args.enabled]);
1602
+ useLayoutEffect(() => {
1603
+ if (args.hostInputPending || pendingCount > 0) conceal();
1604
+ }, [
1605
+ args.hostInputPending,
1606
+ args.fullscreen,
1607
+ args.enabled,
1608
+ pendingCount,
1609
+ conceal
1610
+ ]);
1611
+ useEffect(() => {
1612
+ if (!args.enabled || !args.fullscreen || collapsed) return;
1613
+ const keydown = (event) => {
1614
+ const element = current.current.element();
1615
+ if (event.key !== "Escape" || event.defaultPrevented || pending.current.size || current.current.hostInputPending || !element?.contains(document.activeElement))
1616
+ return;
1617
+ event.preventDefault();
1618
+ dismiss();
1619
+ };
1620
+ window.addEventListener("keydown", keydown);
1621
+ return () => window.removeEventListener("keydown", keydown);
1622
+ }, [args.enabled, args.fullscreen, collapsed, dismiss]);
1623
+ const trackInput = useCallback(
1624
+ (report) => {
1625
+ const id = Symbol();
1626
+ let finished = false;
1627
+ const update = (waiting) => {
1628
+ if (finished) return;
1629
+ if (waiting) {
1630
+ pending.current.add(id);
1631
+ conceal();
1632
+ } else pending.current.delete(id);
1633
+ setPendingCount(pending.current.size);
1634
+ report?.(waiting);
1635
+ };
1636
+ return {
1637
+ update,
1638
+ finish: () => {
1639
+ if (pending.current.has(id)) update(false);
1640
+ finished = true;
1641
+ }
1642
+ };
1643
+ },
1644
+ [conceal]
1645
+ );
1646
+ return {
1647
+ collapsed,
1648
+ dismiss,
1649
+ open,
1650
+ trackInput,
1651
+ pending: pendingCount > 0 || args.hostInputPending
1652
+ };
1653
+ }
1360
1654
  function useInitialRenderOutcome(ready, failed, notify) {
1361
1655
  const delivered = useRef(false);
1362
1656
  const callback = useRef(notify);
@@ -1432,6 +1726,8 @@ function McpAppsModal({
1432
1726
  const appToolsRegistry = useAppToolsRegistryApi();
1433
1727
  const Modal = host.components?.Modal;
1434
1728
  const [modalHtml, setModalHtml] = useState(null);
1729
+ const [sourceReceipt, setSourceReceipt] = useState();
1730
+ const [sandboxSource, setSandboxSource] = useState({ serverId, resourceUri, toolCallId });
1435
1731
  const modalSandboxRef = useRef(null);
1436
1732
  const modalBridgeRef = useRef(null);
1437
1733
  const modalAppToolsBridgeIdRef = useRef(null);
@@ -1446,11 +1742,13 @@ function McpAppsModal({
1446
1742
  modalAppToolsBridgeIdRef.current = null;
1447
1743
  }
1448
1744
  setModalHtml(null);
1745
+ setSourceReceipt(void 0);
1449
1746
  return;
1450
1747
  }
1748
+ let active = true;
1451
1749
  const fetchModalHtml = async () => {
1452
1750
  try {
1453
- const { html } = await host.services.fetchWidgetContent({
1751
+ const { html, sourceReceipt: receipt } = await host.services.fetchWidgetContent({
1454
1752
  serverId,
1455
1753
  forceWebEndpoint: webManagedServers,
1456
1754
  resourceUri,
@@ -1465,12 +1763,18 @@ function McpAppsModal({
1465
1763
  viewMode: "modal",
1466
1764
  viewParams: params
1467
1765
  });
1766
+ if (!active) return;
1468
1767
  setModalHtml(html);
1768
+ setSourceReceipt(receipt);
1769
+ setSandboxSource({ serverId, resourceUri, toolCallId });
1469
1770
  } catch (err) {
1470
1771
  console.error("[MCP Apps] Failed to fetch modal HTML", err);
1471
1772
  }
1472
1773
  };
1473
1774
  fetchModalHtml();
1775
+ return () => {
1776
+ active = false;
1777
+ };
1474
1778
  }, [
1475
1779
  appToolsRegistry,
1476
1780
  open,
@@ -1652,6 +1956,21 @@ function McpAppsModal({
1652
1956
  {
1653
1957
  ref: modalSandboxRef,
1654
1958
  html: modalHtml,
1959
+ viewAdmission: host.services.prepareSandboxView ? {
1960
+ services: host.services,
1961
+ request: {
1962
+ source: sandboxSource,
1963
+ sourceReceipt,
1964
+ html: modalHtml,
1965
+ policy: {
1966
+ csp: widgetCsp,
1967
+ cspDirectives: widgetCspDirectives,
1968
+ cspSubtypePolicy: widgetCspSubtypePolicy,
1969
+ permissive: widgetPermissive
1970
+ },
1971
+ mode: widgetPermissive || Object.keys(widgetCspDirectives ?? {}).length > 0 ? "debugger" : "declared"
1972
+ }
1973
+ } : void 0,
1655
1974
  sandbox: "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",
1656
1975
  csp: widgetCsp,
1657
1976
  permissions: widgetPermissions,
@@ -2306,7 +2625,10 @@ function MCPAppsRenderer(props) {
2306
2625
  return /* @__PURE__ */ jsx(PersistentMCPAppsRendererRegistration, { ...props });
2307
2626
  }
2308
2627
  function MCPAppsRendererSurface({
2628
+ appToolSourceLabel,
2629
+ hostInputPending = false,
2309
2630
  chatSessionId,
2631
+ getModelChatSessionId,
2310
2632
  serverId,
2311
2633
  serverName,
2312
2634
  toolCallId,
@@ -2517,6 +2839,9 @@ function MCPAppsRendererSurface({
2517
2839
  ]
2518
2840
  );
2519
2841
  const advertisedAvailableDisplayModes = effectiveAvailableDisplayModes;
2842
+ useEffect(() => {
2843
+ onAppSupportedDisplayModesChange?.(effectiveAvailableDisplayModes);
2844
+ }, [effectiveAvailableDisplayModes, onAppSupportedDisplayModesChange]);
2520
2845
  const playgroundCapabilities = environment.playgroundCapabilities;
2521
2846
  const configuredCapabilities = draftHostContext?.deviceCapabilities && typeof draftHostContext.deviceCapabilities === "object" && !Array.isArray(draftHostContext.deviceCapabilities) ? draftHostContext.deviceCapabilities : void 0;
2522
2847
  const deviceCapabilities = useMemo(() => {
@@ -2616,16 +2941,30 @@ function MCPAppsRendererSurface({
2616
2941
  displayMode
2617
2942
  ]
2618
2943
  );
2944
+ const fullscreenContainerRef = useRef(null);
2945
+ const fullscreenDismissal = useFullscreenDismissal({
2946
+ fullscreen: effectiveDisplayMode === "fullscreen",
2947
+ enabled: !hostManagedPresentation,
2948
+ canInline: effectiveAvailableDisplayModes.includes("inline"),
2949
+ unowned: fixedDisplayMode === void 0 && isControlled && !!onRequestFullscreen && !ownsFullscreenDisplayMode,
2950
+ hostInputPending,
2951
+ element: () => fullscreenContainerRef.current,
2952
+ inline: () => {
2953
+ userPreferInlineRef.current = true;
2954
+ setDisplayMode("inline");
2955
+ },
2956
+ exit: () => onExitFullscreen?.(displayWidgetId),
2957
+ open: () => setDisplayMode("fullscreen")
2958
+ });
2619
2959
  const lastForcedDisplayModeRef = useRef(null);
2620
2960
  const fullscreenPlacement = useContext(WidgetFullscreenPlacementContext);
2621
- const placedFullscreen = !hostManagedPresentation && effectiveDisplayMode === "fullscreen" && !(isPlaygroundActive && (playgroundDeviceType === "mobile" || playgroundDeviceType === "tablet")) && !!fullscreenPlacement?.rect;
2961
+ const placedFullscreen = !hostManagedPresentation && effectiveDisplayMode === "fullscreen" && !fullscreenDismissal.collapsed && !(isPlaygroundActive && (playgroundDeviceType === "mobile" || playgroundDeviceType === "tablet")) && !!fullscreenPlacement?.rect;
2622
2962
  const fullscreenPlacementRef = useRef(fullscreenPlacement);
2623
2963
  fullscreenPlacementRef.current = fullscreenPlacement;
2624
2964
  const placedExitRef = useRef(() => {
2625
2965
  });
2626
2966
  placedExitRef.current = () => {
2627
- userPreferInlineRef.current = true;
2628
- setDisplayMode("inline");
2967
+ fullscreenDismissal.dismiss();
2629
2968
  };
2630
2969
  const fullscreenLabel = serverName?.trim() || serverId.trim() || "App";
2631
2970
  useEffect(() => {
@@ -2637,6 +2976,7 @@ function MCPAppsRendererSurface({
2637
2976
  return () => fullscreenPlacementRef.current?.onLeave?.();
2638
2977
  }, [placedFullscreen, fullscreenLabel]);
2639
2978
  useEffect(() => {
2979
+ if (fullscreenDismissal.collapsed) return;
2640
2980
  if (requestedDisplayMode === effectiveDisplayMode) {
2641
2981
  lastForcedDisplayModeRef.current = null;
2642
2982
  return;
@@ -2646,7 +2986,7 @@ function MCPAppsRendererSurface({
2646
2986
  }
2647
2987
  lastForcedDisplayModeRef.current = effectiveDisplayMode;
2648
2988
  setDisplayMode(effectiveDisplayMode);
2649
- }, [effectiveDisplayMode, requestedDisplayMode, setDisplayMode]);
2989
+ }, [effectiveDisplayMode, requestedDisplayMode, setDisplayMode, fullscreenDismissal.collapsed]);
2650
2990
  const [isReady, setIsReady] = useState(false);
2651
2991
  const [reinitCount, setReinitCount] = useState(0);
2652
2992
  const [loadError, setLoadError] = useState(null);
@@ -2687,6 +3027,8 @@ function MCPAppsRendererSurface({
2687
3027
  const [widgetPermissive, setWidgetPermissive] = useState(
2688
3028
  isCachedReplay ? true : initialWidgetPermissive ?? false
2689
3029
  );
3030
+ const [sourceReceipt, setSourceReceipt] = useState();
3031
+ const [sandboxSource, setSandboxSource] = useState({ serverId, resourceUri, toolCallId });
2690
3032
  const [viewOriginLabel, setViewOriginLabel] = useState(
2691
3033
  void 0
2692
3034
  );
@@ -2740,6 +3082,7 @@ function MCPAppsRendererSurface({
2740
3082
  hasRenderedLiveRef.current = false;
2741
3083
  liveRenderIdentityRef.current = null;
2742
3084
  setWidgetHtml(null);
3085
+ setSourceReceipt(void 0);
2743
3086
  setResourceDisplayHints(void 0);
2744
3087
  setBridgeTransportReady(false);
2745
3088
  setLoadedCspMode(null);
@@ -2800,9 +3143,6 @@ function MCPAppsRendererSurface({
2800
3143
  const ownsPipDisplayModeRef = useRef(ownsPipDisplayMode);
2801
3144
  const toolsMetadataRef = useRef(toolsMetadata);
2802
3145
  const onModelContextUpdateRef = useRef(onModelContextUpdate);
2803
- const onAppSupportedDisplayModesChangeRef = useRef(
2804
- onAppSupportedDisplayModesChange
2805
- );
2806
3146
  const toolInputRef = useRef(toolInput);
2807
3147
  toolInputRef.current = toolInput;
2808
3148
  const toolOutputRef = useRef(toolOutput);
@@ -2876,6 +3216,7 @@ function MCPAppsRendererSurface({
2876
3216
  hasRenderedLiveRef.current = false;
2877
3217
  liveRenderIdentityRef.current = null;
2878
3218
  setWidgetHtml(html);
3219
+ setSourceReceipt(void 0);
2879
3220
  setWidgetCsp(void 0);
2880
3221
  setFirstCspBlock(null);
2881
3222
  setWidgetPermissions(void 0);
@@ -2905,6 +3246,7 @@ function MCPAppsRendererSurface({
2905
3246
  });
2906
3247
  };
2907
3248
  const loadFromLiveFetch = async () => {
3249
+ const fetchedSource = { serverId, resourceUri, toolCallId: toolCallIdRef.current };
2908
3250
  const {
2909
3251
  html,
2910
3252
  csp,
@@ -2916,6 +3258,7 @@ function MCPAppsRendererSurface({
2916
3258
  resourceDisplayHints: resourceHints,
2917
3259
  declaredDomain: serverDeclaredDomain,
2918
3260
  viewOriginLabel: serverViewOriginLabel,
3261
+ sourceReceipt: serverSourceReceipt,
2919
3262
  injectedOpenAiCompat: serverInjectedOpenAiCompat,
2920
3263
  injectedOpenAiCompatCapabilities: serverInjectedOpenAiCompatCapabilities
2921
3264
  } = await host.services.fetchWidgetContent({
@@ -2932,7 +3275,7 @@ function MCPAppsRendererSurface({
2932
3275
  // output for callers that don't pass it.
2933
3276
  toolResponseMetadata: toolResponseMetadata ?? readToolResultMeta(toolOutputRef.current) ?? null,
2934
3277
  initialWidgetState,
2935
- toolId: toolCallIdRef.current,
3278
+ toolId: fetchedSource.toolCallId,
2936
3279
  toolName,
2937
3280
  theme: themeModeRef.current,
2938
3281
  cspMode,
@@ -2975,6 +3318,8 @@ function MCPAppsRendererSurface({
2975
3318
  setDisplayMode(initialMode);
2976
3319
  }
2977
3320
  setWidgetHtml(html);
3321
+ setSourceReceipt(serverSourceReceipt);
3322
+ setSandboxSource(fetchedSource);
2978
3323
  setWidgetCsp(csp);
2979
3324
  setFirstCspBlock(null);
2980
3325
  setWidgetPermissions(permissions);
@@ -3123,13 +3468,20 @@ function MCPAppsRendererSurface({
3123
3468
  },
3124
3469
  []
3125
3470
  );
3471
+ const modelChatAccessorRef = useRef(getModelChatSessionId);
3472
+ modelChatAccessorRef.current = getModelChatSessionId;
3473
+ const readModelChatSessionId = useCallback(
3474
+ () => modelChatAccessorRef.current ? modelChatAccessorRef.current() : chatSessionId,
3475
+ [chatSessionId]
3476
+ );
3477
+ const readAppToolPresentation = useAppToolPresentation(appToolsRegistry, appToolsBridgeIdState, appToolSourceLabel, () => sandboxRef.current?.getIframeElement() ?? null);
3126
3478
  const discoverAppTools = useMemo(() => createAppToolDiscovery({
3127
3479
  registry: appToolsRegistry,
3128
- context: () => ({ chatSessionId, parentToolCallId: toolCallIdRef.current, serverId: serverIdRef.current }),
3480
+ context: () => ({ chatSessionId, getModelChatSessionId: readModelChatSessionId, parentToolCallId: toolCallIdRef.current, serverId: serverIdRef.current, presentation: readAppToolPresentation() }),
3129
3481
  onError: (error) => logWidgetDebug("ui-to-host", "debug/app-tools-list-failed", {
3130
3482
  error: error instanceof Error ? error.message : String(error)
3131
3483
  })
3132
- }), [appToolsRegistry, chatSessionId, logWidgetDebug]);
3484
+ }), [appToolsRegistry, chatSessionId, readModelChatSessionId, logWidgetDebug, readAppToolPresentation]);
3133
3485
  const refreshAppProvidedTools = useCallback((bridge, bridgeId, options = {}) => discoverAppTools(bridge, bridgeId, {
3134
3486
  ...options,
3135
3487
  getIframeElement: options.getIframeElement ?? (() => sandboxRef.current?.getIframeElement() ?? null),
@@ -3695,7 +4047,6 @@ function MCPAppsRendererSurface({
3695
4047
  ownsPipDisplayModeRef.current = ownsPipDisplayMode;
3696
4048
  toolsMetadataRef.current = toolsMetadata;
3697
4049
  onModelContextUpdateRef.current = onModelContextUpdate;
3698
- onAppSupportedDisplayModesChangeRef.current = onAppSupportedDisplayModesChange;
3699
4050
  onRequestTeardownRef.current = onRequestTeardown;
3700
4051
  onConfirmDownloadRef.current = onConfirmDownload;
3701
4052
  }, [
@@ -3716,7 +4067,6 @@ function MCPAppsRendererSurface({
3716
4067
  ownsPipDisplayMode,
3717
4068
  toolsMetadata,
3718
4069
  onModelContextUpdate,
3719
- onAppSupportedDisplayModesChange,
3720
4070
  onRequestTeardown,
3721
4071
  onConfirmDownload
3722
4072
  ]);
@@ -3740,21 +4090,22 @@ function MCPAppsRendererSurface({
3740
4090
  wasReady
3741
4091
  });
3742
4092
  const declaredAppModes = appCaps?.availableDisplayModes;
3743
- onAppSupportedDisplayModesChangeRef.current?.(declaredAppModes);
3744
4093
  const negotiated = displayModesFor(
3745
4094
  hostAvailableDisplayModesRef.current,
3746
4095
  resourceDisplayHintsRef.current,
3747
4096
  declaredAppModes
3748
4097
  );
4098
+ setAppSupportedDisplayModes(declaredAppModes);
3749
4099
  if (negotiated.length === 0) {
3750
4100
  const fixed = fixedDisplayModeRef.current;
3751
4101
  setLoadError(
3752
4102
  openAIRulesRef.current && fixed === "fullscreen" ? "This App can't open here because it doesn't support full screen. Add full screen support to the App, then open it again." : "This App has no supported display mode"
3753
4103
  );
4104
+ setIsReady(false);
4105
+ isReadyRef.current = false;
3754
4106
  void b.close();
3755
4107
  return;
3756
4108
  }
3757
- setAppSupportedDisplayModes(declaredAppModes);
3758
4109
  if (openAIRulesRef.current && !negotiated.includes(effectiveDisplayModeRef.current)) {
3759
4110
  const next = pickOpenAIDisplayMode(
3760
4111
  negotiated,
@@ -3790,14 +4141,20 @@ function MCPAppsRendererSurface({
3790
4141
  onOpenLink: (url) => {
3791
4142
  window.open(url, "_blank", "noopener,noreferrer");
3792
4143
  },
3793
- onCallTool: async (name, invocationInput) => {
4144
+ onCallTool: async (name, invocationInput, context) => {
3794
4145
  if (!onCallToolRef.current) {
3795
4146
  throw new Error("Tool calls not supported");
3796
4147
  }
3797
- return await onCallToolRef.current(
3798
- name,
3799
- invocationInput
3800
- );
4148
+ const input = fullscreenDismissal.trackInput(context?.onInputPending);
4149
+ try {
4150
+ return await onCallToolRef.current(
4151
+ name,
4152
+ invocationInput,
4153
+ context ? { ...context, onInputPending: input.update } : context
4154
+ );
4155
+ } finally {
4156
+ input.finish();
4157
+ }
3801
4158
  },
3802
4159
  onAppToolInvocation: (update) => {
3803
4160
  onAppToolInvocationChangeRef.current?.(update);
@@ -4040,6 +4397,17 @@ function MCPAppsRendererSurface({
4040
4397
  hasWidgetHtml,
4041
4398
  logReady: (details) => logWidgetDebug("ui-to-host", "debug/sandbox-proxy-ready", details)
4042
4399
  });
4400
+ useSandboxReadyDeadline({
4401
+ waiting: !!widgetHtml && sandboxProxyGeneration === 0 && !loadError,
4402
+ identity: toolCallId,
4403
+ onTimeout: () => {
4404
+ setLoadError("The app sandbox did not become ready. Reload this page to try again.");
4405
+ logWidgetDebug("host-to-ui", "debug/sandbox-proxy-timeout", {
4406
+ code: "SANDBOX_PROXY_TIMEOUT",
4407
+ timeoutMs: SANDBOX_READY_TIMEOUT_MS
4408
+ });
4409
+ }
4410
+ });
4043
4411
  useEffect(() => {
4044
4412
  if (!widgetHtml) return;
4045
4413
  if (sandboxProxyGeneration === 0) {
@@ -4587,6 +4955,21 @@ function MCPAppsRendererSurface({
4587
4955
  {
4588
4956
  ref: sandboxRef,
4589
4957
  html: bridgeTransportReady ? widgetHtml : null,
4958
+ viewAdmission: host.services.prepareSandboxView ? {
4959
+ services: host.services,
4960
+ request: {
4961
+ source: sandboxSource,
4962
+ sourceReceipt,
4963
+ html: widgetHtml ?? "",
4964
+ policy: {
4965
+ csp: effectiveSandbox.csp,
4966
+ cspDirectives: effectiveSandbox.cspDirectives,
4967
+ cspSubtypePolicy: effectiveSandbox.cspSubtypePolicy,
4968
+ permissive: effectiveSandbox.permissive
4969
+ },
4970
+ mode: effectiveSandbox.permissive || Object.keys(effectiveSandbox.cspDirectives ?? {}).length > 0 ? "debugger" : "declared"
4971
+ }
4972
+ } : void 0,
4590
4973
  reloadKey: bridgeGeneration,
4591
4974
  sandbox: "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",
4592
4975
  csp: effectiveSandbox.csp,
@@ -4612,193 +4995,197 @@ function MCPAppsRendererSurface({
4612
4995
  style: iframeStyle
4613
4996
  }
4614
4997
  );
4615
- return /* @__PURE__ */ jsxs(
4616
- "div",
4617
- {
4618
- className: containerClassName,
4619
- style: placedFullscreen && fullscreenPlacement?.rect ? {
4620
- inset: "auto",
4621
- top: fullscreenPlacement.rect.top,
4622
- left: fullscreenPlacement.rect.left,
4623
- width: fullscreenPlacement.rect.width,
4624
- height: fullscreenPlacement.rect.height
4625
- } : void 0,
4626
- "data-mcp-app-fullscreen-placed": placedFullscreen || void 0,
4627
- "data-mcp-app-persistent-initial-tool-call-id": persistentSurfaceInitialToolCallId,
4628
- "data-mcp-app-persistent-surface-id": persistentSurfaceId,
4629
- children: [
4630
- !hostManagedPresentation && (isFullscreen && isContainedFullscreenMode || isPip && isMobilePlaygroundMode) && /* @__PURE__ */ jsxs(Fragment, { children: [
4631
- /* @__PURE__ */ jsx(
4998
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
4999
+ fullscreenDismissal.collapsed && /* @__PURE__ */ jsx("button", { className: "rounded-md border border-border px-3 py-2 text-sm text-foreground", disabled: fullscreenDismissal.pending, onClick: fullscreenDismissal.open, children: fullscreenDismissal.pending ? "App is waiting for input" : "Open App" }),
5000
+ /* @__PURE__ */ jsxs(
5001
+ "div",
5002
+ {
5003
+ ref: fullscreenContainerRef,
5004
+ hidden: fullscreenDismissal.collapsed,
5005
+ className: containerClassName,
5006
+ style: fullscreenDismissal.collapsed ? { display: "none" } : placedFullscreen && fullscreenPlacement?.rect ? {
5007
+ inset: "auto",
5008
+ top: fullscreenPlacement.rect.top,
5009
+ left: fullscreenPlacement.rect.left,
5010
+ width: fullscreenPlacement.rect.width,
5011
+ height: fullscreenPlacement.rect.height
5012
+ } : void 0,
5013
+ "data-mcp-app-fullscreen-placed": placedFullscreen || void 0,
5014
+ "data-mcp-app-persistent-initial-tool-call-id": persistentSurfaceInitialToolCallId,
5015
+ "data-mcp-app-persistent-surface-id": persistentSurfaceId,
5016
+ children: [
5017
+ !hostManagedPresentation && (isFullscreen && isContainedFullscreenMode || isPip && isMobilePlaygroundMode) && /* @__PURE__ */ jsxs(Fragment, { children: [
5018
+ /* @__PURE__ */ jsx(
5019
+ "button",
5020
+ {
5021
+ onClick: () => {
5022
+ if (isPip) {
5023
+ userPreferInlineRef.current = true;
5024
+ setDisplayMode("inline");
5025
+ onExitPip?.(pipWidgetId ?? displayWidgetId);
5026
+ } else fullscreenDismissal.dismiss();
5027
+ },
5028
+ 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",
5029
+ "aria-label": "Close",
5030
+ children: /* @__PURE__ */ jsx(X, { className: "w-5 h-5" })
5031
+ }
5032
+ ),
5033
+ showOpenInAppButton && /* @__PURE__ */ jsx(
5034
+ "button",
5035
+ {
5036
+ onClick: handleOpenInApp,
5037
+ 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",
5038
+ "aria-label": `Open in ${openInAppLabel}`,
5039
+ title: `Open in ${openInAppLabel}`,
5040
+ children: /* @__PURE__ */ jsx(ExternalLink, { className: "w-4 h-4" })
5041
+ }
5042
+ )
5043
+ ] }),
5044
+ !hostManagedPresentation && isFullscreen && !isContainedFullscreenMode && /* @__PURE__ */ jsxs("div", { className: `grid items-center gap-3 px-4 h-14 border-b border-border/40 bg-background/95 backdrop-blur z-40 shrink-0 ${placedFullscreen ? "grid-cols-[minmax(0,1fr)_auto]" : "grid-cols-[1fr_auto_1fr]"}`, children: [
5045
+ !placedFullscreen && /* @__PURE__ */ jsx("div", {}),
5046
+ /* @__PURE__ */ jsx("div", { className: `font-medium text-sm text-muted-foreground min-w-0 truncate ${placedFullscreen ? "" : "max-w-[40vw]"}`, children: openInAppLabel }),
5047
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-2 min-w-0", children: [
5048
+ showOpenInAppButton && /* @__PURE__ */ jsxs(
5049
+ "button",
5050
+ {
5051
+ onClick: handleOpenInApp,
5052
+ className: "inline-flex min-w-0 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",
5053
+ "aria-label": `Open in ${openInAppLabel}`,
5054
+ title: `Open in ${openInAppLabel}`,
5055
+ children: [
5056
+ /* @__PURE__ */ jsx(ExternalLink, { className: "w-3.5 h-3.5 shrink-0" }),
5057
+ /* @__PURE__ */ jsxs("span", { className: "hidden sm:inline min-w-0 truncate", children: [
5058
+ "Open in ",
5059
+ openInAppLabel
5060
+ ] })
5061
+ ]
5062
+ }
5063
+ ),
5064
+ /* @__PURE__ */ jsx(
5065
+ "button",
5066
+ {
5067
+ onClick: () => {
5068
+ fullscreenDismissal.dismiss();
5069
+ if (ownsPipDisplayMode) {
5070
+ onExitPip?.(pipWidgetId ?? displayWidgetId);
5071
+ }
5072
+ if (placedFullscreen) fullscreenPlacement?.onExit?.();
5073
+ },
5074
+ className: placedFullscreen && fullscreenPlacement?.exitLabel ? "shrink-0 whitespace-nowrap rounded-lg px-2 py-1 text-sm font-medium text-foreground hover:bg-muted transition-colors" : "p-2 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors",
5075
+ "aria-label": "Exit fullscreen",
5076
+ children: placedFullscreen && fullscreenPlacement?.exitLabel ? fullscreenPlacement.exitLabel : /* @__PURE__ */ jsx(X, { className: "w-5 h-5" })
5077
+ }
5078
+ )
5079
+ ] })
5080
+ ] }),
5081
+ !hostManagedPresentation && isPip && !isMobilePlaygroundMode && /* @__PURE__ */ jsx(
4632
5082
  "button",
4633
5083
  {
4634
5084
  onClick: () => {
4635
5085
  userPreferInlineRef.current = true;
4636
5086
  setDisplayMode("inline");
4637
- if (isPip) {
4638
- onExitPip?.(pipWidgetId ?? displayWidgetId);
4639
- }
5087
+ onExitPip?.(pipWidgetId ?? displayWidgetId);
4640
5088
  },
4641
- 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",
4642
- "aria-label": "Close",
4643
- children: /* @__PURE__ */ jsx(X, { className: "w-5 h-5" })
5089
+ 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",
5090
+ "aria-label": "Close PiP mode",
5091
+ title: "Close PiP mode",
5092
+ children: /* @__PURE__ */ jsx(X, { className: "w-4 h-4" })
4644
5093
  }
4645
5094
  ),
4646
- showOpenInAppButton && /* @__PURE__ */ jsx(
4647
- "button",
5095
+ /* @__PURE__ */ jsx(
5096
+ "div",
4648
5097
  {
4649
- onClick: handleOpenInApp,
4650
- 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",
4651
- "aria-label": `Open in ${openInAppLabel}`,
4652
- title: `Open in ${openInAppLabel}`,
4653
- children: /* @__PURE__ */ jsx(ExternalLink, { className: "w-4 h-4" })
5098
+ "data-testid": showHostChrome ? "mcp-app-host-chrome" : void 0,
5099
+ className: showHostChrome ? "rounded-md" : "contents",
5100
+ style: hostChromeStyle,
5101
+ children: iframe
4654
5102
  }
4655
- )
4656
- ] }),
4657
- !hostManagedPresentation && isFullscreen && !isContainedFullscreenMode && /* @__PURE__ */ jsxs("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", children: [
4658
- /* @__PURE__ */ jsx("div", {}),
4659
- /* @__PURE__ */ jsx("div", { className: "font-medium text-sm text-muted-foreground min-w-0 max-w-[40vw] truncate", children: openInAppLabel }),
4660
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-2 min-w-0", children: [
4661
- showOpenInAppButton && /* @__PURE__ */ jsxs(
4662
- "button",
4663
- {
4664
- onClick: handleOpenInApp,
4665
- 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",
4666
- "aria-label": `Open in ${openInAppLabel}`,
4667
- title: `Open in ${openInAppLabel}`,
4668
- children: [
4669
- /* @__PURE__ */ jsx(ExternalLink, { className: "w-3.5 h-3.5 shrink-0" }),
4670
- /* @__PURE__ */ jsxs("span", { className: "hidden sm:inline min-w-0 truncate", children: [
4671
- "Open in ",
4672
- openInAppLabel
4673
- ] })
4674
- ]
4675
- }
4676
- ),
4677
- /* @__PURE__ */ jsx(
4678
- "button",
4679
- {
4680
- onClick: () => {
4681
- userPreferInlineRef.current = true;
4682
- setDisplayMode("inline");
4683
- if (ownsPipDisplayMode) {
4684
- onExitPip?.(pipWidgetId ?? displayWidgetId);
4685
- }
4686
- if (placedFullscreen) fullscreenPlacement?.onExit?.();
4687
- },
4688
- className: placedFullscreen && fullscreenPlacement?.exitLabel ? "rounded-lg px-2 py-1 text-sm font-medium text-foreground hover:bg-muted transition-colors" : "p-2 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors",
4689
- "aria-label": "Exit fullscreen",
4690
- children: placedFullscreen && fullscreenPlacement?.exitLabel ? fullscreenPlacement.exitLabel : /* @__PURE__ */ jsx(X, { className: "w-5 h-5" })
4691
- }
4692
- )
4693
- ] })
4694
- ] }),
4695
- !hostManagedPresentation && isPip && !isMobilePlaygroundMode && /* @__PURE__ */ jsx(
4696
- "button",
4697
- {
4698
- onClick: () => {
4699
- userPreferInlineRef.current = true;
4700
- setDisplayMode("inline");
4701
- onExitPip?.(pipWidgetId ?? displayWidgetId);
4702
- },
4703
- 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",
4704
- "aria-label": "Close PiP mode",
4705
- title: "Close PiP mode",
4706
- children: /* @__PURE__ */ jsx(X, { className: "w-4 h-4" })
4707
- }
4708
- ),
4709
- /* @__PURE__ */ jsx(
4710
- "div",
4711
- {
4712
- "data-testid": showHostChrome ? "mcp-app-host-chrome" : void 0,
4713
- className: showHostChrome ? "rounded-md" : "contents",
4714
- style: hostChromeStyle,
4715
- children: iframe
4716
- }
4717
- ),
4718
- showCspBlockedNotice && /* @__PURE__ */ jsxs(
4719
- "div",
4720
- {
4721
- "data-testid": "mcp-app-csp-blocked-notice",
4722
- role: "status",
4723
- className: "border border-destructive/40 bg-destructive/10 text-destructive text-xs rounded-md px-3 py-2",
4724
- children: [
4725
- /* @__PURE__ */ jsx("span", { children: minimalMode ? "This app couldn't load its resources." : `MCP App blocked by Content Security Policy${firstCspBlock?.directive ? ` (${firstCspBlock.directive})` : ""}.` }),
4726
- firstCspBlock?.blockedUri ? /* @__PURE__ */ jsx("span", { className: "mt-0.5 block font-mono break-all opacity-80", children: firstCspBlock.blockedUri }) : null
4727
- ]
4728
- }
4729
- ),
4730
- pendingAppToolCalls > 0 && !isFullscreen && /* @__PURE__ */ jsx(
4731
- "div",
4732
- {
4733
- 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",
4734
- "aria-label": "App tool call in progress",
4735
- title: "App tool call in progress",
4736
- "data-testid": "mcp-app-busy-indicator",
4737
- children: /* @__PURE__ */ jsx(Loader2, { className: "w-3.5 h-3.5 animate-spin" })
4738
- }
4739
- ),
4740
- /* @__PURE__ */ jsx(
4741
- McpAppsModal,
4742
- {
4743
- open: modalOpen,
4744
- onOpenChange: setModalOpen,
4745
- title: modalTitle,
4746
- template: modalTemplate,
4747
- params: modalParams,
4748
- registerBridgeHandlers,
4749
- refreshAppProvidedTools,
4750
- widgetCsp: effectiveSandbox.csp,
4751
- widgetPermissions: effectiveSandbox.permissions,
4752
- widgetPermissive: effectiveSandbox.permissive,
4753
- widgetSandboxAttrs: effectiveSandbox.sandboxAttrs,
4754
- widgetAllowFeatures: effectiveSandbox.allowFeatures,
4755
- widgetCspDirectives: effectiveSandbox.cspDirectives,
4756
- widgetCspSubtypePolicy: effectiveSandbox.cspSubtypePolicy,
4757
- widgetClientContext: cspClientContext,
4758
- widgetBrowserStorage: effectiveSandbox.browserStorage,
4759
- widgetMountMode: viewMountMode,
4760
- widgetToolResult: earlyEffectiveMcpAppsCapabilities.toolResult,
4761
- hostContextRef,
4762
- serverId,
4763
- resourceUri,
4764
- toolCallId,
4765
- toolName,
4766
- cspMode,
4767
- injectOpenAiCompat: effectiveInjectOpenAiCompat,
4768
- effectiveHostCapabilities,
4769
- hostInfo: resolvedBridgeHostInfo,
4770
- webManagedServers,
4771
- toolInputRef,
4772
- toolOutputRef,
4773
- themeModeRef,
4774
- addUiLog: (log) => logUiEvent({
4775
- ...log,
4776
- protocol: "mcp-apps"
4777
- }),
4778
- onCspViolation: handleCspViolation,
4779
- onCspApplied: handleCspApplied
4780
- }
4781
- ),
4782
- checkoutSession != null && Checkout && /* @__PURE__ */ jsx(
4783
- Checkout,
4784
- {
4785
- session: checkoutSession,
4786
- open: checkoutOpen,
4787
- onOpenChange: setCheckoutOpen,
4788
- onComplete: (result) => respondToCheckout(result),
4789
- onError: (error) => respondToCheckout(null, error),
4790
- onCancel: () => respondToCheckout(null, "User cancelled checkout"),
4791
- onCallTool: async (toolName2, params) => {
4792
- if (!onCallTool) {
4793
- throw new Error("Tool calls not supported");
5103
+ ),
5104
+ showCspBlockedNotice && /* @__PURE__ */ jsxs(
5105
+ "div",
5106
+ {
5107
+ "data-testid": "mcp-app-csp-blocked-notice",
5108
+ role: "status",
5109
+ className: "border border-destructive/40 bg-destructive/10 text-destructive text-xs rounded-md px-3 py-2",
5110
+ children: [
5111
+ /* @__PURE__ */ jsx("span", { children: minimalMode ? "This app couldn't load its resources." : `MCP App blocked by Content Security Policy${firstCspBlock?.directive ? ` (${firstCspBlock.directive})` : ""}.` }),
5112
+ firstCspBlock?.blockedUri ? /* @__PURE__ */ jsx("span", { className: "mt-0.5 block font-mono break-all opacity-80", children: firstCspBlock.blockedUri }) : null
5113
+ ]
5114
+ }
5115
+ ),
5116
+ pendingAppToolCalls > 0 && !isFullscreen && /* @__PURE__ */ jsx(
5117
+ "div",
5118
+ {
5119
+ 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",
5120
+ "aria-label": "App tool call in progress",
5121
+ title: "App tool call in progress",
5122
+ "data-testid": "mcp-app-busy-indicator",
5123
+ children: /* @__PURE__ */ jsx(Loader2, { className: "w-3.5 h-3.5 animate-spin" })
5124
+ }
5125
+ ),
5126
+ /* @__PURE__ */ jsx(
5127
+ McpAppsModal,
5128
+ {
5129
+ open: modalOpen,
5130
+ onOpenChange: setModalOpen,
5131
+ title: modalTitle,
5132
+ template: modalTemplate,
5133
+ params: modalParams,
5134
+ registerBridgeHandlers,
5135
+ refreshAppProvidedTools,
5136
+ widgetCsp: effectiveSandbox.csp,
5137
+ widgetPermissions: effectiveSandbox.permissions,
5138
+ widgetPermissive: effectiveSandbox.permissive,
5139
+ widgetSandboxAttrs: effectiveSandbox.sandboxAttrs,
5140
+ widgetAllowFeatures: effectiveSandbox.allowFeatures,
5141
+ widgetCspDirectives: effectiveSandbox.cspDirectives,
5142
+ widgetCspSubtypePolicy: effectiveSandbox.cspSubtypePolicy,
5143
+ widgetClientContext: cspClientContext,
5144
+ widgetBrowserStorage: effectiveSandbox.browserStorage,
5145
+ widgetMountMode: viewMountMode,
5146
+ widgetToolResult: earlyEffectiveMcpAppsCapabilities.toolResult,
5147
+ hostContextRef,
5148
+ serverId,
5149
+ resourceUri,
5150
+ toolCallId,
5151
+ toolName,
5152
+ cspMode,
5153
+ injectOpenAiCompat: effectiveInjectOpenAiCompat,
5154
+ effectiveHostCapabilities,
5155
+ hostInfo: resolvedBridgeHostInfo,
5156
+ webManagedServers,
5157
+ toolInputRef,
5158
+ toolOutputRef,
5159
+ themeModeRef,
5160
+ addUiLog: (log) => logUiEvent({
5161
+ ...log,
5162
+ protocol: "mcp-apps"
5163
+ }),
5164
+ onCspViolation: handleCspViolation,
5165
+ onCspApplied: handleCspApplied
5166
+ }
5167
+ ),
5168
+ checkoutSession != null && Checkout && /* @__PURE__ */ jsx(
5169
+ Checkout,
5170
+ {
5171
+ session: checkoutSession,
5172
+ open: checkoutOpen,
5173
+ onOpenChange: setCheckoutOpen,
5174
+ onComplete: (result) => respondToCheckout(result),
5175
+ onError: (error) => respondToCheckout(null, error),
5176
+ onCancel: () => respondToCheckout(null, "User cancelled checkout"),
5177
+ onCallTool: async (toolName2, params) => {
5178
+ if (!onCallTool) {
5179
+ throw new Error("Tool calls not supported");
5180
+ }
5181
+ return onCallTool(toolName2, params);
4794
5182
  }
4795
- return onCallTool(toolName2, params);
4796
5183
  }
4797
- }
4798
- )
4799
- ]
4800
- }
4801
- );
5184
+ )
5185
+ ]
5186
+ }
5187
+ )
5188
+ ] });
4802
5189
  }
4803
5190
  function createSurfaceContainer(surfaceId) {
4804
5191
  const container = document.createElement("div");
@@ -4893,13 +5280,17 @@ function WidgetSurfaceHost({
4893
5280
  }
4894
5281
  function WidgetWorkspaceProvider({
4895
5282
  workspaceId,
4896
- children
5283
+ children,
5284
+ inheritAppTools = false
4897
5285
  }) {
5286
+ const parentRegistry = useAppToolsRegistryApi();
5287
+ const parentInvocations = useAppToolInvocationLogApi();
4898
5288
  const [value] = useState(() => ({
4899
5289
  workspaceId,
4900
5290
  surfaces: createWidgetSurfaceStore({ retainInstances: true }),
4901
- registry: createAppToolsRegistry({ maxInstances: 64 }),
4902
- invocations: createAppToolInvocationLog()
5291
+ ownsAppTools: !inheritAppTools,
5292
+ registry: inheritAppTools ? parentRegistry : createAppToolsRegistry({ maxInstances: 64 }),
5293
+ invocations: inheritAppTools ? parentInvocations : createAppToolInvocationLog()
4903
5294
  }));
4904
5295
  if (value.workspaceId !== workspaceId)
4905
5296
  throw new Error(
@@ -4909,16 +5300,26 @@ function WidgetWorkspaceProvider({
4909
5300
  useEffect(() => {
4910
5301
  if (cleanupTimer.current !== null) clearTimeout(cleanupTimer.current);
4911
5302
  cleanupTimer.current = null;
4912
- value.registry.getState().setEnabled(true);
4913
- value.invocations.getState().setEnabled(true);
5303
+ if (value.ownsAppTools) {
5304
+ value.registry.getState().setEnabled(true);
5305
+ value.invocations.getState().setEnabled(true);
5306
+ }
4914
5307
  value.surfaces.getState().setEnabled(true);
4915
5308
  return () => {
4916
- value.registry.getState().setEnabled(false);
4917
- value.invocations.getState().setEnabled(false);
5309
+ if (value.ownsAppTools) {
5310
+ value.registry.getState().setEnabled(false);
5311
+ value.invocations.getState().setEnabled(false);
5312
+ }
4918
5313
  value.surfaces.getState().setEnabled(false);
4919
5314
  cleanupTimer.current = setTimeout(() => {
4920
- value.registry.getState().dispose();
4921
- value.invocations.getState().dispose();
5315
+ if (value.ownsAppTools) {
5316
+ value.registry.getState().dispose();
5317
+ value.invocations.getState().dispose();
5318
+ } else {
5319
+ for (const instance of value.registry.getState().instancesByBridgeId.values())
5320
+ if (instance.chatSessionId === value.workspaceId)
5321
+ value.registry.getState().unregisterInstance(instance.bridgeId);
5322
+ }
4922
5323
  value.surfaces.getState().dispose();
4923
5324
  }, 0);
4924
5325
  };
@@ -4983,6 +5384,6 @@ function WidgetWorkspaceSurfaceHost({
4983
5384
  ] });
4984
5385
  }
4985
5386
 
4986
- export { MAX_SNAPSHOT_ENTRIES, MCPAppsRenderer, MCPAppsRendererSurface, PARTIAL_INPUT_THROTTLE_MS, SIGNATURE_MAX_ARRAY_ITEMS, SIGNATURE_MAX_DEPTH, SIGNATURE_MAX_OBJECT_KEYS, SIGNATURE_STRING_EDGE_LENGTH, STREAMING_REVEAL_FALLBACK_MS, SandboxedIframe, UIType, WidgetFullscreenPlacementContext, WidgetHostProvider, WidgetSurfaceHost, WidgetSurfaceHostProvider, WidgetWorkspaceProvider, WidgetWorkspaceSurfaceHost, __internal, closeWorkspaceSurface, createAppToolInvocationLog, createAppToolsRegistry, createWidgetSurfaceStore, detectUIType, detectUiTypeFromTool, dispatchAppToolCall, getRenderableSurfaceEntries, getToolInputSignature, getUIResourceUri, listAppToolCatalog, readToolResultMeta, readToolResultObject, readToolResultServerId, recordAppToolInvocation, resolveSandboxProxyUrl, useAppToolAttribution, useAppToolAttributionResolver, useAppToolInvocationLog, useAppToolInvocationLogApi, useAppToolsRegistry, useAppToolsRegistryApi, useOptionalWidgetWorkspace, usePersistentWidgetSurfaceHost, useToolInputStreaming, useWidgetHost, useWidgetSurfaceAdmissionError, useWidgetSurfaceStore, useWidgetSurfaceStoreApi, useWidgetWorkspace };
5387
+ export { MAX_SNAPSHOT_ENTRIES, MCPAppsRenderer, MCPAppsRendererSurface, PARTIAL_INPUT_THROTTLE_MS, SIGNATURE_MAX_ARRAY_ITEMS, SIGNATURE_MAX_DEPTH, SIGNATURE_MAX_OBJECT_KEYS, SIGNATURE_STRING_EDGE_LENGTH, STREAMING_REVEAL_FALLBACK_MS, SandboxViewAdmissionError, SandboxedIframe, UIType, WidgetFullscreenPlacementContext, WidgetHostProvider, WidgetSurfaceHost, WidgetSurfaceHostProvider, WidgetWorkspaceProvider, WidgetWorkspaceSurfaceHost, __internal, closeWorkspaceSurface, createAppToolInvocationLog, createAppToolsRegistry, createWidgetSurfaceStore, detectUIType, detectUiTypeFromTool, dispatchAppToolCall, getRenderableSurfaceEntries, getToolInputSignature, getUIResourceUri, listAppToolCatalog, modelChatSessionId, readToolResultMeta, readToolResultObject, readToolResultServerId, recordAppToolInvocation, resolveSandboxProxyUrl, useAppToolAttribution, useAppToolAttributionResolver, useAppToolInvocationLog, useAppToolInvocationLogApi, useAppToolsRegistry, useAppToolsRegistryApi, useOptionalWidgetWorkspace, usePersistentWidgetSurfaceHost, useToolInputStreaming, useWidgetHost, useWidgetSurfaceAdmissionError, useWidgetSurfaceStore, useWidgetSurfaceStoreApi, useWidgetWorkspace };
4987
5388
  //# sourceMappingURL=index.js.map
4988
5389
  //# sourceMappingURL=index.js.map