@meshagent/meshagent-tailwind 0.43.3 → 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 (95) hide show
  1. package/CHANGELOG.md +11 -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 +76 -4
  5. package/dist/cjs/chat/agent-thread.js +1114 -54
  6. package/dist/cjs/chat/chat-bot-view.d.ts +7 -4
  7. package/dist/cjs/chat/chat-bot-view.js +33 -525
  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 +3 -1
  15. package/dist/cjs/chat/multi-thread-view.js +4 -2
  16. package/dist/cjs/chat/new-chat-thread.d.ts +3 -1
  17. package/dist/cjs/chat/new-chat-thread.js +7 -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 +41 -5
  40. package/dist/cjs/index.d.ts +3 -0
  41. package/dist/cjs/index.js +13 -0
  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 +76 -4
  49. package/dist/esm/chat/agent-thread.js +1132 -56
  50. package/dist/esm/chat/chat-bot-view.d.ts +7 -4
  51. package/dist/esm/chat/chat-bot-view.js +40 -555
  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 +3 -1
  59. package/dist/esm/chat/multi-thread-view.js +4 -2
  60. package/dist/esm/chat/new-chat-thread.d.ts +3 -1
  61. package/dist/esm/chat/new-chat-thread.js +8 -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 +29 -3
  84. package/dist/esm/index.d.ts +3 -0
  85. package/dist/esm/index.js +9 -0
  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 +4 -4
  92. package/dist/cjs/chat/chat-bot-view.test.js +0 -325
  93. package/dist/cjs/chat/live-chat-widgets.test.js +0 -256
  94. package/dist/esm/chat/chat-bot-view.test.js +0 -336
  95. package/dist/esm/chat/live-chat-widgets.test.js +0 -262
@@ -28,7 +28,18 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
29
  var agent_thread_exports = {};
30
30
  __export(agent_thread_exports, {
31
- AgentThread: () => AgentThread
31
+ AgentThread: () => AgentThread,
32
+ AgentToolChoice: () => AgentToolChoice,
33
+ AgentUsageFooter: () => AgentUsageFooter,
34
+ AgentUsageSnapshot: () => AgentUsageSnapshot,
35
+ ChatThreadPreview: () => ChatThreadPreview,
36
+ EventLine: () => EventLine,
37
+ ReasoningTrace: () => ReasoningTrace,
38
+ ShellLine: () => ShellLine,
39
+ formatAgentUsageFooter: () => formatAgentUsageFooter,
40
+ formatAgentUsageTokenCount: () => formatAgentUsageTokenCount,
41
+ formatAgentUsageTooltip: () => formatAgentUsageTooltip,
42
+ shouldReplaceAgentUsageSnapshot: () => shouldReplaceAgentUsageSnapshot
32
43
  });
33
44
  module.exports = __toCommonJS(agent_thread_exports);
34
45
  var import_jsx_runtime = require("react/jsx-runtime");
@@ -39,12 +50,175 @@ var import_react_markdown = __toESM(require("react-markdown"));
39
50
  var import_rehype_highlight = __toESM(require("rehype-highlight"));
40
51
  var import_rehype_sanitize = __toESM(require("rehype-sanitize"));
41
52
  var import_remark_gfm = __toESM(require("remark-gfm"));
42
- var import_spinner = require("../components/ui/spinner.js");
43
- var import_utils = require("../lib/utils.js");
44
- var import_chat_input = require("./chat-input.js");
45
- var import_chat_typing_indicator = require("./chat-typing-indicator.js");
46
- var import_file_attachment = require("./file-attachment.js");
53
+ var import_spinner = require("../components/ui/spinner");
54
+ var import_utils = require("../lib/utils");
55
+ var import_chat_input = require("./chat-input");
56
+ var import_chat_typing_indicator = require("./chat-typing-indicator");
57
+ var import_file_attachment = require("./file-attachment");
58
+ var import_file_preview = require("../file-preview/file-preview.js");
47
59
  const stickyBottomThresholdPx = 24;
60
+ class AgentToolChoice {
61
+ toolkitName;
62
+ toolName;
63
+ constructor({ toolkitName, toolName }) {
64
+ this.toolkitName = toolkitName;
65
+ this.toolName = toolName;
66
+ }
67
+ toJson() {
68
+ return { toolkit_name: this.toolkitName, tool_name: this.toolName };
69
+ }
70
+ }
71
+ function finiteNumber(value) {
72
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
73
+ }
74
+ function integerNumber(value) {
75
+ const numeric = finiteNumber(value);
76
+ return numeric == null ? null : Math.trunc(numeric);
77
+ }
78
+ function usageKeyMatches(key, names) {
79
+ for (const name of names) {
80
+ if (key === name || key.endsWith(`.${name}`)) {
81
+ return true;
82
+ }
83
+ }
84
+ return false;
85
+ }
86
+ function sumUsageKeys(rawUsage, names) {
87
+ let total = 0;
88
+ let found = false;
89
+ for (const [key, value] of Object.entries(rawUsage)) {
90
+ if (!usageKeyMatches(key, names)) {
91
+ continue;
92
+ }
93
+ const numeric = finiteNumber(value);
94
+ if (numeric == null) {
95
+ continue;
96
+ }
97
+ total += numeric;
98
+ found = true;
99
+ }
100
+ return found ? total : null;
101
+ }
102
+ function usageTotalTokens(rawUsage) {
103
+ const explicitTotal = sumUsageKeys(rawUsage, /* @__PURE__ */ new Set(["total_tokens"]));
104
+ if (explicitTotal != null) {
105
+ return explicitTotal;
106
+ }
107
+ const inputTokens = sumUsageKeys(rawUsage, /* @__PURE__ */ new Set([
108
+ "input_tokens",
109
+ "audio_input_tokens",
110
+ "image_input_tokens",
111
+ "cache_creation_input_tokens",
112
+ "cache_read_input_tokens"
113
+ ]));
114
+ const outputTokens = sumUsageKeys(rawUsage, /* @__PURE__ */ new Set(["output_tokens", "audio_output_tokens", "image_output_tokens"]));
115
+ const cachedTokens = sumUsageKeys(rawUsage, /* @__PURE__ */ new Set(["cached_tokens", "audio_cached_tokens", "image_cached_tokens"]));
116
+ const reasoningTokens = sumUsageKeys(rawUsage, /* @__PURE__ */ new Set(["reasoning_tokens"]));
117
+ let total = 0;
118
+ let hasTotal = false;
119
+ if (inputTokens != null) {
120
+ total += inputTokens;
121
+ hasTotal = true;
122
+ } else if (cachedTokens != null) {
123
+ total += cachedTokens;
124
+ hasTotal = true;
125
+ }
126
+ if (outputTokens != null) {
127
+ total += outputTokens;
128
+ hasTotal = true;
129
+ } else if (reasoningTokens != null) {
130
+ total += reasoningTokens;
131
+ hasTotal = true;
132
+ }
133
+ return hasTotal ? total : null;
134
+ }
135
+ function usageValues(rawUsage) {
136
+ const usage = {};
137
+ for (const [key, value] of Object.entries(rawUsage)) {
138
+ const trimmedKey = key.trim();
139
+ const numeric = finiteNumber(value);
140
+ if (trimmedKey === "" || numeric == null) {
141
+ continue;
142
+ }
143
+ usage[trimmedKey] = numeric;
144
+ }
145
+ return Object.freeze(usage);
146
+ }
147
+ class AgentUsageSnapshot {
148
+ threadPath;
149
+ turnId;
150
+ contextUsedTokens;
151
+ contextTotalTokens;
152
+ compactionMode;
153
+ compactionThreshold;
154
+ totalTokens;
155
+ usage;
156
+ constructor({
157
+ threadPath,
158
+ turnId,
159
+ contextUsedTokens,
160
+ contextTotalTokens,
161
+ compactionMode,
162
+ compactionThreshold,
163
+ totalTokens,
164
+ usage
165
+ }) {
166
+ this.threadPath = threadPath;
167
+ this.turnId = turnId;
168
+ this.contextUsedTokens = contextUsedTokens;
169
+ this.contextTotalTokens = contextTotalTokens;
170
+ this.compactionMode = compactionMode;
171
+ this.compactionThreshold = compactionThreshold;
172
+ this.totalTokens = totalTokens;
173
+ this.usage = Object.freeze({ ...usage });
174
+ }
175
+ static fromMessage(message) {
176
+ if (!isTypedMessage(message, import_meshagent_agents.AgentUsageUpdated)) {
177
+ return null;
178
+ }
179
+ return AgentUsageSnapshot.fromPayload(message.toJson());
180
+ }
181
+ static fromPayload(payload) {
182
+ if (payload.type !== "meshagent.agent.usage.updated") {
183
+ return null;
184
+ }
185
+ const rawThreadPath = payload.thread_id;
186
+ if (typeof rawThreadPath !== "string" || rawThreadPath.trim() === "") {
187
+ return null;
188
+ }
189
+ const rawContextWindow = payload.context_window;
190
+ if (rawContextWindow == null || typeof rawContextWindow !== "object") {
191
+ return null;
192
+ }
193
+ const contextWindow = rawContextWindow;
194
+ const usedTokens = integerNumber(contextWindow.used_tokens);
195
+ if (usedTokens == null) {
196
+ return null;
197
+ }
198
+ const totalContextTokens = contextWindow.total_tokens == null ? void 0 : integerNumber(contextWindow.total_tokens) ?? void 0;
199
+ const rawCompactionMode = contextWindow.compaction_mode;
200
+ const compactionMode = typeof rawCompactionMode === "string" && rawCompactionMode.trim() !== "" ? rawCompactionMode.trim() : void 0;
201
+ const compactionThreshold = contextWindow.compaction_threshold == null ? void 0 : integerNumber(contextWindow.compaction_threshold) ?? void 0;
202
+ const rawUsage = payload.usage != null && typeof payload.usage === "object" ? payload.usage : {};
203
+ const rawTurnId = payload.turn_id;
204
+ return new AgentUsageSnapshot({
205
+ threadPath: rawThreadPath.trim(),
206
+ turnId: typeof rawTurnId === "string" && rawTurnId.trim() !== "" ? rawTurnId.trim() : void 0,
207
+ contextUsedTokens: usedTokens,
208
+ contextTotalTokens: totalContextTokens,
209
+ compactionMode,
210
+ compactionThreshold,
211
+ totalTokens: usageTotalTokens(rawUsage) ?? void 0,
212
+ usage: usageValues(rawUsage)
213
+ });
214
+ }
215
+ }
216
+ function shouldReplaceAgentUsageSnapshot(current, next) {
217
+ if (current != null && current.contextUsedTokens > 0 && next.contextUsedTokens === 0 && Object.keys(next.usage).length === 0) {
218
+ return false;
219
+ }
220
+ return true;
221
+ }
48
222
  function isTypedMessage(message, ctor) {
49
223
  return message instanceof ctor;
50
224
  }
