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