@djangocfg/ui-tools 2.1.368 → 2.1.369

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@djangocfg/ui-tools",
3
- "version": "2.1.368",
3
+ "version": "2.1.369",
4
4
  "description": "Heavy React tools with lazy loading - for Electron, Vite, CRA, Next.js apps",
5
5
  "keywords": [
6
6
  "ui-tools",
@@ -156,8 +156,8 @@
156
156
  "check": "tsc --noEmit"
157
157
  },
158
158
  "peerDependencies": {
159
- "@djangocfg/i18n": "^2.1.368",
160
- "@djangocfg/ui-core": "^2.1.368",
159
+ "@djangocfg/i18n": "^2.1.369",
160
+ "@djangocfg/ui-core": "^2.1.369",
161
161
  "consola": "^3.4.2",
162
162
  "lodash-es": "^4.18.1",
163
163
  "lucide-react": "^0.545.0",
@@ -193,6 +193,7 @@
193
193
  "react-lottie-player": "^2.1.0",
194
194
  "react-map-gl": "^8.1.0",
195
195
  "react-markdown": "10.1.0",
196
+ "react-virtuoso": "^4.18.7",
196
197
  "react-zoom-pan-pinch": "^3.7.0",
197
198
  "rehype-external-links": "^3.0.0",
198
199
  "rehype-raw": "^7.0.0",
@@ -210,10 +211,10 @@
210
211
  "material-file-icons": "^2.4.0"
211
212
  },
212
213
  "devDependencies": {
213
- "@djangocfg/i18n": "^2.1.368",
214
+ "@djangocfg/i18n": "^2.1.369",
214
215
  "@djangocfg/playground": "workspace:*",
215
- "@djangocfg/typescript-config": "^2.1.368",
216
- "@djangocfg/ui-core": "^2.1.368",
216
+ "@djangocfg/typescript-config": "^2.1.369",
217
+ "@djangocfg/ui-core": "^2.1.369",
217
218
  "@types/lodash-es": "^4.17.12",
218
219
  "@types/mapbox__mapbox-gl-draw": "^1.4.8",
219
220
  "@types/node": "^24.7.2",
@@ -513,7 +513,28 @@ LazyChat
513
513
  - **Token coalescing.** `createTokenBuffer` aggregates stream chunks within ~16ms before dispatching → ≤1 render per frame.
514
514
  - **Plain text during stream.** `MessageBubble` skips ReactMarkdown until the message finishes, then re-renders once with full markdown.
515
515
  - **Memoized bubbles.** Memo key `(id, content, isStreaming, version, toolActivity, toolCalls, sources, attachments)` — references only.
516
- - **Virtualization is opt-in.** `@tanstack/react-virtual` stays a host-side decision via `MessageList renderItem` slot.
516
+ - **Virtualization is on by default.** As of plan64, `<MessageList>` is built on [`react-virtuoso`](https://virtuoso.dev/). Sticky-bottom + auto-follow on streaming come from `followOutput`, top-of-list pagination from `startReached`, scroll-anchor preservation on prepend from `firstItemIndex`. No host-side virtualizer needed. Set `noVirtualize` on `<MessageList>` to opt out (stories / DevTools tracing).
517
+
518
+ ### Scroll API
519
+
520
+ `<MessageList>` exposes an imperative handle:
521
+
522
+ ```tsx
523
+ const listRef = useRef<MessageListHandle>(null);
524
+
525
+ <MessageList
526
+ ref={listRef}
527
+ onAtBottomChange={setIsAtBottom} // drives "Jump to latest" pill
528
+ onStartReached={() => void loadMore()} // top-of-list pagination
529
+ />;
530
+
531
+ listRef.current?.scrollToBottom(true); // smooth jump
532
+ listRef.current?.scrollToIndex(42); // jump to a specific bubble
533
+ ```
534
+
535
+ The legacy `useChatScroll` hook is kept for hosts that render their
536
+ own (non-virtualized) scroll container, but is `@deprecated` for use
537
+ with `<MessageList>` — the component owns sticky-bottom internally.
517
538
 
518
539
  ## Design docs
519
540
 
@@ -1,6 +1,6 @@
1
1
  'use client';
2
2
 
3
- import { type ReactNode, useRef } from 'react';
3
+ import { type ReactNode, useRef, useState } from 'react';
4
4
 
5
5
  import { cn } from '@djangocfg/ui-core/lib';
6
6
 
@@ -8,14 +8,12 @@ import type { ChatAttachment, ChatConfig, ChatMessage, ChatTransport } from '../
8
8
  import type { ChatAudioConfig } from '../core/audio/types';
9
9
  import { ChatProvider, useChatContext, type ChatContextValue } from '../context';
10
10
  import { useChatComposer, type UseChatComposerReturn } from '../hooks/useChatComposer';
11
- import { useChatScroll } from '../hooks/useChatScroll';
12
- import { useChatHistory } from '../hooks/useChatHistory';
13
11
  import { Composer, type ComposerSize } from './Composer';
14
12
  import { EmptyState } from './EmptyState';
15
13
  import { ErrorBanner } from './ErrorBanner';
16
14
  import { JumpToLatest } from './JumpToLatest';
17
15
  import { MessageBubble } from './MessageBubble';
18
- import { MessageList } from './MessageList';
16
+ import { MessageList, type MessageListHandle } from './MessageList';
19
17
  import type { AttachmentRendererMap } from './Attachments';
20
18
  import type { ToolCallsProps } from './ToolCalls';
21
19
 
@@ -115,24 +113,14 @@ function ChatRootShell({ className, listClassName, slots }: ChatRootShellProps)
115
113
  onSubmit: (content, attachments) => chat.sendMessage(content, attachments),
116
114
  disabled: chat.isStreaming,
117
115
  });
