@dbx-tools/ui-mastra 0.9.214 → 0.11.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.
@@ -8,6 +8,7 @@ import {
8
8
  TooltipTrigger,
9
9
  cn,
10
10
  } from "@databricks/appkit-ui/react";
11
+ import { IconTooltipButton } from "@dbx-tools/ui/react";
11
12
  import { HistoryIcon, Loader2Icon, PlusIcon, XIcon } from "lucide-react";
12
13
  import { type ReactNode, useEffect, useRef, useState } from "react";
13
14
  import { centeredThreadTabScrollLeft } from "./_thread-tab-scroll.ts";
@@ -73,40 +74,19 @@ export const ThreadActions = ({
73
74
  return (
74
75
  <>
75
76
  {onNew && (
76
- <Tooltip>
77
- <TooltipTrigger asChild>
78
- <Button
79
- type="button"
80
- variant="ghost"
81
- size="icon"
82
- onClick={onNew}
83
- aria-label="New chat"
84
- className="size-7 shrink-0"
85
- >
86
- {newIcon ?? <PlusIcon className="size-4" />}
87
- </Button>
88
- </TooltipTrigger>
89
- <TooltipContent>New chat</TooltipContent>
90
- </Tooltip>
77
+ <IconTooltipButton tooltip="New chat" onClick={onNew} className="shrink-0">
78
+ {newIcon ?? <PlusIcon className="size-4" />}
79
+ </IconTooltipButton>
91
80
  )}
92
81
  {historyLeadingActions}
93
82
  <Popover open={historyOpen} onOpenChange={setHistoryOpen} modal>
94
- <Tooltip>
95
- <TooltipTrigger asChild>
96
- <PopoverTrigger asChild>
97
- <Button
98
- type="button"
99
- variant="ghost"
100
- size="icon"
101
- aria-label="Conversation history"
102
- className="size-7 shrink-0"
103
- >
104
- {historyIcon ?? <HistoryIcon className="size-4" />}
105
- </Button>
106
- </PopoverTrigger>
107
- </TooltipTrigger>
108
- <TooltipContent>Conversation history</TooltipContent>
109
- </Tooltip>
83
+ <IconTooltipButton
84
+ tooltip="Conversation history"
85
+ className="shrink-0"
86
+ wrapButton={(button) => <PopoverTrigger asChild>{button}</PopoverTrigger>}
87
+ >
88
+ {historyIcon ?? <HistoryIcon className="size-4" />}
89
+ </IconTooltipButton>
110
90
  <PopoverContent
111
91
  align="end"
112
92
  aria-label="Conversation history"
@@ -5,7 +5,7 @@ import {
5
5
  Spinner,
6
6
  cn,
7
7
  } from "@databricks/appkit-ui/react";
8
- import { parse, toLabel, capitalize } from "@dbx-tools/shared-core";
8
+ import { capitalize, isRecord, parse, toLabel } 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";
@@ -443,12 +443,10 @@ export type ToolInputPresentation = {
443
443
  };
444
444
 
445
445
  const inputRecord = (value: unknown): Record<string, unknown> | undefined =>
446
- typeof value === "object" && value !== null && !Array.isArray(value)
447
- ? (value as Record<string, unknown>)
448
- : undefined;
446
+ isRecord(value) ? value : undefined;
449
447
 
450
448
  /** Detect the most useful syntax grammar for a code-like tool request. */
451
- export function detectToolSourceLanguage(
449
+ function detectToolSourceLanguage(
452
450
  source: string,
453
451
  fallback: ToolInputPresentation["language"],
454
452
  ): ToolInputPresentation["language"] {
@@ -816,6 +814,7 @@ export const ToolSessionPill = ({ events }: { events: ToolEvent[] }) => {
816
814
 
817
815
  return (
818
816
  <div
817
+ data-slot="aui_tool-summary"
819
818
  className={cn(
820
819
  "min-w-0 max-w-full overflow-hidden rounded-md border bg-background/30 px-2 py-1 transition-colors",
821
820
  // Loud-but-not-jarring "in flight" treatment when any row
@@ -190,6 +190,12 @@ export type ChatViewProps = {
190
190
  * questions when the caller doesn't pass an explicit list.
191
191
  */
192
192
  suggestions?: string[];
193
+ /**
194
+ * Empty transcript content rendered above starter suggestions. Omit for the
195
+ * built-in welcome, pass a React node to replace it, or `false` to render no
196
+ * welcome block while retaining suggestions and the composer.
197
+ */
198
+ emptyState?: ReactNode | false;
193
199
  /** Enabled post-turn follow-up sources published by the server. */
194
200
  followUpSuggestions?: FollowUpSuggestionMode;
195
201
  /** Maximum post-turn follow-up questions shown under one response. */
package/src/styles.css CHANGED
@@ -20,3 +20,83 @@
20
20
  @import "@dbx-tools/ui/styles.css";
21
21
 
22
22
  @source "./react";
23
+
24
+ /*
25
+ * Semantic brand typography is opt-in. When a BrandContext omits these
26
+ * variables, every fallback below matches the component's existing Tailwind
27
+ * size and line-height. Attribute selectors deliberately outrank broad host
28
+ * resets such as `button { font: inherit }` without requiring consumers to
29
+ * target internal utility classes.
30
+ */
31
+ [data-slot="aui_thread-frame"] {
32
+ font-family: var(--brand-font-sans, var(--font-sans, sans-serif));
33
+ }
34
+
35
+ [data-slot="aui_thread-content"] {
36
+ gap: var(--brand-section-spacing, 0.75rem);
37
+ }
38
+
39
+ [data-slot="aui_assistant-title"] {
40
+ font-size: var(--brand-font-title-size, 0.875rem);
41
+ line-height: var(--brand-font-title-line-height, 1.25rem);
42
+ font-weight: var(--brand-font-title-weight, 600);
43
+ }
44
+
45
+ [data-slot="aui_assistant-caption"],
46
+ [data-slot="aui_tool-summary"],
47
+ [data-slot="aui_tool-summary"] button,
48
+ [data-slot="aui_tool-markdown"],
49
+ [data-slot="aui_tool-markdown"] :where(p, li, th, td, a) {
50
+ font-size: var(--brand-font-caption-size, 0.75rem);
51
+ line-height: var(--brand-font-caption-line-height, 1rem);
52
+ font-weight: var(--brand-font-caption-weight, 400);
53
+ }
54
+
55
+ [data-slot="aui_assistant-markdown"],
56
+ [data-slot="aui_assistant-markdown"] :where(p, li, th, td, a),
57
+ [data-slot="aui_composer-input"] {
58
+ font-size: var(--brand-font-body-size, 0.875rem);
59
+ line-height: var(--brand-font-body-line-height, 1.25rem);
60
+ font-weight: var(--brand-font-body-weight, 400);
61
+ }
62
+
63
+ [data-slot="aui_assistant-markdown"] h1 {
64
+ font-size: var(--brand-font-title-size, 1.125rem);
65
+ line-height: var(--brand-font-title-line-height, 1.75rem);
66
+ font-weight: var(--brand-font-title-weight, 600);
67
+ }
68
+
69
+ [data-slot="aui_assistant-markdown"] h2 {
70
+ font-size: var(--brand-font-title-size, 1rem);
71
+ line-height: var(--brand-font-title-line-height, 1.5rem);
72
+ font-weight: var(--brand-font-title-weight, 600);
73
+ }
74
+
75
+ [data-slot="aui_assistant-markdown"] h3 {
76
+ font-size: var(--brand-font-title-size, 0.875rem);
77
+ line-height: var(--brand-font-title-line-height, 1.25rem);
78
+ font-weight: var(--brand-font-title-weight, 600);
79
+ }
80
+
81
+ [data-slot="aui_chat-table"] th {
82
+ font-size: var(--brand-font-caption-size, 0.75rem);
83
+ line-height: var(--brand-font-caption-line-height, 1rem);
84
+ font-weight: var(--brand-font-title-weight, 600);
85
+ }
86
+
87
+ [data-slot="aui_chat-table"],
88
+ [data-slot="aui_chat-table"] td {
89
+ font-size: var(--brand-font-caption-size, 0.75rem);
90
+ line-height: var(--brand-font-caption-line-height, 1rem);
91
+ font-weight: var(--brand-font-caption-weight, 400);
92
+ }
93
+
94
+ [data-slot="aui_suggestion-pills"] button {
95
+ min-height: var(--brand-control-height, auto);
96
+ }
97
+
98
+ @media (max-width: 639px) {
99
+ [data-slot="aui_composer-input"] {
100
+ font-size: max(16px, var(--brand-font-body-size, 16px));
101
+ }
102
+ }
@@ -1,9 +1,16 @@
1
+ import {
2
+ browserStorage,
3
+ readStoredItem,
4
+ removeStoredItem,
5
+ writeStoredItem,
6
+ type StorageLike,
7
+ } from "@dbx-tools/ui/react";
1
8
  import type { UIMessage } from "ai";
2
9
  import { z } from "zod";
3
10
 
4
11
  const ACTIVE_RUN_MAX_AGE_MS = 24 * 60 * 60 * 1_000;
5
12
 
6
- export const StoredActiveRunSchema = z
13
+ const StoredActiveRunSchema = z
7
14
  .object({
8
15
  threadId: z.string().min(1).describe("Mastra thread receiving the background turn."),
9
16
  runId: z.string().min(1).describe("Mastra background run identifier."),
@@ -34,8 +41,6 @@ const StoredActiveRunFileSchema = z
34
41
  .strict()
35
42
  .describe("Browser-persisted Mastra background run registry.");
36
43
 
37
- type StorageLike = Pick<Storage, "getItem" | "setItem" | "removeItem">;
38
-
39
44
  /** Build the browser storage key for one Mastra agent's active runs. */
40
45
  export const activeRunStorageKey = (
41
46
  basePath: string,
@@ -46,14 +51,6 @@ export const activeRunStorageKey = (
46
51
  return resourceScope ? `${prefix}:${encodeURIComponent(resourceScope)}` : prefix;
47
52
  };
48
53
 
49
- function browserStorage(): StorageLike | undefined {
50
- try {
51
- return typeof window === "undefined" ? undefined : window.localStorage;
52
- } catch {
53
- return undefined;
54
- }
55
- }
56
-
57
54
  /** Read current non-stale background runs, deleting malformed storage. */
58
55
  export function readStoredActiveRuns(
59
56
  key: string,
@@ -62,7 +59,7 @@ export function readStoredActiveRuns(
62
59
  ): StoredActiveRun[] {
63
60
  if (!storage) return [];
64
61
  try {
65
- const serialized = storage.getItem(key);
62
+ const serialized = readStoredItem(key, storage);
66
63
  if (!serialized) return [];
67
64
  const parsed = StoredActiveRunFileSchema.parse(JSON.parse(serialized));
68
65
  const parsedRuns: StoredActiveRun[] = parsed.runs.map((run) => ({
@@ -73,9 +70,7 @@ export function readStoredActiveRuns(
73
70
  if (runs.length !== parsed.runs.length) writeStoredActiveRuns(key, runs, storage);
74
71
  return runs as StoredActiveRun[];
75
72
  } catch {
76
- try {
77
- storage.removeItem(key);
78
- } catch {}
73
+ removeStoredItem(key, storage);
79
74
  return [];
80
75
  }
81
76
  }
@@ -107,10 +102,10 @@ export function removeStoredActiveRun(
107
102
  function writeStoredActiveRuns(key: string, runs: StoredActiveRun[], storage: StorageLike): void {
108
103
  try {
109
104
  if (runs.length === 0) {
110
- storage.removeItem(key);
105
+ removeStoredItem(key, storage);
111
106
  return;
112
107
  }
113
- storage.setItem(key, JSON.stringify({ version: 1, runs }));
108
+ writeStoredItem(key, JSON.stringify({ version: 1, runs }), storage);
114
109
  } catch {
115
110
  // Browser persistence is best-effort; the live in-memory run remains valid.
116
111
  }
@@ -1,10 +1,18 @@
1
+ import { isRecord } from "@dbx-tools/shared-core";
2
+ import {
3
+ browserStorage,
4
+ readStoredItem,
5
+ removeStoredItem,
6
+ writeStoredItem,
7
+ type StorageLike,
8
+ } from "@dbx-tools/ui/react";
1
9
  import type { UIMessage } from "ai";
2
10
  import { z } from "zod";
3
11
 
4
12
  const DEFAULT_MAX_MESSAGES = 100;
5
13
 
6
14
  /** Client-observed lifecycle timestamps stored with one browser-held message. */
7
- export const BrowserMessageTimestampsSchema = z
15
+ const BrowserMessageTimestampsSchema = z
8
16
  .object({
9
17
  createdAt: z.iso.datetime().describe("ISO-8601 time when the message turn started."),
10
18
  completedAt: z.iso
@@ -43,16 +51,6 @@ const StoredBrowserTranscriptSchema = z
43
51
  .strict()
44
52
  .describe("Browser-persisted Mastra conversation transcript.");
45
53
 
46
- type StorageLike = Pick<Storage, "getItem" | "setItem" | "removeItem">;
47
-
48
- function browserStorage(): StorageLike | undefined {
49
- try {
50
- return typeof window === "undefined" ? undefined : window.localStorage;
51
- } catch {
52
- return undefined;
53
- }
54
- }
55
-
56
54
  /** Build the browser storage key for one resource-scoped Mastra thread. */
57
55
  export function browserTranscriptStorageKey(
58
56
  basePath: string,
@@ -71,14 +69,12 @@ export function readStoredBrowserTranscript(
71
69
  ): UIMessage[] {
72
70
  if (!storage) return [];
73
71
  try {
74
- const serialized = storage.getItem(key);
72
+ const serialized = readStoredItem(key, storage);
75
73
  if (!serialized) return [];
76
74
  const parsed = StoredBrowserTranscriptSchema.parse(JSON.parse(serialized));
77
75
  return parsed.messages as UIMessage[];
78
76
  } catch {
79
- try {
80
- storage.removeItem(key);
81
- } catch {}
77
+ removeStoredItem(key, storage);
82
78
  return [];
83
79
  }
84
80
  }
@@ -96,10 +92,7 @@ export function withBrowserMessageTimestamps(
96
92
  message: UIMessage,
97
93
  timestamps: BrowserMessageTimestamps,
98
94
  ): UIMessage {
99
- const existing =
100
- message.metadata && typeof message.metadata === "object" && !Array.isArray(message.metadata)
101
- ? message.metadata
102
- : {};
95
+ const existing = isRecord(message.metadata) ? message.metadata : {};
103
96
  const current = readBrowserMessageTimestamps(message);
104
97
  const next = BrowserMessageTimestampsSchema.parse({
105
98
  ...existing,
@@ -119,13 +112,13 @@ export function storeBrowserTranscript(
119
112
  if (!storage) return;
120
113
  try {
121
114
  if (messages.length === 0) {
122
- storage.removeItem(key);
115
+ removeStoredItem(key, storage);
123
116
  return;
124
117
  }
125
118
  const limit = Number.isFinite(maxMessages)
126
119
  ? Math.max(1, Math.floor(maxMessages))
127
120
  : DEFAULT_MAX_MESSAGES;
128
- storage.setItem(key, JSON.stringify({ version: 2, messages: messages.slice(-limit) }));
121
+ writeStoredItem(key, JSON.stringify({ version: 2, messages: messages.slice(-limit) }), storage);
129
122
  } catch {
130
123
  // Storage can be blocked or full; the live in-memory transcript remains valid.
131
124
  }
@@ -60,6 +60,16 @@ function hasTitleText(title: unknown): boolean {
60
60
  return entries.some((t) => isObj(t) && typeof t.text === "string" && t.text.trim().length > 0);
61
61
  }
62
62
 
63
+ /** Return the complete visible chart title for accessible labels and tooltips. */
64
+ export function chartTitleText(option: unknown): string | undefined {
65
+ if (!isObj(option)) return undefined;
66
+ const entries = Array.isArray(option.title) ? option.title : [option.title];
67
+ const titles = entries
68
+ .flatMap((title) => (isObj(title) && typeof title.text === "string" ? [title.text.trim()] : []))
69
+ .filter(Boolean);
70
+ return titles.length > 0 ? titles.join(". ") : undefined;
71
+ }
72
+
63
73
  /** True when one axis object carries a visible name. */
64
74
  function hasAxisName(axis: unknown): boolean {
65
75
  const entries = Array.isArray(axis) ? axis : [axis];
@@ -99,11 +109,19 @@ function lineColored(node: unknown, key: string, color: string): Obj {
99
109
  }
100
110
 
101
111
  /** Pin a title to the top-center so it clears the plot / axis names. */
102
- function normalizeTitle(title: unknown, chrome?: ChartChrome): unknown {
103
- if (Array.isArray(title)) return title.map((t) => normalizeTitle(t, chrome));
112
+ function normalizeTitle(title: unknown, typography: Obj, chrome?: ChartChrome): unknown {
113
+ if (Array.isArray(title)) return title.map((t) => normalizeTitle(t, typography, chrome));
104
114
  if (!isObj(title)) return title;
105
115
  const next: Obj = { left: "center", top: 8, ...title };
106
- return chrome ? patched(next, "textStyle", { color: chrome.axisTitle }) : next;
116
+ const existing = isObj(next.textStyle) ? next.textStyle : {};
117
+ next.textStyle = {
118
+ ...typography,
119
+ ...existing,
120
+ width: existing.width ?? 280,
121
+ overflow: existing.overflow ?? "break",
122
+ ...(chrome ? { color: chrome.axisTitle } : {}),
123
+ };
124
+ return next;
107
125
  }
108
126
 
109
127
  /**
@@ -124,7 +142,7 @@ function normalizeGrid(
124
142
  left: 12,
125
143
  right: 24,
126
144
  ...base,
127
- top: base.top ?? (opts.hasTitle ? 64 : 32),
145
+ top: base.top ?? (opts.hasTitle ? 80 : 32),
128
146
  bottom: minimumPixelMargin(base.bottom, bottom),
129
147
  containLabel: base.containLabel ?? true,
130
148
  };
@@ -145,7 +163,7 @@ function categoryLabelWidth(axis: Obj): number {
145
163
  }
146
164
 
147
165
  /** Patch a single axis node in place-safe fashion (`x` or `y`). */
148
- function normalizeAxis(axis: Obj, pos: "x" | "y", chrome?: ChartChrome): Obj {
166
+ function normalizeAxis(axis: Obj, pos: "x" | "y", typography: Obj, chrome?: ChartChrome): Obj {
149
167
  let next: Obj = { ...axis };
150
168
  const existingLabel = isObj(next.axisLabel) ? next.axisLabel : {};
151
169
 
@@ -182,8 +200,8 @@ function normalizeAxis(axis: Obj, pos: "x" | "y", chrome?: ChartChrome): Obj {
182
200
  // Echarts defaults every one of these to a near-black that vanishes
183
201
  // on a dark surface, so all four follow the theme together: the
184
202
  // ticks and their labels, the axis name, and the split lines.
185
- next = patched(next, "axisLabel", { color: chrome.axisLabel });
186
- next = patched(next, "nameTextStyle", { color: chrome.axisTitle });
203
+ next = patched(next, "axisLabel", { ...typography, color: chrome.axisLabel });
204
+ next = patched(next, "nameTextStyle", { ...typography, color: chrome.axisTitle });
187
205
  next = lineColored(next, "axisLine", chrome.grid);
188
206
  next = lineColored(next, "axisTick", chrome.grid);
189
207
  next = lineColored(next, "splitLine", chrome.grid);
@@ -192,9 +210,16 @@ function normalizeAxis(axis: Obj, pos: "x" | "y", chrome?: ChartChrome): Obj {
192
210
  }
193
211
 
194
212
  /** Apply {@link normalizeAxis} across an axis field (object or array). */
195
- function normalizeAxisField(axis: unknown, pos: "x" | "y", chrome?: ChartChrome): unknown {
196
- if (Array.isArray(axis)) return axis.map((a) => (isObj(a) ? normalizeAxis(a, pos, chrome) : a));
197
- return isObj(axis) ? normalizeAxis(axis, pos, chrome) : axis;
213
+ function normalizeAxisField(
214
+ axis: unknown,
215
+ pos: "x" | "y",
216
+ typography: Obj,
217
+ chrome?: ChartChrome,
218
+ ): unknown {
219
+ if (Array.isArray(axis)) {
220
+ return axis.map((a) => (isObj(a) ? normalizeAxis(a, pos, typography, chrome) : a));
221
+ }
222
+ return isObj(axis) ? normalizeAxis(axis, pos, typography, chrome) : axis;
198
223
  }
199
224
 
200
225
  /**
@@ -206,14 +231,14 @@ function normalizeAxisField(axis: unknown, pos: "x" | "y", chrome?: ChartChrome)
206
231
  * theme set - the font is brand identity and the same in either theme;
207
232
  * only the color is theme-dependent, so only the color is replaced.
208
233
  */
209
- function normalizeChrome(option: Obj, chrome: ChartChrome): Obj {
234
+ function normalizeChrome(option: Obj, typography: Obj, chrome: ChartChrome): Obj {
210
235
  const next = patched(option, "textStyle", { color: chrome.axisTitle });
211
236
  // Legend and tooltip are patched only where the spec already declares
212
237
  // them: in Echarts a bare `legend: {}` is a SHOWN legend, so
213
238
  // conjuring one to hold a color would add a legend to a chart that
214
239
  // deliberately has none.
215
240
  if (isObj(next.legend)) {
216
- next.legend = patched(next.legend, "textStyle", { color: chrome.axisLabel });
241
+ next.legend = patched(next.legend, "textStyle", { ...typography, color: chrome.axisLabel });
217
242
  }
218
243
  if (isObj(next.tooltip)) {
219
244
  next.tooltip = {
@@ -247,14 +272,15 @@ function normalizeChrome(option: Obj, chrome: ChartChrome): Obj {
247
272
  export function normalizeChartOption<T>(option: T, chrome?: ChartChrome): T {
248
273
  if (!isObj(option)) return option;
249
274
  let next: Obj = { ...option };
250
- next.title = normalizeTitle(next.title, chrome);
275
+ const typography = isObj(next.textStyle) ? next.textStyle : {};
276
+ next.title = normalizeTitle(next.title, typography, chrome);
251
277
  next.grid = normalizeGrid(next.grid, {
252
278
  hasTitle: hasTitleText(next.title),
253
279
  hasXAxisName: hasAxisName(next.xAxis),
254
280
  hasLegend: hasVisibleLegend(next.legend),
255
281
  });
256
- next.xAxis = normalizeAxisField(next.xAxis, "x", chrome);
257
- next.yAxis = normalizeAxisField(next.yAxis, "y", chrome);
258
- if (chrome) next = normalizeChrome(next, chrome);
282
+ next.xAxis = normalizeAxisField(next.xAxis, "x", typography, chrome);
283
+ next.yAxis = normalizeAxisField(next.yAxis, "y", typography, chrome);
284
+ if (chrome) next = normalizeChrome(next, typography, chrome);
259
285
  return next as T;
260
286
  }
@@ -23,6 +23,7 @@ import {
23
23
  ChartSchema,
24
24
  StatementDataSchema,
25
25
  type GenieVisualizationEmbed,
26
+ agentChatRoutePath,
26
27
  genieVisualizationImagePath,
27
28
  } from "@dbx-tools/shared-mastra";
28
29
  import type { ModelSource, ReasoningEffort, ServingEndpointSummary } from "@dbx-tools/shared-model";
@@ -39,6 +40,9 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
39
40
 
40
41
  type NativeAgentClient = ReturnType<MastraClient["getAgent"]>;
41
42
 
43
+ const clientOrigin = (): string =>
44
+ typeof window !== "undefined" ? window.location.origin : "http://localhost";
45
+
42
46
  /** Browser stream and response headers returned by a Mastra chat request. */
43
47
  export interface MastraStreamResponse {
44
48
  headers: Headers;
@@ -114,7 +118,7 @@ export class MastraPluginClient extends MastraClient {
114
118
 
115
119
  constructor(config: MastraClientConfig) {
116
120
  super({
117
- baseUrl: typeof window !== "undefined" ? window.location.origin : "http://localhost",
121
+ baseUrl: clientOrigin(),
118
122
  apiPrefix: config.basePath,
119
123
  credentials: "include",
120
124
  headers: {},
@@ -163,20 +167,8 @@ export class MastraPluginClient extends MastraClient {
163
167
  routing: { threadId?: string; model?: string; aiDecideStrategy?: AiDecideStrategy };
164
168
  signal?: AbortSignal;
165
169
  }): Promise<MastraStreamResponse> {
166
- let headers = new Headers();
167
- const origin = typeof window !== "undefined" ? window.location.origin : "http://localhost";
168
- const transport = new DefaultChatTransport<UIMessage>({
169
- api: new URL(options.path, origin).toString(),
170
- credentials: "include",
171
- headers: this.#routingHeaders(options.routing),
172
- fetch: async (input, init) => {
173
- const response = await fetch(input, init);
174
- headers = new Headers(response.headers);
175
- await assertChatResponse(response);
176
- return response;
177
- },
178
- });
179
- const stream = await transport.sendMessages({
170
+ const request = this.#chatTransport(options.path, options.routing);
171
+ const stream = await request.transport.sendMessages({
180
172
  trigger: "submit-message",
181
173
  chatId: options.chatId,
182
174
  messageId: undefined,
@@ -184,7 +176,7 @@ export class MastraPluginClient extends MastraClient {
184
176
  abortSignal: options.signal,
185
177
  ...(options.body ? { body: options.body } : {}),
186
178
  });
187
- return { headers, stream };
179
+ return { headers: request.headers(), stream };
188
180
  }
189
181
 
190
182
  async #uiReconnect(options: {
@@ -193,13 +185,32 @@ export class MastraPluginClient extends MastraClient {
193
185
  routing: { threadId?: string; model?: string };
194
186
  signal?: AbortSignal;
195
187
  }): Promise<MastraStreamResponse> {
188
+ const request = this.#chatTransport(options.path, options.routing, true);
189
+ const stream = await request.transport.reconnectToStream({
190
+ chatId: options.chatId,
191
+ abortSignal: options.signal,
192
+ });
193
+ if (!stream) throw new Error(`Run ${options.chatId} is no longer available`);
194
+ return { headers: request.headers(), stream };
195
+ }
196
+
197
+ #absoluteUrl(path: string): string {
198
+ return new URL(path, clientOrigin()).toString();
199
+ }
200
+
201
+ #chatTransport(
202
+ path: string,
203
+ routing: { threadId?: string; model?: string; aiDecideStrategy?: AiDecideStrategy },
204
+ reconnect = false,
205
+ ): { transport: DefaultChatTransport<UIMessage>; headers: () => Headers } {
196
206
  let headers = new Headers();
197
- const origin = typeof window !== "undefined" ? window.location.origin : "http://localhost";
198
207
  const transport = new DefaultChatTransport<UIMessage>({
199
- api: new URL(options.path, origin).toString(),
208
+ api: this.#absoluteUrl(path),
200
209
  credentials: "include",
201
- headers: this.#routingHeaders(options.routing),
202
- prepareReconnectToStreamRequest: ({ api }) => ({ api }),
210
+ headers: this.#routingHeaders(routing),
211
+ ...(reconnect
212
+ ? { prepareReconnectToStreamRequest: ({ api }: { api: string }) => ({ api }) }
213
+ : {}),
203
214
  fetch: async (input, init) => {
204
215
  const response = await fetch(input, init);
205
216
  headers = new Headers(response.headers);
@@ -207,12 +218,7 @@ export class MastraPluginClient extends MastraClient {
207
218
  return response;
208
219
  },
209
220
  });
210
- const stream = await transport.reconnectToStream({
211
- chatId: options.chatId,
212
- abortSignal: options.signal,
213
- });
214
- if (!stream) throw new Error(`Run ${options.chatId} is no longer available`);
215
- return { headers, stream };
221
+ return { transport, headers: () => headers };
216
222
  }
217
223
 
218
224
  #requestClient(
@@ -220,7 +226,7 @@ export class MastraPluginClient extends MastraClient {
220
226
  signal?: AbortSignal,
221
227
  ): MastraClient {
222
228
  return new MastraClient({
223
- baseUrl: typeof window !== "undefined" ? window.location.origin : "http://localhost",
229
+ baseUrl: clientOrigin(),
224
230
  apiPrefix: this.basePath,
225
231
  credentials: "include",
226
232
  headers: this.#routingHeaders(routing),
@@ -252,7 +258,7 @@ export class MastraPluginClient extends MastraClient {
252
258
  signal?: AbortSignal;
253
259
  }): Promise<MastraStreamResponse> {
254
260
  return this.uiStream({
255
- path: `${this.basePath}${MASTRA_ROUTES.chat}/${encodeURIComponent(params.agentId)}`,
261
+ path: `${this.basePath}${agentChatRoutePath(params.agentId)}`,
256
262
  chatId: params.threadId ?? params.runId,
257
263
  messages: params.messages,
258
264
  body: {
@@ -276,7 +282,11 @@ export class MastraPluginClient extends MastraClient {
276
282
  signal?: AbortSignal;
277
283
  }): Promise<MastraStreamResponse> {
278
284
  return this.#uiReconnect({
279
- path: `${this.basePath}${MASTRA_ROUTES.chat}/${encodeURIComponent(params.agentId)}${MASTRA_ROUTES.runs}/${encodeURIComponent(params.runId)}`,
285
+ path: `${this.basePath}${agentChatRoutePath(
286
+ params.agentId,
287
+ MASTRA_ROUTES.runs,
288
+ params.runId,
289
+ )}`,
280
290
  chatId: params.runId,
281
291
  routing: params,
282
292
  signal: params.signal,
@@ -290,12 +300,15 @@ export class MastraPluginClient extends MastraClient {
290
300
  threadId?: string;
291
301
  signal?: AbortSignal;
292
302
  }): Promise<boolean> {
293
- const origin = typeof window !== "undefined" ? window.location.origin : "http://localhost";
294
303
  const response = await this.#mutateJson(
295
- new URL(
296
- `${this.basePath}${MASTRA_ROUTES.chat}/${encodeURIComponent(params.agentId)}${MASTRA_ROUTES.runs}/${encodeURIComponent(params.runId)}${MASTRA_ROUTES.abort}`,
297
- origin,
298
- ).toString(),
304
+ this.#absoluteUrl(
305
+ `${this.basePath}${agentChatRoutePath(
306
+ params.agentId,
307
+ MASTRA_ROUTES.runs,
308
+ params.runId,
309
+ MASTRA_ROUTES.abort,
310
+ )}`,
311
+ ),
299
312
  "POST",
300
313
  MastraRunAbortResponseSchema,
301
314
  {
@@ -353,7 +366,7 @@ export class MastraPluginClient extends MastraClient {
353
366
  },
354
367
  ): Promise<MastraStreamResponse> {
355
368
  return this.uiStream({
356
- path: `${this.basePath}${MASTRA_ROUTES.chat}/${encodeURIComponent(agentId)}`,
369
+ path: `${this.basePath}${agentChatRoutePath(agentId)}`,
357
370
  chatId: params.threadId ?? params.runId,
358
371
  messages: [],
359
372
  body: {