@widgetic/chat 0.1.42 → 0.1.43

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 (83) hide show
  1. package/README.md +461 -6
  2. package/dist/components/Chat.svelte +1078 -87
  3. package/dist/components/Chat.svelte.d.ts +102 -2
  4. package/dist/components/ChatComposer.svelte +382 -9
  5. package/dist/components/ChatComposer.svelte.d.ts +66 -3
  6. package/dist/components/ChatMessageQueue.svelte +56 -0
  7. package/dist/components/ChatMessageQueue.svelte.d.ts +20 -0
  8. package/dist/components/ChatMessages.svelte +477 -46
  9. package/dist/components/ChatMessages.svelte.d.ts +45 -2
  10. package/dist/components/ComposerAttachmentsTray.svelte +42 -10
  11. package/dist/components/ComposerAttachmentsTray.svelte.d.ts +5 -0
  12. package/dist/components/ComposerMentionChips.svelte +53 -0
  13. package/dist/components/ComposerMentionChips.svelte.d.ts +15 -0
  14. package/dist/components/FollowUpCard.svelte +134 -0
  15. package/dist/components/FollowUpCard.svelte.d.ts +17 -0
  16. package/dist/components/MentionChip.svelte +41 -0
  17. package/dist/components/MentionChip.svelte.d.ts +12 -0
  18. package/dist/components/MentionMenu.svelte +114 -0
  19. package/dist/components/MentionMenu.svelte.d.ts +19 -0
  20. package/dist/components/agent/AgentAvatar.svelte +6 -4
  21. package/dist/components/agent/AgentAvatar.svelte.d.ts +1 -1
  22. package/dist/components/agent/CodeCard.svelte +122 -27
  23. package/dist/components/agent/CodeCard.svelte.d.ts +3 -0
  24. package/dist/components/agent/CodeDiff.svelte +180 -0
  25. package/dist/components/agent/CodeDiff.svelte.d.ts +10 -0
  26. package/dist/components/agent/GenerationModule.svelte +13 -2
  27. package/dist/components/agent/GenerationModule.svelte.d.ts +3 -0
  28. package/dist/components/index.d.ts +4 -0
  29. package/dist/components/index.js +9 -0
  30. package/dist/errors/logTechnicalUserError.d.ts +1 -0
  31. package/dist/errors/logTechnicalUserError.js +37 -0
  32. package/dist/i18n/messages.d.ts +106 -1
  33. package/dist/i18n/messages.js +112 -1
  34. package/dist/i18n/sketchLocales.js +8 -8
  35. package/dist/messageQueue.d.ts +83 -0
  36. package/dist/messageQueue.js +84 -0
  37. package/dist/services/sketchAssistantClient.js +6 -2
  38. package/dist/services/sketchAssistantErrors.d.ts +4 -0
  39. package/dist/services/sketchAssistantErrors.js +22 -0
  40. package/dist/services/sketchAssistantOrchestrator.d.ts +1 -6
  41. package/dist/services/sketchAssistantOrchestrator.js +10 -24
  42. package/dist/services/sketchAssistantReply.js +3 -1
  43. package/dist/stores/chatStore.d.ts +5 -0
  44. package/dist/stores/chatStore.js +21 -0
  45. package/dist/types/agent.d.ts +4 -3
  46. package/dist/types/attachment.d.ts +16 -0
  47. package/dist/types/config.d.ts +6 -0
  48. package/dist/types/index.d.ts +1 -0
  49. package/dist/types/index.js +2 -0
  50. package/dist/types/mention.d.ts +40 -0
  51. package/dist/types/mention.js +8 -0
  52. package/dist/types/message.d.ts +60 -1
  53. package/dist/utils/agentTurn.d.ts +40 -9
  54. package/dist/utils/agentTurn.js +43 -11
  55. package/dist/utils/attachmentProgress.d.ts +12 -0
  56. package/dist/utils/attachmentProgress.js +18 -0
  57. package/dist/utils/bubbleRichFit.d.ts +68 -0
  58. package/dist/utils/bubbleRichFit.js +45 -0
  59. package/dist/utils/bubbleShrinkWrap.d.ts +8 -1
  60. package/dist/utils/bubbleShrinkWrap.js +113 -17
  61. package/dist/utils/codeChanges.d.ts +103 -0
  62. package/dist/utils/codeChanges.js +226 -0
  63. package/dist/utils/codeHighlight.js +1 -0
  64. package/dist/utils/codeStreamFormat.d.ts +5 -2
  65. package/dist/utils/composerMentions.d.ts +96 -0
  66. package/dist/utils/composerMentions.js +217 -0
  67. package/dist/utils/followUps.d.ts +74 -0
  68. package/dist/utils/followUps.js +116 -0
  69. package/dist/utils/generationArchiveStore.d.ts +6 -0
  70. package/dist/utils/generationArchiveStore.js +11 -3
  71. package/dist/utils/index.d.ts +12 -0
  72. package/dist/utils/index.js +20 -0
  73. package/dist/utils/orderedLine.d.ts +29 -0
  74. package/dist/utils/orderedLine.js +17 -0
  75. package/dist/utils/pastedContent.d.ts +99 -0
  76. package/dist/utils/pastedContent.js +258 -0
  77. package/dist/utils/questionCards.d.ts +131 -0
  78. package/dist/utils/questionCards.js +287 -0
  79. package/dist/utils/referenceItems.d.ts +36 -0
  80. package/dist/utils/referenceItems.js +56 -0
  81. package/dist/utils/sentReferenceBadges.d.ts +26 -0
  82. package/dist/utils/sentReferenceBadges.js +32 -0
  83. package/package.json +1 -1
