@meshagent/meshagent-tailwind 0.55.1 → 0.55.2

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 (38) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +34 -3
  3. package/dist/cjs/chat/agent-thread.d.ts +42 -7
  4. package/dist/cjs/chat/agent-thread.js +422 -183
  5. package/dist/cjs/chat/chat-input-state.d.ts +2 -0
  6. package/dist/cjs/chat/chat-input-state.js +41 -0
  7. package/dist/cjs/chat/chat-input.d.ts +14 -2
  8. package/dist/cjs/chat/chat-input.js +41 -76
  9. package/dist/cjs/chat/chat-scroller.js +45 -43
  10. package/dist/cjs/chat/chat-thread-timeline.d.ts +2 -0
  11. package/dist/cjs/chat/chat-thread-timeline.js +83 -10
  12. package/dist/cjs/chat/composer-action-button.d.ts +11 -0
  13. package/dist/cjs/chat/composer-action-button.js +68 -0
  14. package/dist/cjs/chat/use-chat-virtualizer.d.ts +14 -17
  15. package/dist/cjs/chat/use-chat-virtualizer.js +288 -222
  16. package/dist/cjs/chat/virtualization.d.ts +0 -5
  17. package/dist/cjs/chat/virtualization.js +4 -6
  18. package/dist/cjs/index.d.ts +1 -0
  19. package/dist/cjs/index.js +1 -0
  20. package/dist/esm/chat/agent-thread.d.ts +42 -7
  21. package/dist/esm/chat/agent-thread.js +424 -186
  22. package/dist/esm/chat/chat-input-state.d.ts +2 -0
  23. package/dist/esm/chat/chat-input-state.js +21 -0
  24. package/dist/esm/chat/chat-input.d.ts +14 -2
  25. package/dist/esm/chat/chat-input.js +41 -76
  26. package/dist/esm/chat/chat-scroller.js +46 -44
  27. package/dist/esm/chat/chat-thread-timeline.d.ts +2 -0
  28. package/dist/esm/chat/chat-thread-timeline.js +83 -10
  29. package/dist/esm/chat/composer-action-button.d.ts +11 -0
  30. package/dist/esm/chat/composer-action-button.js +48 -0
  31. package/dist/esm/chat/use-chat-virtualizer.d.ts +14 -17
  32. package/dist/esm/chat/use-chat-virtualizer.js +290 -226
  33. package/dist/esm/chat/virtualization.d.ts +0 -5
  34. package/dist/esm/chat/virtualization.js +4 -6
  35. package/dist/esm/index.d.ts +1 -0
  36. package/dist/esm/index.js +1 -0
  37. package/dist/index.css +1 -1
  38. package/package.json +6 -5