@@ -171,6 +345,197 @@ function imageStatus(message) {
171
345
  }
172
346
  return "in_progress";
173
347
  }
348
+ function agentErrorIsCancellation(error) {
349
+ const values = [error.code, error.message].filter((value) => typeof value === "string");
350
+ return values.some((value) => {
351
+ const normalized = value.trim().toLowerCase();
352
+ return normalized.includes("cancel") || normalized.includes("interrupt") || normalized.includes("abort");
353
+ });
354
+ }
355
+ function toolCallLabel(message) {
356
+ return [message.toolkit, message.tool].filter((part) => part?.trim()).join(".") || "Tool call";
357
+ }
358
+ function toolArgumentString(argumentsValue, keys) {
359
+ if (argumentsValue == null) {
360
+ return void 0;
361
+ }
362
+ for (const key of keys) {
363
+ const value = argumentsValue[key];
364
+ if (typeof value === "string" && value.trim() !== "") {
365
+ return value.trim();
366
+ }
367
+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) {
368
+ const joined = value.join(" ").trim();
369
+ if (joined !== "") {
370
+ return joined;
371
+ }
372
+ }
373
+ }
374
+ return void 0;
375
+ }
376
+ function toolCommandText(message) {
377
+ return toolArgumentString(message.arguments, ["command", "cmd", "script", "input", "query"]);
378
+ }
379
+ function contentText(value) {
380
+ if (typeof value === "string" && value.trim() !== "") {
381
+ return value.trim();
382
+ }
383
+ if (value == null || typeof value !== "object") {
384
+ return void 0;
385
+ }
386
+ const obj = value;
387
+ for (const key of ["text", "result", "output", "stdout", "stderr"]) {
388
+ const candidate = obj[key];
389
+ if (typeof candidate === "string" && candidate.trim() !== "") {
390
+ return candidate.trim();
391
+ }
392
+ }
393
+ const json = obj["json"];
394
+ if (json != null) {
395
+ return JSON.stringify(json, null, 2);
396
+ }
397
+ return void 0;
398
+ }
399
+ function shellOutputFields(message) {
400
+ const result = message.result;
401
+ const resultObject = result != null && typeof result === "object" ? result : void 0;
402
+ return {
403
+ result: contentText(result),
404
+ stdout: resultObject == null ? void 0 : contentText(resultObject["stdout"]),
405
+ stderr: message.error?.message.trim() || (resultObject == null ? void 0 : contentText(resultObject["stderr"]))
406
+ };
407
+ }
408
+ function formatJsonValue(value) {
409
+ if (value == null) {
410
+ return void 0;
411
+ }
412
+ try {
413
+ return JSON.stringify(value, null, 2);
414
+ } catch {
415
+ return void 0;
416
+ }
417
+ }
418
+ function toolArgumentsText(argumentsValue) {
419
+ return argumentsValue == null ? void 0 : formatJsonValue(argumentsValue);
420
+ }
421
+ function appendToolArgumentsDelta(existing, delta) {
422
+ if (delta.trim() === "") {
423
+ return existing?.argumentsText;
424
+ }
425
+ return `${existing?.argumentsText ?? ""}${delta}`;
426
+ }
427
+ function formatToolLogLine(line) {
428
+ const text = line.text.trim();
429
+ if (text === "") {
430
+ return null;
431
+ }
432
+ const source = line.source.trim();
433
+ return source === "" ? text : `${source}: ${text}`;
434
+ }
435
+ function appendToolLogs(existing, lines) {
436
+ const logs = [...existing?.logs ?? []];
437
+ for (const line of lines) {
438
+ const formatted = formatToolLogLine(line);
439
+ if (formatted !== null) {
440
+ logs.push(formatted);
441
+ }
442
+ }
443
+ return logs;
444
+ }
445
+ function toolCallState(message) {
446
+ if (isTypedMessage(message, import_meshagent_agents.AgentToolCallEnded)) {
447
+ return message.error == null ? "completed" : "failed";
448
+ }
449
+ if (isTypedMessage(message, import_meshagent_agents.AgentToolCallPending)) {
450
+ return "queued";
451
+ }
452
+ return "in_progress";
453
+ }
454
+ function toolCallHeadline(message) {
455
+ const label = toolCallLabel(message);
456
+ if (toolCallFailed(message)) {
457
+ return `Failed ${label}`;
458
+ }
459
+ if (isTypedMessage(message, import_meshagent_agents.AgentToolCallPending)) {
460
+ return `Preparing ${label}`;
461
+ }
462
+ if (isTypedMessage(message, import_meshagent_agents.AgentToolCallEnded)) {
463
+ return `Ran ${label}`;
464
+ }
465
+ return `Running ${label}`;
466
+ }
467
+ function modelChangedText(message) {
468
+ const model = [message.provider, message.model].filter((part) => part.trim() !== "").join(" / ");
469
+ const voice = message.voice?.trim();
470
+ return voice ? `Model changed to ${model} (${voice})` : `Model changed to ${model}`;
471
+ }
472
+ function rejectionText(message, fallback) {
473
+ const error = message.error?.message.trim();
474
+ return error ? `${fallback}: ${error}` : fallback;
475
+ }
476
+ function lifecycleEventItem(message, createdAt) {
477
+ const turnId = stringValue(message.turnId);
478
+ const base = {
479
+ id: ["event", message.type, turnId ?? message.sourceMessageId ?? message.messageId].join(":"),
480
+ kind: "event",
481
+ role: "agent",
482
+ attachments: [],
483
+ createdAt,
484
+ turnId
485
+ };
486
+ if (isTypedMessage(message, import_meshagent_agents.TurnStartAccepted)) {
487
+ return { ...base, text: "Turn accepted", state: "queued" };
488
+ }
489
+ if (isTypedMessage(message, import_meshagent_agents.TurnStarted)) {
490
+ return { ...base, text: "Turn started", state: "running" };
491
+ }
492
+ if (isTypedMessage(message, import_meshagent_agents.TurnStartRejected)) {
493
+ return { ...base, text: rejectionText(message, "Turn rejected"), state: "failed", failed: true };
494
+ }
495
+ if (isTypedMessage(message, import_meshagent_agents.TurnSteerAccepted)) {
496
+ return { ...base, text: "Steer accepted", state: "queued" };
497
+ }
498
+ if (isTypedMessage(message, import_meshagent_agents.TurnSteered)) {
499
+ return { ...base, text: "Turn steered", state: "running" };
500
+ }
501
+ if (isTypedMessage(message, import_meshagent_agents.TurnSteerRejected)) {
502
+ return { ...base, text: rejectionText(message, "Steer rejected"), state: "failed", failed: true };
503
+ }
504
+ if (isTypedMessage(message, import_meshagent_agents.TurnInterruptAccepted)) {
505
+ return { ...base, text: "Interrupt accepted", state: "cancelled" };
506
+ }
507
+ if (isTypedMessage(message, import_meshagent_agents.TurnInterrupted)) {
508
+ return { ...base, text: "Turn interrupted", state: "cancelled" };
509
+ }
510
+ return null;
511
+ }
512
+ function isShellTool(message) {
513
+ const values = [message.toolkit, message.tool].filter((value) => typeof value === "string").map((value) => value.trim().toLowerCase());
514
+ return message.command != null || values.some((value) => value === "shell" || value === "exec" || value === "local_shell" || value === "local_shell_call" || value.includes("shell") || value.includes("exec"));
515
+ }
516
+ function toolCallFailed(message) {
517
+ return isTypedMessage(message, import_meshagent_agents.AgentToolCallEnded) && message.error != null;
518
+ }
519
+ function turnEndedErrorItem(message, createdAt) {
520
+ const error = message.error;
521
+ if (error == null || agentErrorIsCancellation(error)) {
522
+ return null;
523
+ }
524
+ const text = error.message.trim();
525
+ if (text === "") {
526
+ return null;
527
+ }
528
+ const turnId = stringValue(message.turnId);
529
+ return {
530
+ id: ["turn-error", turnId ?? message.messageId].join(":"),
531
+ kind: "error",
532
+ role: "agent",
533
+ text,
534
+ attachments: [],
535
+ createdAt,
536
+ turnId
537
+ };
538
+ }
174
539
  function feedFromSession(session) {
175
540
  if (session === null) {
176
541
  return [];
@@ -178,12 +543,29 @@ function feedFromSession(session) {
178
543
  const items = /* @__PURE__ */ new Map();
179
544
  for (const event of session.messages) {
180
545
  const message = event.message;
181
- const createdAt = /* @__PURE__ */ new Date();
546
+ const createdAt = event.createdAt;
182
547
  const inputItem = inputItemFromMessage(message, createdAt);
183
548
  if (inputItem !== null && !items.has(inputItem.id)) {
184
549
  upsertItem(items, inputItem);
185
550
  continue;
186
551
  }
552
+ const lifecycleItem = lifecycleEventItem(message, createdAt);
553
+ if (lifecycleItem !== null) {
554
+ upsertItem(items, lifecycleItem);
555
+ continue;
556
+ }
557
+ if (isTypedMessage(message, import_meshagent_agents.AgentModelChanged)) {
558
+ upsertItem(items, {
559
+ id: ["model", message.messageId].join(":"),
560
+ kind: "event",
561
+ role: "agent",
562
+ text: modelChangedText(message),
563
+ attachments: [],
564
+ createdAt,
565
+ state: "completed"
566
+ });
567
+ continue;
568
+ }
187
569
  if (isTypedMessage(message, import_meshagent_agents.AgentTextContentStarted)) {
188
570
  upsertItem(items, {
189
571
  id: message.itemId,
@@ -191,14 +573,18 @@ function feedFromSession(session) {
191
573
  role: "agent",
192
574
  text: "",
193
575
  attachments: [],
194
- createdAt
576
+ createdAt,
577
+ phase: message.phase,
578
+ turnId: message.turnId
195
579
  });
196
580
  } else if (isTypedMessage(message, import_meshagent_agents.AgentTextContentDelta)) {
197
581
  appendText(items, message.itemId, {
198
582
  id: message.itemId,
199
583
  kind: "message",
200
584
  role: "agent",
201
- createdAt
585
+ createdAt,
586
+ phase: message.phase,
587
+ turnId: message.turnId
202
588
  }, message.text);
203
589
  } else if (isTypedMessage(message, import_meshagent_agents.AgentTextContentEnded)) {
204
590
  if (!items.has(message.itemId)) {
@@ -208,7 +594,9 @@ function feedFromSession(session) {
208
594
  role: "agent",
209
595
  text: "",
210
596
  attachments: [],
211
- createdAt
597
+ createdAt,
598
+ phase: message.phase,
599
+ turnId: message.turnId
212
600
  });
213
601
  }
214
602
  } else if (isTypedMessage(message, import_meshagent_agents.AgentReasoningContentStarted)) {
@@ -218,14 +606,16 @@ function feedFromSession(session) {
218
606
  role: "agent",
219
607
  text: "",
220
608
  attachments: [],
221
- createdAt
609
+ createdAt,
610
+ turnId: message.turnId
222
611
  });
223
612
  } else if (isTypedMessage(message, import_meshagent_agents.AgentReasoningContentDelta)) {
224
613
  appendText(items, message.itemId, {
225
614
  id: message.itemId,
226
615
  kind: "reasoning",
227
616
  role: "agent",
228
- createdAt
617
+ createdAt,
618
+ turnId: message.turnId
229
619
  }, message.text);
230
620
  } else if (isTypedMessage(message, import_meshagent_agents.AgentReasoningContentEnded)) {
231
621
  if (!items.has(message.itemId)) {
@@ -235,13 +625,14 @@ function feedFromSession(session) {
235
625
  role: "agent",
236
626
  text: "",
237
627
  attachments: [],
238
- createdAt
628
+ createdAt,
629
+ turnId: message.turnId
239
630
  });
240
631
  }
241
- } else if (isTypedMessage(message, import_meshagent_agents.AgentFileContentDelta)) {
632
+ } else if (isTypedMessage(message, import_meshagent_agents.AgentFileContentStarted) || isTypedMessage(message, import_meshagent_agents.AgentFileContentDelta) || isTypedMessage(message, import_meshagent_agents.AgentFileContentEnded)) {
242
633
  const existing = items.get(message.itemId);
243
- const attachments = existing?.attachments ?? [];
244
- if (!attachments.includes(message.url)) {
634
+ const attachments = [...existing?.attachments ?? []];
635
+ if (isTypedMessage(message, import_meshagent_agents.AgentFileContentDelta) && !attachments.includes(message.url)) {
245
636
  attachments.push(message.url);
246
637
  }
247
638
  upsertItem(items, {
@@ -250,19 +641,106 @@ function feedFromSession(session) {
250
641
  role: "agent",
251
642
  text: existing?.text ?? "",
252
643
  attachments,
253
- createdAt
644
+ createdAt,
645
+ turnId: message.turnId,
646
+ state: isTypedMessage(message, import_meshagent_agents.AgentFileContentEnded) ? "completed" : "in_progress"
254
647
  });
255
648
  } else if (isTypedMessage(message, import_meshagent_agents.AgentToolCallPending) || isTypedMessage(message, import_meshagent_agents.AgentToolCallInProgress) || isTypedMessage(message, import_meshagent_agents.AgentToolCallStarted) || isTypedMessage(message, import_meshagent_agents.AgentToolCallEnded)) {
649
+ const existing = items.get(message.itemId);
650
+ const command = toolCommandText(message) ?? existing?.command;
651
+ const endedFields = isTypedMessage(message, import_meshagent_agents.AgentToolCallEnded) ? shellOutputFields(message) : {};
652
+ const argumentsText = toolArgumentsText(message.arguments) ?? existing?.argumentsText;
653
+ upsertItem(items, {
654
+ id: message.itemId,
655
+ kind: "tool_call",
656
+ role: "agent",
657
+ text: toolCallHeadline(message),
658
+ attachments: [],
659
+ createdAt,
660
+ turnId: message.turnId,
661
+ toolkit: message.toolkit ?? existing?.toolkit,
662
+ tool: message.tool ?? existing?.tool,
663
+ command,
664
+ argumentsText,
665
+ logs: existing?.logs,
666
+ result: endedFields.result ?? existing?.result,
667
+ stdout: endedFields.stdout ?? existing?.stdout,
668
+ stderr: endedFields.stderr ?? existing?.stderr,
669
+ state: toolCallState(message),
670
+ failed: toolCallFailed(message)
671
+ });
672
+ } else if (isTypedMessage(message, import_meshagent_agents.AgentToolCallArgumentsDelta)) {
673
+ const existing = items.get(message.itemId);
674
+ upsertItem(items, {
675
+ id: message.itemId,
676
+ kind: "tool_call",
677
+ role: "agent",
678
+ text: existing?.text ?? "Running tool",
679
+ attachments: [],
680
+ createdAt,
681
+ turnId: message.turnId,
682
+ toolkit: existing?.toolkit,
683
+ tool: existing?.tool,
684
+ command: existing?.command,
685
+ argumentsText: appendToolArgumentsDelta(existing, message.delta),
686
+ logs: existing?.logs,
687
+ result: existing?.result,
688
+ stdout: existing?.stdout,
689
+ stderr: existing?.stderr,
690
+ state: existing?.state ?? "in_progress",
691
+ failed: existing?.failed
692
+ });
693
+ } else if (isTypedMessage(message, import_meshagent_agents.AgentToolCallLogDelta)) {
694
+ const existing = items.get(message.itemId);
256
695
  upsertItem(items, {
257
696
  id: message.itemId,
258
697
  kind: "tool_call",
259
698
  role: "agent",
260
- text: [message.toolkit, message.tool].filter((part) => part?.trim()).join(".") || "Tool call",
699
+ text: existing?.text ?? "Running tool",
261
700
  attachments: [],
262
- createdAt
701
+ createdAt,
702
+ turnId: message.turnId,
703
+ toolkit: existing?.toolkit,
704
+ tool: existing?.tool,
705
+ command: existing?.command,
706
+ argumentsText: existing?.argumentsText,
707
+ logs: appendToolLogs(existing, message.lines),
708
+ result: existing?.result,
709
+ stdout: existing?.stdout,
710
+ stderr: existing?.stderr,
711
+ state: existing?.state ?? "in_progress",
712
+ failed: existing?.failed
713
+ });
714
+ } else if (isTypedMessage(message, import_meshagent_agents.AgentClientToolCallRequested)) {
715
+ const argumentsText = toolArgumentsText(message.arguments);
716
+ upsertItem(items, {
717
+ id: message.itemId,
718
+ kind: "tool_call",
719
+ role: "agent",
720
+ text: "Waiting for client tool " + toolCallLabel(message),
721
+ attachments: [],
722
+ createdAt,
723
+ turnId: message.turnId,
724
+ toolkit: message.toolkit,
725
+ tool: message.tool,
726
+ argumentsText,
727
+ state: "queued"
728
+ });
729
+ } else if (isTypedMessage(message, import_meshagent_agents.AgentSecretRequested)) {
730
+ const scope = message.scope?.trim();
731
+ upsertItem(items, {
732
+ id: message.itemId,
733
+ kind: "event",
734
+ role: "agent",
735
+ text: scope ? "Secret requested: " + message.name + " (" + scope + ")" : "Secret requested: " + message.name,
736
+ attachments: [],
737
+ createdAt,
738
+ turnId: message.turnId,
739
+ state: "queued"
263
740
  });
264
741
  } else if (isTypedMessage(message, import_meshagent_agents.AgentImageGenerationStarted) || isTypedMessage(message, import_meshagent_agents.AgentImageGenerationPartial) || isTypedMessage(message, import_meshagent_agents.AgentImageGenerationCompleted) || isTypedMessage(message, import_meshagent_agents.AgentImageGenerationFailed)) {
265
- const image = isTypedMessage(message, import_meshagent_agents.AgentImageGenerationPartial) ? message.image : isTypedMessage(message, import_meshagent_agents.AgentImageGenerationCompleted) ? message.images[0] : void 0;
742
+ const images = isTypedMessage(message, import_meshagent_agents.AgentImageGenerationCompleted) ? message.images : [];
743
+ const image = isTypedMessage(message, import_meshagent_agents.AgentImageGenerationPartial) ? message.image : images[0];
266
744
  upsertItem(items, {
267
745
  id: message.itemId,
268
746
  kind: "image_generation",
@@ -270,12 +748,19 @@ function feedFromSession(session) {
270
748
  text: "",
271
749
  attachments: [],
272
750
  createdAt,
751
+ turnId: message.turnId,
273
752
  image: {
274
753
  uri: image?.uri,
275
754
  status: image?.status ?? imageStatus(message),
276
- statusDetail: isTypedMessage(message, import_meshagent_agents.AgentImageGenerationFailed) ? message.error.message : void 0
755
+ statusDetail: isTypedMessage(message, import_meshagent_agents.AgentImageGenerationFailed) ? message.error.message : void 0,
756
+ images
277
757
  }
278
758
  });
759
+ } else if (isTypedMessage(message, import_meshagent_agents.TurnEnded)) {
760
+ const errorItem = turnEndedErrorItem(message, createdAt);
761
+ if (errorItem !== null) {
762
+ upsertItem(items, errorItem);
763
+ }
279
764
  }
280
765
  }
281
766
  for (const pending of session.pendingInputs) {
@@ -284,7 +769,178 @@ function feedFromSession(session) {
284
769
  upsertItem(items, item);
285
770
  }
286
771
  }
287
- return [...items.values()].filter((item) => item.text.trim() !== "" || item.attachments.length > 0 || item.image != null || item.kind === "tool_call");
772
+ 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");
773
+ }
774
+ function firstNonEmptyLine(text) {
775
+ for (const line of text.split(/\r?\n/)) {
776
+ const trimmed = line.trim();
777
+ if (trimmed !== "") {
778
+ return trimmed;
779
+ }
780
+ }
781
+ return null;
782
+ }
783
+ function detailGroupId(messages) {
784
+ const first = messages[0];
785
+ return ["details", first?.turnId ?? "", first?.id ?? "", first?.createdAt.getTime() ?? 0].join(":");
786
+ }
787
+ function messagesShareTurn(left, right) {
788
+ return left.turnId != null && left.turnId.trim() !== "" && left.turnId === right.turnId;
789
+ }
790
+ function canCollapseAsCommentary(message) {
791
+ if (message.phase === "final_answer") {
792
+ return false;
793
+ }
794
+ return message.kind === "message" && message.role === "agent" && message.attachments.length === 0 && message.image == null;
795
+ }
796
+ function canRenderAsFinalAnswer(message) {
797
+ if (message.kind !== "message" || message.role !== "agent" || message.phase === "commentary") {
798
+ return false;
799
+ }
800
+ return message.text.trim() !== "" || message.attachments.length > 0 || message.image != null;
801
+ }
802
+ function isIntrinsicDetail(message) {
803
+ return message.kind === "reasoning" || message.kind === "event" || message.kind === "tool_call" && message.failed !== true || canCollapseAsCommentary(message) && message.phase === "commentary";
804
+ }
805
+ function nextUserMessageIndex(messages, start) {
806
+ for (let index = start; index < messages.length; index += 1) {
807
+ const message = messages[index];
808
+ if (message.kind === "message" && message.role === "user") {
809
+ return index;
810
+ }
811
+ }
812
+ return null;
813
+ }
814
+ function finalAgentMessageIndexForSegment(messages, start, end) {
815
+ let explicitFinalIndex = -1;
816
+ for (let index = start; index < end; index += 1) {
817
+ const message = messages[index];
818
+ if (canRenderAsFinalAnswer(message) && message.phase === "final_answer") {
819
+ explicitFinalIndex = index;
820
+ }
821
+ }
822
+ if (explicitFinalIndex !== -1) {
823
+ return explicitFinalIndex;
824
+ }
825
+ let inferredFinalIndex = -1;
826
+ for (let index = start; index < end; index += 1) {
827
+ if (canRenderAsFinalAnswer(messages[index])) {
828
+ inferredFinalIndex = index;
829
+ }
830
+ }
831
+ return inferredFinalIndex;
832
+ }
833
+ function addDetailIndexesForSegment(messages, start, end, detailIndexes) {
834
+ const finalAgentMessageIndex = finalAgentMessageIndexForSegment(messages, start, end);
835
+ for (let index = start; index < end; index += 1) {
836
+ const message = messages[index];
837
+ if (isIntrinsicDetail(message)) {
838
+ detailIndexes.add(index);
839
+ continue;
840
+ }
841
+ if (index !== finalAgentMessageIndex && canCollapseAsCommentary(message)) {
842
+ detailIndexes.add(index);
843
+ }
844
+ }
845
+ }
846
+ function nextNonDetailMessage(messages, detailIndexes, start, end) {
847
+ for (let index = start; index < end; index += 1) {
848
+ if (!detailIndexes.has(index)) {
849
+ return messages[index];
850
+ }
851
+ }
852
+ return null;
853
+ }
854
+ function detailGroupCollapsedMessage(messages) {
855
+ for (const message of [...messages].reverse()) {
856
+ if (canCollapseAsCommentary(message) && message.text.trim() !== "") {
857
+ return message;
858
+ }
859
+ }
860
+ for (const message of [...messages].reverse()) {
861
+ if (message.kind === "reasoning" && message.text.trim() !== "") {
862
+ return message;
863
+ }
864
+ }
865
+ return null;
866
+ }
867
+ function formatDetailGroupDuration(milliseconds) {
868
+ const seconds = Math.max(0, Math.round(milliseconds / 1e3));
869
+ if (seconds < 60) {
870
+ return `${seconds}s`;
871
+ }
872
+ const minutes = Math.floor(seconds / 60);
873
+ const remainingSeconds = seconds % 60;
874
+ return remainingSeconds === 0 ? `${minutes}m` : `${minutes}m ${remainingSeconds}s`;
875
+ }
876
+ function detailGroupCollapsedText(messages, nextMessage) {
877
+ const first = messages[0];
878
+ if (first && nextMessage != null && canRenderAsFinalAnswer(nextMessage) && messagesShareTurn(first, nextMessage)) {
879
+ return `Worked for ${formatDetailGroupDuration(nextMessage.createdAt.getTime() - first.createdAt.getTime())}`;
880
+ }
881
+ return firstNonEmptyLine(detailGroupCollapsedMessage(messages)?.text ?? "") ?? "Working";
882
+ }
883
+ function detailGroupAuthorName(message, localParticipantName, agentName) {
884
+ const authorName = message.authorName?.trim();
885
+ if (authorName) {
886
+ return authorName;
887
+ }
888
+ if (message.role === "user") {
889
+ return localParticipantName;
890
+ }
891
+ return displayParticipantName(agentName);
892
+ }
893
+ function detailGroupForMessages(messages, nextMessage, expandedIds, localParticipantName, agentName) {
894
+ const collapsedMessage = detailGroupCollapsedMessage(messages) ?? messages[0];
895
+ const id = detailGroupId(messages);
896
+ return {
897
+ id,
898
+ kind: "detail_group",
899
+ messages,
900
+ collapsedText: detailGroupCollapsedText(messages, nextMessage),
901
+ authorName: detailGroupAuthorName(collapsedMessage, localParticipantName, agentName),
902
+ createdAt: collapsedMessage.createdAt,
903
+ expanded: expandedIds.has(id)
904
+ };
905
+ }
906
+ function threadFeedItems(messages, expandedIds, localParticipantName, agentName) {
907
+ const items = [];
908
+ let index = 0;
909
+ while (index < messages.length) {
910
+ const segmentEnd = nextUserMessageIndex(messages, index + 1) ?? messages.length;
911
+ const detailIndexes = /* @__PURE__ */ new Set();
912
+ addDetailIndexesForSegment(messages, index, segmentEnd, detailIndexes);
913
+ const groupedMessages = [...detailIndexes].sort((left, right) => left - right).map((detailIndex) => messages[detailIndex]);
914
+ let insertedDetailGroup = false;
915
+ for (let segmentIndex = index; segmentIndex < segmentEnd; segmentIndex += 1) {
916
+ if (!detailIndexes.has(segmentIndex)) {
917
+ items.push(messages[segmentIndex]);
918
+ continue;
919
+ }
920
+ if (insertedDetailGroup || groupedMessages.length === 0) {
921
+ continue;
922
+ }
923
+ items.push(detailGroupForMessages(
924
+ groupedMessages,
925
+ nextNonDetailMessage(messages, detailIndexes, segmentIndex + 1, segmentEnd),
926
+ expandedIds,
927
+ localParticipantName,
928
+ agentName
929
+ ));
930
+ insertedDetailGroup = true;
931
+ }
932
+ index = segmentEnd;
933
+ }
934
+ return items;
935
+ }
936
+ function previousMessageFeedItem(items, index) {
937
+ for (let cursor = index - 1; cursor >= 0; cursor -= 1) {
938
+ const item = items[cursor];
939
+ if (item.kind !== "detail_group") {
940
+ return item;
941
+ }
942
+ }
943
+ return null;
288
944
  }
289
945
  function latestThreadStatus(session) {
290
946
  if (session === null) {
@@ -296,6 +952,72 @@ function latestThreadStatus(session) {
296
952
  }
297
953
  return null;
298
954
  }
955
+ function latestUsageSnapshot(session) {
956
+ if (session === null) {
957
+ return null;
958
+ }
959
+ let usage = null;
960
+ for (const event of session.messages) {
961
+ const next = AgentUsageSnapshot.fromMessage(event.message);
962
+ if (next === null) {
963
+ continue;
964
+ }
965
+ if (shouldReplaceAgentUsageSnapshot(usage, next)) {
966
+ usage = next;
967
+ }
968
+ }
969
+ return usage;
970
+ }
971
+ function formatAgentUsageTokenCount(value) {
972
+ const magnitude = Math.abs(value);
973
+ if (magnitude >= 1e6) {
974
+ return `${trimFixed(value / 1e6)}M`;
975
+ }
976
+ if (magnitude >= 1e3) {
977
+ return `${trimFixed(value / 1e3)}K`;
978
+ }
979
+ return Math.round(value).toString();
980
+ }
981
+ function trimFixed(value) {
982
+ const fixed = value.toFixed(1);
983
+ return fixed.endsWith(".0") ? fixed.slice(0, -2) : fixed;
984
+ }
985
+ function formatAgentUsageFooter(usage) {
986
+ const contextLimitTokens = usage.compactionThreshold ?? usage.contextTotalTokens;
987
+ const used = formatAgentUsageTokenCount(usage.contextUsedTokens);
988
+ const limit = contextLimitTokens == null ? "" : `/${formatAgentUsageTokenCount(contextLimitTokens)}`;
989
+ return `context ${used}${limit}`;
990
+ }
991
+ function formatAgentUsageTooltip(usage) {
992
+ const lines = [`context used: ${formatAgentUsageTokenCount(usage.contextUsedTokens)}`];
993
+ if (usage.compactionMode != null) {
994
+ lines.push(`context management: ${usage.compactionMode}`);
995
+ if (usage.compactionThreshold != null) {
996
+ lines.push(`context threshold: ${formatAgentUsageTokenCount(usage.compactionThreshold)}`);
997
+ }
998
+ }
999
+ if (usage.compactionThreshold != null && usage.contextTotalTokens != null) {
1000
+ lines.push(`model window: ${formatAgentUsageTokenCount(usage.contextTotalTokens)}`);
1001
+ }
1002
+ const entries = Object.entries(usage.usage).sort(([left], [right]) => left.localeCompare(right));
1003
+ for (const [key, value] of entries) {
1004
+ lines.push(`${key}: ${formatAgentUsageTokenCount(value)}`);
1005
+ }
1006
+ return lines.join("\n");
1007
+ }
1008
+ function AgentUsageFooter({ usage, className }) {
1009
+ const tooltip = usage === null ? void 0 : formatAgentUsageTooltip(usage);
1010
+ const label = usage === null ? "" : formatAgentUsageFooter(usage);
1011
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1012
+ "div",
1013
+ {
1014
+ className: (0, import_utils.cn)("min-h-4 truncate px-2 text-right text-[11px] leading-4 text-muted-foreground", className),
1015
+ title: tooltip,
1016
+ "aria-label": tooltip,
1017
+ children: label
1018
+ }
1019
+ );
1020
+ }
299
1021
  function dateFromString(value) {
300
1022
  if (value == null || value.trim() === "") {
301
1023
  return null;
@@ -307,6 +1029,23 @@ function normalizeAttachmentPath(path) {
307
1029
  const prefix = "room:///";
308
1030
  return path.startsWith(prefix) ? path.slice(prefix.length) : path;
309
1031
  }
1032
+ function isHttpUrl(path) {
1033
+ return /^https?:\/\//iu.test(path.trim());
1034
+ }
1035
+ function isInlineImageUrl(path) {
1036
+ return path.trim().toLowerCase().startsWith("data:image/");
1037
+ }
1038
+ function attachmentImagePath(path) {
1039
+ const trimmed = path.trim();
1040
+ if (trimmed === "") {
1041
+ return null;
1042
+ }
1043
+ if (isInlineImageUrl(trimmed)) {
1044
+ return trimmed;
1045
+ }
1046
+ const normalized = normalizeAttachmentPath(trimmed);
1047
+ return (0, import_file_preview.isImagePath)(normalized) ? normalized : null;
1048
+ }
310
1049
  function MarkdownBlock({ text }) {
311
1050
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
312
1051
  import_react_markdown.default,
@@ -332,17 +1071,191 @@ function ChatBubble({ text, mine }) {
332
1071
  mine ? "bg-secondary/85 text-foreground" : "bg-muted/70 text-foreground"
333
1072
  ), children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(MarkdownBlock, { text }) });
334
1073
  }
1074
+ function ReasoningTrace({ text, className }) {
1075
+ if (text.trim() === "") {
1076
+ return null;
1077
+ }
1078
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: (0, import_utils.cn)("mr-[50px] ml-1.5 px-4 py-1 text-sm leading-6 text-muted-foreground", className), children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(MarkdownBlock, { text }) });
1079
+ }
1080
+ function trimShellText(value) {
1081
+ if (value == null) {
1082
+ return void 0;
1083
+ }
1084
+ return value.length < 1024 ? value : value.slice(0, 1024) + "...";
1085
+ }
1086
+ function ShellLine({ command, result, stdout, stderr, argumentsText, logs, title = "Terminal", className }) {
1087
+ const displayCommand = command?.trim() || title;
1088
+ const [expanded, setExpanded] = (0, import_react.useState)(title.toLowerCase().includes("error"));
1089
+ const trimmedResult = trimShellText(result);
1090
+ const trimmedStdout = trimShellText(stdout);
1091
+ const trimmedStderr = trimShellText(stderr);
1092
+ const trimmedArguments = trimShellText(argumentsText);
1093
+ const trimmedLogs = logs == null || logs.length === 0 ? void 0 : trimShellText(logs.join("\n"));
1094
+ const hasDetails = trimmedResult != null || trimmedStdout != null || trimmedStderr != null || trimmedArguments != null || trimmedLogs != null;
1095
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: (0, import_utils.cn)("mr-[50px] ml-1.5 overflow-hidden rounded-md border bg-background text-sm", className), children: [
1096
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex items-center gap-2 border-b bg-secondary/70 px-4 py-1.5 text-foreground", children: [
1097
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_lucide_react.Terminal, { className: "h-4 w-4 shrink-0" }),
1098
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "font-medium", children: title })
1099
+ ] }),
1100
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex items-start gap-1 px-2 py-1.5", children: [
1101
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1102
+ "button",
1103
+ {
1104
+ type: "button",
1105
+ 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",
1106
+ onClick: () => setExpanded((current) => !current),
1107
+ "aria-expanded": expanded,
1108
+ "aria-label": expanded ? "Collapse terminal output" : "Expand terminal output",
1109
+ children: expanded ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_lucide_react.ChevronDown, { className: "h-4 w-4" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_lucide_react.ChevronRight, { className: "h-4 w-4" })
1110
+ }
1111
+ ),
1112
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("pre", { className: (0, import_utils.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 })
1113
+ ] }),
1114
+ expanded && hasDetails ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "space-y-2 border-t px-4 py-3", children: [
1115
+ trimmedResult != null ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("pre", { className: "whitespace-pre-wrap break-words font-mono text-xs leading-5 text-foreground", children: trimmedResult }) : null,
1116
+ trimmedStdout != null ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("pre", { className: "whitespace-pre-wrap break-words font-mono text-xs leading-5 text-foreground", children: trimmedStdout }) : null,
1117
+ trimmedStderr != null ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("pre", { className: "whitespace-pre-wrap break-words font-mono text-xs leading-5 text-destructive", children: trimmedStderr }) : null,
1118
+ trimmedArguments != null ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("pre", { className: "whitespace-pre-wrap break-words font-mono text-xs leading-5 text-muted-foreground", children: trimmedArguments }) : null,
1119
+ trimmedLogs != null ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("pre", { className: "whitespace-pre-wrap break-words font-mono text-xs leading-5 text-muted-foreground", children: trimmedLogs }) : null
1120
+ ] }) : null
1121
+ ] });
1122
+ }
1123
+ function eventLineStateClass(state, failed) {
1124
+ const normalizedState = state?.trim().toLowerCase();
1125
+ if (failed === true || normalizedState === "failed") {
1126
+ return "text-destructive";
1127
+ }
1128
+ if (normalizedState === "cancelled") {
1129
+ return "text-muted-foreground";
1130
+ }
1131
+ if (normalizedState === "running" || normalizedState === "in_progress" || normalizedState === "queued") {
1132
+ return "text-primary";
1133
+ }
1134
+ return "text-muted-foreground";
1135
+ }
1136
+ function eventLineDetails(details) {
1137
+ if (details == null) {
1138
+ return [];
1139
+ }
1140
+ const lines = typeof details === "string" ? details.split(/\r?\n/) : details;
1141
+ return lines.map((line) => line.trim()).filter((line) => line !== "");
1142
+ }
1143
+ function EventLine({ headline, details, state = "info", failed = false, className }) {
1144
+ const normalizedHeadline = headline.trim();
1145
+ const detailLines = eventLineDetails(details);
1146
+ if (normalizedHeadline === "") {
1147
+ return null;
1148
+ }
1149
+ const textClass = eventLineStateClass(state, failed);
1150
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: (0, import_utils.cn)("ml-1.5 px-4 py-1 text-xs leading-5", textClass, className), children: [
1151
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "font-semibold", children: normalizedHeadline }),
1152
+ detailLines.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "mt-0.5 whitespace-pre-wrap break-words opacity-85", children: detailLines.join("\n") }) : null
1153
+ ] });
1154
+ }
1155
+ function toolDetailLines(message) {
1156
+ const details = [];
1157
+ if (message.argumentsText?.trim()) {
1158
+ details.push(message.argumentsText);
1159
+ }
1160
+ if (message.logs != null && message.logs.length > 0) {
1161
+ details.push(message.logs.join("\n"));
1162
+ }
1163
+ if (message.result?.trim()) {
1164
+ details.push(message.result);
1165
+ }
1166
+ if (message.stdout?.trim()) {
1167
+ details.push(message.stdout);
1168
+ }
1169
+ if (message.stderr?.trim()) {
1170
+ details.push(message.stderr);
1171
+ }
1172
+ return details;
1173
+ }
1174
+ function ToolCallLine({ message }) {
1175
+ const detailLines = toolDetailLines(message);
1176
+ const [expanded, setExpanded] = (0, import_react.useState)(message.failed === true);
1177
+ const hasDetails = detailLines.length > 0;
1178
+ if (!hasDetails) {
1179
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventLine, { headline: message.text, state: message.state ?? (message.failed === true ? "failed" : "completed"), failed: message.failed });
1180
+ }
1181
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "ml-1.5 max-w-[85%] overflow-hidden rounded-md border bg-background text-sm sm:max-w-2xl", children: [
1182
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
1183
+ "button",
1184
+ {
1185
+ type: "button",
1186
+ className: "flex w-full items-start gap-2 px-3 py-2 text-left transition-colors hover:bg-muted/50",
1187
+ onClick: () => setExpanded((current) => !current),
1188
+ "aria-expanded": expanded,
1189
+ "aria-label": expanded ? "Collapse tool details" : "Expand tool details",
1190
+ children: [
1191
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "mt-0.5 inline-flex h-5 w-5 shrink-0 items-center justify-center text-muted-foreground", children: expanded ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_lucide_react.ChevronDown, { className: "h-4 w-4" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_lucide_react.ChevronRight, { className: "h-4 w-4" }) }),
1192
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: (0, import_utils.cn)("min-w-0 flex-1 text-xs font-semibold leading-5", eventLineStateClass(message.state, message.failed)), children: message.text })
1193
+ ]
1194
+ }
1195
+ ),
1196
+ expanded ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "space-y-2 border-t px-4 py-3", children: detailLines.map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("pre", { className: (0, import_utils.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
1197
+ ] });
1198
+ }
335
1199
  function AttachmentView({ room, path }) {
1200
+ return attachmentImagePath(path) == null ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AttachmentDownloadButton, { room, path }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ChatImageAttachment, { room, path });
1201
+ }
1202
+ function ChatImageAttachment({ room, path }) {
1203
+ const imagePath = attachmentImagePath(path) ?? path;
1204
+ const [url, setUrl] = (0, import_react.useState)(() => isInlineImageUrl(imagePath) || isHttpUrl(imagePath) ? imagePath : null);
1205
+ const [error, setError] = (0, import_react.useState)(null);
1206
+ (0, import_react.useEffect)(() => {
1207
+ let cancelled = false;
1208
+ setError(null);
1209
+ if (isInlineImageUrl(imagePath) || isHttpUrl(imagePath)) {
1210
+ setUrl(imagePath);
1211
+ return;
1212
+ }
1213
+ setUrl(null);
1214
+ void room.storage.downloadUrl(imagePath).then((nextUrl) => {
1215
+ if (!cancelled) {
1216
+ setUrl(nextUrl);
1217
+ }
1218
+ }).catch((nextError) => {
1219
+ if (!cancelled) {
1220
+ setError(nextError);
1221
+ }
1222
+ });
1223
+ return () => {
1224
+ cancelled = true;
1225
+ };
1226
+ }, [imagePath, room]);
1227
+ if (error != null) {
1228
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AttachmentDownloadButton, { room, path });
1229
+ }
1230
+ if (url == null) {
1231
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "flex h-[240px] w-[240px] items-center justify-center rounded-md border bg-background text-muted-foreground", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_spinner.Spinner, { className: "h-5 w-5" }) });
1232
+ }
1233
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1234
+ "button",
1235
+ {
1236
+ type: "button",
1237
+ className: "block max-w-full overflow-hidden rounded-md shadow-xs transition-opacity hover:opacity-90",
1238
+ onClick: () => window.open(url, "_blank", "noopener,noreferrer"),
1239
+ title: "Open image",
1240
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("img", { src: url, alt: (0, import_file_preview.filePreviewName)(imagePath), className: "max-h-[312px] max-w-full object-contain" })
1241
+ }
1242
+ );
1243
+ }
1244
+ function AttachmentDownloadButton({ room, path, className }) {
336
1245
  const preview = normalizeAttachmentPath(path);
337
- const filename = preview.split("/").pop() ?? preview;
1246
+ const filename = (0, import_file_preview.filePreviewName)(preview);
338
1247
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
339
1248
  "button",
340
1249
  {
341
1250
  type: "button",
342
- className: "inline-flex max-w-full items-center gap-2 rounded-md bg-muted/60 px-3 py-2 text-left shadow-xs transition-colors hover:bg-muted/80",
1251
+ className: (0, import_utils.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),
343
1252
  onClick: () => {
344
- void room.storage.downloadUrl(preview).then((url) => {
345
- window.open(url, "_blank", "noopener,noreferrer");
1253
+ if (isInlineImageUrl(path) || isHttpUrl(path)) {
1254
+ window.open(path, "_blank", "noopener,noreferrer");
1255
+ return;
1256
+ }
1257
+ void room.storage.downloadUrl(preview).then((nextUrl) => {
1258
+ window.open(nextUrl, "_blank", "noopener,noreferrer");
346
1259
  });
347
1260
  },
348
1261
  children: [
@@ -353,20 +1266,126 @@ function AttachmentView({ room, path }) {
353
1266
  }
354
1267
  );
355
1268
  }
1269
+ function ChatThreadPreview({ room, path, className }) {
1270
+ const normalizedPath = normalizeAttachmentPath(path);
1271
+ if (attachmentImagePath(path) != null) {
1272
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: (0, import_utils.cn)("h-[312.5px] w-[312.5px] max-w-full overflow-hidden rounded-2xl bg-background", className), children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ChatImageAttachment, { room, path }) });
1273
+ }
1274
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AttachmentDownloadButton, { room, path: normalizedPath, className });
1275
+ }
1276
+ function DetailGroupLine({ item, onToggle }) {
1277
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
1278
+ "button",
1279
+ {
1280
+ type: "button",
1281
+ 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",
1282
+ onClick: onToggle,
1283
+ "aria-expanded": item.expanded,
1284
+ title: item.expanded ? "Collapse details" : "Expand details",
1285
+ children: [
1286
+ item.expanded ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_lucide_react.ChevronDown, { className: "h-3.5 w-3.5 shrink-0" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_lucide_react.ChevronRight, { className: "h-3.5 w-3.5 shrink-0" }),
1287
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "min-w-0 truncate", children: item.collapsedText }),
1288
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "shrink-0", children: timeAgo(item.createdAt) })
1289
+ ]
1290
+ }
1291
+ );
1292
+ }
1293
+ function ExpandedDetailGroup({
1294
+ room,
1295
+ item,
1296
+ localParticipantName,
1297
+ agentName
1298
+ }) {
1299
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex flex-col gap-3", children: [
1300
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "flex w-full justify-start", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "max-w-[85%] px-1 text-left sm:max-w-2xl", children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground", children: [
1301
+ item.authorName.trim() !== "" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "font-semibold text-foreground", children: displayParticipantName(item.authorName) }) : null,
1302
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: timeAgo(item.createdAt) })
1303
+ ] }) }) }),
1304
+ item.messages.map((message, index) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1305
+ ThreadMessageView,
1306
+ {
1307
+ room,
1308
+ message,
1309
+ previous: index > 0 ? item.messages[index - 1] : null,
1310
+ localParticipantName,
1311
+ agentName,
1312
+ forceHideHeader: true
1313
+ },
1314
+ message.id
1315
+ ))
1316
+ ] });
1317
+ }
1318
+ function GeneratedImageView({ image }) {
1319
+ const completedImages = image.images?.filter((entry) => entry.uri?.trim()) ?? [];
1320
+ if (completedImages.length > 0) {
1321
+ return /* @__PURE__ */ (0, import_jsx_runtime.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__ */ (0, import_jsx_runtime.jsx)(
1322
+ "button",
1323
+ {
1324
+ type: "button",
1325
+ className: "overflow-hidden rounded-md shadow-xs transition-opacity hover:opacity-90",
1326
+ onClick: () => entry.uri != null ? window.open(entry.uri, "_blank", "noopener,noreferrer") : void 0,
1327
+ title: "Open generated image",
1328
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("img", { src: entry.uri, alt: "Generated image", className: "max-h-[312px] w-full object-contain" })
1329
+ },
1330
+ `${entry.uri}:${index}`
1331
+ )) });
1332
+ }
1333
+ if (image.uri) {
1334
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1335
+ "button",
1336
+ {
1337
+ type: "button",
1338
+ className: "max-w-[85%] overflow-hidden rounded-md shadow-xs transition-opacity hover:opacity-90 sm:max-w-2xl",
1339
+ onClick: () => window.open(image.uri, "_blank", "noopener,noreferrer"),
1340
+ title: "Open generated image",
1341
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("img", { src: image.uri, alt: "Generated image", className: "max-h-[312px] max-w-full object-contain" })
1342
+ }
1343
+ );
1344
+ }
1345
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "flex h-[240px] w-[240px] items-center justify-center rounded-md border bg-background text-muted-foreground", children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex max-w-full flex-col items-center gap-2 px-3 text-center text-xs", children: [
1346
+ image.status === "failed" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_lucide_react.ImageOff, { className: "h-5 w-5" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_spinner.Spinner, { className: "h-5 w-5" }),
1347
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: image.statusDetail ?? (image.status === "failed" ? "Image failed" : "Generating image") })
1348
+ ] }) });
1349
+ }
356
1350
  function ThreadMessageView({
357
1351
  room,
358
1352
  message,
359
1353
  previous,
360
1354
  localParticipantName,
361
- agentName
1355
+ agentName,
1356
+ forceHideHeader = false
362
1357
  }) {
363
- if (message.kind === "reasoning" || message.kind === "tool_call") {
364
- return message.text.trim() === "" ? null : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "px-6 py-1 text-center text-sm text-muted-foreground", children: message.text });
1358
+ if (message.kind === "error") {
1359
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "px-6 py-1 text-center text-sm text-destructive", children: message.text });
1360
+ }
1361
+ if (message.kind === "reasoning") {
1362
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ReasoningTrace, { text: message.text });
1363
+ }
1364
+ if (message.kind === "event") {
1365
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventLine, { headline: message.text, state: message.state, failed: message.failed });
1366
+ }
1367
+ if (message.kind === "tool_call") {
1368
+ if (isShellTool(message)) {
1369
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1370
+ ShellLine,
1371
+ {
1372
+ command: message.command ?? message.text,
1373
+ result: message.result,
1374
+ stdout: message.stdout,
1375
+ stderr: message.stderr,
1376
+ argumentsText: message.argumentsText,
1377
+ logs: message.logs,
1378
+ title: message.failed === true ? "Terminal Error" : "Terminal",
1379
+ className: message.failed === true ? "border-destructive/40" : void 0
1380
+ }
1381
+ );
1382
+ }
1383
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ToolCallLine, { message });
365
1384
  }
