@dbx-tools/ui-mastra 0.11.2 → 0.11.4

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.
package/index.react.ts CHANGED
@@ -34,7 +34,7 @@ export type { GenieFeedbackTarget, MessageFeedbackDestination } from "./src/reac
34
34
  export { useChatHistory } from "./src/react/chat-history.ts";
35
35
  export { useChatSessions } from "./src/react/chat-sessions.ts";
36
36
  export type { ThreadSessionReader, ThreadSessionUpdater, ThreadMessageWriter } from "./src/react/chat-sessions.ts";
37
- export { readMlflowTracePart, readThreadTitlePart, readModelUsagePart, readModelRoutePart, chatStatusForChunk, closeOnTerminalChunk, waitForTerminalChunk, useChatStream } from "./src/react/chat-stream.ts";
37
+ export { readMlflowTracePart, readThreadTitlePart, readModelUsagePart, readModelRoutePart, chatStatusForChunk, isTurnCompletionChunk, closeOnTerminalChunk, waitForTerminalChunk, useChatStream } from "./src/react/chat-stream.ts";
38
38
  export { ChatThreadLayout } from "./src/react/chat-thread-layout.tsx";
39
39
  export { TRANSCRIPT_FOLLOW_CANCEL_EVENTS, latestVisibleAssistantIndexInTurn, useChatTranscriptController, ChatTranscript } from "./src/react/chat-transcript.tsx";
40
40
  export type { ChatTranscriptController } from "./src/react/chat-transcript.tsx";
package/index.support.ts CHANGED
@@ -18,7 +18,7 @@ export * as threadPersistence from "./src/support/thread-persistence.ts";
18
18
  export * as threadSessions from "./src/support/thread-sessions.ts";
19
19
  export * as threadTabs from "./src/support/thread-tabs.ts";
20
20
  export * as toolEvents from "./src/support/tool-events.ts";
21
- export { activeRunStorageKey, readStoredActiveRuns, storeActiveRun, removeStoredActiveRun } from "./src/support/active-runs.ts";
21
+ export { activeRunsForThread, activeRunStorageKey, readStoredActiveRuns, storeActiveRun, removeStoredActiveRun } from "./src/support/active-runs.ts";
22
22
  export type { StoredActiveRun } from "./src/support/active-runs.ts";
23
23
  export { browserTranscriptStorageKey, readStoredBrowserTranscript, readBrowserMessageTimestamps, withBrowserMessageTimestamps, storeBrowserTranscript } from "./src/support/browser-transcript.ts";
24
24
  export type { BrowserMessageTimestamps } from "./src/support/browser-transcript.ts";
package/index.ts CHANGED
@@ -3,4 +3,4 @@
3
3
  // Hand edits are overwritten on the next generation; this file is read-only.
4
4
 
5
5
  export const PACKAGE_IDENTIFIER = "@dbx-tools/ui-mastra";
6
- export const PACKAGE_VERSION = "0.11.2";
6
+ export const PACKAGE_VERSION = "0.11.4";
package/package.json CHANGED
@@ -37,13 +37,13 @@
37
37
  },