package/README.md CHANGED
@@ -213,6 +213,99 @@ decides where a rating goes. A rating is one of three words: `up`, `down`, or `n
213
213
  the chat is loading or generating, and the thumbs belong to the last message only.
214
214
  - Words: `chat.messages.rateGroup`, `chat.messages.rateUp` and `chat.messages.rateDown` (see [Languages](#languages)).
215
215
 
216
+ ### The message box on its own
217
+
218
+ `ChatComposer` is the box the chat writes its messages in: the text, Enter to send, Shift+Enter for a new line, the arrow-up send button, and the
219
+ chips of the picked parts above the text. A page that needs a box like it outside the chat can use it. The creator writes the note of a part
220
+ picked on the preview in one.
221
+
222
+ ```svelte
223
+ <script lang="ts">
224
+ import { ChatComposer } from '@widgetic/chat';
225
+
226
+ let note = $state('');
227
+ </script>
228
+
229
+ <ChatComposer
230
+ bind:value={note}
231
+ panelLayout
232
+ autofocus
233
+ canSendWithoutText
234
+ placeholder="Note for this part"
235
+ inputLabel="Note for this part"
236
+ sendLabel="Add to the chat"
237
+ enterKeyHint="done"
238
+ onSend={(text) => keepNote(text)}
239
+ />
240
+ ```
241
+
242
+ - `onSend(text)` is called on Enter and on the send button, with the text trimmed (Shift+Enter is a new line). With `canSendWithoutText` an empty
243
+ box can be sent too.
244
+ - Four props are for a box used on its own, and the chat's own box asks for none of them: `autofocus` (the box takes the focus when it is drawn,
245
+ with the caret after the text), `inputLabel` (the name a screen reader gives the box; without it the placeholder is the name), `enterKeyHint`
246
+ (what the Enter key of a touch keyboard says: `done`, `send`, and so on) and `sendLabel` (the name of the send button; without it "Send message").
247
+ - Outside a `Chat` the box speaks English, and the words a person sees or hears are the ones the page gives it (`placeholder`, `inputLabel`,
248
+ `sendLabel`). The box has no stop button to show while nothing is generated, and no limit to say "Message is too long" about.
249
+ ### Mentioning with @
250
+
251
+ A person can point a message at something the page knows about by typing `@` in the message box: a connected app, a widget, a composition. The
252
+ menu is **opt-in**: give `Chat` `mentionSources` and typing `@` opens it, leave it out (or empty) and `@` is an ordinary character in a box that is
253
+ exactly as it was. The chat knows nothing about what a row is: the page makes the lists, and decides what a pick means when the message arrives.
254
+
255
+ ```svelte
256
+ <script lang="ts">
257
+ import { Chat, type MentionSource, type ComposerMention } from '@widgetic/chat';
258
+
259
+ const mentionSources: MentionSource[] = [
260
+ {
261
+ kind: 'openMcp', // what the page calls this kind of row: it comes back with the pick
262
+ label: 'Connected apps', // the heading of the group, shown only when the menu holds more than one kind
263
+ items: [
264
+ { id: 'a1', name: 'Figma', caption: 'Designs and files', linkHosts: ['mcp.figma.com'] },
265
+ // A row that cannot be picked yet is shown dimmed with the page's own reason
266
+ { id: 'b2', name: 'Linear', selectable: false, unavailableReason: 'Turn on “Use in chats” in Settings first' }
267
+ ]
268
+ }
269
+ ];
270
+
271
+ async function sendMessage(content: string, attachments?: unknown, options?: { mentions?: ComposerMention[] }) {
272
+ // [{ kind: 'openMcp', id: 'a1', name: 'Figma' }] in the order they were picked; the key is left out when nothing was picked
273
+ const picks = options?.mentions ?? [];
274
+ await api.send({ content, picks: picks.map(({ kind, id }) => ({ kind, id })) });
275
+ }
276
+ </script>
277
+
278
+ <Chat {context} {mentionSources} mentionLimit={3} onSendMessage={sendMessage} />
279
+ ```
280
+
281
+ - **The menu** opens while the caret is in a word that starts with `@` (at the start of the text or after a space) and lists the rows whose name or
282
+ caption holds what was typed after it. The arrow keys move over the rows that can be picked (a dimmed row is passed over, and the list wraps),
283
+ **Enter or Tab picks**, Escape closes it and it stays closed for that word. None of them picks while Shift, Alt, Ctrl or Meta is held or an input method is
284
+ composing. The menu is drawn only while a row matches: an `@` that matches nothing is plain text, and Enter sends the message as always. A click
285
+ on a row picks it without taking the focus out of the box.
286
+ - **A pick** writes `@Name ` into the text (what the person sees is what was sent), draws a chip in the box (with its remove button) and puts the caret
287
+ after the name. Picking the same row again changes nothing: one `kind` and `id` counts once. Only `kind` and `id` say what was picked: believe
288
+ nothing else of `name` than that it is what the row showed.
289
+ - **`mentions` in `onSendMessage`** is the list of picks, in the order they were made, in the third argument next to `skipIntentGate`,
290
+ `chipIntent` and `selectedElements`. It is **left out when nothing was picked**, so a host that does not know it gets the options it always had. The
291
+ chips are cleared with the text, when the message is sent or the draft is cleared. They are not part of the draft a page keeps for reloads, and a
292
+ host that retries a failed turn (`onRetryMessage`) has to keep the picks of the last message itself: Retry gives it the text only.
293
+ - **`mentionLimit`** (5 when left out) is the most picks one message holds. Once it is reached the other rows are dimmed and the menu says why, so the
294
+ limit is never a silent refusal. Give it the number the host's service takes.
295
+ - **The link hint.** A pasted link whose address belongs to a row is offered under the box as "Read this link with *name*": one tap adds the chip
296
+ and writes nothing into the text. A row belongs to a link when its `linkHosts` hold the link's registrable domain (`mcp.figma.com` matches
297
+ `www.figma.com`; `docs.superhuman.com` matches `superhuman.com`). Hints are offered for at most three rows, never for one already picked or
298
+ one that cannot be picked, and none once the limit is reached. A page gives `linkHosts` only to rows that would **not** read the link by
299
+ themselves: a row that reads a pasted link anyway needs no hint, and a hint for it would say the opposite of what happens.
300
+ - Screen readers: the menu is a listbox of options (`aria-selected`, `aria-disabled`), and while it is open the text box points at the highlighted
301
+ option with `aria-activedescendant` and `aria-controls`, and gives both back when it closes.
302
+ - Words: `chat.mentions.menuLabel`, `chat.mentions.limitReached`, `chat.mentions.chipsLabel`, `chat.mentions.remove` and `chat.mentions.linkHint` (see
303
+ [Languages](#languages)). The twelve shipped languages are in the Widgetic modules' locale files, not in this package: until a language has them the
304
+ five are shown in English.
305
+ - A page with a message box of its own uses the same rules and parts: `findActiveMentionTrigger`, `buildMentionRows`, `insertMentionText`,
306
+ `caretAfterMentionInsert`, `addMention`, `removeMention`, `findMentionLinkHints` and the rest of the `composerMentions` exports, and the components
307
+ `MentionMenu` and `MentionChip`. The dev page (`src/routes/agent/+page.svelte`, `?mentions=1`) shows a chat with two pretend lists and a limit of three.
308
+
216
309
  ## State Management
217
310
 
218
311
  The chat module uses Svelte 5 runes for reactive state management:
@@ -259,6 +352,8 @@ interface ChatConfig {
259
352
  aiSuggestions: boolean;
260
353
  screenRecording: boolean;
261
354
  restoreCheckpoint: boolean;
355
+ /** Messages sent while the agent works wait in a queue. On unless this is `false`. */
356
+ messageQueue?: boolean;
262
357
  };
263
358
  }
264
359
  ```
