@widgetic/chat 0.1.42 → 0.1.44

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 (85) 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 +485 -50
  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/index.d.ts +1 -1
  38. package/dist/services/sketchAssistantClient.d.ts +27 -0
  39. package/dist/services/sketchAssistantClient.js +7 -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 +7 -7
  43. package/dist/services/sketchAssistantOrchestrator.js +11 -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 +12 -0
  74. package/dist/utils/index.js +20 -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/sentReferenceBadges.d.ts +26 -0
  84. package/dist/utils/sentReferenceBadges.js +32 -0
  85. package/package.json +1 -1
@@ -9,17 +9,26 @@
9
9
  *
10
10
  * It is open while it is the part being written and closed once the next part (or the conclusion) has taken over; the
11
11
  * person's own choice wins from the moment they press it. Under a conclusion it comes back closed, for the person to open.
12
+ *
13
+ * After a later round of a conversation the card also knows what that round changed (`changes`, worked out by the gateway
14
+ * from the version before and the version it saved: the stream cannot tell, it is only a sampled tail of what was written).
15
+ * It then opens on a "Changes" view, the lines taken out in red and the lines put in in green (`CodeDiff`, read-only), with
16
+ * "Code" one press away for all the code; its header says how much changed even while it is closed. A card with no changes
17
+ * (the first message of a conversation, the live card, a page that does not give them) is the card it always was.
12
18
  */
13
19
  import { onDestroy, tick } from 'svelte';
14
20
  import IconCheck from '@tabler/icons-svelte/icons/check';
15
21
  import IconChevronRight from '@tabler/icons-svelte/icons/chevron-right';
16
22
  import IconCode from '@tabler/icons-svelte/icons/code';
17
23
  import IconCopy from '@tabler/icons-svelte/icons/copy';
24
+ import { Tabs } from '@widgetic/design-system/components';
18
25
  import { useChatLanguage } from '../../i18n/language.js';
26
+ import { patchTextOfChanges, summarizeCodeChanges, type CodeChanges } from '../../utils/codeChanges.js';
19
27
  import { highlightCodeToHtml } from '../../utils/codeHighlight.js';
20
28
  import { formatScriptWithCursor } from '../../utils/codePrettier.js';
21
29
  import { countCodeLines, createStreamingFormatter, detectCodeKind } from '../../utils/codeStreamFormat.js';
22
30
  import { chatLog, chatWarn } from '../../utils/logger.js';
31
+ import CodeDiff from './CodeDiff.svelte';
23
32
 
24
33
  // The words of the card, in the language of the chat above
25
34
  const { t } = useChatLanguage();
@@ -31,10 +40,21 @@
31
40
  streaming?: boolean;
32
41
  /** Open until the person chooses (the live part), or closed until they do (the part under a conclusion). */
33
42
  openByDefault?: boolean;
43
+ /** What the round changed in the widget's files, when the page knows it: the card then offers the "Changes" view. */
44
+ changes?: CodeChanges | null;
34
45
  class?: string;
35
46
  }
36
47
 
37
- let { code, streaming = false, openByDefault = false, class: className = '' }: Props = $props();
48
+ let { code, streaming = false, openByDefault = false, changes = null, class: className = '' }: Props = $props();
49
+
50
+ /**
51
+ * The colours of the words: keywords blue, tags and strings maroon, the attributes of a tag red-orange (highlight.js also calls
52
+ * `name:` in a parameter list an attribute, so only the ones inside a tag are painted), comments muted. Their classes are the
53
+ * card's own `wc-code-*`, not the ones of highlight.js: see CODE_TOKEN_CLASS_PREFIX. The panel of the code and the diff wear the
54
+ * same palette, so a word has the same colour in both views.
55
+ */
56
+ const CODE_PALETTE_CLASSES =
57
+ '[&_.wc-code-tag_.wc-code-attr]:text-[#e5462b] [&_.wc-code-comment]:text-muted-foreground [&_.wc-code-comment]:italic [&_.wc-code-keyword]:text-[#2b5fc2] [&_.wc-code-literal]:text-[#2b5fc2] [&_.wc-code-meta]:text-muted-foreground [&_.wc-code-name]:text-[#8d2a1b] [&_.wc-code-number]:text-[#2b5fc2] [&_.wc-code-regexp]:text-[#8d2a1b] [&_.wc-code-string]:text-[#8d2a1b] [&_.wc-code-tag]:text-[#8d2a1b] [&_.wc-code-title]:text-[#2b5fc2] [.dark_&_.wc-code-tag_.wc-code-attr]:text-[#ff8a73] [.dark_&_.wc-code-keyword]:text-[#8ab4ff] [.dark_&_.wc-code-literal]:text-[#8ab4ff] [.dark_&_.wc-code-name]:text-[#f0a89a] [.dark_&_.wc-code-number]:text-[#8ab4ff] [.dark_&_.wc-code-regexp]:text-[#f0a89a] [.dark_&_.wc-code-string]:text-[#f0a89a] [.dark_&_.wc-code-tag]:text-[#f0a89a] [.dark_&_.wc-code-title]:text-[#8ab4ff]';
38
58
 
