@dbx-tools/ui-mastra 0.9.190 → 0.9.194

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/README.md CHANGED
@@ -186,6 +186,20 @@ Configure the client with these options:
186
186
  - `agentId` selects a registered agent and defaults to the plugin default agent.
187
187
  - `genieSpace` selects a configured Genie alias and bypasses the agent.
188
188
  - `showModelPicker` fetches `/models` and sends `X-Mastra-Model` overrides.
189
+ - `showSelectedModel` adds the friendly model name to the assistant footer as
190
+ soon as routing completes, with the concrete serving endpoint on hover or
191
+ keyboard focus. It is off by default.
192
+ - `metrics` adds one or more right-aligned per-turn footer counters: `tokens`,
193
+ `time`, `dbu`, or `usd`. It is off by default. Hovering or focusing the
194
+ metric group shows all four values even when only a subset is visible.
195
+ - `enableRetry={false}` hides retry actions. Retry is enabled by default.
196
+ - `onModelRoute` receives the concrete endpoint as soon as routing completes.
197
+ - `onModelUsage` receives the latest cumulative tokens after each completed
198
+ model step, along with the resolved endpoint, Smart Router observation when
199
+ applicable, plus estimated DBU cost when Databricks publishes token rates.
200
+ `onModelRoute` also carries the selected standard list-price row and
201
+ Databricks USD-per-DBU prices by cloud so clients can derive cloud-specific
202
+ costs while response text is still streaming.
189
203
  - `composerActions` places host-owned per-turn controls beside the model
190
204
  selector without replacing the built-in composer.
191
205
  - `modelSelectorActions` places host-owned controls inside the model menu after
@@ -203,6 +217,13 @@ Configure the client with these options:
203
217
  - `threadId` and `onThreadIdChange` let a host bind the active conversation to
204
218
  URL state or another external selector. Unknown external IDs are replaced by
205
219
  a new thread and reported with the `missing` reason.
220
+ - `conversationHistory="browser"` sends the complete browser-held transcript
221
+ with each turn for agents without Mastra memory. The default `"memory"`
222
+ sends only the newest message because the persisted Mastra thread is the
223
+ authoritative history.
224
+ - `browserPersistence` stores that browser-held transcript in local storage,
225
+ scoped by plugin mount, agent, signed-in resource, and thread. Pass `true`
226
+ for the default 100-message limit or `{ maxMessages }` to set a bound.
206
227
  - `enableExport` adds whole-conversation and per-message export affordances.
207
228
  - Feedback defaults to auto: thumbs, dislike, and comment controls appear when
208
229
  the server reports MLflow feedback is available and a turn produced a trace
