@widgetic/chat 0.1.45 → 0.1.48

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 (69) hide show
  1. package/README.md +148 -20
  2. package/dist/components/AttachmentDisplay.svelte +22 -130
  3. package/dist/components/AttachmentPreviewDialog.svelte +428 -0
  4. package/dist/components/AttachmentPreviewDialog.svelte.d.ts +14 -0
  5. package/dist/components/Chat.svelte +514 -94
  6. package/dist/components/Chat.svelte.d.ts +19 -2
  7. package/dist/components/ChatComposer.svelte +126 -72
  8. package/dist/components/ChatComposer.svelte.d.ts +13 -3
  9. package/dist/components/ChatDropOverlay.svelte +58 -0
  10. package/dist/components/ChatDropOverlay.svelte.d.ts +8 -0
  11. package/dist/components/ChatInput.svelte +42 -1
  12. package/dist/components/ChatInput.svelte.d.ts +2 -0
  13. package/dist/components/ChatMessages.svelte +322 -98
  14. package/dist/components/ChatMessages.svelte.d.ts +11 -2
  15. package/dist/components/ComposerAttachmentsTray.svelte +144 -56
  16. package/dist/components/ComposerAttachmentsTray.svelte.d.ts +11 -1
  17. package/dist/components/FileGlyphIcon.svelte +34 -0
  18. package/dist/components/FileGlyphIcon.svelte.d.ts +8 -0
  19. package/dist/components/RestoreCheckpointDialog.svelte +66 -0
  20. package/dist/components/RestoreCheckpointDialog.svelte.d.ts +11 -0
  21. package/dist/components/SentAttachments.svelte +118 -0
  22. package/dist/components/SentAttachments.svelte.d.ts +12 -0
  23. package/dist/components/agent/AgentTurn.svelte +17 -2
  24. package/dist/components/agent/CodeCard.svelte +9 -3
  25. package/dist/i18n/messages.d.ts +45 -3
  26. package/dist/i18n/messages.js +51 -5
  27. package/dist/services/index.d.ts +4 -2
  28. package/dist/services/index.js +2 -1
  29. package/dist/services/limitRefusal.d.ts +42 -0
  30. package/dist/services/limitRefusal.js +60 -0
  31. package/dist/services/sketchAssistantClient.d.ts +11 -3
  32. package/dist/services/sketchAssistantClient.js +37 -10
  33. package/dist/services/sketchAssistantErrors.d.ts +16 -1
  34. package/dist/services/sketchAssistantErrors.js +25 -4
  35. package/dist/services/sketchAssistantOrchestrator.d.ts +7 -1
  36. package/dist/services/sketchAssistantOrchestrator.js +2 -2
  37. package/dist/types/attachment.d.ts +11 -0
  38. package/dist/utils/agentTurn.d.ts +32 -1
  39. package/dist/utils/agentTurn.js +46 -3
  40. package/dist/utils/attachmentDuplicates.d.ts +48 -0
  41. package/dist/utils/attachmentDuplicates.js +70 -0
  42. package/dist/utils/attachmentPolicy.d.ts +88 -0
  43. package/dist/utils/attachmentPolicy.js +135 -0
  44. package/dist/utils/attachmentPreview.d.ts +146 -0
  45. package/dist/utils/attachmentPreview.js +224 -0
  46. package/dist/utils/attachmentTray.d.ts +35 -0
  47. package/dist/utils/attachmentTray.js +27 -0
  48. package/dist/utils/chatFileDrag.d.ts +39 -0
  49. package/dist/utils/chatFileDrag.js +29 -0
  50. package/dist/utils/composerPreview.d.ts +33 -0
  51. package/dist/utils/composerPreview.js +31 -0
  52. package/dist/utils/generationArchiveStore.d.ts +5 -1
  53. package/dist/utils/generationArchiveStore.js +9 -4
  54. package/dist/utils/index.d.ts +1 -1
  55. package/dist/utils/index.js +1 -1
  56. package/dist/utils/limitFailureLine.d.ts +20 -0
  57. package/dist/utils/limitFailureLine.js +40 -0
  58. package/dist/utils/panelListPadding.d.ts +20 -0
  59. package/dist/utils/panelListPadding.js +31 -0
  60. package/dist/utils/pasteInsertion.d.ts +43 -0
  61. package/dist/utils/pasteInsertion.js +94 -0
  62. package/dist/utils/pastedContent.d.ts +13 -0
  63. package/dist/utils/pastedContent.js +18 -1
  64. package/dist/utils/referenceItems.js +11 -3
  65. package/dist/utils/sentAttachments.d.ts +43 -0
  66. package/dist/utils/sentAttachments.js +38 -0
  67. package/dist/utils/sentReferenceBadges.d.ts +11 -1
  68. package/dist/utils/sentReferenceBadges.js +47 -2
  69. package/package.json +3 -3
