@widgetic/chat 0.1.39 → 0.1.41

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 (58) hide show
  1. package/README.md +71 -0
  2. package/dist/components/Chat.svelte +63 -4
  3. package/dist/components/Chat.svelte.d.ts +31 -0
  4. package/dist/components/ChatComposer.svelte +5 -1
  5. package/dist/components/ChatMessages.svelte +574 -214
  6. package/dist/components/ChatMessages.svelte.d.ts +18 -0
  7. package/dist/components/agent/AgentAvatar.svelte +153 -0
  8. package/dist/components/agent/AgentAvatar.svelte.d.ts +27 -0
  9. package/dist/components/agent/AgentTurn.svelte +64 -0
  10. package/dist/components/agent/AgentTurn.svelte.d.ts +32 -0
  11. package/dist/components/agent/AvatarBoundary.svelte +29 -0
  12. package/dist/components/agent/AvatarBoundary.svelte.d.ts +20 -0
  13. package/dist/components/agent/CodeCard.svelte +288 -0
  14. package/dist/components/agent/CodeCard.svelte.d.ts +12 -0
  15. package/dist/components/agent/GenerationModule.svelte +99 -0
  16. package/dist/components/agent/GenerationModule.svelte.d.ts +16 -0
  17. package/dist/components/agent/MemberAvatar.svelte +87 -0
  18. package/dist/components/agent/MemberAvatar.svelte.d.ts +8 -0
  19. package/dist/components/index.d.ts +5 -0
  20. package/dist/components/index.js +9 -0
  21. package/dist/i18n/index.d.ts +1 -0
  22. package/dist/i18n/index.js +1 -0
  23. package/dist/i18n/messages.d.ts +46 -9
  24. package/dist/i18n/messages.js +48 -10
  25. package/dist/i18n/sketchLocales.d.ts +2 -0
  26. package/dist/i18n/sketchLocales.js +83 -0
  27. package/dist/services/index.d.ts +5 -0
  28. package/dist/services/index.js +3 -0
  29. package/dist/services/sketchAssistantClient.d.ts +68 -0
  30. package/dist/services/sketchAssistantClient.js +73 -0
  31. package/dist/services/sketchAssistantOrchestrator.d.ts +45 -0
  32. package/dist/services/sketchAssistantOrchestrator.js +128 -0
  33. package/dist/services/sketchAssistantReply.d.ts +12 -0
  34. package/dist/services/sketchAssistantReply.js +28 -0
  35. package/dist/stores/chatStore.d.ts +1 -0
  36. package/dist/stores/chatStore.js +21 -0
  37. package/dist/types/agent.d.ts +74 -0
  38. package/dist/types/agent.js +1 -0
  39. package/dist/types/index.d.ts +1 -0
  40. package/dist/types/index.js +2 -0
  41. package/dist/types/message.d.ts +2 -0
  42. package/dist/utils/agentTurn.d.ts +219 -0
  43. package/dist/utils/agentTurn.js +301 -0
  44. package/dist/utils/bubbleFit.d.ts +75 -0
  45. package/dist/utils/bubbleFit.js +116 -0
  46. package/dist/utils/bubbleShrinkWrap.d.ts +32 -0
  47. package/dist/utils/bubbleShrinkWrap.js +360 -0
  48. package/dist/utils/codeHighlight.d.ts +13 -0
  49. package/dist/utils/codeHighlight.js +61 -0
  50. package/dist/utils/codePrettier.d.ts +6 -0
  51. package/dist/utils/codePrettier.js +34 -0
  52. package/dist/utils/codeStreamFormat.d.ts +90 -0
  53. package/dist/utils/codeStreamFormat.js +429 -0
  54. package/dist/utils/generationArchiveStore.d.ts +5 -0
  55. package/dist/utils/generationArchiveStore.js +1 -0
  56. package/dist/utils/index.d.ts +2 -0
  57. package/dist/utils/index.js +3 -0
  58. package/package.json +3 -2
@@ -1,8 +1,9 @@
1
1
  <script lang="ts">
2
2
  import type { ChatMessage, ChatContext } from '../types/index.js';
3
3
  import type { ClarificationSuggestion, DesignControlRequest, VersionRating } from '../types/message.js';
4
- import { MESSAGE_COLORS } from '../constants/colors.js';
5
- import { chatLog } from '../utils/logger.js';
4
+ import type { AgentAvatarRenderer, AgentAvatarState, AgentSoundPlayer, ChatMember } from '../types/agent.js';
5
+ import { chatLog, chatWarn } from '../utils/logger.js';
6
+ import { shrinkWrapBubble } from '../utils/bubbleShrinkWrap.js';
6
7
  import { splitTextIntoLinks } from '../utils/linkifyText.js';
7
8
  import { isRatableVersionReply, type VersionThumb } from '../utils/versionRatings.js';
8
9
  import { isLocalMessageId, restoreBeforeTarget, textToCopy, type TurnRestorePoint } from '../utils/messageActions.js';
@@ -11,7 +12,10 @@
11
12
  import PanelFollowUpSuggestions from './PanelFollowUpSuggestions.svelte';
12
13
  import CodeBlock from './CodeBlock.svelte';
13
14
  import MessageActions from './MessageActions.svelte';
14
- import { onDestroy, onMount, tick } from 'svelte';
15
+ import AgentTurn from './agent/AgentTurn.svelte';
16
+ import GenerationModule from './agent/GenerationModule.svelte';
17
+ import MemberAvatar from './agent/MemberAvatar.svelte';
18
+ import { onDestroy, onMount, tick, untrack } from 'svelte';
15
19
  import type { Snippet } from 'svelte';
16
20
  import { useChatLanguage } from '../i18n/language.js';
17
21
  import { CHAT_MESSAGES } from '../i18n/messages.js';
@@ -19,6 +23,8 @@
19
23
  import { dirForUserText, useTextDirection } from '@widgetic/design-system/components/textDirection';
20
24
  import IconSparkles from '@tabler/icons-svelte/icons/sparkles';
21
25
  import IconPlayerStop from '@tabler/icons-svelte/icons/player-stop';
26
+ import IconAlertTriangle from '@tabler/icons-svelte/icons/alert-triangle';
27
+ import IconRefresh from '@tabler/icons-svelte/icons/refresh';
22
28
  import {
23
29
  generationActivityAriaKey,
24
30
  generationActivityPhase,
@@ -27,6 +33,25 @@
27
33
  readCodegenStreamTail,
28
34
  } from '../utils/generationActivity.js';
29
35
  import { mapWidgetPlanToPlanCard, type GenerationPlanWire } from '../utils/generationPlan.js';