366
1385
  const mine = message.role === "user";
367
1386
  const authorName = message.authorName ?? (mine ? localParticipantName : displayParticipantName(agentName));
368
1387
  const previousAuthor = previous?.authorName ?? (previous?.role === "user" ? localParticipantName : displayParticipantName(agentName));
369
- const shouldShowHeader = previous?.kind !== "message" || previousAuthor !== authorName;
1388
+ const shouldShowHeader = !forceHideHeader && (previous?.kind !== "message" || previousAuthor !== authorName);
370
1389
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex flex-col gap-2", children: [
371
1390
  shouldShowHeader ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: (0, import_utils.cn)("flex w-full", mine ? "justify-end" : "justify-start"), children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: (0, import_utils.cn)("max-w-[85%] px-1 sm:max-w-2xl", mine ? "text-right" : "text-left"), children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: (0, import_utils.cn)("flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground", mine ? "justify-end" : "justify-start"), children: [
372
1391
  authorName.trim() !== "" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "font-semibold text-foreground", children: displayParticipantName(authorName) }) : null,
@@ -374,10 +1393,7 @@ function ThreadMessageView({
374
1393
  ] }) }) }) : null,
375
1394
  message.text.trim() !== "" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: (0, import_utils.cn)("flex w-full", mine ? "justify-end" : "justify-start"), children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ChatBubble, { text: message.text, mine }) }) : null,