118
- const containerRef = useRef<HTMLDivElement | null>(null);
119
- const bottomRef = useRef<HTMLDivElement | null>(null);
120
- const topRef = useRef<HTMLDivElement | null>(null);
121
-
122
- const scroll = useChatScroll({
123
- containerRef,
124
- bottomRef,
125
- isStreaming: chat.isStreaming,
126
- messagesCount: chat.messages.length,
127
- });
128
-
129
- useChatHistory({
130
- containerRef,
131
- topSentinelRef: topRef,
132
- hasMore: chat.hasMore,
133
- isLoadingMore: chat.isLoadingMore,
134
- loadMore: chat.loadMore,
135
- });
116
+ // MessageList (virtuoso) owns the scroll viewport. We talk to it
117
+ // via the imperative handle (scrollToBottom on JumpToLatest click)
118
+ // and via the `onAtBottomChange` callback (drives the pill).
119
+ const listRef = useRef<MessageListHandle | null>(null);
120
+ const [isAtBottom, setIsAtBottom] = useState(true);
121
+ const handleStartReached = chat.hasMore && !chat.isLoadingMore
122
+ ? () => void chat.loadMore()
123
+ : undefined;
136
124
 
137
125
  const greeting = chat.config.greeting ?? 'How can I help?';
138
126
  const description = chat.config.description;
@@ -180,19 +168,18 @@ function ChatRootShell({ className, listClassName, slots }: ChatRootShellProps)
180
168
  onRetry={chat.error ? () => void chat.regenerate() : undefined}
181
169
  />
182
170
  <MessageList
183
- ref={containerRef}
184
- topSentinelRef={topRef}
185
- bottomRef={bottomRef}
171
+ ref={listRef}
186
172
  renderItem={renderItem}
187
173
  renderEmpty={() => <>{emptyNode}</>}
188
174
  className={listClassName}
175
+ onStartReached={handleStartReached}
176
+ onAtBottomChange={setIsAtBottom}
189
177
  />
190
178
  <div className="pointer-events-none absolute inset-x-0 bottom-2 flex justify-center">