36
+ import {
37
+ agentLookSignature,
38
+ avatarStartAfter,
39
+ finishedGenerationBelongsTo,
40
+ finishedModulesView,
41
+ keepFinishedGeneration,
42
+ keptWorkIsOutdated,
43
+ liveAgentLook,
44
+ liveModulesView,
45
+ pageNamesPeople,
46
+ resolveChatMember,
47
+ settledAgentLook,
48
+ soundStateOf,
49
+ turnOutcome,
50
+ type AgentAvatarSize,
51
+ type AgentLook,
52
+ type FinishedGeneration,
53
+ type TurnReplyFacts
54
+ } from '../utils/agentTurn.js';
30
55
  import {
31
56
  clearGenerationArchive,
32
57
  loadGenerationArchive,
@@ -35,8 +60,6 @@
35
60
  // The chat barrel of the design system: its export map resolves `components/<name>` to `<name>.js` only,
36
61
  // so a deep `.svelte` path types fine but cannot be resolved by Vite or Node.
37
62
  import {
38
- ActivityRow,
39
- ChatAlertCard,
40
63
  Message,
41
64
  MessageCheckpointRow,
42
65
  PlanCard,
@@ -139,6 +162,23 @@
139
162
  onRequestOlderMessages?: () => Promise<boolean | void>;
140
163
  /** Widget creator side panel: Figma empty / follow-up suggestion cards. */
141
164
  panelLayout?: boolean;
165
+ /**
166
+ * The people of the project's team. A message a person wrote gets that person's picture (or initials) at its right, and
167
+ * their e-mail while the pointer is on it.
168
+ */
169
+ members?: ChatMember[];
170
+ /** The signed-in person: who wrote the messages they just sent, and anything no member matches. */
171
+ currentUser?: ChatMember | null;
172
+ /** How the assistant's avatar is drawn (the Scribble Mascot in the Widgetic apps). A plain round avatar without it. */
173
+ renderAgentAvatar?: AgentAvatarRenderer;
174
+ /** Lets the avatar be heard: told its state once for each change, for runs the person watched. Silent without it. */
175
+ agentSound?: AgentSoundPlayer;
176
+ /**
177
+ * Sizes the bubbles of what people wrote to their text with Pretext (https://chenglou.me/pretext/bubbles/): a bubble whose text
178
+ * wraps is as narrow as its widest line allows, not as wide as the chat, so no dead space is left beside short lines. A text that
179
+ * 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
+ */
181
+ tightBubbles?: boolean;
142
182
  /** Active conversation id — persists generation archive in IndexedDB across reload. */
143
183
  conversationId?: string | null;
144
184
  }
@@ -174,6 +214,11 @@
174
214
  hasOlderMessages = false,
175
215
  onRequestOlderMessages,
176
216
  panelLayout = false,
217
+ members = [],
218
+ currentUser = null,
219
+ renderAgentAvatar,
220
+ agentSound,
221
+ tightBubbles = true,
177
222
  conversationId = null,
178
223
  }: Props = $props();
179
224
 
@@ -216,7 +261,10 @@
216
261
  }
217
262
  return;
218
263
  }
219
- node.style.setProperty('padding-inline-end', messagesHasScrollbar ? '0px' : '12px', 'important');
264
+ // A scrollbar that takes room of its own (classic bars) is the gap itself. One that floats over the list (overlay bars, as on
265
+ // a Mac) takes none, so there the 12px stay, and a wide card (a question, a plan) does not touch the edge under the bar.
266
+ const scrollbarTakesRoom = node.offsetWidth - node.clientWidth > 0;
267
+ node.style.setProperty('padding-inline-end', messagesHasScrollbar && scrollbarTakesRoom ? '0px' : '12px', 'important');
220
268
  }
221
269
  const resizeObserver = new ResizeObserver(check);
222
270
  resizeObserver.observe(node);
@@ -815,18 +863,28 @@
815
863
  return !isGenerationSummary(reply);
816
864
  }
817
865
 
866
+ /**
867
+ * The parent reads the conversation once and sets `showEmptyState` from what it found. A message that arrives
868
+ * afterwards (a sketch turn, a first send that failed) hides the hero too: kept, it sits over the messages as soon
869
+ * as the list is taller than the panel (the block shrinks to nothing and its content spills over the turns below).
870
+ */
871
+ const emptyStateVisible = $derived(showEmptyState && messages.length === 0);
872
+
818
873
  /** Figma ready frame: follow-up cards sit above the composer, outside the scroll area. */
819
874
  const panelAnchoredFollowUp = $derived.by((): { labels: string[] } | null => {
820
- if (!panelLayout || showEmptyState) return null;
875
+ if (!panelLayout || emptyStateVisible) return null;
821
876
  for (let ti = chatTurns.length - 1; ti >= 0; ti--) {
822
877
  const turn = chatTurns[ti];
823
878
  for (let ri = turn.replies.length - 1; ri >= 0; ri--) {
824
879
  const reply = turn.replies[ri];
825
880
  const meta = reply.metadata as { panelFollowUp?: boolean } | undefined;
826
- if (!reply.suggestions?.length || meta?.panelFollowUp === false) continue;
881
+ // 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);
884
+ if (!followUpSuggestions.length || meta?.panelFollowUp === false) continue;
827
885
  if (!shouldShowAssistantReply(reply)) continue;
828
886
  // A suggestion without a text label would give the keyed list a NaN key and stop the whole panel from rendering.
829
- const suggestionLabels = reply.suggestions
887
+ const suggestionLabels = followUpSuggestions
830
888
  .map((suggestion) => suggestion?.label)
831
889
  .filter((label): label is string => typeof label === 'string' && label.trim().length > 0);
832
890
  if (suggestionLabels.length === 0) continue;
@@ -891,6 +949,108 @@
891
949
  );
892
950
  });
893
951
 
952
+ // --- the faces: the assistant's avatar on its turn, and the people's next to what they wrote --------------------------
953
+
954
+ /** Whether the page said who is who: without it no face is drawn next to what people wrote. */
955
+ const peopleAreNamed = $derived(pageNamesPeople(members, currentUser));
956
+
957
+ /** The person who wrote a message, or null when nobody can be named (no face is better than a wrong one). */
958
+ function authorOfMessage(message: ChatMessage): ChatMember | null {
959
+ if (!peopleAreNamed) return null;
960
+ return resolveChatMember(message.userId, members, currentUser);
961
+ }
962
+
963
+ // An author the page did not name is said once per author, not on every redraw
964
+ const unnamedAuthorIdsSaid = new Set<string>();
965
+ $effect(() => {
966
+ if (!peopleAreNamed) return;
967
+ for (const message of messages) {
968
+ if (message.messageType !== 'user') continue;
969
+ const authorId = message.userId;
970
+ if (unnamedAuthorIdsSaid.has(authorId) || resolveChatMember(authorId, members, currentUser)) continue;
971
+ unnamedAuthorIdsSaid.add(authorId);
972
+ chatWarn('[Chat] No member of the team matches the author of a message, so it has no face:', authorId);
973
+ }
974
+ });
975
+
976
+ /** What the assistant looks like and shows in one turn. */
977
+ type TurnAssistantView = {
978
+ /** Anything to draw for the assistant in this turn: a reply to show, or a run that just ended for it. */
979
+ hasContent: boolean;
980
+ look: AgentLook;
981
+ /**
982
+ * The size the avatar glides from as it appears. It takes over from the live avatar of the run that just ended, so it starts as
983
+ * large or as small as that one was (a Stop pressed while it was large shrinks it down; the conclusion grows out of the work).
984
+ */
985
+ startSize: AgentAvatarSize | undefined;
986
+ /** The state the avatar is drawn in first, the one of the live avatar it takes over from, before it moves on to its own. */
987
+ startState: AgentAvatarState | undefined;
988
+ /** What the assistant did in the run that just ended for this turn: the modules under its conclusion. */
989
+ finished: FinishedGeneration | null;
990
+ /** It built something and the chat shows no message about it: the catalog's "done" line is its conclusion. */
991
+ showDoneLine: boolean;
992
+ };
993
+
994
+ const NO_ASSISTANT_VIEW: TurnAssistantView = {
995
+ hasContent: false,
996
+ look: { state: 'idle', size: 'small', live: false },
997
+ startSize: undefined,
998
+ startState: undefined,
999
+ finished: null,
1000
+ showDoneLine: false,
1001
+ };
1002
+
1003
+ /** What the chat found out about one reply, in the terms the turn's outcome is judged by (the rules live in `agentTurn.ts`). */
1004
+ function replyFactsOf(reply: ChatMessage): TurnReplyFacts {
1005
+ return {
1006
+ isFailure: isCodegenFailure(reply),
1007
+ 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,
1010
+ hasCommit: messageHasCommit(reply) && !isCodegenFailure(reply),
1011
+ isCompletion: /^Code generation completed/i.test((reply.messageContent || '').trim()),
1012
+ };
1013
+ }
1014
+
1015
+ /**
1016
+ * 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.
1018
+ */
1019
+ function assistantViewOf(turn: ChatTurn): TurnAssistantView {
1020
+ const visibleReplies = turn.replies.filter(shouldShowAssistantReply);
1021
+ const isNewestTurn = isLastUserTurn(turn);
1022
+ const keptWork = finishedGeneration;
1023
+ // The words of the prompt find the turn again after a reload, but a prompt sent again (a retry) has the same words as the one
1024
+ // the work answered: the chat adds that message before the host has saved it and started the run, and until then the new
1025
+ // turn is not the work's, which the message the work answered tells.
1026
+ const finished =
1027
+ isNewestTurn &&
1028
+ finishedGenerationBelongsTo(keptWork, turn.user?.messageContent) &&
1029
+ !keptWorkIsOutdated(keptForUserMessageId, messages)
1030
+ ? keptWork
1031
+ : null;
1032
+ const outcome = turnOutcome(visibleReplies.map(replyFactsOf), finished !== null);
1033
+ if (outcome === null) return NO_ASSISTANT_VIEW;
1034
+ // A success the person did not just watch (the conversation was loaded, or a debug line says so) is not celebrated
1035
+ const shownOutcome = outcome === 'success' && finished === null ? 'answer' : outcome;
1036
+ // The run is over, but the effects that keep its work and clear its traces have not run yet. The page tells a failure or a
1037
+ // stop in the same tick the run ends (the creator adds the message, then clears isGenerating), so the avatar that appears in
1038
+ // this very pass is the end of that run, and the one of a success appears a pass later. It takes over from the live avatar
1039
+ // and starts from how that one looked: a Stop pressed while the avatar is still large shrinks it down to its small size, the
1040
+ // conclusion grows out of the small avatar of the work.
1041
+ const runIsEnding = thinkingHold && !assistantIsWorking;
1042
+ const takesOverFromLiveAvatar = finished !== null || (isNewestTurn && runIsEnding);
1043
+ const avatarStart = takesOverFromLiveAvatar ? avatarStartAfter(lastLiveLook) : null;
1044
+ return {
1045
+ hasContent: true,
1046
+ look: settledAgentLook(shownOutcome, isNewestTurn),
1047
+ startSize: avatarStart?.startSize,
1048
+ startState: avatarStart?.startState,
1049
+ finished,
1050
+ showDoneLine: finished !== null && outcome === 'success' && visibleReplies.length === 0,
1051
+ };
1052
+ }
1053
+
894
1054
  /** One entry per turn, in the order of `chatTurns`. */
895
1055
  const restorePoints = $derived(chatTurns.map(restorePointOf));
896
1056
 
@@ -903,13 +1063,6 @@
903
1063
  return autoScroll;
904
1064
  }
