@widgetic/chat 0.1.45 → 0.1.48

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +148 -20
  2. package/dist/components/AttachmentDisplay.svelte +22 -130
  3. package/dist/components/AttachmentPreviewDialog.svelte +428 -0
  4. package/dist/components/AttachmentPreviewDialog.svelte.d.ts +14 -0
  5. package/dist/components/Chat.svelte +514 -94
  6. package/dist/components/Chat.svelte.d.ts +19 -2
  7. package/dist/components/ChatComposer.svelte +126 -72
  8. package/dist/components/ChatComposer.svelte.d.ts +13 -3
  9. package/dist/components/ChatDropOverlay.svelte +58 -0
  10. package/dist/components/ChatDropOverlay.svelte.d.ts +8 -0
  11. package/dist/components/ChatInput.svelte +42 -1
  12. package/dist/components/ChatInput.svelte.d.ts +2 -0
  13. package/dist/components/ChatMessages.svelte +322 -98
  14. package/dist/components/ChatMessages.svelte.d.ts +11 -2
  15. package/dist/components/ComposerAttachmentsTray.svelte +144 -56
  16. package/dist/components/ComposerAttachmentsTray.svelte.d.ts +11 -1
  17. package/dist/components/FileGlyphIcon.svelte +34 -0
  18. package/dist/components/FileGlyphIcon.svelte.d.ts +8 -0
  19. package/dist/components/RestoreCheckpointDialog.svelte +66 -0
  20. package/dist/components/RestoreCheckpointDialog.svelte.d.ts +11 -0
  21. package/dist/components/SentAttachments.svelte +118 -0
  22. package/dist/components/SentAttachments.svelte.d.ts +12 -0
  23. package/dist/components/agent/AgentTurn.svelte +17 -2
  24. package/dist/components/agent/CodeCard.svelte +9 -3
  25. package/dist/i18n/messages.d.ts +45 -3
  26. package/dist/i18n/messages.js +51 -5
  27. package/dist/services/index.d.ts +4 -2
  28. package/dist/services/index.js +2 -1
  29. package/dist/services/limitRefusal.d.ts +42 -0
  30. package/dist/services/limitRefusal.js +60 -0
  31. package/dist/services/sketchAssistantClient.d.ts +11 -3
  32. package/dist/services/sketchAssistantClient.js +37 -10
  33. package/dist/services/sketchAssistantErrors.d.ts +16 -1
  34. package/dist/services/sketchAssistantErrors.js +25 -4
  35. package/dist/services/sketchAssistantOrchestrator.d.ts +7 -1
  36. package/dist/services/sketchAssistantOrchestrator.js +2 -2
  37. package/dist/types/attachment.d.ts +11 -0
  38. package/dist/utils/agentTurn.d.ts +32 -1
  39. package/dist/utils/agentTurn.js +46 -3
  40. package/dist/utils/attachmentDuplicates.d.ts +48 -0
  41. package/dist/utils/attachmentDuplicates.js +70 -0
  42. package/dist/utils/attachmentPolicy.d.ts +88 -0
  43. package/dist/utils/attachmentPolicy.js +135 -0
  44. package/dist/utils/attachmentPreview.d.ts +146 -0
  45. package/dist/utils/attachmentPreview.js +224 -0
  46. package/dist/utils/attachmentTray.d.ts +35 -0
  47. package/dist/utils/attachmentTray.js +27 -0
  48. package/dist/utils/chatFileDrag.d.ts +39 -0
  49. package/dist/utils/chatFileDrag.js +29 -0
  50. package/dist/utils/composerPreview.d.ts +33 -0
  51. package/dist/utils/composerPreview.js +31 -0
  52. package/dist/utils/generationArchiveStore.d.ts +5 -1
  53. package/dist/utils/generationArchiveStore.js +9 -4
  54. package/dist/utils/index.d.ts +1 -1
  55. package/dist/utils/index.js +1 -1
  56. package/dist/utils/limitFailureLine.d.ts +20 -0
  57. package/dist/utils/limitFailureLine.js +40 -0
  58. package/dist/utils/panelListPadding.d.ts +20 -0
  59. package/dist/utils/panelListPadding.js +31 -0
  60. package/dist/utils/pasteInsertion.d.ts +43 -0
  61. package/dist/utils/pasteInsertion.js +94 -0
  62. package/dist/utils/pastedContent.d.ts +13 -0
  63. package/dist/utils/pastedContent.js +18 -1
  64. package/dist/utils/referenceItems.js +11 -3
  65. package/dist/utils/sentAttachments.d.ts +43 -0
  66. package/dist/utils/sentAttachments.js +38 -0
  67. package/dist/utils/sentReferenceBadges.d.ts +11 -1
  68. package/dist/utils/sentReferenceBadges.js +47 -2
  69. package/package.json +3 -3
@@ -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
@@ -399,6 +439,10 @@
399
439
  composerModels?: ComposerModelOption[];
400
440
  selectedComposerModelId?: string | null;
401
441
  onSelectComposerModel?: (modelId: string) => void;
442
+ /**
443
+ * Rewrites the text in the composer (Magic Enhance). Left out, the sparkle control is not drawn.
444
+ */
445
+ onEnhancePrompt?: (prompt: string) => Promise<string>;
402
446
  }
403
447
 
404
448
  // Expose methods to parent component
@@ -449,7 +493,7 @@
449
493
  updateLastUserMessageAttachments: (attachments: Array<{ id?: string; url: string; file_type?: string; file_name?: string | null }>) => void;
450
494
  }
451
495
 
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();
496
+ 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, onEnhancePrompt }: Props = $props();
453
497
 
454
498
  // The words of everything inside the chat, in the language the page chose. The page can change the language while the
455
499
  // chat is open: the settings are read again whenever they change (and setting the same language again does nothing).
