@tomny-dev/uzi 0.12.0 → 0.13.0-pr.108.359.1.db8e67d

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 (91) hide show
  1. package/dist/components/auth-form/AuthForm.d.ts +24 -0
  2. package/dist/components/auth-form/AuthForm.d.ts.map +1 -0
  3. package/dist/components/auth-form/AuthForm.test.d.ts +2 -0
  4. package/dist/components/auth-form/AuthForm.test.d.ts.map +1 -0
  5. package/dist/components/auth-pages/AuthPages.d.ts.map +1 -1
  6. package/dist/index.cjs +13 -9
  7. package/dist/index.d.ts +2 -0
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +11 -10
  10. package/dist/index63.js +15 -21
  11. package/dist/index63.js.map +1 -1
  12. package/dist/index64.cjs +21 -30
  13. package/dist/index64.cjs.map +1 -1
  14. package/dist/index64.js +51 -44
  15. package/dist/index64.js.map +1 -1
  16. package/dist/index65.cjs +52 -43
  17. package/dist/index65.cjs.map +1 -1
  18. package/dist/index65.js +14 -50
  19. package/dist/index65.js.map +1 -1
  20. package/dist/index66.cjs +15 -69
  21. package/dist/index66.cjs.map +1 -1
  22. package/dist/index66.js +25 -414
  23. package/dist/index66.js.map +1 -1
  24. package/dist/index67.cjs +25 -416
  25. package/dist/index67.cjs.map +1 -1
  26. package/dist/index67.js +56 -58
  27. package/dist/index67.js.map +1 -1
  28. package/dist/index68.cjs +82 -85
  29. package/dist/index68.cjs.map +1 -1
  30. package/dist/index68.js +420 -226
  31. package/dist/index68.js.map +1 -1
  32. package/dist/index69.cjs +421 -225
  33. package/dist/index69.cjs.map +1 -1
  34. package/dist/index69.js +58 -42
  35. package/dist/index69.js.map +1 -1
  36. package/dist/index70.cjs +85 -61
  37. package/dist/index70.cjs.map +1 -1
  38. package/dist/index70.js +236 -76
  39. package/dist/index70.js.map +1 -1
  40. package/dist/index71.cjs +235 -75
  41. package/dist/index71.cjs.map +1 -1
  42. package/dist/index71.js +42 -20
  43. package/dist/index71.js.map +1 -1
  44. package/dist/index72.cjs +60 -27
  45. package/dist/index72.cjs.map +1 -1
  46. package/dist/index72.js +73 -88
  47. package/dist/index72.js.map +1 -1
  48. package/dist/index73.cjs +73 -90
  49. package/dist/index73.cjs.map +1 -1
  50. package/dist/index73.js +17 -15
  51. package/dist/index73.js.map +1 -1
  52. package/dist/index74.cjs +22 -19
  53. package/dist/index74.cjs.map +1 -1
  54. package/dist/index74.js +85 -143
  55. package/dist/index74.js.map +1 -1
  56. package/dist/index75.cjs +87 -143
  57. package/dist/index75.cjs.map +1 -1
  58. package/dist/index75.js +19 -91
  59. package/dist/index75.js.map +1 -1
  60. package/dist/index76.cjs +27 -135
  61. package/dist/index76.cjs.map +1 -1
  62. package/dist/index76.js +140 -673
  63. package/dist/index76.js.map +1 -1
  64. package/dist/index77.cjs +140 -673
  65. package/dist/index77.cjs.map +1 -1
  66. package/dist/index77.js +91 -31
  67. package/dist/index77.js.map +1 -1
  68. package/dist/index78.cjs +135 -45
  69. package/dist/index78.cjs.map +1 -1
  70. package/dist/index78.js +667 -206
  71. package/dist/index78.js.map +1 -1
  72. package/dist/index79.cjs +667 -204
  73. package/dist/index79.cjs.map +1 -1
  74. package/dist/index79.js +31 -15
  75. package/dist/index79.js.map +1 -1
  76. package/dist/index80.cjs +45 -21
  77. package/dist/index80.cjs.map +1 -1
  78. package/dist/index80.js +224 -29
  79. package/dist/index80.js.map +1 -1
  80. package/dist/index81.cjs +224 -30
  81. package/dist/index81.cjs.map +1 -1
  82. package/dist/index81.js +19 -0
  83. package/dist/index81.js.map +1 -0
  84. package/dist/index82.cjs +25 -0
  85. package/dist/index82.cjs.map +1 -0
  86. package/dist/index82.js +36 -0
  87. package/dist/index82.js.map +1 -0
  88. package/dist/index83.cjs +37 -0
  89. package/dist/index83.cjs.map +1 -0
  90. package/dist/style.css +13 -3
  91. package/package.json +1 -1
package/dist/index78.js CHANGED
@@ -1,231 +1,692 @@
1
1
  "use client";
