@widgetic/chat 0.1.38 → 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.
@@ -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';
@@ -324,6 +328,10 @@
324
328
 
325
329
  // Local input state per chat instance (instead of shared store state)
326
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);
327
335
  let localAttachments = $state<AttachmentInput[]>([]);
328
336
  let localIsRecording = $state(false);
329
337
  let localIsSending = $state(false);
@@ -603,6 +611,11 @@
603
611
  });
604
612
 
605
613
  currentConversationId = conversationId;
614
+ chatStore.actions.setMessages(conversationId, []);
615
+ showEmptyState = true;
616
+ clearDraft();
617
+ onConversationChange?.(conversationId);
618
+ focusComposerTextarea();
606
619
  return conversation;
607
620
  } catch (error) {
608
621
  console.error('Failed to create conversation:', error);
@@ -630,6 +643,13 @@
630
643
  }
631
644
 
632
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;
633
653
  if (!currentConversationId) {
634
654
  if (initializePromise) {
635
655
  try {
@@ -774,8 +794,8 @@
774
794
  submittedContent,
775
795
  outgoing.length > 0 ? outgoing : undefined,
776
796
  submittedSelectedElements
777
- ? { ...options, selectedElements: submittedSelectedElements }
778
- : options
797
+ ? { ...mergedOptions, selectedElements: submittedSelectedElements }
798
+ : mergedOptions
779
799
  );
780
800
  } else {
781
801
  const aiResponse = await chatService.processAIResponse(activeConversationId, userMessage);
@@ -1000,9 +1020,8 @@
1000
1020
  options: { source?: string } = {},
1001
1021
  ): Promise<void> {
1002
1022
  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
- }
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);
1006
1025
  return;
1007
1026
  }
1008
1027
 
@@ -1015,13 +1034,8 @@
1015
1034
  entry.uploadedUrl = uploaded.url;
1016
1035
  entry.uploadId = uploaded.id;
1017
1036
  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
- }
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.
1025
1039
  entry.preview = uploaded.url;
1026
1040
  }
1027
1041
  entry.uploadProgress = 100;
@@ -1031,9 +1045,7 @@
1031
1045
  // chatLog('[Chat] Attachment uploaded to CDN:', uploaded.url.slice(0, 80), 'id:', uploaded.id);
1032
1046
  } catch (uploadError) {
1033
1047
  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
- }
1048
+ if (!entry.preview) entry.preview = createLocalPreviewUrl(file);
1037
1049
  entry.uploadProgress = 0;
1038
1050
  bumpAttachmentProgress(attachmentIndex, 0);
1039
1051
  // Soft warning only — local File still works for codegen vision; don't block the chat UI.
@@ -1064,17 +1076,10 @@
1064
1076
  );
1065
1077
  }
1066
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.
1067
1081
  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
- }
1082
+ return readAttachmentPreviewUrl(attachment);
1078
1083
  }
1079
1084
 
1080
1085
  function removeFooterAttachment(index: number) {
@@ -1133,8 +1138,13 @@
1133
1138
  }
1134
1139
 
1135
1140
  async function addFilesAsAttachments(files: File[]) {
1136
- const usableFiles = (files || []).filter((file) => file && file.size > 0);
1137
- 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
+ );
1138
1148
 
1139
1149
  const previousCount = localAttachments.length;
1140
1150
  const newAttachments: AttachmentInput[] = usableFiles.map((file) => ({
@@ -1144,6 +1154,8 @@
1144
1154
  : file.type.startsWith('video/')
1145
1155
  ? 'video'
1146
1156
  : 'document',
1157
+ // The picture the tray draws: made now, once, because the tray cannot write it while it draws.
1158
+ preview: createLocalPreviewUrl(file),
1147
1159
  uploadProgress: 0,
1148
1160
  }));
1149
1161
 
@@ -1216,45 +1228,43 @@
1216
1228
  showFailure(actionFailureKey(detail.type));
1217
1229
  }
1218
1230
 
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();
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);
1239
+ }
1240
+ }
1241
+
1242
+ function fillDraftFromSuggestion(label: string, intent?: ClarificationSuggestion['intent']) {
1243
+ const trimmed = label.trim();
1247
1244
  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');
1245
+ localInputText = mergeSuggestionIntoDraft(localInputText, trimmed);
1246
+ if (intent) {
1247
+ pendingChipIntent = intent;
1248
+ pendingSkipIntentGate = intent === 'generate_anyway';
1249
+ } else {
1250
+ pendingChipIntent = null;
1251
+ pendingSkipIntentGate = false;
1257
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);
1258
1268
  }
1259
1269
 
1260
1270
  async function handleRetryMessage(content: string) {
@@ -1446,6 +1456,8 @@
1446
1456
 
1447
1457
  function setDraftText(text: string) {
1448
1458
  localInputText = text;
1459
+ pendingChipIntent = null;
1460
+ pendingSkipIntentGate = false;
1449
1461
  }
1450
1462
 
1451
1463
  function getAttachmentDataUrls(): string[] {
@@ -1504,6 +1516,8 @@
1504
1516
  }
1505
1517
  localInputText = '';
1506
1518
  localAttachments = [];
1519
+ pendingChipIntent = null;
1520
+ pendingSkipIntentGate = false;
1507
1521
  notifyDraftChange();
1508
1522
  }
1509
1523
 
@@ -1995,6 +2009,7 @@
1995
2009
  conversations={availableConversations}
1996
2010
  currentConversationId={currentConversationId}
1997
2011
  onSelectConversation={(id) => void loadConversation(id)}
2012
+ isGenerating={isGenerating || localIsSending}
1998
2013
  />
1999
2014
  {:else if showHeader}
2000
2015
  <!-- Simple Chat Header -->
@@ -2064,6 +2079,7 @@
2064
2079
  onClarificationSuggestionSelected={handleClarificationSuggestionSelected}
2065
2080
  {renderDesignControls}
2066
2081
  {storedLineLabel}
2082
+ conversationId={currentConversationId}
2067
2083
  />
2068
2084
  </div>
2069
2085
 
@@ -2084,7 +2100,7 @@
2084
2100
  {/if}
2085
2101
 
2086
2102
  <div
2087
- 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' : ''}"
2088
2104
  >
