@widgetic/chat 0.1.38 → 0.1.40

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 (59) hide show
  1. package/README.md +71 -0
  2. package/dist/components/AttachmentDisplay.svelte +14 -4
  3. package/dist/components/Chat.svelte +131 -106
  4. package/dist/components/Chat.svelte.d.ts +29 -0
  5. package/dist/components/ChatComposer.svelte +5 -1
  6. package/dist/components/ChatMessages.svelte +595 -175
  7. package/dist/components/ChatMessages.svelte.d.ts +20 -0
  8. package/dist/components/CodeBlock.svelte +9 -1
  9. package/dist/components/ComposerAttachmentsTray.svelte +64 -0
  10. package/dist/components/ComposerAttachmentsTray.svelte.d.ts +11 -0
  11. package/dist/components/PanelChatHeader.svelte +26 -6
  12. package/dist/components/PanelChatHeader.svelte.d.ts +1 -0
  13. package/dist/components/PanelFollowUpSuggestions.svelte +2 -2
  14. package/dist/components/PanelSuggestionButtons.svelte +2 -1
  15. package/dist/components/agent/AgentAvatar.svelte +153 -0
  16. package/dist/components/agent/AgentAvatar.svelte.d.ts +27 -0
  17. package/dist/components/agent/AgentTurn.svelte +64 -0
  18. package/dist/components/agent/AgentTurn.svelte.d.ts +32 -0
  19. package/dist/components/agent/AvatarBoundary.svelte +29 -0
  20. package/dist/components/agent/AvatarBoundary.svelte.d.ts +20 -0
  21. package/dist/components/agent/CodeCard.svelte +288 -0
  22. package/dist/components/agent/CodeCard.svelte.d.ts +12 -0
  23. package/dist/components/agent/GenerationModule.svelte +99 -0
  24. package/dist/components/agent/GenerationModule.svelte.d.ts +16 -0
  25. package/dist/components/agent/MemberAvatar.svelte +87 -0
  26. package/dist/components/agent/MemberAvatar.svelte.d.ts +8 -0
  27. package/dist/components/index.d.ts +5 -0
  28. package/dist/components/index.js +9 -0
  29. package/dist/i18n/messages.d.ts +32 -10
  30. package/dist/i18n/messages.js +32 -10
  31. package/dist/types/agent.d.ts +74 -0
  32. package/dist/types/agent.js +1 -0
  33. package/dist/types/index.d.ts +1 -0
  34. package/dist/types/index.js +2 -0
  35. package/dist/utils/agentTurn.d.ts +219 -0
  36. package/dist/utils/agentTurn.js +301 -0
  37. package/dist/utils/attachmentPreviewUrl.d.ts +21 -0
  38. package/dist/utils/attachmentPreviewUrl.js +39 -0
  39. package/dist/utils/bubbleFit.d.ts +75 -0
  40. package/dist/utils/bubbleFit.js +116 -0
  41. package/dist/utils/bubbleShrinkWrap.d.ts +32 -0
  42. package/dist/utils/bubbleShrinkWrap.js +360 -0
  43. package/dist/utils/chatImageUploadPrep.d.ts +22 -0
  44. package/dist/utils/chatImageUploadPrep.js +90 -0
  45. package/dist/utils/codeHighlight.d.ts +13 -0
  46. package/dist/utils/codeHighlight.js +61 -0
  47. package/dist/utils/codePrettier.d.ts +6 -0
  48. package/dist/utils/codePrettier.js +34 -0
  49. package/dist/utils/codeStreamFormat.d.ts +90 -0
  50. package/dist/utils/codeStreamFormat.js +429 -0
  51. package/dist/utils/generationArchiveStore.d.ts +15 -0
  52. package/dist/utils/generationArchiveStore.js +89 -0
  53. package/dist/utils/imageTransform.d.ts +12 -0
  54. package/dist/utils/imageTransform.js +45 -0
  55. package/dist/utils/index.d.ts +2 -0
  56. package/dist/utils/index.js +3 -0
  57. package/dist/utils/suggestionDraft.d.ts +5 -0
  58. package/dist/utils/suggestionDraft.js +15 -0
  59. package/package.json +5 -4
