@widgetic/chat 0.1.38 → 0.1.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +71 -0
  2. package/dist/components/AttachmentDisplay.svelte +14 -4
  3. package/dist/components/Chat.svelte +131 -106
  4. package/dist/components/Chat.svelte.d.ts +29 -0
  5. package/dist/components/ChatComposer.svelte +5 -1
  6. package/dist/components/ChatMessages.svelte +595 -175
  7. package/dist/components/ChatMessages.svelte.d.ts +20 -0
  8. package/dist/components/CodeBlock.svelte +9 -1
  9. package/dist/components/ComposerAttachmentsTray.svelte +64 -0
  10. package/dist/components/ComposerAttachmentsTray.svelte.d.ts +11 -0
  11. package/dist/components/PanelChatHeader.svelte +26 -6
  12. package/dist/components/PanelChatHeader.svelte.d.ts +1 -0
  13. package/dist/components/PanelFollowUpSuggestions.svelte +2 -2
  14. package/dist/components/PanelSuggestionButtons.svelte +2 -1
  15. package/dist/components/agent/AgentAvatar.svelte +153 -0
  16. package/dist/components/agent/AgentAvatar.svelte.d.ts +27 -0
  17. package/dist/components/agent/AgentTurn.svelte +64 -0
  18. package/dist/components/agent/AgentTurn.svelte.d.ts +32 -0
  19. package/dist/components/agent/AvatarBoundary.svelte +29 -0
  20. package/dist/components/agent/AvatarBoundary.svelte.d.ts +20 -0
  21. package/dist/components/agent/CodeCard.svelte +288 -0
  22. package/dist/components/agent/CodeCard.svelte.d.ts +12 -0
  23. package/dist/components/agent/GenerationModule.svelte +99 -0
  24. package/dist/components/agent/GenerationModule.svelte.d.ts +16 -0
  25. package/dist/components/agent/MemberAvatar.svelte +87 -0
  26. package/dist/components/agent/MemberAvatar.svelte.d.ts +8 -0
  27. package/dist/components/index.d.ts +5 -0
  28. package/dist/components/index.js +9 -0
  29. package/dist/i18n/messages.d.ts +32 -10
  30. package/dist/i18n/messages.js +32 -10
  31. package/dist/types/agent.d.ts +74 -0
  32. package/dist/types/agent.js +1 -0
  33. package/dist/types/index.d.ts +1 -0
  34. package/dist/types/index.js +2 -0
  35. package/dist/utils/agentTurn.d.ts +219 -0
  36. package/dist/utils/agentTurn.js +301 -0
  37. package/dist/utils/attachmentPreviewUrl.d.ts +21 -0
  38. package/dist/utils/attachmentPreviewUrl.js +39 -0
  39. package/dist/utils/bubbleFit.d.ts +75 -0
  40. package/dist/utils/bubbleFit.js +116 -0
  41. package/dist/utils/bubbleShrinkWrap.d.ts +32 -0
  42. package/dist/utils/bubbleShrinkWrap.js +360 -0
  43. package/dist/utils/chatImageUploadPrep.d.ts +22 -0
  44. package/dist/utils/chatImageUploadPrep.js +90 -0
  45. package/dist/utils/codeHighlight.d.ts +13 -0
  46. package/dist/utils/codeHighlight.js +61 -0
  47. package/dist/utils/codePrettier.d.ts +6 -0
  48. package/dist/utils/codePrettier.js +34 -0
  49. package/dist/utils/codeStreamFormat.d.ts +90 -0
  50. package/dist/utils/codeStreamFormat.js +429 -0
  51. package/dist/utils/generationArchiveStore.d.ts +15 -0
  52. package/dist/utils/generationArchiveStore.js +89 -0
  53. package/dist/utils/imageTransform.d.ts +12 -0
  54. package/dist/utils/imageTransform.js +45 -0
  55. package/dist/utils/index.d.ts +2 -0
  56. package/dist/utils/index.js +3 -0
  57. package/dist/utils/suggestionDraft.d.ts +5 -0
  58. package/dist/utils/suggestionDraft.js +15 -0
  59. package/package.json +5 -4
