@salmonui/chat 0.0.0-stage → 0.2.0

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.
Files changed (103) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +41 -2
  3. package/dist/conversation/Conversation.d.ts +4 -0
  4. package/dist/conversation/Conversation.d.ts.map +1 -0
  5. package/dist/conversation/Conversation.js +588 -0
  6. package/dist/conversation/Conversation.js.map +1 -0
  7. package/dist/conversation/Item.d.ts +67 -0
  8. package/dist/conversation/Item.d.ts.map +1 -0
  9. package/dist/conversation/Item.js +149 -0
  10. package/dist/conversation/Item.js.map +1 -0
  11. package/dist/conversation/assistant-lazy.d.ts +6 -0
  12. package/dist/conversation/assistant-lazy.d.ts.map +1 -0
  13. package/dist/conversation/assistant-lazy.js +16 -0
  14. package/dist/conversation/assistant-lazy.js.map +1 -0
  15. package/dist/conversation/assistant-static.d.ts +4 -0
  16. package/dist/conversation/assistant-static.d.ts.map +1 -0
  17. package/dist/conversation/assistant-static.js +9 -0
  18. package/dist/conversation/assistant-static.js.map +1 -0
  19. package/dist/conversation/assistant-types.d.ts +2 -0
  20. package/dist/conversation/assistant-types.d.ts.map +1 -0
  21. package/dist/conversation/assistant-types.js +3 -0
  22. package/dist/conversation/assistant-types.js.map +1 -0
  23. package/dist/conversation/assistant.d.ts +54 -0
  24. package/dist/conversation/assistant.d.ts.map +1 -0
  25. package/dist/conversation/assistant.js +348 -0
  26. package/dist/conversation/assistant.js.map +1 -0
  27. package/dist/conversation/context.d.ts +80 -0
  28. package/dist/conversation/context.d.ts.map +1 -0
  29. package/dist/conversation/context.js +40 -0
  30. package/dist/conversation/context.js.map +1 -0
  31. package/dist/conversation/format.d.ts +33 -0
  32. package/dist/conversation/format.d.ts.map +1 -0
  33. package/dist/conversation/format.js +150 -0
  34. package/dist/conversation/format.js.map +1 -0
  35. package/dist/conversation/parts.d.ts +16 -0
  36. package/dist/conversation/parts.d.ts.map +1 -0
  37. package/dist/conversation/parts.js +326 -0
  38. package/dist/conversation/parts.js.map +1 -0
  39. package/dist/conversation/runner.d.ts +15 -0
  40. package/dist/conversation/runner.d.ts.map +1 -0
  41. package/dist/conversation/runner.js +52 -0
  42. package/dist/conversation/runner.js.map +1 -0
  43. package/dist/conversation/store.d.ts +63 -0
  44. package/dist/conversation/store.d.ts.map +1 -0
  45. package/dist/conversation/store.js +142 -0
  46. package/dist/conversation/store.js.map +1 -0
  47. package/dist/conversation/types.d.ts +473 -0
  48. package/dist/conversation/types.d.ts.map +1 -0
  49. package/dist/conversation/types.js +5 -0
  50. package/dist/conversation/types.js.map +1 -0
  51. package/dist/conversation.css +788 -0
  52. package/dist/conversation.d.ts +18 -0
  53. package/dist/conversation.d.ts.map +1 -0
  54. package/dist/conversation.js +26 -0
  55. package/dist/conversation.js.map +1 -0
  56. package/dist/inline-assist/InlineAssist.d.ts +16 -0
  57. package/dist/inline-assist/InlineAssist.d.ts.map +1 -0
  58. package/dist/inline-assist/InlineAssist.js +384 -0
  59. package/dist/inline-assist/InlineAssist.js.map +1 -0
  60. package/dist/inline-assist/model.d.ts +40 -0
  61. package/dist/inline-assist/model.d.ts.map +1 -0
  62. package/dist/inline-assist/model.js +87 -0
  63. package/dist/inline-assist/model.js.map +1 -0
  64. package/dist/inline-assist/types.d.ts +216 -0
  65. package/dist/inline-assist/types.d.ts.map +1 -0
  66. package/dist/inline-assist/types.js +5 -0
  67. package/dist/inline-assist/types.js.map +1 -0
  68. package/dist/inline-assist.css +890 -0
  69. package/dist/inline-assist.d.ts +5 -0
  70. package/dist/inline-assist.d.ts.map +1 -0
  71. package/dist/inline-assist.js +12 -0
  72. package/dist/inline-assist.js.map +1 -0
  73. package/dist/internal/stream-run.d.ts +71 -0
  74. package/dist/internal/stream-run.d.ts.map +1 -0
  75. package/dist/internal/stream-run.js +161 -0
  76. package/dist/internal/stream-run.js.map +1 -0
  77. package/dist/internal/suggest.d.ts +90 -0
  78. package/dist/internal/suggest.d.ts.map +1 -0
  79. package/dist/internal/suggest.js +332 -0
  80. package/dist/internal/suggest.js.map +1 -0
  81. package/dist/smart-paste/fields.d.ts +31 -0
  82. package/dist/smart-paste/fields.d.ts.map +1 -0
  83. package/dist/smart-paste/fields.js +162 -0
  84. package/dist/smart-paste/fields.js.map +1 -0
  85. package/dist/smart-paste/useSmartPaste.d.ts +38 -0
  86. package/dist/smart-paste/useSmartPaste.d.ts.map +1 -0
  87. package/dist/smart-paste/useSmartPaste.js +56 -0
  88. package/dist/smart-paste/useSmartPaste.js.map +1 -0
  89. package/dist/smart-paste.d.ts +3 -0
  90. package/dist/smart-paste.d.ts.map +1 -0
  91. package/dist/smart-paste.js +6 -0
  92. package/dist/smart-paste.js.map +1 -0
  93. package/dist/styles.css +1754 -0
  94. package/dist/text-suggest/useTextSuggest.d.ts +13 -0
  95. package/dist/text-suggest/useTextSuggest.d.ts.map +1 -0
  96. package/dist/text-suggest/useTextSuggest.js +55 -0
  97. package/dist/text-suggest/useTextSuggest.js.map +1 -0
  98. package/dist/text-suggest.css +78 -0
  99. package/dist/text-suggest.d.ts +4 -0
  100. package/dist/text-suggest.d.ts.map +1 -0
  101. package/dist/text-suggest.js +9 -0
  102. package/dist/text-suggest.js.map +1 -0
  103. package/package.json +68 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 NuLL
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,42 @@
1
- # Temporary Holding Version
1
+ # @salmonui/chat
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Conversation, InlineAssist, TextSuggest and SmartPaste for Salmon UI with provider-agnostic AI adapters.
4
+
5
+ ```sh
6
+ npm install @salmonui/chat @salmonui/core react react-dom
7
+ ```
8
+
9
+ `react` and `react-dom` `>=19` are peer dependencies. ESM only.
10
+ Every `@salmonui/*` package of an application must resolve to the same
11
+ version (they are released together and exact-pinned to each other);
12
+ `@salmonui/core` warns in development when a second copy loads.
13
+
14
+ ```tsx
15
+ import { Conversation, ConversationComposer } from '@salmonui/chat/conversation';
16
+ import { InlineAssist } from '@salmonui/chat/inline-assist';
17
+ import { useTextSuggest } from '@salmonui/chat/text-suggest';
18
+ ```
19
+
20
+ Import the theme stylesheet once per application, then the
21
+ stylesheet of each family you use:
22
+
23
+ ```tsx
24
+ import '@salmonui/core/styles.css'; // the theme, once per application
25
+ import '@salmonui/chat/conversation/styles.css';
26
+ ```
27
+
28
+ Each family has its own `@salmonui/chat/<family>/styles.css` (`@salmonui/chat/smart-paste`
29
+ is a hook and has none).
30
+ A family stylesheet carries its own rules and those of every family and shared
31
+ module it renders, so it is the only stylesheet that family needs.
32
+
33
+ Public entry points:
34
+
35
+ - `@salmonui/chat/conversation`
36
+ - `@salmonui/chat/inline-assist`
37
+ - `@salmonui/chat/text-suggest`
38
+ - `@salmonui/chat/smart-paste`
39
+
40
+ ## License
41
+
42
+ MIT
@@ -0,0 +1,4 @@
1
+ import { type ReactNode } from 'react';
2
+ import type { ConversationProps } from './types.js';
3
+ export declare function ConversationRoot(props: ConversationProps): ReactNode;
4
+ //# sourceMappingURL=Conversation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Conversation.d.ts","sourceRoot":"","sources":["../../src/conversation/Conversation.tsx"],"names":[],"mappings":"AAeA,OAAO,EAAiJ,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AAYtL,OAAO,KAAK,EAAyE,iBAAiB,EAAoB,MAAM,YAAY,CAAC;AAuG7I,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,iBAAiB,GAAG,SAAS,CA6LpE"}
@@ -0,0 +1,588 @@
1
+ 'use client';
2
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ // <Conversation variant="chat" | "assistant">: the root owns the store,
4
+ // the message triad, the adapter runner, the live region and the feed. The
5
+ // feed is an APG Feed (`role="feed"`, `role="article"` items) inside a
6
+ // `flex-direction: column-reverse` scroller, so server HTML is already
7
+ // bottom-anchored and prepending older history keeps the distance from the
8
+ // bottom (the technique holds with the virtualizer; the anchor restore
9
+ // below covers measurement changes).
10
+ // Variable-height windowing reuses the Data Grid core metrics
11
+ // (`createVariableRowMetrics`, `computeRange`). Scroll position, the
12
+ // at-bottom flag, measured heights and the unread count live in the store
13
+ // or the DOM, never in React state.
14
+ import { computeRange, createVariableRowMetrics } from '@salmonui/core/virtual';
15
+ import { Children, isValidElement, useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo, useState, useSyncExternalStore } from 'react';
16
+ import { useControllableState } from '@salmonui/core/internal/controllable';
17
+ import { useLocale, useLocaleText } from '@salmonui/core/internal/locale';
18
+ import { DEV, warnOnce } from '@salmonui/core/internal/dev';
19
+ import { focusableIn } from '@salmonui/core/internal/focus-scope';
20
+ import { ConversationConfigContext, ConversationInstanceContext, join, useStore } from './context.js';
21
+ import { createText, typingText } from './format.js';
22
+ import { FeedItem } from './Item.js';
23
+ import { ConversationJumpButton, ConversationPinnedBar, SLOT } from './parts.js';
24
+ import { loadAssistant } from '#conversation-assistant';
25
+ import { runAdapter } from './runner.js';
26
+ import { createConversationStore } from './store.js';
27
+ const EMPTY = Object.freeze([]);
28
+ const OVERSCAN = 6;
29
+ /** Distance from the bottom in px that still counts as "at the bottom". */
30
+ const BOTTOM_SLACK = 4;
31
+ /** Index window rendered on the server and before the first measurement. */
32
+ function initialWindow(count, initial) {
33
+ return { first: Math.max(0, count - initial), last: count };
34
+ }
35
+ function Feed({ instance, geometry, setSize, busy, label }) {
36
+ const store = instance.store;
37
+ const ids = useStore(store, store.getIds);
38
+ const first = useStore(store, () => store.getView().first);
39
+ const last = useStore(store, () => store.getView().last);
40
+ const focusIndex = useSyncExternalStore(store.subscribe, () => store.getView().focusIndex, () => -1);
41
+ const end = Math.min(last, ids.length);
42
+ const items = [];
43
+ // The roving article stays mounted when scrolled out of the window.
44
+ const push = (i) => void items.push(_jsx(FeedItem, { id: ids[i], index: i, setSize: setSize }, ids[i]));
45
+ if (focusIndex >= 0 && focusIndex < first && focusIndex < ids.length)
46
+ push(focusIndex);
47
+ for (let i = first; i < end; i++)
48
+ push(i);
49
+ if (focusIndex >= end && focusIndex < ids.length)
50
+ push(focusIndex);
51
+ const onKeyDown = (event) => {
52
+ const article = event.target.closest('article');
53
+ if (!article || !event.currentTarget.contains(article))
54
+ return;
55
+ const index = Number(article.getAttribute('data-index'));
56
+ const root = instance.root;
57
+ if ((event.ctrlKey || event.metaKey) && (event.key === 'End' || event.key === 'Home')) {
58
+ // APG Feed: leave the feed to the first focusable element after / before it.
59
+ const scroller = instance.scroller;
60
+ if (!root || !scroller)
61
+ return;
62
+ const all = focusableIn(root).filter((el) => !scroller.contains(el));
63
+ const after = event.key === 'End';
64
+ const target = after ? all.find((el) => scroller.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING) : [...all].reverse().find((el) => scroller.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_PRECEDING);
65
+ if (target) {
66
+ event.preventDefault();
67
+ target.focus();
68
+ }
69
+ return;
70
+ }
71
+ if (event.target !== article)
72
+ return;
73
+ if (event.key === 'PageDown' || event.key === 'PageUp') {
74
+ event.preventDefault();
75
+ const next = index + (event.key === 'PageDown' ? 1 : -1);
76
+ const id = store.getIds()[next];
77
+ if (id !== undefined)
78
+ instance.scrollToMessage(id, true);
79
+ }
80
+ };
81
+ const onFocus = (event) => {
82
+ const article = event.target.closest?.('article');
83
+ if (article)
84
+ store.setView({ focusIndex: Number(article.getAttribute('data-index')) });
85
+ };
86
+ return (_jsx("div", { role: "feed", className: "salmon-conversation-feed", "aria-label": label, "aria-busy": busy ? true : undefined, onKeyDown: onKeyDown, onFocus: onFocus, children: items }));
87
+ }
88
+ function TypingIndicator({ users, config, render }) {
89
+ if (users.length === 0)
90
+ return null;
91
+ const resolved = users.map((id) => config.users.get(id) ?? { id, name: id });
92
+ return (_jsx("div", { className: "salmon-conversation-typing", "aria-hidden": "true", children: render ? (render({ users: resolved })) : (_jsxs(_Fragment, { children: [_jsxs("span", { className: "salmon-conversation-typing__dots", children: [_jsx("span", {}), _jsx("span", {}), _jsx("span", {})] }), _jsx("span", { className: "salmon-conversation-typing__text", children: typingText(config.text, resolved.map((u) => u.name)) })] })) }));
93
+ }
94
+ export function ConversationRoot(props) {
95
+ const { variant = 'chat', currentUser = 'user', users = EMPTY, typingUsers = EMPTY, layout = 'bubbles', timestamps = true, formatTimestamp, timeZone, dateSeparators = false, renderDateSeparator, renderItem, renderAvatar, renderEmpty, renderTyping, itemActions, renderContent, renderPending, renderReasoning, renderTool, hasOlder = false, jumpButton = true, initialItemCount = 30, className, style, classNames, styles, children, ref, } = props;
96
+ const locale = useLocale(props.locale) ?? 'en-US';
97
+ const localeText = useLocaleText('conversation', props.localeText);
98
+ const baseId = useId();
99
+ const [messages, setMessages] = useControllableState(props.messages, () => props.defaultMessages ?? EMPTY, props.onMessagesChange, 'Conversation messages');
100
+ const [store] = useState(() => {
101
+ const s = createConversationStore(messages);
102
+ s.setView(initialWindow(messages.length, initialItemCount));
103
+ return s;
104
+ });
105
+ const [geometry] = useState(() => ({ heights: new Map(), metrics: createVariableRowMetrics(0, () => 0), ids: EMPTY, anchor: null, stick: true, reveal: null, observer: null, frame: 0, lastTop: 0 }));
106
+ const [instance] = useState(() => createInstance(store, baseId, props, geometry));
107
+ const loadingOlder = useSyncExternalStore(store.subscribe, () => store.getView().loadingOlder, () => false);
108
+ const ids = useStore(store, store.getIds);
109
+ if (DEV && variant !== 'chat' && variant !== 'assistant')
110
+ warnOnce('conversation-variant', `Conversation: unknown variant "${String(variant)}".`);
111
+ useLayoutEffect(() => {
112
+ instance.props = props;
113
+ instance.commitRaw = setMessages;
114
+ instance.text = config.text;
115
+ });
116
+ const usersKey = users;
117
+ const userMap = useMemo(() => new Map(usersKey.map((u) => [u.id, u])), [usersKey]);
118
+ const config = useMemo(() => ({
119
+ currentUser,
120
+ users: userMap,
121
+ layout,
122
+ timestamps,
123
+ formatTimestamp,
124
+ locale,
125
+ timeZone,
126
+ dateSeparators,
127
+ renderDateSeparator,
128
+ renderItem,
129
+ renderAvatar,
130
+ itemActions,
131
+ assistant: variant === 'assistant',
132
+ renderContent,
133
+ renderPending,
134
+ renderReasoning,
135
+ renderTool,
136
+ renderAttachment: props.renderAttachment,
137
+ onAttachmentClick: props.onAttachmentClick,
138
+ hasRetry: props.onRetry !== undefined,
139
+ text: createText(localeText, locale),
140
+ }), [currentUser, userMap, layout, timestamps, formatTimestamp, locale, timeZone, dateSeparators, renderDateSeparator, renderItem, renderAvatar, itemActions, variant, renderContent, renderPending, renderReasoning, renderTool, props.renderAttachment, props.onAttachmentClick, props.onRetry, localeText]);
141
+ // Sync the message list into the store, then anchor, announce and count unread.
142
+ useLayoutEffect(() => {
143
+ const before = store.getIds().length;
144
+ const view = store.getView();
145
+ const diff = store.setMessages(messages);
146
+ if (!diff.changed)
147
+ return;
148
+ if (diff.prepended > 0)
149
+ store.setView({ first: view.first + diff.prepended, last: view.last + diff.prepended, focusIndex: view.focusIndex >= 0 ? view.focusIndex + diff.prepended : -1 });
150
+ else if (view.last >= before)
151
+ store.setView({ last: messages.length });
152
+ if (diff.appended.length > 0 && before > 0) {
153
+ const auto = instance.props.autoScroll ?? 'whenAtBottom';
154
+ const own = diff.appended.some((id) => store.getMessage(id)?.author === currentUser);
155
+ const stick = auto === 'always' || (auto !== 'never' && (own || store.getView().atBottom));
156
+ geometry.stick = stick;
157
+ const incoming = diff.appended.map((id) => store.getMessage(id)).filter((m) => !!m && m.author !== currentUser && m.text !== '');
158
+ if (!stick && incoming.length > 0)
159
+ store.setView({ unread: store.getView().unread + incoming.length });
160
+ const latest = incoming[incoming.length - 1];
161
+ if (latest)
162
+ instance.announce(config.text('newMessage', { author: userMap.get(latest.author)?.name ?? latest.author, text: latest.text }));
163
+ }
164
+ adjust(instance, geometry);
165
+ }, [messages, store, instance, geometry, currentUser, config, userMap]);
166
+ // Typing indicator changes are announced once each.
167
+ const typingKey = typingUsers.join('\u0000');
168
+ useEffect(() => {
169
+ if (typingKey === '')
170
+ return;
171
+ instance.announce(typingText(config.text, typingKey.split('\u0000').map((id) => userMap.get(id)?.name ?? id)));
172
+ }, [typingKey, instance, config, userMap]);
173
+ useEffect(() => mountFeed(instance, geometry), [instance, geometry]);
174
+ useImperativeHandle(ref, () => ({
175
+ scrollToBottom: (options) => instance.scrollToBottom(options?.behavior),
176
+ scrollToMessage: (id, options) => instance.scrollToMessage(id, options?.focus ?? false),
177
+ focus: () => instance.focusComposer(),
178
+ send: (text) => void instance.send(text),
179
+ stop: () => instance.stop(),
180
+ regenerate: (id) => void loadAssistant().then((m) => m.regenerate(instance, id)),
181
+ get element() {
182
+ return instance.root;
183
+ },
184
+ }), [instance]);
185
+ const start = [];
186
+ const end = [];
187
+ Children.forEach(children, (child) => {
188
+ if (isValidElement(child) && child.type[SLOT] === 'start')
189
+ start.push(child);
190
+ else
191
+ end.push(child);
192
+ });
193
+ const setSize = hasOlder ? -1 : ids.length;
194
+ return (_jsx(ConversationInstanceContext, { value: instance, children: _jsx(ConversationConfigContext, { value: config, children: _jsxs("div", { ref: (el) => {
195
+ instance.root = el;
196
+ }, className: join('salmon-conversation', className, classNames?.root), style: styles?.root ? { ...styles.root, ...style } : style, "data-variant": variant, "data-layout": layout, children: [start, _jsx(ConversationPinnedBar, {}), _jsx("div", { ref: (el) => {
197
+ instance.scroller = el;
198
+ }, className: join('salmon-conversation-scroller', classNames?.scroller), style: styles?.scroller, children: _jsxs("div", { className: "salmon-conversation-content", children: [hasOlder ? (_jsx("div", { className: "salmon-conversation-older", "data-loading": loadingOlder ? '' : undefined, children: loadingOlder ? (_jsx("span", { className: "salmon-conversation-skeleton", role: "status", children: _jsx("span", { className: "salmon-conversation-sr", children: config.text('loadingOlder') }) })) : null })) : null, _jsx("div", { className: "salmon-conversation-spacer", "data-edge": "start", "aria-hidden": "true" }), ids.length === 0 && renderEmpty ? _jsx("div", { className: "salmon-conversation-empty", children: renderEmpty() }) : null, _jsx(Feed, { instance: instance, geometry: geometry, setSize: setSize, busy: loadingOlder, label: config.text('feedLabel') }), _jsx("div", { className: "salmon-conversation-spacer", "data-edge": "end", "aria-hidden": "true" })] }) }), _jsx(TypingIndicator, { users: typingUsers, config: config, render: renderTyping }), jumpButton ? _jsx(ConversationJumpButton, {}) : null, end, _jsx("div", { ref: (el) => {
199
+ instance.live = el;
200
+ }, className: "salmon-conversation-sr", role: "status", "aria-live": "polite", "aria-atomic": "true" })] }) }) }));
201
+ }
202
+ function createInstance(store, baseId, initialProps, geometry) {
203
+ let controller = null;
204
+ let typing = false;
205
+ let typingTimer = null;
206
+ let announceTimer = null;
207
+ let generated = 0;
208
+ const newId = () => {
209
+ const c = globalThis.crypto;
210
+ return c?.randomUUID ? c.randomUUID() : `${baseId}-${Date.now().toString(36)}-${(generated++).toString(36)}`;
211
+ };
212
+ /** Runs the adapter for response `id` and commits the result once; the assistant variant runs it in its chunk. */
213
+ const respond = (history, text, attachments, id) => {
214
+ const adapter = instance.props.adapter;
215
+ instance.stop();
216
+ const own = new AbortController();
217
+ controller = own;
218
+ store.setView({ responding: true });
219
+ const request = { messages: history, text, attachments };
220
+ const run = instance.props.variant === 'assistant' ? loadAssistant().then((m) => m.run(adapter, request, id, store, own.signal, runAdapter)) : runAdapter(adapter, request, id, store, own.signal);
221
+ void run.then((outcome) => {
222
+ if (controller === own) {
223
+ controller = null;
224
+ store.setView({ responding: false });
225
+ }
226
+ const failed = outcome.status === 'error';
227
+ if (failed)
228
+ instance.props.onError?.(outcome.error);
229
+ instance.commit((prev) => {
230
+ const m = prev.find((x) => x.id === id);
231
+ if (!m)
232
+ return prev;
233
+ const next = outcome.apply ? outcome.apply(m) : outcome.text === '' && !failed ? null : failed ? { ...m, text: outcome.text, status: 'error' } : { id, author: m.author, text: outcome.text, ...(m.createdAt !== undefined ? { createdAt: m.createdAt } : null) };
234
+ return next ? prev.map((x) => (x === m ? next : x)) : prev.filter((x) => x !== m);
235
+ }, 'response');
236
+ if (outcome.status === 'done' && outcome.text !== '') {
237
+ const author = store.getMessage(id)?.author ?? '';
238
+ const name = instance.props.users?.find((u) => u.id === author)?.name ?? author;
239
+ instance.announce(instance.text('responseComplete', { author: name, text: outcome.text }));
240
+ }
241
+ });
242
+ };
243
+ const instance = {
244
+ store,
245
+ baseId,
246
+ props: initialProps,
247
+ root: null,
248
+ scroller: null,
249
+ composer: null,
250
+ live: null,
251
+ commitRaw: null,
252
+ commit(update, reason) {
253
+ instance.commitRaw?.(update, Object.freeze({ reason }));
254
+ },
255
+ send(text, options = {}) {
256
+ const p = instance.props;
257
+ const attachments = options.attachments ?? EMPTY;
258
+ if (text.trim() === '' && attachments.length === 0)
259
+ return false;
260
+ const replyTo = store.getView().replyTo;
261
+ const message = {
262
+ id: newId(),
263
+ author: p.currentUser ?? 'user',
264
+ text,
265
+ createdAt: new Date(),
266
+ ...(replyTo ? { replyTo } : null),
267
+ ...(options.mentions && options.mentions.length > 0 ? { mentions: options.mentions } : null),
268
+ ...(attachments.length > 0 ? { attachments } : null),
269
+ };
270
+ if (p.onBeforeSend) {
271
+ let prevented = false;
272
+ const event = {
273
+ message,
274
+ preventDefault: () => {
275
+ prevented = true;
276
+ },
277
+ get defaultPrevented() {
278
+ return prevented;
279
+ },
280
+ };
281
+ p.onBeforeSend(event);
282
+ if (prevented)
283
+ return false;
284
+ }
285
+ instance.stopTyping();
286
+ geometry.stick = (p.autoScroll ?? 'whenAtBottom') !== 'never';
287
+ store.setView({ replyTo: null, unread: 0 });
288
+ const adapter = p.adapter;
289
+ const responseId = adapter ? newId() : '';
290
+ const author = p.adapterAuthor ?? 'assistant';
291
+ let history = [message];
292
+ // One proposal for the message and the pending response, so a controlled parent sees both.
293
+ instance.commit((prev) => {
294
+ history = [...prev, message];
295
+ return adapter ? [...history, { id: responseId, author, text: '', createdAt: new Date(), status: 'sending' }] : history;
296
+ }, 'send');
297
+ p.onSend?.(Object.freeze({ message }));
298
+ if (adapter)
299
+ respond(history, text, attachments, responseId);
300
+ return true;
301
+ },
302
+ stop() {
303
+ if (!controller)
304
+ return;
305
+ controller.abort();
306
+ instance.props.onStop?.({ message: store.getMessage(store.getStream()?.id) });
307
+ },
308
+ respond,
309
+ scrollToBottom(behavior) {
310
+ const s = instance.scroller;
311
+ geometry.stick = true;
312
+ store.setView({ unread: 0 });
313
+ const n = store.getIds().length;
314
+ const view = store.getView();
315
+ if (view.last < n)
316
+ store.setView({ first: Math.max(0, n - (view.last - view.first)), last: n });
317
+ if (s) {
318
+ s.scrollTo({ top: 0, behavior: behavior ?? 'auto' });
319
+ geometry.lastTop = s.scrollTop;
320
+ }
321
+ adjust(instance, geometry);
322
+ },
323
+ scrollToMessage(id, focus) {
324
+ const index = store.indexOf(id);
325
+ if (index < 0)
326
+ return false;
327
+ geometry.stick = false;
328
+ geometry.reveal = { id, focus: focus ?? false };
329
+ const view = store.getView();
330
+ if (focus)
331
+ store.setView({ focusIndex: index });
332
+ if (index < view.first || index >= view.last) {
333
+ const n = store.getIds().length;
334
+ const size = Math.max(view.last - view.first, OVERSCAN * 2 + 1);
335
+ const first = Math.max(0, Math.min(index - OVERSCAN, n - size));
336
+ // No adjust before React mounts the new window: the old articles would size the
337
+ // spacers wrong. The window subscription adjusts (and reveals) after the commit.
338
+ store.setView({ first, last: Math.min(n, first + size) });
339
+ }
340
+ else
341
+ adjust(instance, geometry);
342
+ return true;
343
+ },
344
+ announce(text) {
345
+ const live = instance.live;
346
+ if (!live)
347
+ return;
348
+ // Clear first so a repeated text is announced again.
349
+ live.textContent = '';
350
+ if (announceTimer)
351
+ clearTimeout(announceTimer);
352
+ announceTimer = setTimeout(() => {
353
+ live.textContent = text;
354
+ }, 50);
355
+ },
356
+ action(action, message) {
357
+ const p = instance.props;
358
+ let prevented = false;
359
+ p.onItemActionClick?.({
360
+ action,
361
+ message,
362
+ preventDefault: () => {
363
+ prevented = true;
364
+ },
365
+ get defaultPrevented() {
366
+ return prevented;
367
+ },
368
+ });
369
+ if (prevented)
370
+ return;
371
+ if (action === 'copy')
372
+ void globalThis.navigator?.clipboard?.writeText(message.text).catch(() => { });
373
+ else if (action === 'reply') {
374
+ store.setView({ replyTo: message.id });
375
+ instance.focusComposer();
376
+ }
377
+ else if (action === 'pin')
378
+ instance.commit((prev) => prev.map((m) => (m.id === message.id ? { ...m, pinned: !m.pinned } : m)), 'pin');
379
+ else if (action === 'delete') {
380
+ if (store.getView().replyTo === message.id)
381
+ store.setView({ replyTo: null });
382
+ instance.commit((prev) => prev.filter((m) => m.id !== message.id), 'delete');
383
+ }
384
+ },
385
+ focusComposer() {
386
+ instance.composer?.focus();
387
+ },
388
+ typed() {
389
+ const p = instance.props;
390
+ if (!p.onTypingChange)
391
+ return;
392
+ if (!typing) {
393
+ typing = true;
394
+ p.onTypingChange(Object.freeze({ typing: true }));
395
+ }
396
+ if (typingTimer)
397
+ clearTimeout(typingTimer);
398
+ typingTimer = setTimeout(() => instance.stopTyping(), p.typingTimeout ?? 3000);
399
+ },
400
+ stopTyping() {
401
+ if (typingTimer)
402
+ clearTimeout(typingTimer);
403
+ typingTimer = null;
404
+ if (!typing)
405
+ return;
406
+ typing = false;
407
+ instance.props.onTypingChange?.(Object.freeze({ typing: false }));
408
+ },
409
+ };
410
+ return instance;
411
+ }
412
+ const rectTop = (el) => el.getBoundingClientRect().top;
413
+ /** Rebuilds the metrics when the id list changed, keeping measured heights by id. */
414
+ function syncMetrics(instance, geometry) {
415
+ const ids = instance.store.getIds();
416
+ if (ids === geometry.ids)
417
+ return;
418
+ const estimate = instance.props.estimatedItemHeight ?? 64;
419
+ geometry.ids = ids;
420
+ geometry.metrics = createVariableRowMetrics(ids.length, (i) => geometry.heights.get(ids[i]) ?? estimate);
421
+ }
422
+ /**
423
+ * Measures the mounted articles, sizes the spacers, restores the anchor (or
424
+ * stays at the bottom), reveals a requested message and recomputes the
425
+ * mounted window. Reads come before writes; runs in layout effects and
426
+ * observer callbacks, never during render.
427
+ */
428
+ function adjust(instance, geometry) {
429
+ const scroller = instance.scroller;
430
+ if (!scroller)
431
+ return;
432
+ const store = instance.store;
433
+ syncMetrics(instance, geometry);
434
+ const metrics = geometry.metrics;
435
+ const ids = geometry.ids;
436
+ const view = store.getView();
437
+ // Measure.
438
+ const articles = scroller.querySelectorAll('article[data-index]');
439
+ for (const a of articles) {
440
+ const id = a.getAttribute('data-id');
441
+ const h = a.getBoundingClientRect().height;
442
+ if (h > 0 && geometry.heights.get(id) !== h) {
443
+ geometry.heights.set(id, h);
444
+ const index = Number(a.getAttribute('data-index'));
445
+ if (ids[index] === id)
446
+ metrics.setHeight(index, h);
447
+ }
448
+ geometry.observer?.observe(a);
449
+ }
450
+ // Spacers stand in for the unmounted items.
451
+ const startSpacer = scroller.querySelector('[data-edge="start"]');
452
+ const endSpacer = scroller.querySelector('[data-edge="end"]');
453
+ const first = Math.min(view.first, ids.length);
454
+ const last = Math.min(view.last, ids.length);
455
+ if (startSpacer)
456
+ startSpacer.style.height = `${metrics.offsetOf(first)}px`;
457
+ if (endSpacer)
458
+ endSpacer.style.height = `${Math.max(0, metrics.totalHeight - metrics.offsetOf(last))}px`;
459
+ // Position. A scroll since the last write or observation wins over a pending stick.
460
+ if (scroller.scrollTop !== geometry.lastTop) {
461
+ geometry.stick = -scroller.scrollTop <= BOTTOM_SLACK;
462
+ geometry.anchor = null;
463
+ }
464
+ const top = rectTop(scroller);
465
+ const reveal = geometry.reveal;
466
+ const revealEl = reveal ? scroller.querySelector(`article[data-id="${cssEscape(reveal.id)}"]`) : null;
467
+ if (reveal && revealEl) {
468
+ geometry.reveal = null;
469
+ revealEl.scrollIntoView({ block: 'nearest' });
470
+ if (reveal.focus)
471
+ revealEl.focus({ preventScroll: true });
472
+ }
473
+ else if (geometry.stick) {
474
+ scroller.scrollTop = 0;
475
+ }
476
+ else if (geometry.anchor) {
477
+ const el = scroller.querySelector(`article[data-id="${cssEscape(geometry.anchor.id)}"]`);
478
+ if (el) {
479
+ const delta = rectTop(el) - top - geometry.anchor.top;
480
+ if (Math.abs(delta) >= 0.5)
481
+ scroller.scrollTop += delta;
482
+ }
483
+ }
484
+ geometry.lastTop = scroller.scrollTop;
485
+ updateWindow(instance, geometry);
486
+ }
487
+ const cssEscape = (value) => (typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(value) : value.replace(/["\\]/g, '\\$&'));
488
+ /** Recomputes the at-bottom flag, the anchor and the mounted window from the scroll position. */
489
+ function updateWindow(instance, geometry) {
490
+ const scroller = instance.scroller;
491
+ if (!scroller)
492
+ return;
493
+ const store = instance.store;
494
+ const startSpacer = scroller.querySelector('[data-edge="start"]');
495
+ if (!startSpacer)
496
+ return;
497
+ const sRect = scroller.getBoundingClientRect();
498
+ const distance = Math.max(0, -scroller.scrollTop);
499
+ const atBottom = distance <= BOTTOM_SLACK;
500
+ // Anchor: the first article whose bottom is below the scroller's top edge.
501
+ let anchor = null;
502
+ for (const a of scroller.querySelectorAll('article[data-index]')) {
503
+ const r = a.getBoundingClientRect();
504
+ if (r.bottom > sRect.top) {
505
+ anchor = { id: a.getAttribute('data-id'), top: r.top - sRect.top };
506
+ break;
507
+ }
508
+ }
509
+ geometry.anchor = anchor;
510
+ const y = sRect.top - startSpacer.getBoundingClientRect().top;
511
+ const range = computeRange(geometry.metrics, y, scroller.clientHeight || 1, OVERSCAN);
512
+ const view = store.getView();
513
+ const n = geometry.ids.length;
514
+ const slack = OVERSCAN >> 1;
515
+ const keep = view.last - view.first > 0 && range.start >= view.first + (view.first > 0 ? slack : 0) && range.end <= view.last - (view.last < n ? slack : 0) && view.last <= n;
516
+ store.setView({ atBottom, ...(atBottom ? { unread: 0 } : null), ...(keep ? null : { first: range.overscanStart, last: range.overscanEnd }) });
517
+ if (!atBottom)
518
+ geometry.stick = false;
519
+ // Load older history when the top is within one viewport.
520
+ const p = instance.props;
521
+ if (p.hasOlder && p.onLoadOlder && !view.loadingOlder && y < scroller.clientHeight) {
522
+ const result = p.onLoadOlder();
523
+ if (result && typeof result.then === 'function') {
524
+ store.setView({ loadingOlder: true });
525
+ void Promise.resolve(result)
526
+ .catch((error) => p.onError?.(error))
527
+ .finally(() => store.setView({ loadingOlder: false }));
528
+ }
529
+ }
530
+ }
531
+ /** Scroll and resize listeners of the feed (client only). */
532
+ function mountFeed(instance, geometry) {
533
+ const scroller = instance.scroller;
534
+ if (!scroller)
535
+ return () => { };
536
+ const win = scroller.ownerDocument.defaultView;
537
+ const schedule = () => {
538
+ if (geometry.frame || !win)
539
+ return;
540
+ geometry.frame = win.requestAnimationFrame(() => {
541
+ geometry.frame = 0;
542
+ adjust(instance, geometry);
543
+ });
544
+ };
545
+ const onScroll = () => {
546
+ // A user scroll away from the bottom wins over a pending stick-to-bottom adjust.
547
+ geometry.stick = -scroller.scrollTop <= BOTTOM_SLACK;
548
+ geometry.lastTop = scroller.scrollTop;
549
+ // The anchor is re-read after the scroll, never restored to its pre-scroll place.
550
+ geometry.anchor = null;
551
+ if (geometry.frame || !win)
552
+ return;
553
+ geometry.frame = win.requestAnimationFrame(() => {
554
+ geometry.frame = 0;
555
+ updateWindow(instance, geometry);
556
+ });
557
+ };
558
+ if (typeof ResizeObserver !== 'undefined') {
559
+ geometry.observer = new ResizeObserver(schedule);
560
+ geometry.observer.observe(scroller);
561
+ }
562
+ scroller.addEventListener('scroll', onScroll, { passive: true });
563
+ // A scroll of the server HTML before hydration is kept.
564
+ geometry.stick = -scroller.scrollTop <= BOTTOM_SLACK;
565
+ geometry.lastTop = scroller.scrollTop;
566
+ // Re-adjust whenever the mounted window changes.
567
+ let last = instance.store.getView();
568
+ const unsubscribe = instance.store.subscribe(() => {
569
+ const v = instance.store.getView();
570
+ if (v.first !== last.first || v.last !== last.last)
571
+ queueMicrotask(() => adjust(instance, geometry));
572
+ last = v;
573
+ });
574
+ adjust(instance, geometry);
575
+ return () => {
576
+ scroller.removeEventListener('scroll', onScroll);
577
+ geometry.observer?.disconnect();
578
+ geometry.observer = null;
579
+ if (geometry.frame && win)
580
+ win.cancelAnimationFrame(geometry.frame);
581
+ geometry.frame = 0;
582
+ unsubscribe();
583
+ instance.stop();
584
+ instance.stopTyping();
585
+ instance.store.dispose();
586
+ };
587
+ }
588
+ //# sourceMappingURL=Conversation.js.map