package/README.md CHANGED
@@ -287,6 +287,77 @@ then live code in the same bubble. Parse wire data with **`readGenerationPlanFro
287
287
  `@widgetic/chat`. When **`features.screenshot`** is `false`, the action bar hides the screenshot control;
288
288
  ordinary image upload and screen recording are unchanged.
289
289
 
290
+ ### The assistant's turn: avatar, sound, faces and bubbles
291
+
292
+ The messages list plays the assistant's turn around an **avatar**. The avatar, its sound and the team's faces come from the page: the chat
293
+ has no dependency on any drawing or sound code. A page that gives nothing gets a plain round avatar and silence, so nothing here is required.
294
+
295
+ ```svelte
296
+ <script lang="ts">
297
+ import { Chat } from '@widgetic/chat';
298
+ import { Mascot } from '@widgetic/brand/mascot';
299
+ import { createMascotSound } from '@widgetic/brand/mascot/sound';
300
+
301
+ // Off until `agentSound.enable()` runs inside a click (browsers keep audio locked until a gesture)
302
+ const agentSound = createMascotSound();
303
+ </script>
304
+
305
+ {#snippet agentAvatar({ state, size, live, label })}
306
+ <Mascot {state} {size} {label} decorative={!label} frozenAt={live ? undefined : 0.5} settleTo="idle" />
307
+ {/snippet}
308
+
309
+ <Chat {context} renderAgentAvatar={agentAvatar} {agentSound} {members} {currentUser} />
310
+ ```
311
+
312
+ | Prop | What it does |
313
+ | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
314
+ | `renderAgentAvatar` | A snippet that draws the avatar, given `{ state, size, live, label }` (`AgentAvatarRenderProps`). `state` is one of the Scribble Mascot's five (`idle`, `thinking`, `writing`, `success`, `error`). |
315
+ | `agentSound` | Lets the avatar be heard: anything with `notifyStateChange(state)` (`AgentSoundPlayer`). The mascot's `createMascotSound()` fits as it is. Left out, the chat is silent. |
316
+ | `members` | The team (`ChatMember[]`: `id`, and optionally `name`, `email`, `avatarUrl`). A message a person wrote gets their picture, or their initials, at its right, and their e-mail while the pointer rests on it; a click on it writes to them (a `mailto:` link, with the hand cursor), as in the project header of the Widgetic site. Without an e-mail it is only a picture. |
317
+ | `currentUser` | The signed-in person: who wrote the messages they just sent, and anyone no member matches. A message nobody can be named for gets no face, and a page that names nobody sees no change. |
318
+ | `tightBubbles` | On by default. Sizes what people wrote to their text with [Pretext](https://chenglou.me/pretext/bubbles/): a bubble whose text wraps is as narrow as its widest line allows. `false` for CSS's widths. |
319
+
320
+ What the person sees, in the order it happens (a page that is not the chat, such as the workflows assistant or the embed, follows the same
321
+ choreography through the exported rules and components, see below):
322
+
323
+ 1. **The message is sent**: the avatar is large and thinks, with a card to its right if the host sends a plan or a question.
324
+ 2. **The reasoning is written**: the avatar glides down to its small size at the left and keeps **thinking**, beside a collapsible "Thinking…"
325
+ text that is open while it is written.
326
+ 3. **Code, or the answer, is written**: the avatar **writes**, beside a "Writing code…" module that is open while the code streams. Writing
327
+ begins only when something other than reasoning arrives.
328
+ 4. **The end**: a success grows the avatar large again, in its **success** look, with the conclusion and the thinking and the code as two
329
+ closed, expandable modules ("Thought for 2 s", "Code"). A failure is one short line in red with a refresh icon that runs the prompt again,
330
+ beside the large **error** avatar. **Stop** glides the avatar down to its small size.
331
+
332
+ Only the newest turn moves, and at most one avatar is alive in a long chat; the older ones are small still pictures. What the assistant did
333
+ (the thinking and the code of the run that just ended) is kept in this browser (IndexedDB, by conversation) and comes back after a reload under
334
+ the turn it belongs to, found again by the words of the prompt.
335
+
336
+ **Sound.** The chat tells `agentSound` the state of the avatar the person is looking at, **once for each change**: `thinking` when the run starts,
337
+ `writing` when code (or the answer) is written, then how it ended: `success`, `error`, or `idle` for a stop, a question or a plain answer. It
338
+ never speaks for a conversation that was only opened or switched to, whatever state its newest turn was left in (opening a chat must not play
339
+ the sound of a failure), and never once per streamed token. Everything else about sounding is the player's: the mascot's is off until the page
340
+ calls `enable()` inside a click, plays one short cue per state, does not repeat the same cue within 250 ms and stays quiet in a hidden tab (see
341
+ the brand README). The chat has no sound control of its own, so the page keeps the person's choice (a mute switch) and passes it on. A page that
342
+ does not draw the mascot should not give `agentSound` either: the sounds belong to the mascot. A player that throws is left alone and never takes
343
+ the chat down.
344
+
345
+ **The code card.** The code the assistant writes is drawn by `CodeCard`: the white card of the design system, the code in a grey panel in a code
346
+ editor's font, coloured, with its line count and a copy button. While the code arrives, **Prettier lays out what has arrived** (see
347
+ `src/lib/utils/codeStreamFormat.ts`): the text is cut after its last whole line, what is still open there is closed (`)`, `]`, `}` and the
348
+ closing tags), the result is formatted and cut again where the real text ended, and the line being typed follows as it was typed. When Prettier
349
+ refuses a cut (a function with no body yet), an earlier one is tried; when none works, the code is shown as written. Prettier is a dependency of
350
+ the chat and a dynamic import: a page that never shows code never loads it. Only scripts (JavaScript, TypeScript, JSX, TSX) are laid out; a page
351
+ or a Svelte component is shown as written. The card colours the code with highlight.js under its own class names (`wc-code-*`), so a highlight
352
+ theme of the page cannot repaint it.
353
+
354
+ A page that builds its own panel can use the pieces: `AgentAvatar`, `AgentTurn`, `CodeCard`, `GenerationModule` and `MemberAvatar`, and the rules they
355
+ follow: `liveAgentLook`, `settledAgentLook`, `turnOutcome`, `avatarStartAfter`, `keepFinishedGeneration` and `soundStateOf`.
356
+
357
+ To see it all on a real chat played by a pretend host, run `npm run dev` and open `/agent`. It loads the mascot and its sound from the
358
+ sibling `brand` checkout when it is there, and answers on `window.__agentDemo` for scripted checks. Query: `scenario=success|failure|question|stopped|plain`,
359
+ `run=1`, `step=1`, `speed=4`, `panel=0`, `rtl=1`, `mascot=0`, `sound=0`, `people=0`, `tight=0`.
360
+
290
361
  ## Languages
291
362
 
292
363
  The chat shows English until it is told otherwise. Two props of `Chat` change that, and both can change while the chat
@@ -3,6 +3,7 @@
3
3
  import { useChatLanguage } from '../i18n/language.js';
4
4
  import { fileSizeText } from '../i18n/labels.js';
5
5
  import { dirForUserText, useTextDirection } from '@widgetic/design-system/components/textDirection';
6
+ import { buildImageThumbnailUrl } from '../utils/imageTransform.js';
6
7
 
7
8
  // The words of the attachments, and the language the numbers of a size are written in
8
9
  const { t, locale } = useChatLanguage();
@@ -51,6 +52,15 @@
51
52
  };
52
53
  }
53
54
 
55
+ /**
56
+ * The key of an attachment in a keyed list. A saved message brings the id of its database row; an attachment that was just
57
+ * sent, or one a server answered without an id, has none, and two of them under the same key (`undefined`) stop the list
58
+ * (Svelte throws `each_key_duplicate`). The name, the address and the place in the list tell them apart.
59
+ */
60
+ function attachmentKey(attachment: ContentItemOutput, index: number): string {
61
+ return attachment.id || `${attachment.file_name ?? ''}|${attachment.url ?? ''}|${index}`;
62
+ }
63
+
54
64
  // Helper functions
55
65
  function getFileIcon(fileType: string): string {
56
66
  if (fileType.startsWith('image/')) return '🖼️';
@@ -132,13 +142,13 @@
132
142
  <!-- Message variant - inline in chat bubbles -->
133
143
  {#if variant === 'message'}
134
144
  <div class="message-attachments">
135
- {#each displayedAttachments as attachment (attachment.id)}
145
+ {#each displayedAttachments as attachment, index (attachmentKey(attachment, index))}
136
146
  <div class="message-attachment-item">
137
147
  {#if isImageType(attachment.file_type, attachment.url) && showPreview}
138
148
  <!-- svelte-ignore a11y_click_events_have_key_events -->
139
149
  <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
140
150
  <img
141
- src={attachment.url}
151
+ src={buildImageThumbnailUrl(attachment.url, 120) || attachment.url}
142
152
  alt={attachment.file_name || $t('chat.attachment.alt')}
143
153
  class="attachment-image"
144
154
  loading="lazy"
@@ -184,7 +194,7 @@
184
194
  <!-- Preview variant - larger display with remove buttons -->
185
195
  {:else if variant === 'preview'}
186
196
  <div class="preview-attachments">
187
- {#each displayedAttachments as attachment (attachment.id)}
197
+ {#each displayedAttachments as attachment, index (attachmentKey(attachment, index))}
188
198
  <div class="preview-attachment-item">
189
199
  {#if isImageType(attachment.file_type, attachment.url) && showPreview}
190
200
  <div class="preview-image-container">
@@ -257,7 +267,7 @@
257
267
  <!-- Compact variant - minimal space usage -->
258
268
  {:else if variant === 'compact'}
259
269
  <div class="compact-attachments">
260
- {#each displayedAttachments as attachment (attachment.id)}
270
+ {#each displayedAttachments as attachment, index (attachmentKey(attachment, index))}
261
271
  <button
262
272
  class="compact-attachment-item"
263
273
  onclick={() => handleView(attachment)}
@@ -10,11 +10,16 @@
10
10
  import type { ChatConfig, ChatContext } from '../types/index.js';
11
11
  import type { ClarificationSuggestion, DesignControlRequest, VersionRating } from '../types/message.js';
12
12
  import type { AttachmentInput, SelectedElementChatReference } from '../types/attachment.js';
13
+ import type { AgentAvatarRenderer, AgentSoundPlayer, ChatMember } from '../types/agent.js';
13
14
  import ChatMessages from './ChatMessages.svelte';
14
15
  import ChatComposer, { type ComposerModelOption } from './ChatComposer.svelte';
15
16
  import { Chip } from '@widgetic/design-system/components/chat/index';
16
17
  import ActionBar from './ActionBar.svelte';
17
18
  import PanelChatHeader from './PanelChatHeader.svelte';
19
+ import ComposerAttachmentsTray from './ComposerAttachmentsTray.svelte';
20
+ import { mergeSuggestionIntoDraft } from '../utils/suggestionDraft.js';
21
+ import { prepareChatImageFileForUpload } from '../utils/chatImageUploadPrep.js';
22
+ import { createLocalPreviewUrl, readAttachmentPreviewUrl } from '../utils/attachmentPreviewUrl.js';
18
23
  import StatusIndicator from './StatusIndicator.svelte';
19
24
  import { provideChatLanguage } from '../i18n/language.js';
20
25
  import { actionFailureKey, contextTypeLabel } from '../i18n/labels.js';
@@ -197,6 +202,34 @@
197
202
  * `conversationLineLabel`). When omitted, message text is shown as stored.
198
203
  */
199
204
  storedLineLabel?: (content: string) => string;
205
+ /**
206
+ * The people of the project's team. A message a person wrote gets that person's picture (or their initials) at its right, and
207
+ * their e-mail when the pointer rests on it, found by the `userId` the message carries. Left out (and without `currentUser`)
208
+ * the chat draws no faces next to what people wrote.
209
+ */
210
+ members?: ChatMember[];
211
+ /**
212
+ * The signed-in person: who wrote the messages they just sent (before the host has saved them and told the real id), and
213
+ * anything no member of `members` matches.
214
+ */
215
+ currentUser?: ChatMember | null;
216
+ /**
217
+ * How the assistant's avatar is drawn. The Widgetic apps pass the Scribble Mascot (`@widgetic/brand/mascot`). Left out, a plain
218
+ * round avatar is drawn, so the chat has no dependency on the mascot. See `AgentAvatarRenderer` for what it is called with.
219
+ */
220
+ renderAgentAvatar?: AgentAvatarRenderer;
221
+ /**
222
+ * Lets the assistant's avatar be heard: it is told the state of the avatar the person is looking at, once for each change (the
223
+ * mascot's `createMascotSound()` fits as it is). Left out, the chat is silent. Whether it sounds is up to the player (off until
224
+ * the person asks), so the page keeps the control for it. See `AgentSoundPlayer`.
225
+ */
226
+ agentSound?: AgentSoundPlayer;
227
+ /**
228
+ * Sizes the bubbles of what people wrote to their text with Pretext (https://chenglou.me/pretext/bubbles/): a bubble whose text
229
+ * wraps is as narrow as its widest line allows, not as wide as the chat, so no dead space is left beside short lines. A text that
230
+ * does not wrap, and a message with code blocks, keep the width CSS gives them. On by default; pass `false` for CSS's widths.
231
+ */
232
+ tightBubbles?: boolean;
200
233
  /** Show the Widget Element Selector toggle button in the action bar (disabled by default). */
201
234
  showSelector?: boolean;
202
235
  /** Whether the Widget Element Selector is currently active for this chat's widget. */
@@ -254,7 +287,7 @@
254
287
  updateLastUserMessageAttachments: (attachments: Array<{ id?: string; url: string; file_type?: string; file_name?: string | null }>) => void;
255
288
  }
256
289
 
257
- let { context, config = {}, class: className = '', locale = null, messages: languageMessages = null, dir = undefined, style = '', isCompleted = false, onStatsUpdate, onChatReady, onCompletionToggle, onSendMessage, onLoadConversations, onLoadMessages, onCreateConversation, onSaveMessage, onRestoreCheckpointBackend, onRateVersion, versionRatings: ratingsFromHost = {}, onTakeScreenshot, onConversationChange, onDraftChange, onRetryMessage, onUpgradePlans, onUploadChatFile, showHeader = true, showPanelHeader = false, showConsoleControl = false, sendNudgeToken = 0, consoleOpen = false, onToggleConsole, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize, onMessagesDrag, onMessagesDragEnd, onLoadOlderMessages, widgetHeadCommitSha = null, versionLabelByCommitSha = {}, versionLabelByPrompt = {}, versionTimeline = [], isGenerating = false, generationStream = '', generationThinking = '', generationPlan = null, onStopGeneration, renderDesignControls, actionBarExtras, completeReplacement, replaceComplete = false, showSelector = false, isSelectorActive = false, selectedElements = [], onToggleSelector, onRemoveSelectedElement, onClearSelectedElements, composerExtras, storedLineLabel, composerModels = [], selectedComposerModelId = null, onSelectComposerModel }: Props = $props();
290
+ let { context, config = {}, class: className = '', locale = null, messages: languageMessages = null, dir = undefined, style = '', isCompleted = false, onStatsUpdate, onChatReady, onCompletionToggle, onSendMessage, onLoadConversations, onLoadMessages, onCreateConversation, onSaveMessage, onRestoreCheckpointBackend, onRateVersion, versionRatings: ratingsFromHost = {}, onTakeScreenshot, onConversationChange, onDraftChange, onRetryMessage, onUpgradePlans, onUploadChatFile, showHeader = true, showPanelHeader = false, showConsoleControl = false, sendNudgeToken = 0, consoleOpen = false, onToggleConsole, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize, onMessagesDrag, onMessagesDragEnd, onLoadOlderMessages, widgetHeadCommitSha = null, versionLabelByCommitSha = {}, versionLabelByPrompt = {}, versionTimeline = [], isGenerating = false, generationStream = '', generationThinking = '', generationPlan = null, onStopGeneration, members = [], currentUser = null, renderAgentAvatar, agentSound, tightBubbles = true, renderDesignControls, actionBarExtras, completeReplacement, replaceComplete = false, showSelector = false, isSelectorActive = false, selectedElements = [], onToggleSelector, onRemoveSelectedElement, onClearSelectedElements, composerExtras, storedLineLabel, composerModels = [], selectedComposerModelId = null, onSelectComposerModel }: Props = $props();
258
291
 
259
292
  // The words of everything inside the chat, in the language the page chose. The page can change the language while the
260
293
  // chat is open: the settings are read again whenever they change (and setting the same language again does nothing).
@@ -324,6 +357,10 @@
324
357
 
325
358
  // Local input state per chat instance (instead of shared store state)
326
359
  let localInputText = $state('');
360
+ /** Intent from a clarification chip filled into the draft until the person sends or edits it away. */
361
+ let pendingChipIntent = $state<ClarificationSuggestion['intent'] | null>(null);
362
+ let pendingSkipIntentGate = $state(false);
363
+ let skipNextDraftIntentClear = $state(false);
327
364
  let localAttachments = $state<AttachmentInput[]>([]);
328
365
  let localIsRecording = $state(false);
329
366
  let localIsSending = $state(false);
@@ -603,6 +640,11 @@
603
640
  });
604
641
 
605
642
  currentConversationId = conversationId;
643
+ chatStore.actions.setMessages(conversationId, []);
644
+ showEmptyState = true;
645
+ clearDraft();
646
+ onConversationChange?.(conversationId);
647
+ focusComposerTextarea();
606
648
  return conversation;
607
649
  } catch (error) {
608
650
  console.error('Failed to create conversation:', error);
@@ -630,6 +672,13 @@
630
672
  }
631
673
 
632
674
  async function sendMessage(content: string, attachments?: Array<File | AttachmentInput>, options?: { skipIntentGate?: boolean; chipIntent?: ClarificationSuggestion['intent'] }) {
675
+ const mergedOptions = {
676
+ ...options,
677
+ chipIntent: options?.chipIntent ?? pendingChipIntent ?? undefined,
678
+ skipIntentGate: options?.skipIntentGate === true || pendingSkipIntentGate,
679
+ };
680
+ pendingChipIntent = null;
681
+ pendingSkipIntentGate = false;
633
682
  if (!currentConversationId) {
634
683
  if (initializePromise) {
635
684
  try {
@@ -774,8 +823,8 @@
774
823
  submittedContent,
775
824
  outgoing.length > 0 ? outgoing : undefined,
776
825
  submittedSelectedElements
777
- ? { ...options, selectedElements: submittedSelectedElements }
778
- : options
826
+ ? { ...mergedOptions, selectedElements: submittedSelectedElements }
827
+ : mergedOptions
779
828
  );
780
829
  } else {
781
830
  const aiResponse = await chatService.processAIResponse(activeConversationId, userMessage);
@@ -1000,9 +1049,8 @@
1000
1049
  options: { source?: string } = {},
1001
1050
  ): Promise<void> {
1002
1051
  if (!onUploadChatFile || !isCdnUploadableFile(file)) {
1003
- if (file.type.startsWith('image/') || file.type.startsWith('video/') || file.type === 'application/pdf') {
1004
- entry.preview = URL.createObjectURL(file);
1005
- }
1052
+ // Only when the file was attached without a picture: one `blob:` address per file, never a second one.
1053
+ if (!entry.preview) entry.preview = createLocalPreviewUrl(file);
1006
1054
  return;
1007
1055
  }
1008
1056
 
@@ -1015,13 +1063,8 @@
1015
1063
  entry.uploadedUrl = uploaded.url;
1016
1064
  entry.uploadId = uploaded.id;
1017
1065
  if (file.type.startsWith('image/') || file.type.startsWith('video/') || file.type === 'application/pdf') {
1018
- if (entry.preview && entry.preview.startsWith('blob:')) {
1019
- try {
1020
- URL.revokeObjectURL(entry.preview);
1021
- } catch {
1022
- /* ignore error */
1023
- }
1024
- }
1066
+ // The local picture is not given back here: the tray holds a copy of this attachment (the progress update
1067
+ // replaces it) and keeps drawing that picture. `removeFooterAttachment` and `clearDraft` give it back.
1025
1068
  entry.preview = uploaded.url;
1026
1069
  }
1027
1070
  entry.uploadProgress = 100;
@@ -1031,9 +1074,7 @@
1031
1074
  // chatLog('[Chat] Attachment uploaded to CDN:', uploaded.url.slice(0, 80), 'id:', uploaded.id);
1032
1075
  } catch (uploadError) {
1033
1076
  console.error('[Chat] Upload failed, using local preview where possible:', uploadError);
1034
- if (file.type.startsWith('image/') || file.type.startsWith('video/') || file.type === 'application/pdf') {
1035
- entry.preview = URL.createObjectURL(file);
1036
- }
1077
+ if (!entry.preview) entry.preview = createLocalPreviewUrl(file);
1037
1078
  entry.uploadProgress = 0;
1038
1079
  bumpAttachmentProgress(attachmentIndex, 0);
1039
1080
  // Soft warning only — local File still works for codegen vision; don't block the chat UI.
@@ -1064,17 +1105,10 @@
1064
1105
  );
1065
1106
  }
1066
1107
 
1108
+ // Read only: the tray calls this inside a derived value, where Svelte does not allow a write to state (a write there
1109
+ // threw, the catch below it turned that into '' and the photo tile stayed empty). The picture is made when the file is attached.
1067
1110
  function getFooterAttachmentPreviewUrl(attachment: AttachmentInput): string {
1068
- if (attachment.preview) return attachment.preview;
1069
- if (attachment.uploadedUrl) return attachment.uploadedUrl;
1070
- if (!attachment.file) return '';
1071
- try {
1072
- const objectUrl = URL.createObjectURL(attachment.file);
1073
- attachment.preview = objectUrl;
1074
- return objectUrl;
1075
- } catch {
1076
- return '';
1077
- }
1111
+ return readAttachmentPreviewUrl(attachment);
1078
1112
  }
1079
1113
 
1080
1114
  function removeFooterAttachment(index: number) {
@@ -1133,8 +1167,13 @@
1133
1167
  }
1134
1168
 
1135
1169
  async function addFilesAsAttachments(files: File[]) {
1136
- const usableFiles = (files || []).filter((file) => file && file.size > 0);
1137
- if (usableFiles.length === 0) return;
1170
+ const incoming = (files || []).filter((file) => file && file.size > 0);
1171
+ if (incoming.length === 0) return;
1172
+ const usableFiles = await Promise.all(
1173
+ incoming.map(async (file) =>
1174
+ file.type.startsWith('image/') ? await prepareChatImageFileForUpload(file) : file,
1175
+ ),
1176
+ );
1138
1177
 
1139
1178
  const previousCount = localAttachments.length;
1140
1179
  const newAttachments: AttachmentInput[] = usableFiles.map((file) => ({
@@ -1144,6 +1183,8 @@
1144
1183
  : file.type.startsWith('video/')
1145
1184
  ? 'video'
1146
1185
  : 'document',
1186
+ // The picture the tray draws: made now, once, because the tray cannot write it while it draws.
1187
+ preview: createLocalPreviewUrl(file),
1147
1188
  uploadProgress: 0,
1148
1189
  }));
1149
1190
 
@@ -1216,45 +1257,43 @@
1216
1257
  showFailure(actionFailureKey(detail.type));
1217
1258
  }
1218
1259
 
1219
- function handleSuggestionSelected(suggestion: string) {
1220
- const trimmed = suggestion.trim();
1221
- if (!trimmed) return;
1222
- // A suggestion (the empty-state cards and the "Try next" follow-ups of the panel alike) goes into the input and is
1223
- // not sent: the person reviews it, edits it, attaches a picture, and presses Send.
1224
- setDraftText(trimmed);
1225
- }
1226
-
1227
- /** Tapping a suggestion chip attached to an assistant clarification card sends it
1228
- * as the next user message. These suggestions resolve an ambiguity the intent
1229
- * gate already detected server-side, so each is a complete, valid ask — the
1230
- * card exists precisely to save the user from retyping it. Generic
1231
- * SuggestionButtons (empty state) keep their autocomplete behavior instead.
1232
- *
1233
- * Chips are structured objects ({ label, intent }): the label is display copy
1234
- * rendered verbatim, the intent is machine-readable behavior. The "generate
1235
- * anyway" chip is the card's escape hatch — identified by
1236
- * `intent === 'generate_anyway'`, never by matching its text — and re-sends
1237
- * with `skipIntentGate: true` (the server's own JSDoc for that flag says "set
1238
- * when the user explicitly chose to generate anyway after a gated response",
1239
- * and a chip tap is exactly that choice). Without the flag the server's
1240
- * verdict cache would re-serve the same card for the same message and the
1241
- * chip could never escape it. The refine chips send normally — they are new
1242
- * asks, and an ask that is still ambiguous should get the card again. The
1243
- * chip's intent rides the request as `chipIntent` so the server measures the
1244
- * conversion from the client's declaration instead of matching copy. */
1245
- async function handleClarificationSuggestionSelected(suggestion: ClarificationSuggestion) {
1246
- const trimmed = suggestion.label.trim();
1260
+ function focusComposerTextarea() {
1261
+ if (typeof document === 'undefined') return;
1262
+ const root = chatContainer?.querySelector('.chat-composer-shell');
1263
+ const textarea = root?.querySelector('textarea');
1264
+ if (textarea instanceof HTMLTextAreaElement) {
1265
+ textarea.focus();
1266
+ const length = textarea.value.length;
1267
+ textarea.setSelectionRange(length, length);
1268
+ }
1269
+ }
1270
+
1271
+ function fillDraftFromSuggestion(label: string, intent?: ClarificationSuggestion['intent']) {
1272
+ const trimmed = label.trim();
1247
1273
  if (!trimmed) return;
1248
- if (isGenerating || localIsSending || isSendingOrLoading) return;
1249
- try {
1250
- await sendMessage(trimmed, undefined, {
1251
- skipIntentGate: suggestion.intent === 'generate_anyway',
1252
- chipIntent: suggestion.intent,
1253
- });
1254
- } catch (err) {
1255
- console.error('[Chat] Clarification suggestion send failed:', err);
1256
- showFailure('chat.error.sendSuggestion');
1274
+ localInputText = mergeSuggestionIntoDraft(localInputText, trimmed);
1275
+ if (intent) {
1276
+ pendingChipIntent = intent;
1277
+ pendingSkipIntentGate = intent === 'generate_anyway';
1278
+ } else {
1279
+ pendingChipIntent = null;
1280
+ pendingSkipIntentGate = false;
1257
1281
  }
1282
+ notifyDraftChange();
1283
+ skipNextDraftIntentClear = true;
1284
+ queueMicrotask(() => focusComposerTextarea());
1285
+ }
1286
+
1287
+ function handleSuggestionSelected(suggestion: string) {
1288
+ if (!suggestion.trim()) return;
1289
+ fillDraftFromSuggestion(suggestion);
1290
+ }
1291
+
1292
+ /** Clarification chips fill the composer like other suggestions; chipIntent is kept on the draft until send. */
1293
+ function handleClarificationSuggestionSelected(suggestion: ClarificationSuggestion) {
1294
+ if (!suggestion.label.trim()) return;
1295
+ if (isGenerating || localIsSending || isSendingOrLoading) return;
1296
+ fillDraftFromSuggestion(suggestion.label, suggestion.intent);
1258
1297
  }
1259
1298
 
1260
1299
  async function handleRetryMessage(content: string) {
@@ -1446,6 +1485,8 @@
1446
1485
 
1447
1486
  function setDraftText(text: string) {
1448
1487
  localInputText = text;
1488
+ pendingChipIntent = null;
1489
+ pendingSkipIntentGate = false;
1449
1490
  }
1450
1491
 
1451
1492
  function getAttachmentDataUrls(): string[] {
@@ -1504,6 +1545,8 @@
1504
1545
  }
1505
1546
  localInputText = '';
1506
1547
  localAttachments = [];
1548
+ pendingChipIntent = null;
1549
+ pendingSkipIntentGate = false;
1507
1550
  notifyDraftChange();
1508
1551
  }
1509
1552
 
@@ -1995,6 +2038,7 @@
1995
2038
  conversations={availableConversations}
1996
2039
  currentConversationId={currentConversationId}
1997
2040
  onSelectConversation={(id) => void loadConversation(id)}
2041
+ isGenerating={isGenerating || localIsSending}
1998
2042
  />
1999
2043
  {:else if showHeader}
2000
2044
  <!-- Simple Chat Header -->
@@ -2064,6 +2108,12 @@
2064
2108
  onClarificationSuggestionSelected={handleClarificationSuggestionSelected}
2065
2109
  {renderDesignControls}
2066
2110
  {storedLineLabel}
2111
+ conversationId={currentConversationId}
2112
+ {members}
2113
+ {currentUser}
2114
+ {renderAgentAvatar}
2115
+ {agentSound}
2116
+ {tightBubbles}
2067
2117
  />
2068
2118
  </div>
2069
2119
 
@@ -2084,7 +2134,7 @@
2084
2134
  {/if}
2085
2135
 
2086
2136
  <div
2087
- class="prompt-chat-footer-ct shrink-0 flex flex-col {showPanelHeader ? 'px-4 pb-4 max-lg:px-3' : ''}"
2137
+ class="prompt-chat-footer-ct shrink-0 flex flex-col {showPanelHeader ? 'px-3 pb-4 max-lg:px-3' : ''}"
2088
2138
  >
2089
2139
  {#if showActionBar}
2090
2140
  <ActionBar
@@ -2156,46 +2206,15 @@
2156
2206
  {/if}
2157
2207
 
2158
2208
  {#if localAttachments.length > 0}
2159
- <div class="prompt-chat-attachments-tray-ct flex flex-wrap gap-2 p-3 border-t border-gray-100 bg-white shrink-0">
2160
- {#each localAttachments as attachment, index (attachment.preview || attachment.uploadedUrl || attachment.file?.name || index)}
2161
- <div class="prompt-chat-attachment-item-ct relative bg-gray-50 rounded-lg overflow-hidden">
2162
- <span class="prompt-chat-attachment-index-badge absolute top-0.5 start-0.5 z-10 w-4 h-4 flex items-center justify-center rounded-full bg-blue-600 text-white text-[9px] font-bold shadow">{index + 1}</span>
2163
- {#if isImageAttachment(attachment)}
2164
- <!-- svelte-ignore a11y_click_events_have_key_events -->
2165
- <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
2166
- <img
2167
- src={getFooterAttachmentPreviewUrl(attachment)}
2168
- alt={attachment.file?.name || $t('chat.attachment.namelessAlt')}
2169
- class="prompt-chat-attachment-image-preview w-16 h-16 object-cover cursor-pointer"
2170
- onclick={() => {
2171
- const previewUrl = getFooterAttachmentPreviewUrl(attachment);
2172
- if (previewUrl) footerLightboxSrc = previewUrl;
2173
- }}
2174
- />
2175
- {:else}
2176
- <div class="prompt-chat-attachment-file-preview flex items-center gap-2 p-3 w-32">
2177
- <span class="text-lg">📄</span>
2178
- <span class="text-xs text-gray-600 truncate flex-1">{attachment.file?.name || $t('chat.attachment.namelessAlt')}</span>
2179
- </div>
2180
- {/if}
2181
-
2182
- <button
2183
- type="button"
2184
- class="prompt-chat-remove-attachment-btn absolute top-1 end-1 w-5 h-5 bg-red-500 text-white rounded-full flex items-center justify-center text-xs hover:bg-red-600 cursor-pointer"
2185
- onclick={() => removeFooterAttachment(index)}
2186
- aria-label={$t('chat.attachment.remove')}
2187
- >
2188
- ✕
2189
- </button>
2190
-
2191
- {#if attachment.uploadProgress && attachment.uploadProgress > 0 && attachment.uploadProgress < 100}
2192
- <div class="prompt-chat-attachment-upload-bar absolute bottom-0 start-0 end-0 h-1 bg-gray-200">
2193
- <div class="h-full bg-blue-500 transition-all duration-300" style="width: {attachment.uploadProgress}%"></div>
2194
- </div>
2195
- {/if}
2196
- </div>
2197
- {/each}
2198
- </div>
2209
+ <ComposerAttachmentsTray
2210
+ attachments={localAttachments}
2211
+ previewUrl={getFooterAttachmentPreviewUrl}
2212
+ isImage={isImageAttachment}
2213
+ onRemove={removeFooterAttachment}
2214
+ onOpenPreview={(url) => {
2215
+ footerLightboxSrc = url;
2216
+ }}
2217
+ />
2199
2218
  {/if}
2200
2219
 
2201
2220
  <ChatComposer
@@ -2208,6 +2227,12 @@
2208
2227
  : undefined}
2209
2228
  bind:value={() => localInputText, (nextInputText) => {
2210
2229
  localInputText = nextInputText;
2230
+ if (skipNextDraftIntentClear) {
2231
+ skipNextDraftIntentClear = false;
2232
+ } else {
2233
+ pendingChipIntent = null;
2234
+ pendingSkipIntentGate = false;
2235
+ }
2211
2236
  notifyDraftChange();
2212
2237
  }}
2213
2238
  isSending={localIsSending}
@@ -3,6 +3,7 @@ import { type TextDirection } from '@widgetic/design-system/components/textDirec
3
3
  import type { ChatConfig, ChatContext } from '../types/index.js';
4
4
  import type { ClarificationSuggestion, DesignControlRequest, VersionRating } from '../types/message.js';
5
5
  import type { AttachmentInput, SelectedElementChatReference } from '../types/attachment.js';
6
+ import type { AgentAvatarRenderer, AgentSoundPlayer, ChatMember } from '../types/agent.js';
6
7
  import { type ComposerModelOption } from './ChatComposer.svelte';
7
8
  interface ChatMethods {
8
9
  sendMessage: (content: string, attachments?: Array<File | AttachmentInput>, options?: {
@@ -240,6 +241,34 @@ interface Props {
240
241
  * `conversationLineLabel`). When omitted, message text is shown as stored.
241
242
  */
242
243
  storedLineLabel?: (content: string) => string;
244
+ /**
245
+ * The people of the project's team. A message a person wrote gets that person's picture (or their initials) at its right, and
246
+ * their e-mail when the pointer rests on it, found by the `userId` the message carries. Left out (and without `currentUser`)
247
+ * the chat draws no faces next to what people wrote.
248
+ */
249
+ members?: ChatMember[];
250
+ /**
251
+ * The signed-in person: who wrote the messages they just sent (before the host has saved them and told the real id), and
252
+ * anything no member of `members` matches.
253
+ */
254
+ currentUser?: ChatMember | null;
255
+ /**
256
+ * How the assistant's avatar is drawn. The Widgetic apps pass the Scribble Mascot (`@widgetic/brand/mascot`). Left out, a plain
257
+ * round avatar is drawn, so the chat has no dependency on the mascot. See `AgentAvatarRenderer` for what it is called with.
258
+ */
259
+ renderAgentAvatar?: AgentAvatarRenderer;
260
+ /**
261
+ * Lets the assistant's avatar be heard: it is told the state of the avatar the person is looking at, once for each change (the
262
+ * mascot's `createMascotSound()` fits as it is). Left out, the chat is silent. Whether it sounds is up to the player (off until
263
+ * the person asks), so the page keeps the control for it. See `AgentSoundPlayer`.
264
+ */
265
+ agentSound?: AgentSoundPlayer;
266
+ /**
267
+ * Sizes the bubbles of what people wrote to their text with Pretext (https://chenglou.me/pretext/bubbles/): a bubble whose text
268
+ * wraps is as narrow as its widest line allows, not as wide as the chat, so no dead space is left beside short lines. A text that
269
+ * does not wrap, and a message with code blocks, keep the width CSS gives them. On by default; pass `false` for CSS's widths.
270
+ */
271
+ tightBubbles?: boolean;
243
272
  /** Show the Widget Element Selector toggle button in the action bar (disabled by default). */
244
273
  showSelector?: boolean;
245
274
  /** Whether the Widget Element Selector is currently active for this chat's widget. */
@@ -59,6 +59,10 @@
59
59
 
60
60
  const composerSendIcon = $derived(panelLayout ? 'arrow-up' : sendIcon);
61
61
 
62
+ // 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
+ // that is used then), never a generic word such as "Assistant": the person knows what they are talking to.
64
+ const fallbackModelLabel = $derived(models?.[0]?.label?.trim() ?? '');
65
+
62
66
  let isFileDragOver = $state(false);
63
67
  let sendNudgePhase = $state<SendNudgePhase>('idle');
64
68
  let sendNudgeBounce = $state(false);
@@ -220,7 +224,7 @@
220
224
  attach: $t('chat.actions.upload'),
221
225
  characterLimit: $t('chat.input.tooLong')
222
226
  }}
223
- assistantLabel={$t('chat.composer.assistant')}
227
+ assistantLabel={fallbackModelLabel}
224
228
  onSend={handleComposerSend}
225
229
  onStop={() => onStop?.()}
226
230
  leading={attachControl}