@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
@@ -59,6 +59,33 @@
59
59
  import ActionBar from './ActionBar.svelte';
60
60
  import PanelChatHeader from './PanelChatHeader.svelte';
61
61
  import ComposerAttachmentsTray from './ComposerAttachmentsTray.svelte';
62
+ import AttachmentPreviewDialog from './AttachmentPreviewDialog.svelte';
63
+ import ChatDropOverlay from './ChatDropOverlay.svelte';
64
+ import { composerPreviewOf } from '../utils/composerPreview.js';
65
+ import type { PreviewableFile } from '../utils/attachmentPreview.js';
66
+ import { isPastedTextAttachment, trayHasTiles } from '../utils/attachmentTray.js';
67
+ import { fingerprintFile, splitNewFromKnown } from '../utils/attachmentDuplicates.js';
68
+ import {
69
+ ATTACHMENT_ACCEPT_ATTRIBUTE,
70
+ checkAttachmentFile,
71
+ dragCarriesFiles,
72
+ judgeDragTransfer,
73
+ partitionAttachmentFiles,
74
+ type RefusedAttachment,
75
+ } from '../utils/attachmentPolicy.js';
76
+ import {
77
+ FILE_DRAG_IDLE_MS,
78
+ dragLeftTheChat,
79
+ overlayForVerdict,
80
+ type FileDragOverlay,
81
+ } from '../utils/chatFileDrag.js';
82
+ import {
83
+ attachmentsNamedByText,
84
+ removeBadgesOfMissingPastedTexts,
85
+ resolvePasteInsertionRange,
86
+ writeReferenceToken,
87
+ type PasteSelection,
88
+ } from '../utils/pasteInsertion.js';
62
89
  import ChatMessageQueue from './ChatMessageQueue.svelte';
63
90
  import { mergeSuggestionIntoDraft } from '../utils/suggestionDraft.js';
64
91
  import { prepareChatImageFileForUpload } from '../utils/chatImageUploadPrep.js';
@@ -205,8 +232,11 @@
205
232
  /** Undo the last sketch-assistant canvas turn (one engine undo step). */
206
233
  onSketchUndo?: () => void | Promise<void>;
207
234
  /**
208
- * What the "Upgrade" button of a failure about the plan or the credits does. Without it the button opens the
209
- * billing page of the Widgetic site; a host that is a guest on somebody else's page gives its own function.
235
+ * What the "Upgrade" button of a failure about the plan or the credits does. The button is drawn right under the failure,
236
+ * in the chat: under a code generation the host saved a failure for ("Code generation failed: … Upgrade your plan …"), and
237
+ * under the sketch assistant's own sentences for a refusal because of money (`chat.sketch.noCredits`, `.planRequired`,
238
+ * `.limitReached`). Without this function the button opens the billing page of the Widgetic site; a host that is a guest on
239
+ * somebody else's page gives its own function.
210
240
  */
211
241
  onUpgradePlans?: () => void;
212
242
  /**
@@ -308,6 +338,16 @@
308
338
  * a run began.
309
339
  */
310
340
  generationChanges?: import('../utils/codeChanges.js').CodeChanges | null;
341
+ /**
342
+ * The agent's own words about what the last run changed (`operation.metadata.summary`: a sentence or two of plain text), or `null`
343
+ * when it said nothing: a gateway that does not send one, a build that was not kept. The conclusion under that run says it in
344
+ * place of "Done. Your changes are ready.".
345
+ *
346
+ * Like `generationChanges` it is what the run left behind, so it is NOT given up when `isGenerating` ends: give it when the
347
+ * operation completes (it may come after `isGenerating` fell) and clear it (`null`) when the next run starts. A page that forgets
348
+ * to clear it is safe: the chat ignores the very value it held when a run began.
349
+ */
350
+ generationSummary?: string | null;
311
351
  onStopGeneration?: () => void;
312
352
  /**
313
353
  * Renders the inline design-control card attached to an assistant reply
@@ -449,7 +489,7 @@
449
489
  updateLastUserMessageAttachments: (attachments: Array<{ id?: string; url: string; file_type?: string; file_name?: string | null }>) => void;
450
490
  }
451
491
 
452
- let { context, config = {}, class: className = '', locale = null, messages: languageMessages = null, dir = undefined, style = '', isCompleted = false, onStatsUpdate, onChatReady, onCompletionToggle, onSendMessage, onQuestionsAnswered, onLoadConversations, onLoadMessages, onCreateConversation, onSaveMessage, onRestoreCheckpointBackend, onRateVersion, versionRatings: ratingsFromHost = {}, onTakeScreenshot, onConversationChange, onDraftChange, onRetryMessage, onSketchUndo, onUpgradePlans, onUploadChatFile, showHeader = true, showPanelHeader = false, showConsoleControl = false, sendNudgeToken = 0, completion, isReferenceableAttachment = isReferenceablePicture, maxReferences, consoleOpen = false, onToggleConsole, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize, onMessagesDrag, onMessagesDragEnd, onLoadOlderMessages, widgetHeadCommitSha = null, versionLabelByCommitSha = {}, versionLabelByPrompt = {}, versionTimeline = [], isGenerating = false, generationStream = '', generationThinking = '', generationPlan = null, generationPlanPending = false, generationChanges = null, onStopGeneration, members = [], currentUser = null, renderAgentAvatar, agentSound, tightBubbles = true, referenceBadges = true, renderDesignControls, actionBarExtras, completeReplacement, replaceComplete = false, showSelector = false, isSelectorActive = false, selectedElements = [], onToggleSelector, onRemoveSelectedElement, onClearSelectedElements, activeSelectedElementId = null, onSelectedElementClick, mentionSources = [], mentionLimit = DEFAULT_MENTION_LIMIT, composerExtras, storedLineLabel, composerModels = [], selectedComposerModelId = null, onSelectComposerModel }: Props = $props();
492
+ let { context, config = {}, class: className = '', locale = null, messages: languageMessages = null, dir = undefined, style = '', isCompleted = false, onStatsUpdate, onChatReady, onCompletionToggle, onSendMessage, onQuestionsAnswered, onLoadConversations, onLoadMessages, onCreateConversation, onSaveMessage, onRestoreCheckpointBackend, onRateVersion, versionRatings: ratingsFromHost = {}, onTakeScreenshot, onConversationChange, onDraftChange, onRetryMessage, onSketchUndo, onUpgradePlans, onUploadChatFile, showHeader = true, showPanelHeader = false, showConsoleControl = false, sendNudgeToken = 0, completion, isReferenceableAttachment = isReferenceablePicture, maxReferences, consoleOpen = false, onToggleConsole, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize, onMessagesDrag, onMessagesDragEnd, onLoadOlderMessages, widgetHeadCommitSha = null, versionLabelByCommitSha = {}, versionLabelByPrompt = {}, versionTimeline = [], isGenerating = false, generationStream = '', generationThinking = '', generationPlan = null, generationPlanPending = false, generationChanges = null, generationSummary = null, onStopGeneration, members = [], currentUser = null, renderAgentAvatar, agentSound, tightBubbles = true, referenceBadges = true, renderDesignControls, actionBarExtras, completeReplacement, replaceComplete = false, showSelector = false, isSelectorActive = false, selectedElements = [], onToggleSelector, onRemoveSelectedElement, onClearSelectedElements, activeSelectedElementId = null, onSelectedElementClick, mentionSources = [], mentionLimit = DEFAULT_MENTION_LIMIT, composerExtras, storedLineLabel, composerModels = [], selectedComposerModelId = null, onSelectComposerModel }: Props = $props();
453
493
 
454
494
  // The words of everything inside the chat, in the language the page chose. The page can change the language while the
455
495
  // chat is open: the settings are read again whenever they change (and setting the same language again does nothing).
@@ -602,7 +642,8 @@
602
642
  try {
603
643
  const takenLabels = labelsOfAttachments(localAttachments);
604
644
  entries.forEach((entry, entryIndex) => {
605
- if (!isReferenceableAttachment(entry)) return;
645
+ // A text pasted into the box is named in the message by its badge, so it is called by a label too
646
+ if (!isReferenceableAttachment(entry) && !isPastedTextAttachment(entry)) return;
606
647
  const label =
607
648
  forcedLabels?.[entryIndex] ??
608
649
  assignReferenceLabel(entry.file?.name ?? '', { takenLabels, genericNumberFloor: referenceGenericFloor });
@@ -629,8 +670,22 @@
629
670
  attachmentInputs: AttachmentInput[] | undefined,
630
671
  sendOptions?: ComposerSendOptions,
631
672
  ): void {
632
- const references = sendOptions?.references ?? [];
633
- void sendMessage(content, attachmentInputs, references.length > 0 ? { references } : undefined);
673
+ // A text that was pasted goes only with words that name it: its badge may have been deleted (or cut, to be put elsewhere), and
674
+ // a file that nothing on the screen shows must not be sent with a message that does not name it.
675
+ const namedAttachments = attachmentInputs ? attachmentsNamedByText(attachmentInputs, content) : undefined;
676
+ const sentAttachments = namedAttachments && namedAttachments.length > 0 ? namedAttachments : undefined;
677
+ // The references of a send name pictures (the host tells the builder which picture a `#word` means). A pasted text is named by its
678
+ // badge and travels as a text file that the host reads by its name, so it is not among them.
679
+ const pastedTextLabels = new Set(
680
+ (attachmentInputs ?? [])
681
+ .filter(isPastedTextAttachment)
682
+ .map((attachment) => attachment.referenceLabel?.toLowerCase())
683
+ .filter((label): label is string => !!label),
684
+ );
685
+ const references = (sendOptions?.references ?? []).filter(
686
+ (reference) => !pastedTextLabels.has(reference.label.toLowerCase()),
687
+ );
688
+ void sendMessage(content, sentAttachments, references.length > 0 ? { references } : undefined);
634
689
  }
635
690
 
636
691
  /** The highest `Image_N` number a text names, as a badge or as a `#Image_N` typed by hand (0 when it names none). */
