@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
package/README.md CHANGED
@@ -287,6 +287,77 @@ then live code in the same bubble. Parse wire data with **`readGenerationPlanFro
287
287
  `@widgetic/chat`. When **`features.screenshot`** is `false`, the action bar hides the screenshot control;
288
288
  ordinary image upload and screen recording are unchanged.
289
289
 
290
+ ### The assistant's turn: avatar, sound, faces and bubbles
291
+
292
+ The messages list plays the assistant's turn around an **avatar**. The avatar, its sound and the team's faces come from the page: the chat
293
+ has no dependency on any drawing or sound code. A page that gives nothing gets a plain round avatar and silence, so nothing here is required.
294
+
295
+ ```svelte
296
+ <script lang="ts">
297
+ import { Chat } from '@widgetic/chat';
298
+ import { Mascot } from '@widgetic/brand/mascot';
299
+ import { createMascotSound } from '@widgetic/brand/mascot/sound';
300
+
301
+ // Off until `agentSound.enable()` runs inside a click (browsers keep audio locked until a gesture)
302
+ const agentSound = createMascotSound();
303
+ </script>
304
+
305
+ {#snippet agentAvatar({ state, size, live, label })}
306
+ <Mascot {state} {size} {label} decorative={!label} frozenAt={live ? undefined : 0.5} settleTo="idle" />
307
+ {/snippet}
308
+
309
+ <Chat {context} renderAgentAvatar={agentAvatar} {agentSound} {members} {currentUser} />
310
+ ```
311
+
312
+ | Prop | What it does |
313
+ | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
314
+ | `renderAgentAvatar` | A snippet that draws the avatar, given `{ state, size, live, label }` (`AgentAvatarRenderProps`). `state` is one of the Scribble Mascot's five (`idle`, `thinking`, `writing`, `success`, `error`). |
315
+ | `agentSound` | Lets the avatar be heard: anything with `notifyStateChange(state)` (`AgentSoundPlayer`). The mascot's `createMascotSound()` fits as it is. Left out, the chat is silent. |
316
+ | `members` | The team (`ChatMember[]`: `id`, and optionally `name`, `email`, `avatarUrl`). A message a person wrote gets their picture, or their initials, at its right, and their e-mail while the pointer rests on it; a click on it writes to them (a `mailto:` link, with the hand cursor), as in the project header of the Widgetic site. Without an e-mail it is only a picture. |
317
+ | `currentUser` | The signed-in person: who wrote the messages they just sent, and anyone no member matches. A message nobody can be named for gets no face, and a page that names nobody sees no change. |
318
+ | `tightBubbles` | On by default. Sizes what people wrote to their text with [Pretext](https://chenglou.me/pretext/bubbles/): a bubble whose text wraps is as narrow as its widest line allows. `false` for CSS's widths. |
319
+
320
+ What the person sees, in the order it happens (a page that is not the chat, such as the workflows assistant or the embed, follows the same
321
+ choreography through the exported rules and components, see below):
322
+
323
+ 1. **The message is sent**: the avatar is large and thinks, with a card to its right if the host sends a plan or a question.
324
+ 2. **The reasoning is written**: the avatar glides down to its small size at the left and keeps **thinking**, beside a collapsible "Thinking…"
325
+ text that is open while it is written.
326
+ 3. **Code, or the answer, is written**: the avatar **writes**, beside a "Writing code…" module that is open while the code streams. Writing
327
+ begins only when something other than reasoning arrives.
328
+ 4. **The end**: a success grows the avatar large again, in its **success** look, with the conclusion and the thinking and the code as two
329
+ closed, expandable modules ("Thought for 2 s", "Code"). A failure is one short line in red with a refresh icon that runs the prompt again,
330
+ beside the large **error** avatar. **Stop** glides the avatar down to its small size.
331
+
332
+ Only the newest turn moves, and at most one avatar is alive in a long chat; the older ones are small still pictures. What the assistant did
333
+ (the thinking and the code of the run that just ended) is kept in this browser (IndexedDB, by conversation) and comes back after a reload under
334
+ the turn it belongs to, found again by the words of the prompt.
335
+
336
+ **Sound.** The chat tells `agentSound` the state of the avatar the person is looking at, **once for each change**: `thinking` when the run starts,
337
+ `writing` when code (or the answer) is written, then how it ended: `success`, `error`, or `idle` for a stop, a question or a plain answer. It
338
+ never speaks for a conversation that was only opened or switched to, whatever state its newest turn was left in (opening a chat must not play
339
+ the sound of a failure), and never once per streamed token. Everything else about sounding is the player's: the mascot's is off until the page
340
+ calls `enable()` inside a click, plays one short cue per state, does not repeat the same cue within 250 ms and stays quiet in a hidden tab (see
341
+ the brand README). The chat has no sound control of its own, so the page keeps the person's choice (a mute switch) and passes it on. A page that
342
+ does not draw the mascot should not give `agentSound` either: the sounds belong to the mascot. A player that throws is left alone and never takes
343
+ the chat down.
344
+
345
+ **The code card.** The code the assistant writes is drawn by `CodeCard`: the white card of the design system, the code in a grey panel in a code
346
+ editor's font, coloured, with its line count and a copy button. While the code arrives, **Prettier lays out what has arrived** (see
347
+ `src/lib/utils/codeStreamFormat.ts`): the text is cut after its last whole line, what is still open there is closed (`)`, `]`, `}` and the
348
+ closing tags), the result is formatted and cut again where the real text ended, and the line being typed follows as it was typed. When Prettier
349
+ refuses a cut (a function with no body yet), an earlier one is tried; when none works, the code is shown as written. Prettier is a dependency of
350
+ the chat and a dynamic import: a page that never shows code never loads it. Only scripts (JavaScript, TypeScript, JSX, TSX) are laid out; a page
351
+ or a Svelte component is shown as written. The card colours the code with highlight.js under its own class names (`wc-code-*`), so a highlight
352
+ theme of the page cannot repaint it.
353
+
354
+ A page that builds its own panel can use the pieces: `AgentAvatar`, `AgentTurn`, `CodeCard`, `GenerationModule` and `MemberAvatar`, and the rules they
355
+ follow: `liveAgentLook`, `settledAgentLook`, `turnOutcome`, `avatarStartAfter`, `keepFinishedGeneration` and `soundStateOf`.
356
+
357
+ To see it all on a real chat played by a pretend host, run `npm run dev` and open `/agent`. It loads the mascot and its sound from the
358
+ sibling `brand` checkout when it is there, and answers on `window.__agentDemo` for scripted checks. Query: `scenario=success|failure|question|stopped|plain`,
359
+ `run=1`, `step=1`, `speed=4`, `panel=0`, `rtl=1`, `mascot=0`, `sound=0`, `people=0`, `tight=0`.
360
+
290
361
  ## Languages
291
362
 
292
363
  The chat shows English until it is told otherwise. Two props of `Chat` change that, and both can change while the chat
@@ -10,6 +10,7 @@
10
10
  import type { ChatConfig, ChatContext } from '../types/index.js';
11
11
  import type { ClarificationSuggestion, DesignControlRequest, VersionRating } from '../types/message.js';
12
12
  import type { AttachmentInput, SelectedElementChatReference } from '../types/attachment.js';
13
+ import type { AgentAvatarRenderer, AgentSoundPlayer, ChatMember } from '../types/agent.js';
13
14
  import ChatMessages from './ChatMessages.svelte';
14
15
  import ChatComposer, { type ComposerModelOption } from './ChatComposer.svelte';
15
16
  import { Chip } from '@widgetic/design-system/components/chat/index';
@@ -201,6 +202,34 @@
201
202
  * `conversationLineLabel`). When omitted, message text is shown as stored.
202
203
  */
203
204
  storedLineLabel?: (content: string) => string;
205
+ /**
206
+ * The people of the project's team. A message a person wrote gets that person's picture (or their initials) at its right, and
207
+ * their e-mail when the pointer rests on it, found by the `userId` the message carries. Left out (and without `currentUser`)
208
+ * the chat draws no faces next to what people wrote.
209
+ */
210
+ members?: ChatMember[];
211
+ /**
212
+ * The signed-in person: who wrote the messages they just sent (before the host has saved them and told the real id), and
213
+ * anything no member of `members` matches.
214
+ */
215
+ currentUser?: ChatMember | null;
216
+ /**
217
+ * How the assistant's avatar is drawn. The Widgetic apps pass the Scribble Mascot (`@widgetic/brand/mascot`). Left out, a plain
218
+ * round avatar is drawn, so the chat has no dependency on the mascot. See `AgentAvatarRenderer` for what it is called with.
219
+ */
220
+ renderAgentAvatar?: AgentAvatarRenderer;
221
+ /**
222
+ * Lets the assistant's avatar be heard: it is told the state of the avatar the person is looking at, once for each change (the
223
+ * mascot's `createMascotSound()` fits as it is). Left out, the chat is silent. Whether it sounds is up to the player (off until
224
+ * the person asks), so the page keeps the control for it. See `AgentSoundPlayer`.
225
+ */
226
+ agentSound?: AgentSoundPlayer;
227
+ /**
228
+ * Sizes the bubbles of what people wrote to their text with Pretext (https://chenglou.me/pretext/bubbles/): a bubble whose text
229
+ * 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
230
+ * does not wrap, and a message with code blocks, keep the width CSS gives them. On by default; pass `false` for CSS's widths.
231
+ */
232
+ tightBubbles?: boolean;
204
233
  /** Show the Widget Element Selector toggle button in the action bar (disabled by default). */
205
234
  showSelector?: boolean;
206
235
  /** Whether the Widget Element Selector is currently active for this chat's widget. */
@@ -258,7 +287,7 @@
258
287
  updateLastUserMessageAttachments: (attachments: Array<{ id?: string; url: string; file_type?: string; file_name?: string | null }>) => void;
259
288
  }
260
289
 
261
- let { context, config = {}, class: className = '', locale = null, messages: languageMessages = null, dir = undefined, style = '', isCompleted = false, onStatsUpdate, onChatReady, onCompletionToggle, onSendMessage, onLoadConversations, onLoadMessages, onCreateConversation, onSaveMessage, onRestoreCheckpointBackend, onRateVersion, versionRatings: ratingsFromHost = {}, onTakeScreenshot, onConversationChange, onDraftChange, onRetryMessage, onUpgradePlans, onUploadChatFile, showHeader = true, showPanelHeader = false, showConsoleControl = false, sendNudgeToken = 0, consoleOpen = false, onToggleConsole, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize, onMessagesDrag, onMessagesDragEnd, onLoadOlderMessages, widgetHeadCommitSha = null, versionLabelByCommitSha = {}, versionLabelByPrompt = {}, versionTimeline = [], isGenerating = false, generationStream = '', generationThinking = '', generationPlan = null, onStopGeneration, renderDesignControls, actionBarExtras, completeReplacement, replaceComplete = false, showSelector = false, isSelectorActive = false, selectedElements = [], onToggleSelector, onRemoveSelectedElement, onClearSelectedElements, composerExtras, storedLineLabel, composerModels = [], selectedComposerModelId = null, onSelectComposerModel }: Props = $props();
290
+ let { context, config = {}, class: className = '', locale = null, messages: languageMessages = null, dir = undefined, style = '', isCompleted = false, onStatsUpdate, onChatReady, onCompletionToggle, onSendMessage, onLoadConversations, onLoadMessages, onCreateConversation, onSaveMessage, onRestoreCheckpointBackend, onRateVersion, versionRatings: ratingsFromHost = {}, onTakeScreenshot, onConversationChange, onDraftChange, onRetryMessage, onUpgradePlans, onUploadChatFile, showHeader = true, showPanelHeader = false, showConsoleControl = false, sendNudgeToken = 0, consoleOpen = false, onToggleConsole, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize, onMessagesDrag, onMessagesDragEnd, onLoadOlderMessages, widgetHeadCommitSha = null, versionLabelByCommitSha = {}, versionLabelByPrompt = {}, versionTimeline = [], isGenerating = false, generationStream = '', generationThinking = '', generationPlan = null, onStopGeneration, members = [], currentUser = null, renderAgentAvatar, agentSound, tightBubbles = true, renderDesignControls, actionBarExtras, completeReplacement, replaceComplete = false, showSelector = false, isSelectorActive = false, selectedElements = [], onToggleSelector, onRemoveSelectedElement, onClearSelectedElements, composerExtras, storedLineLabel, composerModels = [], selectedComposerModelId = null, onSelectComposerModel }: Props = $props();
262
291
 
263
292
  // The words of everything inside the chat, in the language the page chose. The page can change the language while the
264
293
  // chat is open: the settings are read again whenever they change (and setting the same language again does nothing).
@@ -2080,6 +2109,11 @@
2080
2109
  {renderDesignControls}
2081
2110
  {storedLineLabel}
2082
2111
  conversationId={currentConversationId}
2112
+ {members}
2113
+ {currentUser}
2114
+ {renderAgentAvatar}
2115
+ {agentSound}
2116
+ {tightBubbles}
2083
2117
  />
2084
2118
  </div>
2085
2119
 
@@ -3,6 +3,7 @@ import { type TextDirection } from '@widgetic/design-system/components/textDirec
3
3
  import type { ChatConfig, ChatContext } from '../types/index.js';
4
4
  import type { ClarificationSuggestion, DesignControlRequest, VersionRating } from '../types/message.js';
5
5
  import type { AttachmentInput, SelectedElementChatReference } from '../types/attachment.js';
6
+ import type { AgentAvatarRenderer, AgentSoundPlayer, ChatMember } from '../types/agent.js';
6
7
  import { type ComposerModelOption } from './ChatComposer.svelte';
7
8
  interface ChatMethods {
8
9
  sendMessage: (content: string, attachments?: Array<File | AttachmentInput>, options?: {
@@ -240,6 +241,34 @@ interface Props {
240
241
  * `conversationLineLabel`). When omitted, message text is shown as stored.
241
242
  */
242
243
  storedLineLabel?: (content: string) => string;
244
+ /**
245
+ * The people of the project's team. A message a person wrote gets that person's picture (or their initials) at its right, and
246
+ * their e-mail when the pointer rests on it, found by the `userId` the message carries. Left out (and without `currentUser`)
247
+ * the chat draws no faces next to what people wrote.
248
+ */
249
+ members?: ChatMember[];
250
+ /**
251
+ * The signed-in person: who wrote the messages they just sent (before the host has saved them and told the real id), and
252
+ * anything no member of `members` matches.
253
+ */
254
+ currentUser?: ChatMember | null;
255
+ /**
256
+ * How the assistant's avatar is drawn. The Widgetic apps pass the Scribble Mascot (`@widgetic/brand/mascot`). Left out, a plain
257
+ * round avatar is drawn, so the chat has no dependency on the mascot. See `AgentAvatarRenderer` for what it is called with.
258
+ */
259
+ renderAgentAvatar?: AgentAvatarRenderer;
260
+ /**
261
+ * Lets the assistant's avatar be heard: it is told the state of the avatar the person is looking at, once for each change (the
262
+ * mascot's `createMascotSound()` fits as it is). Left out, the chat is silent. Whether it sounds is up to the player (off until
263
+ * the person asks), so the page keeps the control for it. See `AgentSoundPlayer`.
264
+ */
265
+ agentSound?: AgentSoundPlayer;
266
+ /**
267
+ * Sizes the bubbles of what people wrote to their text with Pretext (https://chenglou.me/pretext/bubbles/): a bubble whose text
268
+ * 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
269
+ * does not wrap, and a message with code blocks, keep the width CSS gives them. On by default; pass `false` for CSS's widths.
270
+ */
271
+ tightBubbles?: boolean;
243
272
  /** Show the Widget Element Selector toggle button in the action bar (disabled by default). */
244
273
  showSelector?: boolean;
245
274
  /** Whether the Widget Element Selector is currently active for this chat's widget. */
@@ -59,6 +59,10 @@
59
59
 
60
60
  const composerSendIcon = $derived(panelLayout ? 'arrow-up' : sendIcon);
61
61
 
62
+ // The model menu's button reads the name of the picked model. Until one is picked it reads the name of the first one (the model
63
+ // that is used then), never a generic word such as "Assistant": the person knows what they are talking to.
64
+ const fallbackModelLabel = $derived(models?.[0]?.label?.trim() ?? '');
65
+
62
66
  let isFileDragOver = $state(false);
63
67
  let sendNudgePhase = $state<SendNudgePhase>('idle');
64
68
  let sendNudgeBounce = $state(false);
@@ -220,7 +224,7 @@
220
224
  attach: $t('chat.actions.upload'),
221
225
  characterLimit: $t('chat.input.tooLong')
222
226
  }}
223
- assistantLabel={$t('chat.composer.assistant')}
227
+ assistantLabel={fallbackModelLabel}
224
228
  onSend={handleComposerSend}
225
229
  onStop={() => onStop?.()}
226
230
  leading={attachControl}