@widgetic/chat 0.1.45 → 0.1.47

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 (67) 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 +509 -94
  6. package/dist/components/Chat.svelte.d.ts +15 -2
  7. package/dist/components/ChatComposer.svelte +63 -69
  8. package/dist/components/ChatComposer.svelte.d.ts +8 -3
  9. package/dist/components/ChatDropOverlay.svelte +58 -0
  10. package/dist/components/ChatDropOverlay.svelte.d.ts +8 -0
  11. package/dist/components/ChatMessages.svelte +322 -98
  12. package/dist/components/ChatMessages.svelte.d.ts +11 -2
  13. package/dist/components/ComposerAttachmentsTray.svelte +144 -56
  14. package/dist/components/ComposerAttachmentsTray.svelte.d.ts +11 -1
  15. package/dist/components/FileGlyphIcon.svelte +34 -0
  16. package/dist/components/FileGlyphIcon.svelte.d.ts +8 -0
  17. package/dist/components/RestoreCheckpointDialog.svelte +66 -0
  18. package/dist/components/RestoreCheckpointDialog.svelte.d.ts +11 -0
  19. package/dist/components/SentAttachments.svelte +118 -0
  20. package/dist/components/SentAttachments.svelte.d.ts +12 -0
  21. package/dist/components/agent/AgentTurn.svelte +17 -2
  22. package/dist/components/agent/CodeCard.svelte +9 -3
  23. package/dist/i18n/messages.d.ts +43 -3
  24. package/dist/i18n/messages.js +49 -5
  25. package/dist/services/index.d.ts +4 -2
  26. package/dist/services/index.js +2 -1
  27. package/dist/services/limitRefusal.d.ts +42 -0
  28. package/dist/services/limitRefusal.js +60 -0
  29. package/dist/services/sketchAssistantClient.d.ts +11 -3
  30. package/dist/services/sketchAssistantClient.js +37 -10
  31. package/dist/services/sketchAssistantErrors.d.ts +16 -1
  32. package/dist/services/sketchAssistantErrors.js +25 -4
  33. package/dist/services/sketchAssistantOrchestrator.d.ts +7 -1
  34. package/dist/services/sketchAssistantOrchestrator.js +2 -2
  35. package/dist/types/attachment.d.ts +11 -0
  36. package/dist/utils/agentTurn.d.ts +32 -1
  37. package/dist/utils/agentTurn.js +46 -3
  38. package/dist/utils/attachmentDuplicates.d.ts +48 -0
  39. package/dist/utils/attachmentDuplicates.js +70 -0
  40. package/dist/utils/attachmentPolicy.d.ts +88 -0
  41. package/dist/utils/attachmentPolicy.js +135 -0
  42. package/dist/utils/attachmentPreview.d.ts +146 -0
  43. package/dist/utils/attachmentPreview.js +224 -0
  44. package/dist/utils/attachmentTray.d.ts +35 -0
  45. package/dist/utils/attachmentTray.js +27 -0
  46. package/dist/utils/chatFileDrag.d.ts +39 -0
  47. package/dist/utils/chatFileDrag.js +29 -0
  48. package/dist/utils/composerPreview.d.ts +33 -0
  49. package/dist/utils/composerPreview.js +31 -0
  50. package/dist/utils/generationArchiveStore.d.ts +5 -1
  51. package/dist/utils/generationArchiveStore.js +9 -4
  52. package/dist/utils/index.d.ts +1 -1
  53. package/dist/utils/index.js +1 -1
  54. package/dist/utils/limitFailureLine.d.ts +20 -0
  55. package/dist/utils/limitFailureLine.js +40 -0
  56. package/dist/utils/panelListPadding.d.ts +20 -0
  57. package/dist/utils/panelListPadding.js +31 -0
  58. package/dist/utils/pasteInsertion.d.ts +43 -0
  59. package/dist/utils/pasteInsertion.js +94 -0
  60. package/dist/utils/pastedContent.d.ts +13 -0
  61. package/dist/utils/pastedContent.js +18 -1
  62. package/dist/utils/referenceItems.js +11 -3
  63. package/dist/utils/sentAttachments.d.ts +43 -0
  64. package/dist/utils/sentAttachments.js +38 -0
  65. package/dist/utils/sentReferenceBadges.d.ts +11 -1
  66. package/dist/utils/sentReferenceBadges.js +47 -2
  67. package/package.json +3 -3