191
179
  {slots.jumpToLatest ?? (
192
180
  <JumpToLatest
193
- visible={!scroll.isAtBottom}
194
- unreadCount={scroll.unreadCount}
195
- onClick={() => scroll.scrollToBottom(true)}
181
+ visible={!isAtBottom}
182
+ onClick={() => listRef.current?.scrollToBottom(true)}
196
183
  />
197
184
  )}
198
185
  </div>
@@ -57,6 +57,27 @@ export interface MessageBubbleProps {
57
57
  onRegenerate?: () => void;
58
58
  onEdit?: () => void;
59
59
  onDelete?: () => void;
60
+ /**
61
+ * Extra content rendered alongside the default copy/regenerate/edit/
62
+ * delete actions (after them, on the same row). Hosts pass app-
63
+ * specific affordances here — e.g. "Send to plan", "Add note",
64
+ * "Open in inspector" — without having to fork `<MessageActions>`.
65
+ * Receives the message so renderers can branch by id / role / etc.
66
+ * Plan64.
67
+ */
68
+ messageActionsExtra?: (m: ChatMessage) => ReactNode;
69
+ /**
70
+ * Override the default streaming indicator (the dots / pulse + tool
71
+ * activity label). Receives the message so the host can read
72
+ * `toolActivity`, the running tool call name, etc., and render a
73
+ * richer affordance ("Running cmd_execute on vps-audi…"). Plan64.
74
+ *
75
+ * Renders in two slots: as the in-bubble pre-token affordance, and
76
+ * as the inline label above the bubble when `toolActivity` is set.
77
+ * The render-prop is called for both — branch on `m.content` if
78
+ * you need different behaviour per slot.
79
+ */
80
+ streamingIndicator?: (m: ChatMessage) => ReactNode;
60
81
  }
61
82
 
