@widgetic/chat 0.1.37 → 0.1.39

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 (36) hide show
  1. package/dist/components/AttachmentDisplay.svelte +14 -4
  2. package/dist/components/Chat.svelte +155 -116
  3. package/dist/components/Chat.svelte.d.ts +4 -0
  4. package/dist/components/ChatComposer.svelte +63 -0
  5. package/dist/components/ChatComposer.svelte.d.ts +2 -0
  6. package/dist/components/ChatMessages.svelte +129 -20
  7. package/dist/components/ChatMessages.svelte.d.ts +2 -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/i18n/index.d.ts +1 -0
  16. package/dist/i18n/index.js +1 -0
  17. package/dist/i18n/messages.d.ts +4 -1
  18. package/dist/i18n/messages.js +4 -1
  19. package/dist/i18n/publishNudgeLocales.d.ts +18 -0
  20. package/dist/i18n/publishNudgeLocales.js +17 -0
  21. package/dist/sendNudgeState.d.ts +5 -0
  22. package/dist/sendNudgeState.js +18 -0
  23. package/dist/types/attachment.d.ts +5 -0
  24. package/dist/utils/attachmentPreviewUrl.d.ts +21 -0
  25. package/dist/utils/attachmentPreviewUrl.js +39 -0
  26. package/dist/utils/chatImageUploadPrep.d.ts +22 -0
  27. package/dist/utils/chatImageUploadPrep.js +90 -0
  28. package/dist/utils/generationArchiveStore.d.ts +10 -0
  29. package/dist/utils/generationArchiveStore.js +88 -0
  30. package/dist/utils/imageTransform.d.ts +12 -0
  31. package/dist/utils/imageTransform.js +45 -0
  32. package/dist/utils/linkifyText.d.ts +16 -0
  33. package/dist/utils/linkifyText.js +57 -0
  34. package/dist/utils/suggestionDraft.d.ts +5 -0
  35. package/dist/utils/suggestionDraft.js +15 -0
  36. package/package.json +3 -3
@@ -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)}
@@ -15,6 +15,10 @@
15
15
  import { Chip } from '@widgetic/design-system/components/chat/index';
16
16
  import ActionBar from './ActionBar.svelte';
17
17
  import PanelChatHeader from './PanelChatHeader.svelte';
18
+ import ComposerAttachmentsTray from './ComposerAttachmentsTray.svelte';
19
+ import { mergeSuggestionIntoDraft } from '../utils/suggestionDraft.js';
20
+ import { prepareChatImageFileForUpload } from '../utils/chatImageUploadPrep.js';
21
+ import { createLocalPreviewUrl, readAttachmentPreviewUrl } from '../utils/attachmentPreviewUrl.js';
18
22
  import StatusIndicator from './StatusIndicator.svelte';
19
23
  import { provideChatLanguage } from '../i18n/language.js';
20
24
  import { actionFailureKey, contextTypeLabel } from '../i18n/labels.js';
@@ -123,6 +127,8 @@
123
127
  showPanelHeader?: boolean;
124
128
  /** When true with `onToggleConsole`, shows the debug console icon in the panel header. */
125
129
  showConsoleControl?: boolean;
130
+ /** Increment to bounce the Send button and show the publish-first tooltip (host-driven). */
131
+ sendNudgeToken?: number;
126
132
  consoleOpen?: boolean;
127
133
  onToggleConsole?: () => void;
128
134
  /** Custom title displayed in the header. If empty/undefined, defaults to context.title or context.id. */
@@ -230,6 +236,8 @@
230
236
  setDraftText: (text: string) => void;
231
237
  /** Get attachment preview data URLs in current order. */
232
238
  getAttachmentDataUrls: () => string[];
239
+ /** Attached pictures as `data:` URLs, the form the draft keeps so they are still attached after a refresh. */
240
+ getDraftAttachmentDataUrls: () => string[];
233
241
  /** Get CDN upload row IDs for image attachments (codegen attachmentIds). */
234
242
  getAttachmentUploadIds: () => string[];
235
243
  /** Replace chat attachments from stored data URLs (restores draft attachments). */
