@widgetic/chat 0.1.20 → 0.1.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -225,6 +225,16 @@ const customConfig = {
225
225
  };
226
226
  ```
227
227
 
228
+ ### Environment for local development
229
+
230
+ The demo app in this repo reads its settings from a `.env` file. The file is not committed, because every `PUBLIC_*` value ends up in the JavaScript that browsers download. Copy the template and fill it in:
231
+
232
+ ```bash
233
+ cp .env.example .env
234
+ ```
235
+
236
+ Use an ordinary API key for `PUBLIC_API_KEY`. Never put an internal service key (`wgt_srv_...`) in any `PUBLIC_*` variable.
237
+
228
238
  ## Languages
229
239
 
230
240
  The chat shows English until it is told otherwise. Two props of `Chat` change that, and both can change while the chat
@@ -522,6 +532,8 @@ The why and the silent-degrade failure mode live in
522
532
 
523
533
  ## Publishing
524
534
 
535
+ GitLab CI on `main` publishes this package. Bump `version` in `package.json` and push `main`. The job is an npm Trusted Publisher (`NPM_ID_TOKEN`) and skips a version that is already on npm. The commands further down are the laptop fallback when CI minutes are gone. The token stays in `~/.npmrc` and is never committed.
536
+
525
537
  Publishing starts here: `npm run package` builds the `dist/` directory that
526
538
  is the only content the published tarball ships. Linked consumers keep
527
539
  resolving this checkout’s files until the release lands, so a change is not
@@ -115,6 +115,11 @@
115
115
  resizeExpandsContainer?: boolean;
116
116
  /** Delta in pixels, plus the resulting chat container height (for parent-owned resize). */
117
117
  onMessagesResize?: (deltaPx: number, nextContainerHeightPx?: number) => void;
118
+ /** Pointer drag of the messages/input handle. `totalDy` is from the pointer-down, not one frame. */
119
+ onMessagesDrag?: (totalDy: number) => void;
120
+ onMessagesDragEnd?: () => void;
121
+ /** Messages older than the ones on screen. Empty, or `hasOlder: false`, means the top is the start. */
122
+ onLoadOlderMessages?: (conversationId: string) => Promise<Array<{ id?: string; hasOlder?: boolean }>>;
118
123
  /**
119
124
  * Widget Git HEAD from the host (panel lastCommitId). Used so Head / Restore chrome
120
125
  * still appears when assistant commit bubbles were never persisted.
@@ -195,7 +200,7 @@
195
200
  updateLastUserMessageAttachments: (attachments: Array<{ id?: string; url: string; file_type?: string; file_name?: string | null }>) => void;
196
201
  }
197
202
 
198
- let { context, config = {}, class: className = '', locale = null, messages: languageMessages = null, dir = undefined, style = '', isCompleted = false, onStatsUpdate, onChatReady, onCompletionToggle, onSendMessage, onLoadConversations, onLoadMessages, onCreateConversation, onSaveMessage, onRestoreCheckpointBackend, onTakeScreenshot, onConversationChange, onDraftChange, onRetryMessage, onUpgradePlans, onUploadChatFile, showHeader = true, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize, widgetHeadCommitSha = null, versionLabelByCommitSha = {}, versionLabelByPrompt = {}, versionTimeline = [], viewingVersion = null, isGenerating = false, onStopGeneration, renderDesignControls, actionBarExtras, completeReplacement, replaceComplete = false, composerExtras, storedLineLabel }: Props = $props();
203
+ let { context, config = {}, class: className = '', locale = null, messages: languageMessages = null, dir = undefined, style = '', isCompleted = false, onStatsUpdate, onChatReady, onCompletionToggle, onSendMessage, onLoadConversations, onLoadMessages, onCreateConversation, onSaveMessage, onRestoreCheckpointBackend, onTakeScreenshot, onConversationChange, onDraftChange, onRetryMessage, onUpgradePlans, onUploadChatFile, showHeader = true, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize, onMessagesDrag, onMessagesDragEnd, onLoadOlderMessages, widgetHeadCommitSha = null, versionLabelByCommitSha = {}, versionLabelByPrompt = {}, versionTimeline = [], viewingVersion = null, isGenerating = false, onStopGeneration, renderDesignControls, actionBarExtras, completeReplacement, replaceComplete = false, composerExtras, storedLineLabel }: Props = $props();
199
204
 
200
205
  // The words of everything inside the chat, in the language the page chose. The page can change the language while the
201
206
  // chat is open: the settings are read again whenever they change (and setting the same language again does nothing).
@@ -292,6 +297,72 @@
292
297
  let currentMessages = $derived(
293
298
  currentConversationId && messages ? messages.byConversationId[currentConversationId] || [] : []
294
299
  );
300
+ let hasOlderMessages = $state(false);
301
+ let loadingOlderMessages = false;
302
+
303
+ function messageListHasOlder(list: unknown): boolean {
304
+ return !!list && (list as { hasOlder?: boolean }).hasOlder === true;
305
+ }
306
+
307
+ function loadedMessagesCoverVersion(version: number): boolean {
308
+ const entry = (versionTimeline || []).find((row) => row.version === version);
309
+ if (!entry) return true;
310
+ const sha = (entry.sha || '').slice(0, 7).toLowerCase();
311
+ const prompt = (entry.prompt || '').trim();
312
+ if (!sha && !prompt) return true;
313
+ const list = currentConversationId ? getCurrentMessages(currentConversationId) : [];
314
+ return list.some((message) => {
315
+ const text = message.messageContent || '';
316
+ if (sha && text.toLowerCase().includes(sha)) return true;
317
+ return !!prompt && text.trim() === prompt;
318
+ });
319
+ }
320
+
321
+ async function loadOlderMessages(): Promise<boolean> {
322
+ if (!currentConversationId || !onLoadOlderMessages || loadingOlderMessages || !hasOlderMessages) return false;
323
+ loadingOlderMessages = true;
324
+ try {
325
+ const older = await onLoadOlderMessages(currentConversationId);
326
+ hasOlderMessages = messageListHasOlder(older);
327
+ if (!older?.length) {
328
+ hasOlderMessages = false;
329
+ return false;
330
+ }
331
+ const existing = getCurrentMessages(currentConversationId);
332
+ const seen = new Set(existing.map((message) => message.id));
333
+ const fresh = older.filter((message) => message?.id && !seen.has(message.id));
334
+ if (fresh.length === 0) return false;
335
+ chatStore.actions.setMessages(currentConversationId, [...fresh, ...existing]);
336
+ return true;
337
+ } catch (error) {
338
+ console.warn('[Chat] Failed to load older messages:', error);
339
+ return false;
340
+ } finally {
341
+ loadingOlderMessages = false;
342
+ }
343
+ }
344
+
345
+ let versionPageToken = 0;
346
+ $effect(() => {
347
+ const version = selectedViewingVersion;
348
+ const id = currentConversationId;
349
+ if (version == null || !id || !hasOlderMessages) return;
350
+ if (loadedMessagesCoverVersion(version)) return;
351
+ const token = ++versionPageToken;
352
+ void (async () => {
353
+ let guard = 0;
354
+ while (
355
+ token === versionPageToken
356
+ && guard < 20
357
+ && hasOlderMessages
358
+ && !loadedMessagesCoverVersion(version)
359
+ ) {
360
+ guard += 1;
361
+ const loaded = await loadOlderMessages();
362
+ if (!loaded) break;
363
+ }
364
+ })();
365
+ });
295
366
  let availableConversations = $derived(
296
367
  context && conversations ? conversations.byContextId[context.id] || [] : []
297
368
  );
@@ -310,6 +381,7 @@
310
381
  ? await onLoadMessages(primaryId)
311
382
  : await chatService.getMessages(primaryId);
312
383
  const initialMessageList = initialLoadedMessages || [];
384
+ hasOlderMessages = messageListHasOlder(initialMessageList);
313
385
  chatStore.actions.setMessages(primaryId, initialMessageList);
314
386
 
315
387
  if (initialMessageList.length > 0 || conversations.length === 1) {
@@ -337,6 +409,7 @@
337
409
 
338
410
  const foundWithHistory = probeResults.find((res) => res && res.messages.length > 0);
339
411
  if (foundWithHistory) {
412
+ hasOlderMessages = messageListHasOlder(foundWithHistory.messages);
340
413
  chatStore.actions.setMessages(foundWithHistory.id, foundWithHistory.messages);
341
414
  currentConversationId = foundWithHistory.id;
342
415
  markWidgetHeadAtLatestCommit();
@@ -489,6 +562,7 @@
489
562
  const messages = onLoadMessages
490
563
  ? await onLoadMessages(conversationId)
491
564
  : await chatService.getMessages(conversationId);
565
+ hasOlderMessages = messageListHasOlder(messages);
492
566
  chatStore.actions.setMessages(conversationId, messages);
493
567
  markWidgetHeadAtLatestCommit();
494
568
  } catch (error) {
@@ -1495,6 +1569,7 @@
1495
1569
  if (wouldRegressHead) {
1496
1570
  // chatLog('[Chat] Keep local messages — DB reload would regress HEAD commit');
1497
1571
  } else {
1572
+ hasOlderMessages = messageListHasOlder(loaded);
1498
1573
  chatStore.actions.setMessages(currentConversationId, loaded);
1499
1574
  }
1500
1575
  }
@@ -1655,7 +1730,9 @@
1655
1730
 
1656
1731
  const onMove = (ev: PointerEvent) => {
1657
1732
  const dy = ev.clientY - startY;
1658
- if (resizeExpandsContainer) {
1733
+ if (resizeExpandsContainer && onMessagesDrag) {
1734
+ onMessagesDrag(dy);
1735
+ } else if (resizeExpandsContainer) {
1659
1736
  const frameDelta = dy - lastDy;
1660
1737
  lastDy = dy;
1661
1738
  if (frameDelta !== 0) onMessagesResize?.(frameDelta);
@@ -1664,6 +1741,7 @@
1664
1741
  }
1665
1742
  };
1666
1743
  const onUp = () => {
1744
+ if (resizeExpandsContainer && onMessagesDrag) onMessagesDragEnd?.();
1667
1745
  isResizingMessages = false;
1668
1746
  try {
1669
1747
  handle.releasePointerCapture?.(e.pointerId);
@@ -1735,6 +1813,8 @@
1735
1813
  versionLabelByPrompt={promptVersionLabels}
1736
1814
  {versionTimeline}
1737
1815
  viewingVersion={selectedViewingVersion}
1816
+ {hasOlderMessages}
1817
+ onRequestOlderMessages={() => loadOlderMessages()}
1738
1818
  showCommitMeta={showLogs}
1739
1819
  isGenerating={isGenerating || isLoading}
1740
1820
  onSuggestionSelected={handleSuggestionSelected}
@@ -157,6 +157,14 @@ interface Props {
157
157
  resizeExpandsContainer?: boolean;
158
158
  /** Delta in pixels, plus the resulting chat container height (for parent-owned resize). */
159
159
  onMessagesResize?: (deltaPx: number, nextContainerHeightPx?: number) => void;
160
+ /** Pointer drag of the messages/input handle. `totalDy` is from the pointer-down, not one frame. */
161
+ onMessagesDrag?: (totalDy: number) => void;
162
+ onMessagesDragEnd?: () => void;
163
+ /** Messages older than the ones on screen. Empty, or `hasOlder: false`, means the top is the start. */
164
+ onLoadOlderMessages?: (conversationId: string) => Promise<Array<{
165
+ id?: string;
166
+ hasOlder?: boolean;
167
+ }>>;
160
168
  /**
161
169
  * Widget Git HEAD from the host (panel lastCommitId). Used so Head / Restore chrome
162
170
  * still appears when assistant commit bubbles were never persisted.
@@ -80,6 +80,10 @@
80
80
  renderDesignControls?: Snippet<[DesignControlRequest]>;
81
81
  /** Host translation for lines saved in English (see Chat `storedLineLabel`). */
82
82
  storedLineLabel?: (content: string) => string;
83
+ /** Older messages exist above the ones on screen. */
84
+ hasOlderMessages?: boolean;
85
+ /** Called when the list is scrolled to the top, so the host can prepend the previous page. */
86
+ onRequestOlderMessages?: () => Promise<boolean | void>;
83
87
  }
84
88
 
85
89
  let {
@@ -105,6 +109,8 @@
105
109
  onClarificationSuggestionSelected,
106
110
  renderDesignControls,
107
111
  storedLineLabel,
112
+ hasOlderMessages = false,
113
+ onRequestOlderMessages,
108
114
  }: Props = $props();
109
115
 
110
116
  /** What a visitor reads for stored assistant/system lines; matching still uses the English stored text. */
@@ -688,7 +694,6 @@
688
694
  * available in Debug ON too — the assistant summary and the user-side chrome coexist. */
689
695
  function showCommitMetaOnUserTurn(turn: ChatTurn): boolean {
690
696
  return !!getTurnHeadOrCommitReply(turn)
691
- || canRestoreLegacyUserTurn(turn)
692
697
  || canRestoreFailedLastTurn(turn)
693
698
  || !!versionLabelFromPrompt(turn);
694
699
  }
@@ -740,16 +745,40 @@
740
745
  if (distance !== 0) container.scrollBy({ top: distance, behavior: 'smooth' });
741
746
  }
742
747
 
743
- /** Version dropdown changes which commit is "here" — bring that turn into view. */
748
+ /**
749
+ * The selected version's turn is current. Pinning the list to the bottom
750
+ * would hide it again whenever messages finish loading.
751
+ */
752
+ function viewingTurnIndex(): number {
753
+ return chatTurns.findIndex((turn) => isViewingTurn(turn));
754
+ }
755
+
756
+ function shouldPinChatToBottom(): boolean {
757
+ if (viewingVersion != null) {
758
+ const hereIndex = viewingTurnIndex();
759
+ if (hereIndex < 0 || hereIndex < chatTurns.length - 1) return false;
760
+ }
761
+ return autoScroll;
762
+ }
763
+
764
+ /**
765
+ * Scroll to the selected version only when that selection changes.
766
+ * A page of older messages must not pull the list back to the latest turn.
767
+ */
768
+ let scrolledViewKey = '';
744
769
  $effect(() => {
745
770
  const version = viewingVersion;
746
- const sha = widgetHeadCommitSha;
747
- if ((version == null && !sha) || !messagesContainer) return;
771
+ const sha = widgetHeadCommitSha ?? '';
772
+ const key = `${version ?? ''}|${sha}`;
773
+ const turnCount = chatTurns.length;
774
+ if ((version == null && !sha) || !messagesContainer || turnCount === 0) return;
775
+ if (key === scrolledViewKey || pendingOlderScroll) return;
748
776
  void tick().then(() => {
749
- const here = messagesContainer?.querySelector('[data-you-are-here="true"]');
750
- if (here && messagesContainer) {
751
- scrollIntoViewWithin(messagesContainer, here);
752
- }
777
+ if (!messagesContainer || pendingOlderScroll) return;
778
+ const here = messagesContainer.querySelector('[data-you-are-here="true"]');
779
+ if (!here) return;
780
+ scrollIntoViewWithin(messagesContainer, here);
781
+ scrolledViewKey = key;
753
782
  });
754
783
  });
755
784
 
@@ -803,6 +832,10 @@
803
832
  let messagesContainer: HTMLElement;
804
833
  let showSuggestionsInline = $state(false);
805
834
  let autoScroll = $state(true);
835
+ // The first paint is shorter than the loaded page. Scrolling then, or treating
836
+ // that short box as "the user is at the top", loads older pages and never
837
+ // lands on the newest message. Pin once, after this load has finished.
838
+ let initialBottomPinned = $state(false);
806
839
 
807
840
  // Collapse an expanded suggestions panel as soon as a generation starts, so it
808
841
  // does not reappear under the new turn when generation ends.
@@ -829,27 +862,44 @@
829
862
  // Auto-scroll to bottom when new messages arrive or on initial load.
830
863
  // Also scrolls on mount/conversation-switch when messages are already present.
831
864
  $effect(() => {
832
- if (messagesContainer && autoScroll && visibleMessages.length > 0) {
833
- tick().then(() => {
834
- messagesContainer?.scrollTo({
835
- top: messagesContainer.scrollHeight,
836
- behavior: 'smooth'
865
+ if (isLoading) {
866
+ initialBottomPinned = false;
867
+ return;
868
+ }
869
+ const pinToBottom = shouldPinChatToBottom();
870
+ const messageCount = visibleMessages.length;
871
+ if (!initialBottomPinned && messagesContainer && messageCount > 0 && !pendingOlderScroll) {
872
+ void tick().then(() => {
873
+ requestAnimationFrame(() => {
874
+ if (!messagesContainer || pendingOlderScroll || isLoading) return;
875
+ if (shouldPinChatToBottom()) {
876
+ messagesContainer.scrollTop = messagesContainer.scrollHeight;
877
+ }
878
+ initialBottomPinned = true;
837
879
  });
838
880
  });
839
881
  }
882
+ if (messagesContainer && pinToBottom && messageCount > 0 && !pendingOlderScroll && initialBottomPinned) {
883
+ tick().then(() => {
884
+ if (!messagesContainer || pendingOlderScroll || !shouldPinChatToBottom()) return;
885
+ messagesContainer.scrollTop = messagesContainer.scrollHeight;
886
+ });
887
+ }
840
888
  });
841
889
 
842
890
  // Force scroll to bottom on initial mount (messages may already be loaded)
843
891
  onMount(() => {
844
892
  tick().then(() => {
845
- if (messagesContainer && visibleMessages.length > 0) {
893
+ if (messagesContainer && visibleMessages.length > 0 && !isLoading && shouldPinChatToBottom()) {
846
894
  scrollToBottomInstant();
895
+ initialBottomPinned = true;
847
896
  }
848
897
  // Re-pin after late container resizes (panel open animation, parent
849
898
  // layout settling, height restored from prefs).
850
899
  if (messagesContainer && typeof ResizeObserver !== 'undefined') {
851
900
  containerResizeObserver = new ResizeObserver(() => {
852
- if (autoScroll) scrollToBottomInstant();
901
+ if (pendingOlderScroll || !initialBottomPinned) return;
902
+ if (shouldPinChatToBottom()) scrollToBottomInstant();
853
903
  });
854
904
  containerResizeObserver.observe(messagesContainer);
855
905
  }
@@ -861,12 +911,46 @@
861
911
  containerResizeObserver = null;
862
912
  });
863
913
 
914
+ let olderRequestInFlight = false;
915
+ let pendingOlderScroll: { height: number; top: number } | null = null;
916
+
864
917
  function handleScroll() {
865
918
  if (!messagesContainer) return;
866
919
  const { scrollTop, scrollHeight, clientHeight } = messagesContainer;
920
+ if (pendingOlderScroll || !initialBottomPinned) return;
867
921
  autoScroll = scrollTop + clientHeight >= scrollHeight - 10;
922
+ if (scrollTop > 80 || !hasOlderMessages || olderRequestInFlight || !onRequestOlderMessages) return;
923
+ autoScroll = false;
924
+ olderRequestInFlight = true;
925
+ pendingOlderScroll = { height: scrollHeight, top: scrollTop };
926
+ void Promise.resolve(onRequestOlderMessages()).finally(() => {
927
+ olderRequestInFlight = false;
928
+ });
868
929
  }
869
930
 
931
+ $effect(() => {
932
+ const count = messages.length;
933
+ const snap = pendingOlderScroll;
934
+ if (!snap || count === 0) return;
935
+ void tick().then(() => {
936
+ const place = () => {
937
+ if (!messagesContainer || !pendingOlderScroll) return true;
938
+ const delta = messagesContainer.scrollHeight - pendingOlderScroll.height;
939
+ if (delta <= 0) return false;
940
+ const previousBehavior = messagesContainer.style.scrollBehavior;
941
+ messagesContainer.style.scrollBehavior = 'auto';
942
+ messagesContainer.scrollTop = pendingOlderScroll.top + delta;
943
+ messagesContainer.style.scrollBehavior = previousBehavior;
944
+ pendingOlderScroll = null;
945
+ return true;
946
+ };
947
+ if (place()) return;
948
+ requestAnimationFrame(() => {
949
+ place();
950
+ });
951
+ });
952
+ });
953
+
870
954
  function formatTime(date: Date): string {
871
955
  return new Intl.DateTimeFormat('en-US', {
872
956
  hour: '2-digit',
@@ -1181,7 +1265,7 @@
1181
1265
  bind:this={messagesContainer}
1182
1266
  class="{className ? className : 'prompt-chat-messages-ct'} prompt-chat-messages-scroll flex flex-col overflow-y-auto space-y-4 pb-3"
1183
1267
  class:loading={isLoading}
1184
- style="scroll-behavior: smooth; padding: 12px;"
1268
+ style="padding: 12px; overflow-anchor: none;"
1185
1269
  use:detectMessagesScrollbar
1186
1270
  onscroll={handleScroll}
1187
1271
  >
@@ -1313,7 +1397,7 @@
1313
1397
  </span>
1314
1398
  {/if}
1315
1399
  </div>
1316
- {#if !turn.user?.id?.startsWith('version-fork-') && !isLoading && ((commitReply && (canRestoreToMessage(commitReply) || isHeadCommitReply(commitReply))) || canRestoreLegacyUserTurn(turn) || canRestoreFailedLastTurn(turn))}
1400
+ {#if !turn.user?.id?.startsWith('version-fork-') && !isLoading && ((commitReply && (canRestoreToMessage(commitReply) || isHeadCommitReply(commitReply))) || canRestoreFailedLastTurn(turn))}
1317
1401
  {@const restoreIsCurrentHead = !!(commitReply && isHeadCommitReply(commitReply))}
1318
1402
  <button
1319
1403
  class="restore-checkpoint-btn shrink-0"
@@ -66,6 +66,10 @@ interface Props {
66
66
  renderDesignControls?: Snippet<[DesignControlRequest]>;
67
67
  /** Host translation for lines saved in English (see Chat `storedLineLabel`). */
68
68
  storedLineLabel?: (content: string) => string;
69
+ /** Older messages exist above the ones on screen. */
70
+ hasOlderMessages?: boolean;
71
+ /** Called when the list is scrolled to the top, so the host can prepend the previous page. */
72
+ onRequestOlderMessages?: () => Promise<boolean | void>;
69
73
  }
70
74
  declare const ChatMessages: import("svelte").Component<Props, {}, "">;
71
75
  type ChatMessages = ReturnType<typeof ChatMessages>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/chat",
3
- "version": "0.1.20",
3
+ "version": "0.1.22",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -45,6 +45,7 @@
45
45
  "dev-sv": "NODE_ENV=development vite dev",
46
46
  "build": "vite build",
47
47
  "package": "svelte-kit sync && svelte-package",
48
+ "publish-to-npm": "node ../dev-tools/bin/publish-package.mjs",
48
49
  "package:watch": "svelte-kit sync && svelte-package --watch",
49
50
  "prepackage:watch": "npm run lps",
50
51
  "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --diagnostic-sources \"js,svelte\"",