@@ -0,0 +1,360 @@
1
+ import { chatLog, chatWarn } from './logger.js';
2
+ import { buildCanvasFont, countLinesByTops, findTightTextWidth, letterSpacingInPixels, widerWidthsToTry } from './bubbleFit.js';
3
+ /** 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
+ const FIT_ATTRIBUTE = 'data-bubble-fit';
5
+ /** 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
+ const ROW_ATTRIBUTE = 'data-bubble-row';
7
+ const entries = new Set();
8
+ const entriesOfRow = new Map();
9
+ const lastWidthOfRow = new Map();
10
+ let rowObserver = null;
11
+ let scheduledFrame = null;
12
+ let listeningToFonts = false;
13
+ let pretextPromise = null;
14
+ let loadedPretext = null;
15
+ /** Each of these is said once, however many bubbles there are. */
16
+ let loggedFirstFit = false;
17
+ let loggedUnavailable = false;
18
+ let loggedDisagreement = false;
19
+ let loggedMeasureFailure = false;
20
+ // --- Pretext, loaded when first needed --------------------------------------------------------------------------
21
+ /** Pretext, or `null` when it cannot run here (not a browser, no canvas, an old browser, the module did not load). */
22
+ function loadPretext() {
23
+ if (!pretextPromise) {
24
+ pretextPromise =
25
+ typeof window === 'undefined'
26
+ ? Promise.resolve(null)
27
+ : import('@chenglou/pretext')
28
+ .then((module) => {
29
+ loadedPretext = module;
30
+ return module;
31
+ })
32
+ .catch((error) => {
33
+ if (!loggedUnavailable) {
34
+ loggedUnavailable = true;
35
+ chatWarn('[Chat] Pretext could not load: bubbles keep the width CSS gives them.', error);
36
+ }
37
+ return null;
38
+ });
39
+ }
40
+ return pretextPromise;
41
+ }
42
+ // --- the frame ----------------------------------------------------------------------------------------------------
43
+ function scheduleFlush() {
44
+ if (scheduledFrame !== null || typeof requestAnimationFrame === 'undefined')
45
+ return;
46
+ scheduledFrame = requestAnimationFrame(() => {
47
+ scheduledFrame = null;
48
+ void flushBubbles();
49
+ });
50
+ }
51
+ function pixelsOf(cssLength) {
52
+ const pixels = Number.parseFloat(cssLength);
53
+ return Number.isFinite(pixels) ? pixels : 0;
54
+ }
55
+ /** Reads what the search needs from a bubble's text element, or `null` when it cannot be measured now (hidden, or not a text Pretext knows). */
56
+ function readBubbleBox(node) {
57
+ const style = window.getComputedStyle(node);
58
+ if (style.display === 'none' || node.offsetWidth === 0)
59
+ return null;
60
+ const text = (node.textContent ?? '').replace(/\r\n?/g, '\n');
61
+ if (!text.trim())
62
+ return null;
63
+ // Pretext knows `white-space: normal` and `pre-wrap` (and `word-break: normal` and `keep-all`); other settings are left to CSS
64
+ const whiteSpace = style.whiteSpace === 'pre-wrap' || style.whiteSpace === 'break-spaces' ? 'pre-wrap' : style.whiteSpace === 'normal' ? 'normal' : null;
65
+ const wordBreak = style.wordBreak === 'keep-all' ? 'keep-all' : style.wordBreak === 'normal' ? 'normal' : null;
66
+ if (!whiteSpace || !wordBreak)
67
+ return null;
68
+ const font = buildCanvasFont({ fontStyle: style.fontStyle, fontWeight: style.fontWeight, fontSize: style.fontSize, fontFamily: style.fontFamily });
69
+ if (!font)
70
+ return null;
71
+ // Both sides are added, so the screen's direction does not change the sum; the logical names say that (the audit of the chat asks for them)
72
+ const paddingX = pixelsOf(style.paddingInlineStart) + pixelsOf(style.paddingInlineEnd);
73
+ const borderX = pixelsOf(style.borderInlineStartWidth) + pixelsOf(style.borderInlineEndWidth);
74
+ const sizesByBorderBox = style.boxSizing === 'border-box';
75
+ // The used width (a number of px for a block that is laid out); without it, the client width, which is rounded
76
+ const usedWidth = Number.parseFloat(style.width);
77
+ const contentWidth = Number.isFinite(usedWidth) ? (sizesByBorderBox ? usedWidth - paddingX - borderX : usedWidth) : node.clientWidth - paddingX;
78
+ if (!(contentWidth >= 1))
79
+ return null;
80
+ return {
81
+ text,
82
+ availableWidth: contentWidth,
83
+ extraWidth: sizesByBorderBox ? paddingX + borderX : 0,
84
+ font,
85
+ letterSpacing: letterSpacingInPixels(style.letterSpacing),
86
+ whiteSpace,
87
+ wordBreak
88
+ };
89
+ }
90
+ /** The tight width of one bubble's text, or `null` to leave the bubble to CSS. */
91
+ function computeTightWidth(pretext, entry, box) {
92
+ if (!box)
93
+ return null;
94
+ try {
95
+ // `prepare()` is the expensive part, done once per text and font; a new width only runs the arithmetic after it
96
+ const preparedKey = `${box.font}|${box.letterSpacing}|${box.whiteSpace}|${box.wordBreak}|${box.text}`;
97
+ if (!entry.prepared || entry.preparedKey !== preparedKey) {
98
+ entry.prepared = pretext.prepare(box.text, box.font, {
99
+ whiteSpace: box.whiteSpace,
100
+ ...(box.wordBreak === 'keep-all' ? { wordBreak: 'keep-all' } : {}),
101
+ ...(box.letterSpacing !== 0 ? { letterSpacing: box.letterSpacing } : {})
102
+ });
103
+ entry.preparedKey = preparedKey;
104
+ }
105
+ const prepared = entry.prepared;
106
+ const engine = {
107
+ naturalWidth: pretext.measureNaturalWidth(prepared),
108
+ measureWrap: (width) => pretext.measureLineStats(prepared, width)
109
+ };
110
+ return findTightTextWidth(engine, box.availableWidth);
111
+ }
112
+ catch (error) {
113
+ // No canvas, a font string the canvas cannot read: the bubble stays as CSS made it
114
+ entry.prepared = null;
115
+ entry.preparedKey = '';
116
+ if (!loggedMeasureFailure) {
117
+ loggedMeasureFailure = true;
118
+ chatWarn('[Chat] A bubble could not be measured with Pretext, and keeps the width CSS gives it.', error);
119
+ }
120
+ return null;
121
+ }
122
+ }
123
+ function writeWidth(node, contentWidth, extraWidth) {
124
+ if (contentWidth === null) {
125
+ node.style.removeProperty('width');
126
+ node.style.removeProperty('max-width');
127
+ node.setAttribute(FIT_ATTRIBUTE, 'css');
128
+ return;
129
+ }
130
+ node.style.width = `${contentWidth + extraWidth}px`;
131
+ // Never past the room, if the room shrinks before the bubble is measured again
132
+ node.style.maxWidth = '100%';
133
+ node.setAttribute(FIT_ATTRIBUTE, 'tight');
134
+ }
135
+ /** How many lines the browser made of the text of an element. */
136
+ function countRenderedLines(node) {
137
+ const range = document.createRange();
138
+ range.selectNodeContents(node);
139
+ return countLinesByTops(Array.from(range.getClientRects(), (rectangle) => rectangle.top));
140
+ }
141
+ /**
142
+ * Makes sure that no bubble came out with more lines than Pretext counted (which would be worse than CSS): it widens it a little,
143
+ * and gives it back to CSS if that does not help. Only runs on the bubbles that were given a width, and almost never has to act.
144
+ */
145
+ function verifyWrapping(measured) {
146
+ for (const { entry, box, tight } of measured) {
147
+ if (countRenderedLines(entry.node) <= tight.lineCount)
148
+ continue;
149
+ let fitted = false;
150
+ for (const widerWidth of widerWidthsToTry(tight.width, box.availableWidth)) {
151
+ writeWidth(entry.node, widerWidth, box.extraWidth);
152
+ if (countRenderedLines(entry.node) <= tight.lineCount) {
153
+ fitted = true;
154
+ break;
155
+ }
156
+ }
157
+ if (!fitted)
158
+ writeWidth(entry.node, null, box.extraWidth);
159
+ if (!loggedDisagreement) {
160
+ loggedDisagreement = true;
161
+ chatWarn(fitted
162
+ ? '[Chat] The browser wrapped a bubble in more lines than Pretext counted: it was widened a little.'
163
+ : '[Chat] The browser wrapped a bubble in more lines than Pretext counted: it keeps the width CSS gives it.', { font: box.font, lineCount: tight.lineCount });
164
+ }
165
+ }
166
+ }
167
+ /** Gives every bubble that needs it its tight width, all in one pass over the page. */
168
+ async function flushBubbles() {
169
+ const pretext = await loadPretext();
170
+ const pending = [...entries].filter((entry) => entry.dirty && entry.node.isConnected);
171
+ if (pending.length === 0)
172
+ return;
173
+ if (!pretext) {
174
+ // Nothing to measure with: hand every bubble back to CSS, once
175
+ for (const entry of pending) {
176
+ writeWidth(entry.node, null, 0);
177
+ entry.dirty = false;
178
+ }
179
+ return;
180
+ }
181
+ // A font that is still loading would be measured as its fallback: its end wakes this up again
182
+ if (typeof document !== 'undefined' && document.fonts && document.fonts.status === 'loading')
183
+ return;
184
+ try {
185
+ // 1) Write: let CSS decide each width again, so that what is read next is the room the bubble has, not the width of an earlier pass
186
+ for (const entry of pending) {
187
+ entry.node.style.removeProperty('width');
188
+ entry.node.style.removeProperty('max-width');
189
+ }
190
+ // 2) Read: one layout for all of them
191
+ 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
195
+ const measured = [];
196
+ pending.forEach((entry, index) => {
197
+ const box = boxes[index] ?? null;
198
+ const tight = tightWidths[index] ?? null;
199
+ writeWidth(entry.node, tight ? tight.width : null, box ? box.extraWidth : 0);
200
+ if (box && tight)
201
+ measured.push({ entry, box, tight });
202
+ entry.dirty = false;
203
+ });
204
+ // 5) Verify what the browser did against what Pretext counted
205
+ verifyWrapping(measured);
206
+ if (!loggedFirstFit) {
207
+ loggedFirstFit = true;
208
+ chatLog('[Chat] Bubbles are sized to their text with Pretext.', { bubbles: pending.length, tight: measured.length });
209
+ }
210
+ }
211
+ catch (error) {
212
+ chatWarn('[Chat] Sizing the bubbles failed: they keep the width CSS gives them.', error);
213
+ for (const entry of pending) {
214
+ writeWidth(entry.node, null, 0);
215
+ entry.dirty = false;
216
+ }
217
+ }
218
+ }
219
+ // --- what wakes the bubbles up ------------------------------------------------------------------------------------
220
+ function markEveryBubbleDirty() {
221
+ for (const entry of entries)
222
+ entry.dirty = true;
223
+ scheduleFlush();
224
+ }
225
+ /** A web font finished loading: widths measured before were those of the fallback font. */
226
+ function handleFontsLoaded() {
227
+ loadedPretext?.clearCache();
228
+ for (const entry of entries) {
229
+ entry.prepared = null;
230
+ entry.preparedKey = '';
231
+ }
232
+ markEveryBubbleDirty();
233
+ }
234
+ function startListeningToFonts() {
235
+ if (listeningToFonts || typeof document === 'undefined' || !document.fonts)
236
+ return;
237
+ listeningToFonts = true;
238
+ document.fonts.addEventListener('loadingdone', handleFontsLoaded);
239
+ }
240
+ function stopListeningToFonts() {
241
+ if (!listeningToFonts || typeof document === 'undefined' || !document.fonts)
242
+ return;
243
+ listeningToFonts = false;
244
+ document.fonts.removeEventListener('loadingdone', handleFontsLoaded);
245
+ }
246
+ function observeRow(row, entry) {
247
+ let entriesInRow = entriesOfRow.get(row);
248
+ if (!entriesInRow) {
249
+ entriesInRow = new Set();
250
+ entriesOfRow.set(row, entriesInRow);
251
+ if (typeof ResizeObserver !== 'undefined') {
252
+ rowObserver ??= new ResizeObserver((records) => {
253
+ for (const record of records) {
254
+ const target = record.target;
255
+ const width = record.contentRect.width;
256
+ const previousWidth = lastWidthOfRow.get(target);
257
+ lastWidthOfRow.set(target, width);
258
+ // The first report only says where the row is; later ones matter only when its width changed (a new height is the
259
+ // bubble's own doing, and must not wake it up again)
260
+ if (previousWidth === undefined || Math.abs(previousWidth - width) < 0.5)
261
+ continue;
262
+ for (const entryInRow of entriesOfRow.get(target) ?? [])
263
+ entryInRow.dirty = true;
264
+ scheduleFlush();
265
+ }
266
+ });
267
+ rowObserver.observe(row);
268
+ }
269
+ }
270
+ entriesInRow.add(entry);
271
+ }
272
+ function unobserveRow(row, entry) {
273
+ const entriesInRow = entriesOfRow.get(row);
274
+ if (!entriesInRow)
275
+ return;
276
+ entriesInRow.delete(entry);
277
+ if (entriesInRow.size > 0)
278
+ return;
279
+ entriesOfRow.delete(row);
280
+ lastWidthOfRow.delete(row);
281
+ rowObserver?.unobserve(row);
282
+ }
283
+ /**
284
+ * 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
285
+ * a leak would show.
286
+ */
287
+ export function getBubbleShrinkWrapStats() {
288
+ return {
289
+ bubbles: entries.size,
290
+ rows: entriesOfRow.size,
291
+ watchingRows: rowObserver !== null,
292
+ listeningToFonts,
293
+ framePending: scheduledFrame !== null
294
+ };
295
+ }
296
+ // --- the action ---------------------------------------------------------------------------------------------------
297
+ /**
298
+ * Sizes the text element of a bubble to the narrowest width that keeps its number of lines. Put it on the element that holds the
299
+ * text (`<p class="whitespace-pre-wrap">`), inside a bubble as wide as its content, and mark the row the bubble sits in with
300
+ * `data-bubble-row` (the element whose width is the room of the bubble; without one, the element's parent stands for it).
301
+ *
302
+ * Plain text only: a bubble with code blocks or other widgets in it keeps the width CSS gives it.
303
+ *
304
+ * @example
305
+ * <p class="whitespace-pre-wrap" use:shrinkWrapBubble={{ text: message.content, enabled: tightBubbles }}>{message.content}</p>
306
+ */
307
+ export function shrinkWrapBubble(node, options) {
308
+ let entry = null;
309
+ function attach() {
310
+ if (entry || typeof window === 'undefined')
311
+ return;
312
+ const row = node.closest(`[${ROW_ATTRIBUTE}]`) ?? node.parentElement;
313
+ entry = { node, row, dirty: true, preparedKey: '', prepared: null };
314
+ entries.add(entry);
315
+ if (row)
316
+ observeRow(row, entry);
317
+ startListeningToFonts();
318
+ scheduleFlush();
319
+ }
320
+ function detach() {
321
+ if (!entry)
322
+ return;
323
+ entries.delete(entry);
324
+ if (entry.row)
325
+ unobserveRow(entry.row, entry);
326
+ entry = null;
327
+ // The bubble goes back to the width CSS gives it
328
+ node.style.removeProperty('width');
329
+ node.style.removeProperty('max-width');
330
+ node.removeAttribute(FIT_ATTRIBUTE);
331
+ if (entries.size === 0) {
332
+ stopListeningToFonts();
333
+ rowObserver?.disconnect();
334
+ rowObserver = null;
335
+ if (scheduledFrame !== null && typeof cancelAnimationFrame !== 'undefined')
336
+ cancelAnimationFrame(scheduledFrame);
337
+ scheduledFrame = null;
338
+ }
339
+ }
340
+ if (options.enabled !== false)
341
+ attach();
342
+ return {
343
+ update(nextOptions) {
344
+ if (nextOptions.enabled !== false) {
345
+ if (entry) {
346
+ // A new text (or the same, re-rendered): measured again
347
+ entry.dirty = true;
348
+ scheduleFlush();
349
+ }
350
+ else
351
+ attach();
352
+ }
353
+ else
354
+ detach();
355
+ },
356
+ destroy() {
357
+ detach();
358
+ }
359
+ };
360
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Client-side downscale before chat upload / codegen attachment IDs.
3
+ * Aligns with gateway JEV/Claude standard tier (long edge ≤ 1568 px, ~1.15 MP).
4
+ */
5
+ export declare const CHAT_AGENT_IMAGE_MAX_LONG_EDGE = 1568;
6
+ export declare const CHAT_AGENT_IMAGE_MAX_PIXELS: number;
7
+ export declare const CHAT_AGENT_IMAGE_TARGET_BYTES = 1500000;
8
+ export declare const CHAT_AGENT_JPEG_QUALITY = 0.85;
9
+ export type ChatImagePrepDecision = {
10
+ action: 'passthrough';
11
+ } | {
12
+ action: 'resize';
13
+ maxLongEdge: number;
14
+ quality: number;
15
+ targetBytes: number;
16
+ };
17
+ /** Pure policy: whether and how to resize before upload. */
18
+ export declare function decideChatImagePrep(width: number, height: number, byteLength: number, mimeType: string): ChatImagePrepDecision;
19
+ /**
20
+ * Downscales raster images for the agent; returns the original file on any skip or failure.
21
+ */
22
+ export declare function prepareChatImageFileForUpload(file: File): Promise<File>;
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Client-side downscale before chat upload / codegen attachment IDs.
3
+ * Aligns with gateway JEV/Claude standard tier (long edge ≤ 1568 px, ~1.15 MP).
4
+ */
5
+ export const CHAT_AGENT_IMAGE_MAX_LONG_EDGE = 1568;
6
+ export const CHAT_AGENT_IMAGE_MAX_PIXELS = 1_568 * 1_568;
7
+ export const CHAT_AGENT_IMAGE_TARGET_BYTES = 1_500_000;
8
+ export const CHAT_AGENT_JPEG_QUALITY = 0.85;
9
+ /** Pure policy: whether and how to resize before upload. */
10
+ export function decideChatImagePrep(width, height, byteLength, mimeType) {
11
+ if (!mimeType.startsWith('image/'))
12
+ return { action: 'passthrough' };
13
+ if (mimeType === 'image/svg+xml' || mimeType === 'image/gif')
14
+ return { action: 'passthrough' };
15
+ const longEdge = Math.max(width, height);
16
+ const pixels = width * height;
17
+ if (longEdge <= CHAT_AGENT_IMAGE_MAX_LONG_EDGE &&
18
+ pixels <= CHAT_AGENT_IMAGE_MAX_PIXELS &&
19
+ byteLength <= CHAT_AGENT_IMAGE_TARGET_BYTES) {
20
+ return { action: 'passthrough' };
21
+ }
22
+ return {
23
+ action: 'resize',
24
+ maxLongEdge: CHAT_AGENT_IMAGE_MAX_LONG_EDGE,
25
+ quality: CHAT_AGENT_JPEG_QUALITY,
26
+ targetBytes: CHAT_AGENT_IMAGE_TARGET_BYTES,
27
+ };
28
+ }
29
+ function loadImageFromFile(file) {
30
+ return new Promise((resolve, reject) => {
31
+ const url = URL.createObjectURL(file);
32
+ const img = new Image();
33
+ img.onload = () => {
34
+ URL.revokeObjectURL(url);
35
+ resolve(img);
36
+ };
37
+ img.onerror = () => {
38
+ URL.revokeObjectURL(url);
39
+ reject(new Error('Could not decode image'));
40
+ };
41
+ img.src = url;
42
+ });
43
+ }
44
+ function canvasToBlob(canvas, type, quality) {
45
+ return new Promise((resolve) => {
46
+ canvas.toBlob((blob) => resolve(blob), type, quality);
47
+ });
48
+ }
49
+ /**
50
+ * Downscales raster images for the agent; returns the original file on any skip or failure.
51
+ */
52
+ export async function prepareChatImageFileForUpload(file) {
53
+ if (!file.type.startsWith('image/'))
54
+ return file;
55
+ if (file.type === 'image/svg+xml' || file.type === 'image/gif')
56
+ return file;
57
+ try {
58
+ const img = await loadImageFromFile(file);
59
+ const decision = decideChatImagePrep(img.naturalWidth, img.naturalHeight, file.size, file.type);
60
+ if (decision.action === 'passthrough')
61
+ return file;
62
+ const scale = Math.min(1, decision.maxLongEdge / Math.max(img.naturalWidth, img.naturalHeight));
63
+ const width = Math.max(1, Math.round(img.naturalWidth * scale));
64
+ const height = Math.max(1, Math.round(img.naturalHeight * scale));
65
+ const canvas = document.createElement('canvas');
66
+ canvas.width = width;
67
+ canvas.height = height;
68
+ const ctx = canvas.getContext('2d');
69
+ if (!ctx)
70
+ return file;
71
+ ctx.drawImage(img, 0, 0, width, height);
72
+ const preferPng = file.type === 'image/png' && file.size < 400_000;
73
+ const mime = preferPng ? 'image/png' : 'image/jpeg';
74
+ let quality = decision.quality;
75
+ let blob = await canvasToBlob(canvas, mime, quality);
76
+ if (!blob)
77
+ return file;
78
+ while (blob.size > decision.targetBytes && quality > 0.5 && mime === 'image/jpeg') {
79
+ quality -= 0.08;
80
+ blob = (await canvasToBlob(canvas, mime, quality)) ?? blob;
81
+ }
82
+ const baseName = file.name.replace(/\.[^.]+$/, '') || 'image';
83
+ const ext = mime === 'image/png' ? 'png' : 'jpg';
84
+ return new File([blob], `${baseName}.${ext}`, { type: mime, lastModified: file.lastModified });
85
+ }
86
+ catch (error) {
87
+ console.warn('[Chat] Image prep failed; sending original file', error);
88
+ return file;
89
+ }
90
+ }
@@ -0,0 +1,13 @@
1
+ import type { CodeKind } from './codeStreamFormat.js';
2
+ /** Escapes the five characters that matter in HTML. */
3
+ export declare function escapeHtml(text: string): string;
4
+ /**
5
+ * The class prefix of the tokens the card draws (`wc-code-keyword`...), in place of highlight.js's own `hljs-`.
6
+ *
7
+ * A page's highlight.js theme, and the chat's own `CodeBlock`, paint `.hljs-keyword` and the like with rules that sit outside
8
+ * every cascade layer, and a rule outside the layers beats any utility class whatever its specificity. With another prefix no
9
+ * such theme can match the card's tokens, so the card's palette (Tailwind classes on the panel) is always the one that shows.
10
+ */
11
+ export declare const CODE_TOKEN_CLASS_PREFIX = "wc-code-";
12
+ /** The HTML of the code with its tokens in spans, or the code escaped when it has no grammar or the grammar fails. */
13
+ export declare function highlightCodeToHtml(code: string, kind: CodeKind): string;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Colours code for the code card: highlight.js turns the text into HTML whose spans carry the token classes (`hljs-keyword`,
3
+ * `hljs-tag`, `hljs-attr`...) that the card paints. The text is always escaped, so what the assistant wrote is never markup.
4
+ */
5
+ import hljs from 'highlight.js/lib/core';
6
+ import css from 'highlight.js/lib/languages/css';
7
+ import json from 'highlight.js/lib/languages/json';
8
+ import typescript from 'highlight.js/lib/languages/typescript';
9
+ import xml from 'highlight.js/lib/languages/xml';
10
+ import { chatWarn } from './logger.js';
11
+ // The grammars of what widgets are made of. (`CodeBlock` registers its own set on the same core: registering twice is harmless.)
12
+ hljs.registerLanguage('typescript', typescript);
13
+ hljs.registerLanguage('xml', xml);
14
+ hljs.registerLanguage('json', json);
15
+ hljs.registerLanguage('css', css);
16
+ /** The grammar for each kind of code: TSX is read by the TypeScript grammar, which knows JSX; a page or a component is markup. */
17
+ const HIGHLIGHT_LANGUAGE_BY_KIND = {
18
+ script: 'typescript',
19
+ markup: 'xml',
20
+ json: 'json',
21
+ plain: null
22
+ };
23
+ /** Escapes the five characters that matter in HTML. */
24
+ export function escapeHtml(text) {
25
+ return text
26
+ .replace(/&/g, '&amp;')
27
+ .replace(/</g, '&lt;')
28
+ .replace(/>/g, '&gt;')
29
+ .replace(/"/g, '&quot;')
30
+ .replace(/'/g, '&#039;');
31
+ }
32
+ /**
33
+ * The class prefix of the tokens the card draws (`wc-code-keyword`...), in place of highlight.js's own `hljs-`.
34
+ *
35
+ * A page's highlight.js theme, and the chat's own `CodeBlock`, paint `.hljs-keyword` and the like with rules that sit outside
36
+ * every cascade layer, and a rule outside the layers beats any utility class whatever its specificity. With another prefix no
37
+ * such theme can match the card's tokens, so the card's palette (Tailwind classes on the panel) is always the one that shows.
38
+ */
39
+ export const CODE_TOKEN_CLASS_PREFIX = 'wc-code-';
40
+ /** Gives the tokens of highlight.js's output the prefix of the card (a class like `function_` that has no prefix stays as it is). */
41
+ function renameTokenClasses(highlightedHtml) {
42
+ return highlightedHtml.replace(/class="([^"]*)"/g, (_match, classNames) => `class="${classNames.replace(/\bhljs-/g, CODE_TOKEN_CLASS_PREFIX)}"`);
43
+ }
44
+ /** Said once: a grammar that fails on one text will fail again on the next, and the code is shown plain either way. */
45
+ let hasReportedHighlightFailure = false;
46
+ /** The HTML of the code with its tokens in spans, or the code escaped when it has no grammar or the grammar fails. */
47
+ export function highlightCodeToHtml(code, kind) {
48
+ const language = HIGHLIGHT_LANGUAGE_BY_KIND[kind];
49
+ if (!language || code === '')
50
+ return escapeHtml(code);
51
+ try {
52
+ return renameTokenClasses(hljs.highlight(code, { language, ignoreIllegals: true }).value);
53
+ }
54
+ catch (error) {
55
+ if (!hasReportedHighlightFailure) {
56
+ hasReportedHighlightFailure = true;
57
+ chatWarn('[Chat] code card: the code could not be coloured, it is shown plain:', error);
58
+ }
59
+ return escapeHtml(code);
60
+ }
61
+ }
@@ -0,0 +1,6 @@
1
+ import type { FormatWithCursor } from './codeStreamFormat.js';
2
+ /**
3
+ * Formats a script (JavaScript, TypeScript, JSX or TSX: the `babel-ts` parser reads all four) and tells where the character at
4
+ * `cursorOffset` ended up. Rejects when the text does not parse, which the formatting of half-written code takes in stride.
5
+ */
6
+ export declare const formatScriptWithCursor: FormatWithCursor;
@@ -0,0 +1,34 @@
1
+ import { chatLog, chatWarn } from './logger.js';
2
+ /** How long a failed load is remembered: a card does not ask the network again for every line of code it formats. */
3
+ const RETRY_LOADING_AFTER_MS = 30_000;
4
+ /** The one load, shared by every card. */
5
+ let loadingPrettier = null;
6
+ function loadPrettier() {
7
+ if (!loadingPrettier) {
8
+ chatLog('[Chat] code card: loading Prettier');
9
+ loadingPrettier = Promise.all([
10
+ import('prettier/standalone'),
11
+ import('prettier/plugins/babel'),
12
+ import('prettier/plugins/estree')
13
+ ])
14
+ .then(([prettier, babel, estree]) => ({ prettier, plugins: [babel, estree] }))
15
+ .catch((error) => {
16
+ chatWarn('[Chat] code card: Prettier could not be loaded, the code is shown as it was written:', error);
17
+ // Forgotten after a while, so that a card opened later can try again
18
+ setTimeout(() => {
19
+ loadingPrettier = null;
20
+ }, RETRY_LOADING_AFTER_MS);
21
+ throw error;
22
+ });
23
+ }
24
+ return loadingPrettier;
25
+ }
26
+ /**
27
+ * Formats a script (JavaScript, TypeScript, JSX or TSX: the `babel-ts` parser reads all four) and tells where the character at
28
+ * `cursorOffset` ended up. Rejects when the text does not parse, which the formatting of half-written code takes in stride.
29
+ */
30
+ export const formatScriptWithCursor = async (text, cursorOffset) => {
31
+ const { prettier, plugins } = await loadPrettier();
32
+ const result = await prettier.formatWithCursor(text, { parser: 'babel-ts', plugins, cursorOffset });
33
+ return { formatted: result.formatted, cursorOffset: result.cursorOffset };
34
+ };