@mcpjam/widget-react 0.1.14 → 0.1.16

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, openAIDisplayModes, negotiateResourceDisplayModes, registerHostBridgeHandlers, pickOpenAIDisplayMode, 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,58 @@ 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)
2334
+ const intersection = matrixModes.filter(
2335
+ (mode) => configuredAvailableDisplayModes.includes(mode)
2098
2336
  );
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)
2105
- );
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 openAIRules = host.surface.openAIDisplayModes === true;
2348
+ const openAIRulesRef = useRef(openAIRules);
2349
+ openAIRulesRef.current = openAIRules;
2350
+ const displayModesFor = useCallback(
2351
+ (hostModes, hints, appModes) => {
2352
+ const fixed = fixedDisplayModeRef.current;
2353
+ if (openAIRulesRef.current)
2354
+ return openAIDisplayModes(hostModes, hints, appModes, fixed);
2355
+ return fixed && hostModes.includes(fixed) ? [fixed] : negotiateResourceDisplayModes([...hostModes], hints, appModes);
2356
+ },
2357
+ []
2358
+ );
2359
+ const effectiveAvailableDisplayModes = useMemo(
2360
+ () => displayModesFor(
2361
+ hostAvailableDisplayModes,
2362
+ resourceDisplayHints,
2363
+ appSupportedDisplayModes
2364
+ ),
2365
+ [
2366
+ displayModesFor,
2367
+ fixedDisplayMode,
2368
+ openAIRules,
2369
+ hostAvailableDisplayModes,
2370
+ resourceDisplayHints,
2371
+ appSupportedDisplayModes
2372
+ ]
2373
+ );
2374
+ const advertisedAvailableDisplayModes = effectiveAvailableDisplayModes;
2121
2375
  const playgroundCapabilities = environment.playgroundCapabilities;
2376
+ const configuredCapabilities = draftHostContext?.deviceCapabilities && typeof draftHostContext.deviceCapabilities === "object" && !Array.isArray(draftHostContext.deviceCapabilities) ? draftHostContext.deviceCapabilities : void 0;
2122
2377
  const deviceCapabilities = useMemo(() => {
2123
- const configuredCapabilities = draftHostContext?.deviceCapabilities && typeof draftHostContext.deviceCapabilities === "object" && !Array.isArray(draftHostContext.deviceCapabilities) ? draftHostContext.deviceCapabilities : void 0;
2124
2378
  if (configuredCapabilities) {
2125
2379
  return {
2126
2380
  hover: configuredCapabilities.hover ?? true,
@@ -2128,10 +2382,16 @@ function MCPAppsRendererSurface({
2128
2382
  };
2129
2383
  }
2130
2384
  return isPlaygroundActive ? playgroundCapabilities : { hover: true, touch: false };
2131
- }, [draftHostContext, isPlaygroundActive, playgroundCapabilities]);
2385
+ }, [
2386
+ configuredCapabilities?.hover,
2387
+ configuredCapabilities?.touch,
2388
+ isPlaygroundActive,
2389
+ playgroundCapabilities?.hover,
2390
+ playgroundCapabilities?.touch
2391
+ ]);
2132
2392
  const playgroundSafeAreaInsets = environment.playgroundSafeAreaInsets;
2393
+ const configuredSafeAreaInsets = draftHostContext?.safeAreaInsets && typeof draftHostContext.safeAreaInsets === "object" && !Array.isArray(draftHostContext.safeAreaInsets) ? draftHostContext.safeAreaInsets : void 0;
2133
2394
  const safeAreaInsets = useMemo(() => {
2134
- const configuredSafeAreaInsets = draftHostContext?.safeAreaInsets && typeof draftHostContext.safeAreaInsets === "object" && !Array.isArray(draftHostContext.safeAreaInsets) ? draftHostContext.safeAreaInsets : void 0;
2135
2395
  if (configuredSafeAreaInsets) {
2136
2396
  return {
2137
2397
  top: configuredSafeAreaInsets.top ?? 0,
@@ -2141,7 +2401,17 @@ function MCPAppsRendererSurface({
2141
2401
  };
2142
2402
  }
2143
2403
  return isPlaygroundActive ? playgroundSafeAreaInsets : { top: 0, right: 0, bottom: 0, left: 0 };
2144
- }, [draftHostContext, isPlaygroundActive, playgroundSafeAreaInsets]);
2404
+ }, [
2405
+ configuredSafeAreaInsets?.top,
2406
+ configuredSafeAreaInsets?.right,
2407
+ configuredSafeAreaInsets?.bottom,
2408
+ configuredSafeAreaInsets?.left,
2409
+ isPlaygroundActive,
2410
+ playgroundSafeAreaInsets?.top,
2411
+ playgroundSafeAreaInsets?.right,
2412
+ playgroundSafeAreaInsets?.bottom,
2413
+ playgroundSafeAreaInsets?.left
2414
+ ]);
2145
2415
  const playgroundDeviceType = environment.playgroundDeviceType;
