@meshagent/meshagent-tailwind 0.43.2 → 0.44.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 (99) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/cjs/chat/agent-thread-message-status-store.d.ts +107 -0
  3. package/dist/cjs/chat/agent-thread-message-status-store.js +649 -0
  4. package/dist/cjs/chat/agent-thread.d.ts +87 -0
  5. package/dist/cjs/chat/agent-thread.js +1673 -0
  6. package/dist/cjs/chat/chat-bot-view.d.ts +9 -5
  7. package/dist/cjs/chat/chat-bot-view.js +44 -536
  8. package/dist/cjs/chat/chat-hooks.d.ts +6 -5
  9. package/dist/cjs/chat/chat-hooks.js +21 -466
  10. package/dist/cjs/chat/chat-typing-indicator.d.ts +15 -1
  11. package/dist/cjs/chat/chat-typing-indicator.js +35 -5
  12. package/dist/cjs/chat/file-attachment.d.ts +7 -3
  13. package/dist/cjs/chat/file-attachment.js +30 -6
  14. package/dist/cjs/chat/multi-thread-view.d.ts +5 -2
  15. package/dist/cjs/chat/multi-thread-view.js +6 -2
  16. package/dist/cjs/chat/new-chat-thread.d.ts +5 -2
  17. package/dist/cjs/chat/new-chat-thread.js +10 -3
  18. package/dist/cjs/chat/thread-list-view.d.ts +22 -0
  19. package/dist/cjs/chat/thread-list-view.js +518 -0
  20. package/dist/cjs/chat/tool-call-status-accumulator.d.ts +69 -0
  21. package/dist/cjs/chat/tool-call-status-accumulator.js +268 -0
  22. package/dist/cjs/components/pane-example.d.ts +1 -1
  23. package/dist/cjs/components/ui/avatar.d.ts +3 -3
  24. package/dist/cjs/components/ui/button.d.ts +3 -3
  25. package/dist/cjs/components/ui/card.d.ts +7 -7
  26. package/dist/cjs/components/ui/dialog.d.ts +10 -10
  27. package/dist/cjs/components/ui/form.d.ts +7 -7
  28. package/dist/cjs/components/ui/input.d.ts +1 -1
  29. package/dist/cjs/components/ui/label.d.ts +1 -1
  30. package/dist/cjs/components/ui/progress.d.ts +1 -1
  31. package/dist/cjs/components/ui/radio-group.d.ts +2 -2
  32. package/dist/cjs/components/ui/select.d.ts +10 -10
  33. package/dist/cjs/components/ui/sheet.d.ts +8 -8
  34. package/dist/cjs/components/ui/skeleton.d.ts +1 -1
  35. package/dist/cjs/components/ui/sonner.d.ts +1 -1
  36. package/dist/cjs/components/ui/spinner.d.ts +2 -2
  37. package/dist/cjs/components/ui/textarea.d.ts +1 -1
  38. package/dist/cjs/file-preview/file-preview.d.ts +1 -0
  39. package/dist/cjs/file-preview/file-preview.js +43 -7
  40. package/dist/cjs/index.d.ts +4 -2
  41. package/dist/cjs/index.js +14 -2
  42. package/dist/cjs/meetings/camera-grid.d.ts +2 -2
  43. package/dist/cjs/tools/ask-user-for-file.js +2 -2
  44. package/dist/cjs/tools/file-dialog.d.ts +2 -1
  45. package/dist/cjs/tools/form-dialog.d.ts +2 -1
  46. package/dist/esm/chat/agent-thread-message-status-store.d.ts +107 -0
  47. package/dist/esm/chat/agent-thread-message-status-store.js +647 -0
  48. package/dist/esm/chat/agent-thread.d.ts +87 -0
  49. package/dist/esm/chat/agent-thread.js +1682 -0
  50. package/dist/esm/chat/chat-bot-view.d.ts +9 -5
  51. package/dist/esm/chat/chat-bot-view.js +51 -566
  52. package/dist/esm/chat/chat-hooks.d.ts +6 -5
  53. package/dist/esm/chat/chat-hooks.js +23 -468
  54. package/dist/esm/chat/chat-typing-indicator.d.ts +15 -1
  55. package/dist/esm/chat/chat-typing-indicator.js +35 -5
  56. package/dist/esm/chat/file-attachment.d.ts +7 -3
  57. package/dist/esm/chat/file-attachment.js +30 -6
  58. package/dist/esm/chat/multi-thread-view.d.ts +5 -2
  59. package/dist/esm/chat/multi-thread-view.js +6 -2
  60. package/dist/esm/chat/new-chat-thread.d.ts +5 -2
  61. package/dist/esm/chat/new-chat-thread.js +11 -4
  62. package/dist/esm/chat/thread-list-view.d.ts +22 -0
  63. package/dist/esm/chat/thread-list-view.js +514 -0
  64. package/dist/esm/chat/tool-call-status-accumulator.d.ts +69 -0
  65. package/dist/esm/chat/tool-call-status-accumulator.js +248 -0
  66. package/dist/esm/components/pane-example.d.ts +1 -1
  67. package/dist/esm/components/ui/avatar.d.ts +3 -3
  68. package/dist/esm/components/ui/button.d.ts +3 -3
  69. package/dist/esm/components/ui/card.d.ts +7 -7
  70. package/dist/esm/components/ui/dialog.d.ts +10 -10
  71. package/dist/esm/components/ui/form.d.ts +7 -7
  72. package/dist/esm/components/ui/input.d.ts +1 -1
  73. package/dist/esm/components/ui/label.d.ts +1 -1
  74. package/dist/esm/components/ui/progress.d.ts +1 -1
  75. package/dist/esm/components/ui/radio-group.d.ts +2 -2
  76. package/dist/esm/components/ui/select.d.ts +10 -10
  77. package/dist/esm/components/ui/sheet.d.ts +8 -8
  78. package/dist/esm/components/ui/skeleton.d.ts +1 -1
  79. package/dist/esm/components/ui/sonner.d.ts +1 -1
  80. package/dist/esm/components/ui/spinner.d.ts +2 -2
  81. package/dist/esm/components/ui/textarea.d.ts +1 -1
  82. package/dist/esm/file-preview/file-preview.d.ts +1 -0
  83. package/dist/esm/file-preview/file-preview.js +31 -5
  84. package/dist/esm/index.d.ts +4 -2
  85. package/dist/esm/index.js +10 -2
  86. package/dist/esm/meetings/camera-grid.d.ts +2 -2
  87. package/dist/esm/tools/ask-user-for-file.js +2 -2
  88. package/dist/esm/tools/file-dialog.d.ts +2 -1
  89. package/dist/esm/tools/form-dialog.d.ts +2 -1
  90. package/dist/index.css +1 -1
  91. package/package.json +10 -5
  92. package/dist/cjs/chat/chat-thread.d.ts +0 -12
  93. package/dist/cjs/chat/chat-thread.js +0 -815
  94. package/dist/cjs/chat/dataset-chat-thread.d.ts +0 -16
  95. package/dist/cjs/chat/dataset-chat-thread.js +0 -1813
  96. package/dist/esm/chat/chat-thread.d.ts +0 -12
  97. package/dist/esm/chat/chat-thread.js +0 -785
  98. package/dist/esm/chat/dataset-chat-thread.d.ts +0 -16
  99. package/dist/esm/chat/dataset-chat-thread.js +0 -1811