38
38
  "dependencies": {
39
39
  "@databricks/appkit-ui": "0.106.0",
40
- "@dbx-tools/shared-auth": "0.11.2",
41
- "@dbx-tools/shared-core": "0.11.2",
42
- "@dbx-tools/shared-genie": "0.11.2",
43
- "@dbx-tools/shared-mastra": "0.11.2",
44
- "@dbx-tools/shared-model": "0.11.2",
45
- "@dbx-tools/shared-model-gateway": "0.11.2",
46
- "@dbx-tools/ui": "0.11.2",
40
+ "@dbx-tools/shared-auth": "0.11.4",
41
+ "@dbx-tools/shared-core": "0.11.4",
42
+ "@dbx-tools/shared-genie": "0.11.4",
43
+ "@dbx-tools/shared-mastra": "0.11.4",
44
+ "@dbx-tools/shared-model": "0.11.4",
45
+ "@dbx-tools/shared-model-gateway": "0.11.4",
46
+ "@dbx-tools/ui": "0.11.4",
47
47
  "@mastra/client-js": "1.62.0",
48
48
  "@mastra/core": "1.86.0",
49
49
  "@tanstack/react-table": "^8.21.3",
@@ -61,7 +61,7 @@
61
61
  "publishConfig": {
62
62
  "access": "public"
63
63
  },
64
- "version": "0.11.2",
64
+ "version": "0.11.4",
65
65
  "types": "index.ts",
66
66
  "dbxToolsConfig": {
67
67
  "tags": [
@@ -1,13 +1,13 @@
1
1
  import { Spinner } from "@databricks/appkit-ui/react";
2
2
 
3
- import { isActiveChatStatus, type ChatStatus } from "./types.ts";
3
+ import { isRespondingChatStatus, type ChatStatus } from "./types.ts";
4
4
 
5
5
  /** Whether an assistant bubble should show its active-response status. */
6
6
  export const shouldShowAssistantResponseStatus = (
7
7
  isLast: boolean,
8
8
  status: ChatStatus,
9
9
  hasVisibleResponse: boolean,
10
- ): boolean => isLast && hasVisibleResponse && isActiveChatStatus(status);
10
+ ): boolean => isLast && hasVisibleResponse && isRespondingChatStatus(status);
11
11
 
12
12
  /** Compact progress affordance for an active assistant response. */
13
13
  export const AssistantResponseSpinner = () => (
@@ -69,9 +69,15 @@ export const chatStatusForChunk = (chunk: UIMessageChunk): ChatStatus | undefine
69
69
  return undefined;
70
70
  };
71
71
 
72
+ /** Whether this chunk is the earliest authoritative end of the visible answer. */
73
+ export const isTurnCompletionChunk = (chunk: UIMessageChunk): boolean =>
74
+ (chunk as { type?: string }).type === RESPONSE_COMPLETE_PART_TYPE ||
75
+ chunk.type === "finish" ||
76
+ chunk.type === "abort";
77
+
72
78
  class StreamAborted extends Error {}
73
79
 
74
- /** Stop reading a background run once the AI SDK has delivered its terminal chunk. */
80
+ /** Stop reading once the AI SDK has delivered its real terminal chunk. */
75
81
  export function closeOnTerminalChunk(
76
82
  stream: ReadableStream<UIMessageChunk>,
77
83
  onTerminal?: () => void,
@@ -157,6 +163,7 @@ export function useChatStream({
157
163
  runIdRef: { current: string | null },
158
164
  signal: AbortSignal,
159
165
  turnStartedAt: string,
166
+ onVisibleComplete?: () => void,
160
167
  ) => {
161
168
  const recordTraceId = (traceId: string | undefined): void => {
162
169
  if (!traceId) return;
@@ -179,10 +186,38 @@ export function useChatStream({
179
186
 
180
187
  try {
181
188
  let terminalReceived = false;
189
+ let completedAt: string | undefined;
190
+ let completionNotified = false;
182
191
  let threadTitle: string | undefined;
183
192
  const existing = getSession(threadId).messages.find(
184
193
  (message) => message.id === assistantId,
185
194
  );
195
+ const markTurnComplete = (): void => {
196
+ if (completedAt) return;
197
+ completedAt = new Date().toISOString();
198
+ const messages = getSession(threadId).messages;
199
+ const assistant = messages.find((message) => message.id === assistantId);
200
+ if (!assistant) return;
201
+ writeMessages(
202
+ threadId,
203
+ upsertAssistant(
204
+ messages,
205
+ withBrowserMessageTimestamps(assistant, {
206
+ createdAt: turnStartedAt,
207
+ completedAt,
208
+ }),
209
+ ),
210
+ );
211
+ };
212
+ const notifyVisibleComplete = (): void => {
213
+ if (completionNotified || !completedAt) return;
214
+ const assistant = getSession(threadId).messages.find(
215
+ (message) => message.id === assistantId,
216
+ );
217
+ if (!assistant) return;
218
+ completionNotified = true;
219
+ onVisibleComplete?.();
220
+ };
186
221
  for await (const message of readUIMessageStream({
187
222
  ...(existing ? { message: existing } : {}),
188
223
  stream: closeOnTerminalChunk(
@@ -197,6 +232,7 @@ export function useChatStream({
197
232
  const modelUsage = readModelUsagePart(chunk);
198
233
  if (modelUsage) onModelUsage?.(modelUsage);
199
234
  threadTitle = readThreadTitlePart(chunk) ?? threadTitle;
235
+ if (isTurnCompletionChunk(chunk)) markTurnComplete();
200
236
  const status = chatStatusForChunk(chunk);
201
237
  if (!status) return;
202
238
  updateSession(threadId, (current) => ({
@@ -212,10 +248,11 @@ export function useChatStream({
212
248
  message.id === assistantId ? message : { ...message, id: assistantId },
213
249
  {
214
250
  createdAt: turnStartedAt,
215
- ...(terminalReceived ? { completedAt: new Date().toISOString() } : {}),
251
+ ...(completedAt ? { completedAt } : {}),
216
252
  },
217
253
  );
218
254
  writeMessages(threadId, upsertAssistant(getSession(threadId).messages, assistant));
255
+ notifyVisibleComplete();
219
256
  updateSession(threadId, (current) => ({
220
257
  ...current,
221
258
  runId: runIdRef.current,
@@ -223,10 +260,10 @@ export function useChatStream({
223
260
  }));
224
261
  }
225
262
  if (terminalReceived) {
226
- const completedAt = new Date().toISOString();
263
+ markTurnComplete();
227
264
  const messages = getSession(threadId).messages;
228
265
  const assistant = messages.find((message) => message.id === assistantId);
229
- if (assistant) {
266
+ if (assistant && completedAt) {
230
267
  writeMessages(
231
268
  threadId,
232
269
  upsertAssistant(
@@ -238,6 +275,7 @@ export function useChatStream({
238
275
  ),
239
276
  );
240
277
  }
278
+ notifyVisibleComplete();
241
279
  }
242
280
  return threadTitle;
243
281
  } catch (error) {
@@ -1,8 +1,10 @@
1
1
  import { getAuthStatus } from "@dbx-tools/shared-auth";
2
2
  import { hash, log, toError } from "@dbx-tools/shared-core";
3
3
  import {
4
+ FOLLOW_UP_SUGGESTIONS_PART_TYPE,
4
5
  isStaleMastraResumeError,
5
6
  type GenieVisualizationMode,
7
+ type FollowUpSuggestionMode,
6
8
  type ModelRoutePartData,
7
9
  type ModelUsagePartData,
8
10
  } from "@dbx-tools/shared-mastra";
@@ -23,6 +25,7 @@ import { ChatView } from "./chat-view.tsx";
23
25
  import { dedupeSuggestions } from "./suggestions.ts";
24
26
  import type { ChatViewProps, ThreadPlacement, ThreadSummary } from "./types.ts";
25
27
  import {
28
+ activeRunsForThread,
26
29
  activeRunStorageKey,
27
30
  readStoredActiveRuns,
28
31
  removeStoredActiveRun,
@@ -48,6 +51,7 @@ import {
48
51
  type MastraMemoryThread,
49
52
  type MastraStreamResponse,
50
53
  } from "../support/mastra-client.ts";
54
+ import { messageTextFromParts } from "../support/message-text.ts";
51
55
  import {
52
56
  defaultReasoningEffort,
53
57
  modelStorageKey,
@@ -244,6 +248,8 @@ export interface UseMastraChatOptions<
244
248
  * `[]` to force no suggestions.
245
249
  */
246
250
  suggestions?: string[];
251
+ /** Override the server-published post-turn suggestion policy for this chat instance. */
252
+ followUpSuggestions?: FollowUpSuggestionMode;
247
253
  /** Replace or omit the built-in empty transcript welcome block. */
248
254
  emptyState?: ChatViewProps["emptyState"];
249
255
  /**
@@ -348,6 +354,7 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
348
354
  [genieSpace, genieVisualization, mastraConfig.basePath, mastraConfig.defaultAgent],
349
355
  );
350
356
  const mastraClient = genieClient ?? pluginClient;
357
+ const followUpSuggestions = options.followUpSuggestions ?? mastraClient.followUpSuggestions;
351
358
  // Genie chats key persisted state (active thread, sidebar) by space alias.
352
359
  const agentId = genieSpace
353
360
  ? `genie:${genieSpace}`
@@ -497,7 +504,6 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
497
504
  loading: isLoadingThreads,
498
505
  error: threadsError,
499
506
  refresh: refreshThreads,
500
- sync: syncThreads,
501
507
  } = useMastraThreads(options.agentId, enableThreads, genieClient);
502
508
  // Persist the active thread id so a reload reopens the same
503
509
  // conversation. Best-effort; storage may be unavailable.
@@ -768,6 +774,49 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
768
774
  updateSession,
769
775
  writeMessages,
770
776
  });
777
+ const generateFollowUps = useCallback(
778
+ async (threadId: string, assistantId: string, userMessage: UIMessage) => {
779
+ if (genieSpace || (followUpSuggestions !== "auto" && followUpSuggestions !== "generated")) {
780
+ return;
781
+ }
782
+ const assistant = getSession(threadId).messages.find(
783
+ (message) => message.id === assistantId && message.role === "assistant",
784
+ );
785
+ if (!assistant) return;
786
+ const userText = messageTextFromParts(userMessage.parts).trim();
787
+ const answer = messageTextFromParts(assistant.parts).trim();
788
+ if (!userText || !answer) return;
789
+ try {
790
+ const questions = await mastraClient.generateSuggestions({
791
+ context: { "User message": userText, "Assistant answer": answer },
792
+ maxSuggestions: mastraClient.followUpSuggestionLimit,
793
+ existingSuggestions: [userText],
794
+ });
795
+ if (questions.length === 0) return;
796
+ const messages = getSession(threadId).messages;
797
+ const current = messages.find((message) => message.id === assistantId);
798
+ if (
799
+ !current ||
800
+ current.parts.some((part) => part.type === FOLLOW_UP_SUGGESTIONS_PART_TYPE)
801
+ ) {
802
+ return;
803
+ }
804
+ const part = {
805
+ type: FOLLOW_UP_SUGGESTIONS_PART_TYPE,
806
+ data: { questions, source: "model" as const },
807
+ } as UIMessage["parts"][number];
808
+ writeMessages(
809
+ threadId,
810
+ messages.map((message) =>
811
+ message.id === assistantId ? { ...message, parts: [...message.parts, part] } : message,
812
+ ),
813
+ );
814
+ } catch (error) {
815
+ logger.warn("follow-up suggestion generation failed", { error: toError(error) });
816
+ }
817
+ },
818
+ [followUpSuggestions, genieSpace, getSession, mastraClient, writeMessages],
819
+ );
771
820
  const driveStream = useCallback(
772
821
  async (
773
822
  threadId: string,
@@ -795,12 +844,21 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
795
844
  let sessionThreadId = threadId;
796
845
  let openedStream: MastraStreamResponse | undefined;
797
846
  let streamedTitle: string | undefined;
847
+ let followUpsStarted = false;
798
848
  const adoptAssignedThreadId = () => {
799
849
  const assigned = openedStream?.threadId?.();
800
850
  if (!assigned || assigned === sessionThreadId) return;
801
851
  adoptThreadId(sessionThreadId, assigned);
802
852
  sessionThreadId = assigned;
803
853
  };
854
+ const startFollowUps = () => {
855
+ if (followUpsStarted) return;
856
+ adoptAssignedThreadId();
857
+ const userMessage = lastUserMessage(getSession(sessionThreadId).messages);
858
+ if (!userMessage) return;
859
+ followUpsStarted = true;
860
+ void generateFollowUps(sessionThreadId, assistantId, userMessage);
861
+ };
804
862
  try {
805
863
  try {
806
864
  openedStream = await open(controller.signal);
@@ -811,6 +869,7 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
811
869
  runIdRef,
812
870
  controller.signal,
813
871
  turnStartedAt,
872
+ startFollowUps,
814
873
  );
815
874
  adoptAssignedThreadId();
816
875
  } catch (initialError) {
@@ -849,6 +908,7 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
849
908
  runIdRef,
850
909
  controller.signal,
851
910
  turnStartedAt,
911
+ startFollowUps,
852
912
  );
853
913
  } catch (reconnectError) {
854
914
  writeMessages(threadId, messagesBeforeReplay);
@@ -870,29 +930,6 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
870
930
  : prev,
871
931
  );
872
932
  }
873
- if (enableThreads) {
874
- const synchronized = await syncThreads();
875
- const generatedTitle = synchronized
876
- .find((thread) => thread.id === sessionThreadId)
877
- ?.title?.trim();
878
- if (generatedTitle) {
879
- setProvisionalTitles((prev) => ({
880
- ...prev,
881
- [sessionThreadId]: generatedTitle,
882
- }));
883
- setOptimisticThreads((prev) =>
884
- prev[sessionThreadId]
885
- ? {
886
- ...prev,
887
- [sessionThreadId]: {
888
- ...prev[sessionThreadId],
889
- title: generatedTitle,
890
- },
891
- }
892
- : prev,
893
- );
894
- }
895
- }
896
933
  updateSession(sessionThreadId, (session) => {
897
934
  if (session.runToken !== token) return session;
898
935
  return {
@@ -903,6 +940,7 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
903
940
  runId: runIdRef.current,
904
941
  };
905
942
  });
943
+ refreshThreadsSoon();
906
944
  if (getSession(sessionThreadId).runToken === token) {
907
945
  const completedRunId = runIdRef.current;
908
946
  if (completedRunId) removeStoredActiveRun(activeRunsKey, completedRunId);
@@ -955,10 +993,10 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
955
993
  activeRunsKey,
956
994
  enableThreads,
957
995
  getSession,
996
+ generateFollowUps,
958
997
  mastraClient,
959
998
  processStream,
960
999
  refreshThreadsSoon,
961
- syncThreads,
962
1000
  updateSession,
963
1001
  writeMessages,
964
1002
  ],
@@ -1009,6 +1047,7 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
1009
1047
  model,
1010
1048
  aiDecideStrategy: aiDecideStrategyRef.current,
1011
1049
  reasoningEffort: turnReasoningEffort,
1050
+ generateFollowUpSuggestions: false,
1012
1051
  requestContext,
1013
1052
  signal,
1014
1053
  });
@@ -1028,7 +1067,7 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
1028
1067
  const recoveredRunsKeyRef = useRef<string | undefined>(undefined);
1029
1068
  useEffect(() => {
1030
1069
  if (!persistenceReady || mastraClient.backgroundTurns) return;
1031
- for (const run of readStoredActiveRuns(activeRunsKey)) {
1070
+ for (const run of activeRunsForThread(readStoredActiveRuns(activeRunsKey), requestedThreadId)) {
1032
1071
  removeStoredActiveRun(activeRunsKey, run.runId);
1033
1072
  }
1034
1073
  }, [activeRunsKey, mastraClient.backgroundTurns, persistenceReady]);
@@ -1041,7 +1080,7 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
1041
1080
  return;
1042
1081
  }
1043
1082
  recoveredRunsKeyRef.current = activeRunsKey;
1044
- for (const run of readStoredActiveRuns(activeRunsKey)) {
1083
+ for (const run of activeRunsForThread(readStoredActiveRuns(activeRunsKey), requestedThreadId)) {
1045
1084
  const session = getSession(run.threadId);
1046
1085
  if (isSessionRunning(session) || session.runId === run.runId) continue;
1047
1086
  updateSession(run.threadId, (current) => ({
@@ -1083,6 +1122,7 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
1083
1122
  getSession,
1084
1123
  mastraClient,
1085
1124
  persistenceReady,
1125
+ requestedThreadId,
1086
1126
  updateSession,
1087
1127
  writeMessages,
1088
1128
  ]);
@@ -1737,7 +1777,7 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
1737
1777
  onStop: stop,
1738
1778
  suggestions,
1739
1779
  emptyState: options.emptyState,
1740
- followUpSuggestions: mastraClient.followUpSuggestions,
1780
+ followUpSuggestions,
1741
1781
  followUpSuggestionLimit: mastraClient.followUpSuggestionLimit,
1742
1782
  showSelectedModel: options.showSelectedModel ?? false,
1743
1783
  metrics: options.metrics,
@@ -33,6 +33,14 @@ export type StoredActiveRun = Omit<z.infer<typeof StoredActiveRunSchema>, "userM
33
33
  userMessage: UIMessage;
34
34
  };
35
35
 
36
+ /** Limit recovery to the fixed thread owned by an embedded chat instance. */
37
+ export function activeRunsForThread(
38
+ runs: readonly StoredActiveRun[],
39
+ threadId?: string,
40
+ ): StoredActiveRun[] {
41
+ return threadId ? runs.filter((run) => run.threadId === threadId) : [...runs];
42
+ }
43
+
36
44
  const StoredActiveRunFileSchema = z
37
45
  .object({
38
46
  version: z.literal(1).describe("Active run storage format version."),
@@ -254,6 +254,7 @@ export class MastraPluginClient extends MastraClient {
254
254
  model?: string;
255
255
  aiDecideStrategy?: AiDecideStrategy;
256
256
  reasoningEffort?: ReasoningEffort;
257
+ generateFollowUpSuggestions?: boolean;
257
258
  requestContext?: RequestContext;
258
259
  signal?: AbortSignal;
259
260
  }): Promise<MastraStreamResponse> {
@@ -266,6 +267,9 @@ export class MastraPluginClient extends MastraClient {
266
267
  ...(params.reasoningEffort
267
268
  ? { providerOptions: { openai: { reasoningEffort: params.reasoningEffort } } }
268
269
  : {}),
270
+ ...(params.generateFollowUpSuggestions !== undefined
271
+ ? { generateFollowUpSuggestions: params.generateFollowUpSuggestions }
272
+ : {}),
269
273
  ...(params.requestContext ? { requestContext: params.requestContext } : {}),
270
274
  },
271
275
  routing: params,