@botdojo/chat-sdk 0.0.19 → 0.0.21

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/lib/index.js CHANGED
@@ -171,7 +171,7 @@ var require_tool_utils = __commonJS({
171
171
  name: contextName,
172
172
  description: (options == null ? void 0 : options.description) || `Tools for ${contextName}`,
173
173
  toolPrefix: options == null ? void 0 : options.toolPrefix,
174
- resourceUri: (options == null ? void 0 : options.resourceUri) || `app://${contextName}`,
174
+ uri: (options == null ? void 0 : options.uri) || `app://${contextName}`,
175
175
  tools: modelTools,
176
176
  prompts: []
177
177
  };
@@ -203,14 +203,14 @@ var require_tool_utils = __commonJS({
203
203
  context = toolsToModelContext(name, tools, {
204
204
  description,
205
205
  toolPrefix,
206
- resourceUri: uri
206
+ uri
207
207
  });
208
208
  } else {
209
209
  context = {
210
210
  name,
211
211
  description: description || `Model context for ${name}`,
212
212
  toolPrefix,
213
- resourceUri: uri,
213
+ uri,
214
214
  tools: [],
215
215
  prompts: []
216
216
  };
@@ -408,7 +408,7 @@ var require_modelContextTranslation_snapshot = __commonJS({
408
408
  name: context.name,
409
409
  description: context.description,
410
410
  toolPrefix: context.toolPrefix,
411
- resourceUri: context.resourceUri || context.uri,
411
+ resourceUri: context.uri,
412
412
  tools,
413
413
  prompts,
414
414
  resources
@@ -8305,7 +8305,13 @@ var BotDojoChat = ({
8305
8305
  const connectorRef = useRef(null);
8306
8306
  const iframeLoadedRef = useRef(false);
8307
8307
  const chatReadyRef = useRef(false);
8308
+ const chatReadyFiredRef = useRef(false);
8308
8309
  const resizeStartPos = useRef({ x: 0, y: 0, width: 0, height: 0 });
8310
+ const modelContextCapturedRef = useRef(false);
8311
+ const modelContextRef = useRef(modelContext2);
8312
+ useEffect(() => {
8313
+ modelContextRef.current = modelContext2;
8314
+ }, [modelContext2]);
8309
8315
  const eventHandlersRef = useRef({
8310
8316
  onReady,
8311
8317
  onError,
@@ -8350,6 +8356,28 @@ var BotDojoChat = ({
8350
8356
  onToolCall,
8351
8357
  onUiMessage
8352
8358
  ]);
8359
+ const rpcReadyRef = useRef(false);
8360
+ const [rpcTrigger, setRpcTrigger] = useState(0);
8361
+ useEffect(() => {
8362
+ const handleEarlyMessages = (event) => {
8363
+ const data = event.data;
8364
+ if ((data == null ? void 0 : data.type) !== "botdojo-rpc")
8365
+ return;
8366
+ const payload = data.payload;
8367
+ if ((payload == null ? void 0 : payload.functionName) === "chat_ready") {
8368
+ console.log("[BotDojoChat] Early listener captured chat_ready");
8369
+ chatReadyRef.current = true;
8370
+ if (!iframeLoadedRef.current) {
8371
+ console.log("[BotDojoChat] Setting iframeLoaded=true (inferred from chat_ready)");
8372
+ iframeLoadedRef.current = true;
8373
+ setIframeLoaded(true);
8374
+ setRpcTrigger((t) => t + 1);
8375
+ }
8376
+ }
8377
+ };
8378
+ window.addEventListener("message", handleEarlyMessages);
8379
+ return () => window.removeEventListener("message", handleEarlyMessages);
8380
+ }, []);
8353
8381
  const hasModelContextContent = useMemo(() => {
8354
8382
  if (!modelContext2)
8355
8383
  return false;
@@ -8734,15 +8762,6 @@ var BotDojoChat = ({
8734
8762
  return;
8735
8763
  }
8736
8764
  switch (data.type) {
8737
- case "ready":
8738
- if (handlers.onReady) {
8739
- try {
8740
- handlers.onReady();
8741
- } catch (error) {
8742
- console.error("[BotDojoChat] Error in onReady handler:", error);
8743
- }
8744
- }
8745
- break;
8746
8765
  case "error":
8747
8766
  if (handlers.onError) {
8748
8767
  try {
@@ -8877,7 +8896,10 @@ var BotDojoChat = ({
8877
8896
  }, [getBaseUrl]);
8878
8897
  useEffect(() => {
8879
8898
  var _a;
8880
- if (!((_a = iframeRef.current) == null ? void 0 : _a.contentWindow) || !iframeLoaded) {
8899
+ if (!((_a = iframeRef.current) == null ? void 0 : _a.contentWindow)) {
8900
+ return;
8901
+ }
8902
+ if (!iframeLoaded && !iframeLoadedRef.current) {
8881
8903
  return;
8882
8904
  }
8883
8905
  const initializeConnection = async () => {
@@ -8921,19 +8943,21 @@ var BotDojoChat = ({
8921
8943
  if (msg.functionName === "chat_ready") {
8922
8944
  console.log("[BotDojoChat] Chat is ready for flow requests");
8923
8945
  chatReadyRef.current = true;
8946
+ if (!chatReadyFiredRef.current) {
8947
+ chatReadyFiredRef.current = true;
8948
+ const handlers2 = eventHandlersRef.current;
8949
+ if (handlers2.onReady) {
8950
+ try {
8951
+ handlers2.onReady();
8952
+ } catch (e) {
8953
+ console.error("[BotDojoChat] Error in onReady:", e);
8954
+ }
8955
+ }
8956
+ }
8924
8957
  return;
8925
8958
  }
8926
8959
  const handlers = eventHandlersRef.current;
8927
8960
  const eventData = (_a2 = msg.data) == null ? void 0 : _a2[0];
8928
- if (msg.functionName === "ready" && handlers.onReady) {
8929
- console.log("[BotDojoChat] Received ready event via RPC");
8930
- try {
8931
- handlers.onReady();
8932
- } catch (e) {
8933
- console.error("[BotDojoChat] Error in onReady:", e);
8934
- }
8935
- return;
8936
- }
8937
8961
  if (msg.functionName === "error" && handlers.onError) {
8938
8962
  console.log("[BotDojoChat] Received error event via RPC:", eventData);
8939
8963
  try {
@@ -9101,9 +9125,28 @@ var BotDojoChat = ({
9101
9125
  }
9102
9126
  };
9103
9127
  const tryModelContext = async () => {
9104
- if (!uri || !modelContext2)
9128
+ let waited = 0;
9129
+ const maxWait = 3e3;
9130
+ while (waited < maxWait) {
9131
+ const currentContext = modelContextRef.current;
9132
+ if (currentContext) {
9133
+ const contexts2 = Array.isArray(currentContext) ? currentContext : [currentContext];
9134
+ const allResources2 = contexts2.flatMap((ctx) => ctx.resources || []);
9135
+ const hasMatchingResource = allResources2.some((r) => {
9136
+ return (r == null ? void 0 : r.uri) === uri || (r == null ? void 0 : r.uriTemplate) && matchesTemplate(r.uriTemplate, uri);
9137
+ });
9138
+ if (hasMatchingResource) {
9139
+ console.log("[BotDojoChat] tryModelContext: Found matching resource after", waited, "ms");
9140
+ break;
9141
+ }
9142
+ }
9143
+ await new Promise((r) => setTimeout(r, 50));
9144
+ waited += 50;
9145
+ }
9146
+ const currentModelContext = modelContextRef.current;
9147
+ if (!uri || !currentModelContext)
9105
9148
  return { error: "no modelContext" };
9106
- const contexts = Array.isArray(modelContext2) ? modelContext2 : [modelContext2];
9149
+ const contexts = Array.isArray(currentModelContext) ? currentModelContext : [currentModelContext];
9107
9150
  const allResources = contexts.flatMap((ctx) => ctx.resources || []);
9108
9151
  console.log("[BotDojoChat] tryModelContext: Searching", allResources.length, "resources for URI:", uri);
9109
9152
  allResources.forEach((r, i2) => {
@@ -9117,7 +9160,7 @@ var BotDojoChat = ({
9117
9160
  return uriMatch || templateMatch;
9118
9161
  });
9119
9162
  if (!match) {
9120
- console.log("[BotDojoChat] tryModelContext: No match found");
9163
+ console.log("[BotDojoChat] tryModelContext: No match found after waiting", waited, "ms");
9121
9164
  return { error: "resource not found in modelContext" };
9122
9165
  }
9123
9166
  console.log("[BotDojoChat] tryModelContext: MATCH FOUND:", match.uri);
@@ -9315,8 +9358,7 @@ var BotDojoChat = ({
9315
9358
  name: ctx.name,
9316
9359
  description: ctx.description,
9317
9360
  toolPrefix: ctx.toolPrefix,
9318
- resourceUri: ctx.resourceUri,
9319
- uri: ctx.uri || ctx.resourceUri,
9361
+ uri: ctx.uri,
9320
9362
  tools,
9321
9363
  prompts: ctx.prompts || [],
9322
9364
  resources: ctx.resources || []
@@ -9325,19 +9367,35 @@ var BotDojoChat = ({
9325
9367
  }
9326
9368
  });
9327
9369
  connectionRef.current = connection;
9370
+ modelContextCapturedRef.current = !!modelContext2;
9328
9371
  console.log("[BotDojoChat] RPC connection initialized");
9372
+ if (!chatReadyFiredRef.current) {
9373
+ console.log("[BotDojoChat] RPC ready, firing onReady");
9374
+ chatReadyRef.current = true;
9375
+ chatReadyFiredRef.current = true;
9376
+ rpcReadyRef.current = true;
9377
+ const handlers = eventHandlersRef.current;
9378
+ if (handlers.onReady) {
9379
+ try {
9380
+ handlers.onReady();
9381
+ } catch (e) {
9382
+ console.error("[BotDojoChat] Error in onReady:", e);
9383
+ }
9384
+ }
9385
+ }
9329
9386
  } catch (error) {
9330
9387
  console.error("[BotDojoChat] Failed to initialize RPC connection:", error);
9331
9388
  }
9332
9389
  };
9333
9390
  initializeConnection();
9334
9391
  return () => {
9392
+ modelContextCapturedRef.current = false;
9335
9393
  if (connectionRef.current) {
9336
9394
  connectionRef.current.close();
9337
9395
  connectionRef.current = null;
9338
9396
  }
9339
9397
  };
9340
- }, [connector, iframeLoaded, modelContext2, apiKey]);
9398
+ }, [connector, iframeLoaded, modelContext2, apiKey, rpcTrigger]);
9341
9399
  const parseSize = useCallback((value2, defaultVal) => {
9342
9400
  if (!value2 || value2 === "auto")
9343
9401
  return defaultVal;
@@ -9440,6 +9498,7 @@ var BotDojoChat = ({
9440
9498
  setIframeLoaded(true);
9441
9499
  iframeLoadedRef.current = true;
9442
9500
  chatReadyRef.current = false;
9501
+ chatReadyFiredRef.current = false;
9443
9502
  setIsLoading(false);
9444
9503
  onLoad == null ? void 0 : onLoad();
9445
9504
  }, [onLoad]);
@@ -9995,7 +10054,24 @@ function findOrCreateStep(steps, stepId, parentStepId) {
9995
10054
  return newStep;
9996
10055
  }
9997
10056
  function mergeStep(existing, update) {
9998
- var _a;
10057
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
10058
+ let mergedCanvas = existing.canvas;
10059
+ if (update.canvas) {
10060
+ mergedCanvas = {
10061
+ ...existing.canvas,
10062
+ ...update.canvas,
10063
+ canvasData: {
10064
+ ...(_a = existing.canvas) == null ? void 0 : _a.canvasData,
10065
+ ...(_b = update.canvas) == null ? void 0 : _b.canvasData,
10066
+ // CRITICAL: Preserve html if the update doesn't have it
10067
+ // BotDojoChatProvider resolves ui:// URLs and adds html to canvasData
10068
+ // Subsequent step updates may not have html, so we must preserve it
10069
+ html: (_g = (_d = (_c = update.canvas) == null ? void 0 : _c.canvasData) == null ? void 0 : _d.html) != null ? _g : (_f = (_e = existing.canvas) == null ? void 0 : _e.canvasData) == null ? void 0 : _f.html,
10070
+ // Also preserve url if not in update
10071
+ url: (_l = (_i = (_h = update.canvas) == null ? void 0 : _h.canvasData) == null ? void 0 : _i.url) != null ? _l : (_k = (_j = existing.canvas) == null ? void 0 : _j.canvasData) == null ? void 0 : _k.url
10072
+ }
10073
+ };
10074
+ }
9999
10075
  return {
10000
10076
  ...existing,
10001
10077
  ...update,
@@ -10003,9 +10079,7 @@ function mergeStep(existing, update) {
10003
10079
  stepId: existing.stepId,
10004
10080
  startTime: existing.startTime,
10005
10081
  subSteps: update.subSteps || existing.subSteps,
10006
- // CRITICAL: Preserve canvas from original step if update doesn't have one
10007
- // This allows notifyToolInputPartial to send progress updates without destroying the canvas
10008
- canvas: (_a = update.canvas) != null ? _a : existing.canvas
10082
+ canvas: mergedCanvas
10009
10083
  };
10010
10084
  }
10011
10085
  function convertCoreMessage(msg) {
@@ -10223,6 +10297,7 @@ function BotDojoChatProvider(props) {
10223
10297
  const pendingToolNotificationsRef = useRef(/* @__PURE__ */ new Map());
10224
10298
  const pendingBroadcastNotificationsRef = useRef([]);
10225
10299
  const toolArgumentsCacheRef = useRef(/* @__PURE__ */ new Map());
10300
+ const mcpAppDataCacheRef = useRef(/* @__PURE__ */ new Map());
10226
10301
  const pendingStepUpdatesRef = useRef(/* @__PURE__ */ new Map());
10227
10302
  const appHandlersRef = useRef({
10228
10303
  onOpenLink,
@@ -10473,12 +10548,30 @@ function BotDojoChatProvider(props) {
10473
10548
  }
10474
10549
  }
10475
10550
  };
10476
- return await tool2.execute(args, executionContext);
10551
+ const result = await tool2.execute(args, executionContext);
10552
+ if (result !== void 0) {
10553
+ await executionContext.notifyToolResult(result);
10554
+ }
10555
+ return result;
10477
10556
  }
10478
10557
  }
10479
10558
  }
10480
10559
  throw new Error(`Tool not found: ${toolName}`);
10481
10560
  }, []);
10561
+ const getMcpAppData = useCallback((appId) => {
10562
+ const cached = mcpAppDataCacheRef.current.get(appId);
10563
+ if (!cached)
10564
+ return null;
10565
+ return {
10566
+ mcpAppId: appId,
10567
+ mcpAppType: "mcp-app",
10568
+ ...cached
10569
+ };
10570
+ }, []);
10571
+ const updateMcpAppDataCache = useCallback((appId, data) => {
10572
+ const existing = mcpAppDataCacheRef.current.get(appId) || {};
10573
+ mcpAppDataCacheRef.current.set(appId, { ...existing, ...data });
10574
+ }, []);
10482
10575
  const getResource = useCallback(async (uri, params, onlyMetadata) => {
10483
10576
  console.log("[BotDojoChatProvider] getResource called for URI:", uri);
10484
10577
  const ctx = modelContextRef.current;
@@ -10741,7 +10834,7 @@ function BotDojoChatProvider(props) {
10741
10834
  }
10742
10835
  }
10743
10836
  (async () => {
10744
- var _a2, _b, _c, _d, _e, _f, _g, _h, _i;
10837
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
10745
10838
  let stepToDispatch = rawStep;
10746
10839
  const canvasUrl = (_b = (_a2 = rawStep == null ? void 0 : rawStep.canvas) == null ? void 0 : _a2.canvasData) == null ? void 0 : _b.url;
10747
10840
  if (canvasUrl && canvasUrl.startsWith("ui://") && !((_d = (_c = rawStep == null ? void 0 : rawStep.canvas) == null ? void 0 : _c.canvasData) == null ? void 0 : _d.html)) {
@@ -10783,6 +10876,17 @@ ${htmlContent}`;
10783
10876
  }
10784
10877
  };
10785
10878
  console.log("[BotDojoChatProvider] \u2705 Resolved ui:// resource to HTML (" + htmlContent.length + " chars)");
10879
+ const appIdForCache = rawStep.canvas.canvasId;
10880
+ if (appIdForCache) {
10881
+ const toolNameForCache = rawStep.stepToolName || rawStep.stepLabel;
10882
+ updateMcpAppDataCache(appIdForCache, {
10883
+ html: htmlContent,
10884
+ url: canvasUrl,
10885
+ toolInfo: toolNameForCache ? { tool: { name: toolNameForCache } } : void 0,
10886
+ height: (_e = rawStep.canvas.canvasData) == null ? void 0 : _e.height,
10887
+ width: (_f = rawStep.canvas.canvasData) == null ? void 0 : _f.width
10888
+ });
10889
+ }
10786
10890
  } else {
10787
10891
  console.warn("[BotDojoChatProvider] \u26A0\uFE0F Resource resolved but no text/content found:", Object.keys(resource || {}));
10788
10892
  }
@@ -10796,19 +10900,33 @@ ${htmlContent}`;
10796
10900
  messageId: data.messageId,
10797
10901
  step: stepToDispatch
10798
10902
  });
10799
- const appIdFromCanvas = (_e = stepToDispatch == null ? void 0 : stepToDispatch.canvas) == null ? void 0 : _e.canvasId;
10903
+ const appIdFromCanvas = (_g = stepToDispatch == null ? void 0 : stepToDispatch.canvas) == null ? void 0 : _g.canvasId;
10800
10904
  const appIdFromStepId = (stepToDispatch == null ? void 0 : stepToDispatch.stepId) ? stepIdToAppIdRef.current.get(stepToDispatch.stepId) : void 0;
10801
10905
  const toolNameForLookup = (stepToDispatch == null ? void 0 : stepToDispatch.stepToolName) || (stepToDispatch == null ? void 0 : stepToDispatch.stepLabel);
10802
10906
  const appIdFromToolName = toolNameForLookup ? activeAppByToolRef.current.get(toolNameForLookup) : void 0;
10803
10907
  const appId = appIdFromCanvas || appIdFromStepId || appIdFromToolName;
10804
10908
  if (appId) {
10805
10909
  const toolName = stepToDispatch.stepToolName || stepToDispatch.stepLabel;
10806
- const canvasResult = (_g = (_f = stepToDispatch == null ? void 0 : stepToDispatch.canvas) == null ? void 0 : _f.canvasData) == null ? void 0 : _g.result;
10910
+ const parseIfJson = (value2) => {
10911
+ if (value2 === void 0 || value2 === null || value2 === "")
10912
+ return void 0;
10913
+ if (typeof value2 === "object")
10914
+ return value2;
10915
+ if (typeof value2 === "string" && value2.trim()) {
10916
+ try {
10917
+ return JSON.parse(value2);
10918
+ } catch {
10919
+ return value2;
10920
+ }
10921
+ }
10922
+ return value2;
10923
+ };
10924
+ const canvasResult = parseIfJson((_i = (_h = stepToDispatch == null ? void 0 : stepToDispatch.canvas) == null ? void 0 : _h.canvasData) == null ? void 0 : _i.result);
10807
10925
  const rawStepResult = stepToDispatch.stepToolResult;
10808
- const stepResult = rawStepResult !== void 0 && rawStepResult !== "" && typeof rawStepResult !== "string" ? rawStepResult : rawStepResult && rawStepResult !== "" ? rawStepResult : canvasResult !== void 0 && canvasResult !== "" ? canvasResult : stepToDispatch.content || void 0;
10926
+ const stepResult = rawStepResult !== void 0 && rawStepResult !== "" ? parseIfJson(rawStepResult) : canvasResult !== void 0 ? canvasResult : parseIfJson(stepToDispatch.content);
10809
10927
  const rawStepArgs = stepToDispatch.stepToolArguments;
10810
10928
  const rawArgsString = stepToDispatch.arguments;
10811
- const canvasArgs = (_i = (_h = stepToDispatch == null ? void 0 : stepToDispatch.canvas) == null ? void 0 : _h.canvasData) == null ? void 0 : _i.arguments;
10929
+ const canvasArgs = (_k = (_j = stepToDispatch == null ? void 0 : stepToDispatch.canvas) == null ? void 0 : _j.canvasData) == null ? void 0 : _k.arguments;
10812
10930
  let stepArguments = rawStepArgs && typeof rawStepArgs === "object" ? rawStepArgs : null;
10813
10931
  if (!stepArguments && rawArgsString && rawArgsString.trim()) {
10814
10932
  try {
@@ -10835,6 +10953,12 @@ ${htmlContent}`;
10835
10953
  stepToolArguments: stepArguments != null ? stepArguments : void 0,
10836
10954
  stepToolResult: stepResult
10837
10955
  };
10956
+ updateMcpAppDataCache(appId, {
10957
+ ...stepArguments ? { arguments: stepArguments } : {},
10958
+ ...stepResult !== void 0 ? { result: stepResult } : {},
10959
+ ...stepToDispatch.stepStatus === "complete" ? { isComplete: true } : {},
10960
+ ...toolName ? { toolInfo: { tool: { name: toolName } } } : {}
10961
+ });
10838
10962
  const callback = stepUpdateCallbacksRef.current.get(appId);
10839
10963
  if (callback) {
10840
10964
  console.log(`[BotDojoChatProvider] Sending step update via callback to app: ${appId}`, {
@@ -10896,9 +11020,10 @@ ${htmlContent}`;
10896
11020
  sendToolNotificationToApp,
10897
11021
  registerStepUpdateCallback,
10898
11022
  sendStepUpdateToApp,
11023
+ getMcpAppData,
10899
11024
  appHandlers: appHandlersRef
10900
11025
  }),
10901
- [state, connector, registerMcpApp, unregisterMcpApp, registeredMcpApps, registerToolNotificationSender, sendToolNotificationToApp, registerStepUpdateCallback, sendStepUpdateToApp]
11026
+ [state, connector, registerMcpApp, unregisterMcpApp, registeredMcpApps, registerToolNotificationSender, sendToolNotificationToApp, registerStepUpdateCallback, sendStepUpdateToApp, getMcpAppData]
10902
11027
  );
10903
11028
  return /* @__PURE__ */ jsxs(BotDojoChatContext.Provider, { value: contextValue, children: [
10904
11029
  children,
@@ -11198,10 +11323,20 @@ function useMcpAppHostRequired() {
11198
11323
  }
11199
11324
  return context;
11200
11325
  }
11326
+ function getContentKey(appHtml, appUrl) {
11327
+ if (appUrl)
11328
+ return `url:${appUrl}`;
11329
+ if (appHtml) {
11330
+ const prefix = appHtml.slice(0, 100);
11331
+ const suffix = appHtml.slice(-100);
11332
+ return `html:${appHtml.length}:${prefix}:${suffix}`;
11333
+ }
11334
+ return "empty";
11335
+ }
11201
11336
  function McpAppHost(props) {
11337
+ var _a;
11202
11338
  const {
11203
11339
  mcpAppId,
11204
- mcpAppData,
11205
11340
  onOpenLink,
11206
11341
  onToolCall,
11207
11342
  onUiMessage,
@@ -11215,8 +11350,7 @@ function McpAppHost(props) {
11215
11350
  debug = false
11216
11351
  } = props;
11217
11352
  const iframeRef = useRef(null);
11218
- const [isInitialized, setIsInitialized] = useState(false);
11219
- const [iframeLoaded, setIframeLoaded] = useState(false);
11353
+ const [iframeState, setIframeState] = useState("idle");
11220
11354
  const [autoHeight, setAutoHeight] = useState(null);
11221
11355
  const pendingRequestsRef = useRef(/* @__PURE__ */ new Map());
11222
11356
  const nextRequestIdRef = useRef(0);
@@ -11225,17 +11359,20 @@ function McpAppHost(props) {
11225
11359
  const mcpAppHostContext = useMcpAppHost();
11226
11360
  const chatContext = useContext(BotDojoChatContext);
11227
11361
  const pendingNotificationsRef = useRef([]);
11228
- const isInitializedRef = useRef(false);
11362
+ const mcpAppData = (_a = chatContext == null ? void 0 : chatContext.getMcpAppData) == null ? void 0 : _a.call(chatContext, mcpAppId);
11229
11363
  const appUrl = mcpAppData == null ? void 0 : mcpAppData.url;
11230
11364
  const appHtml = mcpAppData == null ? void 0 : mcpAppData.html;
11365
+ const contentKey = useMemo(() => getContentKey(appHtml, appUrl), [appHtml, appUrl]);
11366
+ const renderedContentKeyRef = useRef("");
11367
+ const currentBlobUrlRef = useRef(null);
11231
11368
  const log = useCallback((...args) => {
11232
11369
  if (debug) {
11233
11370
  console.log(`[McpAppHost:${mcpAppId}]`, ...args);
11234
11371
  }
11235
11372
  }, [debug, mcpAppId]);
11236
11373
  const sendResponse = useCallback((id, result) => {
11237
- var _a;
11238
- if (!((_a = iframeRef.current) == null ? void 0 : _a.contentWindow))
11374
+ var _a2;
11375
+ if (!((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow))
11239
11376
  return;
11240
11377
  iframeRef.current.contentWindow.postMessage(
11241
11378
  { jsonrpc: "2.0", id, result },
@@ -11243,8 +11380,8 @@ function McpAppHost(props) {
11243
11380
  );
11244
11381
  }, []);
11245
11382
  const sendError = useCallback((id, code, message) => {
11246
- var _a;
11247
- if (!((_a = iframeRef.current) == null ? void 0 : _a.contentWindow))
11383
+ var _a2;
11384
+ if (!((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow))
11248
11385
  return;
11249
11386
  iframeRef.current.contentWindow.postMessage(
11250
11387
  { jsonrpc: "2.0", id, error: { code, message } },
@@ -11252,8 +11389,8 @@ function McpAppHost(props) {
11252
11389
  );
11253
11390
  }, []);
11254
11391
  const sendNotification = useCallback((method, params) => {
11255
- var _a;
11256
- if (!((_a = iframeRef.current) == null ? void 0 : _a.contentWindow))
11392
+ var _a2;
11393
+ if (!((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow))
11257
11394
  return;
11258
11395
  log("Sending notification:", method, params);
11259
11396
  iframeRef.current.contentWindow.postMessage(
@@ -11263,8 +11400,8 @@ function McpAppHost(props) {
11263
11400
  }, [log]);
11264
11401
  const sendRequest = useCallback((method, params, timeout = 5e3) => {
11265
11402
  return new Promise((resolve, reject) => {
11266
- var _a;
11267
- if (!((_a = iframeRef.current) == null ? void 0 : _a.contentWindow)) {
11403
+ var _a2;
11404
+ if (!((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow)) {
11268
11405
  reject(new Error("Iframe not ready"));
11269
11406
  return;
11270
11407
  }
@@ -11282,11 +11419,10 @@ function McpAppHost(props) {
11282
11419
  });
11283
11420
  }, [log]);
11284
11421
  const sendInitialize = useCallback(() => {
11285
- var _a;
11286
- if (isInitialized || !((_a = iframeRef.current) == null ? void 0 : _a.contentWindow))
11422
+ var _a2;
11423
+ if (iframeStateRef.current === "ready" || !((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow))
11287
11424
  return;
11288
11425
  const hostContext = {
11289
- // Include mcpAppId so app knows its canvas ID for message routing
11290
11426
  mcpAppId,
11291
11427
  state: mcpAppData == null ? void 0 : mcpAppData.state,
11292
11428
  toolInfo: mcpAppData == null ? void 0 : mcpAppData.toolInfo,
@@ -11310,12 +11446,14 @@ function McpAppHost(props) {
11310
11446
  }).catch((err) => {
11311
11447
  log("ui/initialize failed:", err.message);
11312
11448
  });
11313
- }, [isInitialized, mcpAppId, mcpAppData, initialHostContext, log, sendRequest]);
11449
+ }, [mcpAppId, mcpAppData, initialHostContext, log, sendRequest]);
11450
+ const iframeStateRef = useRef(iframeState);
11451
+ iframeStateRef.current = iframeState;
11314
11452
  const sendInitializeWithRetry = useCallback(() => {
11315
- if (isInitialized)
11453
+ if (iframeStateRef.current === "ready")
11316
11454
  return;
11317
11455
  const attemptSend = () => {
11318
- if (isInitialized)
11456
+ if (iframeStateRef.current === "ready")
11319
11457
  return;
11320
11458
  initializeAttemptsRef.current += 1;
11321
11459
  sendInitialize();
@@ -11331,16 +11469,63 @@ function McpAppHost(props) {
11331
11469
  }
11332
11470
  initializeAttemptsRef.current = 0;
11333
11471
  attemptSend();
11334
- }, [isInitialized, sendInitialize, log]);
11472
+ }, [sendInitialize, log]);
11473
+ const sendHydrationData = useCallback(() => {
11474
+ var _a2, _b, _c;
11475
+ const toolName = (_b = (_a2 = mcpAppData == null ? void 0 : mcpAppData.toolInfo) == null ? void 0 : _a2.tool) == null ? void 0 : _b.name;
11476
+ if (!toolName || !((_c = iframeRef.current) == null ? void 0 : _c.contentWindow))
11477
+ return;
11478
+ const parseMaybeJson2 = (value2) => {
11479
+ if (value2 === void 0 || value2 === null || value2 === "")
11480
+ return void 0;
11481
+ if (typeof value2 === "object")
11482
+ return value2;
11483
+ if (typeof value2 === "string" && value2.trim()) {
11484
+ try {
11485
+ return JSON.parse(value2);
11486
+ } catch {
11487
+ return value2;
11488
+ }
11489
+ }
11490
+ return value2;
11491
+ };
11492
+ const args = parseMaybeJson2(mcpAppData == null ? void 0 : mcpAppData.arguments);
11493
+ const result = parseMaybeJson2(mcpAppData == null ? void 0 : mcpAppData.result);
11494
+ const toolIsComplete = mcpAppData == null ? void 0 : mcpAppData.isComplete;
11495
+ const hasValidArgs = args !== void 0 && typeof args === "object" && Object.keys(args).length > 0;
11496
+ const hasValidResult = result !== void 0 && result !== "";
11497
+ log("Sending hydration data:", { toolName, hasArgs: hasValidArgs, hasResult: hasValidResult });
11498
+ if (hasValidArgs) {
11499
+ iframeRef.current.contentWindow.postMessage({
11500
+ jsonrpc: "2.0",
11501
+ method: "ui/notifications/tool-input",
11502
+ params: { tool: { name: toolName }, arguments: args }
11503
+ }, "*");
11504
+ }
11505
+ if (hasValidResult) {
11506
+ iframeRef.current.contentWindow.postMessage({
11507
+ jsonrpc: "2.0",
11508
+ method: "ui/notifications/tool-result",
11509
+ params: { tool: { name: toolName }, result }
11510
+ }, "*");
11511
+ } else if (toolIsComplete) {
11512
+ log("Sending synthetic tool-result for completed tool without stored result");
11513
+ iframeRef.current.contentWindow.postMessage({
11514
+ jsonrpc: "2.0",
11515
+ method: "ui/notifications/tool-result",
11516
+ params: { tool: { name: toolName }, result: { completed: true } }
11517
+ }, "*");
11518
+ }
11519
+ }, [mcpAppData, log]);
11335
11520
  const handleMessage = useCallback((event) => {
11336
- var _a, _b, _c, _d;
11521
+ var _a2;
11337
11522
  if (!iframeRef.current || event.source !== iframeRef.current.contentWindow) {
11338
11523
  return;
11339
11524
  }
11340
11525
  if (mcpAppHostContext == null ? void 0 : mcpAppHostContext.findAppIdBySource) {
11341
11526
  const sourceAppId = mcpAppHostContext.findAppIdBySource(event.source);
11342
11527
  if (sourceAppId && sourceAppId !== mcpAppId) {
11343
- log("Message from different app, ignoring:", sourceAppId, "expected:", mcpAppId);
11528
+ log("Message from different app, ignoring:", sourceAppId);
11344
11529
  return;
11345
11530
  }
11346
11531
  }
@@ -11370,55 +11555,9 @@ function McpAppHost(props) {
11370
11555
  clearTimeout(initializeTimerRef.current);
11371
11556
  initializeTimerRef.current = null;
11372
11557
  }
11373
- setIsInitialized(true);
11374
- isInitializedRef.current = true;
11375
- const toolName = (_b = (_a = mcpAppData == null ? void 0 : mcpAppData.toolInfo) == null ? void 0 : _a.tool) == null ? void 0 : _b.name;
11376
- if (toolName && ((_c = iframeRef.current) == null ? void 0 : _c.contentWindow)) {
11377
- const rawArgs = mcpAppData == null ? void 0 : mcpAppData.arguments;
11378
- const rawResult = mcpAppData == null ? void 0 : mcpAppData.result;
11379
- const args = rawArgs && rawArgs !== "" && typeof rawArgs === "object" ? rawArgs : void 0;
11380
- const result = rawResult !== void 0 && rawResult !== "" ? rawResult : void 0;
11381
- const toolIsComplete = mcpAppData == null ? void 0 : mcpAppData.isComplete;
11382
- log("Sending hydration data after initialized:", {
11383
- toolName,
11384
- hasArgs: args !== void 0,
11385
- hasResult: result !== void 0,
11386
- isComplete: toolIsComplete,
11387
- rawArgs,
11388
- rawResult
11389
- });
11390
- if (args !== void 0) {
11391
- iframeRef.current.contentWindow.postMessage({
11392
- jsonrpc: "2.0",
11393
- method: "ui/notifications/tool-input",
11394
- params: {
11395
- tool: { name: toolName },
11396
- arguments: args
11397
- }
11398
- }, "*");
11399
- }
11400
- if (result !== void 0) {
11401
- iframeRef.current.contentWindow.postMessage({
11402
- jsonrpc: "2.0",
11403
- method: "ui/notifications/tool-result",
11404
- params: {
11405
- tool: { name: toolName },
11406
- result
11407
- }
11408
- }, "*");
11409
- } else if (toolIsComplete) {
11410
- log("Sending synthetic tool-result for completed tool without stored result");
11411
- iframeRef.current.contentWindow.postMessage({
11412
- jsonrpc: "2.0",
11413
- method: "ui/notifications/tool-result",
11414
- params: {
11415
- tool: { name: toolName },
11416
- result: { completed: true }
11417
- }
11418
- }, "*");
11419
- }
11420
- }
11421
- if (pendingNotificationsRef.current.length > 0 && ((_d = iframeRef.current) == null ? void 0 : _d.contentWindow)) {
11558
+ setIframeState("ready");
11559
+ sendHydrationData();
11560
+ if (pendingNotificationsRef.current.length > 0 && ((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow)) {
11422
11561
  log(`Replaying ${pendingNotificationsRef.current.length} queued notifications`);
11423
11562
  pendingNotificationsRef.current.forEach(({ method: method2, params: params2 }) => {
11424
11563
  log("Replaying notification:", method2, params2);
@@ -11455,7 +11594,7 @@ function McpAppHost(props) {
11455
11594
  clearTimeout(initializeTimerRef.current);
11456
11595
  initializeTimerRef.current = null;
11457
11596
  }
11458
- setIsInitialized(true);
11597
+ setIframeState("ready");
11459
11598
  onReady == null ? void 0 : onReady(mcpAppId);
11460
11599
  break;
11461
11600
  }
@@ -11496,15 +11635,12 @@ function McpAppHost(props) {
11496
11635
  const contentArray = Array.isArray(params == null ? void 0 : params.content) ? params.content : [params == null ? void 0 : params.content].filter(Boolean);
11497
11636
  const firstContent = contentArray[0];
11498
11637
  if ((firstContent == null ? void 0 : firstContent["botdojo/messageType"]) === "persist-state" && typeof firstContent.text === "string") {
11499
- log("Persist state message received (format 1: messageType + text)");
11638
+ log("Persist state message received (format 1)");
11500
11639
  try {
11501
11640
  const parsed = JSON.parse(firstContent.text);
11502
- log("Parsed state to persist:", parsed);
11503
11641
  const persistHandler = onPersistState || (mcpAppHostContext == null ? void 0 : mcpAppHostContext.onPersistState);
11504
11642
  if (persistHandler) {
11505
11643
  persistHandler(parsed, mcpAppId);
11506
- } else {
11507
- log("No onPersistState handler provided - state will not be saved");
11508
11644
  }
11509
11645
  } catch (err) {
11510
11646
  log("Failed to parse persist-state content:", err);
@@ -11515,13 +11651,10 @@ function McpAppHost(props) {
11515
11651
  break;
11516
11652
  }
11517
11653
  if ((firstContent == null ? void 0 : firstContent.type) === "botdojo/persist" && firstContent.state) {
11518
- log("Persist state message received (format 2/3: type + state object)");
11519
- log("State to persist:", firstContent.state);
11654
+ log("Persist state message received (format 2/3)");
11520
11655
  const persistHandler = onPersistState || (mcpAppHostContext == null ? void 0 : mcpAppHostContext.onPersistState);
11521
11656
  if (persistHandler) {
11522
11657
  persistHandler(firstContent.state, mcpAppId);
11523
- } else {
11524
- log("No onPersistState handler provided - state will not be saved");
11525
11658
  }
11526
11659
  if (id !== void 0) {
11527
11660
  sendResponse(id, { ok: true });
@@ -11569,21 +11702,72 @@ function McpAppHost(props) {
11569
11702
  log,
11570
11703
  sendResponse,
11571
11704
  sendError,
11572
- sendNotification
11705
+ sendNotification,
11706
+ sendHydrationData
11573
11707
  ]);
11574
11708
  useEffect(() => {
11575
11709
  window.addEventListener("message", handleMessage);
11576
11710
  return () => window.removeEventListener("message", handleMessage);
11577
11711
  }, [handleMessage]);
11578
11712
  useEffect(() => {
11579
- if (iframeLoaded && !isInitialized) {
11713
+ if (!iframeRef.current)
11714
+ return;
11715
+ if (contentKey === renderedContentKeyRef.current && iframeState !== "idle") {
11716
+ log("Content key unchanged, keeping existing iframe");
11717
+ return;
11718
+ }
11719
+ if (contentKey === "empty") {
11720
+ if (iframeState === "ready" && iframeRef.current.src) {
11721
+ log("Content became empty but iframe is ready, preserving");
11722
+ renderedContentKeyRef.current = contentKey;
11723
+ return;
11724
+ }
11725
+ if (iframeState !== "idle" && iframeRef.current.src) {
11726
+ log("Content became empty but iframe is loading/initializing, preserving");
11727
+ renderedContentKeyRef.current = contentKey;
11728
+ return;
11729
+ }
11730
+ if (iframeState === "idle" && !iframeRef.current.src) {
11731
+ log("Content is empty and iframe is idle with no src, skipping");
11732
+ renderedContentKeyRef.current = contentKey;
11733
+ return;
11734
+ }
11735
+ }
11736
+ log("Content key changed:", { old: renderedContentKeyRef.current, new: contentKey });
11737
+ renderedContentKeyRef.current = contentKey;
11738
+ setIframeState("idle");
11739
+ setAutoHeight(null);
11740
+ initializeAttemptsRef.current = 0;
11741
+ pendingNotificationsRef.current = [];
11742
+ if (initializeTimerRef.current !== null) {
11743
+ clearTimeout(initializeTimerRef.current);
11744
+ initializeTimerRef.current = null;
11745
+ }
11746
+ if (currentBlobUrlRef.current) {
11747
+ URL.revokeObjectURL(currentBlobUrlRef.current);
11748
+ currentBlobUrlRef.current = null;
11749
+ }
11750
+ if (appHtml) {
11751
+ const blob = new Blob([appHtml], { type: "text/html" });
11752
+ const url2 = URL.createObjectURL(blob);
11753
+ currentBlobUrlRef.current = url2;
11754
+ iframeRef.current.src = url2;
11755
+ log("Set iframe src to blob URL");
11756
+ } else if (appUrl) {
11757
+ iframeRef.current.src = appUrl;
11758
+ log("Set iframe src to URL:", appUrl);
11759
+ }
11760
+ }, [contentKey, appHtml, appUrl, iframeState, log]);
11761
+ useEffect(() => {
11762
+ if (iframeState === "loading") {
11580
11763
  log("Iframe loaded, sending ui/initialize");
11764
+ setIframeState("initializing");
11581
11765
  sendInitializeWithRetry();
11582
11766
  }
11583
- }, [iframeLoaded, isInitialized, sendInitializeWithRetry, log]);
11767
+ }, [iframeState, sendInitializeWithRetry, log]);
11584
11768
  const prevStateRef = useRef(void 0);
11585
11769
  useEffect(() => {
11586
- if (!isInitialized) {
11770
+ if (iframeState !== "ready") {
11587
11771
  prevStateRef.current = mcpAppData == null ? void 0 : mcpAppData.state;
11588
11772
  return;
11589
11773
  }
@@ -11591,7 +11775,7 @@ function McpAppHost(props) {
11591
11775
  const prevState = prevStateRef.current;
11592
11776
  const stateChanged = JSON.stringify(currentState) !== JSON.stringify(prevState);
11593
11777
  if (stateChanged && currentState !== void 0) {
11594
- log("State changed after initialization, sending host-context-changed", { prevState, currentState });
11778
+ log("State changed after initialization, sending host-context-changed");
11595
11779
  sendNotification("ui/notifications/host-context-changed", {
11596
11780
  state: currentState,
11597
11781
  toolInfo: mcpAppData == null ? void 0 : mcpAppData.toolInfo,
@@ -11599,14 +11783,14 @@ function McpAppHost(props) {
11599
11783
  });
11600
11784
  prevStateRef.current = currentState;
11601
11785
  }
11602
- }, [isInitialized, mcpAppData == null ? void 0 : mcpAppData.state, mcpAppData == null ? void 0 : mcpAppData.toolInfo, initialHostContext, sendNotification, log]);
11786
+ }, [iframeState, mcpAppData == null ? void 0 : mcpAppData.state, mcpAppData == null ? void 0 : mcpAppData.toolInfo, initialHostContext, sendNotification, log]);
11603
11787
  const handleIframeLoad = useCallback(() => {
11604
11788
  log("Iframe onLoad fired");
11605
- setIframeLoaded(true);
11789
+ setIframeState((prev2) => prev2 === "idle" ? "loading" : prev2);
11606
11790
  }, [log]);
11607
11791
  useEffect(() => {
11608
- var _a;
11609
- if (mcpAppHostContext && ((_a = iframeRef.current) == null ? void 0 : _a.contentWindow)) {
11792
+ var _a2;
11793
+ if (mcpAppHostContext && ((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow)) {
11610
11794
  mcpAppHostContext.registerApp(mcpAppId, iframeRef.current.contentWindow);
11611
11795
  return () => mcpAppHostContext.unregisterApp(mcpAppId);
11612
11796
  }
@@ -11616,38 +11800,26 @@ function McpAppHost(props) {
11616
11800
  useEffect(() => {
11617
11801
  const ctx = chatContextRef.current;
11618
11802
  if (!(ctx == null ? void 0 : ctx.registerToolNotificationSender)) {
11619
- console.log(`[McpAppHost:${mcpAppId}] No registerToolNotificationSender available in context`);
11620
11803
  return;
11621
11804
  }
11622
- console.log(`[McpAppHost:${mcpAppId}] Registering tool notification sender`);
11623
11805
  const sender = (method, params) => {
11624
- var _a;
11625
- if (!isInitializedRef.current || !((_a = iframeRef.current) == null ? void 0 : _a.contentWindow)) {
11626
- console.log(`[McpAppHost:${mcpAppId}] Iframe not initialized, queueing notification:`, method);
11806
+ var _a2;
11807
+ if (iframeStateRef.current !== "ready" || !((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow)) {
11627
11808
  pendingNotificationsRef.current.push({ method, params });
11628
11809
  return;
11629
11810
  }
11630
11811
  if (method === "ui/notifications/tool-input" || method === "ui/notifications/tool-input-partial") {
11631
11812
  const args = params == null ? void 0 : params.arguments;
11632
11813
  if (!args || args === "" || typeof args !== "object" || Object.keys(args).length === 0) {
11633
- if (debug) {
11634
- console.log(`[McpAppHost:${mcpAppId}] Skipping ${method} - empty arguments:`, args);
11635
- }
11636
11814
  return;
11637
11815
  }
11638
11816
  }
11639
11817
  if (method === "ui/notifications/tool-result") {
11640
11818
  const result = params == null ? void 0 : params.result;
11641
11819
  if (result === "" || result === void 0) {
11642
- if (debug) {
11643
- console.log(`[McpAppHost:${mcpAppId}] Skipping ${method} - empty result:`, result);
11644
- }
11645
11820
  return;
11646
11821
  }
11647
11822
  }
11648
- if (debug) {
11649
- console.log(`[McpAppHost:${mcpAppId}] Forwarding tool notification:`, method, params);
11650
- }
11651
11823
  iframeRef.current.contentWindow.postMessage(
11652
11824
  { jsonrpc: "2.0", method, params },
11653
11825
  "*"
@@ -11655,100 +11827,85 @@ function McpAppHost(props) {
11655
11827
  };
11656
11828
  const unregister = ctx.registerToolNotificationSender(mcpAppId, sender);
11657
11829
  return unregister;
11658
- }, [mcpAppId, debug]);
11830
+ }, [mcpAppId]);
11659
11831
  useEffect(() => {
11660
11832
  const ctx = chatContextRef.current;
11661
11833
  if (!(ctx == null ? void 0 : ctx.registerStepUpdateCallback)) {
11662
- console.log(`[McpAppHost:${mcpAppId}] No registerStepUpdateCallback available in context`);
11663
11834
  return;
11664
11835
  }
11665
- console.log(`[McpAppHost:${mcpAppId}] Registering step update callback`);
11666
11836
  const callback = (stepUpdate) => {
11667
- var _a;
11668
- if (!((_a = iframeRef.current) == null ? void 0 : _a.contentWindow))
11837
+ var _a2;
11838
+ if (!((_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow))
11669
11839
  return;
11670
- if (debug) {
11671
- console.log(`[McpAppHost:${mcpAppId}] Received step update via callback:`, stepUpdate);
11672
- }
11673
11840
  const toolName = (stepUpdate == null ? void 0 : stepUpdate.stepToolName) || (stepUpdate == null ? void 0 : stepUpdate.toolName);
11674
11841
  const toolPhase = stepUpdate == null ? void 0 : stepUpdate.toolPhase;
11675
11842
  const toolArguments = stepUpdate == null ? void 0 : stepUpdate.stepToolArguments;
11676
11843
  const toolProgress = stepUpdate == null ? void 0 : stepUpdate.stepToolProgress;
11677
- const toolResult = stepUpdate == null ? void 0 : stepUpdate.stepToolResult;
11844
+ const rawToolResult = stepUpdate == null ? void 0 : stepUpdate.stepToolResult;
11678
11845
  if (!toolName)
11679
11846
  return;
11680
- if (toolPhase === "executing" && toolArguments) {
11681
- if (debug) {
11682
- console.log(`[McpAppHost:${mcpAppId}] Sending tool-input (toolPhase=executing):`, toolArguments);
11683
- }
11684
- iframeRef.current.contentWindow.postMessage({
11685
- jsonrpc: "2.0",
11686
- method: "ui/notifications/tool-input",
11687
- params: {
11688
- tool: { name: toolName },
11689
- arguments: toolArguments
11847
+ const parseIfJson = (value2) => {
11848
+ if (value2 === void 0 || value2 === null || value2 === "")
11849
+ return void 0;
11850
+ if (typeof value2 === "object")
11851
+ return value2;
11852
+ if (typeof value2 === "string" && value2.trim()) {
11853
+ try {
11854
+ return JSON.parse(value2);
11855
+ } catch {
11856
+ return value2;
11690
11857
  }
11691
- }, "*");
11858
+ }
11859
+ return value2;
11860
+ };
11861
+ const toolResult = parseIfJson(rawToolResult);
11862
+ const sendOrQueue = (method, params) => {
11863
+ var _a3;
11864
+ if (iframeStateRef.current === "ready" && ((_a3 = iframeRef.current) == null ? void 0 : _a3.contentWindow)) {
11865
+ iframeRef.current.contentWindow.postMessage({ jsonrpc: "2.0", method, params }, "*");
11866
+ } else {
11867
+ pendingNotificationsRef.current.push({ method, params });
11868
+ }
11869
+ };
11870
+ if (toolPhase === "executing" && toolArguments) {
11871
+ sendOrQueue("ui/notifications/tool-input", {
11872
+ tool: { name: toolName },
11873
+ arguments: toolArguments
11874
+ });
11692
11875
  }
11693
11876
  if (toolProgress) {
11694
- if (debug) {
11695
- console.log(`[McpAppHost:${mcpAppId}] Sending tool-input-partial (progress update):`, toolProgress);
11696
- }
11697
- iframeRef.current.contentWindow.postMessage({
11698
- jsonrpc: "2.0",
11699
- method: "ui/notifications/tool-input-partial",
11700
- params: {
11701
- tool: { name: toolName },
11702
- arguments: { ...toolProgress, _botdojoProgress: true }
11703
- }
11704
- }, "*");
11877
+ sendOrQueue("ui/notifications/tool-input-partial", {
11878
+ tool: { name: toolName },
11879
+ arguments: { ...toolProgress, _botdojoProgress: true }
11880
+ });
11705
11881
  } else if (toolPhase === "streaming_args" && (stepUpdate.stepId || stepUpdate.stepLabel)) {
11706
- if (debug) {
11707
- console.log(`[McpAppHost:${mcpAppId}] Sending tool-input-partial (streaming_args):`, { stepId: stepUpdate.stepId, stepLabel: stepUpdate.stepLabel });
11708
- }
11709
- iframeRef.current.contentWindow.postMessage({
11710
- jsonrpc: "2.0",
11711
- method: "ui/notifications/tool-input-partial",
11712
- params: {
11713
- tool: { name: toolName },
11714
- arguments: {
11715
- ...toolArguments || {},
11716
- stepId: stepUpdate.stepId,
11717
- stepLabel: stepUpdate.stepLabel
11718
- }
11882
+ sendOrQueue("ui/notifications/tool-input-partial", {
11883
+ tool: { name: toolName },
11884
+ arguments: {
11885
+ ...toolArguments || {},
11886
+ stepId: stepUpdate.stepId,
11887
+ stepLabel: stepUpdate.stepLabel
11719
11888
  }
11720
- }, "*");
11889
+ });
11721
11890
  }
11722
11891
  if (toolResult !== void 0 && toolResult !== "") {
11723
- if (debug) {
11724
- console.log(`[McpAppHost:${mcpAppId}] Sending tool-result:`, toolResult);
11725
- }
11726
- iframeRef.current.contentWindow.postMessage({
11727
- jsonrpc: "2.0",
11728
- method: "ui/notifications/tool-result",
11729
- params: {
11730
- tool: { name: toolName },
11731
- result: toolResult
11732
- }
11733
- }, "*");
11892
+ sendOrQueue("ui/notifications/tool-result", {
11893
+ tool: { name: toolName },
11894
+ result: toolResult
11895
+ });
11734
11896
  }
11735
11897
  };
11736
11898
  const unregister = ctx.registerStepUpdateCallback(mcpAppId, callback);
11737
11899
  return unregister;
11738
- }, [mcpAppId, debug]);
11900
+ }, [mcpAppId]);
11739
11901
  useEffect(() => {
11740
- if (!iframeRef.current)
11741
- return;
11742
- if (appHtml) {
11743
- const blob = new Blob([appHtml], { type: "text/html" });
11744
- const url2 = URL.createObjectURL(blob);
11745
- iframeRef.current.src = url2;
11746
- return () => URL.revokeObjectURL(url2);
11747
- }
11748
- if (appUrl) {
11749
- iframeRef.current.src = appUrl;
11750
- }
11751
- }, [appHtml, appUrl]);
11902
+ return () => {
11903
+ if (currentBlobUrlRef.current) {
11904
+ URL.revokeObjectURL(currentBlobUrlRef.current);
11905
+ currentBlobUrlRef.current = null;
11906
+ }
11907
+ };
11908
+ }, []);
11752
11909
  useEffect(() => {
11753
11910
  return () => {
11754
11911
  if (initializeTimerRef.current !== null) {
@@ -11762,18 +11919,6 @@ function McpAppHost(props) {
11762
11919
  pendingRequestsRef.current.clear();
11763
11920
  };
11764
11921
  }, []);
11765
- useEffect(() => {
11766
- setIframeLoaded(false);
11767
- setIsInitialized(false);
11768
- isInitializedRef.current = false;
11769
- setAutoHeight(null);
11770
- initializeAttemptsRef.current = 0;
11771
- pendingNotificationsRef.current = [];
11772
- if (initializeTimerRef.current !== null) {
11773
- clearTimeout(initializeTimerRef.current);
11774
- initializeTimerRef.current = null;
11775
- }
11776
- }, [appHtml, appUrl]);
11777
11922
  const effectiveHeight = autoHeight ? `${autoHeight}px` : (mcpAppData == null ? void 0 : mcpAppData.height) || height;
11778
11923
  return /* @__PURE__ */ jsx(
11779
11924
  "iframe",
@@ -11791,6 +11936,61 @@ function McpAppHost(props) {
11791
11936
  }
11792
11937
  );
11793
11938
  }
11939
+
11940
+ // src/headless/types/headless.ts
11941
+ function parseMaybeJson(value2) {
11942
+ if (value2 === void 0 || value2 === null || value2 === "")
11943
+ return void 0;
11944
+ if (typeof value2 === "object")
11945
+ return value2;
11946
+ if (typeof value2 === "string" && value2.trim()) {
11947
+ try {
11948
+ return JSON.parse(value2);
11949
+ } catch {
11950
+ return value2;
11951
+ }
11952
+ }
11953
+ return value2;
11954
+ }
11955
+ function extractMcpAppData(step, options) {
11956
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
11957
+ const canvas = step == null ? void 0 : step.canvas;
11958
+ if (!(canvas == null ? void 0 : canvas.canvasId)) {
11959
+ return null;
11960
+ }
11961
+ const toolName = step.stepToolName || ((_a = canvas.canvasData) == null ? void 0 : _a.toolName);
11962
+ let toolArguments = step.stepToolArguments;
11963
+ if (!toolArguments || typeof toolArguments === "object" && Object.keys(toolArguments).length === 0) {
11964
+ toolArguments = parseMaybeJson(step.arguments);
11965
+ }
11966
+ if (!toolArguments || typeof toolArguments === "object" && Object.keys(toolArguments).length === 0) {
11967
+ toolArguments = parseMaybeJson((_b = canvas.canvasData) == null ? void 0 : _b.arguments);
11968
+ }
11969
+ let toolResult = step.stepToolResult;
11970
+ if (toolResult === void 0 || toolResult === "") {
11971
+ toolResult = parseMaybeJson((_c = canvas.canvasData) == null ? void 0 : _c.result);
11972
+ }
11973
+ if (toolResult === void 0 || toolResult === "") {
11974
+ const toolPhase = step.stepToolPhase || step.toolPhase;
11975
+ if (toolPhase === "complete" && step.content) {
11976
+ toolResult = parseMaybeJson(step.content);
11977
+ }
11978
+ }
11979
+ return {
11980
+ mcpAppId: canvas.canvasId,
11981
+ mcpAppType: canvas.canvasType || "mcp-app",
11982
+ url: (_d = canvas.canvasData) == null ? void 0 : _d.url,
11983
+ html: (_e = canvas.canvasData) == null ? void 0 : _e.html,
11984
+ height: (_f = canvas.canvasData) == null ? void 0 : _f.height,
11985
+ width: (_g = canvas.canvasData) == null ? void 0 : _g.width,
11986
+ state: (_h = canvas.canvasData) == null ? void 0 : _h.state,
11987
+ arguments: toolArguments,
11988
+ result: toolResult,
11989
+ isComplete: (_i = options == null ? void 0 : options.isComplete) != null ? _i : false,
11990
+ // Include toolInfo for hydration - McpAppHost needs tool.name to send notifications
11991
+ toolInfo: toolName ? { tool: { name: toolName } } : void 0
11992
+ };
11993
+ }
11794
11994
  var DEFAULT_CONFIG = {
11795
11995
  mode: "chat-popup",
11796
11996
  popupOptions: {
@@ -13511,6 +13711,6 @@ var export_textResult = import_sdk_types2.textResult;
13511
13711
  var export_tool = import_sdk_types2.tool;
13512
13712
  var export_uiResource = import_sdk_types2.uiResource;
13513
13713
 
13514
- export { BotDojoCanvasFrame, BotDojoCanvasProvider, BotDojoChat, BotDojoChatConfigurator, BotDojoChatProvider, export_BotDojoConnector as BotDojoConnector, HeadlessChat, export_MIME_TYPES as MIME_TYPES, McpAppHost, McpAppHostContext, McpAppHostProvider, MockCanvasProvider, export_citation as citation, export_citations as citations, export_imageResult as imageResult, export_mcpResource as mcpResource, export_modelContext as modelContext, export_textResult as textResult, export_tool as tool, export_uiResource as uiResource, useBotDojoCanvas, useBotDojoChat, useChatActions, useChatMessages, useChatStatus, useMcpAppHost, useMcpAppHostRequired };
13714
+ export { BotDojoCanvasFrame, BotDojoCanvasProvider, BotDojoChat, BotDojoChatConfigurator, BotDojoChatProvider, export_BotDojoConnector as BotDojoConnector, HeadlessChat, export_MIME_TYPES as MIME_TYPES, McpAppHost, McpAppHostContext, McpAppHostProvider, MockCanvasProvider, export_citation as citation, export_citations as citations, extractMcpAppData, export_imageResult as imageResult, export_mcpResource as mcpResource, export_modelContext as modelContext, parseMaybeJson, export_textResult as textResult, export_tool as tool, export_uiResource as uiResource, useBotDojoCanvas, useBotDojoChat, useChatActions, useChatMessages, useChatStatus, useMcpAppHost, useMcpAppHostRequired };
13515
13715
  //# sourceMappingURL=out.js.map
13516
13716
  //# sourceMappingURL=index.js.map