@dbx-tools/ui-mastra 0.9.182 → 0.9.185

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.
@@ -81,6 +81,7 @@ export type ThreadIdChangeReason = "hydrate" | "select" | "new" | "delete" | "mi
81
81
  // preserving the visual scroll position across the prepend.
82
82
 
83
83
  const logger = log.logger("ui-mastra/chat");
84
+ const STEER_INTERRUPT_SETTLEMENT_TIMEOUT_MS = 2_000;
84
85
 
85
86
  const makeUserMessage = (text: string, files: FileUIPart[] = []): UIMessage => ({
86
87
  id: hash.id(),
@@ -326,8 +327,9 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
326
327
  const enableFeedback = options.enableFeedback !== false;
327
328
  const feedbackModes = enableFeedback ? mastraClient.feedbackModes : [];
328
329
  const feedbackAvailable = feedbackModes.length > 0;
329
- const { url: mlflowExperimentUrl, tracePrefix: mlflowTracePrefix } =
330
- useMastraMlflowExperiment(feedbackModes.includes("mlflow"));
330
+ const { url: mlflowExperimentUrl, tracePrefix: mlflowTracePrefix } = useMastraMlflowExperiment(
331
+ feedbackModes.includes("mlflow"),
332
+ );
331
333
  const [resourceScope, setResourceScope] = useState<string | null>(null);
332
334
  useEffect(() => {
333
335
  let cancelled = false;
@@ -584,6 +586,20 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
584
586
  // `driveStream` (which invokes this) - the ref breaks that cycle without a
585
587
  // stale-closure hazard (assigned each render, same pattern as `loadMoreRef`).
586
588
  const drainQueueRef = useRef<(threadId: string) => void>(() => {});
589
+ const streamSettlementsRef = useRef(new Map<string, Promise<void>>());
590
+ const adoptedThreadIdsRef = useRef(new Map<string, string>());
591
+
592
+ const resolveThreadId = useCallback((threadId: string): string => {
593
+ let resolved = threadId;
594
+ const visited = new Set<string>();
595
+ while (!visited.has(resolved)) {
596
+ visited.add(resolved);
597
+ const next = adoptedThreadIdsRef.current.get(resolved);
598
+ if (!next) break;
599
+ resolved = next;
600
+ }
601
+ return resolved;
602
+ }, []);
587
603
 
588
604
  const activeThreadIdRef = useRef(activeThreadId);
589
605
  activeThreadIdRef.current = activeThreadId;
@@ -592,6 +608,12 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
592
608
  // switch to it when it is still the active thread.
593
609
  const adoptThreadId = useCallback(
594
610
  (localId: string, assignedId: string) => {
611
+ adoptedThreadIdsRef.current.set(localId, assignedId);
612
+ const settlement = streamSettlementsRef.current.get(localId);
613
+ if (settlement) {
614
+ streamSettlementsRef.current.delete(localId);
615
+ streamSettlementsRef.current.set(assignedId, settlement);
616
+ }
595
617
  moveSession(localId, assignedId);
596
618
  localThreadIdsRef.current.delete(localId);
597
619
  localThreadIdsRef.current.add(assignedId);
@@ -661,6 +683,7 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
661
683
  if (
662
684
  controller.signal.aborted ||
663
685
  getSession(threadId).runToken !== token ||
686
+ getSession(threadId).status === "error" ||
664
687
  initialError instanceof MastraChatRequestError ||
665
688
  !mastraClient.backgroundTurns ||
666
689
  !runId
@@ -841,7 +864,7 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
841
864
  const streamThreadId = threadId === DEFAULT_THREAD_SESSION_KEY ? undefined : threadId;
842
865
  const model = modelRef.current || undefined;
843
866
  const turnReasoningEffort = reasoningEffortRef.current;
844
- return driveStream(threadId, assistantId, (signal) => {
867
+ const settlement = driveStream(threadId, assistantId, (signal) => {
845
868
  return mastraClient.streamAgent({
846
869
  agentId,
847
870
  messages: turnMessages,
@@ -853,6 +876,14 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
853
876
  signal,
854
877
  });
855
878
  });
879
+ streamSettlementsRef.current.set(threadId, settlement);
880
+ const clearSettlement = () => {
881
+ for (const [settlementThreadId, current] of streamSettlementsRef.current) {
882
+ if (current === settlement) streamSettlementsRef.current.delete(settlementThreadId);
883
+ }
884
+ };
885
+ void settlement.then(clearSettlement, clearSettlement);
886
+ return settlement;
856
887
  },
857
888
  [activeRunsKey, driveStream, mastraClient, agentId, updateSession],
858
889
  );
@@ -992,14 +1023,31 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
992
1023
  async (threadId: string): Promise<void> => {
993
1024
  const current = getSession(threadId);
994
1025
  if (!isSessionRunning(current)) return;
1026
+ const localSettlement = streamSettlementsRef.current.get(threadId);
995
1027
  const streamThreadId = threadId === DEFAULT_THREAD_SESSION_KEY ? undefined : threadId;
996
1028
  const runId = current.runId;
1029
+ const settlementSignal = AbortSignal.timeout(STEER_INTERRUPT_SETTLEMENT_TIMEOUT_MS);
1030
+ const settlementTimeout = new Promise<void>((resolve) => {
1031
+ if (settlementSignal.aborted) resolve();
1032
+ else settlementSignal.addEventListener("abort", () => resolve(), { once: true });
1033
+ });
997
1034
  const settlement =
998
1035
  mastraClient.backgroundTurns && runId
999
1036
  ? mastraClient
1000
- .observeAgentStream({ agentId, runId, threadId: streamThreadId })
1037
+ .observeAgentStream({
1038
+ agentId,
1039
+ runId,
1040
+ threadId: streamThreadId,
1041
+ signal: settlementSignal,
1042
+ })
1001
1043
  .then((stream) => waitForTerminalChunk(stream.stream))
1002
1044
  .catch((error: unknown) => {
1045
+ if (settlementSignal.aborted) {
1046
+ logger.warn("interrupted background run did not settle before replacement", {
1047
+ runId,
1048
+ });
1049
+ return;
1050
+ }
1003
1051
  logger.warn("failed to observe interrupted background run", {
1004
1052
  runId,
1005
1053
  error: toError(error),
@@ -1033,6 +1081,7 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
1033
1081
  });
1034
1082
  await serverAbort;
1035
1083
  await settlement;
1084
+ if (localSettlement) await Promise.race([localSettlement, settlementTimeout]);
1036
1085
  },
1037
1086
  [activeRunsKey, agentId, getSession, mastraClient, updateSession],
1038
1087
  );
@@ -1100,10 +1149,10 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
1100
1149
  [appendUserMessage, runStream, activeKey, getSession, updateSession],
1101
1150
  );
1102
1151
 
1103
- // Fire a queued steer immediately, out of order: remove it from the queue,
1104
- // append it, and start a turn. `runStream`/`driveStream` supersede any
1105
- // in-flight run (abort + runToken bump + settle running pills), so this
1106
- // interrupts the current turn and sends the chosen steer now.
1152
+ // Fire a queued steer immediately, out of order. Wait for the interrupted
1153
+ // stream to publish and adopt any server-assigned thread id before appending
1154
+ // the replacement turn; otherwise a new direct Genie conversation can start
1155
+ // under the stale local thread id.
1107
1156
  const sendSteerNow = useCallback(
1108
1157
  (steerId: string) => {
1109
1158
  const threadId = activeKey;
@@ -1117,15 +1166,21 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
1117
1166
  logger.info("steer:send-now", { threadId });
1118
1167
  void (async () => {
1119
1168
  await interruptActiveRun(threadId);
1120
- const { message } = appendUserMessage(threadId, steer.text ?? "", steer.files);
1121
- void runStream(
1122
- threadId,
1123
- interruptedTurnMessages(current.messages, message),
1124
- steer.requestContext,
1125
- );
1169
+ const replacementThreadId = resolveThreadId(threadId);
1170
+ const { message } = appendUserMessage(replacementThreadId, steer.text ?? "", steer.files);
1171
+ const replacementMessages = interruptedTurnMessages(current.messages, message);
1172
+ void runStream(replacementThreadId, replacementMessages, steer.requestContext);
1126
1173
  })();
1127
1174
  },
1128
- [activeKey, appendUserMessage, getSession, interruptActiveRun, runStream, updateSession],
1175
+ [
1176
+ activeKey,
1177
+ appendUserMessage,
1178
+ getSession,
1179
+ interruptActiveRun,
1180
+ resolveThreadId,
1181
+ runStream,
1182
+ updateSession,
1183
+ ],
1129
1184
  );
1130
1185
 
1131
1186
  // Drop a queued steer without sending it.
@@ -9,7 +9,7 @@ import { parse, toLabel, capitalize } from "@dbx-tools/shared-core";
9
9
  import { humanizeStatus } from "@dbx-tools/shared-genie";
10
10
  import { detectCodeLanguage, JsonBlock, RecordPreview } from "@dbx-tools/ui/react";
11
11
  import { CheckIcon, ChevronDownIcon, XIcon } from "lucide-react";
12
- import { SourceBlock, ToolMarkdown } from "./markdown.tsx";
12
+ import { CHAT_LINK_SAFETY, SourceBlock, ToolMarkdown } from "./markdown.tsx";
13
13
  import type { ToolEvent, ToolProgress } from "./types.ts";
14
14
 
15
15
  // Consolidated tool-session pill and its Genie progress detail view:
@@ -298,7 +298,7 @@ const MessageGroupBody = ({
298
298
  // opens directly to its SQL instead of adding a redundant
299
299
  // second "SQL" pill around the only child.
300
300
  <Collapsible key={bucket.key} className="rounded border border-border/60 bg-background/40">
301
- <CollapsibleTrigger className="group flex w-full items-center gap-1.5 px-2 py-1 text-left text-xs uppercase tracking-wide text-muted-foreground hover:text-foreground">
301
+ <CollapsibleTrigger className="group flex w-full items-center gap-1.5 py-1 pl-0 pr-1 text-left text-xs uppercase tracking-wide text-muted-foreground hover:text-foreground">
302
302
  <ChevronDownIcon className="size-3 shrink-0 transition-transform group-data-[state=closed]:-rotate-90" />
303
303
  <span>{queryBuckets.length > 1 ? `Query ${i + 1}` : "Query"}</span>
304
304
  {bucket.query?.title ? (
@@ -412,13 +412,20 @@ const RawToolPayload = ({
412
412
  <CollapsibleContent className="min-w-0 max-w-full overflow-hidden">
413
413
  <div className="max-h-48 max-w-full overflow-auto overscroll-contain sm:max-h-64">
414
414
  {structured === undefined ? (
415
- <JsonBlock
416
- json={formatRawToolPayload(value)}
417
- className="py-2 leading-tight text-foreground sm:leading-relaxed"
418
- />
415
+ typeof value === "string" ? (
416
+ <div className="px-2 py-1.5">
417
+ <ToolMarkdown>{value}</ToolMarkdown>
418
+ </div>
419
+ ) : (
420
+ <JsonBlock
421
+ json={formatRawToolPayload(value)}
422
+ className="py-2 leading-tight text-foreground sm:leading-relaxed"
423
+ />
424
+ )
419
425
  ) : (
420
426
  <RecordPreview
421
427
  value={structured}
428
+ linkSafety={CHAT_LINK_SAFETY}
422
429
  className="max-w-full bg-transparent text-foreground [&_pre]:rounded-none [&_pre]:bg-transparent"
423
430
  />
424
431
  )}
@@ -591,14 +598,18 @@ const WebSearchProgressDetails = ({ event }: { event: ToolEvent }) => {
591
598
  };
592
599
 
593
600
  /** Latest cumulative detail emitted by a non-search tool. */
594
- const ToolStatusProgressDetails = ({ event }: { event: ToolEvent }) => {
595
- if (event.toolName === "web_search") return null;
596
- const detail = [...(event.progress ?? [])]
601
+ const toolStatusProgressDetail = (event: ToolEvent): string | undefined => {
602
+ if (event.toolName === "web_search") return undefined;
603
+ return [...(event.progress ?? [])]
597
604
  .reverse()
598
605
  .find(
599
606
  (progress): progress is ToolStatusProgress =>
600
607
  progress.type === "tool_status" && Boolean(progress.detail?.trim()),
601
608
  )?.detail;
609
+ };
610
+
611
+ const ToolStatusProgressDetails = ({ event }: { event: ToolEvent }) => {
612
+ const detail = toolStatusProgressDetail(event);
602
613
  if (!detail) return null;
603
614
  return (
604
615
  <SourceBlock
@@ -616,8 +627,10 @@ const ToolStatusProgressDetails = ({ event }: { event: ToolEvent }) => {
616
627
  * a row whose only content is the question stays non-expandable.
617
628
  */
618
629
  const hasExpandableDetails = (event: ToolEvent): boolean => {
619
- if (event.status === "running") return true;
620
- if ("input" in event || "output" in event) return true;
630
+ if (!event.toolName.startsWith("ask_genie") && event.input !== undefined) return true;
631
+ if (event.output !== undefined) return true;
632
+ if (webSearchProgressGroups(event).length > 0) return true;
633
+ if (toolStatusProgressDetail(event)) return true;
621
634
  const summary = summarizeProgress(event.progress ?? []);
622
635
  return summary.groups.some(
623
636
  (g) => g.attachments.some(isAttachmentRenderable) || g.errors.length > 0,
@@ -724,7 +737,7 @@ const ToolCallRow = ({ event }: { event: ToolEvent }) => {
724
737
  return (
725
738
  <Collapsible className="min-w-0 max-w-full overflow-hidden rounded border border-border/40 bg-background/30">
726
739
  <CollapsibleTrigger className="group flex w-full items-start gap-2 px-2 py-1 text-left text-xs text-muted-foreground cursor-pointer hover:text-foreground">
727
- <ChevronDownIcon className="mt-0.5 size-3 shrink-0 transition-transform group-data-[state=open]:rotate-180" />
740
+ <ChevronDownIcon className="mt-0.5 size-3 shrink-0 transition-transform group-data-[state=closed]:-rotate-90" />
728
741
  <span className="mt-0.5 shrink-0">
729
742
  <ToolStatusIcon status={event.status} />
730
743
  </span>
@@ -774,6 +787,32 @@ export const ToolSessionPill = ({ events }: { events: ToolEvent[] }) => {
774
787
  ? `Calling ${latestName}`
775
788
  : `Called ${latestName}`;
776
789
  const countSuffix = events.length > 1 ? ` · ${events.length} calls` : "";
790
+ const expandable =
791
+ events.length > 1 || hasExpandableDetails(latest) || Boolean(askGenieQuestion(latest));
792
+
793
+ const header = (
794
+ <>
795
+ {expandable ? (
796
+ <ChevronDownIcon className="size-3 shrink-0 transition-transform group-data-[state=closed]:-rotate-90" />
797
+ ) : null}
798
+ <ToolStatusIcon status={tone} />
799
+ <span
800
+ className={cn(
801
+ "min-w-0 flex-1 truncate",
802
+ tone === "running" && "animate-pulse text-foreground/90",
803
+ )}
804
+ >
805
+ {verb}
806
+ {countSuffix}
807
+ </span>
808
+ {tone === "running" && (
809
+ <span className="relative ml-1 flex size-2 shrink-0" aria-hidden>
810
+ <span className="absolute inline-flex size-full animate-ping rounded-full bg-primary/60" />
811
+ <span className="relative inline-flex size-2 rounded-full bg-primary" />
812
+ </span>
813
+ )}
814
+ </>
815
+ );
777
816
 
778
817
  return (
779
818
  <div
@@ -790,53 +829,31 @@ export const ToolSessionPill = ({ events }: { events: ToolEvent[] }) => {
790
829
  : "border-border/40",
791
830
  )}
792
831
  >
793
- <Collapsible>
794
- <CollapsibleTrigger className="group flex w-full items-center gap-2 text-left text-xs text-muted-foreground cursor-pointer hover:text-foreground">
795
- <ChevronDownIcon className="size-3 shrink-0 transition-transform group-data-[state=open]:rotate-180" />
796
- <ToolStatusIcon status={tone} />
797
- {/*
798
- * Verb + count share one span so the `·` separator reads
799
- * as a natural inline divider. `min-w-0` lets the truncate
800
- * clip without forcing the row to overflow when the verb
801
- * is long.
802
- */}
803
- <span
804
- className={cn(
805
- "min-w-0 flex-1 truncate",
806
- tone === "running" && "animate-pulse text-foreground/90",
807
- )}
808
- >
809
- {verb}
810
- {countSuffix}
811
- </span>
812
- {/*
813
- * Trailing "live" pip on the right edge while any tool is
814
- * in flight. Two-layer: a static dot under an animated
815
- * ping ring, matching the convention native chat apps use
816
- * for active recording / streaming indicators.
817
- */}
818
- {tone === "running" && (
819
- <span className="relative ml-1 flex size-2 shrink-0" aria-hidden>
820
- <span className="absolute inline-flex size-full animate-ping rounded-full bg-primary/60" />
821
- <span className="relative inline-flex size-2 rounded-full bg-primary" />
822
- </span>
823
- )}
824
- </CollapsibleTrigger>
825
- <CollapsibleContent className="min-w-0 max-w-full overflow-hidden">
826
- <div
827
- className={cn(
828
- "mt-1.5 min-w-0 max-w-full overflow-hidden",
829
- events.length > 1 && "flex flex-col gap-1",
830
- )}
831
- >
832
- {events.length === 1 ? (
833
- <ToolCallDetails event={latest} showQuestion />
834
- ) : (
835
- events.map((event) => <ToolCallRow key={event.id} event={event} />)
836
- )}
837
- </div>
838
- </CollapsibleContent>
839
- </Collapsible>
832
+ {expandable ? (
833
+ <Collapsible>
834
+ <CollapsibleTrigger className="group flex w-full cursor-pointer items-center gap-2 text-left text-xs text-muted-foreground hover:text-foreground">
835
+ {header}
836
+ </CollapsibleTrigger>
837
+ <CollapsibleContent className="min-w-0 max-w-full overflow-hidden">
838
+ <div
839
+ className={cn(
840
+ "mt-1.5 min-w-0 max-w-full overflow-hidden",
841
+ events.length > 1 && "flex flex-col gap-1",
842
+ )}
843
+ >
844
+ {events.length === 1 ? (
845
+ <ToolCallDetails event={latest} showQuestion />
846
+ ) : (
847
+ events.map((event) => <ToolCallRow key={event.id} event={event} />)
848
+ )}
849
+ </div>
850
+ </CollapsibleContent>
851
+ </Collapsible>
852
+ ) : (
853
+ <div className="flex w-full items-center gap-2 text-left text-xs text-muted-foreground">
854
+ {header}
855
+ </div>
856
+ )}
840
857
  </div>
841
858
  );
842
859
  };
@@ -69,6 +69,7 @@ export type ChatModelOption = Pick<
69
69
  */
70
70
  export type ChatInputMessage = { text?: string; files?: FileUIPart[] };
71
71
 
72
+ /** Queued chat input with the stable identifier used for ordering and removal. */
72
73
  export type QueuedSteer = ChatInputMessage & { id: string };
73
74
 
74
75
  /** Thumbs reaction a user can leave on an assistant turn. */
package/src/styles.css CHANGED
@@ -20,18 +20,3 @@
20
20
  @import "@dbx-tools/ui/styles.css";
21
21
 
22
22
  @source "./react";
23
-
24
- [data-slot="aui_thread-viewport"][data-keyboard-touch-scroller] {
25
- scrollbar-width: none;
26
- }
27
-
28
- [data-slot="aui_thread-viewport"][data-keyboard-touch-scroller]::-webkit-scrollbar {
29
- display: none;
30
- width: 0;
31
- height: 0;
32
- }
33
-
34
- [data-slot="aui_thread-frame"][data-ios-keyboard-open] {
35
- overscroll-behavior: none;
36
- touch-action: none;
37
- }
@@ -38,8 +38,8 @@ export class GenieChatClient extends MastraPluginClient {
38
38
  override readonly threadRename = false;
39
39
  override readonly attachments = false;
40
40
  override readonly followUpSuggestions: "none" | "genie";
41
- /** Thread ids known to be Genie conversations (listed, loaded, or announced). */
42
- readonly #conversations = new Set<string>();
41
+ /** Local and resolved thread ids mapped to their Genie conversation id. */
42
+ readonly #conversationIds = new Map<string, string>();
43
43
  /** Transcript message id to Genie message id, for regenerate cleanup. */
44
44
  readonly #genieMessageIds = new Map<string, string>();
45
45
 
@@ -57,6 +57,17 @@ export class GenieChatClient extends MastraPluginClient {
57
57
  return `${this.basePath}${genieRoutePath(this.alias, ...parts)}`;
58
58
  }
59
59
 
60
+ #rememberConversation(threadId: string | undefined, conversationId: string): void {
61
+ this.#conversationIds.set(conversationId, conversationId);
62
+ if (threadId) this.#conversationIds.set(threadId, conversationId);
63
+ }
64
+
65
+ #forgetConversation(conversationId: string): void {
66
+ for (const [threadId, resolvedId] of this.#conversationIds) {
67
+ if (resolvedId === conversationId) this.#conversationIds.delete(threadId);
68
+ }
69
+ }
70
+
60
71
  async #delete(url: string, signal?: AbortSignal): Promise<void> {
61
72
  const res = await fetch(url, {
62
73
  method: "DELETE",
@@ -79,8 +90,7 @@ export class GenieChatClient extends MastraPluginClient {
79
90
  .map((part) => (part.type === "text" ? part.text : ""))
80
91
  .join("")
81
92
  .trim();
82
- const conversationId =
83
- params.threadId && this.#conversations.has(params.threadId) ? params.threadId : undefined;
93
+ const conversationId = params.threadId ? this.#conversationIds.get(params.threadId) : undefined;
84
94
  const response = await this.uiStream({
85
95
  path: this.#url(MASTRA_ROUTES.chat),
86
96
  chatId: params.threadId ?? params.runId,
@@ -101,7 +111,7 @@ export class GenieChatClient extends MastraPluginClient {
101
111
  const data = GenieConversationPartDataSchema.safeParse(chunk.data);
102
112
  if (data.success) {
103
113
  resolved = data.data.conversationId;
104
- this.#conversations.add(resolved);
114
+ this.#rememberConversation(params.threadId, resolved);
105
115
  if (userMessage && data.data.messageId) {
106
116
  this.#genieMessageIds.set(userMessage.id, data.data.messageId);
107
117
  }
@@ -148,7 +158,7 @@ export class GenieChatClient extends MastraPluginClient {
148
158
  GenieThreadsResponseSchema,
149
159
  options.signal,
150
160
  );
151
- for (const thread of payload.threads) this.#conversations.add(thread.id);
161
+ for (const thread of payload.threads) this.#rememberConversation(thread.id, thread.id);
152
162
  const threads = payload.threads.map((thread) => ({
153
163
  id: thread.id,
154
164
  ...(thread.title ? { title: thread.title } : {}),
@@ -184,7 +194,7 @@ export class GenieChatClient extends MastraPluginClient {
184
194
  options.signal,
185
195
  );
186
196
  messages = await validateUIMessages({ messages: payload.messages });
187
- this.#conversations.add(options.threadId);
197
+ this.#rememberConversation(options.threadId, options.threadId);
188
198
  // History ids already address their Genie message; the delete route
189
199
  // resolves a question id to the message that owns it.
190
200
  for (const message of messages) this.#genieMessageIds.set(message.id, message.id);
@@ -204,9 +214,10 @@ export class GenieChatClient extends MastraPluginClient {
204
214
  threadId: string,
205
215
  options: { signal?: AbortSignal } = {},
206
216
  ): Promise<void> {
207
- if (!this.#conversations.has(threadId)) return;
208
- await this.#delete(this.#url(MASTRA_ROUTES.threads, threadId), options.signal);
209
- this.#conversations.delete(threadId);
217
+ const conversationId = this.#conversationIds.get(threadId);
218
+ if (!conversationId) return;
219
+ await this.#delete(this.#url(MASTRA_ROUTES.threads, conversationId), options.signal);
220
+ this.#forgetConversation(conversationId);
210
221
  }
211
222
 
212
223
  /** Clearing a Genie thread deletes its conversation; the next turn starts a new one. */
@@ -225,7 +236,8 @@ export class GenieChatClient extends MastraPluginClient {
225
236
  messageIds: string[],
226
237
  options: { signal?: AbortSignal } = {},
227
238
  ): Promise<void> {
228
- if (!this.#conversations.has(threadId)) return;
239
+ const conversationId = this.#conversationIds.get(threadId);
240
+ if (!conversationId) return;
229
241
  const genieIds = new Set(
230
242
  messageIds.flatMap((id) => {
231
243
  const genieId = this.#genieMessageIds.get(id);
@@ -234,7 +246,7 @@ export class GenieChatClient extends MastraPluginClient {
234
246
  );
235
247
  for (const genieId of genieIds) {
236
248
  await this.#delete(
237
- this.#url(MASTRA_ROUTES.threads, threadId, MASTRA_ROUTES.messages, genieId),
249
+ this.#url(MASTRA_ROUTES.threads, conversationId, MASTRA_ROUTES.messages, genieId),
238
250
  options.signal,
239
251
  );
240
252
  }
@@ -987,10 +987,9 @@ export const useMastraThreads = (
987
987
  }
988
988
  const controller = new AbortController();
989
989
  if (!hasLoadedRef.current) setLoading(true);
990
- void load(controller.signal)
991
- .finally(() => {
992
- if (!controller.signal.aborted) setLoading(false);
993
- });
990
+ void load(controller.signal).finally(() => {
991
+ if (!controller.signal.aborted) setLoading(false);
992
+ });
994
993
  return () => controller.abort();
995
994
  }, [enabled, load, nonce]);
996
995
 
@@ -1,3 +1,4 @@
1
+ import { GenieMessageSchema } from "@dbx-tools/shared-genie";
1
2
  import {
2
3
  GENIE_PROGRESS_PART_TYPE,
3
4
  GenieProgressPartDataSchema,
@@ -16,6 +17,39 @@ export function compactReasoningText(text: string): string {
16
17
  .join(" ");
17
18
  }
18
19
 
20
+ /** Read reasoning persisted in a completed Genie's message attachments. */
21
+ export function genieOutputReasoningSections(output: unknown): string[] {
22
+ if (!output || typeof output !== "object") return [];
23
+ const candidate = "message" in output ? output.message : output;
24
+ const parsed = GenieMessageSchema.safeParse(candidate);
25
+ if (!parsed.success) return [];
26
+
27
+ return (parsed.data.attachments ?? []).flatMap((attachment) =>
28
+ (attachment.query?.thoughts ?? []).flatMap((thought) => {
29
+ const text = compactReasoningText(thought.content);
30
+ return text ? [text] : [];
31
+ }),
32
+ );
33
+ }
34
+
35
+ /** Collect one tool's streamed and persisted reasoning without duplicates. */
36
+ export function toolReasoningSections(event: ToolEvent): string[] {
37
+ const sections: string[] = [];
38
+ const seen = new Set<string>();
39
+ const append = (text: string) => {
40
+ if (!text || seen.has(text)) return;
41
+ seen.add(text);
42
+ sections.push(text);
43
+ };
44
+
45
+ for (const progress of event.progress ?? []) {
46
+ if (progress.type !== "thinking") continue;
47
+ append(compactReasoningText(progress.text));
48
+ }
49
+ for (const text of genieOutputReasoningSections(event.output)) append(text);
50
+ return sections;
51
+ }
52
+
19
53
  /**
20
54
  * Collect Genie `thinking` events for the assistant Thoughts panel.
21
55
  *
@@ -25,13 +59,7 @@ export function compactReasoningText(text: string): string {
25
59
  */
26
60
  export function genieReasoningText(events: ToolEvent[]): string {
27
61
  const sections: string[] = [];
28
- for (const event of events) {
29
- for (const progress of event.progress ?? []) {
30
- if (progress.type !== "thinking") continue;
31
- const text = compactReasoningText(progress.text);
32
- if (text) sections.push(text);
33
- }
34
- }
62
+ for (const event of events) sections.push(...toolReasoningSections(event));
35
63
  return sections.join("\n");
36
64
  }
37
65