@mcpjam/widget-react 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,3883 @@
1
+ import { createContext, forwardRef, useRef, useState, useMemo, useImperativeHandle, useCallback, useEffect, useContext, useLayoutEffect } from 'react';
2
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
3
+ import { isUIResource } from '@mcp-ui/client';
4
+ import { getToolUiResourceUri, AppBridge, PostMessageTransport } from '@modelcontextprotocol/ext-apps/app-bridge';
5
+ import { buildOuterAllowAttribute, buildOuterSandboxAttribute, stableStringifyJson, registerHostBridgeHandlers, LoggingTransport, extractMethod } from '@mcpjam/sdk/widget-runtime';
6
+ export { getToolVisibility, isVisibleToAppOnly, isVisibleToModelOnly } from '@mcpjam/sdk/widget-runtime';
7
+ import { create } from 'zustand';
8
+ import { useShallow } from 'zustand/react/shallow';
9
+ import { X, ExternalLink, Loader2 } from 'lucide-react';
10
+ import { resolveSandboxPermissions, resolveSandboxCsp } from '@mcpjam/sdk/browser';
11
+ import { createPortal } from 'react-dom';
12
+
13
+ // src/widget-host-context.tsx
14
+ var WidgetHostContext = createContext(null);
15
+ function WidgetHostProvider({
16
+ value,
17
+ children
18
+ }) {
19
+ return /* @__PURE__ */ jsx(WidgetHostContext.Provider, { value, children });
20
+ }
21
+ function useWidgetHost() {
22
+ const host = useContext(WidgetHostContext);
23
+ if (host === null) {
24
+ throw new Error(
25
+ "useWidgetHost must be used within a <WidgetHostProvider>. The inspector supplies the concrete host via its use-widget-host adapter."
26
+ );
27
+ }
28
+ return host;
29
+ }
30
+ var UIType = /* @__PURE__ */ ((UIType2) => {
31
+ UIType2["MCP_APPS"] = "mcp-apps";
32
+ UIType2["OPENAI_SDK"] = "openai-sdk";
33
+ UIType2["OPENAI_SDK_AND_MCP_APPS"] = "openai-sdk-and-mcp-apps";
34
+ UIType2["MCP_UI"] = "mcp-ui";
35
+ return UIType2;
36
+ })(UIType || {});
37
+ function detectUiTypeFromTool(tool) {
38
+ const toolMeta = tool._meta;
39
+ if (!toolMeta) return null;
40
+ return detectUIType(toolMeta, void 0);
41
+ }
42
+ function detectUIType(toolMeta, toolResult) {
43
+ if (toolMeta?.["openai/outputTemplate"] && getToolUiResourceUri({ _meta: toolMeta })) {
44
+ return "openai-sdk-and-mcp-apps" /* OPENAI_SDK_AND_MCP_APPS */;
45
+ }
46
+ if (toolMeta?.["openai/outputTemplate"]) {
47
+ return "openai-sdk" /* OPENAI_SDK */;
48
+ }
49
+ if (getToolUiResourceUri({ _meta: toolMeta })) {
50
+ return "mcp-apps" /* MCP_APPS */;
51
+ }
52
+ const directResource = toolResult?.resource;
53
+ if (directResource?.uri?.startsWith("ui://")) {
54
+ return "mcp-ui" /* MCP_UI */;
55
+ }
56
+ const content = toolResult?.content;
57
+ if (Array.isArray(content)) {
58
+ for (const item of content) {
59
+ if (isUIResource(item)) {
60
+ return "mcp-ui" /* MCP_UI */;
61
+ }
62
+ }
63
+ }
64
+ return null;
65
+ }
66
+ function getUIResourceUri(uiType, toolMeta) {
67
+ switch (uiType) {
68
+ case "mcp-apps" /* MCP_APPS */:
69
+ case "openai-sdk-and-mcp-apps" /* OPENAI_SDK_AND_MCP_APPS */:
70
+ return getToolUiResourceUri({ _meta: toolMeta }) ?? null;
71
+ case "openai-sdk" /* OPENAI_SDK */:
72
+ return toolMeta?.["openai/outputTemplate"] ?? null;
73
+ default:
74
+ return null;
75
+ }
76
+ }
77
+
78
+ // src/tool-result-utils.ts
79
+ function isRecord(value) {
80
+ return !!value && typeof value === "object" && !Array.isArray(value);
81
+ }
82
+ function readToolResultObject(result) {
83
+ if (!isRecord(result)) return void 0;
84
+ return result;
85
+ }
86
+ function readToolResultMeta(result) {
87
+ if (!isRecord(result)) return void 0;
88
+ if (isRecord(result._meta)) {
89
+ return result._meta;
90
+ }
91
+ if (isRecord(result.value) && isRecord(result.value._meta)) {
92
+ return result.value._meta;
93
+ }
94
+ return void 0;
95
+ }
96
+ function readToolResultServerId(result) {
97
+ if (!isRecord(result)) return void 0;
98
+ if (typeof result._serverId === "string") {
99
+ return result._serverId;
100
+ }
101
+ if (isRecord(result.value) && typeof result.value._serverId === "string") {
102
+ return result.value._serverId;
103
+ }
104
+ const meta = readToolResultMeta(result);
105
+ return typeof meta?._serverId === "string" ? meta._serverId : void 0;
106
+ }
107
+ var MAX_SNAPSHOT_ENTRIES = 64;
108
+ var MAX_DESCRIPTION_CHARS = 512;
109
+ var MAX_INPUT_SCHEMA_BYTES = 8 * 1024;
110
+ var ALIAS_REGEX = /^app_[a-z0-9]{8}$/i;
111
+ async function generateAlias(chatSessionId, serverId, parentToolCallId, surface, rawName, salt = 0) {
112
+ const preimage = `${chatSessionId ?? ""}\0${serverId}\0${parentToolCallId}\0${surface}\0${rawName}\0${salt}`;
113
+ const bytes = new TextEncoder().encode(preimage);
114
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
115
+ const hex = Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
116
+ return `app_${hex.slice(0, 8)}`;
117
+ }
118
+ function isReadOnly(tool) {
119
+ return tool.annotations?.readOnlyHint === true;
120
+ }
121
+ function getActiveParentKey(parentToolCallId, chatSessionId) {
122
+ return chatSessionId ? `${chatSessionId}\0${parentToolCallId}` : parentToolCallId;
123
+ }
124
+ function isSameAppSlot(a, b) {
125
+ return a.parentToolCallId === b.parentToolCallId && a.surface === b.surface && a.chatSessionId === b.chatSessionId;
126
+ }
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
+ }
143
+ }
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)
150
+ );
151
+ for (const tool of inst.tools) {
152
+ let salt = 0;
153
+ let alias = await generateAlias(
154
+ inst.chatSessionId,
155
+ inst.serverId,
156
+ inst.parentToolCallId,
157
+ inst.surface,
158
+ tool.name,
159
+ salt
160
+ );
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
+ );
171
+ }
172
+ existing.add(alias);
173
+ aliasesForInst.push({
174
+ alias,
175
+ bridgeId: inst.bridgeId,
176
+ rawName: tool.name,
177
+ readOnly: isReadOnly(tool)
178
+ });
179
+ }
180
+ 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
+ }
188
+ }
189
+ }
190
+ set((s) => {
191
+ const instancesByBridgeId = new Map(s.instancesByBridgeId);
192
+ 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
+ }
201
+ }
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
207
+ );
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
+ });
222
+ },
223
+ unregisterInstance: (bridgeId) => {
224
+ const pending = get().pendingControllers.get(bridgeId);
225
+ if (pending) {
226
+ for (const controller of pending) {
227
+ try {
228
+ controller.abort();
229
+ } catch {
230
+ }
231
+ }
232
+ }
233
+ set((s) => {
234
+ const inst = s.instancesByBridgeId.get(bridgeId);
235
+ if (!inst) return {};
236
+ const instancesByBridgeId = new Map(s.instancesByBridgeId);
237
+ instancesByBridgeId.delete(bridgeId);
238
+ const aliases = new Map(s.aliases);
239
+ for (const [alias, a] of s.aliases) {
240
+ if (a.bridgeId === bridgeId) aliases.delete(alias);
241
+ }
242
+ const activeBridgeByParent = new Map(s.activeBridgeByParent);
243
+ const activeParentKey = getActiveParentKey(
244
+ inst.parentToolCallId,
245
+ inst.chatSessionId
246
+ );
247
+ if (activeBridgeByParent.get(activeParentKey) === bridgeId) {
248
+ let fallback;
249
+ for (const other of instancesByBridgeId.values()) {
250
+ if (other.parentToolCallId === inst.parentToolCallId && other.chatSessionId === inst.chatSessionId) {
251
+ fallback = other.bridgeId;
252
+ break;
253
+ }
254
+ }
255
+ if (fallback) {
256
+ activeBridgeByParent.set(activeParentKey, fallback);
257
+ } else {
258
+ activeBridgeByParent.delete(activeParentKey);
259
+ }
260
+ }
261
+ const pendingControllers = new Map(s.pendingControllers);
262
+ pendingControllers.delete(bridgeId);
263
+ return {
264
+ instancesByBridgeId,
265
+ aliases,
266
+ activeBridgeByParent,
267
+ pendingControllers
268
+ };
269
+ });
270
+ },
271
+ registerPendingCall: (bridgeId, controller) => {
272
+ set((s) => {
273
+ const pendingControllers = new Map(s.pendingControllers);
274
+ const next = new Set(pendingControllers.get(bridgeId));
275
+ next.add(controller);
276
+ pendingControllers.set(bridgeId, next);
277
+ return { pendingControllers };
278
+ });
279
+ },
280
+ unregisterPendingCall: (bridgeId, controller) => {
281
+ set((s) => {
282
+ const existing = s.pendingControllers.get(bridgeId);
283
+ if (!existing || !existing.has(controller)) return {};
284
+ const pendingControllers = new Map(s.pendingControllers);
285
+ if (existing.size === 1) {
286
+ pendingControllers.delete(bridgeId);
287
+ } else {
288
+ const next = new Set(existing);
289
+ next.delete(controller);
290
+ pendingControllers.set(bridgeId, next);
291
+ }
292
+ return { pendingControllers };
293
+ });
294
+ },
295
+ pushActive: (parentToolCallId, bridgeId, chatSessionId) => {
296
+ set((s) => {
297
+ const next = new Map(s.activeBridgeByParent);
298
+ next.set(getActiveParentKey(parentToolCallId, chatSessionId), bridgeId);
299
+ return { activeBridgeByParent: next };
300
+ });
301
+ },
302
+ popActive: (parentToolCallId, bridgeId, chatSessionId) => {
303
+ set((s) => {
304
+ const activeParentKey = getActiveParentKey(
305
+ parentToolCallId,
306
+ chatSessionId
307
+ );
308
+ const current = s.activeBridgeByParent.get(activeParentKey);
309
+ if (current !== bridgeId) return {};
310
+ const next = new Map(s.activeBridgeByParent);
311
+ let fallback;
312
+ for (const inst of s.instancesByBridgeId.values()) {
313
+ if (inst.parentToolCallId === parentToolCallId && inst.chatSessionId === chatSessionId && inst.bridgeId !== bridgeId) {
314
+ fallback = inst.bridgeId;
315
+ break;
316
+ }
317
+ }
318
+ if (fallback) next.set(activeParentKey, fallback);
319
+ else next.delete(activeParentKey);
320
+ return { activeBridgeByParent: next };
321
+ });
322
+ },
323
+ snapshotForChatBody: (chatSessionId) => {
324
+ const { instancesByBridgeId, aliases, activeBridgeByParent } = get();
325
+ const out = [];
326
+ let dropped = 0;
327
+ for (const [alias, a] of aliases) {
328
+ if (out.length >= MAX_SNAPSHOT_ENTRIES) {
329
+ dropped += 1;
330
+ continue;
331
+ }
332
+ if (!ALIAS_REGEX.test(alias)) continue;
333
+ const inst = instancesByBridgeId.get(a.bridgeId);
334
+ if (!inst) continue;
335
+ if (chatSessionId && inst.chatSessionId !== chatSessionId) continue;
336
+ if (activeBridgeByParent.get(
337
+ getActiveParentKey(inst.parentToolCallId, inst.chatSessionId)
338
+ ) !== inst.bridgeId) {
339
+ continue;
340
+ }
341
+ const tool = inst.tools.find((t) => t.name === a.rawName);
342
+ if (!tool) continue;
343
+ let inputSchema = tool.inputSchema;
344
+ if (inputSchema) {
345
+ let size = 0;
346
+ try {
347
+ size = new TextEncoder().encode(JSON.stringify(inputSchema)).length;
348
+ } catch {
349
+ continue;
350
+ }
351
+ if (size > MAX_INPUT_SCHEMA_BYTES) continue;
352
+ }
353
+ const description = tool.description ? tool.description.slice(0, MAX_DESCRIPTION_CHARS) : void 0;
354
+ out.push({
355
+ alias,
356
+ appName: inst.appName,
357
+ appVersion: inst.appVersion,
358
+ serverId: inst.serverId,
359
+ parentToolCallId: inst.parentToolCallId,
360
+ rawName: a.rawName,
361
+ description,
362
+ inputSchema,
363
+ readOnly: a.readOnly
364
+ });
365
+ }
366
+ if (dropped > 0) {
367
+ console.warn(
368
+ `[app-tools] snapshot capped at ${MAX_SNAPSHOT_ENTRIES} entries; dropped ${dropped}.`
369
+ );
370
+ }
371
+ const groupCounts = /* @__PURE__ */ new Map();
372
+ for (const entry of out) {
373
+ const key = `${entry.appName}\0${entry.rawName}`;
374
+ groupCounts.set(key, (groupCounts.get(key) ?? 0) + 1);
375
+ }
376
+ const groupIndex = /* @__PURE__ */ new Map();
377
+ for (const entry of out) {
378
+ const key = `${entry.appName}\0${entry.rawName}`;
379
+ const total = groupCounts.get(key) ?? 1;
380
+ if (total <= 1) continue;
381
+ const n = (groupIndex.get(key) ?? 0) + 1;
382
+ groupIndex.set(key, n);
383
+ const hint = ` (from tool call ${entry.parentToolCallId}; instance ${n} of ${total})`;
384
+ const base = entry.description ?? "";
385
+ entry.description = (base + hint).slice(0, MAX_DESCRIPTION_CHARS);
386
+ }
387
+ return out;
388
+ },
389
+ resolve: (alias, chatSessionId) => {
390
+ const a = get().aliases.get(alias);
391
+ if (!a) return null;
392
+ const inst = get().instancesByBridgeId.get(a.bridgeId);
393
+ if (!inst) return null;
394
+ if (chatSessionId && inst.chatSessionId !== chatSessionId) return null;
395
+ if (get().activeBridgeByParent.get(
396
+ getActiveParentKey(inst.parentToolCallId, inst.chatSessionId)
397
+ ) !== inst.bridgeId) {
398
+ return null;
399
+ }
400
+ return {
401
+ bridge: inst.bridge,
402
+ rawName: a.rawName,
403
+ readOnly: a.readOnly,
404
+ instance: inst
405
+ };
406
+ }
407
+ })
408
+ );
409
+ var MAX_INVOCATION_RECORDS = 200;
410
+ var useAppToolInvocationLog = create(
411
+ (set) => ({
412
+ 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
+ })
422
+ );
423
+ function recordAppToolInvocation(args, addTrafficLog) {
424
+ useAppToolInvocationLog.getState().append({
425
+ ...args,
426
+ invokedAtMs: Date.now()
427
+ });
428
+ if (!addTrafficLog) return;
429
+ try {
430
+ addTrafficLog({
431
+ widgetId: args.parentToolCallId,
432
+ serverId: args.serverId,
433
+ direction: "host-to-ui",
434
+ protocol: "mcp-apps",
435
+ method: "tools/call",
436
+ message: {
437
+ alias: args.alias,
438
+ toolName: args.rawName,
439
+ appName: args.appName,
440
+ arguments: args.input,
441
+ result: {
442
+ content: args.raw.content,
443
+ ...args.raw.isError ? { isError: true } : {}
444
+ }
445
+ }
446
+ });
447
+ } catch {
448
+ }
449
+ }
450
+ function useAppToolAttributionResolver(chatSessionId) {
451
+ const registrySnapshot = useAppToolsRegistry(
452
+ useShallow((s) => ({
453
+ activeBridgeByParent: s.activeBridgeByParent,
454
+ aliases: s.aliases,
455
+ instancesByBridgeId: s.instancesByBridgeId
456
+ }))
457
+ );
458
+ const resolve = useAppToolsRegistry((s) => s.resolve);
459
+ const invocationRecords = useAppToolInvocationLog((s) => s.records);
460
+ return useCallback(
461
+ (label) => {
462
+ if (!ALIAS_REGEX.test(label)) return null;
463
+ const resolved = resolve(label, chatSessionId);
464
+ if (resolved) {
465
+ return {
466
+ rawName: resolved.rawName,
467
+ appName: resolved.instance.appName
468
+ };
469
+ }
470
+ for (let i = invocationRecords.length - 1; i >= 0; i -= 1) {
471
+ const record = invocationRecords[i];
472
+ if (record.alias === label) {
473
+ return { rawName: record.rawName, appName: record.appName };
474
+ }
475
+ }
476
+ return null;
477
+ },
478
+ [chatSessionId, invocationRecords, registrySnapshot, resolve]
479
+ );
480
+ }
481
+ function useAppToolAttribution(label, chatSessionId) {
482
+ const resolveAppToolAttribution = useAppToolAttributionResolver(chatSessionId);
483
+ return resolveAppToolAttribution(label);
484
+ }
485
+ var __internal = { generateAlias, isReadOnly, ALIAS_REGEX };
486
+ var PARTIAL_INPUT_THROTTLE_MS = 120;
487
+ var STREAMING_REVEAL_FALLBACK_MS = 700;
488
+ var SIGNATURE_MAX_DEPTH = 4;
489
+ var SIGNATURE_MAX_ARRAY_ITEMS = 24;
490
+ var SIGNATURE_MAX_OBJECT_KEYS = 32;
491
+ var SIGNATURE_STRING_EDGE_LENGTH = 24;
492
+ function getToolInputSignature(input) {
493
+ if (!input) return "";
494
+ const seen = /* @__PURE__ */ new WeakSet();
495
+ const getValueSignature = (value, depth) => {
496
+ if (value == null) return "null";
497
+ const valueType = typeof value;
498
+ if (valueType === "string") {
499
+ const text = value;
500
+ const head = text.slice(0, SIGNATURE_STRING_EDGE_LENGTH);
501
+ const tail = text.slice(-SIGNATURE_STRING_EDGE_LENGTH);
502
+ return `str:${text.length}:${JSON.stringify(head)}:${JSON.stringify(tail)}`;
503
+ }
504
+ if (valueType === "number") {
505
+ if (Number.isNaN(value)) return "num:NaN";
506
+ if (value === Infinity) return "num:Infinity";
507
+ if (value === -Infinity) return "num:-Infinity";
508
+ if (Object.is(value, -0)) return "num:-0";
509
+ return `num:${value}`;
510
+ }
511
+ if (valueType === "boolean") return `bool:${String(value)}`;
512
+ if (valueType === "bigint") return `bigint:${String(value)}`;
513
+ if (valueType === "undefined") return "undefined";
514
+ if (valueType === "function") return "function";
515
+ if (valueType === "symbol") return `symbol:${String(value)}`;
516
+ if (depth >= SIGNATURE_MAX_DEPTH) {
517
+ if (Array.isArray(value)) return `arr:max-depth:${value.length}`;
518
+ return `obj:max-depth:${Object.keys(value).length}`;
519
+ }
520
+ if (Array.isArray(value)) {
521
+ const length = value.length;
522
+ if (length === 0) return "arr:0";
523
+ const headCount = Math.min(length, SIGNATURE_MAX_ARRAY_ITEMS);
524
+ const headSignatures = [];
525
+ for (let index = 0; index < headCount; index += 1) {
526
+ headSignatures.push(
527
+ `${index}:${getValueSignature(value[index], depth + 1)}`
528
+ );
529
+ }
530
+ if (length <= SIGNATURE_MAX_ARRAY_ITEMS) {
531
+ return `arr:${length}:[${headSignatures.join(",")}]`;
532
+ }
533
+ const tailStart = Math.max(headCount, length - 2);
534
+ const tailSignatures = [];
535
+ for (let index = tailStart; index < length; index += 1) {
536
+ tailSignatures.push(
537
+ `${index}:${getValueSignature(value[index], depth + 1)}`
538
+ );
539
+ }
540
+ return `arr:${length}:[${headSignatures.join(",")}]|tail:[${tailSignatures.join(",")}]`;
541
+ }
542
+ if (valueType === "object") {
543
+ const record = value;
544
+ if (seen.has(record)) return "obj:circular";
545
+ seen.add(record);
546
+ const keys = Object.keys(record).sort();
547
+ const keyCount = Math.min(keys.length, SIGNATURE_MAX_OBJECT_KEYS);
548
+ const entries = [];
549
+ for (let index = 0; index < keyCount; index += 1) {
550
+ const key = keys[index];
551
+ entries.push(`${key}:${getValueSignature(record[key], depth + 1)}`);
552
+ }
553
+ if (keys.length > SIGNATURE_MAX_OBJECT_KEYS) {
554
+ const omitted = keys.length - SIGNATURE_MAX_OBJECT_KEYS;
555
+ const tailKeys = keys.slice(-2).join(",");
556
+ entries.push(`omitted:${omitted}:tail-keys:${tailKeys}`);
557
+ }
558
+ seen.delete(record);
559
+ return `obj:${keys.length}:{${entries.join("|")}}`;
560
+ }
561
+ return `other:${valueType}`;
562
+ };
563
+ return getValueSignature(input, 0);
564
+ }
565
+ function useToolInputStreaming({
566
+ bridgeRef,
567
+ isReady,
568
+ isReadyRef,
569
+ toolState,
570
+ toolInput,
571
+ toolOutput,
572
+ toolErrorText,
573
+ toolCallId,
574
+ sendToolInput,
575
+ onToolInputSent,
576
+ reinitCount,
577
+ mcpAppsCapabilitiesRef
578
+ }) {
579
+ const lastToolInputRef = useRef(null);
580
+ const lastToolInputPartialRef = useRef(null);
581
+ const lastToolInputPartialSentAtRef = useRef(0);
582
+ const pendingToolInputPartialRef = useRef(
583
+ null
584
+ );
585
+ const partialInputTimerRef = useRef(null);
586
+ const streamingRevealTimerRef = useRef(null);
587
+ const lastToolOutputRef = useRef(null);
588
+ const lastToolErrorRef = useRef(null);
589
+ const toolInputSentRef = useRef(false);
590
+ const previousToolStateRef = useRef(toolState);
591
+ const previousToolCallIdRef = useRef(toolCallId);
592
+ const [streamingRenderSignaled, setStreamingRenderSignaled] = useState(false);
593
+ const [streamingRevealFallbackElapsed, setStreamingRevealFallbackElapsed] = useState(false);
594
+ const [hasDeliveredStreamingInput, setHasDeliveredStreamingInput] = useState(false);
595
+ const hasToolInputData = useMemo(
596
+ () => !!toolInput && Object.keys(toolInput).length > 0,
597
+ [toolInput]
598
+ );
599
+ const canRenderStreamingInput = useMemo(() => {
600
+ if (toolState !== "input-streaming") return true;
601
+ if (!sendToolInput) return true;
602
+ return streamingRevealFallbackElapsed || streamingRenderSignaled && hasDeliveredStreamingInput;
603
+ }, [
604
+ hasDeliveredStreamingInput,
605
+ sendToolInput,
606
+ streamingRevealFallbackElapsed,
607
+ streamingRenderSignaled,
608
+ toolState
609
+ ]);
610
+ const resetStreamingState = useCallback(() => {
611
+ lastToolInputRef.current = null;
612
+ lastToolInputPartialRef.current = null;
613
+ lastToolInputPartialSentAtRef.current = 0;
614
+ pendingToolInputPartialRef.current = null;
615
+ if (partialInputTimerRef.current !== null) {
616
+ window.clearTimeout(partialInputTimerRef.current);
617
+ partialInputTimerRef.current = null;
618
+ }
619
+ if (streamingRevealTimerRef.current !== null) {
620
+ window.clearTimeout(streamingRevealTimerRef.current);
621
+ streamingRevealTimerRef.current = null;
622
+ }
623
+ lastToolOutputRef.current = null;
624
+ lastToolErrorRef.current = null;
625
+ toolInputSentRef.current = false;
626
+ setStreamingRenderSignaled(false);
627
+ setStreamingRevealFallbackElapsed(false);
628
+ setHasDeliveredStreamingInput(false);
629
+ }, []);
630
+ const signalStreamingRender = useCallback(() => {
631
+ setStreamingRenderSignaled(true);
632
+ }, []);
633
+ useEffect(() => {
634
+ if (reinitCount === 0) return;
635
+ lastToolInputRef.current = null;
636
+ lastToolInputPartialRef.current = null;
637
+ lastToolOutputRef.current = null;
638
+ lastToolErrorRef.current = null;
639
+ toolInputSentRef.current = false;
640
+ }, [reinitCount]);
641
+ useEffect(() => {
642
+ if (!hasDeliveredStreamingInput && !streamingRevealFallbackElapsed) return;
643
+ if (streamingRevealTimerRef.current !== null) {
644
+ window.clearTimeout(streamingRevealTimerRef.current);
645
+ streamingRevealTimerRef.current = null;
646
+ }
647
+ }, [hasDeliveredStreamingInput, streamingRevealFallbackElapsed]);
648
+ useEffect(() => {
649
+ if (!sendToolInput) return;
650
+ if (!isReady || toolState !== "input-streaming" || hasDeliveredStreamingInput || streamingRevealFallbackElapsed)
651
+ return;
652
+ if (streamingRevealTimerRef.current !== null) return;
653
+ streamingRevealTimerRef.current = window.setTimeout(() => {
654
+ streamingRevealTimerRef.current = null;
655
+ setStreamingRenderSignaled(true);
656
+ setStreamingRevealFallbackElapsed(true);
657
+ }, STREAMING_REVEAL_FALLBACK_MS);
658
+ }, [
659
+ hasDeliveredStreamingInput,
660
+ isReady,
661
+ sendToolInput,
662
+ streamingRevealFallbackElapsed,
663
+ toolState
664
+ ]);
665
+ useEffect(() => {
666
+ const prevToolState = previousToolStateRef.current;
667
+ if (toolState === "input-streaming" && prevToolState && prevToolState !== "input-streaming") {
668
+ resetStreamingState();
669
+ }
670
+ previousToolStateRef.current = toolState;
671
+ }, [resetStreamingState, toolState]);
672
+ useEffect(() => {
673
+ if (!sendToolInput || !isReady || toolState !== "input-streaming" || toolInputSentRef.current)
674
+ return;
675
+ if (!hasToolInputData) return;
676
+ const resolvedToolInput = toolInput ?? {};
677
+ pendingToolInputPartialRef.current = resolvedToolInput;
678
+ const flushPartialInput = () => {
679
+ const bridge = bridgeRef.current;
680
+ if (!bridge || !isReadyRef.current || toolInputSentRef.current) return;
681
+ const pending = pendingToolInputPartialRef.current;
682
+ if (!pending) return;
683
+ const signature = getToolInputSignature(pending);
684
+ if (lastToolInputPartialRef.current === signature) return;
685
+ lastToolInputPartialRef.current = signature;
686
+ lastToolInputPartialSentAtRef.current = Date.now();
687
+ setHasDeliveredStreamingInput(true);
688
+ setStreamingRenderSignaled(true);
689
+ const matrix = mcpAppsCapabilitiesRef.current;
690
+ if (matrix !== null && matrix.toolInputPartial === false) return;
691
+ Promise.resolve(
692
+ bridge.sendToolInputPartial({ arguments: pending })
693
+ ).catch(() => {
694
+ });
695
+ };
696
+ const now = Date.now();
697
+ const elapsed = now - lastToolInputPartialSentAtRef.current;
698
+ if (lastToolInputPartialSentAtRef.current === 0 || elapsed >= PARTIAL_INPUT_THROTTLE_MS) {
699
+ if (partialInputTimerRef.current !== null) {
700
+ window.clearTimeout(partialInputTimerRef.current);
701
+ partialInputTimerRef.current = null;
702
+ }
703
+ flushPartialInput();
704
+ return;
705
+ }
706
+ if (partialInputTimerRef.current !== null) {
707
+ window.clearTimeout(partialInputTimerRef.current);
708
+ }
709
+ partialInputTimerRef.current = window.setTimeout(() => {
710
+ partialInputTimerRef.current = null;
711
+ flushPartialInput();
712
+ }, PARTIAL_INPUT_THROTTLE_MS - elapsed);
713
+ }, [
714
+ hasToolInputData,
715
+ isReady,
716
+ sendToolInput,
717
+ toolCallId,
718
+ toolInput,
719
+ toolState,
720
+ bridgeRef,
721
+ isReadyRef
722
+ ]);
723
+ useEffect(() => {
724
+ if (!isReady) return;
725
+ if (toolState !== "input-available" && toolState !== "output-available")
726
+ return;
727
+ if (partialInputTimerRef.current !== null) {
728
+ window.clearTimeout(partialInputTimerRef.current);
729
+ partialInputTimerRef.current = null;
730
+ }
731
+ if (streamingRevealTimerRef.current !== null) {
732
+ window.clearTimeout(streamingRevealTimerRef.current);
733
+ streamingRevealTimerRef.current = null;
734
+ }
735
+ pendingToolInputPartialRef.current = null;
736
+ if (!sendToolInput) return;
737
+ const bridge = bridgeRef.current;
738
+ if (!bridge) return;
739
+ const resolvedToolInput = toolInput ?? {};
740
+ const serialized = JSON.stringify(resolvedToolInput);
741
+ if (lastToolInputRef.current === serialized) {
742
+ toolInputSentRef.current = true;
743
+ return;
744
+ }
745
+ lastToolInputRef.current = serialized;
746
+ toolInputSentRef.current = true;
747
+ onToolInputSent?.();
748
+ Promise.resolve(
749
+ bridge.sendToolInput({ arguments: resolvedToolInput })
750
+ ).catch(() => {
751
+ toolInputSentRef.current = false;
752
+ lastToolInputRef.current = null;
753
+ });
754
+ }, [
755
+ isReady,
756
+ toolCallId,
757
+ toolInput,
758
+ toolState,
759
+ bridgeRef,
760
+ reinitCount,
761
+ sendToolInput,
762
+ onToolInputSent
763
+ ]);
764
+ useEffect(() => {
765
+ if (!isReady || toolState !== "output-available") return;
766
+ const bridge = bridgeRef.current;
767
+ if (!bridge || !toolOutput) return;
768
+ const serialized = JSON.stringify(toolOutput);
769
+ const outputKey = `${toolCallId}:${serialized}`;
770
+ if (lastToolOutputRef.current === outputKey) return;
771
+ lastToolOutputRef.current = outputKey;
772
+ bridge.sendToolResult(toolOutput);
773
+ }, [isReady, toolCallId, toolOutput, toolState, bridgeRef, reinitCount]);
774
+ useEffect(() => {
775
+ if (!isReady || toolState !== "output-error") return;
776
+ const bridge = bridgeRef.current;
777
+ if (!bridge) return;
778
+ const errorMessage = toolErrorText ?? (toolOutput instanceof Error ? toolOutput.message : typeof toolOutput === "string" ? toolOutput : "Tool execution failed");
779
+ const errorKey = `${toolCallId}:${errorMessage}`;
780
+ if (lastToolErrorRef.current === errorKey) return;
781
+ lastToolErrorRef.current = errorKey;
782
+ const matrix = mcpAppsCapabilitiesRef.current;
783
+ if (matrix !== null && matrix.toolCancelled === false) return;
784
+ bridge.sendToolCancelled({ reason: errorMessage });
785
+ }, [
786
+ isReady,
787
+ toolCallId,
788
+ toolErrorText,
789
+ toolOutput,
790
+ toolState,
791
+ bridgeRef,
792
+ reinitCount,
793
+ mcpAppsCapabilitiesRef
794
+ ]);
795
+ useLayoutEffect(() => {
796
+ if (previousToolCallIdRef.current === toolCallId) return;
797
+ previousToolCallIdRef.current = toolCallId;
798
+ resetStreamingState();
799
+ }, [toolCallId, resetStreamingState]);
800
+ useEffect(() => {
801
+ return () => resetStreamingState();
802
+ }, [resetStreamingState]);
803
+ return {
804
+ canRenderStreamingInput,
805
+ signalStreamingRender,
806
+ resetStreamingState
807
+ };
808
+ }
809
+ var SandboxedIframe = forwardRef(function SandboxedIframe2({
810
+ html,
811
+ sandbox = "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",
812
+ csp,
813
+ permissions,
814
+ sandboxAttrs,
815
+ allowFeatures,
816
+ cspDirectives,
817
+ permissive,
818
+ onProxyReady,
819
+ onMessage,
820
+ className,
821
+ style,
822
+ colorScheme,
823
+ title = "Sandboxed Content",
824
+ hostedMode = false,
825
+ sandboxOrigin = ""
826
+ }, ref) {
827
+ const outerRef = useRef(null);
828
+ const [proxyReady, setProxyReady] = useState(false);
829
+ const lastResourceReadyKeyRef = useRef(null);
830
+ const [sandboxProxyUrl] = useState(() => {
831
+ const proxyPath = hostedMode ? "/api/web/apps/mcp-apps/sandbox-proxy" : "/api/apps/mcp-apps/sandbox-proxy";
832
+ if (hostedMode && sandboxOrigin) {
833
+ return `${sandboxOrigin}${proxyPath}?v=${Date.now()}`;
834
+ }
835
+ const currentHost = window.location.hostname;
836
+ const currentPort = window.location.port;
837
+ const protocol = window.location.protocol;
838
+ let sandboxHost;
839
+ if (currentHost === "localhost") {
840
+ sandboxHost = "127.0.0.1";
841
+ } else if (currentHost === "127.0.0.1") {
842
+ sandboxHost = "localhost";
843
+ } else {
844
+ if (hostedMode) {
845
+ console.warn(
846
+ "[SandboxedIframe] VITE_MCPJAM_SANDBOX_ORIGIN is not configured; sandbox iframe is falling back to same-origin. This is a security regression \u2014 the sandbox shares cookies and storage with the host app. Configure a distinct origin (e.g. https://sandbox.mcpjam.com) and redeploy."
847
+ );
848
+ } else {
849
+ console.warn(
850
+ "[SandboxedIframe] Cross-origin isolation not available for hostname:",
851
+ currentHost,
852
+ "- falling back to same-origin sandbox"
853
+ );
854
+ }
855
+ sandboxHost = currentHost;
856
+ }
857
+ const portSuffix = currentPort ? `:${currentPort}` : "";
858
+ return `${protocol}//${sandboxHost}${portSuffix}${proxyPath}?v=${Date.now()}`;
859
+ });
860
+ const sandboxProxyOrigin = useMemo(() => {
861
+ try {
862
+ return new URL(sandboxProxyUrl).origin;
863
+ } catch {
864
+ return "*";
865
+ }
866
+ }, [sandboxProxyUrl]);
867
+ useImperativeHandle(
868
+ ref,
869
+ () => ({
870
+ postMessage: (data) => {
871
+ outerRef.current?.contentWindow?.postMessage(data, sandboxProxyOrigin);
872
+ },
873
+ getIframeElement: () => outerRef.current
874
+ }),
875
+ [sandboxProxyOrigin]
876
+ );
877
+ const handleMessage = useCallback(
878
+ (event) => {
879
+ if (event.origin !== sandboxProxyOrigin && sandboxProxyOrigin !== "*") {
880
+ return;
881
+ }
882
+ if (event.source !== outerRef.current?.contentWindow) return;
883
+ if (event.data?.type === "mcp-apps:csp-violation") {
884
+ onMessage(event);
885
+ return;
886
+ }
887
+ if (event.data?.type === "openai:uploadFile" || event.data?.type === "openai:getFileDownloadUrl" || event.data?.type === "openai:setWidgetState" || event.data?.type === "openai:setOpenInAppUrl") {
888
+ onMessage(event);
889
+ return;
890
+ }
891
+ const { jsonrpc, method } = event.data || {};
892
+ if (jsonrpc !== "2.0") return;
893
+ if (method === "ui/notifications/sandbox-proxy-ready") {
894
+ setProxyReady(true);
895
+ onProxyReady?.();
896
+ return;
897
+ }
898
+ if (method?.startsWith("ui/notifications/sandbox-")) {
899
+ return;
900
+ }
901
+ onMessage(event);
902
+ },
903
+ [onMessage, onProxyReady, sandboxProxyOrigin]
904
+ );
905
+ useEffect(() => {
906
+ window.addEventListener("message", handleMessage);
907
+ return () => window.removeEventListener("message", handleMessage);
908
+ }, [handleMessage]);
909
+ const outerAllowAttribute = useMemo(
910
+ () => buildOuterAllowAttribute({ permissions, allowFeatures }),
911
+ [permissions, allowFeatures]
912
+ );
913
+ const outerSandboxAttribute = useMemo(
914
+ () => buildOuterSandboxAttribute({ sandbox, sandboxAttrs }),
915
+ [sandbox, sandboxAttrs]
916
+ );
917
+ const resourceReadyKey = useMemo(
918
+ () => stableStringifyJson({
919
+ csp: csp ?? null,
920
+ cspDirectives: cspDirectives ?? null,
921
+ html: html ?? null,
922
+ permissive: permissive ?? null,
923
+ permissions: permissions ?? null,
924
+ sandbox,
925
+ sandboxAttrs: sandboxAttrs ?? null
926
+ }),
927
+ [
928
+ csp,
929
+ cspDirectives,
930
+ html,
931
+ permissive,
932
+ permissions,
933
+ sandbox,
934
+ sandboxAttrs
935
+ ]
936
+ );
937
+ useEffect(() => {
938
+ if (!proxyReady) lastResourceReadyKeyRef.current = null;
939
+ }, [proxyReady]);
940
+ useEffect(() => {
941
+ if (!proxyReady || !html) return;
942
+ const resourceTargetKey = `${sandboxProxyOrigin}\0${resourceReadyKey}`;
943
+ if (lastResourceReadyKeyRef.current === resourceTargetKey) return;
944
+ lastResourceReadyKeyRef.current = resourceTargetKey;
945
+ outerRef.current?.contentWindow?.postMessage(
946
+ {
947
+ jsonrpc: "2.0",
948
+ method: "ui/notifications/sandbox-resource-ready",
949
+ params: {
950
+ html,
951
+ sandbox,
952
+ csp,
953
+ permissions,
954
+ sandboxAttrs,
955
+ // `allowFeatures` is intentionally NOT forwarded to the proxy:
956
+ // it applies to the OUTER iframe only. The inner iframe gets the
957
+ // 4 spec permissions (via `permissions`) and nothing else, matching
958
+ // real claude.ai's outer-grants-fullscreen / inner-trims-to-spec
959
+ // pattern. Centralizing the outer/inner split here means the proxy
960
+ // can't accidentally widen the inner grant by reading a stale
961
+ // field.
962
+ cspDirectives,
963
+ permissive,
964
+ colorScheme
965
+ }
966
+ },
967
+ sandboxProxyOrigin
968
+ );
969
+ }, [
970
+ proxyReady,
971
+ html,
972
+ resourceReadyKey,
973
+ sandboxProxyOrigin
974
+ ]);
975
+ useEffect(() => {
976
+ if (!proxyReady || !colorScheme) return;
977
+ outerRef.current?.contentWindow?.postMessage(
978
+ {
979
+ jsonrpc: "2.0",
980
+ method: "ui/notifications/sandbox-color-scheme-changed",
981
+ params: { colorScheme }
982
+ },
983
+ sandboxProxyOrigin
984
+ );
985
+ }, [proxyReady, colorScheme, sandboxProxyOrigin]);
986
+ const iframeStyle = colorScheme ? { ...style, colorScheme } : style;
987
+ useEffect(() => {
988
+ setProxyReady(false);
989
+ }, [outerSandboxAttribute]);
990
+ return /* @__PURE__ */ jsx(
991
+ "iframe",
992
+ {
993
+ ref: outerRef,
994
+ src: sandboxProxyUrl,
995
+ sandbox: outerSandboxAttribute,
996
+ allow: outerAllowAttribute,
997
+ title,
998
+ className,
999
+ style: iframeStyle
1000
+ },
1001
+ outerSandboxAttribute
1002
+ );
1003
+ });
1004
+ function McpAppsModal({
1005
+ open,
1006
+ onOpenChange,
1007
+ title,
1008
+ template,
1009
+ params,
1010
+ registerBridgeHandlers,
1011
+ refreshAppProvidedTools,
1012
+ widgetCsp,
1013
+ widgetPermissions,
1014
+ widgetPermissive,
1015
+ widgetSandboxAttrs,
1016
+ widgetAllowFeatures,
1017
+ widgetCspDirectives,
1018
+ hostContextRef,
1019
+ serverId,
1020
+ resourceUri,
1021
+ toolCallId,
1022
+ toolName,
1023
+ cspMode,
1024
+ injectOpenAiCompat,
1025
+ effectiveHostCapabilities,
1026
+ hostInfo,
1027
+ webManagedServers,
1028
+ toolInputRef,
1029
+ toolOutputRef,
1030
+ themeModeRef,
1031
+ addUiLog,
1032
+ onCspViolation
1033
+ }) {
1034
+ const host = useWidgetHost();
1035
+ const Modal = host.components?.Modal;
1036
+ const [modalHtml, setModalHtml] = useState(null);
1037
+ const modalSandboxRef = useRef(null);
1038
+ const modalBridgeRef = useRef(null);
1039
+ const modalAppToolsBridgeIdRef = useRef(null);
1040
+ const modalColorScheme = hostContextRef.current?.theme === "light" || hostContextRef.current?.theme === "dark" ? hostContextRef.current.theme : themeModeRef.current === "light" || themeModeRef.current === "dark" ? themeModeRef.current : void 0;
1041
+ useEffect(() => {
1042
+ if (!open) {
1043
+ modalBridgeRef.current?.close().catch(() => {
1044
+ });
1045
+ modalBridgeRef.current = null;
1046
+ if (modalAppToolsBridgeIdRef.current) {
1047
+ useAppToolsRegistry.getState().unregisterInstance(modalAppToolsBridgeIdRef.current);
1048
+ modalAppToolsBridgeIdRef.current = null;
1049
+ }
1050
+ setModalHtml(null);
1051
+ return;
1052
+ }
1053
+ const fetchModalHtml = async () => {
1054
+ try {
1055
+ const { html } = await host.services.fetchWidgetContent({
1056
+ serverId,
1057
+ forceWebEndpoint: webManagedServers,
1058
+ resourceUri,
1059
+ toolInput: toolInputRef.current,
1060
+ toolOutput: toolOutputRef.current,
1061
+ toolId: toolCallId,
1062
+ toolName,
1063
+ theme: themeModeRef.current,
1064
+ cspMode,
1065
+ injectOpenAiCompat,
1066
+ template: template ?? void 0,
1067
+ viewMode: "modal",
1068
+ viewParams: params
1069
+ });
1070
+ setModalHtml(html);
1071
+ } catch (err) {
1072
+ console.error("[MCP Apps] Failed to fetch modal HTML", err);
1073
+ }
1074
+ };
1075
+ fetchModalHtml();
1076
+ }, [
1077
+ open,
1078
+ template,
1079
+ params,
1080
+ serverId,
1081
+ resourceUri,
1082
+ toolCallId,
1083
+ toolName,
1084
+ cspMode,
1085
+ injectOpenAiCompat,
1086
+ webManagedServers,
1087
+ toolInputRef,
1088
+ toolOutputRef,
1089
+ themeModeRef
1090
+ ]);
1091
+ useEffect(() => {
1092
+ if (!modalHtml || !open) return;
1093
+ const iframe = modalSandboxRef.current?.getIframeElement();
1094
+ if (!iframe?.contentWindow) return;
1095
+ const bridge = new AppBridge(
1096
+ null,
1097
+ hostInfo,
1098
+ {
1099
+ ...effectiveHostCapabilities,
1100
+ sandbox: {
1101
+ csp: widgetPermissive ? void 0 : widgetCsp,
1102
+ permissions: widgetPermissions
1103
+ }
1104
+ },
1105
+ { hostContext: hostContextRef.current ?? {} }
1106
+ );
1107
+ registerBridgeHandlers(bridge);
1108
+ bridge.onsizechange = ({ width, height }) => {
1109
+ const modalIframe = modalSandboxRef.current?.getIframeElement();
1110
+ if (!modalIframe) return;
1111
+ if (height !== void 0) {
1112
+ const style = getComputedStyle(modalIframe);
1113
+ const isBorderBox = style.boxSizing === "border-box";
1114
+ let adjustedHeight = height;
1115
+ if (isBorderBox) {
1116
+ adjustedHeight += parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth);
1117
+ }
1118
+ modalIframe.style.height = `${adjustedHeight}px`;
1119
+ }
1120
+ if (width !== void 0) {
1121
+ modalIframe.style.width = `${width}px`;
1122
+ }
1123
+ };
1124
+ bridge.oninitialized = () => {
1125
+ const resolvedToolInput = toolInputRef.current ?? {};
1126
+ bridge.sendToolInput({ arguments: resolvedToolInput });
1127
+ if (toolOutputRef.current) {
1128
+ bridge.sendToolResult(toolOutputRef.current);
1129
+ }
1130
+ const appCaps = bridge.getAppCapabilities();
1131
+ if (appCaps?.tools) {
1132
+ const bridgeId = modalAppToolsBridgeIdRef.current ?? crypto.randomUUID();
1133
+ modalAppToolsBridgeIdRef.current = bridgeId;
1134
+ void refreshAppProvidedTools(bridge, bridgeId, {
1135
+ surface: "modal",
1136
+ getIframeElement: () => modalSandboxRef.current?.getIframeElement() ?? null,
1137
+ isLive: () => modalAppToolsBridgeIdRef.current === bridgeId
1138
+ });
1139
+ }
1140
+ };
1141
+ modalBridgeRef.current = bridge;
1142
+ const pendingRpcMethods = /* @__PURE__ */ new Map();
1143
+ const transport = new LoggingTransport(
1144
+ new PostMessageTransport(iframe.contentWindow, iframe.contentWindow),
1145
+ {
1146
+ onSend: (message) => {
1147
+ const request = message;
1148
+ if (typeof request.method === "string" && (typeof request.id === "string" || typeof request.id === "number")) {
1149
+ pendingRpcMethods.set(request.id, request.method);
1150
+ }
1151
+ addUiLog({
1152
+ widgetId: `${toolCallId}-modal`,
1153
+ serverId,
1154
+ direction: "host-to-ui",
1155
+ protocol: "mcp-apps",
1156
+ method: extractMethod(message, "mcp-apps"),
1157
+ message
1158
+ });
1159
+ },
1160
+ onReceive: (message) => {
1161
+ const response = message;
1162
+ const correlatedMethod = (response.result !== void 0 || response.error !== void 0) && (typeof response.id === "string" || typeof response.id === "number") ? pendingRpcMethods.get(response.id) : void 0;
1163
+ if (correlatedMethod && response.id !== void 0) {
1164
+ pendingRpcMethods.delete(response.id);
1165
+ }
1166
+ const method = correlatedMethod ?? extractMethod(message, "mcp-apps");
1167
+ if (method === "notifications/tools/list_changed") {
1168
+ const bridgeId = modalAppToolsBridgeIdRef.current;
1169
+ if (bridgeId) {
1170
+ void refreshAppProvidedTools(bridge, bridgeId, {
1171
+ force: true,
1172
+ surface: "modal",
1173
+ getIframeElement: () => modalSandboxRef.current?.getIframeElement() ?? null,
1174
+ isLive: () => modalAppToolsBridgeIdRef.current === bridgeId
1175
+ });
1176
+ }
1177
+ }
1178
+ addUiLog({
1179
+ widgetId: `${toolCallId}-modal`,
1180
+ serverId,
1181
+ direction: "ui-to-host",
1182
+ protocol: "mcp-apps",
1183
+ method,
1184
+ message
1185
+ });
1186
+ }
1187
+ }
1188
+ );
1189
+ let isActive = true;
1190
+ bridge.connect(transport).catch((error) => {
1191
+ if (!isActive) return;
1192
+ console.error("[MCP Apps] Modal bridge connection failed", error);
1193
+ });
1194
+ return () => {
1195
+ isActive = false;
1196
+ modalBridgeRef.current = null;
1197
+ if (modalAppToolsBridgeIdRef.current) {
1198
+ const bridgeId = modalAppToolsBridgeIdRef.current;
1199
+ modalAppToolsBridgeIdRef.current = null;
1200
+ useAppToolsRegistry.getState().unregisterInstance(bridgeId);
1201
+ }
1202
+ bridge.close().catch(() => {
1203
+ });
1204
+ };
1205
+ }, [
1206
+ modalHtml,
1207
+ open,
1208
+ addUiLog,
1209
+ serverId,
1210
+ toolCallId,
1211
+ registerBridgeHandlers,
1212
+ refreshAppProvidedTools,
1213
+ widgetPermissive,
1214
+ widgetCsp,
1215
+ widgetPermissions,
1216
+ hostContextRef,
1217
+ toolInputRef,
1218
+ toolOutputRef,
1219
+ hostInfo,
1220
+ effectiveHostCapabilities
1221
+ ]);
1222
+ const handleModalMessage = (event) => {
1223
+ const data = event.data;
1224
+ if (!data) return;
1225
+ if (data.type === "mcp-apps:csp-violation") {
1226
+ onCspViolation(event);
1227
+ }
1228
+ };
1229
+ if (!Modal) return null;
1230
+ return /* @__PURE__ */ jsx(Modal, { open, onClose: () => onOpenChange(false), title, children: /* @__PURE__ */ jsx("div", { className: "flex-1 w-full h-full min-h-0 overflow-auto", children: modalHtml && /* @__PURE__ */ jsx(
1231
+ SandboxedIframe,
1232
+ {
1233
+ ref: modalSandboxRef,
1234
+ html: modalHtml,
1235
+ sandbox: "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",
1236
+ csp: widgetCsp,
1237
+ permissions: widgetPermissions,
1238
+ permissive: widgetPermissive,
1239
+ sandboxAttrs: widgetSandboxAttrs,
1240
+ allowFeatures: widgetAllowFeatures,
1241
+ cspDirectives: widgetCspDirectives,
1242
+ colorScheme: modalColorScheme,
1243
+ onMessage: handleModalMessage,
1244
+ title: `MCP App Modal: ${title}`,
1245
+ hostedMode: host.surface.hostedMode,
1246
+ sandboxOrigin: host.surface.sandboxOrigin,
1247
+ className: "min-w-full border-0 rounded-md bg-transparent overflow-hidden",
1248
+ style: {
1249
+ height: "100%",
1250
+ minHeight: "400px",
1251
+ backgroundColor: "transparent"
1252
+ }
1253
+ }
1254
+ ) }) });
1255
+ }
1256
+
1257
+ // src/widget-file-messages.ts
1258
+ var UPLOADED_FILE_ID_PATTERN = /^file_[0-9a-f-]+$/;
1259
+ function isValidUploadedFileId(fileId) {
1260
+ return typeof fileId === "string" && UPLOADED_FILE_ID_PATTERN.test(fileId);
1261
+ }
1262
+ function buildWidgetDownloadUrl(fileId, hostedMode) {
1263
+ const loc = window.location;
1264
+ const widgetHost = loc.hostname === "localhost" ? "127.0.0.1" : "localhost";
1265
+ const basePath = hostedMode ? "/api/web/apps/files/file" : "/api/apps/files/file";
1266
+ return `${loc.protocol}//${widgetHost}:${loc.port}${basePath}/${fileId}`;
1267
+ }
1268
+ async function handleUploadFileMessage(data, sendResponse, { authFetch, hostedMode }) {
1269
+ const uploadCallId = data.callId;
1270
+ if (hostedMode) {
1271
+ sendResponse({
1272
+ type: "openai:uploadFile:response",
1273
+ callId: uploadCallId,
1274
+ error: "File upload is not supported in hosted mode"
1275
+ });
1276
+ return;
1277
+ }
1278
+ try {
1279
+ const resp = await authFetch("/api/apps/files/upload-file", {
1280
+ method: "POST",
1281
+ headers: { "Content-Type": "application/json" },
1282
+ body: JSON.stringify({
1283
+ data: data.data,
1284
+ mimeType: data.mimeType,
1285
+ fileName: data.fileName
1286
+ })
1287
+ });
1288
+ if (!resp.ok) {
1289
+ const body = await resp.json().catch(() => ({ error: resp.statusText }));
1290
+ sendResponse({
1291
+ type: "openai:uploadFile:response",
1292
+ callId: uploadCallId,
1293
+ error: body.error || "Upload failed"
1294
+ });
1295
+ return;
1296
+ }
1297
+ const { fileId } = await resp.json();
1298
+ sendResponse({
1299
+ type: "openai:uploadFile:response",
1300
+ callId: uploadCallId,
1301
+ result: { fileId }
1302
+ });
1303
+ } catch (err) {
1304
+ sendResponse({
1305
+ type: "openai:uploadFile:response",
1306
+ callId: uploadCallId,
1307
+ error: err instanceof Error ? err.message : "Upload failed"
1308
+ });
1309
+ }
1310
+ }
1311
+ function handleGetFileDownloadUrlMessage(data, sendResponse, { hostedMode }) {
1312
+ const dlCallId = data.callId;
1313
+ if (hostedMode) {
1314
+ sendResponse({
1315
+ type: "openai:getFileDownloadUrl:response",
1316
+ callId: dlCallId,
1317
+ error: "File download is not supported in hosted mode"
1318
+ });
1319
+ return;
1320
+ }
1321
+ const fileId = data.fileId;
1322
+ if (!isValidUploadedFileId(fileId)) {
1323
+ sendResponse({
1324
+ type: "openai:getFileDownloadUrl:response",
1325
+ callId: dlCallId,
1326
+ error: "Invalid fileId"
1327
+ });
1328
+ return;
1329
+ }
1330
+ sendResponse({
1331
+ type: "openai:getFileDownloadUrl:response",
1332
+ callId: dlCallId,
1333
+ result: { downloadUrl: buildWidgetDownloadUrl(fileId, hostedMode) }
1334
+ });
1335
+ }
1336
+ var WidgetSurfaceHostContext = createContext(false);
1337
+ function WidgetSurfaceHostProvider({
1338
+ children
1339
+ }) {
1340
+ return /* @__PURE__ */ jsx(WidgetSurfaceHostContext.Provider, { value: true, children });
1341
+ }
1342
+ function usePersistentWidgetSurfaceHost() {
1343
+ return useContext(WidgetSurfaceHostContext);
1344
+ }
1345
+ var useWidgetSurfaceStore = create((set) => ({
1346
+ surfaces: /* @__PURE__ */ new Map(),
1347
+ nextOrder: 0,
1348
+ upsertRegistration: (surfaceId, toolCallId, props) => {
1349
+ set((state) => {
1350
+ const surfaces = new Map(state.surfaces);
1351
+ const existing = surfaces.get(surfaceId);
1352
+ const registrations = new Map(existing?.registrations);
1353
+ const currentRegistration = registrations.get(toolCallId);
1354
+ const isNewRegistration = !currentRegistration;
1355
+ const order = currentRegistration?.order ?? state.nextOrder;
1356
+ const latestRegistration = existing?.registrations.get(
1357
+ existing.latestToolCallId
1358
+ );
1359
+ const shouldBecomeLatest = !existing || !latestRegistration || isNewRegistration && order > latestRegistration.order;
1360
+ registrations.set(toolCallId, {
1361
+ toolCallId,
1362
+ order,
1363
+ props,
1364
+ anchorElement: currentRegistration?.anchorElement ?? null
1365
+ });
1366
+ surfaces.set(surfaceId, {
1367
+ surfaceId,
1368
+ chatSessionId: props.chatSessionId,
1369
+ initialToolCallId: existing?.initialToolCallId ?? toolCallId,
1370
+ latestToolCallId: shouldBecomeLatest ? toolCallId : existing.latestToolCallId,
1371
+ registrations
1372
+ });
1373
+ return {
1374
+ surfaces,
1375
+ nextOrder: isNewRegistration ? state.nextOrder + 1 : state.nextOrder
1376
+ };
1377
+ });
1378
+ },
1379
+ setAnchor: (surfaceId, toolCallId, anchorElement) => {
1380
+ set((state) => {
1381
+ const existing = state.surfaces.get(surfaceId);
1382
+ const registration = existing?.registrations.get(toolCallId);
1383
+ if (!existing || !registration) return {};
1384
+ if (registration.anchorElement === anchorElement) return {};
1385
+ const registrations = new Map(existing.registrations);
1386
+ registrations.set(toolCallId, {
1387
+ ...registration,
1388
+ anchorElement
1389
+ });
1390
+ const surfaces = new Map(state.surfaces);
1391
+ surfaces.set(surfaceId, {
1392
+ ...existing,
1393
+ registrations
1394
+ });
1395
+ return { surfaces };
1396
+ });
1397
+ },
1398
+ releaseRegistration: (surfaceId, toolCallId) => {
1399
+ set((state) => {
1400
+ const existing = state.surfaces.get(surfaceId);
1401
+ if (!existing || !existing.registrations.has(toolCallId)) return {};
1402
+ const surfaces = new Map(state.surfaces);
1403
+ const registrations = new Map(existing.registrations);
1404
+ registrations.delete(toolCallId);
1405
+ if (registrations.size === 0) {
1406
+ surfaces.delete(surfaceId);
1407
+ return { surfaces };
1408
+ }
1409
+ let latestRegistration = null;
1410
+ for (const registration of registrations.values()) {
1411
+ if (latestRegistration === null || registration.order > latestRegistration.order) {
1412
+ latestRegistration = registration;
1413
+ }
1414
+ }
1415
+ surfaces.set(surfaceId, {
1416
+ ...existing,
1417
+ latestToolCallId: existing.latestToolCallId === toolCallId ? latestRegistration?.toolCallId ?? existing.latestToolCallId : existing.latestToolCallId,
1418
+ registrations
1419
+ });
1420
+ return { surfaces };
1421
+ });
1422
+ },
1423
+ clearChatSession: (chatSessionId) => {
1424
+ set((state) => {
1425
+ let hasMatch = false;
1426
+ for (const surface of state.surfaces.values()) {
1427
+ if (surface.chatSessionId === chatSessionId) {
1428
+ hasMatch = true;
1429
+ break;
1430
+ }
1431
+ }
1432
+ if (!hasMatch) return {};
1433
+ const surfaces = new Map(state.surfaces);
1434
+ for (const [surfaceId, surface] of state.surfaces) {
1435
+ if (surface.chatSessionId === chatSessionId) {
1436
+ surfaces.delete(surfaceId);
1437
+ }
1438
+ }
1439
+ return { surfaces };
1440
+ });
1441
+ }
1442
+ }));
1443
+ function getRenderableSurfaceEntries(surfaces, chatSessionId) {
1444
+ const entries = [];
1445
+ for (const surface of surfaces.values()) {
1446
+ if (surface.chatSessionId !== chatSessionId) continue;
1447
+ const latestRegistration = surface.registrations.get(
1448
+ surface.latestToolCallId
1449
+ );
1450
+ if (!latestRegistration) continue;
1451
+ const initialRegistration = surface.registrations.get(
1452
+ surface.initialToolCallId
1453
+ );
1454
+ const fallbackAnchor = Array.from(surface.registrations.values()).find(
1455
+ (registration) => registration.anchorElement !== null
1456
+ )?.anchorElement ?? null;
1457
+ entries.push({
1458
+ surfaceId: surface.surfaceId,
1459
+ anchorElement: initialRegistration?.anchorElement ?? fallbackAnchor,
1460
+ initialToolCallId: surface.initialToolCallId,
1461
+ props: latestRegistration.props
1462
+ });
1463
+ }
1464
+ return entries;
1465
+ }
1466
+ var NOOP_WIDGET_DEBUG_SINK = {
1467
+ recordMount: () => {
1468
+ },
1469
+ setWidgetDebugInfo: () => {
1470
+ },
1471
+ setWidgetState: () => {
1472
+ },
1473
+ setWidgetGlobals: () => {
1474
+ },
1475
+ setWidgetCsp: () => {
1476
+ },
1477
+ addCspViolation: () => {
1478
+ },
1479
+ clearCspViolations: () => {
1480
+ },
1481
+ setWidgetModelContext: () => {
1482
+ },
1483
+ setWidgetHtml: () => {
1484
+ },
1485
+ setSandboxApplied: () => {
1486
+ },
1487
+ appendLifecycle: () => {
1488
+ },
1489
+ addTrafficLog: () => {
1490
+ }
1491
+ };
1492
+ var DEFAULT_INPUT_SCHEMA = { type: "object" };
1493
+ var SUPPRESSED_UI_LOG_METHODS = /* @__PURE__ */ new Set(["ui/notifications/size-changed"]);
1494
+ var PIP_MAX_HEIGHT = "min(40vh, 600px)";
1495
+ var SAFE_OPEN_IN_APP_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:"]);
1496
+ function toSafeOpenInAppUrl(value) {
1497
+ try {
1498
+ const parsed = new URL(value);
1499
+ return SAFE_OPEN_IN_APP_PROTOCOLS.has(parsed.protocol) ? parsed.href : null;
1500
+ } catch {
1501
+ return null;
1502
+ }
1503
+ }
1504
+ function readExplicitBaseHref(html) {
1505
+ if (!html) return null;
1506
+ if (typeof DOMParser !== "undefined") {
1507
+ try {
1508
+ const parsed = new DOMParser().parseFromString(html, "text/html");
1509
+ const href = parsed.querySelector("base[href]")?.getAttribute("href");
1510
+ if (href?.trim()) return href.trim();
1511
+ } catch {
1512
+ }
1513
+ }
1514
+ const match = html.match(/<base\b[^>]*\bhref\s*=\s*["']([^"']+)["']/i);
1515
+ return match?.[1]?.trim() || null;
1516
+ }
1517
+ function resolveExplicitBaseUrl(html, resourceUri) {
1518
+ const baseHref = readExplicitBaseHref(html);
1519
+ if (!baseHref) return null;
1520
+ const absolute = toSafeOpenInAppUrl(baseHref);
1521
+ if (absolute) return absolute;
1522
+ const resourceUrl = toSafeOpenInAppUrl(resourceUri);
1523
+ if (!resourceUrl) return null;
1524
+ try {
1525
+ return toSafeOpenInAppUrl(new URL(baseHref, resourceUrl).href);
1526
+ } catch {
1527
+ return null;
1528
+ }
1529
+ }
1530
+ function resolveOpenInAppHref(href, explicitBaseUrl) {
1531
+ if (typeof href !== "string") return null;
1532
+ const trimmed = href.trim();
1533
+ if (!trimmed) return null;
1534
+ const absolute = toSafeOpenInAppUrl(trimmed);
1535
+ if (absolute) return absolute;
1536
+ if (!explicitBaseUrl) return null;
1537
+ try {
1538
+ return toSafeOpenInAppUrl(new URL(trimmed, explicitBaseUrl).href);
1539
+ } catch {
1540
+ return null;
1541
+ }
1542
+ }
1543
+ var MCPJAM_HOSTED_CLAMP_ORIGINS = [
1544
+ "https://*.mcpjam.com",
1545
+ "https://mcpjam.com"
1546
+ ];
1547
+ var sepHostStyleVariableKeysCache = /* @__PURE__ */ new WeakMap();
1548
+ function getSepHostStyleVariableKeys(defaultHostStyle) {
1549
+ const cached = sepHostStyleVariableKeysCache.get(defaultHostStyle);
1550
+ if (cached) return cached;
1551
+ const keys = /* @__PURE__ */ new Set([
1552
+ ...Object.keys(defaultHostStyle.mcp.resolveStyleVariables("light")),
1553
+ ...Object.keys(defaultHostStyle.mcp.resolveStyleVariables("dark"))
1554
+ ]);
1555
+ sepHostStyleVariableKeysCache.set(defaultHostStyle, keys);
1556
+ return keys;
1557
+ }
1558
+ function sanitizeHostStyleVariables(variables, sepHostStyleVariableKeys) {
1559
+ if (!variables || typeof variables !== "object" || Array.isArray(variables)) {
1560
+ return void 0;
1561
+ }
1562
+ const sanitized = {};
1563
+ for (const [key, value] of Object.entries(variables)) {
1564
+ if (!sepHostStyleVariableKeys.has(key)) {
1565
+ continue;
1566
+ }
1567
+ if (typeof value === "string" || value === void 0) {
1568
+ sanitized[key] = value;
1569
+ }
1570
+ }
1571
+ return Object.keys(sanitized).length > 0 ? sanitized : void 0;
1572
+ }
1573
+ function mapLogToLifecycle(method, details) {
1574
+ const kindByMethod = {
1575
+ "debug/sandbox-proxy-ready": "sandbox-proxy-ready",
1576
+ "debug/widget-content-requested": "widget-content-requested",
1577
+ "debug/widget-content-ready": "widget-content-ready",
1578
+ "debug/widget-content-error": "widget-content-error",
1579
+ "debug/widget-content-invalid-mimetype": "widget-content-invalid-mimetype",
1580
+ "debug/bridge-connect-start": "bridge-connect-start",
1581
+ "debug/bridge-connect-ready": "bridge-connect-ready",
1582
+ "debug/bridge-connect-error": "bridge-connect-error",
1583
+ "debug/bridge-connect-skipped": "bridge-connect-skipped",
1584
+ "debug/app-initialized": "app-initialized"
1585
+ };
1586
+ const kind = kindByMethod[method];
1587
+ if (!kind) return null;
1588
+ let status;
1589
+ if (method.endsWith("-error") || method === "debug/widget-content-invalid-mimetype") {
1590
+ status = "error";
1591
+ } else if (method.endsWith("-ready") || method === "debug/app-initialized" || method === "debug/bridge-connect-skipped") {
1592
+ status = "ok";
1593
+ } else {
1594
+ status = "pending";
1595
+ }
1596
+ const message = typeof details.error === "string" ? details.error : typeof details.reason === "string" ? details.reason : void 0;
1597
+ return { kind, status, message, timestamp: Date.now() };
1598
+ }
1599
+ var FETCH_SOURCE_KEY_SEGMENTS = [
1600
+ "resourceUri",
1601
+ "cachedReplayWidgetHtmlUrl",
1602
+ "cspMode",
1603
+ "fetchMode",
1604
+ // `injectOpenAiCompat` boolean and the per-method capability hash
1605
+ // are part of the rendering recipe: a host swap from ChatGPT-full
1606
+ // to Copilot-subset (or a master-toggle flip) changes the bytes
1607
+ // baked into the iframe, so a fetch issued under the old recipe
1608
+ // is stale by the time it resolves and must NOT overwrite the
1609
+ // newer commit's state. See plan §5.5 +
1610
+ // feedback_capability_in_render_recipe memory.
1611
+ "injectOpenAiCompat",
1612
+ "compatCapabilitiesHash",
1613
+ "mcpAppsCapabilitiesHash"
1614
+ ];
1615
+ function describeFetchSourceKeyDiff(prev, next) {
1616
+ const prevSegs = prev.split("|");
1617
+ const nextSegs = next.split("|");
1618
+ const changes = [];
1619
+ for (let i = 0; i < FETCH_SOURCE_KEY_SEGMENTS.length; i += 1) {
1620
+ if (prevSegs[i] !== nextSegs[i]) changes.push(FETCH_SOURCE_KEY_SEGMENTS[i]);
1621
+ }
1622
+ return changes.length === 0 ? "remount" : changes.join(", ");
1623
+ }
1624
+ function hashSurfaceIdentity(value) {
1625
+ let hash = 2166136261;
1626
+ for (let i = 0; i < value.length; i += 1) {
1627
+ hash ^= value.charCodeAt(i);
1628
+ hash = Math.imul(hash, 16777619);
1629
+ }
1630
+ return (hash >>> 0).toString(36);
1631
+ }
1632
+ function getPersistentSurfaceId(props) {
1633
+ const identity = stableStringifyJson({
1634
+ chatSessionId: props.chatSessionId ?? null,
1635
+ serverId: props.serverId,
1636
+ resourceUri: props.resourceUri,
1637
+ toolCallId: props.toolCallId,
1638
+ surface: "inline"
1639
+ });
1640
+ return `mcp-app:${hashSurfaceIdentity(identity)}`;
1641
+ }
1642
+ var pendingSurfaceReleaseTimers = /* @__PURE__ */ new Map();
1643
+ var pendingAnchorClearTimers = /* @__PURE__ */ new Map();
1644
+ function getSurfaceRegistrationKey(surfaceId, toolCallId) {
1645
+ return `${surfaceId}\0${toolCallId}`;
1646
+ }
1647
+ function cancelPendingAnchorClear(surfaceId, toolCallId) {
1648
+ const key = getSurfaceRegistrationKey(surfaceId, toolCallId);
1649
+ const timer = pendingAnchorClearTimers.get(key);
1650
+ if (timer === void 0) return;
1651
+ window.clearTimeout(timer);
1652
+ pendingAnchorClearTimers.delete(key);
1653
+ }
1654
+ function scheduleAnchorClear(surfaceId, toolCallId) {
1655
+ const key = getSurfaceRegistrationKey(surfaceId, toolCallId);
1656
+ const existing = pendingAnchorClearTimers.get(key);
1657
+ if (existing !== void 0) window.clearTimeout(existing);
1658
+ const timer = window.setTimeout(() => {
1659
+ pendingAnchorClearTimers.delete(key);
1660
+ useWidgetSurfaceStore.getState().setAnchor(surfaceId, toolCallId, null);
1661
+ }, 0);
1662
+ pendingAnchorClearTimers.set(key, timer);
1663
+ }
1664
+ function cancelPendingSurfaceRelease(surfaceId, toolCallId) {
1665
+ const key = getSurfaceRegistrationKey(surfaceId, toolCallId);
1666
+ const timer = pendingSurfaceReleaseTimers.get(key);
1667
+ if (timer === void 0) return;
1668
+ window.clearTimeout(timer);
1669
+ pendingSurfaceReleaseTimers.delete(key);
1670
+ }
1671
+ function scheduleSurfaceRelease(surfaceId, toolCallId) {
1672
+ const key = getSurfaceRegistrationKey(surfaceId, toolCallId);
1673
+ const existing = pendingSurfaceReleaseTimers.get(key);
1674
+ if (existing !== void 0) window.clearTimeout(existing);
1675
+ const timer = window.setTimeout(() => {
1676
+ pendingSurfaceReleaseTimers.delete(key);
1677
+ useWidgetSurfaceStore.getState().releaseRegistration(surfaceId, toolCallId);
1678
+ }, 0);
1679
+ pendingSurfaceReleaseTimers.set(key, timer);
1680
+ }
1681
+ function PersistentMCPAppsRendererRegistration(props) {
1682
+ const surfaceId = useMemo(
1683
+ () => getPersistentSurfaceId(props),
1684
+ [props.chatSessionId, props.resourceUri, props.serverId, props.toolCallId]
1685
+ );
1686
+ const anchorRef = useRef(null);
1687
+ useLayoutEffect(() => {
1688
+ cancelPendingAnchorClear(surfaceId, props.toolCallId);
1689
+ cancelPendingSurfaceRelease(surfaceId, props.toolCallId);
1690
+ return () => {
1691
+ scheduleSurfaceRelease(surfaceId, props.toolCallId);
1692
+ };
1693
+ }, [surfaceId, props.toolCallId]);
1694
+ useLayoutEffect(() => {
1695
+ cancelPendingAnchorClear(surfaceId, props.toolCallId);
1696
+ cancelPendingSurfaceRelease(surfaceId, props.toolCallId);
1697
+ const store = useWidgetSurfaceStore.getState();
1698
+ store.upsertRegistration(surfaceId, props.toolCallId, props);
1699
+ store.setAnchor(surfaceId, props.toolCallId, anchorRef.current);
1700
+ });
1701
+ const setAnchor = useCallback(
1702
+ (node) => {
1703
+ anchorRef.current = node;
1704
+ if (node === null) {
1705
+ scheduleAnchorClear(surfaceId, props.toolCallId);
1706
+ return;
1707
+ }
1708
+ cancelPendingAnchorClear(surfaceId, props.toolCallId);
1709
+ useWidgetSurfaceStore.getState().setAnchor(surfaceId, props.toolCallId, node);
1710
+ },
1711
+ [surfaceId, props.toolCallId]
1712
+ );
1713
+ return /* @__PURE__ */ jsx(
1714
+ "div",
1715
+ {
1716
+ ref: setAnchor,
1717
+ "data-mcp-app-surface-id": surfaceId,
1718
+ "data-mcp-app-surface-anchor": props.toolCallId
1719
+ }
1720
+ );
1721
+ }
1722
+ function MCPAppsRenderer(props) {
1723
+ const persistentHostEnabled = usePersistentWidgetSurfaceHost();
1724
+ const isCachedReplay = !!props.cachedWidgetHtmlUrl && !props.liveFetchPreferred;
1725
+ const shouldUsePersistentSurface = persistentHostEnabled && !props.isOffline && !isCachedReplay;
1726
+ if (!shouldUsePersistentSurface) {
1727
+ return /* @__PURE__ */ jsx(MCPAppsRendererSurface, { ...props });
1728
+ }
1729
+ return /* @__PURE__ */ jsx(PersistentMCPAppsRendererRegistration, { ...props });
1730
+ }
1731
+ function MCPAppsRendererSurface({
1732
+ chatSessionId,
1733
+ serverId,
1734
+ serverName,
1735
+ toolCallId,
1736
+ toolName,
1737
+ toolState,
1738
+ toolInput,
1739
+ toolOutput,
1740
+ toolResponseMetadata,
1741
+ toolErrorText,
1742
+ resourceUri,
1743
+ toolMetadata,
1744
+ toolsMetadata,
1745
+ onSendFollowUp,
1746
+ onCallTool,
1747
+ onAppToolInvocationChange,
1748
+ onWidgetStateChange,
1749
+ pipWidgetId,
1750
+ fullscreenWidgetId,
1751
+ onRequestPip,
1752
+ onExitPip,
1753
+ displayMode: displayModeProp,
1754
+ onDisplayModeChange,
1755
+ onRequestFullscreen,
1756
+ onExitFullscreen,
1757
+ onModelContextUpdate,
1758
+ onAppSupportedDisplayModesChange,
1759
+ onRequestTeardown,
1760
+ isOffline,
1761
+ cachedWidgetHtmlUrl,
1762
+ liveFetchPreferred,
1763
+ widgetCsp: initialWidgetCsp,
1764
+ widgetPermissions: initialWidgetPermissions,
1765
+ widgetPermissive: initialWidgetPermissive,
1766
+ prefersBorder: initialPrefersBorder,
1767
+ injectedOpenAiCompat: initialInjectedOpenAiCompat,
1768
+ injectedOpenAiCompatCapabilities: initialInjectedOpenAiCompatCapabilities,
1769
+ initialWidgetState,
1770
+ minimalMode = false,
1771
+ persistentSurfaceId,
1772
+ persistentSurfaceInitialToolCallId
1773
+ }) {
1774
+ const sandboxRef = useRef(null);
1775
+ const host = useWidgetHost();
1776
+ const Checkout = host.components?.Checkout;
1777
+ const debug = host.debug ?? NOOP_WIDGET_DEBUG_SINK;
1778
+ const { environment, resolvers } = host;
1779
+ const themeMode = environment.themeMode;
1780
+ const sharedHostStyle = environment.sharedHostStyle;
1781
+ const chatboxHostStyle = environment.chatboxHostStyle;
1782
+ const chatboxHostTheme = environment.chatboxHostTheme;
1783
+ const hostCapabilitiesOverride = environment.hostCapabilitiesOverride;
1784
+ const activeMcpProfileKey = environment.profileKey;
1785
+ const profileSandbox = environment.profileSandbox;
1786
+ const profileHostInfo = environment.profileHostInfo;
1787
+ const hostCapabilitiesOverrideKey = useMemo(
1788
+ () => resolvers.stableStringifyJson(hostCapabilitiesOverride ?? null),
1789
+ [hostCapabilitiesOverride]
1790
+ );
1791
+ const liveEffectiveCompatRuntime = useMemo(
1792
+ () => resolvers.resolveEffectiveCompatRuntime({
1793
+ hostStyle: chatboxHostStyle ?? sharedHostStyle
1794
+ }),
1795
+ [activeMcpProfileKey, chatboxHostStyle, sharedHostStyle]
1796
+ );
1797
+ const liveInjectOpenAiCompat = liveEffectiveCompatRuntime.injected;
1798
+ const liveOpenAiCompatCapabilities = liveEffectiveCompatRuntime.injected ? liveEffectiveCompatRuntime.capabilities : null;
1799
+ const isCachedReplay = !!cachedWidgetHtmlUrl && !liveFetchPreferred;
1800
+ const cachedReplayWidgetHtmlUrl = isCachedReplay ? cachedWidgetHtmlUrl : void 0;
1801
+ const widgetFetchModeKey = isCachedReplay ? "cached" : "live";
1802
+ const cachedReplayPrefersBorder = isCachedReplay ? initialPrefersBorder : void 0;
1803
+ const effectiveInjectOpenAiCompat = isCachedReplay && typeof initialInjectedOpenAiCompat === "boolean" ? initialInjectedOpenAiCompat : liveInjectOpenAiCompat;
1804
+ const draftHostContext = environment.draftHostContext;
1805
+ const baseHostContext = useMemo(
1806
+ () => draftHostContext && typeof draftHostContext === "object" && !Array.isArray(draftHostContext) ? draftHostContext : {},
1807
+ [draftHostContext]
1808
+ );
1809
+ const isPlaygroundActive = environment.isPlaygroundActive;
1810
+ const configuredHostTheme = resolvers.extractHostTheme(baseHostContext);
1811
+ const resolvedTheme = isPlaygroundActive ? configuredHostTheme ?? chatboxHostTheme ?? themeMode : chatboxHostTheme ?? themeMode;
1812
+ const webManagedServers = host.surface.webManagedServers;
1813
+ const webManagedServersRef = useRef(webManagedServers);
1814
+ webManagedServersRef.current = webManagedServers;
1815
+ const cspMode = host.surface.kind === "chatbox" || minimalMode ? "permissive" : host.surface.kind === "playground" ? host.surface.playgroundCspMode : "widget-declared";
1816
+ const playgroundLocale = environment.playgroundLocale;
1817
+ const playgroundTimeZone = environment.playgroundTimeZone;
1818
+ const fallbackLocale = isPlaygroundActive ? playgroundLocale : navigator.language || "en-US";
1819
+ const fallbackTimeZone = isPlaygroundActive ? playgroundTimeZone : Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
1820
+ const locale = typeof draftHostContext?.locale === "string" ? draftHostContext.locale : fallbackLocale;
1821
+ const timeZone = typeof draftHostContext?.timeZone === "string" ? draftHostContext.timeZone : fallbackTimeZone;
1822
+ const playgroundDisplayMode = environment.playgroundDisplayMode;
1823
+ const configuredDisplayMode = useMemo(
1824
+ () => resolvers.extractHostDisplayMode(draftHostContext),
1825
+ [draftHostContext]
1826
+ );
1827
+ const configuredAvailableDisplayModes = useMemo(
1828
+ () => resolvers.extractHostDisplayModes(draftHostContext),
1829
+ [draftHostContext]
1830
+ );
1831
+ const earlyEffectiveHostStyle = isPlaygroundActive ? sharedHostStyle : chatboxHostStyle;
1832
+ const earlyEffectiveMcpAppsCapabilities = useMemo(
1833
+ () => resolvers.resolveEffectiveMcpAppsCapabilities({
1834
+ hostStyle: earlyEffectiveHostStyle
1835
+ }),
1836
+ [activeMcpProfileKey, earlyEffectiveHostStyle]
1837
+ );
1838
+ const [appSupportedDisplayModes, setAppSupportedDisplayModes] = useState(void 0);
1839
+ const effectiveAvailableDisplayModes = useMemo(() => {
1840
+ const matrixModes = earlyEffectiveMcpAppsCapabilities.availableDisplayModes;
1841
+ const hostIntersection = matrixModes.filter(
1842
+ (m) => configuredAvailableDisplayModes.includes(m)
1843
+ );
1844
+ const baseHostModes = hostIntersection.length > 0 ? hostIntersection : matrixModes;
1845
+ if (!appSupportedDisplayModes || appSupportedDisplayModes.length === 0) {
1846
+ return baseHostModes;
1847
+ }
1848
+ const appIntersection = baseHostModes.filter(
1849
+ (m) => appSupportedDisplayModes.includes(m)
1850
+ );
1851
+ return appIntersection.length > 0 ? appIntersection : baseHostModes;
1852
+ }, [
1853
+ earlyEffectiveMcpAppsCapabilities.availableDisplayModes,
1854
+ configuredAvailableDisplayModes,
1855
+ appSupportedDisplayModes
1856
+ ]);
1857
+ const advertisedAvailableDisplayModes = useMemo(() => {
1858
+ if (!appSupportedDisplayModes || appSupportedDisplayModes.length === 0) {
1859
+ return effectiveAvailableDisplayModes;
1860
+ }
1861
+ const intersection = effectiveAvailableDisplayModes.filter(
1862
+ (m) => appSupportedDisplayModes.includes(m)
1863
+ );
1864
+ return intersection.length > 0 ? intersection : effectiveAvailableDisplayModes;
1865
+ }, [effectiveAvailableDisplayModes, appSupportedDisplayModes]);
1866
+ const playgroundCapabilities = environment.playgroundCapabilities;
1867
+ const deviceCapabilities = useMemo(() => {
1868
+ const configuredCapabilities = draftHostContext?.deviceCapabilities && typeof draftHostContext.deviceCapabilities === "object" && !Array.isArray(draftHostContext.deviceCapabilities) ? draftHostContext.deviceCapabilities : void 0;
1869
+ if (configuredCapabilities) {
1870
+ return {
1871
+ hover: configuredCapabilities.hover ?? true,
1872
+ touch: configuredCapabilities.touch ?? false
1873
+ };
1874
+ }
1875
+ return isPlaygroundActive ? playgroundCapabilities : { hover: true, touch: false };
1876
+ }, [draftHostContext, isPlaygroundActive, playgroundCapabilities]);
1877
+ const playgroundSafeAreaInsets = environment.playgroundSafeAreaInsets;
1878
+ const safeAreaInsets = useMemo(() => {
1879
+ const configuredSafeAreaInsets = draftHostContext?.safeAreaInsets && typeof draftHostContext.safeAreaInsets === "object" && !Array.isArray(draftHostContext.safeAreaInsets) ? draftHostContext.safeAreaInsets : void 0;
1880
+ if (configuredSafeAreaInsets) {
1881
+ return {
1882
+ top: configuredSafeAreaInsets.top ?? 0,
1883
+ right: configuredSafeAreaInsets.right ?? 0,
1884
+ bottom: configuredSafeAreaInsets.bottom ?? 0,
1885
+ left: configuredSafeAreaInsets.left ?? 0
1886
+ };
1887
+ }
1888
+ return isPlaygroundActive ? playgroundSafeAreaInsets : { top: 0, right: 0, bottom: 0, left: 0 };
1889
+ }, [draftHostContext, isPlaygroundActive, playgroundSafeAreaInsets]);
1890
+ const playgroundDeviceType = environment.playgroundDeviceType;
1891
+ const isControlled = displayModeProp !== void 0;
1892
+ const [internalDisplayMode, setInternalDisplayMode] = useState(
1893
+ resolvers.clampDisplayModeToAvailableModes(
1894
+ configuredDisplayMode ?? (isPlaygroundActive ? playgroundDisplayMode : "inline"),
1895
+ configuredAvailableDisplayModes
1896
+ )
1897
+ );
1898
+ const displayMode = isControlled ? displayModeProp : internalDisplayMode;
1899
+ const displayWidgetId = persistentSurfaceId ?? toolCallId;
1900
+ const ownsFullscreenDisplayMode = fullscreenWidgetId === displayWidgetId || fullscreenWidgetId === toolCallId;
1901
+ const ownsPipDisplayMode = pipWidgetId === displayWidgetId || pipWidgetId === toolCallId;
1902
+ const requestedDisplayMode = useMemo(() => {
1903
+ if (!isControlled) return displayMode;
1904
+ if (displayMode === "fullscreen" && ownsFullscreenDisplayMode) {
1905
+ return "fullscreen";
1906
+ }
1907
+ if (displayMode === "pip" && ownsPipDisplayMode) return "pip";
1908
+ return "inline";
1909
+ }, [
1910
+ displayMode,
1911
+ isControlled,
1912
+ ownsFullscreenDisplayMode,
1913
+ ownsPipDisplayMode
1914
+ ]);
1915
+ const effectiveDisplayMode = useMemo(
1916
+ () => resolvers.clampDisplayModeToAvailableModes(
1917
+ requestedDisplayMode,
1918
+ effectiveAvailableDisplayModes
1919
+ ),
1920
+ [requestedDisplayMode, effectiveAvailableDisplayModes]
1921
+ );
1922
+ useEffect(() => {
1923
+ if (effectiveDisplayMode !== "inline") {
1924
+ userPreferInlineRef.current = false;
1925
+ }
1926
+ }, [effectiveDisplayMode]);
1927
+ const setDisplayMode = useCallback(
1928
+ (mode) => {
1929
+ if (isControlled) {
1930
+ onDisplayModeChange?.(mode);
1931
+ } else {
1932
+ setInternalDisplayMode(mode);
1933
+ }
1934
+ if (mode === "fullscreen") {
1935
+ onRequestFullscreen?.(displayWidgetId);
1936
+ } else if (displayMode === "fullscreen") {
1937
+ onExitFullscreen?.(displayWidgetId);
1938
+ }
1939
+ },
1940
+ [
1941
+ isControlled,
1942
+ onDisplayModeChange,
1943
+ displayWidgetId,
1944
+ onRequestFullscreen,
1945
+ onExitFullscreen,
1946
+ displayMode
1947
+ ]
1948
+ );
1949
+ const lastForcedDisplayModeRef = useRef(null);
1950
+ useEffect(() => {
1951
+ if (requestedDisplayMode === effectiveDisplayMode) {
1952
+ lastForcedDisplayModeRef.current = null;
1953
+ return;
1954
+ }
1955
+ if (lastForcedDisplayModeRef.current === effectiveDisplayMode) {
1956
+ return;
1957
+ }
1958
+ lastForcedDisplayModeRef.current = effectiveDisplayMode;
1959
+ setDisplayMode(effectiveDisplayMode);
1960
+ }, [effectiveDisplayMode, requestedDisplayMode, setDisplayMode]);
1961
+ const [isReady, setIsReady] = useState(false);
1962
+ const [reinitCount, setReinitCount] = useState(0);
1963
+ const [loadError, setLoadError] = useState(null);
1964
+ const [widgetHtml, setWidgetHtml] = useState(null);
1965
+ const [openInAppUrlOverride, setOpenInAppUrlOverride] = useState(null);
1966
+ const [sandboxProxyReady, setSandboxProxyReady] = useState(false);
1967
+ const [bridgeTransportReady, setBridgeTransportReady] = useState(false);
1968
+ const explicitOpenInAppBaseUrl = useMemo(
1969
+ () => resolveExplicitBaseUrl(widgetHtml, resourceUri),
1970
+ [widgetHtml, resourceUri]
1971
+ );
1972
+ const defaultOpenInAppUrl = useMemo(
1973
+ () => explicitOpenInAppBaseUrl ?? toSafeOpenInAppUrl(resourceUri),
1974
+ [explicitOpenInAppBaseUrl, resourceUri]
1975
+ );
1976
+ const openInAppUrl = openInAppUrlOverride ?? defaultOpenInAppUrl;
1977
+ const openInAppLabel = serverName?.trim() || serverId.trim() || "App";
1978
+ const handleOpenInApp = useCallback(() => {
1979
+ if (!openInAppUrl) return;
1980
+ window.open(openInAppUrl, "_blank", "noopener,noreferrer");
1981
+ }, [openInAppUrl]);
1982
+ useEffect(() => {
1983
+ setOpenInAppUrlOverride(null);
1984
+ }, [toolCallId, resourceUri]);
1985
+ const cachedReplayInjectOpenAiCompat = typeof initialInjectedOpenAiCompat === "boolean" ? initialInjectedOpenAiCompat : null;
1986
+ const widgetInjectOpenAiCompatReloadKey = isCachedReplay ? cachedReplayInjectOpenAiCompat : effectiveInjectOpenAiCompat;
1987
+ const widgetCompatCapabilitiesReloadKey = isCachedReplay ? initialInjectedOpenAiCompatCapabilities ? resolvers.stableStringifyJson(initialInjectedOpenAiCompatCapabilities) : null : effectiveInjectOpenAiCompat ? resolvers.stableStringifyJson(liveOpenAiCompatCapabilities ?? null) : null;
1988
+ const widgetMcpAppsCapabilitiesReloadKey = isCachedReplay ? null : resolvers.stableStringifyJson(earlyEffectiveMcpAppsCapabilities);
1989
+ const requiresCompatOutputAtBoot = effectiveInjectOpenAiCompat && typeof toolMetadata?.["openai/outputTemplate"] === "string";
1990
+ const shouldWaitForCompatToolOutput = !isCachedReplay && requiresCompatOutputAtBoot && toolState !== "output-available";
1991
+ const [widgetCsp, setWidgetCsp] = useState(
1992
+ isCachedReplay ? void 0 : initialWidgetCsp ?? void 0
1993
+ );
1994
+ const [widgetPermissions, setWidgetPermissions] = useState(isCachedReplay ? void 0 : initialWidgetPermissions ?? void 0);
1995
+ const [widgetPermissive, setWidgetPermissive] = useState(
1996
+ isCachedReplay ? true : initialWidgetPermissive ?? false
1997
+ );
1998
+ const [prefersBorder, setPrefersBorder] = useState(
1999
+ initialPrefersBorder ?? true
2000
+ );
2001
+ const matrixGatedWidgetCsp = useMemo(() => {
2002
+ if (!widgetCsp) return widgetCsp;
2003
+ const m = earlyEffectiveMcpAppsCapabilities;
2004
+ if (m.cspFrameDomains && m.cspBaseUriDomains) return widgetCsp;
2005
+ const next = { ...widgetCsp };
2006
+ if (!m.cspFrameDomains) delete next.frameDomains;
2007
+ if (!m.cspBaseUriDomains) delete next.baseUriDomains;
2008
+ return next;
2009
+ }, [widgetCsp, earlyEffectiveMcpAppsCapabilities]);
2010
+ const matrixGatedWidgetPermissions = useMemo(() => {
2011
+ if (!earlyEffectiveMcpAppsCapabilities.sandboxPermissions) return void 0;
2012
+ return widgetPermissions;
2013
+ }, [widgetPermissions, earlyEffectiveMcpAppsCapabilities.sandboxPermissions]);
2014
+ const matrixGatedPrefersBorder = useMemo(() => {
2015
+ if (!earlyEffectiveMcpAppsCapabilities.resourcePrefersBorder) return false;
2016
+ return prefersBorder;
2017
+ }, [prefersBorder, earlyEffectiveMcpAppsCapabilities.resourcePrefersBorder]);
2018
+ const [loadedCspMode, setLoadedCspMode] = useState(null);
2019
+ const [loadedInjectOpenAiCompat, setLoadedInjectOpenAiCompat] = useState(null);
2020
+ const [loadedCompatCapabilitiesHash, setLoadedCompatCapabilitiesHash] = useState(null);
2021
+ const [loadedMcpAppsCapabilitiesHash, setLoadedMcpAppsCapabilitiesHash] = useState(null);
2022
+ const [modalOpen, setModalOpen] = useState(false);
2023
+ const [modalParams, setModalParams] = useState({});
2024
+ const [modalTitle, setModalTitle] = useState("");
2025
+ const [modalTemplate, setModalTemplate] = useState(null);
2026
+ const [checkoutOpen, setCheckoutOpen] = useState(false);
2027
+ const [checkoutSession, setCheckoutSession] = useState(null);
2028
+ const [checkoutCallId, setCheckoutCallId] = useState(null);
2029
+ useEffect(() => {
2030
+ setWidgetHtml(null);
2031
+ setBridgeTransportReady(false);
2032
+ setLoadedCspMode(null);
2033
+ setLoadedInjectOpenAiCompat(null);
2034
+ setLoadedCompatCapabilitiesHash(null);
2035
+ setLoadError(null);
2036
+ setWidgetCsp(void 0);
2037
+ setWidgetPermissions(void 0);
2038
+ setWidgetPermissive(isCachedReplay ? true : false);
2039
+ setPrefersBorder(cachedReplayPrefersBorder ?? true);
2040
+ }, [cachedReplayWidgetHtmlUrl, cachedReplayPrefersBorder, isCachedReplay]);
2041
+ const bridgeRef = useRef(null);
2042
+ const hostContextRef = useRef(null);
2043
+ const isReadyRef = useRef(false);
2044
+ const lastInlineHeightRef = useRef("400px");
2045
+ const userPreferInlineRef = useRef(
2046
+ earlyEffectiveMcpAppsCapabilities.widgetDisplayModeRequests === "user-initiated-only"
2047
+ );
2048
+ const hasAutoPromotedForAppToolsRef = useRef(false);
2049
+ const appToolsBridgeIdRef = useRef(null);
2050
+ const appToolsListedBridgeIdsRef = useRef(/* @__PURE__ */ new Set());
2051
+ const appToolsListInFlightBridgeIdsRef = useRef(/* @__PURE__ */ new Set());
2052
+ const appToolsListRefreshPendingBridgeIdsRef = useRef(/* @__PURE__ */ new Set());
2053
+ const [appToolsBridgeIdState, setAppToolsBridgeIdState] = useState(null);
2054
+ const pendingAppToolCalls = useAppToolsRegistry(
2055
+ (s) => appToolsBridgeIdState ? s.pendingControllers.get(appToolsBridgeIdState)?.size ?? 0 : 0
2056
+ );
2057
+ useEffect(() => {
2058
+ setAppSupportedDisplayModes(void 0);
2059
+ userPreferInlineRef.current = earlyEffectiveMcpAppsCapabilities.widgetDisplayModeRequests === "user-initiated-only";
2060
+ }, [
2061
+ resourceUri,
2062
+ cachedWidgetHtmlUrl,
2063
+ earlyEffectiveMcpAppsCapabilities.widgetDisplayModeRequests
2064
+ ]);
2065
+ const onSendFollowUpRef = useRef(onSendFollowUp);
2066
+ const onCallToolRef = useRef(onCallTool);
2067
+ const onAppToolInvocationChangeRef = useRef(onAppToolInvocationChange);
2068
+ const appToolInvocationSequenceRef = useRef(0);
2069
+ const onRequestPipRef = useRef(onRequestPip);
2070
+ const onExitPipRef = useRef(onExitPip);
2071
+ const onRequestTeardownRef = useRef(onRequestTeardown);
2072
+ const setDisplayModeRef = useRef(setDisplayMode);
2073
+ const isPlaygroundActiveRef = useRef(isPlaygroundActive);
2074
+ const playgroundDeviceTypeRef = useRef(playgroundDeviceType);
2075
+ const effectiveDisplayModeRef = useRef(effectiveDisplayMode);
2076
+ const serverIdRef = useRef(serverId);
2077
+ const toolCallIdRef = useRef(toolCallId);
2078
+ const displayWidgetIdRef = useRef(displayWidgetId);
2079
+ const pipWidgetIdRef = useRef(pipWidgetId);
2080
+ const ownsPipDisplayModeRef = useRef(ownsPipDisplayMode);
2081
+ const toolsMetadataRef = useRef(toolsMetadata);
2082
+ const onModelContextUpdateRef = useRef(onModelContextUpdate);
2083
+ const onAppSupportedDisplayModesChangeRef = useRef(
2084
+ onAppSupportedDisplayModesChange
2085
+ );
2086
+ const toolInputRef = useRef(toolInput);
2087
+ toolInputRef.current = toolInput;
2088
+ const toolOutputRef = useRef(toolOutput);
2089
+ toolOutputRef.current = toolOutput;
2090
+ const themeModeRef = useRef(themeMode);
2091
+ const latestFetchSourceKeyRef = useRef("");
2092
+ const prevLoggedFetchSourceKeyRef = useRef(null);
2093
+ const recordMountStore = debug.recordMount;
2094
+ const mcpAppsCapabilitiesRef = useRef(
2095
+ null
2096
+ );
2097
+ const {
2098
+ canRenderStreamingInput,
2099
+ signalStreamingRender,
2100
+ resetStreamingState
2101
+ } = useToolInputStreaming({
2102
+ bridgeRef,
2103
+ isReady,
2104
+ isReadyRef,
2105
+ toolState,
2106
+ toolInput,
2107
+ toolOutput,
2108
+ toolErrorText,
2109
+ toolCallId,
2110
+ sendToolInput: true,
2111
+ reinitCount,
2112
+ mcpAppsCapabilitiesRef
2113
+ });
2114
+ const hasWidgetHtml = widgetHtml !== null;
2115
+ const widgetHtmlLength = widgetHtml?.length ?? 0;
2116
+ useEffect(() => {
2117
+ const isActiveToolState = toolState === "input-streaming" || toolState === "input-available" || toolState === "output-available";
2118
+ if (!isActiveToolState) return;
2119
+ if (shouldWaitForCompatToolOutput) return;
2120
+ if (widgetHtml && loadedCspMode === cspMode && loadedInjectOpenAiCompat === widgetInjectOpenAiCompatReloadKey && loadedCompatCapabilitiesHash === widgetCompatCapabilitiesReloadKey && loadedMcpAppsCapabilitiesHash === widgetMcpAppsCapabilitiesReloadKey)
2121
+ return;
2122
+ const fetchSourceKey = [
2123
+ resourceUri ?? "",
2124
+ cachedReplayWidgetHtmlUrl ?? "",
2125
+ cspMode,
2126
+ widgetFetchModeKey,
2127
+ // String() so `null` (cached-replay sentinel), `true`, and
2128
+ // `false` all serialize distinctly into the pipe-joined key.
2129
+ String(widgetInjectOpenAiCompatReloadKey),
2130
+ widgetCompatCapabilitiesReloadKey ?? "",
2131
+ widgetMcpAppsCapabilitiesReloadKey ?? ""
2132
+ ].join("|");
2133
+ latestFetchSourceKeyRef.current = fetchSourceKey;
2134
+ if (prevLoggedFetchSourceKeyRef.current !== fetchSourceKey) {
2135
+ const prev = prevLoggedFetchSourceKeyRef.current;
2136
+ const reason = prev === null ? "initial" : describeFetchSourceKeyDiff(prev, fetchSourceKey);
2137
+ prevLoggedFetchSourceKeyRef.current = fetchSourceKey;
2138
+ recordMountStore(toolCallIdRef.current, reason);
2139
+ }
2140
+ const isStillCurrent = () => latestFetchSourceKeyRef.current === fetchSourceKey;
2141
+ const loadFromCachedUrl = async (cachedUrl) => {
2142
+ const cachedResponse = await fetch(cachedUrl);
2143
+ if (!cachedResponse.ok) {
2144
+ throw new Error(
2145
+ `Failed to fetch cached widget HTML: ${cachedResponse.statusText}`
2146
+ );
2147
+ }
2148
+ const html = await cachedResponse.text();
2149
+ if (!isStillCurrent()) return;
2150
+ setBridgeTransportReady(false);
2151
+ setWidgetHtml(html);
2152
+ setWidgetCsp(void 0);
2153
+ setWidgetPermissions(void 0);
2154
+ setWidgetPermissive(true);
2155
+ setPrefersBorder(initialPrefersBorder ?? true);
2156
+ setLoadedCspMode(cspMode);
2157
+ const loadedCachedCompatKey = isCachedReplay ? cachedReplayInjectOpenAiCompat : widgetInjectOpenAiCompatReloadKey;
2158
+ setLoadedInjectOpenAiCompat(loadedCachedCompatKey);
2159
+ setLoadedCompatCapabilitiesHash(widgetCompatCapabilitiesReloadKey);
2160
+ setLoadedMcpAppsCapabilitiesHash(widgetMcpAppsCapabilitiesReloadKey);
2161
+ setWidgetHtmlStore(
2162
+ toolCallIdRef.current,
2163
+ html,
2164
+ loadedCachedCompatKey ?? void 0,
2165
+ // Persisted capabilities flow into the debug store so a
2166
+ // "save view" round-trip from a cached replay (e.g. user
2167
+ // duplicates an old view) carries the original surface
2168
+ // forward instead of stamping the current live matrix.
2169
+ isCachedReplay ? initialInjectedOpenAiCompatCapabilities : liveOpenAiCompatCapabilities ?? void 0
2170
+ );
2171
+ logWidgetDebug("host-to-ui", "debug/widget-content-ready", {
2172
+ cached: true,
2173
+ cspMode,
2174
+ htmlLength: html.length,
2175
+ injectOpenAiCompat: loadedCachedCompatKey,
2176
+ permissive: true
2177
+ });
2178
+ };
2179
+ const loadFromLiveFetch = async () => {
2180
+ const {
2181
+ html,
2182
+ csp,
2183
+ permissions,
2184
+ permissive,
2185
+ mimeTypeWarning: warning,
2186
+ mimeTypeValid: valid,
2187
+ prefersBorder: prefersBorder2,
2188
+ injectedOpenAiCompat: serverInjectedOpenAiCompat,
2189
+ injectedOpenAiCompatCapabilities: serverInjectedOpenAiCompatCapabilities
2190
+ } = await host.services.fetchWidgetContent({
2191
+ serverId,
2192
+ forceWebEndpoint: webManagedServersRef.current,
2193
+ resourceUri,
2194
+ toolInput: toolInputRef.current,
2195
+ toolOutput: toolOutputRef.current,
2196
+ // Surface `_meta` from the tool response so the compat runtime
2197
+ // can expose it as `window.openai.toolResponseMetadata`. Prefer
2198
+ // the explicit `toolResponseMetadata` prop (which the caller
2199
+ // computes from rawOutput where the `{ value, _meta }` wrapper
2200
+ // is still intact); fall back to deriving from the resolved
2201
+ // output for callers that don't pass it.
2202
+ toolResponseMetadata: toolResponseMetadata ?? readToolResultMeta(toolOutputRef.current) ?? null,
2203
+ initialWidgetState,
2204
+ toolId: toolCallIdRef.current,
2205
+ toolName,
2206
+ theme: themeModeRef.current,
2207
+ cspMode,
2208
+ injectOpenAiCompat: effectiveInjectOpenAiCompat,
2209
+ // Per-method capability surface forwarded to the SDK runtime.
2210
+ // Sending this alongside `injectOpenAiCompat: true` is what
2211
+ // makes disabled methods omitted from `window.openai` in the
2212
+ // widget — without it, the runtime falls back to its full
2213
+ // surface default and feature detection lies. Send only when
2214
+ // we're actually injecting (capabilities are meaningless
2215
+ // without the shim).
2216
+ openAiCompatCapabilities: effectiveInjectOpenAiCompat && liveOpenAiCompatCapabilities ? liveOpenAiCompatCapabilities : void 0
2217
+ });
2218
+ const resolvedInjectedOpenAiCompat = typeof serverInjectedOpenAiCompat === "boolean" ? serverInjectedOpenAiCompat : effectiveInjectOpenAiCompat;
2219
+ const resolvedInjectedOpenAiCompatCapabilities = serverInjectedOpenAiCompatCapabilities ?? (resolvedInjectedOpenAiCompat ? liveOpenAiCompatCapabilities ?? void 0 : void 0);
2220
+ if (!isStillCurrent()) return true;
2221
+ if (!valid) {
2222
+ const errorMessage = warning || `Invalid mimetype - SEP-1865 requires "text/html;profile=mcp-app"`;
2223
+ setLoadError(errorMessage);
2224
+ logWidgetDebug("host-to-ui", "debug/widget-content-invalid-mimetype", {
2225
+ cspMode,
2226
+ error: errorMessage
2227
+ });
2228
+ return false;
2229
+ }
2230
+ setBridgeTransportReady(false);
2231
+ setWidgetHtml(html);
2232
+ setWidgetCsp(csp);
2233
+ setWidgetPermissions(permissions);
2234
+ setWidgetPermissive(permissive ?? false);
2235
+ setPrefersBorder(prefersBorder2 ?? true);
2236
+ setLoadedCspMode(cspMode);
2237
+ setLoadedInjectOpenAiCompat(resolvedInjectedOpenAiCompat);
2238
+ setLoadedCompatCapabilitiesHash(widgetCompatCapabilitiesReloadKey);
2239
+ setLoadedMcpAppsCapabilitiesHash(widgetMcpAppsCapabilitiesReloadKey);
2240
+ setWidgetHtmlStore(
2241
+ toolCallIdRef.current,
2242
+ html,
2243
+ resolvedInjectedOpenAiCompat,
2244
+ resolvedInjectedOpenAiCompatCapabilities
2245
+ );
2246
+ if (csp || permissions || !permissive) {
2247
+ setWidgetCspStore(toolCallIdRef.current, {
2248
+ mode: permissive ? "permissive" : "widget-declared",
2249
+ connectDomains: csp?.connectDomains || [],
2250
+ resourceDomains: csp?.resourceDomains || [],
2251
+ frameDomains: csp?.frameDomains || [],
2252
+ baseUriDomains: csp?.baseUriDomains || [],
2253
+ permissions,
2254
+ widgetDeclared: csp ? {
2255
+ connectDomains: csp.connectDomains,
2256
+ resourceDomains: csp.resourceDomains,
2257
+ frameDomains: csp.frameDomains,
2258
+ baseUriDomains: csp.baseUriDomains
2259
+ } : null
2260
+ });
2261
+ }
2262
+ logWidgetDebug("host-to-ui", "debug/widget-content-ready", {
2263
+ cached: false,
2264
+ cspMode,
2265
+ hasCsp: !!csp,
2266
+ hasPermissions: !!permissions,
2267
+ htmlLength: html.length,
2268
+ injectOpenAiCompat: resolvedInjectedOpenAiCompat,
2269
+ permissive: permissive ?? false,
2270
+ prefersBorder: prefersBorder2 ?? true
2271
+ });
2272
+ return true;
2273
+ };
2274
+ const fetchWidgetHtml = async () => {
2275
+ try {
2276
+ logWidgetDebug("host-to-ui", "debug/widget-content-requested", {
2277
+ cachedWidgetHtmlUrl: cachedWidgetHtmlUrl ?? null,
2278
+ cspMode,
2279
+ isOffline: !!isOffline,
2280
+ liveFetchPreferred: !!liveFetchPreferred,
2281
+ resourceUri,
2282
+ toolState: toolState ?? null
2283
+ });
2284
+ if (liveFetchPreferred && cachedWidgetHtmlUrl) {
2285
+ try {
2286
+ await loadFromLiveFetch();
2287
+ return;
2288
+ } catch (liveErr) {
2289
+ logWidgetDebug("host-to-ui", "debug/widget-content-live-fallback", {
2290
+ error: liveErr instanceof Error ? liveErr.message : String(liveErr)
2291
+ });
2292
+ await loadFromCachedUrl(cachedWidgetHtmlUrl);
2293
+ return;
2294
+ }
2295
+ }
2296
+ if (cachedWidgetHtmlUrl) {
2297
+ await loadFromCachedUrl(cachedWidgetHtmlUrl);
2298
+ return;
2299
+ }
2300
+ if (isOffline) {
2301
+ const errorMessage = "Server is offline and this view was saved without cached HTML. Connect the server and re-save the view to enable offline rendering.";
2302
+ setLoadError(errorMessage);
2303
+ logWidgetDebug("host-to-ui", "debug/widget-content-error", {
2304
+ error: errorMessage
2305
+ });
2306
+ return;
2307
+ }
2308
+ await loadFromLiveFetch();
2309
+ } catch (err) {
2310
+ if (!isStillCurrent()) return;
2311
+ const errorMessage = err instanceof Error ? err.message : "Failed to prepare widget";
2312
+ setLoadError(errorMessage);
2313
+ logWidgetDebug("host-to-ui", "debug/widget-content-error", {
2314
+ error: errorMessage
2315
+ });
2316
+ }
2317
+ };
2318
+ fetchWidgetHtml();
2319
+ }, [
2320
+ toolState,
2321
+ widgetHtml,
2322
+ loadedCspMode,
2323
+ loadedInjectOpenAiCompat,
2324
+ widgetInjectOpenAiCompatReloadKey,
2325
+ loadedCompatCapabilitiesHash,
2326
+ widgetCompatCapabilitiesReloadKey,
2327
+ loadedMcpAppsCapabilitiesHash,
2328
+ widgetMcpAppsCapabilitiesReloadKey,
2329
+ effectiveInjectOpenAiCompat,
2330
+ liveOpenAiCompatCapabilities,
2331
+ serverId,
2332
+ resourceUri,
2333
+ toolName,
2334
+ cspMode,
2335
+ isOffline,
2336
+ cachedWidgetHtmlUrl,
2337
+ cachedReplayWidgetHtmlUrl,
2338
+ liveFetchPreferred,
2339
+ widgetFetchModeKey,
2340
+ initialPrefersBorder,
2341
+ cachedReplayInjectOpenAiCompat,
2342
+ initialInjectedOpenAiCompatCapabilities,
2343
+ shouldWaitForCompatToolOutput,
2344
+ recordMountStore
2345
+ ]);
2346
+ const addUiLog = debug.addTrafficLog;
2347
+ const logUiEvent = useCallback(
2348
+ (payload) => {
2349
+ if (minimalMode) return;
2350
+ addUiLog(payload);
2351
+ },
2352
+ [addUiLog, minimalMode]
2353
+ );
2354
+ const logUiEventRef = useRef(logUiEvent);
2355
+ logUiEventRef.current = logUiEvent;
2356
+ const logWidgetDebug = useCallback(
2357
+ (direction, method, details) => {
2358
+ logUiEventRef.current({
2359
+ widgetId: toolCallIdRef.current,
2360
+ serverId: serverIdRef.current,
2361
+ direction,
2362
+ protocol: "mcp-apps",
2363
+ method,
2364
+ message: details
2365
+ });
2366
+ const mapped = mapLogToLifecycle(method, details);
2367
+ if (mapped !== null) {
2368
+ const toolCallId2 = toolCallIdRef.current;
2369
+ if (toolCallId2) appendLifecycleRef.current(toolCallId2, mapped);
2370
+ }
2371
+ },
2372
+ []
2373
+ );
2374
+ const refreshAppProvidedTools = useCallback(
2375
+ async (bridge, bridgeId, options = {}) => {
2376
+ const surface = options.surface ?? "inline";
2377
+ const getIframeElement = options.getIframeElement ?? (() => sandboxRef.current?.getIframeElement() ?? null);
2378
+ const isLive = options.isLive ?? (() => appToolsBridgeIdRef.current === bridgeId);
2379
+ const alreadyListed = appToolsListedBridgeIdsRef.current.has(bridgeId);
2380
+ const inFlight = appToolsListInFlightBridgeIdsRef.current.has(bridgeId);
2381
+ if (inFlight) {
2382
+ if (options.force) {
2383
+ appToolsListRefreshPendingBridgeIdsRef.current.add(bridgeId);
2384
+ }
2385
+ return;
2386
+ }
2387
+ if (!options.force && alreadyListed) return;
2388
+ appToolsListInFlightBridgeIdsRef.current.add(bridgeId);
2389
+ try {
2390
+ let needsRefresh = true;
2391
+ while (needsRefresh) {
2392
+ appToolsListRefreshPendingBridgeIdsRef.current.delete(bridgeId);
2393
+ const tools = [];
2394
+ let cursor;
2395
+ for (let page = 0; page < 8; page += 1) {
2396
+ const result = await bridge.listTools(
2397
+ cursor === void 0 ? {} : { cursor }
2398
+ );
2399
+ tools.push(
2400
+ ...(result.tools ?? []).filter(
2401
+ (t) => Boolean(t && typeof t.name === "string" && t.name.length > 0)
2402
+ )
2403
+ );
2404
+ cursor = result.nextCursor;
2405
+ if (!cursor) break;
2406
+ }
2407
+ appToolsListedBridgeIdsRef.current.add(bridgeId);
2408
+ if (!isLive()) return;
2409
+ const appVersion = bridge.getAppVersion();
2410
+ await useAppToolsRegistry.getState().registerInstance({
2411
+ bridgeId,
2412
+ chatSessionId,
2413
+ parentToolCallId: toolCallIdRef.current,
2414
+ serverId: serverIdRef.current,
2415
+ appName: appVersion?.name ?? serverIdRef.current,
2416
+ appVersion: appVersion?.version,
2417
+ surface,
2418
+ bridge,
2419
+ tools,
2420
+ registeredAtMs: Date.now(),
2421
+ // Stable closure: the inline default reads `sandboxRef.current`
2422
+ // which is React-managed and tracks the live SandboxedIframe
2423
+ // across re-renders. The modal passes its own accessor against
2424
+ // `modalSandboxRef`.
2425
+ getIframeElement
2426
+ });
2427
+ if (!isLive()) {
2428
+ useAppToolsRegistry.getState().unregisterInstance(bridgeId);
2429
+ return;
2430
+ }
2431
+ needsRefresh = appToolsListRefreshPendingBridgeIdsRef.current.has(bridgeId);
2432
+ }
2433
+ } catch (err) {
2434
+ appToolsListedBridgeIdsRef.current.delete(bridgeId);
2435
+ logWidgetDebug("ui-to-host", "debug/app-tools-list-failed", {
2436
+ error: err instanceof Error ? err.message : String(err)
2437
+ });
2438
+ } finally {
2439
+ appToolsListInFlightBridgeIdsRef.current.delete(bridgeId);
2440
+ }
2441
+ },
2442
+ [chatSessionId, logWidgetDebug]
2443
+ );
2444
+ const setWidgetDebugInfo = debug.setWidgetDebugInfo;
2445
+ const setWidgetGlobals = debug.setWidgetGlobals;
2446
+ const setWidgetStateStore = debug.setWidgetState;
2447
+ const setWidgetCspStore = debug.setWidgetCsp;
2448
+ const addCspViolation = debug.addCspViolation;
2449
+ const clearCspViolations = debug.clearCspViolations;
2450
+ const setWidgetModelContext = debug.setWidgetModelContext;
2451
+ const setWidgetHtmlStore = debug.setWidgetHtml;
2452
+ const setSandboxAppliedStore = debug.setSandboxApplied;
2453
+ const appendLifecycleStore = debug.appendLifecycle;
2454
+ const appendLifecycleRef = useRef(appendLifecycleStore);
2455
+ appendLifecycleRef.current = appendLifecycleStore;
2456
+ useEffect(() => {
2457
+ if (loadedCspMode !== null && loadedCspMode !== cspMode) {
2458
+ clearCspViolations(toolCallId);
2459
+ }
2460
+ }, [cspMode, loadedCspMode, toolCallId, clearCspViolations]);
2461
+ useEffect(() => {
2462
+ const injectionChanged = loadedInjectOpenAiCompat !== null && loadedInjectOpenAiCompat !== widgetInjectOpenAiCompatReloadKey;
2463
+ const capabilitiesChanged = loadedCompatCapabilitiesHash !== null && loadedCompatCapabilitiesHash !== widgetCompatCapabilitiesReloadKey || loadedMcpAppsCapabilitiesHash !== null && loadedMcpAppsCapabilitiesHash !== widgetMcpAppsCapabilitiesReloadKey;
2464
+ if (injectionChanged || capabilitiesChanged) {
2465
+ clearCspViolations(toolCallId);
2466
+ }
2467
+ }, [
2468
+ widgetInjectOpenAiCompatReloadKey,
2469
+ loadedInjectOpenAiCompat,
2470
+ widgetCompatCapabilitiesReloadKey,
2471
+ loadedCompatCapabilitiesHash,
2472
+ widgetMcpAppsCapabilitiesReloadKey,
2473
+ loadedMcpAppsCapabilitiesHash,
2474
+ toolCallId,
2475
+ clearCspViolations
2476
+ ]);
2477
+ useEffect(() => {
2478
+ if (loadedCspMode !== null && loadedCspMode !== cspMode) {
2479
+ setIsReady(false);
2480
+ isReadyRef.current = false;
2481
+ resetStreamingState();
2482
+ }
2483
+ }, [cspMode, loadedCspMode, resetStreamingState]);
2484
+ useEffect(() => {
2485
+ const injectionChanged = loadedInjectOpenAiCompat !== null && loadedInjectOpenAiCompat !== widgetInjectOpenAiCompatReloadKey;
2486
+ const capabilitiesChanged = loadedCompatCapabilitiesHash !== null && loadedCompatCapabilitiesHash !== widgetCompatCapabilitiesReloadKey || loadedMcpAppsCapabilitiesHash !== null && loadedMcpAppsCapabilitiesHash !== widgetMcpAppsCapabilitiesReloadKey;
2487
+ if (injectionChanged || capabilitiesChanged) {
2488
+ setIsReady(false);
2489
+ isReadyRef.current = false;
2490
+ resetStreamingState();
2491
+ }
2492
+ }, [
2493
+ widgetInjectOpenAiCompatReloadKey,
2494
+ loadedInjectOpenAiCompat,
2495
+ widgetCompatCapabilitiesReloadKey,
2496
+ loadedCompatCapabilitiesHash,
2497
+ widgetMcpAppsCapabilitiesReloadKey,
2498
+ loadedMcpAppsCapabilitiesHash,
2499
+ resetStreamingState
2500
+ ]);
2501
+ useEffect(() => {
2502
+ if (isPlaygroundActive && !isControlled) {
2503
+ setInternalDisplayMode(
2504
+ resolvers.clampDisplayModeToAvailableModes(
2505
+ configuredDisplayMode ?? playgroundDisplayMode,
2506
+ configuredAvailableDisplayModes
2507
+ )
2508
+ );
2509
+ }
2510
+ }, [
2511
+ configuredAvailableDisplayModes,
2512
+ configuredDisplayMode,
2513
+ isPlaygroundActive,
2514
+ playgroundDisplayMode,
2515
+ isControlled
2516
+ ]);
2517
+ useEffect(() => {
2518
+ setWidgetDebugInfo(toolCallId, {
2519
+ toolName,
2520
+ protocol: "mcp-apps",
2521
+ // Seed from persisted state when a saved view / fork supplied one,
2522
+ // so the Debug "Widget State" tab shows the restored value on
2523
+ // first render instead of `null`. Apps SDK widgets that call
2524
+ // window.openai.setWidgetState() later will overwrite this via
2525
+ // setWidgetStateStore in the openai:setWidgetState handler below.
2526
+ widgetState: initialWidgetState ?? null,
2527
+ prefersBorder,
2528
+ globals: {
2529
+ theme: resolvedTheme,
2530
+ displayMode: effectiveDisplayMode,
2531
+ locale,
2532
+ timeZone,
2533
+ deviceCapabilities,
2534
+ safeAreaInsets
2535
+ }
2536
+ });
2537
+ }, [
2538
+ toolCallId,
2539
+ toolName,
2540
+ setWidgetDebugInfo,
2541
+ resolvedTheme,
2542
+ effectiveDisplayMode,
2543
+ locale,
2544
+ timeZone,
2545
+ deviceCapabilities,
2546
+ safeAreaInsets,
2547
+ prefersBorder,
2548
+ initialWidgetState
2549
+ ]);
2550
+ useEffect(() => {
2551
+ setWidgetGlobals(toolCallId, {
2552
+ theme: resolvedTheme,
2553
+ displayMode: effectiveDisplayMode,
2554
+ locale,
2555
+ timeZone,
2556
+ deviceCapabilities,
2557
+ safeAreaInsets
2558
+ });
2559
+ }, [
2560
+ toolCallId,
2561
+ resolvedTheme,
2562
+ effectiveDisplayMode,
2563
+ locale,
2564
+ timeZone,
2565
+ deviceCapabilities,
2566
+ safeAreaInsets,
2567
+ setWidgetGlobals
2568
+ ]);
2569
+ const effectiveHostStyle = isPlaygroundActive ? sharedHostStyle : chatboxHostStyle;
2570
+ const hostStyleDefinition = resolvers.getHostStyleOrDefault(effectiveHostStyle);
2571
+ const activeShimCapabilities = isCachedReplay ? initialInjectedOpenAiCompatCapabilities ?? null : liveOpenAiCompatCapabilities;
2572
+ const liveOpenAiCompatCapabilitiesRef = useRef(
2573
+ activeShimCapabilities
2574
+ );
2575
+ liveOpenAiCompatCapabilitiesRef.current = activeShimCapabilities;
2576
+ const effectiveHostCapabilities = useMemo(
2577
+ () => resolvers.resolveEffectiveHostCapabilities({
2578
+ hostStyle: effectiveHostStyle,
2579
+ hostCapabilitiesOverride
2580
+ }),
2581
+ [effectiveHostStyle, activeMcpProfileKey, hostCapabilitiesOverrideKey]
2582
+ );
2583
+ const effectiveMcpAppsCapabilities = earlyEffectiveMcpAppsCapabilities;
2584
+ mcpAppsCapabilitiesRef.current = effectiveMcpAppsCapabilities;
2585
+ themeModeRef.current = resolvedTheme;
2586
+ const styleVariables = useMemo(
2587
+ () => hostStyleDefinition.mcp.resolveStyleVariables(resolvedTheme),
2588
+ [resolvedTheme, hostStyleDefinition]
2589
+ );
2590
+ const hostChatBackground = useMemo(
2591
+ () => hostStyleDefinition.chatUi.resolveChatBackground(resolvedTheme),
2592
+ [hostStyleDefinition, resolvedTheme]
2593
+ );
2594
+ const defaultFontCss = hostStyleDefinition.mcp.fontCss;
2595
+ const configuredStyles = baseHostContext.styles && typeof baseHostContext.styles === "object" && !Array.isArray(baseHostContext.styles) ? baseHostContext.styles : void 0;
2596
+ const sepHostStyleVariableKeys = getSepHostStyleVariableKeys(
2597
+ resolvers.DEFAULT_HOST_STYLE
2598
+ );
2599
+ const configuredStyleVariables = useMemo(
2600
+ () => sanitizeHostStyleVariables(
2601
+ configuredStyles?.variables,
2602
+ sepHostStyleVariableKeys
2603
+ ),
2604
+ [configuredStyles?.variables, sepHostStyleVariableKeys]
2605
+ );
2606
+ const mergedStyleVariables = useMemo(() => {
2607
+ return {
2608
+ ...styleVariables,
2609
+ ...configuredStyleVariables && Object.keys(configuredStyleVariables).length > 0 ? configuredStyleVariables : {}
2610
+ };
2611
+ }, [configuredStyleVariables, styleVariables]);
2612
+ const mergedStyles = useMemo(
2613
+ () => ({
2614
+ ...configuredStyles,
2615
+ variables: mergedStyleVariables,
2616
+ css: {
2617
+ ...configuredStyles?.css,
2618
+ fonts: configuredStyles?.css?.fonts ?? defaultFontCss
2619
+ }
2620
+ }),
2621
+ [configuredStyles, defaultFontCss, mergedStyleVariables]
2622
+ );
2623
+ const hostContext = useMemo(() => {
2624
+ const { toolInfo: _toolInfoFromBase, ...baseWithoutToolInfo } = baseHostContext;
2625
+ const base = {
2626
+ ...baseWithoutToolInfo,
2627
+ theme: resolvedTheme,
2628
+ displayMode: effectiveDisplayMode,
2629
+ // Publish the (host ∩ app) intersection here so the view sees the
2630
+ // narrowed set it can `requestDisplayMode` against. The current
2631
+ // `displayMode` above stays clamped to host-supported only.
2632
+ availableDisplayModes: advertisedAvailableDisplayModes,
2633
+ locale,
2634
+ timeZone,
2635
+ platform: baseHostContext.platform === "web" || baseHostContext.platform === "desktop" || baseHostContext.platform === "mobile" ? baseHostContext.platform : hostStyleDefinition.mcp.platform,
2636
+ userAgent: navigator.userAgent,
2637
+ deviceCapabilities,
2638
+ safeAreaInsets,
2639
+ styles: mergedStyles
2640
+ };
2641
+ if (effectiveMcpAppsCapabilities.toolInfo) {
2642
+ base.toolInfo = {
2643
+ id: toolCallId,
2644
+ tool: {
2645
+ name: toolName,
2646
+ inputSchema: toolMetadata?.inputSchema ?? DEFAULT_INPUT_SCHEMA,
2647
+ description: toolMetadata?.description
2648
+ }
2649
+ };
2650
+ }
2651
+ return base;
2652
+ }, [
2653
+ baseHostContext,
2654
+ resolvedTheme,
2655
+ effectiveDisplayMode,
2656
+ advertisedAvailableDisplayModes,
2657
+ locale,
2658
+ timeZone,
2659
+ deviceCapabilities,
2660
+ safeAreaInsets,
2661
+ mergedStyles,
2662
+ hostStyleDefinition,
2663
+ toolCallId,
2664
+ toolName,
2665
+ toolMetadata,
2666
+ effectiveMcpAppsCapabilities.toolInfo
2667
+ ]);
2668
+ useEffect(() => {
2669
+ hostContextRef.current = hostContext;
2670
+ }, [hostContext]);
2671
+ const sandboxCspPolicy = useMemo(
2672
+ () => profileSandbox?.csp,
2673
+ [activeMcpProfileKey]
2674
+ );
2675
+ const sandboxPermissionsPolicy = useMemo(
2676
+ () => profileSandbox?.permissions,
2677
+ [activeMcpProfileKey]
2678
+ );
2679
+ const sandboxAttrsPolicy = useMemo(
2680
+ () => profileSandbox?.sandboxAttrs,
2681
+ [activeMcpProfileKey]
2682
+ );
2683
+ const allowFeaturesPolicy = useMemo(
2684
+ () => profileSandbox?.allowFeatures,
2685
+ [activeMcpProfileKey]
2686
+ );
2687
+ const cspDirectivesPolicy = useMemo(
2688
+ () => profileSandbox?.csp?.cspDirectives,
2689
+ [activeMcpProfileKey]
2690
+ );
2691
+ const cspDirectivesEffective = useMemo(() => {
2692
+ if (!cspDirectivesPolicy) return cspDirectivesPolicy;
2693
+ if (!host.surface.hostedMode) return cspDirectivesPolicy;
2694
+ const isClampBypass = (token) => {
2695
+ if (token === "'self'") return true;
2696
+ if (token.startsWith("'")) return false;
2697
+ if (token === "*") return true;
2698
+ if (/^(https?|wss?):$/i.test(token)) return true;
2699
+ if (/^[a-z]+:$/.test(token)) return false;
2700
+ return /(?:^|[/.@])mcpjam\.com(?:[:/]|$)/i.test(token);
2701
+ };
2702
+ const out = {};
2703
+ for (const [k, tokens] of Object.entries(cspDirectivesPolicy)) {
2704
+ const clamped = tokens.map((t) => t.trim()).filter((t) => t.length > 0 && !isClampBypass(t));
2705
+ if (clamped.length > 0) out[k] = clamped;
2706
+ }
2707
+ return Object.keys(out).length > 0 ? out : void 0;
2708
+ }, [cspDirectivesPolicy]);
2709
+ const effectiveSandbox = useMemo(() => {
2710
+ const restrictToConfigured = sandboxCspPolicy?.restrictTo !== void 0 && Object.values(sandboxCspPolicy.restrictTo).some(
2711
+ (list) => Array.isArray(list) && list.length > 0
2712
+ );
2713
+ const cspDirectivesConfigured = sandboxCspPolicy?.cspDirectives !== void 0 && Object.values(sandboxCspPolicy.cspDirectives).some(
2714
+ (tokens) => Array.isArray(tokens) && tokens.some((t) => {
2715
+ if (typeof t !== "string") return false;
2716
+ const trimmed = t.trim();
2717
+ if (trimmed.length === 0) return false;
2718
+ if (/[;,\n\r"<>]/.test(trimmed)) return false;
2719
+ return true;
2720
+ })
2721
+ );
2722
+ const userTogglePermissive = cspMode === "permissive" && isPlaygroundActive && host.surface.kind !== "chatbox" && !minimalMode;
2723
+ if (userTogglePermissive) {
2724
+ let resolvedPermissions2;
2725
+ if (sandboxPermissionsPolicy) {
2726
+ const resourcePermsMap = {};
2727
+ if (matrixGatedWidgetPermissions && typeof matrixGatedWidgetPermissions === "object") {
2728
+ for (const [k, v] of Object.entries(
2729
+ matrixGatedWidgetPermissions
2730
+ )) {
2731
+ if (v) resourcePermsMap[k] = true;
2732
+ }
2733
+ }
2734
+ const resolved = resolveSandboxPermissions({
2735
+ resourcePermissions: resourcePermsMap,
2736
+ policy: sandboxPermissionsPolicy,
2737
+ hostedMode: host.surface.hostedMode
2738
+ });
2739
+ const out = {};
2740
+ for (const name of Object.keys(resolved.granted)) {
2741
+ out[name] = {};
2742
+ }
2743
+ resolvedPermissions2 = out;
2744
+ }
2745
+ return {
2746
+ csp: void 0,
2747
+ // Same gate on the pass-through fallback: when no sandbox
2748
+ // policy applies, the playground's permissive surface MUST
2749
+ // NOT propagate widget-declared permissions that the host
2750
+ // matrix says to ignore.
2751
+ permissions: resolvedPermissions2 ?? matrixGatedWidgetPermissions,
2752
+ permissive: true,
2753
+ hostPolicyApplied: !!resolvedPermissions2,
2754
+ sandboxAttrs: sandboxAttrsPolicy,
2755
+ allowFeatures: allowFeaturesPolicy,
2756
+ cspDirectives: cspDirectivesEffective
2757
+ };
2758
+ }
2759
+ const isPureRelaxedCsp = sandboxCspPolicy?.mode === "relaxed" && !restrictToConfigured && !cspDirectivesConfigured && !host.surface.hostedMode;
2760
+ let resolvedCsp;
2761
+ if (sandboxCspPolicy && !isPureRelaxedCsp) {
2762
+ const resolved = resolveSandboxCsp({
2763
+ // Matrix-gated: `cspFrameDomains` / `cspBaseUriDomains` off
2764
+ // strips those sub-fields from the widget-declared CSP before
2765
+ // the resolver sees them, simulating hosts (Microsoft 365
2766
+ // Copilot) that don't honor those `_meta.ui.csp.*` fields.
2767
+ resourceCsp: matrixGatedWidgetCsp,
2768
+ policy: sandboxCspPolicy,
2769
+ // "host-default" mode falls back to an EMPTY allowlist inside
2770
+ // the resolver when `hostDefaultBaseline` is omitted (per
2771
+ // SEP-1865 secure-default). For the inspector, the only sensible
2772
+ // default baseline we have is the resource's own declaration —
2773
+ // passing it here means "host-default" is restrictive only as
2774
+ // much as the resource itself asked for (never more, possibly
2775
+ // less if restrictTo narrows it). Without this, picking
2776
+ // "host-default" would silently emit `connect-src 'none'` and
2777
+ // break any widget that fetches external assets.
2778
+ hostDefaultBaseline: matrixGatedWidgetCsp,
2779
+ hostedMode: host.surface.hostedMode,
2780
+ // Defense in depth: in hosted mode strip any widget-declared
2781
+ // domain matching MCPJam's own app/API origins. A hosted widget
2782
+ // that declares `https://app.mcpjam.com/api/...` in
2783
+ // connectDomains could otherwise use the iframe as an
2784
+ // exfiltration channel via the user's authenticated session.
2785
+ // The list is hardcoded here (and not in the SDK) because
2786
+ // "which origins count as MCPJam" is an inspector concern, not
2787
+ // a shared SDK concern; the SDK just enforces what we pass.
2788
+ // Wildcard pattern strips all subdomains incl. staging/api.
2789
+ hostedClampExtraDeny: host.surface.hostedMode ? {
2790
+ // Spread the readonly constant into mutable arrays — the
2791
+ // SDK's `SandboxCspDomainSet` shape declares them as
2792
+ // `string[]`. Spreading per directive avoids accidental
2793
+ // aliasing if the SDK ever mutates internally.
2794
+ connectDomains: [...MCPJAM_HOSTED_CLAMP_ORIGINS],
2795
+ resourceDomains: [...MCPJAM_HOSTED_CLAMP_ORIGINS],
2796
+ frameDomains: [...MCPJAM_HOSTED_CLAMP_ORIGINS],
2797
+ baseUriDomains: [...MCPJAM_HOSTED_CLAMP_ORIGINS]
2798
+ } : void 0
2799
+ });
2800
+ resolvedCsp = {
2801
+ connectDomains: resolved.connectDomains,
2802
+ resourceDomains: resolved.resourceDomains,
2803
+ frameDomains: resolved.frameDomains,
2804
+ baseUriDomains: resolved.baseUriDomains
2805
+ };
2806
+ }
2807
+ let resolvedPermissions;
2808
+ if (sandboxPermissionsPolicy) {
2809
+ const resourcePermsMap = {};
2810
+ if (matrixGatedWidgetPermissions && typeof matrixGatedWidgetPermissions === "object") {
2811
+ for (const [k, v] of Object.entries(
2812
+ matrixGatedWidgetPermissions
2813
+ )) {
2814
+ if (v) resourcePermsMap[k] = true;
2815
+ }
2816
+ }
2817
+ const resolved = resolveSandboxPermissions({
2818
+ resourcePermissions: resourcePermsMap,
2819
+ policy: sandboxPermissionsPolicy,
2820
+ hostedMode: host.surface.hostedMode
2821
+ });
2822
+ const out = {};
2823
+ for (const name of Object.keys(resolved.granted)) {
2824
+ out[name] = {};
2825
+ }
2826
+ resolvedPermissions = out;
2827
+ }
2828
+ const hostPolicyApplied = !!resolvedCsp || !!resolvedPermissions || isPureRelaxedCsp;
2829
+ return {
2830
+ // Pure relaxed → no CSP at all (caller's `permissive: true` below
2831
+ // tells SandboxedIframe to skip CSP injection). Otherwise pass
2832
+ // the resolver output through, falling back to the widget's own
2833
+ // derivation when no host CSP policy is in force.
2834
+ // Use matrix-gated CSP / permissions as the fallback too, so a
2835
+ // Copilot host whose matrix turns frameDomains off doesn't
2836
+ // accidentally pass the un-gated value to the iframe via the
2837
+ // `?? widgetCsp` branch.
2838
+ csp: isPureRelaxedCsp ? void 0 : resolvedCsp ?? (widgetPermissive ? void 0 : matrixGatedWidgetCsp),
2839
+ permissions: resolvedPermissions ?? matrixGatedWidgetPermissions,
2840
+ // A host-applied CSP MUST be honored at the browser layer. When
2841
+ // a restrictive host policy is in force, force `permissive: false`
2842
+ // so the SandboxedIframe injects the meta-CSP. In pure-relaxed
2843
+ // mode the host policy is "permissive on purpose" → force
2844
+ // `permissive: true` so the iframe doesn't inject any meta-CSP
2845
+ // at all. Without host-side CSP policy, pass the widget-derived
2846
+ // flag through.
2847
+ //
2848
+ // Gate ONLY on `resolvedCsp` (not `resolvedPermissions`): a
2849
+ // permissions-only profile (e.g. `mode: "deny-all"` for camera/
2850
+ // mic) used to flip `permissive: false` while `csp` stayed
2851
+ // undefined, which the sandbox proxy interprets as the SEP-1865
2852
+ // secure-default CSP (`default-src 'none'`, `connect-src 'none'`)
2853
+ // — silently breaking network access for permissive widgets.
2854
+ // Permissions and CSP are orthogonal user-facing knobs; tweaking
2855
+ // one must not reshape the other.
2856
+ permissive: isPureRelaxedCsp ? true : resolvedCsp ? false : widgetPermissive,
2857
+ hostPolicyApplied,
2858
+ sandboxAttrs: sandboxAttrsPolicy,
2859
+ allowFeatures: allowFeaturesPolicy,
2860
+ cspDirectives: cspDirectivesEffective
2861
+ };
2862
+ }, [
2863
+ cspMode,
2864
+ isPlaygroundActive,
2865
+ host.surface.kind,
2866
+ minimalMode,
2867
+ sandboxCspPolicy,
2868
+ sandboxPermissionsPolicy,
2869
+ matrixGatedWidgetCsp,
2870
+ matrixGatedWidgetPermissions,
2871
+ widgetPermissive,
2872
+ sandboxAttrsPolicy,
2873
+ allowFeaturesPolicy,
2874
+ cspDirectivesEffective
2875
+ ]);
2876
+ const sandboxHostInfo = useMemo(() => {
2877
+ const raw = profileHostInfo;
2878
+ if (!raw || typeof raw !== "object") return null;
2879
+ const name = raw.name;
2880
+ const version = raw.version;
2881
+ if (typeof name !== "string" || typeof version !== "string") return null;
2882
+ if (name.trim() === "" || version.trim() === "") return null;
2883
+ return { name, version };
2884
+ }, [activeMcpProfileKey]);
2885
+ const resolvedBridgeHostInfo = useMemo(
2886
+ () => resolvers.resolveHostInfo() ?? {
2887
+ name: "mcpjam-inspector",
2888
+ version: __APP_VERSION__
2889
+ },
2890
+ [activeMcpProfileKey]
2891
+ );
2892
+ useEffect(() => {
2893
+ if (!toolCallId) return;
2894
+ setSandboxAppliedStore(
2895
+ toolCallId,
2896
+ {
2897
+ sandboxAttrs: effectiveSandbox.sandboxAttrs,
2898
+ allowFeatures: effectiveSandbox.allowFeatures,
2899
+ cspDirectives: effectiveSandbox.cspDirectives,
2900
+ permissive: effectiveSandbox.permissive,
2901
+ hostPolicyApplied: effectiveSandbox.hostPolicyApplied,
2902
+ restrictTo: sandboxCspPolicy?.restrictTo,
2903
+ cspMode: sandboxCspPolicy?.mode,
2904
+ permissions: effectiveSandbox.permissions
2905
+ },
2906
+ void 0,
2907
+ sandboxHostInfo
2908
+ );
2909
+ }, [
2910
+ toolCallId,
2911
+ effectiveSandbox,
2912
+ sandboxCspPolicy,
2913
+ sandboxHostInfo,
2914
+ setSandboxAppliedStore
2915
+ ]);
2916
+ useLayoutEffect(() => {
2917
+ onSendFollowUpRef.current = onSendFollowUp;
2918
+ onCallToolRef.current = onCallTool;
2919
+ onAppToolInvocationChangeRef.current = onAppToolInvocationChange;
2920
+ onRequestPipRef.current = onRequestPip;
2921
+ onExitPipRef.current = onExitPip;
2922
+ setDisplayModeRef.current = setDisplayMode;
2923
+ isPlaygroundActiveRef.current = isPlaygroundActive;
2924
+ playgroundDeviceTypeRef.current = playgroundDeviceType;
2925
+ effectiveDisplayModeRef.current = effectiveDisplayMode;
2926
+ serverIdRef.current = serverId;
2927
+ toolCallIdRef.current = toolCallId;
2928
+ displayWidgetIdRef.current = displayWidgetId;
2929
+ pipWidgetIdRef.current = pipWidgetId;
2930
+ ownsPipDisplayModeRef.current = ownsPipDisplayMode;
2931
+ toolsMetadataRef.current = toolsMetadata;
2932
+ onModelContextUpdateRef.current = onModelContextUpdate;
2933
+ onAppSupportedDisplayModesChangeRef.current = onAppSupportedDisplayModesChange;
2934
+ onRequestTeardownRef.current = onRequestTeardown;
2935
+ }, [
2936
+ onSendFollowUp,
2937
+ onCallTool,
2938
+ onAppToolInvocationChange,
2939
+ onRequestPip,
2940
+ onExitPip,
2941
+ setDisplayMode,
2942
+ isPlaygroundActive,
2943
+ playgroundDeviceType,
2944
+ effectiveDisplayMode,
2945
+ serverId,
2946
+ toolCallId,
2947
+ displayWidgetId,
2948
+ pipWidgetId,
2949
+ ownsPipDisplayMode,
2950
+ toolsMetadata,
2951
+ onModelContextUpdate,
2952
+ onAppSupportedDisplayModesChange,
2953
+ onRequestTeardown
2954
+ ]);
2955
+ const registerBridgeHandlers = useCallback(
2956
+ (bridge) => {
2957
+ registerHostBridgeHandlers(bridge, {
2958
+ effectiveHostCapabilities,
2959
+ getMatrix: () => mcpAppsCapabilitiesRef.current,
2960
+ getToolMetadata: (name) => toolsMetadataRef.current?.[name],
2961
+ getToolCallId: () => toolCallIdRef.current,
2962
+ nextInvocationSequence: () => appToolInvocationSequenceRef.current++,
2963
+ onWidgetDebug: logWidgetDebug,
2964
+ callbacks: {
2965
+ onAppInitialized: (b) => {
2966
+ const wasReady = isReadyRef.current;
2967
+ setIsReady(true);
2968
+ isReadyRef.current = true;
2969
+ const appCaps = b.getAppCapabilities();
2970
+ logWidgetDebug("ui-to-host", "debug/app-initialized", {
2971
+ availableDisplayModes: appCaps?.availableDisplayModes ?? null,
2972
+ wasReady
2973
+ });
2974
+ const declaredAppModes = appCaps?.availableDisplayModes;
2975
+ onAppSupportedDisplayModesChangeRef.current?.(declaredAppModes);
2976
+ setAppSupportedDisplayModes(declaredAppModes);
2977
+ if (wasReady) {
2978
+ setReinitCount((c) => c + 1);
2979
+ }
2980
+ if (appCaps?.tools) {
2981
+ const bridgeId = appToolsBridgeIdRef.current ?? crypto.randomUUID();
2982
+ appToolsBridgeIdRef.current = bridgeId;
2983
+ setAppToolsBridgeIdState(bridgeId);
2984
+ void refreshAppProvidedTools(b, bridgeId);
2985
+ if (!hasAutoPromotedForAppToolsRef.current && !userPreferInlineRef.current && declaredAppModes?.includes("fullscreen")) {
2986
+ hasAutoPromotedForAppToolsRef.current = true;
2987
+ setDisplayModeRef.current?.("fullscreen");
2988
+ }
2989
+ }
2990
+ },
2991
+ onSendFollowUp: (text) => {
2992
+ onSendFollowUpRef.current?.(text);
2993
+ },
2994
+ onOpenLink: (url) => {
2995
+ window.open(url, "_blank", "noopener,noreferrer");
2996
+ },
2997
+ onCallTool: async (name, invocationInput) => {
2998
+ if (!onCallToolRef.current) {
2999
+ throw new Error("Tool calls not supported");
3000
+ }
3001
+ return await onCallToolRef.current(
3002
+ name,
3003
+ invocationInput
3004
+ );
3005
+ },
3006
+ onAppToolInvocation: (update) => {
3007
+ onAppToolInvocationChangeRef.current?.(update);
3008
+ },
3009
+ onReadResource: async (uri) => {
3010
+ const result = await host.services.readResource(
3011
+ serverIdRef.current,
3012
+ uri,
3013
+ {
3014
+ forceHosted: webManagedServersRef.current
3015
+ }
3016
+ );
3017
+ return result.content;
3018
+ },
3019
+ onListResources: async (params) => {
3020
+ return host.services.listResources(
3021
+ serverIdRef.current,
3022
+ params?.cursor,
3023
+ { forceHosted: webManagedServersRef.current }
3024
+ );
3025
+ },
3026
+ onListResourceTemplates: async () => {
3027
+ const resourceTemplates = await host.services.listResourceTemplates(serverIdRef.current);
3028
+ return { resourceTemplates };
3029
+ },
3030
+ onListPrompts: async () => {
3031
+ const prompts = await host.services.listPrompts(
3032
+ serverIdRef.current,
3033
+ {
3034
+ forceHosted: webManagedServersRef.current
3035
+ }
3036
+ );
3037
+ return { prompts };
3038
+ },
3039
+ onLoggingMessage: ({ level, data, logger }) => {
3040
+ if (minimalMode) return;
3041
+ const prefix = logger ? `[${logger}]` : "[MCP Apps]";
3042
+ const message = `${prefix} ${level.toUpperCase()}:`;
3043
+ if (level === "error" || level === "critical" || level === "alert") {
3044
+ console.error(message, data);
3045
+ return;
3046
+ }
3047
+ if (level === "warning") {
3048
+ console.warn(message, data);
3049
+ return;
3050
+ }
3051
+ console.info(message, data);
3052
+ },
3053
+ onSizeChange: ({ height }) => {
3054
+ if (effectiveDisplayModeRef.current !== "inline") return;
3055
+ const iframe2 = sandboxRef.current?.getIframeElement();
3056
+ if (!iframe2) return;
3057
+ if (height === void 0) return;
3058
+ const style = getComputedStyle(iframe2);
3059
+ const isBorderBox = style.boxSizing === "border-box";
3060
+ const from = {};
3061
+ const to = {};
3062
+ let adjustedHeight = height;
3063
+ if (adjustedHeight !== void 0) {
3064
+ if (isBorderBox) {
3065
+ adjustedHeight += parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth);
3066
+ }
3067
+ from.height = `${iframe2.offsetHeight}px`;
3068
+ iframe2.style.height = to.height = `${adjustedHeight}px`;
3069
+ lastInlineHeightRef.current = `${adjustedHeight}px`;
3070
+ }
3071
+ iframe2.animate([from, to], { duration: 300, easing: "ease-out" });
3072
+ },
3073
+ onRequestDisplayMode: async ({ mode }) => {
3074
+ const requestedMode = mode ?? "inline";
3075
+ const policy = mcpAppsCapabilitiesRef.current?.widgetDisplayModeRequests ?? "accept";
3076
+ if (requestedMode !== "inline" && policy === "decline") {
3077
+ const granted = effectiveDisplayModeRef.current;
3078
+ logWidgetDebug("ui-to-host", "ui/request-display-mode", {
3079
+ requested: requestedMode,
3080
+ granted,
3081
+ reason: "policy-decline"
3082
+ });
3083
+ return { mode: granted };
3084
+ }
3085
+ if (requestedMode !== "inline" && userPreferInlineRef.current) {
3086
+ logWidgetDebug("ui-to-host", "ui/request-display-mode", {
3087
+ requested: requestedMode,
3088
+ granted: "inline",
3089
+ reason: "user-prefers-inline"
3090
+ });
3091
+ return { mode: "inline" };
3092
+ }
3093
+ const hostAvailableModes = resolvers.extractHostDisplayModes(
3094
+ hostContextRef.current
3095
+ );
3096
+ const isMobile = isPlaygroundActiveRef.current ? playgroundDeviceTypeRef.current === "mobile" || playgroundDeviceTypeRef.current === "tablet" : true;
3097
+ const mobileAdjustedMode = isMobile && requestedMode === "pip" ? "fullscreen" : requestedMode;
3098
+ const actualMode = resolvers.clampDisplayModeToAvailableModes(
3099
+ mobileAdjustedMode,
3100
+ hostAvailableModes
3101
+ );
3102
+ setDisplayModeRef.current(actualMode);
3103
+ if (actualMode === "pip") {
3104
+ onRequestPipRef.current?.(displayWidgetIdRef.current);
3105
+ } else if ((actualMode === "inline" || actualMode === "fullscreen") && ownsPipDisplayModeRef.current) {
3106
+ onExitPipRef.current?.(
3107
+ pipWidgetIdRef.current ?? displayWidgetIdRef.current
3108
+ );
3109
+ }
3110
+ return { mode: actualMode };
3111
+ },
3112
+ onUpdateModelContext: (ctxToolCallId, { content, structuredContent }) => {
3113
+ setWidgetModelContext(ctxToolCallId, {
3114
+ content,
3115
+ structuredContent
3116
+ });
3117
+ onModelContextUpdateRef.current?.(ctxToolCallId, {
3118
+ content,
3119
+ structuredContent
3120
+ });
3121
+ },
3122
+ onDownloadFile: async ({ contents }) => {
3123
+ try {
3124
+ for (const item of contents) {
3125
+ if (item.type === "resource" && item.resource) {
3126
+ const res = item.resource;
3127
+ const mimeType = res.mimeType ?? "application/octet-stream";
3128
+ let blob;
3129
+ if (typeof res.blob === "string") {
3130
+ const binary = atob(res.blob);
3131
+ const bytes = new Uint8Array(binary.length);
3132
+ for (let i = 0; i < binary.length; i++) {
3133
+ bytes[i] = binary.charCodeAt(i);
3134
+ }
3135
+ blob = new Blob([bytes], { type: mimeType });
3136
+ } else {
3137
+ blob = new Blob([res.text ?? ""], { type: mimeType });
3138
+ }
3139
+ const url = URL.createObjectURL(blob);
3140
+ try {
3141
+ const anchor = document.createElement("a");
3142
+ anchor.href = url;
3143
+ anchor.download = res.uri.split("/").pop() ?? "download";
3144
+ anchor.rel = "noopener";
3145
+ document.body.appendChild(anchor);
3146
+ anchor.click();
3147
+ anchor.remove();
3148
+ } finally {
3149
+ setTimeout(() => URL.revokeObjectURL(url), 1e3);
3150
+ }
3151
+ } else if (item.type === "resource_link") {
3152
+ const link = item;
3153
+ const parsed = new URL(link.uri, window.location.href);
3154
+ if (!["http:", "https:"].includes(parsed.protocol)) {
3155
+ throw new Error(
3156
+ `Unsupported download URI protocol: ${parsed.protocol}`
3157
+ );
3158
+ }
3159
+ window.open(parsed.href, "_blank", "noopener,noreferrer");
3160
+ }
3161
+ }
3162
+ return {};
3163
+ } catch (err) {
3164
+ logWidgetDebug("ui-to-host", "ui/download-file", {
3165
+ error: err instanceof Error ? err.message : String(err)
3166
+ });
3167
+ return { isError: true };
3168
+ }
3169
+ },
3170
+ onRequestTeardown: (ctxToolCallId) => {
3171
+ onRequestTeardownRef.current?.(
3172
+ ctxToolCallId,
3173
+ displayWidgetIdRef.current
3174
+ );
3175
+ }
3176
+ }
3177
+ });
3178
+ },
3179
+ [
3180
+ setIsReady,
3181
+ setWidgetModelContext,
3182
+ logWidgetDebug,
3183
+ refreshAppProvidedTools,
3184
+ effectiveHostCapabilities
3185
+ ]
3186
+ );
3187
+ useEffect(() => {
3188
+ if (!widgetHtml) return;
3189
+ if (!sandboxProxyReady) {
3190
+ logWidgetDebug("host-to-ui", "debug/bridge-connect-skipped", {
3191
+ reason: "sandbox-proxy-not-ready"
3192
+ });
3193
+ return;
3194
+ }
3195
+ const iframe2 = sandboxRef.current?.getIframeElement();
3196
+ if (!iframe2?.contentWindow) {
3197
+ logWidgetDebug("host-to-ui", "debug/bridge-connect-skipped", {
3198
+ reason: "missing-iframe-content-window"
3199
+ });
3200
+ return;
3201
+ }
3202
+ setBridgeTransportReady(false);
3203
+ setIsReady(false);
3204
+ isReadyRef.current = false;
3205
+ logWidgetDebug("host-to-ui", "debug/bridge-connect-start", {
3206
+ cspMode,
3207
+ // Reflect the resolved (host-policy-applied) sandbox so the debug
3208
+ // panel matches what the iframe and bridge will actually see.
3209
+ hasCsp: !!effectiveSandbox.csp,
3210
+ hasPermissions: !!effectiveSandbox.permissions,
3211
+ htmlLength: widgetHtml.length,
3212
+ permissive: effectiveSandbox.permissive,
3213
+ hostPolicyApplied: effectiveSandbox.hostPolicyApplied,
3214
+ toolState: toolState ?? null
3215
+ });
3216
+ const bridge = new AppBridge(
3217
+ null,
3218
+ resolvedBridgeHostInfo,
3219
+ {
3220
+ ...effectiveHostCapabilities,
3221
+ sandbox: {
3222
+ csp: effectiveSandbox.csp,
3223
+ permissions: effectiveSandbox.permissions
3224
+ }
3225
+ },
3226
+ { hostContext: hostContextRef.current ?? {} }
3227
+ );
3228
+ registerBridgeHandlers(bridge);
3229
+ bridgeRef.current = bridge;
3230
+ const pendingRpcMethods = /* @__PURE__ */ new Map();
3231
+ const transport = new LoggingTransport(
3232
+ new PostMessageTransport(iframe2.contentWindow, iframe2.contentWindow),
3233
+ {
3234
+ onSend: (message) => {
3235
+ const method = extractMethod(message, "mcp-apps");
3236
+ const request = message;
3237
+ if (typeof request.method === "string" && (typeof request.id === "string" || typeof request.id === "number")) {
3238
+ pendingRpcMethods.set(request.id, request.method);
3239
+ }
3240
+ if (SUPPRESSED_UI_LOG_METHODS.has(method)) return;
3241
+ logUiEvent({
3242
+ widgetId: toolCallIdRef.current,
3243
+ serverId: serverIdRef.current,
3244
+ direction: "host-to-ui",
3245
+ protocol: "mcp-apps",
3246
+ method,
3247
+ message
3248
+ });
3249
+ },
3250
+ onReceive: (message) => {
3251
+ const response = message;
3252
+ const correlatedMethod = (response.result !== void 0 || response.error !== void 0) && (typeof response.id === "string" || typeof response.id === "number") ? pendingRpcMethods.get(response.id) : void 0;
3253
+ if (correlatedMethod && response.id !== void 0) {
3254
+ pendingRpcMethods.delete(response.id);
3255
+ }
3256
+ const method = correlatedMethod ?? extractMethod(message, "mcp-apps");
3257
+ if (method === "ui/notifications/size-changed") {
3258
+ signalStreamingRender();
3259
+ }
3260
+ if (method === "notifications/tools/list_changed") {
3261
+ const bridgeId = appToolsBridgeIdRef.current;
3262
+ if (bridgeId) {
3263
+ void refreshAppProvidedTools(bridge, bridgeId, { force: true });
3264
+ }
3265
+ }
3266
+ if (SUPPRESSED_UI_LOG_METHODS.has(method)) return;
3267
+ logUiEvent({
3268
+ widgetId: toolCallIdRef.current,
3269
+ serverId: serverIdRef.current,
3270
+ direction: "ui-to-host",
3271
+ protocol: "mcp-apps",
3272
+ method,
3273
+ message
3274
+ });
3275
+ }
3276
+ }
3277
+ );
3278
+ let isActive = true;
3279
+ bridge.connect(transport).then(() => {
3280
+ if (!isActive) return;
3281
+ setBridgeTransportReady(true);
3282
+ logWidgetDebug("host-to-ui", "debug/bridge-connect-ready", {
3283
+ htmlLength: widgetHtml.length
3284
+ });
3285
+ }).catch((error) => {
3286
+ if (!isActive) return;
3287
+ const errorMessage = error instanceof Error ? error.message : "Failed to connect MCP App";
3288
+ setLoadError(errorMessage);
3289
+ logWidgetDebug("host-to-ui", "debug/bridge-connect-error", {
3290
+ error: errorMessage
3291
+ });
3292
+ });
3293
+ return () => {
3294
+ isActive = false;
3295
+ logWidgetDebug("host-to-ui", "debug/bridge-connect-cleanup", {
3296
+ wasReady: isReadyRef.current
3297
+ });
3298
+ bridgeRef.current = null;
3299
+ if (appToolsBridgeIdRef.current) {
3300
+ useAppToolsRegistry.getState().unregisterInstance(appToolsBridgeIdRef.current);
3301
+ appToolsListedBridgeIdsRef.current.delete(appToolsBridgeIdRef.current);
3302
+ appToolsListInFlightBridgeIdsRef.current.delete(
3303
+ appToolsBridgeIdRef.current
3304
+ );
3305
+ appToolsListRefreshPendingBridgeIdsRef.current.delete(
3306
+ appToolsBridgeIdRef.current
3307
+ );
3308
+ appToolsBridgeIdRef.current = null;
3309
+ setAppToolsBridgeIdState(null);
3310
+ }
3311
+ if (isReadyRef.current) {
3312
+ bridge.teardownResource({}).catch(() => {
3313
+ });
3314
+ }
3315
+ bridge.close().catch(() => {
3316
+ });
3317
+ setWidgetModelContext(toolCallIdRef.current, null);
3318
+ };
3319
+ }, [
3320
+ logUiEvent,
3321
+ minimalMode,
3322
+ serverId,
3323
+ widgetHtml,
3324
+ sandboxProxyReady,
3325
+ registerBridgeHandlers,
3326
+ refreshAppProvidedTools,
3327
+ setWidgetModelContext,
3328
+ cspMode,
3329
+ // Bridge must rebuild when the resolved sandbox policy changes — a host
3330
+ // toggling sandbox policy at runtime needs the new handshake. The memo
3331
+ // identity captures `widgetCsp`/`widgetPermissions`/`widgetPermissive`
3332
+ // and the sandbox slice of mcpProfile transitively.
3333
+ effectiveSandbox,
3334
+ logWidgetDebug,
3335
+ // Bridge must rebuild when the advertised host capabilities change
3336
+ // (host style switch or override edit) so the new handshake reflects
3337
+ // the new contract.
3338
+ effectiveHostCapabilities,
3339
+ // Bridge must rebuild when the host identity advertised in
3340
+ // ui/initialize changes — switching to a template that overrides
3341
+ // hostInfo (e.g. ChatGPT) is observable to the View.
3342
+ resolvedBridgeHostInfo
3343
+ ]);
3344
+ useEffect(() => {
3345
+ const bridge = bridgeRef.current;
3346
+ if (!bridge || !isReady) return;
3347
+ const matrix = mcpAppsCapabilitiesRef.current;
3348
+ if (matrix !== null && matrix.hostContextChanged === false) return;
3349
+ bridge.setHostContext(hostContext);
3350
+ }, [hostContext, isReady]);
3351
+ const handleCspViolation = useCallback(
3352
+ (event) => {
3353
+ const data = event.data;
3354
+ if (!data) return;
3355
+ const {
3356
+ directive,
3357
+ blockedUri,
3358
+ sourceFile,
3359
+ lineNumber,
3360
+ columnNumber,
3361
+ effectiveDirective,
3362
+ timestamp
3363
+ } = data;
3364
+ logUiEvent({
3365
+ widgetId: toolCallId,
3366
+ serverId,
3367
+ direction: "ui-to-host",
3368
+ protocol: "mcp-apps",
3369
+ method: "csp-violation",
3370
+ message: data
3371
+ });
3372
+ addCspViolation(toolCallId, {
3373
+ directive,
3374
+ effectiveDirective,
3375
+ blockedUri,
3376
+ sourceFile,
3377
+ lineNumber,
3378
+ columnNumber,
3379
+ timestamp: timestamp || Date.now()
3380
+ });
3381
+ if (!minimalMode) {
3382
+ console.warn(
3383
+ `[MCP Apps CSP Violation] ${directive}: Blocked ${blockedUri}`,
3384
+ sourceFile ? `at ${sourceFile}:${lineNumber}:${columnNumber}` : ""
3385
+ );
3386
+ }
3387
+ },
3388
+ [addCspViolation, logUiEvent, minimalMode, serverId, toolCallId]
3389
+ );
3390
+ const handleSandboxMessage = (event) => {
3391
+ const data = event.data;
3392
+ if (!data) return;
3393
+ if (data.type === "mcp-apps:csp-violation") {
3394
+ handleCspViolation(event);
3395
+ return;
3396
+ }
3397
+ const liveCaps = liveOpenAiCompatCapabilitiesRef.current;
3398
+ const policyError = (callId, method) => {
3399
+ sandboxRef.current?.postMessage({
3400
+ type: `${method}:response`,
3401
+ callId,
3402
+ error: `${method} denied by host capability policy`
3403
+ });
3404
+ };
3405
+ if (data.type === "openai:uploadFile") {
3406
+ if (liveCaps !== null && liveCaps.uploadFile === false) {
3407
+ policyError(data.callId, "openai:uploadFile");
3408
+ return;
3409
+ }
3410
+ void handleUploadFileMessage(
3411
+ data,
3412
+ (message) => {
3413
+ sandboxRef.current?.postMessage(message);
3414
+ },
3415
+ {
3416
+ authFetch: host.services.authFetch,
3417
+ hostedMode: host.surface.hostedMode
3418
+ }
3419
+ );
3420
+ return;
3421
+ }
3422
+ if (data.type === "openai:getFileDownloadUrl") {
3423
+ if (liveCaps !== null && liveCaps.getFileDownloadUrl === false) {
3424
+ policyError(data.callId, "openai:getFileDownloadUrl");
3425
+ return;
3426
+ }
3427
+ handleGetFileDownloadUrlMessage(
3428
+ data,
3429
+ (message) => {
3430
+ sandboxRef.current?.postMessage(message);
3431
+ },
3432
+ { hostedMode: host.surface.hostedMode }
3433
+ );
3434
+ return;
3435
+ }
3436
+ if (data.type === "openai:setWidgetState") {
3437
+ if (liveCaps !== null && liveCaps.setWidgetState === false) return;
3438
+ if (onWidgetStateChange) {
3439
+ onWidgetStateChange(toolCallId, data.state);
3440
+ }
3441
+ setWidgetStateStore(toolCallId, data.state);
3442
+ return;
3443
+ }
3444
+ if (data.type === "openai:setOpenInAppUrl") {
3445
+ if (liveCaps !== null && liveCaps.setOpenInAppUrl === false) return;
3446
+ const nextUrl = resolveOpenInAppHref(
3447
+ data.href,
3448
+ explicitOpenInAppBaseUrl
3449
+ );
3450
+ if (nextUrl) {
3451
+ setOpenInAppUrlOverride(nextUrl);
3452
+ }
3453
+ return;
3454
+ }
3455
+ if (data.jsonrpc === "2.0" && typeof data.method === "string" && data.method.startsWith("openai/")) {
3456
+ logUiEvent({
3457
+ widgetId: toolCallId,
3458
+ serverId,
3459
+ direction: "ui-to-host",
3460
+ protocol: "mcp-apps",
3461
+ method: data.method,
3462
+ message: data
3463
+ });
3464
+ if (data.method === "openai/requestModal") {
3465
+ if (liveCaps !== null && liveCaps.requestModal === false) return;
3466
+ const params = data.params ?? {};
3467
+ setModalTitle(params.title || "Modal");
3468
+ setModalParams(params.params || {});
3469
+ setModalTemplate(params.template || null);
3470
+ setModalOpen(true);
3471
+ } else if (data.method === "openai/requestClose") {
3472
+ if (liveCaps !== null && liveCaps.requestClose === false) return;
3473
+ setModalOpen(false);
3474
+ } else if (data.method === "openai/requestCheckout") {
3475
+ const params = data.params ?? {};
3476
+ const { callId: cId, ...sessionData } = params;
3477
+ if (liveCaps !== null && liveCaps.requestCheckout === false) {
3478
+ sandboxRef.current?.postMessage({
3479
+ jsonrpc: "2.0",
3480
+ method: "openai/requestCheckout:response",
3481
+ params: {
3482
+ callId: cId,
3483
+ error: "openai/requestCheckout denied by host capability policy"
3484
+ }
3485
+ });
3486
+ return;
3487
+ }
3488
+ setCheckoutCallId(cId);
3489
+ setCheckoutSession(sessionData);
3490
+ setCheckoutOpen(true);
3491
+ }
3492
+ }
3493
+ };
3494
+ const showWidget = isReady && canRenderStreamingInput;
3495
+ useEffect(() => {
3496
+ logWidgetDebug("host-to-ui", "debug/widget-visibility", {
3497
+ bridgeTransportReady,
3498
+ canRenderStreamingInput,
3499
+ hasWidgetHtml,
3500
+ isReady,
3501
+ loadError,
3502
+ showWidget,
3503
+ toolState: toolState ?? null,
3504
+ widgetHtmlLength
3505
+ });
3506
+ }, [
3507
+ bridgeTransportReady,
3508
+ canRenderStreamingInput,
3509
+ hasWidgetHtml,
3510
+ isReady,
3511
+ loadError,
3512
+ showWidget,
3513
+ toolState,
3514
+ widgetHtmlLength,
3515
+ logWidgetDebug
3516
+ ]);
3517
+ useEffect(() => {
3518
+ if (!bridgeTransportReady || !widgetHtml) return;
3519
+ logWidgetDebug("host-to-ui", "debug/sandbox-html-ready", {
3520
+ hasCsp: !!effectiveSandbox.csp,
3521
+ hasPermissions: !!effectiveSandbox.permissions,
3522
+ htmlLength: widgetHtml.length,
3523
+ permissive: effectiveSandbox.permissive,
3524
+ hostPolicyApplied: effectiveSandbox.hostPolicyApplied
3525
+ });
3526
+ }, [bridgeTransportReady, widgetHtml, effectiveSandbox, logWidgetDebug]);
3527
+ const respondToCheckout = useCallback(
3528
+ (result, error) => {
3529
+ if (checkoutCallId == null) return;
3530
+ const params = { callId: checkoutCallId };
3531
+ if (error) {
3532
+ params.error = error;
3533
+ } else {
3534
+ params.result = result;
3535
+ }
3536
+ sandboxRef.current?.postMessage({
3537
+ jsonrpc: "2.0",
3538
+ method: "openai/requestCheckout:response",
3539
+ params
3540
+ });
3541
+ setCheckoutOpen(false);
3542
+ setCheckoutSession(null);
3543
+ setCheckoutCallId(null);
3544
+ },
3545
+ [checkoutCallId]
3546
+ );
3547
+ if (toolState === "output-denied") {
3548
+ return /* @__PURE__ */ jsx("div", { className: "border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2", children: "Tool execution was denied." });
3549
+ }
3550
+ if (loadError) {
3551
+ return /* @__PURE__ */ jsxs("div", { className: "border border-destructive/40 bg-destructive/10 text-destructive text-xs rounded-md px-3 py-2", children: [
3552
+ "Failed to load MCP App: ",
3553
+ loadError
3554
+ ] });
3555
+ }
3556
+ if (!widgetHtml) {
3557
+ return null;
3558
+ }
3559
+ const isPip = effectiveDisplayMode === "pip";
3560
+ const isFullscreen = effectiveDisplayMode === "fullscreen";
3561
+ const isMobilePlaygroundMode = isPlaygroundActive && playgroundDeviceType === "mobile";
3562
+ const isContainedFullscreenMode = isPlaygroundActive && (playgroundDeviceType === "mobile" || playgroundDeviceType === "tablet");
3563
+ const showOpenInAppButton = isFullscreen && !!openInAppUrl && !isMobilePlaygroundMode;
3564
+ const containerClassName = (() => {
3565
+ if (isFullscreen) {
3566
+ if (isContainedFullscreenMode) {
3567
+ return "absolute inset-0 z-10 w-full h-full bg-background flex flex-col";
3568
+ }
3569
+ return "fixed inset-0 z-40 w-full h-full bg-background flex flex-col";
3570
+ }
3571
+ if (isPip) {
3572
+ if (isMobilePlaygroundMode) {
3573
+ return "absolute inset-0 z-10 w-full h-full bg-background flex flex-col";
3574
+ }
3575
+ if (isPlaygroundActive) {
3576
+ return [
3577
+ "absolute top-4 left-1/2 -translate-x-1/2 z-40 w-full min-w-[300px] max-w-[min(90vw,1200px)] space-y-2",
3578
+ "bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80",
3579
+ "shadow-xl border border-border/60 rounded-xl p-3"
3580
+ ].join(" ");
3581
+ }
3582
+ return [
3583
+ "fixed top-4 left-1/2 -translate-x-1/2 z-40 w-full min-w-[300px] max-w-[min(90vw,1200px)] space-y-2",
3584
+ "bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80",
3585
+ "shadow-xl border border-border/60 rounded-xl p-3"
3586
+ ].join(" ");
3587
+ }
3588
+ return "mt-3 space-y-2 relative group";
3589
+ })();
3590
+ const canTransitionHeight = !isFullscreen && effectiveDisplayModeRef.current === effectiveDisplayMode;
3591
+ const iframeStyle = {
3592
+ height: isFullscreen ? "100%" : isPip ? PIP_MAX_HEIGHT : lastInlineHeightRef.current,
3593
+ width: "100%",
3594
+ maxWidth: "100%",
3595
+ backgroundColor: !isFullscreen && matrixGatedPrefersBorder ? mergedStyleVariables["--color-background-primary"] : hostChatBackground ?? "transparent",
3596
+ opacity: showWidget ? 1 : 0,
3597
+ transition: [
3598
+ "opacity 150ms ease-in",
3599
+ canTransitionHeight ? "height 300ms ease-out" : ""
3600
+ ].filter(Boolean).join(", "),
3601
+ // Keep iframe in the layout but invisible while not ready
3602
+ ...!showWidget ? { position: "absolute", pointerEvents: "none" } : {}
3603
+ };
3604
+ const showHostChrome = !isFullscreen && matrixGatedPrefersBorder;
3605
+ const hostChromeStyle = showHostChrome ? {
3606
+ backgroundColor: mergedStyleVariables["--color-background-primary"]
3607
+ } : void 0;
3608
+ const iframe = /* @__PURE__ */ jsx(
3609
+ SandboxedIframe,
3610
+ {
3611
+ ref: sandboxRef,
3612
+ html: bridgeTransportReady ? widgetHtml : null,
3613
+ sandbox: "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",
3614
+ csp: effectiveSandbox.csp,
3615
+ permissions: effectiveSandbox.permissions,
3616
+ permissive: effectiveSandbox.permissive,
3617
+ sandboxAttrs: effectiveSandbox.sandboxAttrs,
3618
+ allowFeatures: effectiveSandbox.allowFeatures,
3619
+ cspDirectives: effectiveSandbox.cspDirectives,
3620
+ colorScheme: resolvedTheme,
3621
+ onProxyReady: () => {
3622
+ setSandboxProxyReady(true);
3623
+ logWidgetDebug("ui-to-host", "debug/sandbox-proxy-ready", {
3624
+ bridgeTransportReady,
3625
+ hasWidgetHtml
3626
+ });
3627
+ },
3628
+ onMessage: handleSandboxMessage,
3629
+ title: `MCP App: ${toolName}`,
3630
+ hostedMode: host.surface.hostedMode,
3631
+ sandboxOrigin: host.surface.sandboxOrigin,
3632
+ className: `bg-transparent overflow-hidden ${isFullscreen ? "flex-1 border-0 rounded-none" : `rounded-md ${matrixGatedPrefersBorder ? "border border-border/40" : ""}`}`,
3633
+ style: iframeStyle
3634
+ }
3635
+ );
3636
+ return /* @__PURE__ */ jsxs(
3637
+ "div",
3638
+ {
3639
+ className: containerClassName,
3640
+ "data-mcp-app-persistent-initial-tool-call-id": persistentSurfaceInitialToolCallId,
3641
+ "data-mcp-app-persistent-surface-id": persistentSurfaceId,
3642
+ children: [
3643
+ (isFullscreen && isContainedFullscreenMode || isPip && isMobilePlaygroundMode) && /* @__PURE__ */ jsxs(Fragment, { children: [
3644
+ /* @__PURE__ */ jsx(
3645
+ "button",
3646
+ {
3647
+ onClick: () => {
3648
+ userPreferInlineRef.current = true;
3649
+ setDisplayMode("inline");
3650
+ if (isPip) {
3651
+ onExitPip?.(pipWidgetId ?? displayWidgetId);
3652
+ }
3653
+ },
3654
+ className: "absolute left-3 top-3 z-20 flex h-8 w-8 items-center justify-center rounded-full bg-black/20 hover:bg-black/40 text-white transition-colors cursor-pointer",
3655
+ "aria-label": "Close",
3656
+ children: /* @__PURE__ */ jsx(X, { className: "w-5 h-5" })
3657
+ }
3658
+ ),
3659
+ showOpenInAppButton && /* @__PURE__ */ jsx(
3660
+ "button",
3661
+ {
3662
+ onClick: handleOpenInApp,
3663
+ className: "absolute right-3 top-3 z-20 flex h-8 w-8 items-center justify-center rounded-full bg-black/20 hover:bg-black/40 text-white transition-colors cursor-pointer",
3664
+ "aria-label": `Open in ${openInAppLabel}`,
3665
+ title: `Open in ${openInAppLabel}`,
3666
+ children: /* @__PURE__ */ jsx(ExternalLink, { className: "w-4 h-4" })
3667
+ }
3668
+ )
3669
+ ] }),
3670
+ 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: [
3671
+ /* @__PURE__ */ jsx("div", {}),
3672
+ /* @__PURE__ */ jsx("div", { className: "font-medium text-sm text-muted-foreground min-w-0 max-w-[40vw] truncate", children: openInAppLabel }),
3673
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-2 min-w-0", children: [
3674
+ showOpenInAppButton && /* @__PURE__ */ jsxs(
3675
+ "button",
3676
+ {
3677
+ onClick: handleOpenInApp,
3678
+ className: "inline-flex items-center justify-center gap-1.5 h-8 max-w-[16rem] rounded-full border border-border/60 px-2 sm:px-3 text-xs font-medium text-foreground hover:bg-muted transition-colors",
3679
+ "aria-label": `Open in ${openInAppLabel}`,
3680
+ title: `Open in ${openInAppLabel}`,
3681
+ children: [
3682
+ /* @__PURE__ */ jsx(ExternalLink, { className: "w-3.5 h-3.5 shrink-0" }),
3683
+ /* @__PURE__ */ jsxs("span", { className: "hidden sm:inline min-w-0 truncate", children: [
3684
+ "Open in ",
3685
+ openInAppLabel
3686
+ ] })
3687
+ ]
3688
+ }
3689
+ ),
3690
+ /* @__PURE__ */ jsx(
3691
+ "button",
3692
+ {
3693
+ onClick: () => {
3694
+ userPreferInlineRef.current = true;
3695
+ setDisplayMode("inline");
3696
+ if (ownsPipDisplayMode) {
3697
+ onExitPip?.(pipWidgetId ?? displayWidgetId);
3698
+ }
3699
+ },
3700
+ className: "p-2 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors",
3701
+ "aria-label": "Exit fullscreen",
3702
+ children: /* @__PURE__ */ jsx(X, { className: "w-5 h-5" })
3703
+ }
3704
+ )
3705
+ ] })
3706
+ ] }),
3707
+ isPip && !isMobilePlaygroundMode && /* @__PURE__ */ jsx(
3708
+ "button",
3709
+ {
3710
+ onClick: () => {
3711
+ userPreferInlineRef.current = true;
3712
+ setDisplayMode("inline");
3713
+ onExitPip?.(pipWidgetId ?? displayWidgetId);
3714
+ },
3715
+ className: "absolute left-2 top-2 z-10 flex h-6 w-6 items-center justify-center rounded-md bg-background/80 hover:bg-background border border-border/50 text-muted-foreground hover:text-foreground transition-colors cursor-pointer",
3716
+ "aria-label": "Close PiP mode",
3717
+ title: "Close PiP mode",
3718
+ children: /* @__PURE__ */ jsx(X, { className: "w-4 h-4" })
3719
+ }
3720
+ ),
3721
+ /* @__PURE__ */ jsx(
3722
+ "div",
3723
+ {
3724
+ "data-testid": showHostChrome ? "mcp-app-host-chrome" : void 0,
3725
+ className: showHostChrome ? "rounded-md" : "contents",
3726
+ style: hostChromeStyle,
3727
+ children: iframe
3728
+ }
3729
+ ),
3730
+ pendingAppToolCalls > 0 && !isFullscreen && /* @__PURE__ */ jsx(
3731
+ "div",
3732
+ {
3733
+ className: "pointer-events-none absolute right-2 top-2 z-20 flex h-6 w-6 items-center justify-center rounded-md bg-background/80 border border-border/50 text-muted-foreground shadow-sm",
3734
+ "aria-label": "App tool call in progress",
3735
+ title: "App tool call in progress",
3736
+ "data-testid": "mcp-app-busy-indicator",
3737
+ children: /* @__PURE__ */ jsx(Loader2, { className: "w-3.5 h-3.5 animate-spin" })
3738
+ }
3739
+ ),
3740
+ /* @__PURE__ */ jsx(
3741
+ McpAppsModal,
3742
+ {
3743
+ open: modalOpen,
3744
+ onOpenChange: setModalOpen,
3745
+ title: modalTitle,
3746
+ template: modalTemplate,
3747
+ params: modalParams,
3748
+ registerBridgeHandlers,
3749
+ refreshAppProvidedTools,
3750
+ widgetCsp: effectiveSandbox.csp,
3751
+ widgetPermissions: effectiveSandbox.permissions,
3752
+ widgetPermissive: effectiveSandbox.permissive,
3753
+ widgetSandboxAttrs: effectiveSandbox.sandboxAttrs,
3754
+ widgetAllowFeatures: effectiveSandbox.allowFeatures,
3755
+ widgetCspDirectives: effectiveSandbox.cspDirectives,
3756
+ hostContextRef,
3757
+ serverId,
3758
+ resourceUri,
3759
+ toolCallId,
3760
+ toolName,
3761
+ cspMode,
3762
+ injectOpenAiCompat: effectiveInjectOpenAiCompat,
3763
+ effectiveHostCapabilities,
3764
+ hostInfo: resolvedBridgeHostInfo,
3765
+ webManagedServers,
3766
+ toolInputRef,
3767
+ toolOutputRef,
3768
+ themeModeRef,
3769
+ addUiLog: (log) => logUiEvent({
3770
+ ...log,
3771
+ protocol: "mcp-apps"
3772
+ }),
3773
+ onCspViolation: handleCspViolation
3774
+ }
3775
+ ),
3776
+ checkoutSession != null && Checkout && /* @__PURE__ */ jsx(
3777
+ Checkout,
3778
+ {
3779
+ session: checkoutSession,
3780
+ open: checkoutOpen,
3781
+ onOpenChange: setCheckoutOpen,
3782
+ onComplete: (result) => respondToCheckout(result),
3783
+ onError: (error) => respondToCheckout(null, error),
3784
+ onCancel: () => respondToCheckout(null, "User cancelled checkout"),
3785
+ onCallTool: async (toolName2, params) => {
3786
+ if (!onCallTool) {
3787
+ throw new Error("Tool calls not supported");
3788
+ }
3789
+ return onCallTool(toolName2, params);
3790
+ }
3791
+ }
3792
+ )
3793
+ ]
3794
+ }
3795
+ );
3796
+ }
3797
+ function createSurfaceContainer(surfaceId) {
3798
+ const container = document.createElement("div");
3799
+ container.dataset.mcpAppSurfaceContainer = surfaceId;
3800
+ container.style.display = "contents";
3801
+ return container;
3802
+ }
3803
+ function WidgetSurfacePortal({
3804
+ anchorElement,
3805
+ initialToolCallId,
3806
+ parkingElement,
3807
+ props,
3808
+ surfaceId
3809
+ }) {
3810
+ const [container] = useState(() => createSurfaceContainer(surfaceId));
3811
+ const targetElement = anchorElement ?? parkingElement;
3812
+ useLayoutEffect(() => {
3813
+ if (!targetElement) return;
3814
+ if (container.parentElement !== targetElement) {
3815
+ targetElement.appendChild(container);
3816
+ }
3817
+ }, [container, targetElement]);
3818
+ useEffect(() => {
3819
+ return () => {
3820
+ container.remove();
3821
+ };
3822
+ }, [container]);
3823
+ return createPortal(
3824
+ /* @__PURE__ */ jsx(
3825
+ MCPAppsRendererSurface,
3826
+ {
3827
+ ...props,
3828
+ persistentSurfaceInitialToolCallId: initialToolCallId,
3829
+ persistentSurfaceId: surfaceId
3830
+ }
3831
+ ),
3832
+ container,
3833
+ surfaceId
3834
+ );
3835
+ }
3836
+ function WidgetSurfaceHost({
3837
+ chatSessionId
3838
+ }) {
3839
+ const [parkingElement, setParkingElement] = useState(
3840
+ null
3841
+ );
3842
+ const surfaces = useWidgetSurfaceStore((state) => state.surfaces);
3843
+ const entries = useMemo(
3844
+ () => getRenderableSurfaceEntries(surfaces, chatSessionId),
3845
+ [chatSessionId, surfaces]
3846
+ );
3847
+ useEffect(() => {
3848
+ return () => {
3849
+ useWidgetSurfaceStore.getState().clearChatSession(chatSessionId);
3850
+ };
3851
+ }, [chatSessionId]);
3852
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
3853
+ /* @__PURE__ */ jsx(
3854
+ "div",
3855
+ {
3856
+ ref: setParkingElement,
3857
+ "data-mcp-app-surface-parking": true,
3858
+ style: {
3859
+ height: 0,
3860
+ overflow: "hidden",
3861
+ pointerEvents: "none",
3862
+ position: "absolute",
3863
+ width: 0
3864
+ }
3865
+ }
3866
+ ),
3867
+ entries.map(({ surfaceId, anchorElement, initialToolCallId, props }) => /* @__PURE__ */ jsx(
3868
+ WidgetSurfacePortal,
3869
+ {
3870
+ anchorElement,
3871
+ initialToolCallId,
3872
+ parkingElement,
3873
+ props,
3874
+ surfaceId
3875
+ },
3876
+ surfaceId
3877
+ ))
3878
+ ] });
3879
+ }
3880
+
3881
+ 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, useAppToolAttribution, useAppToolAttributionResolver, useAppToolInvocationLog, useAppToolsRegistry, usePersistentWidgetSurfaceHost, useToolInputStreaming, useWidgetHost, useWidgetSurfaceStore };
3882
+ //# sourceMappingURL=index.js.map
3883
+ //# sourceMappingURL=index.js.map