@meshagent/meshagent-tailwind 0.47.1 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/cjs/chat/agent-thread.d.ts +24 -24
  3. package/dist/cjs/chat/agent-thread.js +575 -808
  4. package/dist/cjs/chat/chat-bot-view.d.ts +18 -6
  5. package/dist/cjs/chat/chat-bot-view.js +29 -7
  6. package/dist/cjs/chat/chat-feed-widget-view.d.ts +7 -0
  7. package/dist/cjs/chat/chat-feed-widget-view.js +50 -0
  8. package/dist/cjs/chat/chat-feed-widget.d.ts +16 -0
  9. package/dist/cjs/chat/chat-feed-widget.js +51 -0
  10. package/dist/cjs/chat/chat-hooks.d.ts +2 -2
  11. package/dist/cjs/chat/chat-input.d.ts +3 -3
  12. package/dist/cjs/chat/chat-input.js +9 -4
  13. package/dist/cjs/chat/chat-scroller.d.ts +21 -0
  14. package/dist/cjs/chat/chat-scroller.js +139 -0
  15. package/dist/cjs/chat/chat-thread-timeline.d.ts +66 -0
  16. package/dist/cjs/chat/chat-thread-timeline.js +595 -0
  17. package/dist/cjs/chat/dataset-agent-thread.d.ts +16 -4
  18. package/dist/cjs/chat/dataset-agent-thread.js +112 -292
  19. package/dist/cjs/chat/multi-thread-view.d.ts +8 -3
  20. package/dist/cjs/chat/multi-thread-view.js +10 -2
  21. package/dist/cjs/chat/new-chat-thread.d.ts +8 -3
  22. package/dist/cjs/chat/new-chat-thread.js +63 -24
  23. package/dist/cjs/chat/thread-view.d.ts +18 -5
  24. package/dist/cjs/chat/thread-view.js +67 -9
  25. package/dist/cjs/chat/use-chat-virtualizer.d.ts +47 -0
  26. package/dist/cjs/chat/use-chat-virtualizer.js +336 -0
  27. package/dist/cjs/chat/virtualization.d.ts +44 -0
  28. package/dist/cjs/chat/virtualization.js +143 -0
  29. package/dist/cjs/components/ui/button.d.ts +2 -2
  30. package/dist/cjs/components/ui/dialog.d.ts +1 -1
  31. package/dist/cjs/components/ui/dialog.js +11 -1
  32. package/dist/cjs/components/ui/form.d.ts +1 -1
  33. package/dist/cjs/components/ui/portal-container.d.ts +7 -0
  34. package/dist/cjs/components/ui/portal-container.js +46 -0
  35. package/dist/cjs/file-preview/file-preview.js +1 -1
  36. package/dist/cjs/index.d.ts +3 -0
  37. package/dist/cjs/index.js +4 -0
  38. package/dist/cjs/meetings/meeting-scope.d.ts +2 -1
  39. package/dist/cjs/meetings/meeting-scope.js +1 -0
  40. package/dist/cjs/react-syntax-highlighter.d.js +1 -0
  41. package/dist/esm/chat/agent-thread.d.ts +24 -24
  42. package/dist/esm/chat/agent-thread.js +574 -838
  43. package/dist/esm/chat/chat-bot-view.d.ts +18 -6
  44. package/dist/esm/chat/chat-bot-view.js +29 -7
  45. package/dist/esm/chat/chat-feed-widget-view.d.ts +7 -0
  46. package/dist/esm/chat/chat-feed-widget-view.js +30 -0
  47. package/dist/esm/chat/chat-feed-widget.d.ts +16 -0
  48. package/dist/esm/chat/chat-feed-widget.js +31 -0
  49. package/dist/esm/chat/chat-hooks.d.ts +2 -2
  50. package/dist/esm/chat/chat-input.d.ts +3 -3
  51. package/dist/esm/chat/chat-input.js +9 -4
  52. package/dist/esm/chat/chat-scroller.d.ts +21 -0
  53. package/dist/esm/chat/chat-scroller.js +122 -0
  54. package/dist/esm/chat/chat-thread-timeline.d.ts +66 -0
  55. package/dist/esm/chat/chat-thread-timeline.js +605 -0
  56. package/dist/esm/chat/dataset-agent-thread.d.ts +16 -4
  57. package/dist/esm/chat/dataset-agent-thread.js +114 -307
  58. package/dist/esm/chat/multi-thread-view.d.ts +8 -3
  59. package/dist/esm/chat/multi-thread-view.js +10 -2
  60. package/dist/esm/chat/new-chat-thread.d.ts +8 -3
  61. package/dist/esm/chat/new-chat-thread.js +64 -25
  62. package/dist/esm/chat/thread-view.d.ts +18 -5
  63. package/dist/esm/chat/thread-view.js +67 -9
  64. package/dist/esm/chat/use-chat-virtualizer.d.ts +47 -0
  65. package/dist/esm/chat/use-chat-virtualizer.js +331 -0
  66. package/dist/esm/chat/virtualization.d.ts +44 -0
  67. package/dist/esm/chat/virtualization.js +123 -0
  68. package/dist/esm/components/ui/button.d.ts +2 -2
  69. package/dist/esm/components/ui/dialog.d.ts +1 -1
  70. package/dist/esm/components/ui/dialog.js +11 -1
  71. package/dist/esm/components/ui/form.d.ts +1 -1
  72. package/dist/esm/components/ui/portal-container.d.ts +7 -0
  73. package/dist/esm/components/ui/portal-container.js +16 -0
  74. package/dist/esm/file-preview/file-preview.js +1 -1
  75. package/dist/esm/index.d.ts +3 -0
  76. package/dist/esm/index.js +4 -0
  77. package/dist/esm/meetings/meeting-scope.d.ts +2 -1
  78. package/dist/esm/meetings/meeting-scope.js +1 -0
  79. package/dist/esm/react-syntax-highlighter.d.js +0 -0
  80. package/dist/index.css +1 -1
  81. package/package.json +6 -5
@@ -1,57 +1,34 @@
1
1
  import { jsx, jsxs } from "react/jsx-runtime";
2
2
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
3
+ import { ErrorContent } from "@meshagent/meshagent";
3
4
  import {
4
- AgentFileContentDelta,
5
- AgentFileContentEnded,
6
- AgentFileContentStarted,
7
- AgentImageGenerationCompleted,
8
- AgentImageGenerationFailed,
9
- AgentImageGenerationPartial,
10
- AgentImageGenerationStarted,
11
5
  AgentClientToolCallRequested,
12
- AgentSecretRequested,
13
- AgentModelChanged,
14
- AgentReasoningContentDelta,
15
- AgentReasoningContentEnded,
16
- AgentReasoningContentStarted,
17
- AgentTextContentDelta,
18
- AgentTextContentEnded,
19
- AgentTextContentStarted,
6
+ AgentFileContent,
20
7
  AgentThreadStatus,
21
- AgentUsageUpdated,
22
- AgentToolCallArgumentsDelta,
23
8
  AgentToolCallEnded,
24
- AgentToolCallInProgress,
25
- AgentToolCallLogDelta,
26
- AgentToolCallPending,
27
- AgentToolCallStarted,
28
9
  MessagingChatClient,
29
- ToolChoice,
30
- StartThread,
31
- TurnStart,
32
- TurnStartAccepted,
33
- TurnStartRejected,
34
10
  TurnEnded,
35
- TurnInterruptAccepted,
36
- TurnInterrupted,
37
- TurnSteer,
38
- TurnSteerAccepted,
39
- TurnSteerRejected,
40
- TurnSteered,
41
11
  TurnStarted
42
12
  } from "@meshagent/meshagent-agents";
13
+ import { buildChatThreadTimeline, buildMergedChatThreadTimeline } from "./chat-thread-timeline.js";
14
+ import { AgentUsageSnapshot, shouldReplaceAgentUsageSnapshot } from "./chat-thread-timeline.js";
43
15
  import { ChevronDown, ChevronRight, Download, FileText, ImageOff, Terminal } from "lucide-react";
44
16
  import ReactMarkdown from "react-markdown";
45
17
  import rehypeHighlight from "rehype-highlight";
46
18
  import rehypeSanitize from "rehype-sanitize";
47
19
  import remarkGfm from "remark-gfm";
48
- import { Spinner } from "../components/ui/spinner";
49
- import { cn } from "../lib/utils";
50
- import { ChatInput } from "./chat-input";
51
- import { ChatTypingIndicator } from "./chat-typing-indicator";
52
- import { MeshagentFileUpload, fileToAsyncIterable } from "./file-attachment";
20
+ import { v4 as uuidV4 } from "uuid";
21
+ import { Button } from "../components/ui/button.js";
22
+ import { Spinner } from "../components/ui/spinner.js";
23
+ import { cn } from "../lib/utils.js";
24
+ import { ChatInput } from "./chat-input.js";
25
+ import { ChatMessage } from "./chat-message.js";
26
+ import { ChatScroller } from "./chat-scroller.js";
27
+ import { ChatTypingIndicator } from "./chat-typing-indicator.js";
28
+ import { MeshagentFileUpload, fileToAsyncIterable } from "./file-attachment.js";
53
29
  import { filePreviewName, isImagePath } from "../file-preview/file-preview.js";
54
- const stickyBottomThresholdPx = 24;
30
+ import { resolveClientToolkitDescriptions } from "./chat-feed-widget.js";
31
+ import { ChatFeedWidgetView } from "./chat-feed-widget-view.js";
55
32
  class AgentToolChoice {
56
33
  toolkitName;
57
34
  toolName;
@@ -63,162 +40,24 @@ class AgentToolChoice {
63
40
  return { toolkit_name: this.toolkitName, tool_name: this.toolName };
64
41
  }
65
42
  }
