@tomny-dev/uzi 0.18.1 → 0.19.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.
package/dist/index85.cjs CHANGED
@@ -15,6 +15,119 @@ function safeHttpUrl(value) {
15
15
  const url = asString(value);
16
16
  return url && /^https?:\/\//i.test(url) ? url : void 0;
17
17
  }
18
+ /** Allow only inert bitmap image data, never script-capable data or blob links from messages. */
19
+ function safeImageUrl(value) {
20
+ const url = asString(value);
21
+ return url && (/^https?:\/\//i.test(url) || /^data:image\/(?:png|jpeg|gif|webp|avif);base64,/i.test(url)) ? url : void 0;
22
+ }
23
+ function formatAttachmentSize(bytes) {
24
+ if (bytes < 1024) return `${bytes} B`;
25
+ return bytes < 1024 * 1024 ? `${(bytes / 1024).toFixed(1)} KB` : `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
26
+ }
27
+ /** The same attachment surface is used for staged files and sent message parts. */
28
+ function AIChatAttachmentPreview({ name, size, imageUrl, href, staged, onRemove, removeControl }) {
29
+ const safePreviewUrl = imageUrl && (safeImageUrl(imageUrl) || (staged && /^blob:/i.test(imageUrl) ? imageUrl : void 0));
30
+ const safeHref = safeHttpUrl(href);
31
+ const dialogRef = (0, react.useRef)(null);
32
+ const previewButtonRef = (0, react.useRef)(null);
33
+ const [previewOpen, setPreviewOpen] = (0, react.useState)(false);
34
+ (0, react.useEffect)(() => {
35
+ if (previewOpen && dialogRef.current && !dialogRef.current.open) dialogRef.current.showModal?.();
36
+ }, [previewOpen]);
37
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
38
+ className: [
39
+ require_ai_chat_module.default.attachmentCard,
40
+ staged ? require_ai_chat_module.default.stagedAttachment : require_ai_chat_module.default.sentAttachment,
41
+ staged && !safePreviewUrl ? require_ai_chat_module.default.stagedFileAttachment : ""
42
+ ].filter(Boolean).join(" "),
43
+ children: [
44
+ safePreviewUrl ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
45
+ ref: previewButtonRef,
46
+ type: "button",
47
+ className: require_ai_chat_module.default.imageAttachmentButton,
48
+ onClick: () => setPreviewOpen(true),
49
+ "aria-label": `Preview ${name}`,
50
+ title: `Preview ${name}`,
51
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("img", {
52
+ className: require_ai_chat_module.default.attachmentThumbnail,
53
+ src: safePreviewUrl,
54
+ alt: name,
55
+ loading: "lazy"
56
+ })
57
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
58
+ className: require_ai_chat_module.default.fileAttachment,
59
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
60
+ "aria-hidden": "true",
61
+ width: "22",
62
+ height: "22",
63
+ viewBox: "0 0 24 24",
64
+ fill: "none",
65
+ stroke: "currentColor",
66
+ strokeWidth: "1.7",
67
+ strokeLinecap: "round",
68
+ strokeLinejoin: "round",
69
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8Z" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M14 2v6h6M8 13h8M8 17h5" })]
70
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
71
+ className: require_ai_chat_module.default.fileAttachmentDetails,
72
+ children: [safeHref ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("a", {
73
+ href: safeHref,
74
+ target: "_blank",
75
+ rel: "noopener noreferrer",
76
+ title: name,
77
+ children: name
78
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
79
+ title: name,
80
+ children: name
81
+ }), size !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("small", { children: formatAttachmentSize(size) })]
82
+ })]
83
+ }),
84
+ safePreviewUrl && !staged && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
85
+ className: require_ai_chat_module.default.sentAttachmentName,
86
+ title: name,
87
+ children: name
88
+ }),
89
+ removeControl && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
90
+ className: require_ai_chat_module.default.removeAttachmentSlot,
91
+ children: removeControl
92
+ }),
93
+ !removeControl && onRemove && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
94
+ type: "button",
95
+ className: require_ai_chat_module.default.removeAttachment,
96
+ onClick: onRemove,
97
+ "aria-label": `Remove ${name}`,
98
+ title: `Remove ${name}`,
99
+ children: "×"
100
+ }),
101
+ previewOpen && safePreviewUrl && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("dialog", {
102
+ ref: dialogRef,
103
+ className: require_ai_chat_module.default.attachmentDialog,
104
+ "aria-label": `Preview ${name}`,
105
+ onClose: () => {
106
+ setPreviewOpen(false);
107
+ previewButtonRef.current?.focus();
108
+ },
109
+ onClick: (event) => {
110
+ if (event.target === event.currentTarget) event.currentTarget.close();
111
+ },
112
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
113
+ className: require_ai_chat_module.default.attachmentDialogHeader,
114
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
115
+ title: name,
116
+ children: name
117
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
118
+ type: "button",
119
+ onClick: () => dialogRef.current?.close(),
120
+ "aria-label": "Close attachment preview",
121
+ children: "×"
122
+ })]
123
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("img", {
124
+ src: safePreviewUrl,
125
+ alt: name
126
+ })]
127
+ })
128
+ ]
129
+ });
130
+ }
18
131
  function AIChatMessageBubble({ role, label, children, className }) {
19
132
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
20
133
  className: [
@@ -152,13 +265,14 @@ function renderPart(part, index, components, onToolApproval, pendingApprovalId)
152
265
  });
153
266
  }
154
267
  if (type === "file" || type === "image") {
155
- const url = safeHttpUrl(part.url);
156
- return url ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("a", {
157
- href: url,
158
- target: "_blank",
159
- rel: "noopener noreferrer",
160
- children: asString(part.filename) ?? "View attachment"
161
- }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: "Attachment" });
268
+ const name = asString(part.filename) ?? asString(part.name) ?? "Attachment";
269
+ const mediaType = asString(part.mediaType) ?? asString(part.mimeType);
270
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(AIChatAttachmentPreview, {
271
+ name,
272
+ imageUrl: type === "image" || /^image\/(?:png|jpeg|gif|webp|avif)$/i.test(mediaType ?? "") || /\.(?:png|jpe?g|gif|webp|avif)$/i.test(name) ? safeImageUrl(part.url) : void 0,
273
+ href: safeHttpUrl(part.url),
274
+ size: typeof part.size === "number" && part.size >= 0 ? part.size : void 0
275
+ });
162
276
  }
163
277
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", {
164
278
  className: require_ai_chat_module.default.structuredData,
@@ -166,7 +280,7 @@ function renderPart(part, index, components, onToolApproval, pendingApprovalId)
166
280
  });
167
281
  }
168
282
  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, showNewChatInToolbar = true, newChatRequestKey, attachments, history, sendAutomaticallyWhen, onClose, className, style }) {
283
+ 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, showNewChatInToolbar = true, newChatRequestKey, attachments, activityLabel, toolActivityLabels, history, sendAutomaticallyWhen, onClose, className, style }) {
170
284
  const [session, setSession] = (0, react.useState)(0);
171
285
  const transport = (0, react.useMemo)(() => new _assistant_ui_ai_sdk.AssistantChatTransport({
172
286
  api,
@@ -223,6 +337,8 @@ function AIChat({ api, scope, scopeLabel, fetch: requestFetch, headers, credenti
223
337
  showNewChatInToolbar,
224
338
  newChatRequestKey,
225
339
  attachmentOptions: attachments,
340
+ activityLabel,
341
+ toolActivityLabels,
226
342
  history,
227
343
  onNewChat: () => setSession((previous) => previous + 1)
228
344
  })
@@ -236,7 +352,7 @@ function AIChat({ api, scope, scopeLabel, fetch: requestFetch, headers, credenti
236
352
  ]
237
353
  });
238
354
  }
239
- function ChatViewport({ messageLimit, inputPlaceholder, inputAriaLabel, inputMaxLength, components, toolbarActions, showNewChatInToolbar, newChatRequestKey, attachmentOptions, history, onNewChat }) {
355
+ function ChatViewport({ messageLimit, inputPlaceholder, inputAriaLabel, inputMaxLength, components, toolbarActions, showNewChatInToolbar, newChatRequestKey, attachmentOptions, activityLabel, toolActivityLabels, history, onNewChat }) {
240
356
  const chat = (0, _assistant_ui_ai_sdk.useAISDKChat)();
241
357
  const [draft, setDraft] = (0, react.useState)("");
242
358
  const [selectedFiles, setSelectedFiles] = (0, react.useState)([]);
@@ -372,6 +488,8 @@ function ChatViewport({ messageLimit, inputPlaceholder, inputAriaLabel, inputMax
372
488
  ...isRecord(message.metadata) ? { metadata: message.metadata } : {}
373
489
  })),
374
490
  status,
491
+ activityLabel,
492
+ toolActivityLabels,
375
493
  error: chat?.error,
376
494
  draft,
377
495
  onDraftChange: setDraft,
@@ -417,7 +535,7 @@ function ChatViewport({ messageLimit, inputPlaceholder, inputAriaLabel, inputMax
417
535
  * runtime. It does not create providers, transports or chat state. Callbacks
418
536
  * are the only way messages/actions leave the view.
419
537
  */
420
- function AIChatView({ messages, status = "ready", error, draft = "", onDraftChange, onSend, onStop, onRetry, onNewChat, showNewChatInToolbar = true, messageLimit, inputPlaceholder = "Ask a question...", inputAriaLabel = "Message", inputMaxLength = 2e3, components, attachments, onSelectAttachments, onRemoveAttachment, attachmentAccept, attachmentError, onToolApproval, toolbarActions, header, composerLeading, composerTrailing, composer, emptyState, className, style }) {
538
+ function AIChatView({ messages, status = "ready", activityLabel = "Working on your response…", toolActivityLabels, error, draft = "", onDraftChange, onSend, onStop, onRetry, onNewChat, showNewChatInToolbar = true, messageLimit, inputPlaceholder = "Ask a question...", inputAriaLabel = "Message", inputMaxLength = 2e3, components, attachments, onSelectAttachments, onRemoveAttachment, attachmentAccept, attachmentError, onToolApproval, toolbarActions, header, composerLeading, composerTrailing, composer, emptyState, className, style }) {
421
539
  const viewportRef = (0, react.useRef)(null);
422
540
  const pinnedToBottom = (0, react.useRef)(true);
423
541
  const fileInputRef = (0, react.useRef)(null);
@@ -439,6 +557,15 @@ function AIChatView({ messages, status = "ready", error, draft = "", onDraftChan
439
557
  }
440
558
  };
441
559
  const isBusy = status === "submitted" || status === "streaming";
560
+ const lastMessage = messages[messages.length - 1];
561
+ const assistantParts = lastMessage?.role === "assistant" ? lastMessage.parts.filter(isRecord) : [];
562
+ const lastPart = [...assistantParts].reverse().find((part) => part.type !== "step-start");
563
+ const lastPartType = asString(lastPart?.type) ?? "";
564
+ const activeTool = (lastPartType.startsWith("tool-") || lastPartType === "dynamic-tool") && lastPart?.state !== "output-available" && lastPart?.state !== "output-error" ? lastPart : void 0;
565
+ const hasAnswer = assistantParts.some((part) => part.type === "text" && Boolean(asString(part.text)?.trim()));
566
+ const showActivity = isBusy && (!hasAnswer || Boolean(activeTool));
567
+ const toolName = asString(activeTool?.toolName) ?? lastPartType.replace(/^tool-/, "");
568
+ const currentActivityLabel = activeTool?.state === "approval-requested" ? "Waiting for approval…" : activeTool ? toolActivityLabels?.[toolName] ?? "Using a tool…" : activityLabel;
442
569
  const limit = messageLimit != null && Number.isFinite(messageLimit) ? Math.max(1, Math.floor(messageLimit)) : null;
443
570
  const historyFull = limit !== null && messages.filter((message) => message.role === "user").length >= limit;
444
571
  const MessageRenderer = components?.MessageRenderer ?? DefaultMessageRenderer;
@@ -514,9 +641,19 @@ function AIChatView({ messages, status = "ready", error, draft = "", onDraftChan
514
641
  renderMessagePart: (part, index) => renderPart(part, index, components, onToolApproval ? respondToApproval : void 0, pendingApprovalId),
515
642
  onToolApproval: onToolApproval ? respondToApproval : void 0
516
643
  }, message.id)),
517
- isBusy && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
518
- className: require_ai_chat_module.default.status,
519
- children: "Thinking..."
644
+ showActivity && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
645
+ className: require_ai_chat_module.default.activityBubble,
646
+ role: "status",
647
+ "aria-label": currentActivityLabel,
648
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
649
+ className: require_ai_chat_module.default.activityDots,
650
+ "aria-hidden": "true",
651
+ children: [
652
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("i", {}),
653
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("i", {}),
654
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("i", {})
655
+ ]
656
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: currentActivityLabel })]
520
657
  })
521
658
  ]
522
659
  })
@@ -574,37 +711,32 @@ function AIChatView({ messages, status = "ready", error, draft = "", onDraftChan
574
711
  className: require_ai_chat_module.default.composerExtras,
575
712
  children: composerLeading
576
713
  }),
577
- onSelectAttachments && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
714
+ onSelectAttachments && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
715
+ ref: fileInputRef,
716
+ className: require_ai_chat_module.default.visuallyHidden,
717
+ type: "file",
718
+ "aria-label": "Add attachments",
719
+ accept: attachmentAccept,
720
+ multiple: true,
721
+ disabled: isBusy,
722
+ onChange: (event) => {
723
+ if (event.target.files) onSelectAttachments(event.target.files);
724
+ event.target.value = "";
725
+ }
726
+ }),
727
+ attachments && attachments.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
578
728
  className: require_ai_chat_module.default.composerExtras,
579
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
580
- ref: fileInputRef,
581
- className: require_ai_chat_module.default.visuallyHidden,
582
- type: "file",
583
- "aria-label": "Add attachments",
584
- accept: attachmentAccept,
585
- multiple: true,
586
- disabled: isBusy,
587
- onChange: (event) => {
588
- if (event.target.files) onSelectAttachments(event.target.files);
589
- event.target.value = "";
590
- }
591
- }), attachments && attachments.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("ul", {
729
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("ul", {
592
730
  className: require_ai_chat_module.default.attachmentList,
593
- children: attachments.map((attachment, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("li", { children: [attachment.previewUrl ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("img", {
594
- className: require_ai_chat_module.default.attachmentThumbnail,
595
- src: attachment.previewUrl,
596
- alt: attachment.name
597
- }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
598
- className: require_ai_chat_module.default.attachmentFilename,
599
- children: attachment.name
600
- }), onRemoveAttachment && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
601
- type: "button",
602
- onClick: () => onRemoveAttachment(index),
603
- "aria-label": `Remove ${attachment.name}`,
604
- title: `Remove ${attachment.name}`,
605
- children: "×"
606
- })] }, index))
607
- })]
731
+ "aria-label": "Attached files",
732
+ children: attachments.map((attachment, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("li", { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(AIChatAttachmentPreview, {
733
+ name: attachment.name,
734
+ size: attachment.size,
735
+ staged: true,
736
+ imageUrl: attachment.previewUrl,
737
+ onRemove: onRemoveAttachment ? () => onRemoveAttachment(index) : void 0
738
+ }) }, index))
739
+ })
608
740
  }),
609
741
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
610
742
  className: require_ai_chat_module.default.composerSurface,
@@ -697,6 +829,7 @@ function AIChatView({ messages, status = "ready", error, draft = "", onDraftChan
697
829
  }
698
830
  //#endregion
699
831
  exports.AIChat = AIChat;
832
+ exports.AIChatAttachmentPreview = AIChatAttachmentPreview;
700
833
  exports.AIChatMessageBubble = AIChatMessageBubble;
701
834
  exports.AIChatView = AIChatView;
702
835
 
@@ -1 +1 @@
1
- {"version":3,"file":"index85.cjs","names":[],"sources":["../src/components/ai-chat/AIChat.tsx"],"sourcesContent":["'use client';\n\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport type { CSSProperties, ComponentType, FormEvent, KeyboardEvent, ReactNode } from 'react';\n\nimport { AuiConfig, AuiProvider, ThreadPrimitive } from '@assistant-ui/react';\nimport { AISDKChat, AssistantChatTransport, useAISDKChat } from '@assistant-ui/ai-sdk';\n\nimport styles from './ai-chat.module.css';\n\ntype AIChatTransportOptions = NonNullable<ConstructorParameters<typeof AssistantChatTransport>[0]>;\n\nexport interface AIChatProps {\n /** AI SDK UI-message stream endpoint. */\n readonly api: string;\n /** Opaque scope identifier sent to the API. Server must authorize it. */\n readonly scope?: string;\n /** Human-readable display text; never used as an access-control identifier. */\n readonly scopeLabel?: string;\n /** Fetch adapter for authentication, request instrumentation and local demos. */\n readonly fetch?: typeof globalThis.fetch;\n readonly headers?: Record<string, string>;\n readonly credentials?: RequestCredentials;\n /** Customize serialized requests for APIs with a strict request schema. */\n readonly prepareSendMessagesRequest?: AIChatTransportOptions['prepareSendMessagesRequest'];\n /** Change this when the authenticated identity changes to reset the transcript. */\n readonly sessionKey?: string | number;\n /** Maximum number of user turns (default: 8). */\n readonly messageLimit?: number;\n readonly inputPlaceholder?: string;\n /** Accessible name for the message textarea. */\n readonly inputAriaLabel?: string;\n readonly inputMaxLength?: number;\n readonly components?: AIChatComponents;\n /** Actions displayed beside the native New chat control in one shared toolbar. */\n readonly toolbarActions?: ReactNode;\n /** When false, the enclosing AIChatDock owns the New chat control. */\n readonly showNewChatInToolbar?: boolean;\n /** Increment or replace this stable token to request the native New chat flow externally. */\n readonly newChatRequestKey?: string | number;\n /** Opt-in files, restricted to images/text accepted by the application API. */\n readonly attachments?: AIChatAttachmentOptions;\n /** Optional persistence; implementations must scope storage by user AND resource. */\n readonly history?: AIChatHistoryAdapter;\n /** Native SDK continuation predicate for tool approvals. */\n readonly sendAutomaticallyWhen?: NonNullable<Parameters<typeof AISDKChat>[0]>['sendAutomaticallyWhen'];\n readonly onClose?: () => void;\n readonly className?: string;\n readonly style?: CSSProperties;\n}\n\n/**\n * Framework-independent presentation contract. The parent owns the runtime,\n * message identities, approvals, uploads, history and security boundaries.\n * Uzi does not serialize, persist or reinterpret any messages supplied here.\n */\nexport type AIChatMessage = AIChatMessageRendererProps['message'];\n\nexport interface AIChatAttachmentOptions {\n readonly accept: string;\n readonly maxFiles?: number;\n readonly maxBytesPerFile?: number;\n}\n\nexport interface AIChatSelectedAttachment {\n readonly name: string;\n readonly size: number;\n /** Local thumbnail URL for supported image files. */\n readonly previewUrl?: string;\n}\n\nexport interface AIChatHistoryAdapter {\n /** Load only validated UI messages from the authenticated principal's own storage. */\n readonly load: () => Promise<readonly AIChatMessage[]> | readonly AIChatMessage[];\n /** Save after complete turns; the consumer decides what metadata is safe. */\n readonly save: (messages: readonly AIChatMessage[]) => Promise<void> | void;\n readonly clear: () => Promise<void> | void;\n /** Observability for failed history operations; never include message payloads in logs. */\n readonly onError?: (operation: 'load' | 'save' | 'clear', error: unknown) => void;\n}\n\nexport type AIChatToolApprovalHandler = (id: string, approved: boolean) => Promise<void> | void;\n\nexport interface AIChatViewProps {\n readonly messages: readonly AIChatMessage[];\n readonly status?: string;\n readonly error?: Error | null;\n readonly draft?: string;\n readonly onDraftChange?: (draft: string) => void;\n readonly onSend?: () => void;\n readonly onStop?: () => void;\n readonly onRetry?: () => void;\n readonly onNewChat?: () => void;\n /** False when AIChatDock owns the new-chat action in its header. */\n readonly showNewChatInToolbar?: boolean;\n /** No limit by default: specialized apps decide their own session policy. */\n readonly messageLimit?: number;\n readonly inputPlaceholder?: string;\n readonly inputAriaLabel?: string;\n readonly inputMaxLength?: number;\n readonly components?: AIChatComponents;\n readonly attachments?: readonly AIChatSelectedAttachment[];\n readonly onSelectAttachments?: (files: FileList) => void;\n readonly onRemoveAttachment?: (index: number) => void;\n readonly attachmentAccept?: string;\n readonly attachmentError?: string | null;\n /** Only invoked from explicit user action on an approval-requested tool part. */\n readonly onToolApproval?: AIChatToolApprovalHandler;\n /** Custom message toolbar controls, e.g. a conversation selector. */\n readonly toolbarActions?: ReactNode;\n /** Context labels or other app-owned notices above the transcript. */\n readonly header?: ReactNode;\n /** Upload actions, attachment previews or context chips before the input. */\n readonly composerLeading?: ReactNode;\n /** Additional buttons beside the Send/Stop control. */\n readonly composerTrailing?: ReactNode;\n /** Completely replace the composer while retaining shared transcript chrome. */\n readonly composer?: ReactNode;\n readonly emptyState?: ReactNode;\n readonly className?: string;\n readonly style?: CSSProperties;\n}\n\nexport interface AIChatComponents {\n readonly MessageRenderer?: ComponentType<AIChatMessageRendererProps>;\n readonly ReasoningRenderer?: ComponentType<AIChatReasoningRendererProps>;\n readonly SourceRenderer?: ComponentType<AIChatSourceRendererProps>;\n readonly DataRenderer?: ComponentType<AIChatDataRendererProps>;\n readonly ToolRenderer?: ComponentType<AIChatToolRendererProps>;\n readonly ErrorRenderer?: ComponentType<AIChatErrorRendererProps>;\n}\n\nexport interface AIChatMessageRendererProps {\n readonly message: {\n readonly id: string;\n readonly role: 'user' | 'assistant';\n readonly parts: readonly unknown[];\n readonly metadata?: Record<string, unknown>;\n };\n readonly renderMessagePart: (part: Record<string, unknown>, index: number) => ReactNode;\n readonly onToolApproval?: AIChatToolApprovalHandler;\n}\n\nexport interface AIChatReasoningRendererProps {\n readonly children: string;\n readonly title?: string;\n}\n\nexport interface AIChatSource {\n readonly id: string;\n readonly title?: string;\n readonly url?: string;\n}\n\nexport interface AIChatSourceRendererProps {\n readonly sources: readonly AIChatSource[];\n readonly renderSource: (source: AIChatSource, index: number) => ReactNode;\n}\n\nexport interface AIChatDataRendererProps {\n readonly data: readonly Record<string, unknown>[];\n readonly renderDataItem: (item: Record<string, unknown>, index: number) => ReactNode;\n}\n\nexport interface AIChatToolRendererProps {\n readonly part: Record<string, unknown>;\n readonly name: string;\n readonly approvalId?: string;\n readonly onApprove?: () => void;\n readonly onDeny?: () => void;\n readonly approvalPending: boolean;\n}\n\nexport interface AIChatErrorRendererProps {\n readonly error: Error;\n readonly onRetry: () => void;\n readonly onClear: () => void;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction asString(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction safeHttpUrl(value: unknown): string | undefined {\n const url = asString(value);\n return url && /^https?:\\/\\//i.test(url) ? url : undefined;\n}\n\n/** Reusable role-aware message surface for domain renderers. */\nexport interface AIChatMessageBubbleProps {\n readonly role: 'user' | 'assistant';\n readonly label?: string;\n readonly children: ReactNode;\n readonly className?: string;\n}\n\nexport function AIChatMessageBubble({ role, label, children, className }: AIChatMessageBubbleProps) {\n return (\n <div className={[styles.messageBubble, role === 'user' ? styles.userMessage : styles.assistantMessage, className]\n .filter(Boolean).join(' ')} data-role={role}>\n {label && <span className={styles.messageLabel}>{label}</span>}\n {children}\n </div>\n );\n}\n\nfunction DefaultMessageRenderer({ message, renderMessagePart }: AIChatMessageRendererProps) {\n return (\n <AIChatMessageBubble role={message.role}>\n {message.parts.map((part, index) => (\n <div key={isRecord(part) && typeof part.id === 'string' ? part.id : index}>\n {isRecord(part) ? renderMessagePart(part, index) : null}\n </div>\n ))}\n </AIChatMessageBubble>\n );\n}\n\nfunction DefaultReasoningRenderer({ children, title = 'Reasoning' }: AIChatReasoningRendererProps) {\n return (\n <details className={styles.reasoning}>\n <summary className={styles.reasoningSummary}>{title}</summary>\n <p className={styles.reasoningText}>{children}</p>\n </details>\n );\n}\n\nfunction DefaultSourceRenderer({ sources, renderSource }: AIChatSourceRendererProps) {\n return (\n <div className={styles.sources}>\n <span className={styles.sourcesLabel}>Sources</span>\n <ul>\n {sources.map((source, index) => (\n <li key={source.id}>{renderSource(source, index)}</li>\n ))}\n </ul>\n </div>\n );\n}\n\nfunction DefaultDataRenderer({ data, renderDataItem }: AIChatDataRendererProps) {\n return (\n <div className={styles.data}>\n {data.map((item, index) => (\n <div key={index}>{renderDataItem(item, index)}</div>\n ))}\n </div>\n );\n}\n\nfunction DefaultErrorRenderer({ error, onRetry, onClear }: AIChatErrorRendererProps) {\n return (\n <div className={styles.error} role=\"alert\">\n <p>{error.message}</p>\n <div className={styles.errorActions}>\n <button type=\"button\" onClick={onRetry}>Retry response</button>\n <button type=\"button\" onClick={onClear}>Start new chat</button>\n </div>\n </div>\n );\n}\n\nfunction renderPart(\n part: Record<string, unknown>,\n index: number,\n components: AIChatComponents | undefined,\n onToolApproval?: AIChatToolApprovalHandler,\n pendingApprovalId?: string | null,\n): ReactNode {\n const type = asString(part.type) ?? '';\n if (type === 'step-start') return null;\n if (type === 'text') {\n return <span className={styles.textPart}>{asString(part.text) ?? ''}</span>;\n }\n if (type === 'reasoning') {\n const ReasoningRenderer = components?.ReasoningRenderer ?? DefaultReasoningRenderer;\n return <ReasoningRenderer>{asString(part.text) ?? ''}</ReasoningRenderer>;\n }\n if (type === 'source-url' || type === 'source-document') {\n const SourceRenderer = components?.SourceRenderer ?? DefaultSourceRenderer;\n const source: AIChatSource = {\n id: asString(part.sourceId) ?? asString(part.id) ?? `source-${index}`,\n title: asString(part.title) ?? asString(part.filename),\n url: safeHttpUrl(part.url),\n };\n return (\n <SourceRenderer\n sources={[source]}\n renderSource={(item) => item.url ? (\n <a href={item.url} target=\"_blank\" rel=\"noopener noreferrer\">\n {item.title ?? item.url}\n </a>\n ) : <span>{item.title ?? item.id}</span>}\n />\n );\n }\n if (type.startsWith('data-')) {\n const DataRenderer = components?.DataRenderer ?? DefaultDataRenderer;\n return (\n <DataRenderer\n data={[part]}\n renderDataItem={(item) => (\n <pre className={styles.structuredData}>{JSON.stringify(item.data ?? item, null, 2)}</pre>\n )}\n />\n );\n }\n if (type.startsWith('tool-') || type === 'dynamic-tool') {\n const name = asString(part.toolName) ?? type.replace(/^tool-/, '');\n const approval = isRecord(part.approval) ? asString(part.approval.id) : undefined;\n const approvalId = part.state === 'approval-requested' ? approval : undefined;\n const controlsDisabled = pendingApprovalId !== null && pendingApprovalId !== undefined;\n const ToolRenderer = components?.ToolRenderer;\n const props: AIChatToolRendererProps = {\n part, name, approvalId,\n approvalPending: controlsDisabled,\n ...(approvalId && onToolApproval ? {\n onApprove: () => { if (!controlsDisabled) void onToolApproval(approvalId, true); },\n onDeny: () => { if (!controlsDisabled) void onToolApproval(approvalId, false); },\n } : {}),\n };\n if (ToolRenderer) return <ToolRenderer {...props} />;\n return (\n <div className={styles.toolPart}>\n <details>\n <summary>{name}</summary>\n <pre className={styles.structuredData}>\n {JSON.stringify(part.output ?? part.input ?? part, null, 2)}\n </pre>\n </details>\n {approvalId && (\n <div className={styles.approvalActions} aria-label={`Approval required for ${name}`}>\n {props.onApprove && props.onDeny ? (\n <>\n <button type=\"button\" disabled={controlsDisabled} onClick={props.onApprove}>Approve</button>\n <button type=\"button\" disabled={controlsDisabled} onClick={props.onDeny}>Deny</button>\n </>\n ) : <span>Approval required in application</span>}\n </div>\n )}\n </div>\n );\n }\n if (type === 'file' || type === 'image') {\n const url = safeHttpUrl(part.url);\n return url ? (\n <a href={url} target=\"_blank\" rel=\"noopener noreferrer\">\n {asString(part.filename) ?? 'View attachment'}\n </a>\n ) : <span>Attachment</span>;\n }\n // Preserve unsupported part types as inspectable data instead of silently dropping them.\n return <pre className={styles.structuredData}>{JSON.stringify(part, null, 2)}</pre>;\n}\n\nconst DEFAULT_MESSAGE_LIMIT = 8;\n\nexport function AIChat({\n api,\n scope,\n scopeLabel,\n fetch: requestFetch,\n headers,\n credentials,\n prepareSendMessagesRequest,\n sessionKey,\n messageLimit = DEFAULT_MESSAGE_LIMIT,\n inputPlaceholder = 'Ask a question...',\n inputAriaLabel = 'Message',\n inputMaxLength = 2000,\n components,\n toolbarActions,\n showNewChatInToolbar = true,\n newChatRequestKey,\n attachments,\n history,\n sendAutomaticallyWhen,\n onClose,\n className,\n style,\n}: AIChatProps) {\n // Remounting the provider creates a fresh AI SDK chat id, not merely an empty transcript.\n const [session, setSession] = useState(0);\n const transport = useMemo(\n () => new AssistantChatTransport({\n api,\n // The transport merges this with the AI SDK messages, id, model context and tools.\n // The endpoint, not the presentation component, must enforce the scope.\n ...(scope ? { body: { scope } } : {}),\n ...(requestFetch ? { fetch: requestFetch } : {}),\n ...(headers ? { headers } : {}),\n ...(credentials ? { credentials } : {}),\n ...(prepareSendMessagesRequest ? { prepareSendMessagesRequest } : {}),\n }),\n [api, scope, requestFetch, headers, credentials, prepareSendMessagesRequest],\n );\n const config = useMemo(\n () => AuiConfig({ threads: AISDKChat({ transport, ...(sendAutomaticallyWhen ? { sendAutomaticallyWhen } : {}) }) }),\n [transport, session, sendAutomaticallyWhen],\n );\n\n return (\n <div className={[styles.container, className].filter(Boolean).join(' ')} style={style}>\n {scopeLabel && (\n <div className={styles.scope}>\n <span className={styles.scopeLabel}>Current scope</span>\n <strong>{scopeLabel}</strong>\n </div>\n )}\n {onClose && (\n <button className={styles.closeBtn} type=\"button\" onClick={onClose} aria-label=\"Close chat\">\n &#x2715;\n </button>\n )}\n <AuiProvider key={JSON.stringify([api, scope, sessionKey, session])} config={config}>\n <ThreadPrimitive.Root className={styles.thread}>\n <ChatViewport\n messageLimit={Number.isFinite(messageLimit) ? Math.max(1, Math.floor(messageLimit)) : DEFAULT_MESSAGE_LIMIT}\n inputPlaceholder={inputPlaceholder}\n inputAriaLabel={inputAriaLabel}\n inputMaxLength={inputMaxLength}\n components={components}\n toolbarActions={toolbarActions}\n showNewChatInToolbar={showNewChatInToolbar}\n newChatRequestKey={newChatRequestKey}\n attachmentOptions={attachments}\n history={history}\n onNewChat={() => setSession((previous) => previous + 1)}\n />\n </ThreadPrimitive.Root>\n </AuiProvider>\n </div>\n );\n}\n\ninterface ChatViewportProps {\n readonly messageLimit: number;\n readonly inputPlaceholder: string;\n readonly inputAriaLabel: string;\n readonly inputMaxLength: number;\n readonly components?: AIChatComponents;\n readonly toolbarActions?: ReactNode;\n readonly showNewChatInToolbar?: boolean;\n readonly newChatRequestKey?: string | number;\n readonly attachmentOptions?: AIChatAttachmentOptions;\n readonly history?: AIChatHistoryAdapter;\n readonly onNewChat: () => void;\n}\n\nfunction ChatViewport({\n messageLimit,\n inputPlaceholder,\n inputAriaLabel,\n inputMaxLength,\n components,\n toolbarActions,\n showNewChatInToolbar,\n newChatRequestKey,\n attachmentOptions,\n history,\n onNewChat,\n}: ChatViewportProps) {\n const chat = useAISDKChat();\n const [draft, setDraft] = useState('');\n const [selectedFiles, setSelectedFiles] = useState<File[]>([]);\n const [attachmentError, setAttachmentError] = useState<string | null>(null);\n const [attachmentPreviews, setAttachmentPreviews] = useState<string[]>([]);\n const [hydrated, setHydrated] = useState(!history);\n const expectedRestoredId = useRef<string | null>(null);\n const saveQueue = useRef<Promise<void>>(Promise.resolve());\n const [approvalBusy, setApprovalBusy] = useState(false);\n useEffect(() => {\n const urls = selectedFiles.map((file) => file.type.startsWith('image/') && typeof URL.createObjectURL === 'function' ? URL.createObjectURL(file) : '');\n setAttachmentPreviews(urls);\n return () => urls.forEach((url) => { if (url && typeof URL.revokeObjectURL === 'function') URL.revokeObjectURL(url); });\n }, [selectedFiles]);\n const messages = chat?.messages ?? [];\n const status = chat?.status ?? 'ready';\n const isBusy = status === 'submitted' || status === 'streaming';\n const historyFull = messages.filter((message) => message.role === 'user').length >= messageLimit;\n const reportHistoryError = (operation: 'load' | 'save' | 'clear', error: unknown) => {\n if (history?.onError) history.onError(operation, error);\n else console.warn(`[Uzi AIChat] History ${operation} failed`);\n };\n // Persist only complete turns. Do not save an empty runtime over stored history\n // during hydration or while a response is still streaming.\n useEffect(() => {\n if (!history) return;\n let active = true;\n void Promise.resolve().then(() => history.load()).then((restored) => {\n if (!active) return;\n if (Array.isArray(restored)) {\n const valid = restored.filter((message) =>\n typeof message?.id === 'string' &&\n (message.role === 'user' || message.role === 'assistant') &&\n Array.isArray(message.parts));\n expectedRestoredId.current = valid.length ? valid[0].id : null;\n if (valid.length) chat?.setMessages(valid as Parameters<NonNullable<typeof chat>['setMessages']>[0]);\n }\n setHydrated(true);\n }).catch((error: unknown) => {\n if (active) {\n reportHistoryError('load', error);\n setHydrated(true);\n }\n });\n return () => { active = false; };\n }, [chat?.setMessages, history]);\n\n useEffect(() => {\n if (!history || !hydrated || isBusy) return;\n const snapshot = messages.filter((message) => message.role === 'user' || message.role === 'assistant').map((message) => ({\n id: message.id, role: message.role as 'user' | 'assistant', parts: message.parts,\n ...(isRecord(message.metadata) ? { metadata: message.metadata } : {}),\n }));\n // Guard against the transient empty SDK state between history.load and\n // setMessages propagation; otherwise an old transcript could be erased.\n if (expectedRestoredId.current) {\n if (!snapshot.some((message) => message.id === expectedRestoredId.current)) return;\n expectedRestoredId.current = null;\n }\n // Serialize writes. New Chat waits for in-flight writes before clearing.\n saveQueue.current = saveQueue.current.then(\n () => history.save(snapshot),\n () => history.save(snapshot),\n ).then(\n () => {},\n (error: unknown) => { reportHistoryError('save', error); },\n );\n }, [history, hydrated, isBusy, messages]);\n\n const handleSelectedFiles = (files: FileList) => {\n if (!attachmentOptions) return;\n const selected = Array.from(files);\n if (selected.length + selectedFiles.length > (attachmentOptions.maxFiles ?? 3)) {\n setAttachmentError('Too many attachments.');\n return;\n }\n if (selected.some((file) => file.size > (attachmentOptions.maxBytesPerFile ?? 5 * 1024 * 1024))) {\n setAttachmentError('An attachment exceeds the size limit.');\n return;\n }\n const allowedTypes = attachmentOptions.accept.split(',').map((item) => item.trim());\n if (selected.some((file) => !allowedTypes.some((allow) => (\n allow === file.type || (allow.endsWith('/*') && file.type.startsWith(allow.slice(0, -1)))\n )))) {\n setAttachmentError('Unsupported attachment type.');\n return;\n }\n setAttachmentError(null);\n setSelectedFiles((existing) => [...existing, ...selected]);\n };\n\n const handleSubmit = () => {\n const text = draft.trim();\n if (!chat || (!text && selectedFiles.length === 0) || isBusy || historyFull || chat.error || !hydrated || approvalBusy) return;\n const files = selectedFiles.length ? new DataTransfer() : null;\n selectedFiles.forEach((file) => files?.items.add(file));\n // AI SDK serializes FileList to FileUIParts and sends them through the\n // app-owned transport. The server MUST validate types and sizes again.\n // Clear the composer promptly; restore the draft and files if submission\n // fails, so users do not lose attachments or typed content.\n const previousDraft = draft;\n const previousFiles = selectedFiles;\n setDraft('');\n setSelectedFiles([]);\n setAttachmentError(null);\n void Promise.resolve(chat.sendMessage({ text, ...(files ? { files: files.files } : {}) }))\n .catch(() => {\n setDraft((current) => current || previousDraft);\n setSelectedFiles((current) => current.length ? current : previousFiles);\n });\n };\n\n const handleNewChat = () => {\n void (async () => {\n await chat?.stop();\n if (history) {\n try {\n await saveQueue.current;\n await history.clear();\n } catch (error) {\n reportHistoryError('clear', error);\n return;\n }\n }\n onNewChat();\n })();\n };\n\n // An enclosing dock can reuse the native reset path without duplicating\n // history deletion, aborts, or SDK session management in each consumer.\n const lastNewChatRequestKey = useRef(newChatRequestKey);\n useEffect(() => {\n if (lastNewChatRequestKey.current === newChatRequestKey) return;\n lastNewChatRequestKey.current = newChatRequestKey;\n handleNewChat();\n }, [newChatRequestKey]);\n\n const handleRetry = () => {\n if (!chat || isBusy) return;\n chat.clearError();\n void chat.regenerate();\n };\n\n return (\n <AIChatView\n messages={messages.filter((message) => message.role === 'user' || message.role === 'assistant').map((message) => ({\n id: message.id,\n role: message.role as 'user' | 'assistant',\n parts: message.parts,\n ...(isRecord(message.metadata) ? { metadata: message.metadata } : {}),\n }))}\n status={status}\n error={chat?.error}\n draft={draft}\n onDraftChange={setDraft}\n onSend={handleSubmit}\n onStop={() => { void chat?.stop(); }}\n onRetry={handleRetry}\n onNewChat={handleNewChat}\n showNewChatInToolbar={showNewChatInToolbar}\n toolbarActions={toolbarActions}\n messageLimit={messageLimit}\n attachments={selectedFiles.map((file, index) => ({ name: file.name, size: file.size, ...(attachmentPreviews[index] ? { previewUrl: attachmentPreviews[index] } : {}) }))}\n onSelectAttachments={attachmentOptions ? handleSelectedFiles : undefined}\n onRemoveAttachment={attachmentOptions ? (index) => setSelectedFiles((files) => files.filter((_, i) => i !== index)) : undefined}\n attachmentAccept={attachmentOptions?.accept}\n attachmentError={attachmentError}\n onToolApproval={chat ? async (id, approved) => {\n if (approvalBusy) return;\n setApprovalBusy(true);\n try { await chat.addToolApprovalResponse({ id, approved, ...(!approved ? { reason: 'User denied approval' } : {}) }); }\n finally { setApprovalBusy(false); }\n } : undefined}\n inputPlaceholder={inputPlaceholder}\n inputAriaLabel={inputAriaLabel}\n inputMaxLength={inputMaxLength}\n components={components}\n />\n );\n}\n\n/**\n * Controlled chat presentation for apps with their own AI SDK/assistant-ui\n * runtime. It does not create providers, transports or chat state. Callbacks\n * are the only way messages/actions leave the view.\n */\nexport function AIChatView({\n messages,\n status = 'ready',\n error,\n draft = '',\n onDraftChange,\n onSend,\n onStop,\n onRetry,\n onNewChat,\n showNewChatInToolbar = true,\n messageLimit,\n inputPlaceholder = 'Ask a question...',\n inputAriaLabel = 'Message',\n inputMaxLength = 2000,\n components,\n attachments,\n onSelectAttachments,\n onRemoveAttachment,\n attachmentAccept,\n attachmentError,\n onToolApproval,\n toolbarActions,\n header,\n composerLeading,\n composerTrailing,\n composer,\n emptyState,\n className,\n style,\n}: AIChatViewProps) {\n const viewportRef = useRef<HTMLDivElement>(null);\n const pinnedToBottom = useRef(true);\n const fileInputRef = useRef<HTMLInputElement>(null);\n const approvalRef = useRef<string | null>(null);\n const [pendingApprovalId, setPendingApprovalId] = useState<string | null>(null);\n const [approvalError, setApprovalError] = useState<string | null>(null);\n const respondToApproval: AIChatToolApprovalHandler = async (id, approved) => {\n if (!onToolApproval || approvalRef.current) return;\n approvalRef.current = id;\n setPendingApprovalId(id);\n setApprovalError(null);\n try { await onToolApproval(id, approved); }\n catch { setApprovalError('Could not submit approval. Please try again.'); }\n finally { approvalRef.current = null; setPendingApprovalId(null); }\n };\n const isBusy = status === 'submitted' || status === 'streaming';\n const limit = messageLimit != null && Number.isFinite(messageLimit)\n ? Math.max(1, Math.floor(messageLimit)) : null;\n const historyFull = limit !== null && messages.filter((message) => message.role === 'user').length >= limit;\n const MessageRenderer = components?.MessageRenderer ?? DefaultMessageRenderer;\n const ErrorRenderer = components?.ErrorRenderer ?? DefaultErrorRenderer;\n\n // Follow streaming text only if the user is already near the bottom.\n useEffect(() => {\n const viewport = viewportRef.current;\n if (viewport && pinnedToBottom.current) viewport.scrollTop = viewport.scrollHeight;\n });\n\n const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key === 'Enter' && !event.shiftKey && !event.nativeEvent.isComposing) {\n event.preventDefault();\n if (!isBusy && !historyFull && !error && (draft.trim() || (attachments?.length ?? 0) > 0)) onSend?.();\n }\n };\n\n const handleFormSubmit = (event: FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n if (!isBusy && !historyFull && !error && (draft.trim() || (attachments?.length ?? 0) > 0)) onSend?.();\n };\n\n return (\n <div className={[styles.thread, className].filter(Boolean).join(' ')} style={style}>\n {header}\n {(toolbarActions || (showNewChatInToolbar && onNewChat && messages.length > 0)) && (\n <div className={styles.chatToolbar} role=\"toolbar\" aria-label=\"Conversation actions\">\n <div className={styles.chatToolbarExtras}>{toolbarActions}</div>\n {showNewChatInToolbar && onNewChat && messages.length > 0 && (\n <button\n type=\"button\"\n className={styles.newChatButton}\n onClick={onNewChat}\n aria-label=\"New chat\"\n title=\"New chat\"\n >\n <svg aria-hidden=\"true\" width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"none\"\n stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <path d=\"M12 5H6a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2v-6\" />\n <path d=\"m15 5 4 4M13 11l7-7a2.12 2.12 0 0 1 3 3l-7 7-4 1 1-4Z\" transform=\"translate(-2 -2)\" />\n </svg>\n </button>\n )}\n </div>\n )}\n <div\n ref={viewportRef}\n className={styles.viewport}\n onScroll={(event) => {\n const viewport = event.currentTarget;\n pinnedToBottom.current = viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight < 80;\n }}\n >\n <div className={styles.messageList} role=\"log\" aria-label=\"Chat history\" aria-live=\"polite\">\n {messages.length === 0 && (\n <div className={styles.emptyState}>\n {emptyState ?? <p>Start a conversation</p>}\n </div>\n )}\n {messages.map((message) => (\n <MessageRenderer\n key={message.id}\n message={message}\n renderMessagePart={(part, index) => renderPart(part, index, components, onToolApproval ? respondToApproval : undefined, pendingApprovalId)}\n onToolApproval={onToolApproval ? respondToApproval : undefined}\n />\n ))}\n {isBusy && <p className={styles.status}>Thinking...</p>}\n </div>\n </div>\n <div className={styles.footer}>\n {approvalError && <p role=\"alert\" className={styles.attachmentError}>{approvalError}</p>}\n {attachmentError && <p role=\"alert\" className={styles.attachmentError}>{attachmentError}</p>}\n {error && (\n onRetry && onNewChat ? (\n <ErrorRenderer error={error} onRetry={onRetry} onClear={onNewChat} />\n ) : (\n <div className={styles.error} role=\"alert\">\n <p>{error.message}</p>\n {(onRetry || onNewChat) && (\n <div className={styles.errorActions}>\n {onRetry && <button type=\"button\" onClick={onRetry}>Retry response</button>}\n {onNewChat && <button type=\"button\" onClick={onNewChat}>Start new chat</button>}\n </div>\n )}\n </div>\n )\n )}\n {historyFull && !error && !isBusy && onNewChat && (\n <div className={styles.historyLimit}>\n <span>This chat has reached its {limit}-question limit.</span>\n <button type=\"button\" onClick={onNewChat}>Start new chat</button>\n </div>\n )}\n {(!historyFull || isBusy) && !error && (\n composer !== undefined ? composer : (\n <form className={styles.composerForm} onSubmit={handleFormSubmit}>\n {composerLeading && <div className={styles.composerExtras}>{composerLeading}</div>}\n {onSelectAttachments && (\n <div className={styles.composerExtras}>\n <input\n ref={fileInputRef}\n className={styles.visuallyHidden}\n type=\"file\"\n aria-label=\"Add attachments\"\n accept={attachmentAccept}\n multiple\n disabled={isBusy}\n onChange={(event) => {\n if (event.target.files) onSelectAttachments(event.target.files);\n event.target.value = '';\n }}\n />\n {attachments && attachments.length > 0 && (\n <ul className={styles.attachmentList}>\n {attachments.map((attachment, index) => (\n <li key={index}>\n {attachment.previewUrl ? <img className={styles.attachmentThumbnail} src={attachment.previewUrl} alt={attachment.name} /> : <span className={styles.attachmentFilename}>{attachment.name}</span>}\n {onRemoveAttachment && (\n <button type=\"button\" onClick={() => onRemoveAttachment(index)}\n aria-label={`Remove ${attachment.name}`} title={`Remove ${attachment.name}`}>×</button>\n )}\n </li>\n ))}\n </ul>\n )}\n </div>\n )}\n <div className={styles.composerSurface}>\n <div className={styles.composerRow}>\n {onSelectAttachments && (\n <button type=\"button\" className={styles.composerIconButton}\n aria-label=\"Attach file\" title=\"Attach file\"\n disabled={isBusy} onClick={() => fileInputRef.current?.click()}>\n <svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\"\n strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n <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\" />\n </svg>\n </button>\n )}\n <textarea\n className={styles.input}\n aria-label={inputAriaLabel}\n rows={1}\n value={draft}\n onChange={(event) => onDraftChange?.(event.target.value)}\n onKeyDown={handleKeyDown}\n placeholder={inputPlaceholder}\n maxLength={inputMaxLength}\n disabled={isBusy || !onSend || !onDraftChange}\n readOnly={!onDraftChange}\n />\n <div className={styles.composerActions}>\n {composerTrailing}\n {isBusy ? (\n onStop && <button type=\"button\" className={styles.composerIconButton} onClick={onStop}\n aria-label=\"Stop response\" title=\"Stop response\">\n <svg width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"currentColor\" aria-hidden=\"true\"><rect x=\"5\" y=\"5\" width=\"14\" height=\"14\" rx=\"2\" /></svg>\n </button>\n ) : (\n <button type=\"submit\" className={styles.sendButton} aria-label=\"Send message\"\n title=\"Send message\" disabled={!onSend || (!draft.trim() && !attachments?.length)}>\n <svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\"\n strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><path d=\"M12 19V5m-7 7 7-7 7 7\" /></svg>\n </button>\n )}\n </div>\n </div>\n </div>\n </form>\n )\n )}\n </div>\n </div>\n );\n}\n"],"mappings":";;;;;;;AAmLA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,SAAS,OAAoC;CACpD,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C;AAEA,SAAS,YAAY,OAAoC;CACvD,MAAM,MAAM,SAAS,KAAK;CAC1B,OAAO,OAAO,gBAAgB,KAAK,GAAG,IAAI,MAAM,KAAA;AAClD;AAUA,SAAgB,oBAAoB,EAAE,MAAM,OAAO,UAAU,aAAuC;CAClG,OACE,iBAAA,GAAA,kBAAA,KAAA,CAAC,OAAD;EAAK,WAAW;GAAC,uBAAA,QAAO;GAAe,SAAS,SAAS,uBAAA,QAAO,cAAc,uBAAA,QAAO;GAAkB;EAAS,CAAC,CAC9G,OAAO,OAAO,CAAC,CAAC,KAAK,GAAG;EAAG,aAAW;YADzC,CAEG,SAAS,iBAAA,GAAA,kBAAA,IAAA,CAAC,QAAD;GAAM,WAAW,uBAAA,QAAO;aAAe;EAAY,CAAA,GAC5D,QACE;;AAET;AAEA,SAAS,uBAAuB,EAAE,SAAS,qBAAiD;CAC1F,OACE,iBAAA,GAAA,kBAAA,IAAA,CAAC,qBAAD;EAAqB,MAAM,QAAQ;YAChC,QAAQ,MAAM,KAAK,MAAM,UACxB,iBAAA,GAAA,kBAAA,IAA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AW;WACX,UAAU,UAAU,CAAC,UAAU,CAAC;WAChC,UAAU,CAAC;UACZ,CAAA;UACD,iBAAA,GAAA,kBAAA,KAAA,CAAC,OAAD;WAAK,WAAW,uBAAA,QAAO;qBAAvB,CACG,kBACA,SACC,UAAU,iBAAA,GAAA,kBAAA,IAAA,CAAC,UAAD;YAAQ,MAAK;YAAS,WAAW,uBAAA,QAAO;YAAoB,SAAS;YAC7E,cAAW;YAAgB,OAAM;sBACjC,iBAAA,GAAA,kBAAA,IAAA,CAAC,OAAD;aAAK,OAAM;aAAK,QAAO;aAAK,SAAQ;aAAY,MAAK;aAAe,eAAY;uBAAO,iBAAA,GAAA,kBAAA,IAAA,CAAC,QAAD;cAAM,GAAE;cAAI,GAAE;cAAI,OAAM;cAAK,QAAO;cAAK,IAAG;aAAK,CAAA;YAAM,CAAA;WACxI,CAAA,IAER,iBAAA,GAAA,kBAAA,IAAA,CAAC,UAAD;YAAQ,MAAK;YAAS,WAAW,uBAAA,QAAO;YAAY,cAAW;YAC7D,OAAM;YAAe,UAAU,CAAC,UAAW,CAAC,MAAM,KAAK,KAAK,CAAC,aAAa;sBAC1E,iBAAA,GAAA,kBAAA,IAAA,CAAC,OAAD;aAAK,OAAM;aAAK,QAAO;aAAK,SAAQ;aAAY,MAAK;aAAO,QAAO;aACjE,aAAY;aAAI,eAAc;aAAQ,gBAAe;aAAQ,eAAY;uBAAO,iBAAA,GAAA,kBAAA,IAAA,CAAC,QAAD,EAAM,GAAE,wBAAyB,CAAA;YAAM,CAAA;WACnH,CAAA,CAEP;;SACF;;OACF,CAAA;MACD;;IAGP;;EACF;;AAET"}
1
+ {"version":3,"file":"index85.cjs","names":[],"sources":["../src/components/ai-chat/AIChat.tsx"],"sourcesContent":["'use client';\n\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport type { CSSProperties, ComponentType, FormEvent, KeyboardEvent, ReactNode } from 'react';\n\nimport { AuiConfig, AuiProvider, ThreadPrimitive } from '@assistant-ui/react';\nimport { AISDKChat, AssistantChatTransport, useAISDKChat } from '@assistant-ui/ai-sdk';\n\nimport styles from './ai-chat.module.css';\n\ntype AIChatTransportOptions = NonNullable<ConstructorParameters<typeof AssistantChatTransport>[0]>;\n\nexport interface AIChatProps {\n /** AI SDK UI-message stream endpoint. */\n readonly api: string;\n /** Opaque scope identifier sent to the API. Server must authorize it. */\n readonly scope?: string;\n /** Human-readable display text; never used as an access-control identifier. */\n readonly scopeLabel?: string;\n /** Fetch adapter for authentication, request instrumentation and local demos. */\n readonly fetch?: typeof globalThis.fetch;\n readonly headers?: Record<string, string>;\n readonly credentials?: RequestCredentials;\n /** Customize serialized requests for APIs with a strict request schema. */\n readonly prepareSendMessagesRequest?: AIChatTransportOptions['prepareSendMessagesRequest'];\n /** Change this when the authenticated identity changes to reset the transcript. */\n readonly sessionKey?: string | number;\n /** Maximum number of user turns (default: 8). */\n readonly messageLimit?: number;\n readonly inputPlaceholder?: string;\n /** Accessible name for the message textarea. */\n readonly inputAriaLabel?: string;\n readonly inputMaxLength?: number;\n readonly components?: AIChatComponents;\n /** Actions displayed beside the native New chat control in one shared toolbar. */\n readonly toolbarActions?: ReactNode;\n /** When false, the enclosing AIChatDock owns the New chat control. */\n readonly showNewChatInToolbar?: boolean;\n /** Increment or replace this stable token to request the native New chat flow externally. */\n readonly newChatRequestKey?: string | number;\n /** Opt-in files, restricted to images/text accepted by the application API. */\n readonly attachments?: AIChatAttachmentOptions;\n /** Visible, accessible activity label while the assistant has not started answering. */\n readonly activityLabel?: string;\n /** Human-friendly labels for running tools, keyed by SDK tool name. */\n readonly toolActivityLabels?: Readonly<Record<string, string>>;\n /** Optional persistence; implementations must scope storage by user AND resource. */\n readonly history?: AIChatHistoryAdapter;\n /** Native SDK continuation predicate for tool approvals. */\n readonly sendAutomaticallyWhen?: NonNullable<Parameters<typeof AISDKChat>[0]>['sendAutomaticallyWhen'];\n readonly onClose?: () => void;\n readonly className?: string;\n readonly style?: CSSProperties;\n}\n\n/**\n * Framework-independent presentation contract. The parent owns the runtime,\n * message identities, approvals, uploads, history and security boundaries.\n * Uzi does not serialize, persist or reinterpret any messages supplied here.\n */\nexport type AIChatMessage = AIChatMessageRendererProps['message'];\n\nexport interface AIChatAttachmentOptions {\n readonly accept: string;\n readonly maxFiles?: number;\n readonly maxBytesPerFile?: number;\n}\n\nexport interface AIChatSelectedAttachment {\n readonly name: string;\n readonly size: number;\n /** Local thumbnail URL for supported image files. */\n readonly previewUrl?: string;\n}\n\nexport interface AIChatHistoryAdapter {\n /** Load only validated UI messages from the authenticated principal's own storage. */\n readonly load: () => Promise<readonly AIChatMessage[]> | readonly AIChatMessage[];\n /** Save after complete turns; the consumer decides what metadata is safe. */\n readonly save: (messages: readonly AIChatMessage[]) => Promise<void> | void;\n readonly clear: () => Promise<void> | void;\n /** Observability for failed history operations; never include message payloads in logs. */\n readonly onError?: (operation: 'load' | 'save' | 'clear', error: unknown) => void;\n}\n\nexport type AIChatToolApprovalHandler = (id: string, approved: boolean) => Promise<void> | void;\n\nexport interface AIChatViewProps {\n readonly messages: readonly AIChatMessage[];\n readonly status?: string;\n readonly activityLabel?: string;\n readonly toolActivityLabels?: Readonly<Record<string, string>>;\n readonly error?: Error | null;\n readonly draft?: string;\n readonly onDraftChange?: (draft: string) => void;\n readonly onSend?: () => void;\n readonly onStop?: () => void;\n readonly onRetry?: () => void;\n readonly onNewChat?: () => void;\n /** False when AIChatDock owns the new-chat action in its header. */\n readonly showNewChatInToolbar?: boolean;\n /** No limit by default: specialized apps decide their own session policy. */\n readonly messageLimit?: number;\n readonly inputPlaceholder?: string;\n readonly inputAriaLabel?: string;\n readonly inputMaxLength?: number;\n readonly components?: AIChatComponents;\n readonly attachments?: readonly AIChatSelectedAttachment[];\n readonly onSelectAttachments?: (files: FileList) => void;\n readonly onRemoveAttachment?: (index: number) => void;\n readonly attachmentAccept?: string;\n readonly attachmentError?: string | null;\n /** Only invoked from explicit user action on an approval-requested tool part. */\n readonly onToolApproval?: AIChatToolApprovalHandler;\n /** Custom message toolbar controls, e.g. a conversation selector. */\n readonly toolbarActions?: ReactNode;\n /** Context labels or other app-owned notices above the transcript. */\n readonly header?: ReactNode;\n /** Upload actions, attachment previews or context chips before the input. */\n readonly composerLeading?: ReactNode;\n /** Additional buttons beside the Send/Stop control. */\n readonly composerTrailing?: ReactNode;\n /** Completely replace the composer while retaining shared transcript chrome. */\n readonly composer?: ReactNode;\n readonly emptyState?: ReactNode;\n readonly className?: string;\n readonly style?: CSSProperties;\n}\n\nexport interface AIChatComponents {\n readonly MessageRenderer?: ComponentType<AIChatMessageRendererProps>;\n readonly ReasoningRenderer?: ComponentType<AIChatReasoningRendererProps>;\n readonly SourceRenderer?: ComponentType<AIChatSourceRendererProps>;\n readonly DataRenderer?: ComponentType<AIChatDataRendererProps>;\n readonly ToolRenderer?: ComponentType<AIChatToolRendererProps>;\n readonly ErrorRenderer?: ComponentType<AIChatErrorRendererProps>;\n}\n\nexport interface AIChatMessageRendererProps {\n readonly message: {\n readonly id: string;\n readonly role: 'user' | 'assistant';\n readonly parts: readonly unknown[];\n readonly metadata?: Record<string, unknown>;\n };\n readonly renderMessagePart: (part: Record<string, unknown>, index: number) => ReactNode;\n readonly onToolApproval?: AIChatToolApprovalHandler;\n}\n\nexport interface AIChatReasoningRendererProps {\n readonly children: string;\n readonly title?: string;\n}\n\nexport interface AIChatSource {\n readonly id: string;\n readonly title?: string;\n readonly url?: string;\n}\n\nexport interface AIChatSourceRendererProps {\n readonly sources: readonly AIChatSource[];\n readonly renderSource: (source: AIChatSource, index: number) => ReactNode;\n}\n\nexport interface AIChatDataRendererProps {\n readonly data: readonly Record<string, unknown>[];\n readonly renderDataItem: (item: Record<string, unknown>, index: number) => ReactNode;\n}\n\nexport interface AIChatToolRendererProps {\n readonly part: Record<string, unknown>;\n readonly name: string;\n readonly approvalId?: string;\n readonly onApprove?: () => void;\n readonly onDeny?: () => void;\n readonly approvalPending: boolean;\n}\n\nexport interface AIChatErrorRendererProps {\n readonly error: Error;\n readonly onRetry: () => void;\n readonly onClear: () => void;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction asString(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction safeHttpUrl(value: unknown): string | undefined {\n const url = asString(value);\n return url && /^https?:\\/\\//i.test(url) ? url : undefined;\n}\n\n/** Allow only inert bitmap image data, never script-capable data or blob links from messages. */\nfunction safeImageUrl(value: unknown): string | undefined {\n const url = asString(value);\n return url && (/^https?:\\/\\//i.test(url) || /^data:image\\/(?:png|jpeg|gif|webp|avif);base64,/i.test(url))\n ? url : undefined;\n}\n\nfunction formatAttachmentSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n return bytes < 1024 * 1024 ? `${(bytes / 1024).toFixed(1)} KB` : `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/** Shared attachment surface for built-in Uzi chat and custom SDK runtimes. */\nexport interface AIChatAttachmentPreviewProps {\n readonly name: string;\n readonly size?: number;\n /** HTTP(S), safe bitmap data URI, or a local object URL when staged. */\n readonly imageUrl?: string;\n /** Optional HTTP(S) link for non-image files. */\n readonly href?: string;\n /** Compact composer chip rather than a history attachment. */\n readonly staged?: boolean;\n readonly onRemove?: () => void;\n /** Pass an SDK-owned remove button here when removal must be done by a primitive. */\n readonly removeControl?: ReactNode;\n}\n\n/** The same attachment surface is used for staged files and sent message parts. */\nexport function AIChatAttachmentPreview({ name, size, imageUrl, href, staged, onRemove, removeControl }: AIChatAttachmentPreviewProps) {\n const safePreviewUrl = imageUrl && (safeImageUrl(imageUrl) || (staged && /^blob:/i.test(imageUrl) ? imageUrl : undefined));\n const safeHref = safeHttpUrl(href);\n const dialogRef = useRef<HTMLDialogElement>(null);\n const previewButtonRef = useRef<HTMLButtonElement>(null);\n const [previewOpen, setPreviewOpen] = useState(false);\n\n useEffect(() => {\n if (previewOpen && dialogRef.current && !dialogRef.current.open) dialogRef.current.showModal?.();\n }, [previewOpen]);\n\n return (\n <div className={[styles.attachmentCard, staged ? styles.stagedAttachment : styles.sentAttachment,\n staged && !safePreviewUrl ? styles.stagedFileAttachment : ''].filter(Boolean).join(' ')}>\n {safePreviewUrl ? (\n <button ref={previewButtonRef} type=\"button\" className={styles.imageAttachmentButton}\n onClick={() => setPreviewOpen(true)} aria-label={`Preview ${name}`} title={`Preview ${name}`}>\n <img className={styles.attachmentThumbnail} src={safePreviewUrl} alt={name} loading=\"lazy\" />\n </button>\n ) : (\n <div className={styles.fileAttachment}>\n <svg aria-hidden=\"true\" width=\"22\" height=\"22\" viewBox=\"0 0 24 24\" fill=\"none\"\n stroke=\"currentColor\" strokeWidth=\"1.7\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <path d=\"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8Z\" />\n <path d=\"M14 2v6h6M8 13h8M8 17h5\" />\n </svg>\n <span className={styles.fileAttachmentDetails}>\n {safeHref ? <a href={safeHref} target=\"_blank\" rel=\"noopener noreferrer\" title={name}>{name}</a>\n : <span title={name}>{name}</span>}\n {size !== undefined && <small>{formatAttachmentSize(size)}</small>}\n </span>\n </div>\n )}\n {safePreviewUrl && !staged && <span className={styles.sentAttachmentName} title={name}>{name}</span>}\n {removeControl && <span className={styles.removeAttachmentSlot}>{removeControl}</span>}\n {!removeControl && onRemove && (\n <button type=\"button\" className={styles.removeAttachment} onClick={onRemove}\n aria-label={`Remove ${name}`} title={`Remove ${name}`}>×</button>\n )}\n {previewOpen && safePreviewUrl && (\n <dialog ref={dialogRef} className={styles.attachmentDialog} aria-label={`Preview ${name}`}\n onClose={() => { setPreviewOpen(false); previewButtonRef.current?.focus(); }}\n onClick={(event) => { if (event.target === event.currentTarget) event.currentTarget.close(); }}>\n <div className={styles.attachmentDialogHeader}>\n <span title={name}>{name}</span>\n <button type=\"button\" onClick={() => dialogRef.current?.close()} aria-label=\"Close attachment preview\">×</button>\n </div>\n <img src={safePreviewUrl} alt={name} />\n </dialog>\n )}\n </div>\n );\n}\n\n/** Reusable role-aware message surface for domain renderers. */\nexport interface AIChatMessageBubbleProps {\n readonly role: 'user' | 'assistant';\n readonly label?: string;\n readonly children: ReactNode;\n readonly className?: string;\n}\n\nexport function AIChatMessageBubble({ role, label, children, className }: AIChatMessageBubbleProps) {\n return (\n <div className={[styles.messageBubble, role === 'user' ? styles.userMessage : styles.assistantMessage, className]\n .filter(Boolean).join(' ')} data-role={role}>\n {label && <span className={styles.messageLabel}>{label}</span>}\n {children}\n </div>\n );\n}\n\nfunction DefaultMessageRenderer({ message, renderMessagePart }: AIChatMessageRendererProps) {\n return (\n <AIChatMessageBubble role={message.role}>\n {message.parts.map((part, index) => (\n <div key={isRecord(part) && typeof part.id === 'string' ? part.id : index}>\n {isRecord(part) ? renderMessagePart(part, index) : null}\n </div>\n ))}\n </AIChatMessageBubble>\n );\n}\n\nfunction DefaultReasoningRenderer({ children, title = 'Reasoning' }: AIChatReasoningRendererProps) {\n return (\n <details className={styles.reasoning}>\n <summary className={styles.reasoningSummary}>{title}</summary>\n <p className={styles.reasoningText}>{children}</p>\n </details>\n );\n}\n\nfunction DefaultSourceRenderer({ sources, renderSource }: AIChatSourceRendererProps) {\n return (\n <div className={styles.sources}>\n <span className={styles.sourcesLabel}>Sources</span>\n <ul>\n {sources.map((source, index) => (\n <li key={source.id}>{renderSource(source, index)}</li>\n ))}\n </ul>\n </div>\n );\n}\n\nfunction DefaultDataRenderer({ data, renderDataItem }: AIChatDataRendererProps) {\n return (\n <div className={styles.data}>\n {data.map((item, index) => (\n <div key={index}>{renderDataItem(item, index)}</div>\n ))}\n </div>\n );\n}\n\nfunction DefaultErrorRenderer({ error, onRetry, onClear }: AIChatErrorRendererProps) {\n return (\n <div className={styles.error} role=\"alert\">\n <p>{error.message}</p>\n <div className={styles.errorActions}>\n <button type=\"button\" onClick={onRetry}>Retry response</button>\n <button type=\"button\" onClick={onClear}>Start new chat</button>\n </div>\n </div>\n );\n}\n\nfunction renderPart(\n part: Record<string, unknown>,\n index: number,\n components: AIChatComponents | undefined,\n onToolApproval?: AIChatToolApprovalHandler,\n pendingApprovalId?: string | null,\n): ReactNode {\n const type = asString(part.type) ?? '';\n if (type === 'step-start') return null;\n if (type === 'text') {\n return <span className={styles.textPart}>{asString(part.text) ?? ''}</span>;\n }\n if (type === 'reasoning') {\n const ReasoningRenderer = components?.ReasoningRenderer ?? DefaultReasoningRenderer;\n return <ReasoningRenderer>{asString(part.text) ?? ''}</ReasoningRenderer>;\n }\n if (type === 'source-url' || type === 'source-document') {\n const SourceRenderer = components?.SourceRenderer ?? DefaultSourceRenderer;\n const source: AIChatSource = {\n id: asString(part.sourceId) ?? asString(part.id) ?? `source-${index}`,\n title: asString(part.title) ?? asString(part.filename),\n url: safeHttpUrl(part.url),\n };\n return (\n <SourceRenderer\n sources={[source]}\n renderSource={(item) => item.url ? (\n <a href={item.url} target=\"_blank\" rel=\"noopener noreferrer\">\n {item.title ?? item.url}\n </a>\n ) : <span>{item.title ?? item.id}</span>}\n />\n );\n }\n if (type.startsWith('data-')) {\n const DataRenderer = components?.DataRenderer ?? DefaultDataRenderer;\n return (\n <DataRenderer\n data={[part]}\n renderDataItem={(item) => (\n <pre className={styles.structuredData}>{JSON.stringify(item.data ?? item, null, 2)}</pre>\n )}\n />\n );\n }\n if (type.startsWith('tool-') || type === 'dynamic-tool') {\n const name = asString(part.toolName) ?? type.replace(/^tool-/, '');\n const approval = isRecord(part.approval) ? asString(part.approval.id) : undefined;\n const approvalId = part.state === 'approval-requested' ? approval : undefined;\n const controlsDisabled = pendingApprovalId !== null && pendingApprovalId !== undefined;\n const ToolRenderer = components?.ToolRenderer;\n const props: AIChatToolRendererProps = {\n part, name, approvalId,\n approvalPending: controlsDisabled,\n ...(approvalId && onToolApproval ? {\n onApprove: () => { if (!controlsDisabled) void onToolApproval(approvalId, true); },\n onDeny: () => { if (!controlsDisabled) void onToolApproval(approvalId, false); },\n } : {}),\n };\n if (ToolRenderer) return <ToolRenderer {...props} />;\n return (\n <div className={styles.toolPart}>\n <details>\n <summary>{name}</summary>\n <pre className={styles.structuredData}>\n {JSON.stringify(part.output ?? part.input ?? part, null, 2)}\n </pre>\n </details>\n {approvalId && (\n <div className={styles.approvalActions} aria-label={`Approval required for ${name}`}>\n {props.onApprove && props.onDeny ? (\n <>\n <button type=\"button\" disabled={controlsDisabled} onClick={props.onApprove}>Approve</button>\n <button type=\"button\" disabled={controlsDisabled} onClick={props.onDeny}>Deny</button>\n </>\n ) : <span>Approval required in application</span>}\n </div>\n )}\n </div>\n );\n }\n if (type === 'file' || type === 'image') {\n const name = asString(part.filename) ?? asString(part.name) ?? 'Attachment';\n const mediaType = asString(part.mediaType) ?? asString(part.mimeType);\n const isImage = type === 'image' || /^image\\/(?:png|jpeg|gif|webp|avif)$/i.test(mediaType ?? '')\n || /\\.(?:png|jpe?g|gif|webp|avif)$/i.test(name);\n const imageUrl = isImage ? safeImageUrl(part.url) : undefined;\n return <AIChatAttachmentPreview name={name} imageUrl={imageUrl} href={safeHttpUrl(part.url)}\n size={typeof part.size === 'number' && part.size >= 0 ? part.size : undefined} />;\n }\n // Preserve unsupported part types as inspectable data instead of silently dropping them.\n return <pre className={styles.structuredData}>{JSON.stringify(part, null, 2)}</pre>;\n}\n\nconst DEFAULT_MESSAGE_LIMIT = 8;\n\nexport function AIChat({\n api,\n scope,\n scopeLabel,\n fetch: requestFetch,\n headers,\n credentials,\n prepareSendMessagesRequest,\n sessionKey,\n messageLimit = DEFAULT_MESSAGE_LIMIT,\n inputPlaceholder = 'Ask a question...',\n inputAriaLabel = 'Message',\n inputMaxLength = 2000,\n components,\n toolbarActions,\n showNewChatInToolbar = true,\n newChatRequestKey,\n attachments,\n activityLabel,\n toolActivityLabels,\n history,\n sendAutomaticallyWhen,\n onClose,\n className,\n style,\n}: AIChatProps) {\n // Remounting the provider creates a fresh AI SDK chat id, not merely an empty transcript.\n const [session, setSession] = useState(0);\n const transport = useMemo(\n () => new AssistantChatTransport({\n api,\n // The transport merges this with the AI SDK messages, id, model context and tools.\n // The endpoint, not the presentation component, must enforce the scope.\n ...(scope ? { body: { scope } } : {}),\n ...(requestFetch ? { fetch: requestFetch } : {}),\n ...(headers ? { headers } : {}),\n ...(credentials ? { credentials } : {}),\n ...(prepareSendMessagesRequest ? { prepareSendMessagesRequest } : {}),\n }),\n [api, scope, requestFetch, headers, credentials, prepareSendMessagesRequest],\n );\n const config = useMemo(\n () => AuiConfig({ threads: AISDKChat({ transport, ...(sendAutomaticallyWhen ? { sendAutomaticallyWhen } : {}) }) }),\n [transport, session, sendAutomaticallyWhen],\n );\n\n return (\n <div className={[styles.container, className].filter(Boolean).join(' ')} style={style}>\n {scopeLabel && (\n <div className={styles.scope}>\n <span className={styles.scopeLabel}>Current scope</span>\n <strong>{scopeLabel}</strong>\n </div>\n )}\n {onClose && (\n <button className={styles.closeBtn} type=\"button\" onClick={onClose} aria-label=\"Close chat\">\n &#x2715;\n </button>\n )}\n <AuiProvider key={JSON.stringify([api, scope, sessionKey, session])} config={config}>\n <ThreadPrimitive.Root className={styles.thread}>\n <ChatViewport\n messageLimit={Number.isFinite(messageLimit) ? Math.max(1, Math.floor(messageLimit)) : DEFAULT_MESSAGE_LIMIT}\n inputPlaceholder={inputPlaceholder}\n inputAriaLabel={inputAriaLabel}\n inputMaxLength={inputMaxLength}\n components={components}\n toolbarActions={toolbarActions}\n showNewChatInToolbar={showNewChatInToolbar}\n newChatRequestKey={newChatRequestKey}\n attachmentOptions={attachments}\n activityLabel={activityLabel}\n toolActivityLabels={toolActivityLabels}\n history={history}\n onNewChat={() => setSession((previous) => previous + 1)}\n />\n </ThreadPrimitive.Root>\n </AuiProvider>\n </div>\n );\n}\n\ninterface ChatViewportProps {\n readonly messageLimit: number;\n readonly inputPlaceholder: string;\n readonly inputAriaLabel: string;\n readonly inputMaxLength: number;\n readonly components?: AIChatComponents;\n readonly toolbarActions?: ReactNode;\n readonly showNewChatInToolbar?: boolean;\n readonly newChatRequestKey?: string | number;\n readonly attachmentOptions?: AIChatAttachmentOptions;\n readonly activityLabel?: string;\n readonly toolActivityLabels?: Readonly<Record<string, string>>;\n readonly history?: AIChatHistoryAdapter;\n readonly onNewChat: () => void;\n}\n\nfunction ChatViewport({\n messageLimit,\n inputPlaceholder,\n inputAriaLabel,\n inputMaxLength,\n components,\n toolbarActions,\n showNewChatInToolbar,\n newChatRequestKey,\n attachmentOptions,\n activityLabel,\n toolActivityLabels,\n history,\n onNewChat,\n}: ChatViewportProps) {\n const chat = useAISDKChat();\n const [draft, setDraft] = useState('');\n const [selectedFiles, setSelectedFiles] = useState<File[]>([]);\n const [attachmentError, setAttachmentError] = useState<string | null>(null);\n const [attachmentPreviews, setAttachmentPreviews] = useState<string[]>([]);\n const [hydrated, setHydrated] = useState(!history);\n const expectedRestoredId = useRef<string | null>(null);\n const saveQueue = useRef<Promise<void>>(Promise.resolve());\n const [approvalBusy, setApprovalBusy] = useState(false);\n useEffect(() => {\n const urls = selectedFiles.map((file) => file.type.startsWith('image/') && typeof URL.createObjectURL === 'function' ? URL.createObjectURL(file) : '');\n setAttachmentPreviews(urls);\n return () => urls.forEach((url) => { if (url && typeof URL.revokeObjectURL === 'function') URL.revokeObjectURL(url); });\n }, [selectedFiles]);\n const messages = chat?.messages ?? [];\n const status = chat?.status ?? 'ready';\n const isBusy = status === 'submitted' || status === 'streaming';\n const historyFull = messages.filter((message) => message.role === 'user').length >= messageLimit;\n const reportHistoryError = (operation: 'load' | 'save' | 'clear', error: unknown) => {\n if (history?.onError) history.onError(operation, error);\n else console.warn(`[Uzi AIChat] History ${operation} failed`);\n };\n // Persist only complete turns. Do not save an empty runtime over stored history\n // during hydration or while a response is still streaming.\n useEffect(() => {\n if (!history) return;\n let active = true;\n void Promise.resolve().then(() => history.load()).then((restored) => {\n if (!active) return;\n if (Array.isArray(restored)) {\n const valid = restored.filter((message) =>\n typeof message?.id === 'string' &&\n (message.role === 'user' || message.role === 'assistant') &&\n Array.isArray(message.parts));\n expectedRestoredId.current = valid.length ? valid[0].id : null;\n if (valid.length) chat?.setMessages(valid as Parameters<NonNullable<typeof chat>['setMessages']>[0]);\n }\n setHydrated(true);\n }).catch((error: unknown) => {\n if (active) {\n reportHistoryError('load', error);\n setHydrated(true);\n }\n });\n return () => { active = false; };\n }, [chat?.setMessages, history]);\n\n useEffect(() => {\n if (!history || !hydrated || isBusy) return;\n const snapshot = messages.filter((message) => message.role === 'user' || message.role === 'assistant').map((message) => ({\n id: message.id, role: message.role as 'user' | 'assistant', parts: message.parts,\n ...(isRecord(message.metadata) ? { metadata: message.metadata } : {}),\n }));\n // Guard against the transient empty SDK state between history.load and\n // setMessages propagation; otherwise an old transcript could be erased.\n if (expectedRestoredId.current) {\n if (!snapshot.some((message) => message.id === expectedRestoredId.current)) return;\n expectedRestoredId.current = null;\n }\n // Serialize writes. New Chat waits for in-flight writes before clearing.\n saveQueue.current = saveQueue.current.then(\n () => history.save(snapshot),\n () => history.save(snapshot),\n ).then(\n () => {},\n (error: unknown) => { reportHistoryError('save', error); },\n );\n }, [history, hydrated, isBusy, messages]);\n\n const handleSelectedFiles = (files: FileList) => {\n if (!attachmentOptions) return;\n const selected = Array.from(files);\n if (selected.length + selectedFiles.length > (attachmentOptions.maxFiles ?? 3)) {\n setAttachmentError('Too many attachments.');\n return;\n }\n if (selected.some((file) => file.size > (attachmentOptions.maxBytesPerFile ?? 5 * 1024 * 1024))) {\n setAttachmentError('An attachment exceeds the size limit.');\n return;\n }\n const allowedTypes = attachmentOptions.accept.split(',').map((item) => item.trim());\n if (selected.some((file) => !allowedTypes.some((allow) => (\n allow === file.type || (allow.endsWith('/*') && file.type.startsWith(allow.slice(0, -1)))\n )))) {\n setAttachmentError('Unsupported attachment type.');\n return;\n }\n setAttachmentError(null);\n setSelectedFiles((existing) => [...existing, ...selected]);\n };\n\n const handleSubmit = () => {\n const text = draft.trim();\n if (!chat || (!text && selectedFiles.length === 0) || isBusy || historyFull || chat.error || !hydrated || approvalBusy) return;\n const files = selectedFiles.length ? new DataTransfer() : null;\n selectedFiles.forEach((file) => files?.items.add(file));\n // AI SDK serializes FileList to FileUIParts and sends them through the\n // app-owned transport. The server MUST validate types and sizes again.\n // Clear the composer promptly; restore the draft and files if submission\n // fails, so users do not lose attachments or typed content.\n const previousDraft = draft;\n const previousFiles = selectedFiles;\n setDraft('');\n setSelectedFiles([]);\n setAttachmentError(null);\n void Promise.resolve(chat.sendMessage({ text, ...(files ? { files: files.files } : {}) }))\n .catch(() => {\n setDraft((current) => current || previousDraft);\n setSelectedFiles((current) => current.length ? current : previousFiles);\n });\n };\n\n const handleNewChat = () => {\n void (async () => {\n await chat?.stop();\n if (history) {\n try {\n await saveQueue.current;\n await history.clear();\n } catch (error) {\n reportHistoryError('clear', error);\n return;\n }\n }\n onNewChat();\n })();\n };\n\n // An enclosing dock can reuse the native reset path without duplicating\n // history deletion, aborts, or SDK session management in each consumer.\n const lastNewChatRequestKey = useRef(newChatRequestKey);\n useEffect(() => {\n if (lastNewChatRequestKey.current === newChatRequestKey) return;\n lastNewChatRequestKey.current = newChatRequestKey;\n handleNewChat();\n }, [newChatRequestKey]);\n\n const handleRetry = () => {\n if (!chat || isBusy) return;\n chat.clearError();\n void chat.regenerate();\n };\n\n return (\n <AIChatView\n messages={messages.filter((message) => message.role === 'user' || message.role === 'assistant').map((message) => ({\n id: message.id,\n role: message.role as 'user' | 'assistant',\n parts: message.parts,\n ...(isRecord(message.metadata) ? { metadata: message.metadata } : {}),\n }))}\n status={status}\n activityLabel={activityLabel}\n toolActivityLabels={toolActivityLabels}\n error={chat?.error}\n draft={draft}\n onDraftChange={setDraft}\n onSend={handleSubmit}\n onStop={() => { void chat?.stop(); }}\n onRetry={handleRetry}\n onNewChat={handleNewChat}\n showNewChatInToolbar={showNewChatInToolbar}\n toolbarActions={toolbarActions}\n messageLimit={messageLimit}\n attachments={selectedFiles.map((file, index) => ({ name: file.name, size: file.size, ...(attachmentPreviews[index] ? { previewUrl: attachmentPreviews[index] } : {}) }))}\n onSelectAttachments={attachmentOptions ? handleSelectedFiles : undefined}\n onRemoveAttachment={attachmentOptions ? (index) => setSelectedFiles((files) => files.filter((_, i) => i !== index)) : undefined}\n attachmentAccept={attachmentOptions?.accept}\n attachmentError={attachmentError}\n onToolApproval={chat ? async (id, approved) => {\n if (approvalBusy) return;\n setApprovalBusy(true);\n try { await chat.addToolApprovalResponse({ id, approved, ...(!approved ? { reason: 'User denied approval' } : {}) }); }\n finally { setApprovalBusy(false); }\n } : undefined}\n inputPlaceholder={inputPlaceholder}\n inputAriaLabel={inputAriaLabel}\n inputMaxLength={inputMaxLength}\n components={components}\n />\n );\n}\n\n/**\n * Controlled chat presentation for apps with their own AI SDK/assistant-ui\n * runtime. It does not create providers, transports or chat state. Callbacks\n * are the only way messages/actions leave the view.\n */\nexport function AIChatView({\n messages,\n status = 'ready',\n activityLabel = 'Working on your response…',\n toolActivityLabels,\n error,\n draft = '',\n onDraftChange,\n onSend,\n onStop,\n onRetry,\n onNewChat,\n showNewChatInToolbar = true,\n messageLimit,\n inputPlaceholder = 'Ask a question...',\n inputAriaLabel = 'Message',\n inputMaxLength = 2000,\n components,\n attachments,\n onSelectAttachments,\n onRemoveAttachment,\n attachmentAccept,\n attachmentError,\n onToolApproval,\n toolbarActions,\n header,\n composerLeading,\n composerTrailing,\n composer,\n emptyState,\n className,\n style,\n}: AIChatViewProps) {\n const viewportRef = useRef<HTMLDivElement>(null);\n const pinnedToBottom = useRef(true);\n const fileInputRef = useRef<HTMLInputElement>(null);\n const approvalRef = useRef<string | null>(null);\n const [pendingApprovalId, setPendingApprovalId] = useState<string | null>(null);\n const [approvalError, setApprovalError] = useState<string | null>(null);\n const respondToApproval: AIChatToolApprovalHandler = async (id, approved) => {\n if (!onToolApproval || approvalRef.current) return;\n approvalRef.current = id;\n setPendingApprovalId(id);\n setApprovalError(null);\n try { await onToolApproval(id, approved); }\n catch { setApprovalError('Could not submit approval. Please try again.'); }\n finally { approvalRef.current = null; setPendingApprovalId(null); }\n };\n const isBusy = status === 'submitted' || status === 'streaming';\n const lastMessage = messages[messages.length - 1];\n const assistantParts = lastMessage?.role === 'assistant' ? lastMessage.parts.filter(isRecord) : [];\n const lastPart = [...assistantParts].reverse().find((part) => part.type !== 'step-start');\n const lastPartType = asString(lastPart?.type) ?? '';\n const activeTool = (lastPartType.startsWith('tool-') || lastPartType === 'dynamic-tool')\n && lastPart?.state !== 'output-available' && lastPart?.state !== 'output-error'\n ? lastPart : undefined;\n const hasAnswer = assistantParts.some((part) => part.type === 'text' && Boolean(asString(part.text)?.trim()));\n const showActivity = isBusy && (!hasAnswer || Boolean(activeTool));\n const toolName = asString(activeTool?.toolName) ?? lastPartType.replace(/^tool-/, '');\n const currentActivityLabel = activeTool?.state === 'approval-requested' ? 'Waiting for approval…'\n : activeTool ? (toolActivityLabels?.[toolName] ?? 'Using a tool…') : activityLabel;\n const limit = messageLimit != null && Number.isFinite(messageLimit)\n ? Math.max(1, Math.floor(messageLimit)) : null;\n const historyFull = limit !== null && messages.filter((message) => message.role === 'user').length >= limit;\n const MessageRenderer = components?.MessageRenderer ?? DefaultMessageRenderer;\n const ErrorRenderer = components?.ErrorRenderer ?? DefaultErrorRenderer;\n\n // Follow streaming text only if the user is already near the bottom.\n useEffect(() => {\n const viewport = viewportRef.current;\n if (viewport && pinnedToBottom.current) viewport.scrollTop = viewport.scrollHeight;\n });\n\n const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key === 'Enter' && !event.shiftKey && !event.nativeEvent.isComposing) {\n event.preventDefault();\n if (!isBusy && !historyFull && !error && (draft.trim() || (attachments?.length ?? 0) > 0)) onSend?.();\n }\n };\n\n const handleFormSubmit = (event: FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n if (!isBusy && !historyFull && !error && (draft.trim() || (attachments?.length ?? 0) > 0)) onSend?.();\n };\n\n return (\n <div className={[styles.thread, className].filter(Boolean).join(' ')} style={style}>\n {header}\n {(toolbarActions || (showNewChatInToolbar && onNewChat && messages.length > 0)) && (\n <div className={styles.chatToolbar} role=\"toolbar\" aria-label=\"Conversation actions\">\n <div className={styles.chatToolbarExtras}>{toolbarActions}</div>\n {showNewChatInToolbar && onNewChat && messages.length > 0 && (\n <button\n type=\"button\"\n className={styles.newChatButton}\n onClick={onNewChat}\n aria-label=\"New chat\"\n title=\"New chat\"\n >\n <svg aria-hidden=\"true\" width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"none\"\n stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <path d=\"M12 5H6a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2v-6\" />\n <path d=\"m15 5 4 4M13 11l7-7a2.12 2.12 0 0 1 3 3l-7 7-4 1 1-4Z\" transform=\"translate(-2 -2)\" />\n </svg>\n </button>\n )}\n </div>\n )}\n <div\n ref={viewportRef}\n className={styles.viewport}\n onScroll={(event) => {\n const viewport = event.currentTarget;\n pinnedToBottom.current = viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight < 80;\n }}\n >\n <div className={styles.messageList} role=\"log\" aria-label=\"Chat history\" aria-live=\"polite\">\n {messages.length === 0 && (\n <div className={styles.emptyState}>\n {emptyState ?? <p>Start a conversation</p>}\n </div>\n )}\n {messages.map((message) => (\n <MessageRenderer\n key={message.id}\n message={message}\n renderMessagePart={(part, index) => renderPart(part, index, components, onToolApproval ? respondToApproval : undefined, pendingApprovalId)}\n onToolApproval={onToolApproval ? respondToApproval : undefined}\n />\n ))}\n {showActivity && (\n <div className={styles.activityBubble} role=\"status\" aria-label={currentActivityLabel}>\n <span className={styles.activityDots} aria-hidden=\"true\"><i /><i /><i /></span>\n <span>{currentActivityLabel}</span>\n </div>\n )}\n </div>\n </div>\n <div className={styles.footer}>\n {approvalError && <p role=\"alert\" className={styles.attachmentError}>{approvalError}</p>}\n {attachmentError && <p role=\"alert\" className={styles.attachmentError}>{attachmentError}</p>}\n {error && (\n onRetry && onNewChat ? (\n <ErrorRenderer error={error} onRetry={onRetry} onClear={onNewChat} />\n ) : (\n <div className={styles.error} role=\"alert\">\n <p>{error.message}</p>\n {(onRetry || onNewChat) && (\n <div className={styles.errorActions}>\n {onRetry && <button type=\"button\" onClick={onRetry}>Retry response</button>}\n {onNewChat && <button type=\"button\" onClick={onNewChat}>Start new chat</button>}\n </div>\n )}\n </div>\n )\n )}\n {historyFull && !error && !isBusy && onNewChat && (\n <div className={styles.historyLimit}>\n <span>This chat has reached its {limit}-question limit.</span>\n <button type=\"button\" onClick={onNewChat}>Start new chat</button>\n </div>\n )}\n {(!historyFull || isBusy) && !error && (\n composer !== undefined ? composer : (\n <form className={styles.composerForm} onSubmit={handleFormSubmit}>\n {composerLeading && <div className={styles.composerExtras}>{composerLeading}</div>}\n {onSelectAttachments && (\n <input\n ref={fileInputRef}\n className={styles.visuallyHidden}\n type=\"file\"\n aria-label=\"Add attachments\"\n accept={attachmentAccept}\n multiple\n disabled={isBusy}\n onChange={(event) => {\n if (event.target.files) onSelectAttachments(event.target.files);\n event.target.value = '';\n }}\n />\n )}\n {attachments && attachments.length > 0 && (\n <div className={styles.composerExtras}>\n <ul className={styles.attachmentList} aria-label=\"Attached files\">\n {attachments.map((attachment, index) => (\n <li key={index}>\n <AIChatAttachmentPreview name={attachment.name} size={attachment.size} staged\n imageUrl={attachment.previewUrl}\n onRemove={onRemoveAttachment ? () => onRemoveAttachment(index) : undefined} />\n </li>\n ))}\n </ul>\n </div>\n )}\n <div className={styles.composerSurface}>\n <div className={styles.composerRow}>\n {onSelectAttachments && (\n <button type=\"button\" className={styles.composerIconButton}\n aria-label=\"Attach file\" title=\"Attach file\"\n disabled={isBusy} onClick={() => fileInputRef.current?.click()}>\n <svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\"\n strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n <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\" />\n </svg>\n </button>\n )}\n <textarea\n className={styles.input}\n aria-label={inputAriaLabel}\n rows={1}\n value={draft}\n onChange={(event) => onDraftChange?.(event.target.value)}\n onKeyDown={handleKeyDown}\n placeholder={inputPlaceholder}\n maxLength={inputMaxLength}\n disabled={isBusy || !onSend || !onDraftChange}\n readOnly={!onDraftChange}\n />\n <div className={styles.composerActions}>\n {composerTrailing}\n {isBusy ? (\n onStop && <button type=\"button\" className={styles.composerIconButton} onClick={onStop}\n aria-label=\"Stop response\" title=\"Stop response\">\n <svg width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"currentColor\" aria-hidden=\"true\"><rect x=\"5\" y=\"5\" width=\"14\" height=\"14\" rx=\"2\" /></svg>\n </button>\n ) : (\n <button type=\"submit\" className={styles.sendButton} aria-label=\"Send message\"\n title=\"Send message\" disabled={!onSend || (!draft.trim() && !attachments?.length)}>\n <svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\"\n strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><path d=\"M12 19V5m-7 7 7-7 7 7\" /></svg>\n </button>\n )}\n </div>\n </div>\n </div>\n </form>\n )\n )}\n </div>\n </div>\n );\n}\n"],"mappings":";;;;;;;AAyLA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,SAAS,OAAoC;CACpD,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C;AAEA,SAAS,YAAY,OAAoC;CACvD,MAAM,MAAM,SAAS,KAAK;CAC1B,OAAO,OAAO,gBAAgB,KAAK,GAAG,IAAI,MAAM,KAAA;AAClD;;AAGA,SAAS,aAAa,OA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