@widgetic/chat 0.1.42 → 0.1.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +461 -6
  2. package/dist/components/Chat.svelte +1078 -87
  3. package/dist/components/Chat.svelte.d.ts +102 -2
  4. package/dist/components/ChatComposer.svelte +382 -9
  5. package/dist/components/ChatComposer.svelte.d.ts +66 -3
  6. package/dist/components/ChatMessageQueue.svelte +56 -0
  7. package/dist/components/ChatMessageQueue.svelte.d.ts +20 -0
  8. package/dist/components/ChatMessages.svelte +485 -50
  9. package/dist/components/ChatMessages.svelte.d.ts +45 -2
  10. package/dist/components/ComposerAttachmentsTray.svelte +42 -10
  11. package/dist/components/ComposerAttachmentsTray.svelte.d.ts +5 -0
  12. package/dist/components/ComposerMentionChips.svelte +53 -0
  13. package/dist/components/ComposerMentionChips.svelte.d.ts +15 -0
  14. package/dist/components/FollowUpCard.svelte +134 -0
  15. package/dist/components/FollowUpCard.svelte.d.ts +17 -0
  16. package/dist/components/MentionChip.svelte +41 -0
  17. package/dist/components/MentionChip.svelte.d.ts +12 -0
  18. package/dist/components/MentionMenu.svelte +114 -0
  19. package/dist/components/MentionMenu.svelte.d.ts +19 -0
  20. package/dist/components/agent/AgentAvatar.svelte +6 -4
  21. package/dist/components/agent/AgentAvatar.svelte.d.ts +1 -1
  22. package/dist/components/agent/CodeCard.svelte +122 -27
  23. package/dist/components/agent/CodeCard.svelte.d.ts +3 -0
  24. package/dist/components/agent/CodeDiff.svelte +180 -0
  25. package/dist/components/agent/CodeDiff.svelte.d.ts +10 -0
  26. package/dist/components/agent/GenerationModule.svelte +13 -2
  27. package/dist/components/agent/GenerationModule.svelte.d.ts +3 -0
  28. package/dist/components/index.d.ts +4 -0
  29. package/dist/components/index.js +9 -0
  30. package/dist/errors/logTechnicalUserError.d.ts +1 -0
  31. package/dist/errors/logTechnicalUserError.js +37 -0
  32. package/dist/i18n/messages.d.ts +106 -1
  33. package/dist/i18n/messages.js +112 -1
  34. package/dist/i18n/sketchLocales.js +8 -8
  35. package/dist/messageQueue.d.ts +83 -0
  36. package/dist/messageQueue.js +84 -0
  37. package/dist/services/index.d.ts +1 -1
  38. package/dist/services/sketchAssistantClient.d.ts +27 -0
  39. package/dist/services/sketchAssistantClient.js +7 -2
  40. package/dist/services/sketchAssistantErrors.d.ts +4 -0
  41. package/dist/services/sketchAssistantErrors.js +22 -0
  42. package/dist/services/sketchAssistantOrchestrator.d.ts +7 -7
  43. package/dist/services/sketchAssistantOrchestrator.js +11 -24
  44. package/dist/services/sketchAssistantReply.js +3 -1
  45. package/dist/stores/chatStore.d.ts +5 -0
  46. package/dist/stores/chatStore.js +21 -0
  47. package/dist/types/agent.d.ts +4 -3
  48. package/dist/types/attachment.d.ts +16 -0
  49. package/dist/types/config.d.ts +6 -0
  50. package/dist/types/index.d.ts +1 -0
  51. package/dist/types/index.js +2 -0
  52. package/dist/types/mention.d.ts +40 -0
  53. package/dist/types/mention.js +8 -0
  54. package/dist/types/message.d.ts +60 -1
  55. package/dist/utils/agentTurn.d.ts +40 -9
  56. package/dist/utils/agentTurn.js +43 -11
  57. package/dist/utils/attachmentProgress.d.ts +12 -0
  58. package/dist/utils/attachmentProgress.js +18 -0
  59. package/dist/utils/bubbleRichFit.d.ts +68 -0
  60. package/dist/utils/bubbleRichFit.js +45 -0
  61. package/dist/utils/bubbleShrinkWrap.d.ts +8 -1
  62. package/dist/utils/bubbleShrinkWrap.js +113 -17
  63. package/dist/utils/codeChanges.d.ts +103 -0
  64. package/dist/utils/codeChanges.js +226 -0
  65. package/dist/utils/codeHighlight.js +1 -0
  66. package/dist/utils/codeStreamFormat.d.ts +5 -2
  67. package/dist/utils/composerMentions.d.ts +96 -0
  68. package/dist/utils/composerMentions.js +217 -0
  69. package/dist/utils/followUps.d.ts +74 -0
  70. package/dist/utils/followUps.js +116 -0
  71. package/dist/utils/generationArchiveStore.d.ts +6 -0
  72. package/dist/utils/generationArchiveStore.js +11 -3
  73. package/dist/utils/index.d.ts +12 -0
  74. package/dist/utils/index.js +20 -0
  75. package/dist/utils/orderedLine.d.ts +29 -0
  76. package/dist/utils/orderedLine.js +17 -0
  77. package/dist/utils/pastedContent.d.ts +99 -0
  78. package/dist/utils/pastedContent.js +258 -0
  79. package/dist/utils/questionCards.d.ts +131 -0
  80. package/dist/utils/questionCards.js +287 -0
  81. package/dist/utils/referenceItems.d.ts +36 -0
  82. package/dist/utils/referenceItems.js +56 -0
  83. package/dist/utils/sentReferenceBadges.d.ts +26 -0
  84. package/dist/utils/sentReferenceBadges.js +32 -0
  85. package/package.json +1 -1
@@ -1,15 +1,54 @@
1
1
  <script lang="ts">
2
2
  import type { ChatMessage, ChatContext } from '../types/index.js';
3
- import type { ClarificationSuggestion, DesignControlRequest, VersionRating } from '../types/message.js';
3
+ import type {
4
+ ClarificationSuggestion,
5
+ ContentItemOutput,
6
+ DesignControlRequest,
7
+ QuestionCardAnswer,
8
+ QuestionCardModel,
9
+ VersionRating
10
+ } from '../types/message.js';
4
11
  import type { AgentAvatarRenderer, AgentAvatarState, AgentSoundPlayer, ChatMember } from '../types/agent.js';
5
12
  import { chatLog, chatWarn } from '../utils/logger.js';
13
+ import type { CodeChanges } from '../utils/codeChanges.js';
6
14
  import { shrinkWrapBubble } from '../utils/bubbleShrinkWrap.js';
15
+ import { sentAttachmentsOf, sentBadgePictureOf, sentBadgeTitleOf } from '../utils/sentReferenceBadges.js';
16
+ // The file badge of a sent message: the words that name a file, and the pill drawn for each (the design system's kit for `#` references)
17
+ import {
18
+ SENT_BADGE_CLASSES,
19
+ SENT_BADGE_LABEL_CLASSES,
20
+ SENT_BADGE_THUMBNAIL_CLASSES,
21
+ hasSentBadges,
22
+ segmentSentText,
23
+ type SentSegment
24
+ } from '@widgetic/design-system/prompt-references';
7
25
  import { splitTextIntoLinks } from '../utils/linkifyText.js';
