@widgetic/chat 0.1.11 → 0.1.13

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
@@ -403,6 +403,91 @@ import type {
403
403
 
404
404
  ## Development
405
405
 
406
+ ### Sibling packages
407
+
408
+ This app compiles sibling `@widgetic/*` source in dev through the dev-alias
409
+ setup `@widgetic/dev-tools` owns. The alias tables, the `$lib` remap, and
410
+ everything else the mapping needs come from the installed
411
+ `@widgetic/dev-tools` dependency. An ordinary `npm install` is the whole
412
+ setup — there is no linking step.
413
+
414
+ The why and the silent-degrade failure mode live in
415
+ [the dev-tools README](../dev-tools/README.md).
416
+
417
+ ## Publishing
418
+
419
+ Publishing starts here: `npm run package` builds the `dist/` directory that
420
+ is the only content the published tarball ships. Linked consumers keep
421
+ resolving this checkout’s files until the release lands, so a change is not
422
+ real for anyone else until it publishes. After publishing, each consumer
423
+ package bumps its dependency to the new version and refreshes its lockfile
424
+ with `npm install`, so `npm ci` resolves the release from the registry. A
425
+ consumer that skips the lockfile refresh keeps resolving the old version, so
426
+ the version bump and the lockfile refresh land as one commit.
427
+
428
+ #### Local development
429
+
430
+ ```bash
431
+ npm run i
432
+ ```
433
+
434
+ Installs dependencies and runs `npm run lps` first, which links the sibling
435
+ `@widgetic/*` checkouts (`dev-tools`, `api-sdk`, `design-system`) into
436
+ `node_modules`. `dev` and `package:watch` re-run the link script
437
+ automatically, and `npm run lps:check` verifies the links are healthy.
438
+
439
+ ```bash
440
+ npm run dev
441
+ ```
442
+
443
+ Starts Vite in development mode (`dev-sv`) and opens the app in a new
444
+ browser tab. This is the SvelteKit app wrapper around the library — for
445
+ consuming `@widgetic/chat` in another project, see Installation above.
446
+
447
+ #### Checks
448
+
449
+ ```bash
450
+ npm run check # svelte-kit sync + svelte-check
451
+ npm run lint # prettier --check + eslint
452
+ npm run format # prettier --write
453
+ ```
454
+
455
+ #### Building the library output
456
+
457
+ `npm run package` (svelte-package) emits `dist/` — the published package
458
+ shape the manifest promises
459
+ (`dist/{index,components,stores,services,types}/index.{js,d.ts}`), which
460
+ the link-doctor verifies exist. `npm run package:watch` re-emits on every
461
+ source edit; `npm run build` builds the demo app itself.
462
+
463
+ #### The link script (`npm run lps`)
464
+
465
+ `dev` and `package:watch` run `scripts/link-siblings.mjs` first, which keeps
466
+ the `node_modules/@widgetic/*` symlinks pointing at the sibling checkouts
467
+ (`dev-tools`, `api-sdk`, `design-system`). It is idempotent, repairs stale
468
+ links, and skips a sibling whose checkout is absent — so it is safe on every
469
+ machine and after every fresh install (`npm i` prunes unowned links).
470
+ `npm run lps:check` prints the link table for verification.
471
+
472
+ #### Publishing and the consumers
473
+
474
+ `@widgetic/chat` is consumed by the creator (dev source aliases plus
475
+ `node_modules/@widgetic/chat` for type-check and any non-aliased session) and
476
+ by the site. The published tarball is the contract for both, so before
477
+ depending on a new version elsewhere:
478
+
479
+ ```sh
480
+ npm run lps:check # sibling links healthy
481
+ npm run package # dist/ is fresh — svelte-package output
482
+ npm publish
483
+ ```
484
+
485
+ For iterating on chat features against the creator without publishing, run
486
+ `npm run package:watch` here and keep the creator's
487
+ `node_modules/@widgetic/chat` linked to this checkout — every saved edit
488
+ lands in the creator's installed package within seconds, no manual dist
489
+ copying. The same workflow generalizes to the other `@widgetic/*` siblings.
490
+
406
491
  ### Building
407
492
 
408
493
  ```bash
@@ -4,6 +4,7 @@
4
4
  import { createChatService } from '../services/chatService.js';
5
5
  import { setLogsEnabled, chatLog, chatWarn } from '../utils/logger.js';
6
6
  import type { ChatConfig, ChatContext } from '../types/index.js';
7
+ import type { ClarificationSuggestion } from '../types/message.js';
7
8
  import type { AttachmentInput } from '../types/attachment.js';
8
9
  import ChatMessages from './ChatMessages.svelte';
9
10
  import ChatInput from './ChatInput.svelte';
@@ -22,7 +23,10 @@
22
23
  onChatReady?: (chatMethods: ChatMethods) => void;
23
24
  onCompletionToggle?: (detail?: { conversationId: string | null; completed: boolean }) => void;
24
25
  /** When provided, called instead of the built-in mock service for sending messages.
25
- * The parent handles the actual API call and can push assistant messages via addAssistantMessage. */
26
+ * The parent handles the actual API call and can push assistant messages via addAssistantMessage.
27
+ * `options` carries per-send modifiers — e.g. `skipIntentGate: true` plus the tapped chip's
28
+ * `chipIntent` when the send is an explicit override of a clarification card (see
29
+ * handleClarificationSuggestionSelected). */
26
30
  onSendMessage?: (
27
31
  content: string,
28
32
  attachments?: Array<{
@@ -33,6 +37,7 @@
33
37
  fileName: string;
34
38
  fileSize?: number;
35
39
  }>,
40
+ options?: { skipIntentGate?: boolean; chipIntent?: ClarificationSuggestion['intent'] },
36
41
  ) => Promise<void>;
37
42
  /** Backend integration callbacks — when provided, replace mock chatService methods */
38
43
  onLoadConversations?: (contextId: string) => Promise<any[] | null>;
@@ -43,6 +48,7 @@
43
48
  content: string,
44
49
  messageType: string,
45
50
  attachments?: Array<{ url?: string; file?: File; file_type?: string; file_name?: string | null; file_size?: number | null; display_order?: number }>,
51
+ suggestions?: ClarificationSuggestion[],
46
52
  ) => Promise<any>;
47
53
  onRestoreCheckpointBackend?: (conversationId: string, checkpointMessageId: string) => Promise<any>;
48
54
  onTakeScreenshot?: () => Promise<string | null>;
@@ -84,6 +90,12 @@
84
90
  * still appears when assistant commit bubbles were never persisted.
85
91
  */
86
92
  widgetHeadCommitSha?: string | null;
93
+ /**
94
+ * Short commit sha → human version label ("Version 4"). The host owns the
95
+ * mapping (it knows the widget's versions); the chat only renders it, so a
96
+ * turn reads as the version it produced instead of a commit hash.
97
+ */
98
+ versionLabelByCommitSha?: Record<string, string>;
87
99
  /** Host is running widget codegen — send button becomes stop. */
88
100
  isGenerating?: boolean;
89
101
  onStopGeneration?: () => void;
@@ -91,8 +103,8 @@
91
103
 
92
104
  // Expose methods to parent component
93
105
  interface ChatMethods {
94
- sendMessage: (content: string, attachments?: Array<File | AttachmentInput>) => Promise<void>;
95
- addAssistantMessage: (content: string, skipPersist?: boolean) => void;
106
+ sendMessage: (content: string, attachments?: Array<File | AttachmentInput>, options?: { skipIntentGate?: boolean; chipIntent?: ClarificationSuggestion['intent'] }) => Promise<void>;
107
+ addAssistantMessage: (content: string, skipPersist?: boolean, suggestions?: ClarificationSuggestion[]) => void;
96
108
  addUserMessage: (content: string, attachments?: Array<{ id: string; url: string; file_type: string; file_name: string; file_size?: number }>) => void;
97
109
  /** Returns the current conversation ID (null if no conversation is active). */
98
110
  getConversationId: () => string | null;
@@ -124,7 +136,7 @@
124
136
  updateLastUserMessageAttachments: (attachments: Array<{ id?: string; url: string; file_type?: string; file_name?: string | null }>) => void;
125
137
  }
126
138
 
127
- let { context, config = {}, class: className = '', style = '', isCompleted = false, onStatsUpdate, onChatReady, onCompletionToggle, onSendMessage, onLoadConversations, onLoadMessages, onCreateConversation, onSaveMessage, onRestoreCheckpointBackend, onTakeScreenshot, onConversationChange, onDraftChange, onRetryMessage, onUploadChatFile, showHeader = true, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize, widgetHeadCommitSha = null, isGenerating = false, onStopGeneration }: Props = $props();
139
+ let { context, config = {}, class: className = '', style = '', isCompleted = false, onStatsUpdate, onChatReady, onCompletionToggle, onSendMessage, onLoadConversations, onLoadMessages, onCreateConversation, onSaveMessage, onRestoreCheckpointBackend, onTakeScreenshot, onConversationChange, onDraftChange, onRetryMessage, onUploadChatFile, showHeader = true, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize, widgetHeadCommitSha = null, versionLabelByCommitSha = {}, isGenerating = false, onStopGeneration }: Props = $props();
128
140
 
129
141
  function notifyDraftChange() {
130
142
  onDraftChange?.();
@@ -402,7 +414,7 @@
402
414
  }
403
415
  }
404
416
 
405
- async function sendMessage(content: string, attachments?: Array<File | AttachmentInput>) {
417
+ async function sendMessage(content: string, attachments?: Array<File | AttachmentInput>, options?: { skipIntentGate?: boolean; chipIntent?: ClarificationSuggestion['intent'] }) {
406
418
  if (!currentConversationId) {
407
419
  if (initializePromise) {
408
420
  try {
@@ -515,7 +527,7 @@
515
527
  fileName: att.file?.name || 'attachment',
516
528
  fileSize: att.file?.size,
517
529
  }));
518
- await onSendMessage(submittedContent, outgoing.length > 0 ? outgoing : undefined);
530
+ await onSendMessage(submittedContent, outgoing.length > 0 ? outgoing : undefined, options);
519
531
  } else {
520
532
  const aiResponse = await chatService.processAIResponse(activeConversationId, userMessage);
521
533
  chatStore.actions.addMessage(activeConversationId, aiResponse);
@@ -534,7 +546,7 @@
534
546
  /** Add an assistant message to the current conversation (called by parent via chatMethods).
535
547
  * When skipPersist is true, the message is shown locally but not saved to DB
536
548
  * (use when the backend already persists its own version). */
537
- function addAssistantMessage(content: string, skipPersist = false) {
549
+ function addAssistantMessage(content: string, skipPersist = false, suggestions?: ClarificationSuggestion[]) {
538
550
  if (!currentConversationId) return;
539
551
  const assistantMsg = {
540
552
  id: `assistant_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
@@ -548,7 +560,8 @@
548
560
  updatedAt: new Date(),
549
561
  _optimistic: false,
550
562
  _failed: false,
551
- _retryCount: 0
563
+ _retryCount: 0,
564
+ ...(suggestions && suggestions.length > 0 ? { suggestions } : {})
552
565
  };