@@ -287,6 +382,107 @@ then live code in the same bubble. Parse wire data with **`readGenerationPlanFro
287
382
  `@widgetic/chat`. When **`features.screenshot`** is `false`, the action bar hides the screenshot control;
288
383
  ordinary image upload and screen recording are unchanged.
289
384
 
385
+ To show the plan card while the plan is still being written, also raise **`generationPlanPending`** (the host asked the
386
+ gateway for a plan with `clientCapabilities.plan`, and it has not come yet). Until `generationPlan` arrives the card is drawn
387
+ **closed**, saying "Planning" in a shimmer, and it is the same card that opens to its tasks when the plan comes. From then
388
+ on each task moves with its status: the task being worked on shimmers and its box becomes a dashed ring that turns; when
389
+ it is done the ring shrinks away, a green check pops up and the line through the task grows across it; and the count
390
+ ("2 of 5") ticks over, one letter at a time. While the card says "Planning" the thinking line waits.
391
+
392
+ ```svelte
393
+ <Chat
394
+ {context}
395
+ isGenerating={codegenRunning}
396
+ generationPlanPending={codegenRunning && !plan}
397
+ generationPlan={plan}
398
+ />
399
+ ```
400
+
401
+ Lower the flag when the plan arrives, or when no plan is coming. It is ignored when the run is over, and it ends by itself
402
+ once the coder's thinking or its code streams (both come after the plan, so a plan that was never made is not waited for).
403
+ Left `false`, the default, nothing is drawn until `generationPlan` arrives, as before.
404
+
405
+ The plan card belongs to the run in front of the person. When the run ends, however it ends (finished, failed or **stopped**),
406
+ the card goes in the same pass: the plan is not kept in the conversation, and no task is left shimmering, turning or struck
407
+ through. A host does not have to clear `generationPlan` first for that, but it should, so that the next run does not begin
408
+ with the plan of the last one. With reduced motion the card changes without moving. The words are the catalog keys
409
+ `chat.plan.planning`, `chat.plan.taskPending`, `chat.plan.taskActive` and `chat.plan.taskDone` (the last three are said to a
410
+ screen reader before each task). The effects are the design system's: the `shimmer` util, the `TextFlip` component and
411
+ `PlanCard`'s `planning` prop.
412
+ ### Messages sent while the agent works (the queue)
413
+
414
+ While `isGenerating` is on, a message the person sends does not stop the run and is not lost: it **waits in a queue**, a card above the
415
+ composer with the newest message at the bottom. Enter queues a typed message (the composer's main control reads "Add to queue" while
416
+ something is typed and stays Stop when nothing is). The files that were attached go with the message.
417
+
418
+ - **By itself.** Once the agent has been idle for a moment (0.6 s, so a host that raises its next run in the same tick is not interrupted),
419
+ the oldest message is sent through `onSendMessage`, like a typed one and without touching the composer, then the next one when that run ends.
420
+ - **On a row** (hover, keyboard focus, always on a touch screen): **Send now** stops the agent through `onStopGeneration` and sends that
421
+ message as soon as the agent has stopped (after 15 s without a stop the message stays queued and a notice says so); **Edit** puts its text and
422
+ files in the composer with an "Editing ×" pill and a check to save, and what the person had written meanwhile waits and comes back when the
423
+ edit is saved or dropped (the pill or Escape drops it); **Delete** drops it.
424
+ - **Stop** with messages waiting pauses the queue ("Paused"): nothing is sent by itself until one is sent now.
425
+ - The queue belongs to the open conversation and lives in memory: another conversation drops it (with a notice), a reload loses it.
426
+ - A host with no `onStopGeneration` gets Edit and Delete but no Send now. `features: { messageQueue: false }` turns the queue off: Enter
427
+ while the agent works is Stop again.
428
+
429
+ #### What a round changed: the diff in the code card
430
+
431
+ After a **later round** of a conversation, the code card under its conclusion opens on what that round changed: the lines taken out on a
432
+ **red** ground and the lines put in on a **green** one, file by file, with the number each line has in the old file and in the new one, and the
433
+ unchanged lines between two changes folded into one row ("9 unchanged lines"). It is **read-only**: nothing in it edits, applies or reverts a change.
434
+
435
+ The chat does not work the changes out. The streamed code is only a sampled tail of what the model wrote, and two tails cannot be compared, so the
436
+ gateway does it, from the version before the round and the version it saved, and sends the result in the completed operation's
437
+ `metadata.codeChanges` (only to a client that asked for it with `clientCapabilities.codeChanges`; the gateway's `29-code-card-changes.md` has the
438
+ wire format and the bounds). A page reads it with **`readCodeChangesFromMetadata`** and gives it to `Chat` as **`generationChanges`**:
439
+
440
+ ```svelte
441
+ <script lang="ts">
442
+ import { Chat, readCodeChangesFromMetadata } from '@widgetic/chat';
443
+
444
+ let codegenRunning = $state(false);
445
+ let changes = $state.raw(null);
446
+
447
+ function onRunStarted() {
448
+ changes = null; // the changes of the run before are not this run's
449
+ codegenRunning = true;
450
+ }
451
+
452
+ function onOperationCompleted(operation) {
453
+ // Give the changes when the operation completes: before or after isGenerating is lowered, both work
454
+ changes = readCodeChangesFromMetadata(operation.metadata);
455
+ codegenRunning = false;
456
+ }
457
+ </script>
458
+
459
+ <Chat {context} isGenerating={codegenRunning} generationChanges={changes} />
460
+ ```
461
+
462
+ - Unlike the live props above, `generationChanges` is **not** given up when `isGenerating` ends: it is what the run leaves behind. Give it **when
463
+ the operation completes**, and clear it when the next run starts. It may come **after** `isGenerating` fell: a host that lets the person send the
464
+ next message as soon as the preview is up (the widget creator does) lowers the flag before the gateway has sent the completed operation, and the chat
465
+ puts the changes into the work of the run that just ended. It does so only for work that a run kept when it ended in this chat and that has no changes
466
+ yet: never while a run works, never with no work kept (another conversation was opened), never into work that came back from the archive (that is of
467
+ an earlier turn), and never the value the chat held when the run began. A page that forgets to clear the changes is safe for the same reason. Give
468
+ them only for a run the person watched work: the chat has no work to put them with for a run it did not see. The demo page plays this order with
469
+ `?late=1`.
470
+ - The card opens on **Changes**, with a **Changes | Code** switch (the design system's `Tabs`) for all the code. Its header says how much changed
471
+ (`+12 −3`) even while it is closed. In the Changes view the copy button copies the changes as one unified diff; in the Code view, the code.
472
+ - The changes are kept with the rest of the run's work, in this browser (IndexedDB, by conversation), and come back after a reload.
473
+ - A card with no changes is the card it always was: the first message of a conversation (its code is all new, so there is nothing to compare), a
474
+ build that was not kept, a gateway that does not send them, a page that does not give them, and the live card while the code is still arriving.
475
+ - The chat trusts nothing it is given: `readCodeChanges` drops a file that has no path, reads a status it does not know as `modified`, and bounds
476
+ the files, the characters of each patch and of all of them together. A patch that was cut for its size shows what it has and says the rest is not
477
+ shown; a file too large to be sent shows its header and says so.
478
+ - Every line is coloured on its own, with the same palette as the code (a construct that runs over several lines, a block comment for instance, is
479
+ coloured by the line it is read on, since the lines around a change are all that is known of the file). A line of more than 1,000 characters is
480
+ shown as it is.
481
+ - `CodeDiff` draws the diff on its own (`<CodeDiff changes={changes} />`) for a page that builds its own panel. The words are the catalog keys
482
+ `chat.code.*` (the tabs, the badges, the folded rows and the notes) and `chat.generation.codeUpdated`. The design system has no green for success,
483
+ so the green is Tailwind's (`green-500/15` for the ground, `green-700` for the numbers, `green-400` on the dark theme through the `.dark` class);
484
+ the red is the design system's `destructive`.
485
+
290
486
  ### The assistant's turn: avatar, sound, faces and bubbles
291
487
 
292
488
  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
@@ -311,11 +507,12 @@ has no dependency on any drawing or sound code. A page that gives nothing gets a
311
507
 
312
508
  | Prop | What it does |
313
509
  | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
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`). |
510
+ | `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`). `live` is `false` for a still picture: the older turns, and a failure, which holds its red `error` look until the prompt is sent again. |
315
511
  | `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
512
  | `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