2
- import ai_chat_dock_module_default from "./index77.js";
3
- import { useEffect, useId, useRef, useState } from "react";
4
- import { jsx, jsxs } from "react/jsx-runtime";
5
- //#region src/components/ai-chat/AIChatDock.tsx
6
- /**
7
- * Shared chat navigation chrome. Children remain mounted while closed to retain
8
- * the consumer's active AI SDK conversation, pending approvals and attachments.
9
- * The dock never creates a second chat runtime or reads application messages.
10
- * Desktop is deliberately non-modal: Tab can move back into the page.
11
- * On mobile the full-screen modal sheet traps sequential keyboard focus.
12
- */
13
- function AIChatDock({ title, description, launcherLabel, showLauncher = true, panelId: controlledPanelId, externalLauncherId, children, open, defaultOpen = false, onOpenChange, expanded, defaultExpanded = false, onExpandedChange, className }) {
14
- const autoId = useId();
15
- const panelId = controlledPanelId ?? `uzi-ai-dock-${autoId}`;
16
- const [internalOpen, setInternalOpen] = useState(defaultOpen);
17
- const [internalExpanded, setInternalExpanded] = useState(defaultExpanded);
18
- const isOpen = open ?? internalOpen;
19
- const isExpanded = expanded ?? internalExpanded;
20
- const [mobile, setMobile] = useState(false);
21
- const launcherRef = useRef(null);
22
- const panelRef = useRef(null);
23
- const openerRef = useRef(null);
24
- const wasOpen = useRef(false);
25
- const changeOpen = (next) => {
26
- if (open === void 0) setInternalOpen(next);
27
- onOpenChange?.(next);
28
- };
29
- const changeExpanded = (next) => {
30
- if (expanded === void 0) setInternalExpanded(next);
31
- onExpandedChange?.(next);
32
- if (next && !isOpen) changeOpen(true);
33
- };
34
- useEffect(() => {
35
- if (typeof window.matchMedia !== "function") return;
36
- const media = window.matchMedia("(max-width: 640px)");
37
- const update = () => setMobile(media.matches);
38
- update();
39
- media.addEventListener("change", update);
40
- return () => media.removeEventListener("change", update);
41
- }, []);
2
+ import ai_chat_module_default from "./index77.js";
3
+ import { useEffect, useMemo, useRef, useState } from "react";
4
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
+ import { AuiConfig, AuiProvider, ThreadPrimitive } from "@assistant-ui/react";
6
+ import { AISDKChat, AssistantChatTransport, useAISDKChat } from "@assistant-ui/ai-sdk";
7
+ //#region src/components/ai-chat/AIChat.tsx
8
+ function isRecord(value) {
9
+ return typeof value === "object" && value !== null && !Array.isArray(value);
10
+ }
11
+ function asString(value) {
12
+ return typeof value === "string" ? value : void 0;
13
+ }
14
+ function safeHttpUrl(value) {
15
+ const url = asString(value);
16
+ return url && /^https?:\/\//i.test(url) ? url : void 0;
17
+ }
18
+ function AIChatMessageBubble({ role, label, children, className }) {
19
+ return /* @__PURE__ */ jsxs("div", {
20
+ className: [
21
+ ai_chat_module_default.messageBubble,
22
+ role === "user" ? ai_chat_module_default.userMessage : ai_chat_module_default.assistantMessage,
23
+ className
24
+ ].filter(Boolean).join(" "),
25
+ "data-role": role,
26
+ children: [label && /* @__PURE__ */ jsx("span", {
27
+ className: ai_chat_module_default.messageLabel,
28
+ children: label
29
+ }), children]
30
+ });
31
+ }
32
+ function DefaultMessageRenderer({ message, renderMessagePart }) {
33
+ return /* @__PURE__ */ jsx(AIChatMessageBubble, {
34
+ role: message.role,
35
+ children: message.parts.map((part, index) => /* @__PURE__ */ jsx("div", { children: isRecord(part) ? renderMessagePart(part, index) : null }, isRecord(part) && typeof part.id === "string" ? part.id : index))
36
+ });
37
+ }
38
+ function DefaultReasoningRenderer({ children, title = "Reasoning" }) {
39
+ return /* @__PURE__ */ jsxs("details", {
40
+ className: ai_chat_module_default.reasoning,
41
+ children: [/* @__PURE__ */ jsx("summary", {
42
+ className: ai_chat_module_default.reasoningSummary,
43
+ children: title
44
+ }), /* @__PURE__ */ jsx("p", {
45
+ className: ai_chat_module_default.reasoningText,
46
+ children
47
+ })]
48
+ });
49
+ }
50
+ function DefaultSourceRenderer({ sources, renderSource }) {
51
+ return /* @__PURE__ */ jsxs("div", {
52
+ className: ai_chat_module_default.sources,
53
+ children: [/* @__PURE__ */ jsx("span", {
54
+ className: ai_chat_module_default.sourcesLabel,
55
+ children: "Sources"
56
+ }), /* @__PURE__ */ jsx("ul", { children: sources.map((source, index) => /* @__PURE__ */ jsx("li", { children: renderSource(source, index) }, source.id)) })]
57
+ });
58
+ }
59
+ function DefaultDataRenderer({ data, renderDataItem }) {
60
+ return /* @__PURE__ */ jsx("div", {
61
+ className: ai_chat_module_default.data,
62
+ children: data.map((item, index) => /* @__PURE__ */ jsx("div", { children: renderDataItem(item, index) }, index))
63
+ });
64
+ }
65
+ function DefaultErrorRenderer({ error, onRetry, onClear }) {
66
+ return /* @__PURE__ */ jsxs("div", {
67
+ className: ai_chat_module_default.error,
68
+ role: "alert",
69
+ children: [/* @__PURE__ */ jsx("p", { children: error.message }), /* @__PURE__ */ jsxs("div", {
70
+ className: ai_chat_module_default.errorActions,
71
+ children: [/* @__PURE__ */ jsx("button", {
72
+ type: "button",
73
+ onClick: onRetry,
74
+ children: "Retry response"
75
+ }), /* @__PURE__ */ jsx("button", {
76
+ type: "button",
77
+ onClick: onClear,
78
+ children: "Start new chat"
79
+ })]
80
+ })]
81
+ });
82
+ }
83
+ function renderPart(part, index, components, onToolApproval, pendingApprovalId) {
84
+ const type = asString(part.type) ?? "";
85
+ if (type === "step-start") return null;
86
+ if (type === "text") return /* @__PURE__ */ jsx("span", {
87
+ className: ai_chat_module_default.textPart,
88
+ children: asString(part.text) ?? ""
89
+ });
90
+ if (type === "reasoning") return /* @__PURE__ */ jsx(components?.ReasoningRenderer ?? DefaultReasoningRenderer, { children: asString(part.text) ?? "" });
91
+ if (type === "source-url" || type === "source-document") return /* @__PURE__ */ jsx(components?.SourceRenderer ?? DefaultSourceRenderer, {
92
+ sources: [{
93
+ id: asString(part.sourceId) ?? asString(part.id) ?? `source-${index}`,
94
+ title: asString(part.title) ?? asString(part.filename),
95
+ url: safeHttpUrl(part.url)
96
+ }],
97
+ renderSource: (item) => item.url ? /* @__PURE__ */ jsx("a", {
98
+ href: item.url,
99
+ target: "_blank",
100
+ rel: "noopener noreferrer",
101
+ children: item.title ?? item.url
102
+ }) : /* @__PURE__ */ jsx("span", { children: item.title ?? item.id })
103
+ });
104
+ if (type.startsWith("data-")) return /* @__PURE__ */ jsx(components?.DataRenderer ?? DefaultDataRenderer, {
105
+ data: [part],
106
+ renderDataItem: (item) => /* @__PURE__ */ jsx("pre", {
107
+ className: ai_chat_module_default.structuredData,
108
+ children: JSON.stringify(item.data ?? item, null, 2)
109
+ })
110
+ });
111
+ if (type.startsWith("tool-") || type === "dynamic-tool") {
112
+ const name = asString(part.toolName) ?? type.replace(/^tool-/, "");
113
+ const approval = isRecord(part.approval) ? asString(part.approval.id) : void 0;
114
+ const approvalId = part.state === "approval-requested" ? approval : void 0;
115
+ const controlsDisabled = pendingApprovalId !== null && pendingApprovalId !== void 0;
116
+ const ToolRenderer = components?.ToolRenderer;
117
+ const props = {
118
+ part,
119
+ name,
120
+ approvalId,
121
+ approvalPending: controlsDisabled,
122
+ ...approvalId && onToolApproval ? {
123
+ onApprove: () => {
124
+ if (!controlsDisabled) onToolApproval(approvalId, true);
125
+ },
126
+ onDeny: () => {
127
+ if (!controlsDisabled) onToolApproval(approvalId, false);
128
+ }
129
+ } : {}
130
+ };
131
+ if (ToolRenderer) return /* @__PURE__ */ jsx(ToolRenderer, { ...props });
132
+ return /* @__PURE__ */ jsxs("div", {
133
+ className: ai_chat_module_default.toolPart,
134
+ children: [/* @__PURE__ */ jsxs("details", { children: [/* @__PURE__ */ jsx("summary", { children: name }), /* @__PURE__ */ jsx("pre", {
135
+ className: ai_chat_module_default.structuredData,
136
+ children: JSON.stringify(part.output ?? part.input ?? part, null, 2)
137
+ })] }), approvalId && /* @__PURE__ */ jsx("div", {
138
+ className: ai_chat_module_default.approvalActions,
139
+ "aria-label": `Approval required for ${name}`,
140
+ children: props.onApprove && props.onDeny ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("button", {
141
+ type: "button",
142
+ disabled: controlsDisabled,
143
+ onClick: props.onApprove,
144
+ children: "Approve"
145
+ }), /* @__PURE__ */ jsx("button", {
146
+ type: "button",
147
+ disabled: controlsDisabled,
148
+ onClick: props.onDeny,
149
+ children: "Deny"
150
+ })] }) : /* @__PURE__ */ jsx("span", { children: "Approval required in application" })
151
+ })]
152
+ });
153
+ }
154
+ if (type === "file" || type === "image") {
155
+ const url = safeHttpUrl(part.url);
156
+ return url ? /* @__PURE__ */ jsx("a", {
157
+ href: url,
158
+ target: "_blank",
159
+ rel: "noopener noreferrer",
160
+ children: asString(part.filename) ?? "View attachment"
161
+ }) : /* @__PURE__ */ jsx("span", { children: "Attachment" });
162
+ }
163
+ return /* @__PURE__ */ jsx("pre", {
164
+ className: ai_chat_module_default.structuredData,
165
+ children: JSON.stringify(part, null, 2)
166
+ });
167
+ }
168
+ var DEFAULT_MESSAGE_LIMIT = 8;
169
+ function AIChat({ api, scope, scopeLabel, fetch: requestFetch, headers, credentials, prepareSendMessagesRequest, sessionKey, messageLimit = DEFAULT_MESSAGE_LIMIT, inputPlaceholder = "Ask a question...", inputAriaLabel = "Message", inputMaxLength = 2e3, components, toolbarActions, attachments, history, sendAutomaticallyWhen, onClose, className, style }) {
170
+ const [session, setSession] = useState(0);
171
+ const transport = useMemo(() => new AssistantChatTransport({
172
+ api,
173
+ ...scope ? { body: { scope } } : {},
174
+ ...requestFetch ? { fetch: requestFetch } : {},
175
+ ...headers ? { headers } : {},
176
+ ...credentials ? { credentials } : {},
177
+ ...prepareSendMessagesRequest ? { prepareSendMessagesRequest } : {}
178
+ }), [
179
+ api,
180
+ scope,
181
+ requestFetch,
182
+ headers,
183
+ credentials,
184
+ prepareSendMessagesRequest
185
+ ]);
186
+ const config = useMemo(() => AuiConfig({ threads: AISDKChat({
187
+ transport,
188
+ ...sendAutomaticallyWhen ? { sendAutomaticallyWhen } : {}
189
+ }) }), [
190
+ transport,
191
+ session,
192
+ sendAutomaticallyWhen
193
+ ]);
194
+ return /* @__PURE__ */ jsxs("div", {
195
+ className: [ai_chat_module_default.container, className].filter(Boolean).join(" "),
196
+ style,
197
+ children: [
198
+ scopeLabel && /* @__PURE__ */ jsxs("div", {
199
+ className: ai_chat_module_default.scope,
200
+ children: [/* @__PURE__ */ jsx("span", {
201
+ className: ai_chat_module_default.scopeLabel,
202
+ children: "Current scope"
203
+ }), /* @__PURE__ */ jsx("strong", { children: scopeLabel })]
204
+ }),
205
+ onClose && /* @__PURE__ */ jsx("button", {
206
+ className: ai_chat_module_default.closeBtn,
207
+ type: "button",
208
+ onClick: onClose,
209
+ "aria-label": "Close chat",
210
+ children: "✕"
211
+ }),
212
+ /* @__PURE__ */ jsx(AuiProvider, {
213
+ config,
214
+ children: /* @__PURE__ */ jsx(ThreadPrimitive.Root, {
215
+ className: ai_chat_module_default.thread,
216
+ children: /* @__PURE__ */ jsx(ChatViewport, {
217
+ messageLimit: Number.isFinite(messageLimit) ? Math.max(1, Math.floor(messageLimit)) : DEFAULT_MESSAGE_LIMIT,
218
+ inputPlaceholder,
219
+ inputAriaLabel,
220
+ inputMaxLength,
221
+ components,
222
+ toolbarActions,
223
+ attachmentOptions: attachments,
224
+ history,
225
+ onNewChat: () => setSession((previous) => previous + 1)
226
+ })
227
+ })
228
+ }, JSON.stringify([
229
+ api,
230
+ scope,
231
+ sessionKey,
232
+ session
233
+ ]))
234
+ ]
235
+ });
236
+ }
237
+ function ChatViewport({ messageLimit, inputPlaceholder, inputAriaLabel, inputMaxLength, components, toolbarActions, attachmentOptions, history, onNewChat }) {
238
+ const chat = useAISDKChat();
239
+ const [draft, setDraft] = useState("");
240
+ const [selectedFiles, setSelectedFiles] = useState([]);
241
+ const [attachmentError, setAttachmentError] = useState(null);
242
+ const [attachmentPreviews, setAttachmentPreviews] = useState([]);
243
+ const [hydrated, setHydrated] = useState(!history);
244
+ const expectedRestoredId = useRef(null);
245
+ const saveQueue = useRef(Promise.resolve());
246
+ const [approvalBusy, setApprovalBusy] = useState(false);
42
247
  useEffect(() => {
43
- if (isOpen && !wasOpen.current) {
44
- openerRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
45
- panelRef.current?.focus();
46
- } else if (!isOpen && wasOpen.current) {
47
- const previous = openerRef.current;
48
- if (previous?.isConnected && previous !== panelRef.current) previous.focus();
49
- else if (externalLauncherId) document.getElementById(externalLauncherId)?.focus();
50
- else launcherRef.current?.focus();
51
- }
52
- wasOpen.current = isOpen;
53
- }, [isOpen, externalLauncherId]);
248
+ const urls = selectedFiles.map((file) => file.type.startsWith("image/") && typeof URL.createObjectURL === "function" ? URL.createObjectURL(file) : "");
249
+ setAttachmentPreviews(urls);
250
+ return () => urls.forEach((url) => {
251
+ if (url && typeof URL.revokeObjectURL === "function") URL.revokeObjectURL(url);
252
+ });
253
+ }, [selectedFiles]);
254
+ const messages = chat?.messages ?? [];
255
+ const status = chat?.status ?? "ready";
256
+ const isBusy = status === "submitted" || status === "streaming";
257
+ const historyFull = messages.filter((message) => message.role === "user").length >= messageLimit;
258
+ const reportHistoryError = (operation, error) => {
259
+ if (history?.onError) history.onError(operation, error);
260
+ else console.warn(`[Uzi AIChat] History ${operation} failed`);
261
+ };
54
262
  useEffect(() => {
55
- if (!isOpen || !mobile) return;
56
- const previous = document.body.style.overflow;
57
- document.body.style.overflow = "hidden";
263
+ if (!history) return;
264
+ let active = true;
265
+ Promise.resolve().then(() => history.load()).then((restored) => {
266
+ if (!active) return;
267
+ if (Array.isArray(restored)) {
268
+ const valid = restored.filter((message) => typeof message?.id === "string" && (message.role === "user" || message.role === "assistant") && Array.isArray(message.parts));
269
+ expectedRestoredId.current = valid.length ? valid[0].id : null;
270
+ if (valid.length) chat?.setMessages(valid);
271
+ }
272
+ setHydrated(true);
273
+ }).catch((error) => {
274
+ if (active) {
275
+ reportHistoryError("load", error);
276
+ setHydrated(true);
277
+ }
278
+ });
58
279
  return () => {
59
- document.body.style.overflow = previous;
280
+ active = false;
60
281
  };
61
- }, [isOpen, mobile]);
282
+ }, [chat?.setMessages, history]);
62
283
  useEffect(() => {
63
- if (!isOpen) return;
64
- const keydown = (event) => {
65
- if (event.key === "Escape") {
66
- event.preventDefault();
67
- changeOpen(false);
68
- return;
69
- }
70
- if (event.key !== "Tab" || !mobile) return;
71
- const focusable = Array.from(panelRef.current?.querySelectorAll("a[href], button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex=\"-1\"])") ?? []).filter((item) => item.tabIndex >= 0 && item.getClientRects().length > 0);
72
- if (!focusable.length) {
73
- event.preventDefault();
74
- panelRef.current?.focus();
284
+ if (!history || !hydrated || isBusy) return;
285
+ const snapshot = messages.filter((message) => message.role === "user" || message.role === "assistant").map((message) => ({
286
+ id: message.id,
287
+ role: message.role,
288
+ parts: message.parts,
289
+ ...isRecord(message.metadata) ? { metadata: message.metadata } : {}
290
+ }));
291
+ if (expectedRestoredId.current) {
292
+ if (!snapshot.some((message) => message.id === expectedRestoredId.current)) return;
293
+ expectedRestoredId.current = null;
294
+ }
295
+ saveQueue.current = saveQueue.current.then(() => history.save(snapshot), () => history.save(snapshot)).then(() => {}, (error) => {
296
+ reportHistoryError("save", error);
297
+ });
298
+ }, [
299
+ history,
300
+ hydrated,
301
+ isBusy,
302
+ messages
303
+ ]);
304
+ const handleSelectedFiles = (files) => {
305
+ if (!attachmentOptions) return;
306
+ const selected = Array.from(files);
307
+ if (selected.length + selectedFiles.length > (attachmentOptions.maxFiles ?? 3)) {
308
+ setAttachmentError("Too many attachments.");
309
+ return;
310
+ }
311
+ if (selected.some((file) => file.size > (attachmentOptions.maxBytesPerFile ?? 5 * 1024 * 1024))) {
312
+ setAttachmentError("An attachment exceeds the size limit.");
313
+ return;
314
+ }
315
+ const allowedTypes = attachmentOptions.accept.split(",").map((item) => item.trim());
316
+ if (selected.some((file) => !allowedTypes.some((allow) => allow === file.type || allow.endsWith("/*") && file.type.startsWith(allow.slice(0, -1))))) {
317
+ setAttachmentError("Unsupported attachment type.");
318
+ return;
319
+ }
320
+ setAttachmentError(null);
321
+ setSelectedFiles((existing) => [...existing, ...selected]);
322
+ };
323
+ const handleSubmit = () => {
324
+ const text = draft.trim();
325
+ if (!chat || !text && selectedFiles.length === 0 || isBusy || historyFull || chat.error || !hydrated || approvalBusy) return;
326
+ const files = selectedFiles.length ? new DataTransfer() : null;
327
+ selectedFiles.forEach((file) => files?.items.add(file));
328
+ const previousDraft = draft;
329
+ const previousFiles = selectedFiles;
330
+ setDraft("");
331
+ setSelectedFiles([]);
332
+ setAttachmentError(null);
333
+ Promise.resolve(chat.sendMessage({
334
+ text,
335
+ ...files ? { files: files.files } : {}
336
+ })).catch(() => {
337
+ setDraft((current) => current || previousDraft);
338
+ setSelectedFiles((current) => current.length ? current : previousFiles);
339
+ });
340
+ };
341
+ const handleNewChat = () => {
342
+ (async () => {
343
+ await chat?.stop();
344
+ if (history) try {
345
+ await saveQueue.current;
346
+ await history.clear();
347
+ } catch (error) {
348
+ reportHistoryError("clear", error);
75
349
  return;
76
350
  }
77
- const first = focusable[0], last = focusable[focusable.length - 1];
78
- if (event.shiftKey && (document.activeElement === first || !panelRef.current?.contains(document.activeElement))) {
79
- event.preventDefault();
80
- last?.focus();
81
- } else if (!event.shiftKey && (document.activeElement === last || !panelRef.current?.contains(document.activeElement))) {
82
- event.preventDefault();
83
- first?.focus();
351
+ onNewChat();
352
+ })();
353
+ };
354
+ const handleRetry = () => {
355
+ if (!chat || isBusy) return;
356
+ chat.clearError();
357
+ chat.regenerate();
358
+ };
359
+ return /* @__PURE__ */ jsx(AIChatView, {
360
+ messages: messages.filter((message) => message.role === "user" || message.role === "assistant").map((message) => ({
361
+ id: message.id,
362
+ role: message.role,
363
+ parts: message.parts,
364
+ ...isRecord(message.metadata) ? { metadata: message.metadata } : {}
365
+ })),
366
+ status,
367
+ error: chat?.error,
368
+ draft,
369
+ onDraftChange: setDraft,
370
+ onSend: handleSubmit,
371
+ onStop: () => {
372
+ chat?.stop();
373
+ },
374
+ onRetry: handleRetry,
375
+ onNewChat: handleNewChat,
376
+ toolbarActions,
377
+ messageLimit,
378
+ attachments: selectedFiles.map((file, index) => ({
379
+ name: file.name,
380
+ size: file.size,
381
+ ...attachmentPreviews[index] ? { previewUrl: attachmentPreviews[index] } : {}
382
+ })),
383
+ onSelectAttachments: attachmentOptions ? handleSelectedFiles : void 0,
384
+ onRemoveAttachment: attachmentOptions ? (index) => setSelectedFiles((files) => files.filter((_, i) => i !== index)) : void 0,
385
+ attachmentAccept: attachmentOptions?.accept,
386
+ attachmentError,
387
+ onToolApproval: chat ? async (id, approved) => {
388
+ if (approvalBusy) return;
389
+ setApprovalBusy(true);
390
+ try {
391
+ await chat.addToolApprovalResponse({
392
+ id,
393
+ approved,
394
+ ...!approved ? { reason: "User denied approval" } : {}
395
+ });
396
+ } finally {
397
+ setApprovalBusy(false);
84
398
  }
85
- };
86
- document.addEventListener("keydown", keydown);
87
- return () => document.removeEventListener("keydown", keydown);
88
- }, [
89
- isOpen,
90
- mobile,
91
- onOpenChange,
92
- open
93
- ]);
399
+ } : void 0,
400
+ inputPlaceholder,
401
+ inputAriaLabel,
402
+ inputMaxLength,
403
+ components
404
+ });
405
+ }
406
+ /**
407
+ * Controlled chat presentation for apps with their own AI SDK/assistant-ui
408
+ * runtime. It does not create providers, transports or chat state. Callbacks
409
+ * are the only way messages/actions leave the view.
410
+ */
411
+ function AIChatView({ messages, status = "ready", error, draft = "", onDraftChange, onSend, onStop, onRetry, onNewChat, messageLimit, inputPlaceholder = "Ask a question...", inputAriaLabel = "Message", inputMaxLength = 2e3, components, attachments, onSelectAttachments, onRemoveAttachment, attachmentAccept, attachmentError, onToolApproval, toolbarActions, header, composerLeading, composerTrailing, composer, emptyState, className, style }) {
412
+ const viewportRef = useRef(null);
413
+ const pinnedToBottom = useRef(true);
414
+ const fileInputRef = useRef(null);
415
+ const approvalRef = useRef(null);
416
+ const [pendingApprovalId, setPendingApprovalId] = useState(null);
417
+ const [approvalError, setApprovalError] = useState(null);
418
+ const respondToApproval = async (id, approved) => {
419
+ if (!onToolApproval || approvalRef.current) return;
420
+ approvalRef.current = id;
421
+ setPendingApprovalId(id);
422
+ setApprovalError(null);
423
+ try {
424
+ await onToolApproval(id, approved);
425
+ } catch {
426
+ setApprovalError("Could not submit approval. Please try again.");
427
+ } finally {
428
+ approvalRef.current = null;
429
+ setPendingApprovalId(null);
430
+ }
431
+ };
432
+ const isBusy = status === "submitted" || status === "streaming";
433
+ const limit = messageLimit != null && Number.isFinite(messageLimit) ? Math.max(1, Math.floor(messageLimit)) : null;
434
+ const historyFull = limit !== null && messages.filter((message) => message.role === "user").length >= limit;
435
+ const MessageRenderer = components?.MessageRenderer ?? DefaultMessageRenderer;
436
+ const ErrorRenderer = components?.ErrorRenderer ?? DefaultErrorRenderer;
437
+ useEffect(() => {
438
+ const viewport = viewportRef.current;
439
+ if (viewport && pinnedToBottom.current) viewport.scrollTop = viewport.scrollHeight;
440
+ });
441
+ const handleKeyDown = (event) => {
442
+ if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {
443
+ event.preventDefault();
444
+ if (!isBusy && !historyFull && !error && (draft.trim() || (attachments?.length ?? 0) > 0)) onSend?.();
445
+ }
446
+ };
447
+ const handleFormSubmit = (event) => {
448
+ event.preventDefault();
449
+ if (!isBusy && !historyFull && !error && (draft.trim() || (attachments?.length ?? 0) > 0)) onSend?.();
450
+ };
94
451
  return /* @__PURE__ */ jsxs("div", {
95
- className: [ai_chat_dock_module_default.dock, className].filter(Boolean).join(" "),
452
+ className: [ai_chat_module_default.thread, className].filter(Boolean).join(" "),
453
+ style,
96
454
  children: [
97
- showLauncher && !isOpen && /* @__PURE__ */ jsxs("button", {
98
- ref: launcherRef,
99
- type: "button",
100
- className: ai_chat_dock_module_default.launcher,
101
- "aria-controls": panelId,
102
- "aria-expanded": false,
103
- "aria-label": launcherLabel ?? `Open ${title}`,
104
- onClick: () => changeOpen(true),
105
- children: [/* @__PURE__ */ jsx("svg", {
106
- "aria-hidden": "true",
107
- width: "23",
108
- height: "23",
109
- viewBox: "0 0 24 24",
110
- fill: "none",
111
- stroke: "currentColor",
112
- strokeWidth: "1.8",
113
- strokeLinecap: "round",
114
- strokeLinejoin: "round",
115
- children: /* @__PURE__ */ jsx("path", { d: "M21 11.5a8.5 8.5 0 0 1-8.5 8.5 9.1 9.1 0 0 1-4-.9L3 21l1.9-5.5a9.1 9.1 0 0 1-.9-4 8.5 8.5 0 0 1 8.5-8.5h.5A8.5 8.5 0 0 1 21 11.5Z" })
116
- }), /* @__PURE__ */ jsx("span", {
117
- className: ai_chat_dock_module_default.launcherText,
118
- children: title
455
+ header,
456
+ (messages.length > 0 || toolbarActions) && (onNewChat || toolbarActions) && /* @__PURE__ */ jsxs("div", {
457
+ className: ai_chat_module_default.chatToolbar,
458
+ role: "toolbar",
459
+ "aria-label": "Conversation actions",
460
+ children: [/* @__PURE__ */ jsx("div", {
461
+ className: ai_chat_module_default.chatToolbarExtras,
462
+ children: toolbarActions
463
+ }), onNewChat && messages.length > 0 && /* @__PURE__ */ jsx("button", {
464
+ type: "button",
465
+ className: ai_chat_module_default.newChatButton,
466
+ onClick: onNewChat,
467
+ "aria-label": "New chat",
468
+ title: "New chat",
469
+ children: /* @__PURE__ */ jsxs("svg", {
470
+ "aria-hidden": "true",
471
+ width: "18",
472
+ height: "18",
473
+ viewBox: "0 0 24 24",
474
+ fill: "none",
475
+ stroke: "currentColor",
476
+ strokeWidth: "1.8",
477
+ strokeLinecap: "round",
478
+ strokeLinejoin: "round",
479
+ children: [/* @__PURE__ */ jsx("path", { d: "M12 5H6a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2v-6" }), /* @__PURE__ */ jsx("path", {
480
+ d: "m15 5 4 4M13 11l7-7a2.12 2.12 0 0 1 3 3l-7 7-4 1 1-4Z",
481
+ transform: "translate(-2 -2)"
482
+ })]
483
+ })
119
484
  })]
120
485
  }),
121
- isOpen && mobile && /* @__PURE__ */ jsx("div", {
122
- className: ai_chat_dock_module_default.backdrop,
123
- "aria-hidden": "true",
124
- onClick: () => changeOpen(false)
486
+ /* @__PURE__ */ jsx("div", {
487
+ ref: viewportRef,
488
+ className: ai_chat_module_default.viewport,
489
+ onScroll: (event) => {
490
+ const viewport = event.currentTarget;
491
+ pinnedToBottom.current = viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight < 80;
492
+ },
493
+ children: /* @__PURE__ */ jsxs("div", {
494
+ className: ai_chat_module_default.messageList,
495
+ role: "log",
496
+ "aria-label": "Chat history",
497
+ "aria-live": "polite",
498
+ children: [
499
+ messages.length === 0 && /* @__PURE__ */ jsx("div", {
500
+ className: ai_chat_module_default.emptyState,
501
+ children: emptyState ?? /* @__PURE__ */ jsx("p", { children: "Start a conversation" })
502
+ }),
503
+ messages.map((message) => /* @__PURE__ */ jsx(MessageRenderer, {
504
+ message,
505
+ renderMessagePart: (part, index) => renderPart(part, index, components, onToolApproval ? respondToApproval : void 0, pendingApprovalId),
506
+ onToolApproval: onToolApproval ? respondToApproval : void 0
507
+ }, message.id)),
508
+ isBusy && /* @__PURE__ */ jsx("p", {
509
+ className: ai_chat_module_default.status,
510
+ children: "Thinking..."
511
+ })
512
+ ]
513
+ })
125
514
  }),
126
- /* @__PURE__ */ jsxs("section", {
127
- ref: panelRef,
128
- id: panelId,
129
- role: "dialog",
130
- "aria-modal": mobile && isOpen,
131
- "aria-label": title,
132
- tabIndex: -1,
133
- className: ai_chat_dock_module_default.panel,
134
- "data-expanded": isExpanded,
135
- hidden: !isOpen,
136
- children: [/* @__PURE__ */ jsxs("header", {
137
- className: ai_chat_dock_module_default.header,
138
- children: [/* @__PURE__ */ jsxs("div", {
139
- className: ai_chat_dock_module_default.identity,
140
- children: [/* @__PURE__ */ jsx("div", {
141
- className: ai_chat_dock_module_default.avatar,
142
- "aria-hidden": "true",
143
- children: /* @__PURE__ */ jsxs("svg", {
144
- width: "18",
145
- height: "18",
146
- viewBox: "0 0 24 24",
147
- fill: "none",
148
- stroke: "currentColor",
149
- strokeWidth: "1.8",
150
- strokeLinecap: "round",
151
- strokeLinejoin: "round",
152
- children: [/* @__PURE__ */ jsx("rect", {
153
- x: "4",
154
- y: "6",
155
- width: "16",
156
- height: "14",
157
- rx: "4"
158
- }), /* @__PURE__ */ jsx("path", { d: "M12 3v3M9 13h.01M15 13h.01M9 17h6" })]
159
- })
160
- }), /* @__PURE__ */ jsxs("div", {
161
- className: ai_chat_dock_module_default.titles,
162
- children: [/* @__PURE__ */ jsx("strong", {
163
- className: ai_chat_dock_module_default.title,
164
- children: title
165
- }), description && /* @__PURE__ */ jsx("span", {
166
- className: ai_chat_dock_module_default.description,
167
- children: description
515
+ /* @__PURE__ */ jsxs("div", {
516
+ className: ai_chat_module_default.footer,
517
+ children: [
518
+ approvalError && /* @__PURE__ */ jsx("p", {
519
+ role: "alert",
520
+ className: ai_chat_module_default.attachmentError,
521
+ children: approvalError
522
+ }),
523
+ attachmentError && /* @__PURE__ */ jsx("p", {
524
+ role: "alert",
525
+ className: ai_chat_module_default.attachmentError,
526
+ children: attachmentError
527
+ }),
528
+ error && (onRetry && onNewChat ? /* @__PURE__ */ jsx(ErrorRenderer, {
529
+ error,
530
+ onRetry,
531
+ onClear: onNewChat
532
+ }) : /* @__PURE__ */ jsxs("div", {
533
+ className: ai_chat_module_default.error,
534
+ role: "alert",
535
+ children: [/* @__PURE__ */ jsx("p", { children: error.message }), (onRetry || onNewChat) && /* @__PURE__ */ jsxs("div", {
536
+ className: ai_chat_module_default.errorActions,
537
+ children: [onRetry && /* @__PURE__ */ jsx("button", {
538
+ type: "button",
539
+ onClick: onRetry,
540
+ children: "Retry response"
541
+ }), onNewChat && /* @__PURE__ */ jsx("button", {
542
+ type: "button",
543
+ onClick: onNewChat,
544
+ children: "Start new chat"
168
545
  })]
169
546
  })]
170
- }), /* @__PURE__ */ jsxs("div", {
171
- className: ai_chat_dock_module_default.actions,
172
- children: [/* @__PURE__ */ jsx("button", {
547
+ })),
548
+ historyFull && !error && !isBusy && onNewChat && /* @__PURE__ */ jsxs("div", {
549
+ className: ai_chat_module_default.historyLimit,
550
+ children: [/* @__PURE__ */ jsxs("span", { children: [
551
+ "This chat has reached its ",
552
+ limit,
553
+ "-question limit."
554
+ ] }), /* @__PURE__ */ jsx("button", {
173
555
  type: "button",
174
- className: ai_chat_dock_module_default.iconButton,
175
- "aria-label": isExpanded ? `Collapse ${title}` : `Expand ${title}`,
176
- title: isExpanded ? "Collapse" : "Expand",
177
- onClick: () => changeExpanded(!isExpanded),
178
- children: isExpanded ? /* @__PURE__ */ jsx("svg", {
179
- width: "17",
180
- height: "17",
181
- viewBox: "0 0 24 24",
182
- fill: "none",
183
- stroke: "currentColor",
184
- strokeWidth: "2",
185
- strokeLinecap: "round",
186
- strokeLinejoin: "round",
187
- "aria-hidden": "true",
188
- children: /* @__PURE__ */ jsx("path", { d: "M9 3v6H3M15 21v-6h6M3 9l6-6M21 15l-6 6" })
189
- }) : /* @__PURE__ */ jsx("svg", {
190
- width: "17",
191
- height: "17",
192
- viewBox: "0 0 24 24",
193
- fill: "none",
194
- stroke: "currentColor",
195
- strokeWidth: "2",
196
- strokeLinecap: "round",
197
- strokeLinejoin: "round",
198
- "aria-hidden": "true",
199
- children: /* @__PURE__ */ jsx("path", { d: "M8 3H3v5M16 21h5v-5M3 3l7 7M21 21l-7-7" })
200
- })
201
- }), /* @__PURE__ */ jsx("button", {
202
- type: "button",
203
- className: ai_chat_dock_module_default.iconButton,
204
- "aria-label": `Close ${title}`,
205
- title: "Close",
206
- onClick: () => changeOpen(false),
207
- children: /* @__PURE__ */ jsx("svg", {
208
- width: "18",
209
- height: "18",
210
- viewBox: "0 0 24 24",
211
- fill: "none",
212
- stroke: "currentColor",
213
- strokeWidth: "2",
214
- strokeLinecap: "round",
215
- "aria-hidden": "true",
216
- children: /* @__PURE__ */ jsx("path", { d: "M18 6 6 18M6 6l12 12" })
217
- })
556
+ onClick: onNewChat,
557
+ children: "Start new chat"
218
558
  })]
219
- })]
220
- }), /* @__PURE__ */ jsx("div", {
221
- className: ai_chat_dock_module_default.content,
222
- children
223
- })]
559
+ }),
560
+ (!historyFull || isBusy) && !error && (composer !== void 0 ? composer : /* @__PURE__ */ jsxs("form", {
561
+ className: ai_chat_module_default.composerForm,
562
+ onSubmit: handleFormSubmit,
563
+ children: [
564
+ composerLeading && /* @__PURE__ */ jsx("div", {
565
+ className: ai_chat_module_default.composerExtras,
566
+ children: composerLeading
567
+ }),
568
+ onSelectAttachments && /* @__PURE__ */ jsxs("div", {
569
+ className: ai_chat_module_default.composerExtras,
570
+ children: [/* @__PURE__ */ jsx("input", {
571
+ ref: fileInputRef,
572
+ className: ai_chat_module_default.visuallyHidden,
573
+ type: "file",
574
+ "aria-label": "Add attachments",
575
+ accept: attachmentAccept,
576
+ multiple: true,
577
+ disabled: isBusy,
578
+ onChange: (event) => {
579
+ if (event.target.files) onSelectAttachments(event.target.files);
580
+ event.target.value = "";
581
+ }
582
+ }), attachments && attachments.length > 0 && /* @__PURE__ */ jsx("ul", {
583
+ className: ai_chat_module_default.attachmentList,
584
+ children: attachments.map((attachment, index) => /* @__PURE__ */ jsxs("li", { children: [attachment.previewUrl ? /* @__PURE__ */ jsx("img", {
585
+ className: ai_chat_module_default.attachmentThumbnail,
586
+ src: attachment.previewUrl,
587
+ alt: attachment.name
588
+ }) : /* @__PURE__ */ jsx("span", {
589
+ className: ai_chat_module_default.attachmentFilename,
590
+ children: attachment.name
591
+ }), onRemoveAttachment && /* @__PURE__ */ jsx("button", {
592
+ type: "button",
593
+ onClick: () => onRemoveAttachment(index),
594
+ "aria-label": `Remove ${attachment.name}`,
595
+ title: `Remove ${attachment.name}`,
596
+ children: "×"
597
+ })] }, index))
598
+ })]
599
+ }),
600
+ /* @__PURE__ */ jsx("div", {
601
+ className: ai_chat_module_default.composerSurface,
602
+ children: /* @__PURE__ */ jsxs("div", {
603
+ className: ai_chat_module_default.composerRow,
604
+ children: [
605
+ onSelectAttachments && /* @__PURE__ */ jsx("button", {
606
+ type: "button",
607
+ className: ai_chat_module_default.composerIconButton,
608
+ "aria-label": "Attach file",
609
+ title: "Attach file",
610
+ disabled: isBusy,
611
+ onClick: () => fileInputRef.current?.click(),
612
+ children: /* @__PURE__ */ jsx("svg", {
613
+ width: "20",
614
+ height: "20",
615
+ viewBox: "0 0 24 24",
616
+ fill: "none",
617
+ stroke: "currentColor",
618
+ strokeWidth: "1.8",
619
+ strokeLinecap: "round",
620
+ strokeLinejoin: "round",
621
+ "aria-hidden": "true",
622
+ children: /* @__PURE__ */ jsx("path", { d: "m21 11-8.5 8.5a6 6 0 0 1-8.5-8.5l9-9a4 4 0 0 1 5.7 5.7l-9 9a2 2 0 0 1-2.8-2.8l8.5-8.5" })
623
+ })
624
+ }),
625
+ /* @__PURE__ */ jsx("textarea", {
626
+ className: ai_chat_module_default.input,
627
+ "aria-label": inputAriaLabel,
628
+ rows: 1,
629
+ value: draft,
630
+ onChange: (event) => onDraftChange?.(event.target.value),
631
+ onKeyDown: handleKeyDown,
632
+ placeholder: inputPlaceholder,
633
+ maxLength: inputMaxLength,
634
+ disabled: isBusy || !onSend || !onDraftChange,
635
+ readOnly: !onDraftChange
636
+ }),
637
+ /* @__PURE__ */ jsxs("div", {
638
+ className: ai_chat_module_default.composerActions,
639
+ children: [composerTrailing, isBusy ? onStop && /* @__PURE__ */ jsx("button", {
640
+ type: "button",
641
+ className: ai_chat_module_default.composerIconButton,
642
+ onClick: onStop,
643
+ "aria-label": "Stop response",
644
+ title: "Stop response",
645
+ children: /* @__PURE__ */ jsx("svg", {
646
+ width: "18",
647
+ height: "18",
648
+ viewBox: "0 0 24 24",
649
+ fill: "currentColor",
650
+ "aria-hidden": "true",
651
+ children: /* @__PURE__ */ jsx("rect", {
652
+ x: "5",
653
+ y: "5",
654
+ width: "14",
655
+ height: "14",
656
+ rx: "2"
657
+ })
658
+ })
659
+ }) : /* @__PURE__ */ jsx("button", {
660
+ type: "submit",
661
+ className: ai_chat_module_default.sendButton,
662
+ "aria-label": "Send message",
663
+ title: "Send message",
664
+ disabled: !onSend || !draft.trim() && !attachments?.length,
665
+ children: /* @__PURE__ */ jsx("svg", {
666
+ width: "20",
667
+ height: "20",
668
+ viewBox: "0 0 24 24",
669
+ fill: "none",
670
+ stroke: "currentColor",
671
+ strokeWidth: "2",
672
+ strokeLinecap: "round",
673
+ strokeLinejoin: "round",
674
+ "aria-hidden": "true",
675
+ children: /* @__PURE__ */ jsx("path", { d: "M12 19V5m-7 7 7-7 7 7" })
676
+ })
677
+ })]
678
+ })
679
+ ]
680
+ })
681
+ })
682
+ ]
683
+ }))
684
+ ]
224
685
  })
225
686
  ]
226
687
  });
227
688
  }
228
689
  //#endregion
229
- export { AIChatDock };
690
+ export { AIChat, AIChatMessageBubble, AIChatView };
230
691
 
231
692
  //# sourceMappingURL=index78.js.map