@@ -0,0 +1,43 @@
1
+ import type { AttachmentInput } from '../types/attachment.js';
2
+ /** Where the paste landed in the text of the box: the caret, or the part of the text that the paste replaces. */
3
+ export interface PasteSelection {
4
+ start: number;
5
+ end: number;
6
+ }
7
+ /** Whether a label is one a pasted text is given (for a draft that comes back without its files: see `Chat.svelte`). */
8
+ export declare function isPastedTextLabel(label: string): boolean;
9
+ /**
10
+ * Where in the text the badge goes, given where the caret was when the paste arrived (`snapshotText`, with `selection` in it) and
11
+ * what the box holds now (`currentText`). The two are the same unless the person typed in the moments between (a paste waits for
12
+ * the pastes before it, and a picture is made smaller first). Typing after the caret does not move it; typing before it does, and
13
+ * then the place is lost: the badge goes at the end of the text, which is where the person would look for it.
14
+ */
15
+ export declare function resolvePasteInsertionRange(snapshotText: string, currentText: string, selection: PasteSelection | null | undefined): PasteSelection;
16
+ /** What writing a badge into a text gives: the new text and where the caret goes (after the badge, ready to go on typing). */
17
+ export interface TokenWritten {
18
+ text: string;
19
+ caret: number;
20
+ }
21
+ /**
22
+ * Writes the badge of `label` into `text` over `range`. A space goes before it when a word stands right in front of it (a badge
23
+ * hugging a word would look like part of it), and the design system's plan adds the space after it (unless one is there).
24
+ */
25
+ export declare function writeReferenceToken(text: string, range: PasteSelection, label: string): TokenWritten;
26
+ /** The words (labels, lower case) a text names: the badges in it and the `#label` words typed by hand. */
27
+ export declare function labelsNamedByText(text: string): Set<string>;
28
+ /**
29
+ * The files that go with a message: every file, except a pasted text the message no longer names. A pasted text has no tile in
30
+ * the tray, so a badge that was deleted (or cut, to be put somewhere else) leaves a file that nothing on the screen shows: it is
31
+ * kept (undo, or pasting the badge back, brings the badge to life again) but it must not be sent with words that do not name it.
32
+ */
33
+ export declare function attachmentsNamedByText(attachments: readonly AttachmentInput[], text: string): AttachmentInput[];
34
+ /**
35
+ * A draft that comes back after a refresh has its pictures but not the texts that were pasted (only pictures are kept in a draft).
36
+ * The badge of a text that is not here is taken out of the words, with one space beside it, instead of being left as a plain
37
+ * `#pasted_text` that stands for nothing. Only badges of the labels a pasted text is given are touched; `knownLabels` are the
38
+ * labels of the files that are attached now.
39
+ */
40
+ export declare function removeBadgesOfMissingPastedTexts(text: string, knownLabels: Iterable<string>): {
41
+ text: string;
42
+ removed: number;
43
+ };
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Where a pasted text goes in the message, and how it gets there. Kept apart from the components so Node can test it.
3
+ *
4
+ * A long text pasted into the box is attached as a file (`attachmentsFromPaste`), and the message names it with a badge written
5
+ * where the caret was: so a person who pastes a log after the second paragraph of a brief has the badge after the second paragraph,
6
+ * and can say "…as the error in #pasted_text shows" around it. The badge is the design system's token (its rooms, the `#`, the
7
+ * label), written into the text the box holds; the box paints it.
8
+ */
9
+ // From the module of the tokens itself and not from the folder's index: the index also brings the menu (a Svelte file), and what is
10
+ // needed here is the text model alone, which Node can load for the tests
11
+ import { FIGURE_SPACE, isRegularWhitespace, parseTokens, planTokenInsertion, referenceOccurrences, removeToken, } from '@widgetic/design-system/prompt-references/referenceTokens';
12
+ import { isPastedTextAttachment } from './attachmentTray.js';
13
+ /** The labels a pasted text is called by: `pasted_text`, then `pasted_text_2`, … (the file is `pasted-text.txt`, then `pasted-text-2.txt`). */
14
+ const PASTED_TEXT_LABEL_PATTERN = /^pasted_text(?:_\d+)?$/i;
15
+ /** Whether a label is one a pasted text is given (for a draft that comes back without its files: see `Chat.svelte`). */
16
+ export function isPastedTextLabel(label) {
17
+ return PASTED_TEXT_LABEL_PATTERN.test(label);
18
+ }
19
+ /** A number kept inside `[low, high]`; a value that is not a number is `low`. */
20
+ function clamp(value, low, high) {
21
+ if (!Number.isFinite(value))
22
+ return low;
23
+ return Math.min(high, Math.max(low, Math.floor(value)));
24
+ }
25
+ /**
26
+ * Where in the text the badge goes, given where the caret was when the paste arrived (`snapshotText`, with `selection` in it) and
27
+ * what the box holds now (`currentText`). The two are the same unless the person typed in the moments between (a paste waits for
28
+ * the pastes before it, and a picture is made smaller first). Typing after the caret does not move it; typing before it does, and
29
+ * then the place is lost: the badge goes at the end of the text, which is where the person would look for it.
30
+ */
31
+ export function resolvePasteInsertionRange(snapshotText, currentText, selection) {
32
+ if (!selection)
33
+ return { start: currentText.length, end: currentText.length };
34
+ const start = clamp(selection.start, 0, snapshotText.length);
35
+ const end = clamp(selection.end, start, snapshotText.length);
36
+ if (currentText === snapshotText)
37
+ return { start, end };
38
+ const textBeforeCaretIsTheSame = currentText.startsWith(snapshotText.slice(0, start));
39
+ if (!textBeforeCaretIsTheSame)
40
+ return { start: currentText.length, end: currentText.length };
41
+ // A selection the paste replaces is replaced only while it is still there: otherwise the badge is put in front of what stands there now.
42
+ const selectedText = snapshotText.slice(start, end);
43
+ const selectionIsStillThere = currentText.slice(start, start + selectedText.length) === selectedText;
44
+ return selectionIsStillThere ? { start, end: start + selectedText.length } : { start, end: start };
45
+ }
46
+ /**
47
+ * Writes the badge of `label` into `text` over `range`. A space goes before it when a word stands right in front of it (a badge
48
+ * hugging a word would look like part of it), and the design system's plan adds the space after it (unless one is there).
49
+ */
50
+ export function writeReferenceToken(text, range, label) {
51
+ const start = clamp(range.start, 0, text.length);
52
+ const end = clamp(range.end, start, text.length);
53
+ const plan = planTokenInsertion(text, { start, end }, label);
54
+ const characterBefore = start > 0 ? text[start - 1] : undefined;
55
+ const needsSpaceBefore = characterBefore !== undefined && characterBefore !== FIGURE_SPACE && !isRegularWhitespace(characterBefore);
56
+ const spaceBefore = needsSpaceBefore ? ' ' : '';
57
+ return {
58
+ text: `${text.slice(0, start)}${spaceBefore}${plan.insertion}${text.slice(end)}`,
59
+ caret: start + spaceBefore.length + plan.insertion.length,
60
+ };
61
+ }
62
+ /** The words (labels, lower case) a text names: the badges in it and the `#label` words typed by hand. */
63
+ export function labelsNamedByText(text) {
64
+ return new Set(referenceOccurrences(text).map((occurrence) => occurrence.label.toLowerCase()));
65
+ }
66
+ /**
67
+ * The files that go with a message: every file, except a pasted text the message no longer names. A pasted text has no tile in
68
+ * the tray, so a badge that was deleted (or cut, to be put somewhere else) leaves a file that nothing on the screen shows: it is
69
+ * kept (undo, or pasting the badge back, brings the badge to life again) but it must not be sent with words that do not name it.
70
+ */
71
+ export function attachmentsNamedByText(attachments, text) {
72
+ const named = labelsNamedByText(text);
73
+ return attachments.filter((attachment) => !isPastedTextAttachment(attachment) ||
74
+ (attachment.referenceLabel !== undefined && named.has(attachment.referenceLabel.toLowerCase())));
75
+ }
76
+ /**
77
+ * A draft that comes back after a refresh has its pictures but not the texts that were pasted (only pictures are kept in a draft).
78
+ * The badge of a text that is not here is taken out of the words, with one space beside it, instead of being left as a plain
79
+ * `#pasted_text` that stands for nothing. Only badges of the labels a pasted text is given are touched; `knownLabels` are the
80
+ * labels of the files that are attached now.
81
+ */
82
+ export function removeBadgesOfMissingPastedTexts(text, knownLabels) {
83
+ const known = new Set(Array.from(knownLabels, (label) => label.toLowerCase()));
84
+ let result = text;
85
+ let removed = 0;
86
+ // From the end, so the places of the badges before it stay as they were
87
+ for (const token of parseTokens(text).reverse()) {
88
+ if (!isPastedTextLabel(token.label) || known.has(token.label.toLowerCase()))
89
+ continue;
90
+ result = removeToken(result, token).text;
91
+ removed += 1;
92
+ }
93
+ return { text: result, removed };
94
+ }
@@ -33,7 +33,20 @@ export interface PastedAttachment {
33
33
  file: File;
34
34
  /** The first words of a pasted text. It is for the screen only: it is never sent anywhere, the name of the file is. */
35
35
  label?: string;
36
+ /**
37
+ * The beginning of a pasted text (see `pastedTextExcerpt`): the card over the text's badge shows it. Only a pasted text has one,
38
+ * and it is what tells a pasted text from any other file. For the screen only: it is never sent anywhere.
39
+ */
40
+ excerpt?: string;
36
41
  }