39
59
  /** How often Prettier follows the code while it arrives (a run takes some tens of milliseconds on a long file). */
40
60
  const FORMAT_INTERVAL_MS = 250;
@@ -51,6 +71,24 @@
51
71
  let panelElement = $state<HTMLElement | null>(null);
52
72
  let isFollowingNewestLine = true;
53
73
 
74
+ // --- The two views: what the round changed, or all the code ----------------------------------------------------------
75
+
76
+ type CardView = 'changes' | 'code';
77
+
78
+ /** The changes that are shown: only a card that is no longer being written has them (the live card shows the code). */
79
+ const shownChanges = $derived(changes !== null && changes.files.length > 0 && !streaming ? changes : null);
80
+ const changesSummary = $derived(shownChanges ? summarizeCodeChanges(shownChanges) : null);
81
+
82
+ // What the person chose, once they have chosen: from then on it wins over the default (the changes, when there are some)
83
+ let chosenView = $state<CardView | null>(null);
84
+ const view = $derived<CardView>(shownChanges ? (chosenView ?? 'changes') : 'code');
85
+
86
+ function chooseView(nextView: string): void {
87
+ if (nextView !== 'changes' && nextView !== 'code') return;
88
+ chosenView = nextView;
89
+ chatLog('[Chat] code card: the person chose the', nextView, 'view');
90
+ }
91
+
54
92
  // What the code is decides its colours and whether Prettier can lay it out
55
93
  const codeKind = $derived(detectCodeKind(code));
56
94
 
@@ -114,7 +152,8 @@
114
152
  $effect(() => {
115
153
  const codeToFormat = code;
116
154
  const codeIsComplete = !streaming;
117
- const canFormat = isOpen && codeKind === 'script' && codeToFormat.length <= MAX_FORMATTED_CHARACTERS;
155
+ // Only the view of the code needs it: the changes are drawn from the patches, as they are
156
+ const canFormat = isOpen && view === 'code' && codeKind === 'script' && codeToFormat.length <= MAX_FORMATTED_CHARACTERS;
118
157
  if (!canFormat) return;
119
158
  newestCode = codeToFormat;
120
159
  newestCodeIsComplete = codeIsComplete;
@@ -184,18 +223,26 @@
184
223
  let hasCopied = $state(false);
185
224
  let copiedTimer: ReturnType<typeof setTimeout> | null = null;
186
225
 
226
+ /** The changes as one unified diff, for the Copy button of the "Changes" view. */
227
+ const changesText = $derived(shownChanges ? patchTextOfChanges(shownChanges) : '');
228
+ /** What the Copy button copies: the diff under "Changes", the code under "Code". */
229
+ const textToCopy = $derived(view === 'changes' ? changesText : visibleText);
230
+ const copyTitle = $derived(
231
+ hasCopied ? $t('chat.code.copied') : view === 'changes' ? $t('chat.code.copyChangesTitle') : $t('chat.code.copyTitle')
232
+ );
233
+
187
234
  async function copyCode(): Promise<void> {
188
235
  try {
189
- await navigator.clipboard.writeText(visibleText);
236
+ await navigator.clipboard.writeText(textToCopy);
190
237
  hasCopied = true;
191
- chatLog('[Chat] code card: the code was copied');
238
+ chatLog(`[Chat] code card: the ${view === 'changes' ? 'changes were' : 'code was'} copied`);
192
239
  if (copiedTimer !== null) clearTimeout(copiedTimer);
193
240
  copiedTimer = setTimeout(() => {
194
241
  hasCopied = false;
195
242
  copiedTimer = null;
196
243
  }, 2000);
197
244
  } catch (error) {
198
- chatWarn('[Chat] code card: the code could not be copied:', error);
245
+ chatWarn(`[Chat] code card: the ${view === 'changes' ? 'changes' : 'code'} could not be copied:`, error);
199
246
  }
200
247
  }
201
248
 
@@ -206,6 +253,24 @@
206
253
  });
207
254
  </script>
208
255
 