8
26
  import { isRatableVersionReply, type VersionThumb } from '../utils/versionRatings.js';
9
27
  import { isLocalMessageId, restoreBeforeTarget, textToCopy, type TurnRestorePoint } from '../utils/messageActions.js';
28
+ import {
29
+ findFollowUpCard,
30
+ followUpDismissKey,
31
+ isFollowUpSuggestion,
32
+ openQuestionOptionsOf,
33
+ withQuestionSkipped,
34
+ withoutDismissedPills,
35
+ type FollowUpPill
36
+ } from '../utils/followUps.js';
37
+ import {
38
+ answersFromPicks,
39
+ areAllAnswersSkipped,
40
+ chipQuestionOutcomeOf,
41
+ isSkippedAnswer,
42
+ questionCardOf,
43
+ questionCardStateOf,
44
+ skippedAnswersOf,
45
+ type ChipQuestionOutcome,
46
+ type QuestionCardState
47
+ } from '../utils/questionCards.js';
10
48
  import { AttachmentDisplay, SuggestionButtons } from './index.js';
11
49
  import PanelSuggestionButtons from './PanelSuggestionButtons.svelte';
12
50
  import PanelFollowUpSuggestions from './PanelFollowUpSuggestions.svelte';
51
+ import FollowUpCard from './FollowUpCard.svelte';
13
52
  import CodeBlock from './CodeBlock.svelte';
14
53
  import MessageActions from './MessageActions.svelte';
15
54
  import AgentTurn from './agent/AgentTurn.svelte';
@@ -23,7 +62,6 @@
23
62
  import { dirForUserText, useTextDirection } from '@widgetic/design-system/components/textDirection';
24
63
  import IconSparkles from '@tabler/icons-svelte/icons/sparkles';
25
64
  import IconPlayerStop from '@tabler/icons-svelte/icons/player-stop';
26
- import IconAlertTriangle from '@tabler/icons-svelte/icons/alert-triangle';
27
65
  import IconRefresh from '@tabler/icons-svelte/icons/refresh';
28
66
  import {
29
67
  generationActivityAriaKey,
@@ -47,6 +85,7 @@
47
85
  settledAgentLook,
48
86
  soundStateOf,
49
87
  turnOutcome,
88
+ withChangesOfTheRun,
50
89
  type AgentAvatarSize,
51
90
  type AgentLook,
52
91
  type FinishedGeneration,
@@ -64,6 +103,7 @@
64
103
  MessageCheckpointRow,
65
104
  PlanCard,
66
105
  QuestionCard,
106
+ QuestionCardSummary,
67
107
  ScrollToBottom
68
108
  } from '@widgetic/design-system/components/chat/index';
69
109
 
@@ -125,9 +165,28 @@
125
165
  generationStream?: string;
126
166
  /** Rolling tail of streamed model reasoning during codegen. */
127
167
  generationThinking?: string;
128
- /** Gateway build plan while codegen runs; `null` hides the card. */
168
+ /** Gateway build plan while codegen runs; `null` hides the card (unless `generationPlanPending` shows it closed). */
129
169
  generationPlan?: GenerationPlanWire | null;
170
+ /**
171
+ * The host asked for a plan and it has not arrived: the plan card shows closed, saying "Planning" in a shimmer, and opens when the
172
+ * plan comes. It ends by itself once code streams (the plan comes before the build). Default false: no card until the plan arrives.
173
+ */
174
+ generationPlanPending?: boolean;
175
+ /**
176
+ * What the last run changed in the widget's files, from the host (the gateway works it out: see `readCodeChangesFromMetadata`).
177
+ * The chat keeps it with the work of that run and draws it as the "Changes" view of the code card under the conclusion.
178
+ * Give it when the operation completes (before or after `isGenerating` turns false: a value that comes after goes into the work
179
+ * of the run that just ended), and clear it when the next run starts; the chat also ignores the very value it held when a run
180
+ * began, so a host that forgets to clear it never shows a run the changes of the run before.
181
+ */
182
+ generationChanges?: CodeChanges | null;
130
183
  onSuggestionSelected?: (suggestion: string) => void;
184
+ /**
185
+ * What is in the message box now. The follow-up card under the last reply (ideas for what to improve next, as small pills)
186
+ * shows a pill checked for as long as its request is in the box, and does not let the same request be added twice. Without
187
+ * it no pill is ever checked. Default: nothing.
188
+ */
189
+ draftText?: string;
131
190
  /**
132
191
  * Draws a restore icon on the messages the person sent, shown when the pointer is over the message. Pressing it asks the host to
133
192
  * put the widget back to how it was BEFORE that message: called with the id of the saved reply that stands for that earlier state
@@ -152,6 +211,19 @@
152
211
  * carrying the chip's structured intent. Chips are disabled while the host
153
212
  * runs widget codegen (`isGenerating`). */
154
213
  onClarificationSuggestionSelected?: (suggestion: ClarificationSuggestion) => void;
214
+ /**
215
+ * The person pressed Skip on a question card (the id of the reply that asked it). The card has already gone and nothing was
216
+ * sent: the question stays in the conversation as a plain message. `Chat` uses this to put the cursor back in the message box.
217
+ */
218
+ onQuestionSkipped?: (replyId: string) => void;
219
+ /**
220
+ * The person answered the card of questions of a reply (`ChatMessage.questionCard`) in the card itself: Submit on the last
221
+ * question, or Skip. `answers` is one answer for each question in the card's order (an empty answer is a question that was
222
+ * skipped: Next with nothing picked, or Skip), and `skippedAll` is true when none of them has a pick. `Chat` keeps the answers
223
+ * on the message, so the card is drawn closed, and tells its host. A card that is left by writing in the chat does not come
224
+ * through here: that message is sent with the skipped questions (`Chat` does it).
225
+ */
226
+ onQuestionCardAnswered?: (detail: { messageId: string; answers: QuestionCardAnswer[]; skippedAll: boolean }) => void;
155
227
  /** Host-rendered inline design-control card for messages carrying `designControls`. */
156
228
  renderDesignControls?: Snippet<[DesignControlRequest]>;
157
229
  /** Host translation for lines saved in English (see Chat `storedLineLabel`). */
@@ -179,6 +251,12 @@
179
251
  * does not wrap, and a message with code blocks, keep the width CSS gives them. On by default; pass `false` for CSS's widths.
180
252
  */
181
253
  tightBubbles?: boolean;
254
+ /**
255
+ * Draws a file badge (the picture and `#name`, without an X) for each word of a sent message that names a file attached to it,
256
+ * as the message box drew it while the message was written. The words are matched with the names of the message's pictures, and
257
+ * a word that cannot be matched for sure stays plain text. On by default; pass `false` for the text as it was sent.
258
+ */
259
+ referenceBadges?: boolean;
182
260
  /** Active conversation id — persists generation archive in IndexedDB across reload. */
183
261
  conversationId?: string | null;
184
262
  }
@@ -202,13 +280,18 @@
202
280
  generationStream = '',
203
281
  generationThinking = '',
204
282
  generationPlan = null,
283
+ generationPlanPending = false,
284
+ generationChanges = null,
205
285
  onSuggestionSelected,
286
+ draftText = '',
206
287
  onRestoreCheckpoint,
207
288
  onRateVersion,
208
289
  versionRatings = {},