905
1065
 
906
- function scrollGenerationTail(): void {
907
- const tail = messagesContainer?.querySelector('.generation-stream');
908
- if (tail) tail.scrollTop = tail.scrollHeight;
909
- const thinking = messagesContainer?.querySelector('.generation-thinking-stream');
910
- if (thinking) thinking.scrollTop = thinking.scrollHeight;
911
- }
912
-
913
1066
  function messageImpliesAttachedFile(content: string): boolean {
914
1067
  return /imaginea ata[sș]at[ăa]|attached (reference )?(image|document|file|pdf|video)|reference image|din imagine|ata[sș]at[ăa]?\s+(document|pdf|fi[sș]ier|video)|attached document/i.test(
915
1068
  content,
@@ -930,14 +1083,14 @@
930
1083
  return /credit balance|free trial|not available in your plan|not available on the free plan|upgrade your plan|upgrade to a solo/i.test(message);
931
1084
  }
932
1085
 
933
- /** What the alert card of a failed reply says under its title: the server's own words when they tell something specific
934
- * (the plan or the credits, too many requests, the service is unavailable, the run was stopped), otherwise Figma's line. */
935
- function failureAlertDescription(message: ChatMessage): string {
1086
+ /** What the line of a failed reply says: the server's own words when they tell something specific (the plan or the credits,
1087
+ * too many requests, the service is unavailable, the run was stopped), otherwise the short "Could not build the widget". */
1088
+ function failureLine(message: ChatMessage): string {
936
1089
  const serverText = visibleMessageContent(message.messageContent || '').trim();
937
1090
  const isSpecificFailure =
938
1091
  isPlanLimitMessage(message.messageContent) ||
939
1092
  /Too many generation requests|temporarily unavailable|Generation stopped/i.test(serverText);
940
- return isSpecificFailure && serverText ? serverText : $t('chat.messages.failedHint');
1093
+ return isSpecificFailure && serverText ? serverText : $t('chat.messages.failedTitle');
941
1094
  }
942
1095
 
943
1096
  function openUpgradePlans() {
@@ -985,27 +1138,11 @@
985
1138
  let thinkingHold = $state(false);
986
1139
  let generationWasRunning = false;
987
1140
  let keptThinkingText = $state('');
988
- $effect(() => {
989
- const id = conversationId?.trim() ?? '';
990
- void messages.length;
991
- if (!id || isGenerating) return;
992
- void loadGenerationArchive(id).then((record) => {
993
- if (record) archivedGeneration = record;
994
- });
995
- });
996
-
997
- let archivedGeneration = $state<{
998
- thinking: string;
999
- code: string;
1000
- thoughtSeconds: number | null;
1001
- } | null>(null);
1002
1141
  let thinkingStartedAtMs = $state<number | null>(null);
1003
1142
  let codeStreamingStartedAtMs = $state<number | null>(null);
1004
1143
  let frozenThoughtSeconds = $state<number | null>(null);
1005
- let thinkingExpanded = $state(false);
1006
1144
  let generationAriaLine = $state('');
1007
1145
  let lastGenerationAriaKey = '';
1008
- let thinkingStreamEl = $state<HTMLDivElement | null>(null);
1009
1146
 
1010
1147
  const planCardView = $derived(
1011
1148
  isGenerating && generationPlan
@@ -1036,10 +1173,173 @@
1036
1173
  return previous + '\n' + incoming;
1037
1174
  }
1038
1175
 
1176
+ // --- what the assistant did, kept for its conclusion -------------------------------------------------------------
1177
+
1178
+ /**
1179
+ * True only while the assistant really works. The chat raises `isGenerating` while the history loads as well (that locks the
1180
+ * composer), but loading is no work of the assistant: no avatar thinks for it, and nothing is kept from it.
1181
+ */
1182
+ const assistantIsWorking = $derived(isGenerating && !isLoading);
1183
+
1184
+ /**
1185
+ * The thinking and the code of the generation that just ended: the modules under its conclusion show them, closed, for the
1186
+ * person to open. For the newest turn only. The host saves neither, so this browser keeps them (see the archive below) and
1187
+ * they come back after a reload, found again by the words of the prompt they answered.
1188
+ */
1189
+ let finishedGeneration = $state<FinishedGeneration | null>(null);
1190
+
1191
+ /**
1192
+ * 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
1193
+ * are the same (see `keptWorkIsOutdated`). It is set together with `finishedGeneration`, which is what makes the turns draw
1194
+ * again, so it needs no state of its own. Work that came back from the archive knows only the words of its prompt: this is null
1195
+ * until the history is there and the message with those words is found (see `restoredWorkAwaitsItsMessage`).
1196
+ */
1197
+ let keptForUserMessageId: string | null = null;
1198
+
1199
+ /** Work came back from the archive and has not been told yet which message it answered (the history may not be there yet). */
1200
+ let restoredWorkAwaitsItsMessage = false;
1201
+
1202
+ /** The work of the last run is not the newest work any more (a new run, another conversation, an empty thread). */
1203
+ function forgetKeptWork(): void {
1204
+ finishedGeneration = null;
1205
+ keptForUserMessageId = null;
1206
+ restoredWorkAwaitsItsMessage = false;
1207
+ }
1208
+
1209
+ /**
1210
+ * How the live avatar of the run looked at its last change of look. The avatar that takes over when the run ends starts from it
1211
+ * (see `avatarStartAfter`). It is read in the pass that ends the run, which does not wait for it, so it is a plain variable and
1212
+ * not state: a change of look has no reason to draw the list again.
1213
+ */
1214
+ let lastLiveLook: AgentLook | null = null;
1215
+
1216
+ /**
1217
+ * A run worked while this conversation was open here: the person saw it happen. The sound of the avatar follows only what the
1218
+ * person saw, so a conversation that is merely opened (whose newest turn may well have ended in an error) stays silent until a run
1219
+ * works in it (see `soundStateOf`). State, because what the sound is told is worked out from it.
1220
+ */
1221
+ let runWasWatched = $state(false);
1222
+
1223
+ /** The newest message the person sent: the turn the run that just ended belongs to. */
1224
+ function newestUserMessage(): ChatMessage | null {
1225
+ for (let messageIndex = messages.length - 1; messageIndex >= 0; messageIndex--) {
1226
+ if (messages[messageIndex].messageType === 'user') return messages[messageIndex];
1227
+ }
1228
+ return null;
1229
+ }
1230
+
1231
+ let assistantWasWorking = false;
1232
+ // The end of a run keeps its work. It has to do that BEFORE the effect below clears the texts that work is made of: effects run
1233
+ // in the order they are written, so this one stays above it (a test of the chat guards the order).
1234
+ $effect(() => {
1235
+ const working = assistantIsWorking;
1236
+ if (working === assistantWasWorking) return;
1237
+ assistantWasWorking = working;
1238
+ // Only the start and the end of a run get here; what is read below is not what makes this run again
1239
+ untrack(() => {
1240
+ try {
1241
+ if (working) {
1242
+ // 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
1243
+ forgetKeptWork();
1244
+ lastLiveLook = null;
1245
+ runWasWatched = true;
1246
+ return;
1247
+ }
1248
+ const keptThinking = keptThinkingText;
1249
+ const keptCode = keptGenerationText;
1250
+ const keptThoughtSeconds =
1251
+ frozenThoughtSeconds ??
1252
+ (keptThinking.trim().length > 0 ? thoughtDurationSeconds(thinkingStartedAtMs, Date.now()) : null);
1253
+ const answeredMessage = newestUserMessage();
1254
+ finishedGeneration = keepFinishedGeneration({
1255
+ promptText: answeredMessage?.messageContent,
1256
+ thinking: keptThinking,
1257
+ code: keptCode,
1258
+ thoughtSeconds: keptThoughtSeconds,
1259
+ });
1260
+ // 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
+ keptForUserMessageId = finishedGeneration ? (answeredMessage?.id ?? null) : null;
1262
+ chatLog('[Chat] the assistant finished, kept for its conclusion:', {
1263
+ 'Thinking Characters Kept': finishedGeneration?.thinking.length ?? 0,
1264
+ 'Code Characters Kept': finishedGeneration?.code.length ?? 0,
1265
+ 'Thought Seconds': keptThoughtSeconds,
1266
+ });
1267
+ // Also in this browser (by conversation), so a reload of the page brings the same modules back under the conclusion
1268
+ if (finishedGeneration) void saveGenerationArchive(conversationId, finishedGeneration);
1269
+ } catch (error) {
1270
+ chatWarn('[Chat] Could not keep what the assistant did for its conclusion:', error);
1271
+ forgetKeptWork();
1272
+ }
1273
+ });
1274
+ });
1275
+
1276
+ // 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
+ // newest turn shows its thinking and its code again. Only the id of the conversation makes this run again.
1278
+ let archiveConversationId: string | null = null;
1279
+ $effect(() => {
1280
+ const archiveKey = conversationId?.trim() || null;
1281
+ untrack(() => {
1282
+ const previousKey = archiveConversationId;
1283
+ archiveConversationId = archiveKey;
1284
+ // Another conversation (or none) is open: nothing in it was watched yet. Not while a run works at this very moment: the first
1285
+ // message of a new chat makes its conversation, and the run it starts is the one the person is watching.
1286
+ if (previousKey !== archiveKey && !assistantIsWorking) runWasWatched = false;
1287
+ if (!archiveKey) return;
1288
+ // Another conversation was opened: what was kept for the one before is not this one's work
1289
+ if (previousKey && previousKey !== archiveKey) forgetKeptWork();
1290
+ void loadGenerationArchive(archiveKey)
1291
+ .then((record) => {
1292
+ // A run that began or ended while the archive was read keeps what it has, and so does a conversation that changed meanwhile
1293
+ if (!record || assistantIsWorking || finishedGeneration || archiveConversationId !== archiveKey) return;
1294
+ finishedGeneration = keepFinishedGeneration({
1295
+ promptText: record.prompt,
1296
+ thinking: record.thinking,
1297
+ code: record.code,
1298
+ thoughtSeconds: record.thoughtSeconds,
1299
+ });
1300
+ // The archive knows the words of the prompt and nothing else: they find the turn again, and the effect below tells the
1301
+ // work which message that is as soon as the history is there
1302
+ keptForUserMessageId = null;
1303
+ restoredWorkAwaitsItsMessage = finishedGeneration !== null;
1304
+ chatLog('[Chat] the work of the last run came back from the archive:', {
1305
+ 'Thinking Characters': finishedGeneration?.thinking.length ?? 0,
1306
+ 'Code Characters': finishedGeneration?.code.length ?? 0,
1307
+ });
1308
+ })
1309
+ .catch((error) => chatWarn('[Chat] Could not read the archive of the last run:', error));
1310
+ });
1311
+ });
1312
+
1313
+ // The work that came back from the archive is told which message of the person it answered: the newest one with its words, once
1314
+ // the history is there. From then on a prompt sent after it is a new turn even if its words are the same (a retry after a
1315
+ // reload). Work that answers none of the newest messages (the run it came from is not the newest turn) has no turn to show
1316
+ // under, and must not be taken for the work of a later prompt that happens to have the same words, so it goes.
1317
+ $effect(() => {
1318
+ const restoredWork = finishedGeneration;
1319
+ const historyIsThere = isInitialized && !isLoading && messages.length > 0;
1320
+ if (!restoredWork || !historyIsThere || assistantIsWorking) return;
1321
+ untrack(() => {
1322
+ if (!restoredWorkAwaitsItsMessage) return;
1323
+ restoredWorkAwaitsItsMessage = false;
1324
+ try {
1325
+ const newestMessage = newestUserMessage();
1326
+ if (newestMessage && finishedGenerationBelongsTo(restoredWork, newestMessage.messageContent)) {
1327
+ keptForUserMessageId = newestMessage.id;
1328
+ return;
1329
+ }
1330
+ chatLog('[Chat] the work in the archive answers none of the newest messages, so it is not shown:', {
1331
+ 'Prompt Of The Work': restoredWork.prompt.slice(0, 60),
1332
+ });
1333
+ forgetKeptWork();
1334
+ } catch (error) {
1335
+ chatWarn('[Chat] Could not tell which message the work from the archive answered:', error);
1336
+ }
1337
+ });
1338
+ });
1339
+
1039
1340
  // A new send starts a fresh transcript. An empty thread drops the previous one.
1040
1341
  $effect(() => {
1041
1342
  if (isGenerating && !generationWasRunning) {
1042
- archivedGeneration = null;
1043
1343
  keptGenerationText = '';
1044
1344
  keptThinkingText = '';
1045
1345
  shownGenerationCount = 0;
@@ -1048,26 +1348,16 @@
1048
1348
  thinkingStartedAtMs = Date.now();
1049
1349
  codeStreamingStartedAtMs = null;
1050
1350
  frozenThoughtSeconds = null;
1051
- thinkingExpanded = false;
1052
1351
  generationAriaLine = '';
1053
1352
  lastGenerationAriaKey = '';
1054
1353
  }
1055
1354
  if (!isGenerating && generationWasRunning) {
1056
- if (keptThinkingText.trim() || keptGenerationText.trim()) {
1057
- archivedGeneration = {
1058
- thinking: keptThinkingText,
1059
- code: keptGenerationText,
1060
- thoughtSeconds: frozenThoughtSeconds,
1061
- };
1062
- void saveGenerationArchive(conversationId, archivedGeneration);
1063
- }
1064
1355
  thinkingHold = false;
1065
1356
  shownGenerationCount = keptGenerationText.length;
1066
1357
  thinkingShownCount = $t('chat.messages.thinking').length;
1067
1358
  thinkingStartedAtMs = null;
1068
1359
  codeStreamingStartedAtMs = null;
1069
1360
  frozenThoughtSeconds = null;
1070
- thinkingExpanded = false;
1071
1361
  }
1072
1362
  generationWasRunning = isGenerating;
1073
1363
  });
@@ -1078,6 +1368,7 @@
1078
1368
  if (!isInitialized || isLoading || isGenerating) return;
1079
1369
  if (messages.length === 0) {
1080
1370
  void clearGenerationArchive(conversationId);
1371
+ forgetKeptWork();
1081
1372
  keptGenerationText = '';
1082
1373
  keptThinkingText = '';
1083
1374
  shownGenerationCount = 0;
@@ -1108,23 +1399,72 @@
1108
1399
  generationActivityPhase(isGenerating, keptThinkingText, keptGenerationText),
1109
1400
  );
1110
1401
 
1402
+ /** What the avatar of the live turn looks like and does, and which parts of the work are on screen, for this phase of the run. */
1403
+ const liveLook = $derived(liveAgentLook(activityPhase));
1404
+ const liveModules = $derived(liveModulesView(activityPhase));
1405
+
1406
+ // Said once per change of the look (never on every streamed token)
1407
+ let lastLiveLookSignature = '';
1111
1408
  $effect(() => {
1112
- const key = generationActivityAriaKey(activityPhase) ?? '';
1113
- if (!key || key === lastGenerationAriaKey) return;
1114
- lastGenerationAriaKey = key;
1115
- generationAriaLine = $t(key);
1409
+ if (!thinkingHold || !assistantIsWorking) {
1410
+ lastLiveLookSignature = '';
1411
+ return;
1412
+ }
1413
+ const signature = agentLookSignature(liveLook);
1414
+ if (signature === lastLiveLookSignature) return;
1415
+ lastLiveLookSignature = signature;
1416
+ // What the avatar of the run's ending takes over from (it is read when the run is over, see `lastLiveLook`)
1417
+ lastLiveLook = liveLook;
1418
+ chatLog('[Chat] the assistant, while it works:', { 'Look': signature, 'Phase': activityPhase });
1116
1419
  });
1117
1420
 
1421
+ /**
1422
+ * How the settled avatar of the newest turn looks: the very view the turn draws, so the sound follows what the person sees and
1423
+ * never a state the avatar does not show. Null while that turn has nothing to show (a prompt just sent, a run that ended a
1424
+ * moment before its conclusion arrives).
1425
+ */
1426
+ const newestTurnLook = $derived.by((): AgentLook | null => {
1427
+ for (let turnIndex = chatTurns.length - 1; turnIndex >= 0; turnIndex--) {
1428
+ if (!chatTurns[turnIndex].user) continue;
1429
+ const newestTurnView = assistantViewOf(chatTurns[turnIndex]);
1430
+ return newestTurnView.hasContent ? newestTurnView.look : null;
1431
+ }
1432
+ return null;
1433
+ });
1434
+
1435
+ /** The state of the avatar the person is looking at, for the page's sound, or null when there is nothing to hear (see `soundStateOf`). */
1436
+ const soundState = $derived(
1437
+ soundStateOf({
1438
+ runIsLive: thinkingHold && assistantIsWorking,
1439
+ liveLook,
1440
+ runWasWatched,
1441
+ newestTurnLook,
1442
+ }),
1443
+ );
1444
+
1445
+ // The page's sound is told once for each change of what the person looks at (never on every streamed token): thinking when the
1446
+ // run starts, writing when it writes code or the answer, then how it went. The player decides whether anything sounds.
1118
1447
  $effect(() => {
1119
- if (!isGenerating || !thinkingStreamEl) return;
1120
- const length = keptThinkingText.length;
1121
- if (length === 0) return;
1122
- tick().then(() => {
1123
- if (!thinkingStreamEl) return;
1124
- thinkingStreamEl.scrollTop = thinkingStreamEl.scrollHeight;
1448
+ const announcedState = soundState;
1449
+ if (announcedState === null) return;
1450
+ untrack(() => {
1451
+ if (!agentSound) return;
1452
+ try {
1453
+ chatLog('[Chat] the avatar of the assistant is heard going to:', { 'Sound State': announcedState });
1454
+ agentSound.notifyStateChange(announcedState);
1455
+ } catch (error) {
1456
+ chatWarn('[Chat] The sound of the assistant failed, so it stays silent:', error);
1457
+ }
1125
1458
  });
1126
1459
  });
1127
1460
 
1461
+ $effect(() => {
1462
+ const key = generationActivityAriaKey(activityPhase) ?? '';
1463
+ if (!key || key === lastGenerationAriaKey) return;
1464
+ lastGenerationAriaKey = key;
1465
+ generationAriaLine = $t(key);
1466
+ });
1467
+
1128
1468
  // Reveal from the first character already on screen, then catch up to new tokens.
1129
1469
  $effect(() => {
1130
1470
  const target = keptGenerationText.length;
@@ -1185,6 +1525,43 @@
1185
1525
  requestAnimationFrame(step);
1186
1526
  }
1187
1527
 
1528
+ /**
1529
+ * An action for the part of the list that is still changing: the assistant's turn while it works, and the newest turn once
1530
+ * it has answered. Such a turn changes size under the list: the plan card moves on, the thinking grows inside its module,
1531
+ * the code streams, a module opens, and when the conclusion appears the face glides to its size and the content beside it
1532
+ * wraps again (a card gets taller). The mutation observer below sees nodes come and go, not a text that grows inside a node
1533
+ * or a card that re-wraps, so the end slid out of view. This watches the size of the turn itself and keeps the end in view,
1534
+ * as a generation always has (see `shouldPinChatToBottom`). Only the newest turn is watched (`active`): opening something in
1535
+ * the history must not pull the view away. At most one turn is observed at a time, and the observer is let go when the turn
1536
+ * stops being the newest or leaves.
1537
+ */
1538
+ function keepEndInView(node: HTMLElement, active: boolean = true) {
1539
+ if (typeof ResizeObserver === 'undefined') return;
1540
+ let growthObserver: ResizeObserver | null = null;
1541
+
1542
+ function watchGrowth(shouldWatch: boolean): void {
1543
+ growthObserver?.disconnect();
1544
+ growthObserver = null;
1545
+ if (!shouldWatch) return;
1546
+ growthObserver = new ResizeObserver(() => {
1547
+ if (pendingOlderScroll || !initialBottomPinned) return;
1548
+ if (shouldPinChatToBottom()) scrollMessagesToEnd();
1549
+ });
1550
+ growthObserver.observe(node);
1551
+ }
1552
+
1553
+ watchGrowth(active);
1554
+ return {
1555
+ update(shouldWatch: boolean) {
1556
+ watchGrowth(shouldWatch);
1557
+ },
1558
+ destroy() {
1559
+ growthObserver?.disconnect();
1560
+ growthObserver = null;
1561
+ }
1562
+ };
1563
+ }
1564
+
1188
1565
  // Auto-scroll to bottom when new messages arrive or on initial load.
1189
1566
  // Also scrolls on mount/conversation-switch when messages are already present.
1190
1567
  $effect(() => {
@@ -1201,8 +1578,8 @@
1201
1578
  if (messagesContainer && pinToBottom && (messageCount > 0 || streamLength > 0) && !pendingOlderScroll && initialBottomPinned) {
1202
1579
  tick().then(() => {
1203
1580
  if (!messagesContainer || pendingOlderScroll || !shouldPinChatToBottom()) return;
1581
+ // (The thinking and the code keep their own newest line in view: see GenerationModule.)
1204
1582
  scrollMessagesToEnd();
1205
- if (isGenerating) scrollGenerationTail();
1206
1583
  });
1207
1584
  }
1208
1585
  });
@@ -1625,7 +2002,7 @@
1625
2002
  <!-- Empty state stays out of the document until the parent has finished reading
1626
2003
  messages and found none. A generation in flight hides it too: the user
1627
2004
  bubble lands a tick after send, so the list is briefly empty again. -->
1628
- {#if showEmptyState && !isLoading && !isGenerating}
2005
+ {#if emptyStateVisible && !isLoading && !isGenerating}
1629
2006
  <!-- Figma: Chat / Empty. The hero (a circle with the sparkles icon, the title and a line under it) sits in the
1630
2007
  middle of the messages, and the suggestions are pinned under it, above the composer. The block takes the
1631
2008
  free height with flex-1 (not min-h-full): the sticky scroll-to-bottom row below it needs its own room, and a
@@ -1660,18 +2037,25 @@
1660
2037
  <div class="{panelLayout && chatTurns.length > 0 ? 'mt-auto flex w-full flex-col gap-4' : 'contents'}">
1661
2038
  <!-- Conversation turns (user prompt + assistant status grouped) -->
1662
2039
  {#each chatTurns as turn, turnIndex (turn.user?.id ?? turn.replies[0]?.id ?? turnIndex)}
1663
- <div class="wc-chat-turn-ct rounded-lg {panelLayout ? 'flex flex-col gap-[52px]' : 'space-y-1.5 border border-transparent p-0.5'}">
2040
+ {@const assistant = assistantViewOf(turn)}
2041
+ <div
2042
+ class="wc-chat-turn-ct rounded-lg {panelLayout ? 'flex flex-col gap-[52px]' : 'space-y-1.5 border border-transparent p-0.5'}"
2043
+ use:keepEndInView={turnIndex === chatTurns.length - 1}
2044
+ >
1664
2045
  {#if turn.user}
1665
2046
  {@const userMsg = turn.user}
1666
2047
  {@const shownAttachments = visibleUserAttachments(turn, turnIndex)}
2048
+ {@const author = authorOfMessage(userMsg)}
1667
2049
  <div class="message-container wc-chat-turn-user flex w-full flex-col {panelLayout ? 'items-end' : 'items-stretch'}"
1668
2050
  class:opacity-75={userMsg._optimistic}
1669
2051
  class:opacity-50={userMsg._failed}
1670
2052
  class:has-attachments={shownAttachments.length > 0}
1671
2053
  >
2054
+ <!-- The bubble and, at its end, the face of the person who wrote it (when the page told the chat who is who). -->
2055
+ <div class="wc-chat-turn-user-row flex w-full min-w-0 items-start gap-2" data-bubble-row>
1672
2056
  <Message
1673
2057
  role="user"
1674
- class="{panelLayout ? 'panel-layout-user-message ms-auto w-fit max-w-[85%]' : 'ms-auto w-full max-w-full'}"
2058
+ class="{panelLayout ? 'panel-layout-user-message ms-auto w-fit max-w-[85%]' : 'ms-auto w-full max-w-full'} min-w-0"
1675
2059
  data-testid="chat-user-bubble"
1676
2060
  >
1677
2061
  {#snippet children()}
@@ -1698,7 +2082,8 @@
1698
2082
  {/each}
1699
2083
  </div>
1700
2084
  {:else}
1701
- <p class="wc-chat-text whitespace-pre-wrap [overflow-wrap:anywhere] {panelLayout ? '' : 'p-3'}" dir={dirForUserText($textDirection)}>{@render linkified(userMsg.messageContent)}</p>
2085
+ <!-- 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>
1702
2087
  {/if}
1703
2088
  {/if}
1704
2089
  {#if shownAttachments.length > 0}
@@ -1719,11 +2104,15 @@
1719
2104
  </div>
1720
2105
  {/snippet}
1721
2106
  </Message>
2107
+ {#if author}
2108
+ <MemberAvatar member={author} class="mt-1" />
2109
+ {/if}
2110
+ </div>
1722
2111
  {#if showCommitMetaOnUserTurn(turn) && (!panelLayout || showCommitMeta)}
1723
2112
  {@const commitTitle = getTurnCommitTitle(turn)}
1724
2113
  {@const versionLabel = getTurnVersionLabel(turn)}
1725
2114
  {#if showCommitMeta && commitTitle}
1726
- <div class="wc-user-commit-title-row flex w-full min-w-0 mt-1">
2115
+ <div class="wc-user-commit-title-row flex w-full min-w-0 mt-1 {author ? 'pe-8' : ''}">
1727
2116
  <span class="wc-user-commit-title text-xs text-gray-600" title={commitTitle}>
1728
2117
  {commitTitle}
1729
2118
  </span>
@@ -1733,7 +2122,7 @@
1733
2122
  {@const restoredVersion = restoredVersionFromTurn(turn)}
1734
2123
  {@const headRedoId = turnIsRestoreEcho(turn) ? headCommitRestoreTargetId() : null}
1735
2124
  <MessageCheckpointRow
1736
- class="wc-user-commit-meta-ct mt-1"
2125
+ class="wc-user-commit-meta-ct mt-1 {author ? 'pe-8' : ''}"
1737
2126
  versionLabel={versionLabel && versionNumberFromLabel(versionLabel) !== 1
1738
2127
  ? versionLabelText(versionLabel, $t)
1739
2128
  : showCommitMeta && getTurnCommitShort(turn)
@@ -1755,41 +2144,69 @@
1755
2144
  </div>
1756
2145
  {/if}
1757
2146
 
2147
+ <!-- Everything the assistant said or showed in this turn, with its face: the avatar at the left, the words to its right. After
2148
+ a run that just ended, the thinking and the code it made sit closed above its conclusion. (Not re-indented: the replies
2149
+ below are the same markup that used to sit directly in the turn.) -->
2150
+ {#if assistant.hasContent}
2151
+ <AgentTurn look={assistant.look} startSize={assistant.startSize} startState={assistant.startState} {renderAgentAvatar} class="wc-chat-turn-assistant">
2152
+ {#if assistant.finished}
2153
+ {@const keptModules = finishedModulesView(assistant.finished)}
2154
+ {#if keptModules.showThinking}
2155
+ <GenerationModule kind="thinking" text={assistant.finished.thinking} seconds={assistant.finished.thoughtSeconds} />
2156
+ {/if}
2157
+ {#if keptModules.showCode}
2158
+ <GenerationModule kind="code" text={assistant.finished.code} />
2159
+ {/if}
2160
+ {/if}
1758
2161
  {#each turn.replies as reply (reply.id)}
1759
2162
  {#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))}
1760
2165
  {#if panelLayout && isStoppedByUser(reply)}
1761
2166
  <!-- A stop is the person's own command: one quiet line, not the red "Could not build the widget" card. -->
1762
2167
  <p
1763
- class="wc-chat-turn-reply wc-chat-stopped text-body text-muted-foreground flex items-center gap-2"
2168
+ class="wc-chat-turn-reply wc-chat-stopped text-body text-muted-foreground flex min-h-7 items-center gap-2"
1764
2169
  data-testid="chat-stopped-notice"
1765
2170
  >
1766
2171
  <IconPlayerStop class="size-4 shrink-0 stroke-2" aria-hidden="true" />
1767
2172
  <span>{$t('chat.messages.stoppedByYou')}</span>
1768
2173
  </p>
1769
2174
  {:else if panelLayout && isCodegenFailure(reply)}
1770
- <!-- Figma Alert (526:3205): a failed reply in the docked panel is a card with a title, a line and "Try again",
1771
- not a red line of text. The button runs the prompt of this turn again, on the last failure of the turn only. -->
1772
- <ChatAlertCard
1773
- class="wc-chat-turn-reply"
1774
- title={$t('chat.messages.failedTitle')}
1775
- description={failureAlertDescription(reply)}
1776
- actionLabel={onRetryMessage &&
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). -->
2177
+ {@const canRetryFailure =
2178
+ !!onRetryMessage &&
1777
2179
  isLastCodegenFailureInTurn(turn, reply) &&
1778
2180
  !isPlanLimitMessage(reply.messageContent) &&
1779
- turnNeedsRetry(turn, turnIndex)
1780
- ? $t('chat.messages.failedRetry')
1781
- : ''}
1782
- onAction={() => handleRetryTurn(turn, turnIndex)}
1783
- />
1784
- {:else}
2181
+ turnNeedsRetry(turn, turnIndex)}
2182
+ <div
2183
+ class="wc-chat-turn-reply wc-chat-failed text-body text-destructive flex min-h-7 items-center gap-2"
2184
+ data-testid="chat-failed-notice"
2185
+ >
2186
+ <IconAlertTriangle class="size-4 shrink-0 stroke-2" aria-hidden="true" />
2187
+ <span class="min-w-0 flex-1 [overflow-wrap:anywhere]">{failureLine(reply)}</span>
2188
+ {#if canRetryFailure}
2189
+ <button
2190
+ type="button"
2191
+ class="text-muted-foreground hover:text-foreground hover:bg-muted focus-visible:ring-ring flex size-7 shrink-0 items-center justify-center rounded-md transition-colors focus-visible:ring-2 focus-visible:outline-none"
2192
+ aria-label={$t('chat.messages.failedRetry')}
2193
+ title={$t('chat.messages.failedRetry')}
2194
+ data-testid="chat-failed-retry"
2195
+ onclick={() => handleRetryTurn(turn, turnIndex)}
2196
+ >
2197
+ <IconRefresh class="size-4 stroke-2" aria-hidden="true" />
2198
+ </button>
2199
+ {/if}
2200
+ </div>
2201
+ {:else if replyTextIsShown || isCodegenFailure(reply)}
1785
2202
  <Message
1786
2203
  role="assistant"
1787
- class="wc-chat-turn-reply max-w-full"
2204
+ class="wc-chat-turn-reply mt-0.5 max-w-full"
1788
2205
  error={isCodegenFailure(reply)}
1789
2206
  errorText={visibleMessageContent(reply.messageContent || '')}
1790
2207
  >
1791
2208
  {#snippet children()}
1792
- {#if reply.messageContent && (panelLayout || !(reply.suggestions && reply.suggestions.length > 0))}
2209
+ {#if replyTextIsShown}
1793
2210
  <div class="message-content-assistant select-text text-sm leading-relaxed" use:bubbleScrollPadding>
1794
2211
  {#if reply.messageContent}
1795
2212
  {#if hasCodeBlocks(reply.messageContent)}
@@ -1824,6 +2241,21 @@
1824
2241
  </div>
1825
2242
  {/if}
1826
2243
 
2244
+ {#if reply.suggestions?.some((suggestion) => suggestion.undoSketch) && panelLayout}
2245
+ <div class="mt-2 flex flex-wrap gap-2">
2246
+ {#each reply.suggestions.filter((suggestion) => suggestion.undoSketch) as suggestion (suggestion.label)}
2247
+ <button
2248
+ type="button"
2249
+ data-testid={suggestion.undoSketch ? 'sketch-undo-chip' : undefined}
2250
+ class="border-border bg-muted text-foreground rounded-full border px-3 py-1 text-sm"
2251
+ onclick={() => onClarificationSuggestionSelected?.(suggestion)}
2252
+ >
2253
+ {suggestion.label || $t('chat.sketch.undoLabel')}
2254
+ </button>
2255
+ {/each}
2256
+ </div>
2257
+ {/if}
2258
+
1827
2259
  {#if reply.suggestions && reply.suggestions.length > 0 && !panelLayout}
1828
2260
  <QuestionCard
1829
2261
  class="mt-1.5 w-full max-w-full"
@@ -1855,6 +2287,20 @@
1855
2287
  {/if}
1856
2288
  {/if}
1857
2289
  {/each}
2290
+ {#if assistant.showDoneLine}
2291
+ <!-- The first line of the turn (no thinking or code above it) is as tall as the small avatar, like every first line -->
2292
+ {@const doneLineHasModulesAbove =
2293
+ !!assistant.finished &&
2294
+ (finishedModulesView(assistant.finished).showThinking || finishedModulesView(assistant.finished).showCode)}
2295
+ <p
2296
+ class="text-body text-foreground {doneLineHasModulesAbove ? '' : 'flex min-h-7 items-center'}"
2297
+ data-testid="agent-conclusion"
2298
+ >
2299
+ {$t('chat.generation.doneMessage')}
2300
+ </p>
2301
+ {/if}
2302
+ </AgentTurn>
2303
+ {/if}
1858
2304
 
1859
2305
  <!-- Copy, regenerate and the two thumbs: at the end of the last message only, and not while something is being generated.
1860
2306
  Not in the panel either: the creator page's chat panel (Figma 526:2706, ready) draws no row of actions under the last message. -->
@@ -1879,35 +2325,55 @@
1879
2325
  </div>
1880
2326
  {/each}
1881
2327
 
1882
- {#if panelLayout && archivedGeneration && !isGenerating && !thinkingHold}
1883
- <div
1884
- class="generation-archive-card w-full max-w-full rounded-lg border border-border bg-muted/40 p-3 text-sm"
1885
- data-testid="generation-archive"
1886
- >
1887
- {#if archivedGeneration.thinking.trim()}
1888
- <button
1889
- type="button"
1890
- class="text-muted-foreground hover:text-foreground mb-2 flex w-full items-center gap-2 text-start text-xs underline-offset-2 hover:underline"
1891
- aria-expanded={thinkingExpanded}
1892
- onclick={() => { thinkingExpanded = !thinkingExpanded; }}
1893
- >
1894
- <span>
1895
- {#if archivedGeneration.thoughtSeconds != null}
1896
- {$t('chat.generation.thoughtFor', { seconds: String(archivedGeneration.thoughtSeconds) })}
1897
- {:else}
1898
- {$t('chat.generation.thinking')}
1899
- {/if}
1900
- </span>
1901
- </button>
1902
- {#if thinkingExpanded}
1903
- <div class="text-muted-foreground mb-2 max-h-24 overflow-auto whitespace-pre-wrap break-words text-xs">
1904
- {archivedGeneration.thinking}
2328
+ <!-- The assistant while it works: its face (large while it waits, small once its thoughts or its code stream) and, to its
2329
+ right, the parts of its work one under the other, each with its own words: the plan, "Thinking…", "Writing code…". When it is done the face is
2330
+ drawn again under the turn it answered, grown into the conclusion. The offset keeps the face where that turn will put it
2331
+ (the turn spaces its reply closer than the list spaces a turn from the next). -->
2332
+ {#if thinkingHold && assistantIsWorking}
2333
+ <!-- (The wrapper is what the list sees grow: keepEndInView keeps the end of the list in view while the turn changes size.) -->
2334
+ <div class="loading-indicator-ct {panelLayout ? 'mt-9 pb-3' : '-mt-3'}" use:keepEndInView>
2335
+ <AgentTurn look={liveLook} {renderAgentAvatar}>
2336
+ {#if planCardView}
2337
+ <PlanCard
2338
+ class="w-full"
2339
+ dir="auto"
2340
+ role="region"
2341
+ aria-label={$t('chat.plan.regionLabel')}
2342
+ title={planCardView.title}
2343
+ tasks={planCardView.tasks}
2344
+ progressCurrent={planCardView.progressCurrent}
2345
+ progressTotal={planCardView.progressTotal}
2346
+ visibleTaskCount={4}
2347
+ messages={planCardMessages}
2348
+ />
2349
+ {/if}
2350
+ {#if liveModules.showShimmer}
2351
+ <div class="thinking-bubble relative flex min-h-7 w-fit items-center whitespace-nowrap text-sm">
2352
+ <span class="thinking-sizer" aria-hidden="true">{thinkingLabel}</span>
2353
+ <span class="thinking-reveal absolute inset-0 flex items-center">{shownThinkingLabel}</span>
1905
2354
  </div>
1906
2355
  {/if}
1907
- {/if}
1908
- {#if archivedGeneration.code.trim()}
1909
- <CodeBlock code={archivedGeneration.code} language="typescript" />
1910
- {/if}
2356
+ {#if liveModules.showThinking}
2357
+ <GenerationModule
2358
+ kind="thinking"
2359
+ text={keptThinkingText}
2360
+ streaming={liveModules.thinkingStreaming}
2361
+ seconds={frozenThoughtSeconds}
2362
+ openByDefault={liveModules.thinkingOpenByDefault}
2363
+ />
2364
+ {/if}
2365
+ {#if liveModules.showCode && shownGenerationText}
2366
+ <GenerationModule
2367
+ kind="code"
2368
+ text={shownGenerationText}
2369
+ streaming={liveModules.codeStreaming}
2370
+ openByDefault={liveModules.codeOpenByDefault}
2371
+ />
2372
+ {/if}
2373
+ {#if generationAriaLine}
2374
+ <p class="sr-only" aria-live="polite">{generationAriaLine}</p>
2375
+ {/if}
2376
+ </AgentTurn>
1911
2377
  </div>
1912
2378
  {/if}
1913
2379
  </div>
@@ -1922,87 +2388,6 @@
1922
2388
  </div>
1923
2389
  </div>
1924
2390
  {/if}
1925
- {#if thinkingHold}
1926
- <div class="loading-indicator-ct flex flex-col items-start gap-2 p-3">
1927
- {#if planCardView}
1928
- <PlanCard
1929
- class="w-full"
1930
- dir="auto"
1931
- role="region"
1932
- aria-label={$t('chat.plan.regionLabel')}
1933
- title={planCardView.title}
1934
- tasks={planCardView.tasks}
1935
- progressCurrent={planCardView.progressCurrent}
1936
- progressTotal={planCardView.progressTotal}
1937
- visibleTaskCount={4}
1938
- messages={planCardMessages}
1939
- />
1940
- {/if}
1941
- <ActivityRow
1942
- class="w-full"
1943
- label={shownThinkingLabel || $t('chat.generation.thinking')}
1944
- status={activityPhase === 'code-only' || activityPhase === 'thinking-and-code' ? 'running' : 'pending'}
1945
- />
1946
- <div
1947
- class="generation-activity-card w-full max-w-full rounded-lg p-3 text-sm leading-relaxed shadow-sm"
1948
- style="background-color: {MESSAGE_COLORS.ASSISTANT}; color: {MESSAGE_COLORS.ASSISTANT_TEXT}"
1949
- >
1950
- {#if activityPhase === 'shimmer-only'}
1951
- <div class="thinking-bubble relative inline-block whitespace-nowrap">
1952
- <span class="thinking-sizer" aria-hidden="true">{thinkingLabel}</span>
1953
- <span class="thinking-reveal absolute inset-0 flex items-center">{shownThinkingLabel}</span>
1954
- </div>
1955
- {:else}
1956
- {#if activityPhase === 'thinking-stream'}
1957
- <div class="mb-2 flex items-center gap-2 font-medium">
1958
- <div class="h-4 w-4 shrink-0 rounded-full border-2 border-gray-400 border-t-transparent animate-spin" aria-hidden="true"></div>
1959
- <span class="thinking-reveal-inline">{$t('chat.generation.thinking')}</span>
1960
- </div>
1961
- <div
1962
- bind:this={thinkingStreamEl}
1963
- class="generation-thinking-stream max-h-32 w-full overflow-auto whitespace-pre-wrap break-words text-xs text-gray-600"
1964
- dir="auto"
1965
- >{keptThinkingText}</div>
1966
- {:else if activityPhase === 'thinking-and-code' || activityPhase === 'code-only'}
1967
- {#if keptThinkingText.trim().length > 0}
1968
- <button
1969
- type="button"
1970
- class="thought-summary-btn mb-2 flex w-full items-center gap-2 text-start text-xs text-gray-600 underline-offset-2 hover:underline"
1971
- aria-expanded={thinkingExpanded}
1972
- onclick={() => { thinkingExpanded = !thinkingExpanded; }}
1973
- >
1974
- <span>
1975
- {#if frozenThoughtSeconds != null}
1976
- {$t('chat.generation.thoughtFor', { seconds: String(frozenThoughtSeconds) })}
1977
- {:else}
1978
- {$t('chat.generation.thinking')}
1979
- {/if}
1980
- </span>
1981
- <span class="sr-only">
1982
- {thinkingExpanded ? $t('chat.generation.collapseThought') : $t('chat.generation.expandThought')}
1983
- </span>
1984
- </button>
1985
- {#if thinkingExpanded}
1986
- <div
1987
- class="generation-thinking-stream mb-2 max-h-24 w-full overflow-auto whitespace-pre-wrap break-words text-xs text-gray-600"
1988
- dir="auto"
1989
- >{keptThinkingText}</div>
1990
- {/if}
1991
- {/if}
1992
- {#if shownGenerationText}
1993
- <div class="mb-1 text-xs font-medium text-gray-800">
1994
- <span>{$t('chat.generation.writingCode')}</span>
1995
- </div>
1996
- <pre class="generation-stream m-0 max-h-40 w-full overflow-auto whitespace-pre-wrap break-words rounded-lg bg-gray-900 p-3 font-mono text-[11px] leading-relaxed text-gray-100" dir="ltr">{shownGenerationText}</pre>
1997
- {/if}
1998
- {/if}
1999
- {/if}
2000
- </div>
2001
- {#if generationAriaLine}
2002
- <p class="sr-only" aria-live="polite">{generationAriaLine}</p>
2003
- {/if}
2004
- </div>
2005
- {/if}
2006
2391
 
2007
2392
  {#if !autoScroll && messages.length > 0 && !isLoading}
2008
2393
  <div class="sticky bottom-2 z-10 flex justify-center pb-1 pt-2 pointer-events-none [&_button]:pointer-events-auto">
@@ -2051,38 +2436,13 @@
2051
2436
  0% { background-position: 100% 0; }
2052
2437
  100% { background-position: -100% 0; }
2053
2438
  }
2054
- .thinking-reveal-inline {
2055
- background-image: linear-gradient(100deg, #1f2937 35%, #ffffff 50%, #1f2937 65%);
2056
- background-size: 200% 100%;
2057
- -webkit-background-clip: text;
2058
- background-clip: text;
2059
- color: transparent;
2060
- animation: thinking-shine 1.6s linear infinite;
2061
- }
2062
2439
  @media (prefers-reduced-motion: reduce) {
2063
- .thinking-reveal,
2064
- .thinking-reveal-inline {
2440
+ .thinking-reveal {
2065
2441
  animation: none;
2066
2442
  color: inherit;
2067
2443
  background-image: none;
2068
2444
  }
2069
2445
  }
2070
- .generation-stream {
2071
- scrollbar-width: thin;
2072
- scrollbar-color: rgba(255, 255, 255, 0.35) transparent;
2073
- }
2074
- .generation-stream::-webkit-scrollbar {
2075
- width: 8px;
2076
- height: 8px;
2077
- background: transparent;
2078
- }
2079
- .generation-stream::-webkit-scrollbar-track {
2080
- background: transparent;
2081
- }
2082
- .generation-stream::-webkit-scrollbar-thumb {
2083
- background: rgba(255, 255, 255, 0.35);
2084
- border-radius: 4px;
2085
- }
2086
2446
  .loading {
2087
2447
  opacity: 0.75;
2088
2448
  }