@mcpjam/widget-react 0.1.14 → 0.1.15

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,13 +1,13 @@
1
- import { createContext, forwardRef, useRef, useState, useMemo, useImperativeHandle, useCallback, useEffect, useContext, useLayoutEffect } from 'react';
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, applyToolResultPolicy, registerHostBridgeHandlers, LoggingTransport, extractMethod } from '@mcpjam/sdk/widget-runtime';
4
+ import { buildOuterAllowAttribute, buildOuterSandboxAttribute, stableStringifyJson, resolveToolUiResourceUri, applyToolResultPolicy, negotiateResourceDisplayModes, registerHostBridgeHandlers, createHostAppBridge, LoggingTransport, extractMethod } from '@mcpjam/sdk/widget-runtime';
5
5
  export { getToolVisibility, isVisibleToAppOnly, isVisibleToModelOnly } from '@mcpjam/sdk/widget-runtime';
6
- import { create } from 'zustand';
6
+ import { useStore, create } from 'zustand';
7
7
  import { useShallow } from 'zustand/react/shallow';
8
8
  import { X, ExternalLink, Loader2 } from 'lucide-react';
9
9
  import { resolveSandboxPermissions, resolveSandboxCsp } from '@mcpjam/sdk/browser';
10
- import { AppBridge, PostMessageTransport } from '@modelcontextprotocol/ext-apps/app-bridge';
10
+ import { PostMessageTransport, AppBridge } from '@modelcontextprotocol/ext-apps/app-bridge';
11
11
  import { createPortal } from 'react-dom';
12
12
 
13
13
  // src/widget-host-context.tsx
@@ -27,6 +27,9 @@ function useWidgetHost() {
27
27
  }
28
28
  return host;
29
29
  }