209
290
  onRetryMessage,
210
291
  onUpgradePlans,
211
292
  onClarificationSuggestionSelected,
293
+ onQuestionSkipped,
294
+ onQuestionCardAnswered,
212
295
  renderDesignControls,
213
296
  storedLineLabel,
214
297
  hasOlderMessages = false,
@@ -219,9 +302,32 @@
219
302
  renderAgentAvatar,
220
303
  agentSound,
221
304
  tightBubbles = true,
305
+ referenceBadges = true,
222
306
  conversationId = null,
223
307
  }: Props = $props();
224
308
 
309
+ /**
310
+ * The text of a sent message cut into plain runs and file badges, or `null` when it has no badge to draw (the usual message). The
311
+ * attachments are the ones the bubble shows; the design system works out which word names which of them.
312
+ */
313
+ // Said once, however many messages fail the same way
314
+ let warnedAboutBadges = false;
315
+
316
+ function sentSegmentsOf(text: string | null | undefined, attachments: readonly ContentItemOutput[]): SentSegment[] | null {
317
+ if (!referenceBadges || !text || attachments.length === 0 || !text.includes('#')) return null;
318
+ try {
319
+ const segments = segmentSentText(text, sentAttachmentsOf(attachments));
320
+ return hasSentBadges(segments) ? segments : null;
321
+ } catch (error) {
322
+ // The message stays as the text that was sent
323
+ if (!warnedAboutBadges) {
324
+ warnedAboutBadges = true;
325
+ chatWarn('[Chat] The file badges of a sent message could not be worked out; its text is shown as it is.', error);
326
+ }
327
+ return null;
328
+ }
329
+ }
330
+
225
331
 
226
332
  /** The property-edit sentence used to be stored with markdown the bubble does not render. */
227
333
  function readablePropertyEditLine(content: string): string {
@@ -879,8 +985,11 @@
879
985
  const reply = turn.replies[ri];
880
986
  const meta = reply.metadata as { panelFollowUp?: boolean } | undefined;
881
987
  // The sketch "Undo drawing" chip is drawn under its own reply (it has no label of its own to show here); this
882
- // list is for the prompts a reply suggests.
883
- const followUpSuggestions = (reply.suggestions ?? []).filter((suggestion) => !suggestion?.undoSketch);
988
+ // list is for the prompts a reply suggests. A chip with a title is a follow-up pill, which is drawn as the follow-up
989
+ // card under the last reply: it is not one of these rows too.
990
+ const followUpSuggestions = (reply.suggestions ?? []).filter(
991
+ (suggestion) => !suggestion?.undoSketch && !isFollowUpSuggestion(suggestion)
992
+ );
884
993
  if (!followUpSuggestions.length || meta?.panelFollowUp === false) continue;
885
994
  if (!shouldShowAssistantReply(reply)) continue;
886
995
  // A suggestion without a text label would give the keyed list a NaN key and stop the whole panel from rendering.
@@ -894,6 +1003,126 @@
894
1003
  return null;
895
1004
  });
896
1005
 
1006
+ /**
1007
+ * The pills the person took out of the follow-up card, each remembered by its reply and its request (`followUpDismissKey`).
1008
+ * Local to this view on purpose: it is not saved, so a reload brings the ideas back, and the words a pill already put in the
1009
+ * message box stay there. A new message takes the whole card away, so these keys are only of use until then.
1010
+ */
1011
+ let dismissedFollowUpKeys = $state<string[]>([]);
1012
+
1013
+ /**
1014
+ * The follow-up card under the last reply (Figma: Chat cards, "Follow-ups"): ideas for what to improve next on the widget, from
1015
+ * the titled chips of the newest reply that has them. A message of the person takes it away, and a pill the person took out
1016
+ * stays out. It is not the starting suggestions and not a question: those have their own cards.
1017
+ */
1018
+ const followUpCard = $derived.by(() => {
1019
+ if (emptyStateVisible) return null;
1020
+ try {
1021
+ return withoutDismissedPills(findFollowUpCard(messages), dismissedFollowUpKeys);
1022
+ } catch (error) {
1023
+ chatWarn('[Chat] The follow-up card could not be worked out:', error);
1024
+ return null;
1025
+ }
1026
+ });
1027
+
1028
+ /**
1029
+ * A pill was clicked: the request goes into the message box (the parent merges it into the draft; nothing is sent).
1030
+ * It takes the plain path of the starting suggestions and the "Try next" rows, not the one of a question's options: a chip's
1031
+ * intent (`refine` is on every saved chip, a follow-up included) is what the gateway counts as an answer to a question card,
1032
+ * and a follow-up answers no question.
1033
+ */
1034
+ function handleFollowUpPick(pill: FollowUpPill) {
1035
+ chatLog('[Chat] A follow-up pill was picked:', { 'Title': pill.title, 'Request': pill.request });
1036
+ onSuggestionSelected?.(pill.request);
1037
+ }
1038
+
1039
+ /** The cross of a pill was pressed: the pill leaves the card (and the card goes with its last pill). */
1040
+ function handleFollowUpDismiss(pill: FollowUpPill) {
1041
+ const card = followUpCard;
1042
+ if (!card) return;
1043
+ chatLog('[Chat] A follow-up pill was taken out of the card:', { 'Title': pill.title });
1044
+ dismissedFollowUpKeys = [...dismissedFollowUpKeys, followUpDismissKey(card.replyId, pill)];
1045
+ }
1046
+
1047
+ /**
1048
+ * The replies whose question card the person set aside with Skip. Local to this view on purpose, like the pills taken out of
1049
+ * the follow-up card: it is not saved, and nothing is sent. The card goes, the words of the question stay as a plain message
1050
+ * of the assistant, and the turn stops waiting for an answer (see `replyFactsOf`).
1051
+ */
1052
+ let skippedQuestionReplyIds = $state<string[]>([]);
1053
+
1054
+ /** Skip was pressed on the question card of a reply: the card goes, and the host may put the cursor back in the message box. */
1055
+ function handleQuestionSkip(reply: ChatMessage) {
1056
+ try {
1057
+ chatLog('[Chat] A question was skipped:', { 'Reply': reply.id });
1058
+ skippedQuestionReplyIds = withQuestionSkipped(skippedQuestionReplyIds, reply.id);
1059
+ onQuestionSkipped?.(reply.id);
1060
+ } catch (error) {
1061
+ chatWarn('[Chat] A question could not be skipped:', error);
1062
+ }
1063
+ }
1064
+
1065
+ /**
1066
+ * The card of questions of every reply that carries one (`ChatMessage.questionCard`), by the id of the reply, with what it is now:
1067
+ * open (the newest message, nothing done with it), answered (with the picks), skipped (no pick: a Skip, a Next with nothing
1068
+ * picked, or a message the person wrote in the chat instead), or closed (answered, picks not known after a reload: it is drawn as
1069
+ * the plain words it was saved with). Worked out in one pass over the conversation, from the messages alone.
1070
+ */
1071
+ const questionCardViews = $derived.by(() => {
1072
+ const views = new Map<string, { card: QuestionCardModel; state: QuestionCardState }>();
1073
+ try {
1074
+ messages.forEach((message, index) => {
1075
+ const card = questionCardOf(message);
1076
+ const state = card ? questionCardStateOf(messages, index) : null;
1077
+ if (card && state) views.set(message.id, { card, state });
1078
+ });
1079
+ } catch (error) {
1080
+ chatWarn('[Chat] The cards of questions could not be worked out:', error);
1081
+ }
1082
+ return views;
1083
+ });
1084
+
1085
+ /** Whether the chat draws a card (or its summary) in place of the words of the reply: every state but a closed card with no picks. */
1086
+ function drawsQuestionCard(reply: ChatMessage): boolean {
1087
+ const view = questionCardViews.get(reply.id);
1088
+ return !!view && view.state.kind !== 'closed';
1089
+ }
1090
+
1091
+ /** What became of the older card of a reply (the chips of a question the intent gate asked) once the person wrote in the chat. */
1092
+ function chipQuestionOutcomeOfReply(reply: ChatMessage, options: ClarificationSuggestion[]): ChipQuestionOutcome {
1093
+ const replyIndex = messages.findIndex((message) => message.id === reply.id);
1094
+ if (replyIndex < 0) return { kind: 'open' };
1095
+ return chipQuestionOutcomeOf(messages, replyIndex, options.map((option) => option.label));
1096
+ }
1097
+
1098
+ /**
1099
+ * Submit was pressed on the last question of a reply's card: the picks of every question become the answers (a question with no
1100
+ * pick is skipped, and the assistant decides it itself). The card is closed by `Chat`, which keeps the answers on the message.
1101
+ */
1102
+ function handleQuestionCardSubmit(reply: ChatMessage, card: QuestionCardModel, pickedOptionIds: string[][]) {
1103
+ try {
1104
+ const answers = answersFromPicks(card, pickedOptionIds);
1105
+ chatLog('[Chat] A card of questions was answered:', {
1106
+ 'Reply': reply.id,
1107
+ 'Questions': answers.length,
1108
+ 'Skipped': answers.filter(isSkippedAnswer).length
1109
+ });
1110
+ onQuestionCardAnswered?.({ messageId: reply.id, answers, skippedAll: areAllAnswersSkipped(answers) });
1111
+ } catch (error) {
1112
+ chatWarn('[Chat] A card of questions could not be answered:', error);
1113
+ }
1114
+ }
1115
+
1116
+ /** Skip was pressed on a reply's card of questions: every question is left to the assistant, which goes on with what it decides. */
1117
+ function handleQuestionCardSkip(reply: ChatMessage, card: QuestionCardModel) {
1118
+ try {
1119
+ chatLog('[Chat] A card of questions was skipped:', { 'Reply': reply.id, 'Questions': card.questions.length });
1120
+ onQuestionCardAnswered?.({ messageId: reply.id, answers: skippedAnswersOf(card), skippedAll: true });
1121
+ } catch (error) {
1122
+ chatWarn('[Chat] A card of questions could not be skipped:', error);
1123
+ }
1124
+ }
1125
+
897
1126
  /** Show the commit chrome (title, version label, the restore icon) on the user prompt whenever the turn has a commit.
898
1127
  * Previously this was gated to Debug OFF (assistant reply hidden), but we want it
899
1128
  * available in Debug ON too — the assistant summary and the user-side chrome coexist. */
