@widgetic/chat 0.1.39 → 0.1.40

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 (43) hide show
  1. package/README.md +71 -0
  2. package/dist/components/Chat.svelte +35 -1
  3. package/dist/components/Chat.svelte.d.ts +29 -0
  4. package/dist/components/ChatComposer.svelte +5 -1
  5. package/dist/components/ChatMessages.svelte +545 -210
  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/messages.d.ts +31 -9
  22. package/dist/i18n/messages.js +31 -9
  23. package/dist/types/agent.d.ts +74 -0
  24. package/dist/types/agent.js +1 -0
  25. package/dist/types/index.d.ts +1 -0
  26. package/dist/types/index.js +2 -0
  27. package/dist/utils/agentTurn.d.ts +219 -0
  28. package/dist/utils/agentTurn.js +301 -0
  29. package/dist/utils/bubbleFit.d.ts +75 -0
  30. package/dist/utils/bubbleFit.js +116 -0
  31. package/dist/utils/bubbleShrinkWrap.d.ts +32 -0
  32. package/dist/utils/bubbleShrinkWrap.js +360 -0
  33. package/dist/utils/codeHighlight.d.ts +13 -0
  34. package/dist/utils/codeHighlight.js +61 -0
  35. package/dist/utils/codePrettier.d.ts +6 -0
  36. package/dist/utils/codePrettier.js +34 -0
  37. package/dist/utils/codeStreamFormat.d.ts +90 -0
  38. package/dist/utils/codeStreamFormat.js +429 -0
  39. package/dist/utils/generationArchiveStore.d.ts +5 -0
  40. package/dist/utils/generationArchiveStore.js +1 -0
  41. package/dist/utils/index.d.ts +2 -0
  42. package/dist/utils/index.js +3 -0
  43. 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);
@@ -891,6 +939,108 @@
891
939
  );
892
940
  });
893
941
 
942
+ // --- the faces: the assistant's avatar on its turn, and the people's next to what they wrote --------------------------
943
+
944
+ /** Whether the page said who is who: without it no face is drawn next to what people wrote. */
945
+ const peopleAreNamed = $derived(pageNamesPeople(members, currentUser));
946
+
947
+ /** The person who wrote a message, or null when nobody can be named (no face is better than a wrong one). */
948
+ function authorOfMessage(message: ChatMessage): ChatMember | null {
949
+ if (!peopleAreNamed) return null;
950
+ return resolveChatMember(message.userId, members, currentUser);
951
+ }
952
+
953
+ // An author the page did not name is said once per author, not on every redraw
954
+ const unnamedAuthorIdsSaid = new Set<string>();
955
+ $effect(() => {
956
+ if (!peopleAreNamed) return;
957
+ for (const message of messages) {
958
+ if (message.messageType !== 'user') continue;
959
+ const authorId = message.userId;
960
+ if (unnamedAuthorIdsSaid.has(authorId) || resolveChatMember(authorId, members, currentUser)) continue;
961
+ unnamedAuthorIdsSaid.add(authorId);
962
+ chatWarn('[Chat] No member of the team matches the author of a message, so it has no face:', authorId);
963
+ }
964
+ });
965
+
966
+ /** What the assistant looks like and shows in one turn. */
967
+ type TurnAssistantView = {
968
+ /** Anything to draw for the assistant in this turn: a reply to show, or a run that just ended for it. */
969
+ hasContent: boolean;
970
+ look: AgentLook;
971
+ /**
972
+ * 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
973
+ * 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).
974
+ */
975
+ startSize: AgentAvatarSize | undefined;
976
+ /** 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. */
977
+ startState: AgentAvatarState | undefined;
978
+ /** What the assistant did in the run that just ended for this turn: the modules under its conclusion. */
979
+ finished: FinishedGeneration | null;
980
+ /** It built something and the chat shows no message about it: the catalog's "done" line is its conclusion. */
981
+ showDoneLine: boolean;
982
+ };
983
+
984
+ const NO_ASSISTANT_VIEW: TurnAssistantView = {
985
+ hasContent: false,
986
+ look: { state: 'idle', size: 'small', live: false },
987
+ startSize: undefined,
988
+ startState: undefined,
989
+ finished: null,
990
+ showDoneLine: false,
991
+ };
992
+
993
+ /** What the chat found out about one reply, in the terms the turn's outcome is judged by (the rules live in `agentTurn.ts`). */
994
+ function replyFactsOf(reply: ChatMessage): TurnReplyFacts {
995
+ return {
996
+ isFailure: isCodegenFailure(reply),
997
+ isStopped: isStoppedByUser(reply),
998
+ // In the panel the suggestions are the cards above the composer, not a card in the turn
999
+ hasQuestion: !panelLayout && (reply.suggestions?.length ?? 0) > 0,
1000
+ hasCommit: messageHasCommit(reply) && !isCodegenFailure(reply),
1001
+ isCompletion: /^Code generation completed/i.test((reply.messageContent || '').trim()),
1002
+ };
1003
+ }
1004
+
1005
+ /**
1006
+ * The assistant of one turn: its avatar's look, and what it shows besides its replies. Only the newest turn moves, and only
1007
+ * what just ended in front of the person (a run, a failure, a card to answer) is large: the rest is small and still.
1008
+ */
1009
+ function assistantViewOf(turn: ChatTurn): TurnAssistantView {
1010
+ const visibleReplies = turn.replies.filter(shouldShowAssistantReply);
1011
+ const isNewestTurn = isLastUserTurn(turn);
1012
+ const keptWork = finishedGeneration;
1013
+ // 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
1014
+ // the work answered: the chat adds that message before the host has saved it and started the run, and until then the new
1015
+ // turn is not the work's, which the message the work answered tells.
1016
+ const finished =
1017
+ isNewestTurn &&
1018
+ finishedGenerationBelongsTo(keptWork, turn.user?.messageContent) &&
1019
+ !keptWorkIsOutdated(keptForUserMessageId, messages)
1020
+ ? keptWork
1021
+ : null;
1022
+ const outcome = turnOutcome(visibleReplies.map(replyFactsOf), finished !== null);
1023
+ if (outcome === null) return NO_ASSISTANT_VIEW;
1024
+ // A success the person did not just watch (the conversation was loaded, or a debug line says so) is not celebrated
1025
+ const shownOutcome = outcome === 'success' && finished === null ? 'answer' : outcome;
1026
+ // 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
1027
+ // stop in the same tick the run ends (the creator adds the message, then clears isGenerating), so the avatar that appears in
1028
+ // 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
1029
+ // and starts from how that one looked: a Stop pressed while the avatar is still large shrinks it down to its small size, the
1030
+ // conclusion grows out of the small avatar of the work.
1031
+ const runIsEnding = thinkingHold && !assistantIsWorking;
1032
+ const takesOverFromLiveAvatar = finished !== null || (isNewestTurn && runIsEnding);
1033
+ const avatarStart = takesOverFromLiveAvatar ? avatarStartAfter(lastLiveLook) : null;
1034
+ return {
1035
+ hasContent: true,
1036
+ look: settledAgentLook(shownOutcome, isNewestTurn),
1037
+ startSize: avatarStart?.startSize,
1038
+ startState: avatarStart?.startState,
1039
+ finished,
1040
+ showDoneLine: finished !== null && outcome === 'success' && visibleReplies.length === 0,
1041
+ };
1042
+ }
1043
+
894
1044
  /** One entry per turn, in the order of `chatTurns`. */
