@widgetic/chat 0.1.41 → 0.1.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +461 -6
  2. package/dist/components/Chat.svelte +1117 -119
  3. package/dist/components/Chat.svelte.d.ts +112 -2
  4. package/dist/components/ChatComposer.svelte +389 -8
  5. package/dist/components/ChatComposer.svelte.d.ts +71 -2
  6. package/dist/components/ChatMessageQueue.svelte +56 -0
  7. package/dist/components/ChatMessageQueue.svelte.d.ts +20 -0
  8. package/dist/components/ChatMessages.svelte +477 -46
  9. package/dist/components/ChatMessages.svelte.d.ts +45 -2
  10. package/dist/components/ComposerAttachmentsTray.svelte +42 -10
  11. package/dist/components/ComposerAttachmentsTray.svelte.d.ts +5 -0
  12. package/dist/components/ComposerMentionChips.svelte +53 -0
  13. package/dist/components/ComposerMentionChips.svelte.d.ts +15 -0
  14. package/dist/components/FollowUpCard.svelte +134 -0
  15. package/dist/components/FollowUpCard.svelte.d.ts +17 -0
  16. package/dist/components/MentionChip.svelte +41 -0
  17. package/dist/components/MentionChip.svelte.d.ts +12 -0
  18. package/dist/components/MentionMenu.svelte +114 -0
  19. package/dist/components/MentionMenu.svelte.d.ts +19 -0
  20. package/dist/components/SelectedElementChip.svelte +73 -0
  21. package/dist/components/SelectedElementChip.svelte.d.ts +20 -0
  22. package/dist/components/agent/AgentAvatar.svelte +6 -4
  23. package/dist/components/agent/AgentAvatar.svelte.d.ts +1 -1
  24. package/dist/components/agent/CodeCard.svelte +122 -27
  25. package/dist/components/agent/CodeCard.svelte.d.ts +3 -0
  26. package/dist/components/agent/CodeDiff.svelte +180 -0
  27. package/dist/components/agent/CodeDiff.svelte.d.ts +10 -0
  28. package/dist/components/agent/GenerationModule.svelte +13 -2
  29. package/dist/components/agent/GenerationModule.svelte.d.ts +3 -0
  30. package/dist/components/index.d.ts +5 -0
  31. package/dist/components/index.js +12 -0
  32. package/dist/errors/logTechnicalUserError.d.ts +1 -0
  33. package/dist/errors/logTechnicalUserError.js +37 -0
  34. package/dist/i18n/messages.d.ts +106 -1
  35. package/dist/i18n/messages.js +112 -1
  36. package/dist/i18n/sketchLocales.js +8 -8
  37. package/dist/messageQueue.d.ts +83 -0
  38. package/dist/messageQueue.js +84 -0
  39. package/dist/services/sketchAssistantClient.js +6 -2
  40. package/dist/services/sketchAssistantErrors.d.ts +4 -0
  41. package/dist/services/sketchAssistantErrors.js +22 -0
  42. package/dist/services/sketchAssistantOrchestrator.d.ts +1 -6
  43. package/dist/services/sketchAssistantOrchestrator.js +10 -24
  44. package/dist/services/sketchAssistantReply.js +3 -1
  45. package/dist/stores/chatStore.d.ts +5 -0
  46. package/dist/stores/chatStore.js +21 -0
  47. package/dist/types/agent.d.ts +4 -3
  48. package/dist/types/attachment.d.ts +16 -0
  49. package/dist/types/config.d.ts +6 -0
  50. package/dist/types/index.d.ts +1 -0
  51. package/dist/types/index.js +2 -0
  52. package/dist/types/mention.d.ts +40 -0
  53. package/dist/types/mention.js +8 -0
  54. package/dist/types/message.d.ts +60 -1
  55. package/dist/utils/agentTurn.d.ts +40 -9
  56. package/dist/utils/agentTurn.js +43 -11
  57. package/dist/utils/attachmentProgress.d.ts +12 -0
  58. package/dist/utils/attachmentProgress.js +18 -0
  59. package/dist/utils/bubbleRichFit.d.ts +68 -0
  60. package/dist/utils/bubbleRichFit.js +45 -0
  61. package/dist/utils/bubbleShrinkWrap.d.ts +8 -1
  62. package/dist/utils/bubbleShrinkWrap.js +113 -17
  63. package/dist/utils/codeChanges.d.ts +103 -0
  64. package/dist/utils/codeChanges.js +226 -0
  65. package/dist/utils/codeHighlight.js +1 -0
  66. package/dist/utils/codeStreamFormat.d.ts +5 -2
  67. package/dist/utils/composerMentions.d.ts +96 -0
  68. package/dist/utils/composerMentions.js +217 -0
  69. package/dist/utils/followUps.d.ts +74 -0
  70. package/dist/utils/followUps.js +116 -0
  71. package/dist/utils/generationArchiveStore.d.ts +6 -0
  72. package/dist/utils/generationArchiveStore.js +11 -3
  73. package/dist/utils/index.d.ts +14 -0
  74. package/dist/utils/index.js +22 -0
  75. package/dist/utils/orderedLine.d.ts +29 -0
  76. package/dist/utils/orderedLine.js +17 -0
  77. package/dist/utils/pastedContent.d.ts +99 -0
  78. package/dist/utils/pastedContent.js +258 -0
  79. package/dist/utils/questionCards.d.ts +131 -0
  80. package/dist/utils/questionCards.js +287 -0
  81. package/dist/utils/referenceItems.d.ts +36 -0
  82. package/dist/utils/referenceItems.js +56 -0
  83. package/dist/utils/selectedElementChip.d.ts +47 -0
  84. package/dist/utils/selectedElementChip.js +73 -0
  85. package/dist/utils/sentReferenceBadges.d.ts +26 -0
  86. package/dist/utils/sentReferenceBadges.js +32 -0
  87. package/package.json +1 -1
