@widgetic/chat 0.1.19 → 0.1.21

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
@@ -1,5 +1,7 @@
1
1
  # @widgetic/chat
2
2
 
3
+ > **Internal building block.** This package is part of Widgetic's own apps and is not a supported integration surface. Partners: use [`@widgetic/ui-sdk`](https://www.npmjs.com/package/@widgetic/ui-sdk) instead.
4
+
3
5
  A modern, reusable chat module built with Svelte 5, TypeScript, and the Widgetic Design System. Designed for canvas-based platforms with frame content integration and LLM communication.
4
6
 
5
7
  ## Features
@@ -223,6 +225,16 @@ const customConfig = {
223
225
  };
224
226
  ```
225
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
+
226
238
  ## Languages
227
239
 
228
240
  The chat shows English until it is told otherwise. Two props of `Chat` change that, and both can change while the chat
@@ -520,6 +532,8 @@ The why and the silent-degrade failure mode live in
520
532
 
521
533
  ## Publishing
522
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
+
523
537
  Publishing starts here: `npm run package` builds the `dist/` directory that
524
538
  is the only content the published tarball ships. Linked consumers keep
525
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) {
@@ -1334,6 +1408,11 @@
1334
1408
  }
1335
1409
  }
1336
1410
  if (!headId) return;
1411
+ // Copying every message forces the open chat to rebuild. Completion marks
1412
+ // the head twice (new bubble, then the status line). The second copy, on a
1413
+ // long thread, ran in the same turn as the version-menu rebuild.
1414
+ const needsWrite = msgs.some((m) => (m.id === headId) !== !!m.isWidgetHead || !!m.rolledBackAt);
1415
+ if (!needsWrite) return;
1337
1416
  const updated = msgs.map((m) => ({
1338
1417
  ...m,
1339
1418
  isWidgetHead: m.id === headId,
@@ -1490,6 +1569,7 @@
1490
1569
  if (wouldRegressHead) {
1491
1570
  // chatLog('[Chat] Keep local messages — DB reload would regress HEAD commit');
1492
1571
  } else {
1572
+ hasOlderMessages = messageListHasOlder(loaded);
1493
1573
  chatStore.actions.setMessages(currentConversationId, loaded);
1494
1574
  }
1495
1575
  }
@@ -1650,7 +1730,9 @@
1650
1730
 
1651
1731
  const onMove = (ev: PointerEvent) => {
1652
1732
  const dy = ev.clientY - startY;
1653
- if (resizeExpandsContainer) {
1733
+ if (resizeExpandsContainer && onMessagesDrag) {
1734
+ onMessagesDrag(dy);
1735
+ } else if (resizeExpandsContainer) {
1654
1736
  const frameDelta = dy - lastDy;
1655
1737
  lastDy = dy;
1656
1738
  if (frameDelta !== 0) onMessagesResize?.(frameDelta);
@@ -1659,6 +1741,7 @@
1659
1741
  }
1660
1742
  };
1661
1743
  const onUp = () => {
1744
+ if (resizeExpandsContainer && onMessagesDrag) onMessagesDragEnd?.();
1662
1745
  isResizingMessages = false;
1663
1746
  try {
1664
1747
  handle.releasePointerCapture?.(e.pointerId);
@@ -1730,6 +1813,8 @@
1730
1813
  versionLabelByPrompt={promptVersionLabels}
1731
1814
  {versionTimeline}
1732
1815
  viewingVersion={selectedViewingVersion}
1816
+ {hasOlderMessages}
1817
+ onRequestOlderMessages={() => loadOlderMessages()}
1733
1818
  showCommitMeta={showLogs}
1734
1819
  isGenerating={isGenerating || isLoading}
1735
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. */
@@ -740,16 +746,40 @@
740
746
  if (distance !== 0) container.scrollBy({ top: distance, behavior: 'smooth' });
741
747
  }
742
748
 
743
- /** Version dropdown changes which commit is "here" — bring that turn into view. */
749
+ /**
750
+ * The selected version's turn is current. Pinning the list to the bottom
751
+ * would hide it again whenever messages finish loading.
752
+ */
753
+ function viewingTurnIndex(): number {
754
+ return chatTurns.findIndex((turn) => isViewingTurn(turn));
755
+ }
756
+
757
+ function shouldPinChatToBottom(): boolean {
758
+ if (viewingVersion != null) {
759
+ const hereIndex = viewingTurnIndex();
760
+ if (hereIndex < 0 || hereIndex < chatTurns.length - 1) return false;
761
+ }
762
+ return autoScroll;
763
+ }
764
+
765
+ /**
766
+ * Scroll to the selected version only when that selection changes.
767
+ * A page of older messages must not pull the list back to the latest turn.
768
+ */
769
+ let scrolledViewKey = '';
744
770
  $effect(() => {
745
771
  const version = viewingVersion;
746
- const sha = widgetHeadCommitSha;
747
- if ((version == null && !sha) || !messagesContainer) return;
772
+ const sha = widgetHeadCommitSha ?? '';
773
+ const key = `${version ?? ''}|${sha}`;
774
+ const turnCount = chatTurns.length;
775
+ if ((version == null && !sha) || !messagesContainer || turnCount === 0) return;
776
+ if (key === scrolledViewKey || pendingOlderScroll) return;
748
777
  void tick().then(() => {
749
- const here = messagesContainer?.querySelector('[data-you-are-here="true"]');
750
- if (here && messagesContainer) {
751
- scrollIntoViewWithin(messagesContainer, here);
752
- }
778
+ if (!messagesContainer || pendingOlderScroll) return;
779
+ const here = messagesContainer.querySelector('[data-you-are-here="true"]');
780
+ if (!here) return;
781
+ scrollIntoViewWithin(messagesContainer, here);
782
+ scrolledViewKey = key;
753
783
  });
754
784
  });
755
785
 
@@ -829,12 +859,12 @@
829
859
  // Auto-scroll to bottom when new messages arrive or on initial load.
830
860
  // Also scrolls on mount/conversation-switch when messages are already present.
831
861
  $effect(() => {
832
- if (messagesContainer && autoScroll && visibleMessages.length > 0) {
862
+ const pinToBottom = shouldPinChatToBottom();
863
+ const messageCount = visibleMessages.length;
864
+ if (messagesContainer && pinToBottom && messageCount > 0 && !pendingOlderScroll) {
833
865
  tick().then(() => {
834
- messagesContainer?.scrollTo({
835
- top: messagesContainer.scrollHeight,
836
- behavior: 'smooth'
837
- });
866
+ if (!messagesContainer || pendingOlderScroll || !shouldPinChatToBottom()) return;
867
+ messagesContainer.scrollTop = messagesContainer.scrollHeight;
838
868
  });
839
869
  }
840
870
  });
@@ -842,14 +872,15 @@
842
872
  // Force scroll to bottom on initial mount (messages may already be loaded)
843
873
  onMount(() => {
844
874
  tick().then(() => {
845
- if (messagesContainer && visibleMessages.length > 0) {
875
+ if (messagesContainer && visibleMessages.length > 0 && shouldPinChatToBottom()) {
846
876
  scrollToBottomInstant();
847
877
  }
848
878
  // Re-pin after late container resizes (panel open animation, parent
849
879
  // layout settling, height restored from prefs).
850
880
  if (messagesContainer && typeof ResizeObserver !== 'undefined') {
851
881
  containerResizeObserver = new ResizeObserver(() => {
852
- if (autoScroll) scrollToBottomInstant();
882
+ if (pendingOlderScroll) return;
883
+ if (shouldPinChatToBottom()) scrollToBottomInstant();
853
884
  });
854
885
  containerResizeObserver.observe(messagesContainer);
855
886
  }
@@ -861,12 +892,46 @@
861
892
  containerResizeObserver = null;
862
893
  });
863
894
 
895
+ let olderRequestInFlight = false;
896
+ let pendingOlderScroll: { height: number; top: number } | null = null;
897
+
864
898
  function handleScroll() {
865
899
  if (!messagesContainer) return;
866
900
  const { scrollTop, scrollHeight, clientHeight } = messagesContainer;
901
+ if (pendingOlderScroll) return;
867
902
  autoScroll = scrollTop + clientHeight >= scrollHeight - 10;
903
+ if (scrollTop > 80 || !hasOlderMessages || olderRequestInFlight || !onRequestOlderMessages) return;
904
+ autoScroll = false;
905
+ olderRequestInFlight = true;
906
+ pendingOlderScroll = { height: scrollHeight, top: scrollTop };
907
+ void Promise.resolve(onRequestOlderMessages()).finally(() => {
908
+ olderRequestInFlight = false;
909
+ });
868
910
  }
869
911
 
912
+ $effect(() => {
913
+ const count = messages.length;
914
+ const snap = pendingOlderScroll;
915
+ if (!snap || count === 0) return;
916
+ void tick().then(() => {
917
+ const place = () => {
918
+ if (!messagesContainer || !pendingOlderScroll) return true;
919
+ const delta = messagesContainer.scrollHeight - pendingOlderScroll.height;
920
+ if (delta <= 0) return false;
921
+ const previousBehavior = messagesContainer.style.scrollBehavior;
922
+ messagesContainer.style.scrollBehavior = 'auto';
923
+ messagesContainer.scrollTop = pendingOlderScroll.top + delta;
924
+ messagesContainer.style.scrollBehavior = previousBehavior;
925
+ pendingOlderScroll = null;
926
+ return true;
927
+ };
928
+ if (place()) return;
929
+ requestAnimationFrame(() => {
930
+ place();
931
+ });
932
+ });
933
+ });
934
+
870
935
  function formatTime(date: Date): string {
871
936
  return new Intl.DateTimeFormat('en-US', {
872
937
  hour: '2-digit',
@@ -1181,7 +1246,7 @@
1181
1246
  bind:this={messagesContainer}
1182
1247
  class="{className ? className : 'prompt-chat-messages-ct'} prompt-chat-messages-scroll flex flex-col overflow-y-auto space-y-4 pb-3"
1183
1248
  class:loading={isLoading}
1184
- style="scroll-behavior: smooth; padding: 12px;"
1249
+ style="padding: 12px; overflow-anchor: none;"
1185
1250
  use:detectMessagesScrollbar
1186
1251
  onscroll={handleScroll}
1187
1252
  >
@@ -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>;
@@ -172,6 +172,14 @@ function createChatStore() {
172
172
  */
173
173
  actions: {
174
174
  setActiveContext: (contextId, isExpanded) => {
175
+ const current = get(chatStore);
176
+ const nextExpanded = isExpanded ?? current.activeContext.isExpanded;
177
+ // A new object with the same id still notified every subscriber. The chat
178
+ // effect runs on each parent render (the context object is inline), and
179
+ // that write scheduled another render of every open conversation.
180
+ if (current.activeContext.contextId === contextId && current.activeContext.isExpanded === nextExpanded) {
181
+ return;
182
+ }
175
183
  update(state => ({
176
184
  ...state,
177
185
  activeContext: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/chat",
3
- "version": "0.1.19",
3
+ "version": "0.1.21",
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": "npm version patch --no-git-tag-version && npm run package && npm publish --ignore-scripts --access public",
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\"",
@@ -71,7 +72,7 @@
71
72
  "@tailwindcss/postcss": "^4.1.4",
72
73
  "@types/node": "^26.4.1",
73
74
  "@widgetic/api-sdk": "^1.0.10",
74
- "@widgetic/design-system": "^0.5.12",
75
+ "@widgetic/design-system": "^0.5.17",
75
76
  "@widgetic/dev-tools": "^0.2.0",
76
77
  "autoprefixer": "^10.4.20",
77
78
  "eslint": "^9.0.0",