895
1045
  const restorePoints = $derived(chatTurns.map(restorePointOf));
896
1046
 
@@ -903,13 +1053,6 @@
903
1053
  return autoScroll;
904
1054
  }
905
1055
 
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
1056
  function messageImpliesAttachedFile(content: string): boolean {
914
1057
  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
1058
  content,
@@ -930,14 +1073,14 @@
930
1073
  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
1074
  }
932
1075
 
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 {
1076
+ /** What the line of a failed reply says: the server's own words when they tell something specific (the plan or the credits,
1077
+ * too many requests, the service is unavailable, the run was stopped), otherwise the short "Could not build the widget". */
1078
+ function failureLine(message: ChatMessage): string {
936
1079
  const serverText = visibleMessageContent(message.messageContent || '').trim();
937
1080
  const isSpecificFailure =
938
1081
  isPlanLimitMessage(message.messageContent) ||
939
1082
  /Too many generation requests|temporarily unavailable|Generation stopped/i.test(serverText);
940
- return isSpecificFailure && serverText ? serverText : $t('chat.messages.failedHint');
1083
+ return isSpecificFailure && serverText ? serverText : $t('chat.messages.failedTitle');
941
1084
  }
942
1085
 
943
1086
  function openUpgradePlans() {
@@ -985,27 +1128,11 @@
985
1128
  let thinkingHold = $state(false);
986
1129
  let generationWasRunning = false;
987
1130
  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
1131
  let thinkingStartedAtMs = $state<number | null>(null);
1003
1132
  let codeStreamingStartedAtMs = $state<number | null>(null);
1004
1133
  let frozenThoughtSeconds = $state<number | null>(null);
1005
- let thinkingExpanded = $state(false);
1006
1134
  let generationAriaLine = $state('');
1007
1135
  let lastGenerationAriaKey = '';
1008
- let thinkingStreamEl = $state<HTMLDivElement | null>(null);
1009
1136
 
1010
1137
  const planCardView = $derived(
1011
1138
  isGenerating && generationPlan
@@ -1036,10 +1163,173 @@
1036
1163
  return previous + '\n' + incoming;
1037
1164
  }
1038
1165
 
1166
+ // --- what the assistant did, kept for its conclusion -------------------------------------------------------------
1167
+
1168
+ /**
1169
+ * True only while the assistant really works. The chat raises `isGenerating` while the history loads as well (that locks the
1170
+ * composer), but loading is no work of the assistant: no avatar thinks for it, and nothing is kept from it.
1171
+ */
1172
+ const assistantIsWorking = $derived(isGenerating && !isLoading);
1173
+
1174
+ /**
1175
+ * The thinking and the code of the generation that just ended: the modules under its conclusion show them, closed, for the
1176
+ * person to open. For the newest turn only. The host saves neither, so this browser keeps them (see the archive below) and
1177
+ * they come back after a reload, found again by the words of the prompt they answered.
1178
+ */
1179
+ let finishedGeneration = $state<FinishedGeneration | null>(null);
1180
+
1181
+ /**
1182
+ * 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
1183
+ * are the same (see `keptWorkIsOutdated`). It is set together with `finishedGeneration`, which is what makes the turns draw
1184
+ * 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
1185
+ * until the history is there and the message with those words is found (see `restoredWorkAwaitsItsMessage`).
1186
+ */
1187
+ let keptForUserMessageId: string | null = null;
1188
+
1189
+ /** Work came back from the archive and has not been told yet which message it answered (the history may not be there yet). */
1190
+ let restoredWorkAwaitsItsMessage = false;
1191
+
1192
+ /** The work of the last run is not the newest work any more (a new run, another conversation, an empty thread). */
1193
+ function forgetKeptWork(): void {
1194
+ finishedGeneration = null;
1195
+ keptForUserMessageId = null;
1196
+ restoredWorkAwaitsItsMessage = false;
1197
+ }
1198
+
1199
+ /**
1200
+ * 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
1201
+ * (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
1202
+ * not state: a change of look has no reason to draw the list again.
1203
+ */
1204
+ let lastLiveLook: AgentLook | null = null;
1205
+
1206
+ /**
1207
+ * A run worked while this conversation was open here: the person saw it happen. The sound of the avatar follows only what the
1208
+ * person saw, so a conversation that is merely opened (whose newest turn may well have ended in an error) stays silent until a run
1209
+ * works in it (see `soundStateOf`). State, because what the sound is told is worked out from it.
1210
+ */
1211
+ let runWasWatched = $state(false);
1212
+
1213
+ /** The newest message the person sent: the turn the run that just ended belongs to. */
1214
+ function newestUserMessage(): ChatMessage | null {
1215
+ for (let messageIndex = messages.length - 1; messageIndex >= 0; messageIndex--) {
1216
+ if (messages[messageIndex].messageType === 'user') return messages[messageIndex];
1217
+ }
1218
+ return null;
1219
+ }
1220
+
1221
+ let assistantWasWorking = false;
1222
+ // 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
1223
+ // in the order they are written, so this one stays above it (a test of the chat guards the order).
1224
+ $effect(() => {
1225
+ const working = assistantIsWorking;
1226
+ if (working === assistantWasWorking) return;
1227
+ assistantWasWorking = working;
1228
+ // Only the start and the end of a run get here; what is read below is not what makes this run again
1229
+ untrack(() => {
1230
+ try {
1231
+ if (working) {
1232
+ // 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
1233
+ forgetKeptWork();
1234
+ lastLiveLook = null;
1235
+ runWasWatched = true;
1236
+ return;
1237
+ }
1238
+ const keptThinking = keptThinkingText;
1239
+ const keptCode = keptGenerationText;
1240
+ const keptThoughtSeconds =
1241
+ frozenThoughtSeconds ??
1242
+ (keptThinking.trim().length > 0 ? thoughtDurationSeconds(thinkingStartedAtMs, Date.now()) : null);
1243
+ const answeredMessage = newestUserMessage();
1244
+ finishedGeneration = keepFinishedGeneration({
1245
+ promptText: answeredMessage?.messageContent,
1246
+ thinking: keptThinking,
1247
+ code: keptCode,
1248
+ thoughtSeconds: keptThoughtSeconds,
1249
+ });
1250
+ // Said with the work, so that a prompt sent after it (even with the same words) is not taken for the one it answered
1251
+ keptForUserMessageId = finishedGeneration ? (answeredMessage?.id ?? null) : null;
1252
+ chatLog('[Chat] the assistant finished, kept for its conclusion:', {
1253
+ 'Thinking Characters Kept': finishedGeneration?.thinking.length ?? 0,
1254
+ 'Code Characters Kept': finishedGeneration?.code.length ?? 0,
1255
+ 'Thought Seconds': keptThoughtSeconds,
1256
+ });
1257
+ // Also in this browser (by conversation), so a reload of the page brings the same modules back under the conclusion
1258
+ if (finishedGeneration) void saveGenerationArchive(conversationId, finishedGeneration);
1259
+ } catch (error) {
1260
+ chatWarn('[Chat] Could not keep what the assistant did for its conclusion:', error);
1261
+ forgetKeptWork();
1262
+ }
1263
+ });
1264
+ });
1265
+
1266
+ // After a reload, or when a conversation is opened, the work of its last run comes back from what this browser kept, so the
1267
+ // newest turn shows its thinking and its code again. Only the id of the conversation makes this run again.
1268
+ let archiveConversationId: string | null = null;
1269
+ $effect(() => {
1270
+ const archiveKey = conversationId?.trim() || null;
1271
+ untrack(() => {
1272
+ const previousKey = archiveConversationId;
1273
+ archiveConversationId = archiveKey;
1274
+ // Another conversation (or none) is open: nothing in it was watched yet. Not while a run works at this very moment: the first
1275
+ // message of a new chat makes its conversation, and the run it starts is the one the person is watching.
1276
+ if (previousKey !== archiveKey && !assistantIsWorking) runWasWatched = false;
1277
+ if (!archiveKey) return;
1278
+ // Another conversation was opened: what was kept for the one before is not this one's work
1279
+ if (previousKey && previousKey !== archiveKey) forgetKeptWork();
1280
+ void loadGenerationArchive(archiveKey)
1281
+ .then((record) => {
1282
+ // A run that began or ended while the archive was read keeps what it has, and so does a conversation that changed meanwhile
1283
+ if (!record || assistantIsWorking || finishedGeneration || archiveConversationId !== archiveKey) return;
1284
+ finishedGeneration = keepFinishedGeneration({
1285
+ promptText: record.prompt,
1286
+ thinking: record.thinking,
1287
+ code: record.code,
1288
+ thoughtSeconds: record.thoughtSeconds,
1289
+ });
1290
+ // The archive knows the words of the prompt and nothing else: they find the turn again, and the effect below tells the
1291
+ // work which message that is as soon as the history is there
1292
+ keptForUserMessageId = null;
1293
+ restoredWorkAwaitsItsMessage = finishedGeneration !== null;
1294
+ chatLog('[Chat] the work of the last run came back from the archive:', {
1295
+ 'Thinking Characters': finishedGeneration?.thinking.length ?? 0,
1296
+ 'Code Characters': finishedGeneration?.code.length ?? 0,
1297
+ });
1298
+ })
1299
+ .catch((error) => chatWarn('[Chat] Could not read the archive of the last run:', error));
1300
+ });
1301
+ });
1302
+
1303
+ // The work that came back from the archive is told which message of the person it answered: the newest one with its words, once
1304
+ // 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
1305
+ // reload). Work that answers none of the newest messages (the run it came from is not the newest turn) has no turn to show
1306
+ // under, and must not be taken for the work of a later prompt that happens to have the same words, so it goes.
1307
+ $effect(() => {
1308
+ const restoredWork = finishedGeneration;
1309
+ const historyIsThere = isInitialized && !isLoading && messages.length > 0;
1310
+ if (!restoredWork || !historyIsThere || assistantIsWorking) return;
1311
+ untrack(() => {
1312
+ if (!restoredWorkAwaitsItsMessage) return;
1313
+ restoredWorkAwaitsItsMessage = false;
1314
+ try {
1315
+ const newestMessage = newestUserMessage();
1316
+ if (newestMessage && finishedGenerationBelongsTo(restoredWork, newestMessage.messageContent)) {
1317
+ keptForUserMessageId = newestMessage.id;
1318
+ return;
1319
+ }
1320
+ chatLog('[Chat] the work in the archive answers none of the newest messages, so it is not shown:', {
1321
+ 'Prompt Of The Work': restoredWork.prompt.slice(0, 60),
1322
+ });
1323
+ forgetKeptWork();
1324
+ } catch (error) {
1325
+ chatWarn('[Chat] Could not tell which message the work from the archive answered:', error);
1326
+ }
1327
+ });
1328
+ });
1329
+
1039
1330
  // A new send starts a fresh transcript. An empty thread drops the previous one.
1040
1331
  $effect(() => {
1041
1332
  if (isGenerating && !generationWasRunning) {
1042
- archivedGeneration = null;
1043
1333
  keptGenerationText = '';
1044
1334
  keptThinkingText = '';
1045
1335
  shownGenerationCount = 0;
@@ -1048,26 +1338,16 @@
1048
1338
  thinkingStartedAtMs = Date.now();
1049
1339
  codeStreamingStartedAtMs = null;
1050
1340
  frozenThoughtSeconds = null;
1051
- thinkingExpanded = false;
1052
1341
  generationAriaLine = '';
1053
1342
  lastGenerationAriaKey = '';
1054
1343
  }
1055
1344
  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
1345
  thinkingHold = false;
1065
1346
  shownGenerationCount = keptGenerationText.length;
1066
1347
  thinkingShownCount = $t('chat.messages.thinking').length;
1067
1348
  thinkingStartedAtMs = null;
1068
1349
  codeStreamingStartedAtMs = null;
1069
1350
  frozenThoughtSeconds = null;
1070
- thinkingExpanded = false;
1071
1351
  }
1072
1352
  generationWasRunning = isGenerating;
1073
1353
  });
@@ -1078,6 +1358,7 @@
1078
1358
  if (!isInitialized || isLoading || isGenerating) return;
1079
1359
  if (messages.length === 0) {
1080
1360
  void clearGenerationArchive(conversationId);
1361
+ forgetKeptWork();
1081
1362
  keptGenerationText = '';
1082
1363
  keptThinkingText = '';
1083
1364
  shownGenerationCount = 0;
@@ -1108,23 +1389,72 @@
1108
1389
  generationActivityPhase(isGenerating, keptThinkingText, keptGenerationText),
1109
1390
  );
1110
1391
 
1392
+ /** 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. */
1393
+ const liveLook = $derived(liveAgentLook(activityPhase));
1394
+ const liveModules = $derived(liveModulesView(activityPhase));
1395
+
1396
+ // Said once per change of the look (never on every streamed token)
1397
+ let lastLiveLookSignature = '';
1111
1398
  $effect(() => {
1112
- const key = generationActivityAriaKey(activityPhase) ?? '';
1113
- if (!key || key === lastGenerationAriaKey) return;
1114
- lastGenerationAriaKey = key;
1115
- generationAriaLine = $t(key);
1399
+ if (!thinkingHold || !assistantIsWorking) {
1400
+ lastLiveLookSignature = '';
1401
+ return;
1402
+ }
1403
+ const signature = agentLookSignature(liveLook);
1404
+ if (signature === lastLiveLookSignature) return;
1405
+ lastLiveLookSignature = signature;
1406
+ // What the avatar of the run's ending takes over from (it is read when the run is over, see `lastLiveLook`)
1407
+ lastLiveLook = liveLook;
1408
+ chatLog('[Chat] the assistant, while it works:', { 'Look': signature, 'Phase': activityPhase });
1116
1409
  });
1117
1410
 
1411
+ /**
1412
+ * How the settled avatar of the newest turn looks: the very view the turn draws, so the sound follows what the person sees and
1413
+ * 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
1414
+ * moment before its conclusion arrives).
1415
+ */
1416
+ const newestTurnLook = $derived.by((): AgentLook | null => {
1417
+ for (let turnIndex = chatTurns.length - 1; turnIndex >= 0; turnIndex--) {
1418
+ if (!chatTurns[turnIndex].user) continue;
1419
+ const newestTurnView = assistantViewOf(chatTurns[turnIndex]);
1420
+ return newestTurnView.hasContent ? newestTurnView.look : null;
1421
+ }
1422
+ return null;
1423
+ });
1424
+
1425
+ /** 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`). */
1426
+ const soundState = $derived(
1427
+ soundStateOf({
1428
+ runIsLive: thinkingHold && assistantIsWorking,
1429
+ liveLook,
1430
+ runWasWatched,
1431
+ newestTurnLook,
1432
+ }),
1433
+ );
1434
+
1435
+ // The page's sound is told once for each change of what the person looks at (never on every streamed token): thinking when the
1436
+ // run starts, writing when it writes code or the answer, then how it went. The player decides whether anything sounds.
1118
1437
  $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;
1438
+ const announcedState = soundState;
1439
+ if (announcedState === null) return;
1440
+ untrack(() => {
1441
+ if (!agentSound) return;
1442
+ try {
1443
+ chatLog('[Chat] the avatar of the assistant is heard going to:', { 'Sound State': announcedState });
1444
+ agentSound.notifyStateChange(announcedState);
1445
+ } catch (error) {
1446
+ chatWarn('[Chat] The sound of the assistant failed, so it stays silent:', error);
1447
+ }
1125
1448
  });
1126
1449
  });
