@mcpjam/widget-react 0.2.1 → 0.3.0

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
@@ -1,7 +1,7 @@
1
1
  import { createContext, forwardRef, useRef, useState, useMemo, useImperativeHandle, useCallback, useEffect, useContext, useLayoutEffect, Fragment as Fragment$1 } from 'react';
2
2
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
3
3
  import { isUIResource } from '@mcp-ui/client';
4
- import { buildOuterAllowAttribute, buildOuterSandboxAttribute, stableStringifyJson, resolveToolUiResourceUri, callViewWebmcpTool, applyToolResultPolicy, openAIDisplayModes, negotiateResourceDisplayModes, registerHostBridgeHandlers, pickOpenAIDisplayMode, createHostAppBridge, LoggingTransport, extractMethod, appToolSourceFor, discoverViewAppTools, listViewWebmcpTools } from '@mcpjam/sdk/widget-runtime';
4
+ import { buildOuterAllowAttribute, buildOuterSandboxAttribute, stableStringifyJson, resolveToolUiResourceUri, callViewWebmcpTool, applyToolResultPolicy, openAIDisplayModes, inlineThenMoveModes, negotiateResourceDisplayModes, registerHostBridgeHandlers, pickOpenAIDisplayMode, createHostAppBridge, LoggingTransport, extractMethod, shouldMoveToPanel, inlineThenMoveStart, appToolSourceFor, discoverViewAppTools, listViewWebmcpTools } from '@mcpjam/sdk/widget-runtime';
5
5
  export { getToolVisibility, isVisibleToAppOnly, isVisibleToModelOnly } from '@mcpjam/sdk/widget-runtime';
6
6
  import { useStore, create } from 'zustand';
7
7
  import { useShallow } from 'zustand/react/shallow';
@@ -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,7 +1265,9 @@ 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(() => {
1270
+ if (!sandboxProxyUrl) return null;
1084
1271
  try {
1085
1272
  return new URL(sandboxProxyUrl).origin;
1086
1273
  } catch {
@@ -1091,14 +1278,15 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
1091
1278
  ref,
1092
1279
  () => ({
1093
1280
  postMessage: (data) => {
1094
- outerRef.current?.contentWindow?.postMessage(data, sandboxProxyOrigin);
1281
+ if (sandboxProxyOrigin) outerRef.current?.contentWindow?.postMessage(data, sandboxProxyOrigin);
1095
1282
  },
1096
1283
  getIframeElement: () => outerRef.current
1097
1284
  }),
1098
- [sandboxProxyOrigin]
1285
+ [sandboxProxyOrigin, sandboxProxyUrl]
1099
1286
  );
1100
1287
  const handleMessage = useCallback(
1101
1288
  (event) => {
1289
+ if (!sandboxProxyUrl) return;
1102
1290
  if (event.origin !== sandboxProxyOrigin && sandboxProxyOrigin !== "*") {
1103
1291
  return;
1104
1292
  }
@@ -1140,7 +1328,7 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
1140
1328
  }
1141
1329
  onMessageRef.current(event);
1142
1330
  },
1143
- [sandboxProxyOrigin]
1331
+ [sandboxProxyOrigin, sandboxProxyUrl]
1144
1332
  );
1145
1333
  useEffect(() => {
1146
1334
  window.addEventListener("message", handleMessage);
@@ -1195,7 +1383,7 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
1195
1383
  if (!proxyReady) lastResourceReadyKeyRef.current = null;
1196
1384
  }, [proxyReady]);
1197
1385
  useEffect(() => {
1198
- if (!proxyReady || !html) return;
1386
+ if (!proxyReady || !html || !sandboxProxyOrigin) return;
1199
1387
  const resourceTargetKey = `${sandboxProxyOrigin}\0${resourceReadyKey}`;
1200
1388
  if (lastResourceReadyKeyRef.current === resourceTargetKey) return;
1201
1389
  lastResourceReadyKeyRef.current = resourceTargetKey;
@@ -1239,7 +1427,7 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
1239
1427
  });
1240
1428
  }, [proxyReady, html, resourceReadyKey, sandboxProxyOrigin]);
1241
1429
  useEffect(() => {
1242
- if (!proxyReady || !colorScheme) return;
1430
+ if (!proxyReady || !colorScheme || !sandboxProxyOrigin) return;
1243
1431
  outerRef.current?.contentWindow?.postMessage(
1244
1432
  {
1245
1433
  jsonrpc: "2.0",
@@ -1252,24 +1440,49 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
1252
1440
  const iframeStyle = colorScheme ? { ...style, colorScheme } : style;
1253
1441
  useEffect(() => {
1254
1442
  setProxyReady(false);
1255
- }, [outerSandboxAttribute, sandboxProxyOrigin]);
1443
+ }, [outerSandboxAttribute, sandboxProxyUrl]);
1444
+ if (preparedView.error) return /* @__PURE__ */ jsx("div", { role: "alert", children: preparedView.error });
1256
1445
  return /* @__PURE__ */ jsx(
1257
1446
  "iframe",
1258
1447
  {
1259
1448
  ref: outerRef,
1260
- src: sandboxProxyUrl,
1449
+ src: sandboxProxyUrl ?? "about:blank",
1261
1450
  sandbox: outerSandboxAttribute,
1262
1451
  allow: outerAllowAttribute,
1263
1452
  title,
1264
1453
  className,
1265
1454
  style: iframeStyle
1266
1455
  },
1267
- `${sandboxProxyOrigin}\0${outerSandboxAttribute}`
1456
+ `${preparedView.required ? "admitted" : sandboxProxyOrigin}\0${outerSandboxAttribute}`
1268
1457
  );
1269
1458
  });