376
1395
  message.attachments.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: (0, import_utils.cn)("flex w-full", mine ? "justify-end" : "justify-start"), children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: (0, import_utils.cn)("flex max-w-[85%] flex-wrap gap-3 px-1 sm:max-w-2xl", mine ? "justify-end" : "justify-start"), children: message.attachments.map((attachment, index) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AttachmentView, { room, path: attachment }, `${message.id}:attachment:${attachment}:${index}`)) }) }) : null,
377
- message.image ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "flex w-full justify-start", children: message.image.uri ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("img", { src: message.image.uri, alt: "Generated image", className: "max-h-[312px] max-w-full rounded-md object-contain shadow-xs" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "flex h-[240px] w-[240px] items-center justify-center rounded-md border bg-background text-muted-foreground", children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex max-w-full flex-col items-center gap-2 px-3 text-center text-xs", children: [
378
- message.image.status === "failed" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_lucide_react.ImageOff, { className: "h-5 w-5" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_spinner.Spinner, { className: "h-5 w-5" }),
379
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: message.image.statusDetail ?? (message.image.status === "failed" ? "Image failed" : "Generating image") })
380
- ] }) }) }) : null
1396
+ message.image ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "flex w-full justify-start", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(GeneratedImageView, { image: message.image }) }) : null
381
1397
  ] });
