@widgetic/chat 0.1.41 → 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 (87) hide show
  1. package/README.md +461 -6
  2. package/dist/components/Chat.svelte +1117 -119
  3. package/dist/components/Chat.svelte.d.ts +112 -2
  4. package/dist/components/ChatComposer.svelte +389 -8
  5. package/dist/components/ChatComposer.svelte.d.ts +71 -2
  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/SelectedElementChip.svelte +73 -0
  21. package/dist/components/SelectedElementChip.svelte.d.ts +20 -0
  22. package/dist/components/agent/AgentAvatar.svelte +6 -4
  23. package/dist/components/agent/AgentAvatar.svelte.d.ts +1 -1
  24. package/dist/components/agent/CodeCard.svelte +122 -27
  25. package/dist/components/agent/CodeCard.svelte.d.ts +3 -0
  26. package/dist/components/agent/CodeDiff.svelte +180 -0
  27. package/dist/components/agent/CodeDiff.svelte.d.ts +10 -0
  28. package/dist/components/agent/GenerationModule.svelte +13 -2
  29. package/dist/components/agent/GenerationModule.svelte.d.ts +3 -0
  30. package/dist/components/index.d.ts +5 -0
  31. package/dist/components/index.js +12 -0
  32. package/dist/errors/logTechnicalUserError.d.ts +1 -0
  33. package/dist/errors/logTechnicalUserError.js +37 -0
  34. package/dist/i18n/messages.d.ts +106 -1
  35. package/dist/i18n/messages.js +112 -1
  36. package/dist/i18n/sketchLocales.js +8 -8
  37. package/dist/messageQueue.d.ts +83 -0
  38. package/dist/messageQueue.js +84 -0
  39. package/dist/services/sketchAssistantClient.js +6 -2
  40. package/dist/services/sketchAssistantErrors.d.ts +4 -0
  41. package/dist/services/sketchAssistantErrors.js +22 -0
  42. package/dist/services/sketchAssistantOrchestrator.d.ts +1 -6
  43. package/dist/services/sketchAssistantOrchestrator.js +10 -24
  44. package/dist/services/sketchAssistantReply.js +3 -1
  45. package/dist/stores/chatStore.d.ts +5 -0
  46. package/dist/stores/chatStore.js +21 -0
  47. package/dist/types/agent.d.ts +4 -3
  48. package/dist/types/attachment.d.ts +16 -0
  49. package/dist/types/config.d.ts +6 -0
  50. package/dist/types/index.d.ts +1 -0
  51. package/dist/types/index.js +2 -0
  52. package/dist/types/mention.d.ts +40 -0
  53. package/dist/types/mention.js +8 -0
  54. package/dist/types/message.d.ts +60 -1
  55. package/dist/utils/agentTurn.d.ts +40 -9
  56. package/dist/utils/agentTurn.js +43 -11
  57. package/dist/utils/attachmentProgress.d.ts +12 -0
  58. package/dist/utils/attachmentProgress.js +18 -0
  59. package/dist/utils/bubbleRichFit.d.ts +68 -0
  60. package/dist/utils/bubbleRichFit.js +45 -0
  61. package/dist/utils/bubbleShrinkWrap.d.ts +8 -1
  62. package/dist/utils/bubbleShrinkWrap.js +113 -17
  63. package/dist/utils/codeChanges.d.ts +103 -0
  64. package/dist/utils/codeChanges.js +226 -0
  65. package/dist/utils/codeHighlight.js +1 -0
  66. package/dist/utils/codeStreamFormat.d.ts +5 -2
  67. package/dist/utils/composerMentions.d.ts +96 -0
  68. package/dist/utils/composerMentions.js +217 -0
  69. package/dist/utils/followUps.d.ts +74 -0
  70. package/dist/utils/followUps.js +116 -0
  71. package/dist/utils/generationArchiveStore.d.ts +6 -0
  72. package/dist/utils/generationArchiveStore.js +11 -3
  73. package/dist/utils/index.d.ts +14 -0
  74. package/dist/utils/index.js +22 -0
  75. package/dist/utils/orderedLine.d.ts +29 -0
  76. package/dist/utils/orderedLine.js +17 -0
  77. package/dist/utils/pastedContent.d.ts +99 -0
  78. package/dist/utils/pastedContent.js +258 -0
  79. package/dist/utils/questionCards.d.ts +131 -0
  80. package/dist/utils/questionCards.js +287 -0
  81. package/dist/utils/referenceItems.d.ts +36 -0
  82. package/dist/utils/referenceItems.js +56 -0
  83. package/dist/utils/selectedElementChip.d.ts +47 -0
  84. package/dist/utils/selectedElementChip.js +73 -0
  85. package/dist/utils/sentReferenceBadges.d.ts +26 -0
  86. package/dist/utils/sentReferenceBadges.js +32 -0
  87. package/package.json +1 -1
@@ -1,3 +1,4 @@
1
+ import { readCodeChanges } from './codeChanges.js';
1
2
  /** A turn that is not the newest, or has nothing to say about itself: small, still, calm. */
2
3
  const RESTING_STILL_LOOK = { state: 'idle', size: 'small', live: false };
