@meshagent/meshagent-tailwind 0.43.2 → 0.43.3

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.
Files changed (37) hide show
  1. package/CHANGELOG.md +3 -0
  2. package/dist/cjs/chat/agent-thread.d.ts +15 -0
  3. package/dist/cjs/chat/agent-thread.js +613 -0
  4. package/dist/cjs/chat/chat-bot-view.d.ts +3 -2
  5. package/dist/cjs/chat/chat-bot-view.js +34 -34
  6. package/dist/cjs/chat/chat-bot-view.test.js +325 -0
  7. package/dist/cjs/chat/live-chat-widgets.test.js +256 -0
  8. package/dist/cjs/chat/multi-thread-view.d.ts +3 -2
  9. package/dist/cjs/chat/multi-thread-view.js +4 -2
  10. package/dist/cjs/chat/new-chat-thread.d.ts +3 -2
  11. package/dist/cjs/chat/new-chat-thread.js +5 -2
  12. package/dist/cjs/file-preview/file-preview.js +2 -2
  13. package/dist/cjs/index.d.ts +1 -2
  14. package/dist/cjs/index.js +1 -2
  15. package/dist/esm/chat/agent-thread.d.ts +15 -0
  16. package/dist/esm/chat/agent-thread.js +606 -0
  17. package/dist/esm/chat/chat-bot-view.d.ts +3 -2
  18. package/dist/esm/chat/chat-bot-view.js +34 -34
  19. package/dist/esm/chat/chat-bot-view.test.js +336 -0
  20. package/dist/esm/chat/live-chat-widgets.test.js +262 -0
  21. package/dist/esm/chat/multi-thread-view.d.ts +3 -2
  22. package/dist/esm/chat/multi-thread-view.js +4 -2
  23. package/dist/esm/chat/new-chat-thread.d.ts +3 -2
  24. package/dist/esm/chat/new-chat-thread.js +5 -2
  25. package/dist/esm/file-preview/file-preview.js +2 -2
  26. package/dist/esm/index.d.ts +1 -2
  27. package/dist/esm/index.js +1 -2
  28. package/dist/index.css +1 -1
  29. package/package.json +10 -5
  30. package/dist/cjs/chat/chat-thread.d.ts +0 -12
  31. package/dist/cjs/chat/chat-thread.js +0 -815
  32. package/dist/cjs/chat/dataset-chat-thread.d.ts +0 -16
  33. package/dist/cjs/chat/dataset-chat-thread.js +0 -1813
  34. package/dist/esm/chat/chat-thread.d.ts +0 -12
  35. package/dist/esm/chat/chat-thread.js +0 -785
  36. package/dist/esm/chat/dataset-chat-thread.d.ts +0 -16
  37. package/dist/esm/chat/dataset-chat-thread.js +0 -1811
package/CHANGELOG.md CHANGED
@@ -1,3 +1,6 @@
1
+ ## [0.43.3]
2
+ - Stability
3
+
1
4
  ## [0.43.2]
2
5
  - Introduced `@meshagent/meshagent-livekit` as a standalone TypeScript helper package, with `livekit-client ^2.15.5`.
3
6
  - Reworked `@meshagent/meshagent-agents` packaging for dual ESM/CommonJS/browser resolution, including `.js` specifiers, module-scoped `src/`, and an ESM-default export.