42
+ /** Longest excerpt of a pasted text, in characters: far more than the card over the badge has room for (it cuts it again by lines). */
43
+ export declare const PASTED_TEXT_EXCERPT_MAX_CHARACTERS = 600;
44
+ /**
45
+ * The beginning of a pasted text as the card over its badge shows it: the text as it was written (its line breaks stay, so a list
46
+ * or a piece of code reads as it did), with the blank lines at both ends and runs of more than one blank line in a row taken out,
47
+ * cut at `maxCharacters` with an ellipsis. A text that fits is returned whole, with no ellipsis.
48
+ */
49
+ export declare function pastedTextExcerpt(text: string, maxCharacters?: number): string;
37
50
  /** One entry of `clipboardData.items`, as much as the rules read of it. */
38
51
  export interface PasteSourceItem {
39
52
  readonly kind: string;
@@ -27,6 +27,23 @@ export const DEFAULT_PASTED_TEXT_THRESHOLDS = {
27
27
  minCharacters: PASTED_TEXT_MIN_CHARACTERS,
28
28
  minLines: PASTED_TEXT_MIN_LINES
29
29
  };
30
+ /** Longest excerpt of a pasted text, in characters: far more than the card over the badge has room for (it cuts it again by lines). */
31
+ export const PASTED_TEXT_EXCERPT_MAX_CHARACTERS = 600;
32
+ /**
33
+ * The beginning of a pasted text as the card over its badge shows it: the text as it was written (its line breaks stay, so a list
34
+ * or a piece of code reads as it did), with the blank lines at both ends and runs of more than one blank line in a row taken out,
35
+ * cut at `maxCharacters` with an ellipsis. A text that fits is returned whole, with no ellipsis.
36
+ */
37
+ export function pastedTextExcerpt(text, maxCharacters = PASTED_TEXT_EXCERPT_MAX_CHARACTERS) {
38
+ const tidyText = (text ?? '')
39
+ .replace(/\r\n?/g, '\n')
40
+ .replace(/\n{3,}/g, '\n\n')
41
+ .trim();
42
+ const characters = Array.from(tidyText);
43
+ if (characters.length <= maxCharacters)
44
+ return tidyText;
45
+ return `${characters.slice(0, maxCharacters).join('').trimEnd()}…`;
46
+ }
30
47
  /** A line break of any system. */
31
48
  const LINE_BREAK = /\r\n|\r|\n/;
32
49
  /** A text that is nothing but one address: what some browsers write next to a picture copied from a page. */
@@ -252,7 +269,7 @@ export function attachmentsFromPaste(source, thresholds = {}) {
252
269
  }
253
270
  // Chat text, a long brief, a log: it is kept out of the box (which shows a few lines) and attached as a text file.
254
271
  if (isLongPastedText(pastedText, thresholds)) {
255
- return [{ file: textAsFile(pastedText), label: pastedTextLabel(pastedText) }];
272
+ return [{ file: textAsFile(pastedText), label: pastedTextLabel(pastedText), excerpt: pastedTextExcerpt(pastedText) }];
256
273
  }
257
274
  return [];
258
275
  }