3
4
  /**
@@ -45,9 +46,18 @@ export function turnOutcome(replies, generationRanForTurn) {
45
46
  return 'answer';
46
47
  }
47
48
  /**
48
- * The look of a turn that is not running. Only the newest turn moves, and only its conclusion is large (the success or
49
- * the error avatar, or a question to answer): older turns are small still pictures, so a long chat keeps one mascot
50
- * alive instead of one per message.
49
+ * The look of a turn that is not running. Only the newest turn moves, and only its conclusion is large (the success avatar,
50
+ * or a question to answer): older turns are small still pictures, so a long chat keeps one mascot alive instead of one per
51
+ * message.
52
+ *
53
+ * A failure is the one conclusion that does not move: its avatar sits SMALL and STILL in its red error look, and keeps it until
54
+ * the person tries again or sends another message. The turn is then no longer the newest, so it falls back to the quiet picture of
55
+ * every older turn, and the new run brings its own live avatar.
56
+ *
57
+ * - Small, so that the line saying what went wrong sits where the text of any turn sits (an avatar that was large while the run
58
+ * waited glides down to it), and the top of the avatar is the top of that line.
59
+ * - Still, because the mascot's own error is a one-shot that rests back to idle within a second: left to play it would turn
60
+ * the avatar blue again, and a red look that is held can only be a picture.
51
61
  */
