@tomny-dev/uzi 0.18.1-pr.128.433.1.911cffa → 0.18.1

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/index84.js CHANGED
@@ -15,113 +15,6 @@ 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 ChatAttachment({ name, size, imageUrl, href, staged, onRemove }) {
29
- const dialogRef = useRef(null);
30
- const previewButtonRef = useRef(null);
31
- const [previewOpen, setPreviewOpen] = useState(false);
32
- useEffect(() => {
33
- if (previewOpen && dialogRef.current && !dialogRef.current.open) dialogRef.current.showModal?.();
34
- }, [previewOpen]);
35
- return /* @__PURE__ */ jsxs("div", {
36
- className: [
37
- ai_chat_module_default.attachmentCard,
38
- staged ? ai_chat_module_default.stagedAttachment : ai_chat_module_default.sentAttachment,
39
- staged && !imageUrl ? ai_chat_module_default.stagedFileAttachment : ""
40
- ].filter(Boolean).join(" "),
41
- children: [
42
- imageUrl ? /* @__PURE__ */ jsx("button", {
43
- ref: previewButtonRef,
44
- type: "button",
45
- className: ai_chat_module_default.imageAttachmentButton,
46
- onClick: () => setPreviewOpen(true),
47
- "aria-label": `Preview ${name}`,
48
- title: `Preview ${name}`,
49
- children: /* @__PURE__ */ jsx("img", {
50
- className: ai_chat_module_default.attachmentThumbnail,
51
- src: imageUrl,
52
- alt: name,
53
- loading: "lazy"
54
- })
55
- }) : /* @__PURE__ */ jsxs("div", {
56
- className: ai_chat_module_default.fileAttachment,
57
- children: [/* @__PURE__ */ jsxs("svg", {
58
- "aria-hidden": "true",
59
- width: "22",
60
- height: "22",
61
- viewBox: "0 0 24 24",
62
- fill: "none",
63
- stroke: "currentColor",
64
- strokeWidth: "1.7",
65
- strokeLinecap: "round",
66
- strokeLinejoin: "round",
67
- children: [/* @__PURE__ */ jsx("path", { d: "M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8Z" }), /* @__PURE__ */ jsx("path", { d: "M14 2v6h6M8 13h8M8 17h5" })]
68
- }), /* @__PURE__ */ jsxs("span", {
69
- className: ai_chat_module_default.fileAttachmentDetails,
70
- children: [href ? /* @__PURE__ */ jsx("a", {
71
- href,
72
- target: "_blank",
73
- rel: "noopener noreferrer",
74
- title: name,
75
- children: name
76
- }) : /* @__PURE__ */ jsx("span", {
77
- title: name,
78
- children: name
79
- }), size !== void 0 && /* @__PURE__ */ jsx("small", { children: formatAttachmentSize(size) })]
80
- })]
81
- }),
82
- imageUrl && !staged && /* @__PURE__ */ jsx("span", {
83
- className: ai_chat_module_default.sentAttachmentName,
84
- title: name,
85
- children: name
86
- }),
87
- onRemove && /* @__PURE__ */ jsx("button", {
88
- type: "button",
89
- className: ai_chat_module_default.removeAttachment,
90
- onClick: onRemove,
91
- "aria-label": `Remove ${name}`,
92
- title: `Remove ${name}`,
93
- children: "×"
94
- }),
95
- previewOpen && imageUrl && /* @__PURE__ */ jsxs("dialog", {
96
- ref: dialogRef,
97
- className: ai_chat_module_default.attachmentDialog,
98
- "aria-label": `Preview ${name}`,
99
- onClose: () => {
100
- setPreviewOpen(false);
101
- previewButtonRef.current?.focus();
102
- },
103
- onClick: (event) => {
104
- if (event.target === event.currentTarget) event.currentTarget.close();
105
- },
106
- children: [/* @__PURE__ */ jsxs("div", {
107
- className: ai_chat_module_default.attachmentDialogHeader,
108
- children: [/* @__PURE__ */ jsx("span", {
109
- title: name,
110
- children: name
111
- }), /* @__PURE__ */ jsx("button", {
112
- type: "button",
113
- onClick: () => dialogRef.current?.close(),
114
- "aria-label": "Close attachment preview",
115
- children: "×"
116
- })]
117
- }), /* @__PURE__ */ jsx("img", {
118
- src: imageUrl,
119
- alt: name
120
- })]
121
- })
122
- ]
123
- });
124
- }
125
18
  function AIChatMessageBubble({ role, label, children, className }) {
126
19
  return /* @__PURE__ */ jsxs("div", {
127
20
  className: [
@@ -259,14 +152,13 @@ function renderPart(part, index, components, onToolApproval, pendingApprovalId)
259
152
  });
260
153
  }
261
154
  if (type === "file" || type === "image") {
262
- const name = asString(part.filename) ?? asString(part.name) ?? "Attachment";
263
- const mediaType = asString(part.mediaType) ?? asString(part.mimeType);
264
- return /* @__PURE__ */ jsx(ChatAttachment, {
265
- name,
266
- 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,
267
- href: safeHttpUrl(part.url),
268
- size: typeof part.size === "number" && part.size >= 0 ? part.size : void 0
269
- });
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" });
270
162
  }
271
163
  return /* @__PURE__ */ jsx("pre", {
272
164
  className: ai_chat_module_default.structuredData,
@@ -274,7 +166,7 @@ function renderPart(part, index, components, onToolApproval, pendingApprovalId)
274
166
  });
275
167
  }