@@ -250,7 +258,7 @@
250
258
  updateLastUserMessageAttachments: (attachments: Array<{ id?: string; url: string; file_type?: string; file_name?: string | null }>) => void;
251
259
  }
252
260
 
253
- 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, 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();
261
+ 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();
254
262
 
255
263
  // The words of everything inside the chat, in the language the page chose. The page can change the language while the
256
264
  // chat is open: the settings are read again whenever they change (and setting the same language again does nothing).
@@ -320,6 +328,10 @@
320
328
 
321
329
  // Local input state per chat instance (instead of shared store state)
322
330
  let localInputText = $state('');
331
+ /** Intent from a clarification chip filled into the draft until the person sends or edits it away. */
332
+ let pendingChipIntent = $state<ClarificationSuggestion['intent'] | null>(null);
333
+ let pendingSkipIntentGate = $state(false);
334
+ let skipNextDraftIntentClear = $state(false);
323
335
  let localAttachments = $state<AttachmentInput[]>([]);
324
336
  let localIsRecording = $state(false);
325
337
  let localIsSending = $state(false);
@@ -599,6 +611,11 @@
599
611
  });
600
612
 
601
613
  currentConversationId = conversationId;
614
+ chatStore.actions.setMessages(conversationId, []);
615
+ showEmptyState = true;
616
+ clearDraft();
617
+ onConversationChange?.(conversationId);
618
+ focusComposerTextarea();
602
619
  return conversation;
603
620
  } catch (error) {
604
621
  console.error('Failed to create conversation:', error);
@@ -626,6 +643,13 @@
626
643
  }
627
644
 