@@ -686,7 +741,11 @@
686
741
  // First the pictures that came back: none answers to a word the restored text already names ...
687
742
  renameRestoredPicturesNamedByText(localInputText);
688
743
  // ... so a badge in that text has no file by now, unless the person made it since: it is plain `#label` again
689
- const checkedText = unbadgeTokensWithoutFiles(localInputText, labelsOfAttachments(localAttachments));
744
+ // A text that was pasted does not come back with a draft (only pictures are kept in one): its badge is taken out, not left as a
745
+ // plain `#pasted_text` that stands for nothing. Then every other badge whose file is gone is plain `#label` again.
746
+ const attachedLabels = labelsOfAttachments(localAttachments);
747
+ const withoutPastedTextBadges = removeBadgesOfMissingPastedTexts(localInputText, attachedLabels);
748
+ const checkedText = unbadgeTokensWithoutFiles(withoutPastedTextBadges.text, attachedLabels);
690
749
  if (checkedText !== localInputText) {
691
750
  chatLog('[Chat] A restored draft had badges for files that are not attached: they are plain text again');
692
751
  localInputText = checkedText;
@@ -729,6 +788,11 @@
729
788
  }
730
789
  }
731
790
  }
791
+ if (flashedAttachmentTimer) clearTimeout(flashedAttachmentTimer);
792
+ // A drag that was still over the chat is over with it
793
+ stopWaitingForFileDrag();
794
+ // The addresses made for an open preview go with the chat
795
+ releaseComposerPreviewAddresses();
732
796
  // The waiting messages go with the chat: their pictures are given back and nothing is sent once the chat is gone
733
797
  clearQueueSendNowTimer();
734
798
  releasePreviewAddresses(blobPreviewsOf(queuedMessages.flatMap((message) => message.attachments)));
@@ -1445,12 +1509,12 @@
1445
1509
  // The label the message can call the screenshot by (`#Image_1`), given in the same breath as it joins the tray
1446
1510
  labelNewAttachments([attachmentInput]);
1447
1511
 
1512
+ const previousTileCount = countTrayTiles();
1448
1513
  localAttachments = [...localAttachments, attachmentInput];
1449
- const attachmentIndex = localAttachments.length - 1;
1450
1514
  notifyDraftChange();
1451
- expandChatForAttachmentGrowth(attachmentIndex);
1515
+ expandChatForAttachmentGrowth(previousTileCount);
1452
1516
  chatStore.actions.updateUI({ errorMessage: null });
1453
- console.log('[Chat] attachments now', localAttachments.length);
1517
+ // console.log('[Chat] attachments now', localAttachments.length);
1454
1518
 