@@ -1,3 +1,4 @@
1
+ import { isPastedTextAttachment } from "./attachmentTray.js";
1
2
  /**
2
3
  * The files of the composer tray as the message box offers them to a `#` (the design system's `references` prop). Kept apart from
3
4
  * the components so Node can test it. The label a file is called by is given in `Chat.svelte` when the file joins the tray; the rules
@@ -27,17 +28,24 @@ export function buildReferenceItems(attachments, sources) {
27
28
  const items = [];
28
29
  for (const attachment of attachments) {
29
30
  const label = attachment.referenceLabel;
30
- if (!label || !sources.isReferenceable(attachment))
31
+ // A text pasted into the box is always referenceable: its badge is how the message holds it (see `isPastedTextAttachment`).
32
+ const pastedText = isPastedTextAttachment(attachment);
33
+ if (!label || !(pastedText || sources.isReferenceable(attachment)))
31
34
  continue;
32
- const previewUrl = sources.previewUrlOf(attachment);
35
+ const previewUrl = pastedText ? "" : sources.previewUrlOf(attachment);
33
36
  const sizeLabel = sources.sizeLabelOf(attachment);
34
37
  items.push({
35
38
  id: referenceIdOf(attachment),
36
39
  label,
37
40
  number: items.length + 1,
38
- fileName: attachment.file?.name ?? "",
41
+ // A pasted text is called by its first words (what its tile used to say), not by "pasted-text.txt".
42
+ fileName: pastedText
43
+ ? attachment.label || attachment.file?.name || ""
44
+ : (attachment.file?.name ?? ""),
39
45
  previewUrl: previewUrl || null,
40
46
  sizeLabel: sizeLabel || undefined,
47
+ // The card over its badge shows what the text says, cut short with an ellipsis (the design system draws it).
48
+ ...(pastedText ? { excerpt: attachment.excerpt } : {}),
41
49
  });
42
50
  }
43
51
  return items;
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Which of the files of a sent message are drawn above its bubble, and in what order. Kept apart from the components so Node can test it.
3
+ *
4
+ * A person who sends a message with files sees the same small arrangement they saw in the message box: the files that are not
5
+ * pictures come first, each as a chip with the glyph of its kind, and the pictures follow below them as small thumbnails, one after the
6
+ * other, whatever order the files were attached in. Both rows sit above the bubble (a bubble holds words, not pictures), at its end.
7
+ *
8
+ * A text that was pasted into the box is not drawn here when the words of the message name it with a badge: the badge stands where the
9
+ * text was pasted, so a chip of the same file would show it twice. A pasted text no badge names is drawn as a chip, so no file of a
10
+ * message is ever hidden without a reason.
11
+ */
12
+ import type { ContentItemOutput } from '../types/message.js';
13
+ /** One file of a sent message, with its place in the list the message holds. */
14
+ export interface SentEntry {
15
+ attachment: ContentItemOutput;
16
+ /** The place of the file among the files of the message (the number a badge of the words carries as `attachmentIndex`). */
17
+ index: number;
18
+ }
19
+ /** The files of a message as they are drawn, top to bottom. */
20
+ export interface SentArrangement {
21
+ /** The files that are not pictures, in the order the message holds them: each is a chip. */
22
+ chips: SentEntry[];
23
+ /** The pictures, in the order the message holds them: each is a small thumbnail below the chips. */
24
+ pictures: SentEntry[];
25
+ }
26
+ /** What of a badge of the words matters here: that it is one, and which file it names (the shape of the design system's `SentSegment`). */
27
+ export interface BadgeSegmentFacts {
28
+ kind: string;
29
+ attachmentIndex?: number;
30
+ }
31
+ /** The places of the files that a badge of the message's words names (an empty set when the words have no badge). */
32
+ export declare function attachmentIndexesNamedByBadges(segments: readonly BadgeSegmentFacts[] | null | undefined): Set<number>;
33
+ /** Whether a file is drawn as a thumbnail: a picture that has an address to draw it from. */
34
+ export declare function isSentPicture(attachment: ContentItemOutput): boolean;
35
+ /**
36
+ * The files of a message in the order they are drawn. A pasted text that a badge names is left out; every other file is drawn, as a
37
+ * chip or as a thumbnail, and each row keeps the order in which its files were attached.
38
+ */
39
+ export declare function arrangeSentAttachments(attachments: readonly ContentItemOutput[], namedByBadge?: ReadonlySet<number>): SentArrangement;
40
+ /** Whether there is anything to draw above the bubble. */
41
+ export declare function hasSentTiles(arrangement: SentArrangement): boolean;
42
+ /** The files in the order the screen draws them (the chips, then the pictures): the order the arrows of the preview step through. */
43
+ export declare function sentAttachmentsInDrawnOrder(arrangement: SentArrangement): ContentItemOutput[];
@@ -0,0 +1,38 @@
1
+ import { isPastedTextOfMessage, isPictureOfMessage } from './sentReferenceBadges.js';
2
+ /** The places of the files that a badge of the message's words names (an empty set when the words have no badge). */
3
+ export function attachmentIndexesNamedByBadges(segments) {
4
+ const named = new Set();
5
+ for (const segment of segments ?? []) {
6
+ if (segment.kind === 'badge' && typeof segment.attachmentIndex === 'number')
7
+ named.add(segment.attachmentIndex);
8
+ }
9
+ return named;
10
+ }
11
+ /** Whether a file is drawn as a thumbnail: a picture that has an address to draw it from. */
12
+ export function isSentPicture(attachment) {
13
+ return isPictureOfMessage(attachment) && typeof attachment.url === 'string' && attachment.url !== '';
14
+ }
15
+ /**
16
+ * The files of a message in the order they are drawn. A pasted text that a badge names is left out; every other file is drawn, as a
17
+ * chip or as a thumbnail, and each row keeps the order in which its files were attached.
18
+ */
19
+ export function arrangeSentAttachments(attachments, namedByBadge = new Set()) {
20
+ const arrangement = { chips: [], pictures: [] };
21
+ attachments.forEach((attachment, index) => {
22
+ if (isPastedTextOfMessage(attachment) && namedByBadge.has(index))
23
+ return;
24
+ if (isSentPicture(attachment))
25
+ arrangement.pictures.push({ attachment, index });
26
+ else
27
+ arrangement.chips.push({ attachment, index });
28
+ });
29
+ return arrangement;
30
+ }
31
+ /** Whether there is anything to draw above the bubble. */
32
+ export function hasSentTiles(arrangement) {
33
+ return arrangement.chips.length + arrangement.pictures.length > 0;
34
+ }
35
+ /** The files in the order the screen draws them (the chips, then the pictures): the order the arrows of the preview step through. */
36
+ export function sentAttachmentsInDrawnOrder(arrangement) {
37
+ return [...arrangement.chips, ...arrangement.pictures].map((entry) => entry.attachment);
38
+ }
@@ -14,13 +14,23 @@ export declare const SENT_BADGE_PICTURE_PX = 18;
14
14
  type PictureFacts = Pick<ContentItemOutput, 'file_type' | 'url'>;