276
168
  var DEFAULT_MESSAGE_LIMIT = 8;
277
- 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 }) {
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 }) {
278
170
  const [session, setSession] = useState(0);
279
171
  const transport = useMemo(() => new AssistantChatTransport({
280
172
  api,
@@ -331,8 +223,6 @@ function AIChat({ api, scope, scopeLabel, fetch: requestFetch, headers, credenti
331
223
  showNewChatInToolbar,
332
224
  newChatRequestKey,
333
225
  attachmentOptions: attachments,
334
- activityLabel,
335
- toolActivityLabels,
336
226
  history,
337
227
  onNewChat: () => setSession((previous) => previous + 1)
338
228
  })
@@ -346,7 +236,7 @@ function AIChat({ api, scope, scopeLabel, fetch: requestFetch, headers, credenti
346
236
  ]
347
237
  });
348
238
  }
349
- function ChatViewport({ messageLimit, inputPlaceholder, inputAriaLabel, inputMaxLength, components, toolbarActions, showNewChatInToolbar, newChatRequestKey, attachmentOptions, activityLabel, toolActivityLabels, history, onNewChat }) {
239
+ function ChatViewport({ messageLimit, inputPlaceholder, inputAriaLabel, inputMaxLength, components, toolbarActions, showNewChatInToolbar, newChatRequestKey, attachmentOptions, history, onNewChat }) {
350
240
  const chat = useAISDKChat();
351
241
  const [draft, setDraft] = useState("");
352
242
  const [selectedFiles, setSelectedFiles] = useState([]);
@@ -482,8 +372,6 @@ function ChatViewport({ messageLimit, inputPlaceholder, inputAriaLabel, inputMax
482
372
  ...isRecord(message.metadata) ? { metadata: message.metadata } : {}
483
373
  })),
484
374
  status,
485
- activityLabel,
486
- toolActivityLabels,
487
375
  error: chat?.error,
488
376
  draft,
489
377
  onDraftChange: setDraft,
@@ -529,7 +417,7 @@ function ChatViewport({ messageLimit, inputPlaceholder, inputAriaLabel, inputMax
529
417
  * runtime. It does not create providers, transports or chat state. Callbacks
530
418
  * are the only way messages/actions leave the view.
531
419
  */
532
- 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 }) {
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 }) {
533
421
  const viewportRef = useRef(null);
534
422
  const pinnedToBottom = useRef(true);
535
423
  const fileInputRef = useRef(null);
@@ -551,15 +439,6 @@ function AIChatView({ messages, status = "ready", activityLabel = "Working on yo
551
439
  }
552
440
  };
553
441
  const isBusy = status === "submitted" || status === "streaming";
554
- const lastMessage = messages[messages.length - 1];
555
- const assistantParts = lastMessage?.role === "assistant" ? lastMessage.parts.filter(isRecord) : [];
556
- const lastPart = [...assistantParts].reverse().find((part) => part.type !== "step-start");
557
- const lastPartType = asString(lastPart?.type) ?? "";
558
- const activeTool = (lastPartType.startsWith("tool-") || lastPartType === "dynamic-tool") && lastPart?.state !== "output-available" && lastPart?.state !== "output-error" ? lastPart : void 0;
559
- const hasAnswer = assistantParts.some((part) => part.type === "text" && Boolean(asString(part.text)?.trim()));
560
- const showActivity = isBusy && (!hasAnswer || Boolean(activeTool));
561
- const toolName = asString(activeTool?.toolName) ?? lastPartType.replace(/^tool-/, "");
562
- const currentActivityLabel = activeTool?.state === "approval-requested" ? "Waiting for approval…" : activeTool ? toolActivityLabels?.[toolName] ?? "Using a tool…" : activityLabel;
563
442
  const limit = messageLimit != null && Number.isFinite(messageLimit) ? Math.max(1, Math.floor(messageLimit)) : null;
564
443
  const historyFull = limit !== null && messages.filter((message) => message.role === "user").length >= limit;
565
444
  const MessageRenderer = components?.MessageRenderer ?? DefaultMessageRenderer;
@@ -635,19 +514,9 @@ function AIChatView({ messages, status = "ready", activityLabel = "Working on yo
635
514
  renderMessagePart: (part, index) => renderPart(part, index, components, onToolApproval ? respondToApproval : void 0, pendingApprovalId),
636
515
  onToolApproval: onToolApproval ? respondToApproval : void 0
637
516
  }, message.id)),
638
- showActivity && /* @__PURE__ */ jsxs("div", {
639
- className: ai_chat_module_default.activityBubble,
640
- role: "status",
641
- "aria-label": currentActivityLabel,
642
- children: [/* @__PURE__ */ jsxs("span", {
643
- className: ai_chat_module_default.activityDots,
644
- "aria-hidden": "true",
645
- children: [
646
- /* @__PURE__ */ jsx("i", {}),
647
- /* @__PURE__ */ jsx("i", {}),
648
- /* @__PURE__ */ jsx("i", {})
649
- ]
650
- }), /* @__PURE__ */ jsx("span", { children: currentActivityLabel })]
517
+ isBusy && /* @__PURE__ */ jsx("p", {
518
+ className: ai_chat_module_default.status,
519
+ children: "Thinking..."
651
520
  })
652
521
  ]
653
522
  })
@@ -705,32 +574,37 @@ function AIChatView({ messages, status = "ready", activityLabel = "Working on yo
705
574
  className: ai_chat_module_default.composerExtras,
706
575
  children: composerLeading
707
576
  }),
708
- onSelectAttachments && /* @__PURE__ */ jsx("input", {
709
- ref: fileInputRef,
710
- className: ai_chat_module_default.visuallyHidden,
711
- type: "file",
712
- "aria-label": "Add attachments",
713
- accept: attachmentAccept,
714
- multiple: true,
715
- disabled: isBusy,
716
- onChange: (event) => {
717
- if (event.target.files) onSelectAttachments(event.target.files);
718
- event.target.value = "";
719
- }
720
- }),
721
- attachments && attachments.length > 0 && /* @__PURE__ */ jsx("div", {
577
+ onSelectAttachments && /* @__PURE__ */ jsxs("div", {
722
578
  className: ai_chat_module_default.composerExtras,
723
- children: /* @__PURE__ */ jsx("ul", {
579
+ children: [/* @__PURE__ */ jsx("input", {
580
+ ref: fileInputRef,
581
+ className: 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__ */ jsx("ul", {
724
592
  className: ai_chat_module_default.attachmentList,
725
- "aria-label": "Attached files",
726
- children: attachments.map((attachment, index) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx(ChatAttachment, {
727
- name: attachment.name,
728
- size: attachment.size,
729
- staged: true,
730
- imageUrl: attachment.previewUrl,
731
- onRemove: onRemoveAttachment ? () => onRemoveAttachment(index) : void 0
732
- }) }, index))
733
- })
593
+ children: attachments.map((attachment, index) => /* @__PURE__ */ jsxs("li", { children: [attachment.previewUrl ? /* @__PURE__ */ jsx("img", {
594
+ className: ai_chat_module_default.attachmentThumbnail,
595
+ src: attachment.previewUrl,
596
+ alt: attachment.name
597
+ }) : /* @__PURE__ */ jsx("span", {
598
+ className: ai_chat_module_default.attachmentFilename,
599
+ children: attachment.name
600
+ }), onRemoveAttachment && /* @__PURE__ */ 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
+ })]
734
608
  }),
735
609
  /* @__PURE__ */ jsx("div", {
736
610
  className: ai_chat_module_default.composerSurface,
@@ -1 +1 @@
1
- {"version":3,"file":"index84.js","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\ninterface ChatAttachmentProps {\n readonly name: string;\n readonly size?: number;\n readonly imageUrl?: string;\n readonly href?: string;\n readonly staged?: boolean;\n readonly onRemove?: () => void;\n}\n\n/** The same attachment surface is used for staged files and sent message parts. */\nfunction ChatAttachment({ name, size, imageUrl, href, staged, onRemove }: ChatAttachmentProps) {\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 && !imageUrl ? styles.stagedFileAttachment : ''].filter(Boolean).join(' ')}>\n {imageUrl ? (\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={imageUrl} 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 {href ? <a href={href} 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 {imageUrl && !staged && <span className={styles.sentAttachmentName} title={name}>{name}</span>}\n {onRemove && (\n <button type=\"button\" className={styles.removeAttachment} onClick={onRemove}\n aria-label={`Remove ${name}`} title={`Remove ${name}`}>×</button>\n )}\n {previewOpen && imageUrl && (\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={imageUrl} 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 <ChatAttachment 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 <ChatAttachment 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,OAAoC;CACxD,MAAM,MAAM,SAAS,KAAK;CAC1B,OAAO,QAAQ,gBAAgB,KAAK,GAAG,KAAK,mDAAmD,KAAK,GAAG,KACnG,MAAM,KAAA;AACZ;AAEA,SAAS,qBAAqB,OAAuB;CACnD,IAAI,QAAQ,MAAM,OAAO,GAAG,MAAM;CAClC,OAAO,QAAQ,OAAO,OAAO,IAAI,QAAQ,KAAA,CAAM,QAAQ,CAAC,EAAE,OAAO,IAAI,SAAS,OAAO,MAAA,CAAO,QAAQ,CAAC,EA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Q,eAAY;uBAAO,oBAAC,QAAD,EAAM,GAAE,wBAAyB,CAAA;YAAM,CAAA;WACnH,CAAA,CAEP;;SACF;;OACF,CAAA;MACD;;IAGP;;EACF;;AAET"}
1
+ {"version":3,"file":"index84.js","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,qBAAC,OAAD;EAAK,WAAW;GAAC,uBAAO;GAAe,SAAS,SAAS,uBAAO,cAAc,uBAAO;GAAkB;EAAS,CAAC,CAC9G,OAAO,OAAO,CAAC,CAAC,KAAK,GAAG;EAAG,aAAW;YADzC,CAEG,SAAS,oBAAC,QAAD;GAAM,WAAW,uBAAO;aAAe;EAAY,CAAA,GAC5D,QACE;;AAET;AAEA,SAAS,uBAAuB,EAAE,SAAS,qBAAiD;CAC1F,OACE,oBAAC,qBAAD;EAAqB,MAAM,QAAQ;YAChC,QAAQ,MAAM,KAAK,MAAM,UACxB,oBAAC,OAAD,EAAA,UACG,SAAS,IAAI,IAAI,kBAAkB,MAAM,KAAK,IAAI,KAChD,GAFK,SAAS,IAAI,KAAK,OAAO,KAAK,OAAO,WAAW,KAAK,KAAK,KAE/D,CACN;CACkB,CAAA;AA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