1127
1450
 
1451
+ $effect(() => {
1452
+ const key = generationActivityAriaKey(activityPhase) ?? '';
1453
+ if (!key || key === lastGenerationAriaKey) return;
1454
+ lastGenerationAriaKey = key;
1455
+ generationAriaLine = $t(key);
1456
+ });
1457
+
1128
1458
  // Reveal from the first character already on screen, then catch up to new tokens.
1129
1459
  $effect(() => {
1130
1460
  const target = keptGenerationText.length;
@@ -1185,6 +1515,43 @@
1185
1515
  requestAnimationFrame(step);
1186
1516
  }
1187
1517
 
1518
+ /**
1519
+ * An action for the part of the list that is still changing: the assistant's turn while it works, and the newest turn once
1520
+ * it has answered. Such a turn changes size under the list: the plan card moves on, the thinking grows inside its module,
1521
+ * the code streams, a module opens, and when the conclusion appears the face glides to its size and the content beside it
1522
+ * wraps again (a card gets taller). The mutation observer below sees nodes come and go, not a text that grows inside a node
1523
+ * 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,
1524
+ * as a generation always has (see `shouldPinChatToBottom`). Only the newest turn is watched (`active`): opening something in
1525
+ * 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
1526
+ * stops being the newest or leaves.
1527
+ */
1528
+ function keepEndInView(node: HTMLElement, active: boolean = true) {
1529
+ if (typeof ResizeObserver === 'undefined') return;
1530
+ let growthObserver: ResizeObserver | null = null;
1531
+
1532
+ function watchGrowth(shouldWatch: boolean): void {
1533
+ growthObserver?.disconnect();
1534
+ growthObserver = null;
1535
+ if (!shouldWatch) return;
1536
+ growthObserver = new ResizeObserver(() => {
1537
+ if (pendingOlderScroll || !initialBottomPinned) return;
1538
+ if (shouldPinChatToBottom()) scrollMessagesToEnd();
1539
+ });
1540
+ growthObserver.observe(node);
1541
+ }
1542
+
1543
+ watchGrowth(active);
1544
+ return {
1545
+ update(shouldWatch: boolean) {
1546
+ watchGrowth(shouldWatch);
1547
+ },
1548
+ destroy() {
1549
+ growthObserver?.disconnect();
1550
+ growthObserver = null;
1551
+ }
1552
+ };
1553
+ }
1554
+
1188
1555
  // Auto-scroll to bottom when new messages arrive or on initial load.
1189
1556
  // Also scrolls on mount/conversation-switch when messages are already present.
1190
1557
  $effect(() => {
@@ -1201,8 +1568,8 @@
1201
1568
  if (messagesContainer && pinToBottom && (messageCount > 0 || streamLength > 0) && !pendingOlderScroll && initialBottomPinned) {
1202
1569
  tick().then(() => {
1203
1570
  if (!messagesContainer || pendingOlderScroll || !shouldPinChatToBottom()) return;
1571
+ // (The thinking and the code keep their own newest line in view: see GenerationModule.)
1204
1572
  scrollMessagesToEnd();
1205
- if (isGenerating) scrollGenerationTail();
1206
1573
  });
1207
1574
  }
1208
1575
  });
@@ -1660,18 +2027,25 @@
1660
2027
  <div class="{panelLayout && chatTurns.length > 0 ? 'mt-auto flex w-full flex-col gap-4' : 'contents'}">
1661
2028
  <!-- Conversation turns (user prompt + assistant status grouped) -->
1662
2029
  {#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'}">
2030
+ {@const assistant = assistantViewOf(turn)}
2031
+ <div
2032
+ class="wc-chat-turn-ct rounded-lg {panelLayout ? 'flex flex-col gap-[52px]' : 'space-y-1.5 border border-transparent p-0.5'}"
2033
+ use:keepEndInView={turnIndex === chatTurns.length - 1}
2034
+ >
1664
2035
  {#if turn.user}
1665
2036
  {@const userMsg = turn.user}
1666
2037
  {@const shownAttachments = visibleUserAttachments(turn, turnIndex)}
2038
+ {@const author = authorOfMessage(userMsg)}
1667
2039
  <div class="message-container wc-chat-turn-user flex w-full flex-col {panelLayout ? 'items-end' : 'items-stretch'}"
1668
2040
  class:opacity-75={userMsg._optimistic}
1669
2041
  class:opacity-50={userMsg._failed}
1670
2042
  class:has-attachments={shownAttachments.length > 0}
1671
2043
  >
2044
+ <!-- The bubble and, at its end, the face of the person who wrote it (when the page told the chat who is who). -->
2045
+ <div class="wc-chat-turn-user-row flex w-full min-w-0 items-start gap-2" data-bubble-row>
1672
2046
  <Message
1673
2047
  role="user"
1674
- class="{panelLayout ? 'panel-layout-user-message ms-auto w-fit max-w-[85%]' : 'ms-auto w-full max-w-full'}"
2048
+ class="{panelLayout ? 'panel-layout-user-message ms-auto w-fit max-w-[85%]' : 'ms-auto w-full max-w-full'} min-w-0"
1675
2049
  data-testid="chat-user-bubble"
1676
2050
  >
1677
2051
  {#snippet children()}
@@ -1698,7 +2072,8 @@
1698
2072
  {/each}
1699
2073
  </div>
1700
2074
  {:else}
1701
- <p class="wc-chat-text whitespace-pre-wrap [overflow-wrap:anywhere] {panelLayout ? '' : 'p-3'}" dir={dirForUserText($textDirection)}>{@render linkified(userMsg.messageContent)}</p>
2075
+ <!-- Pretext sizes this text to the narrowest width that keeps its lines, so a wrapped bubble has no dead space beside them -->
2076
+ <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
2077
  {/if}
1703
2078
  {/if}
1704
2079
  {#if shownAttachments.length > 0}
@@ -1719,11 +2094,15 @@
1719
2094
  </div>
1720
2095
  {/snippet}
1721
2096
  </Message>
2097
+ {#if author}
2098
+ <MemberAvatar member={author} class="mt-1" />
2099
+ {/if}
2100
+ </div>
1722
2101
  {#if showCommitMetaOnUserTurn(turn) && (!panelLayout || showCommitMeta)}
1723
2102
  {@const commitTitle = getTurnCommitTitle(turn)}
1724
2103
  {@const versionLabel = getTurnVersionLabel(turn)}
1725
2104
  {#if showCommitMeta && commitTitle}
1726
- <div class="wc-user-commit-title-row flex w-full min-w-0 mt-1">
2105
+ <div class="wc-user-commit-title-row flex w-full min-w-0 mt-1 {author ? 'pe-8' : ''}">
1727
2106
  <span class="wc-user-commit-title text-xs text-gray-600" title={commitTitle}>
1728
2107
  {commitTitle}
1729
2108
  </span>
@@ -1733,7 +2112,7 @@
1733
2112
  {@const restoredVersion = restoredVersionFromTurn(turn)}
1734
2113
  {@const headRedoId = turnIsRestoreEcho(turn) ? headCommitRestoreTargetId() : null}
1735
2114
  <MessageCheckpointRow
1736
- class="wc-user-commit-meta-ct mt-1"
2115
+ class="wc-user-commit-meta-ct mt-1 {author ? 'pe-8' : ''}"
1737
2116
  versionLabel={versionLabel && versionNumberFromLabel(versionLabel) !== 1
1738
2117
  ? versionLabelText(versionLabel, $t)
1739
2118
  : showCommitMeta && getTurnCommitShort(turn)
@@ -1755,41 +2134,69 @@
1755
2134
  </div>
1756
2135
  {/if}
1757
2136
 
2137
+ <!-- Everything the assistant said or showed in this turn, with its face: the avatar at the left, the words to its right. After
2138
+ a run that just ended, the thinking and the code it made sit closed above its conclusion. (Not re-indented: the replies
2139
+ below are the same markup that used to sit directly in the turn.) -->
2140
+ {#if assistant.hasContent}
2141
+ <AgentTurn look={assistant.look} startSize={assistant.startSize} startState={assistant.startState} {renderAgentAvatar} class="wc-chat-turn-assistant">
2142
+ {#if assistant.finished}
2143
+ {@const keptModules = finishedModulesView(assistant.finished)}
2144
+ {#if keptModules.showThinking}
2145
+ <GenerationModule kind="thinking" text={assistant.finished.thinking} seconds={assistant.finished.thoughtSeconds} />
2146
+ {/if}
2147
+ {#if keptModules.showCode}
2148
+ <GenerationModule kind="code" text={assistant.finished.code} />
2149
+ {/if}
2150
+ {/if}
1758
2151
  {#each turn.replies as reply (reply.id)}
1759
2152
  {#if shouldShowAssistantReply(reply)}
2153
+ <!-- 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 -->
2154
+ {@const replyTextIsShown = !!reply.messageContent && (panelLayout || !(reply.suggestions && reply.suggestions.length > 0))}
1760
2155
  {#if panelLayout && isStoppedByUser(reply)}
1761
2156
  <!-- A stop is the person's own command: one quiet line, not the red "Could not build the widget" card. -->
1762
2157
  <p
1763
- class="wc-chat-turn-reply wc-chat-stopped text-body text-muted-foreground flex items-center gap-2"
2158
+ class="wc-chat-turn-reply wc-chat-stopped text-body text-muted-foreground flex min-h-7 items-center gap-2"
1764
2159
  data-testid="chat-stopped-notice"
1765
2160
  >
1766
2161
  <IconPlayerStop class="size-4 shrink-0 stroke-2" aria-hidden="true" />
1767
2162
  <span>{$t('chat.messages.stoppedByYou')}</span>
1768
2163
  </p>
1769
2164
  {: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 &&
2165
+ <!-- A failed reply in the docked panel is one short line, not a card: the warning mark, what went wrong in a few words,
2166
+ 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). -->
2167
+ {@const canRetryFailure =
2168
+ !!onRetryMessage &&
1777
2169
  isLastCodegenFailureInTurn(turn, reply) &&
1778
2170
  !isPlanLimitMessage(reply.messageContent) &&
1779
- turnNeedsRetry(turn, turnIndex)
1780
- ? $t('chat.messages.failedRetry')
1781
- : ''}
1782
- onAction={() => handleRetryTurn(turn, turnIndex)}
1783
- />
1784
- {:else}
2171
+ turnNeedsRetry(turn, turnIndex)}
2172
+ <div
2173
+ class="wc-chat-turn-reply wc-chat-failed text-body text-destructive flex min-h-7 items-center gap-2"
2174
+ data-testid="chat-failed-notice"
2175
+ >
2176
+ <IconAlertTriangle class="size-4 shrink-0 stroke-2" aria-hidden="true" />
2177
+ <span class="min-w-0 flex-1 [overflow-wrap:anywhere]">{failureLine(reply)}</span>
2178
+ {#if canRetryFailure}
2179
+ <button
2180
+ type="button"
2181
+ 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"
2182
+ aria-label={$t('chat.messages.failedRetry')}
2183
+ title={$t('chat.messages.failedRetry')}
2184
+ data-testid="chat-failed-retry"
2185
+ onclick={() => handleRetryTurn(turn, turnIndex)}
2186
+ >
2187
+ <IconRefresh class="size-4 stroke-2" aria-hidden="true" />
2188
+ </button>
2189
+ {/if}
2190
+ </div>
2191
+ {:else if replyTextIsShown || isCodegenFailure(reply)}
1785
2192
  <Message
1786
2193
  role="assistant"
1787
- class="wc-chat-turn-reply max-w-full"
2194
+ class="wc-chat-turn-reply mt-0.5 max-w-full"
1788
2195
  error={isCodegenFailure(reply)}
1789
2196
  errorText={visibleMessageContent(reply.messageContent || '')}
1790
2197
  >
1791
2198
  {#snippet children()}
1792
- {#if reply.messageContent && (panelLayout || !(reply.suggestions && reply.suggestions.length > 0))}
2199
+ {#if replyTextIsShown}
1793
2200
  <div class="message-content-assistant select-text text-sm leading-relaxed" use:bubbleScrollPadding>
1794
2201
  {#if reply.messageContent}
1795
2202
  {#if hasCodeBlocks(reply.messageContent)}
@@ -1855,6 +2262,20 @@
1855
2262
  {/if}
1856
2263
  {/if}
1857
2264
  {/each}
2265
+ {#if assistant.showDoneLine}
2266
+ <!-- The first line of the turn (no thinking or code above it) is as tall as the small avatar, like every first line -->
2267
+ {@const doneLineHasModulesAbove =
2268
+ !!assistant.finished &&
2269
+ (finishedModulesView(assistant.finished).showThinking || finishedModulesView(assistant.finished).showCode)}
2270
+ <p
2271
+ class="text-body text-foreground {doneLineHasModulesAbove ? '' : 'flex min-h-7 items-center'}"
2272
+ data-testid="agent-conclusion"
2273
+ >
2274
+ {$t('chat.generation.doneMessage')}
2275
+ </p>
2276
+ {/if}
2277
+ </AgentTurn>
2278
+ {/if}
1858
2279
 
1859
2280
  <!-- Copy, regenerate and the two thumbs: at the end of the last message only, and not while something is being generated.
1860
2281
  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 +2300,55 @@
1879
2300
  </div>
1880
2301
  {/each}
1881
2302
 
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}
2303
+ <!-- The assistant while it works: its face (large while it waits, small once its thoughts or its code stream) and, to its
2304
+ 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
2305
+ drawn again under the turn it answered, grown into the conclusion. The offset keeps the face where that turn will put it
2306
+ (the turn spaces its reply closer than the list spaces a turn from the next). -->
2307
+ {#if thinkingHold && assistantIsWorking}
2308
+ <!-- (The wrapper is what the list sees grow: keepEndInView keeps the end of the list in view while the turn changes size.) -->
2309
+ <div class="loading-indicator-ct {panelLayout ? 'mt-9 pb-3' : '-mt-3'}" use:keepEndInView>
2310
+ <AgentTurn look={liveLook} {renderAgentAvatar}>
2311
+ {#if planCardView}
2312
+ <PlanCard
2313
+ class="w-full"
2314
+ dir="auto"
2315
+ role="region"
2316
+ aria-label={$t('chat.plan.regionLabel')}
2317
+ title={planCardView.title}
2318
+ tasks={planCardView.tasks}
2319
+ progressCurrent={planCardView.progressCurrent}
2320
+ progressTotal={planCardView.progressTotal}
2321
+ visibleTaskCount={4}
2322
+ messages={planCardMessages}
2323
+ />
2324
+ {/if}
2325
+ {#if liveModules.showShimmer}
2326
+ <div class="thinking-bubble relative flex min-h-7 w-fit items-center whitespace-nowrap text-sm">
2327
+ <span class="thinking-sizer" aria-hidden="true">{thinkingLabel}</span>
2328
+ <span class="thinking-reveal absolute inset-0 flex items-center">{shownThinkingLabel}</span>
1905
2329
  </div>
1906
2330
  {/if}
1907
- {/if}
1908
- {#if archivedGeneration.code.trim()}
1909
- <CodeBlock code={archivedGeneration.code} language="typescript" />
1910
- {/if}
2331
+ {#if liveModules.showThinking}
2332
+ <GenerationModule
2333
+ kind="thinking"
2334
+ text={keptThinkingText}
2335
+ streaming={liveModules.thinkingStreaming}
2336
+ seconds={frozenThoughtSeconds}
2337
+ openByDefault={liveModules.thinkingOpenByDefault}
2338
+ />
2339
+ {/if}
2340
+ {#if liveModules.showCode && shownGenerationText}
2341
+ <GenerationModule
2342
+ kind="code"
2343
+ text={shownGenerationText}
2344
+ streaming={liveModules.codeStreaming}
2345
+ openByDefault={liveModules.codeOpenByDefault}
2346
+ />
2347
+ {/if}
2348
+ {#if generationAriaLine}
2349
+ <p class="sr-only" aria-live="polite">{generationAriaLine}</p>
2350
+ {/if}
2351
+ </AgentTurn>
1911
2352
  </div>
1912
2353
  {/if}
1913
2354
  </div>
@@ -1922,87 +2363,6 @@
1922
2363
  </div>
1923
2364
  </div>
1924
2365
  {/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
2366
 
2007
2367
  {#if !autoScroll && messages.length > 0 && !isLoading}
2008
2368
  <div class="sticky bottom-2 z-10 flex justify-center pb-1 pt-2 pointer-events-none [&_button]:pointer-events-auto">
@@ -2051,38 +2411,13 @@
2051
2411
  0% { background-position: 100% 0; }
2052
2412
  100% { background-position: -100% 0; }
2053
2413
  }
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
2414
  @media (prefers-reduced-motion: reduce) {
2063
- .thinking-reveal,
2064
- .thinking-reveal-inline {
2415
+ .thinking-reveal {
2065
2416
  animation: none;
2066
2417
  color: inherit;
2067
2418
  background-image: none;
2068
2419
  }
2069
2420
  }
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
2421
  .loading {
2087
2422
  opacity: 0.75;
2088
2423
  }