628
645
  async function sendMessage(content: string, attachments?: Array<File | AttachmentInput>, options?: { skipIntentGate?: boolean; chipIntent?: ClarificationSuggestion['intent'] }) {
646
+ const mergedOptions = {
647
+ ...options,
648
+ chipIntent: options?.chipIntent ?? pendingChipIntent ?? undefined,
649
+ skipIntentGate: options?.skipIntentGate === true || pendingSkipIntentGate,
650
+ };
651
+ pendingChipIntent = null;
652
+ pendingSkipIntentGate = false;
629
653
  if (!currentConversationId) {
630
654
  if (initializePromise) {
631
655
  try {
@@ -770,8 +794,8 @@
770
794
  submittedContent,
771
795
  outgoing.length > 0 ? outgoing : undefined,
772
796
  submittedSelectedElements
773
- ? { ...options, selectedElements: submittedSelectedElements }
774
- : options
797
+ ? { ...mergedOptions, selectedElements: submittedSelectedElements }
798
+ : mergedOptions
775
799
  );
776
800
  } else {
777
801
  const aiResponse = await chatService.processAIResponse(activeConversationId, userMessage);
@@ -996,9 +1020,8 @@
996
1020
  options: { source?: string } = {},
997
1021
  ): Promise<void> {
998
1022
  if (!onUploadChatFile || !isCdnUploadableFile(file)) {
999
- if (file.type.startsWith('image/') || file.type.startsWith('video/') || file.type === 'application/pdf') {
1000
- entry.preview = URL.createObjectURL(file);
1001
- }
1023
+ // Only when the file was attached without a picture: one `blob:` address per file, never a second one.
1024
+ if (!entry.preview) entry.preview = createLocalPreviewUrl(file);
1002
1025
  return;
1003
1026
  }
1004
1027
 
@@ -1011,13 +1034,8 @@
1011
1034
  entry.uploadedUrl = uploaded.url;
1012
1035
  entry.uploadId = uploaded.id;
1013
1036
  if (file.type.startsWith('image/') || file.type.startsWith('video/') || file.type === 'application/pdf') {
1014
- if (entry.preview && entry.preview.startsWith('blob:')) {
1015
- try {
1016
- URL.revokeObjectURL(entry.preview);
1017
- } catch {
1018
- /* ignore error */
1019
- }
1020
- }
1037
+ // The local picture is not given back here: the tray holds a copy of this attachment (the progress update
1038
+ // replaces it) and keeps drawing that picture. `removeFooterAttachment` and `clearDraft` give it back.
1021
1039
  entry.preview = uploaded.url;
1022
1040
  }
1023
1041
  entry.uploadProgress = 100;
@@ -1027,9 +1045,7 @@
1027
1045
  // chatLog('[Chat] Attachment uploaded to CDN:', uploaded.url.slice(0, 80), 'id:', uploaded.id);
1028
1046
  } catch (uploadError) {
1029
1047
  console.error('[Chat] Upload failed, using local preview where possible:', uploadError);
1030
- if (file.type.startsWith('image/') || file.type.startsWith('video/') || file.type === 'application/pdf') {
1031
- entry.preview = URL.createObjectURL(file);
1032
- }
1048
+ if (!entry.preview) entry.preview = createLocalPreviewUrl(file);
1033
1049
  entry.uploadProgress = 0;
1034
1050
  bumpAttachmentProgress(attachmentIndex, 0);
1035
1051
  // Soft warning only — local File still works for codegen vision; don't block the chat UI.
@@ -1060,17 +1076,10 @@
1060
1076
  );
1061
1077
  }
1062
1078
 
1079
+ // Read only: the tray calls this inside a derived value, where Svelte does not allow a write to state (a write there
1080
+ // threw, the catch below it turned that into '' and the photo tile stayed empty). The picture is made when the file is attached.
1063
1081
  function getFooterAttachmentPreviewUrl(attachment: AttachmentInput): string {
1064
- if (attachment.preview) return attachment.preview;
1065
- if (attachment.uploadedUrl) return attachment.uploadedUrl;
1066
- if (!attachment.file) return '';
1067
- try {
1068
- const objectUrl = URL.createObjectURL(attachment.file);
1069
- attachment.preview = objectUrl;
1070
- return objectUrl;
1071
- } catch {
1072
- return '';
1073
- }
1082
+ return readAttachmentPreviewUrl(attachment);
1074
1083
  }
1075
1084
 
1076
1085
  function removeFooterAttachment(index: number) {
@@ -1089,9 +1098,53 @@
1089
1098
 
1090
1099
  let footerLightboxSrc: string | null = $state(null);
1091
1100
 
1101
+ /** Biggest image kept in the draft: a draft is written to the browser's storage on every change. */
1102
+ const MAX_PERSISTED_IMAGE_BYTES = 6 * 1024 * 1024;
1103
+
1104
+ /** Reads an attached image into a `data:` URL for the draft; resolves to '' when it cannot or should not be kept. */
1105
+ function readImageAsDataUrl(file: File): Promise<string> {
1106
+ return new Promise((resolve) => {
1107
+ if (!file.type.startsWith('image/') || file.size > MAX_PERSISTED_IMAGE_BYTES) {
1108
+ resolve('');
1109
+ return;
1110
+ }
1111
+ try {
1112
+ const reader = new FileReader();
1113
+ reader.onload = () => resolve(typeof reader.result === 'string' ? reader.result : '');
1114
+ reader.onerror = () => {
1115
+ chatWarn('[Chat] Could not read the image for the draft:', file.name);
1116
+ resolve('');
1117
+ };
1118
+ reader.readAsDataURL(file);
1119
+ } catch (error) {
1120
+ chatWarn('[Chat] Could not read the image for the draft:', error);
1121
+ resolve('');
1122
+ }
1123
+ });
1124
+ }
1125
+
1126
+ /** Keeps an attached image in the draft, so it is still attached after a refresh. */
1127
+ async function rememberImageForDraft(entry: AttachmentInput): Promise<void> {
1128
+ const dataUrl = await readImageAsDataUrl(entry.file);
1129
+ if (!dataUrl) return;
1130
+ entry.persistedDataUrl = dataUrl;
1131
+ // The attachment may have been removed while the file was read: only a tray that still holds it is saved.
1132
+ // It is set on the object the tray holds now, not on a copy: the upload keeps writing to that object.
1133
+ const inTray = localAttachments.find((att) => att.file === entry.file);
1134
+ if (!inTray) return;
1135
+ inTray.persistedDataUrl = dataUrl;
1136
+ localAttachments = [...localAttachments];
1137
+ notifyDraftChange();
1138
+ }
1139
+
1092
1140
  async function addFilesAsAttachments(files: File[]) {
1093
- const usableFiles = (files || []).filter((file) => file && file.size > 0);
1094
- if (usableFiles.length === 0) return;
1141
+ const incoming = (files || []).filter((file) => file && file.size > 0);
1142
+ if (incoming.length === 0) return;
1143
+ const usableFiles = await Promise.all(
1144
+ incoming.map(async (file) =>
1145
+ file.type.startsWith('image/') ? await prepareChatImageFileForUpload(file) : file,
1146
+ ),
1147
+ );
1095
1148
 
1096
1149
  const previousCount = localAttachments.length;
1097
1150
  const newAttachments: AttachmentInput[] = usableFiles.map((file) => ({
@@ -1101,6 +1154,8 @@
1101
1154
  : file.type.startsWith('video/')
1102
1155
  ? 'video'
1103
1156
  : 'document',
1157
+ // The picture the tray draws: made now, once, because the tray cannot write it while it draws.
1158
+ preview: createLocalPreviewUrl(file),
1104
1159
  uploadProgress: 0,
1105
1160
  }));
1106
1161
 
@@ -1110,6 +1165,8 @@
1110
1165
  expandChatForAttachmentGrowth(previousCount);
1111
1166
  chatStore.actions.updateUI({ errorMessage: null });
1112
1167
  console.log('[Chat] attachments now', localAttachments.length);
1168
+ // The draft keeps each picture as it is attached, before the upload ends (a refresh can come at any time).
1169
+ for (const entry of newAttachments) void rememberImageForDraft(entry);
1113
1170
 
1114
1171
  try {
1115
1172
  localIsUploading = true;
@@ -1171,55 +1228,43 @@
1171
1228
  showFailure(actionFailureKey(detail.type));
1172
1229
  }
1173
1230
 
1174
- async function handleSuggestionSelected(suggestion: string) {
1175
- const trimmed = suggestion.trim();
1176
- if (!trimmed) return;
1177
- if (showPanelHeader) {
1178
- if (isGenerating || localIsSending || isSendingOrLoading) return;
1179
- try {
1180
- await sendMessage(trimmed, undefined, { skipIntentGate: true });
1181
- } catch (err) {
1182
- console.error('[Chat] Panel suggestion send failed:', err);
1183
- showFailure('chat.error.sendSuggestion');
1184
- }
1185
- return;
1231
+ function focusComposerTextarea() {
1232
+ if (typeof document === 'undefined') return;
1233
+ const root = chatContainer?.querySelector('.chat-composer-shell');
1234
+ const textarea = root?.querySelector('textarea');
1235
+ if (textarea instanceof HTMLTextAreaElement) {
1236
+ textarea.focus();
1237
+ const length = textarea.value.length;
1238
+ textarea.setSelectionRange(length, length);
1186
1239
  }
1187
- // Autocomplete into input instead of sending immediately — lets user review,
1188
- // edit, and attach an image before sending.
1189
- setDraftText(trimmed);
1190
- }
1191
-
1192
- /** Tapping a suggestion chip attached to an assistant clarification card sends it
1193
- * as the next user message. These suggestions resolve an ambiguity the intent
1194
- * gate already detected server-side, so each is a complete, valid ask — the
1195
- * card exists precisely to save the user from retyping it. Generic
1196
- * SuggestionButtons (empty state) keep their autocomplete behavior instead.
1197
- *
1198
- * Chips are structured objects ({ label, intent }): the label is display copy
1199
- * rendered verbatim, the intent is machine-readable behavior. The "generate
1200
- * anyway" chip is the card's escape hatch — identified by
1201
- * `intent === 'generate_anyway'`, never by matching its text — and re-sends
1202
- * with `skipIntentGate: true` (the server's own JSDoc for that flag says "set
1203
- * when the user explicitly chose to generate anyway after a gated response",
1204
- * and a chip tap is exactly that choice). Without the flag the server's
1205
- * verdict cache would re-serve the same card for the same message and the
1206
- * chip could never escape it. The refine chips send normally — they are new
1207
- * asks, and an ask that is still ambiguous should get the card again. The
1208
- * chip's intent rides the request as `chipIntent` so the server measures the
1209
- * conversion from the client's declaration instead of matching copy. */
1210
- async function handleClarificationSuggestionSelected(suggestion: ClarificationSuggestion) {
1211
- const trimmed = suggestion.label.trim();
1240
+ }
1241
+
1242
+ function fillDraftFromSuggestion(label: string, intent?: ClarificationSuggestion['intent']) {
1243
+ const trimmed = label.trim();
1212
1244
  if (!trimmed) return;
1213
- if (isGenerating || localIsSending || isSendingOrLoading) return;
1214
- try {
1215
- await sendMessage(trimmed, undefined, {
1216
- skipIntentGate: suggestion.intent === 'generate_anyway',
1217
- chipIntent: suggestion.intent,
1218
- });
1219
- } catch (err) {
1220
- console.error('[Chat] Clarification suggestion send failed:', err);
1221
- showFailure('chat.error.sendSuggestion');
1245
+ localInputText = mergeSuggestionIntoDraft(localInputText, trimmed);
1246
+ if (intent) {
1247
+ pendingChipIntent = intent;
1248
+ pendingSkipIntentGate = intent === 'generate_anyway';
1249
+ } else {
1250
+ pendingChipIntent = null;
1251
+ pendingSkipIntentGate = false;
1222
1252
  }
1253
+ notifyDraftChange();
1254
+ skipNextDraftIntentClear = true;
1255
+ queueMicrotask(() => focusComposerTextarea());
1256
+ }
1257
+
1258
+ function handleSuggestionSelected(suggestion: string) {
1259
+ if (!suggestion.trim()) return;
1260
+ fillDraftFromSuggestion(suggestion);
1261
+ }
1262
+
1263
+ /** Clarification chips fill the composer like other suggestions; chipIntent is kept on the draft until send. */
1264
+ function handleClarificationSuggestionSelected(suggestion: ClarificationSuggestion) {
1265
+ if (!suggestion.label.trim()) return;
1266
+ if (isGenerating || localIsSending || isSendingOrLoading) return;
1267
+ fillDraftFromSuggestion(suggestion.label, suggestion.intent);
1223
1268
  }
1224
1269
 
1225
1270
  async function handleRetryMessage(content: string) {
@@ -1411,6 +1456,8 @@
1411
1456
 
1412
1457
  function setDraftText(text: string) {
1413
1458
  localInputText = text;
1459
+ pendingChipIntent = null;
1460
+ pendingSkipIntentGate = false;
1414
1461
  }
1415
1462
 
1416
1463
  function getAttachmentDataUrls(): string[] {
@@ -1420,6 +1467,17 @@
1420
1467
  .filter((url) => !!url);
1421
1468
  }
1422
1469
 
1470
+ /**
1471
+ * The attached pictures in the one form a refresh can rebuild them from: `data:` URLs. This is what the draft keeps;
1472
+ * `getAttachmentDataUrls` stays the list of addresses to send with a message (a CDN address when the upload ended).
1473
+ */
1474
+ function getDraftAttachmentDataUrls(): string[] {
1475
+ return localAttachments
1476
+ .filter((att) => att.type === 'image' || att.file?.type?.startsWith('image/'))
1477
+ .map((att) => att.persistedDataUrl || (att.preview?.startsWith('data:') ? att.preview : '') || '')
1478
+ .filter((url) => !!url);
1479
+ }
1480
+
1423
1481
  function getAttachmentUploadIds(): string[] {
1424
1482
  return localAttachments
1425
1483
  .filter((att) => Boolean(att.uploadId))
@@ -1458,6 +1516,8 @@
1458
1516
  }
1459
1517
  localInputText = '';
1460
1518
  localAttachments = [];
1519
+ pendingChipIntent = null;
1520
+ pendingSkipIntentGate = false;
1461
1521
  notifyDraftChange();
1462
1522
  }
1463
1523
 
@@ -1796,6 +1856,7 @@
1796
1856
  getDraftText,
1797
1857
  setDraftText,
1798
1858
  getAttachmentDataUrls,
1859
+ getDraftAttachmentDataUrls,
1799
1860
  getAttachmentUploadIds,
1800
1861
  restoreAttachmentsFromDataUrls,
1801
1862
  clearDraft,
@@ -1948,6 +2009,7 @@
1948
2009
  conversations={availableConversations}
1949
2010
  currentConversationId={currentConversationId}
1950
2011
  onSelectConversation={(id) => void loadConversation(id)}
2012
+ isGenerating={isGenerating || localIsSending}
1951
2013
  />
1952
2014
  {:else if showHeader}
1953
2015
  <!-- Simple Chat Header -->
@@ -1991,7 +2053,7 @@
1991
2053
  messages={currentMessages || []}
1992
2054
  isLoading={isLoading}
1993
2055
  isInitialized={isInitialized}
1994
- {showEmptyState}
2056
+ showEmptyState={showEmptyState && localAttachments.length === 0}
1995
2057
  panelLayout={showPanelHeader}
1996
2058
  {context}
1997
2059
  isCompleted={isCompleted}
@@ -2017,6 +2079,7 @@
2017
2079
  onClarificationSuggestionSelected={handleClarificationSuggestionSelected}
2018
2080
  {renderDesignControls}
2019
2081
  {storedLineLabel}
2082
+ conversationId={currentConversationId}
2020
2083
  />
2021
2084
  </div>
2022
2085
 
@@ -2037,7 +2100,7 @@
2037
2100
  {/if}
2038
2101
 
2039
2102
  <div
2040
- class="prompt-chat-footer-ct shrink-0 flex flex-col {showPanelHeader ? 'px-4 pb-4 max-lg:px-3' : ''}"
2103
+ class="prompt-chat-footer-ct shrink-0 flex flex-col {showPanelHeader ? 'px-3 pb-4 max-lg:px-3' : ''}"
2041
2104
  >
2042
2105
  {#if showActionBar}
2043
2106
  <ActionBar
@@ -2109,49 +2172,19 @@
2109
2172
  {/if}
2110
2173
 
2111
2174
  {#if localAttachments.length > 0}
2112
- <div class="prompt-chat-attachments-tray-ct flex flex-wrap gap-2 p-3 border-t border-gray-100 bg-white shrink-0">
2113
- {#each localAttachments as attachment, index (attachment.preview || attachment.uploadedUrl || attachment.file?.name || index)}
2114
- <div class="prompt-chat-attachment-item-ct relative bg-gray-50 rounded-lg overflow-hidden">
2115
- <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>
2116
- {#if isImageAttachment(attachment)}
2117
- <!-- svelte-ignore a11y_click_events_have_key_events -->
2118
- <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
2119
- <img
2120
- src={getFooterAttachmentPreviewUrl(attachment)}
2121
- alt={attachment.file?.name || $t('chat.attachment.namelessAlt')}
2122
- class="prompt-chat-attachment-image-preview w-16 h-16 object-cover cursor-pointer"
2123
- onclick={() => {
2124
- const previewUrl = getFooterAttachmentPreviewUrl(attachment);
2125
- if (previewUrl) footerLightboxSrc = previewUrl;
2126
- }}
2127
- />
2128
- {:else}
2129
- <div class="prompt-chat-attachment-file-preview flex items-center gap-2 p-3 w-32">
2130
- <span class="text-lg">📄</span>
2131
- <span class="text-xs text-gray-600 truncate flex-1">{attachment.file?.name || $t('chat.attachment.namelessAlt')}</span>
2132
- </div>
2133
- {/if}
2134
-
2135
- <button
2136
- type="button"
2137
- 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"
2138
- onclick={() => removeFooterAttachment(index)}
2139
- aria-label={$t('chat.attachment.remove')}
2140
- >
2141
- ✕
2142
- </button>
2143
-
2144
- {#if attachment.uploadProgress && attachment.uploadProgress > 0 && attachment.uploadProgress < 100}
2145
- <div class="prompt-chat-attachment-upload-bar absolute bottom-0 start-0 end-0 h-1 bg-gray-200">
2146
- <div class="h-full bg-blue-500 transition-all duration-300" style="width: {attachment.uploadProgress}%"></div>
2147
- </div>
2148
- {/if}
2149
- </div>
2150
- {/each}
2151
- </div>
2175
+ <ComposerAttachmentsTray
2176
+ attachments={localAttachments}
2177
+ previewUrl={getFooterAttachmentPreviewUrl}
2178
+ isImage={isImageAttachment}
2179
+ onRemove={removeFooterAttachment}
2180
+ onOpenPreview={(url) => {
2181
+ footerLightboxSrc = url;
2182
+ }}
2183
+ />
2152
2184
  {/if}
2153
2185
 
2154
2186
  <ChatComposer
2187
+ {sendNudgeToken}
2155
2188
  panelLayout={showPanelHeader}
2156
2189
  placeholder={showPanelHeader
2157
2190
  ? (currentMessages?.length ?? 0) > 0
@@ -2160,6 +2193,12 @@
2160
2193
  : undefined}
2161
2194
  bind:value={() => localInputText, (nextInputText) => {
2162
2195
  localInputText = nextInputText;
2196
+ if (skipNextDraftIntentClear) {
2197
+ skipNextDraftIntentClear = false;
2198
+ } else {
2199
+ pendingChipIntent = null;
2200
+ pendingSkipIntentGate = false;
2201
+ }
2163
2202
  notifyDraftChange();
2164
2203
  }}
2165
2204
  isSending={localIsSending}
@@ -29,6 +29,8 @@ interface ChatMethods {
29
29
  setDraftText: (text: string) => void;
30
30
  /** Get attachment preview data URLs in current order. */
31
31
  getAttachmentDataUrls: () => string[];
32
+ /** Attached pictures as `data:` URLs, the form the draft keeps so they are still attached after a refresh. */
33
+ getDraftAttachmentDataUrls: () => string[];
32
34
  /** Get CDN upload row IDs for image attachments (codegen attachmentIds). */
33
35
  getAttachmentUploadIds: () => string[];
34
36
  /** Replace chat attachments from stored data URLs (restores draft attachments). */
@@ -160,6 +162,8 @@ interface Props {
160
162
  showPanelHeader?: boolean;
161
163
  /** When true with `onToggleConsole`, shows the debug console icon in the panel header. */
162
164
  showConsoleControl?: boolean;
165
+ /** Increment to bounce the Send button and show the publish-first tooltip (host-driven). */
166
+ sendNudgeToken?: number;
163
167
  consoleOpen?: boolean;
164
168
  onToggleConsole?: () => void;
165
169
  /** Custom title displayed in the header. If empty/undefined, defaults to context.title or context.id. */
@@ -4,6 +4,7 @@
4
4
  import { dirForUserText, useTextDirection } from '@widgetic/design-system/components/textDirection';
5
5
  import { Composer, IconButton } from '@widgetic/design-system/components/chat/index';
6
6
  import { chatLog } from '../utils/logger.js';
7
+ import { reduceSendNudge, SEND_NUDGE_VISIBLE_MS, type SendNudgePhase } from '../sendNudgeState.js';
7
8
 
8
9
  const { t } = useChatLanguage();
9
10
  const textDirection = useTextDirection();
@@ -31,6 +32,8 @@
31
32
  panelLayout?: boolean;
32
33
  /** Figma panel composer (65:31): arrow-up send icon instead of paper-plane. */
33
34
  sendIcon?: 'send' | 'arrow-up';
35
+ /** Increment from the host to nudge Send before publish. */
36
+ sendNudgeToken?: number;
34
37
  }
35
38
 
36
39
  let {
@@ -51,11 +54,65 @@
51
54
  onAttach,
52
55
  panelLayout = false,
53
56
  sendIcon = 'send',
57
+ sendNudgeToken = 0,
54
58
  }: Props = $props();
55
59
 
56
60
  const composerSendIcon = $derived(panelLayout ? 'arrow-up' : sendIcon);
57
61
 
58
62
  let isFileDragOver = $state(false);
63
+ let sendNudgePhase = $state<SendNudgePhase>('idle');
64
+ let sendNudgeBounce = $state(false);
65
+ let sendNudgeHideTimer: ReturnType<typeof setTimeout> | null = null;
66
+ let sendNudgeBounceTimer: ReturnType<typeof setTimeout> | null = null;
67
+ let lastNudgeToken = $state(0);
68
+
69
+ const publishNudgeText = $derived($t('chat.input.publishNudge'));
70
+ const sendAttention = $derived(
71
+ sendNudgePhase === 'active'
72
+ ? {
73
+ bounce: sendNudgeBounce,
74
+ hintOpen: true,
75
+ hintText: publishNudgeText,
76
+ }
77
+ : sendNudgeBounce
78
+ ? { bounce: true, hintOpen: false, hintText: '' }
79
+ : undefined,
80
+ );
81
+
82
+ function clearSendNudgeTimers() {
83
+ if (sendNudgeHideTimer) {
84
+ clearTimeout(sendNudgeHideTimer);
85
+ sendNudgeHideTimer = null;
86
+ }
87
+ if (sendNudgeBounceTimer) {
88
+ clearTimeout(sendNudgeBounceTimer);
89
+ sendNudgeBounceTimer = null;
90
+ }
91
+ }
92
+
93
+ function armSendNudge() {
94
+ clearSendNudgeTimers();
95
+ sendNudgePhase = reduceSendNudge(sendNudgePhase, 'trigger');
96
+ const reducedMotion =
97
+ typeof window !== 'undefined' &&
98
+ window.matchMedia('(prefers-reduced-motion: reduce)').matches;
99
+ sendNudgeBounce = !reducedMotion;
100
+ if (sendNudgeBounce) {
101
+ sendNudgeBounceTimer = setTimeout(() => {
102
+ sendNudgeBounce = false;
103
+ }, 750);
104
+ }
105
+ sendNudgeHideTimer = setTimeout(() => {
106
+ sendNudgePhase = reduceSendNudge(sendNudgePhase, 'autoHide');
107
+ }, SEND_NUDGE_VISIBLE_MS);
108
+ }
109
+
110
+ $effect(() => {
111
+ if (sendNudgeToken > 0 && sendNudgeToken !== lastNudgeToken) {
112
+ lastNudgeToken = sendNudgeToken;
113
+ armSendNudge();
114
+ }
115
+ });
59
116
 
60
117
  const busy = $derived(isGenerating || isSending);
61
118
  const allowEmptySend = $derived(canSendWithoutText);
@@ -99,6 +156,11 @@
99
156
  const trimmed = text.trim();
100
157
  if (!trimmed && !allowEmptySend) return;
101
158
  if (isSending && !isGenerating) return;
159
+ if (sendNudgePhase === 'active') {
160
+ sendNudgePhase = reduceSendNudge(sendNudgePhase, 'userInteract');
161
+ clearSendNudgeTimers();
162
+ sendNudgeBounce = false;
163
+ }
102
164
  onSend(trimmed, undefined);
103
165
  }
104
166
  </script>
@@ -162,5 +224,6 @@
162
224
  onSend={handleComposerSend}
163
225
  onStop={() => onStop?.()}
164
226
  leading={attachControl}
227
+ {sendAttention}
165
228
  />
166
229
  </div>
@@ -24,6 +24,8 @@ interface Props {
24
24
  panelLayout?: boolean;
25
25
  /** Figma panel composer (65:31): arrow-up send icon instead of paper-plane. */
26
26
  sendIcon?: 'send' | 'arrow-up';
27
+ /** Increment from the host to nudge Send before publish. */
28
+ sendNudgeToken?: number;
27
29
  }
28
30
  declare const ChatComposer: import("svelte").Component<Props, {}, "value">;
29
31
  type ChatComposer = ReturnType<typeof ChatComposer>;