@webority/chat-react 0.121.0 → 0.124.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/README.md CHANGED
@@ -70,74 +70,38 @@ the routes, so the conversation survives navigation.
70
70
  The streamed reply is read through axios's XHR adapter, the browser default. An instance forced
71
71
  onto the fetch adapter still works, but the reply then appears whole at the end.
72
72
 
73
- ## The client
73
+ ## The engine and the contract
74
74
 
75
- `createChatClient(http, { base })` takes an axios instance (`get`, `post`, `put`, `delete`
76
- resolving to `{ data }`) and the prefix the API maps the chat endpoints under. Every method
77
- rejects with a `ChatApiError` carrying `code`, `status`, `resetsAtUtc` and a `message` written for
78
- the person, which the components show as-is. `code` is the server's code, `network` when no
79
- response arrived, or `aborted` when the request was cancelled.
75
+ The client, the stream reader, the conversation rules and the server contract (the routes, the
76
+ request bodies, the events and the error codes) live in
77
+ [`@webority/chat-core`](https://www.npmjs.com/package/@webority/chat-core). This package draws the
78
+ assistant on top of it and re-exports its names, so a product imports every chat name from
79
+ `@webority/chat-react`. That includes `CHAT_CONTRACT_VERSION`, `createChatClient`,
80
+ `createConversationList`, `DEFAULT_CHAT_LABELS` and `mergeLabels` from the engine, and
81
+ `splitCitations` from `@webority/markdown-core`.
80
82
 
81
- | Method | Request |
82
- |---|---|
83
- | `sendMessage({ message, conversationId, pageContext }, { signal, onEvent })` | `POST {base}/chat`, streamed; resolves with the `done` event |
84
- | `getAllowance()` | `GET {base}/allowance` |
85
- | `listConversations({ skip, take })` | `GET {base}/conversations?skip=&take=` |
86
- | `getConversation(id)` | `GET {base}/conversations/{id}` |
87
- | `deleteConversation(id)` | `DELETE {base}/conversations/{id}` |
88
- | `rateMessage(conversationId, messageId, { rating, note })` | `PUT {base}/conversations/{conversationId}/messages/{messageId}/rating` |
89
-
90
- `onEvent(name, data)` is called with `delta`, `reset`, `tool` and `actions` as they arrive.
91
- `createSseParser(onEvent)` is exported too, for reading the same stream elsewhere.
92
-
93
- ## The server contract
94
-
95
- ### `POST {base}/chat`
83
+ ## Server contract
96
84
 
97
- Request body, JSON: `{ message, conversationId?, pageContext? }`. Leave `conversationId` out to
98
- start a conversation. `pageContext` is whatever the product chooses to describe the screen, and
99
- it is passed through untouched.
85
+ The client sends contract number 2 (`CHAT_CONTRACT_VERSION`). A server that reports a lower number, or a 404 on the settings route, makes the client answer `assistant_outdated`, whose message is "The assistant needs an update before it can answer. Please try again later." The panel shows that message in place of the answer.
100
86
 
101
- A refusal before any reply is plain JSON `{ code, message, resetsAtUtc? }` with a non-2xx status:
87
+ ## Settings
102
88
 
103
- | Status | `code` |
104
- |---|---|
105
- | 400 | `message_required`, `message_too_long`, `message_not_allowed`, `request_invalid` |
106
- | 404 | `conversation_not_found`, `approval_not_found`, `message_not_found` |
107
- | 429 | `daily_limit`, with `resetsAtUtc` |
108
- | 503 | `assistant_at_capacity`, `assistant_disabled`, `assistant_unavailable` |
109
-
110
- Otherwise the response is `text/event-stream`:
89
+ The chat needs the server side of `Webority.Ai.Chat`, served by `Webority.Ai.Chat.AspNetCore`, with
90
+ `GET {base}/settings` mapped. The panel reads that route once and keeps the answer. It carries the
91
+ attachment limits: the panel refuses a file over them before upload, and the Attach button appears
92
+ once they have loaded. A 404 on that route means the server is too old, and the panel shows the
93
+ assistant as outdated. A server without the attachment routes gives no limits, so no Attach button.
111
94
 
112
- | Event | Data | What the client does |
113
- |---|---|---|
114
- | `delta` | `{ text }` | Appends the text. |
115
- | `reset` | `{}` | Discards the text shown so far. |
116
- | `tool` | `{ toolName }` | A tool call started; the name only, never its arguments. `useChat` shows it as the turn's `step`. |
117
- | `actions` | `{ actions: [{ token, kind, ticketId, ticketNumber, category, subject, body, expiresDateTimeUtc }] }` | Holds support cards; `kind` is `RaiseTicket`, `Reply` or `Reopen`. |
118
- | `done` | `{ conversationId, messageId, reply, messagesLeftToday }` | Ends the turn. `reply` is the reply of record and replaces the streamed text. `messageId` is null when storing failed; `messagesLeftToday` is null with no daily limit. |
119
- | `error` | `{ code, message }` | Ends the turn with a failure. |
95
+ ## Panel behaviour
120
96
 
121
- Exactly one `done` or `error` ends each stream.
97
+ - Stop cancels the answer arriving. The question and its files stay in the turn.
98
+ - Retry sends again the last turn that failed or was stopped, with its files.
99
+ - Regenerate asks for a new answer to the last answered turn, replacing it.
100
+ - Edit puts a question and its files back in the box. Sending replaces that question and every later turn.
101
+ - Attach uploads files in parallel, each with its progress. An upload still running blocks sending; a failed upload is skipped.
122
102
 
123
- ### Read endpoints
103
+ ## Support actions
124
104
 
125
- The chat endpoint writes one turn. `MapAiChat` from `Webority.Ai.Chat.AspNetCore` 0.11.0 maps
126
- these beside it, under the same prefix, for the allowance, past chats and ratings. They are the
127
- shape the client reads:
128
-
129
- | Request | Response |
130
- |---|---|
131
- | `GET {base}/allowance` | `{ messagesLeftToday }`, null with no daily limit |
132
- | `GET {base}/conversations?skip&take` | `[{ publicId, title, createdDateTimeUtc, lastMessageDateTimeUtc }]`, newest first |
133
- | `GET {base}/conversations/{id}` | `{ publicId, title, messages: [{ publicId, role, content, actionsJson, rating, ratingNote, createdDateTimeUtc }] }` |
134
- | `DELETE {base}/conversations/{id}` | any 2xx |
135
- | `PUT {base}/conversations/{conversationId}/messages/{messageId}/rating` | body `{ rating, note }`; any 2xx |
136
-
137
- `role` is `User` or `Assistant`; `rating` is `Up`, `Down` or null; `actionsJson` is the support
138
- actions offered with a reply, as a JSON array, or null. A failure answers `{ code, message }`.
139
-
140
- ### Support actions
141
105
 
142
106
  A support card's Confirm calls the `confirmAction(token)` it is given. With
143
107
  `@webority/support-react` that is `supportClient.confirmAction`, which sends
@@ -152,7 +116,7 @@ routes with this package's client, labels and reply parser, and shows the launch
152
116
  the conversation. Its attributes are this package's props in kebab case: `base`, `position`,
153
117
  `icon`, `compact`, `panel-title`, `disclaimer`, `max-length`, `allowance-threshold`, `rating`,
154
118
  `labels` (JSON) and `page-context` (JSON). `title` is `panel-title` there, because `title` is a
155
- global HTML attribute. The past-chats list, support action cards, the rating note, `linkComponent`
119
+ global HTML attribute. The `conversations` attribute offers the past-chats list. Support action cards, the rating note, `linkComponent`
156
120
  and `renderReply` are not in the element.
157
121
 
158
122
  ## The hook
@@ -161,12 +125,24 @@ and `renderReply` are not in the element.
161
125
 
162
126
  | Field | What it is |
163
127
  |---|---|
164
- | `turns` | `[{ id, question, answer, streaming, step, error, actions, messageId, rating, ratingNote }]`, oldest first; `step` is the name of the tool the assistant is running, or null (set by a `tool` event, cleared when text arrives, on a reset and when the turn ends), for the product to map to its own sentence |
128
+ | `turns` | `[{ id, questionId, question, attachments, answer, streaming, stopped, step, error, actions, messageId, rating, ratingNote }]`, oldest first. `questionId` is the stored question's id (null until the server answers; Edit needs it). `attachments` are the files sent with the question. `stopped` is true when the person stopped the answer. `step` is the name of the tool the assistant is running, or null (set by a `tool` event, cleared when text arrives, on a reset and when the turn ends), for the product to map to its own sentence. `suggestions` are the follow-up questions offered under a settled answer, `[]` when none |
129
+ | `client` | The chat client the session talks to; pass it to `ChatConversationList` for the past-chats list |
165
130
  | `conversationId` | The conversation being continued, or null |
166
131
  | `messagesLeftToday` | From the last answer or `refreshAllowance()`; null with no daily limit |
167
132
  | `streaming` | An answer is arriving |
168
133
  | `loading`, `loadError` | `openConversation` is loading, or failed |
134
+ | `settings` | `{ contractVersion, titleMaxLength, attachments }` from `GET {base}/settings`, where `titleMaxLength` caps a chat's renamed title and `attachments` is `{ maxFiles, maxFileBytes, contentTypes }` or null when attachments are off; null until loaded |
135
+ | `settingsError` | The settings read failed; the error shows until reset |
136
+ | `editing` | `{ turnId, text }` while a question is being edited, or null |
137
+ | `attachments` | The files in the question being written: `{ key, fileName, contentType, length, status, progress, error }`, status `Uploading`, `Ready` or `Failed` |
169
138
  | `submit(message)` | Asks a question. Ignored while an answer is still arriving. |
139
+ | `stop()` | Cancels the answer arriving; the question and its files stay in the turn |
140
+ | `retry(turnId)` | Sends the last turn again when it failed or was stopped, with its files |
141
+ | `regenerate(turnId)` | Asks for a new answer to the last answered turn, replacing it |
142
+ | `startEdit(turnId)` | Puts that question and its files back in the box for editing; sending replaces it and every later turn |
143
+ | `cancelEdit()` | Leaves editing without sending |
144
+ | `attach(files)` | Uploads picked files, each with its progress; a failed upload stays listed with its error |
145
+ | `removeAttachment(key)` | Removes a file from the question being written |
170
146
  | `openConversation(id)` | Replaces the thread with a stored conversation |
171
147
  | `newConversation()` | Clears the thread; the next question starts a conversation |
172
148
  | `rate(turnId, rating, note?)` | Saves a rating, shown at once; a failed save puts the old one back and rejects |
@@ -180,7 +156,10 @@ unmount. A failed turn keeps the question, drops the half-streamed text and carr
180
156
 
181
157
  ## Components
182
158
 
183
- Every component takes `labels`, any subset of `DEFAULT_CHAT_LABELS`, to change its wording.
159
+ Every component takes `labels`, any subset of `DEFAULT_CHAT_LABELS`, to change its wording. The keys
160
+ added for copy, suggestions, citations, past chats and renaming are `copy`, `copied`, `toolStep`,
161
+ `suggestions`, `openCitation`, `renameConversation`, `conversationTitle`, `renameSave`,
162
+ `renameFailed` and `backToChat`.
184
163
 
185
164
  ### `<ChatLauncher />`
186
165
 
@@ -219,15 +198,26 @@ Escape closes it, and the question box takes focus when it opens.
219
198
  | `confirmAction`, `onViewTicket` | Support action cards; see `ActionCard`. |
220
199
  | `rating` | Offer ratings under stored replies. Default true. |
221
200
  | `renderReply` | Draws each assistant reply your way; see Custom reply rendering below. |
201
+ | `openAttachment` | Opens a file attached to a question, called with `{ publicId, fileName, contentType, length }`. The session has no open action, so the app supplies one, for example with `client.getAttachment(publicId)` (the bytes) and a blob URL: `(file) => client.getAttachment(file.publicId).then((bytes) => window.open(URL.createObjectURL(new Blob([bytes], { type: file.contentType }))))`. Without it the attachment chips on a question are not buttons. |
202
+ | `conversations` | Off by default. When true, a history icon in the header (labelled `labels.conversations`) shows the person's past chats in place of the conversation; opening one loads it. A back icon (labelled `labels.backToChat`) returns to the chat. |
203
+ | `isCitation`, `onOpenCitation` | Draw a run of the reply as a citation chip and handle its press; see Citation chips. |
204
+ | `labels` | Replacements for any subset of `DEFAULT_CHAT_LABELS`. |
222
205
 
223
206
  ### `<ChatThread />`, `<ChatMessage />`, `<ChatComposer />`
224
207
 
225
208
  The panel's parts, for a product that lays out its own assistant page. `ChatThread` takes
226
- `turns`, `empty`, `onRate`, `resolveLink`, `linkComponent`, `confirmAction`, `onViewTicket` and
227
- `renderReply`.
228
- Each answer is a polite live region, marked busy while it streams. `ChatComposer` takes
229
- `onSubmit`, `busy`, `disabled`, `maxLength` and `inputRef`; Enter sends, Shift and Enter starts a
230
- new line.
209
+ `turns`, `empty`, `onRate`, `resolveLink`, `linkComponent`, `confirmAction`, `onViewTicket`,
210
+ `renderReply`, `onRetry`, `onRegenerate`, `onEdit`, `onOpenAttachment`, `onAskSuggestion`, `isCitation` and `onOpenCitation`. `onRetry` is offered on the
211
+ last turn only, `onRegenerate` (New answer) on the last answered turn only, `onEdit` beside each
212
+ question that has a `questionId`, and `onOpenAttachment` makes each attachment chip a button.
213
+ Each answer is a polite live region, marked busy while it streams. `ChatMessage` draws one turn with the same reply props. Under a settled answer, `onAskSuggestion(text)` offers the suggested follow-up questions; `ChatPanel` wires it to send the chosen question through `submit`.
214
+
215
+ `ChatComposer` takes `onSubmit`, `busy`, `disabled`, `maxLength` and `inputRef`; Enter sends, Shift
216
+ and Enter starts a new line. With `onStop` it shows Stop in place of Send while `busy`. With
217
+ `onAttach` it shows the attach button, and `accept` sets the file types the picker offers; the picked
218
+ files come to `onAttach(files)`, and `attachments` (each with `key`, `fileName`, `status`, `progress`
219
+ and `error`) show as chips that `onRemoveAttachment(key)` removes. `editing` (`{ text }`) fills the
220
+ box and shows the editing notice, whose Cancel calls `onCancelEdit`.
231
221
 
232
222
  ### `<ReplyRating />`
233
223
 
@@ -237,7 +227,23 @@ note, saved with the same rating. Takes `rating` and `onRate(rating, note?)`.
237
227
  ### `<ChatConversationList />`
238
228
 
239
229
  Past chats, newest first, for a page or a panel: `client`, `onOpen(conversation)`,
240
- `onDeleted(id)` and `pageSize` (default 20). It pages with Show more and deletes after a confirm.
230
+ `onDeleted(id)` and `pageSize` (default 20). It pages with Show more, opens one through `onOpen`,
231
+ renames one in place and deletes one after a confirm. The rename form caps the title at the
232
+ server's `titleMaxLength`. If the settings read fails, its message shows in the rename form and Save
233
+ stays enabled, because the server enforces the limit. The component calls `client.getSettings()`
234
+ only when the client has that method.
235
+
236
+ ### The paged past-chats list
237
+
238
+ `createConversationList({ client, pageSize })` (exported from `@webority/chat-react`) builds the
239
+ state the component draws. It returns `getState()`, `subscribe(listener)`, `load()` (reads the first
240
+ page and replaces the list), `loadMore()` (reads the next page), `rename(id, title)`, `remove(id)`
241
+ and `dispose()`. `getState()` returns `{ items, totalCount, loading, error, hasMore }`, where
242
+ `error` is `{ code, message, resetsAtUtc }` and its message is written for the person.
243
+
244
+ The client it reads from provides `listConversations({ page, pageSize })`, which resolves to a
245
+ `PagedDataObject` `{ items, page, pageSize, totalCount, totalPages }`, plus `renameConversation(id,
246
+ title)`, `deleteConversation(id)` and `getSettings()`.
241
247
 
242
248
  ### `<ActionCard />`
243
249
 
@@ -264,7 +270,7 @@ default "Nothing is sent until you confirm."), `onConfirm()` and `labels`.
264
270
 