66
- function finiteNumber(value) {
67
- return typeof value === "number" && Number.isFinite(value) ? value : null;
68
- }
69
- function integerNumber(value) {
70
- const numeric = finiteNumber(value);
71
- return numeric == null ? null : Math.trunc(numeric);
72
- }
73
- function usageKeyMatches(key, names) {
74
- for (const name of names) {
75
- if (key === name || key.endsWith(`.${name}`)) {
76
- return true;
77
- }
78
- }
79
- return false;
43
+ function stringValue(value) {
44
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
80
45
  }
81
- function sumUsageKeys(rawUsage, names) {
82
- let total = 0;
83
- let found = false;
84
- for (const [key, value] of Object.entries(rawUsage)) {
85
- if (!usageKeyMatches(key, names)) {
86
- continue;
87
- }
88
- const numeric = finiteNumber(value);
89
- if (numeric == null) {
90
- continue;
91
- }
92
- total += numeric;
93
- found = true;
94
- }
95
- return found ? total : null;
96
- }
97
- function usageTotalTokens(rawUsage) {
98
- const explicitTotal = sumUsageKeys(rawUsage, /* @__PURE__ */ new Set(["total_tokens"]));
99
- if (explicitTotal != null) {
100
- return explicitTotal;
101
- }
102
- const inputTokens = sumUsageKeys(rawUsage, /* @__PURE__ */ new Set([
103
- "input_tokens",
104
- "audio_input_tokens",
105
- "image_input_tokens",
106
- "cache_creation_input_tokens",
107
- "cache_read_input_tokens"
108
- ]));
109
- const outputTokens = sumUsageKeys(rawUsage, /* @__PURE__ */ new Set(["output_tokens", "audio_output_tokens", "image_output_tokens"]));
110
- const cachedTokens = sumUsageKeys(rawUsage, /* @__PURE__ */ new Set(["cached_tokens", "audio_cached_tokens", "image_cached_tokens"]));
111
- const reasoningTokens = sumUsageKeys(rawUsage, /* @__PURE__ */ new Set(["reasoning_tokens"]));
112
- let total = 0;
113
- let hasTotal = false;
114
- if (inputTokens != null) {
115
- total += inputTokens;
116
- hasTotal = true;
117
- } else if (cachedTokens != null) {
118
- total += cachedTokens;
119
- hasTotal = true;
120
- }
121
- if (outputTokens != null) {
122
- total += outputTokens;
123
- hasTotal = true;
124
- } else if (reasoningTokens != null) {
125
- total += reasoningTokens;
126
- hasTotal = true;
127
- }
128
- return hasTotal ? total : null;
129
- }
130
- function usageValues(rawUsage) {
131
- const usage = {};
132
- for (const [key, value] of Object.entries(rawUsage)) {
133
- const trimmedKey = key.trim();
134
- const numeric = finiteNumber(value);
135
- if (trimmedKey === "" || numeric == null) {
136
- continue;
137
- }
138
- usage[trimmedKey] = numeric;
139
- }
140
- return Object.freeze(usage);
141
- }
142
- class AgentUsageSnapshot {
143
- threadPath;
144
- turnId;
145
- contextUsedTokens;
146
- contextTotalTokens;
147
- compactionMode;
148
- compactionThreshold;
149
- totalTokens;
150
- usage;
151
- constructor({
152
- threadPath,
153
- turnId,
154
- contextUsedTokens,
155
- contextTotalTokens,
156
- compactionMode,
157
- compactionThreshold,
158
- totalTokens,
159
- usage
160
- }) {
161
- this.threadPath = threadPath;
162
- this.turnId = turnId;
163
- this.contextUsedTokens = contextUsedTokens;
164
- this.contextTotalTokens = contextTotalTokens;
165
- this.compactionMode = compactionMode;
166
- this.compactionThreshold = compactionThreshold;
167
- this.totalTokens = totalTokens;
168
- this.usage = Object.freeze({ ...usage });
169
- }
170
- static fromMessage(message) {
171
- if (!isTypedMessage(message, AgentUsageUpdated)) {
172
- return null;
173
- }
174
- return AgentUsageSnapshot.fromPayload(message.toJson());
175
- }
176
- static fromPayload(payload) {
177
- if (payload.type !== "meshagent.agent.usage.updated") {
178
- return null;
179
- }
180
- const rawThreadPath = payload.thread_id;
181
- if (typeof rawThreadPath !== "string" || rawThreadPath.trim() === "") {
182
- return null;
183
- }
184
- const rawContextWindow = payload.context_window;
185
- if (rawContextWindow == null || typeof rawContextWindow !== "object") {
186
- return null;
187
- }
188
- const contextWindow = rawContextWindow;
189
- const usedTokens = integerNumber(contextWindow.used_tokens);
190
- if (usedTokens == null) {
191
- return null;
46
+ function mergeAgentMessageEvents(persistedEvents, liveEvents) {
47
+ const merged = [...persistedEvents];
48
+ const indexByMessageId = new Map(
49
+ merged.map((event, index) => [event.message.messageId, index])
50
+ );
51
+ for (const event of liveEvents) {
52
+ const existingIndex = indexByMessageId.get(event.message.messageId);
53
+ if (existingIndex === void 0) {
54
+ indexByMessageId.set(event.message.messageId, merged.length);
55
+ merged.push(event);
56
+ } else {
57
+ merged[existingIndex] = event;
192
58
  }
193
- const totalContextTokens = contextWindow.total_tokens == null ? void 0 : integerNumber(contextWindow.total_tokens) ?? void 0;
194
- const rawCompactionMode = contextWindow.compaction_mode;
195
- const compactionMode = typeof rawCompactionMode === "string" && rawCompactionMode.trim() !== "" ? rawCompactionMode.trim() : void 0;
196
- const compactionThreshold = contextWindow.compaction_threshold == null ? void 0 : integerNumber(contextWindow.compaction_threshold) ?? void 0;
197
- const rawUsage = payload.usage != null && typeof payload.usage === "object" ? payload.usage : {};
198
- const rawTurnId = payload.turn_id;
199
- return new AgentUsageSnapshot({
200
- threadPath: rawThreadPath.trim(),
201
- turnId: typeof rawTurnId === "string" && rawTurnId.trim() !== "" ? rawTurnId.trim() : void 0,
202
- contextUsedTokens: usedTokens,
203
- contextTotalTokens: totalContextTokens,
204
- compactionMode,
205
- compactionThreshold,
206
- totalTokens: usageTotalTokens(rawUsage) ?? void 0,
207
- usage: usageValues(rawUsage)
208
- });
209
59
  }
210
- }
211
- function shouldReplaceAgentUsageSnapshot(current, next) {
212
- if (current != null && current.contextUsedTokens > 0 && next.contextUsedTokens === 0 && Object.keys(next.usage).length === 0) {
213
- return false;
214
- }
215
- return true;
216
- }
217
- function isTypedMessage(message, ctor) {
218
- return message instanceof ctor;
219
- }
220
- function stringValue(value) {
221
- return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
60
+ return merged;
222
61
  }
223
62
  function displayParticipantName(name) {
224
63
  const normalized = name?.trim();
@@ -245,526 +84,15 @@ function findAgentParticipant(room, agentName) {
245
84
  }
246
85
  function timeAgo(date) {
247
86
  const seconds = Math.max(0, Math.floor((Date.now() - date.getTime()) / 1e3));
248
- if (seconds < 60) {
249
- return "now";
250
- }
87
+ if (seconds < 60) return "now";
251
88
  const minutes = Math.floor(seconds / 60);
252
- if (minutes < 60) {
253
- return `${minutes}m`;
254
- }
89
+ if (minutes < 60) return String(minutes) + "m";
255
90
  const hours = Math.floor(minutes / 60);
256
- if (hours < 24) {
257
- return `${hours}h`;
258
- }
259
- return `${Math.floor(hours / 24)}d`;
260
- }
261
- function distanceFromBottom(element) {
262
- return Math.max(element.scrollHeight - element.clientHeight - element.scrollTop, 0);
263
- }
264
- function isNearBottom(element) {
265
- return distanceFromBottom(element) <= stickyBottomThresholdPx;
266
- }
267
- function inputContent(message) {
268
- const textParts = [];
269
- const attachments = [];
270
- for (const item of message.content ?? []) {
271
- if (item.type === "text" && item.text.trim() !== "") {
272
- textParts.push(item.text);
273
- } else if (item.type === "file" && item.url.trim() !== "") {
274
- attachments.push(item.url);
275
- }
276
- }
277
- return { text: textParts.join("\n"), attachments };
278
- }
279
- function inputItemFromMessage(message, createdAt) {
280
- if (isTypedMessage(message, StartThread) || isTypedMessage(message, TurnStart) || isTypedMessage(message, TurnSteer)) {
281
- const content = inputContent(message);
282
- if (content.text.trim() === "" && content.attachments.length === 0) {
283
- return null;
284
- }
285
- return {
286
- id: message.messageId,
287
- kind: "message",
288
- role: "user",
289
- text: content.text,
290
- attachments: content.attachments,
291
- authorName: message.senderName,
292
- createdAt
293
- };
294
- }
295
- if (isTypedMessage(message, TurnStartAccepted) || isTypedMessage(message, TurnSteerAccepted)) {
296
- const content = inputContent(message);
297
- if (content.text.trim() === "" && content.attachments.length === 0) {
298
- return null;
299
- }
300
- return {
301
- id: message.sourceMessageId,
302
- kind: "message",
303
- role: "user",
304
- text: content.text,
305
- attachments: content.attachments,
306
- authorName: message.senderName,
307
- createdAt
308
- };
309
- }
310
- return null;
311
- }
312
- function pendingItemFromInput(pending) {
313
- const item = inputItemFromMessage(pending.payload, pending.createdAt);
314
- if (item === null) {
315
- return null;
316
- }
317
- return { ...item, id: pending.messageId };
318
- }
319
- function upsertItem(items, item) {
320
- items.set(item.id, { ...items.get(item.id), ...item });
321
- }
322
- function appendText(items, itemId, base, text) {
323
- if (text === "") {
324
- return;
325
- }
326
- const existing = items.get(itemId);
327
- upsertItem(items, {
328
- ...base,
329
- id: itemId,
330
- text: `${existing?.text ?? ""}${text}`,
331
- attachments: existing?.attachments ?? []
332
- });
333
- }
334
- function imageStatus(message) {
335
- if (isTypedMessage(message, AgentImageGenerationCompleted)) {
336
- return "completed";
337
- }
338
- if (isTypedMessage(message, AgentImageGenerationFailed)) {
339
- return "failed";
340
- }
341
- return "in_progress";
342
- }
343
- function agentErrorIsCancellation(error) {
344
- const values = [error.code, error.message].filter((value) => typeof value === "string");
345
- return values.some((value) => {
346
- const normalized = value.trim().toLowerCase();
347
- return normalized.includes("cancel") || normalized.includes("interrupt") || normalized.includes("abort");
348
- });
349
- }
350
- function toolCallLabel(message) {
351
- return [message.toolkit, message.tool].filter((part) => part?.trim()).join(".") || "Tool call";
352
- }
353
- function toolArgumentString(argumentsValue, keys) {
354
- if (argumentsValue == null) {
355
- return void 0;
356
- }
357
- for (const key of keys) {
358
- const value = argumentsValue[key];
359
- if (typeof value === "string" && value.trim() !== "") {
360
- return value.trim();
361
- }
362
- if (Array.isArray(value) && value.every((item) => typeof item === "string")) {
363
- const joined = value.join(" ").trim();
364
- if (joined !== "") {
365
- return joined;
366
- }
367
- }
368
- }
369
- return void 0;
370
- }
371
- function toolCommandText(message) {
372
- return toolArgumentString(message.arguments, ["command", "cmd", "script", "input", "query"]);
373
- }
374
- function contentText(value) {
375
- if (typeof value === "string" && value.trim() !== "") {
376
- return value.trim();
377
- }
378
- if (value == null || typeof value !== "object") {
379
- return void 0;
380
- }
381
- const obj = value;
382
- for (const key of ["text", "result", "output", "stdout", "stderr"]) {
383
- const candidate = obj[key];
384
- if (typeof candidate === "string" && candidate.trim() !== "") {
385
- return candidate.trim();
386
- }
387
- }
388
- const json = obj["json"];
389
- if (json != null) {
390
- return JSON.stringify(json, null, 2);
391
- }
392
- return void 0;
393
- }
394
- function shellOutputFields(message) {
395
- const result = message.result;
396
- const resultObject = result != null && typeof result === "object" ? result : void 0;
397
- return {
398
- result: contentText(result),
399
- stdout: resultObject == null ? void 0 : contentText(resultObject["stdout"]),
400
- stderr: message.error?.message.trim() || (resultObject == null ? void 0 : contentText(resultObject["stderr"]))
401
- };
402
- }
403
- function formatJsonValue(value) {
404
- if (value == null) {
405
- return void 0;
406
- }
407
- try {
408
- return JSON.stringify(value, null, 2);
409
- } catch {
410
- return void 0;
411
- }
412
- }
413
- function toolArgumentsText(argumentsValue) {
414
- return argumentsValue == null ? void 0 : formatJsonValue(argumentsValue);
415
- }
416
- function appendToolArgumentsDelta(existing, delta) {
417
- if (delta.trim() === "") {
418
- return existing?.argumentsText;
419
- }
420
- return `${existing?.argumentsText ?? ""}${delta}`;
421
- }
422
- function formatToolLogLine(line) {
423
- const text = line.text.trim();
424
- if (text === "") {
425
- return null;
426
- }
427
- const source = line.source.trim();
428
- return source === "" ? text : `${source}: ${text}`;
429
- }
430
- function appendToolLogs(existing, lines) {
431
- const logs = [...existing?.logs ?? []];
432
- for (const line of lines) {
433
- const formatted = formatToolLogLine(line);
434
- if (formatted !== null) {
435
- logs.push(formatted);
436
- }
437
- }
438
- return logs;
439
- }
440
- function toolCallState(message) {
441
- if (isTypedMessage(message, AgentToolCallEnded)) {
442
- return message.error == null ? "completed" : "failed";
443
- }
444
- if (isTypedMessage(message, AgentToolCallPending)) {
445
- return "queued";
446
- }
447
- return "in_progress";
448
- }
449
- function toolCallHeadline(message) {
450
- const label = toolCallLabel(message);
451
- if (toolCallFailed(message)) {
452
- return `Failed ${label}`;
453
- }
454
- if (isTypedMessage(message, AgentToolCallPending)) {
455
- return `Preparing ${label}`;
456
- }
457
- if (isTypedMessage(message, AgentToolCallEnded)) {
458
- return `Ran ${label}`;
459
- }
460
- return `Running ${label}`;
461
- }
462
- function modelChangedText(message) {
463
- const model = [message.provider, message.model].filter((part) => part.trim() !== "").join(" / ");
464
- const voice = message.voice?.trim();
465
- return voice ? `Model changed to ${model} (${voice})` : `Model changed to ${model}`;
466
- }
467
- function rejectionText(message, fallback) {
468
- const error = message.error?.message.trim();
469
- return error ? `${fallback}: ${error}` : fallback;
470
- }
471
- function lifecycleEventItem(message, createdAt) {
472
- const turnId = stringValue(message.turnId);
473
- const base = {
474
- id: ["event", message.type, turnId ?? message.sourceMessageId ?? message.messageId].join(":"),
475
- kind: "event",
476
- role: "agent",
477
- attachments: [],
478
- createdAt,
479
- turnId
480
- };
481
- if (isTypedMessage(message, TurnStartAccepted)) {
482
- return { ...base, text: "Turn accepted", state: "queued" };
483
- }
484
- if (isTypedMessage(message, TurnStarted)) {
485
- return { ...base, text: "Turn started", state: "running" };
486
- }
487
- if (isTypedMessage(message, TurnStartRejected)) {
488
- return { ...base, text: rejectionText(message, "Turn rejected"), state: "failed", failed: true };
489
- }
490
- if (isTypedMessage(message, TurnSteerAccepted)) {
491
- return { ...base, text: "Steer accepted", state: "queued" };
492
- }
493
- if (isTypedMessage(message, TurnSteered)) {
494
- return { ...base, text: "Turn steered", state: "running" };
495
- }
496
- if (isTypedMessage(message, TurnSteerRejected)) {
497
- return { ...base, text: rejectionText(message, "Steer rejected"), state: "failed", failed: true };
498
- }
499
- if (isTypedMessage(message, TurnInterruptAccepted)) {
500
- return { ...base, text: "Interrupt accepted", state: "cancelled" };
501
- }
502
- if (isTypedMessage(message, TurnInterrupted)) {
503
- return { ...base, text: "Turn interrupted", state: "cancelled" };
504
- }
505
- return null;
91
+ return hours < 24 ? String(hours) + "h" : String(Math.floor(hours / 24)) + "d";
506
92
  }
507
93
  function isShellTool(message) {
508
94
  const values = [message.toolkit, message.tool].filter((value) => typeof value === "string").map((value) => value.trim().toLowerCase());
509
- return message.command != null || values.some((value) => value === "shell" || value === "exec" || value === "local_shell" || value === "local_shell_call" || value.includes("shell") || value.includes("exec"));
510
- }
511
- function toolCallFailed(message) {
512
- return isTypedMessage(message, AgentToolCallEnded) && message.error != null;
513
- }
514
- function turnEndedErrorItem(message, createdAt) {
515
- const error = message.error;
516
- if (error == null || agentErrorIsCancellation(error)) {
517
- return null;
518
- }
519
- const text = error.message.trim();
520
- if (text === "") {
521
- return null;
522
- }
523
- const turnId = stringValue(message.turnId);
524
- return {
525
- id: ["turn-error", turnId ?? message.messageId].join(":"),
526
- kind: "error",
527
- role: "agent",
528
- text,
529
- attachments: [],
530
- createdAt,
531
- turnId
532
- };
533
- }
534
- function feedFromSession(session) {
535
- if (session === null) {
536
- return [];
537
- }
538
- const items = /* @__PURE__ */ new Map();
539
- for (const event of session.messages) {
540
- const message = event.message;
541
- const createdAt = event.createdAt;
542
- const inputItem = inputItemFromMessage(message, createdAt);
543
- if (inputItem !== null && !items.has(inputItem.id)) {
544
- upsertItem(items, inputItem);
545
- continue;
546
- }
547
- const lifecycleItem = lifecycleEventItem(message, createdAt);
548
- if (lifecycleItem !== null) {
549
- upsertItem(items, lifecycleItem);
550
- continue;
551
- }
552
- if (isTypedMessage(message, AgentModelChanged)) {
553
- upsertItem(items, {
554
- id: ["model", message.messageId].join(":"),
555
- kind: "event",
556
- role: "agent",
557
- text: modelChangedText(message),
558
- attachments: [],
559
- createdAt,
560
- state: "completed"
561
- });
562
- continue;
563
- }
564
- if (isTypedMessage(message, AgentTextContentStarted)) {
565
- upsertItem(items, {
566
- id: message.itemId,
567
- kind: "message",
568
- role: "agent",
569
- text: "",
570
- attachments: [],
571
- createdAt,
572
- phase: message.phase,
573
- turnId: message.turnId
574
- });
575
- } else if (isTypedMessage(message, AgentTextContentDelta)) {
576
- appendText(items, message.itemId, {
577
- id: message.itemId,
578
- kind: "message",
579
- role: "agent",
580
- createdAt,
581
- phase: message.phase,
582
- turnId: message.turnId
583
- }, message.text);
584
- } else if (isTypedMessage(message, AgentTextContentEnded)) {
585
- if (!items.has(message.itemId)) {
586
- upsertItem(items, {
587
- id: message.itemId,
588
- kind: "message",
589
- role: "agent",
590
- text: "",
591
- attachments: [],
592
- createdAt,
593
- phase: message.phase,
594
- turnId: message.turnId
595
- });
596
- }
597
- } else if (isTypedMessage(message, AgentReasoningContentStarted)) {
598
- upsertItem(items, {
599
- id: message.itemId,
600
- kind: "reasoning",
601
- role: "agent",
602
- text: "",
603
- attachments: [],
604
- createdAt,
605
- turnId: message.turnId
606
- });
607
- } else if (isTypedMessage(message, AgentReasoningContentDelta)) {
608
- appendText(items, message.itemId, {
609
- id: message.itemId,
610
- kind: "reasoning",
611
- role: "agent",
612
- createdAt,
613
- turnId: message.turnId
614
- }, message.text);
615
- } else if (isTypedMessage(message, AgentReasoningContentEnded)) {
616
- if (!items.has(message.itemId)) {
617
- upsertItem(items, {
618
- id: message.itemId,
619
- kind: "reasoning",
620
- role: "agent",
621
- text: "",
622
- attachments: [],
623
- createdAt,
624
- turnId: message.turnId
625
- });
626
- }
627
- } else if (isTypedMessage(message, AgentFileContentStarted) || isTypedMessage(message, AgentFileContentDelta) || isTypedMessage(message, AgentFileContentEnded)) {
628
- const existing = items.get(message.itemId);
629
- const attachments = [...existing?.attachments ?? []];
630
- if (isTypedMessage(message, AgentFileContentDelta) && !attachments.includes(message.url)) {
631
- attachments.push(message.url);
632
- }
633
- upsertItem(items, {
634
- id: message.itemId,
635
- kind: "message",
636
- role: "agent",
637
- text: existing?.text ?? "",
638
- attachments,
639
- createdAt,
640
- turnId: message.turnId,
641
- state: isTypedMessage(message, AgentFileContentEnded) ? "completed" : "in_progress"
642
- });
643
- } else if (isTypedMessage(message, AgentToolCallPending) || isTypedMessage(message, AgentToolCallInProgress) || isTypedMessage(message, AgentToolCallStarted) || isTypedMessage(message, AgentToolCallEnded)) {
644
- const existing = items.get(message.itemId);
645
- const command = toolCommandText(message) ?? existing?.command;
646
- const endedFields = isTypedMessage(message, AgentToolCallEnded) ? shellOutputFields(message) : {};
647
- const argumentsText = toolArgumentsText(message.arguments) ?? existing?.argumentsText;
648
- upsertItem(items, {
649
- id: message.itemId,
650
- kind: "tool_call",
651
- role: "agent",
652
- text: toolCallHeadline(message),
653
- attachments: [],
654
- createdAt,
655
- turnId: message.turnId,
656
- toolkit: message.toolkit ?? existing?.toolkit,
657
- tool: message.tool ?? existing?.tool,
658
- command,
659
- argumentsText,
660
- logs: existing?.logs,
661
- result: endedFields.result ?? existing?.result,
662
- stdout: endedFields.stdout ?? existing?.stdout,
663
- stderr: endedFields.stderr ?? existing?.stderr,
664
- state: toolCallState(message),
665
- failed: toolCallFailed(message)
666
- });
667
- } else if (isTypedMessage(message, AgentToolCallArgumentsDelta)) {
668
- const existing = items.get(message.itemId);
669
- upsertItem(items, {
670
- id: message.itemId,
671
- kind: "tool_call",
672
- role: "agent",
673
- text: existing?.text ?? "Running tool",
674
- attachments: [],
675
- createdAt,
676
- turnId: message.turnId,
677
- toolkit: existing?.toolkit,
678
- tool: existing?.tool,
679
- command: existing?.command,
680
- argumentsText: appendToolArgumentsDelta(existing, message.delta),
681
- logs: existing?.logs,
682
- result: existing?.result,
683
- stdout: existing?.stdout,
684
- stderr: existing?.stderr,
685
- state: existing?.state ?? "in_progress",
686
- failed: existing?.failed
687
- });
688
- } else if (isTypedMessage(message, AgentToolCallLogDelta)) {
689
- const existing = items.get(message.itemId);
690
- upsertItem(items, {
691
- id: message.itemId,
692
- kind: "tool_call",
693
- role: "agent",
694
- text: existing?.text ?? "Running tool",
695
- attachments: [],
696
- createdAt,
697
- turnId: message.turnId,
698
- toolkit: existing?.toolkit,
699
- tool: existing?.tool,
700
- command: existing?.command,
701
- argumentsText: existing?.argumentsText,
702
- logs: appendToolLogs(existing, message.lines),
703
- result: existing?.result,
704
- stdout: existing?.stdout,
705
- stderr: existing?.stderr,
706
- state: existing?.state ?? "in_progress",
707
- failed: existing?.failed
708
- });
709
- } else if (isTypedMessage(message, AgentClientToolCallRequested)) {
710
- const argumentsText = toolArgumentsText(message.arguments);
711
- upsertItem(items, {
712
- id: message.itemId,
713
- kind: "tool_call",
714
- role: "agent",
715
- text: "Waiting for client tool " + toolCallLabel(message),
716
- attachments: [],
717
- createdAt,
718
- turnId: message.turnId,
719
- toolkit: message.toolkit,
720
- tool: message.tool,
721
- argumentsText,
722
- state: "queued"
723
- });
724
- } else if (isTypedMessage(message, AgentSecretRequested)) {
725
- const scope = message.scope?.trim();
726
- upsertItem(items, {
727
- id: message.itemId,
728
- kind: "event",
729
- role: "agent",
730
- text: scope ? "Secret requested: " + message.name + " (" + scope + ")" : "Secret requested: " + message.name,
731
- attachments: [],
732
- createdAt,
733
- turnId: message.turnId,
734
- state: "queued"
735
- });
736
- } else if (isTypedMessage(message, AgentImageGenerationStarted) || isTypedMessage(message, AgentImageGenerationPartial) || isTypedMessage(message, AgentImageGenerationCompleted) || isTypedMessage(message, AgentImageGenerationFailed)) {
737
- const images = isTypedMessage(message, AgentImageGenerationCompleted) ? message.images : [];
738
- const image = isTypedMessage(message, AgentImageGenerationPartial) ? message.image : images[0];
739
- upsertItem(items, {
740
- id: message.itemId,
741
- kind: "image_generation",
742
- role: "agent",
743
- text: "",
744
- attachments: [],
745
- createdAt,
746
- turnId: message.turnId,
747
- image: {
748
- uri: image?.uri,
749
- status: image?.status ?? imageStatus(message),
750
- statusDetail: isTypedMessage(message, AgentImageGenerationFailed) ? message.error.message : void 0,
751
- images
752
- }
753
- });
754
- } else if (isTypedMessage(message, TurnEnded)) {
755
- const errorItem = turnEndedErrorItem(message, createdAt);
756
- if (errorItem !== null) {
757
- upsertItem(items, errorItem);
758
- }
759
- }
760
- }
761
- for (const pending of session.pendingInputs) {
762
- const item = pendingItemFromInput(pending);
763
- if (item !== null && !items.has(item.id)) {
764
- upsertItem(items, item);
765
- }
766
- }
767
- return [...items.values()].filter((item) => item.text.trim() !== "" || item.attachments.length > 0 || item.image != null || item.kind === "tool_call" || item.kind === "event" || item.kind === "error");
95
+ return values.some((value) => value === "shell" || value === "exec" || value === "local_shell" || value === "local_shell_call" || value.includes("shell") || value.includes("exec"));
768
96
  }
769
97
  function firstNonEmptyLine(text) {
770
98
  for (const line of text.split(/\r?\n/)) {
@@ -794,8 +122,52 @@ function canRenderAsFinalAnswer(message) {
794
122
  }
795
123
  return message.text.trim() !== "" || message.attachments.length > 0 || message.image != null;
796
124
  }
797
- function isIntrinsicDetail(message) {
798
- return message.kind === "reasoning" || message.kind === "event" || message.kind === "tool_call" && message.failed !== true || canCollapseAsCommentary(message) && message.phase === "commentary";
125
+ function isChatFeedWidgetCall(message, chatFeedWidgetsByName) {
126
+ return message.kind === "tool_call" && message.toolkit === "client" && message.tool != null && chatFeedWidgetsByName.has(message.tool);
127
+ }
128
+ function isFollowUpSuggestionCall(message, chatFeedWidgetsByName) {
129
+ if (!isChatFeedWidgetCall(message, chatFeedWidgetsByName) || message.tool == null) {
130
+ return false;
131
+ }
132
+ return chatFeedWidgetsByName.get(message.tool)?.getFollowUpSuggestions != null;
133
+ }
134
+ function latestTurnFollowUpSuggestions(messages, chatFeedWidgetsByName) {
135
+ let latestUserIndex = -1;
136
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
137
+ const message = messages[index];
138
+ if (message.kind === "message" && message.role === "user") {
139
+ latestUserIndex = index;
140
+ break;
141
+ }
142
+ }
143
+ if (latestUserIndex === -1) {
144
+ return null;
145
+ }
146
+ const latestTurnMessages = messages.slice(latestUserIndex + 1);
147
+ if (!latestTurnMessages.some(canRenderAsFinalAnswer)) {
148
+ return [];
149
+ }
150
+ for (let index = latestTurnMessages.length - 1; index >= 0; index -= 1) {
151
+ const message = latestTurnMessages[index];
152
+ if (message.kind !== "tool_call" || message.state !== "completed" || message.tool == null || !isFollowUpSuggestionCall(message, chatFeedWidgetsByName)) {
153
+ continue;
154
+ }
155
+ const widget = chatFeedWidgetsByName.get(message.tool);
156
+ try {
157
+ return widget?.getFollowUpSuggestions?.({
158
+ status: "completed",
159
+ input: message.input ?? {},
160
+ output: message.output
161
+ }) ?? [];
162
+ } catch (error) {
163
+ console.error("ChatFeedWidget follow-up suggestion extraction failed", error);
164
+ return [];
165
+ }
166
+ }
167
+ return [];
168
+ }
169
+ function isIntrinsicDetail(message, chatFeedWidgetsByName) {
170
+ return message.kind === "reasoning" || message.kind === "event" || message.kind === "tool_call" && message.failed !== true && !isChatFeedWidgetCall(message, chatFeedWidgetsByName) || canCollapseAsCommentary(message) && message.phase === "commentary";
799
171
  }
800
172
  function nextUserMessageIndex(messages, start) {
801
173
  for (let index = start; index < messages.length; index += 1) {
@@ -825,11 +197,11 @@ function finalAgentMessageIndexForSegment(messages, start, end) {
825
197
  }
826
198
  return inferredFinalIndex;
827
199
  }
828
- function addDetailIndexesForSegment(messages, start, end, detailIndexes) {
200
+ function addDetailIndexesForSegment(messages, start, end, detailIndexes, chatFeedWidgetsByName) {
829
201
  const finalAgentMessageIndex = finalAgentMessageIndexForSegment(messages, start, end);
830
202
  for (let index = start; index < end; index += 1) {
831
203
  const message = messages[index];
832
- if (isIntrinsicDetail(message)) {
204
+ if (isIntrinsicDetail(message, chatFeedWidgetsByName)) {
833
205
  detailIndexes.add(index);
834
206
  continue;
835
207
  }
@@ -898,13 +270,13 @@ function detailGroupForMessages(messages, nextMessage, expandedIds, localPartici
898
270
  expanded: expandedIds.has(id)
899
271
  };
900
272
  }
901
- function threadFeedItems(messages, expandedIds, localParticipantName, agentName) {
273
+ function groupThreadItems(messages, expandedIds, localParticipantName, agentName, chatFeedWidgetsByName) {
902
274
  const items = [];
903
275
  let index = 0;
904
276
  while (index < messages.length) {
905
277
  const segmentEnd = nextUserMessageIndex(messages, index + 1) ?? messages.length;
906
278
  const detailIndexes = /* @__PURE__ */ new Set();
907
- addDetailIndexesForSegment(messages, index, segmentEnd, detailIndexes);
279
+ addDetailIndexesForSegment(messages, index, segmentEnd, detailIndexes, chatFeedWidgetsByName);
908
280
  const groupedMessages = [...detailIndexes].sort((left, right) => left - right).map((detailIndex) => messages[detailIndex]);
909
281
  let insertedDetailGroup = false;
910
282
  for (let segmentIndex = index; segmentIndex < segmentEnd; segmentIndex += 1) {
@@ -928,7 +300,7 @@ function threadFeedItems(messages, expandedIds, localParticipantName, agentName)
928
300
  }
929
301
  return items;
930
302
  }
931
- function previousMessageFeedItem(items, index) {
303
+ function previousMessageItem(items, index) {
932
304
  for (let cursor = index - 1; cursor >= 0; cursor -= 1) {
933
305
  const item = items[cursor];
934
306
  if (item.kind !== "detail_group") {
@@ -937,32 +309,6 @@ function previousMessageFeedItem(items, index) {
937
309
  }
938
310
  return null;
939
311
  }
940
- function latestThreadStatus(session) {
941
- if (session === null) {
942
- return null;
943
- }
944
- const status = session.threadStatus;
945
- if (status !== void 0 && isTypedMessage(status, AgentThreadStatus)) {
946
- return status;
947
- }
948
- return null;
949
- }
950
- function latestUsageSnapshot(session) {
951
- if (session === null) {
952
- return null;
953
- }
954
- let usage = null;
955
- for (const event of session.messages) {
956
- const next = AgentUsageSnapshot.fromMessage(event.message);
957
- if (next === null) {
958
- continue;
959
- }
960
- if (shouldReplaceAgentUsageSnapshot(usage, next)) {
961
- usage = next;
962
- }
963
- }
964
- return usage;
965
- }
966
312
  function formatAgentUsageTokenCount(value) {
967
313
  const magnitude = Math.abs(value);
968
314
  if (magnitude >= 1e6) {
@@ -1289,7 +635,8 @@ function ExpandedDetailGroup({
1289
635
  room,
1290
636
  item,
1291
637
  localParticipantName,
1292
- agentName
638
+ agentName,
639
+ chatFeedWidgetsByName
1293
640
  }) {
1294
641
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3", children: [
1295
642
  /* @__PURE__ */ jsx("div", { className: "flex w-full justify-start", children: /* @__PURE__ */ jsx("div", { className: "max-w-[85%] px-1 text-left sm:max-w-2xl", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground", children: [
@@ -1304,6 +651,7 @@ function ExpandedDetailGroup({
1304
651
  previous: index > 0 ? item.messages[index - 1] : null,
1305
652
  localParticipantName,
1306
653
  agentName,
654
+ chatFeedWidgetsByName,
1307
655
  forceHideHeader: true
1308
656
  },
1309
657
  message.id
@@ -1348,6 +696,7 @@ function ThreadMessageView({
1348
696
  previous,
1349
697
  localParticipantName,
1350
698
  agentName,
699
+ chatFeedWidgetsByName,
1351
700
  forceHideHeader = false
1352
701
  }) {
1353
702
  if (message.kind === "error") {
@@ -1375,6 +724,23 @@ function ThreadMessageView({
1375
724
  }
1376
725
  );
1377
726
  }
727
+ const widget = message.toolkit === "client" && message.tool != null ? chatFeedWidgetsByName.get(message.tool) : void 0;
728
+ if (widget != null) {
729
+ const status = message.failed === true || message.state === "failed" ? "failed" : message.state === "completed" ? "completed" : message.state === "in_progress" ? "in_progress" : "queued";
730
+ return /* @__PURE__ */ jsx(
731
+ ChatFeedWidgetView,
732
+ {
733
+ widget,
734
+ toolCall: {
735
+ status,
736
+ input: message.input ?? {},
737
+ output: message.output
738
+ },
739
+ fallback: /* @__PURE__ */ jsx(ToolCallLine, { message })
740
+ },
741
+ [message.id, status].join(":")
742
+ );
743
+ }
1378
744
  return /* @__PURE__ */ jsx(ToolCallLine, { message });
1379
745
  }
1380
746
  const mine = message.role === "user";
@@ -1400,8 +766,14 @@ function EmptyState({ title, description }) {
1400
766
  function LoadingState() {
1401
767
  return /* @__PURE__ */ jsx("div", { className: "h-full mx-auto flex max-w-2xl flex-col items-center justify-center px-6 py-20 text-muted-foreground", children: /* @__PURE__ */ jsx(Spinner, { size: "lg" }) });
1402
768
  }
1403
- function ErrorBanner({ message }) {
1404
- return /* @__PURE__ */ 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 });
769
+ function ErrorBanner({
770
+ message,
771
+ onRetry
772
+ }) {
773
+ return /* @__PURE__ */ jsxs("div", { className: "mx-auto flex w-full max-w-[912px] items-center justify-between gap-3 whitespace-pre-wrap rounded-md border border-destructive/30 bg-destructive/5 px-4 py-3 text-sm text-destructive", children: [
774
+ /* @__PURE__ */ jsx("span", { children: message }),
775
+ onRetry ? /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", size: "sm", onClick: onRetry, children: "Retry restore" }) : null
776
+ ] });
1405
777
  }
1406
778
  function describeError(error) {
1407
779
  if (error instanceof Error && error.message.trim() !== "") {
@@ -1409,6 +781,11 @@ function describeError(error) {
1409
781
  }
1410
782
  return String(error);
1411
783
  }
784
+ function hasAgentParticipantWaiter(chatClient) {
785
+ return "waitForAgentParticipant" in chatClient && typeof chatClient.waitForAgentParticipant === "function";
786
+ }
787
+ const persistedEventsParticipantWaitTimeoutMs = 3e4;
788
+ const threadLoadTimeoutMs = 3e4;
1412
789
  function normalizeAgentAttachmentUrl(path) {
1413
790
  const trimmedPath = path.trim();
1414
791
  if (trimmedPath === "") {
@@ -1424,6 +801,100 @@ function normalizeAgentAttachmentUrl(path) {
1424
801
  const roomPath = trimmedPath.startsWith("/") ? trimmedPath.slice(1) : trimmedPath;
1425
802
  return roomPath === "" ? null : `room:///${roomPath}`;
1426
803
  }
804
+ const handledChatFeedWidgetRequests = /* @__PURE__ */ new WeakMap();
805
+ const initializedChatFeedWidgetSessions = /* @__PURE__ */ new WeakSet();
806
+ const replayingChatFeedWidgetSessions = /* @__PURE__ */ new WeakSet();
807
+ function handledRequestsForSession(session) {
808
+ const existing = handledChatFeedWidgetRequests.get(session);
809
+ if (existing != null) {
810
+ return existing;
811
+ }
812
+ const created = /* @__PURE__ */ new Set();
813
+ handledChatFeedWidgetRequests.set(session, created);
814
+ return created;
815
+ }
816
+ function chatFeedWidgetCallKey(threadPath, itemId) {
817
+ return [threadPath, itemId].join("\0");
818
+ }
819
+ function processChatFeedWidgetRequests({
820
+ session,
821
+ widgetsByName,
822
+ updateCall,
823
+ executeRequests
824
+ }) {
825
+ if (widgetsByName.size === 0) {
826
+ return;
827
+ }
828
+ const requests = session.messages.map((event) => event.message).filter((message) => message instanceof AgentClientToolCallRequested).filter((message) => message.toolkit === "client" && widgetsByName.has(message.tool));
829
+ const handledRequests = handledRequestsForSession(session);
830
+ if (!initializedChatFeedWidgetSessions.has(session)) {
831
+ initializedChatFeedWidgetSessions.add(session);
832
+ if (session.isLoading || session.loadState.requestMessageId != null) {
833
+ replayingChatFeedWidgetSessions.add(session);
834
+ }
835
+ }
836
+ if (!executeRequests) {
837
+ return;
838
+ }
839
+ if (replayingChatFeedWidgetSessions.has(session)) {
840
+ if (session.isLoading) {
841
+ return;
842
+ }
843
+ replayingChatFeedWidgetSessions.delete(session);
844
+ const completedItemIds = new Set(session.messages.map((event) => event.message).filter((message) => message instanceof AgentToolCallEnded && message.toolkit === "client").map((message) => message.itemId));
845
+ for (const request of requests) {
846
+ if (completedItemIds.has(request.requestId)) {
847
+ handledRequests.add(request.requestId);
848
+ }
849
+ }
850
+ }
851
+ for (const request of requests) {
852
+ if (handledRequests.has(request.requestId)) {
853
+ continue;
854
+ }
855
+ const widget = widgetsByName.get(request.tool);
856
+ if (widget == null) {
857
+ continue;
858
+ }
859
+ if (!session.claimClientToolCall(request.requestId)) {
860
+ handledRequests.add(request.requestId);
861
+ continue;
862
+ }
863
+ handledRequests.add(request.requestId);
864
+ updateCall(chatFeedWidgetCallKey(session.threadPath, request.requestId), {
865
+ status: "in_progress"
866
+ });
867
+ void (async () => {
868
+ let response;
869
+ let status;
870
+ try {
871
+ response = await widget.execute(request.arguments);
872
+ status = response instanceof ErrorContent ? "failed" : "completed";
873
+ } catch (error) {
874
+ response = new ErrorContent({ text: describeError(error) });
875
+ status = "failed";
876
+ }
877
+ updateCall(chatFeedWidgetCallKey(session.threadPath, request.requestId), {
878
+ status,
879
+ output: response
880
+ });
881
+ try {
882
+ await session.respondToClientToolCall({
883
+ turnId: request.turnId,
884
+ requestId: request.requestId,
885
+ response
886
+ });
887
+ session.finishClientToolCall(request.requestId, { responseSent: true });
888
+ } catch (error) {
889
+ session.finishClientToolCall(request.requestId, { responseSent: false });
890
+ updateCall(chatFeedWidgetCallKey(session.threadPath, request.requestId), {
891
+ status: "failed",
892
+ output: new ErrorContent({ text: describeError(error) })
893
+ });
894
+ }
895
+ })();
896
+ }
897
+ }
1427
898
  function AgentThread({
1428
899
  room,
1429
900
  path,
@@ -1433,24 +904,65 @@ function AgentThread({
1433
904
  emptyStateTitle = "Chat to get started",
1434
905
  emptyStateDescription,
1435
906
  clientToolkits,
1436
- toolChoice,
1437
- collapseMessages = true
907
+ chatFeedWidgets,
908
+ collapseMessages = true,
909
+ suggestions,
910
+ enableFileUpload = false,
911
+ persistedEvents,
912
+ deferLiveEvents = false,
913
+ loadThread = true,
914
+ injectPersistedEvents = false,
915
+ composerDisabled: composerDisabledProp = false,
916
+ closeThreadOnUnmount = false,
917
+ onPersistedEventsInjectionStarted,
918
+ onPersistedEventsInjected,
919
+ onEventsChanged
1438
920
  }) {
1439
921
  const [attachments, setAttachments] = useState([]);
1440
922
  const [sendError, setSendError] = useState(null);
923
+ const [restorationError, setRestorationError] = useState(null);
924
+ const [restorationAttempt, setRestorationAttempt] = useState(0);
1441
925
  const [version, setVersion] = useState(0);
1442
926
  const [expandedDetailGroupIds, setExpandedDetailGroupIds] = useState(() => /* @__PURE__ */ new Set());
1443
- const scrollContainerRef = useRef(null);
1444
- const contentRef = useRef(null);
1445
- const stickToBottomRef = useRef(true);
927
+ const [chatFeedWidgetCallOverrides, setChatFeedWidgetCallOverrides] = useState(() => /* @__PURE__ */ new Map());
1446
928
  const sessionRef = useRef(null);
929
+ const mountedRef = useRef(true);
930
+ const persistedEventsRef = useRef(persistedEvents);
931
+ persistedEventsRef.current = persistedEvents;
932
+ const restoredPathRef = useRef(null);
933
+ const restorationReadyRef = useRef(!injectPersistedEvents);
934
+ const pendingCloseRef = useRef(null);
1447
935
  const ownsChatClient = chatClient == null;
1448
936
  const activeChatClient = useMemo(
1449
937
  () => chatClient ?? new MessagingChatClient({ room, agentName }),
1450
938
  [agentName, chatClient, room]
1451
939
  );
940
+ const resolvedClientToolkits = useMemo(
941
+ () => resolveClientToolkitDescriptions(clientToolkits, chatFeedWidgets),
942
+ [chatFeedWidgets, clientToolkits]
943
+ );
944
+ const chatFeedWidgetsByName = useMemo(
945
+ () => new Map((chatFeedWidgets ?? []).map((widget) => [widget.name, widget])),
946
+ [chatFeedWidgets]
947
+ );
948
+ const updateChatFeedWidgetCall = useCallback((callKey, override) => {
949
+ if (!mountedRef.current) {
950
+ return;
951
+ }
952
+ setChatFeedWidgetCallOverrides((current) => {
953
+ const next = new Map(current);
954
+ next.set(callKey, override);
955
+ return next;
956
+ });
957
+ }, []);
1452
958
  const localParticipantName = getParticipantName(room.localParticipant);
1453
959
  const agentParticipant = activeChatClient.agentParticipant() ?? findAgentParticipant(room, agentName);
960
+ useEffect(() => {
961
+ mountedRef.current = true;
962
+ return () => {
963
+ mountedRef.current = false;
964
+ };
965
+ }, []);
1454
966
  useEffect(() => {
1455
967
  void activeChatClient.start();
1456
968
  const handleChange = () => {
@@ -1465,63 +977,262 @@ function AgentThread({
1465
977
  };
1466
978
  }, [activeChatClient, disposeChatClient, ownsChatClient]);
1467
979
  useEffect(() => {
1468
- const session2 = activeChatClient.openThread(path);
980
+ restorationReadyRef.current = !loadThread && (!injectPersistedEvents || restoredPathRef.current === path);
981
+ const session2 = activeChatClient.openThread(path, {
982
+ load: loadThread,
983
+ reloadIfOpen: loadThread && restorationAttempt > 0
984
+ });
985
+ if (pendingCloseRef.current?.session === session2) {
986
+ clearTimeout(pendingCloseRef.current.timer);
987
+ pendingCloseRef.current = null;
988
+ }
1469
989
  sessionRef.current = session2;
990
+ let threadLoadTimeout = null;
991
+ let loadParticipantAbortController = null;
992
+ const clearThreadLoadTimeout = () => {
993
+ if (threadLoadTimeout != null) {
994
+ clearTimeout(threadLoadTimeout);
995
+ threadLoadTimeout = null;
996
+ }
997
+ };
998
+ const synchronizeThreadLoadState = () => {
999
+ if (!loadThread) {
1000
+ return;
1001
+ }
1002
+ if (session2.isLoading) {
1003
+ restorationReadyRef.current = false;
1004
+ if (activeChatClient.agentParticipant() == null && hasAgentParticipantWaiter(activeChatClient)) {
1005
+ clearThreadLoadTimeout();
1006
+ return;
1007
+ }
1008
+ if (threadLoadTimeout == null) {
1009
+ threadLoadTimeout = setTimeout(() => {
1010
+ threadLoadTimeout = null;
1011
+ if (sessionRef.current !== session2 || !session2.isLoading) {
1012
+ return;
1013
+ }
1014
+ restorationReadyRef.current = false;
1015
+ setRestorationError("Unable to restore conversation context: the server thread did not finish loading within 30 seconds.");
1016
+ setVersion((current) => current + 1);
1017
+ }, threadLoadTimeoutMs);
1018
+ }
1019
+ return;
1020
+ }
1021
+ clearThreadLoadTimeout();
1022
+ const loadError = session2.loadState.error;
1023
+ if (loadError != null) {
1024
+ restorationReadyRef.current = false;
1025
+ if (activeChatClient.agentParticipant() == null && hasAgentParticipantWaiter(activeChatClient)) {
1026
+ setRestorationError(null);
1027
+ return;
1028
+ }
1029
+ setRestorationError(`Unable to restore conversation context: ${loadError}`);
1030
+ return;
1031
+ }
1032
+ restorationReadyRef.current = !injectPersistedEvents || restoredPathRef.current === path;
1033
+ setRestorationError(null);
1034
+ };
1470
1035
  const handleChange = () => {
1036
+ synchronizeThreadLoadState();
1037
+ processChatFeedWidgetRequests({
1038
+ session: session2,
1039
+ widgetsByName: chatFeedWidgetsByName,
1040
+ updateCall: updateChatFeedWidgetCall,
1041
+ executeRequests: !deferLiveEvents && restorationReadyRef.current
1042
+ });
1043
+ const latestMessage = session2.messages[session2.messages.length - 1]?.message;
1044
+ onEventsChanged?.(
1045
+ session2.threadPath,
1046
+ mergeAgentMessageEvents(persistedEventsRef.current ?? [], session2.messages),
1047
+ latestMessage ?? null
1048
+ );
1471
1049
  setVersion((current) => current + 1);
1472
1050
  };
1473
1051
  session2.addListener(handleChange);
1474
1052
  handleChange();
1053
+ if (loadThread && activeChatClient.agentParticipant() == null && hasAgentParticipantWaiter(activeChatClient)) {
1054
+ loadParticipantAbortController = new AbortController();
1055
+ const { signal } = loadParticipantAbortController;
1056
+ void (async () => {
1057
+ try {
1058
+ await activeChatClient.waitForAgentParticipant({
1059
+ waitKey: `thread-load:${path}:${restorationAttempt}:${uuidV4()}`,
1060
+ signal,
1061
+ timeoutMs: persistedEventsParticipantWaitTimeoutMs
1062
+ });
1063
+ if (signal.aborted || sessionRef.current !== session2) {
1064
+ return;
1065
+ }
1066
+ if (session2.loadState.error != null) {
1067
+ setRestorationError(null);
1068
+ activeChatClient.openThread(path, {
1069
+ load: true,
1070
+ reloadIfOpen: true
1071
+ });
1072
+ }
1073
+ handleChange();
1074
+ } catch (error) {
1075
+ if (signal.aborted || sessionRef.current !== session2) {
1076
+ return;
1077
+ }
1078
+ restorationReadyRef.current = false;
1079
+ setRestorationError(`Unable to restore conversation context: ${describeError(error)}`);
1080
+ setVersion((current) => current + 1);
1081
+ }
1082
+ })();
1083
+ }
1084
+ let restorationAbortController = null;
1085
+ const eventsToInject = persistedEventsRef.current;
1086
+ if (injectPersistedEvents && eventsToInject != null && restoredPathRef.current !== path) {
1087
+ restorationAbortController = new AbortController();
1088
+ const { signal } = restorationAbortController;
1089
+ setRestorationError(null);
1090
+ onPersistedEventsInjectionStarted?.();
1091
+ void (async () => {
1092
+ try {
1093
+ await Promise.resolve();
1094
+ if (signal.aborted || sessionRef.current !== session2) {
1095
+ return;
1096
+ }
1097
+ if (activeChatClient.agentParticipant() == null && hasAgentParticipantWaiter(activeChatClient)) {
1098
+ await activeChatClient.waitForAgentParticipant({
1099
+ waitKey: `persisted-events:${path}:${restorationAttempt}:${uuidV4()}`,
1100
+ signal,
1101
+ timeoutMs: persistedEventsParticipantWaitTimeoutMs
1102
+ });
1103
+ }
1104
+ if (signal.aborted || sessionRef.current !== session2) {
1105
+ return;
1106
+ }
1107
+ await session2.injectMessages(eventsToInject.map((event) => event.message));
1108
+ if (signal.aborted || sessionRef.current !== session2) {
1109
+ return;
1110
+ }
1111
+ restoredPathRef.current = path;
1112
+ restorationReadyRef.current = true;
1113
+ setRestorationError(null);
1114
+ onPersistedEventsInjected?.(null);
1115
+ handleChange();
1116
+ } catch (error) {
1117
+ if (signal.aborted || sessionRef.current !== session2) {
1118
+ return;
1119
+ }
1120
+ if (restoredPathRef.current === path) {
1121
+ restoredPathRef.current = null;
1122
+ }
1123
+ restorationReadyRef.current = false;
1124
+ setRestorationError(`Unable to restore conversation context: ${describeError(error)}`);
1125
+ onPersistedEventsInjected?.(error);
1126
+ setVersion((current) => current + 1);
1127
+ }
1128
+ })();
1129
+ } else if (!injectPersistedEvents && !loadThread) {
1130
+ setRestorationError(null);
1131
+ }
1475
1132
  return () => {
1133
+ clearThreadLoadTimeout();
1134
+ loadParticipantAbortController?.abort();
1135
+ restorationAbortController?.abort();
1476
1136
  session2.removeListener(handleChange);
1477
1137
  if (sessionRef.current === session2) {
1478
1138
  sessionRef.current = null;
1479
1139
  }
1140
+ if (closeThreadOnUnmount) {
1141
+ const timer = setTimeout(() => {
1142
+ if (pendingCloseRef.current?.timer === timer) {
1143
+ pendingCloseRef.current = null;
1144
+ }
1145
+ if (sessionRef.current !== session2) {
1146
+ void session2.close();
1147
+ }
1148
+ }, 0);
1149
+ pendingCloseRef.current = { session: session2, timer };
1150
+ }
1480
1151
  };
1481
- }, [activeChatClient, path]);
1152
+ }, [
1153
+ activeChatClient,
1154
+ chatFeedWidgetsByName,
1155
+ closeThreadOnUnmount,
1156
+ deferLiveEvents,
1157
+ injectPersistedEvents,
1158
+ loadThread,
1159
+ onEventsChanged,
1160
+ onPersistedEventsInjectionStarted,
1161
+ onPersistedEventsInjected,
1162
+ path,
1163
+ restorationAttempt,
1164
+ updateChatFeedWidgetCall
1165
+ ]);
1166
+ const retryRestoration = useCallback(() => {
1167
+ restoredPathRef.current = null;
1168
+ restorationReadyRef.current = false;
1169
+ setRestorationError(null);
1170
+ setRestorationAttempt((current) => current + 1);
1171
+ }, []);
1482
1172
  const normalizedPath = path.trim();
1483
1173
  const session = sessionRef.current?.threadPath === normalizedPath ? sessionRef.current : null;
1484
- const feedItems = useMemo(() => feedFromSession(session), [session, version]);
1485
- const showThreadLoading = (session === null || session.isLoading) && feedItems.length === 0;
1486
- const renderedFeedItems = useMemo(() => collapseMessages ? threadFeedItems(feedItems, expandedDetailGroupIds, localParticipantName, agentName) : feedItems, [agentName, collapseMessages, expandedDetailGroupIds, feedItems, localParticipantName]);
1487
- const status = useMemo(() => latestThreadStatus(session), [session, version]);
1488
- const usage = useMemo(() => latestUsageSnapshot(session), [session, version]);
1489
- const statusText = status?.status?.trim() || null;
1490
- const turnId = stringValue(status?.turnId);
1491
- const canInterruptActiveTurn = turnId != null && (agentParticipant != null || chatClient != null);
1492
- const lastItem = feedItems.length > 0 ? feedItems[feedItems.length - 1] : void 0;
1493
- const lastMessageKey = `${lastItem?.id ?? ""}:${lastItem?.text.length ?? 0}:${feedItems.length}:${version}`;
1494
- useEffect(() => {
1495
- const container = scrollContainerRef.current;
1496
- if (!container) {
1497
- return;
1174
+ const timeline = useMemo(() => {
1175
+ if (session == null) {
1176
+ return null;
1498
1177
  }
1499
- stickToBottomRef.current = true;
1500
- container.scrollTop = container.scrollHeight;
1501
- }, [path]);
1502
- useEffect(() => {
1503
- const container = scrollContainerRef.current;
1504
- if (!container || !stickToBottomRef.current) {
1505
- return;
1178
+ if (deferLiveEvents) {
1179
+ return buildChatThreadTimeline(persistedEvents ?? []);
1506
1180
  }
1507
- container.scrollTop = container.scrollHeight;
1508
- }, [lastMessageKey, statusText]);
1509
- useEffect(() => {
1510
- const container = scrollContainerRef.current;
1511
- const content = contentRef.current;
1512
- if (!container || !content || typeof ResizeObserver === "undefined") {
1513
- return;
1181
+ return persistedEvents == null ? buildChatThreadTimeline(session.messages, session.pendingInputs) : buildMergedChatThreadTimeline(persistedEvents, session.messages, session.pendingInputs);
1182
+ }, [deferLiveEvents, persistedEvents, session, version]);
1183
+ const timelineItems = useMemo(() => (timeline?.items ?? []).map((item) => {
1184
+ const override = session == null ? void 0 : chatFeedWidgetCallOverrides.get(chatFeedWidgetCallKey(session.threadPath, item.id));
1185
+ if (override == null || item.kind !== "tool_call" || (item.state === "completed" || item.state === "failed")) {
1186
+ return item;
1514
1187
  }
1515
- const observer = new ResizeObserver(() => {
1516
- if (stickToBottomRef.current) {
1517
- container.scrollTop = container.scrollHeight;
1188
+ return {
1189
+ ...item,
1190
+ state: override.status,
1191
+ failed: override.status === "failed",
1192
+ output: override.output ?? item.output
1193
+ };
1194
+ }), [chatFeedWidgetCallOverrides, session, timeline]);
1195
+ const showThreadLoading = (deferLiveEvents || session === null || session.isLoading) && timelineItems.length === 0;
1196
+ const followUpSuggestions = useMemo(
1197
+ () => latestTurnFollowUpSuggestions(timelineItems, chatFeedWidgetsByName),
1198
+ [chatFeedWidgetsByName, timelineItems]
1199
+ );
1200
+ const feedTimelineItems = useMemo(
1201
+ () => timelineItems.filter((item) => !isFollowUpSuggestionCall(item, chatFeedWidgetsByName)),
1202
+ [chatFeedWidgetsByName, timelineItems]
1203
+ );
1204
+ const renderedItems = useMemo(() => collapseMessages ? groupThreadItems(feedTimelineItems, expandedDetailGroupIds, localParticipantName, agentName, chatFeedWidgetsByName) : feedTimelineItems, [agentName, chatFeedWidgetsByName, collapseMessages, expandedDetailGroupIds, feedTimelineItems, localParticipantName]);
1205
+ const status = useMemo(() => {
1206
+ if (session == null) return null;
1207
+ let current = null;
1208
+ for (const event of session.messages) {
1209
+ const message = event.message;
1210
+ if (message instanceof AgentThreadStatus) {
1211
+ current = stringValue(message.status) == null ? null : message;
1212
+ continue;
1213
+ }
1214
+ if (message instanceof TurnStarted || message instanceof TurnEnded) {
1215
+ const statusTurnId = stringValue(current?.turnId);
1216
+ const messageTurnId = stringValue(message.turnId);
1217
+ if (statusTurnId == null || statusTurnId === messageTurnId) current = null;
1518
1218
  }
1219
+ }
1220
+ return current;
1221
+ }, [session, version]);
1222
+ const usage = timeline?.usage ?? null;
1223
+ const statusText = status?.status?.trim() || null;
1224
+ const turnId = stringValue(status?.turnId);
1225
+ const canInterruptActiveTurn = turnId != null && (agentParticipant != null || chatClient != null);
1226
+ const renderedItemsNewestFirst = useMemo(() => [...renderedItems].reverse(), [renderedItems]);
1227
+ const firstRenderedItemId = renderedItems[0]?.id;
1228
+ const lastRenderedItemId = renderedItems[renderedItems.length - 1]?.id;
1229
+ const previousItemById = useMemo(() => {
1230
+ const previousById = /* @__PURE__ */ new Map();
1231
+ renderedItems.forEach((item, index) => {
1232
+ previousById.set(item.id, previousMessageItem(renderedItems, index));
1519
1233
  });
1520
- observer.observe(content);
1521
- return () => {
1522
- observer.disconnect();
1523
- };
1524
- }, []);
1234
+ return previousById;
1235
+ }, [renderedItems]);
1525
1236
  const selectAttachments = useCallback((files) => {
1526
1237
  const nextAttachments = files.map((file) => new MeshagentFileUpload(
1527
1238
  room,
@@ -1549,19 +1260,33 @@ function AgentThread({
1549
1260
  await openSession.sendText({
1550
1261
  messageId: message.id,
1551
1262
  text: message.text,
1552
- attachments: normalizedAttachments,
1263
+ attachments: normalizedAttachments.map((url) => new AgentFileContent({ url })),
1553
1264
  turnId,
1554
1265
  steer: status?.mode === "steerable" && turnId != null,
1555
1266
  senderName: localParticipantName.trim() || void 0,
1556
- clientToolkits,
1557
- toolChoice: toolChoice == null ? void 0 : new ToolChoice({ toolkitName: toolChoice.toolkitName, toolName: toolChoice.toolName })
1267
+ clientToolkits: resolvedClientToolkits
1558
1268
  });
1559
1269
  setSendError(null);
1560
1270
  setVersion((current) => current + 1);
1561
1271
  } catch (error) {
1562
1272
  setSendError(describeError(error));
1563
1273
  }
1564
- }, [agentParticipant, chatClient, clientToolkits, localParticipantName, status?.mode, toolChoice, turnId]);
1274
+ }, [agentParticipant, chatClient, resolvedClientToolkits, localParticipantName, status?.mode, turnId]);
1275
+ const visibleSuggestions = useMemo(
1276
+ () => (followUpSuggestions ?? suggestions ?? []).filter((suggestion) => suggestion.label.trim() !== ""),
1277
+ [followUpSuggestions, suggestions]
1278
+ );
1279
+ const composerDisabled = composerDisabledProp || loadThread && !restorationReadyRef.current || injectPersistedEvents && restoredPathRef.current !== path || agentParticipant == null && chatClient == null;
1280
+ const handleSuggestionClick = useCallback((suggestion) => {
1281
+ const text = suggestion.prompt?.trim() || suggestion.label.trim();
1282
+ if (text === "") {
1283
+ return;
1284
+ }
1285
+ void handleSend(new ChatMessage({
1286
+ id: uuidV4(),
1287
+ text
1288
+ }));
1289
+ }, [handleSend]);
1565
1290
  const cancelTurn = useCallback(async () => {
1566
1291
  const openSession = sessionRef.current;
1567
1292
  if (openSession === null || turnId == null) {
@@ -1582,55 +1307,40 @@ function AgentThread({
1582
1307
  }, []);
1583
1308
  return /* @__PURE__ */ jsxs("div", { className: "flex h-full min-h-0 flex-1 flex-col", children: [
1584
1309
  /* @__PURE__ */ jsxs("div", { className: "relative flex h-full min-h-0 flex-1 flex-col", children: [
1585
- /* @__PURE__ */ jsx(
1586
- "div",
1310
+ showThreadLoading ? /* @__PURE__ */ jsx("div", { className: "min-h-0 flex-1 overflow-hidden", children: /* @__PURE__ */ jsx(LoadingState, {}) }) : timelineItems.length === 0 ? /* @__PURE__ */ jsx("div", { className: "min-h-0 flex-1 overflow-hidden", children: /* @__PURE__ */ jsx(EmptyState, { title: emptyStateTitle, description: emptyStateDescription }) }) : /* @__PURE__ */ jsx(
1311
+ ChatScroller,
1587
1312
  {
1588
- ref: scrollContainerRef,
1589
- className: "min-h-0 flex-1 overflow-y-auto overflow-x-hidden [overflow-anchor:none]",
1590
- onScroll: (event) => {
1591
- stickToBottomRef.current = isNearBottom(event.currentTarget);
1592
- },
1593
- children: /* @__PURE__ */ jsxs(
1594
- "div",
1595
- {
1596
- ref: contentRef,
1597
- className: cn(
1598
- "mx-auto flex min-h-full w-full max-w-[912px] flex-col gap-8 px-4 pt-6",
1599
- feedItems.length > 0 ? "justify-end" : null,
1600
- statusText ? "pb-24" : "pb-6"
1601
- ),
1602
- children: [
1603
- showThreadLoading ? /* @__PURE__ */ jsx(LoadingState, {}) : feedItems.length === 0 ? /* @__PURE__ */ jsx(EmptyState, { title: emptyStateTitle, description: emptyStateDescription }) : null,
1604
- renderedFeedItems.map((item, index) => item.kind === "detail_group" ? item.expanded ? /* @__PURE__ */ jsx(
1605
- ExpandedDetailGroup,
1606
- {
1607
- room,
1608
- item,
1609
- localParticipantName,
1610
- agentName
1611
- },
1612
- item.id
1613
- ) : /* @__PURE__ */ jsx(
1614
- DetailGroupLine,
1615
- {
1616
- item,
1617
- onToggle: () => toggleDetailGroup(item.id)
1618
- },
1619
- item.id
1620
- ) : /* @__PURE__ */ jsx(
1621
- ThreadMessageView,
1622
- {
1623
- room,
1624
- message: item,
1625
- previous: previousMessageFeedItem(renderedFeedItems, index),
1626
- localParticipantName,
1627
- agentName
1628
- },
1629
- item.id
1630
- ))
1631
- ]
1632
- }
1633
- )
1313
+ bottomThresholdPx: 24,
1314
+ className: "flex-1 overflow-x-hidden",
1315
+ currentUserId: "user",
1316
+ getMessageAuthorId: (item) => item.kind === "detail_group" ? "agent" : item.role,
1317
+ messages: renderedItemsNewestFirst,
1318
+ renderMessage: (item) => {
1319
+ return /* @__PURE__ */ jsx("div", { className: cn(
1320
+ "mx-auto w-full max-w-[912px] px-1 py-3",
1321
+ item.id === firstRenderedItemId ? "pt-6" : null,
1322
+ item.id === lastRenderedItemId ? statusText ? "pb-24" : "pb-6" : null
1323
+ ), children: item.kind === "detail_group" ? item.expanded ? /* @__PURE__ */ jsx(
1324
+ ExpandedDetailGroup,
1325
+ {
1326
+ room,
1327
+ item,
1328
+ localParticipantName,
1329
+ agentName,
1330
+ chatFeedWidgetsByName
1331
+ }
1332
+ ) : /* @__PURE__ */ jsx(DetailGroupLine, { item, onToggle: () => toggleDetailGroup(item.id) }) : /* @__PURE__ */ jsx(
1333
+ ThreadMessageView,
1334
+ {
1335
+ room,
1336
+ message: item,
1337
+ previous: previousItemById.get(item.id) ?? null,
1338
+ localParticipantName,
1339
+ agentName,
1340
+ chatFeedWidgetsByName
1341
+ }
1342
+ ) });
1343
+ }
1634
1344
  }
1635
1345
  ),
1636
1346
  statusText ? /* @__PURE__ */ jsx("div", { className: "pointer-events-none absolute inset-x-0 bottom-0 flex justify-center px-4 pb-4", children: /* @__PURE__ */ jsx("div", { className: "pointer-events-auto w-full max-w-[912px]", children: /* @__PURE__ */ jsx(
@@ -1649,8 +1359,33 @@ function AgentThread({
1649
1359
  }
1650
1360
  ) }) }) : null
1651
1361
  ] }),
1362
+ restorationError ? /* @__PURE__ */ jsx("div", { className: "px-4 pb-2", children: /* @__PURE__ */ jsx(
1363
+ ErrorBanner,
1364
+ {
1365
+ message: restorationError,
1366
+ onRetry: retryRestoration
1367
+ }
1368
+ ) }) : null,
1652
1369
  sendError ? /* @__PURE__ */ jsx("div", { className: "px-4 pb-2", children: /* @__PURE__ */ jsx(ErrorBanner, { message: sendError }) }) : null,
1653
1370
  /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
1371
+ visibleSuggestions.length > 0 ? /* @__PURE__ */ jsx(
1372
+ "ul",
1373
+ {
1374
+ "aria-label": "Follow-up suggestions",
1375
+ className: "mx-auto flex flex-wrap w-full max-w-[912px] gap-2 overflow-x-auto px-4 pt-2 pb-1",
1376
+ children: visibleSuggestions.map((suggestion, index) => /* @__PURE__ */ jsx("li", { className: "shrink-0", children: /* @__PURE__ */ jsx(
1377
+ Button,
1378
+ {
1379
+ type: "button",
1380
+ variant: "outline",
1381
+ className: "h-auto min-h-8 rounded-full px-3 py-1.5",
1382
+ disabled: composerDisabled,
1383
+ onClick: () => handleSuggestionClick(suggestion),
1384
+ children: suggestion.label
1385
+ }
1386
+ ) }, index))
1387
+ }
1388
+ ) : null,
1654
1389
  /* @__PURE__ */ jsx(
1655
1390
  ChatInput,
1656
1391
  {
@@ -1658,7 +1393,8 @@ function AgentThread({
1658
1393
  attachments,
1659
1394
  onFilesSelected: selectAttachments,
1660
1395
  setAttachments,
1661
- disabled: agentParticipant == null && chatClient == null,
1396
+ enableFileUpload,
1397
+ disabled: composerDisabled,
1662
1398
  placeholder: agentParticipant || chatClient ? "Type a message" : `Waiting for ${displayParticipantName(agentName)}`
1663
1399
  }
1664
1400
  ),