513
  | `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
514
  | `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. |
515
+ | `referenceBadges` | On by default. A sent message that names a picture attached to it with a `#word` (`make #hero_banner bigger`) shows the word as the badge the message box drew while it was written: the picture and the name, without an X. Nothing is stored for it; the words are matched with the names of the message's pictures (see below), and a word that cannot be matched for sure stays plain text. `false` shows the text as it was sent. |
319
516
 
320
517
  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
518
  choreography through the exported rules and components, see below):
@@ -326,8 +523,10 @@ choreography through the exported rules and components, see below):
326
523
  3. **Code, or the answer, is written**: the avatar **writes**, beside a "Writing code…" module that is open while the code streams. Writing
327
524
  begins only when something other than reasoning arrives.
328
525
  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.
526
+ closed, expandable modules ("Thought for 2 s", "Code"). A failure is one short line in red (no warning mark) with a refresh icon that runs
527
+ the prompt again. The avatar beside it glides down to its small size, if it was large, so the line sits where the text of any turn sits, and
528
+ **holds its red `error` look** as a still picture until the person tries again or sends another message; it is then the quiet picture of
529
+ every older turn. **Stop** glides the avatar down to its small size.
331
530
 
332
531
  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
532
  (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
@@ -349,14 +548,220 @@ closing tags), the result is formatted and cut again where the real text ended,
349
548
  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
549
  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
550
  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.
551
+ theme of the page cannot repaint it. After a later round the card shows what changed as a diff, in red and green (see *What a round changed* above).
353
552
 
354
- A page that builds its own panel can use the pieces: `AgentAvatar`, `AgentTurn`, `CodeCard`, `GenerationModule` and `MemberAvatar`, and the rules they
553
+ A page that builds its own panel can use the pieces: `AgentAvatar`, `AgentTurn`, `CodeCard`, `CodeDiff`, `GenerationModule` and `MemberAvatar`, and the rules they
355
554
  follow: `liveAgentLook`, `settledAgentLook`, `turnOutcome`, `avatarStartAfter`, `keepFinishedGeneration` and `soundStateOf`.
356
555
 