30
+ function useOptionalWidgetHost() {
31
+ return useContext(WidgetHostContext);
32
+ }
30
33
  var UIType = /* @__PURE__ */ ((UIType2) => {
31
34
  UIType2["MCP_APPS"] = "mcp-apps";
32
35
  UIType2["OPENAI_SDK"] = "openai-sdk";
@@ -104,6 +107,7 @@ function readToolResultServerId(result) {
104
107
  const meta = readToolResultMeta(result);
105
108
  return typeof meta?._serverId === "string" ? meta._serverId : void 0;
106
109
  }
110
+ var WidgetWorkspaceContext = createContext(null);
107
111
  var MAX_SNAPSHOT_ENTRIES = 64;
108
112
  var MAX_DESCRIPTION_CHARS = 512;
109
113
  var MAX_INPUT_SCHEMA_BYTES = 8 * 1024;
@@ -124,33 +128,38 @@ function getActiveParentKey(parentToolCallId, chatSessionId) {
124
128
  function isSameAppSlot(a, b) {
125
129
  return a.parentToolCallId === b.parentToolCallId && a.surface === b.surface && a.chatSessionId === b.chatSessionId;
126
130
  }
127
- var useAppToolsRegistry = create(
128
- (set, get) => ({
129
- instancesByBridgeId: /* @__PURE__ */ new Map(),
130
- aliases: /* @__PURE__ */ new Map(),
131
- activeBridgeByParent: /* @__PURE__ */ new Map(),
132
- pendingControllers: /* @__PURE__ */ new Map(),
133
- // Returns a Promise so callers (and tests) can await the alias-hash
134
- // round-trip. The renderer uses `void registerInstance(...)` because
135
- // there's nothing to do until the next chat POST. Tests await so
136
- // resolved microtasks don't bleed into the next test's reset store.
137
- registerInstance: async (inst) => {
138
- const supersededBridgeIds = /* @__PURE__ */ new Set();
139
- for (const [bridgeId, oldInst] of get().instancesByBridgeId) {
140
- if (bridgeId !== inst.bridgeId && isSameAppSlot(oldInst, inst)) {
141
- supersededBridgeIds.add(bridgeId);
142
- }
131
+ function createAppToolsRegistry(options = {}) {
132
+ let disposed = false;
133
+ let enabled = true;
134
+ const pendingRegistrations = /* @__PURE__ */ new Map();
135
+ const slotRegistrations = /* @__PURE__ */ new Map();
136
+ const completeRegistration = async (set, get, inst, slot, slotRegistration, registration) => {
137
+ const supersededBridgeIds = /* @__PURE__ */ new Set();
138
+ for (const [bridgeId, oldInst] of get().instancesByBridgeId) {
139
+ if (bridgeId !== inst.bridgeId && isSameAppSlot(oldInst, inst)) {
140
+ supersededBridgeIds.add(bridgeId);
143
141
  }
144
- const aliasesForInst = [];
145
- const existing = new Set(
146
- [...get().aliases.entries()].filter(([, alias]) => {
147
- if (alias.bridgeId === inst.bridgeId) return false;
148
- return !supersededBridgeIds.has(alias.bridgeId);
149
- }).map(([alias]) => alias)
142
+ }
143
+ const aliasesForInst = [];
144
+ const existing = new Set(
145
+ [...get().aliases.entries()].filter(([, alias]) => {
146
+ if (alias.bridgeId === inst.bridgeId) return false;
147
+ return !supersededBridgeIds.has(alias.bridgeId);
148
+ }).map(([alias]) => alias)
149
+ );
150
+ for (const tool of inst.tools) {
151
+ let salt = 0;
152
+ let alias = await generateAlias(
153
+ inst.chatSessionId,
154
+ inst.serverId,
155
+ inst.parentToolCallId,
156
+ inst.surface,
157
+ tool.name,
158
+ salt
150
159
  );
151
- for (const tool of inst.tools) {
152
- let salt = 0;
153
- let alias = await generateAlias(
160
+ while (existing.has(alias)) {
161
+ salt += 1;
162
+ alias = await generateAlias(
154
163
  inst.chatSessionId,
155
164
  inst.serverId,
156
165
  inst.parentToolCallId,
@@ -158,69 +167,109 @@ var useAppToolsRegistry = create(
158
167
  tool.name,
159
168
  salt
160
169
  );
161
- while (existing.has(alias)) {
162
- salt += 1;
163
- alias = await generateAlias(
164
- inst.chatSessionId,
165
- inst.serverId,
166
- inst.parentToolCallId,
167
- inst.surface,
168
- tool.name,
169
- salt
170
- );
170
+ }
171
+ existing.add(alias);
172
+ aliasesForInst.push({
173
+ alias,
174
+ bridgeId: inst.bridgeId,
175
+ rawName: tool.name,
176
+ readOnly: isReadOnly(tool)
177
+ });
178
+ }
179
+ if (disposed || !enabled || pendingRegistrations.get(inst.bridgeId) !== registration || slotRegistrations.get(slot) !== slotRegistration)
180
+ return;
181
+ for (const [bridgeId, oldInst] of get().instancesByBridgeId)
182
+ if (bridgeId !== inst.bridgeId && isSameAppSlot(oldInst, inst))
183
+ supersededBridgeIds.add(bridgeId);
184
+ if (!get().instancesByBridgeId.has(inst.bridgeId) && options.maxInstances !== void 0 && get().instancesByBridgeId.size - supersededBridgeIds.size >= options.maxInstances)
185
+ throw new Error(
186
+ `Widget registry instance limit reached: too many Apps are open (${options.maxInstances}). Close an App to use this one's tools.`
187
+ );
188
+ for (const bridgeId of supersededBridgeIds) {
189
+ const pending = get().pendingControllers.get(bridgeId);
190
+ if (!pending) continue;
191
+ for (const controller of pending) {
192
+ try {
193
+ controller.abort();
194
+ } catch {
171
195
  }
172
- existing.add(alias);
173
- aliasesForInst.push({
174
- alias,
175
- bridgeId: inst.bridgeId,
176
- rawName: tool.name,
177
- readOnly: isReadOnly(tool)
178
- });
179
196
  }
197
+ }
198
+ set((s) => {
199
+ const instancesByBridgeId = new Map(s.instancesByBridgeId);
180
200
  for (const bridgeId of supersededBridgeIds) {
181
- const pending = get().pendingControllers.get(bridgeId);
182
- if (!pending) continue;
183
- for (const controller of pending) {
184
- try {
185
- controller.abort();
186
- } catch {
187
- }
201
+ instancesByBridgeId.delete(bridgeId);
202
+ }
203
+ instancesByBridgeId.set(inst.bridgeId, inst);
204
+ const aliases = new Map(s.aliases);
205
+ for (const [alias, a] of s.aliases) {
206
+ if (a.bridgeId === inst.bridgeId || supersededBridgeIds.has(a.bridgeId)) {
207
+ aliases.delete(alias);
188
208
  }
189
209
  }
190
- set((s) => {
191
- const instancesByBridgeId = new Map(s.instancesByBridgeId);
210
+ for (const a of aliasesForInst) aliases.set(a.alias, a);
211
+ const activeBridgeByParent = new Map(s.activeBridgeByParent);
212
+ activeBridgeByParent.set(
213
+ getActiveParentKey(inst.parentToolCallId, inst.chatSessionId),
214
+ inst.bridgeId
215
+ );
216
+ let pendingControllers = s.pendingControllers;
217
+ if (supersededBridgeIds.size > 0) {
218
+ pendingControllers = new Map(s.pendingControllers);
192
219
  for (const bridgeId of supersededBridgeIds) {
193
- instancesByBridgeId.delete(bridgeId);
194
- }
195
- instancesByBridgeId.set(inst.bridgeId, inst);
196
- const aliases = new Map(s.aliases);
197
- for (const [alias, a] of s.aliases) {
198
- if (a.bridgeId === inst.bridgeId || supersededBridgeIds.has(a.bridgeId)) {
199
- aliases.delete(alias);
200
- }
220
+ pendingControllers.delete(bridgeId);
201
221
  }
202
- for (const a of aliasesForInst) aliases.set(a.alias, a);
203
- const activeBridgeByParent = new Map(s.activeBridgeByParent);
204
- activeBridgeByParent.set(
205
- getActiveParentKey(inst.parentToolCallId, inst.chatSessionId),
206
- inst.bridgeId
222
+ }
223
+ return {
224
+ instancesByBridgeId,
225
+ aliases,
226
+ activeBridgeByParent,
227
+ pendingControllers
228
+ };
229
+ });
230
+ };
231
+ return create((set, get) => ({
232
+ instancesByBridgeId: /* @__PURE__ */ new Map(),
233
+ aliases: /* @__PURE__ */ new Map(),
234
+ activeBridgeByParent: /* @__PURE__ */ new Map(),
235
+ pendingControllers: /* @__PURE__ */ new Map(),
236
+ // Returns a Promise so callers (and tests) can await the alias-hash
237
+ // round-trip. The renderer uses `void registerInstance(...)` because
238
+ // there's nothing to do until the next chat POST. Tests await so
239
+ // resolved microtasks don't bleed into the next test's reset store.
240
+ registerInstance: async (inst) => {
241
+ if (disposed || !enabled) return;
242
+ if (!pendingRegistrations.has(inst.bridgeId) && options.maxIdentities !== void 0 && pendingRegistrations.size >= options.maxIdentities)
243
+ throw new Error(
244
+ "Widget registry identity limit reached: too many Apps are registering tools at once. Try again in a moment."
207
245
  );
208
- let pendingControllers = s.pendingControllers;
209
- if (supersededBridgeIds.size > 0) {
210
- pendingControllers = new Map(s.pendingControllers);
211
- for (const bridgeId of supersededBridgeIds) {
212
- pendingControllers.delete(bridgeId);
213
- }
214
- }
215
- return {
216
- instancesByBridgeId,
217
- aliases,
218
- activeBridgeByParent,
219
- pendingControllers
220
- };
221
- });
246
+ const slot = JSON.stringify([
247
+ inst.chatSessionId ?? null,
248
+ inst.parentToolCallId,
249
+ inst.surface
250
+ ]);
251
+ const slotRegistration = Symbol();
252
+ slotRegistrations.set(slot, slotRegistration);
253
+ const registration = Symbol();
254
+ pendingRegistrations.set(inst.bridgeId, registration);
255
+ try {
256
+ await completeRegistration(
257
+ set,
258
+ get,
259
+ inst,
260
+ slot,
261
+ slotRegistration,
262
+ registration
263
+ );
264
+ } finally {
265
+ if (pendingRegistrations.get(inst.bridgeId) === registration)
266
+ pendingRegistrations.delete(inst.bridgeId);
267
+ if (slotRegistrations.get(slot) === slotRegistration)
268
+ slotRegistrations.delete(slot);
269
+ }
222
270
  },
223
271
  unregisterInstance: (bridgeId) => {
272
+ pendingRegistrations.delete(bridgeId);
224
273
  const pending = get().pendingControllers.get(bridgeId);
225
274
  if (pending) {
226
275
  for (const controller of pending) {
@@ -269,6 +318,10 @@ var useAppToolsRegistry = create(
269
318
  });
270
319
  },
271
320
  registerPendingCall: (bridgeId, controller) => {
321
+ if (disposed || !enabled || !get().instancesByBridgeId.has(bridgeId)) {
322
+ controller.abort();
323
+ return;
324
+ }
272
325
  set((s) => {
273
326
  const pendingControllers = new Map(s.pendingControllers);
274
327
  const next = new Set(pendingControllers.get(bridgeId));
@@ -321,6 +374,7 @@ var useAppToolsRegistry = create(
321
374
  });
322
375
  },
323
376
  snapshotForChatBody: (chatSessionId) => {
377
+ if (disposed || !enabled) return [];
324
378
  const { instancesByBridgeId, aliases, activeBridgeByParent } = get();
325
379
  const out = [];
326
380
  let dropped = 0;
@@ -386,7 +440,20 @@ var useAppToolsRegistry = create(
386
440
  }
387
441
  return out;
388
442
  },
443
+ setEnabled: (value) => {
444
+ enabled = value;
445
+ if (!value)
446
+ for (const pending of get().pendingControllers.values())
447
+ for (const controller of pending) controller.abort();
448
+ },
449
+ dispose: () => {
450
+ disposed = true;
451
+ enabled = false;
452
+ for (const bridgeId of get().instancesByBridgeId.keys())
453
+ get().unregisterInstance(bridgeId);
454
+ },
389
455
  resolve: (alias, chatSessionId) => {
456
+ if (disposed || !enabled) return null;
390
457
  const a = get().aliases.get(alias);
391
458
  if (!a) return null;
392
459
  const inst = get().instancesByBridgeId.get(a.bridgeId);
@@ -404,24 +471,52 @@ var useAppToolsRegistry = create(
404
471
  instance: inst
405
472
  };
406
473
  }
407
- })
474
+ }));
475
+ }
476
+ var legacyAppToolsRegistry = createAppToolsRegistry();
477
+ function useAppToolsRegistryApi() {
478
+ return useContext(WidgetWorkspaceContext)?.registry ?? legacyAppToolsRegistry;
479
+ }
480
+ var useAppToolsRegistry = Object.assign(
481
+ (selector = (state) => state) => useStore(useAppToolsRegistryApi(), selector),
482
+ legacyAppToolsRegistry
408
483
  );
409
484
  var MAX_INVOCATION_RECORDS = 200;
410
- var useAppToolInvocationLog = create(
411
- (set) => ({
485
+ function createAppToolInvocationLog() {
486
+ let enabled = true;
487
+ let disposed = false;
488
+ return create((set) => ({
412
489
  records: [],
413
- append: (r) => set((s) => {
414
- const next = s.records.concat(r);
415
- if (next.length > MAX_INVOCATION_RECORDS) {
416
- next.splice(0, next.length - MAX_INVOCATION_RECORDS);
417
- }
418
- return { records: next };
419
- }),
420
- clear: () => set({ records: [] })
421
- })
490
+ append: (r) => {
491
+ if (disposed || !enabled) return;
492
+ set((s) => {
493
+ const next = s.records.concat(r);
494
+ if (next.length > MAX_INVOCATION_RECORDS) {
495
+ next.splice(0, next.length - MAX_INVOCATION_RECORDS);
496
+ }
497
+ return { records: next };
498
+ });
499
+ },
500
+ clear: () => set({ records: [] }),
501
+ setEnabled: (value) => {
502
+ enabled = value;
503
+ },
504
+ dispose: () => {
505
+ disposed = true;
506
+ set({ records: [] });
507
+ }
508
+ }));
509
+ }
510
+ var legacyInvocationLog = createAppToolInvocationLog();
511
+ function useAppToolInvocationLogApi() {
512
+ return useContext(WidgetWorkspaceContext)?.invocations ?? legacyInvocationLog;
513
+ }
514
+ var useAppToolInvocationLog = Object.assign(
515
+ (selector = (state) => state) => useStore(useAppToolInvocationLogApi(), selector),
516
+ legacyInvocationLog
422
517
  );
423
- function recordAppToolInvocation(args, addTrafficLog) {
424
- useAppToolInvocationLog.getState().append({
518
+ function recordAppToolInvocation(args, addTrafficLog, invocationLog = legacyInvocationLog) {
519
+ invocationLog.getState().append({
425
520
  ...args,
426
521
  invokedAtMs: Date.now()
427
522
  });
@@ -930,7 +1025,8 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
930
1025
  sandboxOrigin = "",
931
1026
  mountMode,
932
1027
  viewOriginLabel,
933
- viewSubdomainsEnabled
1028
+ viewSubdomainsEnabled,
1029
+ reloadKey
934
1030
  }, ref) {
935
1031
  const outerRef = useRef(null);
936
1032
  const [proxyReady, setProxyReady] = useState(false);
@@ -986,6 +1082,10 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
986
1082
  onMessageRef.current(event);
987
1083
  return;
988
1084
  }
1085
+ if (event.data?.type === "mcpjam:view-channel-closed") {
1086
+ onMessageRef.current(event);
1087
+ return;
1088
+ }
989
1089
  if (event.data?.type === "mcpjam:csp-applied") {
990
1090
  onMessageRef.current(event);
991
1091
  return;
@@ -1038,7 +1138,8 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
1038
1138
  recordMode: recordMode ?? null,
1039
1139
  // Part of the render recipe: it decides how the proxy mounts the HTML,
1040
1140
  // so a change must re-send rather than leave the previous mount up.
1041
- mountMode: mountMode ?? null
1141
+ mountMode: mountMode ?? null,
1142
+ reloadKey: reloadKey ?? null
1042
1143
  }),
1043
1144
  [
1044
1145
  csp,
@@ -1052,7 +1153,8 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
1052
1153
  sandbox,
1053
1154
  sandboxAttrs,
1054
1155
  recordMode,
1055
- mountMode
1156
+ mountMode,
1157
+ reloadKey
1056
1158
  ]
1057
1159
  );
1058
1160
  useEffect(() => {
@@ -1075,11 +1177,11 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
1075
1177
  sandboxAttrs,
1076
1178
  // `allowFeatures` is intentionally NOT forwarded to the proxy:
1077
1179
  // it applies to the OUTER iframe only. The inner iframe gets the
1078
- // 4 spec permissions (via `permissions`) and nothing else, matching
1079
- // real claude.ai's outer-grants-fullscreen / inner-trims-to-spec
1080
- // pattern. Centralizing the outer/inner split here means the proxy
1081
- // can't accidentally widen the inner grant by reading a stale
1082
- // field.
1180
+ // 4 spec permissions (via `permissions`) and nothing else — the
1181
+ // proxy itself adds `fullscreen *` on the opaque mount, as
1182
+ // Claude's opaque mode does. Centralizing the outer/inner split here means
1183
+ // the proxy can't accidentally widen the inner grant by reading a
1184
+ // stale field.
1083
1185
  cspDirectives,
1084
1186
  cspSubtypePolicy,
1085
1187
  clientContext,
@@ -1130,6 +1232,20 @@ var SandboxedIframe = forwardRef(function SandboxedIframe2({
1130
1232
  `${sandboxProxyOrigin}\0${outerSandboxAttribute}`
1131
1233
  );
1132
1234
  });
1235
+ function useInitialRenderOutcome(ready, failed, notify) {
1236
+ const delivered = useRef(false);
1237
+ const callback = useRef(notify);
1238
+ callback.current = notify;
1239
+ useEffect(() => {
1240
+ if (delivered.current || !ready && !failed || !callback.current) return;
1241
+ delivered.current = true;
1242
+ try {
1243
+ callback.current(failed ? "error" : "ready");
1244
+ } catch {
1245
+ }
1246
+ }, [ready, failed, notify]);
1247
+ }
1248
+ var WidgetFullscreenPlacementContext = createContext(null);
1133
1249
  function McpAppsModal({
1134
1250
  open,
1135
1251
  onOpenChange,
@@ -1148,6 +1264,7 @@ function McpAppsModal({
1148
1264
  widgetClientContext,
1149
1265
  widgetToolResult,
1150
1266
  widgetBrowserStorage,
1267
+ widgetMountMode,
1151
1268
  hostContextRef,
1152
1269
  serverId,
1153
1270
  resourceUri,
@@ -1166,6 +1283,7 @@ function McpAppsModal({
1166
1283
  onCspApplied
1167
1284
  }) {
1168
1285
  const host = useWidgetHost();
1286
+ const appToolsRegistry = useAppToolsRegistryApi();
1169
1287
  const Modal = host.components?.Modal;
1170
1288
  const [modalHtml, setModalHtml] = useState(null);
1171
1289
  const modalSandboxRef = useRef(null);
@@ -1178,7 +1296,7 @@ function McpAppsModal({
1178
1296
  });
1179
1297
  modalBridgeRef.current = null;
1180
1298
  if (modalAppToolsBridgeIdRef.current) {
1181
- useAppToolsRegistry.getState().unregisterInstance(modalAppToolsBridgeIdRef.current);
1299
+ appToolsRegistry.getState().unregisterInstance(modalAppToolsBridgeIdRef.current);
1182
1300
  modalAppToolsBridgeIdRef.current = null;
1183
1301
  }
1184
1302
  setModalHtml(null);
@@ -1208,6 +1326,7 @@ function McpAppsModal({
1208
1326
  };
1209
1327
  fetchModalHtml();
1210
1328
  }, [
1329
+ appToolsRegistry,
1211
1330
  open,
1212
1331
  template,
1213
1332
  params,
@@ -1336,12 +1455,13 @@ function McpAppsModal({
1336
1455
  if (modalAppToolsBridgeIdRef.current) {
1337
1456
  const bridgeId = modalAppToolsBridgeIdRef.current;
1338
1457
  modalAppToolsBridgeIdRef.current = null;
1339
- useAppToolsRegistry.getState().unregisterInstance(bridgeId);
1458
+ appToolsRegistry.getState().unregisterInstance(bridgeId);
1340
1459
  }
1341
1460
  bridge.close().catch(() => {
1342
1461
  });
1343
1462
  };
1344
1463
  }, [
1464
+ appToolsRegistry,
1345
1465
  modalHtml,
1346
1466
  open,
1347
1467
  addUiLog,
@@ -1402,7 +1522,7 @@ function McpAppsModal({
1402
1522
  title: `MCP App Modal: ${title}`,
1403
1523
  hostedMode: host.surface.hostedMode,
1404
1524
  sandboxOrigin: host.surface.sandboxOrigin,
1405
- mountMode: host.surface.viewMountMode,
1525
+ mountMode: widgetMountMode ?? host.surface.viewMountMode,
1406
1526
  viewSubdomainsEnabled: host.surface.viewSubdomainsEnabled,
1407
1527
  className: "min-w-full border-0 rounded-md bg-transparent overflow-hidden",
1408
1528
  style: {
@@ -1500,106 +1620,195 @@ function WidgetSurfaceHostProvider({
1500
1620
  return /* @__PURE__ */ jsx(WidgetSurfaceHostContext.Provider, { value: true, children });
1501
1621
  }
1502
1622
  function usePersistentWidgetSurfaceHost() {
1503
- return useContext(WidgetSurfaceHostContext);
1623
+ const legacy = useContext(WidgetSurfaceHostContext);
1624
+ const workspace = useContext(WidgetWorkspaceContext);
1625
+ return legacy || workspace !== null;
1504
1626
  }
1505
- var useWidgetSurfaceStore = create((set) => ({
1506
- surfaces: /* @__PURE__ */ new Map(),
1507
- nextOrder: 0,
1508
- upsertRegistration: (surfaceId, toolCallId, props) => {
1509
- set((state) => {
1510
- const surfaces = new Map(state.surfaces);
1511
- const existing = surfaces.get(surfaceId);
1512
- const registrations = new Map(existing?.registrations);
1513
- const currentRegistration = registrations.get(toolCallId);
1514
- const isNewRegistration = !currentRegistration;
1515
- const order = currentRegistration?.order ?? state.nextOrder;
1516
- const latestRegistration = existing?.registrations.get(
1517
- existing.latestToolCallId
1518
- );
1519
- const shouldBecomeLatest = !existing || !latestRegistration || isNewRegistration && order > latestRegistration.order;
1520
- registrations.set(toolCallId, {
1521
- toolCallId,
1522
- order,
1523
- props,
1524
- anchorElement: currentRegistration?.anchorElement ?? null
1525
- });
1526
- surfaces.set(surfaceId, {
1527
- surfaceId,
1528
- chatSessionId: props.chatSessionId,
1529
- initialToolCallId: existing?.initialToolCallId ?? toolCallId,
1530
- latestToolCallId: shouldBecomeLatest ? toolCallId : existing.latestToolCallId,
1531
- registrations
1532
- });
1533
- return {
1534
- surfaces,
1535
- nextOrder: isNewRegistration ? state.nextOrder + 1 : state.nextOrder
1536
- };
1537
- });
1538
- },
1539
- setAnchor: (surfaceId, toolCallId, anchorElement) => {
1540
- set((state) => {
1541
- const existing = state.surfaces.get(surfaceId);
1542
- const registration = existing?.registrations.get(toolCallId);
1543
- if (!existing || !registration) return {};
1544
- if (registration.anchorElement === anchorElement) return {};
1545
- const registrations = new Map(existing.registrations);
1546
- registrations.set(toolCallId, {
1547
- ...registration,
1548
- anchorElement
1549
- });
1550
- const surfaces = new Map(state.surfaces);
1551
- surfaces.set(surfaceId, {
1552
- ...existing,
1553
- registrations
1627
+ var MAX_CLOSED_SURFACE_IDS = 2048;
1628
+ function createWidgetSurfaceStore(options = {}) {
1629
+ const closed = /* @__PURE__ */ new Set();
1630
+ const closeSurfaceId = (surfaceId) => {
1631
+ closed.delete(surfaceId);
1632
+ closed.add(surfaceId);
1633
+ while (closed.size > MAX_CLOSED_SURFACE_IDS) {
1634
+ closed.delete(closed.values().next().value);
1635
+ }
1636
+ };
1637
+ let disposed = false;
1638
+ let enabled = true;
1639
+ const maxInstances = options.maxInstances ?? 64;
1640
+ if (!Number.isSafeInteger(maxInstances) || maxInstances < 1 || maxInstances > 64)
1641
+ throw new Error("Invalid widget instance limit");
1642
+ return create((set) => ({
1643
+ surfaces: /* @__PURE__ */ new Map(),
1644
+ refused: /* @__PURE__ */ new Map(),
1645
+ nextOrder: 0,
1646
+ upsertRegistration: (surfaceId, toolCallId, props, host, presentation) => {
1647
+ set((state) => {
1648
+ const surfaces = new Map(state.surfaces);
1649
+ const existing = surfaces.get(surfaceId);
1650
+ if (disposed || !enabled || closed.has(surfaceId)) return {};
1651
+ if (presentation !== void 0 && (presentation !== "panel" && presentation !== "modal" || existing && (existing.presentation ?? "panel") !== presentation))
1652
+ throw new Error(
1653
+ "Widget presentation cannot change during its lifetime"
1654
+ );
1655
+ if (options.retainInstances && !existing && surfaces.size >= maxInstances) {
1656
+ if (state.refused.has(surfaceId)) return {};
1657
+ const refused2 = new Map(state.refused);
1658
+ refused2.set(surfaceId, {
1659
+ code: "WIDGET_INSTANCE_LIMIT",
1660
+ message: `Too many Apps are open (${maxInstances}). Close an App to open this one.`,
1661
+ limit: maxInstances
1662
+ });
1663
+ while (refused2.size > maxInstances) {
1664
+ refused2.delete(refused2.keys().next().value);
1665
+ }
1666
+ return { refused: refused2 };
1667
+ }
1668
+ const registrations = new Map(existing?.registrations);
1669
+ const currentRegistration = registrations.get(toolCallId);
1670
+ const isNewRegistration = !currentRegistration;
1671
+ const order = currentRegistration?.order ?? state.nextOrder;
1672
+ const latestRegistration = existing?.registrations.get(
1673
+ existing.latestToolCallId
1674
+ );
1675
+ const shouldBecomeLatest = !existing || !latestRegistration || isNewRegistration && order > latestRegistration.order;
1676
+ registrations.set(toolCallId, {
1677
+ toolCallId,
1678
+ order,
1679
+ props,
1680
+ anchorElement: currentRegistration?.anchorElement ?? null
1681
+ });
1682
+ surfaces.set(surfaceId, {
1683
+ surfaceId,
1684
+ presentation: existing?.presentation ?? presentation ?? "panel",
1685
+ chatSessionId: props.chatSessionId,
1686
+ initialToolCallId: existing?.initialToolCallId ?? toolCallId,
1687
+ latestToolCallId: shouldBecomeLatest ? toolCallId : existing.latestToolCallId,
1688
+ registrations,
1689
+ retainedProps: shouldBecomeLatest || existing.latestToolCallId === toolCallId ? props : existing.retainedProps,
1690
+ host: shouldBecomeLatest || existing.latestToolCallId === toolCallId ? host ?? existing?.host : existing.host
1691
+ });
1692
+ let refused = state.refused;
1693
+ if (refused.has(surfaceId)) {
1694
+ refused = new Map(refused);
1695
+ refused.delete(surfaceId);
1696
+ }
1697
+ return {
1698
+ surfaces,
1699
+ refused,
1700
+ nextOrder: isNewRegistration ? state.nextOrder + 1 : state.nextOrder
1701
+ };
1554
1702
  });
1555
- return { surfaces };
1556
- });
1557
- },
1558
- releaseRegistration: (surfaceId, toolCallId) => {
1559
- set((state) => {
1560
- const existing = state.surfaces.get(surfaceId);
1561
- if (!existing || !existing.registrations.has(toolCallId)) return {};
1562
- const surfaces = new Map(state.surfaces);
1563
- const registrations = new Map(existing.registrations);
1564
- registrations.delete(toolCallId);
1565
- if (registrations.size === 0) {
1566
- surfaces.delete(surfaceId);
1703
+ },
1704
+ setAnchor: (surfaceId, toolCallId, anchorElement) => {
1705
+ set((state) => {
1706
+ const existing = state.surfaces.get(surfaceId);
1707
+ const registration = existing?.registrations.get(toolCallId);
1708
+ if (!existing || !registration) return {};
1709
+ if (registration.anchorElement === anchorElement) return {};
1710
+ const registrations = new Map(existing.registrations);
1711
+ registrations.set(toolCallId, {
1712
+ ...registration,
1713
+ anchorElement
1714
+ });
1715
+ const surfaces = new Map(state.surfaces);
1716
+ surfaces.set(surfaceId, {
1717
+ ...existing,
1718
+ registrations
1719
+ });
1567
1720
  return { surfaces };
1568
- }
1569
- let latestRegistration = null;
1570
- for (const registration of registrations.values()) {
1571
- if (latestRegistration === null || registration.order > latestRegistration.order) {
1572
- latestRegistration = registration;
1721
+ });
1722
+ },
1723
+ releaseRegistration: (surfaceId, toolCallId) => {
1724
+ set((state) => {
1725
+ const existing = state.surfaces.get(surfaceId);
1726
+ if (!existing || !existing.registrations.has(toolCallId)) return {};
1727
+ const surfaces = new Map(state.surfaces);
1728
+ const registrations = new Map(existing.registrations);
1729
+ registrations.delete(toolCallId);
1730
+ if (registrations.size === 0 && !options.retainInstances) {
1731
+ surfaces.delete(surfaceId);
1732
+ return { surfaces };
1573
1733
  }
1574
- }
1575
- surfaces.set(surfaceId, {
1576
- ...existing,
1577
- latestToolCallId: existing.latestToolCallId === toolCallId ? latestRegistration?.toolCallId ?? existing.latestToolCallId : existing.latestToolCallId,
1578
- registrations
1734
+ let latestRegistration = null;
1735
+ for (const registration of registrations.values()) {
1736
+ if (latestRegistration === null || registration.order > latestRegistration.order) {
1737
+ latestRegistration = registration;
1738
+ }
1739
+ }
1740
+ surfaces.set(surfaceId, {
1741
+ ...existing,
1742
+ latestToolCallId: existing.latestToolCallId === toolCallId ? latestRegistration?.toolCallId ?? existing.latestToolCallId : existing.latestToolCallId,
1743
+ registrations
1744
+ });
1745
+ return { surfaces };
1579
1746
  });
1580
- return { surfaces };
1581
- });
1582
- },
1583
- clearChatSession: (chatSessionId) => {
1584
- set((state) => {
1585
- let hasMatch = false;
1586
- for (const surface of state.surfaces.values()) {
1587
- if (surface.chatSessionId === chatSessionId) {
1588
- hasMatch = true;
1589
- break;
1747
+ },
1748
+ clearChatSession: (chatSessionId) => {
1749
+ if (options.retainInstances) return;
1750
+ set((state) => {
1751
+ let hasMatch = false;
1752
+ for (const surface of state.surfaces.values()) {
1753
+ if (surface.chatSessionId === chatSessionId) {
1754
+ hasMatch = true;
1755
+ break;
1756
+ }
1590
1757
  }
1591
- }
1592
- if (!hasMatch) return {};
1593
- const surfaces = new Map(state.surfaces);
1594
- for (const [surfaceId, surface] of state.surfaces) {
1595
- if (surface.chatSessionId === chatSessionId) {
1758
+ if (!hasMatch) return {};
1759
+ const surfaces = new Map(state.surfaces);
1760
+ for (const [surfaceId, surface] of state.surfaces) {
1761
+ if (surface.chatSessionId === chatSessionId) {
1762
+ surfaces.delete(surfaceId);
1763
+ }
1764
+ }
1765
+ return { surfaces };
1766
+ });
1767
+ },
1768
+ destroySurface: (surfaceId) => {
1769
+ closeSurfaceId(surfaceId);
1770
+ set((state) => {
1771
+ const hasSurface = state.surfaces.has(surfaceId);
1772
+ const hasRefusal = state.refused.has(surfaceId);
1773
+ if (!hasSurface && !hasRefusal) return {};
1774
+ const next = {};
1775
+ if (hasSurface) {
1776
+ const surfaces = new Map(state.surfaces);
1596
1777
  surfaces.delete(surfaceId);
1778
+ next.surfaces = surfaces;
1597
1779
  }
1598
- }
1599
- return { surfaces };
1600
- });
1601
- }
1602
- }));
1780
+ if (hasRefusal) {
1781
+ const refused = new Map(state.refused);
1782
+ refused.delete(surfaceId);
1783
+ next.refused = refused;
1784
+ }
1785
+ return next;
1786
+ });
1787
+ },
1788
+ setEnabled: (value) => {
1789
+ enabled = value;
1790
+ },
1791
+ dispose: () => {
1792
+ disposed = true;
1793
+ closed.clear();
1794
+ set({ surfaces: /* @__PURE__ */ new Map(), refused: /* @__PURE__ */ new Map() });
1795
+ }
1796
+ }));
1797
+ }
1798
+ function useWidgetSurfaceAdmissionError(surfaceId) {
1799
+ return useStore(
1800
+ useWidgetSurfaceStoreApi(),
1801
+ (state) => surfaceId ? state.refused.get(surfaceId) ?? null : null
1802
+ );
1803
+ }
1804
+ var legacySurfaceStore = createWidgetSurfaceStore();
1805
+ function useWidgetSurfaceStoreApi() {
1806
+ return useContext(WidgetWorkspaceContext)?.surfaces ?? legacySurfaceStore;
1807
+ }
1808
+ var useWidgetSurfaceStore = Object.assign(
1809
+ (selector = (state) => state) => useStore(useWidgetSurfaceStoreApi(), selector),
1810
+ legacySurfaceStore
1811
+ );
1603
1812
  function getRenderableSurfaceEntries(surfaces, chatSessionId) {
1604
1813
  const entries = [];
1605
1814
  for (const surface of surfaces.values()) {
@@ -1618,7 +1827,8 @@ function getRenderableSurfaceEntries(surfaces, chatSessionId) {
1618
1827
  surfaceId: surface.surfaceId,
1619
1828
  anchorElement: initialRegistration?.anchorElement ?? fallbackAnchor,
1620
1829
  initialToolCallId: surface.initialToolCallId,
1621
- props: latestRegistration.props
1830
+ props: latestRegistration.props,
1831
+ host: surface.host
1622
1832
  });
1623
1833
  }
1624
1834
  return entries;
@@ -1775,14 +1985,15 @@ function mapLogToLifecycle(method, details) {
1775
1985
  "debug/bridge-connect-error": "bridge-connect-error",
1776
1986
  "debug/bridge-connect-skipped": "bridge-connect-skipped",
1777
1987
  "debug/app-initialized": "app-initialized",
1778
- "debug/view-mounted": "view-mounted"
1988
+ "debug/view-mounted": "view-mounted",
1989
+ "debug/view-channel-closed": "view-channel-closed"
1779
1990
  };
1780
1991
  const kind = kindByMethod[method];
1781
1992
  if (!kind) return null;
1782
1993
  let status;
1783
1994
  if (method === "debug/view-mounted") {
1784
- status = details.mode === "url" ? "ok" : "error";
1785
- } else if (method.endsWith("-error") || method === "debug/widget-content-invalid-mimetype") {
1995
+ status = details.mode === "url" || details.mode === "opaque" ? "ok" : "error";
1996
+ } else if (method.endsWith("-error") || method === "debug/widget-content-invalid-mimetype" || method === "debug/view-channel-closed") {
1786
1997
  status = "error";
1787
1998
  } else if (method.endsWith("-ready") || method === "debug/app-initialized" || method === "debug/bridge-connect-skipped") {
1788
1999
  status = "ok";
@@ -1843,76 +2054,90 @@ function getPersistentSurfaceId(props) {
1843
2054
  });
1844
2055
  return `mcp-app:${hashSurfaceIdentity(identity)}`;
1845
2056
  }
1846
- var pendingSurfaceReleaseTimers = /* @__PURE__ */ new Map();
1847
- var pendingAnchorClearTimers = /* @__PURE__ */ new Map();
2057
+ var surfaceTimers = /* @__PURE__ */ new WeakMap();
2058
+ function timersFor(store) {
2059
+ let timers = surfaceTimers.get(store);
2060
+ if (!timers) {
2061
+ timers = { release: /* @__PURE__ */ new Map(), anchor: /* @__PURE__ */ new Map() };
2062
+ surfaceTimers.set(store, timers);
2063
+ }
2064
+ return timers;
2065
+ }
1848
2066
  function getSurfaceRegistrationKey(surfaceId, toolCallId) {
1849
2067
  return `${surfaceId}\0${toolCallId}`;
1850
2068
  }
1851
- function cancelPendingAnchorClear(surfaceId, toolCallId) {
2069
+ function cancelPendingAnchorClear(store, surfaceId, toolCallId) {
1852
2070
  const key = getSurfaceRegistrationKey(surfaceId, toolCallId);
1853
- const timer = pendingAnchorClearTimers.get(key);
2071
+ const timer = timersFor(store).anchor.get(key);
1854
2072
  if (timer === void 0) return;
1855
2073
  window.clearTimeout(timer);
1856
- pendingAnchorClearTimers.delete(key);
2074
+ timersFor(store).anchor.delete(key);
1857
2075
  }
1858
- function scheduleAnchorClear(surfaceId, toolCallId) {
2076
+ function scheduleAnchorClear(store, surfaceId, toolCallId) {
1859
2077
  const key = getSurfaceRegistrationKey(surfaceId, toolCallId);
1860
- const existing = pendingAnchorClearTimers.get(key);
2078
+ const existing = timersFor(store).anchor.get(key);
1861
2079
  if (existing !== void 0) window.clearTimeout(existing);
1862
2080
  const timer = window.setTimeout(() => {
1863
- pendingAnchorClearTimers.delete(key);
1864
- useWidgetSurfaceStore.getState().setAnchor(surfaceId, toolCallId, null);
2081
+ timersFor(store).anchor.delete(key);
2082
+ store.getState().setAnchor(surfaceId, toolCallId, null);
1865
2083
  }, 0);
1866
- pendingAnchorClearTimers.set(key, timer);
2084
+ timersFor(store).anchor.set(key, timer);
1867
2085
  }
1868
- function cancelPendingSurfaceRelease(surfaceId, toolCallId) {
2086
+ function cancelPendingSurfaceRelease(store, surfaceId, toolCallId) {
1869
2087
  const key = getSurfaceRegistrationKey(surfaceId, toolCallId);
1870
- const timer = pendingSurfaceReleaseTimers.get(key);
2088
+ const timer = timersFor(store).release.get(key);
1871
2089
  if (timer === void 0) return;
1872
2090
  window.clearTimeout(timer);
1873
- pendingSurfaceReleaseTimers.delete(key);
2091
+ timersFor(store).release.delete(key);
1874
2092
  }
1875
- function scheduleSurfaceRelease(surfaceId, toolCallId) {
2093
+ function scheduleSurfaceRelease(store, surfaceId, toolCallId) {
1876
2094
  const key = getSurfaceRegistrationKey(surfaceId, toolCallId);
1877
- const existing = pendingSurfaceReleaseTimers.get(key);
2095
+ const existing = timersFor(store).release.get(key);
1878
2096
  if (existing !== void 0) window.clearTimeout(existing);
1879
2097
  const timer = window.setTimeout(() => {
1880
- pendingSurfaceReleaseTimers.delete(key);
1881
- useWidgetSurfaceStore.getState().releaseRegistration(surfaceId, toolCallId);
2098
+ timersFor(store).release.delete(key);
2099
+ store.getState().releaseRegistration(surfaceId, toolCallId);
1882
2100
  }, 0);
1883
- pendingSurfaceReleaseTimers.set(key, timer);
2101
+ timersFor(store).release.set(key, timer);
1884
2102
  }
1885
2103
  function PersistentMCPAppsRendererRegistration(props) {
2104
+ const surfaceStore = useWidgetSurfaceStoreApi();
2105
+ const host = useOptionalWidgetHost();
1886
2106
  const surfaceId = useMemo(
1887
2107
  () => getPersistentSurfaceId(props),
1888
2108
  [props.chatSessionId, props.resourceUri, props.serverId, props.toolCallId]
1889
2109
  );
1890
2110
  const anchorRef = useRef(null);
1891
2111
  useLayoutEffect(() => {
1892
- cancelPendingAnchorClear(surfaceId, props.toolCallId);
1893
- cancelPendingSurfaceRelease(surfaceId, props.toolCallId);
2112
+ cancelPendingAnchorClear(surfaceStore, surfaceId, props.toolCallId);
2113
+ cancelPendingSurfaceRelease(surfaceStore, surfaceId, props.toolCallId);
1894
2114
  return () => {
1895
- scheduleSurfaceRelease(surfaceId, props.toolCallId);
2115
+ scheduleSurfaceRelease(surfaceStore, surfaceId, props.toolCallId);
1896
2116
  };
1897
- }, [surfaceId, props.toolCallId]);
2117
+ }, [surfaceStore, surfaceId, props.toolCallId]);
1898
2118
  useLayoutEffect(() => {
1899
- cancelPendingAnchorClear(surfaceId, props.toolCallId);
1900
- cancelPendingSurfaceRelease(surfaceId, props.toolCallId);
1901
- const store = useWidgetSurfaceStore.getState();
1902
- store.upsertRegistration(surfaceId, props.toolCallId, props);
2119
+ cancelPendingAnchorClear(surfaceStore, surfaceId, props.toolCallId);
2120
+ cancelPendingSurfaceRelease(surfaceStore, surfaceId, props.toolCallId);
2121
+ const store = surfaceStore.getState();
2122
+ store.upsertRegistration(
2123
+ surfaceId,
2124
+ props.toolCallId,
2125
+ props,
2126
+ host ?? void 0
2127
+ );
1903
2128
  store.setAnchor(surfaceId, props.toolCallId, anchorRef.current);
1904
2129
  });
1905
2130
  const setAnchor = useCallback(
1906
2131
  (node) => {
1907
2132
  anchorRef.current = node;
1908
2133
  if (node === null) {
1909
- scheduleAnchorClear(surfaceId, props.toolCallId);
2134
+ scheduleAnchorClear(surfaceStore, surfaceId, props.toolCallId);
1910
2135
  return;
1911
2136
  }
1912
- cancelPendingAnchorClear(surfaceId, props.toolCallId);
1913
- useWidgetSurfaceStore.getState().setAnchor(surfaceId, props.toolCallId, node);
2137
+ cancelPendingAnchorClear(surfaceStore, surfaceId, props.toolCallId);
2138
+ surfaceStore.getState().setAnchor(surfaceId, props.toolCallId, node);
1914
2139
  },
1915
- [surfaceId, props.toolCallId]
2140
+ [surfaceStore, surfaceId, props.toolCallId]
1916
2141
  );
1917
2142
  return /* @__PURE__ */ jsx(
1918
2143
  "div",
@@ -1953,6 +2178,7 @@ function MCPAppsRendererSurface({
1953
2178
  onCallTool,
1954
2179
  onAppToolInvocationChange,
1955
2180
  onWidgetStateChange,
2181
+ onInitialRenderOutcome,
1956
2182
  recordMode,
1957
2183
  onRecorderStep,
1958
2184
  onRecorderReady,
@@ -1980,6 +2206,7 @@ function MCPAppsRendererSurface({
1980
2206
  injectedOpenAiCompatCapabilities: initialInjectedOpenAiCompatCapabilities,
1981
2207
  initialWidgetState,
1982
2208
  minimalMode = false,
2209
+ hostManagedPresentation = false,
1983
2210
  persistentSurfaceId,
1984
2211
  persistentSurfaceInitialToolCallId
1985
2212
  }) {
@@ -2048,6 +2275,12 @@ function MCPAppsRendererSurface({
2048
2275
  const liveOpenAiCompatCapabilities = liveEffectiveCompatRuntime.injected ? liveEffectiveCompatRuntime.capabilities : null;
2049
2276
  const isCachedReplay = !!cachedWidgetHtmlUrl && !liveFetchPreferred;
2050
2277
  const cachedReplayWidgetHtmlUrl = isCachedReplay ? cachedWidgetHtmlUrl : void 0;
2278
+ const hasOwnedMessage = !!host.services.sendMessage;
2279
+ const ownedMessageRef = useRef(host.services.sendMessage);
2280
+ ownedMessageRef.current = host.services.sendMessage;
2281
+ const hasOwnedModelContext = !!host.services.updateModelContext;
2282
+ const ownedModelContextRef = useRef(host.services.updateModelContext);
2283
+ ownedModelContextRef.current = host.services.updateModelContext;
2051
2284
  const artifactCacheKey = host.services.artifactCacheKey;
2052
2285
  const cachedWidgetHtmlKey = cachedWidgetHtmlUrl ? artifactCacheKey?.(cachedWidgetHtmlUrl) ?? cachedWidgetHtmlUrl : void 0;
2053
2286
  const cachedReplayWidgetHtmlKey = isCachedReplay ? cachedWidgetHtmlKey : void 0;
@@ -2090,37 +2323,52 @@ function MCPAppsRendererSurface({
2090
2323
  }),
2091
2324
  [activeMcpProfileKey, earlyEffectiveHostStyle]
2092
2325
  );
2326
+ const [resourceDisplayHints, setResourceDisplayHints] = useState();
2327
+ const resourceDisplayHintsRef = useRef(
2328
+ void 0
2329
+ );
2330
+ resourceDisplayHintsRef.current = resourceDisplayHints;
2093
2331
  const [appSupportedDisplayModes, setAppSupportedDisplayModes] = useState(void 0);
2094
- const effectiveAvailableDisplayModes = useMemo(() => {
2332
+ const hostAvailableDisplayModes = useMemo(() => {
2095
2333
  const matrixModes = earlyEffectiveMcpAppsCapabilities.availableDisplayModes;
2096
- const hostIntersection = matrixModes.filter(
2097
- (m) => configuredAvailableDisplayModes.includes(m)
2098
- );
2099
- const baseHostModes = hostIntersection.length > 0 ? hostIntersection : matrixModes;
2100
- if (!appSupportedDisplayModes || appSupportedDisplayModes.length === 0) {
2101
- return baseHostModes;
2102
- }
2103
- const appIntersection = baseHostModes.filter(
2104
- (m) => appSupportedDisplayModes.includes(m)
2334
+ const intersection = matrixModes.filter(
2335
+ (mode) => configuredAvailableDisplayModes.includes(mode)
2105
2336
  );
2106
- return appIntersection.length > 0 ? appIntersection : baseHostModes;
2337
+ return intersection.length ? intersection : matrixModes;
2107
2338
  }, [
2108
2339
  earlyEffectiveMcpAppsCapabilities.availableDisplayModes,
2109
- configuredAvailableDisplayModes,
2110
- appSupportedDisplayModes
2340
+ configuredAvailableDisplayModes
2111
2341
  ]);
2112
- const advertisedAvailableDisplayModes = useMemo(() => {
2113
- if (!appSupportedDisplayModes || appSupportedDisplayModes.length === 0) {
2114
- return effectiveAvailableDisplayModes;
2115
- }
2116
- const intersection = effectiveAvailableDisplayModes.filter(
2117
- (m) => appSupportedDisplayModes.includes(m)
2118
- );
2119
- return intersection.length > 0 ? intersection : effectiveAvailableDisplayModes;
2120
- }, [effectiveAvailableDisplayModes, appSupportedDisplayModes]);
2342
+ const hostAvailableDisplayModesRef = useRef(hostAvailableDisplayModes);
2343
+ hostAvailableDisplayModesRef.current = hostAvailableDisplayModes;
2344
+ const fixedDisplayMode = host.surface.fixedDisplayMode;
2345
+ const fixedDisplayModeRef = useRef(fixedDisplayMode);
2346
+ fixedDisplayModeRef.current = fixedDisplayMode;
2347
+ const displayModesFor = useCallback(
2348
+ (hostModes, hints, appModes) => {
2349
+ const fixed = fixedDisplayModeRef.current;
2350
+ return fixed && hostModes.includes(fixed) ? [fixed] : negotiateResourceDisplayModes([...hostModes], hints, appModes);
2351
+ },
2352
+ []
2353
+ );
2354
+ const effectiveAvailableDisplayModes = useMemo(
2355
+ () => displayModesFor(
2356
+ hostAvailableDisplayModes,
2357
+ resourceDisplayHints,
2358
+ appSupportedDisplayModes
2359
+ ),
2360
+ [
2361
+ displayModesFor,
2362
+ fixedDisplayMode,
2363
+ hostAvailableDisplayModes,
2364
+ resourceDisplayHints,
2365
+ appSupportedDisplayModes
2366
+ ]
2367
+ );
2368
+ const advertisedAvailableDisplayModes = effectiveAvailableDisplayModes;
2121
2369
  const playgroundCapabilities = environment.playgroundCapabilities;
2370
+ const configuredCapabilities = draftHostContext?.deviceCapabilities && typeof draftHostContext.deviceCapabilities === "object" && !Array.isArray(draftHostContext.deviceCapabilities) ? draftHostContext.deviceCapabilities : void 0;
2122
2371
  const deviceCapabilities = useMemo(() => {
2123
- const configuredCapabilities = draftHostContext?.deviceCapabilities && typeof draftHostContext.deviceCapabilities === "object" && !Array.isArray(draftHostContext.deviceCapabilities) ? draftHostContext.deviceCapabilities : void 0;
2124
2372
  if (configuredCapabilities) {
2125
2373
  return {
2126
2374
  hover: configuredCapabilities.hover ?? true,
@@ -2128,10 +2376,16 @@ function MCPAppsRendererSurface({
2128
2376
  };
2129
2377
  }
2130
2378
  return isPlaygroundActive ? playgroundCapabilities : { hover: true, touch: false };
2131
- }, [draftHostContext, isPlaygroundActive, playgroundCapabilities]);
2379
+ }, [
2380
+ configuredCapabilities?.hover,
2381
+ configuredCapabilities?.touch,
2382
+ isPlaygroundActive,
2383
+ playgroundCapabilities?.hover,
2384
+ playgroundCapabilities?.touch
2385
+ ]);
2132
2386
  const playgroundSafeAreaInsets = environment.playgroundSafeAreaInsets;
2387
+ const configuredSafeAreaInsets = draftHostContext?.safeAreaInsets && typeof draftHostContext.safeAreaInsets === "object" && !Array.isArray(draftHostContext.safeAreaInsets) ? draftHostContext.safeAreaInsets : void 0;
2133
2388
  const safeAreaInsets = useMemo(() => {
2134
- const configuredSafeAreaInsets = draftHostContext?.safeAreaInsets && typeof draftHostContext.safeAreaInsets === "object" && !Array.isArray(draftHostContext.safeAreaInsets) ? draftHostContext.safeAreaInsets : void 0;
2135
2389
  if (configuredSafeAreaInsets) {
2136
2390
  return {
2137
2391
  top: configuredSafeAreaInsets.top ?? 0,
@@ -2141,7 +2395,17 @@ function MCPAppsRendererSurface({
2141
2395
  };
2142
2396
  }
2143
2397
  return isPlaygroundActive ? playgroundSafeAreaInsets : { top: 0, right: 0, bottom: 0, left: 0 };
2144
- }, [draftHostContext, isPlaygroundActive, playgroundSafeAreaInsets]);
2398
+ }, [
2399
+ configuredSafeAreaInsets?.top,
2400
+ configuredSafeAreaInsets?.right,
2401
+ configuredSafeAreaInsets?.bottom,
2402
+ configuredSafeAreaInsets?.left,
2403
+ isPlaygroundActive,
2404
+ playgroundSafeAreaInsets?.top,
2405
+ playgroundSafeAreaInsets?.right,
2406
+ playgroundSafeAreaInsets?.bottom,
2407
+ playgroundSafeAreaInsets?.left
2408
+ ]);
2145
2409
  const playgroundDeviceType = environment.playgroundDeviceType;
2146
2410
  const isControlled = displayModeProp !== void 0;
2147
2411
  const [internalDisplayMode, setInternalDisplayMode] = useState(
@@ -2202,6 +2466,25 @@ function MCPAppsRendererSurface({
2202
2466
  ]
2203
2467
  );
2204
2468
  const lastForcedDisplayModeRef = useRef(null);
2469
+ const fullscreenPlacement = useContext(WidgetFullscreenPlacementContext);
2470
+ const placedFullscreen = !hostManagedPresentation && effectiveDisplayMode === "fullscreen" && !(isPlaygroundActive && (playgroundDeviceType === "mobile" || playgroundDeviceType === "tablet")) && !!fullscreenPlacement?.rect;
2471
+ const fullscreenPlacementRef = useRef(fullscreenPlacement);
2472
+ fullscreenPlacementRef.current = fullscreenPlacement;
2473
+ const placedExitRef = useRef(() => {
2474
+ });
2475
+ placedExitRef.current = () => {
2476
+ userPreferInlineRef.current = true;
2477
+ setDisplayMode("inline");
2478
+ };
2479
+ const fullscreenLabel = serverName?.trim() || serverId.trim() || "App";
2480
+ useEffect(() => {
2481
+ if (!placedFullscreen) return;
2482
+ fullscreenPlacementRef.current?.onEnter?.({
2483
+ label: fullscreenLabel,
2484
+ exit: () => placedExitRef.current()
2485
+ });
2486
+ return () => fullscreenPlacementRef.current?.onLeave?.();
2487
+ }, [placedFullscreen, fullscreenLabel]);
2205
2488
  useEffect(() => {
2206
2489
  if (requestedDisplayMode === effectiveDisplayMode) {
2207
2490
  lastForcedDisplayModeRef.current = null;
@@ -2216,12 +2499,14 @@ function MCPAppsRendererSurface({
2216
2499
  const [isReady, setIsReady] = useState(false);
2217
2500
  const [reinitCount, setReinitCount] = useState(0);
2218
2501
  const [loadError, setLoadError] = useState(null);
2502
+ useInitialRenderOutcome(isReady, loadError !== null, onInitialRenderOutcome);
2219
2503
  const [firstCspBlock, setFirstCspBlock] = useState(null);
2220
2504
  const [widgetHtml, setWidgetHtml] = useState(null);
2221
2505
  const [openInAppUrlOverride, setOpenInAppUrlOverride] = useState(null);
2222
2506
  const [sandboxProxyReady, setSandboxProxyReady] = useState(false);
2223
2507
  const [viewMount, setViewMount] = useState(null);
2224
2508
  const [bridgeTransportReady, setBridgeTransportReady] = useState(false);
2509
+ const [bridgeGeneration, setBridgeGeneration] = useState(0);
2225
2510
  const explicitOpenInAppBaseUrl = useMemo(
2226
2511
  () => resolveExplicitBaseUrl(widgetHtml, resourceUri),
2227
2512
  [widgetHtml, resourceUri]
@@ -2305,6 +2590,7 @@ function MCPAppsRendererSurface({
2305
2590
  hasRenderedLiveRef.current = false;
2306
2591
  liveRenderIdentityRef.current = null;
2307
2592
  setWidgetHtml(null);
2593
+ setResourceDisplayHints(void 0);
2308
2594
  setBridgeTransportReady(false);
2309
2595
  setLoadedCspMode(null);
2310
2596
  setLoadedInjectOpenAiCompat(null);
@@ -2334,6 +2620,7 @@ function MCPAppsRendererSurface({
2334
2620
  const appToolsListInFlightBridgeIdsRef = useRef(/* @__PURE__ */ new Set());
2335
2621
  const appToolsListRefreshPendingBridgeIdsRef = useRef(/* @__PURE__ */ new Set());
2336
2622
  const [appToolsBridgeIdState, setAppToolsBridgeIdState] = useState(null);
2623
+ const appToolsRegistry = useAppToolsRegistryApi();
2337
2624
  const pendingAppToolCalls = useAppToolsRegistry(
2338
2625
  (s) => appToolsBridgeIdState ? s.pendingControllers.get(appToolsBridgeIdState)?.size ?? 0 : 0
2339
2626
  );
@@ -2347,6 +2634,8 @@ function MCPAppsRendererSurface({
2347
2634
  ]);
2348
2635
  const onSendFollowUpRef = useRef(onSendFollowUp);
2349
2636
  const onCallToolRef = useRef(onCallTool);
2637
+ const onReadResourceV2Ref = useRef(host.services.readResourceV2);
2638
+ const hasResourceReadV2 = Boolean(host.services.readResourceV2);
2350
2639
  const onAppToolInvocationChangeRef = useRef(onAppToolInvocationChange);
2351
2640
  const appToolInvocationSequenceRef = useRef(0);
2352
2641
  const onRequestPipRef = useRef(onRequestPip);
@@ -2477,6 +2766,7 @@ function MCPAppsRendererSurface({
2477
2766
  mimeTypeWarning: warning,
2478
2767
  mimeTypeValid: valid,
2479
2768
  prefersBorder: prefersBorder2,
2769
+ resourceDisplayHints: resourceHints,
2480
2770
  declaredDomain: serverDeclaredDomain,
2481
2771
  viewOriginLabel: serverViewOriginLabel,
2482
2772
  injectedOpenAiCompat: serverInjectedOpenAiCompat,
@@ -2524,6 +2814,18 @@ function MCPAppsRendererSurface({
2524
2814
  setBridgeTransportReady(false);
2525
2815
  hasRenderedLiveRef.current = true;
2526
2816
  liveRenderIdentityRef.current = liveRenderIdentityKey;
2817
+ const allowed = displayModesFor(
2818
+ hostAvailableDisplayModesRef.current,
2819
+ resourceHints
2820
+ );
2821
+ if (allowed.length === 0) {
2822
+ setLoadError("This App has no supported display mode");
2823
+ return false;
2824
+ }
2825
+ setResourceDisplayHints(resourceHints);
2826
+ if (resourceHints?.preferredDisplayMode && allowed.includes(resourceHints.preferredDisplayMode)) {
2827
+ setDisplayMode(resourceHints.preferredDisplayMode);
2828
+ }
2527
2829
  setWidgetHtml(html);
2528
2830
  setWidgetCsp(csp);
2529
2831
  setFirstCspBlock(null);
@@ -2715,7 +3017,7 @@ function MCPAppsRendererSurface({
2715
3017
  appToolsListedBridgeIdsRef.current.add(bridgeId);
2716
3018
  if (!isLive()) return;
2717
3019
  const appVersion = bridge.getAppVersion();
2718
- await useAppToolsRegistry.getState().registerInstance({
3020
+ await appToolsRegistry.getState().registerInstance({
2719
3021
  bridgeId,
2720
3022
  chatSessionId,
2721
3023
  parentToolCallId: toolCallIdRef.current,
@@ -2733,7 +3035,7 @@ function MCPAppsRendererSurface({
2733
3035
  getIframeElement
2734
3036
  });
2735
3037
  if (!isLive()) {
2736
- useAppToolsRegistry.getState().unregisterInstance(bridgeId);
3038
+ appToolsRegistry.getState().unregisterInstance(bridgeId);
2737
3039
  return;
2738
3040
  }
2739
3041
  needsRefresh = appToolsListRefreshPendingBridgeIdsRef.current.has(bridgeId);
@@ -2747,7 +3049,7 @@ function MCPAppsRendererSurface({
2747
3049
  appToolsListInFlightBridgeIdsRef.current.delete(bridgeId);
2748
3050
  }
2749
3051
  },
2750
- [chatSessionId, logWidgetDebug]
3052
+ [appToolsRegistry, chatSessionId, logWidgetDebug]
2751
3053
  );
2752
3054
  const setWidgetDebugInfo = debug.setWidgetDebugInfo;
2753
3055
  const setWidgetGlobals = debug.setWidgetGlobals;
@@ -3010,6 +3312,11 @@ function MCPAppsRendererSurface({
3010
3312
  () => profileSandbox?.browserStorage,
3011
3313
  [activeMcpProfileKey]
3012
3314
  );
3315
+ const sameOriginAppIframe = useMemo(
3316
+ () => profileSandbox?.sameOriginAppIframe,
3317
+ [activeMcpProfileKey]
3318
+ );
3319
+ const viewMountMode = sameOriginAppIframe === false ? "opaque" : host.surface.viewMountMode;
3013
3320
  const cspDirectivesEffective = useMemo(() => {
3014
3321
  if (!cspDirectivesPolicy) return cspDirectivesPolicy;
3015
3322
  if (!host.surface.hostedMode) return cspDirectivesPolicy;
@@ -3289,6 +3596,7 @@ function MCPAppsRendererSurface({
3289
3596
  useLayoutEffect(() => {
3290
3597
  onSendFollowUpRef.current = onSendFollowUp;
3291
3598
  onCallToolRef.current = onCallTool;
3599
+ onReadResourceV2Ref.current = host.services.readResourceV2;
3292
3600
  onAppToolInvocationChangeRef.current = onAppToolInvocationChange;
3293
3601
  onRequestPipRef.current = onRequestPip;
3294
3602
  onExitPipRef.current = onExitPip;
@@ -3309,6 +3617,7 @@ function MCPAppsRendererSurface({
3309
3617
  }, [
3310
3618
  onSendFollowUp,
3311
3619
  onCallTool,
3620
+ host.services.readResourceV2,
3312
3621
  onAppToolInvocationChange,
3313
3622
  onRequestPip,
3314
3623
  onExitPip,
@@ -3348,6 +3657,16 @@ function MCPAppsRendererSurface({
3348
3657
  });
3349
3658
  const declaredAppModes = appCaps?.availableDisplayModes;
3350
3659
  onAppSupportedDisplayModesChangeRef.current?.(declaredAppModes);
3660
+ const negotiated = displayModesFor(
3661
+ hostAvailableDisplayModesRef.current,
3662
+ resourceDisplayHintsRef.current,
3663
+ declaredAppModes
3664
+ );
3665
+ if (negotiated.length === 0) {
3666
+ setLoadError("This App has no supported display mode");
3667
+ void b.close();
3668
+ return;
3669
+ }
3351
3670
  setAppSupportedDisplayModes(declaredAppModes);
3352
3671
  if (wasReady) {
3353
3672
  setReinitCount((c) => c + 1);
@@ -3363,9 +3682,17 @@ function MCPAppsRendererSurface({
3363
3682
  }
3364
3683
  }
3365
3684
  },
3685
+ ...hasOwnedMessage ? {
3686
+ onSendMessage: async (params) => {
3687
+ const send = ownedMessageRef.current;
3688
+ if (!send) throw new Error("App message unavailable");
3689
+ return await send(params);
3690
+ }
3691
+ } : {},
3366
3692
  onSendFollowUp: (text) => {
3367
3693
  onSendFollowUpRef.current?.(text);
3368
3694
  },
3695
+ onOpenAppLink: host.services.openAppLink,
3369
3696
  onOpenLink: (url) => {
3370
3697
  window.open(url, "_blank", "noopener,noreferrer");
3371
3698
  },
@@ -3391,6 +3718,11 @@ function MCPAppsRendererSurface({
3391
3718
  );
3392
3719
  return result.content;
3393
3720
  },
3721
+ onReadResourceV2: hasResourceReadV2 ? (params, extra) => {
3722
+ const read = onReadResourceV2Ref.current;
3723
+ if (!read) throw new Error("Resource executor unavailable");
3724
+ return read(params, extra);
3725
+ } : void 0,
3394
3726
  onListResources: async (params) => {
3395
3727
  return host.services.listResources(
3396
3728
  serverIdRef.current,
@@ -3492,6 +3824,13 @@ function MCPAppsRendererSurface({
3492
3824
  }
3493
3825
  return { mode: actualMode };
3494
3826
  },
3827
+ ...hasOwnedModelContext ? {
3828
+ onUpdateModelContextV2: async (_id, params) => {
3829
+ const update = ownedModelContextRef.current;
3830
+ if (!update) throw new Error("App model context unavailable");
3831
+ return update(params);
3832
+ }
3833
+ } : {},
3495
3834
  onUpdateModelContext: (ctxToolCallId, { content, structuredContent }) => {
3496
3835
  setWidgetModelContextRef.current(ctxToolCallId, {
3497
3836
  content,
@@ -3593,7 +3932,10 @@ function MCPAppsRendererSurface({
3593
3932
  setIsReady,
3594
3933
  logWidgetDebug,
3595
3934
  refreshAppProvidedTools,
3596
- effectiveHostCapabilitiesKey
3935
+ hasResourceReadV2,
3936
+ effectiveHostCapabilitiesKey,
3937
+ hasOwnedModelContext,
3938
+ hasOwnedMessage
3597
3939
  ]
3598
3940
  );
3599
3941
  useEffect(() => {
@@ -3625,19 +3967,20 @@ function MCPAppsRendererSurface({
3625
3967
  hostPolicyApplied: effectiveSandbox.hostPolicyApplied,
3626
3968
  toolState: toolState ?? null
3627
3969
  });
3628
- const bridge = new AppBridge(
3629
- null,
3630
- resolvedBridgeHostInfo,
3631
- {
3632
- ...effectiveHostCapabilities,
3633
- sandbox: {
3634
- csp: effectiveSandbox.csp,
3635
- permissions: effectiveSandbox.permissions
3636
- }
3970
+ const bridge = createHostAppBridge({
3971
+ hostInfo: resolvedBridgeHostInfo,
3972
+ hostCapabilities: effectiveHostCapabilities,
3973
+ sandbox: {
3974
+ csp: effectiveSandbox.csp,
3975
+ permissions: effectiveSandbox.permissions
3637
3976
  },
3638
- { hostContext: hostContextRef.current ?? {} }
3639
- );
3977
+ hostContext: hostContextRef.current ?? {}
3978
+ });
3640
3979
  registerBridgeHandlers(bridge);
3980
+ const releaseExtensions = host.services.configureAppBridge?.(
3981
+ bridge,
3982
+ effectiveHostCapabilities
3983
+ );
3641
3984
  bridgeRef.current = bridge;
3642
3985
  const pendingRpcMethods = /* @__PURE__ */ new Map();
3643
3986
  const transport = new LoggingTransport(
@@ -3691,6 +4034,7 @@ function MCPAppsRendererSurface({
3691
4034
  bridge.connect(transport).then(() => {
3692
4035
  if (!isActive) return;
3693
4036
  setBridgeTransportReady(true);
4037
+ setBridgeGeneration((generation) => generation + 1);
3694
4038
  logWidgetDebug("host-to-ui", "debug/bridge-connect-ready", {
3695
4039
  htmlLength: widgetHtml.length
3696
4040
  });
@@ -3704,12 +4048,17 @@ function MCPAppsRendererSurface({
3704
4048
  });
3705
4049
  return () => {
3706
4050
  isActive = false;
4051
+ try {
4052
+ releaseExtensions?.();
4053
+ } catch {
4054
+ logWidgetDebug("host-to-ui", "debug/extension-cleanup-error", {});
4055
+ }
3707
4056
  logWidgetDebug("host-to-ui", "debug/bridge-connect-cleanup", {
3708
4057
  wasReady: isReadyRef.current
3709
4058
  });
3710
4059
  bridgeRef.current = null;
3711
4060
  if (appToolsBridgeIdRef.current) {
3712
- useAppToolsRegistry.getState().unregisterInstance(appToolsBridgeIdRef.current);
4061
+ appToolsRegistry.getState().unregisterInstance(appToolsBridgeIdRef.current);
3713
4062
  appToolsListedBridgeIdsRef.current.delete(appToolsBridgeIdRef.current);
3714
4063
  appToolsListInFlightBridgeIdsRef.current.delete(
3715
4064
  appToolsBridgeIdRef.current
@@ -3747,7 +4096,8 @@ function MCPAppsRendererSurface({
3747
4096
  // Bridge must rebuild when the host identity advertised in
3748
4097
  // ui/initialize changes — switching to a template that overrides
3749
4098
  // hostInfo (e.g. ChatGPT) is observable to the View.
3750
- resolvedBridgeHostInfoKey
4099
+ resolvedBridgeHostInfoKey,
4100
+ host.services.configureAppBridge
3751
4101
  ]);
3752
4102
  useEffect(() => {
3753
4103
  const bridge = bridgeRef.current;
@@ -3849,7 +4199,7 @@ function MCPAppsRendererSurface({
3849
4199
  }
3850
4200
  if (data.type === "mcpjam:view-mode") {
3851
4201
  const mode = data.mode;
3852
- if (mode === "url" || mode === "srcdoc" || mode === "srcdoc-fallback") {
4202
+ if (mode === "url" || mode === "srcdoc" || mode === "srcdoc-fallback" || mode === "opaque") {
3853
4203
  const url = typeof data.url === "string" ? data.url : "";
3854
4204
  const mountId = normalizeCspMountId(data.mountId);
3855
4205
  setViewMount({ mountId, mode, url });
@@ -3861,6 +4211,13 @@ function MCPAppsRendererSurface({
3861
4211
  }
3862
4212
  return;
3863
4213
  }
4214
+ if (data.type === "mcpjam:view-channel-closed") {
4215
+ logWidgetDebug("ui-to-host", "debug/view-channel-closed", {
4216
+ mountId: normalizeCspMountId(data.mountId),
4217
+ reason: typeof data.reason === "string" ? data.reason : void 0
4218
+ });
4219
+ return;
4220
+ }
3864
4221
  if (data.type === "recorder:step") {
3865
4222
  recorderDebug2("step from sandbox", {
3866
4223
  toolName,
@@ -4070,10 +4427,15 @@ function MCPAppsRendererSurface({
4070
4427
  const isContainedFullscreenMode = isPlaygroundActive && (playgroundDeviceType === "mobile" || playgroundDeviceType === "tablet");
4071
4428
  const showOpenInAppButton = isFullscreen && !!openInAppUrl && !isMobilePlaygroundMode;
4072
4429
  const containerClassName = (() => {
4430
+ if (hostManagedPresentation)
4431
+ return "relative h-full min-h-0 w-full bg-background flex flex-col";
4073
4432
  if (isFullscreen) {
4074
4433
  if (isContainedFullscreenMode) {
4075
4434
  return "absolute inset-0 z-10 w-full h-full bg-background flex flex-col";
4076
4435
  }
4436
+ if (placedFullscreen) {
4437
+ return "fixed z-50 bg-background flex flex-col";
4438
+ }
4077
4439
  return "fixed inset-0 z-40 w-full h-full bg-background flex flex-col";
4078
4440
  }
4079
4441
  if (isPip) {
@@ -4097,7 +4459,7 @@ function MCPAppsRendererSurface({
4097
4459
  })();
4098
4460
  const canTransitionHeight = !isFullscreen && effectiveDisplayModeRef.current === effectiveDisplayMode;
4099
4461
  const iframeStyle = {
4100
- height: isFullscreen ? "100%" : isPip ? PIP_MAX_HEIGHT : lastInlineHeightRef.current,
4462
+ height: hostManagedPresentation || isFullscreen ? "100%" : isPip ? PIP_MAX_HEIGHT : lastInlineHeightRef.current,
4101
4463
  width: "100%",
4102
4464
  maxWidth: "100%",
4103
4465
  backgroundColor: !isFullscreen && matrixGatedPrefersBorder ? mergedStyleVariables["--color-background-primary"] : hostChatBackground ?? "transparent",
@@ -4109,7 +4471,7 @@ function MCPAppsRendererSurface({
4109
4471
  // Keep iframe in the layout but invisible while not ready
4110
4472
  ...!showWidget ? { position: "absolute", pointerEvents: "none" } : {}
4111
4473
  };
4112
- const showHostChrome = !isFullscreen && matrixGatedPrefersBorder && !showCspBlockedNotice;
4474
+ const showHostChrome = !hostManagedPresentation && !isFullscreen && matrixGatedPrefersBorder && !showCspBlockedNotice;
4113
4475
  const hostChromeStyle = showHostChrome ? {
4114
4476
  backgroundColor: mergedStyleVariables["--color-background-primary"]
4115
4477
  } : void 0;
@@ -4129,6 +4491,7 @@ function MCPAppsRendererSurface({
4129
4491
  {
4130
4492
  ref: sandboxRef,
4131
4493
  html: bridgeTransportReady ? widgetHtml : null,
4494
+ reloadKey: bridgeGeneration,
4132
4495
  sandbox: "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",
4133
4496
  csp: effectiveSandbox.csp,
4134
4497
  permissions: effectiveSandbox.permissions,
@@ -4152,7 +4515,7 @@ function MCPAppsRendererSurface({
4152
4515
  title: `MCP App: ${toolName}`,
4153
4516
  hostedMode: host.surface.hostedMode,
4154
4517
  sandboxOrigin: host.surface.sandboxOrigin,
4155
- mountMode: host.surface.viewMountMode,
4518
+ mountMode: viewMountMode,
4156
4519
  viewOriginLabel,
4157
4520
  viewSubdomainsEnabled: host.surface.viewSubdomainsEnabled,
4158
4521
  className: `bg-transparent overflow-hidden ${isFullscreen ? "flex-1 border-0 rounded-none" : `rounded-md ${matrixGatedPrefersBorder ? "border border-border/40" : ""}`}`,
@@ -4163,10 +4526,18 @@ function MCPAppsRendererSurface({
4163
4526
  "div",
4164
4527
  {
4165
4528
  className: containerClassName,
4529
+ style: placedFullscreen && fullscreenPlacement?.rect ? {
4530
+ inset: "auto",
4531
+ top: fullscreenPlacement.rect.top,
4532
+ left: fullscreenPlacement.rect.left,
4533
+ width: fullscreenPlacement.rect.width,
4534
+ height: fullscreenPlacement.rect.height
4535
+ } : void 0,
4536
+ "data-mcp-app-fullscreen-placed": placedFullscreen || void 0,
4166
4537
  "data-mcp-app-persistent-initial-tool-call-id": persistentSurfaceInitialToolCallId,
4167
4538
  "data-mcp-app-persistent-surface-id": persistentSurfaceId,
4168
4539
  children: [
4169
- (isFullscreen && isContainedFullscreenMode || isPip && isMobilePlaygroundMode) && /* @__PURE__ */ jsxs(Fragment, { children: [
4540
+ !hostManagedPresentation && (isFullscreen && isContainedFullscreenMode || isPip && isMobilePlaygroundMode) && /* @__PURE__ */ jsxs(Fragment, { children: [
4170
4541
  /* @__PURE__ */ jsx(
4171
4542
  "button",
4172
4543
  {
@@ -4193,7 +4564,7 @@ function MCPAppsRendererSurface({
4193
4564
  }
4194
4565
  )
4195
4566
  ] }),
4196
- 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: [
4567
+ !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: [
4197
4568
  /* @__PURE__ */ jsx("div", {}),
4198
4569
  /* @__PURE__ */ jsx("div", { className: "font-medium text-sm text-muted-foreground min-w-0 max-w-[40vw] truncate", children: openInAppLabel }),
4199
4570
  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-2 min-w-0", children: [
@@ -4222,15 +4593,16 @@ function MCPAppsRendererSurface({
4222
4593
  if (ownsPipDisplayMode) {
4223
4594
  onExitPip?.(pipWidgetId ?? displayWidgetId);
4224
4595
  }
4596
+ if (placedFullscreen) fullscreenPlacement?.onExit?.();
4225
4597
  },
4226
- className: "p-2 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors",
4598
+ 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",
4227
4599
  "aria-label": "Exit fullscreen",
4228
- children: /* @__PURE__ */ jsx(X, { className: "w-5 h-5" })
4600
+ children: placedFullscreen && fullscreenPlacement?.exitLabel ? fullscreenPlacement.exitLabel : /* @__PURE__ */ jsx(X, { className: "w-5 h-5" })
4229
4601
  }
4230
4602
  )
4231
4603
  ] })
4232
4604
  ] }),
4233
- isPip && !isMobilePlaygroundMode && /* @__PURE__ */ jsx(
4605
+ !hostManagedPresentation && isPip && !isMobilePlaygroundMode && /* @__PURE__ */ jsx(
4234
4606
  "button",
4235
4607
  {
4236
4608
  onClick: () => {
@@ -4294,6 +4666,7 @@ function MCPAppsRendererSurface({
4294
4666
  widgetCspSubtypePolicy: effectiveSandbox.cspSubtypePolicy,
4295
4667
  widgetClientContext: cspClientContext,
4296
4668
  widgetBrowserStorage: effectiveSandbox.browserStorage,
4669
+ widgetMountMode: viewMountMode,
4297
4670
  widgetToolResult: earlyEffectiveMcpAppsCapabilities.toolResult,
4298
4671
  hostContextRef,
4299
4672
  serverId,
@@ -4348,7 +4721,8 @@ function WidgetSurfacePortal({
4348
4721
  initialToolCallId,
4349
4722
  parkingElement,
4350
4723
  props,
4351
- surfaceId
4724
+ surfaceId,
4725
+ host
4352
4726
  }) {
4353
4727
  const [container] = useState(() => createSurfaceContainer(surfaceId));
4354
4728
  const targetElement = anchorElement ?? parkingElement;
@@ -4363,15 +4737,16 @@ function WidgetSurfacePortal({
4363
4737
  container.remove();
4364
4738
  };
4365
4739
  }, [container]);
4740
+ const renderer = /* @__PURE__ */ jsx(
4741
+ MCPAppsRendererSurface,
4742
+ {
4743
+ ...props,
4744
+ persistentSurfaceInitialToolCallId: initialToolCallId,
4745
+ persistentSurfaceId: surfaceId
4746
+ }
4747
+ );
4366
4748
  return createPortal(
4367
- /* @__PURE__ */ jsx(
4368
- MCPAppsRendererSurface,
4369
- {
4370
- ...props,
4371
- persistentSurfaceInitialToolCallId: initialToolCallId,
4372
- persistentSurfaceId: surfaceId
4373
- }
4374
- ),
4749
+ host ? /* @__PURE__ */ jsx(WidgetHostProvider, { value: host, children: renderer }) : renderer,
4375
4750
  container,
4376
4751
  surfaceId
4377
4752
  );
@@ -4379,6 +4754,8 @@ function WidgetSurfacePortal({
4379
4754
  function WidgetSurfaceHost({
4380
4755
  chatSessionId
4381
4756
  }) {
4757
+ const workspace = useContext(WidgetWorkspaceContext);
4758
+ const surfaceStore = useWidgetSurfaceStoreApi();
4382
4759
  const [parkingElement, setParkingElement] = useState(
4383
4760
  null
4384
4761
  );
@@ -4389,9 +4766,10 @@ function WidgetSurfaceHost({
4389
4766
  );
4390
4767
  useEffect(() => {
4391
4768
  return () => {
4392
- useWidgetSurfaceStore.getState().clearChatSession(chatSessionId);
4769
+ surfaceStore.getState().clearChatSession(chatSessionId);
4393
4770
  };
4394
- }, [chatSessionId]);
4771
+ }, [chatSessionId, surfaceStore]);
4772
+ if (workspace) return null;
4395
4773
  return /* @__PURE__ */ jsxs(Fragment, { children: [
4396
4774
  /* @__PURE__ */ jsx(
4397
4775
  "div",
@@ -4407,20 +4785,114 @@ function WidgetSurfaceHost({
4407
4785
  }
4408
4786
  }
4409
4787
  ),
4410
- entries.map(({ surfaceId, anchorElement, initialToolCallId, props }) => /* @__PURE__ */ jsx(
4411
- WidgetSurfacePortal,
4412
- {
4413
- anchorElement,
4414
- initialToolCallId,
4415
- parkingElement,
4416
- props,
4788
+ entries.map(
4789
+ ({ surfaceId, anchorElement, initialToolCallId, props, host }) => /* @__PURE__ */ jsx(
4790
+ WidgetSurfacePortal,
4791
+ {
4792
+ anchorElement,
4793
+ initialToolCallId,
4794
+ parkingElement,
4795
+ props,
4796
+ host,
4797
+ surfaceId
4798
+ },
4417
4799
  surfaceId
4418
- },
4419
- surfaceId
4420
- ))
4800
+ )
4801
+ )
4802
+ ] });
4803
+ }
4804
+ function WidgetWorkspaceProvider({
4805
+ workspaceId,
4806
+ children
4807
+ }) {
4808
+ const [value] = useState(() => ({
4809
+ workspaceId,
4810
+ surfaces: createWidgetSurfaceStore({ retainInstances: true }),
4811
+ registry: createAppToolsRegistry({ maxInstances: 64 }),
4812
+ invocations: createAppToolInvocationLog()
4813
+ }));
4814
+ if (value.workspaceId !== workspaceId)
4815
+ throw new Error(
4816
+ "A widget workspace must be remounted when its identity changes"
4817
+ );
4818
+ const cleanupTimer = useRef(null);
4819
+ useEffect(() => {
4820
+ if (cleanupTimer.current !== null) clearTimeout(cleanupTimer.current);
4821
+ cleanupTimer.current = null;
4822
+ value.registry.getState().setEnabled(true);
4823
+ value.invocations.getState().setEnabled(true);
4824
+ value.surfaces.getState().setEnabled(true);
4825
+ return () => {
4826
+ value.registry.getState().setEnabled(false);
4827
+ value.invocations.getState().setEnabled(false);
4828
+ value.surfaces.getState().setEnabled(false);
4829
+ cleanupTimer.current = setTimeout(() => {
4830
+ value.registry.getState().dispose();
4831
+ value.invocations.getState().dispose();
4832
+ value.surfaces.getState().dispose();
4833
+ }, 0);
4834
+ };
4835
+ }, [value]);
4836
+ return /* @__PURE__ */ jsx(WidgetWorkspaceContext.Provider, { value, children });
4837
+ }
4838
+ function useOptionalWidgetWorkspace() {
4839
+ return useContext(WidgetWorkspaceContext);
4840
+ }
4841
+ function useWidgetWorkspace() {
4842
+ const workspace = useOptionalWidgetWorkspace();
4843
+ if (!workspace) throw new Error("WidgetWorkspaceProvider is required");
4844
+ return workspace;
4845
+ }
4846
+ function closeWorkspaceSurface(workspace, surfaceId) {
4847
+ const surface = workspace.surfaces.getState().surfaces.get(surfaceId);
4848
+ if (!surface) return;
4849
+ const toolCallIds = /* @__PURE__ */ new Set([
4850
+ surface.initialToolCallId,
4851
+ surface.latestToolCallId,
4852
+ ...surface.registrations.keys()
4853
+ ]);
4854
+ workspace.surfaces.getState().destroySurface(surfaceId);
4855
+ for (const instance of workspace.registry.getState().instancesByBridgeId.values()) {
4856
+ if (toolCallIds.has(instance.parentToolCallId) && instance.chatSessionId === surface.chatSessionId && instance.serverId === surface.retainedProps.serverId)
4857
+ workspace.registry.getState().unregisterInstance(instance.bridgeId);
4858
+ }
4859
+ }
4860
+ function renderLiveSurface(props) {
4861
+ return /* @__PURE__ */ jsx(MCPAppsRendererSurface, { ...props });
4862
+ }
4863
+ function WidgetWorkspaceSurfaceHost({
4864
+ activeSurfaceId,
4865
+ renderSurface = renderLiveSurface,
4866
+ renderContainer
4867
+ }) {
4868
+ useWidgetWorkspace();
4869
+ const surfaces = useWidgetSurfaceStore((state) => state.surfaces);
4870
+ const refusal = useWidgetSurfaceAdmissionError(
4871
+ activeSurfaceId !== null && !surfaces.has(activeSurfaceId) ? activeSurfaceId : null
4872
+ );
4873
+ return /* @__PURE__ */ jsxs("div", { "data-mcp-app-workspace-surfaces": true, children: [
4874
+ refusal ? /* @__PURE__ */ jsx("p", { role: "alert", "data-mcp-app-workspace-refused": activeSurfaceId, children: refusal.message }) : null,
4875
+ Array.from(surfaces.values()).map((surface) => {
4876
+ const props = {
4877
+ ...surface.retainedProps,
4878
+ persistentSurfaceInitialToolCallId: surface.initialToolCallId,
4879
+ persistentSurfaceId: surface.surfaceId
4880
+ };
4881
+ const content = renderSurface === renderLiveSurface && !surface.host ? /* @__PURE__ */ jsx("p", { role: "status", children: "App host unavailable" }) : renderSurface(props);
4882
+ const children = surface.host ? /* @__PURE__ */ jsx(WidgetHostProvider, { value: surface.host, children: content }) : content;
4883
+ const active = surface.surfaceId === activeSurfaceId;
4884
+ return /* @__PURE__ */ jsx(Fragment$1, { children: renderContainer ? renderContainer({ surface, active, children }) : /* @__PURE__ */ jsx(
4885
+ "div",
4886
+ {
4887
+ "data-mcp-app-workspace-instance": surface.surfaceId,
4888
+ hidden: !active,
4889
+ children
4890
+ }
4891
+ ) }, surface.surfaceId);
4892
+ })
4421
4893
  ] });
4422
4894
  }
4423
4895
 
4424
- export { 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, WidgetHostProvider, WidgetSurfaceHost, WidgetSurfaceHostProvider, __internal, detectUIType, detectUiTypeFromTool, getRenderableSurfaceEntries, getToolInputSignature, getUIResourceUri, readToolResultMeta, readToolResultObject, readToolResultServerId, recordAppToolInvocation, resolveSandboxProxyUrl, useAppToolAttribution, useAppToolAttributionResolver, useAppToolInvocationLog, useAppToolsRegistry, usePersistentWidgetSurfaceHost, useToolInputStreaming, useWidgetHost, useWidgetSurfaceStore };
4896
+ export { 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, getRenderableSurfaceEntries, getToolInputSignature, getUIResourceUri, readToolResultMeta, readToolResultObject, readToolResultServerId, recordAppToolInvocation, resolveSandboxProxyUrl, useAppToolAttribution, useAppToolAttributionResolver, useAppToolInvocationLog, useAppToolInvocationLogApi, useAppToolsRegistry, useAppToolsRegistryApi, useOptionalWidgetWorkspace, usePersistentWidgetSurfaceHost, useToolInputStreaming, useWidgetHost, useWidgetSurfaceAdmissionError, useWidgetSurfaceStore, useWidgetSurfaceStoreApi, useWidgetWorkspace };
4425
4897
  //# sourceMappingURL=index.js.map
4426
4898
  //# sourceMappingURL=index.js.map