@botdojo/chat-sdk 0.0.4 → 0.0.6
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/README.md +1 -1
- package/lib/index.d.ts +484 -39
- package/lib/index.js +2455 -526
- package/lib/index.js.map +1 -1
- package/package.json +1 -3
package/lib/index.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import React2, { useRef, useState, useCallback, useEffect, createContext, useMemo, useReducer, useContext } from 'react';
|
|
2
|
-
import { BotDojoConnector } from '@botdojo/sdk-canvas';
|
|
2
|
+
import { BotDojoConnector, extractUiCspFromResource, resolveUiCsp } from '@botdojo/sdk-canvas';
|
|
3
3
|
export { BotDojoConnector } from '@botdojo/sdk-canvas';
|
|
4
|
-
import { PostMessageBridge, RPCMessage, PostMessageRPCClient, RPCConnection, ConectionOptions
|
|
4
|
+
import { PostMessageBridge, RPCMessage, PostMessageRPCClient, RPCConnection, ConectionOptions } from 'botdojo-rpc';
|
|
5
5
|
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
|
|
6
|
-
|
|
6
|
+
import { translateModelContextToBackend } from '@botdojo/sdk-types';
|
|
7
|
+
export { MIME_TYPES, citation, citations, imageResult, mcpResource, modelContext, textResult, tool, uiResource } from '@botdojo/sdk-types';
|
|
7
8
|
|
|
8
9
|
// src/BotDojoChat.tsx
|
|
9
10
|
var BotDojoChat = ({
|
|
@@ -12,7 +13,7 @@ var BotDojoChat = ({
|
|
|
12
13
|
popupOptions,
|
|
13
14
|
sidePanelOptions,
|
|
14
15
|
width = "400px",
|
|
15
|
-
height = "
|
|
16
|
+
height = "100%",
|
|
16
17
|
accentColor = "#4a3ed4",
|
|
17
18
|
backgroundColor = "#ffffff",
|
|
18
19
|
theme,
|
|
@@ -26,15 +27,31 @@ var BotDojoChat = ({
|
|
|
26
27
|
hideBotIcon = false,
|
|
27
28
|
newSession = false,
|
|
28
29
|
sessionId,
|
|
30
|
+
sessionKeyPrefix,
|
|
31
|
+
welcomeMessage,
|
|
29
32
|
allowMicrophone = false,
|
|
30
33
|
baseUrl,
|
|
31
|
-
modelContext,
|
|
34
|
+
modelContext: modelContext2,
|
|
32
35
|
onLoad,
|
|
33
36
|
onOpen,
|
|
34
37
|
onClose,
|
|
35
38
|
onConnectorInit,
|
|
36
39
|
onConnectorError,
|
|
37
|
-
onBotDojoChatControl
|
|
40
|
+
onBotDojoChatControl,
|
|
41
|
+
// Flow event handlers
|
|
42
|
+
onReady,
|
|
43
|
+
onError,
|
|
44
|
+
onMessageStart,
|
|
45
|
+
onMessageComplete,
|
|
46
|
+
onStepUpdate,
|
|
47
|
+
onToken,
|
|
48
|
+
onSessionCreated,
|
|
49
|
+
onSessionHydrated,
|
|
50
|
+
onRequestAborted,
|
|
51
|
+
// MCP App event handlers
|
|
52
|
+
onOpenLink,
|
|
53
|
+
onToolCall,
|
|
54
|
+
onUiMessage
|
|
38
55
|
}) => {
|
|
39
56
|
const popupConfig = {
|
|
40
57
|
width: (popupOptions == null ? void 0 : popupOptions.width) || width,
|
|
@@ -69,34 +86,80 @@ var BotDojoChat = ({
|
|
|
69
86
|
const iframeLoadedRef = useRef(false);
|
|
70
87
|
const chatReadyRef = useRef(false);
|
|
71
88
|
const resizeStartPos = useRef({ x: 0, y: 0, width: 0, height: 0 });
|
|
89
|
+
const eventHandlersRef = useRef({
|
|
90
|
+
onReady,
|
|
91
|
+
onError,
|
|
92
|
+
onMessageStart,
|
|
93
|
+
onMessageComplete,
|
|
94
|
+
onStepUpdate,
|
|
95
|
+
onToken,
|
|
96
|
+
onSessionCreated,
|
|
97
|
+
onSessionHydrated,
|
|
98
|
+
onRequestAborted,
|
|
99
|
+
// MCP App handlers
|
|
100
|
+
onOpenLink,
|
|
101
|
+
onToolCall,
|
|
102
|
+
onUiMessage
|
|
103
|
+
});
|
|
104
|
+
useEffect(() => {
|
|
105
|
+
eventHandlersRef.current = {
|
|
106
|
+
onReady,
|
|
107
|
+
onError,
|
|
108
|
+
onMessageStart,
|
|
109
|
+
onMessageComplete,
|
|
110
|
+
onStepUpdate,
|
|
111
|
+
onToken,
|
|
112
|
+
onSessionCreated,
|
|
113
|
+
onSessionHydrated,
|
|
114
|
+
onRequestAborted,
|
|
115
|
+
onOpenLink,
|
|
116
|
+
onToolCall,
|
|
117
|
+
onUiMessage
|
|
118
|
+
};
|
|
119
|
+
}, [
|
|
120
|
+
onReady,
|
|
121
|
+
onError,
|
|
122
|
+
onMessageStart,
|
|
123
|
+
onMessageComplete,
|
|
124
|
+
onStepUpdate,
|
|
125
|
+
onToken,
|
|
126
|
+
onSessionCreated,
|
|
127
|
+
onSessionHydrated,
|
|
128
|
+
onRequestAborted,
|
|
129
|
+
onOpenLink,
|
|
130
|
+
onToolCall,
|
|
131
|
+
onUiMessage
|
|
132
|
+
]);
|
|
72
133
|
const hasModelContextContent = useMemo(() => {
|
|
73
|
-
if (!
|
|
134
|
+
if (!modelContext2)
|
|
74
135
|
return false;
|
|
75
|
-
const contexts = Array.isArray(
|
|
136
|
+
const contexts = Array.isArray(modelContext2) ? modelContext2 : [modelContext2];
|
|
76
137
|
return contexts.some((ctx) => {
|
|
77
138
|
const hasTools = ctx.tools && (Array.isArray(ctx.tools) ? ctx.tools.length > 0 : Object.keys(ctx.tools).length > 0);
|
|
78
139
|
const hasPrompts = ctx.prompts && (Array.isArray(ctx.prompts) ? ctx.prompts.length > 0 : Object.keys(ctx.prompts).length > 0);
|
|
79
140
|
const hasResources = ctx.resources && (Array.isArray(ctx.resources) ? ctx.resources.length > 0 : Object.keys(ctx.resources).length > 0);
|
|
80
141
|
return hasTools || hasPrompts || hasResources || !!ctx.name;
|
|
81
142
|
});
|
|
82
|
-
}, [
|
|
143
|
+
}, [modelContext2]);
|
|
83
144
|
const needsConnector = hasModelContextContent;
|
|
84
|
-
console.log("[BotDojoChat] needsConnector:", needsConnector, "hasModelContextContent:", hasModelContextContent);
|
|
85
145
|
const getBaseUrl = useCallback(() => {
|
|
86
146
|
if (baseUrl) {
|
|
87
147
|
return baseUrl;
|
|
88
148
|
}
|
|
89
149
|
return "https://embed.botdojo.com";
|
|
90
150
|
}, [baseUrl]);
|
|
91
|
-
const
|
|
151
|
+
const hasEventCallbacks = !!(onReady || onError || onMessageStart || onMessageComplete || onStepUpdate || onToken || onSessionCreated || onSessionHydrated || onRequestAborted);
|
|
152
|
+
console.log("[BotDojoChat] hasEventCallbacks:", hasEventCallbacks, {
|
|
153
|
+
onReady: !!onReady,
|
|
154
|
+
onToken: !!onToken,
|
|
155
|
+
onMessageStart: !!onMessageStart
|
|
156
|
+
});
|
|
157
|
+
const iframeUrl = useMemo(() => {
|
|
92
158
|
try {
|
|
93
|
-
const
|
|
94
|
-
const url = new URL(
|
|
159
|
+
const base = `${getBaseUrl()}/embed/chat?key=${encodeURIComponent(apiKey)}`;
|
|
160
|
+
const url = new URL(base);
|
|
95
161
|
url.searchParams.set("accent-color", accentColor);
|
|
96
162
|
url.searchParams.set("flow-version", flowVersion);
|
|
97
|
-
if (typeof window !== "undefined") {
|
|
98
|
-
url.searchParams.set("embedded-source-url", window.location.href);
|
|
99
|
-
}
|
|
100
163
|
if (flowHeaders)
|
|
101
164
|
url.searchParams.set("flow-headers", JSON.stringify(flowHeaders));
|
|
102
165
|
if (botImage)
|
|
@@ -109,6 +172,12 @@ var BotDojoChat = ({
|
|
|
109
172
|
url.searchParams.set("hide-bot-icon", "true");
|
|
110
173
|
if (sessionId)
|
|
111
174
|
url.searchParams.set("session-id", sessionId);
|
|
175
|
+
if (sessionKeyPrefix) {
|
|
176
|
+
url.searchParams.set("session-key-prefix", sessionKeyPrefix);
|
|
177
|
+
url.searchParams.set("agent-key", sessionKeyPrefix);
|
|
178
|
+
}
|
|
179
|
+
if (welcomeMessage)
|
|
180
|
+
url.searchParams.set("welcome-message", welcomeMessage);
|
|
112
181
|
if (fontSize)
|
|
113
182
|
url.searchParams.set("font-size", fontSize);
|
|
114
183
|
if (backgroundColor)
|
|
@@ -117,11 +186,14 @@ var BotDojoChat = ({
|
|
|
117
186
|
url.searchParams.set("theme", theme);
|
|
118
187
|
if (newSession)
|
|
119
188
|
url.searchParams.set("new-session", "true");
|
|
120
|
-
console.log("[BotDojoChat] Enabling postMessage transport (default for embedded chat)");
|
|
121
189
|
url.searchParams.set("transport", "postmessage");
|
|
122
190
|
url.searchParams.set("transport-mode", "iframe");
|
|
191
|
+
if (hasEventCallbacks) {
|
|
192
|
+
url.searchParams.set("forward-events", "true");
|
|
193
|
+
console.log("[BotDojoChat] Added forward-events=true to iframe URL");
|
|
194
|
+
}
|
|
123
195
|
const finalUrl = url.toString();
|
|
124
|
-
console.log("[BotDojoChat]
|
|
196
|
+
console.log("[BotDojoChat] iframeUrl:", finalUrl);
|
|
125
197
|
return finalUrl;
|
|
126
198
|
} catch (error) {
|
|
127
199
|
console.warn("[BotDojoChat] Error building iframe URL:", error);
|
|
@@ -136,11 +208,15 @@ var BotDojoChat = ({
|
|
|
136
208
|
botImage,
|
|
137
209
|
userImage,
|
|
138
210
|
voiceIcon,
|
|
211
|
+
hideBotIcon,
|
|
139
212
|
sessionId,
|
|
213
|
+
sessionKeyPrefix,
|
|
214
|
+
welcomeMessage,
|
|
140
215
|
fontSize,
|
|
141
216
|
backgroundColor,
|
|
142
217
|
theme,
|
|
143
|
-
newSession
|
|
218
|
+
newSession,
|
|
219
|
+
hasEventCallbacks
|
|
144
220
|
]);
|
|
145
221
|
useEffect(() => {
|
|
146
222
|
if (!needsConnector) {
|
|
@@ -158,7 +234,7 @@ var BotDojoChat = ({
|
|
|
158
234
|
accountId: "embedded",
|
|
159
235
|
projectId: "embedded",
|
|
160
236
|
flowId: "embedded",
|
|
161
|
-
modelContext,
|
|
237
|
+
modelContext: modelContext2,
|
|
162
238
|
// Don't pass toolCalls - tools will be registered from modelContext with canvas metadata preserved
|
|
163
239
|
transport: "postmessage"
|
|
164
240
|
// CORS is extracted from modelContext.cors by the connector
|
|
@@ -205,11 +281,11 @@ var BotDojoChat = ({
|
|
|
205
281
|
useEffect(() => {
|
|
206
282
|
if (!connector)
|
|
207
283
|
return;
|
|
208
|
-
if (
|
|
209
|
-
connector.setModelContext(
|
|
284
|
+
if (modelContext2) {
|
|
285
|
+
connector.setModelContext(modelContext2);
|
|
210
286
|
console.log("[BotDojoChat] Updated model context");
|
|
211
287
|
}
|
|
212
|
-
}, [connector,
|
|
288
|
+
}, [connector, modelContext2]);
|
|
213
289
|
const controlMethods = React2.useMemo(() => ({
|
|
214
290
|
openChat: () => {
|
|
215
291
|
if (mode === "inline") {
|
|
@@ -288,6 +364,270 @@ var BotDojoChat = ({
|
|
|
288
364
|
onBotDojoChatControl(controlMethods);
|
|
289
365
|
console.log("[BotDojoChat] Control methods exposed");
|
|
290
366
|
}, [onBotDojoChatControl]);
|
|
367
|
+
useEffect(() => {
|
|
368
|
+
if (!iframeRef.current) {
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
const handleMessage = (event) => {
|
|
372
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
|
|
373
|
+
const handlers = eventHandlersRef.current;
|
|
374
|
+
if (((_a = event.data) == null ? void 0 : _a.jsonrpc) === "2.0" && event.data.method) {
|
|
375
|
+
const { method, params, id } = event.data;
|
|
376
|
+
const reply = (payload) => {
|
|
377
|
+
var _a2;
|
|
378
|
+
if (id === void 0)
|
|
379
|
+
return;
|
|
380
|
+
(_a2 = event.source) == null ? void 0 : _a2.postMessage({ jsonrpc: "2.0", id, ...payload }, event.origin || "*");
|
|
381
|
+
};
|
|
382
|
+
const sendNotification = (m, p) => {
|
|
383
|
+
var _a2;
|
|
384
|
+
(_a2 = event.source) == null ? void 0 : _a2.postMessage({ jsonrpc: "2.0", method: m, params: p }, event.origin || "*");
|
|
385
|
+
};
|
|
386
|
+
const withHandlers = (fn) => {
|
|
387
|
+
try {
|
|
388
|
+
return Promise.resolve(fn());
|
|
389
|
+
} catch (err) {
|
|
390
|
+
return Promise.reject(err);
|
|
391
|
+
}
|
|
392
|
+
};
|
|
393
|
+
const handle = async () => {
|
|
394
|
+
var _a2, _b2, _c2, _d2, _e2;
|
|
395
|
+
try {
|
|
396
|
+
switch (method) {
|
|
397
|
+
case "ui/initialize": {
|
|
398
|
+
const result = {
|
|
399
|
+
hostInfo: { name: "BotDojo Chat Host", version: "1.0.0" },
|
|
400
|
+
capabilities: { extensions: { "io.modelcontextprotocol/ui": { mimeTypes: ["text/html+mcp"] } } },
|
|
401
|
+
hostContext: {}
|
|
402
|
+
};
|
|
403
|
+
reply({ result });
|
|
404
|
+
sendNotification("ui/notifications/initialized", {});
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
case "ui/open-link": {
|
|
408
|
+
const url = params == null ? void 0 : params.url;
|
|
409
|
+
if (url && handlers.onOpenLink) {
|
|
410
|
+
withHandlers(() => handlers.onOpenLink(url, (params == null ? void 0 : params.target) || "_blank", (params == null ? void 0 : params.canvasId) || "unknown"));
|
|
411
|
+
}
|
|
412
|
+
reply({ result: { ok: true } });
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
case "ui/message": {
|
|
416
|
+
console.log("[MCP Persist Debug] Host received ui/message JSON-RPC", { params });
|
|
417
|
+
if (handlers.onUiMessage) {
|
|
418
|
+
const message = ((_b2 = (_a2 = params == null ? void 0 : params.content) == null ? void 0 : _a2[0]) == null ? void 0 : _b2.text) || JSON.stringify(params).slice(0, 120);
|
|
419
|
+
await withHandlers(
|
|
420
|
+
() => handlers.onUiMessage(message, params, (params == null ? void 0 : params.canvasId) || "unknown")
|
|
421
|
+
);
|
|
422
|
+
}
|
|
423
|
+
reply({ result: { ok: true } });
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
case "tools/call": {
|
|
427
|
+
const toolName = (params == null ? void 0 : params.tool) || (params == null ? void 0 : params.name);
|
|
428
|
+
if (toolName && handlers.onToolCall) {
|
|
429
|
+
const res = await withHandlers(
|
|
430
|
+
() => handlers.onToolCall(toolName, (params == null ? void 0 : params.params) || (params == null ? void 0 : params.arguments) || {}, (params == null ? void 0 : params.canvasId) || "unknown")
|
|
431
|
+
);
|
|
432
|
+
reply({ result: res != null ? res : { ok: true } });
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
reply({ result: { ok: false, ignored: true } });
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
case "resources/read": {
|
|
439
|
+
const uri = params == null ? void 0 : params.uri;
|
|
440
|
+
const resourceParams = (params == null ? void 0 : params.params) || ((params == null ? void 0 : params.mimeType) ? { mimeType: params.mimeType } : void 0);
|
|
441
|
+
const metadataOnly = (_d2 = (_c2 = params == null ? void 0 : params.metadataOnly) != null ? _c2 : params == null ? void 0 : params.onlyMetadata) != null ? _d2 : false;
|
|
442
|
+
const connector2 = connectorRef.current;
|
|
443
|
+
if (!uri) {
|
|
444
|
+
reply({ error: { code: -32602, message: "resources/read missing uri" } });
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
const rpcConnection = (_e2 = connector2 == null ? void 0 : connector2.getConnection) == null ? void 0 : _e2.call(connector2);
|
|
448
|
+
if (rpcConnection == null ? void 0 : rpcConnection.sendRequest) {
|
|
449
|
+
try {
|
|
450
|
+
const result = await rpcConnection.sendRequest(
|
|
451
|
+
"agent_host",
|
|
452
|
+
"getResource",
|
|
453
|
+
[uri, resourceParams, metadataOnly],
|
|
454
|
+
5e3
|
|
455
|
+
);
|
|
456
|
+
reply({ result });
|
|
457
|
+
} catch (err) {
|
|
458
|
+
reply({ error: { code: -32001, message: (err == null ? void 0 : err.message) || "resources/read failed" } });
|
|
459
|
+
}
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
reply({ error: { code: -32601, message: "resources/read not supported in host" } });
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
default:
|
|
466
|
+
reply({ result: { ok: true, ignored: true } });
|
|
467
|
+
}
|
|
468
|
+
} catch (err) {
|
|
469
|
+
reply({ error: { code: -32e3, message: (err == null ? void 0 : err.message) || "Host error" } });
|
|
470
|
+
}
|
|
471
|
+
};
|
|
472
|
+
void handle();
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
try {
|
|
476
|
+
const eventOrigin = new URL(event.origin).origin;
|
|
477
|
+
const expectedOrigin = new URL(getBaseUrl()).origin;
|
|
478
|
+
if (eventOrigin !== expectedOrigin) {
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
} catch (e) {
|
|
482
|
+
console.error("[BotDojoChat] Invalid origin:", event.origin);
|
|
483
|
+
return;
|
|
484
|
+
}
|
|
485
|
+
const data = event.data;
|
|
486
|
+
if (!data || !data.type || data.type === "botdojo-rpc") {
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
switch (data.type) {
|
|
490
|
+
case "ready":
|
|
491
|
+
if (handlers.onReady) {
|
|
492
|
+
try {
|
|
493
|
+
handlers.onReady();
|
|
494
|
+
} catch (error) {
|
|
495
|
+
console.error("[BotDojoChat] Error in onReady handler:", error);
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
break;
|
|
499
|
+
case "error":
|
|
500
|
+
if (handlers.onError) {
|
|
501
|
+
try {
|
|
502
|
+
const error = new Error(data.error || "Unknown error");
|
|
503
|
+
handlers.onError(error, data.messageId, data.stepId);
|
|
504
|
+
} catch (handlerError) {
|
|
505
|
+
console.error("[BotDojoChat] Error in onError handler:", handlerError);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
break;
|
|
509
|
+
case "message_start":
|
|
510
|
+
if (handlers.onMessageStart) {
|
|
511
|
+
try {
|
|
512
|
+
handlers.onMessageStart(data.role, data.messageId);
|
|
513
|
+
} catch (error) {
|
|
514
|
+
console.error("[BotDojoChat] Error in onMessageStart handler:", error);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
break;
|
|
518
|
+
case "message_complete":
|
|
519
|
+
if (handlers.onMessageComplete) {
|
|
520
|
+
try {
|
|
521
|
+
handlers.onMessageComplete(data.messageId, data.content);
|
|
522
|
+
} catch (error) {
|
|
523
|
+
console.error("[BotDojoChat] Error in onMessageComplete handler:", error);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
break;
|
|
527
|
+
case "step_update":
|
|
528
|
+
if (handlers.onStepUpdate) {
|
|
529
|
+
try {
|
|
530
|
+
handlers.onStepUpdate(data.messageId, data.step);
|
|
531
|
+
} catch (error) {
|
|
532
|
+
console.error("[BotDojoChat] Error in onStepUpdate handler:", error);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
break;
|
|
536
|
+
case "token":
|
|
537
|
+
if (handlers.onToken) {
|
|
538
|
+
try {
|
|
539
|
+
handlers.onToken(data.messageId, data.tokenUpdate);
|
|
540
|
+
} catch (error) {
|
|
541
|
+
console.error("[BotDojoChat] Error in onToken handler:", error);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
break;
|
|
545
|
+
case "session_created":
|
|
546
|
+
if (handlers.onSessionCreated) {
|
|
547
|
+
try {
|
|
548
|
+
handlers.onSessionCreated(data.sessionId);
|
|
549
|
+
} catch (error) {
|
|
550
|
+
console.error("[BotDojoChat] Error in onSessionCreated handler:", error);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
break;
|
|
554
|
+
case "session_hydrated":
|
|
555
|
+
if (handlers.onSessionHydrated) {
|
|
556
|
+
try {
|
|
557
|
+
handlers.onSessionHydrated(data.sessionId, data.messageCount);
|
|
558
|
+
} catch (error) {
|
|
559
|
+
console.error("[BotDojoChat] Error in onSessionHydrated handler:", error);
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
break;
|
|
563
|
+
case "request_aborted":
|
|
564
|
+
if (handlers.onRequestAborted) {
|
|
565
|
+
try {
|
|
566
|
+
handlers.onRequestAborted();
|
|
567
|
+
} catch (error) {
|
|
568
|
+
console.error("[BotDojoChat] Error in onRequestAborted handler:", error);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
break;
|
|
572
|
+
case "canvas_intent":
|
|
573
|
+
case "intent":
|
|
574
|
+
const intent = data.intent || ((_b = data.payload) == null ? void 0 : _b.intent);
|
|
575
|
+
const intentParams = data.params || ((_c = data.payload) == null ? void 0 : _c.params) || {};
|
|
576
|
+
const intentCanvasId = data.canvasId || ((_d = data.payload) == null ? void 0 : _d.canvasId);
|
|
577
|
+
if (intentCanvasId && intent && handlers.onToolCall) {
|
|
578
|
+
try {
|
|
579
|
+
handlers.onToolCall(intent, intentParams, intentCanvasId);
|
|
580
|
+
} catch (error) {
|
|
581
|
+
console.error("[BotDojoChat] Error in onToolCall handler:", error);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
break;
|
|
585
|
+
case "canvas_notify":
|
|
586
|
+
case "notify":
|
|
587
|
+
const notifyMessage = data.message || ((_e = data.payload) == null ? void 0 : _e.message);
|
|
588
|
+
const notifyParams = data.params || ((_f = data.payload) == null ? void 0 : _f.params) || {};
|
|
589
|
+
const notifyCanvasId = data.canvasId || ((_g = data.payload) == null ? void 0 : _g.canvasId);
|
|
590
|
+
if (notifyCanvasId && notifyMessage && handlers.onUiMessage) {
|
|
591
|
+
try {
|
|
592
|
+
handlers.onUiMessage(notifyMessage, notifyParams, notifyCanvasId);
|
|
593
|
+
} catch (error) {
|
|
594
|
+
console.error("[BotDojoChat] Error in onUiMessage handler:", error);
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
break;
|
|
598
|
+
case "canvas_prompt":
|
|
599
|
+
case "prompt":
|
|
600
|
+
const promptText = data.prompt || ((_h = data.payload) == null ? void 0 : _h.prompt);
|
|
601
|
+
const promptParams = data.params || ((_i = data.payload) == null ? void 0 : _i.params) || {};
|
|
602
|
+
const promptCanvasId = data.canvasId || ((_j = data.payload) == null ? void 0 : _j.canvasId);
|
|
603
|
+
if (promptCanvasId && promptText && handlers.onUiMessage) {
|
|
604
|
+
try {
|
|
605
|
+
handlers.onUiMessage(promptText, promptParams, promptCanvasId);
|
|
606
|
+
} catch (error) {
|
|
607
|
+
console.error("[BotDojoChat] Error in onUiMessage handler:", error);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
break;
|
|
611
|
+
case "canvas_link":
|
|
612
|
+
case "link":
|
|
613
|
+
const linkUrl = data.url || ((_k = data.payload) == null ? void 0 : _k.url);
|
|
614
|
+
const linkTarget = data.target || ((_l = data.payload) == null ? void 0 : _l.target) || "_blank";
|
|
615
|
+
const linkCanvasId = data.canvasId || ((_m = data.payload) == null ? void 0 : _m.canvasId);
|
|
616
|
+
if (linkUrl && handlers.onOpenLink) {
|
|
617
|
+
try {
|
|
618
|
+
handlers.onOpenLink(linkUrl, linkTarget, linkCanvasId || "unknown");
|
|
619
|
+
} catch (error) {
|
|
620
|
+
console.error("[BotDojoChat] Error in onOpenLink handler:", error);
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
break;
|
|
624
|
+
}
|
|
625
|
+
};
|
|
626
|
+
window.addEventListener("message", handleMessage);
|
|
627
|
+
return () => {
|
|
628
|
+
window.removeEventListener("message", handleMessage);
|
|
629
|
+
};
|
|
630
|
+
}, [getBaseUrl]);
|
|
291
631
|
useEffect(() => {
|
|
292
632
|
var _a;
|
|
293
633
|
if (!((_a = iframeRef.current) == null ? void 0 : _a.contentWindow) || !iframeLoaded) {
|
|
@@ -300,7 +640,7 @@ var BotDojoChat = ({
|
|
|
300
640
|
}
|
|
301
641
|
try {
|
|
302
642
|
console.log("[BotDojoChat] Creating PostMessageRPCClient + RPCConnection");
|
|
303
|
-
const firstContext =
|
|
643
|
+
const firstContext = modelContext2 ? Array.isArray(modelContext2) ? modelContext2[0] : modelContext2 : null;
|
|
304
644
|
const corsConfig = (firstContext == null ? void 0 : firstContext.cors) ? {
|
|
305
645
|
allowedToolCallOrigins: firstContext.cors.allowedToolCallOrigins
|
|
306
646
|
// botdojoChatDomain is configured server-side, not by SDK users
|
|
@@ -326,6 +666,7 @@ var BotDojoChat = ({
|
|
|
326
666
|
client,
|
|
327
667
|
new ConectionOptions(),
|
|
328
668
|
async (msg) => {
|
|
669
|
+
var _a2, _b, _c, _d, _e;
|
|
329
670
|
if (msg.origin === "server") {
|
|
330
671
|
console.log(`[BotDojoChat] Agent tool call (origin=server): ${msg.functionName}`);
|
|
331
672
|
}
|
|
@@ -335,9 +676,330 @@ var BotDojoChat = ({
|
|
|
335
676
|
chatReadyRef.current = true;
|
|
336
677
|
return;
|
|
337
678
|
}
|
|
679
|
+
const handlers = eventHandlersRef.current;
|
|
680
|
+
const eventData = (_a2 = msg.data) == null ? void 0 : _a2[0];
|
|
681
|
+
if (msg.functionName === "ready" && handlers.onReady) {
|
|
682
|
+
console.log("[BotDojoChat] Received ready event via RPC");
|
|
683
|
+
try {
|
|
684
|
+
handlers.onReady();
|
|
685
|
+
} catch (e) {
|
|
686
|
+
console.error("[BotDojoChat] Error in onReady:", e);
|
|
687
|
+
}
|
|
688
|
+
return;
|
|
689
|
+
}
|
|
690
|
+
if (msg.functionName === "error" && handlers.onError) {
|
|
691
|
+
console.log("[BotDojoChat] Received error event via RPC:", eventData);
|
|
692
|
+
try {
|
|
693
|
+
const error = new Error((eventData == null ? void 0 : eventData.error) || "Unknown error");
|
|
694
|
+
handlers.onError(error, eventData == null ? void 0 : eventData.messageId, eventData == null ? void 0 : eventData.stepId);
|
|
695
|
+
} catch (e) {
|
|
696
|
+
console.error("[BotDojoChat] Error in onError:", e);
|
|
697
|
+
}
|
|
698
|
+
return;
|
|
699
|
+
}
|
|
700
|
+
if (msg.functionName === "message_start" && handlers.onMessageStart) {
|
|
701
|
+
console.log("[BotDojoChat] Received message_start event via RPC:", eventData);
|
|
702
|
+
try {
|
|
703
|
+
handlers.onMessageStart(eventData == null ? void 0 : eventData.role, eventData == null ? void 0 : eventData.messageId);
|
|
704
|
+
} catch (e) {
|
|
705
|
+
console.error("[BotDojoChat] Error in onMessageStart:", e);
|
|
706
|
+
}
|
|
707
|
+
return;
|
|
708
|
+
}
|
|
709
|
+
if (msg.functionName === "message_complete" && handlers.onMessageComplete) {
|
|
710
|
+
console.log("[BotDojoChat] Received message_complete event via RPC:", eventData);
|
|
711
|
+
try {
|
|
712
|
+
handlers.onMessageComplete(eventData == null ? void 0 : eventData.messageId, eventData == null ? void 0 : eventData.content);
|
|
713
|
+
} catch (e) {
|
|
714
|
+
console.error("[BotDojoChat] Error in onMessageComplete:", e);
|
|
715
|
+
}
|
|
716
|
+
return;
|
|
717
|
+
}
|
|
718
|
+
if (msg.functionName === "step_update" && handlers.onStepUpdate) {
|
|
719
|
+
console.log("[BotDojoChat] Received step_update event via RPC:", eventData);
|
|
720
|
+
try {
|
|
721
|
+
handlers.onStepUpdate(eventData == null ? void 0 : eventData.messageId, eventData == null ? void 0 : eventData.step);
|
|
722
|
+
} catch (e) {
|
|
723
|
+
console.error("[BotDojoChat] Error in onStepUpdate:", e);
|
|
724
|
+
}
|
|
725
|
+
return;
|
|
726
|
+
}
|
|
727
|
+
if (msg.functionName === "token" && handlers.onToken) {
|
|
728
|
+
console.log("[BotDojoChat] Received token event via RPC:", eventData);
|
|
729
|
+
try {
|
|
730
|
+
handlers.onToken(eventData == null ? void 0 : eventData.messageId, eventData == null ? void 0 : eventData.tokenUpdate);
|
|
731
|
+
} catch (e) {
|
|
732
|
+
console.error("[BotDojoChat] Error in onToken:", e);
|
|
733
|
+
}
|
|
734
|
+
return;
|
|
735
|
+
}
|
|
736
|
+
if (msg.functionName === "session_created" && handlers.onSessionCreated) {
|
|
737
|
+
console.log("[BotDojoChat] Received session_created event via RPC:", eventData);
|
|
738
|
+
try {
|
|
739
|
+
handlers.onSessionCreated(eventData == null ? void 0 : eventData.sessionId);
|
|
740
|
+
} catch (e) {
|
|
741
|
+
console.error("[BotDojoChat] Error in onSessionCreated:", e);
|
|
742
|
+
}
|
|
743
|
+
return;
|
|
744
|
+
}
|
|
745
|
+
if (msg.functionName === "session_hydrated" && handlers.onSessionHydrated) {
|
|
746
|
+
console.log("[BotDojoChat] Received session_hydrated event via RPC:", eventData);
|
|
747
|
+
try {
|
|
748
|
+
handlers.onSessionHydrated(eventData == null ? void 0 : eventData.sessionId, eventData == null ? void 0 : eventData.messageCount);
|
|
749
|
+
} catch (e) {
|
|
750
|
+
console.error("[BotDojoChat] Error in onSessionHydrated:", e);
|
|
751
|
+
}
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
if (msg.functionName === "request_aborted" && handlers.onRequestAborted) {
|
|
755
|
+
console.log("[BotDojoChat] Received request_aborted event via RPC");
|
|
756
|
+
try {
|
|
757
|
+
handlers.onRequestAborted();
|
|
758
|
+
} catch (e) {
|
|
759
|
+
console.error("[BotDojoChat] Error in onRequestAborted:", e);
|
|
760
|
+
}
|
|
761
|
+
return;
|
|
762
|
+
}
|
|
763
|
+
if (msg.functionName === "canvas_event") {
|
|
764
|
+
const canvasEvent = eventData;
|
|
765
|
+
console.log("[BotDojoChat] Received canvas_event via RPC:", canvasEvent);
|
|
766
|
+
const looksLikeHtml = (value) => {
|
|
767
|
+
if (!value || typeof value !== "string")
|
|
768
|
+
return false;
|
|
769
|
+
const trimmed = value.trim();
|
|
770
|
+
if (!trimmed.startsWith("<"))
|
|
771
|
+
return false;
|
|
772
|
+
return /<\/?(html|head|body|div|span|script|style)/i.test(trimmed);
|
|
773
|
+
};
|
|
774
|
+
const extractHtmlFromResource = (resource) => {
|
|
775
|
+
if (!resource)
|
|
776
|
+
return void 0;
|
|
777
|
+
if (typeof resource.html === "string")
|
|
778
|
+
return resource.html;
|
|
779
|
+
if (typeof resource.text === "string" && looksLikeHtml(resource.text))
|
|
780
|
+
return resource.text;
|
|
781
|
+
if (typeof resource.data === "string" && looksLikeHtml(resource.data))
|
|
782
|
+
return resource.data;
|
|
783
|
+
const contents = (resource == null ? void 0 : resource.contents) || (resource == null ? void 0 : resource.content) || (resource == null ? void 0 : resource.data);
|
|
784
|
+
const list = Array.isArray(contents) ? contents : contents ? [contents] : [];
|
|
785
|
+
const match = list.find((item) => typeof (item == null ? void 0 : item.html) === "string" || looksLikeHtml(item == null ? void 0 : item.text) || typeof (item == null ? void 0 : item.data) === "string");
|
|
786
|
+
if (match) {
|
|
787
|
+
return match.html || (looksLikeHtml(match.text) ? match.text : typeof match.data === "string" ? match.data : void 0);
|
|
788
|
+
}
|
|
789
|
+
return void 0;
|
|
790
|
+
};
|
|
791
|
+
if ((canvasEvent == null ? void 0 : canvasEvent.type) === "sandbox-resource") {
|
|
792
|
+
const uri = canvasEvent.resource;
|
|
793
|
+
const mimeType = canvasEvent.mimeType;
|
|
794
|
+
const connection2 = (_c = (_b = connectorRef.current) == null ? void 0 : _b.getConnection) == null ? void 0 : _c.call(_b);
|
|
795
|
+
const matchesTemplate = (template, value) => {
|
|
796
|
+
if (!template || !value)
|
|
797
|
+
return false;
|
|
798
|
+
const escaped = template.replace(/[-/\\^$+?.()|[\]{}]/g, "\\$&");
|
|
799
|
+
const regex = new RegExp("^" + escaped.replace(/\\{[^}]+\\}/g, "[^/]+") + "$");
|
|
800
|
+
return regex.test(value);
|
|
801
|
+
};
|
|
802
|
+
const extractTemplateParams = (template, value) => {
|
|
803
|
+
const params = {};
|
|
804
|
+
const tmplParts = template.split("/");
|
|
805
|
+
const valParts = value.split("/");
|
|
806
|
+
tmplParts.forEach((part, idx) => {
|
|
807
|
+
if (part.startsWith("{") && part.endsWith("}")) {
|
|
808
|
+
params[part.slice(1, -1)] = valParts[idx];
|
|
809
|
+
}
|
|
810
|
+
});
|
|
811
|
+
return params;
|
|
812
|
+
};
|
|
813
|
+
const tryConnector = async () => {
|
|
814
|
+
if (!uri || !(connection2 == null ? void 0 : connection2.sendRequest))
|
|
815
|
+
return { error: "missing connection" };
|
|
816
|
+
let contexts = null;
|
|
817
|
+
try {
|
|
818
|
+
contexts = await connection2.sendRequest("agent_host", "getModelContexts", [], 4e3);
|
|
819
|
+
} catch (e) {
|
|
820
|
+
console.warn("[BotDojoChat] sandbox-resource could not list contexts", e);
|
|
821
|
+
}
|
|
822
|
+
const hasMatch = (ctx) => ((ctx == null ? void 0 : ctx.resources) || []).some(
|
|
823
|
+
(r) => (r == null ? void 0 : r.uri) === uri || (r == null ? void 0 : r.uriTemplate) && matchesTemplate(r.uriTemplate, uri)
|
|
824
|
+
);
|
|
825
|
+
const matchingCtx = contexts == null ? void 0 : contexts.find(hasMatch);
|
|
826
|
+
if (!matchingCtx && !contexts) {
|
|
827
|
+
console.warn("[BotDojoChat] sandbox-resource: no contexts available, trying direct getResource");
|
|
828
|
+
} else if (!matchingCtx) {
|
|
829
|
+
console.warn("[BotDojoChat] sandbox-resource: no matching context found for", uri);
|
|
830
|
+
}
|
|
831
|
+
try {
|
|
832
|
+
const result = await connection2.sendRequest(
|
|
833
|
+
"agent_host",
|
|
834
|
+
"getResource",
|
|
835
|
+
[uri, mimeType ? { mimeType } : void 0, false],
|
|
836
|
+
7e3
|
|
837
|
+
);
|
|
838
|
+
const html = extractHtmlFromResource(result);
|
|
839
|
+
if (!html) {
|
|
840
|
+
return { error: "no html from agent_host" };
|
|
841
|
+
}
|
|
842
|
+
const cspMeta = extractUiCspFromResource(result);
|
|
843
|
+
const resolvedCsp = resolveUiCsp(cspMeta);
|
|
844
|
+
return {
|
|
845
|
+
html,
|
|
846
|
+
csp: resolvedCsp.csp,
|
|
847
|
+
sandbox: canvasEvent.sandbox || resolvedCsp.sandbox
|
|
848
|
+
};
|
|
849
|
+
} catch (e) {
|
|
850
|
+
console.error("[BotDojoChat] sandbox-resource connector resolver error", e);
|
|
851
|
+
return { error: (e == null ? void 0 : e.message) || "connector error" };
|
|
852
|
+
}
|
|
853
|
+
};
|
|
854
|
+
const tryModelContext = async () => {
|
|
855
|
+
if (!uri || !modelContext2)
|
|
856
|
+
return { error: "no modelContext" };
|
|
857
|
+
const contexts = Array.isArray(modelContext2) ? modelContext2 : [modelContext2];
|
|
858
|
+
const match = contexts.flatMap((ctx) => ctx.resources || []).find((r) => {
|
|
859
|
+
const candidate = r;
|
|
860
|
+
const uriMatch = typeof (candidate == null ? void 0 : candidate.uri) === "string" && candidate.uri === uri;
|
|
861
|
+
const templateMatch = "uriTemplate" in candidate && candidate.uriTemplate && matchesTemplate(candidate.uriTemplate, uri);
|
|
862
|
+
return uriMatch || templateMatch;
|
|
863
|
+
});
|
|
864
|
+
if (!match)
|
|
865
|
+
return { error: "resource not found in modelContext" };
|
|
866
|
+
try {
|
|
867
|
+
const content = typeof match.getContent === "function" ? await match.getContent(
|
|
868
|
+
"uriTemplate" in match && match.uriTemplate ? extractTemplateParams(match.uriTemplate, uri) : void 0
|
|
869
|
+
) : match;
|
|
870
|
+
const html = extractHtmlFromResource(content);
|
|
871
|
+
if (!html) {
|
|
872
|
+
return { error: "no html in modelContext resource" };
|
|
873
|
+
}
|
|
874
|
+
const cspMeta = extractUiCspFromResource(content);
|
|
875
|
+
const resolvedCsp = resolveUiCsp(cspMeta);
|
|
876
|
+
return {
|
|
877
|
+
html,
|
|
878
|
+
csp: resolvedCsp.csp,
|
|
879
|
+
sandbox: canvasEvent.sandbox || resolvedCsp.sandbox
|
|
880
|
+
};
|
|
881
|
+
} catch (e) {
|
|
882
|
+
return { error: (e == null ? void 0 : e.message) || "modelContext getContent error" };
|
|
883
|
+
}
|
|
884
|
+
};
|
|
885
|
+
const connectorResult = await tryConnector();
|
|
886
|
+
if (connectorResult.html) {
|
|
887
|
+
return {
|
|
888
|
+
html: connectorResult.html,
|
|
889
|
+
sandbox: connectorResult.sandbox || canvasEvent.sandbox,
|
|
890
|
+
csp: connectorResult.csp
|
|
891
|
+
};
|
|
892
|
+
}
|
|
893
|
+
const mcResult = await tryModelContext();
|
|
894
|
+
if (mcResult.html) {
|
|
895
|
+
return {
|
|
896
|
+
html: mcResult.html,
|
|
897
|
+
sandbox: mcResult.sandbox || canvasEvent.sandbox,
|
|
898
|
+
csp: mcResult.csp
|
|
899
|
+
};
|
|
900
|
+
}
|
|
901
|
+
return { ok: false, error: connectorResult.error || mcResult.error || "sandbox-resource failed" };
|
|
902
|
+
}
|
|
903
|
+
const handlerPromises = [];
|
|
904
|
+
if ((canvasEvent == null ? void 0 : canvasEvent.type) === "link") {
|
|
905
|
+
if (handlers.onOpenLink) {
|
|
906
|
+
try {
|
|
907
|
+
const maybe = handlers.onOpenLink(canvasEvent.url, canvasEvent.target || "_blank", canvasEvent.canvasId || "unknown");
|
|
908
|
+
if (maybe && typeof maybe.then === "function")
|
|
909
|
+
handlerPromises.push(maybe);
|
|
910
|
+
} catch (e) {
|
|
911
|
+
console.error("[BotDojoChat] Error in onOpenLink:", e);
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
} else if ((canvasEvent == null ? void 0 : canvasEvent.type) === "intent") {
|
|
915
|
+
if (handlers.onToolCall) {
|
|
916
|
+
try {
|
|
917
|
+
const maybe = handlers.onToolCall(canvasEvent.intent, canvasEvent.params || {}, canvasEvent.canvasId || "unknown");
|
|
918
|
+
if (maybe && typeof maybe.then === "function")
|
|
919
|
+
handlerPromises.push(maybe);
|
|
920
|
+
} catch (e) {
|
|
921
|
+
console.error("[BotDojoChat] Error in onToolCall:", e);
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
} else if ((canvasEvent == null ? void 0 : canvasEvent.type) === "notify") {
|
|
925
|
+
if (handlers.onUiMessage) {
|
|
926
|
+
try {
|
|
927
|
+
const maybe = handlers.onUiMessage(canvasEvent.message, canvasEvent.params || {}, canvasEvent.canvasId || "unknown");
|
|
928
|
+
if (maybe && typeof maybe.then === "function")
|
|
929
|
+
handlerPromises.push(maybe);
|
|
930
|
+
} catch (e) {
|
|
931
|
+
console.error("[BotDojoChat] Error in onUiMessage:", e);
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
} else if ((canvasEvent == null ? void 0 : canvasEvent.type) === "prompt") {
|
|
935
|
+
if (handlers.onUiMessage) {
|
|
936
|
+
try {
|
|
937
|
+
const maybe = handlers.onUiMessage(canvasEvent.prompt, canvasEvent.params || {}, canvasEvent.canvasId || "unknown");
|
|
938
|
+
if (maybe && typeof maybe.then === "function")
|
|
939
|
+
handlerPromises.push(maybe);
|
|
940
|
+
} catch (e) {
|
|
941
|
+
console.error("[BotDojoChat] Error in onUiMessage:", e);
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
} else if ((canvasEvent == null ? void 0 : canvasEvent.type) === "update") {
|
|
945
|
+
if (handlers.onUiMessage) {
|
|
946
|
+
try {
|
|
947
|
+
const maybe = handlers.onUiMessage(canvasEvent.data, {}, canvasEvent.canvasId || "unknown");
|
|
948
|
+
if (maybe && typeof maybe.then === "function")
|
|
949
|
+
handlerPromises.push(maybe);
|
|
950
|
+
} catch (e) {
|
|
951
|
+
console.error("[BotDojoChat] Error in onUiMessage:", e);
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
} else if ((canvasEvent == null ? void 0 : canvasEvent.type) === "tool") {
|
|
955
|
+
if (handlers.onToolCall) {
|
|
956
|
+
try {
|
|
957
|
+
const maybe = handlers.onToolCall(canvasEvent.tool, canvasEvent.params || {}, canvasEvent.canvasId || "unknown");
|
|
958
|
+
if (maybe && typeof maybe.then === "function")
|
|
959
|
+
handlerPromises.push(maybe);
|
|
960
|
+
} catch (e) {
|
|
961
|
+
console.error("[BotDojoChat] Error in onToolCall:", e);
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
} else if ((canvasEvent == null ? void 0 : canvasEvent.type) === "action") {
|
|
965
|
+
const actionType = canvasEvent.actionType || canvasEvent.action || canvasEvent.type;
|
|
966
|
+
if (actionType === "ui/message") {
|
|
967
|
+
if (handlers.onUiMessage) {
|
|
968
|
+
try {
|
|
969
|
+
const message = ((_e = (_d = canvasEvent == null ? void 0 : canvasEvent.content) == null ? void 0 : _d[0]) == null ? void 0 : _e.text) || JSON.stringify(canvasEvent).slice(0, 120);
|
|
970
|
+
const maybe = handlers.onUiMessage(message, canvasEvent, canvasEvent.canvasId || "unknown");
|
|
971
|
+
if (maybe && typeof maybe.then === "function")
|
|
972
|
+
handlerPromises.push(maybe);
|
|
973
|
+
} catch (e) {
|
|
974
|
+
console.error("[BotDojoChat] Error in onUiMessage (ui/message):", e);
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
} else {
|
|
978
|
+
console.warn("[BotDojoChat] Ignoring unsupported canvas action type", actionType);
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
if (handlerPromises.length > 0) {
|
|
982
|
+
try {
|
|
983
|
+
const results = await Promise.allSettled(handlerPromises);
|
|
984
|
+
if ((canvasEvent == null ? void 0 : canvasEvent.type) === "tool") {
|
|
985
|
+
console.log("[BotDojoChat] canvas_event tool handler results", results);
|
|
986
|
+
const firstValue = results.find((r) => r.status === "fulfilled" && r.value !== void 0);
|
|
987
|
+
if (firstValue) {
|
|
988
|
+
console.log("[BotDojoChat] Returning tool handler value to canvas", firstValue.value);
|
|
989
|
+
return firstValue.value;
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
return { ok: true, results };
|
|
993
|
+
} catch (e) {
|
|
994
|
+
console.error("[BotDojoChat] Error awaiting canvas_event handlers:", e);
|
|
995
|
+
return { ok: false, error: String(e) };
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
return { ok: true };
|
|
999
|
+
}
|
|
338
1000
|
if (msg.functionName === "broadcastAgentHostConnected") {
|
|
339
1001
|
console.log("[BotDojoChat] Received broadcastAgentHostConnected, registering ModelContext(s) with chat iframe router");
|
|
340
|
-
const contexts = Array.isArray(
|
|
1002
|
+
const contexts = Array.isArray(modelContext2) ? modelContext2 : modelContext2 ? [modelContext2] : [];
|
|
341
1003
|
for (const ctx of contexts) {
|
|
342
1004
|
try {
|
|
343
1005
|
console.log(`[BotDojoChat] Registering ModelContext "${ctx.name}" with chat iframe router`);
|
|
@@ -354,12 +1016,12 @@ var BotDojoChat = ({
|
|
|
354
1016
|
}
|
|
355
1017
|
return;
|
|
356
1018
|
}
|
|
357
|
-
if (
|
|
358
|
-
const contexts = Array.isArray(
|
|
1019
|
+
if (modelContext2) {
|
|
1020
|
+
const contexts = Array.isArray(modelContext2) ? modelContext2 : [modelContext2];
|
|
359
1021
|
for (const ctx of contexts) {
|
|
360
1022
|
if (ctx.tools) {
|
|
361
1023
|
const toolsArray = Array.isArray(ctx.tools) ? ctx.tools : Object.values(ctx.tools);
|
|
362
|
-
const isModelContextTool = toolsArray.some((
|
|
1024
|
+
const isModelContextTool = toolsArray.some((tool2) => tool2.name === msg.functionName);
|
|
363
1025
|
if (isModelContextTool) {
|
|
364
1026
|
console.log(`[BotDojoChat] Message is for model context tool ${msg.functionName}, letting connector handle it`);
|
|
365
1027
|
return;
|
|
@@ -375,18 +1037,18 @@ var BotDojoChat = ({
|
|
|
375
1037
|
source: connection.sender,
|
|
376
1038
|
func: async () => {
|
|
377
1039
|
console.log("[BotDojoChat] Handling getModelContexts request");
|
|
378
|
-
const contexts = Array.isArray(
|
|
1040
|
+
const contexts = Array.isArray(modelContext2) ? modelContext2 : modelContext2 ? [modelContext2] : [];
|
|
379
1041
|
return contexts.map((ctx) => {
|
|
380
1042
|
let tools = [];
|
|
381
1043
|
if (ctx.tools) {
|
|
382
1044
|
if (Array.isArray(ctx.tools)) {
|
|
383
|
-
tools = ctx.tools.map((
|
|
384
|
-
const { execute, ...toolWithoutExecute } =
|
|
1045
|
+
tools = ctx.tools.map((tool2) => {
|
|
1046
|
+
const { execute, ...toolWithoutExecute } = tool2;
|
|
385
1047
|
return toolWithoutExecute;
|
|
386
1048
|
});
|
|
387
1049
|
} else {
|
|
388
|
-
tools = Object.entries(ctx.tools).map(([name,
|
|
389
|
-
const { execute, ...toolWithoutExecute } =
|
|
1050
|
+
tools = Object.entries(ctx.tools).map(([name, tool2]) => {
|
|
1051
|
+
const { execute, ...toolWithoutExecute } = tool2;
|
|
390
1052
|
return { name, ...toolWithoutExecute };
|
|
391
1053
|
});
|
|
392
1054
|
}
|
|
@@ -417,7 +1079,7 @@ var BotDojoChat = ({
|
|
|
417
1079
|
connectionRef.current = null;
|
|
418
1080
|
}
|
|
419
1081
|
};
|
|
420
|
-
}, [connector, iframeLoaded,
|
|
1082
|
+
}, [connector, iframeLoaded, modelContext2, apiKey]);
|
|
421
1083
|
const parseSize = useCallback((value, defaultVal) => {
|
|
422
1084
|
if (!value || value === "auto")
|
|
423
1085
|
return defaultVal;
|
|
@@ -776,7 +1438,7 @@ var BotDojoChat = ({
|
|
|
776
1438
|
"iframe",
|
|
777
1439
|
{
|
|
778
1440
|
ref: iframeRef,
|
|
779
|
-
src:
|
|
1441
|
+
src: iframeUrl,
|
|
780
1442
|
style: iframeStyles,
|
|
781
1443
|
allow: allowMicrophone ? "microphone" : void 0,
|
|
782
1444
|
onLoad: handleIframeLoad,
|
|
@@ -804,18 +1466,22 @@ var HeadlessChat = React2.forwardRef(
|
|
|
804
1466
|
(props, ref) => {
|
|
805
1467
|
const {
|
|
806
1468
|
apiKey,
|
|
807
|
-
modelContext,
|
|
1469
|
+
modelContext: modelContext2,
|
|
808
1470
|
baseUrl = "http://localhost:3000",
|
|
809
1471
|
config,
|
|
810
1472
|
onStatusChange,
|
|
811
1473
|
onToken,
|
|
812
1474
|
onStep,
|
|
813
|
-
|
|
1475
|
+
onMcpApp,
|
|
814
1476
|
onMessageStart,
|
|
815
1477
|
onMessageComplete,
|
|
816
1478
|
onMessage,
|
|
817
1479
|
onReady,
|
|
818
|
-
onError
|
|
1480
|
+
onError,
|
|
1481
|
+
// MCP App event callbacks
|
|
1482
|
+
onOpenLink,
|
|
1483
|
+
onToolCall,
|
|
1484
|
+
onUiMessage
|
|
819
1485
|
} = props;
|
|
820
1486
|
const iframeRef = useRef(null);
|
|
821
1487
|
const connectorRef = useRef(null);
|
|
@@ -872,7 +1538,7 @@ var HeadlessChat = React2.forwardRef(
|
|
|
872
1538
|
isReady: () => isReady
|
|
873
1539
|
}));
|
|
874
1540
|
useEffect(() => {
|
|
875
|
-
if (!
|
|
1541
|
+
if (!modelContext2)
|
|
876
1542
|
return;
|
|
877
1543
|
let mounted = true;
|
|
878
1544
|
(async () => {
|
|
@@ -880,7 +1546,7 @@ var HeadlessChat = React2.forwardRef(
|
|
|
880
1546
|
console.log("[HeadlessChat] Initializing BotDojoConnector with modelContext");
|
|
881
1547
|
const currentConnector = new BotDojoConnector({
|
|
882
1548
|
apiKey,
|
|
883
|
-
modelContext,
|
|
1549
|
+
modelContext: modelContext2,
|
|
884
1550
|
transport: "postmessage"
|
|
885
1551
|
});
|
|
886
1552
|
connectorRef.current = currentConnector;
|
|
@@ -907,9 +1573,10 @@ var HeadlessChat = React2.forwardRef(
|
|
|
907
1573
|
connectorRef.current = null;
|
|
908
1574
|
}
|
|
909
1575
|
};
|
|
910
|
-
}, [
|
|
1576
|
+
}, [modelContext2, apiKey]);
|
|
911
1577
|
useEffect(() => {
|
|
912
1578
|
const handleMessage = (event) => {
|
|
1579
|
+
var _a, _b;
|
|
913
1580
|
const data = event.data;
|
|
914
1581
|
switch (data.type) {
|
|
915
1582
|
case "ready":
|
|
@@ -947,7 +1614,7 @@ var HeadlessChat = React2.forwardRef(
|
|
|
947
1614
|
if (data.step) {
|
|
948
1615
|
onStep == null ? void 0 : onStep(data.step, data.messageId);
|
|
949
1616
|
if (data.step.canvas) {
|
|
950
|
-
|
|
1617
|
+
onMcpApp == null ? void 0 : onMcpApp(data.step.canvas, data.step.stepId, data.messageId);
|
|
951
1618
|
}
|
|
952
1619
|
}
|
|
953
1620
|
break;
|
|
@@ -978,11 +1645,30 @@ var HeadlessChat = React2.forwardRef(
|
|
|
978
1645
|
onStatusChange == null ? void 0 : onStatusChange("idle");
|
|
979
1646
|
currentMessageRef.current = null;
|
|
980
1647
|
break;
|
|
1648
|
+
case "mcp_open_link":
|
|
1649
|
+
case "ui/open-link":
|
|
1650
|
+
if (onOpenLink && data.url) {
|
|
1651
|
+
onOpenLink(data.url, data.target || "_blank", data.appId || "unknown");
|
|
1652
|
+
}
|
|
1653
|
+
break;
|
|
1654
|
+
case "mcp_tool_call":
|
|
1655
|
+
case "tools/call":
|
|
1656
|
+
if (onToolCall && data.tool) {
|
|
1657
|
+
onToolCall(data.tool, data.params || {}, data.appId || "unknown");
|
|
1658
|
+
}
|
|
1659
|
+
break;
|
|
1660
|
+
case "mcp_ui_message":
|
|
1661
|
+
case "ui/message":
|
|
1662
|
+
if (onUiMessage) {
|
|
1663
|
+
const message = data.message || ((_b = (_a = data.content) == null ? void 0 : _a[0]) == null ? void 0 : _b.text) || JSON.stringify(data).slice(0, 120);
|
|
1664
|
+
onUiMessage(message, data.params || data, data.appId || "unknown");
|
|
1665
|
+
}
|
|
1666
|
+
break;
|
|
981
1667
|
}
|
|
982
1668
|
};
|
|
983
1669
|
window.addEventListener("message", handleMessage);
|
|
984
1670
|
return () => window.removeEventListener("message", handleMessage);
|
|
985
|
-
}, [config, onStatusChange, onToken, onStep,
|
|
1671
|
+
}, [config, onStatusChange, onToken, onStep, onMcpApp, onMessageStart, onMessageComplete, onMessage, onReady, onError, onOpenLink, onToolCall, onUiMessage, sendToIframe]);
|
|
986
1672
|
return /* @__PURE__ */ jsx(
|
|
987
1673
|
"iframe",
|
|
988
1674
|
{
|
|
@@ -1018,10 +1704,10 @@ function findOrCreateStep(steps, stepId, parentStepId) {
|
|
|
1018
1704
|
if (parentStepId) {
|
|
1019
1705
|
const parent = steps.find((s) => s.stepId === parentStepId);
|
|
1020
1706
|
if (parent) {
|
|
1021
|
-
if (!parent.
|
|
1022
|
-
parent.
|
|
1707
|
+
if (!parent.subSteps) {
|
|
1708
|
+
parent.subSteps = [];
|
|
1023
1709
|
}
|
|
1024
|
-
step = parent.
|
|
1710
|
+
step = parent.subSteps.find((s) => s.stepId === stepId);
|
|
1025
1711
|
if (step)
|
|
1026
1712
|
return step;
|
|
1027
1713
|
const newStep2 = {
|
|
@@ -1032,7 +1718,7 @@ function findOrCreateStep(steps, stepId, parentStepId) {
|
|
|
1032
1718
|
startTime: /* @__PURE__ */ new Date(),
|
|
1033
1719
|
parentStepId
|
|
1034
1720
|
};
|
|
1035
|
-
parent.
|
|
1721
|
+
parent.subSteps.push(newStep2);
|
|
1036
1722
|
return newStep2;
|
|
1037
1723
|
}
|
|
1038
1724
|
}
|
|
@@ -1054,15 +1740,15 @@ function mergeStep(existing, update) {
|
|
|
1054
1740
|
// Preserve fields that shouldn't be overwritten by partial updates
|
|
1055
1741
|
stepId: existing.stepId,
|
|
1056
1742
|
startTime: existing.startTime,
|
|
1057
|
-
|
|
1743
|
+
subSteps: update.subSteps || existing.subSteps
|
|
1058
1744
|
};
|
|
1059
1745
|
}
|
|
1060
1746
|
function convertCoreMessage(msg) {
|
|
1061
1747
|
return {
|
|
1062
|
-
id: msg.id
|
|
1748
|
+
id: msg.id || `msg-${Date.now()}`,
|
|
1063
1749
|
role: msg.role,
|
|
1064
1750
|
content: msg.content || "",
|
|
1065
|
-
timestamp: new Date(msg.
|
|
1751
|
+
timestamp: msg.date ? new Date(msg.date) : /* @__PURE__ */ new Date(),
|
|
1066
1752
|
status: "complete",
|
|
1067
1753
|
steps: msg.steps || []
|
|
1068
1754
|
// CoreChatMessage may have steps
|
|
@@ -1189,11 +1875,59 @@ function chatReducer(state, action) {
|
|
|
1189
1875
|
return state;
|
|
1190
1876
|
}
|
|
1191
1877
|
}
|
|
1878
|
+
|
|
1879
|
+
// ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/rng.js
|
|
1880
|
+
var getRandomValues;
|
|
1881
|
+
var rnds8 = new Uint8Array(16);
|
|
1882
|
+
function rng() {
|
|
1883
|
+
if (!getRandomValues) {
|
|
1884
|
+
getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
|
|
1885
|
+
if (!getRandomValues) {
|
|
1886
|
+
throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
|
|
1887
|
+
}
|
|
1888
|
+
}
|
|
1889
|
+
return getRandomValues(rnds8);
|
|
1890
|
+
}
|
|
1891
|
+
|
|
1892
|
+
// ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/stringify.js
|
|
1893
|
+
var byteToHex = [];
|
|
1894
|
+
for (let i = 0; i < 256; ++i) {
|
|
1895
|
+
byteToHex.push((i + 256).toString(16).slice(1));
|
|
1896
|
+
}
|
|
1897
|
+
function unsafeStringify(arr, offset = 0) {
|
|
1898
|
+
return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];
|
|
1899
|
+
}
|
|
1900
|
+
|
|
1901
|
+
// ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/native.js
|
|
1902
|
+
var randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
|
|
1903
|
+
var native_default = {
|
|
1904
|
+
randomUUID
|
|
1905
|
+
};
|
|
1906
|
+
|
|
1907
|
+
// ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/v4.js
|
|
1908
|
+
function v4(options, buf, offset) {
|
|
1909
|
+
if (native_default.randomUUID && !buf && !options) {
|
|
1910
|
+
return native_default.randomUUID();
|
|
1911
|
+
}
|
|
1912
|
+
options = options || {};
|
|
1913
|
+
const rnds = options.random || (options.rng || rng)();
|
|
1914
|
+
rnds[6] = rnds[6] & 15 | 64;
|
|
1915
|
+
rnds[8] = rnds[8] & 63 | 128;
|
|
1916
|
+
if (buf) {
|
|
1917
|
+
offset = offset || 0;
|
|
1918
|
+
for (let i = 0; i < 16; ++i) {
|
|
1919
|
+
buf[offset + i] = rnds[i];
|
|
1920
|
+
}
|
|
1921
|
+
return buf;
|
|
1922
|
+
}
|
|
1923
|
+
return unsafeStringify(rnds);
|
|
1924
|
+
}
|
|
1925
|
+
var v4_default = v4;
|
|
1192
1926
|
var BotDojoChatContext = createContext(null);
|
|
1193
1927
|
function BotDojoChatProvider(props) {
|
|
1194
1928
|
const {
|
|
1195
1929
|
apiKey,
|
|
1196
|
-
modelContext,
|
|
1930
|
+
modelContext: modelContext2,
|
|
1197
1931
|
baseUrl = typeof window !== "undefined" ? window.location.hostname === "localhost" ? "http://localhost:3000" : "https://embed.botdojo.com" : "https://embed.botdojo.com",
|
|
1198
1932
|
sessionId,
|
|
1199
1933
|
newSession = false,
|
|
@@ -1214,14 +1948,22 @@ function BotDojoChatProvider(props) {
|
|
|
1214
1948
|
const [state, dispatch] = useReducer(chatReducer, initialState);
|
|
1215
1949
|
const iframeRef = useRef(null);
|
|
1216
1950
|
const [isIframeReady, setIsIframeReady] = useState(false);
|
|
1951
|
+
const [isSocketConnected, setIsSocketConnected] = useState(false);
|
|
1952
|
+
const externalUIChannelIdRef = useRef(v4_default());
|
|
1217
1953
|
const connectorRef = useRef(null);
|
|
1218
1954
|
const connectionRef = useRef(null);
|
|
1219
1955
|
const [connector, setConnector] = useState(null);
|
|
1220
1956
|
const [isConnectorReady, setIsConnectorReady] = useState(false);
|
|
1957
|
+
const [isModelContextRegistered, setIsModelContextRegistered] = useState(false);
|
|
1221
1958
|
const canvasBridgesRef = useRef(/* @__PURE__ */ new Map());
|
|
1222
1959
|
const canvasIframeRefsRef = useRef(/* @__PURE__ */ new Map());
|
|
1223
1960
|
const pendingCanvasEventsRef = useRef(/* @__PURE__ */ new Map());
|
|
1224
1961
|
const [registeredCanvases, setRegisteredCanvases] = useState(/* @__PURE__ */ new Set());
|
|
1962
|
+
const toolNotificationSendersRef = useRef(/* @__PURE__ */ new Map());
|
|
1963
|
+
const stepUpdateCallbacksRef = useRef(/* @__PURE__ */ new Map());
|
|
1964
|
+
const activeCanvasByToolRef = useRef(/* @__PURE__ */ new Map());
|
|
1965
|
+
const pendingToolNotificationsRef = useRef(/* @__PURE__ */ new Map());
|
|
1966
|
+
const pendingBroadcastNotificationsRef = useRef([]);
|
|
1225
1967
|
const canvasHandlersRef = useRef({
|
|
1226
1968
|
onCanvasIntent,
|
|
1227
1969
|
onCanvasNotify,
|
|
@@ -1229,9 +1971,14 @@ function BotDojoChatProvider(props) {
|
|
|
1229
1971
|
onCanvasLink,
|
|
1230
1972
|
onCanvasAction
|
|
1231
1973
|
});
|
|
1974
|
+
const modelContextRef = useRef(modelContext2);
|
|
1975
|
+
useEffect(() => {
|
|
1976
|
+
modelContextRef.current = modelContext2;
|
|
1977
|
+
}, [modelContext2]);
|
|
1232
1978
|
const iframeUrl = useMemo(() => {
|
|
1233
1979
|
const url = new URL("/embed/headless", baseUrl);
|
|
1234
1980
|
url.searchParams.set("apiKey", apiKey);
|
|
1981
|
+
url.searchParams.set("externalUIChannelId", externalUIChannelIdRef.current);
|
|
1235
1982
|
if (sessionId)
|
|
1236
1983
|
url.searchParams.set("session-id", sessionId);
|
|
1237
1984
|
if (newSession)
|
|
@@ -1248,53 +1995,210 @@ function BotDojoChatProvider(props) {
|
|
|
1248
1995
|
};
|
|
1249
1996
|
}, [onCanvasIntent, onCanvasNotify, onCanvasPrompt, onCanvasLink, onCanvasAction]);
|
|
1250
1997
|
useEffect(() => {
|
|
1251
|
-
if (
|
|
1998
|
+
if (isSocketConnected && modelContext2) {
|
|
1999
|
+
setIsConnectorReady(true);
|
|
2000
|
+
}
|
|
2001
|
+
}, [isSocketConnected, modelContext2]);
|
|
2002
|
+
const handleIframeLoad = useCallback(() => {
|
|
2003
|
+
console.log("[BotDojoChatProvider] Headless iframe loaded");
|
|
2004
|
+
setIsIframeReady(true);
|
|
2005
|
+
}, []);
|
|
2006
|
+
const serializeModelContext = useCallback((ctx) => {
|
|
2007
|
+
const backendFormat = translateModelContextToBackend(ctx);
|
|
2008
|
+
const tools = (backendFormat.tools || []).map((tool2) => {
|
|
2009
|
+
const { execute, ...toolWithoutExecute } = tool2;
|
|
2010
|
+
return toolWithoutExecute;
|
|
2011
|
+
});
|
|
2012
|
+
return {
|
|
2013
|
+
...backendFormat,
|
|
2014
|
+
tools,
|
|
2015
|
+
uri: backendFormat.resourceUri
|
|
2016
|
+
};
|
|
2017
|
+
}, []);
|
|
2018
|
+
const sendModelContextToHeadless = useCallback(() => {
|
|
2019
|
+
var _a;
|
|
2020
|
+
if (!((_a = iframeRef.current) == null ? void 0 : _a.contentWindow) || !modelContextRef.current) {
|
|
1252
2021
|
return;
|
|
1253
2022
|
}
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
2023
|
+
const contexts = Array.isArray(modelContextRef.current) ? modelContextRef.current : [modelContextRef.current];
|
|
2024
|
+
const ctx = contexts[0];
|
|
2025
|
+
if (ctx) {
|
|
2026
|
+
console.log("[BotDojoChatProvider] Sending model context to HeadlessEmbed:", ctx.name);
|
|
2027
|
+
iframeRef.current.contentWindow.postMessage({
|
|
2028
|
+
type: "set_model_context",
|
|
2029
|
+
modelContext: serializeModelContext(ctx)
|
|
2030
|
+
}, baseUrl);
|
|
2031
|
+
}
|
|
2032
|
+
}, [baseUrl, serializeModelContext]);
|
|
2033
|
+
const sendToolNotificationToCanvas = useCallback((canvasId, method, params) => {
|
|
2034
|
+
console.log(`[BotDojoChatProvider] Sending tool notification to canvas ${canvasId}: ${method}`, params);
|
|
2035
|
+
const sender = toolNotificationSendersRef.current.get(canvasId);
|
|
2036
|
+
if (sender) {
|
|
1257
2037
|
try {
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
transport: "postmessage",
|
|
1262
|
-
targetWindow: ((_a = iframeRef.current) == null ? void 0 : _a.contentWindow) || void 0
|
|
1263
|
-
});
|
|
1264
|
-
connectorRef.current = newConnector;
|
|
1265
|
-
setConnector(newConnector);
|
|
1266
|
-
if ((_b = iframeRef.current) == null ? void 0 : _b.contentWindow) {
|
|
1267
|
-
await newConnector.updatePostMessageTarget(iframeRef.current.contentWindow);
|
|
1268
|
-
}
|
|
1269
|
-
setIsConnectorReady(true);
|
|
1270
|
-
onConnectorInit == null ? void 0 : onConnectorInit(newConnector);
|
|
1271
|
-
console.log("[BotDojoChatProvider] BotDojoConnector initialized");
|
|
1272
|
-
} catch (error) {
|
|
1273
|
-
console.error("[BotDojoChatProvider] Failed to initialize connector:", error);
|
|
1274
|
-
onConnectorError == null ? void 0 : onConnectorError(error);
|
|
2038
|
+
sender(method, params);
|
|
2039
|
+
} catch (err) {
|
|
2040
|
+
console.warn(`[BotDojoChatProvider] Failed to send notification to ${canvasId}:`, err);
|
|
1275
2041
|
}
|
|
1276
|
-
}
|
|
1277
|
-
|
|
1278
|
-
if (
|
|
1279
|
-
|
|
1280
|
-
setConnector(null);
|
|
1281
|
-
setIsConnectorReady(false);
|
|
2042
|
+
} else {
|
|
2043
|
+
console.log(`[BotDojoChatProvider] Canvas ${canvasId} not registered yet, queueing notification: ${method}`);
|
|
2044
|
+
if (!pendingToolNotificationsRef.current.has(canvasId)) {
|
|
2045
|
+
pendingToolNotificationsRef.current.set(canvasId, []);
|
|
1282
2046
|
}
|
|
2047
|
+
pendingToolNotificationsRef.current.get(canvasId).push({ method, params });
|
|
2048
|
+
}
|
|
2049
|
+
}, []);
|
|
2050
|
+
const broadcastToolNotification = useCallback((method, params, toolName) => {
|
|
2051
|
+
var _a;
|
|
2052
|
+
console.log(`[BotDojoChatProvider] Broadcasting tool notification: ${method}`, params);
|
|
2053
|
+
if (toolNotificationSendersRef.current.size === 0) {
|
|
2054
|
+
console.log(`[BotDojoChatProvider] No canvases registered, queueing broadcast notification: ${method}`);
|
|
2055
|
+
pendingBroadcastNotificationsRef.current.push({ method, params, toolName: toolName || ((_a = params == null ? void 0 : params.tool) == null ? void 0 : _a.name) || "" });
|
|
2056
|
+
} else {
|
|
2057
|
+
toolNotificationSendersRef.current.forEach((sender, mcpAppId) => {
|
|
2058
|
+
try {
|
|
2059
|
+
sender(method, params);
|
|
2060
|
+
} catch (err) {
|
|
2061
|
+
console.warn(`[BotDojoChatProvider] Failed to send notification to ${mcpAppId}:`, err);
|
|
2062
|
+
}
|
|
2063
|
+
});
|
|
2064
|
+
}
|
|
2065
|
+
}, []);
|
|
2066
|
+
const registerToolNotificationSender = useCallback((mcpAppId, sender) => {
|
|
2067
|
+
console.log(`[BotDojoChatProvider] Registering tool notification sender for: ${mcpAppId}`);
|
|
2068
|
+
toolNotificationSendersRef.current.set(mcpAppId, sender);
|
|
2069
|
+
const pendingForCanvas = pendingToolNotificationsRef.current.get(mcpAppId);
|
|
2070
|
+
if (pendingForCanvas && pendingForCanvas.length > 0) {
|
|
2071
|
+
console.log(`[BotDojoChatProvider] Replaying ${pendingForCanvas.length} queued notifications for canvas: ${mcpAppId}`);
|
|
2072
|
+
pendingForCanvas.forEach(({ method, params }) => {
|
|
2073
|
+
try {
|
|
2074
|
+
console.log(`[BotDojoChatProvider] Replaying: ${method}`, params);
|
|
2075
|
+
sender(method, params);
|
|
2076
|
+
} catch (err) {
|
|
2077
|
+
console.warn(`[BotDojoChatProvider] Failed to replay notification to ${mcpAppId}:`, err);
|
|
2078
|
+
}
|
|
2079
|
+
});
|
|
2080
|
+
pendingToolNotificationsRef.current.delete(mcpAppId);
|
|
2081
|
+
}
|
|
2082
|
+
const pendingBroadcasts = pendingBroadcastNotificationsRef.current;
|
|
2083
|
+
if (pendingBroadcasts.length > 0) {
|
|
2084
|
+
console.log(`[BotDojoChatProvider] Replaying ${pendingBroadcasts.length} queued broadcast notifications to: ${mcpAppId}`);
|
|
2085
|
+
pendingBroadcasts.forEach(({ method, params }) => {
|
|
2086
|
+
try {
|
|
2087
|
+
console.log(`[BotDojoChatProvider] Replaying broadcast: ${method}`, params);
|
|
2088
|
+
sender(method, params);
|
|
2089
|
+
} catch (err) {
|
|
2090
|
+
console.warn(`[BotDojoChatProvider] Failed to replay broadcast notification to ${mcpAppId}:`, err);
|
|
2091
|
+
}
|
|
2092
|
+
});
|
|
2093
|
+
pendingBroadcastNotificationsRef.current = [];
|
|
2094
|
+
}
|
|
2095
|
+
return () => {
|
|
2096
|
+
console.log(`[BotDojoChatProvider] Unregistering tool notification sender for: ${mcpAppId}`);
|
|
2097
|
+
toolNotificationSendersRef.current.delete(mcpAppId);
|
|
1283
2098
|
};
|
|
1284
|
-
}, [modelContext, apiKey, baseUrl, onConnectorInit, onConnectorError]);
|
|
1285
|
-
const handleIframeLoad = useCallback(() => {
|
|
1286
|
-
console.log("[BotDojoChatProvider] Iframe loaded");
|
|
1287
|
-
setIsIframeReady(true);
|
|
1288
2099
|
}, []);
|
|
1289
|
-
const
|
|
1290
|
-
console.log(
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
2100
|
+
const registerStepUpdateCallback = useCallback((canvasId, callback) => {
|
|
2101
|
+
console.log(`[BotDojoChatProvider] Registering step update callback for canvas: ${canvasId}`);
|
|
2102
|
+
stepUpdateCallbacksRef.current.set(canvasId, callback);
|
|
2103
|
+
return () => {
|
|
2104
|
+
console.log(`[BotDojoChatProvider] Unregistering step update callback for canvas: ${canvasId}`);
|
|
2105
|
+
stepUpdateCallbacksRef.current.delete(canvasId);
|
|
2106
|
+
};
|
|
2107
|
+
}, []);
|
|
2108
|
+
const sendStepUpdateToCanvas = useCallback((canvasId, stepUpdate) => {
|
|
2109
|
+
const callback = stepUpdateCallbacksRef.current.get(canvasId);
|
|
2110
|
+
if (callback) {
|
|
2111
|
+
console.log(`[BotDojoChatProvider] Sending step update to canvas: ${canvasId}`, stepUpdate);
|
|
2112
|
+
callback(stepUpdate);
|
|
2113
|
+
} else {
|
|
2114
|
+
console.warn(`[BotDojoChatProvider] No step update callback registered for canvas: ${canvasId}`);
|
|
1294
2115
|
}
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
2116
|
+
}, []);
|
|
2117
|
+
const executeToolCall = useCallback(async (toolName, args, targetCanvasId) => {
|
|
2118
|
+
const ctx = modelContextRef.current;
|
|
2119
|
+
if (!ctx) {
|
|
2120
|
+
throw new Error("No model context available");
|
|
2121
|
+
}
|
|
2122
|
+
const contexts = Array.isArray(ctx) ? ctx : [ctx];
|
|
2123
|
+
for (const context of contexts) {
|
|
2124
|
+
if (context.tools) {
|
|
2125
|
+
const toolsArray = Array.isArray(context.tools) ? context.tools : Object.values(context.tools);
|
|
2126
|
+
const tool2 = toolsArray.find((t) => t.name === toolName);
|
|
2127
|
+
if (tool2 && typeof tool2.execute === "function") {
|
|
2128
|
+
let resolvedCanvasId = targetCanvasId;
|
|
2129
|
+
if (!resolvedCanvasId) {
|
|
2130
|
+
resolvedCanvasId = activeCanvasByToolRef.current.get(toolName);
|
|
2131
|
+
if (!resolvedCanvasId && context.name) {
|
|
2132
|
+
const prefixedToolName = `${context.name}_${toolName}`;
|
|
2133
|
+
resolvedCanvasId = activeCanvasByToolRef.current.get(prefixedToolName);
|
|
2134
|
+
}
|
|
2135
|
+
}
|
|
2136
|
+
console.log(`[BotDojoChatProvider] Executing tool "${toolName}" for canvas: ${resolvedCanvasId || "ALL (broadcast)"}`);
|
|
2137
|
+
const executionContext = {
|
|
2138
|
+
toolName,
|
|
2139
|
+
notifyToolInputPartial: async (data) => {
|
|
2140
|
+
console.log(`[BotDojoChatProvider] Tool "${toolName}" notifyToolInputPartial:`, data);
|
|
2141
|
+
const notification = {
|
|
2142
|
+
tool: { name: toolName },
|
|
2143
|
+
arguments: data
|
|
2144
|
+
};
|
|
2145
|
+
if (resolvedCanvasId) {
|
|
2146
|
+
sendToolNotificationToCanvas(resolvedCanvasId, "ui/notifications/tool-input-partial", notification);
|
|
2147
|
+
} else {
|
|
2148
|
+
broadcastToolNotification("ui/notifications/tool-input-partial", notification, toolName);
|
|
2149
|
+
}
|
|
2150
|
+
},
|
|
2151
|
+
notifyToolResult: async (data) => {
|
|
2152
|
+
var _a;
|
|
2153
|
+
console.log(`[BotDojoChatProvider] Tool "${toolName}" notifyToolResult:`, data);
|
|
2154
|
+
const notification = {
|
|
2155
|
+
tool: { name: toolName },
|
|
2156
|
+
result: (_a = data == null ? void 0 : data.result) != null ? _a : data
|
|
2157
|
+
};
|
|
2158
|
+
if (resolvedCanvasId) {
|
|
2159
|
+
sendToolNotificationToCanvas(resolvedCanvasId, "ui/notifications/tool-result", notification);
|
|
2160
|
+
} else {
|
|
2161
|
+
broadcastToolNotification("ui/notifications/tool-result", notification, toolName);
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
2164
|
+
};
|
|
2165
|
+
return await tool2.execute(args, executionContext);
|
|
2166
|
+
}
|
|
2167
|
+
}
|
|
2168
|
+
}
|
|
2169
|
+
throw new Error(`Tool not found: ${toolName}`);
|
|
2170
|
+
}, [broadcastToolNotification, sendToolNotificationToCanvas]);
|
|
2171
|
+
const getResource = useCallback(async (uri, params, onlyMetadata) => {
|
|
2172
|
+
const ctx = modelContextRef.current;
|
|
2173
|
+
if (!ctx) {
|
|
2174
|
+
throw new Error("No model context available");
|
|
2175
|
+
}
|
|
2176
|
+
const contexts = Array.isArray(ctx) ? ctx : [ctx];
|
|
2177
|
+
for (const context of contexts) {
|
|
2178
|
+
if (context.resources) {
|
|
2179
|
+
for (const resource of context.resources) {
|
|
2180
|
+
if ("uri" in resource && resource.uri === uri && resource.getContent) {
|
|
2181
|
+
const content = await resource.getContent();
|
|
2182
|
+
return {
|
|
2183
|
+
uri,
|
|
2184
|
+
mimeType: resource.mimeType,
|
|
2185
|
+
...typeof content === "string" ? { text: content } : content
|
|
2186
|
+
};
|
|
2187
|
+
}
|
|
2188
|
+
}
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
throw new Error(`Resource not found: ${uri}`);
|
|
2192
|
+
}, []);
|
|
2193
|
+
const registerCanvasIframe = useCallback((canvasId, iframeWindow) => {
|
|
2194
|
+
console.log("[BotDojoChatProvider] Registering canvas iframe:", canvasId);
|
|
2195
|
+
if (canvasBridgesRef.current.has(canvasId)) {
|
|
2196
|
+
console.log("[BotDojoChatProvider] Canvas already registered:", canvasId);
|
|
2197
|
+
return;
|
|
2198
|
+
}
|
|
2199
|
+
canvasIframeRefsRef.current.set(canvasId, iframeWindow);
|
|
2200
|
+
const bridge = new PostMessageBridge({
|
|
2201
|
+
targetWindow: iframeWindow,
|
|
1298
2202
|
targetOrigin: baseUrl,
|
|
1299
2203
|
clientId: `parent-to-canvas-${canvasId}`,
|
|
1300
2204
|
debug: true,
|
|
@@ -1377,56 +2281,6 @@ function BotDojoChatProvider(props) {
|
|
|
1377
2281
|
pendingCanvasEventsRef.current.get(canvasId).push({ eventName, data });
|
|
1378
2282
|
}
|
|
1379
2283
|
}, []);
|
|
1380
|
-
useEffect(() => {
|
|
1381
|
-
var _a;
|
|
1382
|
-
if (!((_a = iframeRef.current) == null ? void 0 : _a.contentWindow) || !isIframeReady || !isConnectorReady) {
|
|
1383
|
-
return;
|
|
1384
|
-
}
|
|
1385
|
-
console.log("[BotDojoChatProvider] Initializing RPCConnection to chat iframe");
|
|
1386
|
-
try {
|
|
1387
|
-
const funcInfo = {
|
|
1388
|
-
getToken: async () => "",
|
|
1389
|
-
clientId: "parent",
|
|
1390
|
-
defaultDestinationId: "agent_host",
|
|
1391
|
-
baseChannel: "headless"
|
|
1392
|
-
};
|
|
1393
|
-
const client = new PostMessageRPCClient(
|
|
1394
|
-
iframeRef.current.contentWindow,
|
|
1395
|
-
funcInfo,
|
|
1396
|
-
baseUrl,
|
|
1397
|
-
true,
|
|
1398
|
-
// debug
|
|
1399
|
-
"parent",
|
|
1400
|
-
// role
|
|
1401
|
-
{}
|
|
1402
|
-
// CORS config
|
|
1403
|
-
);
|
|
1404
|
-
const connection = new RPCConnection(
|
|
1405
|
-
client,
|
|
1406
|
-
new ConectionOptions(),
|
|
1407
|
-
async (msg) => {
|
|
1408
|
-
console.log("[BotDojoChatProvider] RPC message:", msg.functionName);
|
|
1409
|
-
console.log("[BotDojoChatProvider] Unhandled message (may be handled by connector):", msg.functionName);
|
|
1410
|
-
return new RPCMessageError("Unknown function: " + msg.functionName);
|
|
1411
|
-
}
|
|
1412
|
-
);
|
|
1413
|
-
connectionRef.current = connection;
|
|
1414
|
-
connection.init().then(() => {
|
|
1415
|
-
console.log("[BotDojoChatProvider] RPCConnection initialized");
|
|
1416
|
-
}).catch((error) => {
|
|
1417
|
-
console.error("[BotDojoChatProvider] RPCConnection init failed:", error);
|
|
1418
|
-
});
|
|
1419
|
-
} catch (error) {
|
|
1420
|
-
console.error("[BotDojoChatProvider] Failed to initialize RPCConnection:", error);
|
|
1421
|
-
}
|
|
1422
|
-
return () => {
|
|
1423
|
-
console.log("[BotDojoChatProvider] Cleaning up RPCConnection");
|
|
1424
|
-
if (connectionRef.current) {
|
|
1425
|
-
connectionRef.current.close();
|
|
1426
|
-
connectionRef.current = null;
|
|
1427
|
-
}
|
|
1428
|
-
};
|
|
1429
|
-
}, [isIframeReady, isConnectorReady, connector, modelContext, apiKey, baseUrl]);
|
|
1430
2284
|
const handleMessage = useCallback((event) => {
|
|
1431
2285
|
var _a, _b, _c;
|
|
1432
2286
|
try {
|
|
@@ -1447,6 +2301,75 @@ function BotDojoChatProvider(props) {
|
|
|
1447
2301
|
}
|
|
1448
2302
|
console.log("[BotDojoChatProvider] Received event:", data.type, data);
|
|
1449
2303
|
switch (data.type) {
|
|
2304
|
+
case "socket_connected":
|
|
2305
|
+
console.log("[BotDojoChatProvider] HeadlessEmbed Socket.IO connected");
|
|
2306
|
+
setIsSocketConnected(true);
|
|
2307
|
+
sendModelContextToHeadless();
|
|
2308
|
+
break;
|
|
2309
|
+
case "request_model_context":
|
|
2310
|
+
console.log("[BotDojoChatProvider] HeadlessEmbed requesting model context");
|
|
2311
|
+
sendModelContextToHeadless();
|
|
2312
|
+
break;
|
|
2313
|
+
case "get_model_contexts":
|
|
2314
|
+
console.log("[BotDojoChatProvider] HeadlessEmbed requesting all model contexts");
|
|
2315
|
+
sendModelContextToHeadless();
|
|
2316
|
+
break;
|
|
2317
|
+
case "tool_call":
|
|
2318
|
+
console.log("[BotDojoChatProvider] Tool call from HeadlessEmbed:", data.toolName, "canvasId:", data.canvasId || "none");
|
|
2319
|
+
(async () => {
|
|
2320
|
+
var _a2, _b2, _c2, _d;
|
|
2321
|
+
try {
|
|
2322
|
+
const result = await executeToolCall(data.toolName, data.arguments, data.canvasId);
|
|
2323
|
+
console.log(`[BotDojoChatProvider] \u2705 Tool "${data.toolName}" executed successfully`);
|
|
2324
|
+
(_b2 = (_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow) == null ? void 0 : _b2.postMessage({
|
|
2325
|
+
type: "tool_response",
|
|
2326
|
+
requestId: data.requestId,
|
|
2327
|
+
result
|
|
2328
|
+
}, baseUrl);
|
|
2329
|
+
} catch (error2) {
|
|
2330
|
+
console.error(`[BotDojoChatProvider] \u274C Tool "${data.toolName}" failed:`, error2);
|
|
2331
|
+
(_d = (_c2 = iframeRef.current) == null ? void 0 : _c2.contentWindow) == null ? void 0 : _d.postMessage({
|
|
2332
|
+
type: "tool_response",
|
|
2333
|
+
requestId: data.requestId,
|
|
2334
|
+
error: error2.message
|
|
2335
|
+
}, baseUrl);
|
|
2336
|
+
}
|
|
2337
|
+
})();
|
|
2338
|
+
break;
|
|
2339
|
+
case "get_resource":
|
|
2340
|
+
console.log("[BotDojoChatProvider] Resource request from HeadlessEmbed:", data.uri);
|
|
2341
|
+
(async () => {
|
|
2342
|
+
var _a2, _b2, _c2, _d;
|
|
2343
|
+
try {
|
|
2344
|
+
const resource = await getResource(data.uri, data.params, data.onlyMetadata);
|
|
2345
|
+
(_b2 = (_a2 = iframeRef.current) == null ? void 0 : _a2.contentWindow) == null ? void 0 : _b2.postMessage({
|
|
2346
|
+
type: "get_resource_response",
|
|
2347
|
+
requestId: data.requestId,
|
|
2348
|
+
resource
|
|
2349
|
+
}, baseUrl);
|
|
2350
|
+
} catch (error2) {
|
|
2351
|
+
console.error(`[BotDojoChatProvider] \u274C Resource fetch failed:`, error2);
|
|
2352
|
+
(_d = (_c2 = iframeRef.current) == null ? void 0 : _c2.contentWindow) == null ? void 0 : _d.postMessage({
|
|
2353
|
+
type: "get_resource_response",
|
|
2354
|
+
requestId: data.requestId,
|
|
2355
|
+
error: error2.message
|
|
2356
|
+
}, baseUrl);
|
|
2357
|
+
}
|
|
2358
|
+
})();
|
|
2359
|
+
break;
|
|
2360
|
+
case "model_context_registered":
|
|
2361
|
+
console.log("[BotDojoChatProvider] \u2705 Model context registered:", data.name);
|
|
2362
|
+
setIsModelContextRegistered(true);
|
|
2363
|
+
onConnectorInit == null ? void 0 : onConnectorInit(null);
|
|
2364
|
+
break;
|
|
2365
|
+
case "model_context_registration_error":
|
|
2366
|
+
console.error("[BotDojoChatProvider] \u274C Model context registration failed:", data.error);
|
|
2367
|
+
onConnectorError == null ? void 0 : onConnectorError(new Error(data.error));
|
|
2368
|
+
break;
|
|
2369
|
+
case "socket_error":
|
|
2370
|
+
console.error("[BotDojoChatProvider] HeadlessEmbed Socket.IO error:", data.error);
|
|
2371
|
+
onConnectorError == null ? void 0 : onConnectorError(new Error(data.error));
|
|
2372
|
+
break;
|
|
1450
2373
|
case "ready":
|
|
1451
2374
|
dispatch({ type: "READY" });
|
|
1452
2375
|
onReady == null ? void 0 : onReady();
|
|
@@ -1482,18 +2405,73 @@ function BotDojoChatProvider(props) {
|
|
|
1482
2405
|
});
|
|
1483
2406
|
break;
|
|
1484
2407
|
case "step_update":
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
"onIntermediateStepUpdate",
|
|
1494
|
-
data.step
|
|
1495
|
-
);
|
|
2408
|
+
if ((_b = data.step) == null ? void 0 : _b.canvas) {
|
|
2409
|
+
console.log("[BotDojoChatProvider] Step has canvas:", data.step.canvas.canvasId, data.step.canvas.canvasType, JSON.stringify(data.step.canvas.canvasData, null, 2));
|
|
2410
|
+
const toolName = (_c = data.step.canvas.canvasData) == null ? void 0 : _c.toolName;
|
|
2411
|
+
const canvasId = data.step.canvas.canvasId;
|
|
2412
|
+
if (toolName && canvasId) {
|
|
2413
|
+
console.log(`[BotDojoChatProvider] Registering canvas ${canvasId} for tool: ${toolName}`);
|
|
2414
|
+
activeCanvasByToolRef.current.set(toolName, canvasId);
|
|
2415
|
+
}
|
|
1496
2416
|
}
|
|
2417
|
+
(async () => {
|
|
2418
|
+
var _a2, _b2, _c2, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
|
|
2419
|
+
let stepToDispatch = data.step;
|
|
2420
|
+
const canvasUrl = (_c2 = (_b2 = (_a2 = data.step) == null ? void 0 : _a2.canvas) == null ? void 0 : _b2.canvasData) == null ? void 0 : _c2.url;
|
|
2421
|
+
if (canvasUrl && canvasUrl.startsWith("ui://") && !((_f = (_e = (_d = data.step) == null ? void 0 : _d.canvas) == null ? void 0 : _e.canvasData) == null ? void 0 : _f.html)) {
|
|
2422
|
+
console.log("[BotDojoChatProvider] Resolving ui:// resource:", canvasUrl);
|
|
2423
|
+
try {
|
|
2424
|
+
const resource = await getResource(canvasUrl);
|
|
2425
|
+
console.log("[BotDojoChatProvider] Resource result:", resource ? "got content" : "no content");
|
|
2426
|
+
const htmlContent = (resource == null ? void 0 : resource.text) || (resource == null ? void 0 : resource.content);
|
|
2427
|
+
if (htmlContent) {
|
|
2428
|
+
stepToDispatch = {
|
|
2429
|
+
...data.step,
|
|
2430
|
+
canvas: {
|
|
2431
|
+
...data.step.canvas,
|
|
2432
|
+
canvasData: {
|
|
2433
|
+
...data.step.canvas.canvasData,
|
|
2434
|
+
html: htmlContent
|
|
2435
|
+
}
|
|
2436
|
+
}
|
|
2437
|
+
};
|
|
2438
|
+
console.log("[BotDojoChatProvider] \u2705 Resolved ui:// resource to HTML (" + htmlContent.length + " chars)");
|
|
2439
|
+
} else {
|
|
2440
|
+
console.warn("[BotDojoChatProvider] \u26A0\uFE0F Resource resolved but no text/content found:", Object.keys(resource || {}));
|
|
2441
|
+
}
|
|
2442
|
+
} catch (err) {
|
|
2443
|
+
console.error("[BotDojoChatProvider] \u274C Failed to resolve ui:// resource:", err.message);
|
|
2444
|
+
}
|
|
2445
|
+
}
|
|
2446
|
+
dispatch({
|
|
2447
|
+
type: "STEP_UPDATE",
|
|
2448
|
+
messageId: data.messageId,
|
|
2449
|
+
step: stepToDispatch
|
|
2450
|
+
});
|
|
2451
|
+
if ((_g = stepToDispatch == null ? void 0 : stepToDispatch.canvas) == null ? void 0 : _g.canvasId) {
|
|
2452
|
+
const canvasId = stepToDispatch.canvas.canvasId;
|
|
2453
|
+
const callback = stepUpdateCallbacksRef.current.get(canvasId);
|
|
2454
|
+
if (callback) {
|
|
2455
|
+
const stepResult = (_j = stepToDispatch.content) != null ? _j : (_i = (_h = stepToDispatch.canvas) == null ? void 0 : _h.canvasData) == null ? void 0 : _i.result;
|
|
2456
|
+
console.log(`[BotDojoChatProvider] Sending step update via callback to canvas: ${canvasId}`, {
|
|
2457
|
+
hasStepContent: stepToDispatch.content !== void 0,
|
|
2458
|
+
hasCanvasResult: ((_l = (_k = stepToDispatch.canvas) == null ? void 0 : _k.canvasData) == null ? void 0 : _l.result) !== void 0
|
|
2459
|
+
});
|
|
2460
|
+
callback({
|
|
2461
|
+
...stepToDispatch,
|
|
2462
|
+
toolName: (_n = (_m = stepToDispatch.canvas) == null ? void 0 : _m.canvasData) == null ? void 0 : _n.toolName,
|
|
2463
|
+
arguments: (_p = (_o = stepToDispatch.canvas) == null ? void 0 : _o.canvasData) == null ? void 0 : _p.arguments,
|
|
2464
|
+
result: stepResult
|
|
2465
|
+
});
|
|
2466
|
+
} else {
|
|
2467
|
+
forwardEventToCanvas(
|
|
2468
|
+
canvasId,
|
|
2469
|
+
"onIntermediateStepUpdate",
|
|
2470
|
+
stepToDispatch
|
|
2471
|
+
);
|
|
2472
|
+
}
|
|
2473
|
+
}
|
|
2474
|
+
})();
|
|
1497
2475
|
break;
|
|
1498
2476
|
case "token":
|
|
1499
2477
|
dispatch({
|
|
@@ -1505,10 +2483,8 @@ function BotDojoChatProvider(props) {
|
|
|
1505
2483
|
case "request_aborted":
|
|
1506
2484
|
dispatch({ type: "REQUEST_ABORTED" });
|
|
1507
2485
|
break;
|
|
1508
|
-
default:
|
|
1509
|
-
console.warn("[BotDojoChatProvider] Unknown event type:", data.type);
|
|
1510
2486
|
}
|
|
1511
|
-
}, [baseUrl, onReady, onError, forwardEventToCanvas]);
|
|
2487
|
+
}, [baseUrl, onReady, onError, onConnectorInit, onConnectorError, onSessionCreated, onSessionHydrated, forwardEventToCanvas, sendModelContextToHeadless, executeToolCall, getResource]);
|
|
1512
2488
|
useEffect(() => {
|
|
1513
2489
|
if (typeof window === "undefined")
|
|
1514
2490
|
return;
|
|
@@ -1525,9 +2501,13 @@ function BotDojoChatProvider(props) {
|
|
|
1525
2501
|
registerCanvasIframe,
|
|
1526
2502
|
unregisterCanvasIframe,
|
|
1527
2503
|
registeredCanvases,
|
|
2504
|
+
registerToolNotificationSender,
|
|
2505
|
+
sendToolNotificationToCanvas,
|
|
2506
|
+
registerStepUpdateCallback,
|
|
2507
|
+
sendStepUpdateToCanvas,
|
|
1528
2508
|
canvasHandlers: canvasHandlersRef
|
|
1529
2509
|
}),
|
|
1530
|
-
[state, connector, registerCanvasIframe, unregisterCanvasIframe, registeredCanvases]
|
|
2510
|
+
[state, connector, registerCanvasIframe, unregisterCanvasIframe, registeredCanvases, registerToolNotificationSender, sendToolNotificationToCanvas, registerStepUpdateCallback, sendStepUpdateToCanvas]
|
|
1531
2511
|
);
|
|
1532
2512
|
return /* @__PURE__ */ jsxs(BotDojoChatContext.Provider, { value: contextValue, children: [
|
|
1533
2513
|
children,
|
|
@@ -1602,12 +2582,25 @@ function useChatActions() {
|
|
|
1602
2582
|
}
|
|
1603
2583
|
iframeRef.current.src = iframeRef.current.src;
|
|
1604
2584
|
}, [iframeRef]);
|
|
2585
|
+
const persistCanvasState = useCallback((canvasId, state) => {
|
|
2586
|
+
var _a;
|
|
2587
|
+
if (!((_a = iframeRef.current) == null ? void 0 : _a.contentWindow)) {
|
|
2588
|
+
console.error("[useChatActions] Iframe not ready");
|
|
2589
|
+
return;
|
|
2590
|
+
}
|
|
2591
|
+
console.log("[useChatActions] Persisting canvas state:", canvasId, state);
|
|
2592
|
+
iframeRef.current.contentWindow.postMessage(
|
|
2593
|
+
{ type: "persist_canvas_state", canvasId, state },
|
|
2594
|
+
"*"
|
|
2595
|
+
);
|
|
2596
|
+
}, [iframeRef]);
|
|
1605
2597
|
return {
|
|
1606
2598
|
sendMessage,
|
|
1607
2599
|
abortRequest,
|
|
1608
2600
|
bargeInRequest,
|
|
1609
2601
|
setSessionId,
|
|
1610
|
-
reload
|
|
2602
|
+
reload,
|
|
2603
|
+
persistCanvasState
|
|
1611
2604
|
};
|
|
1612
2605
|
}
|
|
1613
2606
|
|
|
@@ -1618,14 +2611,14 @@ function useBotDojoChat() {
|
|
|
1618
2611
|
throw new Error("useBotDojoChat must be used within BotDojoChatProvider");
|
|
1619
2612
|
}
|
|
1620
2613
|
const { state } = context;
|
|
1621
|
-
const
|
|
2614
|
+
const actions = useChatActions();
|
|
1622
2615
|
return {
|
|
1623
2616
|
state: {
|
|
1624
2617
|
status: state.status,
|
|
1625
2618
|
isReady: state.isReady,
|
|
1626
2619
|
error: state.error
|
|
1627
2620
|
},
|
|
1628
|
-
actions
|
|
2621
|
+
actions
|
|
1629
2622
|
};
|
|
1630
2623
|
}
|
|
1631
2624
|
function useChatMessages() {
|
|
@@ -1660,203 +2653,705 @@ function useChatStatus() {
|
|
|
1660
2653
|
function BotDojoCanvasFrame(props) {
|
|
1661
2654
|
const { canvasId, canvasData, canvasType: explicitCanvasType, width = "100%", height = "400px", style = {} } = props;
|
|
1662
2655
|
const iframeRef = useRef(null);
|
|
1663
|
-
|
|
1664
|
-
const
|
|
1665
|
-
const context = useContext(BotDojoChatContext);
|
|
1666
|
-
const canvasType = explicitCanvasType || (canvasData == null ? void 0 : canvasData.canvasType) || (canvasData == null ? void 0 : canvasData.type) || "dojo-canvas";
|
|
1667
|
-
const isMcpUi = canvasType.startsWith("mcp-ui-");
|
|
1668
|
-
const actualCanvasData = (canvasData == null ? void 0 : canvasData.canvasData) || canvasData;
|
|
1669
|
-
console.log("[BotDojoCanvasFrame] Rendering canvas:", {
|
|
1670
|
-
canvasId,
|
|
1671
|
-
canvasType,
|
|
1672
|
-
isMcpUi,
|
|
1673
|
-
hasUrl: !!(actualCanvasData == null ? void 0 : actualCanvasData.url),
|
|
1674
|
-
hasHtml: !!(actualCanvasData == null ? void 0 : actualCanvasData.html),
|
|
1675
|
-
hasRemoteDom: !!(actualCanvasData == null ? void 0 : actualCanvasData.remoteDomScript)
|
|
1676
|
-
});
|
|
2656
|
+
explicitCanvasType || (canvasData == null ? void 0 : canvasData.canvasType) || (canvasData == null ? void 0 : canvasData.type) || "dojo-canvas";
|
|
2657
|
+
const actualData = (canvasData == null ? void 0 : canvasData.canvasData) || canvasData;
|
|
1677
2658
|
useEffect(() => {
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
2659
|
+
if ((actualData == null ? void 0 : actualData.html) && iframeRef.current) {
|
|
2660
|
+
const blob = new Blob([actualData.html], { type: "text/html" });
|
|
2661
|
+
const url = URL.createObjectURL(blob);
|
|
2662
|
+
iframeRef.current.src = url;
|
|
2663
|
+
return () => URL.revokeObjectURL(url);
|
|
1681
2664
|
}
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
2665
|
+
if ((actualData == null ? void 0 : actualData.url) && iframeRef.current) {
|
|
2666
|
+
iframeRef.current.src = actualData.url;
|
|
2667
|
+
}
|
|
2668
|
+
}, [actualData]);
|
|
2669
|
+
return /* @__PURE__ */ jsx(
|
|
2670
|
+
"iframe",
|
|
2671
|
+
{
|
|
2672
|
+
ref: iframeRef,
|
|
2673
|
+
title: canvasId,
|
|
2674
|
+
style: { width, height, border: "none", ...style },
|
|
2675
|
+
sandbox: "allow-forms allow-scripts allow-same-origin allow-popups"
|
|
2676
|
+
}
|
|
2677
|
+
);
|
|
2678
|
+
}
|
|
2679
|
+
var McpAppHostContext = createContext(null);
|
|
2680
|
+
function McpAppHostProvider(props) {
|
|
2681
|
+
const { children, onOpenLink, onToolCall, onUiMessage, onPersistState, debug = false } = props;
|
|
2682
|
+
const registeredAppsRef = useRef(/* @__PURE__ */ new Map());
|
|
2683
|
+
const [registeredAppIds, setRegisteredAppIds] = useState(/* @__PURE__ */ new Set());
|
|
2684
|
+
const nextRequestId = useRef(0);
|
|
2685
|
+
const log = useCallback((...args) => {
|
|
2686
|
+
if (debug) {
|
|
2687
|
+
console.log("[McpAppHostContext]", ...args);
|
|
2688
|
+
}
|
|
2689
|
+
}, [debug]);
|
|
2690
|
+
const registerApp = useCallback((mcpAppId, iframeWindow) => {
|
|
2691
|
+
log("Registering app:", mcpAppId);
|
|
2692
|
+
if (registeredAppsRef.current.has(mcpAppId)) {
|
|
2693
|
+
log("App already registered, updating window reference:", mcpAppId);
|
|
2694
|
+
}
|
|
2695
|
+
registeredAppsRef.current.set(mcpAppId, {
|
|
2696
|
+
mcpAppId,
|
|
2697
|
+
iframeWindow,
|
|
2698
|
+
pendingRequests: /* @__PURE__ */ new Map()
|
|
2699
|
+
});
|
|
2700
|
+
setRegisteredAppIds((prev) => new Set(prev).add(mcpAppId));
|
|
2701
|
+
}, [log]);
|
|
2702
|
+
const unregisterApp = useCallback((mcpAppId) => {
|
|
2703
|
+
log("Unregistering app:", mcpAppId);
|
|
2704
|
+
const app = registeredAppsRef.current.get(mcpAppId);
|
|
2705
|
+
if (app) {
|
|
2706
|
+
app.pendingRequests.forEach(({ reject }) => {
|
|
2707
|
+
reject(new Error("App unregistered"));
|
|
2708
|
+
});
|
|
2709
|
+
}
|
|
2710
|
+
registeredAppsRef.current.delete(mcpAppId);
|
|
2711
|
+
setRegisteredAppIds((prev) => {
|
|
2712
|
+
const next = new Set(prev);
|
|
2713
|
+
next.delete(mcpAppId);
|
|
2714
|
+
return next;
|
|
2715
|
+
});
|
|
2716
|
+
}, [log]);
|
|
2717
|
+
const findAppIdBySource = useCallback((source) => {
|
|
2718
|
+
if (!source)
|
|
2719
|
+
return null;
|
|
2720
|
+
for (const [mcpAppId, app] of registeredAppsRef.current.entries()) {
|
|
2721
|
+
if (app.iframeWindow === source) {
|
|
2722
|
+
return mcpAppId;
|
|
1688
2723
|
}
|
|
2724
|
+
}
|
|
2725
|
+
return null;
|
|
2726
|
+
}, []);
|
|
2727
|
+
const sendToApp = useCallback(async (mcpAppId, method, params) => {
|
|
2728
|
+
const app = registeredAppsRef.current.get(mcpAppId);
|
|
2729
|
+
if (!app) {
|
|
2730
|
+
throw new Error(`App not registered: ${mcpAppId}`);
|
|
2731
|
+
}
|
|
2732
|
+
const id = `host-${++nextRequestId.current}`;
|
|
2733
|
+
const request = {
|
|
2734
|
+
jsonrpc: "2.0",
|
|
2735
|
+
id,
|
|
2736
|
+
method,
|
|
2737
|
+
params
|
|
1689
2738
|
};
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
2739
|
+
log("Sending to app:", mcpAppId, method, params);
|
|
2740
|
+
return new Promise((resolve, reject) => {
|
|
2741
|
+
const timer = setTimeout(() => {
|
|
2742
|
+
app.pendingRequests.delete(id);
|
|
2743
|
+
reject(new Error(`Request timeout: ${method}`));
|
|
2744
|
+
}, 1e4);
|
|
2745
|
+
app.pendingRequests.set(id, {
|
|
2746
|
+
resolve: (value) => {
|
|
2747
|
+
clearTimeout(timer);
|
|
2748
|
+
resolve(value);
|
|
2749
|
+
},
|
|
2750
|
+
reject: (reason) => {
|
|
2751
|
+
clearTimeout(timer);
|
|
2752
|
+
reject(reason);
|
|
2753
|
+
}
|
|
2754
|
+
});
|
|
2755
|
+
app.iframeWindow.postMessage(request, "*");
|
|
2756
|
+
});
|
|
2757
|
+
}, [log]);
|
|
2758
|
+
const broadcastToApps = useCallback((method, params) => {
|
|
2759
|
+
const notification = {
|
|
2760
|
+
jsonrpc: "2.0",
|
|
2761
|
+
method,
|
|
2762
|
+
params
|
|
2763
|
+
};
|
|
2764
|
+
log("Broadcasting to all apps:", method, params);
|
|
2765
|
+
registeredAppsRef.current.forEach((app) => {
|
|
2766
|
+
try {
|
|
2767
|
+
app.iframeWindow.postMessage(notification, "*");
|
|
2768
|
+
} catch (err) {
|
|
2769
|
+
log("Failed to broadcast to app:", app.mcpAppId, err);
|
|
2770
|
+
}
|
|
2771
|
+
});
|
|
2772
|
+
}, [log]);
|
|
2773
|
+
const contextValue = useMemo(() => ({
|
|
2774
|
+
registerApp,
|
|
2775
|
+
unregisterApp,
|
|
2776
|
+
registeredApps: registeredAppIds,
|
|
2777
|
+
findAppIdBySource,
|
|
2778
|
+
sendToApp,
|
|
2779
|
+
broadcastToApps,
|
|
2780
|
+
onOpenLink,
|
|
2781
|
+
onToolCall,
|
|
2782
|
+
onUiMessage,
|
|
2783
|
+
onPersistState
|
|
2784
|
+
}), [
|
|
2785
|
+
registerApp,
|
|
2786
|
+
unregisterApp,
|
|
2787
|
+
registeredAppIds,
|
|
2788
|
+
findAppIdBySource,
|
|
2789
|
+
sendToApp,
|
|
2790
|
+
broadcastToApps,
|
|
2791
|
+
onOpenLink,
|
|
2792
|
+
onToolCall,
|
|
2793
|
+
onUiMessage,
|
|
2794
|
+
onPersistState
|
|
2795
|
+
]);
|
|
2796
|
+
return /* @__PURE__ */ jsx(McpAppHostContext.Provider, { value: contextValue, children });
|
|
2797
|
+
}
|
|
2798
|
+
|
|
2799
|
+
// src/headless/hooks/useMcpAppHost.ts
|
|
2800
|
+
function useMcpAppHost() {
|
|
2801
|
+
return useContext(McpAppHostContext);
|
|
2802
|
+
}
|
|
2803
|
+
function useMcpAppHostRequired() {
|
|
2804
|
+
const context = useContext(McpAppHostContext);
|
|
2805
|
+
if (!context) {
|
|
2806
|
+
throw new Error("useMcpAppHostRequired must be used within McpAppHostProvider");
|
|
2807
|
+
}
|
|
2808
|
+
return context;
|
|
2809
|
+
}
|
|
2810
|
+
function McpAppHost(props) {
|
|
2811
|
+
const {
|
|
2812
|
+
mcpAppId,
|
|
2813
|
+
mcpAppData,
|
|
2814
|
+
onOpenLink,
|
|
2815
|
+
onToolCall,
|
|
2816
|
+
onUiMessage,
|
|
2817
|
+
onPersistState,
|
|
2818
|
+
onSizeChange,
|
|
2819
|
+
onReady,
|
|
2820
|
+
width = "100%",
|
|
2821
|
+
height = "100%",
|
|
2822
|
+
style,
|
|
2823
|
+
initialHostContext,
|
|
2824
|
+
debug = false
|
|
2825
|
+
} = props;
|
|
2826
|
+
const iframeRef = useRef(null);
|
|
2827
|
+
const [isInitialized, setIsInitialized] = useState(false);
|
|
2828
|
+
const [iframeLoaded, setIframeLoaded] = useState(false);
|
|
2829
|
+
const [autoHeight, setAutoHeight] = useState(null);
|
|
2830
|
+
const pendingRequestsRef = useRef(/* @__PURE__ */ new Map());
|
|
2831
|
+
const nextRequestIdRef = useRef(0);
|
|
2832
|
+
const initializeAttemptsRef = useRef(0);
|
|
2833
|
+
const initializeTimerRef = useRef(null);
|
|
2834
|
+
const mcpAppHostContext = useMcpAppHost();
|
|
2835
|
+
const chatContext = useContext(BotDojoChatContext);
|
|
2836
|
+
const pendingNotificationsRef = useRef([]);
|
|
2837
|
+
const isInitializedRef = useRef(false);
|
|
2838
|
+
const appUrl = mcpAppData == null ? void 0 : mcpAppData.url;
|
|
2839
|
+
const appHtml = mcpAppData == null ? void 0 : mcpAppData.html;
|
|
2840
|
+
const log = useCallback((...args) => {
|
|
2841
|
+
if (debug) {
|
|
2842
|
+
console.log(`[McpAppHost:${mcpAppId}]`, ...args);
|
|
2843
|
+
}
|
|
2844
|
+
}, [debug, mcpAppId]);
|
|
2845
|
+
const sendResponse = useCallback((id, result) => {
|
|
2846
|
+
var _a;
|
|
2847
|
+
if (!((_a = iframeRef.current) == null ? void 0 : _a.contentWindow))
|
|
2848
|
+
return;
|
|
2849
|
+
iframeRef.current.contentWindow.postMessage(
|
|
2850
|
+
{ jsonrpc: "2.0", id, result },
|
|
2851
|
+
"*"
|
|
2852
|
+
);
|
|
2853
|
+
}, []);
|
|
2854
|
+
const sendError = useCallback((id, code, message) => {
|
|
2855
|
+
var _a;
|
|
2856
|
+
if (!((_a = iframeRef.current) == null ? void 0 : _a.contentWindow))
|
|
2857
|
+
return;
|
|
2858
|
+
iframeRef.current.contentWindow.postMessage(
|
|
2859
|
+
{ jsonrpc: "2.0", id, error: { code, message } },
|
|
2860
|
+
"*"
|
|
2861
|
+
);
|
|
2862
|
+
}, []);
|
|
2863
|
+
const sendNotification = useCallback((method, params) => {
|
|
2864
|
+
var _a;
|
|
2865
|
+
if (!((_a = iframeRef.current) == null ? void 0 : _a.contentWindow))
|
|
2866
|
+
return;
|
|
2867
|
+
log("Sending notification:", method, params);
|
|
2868
|
+
iframeRef.current.contentWindow.postMessage(
|
|
2869
|
+
{ jsonrpc: "2.0", method, params },
|
|
2870
|
+
"*"
|
|
2871
|
+
);
|
|
2872
|
+
}, [log]);
|
|
2873
|
+
const sendRequest = useCallback((method, params, timeout = 5e3) => {
|
|
2874
|
+
return new Promise((resolve, reject) => {
|
|
2875
|
+
var _a;
|
|
2876
|
+
if (!((_a = iframeRef.current) == null ? void 0 : _a.contentWindow)) {
|
|
2877
|
+
reject(new Error("Iframe not ready"));
|
|
1695
2878
|
return;
|
|
1696
2879
|
}
|
|
1697
|
-
const
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
2880
|
+
const id = `host-${++nextRequestIdRef.current}`;
|
|
2881
|
+
const timer = setTimeout(() => {
|
|
2882
|
+
pendingRequestsRef.current.delete(id);
|
|
2883
|
+
reject(new Error(`Request timeout: ${method}`));
|
|
2884
|
+
}, timeout);
|
|
2885
|
+
pendingRequestsRef.current.set(id, { resolve, reject, timer });
|
|
2886
|
+
log("Sending request:", method, params);
|
|
2887
|
+
iframeRef.current.contentWindow.postMessage(
|
|
2888
|
+
{ jsonrpc: "2.0", id, method, params },
|
|
2889
|
+
"*"
|
|
2890
|
+
);
|
|
2891
|
+
});
|
|
2892
|
+
}, [log]);
|
|
2893
|
+
const sendInitialize = useCallback(() => {
|
|
2894
|
+
var _a;
|
|
2895
|
+
if (isInitialized || !((_a = iframeRef.current) == null ? void 0 : _a.contentWindow))
|
|
2896
|
+
return;
|
|
2897
|
+
const hostContext = {
|
|
2898
|
+
// Include mcpAppId so app knows its canvas ID for message routing
|
|
2899
|
+
mcpAppId,
|
|
2900
|
+
state: mcpAppData == null ? void 0 : mcpAppData.state,
|
|
2901
|
+
toolInfo: mcpAppData == null ? void 0 : mcpAppData.toolInfo,
|
|
2902
|
+
...initialHostContext
|
|
2903
|
+
};
|
|
2904
|
+
const params = {
|
|
2905
|
+
protocolVersion: "mcp-apps/0.1",
|
|
2906
|
+
appInfo: { name: "McpAppHost", version: "1.0.0" },
|
|
2907
|
+
hostCapabilities: {
|
|
2908
|
+
openLinks: {},
|
|
2909
|
+
"botdojo/persistence": true,
|
|
2910
|
+
extensions: {
|
|
2911
|
+
"io.modelcontextprotocol/ui": { mimeTypes: ["text/html+mcp"] }
|
|
1706
2912
|
}
|
|
2913
|
+
},
|
|
2914
|
+
hostContext
|
|
2915
|
+
};
|
|
2916
|
+
log("Sending ui/initialize to app", params);
|
|
2917
|
+
sendRequest("ui/initialize", params, 2e3).then((result) => {
|
|
2918
|
+
log("App responded to ui/initialize:", result);
|
|
2919
|
+
}).catch((err) => {
|
|
2920
|
+
log("ui/initialize failed:", err.message);
|
|
2921
|
+
});
|
|
2922
|
+
}, [isInitialized, mcpAppId, mcpAppData, initialHostContext, log, sendRequest]);
|
|
2923
|
+
const sendInitializeWithRetry = useCallback(() => {
|
|
2924
|
+
if (isInitialized)
|
|
2925
|
+
return;
|
|
2926
|
+
const attemptSend = () => {
|
|
2927
|
+
if (isInitialized)
|
|
1707
2928
|
return;
|
|
2929
|
+
initializeAttemptsRef.current += 1;
|
|
2930
|
+
sendInitialize();
|
|
2931
|
+
if (initializeAttemptsRef.current < 5) {
|
|
2932
|
+
initializeTimerRef.current = setTimeout(attemptSend, 300);
|
|
2933
|
+
} else {
|
|
2934
|
+
initializeTimerRef.current = null;
|
|
2935
|
+
log("Max initialize attempts reached");
|
|
1708
2936
|
}
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
2937
|
+
};
|
|
2938
|
+
if (initializeTimerRef.current !== null) {
|
|
2939
|
+
clearTimeout(initializeTimerRef.current);
|
|
2940
|
+
}
|
|
2941
|
+
initializeAttemptsRef.current = 0;
|
|
2942
|
+
attemptSend();
|
|
2943
|
+
}, [isInitialized, sendInitialize, log]);
|
|
2944
|
+
const handleMessage = useCallback((event) => {
|
|
2945
|
+
var _a, _b, _c, _d;
|
|
2946
|
+
if (!iframeRef.current || event.source !== iframeRef.current.contentWindow) {
|
|
2947
|
+
return;
|
|
2948
|
+
}
|
|
2949
|
+
if (mcpAppHostContext == null ? void 0 : mcpAppHostContext.findAppIdBySource) {
|
|
2950
|
+
const sourceAppId = mcpAppHostContext.findAppIdBySource(event.source);
|
|
2951
|
+
if (sourceAppId && sourceAppId !== mcpAppId) {
|
|
2952
|
+
log("Message from different app, ignoring:", sourceAppId, "expected:", mcpAppId);
|
|
2953
|
+
return;
|
|
2954
|
+
}
|
|
2955
|
+
}
|
|
2956
|
+
const data = event.data;
|
|
2957
|
+
if (!data || data.jsonrpc !== "2.0")
|
|
2958
|
+
return;
|
|
2959
|
+
if ("id" in data && !("method" in data)) {
|
|
2960
|
+
const pending = pendingRequestsRef.current.get(String(data.id));
|
|
2961
|
+
if (pending) {
|
|
2962
|
+
if (pending.timer)
|
|
2963
|
+
clearTimeout(pending.timer);
|
|
2964
|
+
pendingRequestsRef.current.delete(String(data.id));
|
|
2965
|
+
if ("error" in data) {
|
|
2966
|
+
pending.reject(data.error);
|
|
2967
|
+
} else {
|
|
2968
|
+
pending.resolve(data.result);
|
|
1729
2969
|
}
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
2970
|
+
}
|
|
2971
|
+
return;
|
|
2972
|
+
}
|
|
2973
|
+
const { method, params, id } = data;
|
|
2974
|
+
log("Received:", method, params);
|
|
2975
|
+
switch (method) {
|
|
2976
|
+
case "ui/notifications/initialized": {
|
|
2977
|
+
log("App confirmed initialization");
|
|
2978
|
+
if (initializeTimerRef.current !== null) {
|
|
2979
|
+
clearTimeout(initializeTimerRef.current);
|
|
2980
|
+
initializeTimerRef.current = null;
|
|
2981
|
+
}
|
|
2982
|
+
setIsInitialized(true);
|
|
2983
|
+
isInitializedRef.current = true;
|
|
2984
|
+
const toolName = (_b = (_a = mcpAppData == null ? void 0 : mcpAppData.toolInfo) == null ? void 0 : _a.tool) == null ? void 0 : _b.name;
|
|
2985
|
+
if (toolName && ((_c = iframeRef.current) == null ? void 0 : _c.contentWindow)) {
|
|
2986
|
+
const args = mcpAppData == null ? void 0 : mcpAppData.arguments;
|
|
2987
|
+
const result = mcpAppData == null ? void 0 : mcpAppData.result;
|
|
2988
|
+
const toolIsComplete = mcpAppData == null ? void 0 : mcpAppData.isComplete;
|
|
2989
|
+
log("Sending hydration data after initialized:", {
|
|
2990
|
+
toolName,
|
|
2991
|
+
hasArgs: args !== void 0,
|
|
2992
|
+
hasResult: result !== void 0,
|
|
2993
|
+
isComplete: toolIsComplete
|
|
2994
|
+
});
|
|
2995
|
+
if (args !== void 0) {
|
|
2996
|
+
iframeRef.current.contentWindow.postMessage({
|
|
2997
|
+
jsonrpc: "2.0",
|
|
2998
|
+
method: "ui/notifications/tool-input",
|
|
2999
|
+
params: {
|
|
3000
|
+
tool: { name: toolName },
|
|
3001
|
+
arguments: args
|
|
1760
3002
|
}
|
|
1761
|
-
}
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
);
|
|
1771
|
-
if (result && ((_l = iframeRef.current) == null ? void 0 : _l.contentWindow)) {
|
|
1772
|
-
iframeRef.current.contentWindow.postMessage({
|
|
1773
|
-
type: "prompt_response",
|
|
1774
|
-
result
|
|
1775
|
-
}, "*");
|
|
1776
|
-
}
|
|
1777
|
-
} catch (err) {
|
|
1778
|
-
console.error("[BotDojoCanvasFrame] Error in onCanvasPrompt:", err);
|
|
3003
|
+
}, "*");
|
|
3004
|
+
}
|
|
3005
|
+
if (result !== void 0) {
|
|
3006
|
+
iframeRef.current.contentWindow.postMessage({
|
|
3007
|
+
jsonrpc: "2.0",
|
|
3008
|
+
method: "ui/notifications/tool-result",
|
|
3009
|
+
params: {
|
|
3010
|
+
tool: { name: toolName },
|
|
3011
|
+
result
|
|
1779
3012
|
}
|
|
1780
|
-
}
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
);
|
|
1790
|
-
} catch (err) {
|
|
1791
|
-
console.error("[BotDojoCanvasFrame] Error in onCanvasLink:", err);
|
|
3013
|
+
}, "*");
|
|
3014
|
+
} else if (toolIsComplete) {
|
|
3015
|
+
log("Sending synthetic tool-result for completed tool without stored result");
|
|
3016
|
+
iframeRef.current.contentWindow.postMessage({
|
|
3017
|
+
jsonrpc: "2.0",
|
|
3018
|
+
method: "ui/notifications/tool-result",
|
|
3019
|
+
params: {
|
|
3020
|
+
tool: { name: toolName },
|
|
3021
|
+
result: { completed: true }
|
|
1792
3022
|
}
|
|
3023
|
+
}, "*");
|
|
3024
|
+
}
|
|
3025
|
+
}
|
|
3026
|
+
if (pendingNotificationsRef.current.length > 0 && ((_d = iframeRef.current) == null ? void 0 : _d.contentWindow)) {
|
|
3027
|
+
log(`Replaying ${pendingNotificationsRef.current.length} queued notifications`);
|
|
3028
|
+
pendingNotificationsRef.current.forEach(({ method: method2, params: params2 }) => {
|
|
3029
|
+
log("Replaying notification:", method2, params2);
|
|
3030
|
+
iframeRef.current.contentWindow.postMessage(
|
|
3031
|
+
{ jsonrpc: "2.0", method: method2, params: params2 },
|
|
3032
|
+
"*"
|
|
3033
|
+
);
|
|
3034
|
+
});
|
|
3035
|
+
pendingNotificationsRef.current = [];
|
|
3036
|
+
}
|
|
3037
|
+
onReady == null ? void 0 : onReady(mcpAppId);
|
|
3038
|
+
break;
|
|
3039
|
+
}
|
|
3040
|
+
case "ui/initialize": {
|
|
3041
|
+
log("Handling ui/initialize request from app");
|
|
3042
|
+
const hostContext = {
|
|
3043
|
+
state: mcpAppData == null ? void 0 : mcpAppData.state,
|
|
3044
|
+
toolInfo: mcpAppData == null ? void 0 : mcpAppData.toolInfo,
|
|
3045
|
+
...initialHostContext
|
|
3046
|
+
};
|
|
3047
|
+
sendResponse(id, {
|
|
3048
|
+
appInfo: { name: "McpAppHost", version: "1.0.0" },
|
|
3049
|
+
hostCapabilities: {
|
|
3050
|
+
openLinks: {},
|
|
3051
|
+
"botdojo/persistence": true,
|
|
3052
|
+
extensions: {
|
|
3053
|
+
"io.modelcontextprotocol/ui": { mimeTypes: ["text/html+mcp"] }
|
|
1793
3054
|
}
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
3055
|
+
},
|
|
3056
|
+
hostContext
|
|
3057
|
+
});
|
|
3058
|
+
sendNotification("ui/notifications/initialized", {});
|
|
3059
|
+
if (initializeTimerRef.current !== null) {
|
|
3060
|
+
clearTimeout(initializeTimerRef.current);
|
|
3061
|
+
initializeTimerRef.current = null;
|
|
1797
3062
|
}
|
|
3063
|
+
setIsInitialized(true);
|
|
3064
|
+
onReady == null ? void 0 : onReady(mcpAppId);
|
|
3065
|
+
break;
|
|
1798
3066
|
}
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
3067
|
+
case "ui/open-link": {
|
|
3068
|
+
if (params == null ? void 0 : params.url) {
|
|
3069
|
+
const handler = onOpenLink || (mcpAppHostContext == null ? void 0 : mcpAppHostContext.onOpenLink);
|
|
3070
|
+
handler == null ? void 0 : handler(params.url, params.target || "_blank", mcpAppId);
|
|
3071
|
+
}
|
|
3072
|
+
if (id !== void 0) {
|
|
3073
|
+
sendResponse(id, { ok: true });
|
|
3074
|
+
}
|
|
3075
|
+
break;
|
|
1807
3076
|
}
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
3077
|
+
case "tools/call": {
|
|
3078
|
+
const toolName = (params == null ? void 0 : params.name) || (params == null ? void 0 : params.tool);
|
|
3079
|
+
const toolParams = (params == null ? void 0 : params.arguments) || (params == null ? void 0 : params.params) || {};
|
|
3080
|
+
const handler = onToolCall || (mcpAppHostContext == null ? void 0 : mcpAppHostContext.onToolCall);
|
|
3081
|
+
if (handler && toolName) {
|
|
3082
|
+
Promise.resolve(handler(toolName, toolParams, mcpAppId)).then((result) => {
|
|
3083
|
+
log("Tool call result:", result);
|
|
3084
|
+
if (id !== void 0) {
|
|
3085
|
+
sendResponse(id, result != null ? result : { ok: true });
|
|
3086
|
+
}
|
|
3087
|
+
}).catch((err) => {
|
|
3088
|
+
log("Tool call error:", err);
|
|
3089
|
+
if (id !== void 0) {
|
|
3090
|
+
sendError(id, -32e3, err.message || "Tool execution failed");
|
|
3091
|
+
}
|
|
3092
|
+
});
|
|
3093
|
+
} else {
|
|
3094
|
+
if (id !== void 0) {
|
|
3095
|
+
sendResponse(id, { ok: false, error: "No tool handler" });
|
|
3096
|
+
}
|
|
3097
|
+
}
|
|
3098
|
+
break;
|
|
1825
3099
|
}
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
3100
|
+
case "ui/message": {
|
|
3101
|
+
const contentArray = Array.isArray(params == null ? void 0 : params.content) ? params.content : [params == null ? void 0 : params.content].filter(Boolean);
|
|
3102
|
+
const firstContent = contentArray[0];
|
|
3103
|
+
if ((firstContent == null ? void 0 : firstContent["botdojo/messageType"]) === "persist-state" && typeof firstContent.text === "string") {
|
|
3104
|
+
log("Persist state message received (format 1: messageType + text)");
|
|
3105
|
+
try {
|
|
3106
|
+
const parsed = JSON.parse(firstContent.text);
|
|
3107
|
+
log("Parsed state to persist:", parsed);
|
|
3108
|
+
const persistHandler = onPersistState || (mcpAppHostContext == null ? void 0 : mcpAppHostContext.onPersistState);
|
|
3109
|
+
if (persistHandler) {
|
|
3110
|
+
persistHandler(parsed, mcpAppId);
|
|
3111
|
+
} else {
|
|
3112
|
+
log("No onPersistState handler provided - state will not be saved");
|
|
3113
|
+
}
|
|
3114
|
+
} catch (err) {
|
|
3115
|
+
log("Failed to parse persist-state content:", err);
|
|
3116
|
+
}
|
|
3117
|
+
if (id !== void 0) {
|
|
3118
|
+
sendResponse(id, { ok: true });
|
|
3119
|
+
}
|
|
3120
|
+
break;
|
|
3121
|
+
}
|
|
3122
|
+
if ((firstContent == null ? void 0 : firstContent.type) === "botdojo/persist" && firstContent.state) {
|
|
3123
|
+
log("Persist state message received (format 2/3: type + state object)");
|
|
3124
|
+
log("State to persist:", firstContent.state);
|
|
3125
|
+
const persistHandler = onPersistState || (mcpAppHostContext == null ? void 0 : mcpAppHostContext.onPersistState);
|
|
3126
|
+
if (persistHandler) {
|
|
3127
|
+
persistHandler(firstContent.state, mcpAppId);
|
|
3128
|
+
} else {
|
|
3129
|
+
log("No onPersistState handler provided - state will not be saved");
|
|
3130
|
+
}
|
|
3131
|
+
if (id !== void 0) {
|
|
3132
|
+
sendResponse(id, { ok: true });
|
|
3133
|
+
}
|
|
3134
|
+
break;
|
|
3135
|
+
}
|
|
3136
|
+
const handler = onUiMessage || (mcpAppHostContext == null ? void 0 : mcpAppHostContext.onUiMessage);
|
|
3137
|
+
if (handler) {
|
|
3138
|
+
const text = (firstContent == null ? void 0 : firstContent.text) || JSON.stringify(params);
|
|
3139
|
+
handler(text, params, mcpAppId);
|
|
3140
|
+
}
|
|
3141
|
+
if (id !== void 0) {
|
|
3142
|
+
sendResponse(id, { ok: true });
|
|
3143
|
+
}
|
|
3144
|
+
break;
|
|
3145
|
+
}
|
|
3146
|
+
case "ui/size-change":
|
|
3147
|
+
case "ui/notifications/size-change": {
|
|
3148
|
+
if (params == null ? void 0 : params.height) {
|
|
3149
|
+
setAutoHeight(params.height);
|
|
3150
|
+
}
|
|
3151
|
+
if ((params == null ? void 0 : params.width) && (params == null ? void 0 : params.height)) {
|
|
3152
|
+
onSizeChange == null ? void 0 : onSizeChange(params.width, params.height, mcpAppId);
|
|
3153
|
+
}
|
|
3154
|
+
break;
|
|
3155
|
+
}
|
|
3156
|
+
default: {
|
|
3157
|
+
log("Unhandled method:", method);
|
|
3158
|
+
if (id !== void 0) {
|
|
3159
|
+
sendResponse(id, { ok: true, ignored: true });
|
|
3160
|
+
}
|
|
3161
|
+
}
|
|
3162
|
+
}
|
|
3163
|
+
}, [
|
|
3164
|
+
mcpAppId,
|
|
3165
|
+
mcpAppData,
|
|
3166
|
+
onOpenLink,
|
|
3167
|
+
onToolCall,
|
|
3168
|
+
onUiMessage,
|
|
3169
|
+
onPersistState,
|
|
3170
|
+
onSizeChange,
|
|
3171
|
+
onReady,
|
|
3172
|
+
mcpAppHostContext,
|
|
3173
|
+
initialHostContext,
|
|
3174
|
+
log,
|
|
3175
|
+
sendResponse,
|
|
3176
|
+
sendError,
|
|
3177
|
+
sendNotification
|
|
3178
|
+
]);
|
|
3179
|
+
useEffect(() => {
|
|
3180
|
+
window.addEventListener("message", handleMessage);
|
|
3181
|
+
return () => window.removeEventListener("message", handleMessage);
|
|
3182
|
+
}, [handleMessage]);
|
|
3183
|
+
useEffect(() => {
|
|
3184
|
+
if (iframeLoaded && !isInitialized) {
|
|
3185
|
+
log("Iframe loaded, sending ui/initialize");
|
|
3186
|
+
sendInitializeWithRetry();
|
|
3187
|
+
}
|
|
3188
|
+
}, [iframeLoaded, isInitialized, sendInitializeWithRetry, log]);
|
|
3189
|
+
const prevStateRef = useRef(void 0);
|
|
3190
|
+
useEffect(() => {
|
|
3191
|
+
if (!isInitialized) {
|
|
3192
|
+
prevStateRef.current = mcpAppData == null ? void 0 : mcpAppData.state;
|
|
3193
|
+
return;
|
|
3194
|
+
}
|
|
3195
|
+
const currentState = mcpAppData == null ? void 0 : mcpAppData.state;
|
|
3196
|
+
const prevState = prevStateRef.current;
|
|
3197
|
+
const stateChanged = JSON.stringify(currentState) !== JSON.stringify(prevState);
|
|
3198
|
+
if (stateChanged && currentState !== void 0) {
|
|
3199
|
+
log("State changed after initialization, sending host-context-changed", { prevState, currentState });
|
|
3200
|
+
sendNotification("ui/notifications/host-context-changed", {
|
|
3201
|
+
state: currentState,
|
|
3202
|
+
toolInfo: mcpAppData == null ? void 0 : mcpAppData.toolInfo,
|
|
3203
|
+
...initialHostContext
|
|
3204
|
+
});
|
|
3205
|
+
prevStateRef.current = currentState;
|
|
3206
|
+
}
|
|
3207
|
+
}, [isInitialized, mcpAppData == null ? void 0 : mcpAppData.state, mcpAppData == null ? void 0 : mcpAppData.toolInfo, initialHostContext, sendNotification, log]);
|
|
3208
|
+
const handleIframeLoad = useCallback(() => {
|
|
3209
|
+
log("Iframe onLoad fired");
|
|
3210
|
+
setIframeLoaded(true);
|
|
3211
|
+
}, [log]);
|
|
3212
|
+
useEffect(() => {
|
|
3213
|
+
var _a;
|
|
3214
|
+
if (mcpAppHostContext && ((_a = iframeRef.current) == null ? void 0 : _a.contentWindow)) {
|
|
3215
|
+
mcpAppHostContext.registerApp(mcpAppId, iframeRef.current.contentWindow);
|
|
3216
|
+
return () => mcpAppHostContext.unregisterApp(mcpAppId);
|
|
3217
|
+
}
|
|
3218
|
+
}, [mcpAppId, mcpAppHostContext]);
|
|
3219
|
+
const chatContextRef = useRef(chatContext);
|
|
3220
|
+
chatContextRef.current = chatContext;
|
|
3221
|
+
useEffect(() => {
|
|
3222
|
+
const ctx = chatContextRef.current;
|
|
3223
|
+
if (!(ctx == null ? void 0 : ctx.registerToolNotificationSender)) {
|
|
3224
|
+
console.log(`[McpAppHost:${mcpAppId}] No registerToolNotificationSender available in context`);
|
|
3225
|
+
return;
|
|
3226
|
+
}
|
|
3227
|
+
console.log(`[McpAppHost:${mcpAppId}] Registering tool notification sender`);
|
|
3228
|
+
const sender = (method, params) => {
|
|
3229
|
+
var _a;
|
|
3230
|
+
if (!isInitializedRef.current || !((_a = iframeRef.current) == null ? void 0 : _a.contentWindow)) {
|
|
3231
|
+
console.log(`[McpAppHost:${mcpAppId}] Iframe not initialized, queueing notification:`, method);
|
|
3232
|
+
pendingNotificationsRef.current.push({ method, params });
|
|
3233
|
+
return;
|
|
3234
|
+
}
|
|
3235
|
+
if (debug) {
|
|
3236
|
+
console.log(`[McpAppHost:${mcpAppId}] Forwarding tool notification:`, method, params);
|
|
3237
|
+
}
|
|
3238
|
+
iframeRef.current.contentWindow.postMessage(
|
|
3239
|
+
{ jsonrpc: "2.0", method, params },
|
|
3240
|
+
"*"
|
|
3241
|
+
);
|
|
3242
|
+
};
|
|
3243
|
+
const unregister = ctx.registerToolNotificationSender(mcpAppId, sender);
|
|
3244
|
+
return unregister;
|
|
3245
|
+
}, [mcpAppId, debug]);
|
|
3246
|
+
useEffect(() => {
|
|
3247
|
+
const ctx = chatContextRef.current;
|
|
3248
|
+
if (!(ctx == null ? void 0 : ctx.registerStepUpdateCallback)) {
|
|
3249
|
+
console.log(`[McpAppHost:${mcpAppId}] No registerStepUpdateCallback available in context`);
|
|
3250
|
+
return;
|
|
3251
|
+
}
|
|
3252
|
+
console.log(`[McpAppHost:${mcpAppId}] Registering step update callback`);
|
|
3253
|
+
const callback = (stepUpdate) => {
|
|
3254
|
+
var _a, _b, _c, _d, _e;
|
|
3255
|
+
if (!((_a = iframeRef.current) == null ? void 0 : _a.contentWindow))
|
|
3256
|
+
return;
|
|
3257
|
+
if (debug) {
|
|
3258
|
+
console.log(`[McpAppHost:${mcpAppId}] Received step update via callback:`, stepUpdate);
|
|
3259
|
+
}
|
|
3260
|
+
const toolName = (stepUpdate == null ? void 0 : stepUpdate.toolName) || (stepUpdate == null ? void 0 : stepUpdate.tool) || ((_c = (_b = stepUpdate == null ? void 0 : stepUpdate.canvas) == null ? void 0 : _b.canvasData) == null ? void 0 : _c.toolName);
|
|
3261
|
+
const hasResult = (stepUpdate == null ? void 0 : stepUpdate.result) !== void 0;
|
|
3262
|
+
const argsStepId = (_d = stepUpdate == null ? void 0 : stepUpdate.arguments) == null ? void 0 : _d.stepId;
|
|
3263
|
+
const argsStepLabel = (_e = stepUpdate == null ? void 0 : stepUpdate.arguments) == null ? void 0 : _e.stepLabel;
|
|
3264
|
+
const hasStepInfo = argsStepId !== void 0 || argsStepLabel !== void 0 || (stepUpdate == null ? void 0 : stepUpdate.stepId) !== void 0 || (stepUpdate == null ? void 0 : stepUpdate.stepLabel) !== void 0;
|
|
3265
|
+
if (toolName && (hasStepInfo || hasResult)) {
|
|
3266
|
+
if (hasStepInfo) {
|
|
3267
|
+
if (debug) {
|
|
3268
|
+
console.log(`[McpAppHost:${mcpAppId}] Sending tool-input-partial to iframe (has step info)`);
|
|
3269
|
+
}
|
|
3270
|
+
iframeRef.current.contentWindow.postMessage({
|
|
3271
|
+
jsonrpc: "2.0",
|
|
3272
|
+
method: "ui/notifications/tool-input-partial",
|
|
3273
|
+
params: {
|
|
3274
|
+
tool: { name: toolName },
|
|
3275
|
+
arguments: {
|
|
3276
|
+
...stepUpdate.arguments || {},
|
|
3277
|
+
stepId: argsStepId != null ? argsStepId : stepUpdate.stepId,
|
|
3278
|
+
stepLabel: argsStepLabel != null ? argsStepLabel : stepUpdate.stepLabel
|
|
3279
|
+
}
|
|
3280
|
+
}
|
|
3281
|
+
}, "*");
|
|
3282
|
+
}
|
|
3283
|
+
if (hasResult) {
|
|
3284
|
+
if (debug) {
|
|
3285
|
+
console.log(`[McpAppHost:${mcpAppId}] Sending tool-result to iframe`);
|
|
3286
|
+
}
|
|
3287
|
+
iframeRef.current.contentWindow.postMessage({
|
|
3288
|
+
jsonrpc: "2.0",
|
|
3289
|
+
method: "ui/notifications/tool-result",
|
|
3290
|
+
params: {
|
|
3291
|
+
tool: { name: toolName },
|
|
3292
|
+
result: stepUpdate.result
|
|
3293
|
+
}
|
|
3294
|
+
}, "*");
|
|
3295
|
+
}
|
|
3296
|
+
}
|
|
3297
|
+
};
|
|
3298
|
+
const unregister = ctx.registerStepUpdateCallback(mcpAppId, callback);
|
|
3299
|
+
return unregister;
|
|
3300
|
+
}, [mcpAppId, debug]);
|
|
3301
|
+
useEffect(() => {
|
|
3302
|
+
if (!iframeRef.current)
|
|
3303
|
+
return;
|
|
3304
|
+
if (appHtml) {
|
|
3305
|
+
const blob = new Blob([appHtml], { type: "text/html" });
|
|
3306
|
+
const url = URL.createObjectURL(blob);
|
|
3307
|
+
iframeRef.current.src = url;
|
|
3308
|
+
return () => URL.revokeObjectURL(url);
|
|
3309
|
+
}
|
|
3310
|
+
if (appUrl) {
|
|
3311
|
+
iframeRef.current.src = appUrl;
|
|
3312
|
+
}
|
|
3313
|
+
}, [appHtml, appUrl]);
|
|
3314
|
+
useEffect(() => {
|
|
3315
|
+
return () => {
|
|
3316
|
+
if (initializeTimerRef.current !== null) {
|
|
3317
|
+
clearTimeout(initializeTimerRef.current);
|
|
3318
|
+
}
|
|
3319
|
+
pendingRequestsRef.current.forEach(({ timer, reject }) => {
|
|
3320
|
+
if (timer)
|
|
3321
|
+
clearTimeout(timer);
|
|
3322
|
+
reject(new Error("Component unmounted"));
|
|
3323
|
+
});
|
|
3324
|
+
pendingRequestsRef.current.clear();
|
|
3325
|
+
};
|
|
3326
|
+
}, []);
|
|
3327
|
+
useEffect(() => {
|
|
3328
|
+
setIframeLoaded(false);
|
|
3329
|
+
setIsInitialized(false);
|
|
3330
|
+
isInitializedRef.current = false;
|
|
3331
|
+
setAutoHeight(null);
|
|
3332
|
+
initializeAttemptsRef.current = 0;
|
|
3333
|
+
pendingNotificationsRef.current = [];
|
|
3334
|
+
if (initializeTimerRef.current !== null) {
|
|
3335
|
+
clearTimeout(initializeTimerRef.current);
|
|
3336
|
+
initializeTimerRef.current = null;
|
|
3337
|
+
}
|
|
3338
|
+
}, [appHtml, appUrl]);
|
|
3339
|
+
const effectiveHeight = autoHeight ? `${autoHeight}px` : (mcpAppData == null ? void 0 : mcpAppData.height) || height;
|
|
3340
|
+
return /* @__PURE__ */ jsx(
|
|
3341
|
+
"iframe",
|
|
1840
3342
|
{
|
|
1841
3343
|
ref: iframeRef,
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
onLoad: () => {
|
|
1845
|
-
console.log("[BotDojoCanvas] Iframe loaded:", canvasId, "type:", canvasType);
|
|
1846
|
-
if (isMcpUi) {
|
|
1847
|
-
setReady(true);
|
|
1848
|
-
}
|
|
1849
|
-
},
|
|
3344
|
+
title: `mcp-app-${mcpAppId}`,
|
|
3345
|
+
onLoad: handleIframeLoad,
|
|
1850
3346
|
style: {
|
|
1851
|
-
width
|
|
1852
|
-
height,
|
|
3347
|
+
width,
|
|
3348
|
+
height: effectiveHeight,
|
|
1853
3349
|
border: "none",
|
|
1854
|
-
|
|
3350
|
+
...style
|
|
1855
3351
|
},
|
|
1856
|
-
|
|
1857
|
-
allow: "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
|
3352
|
+
sandbox: "allow-forms allow-scripts allow-same-origin allow-popups"
|
|
1858
3353
|
}
|
|
1859
|
-
)
|
|
3354
|
+
);
|
|
1860
3355
|
}
|
|
1861
3356
|
var DEFAULT_CONFIG = {
|
|
1862
3357
|
mode: "chat-popup",
|
|
@@ -2674,203 +4169,574 @@ var BotDojoChatConfigurator = ({
|
|
|
2674
4169
|
] }) });
|
|
2675
4170
|
};
|
|
2676
4171
|
var CanvasContext = createContext(null);
|
|
4172
|
+
var DEFAULT_ACK_TTL_MS = 3 * 60 * 1e3;
|
|
4173
|
+
var DEFAULT_RESPONSE_TIMEOUT_MS = 2e4;
|
|
4174
|
+
var MCP_FUNCTION_NAME_MAP = {
|
|
4175
|
+
intent: "canvas_intent",
|
|
4176
|
+
notify: "canvas_notify",
|
|
4177
|
+
prompt: "canvas_prompt",
|
|
4178
|
+
tool: "canvas_tool",
|
|
4179
|
+
callTool: "canvas_tool",
|
|
4180
|
+
link: "canvas_link",
|
|
4181
|
+
update: "update_canvas_data",
|
|
4182
|
+
message: "mcp_app_message",
|
|
4183
|
+
"askAI": "mcp_app_message",
|
|
4184
|
+
"ui-size-change": "canvas_resize",
|
|
4185
|
+
"ui-lifecycle-iframe-ready": "canvas_ready",
|
|
4186
|
+
"botdojo/tool_update": "botdojo/tool_update"
|
|
4187
|
+
};
|
|
4188
|
+
function generateMessageId() {
|
|
4189
|
+
if (typeof crypto !== "undefined" && crypto.randomUUID) {
|
|
4190
|
+
return crypto.randomUUID();
|
|
4191
|
+
}
|
|
4192
|
+
return `mcp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
|
4193
|
+
}
|
|
4194
|
+
function normalizeMcpFunctionName(type) {
|
|
4195
|
+
if (MCP_FUNCTION_NAME_MAP[type]) {
|
|
4196
|
+
return MCP_FUNCTION_NAME_MAP[type];
|
|
4197
|
+
}
|
|
4198
|
+
return `mcp_app_${type.replace(/-/g, "_")}`;
|
|
4199
|
+
}
|
|
2677
4200
|
function BotDojoCanvasProvider({
|
|
2678
4201
|
children,
|
|
2679
4202
|
canvasData: initialCanvasData,
|
|
2680
4203
|
connector: externalConnector,
|
|
2681
|
-
modelContext,
|
|
2682
|
-
debug = false
|
|
4204
|
+
modelContext: modelContext2,
|
|
4205
|
+
debug = false,
|
|
4206
|
+
mode = "dojo",
|
|
4207
|
+
initialRenderData,
|
|
4208
|
+
mirrorLegacyCanvasRpc
|
|
2683
4209
|
}) {
|
|
4210
|
+
const isMcpUi = mode === "mcp-app";
|
|
4211
|
+
const mirrorLegacy = mirrorLegacyCanvasRpc != null ? mirrorLegacyCanvasRpc : isMcpUi;
|
|
2684
4212
|
const [isReady, setIsReady] = useState(false);
|
|
2685
4213
|
const [error, setError] = useState(null);
|
|
2686
4214
|
const [eventHandlers] = useState(/* @__PURE__ */ new Map());
|
|
2687
4215
|
const [connector, setConnector] = useState(externalConnector || null);
|
|
2688
|
-
const deriveStatusFromData = useCallback((data) => {
|
|
2689
|
-
if (!data) {
|
|
2690
|
-
return void 0;
|
|
2691
|
-
}
|
|
2692
|
-
if (data.status === "complete") {
|
|
2693
|
-
return "complete";
|
|
2694
|
-
}
|
|
2695
|
-
if (data.status === "error" || data.error) {
|
|
2696
|
-
return "error";
|
|
2697
|
-
}
|
|
2698
|
-
if (data.status) {
|
|
2699
|
-
return "processing";
|
|
2700
|
-
}
|
|
2701
|
-
return void 0;
|
|
2702
|
-
}, []);
|
|
2703
4216
|
const [canvasData, setCanvasData] = useState(initialCanvasData);
|
|
4217
|
+
const [renderData, setRenderData] = useState(initialRenderData != null ? initialRenderData : null);
|
|
4218
|
+
const [uiSize, setUiSize] = useState(null);
|
|
4219
|
+
const [messageIdMap, setMessageIdMap] = useState({});
|
|
4220
|
+
const [lastAck, setLastAck] = useState();
|
|
2704
4221
|
const [toolPhase, setToolPhase] = useState();
|
|
2705
|
-
const [toolStatus, setToolStatus] = useState(
|
|
2706
|
-
deriveStatusFromData(initialCanvasData)
|
|
2707
|
-
);
|
|
4222
|
+
const [toolStatus, setToolStatus] = useState();
|
|
2708
4223
|
const [partialArguments, setPartialArguments] = useState();
|
|
2709
4224
|
const [parsedArguments, setParsedArguments] = useState();
|
|
2710
4225
|
const [toolError, setToolError] = useState();
|
|
2711
4226
|
const [isExecuting, setIsExecuting] = useState(false);
|
|
4227
|
+
const pendingResponses = useRef(/* @__PURE__ */ new Map());
|
|
4228
|
+
const cleanupTimers = useRef(/* @__PURE__ */ new Map());
|
|
2712
4229
|
const log = useCallback((...args) => {
|
|
2713
4230
|
if (debug) {
|
|
2714
4231
|
console.log("[BotDojoCanvas]", ...args);
|
|
2715
4232
|
}
|
|
2716
4233
|
}, [debug]);
|
|
4234
|
+
const deriveStatusFromData = useCallback((data) => {
|
|
4235
|
+
if (!data)
|
|
4236
|
+
return void 0;
|
|
4237
|
+
if (data.status === "complete")
|
|
4238
|
+
return "complete";
|
|
4239
|
+
if (data.status === "error" || data.error)
|
|
4240
|
+
return "error";
|
|
4241
|
+
if (data.status)
|
|
4242
|
+
return "processing";
|
|
4243
|
+
return void 0;
|
|
4244
|
+
}, []);
|
|
4245
|
+
const emitEvent = useCallback((event, payload) => {
|
|
4246
|
+
const handlers = eventHandlers.get(event);
|
|
4247
|
+
if (handlers) {
|
|
4248
|
+
handlers.forEach((handler) => {
|
|
4249
|
+
try {
|
|
4250
|
+
handler(payload);
|
|
4251
|
+
} catch (err) {
|
|
4252
|
+
console.error("[BotDojoCanvas] Error in event handler:", err);
|
|
4253
|
+
}
|
|
4254
|
+
});
|
|
4255
|
+
}
|
|
4256
|
+
}, [eventHandlers]);
|
|
4257
|
+
const scheduleAckCleanup = useCallback((messageId) => {
|
|
4258
|
+
if (typeof window === "undefined")
|
|
4259
|
+
return;
|
|
4260
|
+
const timer = window.setTimeout(() => {
|
|
4261
|
+
setMessageIdMap((prev) => {
|
|
4262
|
+
const next = { ...prev };
|
|
4263
|
+
delete next[messageId];
|
|
4264
|
+
return next;
|
|
4265
|
+
});
|
|
4266
|
+
cleanupTimers.current.delete(messageId);
|
|
4267
|
+
}, DEFAULT_ACK_TTL_MS);
|
|
4268
|
+
cleanupTimers.current.set(messageId, timer);
|
|
4269
|
+
}, []);
|
|
4270
|
+
const handleMessageAck = useCallback((messageId, status, payload, err) => {
|
|
4271
|
+
const ts = Date.now();
|
|
4272
|
+
setMessageIdMap((prev) => ({
|
|
4273
|
+
...prev,
|
|
4274
|
+
[messageId]: { status, payload, error: err, ts }
|
|
4275
|
+
}));
|
|
4276
|
+
setLastAck({ messageId, status, payload, error: err, ts });
|
|
4277
|
+
if (status === "received") {
|
|
4278
|
+
emitEvent("mcp-app:message-received", { messageId, payload });
|
|
4279
|
+
return;
|
|
4280
|
+
}
|
|
4281
|
+
const pending = pendingResponses.current.get(messageId);
|
|
4282
|
+
if (pending) {
|
|
4283
|
+
if (pending.timer) {
|
|
4284
|
+
window.clearTimeout(pending.timer);
|
|
4285
|
+
}
|
|
4286
|
+
pendingResponses.current.delete(messageId);
|
|
4287
|
+
if (status === "error") {
|
|
4288
|
+
pending.reject(err != null ? err : new Error("Message responded with error"));
|
|
4289
|
+
} else {
|
|
4290
|
+
pending.resolve(payload);
|
|
4291
|
+
}
|
|
4292
|
+
}
|
|
4293
|
+
emitEvent("mcp-app:message-response", { messageId, payload, error: err });
|
|
4294
|
+
scheduleAckCleanup(messageId);
|
|
4295
|
+
}, [emitEvent, scheduleAckCleanup]);
|
|
4296
|
+
const handleToolUpdate = useCallback((update) => {
|
|
4297
|
+
var _a;
|
|
4298
|
+
if (!update)
|
|
4299
|
+
return;
|
|
4300
|
+
log("Handling botdojo/tool_update", update);
|
|
4301
|
+
if (update.stepStatus && update.stepStatus !== "complete" && update.stepStatus !== "error") {
|
|
4302
|
+
setIsExecuting(true);
|
|
4303
|
+
}
|
|
4304
|
+
if (update.canvasPatch) {
|
|
4305
|
+
setCanvasData((prev) => ({
|
|
4306
|
+
...prev || {},
|
|
4307
|
+
...typeof update.canvasPatch === "object" ? update.canvasPatch : {}
|
|
4308
|
+
}));
|
|
4309
|
+
}
|
|
4310
|
+
if ((_a = update.canvas) == null ? void 0 : _a.canvasData) {
|
|
4311
|
+
setCanvasData((prev) => ({
|
|
4312
|
+
...prev || {},
|
|
4313
|
+
...update.canvas.canvasData
|
|
4314
|
+
}));
|
|
4315
|
+
const derived = deriveStatusFromData(update.canvas.canvasData);
|
|
4316
|
+
if (derived) {
|
|
4317
|
+
setToolStatus(derived);
|
|
4318
|
+
}
|
|
4319
|
+
}
|
|
4320
|
+
if ("toolPhase" in update) {
|
|
4321
|
+
setToolPhase(update.toolPhase);
|
|
4322
|
+
}
|
|
4323
|
+
if (update.stepStatus) {
|
|
4324
|
+
const status = update.stepStatus === "complete" ? "complete" : update.stepStatus === "error" ? "error" : "processing";
|
|
4325
|
+
setToolStatus(status);
|
|
4326
|
+
if (status === "complete" || status === "error") {
|
|
4327
|
+
setIsExecuting(false);
|
|
4328
|
+
}
|
|
4329
|
+
}
|
|
4330
|
+
if (update.error) {
|
|
4331
|
+
setToolError(update.error);
|
|
4332
|
+
}
|
|
4333
|
+
if (update.argumentStream) {
|
|
4334
|
+
setPartialArguments(update.argumentStream);
|
|
4335
|
+
try {
|
|
4336
|
+
setParsedArguments(JSON.parse(update.argumentStream));
|
|
4337
|
+
} catch {
|
|
4338
|
+
}
|
|
4339
|
+
}
|
|
4340
|
+
if (update.arguments && update.toolPhase === "executing") {
|
|
4341
|
+
try {
|
|
4342
|
+
const parsed = typeof update.arguments === "string" ? JSON.parse(update.arguments) : update.arguments;
|
|
4343
|
+
setParsedArguments(parsed);
|
|
4344
|
+
} catch (e) {
|
|
4345
|
+
log("Error parsing arguments:", e);
|
|
4346
|
+
}
|
|
4347
|
+
}
|
|
4348
|
+
try {
|
|
4349
|
+
const customEvent = new CustomEvent("mcp-app:botdojo-tool-update", { detail: update });
|
|
4350
|
+
window.dispatchEvent(customEvent);
|
|
4351
|
+
} catch {
|
|
4352
|
+
}
|
|
4353
|
+
emitEvent("mcp-app:botdojo-tool-update", update);
|
|
4354
|
+
}, [deriveStatusFromData, emitEvent, log]);
|
|
2717
4355
|
useEffect(() => {
|
|
2718
4356
|
if (externalConnector) {
|
|
2719
4357
|
log("Using external connector");
|
|
2720
4358
|
setConnector(externalConnector);
|
|
2721
|
-
return;
|
|
4359
|
+
return () => void 0;
|
|
2722
4360
|
}
|
|
2723
4361
|
if (typeof window === "undefined" || window.self === window.parent) {
|
|
2724
4362
|
log("Not in iframe, no auto-connector");
|
|
2725
|
-
return;
|
|
4363
|
+
return () => void 0;
|
|
2726
4364
|
}
|
|
2727
4365
|
log("In iframe, creating auto-connector for postMessage");
|
|
2728
|
-
const urlParams = new URLSearchParams(window.location.search);
|
|
2729
|
-
const agentSocketUrl = urlParams.get("agent_socket_url");
|
|
2730
|
-
const canvasId = urlParams.get("canvas_id");
|
|
2731
|
-
const transport = urlParams.get("transport") || "postmessage";
|
|
2732
4366
|
const apiKey = window.BOTDOJO_API_KEY || "embedded-canvas";
|
|
2733
|
-
|
|
4367
|
+
let createdConnector = null;
|
|
2734
4368
|
try {
|
|
2735
|
-
console.log("[BotDojoCanvas] Creating connector for postMessage mode", { hasModelContext: !!modelContext, apiKey: !!apiKey, canvasId });
|
|
2736
4369
|
const conn = new BotDojoConnector({
|
|
2737
4370
|
apiKey,
|
|
2738
4371
|
accountId: "embedded",
|
|
2739
4372
|
projectId: "embedded",
|
|
2740
4373
|
flowId: "embedded",
|
|
2741
|
-
modelContext,
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
canvasId: canvasId || void 0
|
|
2745
|
-
// Pass canvasId if available from URL
|
|
4374
|
+
modelContext: modelContext2,
|
|
4375
|
+
transport: "postmessage"
|
|
4376
|
+
// No canvasId needed - parent routes messages to us based on iframe reference
|
|
2746
4377
|
});
|
|
2747
|
-
|
|
4378
|
+
createdConnector = conn;
|
|
2748
4379
|
conn.init().then(() => {
|
|
2749
4380
|
log("Auto-connector initialized");
|
|
2750
|
-
console.log("[BotDojoCanvas] Connector init complete, setting up PostMessage bridge");
|
|
2751
4381
|
if (window.parent !== window) {
|
|
2752
|
-
log("Setting up PostMessage bridge to parent (chat iframe)");
|
|
2753
|
-
console.log("[BotDojoCanvas] Calling updatePostMessageTarget...");
|
|
2754
4382
|
conn.updatePostMessageTarget(window.parent).then(async () => {
|
|
2755
4383
|
var _a;
|
|
2756
|
-
console.log("[BotDojoCanvas] PostMessage bridge to parent configured successfully");
|
|
2757
4384
|
log("PostMessage bridge to parent configured");
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
|
|
2762
|
-
|
|
2763
|
-
[],
|
|
2764
|
-
|
|
2765
|
-
|
|
2766
|
-
|
|
2767
|
-
if (
|
|
2768
|
-
|
|
4385
|
+
const MAX_READY_RETRIES = 5;
|
|
4386
|
+
const RETRY_DELAY_MS = 500;
|
|
4387
|
+
const sendReadySignal = async (attempt) => {
|
|
4388
|
+
var _a2, _b;
|
|
4389
|
+
try {
|
|
4390
|
+
await ((_a2 = conn.connection) == null ? void 0 : _a2.sendRequest("agent_host", "canvas_ready", [], 2e3));
|
|
4391
|
+
log(`canvas_ready succeeded on attempt ${attempt}`);
|
|
4392
|
+
return true;
|
|
4393
|
+
} catch (err) {
|
|
4394
|
+
if (attempt < MAX_READY_RETRIES) {
|
|
4395
|
+
log(`canvas_ready attempt ${attempt} failed, retrying in ${RETRY_DELAY_MS}ms...`);
|
|
4396
|
+
await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS));
|
|
4397
|
+
return sendReadySignal(attempt + 1);
|
|
4398
|
+
}
|
|
4399
|
+
if (!((_b = err == null ? void 0 : err.message) == null ? void 0 : _b.includes("Timeout"))) {
|
|
4400
|
+
console.warn("[BotDojoCanvas] canvas_ready failed after retries (non-critical):", err);
|
|
2769
4401
|
}
|
|
2770
|
-
|
|
4402
|
+
return false;
|
|
4403
|
+
}
|
|
4404
|
+
};
|
|
4405
|
+
try {
|
|
4406
|
+
await sendReadySignal(1);
|
|
4407
|
+
if (isMcpUi) {
|
|
4408
|
+
await ((_a = conn.connection) == null ? void 0 : _a.sendRequest("agent_host", normalizeMcpFunctionName("ui-lifecycle-iframe-ready"), [{ ready: true }], 2e3).catch(() => void 0));
|
|
4409
|
+
}
|
|
2771
4410
|
} catch (err) {
|
|
2772
|
-
console.warn("[BotDojoCanvas] Failed to send
|
|
4411
|
+
console.warn("[BotDojoCanvas] Failed to send ready signal:", err);
|
|
2773
4412
|
}
|
|
2774
4413
|
}).catch((err) => {
|
|
2775
4414
|
console.error("[BotDojoCanvas] Failed to configure PostMessage bridge:", err);
|
|
2776
4415
|
setError(err);
|
|
2777
4416
|
});
|
|
2778
|
-
} else {
|
|
2779
|
-
console.warn("[BotDojoCanvas] window.parent === window, not setting up PostMessage bridge");
|
|
2780
4417
|
}
|
|
2781
4418
|
}).catch((err) => {
|
|
2782
4419
|
console.error("[BotDojoCanvas] Failed to init auto-connector:", err);
|
|
2783
4420
|
setError(err);
|
|
2784
4421
|
});
|
|
2785
|
-
|
|
2786
|
-
console.log("[BotDojoCanvas] Setting connector state");
|
|
2787
|
-
setConnector(conn);
|
|
4422
|
+
setConnector(createdConnector);
|
|
2788
4423
|
} catch (err) {
|
|
2789
4424
|
console.error("[BotDojoCanvas] Failed to create auto-connector:", err);
|
|
2790
4425
|
setError(err);
|
|
2791
4426
|
}
|
|
2792
4427
|
return () => {
|
|
2793
|
-
if (
|
|
4428
|
+
if (createdConnector && !externalConnector) {
|
|
2794
4429
|
log("Cleaning up auto-connector");
|
|
2795
|
-
|
|
4430
|
+
createdConnector.close();
|
|
2796
4431
|
}
|
|
2797
4432
|
};
|
|
2798
|
-
}, [externalConnector, log]);
|
|
4433
|
+
}, [externalConnector, log, modelContext2, isMcpUi]);
|
|
2799
4434
|
useEffect(() => {
|
|
2800
|
-
log("Initializing canvas provider", { canvasData, hasConnector: !!connector });
|
|
4435
|
+
log("Initializing canvas provider", { canvasData, hasConnector: !!connector, mode });
|
|
2801
4436
|
setIsReady(true);
|
|
2802
|
-
|
|
2803
|
-
|
|
2804
|
-
|
|
2805
|
-
|
|
2806
|
-
|
|
2807
|
-
|
|
2808
|
-
|
|
2809
|
-
}
|
|
2810
|
-
});
|
|
4437
|
+
emitEvent("canvas:ready", { canvasData, renderData, mode });
|
|
4438
|
+
}, [canvasData, connector, emitEvent, log, mode, renderData]);
|
|
4439
|
+
const sendCanvasAction = useCallback(async (functionName, data) => {
|
|
4440
|
+
var _a;
|
|
4441
|
+
if (!connector) {
|
|
4442
|
+
log("Cannot send canvas action - no connector");
|
|
4443
|
+
return;
|
|
2811
4444
|
}
|
|
2812
|
-
|
|
2813
|
-
|
|
2814
|
-
|
|
4445
|
+
const conn = connector;
|
|
4446
|
+
if (!((_a = conn.connection) == null ? void 0 : _a.sendRequest)) {
|
|
4447
|
+
log("Cannot send canvas action - no RPC connection");
|
|
2815
4448
|
return;
|
|
2816
4449
|
}
|
|
2817
|
-
|
|
2818
|
-
|
|
2819
|
-
|
|
2820
|
-
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
html.scrollHeight,
|
|
2824
|
-
html.offsetHeight
|
|
2825
|
-
);
|
|
2826
|
-
const width = Math.max(
|
|
2827
|
-
body.scrollWidth,
|
|
2828
|
-
body.offsetWidth,
|
|
2829
|
-
html.clientWidth,
|
|
2830
|
-
html.scrollWidth,
|
|
2831
|
-
html.offsetWidth
|
|
2832
|
-
);
|
|
2833
|
-
log("Reporting size to parent:", { width, height });
|
|
2834
|
-
conn.connection.sendRequest(
|
|
2835
|
-
"agent_host",
|
|
2836
|
-
"canvas_resize",
|
|
2837
|
-
[{ width, height }],
|
|
2838
|
-
2e3
|
|
2839
|
-
).catch((err) => {
|
|
2840
|
-
var _a;
|
|
2841
|
-
if (!((_a = err.message) == null ? void 0 : _a.includes("timeout"))) {
|
|
2842
|
-
console.warn("[BotDojoCanvas] canvas_resize failed (non-critical):", err);
|
|
4450
|
+
try {
|
|
4451
|
+
return await conn.connection.sendRequest("agent_host", functionName, [data], 2e3);
|
|
4452
|
+
} catch (err) {
|
|
4453
|
+
if (typeof (err == null ? void 0 : err.message) === "string" && err.message.toLowerCase().includes("timeout")) {
|
|
4454
|
+
log("Canvas action timed out (ignored):", functionName);
|
|
4455
|
+
return { ok: true, timeout: true };
|
|
2843
4456
|
}
|
|
2844
|
-
|
|
2845
|
-
|
|
2846
|
-
useEffect(() => {
|
|
2847
|
-
if (!connector || typeof window === "undefined") {
|
|
2848
|
-
return;
|
|
4457
|
+
console.warn("[BotDojoCanvas] Canvas action failed:", functionName, err);
|
|
4458
|
+
throw err;
|
|
2849
4459
|
}
|
|
2850
|
-
|
|
2851
|
-
|
|
2852
|
-
|
|
2853
|
-
const
|
|
2854
|
-
|
|
2855
|
-
|
|
2856
|
-
|
|
2857
|
-
|
|
2858
|
-
|
|
2859
|
-
|
|
4460
|
+
}, [connector, log]);
|
|
4461
|
+
const sendMcpUiAction = useCallback(async (type, payload = {}, options = {}) => {
|
|
4462
|
+
var _a, _b, _c, _d, _e;
|
|
4463
|
+
const messageId = options.messageId || (payload == null ? void 0 : payload.messageId) || (options.awaitResponse ? generateMessageId() : void 0);
|
|
4464
|
+
const actionPayload = { ...payload, ...messageId ? { messageId } : {} };
|
|
4465
|
+
if (messageId) {
|
|
4466
|
+
setMessageIdMap((prev) => ({ ...prev, [messageId]: { status: "pending", ts: Date.now() } }));
|
|
4467
|
+
setLastAck({ messageId, status: "pending", ts: Date.now() });
|
|
4468
|
+
}
|
|
4469
|
+
const mcpMethodMap = {
|
|
4470
|
+
intent: "tools/call",
|
|
4471
|
+
notify: "ui/notify",
|
|
4472
|
+
prompt: "ui/prompt",
|
|
4473
|
+
link: "ui/open-link",
|
|
4474
|
+
update: "ui/update",
|
|
4475
|
+
message: "ui/message",
|
|
4476
|
+
"askAI": "ui/message",
|
|
4477
|
+
tool: "tools/call",
|
|
4478
|
+
"ui-size-change": "ui/notifications/size-change",
|
|
4479
|
+
"resources/read": "resources/read",
|
|
4480
|
+
"ui/message": "ui/message",
|
|
4481
|
+
"ui/open-link": "ui/open-link",
|
|
4482
|
+
"ui/update": "ui/update",
|
|
4483
|
+
"tools/call": "tools/call"
|
|
2860
4484
|
};
|
|
2861
|
-
|
|
4485
|
+
let responsePromise = null;
|
|
4486
|
+
if (messageId && options.awaitResponse) {
|
|
4487
|
+
const respTimeout = (_a = options.responseTimeoutMs) != null ? _a : DEFAULT_RESPONSE_TIMEOUT_MS;
|
|
4488
|
+
responsePromise = new Promise((resolve, reject) => {
|
|
4489
|
+
const timer = window.setTimeout(() => {
|
|
4490
|
+
pendingResponses.current.delete(messageId);
|
|
4491
|
+
resolve({ ok: true, timeout: true, viaPostMessage: true });
|
|
4492
|
+
}, respTimeout);
|
|
4493
|
+
pendingResponses.current.set(messageId, { resolve, reject, timer });
|
|
4494
|
+
});
|
|
4495
|
+
}
|
|
4496
|
+
if (isMcpUi && typeof window !== "undefined" && window.parent !== window) {
|
|
4497
|
+
const mcpMethod = type.includes("/") ? type : mcpMethodMap[type] || `ui/${type}`;
|
|
4498
|
+
log("[MCP Debug] sending MCP action via postMessage", { type, mcpMethod, messageId, params: actionPayload });
|
|
4499
|
+
const params = mcpMethod === "tools/call" ? {
|
|
4500
|
+
name: actionPayload.tool || actionPayload.intent || actionPayload.name,
|
|
4501
|
+
arguments: (_c = (_b = actionPayload.params) != null ? _b : actionPayload.arguments) != null ? _c : actionPayload,
|
|
4502
|
+
messageId
|
|
4503
|
+
} : actionPayload;
|
|
4504
|
+
const rpcEnvelope = messageId ? { jsonrpc: "2.0", id: messageId, method: mcpMethod, params } : { jsonrpc: "2.0", method: mcpMethod, params };
|
|
4505
|
+
try {
|
|
4506
|
+
window.parent.postMessage(rpcEnvelope, "*");
|
|
4507
|
+
log(`[MCP Debug] Sent MCP Apps action via postMessage: ${mcpMethod}`, actionPayload);
|
|
4508
|
+
} catch (err) {
|
|
4509
|
+
log(`[MCP Debug] Failed to send MCP Apps action ${mcpMethod} (non-critical)`, err);
|
|
4510
|
+
}
|
|
4511
|
+
}
|
|
4512
|
+
const conn = connector;
|
|
4513
|
+
const hasRpcConnection = (_d = conn == null ? void 0 : conn.connection) == null ? void 0 : _d.sendRequest;
|
|
4514
|
+
if (hasRpcConnection) {
|
|
4515
|
+
const functionName = normalizeMcpFunctionName(type);
|
|
4516
|
+
const shouldMirror = (_e = options.mirrorLegacyCanvasRpc) != null ? _e : mirrorLegacy;
|
|
4517
|
+
const rpcTimeout = options.responseTimeoutMs && options.responseTimeoutMs > 0 ? Math.min(options.responseTimeoutMs, 2e3) : isMcpUi ? 500 : 2e3;
|
|
4518
|
+
log("[MCP Debug] Mirroring MCP action via RPC", { type, functionName, messageId });
|
|
4519
|
+
const sendPromise = conn.connection.sendRequest("agent_host", functionName, [actionPayload], rpcTimeout).catch((err) => {
|
|
4520
|
+
var _a2;
|
|
4521
|
+
if ((_a2 = err.message) == null ? void 0 : _a2.includes("Timeout")) {
|
|
4522
|
+
log(`[MCP Debug] RPC timeout for ${type} (non-critical, postMessage already sent)`);
|
|
4523
|
+
return { ok: true, timeout: true };
|
|
4524
|
+
}
|
|
4525
|
+
throw err;
|
|
4526
|
+
});
|
|
4527
|
+
if (shouldMirror && type !== "ui-size-change") {
|
|
4528
|
+
const legacyMap = {
|
|
4529
|
+
intent: "canvas_intent",
|
|
4530
|
+
notify: "canvas_notify",
|
|
4531
|
+
prompt: "canvas_prompt",
|
|
4532
|
+
link: "canvas_link",
|
|
4533
|
+
update: "canvas_update",
|
|
4534
|
+
message: "canvas_message",
|
|
4535
|
+
"askAI": "canvas_message"
|
|
4536
|
+
};
|
|
4537
|
+
const legacyName = legacyMap[type];
|
|
4538
|
+
if (legacyName) {
|
|
4539
|
+
sendCanvasAction(legacyName, payload).catch(() => void 0);
|
|
4540
|
+
}
|
|
4541
|
+
}
|
|
4542
|
+
if (responsePromise) {
|
|
4543
|
+
try {
|
|
4544
|
+
const sendResult = await sendPromise;
|
|
4545
|
+
if (messageId) {
|
|
4546
|
+
const pending = pendingResponses.current.get(messageId);
|
|
4547
|
+
if (pending) {
|
|
4548
|
+
handleMessageAck(messageId, "responded", sendResult);
|
|
4549
|
+
}
|
|
4550
|
+
}
|
|
4551
|
+
} catch {
|
|
4552
|
+
}
|
|
4553
|
+
return responsePromise;
|
|
4554
|
+
}
|
|
4555
|
+
return sendPromise;
|
|
4556
|
+
}
|
|
4557
|
+
if (isMcpUi) {
|
|
4558
|
+
return responsePromise || { ok: true, viaPostMessage: true };
|
|
4559
|
+
}
|
|
4560
|
+
throw new Error("No connector available");
|
|
4561
|
+
}, [connector, handleMessageAck, isMcpUi, log, mirrorLegacy, scheduleAckCleanup, sendCanvasAction]);
|
|
4562
|
+
const sendMessage = useCallback(async (text, params, options) => {
|
|
4563
|
+
log("sendMessage called", { text, params, mode });
|
|
4564
|
+
if (isMcpUi) {
|
|
4565
|
+
const payload = { text, params: params || {} };
|
|
4566
|
+
const mcpPromise = sendMcpUiAction("message", payload, { awaitResponse: true, ...options }).catch((err) => {
|
|
4567
|
+
log("sendMcpUiAction(message) failed (non-blocking)", err);
|
|
4568
|
+
return void 0;
|
|
4569
|
+
});
|
|
4570
|
+
if (connector == null ? void 0 : connector.run) {
|
|
4571
|
+
const result = await connector.run({ text_input: text, ...params });
|
|
4572
|
+
emitEvent("message", result);
|
|
4573
|
+
await mcpPromise;
|
|
4574
|
+
return result;
|
|
4575
|
+
}
|
|
4576
|
+
return mcpPromise;
|
|
4577
|
+
}
|
|
4578
|
+
if (!connector) {
|
|
4579
|
+
throw new Error("No connector available");
|
|
4580
|
+
}
|
|
4581
|
+
try {
|
|
4582
|
+
const result = await connector.run({ text_input: text, ...params });
|
|
4583
|
+
emitEvent("message", result);
|
|
4584
|
+
return result;
|
|
4585
|
+
} catch (err) {
|
|
4586
|
+
log("sendMessage error", err);
|
|
4587
|
+
setError(err);
|
|
4588
|
+
emitEvent("error", err);
|
|
4589
|
+
throw err;
|
|
4590
|
+
}
|
|
4591
|
+
}, [connector, emitEvent, isMcpUi, log, mode, sendMcpUiAction]);
|
|
4592
|
+
const sendLink = useCallback((url, target = "_blank", options) => {
|
|
4593
|
+
log("sendLink called", { url, target });
|
|
4594
|
+
if (isMcpUi) {
|
|
4595
|
+
return sendMcpUiAction("link", { url, target }, options);
|
|
4596
|
+
}
|
|
4597
|
+
return sendCanvasAction("canvas_link", { url, target });
|
|
4598
|
+
}, [isMcpUi, sendCanvasAction, sendMcpUiAction, log]);
|
|
4599
|
+
const sendIntent = useCallback((intent, params, options) => {
|
|
4600
|
+
log("sendIntent called", { intent, params });
|
|
4601
|
+
if (isMcpUi) {
|
|
4602
|
+
return sendMcpUiAction("intent", { intent, params: params || {} }, { awaitResponse: true, ...options });
|
|
4603
|
+
}
|
|
4604
|
+
return sendCanvasAction("canvas_intent", { intent, params: params || {} });
|
|
4605
|
+
}, [isMcpUi, sendCanvasAction, sendMcpUiAction, log]);
|
|
4606
|
+
const sendNotify = useCallback((message, params, options) => {
|
|
4607
|
+
log("sendNotify called", { message, params });
|
|
4608
|
+
if (isMcpUi) {
|
|
4609
|
+
return sendMcpUiAction("notify", { message, params: params || {} }, options);
|
|
4610
|
+
}
|
|
4611
|
+
return sendCanvasAction("canvas_notify", { message, params: params || {} });
|
|
4612
|
+
}, [isMcpUi, sendCanvasAction, sendMcpUiAction, log]);
|
|
4613
|
+
const sendPrompt = useCallback((prompt, params, options) => {
|
|
4614
|
+
log("sendPrompt called", { prompt, params });
|
|
4615
|
+
if (isMcpUi) {
|
|
4616
|
+
return sendMcpUiAction("prompt", { prompt, params: params || {} }, { awaitResponse: true, ...options });
|
|
4617
|
+
}
|
|
4618
|
+
return sendCanvasAction("canvas_prompt", { prompt, params: params || {} });
|
|
4619
|
+
}, [isMcpUi, sendCanvasAction, sendMcpUiAction, log]);
|
|
4620
|
+
const sendUpdate = useCallback((data, options) => {
|
|
4621
|
+
if (isMcpUi) {
|
|
4622
|
+
return sendMcpUiAction("update", data, options);
|
|
4623
|
+
}
|
|
4624
|
+
if (connector == null ? void 0 : connector.updateState) {
|
|
4625
|
+
return connector.updateState(data);
|
|
4626
|
+
}
|
|
4627
|
+
return sendCanvasAction("canvas_update", data);
|
|
4628
|
+
}, [connector, isMcpUi, sendCanvasAction, sendMcpUiAction]);
|
|
4629
|
+
const sendTool = useCallback((toolName, args, options) => {
|
|
4630
|
+
if (isMcpUi) {
|
|
4631
|
+
return sendMcpUiAction("tool", { tool: toolName, params: args }, { awaitResponse: true, ...options });
|
|
4632
|
+
}
|
|
4633
|
+
if (connector == null ? void 0 : connector.executeToolCall) {
|
|
4634
|
+
return connector.executeToolCall(toolName, args);
|
|
4635
|
+
}
|
|
4636
|
+
return sendCanvasAction(toolName, args);
|
|
4637
|
+
}, [connector, isMcpUi, sendCanvasAction, sendMcpUiAction]);
|
|
4638
|
+
const dispatchUIAction = useCallback((action, options) => {
|
|
4639
|
+
return sendMcpUiAction(action.type, action.payload, { messageId: action.messageId, ...options });
|
|
4640
|
+
}, [sendMcpUiAction]);
|
|
2862
4641
|
useEffect(() => {
|
|
2863
|
-
if (!
|
|
4642
|
+
if (!initialCanvasData)
|
|
2864
4643
|
return;
|
|
4644
|
+
const derived = deriveStatusFromData(initialCanvasData);
|
|
4645
|
+
if (derived) {
|
|
4646
|
+
setToolStatus(derived);
|
|
2865
4647
|
}
|
|
2866
|
-
|
|
2867
|
-
}, [connector, modelContext, log]);
|
|
4648
|
+
}, [initialCanvasData, deriveStatusFromData]);
|
|
2868
4649
|
useEffect(() => {
|
|
2869
|
-
if (typeof window === "undefined"
|
|
2870
|
-
return;
|
|
4650
|
+
if (typeof window === "undefined") {
|
|
4651
|
+
return () => void 0;
|
|
2871
4652
|
}
|
|
2872
4653
|
const handleMessage = (event) => {
|
|
2873
|
-
var _a, _b;
|
|
4654
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
|
|
4655
|
+
if (isMcpUi && ((_a = event.data) == null ? void 0 : _a.jsonrpc) === "2.0" && "id" in event.data && !event.data.method) {
|
|
4656
|
+
const rpcId = String(event.data.id);
|
|
4657
|
+
if (pendingResponses.current.has(rpcId)) {
|
|
4658
|
+
const pending = pendingResponses.current.get(rpcId);
|
|
4659
|
+
if (pending.timer)
|
|
4660
|
+
window.clearTimeout(pending.timer);
|
|
4661
|
+
pendingResponses.current.delete(rpcId);
|
|
4662
|
+
if ("error" in event.data) {
|
|
4663
|
+
pending.reject(event.data.error);
|
|
4664
|
+
handleMessageAck(rpcId, "error", void 0, (_b = event.data.error) == null ? void 0 : _b.message);
|
|
4665
|
+
} else {
|
|
4666
|
+
pending.resolve(event.data.result);
|
|
4667
|
+
handleMessageAck(rpcId, "responded", event.data.result);
|
|
4668
|
+
}
|
|
4669
|
+
scheduleAckCleanup(rpcId);
|
|
4670
|
+
}
|
|
4671
|
+
return;
|
|
4672
|
+
}
|
|
4673
|
+
if (isMcpUi && ((_c = event.data) == null ? void 0 : _c.method) && typeof event.data.method === "string") {
|
|
4674
|
+
const { method, params } = event.data;
|
|
4675
|
+
log("Received MCP Apps protocol message:", method);
|
|
4676
|
+
if (method === "ui/notifications/tool-input-partial" || method === "ui/notifications/tool-input") {
|
|
4677
|
+
if (params == null ? void 0 : params.arguments) {
|
|
4678
|
+
log("Updating canvasData from tool-input:", params.arguments);
|
|
4679
|
+
setCanvasData((prev) => ({ ...prev || {}, ...params.arguments }));
|
|
4680
|
+
emitEvent("mcp-app:tool-input", params);
|
|
4681
|
+
}
|
|
4682
|
+
return;
|
|
4683
|
+
}
|
|
4684
|
+
if (method === "ui/initialize") {
|
|
4685
|
+
log("Received ui/initialize", params);
|
|
4686
|
+
const capabilities = ((_e = (_d = params == null ? void 0 : params.hostCapabilities) == null ? void 0 : _d.extensions) == null ? void 0 : _e["io.modelcontextprotocol/ui"]) || ((_g = (_f = params == null ? void 0 : params.capabilities) == null ? void 0 : _f.extensions) == null ? void 0 : _g["io.modelcontextprotocol/ui"]);
|
|
4687
|
+
if (!capabilities || !((_h = capabilities.mimeTypes) == null ? void 0 : _h.includes("text/html+mcp"))) {
|
|
4688
|
+
const err = new Error("Host does not advertise io.modelcontextprotocol/ui with text/html+mcp");
|
|
4689
|
+
setError(err);
|
|
4690
|
+
if ((_i = event.data) == null ? void 0 : _i.id) {
|
|
4691
|
+
(window.parent || window).postMessage(
|
|
4692
|
+
{ jsonrpc: "2.0", id: event.data.id, error: { code: -32001, message: err.message } },
|
|
4693
|
+
"*"
|
|
4694
|
+
);
|
|
4695
|
+
}
|
|
4696
|
+
return;
|
|
4697
|
+
}
|
|
4698
|
+
const hostContext = params == null ? void 0 : params.hostContext;
|
|
4699
|
+
if (hostContext == null ? void 0 : hostContext.initialData) {
|
|
4700
|
+
log("Received initial data from hostContext (hydration):", hostContext.initialData);
|
|
4701
|
+
setCanvasData((prev) => ({ ...prev || {}, ...hostContext.initialData }));
|
|
4702
|
+
emitEvent("mcp-app:initial-data", hostContext.initialData);
|
|
4703
|
+
}
|
|
4704
|
+
if ((_j = event.data) == null ? void 0 : _j.id) {
|
|
4705
|
+
(window.parent || window).postMessage(
|
|
4706
|
+
{
|
|
4707
|
+
jsonrpc: "2.0",
|
|
4708
|
+
id: event.data.id,
|
|
4709
|
+
result: {
|
|
4710
|
+
clientInfo: { name: "BotDojo Canvas", version: "1.0.0" }
|
|
4711
|
+
}
|
|
4712
|
+
},
|
|
4713
|
+
"*"
|
|
4714
|
+
);
|
|
4715
|
+
}
|
|
4716
|
+
if (window.parent !== window) {
|
|
4717
|
+
window.parent.postMessage({ jsonrpc: "2.0", method: "ui/notifications/initialized", params: {} }, "*");
|
|
4718
|
+
}
|
|
4719
|
+
return;
|
|
4720
|
+
}
|
|
4721
|
+
if (method === "ui/notifications/host-context-changed" || method === "ui/notifications/host-context-change") {
|
|
4722
|
+
log("Received host-context change", params);
|
|
4723
|
+
emitEvent("mcp-app:host-context-changed", params);
|
|
4724
|
+
return;
|
|
4725
|
+
}
|
|
4726
|
+
if (method === "ui/tool-cancelled") {
|
|
4727
|
+
log("Received tool-cancelled", params);
|
|
4728
|
+
setIsExecuting(false);
|
|
4729
|
+
emitEvent("mcp-app:tool-cancelled", params);
|
|
4730
|
+
return;
|
|
4731
|
+
}
|
|
4732
|
+
if (method === "ui/notifications/tool-result") {
|
|
4733
|
+
log("Received tool-result", params);
|
|
4734
|
+
setIsExecuting(false);
|
|
4735
|
+
emitEvent("mcp-app:tool-result", params);
|
|
4736
|
+
return;
|
|
4737
|
+
}
|
|
4738
|
+
return;
|
|
4739
|
+
}
|
|
2874
4740
|
if (!event.data || event.data.type !== "botdojo-rpc") {
|
|
2875
4741
|
return;
|
|
2876
4742
|
}
|
|
@@ -2878,26 +4744,32 @@ function BotDojoCanvasProvider({
|
|
|
2878
4744
|
if (!msg || msg.direction !== "request") {
|
|
2879
4745
|
return;
|
|
2880
4746
|
}
|
|
2881
|
-
|
|
4747
|
+
if (isMcpUi && (msg.functionName === "botdojo/tool_update" || msg.functionName === "botdojo_tool_update")) {
|
|
4748
|
+
handleToolUpdate((_k = msg.data) == null ? void 0 : _k[0]);
|
|
4749
|
+
return;
|
|
4750
|
+
}
|
|
4751
|
+
if (isMcpUi && ((_l = msg.functionName) == null ? void 0 : _l.startsWith("mcp_ui_"))) {
|
|
4752
|
+
const payload = (_m = msg.data) == null ? void 0 : _m[0];
|
|
4753
|
+
const mcpType = msg.functionName.replace("mcp_ui_", "");
|
|
4754
|
+
if (mcpType === "lifecycle_render_data") {
|
|
4755
|
+
setRenderData(payload);
|
|
4756
|
+
emitEvent("mcp-app:render-data", payload);
|
|
4757
|
+
}
|
|
4758
|
+
if (mcpType === "message_received" && (payload == null ? void 0 : payload.messageId)) {
|
|
4759
|
+
handleMessageAck(payload.messageId, "received", (_n = payload.payload) != null ? _n : payload.data);
|
|
4760
|
+
}
|
|
4761
|
+
if (mcpType === "message_response" && (payload == null ? void 0 : payload.messageId)) {
|
|
4762
|
+
handleMessageAck(payload.messageId, payload.error ? "error" : "responded", (_o = payload.payload) != null ? _o : payload.data, payload.error);
|
|
4763
|
+
}
|
|
4764
|
+
return;
|
|
4765
|
+
}
|
|
2882
4766
|
if (msg.functionName === "onIntermediateStepUpdate") {
|
|
2883
|
-
const update = (
|
|
2884
|
-
console.log("[BotDojoCanvas] Received onIntermediateStepUpdate:", {
|
|
2885
|
-
hasUpdate: !!update,
|
|
2886
|
-
hasCanvas: update == null ? void 0 : update.canvas,
|
|
2887
|
-
toolPhase: update == null ? void 0 : update.toolPhase,
|
|
2888
|
-
stepStatus: update == null ? void 0 : update.stepStatus,
|
|
2889
|
-
argumentStream: update == null ? void 0 : update.argumentStream,
|
|
2890
|
-
isExecuting
|
|
2891
|
-
});
|
|
4767
|
+
const update = (_p = msg.data) == null ? void 0 : _p[0];
|
|
2892
4768
|
if (update && (update.canvas || isExecuting)) {
|
|
2893
4769
|
if (update.canvas) {
|
|
2894
|
-
log("Updating canvas from intermediate step:", update.canvas);
|
|
2895
4770
|
setIsExecuting(true);
|
|
2896
4771
|
if (update.canvas.canvasData) {
|
|
2897
|
-
setCanvasData((prev) => ({
|
|
2898
|
-
...prev,
|
|
2899
|
-
...update.canvas.canvasData
|
|
2900
|
-
}));
|
|
4772
|
+
setCanvasData((prev) => ({ ...prev || {}, ...update.canvas.canvasData }));
|
|
2901
4773
|
if (!update.stepStatus) {
|
|
2902
4774
|
const derived = deriveStatusFromData(update.canvas.canvasData);
|
|
2903
4775
|
if (derived) {
|
|
@@ -2905,16 +4777,12 @@ function BotDojoCanvasProvider({
|
|
|
2905
4777
|
}
|
|
2906
4778
|
}
|
|
2907
4779
|
}
|
|
2908
|
-
} else {
|
|
2909
|
-
log("Updating canvas from intermediate step update (no canvas field, continuing execution)");
|
|
2910
4780
|
}
|
|
2911
4781
|
if ("toolPhase" in update) {
|
|
2912
|
-
console.log("[BotDojoCanvas] Setting toolPhase to:", update.toolPhase);
|
|
2913
4782
|
setToolPhase(update.toolPhase);
|
|
2914
4783
|
}
|
|
2915
4784
|
if (update.stepStatus) {
|
|
2916
4785
|
const status = update.stepStatus === "complete" ? "complete" : update.stepStatus === "error" ? "error" : "processing";
|
|
2917
|
-
console.log("[BotDojoCanvas] Setting toolStatus to:", status);
|
|
2918
4786
|
setToolStatus(status);
|
|
2919
4787
|
if (status === "complete" || status === "error") {
|
|
2920
4788
|
setIsExecuting(false);
|
|
@@ -2939,17 +4807,15 @@ function BotDojoCanvasProvider({
|
|
|
2939
4807
|
}
|
|
2940
4808
|
}
|
|
2941
4809
|
}
|
|
4810
|
+
return;
|
|
2942
4811
|
}
|
|
2943
4812
|
if (msg.functionName === "onNewToken") {
|
|
2944
|
-
const tokenUpdate = (
|
|
2945
|
-
if (tokenUpdate) {
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
setParsedArguments(JSON.parse(tokenUpdate.toolArguments));
|
|
2951
|
-
} catch {
|
|
2952
|
-
}
|
|
4813
|
+
const tokenUpdate = (_q = msg.data) == null ? void 0 : _q[0];
|
|
4814
|
+
if (tokenUpdate == null ? void 0 : tokenUpdate.toolArguments) {
|
|
4815
|
+
setPartialArguments(tokenUpdate.toolArguments);
|
|
4816
|
+
try {
|
|
4817
|
+
setParsedArguments(JSON.parse(tokenUpdate.toolArguments));
|
|
4818
|
+
} catch {
|
|
2953
4819
|
}
|
|
2954
4820
|
}
|
|
2955
4821
|
}
|
|
@@ -2960,82 +4826,116 @@ function BotDojoCanvasProvider({
|
|
|
2960
4826
|
window.removeEventListener("message", handleMessage);
|
|
2961
4827
|
log("Stopped listening for flow events");
|
|
2962
4828
|
};
|
|
2963
|
-
}, [deriveStatusFromData, log]);
|
|
2964
|
-
|
|
2965
|
-
if (
|
|
4829
|
+
}, [deriveStatusFromData, emitEvent, handleMessageAck, handleToolUpdate, isExecuting, isMcpUi, log]);
|
|
4830
|
+
const reportSize = useCallback((conn) => {
|
|
4831
|
+
if (typeof window === "undefined") {
|
|
2966
4832
|
return;
|
|
2967
4833
|
}
|
|
2968
|
-
const
|
|
2969
|
-
|
|
2970
|
-
|
|
4834
|
+
const body = document.body;
|
|
4835
|
+
const html = document.documentElement;
|
|
4836
|
+
const height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
|
|
4837
|
+
const width = Math.max(body.scrollWidth, body.offsetWidth, html.clientWidth, html.scrollWidth, html.offsetWidth);
|
|
4838
|
+
setUiSize({ width, height });
|
|
4839
|
+
if (isMcpUi && window.parent !== window) {
|
|
4840
|
+
try {
|
|
4841
|
+
window.parent.postMessage({
|
|
4842
|
+
jsonrpc: "2.0",
|
|
4843
|
+
method: "ui/notifications/size-change",
|
|
4844
|
+
params: { width, height }
|
|
4845
|
+
}, "*");
|
|
4846
|
+
log("Sent MCP Apps size-change notification", { width, height });
|
|
4847
|
+
} catch (err) {
|
|
4848
|
+
log("Failed to send MCP Apps size-change (non-critical)", err);
|
|
4849
|
+
}
|
|
4850
|
+
sendMcpUiAction("ui-size-change", { width, height }, { mirrorLegacyCanvasRpc: mirrorLegacy }).catch(() => void 0);
|
|
4851
|
+
return;
|
|
2971
4852
|
}
|
|
2972
|
-
|
|
2973
|
-
|
|
2974
|
-
log("sendMessage called", { text, params });
|
|
2975
|
-
if (!connector) {
|
|
2976
|
-
throw new Error("No connector available");
|
|
4853
|
+
if (!(conn == null ? void 0 : conn.connection)) {
|
|
4854
|
+
return;
|
|
2977
4855
|
}
|
|
2978
|
-
|
|
2979
|
-
|
|
2980
|
-
|
|
2981
|
-
|
|
2982
|
-
});
|
|
2983
|
-
log("sendMessage result", result);
|
|
2984
|
-
const handlers = eventHandlers.get("message");
|
|
2985
|
-
if (handlers) {
|
|
2986
|
-
handlers.forEach((handler) => {
|
|
2987
|
-
try {
|
|
2988
|
-
handler(result);
|
|
2989
|
-
} catch (err) {
|
|
2990
|
-
console.error("[BotDojoCanvas] Error in message handler:", err);
|
|
2991
|
-
}
|
|
2992
|
-
});
|
|
2993
|
-
}
|
|
2994
|
-
return result;
|
|
2995
|
-
} catch (err) {
|
|
2996
|
-
log("sendMessage error", err);
|
|
2997
|
-
setError(err);
|
|
2998
|
-
const handlers = eventHandlers.get("error");
|
|
2999
|
-
if (handlers) {
|
|
3000
|
-
handlers.forEach((handler) => {
|
|
3001
|
-
try {
|
|
3002
|
-
handler(err);
|
|
3003
|
-
} catch (e) {
|
|
3004
|
-
console.error("[BotDojoCanvas] Error in error handler:", e);
|
|
3005
|
-
}
|
|
3006
|
-
});
|
|
4856
|
+
conn.connection.sendRequest("agent_host", "canvas_resize", [{ width, height }], 2e3).catch((err) => {
|
|
4857
|
+
var _a;
|
|
4858
|
+
if (!((_a = err.message) == null ? void 0 : _a.includes("timeout"))) {
|
|
4859
|
+
console.warn("[BotDojoCanvas] canvas_resize failed (non-critical):", err);
|
|
3007
4860
|
}
|
|
3008
|
-
|
|
4861
|
+
});
|
|
4862
|
+
}, [isMcpUi, log, mirrorLegacy, sendMcpUiAction]);
|
|
4863
|
+
useEffect(() => {
|
|
4864
|
+
if (!connector || typeof window === "undefined") {
|
|
4865
|
+
return () => void 0;
|
|
3009
4866
|
}
|
|
3010
|
-
|
|
4867
|
+
const initialTimer = window.setTimeout(() => {
|
|
4868
|
+
reportSize(connector);
|
|
4869
|
+
}, 100);
|
|
4870
|
+
const observer = new ResizeObserver(() => {
|
|
4871
|
+
reportSize(connector);
|
|
4872
|
+
});
|
|
4873
|
+
observer.observe(document.body);
|
|
4874
|
+
return () => {
|
|
4875
|
+
window.clearTimeout(initialTimer);
|
|
4876
|
+
observer.disconnect();
|
|
4877
|
+
};
|
|
4878
|
+
}, [connector, reportSize, canvasData]);
|
|
4879
|
+
useEffect(() => {
|
|
4880
|
+
return () => {
|
|
4881
|
+
if (isMcpUi && typeof window !== "undefined" && window.parent !== window) {
|
|
4882
|
+
try {
|
|
4883
|
+
window.parent.postMessage({ jsonrpc: "2.0", method: "ui/resource-teardown", params: {} }, "*");
|
|
4884
|
+
} catch {
|
|
4885
|
+
}
|
|
4886
|
+
}
|
|
4887
|
+
};
|
|
4888
|
+
}, [isMcpUi]);
|
|
4889
|
+
useEffect(() => {
|
|
4890
|
+
return () => {
|
|
4891
|
+
pendingResponses.current.forEach(({ timer }) => {
|
|
4892
|
+
if (timer)
|
|
4893
|
+
window.clearTimeout(timer);
|
|
4894
|
+
});
|
|
4895
|
+
cleanupTimers.current.forEach((timer) => window.clearTimeout(timer));
|
|
4896
|
+
pendingResponses.current.clear();
|
|
4897
|
+
cleanupTimers.current.clear();
|
|
4898
|
+
};
|
|
4899
|
+
}, []);
|
|
3011
4900
|
const on = useCallback((event, handler) => {
|
|
3012
|
-
log("Registering event handler", event);
|
|
3013
4901
|
if (!eventHandlers.has(event)) {
|
|
3014
4902
|
eventHandlers.set(event, /* @__PURE__ */ new Set());
|
|
3015
4903
|
}
|
|
3016
4904
|
const handlers = eventHandlers.get(event);
|
|
3017
4905
|
handlers.add(handler);
|
|
3018
4906
|
return () => {
|
|
3019
|
-
log("Unregistering event handler", event);
|
|
3020
4907
|
handlers.delete(handler);
|
|
3021
4908
|
};
|
|
3022
|
-
}, [eventHandlers
|
|
4909
|
+
}, [eventHandlers]);
|
|
3023
4910
|
const contextValue = useMemo(() => ({
|
|
3024
4911
|
isReady,
|
|
3025
4912
|
error,
|
|
3026
4913
|
canvasData: canvasData || null,
|
|
4914
|
+
renderData,
|
|
4915
|
+
lastAck,
|
|
4916
|
+
messageIdMap,
|
|
4917
|
+
uiSize,
|
|
4918
|
+
mode,
|
|
3027
4919
|
connector: connector || null,
|
|
3028
4920
|
isMockMode: false,
|
|
3029
4921
|
sendMessage,
|
|
4922
|
+
sendLink,
|
|
4923
|
+
sendIntent,
|
|
4924
|
+
sendNotify,
|
|
4925
|
+
sendPrompt,
|
|
4926
|
+
sendTool,
|
|
4927
|
+
sendUpdate,
|
|
4928
|
+
dispatchUIAction,
|
|
3030
4929
|
on,
|
|
3031
4930
|
toolPhase,
|
|
3032
4931
|
toolStatus,
|
|
3033
4932
|
partialArguments,
|
|
3034
4933
|
parsedArguments,
|
|
3035
4934
|
toolError
|
|
3036
|
-
}), [
|
|
4935
|
+
}), [canvasData, connector, dispatchUIAction, error, isReady, lastAck, messageIdMap, mode, on, parsedArguments, partialArguments, renderData, sendIntent, sendLink, sendMessage, sendNotify, sendPrompt, sendTool, sendUpdate, toolError, toolPhase, toolStatus, uiSize]);
|
|
3037
4936
|
return /* @__PURE__ */ jsx(CanvasContext.Provider, { value: contextValue, children });
|
|
3038
4937
|
}
|
|
4938
|
+
var hasWarnedDeprecation = false;
|
|
3039
4939
|
function MockCanvasProvider({
|
|
3040
4940
|
children,
|
|
3041
4941
|
mockCanvasData,
|
|
@@ -3043,6 +4943,14 @@ function MockCanvasProvider({
|
|
|
3043
4943
|
debug = false
|
|
3044
4944
|
}) {
|
|
3045
4945
|
const [eventHandlers] = useState(/* @__PURE__ */ new Map());
|
|
4946
|
+
useEffect(() => {
|
|
4947
|
+
if (!hasWarnedDeprecation) {
|
|
4948
|
+
hasWarnedDeprecation = true;
|
|
4949
|
+
console.warn(
|
|
4950
|
+
"[DEPRECATED] MockCanvasProvider is deprecated. Use useMcpApp from mcp-app-view/react with initialState instead. See migration guide: https://docs.botdojo.com/migration/mcp-apps"
|
|
4951
|
+
);
|
|
4952
|
+
}
|
|
4953
|
+
}, []);
|
|
3046
4954
|
const log = useCallback((...args) => {
|
|
3047
4955
|
if (debug) {
|
|
3048
4956
|
console.log("[MockCanvas]", ...args);
|
|
@@ -3105,9 +5013,21 @@ function MockCanvasProvider({
|
|
|
3105
5013
|
isReady: true,
|
|
3106
5014
|
// Mock is always ready
|
|
3107
5015
|
error: null,
|
|
5016
|
+
renderData: mockCanvasData == null ? void 0 : mockCanvasData.renderData,
|
|
5017
|
+
lastAck: void 0,
|
|
5018
|
+
messageIdMap: {},
|
|
5019
|
+
uiSize: null,
|
|
5020
|
+
mode: "dojo",
|
|
3108
5021
|
connector: null,
|
|
3109
5022
|
isMockMode: true,
|
|
3110
5023
|
sendMessage,
|
|
5024
|
+
sendLink: async () => void 0,
|
|
5025
|
+
sendIntent: async () => void 0,
|
|
5026
|
+
sendNotify: async () => void 0,
|
|
5027
|
+
sendPrompt: async () => void 0,
|
|
5028
|
+
sendTool: async () => void 0,
|
|
5029
|
+
sendUpdate: async () => void 0,
|
|
5030
|
+
dispatchUIAction: async () => void 0,
|
|
3111
5031
|
on,
|
|
3112
5032
|
// Spread mockCanvasData to include canvasData and tool execution fields
|
|
3113
5033
|
...mockCanvasData || {},
|
|
@@ -3116,14 +5036,23 @@ function MockCanvasProvider({
|
|
|
3116
5036
|
}), [mockCanvasData, sendMessage, on]);
|
|
3117
5037
|
return /* @__PURE__ */ jsx(CanvasContext.Provider, { value: contextValue, children });
|
|
3118
5038
|
}
|
|
5039
|
+
var hasWarnedDeprecation2 = false;
|
|
3119
5040
|
function useBotDojoCanvas() {
|
|
3120
5041
|
const context = useContext(CanvasContext);
|
|
5042
|
+
useEffect(() => {
|
|
5043
|
+
if (!hasWarnedDeprecation2) {
|
|
5044
|
+
hasWarnedDeprecation2 = true;
|
|
5045
|
+
console.warn(
|
|
5046
|
+
"[DEPRECATED] useBotDojoCanvas is deprecated. Use useMcpApp from mcp-app-view/react instead. See migration guide: https://docs.botdojo.com/migration/mcp-apps"
|
|
5047
|
+
);
|
|
5048
|
+
}
|
|
5049
|
+
}, []);
|
|
3121
5050
|
if (!context) {
|
|
3122
5051
|
throw new Error("useBotDojoCanvas must be used within BotDojoCanvasProvider or MockCanvasProvider");
|
|
3123
5052
|
}
|
|
3124
5053
|
return context;
|
|
3125
5054
|
}
|
|
3126
5055
|
|
|
3127
|
-
export { BotDojoCanvasFrame, BotDojoCanvasProvider, BotDojoChat, BotDojoChatConfigurator, BotDojoChatProvider, HeadlessChat, MockCanvasProvider, useBotDojoCanvas, useBotDojoChat, useChatActions, useChatMessages, useChatStatus };
|
|
5056
|
+
export { BotDojoCanvasFrame, BotDojoCanvasProvider, BotDojoChat, BotDojoChatConfigurator, BotDojoChatProvider, HeadlessChat, McpAppHost, McpAppHostContext, McpAppHostProvider, MockCanvasProvider, useBotDojoCanvas, useBotDojoChat, useChatActions, useChatMessages, useChatStatus, useMcpAppHost, useMcpAppHostRequired };
|
|
3128
5057
|
//# sourceMappingURL=out.js.map
|
|
3129
5058
|
//# sourceMappingURL=index.js.map
|