@@ -1005,8 +1234,12 @@
1005
1234
  return {
1006
1235
  isFailure: isCodegenFailure(reply),
1007
1236
  isStopped: isStoppedByUser(reply),
1008
- // In the panel the suggestions are the cards above the composer, not a card in the turn
1009
- hasQuestion: !panelLayout && (reply.suggestions?.length ?? 0) > 0,
1237
+ // In the panel the suggestions are the cards above the composer, not a card in the turn. The follow-up pills are not a
1238
+ // question (nothing is asked): they never make the turn wait for an answer. Nor does a question the person skipped. The card
1239
+ // of questions the assistant puts before it builds waits for an answer while it is open, in either layout.
1240
+ hasQuestion:
1241
+ questionCardViews.get(reply.id)?.state.kind === 'open' ||
1242
+ (!panelLayout && openQuestionOptionsOf(reply.suggestions, reply.id, skippedQuestionReplyIds).length > 0),
1010
1243
  hasCommit: messageHasCommit(reply) && !isCodegenFailure(reply),
1011
1244
  isCompletion: /^Code generation completed/i.test((reply.messageContent || '').trim()),
1012
1245
  };
@@ -1014,7 +1247,8 @@
1014
1247
 
1015
1248
  /**
1016
1249
  * The assistant of one turn: its avatar's look, and what it shows besides its replies. Only the newest turn moves, and only
1017
- * what just ended in front of the person (a run, a failure, a card to answer) is large: the rest is small and still.
1250
+ * what just ended in front of the person (a run, a card to answer) is large: the rest is small and still. A failure is small and
1251
+ * still too, in its red error look, which it holds until the prompt is sent again.
1018
1252
  */
1019
1253
  function assistantViewOf(turn: ChatTurn): TurnAssistantView {
1020
1254
  const visibleReplies = turn.replies.filter(shouldShowAssistantReply);
@@ -1153,6 +1387,30 @@
1153
1387
  progress: $t('chat.plan.progress', { current: '{current}', total: '{total}' }),
1154
1388
  showMoreTasks: $t('chat.plan.showMoreTasks', { count: '{count}' }),
1155
1389
  showFewerTasks: $t('chat.plan.showFewerTasks'),
1390
+ planning: $t('chat.plan.planning'),
1391
+ taskPending: $t('chat.plan.taskPending'),
1392
+ taskActive: $t('chat.plan.taskActive'),
1393
+ taskDone: $t('chat.plan.taskDone'),
1394
+ });
1395
+ // The words of the question card, in the chat's language. Like the plan card's progress, the card puts the step into
1396
+ // `{current}` and `{total}` itself, so they are handed over as they are.
1397
+ const questionCardMessages = $derived({
1398
+ title: $t('chat.question.title'),
1399
+ titleMany: $t('chat.question.titleMany'),
1400
+ step: $t('chat.question.step', { current: '{current}', total: '{total}' }),
1401
+ back: $t('chat.question.back'),
1402
+ forward: $t('chat.question.forward'),
1403
+ next: $t('chat.question.next'),
1404
+ submit: $t('chat.question.submit'),
1405
+ skip: $t('chat.question.skip'),
1406
+ multipleHint: $t('chat.question.multipleHint'),
1407
+ noOptionsHint: $t('chat.question.noOptionsHint'),
1408
+ });
1409
+ // The words of the card once it is closed: the same small title, and what stands for a question with no pick.
1410
+ const questionCardSummaryMessages = $derived({
1411
+ title: $t('chat.question.title'),
1412
+ titleMany: $t('chat.question.titleMany'),
1413
+ skipped: $t('chat.question.skipped'),
1156
1414
  });
1157
1415
 
1158
1416
  // The first paint is shorter than the loaded page. Scrolling then, or treating
@@ -1185,8 +1443,25 @@
1185
1443
  * The thinking and the code of the generation that just ended: the modules under its conclusion show them, closed, for the
1186
1444
  * person to open. For the newest turn only. The host saves neither, so this browser keeps them (see the archive below) and
1187
1445
  * they come back after a reload, found again by the words of the prompt they answered.