15
15
  /** Whether a file of a message is a picture (the only files a badge shows, since a badge shows what is in the file). */
16
16
  export declare function isPictureOfMessage(attachment: PictureFacts): boolean;
17
+ /** Whether a file of a message is a text that was pasted into the box (it has no thumbnail: its badge shows a file glyph). */
18
+ export declare function isPastedTextOfMessage(attachment: Pick<ContentItemOutput, 'file_name'> | undefined): boolean;
17
19
  /**
18
20
  * The files of a message as `segmentSentText` takes them, in the order the message holds them. Every file counts for the rule (a
19
- * name two files share is not trusted, whatever the files are); only a picture that has an address to draw it from may have a badge.
21
+ * name two files share is not trusted, whatever the files are); only a picture that has an address to draw it from, and a text that
22
+ * was pasted (its badge draws a glyph), may have a badge.
20
23
  */
21
24
  export declare function sentAttachmentsOf(attachments: readonly ContentItemOutput[]): SentAttachment[];
22
25
  /** The address of the picture a badge shows, at the size a badge draws it, or '' when the file has none. */
23
26
  export declare function sentBadgePictureOf(attachment: Pick<ContentItemOutput, 'url'> | undefined): string;
24
27
  /** What a badge says to a screen reader beyond its words: the name of the file, or nothing when the file has none. */