@@ -0,0 +1,15 @@
1
+ import type { ReactElement } from "react";
2
+ import type { RoomClient } from "@meshagent/meshagent";
3
+ import type { BaseChatClient, ClientToolkitDescription } from "@meshagent/meshagent-agents";
4
+ interface AgentThreadProps {
5
+ room: RoomClient;
6
+ path: string;
7
+ chatClient?: BaseChatClient;
8
+ disposeChatClient?: boolean;
9
+ agentName?: string;
10
+ emptyStateTitle?: string;
11
+ emptyStateDescription?: string;
12
+ clientToolkits?: ClientToolkitDescription[];
13
+ }
14
+ export declare function AgentThread({ room, path, chatClient, disposeChatClient, agentName, emptyStateTitle, emptyStateDescription, clientToolkits, }: AgentThreadProps): ReactElement;
15
+ export {};
@@ -0,0 +1,613 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var agent_thread_exports = {};
30
+ __export(agent_thread_exports, {
31
+ AgentThread: () => AgentThread
32
+ });
33
+ module.exports = __toCommonJS(agent_thread_exports);
34
+ var import_jsx_runtime = require("react/jsx-runtime");
35
+ var import_react = require("react");
36
+ var import_meshagent_agents = require("@meshagent/meshagent-agents");
37
+ var import_lucide_react = require("lucide-react");
38
+ var import_react_markdown = __toESM(require("react-markdown"));
39
+ var import_rehype_highlight = __toESM(require("rehype-highlight"));
40
+ var import_rehype_sanitize = __toESM(require("rehype-sanitize"));
41
+ var import_remark_gfm = __toESM(require("remark-gfm"));
42
+ var import_spinner = require("../components/ui/spinner.js");
43
+ var import_utils = require("../lib/utils.js");
44
+ var import_chat_input = require("./chat-input.js");
45
+ var import_chat_typing_indicator = require("./chat-typing-indicator.js");
46
+ var import_file_attachment = require("./file-attachment.js");
47
+ const stickyBottomThresholdPx = 24;
48
+ function isTypedMessage(message, ctor) {
49
+ return message instanceof ctor;
50
+ }
51
+ function stringValue(value) {
52
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
53
+ }
54
+ function displayParticipantName(name) {
55
+ const normalized = name?.trim();
56
+ if (!normalized) {
57
+ return "agent";
58
+ }
59
+ return normalized.split("@")[0]?.trim() || normalized;
60
+ }
61
+ function getParticipantName(participant) {
62
+ const name = participant?.getAttribute("name");
63
+ return typeof name === "string" ? name.trim() : "";
64
+ }
65
+ function findAgentParticipant(room, agentName) {
66
+ const normalizedAgentName = agentName?.trim();
67
+ for (const participant of room.messaging.remoteParticipants) {
68
+ if (normalizedAgentName && getParticipantName(participant) !== normalizedAgentName) {
69
+ continue;
70
+ }
71
+ if (participant.getAttribute("supports_agent_messages") === true) {
72
+ return participant;
73
+ }
74
+ }
75
+ return null;
76
+ }
77
+ function timeAgo(date) {
78
+ const seconds = Math.max(0, Math.floor((Date.now() - date.getTime()) / 1e3));
79
+ if (seconds < 60) {
80
+ return "now";
81
+ }
82
+ const minutes = Math.floor(seconds / 60);
83
+ if (minutes < 60) {
84
+ return `${minutes}m`;
85
+ }
86
+ const hours = Math.floor(minutes / 60);
87
+ if (hours < 24) {
88
+ return `${hours}h`;
89
+ }
90
+ return `${Math.floor(hours / 24)}d`;
91
+ }
92
+ function distanceFromBottom(element) {
93
+ return Math.max(element.scrollHeight - element.clientHeight - element.scrollTop, 0);
94
+ }
95
+ function isNearBottom(element) {
96
+ return distanceFromBottom(element) <= stickyBottomThresholdPx;
97
+ }
98
+ function inputContent(message) {
99
+ const textParts = [];
100
+ const attachments = [];
101
+ for (const item of message.content ?? []) {
102
+ if (item.type === "text" && item.text.trim() !== "") {
103
+ textParts.push(item.text);
104
+ } else if (item.type === "file" && item.url.trim() !== "") {
105
+ attachments.push(item.url);
106
+ }
107
+ }
108
+ return { text: textParts.join("\n"), attachments };
109
+ }
110
+ function inputItemFromMessage(message, createdAt) {
111
+ if (isTypedMessage(message, import_meshagent_agents.StartThread) || isTypedMessage(message, import_meshagent_agents.TurnStart) || isTypedMessage(message, import_meshagent_agents.TurnSteer)) {
112
+ const content = inputContent(message);
113
+ if (content.text.trim() === "" && content.attachments.length === 0) {
114
+ return null;
115
+ }
116
+ return {
117
+ id: message.messageId,
118
+ kind: "message",
119
+ role: "user",
120
+ text: content.text,
121
+ attachments: content.attachments,
122
+ authorName: message.senderName,
123
+ createdAt
124
+ };
125
+ }
126
+ if (isTypedMessage(message, import_meshagent_agents.TurnStartAccepted) || isTypedMessage(message, import_meshagent_agents.TurnSteerAccepted)) {
127
+ const content = inputContent(message);
128
+ if (content.text.trim() === "" && content.attachments.length === 0) {
129
+ return null;
130
+ }
131
+ return {
132
+ id: message.sourceMessageId,
133
+ kind: "message",
134
+ role: "user",
135
+ text: content.text,
136
+ attachments: content.attachments,
137
+ authorName: message.senderName,
138
+ createdAt
139
+ };
140
+ }
141
+ return null;
142
+ }
143
+ function pendingItemFromInput(pending) {
144
+ const item = inputItemFromMessage(pending.payload, pending.createdAt);
145
+ if (item === null) {
146
+ return null;
147
+ }
148
+ return { ...item, id: pending.messageId };
149
+ }
150
+ function upsertItem(items, item) {
151
+ items.set(item.id, { ...items.get(item.id), ...item });
152
+ }
153
+ function appendText(items, itemId, base, text) {
154
+ if (text === "") {
155
+ return;
156
+ }
157
+ const existing = items.get(itemId);
158
+ upsertItem(items, {
159
+ ...base,
160
+ id: itemId,
161
+ text: `${existing?.text ?? ""}${text}`,
162
+ attachments: existing?.attachments ?? []
163
+ });
164
+ }
165
+ function imageStatus(message) {
166
+ if (isTypedMessage(message, import_meshagent_agents.AgentImageGenerationCompleted)) {
167
+ return "completed";
168
+ }
169
+ if (isTypedMessage(message, import_meshagent_agents.AgentImageGenerationFailed)) {
170
+ return "failed";
171
+ }
172
+ return "in_progress";
173
+ }
174
+ function feedFromSession(session) {
175
+ if (session === null) {
176
+ return [];
177
+ }
178
+ const items = /* @__PURE__ */ new Map();
179
+ for (const event of session.messages) {
180
+ const message = event.message;
181
+ const createdAt = /* @__PURE__ */ new Date();
182
+ const inputItem = inputItemFromMessage(message, createdAt);
183
+ if (inputItem !== null && !items.has(inputItem.id)) {
184
+ upsertItem(items, inputItem);
185
+ continue;
186
+ }
187
+ if (isTypedMessage(message, import_meshagent_agents.AgentTextContentStarted)) {
188
+ upsertItem(items, {
189
+ id: message.itemId,
190
+ kind: "message",
191
+ role: "agent",
192
+ text: "",
193
+ attachments: [],
194
+ createdAt
195
+ });
196
+ } else if (isTypedMessage(message, import_meshagent_agents.AgentTextContentDelta)) {
197
+ appendText(items, message.itemId, {
198
+ id: message.itemId,
199
+ kind: "message",
200
+ role: "agent",
201
+ createdAt
202
+ }, message.text);
203
+ } else if (isTypedMessage(message, import_meshagent_agents.AgentTextContentEnded)) {
204
+ if (!items.has(message.itemId)) {
205
+ upsertItem(items, {
206
+ id: message.itemId,
207
+ kind: "message",
208
+ role: "agent",
209
+ text: "",
210
+ attachments: [],
211
+ createdAt
212
+ });
213
+ }
214
+ } else if (isTypedMessage(message, import_meshagent_agents.AgentReasoningContentStarted)) {
215
+ upsertItem(items, {
216
+ id: message.itemId,
217
+ kind: "reasoning",
218
+ role: "agent",
219
+ text: "",
220
+ attachments: [],
221
+ createdAt
222
+ });
223
+ } else if (isTypedMessage(message, import_meshagent_agents.AgentReasoningContentDelta)) {
224
+ appendText(items, message.itemId, {
225
+ id: message.itemId,
226
+ kind: "reasoning",
227
+ role: "agent",
228
+ createdAt
229
+ }, message.text);
230
+ } else if (isTypedMessage(message, import_meshagent_agents.AgentReasoningContentEnded)) {
231
+ if (!items.has(message.itemId)) {
232
+ upsertItem(items, {
233
+ id: message.itemId,
234
+ kind: "reasoning",
235
+ role: "agent",
236
+ text: "",
237
+ attachments: [],
238
+ createdAt
239
+ });
240
+ }
241
+ } else if (isTypedMessage(message, import_meshagent_agents.AgentFileContentDelta)) {
242
+ const existing = items.get(message.itemId);
243
+ const attachments = existing?.attachments ?? [];
244
+ if (!attachments.includes(message.url)) {
245
+ attachments.push(message.url);
246
+ }
247
+ upsertItem(items, {
248
+ id: message.itemId,
249
+ kind: "message",
250
+ role: "agent",
251
+ text: existing?.text ?? "",
252
+ attachments,
253
+ createdAt
254
+ });
255
+ } else if (isTypedMessage(message, import_meshagent_agents.AgentToolCallPending) || isTypedMessage(message, import_meshagent_agents.AgentToolCallInProgress) || isTypedMessage(message, import_meshagent_agents.AgentToolCallStarted) || isTypedMessage(message, import_meshagent_agents.AgentToolCallEnded)) {
256
+ upsertItem(items, {
257
+ id: message.itemId,
258
+ kind: "tool_call",
259
+ role: "agent",
260
+ text: [message.toolkit, message.tool].filter((part) => part?.trim()).join(".") || "Tool call",
261
+ attachments: [],
262
+ createdAt
263
+ });
264
+ } else if (isTypedMessage(message, import_meshagent_agents.AgentImageGenerationStarted) || isTypedMessage(message, import_meshagent_agents.AgentImageGenerationPartial) || isTypedMessage(message, import_meshagent_agents.AgentImageGenerationCompleted) || isTypedMessage(message, import_meshagent_agents.AgentImageGenerationFailed)) {
265
+ const image = isTypedMessage(message, import_meshagent_agents.AgentImageGenerationPartial) ? message.image : isTypedMessage(message, import_meshagent_agents.AgentImageGenerationCompleted) ? message.images[0] : void 0;
266
+ upsertItem(items, {
267
+ id: message.itemId,
268
+ kind: "image_generation",
269
+ role: "agent",
270
+ text: "",
271
+ attachments: [],
272
+ createdAt,
273
+ image: {
274
+ uri: image?.uri,
275
+ status: image?.status ?? imageStatus(message),
276
+ statusDetail: isTypedMessage(message, import_meshagent_agents.AgentImageGenerationFailed) ? message.error.message : void 0
277
+ }
278
+ });
279
+ }
280
+ }
281
+ for (const pending of session.pendingInputs) {
282
+ const item = pendingItemFromInput(pending);
283
+ if (item !== null && !items.has(item.id)) {
284
+ upsertItem(items, item);
285
+ }
286
+ }
287
+ return [...items.values()].filter((item) => item.text.trim() !== "" || item.attachments.length > 0 || item.image != null || item.kind === "tool_call");
288
+ }
289
+ function latestThreadStatus(session) {
290
+ if (session === null) {
291
+ return null;
292
+ }
293
+ const status = session.threadStatus;
294
+ if (status !== void 0 && isTypedMessage(status, import_meshagent_agents.AgentThreadStatus)) {
295
+ return status;
296
+ }
297
+ return null;
298
+ }
299
+ function dateFromString(value) {
300
+ if (value == null || value.trim() === "") {
301
+ return null;
302
+ }
303
+ const parsed = new Date(value);
304
+ return Number.isNaN(parsed.getTime()) ? null : parsed;
305
+ }
306
+ function normalizeAttachmentPath(path) {
307
+ const prefix = "room:///";
308
+ return path.startsWith(prefix) ? path.slice(prefix.length) : path;
309
+ }
310
+ function MarkdownBlock({ text }) {
311
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
312
+ import_react_markdown.default,
313
+ {
314
+ remarkPlugins: [import_remark_gfm.default],
315
+ rehypePlugins: [import_rehype_sanitize.default, import_rehype_highlight.default],
316
+ components: {
317
+ pre: ({ className, children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("pre", { ...props, className: (0, import_utils.cn)("overflow-x-auto rounded-md border bg-background/80 p-3", className), children }),
318
+ p: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { ...props, className: "mb-2 last:mb-0", children }),
319
+ ul: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("ul", { ...props, className: "mb-2 ml-6 list-disc last:mb-0", children }),
320
+ ol: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("ol", { ...props, className: "mb-2 ml-6 list-decimal last:mb-0", children })
321
+ },
322
+ children: text
323
+ }
324
+ );
325
+ }
326
+ function ChatBubble({ text, mine }) {
327
+ if (text.trim() === "") {
328
+ return null;
329
+ }
330
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: (0, import_utils.cn)(
331
+ "w-fit max-w-[85%] rounded-md px-4 py-3 text-sm leading-6 shadow-xs sm:max-w-2xl",
332
+ mine ? "bg-secondary/85 text-foreground" : "bg-muted/70 text-foreground"
333
+ ), children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(MarkdownBlock, { text }) });
334
+ }
335
+ function AttachmentView({ room, path }) {
336
+ const preview = normalizeAttachmentPath(path);
337
+ const filename = preview.split("/").pop() ?? preview;
338
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
339
+ "button",
340
+ {
341
+ type: "button",
342
+ className: "inline-flex max-w-full items-center gap-2 rounded-md bg-muted/60 px-3 py-2 text-left shadow-xs transition-colors hover:bg-muted/80",
343
+ onClick: () => {
344
+ void room.storage.downloadUrl(preview).then((url) => {
345
+ window.open(url, "_blank", "noopener,noreferrer");
346
+ });
347
+ },
348
+ children: [
349
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_lucide_react.FileText, { className: "h-4 w-4 shrink-0 text-muted-foreground" }),
350
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "truncate text-sm font-medium", children: filename }),
351
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_lucide_react.Download, { className: "h-4 w-4 shrink-0 text-muted-foreground" })
352
+ ]
353
+ }
354
+ );
355
+ }
356
+ function ThreadMessageView({
357
+ room,
358
+ message,
359
+ previous,
360
+ localParticipantName,
361
+ agentName
362
+ }) {
363
+ if (message.kind === "reasoning" || message.kind === "tool_call") {
364
+ return message.text.trim() === "" ? null : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "px-6 py-1 text-center text-sm text-muted-foreground", children: message.text });
365
+ }
366
+ const mine = message.role === "user";
367
+ const authorName = message.authorName ?? (mine ? localParticipantName : displayParticipantName(agentName));
368
+ const previousAuthor = previous?.authorName ?? (previous?.role === "user" ? localParticipantName : displayParticipantName(agentName));
369
+ const shouldShowHeader = previous?.kind !== "message" || previousAuthor !== authorName;
370
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex flex-col gap-2", children: [
371
+ shouldShowHeader ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: (0, import_utils.cn)("flex w-full", mine ? "justify-end" : "justify-start"), children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: (0, import_utils.cn)("max-w-[85%] px-1 sm:max-w-2xl", mine ? "text-right" : "text-left"), children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: (0, import_utils.cn)("flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground", mine ? "justify-end" : "justify-start"), children: [
372
+ authorName.trim() !== "" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "font-semibold text-foreground", children: displayParticipantName(authorName) }) : null,
373
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: timeAgo(message.createdAt) })
374
+ ] }) }) }) : null,
375
+ message.text.trim() !== "" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: (0, import_utils.cn)("flex w-full", mine ? "justify-end" : "justify-start"), children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ChatBubble, { text: message.text, mine }) }) : null,
376
+ message.attachments.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: (0, import_utils.cn)("flex w-full", mine ? "justify-end" : "justify-start"), children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: (0, import_utils.cn)("flex max-w-[85%] flex-wrap gap-3 px-1 sm:max-w-2xl", mine ? "justify-end" : "justify-start"), children: message.attachments.map((attachment, index) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AttachmentView, { room, path: attachment }, `${message.id}:attachment:${attachment}:${index}`)) }) }) : null,
377
+ message.image ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "flex w-full justify-start", children: message.image.uri ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("img", { src: message.image.uri, alt: "Generated image", className: "max-h-[312px] max-w-full rounded-md object-contain shadow-xs" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "flex h-[240px] w-[240px] items-center justify-center rounded-md border bg-background text-muted-foreground", children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex max-w-full flex-col items-center gap-2 px-3 text-center text-xs", children: [
378
+ message.image.status === "failed" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_lucide_react.ImageOff, { className: "h-5 w-5" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_spinner.Spinner, { className: "h-5 w-5" }),
379
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: message.image.statusDetail ?? (message.image.status === "failed" ? "Image failed" : "Generating image") })
380
+ ] }) }) }) : null
381
+ ] });
382
+ }
383
+ function EmptyState({ title, description }) {
384
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "mx-auto flex h-full max-w-2xl flex-col items-center justify-center px-6 py-20 text-center", children: [
385
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("h2", { className: "text-4xl font-semibold tracking-tight text-foreground sm:text-5xl", children: title }),
386
+ description?.trim() ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "mt-3 max-w-xl text-sm leading-6 text-muted-foreground sm:text-base", children: description }) : null
387
+ ] });
388
+ }
389
+ function ErrorBanner({ message }) {
390
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "mx-auto w-full max-w-[912px] whitespace-pre-wrap rounded-md border border-destructive/30 bg-destructive/5 px-4 py-3 text-sm text-destructive", children: message });
391
+ }
392
+ function describeError(error) {
393
+ if (error instanceof Error && error.message.trim() !== "") {
394
+ return error.message;
395
+ }
396
+ return String(error);
397
+ }
398
+ function normalizeAgentAttachmentUrl(path) {
399
+ const trimmedPath = path.trim();
400
+ if (trimmedPath === "") {
401
+ return null;
402
+ }
403
+ try {
404
+ const parsed = new URL(trimmedPath);
405
+ if (parsed.protocol !== "") {
406
+ return trimmedPath;
407
+ }
408
+ } catch {
409
+ }
410
+ const roomPath = trimmedPath.startsWith("/") ? trimmedPath.slice(1) : trimmedPath;
411
+ return roomPath === "" ? null : `room:///${roomPath}`;
412
+ }
413
+ function AgentThread({
414
+ room,
415
+ path,
416
+ chatClient,
417
+ disposeChatClient = false,
418
+ agentName,
419
+ emptyStateTitle = "Chat to get started",
420
+ emptyStateDescription,
421
+ clientToolkits
422
+ }) {
423
+ const [attachments, setAttachments] = (0, import_react.useState)([]);
424
+ const [sendError, setSendError] = (0, import_react.useState)(null);
425
+ const [version, setVersion] = (0, import_react.useState)(0);
426
+ const scrollContainerRef = (0, import_react.useRef)(null);
427
+ const contentRef = (0, import_react.useRef)(null);
428
+ const stickToBottomRef = (0, import_react.useRef)(true);
429
+ const sessionRef = (0, import_react.useRef)(null);
430
+ const ownsChatClient = chatClient == null;
431
+ const activeChatClient = (0, import_react.useMemo)(
432
+ () => chatClient ?? new import_meshagent_agents.MessagingChatClient({ room, agentName }),
433
+ [agentName, chatClient, room]
434
+ );
435
+ const localParticipantName = getParticipantName(room.localParticipant);
436
+ const agentParticipant = activeChatClient.agentParticipant() ?? findAgentParticipant(room, agentName);
437
+ (0, import_react.useEffect)(() => {
438
+ void activeChatClient.start();
439
+ const handleChange = () => {
440
+ setVersion((current) => current + 1);
441
+ };
442
+ activeChatClient.addListener(handleChange);
443
+ return () => {
444
+ activeChatClient.removeListener(handleChange);
445
+ if (ownsChatClient || disposeChatClient) {
446
+ void activeChatClient.stop();
447
+ }
448
+ };
449
+ }, [activeChatClient, disposeChatClient, ownsChatClient]);
450
+ (0, import_react.useEffect)(() => {
451
+ const session2 = activeChatClient.openThread(path);
452
+ sessionRef.current = session2;
453
+ const handleChange = () => {
454
+ setVersion((current) => current + 1);
455
+ };
456
+ session2.addListener(handleChange);
457
+ handleChange();
458
+ return () => {
459
+ session2.removeListener(handleChange);
460
+ if (sessionRef.current === session2) {
461
+ sessionRef.current = null;
462
+ }
463
+ };
464
+ }, [activeChatClient, path]);
465
+ const session = sessionRef.current;
466
+ const feedItems = (0, import_react.useMemo)(() => feedFromSession(session), [session, version]);
467
+ const status = (0, import_react.useMemo)(() => latestThreadStatus(session), [session, version]);
468
+ const statusText = status?.status?.trim() || null;
469
+ const turnId = stringValue(status?.turnId);
470
+ const canInterruptActiveTurn = turnId != null && (agentParticipant != null || chatClient != null);
471
+ const lastItem = feedItems.length > 0 ? feedItems[feedItems.length - 1] : void 0;
472
+ const lastMessageKey = `${lastItem?.id ?? ""}:${lastItem?.text.length ?? 0}:${feedItems.length}:${version}`;
473
+ (0, import_react.useEffect)(() => {
474
+ const container = scrollContainerRef.current;
475
+ if (!container) {
476
+ return;
477
+ }
478
+ stickToBottomRef.current = true;
479
+ container.scrollTop = container.scrollHeight;
480
+ }, [path]);
481
+ (0, import_react.useEffect)(() => {
482
+ const container = scrollContainerRef.current;
483
+ if (!container || !stickToBottomRef.current) {
484
+ return;
485
+ }
486
+ container.scrollTop = container.scrollHeight;
487
+ }, [lastMessageKey, statusText]);
488
+ (0, import_react.useEffect)(() => {
489
+ const container = scrollContainerRef.current;
490
+ const content = contentRef.current;
491
+ if (!container || !content || typeof ResizeObserver === "undefined") {
492
+ return;
493
+ }
494
+ const observer = new ResizeObserver(() => {
495
+ if (stickToBottomRef.current) {
496
+ container.scrollTop = container.scrollHeight;
497
+ }
498
+ });
499
+ observer.observe(content);
500
+ return () => {
501
+ observer.disconnect();
502
+ };
503
+ }, []);
504
+ const selectAttachments = (0, import_react.useCallback)((files) => {
505
+ const nextAttachments = files.map((file) => new import_file_attachment.MeshagentFileUpload(
506
+ room,
507
+ `uploaded-files/${file.name}`,
508
+ (0, import_file_attachment.fileToAsyncIterable)(file),
509
+ file.size
510
+ ));
511
+ setAttachments((current) => [...current, ...nextAttachments]);
512
+ }, [room]);
513
+ const handleSend = (0, import_react.useCallback)(async (message) => {
514
+ if (message.text.trim() === "" && message.attachments.length === 0) {
515
+ return;
516
+ }
517
+ if (!agentParticipant && chatClient == null) {
518
+ setSendError("This thread requires an online agent that supports agent messages.");
519
+ return;
520
+ }
521
+ const openSession = sessionRef.current;
522
+ if (openSession === null) {
523
+ setSendError("No thread session is open.");
524
+ return;
525
+ }
526
+ const normalizedAttachments = message.attachments.map(normalizeAgentAttachmentUrl).filter((attachment) => attachment !== null);
527
+ try {
528
+ await openSession.sendText({
529
+ messageId: message.id,
530
+ text: message.text,
531
+ attachments: normalizedAttachments,
532
+ turnId,
533
+ steer: status?.mode === "steerable" && turnId != null,
534
+ senderName: localParticipantName.trim() || void 0,
535
+ clientToolkits
536
+ });
537
+ setSendError(null);
538
+ setVersion((current) => current + 1);
539
+ } catch (error) {
540
+ setSendError(describeError(error));
541
+ }
542
+ }, [agentParticipant, chatClient, clientToolkits, localParticipantName, status?.mode, turnId]);
543
+ const cancelTurn = (0, import_react.useCallback)(async () => {
544
+ const openSession = sessionRef.current;
545
+ if (openSession === null || turnId == null) {
546
+ return;
547
+ }
548
+ await openSession.interruptTurn(turnId);
549
+ }, [turnId]);
550
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex h-full min-h-0 flex-1 flex-col", children: [
551
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "relative flex h-full min-h-0 flex-1 flex-col", children: [
552
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
553
+ "div",
554
+ {
555
+ ref: scrollContainerRef,
556
+ className: "min-h-0 flex-1 overflow-y-auto overflow-x-hidden [overflow-anchor:none]",
557
+ onScroll: (event) => {
558
+ stickToBottomRef.current = isNearBottom(event.currentTarget);
559
+ },
560
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
561
+ "div",
562
+ {
563
+ ref: contentRef,
564
+ className: (0, import_utils.cn)(
565
+ "mx-auto flex min-h-full w-full max-w-[912px] flex-col gap-8 px-4 pt-6",
566
+ feedItems.length > 0 ? "justify-end" : null,
567
+ statusText ? "pb-24" : "pb-6"
568
+ ),
569
+ children: [
570
+ feedItems.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EmptyState, { title: emptyStateTitle, description: emptyStateDescription }) : null,
571
+ feedItems.map((message, index) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
572
+ ThreadMessageView,
573
+ {
574
+ room,
575
+ message,
576
+ previous: index > 0 ? feedItems[index - 1] : null,
577
+ localParticipantName,
578
+ agentName
579
+ },
580
+ message.id
581
+ ))
582
+ ]
583
+ }
584
+ )
585
+ }
586
+ ),
587
+ statusText ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "pointer-events-none absolute inset-x-0 bottom-0 flex justify-center px-4 pb-4", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "pointer-events-auto w-full max-w-[912px]", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
588
+ import_chat_typing_indicator.ChatTypingIndicator,
589
+ {
590
+ typing: false,
591
+ thinking: false,
592
+ statusText,
593
+ startedAt: dateFromString(status?.startedAt),
594
+ onCancel: canInterruptActiveTurn ? cancelTurn : void 0,
595
+ showCancelButton: status?.mode != null,
596
+ cancelEnabled: true
597
+ }
598
+ ) }) }) : null
599
+ ] }),
600
+ sendError ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "px-4 pb-2", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ErrorBanner, { message: sendError }) }) : null,
601
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
602
+ import_chat_input.ChatInput,
603
+ {
604
+ onSubmit: handleSend,
605
+ attachments,
606
+ onFilesSelected: selectAttachments,
607
+ setAttachments,
608
+ disabled: agentParticipant == null && chatClient == null,
609
+ placeholder: agentParticipant || chatClient ? "Type a message" : `Waiting for ${displayParticipantName(agentName)}`
610
+ }
611
+ )
612
+ ] });
613
+ }
@@ -1,6 +1,6 @@
1
1
  import type { ReactElement } from "react";