256
+ {#snippet codePanel()}
257
+ <!-- The words are coloured with the palette in CODE_PALETTE_CLASSES. The two pieces of html in the panel are the only ones of the
258
+ card's own, and safe: `highlightCodeToHtml` escapes every character of the code, and the only tags it writes are the `span`s
259
+ of the words. -->
260
+ <!-- The panel scrolls, so the keyboard has to be able to reach it -->
261
+ <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
262
+ <pre
263
+ bind:this={panelElement}
264
+ onscroll={updateFollowing}
265
+ tabindex="0"
266
+ aria-label={$t('chat.generation.codeTitle')}
267
+ class="bg-muted text-foreground m-0 max-h-72 w-full overflow-auto rounded-lg p-3 font-[ui-monospace,SFMono-Regular,'SF_Mono',Menlo,Monaco,Consolas,'Liberation_Mono','Courier_New',monospace] text-[12px] leading-[18px] break-words whitespace-pre-wrap [tab-size:2] [scrollbar-color:var(--border)_transparent] [scrollbar-width:thin] {CODE_PALETTE_CLASSES}"
268
+ dir="ltr"
269
+ data-testid="code-card-text"><code
270
+ >{@html settledHtml}{lastLineBreakIndex === -1 ? '' : '\n'}{@html typingHtml}</code
271
+ ></pre>
272
+ {/snippet}
273
+
209
274
  <div
210
275
  class="rounded-card border-border bg-background flex w-full max-w-full min-w-0 flex-col border {isOpen
211
276
  ? 'gap-3 p-4'
@@ -214,6 +279,7 @@
214
279
  data-open={isOpen}
215
280
  data-streaming={streaming}
216
281
  data-formatted={isFormattedStartValid}
282
+ data-view={view}
217
283
  >
218
284
  <header class="flex min-w-0 items-center gap-2">
219
285
  <button
@@ -225,6 +291,16 @@
225
291
  >
226
292
  <IconCode class="size-4 shrink-0 stroke-2" aria-hidden="true" />
227
293
  <span class="text-body-medium min-w-0 flex-1 truncate">{$t('chat.generation.codeTitle')}</span>
294
+ {#if changesSummary}
295
+ <!-- How much the round changed, even while the card is closed: the numbers are for the eyes, the words for a screen reader -->
296
+ <span class="text-caption flex shrink-0 gap-1.5" dir="ltr" aria-hidden="true" data-testid="code-card-stats">
297
+ <span class="text-green-700 [.dark_&]:text-green-400">+{changesSummary.additions}</span>
298
+ <span class="text-destructive">−{changesSummary.deletions}</span>
299
+ </span>
300
+ <span class="sr-only">{$t('chat.code.filesChanged', { count: changesSummary.totalFiles })},</span>
301
+ <span class="sr-only">{$t('chat.code.linesAdded', { count: changesSummary.additions })},</span>
302
+ <span class="sr-only">{$t('chat.code.linesRemoved', { count: changesSummary.deletions })}</span>
303
+ {/if}
228
304
  <IconChevronRight
229
305
  class="text-muted-foreground size-4 shrink-0 stroke-2 transition-transform motion-reduce:transition-none rtl:-scale-x-100 {isOpen
230
306
  ? 'rotate-90 rtl:-rotate-90'
@@ -233,12 +309,12 @@
233
309
  />
234
310
  <span class="sr-only">{toggleLabel}</span>
235
311
  </button>
236
- {#if isOpen && visibleText !== ''}
312
+ {#if isOpen && textToCopy !== ''}
237
313
  <button
238
314
  type="button"
239
315
  class="text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:bg-accent focus-visible:text-foreground flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-md transition-colors focus-visible:outline-none"
240
- title={hasCopied ? $t('chat.code.copied') : $t('chat.code.copyTitle')}
241
- aria-label={hasCopied ? $t('chat.code.copied') : $t('chat.code.copyTitle')}
316
+ title={copyTitle}
317
+ aria-label={copyTitle}
242
318
  onclick={copyCode}
243
319
  data-testid="code-card-copy"
244
320
  >
@@ -253,34 +329,53 @@
253
329
 
254
330
  {#if isOpen}
255
331
  <div id={bodyId} class="flex min-w-0 flex-col gap-3">
256
- <!-- The colours of the words: keywords blue, tags and strings maroon, the attributes of a tag red-orange (highlight.js also calls
257
- `name:` in a parameter list an attribute, so only the ones inside a tag are painted), comments muted. Their classes are
258
- the card's own `wc-code-*`, not the ones of highlight.js: see CODE_TOKEN_CLASS_PREFIX. The two pieces of html in the panel are
259
- the only ones in the card, and safe: `highlightCodeToHtml` escapes every character of the code, and the only tags it writes
260
- are the `span`s of the words. -->
261
- <!-- The panel scrolls, so the keyboard has to be able to reach it -->
262
- <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
263
- <pre
264
- bind:this={panelElement}
265
- onscroll={updateFollowing}
266
- tabindex="0"
267
- aria-label={$t('chat.generation.codeTitle')}
268
- class="bg-muted text-foreground m-0 max-h-72 w-full overflow-auto rounded-lg p-3 font-[ui-monospace,SFMono-Regular,'SF_Mono',Menlo,Monaco,Consolas,'Liberation_Mono','Courier_New',monospace] text-[12px] leading-[18px] break-words whitespace-pre-wrap [tab-size:2] [scrollbar-color:var(--border)_transparent] [scrollbar-width:thin] [&_.wc-code-tag_.wc-code-attr]:text-[#e5462b] [&_.wc-code-comment]:text-muted-foreground [&_.wc-code-comment]:italic [&_.wc-code-keyword]:text-[#2b5fc2] [&_.wc-code-literal]:text-[#2b5fc2] [&_.wc-code-meta]:text-muted-foreground [&_.wc-code-name]:text-[#8d2a1b] [&_.wc-code-number]:text-[#2b5fc2] [&_.wc-code-regexp]:text-[#8d2a1b] [&_.wc-code-string]:text-[#8d2a1b] [&_.wc-code-tag]:text-[#8d2a1b] [&_.wc-code-title]:text-[#2b5fc2] [.dark_&_.wc-code-tag_.wc-code-attr]:text-[#ff8a73] [.dark_&_.wc-code-keyword]:text-[#8ab4ff] [.dark_&_.wc-code-literal]:text-[#8ab4ff] [.dark_&_.wc-code-name]:text-[#f0a89a] [.dark_&_.wc-code-number]:text-[#8ab4ff] [.dark_&_.wc-code-regexp]:text-[#f0a89a] [.dark_&_.wc-code-string]:text-[#f0a89a] [.dark_&_.wc-code-tag]:text-[#f0a89a] [.dark_&_.wc-code-title]:text-[#8ab4ff]"
269
- dir="ltr"
270
- data-testid="code-card-text"><code
271
- >{@html settledHtml}{lastLineBreakIndex === -1 ? '' : '\n'}{@html typingHtml}</code
272
- ></pre>
332
+ {#if shownChanges}
333
+ <!-- Only one view is drawn at a time (a panel that is not shown is not built), and the panels are not tab stops of their own:
334
+ the diff and the code are, since they scroll -->
335
+ <Tabs.Root value={view} onValueChange={chooseView} class="flex min-w-0 flex-col gap-3">
336
+ <Tabs.List aria-label={$t('chat.code.viewLabel')} class="h-7 self-start rounded-lg p-0.5">
337
+ <Tabs.Trigger value="changes" class="text-label-small h-6 rounded-md px-2.5" data-testid="code-card-view-changes">
338
+ {$t('chat.code.changesTab')}
339
+ </Tabs.Trigger>
340
+ <Tabs.Trigger value="code" class="text-label-small h-6 rounded-md px-2.5" data-testid="code-card-view-code">
341
+ {$t('chat.code.codeTab')}
342
+ </Tabs.Trigger>
343
+ </Tabs.List>
344
+ <Tabs.Content value="changes" tabindex={-1} class="min-w-0">
345
+ {#if view === 'changes'}<CodeDiff changes={shownChanges} class={CODE_PALETTE_CLASSES} />{/if}
346
+ </Tabs.Content>
347
+ <Tabs.Content value="code" tabindex={-1} class="min-w-0">
348
+ {#if view === 'code'}{@render codePanel()}{/if}
349
+ </Tabs.Content>
350
+ </Tabs.Root>
351
+ {:else}
352
+ {@render codePanel()}
353
+ {/if}
273
354
  <footer class="text-caption text-muted-foreground flex flex-col gap-0.5" data-testid="code-card-status">
274
355
  <span class="flex items-center gap-2">
275
356
  <span
276
357
  class="bg-brand size-2 shrink-0 rounded-full {streaming ? 'animate-pulse motion-reduce:animate-none' : ''}"
277
358
  aria-hidden="true"
278
359
  ></span>
279
- <span>{streaming ? $t('chat.generation.writingCode') : $t('chat.generation.codeWritten')}</span>
360
+ <span>
361
+ {#if streaming}
362
+ {$t('chat.generation.writingCode')}
363
+ {:else if view === 'changes'}
364
+ {$t('chat.generation.codeUpdated')}
365
+ {:else}
366
+ {$t('chat.generation.codeWritten')}
367
+ {/if}
368
+ </span>
280
369
  </span>
281
370
  <span class="flex items-center gap-2 ps-0.5">
282
371
  <span class="border-border h-2.5 w-2 shrink-0 border-s border-b" aria-hidden="true"></span>
283
- <span>{$t('chat.generation.codeLineCount', { count: lineCount })}</span>
372
+ <span>
373
+ {#if view === 'changes' && changesSummary}
374
+ {$t('chat.code.filesChanged', { count: changesSummary.totalFiles })}
375
+ {:else}
376
+ {$t('chat.generation.codeLineCount', { count: lineCount })}
377
+ {/if}
378
+ </span>
284
379
  </span>
285
380
  </footer>
286
381
  </div>
@@ -1,3 +1,4 @@
1
+ import { type CodeChanges } from '../../utils/codeChanges.js';
1
2
  interface Props {
2
3
  /** Everything written so far. */
3
4
  code: string;
@@ -5,6 +6,8 @@ interface Props {
5
6
  streaming?: boolean;
6
7
  /** Open until the person chooses (the live part), or closed until they do (the part under a conclusion). */
7
8
  openByDefault?: boolean;
9
+ /** What the round changed in the widget's files, when the page knows it: the card then offers the "Changes" view. */
10
+ changes?: CodeChanges | null;
8
11
  class?: string;
9
12
  }
10
13
  declare const CodeCard: import("svelte").Component<Props, {}, "">;
@@ -0,0 +1,180 @@
1
+ <script lang="ts">
2
+ /**
3
+ * What a round changed in the widget's files, drawn for reading: a header for each file (its path, whether it is new, the lines
4
+ * put in and taken out), and under it the rows of the diff. A line taken out is on a red ground, a line put in on a green one,
5
+ * and the lines around them stay as they are, with the number each has in the old file and in the new one. The lines that did
6
+ * not change and lie between two hunks are folded into one row that says how many there are.
7
+ *
8
+ * It only shows. It has no way to edit, apply or revert a change, and the gateway has already done the diffing: the rows come
9
+ * from the patches it sent (see `codeChanges.ts`). The code is read left to right whatever the page, as in the code card, and
10
+ * every line is coloured on its own (a construct that runs over several lines, a block comment for instance, is coloured by
11
+ * the line it is read on, since the lines around the change are all that is known of the file).
12
+ */
13
+ import IconChevronRight from '@tabler/icons-svelte/icons/chevron-right';
14
+ import { useChatLanguage } from '../../i18n/language.js';
15
+ import { codeKindOfPath, parseUnifiedPatch, type CodeChanges, type DiffLineKind } from '../../utils/codeChanges.js';
16
+ import { escapeHtml, highlightCodeToHtml } from '../../utils/codeHighlight.js';
17
+ import type { CodeKind } from '../../utils/codeStreamFormat.js';
18
+
19
+ // The words of the diff, in the language of the chat above
20
+ const { t } = useChatLanguage();
21
+
22
+ interface Props {
23
+ /** What the round changed, as `readCodeChanges` made it. */
24
+ changes: CodeChanges;
25
+ /** The code card puts the palette of its words here, so that the words of the diff are the colours of its code. */
26
+ class?: string;
27
+ }
28
+
29
+ let { changes, class: className = '' }: Props = $props();
30
+
31
+ /** A line longer than this is shown as it is, not coloured: colouring a minified line costs more than it shows. */
32
+ const MAX_COLOURED_LINE_CHARACTERS = 1_000;
33
+
34
+ /**
35
+ * What each kind of row looks like: a line taken out on a red ground, a line put in on a green one, the rest as it is. The red is
36
+ * a little stronger on the dark theme (`.dark` class), where the same share of it over a dark ground reads as brown next to the green.
37
+ */
38
+ const ROW_CLASSES: Readonly<Record<DiffLineKind, string>> = {
39
+ context: '',
40
+ delete: 'bg-destructive/10 [.dark_&]:bg-destructive/20',
41
+ insert: 'bg-green-500/15'
42
+ };
43
+
44
+ /** The numbers and the mark of a row take the colour of its kind, so that a row is told apart by more than its ground. */
45
+ const MARK_CLASSES: Readonly<Record<DiffLineKind, string>> = {
46
+ context: 'text-muted-foreground',
47
+ delete: 'text-destructive',
48
+ insert: 'text-green-700 [.dark_&]:text-green-400'
49
+ };
50
+
51
+ const MARKS: Readonly<Record<DiffLineKind, string>> = { context: '', delete: '−', insert: '+' };
52
+
53
+ const rootId = $props.id();
54
+
55
+ /** Each file with the kind of code it is and the rows of its patch, read once for the changes it is given. */
56
+ const viewedFiles = $derived(
57
+ changes.files.map((file) => ({
58
+ file,
59
+ kind: codeKindOfPath(file.path),
60
+ hunks: parseUnifiedPatch(file.patch)
61
+ }))
62
+ );
63
+
64
+ // The files the person folded; every file is open until they do
65
+ let foldedPaths = $state<Record<string, boolean>>({});
66
+
67
+ function toggleFile(path: string): void {
68
+ foldedPaths[path] = !foldedPaths[path];
69
+ }
70
+
71
+ /** The HTML of one line: its words in spans, or the line escaped when it is too long to colour. */
72
+ function lineToHtml(text: string, kind: CodeKind): string {
73
+ return text.length > MAX_COLOURED_LINE_CHARACTERS ? escapeHtml(text) : highlightCodeToHtml(text, kind);
74
+ }
75
+ </script>
76
+
77
+ <!-- The colours of the words come from the palette the code card puts on this element (`class`): the same one as its code.
78
+ The one piece of html in the rows is safe: `highlightCodeToHtml` and `escapeHtml` escape every character of the code, and the
79
+ only tags `highlightCodeToHtml` writes are the `span`s of the words. -->
80
+ <!-- The panel scrolls, so the keyboard has to be able to reach it -->
81
+ <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
82
+ <div
83
+ class="bg-background border-border max-h-80 w-full min-w-0 overflow-auto rounded-lg border font-[ui-monospace,SFMono-Regular,'SF_Mono',Menlo,Monaco,Consolas,'Liberation_Mono','Courier_New',monospace] text-[12px] leading-[18px] [scrollbar-color:var(--border)_transparent] [scrollbar-width:thin] {className}"
84
+ dir="ltr"
85
+ role="group"
86
+ tabindex="0"
87
+ aria-label={$t('chat.code.changesTitle')}
88
+ data-testid="code-diff"
89
+ >
90
+ {#each viewedFiles as viewedFile, fileIndex (fileIndex)}
91
+ {@const file = viewedFile.file}
92
+ {@const isFolded = foldedPaths[file.path] === true}
93
+ {@const rowsId = `${rootId}-${fileIndex}`}
94
+ <section class="min-w-0 {fileIndex > 0 ? 'border-border border-t' : ''}" data-testid="code-diff-file" data-status={file.status}>
95
+ <button
96
+ type="button"
97
+ class="bg-muted text-foreground hover:bg-accent focus-visible:ring-ring flex w-full min-w-0 cursor-pointer items-center gap-2 px-3 py-1.5 text-start transition-colors focus-visible:ring-2 focus-visible:outline-none focus-visible:ring-inset"
98
+ aria-expanded={!isFolded}
99
+ aria-controls={rowsId}
100
+ title={file.path}
101
+ onclick={() => toggleFile(file.path)}
102
+ data-testid="code-diff-file-toggle"
103
+ >
104
+ <IconChevronRight
105
+ class="text-muted-foreground size-3.5 shrink-0 stroke-2 transition-transform motion-reduce:transition-none {isFolded
106
+ ? ''
107
+ : 'rotate-90'}"
108
+ aria-hidden="true"
109
+ />
110
+ <span class="min-w-0 flex-1 truncate">{file.path}</span>
111
+ {#if file.status !== 'modified'}
112
+ <span class="border-border text-muted-foreground shrink-0 rounded-sm border px-1 font-sans text-[11px] leading-4">
113
+ {#if file.status === 'added'}
114
+ {$t('chat.code.fileAdded')}
115
+ {:else if file.status === 'deleted'}
116
+ {$t('chat.code.fileDeleted')}
117
+ {:else}
118
+ {$t('chat.code.fileRenamed')}
119
+ {/if}
120
+ </span>
121
+ {/if}
122
+ <span class="flex shrink-0 gap-1.5" dir="ltr" aria-hidden="true">
123
+ <span class="text-green-700 [.dark_&]:text-green-400">+{file.additions}</span>
124
+ <span class="text-destructive">−{file.deletions}</span>
125
+ </span>
126
+ <span class="sr-only">
127
+ {$t('chat.code.linesAdded', { count: file.additions })}, {$t('chat.code.linesRemoved', { count: file.deletions })}
128
+ </span>
129
+ </button>
130
+
131
+ {#if !isFolded}
132
+ <div id={rowsId} class="min-w-0">
133
+ {#each viewedFile.hunks as hunk, hunkIndex (hunkIndex)}
134
+ {#if hunk.unchangedLinesBefore > 0}
135
+ <div class="bg-muted/60 text-muted-foreground text-caption px-3 py-1 text-center font-sans" data-testid="code-diff-gap">
136
+ {$t('chat.code.unchangedLines', { count: hunk.unchangedLinesBefore })}
137
+ </div>
138
+ {/if}
139
+ {#each hunk.lines as line, lineIndex (lineIndex)}
140
+ <div class="flex min-h-[18px] items-start {ROW_CLASSES[line.kind]}" data-testid="code-diff-line" data-kind={line.kind}>
141
+ <span class="w-10 shrink-0 px-1 text-end tabular-nums select-none {MARK_CLASSES[line.kind]}" aria-hidden="true">
142
+ {line.oldNumber ?? ''}
143
+ </span>
144
+ <span class="w-10 shrink-0 px-1 text-end tabular-nums select-none {MARK_CLASSES[line.kind]}" aria-hidden="true">
145
+ {line.newNumber ?? ''}
146
+ </span>
147
+ <span class="w-4 shrink-0 text-center select-none {MARK_CLASSES[line.kind]}" aria-hidden="true">
148
+ {MARKS[line.kind]}
149
+ </span>
150
+ <code class="text-foreground min-w-0 flex-1 pe-3 break-words whitespace-pre-wrap [tab-size:2]">
151
+ {#if line.kind === 'insert'}
152
+ <span class="sr-only">{$t('chat.code.lineAdded')}{' '}</span>
153
+ {:else if line.kind === 'delete'}
154
+ <span class="sr-only">{$t('chat.code.lineRemoved')}{' '}</span>
155
+ {/if}{@html lineToHtml(line.text, viewedFile.kind)}</code
156
+ >
157
+ </div>
158
+ {/each}
159
+ {/each}
160
+
161
+ {#if viewedFile.hunks.length === 0}
162
+ <p class="text-muted-foreground text-caption m-0 px-3 py-2 font-sans" data-testid="code-diff-note">
163
+ {$t('chat.code.changeTooLarge')}
164
+ </p>
165
+ {:else if file.truncated}
166
+ <p class="text-muted-foreground text-caption m-0 px-3 py-2 font-sans" data-testid="code-diff-note">
167
+ {$t('chat.code.changeTruncated')}
168
+ </p>
169
+ {/if}
170
+ </div>
171
+ {/if}
172
+ </section>
173
+ {/each}
174
+
175
+ {#if changes.omittedFiles > 0}
176
+ <p class="text-muted-foreground text-caption border-border m-0 border-t px-3 py-2 font-sans" data-testid="code-diff-more-files">
177
+ {$t('chat.code.moreFiles', { count: changes.omittedFiles })}
178
+ </p>
179
+ {/if}
180
+ </div>
@@ -0,0 +1,10 @@
1
+ import { type CodeChanges } from '../../utils/codeChanges.js';
2
+ interface Props {
3
+ /** What the round changed, as `readCodeChanges` made it. */
4
+ changes: CodeChanges;
5
+ /** The code card puts the palette of its words here, so that the words of the diff are the colours of its code. */
6
+ class?: string;
7
+ }
8
+ declare const CodeDiff: import("svelte").Component<Props, {}, "">;
9
+ type CodeDiff = ReturnType<typeof CodeDiff>;
10
+ export default CodeDiff;
@@ -10,6 +10,7 @@
10
10
  import { tick } from 'svelte';
11
11
  import IconChevronRight from '@tabler/icons-svelte/icons/chevron-right';
12
12
  import { useChatLanguage } from '../../i18n/language.js';
13
+ import type { CodeChanges } from '../../utils/codeChanges.js';
13
14
  import { chatLog } from '../../utils/logger.js';
14
15
  import CodeCard from './CodeCard.svelte';
15
16
 
@@ -27,10 +28,20 @@
27
28
  seconds?: number | null;
28
29
  /** Open until the person chooses (the live part), or closed until they do (the part under a conclusion). */
29
30
  openByDefault?: boolean;
31
+ /** What the round changed in the widget's files, for the code kind: the code card then offers the "Changes" view. */
32
+ changes?: CodeChanges | null;
30
33
  class?: string;
31
34
  }
32
35
 
33
- let { kind, text, streaming = false, seconds = null, openByDefault = false, class: className = '' }: Props = $props();
36
+ let {
37
+ kind,
38
+ text,
39
+ streaming = false,
40
+ seconds = null,
41
+ openByDefault = false,
42
+ changes = null,
43
+ class: className = ''
44
+ }: Props = $props();
34
45
 
35
46
  // What the person chose, once they have chosen: from then on it wins over the default
36
47
  let chosenOpen = $state<boolean | null>(null);
@@ -67,7 +78,7 @@
67
78
 
68
79
  {#if kind === 'code'}
69
80
  <!-- The code is a card of its own (open, closed, copy, the status line): see CodeCard -->
70
- <CodeCard code={text} {streaming} {openByDefault} class={className} />
81
+ <CodeCard code={text} {streaming} {openByDefault} {changes} class={className} />
71
82
  {:else}
72
83
  <div class="flex min-w-0 flex-col {className}" data-testid="generation-module" data-generation-module={kind} data-open={isOpen}>
73
84
  <button
@@ -1,3 +1,4 @@
1
+ import type { CodeChanges } from '../../utils/codeChanges.js';
1
2
  interface Props {
2
3
  /** What this part of the work is. */
3
4
  kind: 'thinking' | 'code';
@@ -9,6 +10,8 @@ interface Props {
9
10
  seconds?: number | null;
10
11
  /** Open until the person chooses (the live part), or closed until they do (the part under a conclusion). */
11
12
  openByDefault?: boolean;
13
+ /** What the round changed in the widget's files, for the code kind: the code card then offers the "Changes" view. */
14
+ changes?: CodeChanges | null;
12
15
  class?: string;
13
16
  }
14
17
  declare const GenerationModule: import("svelte").Component<Props, {}, "">;
@@ -12,7 +12,11 @@ export { default as LoadingIndicator } from './LoadingIndicator.svelte';
12
12
  export { default as AgentAvatar } from './agent/AgentAvatar.svelte';
13
13
  export { default as AgentTurn } from './agent/AgentTurn.svelte';
14
14
  export { default as CodeCard } from './agent/CodeCard.svelte';
15
+ export { default as CodeDiff } from './agent/CodeDiff.svelte';
15
16
  export { default as GenerationModule } from './agent/GenerationModule.svelte';
16
17
  export { default as MemberAvatar } from './agent/MemberAvatar.svelte';
17
18
  export { default as SelectedElementChip } from './SelectedElementChip.svelte';
19
+ export { default as ChatComposer } from './ChatComposer.svelte';
20
+ export { default as MentionMenu } from './MentionMenu.svelte';
21
+ export { default as MentionChip } from './MentionChip.svelte';
18
22
  export type { ComponentProps } from 'svelte';
@@ -17,8 +17,17 @@ export { default as LoadingIndicator } from './LoadingIndicator.svelte';
17
17
  export { default as AgentAvatar } from './agent/AgentAvatar.svelte';
18
18
  export { default as AgentTurn } from './agent/AgentTurn.svelte';
19
19
  export { default as CodeCard } from './agent/CodeCard.svelte';
20
+ export { default as CodeDiff } from './agent/CodeDiff.svelte';
20
21
  export { default as GenerationModule } from './agent/GenerationModule.svelte';
21
22
  export { default as MemberAvatar } from './agent/MemberAvatar.svelte';
22
23
  // The chip of a part the person picked on the preview (the numbered badge, the first words of its note, the cross), for a page
23
24
  // that builds its own message box. Inside `Chat` the chips are drawn for the page, in the message box.
24
25
  export { default as SelectedElementChip } from './SelectedElementChip.svelte';
26
+ // The chat's own message box (the text, Enter to send, Shift+Enter for a new line, the arrow-up send button), for a page that
27
+ // needs a box like it outside the chat: the note of a part picked on the preview is written in one. Used on its own it speaks
28
+ // English, except for the words the page gives it (`placeholder`, `inputLabel`, `sendLabel`).
29
+ export { default as ChatComposer } from './ChatComposer.svelte';
30
+ // The @ menu and the chip of a pick, for a page that builds its own message box (the rules they follow are in the utilities:
31
+ // `buildMentionRows`, `findActiveMentionTrigger`, ...). Inside `Chat` they are drawn for the page, from its `mentionSources`.
32
+ export { default as MentionMenu } from './MentionMenu.svelte';
33
+ export { default as MentionChip } from './MentionChip.svelte';
@@ -0,0 +1 @@
1
+ export declare function logTechnicalUserError(context: string, error: unknown, detail?: string | null): void;
@@ -0,0 +1,37 @@
1
+ const loggedObjects = new WeakSet();
2
+ const loggedStringKeys = new Set();
3
+ const MAX_DEDUPED_STRING_KEYS = 200;
4
+ function rememberStringKey(key) {
5
+ if (loggedStringKeys.has(key))
6
+ return false;
7
+ if (loggedStringKeys.size >= MAX_DEDUPED_STRING_KEYS) {
8
+ const first = loggedStringKeys.values().next().value;
9
+ if (typeof first === 'string')
10
+ loggedStringKeys.delete(first);
11
+ }
12
+ loggedStringKeys.add(key);
13
+ return true;
14
+ }
15
+ export function logTechnicalUserError(context, error, detail) {
16
+ const prefix = `[chat] ${context}`;
17
+ if (error !== null && error !== undefined && typeof error === 'object') {
18
+ if (loggedObjects.has(error))
19
+ return;
20
+ loggedObjects.add(error);
21
+ console.error(prefix, error);
22
+ return;
23
+ }
24
+ const fallback = detail?.trim() || (typeof error === 'string' ? error.trim() : '');
25
+ const dedupeKey = `${context}\0${fallback || String(error)}`;
26
+ if (!rememberStringKey(dedupeKey))
27
+ return;
28
+ if (error !== undefined && error !== null) {
29
+ console.error(prefix, error);
30
+ }
31
+ else if (fallback) {
32
+ console.error(prefix, fallback);
33
+ }
34
+ else {
35
+ console.error(prefix);
36
+ }
37
+ }