1455
1519
  if (onUploadChatFile) {
1456
1520
  await uploadAttachmentToCdn(screenshotFile, attachmentInput, {
@@ -1503,7 +1567,7 @@
1503
1567
 
1504
1568
  // Add to attachments
1505
1569
  localAttachments = [...localAttachments, attachmentInput];
1506
- console.log('[Chat] attachments now', localAttachments.length);
1570
+ // console.log('[Chat] attachments now', localAttachments.length);
1507
1571
 
1508
1572
  // chatLog('Recording stopped and added to attachments');
1509
1573
 
@@ -1592,7 +1656,9 @@
1592
1656
  }
1593
1657
 
1594
1658
  function expandChatForAttachmentGrowth(previousCount: number) {
1595
- if (localAttachments.length <= previousCount) return;
1659
+ // Counted in tiles: a text that was pasted is a badge in the words and takes no room of its own
1660
+ const tileCount = countTrayTiles();
1661
+ if (tileCount <= previousCount) return;
1596
1662
 
1597
1663
  // When the first attachment appears, free space in a fixed messages area so the footer tray stays visible.
1598
1664
  if (previousCount === 0 && messagesAreaHeight !== null) {
@@ -1602,7 +1668,7 @@
1602
1668
  if (!resizeExpandsContainer) return;
1603
1669
  // Grow the fixed-height host once per net attachment increase so the tray is not clipped.
1604
1670
  onMessagesResize?.(120);
1605
- chatLog('[Chat] Expanded chat host for attachments:', previousCount, '→', localAttachments.length);
1671
+ chatLog('[Chat] Expanded chat host for attachments:', previousCount, '→', tileCount);
1606
1672
  }
1607
1673
 
1608
1674
  function isImageAttachment(attachment: AttachmentInput): boolean {
@@ -1646,7 +1712,48 @@
1646
1712
  chatLog('[Chat] Removed footer attachment at index:', index);
1647
1713
  }
1648
1714
 
1649
- let footerLightboxSrc: string | null = $state(null);
1715
+ // ===== The preview of a file of the message box (a card with the look of the File Browser's preview) =====
1716
+ /** The files the open preview steps through and the place of the open one, or null while no preview is open. */
1717
+ let composerPreview = $state<{ files: PreviewableFile[]; openIndex: number } | null>(null);
1718
+ /** The addresses made only for the open preview (a text file has none until it is uploaded): given back when the preview closes. */
1719
+ let composerPreviewMadeUrls: string[] = [];
1720
+
1721
+ /** Gives back the addresses that were made for a preview, so the browser does not keep the files in memory for nothing. */
1722
+ function releaseComposerPreviewAddresses(): void {
1723
+ releasePreviewAddresses(composerPreviewMadeUrls);
1724
+ composerPreviewMadeUrls = [];
1725
+ }
1726
+
1727
+ /** A thumbnail or a file chip of the message box was pressed: its file opens in the preview, with the files next to it. */
1728
+ function openComposerPreview(pressed: AttachmentInput): void {
1729
+ try {
1730
+ const preview = composerPreviewOf(localAttachments, pressed, {
1731
+ isPicture: isImageAttachment,
1732
+ readUrl: getFooterAttachmentPreviewUrl,
1733
+ makeObjectUrl: (file) => {
1734
+ try {
1735
+ return URL.createObjectURL(file);
1736
+ } catch (error) {
1737
+ console.warn('[Chat] Could not make an address to preview the attached file:', error);
1738
+ return null;
1739
+ }
1740
+ },
1741
+ });
1742
+ if (!preview) return;
1743
+ // The addresses of an earlier preview are not needed any more
1744
+ releaseComposerPreviewAddresses();
1745
+ composerPreviewMadeUrls = preview.madeUrls;
1746
+ composerPreview = { files: preview.files, openIndex: preview.openIndex };
1747
+ chatLog('[Chat] A file of the message box was opened in the preview:', pressed.file?.name);
1748
+ } catch (error) {
1749
+ console.warn('[Chat] Could not open the attached file in the preview:', error);
1750
+ }
1751
+ }
1752
+
1753
+ function closeComposerPreview(): void {
1754
+ composerPreview = null;
1755
+ releaseComposerPreviewAddresses();
1756
+ }
1650
1757
 
1651
1758
  /** Biggest image kept in the draft: a draft is written to the browser's storage on every change. */
1652
1759
  const MAX_PERSISTED_IMAGE_BYTES = 6 * 1024 * 1024;
@@ -1684,25 +1791,137 @@
1684
1791
  }
1685
1792
 
1686
1793
  /**
1687
- * Attaches files to the message being written: the ones dropped on the box, picked with "+", or pasted into it. A file may
1688
- * come with the words its tile says in place of its name (the first words of a pasted text). The tiles are put in the tray
1689
- * first and the files are uploaded after, one by one; `onTilesAdded` is called between the two, so a caller that keeps a
1690
- * line of pastes (see `addPastedAttachments`) can let the next paste in while these files are still uploading.
1794
+ * How many tiles the tray draws now: every file but a text that was pasted into the box (it is a badge in the words, with no tile).
1795
+ * The chat makes room for the tray when this goes from nothing to something.
1796
+ */
1797
+ function countTrayTiles(): number {
1798
+ return localAttachments.filter((attachment) => !isPastedTextAttachment(attachment)).length;
1799
+ }
1800
+
1801
+ /** How long the tile of a file that was attached already stays ringed when the person tries to attach it again. */
1802
+ const KNOWN_FILE_FLASH_MS = 1400;
1803
+ /** The files the person tried to attach again (they are in the tray already): their tiles are ringed for a moment. */
1804
+ let flashedAttachmentIds = $state<string[]>([]);
1805
+ let flashedAttachmentTimer: ReturnType<typeof setTimeout> | null = null;
1806
+
1807
+ /**
1808
+ * The message box, to put the caret after a badge that was written into the text (a text was pasted): a text set from outside
1809
+ * leaves the caret at its end.
1810
+ */
1811
+ let composerHandle = $state<{ placeCaret: (position: number) => Promise<void> } | null>(null);
1812
+
1813
+ /**
1814
+ * The fingerprints (see `fingerprintFile`) of files that arrived and are not in the tray yet: a big picture is made smaller first,
1815
+ * and the same picture dropped twice in that time must still be attached once.
1816
+ */
1817
+ const fingerprintsBeingPrepared = new Set<string>();
1818
+
1819
+ /** What a file that arrives carries, besides the file: the words of its tile, and for a pasted text its beginning. */
1820
+ type ArrivingFile = { file: File; label?: string; excerpt?: string };
1821
+
1822
+ /**
1823
+ * Sorts what arrives into the files that are new and the ones the message holds already: the same bytes are in the tray (or in
1824
+ * the batch itself, or in a batch that is being made ready). Their fingerprints are made first, and the sorting is one step with
1825
+ * no wait in it, so two arrivals that follow each other never both find the tray empty. The new ones are held (in
1826
+ * `fingerprintsBeingPrepared`) until their tiles are in the tray; `known` says which tile has the file, when there is one.
1827
+ */
1828
+ async function sortOutKnownFiles<Entry extends ArrivingFile>(
1829
+ entries: Entry[],
1830
+ ): Promise<{
1831
+ fresh: Array<Entry & { fingerprint: string }>;
1832
+ known: Array<{ entry: Entry; existing: AttachmentInput | null }>;
1833
+ }> {
1834
+ const fingerprinted = await Promise.all(
1835
+ entries.map(async (entry) => ({ entry, fingerprint: await fingerprintFile(entry.file) })),
1836
+ );
1837
+ const { fresh, known } = splitNewFromKnown(fingerprinted, localAttachments, fingerprintsBeingPrepared);
1838
+ for (const { fingerprint } of fresh) fingerprintsBeingPrepared.add(fingerprint);
1839
+ return {
1840
+ fresh: fresh.map(({ entry, fingerprint }) => ({ ...entry, fingerprint })),
1841
+ known: known.map(({ entry, existingIndex }) => ({
1842
+ entry,
1843
+ existing: existingIndex >= 0 ? (localAttachments[existingIndex] ?? null) : null,
1844
+ })),
1845
+ };
1846
+ }
1847
+
1848
+ /** Lets go of the files that were held while they were made ready: their tiles are in the tray now (or they could not be attached). */
1849
+ function releaseFingerprints(fingerprints: readonly string[]): void {
1850
+ for (const fingerprint of fingerprints) fingerprintsBeingPrepared.delete(fingerprint);
1851
+ }
1852
+
1853
+ /**
1854
+ * The files that came again: none is attached a second time, and the tile of the one the tray holds is ringed for a moment, so
1855
+ * the person sees it is there. (A text that was pasted again is named in the message once more: see `addPastedAttachments`.)
1856
+ */
1857
+ function flashKnownFiles(known: ReadonlyArray<{ existing: AttachmentInput | null }>): void {
1858
+ if (known.length === 0) return;
1859
+ chatLog('[Chat] Files that are attached already were not attached again:', known.length);
1860
+ const tileIds = known
1861
+ .map(({ existing }) => existing)
1862
+ .filter((existing): existing is AttachmentInput => !!existing?.id && !isPastedTextAttachment(existing))
1863
+ .map((existing) => existing.id as string);
1864
+ if (tileIds.length === 0) return;
1865
+ flashedAttachmentIds = tileIds;
1866
+ if (flashedAttachmentTimer) clearTimeout(flashedAttachmentTimer);
1867
+ flashedAttachmentTimer = setTimeout(() => {
1868
+ flashedAttachmentIds = [];
1869
+ flashedAttachmentTimer = null;
1870
+ }, KNOWN_FILE_FLASH_MS);
1871
+ }
1872
+
1873
+ /**
1874
+ * Tells the person which files were left out and why, in a toast: one line for the files of a kind of refusal, so a drop of many
1875
+ * says it once. A file that is not a kind the box takes, one that is too large, or a folder.
1876
+ */
1877
+ function reportRefusedFiles(refused: readonly RefusedAttachment[]): void {
1878
+ if (refused.length === 0) return;
1879
+ chatWarn('[Chat] Files were left out:', refused.map(({ file, reason }) => `${file.name} (${reason})`).join(', '));
1880
+ try {
1881
+ const folders = refused.filter(({ reason }) => reason === 'folder');
1882
+ const wrongKind = refused.filter(({ reason }) => reason === 'type');
1883
+ const tooLarge = refused.filter(({ reason }) => reason === 'size');
1884
+ if (folders.length > 0) showToast('error', $t('chat.attachment.refusedFolder'));
1885
+ if (wrongKind.length === 1) {
1886
+ showToast('error', $t('chat.attachment.refusedTypeOne', { name: wrongKind[0].file.name }));
1887
+ } else if (wrongKind.length > 1) {
1888
+ showToast('error', $t('chat.attachment.refusedTypeMany', { count: wrongKind.length }));
1889
+ }
1890
+ if (tooLarge.length === 1) {
1891
+ const limit = fileSizeText(tooLarge[0].limitBytes, $t, $spokenLocale);
1892
+ showToast('error', $t('chat.attachment.refusedSizeOne', { name: tooLarge[0].file.name, limit }));
1893
+ } else if (tooLarge.length > 1) {
1894
+ showToast('error', $t('chat.attachment.refusedSizeMany', { count: tooLarge.length }));
1895
+ }
1896
+ } catch (error) {
1897
+ console.warn('[Chat] Could not tell which files were left out:', error);
1898
+ }
1899
+ }
1900
+
1901
+ /**
1902
+ * Attaches files to the message being written: the ones dropped on the chat, picked with "+", or pasted into the box. A file may
1903
+ * come with the words its tile says in place of its name (the first words of a pasted text), and a pasted text with its
1904
+ * beginning (`excerpt`, which is also what makes it a pasted text). The tiles are put in the tray first and the files are
1905
+ * uploaded after, one by one; `onTilesAdded` is called between the two, with the tiles that were added, so a caller that keeps a
1906
+ * line of pastes (see `addPastedAttachments`) can let the next paste in while these files are still uploading, and one that has
1907
+ * to write into the text (a badge for a pasted text) does it in the same step as the tiles come.
1691
1908
  */
1692
1909
  async function attachFiles(
1693
- entries: Array<{ file: File; label?: string }>,
1694
- options: { onTilesAdded?: () => void } = {},
1910
+ entries: Array<ArrivingFile & { fingerprint?: string }>,
1911
+ options: { onTilesAdded?: (addedAttachments: AttachmentInput[]) => void } = {},
1695
1912
  ) {
1696
1913
  const usableEntries = (entries || []).filter(({ file }) => file && file.size > 0);
1697
1914
  if (usableEntries.length === 0) return;
1698
1915
 
1699
- const previousCount = localAttachments.length;
1700
- const newAttachments: AttachmentInput[] = usableEntries.map(({ file, label }) => ({
1916
+ const previousTileCount = countTrayTiles();
1917
+ const newAttachments: AttachmentInput[] = usableEntries.map(({ file, label, excerpt, fingerprint }) => ({
1701
1918
  // Tells the tiles apart while the tray shows them (two pasted screenshots are both "image.png"), and is how the upload
1702
1919
  // finds its tile again while other uploads run: see `updateAttachment`.
1703
1920
  id: generateFileId(),
1704
1921
  file,
1705
1922
  label,
1923
+ excerpt,
1924
+ fingerprint,
1706
1925
  type: file.type.startsWith('image/')
1707
1926
  ? 'image'
1708
1927
  : file.type.startsWith('video/')
@@ -1716,13 +1935,13 @@
1716
1935
  labelNewAttachments(newAttachments);
1717
1936
  localAttachments = [...localAttachments, ...newAttachments];
1718
1937
  notifyDraftChange();
1719
- expandChatForAttachmentGrowth(previousCount);
1938
+ expandChatForAttachmentGrowth(previousTileCount);
1720
1939
  chatStore.actions.updateUI({ errorMessage: null });
1721
- console.log('[Chat] attachments now', localAttachments.length);
1940
+ // console.log('[Chat] attachments now', localAttachments.length);
1722
1941
  // The draft keeps each picture as it is attached, before the upload ends (a refresh can come at any time).
1723
1942
  for (const entry of newAttachments) void rememberImageForDraft(entry);
1724
1943
  // Everything the next paste has to see is in the tray now; the uploads below are not waited for.
1725
- options.onTilesAdded?.();
1944
+ options.onTilesAdded?.(newAttachments);
1726
1945
 
1727
1946
  try {
1728
1947
  localIsUploading = true;
@@ -1737,18 +1956,126 @@
1737
1956
  }
1738
1957
 
1739
1958
  /**
1740
- * The files dropped on the box or picked with "+". A picture is made smaller first when it is large (see
1741
- * `prepareChatImageFileForUpload`); a paste gets the same preparation, in the line of the pastes (see `addPastedAttachments`).
1959
+ * The files dropped on the chat or picked with "+". Files of a kind the box does not take, and ones that are too large, are left
1960
+ * out with a word about why; a file that is attached already (the same bytes, whatever it is called) is not attached again, and
1961
+ * its tile is ringed instead. A picture is made smaller first when it is large (see `prepareChatImageFileForUpload`; a paste gets
1962
+ * the same preparation, in the line of the pastes: see `addPastedAttachments`), and the size that counts is the one that is sent.
1742
1963
  */
1743
1964
  async function addFilesAsAttachments(files: File[]) {
1744
- const incoming = (files || []).filter((file) => file && file.size > 0);
1965
+ const incoming = Array.from(files || []).filter((file) => !!file);
1745
1966
  if (incoming.length === 0) return;
1746
- const usableFiles = await Promise.all(
1747
- incoming.map(async (file) =>
1748
- file.type.startsWith('image/') ? await prepareChatImageFileForUpload(file) : file,
1749
- ),
1750
- );
1751
- await attachFiles(usableFiles.map((file) => ({ file })));
1967
+ // A picture may be too large as it comes and fine once it is made smaller, so its size is checked after that
1968
+ const { accepted, refused } = partitionAttachmentFiles(incoming, { skipPictureSize: true });
1969
+ reportRefusedFiles(refused);
1970
+ const usableFiles = accepted.filter((file) => file.size > 0);
1971
+ if (usableFiles.length === 0) return;
1972
+
1973
+ const { fresh, known } = await sortOutKnownFiles(usableFiles.map((file) => ({ file })));
1974
+ flashKnownFiles(known);
1975
+ if (fresh.length === 0) return;
1976
+ const heldFingerprints = fresh.map(({ fingerprint }) => fingerprint);
1977
+ try {
1978
+ const preparedEntries = await Promise.all(
1979
+ fresh.map(async (entry) => ({
1980
+ ...entry,
1981
+ file: entry.file.type.startsWith('image/') ? await prepareChatImageFileForUpload(entry.file) : entry.file,
1982
+ })),
1983
+ );
1984
+ const stillTooLarge: RefusedAttachment[] = [];
1985
+ const attachableEntries = preparedEntries.filter((entry) => {
1986
+ const check = checkAttachmentFile(entry.file);
1987
+ if (check.ok) return true;
1988
+ if (check.reason === 'size') stillTooLarge.push({ file: entry.file, reason: 'size', limitBytes: check.limitBytes });
1989
+ return false;
1990
+ });
1991
+ reportRefusedFiles(stillTooLarge);
1992
+ await attachFiles(attachableEntries, { onTilesAdded: () => releaseFingerprints(heldFingerprints) });
1993
+ } catch (error) {
1994
+ console.error('[Chat] Could not attach the files:', error);
1995
+ } finally {
1996
+ // Held only until the tiles are in the tray: let go even when the files could not be attached (letting go twice changes nothing)
1997
+ releaseFingerprints(heldFingerprints);
1998
+ }
1999
+ }
2000
+
2001
+ // --- Files dragged over the chat -------------------------------------------------------------------------------------------
2002
+ // The whole chat takes a drop, not only the message box: while files are over it a veil covers it and says what releasing them
2003
+ // would do (`ChatDropOverlay`). The drag events of every part of the chat come up to its root, so one set of handlers there is
2004
+ // enough, and the message box has none of its own.
2005
+
2006
+ /** What covers the chat now: nothing, the invitation to release the files, or the word that they are not taken. */
2007
+ let fileDragOverlay = $state<FileDragOverlay>('hidden');
2008
+ let fileDragIdleTimer: ReturnType<typeof setTimeout> | null = null;
2009
+
2010
+ /** Whether the chat takes files at all: the host that switched uploads off gets no veil and no drop. */
2011
+ const chatTakesFiles = $derived(config?.features?.fileUpload !== false);
2012
+
2013
+ function stopWaitingForFileDrag(): void {
2014
+ if (fileDragIdleTimer) clearTimeout(fileDragIdleTimer);
2015
+ fileDragIdleTimer = null;
2016
+ }
2017
+
2018
+ /** The drag is over (the files left, were dropped, or the browser stopped saying): the veil goes away. */
2019
+ function endFileDrag(): void {
2020
+ stopWaitingForFileDrag();
2021
+ fileDragOverlay = 'hidden';
2022
+ }
2023
+
2024
+ /** Files over the chat (`dragenter`, then `dragover` for as long as they stay): the chat says what releasing them would do. */
2025
+ function handleChatFileDrag(event: DragEvent): void {
2026
+ if (!chatTakesFiles) return;
2027
+ const verdict = judgeDragTransfer(event.dataTransfer);
2028
+ // A text or a link dragged over the chat is not for it: the browser deals with it as it always did
2029
+ if (verdict === 'none') return;
2030
+ // Allows the drop, wherever on the chat the files are. A refused kind is allowed too, so the drop can say which file was left out.
2031
+ event.preventDefault();
2032
+ if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';
2033
+ const nextOverlay = overlayForVerdict(verdict);
2034
+ if (nextOverlay !== fileDragOverlay) {
2035
+ fileDragOverlay = nextOverlay;
2036
+ chatLog('[Chat] Files are over the chat:', nextOverlay);
2037
+ }
2038
+ // The browser says nothing when a drag is cancelled (Escape): the chat takes the drag for over when it stops hearing from it
2039
+ stopWaitingForFileDrag();
2040
+ fileDragIdleTimer = setTimeout(endFileDrag, FILE_DRAG_IDLE_MS);
2041
+ }
2042
+
2043
+ /** Files left a part of the chat: the veil goes away only when they left the chat (not when they crossed to another part of it). */
2044
+ function handleChatFileDragLeave(event: DragEvent): void {
2045
+ if (fileDragOverlay === 'hidden' || !chatContainer) return;
2046
+ try {
2047
+ const chatBox = chatContainer.getBoundingClientRect();
2048
+ const leftTheChat = dragLeftTheChat(
2049
+ { relatedTarget: event.relatedTarget, clientX: event.clientX, clientY: event.clientY },
2050
+ {
2051
+ contains: (node) => node instanceof Node && chatContainer.contains(node),
2052
+ left: chatBox.left,
2053
+ top: chatBox.top,
2054
+ right: chatBox.right,
2055
+ bottom: chatBox.bottom,
2056
+ },
2057
+ );
2058
+ if (leftTheChat) endFileDrag();
2059
+ } catch (error) {
2060
+ console.warn('[Chat] Could not tell whether the files left the chat:', error);
2061
+ endFileDrag();
2062
+ }
2063
+ }
2064
+
2065
+ /** Files released over the chat, wherever on it: they are attached the way the ones picked with "+" are. */
2066
+ function handleChatFileDrop(event: DragEvent): void {
2067
+ if (!chatTakesFiles || !dragCarriesFiles(event.dataTransfer)) return;
2068
+ event.preventDefault();
2069
+ // The drop is the chat's: a host that also listens for dropped files above the chat does not get it too
2070
+ event.stopPropagation();
2071
+ endFileDrag();
2072
+ try {
2073
+ const droppedFiles = Array.from(event.dataTransfer?.files ?? []);
2074
+ chatLog('[Chat] Files were dropped on the chat:', droppedFiles.length);
2075
+ if (droppedFiles.length > 0) void addFilesAsAttachments(droppedFiles);
2076
+ } catch (error) {
2077
+ console.error('[Chat] Could not take the files that were dropped:', error);
2078
+ }
1752
2079
  }
1753
2080
 
1754
2081
  /**
@@ -1760,31 +2087,118 @@
1760
2087
  */
1761
2088
  const pasteTileLine = createOrderedLine();
1762
2089
 
2090
+ /**
2091
+ * Writes the badge of each pasted text into the words of the message, at the place the caret was when it was pasted, and puts
2092
+ * the caret after the badge. The tiles and the words change in the same step (no wait between them), so nothing sees a text
2093
+ * that is attached and not yet named. A person pasting after the second paragraph has the badge after the second paragraph.
2094
+ */
2095
+ function writePastedTextBadges(
2096
+ pastedTexts: readonly AttachmentInput[],
2097
+ textWhenPasted: string,
2098
+ selection: PasteSelection | undefined,
2099
+ ): void {
2100
+ const namedTexts = pastedTexts.filter((attachment) => !!attachment.referenceLabel);
2101
+ if (namedTexts.length === 0) return;
2102
+ try {
2103
+ // Where the caret was, in the text as it is now (the person may have typed since the paste arrived)
2104
+ let insertionRange = resolvePasteInsertionRange(textWhenPasted, localInputText, selection);
2105
+ let nextText = localInputText;
2106
+ let caretAfterBadges = insertionRange.start;
2107
+ for (const pastedText of namedTexts) {
2108
+ const written = writeReferenceToken(nextText, insertionRange, pastedText.referenceLabel as string);
2109
+ nextText = written.text;
2110
+ caretAfterBadges = written.caret;
2111
+ insertionRange = { start: written.caret, end: written.caret };
2112
+ }
2113
+ localInputText = nextText;
2114
+ // The words were changed by the person's own paste: a suggestion they picked no longer stands for what is written
2115
+ pendingChipIntent = null;
2116
+ pendingSkipIntentGate = false;
2117
+ notifyDraftChange();
2118
+ void composerHandle?.placeCaret(caretAfterBadges);
2119
+ chatLog('[Chat] A pasted text is named in the message at', caretAfterBadges, 'as', namedTexts.map((text) => `#${text.referenceLabel}`).join(' '));
2120
+ } catch (error) {
2121
+ console.warn('[Chat] Could not name the pasted text in the message:', error);
2122
+ }
2123
+ }
2124
+
1763
2125
  /**
1764
2126
  * What a paste into the box brought in (see `attachmentsFromPaste`): a screenshot or a file, or a long text as a text file.
1765
2127
  * It is attached the way a dropped file is, so it is uploaded and sent like one, and a large picture is made smaller first
1766
- * (see `prepareImagesOfPaste`). The tile of a pasted text says its first words, not "pasted-text.txt". Every paste is an
1767
- * attachment of its own, with a name of its own among the files already in the tray: two screenshots are both "image.png"
1768
- * and two texts both "pasted-text.txt", and the builder names the text files it reads (and the person is told which it
1769
- * could not read) by those names. The pastes get their tiles in the order they were made in (see `pasteTileLine`).
2128
+ * (see `prepareImagesOfPaste`). A text has no tile: the message names it with a badge, written where the caret was (`selection`),
2129
+ * and the card over the badge shows what the text says. A file that is attached already is not attached again (a text pasted a
2130
+ * second time is named again, once more, where the caret is now). Every paste is an attachment of its own, with a name of its own
2131
+ * among the files already in the tray: two screenshots are both "image.png" and two texts both "pasted-text.txt", and the builder
2132
+ * names the text files it reads (and the person is told which it could not read) by those names. The pastes get their tiles in
2133
+ * the order they were made in (see `pasteTileLine`).
1770
2134
  */
1771
- async function addPastedAttachments(pastedAttachments: PastedAttachment[]) {
1772
- // The place in the line is taken now, before anything is waited for: it follows the order the pastes arrived in.
2135
+ async function addPastedAttachments(pastedAttachments: PastedAttachment[], selection?: PasteSelection) {
2136
+ // The place in the line is taken now, before anything is waited for: it follows the order the pastes arrived in. So is the text
2137
+ // the caret was in: the badge of a pasted text is written into it where the caret was.
2138
+ const textWhenPasted = localInputText;
1773
2139
  const placeInLine = pasteTileLine.takePlace();
2140
+ let heldFingerprints: string[] = [];
1774
2141
  try {
1775
2142
  chatLog('[Chat] Attaching pasted content:', pastedAttachments.length);
2143
+ // A file of a kind the box does not take is left out with a word about why (a pasted text and a picture always pass)
2144
+ const { accepted, refused } = partitionAttachmentFiles(
2145
+ pastedAttachments.filter((pasted) => pasted.excerpt === undefined).map((pasted) => pasted.file),
2146
+ { skipPictureSize: true },
2147
+ );
2148
+ reportRefusedFiles(refused);
2149
+ const acceptedFiles = new Set(accepted);
2150
+ const takenPastes = pastedAttachments.filter(
2151
+ (pasted) => pasted.excerpt !== undefined || acceptedFiles.has(pasted.file),
2152
+ );
2153
+
2154
+ const { fresh, known } = await sortOutKnownFiles(takenPastes);
2155
+ flashKnownFiles(known);
2156
+ heldFingerprints = fresh.map(({ fingerprint }) => fingerprint);
2157
+ // A text that was pasted before and is still in the tray is named again, where the caret is now
2158
+ const knownPastedTexts = known
2159
+ .map(({ existing }) => existing)
2160
+ .filter((existing): existing is AttachmentInput => !!existing && isPastedTextAttachment(existing));
2161
+
1776
2162
  // Preparing is done by all the pastes at once; only the tiles wait for their place.
1777
- const preparedAttachments = await prepareImagesOfPaste(pastedAttachments, prepareChatImageFileForUpload);
2163
+ const preparedAttachments = await prepareImagesOfPaste(fresh, prepareChatImageFileForUpload);
1778
2164
  await placeInLine.untilReached;
1779
2165
  // The tray is read in the same step that the tiles are added, with no wait between: the paste after this one sees them.
1780
2166
  const namesInTray = localAttachments.map((attachment) => attachment.file?.name ?? '').filter(Boolean);
2167
+ const namedPastes = withUniqueFileNames(preparedAttachments, namesInTray).map((pasted, pasteIndex) => ({
2168
+ ...pasted,
2169
+ // The fingerprint is that of the file as it came: `prepareImagesOfPaste` and `withUniqueFileNames` keep the order and the length
2170
+ fingerprint: fresh[pasteIndex]?.fingerprint,
2171
+ }));
2172
+ const attachableEntries = namedPastes.filter((pasted) => {
2173
+ if (pasted.excerpt !== undefined) return true;
2174
+ const check = checkAttachmentFile(pasted.file);
2175
+ if (!check.ok && check.reason === 'size') {
2176
+ reportRefusedFiles([{ file: pasted.file, reason: 'size', limitBytes: check.limitBytes }]);
2177
+ }
2178
+ return check.ok;
2179
+ });
2180
+ if (attachableEntries.length === 0 && knownPastedTexts.length > 0) {
2181
+ // Nothing new: the text that is attached already is named again, in this same step
2182
+ writePastedTextBadges(knownPastedTexts, textWhenPasted, selection);
2183
+ }
1781
2184
  // The place is left as soon as the tiles are in the tray, not when the uploads end: they run side by side.
1782
- await attachFiles(withUniqueFileNames(preparedAttachments, namesInTray), { onTilesAdded: placeInLine.leave });
2185
+ await attachFiles(attachableEntries, {
2186
+ onTilesAdded: (addedAttachments) => {
2187
+ placeInLine.leave();
2188
+ releaseFingerprints(heldFingerprints);
2189
+ writePastedTextBadges(
2190
+ [...addedAttachments.filter(isPastedTextAttachment), ...knownPastedTexts],
2191
+ textWhenPasted,
2192
+ selection,
2193
+ );
2194
+ },
2195
+ });
1783
2196
  } catch (error) {
1784
2197
  console.error('[Chat] Could not attach the pasted content:', error);
1785
2198
  } finally {
1786
2199
  // The next paste's tiles may come now, even when this one could not be attached (leaving a second time changes nothing).
1787
2200
  placeInLine.leave();
2201
+ releaseFingerprints(heldFingerprints);
1788
2202
  }
1789
2203
  }
1790
2204
 
@@ -1794,7 +2208,8 @@
1794
2208
  const fileInput = document.createElement('input');
1795
2209
  fileInput.type = 'file';
1796
2210
  fileInput.multiple = true;
1797
- fileInput.accept = '*/*';
2211
+ // The kinds the box takes: a person is not invited to pick what would be refused (a drop or a paste of another kind says so)
2212
+ fileInput.accept = ATTACHMENT_ACCEPT_ATTRIBUTE;
1798
2213
 
1799
2214
  fileInput.onchange = async (event) => {
1800
2215
  const files = Array.from((event.target as HTMLInputElement).files || []);
@@ -1852,8 +2267,13 @@
1852
2267
  /** The links of the text that one of the page's lists is made for, to offer as a one-tap pick beside the chips. */
1853
2268
  const mentionLinkHints = $derived(findMentionLinkHints(localInputText, mentionSources, localMentions, mentionLimit));
1854
2269
 
1855
- /** Whether the message box has anything to show above the text: a part picked on the preview, a pick, or an offer. With none it looks as it always did. */
1856
- const composerHasChips = $derived((selectedElements?.length ?? 0) > 0 || localMentions.length > 0 || mentionLinkHints.length > 0);
2270
+ /** Whether the attached files have anything to draw over the text: some file that is not a text pasted into the box (it is a badge in the words). */
2271
+ const composerHasTiles = $derived(trayHasTiles(localAttachments));
2272
+
2273
+ /** Whether the message box has anything to show above the text: a part picked on the preview, a pick, an offer, or an attached file. With none it looks as it always did. */
2274
+ const composerHasChips = $derived(
2275
+ (selectedElements?.length ?? 0) > 0 || localMentions.length > 0 || mentionLinkHints.length > 0 || composerHasTiles,
2276
+ );
1857
2277
 
1858
2278
  function addMentionPick(mention: ComposerMention) {
1859
2279
  localMentions = addMention(localMentions, mention, mentionLimit);
@@ -2051,7 +2471,7 @@
2051
2471
  file_name: attachment.file_name || attachment.fileName || 'design-screenshot.png',
2052
2472
  file_size: attachment.file_size ?? attachment.fileSize,
2053
2473
  }));
2054
- console.log('[Chat] Restore echo attachments', restoredAttachments.length);
2474
+ // console.log('[Chat] Restore echo attachments', restoredAttachments.length);
2055
2475
  addUserMessage(promptCopy, restoredAttachments.length ? restoredAttachments : undefined);
2056
2476
  addAssistantMessage(`Restored from ${sourceLabel}\n\nCommit: ${newSha.slice(0, 8)}`);
2057
2477
  }
@@ -2104,6 +2524,7 @@
2104
2524
  const mimeMatch = dataUrl.match(/data:(image\/[^;]+);/);
2105
2525
  const mimeType = mimeMatch?.[1] || blob.type || 'image/png';
2106
2526
  const handedOverFile = new File([blob], fileName, { type: mimeType });
2527
+ const pictureFingerprint = await fingerprintFile(handedOverFile);
2107
2528
  // The same file comes back when there is nothing to do (a small picture) or when it could not be made ready in time (see
2108
2529
  // `prepareImageWithTimeLimit`: a picture that never gets ready must not hold up the pastes after it); a large one comes
2109
2530
  // back smaller, under a new name.
@@ -2129,13 +2550,15 @@
2129
2550
  // The tile keeps drawing this `data:` URL, and the draft keeps it too: the stored address that comes when the upload
2130
2551
  // ends is only the picture's second choice (see `readAttachmentPreviewUrl`).
2131
2552
  persistedDataUrl: pictureDataUrl,
2553
+ // What the picture is made of, so the same picture dragged or pasted later is recognised and not attached a second time
2554
+ fingerprint: pictureFingerprint,
2132
2555
  uploadProgress: 0,
2133
2556
  };
2134
2557
  labelNewAttachments([attachmentInput], [forcedLabel]);
2135
- const attachmentIndex = localAttachments.length;
2558
+ const previousTileCount = countTrayTiles();
2136
2559
  localAttachments = [...localAttachments, attachmentInput];
2137
2560
  notifyDraftChange();
2138
- expandChatForAttachmentGrowth(attachmentIndex);
2561
+ expandChatForAttachmentGrowth(previousTileCount);
2139
2562
  } catch (err) {
2140
2563
  console.error('[Chat] Failed to add image attachment:', err);
2141
2564
  } finally {
@@ -2303,8 +2726,8 @@
2303
2726
  const queuedMessage: QueuedMessage = {
2304
2727
  id: createQueuedMessageId(),
2305
2728
  text: trimmed,
2306
- // The files move with the message: they are not given back, they belong to the queue now
2307
- attachments: [...localAttachments],
2729
+ // The files move with the message: they are not given back, they belong to the queue now (a pasted text the words no longer name stays behind)
2730
+ attachments: attachmentsNamedByText(localAttachments, trimmed),
2308
2731
  chipIntent: pendingChipIntent ?? undefined,
2309
2732
  skipIntentGate: pendingSkipIntentGate,
2310
2733
  };
@@ -3034,11 +3457,17 @@
3034
3457
  {/if}
3035
3458
  {/snippet}
3036
3459
 
3460
+ <!-- Files dragged over any part of the chat (and dropped on it) are taken here: see `handleChatFileDrag` -->
3461
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
3037
3462
  <div
3038
3463
  bind:this={chatContainer}
3039
3464
  class="{className ? className : 'prompt-chat-ct'} border-border bg-background relative flex h-full min-h-0 max-w-full flex-col overflow-hidden border {showPanelHeader ? 'w-full' : 'w-chat-panel'} {className ? '' : 'rounded-panel'}"
3040
3465
  dir={$textDirection}
3041
3466
  style={style}
3467
+ ondragenter={handleChatFileDrag}
3468
+ ondragover={handleChatFileDrag}
3469
+ ondragleave={handleChatFileDragLeave}
3470
+ ondrop={handleChatFileDrop}
3042
3471
  >
3043
3472
  {#if showPanelHeader}
3044
3473
  {@const panelTitle =
@@ -3102,7 +3531,7 @@
3102
3531
  messages={currentMessages || []}
3103
3532
  isLoading={isLoading}
3104
3533
  isInitialized={isInitialized}
3105
- showEmptyState={showEmptyState && localAttachments.length === 0}
3534
+ showEmptyState={showEmptyState && !composerHasTiles}
3106
3535
  panelLayout={showPanelHeader}
3107
3536
  {context}
3108
3537
  isCompleted={isCompleted}
@@ -3121,6 +3550,7 @@
3121
3550
  generationPlan={isGenerating ? generationPlan : null}
3122
3551
  generationPlanPending={isGenerating ? generationPlanPending : false}
3123
3552
  {generationChanges}
3553
+ {generationSummary}
3124
3554
  onSuggestionSelected={handleSuggestionSelected}
3125
3555
  draftText={localInputText}
3126
3556
  onRestoreCheckpoint={onRestoreCheckpointBackend ? handleRestoreCheckpoint : undefined}
@@ -3185,19 +3615,6 @@
3185
3615
  </div>
3186
3616
  {/if}
3187
3617
 
3188
- {#if localAttachments.length > 0}
3189
- <ComposerAttachmentsTray
3190
- attachments={localAttachments}
3191
- previewUrl={getFooterAttachmentPreviewUrl}
3192
- isImage={isImageAttachment}
3193
- highlightedLabel={highlightedReferenceLabel}
3194
- onRemove={removeFooterAttachment}
3195
- onOpenPreview={(url) => {
3196
- footerLightboxSrc = url;
3197
- }}
3198
- />
3199
- {/if}
3200
-
3201
3618
  <!--
3202
3619
  The parts the person picked on the preview, as chips inside the message box (Figma: Selecting elements, frames 2 to 4).
3203
3620
  A chip says the first words of the part's note; its body opens that note over the part on the preview, and the cross takes
@@ -3244,9 +3661,23 @@
3244
3661
  {#if selectedElements && selectedElements.length > 0}
3245
3662
  {@render selectedElementChips()}
3246
3663
  {/if}
3664
+ <!-- The attached files, inside the box over the text: the chips first, then the pictures as small thumbnails below them.
3665
+ The box grows with them and its text scrolls when it has more than fits. -->
3666
+ {#if composerHasTiles}
3667
+ <ComposerAttachmentsTray
3668
+ attachments={localAttachments}
3669
+ previewUrl={getFooterAttachmentPreviewUrl}
3670
+ isImage={isImageAttachment}
3671
+ highlightedLabel={highlightedReferenceLabel}
3672
+ {flashedAttachmentIds}
3673
+ onRemove={removeFooterAttachment}
3674
+ onOpenPreview={openComposerPreview}
3675
+ />
3676
+ {/if}
3247
3677
  {/snippet}
3248
3678
 
3249
3679
  <ChatComposer
3680
+ bind:this={composerHandle}
3250
3681
  {sendNudgeToken}
3251
3682
  {completion}
3252
3683
  {referenceItems}
@@ -3285,45 +3716,29 @@
3285
3716
  const attachmentInputs = localAttachments.length > 0 ? localAttachments : undefined;
3286
3717
  handleComposerSend(content, attachmentInputs, sendOptions);
3287
3718
  }}
3288
- onFilesDropped={(files) => {
3289
- void addFilesAsAttachments(files);
3290
- }}
3291
3719
  onFilesPasted={config?.features?.fileUpload !== false
3292
- ? (pastedAttachments) => void addPastedAttachments(pastedAttachments)
3720
+ ? (pastedAttachments, selection) => void addPastedAttachments(pastedAttachments, selection)
3293
3721
  : undefined}
3294
3722
  onAttach={config?.features?.fileUpload !== false ? () => void handleUpload() : undefined}
3295
3723
  canSendWithoutText={(selectedElements ?? []).some((element) => !!element.note?.trim())}
3296
3724
  />
3297
3725
  </div>
3298
3726
 
3299
- {#if footerLightboxSrc}
3300
- <!-- svelte-ignore a11y_click_events_have_key_events -->
3301
- <!-- svelte-ignore a11y_no_static_element_interactions -->
3302
- <div
3303
- class="prompt-chat-footer-lightbox-overlay fixed inset-0 z-[9999] flex items-center justify-center bg-black/85"
3304
- onclick={() => (footerLightboxSrc = null)}
3305
- >
3306
- <button
3307
- type="button"
3308
- class="prompt-chat-footer-lightbox-close-btn absolute top-4 end-4 w-9 h-9 rounded-full bg-white/15 text-white text-lg flex items-center justify-center cursor-pointer hover:bg-white/30"
3309
- onclick={() => (footerLightboxSrc = null)}
3310
- title={$t('chat.attachment.close')}
3311
- aria-label={$t('chat.attachment.close')}
3312
- >
3313
- ✕
3314
- </button>
3315
- <!-- svelte-ignore a11y_click_events_have_key_events -->
3316
- <!-- svelte-ignore a11y_no_static_element_interactions -->
3317
- <div class="prompt-chat-footer-lightbox-content max-w-[90vw] max-h-[90vh]" onclick={(e) => e.stopPropagation()}>
3318
- <img
3319
- src={footerLightboxSrc}
3320
- alt={$t('chat.attachment.previewAlt')}
3321
- class="prompt-chat-footer-lightbox-image max-w-[90vw] max-h-[85vh] object-contain rounded-lg"
3322
- />
3323
- </div>
3324
- </div>
3727
+ <!-- The preview of a file of the message box: the card that opens from a thumbnail or a file chip, with the arrows to the next file -->
3728
+ {#if composerPreview}
3729
+ <AttachmentPreviewDialog
3730
+ files={composerPreview.files}
3731
+ openIndex={composerPreview.openIndex}
3732
+ onNavigate={(index) => {
3733
+ if (composerPreview) composerPreview = { ...composerPreview, openIndex: index };
3734
+ }}
3735
+ onClose={closeComposerPreview}
3736
+ />
3325
3737
  {/if}
3326
3738
 
3739
+ <!-- What covers the chat while files are dragged over it: the invitation to release them, or the word that they are not taken -->
3740
+ <ChatDropOverlay overlay={fileDragOverlay} />
3741
+
3327
3742
  <!-- Error Display -->
3328
3743
  {#if ui?.errorMessage}
3329
3744
  <div class="error-message-ct absolute top-0 start-0 end-0 bg-red-50 border-s-4 border-red-400 p-3 flex items-center justify-between gap-2 text-sm text-red-700 rounded-none z-10">