2
2
  import { Participant, RoomClient } from "@meshagent/meshagent";
3
- import type { BaseChatClient } from "@meshagent/meshagent-agents";
3
+ import type { BaseChatClient, ClientToolkitDescription } from "@meshagent/meshagent-agents";
4
4
  import { ChatThreadDisplayMode } from "./conversation-descriptor.js";
5
5
  export { ChatThreadDisplayMode, chatDocumentPath, resolvedThreadListPath, } from "./conversation-descriptor.js";
6
6
  export interface ChatBotViewProps {
@@ -30,5 +30,6 @@ export interface ChatBotViewProps {
30
30
  showThreadList?: boolean;
31
31
  threadListWidth?: number;
32
32
  threadListCollapsedHeight?: number;
33
+ clientToolkits?: ClientToolkitDescription[];
33
34
  }
34
- export declare function ChatBotView({ room, chatClient, disposeChatClient, path, documentPath, participants, agentName, threadDisplayMode, threadDir, threadListPath, toolkit, tool, centerComposer, emptyStateTitle, emptyStateDescription, startNewThreadTitle, startNewThreadDescription, selectedThreadPath, onSelectedThreadPathChanged, onSelectedThreadResolved, onThreadResolved, newThreadResetVersion, showThreadList, threadListWidth, threadListCollapsedHeight, }: ChatBotViewProps): ReactElement;
35
+ export declare function ChatBotView({ room, chatClient, disposeChatClient, path, documentPath, participants, agentName, threadDisplayMode, threadDir, threadListPath, toolkit, tool, centerComposer, emptyStateTitle, emptyStateDescription, startNewThreadTitle, startNewThreadDescription, selectedThreadPath, onSelectedThreadPathChanged, onSelectedThreadResolved, onThreadResolved, newThreadResetVersion, showThreadList, threadListWidth, threadListCollapsedHeight, clientToolkits, }: ChatBotViewProps): ReactElement;