553
566
  chatStore.actions.addMessage(currentConversationId, assistantMsg);
554
567
 
@@ -560,7 +573,12 @@
560
573
 
561
574
  if (onSaveMessage && !skipPersist) {
562
575
  const convId = currentConversationId;
563
- onSaveMessage(convId, content, 'assistant').then(saved => {
576
+ // Suggestions ride the same write as the reply, so the clarification
577
+ // card — chips included — survives a reload. The server-side gated-turn
578
+ // persistence (intent gate) already saved this turn when it served the
579
+ // card; this write is the client-driven path (local-only conversations,
580
+ // hosts without the gate) and lands with the same shape either way.
581
+ onSaveMessage(convId, content, 'assistant', undefined, suggestions).then(saved => {
564
582
  if (saved?.id && saved.id !== assistantMsg.id) {
565
583
  chatStore.actions.updateMessageId(convId, assistantMsg.id, saved.id);
566
584
  }
@@ -916,6 +934,41 @@
916
934
  setDraftText(suggestion);
917
935
  }
918
936
 
937
+ /** Tapping a suggestion chip attached to an assistant clarification card sends it
938
+ * as the next user message. These suggestions resolve an ambiguity the intent
939
+ * gate already detected server-side, so each is a complete, valid ask — the
940
+ * card exists precisely to save the user from retyping it. Generic
941
+ * SuggestionButtons (empty state) keep their autocomplete behavior instead.
942
+ *
943
+ * Chips are structured objects ({ label, intent }): the label is display copy
944
+ * rendered verbatim, the intent is machine-readable behavior. The "generate
945
+ * anyway" chip is the card's escape hatch — identified by
946
+ * `intent === 'generate_anyway'`, never by matching its text — and re-sends
947
+ * with `skipIntentGate: true` (the server's own JSDoc for that flag says "set
948
+ * when the user explicitly chose to generate anyway after a gated response",
949
+ * and a chip tap is exactly that choice). Without the flag the server's
950
+ * verdict cache would re-serve the same card for the same message and the
951
+ * chip could never escape it. The refine chips send normally — they are new
952
+ * asks, and an ask that is still ambiguous should get the card again. The
953
+ * chip's intent rides the request as `chipIntent` so the server measures the
954
+ * conversion from the client's declaration instead of matching copy. */
955
+ async function handleClarificationSuggestionSelected(suggestion: ClarificationSuggestion) {
956
+ const trimmed = suggestion.label.trim();
957
+ if (!trimmed) return;
958
+ if (isGenerating || localIsSending || isSendingOrLoading) return;
959
+ try {
960
+ await sendMessage(trimmed, undefined, {
961
+ skipIntentGate: suggestion.intent === 'generate_anyway',
962
+ chipIntent: suggestion.intent,
963
+ });
964
+ } catch (err) {
965
+ console.error('[Chat] Clarification suggestion send failed:', err);
966
+ chatStore.actions.updateUI({
967
+ errorMessage: 'Failed to send the selected suggestion. Please try again.'
968
+ });
969
+ }
970
+ }
971
+
919
972
  async function handleRetryMessage(content: string) {
920
973
  const retryContent = content.trim();
921
974
  if (!retryContent) return;
@@ -1198,7 +1251,9 @@
1198
1251
  // chatLog('[Chat] Widget HEAD marked on message:', headId);
1199
1252
  }
1200
1253
 
1201
- const CODEGEN_STATUS_MESSAGE_REGEX = /^Code generation completed/i;
1254
+ // Terminal codegen status lines: the normal completion and the semantic-cache
1255
+ // "already done" affordance. Both are turn-deduped status bubbles.
1256
+ const CODEGEN_STATUS_MESSAGE_REGEX = /^(Code generation completed|Already done)/i;
1202
1257
 
1203
1258
  function isCodegenStatusMessage(content?: string | null): boolean {
1204
1259
  return CODEGEN_STATUS_MESSAGE_REGEX.test((content || '').trim());
@@ -1550,11 +1605,13 @@
1550
1605
  enableAutoCodeDetection={config?.features?.autoCodeDetection === true}
1551
1606
  showGenerationSummaries={config?.features?.showGenerationSummaries === true}
1552
1607
  widgetHeadCommitSha={widgetHeadCommitSha}
1608
+ versionLabelByCommitSha={versionLabelByCommitSha}
1553
1609
  showCommitMeta={showLogs}
1554
1610
  isGenerating={isGenerating || isLoading}
1555
1611
  onSuggestionSelected={handleSuggestionSelected}
1556
1612
  onRestoreCheckpoint={handleRestoreCheckpoint}
1557
1613
  onRetryMessage={handleRetryMessage}
1614
+ onClarificationSuggestionSelected={handleClarificationSuggestionSelected}
1558
1615
  />
1559
1616
  </div>
1560
1617
 
@@ -1,8 +1,12 @@
1
1
  import type { ChatConfig, ChatContext } from '../types/index.js';
2
+ import type { ClarificationSuggestion } from '../types/message.js';
2
3
  import type { AttachmentInput } from '../types/attachment.js';
3
4
  interface ChatMethods {
4
- sendMessage: (content: string, attachments?: Array<File | AttachmentInput>) => Promise<void>;
5
- addAssistantMessage: (content: string, skipPersist?: boolean) => void;
5
+ sendMessage: (content: string, attachments?: Array<File | AttachmentInput>, options?: {
6
+ skipIntentGate?: boolean;
7
+ chipIntent?: ClarificationSuggestion['intent'];
8
+ }) => Promise<void>;
9
+ addAssistantMessage: (content: string, skipPersist?: boolean, suggestions?: ClarificationSuggestion[]) => void;
6
10
  addUserMessage: (content: string, attachments?: Array<{
7
11
  id: string;
8
12
  url: string;
@@ -58,7 +62,10 @@ interface Props {
58
62
  completed: boolean;
59
63
  }) => void;
60
64
  /** When provided, called instead of the built-in mock service for sending messages.
61
- * The parent handles the actual API call and can push assistant messages via addAssistantMessage. */
65
+ * The parent handles the actual API call and can push assistant messages via addAssistantMessage.
66
+ * `options` carries per-send modifiers — e.g. `skipIntentGate: true` plus the tapped chip's
67
+ * `chipIntent` when the send is an explicit override of a clarification card (see
68
+ * handleClarificationSuggestionSelected). */
62
69
  onSendMessage?: (content: string, attachments?: Array<{
63
70
  file?: File;
64
71
  url?: string;
@@ -66,7 +73,10 @@ interface Props {
66
73
  fileType: string;
67
74
  fileName: string;
68
75
  fileSize?: number;
69
- }>) => Promise<void>;
76
+ }>, options?: {
77
+ skipIntentGate?: boolean;
78
+ chipIntent?: ClarificationSuggestion['intent'];
79
+ }) => Promise<void>;
70
80
  /** Backend integration callbacks — when provided, replace mock chatService methods */
71
81
  onLoadConversations?: (contextId: string) => Promise<any[] | null>;
72
82
  onLoadMessages?: (conversationId: string) => Promise<any[]>;
@@ -78,7 +88,7 @@ interface Props {
78
88
  file_name?: string | null;
79
89
  file_size?: number | null;
80
90
  display_order?: number;
81
- }>) => Promise<any>;
91
+ }>, suggestions?: ClarificationSuggestion[]) => Promise<any>;
82
92
  onRestoreCheckpointBackend?: (conversationId: string, checkpointMessageId: string) => Promise<any>;
83
93
  onTakeScreenshot?: () => Promise<string | null>;
84
94
  /** Fires whenever the active conversation ID changes (including initial null → uuid). */
@@ -125,6 +135,12 @@ interface Props {
125
135
  * still appears when assistant commit bubbles were never persisted.
126
136
  */
127
137
  widgetHeadCommitSha?: string | null;
138
+ /**
139
+ * Short commit sha → human version label ("Version 4"). The host owns the
140
+ * mapping (it knows the widget's versions); the chat only renders it, so a
141
+ * turn reads as the version it produced instead of a commit hash.
142
+ */
143
+ versionLabelByCommitSha?: Record<string, string>;
128
144
  /** Host is running widget codegen — send button becomes stop. */
129
145
  isGenerating?: boolean;
130
146
  onStopGeneration?: () => void;
@@ -1,5 +1,6 @@
1
1
  <script lang="ts">
2
2
  import type { ChatMessage, ChatContext } from '../types/index.js';
3
+ import type { ClarificationSuggestion } from '../types/message.js';
3
4
  import { MESSAGE_COLORS } from '../constants/colors.js';
4
5
  import { chatLog } from '../utils/logger.js';
5
6
  import { AttachmentDisplay, SuggestionButtons } from './index.js';
@@ -32,13 +33,23 @@
32
33
  showGenerationSummaries?: boolean;
33
34
  /** Host widget HEAD sha — Head chrome when assistant commit bubbles are missing. */
34
35
  widgetHeadCommitSha?: string | null;
35
- /** When false, hide commit hashes next to Head-at-commit (user mode). */
36
+ /**
37
+ * Short commit sha → human version label ("Version 4"), supplied by the host.
38
+ * A commit hash means nothing to someone who is not a developer, so the turn
39
+ * is labelled with the version it produced and the hash is debug-only.
40
+ */
41
+ versionLabelByCommitSha?: Record<string, string>;
42
+ /** When false, hide commit hashes next to the version label (user mode). */
36
43
  showCommitMeta?: boolean;
37
44
  /** True while codegen / send is in flight — suppresses premature Retry. */
38
45
  isGenerating?: boolean;
39
46
  onSuggestionSelected?: (suggestion: string) => void;
40
47
  onRestoreCheckpoint?: (messageId: string, messageIndex: number) => void;
41
48
  onRetryMessage?: (content: string) => void;
49
+ /** Tapping a clarification-card suggestion chip sends it as the next user message,
50
+ * carrying the chip's structured intent. Chips are disabled while the host
51
+ * runs widget codegen (`isGenerating`). */
52
+ onClarificationSuggestionSelected?: (suggestion: ClarificationSuggestion) => void;
42
53
  }
43
54
 
44
55
  let {
@@ -51,11 +62,13 @@
51
62
  enableAutoCodeDetection = false,
52
63
  showGenerationSummaries = false,
53
64
  widgetHeadCommitSha = null,
65
+ versionLabelByCommitSha = {},
54
66
  showCommitMeta = true,
55
67
  isGenerating = false,
56
68
  onSuggestionSelected,
57
69
  onRestoreCheckpoint,
58
70
  onRetryMessage,
71
+ onClarificationSuggestionSelected,
59
72
  }: Props = $props();
60
73
 
61
74
  let messagesHasScrollbar = $state(false);
@@ -242,6 +255,28 @@
242
255
  return head.startsWith(sha) || sha.startsWith(head.slice(0, 7));
243
256
  }
244
257
 
258
+ /** True when some reply carries the host's current HEAD commit. */
259
+ function conversationMatchesHeadSha(): boolean {
260
+ if (!widgetHeadCommitSha) return false;
261
+ return chatTurns.some((turn) =>
262
+ turn.replies.some(
263
+ (r) =>
264
+ messageHasCommit(r)
265
+ && !isCodegenFailure(r)
266
+ && commitShaMatchesHead(r.messageContent || ''),
267
+ ),
268
+ );
269
+ }
270
+
271
+ /**
272
+ * Head resolution. When the host tells us its HEAD commit, that is the
273
+ * authority: the reply mentioning it is Head. But HEAD routinely moves to a
274
+ * commit no persisted reply mentions — a generation whose summary has not been
275
+ * reloaded yet, or a turn whose status bubble records an earlier commit — and
276
+ * matching on the sha alone then left every turn without Head chrome. In that
277
+ * case `getFallbackHeadReply` puts it on the latest turn instead, so the local
278
+ * `isWidgetHead` flag is only consulted when the host names no HEAD at all.
279
+ */
245
280
  function isHeadCommitReply(reply: ChatMessage): boolean {
246
281
  if (!messageHasCommit(reply) || isCodegenFailure(reply)) return false;
247
282
  if (widgetHeadCommitSha) return commitShaMatchesHead(reply.messageContent || '');
@@ -249,7 +284,10 @@
249
284
  }
250
285
 
251
286
  function turnHasWidgetHead(turn: ChatTurn): boolean {
252
- return turn.replies.some((r) => isHeadCommitReply(r));
287
+ if (turn.replies.some((r) => isHeadCommitReply(r))) return true;
288
+ // A synthesized Head reply is not in `replies`, so the turn highlight has to
289
+ // ask for it explicitly or the badge appears without its turn chrome.
290
+ return !!getFallbackHeadReply(turn);
253
291
  }
254
292
 
255
293
  function isCodegenFailure(message: ChatMessage): boolean {
@@ -284,8 +322,25 @@
284
322
  return match?.[1]?.slice(0, 8) ?? null;
285
323
  }
286
324
 
325
+ /**
326
+ * The reply this turn's commit chrome describes. The Head fallback wins over
327
+ * the turn's own commit reply: when it exists, HEAD is on a commit that reply
328
+ * does not name, so showing the reply would label the turn with a stale sha
329
+ * and drop the Head badge from the conversation entirely.
330
+ */
331
+ function getTurnHeadOrCommitReply(turn: ChatTurn): ChatMessage | null {
332
+ return getFallbackHeadReply(turn) || getTurnCommitReply(turn);
333
+ }
334
+
335
+ /** The version this turn produced, when the host knows it. */
336
+ function getTurnVersionLabel(turn: ChatTurn): string | null {
337
+ const short = getTurnCommitShort(turn);
338
+ if (!short) return null;
339
+ return versionLabelByCommitSha[short.slice(0, 7).toLowerCase()] ?? null;
340
+ }
341
+
287
342
  function getTurnCommitShort(turn: ChatTurn): string | null {
288
- const commitReply = getTurnCommitReply(turn) || getFallbackHeadReply(turn);
343
+ const commitReply = getTurnHeadOrCommitReply(turn);
289
344
  const fromReply = extractCommitShort(commitReply?.messageContent || '');
290
345
  if (fromReply) return fromReply;
291
346
  for (const reply of turn.replies) {
@@ -314,12 +369,16 @@
314
369
  return false;
315
370
  }
316
371
 
317
- /** When DB history has only user prompts, still show Head on the latest turn. */
372
+ /**
373
+ * Head chrome for the latest turn when no persisted reply carries HEAD: the
374
+ * history holds only user prompts, the generation summary has not been
375
+ * reloaded yet, or the turn's own status bubble records an earlier commit
376
+ * than the one the widget now sits on.
377
+ */
318
378
  function getFallbackHeadReply(turn: ChatTurn): ChatMessage | null {
319
379
  if (!widgetHeadCommitSha || !turn.user) return null;
320
- if (getTurnCommitReply(turn)) return null;
321
380
  if (!isLastUserTurn(turn)) return null;
322
- if (conversationHasCommitReply()) return null;
381
+ if (conversationMatchesHeadSha()) return null;
323
382
  const sha = widgetHeadCommitSha.slice(0, 8);
324
383
  return {
325
384
  ...turn.user,
@@ -362,7 +421,7 @@
362
421
  * Previously this was gated to Debug OFF (assistant reply hidden), but we want the buttons
363
422
  * available in Debug ON too — the assistant summary and the user-side chrome coexist. */
364
423
  function showCommitMetaOnUserTurn(turn: ChatTurn): boolean {
365
- return !!getTurnCommitReply(turn) || !!getFallbackHeadReply(turn) || canRestoreLegacyUserTurn(turn);
424
+ return !!getTurnHeadOrCommitReply(turn) || canRestoreLegacyUserTurn(turn);
366
425
  }
367
426
 
368
427
  type ChatTurn = {
@@ -422,6 +481,12 @@
422
481
  let messagesContainer: HTMLElement;
423
482
  let showSuggestionsInline = $state(false);
424
483
  let autoScroll = $state(true);
484
+
485
+ // Collapse an expanded suggestions panel as soon as a generation starts, so it
486
+ // does not reappear under the new turn when generation ends.
487
+ $effect(() => {
488
+ if (isGenerating && showSuggestionsInline) showSuggestionsInline = false;
489
+ });
425
490
  /**
426
491
  * Opening on a small screen often resizes the container (parent panel layout)
427
492
  * AFTER mount, which resets scroll to the top and clips the input below the
@@ -799,8 +864,10 @@
799
864
  onscroll={handleScroll}
800
865
  >
801
866
  <!-- Empty state with suggestions — hidden until initialization completes so
802
- suggestions never flash before the loaded messages arrive. -->
803
- {#if isInitialized && messages.length === 0 && !isLoading}
867
+ suggestions never flash before the loaded messages arrive, and hidden
868
+ while a generation is in flight (the optimistic user bubble lands a tick
869
+ after send, so the list is briefly empty again). -->
870
+ {#if isInitialized && messages.length === 0 && !isLoading && !isGenerating}
804
871
  <div class="empty-state-ct flex flex-col items-center justify-center text-center max-w-sm w-full" style="align-self: center;">
805
872
  <h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2">💬 Start a conversation</h3>
806
873
  <p class="text-gray-600 dark:text-gray-400 text-sm mb-6">
@@ -823,7 +890,7 @@
823
890
  >
824
891
  {#if turn.user}
825
892
  {@const userMsg = turn.user}
826
- {@const commitReply = getTurnCommitReply(turn) || getFallbackHeadReply(turn)}
893
+ {@const commitReply = getTurnHeadOrCommitReply(turn)}
827
894
  <div class="message-container wc-chat-turn-user ml-auto w-fit max-w-[80%] flex flex-col items-stretch"
828
895
  class:opacity-75={userMsg._optimistic}
829
896
  class:opacity-50={userMsg._failed}
@@ -893,16 +960,21 @@
893
960
  <div class="wc-user-commit-meta-ct flex w-full items-center justify-between gap-2 mt-1">
894
961
  <div class="wc-user-commit-meta-left flex items-center gap-2 min-w-0">
895
962
  {#if commitReply && isHeadCommitReply(commitReply)}
896
- <div class="checkpoint-label wc-head-commit-label">
963
+ <div class="checkpoint-label wc-head-commit-label" title="This is the version you are looking at">
897
964
  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
898
965
  <path d="M20 6L9 17l-5-5"/>
899
966
  </svg>
900
- Head at commit
967
+ You are here
901
968
  </div>
902
969
  {/if}
970
+ {#if getTurnVersionLabel(turn)}
971
+ <span class="wc-user-version-label text-xs text-gray-500">
972
+ {getTurnVersionLabel(turn)}
973
+ </span>
974
+ {/if}
903
975
  {#if showCommitMeta && getTurnCommitShort(turn)}
904
976
  <span class="wc-user-commit-sha font-mono text-xs text-gray-500">
905
- Commit {getTurnCommitShort(turn)}
977
+ (commit id: {getTurnCommitShort(turn)})
906
978
  </span>
907
979
  {/if}
908
980
  </div>
@@ -960,6 +1032,22 @@
960
1032
  {/if}
961
1033
  </div>
962
1034
 
1035
+ {#if reply.suggestions && reply.suggestions.length > 0}
1036
+ <div class="clarification-suggestions flex flex-wrap gap-1.5 mt-1.5">
1037
+ {#each reply.suggestions as suggestion, i (i)}
1038
+ <button
1039
+ type="button"
1040
+ class="clarification-chip"
1041
+ disabled={!onClarificationSuggestionSelected || isLoading || isGenerating}
1042
+ onclick={() => onClarificationSuggestionSelected?.(suggestion)}
1043
+ title={suggestion.label}
1044
+ >
1045
+ {suggestion.label}
1046
+ </button>
1047
+ {/each}
1048
+ </div>
1049
+ {/if}
1050
+
963
1051
  {#if isCodegenFailure(reply) && isLastCodegenFailureInTurn(turn, reply) && getRetryPromptForTurn(turn, turnIndex) && !isLoading}
964
1052
  <div class="retry-codegen-row flex justify-start mt-1">
965
1053
  <button
@@ -982,7 +1070,7 @@
982
1070
  {/each}
983
1071
 
984
1072
  <!-- Show suggestions toggle (when there are messages) -->
985
- {#if messages.length > 0 && !isLoading}
1073
+ {#if messages.length > 0 && !isLoading && !isGenerating}
986
1074
  <div class="suggestions-toggle-ct flex justify-center py-2">
987
1075
  {#if showSuggestionsInline}
988
1076
  <SuggestionButtons
@@ -1146,35 +1234,42 @@
1146
1234
  border-color: #fca5a5;
1147
1235
  }
1148
1236
 
1149
- .restore-checkpoint-btn svg,
1150
- .retry-codegen-btn svg {
1151
- flex-shrink: 0;
1152
- }
1153
-
1154
- /* Copy message button — top-right, visible on hover */
1155
- .copy-msg-btn {
1156
- position: absolute;
1157
- top: 4px;
1158
- right: 4px;
1159
- display: flex;
1237
+ /* Clarification-card suggestion chips — tap to send as the next user message */
1238
+ .clarification-chip {
1239
+ display: inline-flex;
1160
1240
  align-items: center;
1161
- justify-content: center;
1162
- width: 22px;
1163
- height: 22px;
1164
- border-radius: 4px;
1165
- border: none;
1166
- background: rgba(0, 0, 0, 0.06);
1167
- color: #888;
1241
+ max-width: 100%;
1242
+ padding: 4px 12px;
1243
+ background: #fff;
1244
+ color: #2563eb;
1245
+ border: 1px solid #bfdbfe;
1246
+ border-radius: 999px;
1247
+ font-size: 12px;
1248
+ font-weight: 500;
1168
1249
  cursor: pointer;
1169
- opacity: 0;
1170
- transition: opacity 0.15s ease;
1250
+ text-align: left;
1251
+ overflow-wrap: anywhere;
1252
+ white-space: normal;
1253
+ transition: background-color 0.15s ease, border-color 0.15s ease, color 0.15s ease;
1171
1254
  }
1172
- .message-bubble:hover .copy-msg-btn {
1173
- opacity: 1;
1255
+
1256
+ .clarification-chip:hover:not(:disabled) {
1257
+ background: #eff6ff;
1258
+ border-color: #93c5fd;
1174
1259
  }
1175
- .copy-msg-btn:hover {
1176
- background: rgba(0, 0, 0, 0.12);
1177
- color: #555;
1260
+
1261
+ .clarification-chip:active:not(:disabled) {
1262
+ background: #dbeafe;
1263
+ }
1264
+
1265
+ .clarification-chip:disabled {
1266
+ opacity: 0.5;
1267
+ cursor: default;
1268
+ }
1269
+
1270
+ .restore-checkpoint-btn svg,
1271
+ .retry-codegen-btn svg {
1272
+ flex-shrink: 0;
1178
1273
  }
1179
1274
 
1180
1275
  /* Checkpoint label — shown above the restored message */
@@ -1,4 +1,5 @@
1
1
  import type { ChatMessage, ChatContext } from '../types/index.js';
2
+ import type { ClarificationSuggestion } from '../types/message.js';
2
3
  interface Props {
3
4
  class?: string;
4
5
  messages: ChatMessage[];
@@ -23,13 +24,23 @@ interface Props {
23
24
  showGenerationSummaries?: boolean;
24
25
  /** Host widget HEAD sha — Head chrome when assistant commit bubbles are missing. */
25
26
  widgetHeadCommitSha?: string | null;
26
- /** When false, hide commit hashes next to Head-at-commit (user mode). */
27
+ /**
28
+ * Short commit sha → human version label ("Version 4"), supplied by the host.
29
+ * A commit hash means nothing to someone who is not a developer, so the turn
30
+ * is labelled with the version it produced and the hash is debug-only.
31
+ */
32
+ versionLabelByCommitSha?: Record<string, string>;
33
+ /** When false, hide commit hashes next to the version label (user mode). */
27
34
  showCommitMeta?: boolean;
28
35
  /** True while codegen / send is in flight — suppresses premature Retry. */
29
36
  isGenerating?: boolean;
30
37
  onSuggestionSelected?: (suggestion: string) => void;
31
38
  onRestoreCheckpoint?: (messageId: string, messageIndex: number) => void;
32
39
  onRetryMessage?: (content: string) => void;
40
+ /** Tapping a clarification-card suggestion chip sends it as the next user message,
41
+ * carrying the chip's structured intent. Chips are disabled while the host
42
+ * runs widget codegen (`isGenerating`). */
43
+ onClarificationSuggestionSelected?: (suggestion: ClarificationSuggestion) => void;
33
44
  }
34
45
  declare const ChatMessages: import("svelte").Component<Props, {}, "">;
35
46
  type ChatMessages = ReturnType<typeof ChatMessages>;
@@ -34,6 +34,19 @@ export interface ChatMessage {
34
34
  rolledBackAt?: string | null;
35
35
  /** Latest successful repo commit — show "Head at commit" on this assistant message. */
36
36
  isWidgetHead?: boolean;
37
+ /** Clarification-card follow-up chips (assistant only), as structured
38
+ * objects: `label` is display copy rendered verbatim, `intent` is the
39
+ * machine-readable behavior the chip's tap declares back on the next
40
+ * generate request (`chipIntent`). Bare-string rows from before the
41
+ * contract are normalized to refine suggestions by the server on read. */
42
+ suggestions?: ClarificationSuggestion[];
43
+ }
44
+ /** One suggestion chip on a clarification card — display copy plus the
45
+ * machine-readable behavior of tapping it. The client keys off `intent`;
46
+ * `label` is never parsed. */
47
+ export interface ClarificationSuggestion {
48
+ label: string;
49
+ intent: 'refine' | 'generate_anyway';
37
50
  }
38
51
  /**
39
52
  * Message input type for creating new messages
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/chat",
3
- "version": "0.1.11",
3
+ "version": "0.1.13",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -37,12 +37,16 @@
37
37
  "scripts": {
38
38
  "i": "npm run clean-modules && npm i && npm run lps",
39
39
  "clean-modules": "rm -rf node_modules",
40
- "lps": "volta run npm link --save @widgetic/api-sdk && volta run npm link --save @widgetic/design-system",
40
+ "lps": "node scripts/link-siblings.mjs",
41
+ "llinks": "ls -la node_modules/@widgetic",
42
+ "lps:check": "node scripts/link-siblings.mjs && npm run llinks",
43
+ "predev": "npm run lps",
41
44
  "dev": "npm run dev-sv -- --open",
42
45
  "dev-sv": "NODE_ENV=development vite dev",
43
46
  "build": "vite build",
44
47
  "package": "svelte-package",
45
48
  "package:watch": "svelte-package --watch",
49
+ "prepackage:watch": "npm run lps",
46
50
  "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --diagnostic-sources \"js,svelte\"",
47
51
  "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
48
52
  "lint": "prettier --check . && eslint .",
@@ -64,10 +68,10 @@
64
68
  "@sveltejs/package": "^2.3.7",
65
69
  "@sveltejs/vite-plugin-svelte": "^5.0.3",
66
70
  "@tailwindcss/postcss": "^4.1.4",
67
- "@types/eslint": "^9.6.0",
68
71
  "@types/node": "^26.4.1",
69
72
  "@widgetic/api-sdk": "^1.0.10",
70
- "@widgetic/design-system": "^0.3.89",
73
+ "@widgetic/design-system": "^0.5.12",
74
+ "@widgetic/dev-tools": "^0.2.0",
71
75
  "autoprefixer": "^10.4.20",
72
76
  "eslint": "^9.0.0",
73
77
  "eslint-config-prettier": "^9.1.0",