@@ -602,7 +646,8 @@
602
646
  try {
603
647
  const takenLabels = labelsOfAttachments(localAttachments);
604
648
  entries.forEach((entry, entryIndex) => {
605
- if (!isReferenceableAttachment(entry)) return;
649
+ // A text pasted into the box is named in the message by its badge, so it is called by a label too
650
+ if (!isReferenceableAttachment(entry) && !isPastedTextAttachment(entry)) return;
606
651
  const label =
607
652
  forcedLabels?.[entryIndex] ??
608
653
  assignReferenceLabel(entry.file?.name ?? '', { takenLabels, genericNumberFloor: referenceGenericFloor });
@@ -629,8 +674,22 @@
629
674
  attachmentInputs: AttachmentInput[] | undefined,
630
675
  sendOptions?: ComposerSendOptions,
631
676
  ): void {
632
- const references = sendOptions?.references ?? [];
633
- void sendMessage(content, attachmentInputs, references.length > 0 ? { references } : undefined);
677
+ // 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
678
+ // a file that nothing on the screen shows must not be sent with a message that does not name it.
679
+ const namedAttachments = attachmentInputs ? attachmentsNamedByText(attachmentInputs, content) : undefined;
680
+ const sentAttachments = namedAttachments && namedAttachments.length > 0 ? namedAttachments : undefined;
681
+ // The references of a send name pictures (the host tells the builder which picture a `#word` means). A pasted text is named by its
682
+ // badge and travels as a text file that the host reads by its name, so it is not among them.
683
+ const pastedTextLabels = new Set(
684
+ (attachmentInputs ?? [])
685
+ .filter(isPastedTextAttachment)
686
+ .map((attachment) => attachment.referenceLabel?.toLowerCase())
687
+ .filter((label): label is string => !!label),
688
+ );
689
+ const references = (sendOptions?.references ?? []).filter(
690
+ (reference) => !pastedTextLabels.has(reference.label.toLowerCase()),
691
+ );
692
+ void sendMessage(content, sentAttachments, references.length > 0 ? { references } : undefined);
634
693
  }
635
694
 
636
695
  /** 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 +745,11 @@
686
745
  // First the pictures that came back: none answers to a word the restored text already names ...
687
746
  renameRestoredPicturesNamedByText(localInputText);
688
747
  // ... 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));
748
+ // 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
749
+ // plain `#pasted_text` that stands for nothing. Then every other badge whose file is gone is plain `#label` again.
750
+ const attachedLabels = labelsOfAttachments(localAttachments);
751
+ const withoutPastedTextBadges = removeBadgesOfMissingPastedTexts(localInputText, attachedLabels);
752
+ const checkedText = unbadgeTokensWithoutFiles(withoutPastedTextBadges.text, attachedLabels);
690
753
  if (checkedText !== localInputText) {
691
754
  chatLog('[Chat] A restored draft had badges for files that are not attached: they are plain text again');
692
755
  localInputText = checkedText;
@@ -729,6 +792,11 @@
729
792
  }
730
793
  }
731
794
  }
795
+ if (flashedAttachmentTimer) clearTimeout(flashedAttachmentTimer);
796
+ // A drag that was still over the chat is over with it
797
+ stopWaitingForFileDrag();
798
+ // The addresses made for an open preview go with the chat
799
+ releaseComposerPreviewAddresses();
732
800
  // The waiting messages go with the chat: their pictures are given back and nothing is sent once the chat is gone
733
801
  clearQueueSendNowTimer();
734
802
  releasePreviewAddresses(blobPreviewsOf(queuedMessages.flatMap((message) => message.attachments)));
@@ -1445,12 +1513,12 @@
1445
1513
  // The label the message can call the screenshot by (`#Image_1`), given in the same breath as it joins the tray
1446
1514
  labelNewAttachments([attachmentInput]);
1447
1515
 
1516
+ const previousTileCount = countTrayTiles();
1448
1517
  localAttachments = [...localAttachments, attachmentInput];
1449
- const attachmentIndex = localAttachments.length - 1;
1450
1518
  notifyDraftChange();
1451
- expandChatForAttachmentGrowth(attachmentIndex);
1519
+ expandChatForAttachmentGrowth(previousTileCount);
1452
1520
  chatStore.actions.updateUI({ errorMessage: null });
1453
- console.log('[Chat] attachments now', localAttachments.length);
1521
+ // console.log('[Chat] attachments now', localAttachments.length);
1454
1522
 
1455
1523
  if (onUploadChatFile) {
1456
1524
  await uploadAttachmentToCdn(screenshotFile, attachmentInput, {
@@ -1503,7 +1571,7 @@
1503
1571
 
1504
1572
  // Add to attachments
1505
1573
  localAttachments = [...localAttachments, attachmentInput];
1506
- console.log('[Chat] attachments now', localAttachments.length);
1574
+ // console.log('[Chat] attachments now', localAttachments.length);
1507
1575
 
1508
1576
  // chatLog('Recording stopped and added to attachments');
1509
1577
 
@@ -1592,7 +1660,9 @@
1592
1660
  }
1593
1661
 
1594
1662
  function expandChatForAttachmentGrowth(previousCount: number) {
1595
- if (localAttachments.length <= previousCount) return;
1663
+ // Counted in tiles: a text that was pasted is a badge in the words and takes no room of its own
1664
+ const tileCount = countTrayTiles();
1665
+ if (tileCount <= previousCount) return;
1596
1666
 
1597
1667
  // When the first attachment appears, free space in a fixed messages area so the footer tray stays visible.
1598
1668
  if (previousCount === 0 && messagesAreaHeight !== null) {
@@ -1602,7 +1672,7 @@
1602
1672
  if (!resizeExpandsContainer) return;
1603
1673
  // Grow the fixed-height host once per net attachment increase so the tray is not clipped.
1604
1674
  onMessagesResize?.(120);
1605
- chatLog('[Chat] Expanded chat host for attachments:', previousCount, '→', localAttachments.length);
1675
+ chatLog('[Chat] Expanded chat host for attachments:', previousCount, '→', tileCount);
1606
1676
  }
1607
1677
 
1608
1678
  function isImageAttachment(attachment: AttachmentInput): boolean {
@@ -1646,7 +1716,48 @@
1646
1716
  chatLog('[Chat] Removed footer attachment at index:', index);
1647
1717
  }
1648
1718
 
1649
- let footerLightboxSrc: string | null = $state(null);
1719
+ // ===== The preview of a file of the message box (a card with the look of the File Browser's preview) =====
1720
+ /** The files the open preview steps through and the place of the open one, or null while no preview is open. */
1721
+ let composerPreview = $state<{ files: PreviewableFile[]; openIndex: number } | null>(null);
1722
+ /** The addresses made only for the open preview (a text file has none until it is uploaded): given back when the preview closes. */
1723
+ let composerPreviewMadeUrls: string[] = [];
1724
+
1725
+ /** Gives back the addresses that were made for a preview, so the browser does not keep the files in memory for nothing. */
1726
+ function releaseComposerPreviewAddresses(): void {
1727
+ releasePreviewAddresses(composerPreviewMadeUrls);
1728
+ composerPreviewMadeUrls = [];
1729
+ }
1730
+
1731
+ /** A thumbnail or a file chip of the message box was pressed: its file opens in the preview, with the files next to it. */
1732
+ function openComposerPreview(pressed: AttachmentInput): void {
1733
+ try {
1734
+ const preview = composerPreviewOf(localAttachments, pressed, {
1735
+ isPicture: isImageAttachment,
1736
+ readUrl: getFooterAttachmentPreviewUrl,
1737
+ makeObjectUrl: (file) => {
1738
+ try {
1739
+ return URL.createObjectURL(file);
1740
+ } catch (error) {
1741
+ console.warn('[Chat] Could not make an address to preview the attached file:', error);
1742
+ return null;
1743
+ }
1744
+ },
1745
+ });
1746
+ if (!preview) return;
1747
+ // The addresses of an earlier preview are not needed any more
1748
+ releaseComposerPreviewAddresses();
1749
+ composerPreviewMadeUrls = preview.madeUrls;
1750
+ composerPreview = { files: preview.files, openIndex: preview.openIndex };
1751
+ chatLog('[Chat] A file of the message box was opened in the preview:', pressed.file?.name);
1752
+ } catch (error) {
1753
+ console.warn('[Chat] Could not open the attached file in the preview:', error);
1754
+ }
1755
+ }
1756
+
1757
+ function closeComposerPreview(): void {
1758
+ composerPreview = null;
1759
+ releaseComposerPreviewAddresses();
1760
+ }
1650
1761
 
1651
1762
  /** Biggest image kept in the draft: a draft is written to the browser's storage on every change. */
1652
1763
  const MAX_PERSISTED_IMAGE_BYTES = 6 * 1024 * 1024;
@@ -1684,25 +1795,137 @@
1684
1795
  }
1685
1796
 
1686
1797
  /**
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.
1798
+ * 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).
1799
+ * The chat makes room for the tray when this goes from nothing to something.
1800
+ */
1801
+ function countTrayTiles(): number {
1802
+ return localAttachments.filter((attachment) => !isPastedTextAttachment(attachment)).length;
1803
+ }
1804
+
1805
+ /** How long the tile of a file that was attached already stays ringed when the person tries to attach it again. */
1806
+ const KNOWN_FILE_FLASH_MS = 1400;
1807
+ /** The files the person tried to attach again (they are in the tray already): their tiles are ringed for a moment. */
1808
+ let flashedAttachmentIds = $state<string[]>([]);
1809
+ let flashedAttachmentTimer: ReturnType<typeof setTimeout> | null = null;
1810
+
1811
+ /**
1812
+ * 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
1813
+ * leaves the caret at its end.
1814
+ */
1815
+ let composerHandle = $state<{ placeCaret: (position: number) => Promise<void> } | null>(null);
1816
+
1817
+ /**
1818
+ * The fingerprints (see `fingerprintFile`) of files that arrived and are not in the tray yet: a big picture is made smaller first,
1819
+ * and the same picture dropped twice in that time must still be attached once.
1820
+ */
1821
+ const fingerprintsBeingPrepared = new Set<string>();
1822
+
1823
+ /** What a file that arrives carries, besides the file: the words of its tile, and for a pasted text its beginning. */
1824
+ type ArrivingFile = { file: File; label?: string; excerpt?: string };
1825
+
1826
+ /**
1827
+ * 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
1828
+ * the batch itself, or in a batch that is being made ready). Their fingerprints are made first, and the sorting is one step with
1829
+ * no wait in it, so two arrivals that follow each other never both find the tray empty. The new ones are held (in
1830
+ * `fingerprintsBeingPrepared`) until their tiles are in the tray; `known` says which tile has the file, when there is one.
1831
+ */
1832
+ async function sortOutKnownFiles<Entry extends ArrivingFile>(
1833
+ entries: Entry[],
1834
+ ): Promise<{
1835
+ fresh: Array<Entry & { fingerprint: string }>;
1836
+ known: Array<{ entry: Entry; existing: AttachmentInput | null }>;
1837
+ }> {
1838
+ const fingerprinted = await Promise.all(
1839
+ entries.map(async (entry) => ({ entry, fingerprint: await fingerprintFile(entry.file) })),
1840
+ );
1841
+ const { fresh, known } = splitNewFromKnown(fingerprinted, localAttachments, fingerprintsBeingPrepared);
1842
+ for (const { fingerprint } of fresh) fingerprintsBeingPrepared.add(fingerprint);
1843
+ return {
1844
+ fresh: fresh.map(({ entry, fingerprint }) => ({ ...entry, fingerprint })),
1845
+ known: known.map(({ entry, existingIndex }) => ({
1846
+ entry,
1847
+ existing: existingIndex >= 0 ? (localAttachments[existingIndex] ?? null) : null,
1848
+ })),
1849
+ };
1850
+ }
1851
+
1852
+ /** 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). */
1853
+ function releaseFingerprints(fingerprints: readonly string[]): void {
1854
+ for (const fingerprint of fingerprints) fingerprintsBeingPrepared.delete(fingerprint);
1855
+ }
1856
+
1857
+ /**
1858
+ * 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
1859
+ * the person sees it is there. (A text that was pasted again is named in the message once more: see `addPastedAttachments`.)
1860
+ */
1861
+ function flashKnownFiles(known: ReadonlyArray<{ existing: AttachmentInput | null }>): void {
1862
+ if (known.length === 0) return;
1863
+ chatLog('[Chat] Files that are attached already were not attached again:', known.length);
1864
+ const tileIds = known
1865
+ .map(({ existing }) => existing)
1866
+ .filter((existing): existing is AttachmentInput => !!existing?.id && !isPastedTextAttachment(existing))
1867
+ .map((existing) => existing.id as string);
1868
+ if (tileIds.length === 0) return;
1869
+ flashedAttachmentIds = tileIds;
1870
+ if (flashedAttachmentTimer) clearTimeout(flashedAttachmentTimer);
1871
+ flashedAttachmentTimer = setTimeout(() => {
1872
+ flashedAttachmentIds = [];
1873
+ flashedAttachmentTimer = null;
1874
+ }, KNOWN_FILE_FLASH_MS);
1875
+ }
1876
+
1877
+ /**
1878
+ * 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
1879
+ * says it once. A file that is not a kind the box takes, one that is too large, or a folder.
1880
+ */
1881
+ function reportRefusedFiles(refused: readonly RefusedAttachment[]): void {
1882
+ if (refused.length === 0) return;
1883
+ chatWarn('[Chat] Files were left out:', refused.map(({ file, reason }) => `${file.name} (${reason})`).join(', '));
1884
+ try {
1885
+ const folders = refused.filter(({ reason }) => reason === 'folder');
1886
+ const wrongKind = refused.filter(({ reason }) => reason === 'type');
1887
+ const tooLarge = refused.filter(({ reason }) => reason === 'size');
1888
+ if (folders.length > 0) showToast('error', $t('chat.attachment.refusedFolder'));
1889
+ if (wrongKind.length === 1) {
1890
+ showToast('error', $t('chat.attachment.refusedTypeOne', { name: wrongKind[0].file.name }));
1891
+ } else if (wrongKind.length > 1) {
1892
+ showToast('error', $t('chat.attachment.refusedTypeMany', { count: wrongKind.length }));
1893
+ }
1894
+ if (tooLarge.length === 1) {
1895
+ const limit = fileSizeText(tooLarge[0].limitBytes, $t, $spokenLocale);
1896
+ showToast('error', $t('chat.attachment.refusedSizeOne', { name: tooLarge[0].file.name, limit }));
1897
+ } else if (tooLarge.length > 1) {
1898
+ showToast('error', $t('chat.attachment.refusedSizeMany', { count: tooLarge.length }));
1899
+ }
1900
+ } catch (error) {
1901
+ console.warn('[Chat] Could not tell which files were left out:', error);
1902
+ }
1903
+ }
1904
+
1905
+ /**
1906
+ * Attaches files to the message being written: the ones dropped on the chat, picked with "+", or pasted into the box. A file may
1907
+ * 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
1908
+ * beginning (`excerpt`, which is also what makes it a pasted text). The tiles are put in the tray first and the files are
1909
+ * uploaded after, one by one; `onTilesAdded` is called between the two, with the tiles that were added, so a caller that keeps a
1910
+ * line of pastes (see `addPastedAttachments`) can let the next paste in while these files are still uploading, and one that has
1911
+ * to write into the text (a badge for a pasted text) does it in the same step as the tiles come.
1691
1912
  */
1692
1913
  async function attachFiles(
1693
- entries: Array<{ file: File; label?: string }>,
1694
- options: { onTilesAdded?: () => void } = {},
1914
+ entries: Array<ArrivingFile & { fingerprint?: string }>,
1915
+ options: { onTilesAdded?: (addedAttachments: AttachmentInput[]) => void } = {},
1695
1916
  ) {
1696
1917
  const usableEntries = (entries || []).filter(({ file }) => file && file.size > 0);
1697
1918
  if (usableEntries.length === 0) return;
1698
1919
 
1699
- const previousCount = localAttachments.length;
1700
- const newAttachments: AttachmentInput[] = usableEntries.map(({ file, label }) => ({
1920
+ const previousTileCount = countTrayTiles();
1921
+ const newAttachments: AttachmentInput[] = usableEntries.map(({ file, label, excerpt, fingerprint }) => ({
1701
1922
  // Tells the tiles apart while the tray shows them (two pasted screenshots are both "image.png"), and is how the upload
1702
1923
  // finds its tile again while other uploads run: see `updateAttachment`.
1703
1924
  id: generateFileId(),
1704
1925
  file,
1705
1926
  label,
1927
+ excerpt,
1928
+ fingerprint,
1706
1929
  type: file.type.startsWith('image/')
1707
1930
  ? 'image'
1708
1931
  : file.type.startsWith('video/')
@@ -1716,13 +1939,13 @@
1716
1939
  labelNewAttachments(newAttachments);
1717
1940
  localAttachments = [...localAttachments, ...newAttachments];
1718
1941
  notifyDraftChange();
1719
- expandChatForAttachmentGrowth(previousCount);
1942
+ expandChatForAttachmentGrowth(previousTileCount);
1720
1943
  chatStore.actions.updateUI({ errorMessage: null });
1721
- console.log('[Chat] attachments now', localAttachments.length);
1944
+ // console.log('[Chat] attachments now', localAttachments.length);
1722
1945
  // The draft keeps each picture as it is attached, before the upload ends (a refresh can come at any time).
1723
1946
  for (const entry of newAttachments) void rememberImageForDraft(entry);
1724
1947
  // Everything the next paste has to see is in the tray now; the uploads below are not waited for.
1725
- options.onTilesAdded?.();
1948
+ options.onTilesAdded?.(newAttachments);
1726
1949
 
1727
1950
  try {
1728
1951
  localIsUploading = true;
@@ -1737,18 +1960,126 @@
1737
1960
  }
1738
1961
 
1739
1962
  /**
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`).
1963
+ * 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
1964
+ * out with a word about why; a file that is attached already (the same bytes, whatever it is called) is not attached again, and
1965
+ * its tile is ringed instead. A picture is made smaller first when it is large (see `prepareChatImageFileForUpload`; a paste gets
1966
+ * the same preparation, in the line of the pastes: see `addPastedAttachments`), and the size that counts is the one that is sent.
1742
1967
  */
1743
1968
  async function addFilesAsAttachments(files: File[]) {
1744
- const incoming = (files || []).filter((file) => file && file.size > 0);
1969
+ const incoming = Array.from(files || []).filter((file) => !!file);
1745
1970
  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 })));
1971
+ // A picture may be too large as it comes and fine once it is made smaller, so its size is checked after that
1972
+ const { accepted, refused } = partitionAttachmentFiles(incoming, { skipPictureSize: true });
1973
+ reportRefusedFiles(refused);
1974
+ const usableFiles = accepted.filter((file) => file.size > 0);
1975
+ if (usableFiles.length === 0) return;
1976
+
1977
+ const { fresh, known } = await sortOutKnownFiles(usableFiles.map((file) => ({ file })));
1978
+ flashKnownFiles(known);
1979
+ if (fresh.length === 0) return;
1980
+ const heldFingerprints = fresh.map(({ fingerprint }) => fingerprint);
1981
+ try {
1982
+ const preparedEntries = await Promise.all(
1983
+ fresh.map(async (entry) => ({
1984
+ ...entry,
1985
+ file: entry.file.type.startsWith('image/') ? await prepareChatImageFileForUpload(entry.file) : entry.file,
1986
+ })),
1987
+ );
1988
+ const stillTooLarge: RefusedAttachment[] = [];
1989
+ const attachableEntries = preparedEntries.filter((entry) => {
1990
+ const check = checkAttachmentFile(entry.file);
1991
+ if (check.ok) return true;
1992
+ if (check.reason === 'size') stillTooLarge.push({ file: entry.file, reason: 'size', limitBytes: check.limitBytes });
1993
+ return false;
1994
+ });
1995
+ reportRefusedFiles(stillTooLarge);
1996
+ await attachFiles(attachableEntries, { onTilesAdded: () => releaseFingerprints(heldFingerprints) });
1997
+ } catch (error) {
1998
+ console.error('[Chat] Could not attach the files:', error);
1999
+ } finally {
2000
+ // Held only until the tiles are in the tray: let go even when the files could not be attached (letting go twice changes nothing)
2001
+ releaseFingerprints(heldFingerprints);
2002
+ }
2003
+ }
2004
+
2005
+ // --- Files dragged over the chat -------------------------------------------------------------------------------------------
2006
+ // 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
2007
+ // would do (`ChatDropOverlay`). The drag events of every part of the chat come up to its root, so one set of handlers there is
2008
+ // enough, and the message box has none of its own.
2009
+
2010
+ /** What covers the chat now: nothing, the invitation to release the files, or the word that they are not taken. */
2011
+ let fileDragOverlay = $state<FileDragOverlay>('hidden');
2012
+ let fileDragIdleTimer: ReturnType<typeof setTimeout> | null = null;
2013
+
2014
+ /** Whether the chat takes files at all: the host that switched uploads off gets no veil and no drop. */
2015
+ const chatTakesFiles = $derived(config?.features?.fileUpload !== false);
2016
+
2017
+ function stopWaitingForFileDrag(): void {
2018
+ if (fileDragIdleTimer) clearTimeout(fileDragIdleTimer);
2019
+ fileDragIdleTimer = null;
2020
+ }
2021
+
2022
+ /** The drag is over (the files left, were dropped, or the browser stopped saying): the veil goes away. */
2023
+ function endFileDrag(): void {
2024
+ stopWaitingForFileDrag();
2025
+ fileDragOverlay = 'hidden';
2026
+ }
2027
+
2028
+ /** Files over the chat (`dragenter`, then `dragover` for as long as they stay): the chat says what releasing them would do. */
2029
+ function handleChatFileDrag(event: DragEvent): void {
2030
+ if (!chatTakesFiles) return;
2031
+ const verdict = judgeDragTransfer(event.dataTransfer);
2032
+ // A text or a link dragged over the chat is not for it: the browser deals with it as it always did
2033
+ if (verdict === 'none') return;
2034
+ // 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.
2035
+ event.preventDefault();
2036
+ if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';
2037
+ const nextOverlay = overlayForVerdict(verdict);
2038
+ if (nextOverlay !== fileDragOverlay) {
2039
+ fileDragOverlay = nextOverlay;
2040
+ chatLog('[Chat] Files are over the chat:', nextOverlay);
2041
+ }
2042
+ // The browser says nothing when a drag is cancelled (Escape): the chat takes the drag for over when it stops hearing from it
2043
+ stopWaitingForFileDrag();
2044
+ fileDragIdleTimer = setTimeout(endFileDrag, FILE_DRAG_IDLE_MS);
2045
+ }
2046
+
2047
+ /** 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). */
2048
+ function handleChatFileDragLeave(event: DragEvent): void {
2049
+ if (fileDragOverlay === 'hidden' || !chatContainer) return;
2050
+ try {
2051
+ const chatBox = chatContainer.getBoundingClientRect();
2052
+ const leftTheChat = dragLeftTheChat(
2053
+ { relatedTarget: event.relatedTarget, clientX: event.clientX, clientY: event.clientY },
2054
+ {
2055
+ contains: (node) => node instanceof Node && chatContainer.contains(node),
2056
+ left: chatBox.left,
2057
+ top: chatBox.top,
2058
+ right: chatBox.right,
2059
+ bottom: chatBox.bottom,
2060
+ },
2061
+ );
2062
+ if (leftTheChat) endFileDrag();
2063
+ } catch (error) {
2064
+ console.warn('[Chat] Could not tell whether the files left the chat:', error);
2065
+ endFileDrag();
2066
+ }
2067
+ }
2068
+
2069
+ /** Files released over the chat, wherever on it: they are attached the way the ones picked with "+" are. */
2070
+ function handleChatFileDrop(event: DragEvent): void {
2071
+ if (!chatTakesFiles || !dragCarriesFiles(event.dataTransfer)) return;
2072
+ event.preventDefault();
2073
+ // The drop is the chat's: a host that also listens for dropped files above the chat does not get it too
2074
+ event.stopPropagation();
2075
+ endFileDrag();
2076
+ try {
2077
+ const droppedFiles = Array.from(event.dataTransfer?.files ?? []);
2078
+ chatLog('[Chat] Files were dropped on the chat:', droppedFiles.length);
2079
+ if (droppedFiles.length > 0) void addFilesAsAttachments(droppedFiles);
2080
+ } catch (error) {
2081
+ console.error('[Chat] Could not take the files that were dropped:', error);
2082
+ }
1752
2083
  }
1753
2084
 
1754
2085
  /**
@@ -1760,31 +2091,118 @@
1760
2091
  */
1761
2092
  const pasteTileLine = createOrderedLine();
1762
2093
 
2094
+ /**
2095
+ * 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
2096
+ * the caret after the badge. The tiles and the words change in the same step (no wait between them), so nothing sees a text
2097
+ * that is attached and not yet named. A person pasting after the second paragraph has the badge after the second paragraph.
2098
+ */
2099
+ function writePastedTextBadges(
2100
+ pastedTexts: readonly AttachmentInput[],
2101
+ textWhenPasted: string,
2102
+ selection: PasteSelection | undefined,
2103
+ ): void {
2104
+ const namedTexts = pastedTexts.filter((attachment) => !!attachment.referenceLabel);
2105
+ if (namedTexts.length === 0) return;
2106
+ try {
2107
+ // Where the caret was, in the text as it is now (the person may have typed since the paste arrived)
2108
+ let insertionRange = resolvePasteInsertionRange(textWhenPasted, localInputText, selection);
2109
+ let nextText = localInputText;
2110
+ let caretAfterBadges = insertionRange.start;
2111
+ for (const pastedText of namedTexts) {
2112
+ const written = writeReferenceToken(nextText, insertionRange, pastedText.referenceLabel as string);
2113
+ nextText = written.text;
2114
+ caretAfterBadges = written.caret;
2115
+ insertionRange = { start: written.caret, end: written.caret };
2116
+ }
2117
+ localInputText = nextText;
2118
+ // The words were changed by the person's own paste: a suggestion they picked no longer stands for what is written
2119
+ pendingChipIntent = null;
2120
+ pendingSkipIntentGate = false;
2121
+ notifyDraftChange();
2122
+ void composerHandle?.placeCaret(caretAfterBadges);
2123
+ chatLog('[Chat] A pasted text is named in the message at', caretAfterBadges, 'as', namedTexts.map((text) => `#${text.referenceLabel}`).join(' '));
2124
+ } catch (error) {
2125
+ console.warn('[Chat] Could not name the pasted text in the message:', error);
2126
+ }
2127
+ }
2128
+
1763
2129
  /**
1764
2130
  * What a paste into the box brought in (see `attachmentsFromPaste`): a screenshot or a file, or a long text as a text file.
1765
2131
  * 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`).
2132
+ * (see `prepareImagesOfPaste`). A text has no tile: the message names it with a badge, written where the caret was (`selection`),
2133
+ * 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
2134
+ * 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
2135
+ * among the files already in the tray: two screenshots are both "image.png" and two texts both "pasted-text.txt", and the builder
2136
+ * 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
2137
+ * the order they were made in (see `pasteTileLine`).
1770
2138
  */
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.
2139
+ async function addPastedAttachments(pastedAttachments: PastedAttachment[], selection?: PasteSelection) {
2140
+ // 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
2141
+ // the caret was in: the badge of a pasted text is written into it where the caret was.
2142
+ const textWhenPasted = localInputText;
1773
2143
  const placeInLine = pasteTileLine.takePlace();
2144
+ let heldFingerprints: string[] = [];
1774
2145
  try {
1775
2146
  chatLog('[Chat] Attaching pasted content:', pastedAttachments.length);
2147
+ // 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)
2148
+ const { accepted, refused } = partitionAttachmentFiles(
2149
+ pastedAttachments.filter((pasted) => pasted.excerpt === undefined).map((pasted) => pasted.file),
2150
+ { skipPictureSize: true },
2151
+ );
2152
+ reportRefusedFiles(refused);
2153
+ const acceptedFiles = new Set(accepted);
2154
+ const takenPastes = pastedAttachments.filter(
2155
+ (pasted) => pasted.excerpt !== undefined || acceptedFiles.has(pasted.file),
2156
+ );
2157
+
2158
+ const { fresh, known } = await sortOutKnownFiles(takenPastes);
2159
+ flashKnownFiles(known);
2160
+ heldFingerprints = fresh.map(({ fingerprint }) => fingerprint);
2161
+ // A text that was pasted before and is still in the tray is named again, where the caret is now
2162
+ const knownPastedTexts = known
2163
+ .map(({ existing }) => existing)
2164
+ .filter((existing): existing is AttachmentInput => !!existing && isPastedTextAttachment(existing));
2165
+
1776
2166
  // Preparing is done by all the pastes at once; only the tiles wait for their place.
1777
- const preparedAttachments = await prepareImagesOfPaste(pastedAttachments, prepareChatImageFileForUpload);
2167
+ const preparedAttachments = await prepareImagesOfPaste(fresh, prepareChatImageFileForUpload);
1778
2168
  await placeInLine.untilReached;
1779
2169
  // 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
2170
  const namesInTray = localAttachments.map((attachment) => attachment.file?.name ?? '').filter(Boolean);
2171
+ const namedPastes = withUniqueFileNames(preparedAttachments, namesInTray).map((pasted, pasteIndex) => ({
2172
+ ...pasted,
2173
+ // The fingerprint is that of the file as it came: `prepareImagesOfPaste` and `withUniqueFileNames` keep the order and the length
2174
+ fingerprint: fresh[pasteIndex]?.fingerprint,
2175
+ }));
2176
+ const attachableEntries = namedPastes.filter((pasted) => {
2177
+ if (pasted.excerpt !== undefined) return true;
2178
+ const check = checkAttachmentFile(pasted.file);
2179
+ if (!check.ok && check.reason === 'size') {
2180
+ reportRefusedFiles([{ file: pasted.file, reason: 'size', limitBytes: check.limitBytes }]);
2181
+ }
2182
+ return check.ok;
2183
+ });
2184
+ if (attachableEntries.length === 0 && knownPastedTexts.length > 0) {
2185
+ // Nothing new: the text that is attached already is named again, in this same step
2186
+ writePastedTextBadges(knownPastedTexts, textWhenPasted, selection);
2187
+ }
1781
2188
  // 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 });
2189
+ await attachFiles(attachableEntries, {
2190
+ onTilesAdded: (addedAttachments) => {
2191
+ placeInLine.leave();
2192
+ releaseFingerprints(heldFingerprints);
2193
+ writePastedTextBadges(
2194
+ [...addedAttachments.filter(isPastedTextAttachment), ...knownPastedTexts],
2195
+ textWhenPasted,
2196
+ selection,
2197
+ );
2198
+ },
2199
+ });
1783
2200
  } catch (error) {
1784
2201
  console.error('[Chat] Could not attach the pasted content:', error);
1785
2202
  } finally {
1786
2203
  // The next paste's tiles may come now, even when this one could not be attached (leaving a second time changes nothing).
1787
2204
  placeInLine.leave();
2205
+ releaseFingerprints(heldFingerprints);
1788
2206
  }
1789
2207
  }
1790
2208
 
@@ -1794,7 +2212,8 @@
1794
2212
  const fileInput = document.createElement('input');
1795
2213
  fileInput.type = 'file';
1796
2214
  fileInput.multiple = true;
1797
- fileInput.accept = '*/*';
2215
+ // 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)
2216
+ fileInput.accept = ATTACHMENT_ACCEPT_ATTRIBUTE;
1798
2217
 
1799
2218
  fileInput.onchange = async (event) => {
1800
2219
  const files = Array.from((event.target as HTMLInputElement).files || []);
@@ -1852,8 +2271,13 @@
1852
2271
  /** 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
2272
  const mentionLinkHints = $derived(findMentionLinkHints(localInputText, mentionSources, localMentions, mentionLimit));
1854
2273
 
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);
2274
+ /** 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). */
2275
+ const composerHasTiles = $derived(trayHasTiles(localAttachments));
2276
+
2277
+ /** 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. */
2278
+ const composerHasChips = $derived(
2279
+ (selectedElements?.length ?? 0) > 0 || localMentions.length > 0 || mentionLinkHints.length > 0 || composerHasTiles,
2280
+ );
1857
2281
 
1858
2282
  function addMentionPick(mention: ComposerMention) {
1859
2283
  localMentions = addMention(localMentions, mention, mentionLimit);
@@ -2051,7 +2475,7 @@
2051
2475
  file_name: attachment.file_name || attachment.fileName || 'design-screenshot.png',
2052
2476
  file_size: attachment.file_size ?? attachment.fileSize,
2053
2477
  }));
2054
- console.log('[Chat] Restore echo attachments', restoredAttachments.length);
2478
+ // console.log('[Chat] Restore echo attachments', restoredAttachments.length);
2055
2479
  addUserMessage(promptCopy, restoredAttachments.length ? restoredAttachments : undefined);
2056
2480
  addAssistantMessage(`Restored from ${sourceLabel}\n\nCommit: ${newSha.slice(0, 8)}`);
2057
2481
  }
@@ -2104,6 +2528,7 @@
2104
2528
  const mimeMatch = dataUrl.match(/data:(image\/[^;]+);/);
2105
2529
  const mimeType = mimeMatch?.[1] || blob.type || 'image/png';
2106
2530
  const handedOverFile = new File([blob], fileName, { type: mimeType });
2531
+ const pictureFingerprint = await fingerprintFile(handedOverFile);
2107
2532
  // 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
2533
  // `prepareImageWithTimeLimit`: a picture that never gets ready must not hold up the pastes after it); a large one comes
2109
2534
  // back smaller, under a new name.
@@ -2129,13 +2554,15 @@
2129
2554
  // The tile keeps drawing this `data:` URL, and the draft keeps it too: the stored address that comes when the upload
2130
2555
  // ends is only the picture's second choice (see `readAttachmentPreviewUrl`).
2131
2556
  persistedDataUrl: pictureDataUrl,
2557
+ // What the picture is made of, so the same picture dragged or pasted later is recognised and not attached a second time
2558
+ fingerprint: pictureFingerprint,
2132
2559
  uploadProgress: 0,
2133
2560
  };
2134
2561
  labelNewAttachments([attachmentInput], [forcedLabel]);
2135
- const attachmentIndex = localAttachments.length;
2562
+ const previousTileCount = countTrayTiles();
2136
2563
  localAttachments = [...localAttachments, attachmentInput];
2137
2564
  notifyDraftChange();
2138
- expandChatForAttachmentGrowth(attachmentIndex);
2565
+ expandChatForAttachmentGrowth(previousTileCount);
2139
2566
  } catch (err) {
2140
2567
  console.error('[Chat] Failed to add image attachment:', err);
2141
2568
  } finally {
@@ -2303,8 +2730,8 @@
2303
2730
  const queuedMessage: QueuedMessage = {
2304
2731
  id: createQueuedMessageId(),
2305
2732
  text: trimmed,
2306
- // The files move with the message: they are not given back, they belong to the queue now
2307
- attachments: [...localAttachments],
2733
+ // 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)
2734
+ attachments: attachmentsNamedByText(localAttachments, trimmed),
2308
2735
  chipIntent: pendingChipIntent ?? undefined,
2309
2736
  skipIntentGate: pendingSkipIntentGate,
2310
2737
  };
@@ -3034,11 +3461,17 @@
3034
3461
  {/if}
3035
3462
  {/snippet}
3036
3463
 
3464
+ <!-- Files dragged over any part of the chat (and dropped on it) are taken here: see `handleChatFileDrag` -->
3465
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
3037
3466
  <div
3038
3467
  bind:this={chatContainer}
3039
3468
  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
3469
  dir={$textDirection}
3041
3470
  style={style}
3471
+ ondragenter={handleChatFileDrag}
3472
+ ondragover={handleChatFileDrag}
3473
+ ondragleave={handleChatFileDragLeave}
3474
+ ondrop={handleChatFileDrop}
3042
3475
  >
3043
3476
  {#if showPanelHeader}
3044
3477
  {@const panelTitle =
@@ -3102,7 +3535,7 @@
3102
3535
  messages={currentMessages || []}
3103
3536
  isLoading={isLoading}
3104
3537
  isInitialized={isInitialized}
3105
- showEmptyState={showEmptyState && localAttachments.length === 0}
3538
+ showEmptyState={showEmptyState && !composerHasTiles}
3106
3539
  panelLayout={showPanelHeader}
3107
3540
  {context}
3108
3541
  isCompleted={isCompleted}
@@ -3121,6 +3554,7 @@
3121
3554
  generationPlan={isGenerating ? generationPlan : null}
3122
3555
  generationPlanPending={isGenerating ? generationPlanPending : false}
3123
3556
  {generationChanges}
3557
+ {generationSummary}
3124
3558
  onSuggestionSelected={handleSuggestionSelected}
3125
3559
  draftText={localInputText}
3126
3560
  onRestoreCheckpoint={onRestoreCheckpointBackend ? handleRestoreCheckpoint : undefined}
@@ -3185,19 +3619,6 @@
3185
3619
  </div>
3186
3620
  {/if}
3187
3621
 
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
3622
  <!--
3202
3623
  The parts the person picked on the preview, as chips inside the message box (Figma: Selecting elements, frames 2 to 4).
3203
3624
  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 +3665,23 @@
3244
3665
  {#if selectedElements && selectedElements.length > 0}
3245
3666
  {@render selectedElementChips()}
3246
3667
  {/if}
3668
+ <!-- The attached files, inside the box over the text: the chips first, then the pictures as small thumbnails below them.
3669
+ The box grows with them and its text scrolls when it has more than fits. -->
3670
+ {#if composerHasTiles}
3671
+ <ComposerAttachmentsTray
3672
+ attachments={localAttachments}
3673
+ previewUrl={getFooterAttachmentPreviewUrl}
3674
+ isImage={isImageAttachment}
3675
+ highlightedLabel={highlightedReferenceLabel}
3676
+ {flashedAttachmentIds}
3677
+ onRemove={removeFooterAttachment}
3678
+ onOpenPreview={openComposerPreview}
3679
+ />
3680
+ {/if}
3247
3681
  {/snippet}
3248
3682
 
3249
3683
  <ChatComposer
3684
+ bind:this={composerHandle}
3250
3685
  {sendNudgeToken}
3251
3686
  {completion}
3252
3687
  {referenceItems}
@@ -3285,45 +3720,30 @@
3285
3720
  const attachmentInputs = localAttachments.length > 0 ? localAttachments : undefined;
3286
3721
  handleComposerSend(content, attachmentInputs, sendOptions);
3287
3722
  }}
3288
- onFilesDropped={(files) => {
3289
- void addFilesAsAttachments(files);
3290
- }}
3291
3723
  onFilesPasted={config?.features?.fileUpload !== false
3292
- ? (pastedAttachments) => void addPastedAttachments(pastedAttachments)
3724
+ ? (pastedAttachments, selection) => void addPastedAttachments(pastedAttachments, selection)
3293
3725
  : undefined}
3294
3726
  onAttach={config?.features?.fileUpload !== false ? () => void handleUpload() : undefined}
3727
+ onEnhancePrompt={onEnhancePrompt}
3295
3728
  canSendWithoutText={(selectedElements ?? []).some((element) => !!element.note?.trim())}
3296
3729
  />
3297
3730
  </div>
3298
3731
 
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>
3732
+ <!-- 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 -->
3733
+ {#if composerPreview}
3734
+ <AttachmentPreviewDialog
3735
+ files={composerPreview.files}
3736
+ openIndex={composerPreview.openIndex}
3737
+ onNavigate={(index) => {
3738
+ if (composerPreview) composerPreview = { ...composerPreview, openIndex: index };
3739
+ }}
3740
+ onClose={closeComposerPreview}
3741
+ />
3325
3742
  {/if}
3326
3743
 
3744
+ <!-- What covers the chat while files are dragged over it: the invitation to release them, or the word that they are not taken -->
3745
+ <ChatDropOverlay overlay={fileDragOverlay} />
3746
+
3327
3747
  <!-- Error Display -->
3328
3748
  {#if ui?.errorMessage}
3329
3749
  <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">