2146
2416
  const isControlled = displayModeProp !== void 0;
2147
2417
  const [internalDisplayMode, setInternalDisplayMode] = useState(
@@ -2202,6 +2472,25 @@ function MCPAppsRendererSurface({
2202
2472
  ]
2203
2473
  );
2204
2474
  const lastForcedDisplayModeRef = useRef(null);
2475
+ const fullscreenPlacement = useContext(WidgetFullscreenPlacementContext);
2476
+ const placedFullscreen = !hostManagedPresentation && effectiveDisplayMode === "fullscreen" && !(isPlaygroundActive && (playgroundDeviceType === "mobile" || playgroundDeviceType === "tablet")) && !!fullscreenPlacement?.rect;
2477
+ const fullscreenPlacementRef = useRef(fullscreenPlacement);
2478
+ fullscreenPlacementRef.current = fullscreenPlacement;
2479
+ const placedExitRef = useRef(() => {
2480
+ });
2481
+ placedExitRef.current = () => {
2482
+ userPreferInlineRef.current = true;
2483
+ setDisplayMode("inline");
2484
+ };
2485
+ const fullscreenLabel = serverName?.trim() || serverId.trim() || "App";
2486
+ useEffect(() => {
2487
+ if (!placedFullscreen) return;
2488
+ fullscreenPlacementRef.current?.onEnter?.({
2489
+ label: fullscreenLabel,
2490
+ exit: () => placedExitRef.current()
2491
+ });
2492
+ return () => fullscreenPlacementRef.current?.onLeave?.();
2493
+ }, [placedFullscreen, fullscreenLabel]);
2205
2494
  useEffect(() => {
2206
2495
  if (requestedDisplayMode === effectiveDisplayMode) {
2207
2496
  lastForcedDisplayModeRef.current = null;
@@ -2216,12 +2505,14 @@ function MCPAppsRendererSurface({
2216
2505
  const [isReady, setIsReady] = useState(false);
2217
2506
  const [reinitCount, setReinitCount] = useState(0);
2218
2507
  const [loadError, setLoadError] = useState(null);
2508
+ useInitialRenderOutcome(isReady, loadError !== null, onInitialRenderOutcome);
2219
2509
  const [firstCspBlock, setFirstCspBlock] = useState(null);
2220
2510
  const [widgetHtml, setWidgetHtml] = useState(null);
2221
2511
  const [openInAppUrlOverride, setOpenInAppUrlOverride] = useState(null);
2222
2512
  const [sandboxProxyReady, setSandboxProxyReady] = useState(false);
2223
2513
  const [viewMount, setViewMount] = useState(null);
2224
2514
  const [bridgeTransportReady, setBridgeTransportReady] = useState(false);
2515
+ const [bridgeGeneration, setBridgeGeneration] = useState(0);
2225
2516
  const explicitOpenInAppBaseUrl = useMemo(
2226
2517
  () => resolveExplicitBaseUrl(widgetHtml, resourceUri),
2227
2518
  [widgetHtml, resourceUri]
@@ -2305,6 +2596,7 @@ function MCPAppsRendererSurface({
2305
2596
  hasRenderedLiveRef.current = false;
2306
2597
  liveRenderIdentityRef.current = null;
2307
2598
  setWidgetHtml(null);
2599
+ setResourceDisplayHints(void 0);
2308
2600
  setBridgeTransportReady(false);
2309
2601
  setLoadedCspMode(null);
2310
2602
  setLoadedInjectOpenAiCompat(null);
@@ -2334,6 +2626,7 @@ function MCPAppsRendererSurface({
2334
2626
  const appToolsListInFlightBridgeIdsRef = useRef(/* @__PURE__ */ new Set());
2335
2627
  const appToolsListRefreshPendingBridgeIdsRef = useRef(/* @__PURE__ */ new Set());
2336
2628
  const [appToolsBridgeIdState, setAppToolsBridgeIdState] = useState(null);
2629
+ const appToolsRegistry = useAppToolsRegistryApi();
2337
2630
  const pendingAppToolCalls = useAppToolsRegistry(
2338
2631
  (s) => appToolsBridgeIdState ? s.pendingControllers.get(appToolsBridgeIdState)?.size ?? 0 : 0
2339
2632
  );
@@ -2347,6 +2640,8 @@ function MCPAppsRendererSurface({
2347
2640
  ]);
2348
2641
  const onSendFollowUpRef = useRef(onSendFollowUp);
2349
2642
  const onCallToolRef = useRef(onCallTool);
2643
+ const onReadResourceV2Ref = useRef(host.services.readResourceV2);
2644
+ const hasResourceReadV2 = Boolean(host.services.readResourceV2);
2350
2645
  const onAppToolInvocationChangeRef = useRef(onAppToolInvocationChange);
2351
2646
  const appToolInvocationSequenceRef = useRef(0);
2352
2647
  const onRequestPipRef = useRef(onRequestPip);
@@ -2477,6 +2772,7 @@ function MCPAppsRendererSurface({
2477
2772
  mimeTypeWarning: warning,
2478
2773
  mimeTypeValid: valid,
2479
2774
  prefersBorder: prefersBorder2,
2775
+ resourceDisplayHints: resourceHints,
2480
2776
  declaredDomain: serverDeclaredDomain,
2481
2777
  viewOriginLabel: serverViewOriginLabel,
2482
2778
  injectedOpenAiCompat: serverInjectedOpenAiCompat,
@@ -2524,6 +2820,19 @@ function MCPAppsRendererSurface({
2524
2820
  setBridgeTransportReady(false);
2525
2821
  hasRenderedLiveRef.current = true;
2526
2822
  liveRenderIdentityRef.current = liveRenderIdentityKey;
2823
+ const allowed = displayModesFor(
2824
+ hostAvailableDisplayModesRef.current,
2825
+ resourceHints
2826
+ );
2827
+ if (allowed.length === 0) {
2828
+ setLoadError("This App has no supported display mode");
2829
+ return false;
2830
+ }
2831
+ setResourceDisplayHints(resourceHints);
2832
+ const initialMode = openAIRulesRef.current ? pickOpenAIDisplayMode(allowed, resourceHints) : resourceHints?.preferredDisplayMode;
2833
+ if (initialMode && allowed.includes(initialMode) && !(openAIRulesRef.current && initialMode === effectiveDisplayModeRef.current)) {
2834
+ setDisplayMode(initialMode);
2835
+ }
2527
2836
  setWidgetHtml(html);
2528
2837
  setWidgetCsp(csp);
2529
2838
  setFirstCspBlock(null);
@@ -2715,7 +3024,7 @@ function MCPAppsRendererSurface({
2715
3024
  appToolsListedBridgeIdsRef.current.add(bridgeId);
2716
3025
  if (!isLive()) return;
2717
3026
  const appVersion = bridge.getAppVersion();
2718
- await useAppToolsRegistry.getState().registerInstance({
3027
+ await appToolsRegistry.getState().registerInstance({
2719
3028
  bridgeId,
2720
3029
  chatSessionId,
2721
3030
  parentToolCallId: toolCallIdRef.current,
@@ -2733,7 +3042,7 @@ function MCPAppsRendererSurface({
2733
3042
  getIframeElement
2734
3043
  });
2735
3044
  if (!isLive()) {
2736
- useAppToolsRegistry.getState().unregisterInstance(bridgeId);
3045
+ appToolsRegistry.getState().unregisterInstance(bridgeId);
2737
3046
  return;
2738
3047
  }
2739
3048
  needsRefresh = appToolsListRefreshPendingBridgeIdsRef.current.has(bridgeId);
@@ -2747,7 +3056,7 @@ function MCPAppsRendererSurface({
2747
3056
  appToolsListInFlightBridgeIdsRef.current.delete(bridgeId);
2748
3057
  }
2749
3058
  },
2750
- [chatSessionId, logWidgetDebug]
3059
+ [appToolsRegistry, chatSessionId, logWidgetDebug]
2751
3060
  );
2752
3061
  const setWidgetDebugInfo = debug.setWidgetDebugInfo;
2753
3062
  const setWidgetGlobals = debug.setWidgetGlobals;
@@ -3010,6 +3319,11 @@ function MCPAppsRendererSurface({
3010
3319
  () => profileSandbox?.browserStorage,
3011
3320
  [activeMcpProfileKey]
3012
3321
  );
3322
+ const sameOriginAppIframe = useMemo(
3323
+ () => profileSandbox?.sameOriginAppIframe,
3324
+ [activeMcpProfileKey]
3325
+ );
3326
+ const viewMountMode = sameOriginAppIframe === false ? "opaque" : host.surface.viewMountMode;
3013
3327
  const cspDirectivesEffective = useMemo(() => {
3014
3328
  if (!cspDirectivesPolicy) return cspDirectivesPolicy;
3015
3329
  if (!host.surface.hostedMode) return cspDirectivesPolicy;
@@ -3289,6 +3603,7 @@ function MCPAppsRendererSurface({
3289
3603
  useLayoutEffect(() => {
3290
3604
  onSendFollowUpRef.current = onSendFollowUp;
3291
3605
  onCallToolRef.current = onCallTool;
3606
+ onReadResourceV2Ref.current = host.services.readResourceV2;
3292
3607
  onAppToolInvocationChangeRef.current = onAppToolInvocationChange;
3293
3608
  onRequestPipRef.current = onRequestPip;
3294
3609
  onExitPipRef.current = onExitPip;
@@ -3309,6 +3624,7 @@ function MCPAppsRendererSurface({
3309
3624
  }, [
3310
3625
  onSendFollowUp,
3311
3626
  onCallTool,
3627
+ host.services.readResourceV2,
3312
3628
  onAppToolInvocationChange,
3313
3629
  onRequestPip,
3314
3630
  onExitPip,
@@ -3348,7 +3664,27 @@ function MCPAppsRendererSurface({
3348
3664
  });
3349
3665
  const declaredAppModes = appCaps?.availableDisplayModes;
3350
3666
  onAppSupportedDisplayModesChangeRef.current?.(declaredAppModes);
3667
+ const negotiated = displayModesFor(
3668
+ hostAvailableDisplayModesRef.current,
3669
+ resourceDisplayHintsRef.current,
3670
+ declaredAppModes
3671
+ );
3672
+ if (negotiated.length === 0) {
3673
+ const fixed = fixedDisplayModeRef.current;
3674
+ setLoadError(
3675
+ 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"
3676
+ );
3677
+ void b.close();
3678
+ return;
3679
+ }
3351
3680
  setAppSupportedDisplayModes(declaredAppModes);
3681
+ if (openAIRulesRef.current && !negotiated.includes(effectiveDisplayModeRef.current)) {
3682
+ const next = pickOpenAIDisplayMode(
3683
+ negotiated,
3684
+ resourceDisplayHintsRef.current
3685
+ );
3686
+ if (next) setDisplayModeRef.current(next);
3687
+ }
3352
3688
  if (wasReady) {
3353
3689
  setReinitCount((c) => c + 1);
3354
3690
  }
@@ -3363,9 +3699,17 @@ function MCPAppsRendererSurface({
3363
3699
  }
3364
3700
  }
3365
3701
  },
3702
+ ...hasOwnedMessage ? {
3703
+ onSendMessage: async (params) => {
3704
+ const send = ownedMessageRef.current;
3705
+ if (!send) throw new Error("App message unavailable");
3706
+ return await send(params);
3707
+ }
3708
+ } : {},
3366
3709
  onSendFollowUp: (text) => {
3367
3710
  onSendFollowUpRef.current?.(text);
3368
3711
  },
3712
+ onOpenAppLink: host.services.openAppLink,
3369
3713
  onOpenLink: (url) => {
3370
3714
  window.open(url, "_blank", "noopener,noreferrer");
3371
3715
  },
@@ -3391,6 +3735,11 @@ function MCPAppsRendererSurface({
3391
3735
  );
3392
3736
  return result.content;
3393
3737
  },
3738
+ onReadResourceV2: hasResourceReadV2 ? (params, extra) => {
3739
+ const read = onReadResourceV2Ref.current;
3740
+ if (!read) throw new Error("Resource executor unavailable");
3741
+ return read(params, extra);
3742
+ } : void 0,
3394
3743
  onListResources: async (params) => {
3395
3744
  return host.services.listResources(
3396
3745
  serverIdRef.current,
@@ -3492,6 +3841,13 @@ function MCPAppsRendererSurface({
3492
3841
  }
3493
3842
  return { mode: actualMode };
3494
3843
  },
3844
+ ...hasOwnedModelContext ? {
3845
+ onUpdateModelContextV2: async (_id, params) => {
3846
+ const update = ownedModelContextRef.current;
3847
+ if (!update) throw new Error("App model context unavailable");
3848
+ return update(params);
3849
+ }
3850
+ } : {},
3495
3851
  onUpdateModelContext: (ctxToolCallId, { content, structuredContent }) => {
3496
3852
  setWidgetModelContextRef.current(ctxToolCallId, {
3497
3853
  content,
@@ -3593,7 +3949,10 @@ function MCPAppsRendererSurface({
3593
3949
  setIsReady,
3594
3950
  logWidgetDebug,
3595
3951
  refreshAppProvidedTools,
3596
- effectiveHostCapabilitiesKey
3952
+ hasResourceReadV2,
3953
+ effectiveHostCapabilitiesKey,
3954
+ hasOwnedModelContext,
3955
+ hasOwnedMessage
3597
3956
  ]
3598
3957
  );
3599
3958
  useEffect(() => {
@@ -3625,19 +3984,20 @@ function MCPAppsRendererSurface({
3625
3984
  hostPolicyApplied: effectiveSandbox.hostPolicyApplied,
3626
3985
  toolState: toolState ?? null
3627
3986
  });
3628
- const bridge = new AppBridge(
3629
- null,
3630
- resolvedBridgeHostInfo,
3631
- {
3632
- ...effectiveHostCapabilities,
3633
- sandbox: {
3634
- csp: effectiveSandbox.csp,
3635
- permissions: effectiveSandbox.permissions
3636
- }
3987
+ const bridge = createHostAppBridge({
3988
+ hostInfo: resolvedBridgeHostInfo,
3989
+ hostCapabilities: effectiveHostCapabilities,
3990
+ sandbox: {
3991
+ csp: effectiveSandbox.csp,
3992
+ permissions: effectiveSandbox.permissions
3637
3993
  },
3638
- { hostContext: hostContextRef.current ?? {} }
3639
- );
3994
+ hostContext: hostContextRef.current ?? {}
3995
+ });
3640
3996
  registerBridgeHandlers(bridge);
3997
+ const releaseExtensions = host.services.configureAppBridge?.(
3998
+ bridge,
3999
+ effectiveHostCapabilities
4000
+ );
3641
4001
  bridgeRef.current = bridge;
3642
4002
  const pendingRpcMethods = /* @__PURE__ */ new Map();
3643
4003
  const transport = new LoggingTransport(
@@ -3691,6 +4051,7 @@ function MCPAppsRendererSurface({
3691
4051
  bridge.connect(transport).then(() => {
3692
4052
  if (!isActive) return;
3693
4053
  setBridgeTransportReady(true);
4054
+ setBridgeGeneration((generation) => generation + 1);
3694
4055
  logWidgetDebug("host-to-ui", "debug/bridge-connect-ready", {
3695
4056
  htmlLength: widgetHtml.length
3696
4057
  });
@@ -3704,12 +4065,17 @@ function MCPAppsRendererSurface({
3704
4065
  });
3705
4066
  return () => {
3706
4067
  isActive = false;
4068
+ try {
4069
+ releaseExtensions?.();
4070
+ } catch {
4071
+ logWidgetDebug("host-to-ui", "debug/extension-cleanup-error", {});
4072
+ }
3707
4073
  logWidgetDebug("host-to-ui", "debug/bridge-connect-cleanup", {
3708
4074
  wasReady: isReadyRef.current
3709
4075
  });
3710
4076
  bridgeRef.current = null;
3711
4077
  if (appToolsBridgeIdRef.current) {
3712
- useAppToolsRegistry.getState().unregisterInstance(appToolsBridgeIdRef.current);
4078
+ appToolsRegistry.getState().unregisterInstance(appToolsBridgeIdRef.current);
3713
4079
  appToolsListedBridgeIdsRef.current.delete(appToolsBridgeIdRef.current);
3714
4080
  appToolsListInFlightBridgeIdsRef.current.delete(
3715
4081
  appToolsBridgeIdRef.current
@@ -3747,7 +4113,8 @@ function MCPAppsRendererSurface({
3747
4113
  // Bridge must rebuild when the host identity advertised in
3748
4114
  // ui/initialize changes — switching to a template that overrides
3749
4115
  // hostInfo (e.g. ChatGPT) is observable to the View.
3750
- resolvedBridgeHostInfoKey
4116
+ resolvedBridgeHostInfoKey,
4117
+ host.services.configureAppBridge
3751
4118
  ]);
3752
4119
  useEffect(() => {
3753
4120
  const bridge = bridgeRef.current;
@@ -3849,7 +4216,7 @@ function MCPAppsRendererSurface({
3849
4216
  }
3850
4217
  if (data.type === "mcpjam:view-mode") {
3851
4218
  const mode = data.mode;
3852
- if (mode === "url" || mode === "srcdoc" || mode === "srcdoc-fallback") {
4219
+ if (mode === "url" || mode === "srcdoc" || mode === "srcdoc-fallback" || mode === "opaque") {
3853
4220
  const url = typeof data.url === "string" ? data.url : "";
3854
4221
  const mountId = normalizeCspMountId(data.mountId);
3855
4222
  setViewMount({ mountId, mode, url });
@@ -3861,6 +4228,13 @@ function MCPAppsRendererSurface({
3861
4228
  }
3862
4229
  return;
3863
4230
  }
4231
+ if (data.type === "mcpjam:view-channel-closed") {
4232
+ logWidgetDebug("ui-to-host", "debug/view-channel-closed", {
4233
+ mountId: normalizeCspMountId(data.mountId),
4234
+ reason: typeof data.reason === "string" ? data.reason : void 0
4235
+ });
4236
+ return;
4237
+ }
3864
4238
  if (data.type === "recorder:step") {
3865
4239
  recorderDebug2("step from sandbox", {
3866
4240
  toolName,
@@ -4070,10 +4444,15 @@ function MCPAppsRendererSurface({
4070
4444
  const isContainedFullscreenMode = isPlaygroundActive && (playgroundDeviceType === "mobile" || playgroundDeviceType === "tablet");
4071
4445
  const showOpenInAppButton = isFullscreen && !!openInAppUrl && !isMobilePlaygroundMode;
4072
4446
  const containerClassName = (() => {
4447
+ if (hostManagedPresentation)
4448
+ return "relative h-full min-h-0 w-full bg-background flex flex-col";
4073
4449
  if (isFullscreen) {
4074
4450
  if (isContainedFullscreenMode) {
4075
4451
  return "absolute inset-0 z-10 w-full h-full bg-background flex flex-col";
4076
4452
  }
4453
+ if (placedFullscreen) {
4454
+ return "fixed z-50 bg-background flex flex-col";
4455
+ }
4077
4456
  return "fixed inset-0 z-40 w-full h-full bg-background flex flex-col";
4078
4457
  }
4079
4458
  if (isPip) {
@@ -4097,7 +4476,7 @@ function MCPAppsRendererSurface({
4097
4476
  })();
4098
4477
  const canTransitionHeight = !isFullscreen && effectiveDisplayModeRef.current === effectiveDisplayMode;
4099
4478
  const iframeStyle = {
4100
- height: isFullscreen ? "100%" : isPip ? PIP_MAX_HEIGHT : lastInlineHeightRef.current,
4479
+ height: hostManagedPresentation || isFullscreen ? "100%" : isPip ? PIP_MAX_HEIGHT : lastInlineHeightRef.current,
4101
4480
  width: "100%",
4102
4481
  maxWidth: "100%",
4103
4482
  backgroundColor: !isFullscreen && matrixGatedPrefersBorder ? mergedStyleVariables["--color-background-primary"] : hostChatBackground ?? "transparent",
@@ -4109,7 +4488,7 @@ function MCPAppsRendererSurface({
4109
4488
  // Keep iframe in the layout but invisible while not ready
4110
4489
  ...!showWidget ? { position: "absolute", pointerEvents: "none" } : {}
4111
4490
  };
4112
- const showHostChrome = !isFullscreen && matrixGatedPrefersBorder && !showCspBlockedNotice;
4491
+ const showHostChrome = !hostManagedPresentation && !isFullscreen && matrixGatedPrefersBorder && !showCspBlockedNotice;
4113
4492
  const hostChromeStyle = showHostChrome ? {
4114
4493
  backgroundColor: mergedStyleVariables["--color-background-primary"]
4115
4494
  } : void 0;
@@ -4129,6 +4508,7 @@ function MCPAppsRendererSurface({
4129
4508
  {
4130
4509
  ref: sandboxRef,
4131
4510
  html: bridgeTransportReady ? widgetHtml : null,
4511
+ reloadKey: bridgeGeneration,
4132
4512
  sandbox: "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",
4133
4513
  csp: effectiveSandbox.csp,
4134
4514
  permissions: effectiveSandbox.permissions,
@@ -4152,7 +4532,7 @@ function MCPAppsRendererSurface({
4152
4532
  title: `MCP App: ${toolName}`,
4153
4533
  hostedMode: host.surface.hostedMode,
4154
4534
  sandboxOrigin: host.surface.sandboxOrigin,
4155
- mountMode: host.surface.viewMountMode,
4535
+ mountMode: viewMountMode,
4156
4536
  viewOriginLabel,
4157
4537
  viewSubdomainsEnabled: host.surface.viewSubdomainsEnabled,
4158
4538
  className: `bg-transparent overflow-hidden ${isFullscreen ? "flex-1 border-0 rounded-none" : `rounded-md ${matrixGatedPrefersBorder ? "border border-border/40" : ""}`}`,
@@ -4163,10 +4543,18 @@ function MCPAppsRendererSurface({
4163
4543
  "div",
4164
4544
  {
4165
4545
  className: containerClassName,
4546
+ style: placedFullscreen && fullscreenPlacement?.rect ? {
4547
+ inset: "auto",
4548
+ top: fullscreenPlacement.rect.top,
4549
+ left: fullscreenPlacement.rect.left,
4550
+ width: fullscreenPlacement.rect.width,
4551
+ height: fullscreenPlacement.rect.height
4552
+ } : void 0,
4553
+ "data-mcp-app-fullscreen-placed": placedFullscreen || void 0,
4166
4554
  "data-mcp-app-persistent-initial-tool-call-id": persistentSurfaceInitialToolCallId,
4167
4555
  "data-mcp-app-persistent-surface-id": persistentSurfaceId,
4168
4556
  children: [
4169
- (isFullscreen && isContainedFullscreenMode || isPip && isMobilePlaygroundMode) && /* @__PURE__ */ jsxs(Fragment, { children: [
4557
+ !hostManagedPresentation && (isFullscreen && isContainedFullscreenMode || isPip && isMobilePlaygroundMode) && /* @__PURE__ */ jsxs(Fragment, { children: [
4170
4558
  /* @__PURE__ */ jsx(
4171
4559
  "button",
4172
4560
  {
@@ -4193,7 +4581,7 @@ function MCPAppsRendererSurface({
4193
4581
  }
4194
4582
  )
4195
4583
  ] }),
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: [
4584
+ !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
4585
  /* @__PURE__ */ jsx("div", {}),
4198
4586
  /* @__PURE__ */ jsx("div", { className: "font-medium text-sm text-muted-foreground min-w-0 max-w-[40vw] truncate", children: openInAppLabel }),
4199
4587
  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-2 min-w-0", children: [
@@ -4222,15 +4610,16 @@ function MCPAppsRendererSurface({
4222
4610
  if (ownsPipDisplayMode) {
4223
4611
  onExitPip?.(pipWidgetId ?? displayWidgetId);
4224
4612
  }
4613
+ if (placedFullscreen) fullscreenPlacement?.onExit?.();
4225
4614
  },
4226
- className: "p-2 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors",
4615
+ 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
4616
  "aria-label": "Exit fullscreen",
4228
- children: /* @__PURE__ */ jsx(X, { className: "w-5 h-5" })
4617
+ children: placedFullscreen && fullscreenPlacement?.exitLabel ? fullscreenPlacement.exitLabel : /* @__PURE__ */ jsx(X, { className: "w-5 h-5" })
4229
4618
  }
4230
4619
  )
4231
4620
  ] })
4232
4621
  ] }),
4233
- isPip && !isMobilePlaygroundMode && /* @__PURE__ */ jsx(
4622
+ !hostManagedPresentation && isPip && !isMobilePlaygroundMode && /* @__PURE__ */ jsx(
4234
4623
  "button",
4235
4624
  {
4236
4625
  onClick: () => {
@@ -4294,6 +4683,7 @@ function MCPAppsRendererSurface({
4294
4683
  widgetCspSubtypePolicy: effectiveSandbox.cspSubtypePolicy,
4295
4684
  widgetClientContext: cspClientContext,
4296
4685
  widgetBrowserStorage: effectiveSandbox.browserStorage,
4686
+ widgetMountMode: viewMountMode,
4297
4687
  widgetToolResult: earlyEffectiveMcpAppsCapabilities.toolResult,
4298
4688
  hostContextRef,
4299
4689
  serverId,
@@ -4348,7 +4738,8 @@ function WidgetSurfacePortal({
4348
4738
  initialToolCallId,
4349
4739
  parkingElement,
4350
4740
  props,
4351
- surfaceId
4741
+ surfaceId,
4742
+ host
4352
4743
  }) {
4353
4744
  const [container] = useState(() => createSurfaceContainer(surfaceId));
4354
4745
  const targetElement = anchorElement ?? parkingElement;
@@ -4363,15 +4754,16 @@ function WidgetSurfacePortal({
4363
4754
  container.remove();
4364
4755
  };
4365
4756
  }, [container]);
4757
+ const renderer = /* @__PURE__ */ jsx(
4758
+ MCPAppsRendererSurface,
4759
+ {
4760
+ ...props,
4761
+ persistentSurfaceInitialToolCallId: initialToolCallId,
4762
+ persistentSurfaceId: surfaceId
4763
+ }
4764
+ );
4366
4765
  return createPortal(
4367
- /* @__PURE__ */ jsx(
4368
- MCPAppsRendererSurface,
4369
- {
4370
- ...props,
4371
- persistentSurfaceInitialToolCallId: initialToolCallId,
4372
- persistentSurfaceId: surfaceId
4373
- }
4374
- ),
4766
+ host ? /* @__PURE__ */ jsx(WidgetHostProvider, { value: host, children: renderer }) : renderer,
4375
4767
  container,
4376
4768
  surfaceId
4377
4769
  );
@@ -4379,6 +4771,8 @@ function WidgetSurfacePortal({
4379
4771
  function WidgetSurfaceHost({
4380
4772
  chatSessionId
4381
4773
  }) {
4774
+ const workspace = useContext(WidgetWorkspaceContext);
4775
+ const surfaceStore = useWidgetSurfaceStoreApi();
4382
4776
  const [parkingElement, setParkingElement] = useState(
4383
4777
  null
4384
4778
  );
@@ -4389,9 +4783,10 @@ function WidgetSurfaceHost({
4389
4783
  );
4390
4784
  useEffect(() => {
4391
4785
  return () => {
4392
- useWidgetSurfaceStore.getState().clearChatSession(chatSessionId);
4786
+ surfaceStore.getState().clearChatSession(chatSessionId);
4393
4787
  };
4394
- }, [chatSessionId]);
4788
+ }, [chatSessionId, surfaceStore]);
4789
+ if (workspace) return null;
4395
4790
  return /* @__PURE__ */ jsxs(Fragment, { children: [
4396
4791
  /* @__PURE__ */ jsx(
4397
4792
  "div",
@@ -4407,20 +4802,114 @@ function WidgetSurfaceHost({
4407
4802
  }
4408
4803
  }
4409
4804
  ),
4410
- entries.map(({ surfaceId, anchorElement, initialToolCallId, props }) => /* @__PURE__ */ jsx(
4411
- WidgetSurfacePortal,
4412
- {
4413
- anchorElement,
4414
- initialToolCallId,
4415
- parkingElement,
4416
- props,
4805
+ entries.map(
4806
+ ({ surfaceId, anchorElement, initialToolCallId, props, host }) => /* @__PURE__ */ jsx(
4807
+ WidgetSurfacePortal,
4808
+ {
4809
+ anchorElement,
4810
+ initialToolCallId,
4811
+ parkingElement,
4812
+ props,
4813
+ host,
4814
+ surfaceId
4815
+ },
4417
4816
  surfaceId
4418
- },
4419
- surfaceId
4420
- ))
4817
+ )
4818
+ )
4819
+ ] });
4820
+ }
4821
+ function WidgetWorkspaceProvider({
4822
+ workspaceId,
4823
+ children
4824
+ }) {
4825
+ const [value] = useState(() => ({
4826
+ workspaceId,
4827
+ surfaces: createWidgetSurfaceStore({ retainInstances: true }),
4828
+ registry: createAppToolsRegistry({ maxInstances: 64 }),
4829
+ invocations: createAppToolInvocationLog()
4830
+ }));
4831
+ if (value.workspaceId !== workspaceId)
4832
+ throw new Error(
4833
+ "A widget workspace must be remounted when its identity changes"
4834
+ );
4835
+ const cleanupTimer = useRef(null);
4836
+ useEffect(() => {
4837
+ if (cleanupTimer.current !== null) clearTimeout(cleanupTimer.current);
4838
+ cleanupTimer.current = null;
4839
+ value.registry.getState().setEnabled(true);
4840
+ value.invocations.getState().setEnabled(true);
4841
+ value.surfaces.getState().setEnabled(true);
4842
+ return () => {
4843
+ value.registry.getState().setEnabled(false);
4844
+ value.invocations.getState().setEnabled(false);
4845
+ value.surfaces.getState().setEnabled(false);
4846
+ cleanupTimer.current = setTimeout(() => {
4847
+ value.registry.getState().dispose();
4848
+ value.invocations.getState().dispose();
4849
+ value.surfaces.getState().dispose();
4850
+ }, 0);
4851
+ };
4852
+ }, [value]);
4853
+ return /* @__PURE__ */ jsx(WidgetWorkspaceContext.Provider, { value, children });
4854
+ }
4855
+ function useOptionalWidgetWorkspace() {
4856
+ return useContext(WidgetWorkspaceContext);
4857
+ }
4858
+ function useWidgetWorkspace() {
4859
+ const workspace = useOptionalWidgetWorkspace();
4860
+ if (!workspace) throw new Error("WidgetWorkspaceProvider is required");
4861
+ return workspace;
4862
+ }
4863
+ function closeWorkspaceSurface(workspace, surfaceId) {
4864
+ const surface = workspace.surfaces.getState().surfaces.get(surfaceId);
4865
+ if (!surface) return;
4866
+ const toolCallIds = /* @__PURE__ */ new Set([
4867
+ surface.initialToolCallId,
4868
+ surface.latestToolCallId,
4869
+ ...surface.registrations.keys()
4870
+ ]);
4871
+ workspace.surfaces.getState().destroySurface(surfaceId);
4872
+ for (const instance of workspace.registry.getState().instancesByBridgeId.values()) {
4873
+ if (toolCallIds.has(instance.parentToolCallId) && instance.chatSessionId === surface.chatSessionId && instance.serverId === surface.retainedProps.serverId)
4874
+ workspace.registry.getState().unregisterInstance(instance.bridgeId);
4875
+ }
4876
+ }
4877
+ function renderLiveSurface(props) {
4878
+ return /* @__PURE__ */ jsx(MCPAppsRendererSurface, { ...props });
4879
+ }
4880
+ function WidgetWorkspaceSurfaceHost({
4881
+ activeSurfaceId,
4882
+ renderSurface = renderLiveSurface,
4883
+ renderContainer
4884
+ }) {
4885
+ useWidgetWorkspace();
4886
+ const surfaces = useWidgetSurfaceStore((state) => state.surfaces);
4887
+ const refusal = useWidgetSurfaceAdmissionError(
4888
+ activeSurfaceId !== null && !surfaces.has(activeSurfaceId) ? activeSurfaceId : null
4889
+ );
4890
+ return /* @__PURE__ */ jsxs("div", { "data-mcp-app-workspace-surfaces": true, children: [
4891
+ refusal ? /* @__PURE__ */ jsx("p", { role: "alert", "data-mcp-app-workspace-refused": activeSurfaceId, children: refusal.message }) : null,
4892
+ Array.from(surfaces.values()).map((surface) => {
4893
+ const props = {
4894
+ ...surface.retainedProps,
4895
+ persistentSurfaceInitialToolCallId: surface.initialToolCallId,
4896
+ persistentSurfaceId: surface.surfaceId
4897
+ };
4898
+ const content = renderSurface === renderLiveSurface && !surface.host ? /* @__PURE__ */ jsx("p", { role: "status", children: "App host unavailable" }) : renderSurface(props);
4899
+ const children = surface.host ? /* @__PURE__ */ jsx(WidgetHostProvider, { value: surface.host, children: content }) : content;
4900
+ const active = surface.surfaceId === activeSurfaceId;
4901
+ return /* @__PURE__ */ jsx(Fragment$1, { children: renderContainer ? renderContainer({ surface, active, children }) : /* @__PURE__ */ jsx(
4902
+ "div",
4903
+ {
4904
+ "data-mcp-app-workspace-instance": surface.surfaceId,
4905
+ hidden: !active,
4906
+ children
4907
+ }
4908
+ ) }, surface.surfaceId);
4909
+ })
4421
4910
  ] });
4422
4911
  }
4423
4912
 
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 };
4913
+ 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
4914
  //# sourceMappingURL=index.js.map
4426
4915
  //# sourceMappingURL=index.js.map