1459
+ var SANDBOX_READY_TIMEOUT_MS = 3e4;
1460
+ function useSandboxReadyDeadline({
1461
+ waiting,
1462
+ identity,
1463
+ onTimeout
1464
+ }) {
1465
+ const callback = useRef(onTimeout);
1466
+ callback.current = onTimeout;
1467
+ useEffect(() => {
1468
+ if (!waiting) return;
1469
+ const timer = window.setTimeout(
1470
+ () => callback.current(),
1471
+ SANDBOX_READY_TIMEOUT_MS
1472
+ );
1473
+ return () => window.clearTimeout(timer);
1474
+ }, [waiting, identity]);
1475
+ }
1270
1476
  function createAppToolDiscovery(config) {
1271
1477
  const states = /* @__PURE__ */ new WeakMap();
1272
1478
  return function refresh(bridge, bridgeId, options) {
1479
+ const readContext = () => {
1480
+ const context = config.context();
1481
+ return options.getIframeElement ? {
1482
+ ...context,
1483
+ presentation: appToolPresentation(context.presentation?.label, options.getIframeElement())
1484
+ } : context;
1485
+ };
1273
1486
  let state = states.get(bridge);
1274
1487
  if (!state) {
1275
1488
  state = {
@@ -1326,7 +1539,7 @@ function createAppToolDiscovery(config) {
1326
1539
  if (result.source === "webmcp" && result.tools.length === 0) {
1327
1540
  config.registry.getState().unregisterInstance(bridgeId);
1328
1541
  } else {
1329
- const context = config.context();
1542
+ const context = readContext();
1330
1543
  const version = bridge.getAppVersion();
1331
1544
  await config.registry.getState().registerInstance({
1332
1545
  ...context,
@@ -1342,6 +1555,7 @@ function createAppToolDiscovery(config) {
1342
1555
  });
1343
1556
  if (!options.isLive())
1344
1557
  config.registry.getState().unregisterInstance(bridgeId);
1558
+ else config.registry.getState().updatePresentation(bridgeId, readContext().presentation ?? {});
1345
1559
  }
1346
1560
  } while (current.dirty && options.isLive());
1347
1561
  } catch (error) {
@@ -1357,6 +1571,87 @@ function createAppToolDiscovery(config) {
1357
1571
  return current.pending;
1358
1572
  };
1359
1573
  }
1574
+ function useFullscreenDismissal(args) {
1575
+ const current = useRef(args);
1576
+ useLayoutEffect(() => {
1577
+ current.current = args;
1578
+ });
1579
+ const [dismissed, setDismissed] = useState(false);
1580
+ const [pendingCount, setPendingCount] = useState(0);
1581
+ const pending = useRef(/* @__PURE__ */ new Set());
1582
+ const collapsed = args.enabled && args.fullscreen && (dismissed || !args.canInline && args.unowned);
1583
+ const conceal = useCallback(() => {
1584
+ const value = current.current;
1585
+ if (!value.enabled || !value.fullscreen) return;
1586
+ setDismissed(true);
1587
+ value.exit();
1588
+ }, []);
1589
+ const dismiss = useCallback(() => {
1590
+ const value = current.current;
1591
+ if (!value.enabled || !value.fullscreen) return;
1592
+ if (value.canInline) value.inline();
1593
+ else conceal();
1594
+ }, [conceal]);
1595
+ const open = useCallback(() => {
1596
+ if (pending.current.size || current.current.hostInputPending) return;
1597
+ setDismissed(false);
1598
+ current.current.open();
1599
+ }, []);
1600
+ useEffect(() => {
1601
+ if (!args.fullscreen || !args.enabled) setDismissed(false);
1602
+ }, [args.fullscreen, args.enabled]);
1603
+ useLayoutEffect(() => {
1604
+ if (args.hostInputPending || pendingCount > 0) conceal();
1605
+ }, [
1606
+ args.hostInputPending,
1607
+ args.fullscreen,
1608
+ args.enabled,
1609
+ pendingCount,
1610
+ conceal
1611
+ ]);
1612
+ useEffect(() => {
1613
+ if (!args.enabled || !args.fullscreen || collapsed) return;
1614
+ const keydown = (event) => {
1615
+ const element = current.current.element();
1616
+ if (event.key !== "Escape" || event.defaultPrevented || pending.current.size || current.current.hostInputPending || !element?.contains(document.activeElement))
1617
+ return;
1618
+ event.preventDefault();
1619
+ dismiss();
1620
+ };
1621
+ window.addEventListener("keydown", keydown);
1622
+ return () => window.removeEventListener("keydown", keydown);
1623
+ }, [args.enabled, args.fullscreen, collapsed, dismiss]);
1624
+ const trackInput = useCallback(
1625
+ (report) => {
1626
+ const id = Symbol();
1627
+ let finished = false;
1628
+ const update = (waiting) => {
1629
+ if (finished) return;
1630
+ if (waiting) {
1631
+ pending.current.add(id);
1632
+ conceal();
1633
+ } else pending.current.delete(id);
1634
+ setPendingCount(pending.current.size);
1635
+ report?.(waiting);
1636
+ };
1637
+ return {
1638
+ update,
1639
+ finish: () => {
1640
+ if (pending.current.has(id)) update(false);
1641
+ finished = true;
1642
+ }
1643
+ };
1644
+ },
1645
+ [conceal]
1646
+ );
1647
+ return {
1648
+ collapsed,
1649
+ dismiss,
1650
+ open,
1651
+ trackInput,
1652
+ pending: pendingCount > 0 || args.hostInputPending
1653
+ };
1654
+ }
1360
1655
  function useInitialRenderOutcome(ready, failed, notify) {
1361
1656
  const delivered = useRef(false);
1362
1657
  const callback = useRef(notify);
@@ -1392,6 +1687,51 @@ function useSandboxProxyGeneration({
1392
1687
  return { generation, onReady };
1393
1688
  }
1394
1689
  var WidgetFullscreenPlacementContext = createContext(null);
1690
+ var SETTLED_TOOL_STATES = /* @__PURE__ */ new Set([
1691
+ "output-available",
1692
+ "output-error",
1693
+ "output-denied"
1694
+ ]);
1695
+ function isErrorResult(output) {
1696
+ return typeof output === "object" && output !== null && "isError" in output && output.isError === true;
1697
+ }
1698
+ function useInlineThenMove(args) {
1699
+ const latest = useRef(args);
1700
+ useLayoutEffect(() => {
1701
+ latest.current = args;
1702
+ });
1703
+ const on = args.behavior?.start === "inline-then-move";
1704
+ const attempt = on && args.ready && SETTLED_TOOL_STATES.has(args.toolState ?? "");
1705
+ const tried = useRef(false);
1706
+ useEffect(() => {
1707
+ if (!attempt || tried.current) return;
1708
+ tried.current = true;
1709
+ const now = latest.current;
1710
+ const toolResultOk = now.toolState === "output-available" && !isErrorResult(now.toolOutput);
1711
+ if (!now.fullscreen && !now.preferInline() && shouldMoveToPanel({
1712
+ modes: now.modes,
1713
+ preferred: now.preferred,
1714
+ toolResultOk,
1715
+ panelAvailable: now.panelAvailable
1716
+ }))
1717
+ now.moveToPanel();
1718
+ }, [attempt]);
1719
+ const startMode = useCallback(
1720
+ (negotiated) => {
1721
+ const now = latest.current;
1722
+ if (now.behavior?.start !== "inline-then-move") return void 0;
1723
+ const start = inlineThenMoveStart(negotiated);
1724
+ return start === "fullscreen" && !now.panelAvailable ? void 0 : start;
1725
+ },
1726
+ []
1727
+ );
1728
+ const showPanel = useCallback(() => latest.current.revealPanel?.(), []);
1729
+ return {
1730
+ startMode,
1731
+ panelCard: on && args.placed && !args.modes.includes("inline"),
1732
+ showPanel
1733
+ };
1734
+ }
1395
1735
  function McpAppsModal({
1396
1736
  open,
1397
1737
  onOpenChange,
@@ -1432,6 +1772,8 @@ function McpAppsModal({
1432
1772
  const appToolsRegistry = useAppToolsRegistryApi();
1433
1773
  const Modal = host.components?.Modal;
1434
1774
  const [modalHtml, setModalHtml] = useState(null);
1775
+ const [sourceReceipt, setSourceReceipt] = useState();
1776
+ const [sandboxSource, setSandboxSource] = useState({ serverId, resourceUri, toolCallId });
1435
1777
  const modalSandboxRef = useRef(null);
1436
1778
  const modalBridgeRef = useRef(null);
1437
1779
  const modalAppToolsBridgeIdRef = useRef(null);
@@ -1446,11 +1788,13 @@ function McpAppsModal({
1446
1788
  modalAppToolsBridgeIdRef.current = null;
1447
1789
  }
1448
1790
  setModalHtml(null);
1791
+ setSourceReceipt(void 0);
1449
1792
  return;
1450
1793
  }
1794
+ let active = true;
1451
1795
  const fetchModalHtml = async () => {
1452
1796
  try {
1453
- const { html } = await host.services.fetchWidgetContent({
1797
+ const { html, sourceReceipt: receipt } = await host.services.fetchWidgetContent({
1454
1798
  serverId,
1455
1799
  forceWebEndpoint: webManagedServers,
1456
1800
  resourceUri,
@@ -1465,12 +1809,18 @@ function McpAppsModal({
1465
1809
  viewMode: "modal",
1466
1810
  viewParams: params
1467
1811
  });
1812
+ if (!active) return;
1468
1813
  setModalHtml(html);
1814
+ setSourceReceipt(receipt);
1815
+ setSandboxSource({ serverId, resourceUri, toolCallId });
1469
1816
  } catch (err) {
1470
1817
  console.error("[MCP Apps] Failed to fetch modal HTML", err);
1471
1818
  }
1472
1819
  };
1473
1820
  fetchModalHtml();
1821
+ return () => {
1822
+ active = false;
1823
+ };
1474
1824
  }, [
1475
1825
  appToolsRegistry,
1476
1826
  open,
@@ -1652,6 +2002,21 @@ function McpAppsModal({
1652
2002
  {
1653
2003
  ref: modalSandboxRef,
1654
2004
  html: modalHtml,
2005
+ viewAdmission: host.services.prepareSandboxView ? {
2006
+ services: host.services,
2007
+ request: {
2008
+ source: sandboxSource,
2009
+ sourceReceipt,
2010
+ html: modalHtml,
2011
+ policy: {
2012
+ csp: widgetCsp,
2013
+ cspDirectives: widgetCspDirectives,
2014
+ cspSubtypePolicy: widgetCspSubtypePolicy,
2015
+ permissive: widgetPermissive
2016
+ },
2017
+ mode: widgetPermissive || Object.keys(widgetCspDirectives ?? {}).length > 0 ? "debugger" : "declared"
2018
+ }
2019
+ } : void 0,
1655
2020
  sandbox: "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",
1656
2021
  csp: widgetCsp,
1657
2022
  permissions: widgetPermissions,
@@ -2306,7 +2671,10 @@ function MCPAppsRenderer(props) {
2306
2671
  return /* @__PURE__ */ jsx(PersistentMCPAppsRendererRegistration, { ...props });
2307
2672
  }
2308
2673
  function MCPAppsRendererSurface({
2674
+ appToolSourceLabel,
2675
+ hostInputPending = false,
2309
2676
  chatSessionId,
2677
+ getModelChatSessionId,
2310
2678
  serverId,
2311
2679
  serverName,
2312
2680
  toolCallId,
@@ -2489,7 +2857,10 @@ function MCPAppsRendererSurface({
2489
2857
  const fixedDisplayMode = host.surface.fixedDisplayMode;
2490
2858
  const fixedDisplayModeRef = useRef(fixedDisplayMode);
2491
2859
  fixedDisplayModeRef.current = fixedDisplayMode;
2492
- const openAIRules = host.surface.openAIDisplayModes === true;
2860
+ const displayBehavior = host.surface.displayBehavior;
2861
+ const displayBehaviorRef = useRef(displayBehavior);
2862
+ displayBehaviorRef.current = displayBehavior;
2863
+ const openAIRules = displayBehavior?.start === "hint-first";
2493
2864
  const openAIRulesRef = useRef(openAIRules);
2494
2865
  openAIRulesRef.current = openAIRules;
2495
2866
  const displayModesFor = useCallback(
@@ -2497,6 +2868,8 @@ function MCPAppsRendererSurface({
2497
2868
  const fixed = fixedDisplayModeRef.current;
2498
2869
  if (openAIRulesRef.current)
2499
2870
  return openAIDisplayModes(hostModes, hints, appModes, fixed);
2871
+ if (displayBehaviorRef.current?.start === "inline-then-move" && !fixed)
2872
+ return inlineThenMoveModes(hostModes, appModes);
2500
2873
  return fixed && hostModes.includes(fixed) ? [fixed] : negotiateResourceDisplayModes([...hostModes], hints, appModes);
2501
2874
  },
2502
2875
  []
@@ -2517,6 +2890,9 @@ function MCPAppsRendererSurface({
2517
2890
  ]
2518
2891
  );
2519
2892
  const advertisedAvailableDisplayModes = effectiveAvailableDisplayModes;
2893
+ useEffect(() => {
2894
+ onAppSupportedDisplayModesChange?.(effectiveAvailableDisplayModes);
2895
+ }, [effectiveAvailableDisplayModes, onAppSupportedDisplayModesChange]);
2520
2896
  const playgroundCapabilities = environment.playgroundCapabilities;
2521
2897
  const configuredCapabilities = draftHostContext?.deviceCapabilities && typeof draftHostContext.deviceCapabilities === "object" && !Array.isArray(draftHostContext.deviceCapabilities) ? draftHostContext.deviceCapabilities : void 0;
2522
2898
  const deviceCapabilities = useMemo(() => {
@@ -2616,16 +2992,31 @@ function MCPAppsRendererSurface({
2616
2992
  displayMode
2617
2993
  ]
2618
2994
  );
2995
+ const fullscreenContainerRef = useRef(null);
2996
+ const fullscreenDismissal = useFullscreenDismissal({
2997
+ fullscreen: effectiveDisplayMode === "fullscreen",
2998
+ enabled: !hostManagedPresentation,
2999
+ canInline: effectiveAvailableDisplayModes.includes("inline"),
3000
+ unowned: fixedDisplayMode === void 0 && isControlled && !!onRequestFullscreen && !ownsFullscreenDisplayMode,
3001
+ hostInputPending,
3002
+ element: () => fullscreenContainerRef.current,
3003
+ inline: () => {
3004
+ userPreferInlineRef.current = true;
3005
+ setDisplayMode("inline");
3006
+ },
3007
+ exit: () => onExitFullscreen?.(displayWidgetId),
3008
+ open: () => setDisplayMode("fullscreen")
3009
+ });
2619
3010
  const lastForcedDisplayModeRef = useRef(null);
2620
3011
  const fullscreenPlacement = useContext(WidgetFullscreenPlacementContext);
2621
- const placedFullscreen = !hostManagedPresentation && effectiveDisplayMode === "fullscreen" && !(isPlaygroundActive && (playgroundDeviceType === "mobile" || playgroundDeviceType === "tablet")) && !!fullscreenPlacement?.rect;
3012
+ const panelAvailable = !hostManagedPresentation && !(isPlaygroundActive && (playgroundDeviceType === "mobile" || playgroundDeviceType === "tablet")) && !!fullscreenPlacement;
3013
+ const placedFullscreen = panelAvailable && effectiveDisplayMode === "fullscreen" && !fullscreenDismissal.collapsed && !!fullscreenPlacement?.rect;
2622
3014
  const fullscreenPlacementRef = useRef(fullscreenPlacement);
2623
3015
  fullscreenPlacementRef.current = fullscreenPlacement;
2624
3016
  const placedExitRef = useRef(() => {
2625
3017
  });
2626
3018
  placedExitRef.current = () => {
2627
- userPreferInlineRef.current = true;
2628
- setDisplayMode("inline");
3019
+ fullscreenDismissal.dismiss();
2629
3020
  };
2630
3021
  const fullscreenLabel = serverName?.trim() || serverId.trim() || "App";
2631
3022
  useEffect(() => {
@@ -2637,6 +3028,7 @@ function MCPAppsRendererSurface({
2637
3028
  return () => fullscreenPlacementRef.current?.onLeave?.();
2638
3029
  }, [placedFullscreen, fullscreenLabel]);
2639
3030
  useEffect(() => {
3031
+ if (fullscreenDismissal.collapsed) return;
2640
3032
  if (requestedDisplayMode === effectiveDisplayMode) {
2641
3033
  lastForcedDisplayModeRef.current = null;
2642
3034
  return;
@@ -2646,11 +3038,25 @@ function MCPAppsRendererSurface({
2646
3038
  }
2647
3039
  lastForcedDisplayModeRef.current = effectiveDisplayMode;
2648
3040
  setDisplayMode(effectiveDisplayMode);
2649
- }, [effectiveDisplayMode, requestedDisplayMode, setDisplayMode]);
3041
+ }, [effectiveDisplayMode, requestedDisplayMode, setDisplayMode, fullscreenDismissal.collapsed]);
2650
3042
  const [isReady, setIsReady] = useState(false);
2651
3043
  const [reinitCount, setReinitCount] = useState(0);
2652
3044
  const [loadError, setLoadError] = useState(null);
2653
3045
  useInitialRenderOutcome(isReady, loadError !== null, onInitialRenderOutcome);
3046
+ const inlineThenMove = useInlineThenMove({
3047
+ behavior: displayBehavior,
3048
+ ready: isReady,
3049
+ toolState,
3050
+ toolOutput,
3051
+ modes: effectiveAvailableDisplayModes,
3052
+ preferred: resourceDisplayHints?.preferredDisplayMode,
3053
+ panelAvailable,
3054
+ fullscreen: effectiveDisplayMode === "fullscreen",
3055
+ placed: placedFullscreen,
3056
+ preferInline: () => userPreferInlineRef.current,
3057
+ moveToPanel: () => setDisplayModeRef.current("fullscreen"),
3058
+ revealPanel: fullscreenPlacement?.reveal
3059
+ });
2654
3060
  const [firstCspBlock, setFirstCspBlock] = useState(null);
2655
3061
  const [widgetHtml, setWidgetHtml] = useState(null);
2656
3062
  const [openInAppUrlOverride, setOpenInAppUrlOverride] = useState(null);
@@ -2687,6 +3093,8 @@ function MCPAppsRendererSurface({
2687
3093
  const [widgetPermissive, setWidgetPermissive] = useState(
2688
3094
  isCachedReplay ? true : initialWidgetPermissive ?? false
2689
3095
  );
3096
+ const [sourceReceipt, setSourceReceipt] = useState();
3097
+ const [sandboxSource, setSandboxSource] = useState({ serverId, resourceUri, toolCallId });
2690
3098
  const [viewOriginLabel, setViewOriginLabel] = useState(
2691
3099
  void 0
2692
3100
  );
@@ -2740,6 +3148,7 @@ function MCPAppsRendererSurface({
2740
3148
  hasRenderedLiveRef.current = false;
2741
3149
  liveRenderIdentityRef.current = null;
2742
3150
  setWidgetHtml(null);
3151
+ setSourceReceipt(void 0);
2743
3152
  setResourceDisplayHints(void 0);
2744
3153
  setBridgeTransportReady(false);
2745
3154
  setLoadedCspMode(null);
@@ -2800,9 +3209,6 @@ function MCPAppsRendererSurface({
2800
3209
  const ownsPipDisplayModeRef = useRef(ownsPipDisplayMode);
2801
3210
  const toolsMetadataRef = useRef(toolsMetadata);
2802
3211
  const onModelContextUpdateRef = useRef(onModelContextUpdate);
2803
- const onAppSupportedDisplayModesChangeRef = useRef(
2804
- onAppSupportedDisplayModesChange
2805
- );
2806
3212
  const toolInputRef = useRef(toolInput);
2807
3213
  toolInputRef.current = toolInput;
2808
3214
  const toolOutputRef = useRef(toolOutput);
@@ -2876,6 +3282,7 @@ function MCPAppsRendererSurface({
2876
3282
  hasRenderedLiveRef.current = false;
2877
3283
  liveRenderIdentityRef.current = null;
2878
3284
  setWidgetHtml(html);
3285
+ setSourceReceipt(void 0);
2879
3286
  setWidgetCsp(void 0);
2880
3287
  setFirstCspBlock(null);
2881
3288
  setWidgetPermissions(void 0);
@@ -2905,6 +3312,7 @@ function MCPAppsRendererSurface({
2905
3312
  });
2906
3313
  };
2907
3314
  const loadFromLiveFetch = async () => {
3315
+ const fetchedSource = { serverId, resourceUri, toolCallId: toolCallIdRef.current };
2908
3316
  const {
2909
3317
  html,
2910
3318
  csp,
@@ -2913,9 +3321,11 @@ function MCPAppsRendererSurface({
2913
3321
  mimeTypeWarning: warning,
2914
3322
  mimeTypeValid: valid,
2915
3323
  prefersBorder: prefersBorder2,
2916
- resourceDisplayHints: resourceHints,
3324
+ resourceDisplayHints: openAIHints,
3325
+ uiDisplayHints,
2917
3326
  declaredDomain: serverDeclaredDomain,
2918
3327
  viewOriginLabel: serverViewOriginLabel,
3328
+ sourceReceipt: serverSourceReceipt,
2919
3329
  injectedOpenAiCompat: serverInjectedOpenAiCompat,
2920
3330
  injectedOpenAiCompatCapabilities: serverInjectedOpenAiCompatCapabilities
2921
3331
  } = await host.services.fetchWidgetContent({
@@ -2932,7 +3342,7 @@ function MCPAppsRendererSurface({
2932
3342
  // output for callers that don't pass it.
2933
3343
  toolResponseMetadata: toolResponseMetadata ?? readToolResultMeta(toolOutputRef.current) ?? null,
2934
3344
  initialWidgetState,
2935
- toolId: toolCallIdRef.current,
3345
+ toolId: fetchedSource.toolCallId,
2936
3346
  toolName,
2937
3347
  theme: themeModeRef.current,
2938
3348
  cspMode,
@@ -2961,6 +3371,7 @@ function MCPAppsRendererSurface({
2961
3371
  setBridgeTransportReady(false);
2962
3372
  hasRenderedLiveRef.current = true;
2963
3373
  liveRenderIdentityRef.current = liveRenderIdentityKey;
3374
+ const resourceHints = displayBehaviorRef.current?.hints === "ui" ? uiDisplayHints : openAIHints;
2964
3375
  const allowed = displayModesFor(
2965
3376
  hostAvailableDisplayModesRef.current,
2966
3377
  resourceHints
@@ -2970,11 +3381,13 @@ function MCPAppsRendererSurface({
2970
3381
  return false;
2971
3382
  }
2972
3383
  setResourceDisplayHints(resourceHints);
2973
- const initialMode = openAIRulesRef.current ? pickOpenAIDisplayMode(allowed, resourceHints) : resourceHints?.preferredDisplayMode;
3384
+ const initialMode = openAIRulesRef.current ? pickOpenAIDisplayMode(allowed, resourceHints) : displayBehaviorRef.current?.start === "inline-then-move" ? void 0 : resourceHints?.preferredDisplayMode;
2974
3385
  if (initialMode && allowed.includes(initialMode) && !(openAIRulesRef.current && initialMode === effectiveDisplayModeRef.current)) {
2975
3386
  setDisplayMode(initialMode);
2976
3387
  }
2977
3388
  setWidgetHtml(html);
3389
+ setSourceReceipt(serverSourceReceipt);
3390
+ setSandboxSource(fetchedSource);
2978
3391
  setWidgetCsp(csp);
2979
3392
  setFirstCspBlock(null);
2980
3393
  setWidgetPermissions(permissions);
@@ -3123,13 +3536,20 @@ function MCPAppsRendererSurface({
3123
3536
  },
3124
3537
  []
3125
3538
  );
3539
+ const modelChatAccessorRef = useRef(getModelChatSessionId);
3540
+ modelChatAccessorRef.current = getModelChatSessionId;
3541
+ const readModelChatSessionId = useCallback(
3542
+ () => modelChatAccessorRef.current ? modelChatAccessorRef.current() : chatSessionId,
3543
+ [chatSessionId]
3544
+ );
3545
+ const readAppToolPresentation = useAppToolPresentation(appToolsRegistry, appToolsBridgeIdState, appToolSourceLabel, () => sandboxRef.current?.getIframeElement() ?? null);
3126
3546
  const discoverAppTools = useMemo(() => createAppToolDiscovery({
3127
3547
  registry: appToolsRegistry,
3128
- context: () => ({ chatSessionId, parentToolCallId: toolCallIdRef.current, serverId: serverIdRef.current }),
3548
+ context: () => ({ chatSessionId, getModelChatSessionId: readModelChatSessionId, parentToolCallId: toolCallIdRef.current, serverId: serverIdRef.current, presentation: readAppToolPresentation() }),
3129
3549
  onError: (error) => logWidgetDebug("ui-to-host", "debug/app-tools-list-failed", {
3130
3550
  error: error instanceof Error ? error.message : String(error)
3131
3551
  })
3132
- }), [appToolsRegistry, chatSessionId, logWidgetDebug]);
3552
+ }), [appToolsRegistry, chatSessionId, readModelChatSessionId, logWidgetDebug, readAppToolPresentation]);
3133
3553
  const refreshAppProvidedTools = useCallback((bridge, bridgeId, options = {}) => discoverAppTools(bridge, bridgeId, {
3134
3554
  ...options,
3135
3555
  getIframeElement: options.getIframeElement ?? (() => sandboxRef.current?.getIframeElement() ?? null),
@@ -3695,7 +4115,6 @@ function MCPAppsRendererSurface({
3695
4115
  ownsPipDisplayModeRef.current = ownsPipDisplayMode;
3696
4116
  toolsMetadataRef.current = toolsMetadata;
3697
4117
  onModelContextUpdateRef.current = onModelContextUpdate;
3698
- onAppSupportedDisplayModesChangeRef.current = onAppSupportedDisplayModesChange;
3699
4118
  onRequestTeardownRef.current = onRequestTeardown;
3700
4119
  onConfirmDownloadRef.current = onConfirmDownload;
3701
4120
  }, [
@@ -3716,7 +4135,6 @@ function MCPAppsRendererSurface({
3716
4135
  ownsPipDisplayMode,
3717
4136
  toolsMetadata,
3718
4137
  onModelContextUpdate,
3719
- onAppSupportedDisplayModesChange,
3720
4138
  onRequestTeardown,
3721
4139
  onConfirmDownload
3722
4140
  ]);
@@ -3740,26 +4158,27 @@ function MCPAppsRendererSurface({
3740
4158
  wasReady
3741
4159
  });
3742
4160
  const declaredAppModes = appCaps?.availableDisplayModes;
3743
- onAppSupportedDisplayModesChangeRef.current?.(declaredAppModes);
3744
4161
  const negotiated = displayModesFor(
3745
4162
  hostAvailableDisplayModesRef.current,
3746
4163
  resourceDisplayHintsRef.current,
3747
4164
  declaredAppModes
3748
4165
  );
4166
+ setAppSupportedDisplayModes(declaredAppModes);
3749
4167
  if (negotiated.length === 0) {
3750
4168
  const fixed = fixedDisplayModeRef.current;
3751
4169
  setLoadError(
3752
4170
  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
4171
  );
4172
+ setIsReady(false);
4173
+ isReadyRef.current = false;
3754
4174
  void b.close();
3755
4175
  return;
3756
4176
  }
3757
- setAppSupportedDisplayModes(declaredAppModes);
3758
- if (openAIRulesRef.current && !negotiated.includes(effectiveDisplayModeRef.current)) {
3759
- const next = pickOpenAIDisplayMode(
4177
+ if (!negotiated.includes(effectiveDisplayModeRef.current)) {
4178
+ const next = openAIRulesRef.current ? pickOpenAIDisplayMode(
3760
4179
  negotiated,
3761
4180
  resourceDisplayHintsRef.current
3762
- );
4181
+ ) : inlineThenMove.startMode(negotiated);
3763
4182
  if (next) setDisplayModeRef.current(next);
3764
4183
  }
3765
4184
  if (wasReady) {
@@ -3790,14 +4209,20 @@ function MCPAppsRendererSurface({
3790
4209
  onOpenLink: (url) => {
3791
4210
  window.open(url, "_blank", "noopener,noreferrer");
3792
4211
  },
3793
- onCallTool: async (name, invocationInput) => {
4212
+ onCallTool: async (name, invocationInput, context) => {
3794
4213
  if (!onCallToolRef.current) {
3795
4214
  throw new Error("Tool calls not supported");
3796
4215
  }
3797
- return await onCallToolRef.current(
3798
- name,
3799
- invocationInput
3800
- );
4216
+ const input = fullscreenDismissal.trackInput(context?.onInputPending);
4217
+ try {
4218
+ return await onCallToolRef.current(
4219
+ name,
4220
+ invocationInput,
4221
+ context ? { ...context, onInputPending: input.update } : context
4222
+ );
4223
+ } finally {
4224
+ input.finish();
4225
+ }
3801
4226
  },
3802
4227
  onAppToolInvocation: (update) => {
3803
4228
  onAppToolInvocationChangeRef.current?.(update);
@@ -4040,6 +4465,17 @@ function MCPAppsRendererSurface({
4040
4465
  hasWidgetHtml,
4041
4466
  logReady: (details) => logWidgetDebug("ui-to-host", "debug/sandbox-proxy-ready", details)
4042
4467
  });
4468
+ useSandboxReadyDeadline({
4469
+ waiting: !!widgetHtml && sandboxProxyGeneration === 0 && !loadError,
4470
+ identity: toolCallId,
4471
+ onTimeout: () => {
4472
+ setLoadError("The app sandbox did not become ready. Reload this page to try again.");
4473
+ logWidgetDebug("host-to-ui", "debug/sandbox-proxy-timeout", {
4474
+ code: "SANDBOX_PROXY_TIMEOUT",
4475
+ timeoutMs: SANDBOX_READY_TIMEOUT_MS
4476
+ });
4477
+ }
4478
+ });
4043
4479
  useEffect(() => {
4044
4480
  if (!widgetHtml) return;
4045
4481
  if (sandboxProxyGeneration === 0) {
@@ -4587,6 +5023,21 @@ function MCPAppsRendererSurface({
4587
5023
  {
4588
5024
  ref: sandboxRef,
4589
5025
  html: bridgeTransportReady ? widgetHtml : null,
5026
+ viewAdmission: host.services.prepareSandboxView ? {
5027
+ services: host.services,
5028
+ request: {
5029
+ source: sandboxSource,
5030
+ sourceReceipt,
5031
+ html: widgetHtml ?? "",
5032
+ policy: {
5033
+ csp: effectiveSandbox.csp,
5034
+ cspDirectives: effectiveSandbox.cspDirectives,
5035
+ cspSubtypePolicy: effectiveSandbox.cspSubtypePolicy,
5036
+ permissive: effectiveSandbox.permissive
5037
+ },
5038
+ mode: effectiveSandbox.permissive || Object.keys(effectiveSandbox.cspDirectives ?? {}).length > 0 ? "debugger" : "declared"
5039
+ }
5040
+ } : void 0,
4590
5041
  reloadKey: bridgeGeneration,
4591
5042
  sandbox: "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",
4592
5043
  csp: effectiveSandbox.csp,
@@ -4612,193 +5063,205 @@ function MCPAppsRendererSurface({
4612
5063
  style: iframeStyle
4613
5064
  }
4614
5065
  );
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(
5066
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
5067
+ (fullscreenDismissal.collapsed || inlineThenMove.panelCard) && /* @__PURE__ */ jsx(
5068
+ "button",
5069
+ {
5070
+ className: "rounded-md border border-border px-3 py-2 text-sm text-foreground",
5071
+ disabled: fullscreenDismissal.pending,
5072
+ onClick: fullscreenDismissal.collapsed ? fullscreenDismissal.open : inlineThenMove.showPanel,
5073
+ children: fullscreenDismissal.pending ? "App is waiting for input" : "Open App"
5074
+ }
5075
+ ),
5076
+ /* @__PURE__ */ jsxs(
5077
+ "div",
5078
+ {
5079
+ ref: fullscreenContainerRef,
5080
+ hidden: fullscreenDismissal.collapsed,
5081
+ className: containerClassName,
5082
+ style: fullscreenDismissal.collapsed ? { display: "none" } : placedFullscreen && fullscreenPlacement?.rect ? {
5083
+ inset: "auto",
5084
+ top: fullscreenPlacement.rect.top,
5085
+ left: fullscreenPlacement.rect.left,
5086
+ width: fullscreenPlacement.rect.width,
5087
+ height: fullscreenPlacement.rect.height
5088
+ } : void 0,
5089
+ "data-mcp-app-fullscreen-placed": placedFullscreen || void 0,
5090
+ "data-mcp-app-persistent-initial-tool-call-id": persistentSurfaceInitialToolCallId,
5091
+ "data-mcp-app-persistent-surface-id": persistentSurfaceId,
5092
+ children: [
5093
+ !hostManagedPresentation && (isFullscreen && isContainedFullscreenMode || isPip && isMobilePlaygroundMode) && /* @__PURE__ */ jsxs(Fragment, { children: [
5094
+ /* @__PURE__ */ jsx(
5095
+ "button",
5096
+ {
5097
+ onClick: () => {
5098
+ if (isPip) {
5099
+ userPreferInlineRef.current = true;
5100
+ setDisplayMode("inline");
5101
+ onExitPip?.(pipWidgetId ?? displayWidgetId);
5102
+ } else fullscreenDismissal.dismiss();
5103
+ },
5104
+ 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",
5105
+ "aria-label": "Close",
5106
+ children: /* @__PURE__ */ jsx(X, { className: "w-5 h-5" })
5107
+ }
5108
+ ),
5109
+ showOpenInAppButton && /* @__PURE__ */ jsx(
5110
+ "button",
5111
+ {
5112
+ onClick: handleOpenInApp,
5113
+ 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",
5114
+ "aria-label": `Open in ${openInAppLabel}`,
5115
+ title: `Open in ${openInAppLabel}`,
5116
+ children: /* @__PURE__ */ jsx(ExternalLink, { className: "w-4 h-4" })
5117
+ }
5118
+ )
5119
+ ] }),
5120
+ !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: [
5121
+ !placedFullscreen && /* @__PURE__ */ jsx("div", {}),
5122
+ /* @__PURE__ */ jsx("div", { className: `font-medium text-sm text-muted-foreground min-w-0 truncate ${placedFullscreen ? "" : "max-w-[40vw]"}`, children: openInAppLabel }),
5123
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-2 min-w-0", children: [
5124
+ showOpenInAppButton && /* @__PURE__ */ jsxs(
5125
+ "button",
5126
+ {
5127
+ onClick: handleOpenInApp,
5128
+ 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",
5129
+ "aria-label": `Open in ${openInAppLabel}`,
5130
+ title: `Open in ${openInAppLabel}`,
5131
+ children: [
5132
+ /* @__PURE__ */ jsx(ExternalLink, { className: "w-3.5 h-3.5 shrink-0" }),
5133
+ /* @__PURE__ */ jsxs("span", { className: "hidden sm:inline min-w-0 truncate", children: [
5134
+ "Open in ",
5135
+ openInAppLabel
5136
+ ] })
5137
+ ]
5138
+ }
5139
+ ),
5140
+ /* @__PURE__ */ jsx(
5141
+ "button",
5142
+ {
5143
+ onClick: () => {
5144
+ fullscreenDismissal.dismiss();
5145
+ if (ownsPipDisplayMode) {
5146
+ onExitPip?.(pipWidgetId ?? displayWidgetId);
5147
+ }
5148
+ if (placedFullscreen) fullscreenPlacement?.onExit?.();
5149
+ },
5150
+ 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",
5151
+ "aria-label": "Exit fullscreen",
5152
+ children: placedFullscreen && fullscreenPlacement?.exitLabel ? fullscreenPlacement.exitLabel : /* @__PURE__ */ jsx(X, { className: "w-5 h-5" })
5153
+ }
5154
+ )
5155
+ ] })
5156
+ ] }),
5157
+ !hostManagedPresentation && isPip && !isMobilePlaygroundMode && /* @__PURE__ */ jsx(
4632
5158
  "button",
4633
5159
  {
4634
5160
  onClick: () => {
4635
5161
  userPreferInlineRef.current = true;
4636
5162
  setDisplayMode("inline");
4637
- if (isPip) {
4638
- onExitPip?.(pipWidgetId ?? displayWidgetId);
4639
- }
5163
+ onExitPip?.(pipWidgetId ?? displayWidgetId);
4640
5164
  },
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" })
5165
+ 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",
5166
+ "aria-label": "Close PiP mode",
5167
+ title: "Close PiP mode",
5168
+ children: /* @__PURE__ */ jsx(X, { className: "w-4 h-4" })
4644
5169
  }
4645
5170
  ),
4646
- showOpenInAppButton && /* @__PURE__ */ jsx(
4647
- "button",
5171
+ /* @__PURE__ */ jsx(
5172
+ "div",
4648
5173
  {
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" })
5174
+ "data-testid": showHostChrome ? "mcp-app-host-chrome" : void 0,
5175
+ className: showHostChrome ? "rounded-md" : "contents",
5176
+ style: hostChromeStyle,
5177
+ children: iframe
4654
5178
  }
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");
5179
+ ),
5180
+ showCspBlockedNotice && /* @__PURE__ */ jsxs(
5181
+ "div",
5182
+ {
5183
+ "data-testid": "mcp-app-csp-blocked-notice",
5184
+ role: "status",
5185
+ className: "border border-destructive/40 bg-destructive/10 text-destructive text-xs rounded-md px-3 py-2",
5186
+ children: [
5187
+ /* @__PURE__ */ jsx("span", { children: minimalMode ? "This app couldn't load its resources." : `MCP App blocked by Content Security Policy${firstCspBlock?.directive ? ` (${firstCspBlock.directive})` : ""}.` }),
5188
+ firstCspBlock?.blockedUri ? /* @__PURE__ */ jsx("span", { className: "mt-0.5 block font-mono break-all opacity-80", children: firstCspBlock.blockedUri }) : null
5189
+ ]
5190
+ }
5191
+ ),
5192
+ pendingAppToolCalls > 0 && !isFullscreen && /* @__PURE__ */ jsx(
5193
+ "div",
5194
+ {
5195
+ 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",
5196
+ "aria-label": "App tool call in progress",
5197
+ title: "App tool call in progress",
5198
+ "data-testid": "mcp-app-busy-indicator",
5199
+ children: /* @__PURE__ */ jsx(Loader2, { className: "w-3.5 h-3.5 animate-spin" })
5200
+ }
5201
+ ),
5202
+ /* @__PURE__ */ jsx(
5203
+ McpAppsModal,
5204
+ {
5205
+ open: modalOpen,
5206
+ onOpenChange: setModalOpen,
5207
+ title: modalTitle,
5208
+ template: modalTemplate,
5209
+ params: modalParams,
5210
+ registerBridgeHandlers,
5211
+ refreshAppProvidedTools,
5212
+ widgetCsp: effectiveSandbox.csp,
5213
+ widgetPermissions: effectiveSandbox.permissions,
5214
+ widgetPermissive: effectiveSandbox.permissive,
5215
+ widgetSandboxAttrs: effectiveSandbox.sandboxAttrs,
5216
+ widgetAllowFeatures: effectiveSandbox.allowFeatures,
5217
+ widgetCspDirectives: effectiveSandbox.cspDirectives,
5218
+ widgetCspSubtypePolicy: effectiveSandbox.cspSubtypePolicy,
5219
+ widgetClientContext: cspClientContext,
5220
+ widgetBrowserStorage: effectiveSandbox.browserStorage,
5221
+ widgetMountMode: viewMountMode,
5222
+ widgetToolResult: earlyEffectiveMcpAppsCapabilities.toolResult,
5223
+ hostContextRef,
5224
+ serverId,
5225
+ resourceUri,
5226
+ toolCallId,
5227
+ toolName,
5228
+ cspMode,
5229
+ injectOpenAiCompat: effectiveInjectOpenAiCompat,
5230
+ effectiveHostCapabilities,
5231
+ hostInfo: resolvedBridgeHostInfo,
5232
+ webManagedServers,
5233
+ toolInputRef,
5234
+ toolOutputRef,
5235
+ themeModeRef,
5236
+ addUiLog: (log) => logUiEvent({
5237
+ ...log,
5238
+ protocol: "mcp-apps"
5239
+ }),
5240
+ onCspViolation: handleCspViolation,
5241
+ onCspApplied: handleCspApplied
5242
+ }
5243
+ ),
5244
+ checkoutSession != null && Checkout && /* @__PURE__ */ jsx(
5245
+ Checkout,
5246
+ {
5247
+ session: checkoutSession,
5248
+ open: checkoutOpen,
5249
+ onOpenChange: setCheckoutOpen,
5250
+ onComplete: (result) => respondToCheckout(result),
5251
+ onError: (error) => respondToCheckout(null, error),
5252
+ onCancel: () => respondToCheckout(null, "User cancelled checkout"),
5253
+ onCallTool: async (toolName2, params) => {
5254
+ if (!onCallTool) {
5255
+ throw new Error("Tool calls not supported");
5256
+ }
5257
+ return onCallTool(toolName2, params);
4794
5258
  }
4795
- return onCallTool(toolName2, params);
4796
5259
  }
4797
- }
4798
- )
4799
- ]
4800
- }
4801
- );
5260
+ )
5261
+ ]
5262
+ }
5263
+ )
5264
+ ] });
4802
5265
  }
4803
5266
  function createSurfaceContainer(surfaceId) {
4804
5267
  const container = document.createElement("div");
@@ -4893,13 +5356,17 @@ function WidgetSurfaceHost({
4893
5356
  }
4894
5357
  function WidgetWorkspaceProvider({
4895
5358
  workspaceId,
4896
- children
5359
+ children,
5360
+ inheritAppTools = false
4897
5361
  }) {
5362
+ const parentRegistry = useAppToolsRegistryApi();
5363
+ const parentInvocations = useAppToolInvocationLogApi();
4898
5364
  const [value] = useState(() => ({
4899
5365
  workspaceId,
4900
5366
  surfaces: createWidgetSurfaceStore({ retainInstances: true }),
4901
- registry: createAppToolsRegistry({ maxInstances: 64 }),
4902
- invocations: createAppToolInvocationLog()
5367
+ ownsAppTools: !inheritAppTools,
5368
+ registry: inheritAppTools ? parentRegistry : createAppToolsRegistry({ maxInstances: 64 }),
5369
+ invocations: inheritAppTools ? parentInvocations : createAppToolInvocationLog()
4903
5370
  }));
4904
5371
  if (value.workspaceId !== workspaceId)
4905
5372
  throw new Error(
@@ -4909,16 +5376,26 @@ function WidgetWorkspaceProvider({
4909
5376
  useEffect(() => {
4910
5377
  if (cleanupTimer.current !== null) clearTimeout(cleanupTimer.current);
4911
5378
  cleanupTimer.current = null;
4912
- value.registry.getState().setEnabled(true);
4913
- value.invocations.getState().setEnabled(true);
5379
+ if (value.ownsAppTools) {
5380
+ value.registry.getState().setEnabled(true);
5381
+ value.invocations.getState().setEnabled(true);
5382
+ }
4914
5383
  value.surfaces.getState().setEnabled(true);
4915
5384
  return () => {
4916
- value.registry.getState().setEnabled(false);
4917
- value.invocations.getState().setEnabled(false);
5385
+ if (value.ownsAppTools) {
5386
+ value.registry.getState().setEnabled(false);
5387
+ value.invocations.getState().setEnabled(false);
5388
+ }
4918
5389
  value.surfaces.getState().setEnabled(false);
4919
5390
  cleanupTimer.current = setTimeout(() => {
4920
- value.registry.getState().dispose();
4921
- value.invocations.getState().dispose();
5391
+ if (value.ownsAppTools) {
5392
+ value.registry.getState().dispose();
5393
+ value.invocations.getState().dispose();
5394
+ } else {
5395
+ for (const instance of value.registry.getState().instancesByBridgeId.values())
5396
+ if (instance.chatSessionId === value.workspaceId)
5397
+ value.registry.getState().unregisterInstance(instance.bridgeId);
5398
+ }
4922
5399
  value.surfaces.getState().dispose();
4923
5400
  }, 0);
4924
5401
  };
@@ -4983,6 +5460,6 @@ function WidgetWorkspaceSurfaceHost({
4983
5460
  ] });
4984
5461
  }
4985
5462
 
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 };
5463
+ 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
5464
  //# sourceMappingURL=index.js.map
4988
5465
  //# sourceMappingURL=index.js.map