@@ -1,18 +1,34 @@
1
1
  import type { Snippet } from 'svelte';
2
2
  import { type TextDirection } from '@widgetic/design-system/components/textDirection';
3
3
  import type { ChatConfig, ChatContext } from '../types/index.js';
4
- import type { ClarificationSuggestion, DesignControlRequest, VersionRating } from '../types/message.js';
4
+ import type { ClarificationSuggestion, DesignControlRequest, QuestionCardAnswer, QuestionCardModel, VersionRating } from '../types/message.js';
5
5
  import type { AttachmentInput, SelectedElementChatReference } from '../types/attachment.js';
6
+ import type { ComposerMention, MentionSource } from '../types/mention.js';
6
7
  import type { AgentAvatarRenderer, AgentSoundPlayer, ChatMember } from '../types/agent.js';
7
8
  import { type ComposerModelOption } from './ChatComposer.svelte';
9
+ import { type ComposerCompletion } from '@widgetic/design-system/components/chat/index';
8
10
  interface ChatMethods {
9
11
  sendMessage: (content: string, attachments?: Array<File | AttachmentInput>, options?: {
10
12
  skipIntentGate?: boolean;
11
13
  chipIntent?: ClarificationSuggestion['intent'];
14
+ questionAnswers?: QuestionCardAnswer[];
15
+ references?: Array<{
16
+ id: string;
17
+ label: string;
18
+ }>;
12
19
  }) => Promise<void>;
13
20
  addAssistantMessage: (content: string, skipPersist?: boolean, suggestions?: ClarificationSuggestion[], designControls?: DesignControlRequest) => void;
14
21
  /** Add an assistant reply carrying an inline design-control card (no generation). */
15
22
  addDesignControlsMessage: (content: string, designControls: DesignControlRequest) => void;
23
+ /**
24
+ * Add an assistant reply carrying the card of questions the assistant puts before it builds (the gateway's
25
+ * `metadata.clarification`, made a `QuestionCardModel` with `questionCardFromClarification`). The card is open while it is the
26
+ * newest message: the person answers it in the card (`onQuestionsAnswered`), or writes in the chat instead (the message is
27
+ * sent with every question skipped, `questionAnswers`). `content` is the plain words of the card, and what the conversation
28
+ * shows when the card is closed with its picks unknown; left empty it is made from the card. Pass `skipPersist` true when the
29
+ * backend already saved this reply itself (the gateway does), so it is not saved twice.
30
+ */
31
+ addQuestionCardMessage: (card: QuestionCardModel, content?: string, skipPersist?: boolean) => void;
16
32
  addUserMessage: (content: string, attachments?: Array<{
17
33
  id: string;
18
34
  url: string;
@@ -91,7 +107,11 @@ interface Props {
91
107
  * The parent handles the actual API call and can push assistant messages via addAssistantMessage.
92
108
  * `options` carries per-send modifiers — e.g. `skipIntentGate: true` plus the tapped chip's
93
109
  * `chipIntent` when the send is an explicit override of a clarification card (see
94
- * handleClarificationSuggestionSelected). */
110
+ * handleClarificationSuggestionSelected).
111
+ *
112
+ * `content` is the text a person reads: a reference to an attached file is the word `#hero_banner_final`. Each attachment carries
113
+ * the `referenceLabel` it was called by (a picture has one), and `options.references` lists the files the text names, once each
114
+ * and in order of first appearance: `id` is the id of the file's upload when it has ended, its label until then. */
95
115
  onSendMessage?: (content: string, attachments?: Array<{
96
116
  file?: File;
97
117
  url?: string;
@@ -99,11 +119,42 @@ interface Props {
99
119
  fileType: string;
100
120
  fileName: string;
101
121
  fileSize?: number;
122
+ referenceLabel?: string;
102
123
  }>, options?: {
103
124
  skipIntentGate?: boolean;
104
125
  chipIntent?: ClarificationSuggestion['intent'];
105
126
  selectedElements?: SelectedElementChatReference[];
127
+ /**
128
+ * Set when the person wrote this message while a card of questions was waiting (`ChatMessage.questionCard`) instead of
129
+ * answering it: one answer for each question of the card, every one with an EMPTY `answer` (skipped). The card is shown as
130
+ * skipped, the message is what the assistant goes on with, and the host sends these along with it (the gateway's `answers`,
131
+ * with the message as the prompt) so the assistant decides the skipped questions itself and does not ask them again.
132
+ */
133
+ questionAnswers?: QuestionCardAnswer[];
134
+ references?: Array<{
135
+ id: string;
136
+ label: string;
137
+ }>;
138
+ /**
139
+ * What the person picked with `@` for this message (see `mentionSources`), in the order they picked it. Left out when nothing
140
+ * was picked. Only `kind` and `id` say what was picked; `name` is the row's name as it was shown.
141
+ */
142
+ mentions?: ComposerMention[];
106
143
  }) => Promise<void>;
144
+ /**
145
+ * The person answered the card of questions of a reply in the card itself (Submit on its last question, or Skip), as the
146
+ * gateway's `answers`: one for each question in the card's order, an empty `answer` for a question that was skipped (Next with
147
+ * nothing picked, or Skip); several picks of one question are one per line. `messageId` is the reply that holds the card and
148
+ * `skippedAll` is true when no question has a pick. The card is drawn closed at once (with what was picked, or "Skipped").
149
+ * The host sends the request that asked the questions again, with these answers: nothing is added to the conversation
150
+ * here. Reject (or throw) only when the answers could not be sent, because nothing was started: the card opens again. A
151
+ * build that starts and then fails is not that (the host shows the failure as it does for any build; the answers were sent).
152
+ */
153
+ onQuestionsAnswered?: (detail: {
154
+ messageId: string;
155
+ answers: QuestionCardAnswer[];
156
+ skippedAll: boolean;
157
+ }) => Promise<void> | void;
107
158
  /** Backend integration callbacks — when provided, replace mock chatService methods */
108
159
  onLoadConversations?: (contextId: string) => Promise<any[] | null>;
109
160
  onLoadMessages?: (conversationId: string) => Promise<any[]>;
@@ -167,6 +218,20 @@ interface Props {
167
218
  showConsoleControl?: boolean;
168
219
  /** Increment to bounce the Send button and show the publish-first tooltip (host-driven). */
169
220
  sendNudgeToken?: number;
221
+ /**
222
+ * Ghost text after the caret in the message box: a likely continuation of what is typed, taken with Tab (or a tap on it).
223
+ * The host builds the `source` (a call to its own service, or a fixed list) and may hear what happened to each suggestion
224
+ * through `onEvent`. Nothing is drawn or asked while this is not given; Enter still sends and the suggestion goes with it.
225
+ */
226
+ completion?: ComposerCompletion;
227
+ /**
228
+ * Which attached files the message may refer to: after a `#` the person gets a menu of them, with their pictures, and a choice
229
+ * becomes a badge (picture, name, X) in the text. By default the pictures; a host that sends other files to a model that can use
230
+ * them says so here. It is asked when a file is attached: the file that passes is given the label it is called by.
231
+ */
232
+ isReferenceableAttachment?: (attachment: AttachmentInput) => boolean;
233
+ /** The most files one message may refer to (the host's request has a cap): later references stay plain text. Default: no cap. */
234
+ maxReferences?: number;
170
235
  consoleOpen?: boolean;
171
236
  onToggleConsole?: () => void;
172
237
  /** Custom title displayed in the header. If empty/undefined, defaults to context.title or context.id. */
@@ -221,6 +286,26 @@ interface Props {
221
286
  generationThinking?: string;
222
287
  /** Gateway build plan (`operation.metadata.plan`), or `null` to hide the plan card. */
223
288
  generationPlan?: import('../utils/generationPlan.js').GenerationPlanWire | null;
289
+ /**
290
+ * The host asked the gateway for a build plan and it has not arrived yet. While `generationPlan` is still `null` the plan card is
291
+ * drawn closed, saying "Planning" in a shimmer, and it opens when the plan comes. Lower it when the plan arrives or when no plan is
292
+ * coming; it also ends by itself once code starts to stream. Left `false` (the default), nothing is drawn until `generationPlan`
293
+ * arrives, as before.
294
+ */
295
+ generationPlanPending?: boolean;
296
+ /**
297
+ * What the last run changed in the widget's files (`operation.metadata.codeChanges`, read with `readCodeChangesFromMetadata`), or
298
+ * `null` when it changed nothing worth showing: the first message of a conversation, a build that was not kept, a gateway that does
299
+ * not send it. The code card under that run's conclusion then opens on a read-only diff, the lines taken out in red and the lines
300
+ * put in in green, with "Code" one press away.
301
+ *
302
+ * Unlike the live props above it is NOT given up when `isGenerating` ends: it is what the run left behind. Give it when the
303
+ * operation completes, and clear it (`null`) when the next run starts. It may come AFTER `isGenerating` fell (a host that lets the
304
+ * person write again as soon as the preview is up lowers the flag before the completed operation arrives): the chat then puts it
305
+ * into the work of the run that just ended. A page that forgets to clear it is safe: the chat ignores the very value it held when
306
+ * a run began.
307
+ */
308
+ generationChanges?: import('../utils/codeChanges.js').CodeChanges | null;
224
309
  onStopGeneration?: () => void;
225
310
  /**
226
311
  * Renders the inline design-control card attached to an assistant reply
@@ -271,6 +356,12 @@ interface Props {
271
356
  * does not wrap, and a message with code blocks, keep the width CSS gives them. On by default; pass `false` for CSS's widths.
272
357
  */
273
358
  tightBubbles?: boolean;
359
+ /**
360
+ * Draws a file badge (the picture and `#name`, no X) in a sent message for each word that names one of the files attached to it,
361
+ * as the message box drew it while the message was written. A word that cannot be matched to a file for sure stays plain text.
362
+ * On by default; `false` shows the text as it was sent.
363
+ */
364
+ referenceBadges?: boolean;
274
365
  /** Show the Widget Element Selector toggle button in the action bar (disabled by default). */
275
366
  showSelector?: boolean;
276
367
  /** Whether the Widget Element Selector is currently active for this chat's widget. */
@@ -283,6 +374,25 @@ interface Props {
283
374
  onRemoveSelectedElement?: (elementId: string) => void;
284
375
  /** Fired when all selected widget elements should be cleared (e.g. after sending). */
285
376
  onClearSelectedElements?: () => void;
377
+ /**
378
+ * The part whose note is open over the preview, if any. Its chip is drawn as active. Together with
379
+ * `onSelectedElementClick` it lets a chip and the part's marker on the preview open and fold the same note.
380
+ */
381
+ activeSelectedElementId?: string | null;
382
+ /**
383
+ * Fired when the body of a part's chip is clicked: the host shows that part's note over the preview (or folds it when it is
384
+ * already open). Left out, the chips only say what they hold and are not clickable.
385
+ */
386
+ onSelectedElementClick?: (elementId: string) => void;
387
+ /**
388
+ * What the person can pick with `@` in the message box: lists of rows that the page hands over (connected apps, compositions, ...;
389
+ * see `MentionSource`). A pick is drawn as a chip in the message box and goes out with the message as `mentions` in the options of
390
+ * `onSendMessage`; its name is written into the text as well, as the person sees it. A link in the text that a row is made for
391
+ * (`linkHosts`) is offered as a one-tap pick. Left out or empty, `@` is an ordinary character and the box is as it always was.
392
+ */
393
+ mentionSources?: readonly MentionSource[];
394
+ /** The most picks one message holds (5 when left out). Once it is reached the menu shows the other rows dimmed and says why. */
395
+ mentionLimit?: number;
286
396
  /** Model list for the DS composer Assistant menu; hidden when empty. */
287
397
  composerModels?: ComposerModelOption[];
288
398
  selectedComposerModelId?: string | null;
@@ -1,10 +1,33 @@
1
1
  <script lang="ts">
2
+ import { tick, type Snippet } from 'svelte';
2
3
  import type { AttachmentInput } from '../types/attachment.js';
4
+ import type { ComposerMention, MentionSource } from '../types/mention.js';
3
5
  import { useChatLanguage } from '../i18n/language.js';
4
6
  import { dirForUserText, useTextDirection } from '@widgetic/design-system/components/textDirection';
5
- import { Composer, IconButton } from '@widgetic/design-system/components/chat/index';
6
- import { chatLog } from '../utils/logger.js';
7
+ import {
8
+ Composer,
9
+ IconButton,
10
+ type ComposerCompletion,
11
+ type ComposerEditing,
12
+ type ComposerSendOptions,
13
+ type ReferenceHoverEvent,
14
+ type ReferenceItem,
15
+ } from '@widgetic/design-system/components/chat/index';
16
+ import { chatLog, chatError } from '../utils/logger.js';
17
+ import { attachmentsFromPaste, type PastedAttachment } from '../utils/pastedContent.js';
18
+ import {
19
+ DEFAULT_MENTION_LIMIT,
20
+ buildMentionRows,
21
+ caretAfterMentionInsert,
22
+ findActiveMentionTrigger,
23
+ firstSelectableRowIndex,
24
+ insertMentionText,
25
+ mentionOptionId,
26
+ nextSelectableRowIndex,
27
+ type MentionRow,
28
+ } from '../utils/composerMentions.js';
7
29
  import { reduceSendNudge, SEND_NUDGE_VISIBLE_MS, type SendNudgePhase } from '../sendNudgeState.js';
30
+ import MentionMenu from './MentionMenu.svelte';
8
31
 
9
32
  const { t } = useChatLanguage();
10
33
  const textDirection = useTextDirection();
@@ -22,10 +45,30 @@
22
45
  models?: ComposerModelOption[];
23
46
  selectedModelId?: string | null;
24
47
  onSelectModel?: (modelId: string) => void;
25
- onSend: (content: string, attachments?: AttachmentInput[]) => void;
48
+ /**
49
+ * `content` is the text a person reads: a reference is the word `#hero_banner`, whatever room its badge takes in the box. With
50
+ * `referenceItems`, `options.references` lists the attached files the text names (see `ComposerSendOptions`).
51
+ */
52
+ onSend: (content: string, options?: ComposerSendOptions) => void;
26
53
  onStop?: () => void;
54
+ /**
55
+ * What the person typed while an agent works. Given, the send control queues it (the host keeps it until the agent is done) and
56
+ * Enter does not stop the agent; left out, the composer has no queue and the control and Enter stop the agent, as before.
57
+ */
58
+ onQueue?: (text: string) => void;
59
+ /**
60
+ * A queued message is open in the composer: the pill of the edit ("Editing ×") above the text and, in place of Send, the check
61
+ * that saves it. Left out, or null, the composer is not editing.
62
+ */
63
+ editing?: ComposerEditing | null;
27
64
  onInputChange?: (text: string) => void;
28
65
  onFilesDropped?: (files: File[]) => void;
66
+ /**
67
+ * What a paste brings in as files to attach: a screenshot or a file on the clipboard, or a long text (which comes as a text
68
+ * file, with the first words of the text as its label). Without it the composer pastes as the browser does: a page that
69
+ * cannot attach files gets no attachment from a paste, and the text goes into the box.
70
+ */
71
+ onFilesPasted?: (pasted: PastedAttachment[]) => void;
29
72
  /** Opens the file picker. The "+" of the toolbar is drawn only when the page can attach files. */
30
73
  onAttach?: () => void;
31
74
  /** Figma side-panel composer: no top border on the shell; DS Composer keeps its own border. */
@@ -34,6 +77,52 @@
34
77
  sendIcon?: 'send' | 'arrow-up';
35
78
  /** Increment from the host to nudge Send before publish. */
36
79
  sendNudgeToken?: number;
80
+ /**
81
+ * What sits inside the message box above the text (the chips of the parts picked on the preview). The box draws nothing
82
+ * for it while this is not given, so a message with no parts looks as it always did.
83
+ */
84
+ attachments?: Snippet;
85
+ /**
86
+ * For a page that uses the message box on its own, to write one short thing (the note of a part picked on the preview).
87
+ * The chat's own box asks for none of these four and looks and acts as it always did.
88
+ *
89
+ * `autofocus`: the box takes the focus when it is drawn, with the caret after what is already written.
90
+ */
91
+ autofocus?: boolean;
92
+ /** The name a screen reader gives the box. Without it the placeholder is its name. */
93
+ inputLabel?: string;
94
+ /** What the Enter key of a touch keyboard says: "done" for a box that ends a note, "send" for one that sends a message. */
95
+ enterKeyHint?: 'enter' | 'done' | 'go' | 'next' | 'previous' | 'search' | 'send';
96
+ /** The name of the send button, for a box whose Enter is not "Send message" (the note of a part is added to the chat). */
97
+ sendLabel?: string;
98
+ /**
99
+ * Ghost text after the caret: a likely continuation of what is typed, taken with Tab (or a tap). The box draws nothing and
100
+ * asks for nothing while this is not given. Enter still sends, and the suggestion goes with the message.
101
+ */
102
+ completion?: ComposerCompletion;
103
+ /**
104
+ * The attached files the message may refer to with `#` (a menu with their pictures opens, and a choice becomes a badge in the
105
+ * text), in tray order. Left out, the box has no references; an empty list is a box that has none to offer yet.
106
+ */
107
+ referenceItems?: ReferenceItem[];
108
+ /** The most files one message may refer to (the host's request has a cap). Default: no cap. */
109
+ maxReferences?: number;
110
+ /** A badge in the text, or a row of the `#` menu, is on a file (`label: null` when it left): the tray rings the same file. */
111
+ onReferenceHover?: (event: ReferenceHoverEvent) => void;
112
+ /**
113
+ * What the person can pick with `@` in the message box: lists of rows that the page hands over (connected apps, compositions, ...).
114
+ * Left out or empty, `@` is an ordinary character and the box behaves exactly as it always did.
115
+ */
116
+ mentionSources?: readonly MentionSource[];
117
+ /** What the message already holds as picks: the rows picked as many times as `mentionLimit` allows are the last the menu offers. */
118
+ mentions?: readonly ComposerMention[];
119
+ /** The most picks one message holds. */
120
+ mentionLimit?: number;
121
+ /**
122
+ * A row was picked from the menu. Its name was written into the box already (`@Name `); the page keeps the pick, draws its
123
+ * chip and sends it with the message.
124
+ */
125
+ onMentionPick?: (mention: ComposerMention) => void;
37
126
  }
38
127
 
39
128
  let {
@@ -49,16 +138,97 @@
49
138
  onSelectModel,
50
139
  onSend,
51
140
  onStop,
141
+ onQueue,
142
+ editing = null,
52
143
  onInputChange,
53
144
  onFilesDropped,
145
+ onFilesPasted,
54
146
  onAttach,
55
147
  panelLayout = false,
56
148
  sendIcon = 'send',
57
149
  sendNudgeToken = 0,
150
+ attachments,
151
+ autofocus = false,
152
+ inputLabel,
153
+ enterKeyHint,
154
+ sendLabel,
155
+ completion,
156
+ referenceItems,
157
+ maxReferences,
158
+ onReferenceHover,
159
+ mentionSources = [],
160
+ mentions = [],
161
+ mentionLimit = DEFAULT_MENTION_LIMIT,
162
+ onMentionPick,
58
163
  }: Props = $props();
59
164
 
60
165
  const composerSendIcon = $derived(panelLayout ? 'arrow-up' : sendIcon);
61
166
 
167
+ // The shell, to reach the message box in it. The design system's Composer draws the box (a textarea) and does not hand it out,
168
+ // so the three settings below that belong to the box itself are put on it from here, where they can be told apart from the
169
+ // chat's own use of it.
170
+ let shellElement = $state<HTMLDivElement | null>(null);
171
+
172
+ /** The message box the Composer drew inside the shell, or nothing while it is not drawn. */
173
+ function findMessageBox(): HTMLTextAreaElement | null {
174
+ return shellElement?.querySelector('textarea') ?? null;
175
+ }
176
+
177
+ // The box takes the focus once it is drawn (the note of a part opens ready to be written in), caret after what is written.
178
+ $effect(() => {
179
+ if (!autofocus) return;
180
+ try {
181
+ const messageBox = findMessageBox();
182
+ if (!messageBox) return;
183
+ messageBox.focus({ preventScroll: true });
184
+ const caretPosition = messageBox.value.length;
185
+ messageBox.setSelectionRange(caretPosition, caretPosition);
186
+ chatLog('[ChatComposer] Took the focus, caret at', caretPosition);
187
+ } catch (error) {
188
+ chatError('[ChatComposer] Could not take the focus:', error);
189
+ }
190
+ });
191
+
192
+ // The name and the Enter key of the box. They are set with the box and taken off again when they are no longer asked for, so
193
+ // a box that stops asking is as the Composer drew it.
194
+ $effect(() => {
195
+ const messageBox = findMessageBox();
196
+ if (!messageBox) return;
197
+ const settings: Array<[string, string | undefined]> = [
198
+ ['aria-label', inputLabel],
199
+ ['enterkeyhint', enterKeyHint],
200
+ ];
201
+ const applied: string[] = [];
202
+ try {
203
+ for (const [attributeName, attributeValue] of settings) {
204
+ if (!attributeValue) continue;
205
+ messageBox.setAttribute(attributeName, attributeValue);
206
+ applied.push(attributeName);
207
+ }
208
+ } catch (error) {
209
+ chatError('[ChatComposer] Could not set the name or the Enter key of the box:', error);
210
+ }
211
+ return () => {
212
+ for (const attributeName of applied) messageBox.removeAttribute(attributeName);
213
+ };
214
+ });
215
+
216
+ // The files the message may refer to, with the words the box says about them. `{name}` is filled by the box with the file's own name.
217
+ const composerReferences = $derived(
218
+ referenceItems
219
+ ? {
220
+ items: referenceItems,
221
+ messages: {
222
+ hint: $t('chat.input.referenceHint'),
223
+ menuLabel: $t('chat.input.referenceMenuLabel'),
224
+ remove: $t('chat.input.referenceRemove', { name: '{name}' }),
225
+ },
226
+ onHover: onReferenceHover,
227
+ maxReferences,
228
+ }
229
+ : undefined,
230
+ );
231
+
62
232
  // The model menu's button reads the name of the picked model. Until one is picked it reads the name of the first one (the model
63
233
  // that is used then), never a generic word such as "Assistant": the person knows what they are talking to.
64
234
  const fallbackModelLabel = $derived(models?.[0]?.label?.trim() ?? '');
@@ -156,7 +326,193 @@
156
326
  onFilesDropped?.(droppedFiles);
157
327
  }
158
328
 
159
- function handleComposerSend(text: string) {
329
+ /**
330
+ * A paste into the box. A picture or a file on the clipboard, or a long text, is attached the way a dropped file is. A short
331
+ * text, or anything else, is left to the browser, which types it into the box as it always did: only a paste that is
332
+ * attached is stopped. The clipboard is read at once, as it is only open while the event runs.
333
+ */
334
+ function handlePaste(event: ClipboardEvent) {
335
+ if (!onFilesPasted) return;
336
+ // A single-line field inside the composer (not the message box) pastes as it always did.
337
+ if (event.target instanceof HTMLInputElement) return;
338
+ try {
339
+ const pastedAttachments = attachmentsFromPaste(event.clipboardData);
340
+ if (pastedAttachments.length === 0) return;
341
+ event.preventDefault();
342
+ chatLog('[ChatComposer] Pasted content attached:', pastedAttachments.length);
343
+ onFilesPasted(pastedAttachments);
344
+ } catch (error) {
345
+ chatError('[ChatComposer] Could not read what was pasted:', error);
346
+ }
347
+ }
348
+
349
+ // --- The @ menu ----------------------------------------------------------------------------------------------------------
350
+ // The design system's `Composer` owns the text box and sends on Enter inside it, and gives no hold on either. So the menu listens
351
+ // on the box around it: the keys in the capture phase (before the `Composer` hears Enter, which would send), the caret on
352
+ // input, click and the keys that move it. While no row shows, nothing here acts and every key goes where it always went.
353
+
354
+ const mentionListId = $props.id();
355
+ let mentionOpen = $state(false);
356
+ /** Where the `@` is in the text, and what was typed after it up to the caret. */
357
+ let mentionTriggerStart = $state(0);
358
+ let mentionQuery = $state('');
359
+ let mentionHighlight = $state(0);
360
+ /** The `@` that Escape put away stays away while the person goes on typing the same word. */
361
+ let mentionDismissedStart = -1;
362
+
363
+ const mentionRows = $derived(mentionOpen ? buildMentionRows(mentionSources, mentionQuery, mentions, mentionLimit) : []);
364
+ // The menu is drawn only while a row matches: an `@` that matches nothing is ordinary text, with no "nothing found" box in the way.
365
+ const mentionMenuVisible = $derived(mentionRows.length > 0);
366
+ const mentionHighlightIndex = $derived(
367
+ mentionRows[mentionHighlight]?.selectable ? mentionHighlight : firstSelectableRowIndex(mentionRows),
368
+ );
369
+
370
+ function messageTextarea(): HTMLTextAreaElement | null {
371
+ return shellElement?.querySelector('textarea') ?? null;
372
+ }
373
+
374
+ function closeMentionMenu() {
375
+ if (mentionOpen) mentionOpen = false;
376
+ }
377
+
378
+ /** Looks at where the caret is: opens the menu while it sits inside a mention being typed, closes it when it does not. */
379
+ function syncMentionTrigger(textarea: HTMLTextAreaElement) {
380
+ try {
381
+ if (!mentionSources || mentionSources.length === 0 || textarea.selectionStart !== textarea.selectionEnd) {
382
+ closeMentionMenu();
383
+ return;
384
+ }
385
+ const trigger = findActiveMentionTrigger(textarea.value, textarea.selectionStart ?? textarea.value.length);
386
+ if (!trigger) {
387
+ mentionDismissedStart = -1;
388
+ closeMentionMenu();
389
+ return;
390
+ }
391
+ if (trigger.start === mentionDismissedStart) {
392
+ closeMentionMenu();
393
+ return;
394
+ }
395
+ if (!mentionOpen || trigger.start !== mentionTriggerStart || trigger.query !== mentionQuery) mentionHighlight = 0;
396
+ mentionTriggerStart = trigger.start;
397
+ mentionQuery = trigger.query;
398
+ mentionOpen = true;
399
+ } catch (error) {
400
+ chatError('[ChatComposer] Could not read the @ in the box:', error);
401
+ closeMentionMenu();
402
+ }
403
+ }
404
+
405
+ function handleMentionInput(event: Event) {
406
+ if (event.target instanceof HTMLTextAreaElement) syncMentionTrigger(event.target);
407
+ }
408
+
409
+ function handleMentionClick(event: MouseEvent) {
410
+ if (event.target instanceof HTMLTextAreaElement) syncMentionTrigger(event.target);
411
+ }
412
+
413
+ /** The keys that move the caret without typing: the menu follows it. The other keys are heard as input, or by the menu's own handler. */
414
+ function handleMentionKeyup(event: KeyboardEvent) {
415
+ if (!(event.target instanceof HTMLTextAreaElement)) return;
416
+ if (['ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageUp', 'PageDown'].includes(event.key)) syncMentionTrigger(event.target);
417
+ }
418
+
419
+ function handleMentionFocusOut(event: FocusEvent) {
420
+ const next = event.relatedTarget;
421
+ if (next instanceof Node && shellElement?.contains(next)) return;
422
+ closeMentionMenu();
423
+ }
424
+
425
+ /** The keys of the menu, heard before the `Composer` hears them. Only while a row shows, and never in the middle of an IME composition. */
426
+ function handleMentionKeydown(event: KeyboardEvent) {
427
+ if (!mentionMenuVisible || event.isComposing || !(event.target instanceof HTMLTextAreaElement)) return;
428
+ try {
429
+ switch (event.key) {
430
+ case 'ArrowDown':
431
+ case 'ArrowUp': {
432
+ event.preventDefault();
433
+ event.stopPropagation();
434
+ mentionHighlight = nextSelectableRowIndex(mentionRows, mentionHighlightIndex, event.key === 'ArrowDown' ? 1 : -1);
435
+ return;
436
+ }
437
+ case 'Enter':
438
+ case 'Tab': {
439
+ // Shift+Enter writes a new line, Shift+Tab leaves the box, and a shortcut is a shortcut: none of them picks
440
+ if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return;
441
+ const row = mentionRows[mentionHighlightIndex];
442
+ // With no row that can be picked the key does what it always did (Enter sends)
443
+ if (!row?.selectable) return;
444
+ event.preventDefault();
445
+ event.stopPropagation();
446
+ void chooseMention(row);
447
+ return;
448
+ }
449
+ case 'Escape': {
450
+ event.preventDefault();
451
+ event.stopPropagation();
452
+ mentionDismissedStart = mentionTriggerStart;
453
+ closeMentionMenu();
454
+ return;
455
+ }
456
+ }
457
+ } catch (error) {
458
+ chatError('[ChatComposer] Could not handle a key of the @ menu:', error);
459
+ }
460
+ }
461
+
462
+ /** Writes `@Name ` where the person was typing, tells the page about the pick, and puts the caret after it, ready to go on. */
463
+ async function chooseMention(row: MentionRow) {
464
+ if (!row.selectable) return;
465
+ try {
466
+ const textarea = messageTextarea();
467
+ const text = textarea?.value ?? value ?? '';
468
+ const caret = textarea?.selectionStart ?? text.length;
469
+ const nextText = insertMentionText(text, mentionTriggerStart, caret, row.item.name);
470
+ const nextCaret = caretAfterMentionInsert(mentionTriggerStart, row.item.name);
471
+ mentionDismissedStart = -1;
472
+ mentionOpen = false;
473
+ value = nextText;
474
+ onMentionPick?.({ kind: row.kind, id: row.item.id, name: row.item.name });
475
+ chatLog('[ChatComposer] Mention picked:', row.kind);
476
+ // The text reaches the box on the next update: the caret can only be put after it
477
+ await tick();
478
+ const target = messageTextarea();
479
+ if (target) {
480
+ target.focus({ preventScroll: true });
481
+ target.setSelectionRange(nextCaret, nextCaret);
482
+ }
483
+ } catch (error) {
484
+ chatError('[ChatComposer] Could not write the pick into the box:', error);
485
+ }
486
+ }
487
+
488
+ // The text box says which row is highlighted and which list it opened, for screen readers (the focus never leaves it)
489
+ $effect(() => {
490
+ if (!mentionMenuVisible) return;
491
+ const textarea = messageTextarea();
492
+ if (!textarea) return;
493
+ textarea.setAttribute('aria-controls', mentionListId);
494
+ textarea.setAttribute('aria-activedescendant', mentionOptionId(mentionListId, mentionHighlightIndex));
495
+ return () => {
496
+ textarea.removeAttribute('aria-controls');
497
+ textarea.removeAttribute('aria-activedescendant');
498
+ };
499
+ });
500
+
501
+ // The highlighted row stays in view while the arrow keys walk a long list
502
+ $effect(() => {
503
+ if (!mentionMenuVisible) return;
504
+ document.getElementById(mentionOptionId(mentionListId, mentionHighlightIndex))?.scrollIntoView({ block: 'nearest' });
505
+ });
506
+
507
+ /** The send control while an agent works: the message waits in the host's queue instead of stopping the run. */
508
+ function handleComposerQueue(text: string) {
509
+ const trimmed = text.trim();
510
+ if (!trimmed) return;
511
+ chatLog('[ChatComposer] Message queued while the agent works:', trimmed.length);
512
+ onQueue?.(trimmed);
513
+ }
514
+
515
+ function handleComposerSend(text: string, options?: ComposerSendOptions) {
160
516
  const trimmed = text.trim();
161
517
  if (!trimmed && !allowEmptySend) return;
162
518
  if (isSending && !isGenerating) return;
@@ -165,7 +521,7 @@
165
521
  clearSendNudgeTimers();
166
522
  sendNudgeBounce = false;
167
523
  }
168
- onSend(trimmed, undefined);
524
+ onSend(trimmed, options);
169
525
  }
170
526
  </script>
171
527
 
@@ -198,14 +554,21 @@
198
554
 
199
555
  <!-- svelte-ignore a11y_no_static_element_interactions -->
200
556
  <div
201
- class="chat-composer-shell border-border bg-background shrink-0 {panelLayout ? '' : 'border-t'} {className} {isFileDragOver
557
+ class="chat-composer-shell border-border bg-background relative shrink-0 {panelLayout ? '' : 'border-t'} {className} {isFileDragOver
202
558
  ? 'outline-primary outline-2 outline-dashed'
203
559
  : ''}"
204
560
  {style}
561
+ bind:this={shellElement}
205
562
  ondragenter={handleFileDragEnter}
206
563
  ondragover={handleFileDragOver}
207
564
  ondragleave={handleFileDragLeave}
208
565
  ondrop={handleFileDrop}
566
+ onpaste={handlePaste}
567
+ onkeydowncapture={handleMentionKeydown}
568
+ oninput={handleMentionInput}
569
+ onclick={handleMentionClick}
570
+ onkeyup={handleMentionKeyup}
571
+ onfocusout={handleMentionFocusOut}
209
572
  >
210
573
  <Composer
211
574
  class={panelLayout ? 'w-full max-w-full' : 'rounded-none border-0'}
@@ -219,15 +582,33 @@
219
582
  {selectedModelId}
220
583
  onSelectModel={onSelectModel}
221
584
  messages={{
222
- send: $t('chat.input.send'),
585
+ send: sendLabel ?? $t('chat.input.send'),
223
586
  stop: $t('chat.input.stop'),
587
+ queue: $t('chat.input.queue'),
224
588
  attach: $t('chat.actions.upload'),
225
- characterLimit: $t('chat.input.tooLong')
589
+ characterLimit: $t('chat.input.tooLong'),
590
+ completionHint: $t('chat.input.completionHint'),
591
+ completionHintTouch: $t('chat.input.completionHintTouch')
226
592
  }}
227
593
  assistantLabel={fallbackModelLabel}
228
594
  onSend={handleComposerSend}
229
595
  onStop={() => onStop?.()}
596
+ onQueue={onQueue ? handleComposerQueue : undefined}
597
+ {editing}
230
598
  leading={attachControl}
599
+ {attachments}
600
+ {completion}
601
+ references={composerReferences}
231
602
  {sendAttention}
232
603
  />
604
+ {#if mentionMenuVisible}
605
+ <MentionMenu
606
+ rows={mentionRows}
607
+ highlightIndex={mentionHighlightIndex}
608
+ limit={mentionLimit}
609
+ listId={mentionListId}
610
+ onSelect={(row) => void chooseMention(row)}
611
+ onHighlight={(index) => (mentionHighlight = index)}
612
+ />
613
+ {/if}
233
614
  </div>