382
1398
  }
383
1399
  function EmptyState({ title, description }) {
@@ -386,6 +1402,9 @@ function EmptyState({ title, description }) {
386
1402
  description?.trim() ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "mt-3 max-w-xl text-sm leading-6 text-muted-foreground sm:text-base", children: description }) : null
387
1403
  ] });
388
1404
  }
1405
+ function LoadingState() {
1406
+ return /* @__PURE__ */ (0, import_jsx_runtime.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__ */ (0, import_jsx_runtime.jsx)(import_spinner.Spinner, { size: "lg" }) });
1407
+ }
389
1408
  function ErrorBanner({ message }) {
390
1409
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "mx-auto w-full max-w-[912px] whitespace-pre-wrap rounded-md border border-destructive/30 bg-destructive/5 px-4 py-3 text-sm text-destructive", children: message });
391
1410
  }
@@ -418,11 +1437,14 @@ function AgentThread({
418
1437
  agentName,
419
1438
  emptyStateTitle = "Chat to get started",
420
1439
  emptyStateDescription,
421
- clientToolkits
1440
+ clientToolkits,
1441
+ toolChoice,
1442
+ collapseMessages = true
422
1443
  }) {
423
1444
  const [attachments, setAttachments] = (0, import_react.useState)([]);
424
1445
  const [sendError, setSendError] = (0, import_react.useState)(null);
425
1446
  const [version, setVersion] = (0, import_react.useState)(0);
1447
+ const [expandedDetailGroupIds, setExpandedDetailGroupIds] = (0, import_react.useState)(() => /* @__PURE__ */ new Set());
426
1448
  const scrollContainerRef = (0, import_react.useRef)(null);
427
1449
  const contentRef = (0, import_react.useRef)(null);
428
1450
  const stickToBottomRef = (0, import_react.useRef)(true);
@@ -462,9 +1484,13 @@ function AgentThread({
462
1484
  }
463
1485
  };
464
1486
  }, [activeChatClient, path]);