265
271
  ### Citation chips
266
272
 
267
- A reply can cite its sources as `[Clause 4.2]`. `splitCitations(text, isCitation)` splits the reply into text parts and citation parts, and `CitationChip` draws each citation as a chip that opens its source. Only the runs that `isCitation` accepts become chips: a markdown link such as `[text](url)` and an empty `[]` stay text. `CitationChip` takes `citation`, `onOpen(citation)`, and optionally `label` (the chip text, defaulting to the citation) and `ariaLabel`.
273
+ A reply can cite its sources as `[Clause 4.2]`. `splitCitations(text, isCitation)` splits the reply into text parts and citation parts. The function lives in `@webority/markdown-core`; `@webority/chat-react` re-exports it, so the import stays the same. `CitationChip` draws each citation as a chip that opens its source. Only the runs that `isCitation` accepts become chips: a markdown link such as `[text](url)` and an empty `[]` stay text. `CitationChip` takes `citation`, `onOpen(citation)`, and optionally `label` (the chip text, defaulting to the citation) and `ariaLabel`. `ChatMarkdown`, `ChatMessage`, `ChatThread` and `ChatPanel` take `isCitation` and `onOpenCitation`: a run that `isCitation` accepts draws as a chip, and pressing it calls `onOpenCitation(citation)` with the citation text.
268
274
 
269
275
  ```jsx
270
276
  const parts = splitCitations(reply.text, (inner) => sources.has(inner));
@@ -291,6 +297,10 @@ and `resolveLink(href)` returns an in-app route starting with `/`. Any other lin
291
297
  web address, shows its label as plain text. Pass the router's `Link` as `linkComponent` so a link
292
298
  navigates inside the portal.
293
299
 
300
+ Each settled answer has a Copy button that copies the answer as plain text, without the markdown marks.
301
+
302
+ While a tool runs, the waiting line reads `labels.toolStep(name)`. It receives the server's tool name and defaults to "Looking this up", so the name never shows unless the product maps it to the person's words.
303
+
294
304
  ### Custom reply rendering
295
305
 
296
306
  A product that draws replies its own way (charts, maths) passes `renderReply` to `ChatPanel`,
@@ -1 +1,5 @@
1
- import{ChatApiError as e,DEFAULT_CHAT_LABELS as t,createChatClient as n,createSseParser as r,mergeLabels as i}from"@webority/ui-elements/chat-core";import{AppActionIcon as a,AppAlert as o,AppButton as s,AppCard as c,AppChip as l,AppConfirmDialog as u,AppDrawer as d,AppEmptyState as f,AppIcon as p,AppMarkdown as m,AppSkeleton as h,AppSpinner as g,AppTextarea as _,useFloatingStack as v}from"@webority/ui-react";import{memo as y,startTransition as b,useCallback as x,useEffect as S,useId as C,useRef as w,useState as T}from"react";import{Fragment as E,jsx as D,jsxs as O}from"react/jsx-runtime";import{formatDateTime as k}from"@webority/ui-elements/helpers";import{createPortal as A}from"react-dom";function j(e,t){return e.kind===`Reply`?t.actionReply(e.ticketNumber):e.kind===`Reopen`?t.actionReopen(e.ticketNumber):t.actionRaiseTicket}function M(e,t,n){return e===`Reply`?n.actionDoneReply(t):e===`Reopen`?n.actionDoneReopen(t):n.actionDoneRaiseTicket(t)}function N({action:e,confirmAction:t,onViewTicket:n,labels:r}){let a=i(r),[l,u]=T(`ready`),[d,f]=T(null),[p,m]=T(``);if(l===`dismissed`)return D(`p`,{className:`wui-text-sm text-body-secondary mb-0`,children:a.actionDismissed});if(l===`done`)return D(o,{tone:`success`,role:`status`,size:`sm`,action:n?D(s,{size:`sm`,variant:`ghost`,onClick:()=>n(d),children:a.viewTicket}):void 0,children:M(e.kind,d.number,a)});async function h(){u(`sending`),m(``);try{f(await t(e.token)),u(`done`)}catch(e){m(e?.message||a.actionFailed),u(`ready`)}}let g=l===`sending`,_=new Date(e.expiresDateTimeUtc).getTime()<=Date.now(),v=e.kind===`RaiseTicket`?[e.category,e.subject].filter(Boolean).join(` · `):``;return D(c,{padding:`sm`,className:`border`,title:j(e,a),subtitle:v||void 0,children:O(`div`,{className:`d-flex flex-column gap-2`,children:[e.kind!==`Reopen`&&e.body&&D(`p`,{className:`wui-text-sm mb-0`,style:{whiteSpace:`pre-wrap`,overflowWrap:`anywhere`},children:e.body}),_?D(`p`,{className:`wui-text-sm text-body-secondary mb-0`,children:a.actionExpired}):O(E,{children:[D(`p`,{className:`wui-text-xs text-body-secondary mb-0`,children:a.actionNote}),p&&D(o,{size:`sm`,tone:`danger`,children:p}),O(`div`,{className:`d-flex flex-wrap gap-2`,children:[D(s,{size:`sm`,loading:g,onClick:h,children:a.actionConfirm}),D(s,{size:`sm`,variant:`secondary`,disabled:g,onClick:()=>u(`dismissed`),children:a.actionDismiss})]})]})]})})}function P({onSubmit:e,busy:t=!1,disabled:n=!1,maxLength:r=4e3,inputRef:a,labels:o}){let c=i(o),l=C(),[u,d]=T(``),f=t||n||!u.trim();function p(){f||(e(u.trim()),d(``))}return O(`form`,{className:`wui-chat-composer d-flex align-items-end gap-2`,"aria-label":c.composer,onSubmit:e=>{e.preventDefault(),p()},children:[D(_,{id:`${l}-message`,"aria-label":c.composer,"aria-describedby":`${l}-hint`,placeholder:c.placeholder,rows:1,autoGrow:!0,maxLength:r,value:u,disabled:n,ref:a,fieldClassName:`flex-grow-1 mb-0`,onChange:e=>d(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&!e.nativeEvent.isComposing&&(e.preventDefault(),p())}}),D(`span`,{id:`${l}-hint`,className:`visually-hidden`,children:c.composerHint}),D(s,{type:`submit`,leftIcon:`send`,disabled:f,children:D(`span`,{className:`visually-hidden`,children:c.send})})]})}function F({client:e,onOpen:t,onDeleted:n,pageSize:r=20,labels:l}){let d=i(l),[p,m]=T([]),[g,_]=T(!0),[v,y]=T(``),[b,C]=T(!1),[w,E]=T(0),[A,j]=T(null),[M,N]=T(!1),[P,F]=T(``),I=x(async t=>{_(!0),y(``);try{let n=await e.listConversations({skip:t,take:r});m(e=>t===0?n:[...e,...n]),C(n.length===r)}catch(e){y(e?.message||d.loadFailed)}finally{_(!1)}},[e,r,d.loadFailed]);S(()=>{I(0)},[I,w]);async function L(){N(!0),F(``);try{await e.deleteConversation(A.publicId),m(e=>e.filter(e=>e.publicId!==A.publicId)),n?.(A.publicId),j(null)}catch(e){F(e?.message||d.deleteFailed)}finally{N(!1)}}return!g&&!v&&p.length===0?D(f,{icon:`chat`,size:`sm`,title:d.conversationsEmptyTitle,text:d.conversationsEmptyText}):O(`div`,{className:`d-flex flex-column gap-3`,children:[v&&D(o,{tone:`danger`,action:D(s,{size:`sm`,variant:`secondary`,onClick:()=>E(e=>e+1),children:d.retry}),children:v}),p.length>0&&D(`ul`,{className:`list-unstyled d-flex flex-column gap-2 mb-0`,"aria-label":d.conversations,children:p.map(e=>D(`li`,{children:O(c,{padding:`sm`,className:`border`,bodyClassName:`d-flex align-items-center gap-2`,children:[D(s,{variant:`ghost`,className:`flex-grow-1 text-start`,style:{minWidth:0},onClick:()=>t(e),children:O(`span`,{className:`d-flex flex-column`,style:{minWidth:0},children:[D(`span`,{className:`text-truncate fw-semibold`,children:e.title||d.untitled}),D(`time`,{dateTime:e.lastMessageDateTimeUtc,className:`wui-text-xs text-body-secondary`,children:k(e.lastMessageDateTimeUtc)})]})}),D(a,{icon:`trash-2`,danger:!0,label:d.deleteConversation,onClick:()=>{F(``),j(e)}})]})},e.publicId))}),g&&O(`div`,{className:`d-flex flex-column gap-2`,"aria-hidden":`true`,children:[D(h,{height:44}),D(h,{height:44}),D(h,{height:44})]}),!g&&b&&D(s,{variant:`secondary`,className:`align-self-center`,onClick:()=>I(p.length),children:d.loadMore}),D(u,{open:A!==null,title:d.deleteConfirmTitle,message:P?D(o,{tone:`danger`,children:P}):d.deleteConfirmMessage,confirmLabel:d.deleteConfirm,cancelLabel:d.cancel,danger:!0,loading:M,onConfirm:L,onClose:()=>{M||j(null)}})]})}var I={zIndex:`var(--wui-z-fixed)`,bottom:`var(--wui-consent-banner-block, 0px)`},L={end:{insetInlineEnd:0},start:{insetInlineStart:0}};function R({onClick:e,open:t=!1,position:n=`end`,icon:r=`sparkles`,compact:a=!1,className:o,style:c,labels:l}){let u=i(l);return a?D(z,{onClick:e,open:t,position:n,icon:r,className:o,style:c,label:u.launcher}):D(`span`,{"data-support-capture":`exclude`,className:[`position-fixed m-3`,o].filter(Boolean).join(` `),style:{...I,...L[n],...c},children:D(s,{leftIcon:r,className:`rounded-pill`,onClick:e,"aria-haspopup":`dialog`,"aria-expanded":t,children:u.launcher})})}function z({onClick:e,open:t,position:n,icon:r,className:i,style:a,label:o}){let c=v(n);return c?A(D(`span`,{className:[`wui-floating-stack-item wui-floating-stack-item--primary`,i].filter(Boolean).join(` `),style:a,children:D(s,{className:`wui-floating-btn`,onClick:e,"aria-label":o,"aria-haspopup":`dialog`,"aria-expanded":t,tooltip:o,tooltipPlacement:n===`start`?`end`:`start`,children:D(p,{name:r,size:24})})}),c):null}function B({text:e,resolveLink:t,linkComponent:n,className:r}){return D(m,{value:e,links:`app`,headings:`text`,resolveLink:t,linkComponent:n,className:r})}function V({rating:e,onRate:t,noteMaxLength:n=1e3,labels:r}){let a=i(r),c=C(),[l,u]=T(!1),[d,f]=T(!1),[p,m]=T(``),[h,g]=T(``),[v,y]=T(!1);async function b(e,n){u(!0),g(``);try{await t(e,n),f(e===`Down`&&n===void 0),y(e===`Up`||n!==void 0),n!==void 0&&m(``)}catch{g(a.ratingFailed)}finally{u(!1)}}return O(`div`,{className:`d-flex flex-column gap-2`,children:[O(`div`,{className:`d-flex flex-wrap align-items-center gap-1`,children:[D(s,{size:`sm`,variant:e===`Up`?`neutral`:`ghost`,leftIcon:`check`,"aria-pressed":e===`Up`,disabled:l,onClick:()=>b(`Up`),children:a.rateUp}),D(s,{size:`sm`,variant:e===`Down`?`neutral`:`ghost`,leftIcon:`x`,"aria-pressed":e===`Down`,disabled:l,onClick:()=>b(`Down`),children:a.rateDown}),v&&!d&&D(`span`,{className:`wui-text-xs text-body-secondary`,role:`status`,children:a.rated})]}),h&&D(o,{size:`sm`,tone:`danger`,children:h}),d&&O(`form`,{className:`d-flex flex-column gap-2`,onSubmit:e=>{e.preventDefault(),b(`Down`,p)},children:[D(_,{id:`${c}-note`,label:a.ratingNote,hint:a.ratingNoteHint,rows:2,maxLength:n,value:p,onChange:e=>m(e.target.value)}),O(`div`,{className:`d-flex gap-2`,children:[D(s,{type:`submit`,size:`sm`,loading:l,children:a.ratingNoteSend}),D(s,{size:`sm`,variant:`secondary`,disabled:l,onClick:()=>{f(!1),y(!0)},children:a.ratingNoteSkip})]})]})]})}var H={maxWidth:`85%`,whiteSpace:`pre-wrap`,overflowWrap:`anywhere`};function U({turn:e,onRate:t,resolveLink:n,linkComponent:r,confirmAction:a,onViewTicket:s,renderReply:l,labels:u}){let d=i(u),f=e.streaming&&!e.answer;return O(`li`,{className:`d-flex flex-column gap-2`,children:[e.question&&O(`div`,{className:`align-self-end`,style:H,children:[O(`span`,{className:`visually-hidden`,children:[d.you,`: `]}),D(c,{padding:`sm`,variant:`muted`,className:`wui-text-sm`,children:e.question})]}),O(`div`,{className:`d-flex flex-column gap-2`,style:{minWidth:0},children:[O(`span`,{className:`visually-hidden`,children:[d.assistant,`: `]}),D(`div`,{"aria-live":`polite`,"aria-busy":e.streaming,children:f?O(`span`,{className:`d-inline-flex align-items-center gap-2 wui-text-sm text-body-secondary`,children:[D(g,{size:`sm`,label:d.thinking}),D(`span`,{"aria-hidden":`true`,children:d.thinking})]}):e.answer&&(l?l(e,{streaming:!!e.streaming}):D(B,{text:e.answer,resolveLink:n,linkComponent:r}))}),e.error&&D(o,{size:`sm`,tone:`danger`,children:e.error.message}),a&&!e.streaming&&e.actions.map(e=>D(N,{action:e,confirmAction:a,onViewTicket:s,labels:u},e.token)),t&&e.messageId&&!e.streaming&&D(V,{rating:e.rating,onRate:(n,r)=>t(e.id,n,r),labels:u})]})]})}var W=y(U);function G(e){for(let t=e?.parentElement;t&&t!==document.body;t=t.parentElement){let{overflowY:e}=getComputedStyle(t);if((e===`auto`||e===`scroll`)&&t.scrollHeight>t.clientHeight)return t}return null}function K({turns:e,empty:t,onRate:n,resolveLink:r,linkComponent:a,confirmAction:o,onViewTicket:s,renderReply:c,labels:l}){let u=i(l),d=w(null),p=e[e.length-1];return S(()=>{let e=G(d.current);e&&(e.scrollTop=e.scrollHeight)},[e.length,p?.answer,p?.error,p?.actions]),e.length===0?t??D(f,{icon:`sparkles`,size:`sm`,title:u.emptyTitle,text:u.emptyText}):O(E,{children:[D(`ol`,{className:`list-unstyled d-flex flex-column gap-3 mb-0`,"aria-label":u.thread,children:e.map(e=>D(W,{turn:e,onRate:n,resolveLink:r,linkComponent:a,confirmAction:o,onViewTicket:s,renderReply:c,labels:l},e.id))}),D(`div`,{ref:d})]})}function q({chat:e,open:t,onClose:n,title:r,titleIcon:s=`sparkles`,headerActions:c,empty:l,disclaimer:u,maxLength:f=4e3,allowanceThreshold:m=10,width:h=`440px`,resolveLink:_,linkComponent:v,confirmAction:y,onViewTicket:b,rating:x=!0,renderReply:C,labels:T}){let E=i(T),k=w(null),{refreshAllowance:A}=e;S(()=>{t&&A().catch(()=>{})},[t,A]);let j=e.messagesLeftToday,M=r??E.panelTitle;return D(d,{open:t,onClose:n,sheet:!1,width:h,header:O(`div`,{className:`drawer-header`,children:[O(`div`,{className:`drawer-title`,children:[s&&D(`span`,{className:`drawer-title-ic`,children:D(p,{name:s,size:18})}),M]}),O(`div`,{className:`d-flex align-items-center gap-1`,children:[c,D(a,{icon:`plus`,label:E.newChat,onClick:e.newConversation,disabled:e.turns.length===0&&!e.loading}),D(a,{icon:`x`,label:E.close,onClick:n})]})]}),footer:O(`div`,{className:`d-flex flex-column gap-2`,children:[j!==null&&j<=m&&D(`p`,{className:`wui-text-xs text-body-secondary mb-0`,role:`status`,children:E.allowance(j)}),D(P,{onSubmit:e.submit,busy:e.streaming||e.loading,disabled:j===0,maxLength:f,inputRef:k,labels:T}),D(`p`,{className:`wui-text-xs text-body-secondary mb-0`,children:u??E.disclaimer})]}),ariaLabel:typeof M==`string`?M:E.panelTitle,onOpened:()=>k.current?.focus(),children:e.loading?D(`div`,{className:`d-flex justify-content-center py-4`,children:D(g,{label:E.loadingConversation})}):e.loadError?D(o,{tone:`danger`,children:e.loadError.message}):D(K,{turns:e.turns,empty:l,onRate:x?e.rate:void 0,resolveLink:_,linkComponent:v,confirmAction:y,onViewTicket:b,renderReply:C,labels:T})})}var J=/\[([^[\]]*)\](?!\()/g;function Y(e,t){let n=[],r=0;for(let i of e.matchAll(J)){let a=i[1];a===``||!t(a)||(i.index>r&&n.push({text:e.slice(r,i.index)}),n.push({citation:a}),r=i.index+i[0].length)}return r<e.length&&n.push({text:e.slice(r)}),n}function X({citation:e,label:t,ariaLabel:n,onOpen:r}){return D(l,{label:t??e,size:`sm`,tone:`primary`,variant:`outline`,leadingIcon:`book-1`,"aria-label":n??e,onClick:()=>r(e)})}function Z({title:e,subtitle:t,lines:n,note:r,onConfirm:a,labels:l}){let u=i(l),[d,f]=T(`ready`),[p,m]=T(null),[h,g]=T(``);if(d===`dismissed`)return D(`p`,{className:`wui-text-sm text-body-secondary mb-0`,children:u.actionDismissed});if(d===`done`)return D(o,{tone:`success`,role:`status`,size:`sm`,children:p?.message||u.actionDone});async function _(){f(`sending`),g(``);try{let e=await a();m(e??null),f(`done`)}catch(e){g(e?.message||u.actionFailed),f(`ready`)}}let v=d===`sending`;return D(c,{padding:`sm`,className:`border`,title:e,subtitle:t||void 0,children:O(`div`,{className:`d-flex flex-column gap-2`,children:[(n??[]).map((e,t)=>D(`p`,{className:`wui-text-sm mb-0`,style:{whiteSpace:`pre-wrap`,overflowWrap:`anywhere`},children:e},t)),D(`p`,{className:`wui-text-xs text-body-secondary mb-0`,children:r??u.actionNote}),h&&D(o,{size:`sm`,tone:`danger`,children:h}),O(`div`,{className:`d-flex flex-wrap gap-2`,children:[D(s,{size:`sm`,loading:v,onClick:_,children:u.actionConfirm}),D(s,{size:`sm`,variant:`secondary`,disabled:v,onClick:()=>f(`dismissed`),children:u.actionDismiss})]})]})})}function Q(e){return{code:e?.code||`unknown`,message:e?.message||`Something went wrong. Please try again.`,resetsAtUtc:e?.resetsAtUtc??null}}function $(e){if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}function ee(e){let t=[];for(let n of e??[]){if(n.role===`User`){t.push({id:n.publicId,question:n.content,answer:``,streaming:!1,step:null,error:null,actions:[],messageId:null,rating:null,ratingNote:null});continue}let e=t[t.length-1],r={answer:n.content,actions:$(n.actionsJson),messageId:n.publicId,rating:n.rating??null,ratingNote:n.ratingNote??null};e&&e.messageId===null&&e.answer===``?Object.assign(e,r):t.push({id:n.publicId,question:``,streaming:!1,step:null,error:null,...r})}return t}function te({client:e,pageContext:t}){let[n,r]=T([]),[i,a]=T(null),[o,s]=T(null),[c,l]=T(!1),[u,d]=T(null),f=w(null),p=w(0),m=w(0),h=w(t);h.current=t;let g=w(null);g.current=i;let _=w(n);_.current=n;let v=w(new Map),y=w(0),C=w(!1),E=x(()=>{let e=v.current;e.size!==0&&(v.current=new Map,b(()=>{r(t=>t.map(t=>e.has(t.id)?{...t,answer:t.answer+e.get(t.id),step:null}:t))}))},[]),D=x((e,t)=>{v.current.set(e,(v.current.get(e)??``)+t),!C.current&&(C.current=!0,y.current=requestAnimationFrame(()=>{C.current=!1,E()}))},[E]),O=x(()=>{E(),p.current+=1,f.current?.abort(),f.current=null},[E]);S(()=>O,[O]),S(()=>()=>{cancelAnimationFrame(y.current),C.current=!1},[]);let k=x((e,t)=>{r(n=>n.map(n=>n.id===e?{...n,...typeof t==`function`?t(n):t}:n))},[]),A=x(async t=>{let n=typeof t==`string`?t.trim():``;if(!n||f.current)return;let i=p.current,o=new AbortController;f.current=o,m.current+=1;let c=`turn-${m.current}`;r(e=>[...e,{id:c,question:n,answer:``,streaming:!0,step:null,error:null,actions:[],messageId:null,rating:null,ratingNote:null}]);let l=()=>i===p.current&&!o.signal.aborted;try{let t=await e.sendMessage({message:n,conversationId:g.current,pageContext:h.current},{signal:o.signal,onEvent:(e,t)=>{if(l()){if(e===`delta`){D(c,t?.text??``);return}E(),e===`reset`?k(c,{answer:``,step:null}):e===`tool`?k(c,{step:typeof t?.toolName==`string`&&t.toolName?t.toolName:null}):e===`actions`&&k(c,{actions:Array.isArray(t?.actions)?t.actions:[]})}}});if(E(),!l())return;k(c,{answer:t.reply,messageId:t.messageId??null,streaming:!1,step:null}),g.current=t.conversationId,a(t.conversationId),s(t.messagesLeftToday??null)}catch(e){if(E(),!l())return;k(c,{answer:``,actions:[],streaming:!1,step:null,error:Q(e)}),e?.code===`daily_limit`&&s(0),e?.code===`conversation_not_found`&&(g.current=null,a(null))}finally{f.current===o&&(f.current=null)}},[e,k,E,D]),j=x(async t=>{O();let n=p.current;r([]),a(null),d(null),l(!0);try{let i=await e.getConversation(t);if(n!==p.current)return;r(ee(i.messages)),a(i.publicId)}catch(e){if(n!==p.current)return;d(Q(e))}finally{n===p.current&&l(!1)}},[O,e]),M=x(()=>{O(),r([]),a(null),d(null),l(!1)},[O]),N=x(()=>{O(),r([]),a(null),s(null),d(null),l(!1)},[O]),P=x(async()=>{let t=p.current,n=await e.getAllowance();t===p.current&&s(n?.messagesLeftToday??null)},[e]),F=x(async(t,n,r)=>{let i=_.current.find(e=>e.id===t),a=g.current;if(!i?.messageId||!a)throw Error(`Only a stored reply can be rated.`);let o={rating:i.rating,ratingNote:i.ratingNote},s=typeof r==`string`&&r.trim()?r.trim():null;k(t,{rating:n,ratingNote:s});try{await e.rateMessage(a,i.messageId,{rating:n,note:s})}catch(e){throw k(t,o),e}},[e,k]);return{turns:n,conversationId:i,messagesLeftToday:o,streaming:n.some(e=>e.streaming),loading:c,loadError:u,submit:A,openConversation:j,newConversation:M,rate:F,refreshAllowance:P,reset:N}}export{N as ActionCard,e as ChatApiError,P as ChatComposer,F as ChatConversationList,R as ChatLauncher,B as ChatMarkdown,W as ChatMessage,q as ChatPanel,K as ChatThread,X as CitationChip,Z as ConfirmCard,t as DEFAULT_CHAT_LABELS,V as ReplyRating,n as createChatClient,r as createSseParser,Y as splitCitations,te as useChat};
1
+ import{CHAT_CONTRACT_VERSION as e,ChatApiError as t,DEFAULT_CHAT_LABELS as n,createChatClient as r,createChatSession as i,createChatSession as a,createConversationList as o,createConversationList as s,createSseParser as c,mergeLabels as l,mergeLabels as u}from"@webority/chat-core";import{AppActionIcon as d,AppAlert as f,AppButton as p,AppCard as m,AppChip as h,AppChipGroup as g,AppConfirmDialog as _,AppCopyButton as v,AppDrawer as y,AppEmptyState as b,AppIcon as x,AppInput as S,AppMarkdown as C,AppProgress as w,AppSkeleton as T,AppSpinner as E,AppTextarea as D,useFloatingStack as O}from"@webority/ui-react";import{memo as k,useEffect as A,useId as j,useMemo as M,useRef as N,useState as P,useSyncExternalStore as F}from"react";import{Fragment as I,jsx as L,jsxs as R}from"react/jsx-runtime";import{formatDateTime as ee}from"@webority/ui-elements/helpers";import{createPortal as z}from"react-dom";var B=/\[([^[\]\n]+)\](?!\()/g;function V(e,t){let n=[],r=0;B.lastIndex=0;for(let i of e.matchAll(B)){let a=i[1];t(a)&&(i.index>r&&n.push({text:e.slice(r,i.index)}),n.push({citation:a}),r=i.index+i[0].length)}return r<e.length&&n.push({text:e.slice(r)}),n}var H=/* @__PURE__ */ new Set(`!"#$%&'()*+,-./:;<=>?@[\\]^_\`{|}~`),U=/\[([^\]\n]+)\]\(((?:[^()\s]|\([^()\s]*\))+)\)/y,W=/!\[([^\]\n]*)\]\(((?:[^()\s]|\([^()\s]*\))+)\)/y,G=new RegExp(B.source,`y`),K=e=>/[\p{L}\p{N}]/u.test(e);function te(e,t){let n=0;for(let r=t-1;r>=0&&e.charAt(r)===`\\`;--r)n+=1;return n%2==1}function q(e,t,n){let r=n.length===1;for(let i=e.indexOf(n,t);i!==-1;i=e.indexOf(n,i+1)){let a=i>t&&!/\s/.test(e.charAt(t))&&!/\s/.test(e.charAt(i-1)),o=r&&(e.charAt(i+1)===n||e.charAt(i-1)===n),s=n===`_`&&K(e.charAt(i+n.length));if(a&&!o&&!s&&!te(e,i))return i}return-1}function J(e,t){let n=t?.isCitation,r=[],i=``,a=()=>{i&&=(r.push({type:`text`,text:i}),``)},o=0;for(;o<e.length;){let s=e.charAt(o),c=e.charAt(o+1);if(s===`\\`&&H.has(c)){i+=c,o+=2;continue}if(s==="`"){let t=e.indexOf("`",o+1);if(t>o+1){a(),r.push({type:`code`,text:e.slice(o+1,t)}),o=t+1;continue}}let l=s+c;if(l===`**`||l===`__`||l===`~~`){let n=q(e,o+2,l);if(n!==-1&&!(l===`__`&&K(e.charAt(o-1)))){a();let i=J(e.slice(o+2,n),t);l===`~~`?r.push({type:`strike`,children:i}):r.push({type:`strong`,children:i}),o=n+2;continue}i+=l,o+=2}else{if(s===`*`||s===`_`){let n=q(e,o+1,s);if(n!==-1&&!(s===`_`&&K(e.charAt(o-1)))){a(),r.push({type:`em`,children:J(e.slice(o+1,n),t)}),o=n+1;continue}}if(s===`[`){U.lastIndex=o;let t=U.exec(e);if(t){a(),r.push({type:`link`,href:t[2],children:J(t[1])}),o+=t[0].length;continue}if(n){G.lastIndex=o;let t=G.exec(e);if(t&&n(t[1])){a(),r.push({type:`citation`,text:t[1]}),o+=t[0].length;continue}}}if(s===`!`){W.lastIndex=o;let t=W.exec(e);if(t){a(),r.push({type:`image`,children:J(t[1])}),o+=t[0].length;continue}}i+=s,o+=1}}return a(),r.map((e,t)=>({...e,key:t}))}var Y=/^\s*```/,ne=/^\s*```\s*(\S*)/,X=/^\s{0,3}(#{1,6})\s+(.*?)(?:\s+#+)?\s*$/,Z=/^\s*([-*_])(\s*\1){2,}\s*$/,re=/^(\s*)[-*+]\s+(.*)$/,ie=/^(\s*)(\d{1,9})[.)]\s+(.*)$/,Q=/^\s*>\s?(.*)$/,ae=/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)*\|?\s*$/,oe=e=>e.includes(`|`);function se(e){let t=e.trim();return t.startsWith(`|`)&&(t=t.slice(1)),t.endsWith(`|`)&&(t=t.slice(0,-1)),t.split(`|`).map(e=>e.trim())}function ce(e,t){return oe(e[t])&&t+1<e.length&&e[t+1].includes(`|`)&&ae.test(e[t+1])}function le(e,t){let n=e[t];return Y.test(n)||Q.test(n)||re.test(n)||ie.test(n)||X.test(n)||Z.test(n)||ce(e,t)}function ue(e){let t=e.replace(/\t/g,` `).length;return Math.min(Math.floor(t/2),4)}function de(e){let t=ie.exec(e);if(t)return{text:t[3],depth:ue(t[1]),ordered:!0,number:Number(t[2])};let n=re.exec(e);return n?{text:n[2],depth:ue(n[1]),ordered:!1,number:0}:null}function fe(e){let t=(e??``).replace(/\r\n?/g,`
2
+ `).split(`
3
+ `),n=[],r=0;for(;r<t.length;){let e=t[r];if(!e.trim()){r+=1;continue}if(Y.test(e)){let i=ne.exec(e)?.[1]||null,a=[];for(r+=1;r<t.length&&!Y.test(t[r]);)a.push(t[r]),r+=1;r+=1,n.push({type:`code`,text:a.join(`
4
+ `),language:i});continue}if(ce(t,r)){let i=se(e),a=[];for(r+=2;r<t.length&&t[r].trim()&&oe(t[r]);)a.push(se(t[r])),r+=1;n.push({type:`table`,header:i,rows:a});continue}if(Z.test(e)){n.push({type:`rule`}),r+=1;continue}let i=X.exec(e);if(i){n.push({type:`heading`,level:i[1].length,text:i[2]}),r+=1;continue}if(Q.test(e)){let e=[];for(;r<t.length;){let n=Q.exec(t[r]);if(!n)break;e.push(n[1]),r+=1}n.push({type:`quote`,lines:e});continue}let a=de(e);if(a){let e=[];for(;r<t.length&&t[r].trim();){let n=de(t[r]);if(n){if(n.depth===0&&n.ordered!==a.ordered)break;e.push(n)}else if(le(t,r))break;else e[e.length-1].text+=` ${t[r].trim()}`;r+=1}n.push({type:`list`,ordered:a.ordered,start:a.ordered?a.number:1,items:e});continue}let o=[e];for(r+=1;r<t.length&&t[r].trim()&&!le(t,r);)o.push(t[r]),r+=1;n.push({type:`paragraph`,lines:o})}return n.map((e,t)=>({...e,key:t}))}var pe=e=>e.map(e=>e.type===`text`||e.type===`code`||e.type===`citation`?e.text:pe(e.children)).join(``),$=e=>pe(J(e));function me(e){switch(e.type){case`paragraph`:case`quote`:return $(e.lines.join(` `));case`heading`:return $(e.text);case`list`:return e.items.map(e=>$(e.text)).join(`. `);case`table`:return[e.header,...e.rows].map(e=>e.map($).join(`, `)).join(`. `);case`code`:return e.text;case`rule`:return``}}function he(e){return fe(e).map(me).filter(Boolean).join(`
5
+ `)}function ge(e,t){return e.kind===`Reply`?t.actionReply(e.ticketNumber):e.kind===`Reopen`?t.actionReopen(e.ticketNumber):t.actionRaiseTicket}function _e(e,t,n){return e===`Reply`?n.actionDoneReply(t):e===`Reopen`?n.actionDoneReopen(t):n.actionDoneRaiseTicket(t)}function ve({action:e,confirmAction:t,onViewTicket:n,labels:r}){let i=u(r),[a,o]=P(`ready`),[s,c]=P(null),[l,d]=P(``);if(a===`dismissed`)return/* @__PURE__ */ L(`p`,{className:`wui-text-sm text-body-secondary mb-0`,children:i.actionDismissed});if(a===`done`)return/* @__PURE__ */ L(f,{tone:`success`,role:`status`,size:`sm`,action:n?/* @__PURE__ */ L(p,{size:`sm`,variant:`ghost`,onClick:()=>n(s),children:i.viewTicket}):void 0,children:_e(e.kind,s.number,i)});async function h(){o(`sending`),d(``);try{c(await t(e.token)),o(`done`)}catch(e){d(e?.message||i.actionFailed),o(`ready`)}}let g=a===`sending`,_=new Date(e.expiresDateTimeUtc).getTime()<=Date.now(),v=e.kind===`RaiseTicket`?[e.category,e.subject].filter(Boolean).join(` · `):``;return/* @__PURE__ */ L(m,{padding:`sm`,className:`border`,title:ge(e,i),subtitle:v||void 0,children:/* @__PURE__ */ R(`div`,{className:`d-flex flex-column gap-2`,children:[e.kind!==`Reopen`&&e.body&&/* @__PURE__ */ L(`p`,{className:`wui-text-sm mb-0`,style:{whiteSpace:`pre-wrap`,overflowWrap:`anywhere`},children:e.body}),_?/* @__PURE__ */ L(`p`,{className:`wui-text-sm text-body-secondary mb-0`,children:i.actionExpired}):/* @__PURE__ */ R(I,{children:[/* @__PURE__ */ L(`p`,{className:`wui-text-xs text-body-secondary mb-0`,children:i.actionNote}),l&&/* @__PURE__ */ L(f,{size:`sm`,tone:`danger`,children:l}),/* @__PURE__ */ R(`div`,{className:`d-flex flex-wrap gap-2`,children:[/* @__PURE__ */ L(p,{size:`sm`,loading:g,onClick:h,children:i.actionConfirm}),/* @__PURE__ */ L(p,{size:`sm`,variant:`secondary`,disabled:g,onClick:()=>o(`dismissed`),children:i.actionDismiss})]})]})]})})}function ye({attachments:e,onRemove:t,labels:n}){return e.length===0?null:/* @__PURE__ */ R(`div`,{className:`d-flex flex-column gap-2`,children:[/* @__PURE__ */ L(g,{children:e.map(e=>/* @__PURE__ */ L(h,{label:e.fileName,tone:e.status===`Failed`?`danger`:`neutral`,onRemove:()=>t(e.key),removeLabel:n.removeAttachment(e.fileName)},e.key))}),e.map(e=>e.progress===null?null:/* @__PURE__ */ L(w,{value:e.progress,max:1,size:`sm`,label:e.fileName},e.key)),e.filter(e=>e.status===`Failed`).map(e=>/* @__PURE__ */ L(`span`,{className:`small text-danger`,role:`alert`,children:e.error},e.key))]})}function be({onSubmit:e,busy:t=!1,disabled:n=!1,maxLength:r=4e3,inputRef:i,attachments:a=[],onAttach:o,onRemoveAttachment:s,accept:c,onStop:l,editing:d=null,onCancelEdit:f,labels:m}){let h=u(m),g=j(),_=N(null),[v,y]=P(``),b=a.some(e=>e.status===`Uploading`),x=t||n||b||!v.trim();A(()=>{d&&y(d.text)},[d]);function S(){x||(e(v.trim()),y(``))}function C(e){let t=Array.from(e.target.files??[]);e.target.value=``,t.length>0&&o(t)}return/* @__PURE__ */ R(`div`,{className:`d-flex flex-column gap-2`,children:[d&&f&&/* @__PURE__ */ R(`div`,{className:`wui-chat-editing`,children:[/* @__PURE__ */ L(`span`,{className:`small text-body-secondary`,children:h.editing}),/* @__PURE__ */ L(p,{type:`button`,size:`sm`,variant:`ghost`,onClick:f,children:h.cancel})]}),/* @__PURE__ */ L(ye,{attachments:a,onRemove:e=>s?.(e),labels:h}),/* @__PURE__ */ R(`form`,{className:`wui-chat-composer d-flex align-items-end gap-2`,"aria-label":h.composer,onSubmit:e=>{e.preventDefault(),S()},children:[o&&/* @__PURE__ */ R(I,{children:[/* @__PURE__ */ L(p,{type:`button`,variant:`ghost`,leftIcon:`paperclip`,disabled:n,"aria-describedby":`${g}-attach-hint`,onClick:()=>_.current?.click(),children:/* @__PURE__ */ L(`span`,{className:`visually-hidden`,children:h.attach})}),/* @__PURE__ */ L(`span`,{id:`${g}-attach-hint`,className:`visually-hidden`,children:h.attachHint}),/* @__PURE__ */ L(`input`,{ref:_,type:`file`,multiple:!0,accept:c,hidden:!0,onChange:C})]}),/* @__PURE__ */ L(D,{id:`${g}-message`,"aria-label":h.composer,"aria-describedby":`${g}-hint`,placeholder:h.placeholder,rows:1,autoGrow:!0,maxLength:r,value:v,disabled:n,ref:i,fieldClassName:`flex-grow-1 mb-0`,onChange:e=>y(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&!e.nativeEvent.isComposing&&(e.preventDefault(),S())}}),/* @__PURE__ */ L(`span`,{id:`${g}-hint`,className:`visually-hidden`,children:h.composerHint}),t&&l?/* @__PURE__ */ L(p,{type:`button`,leftIcon:`stop`,onClick:l,children:/* @__PURE__ */ L(`span`,{className:`visually-hidden`,children:h.stop})}):/* @__PURE__ */ L(p,{type:`submit`,leftIcon:`send`,disabled:x,children:/* @__PURE__ */ L(`span`,{className:`visually-hidden`,children:h.send})})]})]})}function xe({client:e,onOpen:t,onDeleted:n,pageSize:r=20,labels:i}){let a=u(i),o=M(()=>s({client:e,pageSize:r}),[e,r]),c=F(o.subscribe,o.getState),[l,h]=P(null),[g,v]=P(!1),[y,x]=P(``),[C,w]=P(null),[E,D]=P(``),[O,k]=P(!1),[j,N]=P(``),[I,z]=P(void 0),[B,V]=P(``);A(()=>(o.load(),o.dispose),[o]),A(()=>{if(typeof e.getSettings!=`function`)return;let t=!0;return Promise.resolve().then(()=>e.getSettings()).then(e=>{t&&z(e.titleMaxLength)}).catch(e=>{t&&V(e?.message||a.loadFailed)}),()=>{t=!1}},[e,a.loadFailed]);async function H(){v(!0),x(``);try{await o.remove(l.publicId),n?.(l.publicId),h(null)}catch(e){x(e?.message||a.deleteFailed)}finally{v(!1)}}function U(e){O||(w(e.publicId),D(e.title||``),N(``))}function W(){w(null),N(``)}async function G(e){if(!(O||E.trim()===``)){k(!0),N(``);try{await o.rename(e,E),w(null)}catch(e){N(e?.message||a.renameFailed)}finally{k(!1)}}}let K=c.totalCount===null&&c.error===null;return!c.loading&&!K&&!c.error&&c.items.length===0?/* @__PURE__ */ L(b,{icon:`chat`,size:`sm`,title:a.conversationsEmptyTitle,text:a.conversationsEmptyText}):/* @__PURE__ */ R(`div`,{className:`d-flex flex-column gap-3`,children:[c.error&&/* @__PURE__ */ L(f,{tone:`danger`,action:/* @__PURE__ */ L(p,{size:`sm`,variant:`secondary`,onClick:()=>o.load(),children:a.retry}),children:c.error.message}),c.items.length>0&&/* @__PURE__ */ L(`ul`,{className:`list-unstyled d-flex flex-column gap-2 mb-0`,"aria-label":a.conversations,children:c.items.map(e=>/* @__PURE__ */ L(`li`,{children:C===e.publicId?/* @__PURE__ */ R(m,{padding:`sm`,className:`border`,bodyClassName:`d-flex flex-column gap-2`,children:[/* @__PURE__ */ R(`div`,{className:`d-flex align-items-center gap-2`,children:[/* @__PURE__ */ L(S,{size:`sm`,"aria-label":a.conversationTitle,fieldClassName:`flex-grow-1 mb-0`,value:E,maxLength:I,autoFocus:!0,onChange:e=>D(e.target.value),onKeyDown:t=>{t.key===`Enter`?(t.preventDefault(),G(e.publicId)):t.key===`Escape`&&(t.preventDefault(),W())}}),/* @__PURE__ */ L(p,{variant:`primary`,size:`sm`,loading:O,disabled:O||E.trim()===``,onClick:()=>G(e.publicId),children:a.renameSave}),/* @__PURE__ */ L(p,{variant:`secondary`,size:`sm`,onClick:W,children:a.cancel})]}),(j||B)&&/* @__PURE__ */ L(f,{tone:`danger`,size:`sm`,children:j||B})]}):/* @__PURE__ */ R(m,{padding:`sm`,className:`border`,bodyClassName:`d-flex align-items-center gap-2`,children:[/* @__PURE__ */ L(p,{variant:`ghost`,className:`flex-grow-1 text-start`,style:{minWidth:0},onClick:()=>t(e),children:/* @__PURE__ */ R(`span`,{className:`d-flex flex-column`,style:{minWidth:0},children:[/* @__PURE__ */ L(`span`,{className:`text-truncate fw-semibold`,children:e.title||a.untitled}),/* @__PURE__ */ L(`time`,{dateTime:e.lastMessageDateTimeUtc,className:`wui-text-xs text-body-secondary`,children:ee(e.lastMessageDateTimeUtc)})]})}),/* @__PURE__ */ L(d,{icon:`edit`,label:a.renameConversation,onClick:()=>U(e)}),/* @__PURE__ */ L(d,{icon:`trash-2`,danger:!0,label:a.deleteConversation,onClick:()=>{x(``),h(e)}})]})},e.publicId))}),(c.loading||K)&&/* @__PURE__ */ R(`div`,{className:`d-flex flex-column gap-2`,"aria-hidden":`true`,children:[/* @__PURE__ */ L(T,{height:44}),/* @__PURE__ */ L(T,{height:44}),/* @__PURE__ */ L(T,{height:44})]}),!c.loading&&c.hasMore&&/* @__PURE__ */ L(p,{variant:`secondary`,className:`align-self-center`,onClick:()=>o.loadMore(),children:a.loadMore}),/* @__PURE__ */ L(_,{open:l!==null,title:a.deleteConfirmTitle,message:y?/* @__PURE__ */ L(f,{tone:`danger`,children:y}):a.deleteConfirmMessage,confirmLabel:a.deleteConfirm,cancelLabel:a.cancel,danger:!0,loading:g,onConfirm:H,onClose:()=>{g||h(null)}})]})}var Se={zIndex:`var(--wui-z-fixed)`,bottom:`var(--wui-consent-banner-block, 0px)`},Ce={end:{insetInlineEnd:0},start:{insetInlineStart:0}};function we({onClick:e,open:t=!1,position:n=`end`,icon:r=`sparkles`,compact:i=!1,className:a,style:o,labels:s}){let c=u(s);return i?/* @__PURE__ */ L(Te,{onClick:e,open:t,position:n,icon:r,className:a,style:o,label:c.launcher}):/* @__PURE__ */ L(`span`,{"data-support-capture":`exclude`,className:[`position-fixed m-3`,a].filter(Boolean).join(` `),style:{...Se,...Ce[n],...o},children:/* @__PURE__ */ L(p,{leftIcon:r,className:`rounded-pill`,onClick:e,"aria-haspopup":`dialog`,"aria-expanded":t,children:c.launcher})})}function Te({onClick:e,open:t,position:n,icon:r,className:i,style:a,label:o}){let s=O(n);return s?z(/* @__PURE__ */ L(`span`,{className:[`wui-floating-stack-item wui-floating-stack-item--primary`,i].filter(Boolean).join(` `),style:a,children:/* @__PURE__ */ L(p,{className:`wui-floating-btn`,onClick:e,"aria-label":o,"aria-haspopup":`dialog`,"aria-expanded":t,tooltip:o,tooltipPlacement:n===`start`?`end`:`start`,children:/* @__PURE__ */ L(x,{name:r,size:24})})}),s):null}function Ee({text:e,resolveLink:t,linkComponent:n,isCitation:r,onOpenCitation:i,className:a}){return/* @__PURE__ */ L(C,{value:e,links:`app`,headings:`text`,resolveLink:t,linkComponent:n,isCitation:r,onOpenCitation:i,className:a})}function De({rating:e,onRate:t,noteMaxLength:n=1e3,labels:r}){let i=u(r),a=j(),[o,s]=P(!1),[c,l]=P(!1),[d,m]=P(``),[h,g]=P(``),[_,v]=P(!1);async function y(e,n){s(!0),g(``);try{await t(e,n),l(e===`Down`&&n===void 0),v(e===`Up`||n!==void 0),n!==void 0&&m(``)}catch{g(i.ratingFailed)}finally{s(!1)}}return/* @__PURE__ */ R(`div`,{className:`d-flex flex-column gap-2`,children:[/* @__PURE__ */ R(`div`,{className:`d-flex flex-wrap align-items-center gap-1`,children:[/* @__PURE__ */ L(p,{size:`sm`,variant:e===`Up`?`neutral`:`ghost`,leftIcon:`check`,"aria-pressed":e===`Up`,disabled:o,onClick:()=>y(`Up`),children:i.rateUp}),/* @__PURE__ */ L(p,{size:`sm`,variant:e===`Down`?`neutral`:`ghost`,leftIcon:`x`,"aria-pressed":e===`Down`,disabled:o,onClick:()=>y(`Down`),children:i.rateDown}),_&&!c&&/* @__PURE__ */ L(`span`,{className:`wui-text-xs text-body-secondary`,role:`status`,children:i.rated})]}),h&&/* @__PURE__ */ L(f,{size:`sm`,tone:`danger`,children:h}),c&&/* @__PURE__ */ R(`form`,{className:`d-flex flex-column gap-2`,onSubmit:e=>{e.preventDefault(),y(`Down`,d)},children:[/* @__PURE__ */ L(D,{id:`${a}-note`,label:i.ratingNote,hint:i.ratingNoteHint,rows:2,maxLength:n,value:d,onChange:e=>m(e.target.value)}),/* @__PURE__ */ R(`div`,{className:`d-flex gap-2`,children:[/* @__PURE__ */ L(p,{type:`submit`,size:`sm`,loading:o,children:i.ratingNoteSend}),/* @__PURE__ */ L(p,{size:`sm`,variant:`secondary`,disabled:o,onClick:()=>{l(!1),v(!0)},children:i.ratingNoteSkip})]})]})]})}var Oe={maxWidth:`85%`,whiteSpace:`pre-wrap`,overflowWrap:`anywhere`};function ke({turn:e,onRate:t,onRetry:n,onRegenerate:r,canRegenerate:i,onEdit:a,onOpenAttachment:o,resolveLink:s,linkComponent:c,isCitation:l,onOpenCitation:g,onAskSuggestion:_,confirmAction:y,onViewTicket:b,renderReply:x,labels:S}){let C=u(S),w=e.streaming&&!e.answer,T=!!e.answer&&!e.streaming,D=e.step?C.toolStep(e.step):C.thinking;return/* @__PURE__ */ R(`li`,{className:`d-flex flex-column gap-2`,children:[e.question&&/* @__PURE__ */ R(`div`,{className:`d-flex align-items-center gap-1 align-self-end`,children:[a&&e.questionId&&/* @__PURE__ */ L(d,{icon:`edit`,label:C.edit,onClick:()=>a(e.id)}),/* @__PURE__ */ R(`div`,{style:Oe,children:[/* @__PURE__ */ R(`span`,{className:`visually-hidden`,children:[C.you,`: `]}),/* @__PURE__ */ R(m,{padding:`sm`,variant:`muted`,className:`wui-text-sm`,children:[e.question,e.attachments?.length>0&&/* @__PURE__ */ L(`div`,{className:`wui-chat-question-attachments mt-2`,children:e.attachments.map(e=>/* @__PURE__ */ L(h,{label:e.fileName,leadingIcon:`document`,onClick:o?()=>o(e):void 0},e.publicId))})]})]})]}),/* @__PURE__ */ R(`div`,{className:`d-flex flex-column gap-2`,style:{minWidth:0},children:[/* @__PURE__ */ R(`span`,{className:`visually-hidden`,children:[C.assistant,`: `]}),/* @__PURE__ */ L(`div`,{"aria-live":`polite`,"aria-busy":e.streaming,children:e.stopped?/* @__PURE__ */ L(f,{size:`sm`,tone:`neutral`,children:C.stopped}):w?/* @__PURE__ */ R(`span`,{className:`d-inline-flex align-items-center gap-2 wui-text-sm text-body-secondary`,children:[/* @__PURE__ */ L(E,{size:`sm`,label:D}),/* @__PURE__ */ L(`span`,{"aria-hidden":`true`,children:D})]}):e.answer&&(x?x(e,{streaming:!!e.streaming}):/* @__PURE__ */ L(Ee,{text:e.answer,resolveLink:s,linkComponent:c,isCitation:l,onOpenCitation:g}))}),e.error&&/* @__PURE__ */ L(f,{size:`sm`,tone:`danger`,children:e.error.message}),n&&(e.error||e.stopped)&&/* @__PURE__ */ L(`div`,{children:/* @__PURE__ */ L(p,{variant:`outline`,size:`sm`,onClick:()=>n(e.id),children:C.retry})}),y&&!e.streaming&&e.actions.map(e=>/* @__PURE__ */ L(ve,{action:e,confirmAction:y,onViewTicket:b,labels:S},e.token)),(T||t&&e.messageId&&!e.streaming)&&/* @__PURE__ */ R(`div`,{className:`wui-chat-turn-actions align-items-center`,children:[T&&/* @__PURE__ */ L(v,{text:he(e.answer),label:C.copy,copiedLabel:C.copied,iconOnly:!0,size:`sm`,variant:`ghost`}),t&&e.messageId&&!e.streaming&&/* @__PURE__ */ L(De,{rating:e.rating,onRate:(n,r)=>t(e.id,n,r),labels:S}),r&&i&&T&&/* @__PURE__ */ L(p,{variant:`outline`,size:`sm`,leftIcon:`refresh`,onClick:()=>r(e.id),children:C.regenerate})]}),_&&!e.streaming&&e.suggestions.length>0&&/* @__PURE__ */ L(`div`,{className:`wui-chat-suggestions`,role:`group`,"aria-label":C.suggestions,children:e.suggestions.map(e=>/* @__PURE__ */ L(p,{variant:`outline`,size:`sm`,onClick:()=>_(e),children:e},e))})]})]})}var Ae=k(ke);function je(e){for(let t=e?.parentElement;t&&t!==document.body;t=t.parentElement){let{overflowY:e}=getComputedStyle(t);if((e===`auto`||e===`scroll`)&&t.scrollHeight>t.clientHeight)return t}return null}function Me({turns:e,empty:t,onRate:n,resolveLink:r,linkComponent:i,confirmAction:a,onViewTicket:o,renderReply:s,onRetry:c,onRegenerate:l,onAskSuggestion:d,isCitation:f,onOpenCitation:p,onEdit:m,onOpenAttachment:h,labels:g}){let _=u(g),v=N(null),y=e[e.length-1];return A(()=>{let e=je(v.current);e&&(e.scrollTop=e.scrollHeight)},[e.length,y?.answer,y?.error,y?.actions]),e.length===0?t??/* @__PURE__ */ L(b,{icon:`sparkles`,size:`sm`,title:_.emptyTitle,text:_.emptyText}):/* @__PURE__ */ R(I,{children:[/* @__PURE__ */ L(`ol`,{className:`list-unstyled d-flex flex-column gap-3 mb-0`,"aria-label":_.thread,children:e.map((t,u)=>/* @__PURE__ */ L(Ae,{turn:t,onRate:n,resolveLink:r,linkComponent:i,confirmAction:a,onViewTicket:o,renderReply:s,onRetry:u===e.length-1?c:void 0,onRegenerate:l,onAskSuggestion:u===e.length-1?d:void 0,isCitation:f,onOpenCitation:p,canRegenerate:u===e.length-1,onEdit:m,onOpenAttachment:h,labels:g},t.id))}),/* @__PURE__ */ L(`div`,{ref:v})]})}function Ne({chat:e,open:t,onClose:n,title:r,titleIcon:i=`sparkles`,headerActions:a,empty:o,disclaimer:s,maxLength:c=4e3,allowanceThreshold:l=10,width:p=`440px`,resolveLink:m,linkComponent:h,confirmAction:g,onViewTicket:_,rating:v=!0,renderReply:b,openAttachment:S,conversations:C=!1,isCitation:w,onOpenCitation:T,labels:D}){let O=u(D),k=N(null),{refreshAllowance:j}=e,M=e.settings?.attachments,F=M?.contentTypes.join(`,`),[ee,z]=P(`chat`);A(()=>{t&&j().catch(()=>{})},[t,j]),A(()=>{t||z(`chat`)},[t]);let B=e.messagesLeftToday,V=r??O.panelTitle,H=C&&ee===`conversations`,U=/* @__PURE__ */ R(`div`,{className:`drawer-header`,children:[/* @__PURE__ */ R(`div`,{className:`drawer-title`,children:[i&&/* @__PURE__ */ L(`span`,{className:`drawer-title-ic`,children:/* @__PURE__ */ L(x,{name:i,size:18})}),V]}),/* @__PURE__ */ R(`div`,{className:`d-flex align-items-center gap-1`,children:[a,H?/* @__PURE__ */ L(d,{icon:`arrow-left`,label:O.backToChat,onClick:()=>z(`chat`)}):/* @__PURE__ */ R(I,{children:[C&&/* @__PURE__ */ L(d,{icon:`history`,label:O.conversations,onClick:()=>z(`conversations`)}),/* @__PURE__ */ L(d,{icon:`plus`,label:O.newChat,onClick:e.newConversation,disabled:e.turns.length===0&&!e.loading})]}),/* @__PURE__ */ L(d,{icon:`x`,label:O.close,onClick:n})]})]}),W=/* @__PURE__ */ R(`div`,{className:`d-flex flex-column gap-2`,children:[B!==null&&B<=l&&/* @__PURE__ */ L(`p`,{className:`wui-text-xs text-body-secondary mb-0`,role:`status`,children:O.allowance(B)}),e.settingsError&&/* @__PURE__ */ L(f,{tone:`danger`,children:e.settingsError.message}),/* @__PURE__ */ L(be,{onSubmit:e.submit,busy:e.streaming||e.loading,disabled:B===0,maxLength:c,inputRef:k,attachments:e.attachments,onAttach:M?e.attach:void 0,onRemoveAttachment:e.removeAttachment,accept:F,onStop:e.streaming?e.stop:void 0,editing:e.editing,onCancelEdit:e.cancelEdit,labels:D}),/* @__PURE__ */ L(`p`,{className:`wui-text-xs text-body-secondary mb-0`,children:s??O.disclaimer})]});return/* @__PURE__ */ L(y,{open:t,onClose:n,sheet:!1,width:p,header:U,footer:H?void 0:W,ariaLabel:typeof V==`string`?V:O.panelTitle,onOpened:()=>k.current?.focus(),children:H?/* @__PURE__ */ L(xe,{client:e.client,onOpen:t=>{e.openConversation(t.publicId),z(`chat`)},onDeleted:t=>{t===e.conversationId&&e.newConversation()},labels:D}):e.loading?/* @__PURE__ */ L(`div`,{className:`d-flex justify-content-center py-4`,children:/* @__PURE__ */ L(E,{label:O.loadingConversation})}):e.loadError?/* @__PURE__ */ L(f,{tone:`danger`,children:e.loadError.message}):/* @__PURE__ */ L(Me,{turns:e.turns,empty:o,onRate:v?e.rate:void 0,onRetry:e.retry,onRegenerate:e.regenerate,onAskSuggestion:e.submit,isCitation:w,onOpenCitation:T,onEdit:e.startEdit,onOpenAttachment:S,resolveLink:m,linkComponent:h,confirmAction:g,onViewTicket:_,renderReply:b,labels:D})})}function Pe({citation:e,label:t,ariaLabel:n,onOpen:r}){return/* @__PURE__ */ L(h,{label:t??e,size:`sm`,tone:`primary`,variant:`outline`,leadingIcon:`book-1`,"aria-label":n??e,onClick:()=>r(e)})}function Fe({title:e,subtitle:t,lines:n,note:r,onConfirm:i,labels:a}){let o=u(a),[s,c]=P(`ready`),[l,d]=P(null),[h,g]=P(``);if(s===`dismissed`)return/* @__PURE__ */ L(`p`,{className:`wui-text-sm text-body-secondary mb-0`,children:o.actionDismissed});if(s===`done`)return/* @__PURE__ */ L(f,{tone:`success`,role:`status`,size:`sm`,children:l?.message||o.actionDone});async function _(){c(`sending`),g(``);try{let e=await i();d(e??null),c(`done`)}catch(e){g(e?.message||o.actionFailed),c(`ready`)}}let v=s===`sending`;return/* @__PURE__ */ L(m,{padding:`sm`,className:`border`,title:e,subtitle:t||void 0,children:/* @__PURE__ */ R(`div`,{className:`d-flex flex-column gap-2`,children:[(n??[]).map((e,t)=>/* @__PURE__ */ L(`p`,{className:`wui-text-sm mb-0`,style:{whiteSpace:`pre-wrap`,overflowWrap:`anywhere`},children:e},t)),/* @__PURE__ */ L(`p`,{className:`wui-text-xs text-body-secondary mb-0`,children:r??o.actionNote}),h&&/* @__PURE__ */ L(f,{size:`sm`,tone:`danger`,children:h}),/* @__PURE__ */ R(`div`,{className:`d-flex flex-wrap gap-2`,children:[/* @__PURE__ */ L(p,{size:`sm`,loading:v,onClick:_,children:o.actionConfirm}),/* @__PURE__ */ L(p,{size:`sm`,variant:`secondary`,disabled:v,onClick:()=>c(`dismissed`),children:o.actionDismiss})]})]})})}function Ie({client:e,pageContext:t}){let n=N(t);n.current=t;let r=M(()=>a({client:e,pageContext:()=>n.current}),[e]);A(()=>()=>r.dispose(),[r]);let i=F(r.subscribe,r.getState),o=M(()=>({submit:e=>r.submit(e),stop:()=>r.stop(),retry:e=>r.retry(e),regenerate:e=>r.regenerate(e),startEdit:e=>r.startEdit(e),cancelEdit:()=>r.cancelEdit(),attach:e=>r.attach(e),removeAttachment:e=>r.removeAttachment(e),openConversation:e=>r.openConversation(e),newConversation:()=>r.newConversation(),rate:(e,t,n)=>r.rate(e,t,n),refreshAllowance:()=>r.refreshAllowance(),reset:()=>r.reset()}),[r]);return{...i,...o,client:r.client}}export{ve as ActionCard,e as CHAT_CONTRACT_VERSION,t as ChatApiError,be as ChatComposer,xe as ChatConversationList,we as ChatLauncher,Ee as ChatMarkdown,Ae as ChatMessage,Ne as ChatPanel,Me as ChatThread,Pe as CitationChip,Fe as ConfirmCard,n as DEFAULT_CHAT_LABELS,De as ReplyRating,r as createChatClient,i as createChatSession,o as createConversationList,c as createSseParser,l as mergeLabels,V as splitCitations,Ie as useChat};
@@ -2,7 +2,7 @@
2
2
  "format": "webority-guidance/1",
3
3
  "package": {
4
4
  "name": "@webority/chat-react",
5
- "version": "0.121.0"
5
+ "version": "0.124.0"
6
6
  },
7
7
  "components": [
8
8
  {
@@ -49,7 +49,8 @@
49
49
  "a11y": [
50
50
  "The chats are a list named by the conversations label.",
51
51
  "Each chat is a button showing its title and a time element that carries the date, and the delete icon button is named by the delete label.",
52
- "Deleting asks for confirmation in a dialog first, and the loading skeleton is hidden from assistive technology."
52
+ "Deleting asks for confirmation in a dialog first, and the loading skeleton is hidden from assistive technology.",
53
+ "Renaming turns the row into a labelled text field: Enter saves, Escape cancels, and only one row edits at a time."
53
54
  ]
54
55
  }
55
56
  },
@@ -162,7 +163,7 @@
162
163
  "usage": {
163
164
  "when": [
164
165
  "Show a source the assistant named in a reply as a small chip the person can select to open it.",
165
- "Pair it with splitCitations to turn [source] runs in reply text into chips."
166
+ "Pair it with splitCitations from @webority/markdown-core (re-exported by @webority/chat-react) to turn [source] runs in reply text into chips."
166
167
  ],
167
168
  "whenNot": [
168
169
  {
@@ -5,16 +5,16 @@
5
5
  * conversation) still shows what was offered, without a button that could only fail.
6
6
  *
7
7
  * @param {object} props
8
- * @param {import('@webority/ui-elements/chat-core').SupportAction} props.action
8
+ * @param {import('@webority/chat-core').SupportAction} props.action
9
9
  * @param {(token: string) => Promise<{ id: string, number: string }>} props.confirmAction Sends the
10
10
  * person's yes, e.g. `supportClient.confirmAction`; resolves to the ticket raised, replied on or
11
11
  * reopened. A rejection's `message` is shown when present.
12
12
  * @param {(ticket: { id: string, number: string }) => void} [props.onViewTicket] Shows a View
13
13
  * ticket button once confirmed.
14
- * @param {Partial<typeof import('@webority/ui-elements/chat-core').DEFAULT_CHAT_LABELS>} [props.labels]
14
+ * @param {Partial<typeof import('@webority/chat-core').DEFAULT_CHAT_LABELS>} [props.labels]
15
15
  */
16
16
  export default function ActionCard({ action, confirmAction, onViewTicket, labels: labelOverrides }: {
17
- action: import('@webority/ui-elements/chat-core').SupportAction;
17
+ action: import('@webority/chat-core').SupportAction;
18
18
  confirmAction: (token: string) => Promise<{
19
19
  id: string;
20
20
  number: string;
@@ -23,5 +23,5 @@ export default function ActionCard({ action, confirmAction, onViewTicket, labels
23
23
  id: string;
24
24
  number: string;
25
25
  }) => void;
26
- labels?: Partial<typeof import('@webority/ui-elements/chat-core').DEFAULT_CHAT_LABELS>;
26
+ labels?: Partial<typeof import('@webority/chat-core').DEFAULT_CHAT_LABELS>;
27
27
  }): import("react").JSX.Element;
@@ -1,6 +1,8 @@
1
1
  /**
2
2
  * The question box. Enter sends; Shift and Enter starts a new line. The box clears once a
3
3
  * question is handed on, and stays usable while an answer streams, though sending waits for it.
4
+ * While an answer streams, Stop replaces Send when `onStop` is given. Sending also waits for
5
+ * every attachment to finish uploading.
4
6
  *
5
7
  * @param {object} props
6
8
  * @param {(message: string) => unknown} props.onSubmit Called with the trimmed question.
@@ -8,13 +10,29 @@
8
10
  * @param {boolean} [props.disabled]
9
11
  * @param {number} [props.maxLength]
10
12
  * @param {import('react').Ref<HTMLTextAreaElement>} [props.inputRef] The question box, for focusing it.
11
- * @param {Partial<typeof import('@webority/ui-elements/chat-core').DEFAULT_CHAT_LABELS>} [props.labels]
13
+ * @param {import('@webority/chat-core').ComposerAttachment[]} [props.attachments]
14
+ * @param {(files: File[]) => unknown} [props.onAttach] Shows the attach button; called with the picked files.
15
+ * @param {(key: string) => unknown} [props.onRemoveAttachment] Called with an attachment's key.
16
+ * @param {string} [props.accept] The file types the picker offers, as an `accept` string.
17
+ * @param {() => unknown} [props.onStop] Shows Stop in place of Send while busy.
18
+ * @param {{ text: string } | null} [props.editing] When set, the box takes its text and shows the editing notice.
19
+ * @param {() => unknown} [props.onCancelEdit] Shows the Cancel button beside the editing notice.
20
+ * @param {Partial<typeof import('@webority/chat-core').DEFAULT_CHAT_LABELS>} [props.labels]
12
21
  */
13
- export default function ChatComposer({ onSubmit, busy, disabled, maxLength, inputRef, labels: labelOverrides }: {
22
+ export default function ChatComposer({ onSubmit, busy, disabled, maxLength, inputRef, attachments, onAttach, onRemoveAttachment, accept, onStop, editing, onCancelEdit, labels: labelOverrides, }: {
14
23
  onSubmit: (message: string) => unknown;
15
24
  busy?: boolean;
16
25
  disabled?: boolean;
17
26
  maxLength?: number;
18
27
  inputRef?: import('react').Ref<HTMLTextAreaElement>;
19
- labels?: Partial<typeof import('@webority/ui-elements/chat-core').DEFAULT_CHAT_LABELS>;
28
+ attachments?: import('@webority/chat-core').ComposerAttachment[];
29
+ onAttach?: (files: File[]) => unknown;
30
+ onRemoveAttachment?: (key: string) => unknown;
31
+ accept?: string;
32
+ onStop?: () => unknown;
33
+ editing?: {
34
+ text: string;
35
+ } | null;
36
+ onCancelEdit?: () => unknown;
37
+ labels?: Partial<typeof import('@webority/chat-core').DEFAULT_CHAT_LABELS>;
20
38
  }): import("react").JSX.Element;
@@ -19,6 +19,22 @@ export declare const meta: {
19
19
  readonly default: 4000;
20
20
  readonly description: "The longest question the box accepts, matching the server's message limit.";
21
21
  };
22
+ readonly attachments: {
23
+ readonly type: "array";
24
+ readonly required: false;
25
+ readonly default: readonly [];
26
+ readonly description: "The files attached to the question being written, each with its upload status. Sending waits while one is uploading.";
27
+ };
28
+ readonly accept: {
29
+ readonly type: "string";
30
+ readonly required: false;
31
+ readonly description: "The file types the picker offers, as an accept string such as image/png,application/pdf.";
32
+ };
33
+ readonly editing: {
34
+ readonly type: "object";
35
+ readonly required: false;
36
+ readonly description: "When set, the box takes its text and shows the editing notice. Shape: { text }.";
37
+ };
22
38
  readonly labels: {
23
39
  readonly type: "object";
24
40
  readonly description: "Overrides for the component's text, keyed by label name. A key left out keeps its default.";
@@ -1,20 +1,20 @@
1
1
  /**
2
2
  * The person's past chats, newest first, for a past-chats page or a panel. It pages with Show
3
- * more, opens one through `onOpen`, and deletes one after a confirm.
3
+ * more, opens one through `onOpen`, renames one in place, and deletes one after a confirm.
4
4
  *
5
5
  * @param {object} props
6
- * @param {import('@webority/ui-elements/chat-core').ChatClient} props.client
7
- * @param {(conversation: import('@webority/ui-elements/chat-core').ConversationSummary) => void} props.onOpen
6
+ * @param {import('@webority/chat-core').ChatClient} props.client
7
+ * @param {(conversation: import('@webority/chat-core').ConversationSummary) => void} props.onOpen
8
8
  * E.g. open the panel and call `chat.openConversation(conversation.publicId)`.
9
9
  * @param {(id: string) => void} [props.onDeleted] Called after a chat is deleted, e.g. to start a
10
10
  * new chat when the open one was deleted.
11
11
  * @param {number} [props.pageSize]
12
- * @param {Partial<typeof import('@webority/ui-elements/chat-core').DEFAULT_CHAT_LABELS>} [props.labels]
12
+ * @param {Partial<typeof import('@webority/chat-core').DEFAULT_CHAT_LABELS>} [props.labels]
13
13
  */
14
14
  export default function ChatConversationList({ client, onOpen, onDeleted, pageSize, labels: labelOverrides }: {
15
- client: import('@webority/ui-elements/chat-core').ChatClient;
16
- onOpen: (conversation: import('@webority/ui-elements/chat-core').ConversationSummary) => void;
15
+ client: import('@webority/chat-core').ChatClient;
16
+ onOpen: (conversation: import('@webority/chat-core').ConversationSummary) => void;
17
17
  onDeleted?: (id: string) => void;
18
18
  pageSize?: number;
19
- labels?: Partial<typeof import('@webority/ui-elements/chat-core').DEFAULT_CHAT_LABELS>;
19
+ labels?: Partial<typeof import('@webority/chat-core').DEFAULT_CHAT_LABELS>;
20
20
  }): import("react").JSX.Element;
@@ -32,6 +32,6 @@ export declare const meta: {
32
32
  readonly whenNot: readonly [];
33
33
  readonly do: readonly [];
34
34
  readonly dont: readonly [];
35
- readonly a11y: readonly ["The chats are a list named by the conversations label.", "Each chat is a button showing its title and a time element that carries the date, and the delete icon button is named by the delete label.", "Deleting asks for confirmation in a dialog first, and the loading skeleton is hidden from assistive technology."];
35
+ readonly a11y: readonly ["The chats are a list named by the conversations label.", "Each chat is a button showing its title and a time element that carries the date, and the delete icon button is named by the delete label.", "Deleting asks for confirmation in a dialog first, and the loading skeleton is hidden from assistive technology.", "Renaming turns the row into a labelled text field: Enter saves, Escape cancels, and only one row edits at a time."];
36
36
  };
37
37
  };
@@ -17,7 +17,7 @@
17
17
  * @param {boolean} [props.compact]
18
18
  * @param {string} [props.className]
19
19
  * @param {import('react').CSSProperties} [props.style] Merged over the wrapper's own style.
20
- * @param {Partial<typeof import('@webority/ui-elements/chat-core').DEFAULT_CHAT_LABELS>} [props.labels]
20
+ * @param {Partial<typeof import('@webority/chat-core').DEFAULT_CHAT_LABELS>} [props.labels]
21
21
  */
22
22
  export default function ChatLauncher({ onClick, open, position, icon, compact, className, style, labels: labelOverrides, }: {
23
23
  onClick: () => void;
@@ -27,5 +27,5 @@ export default function ChatLauncher({ onClick, open, position, icon, compact, c
27
27
  compact?: boolean;
28
28
  className?: string;
29
29
  style?: import('react').CSSProperties;
30
- labels?: Partial<typeof import('@webority/ui-elements/chat-core').DEFAULT_CHAT_LABELS>;
30
+ labels?: Partial<typeof import('@webority/chat-core').DEFAULT_CHAT_LABELS>;
31
31
  }): import("react").JSX.Element;
@@ -4,22 +4,44 @@
4
4
  * marked busy. Support actions show under the answer, and the rating once the reply is stored.
5
5
  *
6
6
  * @param {object} props
7
- * @param {import('../useChat.js').ChatTurn} props.turn
7
+ * @param {import('@webority/chat-core').ChatTurn} props.turn
8
8
  * @param {(turnId: string, rating: "Up"|"Down", note?: string) => Promise<unknown>} [props.onRate]
9
9
  * Shows the rating under a stored reply.
10
+ * @param {(turnId: string) => void} [props.onRetry] Offers "Try again" under a failed or stopped turn.
11
+ * @param {(turnId: string) => void} [props.onRegenerate] Offers "New answer" under an answered turn.
12
+ * @param {boolean} [props.canRegenerate] Set on the last turn only, so an older answer has no "New answer".
13
+ * @param {(text: string) => void} [props.onAskSuggestion] Sends a suggested follow-up question; the suggestions show under a settled answer.
14
+ * @param {(inner: string) => boolean} [props.isCitation] Returns true for a run of the answer that is a citation to draw as a chip; see `ChatMarkdown`.
15
+ * @param {(citation: string) => void} [props.onOpenCitation] Called with the citation text when its chip is pressed; see `ChatMarkdown`.
16
+ * @param {(turnId: string) => void} [props.onEdit] Offers an Edit button beside a question that has a `questionId`.
17
+ * @param {(attachment: { publicId: string, fileName: string, contentType: string, length: number }) => void} [props.onOpenAttachment]
18
+ * Makes each attachment chip on the question a button.
10
19
  * @param {(href: string) => string|null|undefined} [props.resolveLink] See `ChatMarkdown`.
11
20
  * @param {import('react').ElementType} [props.linkComponent] A router link (it receives `to`).
12
21
  * @param {(token: string) => Promise<{ id: string, number: string }>} [props.confirmAction] Shows
13
22
  * support action cards; see `ActionCard`.
14
23
  * @param {(ticket: { id: string, number: string }) => void} [props.onViewTicket]
15
- * @param {(turn: import('../useChat.js').ChatTurn, state: { streaming: boolean }) => import('react').ReactNode} [props.renderReply]
24
+ * @param {(turn: import('@webority/chat-core').ChatTurn, state: { streaming: boolean }) => import('react').ReactNode} [props.renderReply]
16
25
  * Draws the assistant's answer in place of `ChatMarkdown` (charts, maths). The question, action
17
26
  * cards, rating and layout stay the library's.
18
- * @param {Partial<typeof import('@webority/ui-elements/chat-core').DEFAULT_CHAT_LABELS>} [props.labels]
27
+ * @param {Partial<import('@webority/chat-core').ChatLabels>} [props.labels]
19
28
  */
20
- declare function ChatMessage({ turn, onRate, resolveLink, linkComponent, confirmAction, onViewTicket, renderReply, labels: labelOverrides }: {
21
- turn: import('../useChat.js').ChatTurn;
29
+ declare function ChatMessage({ turn, onRate, onRetry, onRegenerate, canRegenerate, onEdit, onOpenAttachment, resolveLink, linkComponent, isCitation, onOpenCitation, onAskSuggestion, confirmAction, onViewTicket, renderReply, labels: labelOverrides, }: {
30
+ turn: import('@webority/chat-core').ChatTurn;
22
31
  onRate?: (turnId: string, rating: "Up" | "Down", note?: string) => Promise<unknown>;
32
+ onRetry?: (turnId: string) => void;
33
+ onRegenerate?: (turnId: string) => void;
34
+ canRegenerate?: boolean;
35
+ onAskSuggestion?: (text: string) => void;
36
+ isCitation?: (inner: string) => boolean;
37
+ onOpenCitation?: (citation: string) => void;
38
+ onEdit?: (turnId: string) => void;
39
+ onOpenAttachment?: (attachment: {
40
+ publicId: string;
41
+ fileName: string;
42
+ contentType: string;
43
+ length: number;
44
+ }) => void;
23
45
  resolveLink?: (href: string) => string | null | undefined;
24
46
  linkComponent?: import('react').ElementType;
25
47
  confirmAction?: (token: string) => Promise<{
@@ -30,10 +52,10 @@ declare function ChatMessage({ turn, onRate, resolveLink, linkComponent, confirm
30
52
  id: string;
31
53
  number: string;
32
54
  }) => void;
33
- renderReply?: (turn: import('../useChat.js').ChatTurn, state: {
55
+ renderReply?: (turn: import('@webority/chat-core').ChatTurn, state: {
34
56
  streaming: boolean;
35
57
  }) => import('react').ReactNode;
36
- labels?: Partial<typeof import('@webority/ui-elements/chat-core').DEFAULT_CHAT_LABELS>;
58
+ labels?: Partial<import('@webority/chat-core').ChatLabels>;
37
59
  }): import("react").JSX.Element;
38
60
  declare const _default: import("react").MemoExoticComponent<typeof ChatMessage>;
39
61
  export default _default;
@@ -77,8 +77,28 @@ export declare const meta: {
77
77
  readonly required: false;
78
78
  readonly description: "The note saved with the rating.";
79
79
  };
80
+ readonly questionId: {
81
+ readonly type: "string";
82
+ readonly required: false;
83
+ readonly description: "The stored question's id. Edit needs it; unset until the server answers.";
84
+ };
85
+ readonly attachments: {
86
+ readonly type: "array";
87
+ readonly required: false;
88
+ readonly description: "Files attached to the question, shown as chips under it.";
89
+ };
90
+ readonly stopped: {
91
+ readonly type: "boolean";
92
+ readonly required: false;
93
+ readonly description: "True when the person stopped the turn. Shows the stopped notice where the answer goes.";
94
+ };
80
95
  };
81
96
  };
97
+ readonly canRegenerate: {
98
+ readonly type: "boolean";
99
+ readonly required: false;
100
+ readonly description: "Set on the last turn only, so an older answer has no New answer button.";
101
+ };
82
102
  readonly labels: {
83
103
  readonly type: "object";
84
104
  readonly required: false;
@@ -4,6 +4,9 @@
4
4
  * the questions left today (once 10 or fewer remain) and the AI footnote. Focus stays inside
5
5
  * while it is open, Escape closes it, and the question box takes focus when it opens.
6
6
  *
7
+ * With `conversations`, a history icon shows the person's past chats in place of the body and
8
+ * the footer; a back icon returns to the chat. Closing the drawer returns to the chat.
9
+ *
7
10
  * @param {object} props
8
11
  * @param {ReturnType<typeof import('../useChat.js').useChat>} props.chat
9
12
  * @param {boolean} props.open
@@ -24,9 +27,15 @@
24
27
  * @param {boolean} [props.rating=true]
25
28
  * @param {(turn: import('../useChat.js').ChatTurn, state: { streaming: boolean }) => import('react').ReactNode} [props.renderReply]
26
29
  * Draws each assistant answer instead of `ChatMarkdown`; see `ChatMessage`.
27
- * @param {Partial<typeof import('@webority/ui-elements/chat-core').DEFAULT_CHAT_LABELS>} [props.labels]
30
+ * @param {(attachment: { publicId: string, fileName: string, contentType: string, length: number }) => void} [props.openAttachment]
31
+ * Opens a file on a question; the session has no open action, so the app supplies one (for example
32
+ * with `client.getAttachment` and a blob URL).
33
+ * @param {boolean} [props.conversations=false] Offers the person's past chats from a header icon.
34
+ * @param {(inner: string) => boolean} [props.isCitation] Passed to `ChatThread`; see `ChatMarkdown`.
35
+ * @param {(citation: string) => void} [props.onOpenCitation] Passed to `ChatThread`; see `ChatMarkdown`.
36
+ * @param {Partial<typeof import('@webority/chat-core').DEFAULT_CHAT_LABELS>} [props.labels]
28
37
  */
29
- export default function ChatPanel({ chat, open, onClose, title, titleIcon, headerActions, empty, disclaimer, maxLength, allowanceThreshold, width, resolveLink, linkComponent, confirmAction, onViewTicket, rating, renderReply, labels: labelOverrides, }: {
38
+ export default function ChatPanel({ chat, open, onClose, title, titleIcon, headerActions, empty, disclaimer, maxLength, allowanceThreshold, width, resolveLink, linkComponent, confirmAction, onViewTicket, rating, renderReply, openAttachment, conversations, isCitation, onOpenCitation, labels: labelOverrides, }: {
30
39
  chat: ReturnType<typeof import('../useChat.js').useChat>;
31
40
  open: boolean;
32
41
  onClose: () => void;
@@ -52,5 +61,14 @@ export default function ChatPanel({ chat, open, onClose, title, titleIcon, heade
52
61
  renderReply?: (turn: import('../useChat.js').ChatTurn, state: {
53
62
  streaming: boolean;
54
63
  }) => import('react').ReactNode;
55
- labels?: Partial<typeof import('@webority/ui-elements/chat-core').DEFAULT_CHAT_LABELS>;
64
+ openAttachment?: (attachment: {
65
+ publicId: string;
66
+ fileName: string;
67
+ contentType: string;
68
+ length: number;
69
+ }) => void;
70
+ conversations?: boolean;
71
+ isCitation?: (inner: string) => boolean;
72
+ onOpenCitation?: (citation: string) => void;
73
+ labels?: Partial<typeof import('@webority/chat-core').DEFAULT_CHAT_LABELS>;
56
74
  }): import("react").JSX.Element;
@@ -71,6 +71,21 @@ export declare const meta: {
71
71
  readonly required: false;
72
72
  readonly description: "The stored reply's id.";
73
73
  };
74
+ readonly questionId: {
75
+ readonly type: "string";
76
+ readonly required: false;
77
+ readonly description: "The stored question's id.";
78
+ };
79
+ readonly stopped: {
80
+ readonly type: "boolean";
81
+ readonly required: false;
82
+ readonly description: "True when the person stopped the answer.";
83
+ };
84
+ readonly attachments: {
85
+ readonly type: "array";
86
+ readonly required: false;
87
+ readonly description: "The files sent with the question.";
88
+ };
74
89
  readonly rating: {
75
90
  readonly type: "enum";
76
91
  readonly values: readonly ["Up", "Down"];
@@ -159,6 +174,11 @@ export declare const meta: {
159
174
  readonly default: true;
160
175
  readonly description: "Offer thumbs under stored replies.";
161
176
  };
177
+ readonly conversations: {
178
+ readonly type: "boolean";
179
+ readonly default: false;
180
+ readonly description: "Offers the person's past chats from a header icon; the list replaces the conversation until a chat is opened.";
181
+ };
162
182
  readonly labels: {
163
183
  readonly type: "object";
164
184
  readonly description: "Replacements for the built-in wording.";
@@ -12,9 +12,16 @@
12
12
  * @param {(ticket: { id: string, number: string }) => void} [props.onViewTicket]
13
13
  * @param {(turn: import('../useChat.js').ChatTurn, state: { streaming: boolean }) => import('react').ReactNode} [props.renderReply]
14
14
  * Draws each assistant answer instead of `ChatMarkdown`; see `ChatMessage`.
15
- * @param {Partial<typeof import('@webority/ui-elements/chat-core').DEFAULT_CHAT_LABELS>} [props.labels]
15
+ * @param {(turnId: string) => void} [props.onRetry]
16
+ * @param {(turnId: string) => void} [props.onRegenerate] Offered on the last turn only.
17
+ * @param {(text: string) => void} [props.onAskSuggestion] Sends a suggested follow-up; offered on the last turn only.
18
+ * @param {(inner: string) => boolean} [props.isCitation] Passed to `ChatMessage`; see `ChatMarkdown`.
19
+ * @param {(citation: string) => void} [props.onOpenCitation] Passed to `ChatMessage`; see `ChatMarkdown`.
20
+ * @param {(turnId: string) => void} [props.onEdit]
21
+ * @param {(attachment: { publicId: string, fileName: string, contentType: string, length: number }) => void} [props.onOpenAttachment]
22
+ * @param {Partial<typeof import('@webority/chat-core').DEFAULT_CHAT_LABELS>} [props.labels]
16
23
  */
17
- export default function ChatThread({ turns, empty, onRate, resolveLink, linkComponent, confirmAction, onViewTicket, renderReply, labels: labelOverrides, }: {
24
+ export default function ChatThread({ turns, empty, onRate, resolveLink, linkComponent, confirmAction, onViewTicket, renderReply, onRetry, onRegenerate, onAskSuggestion, isCitation, onOpenCitation, onEdit, onOpenAttachment, labels: labelOverrides, }: {
18
25
  turns: import('../useChat.js').ChatTurn[];
19
26
  empty?: import('react').ReactNode;
20
27
  onRate?: (turnId: string, rating: "Up" | "Down", note?: string) => Promise<unknown>;
@@ -31,5 +38,17 @@ export default function ChatThread({ turns, empty, onRate, resolveLink, linkComp
31
38
  renderReply?: (turn: import('../useChat.js').ChatTurn, state: {
32
39
  streaming: boolean;
33
40
  }) => import('react').ReactNode;
34
- labels?: Partial<typeof import('@webority/ui-elements/chat-core').DEFAULT_CHAT_LABELS>;
41
+ onRetry?: (turnId: string) => void;
42
+ onRegenerate?: (turnId: string) => void;
43
+ onAskSuggestion?: (text: string) => void;
44
+ isCitation?: (inner: string) => boolean;
45
+ onOpenCitation?: (citation: string) => void;
46
+ onEdit?: (turnId: string) => void;
47
+ onOpenAttachment?: (attachment: {
48
+ publicId: string;
49
+ fileName: string;
50
+ contentType: string;
51
+ length: number;
52
+ }) => void;
53
+ labels?: Partial<typeof import('@webority/chat-core').DEFAULT_CHAT_LABELS>;
35
54
  }): string | number | bigint | boolean | import("react").JSX.Element | Iterable<import("react").ReactNode> | Promise<string | number | bigint | boolean | Iterable<import("react").ReactNode> | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | import("react").ReactPortal | null | undefined>;
@@ -66,6 +66,21 @@ export declare const meta: {
66
66
  readonly required: false;
67
67
  readonly description: "The stored reply's id. The rating needs it.";
68
68
  };
69
+ readonly questionId: {
70
+ readonly type: "string";
71
+ readonly required: false;
72
+ readonly description: "The stored question's id. Editing the question needs it.";
73
+ };
74
+ readonly stopped: {
75
+ readonly type: "boolean";
76
+ readonly required: false;
77
+ readonly description: "True when the person stopped the answer before it finished.";
78
+ };
79
+ readonly attachments: {
80
+ readonly type: "array";
81
+ readonly required: false;
82
+ readonly description: "The files sent with the question.";
83
+ };
69
84
  readonly rating: {
70
85
  readonly type: "enum";
71
86
  readonly values: readonly ["Up", "Down"];
@@ -84,6 +99,11 @@ export declare const meta: {
84
99
  readonly required: false;
85
100
  readonly description: "Shown when there are no turns; defaults to a short How can I help state.";
86
101
  };
102
+ readonly linkComponent: {
103
+ readonly type: "node";
104
+ readonly required: false;
105
+ readonly description: "A router link component for in-app links in answers; it receives to.";
106
+ };
87
107
  readonly labels: {
88
108
  readonly type: "object";
89
109
  readonly required: false;
@@ -1,17 +1,3 @@
1
- /**
2
- * Splits reply text at its `[inner]` runs. A run whose inner text `isCitation` accepts becomes
3
- * `{ citation }`; everything else stays text: a markdown link `[text](url)`, an empty `[]`, and a
4
- * run the check rejects.
5
- *
6
- * @param {string} text
7
- * @param {(inner: string) => boolean} isCitation
8
- * @returns {Array<{ text: string } | { citation: string }>}
9
- */
10
- export declare function splitCitations(text: string, isCitation: (inner: string) => boolean): Array<{
11
- text: string;
12
- } | {
13
- citation: string;
14
- }>;
15
1
  /**
16
2
  * A citation the assistant wrote as `[inner]`: a chip that opens the source it names.
17
3
  *
@@ -36,7 +36,7 @@ export declare const meta: {
36
36
  };
37
37
  }];
38
38
  readonly usage: {
39
- readonly when: readonly ["Show a source the assistant named in a reply as a small chip the person can select to open it.", "Pair it with splitCitations to turn [source] runs in reply text into chips."];
39
+ readonly when: readonly ["Show a source the assistant named in a reply as a small chip the person can select to open it.", "Pair it with splitCitations from @webority/markdown-core (re-exported by @webority/chat-react) to turn [source] runs in reply text into chips."];
40
40
  readonly whenNot: readonly [{
41
41
  readonly text: "Showing a general label or removable token that is not a source.";
42
42
  readonly instead: "AppChip";
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The files attached to the question being written. A failed upload stays listed with its
3
+ * error, so the person can remove it.
4
+ *
5
+ * @param {object} props
6
+ * @param {import('@webority/chat-core').ComposerAttachment[]} props.attachments
7
+ * @param {(key: string) => unknown} props.onRemove Called with the attachment key.
8
+ * @param {import('@webority/chat-core').ChatLabels} props.labels The merged labels.
9
+ */
10
+ export default function ComposerAttachments({ attachments, onRemove, labels }: {
11
+ attachments: import('@webority/chat-core').ComposerAttachment[];
12
+ onRemove: (key: string) => unknown;
13
+ labels: import('@webority/chat-core').ChatLabels;
14
+ }): import("react").JSX.Element | null;
@@ -10,7 +10,7 @@
10
10
  * @param {string} [props.note]
11
11
  * @param {() => Promise<{ message?: string } | void>} props.onConfirm Sends the person's yes; resolves to
12
12
  * an optional message for the done state. A rejection's `message` is shown when present.
13
- * @param {Partial<typeof import('@webority/ui-elements/chat-core').DEFAULT_CHAT_LABELS>} [props.labels]
13
+ * @param {Partial<typeof import('@webority/chat-core').DEFAULT_CHAT_LABELS>} [props.labels]
14
14
  */
15
15
  export default function ConfirmCard({ title, subtitle, lines, note, onConfirm, labels: labelsProp }: {
16
16
  title: string;
@@ -20,5 +20,5 @@ export default function ConfirmCard({ title, subtitle, lines, note, onConfirm, l
20
20
  onConfirm: () => Promise<{
21
21
  message?: string;
22
22
  } | void>;
23
- labels?: Partial<typeof import('@webority/ui-elements/chat-core').DEFAULT_CHAT_LABELS>;
23
+ labels?: Partial<typeof import('@webority/chat-core').DEFAULT_CHAT_LABELS>;
24
24
  }): import("react").JSX.Element;
@@ -6,11 +6,11 @@
6
6
  * @param {"Up"|"Down"|null} [props.rating]
7
7
  * @param {(rating: "Up"|"Down", note?: string) => Promise<unknown>} props.onRate Rejects on failure.
8
8
  * @param {number} [props.noteMaxLength]
9
- * @param {Partial<typeof import('@webority/ui-elements/chat-core').DEFAULT_CHAT_LABELS>} [props.labels]
9
+ * @param {Partial<typeof import('@webority/chat-core').DEFAULT_CHAT_LABELS>} [props.labels]
10
10
  */
11
11
  export default function ReplyRating({ rating, onRate, noteMaxLength, labels: labelOverrides }: {
12
12
  rating?: "Up" | "Down" | null;
13
13
  onRate: (rating: "Up" | "Down", note?: string) => Promise<unknown>;
14
14
  noteMaxLength?: number;
15
- labels?: Partial<typeof import('@webority/ui-elements/chat-core').DEFAULT_CHAT_LABELS>;
15
+ labels?: Partial<typeof import('@webority/chat-core').DEFAULT_CHAT_LABELS>;
16
16
  }): import("react").JSX.Element;
@@ -1,4 +1,5 @@
1
- export { ChatApiError, createChatClient, createSseParser, DEFAULT_CHAT_LABELS } from "@webority/ui-elements/chat-core";
1
+ export { CHAT_CONTRACT_VERSION, ChatApiError, createChatClient, createChatSession, createConversationList, createSseParser, DEFAULT_CHAT_LABELS, mergeLabels, } from "@webority/chat-core";
2
+ export { splitCitations } from "@webority/markdown-core";
2
3
  export { default as ActionCard } from "./components/ActionCard.jsx";
3
4
  export { default as ChatComposer } from "./components/ChatComposer.jsx";
4
5
  export { default as ChatConversationList } from "./components/ChatConversationList.jsx";
@@ -6,7 +7,7 @@ export { default as ChatLauncher } from "./components/ChatLauncher.jsx";
6
7
  export { default as ChatMessage } from "./components/ChatMessage.jsx";
7
8
  export { default as ChatPanel } from "./components/ChatPanel.jsx";
8
9
  export { default as ChatThread } from "./components/ChatThread.jsx";
9
- export { default as CitationChip, splitCitations } from "./components/CitationChip.jsx";
10
+ export { default as CitationChip } from "./components/CitationChip.jsx";
10
11
  export { default as ConfirmCard } from "./components/ConfirmCard.jsx";
11
12
  export { default as ReplyRating } from "./components/ReplyRating.jsx";
12
13
  export { ChatMarkdown } from "./markdown.jsx";
@@ -8,11 +8,15 @@
8
8
  * @param {(href: string) => string|null|undefined} [props.resolveLink] Maps `scheme:kind/id` to a
9
9
  * route such as "/support?ticket=3f2a", or null to leave it as text.
10
10
  * @param {import('react').ElementType} [props.linkComponent] A router link (it receives `to`).
11
+ * @param {(inner: string) => boolean} [props.isCitation] Which `[inner]` runs draw as citation chips.
12
+ * @param {(citation: string) => void} [props.onOpenCitation] Called with the citation when its chip is selected.
11
13
  * @param {string} [props.className]
12
14
  */
13
- export declare function ChatMarkdown({ text, resolveLink, linkComponent, className }: {
15
+ export declare function ChatMarkdown({ text, resolveLink, linkComponent, isCitation, onOpenCitation, className }: {
14
16
  text: string;
15
17
  resolveLink?: (href: string) => string | null | undefined;
16
18
  linkComponent?: import('react').ElementType;
19
+ isCitation?: (inner: string) => boolean;
20
+ onOpenCitation?: (citation: string) => void;
17
21
  className?: string;
18
22
  }): import("react").JSX.Element;
@@ -6,48 +6,42 @@ export type ChatTurnError = {
6
6
  message: string;
7
7
  resetsAtUtc: string | null;
8
8
  };
9
- export type ChatTurn = {
10
- /**
11
- * Local key; for a reopened conversation, the stored message's id.
12
- */
13
- id: string;
14
- question: string;
15
- /**
16
- * What is shown: the streamed text, then the reply of record.
17
- */
18
- answer: string;
19
- streaming: boolean;
20
- /**
21
- * The name of the tool the assistant is running, or null. Set when a tool starts;
22
- * cleared when answer text arrives, on a reset and when the turn ends.
23
- */
24
- step: string | null;
25
- error: ChatTurnError | null;
26
- actions: import('@webority/ui-elements/chat-core').SupportAction[];
27
- /**
28
- * The stored reply's id; rating needs it.
29
- */
30
- messageId: string | null;
31
- rating: "Up" | "Down" | null;
32
- ratingNote: string | null;
33
- };
9
+ export type ChatTurn = import('@webority/chat-core').ChatTurn;
10
+ /**
11
+ * @typedef {object} ChatTurnError
12
+ * @property {string} code
13
+ * @property {string} message Written for the person.
14
+ * @property {string|null} resetsAtUtc
15
+ */
16
+ /** @typedef {import('@webority/chat-core').ChatTurn} ChatTurn One question and its answer. */
34
17
  /**
35
- * The chat's state and actions, with no store of its own: it lives in the component that calls
36
- * it. Call `reset()` when the signed-in person or account changes so nothing of one person's chat
37
- * shows to the next. An answer still streaming is cancelled on `reset`, `newConversation`,
38
- * `openConversation` and unmount.
18
+ * The chat's state and actions. The session lives in the component that calls it: one per client,
19
+ * disposed when the client changes or the component unmounts. Call `reset()` when the signed-in
20
+ * person or account changes so nothing of one person's chat shows to the next.
39
21
  *
40
22
  * @param {object} options
41
- * @param {import('@webority/ui-elements/chat-core').ChatClient} options.client From `createChatClient`.
23
+ * @param {import('@webority/chat-core').ChatClient} options.client From `createChatClient`.
42
24
  * @param {any} [options.pageContext] Sent with each question; read at the moment of sending.
43
25
  * @returns {{
26
+ * client: import('@webority/chat-core').ChatClient,
44
27
  * turns: ChatTurn[],
45
28
  * conversationId: string|null,
46
29
  * messagesLeftToday: number|null,
47
30
  * streaming: boolean,
48
31
  * loading: boolean,
49
32
  * loadError: ChatTurnError|null,
33
+ * settings: import('@webority/chat-core').ChatSettings|null,
34
+ * settingsError: ChatTurnError|null,
35
+ * editing: import('@webority/chat-core').ChatEditing|null,
36
+ * attachments: import('@webority/chat-core').ComposerAttachment[],
50
37
  * submit: (message: string) => Promise<void>,
38
+ * stop: () => void,
39
+ * retry: (turnId: string) => Promise<void>,
40
+ * regenerate: (turnId: string) => Promise<void>,
41
+ * startEdit: (turnId: string) => void,
42
+ * cancelEdit: () => void,
43
+ * attach: (files: import('@webority/chat-core').ChatUploadFile[]) => Promise<void>,
44
+ * removeAttachment: (key: string) => Promise<void>,
51
45
  * openConversation: (id: string) => Promise<void>,
52
46
  * newConversation: () => void,
53
47
  * rate: (turnId: string, rating: "Up"|"Down", note?: string) => Promise<void>,
@@ -56,16 +50,28 @@ export type ChatTurn = {
56
50
  * }}
57
51
  */
58
52
  export declare function useChat({ client, pageContext }: {
59
- client: import('@webority/ui-elements/chat-core').ChatClient;
53
+ client: import('@webority/chat-core').ChatClient;
60
54
  pageContext?: any;
61
55
  }): {
56
+ client: import('@webority/chat-core').ChatClient;
62
57
  turns: ChatTurn[];
63
58
  conversationId: string | null;
64
59
  messagesLeftToday: number | null;
65
60
  streaming: boolean;
66
61
  loading: boolean;
67
62
  loadError: ChatTurnError | null;
63
+ settings: import('@webority/chat-core').ChatSettings | null;
64
+ settingsError: ChatTurnError | null;
65
+ editing: import('@webority/chat-core').ChatEditing | null;
66
+ attachments: import('@webority/chat-core').ComposerAttachment[];
68
67
  submit: (message: string) => Promise<void>;
68
+ stop: () => void;
69
+ retry: (turnId: string) => Promise<void>;
70
+ regenerate: (turnId: string) => Promise<void>;
71
+ startEdit: (turnId: string) => void;
72
+ cancelEdit: () => void;
73
+ attach: (files: import('@webority/chat-core').ChatUploadFile[]) => Promise<void>;
74
+ removeAttachment: (key: string) => Promise<void>;
69
75
  openConversation: (id: string) => Promise<void>;
70
76
  newConversation: () => void;
71
77
  rate: (turnId: string, rating: "Up" | "Down", note?: string) => Promise<void>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webority/chat-react",
3
- "version": "0.121.0",
3
+ "version": "0.124.0",
4
4
  "description": "Webority AI assistant for React portals: a streaming chat client, a store-agnostic chat hook, and the launcher, panel, thread, rating and support action card, built on @webority/ui-react.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "module",
@@ -26,9 +26,13 @@
26
26
  "./guidance.json": "./dist/guidance.json"
27
27
  },
28
28
  "sideEffects": false,
29
+ "dependencies": {
30
+ "@webority/chat-core": "0.124.0",
31
+ "@webority/markdown-core": "0.124.0"
32
+ },
29
33
  "peerDependencies": {
30
- "@webority/ui-elements": "0.121.0",
31
- "@webority/ui-react": "0.121.0",
34
+ "@webority/ui-elements": "0.124.0",
35
+ "@webority/ui-react": "0.124.0",
32
36
  "bootstrap": "5.3.3",
33
37
  "react": "^19.0.0",
34
38
  "react-bootstrap": "^2.10.0",
@@ -42,9 +46,9 @@
42
46
  "@types/react": "^19.2.17",
43
47
  "@vitejs/plugin-react": "^6.0.1",
44
48
  "@vitest/coverage-v8": "5.0.1",
45
- "@webority/canvas-kit": "0.121.0",
46
- "@webority/ui-elements": "0.121.0",
47
- "@webority/ui-react": "0.121.0",
49
+ "@webority/canvas-kit": "0.124.0",
50
+ "@webority/ui-elements": "0.124.0",
51
+ "@webority/ui-react": "0.124.0",
48
52
  "bootstrap": "5.3.3",
49
53
  "jsdom": "30.1.1",
50
54
  "react": "^19.2.6",