@@ -1,11 +1,10 @@
1
1
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
2
- import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
2
+ import { Children, createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
3
3
  import { ErrorContent } from "@meshagent/meshagent";
4
4
  import {
5
5
  AgentClientToolCallRequested,
6
6
  AgentFileContent,
7
7
  AgentThreadStatus,
8
- AgentToolCallEnded,
9
8
  MessagingChatClient,
10
9
  TurnEnded,
11
10
  TurnStarted
@@ -22,10 +21,12 @@ import { Button } from "../components/ui/button.js";
22
21
  import { Spinner } from "../components/ui/spinner.js";
23
22
  import { cn } from "../lib/utils.js";
24
23
  import { ChatInput } from "./chat-input.js";
24
+ import { useAttachmentStatusVersion } from "./chat-input-state.js";
25
25
  import { ChatMessage } from "./chat-message.js";
26
+ import { ComposerActionButton } from "./composer-action-button.js";
26
27
  import { ChatScroller } from "./chat-scroller.js";
27
28
  import { ChatTypingIndicator } from "./chat-typing-indicator.js";
28
- import { MeshagentFileUpload, fileToAsyncIterable } from "./file-attachment.js";
29
+ import { MeshagentFileUpload, UploadStatus, fileToAsyncIterable } from "./file-attachment.js";
29
30
  import { filePreviewName, isImagePath } from "../file-preview/file-preview.js";
30
31
  import { resolveClientToolkitDescriptions } from "./chat-feed-widget.js";
31
32
  import { ChatFeedWidgetView } from "./chat-feed-widget-view.js";
@@ -46,9 +47,7 @@ function stringValue(value) {
46
47
  }
47
48
  function mergeAgentMessageEvents(persistedEvents, liveEvents) {
48
49
  const merged = [...persistedEvents];
49
- const indexByMessageId = new Map(
50
- merged.map((event, index) => [event.message.messageId, index])
51
- );
50
+ const indexByMessageId = new Map(merged.map((event, index) => [event.message.messageId, index]));
52
51
  for (const event of liveEvents) {
53
52
  const existingIndex = indexByMessageId.get(event.message.messageId);
54
53
  if (existingIndex === void 0) {
@@ -93,7 +92,9 @@ function timeAgo(date) {
93
92
  }
94
93
  function isShellTool(message) {
95
94
  const values = [message.toolkit, message.tool].filter((value) => typeof value === "string").map((value) => value.trim().toLowerCase());
96
- return values.some((value) => value === "shell" || value === "exec" || value === "local_shell" || value === "local_shell_call" || value.includes("shell") || value.includes("exec"));
95
+ return values.some(
96
+ (value) => value === "shell" || value === "exec" || value === "local_shell" || value === "local_shell_call" || value.includes("shell") || value.includes("exec")
97
+ );
97
98
  }
98
99
  function canCollapseAsCommentary(message) {
99
100
  if (message.phase === "final_answer") {
@@ -210,7 +211,10 @@ function formatAgentUsageTooltip(usage) {
210
211
  }
211
212
  return lines.join("\n");
212
213
  }
213
- function AgentUsageFooter({ usage, className }) {
214
+ function AgentUsageFooter({
215
+ usage,
216
+ className
217
+ }) {
214
218
  const tooltip = usage === null ? void 0 : formatAgentUsageTooltip(usage);
215
219
  const label = usage === null ? "" : formatAgentUsageFooter(usage);
216
220
  return /* @__PURE__ */ jsx(
@@ -271,10 +275,16 @@ function ChatBubble({ text, mine }) {
271
275
  if (text.trim() === "") {
272
276
  return null;
273
277
  }
274
- return /* @__PURE__ */ jsx("div", { className: cn(
275
- "w-fit max-w-[85%] rounded-md px-4 py-3 text-sm leading-6 shadow-xs sm:max-w-2xl",
276
- mine ? "bg-secondary/85 text-foreground" : "bg-muted/70 text-foreground"
277
- ), children: /* @__PURE__ */ jsx(MarkdownBlock, { text }) });
278
+ return /* @__PURE__ */ jsx(
279
+ "div",
280
+ {
281
+ className: cn(
282
+ "w-fit max-w-[85%] rounded-md px-4 py-3 text-sm leading-6 shadow-xs sm:max-w-2xl",
283
+ mine ? "bg-secondary/85 text-foreground" : "bg-muted/70 text-foreground"
284
+ ),
285
+ children: /* @__PURE__ */ jsx(MarkdownBlock, { text })
286
+ }
287
+ );
278
288
  }
279
289
  function ReasoningTrace({ text, className }) {
280
290
  if (text.trim() === "") {
@@ -288,7 +298,16 @@ function trimShellText(value) {
288
298
  }
289
299
  return value.length < 1024 ? value : value.slice(0, 1024) + "...";
290
300
  }
291
- function ShellLine({ command, result, stdout, stderr, argumentsText, logs, title = "Terminal", className }) {
301
+ function ShellLine({
302
+ command,
303
+ result,
304
+ stdout,
305
+ stderr,
306
+ argumentsText,
307
+ logs,
308
+ title = "Terminal",
309
+ className
310
+ }) {
292
311
  const displayCommand = command?.trim() || title;
293
312
  const [expanded, setExpanded] = useState(title.toLowerCase().includes("error"));
294
313
  const trimmedResult = trimShellText(result);
@@ -314,7 +333,16 @@ function ShellLine({ command, result, stdout, stderr, argumentsText, logs, title
314
333
  children: expanded ? /* @__PURE__ */ jsx(ChevronDown, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(ChevronRight, { className: "h-4 w-4" })
315
334
  }
316
335
  ),
317
- /* @__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 })
336
+ /* @__PURE__ */ jsx(
337
+ "pre",
338
+ {
339
+ className: cn(
340
+ "min-w-0 flex-1 overflow-hidden whitespace-pre-wrap break-words font-mono text-xs leading-5 text-foreground",
341
+ expanded ? null : "line-clamp-1"
342
+ ),
343
+ children: displayCommand
344
+ }
345
+ )
318
346
  ] }),
319
347
  expanded && hasDetails ? /* @__PURE__ */ jsxs("div", { className: "space-y-2 border-t px-4 py-3", children: [
320
348
  trimmedResult != null ? /* @__PURE__ */ jsx("pre", { className: "whitespace-pre-wrap break-words font-mono text-xs leading-5 text-foreground", children: trimmedResult }) : null,
@@ -345,7 +373,13 @@ function eventLineDetails(details) {
345
373
  const lines = typeof details === "string" ? details.split(/\r?\n/) : details;
346
374
  return lines.map((line) => line.trim()).filter((line) => line !== "");
347
375
  }
348
- function EventLine({ headline, details, state = "info", failed = false, className }) {
376
+ function EventLine({
377
+ headline,
378
+ details,
379
+ state = "info",
380
+ failed = false,
381
+ className
382
+ }) {
349
383
  const normalizedHeadline = headline.trim();
350
384
  const detailLines = eventLineDetails(details);
351
385
  if (normalizedHeadline === "") {
@@ -381,7 +415,14 @@ function ToolCallLine({ message }) {
381
415
  const [expanded, setExpanded] = useState(message.failed === true);
382
416
  const hasDetails = detailLines.length > 0;
383
417
  if (!hasDetails) {
384
- return /* @__PURE__ */ jsx(EventLine, { headline: message.text, state: message.state ?? (message.failed === true ? "failed" : "completed"), failed: message.failed });
418
+ return /* @__PURE__ */ jsx(
419
+ EventLine,
420
+ {
421
+ headline: message.text,
422
+ state: message.state ?? (message.failed === true ? "failed" : "completed"),
423
+ failed: message.failed
424
+ }
425
+ );
385
426
  }
386
427
  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: [
387
428
  /* @__PURE__ */ jsxs(
@@ -394,11 +435,30 @@ function ToolCallLine({ message }) {
394
435
  "aria-label": expanded ? "Collapse tool details" : "Expand tool details",
395
436
  children: [
396
437
  /* @__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" }) }),
397
- /* @__PURE__ */ jsx("span", { className: cn("min-w-0 flex-1 text-xs font-semibold leading-5", eventLineStateClass(message.state, message.failed)), children: message.text })
438
+ /* @__PURE__ */ jsx(
439
+ "span",
440
+ {
441
+ className: cn(
442
+ "min-w-0 flex-1 text-xs font-semibold leading-5",
443
+ eventLineStateClass(message.state, message.failed)
444
+ ),
445
+ children: message.text
446
+ }
447
+ )
398
448
  ]
399
449
  }
400
450
  ),
401
- 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
451
+ expanded ? /* @__PURE__ */ jsx("div", { className: "space-y-2 border-t px-4 py-3", children: detailLines.map((line, index) => /* @__PURE__ */ jsx(
452
+ "pre",
453
+ {
454
+ className: cn(
455
+ "whitespace-pre-wrap break-words font-mono text-xs leading-5",
456
+ message.failed === true ? "text-destructive" : "text-muted-foreground"
457
+ ),
458
+ children: trimShellText(line)
459
+ },
460
+ index
461
+ )) }) : null
402
462
  ] });
403
463
  }
404
464
  function AttachmentView({ room, path }) {
@@ -406,7 +466,9 @@ function AttachmentView({ room, path }) {
406
466
  }
407
467
  function ChatImageAttachment({ room, path }) {
408
468
  const imagePath = attachmentImagePath(path) ?? path;
409
- const [url, setUrl] = useState(() => isInlineImageUrl(imagePath) || isHttpUrl(imagePath) ? imagePath : null);
469
+ const [url, setUrl] = useState(
470
+ () => isInlineImageUrl(imagePath) || isHttpUrl(imagePath) ? imagePath : null
471
+ );
410
472
  const [error, setError] = useState(null);
411
473
  useEffect(() => {
412
474
  let cancelled = false;
@@ -450,14 +512,21 @@ function ChatImageAttachment({ room, path }) {
450
512
  }
451
513
  );
452
514
  }
453
- function AttachmentDownloadButton({ room, path, className }) {
515
+ function AttachmentDownloadButton({
516
+ room,
517
+ path,
518
+ className
519
+ }) {
454
520
  const preview = normalizeAttachmentPath(path);
455
521
  const filename = filePreviewName(preview);
456
522
  return /* @__PURE__ */ jsxs(
457
523
  "button",
458
524
  {
459
525
  type: "button",
460
- 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),
526
+ className: cn(
527
+ "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",
528
+ className
529
+ ),
461
530
  onClick: () => {
462
531
  if (isInlineImageUrl(path) || isHttpUrl(path)) {
463
532
  window.open(path, "_blank", "noopener,noreferrer");
@@ -479,7 +548,16 @@ function AttachmentDownloadButton({ room, path, className }) {
479
548
  function ChatThreadPreview({ room, path, className }) {
480
549
  const normalizedPath = normalizeAttachmentPath(path);
481
550
  if (attachmentImagePath(path) != null) {
482
- 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 }) });
551
+ return /* @__PURE__ */ jsx(
552
+ "div",
553
+ {
554
+ className: cn(
555
+ "h-[312.5px] w-[312.5px] max-w-full overflow-hidden rounded-2xl bg-background",
556
+ className
557
+ ),
558
+ children: /* @__PURE__ */ jsx(ChatImageAttachment, { room, path })
559
+ }
560
+ );
483
561
  }
484
562
  return /* @__PURE__ */ jsx(AttachmentDownloadButton, { room, path: normalizedPath, className });
485
563
  }
@@ -575,12 +653,37 @@ function ThreadMessageView({
575
653
  const previousAuthor = previous?.authorName ?? (previous?.role === "user" ? localParticipantName : displayParticipantName(agentName));
576
654
  const shouldShowHeader = !forceHideHeader && (previous?.kind !== "message" || previousAuthor !== authorName);
577
655
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2", children: [
578
- 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: [
579
- authorName.trim() !== "" ? /* @__PURE__ */ jsx("span", { className: "font-semibold text-foreground", children: displayParticipantName(authorName) }) : null,
580
- /* @__PURE__ */ jsx("span", { children: timeAgo(message.createdAt) })
581
- ] }) }) }) : null,
656
+ 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(
657
+ "div",
658
+ {
659
+ className: cn(
660
+ "flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground",
661
+ mine ? "justify-end" : "justify-start"
662
+ ),
663
+ children: [
664
+ authorName.trim() !== "" ? /* @__PURE__ */ jsx("span", { className: "font-semibold text-foreground", children: displayParticipantName(authorName) }) : null,
665
+ /* @__PURE__ */ jsx("span", { children: timeAgo(message.createdAt) })
666
+ ]
667
+ }
668
+ ) }) }) : null,
582
669
  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,
583
- 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,
670
+ message.attachments.length > 0 ? /* @__PURE__ */ jsx("div", { className: cn("flex w-full", mine ? "justify-end" : "justify-start"), children: /* @__PURE__ */ jsx(
671
+ "div",
672
+ {
673
+ className: cn(
674
+ "flex max-w-[85%] flex-wrap gap-3 px-1 sm:max-w-2xl",
675
+ mine ? "justify-end" : "justify-start"
676
+ ),
677
+ children: message.attachments.map((attachment, index) => /* @__PURE__ */ jsx(
678
+ AttachmentView,
679
+ {
680
+ room,
681
+ path: attachment
682
+ },
683
+ `${message.id}:attachment:${attachment}:${index}`
684
+ ))
685
+ }
686
+ ) }) : null,
584
687
  message.image ? /* @__PURE__ */ jsx("div", { className: "flex w-full justify-start", children: /* @__PURE__ */ jsx(GeneratedImageView, { image: message.image }) }) : null
585
688
  ] });
586
689
  }
@@ -593,10 +696,7 @@ function EmptyState({ title, description }) {
593
696
  function LoadingState() {
594
697
  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" }) });
595
698
  }
596
- function ErrorBanner({
597
- message,
598
- onRetry
599
- }) {
699
+ function ErrorBanner({ message, onRetry }) {
600
700
  return /* @__PURE__ */ jsxs("div", { className: "mx-auto flex w-full max-w-[912px] items-center justify-between gap-3 whitespace-pre-wrap rounded-md border border-destructive/30 bg-destructive/5 px-4 py-3 text-sm text-destructive", children: [
601
701
  /* @__PURE__ */ jsx("span", { children: message }),
602
702
  onRetry ? /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", size: "sm", onClick: onRetry, children: "Retry restore" }) : null
@@ -652,7 +752,9 @@ function processClientToolRequests({
652
752
  if (toolsByName.size === 0) {
653
753
  return;
654
754
  }
655
- const requests = session.messages.map((event) => event.message).filter((message) => message instanceof AgentClientToolCallRequested).filter((message) => message.toolkit === "client" && toolsByName.has(message.tool));
755
+ const requests = session.messages.map((event) => event.message).filter(
756
+ (message) => message instanceof AgentClientToolCallRequested
757
+ ).filter((message) => message.toolkit === "client" && toolsByName.has(message.tool));
656
758
  const handledRequests = handledRequestsForSession(session);
657
759
  if (!initializedClientToolSessions.has(session)) {
658
760
  initializedClientToolSessions.add(session);
@@ -668,9 +770,11 @@ function processClientToolRequests({
668
770
  return;
669
771
  }
670
772
  replayingClientToolSessions.delete(session);
671
- const completedItemIds = new Set(session.messages.map((event) => event.message).filter((message) => message instanceof AgentToolCallEnded && message.toolkit === "client").map((message) => message.itemId));
773
+ const completedRequestIds = new Set(
774
+ buildChatThreadTimeline(session.messages).items.filter((item) => item.kind === "tool_call" && item.toolkit === "client" && (item.state === "completed" || item.state === "failed")).map((item) => item.clientToolRequestId ?? item.id)
775
+ );
672
776
  for (const request of requests) {
673
- if (completedItemIds.has(request.requestId)) {
777
+ if (completedRequestIds.has(request.requestId)) {
674
778
  handledRequests.add(request.requestId);
675
779
  }
676
780
  }
@@ -744,14 +848,20 @@ function AgentThreadProvider({
744
848
  closeThreadOnUnmount = false,
745
849
  onPersistedEventsInjectionStarted,
746
850
  onPersistedEventsInjected,
747
- onEventsChanged
851
+ onEventsChanged,
852
+ onSubmissionStarted,
853
+ onSubmissionFailed
748
854
  }) {
749
855
  const [attachments, setAttachments] = useState([]);
856
+ const [composerValue, setComposerValue] = useState("");
750
857
  const [sendError, setSendError] = useState(null);
751
858
  const [restorationError, setRestorationError] = useState(null);
752
859
  const [restorationAttempt, setRestorationAttempt] = useState(0);
753
860
  const [version, setVersion] = useState(0);
754
- const [clientToolCallOverrides, setClientToolCallOverrides] = useState(() => /* @__PURE__ */ new Map());
861
+ const [clientToolCallOverrides, setClientToolCallOverrides] = useState(
862
+ () => /* @__PURE__ */ new Map()
863
+ );
864
+ const attachmentStatusVersion = useAttachmentStatusVersion(attachments);
755
865
  const sessionRef = useRef(null);
756
866
  const mountedRef = useRef(true);
757
867
  const persistedEventsRef = useRef(persistedEvents);
@@ -760,14 +870,11 @@ function AgentThreadProvider({
760
870
  const restorationReadyRef = useRef(!injectPersistedEvents);
761
871
  const pendingCloseRef = useRef(null);
762
872
  const ownsChatClient = chatClient == null;
763
- const activeChatClient = useMemo(
764
- () => {
765
- if (chatClient != null) return chatClient;
766
- if (room != null) return new MessagingChatClient({ room, agentName });
767
- throw new Error("AgentThread requires either a room or a chat client.");
768
- },
769
- [agentName, chatClient, room]
770
- );
873
+ const activeChatClient = useMemo(() => {
874
+ if (chatClient != null) return chatClient;
875
+ if (room != null) return new MessagingChatClient({ room, agentName });
876
+ throw new Error("AgentThread requires either a room or a chat client.");
877
+ }, [agentName, chatClient, room]);
771
878
  const resolvedClientToolkits = useMemo(
772
879
  () => resolveClientToolkitDescriptions(clientToolkits, chatFeedWidgets, clientTools),
773
880
  [chatFeedWidgets, clientToolkits, clientTools]
@@ -854,7 +961,9 @@ function AgentThreadProvider({
854
961
  return;
855
962
  }
856
963
  restorationReadyRef.current = false;
857
- setRestorationError("Unable to restore conversation context: the server thread did not finish loading within 30 seconds.");
964
+ setRestorationError(
965
+ "Unable to restore conversation context: the server thread did not finish loading within 30 seconds."
966
+ );
858
967
  setVersion((current) => current + 1);
859
968
  }, threadLoadTimeoutMs);
860
969
  }
@@ -1022,24 +1131,32 @@ function AgentThreadProvider({
1022
1131
  }
1023
1132
  return persistedEvents == null ? buildChatThreadTimeline(session.messages, session.pendingInputs) : buildMergedChatThreadTimeline(persistedEvents, session.messages, session.pendingInputs);
1024
1133
  }, [deferLiveEvents, persistedEvents, session, version]);
1025
- const timelineItems = useMemo(() => (timeline?.items ?? []).map((item) => {
1026
- const override = session == null ? void 0 : clientToolCallOverrides.get(clientToolCallKey(session.threadPath, item.id));
1027
- if (override == null || item.kind !== "tool_call" || (item.state === "completed" || item.state === "failed")) {
1028
- return item;
1029
- }
1030
- return {
1031
- ...item,
1032
- state: override.status,
1033
- failed: override.status === "failed",
1034
- output: override.output ?? item.output
1035
- };
1036
- }), [clientToolCallOverrides, session, timeline]);
1134
+ const timelineItems = useMemo(
1135
+ () => (timeline?.items ?? []).map((item) => {
1136
+ const override = session == null ? void 0 : clientToolCallOverrides.get(clientToolCallKey(session.threadPath, item.clientToolRequestId ?? item.id));
1137
+ if (override == null || item.kind !== "tool_call" || item.state === "completed" || item.state === "failed") {
1138
+ return item;
1139
+ }
1140
+ return {
1141
+ ...item,
1142
+ state: override.status,
1143
+ failed: override.status === "failed",
1144
+ output: override.output ?? item.output
1145
+ };
1146
+ }),
1147
+ [clientToolCallOverrides, session, timeline]
1148
+ );
1037
1149
  const showThreadLoading = (deferLiveEvents || session === null || session.isLoading) && timelineItems.length === 0;
1038
1150
  const feedTimelineItems = useMemo(
1039
- () => timelineItems.filter((item) => !(item.kind === "tool_call" && item.toolkit === "client" && item.tool != null && clientToolsByName.has(item.tool))),
1151
+ () => timelineItems.filter(
1152
+ (item) => !(item.kind === "tool_call" && item.toolkit === "client" && item.tool != null && clientToolsByName.has(item.tool))
1153
+ ),
1040
1154
  [clientToolsByName, timelineItems]
1041
1155
  );
1042
- const renderedItems = useMemo(() => collapseMessages ? groupThreadItems(feedTimelineItems, chatFeedWidgetsByName) : feedTimelineItems, [chatFeedWidgetsByName, collapseMessages, feedTimelineItems]);
1156
+ const renderedItems = useMemo(
1157
+ () => collapseMessages ? groupThreadItems(feedTimelineItems, chatFeedWidgetsByName) : feedTimelineItems,
1158
+ [chatFeedWidgetsByName, collapseMessages, feedTimelineItems]
1159
+ );
1043
1160
  const status = useMemo(() => {
1044
1161
  if (session == null) return null;
1045
1162
  let current = null;
@@ -1060,7 +1177,19 @@ function AgentThreadProvider({
1060
1177
  const usage = timeline?.usage ?? null;
1061
1178
  const statusText = status?.status?.trim() || null;
1062
1179
  const turnId = stringValue(status?.turnId);
1063
- const canInterruptActiveTurn = turnId != null && (agentParticipant != null || chatClient != null);
1180
+ const interruptibleTurnId = useMemo(() => {
1181
+ let active = null;
1182
+ for (const event of session?.messages ?? []) {
1183
+ if (event.message instanceof TurnStarted) {
1184
+ active = event.message.turnId;
1185
+ }
1186
+ if (event.message instanceof TurnEnded && event.message.turnId === active) {
1187
+ active = null;
1188
+ }
1189
+ }
1190
+ return active ?? turnId;
1191
+ }, [session, version, turnId]);
1192
+ const canInterruptActiveTurn = interruptibleTurnId != null && (agentParticipant != null || chatClient != null);
1064
1193
  const renderedItemsNewestFirst = useMemo(() => [...renderedItems].reverse(), [renderedItems]);
1065
1194
  const firstRenderedItemId = renderedItems[0]?.id;
1066
1195
  const lastRenderedItemId = renderedItems[renderedItems.length - 1]?.id;
@@ -1071,94 +1200,149 @@ function AgentThreadProvider({
1071
1200
  });
1072
1201
  return previousById;
1073
1202
  }, [renderedItems]);
1074
- const selectAttachments = useCallback((files) => {
1075
- if (room == null) return;
1076
- const nextAttachments = files.map((file) => new MeshagentFileUpload(
1077
- room,
1078
- `uploaded-files/${file.name}`,
1079
- fileToAsyncIterable(file),
1080
- file.size
1081
- ));
1082
- setAttachments((current) => [...current, ...nextAttachments]);
1083
- }, [room]);
1084
- const handleSend = useCallback(async (message) => {
1085
- if (message.text.trim() === "" && message.attachments.length === 0) {
1086
- return;
1087
- }
1088
- if (!agentParticipant && chatClient == null) {
1089
- setSendError("This thread requires an online agent that supports agent messages.");
1090
- return;
1091
- }
1092
- const openSession = sessionRef.current;
1093
- if (openSession === null) {
1094
- setSendError("No thread session is open.");
1095
- return;
1096
- }
1097
- const normalizedAttachments = message.attachments.map(normalizeAgentAttachmentUrl).filter((attachment) => attachment !== null);
1098
- try {
1099
- await openSession.sendText({
1100
- messageId: message.id,
1101
- text: message.text,
1102
- attachments: normalizedAttachments.map((url) => new AgentFileContent({ url })),
1103
- turnId,
1104
- steer: status?.mode === "steerable" && turnId != null,
1105
- senderName: localParticipantName.trim() || void 0,
1106
- clientToolkits: resolvedClientToolkits
1107
- });
1108
- setSendError(null);
1109
- setVersion((current) => current + 1);
1110
- } catch (error) {
1111
- setSendError(describeError(error));
1112
- }
1113
- }, [agentParticipant, chatClient, resolvedClientToolkits, localParticipantName, status?.mode, turnId]);
1203
+ const selectAttachments = useCallback(
1204
+ (files) => {
1205
+ if (room == null) return;
1206
+ const nextAttachments = files.map(
1207
+ (file) => new MeshagentFileUpload(room, `uploaded-files/${file.name}`, fileToAsyncIterable(file), file.size)
1208
+ );
1209
+ setAttachments((current) => [...current, ...nextAttachments]);
1210
+ },
1211
+ [room]
1212
+ );
1213
+ const handleSend = useCallback(
1214
+ async (message) => {
1215
+ if (message.text.trim() === "" && message.attachments.length === 0) {
1216
+ return;
1217
+ }
1218
+ if (!agentParticipant && chatClient == null) {
1219
+ setSendError("This thread requires an online agent that supports agent messages.");
1220
+ return;
1221
+ }
1222
+ const openSession = sessionRef.current;
1223
+ if (openSession === null) {
1224
+ setSendError("No thread session is open.");
1225
+ return;
1226
+ }
1227
+ const normalizedAttachments = message.attachments.map(normalizeAgentAttachmentUrl).filter((attachment) => attachment !== null);
1228
+ const steeringTurnId = status?.mode === "steerable" && turnId != null ? turnId : void 0;
1229
+ onSubmissionStarted?.(message, steeringTurnId);
1230
+ try {
1231
+ await openSession.sendText({
1232
+ messageId: message.id,
1233
+ text: message.text,
1234
+ attachments: normalizedAttachments.map((url) => new AgentFileContent({ url })),
1235
+ turnId,
1236
+ steer: status?.mode === "steerable" && turnId != null,
1237
+ senderName: localParticipantName.trim() || void 0,
1238
+ clientToolkits: resolvedClientToolkits
1239
+ });
1240
+ setSendError(null);
1241
+ setVersion((current) => current + 1);
1242
+ } catch (error) {
1243
+ onSubmissionFailed?.(message, error);
1244
+ setSendError(describeError(error));
1245
+ }
1246
+ },
1247
+ [
1248
+ agentParticipant,
1249
+ chatClient,
1250
+ resolvedClientToolkits,
1251
+ localParticipantName,
1252
+ status?.mode,
1253
+ turnId,
1254
+ onSubmissionStarted,
1255
+ onSubmissionFailed
1256
+ ]
1257
+ );
1114
1258
  const composerDisabled = composerDisabledProp || loadThread && !restorationReadyRef.current || injectPersistedEvents && restoredPathRef.current !== path || agentParticipant == null && chatClient == null;
1115
- const handleWidgetMessage = useCallback((message) => {
1116
- const text = message.trim();
1117
- if (text === "" || composerDisabled) {
1118
- return;
1119
- }
1120
- void handleSend(new ChatMessage({
1121
- id: uuidV4(),
1122
- text
1123
- }));
1124
- }, [composerDisabled, handleSend]);
1259
+ const allAttachmentsUploaded = useMemo(
1260
+ () => attachments.every((attachment) => attachment.status === UploadStatus.Completed),
1261
+ [attachmentStatusVersion, attachments]
1262
+ );
1263
+ const canSubmit = !composerDisabled && (composerValue.trim() !== "" || attachments.length > 0) && allAttachmentsUploaded;
1264
+ const handleComposerSubmit = useCallback(
1265
+ (message) => {
1266
+ if (!canSubmit) {
1267
+ return;
1268
+ }
1269
+ void handleSend(message);
1270
+ setComposerValue("");
1271
+ setAttachments([]);
1272
+ },
1273
+ [canSubmit, handleSend]
1274
+ );
1275
+ const submitDraft = useCallback(() => {
1276
+ handleComposerSubmit(
1277
+ new ChatMessage({
1278
+ id: uuidV4(),
1279
+ text: composerValue.trim(),
1280
+ attachments: attachments.map((attachment) => attachment.path)
1281
+ })
1282
+ );
1283
+ }, [attachments, composerValue, handleComposerSubmit]);
1284
+ const handleWidgetMessage = useCallback(
1285
+ (message) => {
1286
+ const text = message.trim();
1287
+ if (text === "" || composerDisabled) {
1288
+ return;
1289
+ }
1290
+ void handleSend(
1291
+ new ChatMessage({
1292
+ id: uuidV4(),
1293
+ text
1294
+ })
1295
+ );
1296
+ },
1297
+ [composerDisabled, handleSend]
1298
+ );
1125
1299
  const cancelTurn = useCallback(async () => {
1126
1300
  const openSession = sessionRef.current;
1127
- if (openSession === null || turnId == null) {
1301
+ if (openSession === null || interruptibleTurnId == null) {
1128
1302
  return;
1129
1303
  }
1130
- await openSession.interruptTurn(turnId);
1131
- }, [turnId]);
1132
- return /* @__PURE__ */ jsx(AgentThreadContext.Provider, { value: {
1133
- room,
1134
- agentName,
1135
- emptyStateTitle,
1136
- emptyStateDescription,
1137
- chatFeedWidgetsByName,
1138
- timelineItems,
1139
- renderedItemsNewestFirst,
1140
- firstRenderedItemId,
1141
- lastRenderedItemId,
1142
- previousItemById,
1143
- showThreadLoading,
1144
- localParticipantName,
1145
- status,
1146
- statusText,
1147
- canInterruptActiveTurn,
1148
- restorationError,
1149
- retryRestoration,
1150
- handleWidgetMessage,
1151
- cancelTurn,
1152
- sendError,
1153
- composerDisabled,
1154
- handleSend,
1155
- attachments,
1156
- setAttachments,
1157
- selectAttachments,
1158
- enableFileUpload: enableFileUpload && room != null,
1159
- inputAvailable: agentParticipant != null || chatClient != null,
1160
- usage
1161
- }, children });
1304
+ await openSession.interruptTurn(interruptibleTurnId);
1305
+ }, [interruptibleTurnId]);
1306
+ return /* @__PURE__ */ jsx(
1307
+ AgentThreadContext.Provider,
1308
+ {
1309
+ value: {
1310
+ room,
1311
+ agentName,
1312
+ emptyStateTitle,
1313
+ emptyStateDescription,
1314
+ chatFeedWidgetsByName,
1315
+ timelineItems,
1316
+ renderedItemsNewestFirst,
1317
+ firstRenderedItemId,
1318
+ lastRenderedItemId,
1319
+ previousItemById,
1320
+ showThreadLoading,
1321
+ localParticipantName,
1322
+ status,
1323
+ statusText,
1324
+ canInterruptActiveTurn,
1325
+ restorationError,
1326
+ retryRestoration,
1327
+ handleWidgetMessage,
1328
+ cancelTurn,
1329
+ sendError,
1330
+ composerDisabled,
1331
+ composerValue,
1332
+ setComposerValue,
1333
+ canSubmit,
1334
+ handleComposerSubmit,
1335
+ submitDraft,
1336
+ attachments,
1337
+ setAttachments,
1338
+ selectAttachments,
1339
+ enableFileUpload: enableFileUpload && room != null,
1340
+ inputAvailable: agentParticipant != null || chatClient != null,
1341
+ usage
1342
+ },
1343
+ children
1344
+ }
1345
+ );
1162
1346
  }
1163
1347
  function useAgentThreadContext(componentName) {
1164
1348
  const context = useContext(AgentThreadContext);
@@ -1167,14 +1351,25 @@ function useAgentThreadContext(componentName) {
1167
1351
  }
1168
1352
  return context;
1169
1353
  }
1170
- function AgentThreadFeed() {
1354
+ function useAgentThreadFeedState() {
1355
+ const { renderedItemsNewestFirst } = useAgentThreadContext("useAgentThreadFeedState");
1356
+ return useMemo(() => ({ items: [...renderedItemsNewestFirst].reverse() }), [renderedItemsNewestFirst]);
1357
+ }
1358
+ function useAgentThreadStatus() {
1359
+ const { canInterruptActiveTurn, cancelTurn } = useAgentThreadContext("useAgentThreadStatus");
1360
+ return { canInterrupt: canInterruptActiveTurn, interrupt: cancelTurn };
1361
+ }
1362
+ function AgentThreadFeed({
1363
+ renderAfterItem,
1364
+ renderUnanchored,
1365
+ showStatusIndicator = true
1366
+ } = {}) {
1171
1367
  const {
1172
1368
  room,
1173
1369
  agentName,
1174
1370
  emptyStateTitle,
1175
1371
  emptyStateDescription,
1176
1372
  chatFeedWidgetsByName,
1177
- timelineItems,
1178
1373
  renderedItemsNewestFirst,
1179
1374
  firstRenderedItemId,
1180
1375
  lastRenderedItemId,
@@ -1189,9 +1384,11 @@ function AgentThreadFeed() {
1189
1384
  handleWidgetMessage,
1190
1385
  cancelTurn
1191
1386
  } = useAgentThreadContext("AgentThreadFeed");
1387
+ const unanchoredContent = renderUnanchored?.();
1388
+ const hasUnanchoredContent = Children.toArray(unanchoredContent).length > 0;
1192
1389
  return /* @__PURE__ */ jsxs(Fragment, { children: [
1193
1390
  /* @__PURE__ */ jsxs("div", { className: "relative flex h-full min-h-0 flex-1 flex-col", children: [
1194
- showThreadLoading ? /* @__PURE__ */ jsx("div", { className: "min-h-0 flex-1 overflow-hidden", children: /* @__PURE__ */ jsx(LoadingState, {}) }) : timelineItems.length === 0 ? /* @__PURE__ */ jsx("div", { className: "min-h-0 flex-1 overflow-hidden", children: /* @__PURE__ */ jsx(EmptyState, { title: emptyStateTitle, description: emptyStateDescription }) }) : /* @__PURE__ */ jsx(
1391
+ showThreadLoading ? /* @__PURE__ */ jsx("div", { className: "min-h-0 flex-1 overflow-hidden", children: /* @__PURE__ */ jsx(LoadingState, {}) }) : renderedItemsNewestFirst.length === 0 ? hasUnanchoredContent ? /* @__PURE__ */ jsx("div", { className: "min-h-0 flex-1 overflow-y-auto", children: /* @__PURE__ */ jsx("div", { className: "mx-auto w-full max-w-[912px] px-4 py-3", children: unanchoredContent }) }) : /* @__PURE__ */ jsx("div", { className: "min-h-0 flex-1 overflow-hidden", children: /* @__PURE__ */ jsx(EmptyState, { title: emptyStateTitle, description: emptyStateDescription }) }) : /* @__PURE__ */ jsx(
1195
1392
  ChatScroller,
1196
1393
  {
1197
1394
  bottomThresholdPx: 24,
@@ -1200,26 +1397,36 @@ function AgentThreadFeed() {
1200
1397
  getMessageAuthorId: (item) => item.role,
1201
1398
  messages: renderedItemsNewestFirst,
1202
1399
  renderMessage: (item) => {
1203
- return /* @__PURE__ */ jsx("div", { className: cn(
1204
- "mx-auto w-full max-w-[912px] px-1 py-3",
1205
- item.id === firstRenderedItemId ? "pt-6" : null,
1206
- item.id === lastRenderedItemId ? statusText ? "pb-24" : "pb-6" : null
1207
- ), children: /* @__PURE__ */ jsx(
1208
- ThreadMessageView,
1400
+ return /* @__PURE__ */ jsxs(
1401
+ "div",
1209
1402
  {
1210
- room,
1211
- message: item,
1212
- previous: previousItemById.get(item.id) ?? null,
1213
- localParticipantName,
1214
- agentName,
1215
- chatFeedWidgetsByName,
1216
- onSendMessage: handleWidgetMessage
1403
+ className: cn(
1404
+ "mx-auto w-full max-w-[912px] px-1 py-3",
1405
+ item.id === firstRenderedItemId ? "pt-6" : null,
1406
+ item.id === lastRenderedItemId ? showStatusIndicator && statusText ? "pb-24" : "pb-6" : null
1407
+ ),
1408
+ children: [
1409
+ item.id === firstRenderedItemId ? unanchoredContent : null,
1410
+ /* @__PURE__ */ jsx(
1411
+ ThreadMessageView,
1412
+ {
1413
+ room,
1414
+ message: item,
1415
+ previous: previousItemById.get(item.id) ?? null,
1416
+ localParticipantName,
1417
+ agentName,
1418
+ chatFeedWidgetsByName,
1419
+ onSendMessage: handleWidgetMessage
1420
+ }
1421
+ ),
1422
+ renderAfterItem?.(item)
1423
+ ]
1217
1424
  }
1218
- ) });
1425
+ );
1219
1426
  }
1220
1427
  }
1221
1428
  ),
1222
- 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(
1429
+ showStatusIndicator && 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(
1223
1430
  ChatTypingIndicator,
1224
1431
  {
1225
1432
  typing: false,
@@ -1234,21 +1441,24 @@ function AgentThreadFeed() {
1234
1441
  }
1235
1442
  ) }) }) : null
1236
1443
  ] }),
1237
- restorationError ? /* @__PURE__ */ jsx("div", { className: "px-4 pb-2", children: /* @__PURE__ */ jsx(
1238
- ErrorBanner,
1239
- {
1240
- message: restorationError,
1241
- onRetry: retryRestoration
1242
- }
1243
- ) }) : null
1444
+ restorationError ? /* @__PURE__ */ jsx("div", { className: "px-4 pb-2", children: /* @__PURE__ */ jsx(ErrorBanner, { message: restorationError, onRetry: retryRestoration }) }) : null
1244
1445
  ] });
1245
1446
  }
1246
- function AgentThreadInput() {
1447
+ function AgentThreadInput({
1448
+ className,
1449
+ inputRowClassName,
1450
+ textareaClassName,
1451
+ leadingButton,
1452
+ showSubmitButton = true,
1453
+ submitButtonComponent
1454
+ } = {}) {
1247
1455
  const {
1248
1456
  agentName,
1249
1457
  sendError,
1250
1458
  composerDisabled,
1251
- handleSend,
1459
+ composerValue,
1460
+ setComposerValue,
1461
+ handleComposerSubmit,
1252
1462
  attachments,
1253
1463
  setAttachments,
1254
1464
  selectAttachments,
@@ -1258,23 +1468,48 @@ function AgentThreadInput() {
1258
1468
  } = useAgentThreadContext("AgentThreadInput");
1259
1469
  return /* @__PURE__ */ jsxs(Fragment, { children: [
1260
1470
  sendError ? /* @__PURE__ */ jsx("div", { className: "px-4 pb-2", children: /* @__PURE__ */ jsx(ErrorBanner, { message: sendError }) }) : null,
1261
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
1262
- /* @__PURE__ */ jsx(
1263
- ChatInput,
1264
- {
1265
- onSubmit: handleSend,
1266
- attachments,
1267
- onFilesSelected: selectAttachments,
1268
- setAttachments,
1269
- enableFileUpload,
1270
- disabled: composerDisabled,
1271
- placeholder: inputAvailable ? "Type a message" : `Waiting for ${displayParticipantName(agentName)}`
1272
- }
1273
- ),
1274
- /* @__PURE__ */ jsx(AgentUsageFooter, { usage, className: "mx-auto w-full max-w-[912px]" })
1275
- ] })
1471
+ /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-1", children: /* @__PURE__ */ jsx(
1472
+ ChatInput,
1473
+ {
1474
+ className,
1475
+ inputRowClassName,
1476
+ textareaClassName,
1477
+ leadingButton,
1478
+ onSubmit: handleComposerSubmit,
1479
+ attachments,
1480
+ onFilesSelected: selectAttachments,
1481
+ setAttachments,
1482
+ enableFileUpload,
1483
+ disabled: composerDisabled,
1484
+ clearOnSubmit: false,
1485
+ value: composerValue,
1486
+ onValueChange: setComposerValue,
1487
+ showSubmitButton,
1488
+ submitButtonComponent,
1489
+ placeholder: inputAvailable ? "Type a message" : `Waiting for ${displayParticipantName(agentName)}`
1490
+ }
1491
+ ) })
1276
1492
  ] });
1277
1493
  }
1494
+ function AgentThreadSubmitButton({
1495
+ className,
1496
+ icon,
1497
+ title,
1498
+ ariaLabel
1499
+ } = {}) {
1500
+ const { canSubmit, submitDraft } = useAgentThreadContext("AgentThreadSubmitButton");
1501
+ return /* @__PURE__ */ jsx(
1502
+ ComposerActionButton,
1503
+ {
1504
+ className,
1505
+ disabled: !canSubmit,
1506
+ onClick: submitDraft,
1507
+ icon,
1508
+ title,
1509
+ ariaLabel
1510
+ }
1511
+ );
1512
+ }
1278
1513
  function AgentThread(props) {
1279
1514
  return /* @__PURE__ */ jsx(AgentThreadProvider, { ...props, children: /* @__PURE__ */ jsxs("div", { className: "flex h-full min-h-0 flex-1 flex-col", children: [
1280
1515
  /* @__PURE__ */ jsx(AgentThreadFeed, {}),
@@ -1286,6 +1521,7 @@ export {
1286
1521
  AgentThreadFeed,
1287
1522
  AgentThreadInput,
1288
1523
  AgentThreadProvider,
1524
+ AgentThreadSubmitButton,
1289
1525
  AgentToolChoice,
1290
1526
  AgentUsageFooter,
1291
1527
  AgentUsageSnapshot,
@@ -1296,5 +1532,7 @@ export {
1296
1532
  formatAgentUsageFooter,
1297
1533
  formatAgentUsageTokenCount,
1298
1534
  formatAgentUsageTooltip,
1299
- shouldReplaceAgentUsageSnapshot
1535
+ shouldReplaceAgentUsageSnapshot,
1536
+ useAgentThreadFeedState,
1537
+ useAgentThreadStatus
1300
1538
  };