465
- const session = sessionRef.current;
1487
+ const normalizedPath = path.trim();
1488
+ const session = sessionRef.current?.threadPath === normalizedPath ? sessionRef.current : null;
466
1489
  const feedItems = (0, import_react.useMemo)(() => feedFromSession(session), [session, version]);
1490
+ const showThreadLoading = (session === null || session.isLoading) && feedItems.length === 0;
1491
+ const renderedFeedItems = (0, import_react.useMemo)(() => collapseMessages ? threadFeedItems(feedItems, expandedDetailGroupIds, localParticipantName, agentName) : feedItems, [agentName, collapseMessages, expandedDetailGroupIds, feedItems, localParticipantName]);
467
1492
  const status = (0, import_react.useMemo)(() => latestThreadStatus(session), [session, version]);
1493
+ const usage = (0, import_react.useMemo)(() => latestUsageSnapshot(session), [session, version]);
468
1494
  const statusText = status?.status?.trim() || null;
469
1495
  const turnId = stringValue(status?.turnId);
470
1496
  const canInterruptActiveTurn = turnId != null && (agentParticipant != null || chatClient != null);
@@ -532,14 +1558,15 @@ function AgentThread({
532
1558
  turnId,
533
1559
  steer: status?.mode === "steerable" && turnId != null,
534
1560
  senderName: localParticipantName.trim() || void 0,
535
- clientToolkits
1561
+ clientToolkits,
1562
+ toolChoice: toolChoice == null ? void 0 : new import_meshagent_agents.ToolChoice({ toolkitName: toolChoice.toolkitName, toolName: toolChoice.toolName })
536
1563
  });