2089
2105
  {#if showActionBar}
2090
2106
  <ActionBar
@@ -2156,46 +2172,15 @@
2156
2172
  {/if}
2157
2173
 
2158
2174
  {#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>
2175
+ <ComposerAttachmentsTray
2176
+ attachments={localAttachments}
2177
+ previewUrl={getFooterAttachmentPreviewUrl}
2178
+ isImage={isImageAttachment}
2179
+ onRemove={removeFooterAttachment}
2180
+ onOpenPreview={(url) => {
2181
+ footerLightboxSrc = url;
2182
+ }}
2183
+ />
2199
2184
  {/if}
2200
2185
 
2201
2186
  <ChatComposer
@@ -2208,6 +2193,12 @@
2208
2193
  : undefined}
2209
2194
  bind:value={() => localInputText, (nextInputText) => {
2210
2195
  localInputText = nextInputText;
2196
+ if (skipNextDraftIntentClear) {
2197
+ skipNextDraftIntentClear = false;
2198
+ } else {
2199
+ pendingChipIntent = null;
2200
+ pendingSkipIntentGate = false;
2201
+ }
2211
2202
  notifyDraftChange();
2212
2203
  }}
2213
2204
  isSending={localIsSending}
@@ -23,8 +23,15 @@
23
23
  generationActivityAriaKey,
24
24
  generationActivityPhase,
25
25
  thoughtDurationSeconds,
26
+ readThinkingTail,
27
+ readCodegenStreamTail,
26
28
  } from '../utils/generationActivity.js';
27
29
  import { mapWidgetPlanToPlanCard, type GenerationPlanWire } from '../utils/generationPlan.js';
30
+ import {
31
+ clearGenerationArchive,
32
+ loadGenerationArchive,
33
+ saveGenerationArchive,
34
+ } from '../utils/generationArchiveStore.js';
28
35
  // The chat barrel of the design system: its export map resolves `components/<name>` to `<name>.js` only,
29
36
  // so a deep `.svelte` path types fine but cannot be resolved by Vite or Node.
30
37
  import {
@@ -132,6 +139,8 @@
132
139
  onRequestOlderMessages?: () => Promise<boolean | void>;
133
140
  /** Widget creator side panel: Figma empty / follow-up suggestion cards. */
134
141
  panelLayout?: boolean;
142
+ /** Active conversation id — persists generation archive in IndexedDB across reload. */
143
+ conversationId?: string | null;
135
144
  }
136
145
 
137
146
  let {
@@ -165,6 +174,7 @@
165
174
  hasOlderMessages = false,
166
175
  onRequestOlderMessages,
167
176
  panelLayout = false,
177
+ conversationId = null,
168
178
  }: Props = $props();
169
179
 
170
180
 
@@ -194,12 +204,16 @@
194
204
 
195
205
  function detectMessagesScrollbar(node: HTMLElement) {
196
206
  function check() {
197
- messagesHasScrollbar = node.scrollHeight > node.clientHeight + 1;
207
+ messagesHasScrollbar = node.scrollHeight > node.clientHeight + 4;
198
208
  if (panelLayout) {
199
209
  // The docked panel keeps Figma's 16px on both sides (set in the style of the list); with a scrollbar the bar
200
210
  // takes the place of half of it.
201
211
  if (messagesHasScrollbar) node.style.setProperty('padding-inline-end', '8px', 'important');
202
- else node.style.removeProperty('padding-inline-end');
212
+ else {
213
+ node.style.removeProperty('padding-inline-end');
214
+ node.style.setProperty('padding-inline-start', '16px', 'important');
215
+ node.style.setProperty('padding-inline-end', '16px', 'important');
216
+ }
203
217
  return;
204
218
  }
205
219
  node.style.setProperty('padding-inline-end', messagesHasScrollbar ? '0px' : '12px', 'important');
@@ -811,7 +825,12 @@
811
825
  const meta = reply.metadata as { panelFollowUp?: boolean } | undefined;
812
826
  if (!reply.suggestions?.length || meta?.panelFollowUp === false) continue;
813
827
  if (!shouldShowAssistantReply(reply)) continue;
814
- return { labels: reply.suggestions.map((s) => s.label) };
828
+ // A suggestion without a text label would give the keyed list a NaN key and stop the whole panel from rendering.
829
+ const suggestionLabels = reply.suggestions
830
+ .map((suggestion) => suggestion?.label)
831
+ .filter((label): label is string => typeof label === 'string' && label.trim().length > 0);
832
+ if (suggestionLabels.length === 0) continue;
833
+ return { labels: suggestionLabels };
815
834
  }
816
835
  }
817
836
  return null;
@@ -966,6 +985,20 @@
966
985
  let thinkingHold = $state(false);
967
986
  let generationWasRunning = false;
968
987
  let keptThinkingText = $state('');
988
+ $effect(() => {
989
+ const id = conversationId?.trim() ?? '';
990
+ void messages.length;
991
+ if (!id || isGenerating) return;
992
+ void loadGenerationArchive(id).then((record) => {
993
+ if (record) archivedGeneration = record;
994
+ });
995
+ });
996
+
997
+ let archivedGeneration = $state<{
998
+ thinking: string;
999
+ code: string;
1000
+ thoughtSeconds: number | null;
1001
+ } | null>(null);
969
1002
  let thinkingStartedAtMs = $state<number | null>(null);
970
1003
  let codeStreamingStartedAtMs = $state<number | null>(null);
971
1004
  let frozenThoughtSeconds = $state<number | null>(null);
@@ -1006,6 +1039,7 @@
1006
1039
  // A new send starts a fresh transcript. An empty thread drops the previous one.