@@ -0,0 +1,1682 @@
1
+ import { jsx, jsxs } from "react/jsx-runtime";
2
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
3
+ import {
4
+ AgentFileContentDelta,
5
+ AgentFileContentEnded,
6
+ AgentFileContentStarted,
7
+ AgentImageGenerationCompleted,
8
+ AgentImageGenerationFailed,
9
+ AgentImageGenerationPartial,
10
+ AgentImageGenerationStarted,
11
+ AgentClientToolCallRequested,
12
+ AgentSecretRequested,
13
+ AgentModelChanged,
14
+ AgentReasoningContentDelta,
15
+ AgentReasoningContentEnded,
16
+ AgentReasoningContentStarted,
17
+ AgentTextContentDelta,
18
+ AgentTextContentEnded,
19
+ AgentTextContentStarted,
20
+ AgentThreadStatus,
21
+ AgentUsageUpdated,
22
+ AgentToolCallArgumentsDelta,
23
+ AgentToolCallEnded,
24
+ AgentToolCallInProgress,
25
+ AgentToolCallLogDelta,
26
+ AgentToolCallPending,
27
+ AgentToolCallStarted,
28
+ MessagingChatClient,
29
+ ToolChoice,
30
+ StartThread,
31
+ TurnStart,
32
+ TurnStartAccepted,
33
+ TurnStartRejected,
34
+ TurnEnded,
35
+ TurnInterruptAccepted,
36
+ TurnInterrupted,
37
+ TurnSteer,
38
+ TurnSteerAccepted,
39
+ TurnSteerRejected,
40
+ TurnSteered,
41
+ TurnStarted
42
+ } from "@meshagent/meshagent-agents";
43
+ import { ChevronDown, ChevronRight, Download, FileText, ImageOff, Terminal } from "lucide-react";
44
+ import ReactMarkdown from "react-markdown";
45
+ import rehypeHighlight from "rehype-highlight";
46
+ import rehypeSanitize from "rehype-sanitize";
47
+ 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";
53
+ import { filePreviewName, isImagePath } from "../file-preview/file-preview.js";
54
+ const stickyBottomThresholdPx = 24;
55
+ class AgentToolChoice {
56
+ toolkitName;
57
+ toolName;
58
+ constructor({ toolkitName, toolName }) {
59
+ this.toolkitName = toolkitName;
60
+ this.toolName = toolName;
61
+ }
62
+ toJson() {
63
+ return { toolkit_name: this.toolkitName, tool_name: this.toolName };
64
+ }
65
+ }
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;
80
+ }
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;
192
+ }
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
+ }
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;
222
+ }
223
+ function displayParticipantName(name) {
224
+ const normalized = name?.trim();
225
+ if (!normalized) {
226
+ return "agent";
227
+ }
228
+ return normalized.split("@")[0]?.trim() || normalized;
229
+ }
230
+ function getParticipantName(participant) {
231
+ const name = participant?.getAttribute("name");
232
+ return typeof name === "string" ? name.trim() : "";
233
+ }
234
+ function findAgentParticipant(room, agentName) {
235
+ const normalizedAgentName = agentName?.trim();
236
+ for (const participant of room.messaging.remoteParticipants) {
237
+ if (normalizedAgentName && getParticipantName(participant) !== normalizedAgentName) {
238
+ continue;
239
+ }
240
+ if (participant.getAttribute("supports_agent_messages") === true) {
241
+ return participant;
242
+ }
243
+ }
244
+ return null;
245
+ }
246
+ function timeAgo(date) {
247
+ const seconds = Math.max(0, Math.floor((Date.now() - date.getTime()) / 1e3));
248
+ if (seconds < 60) {
249
+ return "now";
250
+ }
251
+ const minutes = Math.floor(seconds / 60);
252
+ if (minutes < 60) {
253
+ return `${minutes}m`;
254
+ }
255
+ 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;
506
+ }
507
+ function isShellTool(message) {
508
+ 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");
768
+ }
769
+ function firstNonEmptyLine(text) {
770
+ for (const line of text.split(/\r?\n/)) {
771
+ const trimmed = line.trim();
772
+ if (trimmed !== "") {
773
+ return trimmed;
774
+ }
775
+ }
776
+ return null;
777
+ }
778
+ function detailGroupId(messages) {
779
+ const first = messages[0];
780
+ return ["details", first?.turnId ?? "", first?.id ?? "", first?.createdAt.getTime() ?? 0].join(":");
781
+ }
782
+ function messagesShareTurn(left, right) {
783
+ return left.turnId != null && left.turnId.trim() !== "" && left.turnId === right.turnId;
784
+ }
785
+ function canCollapseAsCommentary(message) {
786
+ if (message.phase === "final_answer") {
787
+ return false;
788
+ }
789
+ return message.kind === "message" && message.role === "agent" && message.attachments.length === 0 && message.image == null;
790
+ }
791
+ function canRenderAsFinalAnswer(message) {
792
+ if (message.kind !== "message" || message.role !== "agent" || message.phase === "commentary") {
793
+ return false;
794
+ }
795
+ return message.text.trim() !== "" || message.attachments.length > 0 || message.image != null;
796
+ }
797
+ function isIntrinsicDetail(message) {
798
+ return message.kind === "reasoning" || message.kind === "event" || message.kind === "tool_call" && message.failed !== true || canCollapseAsCommentary(message) && message.phase === "commentary";
799
+ }
800
+ function nextUserMessageIndex(messages, start) {
801
+ for (let index = start; index < messages.length; index += 1) {
802
+ const message = messages[index];
803
+ if (message.kind === "message" && message.role === "user") {
804
+ return index;
805
+ }
806
+ }
807
+ return null;
808
+ }
809
+ function finalAgentMessageIndexForSegment(messages, start, end) {
810
+ let explicitFinalIndex = -1;
811
+ for (let index = start; index < end; index += 1) {
812
+ const message = messages[index];
813
+ if (canRenderAsFinalAnswer(message) && message.phase === "final_answer") {
814
+ explicitFinalIndex = index;
815
+ }
816
+ }
817
+ if (explicitFinalIndex !== -1) {
818
+ return explicitFinalIndex;
819
+ }
820
+ let inferredFinalIndex = -1;
821
+ for (let index = start; index < end; index += 1) {
822
+ if (canRenderAsFinalAnswer(messages[index])) {
823
+ inferredFinalIndex = index;
824
+ }
825
+ }
826
+ return inferredFinalIndex;
827
+ }
828
+ function addDetailIndexesForSegment(messages, start, end, detailIndexes) {
829
+ const finalAgentMessageIndex = finalAgentMessageIndexForSegment(messages, start, end);
830
+ for (let index = start; index < end; index += 1) {
831
+ const message = messages[index];
832
+ if (isIntrinsicDetail(message)) {
833
+ detailIndexes.add(index);
834
+ continue;
835
+ }
836
+ if (index !== finalAgentMessageIndex && canCollapseAsCommentary(message)) {
837
+ detailIndexes.add(index);
838
+ }
839
+ }
840
+ }
841
+ function nextNonDetailMessage(messages, detailIndexes, start, end) {
842
+ for (let index = start; index < end; index += 1) {
843
+ if (!detailIndexes.has(index)) {
844
+ return messages[index];
845
+ }
846
+ }
847
+ return null;
848
+ }
849
+ function detailGroupCollapsedMessage(messages) {
850
+ for (const message of [...messages].reverse()) {
851
+ if (canCollapseAsCommentary(message) && message.text.trim() !== "") {
852
+ return message;
853
+ }
854
+ }
855
+ for (const message of [...messages].reverse()) {
856
+ if (message.kind === "reasoning" && message.text.trim() !== "") {
857
+ return message;
858
+ }
859
+ }
860
+ return null;
861
+ }
862
+ function formatDetailGroupDuration(milliseconds) {
863
+ const seconds = Math.max(0, Math.round(milliseconds / 1e3));
864
+ if (seconds < 60) {
865
+ return `${seconds}s`;
866
+ }
867
+ const minutes = Math.floor(seconds / 60);
868
+ const remainingSeconds = seconds % 60;
869
+ return remainingSeconds === 0 ? `${minutes}m` : `${minutes}m ${remainingSeconds}s`;
870
+ }
871
+ function detailGroupCollapsedText(messages, nextMessage) {
872
+ const first = messages[0];
873
+ if (first && nextMessage != null && canRenderAsFinalAnswer(nextMessage) && messagesShareTurn(first, nextMessage)) {
874
+ return `Worked for ${formatDetailGroupDuration(nextMessage.createdAt.getTime() - first.createdAt.getTime())}`;
875
+ }
876
+ return firstNonEmptyLine(detailGroupCollapsedMessage(messages)?.text ?? "") ?? "Working";
877
+ }
878
+ function detailGroupAuthorName(message, localParticipantName, agentName) {
879
+ const authorName = message.authorName?.trim();
880
+ if (authorName) {
881
+ return authorName;
882
+ }
883
+ if (message.role === "user") {
884
+ return localParticipantName;
885
+ }
886
+ return displayParticipantName(agentName);
887
+ }
888
+ function detailGroupForMessages(messages, nextMessage, expandedIds, localParticipantName, agentName) {
889
+ const collapsedMessage = detailGroupCollapsedMessage(messages) ?? messages[0];
890
+ const id = detailGroupId(messages);
891
+ return {
892
+ id,
893
+ kind: "detail_group",
894
+ messages,
895
+ collapsedText: detailGroupCollapsedText(messages, nextMessage),
896
+ authorName: detailGroupAuthorName(collapsedMessage, localParticipantName, agentName),
897
+ createdAt: collapsedMessage.createdAt,
898
+ expanded: expandedIds.has(id)
899
+ };
900
+ }
901
+ function threadFeedItems(messages, expandedIds, localParticipantName, agentName) {
902
+ const items = [];
903
+ let index = 0;
904
+ while (index < messages.length) {
905
+ const segmentEnd = nextUserMessageIndex(messages, index + 1) ?? messages.length;
906
+ const detailIndexes = /* @__PURE__ */ new Set();
907
+ addDetailIndexesForSegment(messages, index, segmentEnd, detailIndexes);
908
+ const groupedMessages = [...detailIndexes].sort((left, right) => left - right).map((detailIndex) => messages[detailIndex]);
909
+ let insertedDetailGroup = false;
910
+ for (let segmentIndex = index; segmentIndex < segmentEnd; segmentIndex += 1) {
911
+ if (!detailIndexes.has(segmentIndex)) {
912
+ items.push(messages[segmentIndex]);
913
+ continue;
914
+ }
915
+ if (insertedDetailGroup || groupedMessages.length === 0) {
916
+ continue;
917
+ }
918
+ items.push(detailGroupForMessages(
919
+ groupedMessages,
920
+ nextNonDetailMessage(messages, detailIndexes, segmentIndex + 1, segmentEnd),
921
+ expandedIds,
922
+ localParticipantName,
923
+ agentName
924
+ ));
925
+ insertedDetailGroup = true;
926
+ }
927
+ index = segmentEnd;
928
+ }
929
+ return items;
930
+ }
931
+ function previousMessageFeedItem(items, index) {
932
+ for (let cursor = index - 1; cursor >= 0; cursor -= 1) {
933
+ const item = items[cursor];
934
+ if (item.kind !== "detail_group") {
935
+ return item;
936
+ }
937
+ }
938
+ return null;
939
+ }
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
+ function formatAgentUsageTokenCount(value) {
967
+ const magnitude = Math.abs(value);
968
+ if (magnitude >= 1e6) {
969
+ return `${trimFixed(value / 1e6)}M`;
970
+ }
971
+ if (magnitude >= 1e3) {
972
+ return `${trimFixed(value / 1e3)}K`;
973
+ }
974
+ return Math.round(value).toString();
975
+ }
976
+ function trimFixed(value) {
977
+ const fixed = value.toFixed(1);
978
+ return fixed.endsWith(".0") ? fixed.slice(0, -2) : fixed;
979
+ }
980
+ function formatAgentUsageFooter(usage) {
981
+ const contextLimitTokens = usage.compactionThreshold ?? usage.contextTotalTokens;
982
+ const used = formatAgentUsageTokenCount(usage.contextUsedTokens);
983
+ const limit = contextLimitTokens == null ? "" : `/${formatAgentUsageTokenCount(contextLimitTokens)}`;
984
+ return `context ${used}${limit}`;
985
+ }
986
+ function formatAgentUsageTooltip(usage) {
987
+ const lines = [`context used: ${formatAgentUsageTokenCount(usage.contextUsedTokens)}`];
988
+ if (usage.compactionMode != null) {
989
+ lines.push(`context management: ${usage.compactionMode}`);
990
+ if (usage.compactionThreshold != null) {
991
+ lines.push(`context threshold: ${formatAgentUsageTokenCount(usage.compactionThreshold)}`);
992
+ }
993
+ }
994
+ if (usage.compactionThreshold != null && usage.contextTotalTokens != null) {
995
+ lines.push(`model window: ${formatAgentUsageTokenCount(usage.contextTotalTokens)}`);
996
+ }
997
+ const entries = Object.entries(usage.usage).sort(([left], [right]) => left.localeCompare(right));
998
+ for (const [key, value] of entries) {
999
+ lines.push(`${key}: ${formatAgentUsageTokenCount(value)}`);
1000
+ }
1001
+ return lines.join("\n");
1002
+ }
1003
+ function AgentUsageFooter({ usage, className }) {
1004
+ const tooltip = usage === null ? void 0 : formatAgentUsageTooltip(usage);
1005
+ const label = usage === null ? "" : formatAgentUsageFooter(usage);
1006
+ return /* @__PURE__ */ jsx(
1007
+ "div",
1008
+ {
1009
+ className: cn("min-h-4 truncate px-2 text-right text-[11px] leading-4 text-muted-foreground", className),
1010
+ title: tooltip,
1011
+ "aria-label": tooltip,
1012
+ children: label
1013
+ }
1014
+ );
1015
+ }
1016
+ function dateFromString(value) {
1017
+ if (value == null || value.trim() === "") {
1018
+ return null;
1019
+ }
1020
+ const parsed = new Date(value);
1021
+ return Number.isNaN(parsed.getTime()) ? null : parsed;
1022
+ }
1023
+ function normalizeAttachmentPath(path) {
1024
+ const prefix = "room:///";
1025
+ return path.startsWith(prefix) ? path.slice(prefix.length) : path;
1026
+ }
1027
+ function isHttpUrl(path) {
1028
+ return /^https?:\/\//iu.test(path.trim());
1029
+ }
1030
+ function isInlineImageUrl(path) {
1031
+ return path.trim().toLowerCase().startsWith("data:image/");
1032
+ }
1033
+ function attachmentImagePath(path) {
1034
+ const trimmed = path.trim();
1035
+ if (trimmed === "") {
1036
+ return null;
1037
+ }
1038
+ if (isInlineImageUrl(trimmed)) {
1039
+ return trimmed;
1040
+ }
1041
+ const normalized = normalizeAttachmentPath(trimmed);
1042
+ return isImagePath(normalized) ? normalized : null;
1043
+ }
1044
+ function MarkdownBlock({ text }) {
1045
+ return /* @__PURE__ */ jsx(
1046
+ ReactMarkdown,
1047
+ {
1048
+ remarkPlugins: [remarkGfm],
1049
+ rehypePlugins: [rehypeSanitize, rehypeHighlight],
1050
+ components: {
1051
+ pre: ({ className, children, ...props }) => /* @__PURE__ */ jsx("pre", { ...props, className: cn("overflow-x-auto rounded-md border bg-background/80 p-3", className), children }),
1052
+ p: ({ children, ...props }) => /* @__PURE__ */ jsx("p", { ...props, className: "mb-2 last:mb-0", children }),
1053
+ ul: ({ children, ...props }) => /* @__PURE__ */ jsx("ul", { ...props, className: "mb-2 ml-6 list-disc last:mb-0", children }),
1054
+ ol: ({ children, ...props }) => /* @__PURE__ */ jsx("ol", { ...props, className: "mb-2 ml-6 list-decimal last:mb-0", children })
1055
+ },
1056
+ children: text
1057
+ }
1058
+ );
1059
+ }
1060
+ function ChatBubble({ text, mine }) {
1061
+ if (text.trim() === "") {
1062
+ return null;
1063
+ }
1064
+ return /* @__PURE__ */ jsx("div", { className: cn(
1065
+ "w-fit max-w-[85%] rounded-md px-4 py-3 text-sm leading-6 shadow-xs sm:max-w-2xl",
1066
+ mine ? "bg-secondary/85 text-foreground" : "bg-muted/70 text-foreground"
1067
+ ), children: /* @__PURE__ */ jsx(MarkdownBlock, { text }) });
1068
+ }
1069
+ function ReasoningTrace({ text, className }) {
1070
+ if (text.trim() === "") {
1071
+ return null;
1072
+ }
1073
+ return /* @__PURE__ */ jsx("div", { className: cn("mr-[50px] ml-1.5 px-4 py-1 text-sm leading-6 text-muted-foreground", className), children: /* @__PURE__ */ jsx(MarkdownBlock, { text }) });
1074
+ }
1075
+ function trimShellText(value) {
1076
+ if (value == null) {
1077
+ return void 0;
1078
+ }
1079
+ return value.length < 1024 ? value : value.slice(0, 1024) + "...";
1080
+ }
1081
+ function ShellLine({ command, result, stdout, stderr, argumentsText, logs, title = "Terminal", className }) {
1082
+ const displayCommand = command?.trim() || title;
1083
+ const [expanded, setExpanded] = useState(title.toLowerCase().includes("error"));
1084
+ const trimmedResult = trimShellText(result);
1085
+ const trimmedStdout = trimShellText(stdout);
1086
+ const trimmedStderr = trimShellText(stderr);
1087
+ const trimmedArguments = trimShellText(argumentsText);
1088
+ const trimmedLogs = logs == null || logs.length === 0 ? void 0 : trimShellText(logs.join("\n"));
1089
+ const hasDetails = trimmedResult != null || trimmedStdout != null || trimmedStderr != null || trimmedArguments != null || trimmedLogs != null;
1090
+ return /* @__PURE__ */ jsxs("div", { className: cn("mr-[50px] ml-1.5 overflow-hidden rounded-md border bg-background text-sm", className), children: [
1091
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 border-b bg-secondary/70 px-4 py-1.5 text-foreground", children: [
1092
+ /* @__PURE__ */ jsx(Terminal, { className: "h-4 w-4 shrink-0" }),
1093
+ /* @__PURE__ */ jsx("span", { className: "font-medium", children: title })
1094
+ ] }),
1095
+ /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-1 px-2 py-1.5", children: [
1096
+ /* @__PURE__ */ jsx(
1097
+ "button",
1098
+ {
1099
+ type: "button",
1100
+ className: "mt-0.5 inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-muted hover:text-foreground",
1101
+ onClick: () => setExpanded((current) => !current),
1102
+ "aria-expanded": expanded,
1103
+ "aria-label": expanded ? "Collapse terminal output" : "Expand terminal output",
1104
+ children: expanded ? /* @__PURE__ */ jsx(ChevronDown, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(ChevronRight, { className: "h-4 w-4" })
1105
+ }
1106
+ ),
1107
+ /* @__PURE__ */ jsx("pre", { className: cn("min-w-0 flex-1 overflow-hidden whitespace-pre-wrap break-words font-mono text-xs leading-5 text-foreground", expanded ? null : "line-clamp-1"), children: displayCommand })
1108
+ ] }),
1109
+ expanded && hasDetails ? /* @__PURE__ */ jsxs("div", { className: "space-y-2 border-t px-4 py-3", children: [
1110
+ trimmedResult != null ? /* @__PURE__ */ jsx("pre", { className: "whitespace-pre-wrap break-words font-mono text-xs leading-5 text-foreground", children: trimmedResult }) : null,
1111
+ trimmedStdout != null ? /* @__PURE__ */ jsx("pre", { className: "whitespace-pre-wrap break-words font-mono text-xs leading-5 text-foreground", children: trimmedStdout }) : null,
1112
+ trimmedStderr != null ? /* @__PURE__ */ jsx("pre", { className: "whitespace-pre-wrap break-words font-mono text-xs leading-5 text-destructive", children: trimmedStderr }) : null,
1113
+ trimmedArguments != null ? /* @__PURE__ */ jsx("pre", { className: "whitespace-pre-wrap break-words font-mono text-xs leading-5 text-muted-foreground", children: trimmedArguments }) : null,
1114
+ trimmedLogs != null ? /* @__PURE__ */ jsx("pre", { className: "whitespace-pre-wrap break-words font-mono text-xs leading-5 text-muted-foreground", children: trimmedLogs }) : null
1115
+ ] }) : null
1116
+ ] });
1117
+ }
1118
+ function eventLineStateClass(state, failed) {
1119
+ const normalizedState = state?.trim().toLowerCase();
1120
+ if (failed === true || normalizedState === "failed") {
1121
+ return "text-destructive";
1122
+ }
1123
+ if (normalizedState === "cancelled") {
1124
+ return "text-muted-foreground";
1125
+ }
1126
+ if (normalizedState === "running" || normalizedState === "in_progress" || normalizedState === "queued") {
1127
+ return "text-primary";
1128
+ }
1129
+ return "text-muted-foreground";
1130
+ }
1131
+ function eventLineDetails(details) {
1132
+ if (details == null) {
1133
+ return [];
1134
+ }
1135
+ const lines = typeof details === "string" ? details.split(/\r?\n/) : details;
1136
+ return lines.map((line) => line.trim()).filter((line) => line !== "");
1137
+ }
1138
+ function EventLine({ headline, details, state = "info", failed = false, className }) {
1139
+ const normalizedHeadline = headline.trim();
1140
+ const detailLines = eventLineDetails(details);
1141
+ if (normalizedHeadline === "") {
1142
+ return null;
1143
+ }
1144
+ const textClass = eventLineStateClass(state, failed);
1145
+ return /* @__PURE__ */ jsxs("div", { className: cn("ml-1.5 px-4 py-1 text-xs leading-5", textClass, className), children: [
1146
+ /* @__PURE__ */ jsx("div", { className: "font-semibold", children: normalizedHeadline }),
1147
+ detailLines.length > 0 ? /* @__PURE__ */ jsx("div", { className: "mt-0.5 whitespace-pre-wrap break-words opacity-85", children: detailLines.join("\n") }) : null
1148
+ ] });
1149
+ }
1150
+ function toolDetailLines(message) {
1151
+ const details = [];
1152
+ if (message.argumentsText?.trim()) {
1153
+ details.push(message.argumentsText);
1154
+ }
1155
+ if (message.logs != null && message.logs.length > 0) {
1156
+ details.push(message.logs.join("\n"));
1157
+ }
1158
+ if (message.result?.trim()) {
1159
+ details.push(message.result);
1160
+ }
1161
+ if (message.stdout?.trim()) {
1162
+ details.push(message.stdout);
1163
+ }
1164
+ if (message.stderr?.trim()) {
1165
+ details.push(message.stderr);
1166
+ }
1167
+ return details;
1168
+ }
1169
+ function ToolCallLine({ message }) {
1170
+ const detailLines = toolDetailLines(message);
1171
+ const [expanded, setExpanded] = useState(message.failed === true);
1172
+ const hasDetails = detailLines.length > 0;
1173
+ if (!hasDetails) {
1174
+ return /* @__PURE__ */ jsx(EventLine, { headline: message.text, state: message.state ?? (message.failed === true ? "failed" : "completed"), failed: message.failed });
1175
+ }
1176
+ return /* @__PURE__ */ jsxs("div", { className: "ml-1.5 max-w-[85%] overflow-hidden rounded-md border bg-background text-sm sm:max-w-2xl", children: [
1177
+ /* @__PURE__ */ jsxs(
1178
+ "button",
1179
+ {
1180
+ type: "button",
1181
+ className: "flex w-full items-start gap-2 px-3 py-2 text-left transition-colors hover:bg-muted/50",
1182
+ onClick: () => setExpanded((current) => !current),
1183
+ "aria-expanded": expanded,
1184
+ "aria-label": expanded ? "Collapse tool details" : "Expand tool details",
1185
+ children: [
1186
+ /* @__PURE__ */ jsx("span", { className: "mt-0.5 inline-flex h-5 w-5 shrink-0 items-center justify-center text-muted-foreground", children: expanded ? /* @__PURE__ */ jsx(ChevronDown, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(ChevronRight, { className: "h-4 w-4" }) }),
1187
+ /* @__PURE__ */ jsx("span", { className: cn("min-w-0 flex-1 text-xs font-semibold leading-5", eventLineStateClass(message.state, message.failed)), children: message.text })
1188
+ ]
1189
+ }
1190
+ ),
1191
+ expanded ? /* @__PURE__ */ jsx("div", { className: "space-y-2 border-t px-4 py-3", children: detailLines.map((line, index) => /* @__PURE__ */ jsx("pre", { className: cn("whitespace-pre-wrap break-words font-mono text-xs leading-5", message.failed === true ? "text-destructive" : "text-muted-foreground"), children: trimShellText(line) }, index)) }) : null
1192
+ ] });
1193
+ }
1194
+ function AttachmentView({ room, path }) {
1195
+ return attachmentImagePath(path) == null ? /* @__PURE__ */ jsx(AttachmentDownloadButton, { room, path }) : /* @__PURE__ */ jsx(ChatImageAttachment, { room, path });
1196
+ }
1197
+ function ChatImageAttachment({ room, path }) {
1198
+ const imagePath = attachmentImagePath(path) ?? path;
1199
+ const [url, setUrl] = useState(() => isInlineImageUrl(imagePath) || isHttpUrl(imagePath) ? imagePath : null);
1200
+ const [error, setError] = useState(null);
1201
+ useEffect(() => {
1202
+ let cancelled = false;
1203
+ setError(null);
1204
+ if (isInlineImageUrl(imagePath) || isHttpUrl(imagePath)) {
1205
+ setUrl(imagePath);
1206
+ return;
1207
+ }
1208
+ setUrl(null);
1209
+ void room.storage.downloadUrl(imagePath).then((nextUrl) => {
1210
+ if (!cancelled) {
1211
+ setUrl(nextUrl);
1212
+ }
1213
+ }).catch((nextError) => {
1214
+ if (!cancelled) {
1215
+ setError(nextError);
1216
+ }
1217
+ });
1218
+ return () => {
1219
+ cancelled = true;
1220
+ };
1221
+ }, [imagePath, room]);
1222
+ if (error != null) {
1223
+ return /* @__PURE__ */ jsx(AttachmentDownloadButton, { room, path });
1224
+ }
1225
+ if (url == null) {
1226
+ return /* @__PURE__ */ jsx("div", { className: "flex h-[240px] w-[240px] items-center justify-center rounded-md border bg-background text-muted-foreground", children: /* @__PURE__ */ jsx(Spinner, { className: "h-5 w-5" }) });
1227
+ }
1228
+ return /* @__PURE__ */ jsx(
1229
+ "button",
1230
+ {
1231
+ type: "button",
1232
+ className: "block max-w-full overflow-hidden rounded-md shadow-xs transition-opacity hover:opacity-90",
1233
+ onClick: () => window.open(url, "_blank", "noopener,noreferrer"),
1234
+ title: "Open image",
1235
+ children: /* @__PURE__ */ jsx("img", { src: url, alt: filePreviewName(imagePath), className: "max-h-[312px] max-w-full object-contain" })
1236
+ }
1237
+ );
1238
+ }
1239
+ function AttachmentDownloadButton({ room, path, className }) {
1240
+ const preview = normalizeAttachmentPath(path);
1241
+ const filename = filePreviewName(preview);
1242
+ return /* @__PURE__ */ jsxs(
1243
+ "button",
1244
+ {
1245
+ type: "button",
1246
+ className: cn("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", className),
1247
+ onClick: () => {
1248
+ if (isInlineImageUrl(path) || isHttpUrl(path)) {
1249
+ window.open(path, "_blank", "noopener,noreferrer");
1250
+ return;
1251
+ }
1252
+ void room.storage.downloadUrl(preview).then((nextUrl) => {
1253
+ window.open(nextUrl, "_blank", "noopener,noreferrer");
1254
+ });
1255
+ },
1256
+ children: [
1257
+ /* @__PURE__ */ jsx(FileText, { className: "h-4 w-4 shrink-0 text-muted-foreground" }),
1258
+ /* @__PURE__ */ jsx("span", { className: "truncate text-sm font-medium", children: filename }),
1259
+ /* @__PURE__ */ jsx(Download, { className: "h-4 w-4 shrink-0 text-muted-foreground" })
1260
+ ]
1261
+ }
1262
+ );
1263
+ }
1264
+ function ChatThreadPreview({ room, path, className }) {
1265
+ const normalizedPath = normalizeAttachmentPath(path);
1266
+ if (attachmentImagePath(path) != null) {
1267
+ return /* @__PURE__ */ jsx("div", { className: cn("h-[312.5px] w-[312.5px] max-w-full overflow-hidden rounded-2xl bg-background", className), children: /* @__PURE__ */ jsx(ChatImageAttachment, { room, path }) });
1268
+ }
1269
+ return /* @__PURE__ */ jsx(AttachmentDownloadButton, { room, path: normalizedPath, className });
1270
+ }
1271
+ function DetailGroupLine({ item, onToggle }) {
1272
+ return /* @__PURE__ */ jsxs(
1273
+ "button",
1274
+ {
1275
+ type: "button",
1276
+ className: "mx-auto flex max-w-[85%] items-center gap-2 rounded-md px-3 py-1.5 text-left text-xs text-muted-foreground transition-colors hover:bg-muted/50 hover:text-foreground sm:max-w-2xl",
1277
+ onClick: onToggle,
1278
+ "aria-expanded": item.expanded,
1279
+ title: item.expanded ? "Collapse details" : "Expand details",
1280
+ children: [
1281
+ item.expanded ? /* @__PURE__ */ jsx(ChevronDown, { className: "h-3.5 w-3.5 shrink-0" }) : /* @__PURE__ */ jsx(ChevronRight, { className: "h-3.5 w-3.5 shrink-0" }),
1282
+ /* @__PURE__ */ jsx("span", { className: "min-w-0 truncate", children: item.collapsedText }),
1283
+ /* @__PURE__ */ jsx("span", { className: "shrink-0", children: timeAgo(item.createdAt) })
1284
+ ]
1285
+ }
1286
+ );
1287
+ }
1288
+ function ExpandedDetailGroup({
1289
+ room,
1290
+ item,
1291
+ localParticipantName,
1292
+ agentName
1293
+ }) {
1294
+ return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3", children: [
1295
+ /* @__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: [
1296
+ item.authorName.trim() !== "" ? /* @__PURE__ */ jsx("span", { className: "font-semibold text-foreground", children: displayParticipantName(item.authorName) }) : null,
1297
+ /* @__PURE__ */ jsx("span", { children: timeAgo(item.createdAt) })
1298
+ ] }) }) }),
1299
+ item.messages.map((message, index) => /* @__PURE__ */ jsx(
1300
+ ThreadMessageView,
1301
+ {
1302
+ room,
1303
+ message,
1304
+ previous: index > 0 ? item.messages[index - 1] : null,
1305
+ localParticipantName,
1306
+ agentName,
1307
+ forceHideHeader: true
1308
+ },
1309
+ message.id
1310
+ ))
1311
+ ] });
1312
+ }
1313
+ function GeneratedImageView({ image }) {
1314
+ const completedImages = image.images?.filter((entry) => entry.uri?.trim()) ?? [];
1315
+ if (completedImages.length > 0) {
1316
+ return /* @__PURE__ */ jsx("div", { className: "grid max-w-[85%] grid-cols-1 gap-3 sm:max-w-2xl sm:grid-cols-2", children: completedImages.map((entry, index) => /* @__PURE__ */ jsx(
1317
+ "button",
1318
+ {
1319
+ type: "button",
1320
+ className: "overflow-hidden rounded-md shadow-xs transition-opacity hover:opacity-90",
1321
+ onClick: () => entry.uri != null ? window.open(entry.uri, "_blank", "noopener,noreferrer") : void 0,
1322
+ title: "Open generated image",
1323
+ children: /* @__PURE__ */ jsx("img", { src: entry.uri, alt: "Generated image", className: "max-h-[312px] w-full object-contain" })
1324
+ },
1325
+ `${entry.uri}:${index}`
1326
+ )) });
1327
+ }
1328
+ if (image.uri) {
1329
+ return /* @__PURE__ */ jsx(
1330
+ "button",
1331
+ {
1332
+ type: "button",
1333
+ className: "max-w-[85%] overflow-hidden rounded-md shadow-xs transition-opacity hover:opacity-90 sm:max-w-2xl",
1334
+ onClick: () => window.open(image.uri, "_blank", "noopener,noreferrer"),
1335
+ title: "Open generated image",
1336
+ children: /* @__PURE__ */ jsx("img", { src: image.uri, alt: "Generated image", className: "max-h-[312px] max-w-full object-contain" })
1337
+ }
1338
+ );
1339
+ }
1340
+ return /* @__PURE__ */ jsx("div", { className: "flex h-[240px] w-[240px] items-center justify-center rounded-md border bg-background text-muted-foreground", children: /* @__PURE__ */ jsxs("div", { className: "flex max-w-full flex-col items-center gap-2 px-3 text-center text-xs", children: [
1341
+ image.status === "failed" ? /* @__PURE__ */ jsx(ImageOff, { className: "h-5 w-5" }) : /* @__PURE__ */ jsx(Spinner, { className: "h-5 w-5" }),
1342
+ /* @__PURE__ */ jsx("span", { children: image.statusDetail ?? (image.status === "failed" ? "Image failed" : "Generating image") })
1343
+ ] }) });
1344
+ }
1345
+ function ThreadMessageView({
1346
+ room,
1347
+ message,
1348
+ previous,
1349
+ localParticipantName,
1350
+ agentName,
1351
+ forceHideHeader = false
1352
+ }) {
1353
+ if (message.kind === "error") {
1354
+ return /* @__PURE__ */ jsx("div", { className: "px-6 py-1 text-center text-sm text-destructive", children: message.text });
1355
+ }
1356
+ if (message.kind === "reasoning") {
1357
+ return /* @__PURE__ */ jsx(ReasoningTrace, { text: message.text });
1358
+ }
1359
+ if (message.kind === "event") {
1360
+ return /* @__PURE__ */ jsx(EventLine, { headline: message.text, state: message.state, failed: message.failed });
1361
+ }
1362
+ if (message.kind === "tool_call") {
1363
+ if (isShellTool(message)) {
1364
+ return /* @__PURE__ */ jsx(
1365
+ ShellLine,
1366
+ {
1367
+ command: message.command ?? message.text,
1368
+ result: message.result,
1369
+ stdout: message.stdout,
1370
+ stderr: message.stderr,
1371
+ argumentsText: message.argumentsText,
1372
+ logs: message.logs,
1373
+ title: message.failed === true ? "Terminal Error" : "Terminal",
1374
+ className: message.failed === true ? "border-destructive/40" : void 0
1375
+ }
1376
+ );
1377
+ }
1378
+ return /* @__PURE__ */ jsx(ToolCallLine, { message });
1379
+ }
1380
+ const mine = message.role === "user";
1381
+ const authorName = message.authorName ?? (mine ? localParticipantName : displayParticipantName(agentName));
1382
+ const previousAuthor = previous?.authorName ?? (previous?.role === "user" ? localParticipantName : displayParticipantName(agentName));
1383
+ const shouldShowHeader = !forceHideHeader && (previous?.kind !== "message" || previousAuthor !== authorName);
1384
+ return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2", children: [
1385
+ shouldShowHeader ? /* @__PURE__ */ jsx("div", { className: cn("flex w-full", mine ? "justify-end" : "justify-start"), children: /* @__PURE__ */ jsx("div", { className: cn("max-w-[85%] px-1 sm:max-w-2xl", mine ? "text-right" : "text-left"), children: /* @__PURE__ */ jsxs("div", { className: cn("flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground", mine ? "justify-end" : "justify-start"), children: [
1386
+ authorName.trim() !== "" ? /* @__PURE__ */ jsx("span", { className: "font-semibold text-foreground", children: displayParticipantName(authorName) }) : null,
1387
+ /* @__PURE__ */ jsx("span", { children: timeAgo(message.createdAt) })
1388
+ ] }) }) }) : null,
1389
+ message.text.trim() !== "" ? /* @__PURE__ */ jsx("div", { className: cn("flex w-full", mine ? "justify-end" : "justify-start"), children: /* @__PURE__ */ jsx(ChatBubble, { text: message.text, mine }) }) : null,
1390
+ message.attachments.length > 0 ? /* @__PURE__ */ jsx("div", { className: cn("flex w-full", mine ? "justify-end" : "justify-start"), children: /* @__PURE__ */ jsx("div", { className: 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__ */ jsx(AttachmentView, { room, path: attachment }, `${message.id}:attachment:${attachment}:${index}`)) }) }) : null,
1391
+ message.image ? /* @__PURE__ */ jsx("div", { className: "flex w-full justify-start", children: /* @__PURE__ */ jsx(GeneratedImageView, { image: message.image }) }) : null
1392
+ ] });
1393
+ }
1394
+ function EmptyState({ title, description }) {
1395
+ return /* @__PURE__ */ jsxs("div", { className: "mx-auto flex h-full max-w-2xl flex-col items-center justify-center px-6 py-20 text-center", children: [
1396
+ /* @__PURE__ */ jsx("h2", { className: "text-4xl font-semibold tracking-tight text-foreground sm:text-5xl", children: title }),
1397
+ description?.trim() ? /* @__PURE__ */ jsx("p", { className: "mt-3 max-w-xl text-sm leading-6 text-muted-foreground sm:text-base", children: description }) : null
1398
+ ] });
1399
+ }
1400
+ function LoadingState() {
1401
+ 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
+ }
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 });
1405
+ }
1406
+ function describeError(error) {
1407
+ if (error instanceof Error && error.message.trim() !== "") {
1408
+ return error.message;
1409
+ }
1410
+ return String(error);
1411
+ }
1412
+ function normalizeAgentAttachmentUrl(path) {
1413
+ const trimmedPath = path.trim();
1414
+ if (trimmedPath === "") {
1415
+ return null;
1416
+ }
1417
+ try {
1418
+ const parsed = new URL(trimmedPath);
1419
+ if (parsed.protocol !== "") {
1420
+ return trimmedPath;
1421
+ }
1422
+ } catch {
1423
+ }
1424
+ const roomPath = trimmedPath.startsWith("/") ? trimmedPath.slice(1) : trimmedPath;
1425
+ return roomPath === "" ? null : `room:///${roomPath}`;
1426
+ }
1427
+ function AgentThread({
1428
+ room,
1429
+ path,
1430
+ chatClient,
1431
+ disposeChatClient = false,
1432
+ agentName,
1433
+ emptyStateTitle = "Chat to get started",
1434
+ emptyStateDescription,
1435
+ clientToolkits,
1436
+ toolChoice,
1437
+ collapseMessages = true
1438
+ }) {
1439
+ const [attachments, setAttachments] = useState([]);
1440
+ const [sendError, setSendError] = useState(null);
1441
+ const [version, setVersion] = useState(0);
1442
+ const [expandedDetailGroupIds, setExpandedDetailGroupIds] = useState(() => /* @__PURE__ */ new Set());
1443
+ const scrollContainerRef = useRef(null);
1444
+ const contentRef = useRef(null);
1445
+ const stickToBottomRef = useRef(true);
1446
+ const sessionRef = useRef(null);
1447
+ const ownsChatClient = chatClient == null;
1448
+ const activeChatClient = useMemo(
1449
+ () => chatClient ?? new MessagingChatClient({ room, agentName }),
1450
+ [agentName, chatClient, room]
1451
+ );
1452
+ const localParticipantName = getParticipantName(room.localParticipant);
1453
+ const agentParticipant = activeChatClient.agentParticipant() ?? findAgentParticipant(room, agentName);
1454
+ useEffect(() => {
1455
+ void activeChatClient.start();
1456
+ const handleChange = () => {
1457
+ setVersion((current) => current + 1);
1458
+ };
1459
+ activeChatClient.addListener(handleChange);
1460
+ return () => {
1461
+ activeChatClient.removeListener(handleChange);
1462
+ if (ownsChatClient || disposeChatClient) {
1463
+ void activeChatClient.stop();
1464
+ }
1465
+ };
1466
+ }, [activeChatClient, disposeChatClient, ownsChatClient]);
1467
+ useEffect(() => {
1468
+ const session2 = activeChatClient.openThread(path);
1469
+ sessionRef.current = session2;
1470
+ const handleChange = () => {
1471
+ setVersion((current) => current + 1);
1472
+ };
1473
+ session2.addListener(handleChange);
1474
+ handleChange();
1475
+ return () => {
1476
+ session2.removeListener(handleChange);
1477
+ if (sessionRef.current === session2) {
1478
+ sessionRef.current = null;
1479
+ }
1480
+ };
1481
+ }, [activeChatClient, path]);
1482
+ const normalizedPath = path.trim();
1483
+ 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;
1498
+ }
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;
1506
+ }
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;
1514
+ }
1515
+ const observer = new ResizeObserver(() => {
1516
+ if (stickToBottomRef.current) {
1517
+ container.scrollTop = container.scrollHeight;
1518
+ }
1519
+ });
1520
+ observer.observe(content);
1521
+ return () => {
1522
+ observer.disconnect();
1523
+ };
1524
+ }, []);
1525
+ const selectAttachments = useCallback((files) => {
1526
+ const nextAttachments = files.map((file) => new MeshagentFileUpload(
1527
+ room,
1528
+ `uploaded-files/${file.name}`,
1529
+ fileToAsyncIterable(file),
1530
+ file.size
1531
+ ));
1532
+ setAttachments((current) => [...current, ...nextAttachments]);
1533
+ }, [room]);
1534
+ const handleSend = useCallback(async (message) => {
1535
+ if (message.text.trim() === "" && message.attachments.length === 0) {
1536
+ return;
1537
+ }
1538
+ if (!agentParticipant && chatClient == null) {
1539
+ setSendError("This thread requires an online agent that supports agent messages.");
1540
+ return;
1541
+ }
1542
+ const openSession = sessionRef.current;
1543
+ if (openSession === null) {
1544
+ setSendError("No thread session is open.");
1545
+ return;
1546
+ }
1547
+ const normalizedAttachments = message.attachments.map(normalizeAgentAttachmentUrl).filter((attachment) => attachment !== null);
1548
+ try {
1549
+ await openSession.sendText({
1550
+ messageId: message.id,
1551
+ text: message.text,
1552
+ attachments: normalizedAttachments,
1553
+ turnId,
1554
+ steer: status?.mode === "steerable" && turnId != null,
1555
+ senderName: localParticipantName.trim() || void 0,
1556
+ clientToolkits,
1557
+ toolChoice: toolChoice == null ? void 0 : new ToolChoice({ toolkitName: toolChoice.toolkitName, toolName: toolChoice.toolName })
1558
+ });
1559
+ setSendError(null);
1560
+ setVersion((current) => current + 1);
1561
+ } catch (error) {
1562
+ setSendError(describeError(error));
1563
+ }
1564
+ }, [agentParticipant, chatClient, clientToolkits, localParticipantName, status?.mode, toolChoice, turnId]);
1565
+ const cancelTurn = useCallback(async () => {
1566
+ const openSession = sessionRef.current;
1567
+ if (openSession === null || turnId == null) {
1568
+ return;
1569
+ }
1570
+ await openSession.interruptTurn(turnId);
1571
+ }, [turnId]);
1572
+ const toggleDetailGroup = useCallback((id) => {
1573
+ setExpandedDetailGroupIds((current) => {
1574
+ const next = new Set(current);
1575
+ if (next.has(id)) {
1576
+ next.delete(id);
1577
+ } else {
1578
+ next.add(id);
1579
+ }
1580
+ return next;
1581
+ });
1582
+ }, []);
1583
+ return /* @__PURE__ */ jsxs("div", { className: "flex h-full min-h-0 flex-1 flex-col", children: [
1584
+ /* @__PURE__ */ jsxs("div", { className: "relative flex h-full min-h-0 flex-1 flex-col", children: [
1585
+ /* @__PURE__ */ jsx(
1586
+ "div",
1587
+ {
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
+ )
1634
+ }
1635
+ ),
1636
+ 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(
1637
+ ChatTypingIndicator,
1638
+ {
1639
+ typing: false,
1640
+ thinking: false,
1641
+ statusText,
1642
+ startedAt: dateFromString(status?.startedAt),
1643
+ totalBytes: status?.totalBytes,
1644
+ linesAdded: status?.linesAdded,
1645
+ linesRemoved: status?.linesRemoved,
1646
+ onCancel: canInterruptActiveTurn ? cancelTurn : void 0,
1647
+ showCancelButton: status?.mode != null,
1648
+ cancelEnabled: true
1649
+ }
1650
+ ) }) }) : null
1651
+ ] }),
1652
+ sendError ? /* @__PURE__ */ jsx("div", { className: "px-4 pb-2", children: /* @__PURE__ */ jsx(ErrorBanner, { message: sendError }) }) : null,
1653
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
1654
+ /* @__PURE__ */ jsx(
1655
+ ChatInput,
1656
+ {
1657
+ onSubmit: handleSend,
1658
+ attachments,
1659
+ onFilesSelected: selectAttachments,
1660
+ setAttachments,
1661
+ disabled: agentParticipant == null && chatClient == null,
1662
+ placeholder: agentParticipant || chatClient ? "Type a message" : `Waiting for ${displayParticipantName(agentName)}`
1663
+ }
1664
+ ),
1665
+ /* @__PURE__ */ jsx(AgentUsageFooter, { usage, className: "mx-auto w-full max-w-[912px]" })
1666
+ ] })
1667
+ ] });
1668
+ }
1669
+ export {
1670
+ AgentThread,
1671
+ AgentToolChoice,
1672
+ AgentUsageFooter,
1673
+ AgentUsageSnapshot,
1674
+ ChatThreadPreview,
1675
+ EventLine,
1676
+ ReasoningTrace,
1677
+ ShellLine,
1678
+ formatAgentUsageFooter,
1679
+ formatAgentUsageTokenCount,
1680
+ formatAgentUsageTooltip,
1681
+ shouldReplaceAgentUsageSnapshot
1682
+ };