537
1564
  setSendError(null);
538
1565
  setVersion((current) => current + 1);
539
1566
  } catch (error) {
540
1567
  setSendError(describeError(error));
541
1568
  }
542
- }, [agentParticipant, chatClient, clientToolkits, localParticipantName, status?.mode, turnId]);
1569
+ }, [agentParticipant, chatClient, clientToolkits, localParticipantName, status?.mode, toolChoice, turnId]);
543
1570
  const cancelTurn = (0, import_react.useCallback)(async () => {
544
1571
  const openSession = sessionRef.current;
545
1572
  if (openSession === null || turnId == null) {
@@ -547,6 +1574,17 @@ function AgentThread({
547
1574
  }
548
1575
  await openSession.interruptTurn(turnId);
549
1576
  }, [turnId]);
1577
+ const toggleDetailGroup = (0, import_react.useCallback)((id) => {
1578
+ setExpandedDetailGroupIds((current) => {
1579
+ const next = new Set(current);
1580
+ if (next.has(id)) {
1581
+ next.delete(id);
1582
+ } else {
1583
+ next.add(id);
1584
+ }
1585
+ return next;
1586
+ });
1587
+ }, []);
550
1588
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex h-full min-h-0 flex-1 flex-col", children: [
551
1589
  /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "relative flex h-full min-h-0 flex-1 flex-col", children: [
552
1590
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
@@ -567,17 +1605,33 @@ function AgentThread({
567
1605
  statusText ? "pb-24" : "pb-6"
568
1606
  ),
569
1607
  children: [
570
- feedItems.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EmptyState, { title: emptyStateTitle, description: emptyStateDescription }) : null,
571
- feedItems.map((message, index) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1608
+ showThreadLoading ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LoadingState, {}) : feedItems.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EmptyState, { title: emptyStateTitle, description: emptyStateDescription }) : null,
1609
+ renderedFeedItems.map((item, index) => item.kind === "detail_group" ? item.expanded ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1610
+ ExpandedDetailGroup,
1611
+ {
1612
+ room,
1613
+ item,
1614
+ localParticipantName,
1615
+ agentName
1616
+ },
1617
+ item.id
1618
+ ) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1619
+ DetailGroupLine,
1620
+ {
1621
+ item,
1622
+ onToggle: () => toggleDetailGroup(item.id)
1623
+ },
1624
+ item.id
1625
+ ) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
572
1626
  ThreadMessageView,
573
1627
  {
574
1628
  room,
575
- message,
576
- previous: index > 0 ? feedItems[index - 1] : null,
1629
+ message: item,
1630
+ previous: previousMessageFeedItem(renderedFeedItems, index),
577
1631
  localParticipantName,
578
1632
  agentName
579
1633
  },
580
- message.id
1634
+ item.id
581
1635
  ))
582
1636
  ]
583
1637
  }
@@ -591,6 +1645,9 @@ function AgentThread({
591
1645
  thinking: false,
592
1646
  statusText,
593
1647
  startedAt: dateFromString(status?.startedAt),
1648
+ totalBytes: status?.totalBytes,
1649
+ linesAdded: status?.linesAdded,
1650
+ linesRemoved: status?.linesRemoved,
594
1651
  onCancel: canInterruptActiveTurn ? cancelTurn : void 0,
595
1652
  showCancelButton: status?.mode != null,
596
1653
  cancelEnabled: true
@@ -598,16 +1655,19 @@ function AgentThread({
598
1655
  ) }) }) : null
599
1656
  ] }),
600
1657
  sendError ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "px-4 pb-2", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ErrorBanner, { message: sendError }) }) : null,
601
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
602
- import_chat_input.ChatInput,
603
- {
604
- onSubmit: handleSend,
605
- attachments,
606
- onFilesSelected: selectAttachments,
607
- setAttachments,
608
- disabled: agentParticipant == null && chatClient == null,
609
- placeholder: agentParticipant || chatClient ? "Type a message" : `Waiting for ${displayParticipantName(agentName)}`
610
- }
611
- )
1658
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex flex-col gap-1", children: [
1659
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1660
+ import_chat_input.ChatInput,
1661
+ {
1662
+ onSubmit: handleSend,
1663
+ attachments,
1664
+ onFilesSelected: selectAttachments,
1665
+ setAttachments,
1666
+ disabled: agentParticipant == null && chatClient == null,
1667
+ placeholder: agentParticipant || chatClient ? "Type a message" : `Waiting for ${displayParticipantName(agentName)}`
1668
+ }
1669
+ ),
1670
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AgentUsageFooter, { usage, className: "mx-auto w-full max-w-[912px]" })
1671
+ ] })
612
1672
  ] });
613
1673
  }