1007
1040
  $effect(() => {
1008
1041
  if (isGenerating && !generationWasRunning) {
1042
+ archivedGeneration = null;
1009
1043
  keptGenerationText = '';
1010
1044
  keptThinkingText = '';
1011
1045
  shownGenerationCount = 0;
@@ -1019,18 +1053,31 @@
1019
1053
  lastGenerationAriaKey = '';
1020
1054
  }
1021
1055
  if (!isGenerating && generationWasRunning) {
1022
- keptGenerationText = '';
1023
- keptThinkingText = '';
1024
- shownGenerationCount = 0;
1025
- thinkingShownCount = 0;
1056
+ if (keptThinkingText.trim() || keptGenerationText.trim()) {
1057
+ archivedGeneration = {
1058
+ thinking: keptThinkingText,
1059
+ code: keptGenerationText,
1060
+ thoughtSeconds: frozenThoughtSeconds,
1061
+ };
1062
+ void saveGenerationArchive(conversationId, archivedGeneration);
1063
+ }
1026
1064
  thinkingHold = false;
1065
+ shownGenerationCount = keptGenerationText.length;
1066
+ thinkingShownCount = $t('chat.messages.thinking').length;
1027
1067
  thinkingStartedAtMs = null;
1028
1068
  codeStreamingStartedAtMs = null;
1029
1069
  frozenThoughtSeconds = null;
1030
1070
  thinkingExpanded = false;
1031
1071
  }
1032
1072
  generationWasRunning = isGenerating;
1033
- if (messages.length === 0 && !isGenerating) {
1073
+ });
1074
+
1075
+ // Drop the local transcript only after init finished and history is truly empty — not while the thread hydrates on reload.
1076
+ $effect(() => {
1077
+ void messages.length;
1078
+ if (!isInitialized || isLoading || isGenerating) return;
1079
+ if (messages.length === 0) {
1080
+ void clearGenerationArchive(conversationId);
1034
1081
  keptGenerationText = '';
1035
1082
  keptThinkingText = '';
1036
1083
  shownGenerationCount = 0;
@@ -1567,9 +1614,11 @@
1567
1614
  <div class="{panelLayout ? 'panel-messages-shell flex h-full min-h-0 w-full flex-1 flex-col' : 'contents'}">
1568
1615
  <div
1569
1616
  bind:this={messagesContainer}
1570
- class="{className ? className : 'prompt-chat-messages-ct'} prompt-chat-messages-scroll flex flex-col overflow-y-auto {panelLayout ? 'min-h-0 flex-1 gap-4 pb-1' : 'space-y-4 pb-3'}"
1617
+ class="{className ? className : 'prompt-chat-messages-ct'} prompt-chat-messages-scroll flex flex-col {panelLayout && showEmptyState && !isLoading && !isGenerating ? 'overflow-y-hidden pb-0' : 'overflow-y-auto'} {panelLayout ? (showEmptyState && !isLoading && !isGenerating ? 'min-h-0 flex-1' : 'min-h-0 flex-1 pb-4') : 'space-y-4 pb-3'}"
1571
1618
  class:loading={isLoading}
1572
- style={panelLayout ? 'padding: 8px 16px 0; overflow-anchor: none;' : 'padding: 8px 16px 12px; overflow-anchor: none;'}
1619
+ style={panelLayout
1620
+ ? `padding: 8px 16px ${showEmptyState && !isLoading && !isGenerating ? 0 : 16}px; overflow-anchor: none;`
1621
+ : 'padding: 8px 16px 12px; overflow-anchor: none;'}
1573
1622
  use:detectMessagesScrollbar
1574
1623
  onscroll={handleScroll}
1575
1624
  >
@@ -1581,8 +1630,8 @@
1581
1630
  middle of the messages, and the suggestions are pinned under it, above the composer. The block takes the
1582
1631
  free height with flex-1 (not min-h-full): the sticky scroll-to-bottom row below it needs its own room, and a
1583
1632
  block as tall as the whole area would push it out and make the list scroll. -->
1584
- <div class="empty-state-ct flex w-full flex-1 flex-col gap-4 {panelLayout ? 'min-h-0 pb-2' : ''}">
1585
- <div class="empty-state-hero flex flex-1 flex-col items-center justify-center gap-3 px-2 text-center">
1633
+ <div class="empty-state-ct flex w-full flex-col gap-4 {panelLayout ? 'shrink-0' : 'flex-1'}">
1634
+ <div class="empty-state-hero flex shrink-0 flex-col items-center justify-center gap-3 text-center {panelLayout ? 'h-[508px]' : 'min-h-0 flex-1 px-2'}">
1586
1635
  <span class="empty-state-icon-circle bg-muted text-foreground flex size-10 shrink-0 items-center justify-center rounded-full" aria-hidden="true">
1587
1636
  <IconSparkles class="size-4 stroke-2" />
1588
1637
  </span>
@@ -1607,6 +1656,8 @@
1607
1656
  </div>
1608
1657
  {/if}
1609
1658
 
1659
+ <div class="{panelLayout && chatTurns.length > 0 ? 'flex min-h-full flex-col' : 'contents'}">
1660
+ <div class="{panelLayout && chatTurns.length > 0 ? 'mt-auto flex w-full flex-col gap-4' : 'contents'}">
1610
1661
  <!-- Conversation turns (user prompt + assistant status grouped) -->
1611
1662
  {#each chatTurns as turn, turnIndex (turn.user?.id ?? turn.replies[0]?.id ?? turnIndex)}
1612
1663
  <div class="wc-chat-turn-ct rounded-lg {panelLayout ? 'flex flex-col gap-[52px]' : 'space-y-1.5 border border-transparent p-0.5'}">
@@ -1828,6 +1879,40 @@
1828
1879
  </div>
1829
1880
  {/each}
1830
1881
 
1882
+ {#if panelLayout && archivedGeneration && !isGenerating && !thinkingHold}
1883
+ <div
1884
+ class="generation-archive-card w-full max-w-full rounded-lg border border-border bg-muted/40 p-3 text-sm"
1885
+ data-testid="generation-archive"
1886
+ >
1887
+ {#if archivedGeneration.thinking.trim()}
1888
+ <button
1889
+ type="button"
1890
+ class="text-muted-foreground hover:text-foreground mb-2 flex w-full items-center gap-2 text-start text-xs underline-offset-2 hover:underline"
1891
+ aria-expanded={thinkingExpanded}
1892
+ onclick={() => { thinkingExpanded = !thinkingExpanded; }}
1893
+ >
1894
+ <span>
1895
+ {#if archivedGeneration.thoughtSeconds != null}
1896
+ {$t('chat.generation.thoughtFor', { seconds: String(archivedGeneration.thoughtSeconds) })}
1897
+ {:else}
1898
+ {$t('chat.generation.thinking')}
1899
+ {/if}
1900
+ </span>
1901
+ </button>
1902
+ {#if thinkingExpanded}
1903
+ <div class="text-muted-foreground mb-2 max-h-24 overflow-auto whitespace-pre-wrap break-words text-xs">
1904
+ {archivedGeneration.thinking}
1905
+ </div>
1906
+ {/if}
1907
+ {/if}
1908
+ {#if archivedGeneration.code.trim()}
1909
+ <CodeBlock code={archivedGeneration.code} language="typescript" />
1910
+ {/if}
1911
+ </div>
1912
+ {/if}
1913
+ </div>
1914
+ </div>
1915
+
1831
1916
  <!-- Loading indicator -->
1832
1917
  {#if messages.length === 0 && isLoading}
1833
1918
  <div class="loading-history-ct flex flex-1 items-center justify-center p-8">
@@ -1919,10 +2004,10 @@
1919
2004
  </div>
1920
2005
  {/if}
1921
2006
 
1922
- {#if !panelLayout}
1923
- <div class="sticky bottom-2 z-10 flex justify-center pb-1 pt-2">
2007
+ {#if !autoScroll && messages.length > 0 && !isLoading}
2008
+ <div class="sticky bottom-2 z-10 flex justify-center pb-1 pt-2 pointer-events-none [&_button]:pointer-events-auto">
1924
2009
  <ScrollToBottom
1925
- visible={!autoScroll && messages.length > 0 && !isLoading}
2010
+ visible={true}
1926
2011
  label={$t('chat.messages.scrollToBottom')}
1927
2012
  onScroll={() => {
1928
2013
  autoScroll = true;
@@ -95,6 +95,8 @@ interface Props {
95
95
  onRequestOlderMessages?: () => Promise<boolean | void>;
96
96
  /** Widget creator side panel: Figma empty / follow-up suggestion cards. */
97
97
  panelLayout?: boolean;
98
+ /** Active conversation id — persists generation archive in IndexedDB across reload. */
99
+ conversationId?: string | null;
98
100
  }
99
101
  declare const ChatMessages: import("svelte").Component<Props, {}, "">;
100
102
  type ChatMessages = ReturnType<typeof ChatMessages>;
@@ -259,7 +259,6 @@
259
259
 
260
260
  /* Line numbers styling */
261
261
  .with-line-numbers :global(.hljs) {
262
- padding-left: 3em; /* rtl-ok: the numbers are at the left of the code, which is read left to right on every screen */
263
262
  position: relative;
264
263
  }
265
264
 
@@ -286,6 +285,15 @@
286
285
  padding: 0;
287
286
  }
288
287
 
288
+ /* The numbers are drawn over the left edge of the code, so the code keeps the room for them. This rule has to come after
289
+ the reset above: both have the same weight, and the reset would otherwise take the room back and hide the first
290
+ characters of every line under the numbers. The code is a block: the padding of an inline element only reaches the
291
+ first line, so the other lines would still start under the numbers. */
292
+ .code-pre.with-line-numbers :global(.hljs) {
293
+ display: block;
294
+ padding-left: 3em; /* rtl-ok: the numbers are at the left of the code, which is read left to right on every screen */
295
+ }
296
+
289
297
  /* Embedded highlight.js GitHub Light theme tokens */
290
298
  :global(.hljs) {
291
299
  color: #24292e;
@@ -0,0 +1,64 @@
1
+ <script lang="ts">
2
+ import type { AttachmentInput } from '../types/attachment.js';
3
+ import { Chip } from '@widgetic/design-system/components/chat/index';
4
+ import IconX from '@tabler/icons-svelte/icons/x';
5
+ import { useChatLanguage } from '../i18n/language.js';
6
+ import { buildImageThumbnailUrl } from '../utils/imageTransform.js';
7
+
8
+ interface Props {
9
+ attachments: AttachmentInput[];
10
+ previewUrl: (attachment: AttachmentInput) => string;
11
+ isImage: (attachment: AttachmentInput) => boolean;
12
+ onRemove: (index: number) => void;
13
+ onOpenPreview?: (url: string) => void;
14
+ }
15
+
16
+ let { attachments, previewUrl, isImage, onRemove, onOpenPreview }: Props = $props();
17
+ const { t } = useChatLanguage();
18
+
19
+ const IMAGE_PREVIEW_CSS_PX = 56;
20
+ </script>
21
+
22
+ <div class="composer-attachments-tray flex flex-wrap gap-2 pb-2" data-testid="composer-attachments-tray">
23
+ {#each attachments as attachment, index (attachment.preview || attachment.uploadedUrl || attachment.file?.name || index)}
24
+ {@const rawUrl = previewUrl(attachment)}
25
+ {#if isImage(attachment)}
26
+ <div
27
+ class="relative size-14 shrink-0 overflow-hidden rounded-lg border border-border bg-muted"
28
+ data-testid="composer-image-preview"
29
+ >
30
+ <!-- svelte-ignore a11y_click_events_have_key_events -->
31
+ <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
32
+ <img
33
+ src={buildImageThumbnailUrl(rawUrl, IMAGE_PREVIEW_CSS_PX) || rawUrl}
34
+ alt={attachment.file?.name || $t('chat.attachment.namelessAlt')}
35
+ class="size-full object-cover"
36
+ onclick={() => rawUrl && onOpenPreview?.(rawUrl)}
37
+ />
38
+ <button
39
+ type="button"
40
+ class="absolute end-0.5 top-0.5 flex size-5 items-center justify-center rounded-full bg-background/90 text-muted-foreground shadow-sm hover:text-foreground"
41
+ aria-label={$t('chat.attachment.remove')}
42
+ onclick={() => onRemove(index)}
43
+ >
44
+ <IconX class="size-3.5 stroke-2" aria-hidden="true" />
45
+ </button>
46
+ {#if attachment.uploadProgress && attachment.uploadProgress > 0 && attachment.uploadProgress < 100}
47
+ <div class="absolute inset-x-0 bottom-0 h-0.5 bg-border">
48
+ <div
49
+ class="bg-primary h-full transition-all duration-300"
50
+ style="width: {attachment.uploadProgress}%"
51
+ ></div>
52
+ </div>
53
+ {/if}
54
+ </div>
55
+ {:else}
56
+ <Chip
57
+ label={attachment.file?.name || $t('chat.attachment.namelessAlt')}
58
+ showRemove={true}
59
+ removeLabel={$t('chat.attachment.remove')}
60
+ onRemove={() => onRemove(index)}
61
+ />
62
+ {/if}
63
+ {/each}
64
+ </div>
@@ -0,0 +1,11 @@
1
+ import type { AttachmentInput } from '../types/attachment.js';
2
+ interface Props {
3
+ attachments: AttachmentInput[];
4
+ previewUrl: (attachment: AttachmentInput) => string;
5
+ isImage: (attachment: AttachmentInput) => boolean;
6
+ onRemove: (index: number) => void;
7
+ onOpenPreview?: (url: string) => void;
8
+ }
9
+ declare const ComposerAttachmentsTray: import("svelte").Component<Props, {}, "">;
10
+ type ComposerAttachmentsTray = ReturnType<typeof ComposerAttachmentsTray>;
11
+ export default ComposerAttachmentsTray;
@@ -18,6 +18,7 @@
18
18
  conversations?: ConversationRow[];
19
19
  currentConversationId?: string | null;
20
20
  onSelectConversation?: (conversationId: string) => void;
21
+ isGenerating?: boolean;
21
22
  }
22
23
 
23
24
  let {
@@ -29,6 +30,7 @@
29
30
  conversations = [],
30
31
  currentConversationId = null,
31
32
  onSelectConversation,
33
+ isGenerating = false,
32
34
  }: Props = $props();
33
35
 
34
36
  const { t } = useChatLanguage();
@@ -38,8 +40,8 @@
38
40
  return String(row.id || row.conversation_id || row.conversationId || '');
39
41
  }
40
42
 
41
- const canSwitchConversations = $derived(
42
- conversations.length > 0 && typeof onSelectConversation === 'function'
43
+ const historyEnabled = $derived(
44
+ typeof onSelectConversation === 'function' && typeof onNewConversation === 'function'
43
45
  );
44
46
  </script>
45
47
 
@@ -51,8 +53,8 @@
51
53
  {showConsole}
52
54
  {consoleOpen}
53
55
  onToggleConsole={onToggleConsole}
54
- onNewChat={onNewConversation}
55
- onTitleClick={canSwitchConversations ? () => { historyOpen = !historyOpen; } : undefined}
56
+ onNewChat={historyEnabled && !isGenerating ? onNewConversation : undefined}
57
+ onTitleClick={historyEnabled ? () => { historyOpen = !historyOpen; } : undefined}
56
58
  messages={{
57
59
  newChat: $t('chat.header.newConversationTitle'),
58
60
  console: $t('chat.header.console'),
@@ -60,20 +62,38 @@
60
62
  }}
61
63
  />
62
64
 
63
- {#if canSwitchConversations}
65
+ {#if historyEnabled}
64
66
  <DropdownMenu.Root bind:open={historyOpen}>
65
- <DropdownMenu.Content align="start" class="max-h-64 w-64 overflow-y-auto">
67
+ <DropdownMenu.Content align="start" class="max-h-64 w-72 overflow-y-auto">
68
+ <DropdownMenu.Item
69
+ class="gap-2 font-medium"
70
+ disabled={isGenerating}
71
+ onSelect={() => {
72
+ historyOpen = false;
73
+ onNewConversation?.();
74
+ }}
75
+ >
76
+ {$t('chat.header.newConversationTitle')}
77
+ </DropdownMenu.Item>
78
+ <DropdownMenu.Separator />
66
79
  {#each conversations as row (conversationId(row))}
67
80
  {@const id = conversationId(row)}
68
81
  <DropdownMenu.Item
69
82
  class="justify-between gap-2"
83
+ data-active={id === currentConversationId ? true : undefined}
70
84
  onSelect={() => {
85
+ historyOpen = false;
71
86
  if (id && id !== currentConversationId) onSelectConversation?.(id);
72
87
  }}
73
88
  >
74
89
  <span class="truncate">{row.title?.trim() || $t('chat.header.untitled')}</span>
75
90
  </DropdownMenu.Item>
76
91
  {/each}
92
+ {#if conversations.length === 0}
93
+ <DropdownMenu.Item disabled class="text-muted-foreground text-caption">
94
+ {$t('chat.header.noPastChats')}
95
+ </DropdownMenu.Item>
96
+ {/if}
77
97
  </DropdownMenu.Content>
78
98
  </DropdownMenu.Root>
79
99
  {/if}
@@ -13,6 +13,7 @@ interface Props {
13
13
  conversations?: ConversationRow[];
14
14
  currentConversationId?: string | null;
15
15
  onSelectConversation?: (conversationId: string) => void;
16
+ isGenerating?: boolean;
16
17
  }
17
18
  declare const PanelChatHeader: import("svelte").Component<Props, {}, "">;
18
19
  type PanelChatHeader = ReturnType<typeof PanelChatHeader>;
@@ -1,6 +1,6 @@
1
1
  <script lang="ts">
2
2
  import IconClock from '@tabler/icons-svelte/icons/clock';
3
- import IconSparkles from '@tabler/icons-svelte/icons/sparkles';
3
+ import IconWand from '@tabler/icons-svelte/icons/wand';
4
4
  import IconMessage from '@tabler/icons-svelte/icons/message';
5
5
  import { SuggestionCard } from '@widgetic/design-system/components/chat/index';
6
6
  import { useChatLanguage } from '../i18n/language.js';
@@ -16,7 +16,7 @@
16
16
 
17
17
  let { labels, onPick, disabled = false }: Props = $props();
18
18
 
19
- const ICONS = [IconClock, IconSparkles, IconMessage];
19
+ const ICONS = [IconClock, IconWand, IconMessage];
20
20
  </script>
21
21
 
22
22
  <div class="panel-followup-suggestion-ct flex w-full max-w-full flex-col gap-1">
@@ -40,7 +40,7 @@
40
40
  }
41
41
  </script>
42
42
 
43
- <div class="panel-suggestion-ct flex w-full max-w-full flex-col gap-1">
43
+ <div class="panel-suggestion-ct flex w-full max-w-full flex-col gap-1 pb-2">
44
44
  <h4 class="text-caption text-muted-foreground">{$t(titleKey)}</h4>
45
45
  <div class="flex w-full flex-col gap-1">
46
46
  {#each suggestionKeys as suggestionKey (suggestionKey)}
@@ -49,6 +49,7 @@
49
49
  <SuggestionCard
50
50
  title={label}
51
51
  disabled={disabled}
52
+ class="min-h-11"
52
53
  onclick={() => onPick(label)}
53
54
  >
54
55
  {#snippet icon()}
@@ -32,6 +32,7 @@ export declare const CHAT_MESSAGES: {
32
32
  /** The name of a conversation that has none. */
33
33
  readonly 'chat.header.untitled': "Untitled";
34
34
  readonly 'chat.header.newConversationTitle': "New chat";
35
+ readonly 'chat.header.noPastChats': "No previous chats yet";
35
36
  readonly 'chat.header.newConversation': "Start new conversation";
36
37
  /** Label for the debug console icon in the panel chat header. */
37
38
  readonly 'chat.header.console': "Console";
@@ -211,7 +212,6 @@ export declare const CHAT_MESSAGES: {
211
212
  readonly 'chat.error.loadConversations': "Failed to load conversations.";
212
213
  readonly 'chat.error.loadConversation': "Failed to load conversation.";
213
214
  readonly 'chat.error.sendMessage': "Failed to send message. Please try again.";
214
- readonly 'chat.error.sendSuggestion': "Failed to send the selected suggestion. Please try again.";
215
215
  readonly 'chat.error.screenshotUnavailable': "Screenshot capture failed — no preview available.";
216
216
  readonly 'chat.error.screenshotFailed': "Failed to capture screenshot";
217
217
  readonly 'chat.error.screenshotActionFailed': "Screenshot action failed. Please try again.";
@@ -34,6 +34,7 @@ export const CHAT_MESSAGES = {
34
34
  /** The name of a conversation that has none. */
35
35
  'chat.header.untitled': 'Untitled',
36
36
  'chat.header.newConversationTitle': 'New chat',
37
+ 'chat.header.noPastChats': 'No previous chats yet',
37
38
  'chat.header.newConversation': 'Start new conversation',
38
39
  /** Label for the debug console icon in the panel chat header. */
39
40
  'chat.header.console': 'Console',
@@ -222,7 +223,6 @@ export const CHAT_MESSAGES = {
222
223
  'chat.error.loadConversations': 'Failed to load conversations.',
223
224
  'chat.error.loadConversation': 'Failed to load conversation.',
224
225
  'chat.error.sendMessage': 'Failed to send message. Please try again.',
225
- 'chat.error.sendSuggestion': 'Failed to send the selected suggestion. Please try again.',
226
226
  'chat.error.screenshotUnavailable': 'Screenshot capture failed — no preview available.',
227
227
  'chat.error.screenshotFailed': 'Failed to capture screenshot',
228
228
  'chat.error.screenshotActionFailed': 'Screenshot action failed. Please try again.',
@@ -0,0 +1,21 @@
1
+ import type { AttachmentInput } from '../types/attachment.js';
2
+ /**
3
+ * Makes the address the composer tray draws a picked file with — a `blob:` address of the file on this page.
4
+ *
5
+ * It is made once, when the file is attached, and not while the tray draws: the tray reads the address inside a derived
6
+ * value, and Svelte does not allow a write to state there (the picture of a tile used to stay empty for that reason).
7
+ * The page gives the address back when the attachment is removed or the draft is cleared.
8
+ *
9
+ * @param file The file the person picked.
10
+ * @returns The `blob:` address, or `undefined` for a file that has no picture to show (a text file, say) or when the browser refuses.
11
+ */
12
+ export declare function createLocalPreviewUrl(file: File | null | undefined): string | undefined;
13
+ /**
14
+ * The address the tray draws an attachment with, in the order of what is best known: the preview of the page, the CDN
15
+ * address of the upload, then the `data:` copy the draft keeps. It only reads: it never writes to the attachment, so it
16
+ * is safe to call from a template or a derived value.
17
+ *
18
+ * @param attachment The attachment of the composer tray.
19
+ * @returns An address a picture can be drawn from, or '' when the attachment has none yet.
20
+ */
21
+ export declare function readAttachmentPreviewUrl(attachment: Pick<AttachmentInput, 'preview' | 'uploadedUrl' | 'persistedDataUrl'> | null | undefined): string;
@@ -0,0 +1,39 @@
1
+ /** Kinds of file that have a picture to draw in the composer tray: images, videos and PDFs. */
2
+ function fileTypeHasLocalPreview(fileType) {
3
+ const type = (fileType || '').toLowerCase();
4
+ return type.startsWith('image/') || type.startsWith('video/') || type === 'application/pdf';
5
+ }
6
+ /**
7
+ * Makes the address the composer tray draws a picked file with — a `blob:` address of the file on this page.
8
+ *
9
+ * It is made once, when the file is attached, and not while the tray draws: the tray reads the address inside a derived
10
+ * value, and Svelte does not allow a write to state there (the picture of a tile used to stay empty for that reason).
11
+ * The page gives the address back when the attachment is removed or the draft is cleared.
12
+ *
13
+ * @param file The file the person picked.
14
+ * @returns The `blob:` address, or `undefined` for a file that has no picture to show (a text file, say) or when the browser refuses.
15
+ */
16
+ export function createLocalPreviewUrl(file) {
17
+ if (!file || !fileTypeHasLocalPreview(file.type))
18
+ return undefined;
19
+ try {
20
+ return URL.createObjectURL(file);
21
+ }
22
+ catch (error) {
23
+ console.warn('[Chat] Could not make a local preview of the attached file:', error);
24
+ return undefined;
25
+ }
26
+ }
27
+ /**
28
+ * The address the tray draws an attachment with, in the order of what is best known: the preview of the page, the CDN
29
+ * address of the upload, then the `data:` copy the draft keeps. It only reads: it never writes to the attachment, so it
30
+ * is safe to call from a template or a derived value.
31
+ *
32
+ * @param attachment The attachment of the composer tray.
33
+ * @returns An address a picture can be drawn from, or '' when the attachment has none yet.
34
+ */
35
+ export function readAttachmentPreviewUrl(attachment) {
36
+ if (!attachment)
37
+ return '';
38
+ return attachment.preview || attachment.uploadedUrl || attachment.persistedDataUrl || '';
39
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Client-side downscale before chat upload / codegen attachment IDs.
3
+ * Aligns with gateway JEV/Claude standard tier (long edge ≤ 1568 px, ~1.15 MP).
4
+ */
5
+ export declare const CHAT_AGENT_IMAGE_MAX_LONG_EDGE = 1568;
6
+ export declare const CHAT_AGENT_IMAGE_MAX_PIXELS: number;
7
+ export declare const CHAT_AGENT_IMAGE_TARGET_BYTES = 1500000;
8
+ export declare const CHAT_AGENT_JPEG_QUALITY = 0.85;
9
+ export type ChatImagePrepDecision = {
10
+ action: 'passthrough';
11
+ } | {
12
+ action: 'resize';
13
+ maxLongEdge: number;
14
+ quality: number;
15
+ targetBytes: number;
16
+ };
17
+ /** Pure policy: whether and how to resize before upload. */
18
+ export declare function decideChatImagePrep(width: number, height: number, byteLength: number, mimeType: string): ChatImagePrepDecision;
19
+ /**
20
+ * Downscales raster images for the agent; returns the original file on any skip or failure.
21
+ */
22
+ export declare function prepareChatImageFileForUpload(file: File): Promise<File>;
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Client-side downscale before chat upload / codegen attachment IDs.
3
+ * Aligns with gateway JEV/Claude standard tier (long edge ≤ 1568 px, ~1.15 MP).
4
+ */
5
+ export const CHAT_AGENT_IMAGE_MAX_LONG_EDGE = 1568;
6
+ export const CHAT_AGENT_IMAGE_MAX_PIXELS = 1_568 * 1_568;
7
+ export const CHAT_AGENT_IMAGE_TARGET_BYTES = 1_500_000;
8
+ export const CHAT_AGENT_JPEG_QUALITY = 0.85;
9
+ /** Pure policy: whether and how to resize before upload. */
10
+ export function decideChatImagePrep(width, height, byteLength, mimeType) {
11
+ if (!mimeType.startsWith('image/'))
12
+ return { action: 'passthrough' };
13
+ if (mimeType === 'image/svg+xml' || mimeType === 'image/gif')
14
+ return { action: 'passthrough' };
15
+ const longEdge = Math.max(width, height);
16
+ const pixels = width * height;
17
+ if (longEdge <= CHAT_AGENT_IMAGE_MAX_LONG_EDGE &&
18
+ pixels <= CHAT_AGENT_IMAGE_MAX_PIXELS &&
19
+ byteLength <= CHAT_AGENT_IMAGE_TARGET_BYTES) {
20
+ return { action: 'passthrough' };
21
+ }
22
+ return {
23
+ action: 'resize',
24
+ maxLongEdge: CHAT_AGENT_IMAGE_MAX_LONG_EDGE,
25
+ quality: CHAT_AGENT_JPEG_QUALITY,
26
+ targetBytes: CHAT_AGENT_IMAGE_TARGET_BYTES,
27
+ };
28
+ }
29
+ function loadImageFromFile(file) {
30
+ return new Promise((resolve, reject) => {
31
+ const url = URL.createObjectURL(file);
32
+ const img = new Image();
33
+ img.onload = () => {
34
+ URL.revokeObjectURL(url);
35
+ resolve(img);
36
+ };
37
+ img.onerror = () => {
38
+ URL.revokeObjectURL(url);
39
+ reject(new Error('Could not decode image'));
40
+ };
41
+ img.src = url;
42
+ });
43
+ }
44
+ function canvasToBlob(canvas, type, quality) {
45
+ return new Promise((resolve) => {
46
+ canvas.toBlob((blob) => resolve(blob), type, quality);
47
+ });
48
+ }
49
+ /**
50
+ * Downscales raster images for the agent; returns the original file on any skip or failure.
51
+ */
52
+ export async function prepareChatImageFileForUpload(file) {
53
+ if (!file.type.startsWith('image/'))
54
+ return file;
55
+ if (file.type === 'image/svg+xml' || file.type === 'image/gif')
56
+ return file;
57
+ try {
58
+ const img = await loadImageFromFile(file);
59
+ const decision = decideChatImagePrep(img.naturalWidth, img.naturalHeight, file.size, file.type);
60
+ if (decision.action === 'passthrough')
61
+ return file;
62
+ const scale = Math.min(1, decision.maxLongEdge / Math.max(img.naturalWidth, img.naturalHeight));
63
+ const width = Math.max(1, Math.round(img.naturalWidth * scale));
64
+ const height = Math.max(1, Math.round(img.naturalHeight * scale));
65
+ const canvas = document.createElement('canvas');
66
+ canvas.width = width;
67
+ canvas.height = height;
68
+ const ctx = canvas.getContext('2d');
69
+ if (!ctx)
70
+ return file;
71
+ ctx.drawImage(img, 0, 0, width, height);
72
+ const preferPng = file.type === 'image/png' && file.size < 400_000;
73
+ const mime = preferPng ? 'image/png' : 'image/jpeg';
74
+ let quality = decision.quality;
75
+ let blob = await canvasToBlob(canvas, mime, quality);
76
+ if (!blob)
77
+ return file;
78
+ while (blob.size > decision.targetBytes && quality > 0.5 && mime === 'image/jpeg') {
79
+ quality -= 0.08;
80
+ blob = (await canvasToBlob(canvas, mime, quality)) ?? blob;
81
+ }
82
+ const baseName = file.name.replace(/\.[^.]+$/, '') || 'image';
83
+ const ext = mime === 'image/png' ? 'png' : 'jpg';
84
+ return new File([blob], `${baseName}.${ext}`, { type: mime, lastModified: file.lastModified });
85
+ }
86
+ catch (error) {
87
+ console.warn('[Chat] Image prep failed; sending original file', error);
88
+ return file;
89
+ }
90
+ }
@@ -0,0 +1,10 @@
1
+ /** Local persistence for panel generation archive (thinking + code tails), keyed by conversation. */
2
+ export type GenerationArchiveRecord = {
3
+ thinking: string;
4
+ code: string;
5
+ thoughtSeconds: number | null;
6
+ updatedAt: number;
7
+ };
8
+ export declare function loadGenerationArchive(conversationId: string | null | undefined): Promise<GenerationArchiveRecord | null>;
9
+ export declare function saveGenerationArchive(conversationId: string | null | undefined, record: Omit<GenerationArchiveRecord, 'updatedAt'>): Promise<void>;
10
+ export declare function clearGenerationArchive(conversationId: string | null | undefined): Promise<void>;
@@ -0,0 +1,88 @@
1
+ /** Local persistence for panel generation archive (thinking + code tails), keyed by conversation. */
2
+ const DB_NAME = 'widgetic-chat-generation-archive';
3
+ const STORE = 'byConversation';
4
+ const DB_VERSION = 1;
5
+ function openDb() {
6
+ return new Promise((resolve, reject) => {
7
+ if (typeof indexedDB === 'undefined') {
8
+ reject(new Error('indexedDB unavailable'));
9
+ return;
10
+ }
11
+ const request = indexedDB.open(DB_NAME, DB_VERSION);
12
+ request.onerror = () => reject(request.error ?? new Error('idb open failed'));
13
+ request.onsuccess = () => resolve(request.result);
14
+ request.onupgradeneeded = () => {
15
+ const db = request.result;
16
+ if (!db.objectStoreNames.contains(STORE)) {
17
+ db.createObjectStore(STORE, { keyPath: 'conversationId' });
18
+ }
19
+ };
20
+ });
21
+ }
22
+ export async function loadGenerationArchive(conversationId) {
23
+ if (!conversationId)
24
+ return null;
25
+ try {
26
+ const db = await openDb();
27
+ return await new Promise((resolve, reject) => {
28
+ const tx = db.transaction(STORE, 'readonly');
29
+ const req = tx.objectStore(STORE).get(conversationId);
30
+ req.onsuccess = () => {
31
+ const row = req.result;
32
+ if (!row?.thinking?.trim() && !row?.code?.trim()) {
33
+ resolve(null);
34
+ return;
35
+ }
36
+ resolve({
37
+ thinking: row.thinking ?? '',
38
+ code: row.code ?? '',
39
+ thoughtSeconds: row.thoughtSeconds ?? null,
40
+ updatedAt: row.updatedAt ?? 0,
41
+ });
42
+ };
43
+ req.onerror = () => reject(req.error);
44
+ });
45
+ }
46
+ catch (error) {
47
+ console.debug('[generationArchiveStore] load skipped', error);
48
+ return null;
49
+ }
50
+ }
51
+ export async function saveGenerationArchive(conversationId, record) {
52
+ if (!conversationId)
53
+ return;
54
+ if (!record.thinking.trim() && !record.code.trim())
55
+ return;
56
+ try {
57
+ const db = await openDb();
58
+ await new Promise((resolve, reject) => {
59
+ const tx = db.transaction(STORE, 'readwrite');
60
+ tx.objectStore(STORE).put({
61
+ conversationId,
62
+ ...record,
63
+ updatedAt: Date.now(),
64
+ });
65
+ tx.oncomplete = () => resolve();
66
+ tx.onerror = () => reject(tx.error);
67
+ });
68
+ }
69
+ catch (error) {
70
+ console.warn('[generationArchiveStore] save failed', error);
71
+ }
72
+ }
73
+ export async function clearGenerationArchive(conversationId) {
74
+ if (!conversationId)
75
+ return;
76
+ try {
77
+ const db = await openDb();
78
+ await new Promise((resolve, reject) => {
79
+ const tx = db.transaction(STORE, 'readwrite');
80
+ tx.objectStore(STORE).delete(conversationId);
81
+ tx.oncomplete = () => resolve();
82
+ tx.onerror = () => reject(tx.error);
83
+ });
84
+ }
85
+ catch {
86
+ /* ignore */
87
+ }
88
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Cloudflare Image Transformations for chat attachment previews (display only).
3
+ */
4
+ export type ImageTransformOptions = {
5
+ width: number;
6
+ height?: number;
7
+ fit?: 'cover' | 'contain' | 'crop' | 'scale-down';
8
+ quality?: number;
9
+ };
10
+ /** Path-style Cloudflare transform URL, or the original when not on an allowlisted host. */
11
+ export declare function buildTransformedUrl(url: string | null | undefined, options: ImageTransformOptions): string;
12
+ export declare function buildImageThumbnailUrl(url: string | null | undefined, renderedCssPx: number): string;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Cloudflare Image Transformations for chat attachment previews (display only).
3
+ */
4
+ /** Matches site `PUBLIC_IMAGE_TRANSFORM_HOSTS` defaults (library build cannot read Vite env). */
5
+ const TRANSFORM_HOSTS = 'static.widgetic.com,cdn.widgetic.com'
6
+ .split(',')
7
+ .map((host) => host.trim().toLowerCase())
8
+ .filter(Boolean);
9
+ const ENABLED = true;
10
+ function isTransformable(url) {
11
+ if (!ENABLED || !url)
12
+ return false;
13
+ if (url.startsWith('blob:') || url.startsWith('data:'))
14
+ return false;
15
+ try {
16
+ const parsed = new URL(url);
17
+ if (parsed.protocol !== 'https:')
18
+ return false;
19
+ return TRANSFORM_HOSTS.includes(parsed.hostname.toLowerCase());
20
+ }
21
+ catch {
22
+ return false;
23
+ }
24
+ }
25
+ /** Path-style Cloudflare transform URL, or the original when not on an allowlisted host. */
26
+ export function buildTransformedUrl(url, options) {
27
+ const source = url ?? '';
28
+ if (!isTransformable(source))
29
+ return source;
30
+ const parts = [`width=${options.width}`];
31
+ if (options.height)
32
+ parts.push(`height=${options.height}`);
33
+ else if (options.fit === 'cover')
34
+ parts.push(`height=${options.width}`);
35
+ if (options.fit)
36
+ parts.push(`fit=${options.fit}`);
37
+ parts.push(`quality=${options.quality ?? 75}`);
38
+ parts.push('format=auto');
39
+ const parsed = new URL(source);
40
+ return `${parsed.origin}/cdn-cgi/image/${parts.join(',')}/${source}`;
41
+ }
42
+ export function buildImageThumbnailUrl(url, renderedCssPx) {
43
+ const width = Math.min(Math.round(renderedCssPx * 2), 640);
44
+ return buildTransformedUrl(url, { width, fit: 'cover', quality: 80 });
45
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Merges a suggestion label into the composer draft without sending.
3
+ * Empty draft: replace. Nonempty: append after a single space (one line, caret at end).
4
+ */
5
+ export declare function mergeSuggestionIntoDraft(currentDraft: string, suggestion: string): string;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Merges a suggestion label into the composer draft without sending.
3
+ * Empty draft: replace. Nonempty: append after a single space (one line, caret at end).
4
+ */
5
+ export function mergeSuggestionIntoDraft(currentDraft, suggestion) {
6
+ const trimmed = suggestion.trim();
7
+ if (!trimmed)
8
+ return currentDraft;
9
+ const draft = currentDraft;
10
+ if (!draft.trim())
11
+ return trimmed;
12
+ if (draft.endsWith(' ') || draft.endsWith('\n'))
13
+ return `${draft}${trimmed}`;
14
+ return `${draft} ${trimmed}`;
15
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/chat",
3
- "version": "0.1.38",
3
+ "version": "0.1.39",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -57,7 +57,7 @@
57
57
  },
58
58
  "peerDependencies": {
59
59
  "@widgetic/api-sdk": "*",
60
- "@widgetic/design-system": ">=0.5.27",
60
+ "@widgetic/design-system": ">=0.5.36",
61
61
  "svelte": "^5.25.6"
62
62
  },
63
63
  "dependencies": {
@@ -73,7 +73,7 @@
73
73
  "@tailwindcss/postcss": "^4.1.4",
74
74
  "@types/node": "^26.4.1",
75
75
  "@widgetic/api-sdk": "^1.0.10",
76
- "@widgetic/design-system": "^0.5.23",
76
+ "@widgetic/design-system": "^0.5.39",
77
77
  "@widgetic/dev-tools": "^0.2.0",
78
78
  "autoprefixer": "^10.4.20",
79
79
  "eslint": "^9.0.0",