52
62
  export function settledAgentLook(outcome, isNewestTurn) {
53
63
  if (!isNewestTurn)
@@ -56,7 +66,7 @@ export function settledAgentLook(outcome, isNewestTurn) {
56
66
  case 'success':
57
67
  return { state: 'success', size: 'large', live: true };
58
68
  case 'error':
59
- return { state: 'error', size: 'large', live: true };
69
+ return { state: 'error', size: 'small', live: false };
60
70
  case 'question':
61
71
  return { state: 'idle', size: 'large', live: true };
62
72
  case 'stopped':
@@ -68,8 +78,9 @@ export function settledAgentLook(outcome, isNewestTurn) {
68
78
  /**
69
79
  * The live avatar of a run and the one of its ending are two avatars, one after the other, in the same place. The second one starts
70
80
  * from how the first one looked when the run ended, so what the person watched carries on instead of being swapped: a Stop pressed
71
- * while the avatar is still large shrinks it down to its small size, and the mascot calms from what it was doing; a conclusion
72
- * grows out of the avatar of the work.
81
+ * while the avatar is still large shrinks it down to its small size, and the mascot calms from what it was doing; so does a failure
82
+ * that ends a run while it waits, which glides down to the small avatar that holds the red look; a success grows out of the avatar
83
+ * of the work.
73
84
  *
74
85
  * Without a live avatar to take over from (the conversation was opened or reloaded after the run) it starts from the small one,
75
86
  * which is where a conclusion has always grown out of.
@@ -160,14 +171,17 @@ export function liveModulesView(phase) {
160
171
  return NOTHING_SHOWN;
161
172
  }
162
173
  }
163
- /** The modules under a conclusion: whatever was kept, closed, for the person to open. */
174
+ /**
175
+ * The modules under a conclusion: whatever was kept, closed, for the person to open. The code card shows when there is code to
176
+ * show or changes to show (a round whose stream left no code, but whose changes the gateway sent, still has its card).
177
+ */
164
178
  export function finishedModulesView(finished) {
165
179
  if (!finished)
166
180
  return NOTHING_SHOWN;
167
181
  return {
168
182
  ...NOTHING_SHOWN,
169
183
  showThinking: finished.thinking.trim().length > 0,
170
- showCode: finished.code.trim().length > 0
184
+ showCode: finished.code.trim().length > 0 || (finished.changes?.files.length ?? 0) > 0
171
185
  };
172
186
  }
173
187
  /**
@@ -182,19 +196,37 @@ export const MAX_KEPT_GENERATION_CHARS = 120_000;
182
196
  export function normalizePromptText(content) {
183
197
  return (content ?? '').replace(/\s+/g, ' ').trim();
184
198
  }
185
- /** What to keep of a generation that ended, or null when it left nothing to show. */
199
+ /**
200
+ * What to keep of a generation that ended, or null when it left nothing to show. `changes` is whatever the page gave as the
201
+ * changes of the run: it is read here (a part that is not usable is dropped), so what is kept is always plain, bounded data.
202
+ */
186
203
  export function keepFinishedGeneration(input) {
187
204
  const thinking = input.thinking.slice(-MAX_KEPT_GENERATION_CHARS);
188
205
  const code = input.code.slice(-MAX_KEPT_GENERATION_CHARS);
189
- if (thinking.trim().length === 0 && code.trim().length === 0)
206
+ const changes = readCodeChanges(input.changes);
207
+ if (thinking.trim().length === 0 && code.trim().length === 0 && changes === null)
190
208
  return null;
191
209
  return {
192
210
  prompt: normalizePromptText(input.promptText),
193
211
  thinking,
194
212
  code,
195
- thoughtSeconds: input.thoughtSeconds
213
+ thoughtSeconds: input.thoughtSeconds,
214
+ changes
196
215
  };
197
216
  }
217
+ /**
218
+ * The kept work of a run with the changes of that run put into it, for a page that gives the changes AFTER the run ended. The
219
+ * gateway sends them with the completed operation, and a page that lets the chat take the next message as soon as the preview is
220
+ * up (the widget creator does) lowers `isGenerating` before that. The changes are read here like those of `keepFinishedGeneration`.
221
+ * It gives back the very same object when there is nothing to put in (the work has changes already, or what was given is not
222
+ * usable), so the caller can tell by identity that nothing changed.
223
+ */
224
+ export function withChangesOfTheRun(finished, changes) {
225
+ if (finished.changes && finished.changes.files.length > 0)
226
+ return finished;
227
+ const readChanges = readCodeChanges(changes);
228
+ return readChanges === null ? finished : { ...finished, changes: readChanges };
229
+ }
198
230
  /** Whether the kept work belongs under the turn of this prompt: the newest turn, found again by the words of its prompt. */
199
231
  export function finishedGenerationBelongsTo(finished, newestTurnPromptText) {
200
232
  if (!finished)
@@ -0,0 +1,12 @@
1
+ /**
2
+ * How far a file of the composer tray has gone up, as the share its chip draws as its own background (the design system's
3
+ * `Chip` takes `progress`, from 0 to 100, and fills from the start edge behind the name).
4
+ *
5
+ * The chip draws it only while the file is going up: nothing sent yet (0: it waits, or an upload failed and was reset) and
6
+ * everything sent (100: it is done) draw no fill. It is the rule the tile of a picture follows for its thin bar, so a file and
7
+ * a picture of the same tray agree on when an upload is showing.
8
+ *
9
+ * @param uploadProgress The `uploadProgress` of the attachment: a percentage, or nothing for a file that never went up.
10
+ * @returns The share to draw, or `undefined` when the chip has no progress to show.
11
+ */
12
+ export declare function attachmentChipProgress(uploadProgress: number | null | undefined): number | undefined;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * How far a file of the composer tray has gone up, as the share its chip draws as its own background (the design system's
3
+ * `Chip` takes `progress`, from 0 to 100, and fills from the start edge behind the name).
4
+ *
5
+ * The chip draws it only while the file is going up: nothing sent yet (0: it waits, or an upload failed and was reset) and
6
+ * everything sent (100: it is done) draw no fill. It is the rule the tile of a picture follows for its thin bar, so a file and
7
+ * a picture of the same tray agree on when an upload is showing.
8
+ *
9
+ * @param uploadProgress The `uploadProgress` of the attachment: a percentage, or nothing for a file that never went up.
10
+ * @returns The share to draw, or `undefined` when the chip has no progress to show.
11
+ */
12
+ export function attachmentChipProgress(uploadProgress) {
13
+ if (typeof uploadProgress !== 'number' || !Number.isFinite(uploadProgress))
14
+ return undefined;
15
+ if (uploadProgress <= 0 || uploadProgress >= 100)
16
+ return undefined;
17
+ return uploadProgress;
18
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Tight chat bubbles for a message that holds file badges, apart from the page.
3
+ *
4
+ * A message that names an attached file shows the name as a badge: a small pill with the file's picture and `#name`, drawn as an
5
+ * inline box in the middle of the text. Pretext's plain text measuring cannot see a box, so such a bubble is measured as RICH inline
6
+ * text (`@chenglou/pretext/rich-inline`, the recipe of its rich-note demo): the runs between the badges as text in the bubble's font,
7
+ * and each badge as one box of the width it is drawn with. A box is atomic: a line can break on either side of it, never inside.
8
+ *
9
+ * This file makes the items to measure and puts the measuring in the shape `findTightTextWidth` already searches (`BubbleTextEngine`),
10
+ * so the search and the check against the browser are the ones plain bubbles use. It imports nothing from Pretext or the page, so it
11
+ * runs in Node and is tested there with a fake measurer. The browser side is `bubbleShrinkWrap.ts`.
12
+ */
13
+ import type { BubbleTextEngine, WrapStats } from './bubbleFit.js';
14
+ /** One item Pretext's rich inline lays out. A run of text in a font, or a box that is a number of px wide (a badge). */
15
+ export type RichBubbleItem = {
16
+ text: string;
17
+ font: string;
18
+ letterSpacing?: number;
19
+ } | {
20
+ width: number;
21
+ };
22
+ /** The text of a message cut into runs and badges, as the design system's `segmentSentText` gives it. Only what is read here. */
23
+ export type RichBubbleSegment = {
24
+ kind: 'text';
25
+ text: string;
26
+ } | {
27
+ kind: 'badge';
28
+ word: string;
29
+ };
30
+ export interface RichBubbleItemOptions {
31
+ /** The canvas font of the text (`500 14px Inter, sans-serif`): the runs are measured in it, and so is the label of a badge. */
32
+ font: string;
33
+ /** The letter spacing of the text, in px. `0` for none. */
34
+ letterSpacing: number;
35
+ /**
36
+ * The width, in whole px, of the badge that says `word` (`#hero`): the pill, its picture's room and the label as the font measures
37
+ * it. The page writes the very same number on the badge, so what is measured here is what is drawn.
38
+ */
39
+ badgeWidthOf: (word: string) => number;
40
+ /** The room of the text, in px. A badge is never wider than it (the pill's `max-width: 100%`), so a long label cannot ask for more. */
41
+ maxBadgeWidth: number;
42
+ }
43
+ /** What `richBubbleItems` makes. */
44
+ export interface RichBubbleItems {
45
+ /** The items for `prepareRichInline`, in the order of the message. */
46
+ items: RichBubbleItem[];
47
+ /** The width of each badge, in the order of the message: what the page writes on the badges' elements. */
48
+ badgeWidths: number[];
49
+ }
50
+ /**
51
+ * The items of a message: each text run is a text item in the bubble's font, each badge a box. A box is passed as
52
+ * `{ width }` (its element's margin box, which for a badge is its width: it has no margin), and its width is whole pixels.
53
+ */
54
+ export declare function richBubbleItems(segments: readonly RichBubbleSegment[], options: RichBubbleItemOptions): RichBubbleItems;
55
+ /** What the engine needs from a prepared rich text: Pretext's `measureRichInlineStats` answers it, a fake one does in the tests. */
56
+ export interface RichBubbleMeasurer {
57
+ /** How the text wraps in a box this wide. */
58
+ measureStats(width: number): WrapStats;
59
+ }
60
+ /**
61
+ * A width so large that nothing wraps in it: the widest line there is the widest line when only the explicit line breaks apply
62
+ * (CSS `max-content`), which is what plain bubbles ask Pretext's `measureNaturalWidth` for.
63
+ */
64
+ export declare const RICH_NATURAL_WIDTH_PROBE_PX = 1000000;
65
+ /** The same answers the plain engine gives, from a rich text: the width without wrapping, and how it wraps at a width. */
66
+ export declare function richBubbleEngine(measurer: RichBubbleMeasurer): BubbleTextEngine;
67
+ /** Whether a message's segments call for the rich measuring: at least one badge. Plain text keeps the plain engine. */
68
+ export declare function hasRichBubbleBadges(segments: readonly RichBubbleSegment[] | null | undefined): boolean;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The items of a message: each text run is a text item in the bubble's font, each badge a box. A box is passed as
3
+ * `{ width }` (its element's margin box, which for a badge is its width: it has no margin), and its width is whole pixels.
4
+ */
5
+ export function richBubbleItems(segments, options) {
6
+ const items = [];
7
+ const badgeWidths = [];
8
+ const widestBadge = Number.isFinite(options.maxBadgeWidth) ? Math.max(1, Math.floor(options.maxBadgeWidth)) : Number.POSITIVE_INFINITY;
9
+ for (const segment of segments) {
10
+ if (segment.kind === 'badge') {
11
+ const measured = options.badgeWidthOf(segment.word);
12
+ // A measurement that is not a number leaves the bubble to CSS: the caller sees the throw and gives up on this bubble
13
+ if (!Number.isFinite(measured) || measured < 0)
14
+ throw new Error(`The badge "${segment.word}" has no usable width (${String(measured)}).`);
15
+ const width = Math.min(Math.ceil(measured), widestBadge);
16
+ badgeWidths.push(width);
17
+ items.push({ width });
18
+ }
19
+ else if (segment.text !== '') {
20
+ // A carriage return is read as the line break it stands for, as plain bubbles read their text
21
+ const text = segment.text.replace(/\r\n?/g, '\n');
22
+ items.push(options.letterSpacing !== 0
23
+ ? { text, font: options.font, letterSpacing: options.letterSpacing }
24
+ : { text, font: options.font });
25
+ }
26
+ }
27
+ return { items, badgeWidths };
28
+ }
29
+ /**
30
+ * A width so large that nothing wraps in it: the widest line there is the widest line when only the explicit line breaks apply
31
+ * (CSS `max-content`), which is what plain bubbles ask Pretext's `measureNaturalWidth` for.
32
+ */
33
+ export const RICH_NATURAL_WIDTH_PROBE_PX = 1_000_000;
34
+ /** The same answers the plain engine gives, from a rich text: the width without wrapping, and how it wraps at a width. */
35
+ export function richBubbleEngine(measurer) {
36
+ const unwrapped = measurer.measureStats(RICH_NATURAL_WIDTH_PROBE_PX);
37
+ return {
38
+ naturalWidth: unwrapped.maxLineWidth,
39
+ measureWrap: (width) => measurer.measureStats(width)
40
+ };
41
+ }
42
+ /** Whether a message's segments call for the rich measuring: at least one badge. Plain text keeps the plain engine. */
43
+ export function hasRichBubbleBadges(segments) {
44
+ return !!segments && segments.some((segment) => segment.kind === 'badge');
45
+ }
@@ -1,9 +1,16 @@
1
+ import { type SentSegment } from '@widgetic/design-system/prompt-references';
1
2
  /** What the action takes. */
2
3
  export interface ShrinkWrapOptions {
3
4
  /** The text the bubble shows. The width is read from what is laid out; a change of the text is what makes the bubble measured again. */
4
5
  text: string;
5
6
  /** Turns it off: the bubble goes back to the width CSS gives it. Default true. */
6
7
  enabled?: boolean;
8
+ /**
9
+ * The text cut into plain runs and file badges (the design system's `segmentSentText`), when the message draws badges in it. The
10
+ * element then holds one element marked `data-sent-badge` for each badge, in order, and the bubble is measured as rich inline
11
+ * text: the runs as text and each badge as a box. Without badges (or without this), the text is measured as plain text.
12
+ */
13
+ parts?: readonly SentSegment[] | null;
7
14
  }
8
15
  /**
9
16
  * What is held on to right now, for tests and the demo page: when every chat is gone all of it must be back to zero, which is how
@@ -21,7 +28,7 @@ export declare function getBubbleShrinkWrapStats(): {
21
28
  * text (`<p class="whitespace-pre-wrap">`), inside a bubble as wide as its content, and mark the row the bubble sits in with
22
29
  * `data-bubble-row` (the element whose width is the room of the bubble; without one, the element's parent stands for it).
23
30
  *
24
- * Plain text only: a bubble with code blocks or other widgets in it keeps the width CSS gives it.
31
+ * Plain text only (and file badges, with `parts`): a bubble with code blocks or other widgets in it keeps the width CSS gives it.
25
32
  *
26
33
  * @example
27
34
  * <p class="whitespace-pre-wrap" use:shrinkWrapBubble={{ text: message.content, enabled: tightBubbles }}>{message.content}</p>
@@ -1,9 +1,18 @@
1
+ import { sentBadgeWidth } from '@widgetic/design-system/prompt-references';
1
2
  import { chatLog, chatWarn } from './logger.js';
2
3
  import { buildCanvasFont, countLinesByTops, findTightTextWidth, letterSpacingInPixels, widerWidthsToTry } from './bubbleFit.js';
4
+ import { hasRichBubbleBadges, richBubbleEngine, richBubbleItems } from './bubbleRichFit.js';
3
5
  /** An attribute the width given to a bubble can be told by: `tight` or `css` (left to CSS). Handy to look at in a browser. */
4
6
  const FIT_ATTRIBUTE = 'data-bubble-fit';
5
7
  /** What marks the element whose width is the room of the bubbles in it (the row the bubble sits in with the avatar of its author). */
6
8
  const ROW_ATTRIBUTE = 'data-bubble-row';
9
+ /** What marks the element of one file badge inside a bubble's text (`ChatMessages.svelte` puts it there): its width is written here. */
10
+ const BADGE_ATTRIBUTE = 'data-sent-badge';
11
+ /**
12
+ * How far two client rectangles of a line may be apart and still be one line, when the line has a badge in it: a badge sits at the top
13
+ * of the line and its text a little lower (half of what the line's height leaves over), so plain text's 3 px is too close.
14
+ */
15
+ const BADGE_LINE_TOLERANCE_PX = 5;
7
16
  const entries = new Set();
8
17
  const entriesOfRow = new Map();
9
18
  const lastWidthOfRow = new Map();
@@ -12,6 +21,7 @@ let scheduledFrame = null;
12
21
  let listeningToFonts = false;
13
22
  let pretextPromise = null;
14
23
  let loadedPretext = null;
24
+ let richInlinePromise = null;
15
25
  /** Each of these is said once, however many bubbles there are. */
16
26
  let loggedFirstFit = false;
17
27
  let loggedUnavailable = false;
@@ -39,6 +49,19 @@ function loadPretext() {
39
49
  }
40
50
  return pretextPromise;
41
51
  }
52
+ /** Pretext's rich inline layout, loaded the first time a bubble with badges needs it, or `null` when it cannot run here. */
53
+ function loadRichInline() {
54
+ if (!richInlinePromise) {
55
+ richInlinePromise =
56
+ typeof window === 'undefined'
57
+ ? Promise.resolve(null)
58
+ : import('@chenglou/pretext/rich-inline').catch((error) => {
59
+ chatWarn('[Chat] Pretext rich inline could not load: bubbles with file badges keep the width CSS gives them.', error);
60
+ return null;
61
+ });
62
+ }
63
+ return richInlinePromise;
64
+ }
42
65
  // --- the frame ----------------------------------------------------------------------------------------------------
43
66
  function scheduleFlush() {
44
67
  if (scheduledFrame !== null || typeof requestAnimationFrame === 'undefined')
@@ -87,10 +110,55 @@ function readBubbleBox(node) {
87
110
  wordBreak
88
111
  };
89
112
  }
90
- /** The tight width of one bubble's text, or `null` to leave the bubble to CSS. */
91
- function computeTightWidth(pretext, entry, box) {
113
+ /** The badge elements inside a bubble's text, in order. */
114
+ function badgeElementsOf(node) {
115
+ return Array.from(node.querySelectorAll(`[${BADGE_ATTRIBUTE}]`));
116
+ }
117
+ /**
118
+ * The tight width of a bubble that draws file badges, and the width of each badge, measured as rich inline text: the runs of the text
119
+ * in the bubble's font, each badge as a box as wide as the badge is drawn. `null` leaves the bubble to CSS (Pretext's rich inline did
120
+ * not load, or the elements are not what the parts say).
121
+ */
122
+ function computeRichFit(pretext, richInline, entry, box) {
123
+ const parts = entry.parts;
124
+ if (!parts || !richInline)
125
+ return null;
126
+ const badgeCount = parts.filter((part) => part.kind === 'badge').length;
127
+ // The page and the parts must agree on how many badges there are, or a width would land on the wrong badge
128
+ if (badgeElementsOf(entry.node).length !== badgeCount)
129
+ return null;
130
+ try {
131
+ const letterSpacingOption = box.letterSpacing !== 0 ? { letterSpacing: box.letterSpacing } : {};
132
+ const { items, badgeWidths } = richBubbleItems(parts, {
133
+ font: box.font,
134
+ letterSpacing: box.letterSpacing,
135
+ // The label of a badge is measured in the font of the text, as the page draws it; the pill adds its rooms
136
+ badgeWidthOf: (word) => sentBadgeWidth(pretext.measureNaturalWidth(pretext.prepare(word, box.font, letterSpacingOption))),
137
+ maxBadgeWidth: box.availableWidth
138
+ });
139
+ const prepared = richInline.prepareRichInline(items, { whiteSpace: box.whiteSpace, wordBreak: box.wordBreak });
140
+ const engine = richBubbleEngine({ measureStats: (width) => richInline.measureRichInlineStats(prepared, width) });
141
+ return { tight: findTightTextWidth(engine, box.availableWidth), badgeWidths };
142
+ }
143
+ catch (error) {
144
+ if (!loggedMeasureFailure) {
145
+ loggedMeasureFailure = true;
146
+ chatWarn('[Chat] A bubble with file badges could not be measured with Pretext, and keeps the width CSS gives it.', error);
147
+ }
148
+ return null;
149
+ }
150
+ }
151
+ /** What is worked out for one bubble, or `null` to leave it to CSS. A plain bubble has no badge widths. */
152
+ function computeFit(pretext, richInline, entry, box) {
92
153
  if (!box)
93
154
  return null;
155
+ if (hasRichBubbleBadges(entry.parts))
156
+ return computeRichFit(pretext, richInline, entry, box);
157
+ const tight = computeTightWidth(pretext, entry, box);
158
+ return { tight, badgeWidths: null };
159
+ }
160
+ /** The tight width of one bubble's text (plain text), or `null` to leave the bubble to CSS. */
161
+ function computeTightWidth(pretext, entry, box) {
94
162
  try {
95
163
  // `prepare()` is the expensive part, done once per text and font; a new width only runs the arithmetic after it
96
164
  const preparedKey = `${box.font}|${box.letterSpacing}|${box.whiteSpace}|${box.wordBreak}|${box.text}`;
@@ -132,11 +200,25 @@ function writeWidth(node, contentWidth, extraWidth) {
132
200
  node.style.maxWidth = '100%';
133
201
  node.setAttribute(FIT_ATTRIBUTE, 'tight');
134
202
  }
203
+ /**
204
+ * Writes the width each badge is measured at onto its element, so that the browser draws what was measured (a label that is a hair wider
205
+ * in the page cannot move a line break). `null`, or a list that does not match the elements, gives the badges back to CSS.
206
+ */
207
+ function writeBadgeWidths(node, badgeWidths) {
208
+ const elements = badgeElementsOf(node);
209
+ const matches = badgeWidths !== null && badgeWidths.length === elements.length;
210
+ elements.forEach((element, index) => {
211
+ if (matches)
212
+ element.style.width = `${badgeWidths[index]}px`;
213
+ else
214
+ element.style.removeProperty('width');
215
+ });
216
+ }
135
217
  /** How many lines the browser made of the text of an element. */
136
- function countRenderedLines(node) {
218
+ function countRenderedLines(node, tolerance) {
137
219
  const range = document.createRange();
138
220
  range.selectNodeContents(node);
139
- return countLinesByTops(Array.from(range.getClientRects(), (rectangle) => rectangle.top));
221
+ return countLinesByTops(Array.from(range.getClientRects(), (rectangle) => rectangle.top), tolerance);
140
222
  }
141
223
  /**
142
224
  * Makes sure that no bubble came out with more lines than Pretext counted (which would be worse than CSS): it widens it a little,
@@ -144,12 +226,13 @@ function countRenderedLines(node) {
144
226
  */
145
227
  function verifyWrapping(measured) {
146
228
  for (const { entry, box, tight } of measured) {
147
- if (countRenderedLines(entry.node) <= tight.lineCount)
229
+ const tolerance = hasRichBubbleBadges(entry.parts) ? BADGE_LINE_TOLERANCE_PX : undefined;
230
+ if (countRenderedLines(entry.node, tolerance) <= tight.lineCount)
148
231
  continue;
149
232
  let fitted = false;
150
233
  for (const widerWidth of widerWidthsToTry(tight.width, box.availableWidth)) {
151
234
  writeWidth(entry.node, widerWidth, box.extraWidth);
152
- if (countRenderedLines(entry.node) <= tight.lineCount) {
235
+ if (countRenderedLines(entry.node, tolerance) <= tight.lineCount) {
153
236
  fitted = true;
154
237
  break;
155
238
  }
@@ -174,10 +257,13 @@ async function flushBubbles() {
174
257
  // Nothing to measure with: hand every bubble back to CSS, once
175
258
  for (const entry of pending) {
176
259
  writeWidth(entry.node, null, 0);
260
+ writeBadgeWidths(entry.node, null);
177
261
  entry.dirty = false;
178
262
  }
179
263
  return;
180
264
  }
265
+ // Pretext's rich inline is only fetched when a bubble has badges to measure
266
+ const richInline = pending.some((entry) => hasRichBubbleBadges(entry.parts)) ? await loadRichInline() : null;
181
267
  // A font that is still loading would be measured as its fallback: its end wakes this up again
182
268
  if (typeof document !== 'undefined' && document.fonts && document.fonts.status === 'loading')
183
269
  return;
@@ -189,14 +275,17 @@ async function flushBubbles() {
189
275
  }
190
276
  // 2) Read: one layout for all of them
191
277
  const boxes = pending.map((entry) => readBubbleBox(entry.node));
192
- // 3) Compute: no DOM in here
193
- const tightWidths = pending.map((entry, index) => computeTightWidth(pretext, entry, boxes[index] ?? null));
194
- // 4) Write: every width
278
+ // 3) Compute: no DOM in here, except to count the badges a bubble has
279
+ const fits = pending.map((entry, index) => computeFit(pretext, richInline, entry, boxes[index] ?? null));
280
+ // 4) Write: every width (the badges' too: the browser then draws the very boxes that were measured)
195
281
  const measured = [];
196
282
  pending.forEach((entry, index) => {
197
283
  const box = boxes[index] ?? null;
198
- const tight = tightWidths[index] ?? null;
284
+ const fit = fits[index] ?? null;
285
+ const tight = fit ? fit.tight : null;
199
286
  writeWidth(entry.node, tight ? tight.width : null, box ? box.extraWidth : 0);
287
+ if (hasRichBubbleBadges(entry.parts))
288
+ writeBadgeWidths(entry.node, fit ? fit.badgeWidths : null);
200
289
  if (box && tight)
201
290
  measured.push({ entry, box, tight });
202
291
  entry.dirty = false;
@@ -205,13 +294,18 @@ async function flushBubbles() {
205
294
  verifyWrapping(measured);
206
295
  if (!loggedFirstFit) {
207
296
  loggedFirstFit = true;
208
- chatLog('[Chat] Bubbles are sized to their text with Pretext.', { bubbles: pending.length, tight: measured.length });
297
+ chatLog('[Chat] Bubbles are sized to their text with Pretext.', {
298
+ bubbles: pending.length,
299
+ tight: measured.length,
300
+ withBadges: pending.filter((entry) => hasRichBubbleBadges(entry.parts)).length
301
+ });
209
302
  }
210
303
  }
211
304
  catch (error) {
212
305
  chatWarn('[Chat] Sizing the bubbles failed: they keep the width CSS gives them.', error);
213
306
  for (const entry of pending) {
214
307
  writeWidth(entry.node, null, 0);
308
+ writeBadgeWidths(entry.node, null);
215
309
  entry.dirty = false;
216
310
  }
217
311
  }
@@ -299,18 +393,18 @@ export function getBubbleShrinkWrapStats() {
299
393
  * text (`<p class="whitespace-pre-wrap">`), inside a bubble as wide as its content, and mark the row the bubble sits in with
300
394
  * `data-bubble-row` (the element whose width is the room of the bubble; without one, the element's parent stands for it).
301
395
  *
302
- * Plain text only: a bubble with code blocks or other widgets in it keeps the width CSS gives it.
396
+ * Plain text only (and file badges, with `parts`): a bubble with code blocks or other widgets in it keeps the width CSS gives it.
303
397
  *
304
398
  * @example
305
399
  * <p class="whitespace-pre-wrap" use:shrinkWrapBubble={{ text: message.content, enabled: tightBubbles }}>{message.content}</p>
306
400
  */
307
401
  export function shrinkWrapBubble(node, options) {
308
402
  let entry = null;
309
- function attach() {
403
+ function attach(parts) {
310
404
  if (entry || typeof window === 'undefined')
311
405
  return;
312
406
  const row = node.closest(`[${ROW_ATTRIBUTE}]`) ?? node.parentElement;
313
- entry = { node, row, dirty: true, preparedKey: '', prepared: null };
407
+ entry = { node, row, dirty: true, preparedKey: '', prepared: null, parts };
314
408
  entries.add(entry);
315
409
  if (row)
316
410
  observeRow(row, entry);
@@ -328,6 +422,7 @@ export function shrinkWrapBubble(node, options) {
328
422
  node.style.removeProperty('width');
329
423
  node.style.removeProperty('max-width');
330
424
  node.removeAttribute(FIT_ATTRIBUTE);
425
+ writeBadgeWidths(node, null);
331
426
  if (entries.size === 0) {
332
427
  stopListeningToFonts();
333
428
  rowObserver?.disconnect();
@@ -338,17 +433,18 @@ export function shrinkWrapBubble(node, options) {
338
433
  }
339
434
  }
340
435
  if (options.enabled !== false)
341
- attach();
436
+ attach(options.parts ?? null);
342
437
  return {
343
438
  update(nextOptions) {
344
439
  if (nextOptions.enabled !== false) {
345
440
  if (entry) {
346
- // A new text (or the same, re-rendered): measured again
441
+ // A new text (or the same, re-rendered), with its badges: measured again
442
+ entry.parts = nextOptions.parts ?? null;
347
443
  entry.dirty = true;
348
444
  scheduleFlush();
349
445
  }
350
446
  else
351
- attach();
447
+ attach(nextOptions.parts ?? null);
352
448
  }
353
449
  else
354
450
  detach();
@@ -0,0 +1,103 @@
1
+ /**
2
+ * What a round changed in the widget's files, as the code card shows it: red for the lines taken out, green for the lines put in.
3
+ *
4
+ * The chat does not work the changes out. The gateway does, from the version before the round and the version it saved, and
5
+ * sends them in the metadata of the completed operation (`metadata.codeChanges`, only to a client that said it can show them).
6
+ * Nothing here reads the streamed code: the stream is only a sampled tail of what the model wrote, and two tails cannot be
7
+ * compared. This file reads what the gateway sent (it trusts none of it: a malformed part is dropped, never thrown on) and
8
+ * turns each file's patch into rows a view can draw. It is read-only: nothing here edits, applies or reverts a change.
9
+ *
10
+ * The patch of a file is the hunks of a unified diff without the file header:
11
+ *
12
+ * @@ -12,6 +12,7 @@ the old lines 12..17 became the new lines 12..18 (a count of 1 is left out; a count of 0 names the line before)
13
+ * unchanged line a space, then the line
14
+ * -line taken out a minus, then the line
15
+ * +line put in a plus, then the line
16
+ *
17
+ * A patch that was cut for its size ends in the middle of a hunk, so the counts of a header are never trusted: a hunk is read
18
+ * up to the next header, and the line numbers are counted from where it starts.
19
+ */
20
+ import type { CodeKind } from './codeStreamFormat.js';
21
+ /** How a file changed. The gateway sends `added` and `modified`; the others are read so that a later gateway can send them. */
22
+ export type CodeChangeStatus = 'added' | 'modified' | 'deleted' | 'renamed';
23
+ /** One changed file of a round. */
24
+ export interface CodeChangeFile {
25
+ /** The path in the widget's repository, for example `src/Widget.jsx`. */
26
+ path: string;
27
+ status: CodeChangeStatus;
28
+ /** The lines put in, in the whole file (more than the patch shows when the patch was cut). */
29
+ additions: number;
30
+ /** The lines taken out, in the whole file. */
31
+ deletions: number;
32
+ /** The hunks of the file, without the file header. Empty when the change was too large to send. */
33
+ patch: string;
34
+ /** True when the patch was cut for its size: what it shows is the start of the change. */
35
+ truncated: boolean;
36
+ }
37
+ /** What one round changed: the files that were sent, and how many more files changed than were sent. */
38
+ export interface CodeChanges {
39
+ files: CodeChangeFile[];
40
+ omittedFiles: number;
41
+ }
42
+ /** What one row of a diff is: a line that did not change, a line taken out, or a line put in. */
43
+ export type DiffLineKind = 'context' | 'delete' | 'insert';
44
+ /** One row of a diff. A line taken out has no new number, a line put in has no old number. */
45
+ export interface DiffLine {
46
+ kind: DiffLineKind;
47
+ oldNumber: number | null;
48
+ newNumber: number | null;
49
+ text: string;
50
+ }
51
+ /** One run of changes with the lines around it. */
52
+ export interface DiffHunk {
53
+ /** The lines of the new file that lie between the previous hunk (or the start of the file) and this one: the gap to fold. */
54
+ unchangedLinesBefore: number;
55
+ lines: DiffLine[];
56
+ }
57
+ /** The totals of a round, for the header of the card. */
58
+ export interface CodeChangesSummary {
59
+ /** The files that were sent. */
60
+ shownFiles: number;
61
+ /** The files that changed, the ones that were not sent included. */
62
+ totalFiles: number;
63
+ additions: number;
64
+ deletions: number;
65
+ }
66
+ /** The most files read from one round (the gateway sends at most 8; this is only a guard against a runaway). */
67
+ export declare const MAX_CHANGED_FILES_READ = 50;
68
+ /** The most characters read from one file's patch. A longer patch is cut there and marked as cut. */
69
+ export declare const MAX_PATCH_CHARACTERS_READ = 200000;
70
+ /**
71
+ * The most characters read from all the patches of a round together (the gateway sends at most 60,000). What comes after is cut,
72
+ * the files that come after it are listed with no patch, and the changes that are kept (in memory and in the archive of this
73
+ * browser) never grow past it.
74
+ */
75
+ export declare const MAX_TOTAL_PATCH_CHARACTERS_READ = 400000;
76
+ /** The most characters of a path. A longer path is not a path of a widget: the file is dropped. */
77
+ export declare const MAX_PATH_CHARACTERS_READ = 1000;
78
+ /**
79
+ * The changes of a round from what a server sent, or null when there is nothing to show. It never throws: a value that is not
80
+ * the expected shape reads as "no changes", and a file that is not usable is left out of the others.
81
+ */
82
+ export declare function readCodeChanges(raw: unknown): CodeChanges | null;
83
+ /**
84
+ * The changes of a round from the metadata of a completed operation (`metadata.codeChanges`), or null when the operation has none:
85
+ * an old gateway, a client that did not ask, a first build, a build that was not kept, or a round that changed nothing.
86
+ */
87
+ export declare function readCodeChangesFromMetadata(metadata?: Record<string, unknown> | null): CodeChanges | null;
88
+ /** The totals of the changes, for the header of the card. */
89
+ export declare function summarizeCodeChanges(changes: CodeChanges): CodeChangesSummary;
90
+ /**
91
+ * The hunks of a patch, with the line numbers of both sides. Lines before the first header are ignored (a file header that a
92
+ * host left in, for example). A line that belongs to no kind is skipped. The counts in a header are only read to tell a range
93
+ * that has lines from one that names the line before it; the rows come from what the hunk really holds, so a patch that was cut
94
+ * in the middle of a hunk shows the lines it has and nothing more.
95
+ */
96
+ export declare function parseUnifiedPatch(patch: string): DiffHunk[];
97
+ /** The kind of code of a file, from its extension, for the words that colour it. A file of no known kind is plain text. */
98
+ export declare function codeKindOfPath(path: string): CodeKind;
99
+ /**
100
+ * The changes as one unified diff, for the Copy button: each file with its header, then its hunks. A patch that was cut ends
101
+ * where it was cut, which is what the card shows. Files that were not sent are not in it.
102
+ */
103
+ export declare function patchTextOfChanges(changes: CodeChanges): string;