@@ -0,0 +1,224 @@
1
+ import { isPictureOfMessage } from './sentReferenceBadges.js';
2
+ /** The extensions of the files that are read as text when their type says nothing (a browser gives `.md` and `.csv` odd types). */
3
+ const TEXT_EXTENSIONS = new Set(['txt', 'md', 'markdown', 'csv', 'tsv', 'json', 'mermaid', 'mmd']);
4
+ /** The extensions of the files that are sheets: they get the glyph of a sheet. */
5
+ const SHEET_EXTENSIONS = new Set(['csv', 'tsv', 'xls', 'xlsx']);
6
+ /** The extensions of the videos a browser plays, for the case their type says nothing. */
7
+ const VIDEO_EXTENSIONS = new Set(['mp4', 'webm', 'mov', 'm4v', 'ogv']);
8
+ /** The extension of a file name in lower case, or '' when the name has none (`archive.tar.gz` is `gz`; `.env` has none). */
9
+ export function extensionOf(name) {
10
+ if (typeof name !== 'string')
11
+ return '';
12
+ const dotIndex = name.lastIndexOf('.');
13
+ if (dotIndex <= 0 || dotIndex === name.length - 1)
14
+ return '';
15
+ return name.slice(dotIndex + 1).toLowerCase();
16
+ }
17
+ /** The extension as the details line of the card writes it (`PNG`), or '' when the name has none. */
18
+ export function extensionLabelOf(name) {
19
+ return extensionOf(name).toUpperCase();
20
+ }
21
+ /** The type of a file with its parameters cut off and in lower case (`text/plain; charset=utf-8` is `text/plain`). */
22
+ function bareTypeOf(type) {
23
+ return typeof type === 'string' ? type.split(';')[0].trim().toLowerCase() : '';
24
+ }
25
+ /**
26
+ * Which kind of preview a file gets, or null when it gets none. The type of the file decides; when the type says nothing (an empty
27
+ * type, or the catch-all `application/octet-stream`) the extension of the name does; a picture is also known by its address.
28
+ */
29
+ export function previewKindOf(facts) {
30
+ const type = bareTypeOf(facts.type);
31
+ const extension = extensionOf(facts.name);
32
+ const typeSaysNothing = type === '' || type === 'application/octet-stream';
33
+ if (isPictureOfMessage({ file_type: type, url: facts.url ?? '' }))
34
+ return 'image';
35
+ if (type.startsWith('video/') || (typeSaysNothing && VIDEO_EXTENSIONS.has(extension)))
36
+ return 'video';
37
+ if (type === 'application/pdf' || (typeSaysNothing && extension === 'pdf'))
38
+ return 'pdf';
39
+ if (type.startsWith('text/') ||
40
+ type === 'application/json' ||
41
+ type === 'application/csv' ||
42
+ (typeSaysNothing && TEXT_EXTENSIONS.has(extension))) {
43
+ return 'text';
44
+ }
45
+ return null;
46
+ }
47
+ /** The glyph a file chip carries: it says at a glance what the file is, whether or not the file has a preview. */
48
+ export function fileGlyphOf(facts) {
49
+ const type = bareTypeOf(facts.type);
50
+ const extension = extensionOf(facts.name);
51
+ const kind = previewKindOf(facts);
52
+ if (kind === 'pdf')
53
+ return 'pdf';
54
+ if (kind === 'video')
55
+ return 'video';
56
+ if (type === 'text/csv' || type === 'application/csv' || SHEET_EXTENSIONS.has(extension))
57
+ return 'sheet';
58
+ if (kind === 'text')
59
+ return 'text';
60
+ return 'file';
61
+ }
62
+ /**
63
+ * A file of a sent message as the preview takes it, or null when it has none: a file without an address cannot be read, and a kind
64
+ * the preview does not show (a spreadsheet, an archive) has no card.
65
+ */
66
+ export function previewFileOfAttachment(attachment) {
67
+ const url = typeof attachment.url === 'string' ? attachment.url : '';
68
+ if (url === '')
69
+ return null;
70
+ const facts = { url, name: attachment.file_name, type: attachment.file_type };
71
+ if (previewKindOf(facts) === null)
72
+ return null;
73
+ return {
74
+ url,
75
+ name: attachment.file_name?.trim() || '',
76
+ type: attachment.file_type ?? '',
77
+ size: typeof attachment.file_size === 'number' && attachment.file_size > 0 ? attachment.file_size : null
78
+ };
79
+ }
80
+ /**
81
+ * The files a card steps through when one of them is pressed: those that have a preview, in the order the screen draws them (so the
82
+ * right arrow goes to the file drawn after this one). The files that have none are left out; `indexOf` says so with -1.
83
+ */
84
+ export function previewGroupOf(attachmentsInDrawnOrder) {
85
+ const files = [];
86
+ const placeByAttachment = new Map();
87
+ for (const attachment of attachmentsInDrawnOrder) {
88
+ const file = previewFileOfAttachment(attachment);
89
+ if (!file)
90
+ continue;
91
+ placeByAttachment.set(attachment, files.length);
92
+ files.push(file);
93
+ }
94
+ return { files, indexOf: (attachment) => placeByAttachment.get(attachment) ?? -1 };
95
+ }
96
+ /**
97
+ * What an arrow key does in the card, or null for any other key. The arrow keys follow the reading direction: the key that points
98
+ * toward the start of the line goes to the previous file and the key that points toward the end goes to the next one. On a left to
99
+ * right screen that is the left arrow and the right arrow; on a right to left screen the two swap, so the arrow points the way the
100
+ * files are laid out.
101
+ */
102
+ export function previewKeyAction(key, direction) {
103
+ if (key !== 'ArrowLeft' && key !== 'ArrowRight')
104
+ return null;
105
+ const keyPointsToStart = (key === 'ArrowLeft') === (direction !== 'rtl');
106
+ return keyPointsToStart ? 'previous' : 'next';
107
+ }
108
+ /**
109
+ * The place of the file an arrow leads to, or null when there is none (the first file has no one before it, the last none after it;
110
+ * the card does not wrap around, so the arrow is disabled at the ends).
111
+ */
112
+ export function steppedPreviewIndex(currentIndex, direction, fileCount) {
113
+ if (!Number.isInteger(currentIndex) || currentIndex < 0 || currentIndex >= fileCount)
114
+ return null;
115
+ const nextIndex = direction === 'previous' ? currentIndex - 1 : currentIndex + 1;
116
+ return nextIndex >= 0 && nextIndex < fileCount ? nextIndex : null;
117
+ }
118
+ /** What the card takes for itself around the file, in px: the same numbers as the File Browser's card (the padding, the header row). */
119
+ export const PREVIEW_CARD = {
120
+ /** The room between the card and the edge of the window, at each side. */
121
+ sideMargin: 24,
122
+ /** The padding of the card at both sides (24 each) and its two 1 px borders. */
123
+ horizontalPad: 50,
124
+ /** The top row of the card (the name and details, 36 px) and the gap below it (16 px). */
125
+ headerBlock: 52,
126
+ /** The padding of the card at the top and the bottom and its two borders. */
127
+ verticalPad: 50,
128
+ /** The air kept between the file and the edge of the window. */
129
+ contentVerticalGutter: 48,
130
+ /** The narrowest card: the name, the two arrows and the close button need this much. */
131
+ minWidth: 320,
132
+ /** The most of the window a card takes. */
133
+ maxHostFraction: 0.92,
134
+ /** The smallest side a picture is drawn at. */
135
+ minPictureSide: 68
136
+ };
137
+ const TOTAL_VERTICAL_SPACE = PREVIEW_CARD.verticalPad + PREVIEW_CARD.headerBlock;
138
+ /** A host with no size (a window that is not measured yet) gets the size of a common laptop screen, so the card is never 0 px. */
139
+ function usableHost(host) {
140
+ const width = Number.isFinite(host.width) && host.width > 0 ? host.width : 1280;
141
+ const height = Number.isFinite(host.height) && host.height > 0 ? host.height : 720;
142
+ return { width, height };
143
+ }
144
+ /**
145
+ * The card of a picture (or of a video, once the video tells its size): as big as the picture is, and no bigger than the window
146
+ * leaves room for. A small picture is never made larger. A picture that tells no size is drawn as a 4:3 one.
147
+ */
148
+ export function computePictureFrame(naturalWidth, naturalHeight, hostSize) {
149
+ const host = usableHost(hostSize);
150
+ const knownSize = Number.isFinite(naturalWidth) && Number.isFinite(naturalHeight) && naturalWidth > 0 && naturalHeight > 0;
151
+ const width = knownSize ? naturalWidth : 640;
152
+ const height = knownSize ? naturalHeight : 480;
153
+ const maxPictureWidth = Math.max(100, host.width * PREVIEW_CARD.maxHostFraction - 2 * PREVIEW_CARD.sideMargin - PREVIEW_CARD.horizontalPad);
154
+ const maxPictureHeight = Math.max(100, host.height * PREVIEW_CARD.maxHostFraction - TOTAL_VERTICAL_SPACE - PREVIEW_CARD.contentVerticalGutter);
155
+ const scale = Math.min(1, maxPictureWidth / width, maxPictureHeight / height);
156
+ const pictureWidth = Math.max(PREVIEW_CARD.minPictureSide, Math.round(width * scale));
157
+ const pictureHeight = Math.max(PREVIEW_CARD.minPictureSide, Math.round(height * scale));
158
+ const cardWidth = Math.min(Math.max(PREVIEW_CARD.minWidth, pictureWidth + PREVIEW_CARD.horizontalPad), Math.max(pictureWidth + PREVIEW_CARD.horizontalPad, host.width * PREVIEW_CARD.maxHostFraction - 2 * PREVIEW_CARD.sideMargin));
159
+ return { width: cardWidth, height: pictureHeight + TOTAL_VERTICAL_SPACE, pictureWidth, pictureHeight };
160
+ }
161
+ /** The card of a file that is not a picture: a fixed size for a message or a text, the whole window for a PDF (which needs the room). */
162
+ export function computeDocumentFrame(kind, hostSize) {
163
+ const host = usableHost(hostSize);
164
+ const maxWidth = Math.max(PREVIEW_CARD.minWidth, host.width - 2 * PREVIEW_CARD.sideMargin);
165
+ switch (kind) {
166
+ case 'error':
167
+ case 'loading':
168
+ return { width: Math.min(410, maxWidth), height: 256 };
169
+ case 'text':
170
+ return { width: Math.min(566, maxWidth), height: 460 };
171
+ case 'pdf': {
172
+ const maxAvailableHeight = host.height - TOTAL_VERTICAL_SPACE - PREVIEW_CARD.contentVerticalGutter;
173
+ const contentHeight = Math.max(200, Math.min(maxAvailableHeight, maxWidth * 0.75));
174
+ return { width: maxWidth, height: Math.round(contentHeight + TOTAL_VERTICAL_SPACE) };
175
+ }
176
+ }
177
+ }
178
+ /** The most characters of a text the card reads: the card shows a part of a very long text and says so, instead of freezing on it. */
179
+ export const PREVIEW_TEXT_MAX_CHARACTERS = 200_000;
180
+ /**
181
+ * The text of a file as the card shows it: a JSON file is indented so it can be read (a text that is not valid JSON stays as it is),
182
+ * the line ends of a Windows file are the line ends of any other, and a text longer than `PREVIEW_TEXT_MAX_CHARACTERS` is cut.
183
+ */
184
+ export function formatPreviewText(rawText, name) {
185
+ const normalized = rawText.replace(/\r\n?/g, '\n');
186
+ if (normalized.length > PREVIEW_TEXT_MAX_CHARACTERS) {
187
+ return { text: normalized.slice(0, PREVIEW_TEXT_MAX_CHARACTERS), truncated: true };
188
+ }
189
+ if (extensionOf(name) === 'json') {
190
+ try {
191
+ return { text: JSON.stringify(JSON.parse(normalized), null, 2), truncated: false };
192
+ }
193
+ catch {
194
+ // Not valid JSON (a file with a comment in it, or one that was cut): it is shown as it was written
195
+ }
196
+ }
197
+ return { text: normalized, truncated: false };
198
+ }
199
+ /** A length of time as `m:ss` (a video of 75 seconds is `1:15`), or '' when it is not known. */
200
+ export function durationText(seconds) {
201
+ if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0)
202
+ return '';
203
+ const wholeSeconds = Math.floor(seconds);
204
+ return `${Math.floor(wholeSeconds / 60)}:${String(wholeSeconds % 60).padStart(2, '0')}`;
205
+ }
206
+ /** The parts of the details line (`PNG`, `1024 × 1280`, `1.2 MB`); the card joins them with a dot. A part that is not known is left out. */
207
+ export function previewDetailParts(details, sizeText) {
208
+ const parts = [];
209
+ const extension = extensionLabelOf(details.name);
210
+ if (extension)
211
+ parts.push(extension);
212
+ const dimensions = details.dimensions;
213
+ if ((details.kind === 'image' || details.kind === 'video') && dimensions && dimensions.width > 0 && dimensions.height > 0) {
214
+ parts.push(`${Math.round(dimensions.width)} × ${Math.round(dimensions.height)}`);
215
+ }
216
+ if (details.kind === 'video') {
217
+ const length = durationText(details.durationSeconds);
218
+ if (length)
219
+ parts.push(length);
220
+ }
221
+ if (typeof details.size === 'number' && details.size > 0)
222
+ parts.push(sizeText(details.size));
223
+ return parts;
224
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Which of the attached files the tray above the text draws, and in what order. Kept apart from the components so Node can test it.
3
+ *
4
+ * The tray lives inside the message box, over the text. Its order does not follow the order the files were added in: the files that
5
+ * are not pictures come first, each as a chip, and the pictures come after them, one after the other, as small thumbnails. So a
6
+ * picture dropped before a PDF, and another dropped after it, still stand together below the PDF.
7
+ *
8
+ * A text that was pasted is not in the tray at all: it is in the words of the message, as a badge where the caret was.
9
+ */
10
+ import type { AttachmentInput } from '../types/attachment.js';
11
+ /** One file of the tray, with its place in the full list of attached files (what removing it needs). */
12
+ export interface TrayEntry {
13
+ attachment: AttachmentInput;
14
+ /** The place of the file in the list the page keeps: `onRemove` is given it, so a tray that shows the files in another order still removes the right one. */
15
+ index: number;
16
+ }
17
+ /** The tray as it is drawn, top to bottom. */
18
+ export interface TrayArrangement {
19
+ /** The files that are not pictures, in the order they were attached: each is a chip. */
20
+ chips: TrayEntry[];
21
+ /** The pictures, in the order they were attached: each is a thumbnail, and they follow one another below the chips. */
22
+ pictures: TrayEntry[];
23
+ }
24
+ /**
25
+ * Whether a file is a text pasted into the box (see `AttachmentInput.excerpt`): it stands in the words of the message, as a badge,
26
+ * so the tray has no tile for it.
27
+ */
28
+ export declare function isPastedTextAttachment(attachment: Pick<AttachmentInput, 'excerpt'>): boolean;
29
+ /**
30
+ * The files of the tray in the order they are drawn. A pasted text is left out (it has its place in the message). Two lists are
31
+ * given back, the chips and the pictures; each keeps the order in which its files were attached.
32
+ */
33
+ export declare function arrangeTrayAttachments(attachments: readonly AttachmentInput[], isPicture: (attachment: AttachmentInput) => boolean): TrayArrangement;
34
+ /** Whether the tray has anything to draw: some file that is not a pasted text. */
35
+ export declare function trayHasTiles(attachments: readonly AttachmentInput[]): boolean;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Whether a file is a text pasted into the box (see `AttachmentInput.excerpt`): it stands in the words of the message, as a badge,
3
+ * so the tray has no tile for it.
4
+ */
5
+ export function isPastedTextAttachment(attachment) {
6
+ return typeof attachment.excerpt === 'string';
7
+ }
8
+ /**
9
+ * The files of the tray in the order they are drawn. A pasted text is left out (it has its place in the message). Two lists are
10
+ * given back, the chips and the pictures; each keeps the order in which its files were attached.
11
+ */
12
+ export function arrangeTrayAttachments(attachments, isPicture) {
13
+ const arrangement = { chips: [], pictures: [] };
14
+ attachments.forEach((attachment, index) => {
15
+ if (isPastedTextAttachment(attachment))
16
+ return;
17
+ if (isPicture(attachment))
18
+ arrangement.pictures.push({ attachment, index });
19
+ else
20
+ arrangement.chips.push({ attachment, index });
21
+ });
22
+ return arrangement;
23
+ }
24
+ /** Whether the tray has anything to draw: some file that is not a pasted text. */
25
+ export function trayHasTiles(attachments) {
26
+ return attachments.some((attachment) => !isPastedTextAttachment(attachment));
27
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The rules of the screen that covers the chat while files are dragged over it, kept apart from the component so Node can test them.
3
+ *
4
+ * The whole chat takes a drop, not only the message box. The browser sends a `dragenter` and a `dragleave` every time the files
5
+ * cross from a part of the chat to another one (the header, a message, the box), so a `dragleave` alone does not say the files left:
6
+ * `dragLeftTheChat` tells the two apart. And the browser says nothing when the drag ends without a drop on the page (the Escape key,
7
+ * a window that took the files), so the chat takes the drag for over after `FILE_DRAG_IDLE_MS` without a `dragover`.
8
+ */
9
+ import type { DragVerdict } from './attachmentPolicy.js';
10
+ /** What covers the chat: nothing, the screen that invites the drop, or the one that says the files are not taken. */
11
+ export type FileDragOverlay = 'hidden' | 'accept' | 'refuse';
12
+ /**
13
+ * How long the chat waits for the next `dragover` before it takes the drag for over. The browser sends one every 50 to 350 ms for as
14
+ * long as files are over the page, so a longer silence means they are gone.
15
+ */
16
+ export declare const FILE_DRAG_IDLE_MS = 1500;
17
+ /** The screen a verdict on the files calls for: a drag with no file in it ('none') covers nothing. */
18
+ export declare function overlayForVerdict(verdict: DragVerdict): FileDragOverlay;
19
+ /** What a `dragleave` tells: where the files went (not every browser says) and where the pointer was. */
20
+ export interface DragLeaveFacts {
21
+ relatedTarget: unknown;
22
+ clientX: number;
23
+ clientY: number;
24
+ }
25
+ /** The chat the files are dragged over: whether an element is part of it, and the box it takes on the screen. */
26
+ export interface ChatBounds {
27
+ contains: (node: unknown) => boolean;
28
+ left: number;
29
+ top: number;
30
+ right: number;
31
+ bottom: number;
32
+ }
33
+ /**
34
+ * Whether a `dragleave` means the files left the chat (and did not just move from a part of it to another one). When the browser
35
+ * says where they went, that decides. When it does not (Safari gives no `relatedTarget`), the pointer decides: while it is still
36
+ * inside the chat the files are still over it. A pointer on the edge counts as out, as does the position (0, 0) a browser gives
37
+ * when the drag was cancelled with Escape.
38
+ */
39
+ export declare function dragLeftTheChat(leave: DragLeaveFacts, chat: ChatBounds): boolean;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The rules of the screen that covers the chat while files are dragged over it, kept apart from the component so Node can test them.
3
+ *
4
+ * The whole chat takes a drop, not only the message box. The browser sends a `dragenter` and a `dragleave` every time the files
5
+ * cross from a part of the chat to another one (the header, a message, the box), so a `dragleave` alone does not say the files left:
6
+ * `dragLeftTheChat` tells the two apart. And the browser says nothing when the drag ends without a drop on the page (the Escape key,
7
+ * a window that took the files), so the chat takes the drag for over after `FILE_DRAG_IDLE_MS` without a `dragover`.
8
+ */
9
+ /**
10
+ * How long the chat waits for the next `dragover` before it takes the drag for over. The browser sends one every 50 to 350 ms for as
11
+ * long as files are over the page, so a longer silence means they are gone.
12
+ */
13
+ export const FILE_DRAG_IDLE_MS = 1500;
14
+ /** The screen a verdict on the files calls for: a drag with no file in it ('none') covers nothing. */
15
+ export function overlayForVerdict(verdict) {
16
+ return verdict === 'none' ? 'hidden' : verdict;
17
+ }
18
+ /**
19
+ * Whether a `dragleave` means the files left the chat (and did not just move from a part of it to another one). When the browser
20
+ * says where they went, that decides. When it does not (Safari gives no `relatedTarget`), the pointer decides: while it is still
21
+ * inside the chat the files are still over it. A pointer on the edge counts as out, as does the position (0, 0) a browser gives
22
+ * when the drag was cancelled with Escape.
23
+ */
24
+ export function dragLeftTheChat(leave, chat) {
25
+ if (leave.relatedTarget && chat.contains(leave.relatedTarget))
26
+ return false;
27
+ const pointerIsInside = leave.clientX > chat.left && leave.clientX < chat.right && leave.clientY > chat.top && leave.clientY < chat.bottom;
28
+ return !pointerIsInside;
29
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The files of the message box as the preview card takes them: which of them can be opened, in what order the arrows step through
3
+ * them, and the address each is read from. Kept apart from the components so Node can test it.
4
+ *
5
+ * The order is the one the tray draws (the chips first, then the pictures), so the right arrow goes to the file drawn after the open one.
6
+ * A picture, a video or a PDF has an address the tray already draws it with (a `blob:` address of the file, or the address of its
7
+ * upload). A text file has none until it is uploaded, and the card reads text from an address, so one is made for it from the file
8
+ * itself; the page gives those addresses back when the card closes (`madeUrls`).
9
+ */
10
+ import type { AttachmentInput } from '../types/attachment.js';
11
+ import { type PreviewableFile } from './attachmentPreview.js';
12
+ /** What the rules need from the page. */
13
+ export interface ComposerPreviewOptions {
14
+ /** Whether a file of the box is a picture (the tray puts the pictures after the chips). */
15
+ isPicture: (attachment: AttachmentInput) => boolean;
16
+ /** The address the tray draws a file with, or '' when it has none yet. */
17
+ readUrl: (attachment: AttachmentInput) => string;
18
+ /** Makes an address for a file that has none. Left out, a file with no address cannot be opened. */
19
+ makeObjectUrl?: (file: File) => string | null | undefined;
20
+ }
21
+ /** The files of the box the card can step through, and where the one that was pressed stands. */
22
+ export interface ComposerPreview {
23
+ files: PreviewableFile[];
24
+ /** The place in `files` of the file that was pressed. */
25
+ openIndex: number;
26
+ /** The addresses that were made for the card alone (see `makeObjectUrl`): the page gives them back when the card closes. */
27
+ madeUrls: string[];
28
+ }
29
+ /**
30
+ * The card's files for the message box, with the pressed file's place, or null when the pressed file cannot be opened (its kind has no
31
+ * preview, or it has no address and none could be made).
32
+ */
33
+ export declare function composerPreviewOf(attachments: readonly AttachmentInput[], pressed: AttachmentInput, options: ComposerPreviewOptions): ComposerPreview | null;
@@ -0,0 +1,31 @@
1
+ import { arrangeTrayAttachments } from './attachmentTray.js';
2
+ import { previewKindOf } from './attachmentPreview.js';
3
+ /**
4
+ * The card's files for the message box, with the pressed file's place, or null when the pressed file cannot be opened (its kind has no
5
+ * preview, or it has no address and none could be made).
6
+ */
7
+ export function composerPreviewOf(attachments, pressed, options) {
8
+ const { chips, pictures } = arrangeTrayAttachments(attachments, options.isPicture);
9
+ const files = [];
10
+ const madeUrls = [];
11
+ let openIndex = -1;
12
+ for (const { attachment } of [...chips, ...pictures]) {
13
+ const name = attachment.file?.name ?? '';
14
+ const type = attachment.file?.type ?? '';
15
+ let url = options.readUrl(attachment);
16
+ // What the card cannot show is left out before an address is made for it
17
+ if (previewKindOf({ url, name, type }) === null)
18
+ continue;
19
+ if (!url && attachment.file && options.makeObjectUrl) {
20
+ url = options.makeObjectUrl(attachment.file) ?? '';
21
+ if (url)
22
+ madeUrls.push(url);
23
+ }
24
+ if (!url)
25
+ continue;
26
+ if (attachment === pressed)
27
+ openIndex = files.length;
28
+ files.push({ url, name, type, size: typeof attachment.file?.size === 'number' && attachment.file.size > 0 ? attachment.file.size : null });
29
+ }
30
+ return openIndex >= 0 ? { files, openIndex, madeUrls } : null;
31
+ }
@@ -1,4 +1,3 @@
1
- /** Local persistence for panel generation archive (thinking + code tails), keyed by conversation. */
2
1
  import { type CodeChanges } from './codeChanges.js';
3
2
  export type GenerationArchiveRecord = {
4
3
  thinking: string;
@@ -14,6 +13,11 @@ export type GenerationArchiveRecord = {
14
13
  * Records saved before this was kept have none.
15
14
  */
16
15
  changes?: CodeChanges | null;
16
+ /**
17
+ * The agent's own words about what the run changed (the conclusion says them), when the host gave them. Records saved before
18
+ * this was kept have none.
19
+ */
20
+ summary?: string | null;
17
21
  updatedAt: number;
18
22
  };
19
23
  export declare function loadGenerationArchive(conversationId: string | null | undefined): Promise<GenerationArchiveRecord | null>;
@@ -1,4 +1,5 @@
1
1
  /** Local persistence for panel generation archive (thinking + code tails), keyed by conversation. */
2
+ import { readGenerationSummary } from './agentTurn.js';
2
3
  import { readCodeChanges } from './codeChanges.js';
3
4
  const DB_NAME = 'widgetic-chat-generation-archive';
4
5
  const STORE = 'byConversation';
@@ -32,7 +33,8 @@ export async function loadGenerationArchive(conversationId) {
32
33
  const row = req.result;
33
34
  // Read again, not trusted: what is in the browser's storage is data of a past version, or of no version at all
34
35
  const savedChanges = readCodeChanges(row?.changes);
35
- if (!row || (!row.thinking?.trim() && !row.code?.trim() && savedChanges === null)) {
36
+ const savedSummary = readGenerationSummary(row?.summary);
37
+ if (!row || (!row.thinking?.trim() && !row.code?.trim() && savedChanges === null && savedSummary === null)) {
36
38
  resolve(null);
37
39
  return;
38
40
  }
@@ -42,6 +44,7 @@ export async function loadGenerationArchive(conversationId) {
42
44
  thoughtSeconds: row.thoughtSeconds ?? null,
43
45
  prompt: typeof row.prompt === 'string' ? row.prompt : '',
44
46
  changes: savedChanges,
47
+ summary: savedSummary,
45
48
  updatedAt: row.updatedAt ?? 0,
46
49
  });
47
50
  };
@@ -49,7 +52,7 @@ export async function loadGenerationArchive(conversationId) {
49
52
  });
50
53
  }
51
54
  catch (error) {
52
- console.debug('[generationArchiveStore] load skipped', error);
55
+ // console.debug('[generationArchiveStore] load skipped', error);
53
56
  return null;
54
57
  }
55
58
  }
@@ -58,9 +61,10 @@ export async function saveGenerationArchive(conversationId, record) {
58
61
  return;
59
62
  try {
60
63
  // Read again into plain data: IndexedDB cannot copy a proxy, and a record that fails to copy would lose the thinking and the
61
- // code with it. The read also keeps what is written inside the bounds of `readCodeChanges`.
64
+ // code with it. The read also keeps what is written inside the bounds of `readCodeChanges` and `readGenerationSummary`.
62
65
  const changesToSave = readCodeChanges(record.changes);
63
- if (!record.thinking.trim() && !record.code.trim() && changesToSave === null)
66
+ const summaryToSave = readGenerationSummary(record.summary);
67
+ if (!record.thinking.trim() && !record.code.trim() && changesToSave === null && summaryToSave === null)
64
68
  return;
65
69
  const db = await openDb();
66
70
  await new Promise((resolve, reject) => {
@@ -69,6 +73,7 @@ export async function saveGenerationArchive(conversationId, record) {
69
73
  conversationId,
70
74
  ...record,
71
75
  changes: changesToSave,
76
+ summary: summaryToSave,
72
77
  updatedAt: Date.now(),
73
78
  });
74
79
  tx.oncomplete = () => resolve();
@@ -12,7 +12,7 @@ export { readGenerationPlanFromMetadata, mapWidgetPlanToPlanCard, } from './gene
12
12
  export type { GenerationPlanWire, MappedGenerationPlanCard, WidgetPlanTaskStatusWire, } from './generationPlan.js';
13
13
  export { readCodeChanges, readCodeChangesFromMetadata } from './codeChanges.js';
14
14
  export type { CodeChangeFile, CodeChangeStatus, CodeChanges } from './codeChanges.js';
15
- export { AGENT_AVATAR_PIXELS, CURRENT_USER_PLACEHOLDER_ID, LOCAL_SERVICE_USER_ID, MAX_KEPT_GENERATION_CHARS, agentAvatarLabelKey, agentAvatarPixels, agentLookSignature, avatarStartAfter, finishedGenerationBelongsTo, finishedModulesView, keepFinishedGeneration, keptWorkIsOutdated, liveAgentLook, liveModulesView, memberDisplayName, memberMailtoHref, memberTooltipEmail, normalizePromptText, pageNamesPeople, resolveChatMember, settledAgentLook, soundStateOf, turnOutcome } from './agentTurn.js';
15
+ export { AGENT_AVATAR_PIXELS, CURRENT_USER_PLACEHOLDER_ID, LOCAL_SERVICE_USER_ID, MAX_KEPT_GENERATION_CHARS, MAX_KEPT_SUMMARY_CHARS, agentAvatarLabelKey, agentAvatarPixels, agentLookSignature, avatarStartAfter, finishedGenerationBelongsTo, finishedModulesView, keepFinishedGeneration, keptWorkIsOutdated, liveAgentLook, liveModulesView, memberDisplayName, memberMailtoHref, memberTooltipEmail, normalizePromptText, outcomeToShow, pageNamesPeople, readGenerationSummary, resolveChatMember, settledAgentLook, soundStateOf, turnOutcome } from './agentTurn.js';
16
16
  export { CHIP_NOTE_MAX_CHARACTERS, CHIP_NOTE_MAX_WORDS, firstWords, selectedElementChipLabel, selectedElementChipTitle, selectedElementName, } from './selectedElementChip.js';
17
17
  export type { SelectedElementChipSource } from './selectedElementChip.js';
18
18
  export { FOLLOW_UP_MAX_PILLS, FOLLOW_UP_TITLE_CHARS, FOLLOW_UP_TITLE_WORDS, findFollowUpCard, followUpPillsOf, followUpTitleOf, isFollowUpSuggestion, isRequestInDraft, questionOptionsOf } from './followUps.js';
@@ -18,7 +18,7 @@ export { readGenerationPlanFromMetadata, mapWidgetPlanToPlanCard, } from './gene
18
18
  export { readCodeChanges, readCodeChangesFromMetadata } from './codeChanges.js';
19
19
  // The assistant's turn: its avatar's looks, the judgement of a finished turn, who wrote a message, what is kept of the work.
20
20
  // A page that is not the chat (the workflows assistant) follows the same choreography through these.
21
- export { AGENT_AVATAR_PIXELS, CURRENT_USER_PLACEHOLDER_ID, LOCAL_SERVICE_USER_ID, MAX_KEPT_GENERATION_CHARS, agentAvatarLabelKey, agentAvatarPixels, agentLookSignature, avatarStartAfter, finishedGenerationBelongsTo, finishedModulesView, keepFinishedGeneration, keptWorkIsOutdated, liveAgentLook, liveModulesView, memberDisplayName, memberMailtoHref, memberTooltipEmail, normalizePromptText, pageNamesPeople, resolveChatMember, settledAgentLook, soundStateOf, turnOutcome } from './agentTurn.js';
21
+ export { AGENT_AVATAR_PIXELS, CURRENT_USER_PLACEHOLDER_ID, LOCAL_SERVICE_USER_ID, MAX_KEPT_GENERATION_CHARS, MAX_KEPT_SUMMARY_CHARS, agentAvatarLabelKey, agentAvatarPixels, agentLookSignature, avatarStartAfter, finishedGenerationBelongsTo, finishedModulesView, keepFinishedGeneration, keptWorkIsOutdated, liveAgentLook, liveModulesView, memberDisplayName, memberMailtoHref, memberTooltipEmail, normalizePromptText, outcomeToShow, pageNamesPeople, readGenerationSummary, resolveChatMember, settledAgentLook, soundStateOf, turnOutcome } from './agentTurn.js';
22
22
  // What the chip of a picked part says: the first words of its note, or its name while the note is empty.
23
23
  export { CHIP_NOTE_MAX_CHARACTERS, CHIP_NOTE_MAX_WORDS, firstWords, selectedElementChipLabel, selectedElementChipTitle, selectedElementName, } from './selectedElementChip.js';
24
24
  // The follow-up card (ideas for what to improve next, as pills under the last reply): which chips are pills (the ones with a
@@ -0,0 +1,20 @@
1
+ import type { Translate } from '@widgetic/design-system/i18n';
2
+ import { type ChatMessageKey } from '../i18n/messages.js';
3
+ /**
4
+ * Telling the chat's own sentences for a limit among the lines of a conversation.
5
+ *
6
+ * The sketch assistant says a refusal because of money in one of three sentences (`chat.sketch.noCredits`, `.planRequired`,
7
+ * `.limitReached`). A reply is saved as its words only, so after a reload the sentence is all the chat has to tell that the
8
+ * way out is to upgrade (the red failure line, and the "Upgrade" button under it).
9
+ *
10
+ * The words are read whole, and only these: a reply the model writes that happens to mention a free trial must never be
11
+ * taken for a limit (the looser test of `isPlanLimitMessage` would, and it is kept for the lines the widget creator saves
12
+ * for a code generation, which start with "Code generation failed").
13
+ */
14
+ /**
15
+ * The sentences, each as the English the host saves and as `translate` says it in the page's language (a host that saves the
16
+ * words it showed saved them in that language). Said once for a language, so a screen asks for it once and not for each line.
17
+ */
18
+ export declare function limitFailureSentencesOf(translate: Translate<ChatMessageKey>): ReadonlySet<string>;
19
+ /** Whether a saved line is, as a whole, one of the sentences for a limit (spaces around it do not matter). */
20
+ export declare function isLimitFailureLine(content: string | null | undefined, sentences: ReadonlySet<string>): boolean;
@@ -0,0 +1,40 @@
1
+ import { CHAT_MESSAGES } from '../i18n/messages.js';
2
+ /**
3
+ * Telling the chat's own sentences for a limit among the lines of a conversation.
4
+ *
5
+ * The sketch assistant says a refusal because of money in one of three sentences (`chat.sketch.noCredits`, `.planRequired`,
6
+ * `.limitReached`). A reply is saved as its words only, so after a reload the sentence is all the chat has to tell that the
7
+ * way out is to upgrade (the red failure line, and the "Upgrade" button under it).
8
+ *
9
+ * The words are read whole, and only these: a reply the model writes that happens to mention a free trial must never be
10
+ * taken for a limit (the looser test of `isPlanLimitMessage` would, and it is kept for the lines the widget creator saves
11
+ * for a code generation, which start with "Code generation failed").
12
+ */
13
+ /**
14
+ * The sentences, each as the English the host saves and as `translate` says it in the page's language (a host that saves the
15
+ * words it showed saved them in that language). Said once for a language, so a screen asks for it once and not for each line.
16
+ */
17
+ export function limitFailureSentencesOf(translate) {
18
+ const sentences = new Set([
19
+ CHAT_MESSAGES['chat.sketch.noCredits'],
20
+ CHAT_MESSAGES['chat.sketch.planRequired'],
21
+ CHAT_MESSAGES['chat.sketch.limitReached'],
22
+ ]);
23
+ for (const sentence of [
24
+ translate('chat.sketch.noCredits'),
25
+ translate('chat.sketch.planRequired'),
26
+ translate('chat.sketch.limitReached'),
27
+ ]) {
28
+ const trimmedSentence = sentence.trim();
29
+ if (trimmedSentence !== '')
30
+ sentences.add(trimmedSentence);
31
+ }
32
+ return sentences;
33
+ }
34
+ /** Whether a saved line is, as a whole, one of the sentences for a limit (spaces around it do not matter). */
35
+ export function isLimitFailureLine(content, sentences) {
36
+ if (typeof content !== 'string')
37
+ return false;
38
+ const trimmedContent = content.trim();
39
+ return trimmedContent !== '' && sentences.has(trimmedContent);
40
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The room the docked panel leaves at the sides of its list of messages (Figma: Chat states, "Thread").
3
+ *
4
+ * The list keeps 12 px at each side, exactly what the message box under it keeps, so the face of the assistant starts where the box
5
+ * starts and a bubble (and the face of the person who wrote it) ends where the box ends.
6
+ *
7
+ * A scrollbar that takes room of its own (the classic bars of Windows, or of a Mac with a mouse) sits inside the gap at the end: the
8
+ * padding there gives up as much as the bar takes, so the words still end where the box ends. A bar that floats over the list (the
9
+ * overlay bars of a Mac with a trackpad) takes none, and the padding stays what it is. The start is never touched.
10
+ *
11
+ * Plain TypeScript with no Svelte in it, so a test can hold it. `ChatMessages.svelte` reads the list (its width with and without
12
+ * the bar) and sets what this returns.
13
+ */
14
+ /** The room the list leaves at each side, in px: the message box under it keeps the same. */
15
+ export declare const PANEL_LIST_INLINE_PADDING_PX = 12;
16
+ /**
17
+ * The padding at the END of the list (in px) while a scrollbar takes room, or `null` when the padding of the list's own style is
18
+ * right (there is no bar, or it floats over the list). Never throws: a width that is not a number counts as no bar.
19
+ */
20
+ export declare function panelListEndPaddingPx(listHasScrollbar: boolean, scrollbarWidthPx: number): number | null;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The room the docked panel leaves at the sides of its list of messages (Figma: Chat states, "Thread").
3
+ *
4
+ * The list keeps 12 px at each side, exactly what the message box under it keeps, so the face of the assistant starts where the box
5
+ * starts and a bubble (and the face of the person who wrote it) ends where the box ends.
6
+ *
7
+ * A scrollbar that takes room of its own (the classic bars of Windows, or of a Mac with a mouse) sits inside the gap at the end: the
8
+ * padding there gives up as much as the bar takes, so the words still end where the box ends. A bar that floats over the list (the
9
+ * overlay bars of a Mac with a trackpad) takes none, and the padding stays what it is. The start is never touched.
10
+ *
11
+ * Plain TypeScript with no Svelte in it, so a test can hold it. `ChatMessages.svelte` reads the list (its width with and without
12
+ * the bar) and sets what this returns.
13
+ */
14
+ /** The room the list leaves at each side, in px: the message box under it keeps the same. */
15
+ export const PANEL_LIST_INLINE_PADDING_PX = 12;
16
+ /**
17
+ * The padding at the END of the list (in px) while a scrollbar takes room, or `null` when the padding of the list's own style is
18
+ * right (there is no bar, or it floats over the list). Never throws: a width that is not a number counts as no bar.
19
+ */
20
+ export function panelListEndPaddingPx(listHasScrollbar, scrollbarWidthPx) {
21
+ try {
22
+ if (!listHasScrollbar)
23
+ return null;
24
+ if (!Number.isFinite(scrollbarWidthPx) || scrollbarWidthPx <= 0)
25
+ return null;
26
+ return Math.max(0, PANEL_LIST_INLINE_PADDING_PX - scrollbarWidthPx);
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }