@duskmoon-dev/components 0.5.7 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +111 -4
  2. package/dist/chunk-kg46s2vk.js +238 -0
  3. package/dist/chunk-rd10x4gc.js +733 -0
  4. package/dist/components/chat/Chat.types.d.ts +15 -0
  5. package/dist/components/chat/ChatAuthoritativeQueue.d.ts +4 -0
  6. package/dist/components/chat/ChatSessionComposer.d.ts +4 -0
  7. package/dist/components/chat/ChatSessionComposer.types.d.ts +46 -0
  8. package/dist/components/chat/ComposerAttachment.types.d.ts +80 -0
  9. package/dist/components/chat/ComposerDraft.types.d.ts +89 -0
  10. package/dist/components/chat/ComposerProvider.types.d.ts +70 -0
  11. package/dist/components/chat/ComposerQueue.types.d.ts +64 -0
  12. package/dist/components/chat/ComposerSession.types.d.ts +78 -0
  13. package/dist/components/chat/ComposerSettings.d.ts +4 -0
  14. package/dist/components/chat/composer/CompletionList.d.ts +15 -0
  15. package/dist/components/chat/composer/ComposerShell.d.ts +23 -4
  16. package/dist/components/chat/composer/DraftLifecycle.d.ts +19 -0
  17. package/dist/components/chat/composer/EditorAdapter.types.d.ts +36 -0
  18. package/dist/components/chat/composer/PlainEditor.d.ts +2 -0
  19. package/dist/components/chat/composer/PlainSemanticEditor.d.ts +6 -0
  20. package/dist/components/chat/composer/PreservedDraft.d.ts +7 -0
  21. package/dist/components/chat/composer/SemanticComposer.d.ts +10 -0
  22. package/dist/components/chat/composer/attachments.d.ts +4 -0
  23. package/dist/components/chat/composer/document.d.ts +3 -1
  24. package/dist/components/chat/composer/drafts.d.ts +2 -0
  25. package/dist/components/chat/composer/providers.d.ts +40 -0
  26. package/dist/components/chat/composer/session.d.ts +30 -0
  27. package/dist/components/chat/composer/useComposerAttachments.d.ts +3 -0
  28. package/dist/components/chat/composer/useComposerDraft.d.ts +3 -0
  29. package/dist/components/chat/composer/useComposerProviders.d.ts +7 -0
  30. package/dist/components/chat/composer/useComposerSession.d.ts +16 -0
  31. package/dist/components/chat/index.d.ts +17 -0
  32. package/dist/components/chat/index.js +4765 -1286
  33. package/dist/components/chat/rich/LexicalEditor.d.ts +10 -0
  34. package/dist/components/chat/rich/RichChatComposer.d.ts +4 -0
  35. package/dist/components/chat/rich/index.d.ts +2 -0
  36. package/dist/components/chat/rich/index.js +3478 -0
  37. package/dist/components/chat/rich/nodes.d.ts +49 -0
  38. package/dist/generated/version.d.ts +1 -1
  39. package/dist/index.js +11994 -8740
  40. package/dist/infrastructure.js +1 -1
  41. package/dist/styles.css +180 -2
  42. package/package.json +27 -6
@@ -0,0 +1,3478 @@
1
+ "use client";
2
+ import {
3
+ snapshotComposerJson,
4
+ migrateLegacyComposerDocument,
5
+ readComposerDocument,
6
+ snapshotComposerDocument,
7
+ readComposerDraft,
8
+ snapshotComposerSubmission,
9
+ exportComposerText
10
+ } from "../../../chunk-kg46s2vk.js";
11
+ var __chunkGraphs;
12
+ var __chunkSeen;
13
+ var __chunkNonce;
14
+ var __preload = (id, seenOnly) => {
15
+ for (var [base, graph, ids] of __chunkGraphs || [])
16
+ for (var stack = [id], g = globalThis, d = g.document, head, j, node, k, link;j = stack.pop(); )
17
+ if (!__chunkSeen[j] && (node = graph[j])) {
18
+ __chunkSeen[j] = 1;
19
+ for (k = 1;k < node.length; k++)
20
+ stack.push(ids[node[k]]);
21
+ if (!seenOnly && j !== id && (head = d && d.head)) {
22
+ if (__chunkNonce === undefined)
23
+ __chunkNonce = (k = d.querySelector("meta[property=csp-nonce]")) && (k.nonce || k.getAttribute("nonce")) || "";
24
+ link = d.createElement("link");
25
+ link.rel = "modulepreload";
26
+ link.crossOrigin = "";
27
+ if (__chunkNonce)
28
+ link.nonce = __chunkNonce;
29
+ link.href = new g.URL(node[0], base);
30
+ head.appendChild(link);
31
+ }
32
+ }
33
+ };
34
+ var __chunks = (base, ids, nodes, entry) => {
35
+ for (var graph = {}, i = 0;i < ids.length; i++)
36
+ graph[ids[i]] = nodes[i];
37
+ (__chunkGraphs ||= []).push([base, graph, ids]);
38
+ __chunkSeen ||= {};
39
+ __preload(ids[entry], 1);
40
+ };
41
+ __chunks(import.meta.url,["75afjaj1","rd10x4gc","kg46s2vk"],[["./index.js",2],["../../../chunk-rd10x4gc.js",2],["../../../chunk-kg46s2vk.js"]],0);
42
+
43
+ // src/components/chat/rich/RichChatComposer.tsx
44
+ import { Component, Suspense, forwardRef as forwardRef5, lazy } from "react";
45
+
46
+ // src/components/chat/composer/SemanticComposer.tsx
47
+ import {
48
+ forwardRef as forwardRef4,
49
+ useId as useId4,
50
+ useCallback as useCallback2,
51
+ useImperativeHandle as useImperativeHandle3,
52
+ useLayoutEffect as useLayoutEffect8,
53
+ useRef as useRef5,
54
+ useState as useState6,
55
+ useSyncExternalStore as useSyncExternalStore5
56
+ } from "react";
57
+
58
+ // src/components/chat/composer/ComposerShell.tsx
59
+ import { forwardRef, useEffect, useRef as useRef2, useState } from "react";
60
+
61
+ // src/components/button/Button.tsx
62
+ import React from "react";
63
+ import { createPortal } from "react-dom";
64
+
65
+ // ../../node_modules/.bun/clsx@2.1.1/node_modules/clsx/dist/clsx.mjs
66
+ function r(e) {
67
+ var t, f, n = "";
68
+ if (typeof e == "string" || typeof e == "number")
69
+ n += e;
70
+ else if (typeof e == "object")
71
+ if (Array.isArray(e)) {
72
+ var o = e.length;
73
+ for (t = 0;t < o; t++)
74
+ e[t] && (f = r(e[t])) && (n && (n += " "), n += f);
75
+ } else
76
+ for (f in e)
77
+ e[f] && (n && (n += " "), n += f);
78
+ return n;
79
+ }
80
+ function clsx() {
81
+ for (var e, t, f = 0, n = "", o = arguments.length;f < o; f++)
82
+ (e = arguments[f]) && (t = r(e)) && (n && (n += " "), n += t);
83
+ return n;
84
+ }
85
+
86
+ // src/utils/cn.ts
87
+ function cn(...inputs) {
88
+ return clsx(inputs);
89
+ }
90
+ // src/classes/button.ts
91
+ var buttonBaseClass = "btn";
92
+ var buttonColorClasses = {
93
+ primary: "btn-primary",
94
+ secondary: "btn-secondary",
95
+ tertiary: "btn-tertiary",
96
+ accent: "btn-accent",
97
+ neutral: "btn-neutral",
98
+ base: "btn-base",
99
+ info: "btn-info",
100
+ success: "btn-success",
101
+ warning: "btn-warning",
102
+ error: "btn-error"
103
+ };
104
+ var buttonAppearanceClasses = {
105
+ filled: "",
106
+ outline: "btn-outline",
107
+ tonal: "btn-tonal",
108
+ ghost: "btn-ghost",
109
+ text: "btn-text"
110
+ };
111
+ var buttonShapeClasses = {
112
+ rect: "",
113
+ circle: "btn-circle btn-icon",
114
+ square: "btn-square"
115
+ };
116
+ var buttonSizeClasses = {
117
+ xs: "btn-xs",
118
+ sm: "btn-sm",
119
+ md: "btn-md",
120
+ lg: "btn-lg"
121
+ };
122
+ var buttonBlockClass = "btn-block";
123
+ var buttonIsLoadingClass = "btn-loading";
124
+ function getButtonClasses({
125
+ color = "primary",
126
+ appearance = "filled",
127
+ shape = "rect",
128
+ size = "md",
129
+ block,
130
+ isLoading,
131
+ className
132
+ }) {
133
+ return cn(buttonBaseClass, buttonColorClasses[color], buttonAppearanceClasses[appearance], buttonShapeClasses[shape], buttonSizeClasses[size], shape === "circle" && size === "xs" && "btn-icon-sm", shape === "circle" && size === "sm" && "btn-icon-sm", shape === "circle" && size === "lg" && "btn-icon-lg", block && buttonBlockClass, isLoading && buttonIsLoadingClass, className);
134
+ }
135
+
136
+ // src/components/button/Button.tsx
137
+ import { jsx, jsxs, Fragment } from "react/jsx-runtime";
138
+ function isPromiseLike(value) {
139
+ return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
140
+ }
141
+ function Button({
142
+ color = "primary",
143
+ appearance = "filled",
144
+ shape = "rect",
145
+ size = "md",
146
+ block,
147
+ isLoading,
148
+ leftIcon,
149
+ rightIcon,
150
+ className,
151
+ children,
152
+ disabled,
153
+ ref,
154
+ confirm,
155
+ onClick,
156
+ ...props
157
+ }) {
158
+ const buttonRef = React.useRef(null);
159
+ const popoverRef = React.useRef(null);
160
+ const cancelRef = React.useRef(null);
161
+ const approvalRef = React.useRef("idle");
162
+ const pendingRef = React.useRef(false);
163
+ const actionRef = React.useRef(0);
164
+ const operationRef = React.useRef(0);
165
+ const mountedRef = React.useRef(false);
166
+ const [portalTarget, setPortalTarget] = React.useState(null);
167
+ const [confirmLoading, setConfirmLoading] = React.useState(false);
168
+ const [confirmError, setConfirmError] = React.useState(false);
169
+ const generatedId = React.useId().replace(/:/g, "");
170
+ const popoverId = `button-confirm-${generatedId}`;
171
+ const titleId = `${popoverId}-title`;
172
+ const descriptionId = `${popoverId}-description`;
173
+ const anchor = `--${popoverId}-anchor`;
174
+ const hasConfirm = Boolean(confirm);
175
+ const confirmation = confirm && typeof confirm === "object" ? confirm : undefined;
176
+ const title = confirmation ? confirmation.title : "Confirm action";
177
+ const hasTitle = title !== undefined && title !== null && title !== false && title !== "";
178
+ const content = confirmation?.component ?? confirmation?.message ?? confirmation?.description;
179
+ const hasContent = content !== undefined && content !== null && content !== false && content !== "";
180
+ const mergedRef = React.useCallback((node) => {
181
+ buttonRef.current = node;
182
+ if (!node) {
183
+ if (typeof ref === "function")
184
+ ref(null);
185
+ else if (ref)
186
+ ref.current = null;
187
+ return;
188
+ }
189
+ const cleanup = typeof ref === "function" ? ref(node) : undefined;
190
+ if (ref && typeof ref !== "function")
191
+ ref.current = node;
192
+ return () => {
193
+ buttonRef.current = null;
194
+ if (typeof cleanup === "function")
195
+ cleanup();
196
+ else if (typeof ref === "function")
197
+ ref(null);
198
+ else if (ref)
199
+ ref.current = null;
200
+ };
201
+ }, [ref]);
202
+ React.useEffect(() => {
203
+ mountedRef.current = true;
204
+ return () => {
205
+ mountedRef.current = false;
206
+ operationRef.current += 1;
207
+ };
208
+ }, []);
209
+ React.useEffect(() => {
210
+ operationRef.current += 1;
211
+ approvalRef.current = "idle";
212
+ setConfirmError(false);
213
+ setPortalTarget(hasConfirm ? document.body : null);
214
+ }, [hasConfirm]);
215
+ function closePopover() {
216
+ if (popoverRef.current?.matches(":popover-open")) {
217
+ popoverRef.current.hidePopover();
218
+ }
219
+ buttonRef.current?.focus();
220
+ }
221
+ function handleClick(event) {
222
+ if (!confirm) {
223
+ onClick?.(event);
224
+ return;
225
+ }
226
+ if (approvalRef.current === "native") {
227
+ approvalRef.current = "idle";
228
+ return;
229
+ }
230
+ if (approvalRef.current === "action") {
231
+ approvalRef.current = "idle";
232
+ let result;
233
+ try {
234
+ result = onClick?.(event);
235
+ } catch {
236
+ event.preventDefault();
237
+ pendingRef.current = false;
238
+ setConfirmError(true);
239
+ return;
240
+ }
241
+ if (!isPromiseLike(result)) {
242
+ pendingRef.current = false;
243
+ closePopover();
244
+ return;
245
+ }
246
+ const userPreventedDefault = event.defaultPrevented;
247
+ event.preventDefault();
248
+ setConfirmLoading(true);
249
+ const action = actionRef.current;
250
+ const operation = operationRef.current;
251
+ Promise.resolve(result).then(() => {
252
+ if (!mountedRef.current || action !== actionRef.current)
253
+ return;
254
+ pendingRef.current = false;
255
+ setConfirmLoading(false);
256
+ if (operation !== operationRef.current)
257
+ return;
258
+ closePopover();
259
+ if (!userPreventedDefault && !buttonRef.current?.disabled) {
260
+ approvalRef.current = "native";
261
+ buttonRef.current?.click();
262
+ approvalRef.current = "idle";
263
+ }
264
+ }, () => {
265
+ if (!mountedRef.current || action !== actionRef.current)
266
+ return;
267
+ pendingRef.current = false;
268
+ setConfirmLoading(false);
269
+ if (operation !== operationRef.current)
270
+ return;
271
+ setConfirmError(true);
272
+ cancelRef.current?.focus();
273
+ });
274
+ return;
275
+ }
276
+ event.preventDefault();
277
+ if (disabled || isLoading || pendingRef.current)
278
+ return;
279
+ if (popoverRef.current?.matches(":popover-open")) {
280
+ closePopover();
281
+ return;
282
+ }
283
+ setConfirmError(false);
284
+ popoverRef.current?.showPopover();
285
+ cancelRef.current?.focus();
286
+ }
287
+ function handleConfirm(event) {
288
+ event.preventDefault();
289
+ event.stopPropagation();
290
+ const trigger = buttonRef.current;
291
+ if (disabled || isLoading || pendingRef.current || !trigger || trigger.disabled || !event.currentTarget.matches(":popover-open"))
292
+ return;
293
+ setConfirmError(false);
294
+ pendingRef.current = true;
295
+ actionRef.current += 1;
296
+ approvalRef.current = "action";
297
+ trigger.click();
298
+ if (approvalRef.current === "action") {
299
+ approvalRef.current = "idle";
300
+ pendingRef.current = false;
301
+ }
302
+ }
303
+ const classes = getButtonClasses({
304
+ color,
305
+ appearance,
306
+ shape,
307
+ size,
308
+ block,
309
+ isLoading,
310
+ className
311
+ });
312
+ const confirmClasses = getButtonClasses({
313
+ color,
314
+ size: "sm",
315
+ isLoading: confirmLoading
316
+ });
317
+ return /* @__PURE__ */ jsxs(Fragment, {
318
+ children: [
319
+ /* @__PURE__ */ jsxs("button", {
320
+ ref: confirm ? mergedRef : ref,
321
+ className: classes,
322
+ disabled: disabled || isLoading,
323
+ "aria-busy": isLoading,
324
+ "aria-disabled": disabled || isLoading,
325
+ ...props,
326
+ style: confirm ? { ...props.style, anchorName: anchor } : props.style,
327
+ "aria-haspopup": confirm ? "dialog" : props["aria-haspopup"],
328
+ "aria-controls": confirm ? popoverId : props["aria-controls"],
329
+ onClick: confirm ? handleClick : onClick,
330
+ children: [
331
+ isLoading && /* @__PURE__ */ jsx("span", {
332
+ className: "btn-spinner"
333
+ }),
334
+ !isLoading && leftIcon && /* @__PURE__ */ jsx("span", {
335
+ className: "btn-icon-left",
336
+ children: leftIcon
337
+ }),
338
+ /* @__PURE__ */ jsx("span", {
339
+ className: "btn-content",
340
+ children
341
+ }),
342
+ !isLoading && rightIcon && /* @__PURE__ */ jsx("span", {
343
+ className: "btn-icon-right",
344
+ children: rightIcon
345
+ })
346
+ ]
347
+ }),
348
+ confirm && portalTarget && createPortal(/* @__PURE__ */ jsxs("form", {
349
+ id: popoverId,
350
+ ref: popoverRef,
351
+ popover: "auto",
352
+ role: "dialog",
353
+ "aria-labelledby": hasTitle ? titleId : undefined,
354
+ "aria-label": hasTitle ? undefined : "Confirm action",
355
+ "aria-describedby": hasContent ? descriptionId : undefined,
356
+ className: "popover popover-confirm popover-bottom",
357
+ style: { positionAnchor: anchor },
358
+ onSubmit: handleConfirm,
359
+ onClick: (event) => event.stopPropagation(),
360
+ onToggle: (event) => {
361
+ if (!event.currentTarget.matches(":popover-open")) {
362
+ operationRef.current += 1;
363
+ if (event.currentTarget.contains(document.activeElement) || document.activeElement === document.body) {
364
+ buttonRef.current?.focus();
365
+ }
366
+ }
367
+ },
368
+ children: [
369
+ hasTitle && /* @__PURE__ */ jsx("div", {
370
+ className: "popover-header",
371
+ children: /* @__PURE__ */ jsx("h3", {
372
+ id: titleId,
373
+ className: "popover-title",
374
+ children: title
375
+ })
376
+ }),
377
+ hasContent && /* @__PURE__ */ jsx("div", {
378
+ id: descriptionId,
379
+ className: "popover-body",
380
+ children: content
381
+ }),
382
+ confirmError && /* @__PURE__ */ jsx("div", {
383
+ role: "alert",
384
+ className: "popover-body",
385
+ children: "The action failed. Please try again."
386
+ }),
387
+ /* @__PURE__ */ jsxs("div", {
388
+ className: "popover-footer",
389
+ children: [
390
+ /* @__PURE__ */ jsx("button", {
391
+ ref: cancelRef,
392
+ type: "button",
393
+ className: "btn btn-text btn-sm",
394
+ popoverTarget: popoverId,
395
+ popoverTargetAction: "hide",
396
+ disabled: confirmLoading,
397
+ children: confirmation?.cancelText ?? "Cancel"
398
+ }),
399
+ /* @__PURE__ */ jsx("button", {
400
+ type: "submit",
401
+ className: confirmClasses,
402
+ disabled: disabled || isLoading || confirmLoading,
403
+ "aria-busy": confirmLoading,
404
+ children: confirmation?.confirmText ?? "Confirm"
405
+ })
406
+ ]
407
+ })
408
+ ]
409
+ }), portalTarget)
410
+ ]
411
+ });
412
+ }
413
+ // src/components/chat/composer/CompletionList.tsx
414
+ import React2, { useLayoutEffect, useRef } from "react";
415
+ import { jsx as jsx2, jsxs as jsxs2, Fragment as Fragment2 } from "react/jsx-runtime";
416
+ function completionOptionId(composerId, candidateId) {
417
+ return `${composerId}-option-${encodeURIComponent(candidateId)}`;
418
+ }
419
+ function CompletionList({
420
+ composerId,
421
+ label,
422
+ candidates,
423
+ activeId,
424
+ onSelect,
425
+ compact = false,
426
+ anchorName,
427
+ header,
428
+ status,
429
+ onDismiss
430
+ }) {
431
+ const surface = useRef(null);
432
+ useLayoutEffect(() => {
433
+ if (compact)
434
+ surface.current?.showPopover?.();
435
+ }, [compact]);
436
+ useLayoutEffect(() => {
437
+ const tray = surface.current;
438
+ const option = tray?.querySelector('[aria-selected="true"]');
439
+ if (!compact || !tray || !option)
440
+ return;
441
+ const bounds = tray.getBoundingClientRect();
442
+ const selected = option.getBoundingClientRect();
443
+ const top = bounds.top + tray.clientTop;
444
+ const bottom = top + tray.clientHeight;
445
+ if (selected.top < top)
446
+ tray.scrollTop += selected.top - top;
447
+ else if (selected.bottom > bottom)
448
+ tray.scrollTop += selected.bottom - bottom;
449
+ }, [compact, activeId, candidates]);
450
+ const list = candidates.length ? /* @__PURE__ */ jsx2("ul", {
451
+ id: `${composerId}-completions`,
452
+ role: "listbox",
453
+ "aria-label": label,
454
+ className: compact ? "chat-composer-completion-list" : "chat-composer-completions",
455
+ children: candidates.map((item, index) => /* @__PURE__ */ jsxs2(React2.Fragment, {
456
+ children: [
457
+ item.group && candidates[index - 1]?.group !== item.group ? /* @__PURE__ */ jsx2("li", {
458
+ role: "presentation",
459
+ className: "chat-composer-group",
460
+ "aria-hidden": "true",
461
+ children: item.group
462
+ }) : null,
463
+ /* @__PURE__ */ jsxs2("li", {
464
+ id: completionOptionId(composerId, item.id),
465
+ className: compact ? "chat-composer-option chat-composer-option-compact" : "chat-composer-option",
466
+ role: "option",
467
+ "aria-label": item.group ? `${item.group}: ${item.label}` : undefined,
468
+ "aria-selected": item.id === activeId,
469
+ "aria-disabled": item.disabled || undefined,
470
+ onMouseDown: (event) => event.preventDefault(),
471
+ onClick: () => {
472
+ if (!item.disabled)
473
+ onSelect(item);
474
+ },
475
+ onKeyDown: (event) => {
476
+ if (!item.disabled && (event.key === "Enter" || event.key === " ")) {
477
+ event.preventDefault();
478
+ onSelect(item);
479
+ }
480
+ },
481
+ children: [
482
+ compact && item.icon ? /* @__PURE__ */ jsx2("span", {
483
+ className: "chat-composer-option-icon",
484
+ "aria-hidden": "true",
485
+ children: item.icon
486
+ }) : null,
487
+ /* @__PURE__ */ jsx2("span", {
488
+ className: compact ? "chat-composer-label" : undefined,
489
+ title: item.label,
490
+ children: item.label
491
+ }),
492
+ item.description ? /* @__PURE__ */ jsx2("span", {
493
+ className: compact ? "chat-composer-description chat-composer-option-description" : "chat-composer-description",
494
+ title: typeof item.description === "string" ? item.description : undefined,
495
+ children: item.description
496
+ }) : null,
497
+ compact && item.sourceLabel ? /* @__PURE__ */ jsx2("span", {
498
+ className: "chat-composer-description chat-composer-option-source",
499
+ children: item.sourceLabel
500
+ }) : null
501
+ ]
502
+ })
503
+ ]
504
+ }, item.id))
505
+ }) : null;
506
+ return compact ? /* @__PURE__ */ jsxs2("div", {
507
+ ref: surface,
508
+ popover: "auto",
509
+ className: "chat-composer-completions chat-composer-completions-compact",
510
+ style: { positionAnchor: anchorName },
511
+ onToggle: (event) => {
512
+ if (event.newState === "closed")
513
+ onDismiss?.();
514
+ },
515
+ children: [
516
+ header,
517
+ list,
518
+ status
519
+ ]
520
+ }) : /* @__PURE__ */ jsxs2(Fragment2, {
521
+ children: [
522
+ header,
523
+ status,
524
+ list
525
+ ]
526
+ });
527
+ }
528
+
529
+ // src/components/chat/composer/ComposerShell.tsx
530
+ import { jsx as jsx3, jsxs as jsxs3, Fragment as Fragment3 } from "react/jsx-runtime";
531
+ function AttachmentPreview({ file }) {
532
+ const imageRef = useRef2(null);
533
+ useEffect(() => {
534
+ const image = imageRef.current;
535
+ if (!image || !file.type.startsWith("image/") || !URL.createObjectURL)
536
+ return;
537
+ const objectUrl = URL.createObjectURL(file);
538
+ image.src = objectUrl;
539
+ image.hidden = false;
540
+ return () => {
541
+ image.hidden = true;
542
+ image.removeAttribute("src");
543
+ URL.revokeObjectURL(objectUrl);
544
+ };
545
+ }, [file]);
546
+ return file.type.startsWith("image/") ? /* @__PURE__ */ jsx3("img", {
547
+ ref: imageRef,
548
+ className: "chat-composer-preview",
549
+ alt: file.name,
550
+ hidden: true
551
+ }) : null;
552
+ }
553
+ function ComposerIcon({
554
+ action
555
+ }) {
556
+ return /* @__PURE__ */ jsx3("svg", {
557
+ width: "18",
558
+ height: "18",
559
+ viewBox: "0 0 24 24",
560
+ fill: "none",
561
+ stroke: "currentColor",
562
+ strokeWidth: "2",
563
+ strokeLinecap: "round",
564
+ strokeLinejoin: "round",
565
+ "aria-hidden": "true",
566
+ focusable: "false",
567
+ children: action === "attach" ? /* @__PURE__ */ jsx3("path", {
568
+ d: "M12 5v14M5 12h14"
569
+ }) : action === "send" ? /* @__PURE__ */ jsx3("path", {
570
+ d: "m5 12 7-7 7 7M12 5v14"
571
+ }) : action === "stop" ? /* @__PURE__ */ jsx3("rect", {
572
+ x: "6",
573
+ y: "6",
574
+ width: "12",
575
+ height: "12",
576
+ rx: "1",
577
+ fill: "currentColor",
578
+ stroke: "none"
579
+ }) : action === "retry" ? /* @__PURE__ */ jsx3("path", {
580
+ d: "M3 11a9 9 0 1 1 2.6 7.4M3 4v7h7"
581
+ }) : /* @__PURE__ */ jsx3("path", {
582
+ d: "m6 6 12 12M6 18 18 6"
583
+ })
584
+ });
585
+ }
586
+ function AttachmentContent({
587
+ file,
588
+ renderAttachment,
589
+ context
590
+ }) {
591
+ return renderAttachment(file, context);
592
+ }
593
+ function ExtraActions({
594
+ children,
595
+ context
596
+ }) {
597
+ return typeof children === "function" ? children(context) : children;
598
+ }
599
+ var ComposerShell = forwardRef(({
600
+ editor,
601
+ composerId,
602
+ compact = false,
603
+ addMenu,
604
+ entries,
605
+ renderAttachment,
606
+ removeAttachment,
607
+ addAttachments,
608
+ onAttachmentsChange,
609
+ pickerRef,
610
+ accept,
611
+ multiple,
612
+ disabled,
613
+ busy,
614
+ submitting,
615
+ generating,
616
+ eligible,
617
+ completion,
618
+ candidates,
619
+ active,
620
+ showCompletion,
621
+ selectCompletion,
622
+ dismissCompletion,
623
+ visibleError,
624
+ hasError,
625
+ intakeEvents = true,
626
+ completionHeader,
627
+ completionStatus,
628
+ statusContent,
629
+ renderFooter,
630
+ attachLabel,
631
+ sendLabel,
632
+ stopLabel,
633
+ openAttachments,
634
+ submit,
635
+ onStop,
636
+ children,
637
+ className,
638
+ ...props
639
+ }, ref) => {
640
+ const [addOpen, setAddOpen] = useState(false);
641
+ const addId = `${composerId}-add`;
642
+ const addAnchor = `--composer-add-${composerId.replace(/[^a-zA-Z0-9_-]/g, "")}`;
643
+ const completionAnchor = `--composer-completions-${composerId.replace(/[^a-zA-Z0-9_-]/g, "")}`;
644
+ const thumbnails = compact && entries.length > 0 && !renderAttachment && entries.every(({ file, previewUrl, state, status, progress, retry, cancel }) => (previewUrl || file?.type.startsWith("image/") && typeof URL.createObjectURL === "function") && (!state || state === "ready") && !status && progress === undefined && !retry && !cancel);
645
+ const attachmentAction = onAttachmentsChange ? /* @__PURE__ */ jsxs3(Fragment3, {
646
+ children: [
647
+ /* @__PURE__ */ jsx3("input", {
648
+ ref: pickerRef,
649
+ type: "file",
650
+ accept,
651
+ multiple,
652
+ disabled,
653
+ hidden: true,
654
+ "aria-label": attachLabel,
655
+ onChange: (event) => {
656
+ const files = Array.from(event.currentTarget.files ?? []);
657
+ event.currentTarget.value = "";
658
+ if (files.length > 0)
659
+ addAttachments(files, "picker");
660
+ }
661
+ }),
662
+ /* @__PURE__ */ jsx3(Button, {
663
+ type: "button",
664
+ color: "base",
665
+ appearance: "ghost",
666
+ size: "sm",
667
+ shape: "circle",
668
+ "aria-label": attachLabel,
669
+ title: attachLabel,
670
+ disabled,
671
+ onClick: openAttachments,
672
+ children: /* @__PURE__ */ jsx3(ComposerIcon, {
673
+ action: "attach"
674
+ })
675
+ })
676
+ ]
677
+ }) : null;
678
+ const actionContent = /* @__PURE__ */ jsxs3(Fragment3, {
679
+ children: [
680
+ /* @__PURE__ */ jsx3(ExtraActions, {
681
+ context: {
682
+ submit: () => {
683
+ submit();
684
+ },
685
+ submitting,
686
+ canSubmit: eligible,
687
+ disabled,
688
+ generating,
689
+ openAttachments
690
+ },
691
+ children
692
+ }),
693
+ generating && onStop && (!compact || !eligible) ? /* @__PURE__ */ jsx3(Button, {
694
+ type: "button",
695
+ color: compact ? "primary" : undefined,
696
+ size: "sm",
697
+ shape: "circle",
698
+ "aria-label": stopLabel,
699
+ title: stopLabel,
700
+ disabled,
701
+ onClick: onStop,
702
+ children: /* @__PURE__ */ jsx3(ComposerIcon, {
703
+ action: "stop"
704
+ })
705
+ }) : null,
706
+ !compact || !generating || !onStop || eligible ? /* @__PURE__ */ jsx3(Button, {
707
+ type: "button",
708
+ color: "primary",
709
+ size: "sm",
710
+ shape: "circle",
711
+ "aria-label": sendLabel,
712
+ title: sendLabel,
713
+ disabled: !eligible,
714
+ "aria-busy": busy || submitting || undefined,
715
+ onClick: () => {
716
+ submit();
717
+ },
718
+ children: /* @__PURE__ */ jsx3(ComposerIcon, {
719
+ action: "send"
720
+ })
721
+ }) : null
722
+ ]
723
+ });
724
+ function renderToolbar(menuContent) {
725
+ return compact ? /* @__PURE__ */ jsxs3("div", {
726
+ className: "chat-composer-toolbar chat-composer-toolbar-compact",
727
+ children: [
728
+ onAttachmentsChange || addMenu || menuContent ? /* @__PURE__ */ jsxs3(Fragment3, {
729
+ children: [
730
+ /* @__PURE__ */ jsx3(Button, {
731
+ type: "button",
732
+ color: "base",
733
+ appearance: "ghost",
734
+ size: "sm",
735
+ shape: "circle",
736
+ "aria-label": attachLabel,
737
+ title: attachLabel,
738
+ disabled,
739
+ popoverTarget: addId,
740
+ "aria-controls": addId,
741
+ "aria-expanded": addOpen,
742
+ style: { anchorName: addAnchor },
743
+ children: /* @__PURE__ */ jsx3(ComposerIcon, {
744
+ action: "attach"
745
+ })
746
+ }),
747
+ /* @__PURE__ */ jsxs3("div", {
748
+ id: addId,
749
+ popover: "auto",
750
+ role: "group",
751
+ "aria-label": "Add files and more",
752
+ className: "popover popover-menu chat-composer-menu",
753
+ style: { positionAnchor: addAnchor },
754
+ onToggle: (event) => setAddOpen(event.currentTarget.matches(":popover-open")),
755
+ children: [
756
+ /* @__PURE__ */ jsx3("div", {
757
+ className: "chat-composer-group",
758
+ children: "Add"
759
+ }),
760
+ onAttachmentsChange ? /* @__PURE__ */ jsxs3(Fragment3, {
761
+ children: [
762
+ /* @__PURE__ */ jsx3("input", {
763
+ ref: pickerRef,
764
+ type: "file",
765
+ accept,
766
+ multiple,
767
+ disabled,
768
+ hidden: true,
769
+ "aria-label": attachLabel,
770
+ onChange: (event) => {
771
+ const files = Array.from(event.currentTarget.files ?? []);
772
+ event.currentTarget.value = "";
773
+ if (files.length)
774
+ addAttachments(files, "picker");
775
+ }
776
+ }),
777
+ /* @__PURE__ */ jsxs3("button", {
778
+ type: "button",
779
+ className: "popover-menu-item",
780
+ disabled,
781
+ onClick: (event) => {
782
+ event.currentTarget.closest("[popover]")?.hidePopover?.();
783
+ openAttachments();
784
+ },
785
+ children: [
786
+ /* @__PURE__ */ jsx3(ComposerIcon, {
787
+ action: "attach"
788
+ }),
789
+ /* @__PURE__ */ jsx3("span", {
790
+ children: "Files"
791
+ })
792
+ ]
793
+ })
794
+ ]
795
+ }) : null,
796
+ menuContent,
797
+ addMenu
798
+ ]
799
+ })
800
+ ]
801
+ }) : null,
802
+ /* @__PURE__ */ jsx3("div", {
803
+ className: "chat-composer-actions",
804
+ children: actionContent
805
+ })
806
+ ]
807
+ }) : /* @__PURE__ */ jsxs3("div", {
808
+ className: "chat-composer-actions",
809
+ children: [
810
+ attachmentAction,
811
+ actionContent
812
+ ]
813
+ });
814
+ }
815
+ return /* @__PURE__ */ jsxs3("div", {
816
+ ...props,
817
+ ref,
818
+ className: cn("chat-composer", className),
819
+ style: compact ? {
820
+ ...props.style,
821
+ anchorName: props.style?.anchorName && props.style.anchorName !== "none" ? `${props.style.anchorName}, ${completionAnchor}` : completionAnchor
822
+ } : props.style,
823
+ onPaste: (event) => {
824
+ props.onPaste?.(event);
825
+ if (!intakeEvents || event.defaultPrevented || disabled || !onAttachmentsChange)
826
+ return;
827
+ const files = Array.from(event.clipboardData.files ?? []);
828
+ if (files.length)
829
+ addAttachments(files, "paste");
830
+ },
831
+ onDragOver: (event) => {
832
+ props.onDragOver?.(event);
833
+ if (intakeEvents && !event.defaultPrevented && !disabled && onAttachmentsChange && Array.from(event.dataTransfer.types).includes("Files"))
834
+ event.preventDefault();
835
+ },
836
+ onDrop: (event) => {
837
+ props.onDrop?.(event);
838
+ if (!intakeEvents || event.defaultPrevented || disabled || !onAttachmentsChange)
839
+ return;
840
+ const files = Array.from(event.dataTransfer.files ?? []);
841
+ if (files.length) {
842
+ event.preventDefault();
843
+ addAttachments(files, "drop");
844
+ }
845
+ },
846
+ children: [
847
+ entries.length > 0 ? /* @__PURE__ */ jsx3("ul", {
848
+ role: "list",
849
+ className: cn("chat-composer-attachments", thumbnails && "chat-composer-thumbnails"),
850
+ "aria-label": "Attachments",
851
+ children: entries.map(({
852
+ file,
853
+ id,
854
+ name: entryName,
855
+ previewUrl,
856
+ state,
857
+ status,
858
+ progress,
859
+ retry,
860
+ cancel
861
+ }) => {
862
+ const name = file?.name ?? entryName ?? "Attachment";
863
+ return /* @__PURE__ */ jsx3("li", {
864
+ className: cn("chat-composer-attachment", thumbnails && "chat-composer-attachment-tile"),
865
+ "data-state": state,
866
+ children: renderAttachment && file ? /* @__PURE__ */ jsx3(AttachmentContent, {
867
+ file,
868
+ renderAttachment,
869
+ context: {
870
+ remove: () => removeAttachment(id),
871
+ disabled: disabled || !onAttachmentsChange
872
+ }
873
+ }) : /* @__PURE__ */ jsxs3(Fragment3, {
874
+ children: [
875
+ previewUrl ? /* @__PURE__ */ jsx3("img", {
876
+ className: "chat-composer-preview",
877
+ src: previewUrl,
878
+ alt: name
879
+ }) : file ? /* @__PURE__ */ jsx3(AttachmentPreview, {
880
+ file
881
+ }) : null,
882
+ !thumbnails ? /* @__PURE__ */ jsxs3("div", {
883
+ className: "chat-composer-attachment-info",
884
+ children: [
885
+ /* @__PURE__ */ jsx3("span", {
886
+ className: "chat-composer-filename",
887
+ title: name,
888
+ children: name
889
+ }),
890
+ status ? /* @__PURE__ */ jsx3("span", {
891
+ className: "chat-composer-description",
892
+ children: status
893
+ }) : null,
894
+ progress !== undefined ? /* @__PURE__ */ jsx3("progress", {
895
+ className: "progress",
896
+ value: progress,
897
+ max: 1,
898
+ "aria-label": `Preparing ${name}`
899
+ }) : null
900
+ ]
901
+ }) : null,
902
+ retry ? /* @__PURE__ */ jsx3(Button, {
903
+ type: "button",
904
+ size: "sm",
905
+ shape: "circle",
906
+ disabled,
907
+ onClick: retry,
908
+ "aria-label": `Retry ${name}`,
909
+ title: `Retry ${name}`,
910
+ children: /* @__PURE__ */ jsx3(ComposerIcon, {
911
+ action: "retry"
912
+ })
913
+ }) : null,
914
+ cancel ? /* @__PURE__ */ jsx3(Button, {
915
+ type: "button",
916
+ size: "sm",
917
+ shape: "circle",
918
+ disabled,
919
+ onClick: cancel,
920
+ "aria-label": `Cancel ${name}`,
921
+ title: `Cancel ${name}`,
922
+ children: /* @__PURE__ */ jsx3(ComposerIcon, {
923
+ action: "remove"
924
+ })
925
+ }) : null,
926
+ onAttachmentsChange ? /* @__PURE__ */ jsx3(Button, {
927
+ type: "button",
928
+ size: thumbnails ? "xs" : "sm",
929
+ shape: "circle",
930
+ className: thumbnails ? "chat-composer-attachment-remove" : undefined,
931
+ color: "base",
932
+ appearance: "ghost",
933
+ disabled,
934
+ "aria-label": `Remove ${name}`,
935
+ title: `Remove ${name}`,
936
+ onClick: () => removeAttachment(id),
937
+ children: /* @__PURE__ */ jsx3(ComposerIcon, {
938
+ action: "remove"
939
+ })
940
+ }) : null
941
+ ]
942
+ })
943
+ }, id);
944
+ })
945
+ }) : null,
946
+ editor,
947
+ showCompletion || completionHeader || completionStatus ? /* @__PURE__ */ jsx3(CompletionList, {
948
+ composerId,
949
+ label: completion?.label ?? "Suggestions",
950
+ candidates: showCompletion ? candidates : [],
951
+ activeId: active?.id,
952
+ onSelect: selectCompletion,
953
+ compact,
954
+ anchorName: completionAnchor,
955
+ header: completionHeader,
956
+ status: completionStatus,
957
+ onDismiss: dismissCompletion
958
+ }) : null,
959
+ statusContent,
960
+ hasError ? /* @__PURE__ */ jsx3("div", {
961
+ id: `${composerId}-error`,
962
+ role: "alert",
963
+ className: "chat-composer-error chat-composer-status",
964
+ "data-state": "error",
965
+ children: visibleError
966
+ }) : null,
967
+ renderFooter ? renderFooter(renderToolbar) : renderToolbar()
968
+ ]
969
+ });
970
+ });
971
+ ComposerShell.displayName = "ComposerShell";
972
+
973
+ // src/components/chat/composer/useComposerAttachments.ts
974
+ import {
975
+ useEffect as useEffect2,
976
+ useLayoutEffect as useLayoutEffect2,
977
+ useState as useState2,
978
+ useSyncExternalStore
979
+ } from "react";
980
+
981
+ // src/components/chat/composer/attachments.ts
982
+ function metadata(file) {
983
+ return Object.freeze({
984
+ name: file.name,
985
+ mediaType: file.type,
986
+ size: file.size,
987
+ lastModified: file.lastModified
988
+ });
989
+ }
990
+ function limit(value, name) {
991
+ if (value !== undefined && (!Number.isSafeInteger(value) || value < 0))
992
+ throw new TypeError(`${name} must be a nonnegative safe integer`);
993
+ }
994
+ function accepts(file, accept) {
995
+ const types = (accept ?? "").split(",").map((type) => type.trim().toLowerCase()).filter(Boolean);
996
+ const mediaType = file.type.toLowerCase();
997
+ return types.length === 0 || types.some((type) => type === "*/*" ? true : type.startsWith(".") ? file.name.toLowerCase().endsWith(type) : type.endsWith("/*") ? mediaType.startsWith(type.slice(0, -1)) : mediaType === type);
998
+ }
999
+ function validateComposerAttachmentIntake(files, existingCount, policy = {}, source = "picker") {
1000
+ limit(existingCount, "existingCount");
1001
+ limit(policy.maxFiles, "maxFiles");
1002
+ limit(policy.maxFileBytes, "maxFileBytes");
1003
+ const accepted = [];
1004
+ const rejected = [];
1005
+ for (const file of files) {
1006
+ let error;
1007
+ if (!accepts(file, policy.accept))
1008
+ error = {
1009
+ code: "unsupported_type",
1010
+ message: "File type is not accepted."
1011
+ };
1012
+ else if (policy.maxFileBytes !== undefined && file.size > policy.maxFileBytes)
1013
+ error = {
1014
+ code: "file_too_large",
1015
+ message: "File exceeds the size limit."
1016
+ };
1017
+ else if (policy.maxFiles !== undefined && existingCount + accepted.length >= policy.maxFiles)
1018
+ error = { code: "too_many_files", message: "Attachment limit reached." };
1019
+ else
1020
+ error = policy.validate?.(file, source);
1021
+ if (error)
1022
+ rejected.push(Object.freeze({
1023
+ source,
1024
+ metadata: metadata(file),
1025
+ error: Object.freeze({ ...error })
1026
+ }));
1027
+ else
1028
+ accepted.push(file);
1029
+ }
1030
+ return Object.freeze({
1031
+ accepted: Object.freeze(accepted),
1032
+ rejected: Object.freeze(rejected)
1033
+ });
1034
+ }
1035
+ function copyScope(scope) {
1036
+ if (!scope.contextKey || !scope.conversationId)
1037
+ throw new TypeError("Attachment scope requires context and conversation IDs");
1038
+ return Object.freeze({
1039
+ contextKey: scope.contextKey,
1040
+ conversationId: scope.conversationId
1041
+ });
1042
+ }
1043
+ function copyDraftAttachments(attachments, scope) {
1044
+ const result = readComposerDraft({
1045
+ draftVersion: 1,
1046
+ draftKey: "attachment-snapshot",
1047
+ revision: 0,
1048
+ scope,
1049
+ document: { schemaVersion: 1, content: [] },
1050
+ attachments
1051
+ }, { scope, draftKey: "attachment-snapshot" });
1052
+ if (result.status === "incompatible")
1053
+ throw new TypeError(result.reason);
1054
+ return result.value.attachments;
1055
+ }
1056
+ var nextControllerId = 0;
1057
+ var emptyRejections = Object.freeze([]);
1058
+
1059
+ class AttachmentController {
1060
+ options;
1061
+ scope;
1062
+ draftKey;
1063
+ generation = 0;
1064
+ prefix = globalThis.crypto?.randomUUID?.() ?? `attachment-${Date.now()}-${++nextControllerId}`;
1065
+ nextId = 0;
1066
+ usedIds = new Set;
1067
+ entries = new Map;
1068
+ rejections = emptyRejections;
1069
+ listeners = new Set;
1070
+ snapshot;
1071
+ disposed = false;
1072
+ constructor(options) {
1073
+ this.options = options;
1074
+ this.scope = copyScope(options.scope);
1075
+ this.draftKey = options.draftKey;
1076
+ this.snapshot = this.createSnapshot();
1077
+ }
1078
+ getSnapshot = () => this.snapshot;
1079
+ subscribe = (listener) => {
1080
+ if (this.disposed)
1081
+ return () => {};
1082
+ this.listeners.add(listener);
1083
+ return () => this.listeners.delete(listener);
1084
+ };
1085
+ configure(options) {
1086
+ this.assertActive();
1087
+ const scope = copyScope(options.scope);
1088
+ const changed = this.scope.contextKey !== scope.contextKey || this.scope.conversationId !== scope.conversationId || this.draftKey !== options.draftKey;
1089
+ this.options = options;
1090
+ this.scope = scope;
1091
+ this.draftKey = options.draftKey;
1092
+ if (changed)
1093
+ this.clear();
1094
+ }
1095
+ setScope(scope) {
1096
+ this.assertActive();
1097
+ const next = copyScope(scope);
1098
+ if (this.scope.contextKey === next.contextKey && this.scope.conversationId === next.conversationId)
1099
+ return;
1100
+ this.scope = next;
1101
+ this.clear();
1102
+ }
1103
+ intake(files, source) {
1104
+ this.assertActive();
1105
+ const result = validateComposerAttachmentIntake(files, this.entries.size, this.options.policy, source);
1106
+ const entryIds = [];
1107
+ for (const file of result.accepted) {
1108
+ let entryId;
1109
+ do {
1110
+ entryId = `${this.prefix}-${++this.nextId}`;
1111
+ } while (this.usedIds.has(entryId));
1112
+ this.usedIds.add(entryId);
1113
+ const local = {
1114
+ entry: Object.freeze({
1115
+ entryId,
1116
+ metadata: metadata(file),
1117
+ state: Object.freeze({ status: "preparing" })
1118
+ }),
1119
+ file
1120
+ };
1121
+ this.entries.set(entryId, local);
1122
+ this.createPreview(local);
1123
+ entryIds.push(entryId);
1124
+ }
1125
+ this.rejections = Object.freeze([...this.rejections, ...result.rejected]);
1126
+ for (const entryId of entryIds)
1127
+ this.prepare(this.entries.get(entryId), false);
1128
+ this.publish();
1129
+ return Object.freeze({
1130
+ entryIds: Object.freeze(entryIds),
1131
+ rejected: result.rejected
1132
+ });
1133
+ }
1134
+ remove(entryId) {
1135
+ this.assertActive();
1136
+ const local = this.entries.get(entryId);
1137
+ if (!local)
1138
+ return;
1139
+ this.entries.delete(entryId);
1140
+ this.release(local);
1141
+ this.publish();
1142
+ }
1143
+ cancel(entryId) {
1144
+ this.assertActive();
1145
+ const local = this.entries.get(entryId);
1146
+ if (!local?.attempt)
1147
+ return;
1148
+ this.release(local);
1149
+ this.update(local, { status: "cancelled" });
1150
+ }
1151
+ retry(entryId) {
1152
+ this.assertActive();
1153
+ const local = this.entries.get(entryId);
1154
+ if (!local?.file || local.entry.state.status !== "error" && local.entry.state.status !== "cancelled")
1155
+ return false;
1156
+ this.createPreview(local);
1157
+ this.prepare(local);
1158
+ return true;
1159
+ }
1160
+ clearRejections() {
1161
+ this.assertActive();
1162
+ this.rejections = emptyRejections;
1163
+ this.publish();
1164
+ }
1165
+ restore(attachments) {
1166
+ this.assertActive();
1167
+ const restored = copyDraftAttachments(attachments, this.scope).map((attachment) => ({
1168
+ entry: Object.freeze({
1169
+ entryId: attachment.entryId,
1170
+ metadata: attachment.metadata,
1171
+ state: attachment.status === "ready" && this.options.canRecover?.({
1172
+ entryId: attachment.entryId,
1173
+ metadata: attachment.metadata,
1174
+ handle: attachment.handle
1175
+ }, this.scope) === true ? Object.freeze({ status: "ready", handle: attachment.handle }) : Object.freeze({ status: "reattach" })
1176
+ })
1177
+ }));
1178
+ this.generation++;
1179
+ for (const local of this.entries.values())
1180
+ this.release(local);
1181
+ this.entries.clear();
1182
+ for (const local of restored) {
1183
+ this.entries.set(local.entry.entryId, local);
1184
+ this.usedIds.add(local.entry.entryId);
1185
+ }
1186
+ this.rejections = emptyRejections;
1187
+ this.publish();
1188
+ }
1189
+ draftSnapshot() {
1190
+ const attachments = Array.from(this.entries.values(), ({ entry }) => {
1191
+ const base = { entryId: entry.entryId, metadata: entry.metadata };
1192
+ return entry.state.status === "ready" && this.options.canRecover?.({ ...base, handle: entry.state.handle }, this.scope) === true ? { ...base, status: "ready", handle: entry.state.handle } : { ...base, status: "reattach" };
1193
+ });
1194
+ return copyDraftAttachments(attachments, this.scope);
1195
+ }
1196
+ sendableSnapshot() {
1197
+ return Object.freeze(Array.from(this.entries.values(), ({ entry }) => {
1198
+ if (entry.state.status !== "ready")
1199
+ throw new Error("All selected attachments must be ready before submission");
1200
+ return Object.freeze({
1201
+ entryId: entry.entryId,
1202
+ metadata: entry.metadata,
1203
+ handle: entry.state.handle
1204
+ });
1205
+ }));
1206
+ }
1207
+ file(entryId) {
1208
+ return this.entries.get(entryId)?.file;
1209
+ }
1210
+ previewUrl(entryId) {
1211
+ return this.entries.get(entryId)?.preview;
1212
+ }
1213
+ clear() {
1214
+ this.assertActive();
1215
+ this.generation++;
1216
+ for (const local of this.entries.values())
1217
+ this.release(local);
1218
+ this.entries.clear();
1219
+ this.rejections = emptyRejections;
1220
+ this.publish();
1221
+ }
1222
+ dispose() {
1223
+ if (this.disposed)
1224
+ return;
1225
+ this.disposed = true;
1226
+ this.generation++;
1227
+ for (const local of this.entries.values())
1228
+ this.release(local);
1229
+ this.entries.clear();
1230
+ this.rejections = emptyRejections;
1231
+ this.snapshot = this.createSnapshot();
1232
+ const listeners = [...this.listeners];
1233
+ this.listeners.clear();
1234
+ for (const listener of listeners)
1235
+ listener();
1236
+ }
1237
+ assertActive() {
1238
+ if (this.disposed)
1239
+ throw new Error("Attachment controller is disposed");
1240
+ }
1241
+ createSnapshot() {
1242
+ return Object.freeze({
1243
+ scope: this.scope,
1244
+ draftKey: this.draftKey,
1245
+ generation: this.generation,
1246
+ entries: Object.freeze(Array.from(this.entries.values(), ({ entry }) => entry)),
1247
+ rejections: this.rejections
1248
+ });
1249
+ }
1250
+ publish() {
1251
+ this.snapshot = this.createSnapshot();
1252
+ for (const listener of [...this.listeners])
1253
+ listener();
1254
+ }
1255
+ update(local, state) {
1256
+ local.entry = Object.freeze({
1257
+ ...local.entry,
1258
+ state: Object.freeze(state)
1259
+ });
1260
+ this.publish();
1261
+ }
1262
+ createPreview(local) {
1263
+ if (local.preview !== undefined || !local.file?.type.startsWith("image/") || typeof URL.createObjectURL !== "function")
1264
+ return;
1265
+ local.preview = URL.createObjectURL(local.file);
1266
+ }
1267
+ release(local) {
1268
+ const attempt = local.attempt;
1269
+ local.attempt = undefined;
1270
+ attempt?.abort.abort();
1271
+ if (local.preview !== undefined) {
1272
+ URL.revokeObjectURL(local.preview);
1273
+ local.preview = undefined;
1274
+ }
1275
+ }
1276
+ prepare(local, notify = true) {
1277
+ const generation = this.generation;
1278
+ const scope = this.scope;
1279
+ const token = Symbol();
1280
+ const abort = new AbortController;
1281
+ const prepare = this.options.prepare;
1282
+ local.attempt = { token, abort };
1283
+ const isCurrent = () => !this.disposed && this.generation === generation && this.entries.get(local.entry.entryId) === local && local.attempt?.token === token && !abort.signal.aborted;
1284
+ if (notify)
1285
+ this.update(local, { status: "preparing" });
1286
+ Promise.resolve().then(() => {
1287
+ if (!isCurrent())
1288
+ return;
1289
+ return prepare(local.file, {
1290
+ entryId: local.entry.entryId,
1291
+ scope,
1292
+ signal: abort.signal,
1293
+ reportProgress: (progress) => {
1294
+ if (!isCurrent() || !Number.isFinite(progress))
1295
+ return;
1296
+ this.update(local, {
1297
+ status: "uploading",
1298
+ progress: Math.max(0, Math.min(1, progress))
1299
+ });
1300
+ }
1301
+ });
1302
+ }).then((handle) => {
1303
+ if (!isCurrent())
1304
+ return;
1305
+ const attachment = copyDraftAttachments([
1306
+ {
1307
+ entryId: local.entry.entryId,
1308
+ metadata: local.entry.metadata,
1309
+ status: "ready",
1310
+ handle
1311
+ }
1312
+ ], scope)[0];
1313
+ if (attachment.status !== "ready")
1314
+ return;
1315
+ local.attempt = undefined;
1316
+ this.update(local, { status: "ready", handle: attachment.handle });
1317
+ }).catch((cause) => {
1318
+ if (!isCurrent())
1319
+ return;
1320
+ local.attempt = undefined;
1321
+ this.update(local, {
1322
+ status: "error",
1323
+ error: Object.freeze({
1324
+ code: "preparation_failed",
1325
+ message: cause instanceof Error ? cause.message : "Unable to prepare attachment."
1326
+ })
1327
+ });
1328
+ });
1329
+ }
1330
+ }
1331
+ function createComposerAttachmentController(options) {
1332
+ return new AttachmentController(options);
1333
+ }
1334
+
1335
+ // src/components/chat/composer/useComposerAttachments.ts
1336
+ function useComposerAttachments(options) {
1337
+ const [controller] = useState2(() => createComposerAttachmentController(options));
1338
+ const snapshot = useSyncExternalStore(controller.subscribe, controller.getSnapshot, controller.getSnapshot);
1339
+ useLayoutEffect2(() => {
1340
+ controller.configure(options);
1341
+ });
1342
+ useEffect2(() => () => {
1343
+ controller.clear();
1344
+ }, [controller]);
1345
+ return { ...snapshot, controller };
1346
+ }
1347
+
1348
+ // src/components/chat/composer/useComposerProviders.ts
1349
+ import { useLayoutEffect as useLayoutEffect3, useState as useState3, useSyncExternalStore as useSyncExternalStore2 } from "react";
1350
+
1351
+ // src/components/chat/composer/providers.ts
1352
+ var nextController = 0;
1353
+ function composerProviderItemId(providerId, candidateId) {
1354
+ return `provider:${encodeURIComponent(providerId)}:${encodeURIComponent(candidateId)}`;
1355
+ }
1356
+ function matchComposerProviderTrigger(context, provider) {
1357
+ const selection = context.selection;
1358
+ if (!selection || selection.start !== selection.end)
1359
+ return;
1360
+ const node = context.document.content[selection.nodeIndex];
1361
+ if (node?.type !== "text" || !Number.isSafeInteger(selection.start) || selection.start < 0 || selection.start > node.text.length || !provider.trigger.text || /\s/u.test(provider.trigger.text))
1362
+ return;
1363
+ const prefix = node.text.slice(0, selection.start);
1364
+ const marker = provider.trigger.text;
1365
+ const start = provider.trigger.position === "leading" ? 0 : prefix.search(/\S*$/u);
1366
+ if (!prefix.startsWith(marker, start))
1367
+ return;
1368
+ if (provider.trigger.position === "leading") {
1369
+ if (selection.nodeIndex !== 0 || start !== 0 || context.document.command)
1370
+ return;
1371
+ } else if (start > 0 && !/\s/u.test(prefix[start - 1]))
1372
+ return;
1373
+ const query = prefix.slice(start + marker.length);
1374
+ if (/\s/u.test(query))
1375
+ return;
1376
+ return Object.freeze({
1377
+ text: prefix.slice(start),
1378
+ nodeIndex: selection.nodeIndex,
1379
+ start,
1380
+ end: selection.start,
1381
+ caret: selection.start
1382
+ });
1383
+ }
1384
+ function sameRequest(a, b) {
1385
+ return a.requestId === b.requestId && a.providerId === b.providerId && a.scope.contextKey === b.scope.contextKey && a.scope.conversationId === b.scope.conversationId && a.documentRevision === b.documentRevision && a.instanceGeneration === b.instanceGeneration && a.query === b.query && a.trigger.text === b.trigger.text && a.trigger.nodeIndex === b.trigger.nodeIndex && a.trigger.start === b.trigger.start && a.trigger.end === b.trigger.end && a.trigger.caret === b.trigger.caret;
1386
+ }
1387
+ function sameProviders(previous, next) {
1388
+ return previous.length === next.length && previous.every((provider, index) => {
1389
+ const other = next[index];
1390
+ return provider.providerId === other.providerId && provider.label === other.label && provider.query === other.query && provider.trigger.text === other.trigger.text && provider.trigger.position === other.trigger.position;
1391
+ });
1392
+ }
1393
+ function inputSnapshot(context) {
1394
+ const document2 = snapshotComposerDocument(context.document);
1395
+ if (!Number.isSafeInteger(context.documentRevision) || context.documentRevision < 0 || !Number.isSafeInteger(context.instanceGeneration) || context.instanceGeneration < 0)
1396
+ throw new TypeError("Provider revisions and generations must be nonnegative integers");
1397
+ const providers = context.providers.map((provider) => Object.freeze({
1398
+ ...provider,
1399
+ trigger: Object.freeze({ ...provider.trigger })
1400
+ }));
1401
+ if (new Set(providers.map((provider) => provider.providerId)).size !== providers.length || providers.some((provider) => !provider.providerId))
1402
+ throw new TypeError("Suggestion providers require unique, nonempty identities");
1403
+ const scope = Object.freeze({ ...context.scope });
1404
+ const selection = context.selection ? Object.freeze({ ...context.selection }) : null;
1405
+ return {
1406
+ ...context,
1407
+ document: document2,
1408
+ scope,
1409
+ selection,
1410
+ providers,
1411
+ signature: JSON.stringify([
1412
+ document2,
1413
+ context.documentRevision,
1414
+ scope.contextKey,
1415
+ scope.conversationId,
1416
+ context.instanceGeneration,
1417
+ selection
1418
+ ])
1419
+ };
1420
+ }
1421
+ function errorDetails(cause) {
1422
+ return Object.freeze({
1423
+ code: "provider_error",
1424
+ message: cause instanceof Error ? cause.message : "Unable to load suggestions."
1425
+ });
1426
+ }
1427
+ function candidateSnapshot(candidate) {
1428
+ if (typeof candidate.id !== "string" || !candidate.id || typeof candidate.label !== "string" || [candidate.description, candidate.group, candidate.disabledReason].some((value) => value !== undefined && typeof value !== "string"))
1429
+ throw new TypeError("Suggestion candidates require an identity and label");
1430
+ const action = candidate.action;
1431
+ if (action.type === "insert") {
1432
+ const document2 = snapshotComposerDocument({
1433
+ schemaVersion: 1,
1434
+ content: action.content,
1435
+ ...action.command ? { command: action.command } : {}
1436
+ });
1437
+ return Object.freeze({
1438
+ ...candidate,
1439
+ action: Object.freeze({
1440
+ type: "insert",
1441
+ content: document2.content,
1442
+ ...document2.command ? { command: document2.command } : {}
1443
+ })
1444
+ });
1445
+ }
1446
+ if (action.type === "drill") {
1447
+ if (typeof action.refId !== "string" || !action.refId)
1448
+ throw new TypeError("Directory candidates require a refId");
1449
+ } else if (action.type === "invoke") {
1450
+ const document2 = snapshotComposerDocument({
1451
+ schemaVersion: 1,
1452
+ content: [],
1453
+ command: action.command
1454
+ });
1455
+ return Object.freeze({
1456
+ ...candidate,
1457
+ action: Object.freeze({
1458
+ type: "invoke",
1459
+ command: document2.command,
1460
+ ...action.arguments !== undefined ? { arguments: snapshotComposerJson(action.arguments) } : {}
1461
+ })
1462
+ });
1463
+ } else
1464
+ throw new TypeError("Unsupported suggestion action");
1465
+ return Object.freeze({ ...candidate, action: Object.freeze({ ...action }) });
1466
+ }
1467
+ var idleSnapshot = () => Object.freeze({
1468
+ status: "idle",
1469
+ groups: Object.freeze([]),
1470
+ items: Object.freeze([]),
1471
+ breadcrumbs: Object.freeze([])
1472
+ });
1473
+
1474
+ class ComposerProviderController {
1475
+ prefix = `composer-provider-${++nextController}`;
1476
+ requestSequence = 0;
1477
+ generation = 0;
1478
+ input;
1479
+ disposed = false;
1480
+ dismissed = false;
1481
+ navigationProvider;
1482
+ breadcrumbs = [];
1483
+ preferredActiveId;
1484
+ requests = new Map;
1485
+ listeners = new Set;
1486
+ snapshot = idleSnapshot();
1487
+ getSnapshot = () => this.snapshot;
1488
+ subscribe = (listener) => {
1489
+ this.listeners.add(listener);
1490
+ return () => this.listeners.delete(listener);
1491
+ };
1492
+ activate() {
1493
+ this.disposed = false;
1494
+ }
1495
+ update(context) {
1496
+ if (this.disposed)
1497
+ return;
1498
+ let input;
1499
+ try {
1500
+ input = inputSnapshot(context);
1501
+ } catch (cause) {
1502
+ this.cancel();
1503
+ this.input = undefined;
1504
+ const error = errorDetails(cause);
1505
+ if (this.snapshot.status !== "error" || this.snapshot.groups.length > 0 || this.snapshot.error?.message !== error.message)
1506
+ this.publish([], error);
1507
+ return;
1508
+ }
1509
+ if (this.input?.signature === input.signature && sameProviders(this.input.providers, input.providers)) {
1510
+ const availabilityChanged = this.input.candidateDisabledReason !== input.candidateDisabledReason;
1511
+ this.input = input;
1512
+ if (availabilityChanged)
1513
+ this.publish(this.snapshot.groups);
1514
+ return;
1515
+ }
1516
+ this.input = input;
1517
+ this.dismissed = false;
1518
+ this.navigationProvider = undefined;
1519
+ this.breadcrumbs = [];
1520
+ this.preferredActiveId = undefined;
1521
+ this.query();
1522
+ }
1523
+ dismiss() {
1524
+ if (this.disposed)
1525
+ return;
1526
+ this.cancel();
1527
+ this.dismissed = true;
1528
+ this.publish([]);
1529
+ }
1530
+ retry() {
1531
+ if (this.disposed || !this.input)
1532
+ return;
1533
+ this.dismissed = false;
1534
+ this.query();
1535
+ }
1536
+ back(depth = this.breadcrumbs.length - 1) {
1537
+ if (this.disposed || !this.input || depth < 0 || !Number.isInteger(depth))
1538
+ return;
1539
+ if (depth >= this.breadcrumbs.length)
1540
+ return;
1541
+ this.breadcrumbs = this.breadcrumbs.slice(0, depth);
1542
+ if (depth === 0)
1543
+ this.navigationProvider = undefined;
1544
+ this.preferredActiveId = undefined;
1545
+ this.query();
1546
+ }
1547
+ move(direction) {
1548
+ const enabled = this.snapshot.items.filter((item) => this.disabledReason(item) === undefined);
1549
+ if (this.disposed || enabled.length === 0)
1550
+ return;
1551
+ const index = enabled.findIndex((item) => item.id === this.snapshot.activeId);
1552
+ this.preferredActiveId = enabled[(index + direction + enabled.length) % enabled.length].id;
1553
+ this.publish(this.snapshot.groups);
1554
+ }
1555
+ select(itemId = this.snapshot.activeId, current) {
1556
+ if (current)
1557
+ this.update(current);
1558
+ if (this.disposed || !itemId || !this.input || this.dismissed)
1559
+ return;
1560
+ const item = this.snapshot.items.find((candidate) => candidate.id === itemId);
1561
+ if (!item || this.disabledReason(item) !== undefined)
1562
+ return;
1563
+ const provider = this.input.providers.find((candidate) => candidate.providerId === item.providerId);
1564
+ const trigger = provider && matchComposerProviderTrigger(this.input, provider);
1565
+ if (!provider || !trigger || !sameRequest(item.request, {
1566
+ ...item.request,
1567
+ scope: this.input.scope,
1568
+ instanceGeneration: this.input.instanceGeneration,
1569
+ documentRevision: this.input.documentRevision,
1570
+ query: trigger.text.slice(provider.trigger.text.length),
1571
+ trigger
1572
+ }))
1573
+ return;
1574
+ const effect = Object.freeze({
1575
+ itemId: item.id,
1576
+ request: item.request,
1577
+ candidate: item.candidate,
1578
+ action: item.candidate.action
1579
+ });
1580
+ if (effect.action.type === "drill") {
1581
+ this.navigationProvider = item.providerId;
1582
+ this.breadcrumbs = [
1583
+ ...this.breadcrumbs,
1584
+ Object.freeze({
1585
+ refId: effect.action.refId,
1586
+ label: item.candidate.label
1587
+ })
1588
+ ];
1589
+ this.preferredActiveId = undefined;
1590
+ this.query();
1591
+ } else
1592
+ this.dismiss();
1593
+ return effect;
1594
+ }
1595
+ dispose() {
1596
+ this.cancel();
1597
+ this.disposed = true;
1598
+ this.input = undefined;
1599
+ this.breadcrumbs = [];
1600
+ this.navigationProvider = undefined;
1601
+ this.preferredActiveId = undefined;
1602
+ this.snapshot = idleSnapshot();
1603
+ this.listeners.clear();
1604
+ }
1605
+ cancel() {
1606
+ this.generation++;
1607
+ for (const controller of this.requests.values())
1608
+ controller.abort();
1609
+ this.requests.clear();
1610
+ }
1611
+ disabledReason(item) {
1612
+ return item.candidate.disabledReason ?? this.input?.candidateDisabledReason?.(item.candidate);
1613
+ }
1614
+ publish(groups, error) {
1615
+ const items = Object.freeze(groups.flatMap((group) => group.items));
1616
+ const enabled = items.filter((item) => this.disabledReason(item) === undefined);
1617
+ const active = enabled.find((item) => item.id === this.preferredActiveId) ?? enabled[0];
1618
+ if (active)
1619
+ this.preferredActiveId = active.id;
1620
+ const status = error ? "error" : groups.some((group) => group.status === "loading") ? "loading" : items.length ? "ready" : groups.some((group) => group.status === "error") ? "error" : groups.length ? "empty" : "idle";
1621
+ this.snapshot = Object.freeze({
1622
+ status,
1623
+ groups: Object.freeze([...groups]),
1624
+ items,
1625
+ activeId: active?.id,
1626
+ breadcrumbs: Object.freeze([...this.breadcrumbs]),
1627
+ ...error ? { error } : {}
1628
+ });
1629
+ for (const listener of this.listeners)
1630
+ listener();
1631
+ }
1632
+ query() {
1633
+ this.cancel();
1634
+ const input = this.input;
1635
+ if (!input || this.disposed || this.dismissed)
1636
+ return;
1637
+ const generation = this.generation;
1638
+ const matches = input.providers.flatMap((provider) => {
1639
+ if (this.navigationProvider && provider.providerId !== this.navigationProvider)
1640
+ return [];
1641
+ const trigger = matchComposerProviderTrigger(input, provider);
1642
+ return trigger ? [{ provider, trigger }] : [];
1643
+ });
1644
+ const groups = matches.map(({ provider, trigger }) => {
1645
+ const request = Object.freeze({
1646
+ requestId: `${this.prefix}-${++this.requestSequence}`,
1647
+ providerId: provider.providerId,
1648
+ scope: input.scope,
1649
+ instanceGeneration: input.instanceGeneration,
1650
+ documentRevision: input.documentRevision,
1651
+ query: trigger.text.slice(provider.trigger.text.length),
1652
+ trigger
1653
+ });
1654
+ return Object.freeze({
1655
+ providerId: provider.providerId,
1656
+ label: provider.label ?? provider.providerId,
1657
+ status: "loading",
1658
+ items: Object.freeze([]),
1659
+ request
1660
+ });
1661
+ });
1662
+ this.publish(groups);
1663
+ for (let index = 0;index < matches.length; index++) {
1664
+ const { provider } = matches[index];
1665
+ const group = groups[index];
1666
+ const controller = new AbortController;
1667
+ this.requests.set(provider.providerId, controller);
1668
+ const navigation = Object.freeze({
1669
+ breadcrumbs: Object.freeze([...this.breadcrumbs]),
1670
+ ...this.breadcrumbs.length ? { refId: this.breadcrumbs.at(-1).refId } : {}
1671
+ });
1672
+ const isCurrent = () => !this.disposed && generation === this.generation && this.requests.get(provider.providerId) === controller && !controller.signal.aborted;
1673
+ const resolve = async () => {
1674
+ try {
1675
+ const result = await provider.query(group.request, controller.signal, navigation);
1676
+ if (!isCurrent())
1677
+ return;
1678
+ if (!sameRequest(group.request, result.request))
1679
+ throw new TypeError("Provider returned a result for a different request");
1680
+ const identities = new Set;
1681
+ const items = result.candidates.map((candidate) => {
1682
+ const snapshot = candidateSnapshot(candidate);
1683
+ if (identities.has(snapshot.id))
1684
+ throw new TypeError("Duplicate suggestion identity");
1685
+ identities.add(snapshot.id);
1686
+ return Object.freeze({
1687
+ id: composerProviderItemId(provider.providerId, snapshot.id),
1688
+ providerId: provider.providerId,
1689
+ candidate: snapshot,
1690
+ request: group.request
1691
+ });
1692
+ });
1693
+ this.replaceGroup(provider.providerId, {
1694
+ ...group,
1695
+ status: items.length ? "ready" : "empty",
1696
+ items: Object.freeze(items)
1697
+ });
1698
+ } catch (cause) {
1699
+ if (isCurrent())
1700
+ this.replaceGroup(provider.providerId, {
1701
+ ...group,
1702
+ status: "error",
1703
+ items: Object.freeze([]),
1704
+ error: errorDetails(cause)
1705
+ });
1706
+ } finally {
1707
+ if (isCurrent())
1708
+ this.requests.delete(provider.providerId);
1709
+ }
1710
+ };
1711
+ resolve();
1712
+ }
1713
+ }
1714
+ replaceGroup(providerId, group) {
1715
+ this.publish(this.snapshot.groups.map((previous) => previous.providerId === providerId ? Object.freeze(group) : previous));
1716
+ }
1717
+ }
1718
+
1719
+ // src/components/chat/composer/useComposerProviders.ts
1720
+ function useComposerProviders(context) {
1721
+ const [controller] = useState3(() => new ComposerProviderController);
1722
+ const snapshot = useSyncExternalStore2(controller.subscribe, controller.getSnapshot, controller.getSnapshot);
1723
+ useLayoutEffect3(() => {
1724
+ controller.activate();
1725
+ return () => controller.dispose();
1726
+ }, [controller]);
1727
+ useLayoutEffect3(() => {
1728
+ controller.update(context);
1729
+ });
1730
+ return { controller, snapshot };
1731
+ }
1732
+
1733
+ // src/components/chat/composer/useComposerSession.ts
1734
+ import { useId, useLayoutEffect as useLayoutEffect4, useState as useState4, useSyncExternalStore as useSyncExternalStore3 } from "react";
1735
+
1736
+ // src/components/chat/composer/session.ts
1737
+ function sameComposerScope(a, b) {
1738
+ return a.contextKey === b.contextKey && a.conversationId === b.conversationId;
1739
+ }
1740
+
1741
+ class ComposerUncertainTransportError extends Error {
1742
+ code = "uncertain_transport";
1743
+ }
1744
+ function canonical(value) {
1745
+ const json = snapshotComposerJson(value);
1746
+ function encode(item) {
1747
+ if (item === null || typeof item !== "object")
1748
+ return JSON.stringify(item);
1749
+ if (Array.isArray(item))
1750
+ return `[${item.map(encode).join(",")}]`;
1751
+ return `{${Object.keys(item).sort().map((key) => `${JSON.stringify(key)}:${encode(item[key])}`).join(",")}}`;
1752
+ }
1753
+ return encode(json);
1754
+ }
1755
+ function composerActionEligibility(context, requestedIntent) {
1756
+ const { host, runtime, document: document2 } = context;
1757
+ const operation = document2.command ? host.commandOperation?.(document2.command) ?? "prompt" : "prompt";
1758
+ const intent = requestedIntent ?? (runtime.status === "running" ? context.policy?.runningIntent ?? "follow_up" : "send");
1759
+ const label = operation === "command" ? "Run command" : { send: "Send", follow_up: "Send follow-up", steer: "Steer turn" }[intent];
1760
+ const result = {
1761
+ operation,
1762
+ ...operation === "prompt" ? { intent } : {},
1763
+ label
1764
+ };
1765
+ let reason;
1766
+ if (context.disabled || runtime.status === "read_only")
1767
+ reason = "Read only";
1768
+ else if (runtime.status === "disconnected")
1769
+ reason = "Disconnected";
1770
+ else if (context.busy)
1771
+ reason = "Awaiting admission";
1772
+ else if (context.canSubmit === false)
1773
+ reason = "Admission unavailable";
1774
+ else if (context.attachmentsPending)
1775
+ reason = "Attachments are not ready";
1776
+ else if (!host.capabilities.documentVersions.includes(1))
1777
+ reason = "Unsupported document version";
1778
+ else if (document2.command && !host.capabilities.commands)
1779
+ reason = "Commands unavailable";
1780
+ else if ((context.attachments?.length ?? 0) > 0 && !host.capabilities.attachments)
1781
+ reason = "Attachments unavailable";
1782
+ else if (operation === "prompt" && !host.capabilities.intents.includes(intent))
1783
+ reason = "Intent unavailable";
1784
+ else if (intent === "steer" && operation === "prompt" && (runtime.status !== "running" || !runtime.activeTurnId))
1785
+ reason = "No active steering target";
1786
+ else if (!document2.command && !exportComposerText(document2).trim() && !(context.allowAttachmentOnly && context.attachments?.length))
1787
+ reason = "Empty draft";
1788
+ return { ...result, allowed: !reason, ...reason ? { reason } : {} };
1789
+ }
1790
+ function error(code, message) {
1791
+ return Object.freeze({ code, message });
1792
+ }
1793
+ function unknownReceipt(snapshot, cause) {
1794
+ return Object.freeze({
1795
+ protocolVersion: 1,
1796
+ clientSubmissionId: snapshot.clientSubmissionId,
1797
+ scope: snapshot.scope,
1798
+ operation: snapshot.operation,
1799
+ outcome: "unknown",
1800
+ error: cause
1801
+ });
1802
+ }
1803
+ function snapshotComposerReceipt(input, submission) {
1804
+ const value = snapshotComposerJson(input);
1805
+ if (!value || typeof value !== "object" || Array.isArray(value))
1806
+ throw new TypeError("Invalid receipt");
1807
+ const candidate = value;
1808
+ const scope = candidate.scope;
1809
+ if (candidate.protocolVersion !== 1 || candidate.clientSubmissionId !== submission.clientSubmissionId || !scope || typeof scope !== "object" || Array.isArray(scope) || Object.keys(scope).length !== 2 || typeof scope.contextKey !== "string" || !scope.contextKey || typeof scope.conversationId !== "string" || !scope.conversationId || !sameComposerScope(scope, submission.scope) || candidate.operation !== submission.operation)
1810
+ throw new TypeError("Receipt identity mismatch");
1811
+ const common = [
1812
+ "protocolVersion",
1813
+ "clientSubmissionId",
1814
+ "scope",
1815
+ "operation",
1816
+ "outcome"
1817
+ ];
1818
+ let allowed;
1819
+ if (candidate.outcome === "accepted") {
1820
+ if (submission.operation === "command") {
1821
+ if (!Object.hasOwn(candidate, "result"))
1822
+ throw new TypeError("Missing command result");
1823
+ allowed = [...common, "result"];
1824
+ } else {
1825
+ if (!["immediate", "follow_up", "steer"].includes(String(candidate.delivery)) || !["volatile", "durable"].includes(String(candidate.persistence)))
1826
+ throw new TypeError("Missing prompt admission evidence");
1827
+ if (submission.intent === "steer" !== (candidate.delivery === "steer"))
1828
+ throw new TypeError("Unexpected steering delivery");
1829
+ for (const key of ["messageId", "turnId", "queueItemId"])
1830
+ if (Object.hasOwn(candidate, key) && (typeof candidate[key] !== "string" || !candidate[key]))
1831
+ throw new TypeError("Invalid admission identity");
1832
+ if (Object.hasOwn(candidate, "queueRevision") && (!Number.isSafeInteger(candidate.queueRevision) || Number(candidate.queueRevision) < 0))
1833
+ throw new TypeError("Invalid queue revision");
1834
+ allowed = [
1835
+ ...common,
1836
+ "delivery",
1837
+ "persistence",
1838
+ "messageId",
1839
+ "turnId",
1840
+ "queueItemId",
1841
+ "queueRevision"
1842
+ ];
1843
+ }
1844
+ } else if (candidate.outcome === "rejected" || candidate.outcome === "unknown") {
1845
+ const detail = candidate.error;
1846
+ if (!detail || typeof detail !== "object" || Array.isArray(detail) || Object.keys(detail).some((key) => !["code", "message", "details"].includes(key)) || typeof detail.code !== "string" || !detail.code || typeof detail.message !== "string")
1847
+ throw new TypeError("Missing receipt explanation");
1848
+ allowed = [...common, "error"];
1849
+ } else
1850
+ throw new TypeError("Unknown receipt outcome");
1851
+ if (Object.keys(candidate).some((key) => !allowed.includes(key)))
1852
+ throw new TypeError("Unsupported receipt fields");
1853
+ return value;
1854
+ }
1855
+ function createComposerSessionController(initial, identity) {
1856
+ let context = initial;
1857
+ let disposed = false;
1858
+ let state = Object.freeze({ submitting: false });
1859
+ const listeners = new Set;
1860
+ const work = new Map;
1861
+ let activeId;
1862
+ const recoveryFailures = new Map;
1863
+ const emit = (next) => {
1864
+ state = Object.freeze({
1865
+ ...next,
1866
+ recoveryFailures: recoveryFailures.size ? Object.freeze([...recoveryFailures.values()]) : undefined
1867
+ });
1868
+ if (disposed)
1869
+ return;
1870
+ for (const listener of listeners)
1871
+ listener();
1872
+ };
1873
+ const current = (attempt) => !disposed && attempt.instanceId === identity.instanceId && attempt.instanceGeneration === context.instanceGeneration && sameComposerScope(attempt.snapshot.scope, context.scope) && attempt.snapshot.draftKey === context.draftKey && activeId === attempt.snapshot.clientSubmissionId;
1874
+ function handoffFailure(attempt, cause) {
1875
+ recoveryFailures.set(attempt.snapshot.clientSubmissionId, attempt);
1876
+ return error("recovery_handoff_failed", `Recovery handoff failed; draft retained. ${cause instanceof Error ? cause.message : "Host recovery owner failed"}`);
1877
+ }
1878
+ async function transmit(attempt, lookup = false) {
1879
+ const { snapshot } = attempt;
1880
+ const id = snapshot.clientSubmissionId;
1881
+ if (work.has(id))
1882
+ return;
1883
+ const host = context.host;
1884
+ const abort = new AbortController;
1885
+ const pending = Object.freeze({
1886
+ snapshot,
1887
+ instanceId: attempt.instanceId,
1888
+ instanceGeneration: attempt.instanceGeneration,
1889
+ createdAt: attempt.createdAt,
1890
+ status: "pending"
1891
+ });
1892
+ try {
1893
+ host.recovery.retain(pending);
1894
+ recoveryFailures.delete(id);
1895
+ } catch (cause) {
1896
+ const failure = handoffFailure(pending, cause);
1897
+ emit({ ...state, submitting: false, error: failure });
1898
+ return;
1899
+ }
1900
+ work.set(id, { attempt: pending, abort, owner: host.recovery });
1901
+ if (current(attempt))
1902
+ emit({ submitting: true });
1903
+ let receipt;
1904
+ try {
1905
+ const response = lookup ? await host.reconcile(snapshot, abort.signal) : await host.submit(snapshot, abort.signal);
1906
+ receipt = response.outcome === "not_found" ? unknownReceipt(snapshot, error("not_found", "No admission record found. Delivery remains unresolved; retry requires host authorization.")) : snapshotComposerReceipt(response, snapshot);
1907
+ } catch (cause) {
1908
+ receipt = unknownReceipt(snapshot, error(cause instanceof ComposerUncertainTransportError ? cause.code : "unresolved_submission", cause instanceof Error ? cause.message : "Admission could not be confirmed"));
1909
+ }
1910
+ work.delete(id);
1911
+ let recoveryError;
1912
+ let settled = Object.freeze({
1913
+ ...attempt,
1914
+ status: receipt.outcome,
1915
+ receipt
1916
+ });
1917
+ try {
1918
+ const definitive = host.recovery.getSnapshot().find((record) => record.snapshot.clientSubmissionId === id && (record.status === "accepted" || record.status === "rejected"));
1919
+ if (definitive?.receipt) {
1920
+ if (canonical(definitive.snapshot) !== canonical(snapshot))
1921
+ throw new TypeError("Recovery snapshot identity mismatch");
1922
+ receipt = snapshotComposerReceipt(definitive.receipt, snapshot);
1923
+ settled = Object.freeze({
1924
+ ...attempt,
1925
+ status: receipt.outcome,
1926
+ receipt
1927
+ });
1928
+ }
1929
+ host.recovery.retain(settled);
1930
+ recoveryFailures.delete(id);
1931
+ } catch (cause) {
1932
+ recoveryError = handoffFailure(settled, cause);
1933
+ }
1934
+ if (!current(attempt))
1935
+ emit({ ...state, ...recoveryError ? { error: recoveryError } : {} });
1936
+ if (current(attempt)) {
1937
+ emit({
1938
+ submitting: false,
1939
+ lastReceipt: receipt,
1940
+ ...recoveryError ? { error: recoveryError } : receipt.outcome !== "accepted" ? { error: receipt.error } : {}
1941
+ });
1942
+ if (current(attempt) && receipt.outcome === "accepted" && !recoveryError) {
1943
+ if (context.revision === snapshot.draftRevision && canonical(context.document) === canonical(snapshot.document))
1944
+ context.onAccepted?.(snapshot);
1945
+ if (current(attempt))
1946
+ context.onAcceptedAttachments?.(snapshot.attachments);
1947
+ }
1948
+ }
1949
+ return receipt;
1950
+ }
1951
+ return {
1952
+ activate() {
1953
+ if (!disposed)
1954
+ return;
1955
+ disposed = false;
1956
+ activeId = undefined;
1957
+ emit({ submitting: false });
1958
+ },
1959
+ getSnapshot: () => state,
1960
+ subscribe: (listener) => {
1961
+ listeners.add(listener);
1962
+ return () => listeners.delete(listener);
1963
+ },
1964
+ update(next) {
1965
+ const switched = context.instanceGeneration !== next.instanceGeneration || !sameComposerScope(context.scope, next.scope) || context.draftKey !== next.draftKey;
1966
+ context = next;
1967
+ if (switched) {
1968
+ activeId = undefined;
1969
+ emit({ submitting: false });
1970
+ }
1971
+ },
1972
+ eligibility: (intent) => composerActionEligibility(context, intent),
1973
+ async submit(intent) {
1974
+ const action = composerActionEligibility(context, intent);
1975
+ if (disposed || state.submitting || !action.allowed)
1976
+ return;
1977
+ const clientSubmissionId = identity.nextSubmissionId?.() ?? crypto.randomUUID();
1978
+ const common = {
1979
+ protocolVersion: 1,
1980
+ clientSubmissionId,
1981
+ scope: context.scope,
1982
+ draftKey: context.draftKey,
1983
+ draftRevision: context.revision,
1984
+ document: context.document,
1985
+ attachments: context.attachments ?? [],
1986
+ options: context.options ?? {}
1987
+ };
1988
+ const snapshot = snapshotComposerSubmission(action.operation === "command" ? {
1989
+ ...common,
1990
+ operation: "command",
1991
+ document: {
1992
+ ...context.document,
1993
+ command: context.document.command
1994
+ }
1995
+ } : action.intent === "steer" ? {
1996
+ ...common,
1997
+ operation: "prompt",
1998
+ intent: "steer",
1999
+ targetTurnId: context.runtime.activeTurnId
2000
+ } : {
2001
+ ...common,
2002
+ operation: "prompt",
2003
+ intent: action.intent
2004
+ });
2005
+ const attempt = Object.freeze({
2006
+ snapshot,
2007
+ instanceId: identity.instanceId,
2008
+ instanceGeneration: context.instanceGeneration,
2009
+ createdAt: Date.now(),
2010
+ status: "pending"
2011
+ });
2012
+ activeId = clientSubmissionId;
2013
+ return transmit(attempt);
2014
+ },
2015
+ async reconcile(id) {
2016
+ if (disposed || !context.host.reconcile)
2017
+ return;
2018
+ const record = context.host.recovery.getSnapshot().find((item) => item.snapshot.clientSubmissionId === id);
2019
+ if (!record || record.status !== "pending" && record.status !== "unknown")
2020
+ return;
2021
+ return transmit(record, true);
2022
+ },
2023
+ async retry(id) {
2024
+ if (disposed || !context.host.authorizeRetry)
2025
+ return;
2026
+ const host = context.host;
2027
+ const authorizeRetry = host.authorizeRetry;
2028
+ const record = host.recovery.getSnapshot().find((item) => item.snapshot.clientSubmissionId === id);
2029
+ if (!record || record.status !== "unknown" || work.has(id) || !authorizeRetry || !await authorizeRetry(record) || disposed)
2030
+ return;
2031
+ const latest = host.recovery.getSnapshot().find((item) => item.snapshot.clientSubmissionId === id);
2032
+ if (latest?.status !== "unknown" || context.host !== host)
2033
+ return;
2034
+ return transmit(record);
2035
+ },
2036
+ dispose() {
2037
+ if (disposed)
2038
+ return;
2039
+ disposed = true;
2040
+ for (const { attempt, abort, owner } of work.values()) {
2041
+ const receipt = unknownReceipt(attempt.snapshot, error("composer_disposed", "Composer closed before admission was confirmed"));
2042
+ const unresolved = Object.freeze({
2043
+ ...attempt,
2044
+ status: "unknown",
2045
+ receipt
2046
+ });
2047
+ try {
2048
+ owner.retain(unresolved);
2049
+ recoveryFailures.delete(attempt.snapshot.clientSubmissionId);
2050
+ } catch (cause) {
2051
+ emit({
2052
+ ...state,
2053
+ submitting: false,
2054
+ error: handoffFailure(unresolved, cause)
2055
+ });
2056
+ } finally {
2057
+ abort.abort();
2058
+ }
2059
+ }
2060
+ emit({ ...state, submitting: false });
2061
+ listeners.clear();
2062
+ }
2063
+ };
2064
+ }
2065
+
2066
+ // src/components/chat/composer/useComposerSession.ts
2067
+ function useComposerSession(context) {
2068
+ const instanceId = useId();
2069
+ const [controller] = useState4(() => createComposerSessionController(context, { instanceId }));
2070
+ const snapshot = useSyncExternalStore3(controller.subscribe, controller.getSnapshot, controller.getSnapshot);
2071
+ useLayoutEffect4(() => {
2072
+ controller.activate();
2073
+ return () => controller.dispose();
2074
+ }, [controller]);
2075
+ useLayoutEffect4(() => {
2076
+ controller.update(context);
2077
+ });
2078
+ return { controller, snapshot };
2079
+ }
2080
+
2081
+ // src/components/chat/composer/PlainSemanticEditor.tsx
2082
+ import {
2083
+ forwardRef as forwardRef3,
2084
+ useId as useId2,
2085
+ useImperativeHandle as useImperativeHandle2,
2086
+ useCallback,
2087
+ useLayoutEffect as useLayoutEffect6,
2088
+ useRef as useRef4
2089
+ } from "react";
2090
+
2091
+ // src/components/chat/composer/PlainEditor.tsx
2092
+ import {
2093
+ forwardRef as forwardRef2,
2094
+ useImperativeHandle,
2095
+ useLayoutEffect as useLayoutEffect5,
2096
+ useRef as useRef3
2097
+ } from "react";
2098
+
2099
+ // src/classes/input.ts
2100
+ var textAreaWrapperClass = "textarea-wrapper";
2101
+ var textAreaCountClass = "textarea-counter";
2102
+ var textAreaCountExceededClass = "textarea-counter-exceeded";
2103
+ function getTextAreaCountClasses({ exceeded }) {
2104
+ return cn(textAreaCountClass, exceeded && textAreaCountExceededClass);
2105
+ }
2106
+
2107
+ // src/components/chat/composer/PlainEditor.tsx
2108
+ import { jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
2109
+ var PlainEditor = forwardRef2(({
2110
+ value,
2111
+ disabled,
2112
+ minRows,
2113
+ maxRows,
2114
+ generation,
2115
+ textareaProps,
2116
+ composerId,
2117
+ hasError,
2118
+ hasCompletion,
2119
+ showCompletion,
2120
+ activeIndex,
2121
+ activeDescendant,
2122
+ onChange,
2123
+ onKeyDown
2124
+ }, ref) => {
2125
+ const editorRef = useRef3(null);
2126
+ const composingRef = useRef3(false);
2127
+ const minimumRows = Math.max(1, Math.floor(minRows));
2128
+ const maximumRows = Math.max(minimumRows, Math.floor(maxRows));
2129
+ const { showCount, ...nativeProps } = textareaProps ?? {};
2130
+ delete nativeProps.size;
2131
+ delete nativeProps.status;
2132
+ delete nativeProps.variant;
2133
+ delete nativeProps.resize;
2134
+ useImperativeHandle(ref, () => ({
2135
+ focus: () => editorRef.current?.focus(),
2136
+ select: (start, end) => editorRef.current?.setSelectionRange(start, end),
2137
+ selection: (currentValue) => ({
2138
+ value: currentValue,
2139
+ selectionStart: editorRef.current?.selectionStart ?? currentValue.length,
2140
+ selectionEnd: editorRef.current?.selectionEnd ?? currentValue.length
2141
+ })
2142
+ }), []);
2143
+ useLayoutEffect5(() => {
2144
+ composingRef.current = false;
2145
+ }, [generation]);
2146
+ useLayoutEffect5(() => {
2147
+ const editor = editorRef.current;
2148
+ if (!editor)
2149
+ return;
2150
+ function measure() {
2151
+ if (!editor)
2152
+ return;
2153
+ const style = getComputedStyle(editor);
2154
+ const lineHeight = parseFloat(style.lineHeight) || 24;
2155
+ const padding = (parseFloat(style.paddingTop) || 0) + (parseFloat(style.paddingBottom) || 0);
2156
+ const borders = (parseFloat(style.borderTopWidth) || 0) + (parseFloat(style.borderBottomWidth) || 0);
2157
+ const adjustment = style.boxSizing === "border-box" ? padding + borders : 0;
2158
+ editor.style.height = "auto";
2159
+ const minimum = minimumRows * lineHeight + adjustment;
2160
+ const maximum = maximumRows * lineHeight + adjustment;
2161
+ const content = editor.scrollHeight - padding + adjustment;
2162
+ editor.style.height = `${Math.min(maximum, Math.max(minimum, content))}px`;
2163
+ editor.style.overflowY = content > maximum ? "auto" : "hidden";
2164
+ }
2165
+ measure();
2166
+ const observer = typeof ResizeObserver === "undefined" ? undefined : new ResizeObserver(measure);
2167
+ observer?.observe(editor);
2168
+ window.addEventListener("resize", measure);
2169
+ return () => {
2170
+ observer?.disconnect();
2171
+ window.removeEventListener("resize", measure);
2172
+ };
2173
+ }, [value, minimumRows, maximumRows, textareaProps?.style]);
2174
+ const control = /* @__PURE__ */ jsx4("textarea", {
2175
+ ...nativeProps,
2176
+ ref: editorRef,
2177
+ className: cn("chat-composer-editor", textareaProps?.className),
2178
+ value,
2179
+ disabled,
2180
+ rows: minimumRows,
2181
+ "aria-label": textareaProps?.["aria-label"] ?? (textareaProps?.["aria-labelledby"] ? undefined : "Message"),
2182
+ "aria-describedby": cn(textareaProps?.["aria-describedby"], hasError && `${composerId}-error`) || undefined,
2183
+ "aria-invalid": hasError || textareaProps?.status === "error" ? true : textareaProps?.["aria-invalid"],
2184
+ "aria-controls": showCompletion ? `${composerId}-completions` : undefined,
2185
+ "aria-autocomplete": hasCompletion ? "list" : undefined,
2186
+ "aria-haspopup": hasCompletion ? "listbox" : undefined,
2187
+ "aria-activedescendant": activeDescendant ?? (showCompletion && activeIndex >= 0 ? `${composerId}-option-${activeIndex}` : undefined),
2188
+ onChange: (event) => onChange(event.currentTarget.value),
2189
+ onCompositionStart: (event) => {
2190
+ composingRef.current = true;
2191
+ textareaProps?.onCompositionStart?.(event);
2192
+ },
2193
+ onCompositionEnd: (event) => {
2194
+ composingRef.current = false;
2195
+ textareaProps?.onCompositionEnd?.(event);
2196
+ },
2197
+ onKeyDown: (event) => {
2198
+ textareaProps?.onKeyDown?.(event);
2199
+ if (event.defaultPrevented || composingRef.current || event.nativeEvent.isComposing || event.keyCode === 229)
2200
+ return;
2201
+ onKeyDown(event);
2202
+ }
2203
+ });
2204
+ return showCount ? /* @__PURE__ */ jsxs4("span", {
2205
+ className: textAreaWrapperClass,
2206
+ children: [
2207
+ control,
2208
+ /* @__PURE__ */ jsxs4("span", {
2209
+ className: getTextAreaCountClasses({
2210
+ exceeded: textareaProps?.maxLength !== undefined && value.length > textareaProps.maxLength
2211
+ }),
2212
+ children: [
2213
+ value.length,
2214
+ textareaProps?.maxLength !== undefined ? ` / ${textareaProps.maxLength}` : null
2215
+ ]
2216
+ })
2217
+ ]
2218
+ }) : control;
2219
+ });
2220
+ PlainEditor.displayName = "PlainEditor";
2221
+
2222
+ // src/components/chat/composer/PlainSemanticEditor.tsx
2223
+ import { jsx as jsx5 } from "react/jsx-runtime";
2224
+ function isPlainComposerDocument(document2) {
2225
+ return !document2.command && document2.content.every((node) => node.type === "text");
2226
+ }
2227
+ var PlainSemanticEditor = forwardRef3((props, ref) => {
2228
+ const editor = useRef4(null);
2229
+ const originId = useId2();
2230
+ const latest = useRef4(props);
2231
+ const revision = useRef4(props.value.revision);
2232
+ const pendingCaret = useRef4(undefined);
2233
+ const text = props.value.document.content.map((node) => node.type === "text" ? node.text : "").join("");
2234
+ useLayoutEffect6(() => {
2235
+ latest.current = props;
2236
+ revision.current = Math.max(revision.current, props.value.revision);
2237
+ const caret = pendingCaret.current;
2238
+ if (caret && props.value.originId === originId && props.value.revision === caret.revision) {
2239
+ editor.current?.select(caret.offset, caret.offset);
2240
+ pendingCaret.current = undefined;
2241
+ } else if (caret && props.value.revision >= caret.revision) {
2242
+ pendingCaret.current = undefined;
2243
+ }
2244
+ });
2245
+ useLayoutEffect6(() => {
2246
+ latest.current.onReady?.(true);
2247
+ return () => latest.current.onReady?.(false);
2248
+ }, []);
2249
+ const change = useCallback((value, caret) => {
2250
+ revision.current = Math.max(revision.current, latest.current.value.revision) + 1;
2251
+ if (caret !== undefined)
2252
+ pendingCaret.current = { revision: revision.current, offset: caret };
2253
+ latest.current.onChange({
2254
+ document: migrateLegacyComposerDocument(value),
2255
+ revision: revision.current,
2256
+ origin: "edit",
2257
+ originId
2258
+ });
2259
+ }, [originId]);
2260
+ function selection() {
2261
+ const currentText = latest.current.value.document.content.map((node) => node.type === "text" ? node.text : "").join("");
2262
+ const range = editor.current?.selection(currentText);
2263
+ if (!range)
2264
+ return null;
2265
+ let offset = 0;
2266
+ for (const [
2267
+ nodeIndex,
2268
+ node
2269
+ ] of latest.current.value.document.content.entries()) {
2270
+ if (node.type !== "text")
2271
+ return null;
2272
+ if (range.selectionStart <= offset + node.text.length) {
2273
+ if (range.selectionEnd > offset + node.text.length)
2274
+ return null;
2275
+ return {
2276
+ nodeIndex,
2277
+ start: range.selectionStart - offset,
2278
+ end: range.selectionEnd - offset
2279
+ };
2280
+ }
2281
+ offset += node.text.length;
2282
+ }
2283
+ return latest.current.value.document.content.length ? null : { nodeIndex: 0, start: 0, end: 0 };
2284
+ }
2285
+ useImperativeHandle2(ref, () => ({
2286
+ focus: () => editor.current?.focus(),
2287
+ selection,
2288
+ insertText: (value) => {
2289
+ const source = latest.current.value.document.content.map((node) => node.type === "text" ? node.text : "").join("");
2290
+ const range = editor.current?.selection(source);
2291
+ if (!range || latest.current.disabled)
2292
+ return;
2293
+ change(source.slice(0, range.selectionStart) + value + source.slice(range.selectionEnd), range.selectionStart + value.length);
2294
+ editor.current?.focus();
2295
+ },
2296
+ insertReference: () => {
2297
+ throw new Error("References require the optional rich editor");
2298
+ },
2299
+ insertQuote: () => {
2300
+ throw new Error("Quotes require the optional rich editor");
2301
+ },
2302
+ claimCommand: () => {
2303
+ throw new Error("Claimed commands require the optional rich editor");
2304
+ },
2305
+ applyProvider: (effect) => {
2306
+ const current = latest.current;
2307
+ const range = selection();
2308
+ if (current.disabled || effect.action.type !== "insert" || effect.action.command || effect.action.content.some((node) => node.type !== "text") || current.value.revision !== effect.request.documentRevision || !range || range.nodeIndex !== effect.request.trigger.nodeIndex || range.start !== range.end || range.end !== effect.request.trigger.caret)
2309
+ return false;
2310
+ const node = current.value.document.content[range.nodeIndex];
2311
+ if (node?.type !== "text" || node.text.slice(effect.request.trigger.start, effect.request.trigger.end) !== effect.request.trigger.text)
2312
+ return false;
2313
+ const content = [...current.value.document.content];
2314
+ const insertedText = effect.action.content.map((item) => item.type === "text" ? item.text : "").join("");
2315
+ const precedingLength = current.value.document.content.slice(0, range.nodeIndex).reduce((length, item) => length + (item.type === "text" ? item.text.length : 0), 0);
2316
+ content.splice(range.nodeIndex, 1, {
2317
+ type: "text",
2318
+ text: node.text.slice(0, effect.request.trigger.start) + insertedText + node.text.slice(effect.request.trigger.end)
2319
+ });
2320
+ change(content.map((item) => item.type === "text" ? item.text : "").join(""), precedingLength + effect.request.trigger.start + insertedText.length);
2321
+ editor.current?.focus();
2322
+ return true;
2323
+ }
2324
+ }), [change]);
2325
+ return /* @__PURE__ */ jsx5(PlainEditor, {
2326
+ ref: editor,
2327
+ value: text,
2328
+ disabled: !!props.disabled,
2329
+ minRows: props.minRows ?? 1,
2330
+ maxRows: props.maxRows ?? 6,
2331
+ generation: props.instanceGeneration,
2332
+ composerId: props.id,
2333
+ hasError: !!props.invalid,
2334
+ hasCompletion: !!props.hasSuggestions,
2335
+ showCompletion: !!props.controls,
2336
+ activeIndex: -1,
2337
+ activeDescendant: props.activeDescendant,
2338
+ textareaProps: {
2339
+ "aria-label": props.label,
2340
+ "aria-describedby": props.describedBy,
2341
+ "aria-controls": props.controls,
2342
+ "aria-activedescendant": props.activeDescendant,
2343
+ onSelect: () => latest.current.onSelectionChange(selection()),
2344
+ onBlur: () => latest.current.onSelectionChange(null),
2345
+ onPaste: (event) => latest.current.onPaste?.(event),
2346
+ onDrop: (event) => latest.current.onDrop?.(event)
2347
+ },
2348
+ onChange: (value) => {
2349
+ change(value);
2350
+ const range = editor.current?.selection(value);
2351
+ latest.current.onSelectionChange(range ? {
2352
+ nodeIndex: 0,
2353
+ start: range.selectionStart,
2354
+ end: range.selectionEnd
2355
+ } : null);
2356
+ },
2357
+ onKeyDown: (event) => latest.current.onKeyDown?.(event)
2358
+ });
2359
+ });
2360
+ PlainSemanticEditor.displayName = "PlainSemanticEditor";
2361
+
2362
+ // src/components/chat/composer/PreservedDraft.tsx
2363
+ import { jsx as jsx6, jsxs as jsxs5 } from "react/jsx-runtime";
2364
+ function PreservedDraft({
2365
+ input,
2366
+ reason,
2367
+ state = "error"
2368
+ }) {
2369
+ const document2 = readComposerDocument(input);
2370
+ let json;
2371
+ let exportError;
2372
+ try {
2373
+ json = JSON.stringify(snapshotComposerJson(input), null, 2);
2374
+ } catch (cause) {
2375
+ exportError = cause instanceof Error ? cause.message : "Unsupported data";
2376
+ }
2377
+ return /* @__PURE__ */ jsxs5("section", {
2378
+ className: "chat-composer-status",
2379
+ "data-state": state,
2380
+ "aria-label": "Preserved draft",
2381
+ children: [
2382
+ /* @__PURE__ */ jsxs5("p", {
2383
+ role: state === "error" ? "alert" : "status",
2384
+ children: [
2385
+ reason,
2386
+ " Your draft is preserved."
2387
+ ]
2388
+ }),
2389
+ /* @__PURE__ */ jsx6("pre", {
2390
+ children: document2.status === "compatible" ? exportComposerText(document2.value) : json ?? "The application retains the original incompatible input."
2391
+ }),
2392
+ json ? /* @__PURE__ */ jsx6("a", {
2393
+ download: "composer-draft.json",
2394
+ href: `data:application/json;charset=utf-8,${encodeURIComponent(json)}`,
2395
+ children: "Export preserved draft"
2396
+ }) : null,
2397
+ exportError ? /* @__PURE__ */ jsxs5("p", {
2398
+ children: [
2399
+ "JSON export unavailable: ",
2400
+ exportError,
2401
+ ". The application retains the original input."
2402
+ ]
2403
+ }) : null
2404
+ ]
2405
+ });
2406
+ }
2407
+
2408
+ // src/components/chat/composer/DraftLifecycle.tsx
2409
+ import { useId as useId3 } from "react";
2410
+
2411
+ // src/components/chat/composer/useComposerDraft.ts
2412
+ import { useLayoutEffect as useLayoutEffect7, useState as useState5, useSyncExternalStore as useSyncExternalStore4 } from "react";
2413
+
2414
+ // src/components/chat/composer/drafts.ts
2415
+ function error2(cause, code) {
2416
+ return Object.freeze({
2417
+ code,
2418
+ message: cause instanceof Error ? cause.message : "Draft storage failed."
2419
+ });
2420
+ }
2421
+ var writers = new WeakMap;
2422
+ function storageKey(draft) {
2423
+ return JSON.stringify([
2424
+ draft.scope.contextKey,
2425
+ draft.scope.conversationId,
2426
+ draft.draftKey
2427
+ ]);
2428
+ }
2429
+ function enqueueSave(adapter, draft) {
2430
+ let lanes = writers.get(adapter);
2431
+ if (!lanes)
2432
+ writers.set(adapter, lanes = new Map);
2433
+ const key = storageKey(draft);
2434
+ let lane = lanes.get(key);
2435
+ if (!lane)
2436
+ lanes.set(key, lane = { waiters: new Set });
2437
+ const currentLane = lane;
2438
+ const currentLanes = lanes;
2439
+ function start(job) {
2440
+ currentLane.active = job;
2441
+ Promise.resolve().then(job.run).then(() => job.resolve(Object.freeze({ outcome: "saved", draft: job.draft })), (cause) => job.resolve(Object.freeze({
2442
+ outcome: "error",
2443
+ draft: job.draft,
2444
+ error: error2(cause, "draft_save_failed")
2445
+ }))).then(() => {
2446
+ currentLane.active = undefined;
2447
+ const next = currentLane.queued;
2448
+ currentLane.queued = undefined;
2449
+ if (next)
2450
+ start(next);
2451
+ else {
2452
+ currentLanes.delete(key);
2453
+ for (const notify of [...currentLane.waiters])
2454
+ notify();
2455
+ currentLane.waiters.clear();
2456
+ }
2457
+ });
2458
+ }
2459
+ return new Promise((resolve) => {
2460
+ const abort = new AbortController;
2461
+ const save = adapter.save;
2462
+ const job = {
2463
+ draft,
2464
+ abort,
2465
+ run: () => save.call(adapter, draft, abort.signal),
2466
+ resolve
2467
+ };
2468
+ if (!currentLane.active)
2469
+ start(job);
2470
+ else {
2471
+ currentLane.queued?.abort.abort();
2472
+ currentLane.queued?.resolve(Object.freeze({
2473
+ outcome: "superseded",
2474
+ draft: currentLane.queued.draft
2475
+ }));
2476
+ currentLane.queued = job;
2477
+ }
2478
+ });
2479
+ }
2480
+ function waitForSaves(adapter, draft, signal) {
2481
+ const lane = writers.get(adapter)?.get(storageKey(draft));
2482
+ if (!lane)
2483
+ return Promise.resolve();
2484
+ return new Promise((resolve, reject) => {
2485
+ const finish = () => {
2486
+ signal.removeEventListener("abort", cancel);
2487
+ lane.waiters.delete(finish);
2488
+ resolve();
2489
+ };
2490
+ const cancel = () => {
2491
+ lane.waiters.delete(finish);
2492
+ reject(new DOMException("Draft load aborted", "AbortError"));
2493
+ };
2494
+ if (signal.aborted)
2495
+ cancel();
2496
+ else {
2497
+ lane.waiters.add(finish);
2498
+ signal.addEventListener("abort", cancel, { once: true });
2499
+ }
2500
+ });
2501
+ }
2502
+ function contextSnapshot(props) {
2503
+ if (!Number.isSafeInteger(props.instanceGeneration) || props.instanceGeneration < 0)
2504
+ throw new TypeError("Draft instanceGeneration must be a nonnegative safe integer");
2505
+ const result = readComposerDraft({
2506
+ draftVersion: 1,
2507
+ scope: props.scope,
2508
+ draftKey: props.draftKey,
2509
+ revision: props.revision,
2510
+ document: props.document,
2511
+ attachments: props.attachments ?? []
2512
+ }, { scope: props.scope, draftKey: props.draftKey });
2513
+ if (result.status === "incompatible")
2514
+ throw new TypeError(result.reason);
2515
+ return {
2516
+ props: Object.freeze({
2517
+ ...props,
2518
+ scope: result.value.scope,
2519
+ document: result.value.document,
2520
+ attachments: result.value.attachments
2521
+ }),
2522
+ draft: result.value,
2523
+ identity: JSON.stringify([
2524
+ storageKey(result.value),
2525
+ props.instanceGeneration
2526
+ ]),
2527
+ fingerprint: JSON.stringify(result.value),
2528
+ originId: props.originId
2529
+ };
2530
+ }
2531
+
2532
+ class DraftController {
2533
+ current;
2534
+ active = false;
2535
+ ownerGeneration = 0;
2536
+ editGeneration = 0;
2537
+ loadGeneration = 0;
2538
+ saveGeneration = 0;
2539
+ loadAbort;
2540
+ safety = "unloaded";
2541
+ status = "idle";
2542
+ saving = false;
2543
+ restorePending = false;
2544
+ loaded;
2545
+ incompatible;
2546
+ failure;
2547
+ failureOperation;
2548
+ lastSavedRevision;
2549
+ listeners = new Set;
2550
+ snapshot;
2551
+ constructor(context) {
2552
+ this.current = contextSnapshot(context);
2553
+ this.snapshot = this.createSnapshot();
2554
+ }
2555
+ getSnapshot = () => this.snapshot;
2556
+ subscribe = (listener) => {
2557
+ this.listeners.add(listener);
2558
+ return () => this.listeners.delete(listener);
2559
+ };
2560
+ activate() {
2561
+ if (this.active)
2562
+ return;
2563
+ this.active = true;
2564
+ this.ownerGeneration++;
2565
+ this.reload();
2566
+ }
2567
+ update(context) {
2568
+ const next = contextSnapshot(context);
2569
+ const identityChanged = next.identity !== this.current.identity || context.adapter !== this.current.props.adapter;
2570
+ const edited = next.fingerprint !== this.current.fingerprint || next.originId !== this.current.originId;
2571
+ this.current = next;
2572
+ if (identityChanged) {
2573
+ this.ownerGeneration++;
2574
+ this.loadGeneration++;
2575
+ this.loadAbort?.abort();
2576
+ this.loadAbort = undefined;
2577
+ this.safety = "unloaded";
2578
+ this.status = "idle";
2579
+ this.saving = false;
2580
+ this.restorePending = false;
2581
+ this.loaded = undefined;
2582
+ this.incompatible = undefined;
2583
+ this.failure = undefined;
2584
+ this.failureOperation = undefined;
2585
+ this.lastSavedRevision = undefined;
2586
+ this.editGeneration++;
2587
+ if (this.active)
2588
+ this.reload();
2589
+ else
2590
+ this.publish();
2591
+ } else if (edited) {
2592
+ this.editGeneration++;
2593
+ const restoring = this.restorePending;
2594
+ this.restorePending = false;
2595
+ if (this.failureOperation === "save") {
2596
+ this.failure = undefined;
2597
+ this.failureOperation = undefined;
2598
+ if (this.safety === "compatible" || this.safety === "allowed")
2599
+ this.status = "ready";
2600
+ }
2601
+ if (restoring || this.failureOperation === undefined)
2602
+ this.publish();
2603
+ }
2604
+ }
2605
+ async reload() {
2606
+ if (!this.active)
2607
+ return;
2608
+ this.loadAbort?.abort();
2609
+ const abort = new AbortController;
2610
+ this.loadAbort = abort;
2611
+ const owner = this.ownerGeneration;
2612
+ const load = ++this.loadGeneration;
2613
+ const edit = this.editGeneration;
2614
+ const context = this.current;
2615
+ const adapter = context.props.adapter;
2616
+ const read = adapter.load;
2617
+ const isCurrent = () => this.active && this.ownerGeneration === owner && this.loadGeneration === load && !abort.signal.aborted;
2618
+ this.safety = "unloaded";
2619
+ this.status = "loading";
2620
+ this.restorePending = false;
2621
+ this.failure = undefined;
2622
+ this.failureOperation = undefined;
2623
+ this.publish();
2624
+ try {
2625
+ await waitForSaves(adapter, context.draft, abort.signal);
2626
+ if (!isCurrent())
2627
+ return;
2628
+ const input = await read.call(adapter, {
2629
+ scope: context.draft.scope,
2630
+ draftKey: context.draft.draftKey,
2631
+ signal: abort.signal
2632
+ });
2633
+ if (!isCurrent())
2634
+ return;
2635
+ this.loadAbort = undefined;
2636
+ if (input === null || input === undefined) {
2637
+ this.safety = "compatible";
2638
+ this.status = "ready";
2639
+ this.incompatible = undefined;
2640
+ this.loaded = undefined;
2641
+ this.publish();
2642
+ return;
2643
+ }
2644
+ const result = readComposerDraft(input, {
2645
+ scope: context.draft.scope,
2646
+ draftKey: context.draft.draftKey
2647
+ });
2648
+ const wrongScope = result.status === "compatible" && (result.value.scope.contextKey !== context.draft.scope.contextKey || result.value.scope.conversationId !== context.draft.scope.conversationId || result.value.draftKey !== context.draft.draftKey);
2649
+ if (result.status === "incompatible" || wrongScope) {
2650
+ const reason = result.status === "incompatible" ? result.reason : "Stored draft belongs to a different scope or draft key.";
2651
+ this.safety = "incompatible";
2652
+ this.status = "incompatible";
2653
+ this.incompatible = Object.freeze({
2654
+ input,
2655
+ reason,
2656
+ scope: context.draft.scope,
2657
+ draftKey: context.draft.draftKey,
2658
+ instanceGeneration: context.props.instanceGeneration
2659
+ });
2660
+ this.publish();
2661
+ this.failureOperation = "incompatible";
2662
+ this.current.props.onIncompatible?.(input, reason);
2663
+ if (!isCurrent())
2664
+ return;
2665
+ this.failureOperation = undefined;
2666
+ return;
2667
+ }
2668
+ this.safety = "compatible";
2669
+ this.status = "ready";
2670
+ this.incompatible = undefined;
2671
+ const apply = this.editGeneration === edit && !!this.current.props.onRestore;
2672
+ this.loaded = Object.freeze({
2673
+ draft: result.value,
2674
+ migrated: result.migrated,
2675
+ applied: apply
2676
+ });
2677
+ this.restorePending = apply;
2678
+ if (apply) {
2679
+ this.failureOperation = "restore";
2680
+ this.current.props.onRestore?.(result.value);
2681
+ if (!isCurrent())
2682
+ return;
2683
+ this.failureOperation = undefined;
2684
+ }
2685
+ this.publish();
2686
+ } catch (cause) {
2687
+ if (!isCurrent())
2688
+ return;
2689
+ this.loadAbort = undefined;
2690
+ this.safety = this.incompatible ? "incompatible" : "error";
2691
+ this.status = this.incompatible ? "incompatible" : "error";
2692
+ this.restorePending = false;
2693
+ this.failure = error2(cause, "draft_load_failed");
2694
+ this.failureOperation ??= "load";
2695
+ this.publish();
2696
+ }
2697
+ }
2698
+ async save() {
2699
+ const blocked = !this.active ? "inactive" : this.safety === "unloaded" ? "loading" : this.safety === "incompatible" ? "incompatible" : this.safety === "error" ? "load_error" : this.restorePending ? "restoring" : undefined;
2700
+ if (blocked)
2701
+ return Object.freeze({ outcome: "blocked", reason: blocked });
2702
+ const context = this.current;
2703
+ const owner = this.ownerGeneration;
2704
+ const save = ++this.saveGeneration;
2705
+ this.saving = true;
2706
+ this.failure = undefined;
2707
+ this.failureOperation = undefined;
2708
+ this.status = "ready";
2709
+ this.publish();
2710
+ const result = await enqueueSave(context.props.adapter, context.draft);
2711
+ if (this.active && this.ownerGeneration === owner && this.saveGeneration === save) {
2712
+ this.saving = false;
2713
+ if (result.outcome === "saved")
2714
+ this.lastSavedRevision = result.draft.revision;
2715
+ else if (result.outcome === "error") {
2716
+ this.failure = result.error;
2717
+ this.failureOperation = "save";
2718
+ if (this.snapshot.status !== "loading")
2719
+ this.status = "error";
2720
+ }
2721
+ this.publish();
2722
+ }
2723
+ return result;
2724
+ }
2725
+ allowOverwrite(incompatible) {
2726
+ if (!this.active || this.incompatible !== incompatible || this.safety !== "incompatible")
2727
+ return false;
2728
+ this.safety = "allowed";
2729
+ this.status = "ready";
2730
+ this.failure = undefined;
2731
+ this.failureOperation = undefined;
2732
+ this.publish();
2733
+ return true;
2734
+ }
2735
+ dispose() {
2736
+ this.active = false;
2737
+ this.ownerGeneration++;
2738
+ this.loadGeneration++;
2739
+ this.loadAbort?.abort();
2740
+ this.loadAbort = undefined;
2741
+ this.safety = "unloaded";
2742
+ this.status = "idle";
2743
+ this.saving = false;
2744
+ this.restorePending = false;
2745
+ this.snapshot = this.createSnapshot();
2746
+ this.listeners.clear();
2747
+ }
2748
+ createSnapshot() {
2749
+ return Object.freeze({
2750
+ status: this.status,
2751
+ scope: this.current.draft.scope,
2752
+ draftKey: this.current.draft.draftKey,
2753
+ instanceGeneration: this.current.props.instanceGeneration,
2754
+ saving: this.saving,
2755
+ restorePending: this.restorePending,
2756
+ overwriteAllowed: this.safety === "allowed",
2757
+ loaded: this.loaded,
2758
+ incompatible: this.incompatible,
2759
+ error: this.failure,
2760
+ errorOperation: this.failureOperation,
2761
+ lastSavedRevision: this.lastSavedRevision
2762
+ });
2763
+ }
2764
+ publish() {
2765
+ this.snapshot = this.createSnapshot();
2766
+ for (const listener of [...this.listeners])
2767
+ listener();
2768
+ }
2769
+ }
2770
+ function createComposerDraftController(context) {
2771
+ return new DraftController(context);
2772
+ }
2773
+
2774
+ // src/components/chat/composer/useComposerDraft.ts
2775
+ function useComposerDraft(context) {
2776
+ const [controller] = useState5(() => createComposerDraftController(context));
2777
+ const snapshot = useSyncExternalStore4(controller.subscribe, controller.getSnapshot, controller.getSnapshot);
2778
+ useLayoutEffect7(() => {
2779
+ controller.activate();
2780
+ return () => controller.dispose();
2781
+ }, [controller]);
2782
+ useLayoutEffect7(() => {
2783
+ controller.update(context);
2784
+ });
2785
+ return { controller, snapshot };
2786
+ }
2787
+
2788
+ // src/components/chat/composer/DraftLifecycle.tsx
2789
+ import { jsx as jsx7, jsxs as jsxs6, Fragment as Fragment4 } from "react/jsx-runtime";
2790
+ function DraftLifecycle({
2791
+ adapter,
2792
+ scope,
2793
+ draftKey,
2794
+ generation,
2795
+ value,
2796
+ attachments,
2797
+ onDocumentChange,
2798
+ disabled,
2799
+ compact = false,
2800
+ children
2801
+ }) {
2802
+ const originId = `${useId3()}-draft`;
2803
+ function restore(draft) {
2804
+ attachments.restore(draft.attachments);
2805
+ onDocumentChange({
2806
+ document: draft.document,
2807
+ revision: Math.max(value.revision, draft.revision) + 1,
2808
+ origin: "restore",
2809
+ originId
2810
+ });
2811
+ }
2812
+ const { controller, snapshot } = useComposerDraft({
2813
+ adapter,
2814
+ scope,
2815
+ draftKey,
2816
+ instanceGeneration: generation,
2817
+ revision: value.revision,
2818
+ originId: value.originId,
2819
+ document: value.document,
2820
+ attachments: attachments.draftSnapshot(),
2821
+ onRestore: restore
2822
+ });
2823
+ const blocked = disabled || snapshot.saving || snapshot.status === "idle" || snapshot.status === "loading" || snapshot.restorePending || snapshot.status === "incompatible" && !snapshot.overwriteAllowed || snapshot.status === "error" && snapshot.errorOperation !== "save";
2824
+ const status = snapshot.status === "loading" ? "Loading stored draft…" : snapshot.saving ? "Saving draft…" : snapshot.lastSavedRevision === value.revision ? "Draft saved by host storage." : snapshot.loaded?.applied ? "Stored draft restored." : "Draft storage is provided by the host.";
2825
+ const feedback = /* @__PURE__ */ jsxs6(Fragment4, {
2826
+ children: [
2827
+ /* @__PURE__ */ jsx7("div", {
2828
+ role: "status",
2829
+ className: compact ? "sr-only" : undefined,
2830
+ children: status
2831
+ }),
2832
+ snapshot.error ? /* @__PURE__ */ jsx7("p", {
2833
+ role: "alert",
2834
+ children: snapshot.error.message
2835
+ }) : null,
2836
+ snapshot.incompatible ? /* @__PURE__ */ jsxs6(Fragment4, {
2837
+ children: [
2838
+ /* @__PURE__ */ jsx7(PreservedDraft, {
2839
+ input: snapshot.incompatible.input,
2840
+ reason: snapshot.incompatible.reason
2841
+ }),
2842
+ !snapshot.overwriteAllowed ? /* @__PURE__ */ jsx7("button", {
2843
+ type: "button",
2844
+ disabled,
2845
+ onClick: () => {
2846
+ if (snapshot.incompatible)
2847
+ controller.allowOverwrite(snapshot.incompatible);
2848
+ },
2849
+ children: "Allow replacing this stored draft"
2850
+ }) : null
2851
+ ]
2852
+ }) : null,
2853
+ snapshot.loaded && !snapshot.loaded.applied ? /* @__PURE__ */ jsxs6(Fragment4, {
2854
+ children: [
2855
+ /* @__PURE__ */ jsx7(PreservedDraft, {
2856
+ input: snapshot.loaded.draft,
2857
+ reason: "A stored draft arrived after editing. Your current draft is preserved.",
2858
+ state: "pending"
2859
+ }),
2860
+ /* @__PURE__ */ jsx7("button", {
2861
+ type: "button",
2862
+ disabled,
2863
+ onClick: () => {
2864
+ if (snapshot.loaded)
2865
+ restore(snapshot.loaded.draft);
2866
+ },
2867
+ children: "Restore stored draft"
2868
+ })
2869
+ ]
2870
+ }) : null
2871
+ ]
2872
+ });
2873
+ const actions = compact ? /* @__PURE__ */ jsxs6(Fragment4, {
2874
+ children: [
2875
+ /* @__PURE__ */ jsxs6("button", {
2876
+ type: "button",
2877
+ className: "popover-menu-item",
2878
+ title: status,
2879
+ disabled: blocked,
2880
+ onClick: (event) => {
2881
+ controller.save();
2882
+ event.currentTarget.closest("[popover]")?.hidePopover?.();
2883
+ },
2884
+ children: [
2885
+ /* @__PURE__ */ jsx7("svg", {
2886
+ width: "18",
2887
+ height: "18",
2888
+ viewBox: "0 0 24 24",
2889
+ fill: "none",
2890
+ stroke: "currentColor",
2891
+ strokeWidth: "2",
2892
+ strokeLinecap: "round",
2893
+ strokeLinejoin: "round",
2894
+ "aria-hidden": "true",
2895
+ focusable: "false",
2896
+ children: /* @__PURE__ */ jsx7("path", {
2897
+ d: "M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12l4 4v12a2 2 0 0 1-2 2ZM7 3v6h10V3M7 21v-8h10v8"
2898
+ })
2899
+ }),
2900
+ /* @__PURE__ */ jsx7("span", {
2901
+ children: "Save draft"
2902
+ })
2903
+ ]
2904
+ }),
2905
+ /* @__PURE__ */ jsxs6("button", {
2906
+ type: "button",
2907
+ className: "popover-menu-item",
2908
+ title: "Reload stored draft",
2909
+ disabled: disabled || snapshot.status === "loading" || snapshot.saving,
2910
+ onClick: (event) => {
2911
+ controller.reload();
2912
+ event.currentTarget.closest("[popover]")?.hidePopover?.();
2913
+ },
2914
+ children: [
2915
+ /* @__PURE__ */ jsx7("svg", {
2916
+ width: "18",
2917
+ height: "18",
2918
+ viewBox: "0 0 24 24",
2919
+ fill: "none",
2920
+ stroke: "currentColor",
2921
+ strokeWidth: "2",
2922
+ strokeLinecap: "round",
2923
+ strokeLinejoin: "round",
2924
+ "aria-hidden": "true",
2925
+ focusable: "false",
2926
+ children: /* @__PURE__ */ jsx7("path", {
2927
+ d: "M3 11a9 9 0 1 1 2.6 7.4M3 4v7h7"
2928
+ })
2929
+ }),
2930
+ /* @__PURE__ */ jsx7("span", {
2931
+ children: "Reload stored draft"
2932
+ })
2933
+ ]
2934
+ })
2935
+ ]
2936
+ }) : /* @__PURE__ */ jsxs6(Fragment4, {
2937
+ children: [
2938
+ /* @__PURE__ */ jsx7("button", {
2939
+ type: "button",
2940
+ disabled: blocked,
2941
+ onClick: () => void controller.save(),
2942
+ children: "Save draft"
2943
+ }),
2944
+ /* @__PURE__ */ jsx7("button", {
2945
+ type: "button",
2946
+ disabled: disabled || snapshot.status === "loading" || snapshot.saving,
2947
+ onClick: () => void controller.reload(),
2948
+ children: "Reload stored draft"
2949
+ })
2950
+ ]
2951
+ });
2952
+ return compact ? children(feedback, actions) : children(/* @__PURE__ */ jsxs6("div", {
2953
+ className: "chat-composer-status",
2954
+ "aria-label": "Draft storage",
2955
+ children: [
2956
+ feedback,
2957
+ actions
2958
+ ]
2959
+ }));
2960
+ }
2961
+
2962
+ // src/components/chat/composer/SemanticComposer.tsx
2963
+ import { jsx as jsx8, jsxs as jsxs7, Fragment as Fragment5 } from "react/jsx-runtime";
2964
+ var SemanticComposer = forwardRef4(({
2965
+ Editor,
2966
+ structured,
2967
+ value,
2968
+ onDocumentChange,
2969
+ scope,
2970
+ draftKey,
2971
+ host,
2972
+ runtime = { status: "idle" },
2973
+ policy,
2974
+ options,
2975
+ draftAdapter,
2976
+ attachmentOptions,
2977
+ providers = [],
2978
+ onProviderInvoke,
2979
+ disabled = false,
2980
+ busy = false,
2981
+ canSubmit = true,
2982
+ allowAttachmentOnly = false,
2983
+ compact = false,
2984
+ addMenu,
2985
+ onStop,
2986
+ label = "Message",
2987
+ attachLabel = "Attach files",
2988
+ stopLabel = "Stop",
2989
+ minRows = 1,
2990
+ maxRows = 6,
2991
+ error,
2992
+ children,
2993
+ className,
2994
+ onPaste,
2995
+ onDrop,
2996
+ onPasteCapture,
2997
+ onDropCapture,
2998
+ onKeyDown,
2999
+ onKeyDownCapture,
3000
+ ...rootProps
3001
+ }, forwardedRef) => {
3002
+ const id = useId4();
3003
+ const editor = useRef5(null);
3004
+ const picker = useRef5(null);
3005
+ const [readiness, setReadiness] = useState6({ generation: 0, ready: false });
3006
+ const [editorFailure, setEditorFailure] = useState6();
3007
+ const [localFailure, setLocalFailure] = useState6();
3008
+ const [selection, setSelection] = useState6(null);
3009
+ const observed = useRef5({ scope: { ...scope }, draftKey, generation: 0 });
3010
+ const changedScope = !sameComposerScope(observed.current.scope, scope) || observed.current.draftKey !== draftKey;
3011
+ const generation = observed.current.generation + (changedScope ? 1 : 0);
3012
+ const alive = useRef5(false);
3013
+ useLayoutEffect8(() => {
3014
+ alive.current = true;
3015
+ return () => {
3016
+ alive.current = false;
3017
+ };
3018
+ }, []);
3019
+ useLayoutEffect8(() => {
3020
+ if (changedScope)
3021
+ observed.current = { scope: { ...scope }, draftKey, generation };
3022
+ }, [
3023
+ scope,
3024
+ scope.contextKey,
3025
+ scope.conversationId,
3026
+ draftKey,
3027
+ changedScope,
3028
+ generation
3029
+ ]);
3030
+ const ready = readiness.generation === generation && readiness.ready;
3031
+ const editorError = editorFailure?.generation === generation ? editorFailure.error : undefined;
3032
+ const localError = localFailure?.generation === generation ? localFailure.message : undefined;
3033
+ function setLocalError(message, origin = generation) {
3034
+ if (alive.current && observed.current.generation === origin)
3035
+ setLocalFailure(message ? { generation: origin, message } : undefined);
3036
+ }
3037
+ const read = readComposerDocument(value.document);
3038
+ const document2 = read.status === "compatible" ? read.value : migrateLegacyComposerDocument("");
3039
+ const compatible = read.status === "compatible" && (structured || isPlainComposerDocument(document2));
3040
+ const editAvailable = compatible && !editorError;
3041
+ const attachments = useComposerAttachments({
3042
+ scope,
3043
+ ...attachmentOptions,
3044
+ draftKey,
3045
+ prepare: attachmentOptions?.prepare ?? (() => {
3046
+ throw new Error("Attachment preparation is unavailable");
3047
+ })
3048
+ });
3049
+ const attachmentsCurrent = sameComposerScope(attachments.scope, scope) && attachments.draftKey === draftKey;
3050
+ const pendingFiles = attachmentsCurrent && attachments.entries.some((entry) => entry.state.status !== "ready");
3051
+ const sendable = pendingFiles || !attachmentsCurrent ? [] : attachments.controller.sendableSnapshot();
3052
+ const context = {
3053
+ scope,
3054
+ draftKey,
3055
+ document: document2,
3056
+ revision: value.revision,
3057
+ instanceGeneration: generation,
3058
+ runtime,
3059
+ policy,
3060
+ options,
3061
+ host,
3062
+ attachments: sendable,
3063
+ attachmentsPending: pendingFiles,
3064
+ disabled: disabled || !editAvailable || !ready,
3065
+ busy,
3066
+ canSubmit,
3067
+ allowAttachmentOnly,
3068
+ onAccepted: () => {
3069
+ onDocumentChange({
3070
+ document: migrateLegacyComposerDocument(""),
3071
+ revision: value.revision + 1,
3072
+ origin: "clear",
3073
+ originId: id
3074
+ });
3075
+ setSelection(null);
3076
+ },
3077
+ onAcceptedAttachments: (accepted) => {
3078
+ for (const entry of accepted)
3079
+ attachments.controller.remove(entry.entryId);
3080
+ }
3081
+ };
3082
+ const session = useComposerSession(context);
3083
+ const action = composerActionEligibility(context);
3084
+ const recovery = useSyncExternalStore5(host.recovery.subscribe, host.recovery.getSnapshot, host.recovery.getSnapshot);
3085
+ const candidateDisabledReason = useCallback2((candidate) => {
3086
+ if (!structured && candidate.action.type === "insert" && (candidate.action.command || candidate.action.content.some((node) => node.type !== "text")))
3087
+ return "Requires the rich editor";
3088
+ if (candidate.action.type === "invoke" && !onProviderInvoke)
3089
+ return "Host action unavailable";
3090
+ return;
3091
+ }, [structured, onProviderInvoke]);
3092
+ const providerContext = {
3093
+ document: document2,
3094
+ documentRevision: value.revision,
3095
+ scope,
3096
+ instanceGeneration: generation,
3097
+ selection: changedScope ? null : selection,
3098
+ providers: disabled || !editAvailable ? [] : providers,
3099
+ candidateDisabledReason
3100
+ };
3101
+ const completion = useComposerProviders(providerContext);
3102
+ const popup = completion.snapshot.status !== "idle";
3103
+ const candidates = completion.snapshot.items.map((item) => {
3104
+ const provider = providers.find((entry) => entry.providerId === item.providerId);
3105
+ const reason = item.candidate.disabledReason ?? candidateDisabledReason(item.candidate);
3106
+ return {
3107
+ id: item.id,
3108
+ label: item.candidate.label,
3109
+ icon: provider?.icon,
3110
+ sourceLabel: provider?.sourceLabel,
3111
+ description: reason ?? item.candidate.description,
3112
+ disabled: reason !== undefined,
3113
+ group: item.candidate.group ?? completion.snapshot.groups.find((group) => group.providerId === item.providerId)?.label
3114
+ };
3115
+ });
3116
+ const active = candidates.find((item) => item.id === completion.snapshot.activeId && !item.disabled);
3117
+ const showCompletion = popup && candidates.length > 0;
3118
+ const visibleError = error ?? localError ?? session.snapshot.error?.message;
3119
+ const hasError = visibleError !== undefined && visibleError !== null && visibleError !== false;
3120
+ useImperativeHandle3(forwardedRef, () => ({
3121
+ focus: () => editor.current?.focus(),
3122
+ selection: () => editor.current?.selection() ?? null,
3123
+ insertReference: (node) => {
3124
+ if (!editor.current)
3125
+ throw new Error("Editor unavailable; draft preserved");
3126
+ editor.current.insertReference(node);
3127
+ },
3128
+ insertQuote: (node) => {
3129
+ if (!editor.current)
3130
+ throw new Error("Editor unavailable; draft preserved");
3131
+ editor.current.insertQuote(node);
3132
+ },
3133
+ claimCommand: (command, source) => {
3134
+ if (!editor.current)
3135
+ throw new Error("Editor unavailable; draft preserved");
3136
+ editor.current.claimCommand(command, source);
3137
+ },
3138
+ insertText: (text) => {
3139
+ if (!editor.current)
3140
+ throw new Error("Editor unavailable; draft preserved");
3141
+ editor.current.insertText(text);
3142
+ },
3143
+ applyProvider: (effect) => editor.current?.applyProvider(effect) ?? false
3144
+ }), []);
3145
+ function intake(files, source) {
3146
+ if (!disabled && runtime.status !== "read_only" && attachmentOptions)
3147
+ attachments.controller.intake(files, source);
3148
+ }
3149
+ async function submit() {
3150
+ try {
3151
+ await session.controller.submit();
3152
+ } catch (cause) {
3153
+ setLocalError(cause instanceof Error ? cause.message : "Unable to retain submission recovery");
3154
+ }
3155
+ }
3156
+ function selectCandidate(item) {
3157
+ if (item.disabled)
3158
+ return;
3159
+ const effect = completion.controller.select(item.id, {
3160
+ ...providerContext,
3161
+ selection: editor.current?.selection() ?? null
3162
+ });
3163
+ if (!effect)
3164
+ return;
3165
+ if (effect.action.type === "insert") {
3166
+ if (!editor.current?.applyProvider(effect))
3167
+ setLocalError("The draft or selection changed. Choose a suggestion again.");
3168
+ } else if (effect.action.type === "invoke" && onProviderInvoke) {
3169
+ const origin = generation;
3170
+ Promise.resolve().then(() => onProviderInvoke(effect)).catch((cause) => {
3171
+ setLocalError(cause instanceof Error ? cause.message : "Host action failed", origin);
3172
+ });
3173
+ }
3174
+ editor.current?.focus();
3175
+ }
3176
+ const compactImages = compact && attachmentsCurrent && attachments.entries.length > 0 && attachments.entries.every((entry) => entry.state.status === "ready" && entry.metadata.mediaType.startsWith("image/") && !!attachments.controller.previewUrl(entry.entryId));
3177
+ return /* @__PURE__ */ jsx8(ComposerShell, {
3178
+ ...rootProps,
3179
+ className,
3180
+ composerId: id,
3181
+ compact,
3182
+ addMenu,
3183
+ entries: (attachmentsCurrent ? attachments.entries : []).map((entry) => ({
3184
+ id: entry.entryId,
3185
+ name: entry.metadata.name,
3186
+ previewUrl: attachments.controller.previewUrl(entry.entryId),
3187
+ state: entry.state.status === "preparing" ? "validating" : entry.state.status,
3188
+ status: entry.state.status === "error" ? entry.state.error.message : entry.state.status === "reattach" ? "Select this file again to restore it" : entry.state.status === "ready" ? compactImages ? undefined : "Ready" : entry.state.status,
3189
+ ...entry.state.status === "preparing" || entry.state.status === "uploading" ? {
3190
+ progress: entry.state.progress,
3191
+ cancel: () => attachments.controller.cancel(entry.entryId)
3192
+ } : {},
3193
+ ...(entry.state.status === "error" || entry.state.status === "cancelled") && attachments.controller.file(entry.entryId) ? {
3194
+ retry: () => {
3195
+ attachments.controller.retry(entry.entryId);
3196
+ }
3197
+ } : {}
3198
+ })),
3199
+ removeAttachment: (entryId) => attachments.controller.remove(String(entryId)),
3200
+ addAttachments: intake,
3201
+ onAttachmentsChange: attachmentOptions ? () => {} : undefined,
3202
+ intakeEvents: false,
3203
+ onKeyDownCapture: (event) => {
3204
+ onKeyDownCapture?.(event);
3205
+ onKeyDown?.(event);
3206
+ },
3207
+ onPasteCapture: (event) => {
3208
+ onPasteCapture?.(event);
3209
+ onPaste?.(event);
3210
+ if (!event.defaultPrevented)
3211
+ intake(Array.from(event.clipboardData.files ?? []), "paste");
3212
+ },
3213
+ onDropCapture: (event) => {
3214
+ onDropCapture?.(event);
3215
+ onDrop?.(event);
3216
+ if (!event.defaultPrevented && attachmentOptions && event.dataTransfer.files.length) {
3217
+ event.preventDefault();
3218
+ intake(Array.from(event.dataTransfer.files), "drop");
3219
+ }
3220
+ },
3221
+ onDragOver: (event) => {
3222
+ rootProps.onDragOver?.(event);
3223
+ if (!event.defaultPrevented && attachmentOptions && event.dataTransfer.types.includes("Files"))
3224
+ event.preventDefault();
3225
+ },
3226
+ pickerRef: picker,
3227
+ accept: attachmentOptions?.policy?.accept,
3228
+ multiple: true,
3229
+ disabled: disabled || runtime.status === "read_only",
3230
+ busy,
3231
+ submitting: session.snapshot.submitting,
3232
+ generating: runtime.status === "running",
3233
+ eligible: action.allowed && !session.snapshot.submitting,
3234
+ candidates,
3235
+ active,
3236
+ showCompletion,
3237
+ selectCompletion: selectCandidate,
3238
+ dismissCompletion: () => completion.controller.dismiss(),
3239
+ completionHeader: completion.snapshot.breadcrumbs.length ? /* @__PURE__ */ jsxs7("nav", {
3240
+ "aria-label": "Suggestion folders",
3241
+ className: "chat-composer-breadcrumb",
3242
+ children: [
3243
+ /* @__PURE__ */ jsx8("button", {
3244
+ type: "button",
3245
+ onMouseDown: (event) => event.preventDefault(),
3246
+ onClick: () => completion.controller.back(0),
3247
+ children: "All results"
3248
+ }),
3249
+ completion.snapshot.breadcrumbs.map((crumb, index) => /* @__PURE__ */ jsx8("button", {
3250
+ type: "button",
3251
+ onMouseDown: (event) => event.preventDefault(),
3252
+ onClick: () => completion.controller.back(index + 1),
3253
+ children: crumb.label
3254
+ }, crumb.refId)),
3255
+ /* @__PURE__ */ jsx8("span", {
3256
+ className: "chat-composer-hint",
3257
+ children: "Alt+Left returns to the parent folder."
3258
+ })
3259
+ ]
3260
+ }) : null,
3261
+ completionStatus: popup && completion.snapshot.status !== "ready" ? /* @__PURE__ */ jsxs7("div", {
3262
+ role: "status",
3263
+ className: "chat-composer-status",
3264
+ children: [
3265
+ completion.snapshot.status === "loading" ? "Loading suggestions…" : completion.snapshot.status === "empty" ? "No suggestions" : completion.snapshot.error?.message ?? "Some suggestions could not be loaded",
3266
+ completion.snapshot.status === "error" ? /* @__PURE__ */ jsx8("button", {
3267
+ type: "button",
3268
+ onClick: () => completion.controller.retry(),
3269
+ children: "Retry suggestions"
3270
+ }) : null
3271
+ ]
3272
+ }) : null,
3273
+ visibleError,
3274
+ hasError,
3275
+ statusContent: /* @__PURE__ */ jsxs7(Fragment5, {
3276
+ children: [
3277
+ attachmentsCurrent && attachments.rejections.length ? /* @__PURE__ */ jsxs7("div", {
3278
+ role: "alert",
3279
+ className: "chat-composer-status",
3280
+ "data-state": "error",
3281
+ children: [
3282
+ attachments.rejections.map((item, index) => /* @__PURE__ */ jsxs7("p", {
3283
+ children: [
3284
+ item.metadata.name,
3285
+ ": ",
3286
+ item.error.message
3287
+ ]
3288
+ }, `${index}-${item.metadata.name}`)),
3289
+ /* @__PURE__ */ jsx8("button", {
3290
+ type: "button",
3291
+ onClick: () => attachments.controller.clearRejections(),
3292
+ children: "Dismiss attachment errors"
3293
+ })
3294
+ ]
3295
+ }) : null,
3296
+ recovery.filter((attempt) => sameComposerScope(attempt.snapshot.scope, scope) && (attempt.status === "unknown" || attempt.status === "pending")).map((attempt) => compact && attempt.status === "pending" ? /* @__PURE__ */ jsx8("p", {
3297
+ role: "status",
3298
+ className: "sr-only",
3299
+ "data-state": "pending",
3300
+ children: "Awaiting admission"
3301
+ }, attempt.snapshot.clientSubmissionId) : /* @__PURE__ */ jsxs7("details", {
3302
+ className: "chat-composer-status",
3303
+ "data-state": attempt.status,
3304
+ children: [
3305
+ /* @__PURE__ */ jsx8("summary", {
3306
+ children: attempt.status === "unknown" ? "Submission outcome unknown — draft retained" : "Awaiting admission"
3307
+ }),
3308
+ /* @__PURE__ */ jsx8("p", {
3309
+ children: attempt.snapshot.clientSubmissionId
3310
+ }),
3311
+ attempt.receipt?.outcome === "unknown" ? /* @__PURE__ */ jsx8("p", {
3312
+ children: attempt.receipt.error.message
3313
+ }) : null,
3314
+ host.reconcile ? /* @__PURE__ */ jsx8("button", {
3315
+ type: "button",
3316
+ onClick: () => {
3317
+ session.controller.reconcile(attempt.snapshot.clientSubmissionId).catch((cause) => setLocalError(String(cause), generation));
3318
+ },
3319
+ children: "Check submission status"
3320
+ }) : null,
3321
+ attempt.status === "unknown" && host.authorizeRetry ? /* @__PURE__ */ jsx8("button", {
3322
+ type: "button",
3323
+ onClick: () => {
3324
+ session.controller.retry(attempt.snapshot.clientSubmissionId).catch((cause) => setLocalError(String(cause), generation));
3325
+ },
3326
+ children: "Request authorized retry"
3327
+ }) : null,
3328
+ /* @__PURE__ */ jsx8(PreservedDraft, {
3329
+ input: attempt.snapshot.document,
3330
+ reason: "Submitted snapshot",
3331
+ state: attempt.status === "unknown" ? "unknown" : "pending"
3332
+ })
3333
+ ]
3334
+ }, attempt.snapshot.clientSubmissionId)),
3335
+ session.snapshot.recoveryFailures?.map((attempt) => /* @__PURE__ */ jsx8(PreservedDraft, {
3336
+ input: attempt,
3337
+ reason: "The host could not retain this submission. Export its recovery record before leaving."
3338
+ }, attempt.snapshot.clientSubmissionId)),
3339
+ session.snapshot.lastReceipt?.outcome === "accepted" ? /* @__PURE__ */ jsx8("div", {
3340
+ role: "status",
3341
+ className: compact ? "sr-only" : "chat-composer-status",
3342
+ children: session.snapshot.lastReceipt.operation === "command" ? "Command completed" : `Admitted: ${session.snapshot.lastReceipt.delivery} (${session.snapshot.lastReceipt.persistence})`
3343
+ }) : null
3344
+ ]
3345
+ }),
3346
+ renderFooter: (renderToolbar) => draftAdapter && attachmentsCurrent && read.status === "compatible" ? /* @__PURE__ */ jsx8(DraftLifecycle, {
3347
+ compact,
3348
+ adapter: draftAdapter,
3349
+ scope,
3350
+ draftKey,
3351
+ generation,
3352
+ value,
3353
+ attachments: attachments.controller,
3354
+ onDocumentChange,
3355
+ disabled: disabled || runtime.status === "read_only",
3356
+ children: (feedback, actions) => /* @__PURE__ */ jsxs7(Fragment5, {
3357
+ children: [
3358
+ feedback,
3359
+ renderToolbar(actions)
3360
+ ]
3361
+ })
3362
+ }, `draft-${generation}`) : renderToolbar(),
3363
+ attachLabel,
3364
+ sendLabel: action.label,
3365
+ stopLabel,
3366
+ openAttachments: () => {
3367
+ if (!disabled && attachmentOptions)
3368
+ picker.current?.click();
3369
+ },
3370
+ submit,
3371
+ onStop,
3372
+ editor: editAvailable ? /* @__PURE__ */ jsx8(Editor, {
3373
+ ref: editor,
3374
+ value,
3375
+ instanceGeneration: generation,
3376
+ onReady: (ready) => setReadiness({ generation, ready }),
3377
+ onError: (error) => setEditorFailure({ generation, error }),
3378
+ onSelectionChange: setSelection,
3379
+ onChange: (update) => {
3380
+ setLocalError(undefined);
3381
+ onDocumentChange(update);
3382
+ },
3383
+ disabled: disabled || runtime.status === "read_only",
3384
+ id,
3385
+ label,
3386
+ minRows,
3387
+ maxRows,
3388
+ invalid: hasError,
3389
+ describedBy: hasError ? `${id}-error` : undefined,
3390
+ hasSuggestions: providers.length > 0,
3391
+ controls: showCompletion ? `${id}-completions` : undefined,
3392
+ activeDescendant: active && showCompletion ? completionOptionId(id, active.id) : undefined,
3393
+ onKeyDown: (event) => {
3394
+ if (event.defaultPrevented || event.nativeEvent.isComposing || event.keyCode === 229)
3395
+ return;
3396
+ if (popup) {
3397
+ if (event.key === "Escape") {
3398
+ event.preventDefault();
3399
+ completion.controller.dismiss();
3400
+ return;
3401
+ }
3402
+ if (event.key === "ArrowLeft" && event.altKey && completion.snapshot.breadcrumbs.length) {
3403
+ event.preventDefault();
3404
+ completion.controller.back();
3405
+ return;
3406
+ }
3407
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
3408
+ event.preventDefault();
3409
+ completion.controller.move(event.key === "ArrowDown" ? 1 : -1);
3410
+ return;
3411
+ }
3412
+ if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey && (event.key === "Enter" || event.key === "Tab")) {
3413
+ event.preventDefault();
3414
+ if (active)
3415
+ selectCandidate(active);
3416
+ return;
3417
+ }
3418
+ }
3419
+ const gesture = policy?.shortcut === "enter" ? !event.ctrlKey && !event.metaKey && !event.shiftKey && !event.altKey : event.ctrlKey || event.metaKey;
3420
+ if (event.key === "Enter" && gesture) {
3421
+ event.preventDefault();
3422
+ submit();
3423
+ }
3424
+ }
3425
+ }, generation) : /* @__PURE__ */ jsx8(PreservedDraft, {
3426
+ input: value.document,
3427
+ reason: editorError?.message ?? (read.status === "incompatible" ? read.reason : "This draft requires the optional rich editor.")
3428
+ }),
3429
+ children
3430
+ });
3431
+ });
3432
+ SemanticComposer.displayName = "SemanticComposer";
3433
+
3434
+ // src/components/chat/rich/RichChatComposer.tsx
3435
+ import { jsx as jsx9 } from "react/jsx-runtime";
3436
+ var LazyLexicalEditor = lazy(() => (__preload("rd10x4gc"), import("../../../chunk-rd10x4gc.js")));
3437
+
3438
+ class EditorBoundary extends Component {
3439
+ state = {};
3440
+ static getDerivedStateFromError(error) {
3441
+ return { error };
3442
+ }
3443
+ componentDidCatch(error) {
3444
+ this.props.onError?.(error);
3445
+ }
3446
+ render() {
3447
+ return this.state.error ? /* @__PURE__ */ jsx9(PreservedDraft, {
3448
+ input: this.props.input,
3449
+ reason: this.state.error.message
3450
+ }) : this.props.children;
3451
+ }
3452
+ }
3453
+ var OptionalEditor = forwardRef5((props, ref) => /* @__PURE__ */ jsx9(EditorBoundary, {
3454
+ input: props.value.document,
3455
+ onError: props.onError,
3456
+ children: /* @__PURE__ */ jsx9(Suspense, {
3457
+ fallback: /* @__PURE__ */ jsx9(PreservedDraft, {
3458
+ input: props.value.document,
3459
+ reason: "Loading rich editor.",
3460
+ state: "pending"
3461
+ }),
3462
+ children: /* @__PURE__ */ jsx9(LazyLexicalEditor, {
3463
+ ...props,
3464
+ ref
3465
+ })
3466
+ })
3467
+ }));
3468
+ OptionalEditor.displayName = "OptionalComposerEditor";
3469
+ var RichChatComposer = forwardRef5((props, ref) => /* @__PURE__ */ jsx9(SemanticComposer, {
3470
+ ...props,
3471
+ ref,
3472
+ Editor: OptionalEditor,
3473
+ structured: true
3474
+ }));
3475
+ RichChatComposer.displayName = "RichChatComposer";
3476
+ export {
3477
+ RichChatComposer
3478
+ };