1446
+ *
1447
+ * It also holds what the run changed in the widget's files, when the host gave it (`generationChanges`). The value is replaced
1448
+ * as a whole and never edited, so it is raw state: no proxy is made of it, and what the archive writes into IndexedDB (which
1449
+ * cannot copy a proxy) is plain data.
1450
+ */
1451
+ let finishedGeneration = $state.raw<FinishedGeneration | null>(null);
1452
+
1453
+ /**
1454
+ * The changes the host held when the run that is working began. They belong to an earlier run: the changes of this one are a
1455
+ * different value. A plain variable, not state: a run starting is no reason to draw the list again.
1188
1456
  */
1189
- let finishedGeneration = $state<FinishedGeneration | null>(null);
1457
+ let changesHeldAtRunStart: CodeChanges | null = null;
1458
+
1459
+ /** The changes of the run that just ended: what the host gave since the run began, or nothing (never the earlier run's). */
1460
+ function changesOfTheRunThatEnded(): CodeChanges | null {
1461
+ const changesGiven = generationChanges;
1462
+ if (changesGiven === null || changesGiven === changesHeldAtRunStart) return null;
1463
+ return changesGiven;
1464
+ }
1190
1465
 
1191
1466
  /**
1192
1467
  * The id of the message of the person that the kept work answered. A user message after it means a new turn, even if its words
@@ -1199,11 +1474,20 @@
1199
1474
  /** Work came back from the archive and has not been told yet which message it answered (the history may not be there yet). */
1200
1475
  let restoredWorkAwaitsItsMessage = false;
1201
1476
 
1477
+ /**
1478
+ * The kept work is that of a run this chat saw end, and not work that came back from the archive. The changes that come after a
1479
+ * run ended belong only to the first: work from the archive is of an earlier turn, and must never be given the changes of a run it
1480
+ * is not the work of (nor have them written into its archive record). A plain variable: it is read when the changes arrive, and
1481
+ * nothing is drawn from it.
1482
+ */
1483
+ let keptWorkIsFromARunThatEndedHere = false;
1484
+
1202
1485
  /** The work of the last run is not the newest work any more (a new run, another conversation, an empty thread). */
1203
1486
  function forgetKeptWork(): void {
1204
1487
  finishedGeneration = null;
1205
1488
  keptForUserMessageId = null;
1206
1489
  restoredWorkAwaitsItsMessage = false;
1490
+ keptWorkIsFromARunThatEndedHere = false;
1207
1491
  }
1208
1492
 
1209
1493
  /**
@@ -1240,6 +1524,7 @@
1240
1524
  try {
1241
1525
  if (working) {
1242
1526
  // A new run starts: what the last one kept is not the newest work any more, and no avatar of it is left to take over from
1527
+ changesHeldAtRunStart = generationChanges;
1243
1528
  forgetKeptWork();
1244
1529
  lastLiveLook = null;
1245
1530
  runWasWatched = true;
@@ -1256,12 +1541,16 @@
1256
1541
  thinking: keptThinking,
1257
1542
  code: keptCode,
1258
1543
  thoughtSeconds: keptThoughtSeconds,
1544
+ changes: changesOfTheRunThatEnded(),
1259
1545
  });
1260
1546
  // Said with the work, so that a prompt sent after it (even with the same words) is not taken for the one it answered
1261
1547
  keptForUserMessageId = finishedGeneration ? (answeredMessage?.id ?? null) : null;
1548
+ // This work is of the run that just ended here: the changes that come after it are its own (see the effect below)
1549
+ keptWorkIsFromARunThatEndedHere = finishedGeneration !== null;
1262
1550
  chatLog('[Chat] the assistant finished, kept for its conclusion:', {
1263
1551
  'Thinking Characters Kept': finishedGeneration?.thinking.length ?? 0,
1264
1552
  'Code Characters Kept': finishedGeneration?.code.length ?? 0,
1553
+ 'Files Changed Kept': finishedGeneration?.changes?.files.length ?? 0,
1265
1554
  'Thought Seconds': keptThoughtSeconds,
1266
1555
  });
1267
1556
  // Also in this browser (by conversation), so a reload of the page brings the same modules back under the conclusion
@@ -1273,6 +1562,37 @@
1273
1562
  });
1274
1563
  });
1275
1564
 
1565
+ // The changes of a run can come AFTER the run ended: the gateway sends them with the completed operation, and a host that lets
1566
+ // the chat take the next message as soon as the preview is up (the widget creator does) lowers `isGenerating` before that. They
1567
+ // go into the work that run kept, when it kept some and that work has no changes yet. Never while a run works (the end of that
1568
+ // run takes them), never the value the host held when the run began (it belongs to an earlier run), never when no work is
1569
+ // kept (another conversation was opened, or the run left nothing), and never into work that came back from the archive (it is of
1570
+ // an earlier turn, see `keptWorkIsFromARunThatEndedHere`). It is written below the effect that keeps the work, so that in a pass
1571
+ // where both happen the work is kept first.
1572
+ $effect(() => {
1573
+ const changesGiven = generationChanges;
1574
+ // Only a new value of what the host gave makes this run again; what is read below is not what makes it run
1575
+ untrack(() => {
1576
+ try {
1577
+ if (changesGiven === null || assistantIsWorking || changesGiven === changesHeldAtRunStart) return;
1578
+ const keptWork = finishedGeneration;
1579
+ // Work that came back from the archive is of an earlier turn: the changes that were just given are not its own
1580
+ if (!keptWork || !keptWorkIsFromARunThatEndedHere) return;
1581
+ const keptWorkWithChanges = withChangesOfTheRun(keptWork, changesGiven);
1582
+ // The same object back: the work has changes already, or what was given is not usable
1583
+ if (keptWorkWithChanges === keptWork) return;
1584
+ finishedGeneration = keptWorkWithChanges;
1585
+ chatLog('[Chat] the changes of the run that ended came after it, and were put with its work:', {
1586
+ 'Files Changed': keptWorkWithChanges.changes?.files.length ?? 0,
1587
+ });
1588
+ // The archive of this browser has the work as it was kept: it gets the changes too, so a reload brings them back
1589
+ void saveGenerationArchive(conversationId, keptWorkWithChanges);
1590
+ } catch (error) {
1591
+ chatWarn('[Chat] Could not put the changes that came after the run with its work:', error);
1592
+ }
1593
+ });
1594
+ });
1595
+
1276
1596
  // After a reload, or when a conversation is opened, the work of its last run comes back from what this browser kept, so the
1277
1597
  // newest turn shows its thinking and its code again. Only the id of the conversation makes this run again.
1278
1598
  let archiveConversationId: string | null = null;
@@ -1296,14 +1616,18 @@
1296
1616
  thinking: record.thinking,
1297
1617
  code: record.code,
1298
1618
  thoughtSeconds: record.thoughtSeconds,
1619
+ changes: record.changes,
1299
1620
  });
1300
1621
  // The archive knows the words of the prompt and nothing else: they find the turn again, and the effect below tells the
1301
1622
  // work which message that is as soon as the history is there
1302
1623
  keptForUserMessageId = null;
1303
1624
  restoredWorkAwaitsItsMessage = finishedGeneration !== null;
1625
+ // Not the work of a run that ended here: no changes that come later are its own
1626
+ keptWorkIsFromARunThatEndedHere = false;
1304
1627
  chatLog('[Chat] the work of the last run came back from the archive:', {
1305
1628
  'Thinking Characters': finishedGeneration?.thinking.length ?? 0,
1306
1629
  'Code Characters': finishedGeneration?.code.length ?? 0,
1630
+ 'Files Changed': finishedGeneration?.changes?.files.length ?? 0,
1307
1631
  });
1308
1632
  })
1309
1633
  .catch((error) => chatWarn('[Chat] Could not read the archive of the last run:', error));
@@ -1403,6 +1727,30 @@
1403
1727
  const liveLook = $derived(liveAgentLook(activityPhase));
1404
1728
  const liveModules = $derived(liveModulesView(activityPhase));
1405
1729
 
1730
+ // The plan comes before the build, and the coder's thinking and its code only come once the build has begun. So as soon as either
1731
+ // is on its way "Planning" is over, whatever the host still says: a plan the gateway could not make is never coming, and the
1732
+ // card would otherwise say "Planning" through the whole of the thinking (a reasoning model can think for a long time).
1733
+ const buildHasBegun = $derived(
1734
+ activityPhase === 'thinking-stream' || activityPhase === 'code-only' || activityPhase === 'thinking-and-code',
1735
+ );
1736
+ /** The host asked for a plan and it has not come: the plan card is shown closed, saying "Planning" in a shimmer. */
1737
+ const planIsBeingWritten = $derived(
1738
+ isGenerating && generationPlanPending && !generationPlan && !buildHasBegun,
1739
+ );
1740
+
1741
+ // Said once per change of what the plan card shows (never on every streamed token)
1742
+ let lastPlanCardSignature = '';
1743
+ $effect(() => {
1744
+ const signature = planIsBeingWritten
1745
+ ? 'planning'
1746
+ : planCardView
1747
+ ? `ready ${planCardView.progressCurrent}/${planCardView.progressTotal}`
1748
+ : 'hidden';
1749
+ if (signature === lastPlanCardSignature) return;
1750
+ lastPlanCardSignature = signature;
1751
+ chatLog('[Chat] the plan card:', { 'Shows': signature });
1752
+ });
1753
+
1406
1754
  // Said once per change of the look (never on every streamed token)