25
28
  export declare function sentBadgeTitleOf(attachment: Pick<ContentItemOutput, 'file_name'> | undefined): string | undefined;
29
+ /**
30
+ * The beginning of a text that was pasted into a sent message, read from the file the message holds (its address). The message
31
+ * keeps the file and not the excerpt, so it is fetched when the pointer rests on the badge. Resolves to '' when the file cannot be
32
+ * read (the page it is on is not allowed to, the address is gone, it takes too long): the badge then says the name of the file.
33
+ * `fetchText` is the browser's `fetch`, given by the caller so Node can test the rest.
34
+ */
35
+ export declare function fetchPastedTextExcerpt(url: string, fetchText?: typeof fetch, timeLimitMilliseconds?: number): Promise<string>;
26
36
  export {};
@@ -1,4 +1,6 @@
1
1
  import { buildImageThumbnailUrl } from './imageTransform.js';
2
+ import { pastedTextExcerpt } from './pastedContent.js';
3
+ import { chatWarn } from './logger.js';
2
4
  /** The side of the picture inside a badge, in CSS px (the design system's `BADGE_THUMBNAIL_SIZE_PX`). */
3
5
  export const SENT_BADGE_PICTURE_PX = 18;
4
6
  /** Whether a file of a message is a picture (the only files a badge shows, since a badge shows what is in the file). */