@@ -358,6 +379,8 @@ export function ReviewChat(props: ChatViewProps) {
358
379
  sidebar, transcript, tool progress, approval cards, suggestions, export controls,
359
380
  feedback controls, and composer from props. Use it when your app already has a
360
381
  transport or needs to combine Mastra messages with another state model.
382
+ Set `showComposer={false}` when a parent surface owns one shared input, such as a
383
+ side-by-side model comparison.
361
384
 
362
385
  `MastraChat` shows a spinner in the model control while its live default model
363
386
  is being resolved. The picker groups endpoints into
package/index.react.ts CHANGED
@@ -19,6 +19,7 @@ export * as feedbackControls from "./src/react/feedback-controls.tsx";
19
19
  export * as markdown from "./src/react/markdown.tsx";
20
20
  export * as mastraAssistant from "./src/react/mastra-assistant.tsx";
21
21
  export * as mastraChat from "./src/react/mastra-chat.tsx";
22
+ export * as selectedModelPill from "./src/react/selected-model-pill.tsx";
22
23
  export * as suggestionPills from "./src/react/suggestion-pills.tsx";
23
24
  export * as suggestions from "./src/react/suggestions.ts";
24
25
  export * as threadSidebar from "./src/react/thread-sidebar.tsx";
@@ -33,7 +34,7 @@ export type { GenieFeedbackTarget, MessageFeedbackDestination } from "./src/reac
33
34
  export { useChatHistory } from "./src/react/chat-history.ts";
34
35
  export { useChatSessions } from "./src/react/chat-sessions.ts";
35
36
  export type { ThreadSessionReader, ThreadSessionUpdater, ThreadMessageWriter } from "./src/react/chat-sessions.ts";
36
- export { readMlflowTracePart, readThreadTitlePart, chatStatusForChunk, closeOnTerminalChunk, waitForTerminalChunk, useChatStream } from "./src/react/chat-stream.ts";
37
+ export { readMlflowTracePart, readThreadTitlePart, readModelUsagePart, readModelRoutePart, chatStatusForChunk, closeOnTerminalChunk, waitForTerminalChunk, useChatStream } from "./src/react/chat-stream.ts";
37
38
  export { ChatThreadLayout } from "./src/react/chat-thread-layout.tsx";
38
39
  export { TRANSCRIPT_FOLLOW_CANCEL_EVENTS, latestVisibleAssistantIndexInTurn, useChatTranscriptController, ChatTranscript } from "./src/react/chat-transcript.tsx";
39
40
  export type { ChatTranscriptController } from "./src/react/chat-transcript.tsx";
@@ -47,7 +48,9 @@ export { CHAT_LINK_SAFETY, AssistantMarkdown, ToolMarkdown, SqlBlock, SourceBloc
47
48
  export { useMastraAssistant, MastraAssistant } from "./src/react/mastra-assistant.tsx";
48
49
  export type { MastraAssistantMode, MastraAssistantSide, MastraAssistantLauncherPosition, MastraAssistantResizeOptions, MastraAssistantLauncherOptions, MastraAssistantController, MastraAssistantProps } from "./src/react/mastra-assistant.tsx";
49
50
  export { useMastraChat, MastraChat } from "./src/react/mastra-chat.tsx";
50
- export type { ThreadIdChangeReason, UseMastraChatOptions, MastraChatProps } from "./src/react/mastra-chat.tsx";
51
+ export type { ThreadIdChangeReason, BrowserConversationPersistenceOptions, UseMastraChatOptions, UseMastraChatResult, MastraChatProps } from "./src/react/mastra-chat.tsx";
52
+ export { selectedModelActivity, selectedModelRoute, normalizeChatMetrics, selectedModelTurnMetrics, SelectedModelPill } from "./src/react/selected-model-pill.tsx";
53
+ export type { SelectedModelActivity, SelectedModelMessage, SelectedModelTurnMetrics } from "./src/react/selected-model-pill.tsx";
51
54
  export { SuggestionPills } from "./src/react/suggestion-pills.tsx";
52
55
  export type { SuggestionPillsProps } from "./src/react/suggestion-pills.tsx";
53
56
  export { dedupeSuggestions, collectSuggestions } from "./src/react/suggestions.ts";
@@ -58,5 +61,5 @@ export type { ThreadTabsProps, ThreadActionsProps } from "./src/react/thread-tab
58
61
  export { humanizeToolName, formatRawToolPayload, structuredToolPayload, detectToolSourceLanguage, toolInputPresentation, toolOutputPresentation, webSearchProgressGroups, webSearchQueryLabel, webSearchResultLabel, ToolSessionPill } from "./src/react/tool-pill.tsx";
59
62
  export type { ToolInputPresentation, WebSearchProgressGroup } from "./src/react/tool-pill.tsx";
60
63
  export { isActiveChatStatus, isRespondingChatStatus } from "./src/react/types.ts";
61
- export type { ChatStatus, ToolEvent, ToolProgress, ChatModelOption, ChatInputMessage, QueuedSteer, FeedbackValue, FeedbackSubmission, MessageFeedback, ThreadSummary, ThreadPlacement, ChatViewProps, ApprovalDecision, PendingApproval } from "./src/react/types.ts";
64
+ export type { ChatStatus, ChatMetric, ChatMetrics, ToolEvent, ToolProgress, ChatModelOption, ChatInputMessage, QueuedSteer, FeedbackValue, FeedbackSubmission, MessageFeedback, ThreadSummary, ThreadPlacement, ChatViewProps, ApprovalDecision, PendingApproval } from "./src/react/types.ts";
62
65
  export { useChatThreadQuery } from "./src/react/use-chat-thread-query.ts";
package/index.support.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  // Hand edits are overwritten on the next watch; this file is read-only.
4
4
 
5
5
  export * as activeRuns from "./src/support/active-runs.ts";
6
+ export * as browserTranscript from "./src/support/browser-transcript.ts";
6
7
  export * as chartOption from "./src/support/chart-option.ts";
7
8
  export * as chartTheme from "./src/support/chart-theme.ts";
8
9
  export * as download from "./src/support/download.ts";
@@ -18,6 +19,8 @@ export * as threadTabs from "./src/support/thread-tabs.ts";
18
19
  export * as toolEvents from "./src/support/tool-events.ts";
19
20
  export { StoredActiveRunSchema, activeRunStorageKey, readStoredActiveRuns, storeActiveRun, removeStoredActiveRun } from "./src/support/active-runs.ts";
20
21
  export type { StoredActiveRun } from "./src/support/active-runs.ts";
22
+ export { BrowserMessageTimestampsSchema, browserTranscriptStorageKey, readStoredBrowserTranscript, readBrowserMessageTimestamps, withBrowserMessageTimestamps, storeBrowserTranscript } from "./src/support/browser-transcript.ts";
23
+ export type { BrowserMessageTimestamps } from "./src/support/browser-transcript.ts";
21
24
  export { normalizeChartOption } from "./src/support/chart-option.ts";
22
25
  export { LIGHT_CHART_CHROME, resolveChartChrome, useChartChrome } from "./src/support/chart-theme.ts";
23
26
  export type { ChartChrome } from "./src/support/chart-theme.ts";
@@ -32,7 +35,7 @@ export { snapshotRequestContext } from "./src/support/request-context.ts";
32
35
  export type { MastraRequestContextInput, MastraRequestContextSource } from "./src/support/request-context.ts";
33
36
  export { threadTitle, relativeTime } from "./src/support/thread-labels.ts";
34
37
  export { threadStorageKey } from "./src/support/thread-persistence.ts";
35
- export { DEFAULT_THREAD_SESSION_KEY, createThreadSession, isSessionRunning, lastUserMessage, interruptedTurnMessages, enqueueSteer, removeSteer, reorderSteers, sessionKey } from "./src/support/thread-sessions.ts";
36
- export type { SessionQueuedSteer, SessionRun, ThreadSession } from "./src/support/thread-sessions.ts";
38
+ export { DEFAULT_THREAD_SESSION_KEY, createThreadSession, isSessionRunning, lastUserMessage, interruptedTurnMessages, conversationRequestMessages, enqueueSteer, removeSteer, reorderSteers, sessionKey } from "./src/support/thread-sessions.ts";
39
+ export type { SessionQueuedSteer, SessionRun, ConversationHistorySource, ThreadSession } from "./src/support/thread-sessions.ts";
37
40
  export { THREAD_TAB_SEED_MAX, syncThreadTabs, closeThreadTab, nextActiveThreadTab } from "./src/support/thread-tabs.ts";
38
41
  export { compactReasoningText, genieOutputReasoningSections, toolReasoningSections, genieReasoningText, toolEventsFromParts, mergeToolEvents } from "./src/support/tool-events.ts";
package/index.ts CHANGED
@@ -3,4 +3,4 @@
3
3
  // Hand edits are overwritten on the next watch; this file is read-only.
4
4
 
5
5
  export const PACKAGE_IDENTIFIER = "@dbx-tools/ui-mastra";
6
- export const PACKAGE_VERSION = "0.9.190";
6
+ export const PACKAGE_VERSION = "0.9.194";
package/package.json CHANGED
@@ -32,12 +32,13 @@
32
32
  },
33
33
  "dependencies": {
34
34
  "@databricks/appkit-ui": "0.81.0",
35
- "@dbx-tools/shared-auth": "0.9.190",
36
- "@dbx-tools/shared-core": "0.9.190",
37
- "@dbx-tools/shared-genie": "0.9.190",
38
- "@dbx-tools/shared-mastra": "0.9.190",
39
- "@dbx-tools/shared-model": "0.9.190",
40
- "@dbx-tools/ui": "0.9.190",
35
+ "@dbx-tools/shared-auth": "0.9.194",
36
+ "@dbx-tools/shared-core": "0.9.194",
37
+ "@dbx-tools/shared-genie": "0.9.194",
38
+ "@dbx-tools/shared-mastra": "0.9.194",
39
+ "@dbx-tools/shared-model": "0.9.194",
40
+ "@dbx-tools/shared-model-gateway": "0.9.194",
41
+ "@dbx-tools/ui": "0.9.194",
41
42
  "@mastra/client-js": "1.50.0",
42
43
  "@mastra/core": "1.71.0",
43
44
  "@tanstack/react-table": "^8.21.3",
@@ -55,7 +56,7 @@
55
56
  "publishConfig": {
56
57
  "access": "public"
57
58
  },
58
- "version": "0.9.190",
59
+ "version": "0.9.194",
59
60
  "types": "index.ts",
60
61
  "dbxToolsConfig": {
61
62
  "tags": [
@@ -35,10 +35,16 @@ import { MarkdownWithEmbeds } from "./embed-slots.tsx";
35
35
  import { ExportMenu } from "./export-menu.tsx";
36
36
  import { FeedbackControls } from "./feedback-controls.tsx";
37
37
  import { CHAT_LINK_SAFETY, ToolMarkdown } from "./markdown.tsx";
38
+ import {
39
+ SelectedModelPill,
40
+ normalizeChatMetrics,
41
+ type SelectedModelActivity,
42
+ } from "./selected-model-pill.tsx";
38
43
  import { ToolSessionPill, humanizeToolName } from "./tool-pill.tsx";
39
44
  import {
40
45
  isRespondingChatStatus,
41
46
  type ApprovalDecision,
47
+ type ChatMetrics,
42
48
  type ChatStatus,
43
49
  type FeedbackSubmission,
44
50
  type FeedbackValue,
@@ -346,6 +352,14 @@ type AssistantBubbleProps = {
346
352
  feedbackValue?: FeedbackValue;
347
353
  /** MLflow trace link shown only to viewers with `CAN_READ` or higher. */
348
354
  mlflowTraceUrl?: string;
355
+ /** Selected route and usage rendered in the assistant footer. */
356
+ selectedModelActivity?: SelectedModelActivity;
357
+ /** Whether this selected route belongs to the active streaming turn. */
358
+ selectedModelActive?: boolean;
359
+ /** Show the selected model's friendly name in the assistant footer. */
360
+ showSelectedModel?: boolean;
361
+ /** Per-turn metrics pinned to the right side of the assistant footer. */
362
+ metrics?: ChatMetrics;
349
363
  };
350
364
 
351
365
  /** Render one assistant message with tool progress, actions, and optional feedback. */
@@ -364,6 +378,10 @@ export const AssistantBubble = ({
364
378
  feedbackRequest,
365
379
  feedbackValue,
366
380
  mlflowTraceUrl,
381
+ selectedModelActivity,
382
+ selectedModelActive = false,
383
+ showSelectedModel = false,
384
+ metrics,
367
385
  }: AssistantBubbleProps) => {
368
386
  const pendingApprovals = mergePendingApprovals(
369
387
  collectPendingApprovals(message.parts),
@@ -405,7 +423,93 @@ export const AssistantBubble = ({
405
423
  );
406
424
  const hasFooterActions =
407
425
  hasText && (isLast || Boolean(onExport) || Boolean(onFeedback) || Boolean(mlflowTraceUrl));
408
- const showFooter = showResponseStatus || hasFooterActions;
426
+ const showTurnActivity =
427
+ selectedModelActivity !== undefined &&
428
+ (showSelectedModel || normalizeChatMetrics(metrics).length > 0);
429
+ const showFooter = showResponseStatus || hasFooterActions || showTurnActivity;
430
+ const footerActions = (
431
+ <>
432
+ {hasText && isLast && regenerate && (
433
+ <Tooltip>
434
+ <TooltipTrigger asChild>
435
+ <Button
436
+ type="button"
437
+ size="icon"
438
+ variant="ghost"
439
+ className="size-7"
440
+ onClick={() => regenerate()}
441
+ aria-label="Retry response"
442
+ >
443
+ <RefreshCcwIcon className="size-3" />
444
+ </Button>
445
+ </TooltipTrigger>
446
+ <TooltipContent>Retry</TooltipContent>
447
+ </Tooltip>
448
+ )}
449
+ {hasText && isLast && (
450
+ <Tooltip>
451
+ <TooltipTrigger asChild>
452
+ <Button
453
+ type="button"
454
+ size="icon"
455
+ variant="ghost"
456
+ className="size-7"
457
+ onClick={handleCopy}
458
+ aria-label={copied ? "Copied" : "Copy"}
459
+ >
460
+ {copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
461
+ </Button>
462
+ </TooltipTrigger>
463
+ <TooltipContent>{copied ? "Copied" : "Copy"}</TooltipContent>
464
+ </Tooltip>
465
+ )}
466
+ {hasText && onExport && <ExportMenu onExport={onExport} iconOnly tooltip="Export message" />}
467
+ {hasText && onFeedback && (
468
+ <FeedbackControls
469
+ onSubmit={onFeedback}
470
+ {...(feedbackMode ? { mode: feedbackMode } : {})}
471
+ {...(feedbackRequest ? { request: feedbackRequest } : {})}
472
+ {...(feedbackValue ? { value: feedbackValue } : {})}
473
+ />
474
+ )}
475
+ {hasText && mlflowTraceUrl && (
476
+ <Tooltip>
477
+ <TooltipTrigger asChild>
478
+ <Button asChild type="button" size="icon" variant="ghost" className="size-7">
479
+ <a
480
+ href={mlflowTraceUrl}
481
+ target="_blank"
482
+ rel="noreferrer"
483
+ aria-label="Open MLflow trace"
484
+ >
485
+ <BugIcon className="size-3" />
486
+ </a>
487
+ </Button>
488
+ </TooltipTrigger>
489
+ <TooltipContent>Open MLflow trace</TooltipContent>
490
+ </Tooltip>
491
+ )}
492
+ {showResponseStatus && (
493
+ <div className="flex items-center text-muted-foreground">
494
+ <AssistantResponseSpinner />
495
+ </div>
496
+ )}
497
+ </>
498
+ );
499
+ const footer =
500
+ showTurnActivity && selectedModelActivity ? (
501
+ <SelectedModelPill
502
+ activity={selectedModelActivity}
503
+ message={message}
504
+ showModel={showSelectedModel}
505
+ metrics={metrics}
506
+ active={selectedModelActive}
507
+ >
508
+ {footerActions}
509
+ </SelectedModelPill>
510
+ ) : (
511
+ <div className="flex min-h-7 flex-nowrap items-center gap-1">{footerActions}</div>
512
+ );
409
513
  // Charts and tables are placed at inline marker positions in
410
514
  // the assistant's prose. `prepare_chart` / `render_data` mint
411
515
  // a `chartId` and the model embeds `[chart:<chartId>]`; for raw
@@ -438,20 +542,11 @@ export const AssistantBubble = ({
438
542
  ),
439
543
  )}
440
544
  {/*
441
- * Render each text part as its own block. A multi-step turn
442
- * carries one text part per step (see Stream.tsx segmentation),
443
- * so this keeps each step's preamble visually separate instead
444
- * of concatenating them into a single run of prose.
545
+ * AI SDK providers may split one Markdown document across adjacent
546
+ * text parts. Parse their concatenated value once so a boundary in
547
+ * the middle of a fenced code block cannot truncate the rendered code.
445
548
  */}
446
- {textParts.map((part, i) =>
447
- part.text.trim().length > 0 ? (
448
- <MarkdownWithEmbeds
449
- key={`text-${i}`}
450
- text={part.text}
451
- streaming={isStreamingThisBubble}
452
- />
453
- ) : null,
454
- )}
549
+ {hasText && <MarkdownWithEmbeds text={fullText} streaming={isStreamingThisBubble} />}
455
550
  {pendingApprovals.map((p) => (
456
551
  <ToolApprovalCard
457
552
  key={p.toolCallId}
@@ -463,77 +558,7 @@ export const AssistantBubble = ({
463
558
  onResolve={onResolveToolApproval}
464
559
  />
465
560
  ))}
466
- {showFooter && (
467
- <div className="flex min-h-7 flex-nowrap items-center gap-1">
468
- {hasText && isLast && regenerate && (
469
- <Tooltip>
470
- <TooltipTrigger asChild>
471
- <Button
472
- type="button"
473
- size="icon"
474
- variant="ghost"
475
- className="size-7"
476
- onClick={() => regenerate()}
477
- aria-label="Retry response"
478
- >
479
- <RefreshCcwIcon className="size-3" />
480
- </Button>
481
- </TooltipTrigger>
482
- <TooltipContent>Retry</TooltipContent>
483
- </Tooltip>
484
- )}
485
- {hasText && isLast && (
486
- <Tooltip>
487
- <TooltipTrigger asChild>
488
- <Button
489
- type="button"
490
- size="icon"
491
- variant="ghost"
492
- className="size-7"
493
- onClick={handleCopy}
494
- aria-label={copied ? "Copied" : "Copy"}
495
- >
496
- {copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
497
- </Button>
498
- </TooltipTrigger>
499
- <TooltipContent>{copied ? "Copied" : "Copy"}</TooltipContent>
500
- </Tooltip>
501
- )}
502
- {hasText && onExport && (
503
- <ExportMenu onExport={onExport} iconOnly tooltip="Export message" />
504
- )}
505
- {hasText && onFeedback && (
506
- <FeedbackControls
507
- onSubmit={onFeedback}
508
- {...(feedbackMode ? { mode: feedbackMode } : {})}
509
- {...(feedbackRequest ? { request: feedbackRequest } : {})}
510
- {...(feedbackValue ? { value: feedbackValue } : {})}
511
- />
512
- )}
513
- {hasText && mlflowTraceUrl && (
514
- <Tooltip>
515
- <TooltipTrigger asChild>
516
- <Button asChild type="button" size="icon" variant="ghost" className="size-7">
517
- <a
518
- href={mlflowTraceUrl}
519
- target="_blank"
520
- rel="noreferrer"
521
- aria-label="Open MLflow trace"
522
- >
523
- <BugIcon className="size-3" />
524
- </a>
525
- </Button>
526
- </TooltipTrigger>
527
- <TooltipContent>Open MLflow trace</TooltipContent>
528
- </Tooltip>
529
- )}
530
- {showResponseStatus && (
531
- <div className="flex items-center text-muted-foreground">
532
- <AssistantResponseSpinner />
533
- </div>
534
- )}
535
- </div>
536
- )}
561
+ {showFooter ? footer : null}
537
562
  </ItemContent>
538
563
  </Item>
539
564
  );
@@ -2,6 +2,12 @@ import { log, toError, trimToUndefined } from "@dbx-tools/shared-core";
2
2
  import {
3
3
  MLFLOW_TRACE_ID_HEADER,
4
4
  MLFLOW_TRACE_PART_TYPE,
5
+ MODEL_ROUTE_PART_TYPE,
6
+ MODEL_USAGE_PART_TYPE,
7
+ ModelRoutePartDataSchema,
8
+ ModelUsagePartDataSchema,
9
+ type ModelRoutePartData,
10
+ type ModelUsagePartData,
5
11
  MlflowTracePartDataSchema,
6
12
  RESPONSE_COMPLETE_PART_TYPE,
7
13
  THREAD_TITLE_PART_TYPE,
@@ -16,6 +22,7 @@ import type {
16
22
  ThreadSessionUpdater,
17
23
  } from "./chat-sessions.ts";
18
24
  import type { ChatStatus } from "./types.ts";
25
+ import { withBrowserMessageTimestamps } from "../support/browser-transcript.ts";
19
26
  import type { MastraStreamResponse } from "../support/mastra-client.ts";
20
27
 
21
28
  const logger = log.logger("ui-mastra/chat");
@@ -40,6 +47,20 @@ export const readThreadTitlePart = (chunk: UIMessageChunk): string | undefined =
40
47
  return parsed.success ? parsed.data.title : undefined;
41
48
  };
42
49
 
50
+ /** Read the resolved model and latest cumulative usage emitted after a model step. */
51
+ export const readModelUsagePart = (chunk: UIMessageChunk): ModelUsagePartData | undefined => {
52
+ if ((chunk as { type?: string }).type !== MODEL_USAGE_PART_TYPE) return undefined;
53
+ const parsed = ModelUsagePartDataSchema.safeParse((chunk as { data?: unknown }).data);
54
+ return parsed.success ? parsed.data : undefined;
55
+ };
56
+
57
+ /** Read the concrete model route emitted before response generation begins. */
58
+ export const readModelRoutePart = (chunk: UIMessageChunk): ModelRoutePartData | undefined => {
59
+ if ((chunk as { type?: string }).type !== MODEL_ROUTE_PART_TYPE) return undefined;
60
+ const parsed = ModelRoutePartDataSchema.safeParse((chunk as { data?: unknown }).data);
61
+ return parsed.success ? parsed.data : undefined;
62
+ };
63
+
43
64
  /** Map lifecycle-only chunks onto the UI's active-turn state. */
44
65
  export const chatStatusForChunk = (chunk: UIMessageChunk): ChatStatus | undefined => {
45
66
  if (chunk.type === "error") return "error";
@@ -114,12 +135,20 @@ function upsertAssistant(messages: UIMessage[], assistant: UIMessage): UIMessage
114
135
 
115
136
  interface UseChatStreamOptions {
116
137
  getSession: ThreadSessionReader;
138
+ onModelRoute?: (route: ModelRoutePartData) => void;
139
+ onModelUsage?: (usage: ModelUsagePartData) => void;
117
140
  updateSession: ThreadSessionUpdater;
118
141
  writeMessages: ThreadMessageWriter;
119
142
  }
120
143
 
121
144
  /** Project one Mastra stream through the native AI SDK UI message converter. */
122
- export function useChatStream({ getSession, updateSession, writeMessages }: UseChatStreamOptions) {
145
+ export function useChatStream({
146
+ getSession,
147
+ onModelRoute,
148
+ onModelUsage,
149
+ updateSession,
150
+ writeMessages,
151
+ }: UseChatStreamOptions) {
123
152
  return useCallback(
124
153
  async (
125
154
  threadId: string,
@@ -127,6 +156,7 @@ export function useChatStream({ getSession, updateSession, writeMessages }: UseC
127
156
  assistantId: string,
128
157
  runIdRef: { current: string | null },
129
158
  signal: AbortSignal,
159
+ turnStartedAt: string,
130
160
  ) => {
131
161
  const recordTraceId = (traceId: string | undefined): void => {
132
162
  if (!traceId) return;
@@ -162,6 +192,10 @@ export function useChatStream({ getSession, updateSession, writeMessages }: UseC
162
192
  },
163
193
  (chunk) => {
164
194
  recordTraceId(readMlflowTracePart(chunk));
195
+ const modelRoute = readModelRoutePart(chunk);
196
+ if (modelRoute) onModelRoute?.(modelRoute);
197
+ const modelUsage = readModelUsagePart(chunk);
198
+ if (modelUsage) onModelUsage?.(modelUsage);
165
199
  threadTitle = readThreadTitlePart(chunk) ?? threadTitle;
166
200
  const status = chatStatusForChunk(chunk);
167
201
  if (!status) return;
@@ -174,7 +208,13 @@ export function useChatStream({ getSession, updateSession, writeMessages }: UseC
174
208
  terminateOnError: true,
175
209
  })) {
176
210
  if (signal.aborted) throw new StreamAborted();
177
- const assistant = message.id === assistantId ? message : { ...message, id: assistantId };
211
+ const assistant = withBrowserMessageTimestamps(
212
+ message.id === assistantId ? message : { ...message, id: assistantId },
213
+ {
214
+ createdAt: turnStartedAt,
215
+ ...(terminalReceived ? { completedAt: new Date().toISOString() } : {}),
216
+ },
217
+ );
178
218
  writeMessages(threadId, upsertAssistant(getSession(threadId).messages, assistant));
179
219
  updateSession(threadId, (current) => ({
180
220
  ...current,
@@ -182,6 +222,23 @@ export function useChatStream({ getSession, updateSession, writeMessages }: UseC
182
222
  status: terminalReceived || current.status === "finishing" ? "finishing" : "streaming",
183
223
  }));
184
224
  }
225
+ if (terminalReceived) {
226
+ const completedAt = new Date().toISOString();
227
+ const messages = getSession(threadId).messages;
228
+ const assistant = messages.find((message) => message.id === assistantId);
229
+ if (assistant) {
230
+ writeMessages(
231
+ threadId,
232
+ upsertAssistant(
233
+ messages,
234
+ withBrowserMessageTimestamps(assistant, {
235
+ createdAt: turnStartedAt,
236
+ completedAt,
237
+ }),
238
+ ),
239
+ );
240
+ }
241
+ }
185
242
  return threadTitle;
186
243
  } catch (error) {
187
244
  if (error instanceof StreamAborted || signal.aborted) return undefined;
@@ -194,6 +251,6 @@ export function useChatStream({ getSession, updateSession, writeMessages }: UseC
194
251
  throw error;
195
252
  }
196
253
  },
197
- [getSession, updateSession, writeMessages],
254
+ [getSession, onModelRoute, onModelUsage, updateSession, writeMessages],
198
255
  );
199
256
  }
@@ -189,7 +189,7 @@ export const ChatThreadLayout = ({
189
189
  ref={rootRef}
190
190
  data-slot="aui_thread-frame"
191
191
  className={cn(
192
- "flex h-full min-h-0",
192
+ "flex h-full min-h-0 min-w-0",
193
193
  dockedThreads && dockedSide === "right" && "flex-row-reverse",
194
194
  className,
195
195
  )}
@@ -17,6 +17,7 @@ import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from
17
17
  import { flushSync } from "react-dom";
18
18
  import { AssistantBubble, UserBubble } from "./bubbles.tsx";
19
19
  import { messageFeedbackDestination, mlflowTraceUrl } from "./chat-feedback.ts";
20
+ import { selectedModelActivity } from "./selected-model-pill.tsx";
20
21
  import { SuggestionPills } from "./suggestion-pills.tsx";
21
22
  import { isActiveChatStatus, type ChatViewProps, type ToolEvent } from "./types.ts";
22
23
  import { messageText } from "../support/export.ts";
@@ -210,6 +211,8 @@ type ChatTranscriptProps = {
210
211
  error: ChatViewProps["error"];
211
212
  suggestions: NonNullable<ChatViewProps["suggestions"]>;
212
213
  followUpQuestions: string[];
214
+ showSelectedModel: NonNullable<ChatViewProps["showSelectedModel"]>;
215
+ metrics: ChatViewProps["metrics"];
213
216
  onSelectSuggestion: (question: string) => void;
214
217
  toolEventsByMessage: NonNullable<ChatViewProps["toolEventsByMessage"]>;
215
218
  regenerate: ChatViewProps["regenerate"];
@@ -233,6 +236,8 @@ export const ChatTranscript = ({
233
236
  error,
234
237
  suggestions,
235
238
  followUpQuestions,
239
+ showSelectedModel,
240
+ metrics,
236
241
  onSelectSuggestion,
237
242
  toolEventsByMessage,
238
243
  regenerate,
@@ -356,6 +361,10 @@ export const ChatTranscript = ({
356
361
  {messages.map((message, index) => {
357
362
  const isLast = index === activeAssistantIndex;
358
363
  if (message.role === "assistant") {
364
+ const selectedActivity =
365
+ showSelectedModel || metrics !== undefined
366
+ ? selectedModelActivity(message)
367
+ : undefined;
359
368
  const messageFeedback = feedbackByMessage[message.id];
360
369
  const feedbackDestination = messageFeedbackDestination(
361
370
  message,
@@ -384,6 +393,12 @@ export const ChatTranscript = ({
384
393
  regenerate={regenerate}
385
394
  onResolveToolApproval={onResolveToolApproval}
386
395
  externalApprovals={pendingApprovalsByMessage[message.id]}
396
+ selectedModelActivity={selectedActivity}
397
+ selectedModelActive={
398
+ isActiveChatStatus(status) && index === messages.length - 1
399
+ }
400
+ showSelectedModel={showSelectedModel}
401
+ metrics={metrics}
387
402
  {...(onExportMessage
388
403
  ? { onExport: (format) => onExportMessage(message, format) }
389
404
  : {})}
@@ -24,9 +24,12 @@ export const ChatView = ({
24
24
  regenerate,
25
25
  onStop,
26
26
  className,
27
+ showComposer = true,
27
28
  suggestions = [],
28
29
  followUpSuggestions = "none",
29
30
  followUpSuggestionLimit = 3,
31
+ showSelectedModel = false,
32
+ metrics,
30
33
  toolEventsByMessage = {},
31
34
  models,
32
35
  model,
@@ -130,6 +133,8 @@ export const ChatView = ({
130
133
  error={error}
131
134
  suggestions={suggestions}
132
135
  followUpQuestions={followUpQuestions}
136
+ showSelectedModel={showSelectedModel}
137
+ metrics={metrics}
133
138
  onSelectSuggestion={(text) => sendMessage({ text })}
134
139
  toolEventsByMessage={toolEventsByMessage}
135
140
  regenerate={regenerate}
@@ -144,32 +149,34 @@ export const ChatView = ({
144
149
  mlflowExperimentUrl={mlflowExperimentUrl}
145
150
  mlflowTracePrefix={mlflowTracePrefix}
146
151
  />
147
- <ChatComposer
148
- focusRequest={composerFocusRequest}
149
- status={status}
150
- sendMessage={sendMessage}
151
- queuedSteers={queuedSteers}
152
- onSendSteerNow={onSendSteerNow}
153
- onRemoveSteer={onRemoveSteer}
154
- onReorderSteers={onReorderSteers}
155
- onStop={onStop}
156
- models={models}
157
- model={model}
158
- onModelChange={onModelChange}
159
- reasoningEffort={reasoningEffort}
160
- onReasoningEffortChange={onReasoningEffortChange}
161
- defaultModelName={defaultModelName}
162
- defaultModelId={defaultModelId}
163
- defaultModelLoading={defaultModelLoading}
164
- composerActions={composerActions}
165
- modelSelectorActions={modelSelectorActions}
166
- composerLeadingActions={composerLeadingActions}
167
- allowAttachments={allowAttachments}
168
- isLoadingHistory={isLoadingHistory}
169
- onClear={onClear}
170
- onExportConversation={onExportConversation}
171
- onResumeFollow={transcript.resumeFollow}
172
- />
152
+ {showComposer ? (
153
+ <ChatComposer
154
+ focusRequest={composerFocusRequest}
155
+ status={status}
156
+ sendMessage={sendMessage}
157
+ queuedSteers={queuedSteers}
158
+ onSendSteerNow={onSendSteerNow}
159
+ onRemoveSteer={onRemoveSteer}
160
+ onReorderSteers={onReorderSteers}
161
+ onStop={onStop}
162
+ models={models}
163
+ model={model}
164
+ onModelChange={onModelChange}
165
+ reasoningEffort={reasoningEffort}
166
+ onReasoningEffortChange={onReasoningEffortChange}
167
+ defaultModelName={defaultModelName}
168
+ defaultModelId={defaultModelId}
169
+ defaultModelLoading={defaultModelLoading}
170
+ composerActions={composerActions}
171
+ modelSelectorActions={modelSelectorActions}
172
+ composerLeadingActions={composerLeadingActions}
173
+ allowAttachments={allowAttachments}
174
+ isLoadingHistory={isLoadingHistory}
175
+ onClear={onClear}
176
+ onExportConversation={onExportConversation}
177
+ onResumeFollow={transcript.resumeFollow}
178
+ />
179
+ ) : null}
173
180
  </ChatThreadLayout>
174
181
  );
175
182
  };