1407
1755
  let lastLiveLookSignature = '';
1408
1756
  $effect(() => {
@@ -1981,6 +2329,10 @@
1981
2329
  }
1982
2330
  </script>
1983
2331
 
2332
+ <!-- A sent message that names its files: the text with a badge (the picture and `#name`) where a word names one. Written without
2333
+ whitespace between the pieces, because the text around them is pre-wrapped and every space here would show. -->
2334
+ {#snippet sentTextWithBadges(segments: SentSegment[], attachments: readonly ContentItemOutput[])}{#each segments as segment, segmentIndex (segmentIndex)}{#if segment.kind === 'badge'}{@const badgeFile = attachments[segment.attachmentIndex]}{@const badgePicture = sentBadgePictureOf(badgeFile)}<span class={SENT_BADGE_CLASSES} data-sent-badge data-testid="chat-sent-reference-badge" title={sentBadgeTitleOf(badgeFile)}>{#if badgePicture}<img class={SENT_BADGE_THUMBNAIL_CLASSES} src={badgePicture} alt="" draggable="false" loading="lazy" decoding="async" />{/if}<span class={SENT_BADGE_LABEL_CLASSES} dir="auto">{segment.word}</span></span>{:else}{@render linkified(segment.text)}{/if}{/each}{/snippet}
2335
+
1984
2336
  {#snippet linkified(text: string)}{#each splitTextIntoLinks(text) as segment, segmentIndex (segmentIndex)}{#if segment.type === 'link'}<a
1985
2337
  href={segment.href}
1986
2338
  target="_blank"
@@ -1988,10 +2340,25 @@
1988
2340
  class="wc-chat-link text-foreground hover:text-primary underline underline-offset-2 [overflow-wrap:anywhere]"
1989
2341
  data-testid="chat-message-link">{segment.text}</a>{:else}{segment.text}{/if}{/each}{/snippet}
1990
2342
 
2343
+ <!-- The follow-up card (Figma: Chat cards, "Follow-ups"). Drawn in one of two places: at the end of the last turn's assistant column,
2344
+ or alone when that turn shows no words of the assistant. -->
2345
+ {#snippet followUpCardView()}
2346
+ {#if followUpCard}
2347
+ <FollowUpCard
2348
+ class={panelLayout ? '' : 'mt-1.5'}
2349
+ pills={followUpCard.pills}
2350
+ {draftText}
2351
+ disabled={isLoading || isGenerating}
2352
+ onPick={handleFollowUpPick}
2353
+ onDismiss={handleFollowUpDismiss}
2354
+ />
2355
+ {/if}
2356
+ {/snippet}
2357
+
1991
2358
  <div class="{panelLayout ? 'panel-messages-shell flex h-full min-h-0 w-full flex-1 flex-col' : 'contents'}">
1992
2359
  <div
1993
2360
  bind:this={messagesContainer}
1994
- 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'}"
2361
+ class="{className ? className : 'prompt-chat-messages-ct'} prompt-chat-messages-scroll flex flex-col overflow-y-auto {panelLayout && showEmptyState && !isLoading && !isGenerating ? 'pb-0' : ''} {panelLayout ? (showEmptyState && !isLoading && !isGenerating ? 'min-h-0 flex-1' : 'min-h-0 flex-1 pb-4') : 'space-y-4 pb-3'}"
1995
2362
  class:loading={isLoading}
1996
2363
  style={panelLayout
1997
2364
  ? `padding: 8px 16px ${showEmptyState && !isLoading && !isGenerating ? 0 : 16}px; overflow-anchor: none;`
@@ -2006,9 +2373,13 @@
2006
2373
  <!-- Figma: Chat / Empty. The hero (a circle with the sparkles icon, the title and a line under it) sits in the
2007
2374
  middle of the messages, and the suggestions are pinned under it, above the composer. The block takes the
2008
2375
  free height with flex-1 (not min-h-full): the sticky scroll-to-bottom row below it needs its own room, and a
2009
- block as tall as the whole area would push it out and make the list scroll. -->
2010
- <div class="empty-state-ct flex w-full flex-col gap-4 {panelLayout ? 'shrink-0' : 'flex-1'}">
2011
- <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'}">
2376
+ block as tall as the whole area would push it out and make the list scroll.
2377
+ In the panel the hero takes whatever height the suggestions leave and keeps its content in the middle of it, so
2378
+ it stays centered whatever the height of the window is (at the Figma frame's 700px the hero is its 508px, as
2379
+ before). A fixed 508px kept it high in a tall chat and, in a short one, pushed it behind the composer. The 96px
2380
+ it never goes below (min-h-24) is the height of the circle, the title and the line; under that the list scrolls. -->
2381
+ <div class="empty-state-ct flex w-full flex-1 flex-col gap-4">
2382
+ <div class="empty-state-hero flex flex-col items-center justify-center gap-3 text-center {panelLayout ? 'min-h-24 flex-1' : 'min-h-0 flex-1 px-2'}">
2012
2383
  <span class="empty-state-icon-circle bg-muted text-foreground flex size-10 shrink-0 items-center justify-center rounded-full" aria-hidden="true">
2013
2384
  <IconSparkles class="size-4 stroke-2" />
2014
2385
  </span>
@@ -2046,6 +2417,7 @@
2046
2417
  {@const userMsg = turn.user}
2047
2418
  {@const shownAttachments = visibleUserAttachments(turn, turnIndex)}
2048
2419
  {@const author = authorOfMessage(userMsg)}
2420
+ {@const sentSegments = sentSegmentsOf(userMsg.messageContent, shownAttachments)}
2049
2421
  <div class="message-container wc-chat-turn-user flex w-full flex-col {panelLayout ? 'items-end' : 'items-stretch'}"
2050
2422
  class:opacity-75={userMsg._optimistic}
2051
2423
  class:opacity-50={userMsg._failed}
@@ -2083,7 +2455,7 @@
2083
2455
  </div>
2084
2456
  {:else}
2085
2457
  <!-- Pretext sizes this text to the narrowest width that keeps its lines, so a wrapped bubble has no dead space beside them -->
2086
- <p class="wc-chat-text whitespace-pre-wrap [overflow-wrap:anywhere] {panelLayout ? '' : 'p-3'}" dir={dirForUserText($textDirection)} use:shrinkWrapBubble={{ text: userMsg.messageContent, enabled: tightBubbles }}>{@render linkified(userMsg.messageContent)}</p>
2458
+ <p class="wc-chat-text whitespace-pre-wrap [overflow-wrap:anywhere] {panelLayout ? '' : 'p-3'}" dir={dirForUserText($textDirection)} use:shrinkWrapBubble={{ text: userMsg.messageContent, enabled: tightBubbles, parts: sentSegments }}>{#if sentSegments}{@render sentTextWithBadges(sentSegments, shownAttachments)}{:else}{@render linkified(userMsg.messageContent)}{/if}</p>
2087
2459
  {/if}
2088
2460
  {/if}
2089
2461
  {#if shownAttachments.length > 0}
@@ -2155,13 +2527,16 @@
2155
2527
  <GenerationModule kind="thinking" text={assistant.finished.thinking} seconds={assistant.finished.thoughtSeconds} />
2156
2528
  {/if}
2157
2529
  {#if keptModules.showCode}
2158
- <GenerationModule kind="code" text={assistant.finished.code} />
2530
+ <GenerationModule kind="code" text={assistant.finished.code} changes={assistant.finished.changes} />
2159
2531
  {/if}
2160
2532
  {/if}
2161
2533
  {#each turn.replies as reply (reply.id)}
2162
2534
  {#if shouldShowAssistantReply(reply)}
2163
- <!-- In the standard layout a question's text is the question card's own title, so the reply has no text of its own to draw -->
2164
- {@const replyTextIsShown = !!reply.messageContent && (panelLayout || !(reply.suggestions && reply.suggestions.length > 0))}
2535
+ <!-- In the standard layout a question's text is the question card's own title, so the reply has no text of its own to draw
2536
+ (the follow-up pills of a build are not a question: the reply keeps its text) -->
2537
+ <!-- The card of questions the assistant puts before it builds is drawn in place of the words it was saved with (the sentence
2538
+ that introduces it is drawn above the card). A card that is closed with its picks unknown shows those words as they are. -->
2539
+ {@const replyTextIsShown = !!reply.messageContent && !drawsQuestionCard(reply) && (panelLayout || openQuestionOptionsOf(reply.suggestions, reply.id, skippedQuestionReplyIds).length === 0)}
2165
2540
  {#if panelLayout && isStoppedByUser(reply)}
2166
2541
  <!-- A stop is the person's own command: one quiet line, not the red "Could not build the widget" card. -->
2167
2542
  <p
@@ -2172,8 +2547,9 @@
2172
2547
  <span>{$t('chat.messages.stoppedByYou')}</span>
2173
2548
  </p>
2174
2549
  {:else if panelLayout && isCodegenFailure(reply)}
2175
- <!-- A failed reply in the docked panel is one short line, not a card: the warning mark, what went wrong in a few words,
2176
- and a refresh icon that runs the prompt of this turn again (on the last failure of the turn only, never on a plan limit). -->
2550
+ <!-- A failed reply in the docked panel is one short line, not a card: what went wrong in a few words, in red, and a refresh icon
2551
+ that runs the prompt of this turn again (on the last failure of the turn only, never on a plan limit). It has no warning
2552
+ mark: the avatar beside it holds its red error look, and says it. -->
2177
2553
  {@const canRetryFailure =
2178
2554
  !!onRetryMessage &&
2179
2555
  isLastCodegenFailureInTurn(turn, reply) &&
@@ -2183,7 +2559,6 @@
2183
2559
  class="wc-chat-turn-reply wc-chat-failed text-body text-destructive flex min-h-7 items-center gap-2"
2184
2560
  data-testid="chat-failed-notice"
2185
2561
  >
2186
- <IconAlertTriangle class="size-4 shrink-0 stroke-2" aria-hidden="true" />
2187
2562
  <span class="min-w-0 flex-1 [overflow-wrap:anywhere]">{failureLine(reply)}</span>
2188
2563
  {#if canRetryFailure}
2189
2564
  <button
@@ -2256,20 +2631,88 @@
2256
2631
  </div>
2257
2632
  {/if}
2258
2633
 
2259
- {#if reply.suggestions && reply.suggestions.length > 0 && !panelLayout}
2634
+ <!-- A question the assistant asks: its options, one of them recommended. The follow-up pills (chips with a title) are
2635
+ not options: they are the follow-up card under the last reply. Skip puts the card away (the question stays above as
2636
+ a plain message, and nothing is sent). -->
2637
+ {#if !panelLayout}
2638
+ {@const questionOptions = openQuestionOptionsOf(reply.suggestions, reply.id, skippedQuestionReplyIds)}
2639
+ {#if questionOptions.length > 0}
2640
+ {@const chipQuestionText = (visibleMessageContent(reply.messageContent || '') || $t('chat.messages.clarificationPrompt')).trim()}
2641
+ {@const chipQuestionOutcome = chipQuestionOutcomeOfReply(reply, questionOptions)}
2642
+ {#if chipQuestionOutcome.kind === 'open'}
2260
2643
  <QuestionCard
2261
2644
  class="mt-1.5 w-full max-w-full"
2262
- question={(visibleMessageContent(reply.messageContent || '') || $t('chat.messages.clarificationPrompt')).trim()}
2263
- options={reply.suggestions.map((suggestion, index) => ({
2645
+ question={chipQuestionText}
2646
+ options={questionOptions.map((suggestion, index) => ({
2264
2647
  id: String(index),
2265
2648
  label: suggestion.label
2266
2649
  }))}
2650
+ messages={questionCardMessages}
2267
2651
  onSubmit={(selectedIds) => {
2268
2652
  const picked = Number(selectedIds[0]);
2269
- const suggestion = reply.suggestions?.[picked];
2653
+ const suggestion = questionOptions[picked];
2270
2654
  if (suggestion) onClarificationSuggestionSelected?.(suggestion);
2271
2655
  }}
2656
+ onSkip={() => handleQuestionSkip(reply)}
2272
2657
  />
2658
+ {:else}
2659
+ <!-- The person went on in the chat: the card is closed. If what they wrote holds the words of one of its options,
2660
+ that option is what they answered; if not, the question was skipped. -->
2661
+ <QuestionCardSummary
2662
+ class="mt-1.5 w-full max-w-full"
2663
+ items={[
2664
+ {
2665
+ question: chipQuestionText,
2666
+ answers: chipQuestionOutcome.kind === 'answered' ? [chipQuestionOutcome.answer] : []
2667
+ }
2668
+ ]}
2669
+ messages={questionCardSummaryMessages}
2670
+ />
2671
+ {/if}
2672
+ {/if}
2673
+ {/if}
2674
+
2675
+ <!-- The card of questions the assistant puts before it builds (in either layout). Each question takes one answer or
2676
+ several, as the assistant set it. Next with nothing picked leaves that question to the assistant, and so does Skip for
2677
+ all of them. Writing in the chat instead closes the card with every question shown as skipped, and what was written is
2678
+ what the assistant goes on with. A card that is closed is its summary: what was picked, and "Skipped" where nothing was. -->
2679
+ {#if questionCardViews.get(reply.id)}
2680
+ {@const questionCardView = questionCardViews.get(reply.id)!}
2681
+ {#if questionCardView.state.kind !== 'closed'}
2682
+ <!-- "Intro Text": the line the assistant wrote above its questions (may be left out) -->
2683
+ {@const questionCardIntroText = questionCardView.card.message ?? ''}
2684
+ {#if questionCardIntroText}
2685
+ <Message role="assistant" class="wc-chat-turn-reply mt-0.5 max-w-full" data-testid="question-card-intro">
2686
+ {#snippet children()}
2687
+ <div class="message-content-assistant select-text text-sm leading-relaxed" use:bubbleScrollPadding>
2688
+ <p class="wc-chat-text whitespace-pre-wrap [overflow-wrap:anywhere]" dir={dirForUserText($textDirection)}>{@render linkified(questionCardIntroText)}</p>
2689
+ </div>
2690
+ {/snippet}
2691
+ </Message>
2692
+ {/if}
2693
+ {#if questionCardView.state.kind === 'open'}
2694
+ <QuestionCard
2695
+ class="mt-1.5 w-full max-w-full"
2696
+ question=""
2697
+ options={[]}
2698
+ nextSkips
2699
+ questions={questionCardView.card.questions.map((cardQuestion) => ({
2700
+ question: cardQuestion.question,
2701
+ options: cardQuestion.options.map((cardOption) => ({ id: cardOption.id, label: cardOption.label })),
2702
+ multiple: cardQuestion.allowMultiple === true
2703
+ }))}
2704
+ messages={questionCardMessages}
2705
+ onSubmit={(_lastQuestionPicks, pickedOptionIds) => handleQuestionCardSubmit(reply, questionCardView.card, pickedOptionIds)}
2706
+ onSkip={() => handleQuestionCardSkip(reply, questionCardView.card)}
2707
+ />
2708
+ {:else}
2709
+ <QuestionCardSummary
2710
+ class="mt-1.5 w-full max-w-full"
2711
+ items={questionCardView.state.rows}
2712
+ messages={questionCardSummaryMessages}
2713
+ />
2714
+ {/if}
2715
+ {/if}
2273
2716
  {/if}
2274
2717
 
2275
2718
  <!-- A failure about the plan or the credits: the way out is to upgrade. Running the prompt again is the regenerate icon of the last message. -->
@@ -2299,7 +2742,15 @@
2299
2742
  {$t('chat.generation.doneMessage')}
2300
2743
  </p>
2301
2744
  {/if}
2745
+ <!-- Ideas for what to improve next: under the conclusion of the last turn, and nowhere else -->
2746
+ {#if turnIndex === chatTurns.length - 1}
2747
+ {@render followUpCardView()}
2748
+ {/if}
2302
2749
  </AgentTurn>
2750
+ {:else if turnIndex === chatTurns.length - 1 && followUpCard}
2751
+ <!-- A turn the chat shows no words for (the build ran, and what it said is kept out of sight, as after a reload) still ends with
2752
+ its ideas: the card alone, with no face beside it -->
2753
+ {@render followUpCardView()}
2303
2754
  {/if}
2304
2755
 
2305
2756
  <!-- Copy, regenerate and the two thumbs: at the end of the last message only, and not while something is being generated.
@@ -2333,24 +2784,27 @@
2333
2784
  <!-- (The wrapper is what the list sees grow: keepEndInView keeps the end of the list in view while the turn changes size.) -->
2334
2785
  <div class="loading-indicator-ct {panelLayout ? 'mt-9 pb-3' : '-mt-3'}" use:keepEndInView>
2335
2786
  <AgentTurn look={liveLook} {renderAgentAvatar}>
2336
- {#if planCardView}
2787
+ <!-- One card from "Planning" to the finished plan: it is the same card, so it opens where it stood when the plan arrives -->
2788
+ {#if planCardView || planIsBeingWritten}
2337
2789
  <PlanCard
2338
2790
  class="w-full"
2339
2791
  dir="auto"
2340
2792
  role="region"
2341
2793
  aria-label={$t('chat.plan.regionLabel')}
2342
- title={planCardView.title}
2343
- tasks={planCardView.tasks}
2344
- progressCurrent={planCardView.progressCurrent}
2345
- progressTotal={planCardView.progressTotal}
2794
+ planning={planIsBeingWritten}
2795
+ title={planCardView?.title ?? ''}
2796
+ tasks={planCardView?.tasks ?? []}
2797
+ progressCurrent={planCardView?.progressCurrent}
2798
+ progressTotal={planCardView?.progressTotal}
2346
2799
  visibleTaskCount={4}
2347
2800
  messages={planCardMessages}
2348
2801
  />
2349
2802
  {/if}
2350
- {#if liveModules.showShimmer}
2803
+ <!-- The closed plan card already says "Planning" in a shimmer, so the thinking line waits for it to open -->
2804
+ {#if liveModules.showShimmer && !planIsBeingWritten}
2351
2805
  <div class="thinking-bubble relative flex min-h-7 w-fit items-center whitespace-nowrap text-sm">
2352
2806
  <span class="thinking-sizer" aria-hidden="true">{thinkingLabel}</span>
2353
- <span class="thinking-reveal absolute inset-0 flex items-center">{shownThinkingLabel}</span>
2807
+ <span class="shimmer absolute inset-0 flex items-center">{shownThinkingLabel}</span>
2354
2808
  </div>
2355
2809
  {/if}
2356
2810
  {#if liveModules.showThinking}
@@ -2424,25 +2878,6 @@
2424
2878
  .thinking-sizer {
2425
2879
  visibility: hidden;
2426
2880
  }
2427
- .thinking-reveal {
2428
- background-image: linear-gradient(100deg, #1f2937 35%, #ffffff 50%, #1f2937 65%);
2429
- background-size: 200% 100%;
2430
- -webkit-background-clip: text;
2431
- background-clip: text;
2432
- color: transparent;
2433
- animation: thinking-shine 1.6s linear infinite;
2434
- }
2435
- @keyframes thinking-shine {
2436
- 0% { background-position: 100% 0; }
2437
- 100% { background-position: -100% 0; }
2438
- }
2439
- @media (prefers-reduced-motion: reduce) {
2440
- .thinking-reveal {
2441
- animation: none;
2442
- color: inherit;
2443
- background-image: none;
2444
- }
2445
- }
2446
2881
  .loading {
2447
2882
  opacity: 0.75;
2448
2883
  }