@dbx-tools/ui-mastra 0.9.181 → 0.9.184

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.
@@ -0,0 +1,299 @@
1
+ import { useLayoutEffect, type RefObject } from "react";
2
+ import { ScrollBooster } from "scrollbooster";
3
+
4
+ const COMPOSER_DOCK_SELECTOR = '[data-slot="aui_composer-dock"]';
5
+ const COMPOSER_INPUT_SELECTOR = ".aui-composer-input";
6
+ const TRANSCRIPT_SELECTOR = '[data-slot="aui_thread-viewport"]';
7
+ const TRANSCRIPT_CONTENT_SELECTOR = '[data-slot="aui_thread-content"]';
8
+ const TRANSCRIPT_INDICATOR_SELECTOR = '[data-slot="aui_thread-scroll-indicator"]';
9
+
10
+ const SCROLL_BOUNDARY_EPSILON_PX = 1;
11
+ const KEYBOARD_GEOMETRY_THRESHOLD_PX = 80;
12
+ const FOCUS_GUARD_FALLBACK_MS = 600;
13
+ const FOCUS_GUARD_SETTLE_MS = 120;
14
+ const MIN_SCROLL_INDICATOR_HEIGHT_PX = 28;
15
+
16
+ /** Internal event used by the scroll-to-bottom control to cancel iOS drag momentum first. */
17
+ export const CANCEL_TRANSCRIPT_KINETIC_SCROLL_EVENT = "dbx-tools:cancel-transcript-kinetic-scroll";
18
+
19
+ const isIOSWebKit = () => {
20
+ const userAgent = window.navigator.userAgent;
21
+ return (
22
+ /iPad|iPhone|iPod/.test(userAgent) ||
23
+ (userAgent.includes("Macintosh") && window.navigator.maxTouchPoints > 1)
24
+ );
25
+ };
26
+
27
+ const isKeyboardVisible = (viewport: VisualViewport | null): boolean =>
28
+ Boolean(viewport && window.innerHeight - viewport.height > KEYBOARD_GEOMETRY_THRESHOLD_PX);
29
+
30
+ const composerInputFromEvent = (event: Event): HTMLTextAreaElement | null => {
31
+ const target = event.target instanceof Element ? event.target : null;
32
+ return target?.closest<HTMLTextAreaElement>(COMPOSER_INPUT_SELECTOR) ?? null;
33
+ };
34
+
35
+ const createTranscriptScroller = (viewport: HTMLElement, content: HTMLElement) =>
36
+ new ScrollBooster({
37
+ viewport,
38
+ content,
39
+ direction: "vertical",
40
+ pointerMode: "mouse",
41
+ scrollMode: "native",
42
+ bounce: false,
43
+ textSelection: true,
44
+ wheel: false,
45
+ keyboard: false,
46
+ });
47
+
48
+ const syncScrollIndicator = (
49
+ transcript: HTMLElement,
50
+ indicator: HTMLElement | null,
51
+ visible: boolean,
52
+ ) => {
53
+ if (!indicator) return;
54
+
55
+ const maxScrollTop = transcript.scrollHeight - transcript.clientHeight;
56
+ indicator.hidden = !visible || maxScrollTop <= 0;
57
+ if (indicator.hidden) return;
58
+
59
+ // Safari paints native overlay scrollbars against stale pre-keyboard geometry. This thumb is
60
+ // positioned inside the resized transcript so it always matches the visible scroll region.
61
+ const proportionalHeight =
62
+ (transcript.clientHeight / transcript.scrollHeight) * transcript.clientHeight;
63
+ const height = Math.min(
64
+ transcript.clientHeight,
65
+ Math.max(MIN_SCROLL_INDICATOR_HEIGHT_PX, Math.round(proportionalHeight)),
66
+ );
67
+ const scrollTop = Math.min(maxScrollTop, Math.max(0, transcript.scrollTop));
68
+ const top = Math.round((scrollTop / maxScrollTop) * (transcript.clientHeight - height));
69
+ indicator.style.height = `${height}px`;
70
+ indicator.style.transform = `translateY(${top}px)`;
71
+ };
72
+
73
+ /**
74
+ * Contains Mobile Safari keyboard and touch behavior inside the chat frame.
75
+ *
76
+ * When the host shell follows `visualViewport`, this hook owns the remaining iOS-specific work:
77
+ * suppressing Safari's input-reveal pan, routing keyboard-open transcript drags through
78
+ * ScrollBooster, stopping existing momentum before composer actions, and drawing the keyboard-safe
79
+ * scrollbar thumb.
80
+ */
81
+ export const useComposerViewportLock = (frameRef: RefObject<HTMLElement | null>) => {
82
+ useLayoutEffect(() => {
83
+ const frame = frameRef.current;
84
+ const dock = frame?.querySelector<HTMLElement>(COMPOSER_DOCK_SELECTOR);
85
+ const transcript = frame?.querySelector<HTMLElement>(TRANSCRIPT_SELECTOR);
86
+ const transcriptContent = frame?.querySelector<HTMLElement>(TRANSCRIPT_CONTENT_SELECTOR);
87
+ const scrollIndicator =
88
+ frame?.querySelector<HTMLElement>(TRANSCRIPT_INDICATOR_SELECTOR) ?? null;
89
+ if (!frame || !dock || !transcript || !transcriptContent) return;
90
+
91
+ const iosWebKit = isIOSWebKit();
92
+ let transcriptScroller = iosWebKit
93
+ ? createTranscriptScroller(transcript, transcriptContent)
94
+ : null;
95
+ let transcriptScrollerRestartFrame: number | null = null;
96
+ let transcriptTouchRoutingEnabled = false;
97
+ let momentumRestoreFrame: number | null = null;
98
+ let momentumScrollTop = 0;
99
+ let momentumOverflowY: string | null = null;
100
+ let lastTouchY: number | null = null;
101
+ let focusRevealTimer: number | null = null;
102
+ let guardedInput: HTMLTextAreaElement | null = null;
103
+ let guardedOpacity = "";
104
+ let guardViewportHeight = 0;
105
+ let guardViewportTop = 0;
106
+
107
+ const syncIndicator = () =>
108
+ syncScrollIndicator(transcript, scrollIndicator, transcriptTouchRoutingEnabled);
109
+
110
+ const syncKeyboardState = () => {
111
+ const keyboardVisible = iosWebKit && isKeyboardVisible(window.visualViewport);
112
+ transcript.toggleAttribute("data-keyboard-touch-scroller", keyboardVisible);
113
+
114
+ if (keyboardVisible !== transcriptTouchRoutingEnabled) {
115
+ transcriptTouchRoutingEnabled = keyboardVisible;
116
+ transcriptScroller?.updateOptions({ pointerMode: keyboardVisible ? "touch" : "mouse" });
117
+ }
118
+ syncIndicator();
119
+ };
120
+
121
+ const revealGuardedInput = () => {
122
+ if (!guardedInput) return;
123
+ guardedInput.style.opacity = guardedOpacity;
124
+ delete guardedInput.dataset.iosFocusGuard;
125
+ guardedInput = null;
126
+ focusRevealTimer = null;
127
+ guardViewportHeight = 0;
128
+ guardViewportTop = 0;
129
+ };
130
+
131
+ const scheduleGuardReveal = (delay: number) => {
132
+ if (focusRevealTimer !== null) window.clearTimeout(focusRevealTimer);
133
+ focusRevealTimer = window.setTimeout(revealGuardedInput, delay);
134
+ };
135
+
136
+ const guardInput = (input: HTMLTextAreaElement) => {
137
+ if (guardedInput === input) return;
138
+ if (focusRevealTimer !== null) window.clearTimeout(focusRevealTimer);
139
+ revealGuardedInput();
140
+ guardedInput = input;
141
+ guardedOpacity = input.style.opacity;
142
+ guardViewportHeight = window.visualViewport?.height ?? window.innerHeight;
143
+ guardViewportTop = window.visualViewport?.offsetTop ?? 0;
144
+ input.dataset.iosFocusGuard = "true";
145
+ input.style.opacity = "0";
146
+ };
147
+
148
+ const stopNativeTranscriptMomentum = () => {
149
+ if (!iosWebKit) return;
150
+
151
+ transcriptScroller?.setPosition({ y: transcript.scrollTop });
152
+ momentumScrollTop = transcript.scrollTop;
153
+ if (momentumOverflowY === null) momentumOverflowY = transcript.style.overflowY;
154
+ if (momentumRestoreFrame !== null) window.cancelAnimationFrame(momentumRestoreFrame);
155
+
156
+ // WebKit carries an existing inertial transcript gesture through keyboard focus. Removing
157
+ // overflow for one frame ends that gesture while preserving the reader's exact position.
158
+ transcript.style.overflowY = "hidden";
159
+ transcript.scrollTop = momentumScrollTop;
160
+ momentumRestoreFrame = window.requestAnimationFrame(() => {
161
+ transcript.style.overflowY = momentumOverflowY ?? "";
162
+ transcript.scrollTop = momentumScrollTop;
163
+ momentumOverflowY = null;
164
+ momentumRestoreFrame = null;
165
+ });
166
+ };
167
+
168
+ const restartTranscriptScroller = () => {
169
+ if (!iosWebKit) return;
170
+ transcriptScroller?.destroy();
171
+ transcriptScroller = null;
172
+ if (transcriptScrollerRestartFrame !== null) {
173
+ window.cancelAnimationFrame(transcriptScrollerRestartFrame);
174
+ }
175
+
176
+ // Reattach after the current touch sequence and its next paint have completed. Recreating the
177
+ // instance during the same dispatch allows ScrollBooster's old kinetic loop to keep running.
178
+ transcriptScrollerRestartFrame = window.requestAnimationFrame(() => {
179
+ transcriptScrollerRestartFrame = window.requestAnimationFrame(() => {
180
+ transcriptScroller = createTranscriptScroller(transcript, transcriptContent);
181
+ transcriptScroller.updateOptions({
182
+ pointerMode: transcriptTouchRoutingEnabled ? "touch" : "mouse",
183
+ });
184
+ transcriptScrollerRestartFrame = null;
185
+ });
186
+ });
187
+ };
188
+
189
+ const handleInputFocus = (event: FocusEvent) => {
190
+ if (!iosWebKit) return;
191
+ const input = event.target instanceof HTMLTextAreaElement ? event.target : null;
192
+ if (!input?.matches(COMPOSER_INPUT_SELECTOR)) return;
193
+ guardInput(input);
194
+ scheduleGuardReveal(FOCUS_GUARD_FALLBACK_MS);
195
+ };
196
+
197
+ const handleInputBlur = (event: FocusEvent) => {
198
+ if (event.target === guardedInput) revealGuardedInput();
199
+ };
200
+
201
+ const handleVisualViewportChange = () => {
202
+ syncKeyboardState();
203
+ const viewport = window.visualViewport;
204
+ if (!guardedInput || !viewport) return;
205
+ const heightChanged = guardViewportHeight - viewport.height > KEYBOARD_GEOMETRY_THRESHOLD_PX;
206
+ const topChanged =
207
+ Math.abs(viewport.offsetTop - guardViewportTop) > KEYBOARD_GEOMETRY_THRESHOLD_PX;
208
+ if (!heightChanged && !topChanged) return;
209
+
210
+ // Restore only after WebKit has started the keyboard transition and the host shell has
211
+ // resized. Restoring earlier makes the visible textarea eligible for another reveal pan.
212
+ scheduleGuardReveal(FOCUS_GUARD_SETTLE_MS);
213
+ };
214
+
215
+ const handleTouchStart = (event: TouchEvent) => {
216
+ const input = composerInputFromEvent(event);
217
+ if (input && iosWebKit) {
218
+ // This must run before the native focus default action. Focus events can arrive after Safari
219
+ // has already selected and centered its reveal target.
220
+ guardInput(input);
221
+ scheduleGuardReveal(FOCUS_GUARD_FALLBACK_MS);
222
+ }
223
+ lastTouchY = event.touches[0]?.clientY ?? null;
224
+ stopNativeTranscriptMomentum();
225
+ };
226
+
227
+ const handleTouchMove = (event: TouchEvent) => {
228
+ const touchY = event.touches[0]?.clientY;
229
+ if (touchY === undefined) return;
230
+
231
+ const input = composerInputFromEvent(event);
232
+ const deltaY = lastTouchY === null ? 0 : touchY - lastTouchY;
233
+ lastTouchY = touchY;
234
+
235
+ if (input && input.scrollHeight > input.clientHeight + SCROLL_BOUNDARY_EPSILON_PX) {
236
+ const canScrollTowardStart = deltaY > 0 && input.scrollTop > SCROLL_BOUNDARY_EPSILON_PX;
237
+ const canScrollTowardEnd =
238
+ deltaY < 0 &&
239
+ input.scrollTop + input.clientHeight < input.scrollHeight - SCROLL_BOUNDARY_EPSILON_PX;
240
+ if (canScrollTowardStart || canScrollTowardEnd) return;
241
+ }
242
+
243
+ // Composer drags must not select the document or visual viewport as the gesture scroller.
244
+ if (event.cancelable) event.preventDefault();
245
+ };
246
+
247
+ const handleTouchEnd = () => {
248
+ lastTouchY = null;
249
+ };
250
+
251
+ const resizeObserver =
252
+ iosWebKit && scrollIndicator && typeof ResizeObserver !== "undefined"
253
+ ? new ResizeObserver(syncIndicator)
254
+ : null;
255
+ resizeObserver?.observe(transcript);
256
+ resizeObserver?.observe(transcriptContent);
257
+
258
+ dock.addEventListener("touchstart", handleTouchStart, { passive: true });
259
+ dock.addEventListener("touchmove", handleTouchMove, { passive: false });
260
+ dock.addEventListener("touchend", handleTouchEnd, { passive: true });
261
+ dock.addEventListener("touchcancel", handleTouchEnd, { passive: true });
262
+ dock.addEventListener("focus", handleInputFocus, true);
263
+ dock.addEventListener("blur", handleInputBlur, true);
264
+ transcript.addEventListener("scroll", syncIndicator, { passive: true });
265
+ transcript.addEventListener(CANCEL_TRANSCRIPT_KINETIC_SCROLL_EVENT, restartTranscriptScroller);
266
+ window.visualViewport?.addEventListener("resize", handleVisualViewportChange);
267
+ window.visualViewport?.addEventListener("scroll", handleVisualViewportChange);
268
+ window.visualViewport?.addEventListener("scrollend", handleVisualViewportChange);
269
+ syncKeyboardState();
270
+
271
+ return () => {
272
+ if (momentumRestoreFrame !== null) window.cancelAnimationFrame(momentumRestoreFrame);
273
+ if (focusRevealTimer !== null) window.clearTimeout(focusRevealTimer);
274
+ if (transcriptScrollerRestartFrame !== null) {
275
+ window.cancelAnimationFrame(transcriptScrollerRestartFrame);
276
+ }
277
+ revealGuardedInput();
278
+ transcriptScroller?.destroy();
279
+ resizeObserver?.disconnect();
280
+ transcript.removeAttribute("data-keyboard-touch-scroller");
281
+ if (scrollIndicator) scrollIndicator.hidden = true;
282
+ if (momentumOverflowY !== null) transcript.style.overflowY = momentumOverflowY;
283
+ dock.removeEventListener("touchstart", handleTouchStart);
284
+ dock.removeEventListener("touchmove", handleTouchMove);
285
+ dock.removeEventListener("touchend", handleTouchEnd);
286
+ dock.removeEventListener("touchcancel", handleTouchEnd);
287
+ dock.removeEventListener("focus", handleInputFocus, true);
288
+ dock.removeEventListener("blur", handleInputBlur, true);
289
+ transcript.removeEventListener("scroll", syncIndicator);
290
+ transcript.removeEventListener(
291
+ CANCEL_TRANSCRIPT_KINETIC_SCROLL_EVENT,
292
+ restartTranscriptScroller,
293
+ );
294
+ window.visualViewport?.removeEventListener("resize", handleVisualViewportChange);
295
+ window.visualViewport?.removeEventListener("scroll", handleVisualViewportChange);
296
+ window.visualViewport?.removeEventListener("scrollend", handleVisualViewportChange);
297
+ };
298
+ }, [frameRef]);
299
+ };
package/src/styles.css CHANGED
@@ -20,3 +20,15 @@
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
+ /* The adjacent custom thumb uses the transcript's keyboard-resized geometry. */
26
+ scrollbar-gutter: auto;
27
+ scrollbar-width: none;
28
+ }
29
+
30
+ [data-slot="aui_thread-viewport"][data-keyboard-touch-scroller]::-webkit-scrollbar {
31
+ display: none;
32
+ width: 0;
33
+ height: 0;
34
+ }
@@ -724,14 +724,16 @@ export const useMastraClient = (): MastraPluginClient => {
724
724
  */
725
725
  export const useMastraMlflowExperiment = (
726
726
  enabled = true,
727
- ): { url: string | null; loading: boolean } => {
727
+ ): { url: string | null; tracePrefix: string | null; loading: boolean } => {
728
728
  const client = useMastraClient();
729
729
  const [url, setUrl] = useState<string | null>(null);
730
+ const [tracePrefix, setTracePrefix] = useState<string | null>(null);
730
731
  const [loading, setLoading] = useState(enabled);
731
732
 
732
733
  useEffect(() => {
733
734
  if (!enabled) {
734
735
  setUrl(null);
736
+ setTracePrefix(null);
735
737
  setLoading(false);
736
738
  return;
737
739
  }
@@ -740,10 +742,16 @@ export const useMastraMlflowExperiment = (
740
742
  client
741
743
  .mlflowExperiment(controller.signal)
742
744
  .then((result) => {
743
- if (!controller.signal.aborted) setUrl(result.url);
745
+ if (!controller.signal.aborted) {
746
+ setUrl(result.url);
747
+ setTracePrefix(result.tracePrefix);
748
+ }
744
749
  })
745
750
  .catch(() => {
746
- if (!controller.signal.aborted) setUrl(null);
751
+ if (!controller.signal.aborted) {
752
+ setUrl(null);
753
+ setTracePrefix(null);
754
+ }
747
755
  })
748
756
  .finally(() => {
749
757
  if (!controller.signal.aborted) setLoading(false);
@@ -751,7 +759,7 @@ export const useMastraMlflowExperiment = (
751
759
  return () => controller.abort();
752
760
  }, [client, enabled]);
753
761
 
754
- return { url, loading };
762
+ return { url, tracePrefix, loading };
755
763
  };
756
764
 
757
765
  /**
@@ -979,10 +987,9 @@ export const useMastraThreads = (
979
987
  }
980
988
  const controller = new AbortController();
981
989
  if (!hasLoadedRef.current) setLoading(true);
982
- void load(controller.signal)
983
- .finally(() => {
984
- if (!controller.signal.aborted) setLoading(false);
985
- });
990
+ void load(controller.signal).finally(() => {
991
+ if (!controller.signal.aborted) setLoading(false);
992
+ });
986
993
  return () => controller.abort();
987
994
  }, [enabled, load, nonce]);
988
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