62
83
  const MessageBubbleInner = ({
@@ -83,6 +104,8 @@ const MessageBubbleInner = ({
83
104
  onRegenerate,
84
105
  onEdit,
85
106
  onDelete,
107
+ messageActionsExtra,
108
+ streamingIndicator,
86
109
  }: MessageBubbleProps) => {
87
110
  const isUser = isUserProp ?? message.role === 'user';
88
111
  const isStreaming = !!message.isStreaming;
@@ -160,7 +183,9 @@ const MessageBubbleInner = ({
160
183
  >
161
184
  {isStreaming && message.toolActivity ? (
162
185
  <div className="mb-1.5">
163
- <StreamingIndicator label={message.toolActivity} />
186
+ {streamingIndicator
187
+ ? streamingIndicator(message)
188
+ : <StreamingIndicator label={message.toolActivity} />}
164
189
  </div>
165
190
  ) : null}
166
191
 
@@ -172,7 +197,7 @@ const MessageBubbleInner = ({
172
197
  plainText={isStreaming}
173
198
  />
174
199
  ) : (
175
- <StreamingIndicator />
200
+ streamingIndicator ? streamingIndicator(message) : <StreamingIndicator />
176
201
  )}
177
202
  </div>
178
203
 
@@ -189,13 +214,16 @@ const MessageBubbleInner = ({
189
214
  : null}
190
215
 
191
216
  {showActions && !isStreaming ? (
192
- <MessageActions
193
- role={message.role}
194
- onCopy={onCopy}
195
- onRegenerate={onRegenerate}
196
- onEdit={onEdit}
197
- onDelete={onDelete}
198
- />
217
+ <div className="flex items-center gap-0.5">
218
+ <MessageActions
219
+ role={message.role}
220
+ onCopy={onCopy}
221
+ onRegenerate={onRegenerate}
222
+ onEdit={onEdit}
223
+ onDelete={onDelete}
224
+ />
225
+ {messageActionsExtra ? messageActionsExtra(message) : null}
226
+ </div>
199
227
  ) : null}
200
228
 
201
229
  {showTimestamp ? (
@@ -1,6 +1,16 @@
1
1
  'use client';
2
2
 
3
- import { type RefObject, type ReactNode, forwardRef, useCallback } from 'react';
3
+ import {
4
+ type ReactNode,
5
+ type RefObject,
6
+ forwardRef,
7
+ useCallback,
8
+ useEffect,
9
+ useImperativeHandle,
10
+ useMemo,
11
+ useRef,
12
+ } from 'react';
13
+ import { Virtuoso, type VirtuosoHandle } from 'react-virtuoso';
4
14
 
5
15
  import { cn } from '@djangocfg/ui-core/lib';
6
16
  import { Spinner } from '@djangocfg/ui-core/components';
@@ -14,22 +24,68 @@ export interface MessageListProps {
14
24
  renderItem?: (m: ChatMessage, i: number) => ReactNode;
15
25
  renderEmpty?: () => ReactNode;
16
26
  isLoadingMore?: boolean;
27
+ /**
28
+ * Fires when the user scrolls within `topThresholdPx` of the top of
29
+ * the list — wire to your `loadMore()` here. Replaces the previous
30
+ * `topSentinelRef` API. The callback is gated by Virtuoso, so it
31
+ * won't fire repeatedly while a load is in flight (Virtuoso pauses
32
+ * `startReached` until `data` length grows).
33
+ */
34
+ onStartReached?: () => void;
35
+ /**
36
+ * @deprecated Kept as a no-op for backwards compatibility — wire
37
+ * `onStartReached` instead. Virtuoso owns the scroll viewport now,
38
+ * external sentinels never see scroll events.
39
+ */
17
40
  topSentinelRef?: RefObject<HTMLDivElement | null>;
41
+ /**
42
+ * @deprecated Kept as a no-op for backwards compatibility — Virtuoso
43
+ * exposes `scrollToIndex` via the imperative handle instead. See
44
+ * `useChatScroll` for the chat-friendly wrapper.
45
+ */
18
46
  bottomRef?: RefObject<HTMLDivElement | null>;
19
47
  className?: string;
20
48
  itemClassName?: string;
49
+ /**
50
+ * Skip virtualization and render through plain `.map()`. Use for
51
+ * stories / debugging where DevTools needs to see every node, or
52
+ * when `messages` is guaranteed-tiny. Default: `false` — virtualize
53
+ * always. Plan64.
54
+ */
55
+ noVirtualize?: boolean;
56
+ /**
57
+ * Initial item height estimate fed to Virtuoso's first-paint pass.
58
+ * The library re-measures every item after mount; this just tightens
59
+ * the initial scrollbar before measurements land. Default `120`.
60
+ */
61
+ defaultItemHeight?: number;
62
+ /**
63
+ * Fires when the viewport sticky state changes — `true` when the
64
+ * user is pinned to the bottom (streaming token deltas keep them
65
+ * there), `false` once they scroll up. Wire to your "Jump to
66
+ * latest" affordance via the inverse: render the pill when
67
+ * `!isAtBottom`. Plan64.
68
+ */
69
+ onAtBottomChange?: (isAtBottom: boolean) => void;
21
70
  }
22
71
 
23
- export const MessageList = forwardRef<HTMLDivElement, MessageListProps>(function MessageList(
72
+ export interface MessageListHandle {
73
+ scrollToBottom: (smooth?: boolean) => void;
74
+ scrollToIndex: (index: number, smooth?: boolean) => void;
75
+ }
76
+
77
+ export const MessageList = forwardRef<MessageListHandle, MessageListProps>(function MessageList(
24
78
  {
25
79
  messages: messagesProp,
26
80
  renderItem,
27
81
  renderEmpty,
28
82
  isLoadingMore: isLoadingMoreProp,
29
- topSentinelRef,
30
- bottomRef,
83
+ onStartReached,
31
84
  className,
32
85
  itemClassName,
86
+ noVirtualize = false,
87
+ defaultItemHeight = 120,
88
+ onAtBottomChange,
33
89
  },
34
90
  ref,
35
91
  ) {
@@ -37,9 +93,31 @@ export const MessageList = forwardRef<HTMLDivElement, MessageListProps>(function
37
93
  const messages = messagesProp ?? ctx?.messages ?? [];
38
94
  const isLoadingMore = isLoadingMoreProp ?? ctx?.isLoadingMore ?? false;
39
95
 
96
+ const virtuosoRef = useRef<VirtuosoHandle | null>(null);
97
+
98
+ useImperativeHandle(
99
+ ref,
100
+ () => ({
101
+ scrollToBottom: (smooth = false) => {
102
+ virtuosoRef.current?.scrollToIndex({
103
+ index: 'LAST',
104
+ behavior: smooth ? 'smooth' : 'auto',
105
+ align: 'end',
106
+ });
107
+ },
108
+ scrollToIndex: (index, smooth = false) => {
109
+ virtuosoRef.current?.scrollToIndex({
110
+ index,
111
+ behavior: smooth ? 'smooth' : 'auto',
112
+ });
113
+ },
114
+ }),
115
+ [],
116
+ );
117
+
40
118
  const defaultRenderItem = useCallback(
41
119
  (m: ChatMessage) => (
42
- <div className={itemClassName} key={m.id}>
120
+ <div className={itemClassName}>
43
121
  <MessageBubble
44
122
  message={m}
45
123
  onCopy={() => copy(m.content)}
@@ -52,26 +130,110 @@ export const MessageList = forwardRef<HTMLDivElement, MessageListProps>(function
52
130
  );
53
131
 
54
132
  const itemRenderer = renderItem ?? defaultRenderItem;
133
+ const computeItemKey = useCallback((index: number, m: ChatMessage) => m.id ?? index, []);
134
+
135
+ // Wrap user-supplied onStartReached so we don't double-fire while a
136
+ // load is already in flight. Virtuoso pauses startReached until
137
+ // `data` grows, but our consumers pass `onStartReached={loadMore}`
138
+ // directly — `loadMore` sets `isLoadingMore=true` synchronously, so
139
+ // we can suppress further calls until that flag drops back to false.
140
+ const startReachedHandler = useMemo(() => {
141
+ if (!onStartReached) return undefined;
142
+ let inFlight = false;
143
+ return () => {
144
+ if (inFlight || isLoadingMore) return;
145
+ inFlight = true;
146
+ try {
147
+ onStartReached();
148
+ } finally {
149
+ // Release on the next tick — Virtuoso re-fires startReached
150
+ // only after data length changes, so the inFlight guard is
151
+ // belt+suspenders against same-frame double calls.
152
+ queueMicrotask(() => {
153
+ inFlight = false;
154
+ });
155
+ }
156
+ };
157
+ }, [onStartReached, isLoadingMore]);
158
+
159
+ // Empty path — render renderEmpty instead of the virtualizer to avoid
160
+ // a blank Virtuoso frame and the cost of mounting it for nothing.
161
+ if (messages.length === 0) {
162
+ return (
163
+ <div
164
+ role="log"
165
+ aria-live="polite"
166
+ aria-atomic="false"
167
+ className={cn('flex-1 overflow-y-auto', className)}
168
+ >
169
+ {renderEmpty?.() ?? null}
170
+ </div>
171
+ );
172
+ }
173
+
174
+ if (noVirtualize) {
175
+ return (
176
+ <div
177
+ role="log"
178
+ aria-live="polite"
179
+ aria-atomic="false"
180
+ className={cn('flex-1 overflow-y-auto', className)}
181
+ >
182
+ {isLoadingMore ? (
183
+ <div className="flex justify-center py-2">
184
+ <Spinner className="size-4 text-muted-foreground" />
185
+ </div>
186
+ ) : null}
187
+ {messages.map((m, i) => (
188
+ <div key={m.id ?? i}>{itemRenderer(m, i)}</div>
189
+ ))}
190
+ </div>
191
+ );
192
+ }
55
193
 
56
194
  return (
57
- <div
58
- ref={ref}
195
+ <Virtuoso
196
+ ref={virtuosoRef}
59
197
  role="log"
60
198
  aria-live="polite"
61
199
  aria-atomic="false"
62
- className={cn('flex-1 overflow-y-auto', className)}
63
- >
64
- <div ref={topSentinelRef} aria-hidden />
65
- {isLoadingMore ? (
66
- <div className="flex justify-center py-2">
67
- <Spinner className="size-4 text-muted-foreground" />
68
- </div>
69
- ) : null}
70
- {messages.length === 0
71
- ? renderEmpty?.() ?? null
72
- : messages.map((m, i) => itemRenderer(m, i))}
73
- <div ref={bottomRef} aria-hidden />
74
- </div>
200
+ className={cn('flex-1', className)}
201
+ data={messages}
202
+ computeItemKey={computeItemKey}
203
+ itemContent={(index, m) => itemRenderer(m, index)}
204
+ defaultItemHeight={defaultItemHeight}
205
+ // Sticky-bottom: keep the viewport anchored to the latest message
206
+ // unless the user scrolled up. `'smooth'` while streaming would
207
+ // jank; Virtuoso defaults to `'auto'` which is what we want.
208
+ followOutput={(isAtBottom) => (isAtBottom ? 'auto' : false)}
209
+ atBottomStateChange={onAtBottomChange}
210
+ // Pad the list so a short conversation still hugs the bottom of
211
+ // the viewport (Telegram / iMessage feel) instead of stacking at
212
+ // the top.
213
+ alignToBottom
214
+ // Top-of-list pagination — fire when the topmost item enters the
215
+ // viewport. Virtuoso pauses this until `data` grows, so loadMore
216
+ // implementations don't need their own debounce.
217
+ startReached={startReachedHandler}
218
+ // Spinner while older history is loading. Rendering it as the
219
+ // Header keeps it inside the virtualized scroll, so it doesn't
220
+ // shift the viewport when it appears/disappears.
221
+ components={
222
+ isLoadingMore
223
+ ? {
224
+ Header: () => (
225
+ <div className="flex justify-center py-2">
226
+ <Spinner className="size-4 text-muted-foreground" />
227
+ </div>
228
+ ),
229
+ }
230
+ : undefined
231
+ }
232
+ // Item height is dynamic; Virtuoso re-measures on resize. We
233
+ // bias the initial overscan a bit so streaming-token re-layout
234
+ // doesn't leave gaps before the next measurement lands.
235
+ increaseViewportBy={{ top: 200, bottom: 400 }}
236
+ />
75
237
  );
76
238
  });
77
239
 
@@ -1,7 +1,11 @@
1
1
  'use client';
2
2
 
3
3
  export { ChatRoot, type ChatRootProps } from './ChatRoot';
4
- export { MessageList, type MessageListProps } from './MessageList';
4
+ export {
5
+ MessageList,
6
+ type MessageListProps,
7
+ type MessageListHandle,
8
+ } from './MessageList';
5
9
  export { MessageBubble, type MessageBubbleProps } from './MessageBubble';
6
10
  export { MessageActions, type MessageActionsProps } from './MessageActions';
7
11
  export { Composer, type ComposerProps } from './Composer';
@@ -40,6 +40,12 @@ export interface ChatProviderProps {
40
40
  audio?: ChatAudioConfig;
41
41
  /** Enable verbose dev logging via consola. Defaults to `isDev`. */
42
42
  debug?: boolean;
43
+ /**
44
+ * Rewrite outgoing message content before it hits the transport.
45
+ * History bubble keeps the original; useful for stripping rich-
46
+ * display chips so the LLM sees plain text. See `useChat`.
47
+ */
48
+ onBeforeSend?: (content: string) => string | Promise<string>;
43
49
  children?: ReactNode;
44
50
  }
45
51
 
@@ -51,6 +57,7 @@ export function ChatProvider({
51
57
  streaming,
52
58
  audio,
53
59
  debug,
60
+ onBeforeSend,
54
61
  children,
55
62
  }: ChatProviderProps) {
56
63
  const audioApi = useChatAudio(audio ?? {});
@@ -80,6 +87,7 @@ export function ChatProvider({
80
87
  onMessageEnd,
81
88
  onStreamStart,
82
89
  onError,
90
+ onBeforeSend,
83
91
  });
84
92
  const layout = useChatLayout({ defaultMode: 'embedded' });
85
93
 
@@ -37,6 +37,16 @@ export interface UseChatConfig {
37
37
  metadata?: Record<string, unknown>;
38
38
  /** Stamped on outgoing user messages as `message.sender`. */
39
39
  userPersona?: ChatPersona;
40
+ /**
41
+ * Rewrite the outgoing message content right before it hits the
42
+ * transport — runs after the user bubble is added (so history shows
43
+ * the original) but before `transport.stream/send`. Sync or async.
44
+ * Return the original to opt out for that call.
45
+ *
46
+ * Use case: strip rich-display chips (e.g. mention links) so the LLM
47
+ * sees plain text, while the bubble keeps the chip rendering. Plan64.
48
+ */
49
+ onBeforeSend?: (content: string) => string | Promise<string>;
40
50
  /**
41
51
  * Enable verbose dev-mode logging (consola, namespace `chat:*`).
42
52
  * Defaults to `isDev` from `@djangocfg/ui-core/lib`. Pass `false` to silence
@@ -439,13 +449,24 @@ export function useChat(config: UseChatConfig): UseChatReturn {
439
449
  dispatch({ type: 'MESSAGE_USER_ADD', message: userMsg });
440
450
  config.onMessageSent?.(userMsg);
441
451
 
452
+ // History bubble shows the original; transport sees the rewrite.
453
+ // Use case: strip rich-display chips so the LLM sees plain text.
454
+ let outbound = content;
455
+ if (config.onBeforeSend) {
456
+ try {
457
+ outbound = await config.onBeforeSend(content);
458
+ } catch (err) {
459
+ log.error.error('onBeforeSend threw — falling back to original content', err);
460
+ }
461
+ }
462
+
442
463
  if (streaming) {
443
- await consumeStream(sessionId, content, attachments);
464
+ await consumeStream(sessionId, outbound, attachments);
444
465
  } else {
445
- await consumeBuffered(sessionId, content, attachments);
466
+ await consumeBuffered(sessionId, outbound, attachments);
446
467
  }
447
468
  },
448
- [streaming, consumeStream, consumeBuffered, config, awaitSession],
469
+ [streaming, consumeStream, consumeBuffered, config, awaitSession, log],
449
470
  );
450
471
 
451
472
  const cancelStream = useCallback(() => {
@@ -24,6 +24,16 @@ export interface UseChatComposerOptions {
24
24
  submitOn?: 'enter' | 'cmd+enter';
25
25
  history?: { enabled?: boolean; size?: number };
26
26
  onPasteFiles?: (files: File[]) => void;
27
+ /**
28
+ * Persist the current draft to `sessionStorage` under this key. The
29
+ * draft is loaded once on mount (overrides `initialValue` if non-
30
+ * empty) and rewritten on every value change. Cleared on `reset()`.
31
+ *
32
+ * Pass a per-conversation id to keep separate drafts per chat. Pass
33
+ * `undefined` (default) to disable persistence — composer behaves
34
+ * exactly as before. Plan64.
35
+ */
36
+ persistKey?: string;
27
37
  }
28
38
 
29
39
  export interface UseChatComposerReturn {
@@ -62,9 +72,37 @@ export function useChatComposer(options: UseChatComposerOptions): UseChatCompose
62
72
  submitOn = 'enter',
63
73
  history = { enabled: true, size: LIMITS.composerHistorySize },
64
74
  onPasteFiles,
75
+ persistKey,
65
76
  } = options;
66
77
 
67
- const [value, setValueState] = useState(initialValue);
78
+ // Hydrate draft from sessionStorage on mount when a key is provided.
79
+ // We read once, lazily — switching `persistKey` mid-life (e.g.
80
+ // session change) requires a parent remount via React `key`, same
81
+ // pattern as `<MessageList>`. Avoids accidental cross-session
82
+ // bleed-through when the parent forgets to remount.
83
+ const initialFromStorage = (() => {
84
+ if (!persistKey || typeof window === 'undefined') return initialValue;
85
+ try {
86
+ const stored = window.sessionStorage.getItem(`chat:draft:${persistKey}`);
87
+ return stored && stored.length > 0 ? stored : initialValue;
88
+ } catch {
89
+ return initialValue;
90
+ }
91
+ })();
92
+ const [value, setValueState] = useState(initialFromStorage);
93
+
94
+ // Persist on every value change. Throwaway swallow keeps quota /
95
+ // private-mode failures from breaking the composer.
96
+ useEffect(() => {
97
+ if (!persistKey || typeof window === 'undefined') return;
98
+ try {
99
+ const k = `chat:draft:${persistKey}`;
100
+ if (value.length > 0) window.sessionStorage.setItem(k, value);
101
+ else window.sessionStorage.removeItem(k);
102
+ } catch {
103
+ /* noop — quota / disabled storage is non-fatal */
104
+ }
105
+ }, [value, persistKey]);
68
106
  const [attachments, setAttachments] = useState<ChatAttachment[]>([]);
69
107
  const [isSubmitting, setIsSubmitting] = useState(false);
70
108
  const textareaRef = useRef<HTMLTextAreaElement | null>(null);
@@ -2,6 +2,19 @@
2
2
 
3
3
  import { type RefObject, useCallback, useEffect, useRef, useState } from 'react';
4
4
 
5
+ /**
6
+ * @deprecated Plan64. As of ui-tools 2.1.369, `<MessageList>` is
7
+ * virtualized via react-virtuoso and owns its own scroll viewport.
8
+ * Sticky-bottom + auto-follow on streaming live inside the component;
9
+ * use the new `MessageListProps.onAtBottomChange` prop and the
10
+ * `MessageListHandle.scrollToBottom()` imperative method instead.
11
+ *
12
+ * This hook is kept for hosts that render messages outside
13
+ * `<MessageList>` (e.g. headless story shells, custom non-virtualized
14
+ * scroll containers). It still works against any HTMLElement scroll
15
+ * container, but it does NOT integrate with Virtuoso — passing a
16
+ * Virtuoso-managed element here will read garbage scroll metrics.
17
+ */
5
18
  export interface UseChatScrollOptions {
6
19
  containerRef: RefObject<HTMLElement | null>;
7
20
  bottomRef: RefObject<HTMLElement | null>;
@@ -140,6 +140,7 @@ export {
140
140
  AudioToggle,
141
141
  type ChatRootProps,
142
142
  type MessageListProps,
143
+ type MessageListHandle,
143
144
  type MessageBubbleProps,
144
145
  type MessageActionsProps,
145
146
  type ComposerProps,
@@ -178,6 +178,12 @@ export interface SessionInfo {
178
178
  hasMore?: boolean;
179
179
  cursor?: string | null;
180
180
  resumed?: boolean;
181
+ /**
182
+ * Optional human-readable title (typically derived from the first
183
+ * user message). Hosts that render a session-list sidebar can read
184
+ * this directly instead of crawling messages. Plan64.
185
+ */
186
+ title?: string;
181
187
  }
182
188
 
183
189
  export interface HistoryPage {
@@ -1,5 +0,0 @@
1
- export { ChatRoot } from './chunk-WGU5BEZX.mjs';
2
- import './chunk-NWUT327A.mjs';
3
- import './chunk-N2XQF2OL.mjs';
4
- //# sourceMappingURL=ChatRoot-6U7633X3.mjs.map
5
- //# sourceMappingURL=ChatRoot-6U7633X3.mjs.map