556
+ **File badges in sent messages.** A saved message keeps its text and its files, not the labels the message box gave the files while it was written
557
+ (`#hero_banner`). So the bubble works the label of each picture out again from the file's name, by the rule that gave it (the design system's
558
+ `segmentSentText`), and draws the words of the text that name a picture as the badge of the box: a small light pill with the picture and the word as it
559
+ was written, no X, inside the text and inside its line (a badge is as tall as a line of text, so it never makes a line taller). A badge opens nothing
560
+ and is not a control; the text of the bubble, and a copy of it, is the message as it was sent. The rule is cautious, because a wrong picture is worse
561
+ than none: a name that says nothing (`image.png`, a screenshot's), pictures that share a name, a word that names no picture and a word that is only
562
+ part of a longer one stay the plain text they are, a file with no address to draw gets no badge, and a message has at most 40. One case cannot be
563
+ seen from a saved message: when a picture was taken out of the draft before the message was sent, the box may have numbered the next one
564
+ (`#hero_banner_2`) in a way the files no longer show, and a word typed by hand can then name another picture than the one meant; that takes a word
565
+ typed by hand and a picture taken out, both. A bubble with badges is still tight: it is measured as Pretext's rich inline text
566
+ (`@chenglou/pretext/rich-inline`, loaded when a message has a badge: the text as runs and each badge as one box of the width it is drawn with),
567
+ searched the same way as any bubble and checked against what the browser made, and it keeps CSS's width when the two disagree. Needs a design
568
+ system that has `@widgetic/design-system/prompt-references`; `referenceBadges={false}` shows every text as it was sent.
569
+
357
570
  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`,
571
+ sibling `brand` checkout when it is there, and answers on `window.__agentDemo` for scripted checks. Query: `scenario=success|edit|failure|earlyFailure|question|stopped|plain` (`edit` ends with the changes of a later round, so the code card opens on the diff),
359
572
  `run=1`, `step=1`, `speed=4`, `panel=0`, `rtl=1`, `mascot=0`, `sound=0`, `people=0`, `tight=0`.
573
+ sibling `brand` checkout when it is there, and answers on `window.__agentDemo` for scripted checks. Query: `scenario=success|failure|question|questions|stopped|plain`,
574
+ `run=1`, `step=1`, `speed=4`, `panel=0`, `rtl=1`, `mascot=0`, `sound=0`, `people=0`, `tight=0`. The `success` scenario ends with the
575
+ follow-up card (three pills, below); the `questions` scenario adds the card of questions of the gateway (three questions, one of them with several
576
+ answers) and builds once it is answered in the card or by writing in the chat.
577
+
578
+ ### The follow-up card
579
+
580
+ After a build the person kept, the assistant can offer **ideas for what to improve next** on the widget: a card of small pills under the last
581
+ reply (`FollowUpCard`, the "Try next" heading, pills side by side that wrap). It is a third kind of card, and not the other two: the **starting
582
+ suggestions** (the empty state) say what could be built first, a **question card** is the assistant asking for clarity (options, one of them
583
+ recommended), and the follow-ups ask nothing, so nothing is chosen between and none is marked recommended.
584
+
585
+ **What makes a chip a pill is its `title`.** A reply's `suggestions` are `{ label, intent, title? }`: `label` is the whole request,
586
+ `title` is the few words (five at most, cut when read) the pill shows. A chip with a title is a pill; a chip without one is an option of a question,
587
+ drawn as before (the question card, or the rows above the composer in the panel). The server writes the title next to the request when it
588
+ suggests next steps, and chats saved before that have none, so nothing changes for them. `isFollowUpSuggestion`, `followUpPillsOf`,
589
+ `findFollowUpCard` and `questionOptionsOf` are the rules, and they are exported for a page that keeps its own list of messages.
590
+
591
+ - **Where.** At the end of the last turn's assistant column (alone, when that turn shows no words of the assistant, as after a reload). It is made
592
+ from the newest reply that has pills, looking back from the end and stopping at the first message of the person: **a message sent takes the card
593
+ away**, and the ideas of an older turn never come back. Up to five pills.
594
+ - **Pick.** A click puts the whole request in the message box (`onSuggestionSelected`, the plain path of the starting suggestions: nothing is sent,
595
+ and no `chipIntent` rides along, because a follow-up answers no question). The pill then shows **checked** (a check mark and a soft fill) for as long
596
+ as its words are in the box, and a checked pill is not added a second time. **Checked is read from the box, never remembered**: delete the words
597
+ (or send the message) and the pill is ready again. Give `ChatMessages` the box's text for it with `draftText`; `Chat` already does.
598
+ - **Remove.** The cross takes a pill out of the card; the words already in the box stay. The card goes with its last pill. Taken-out pills are not
599
+ saved: a reload brings the ideas back.
600
+ - **Tooltip.** The whole request, while the pointer rests on a pill or the keyboard is on it. The cross has a name that says which pill it removes
601
+ (`chat.followUp.remove`).
602
+ - **While the chat is busy** (`isLoading` or `isGenerating`) the pills are drawn and none can be picked or removed.
603
+
604
+ ### The question card
605
+
606
+ When the assistant needs clarity before it builds, its reply carries the options of a question (the chips with **no** `title`; one of them can be
607
+ the "generate anyway" chip) and the standard layout draws them as the design system's `QuestionCard` (Figma: Chat cards, "Questions"). In the
608
+ panel the same chips are the rows above the composer instead.
609
+
610
+ - **The card.** A small title ("Question") over the question, the options, and a footer with **Skip** and the primary button at its end (it reads
611
+ "Next", and "Submit" on the last of several questions). The primary button is on once an option is picked, and it puts that option in the message
612
+ box (`onClarificationSuggestionSelected`: nothing is sent until the person sends it).
613
+ - **The pager.** When a card asks **several questions** the footer starts with `‹ 1 of 3 ›`: the arrows go back and forth between the questions
614
+ without answering, a pick is kept when the person leaves a question and comes back, and Submit becomes Next until the last one. A card made
615
+ from chips has one question, so the pager shows on **the card of questions of the gateway** (below).
616
+ - **Skip.** Puts the card away and **nothing is sent or filled**: the question stays above as a plain message of the assistant, the turn stops
617
+ waiting for an answer, and the cursor goes back to the message box (`Chat` does that through `onQuestionSkipped`, which `ChatMessages` calls with
618
+ the id of the reply). It is remembered by the reply in this view only, like the pills taken out of the follow-up card: a reload brings the
619
+ card back. A pick is never needed to skip, and a skipped card does not touch the chips the reply was saved with.
620
+ - **Closes when the person writes in the chat.** Once a message of the person comes after the reply, the card is not waiting any more: it is drawn
621
+ as its summary (`QuestionCardSummary`): the question, and the option whose words the message holds (a chip put in the message box and sent), or
622
+ **Skipped** when the message holds none. (`chipQuestionOutcomeOf` is the rule.)
623
+ - **Words.** `chat.question.title`, `titleMany`, `step` (`{current}` of `{total}`), `back`, `forward`, `next`, `submit`, `skip`, `multipleHint`,
624
+ `noOptionsHint` and `skipped`, so a page can say every word of the card in its own language. The card fills in the step itself.
625
+ - **Needs** a design-system with the redesigned `QuestionCard` (the title on top, the pager in the footer, Skip on by default). With an older one the
626
+ card is drawn as it was (the step line above it, a Back button, and no Skip, because that card only shows Skip when asked to), and the words it
627
+ does not know are ignored.
628
+
629
+ ### The card of questions of the gateway
630
+
631
+ When the gateway cannot build safely without a few answers, its planning step ends the operation in `needs_answers` with a **clarification**
632
+ (the sentence that introduces it and up to four questions, each with up to five options, one recommended). The host hands that to the chat, and
633
+ the chat draws it as the same `QuestionCard`, with the pager, as a message of the assistant. It is the model that decides, **question by question**,
634
+ whether a question takes **one answer** (radio buttons) or **several** (check boxes, with "Select all that apply" over them): `allowMultiple` on
635
+ each question. A question with no options at all is answered in the message box (the card says so under the question).
636
+
637
+ ```ts
638
+ import { questionCardFromClarification } from '@widgetic/chat';
639
+
640
+ // the host: the operation ended in `needs_answers` (the gateway already saved the card as the assistant's reply)
641
+ const card = questionCardFromClarification(operation.metadata.clarification);
642
+ if (card) chatMethods.addQuestionCardMessage(card, undefined, /* skipPersist */ true);
643
+ ```
644
+
645
+ - **One answer, or several.** Each question of `ChatMessage.questionCard.questions[]` has `allowMultiple` (set by the model; it only means something
646
+ with two options or more). The card hands the design system's `QuestionCard` `multiple` for each question, so one question can be a choice and the
647
+ next a selection.
648
+ - **Next skips.** Next (Submit on the last question) is always on: with **nothing picked** that question is **skipped**, and the assistant decides it
649
+ itself. Skip at the end of the footer leaves **every** question to the assistant. A pick can be taken back by tapping it again.
650
+ - **Answered in the card.** The chat closes the card at once (it shows what was picked, and **Skipped** under a question with no pick), keeps the
651
+ answers on the message (`questionCard.result`) and calls `onQuestionsAnswered({ messageId, answers, skippedAll })`. `answers` are the gateway's
652
+ `answers`, one for each question in the card's order: `{ question, answer }`, where **an empty `answer` is a skipped question** and **several picks of
653
+ one question are one per line**. The host sends **the request that asked the questions again, with these answers** (nothing is added to the
654
+ conversation: the person said nothing new). Reject only when the answers could not be sent (nothing started): the card then opens again. While a
655
+ request is on its way, or when the card was answered already, a second press does nothing.
656
+ - **Written in the chat instead.** A message written while the card waits (it is the newest message of the conversation, and nothing was done with
657
+ it) **skips every question**: the card is drawn as skipped in that very pass (and after a reload), and `onSendMessage` gets
658
+ `options.questionAnswers`, one answer for each question, **all empty**. The host sends the message as the **prompt** along with them, so the
659
+ assistant decides the skipped questions itself and **the message is what it goes on with**. The chat looks for the waiting card before it adds the
660
+ message, so the order of the two never matters.
661
+ - **What the card is.** `questionCardStateOf(messages, index)` says it from the messages alone: **open** (the newest message, no result),
662
+ **answered** (a result with picks), **skipped** (a result with no pick, or a message of the person right after it, which is also known after a reload),
663
+ or **closed** (answered, with the picks not known: a reload brings back the card the gateway saved, and not what was picked, so it is drawn as the plain
664
+ words it was saved with). An open card keeps the turn waiting for an answer, in either layout (the panel draws it too).
665
+ - **A reload in the same session keeps the picks.** `Chat.reloadConversationMessages` (a host calls it a moment after a build, to read the
666
+ conversation back) carries the picks of the session over to the rows the server saved: a loaded card that asks the same questions as a local card with
667
+ a result gets that result back (`keepLocalQuestionCards(loaded, local)`, exported for a host that keeps its own list). Only a reload of the page loses
668
+ them, and then the card reads as **closed**.
669
+ - **No "in progress" line above the card.** A run that ends by asking questions builds nothing, so `addQuestionCardMessage` first takes the in-flight
670
+ status lines of the turn ("Code generation in progress…", "Planning…") out of the conversation (they are local and are never saved).
671
+ Do not update the status line of the chat after the card was added: that adds a message to the turn when it has none, and the card is then no
672
+ longer the newest message, so it would no longer be open.
673
+ - **Saved.** The gateway saves the card with its reply (the `clarification` of the message's `generation_surface`), so a host that maps saved
674
+ messages gives it back with `questionCardFromClarification(…)` as the message's `questionCard`. Pass `skipPersist` when the gateway already saved
675
+ the reply (it does), so the chat does not save a second one. `questionCardPlainText(card)` is the words the card is saved with.
676
+ - **Needs** a design-system release with `QuestionCardSummary`, the `nextSkips` prop and the second argument of `onSubmit` (the picks of every
677
+ question): raise the `@widgetic/design-system` peer dependency to it. A page that does not pass `onQuestionsAnswered` still shows the card, but
678
+ answering it in the card sends nothing.
679
+ sibling `brand` checkout when it is there, and answers on `window.__agentDemo` for scripted checks. Query: `scenario=success|failure|question|stopped|plain`,
680
+ `run=1`, `step=1`, `speed=4`, `panel=0`, `rtl=1`, `mascot=0`, `sound=0`, `people=0`, `tight=0`, `suggest=1` (see below).
681
+
682
+ ### Suggestions after the caret (ghost text)
683
+
684
+ The message box can show a likely continuation of what is typed, in grey after the caret: type "build a v" and "ideo player" appears, type on
685
+ "with th" and "umbnails" does. The suggestion is set in the box's own font, size and line (only the colour is muted), so it reads as the rest of
686
+ what is being typed. **Tab** takes it (a tap on it does, on a touch screen), **Esc** sends it away, typing on along it follows it with no new
687
+ request, and typing something else, or putting the caret anywhere but the end of the text, lets it go. **Enter still sends**, and the suggestion
688
+ goes with the message. While a suggestion shows, the toolbar says what to do with it ("Tab to accept", or "Tap the suggestion to accept" on a
689
+ touch screen) **until the person has taken one suggestion**: after the first Tab (or tap) that hint stays away for good in that browser (the
690
+ design system keeps one small note in `localStorage`, or on the page when the browser gives none). A screen reader always hears the sentence
691
+ with the suggestion in it, and how to take it. After three dismissals in a row the box stops suggesting for the rest of the session.
692
+
693
+ The chat does not know where suggestions come from. The page gives a **`completion`** prop, an object with a `source` (anything with
694
+ `suggest({ text, signal })`, which answers with the continuations best first), and a page that gives none sees no change: nothing is drawn and
695
+ nothing is asked. The engine, the HTTP source for the Widgetic gateway and the reporter of what people did with the suggestions are the design
696
+ system's, from `@widgetic/design-system/inline-completion`.
697
+
698
+ ```svelte
699
+ <script lang="ts">
700
+ import { Chat } from '@widgetic/chat';
701
+ import { createHttpCompletionSource, createOutcomeReporter } from '@widgetic/design-system/inline-completion';
702
+
703
+ const outcomes = createOutcomeReporter({ surface: 'creator_chat', url: `${gatewayUrl}/agent/composer/outcome` });
704
+
705
+ const completion = {
706
+ source: createHttpCompletionSource({
707
+ url: `${gatewayUrl}/agent/composer/suggest`,
708
+ // Only what the page knows: the text typed is added to the body by the source
709
+ body: () => ({ surface: 'creator_chat', language: 'en' })
710
+ }),
711
+ // What happened to each suggestion (shown, accepted, dismissed, typed past): counts only, never the text
712
+ onEvent: (event) => outcomes.record(event)
713
+ };
714
+ </script>
715
+
716
+ <Chat {context} {completion} />
717
+ ```
718
+
719
+ | Field of `completion` | What it does |
720
+ | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
721
+ | `source` | Answers for the text typed. `null` or left out: no suggestions. Never has to be fast: a suggestion that arrives late is dropped if the text moved on. |
722
+ | `onEvent` | Hears `shown`, `accepted`, `dismissed`, `diverged` and `paused`, for the page's own measuring. |
723
+ | `debounceMs` | The pause in typing before a request is made. Default 150. |
724
+ | `dismissalLimit` | How many dismissals in a row stop the suggestions for the session. Default 3. |
725
+ | `log` | Hears a debug line per transition. Default: `console.debug` with the `[inline-completion]` prefix. |
726
+
727
+ The hint's two sentences are the catalog's `chat.input.completionHint` and `chat.input.completionHintTouch`, so a page that translates the
728
+ chat (see Languages) translates them. They are shown for the first suggestion only (see above); to see them again in a browser, run
729
+ `localStorage.removeItem('widgetic:completion-hint-learned:v1')` in its console. `ChatComposer` takes the same `completion` prop for a page that builds its own panel.
730
+
731
+ To try it, run `npm run dev` and open `/agent?suggest=1` (or tick "Ghost-text suggestions" in its options): the page gives the chat a pretend
732
+ source with a few phrases, so typing "build a v" and pressing Tab writes "build a video player with thumbnails". The page needs a built design
733
+ system (`npm run package` in the design-system checkout) that has the `inline-completion` export.
734
+
735
+ ### Referring to attached files with `#`
736
+
737
+ A message can point at a file that is attached to it. Type **#** in the message box and the files of the tray open as a list, each with its
738
+ picture, its name and its size; the arrow keys and Enter (or a click) pick one, **Esc** closes the list. The pick becomes a **badge** in the
739
+ text: the file's picture, its label (`#hero_banner`) and an X that takes the badge out. Typing the start of a label, of a file name or a tray
740
+ number after the `#` narrows the list. What is sent is the plain text (`#hero_banner`), so a message reads the same wherever it is shown, and
741
+ the files it names go with it. While a file is attached, a line under the box says so ("Type # to reference an attached file").
742
+
743
+ - **Labels.** A file is called by the words of its name: `hero-banner-final.png` is `#hero_banner_final`, and a second file of that name is
744
+ `#hero_banner_final_2`. A name that says nothing (a screenshot, a camera's name, a paste) is `#Image_1`, `#Image_2` and so on, in the order the
745
+ files were attached; a number is not used twice in one draft, even after its file left the tray.
746
+ - **Which files.** The pictures. A page that wants other files gives `isReferenceableAttachment={(attachment) => boolean}`. `maxReferences`
747
+ caps how many files one message may name (no cap unless the page gives one; the first ones the text names are kept).
748
+ - **What the page gets.** Each outgoing attachment of `onSendMessage` carries the `referenceLabel` it was called by, and the third argument has
749
+ `options.references`: an `{ id, label }` for each file the text names, once each, in the order the text names them (`id` is the id of the
750
+ upload once it has ended, the label until then). A `#label` typed by hand names a file as well as a badge does. A message that names no file
751
+ has no `options.references`, and a page that does not read it sees no change.
752
+ - **Taking a file out** of the tray takes its badges out of the text; a `#label` typed by hand stays as it is.
753
+ - **A restored draft.** Restored pictures (`restoreAttachmentsFromDataUrls`) are called `#Image_N`, in the order they were asked for and above
754
+ the numbers the restored text (`setDraftText`) already names; the page may ask for the text and the pictures in either order. Once the
755
+ pictures are in, a restored picture that answers to a word the text names is called something else, and a badge whose file is not attached
756
+ is plain `#label` text again: no word of a restored draft is tied to a picture by luck.
757
+ - **Ghost-text suggestions never see a file's name.** With `completion` on, each reference reaches the source as the neutral word `#file`.
758
+ - The tray rings the tile of the file a badge, or a row of the list, is on.
759
+ - Catalog: `chat.input.referenceHint`, `chat.input.referenceMenuLabel` ("Attached files") and `chat.input.referenceRemove` ("Remove {name}").
760
+ `ChatComposer` takes `referenceItems`, `maxReferences` and `onReferenceHover` for a page that builds its own panel.
761
+
762
+ Needs a design system with the `Composer`'s `references` prop (`npm run package` in the design-system checkout).
763
+ sibling `brand` checkout when it is there, and answers on `window.__agentDemo` for scripted checks. Query: `scenario=success|failure|earlyFailure|question|stopped|plain`,
764
+ `run=1`, `step=1`, `speed=4`, `panel=0`, `rtl=1`, `mascot=0`, `sound=0`, `people=0`, `tight=0`, `files=1` (sent messages that name their pictures, and some that must not) and `badges=0`.
360
765
 
361
766
  ## Languages
362
767
 
@@ -404,6 +809,7 @@ console.log(CHAT_MESSAGES['chat.attachment.more']); // '{count, plural, one {+#
404
809
  | `chat.messages.` | the list of messages: the empty state, "thinking", the icons (copy, regenerate, restore, thumbs), versions and commit ids |
405
810
  | `chat.input.`, `chat.actions.` | the box you type in, and the screenshot, record, upload and "mark complete" buttons |
406
811
  | `chat.suggestions.` | the ideas offered to start with (five for each kind of thing a chat is about) and their headings |
812
+ | `chat.followUp.` | the follow-up card under the last reply (the name of the cross of a pill; its heading is `chat.suggestions.title.tryNext`) |
407
813
  | `chat.attachment.`, `chat.size.` | attachments, and file sizes ("1.5 MB") |
408
814
  | `chat.status.`, `chat.code.`, `chat.resize.` | the status of a conversation, the code blocks and the drag handle |
409
815
  | `chat.error.` | the sentences of the red banner, and its "Retry load history" button |
@@ -470,6 +876,55 @@ it reads the language of that chat, so two chats on one page can speak two langu
470
876
  - **Videos**: MP4 (max 100MB)
471
877
  - **Documents**: PDF, TXT, MD, .mermaid (max 25MB)
472
878
 
879
+ ### Pasting into the message box
880
+
881
+ What a person copies can be pasted into the message box, and it is attached the way a file dropped on the box is, with the same tile in the tray
882
+ (and uploaded and sent like a dropped file, through `onUploadChatFile` and `onSendMessage`):
883
+
884
+ - **A screenshot**, or a picture copied from a page, becomes an image attachment. A file copied in the file manager is attached as that file.
885
+ - **A long text** (500 characters or more, or 12 lines or more), like a reply copied from a chat, becomes a text file, `pasted-text.txt`, and its
886
+ tile says the first words of the text. A host that reads text documents (the Widget Creator does) gives its words to the model.
887
+ - **A short text** is not attached: the browser types it into the box, as it always did.
888
+
889
+ When a picture and a text come together (a spreadsheet writes its cells as a text and as a picture), the text is what was copied: a long one is
890
+ attached as a text file, a short one goes into the box. The name or the link of a copied file, which come as a text next to it, do not count as a text.
891
+
892
+ Every paste is an attachment of its own: three screenshots and two long texts pasted one after another are five tiles, in the order they were pasted,
893
+ and none replaces, joins or hides another. Each is uploaded by itself (one can be taken out while the others are still uploading) and goes to the host
894
+ as its own attachment, with its own stored address and upload id. Files that would share a name are told apart by it, counting the files already in the
895
+ tray: the second screenshot is `image-2.png`, the third `image-3.png`, and a second long text is `pasted-text-2.txt`. A host that reads text documents
896
+ (the Widget Creator does) names each one by its file name, which is why two texts that were both `pasted-text.txt` could not be told apart.
897
+
898
+ A large picture is made smaller before it is uploaded, the way a dropped or picked one is (its long edge is brought to 1568 px and the file to about 1.5 MB,
899
+ by `prepareChatImageFileForUpload`; a small one is left as it is, and a picture made smaller is named by what it became, `image.png` → `image.jpg`). This holds
900
+ for a screenshot pasted into the box and for the pictures a page hands to `addImageAttachment` (the Widget Creator catches a screenshot pasted in its panel
901
+ and does that). A big picture takes longer to prepare than a small one, but the tiles still come in the order of the pastes (a text pasted after a screenshot
902
+ waits for the screenshot's tile), and the uploads still run side by side. A picture that cannot be made ready, or is not ready after 15 seconds, is attached as it
903
+ came: a paste is never lost for that, and a picture that never gets ready cannot hold up the pastes after it.
904
+
905
+ Pasting follows the "+" button: it is on unless `config.features.fileUpload` is `false`, and then the box pastes as the browser does. The name of the
906
+ file never says what is in the text (it is the name the server stores the file under), and the first words are only the label of the tile.
907
+
908
+ A page with a message box of its own can use the same rules:
909
+
910
+ ```typescript
911
+ import { attachmentsFromPaste } from '@widgetic/chat';
912
+
913
+ box.addEventListener('paste', (event) => {
914
+ // [{ file, label? }]: empty for an ordinary paste. A second argument ({ minCharacters, minLines }) sets how long a text must be.
915
+ const pasted = attachmentsFromPaste(event.clipboardData);
916
+ if (pasted.length === 0) return; // let the browser paste
917
+ event.preventDefault();
918
+ attach(pasted.map(({ file }) => file));
919
+ });
920
+ ```
921
+
922
+ In a box of your own, two pastes are told apart the same way: `withUniqueFileNames(pasted, namesInTheBox)` gives each pasted file a name that no file
923
+ in the box (and no other file of the paste) has, and `uniqueFileName(name, takenNames)` does it for one name. `prepareImagesOfPaste(pasted, prepareImage)`
924
+ makes the pictures of a paste ready with the function you give it (one that calls `compressImage`, below, say), all at once and in the order of the paste: a
925
+ text or any file that is not a picture is left as it is, and so is a picture that cannot be prepared or is not ready after 15 seconds (a third argument, in
926
+ milliseconds, changes that limit).
927
+
473
928
  ### File Utilities
474
929
 
475
930
  ```typescript