@@ -8,14 +10,26 @@ export function isPictureOfMessage(attachment) {
8
10
  const url = attachment.url;
9
11
  return typeof url === 'string' && (/^data:image\//i.test(url) || /\.(png|jpe?g|gif|webp|svg)(\?|$)/i.test(url));
10
12
  }
13
+ /**
14
+ * A text that was pasted into the message box is attached under the name "pasted-text.txt" (then "pasted-text-2.txt", …): that is
15
+ * what a message's file says it is. The words of the message name it with a badge, written where the text was pasted.
16
+ */
17
+ const PASTED_TEXT_FILE_NAME_PATTERN = /^pasted-text(?:-\d+)?\.txt$/i;
18
+ /** Whether a file of a message is a text that was pasted into the box (it has no thumbnail: its badge shows a file glyph). */
19
+ export function isPastedTextOfMessage(attachment) {
20
+ const name = attachment?.file_name?.trim();
21
+ return !!name && PASTED_TEXT_FILE_NAME_PATTERN.test(name);
22
+ }
11
23
  /**
12
24
  * The files of a message as `segmentSentText` takes them, in the order the message holds them. Every file counts for the rule (a
13
- * name two files share is not trusted, whatever the files are); only a picture that has an address to draw it from may have a badge.
25
+ * name two files share is not trusted, whatever the files are); only a picture that has an address to draw it from, and a text that
26
+ * was pasted (its badge draws a glyph), may have a badge.
14
27
  */
15
28
  export function sentAttachmentsOf(attachments) {
16
29
  return attachments.map((attachment) => ({
17
30
  fileName: attachment.file_name ?? null,
18
- badge: isPictureOfMessage(attachment) && typeof attachment.url === 'string' && attachment.url !== ''
31
+ badge: (isPictureOfMessage(attachment) && typeof attachment.url === 'string' && attachment.url !== '') ||
32
+ isPastedTextOfMessage(attachment)
19
33
  }));
20
34
  }
21
35
  /** The address of the picture a badge shows, at the size a badge draws it, or '' when the file has none. */
@@ -30,3 +44,34 @@ export function sentBadgeTitleOf(attachment) {
30
44
  const name = attachment?.file_name?.trim();
31
45
  return name ? name : undefined;
32
46
  }
47
+ /** The most of a pasted text the card over its badge needs; the rest of a long text is never read for it. */
48
+ const PASTED_TEXT_READ_MAX_CHARACTERS = 4000;
49
+ /** How long the stored text may take to come before the badge is left with the name of the file. */
50
+ const PASTED_TEXT_FETCH_TIME_LIMIT_MS = 6000;
51
+ /**
52
+ * The beginning of a text that was pasted into a sent message, read from the file the message holds (its address). The message
53
+ * keeps the file and not the excerpt, so it is fetched when the pointer rests on the badge. Resolves to '' when the file cannot be
54
+ * read (the page it is on is not allowed to, the address is gone, it takes too long): the badge then says the name of the file.
55
+ * `fetchText` is the browser's `fetch`, given by the caller so Node can test the rest.
56
+ */
57
+ export async function fetchPastedTextExcerpt(url, fetchText = (input, init) => fetch(input, init), timeLimitMilliseconds = PASTED_TEXT_FETCH_TIME_LIMIT_MS) {
58
+ if (!url)
59
+ return '';
60
+ const controller = typeof AbortController === 'function' ? new AbortController() : null;
61
+ const timer = controller ? setTimeout(() => controller.abort(), timeLimitMilliseconds) : null;
62
+ try {
63
+ const response = await fetchText(url, controller ? { signal: controller.signal } : undefined);
64
+ if (!response.ok)
65
+ return '';
66
+ const wholeText = await response.text();
67
+ return pastedTextExcerpt(wholeText.slice(0, PASTED_TEXT_READ_MAX_CHARACTERS));
68
+ }
69
+ catch (error) {
70
+ chatWarn('[sentReferenceBadges] The text of a pasted text could not be read for its badge:', error);
71
+ return '';
72
+ }
73
+ finally {
74
+ if (timer)
75
+ clearTimeout(timer);
76
+ }
77
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/chat",
3
- "version": "0.1.45",
3
+ "version": "0.1.48",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -57,7 +57,7 @@
57
57
  },
58
58
  "peerDependencies": {
59
59
  "@widgetic/api-sdk": "*",
60
- "@widgetic/design-system": ">=0.5.36",
60
+ "@widgetic/design-system": ">=0.5.43",
61
61
  "svelte": "^5.25.6"
62
62
  },
63
63
  "dependencies": {
@@ -75,7 +75,7 @@
75
75
  "@tailwindcss/postcss": "^4.1.4",
76
76
  "@types/node": "^26.4.1",
77
77
  "@widgetic/api-sdk": "^1.0.10",
78
- "@widgetic/design-system": "^0.5.39",
78
+ "@widgetic/design-system": "^0.5.43",
79
79
  "@widgetic/dev-tools": "^0.2.0",
80
80
  "autoprefixer": "^10.4.20",
81
81
  "eslint": "^9.0.0",