@widgetic/chat 0.1.44 → 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 (75) hide show
  1. package/README.md +162 -20
  2. package/dist/components/ActionBar.svelte +14 -1
  3. package/dist/components/ActionBar.svelte.d.ts +6 -0
  4. package/dist/components/AttachmentDisplay.svelte +22 -130
  5. package/dist/components/AttachmentPreviewDialog.svelte +428 -0
  6. package/dist/components/AttachmentPreviewDialog.svelte.d.ts +14 -0
  7. package/dist/components/Chat.svelte +556 -121
  8. package/dist/components/Chat.svelte.d.ts +15 -2
  9. package/dist/components/ChatComposer.svelte +63 -69
  10. package/dist/components/ChatComposer.svelte.d.ts +8 -3
  11. package/dist/components/ChatDropOverlay.svelte +58 -0
  12. package/dist/components/ChatDropOverlay.svelte.d.ts +8 -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/PanelSuggestionButtons.svelte +67 -19
  20. package/dist/components/PanelSuggestionButtons.svelte.d.ts +3 -1
  21. package/dist/components/RestoreCheckpointDialog.svelte +66 -0
  22. package/dist/components/RestoreCheckpointDialog.svelte.d.ts +11 -0
  23. package/dist/components/SentAttachments.svelte +118 -0
  24. package/dist/components/SentAttachments.svelte.d.ts +12 -0
  25. package/dist/components/agent/AgentTurn.svelte +17 -2
  26. package/dist/components/agent/CodeCard.svelte +9 -3
  27. package/dist/i18n/index.d.ts +1 -1
  28. package/dist/i18n/index.js +1 -1
  29. package/dist/i18n/messages.d.ts +52 -4
  30. package/dist/i18n/messages.js +58 -6
  31. package/dist/i18n/suggestions.d.ts +17 -2
  32. package/dist/i18n/suggestions.js +11 -12
  33. package/dist/services/index.d.ts +4 -2
  34. package/dist/services/index.js +2 -1
  35. package/dist/services/limitRefusal.d.ts +42 -0
  36. package/dist/services/limitRefusal.js +60 -0
  37. package/dist/services/sketchAssistantClient.d.ts +11 -3
  38. package/dist/services/sketchAssistantClient.js +37 -10
  39. package/dist/services/sketchAssistantErrors.d.ts +16 -1
  40. package/dist/services/sketchAssistantErrors.js +25 -4
  41. package/dist/services/sketchAssistantOrchestrator.d.ts +7 -1
  42. package/dist/services/sketchAssistantOrchestrator.js +2 -2
  43. package/dist/types/attachment.d.ts +11 -0
  44. package/dist/utils/agentTurn.d.ts +32 -1
  45. package/dist/utils/agentTurn.js +46 -3
  46. package/dist/utils/attachmentDuplicates.d.ts +48 -0
  47. package/dist/utils/attachmentDuplicates.js +70 -0
  48. package/dist/utils/attachmentPolicy.d.ts +88 -0
  49. package/dist/utils/attachmentPolicy.js +135 -0
  50. package/dist/utils/attachmentPreview.d.ts +146 -0
  51. package/dist/utils/attachmentPreview.js +224 -0
  52. package/dist/utils/attachmentTray.d.ts +35 -0
  53. package/dist/utils/attachmentTray.js +27 -0
  54. package/dist/utils/chatFileDrag.d.ts +39 -0
  55. package/dist/utils/chatFileDrag.js +29 -0
  56. package/dist/utils/composerPreview.d.ts +33 -0
  57. package/dist/utils/composerPreview.js +31 -0
  58. package/dist/utils/generationArchiveStore.d.ts +5 -1
  59. package/dist/utils/generationArchiveStore.js +9 -4
  60. package/dist/utils/index.d.ts +1 -1
  61. package/dist/utils/index.js +1 -1
  62. package/dist/utils/limitFailureLine.d.ts +20 -0
  63. package/dist/utils/limitFailureLine.js +40 -0
  64. package/dist/utils/panelListPadding.d.ts +20 -0
  65. package/dist/utils/panelListPadding.js +31 -0
  66. package/dist/utils/pasteInsertion.d.ts +43 -0
  67. package/dist/utils/pasteInsertion.js +94 -0
  68. package/dist/utils/pastedContent.d.ts +13 -0
  69. package/dist/utils/pastedContent.js +18 -1
  70. package/dist/utils/referenceItems.js +11 -3
  71. package/dist/utils/sentAttachments.d.ts +43 -0
  72. package/dist/utils/sentAttachments.js +38 -0
  73. package/dist/utils/sentReferenceBadges.d.ts +11 -1
  74. package/dist/utils/sentReferenceBadges.js +47 -2
  75. 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)));
@@ -859,6 +923,10 @@
859
923
 
860
924
  if (loaded.length === 0) {
861
925
  // chatLog('[Chat] No existing conversations, creating new one');
926
+ // The list is empty, so the empty state (title and suggestions) is known to be right: it does not wait for the
927
+ // conversation to be made (a request of its own). A message sent in that moment waits for `initializePromise`
928
+ // in `sendMessageAndReport`; a conversation that could not be made takes it away again (the `finally` below).
929
+ showEmptyState = true;
862
930
  await createNewConversation();
863
931
  } else {
864
932
  // chatLog('[Chat] Selecting from', loaded.length, 'conversation(s)');
@@ -1441,12 +1509,12 @@
1441
1509
  // The label the message can call the screenshot by (`#Image_1`), given in the same breath as it joins the tray
1442
1510
  labelNewAttachments([attachmentInput]);
1443
1511
 
1512
+ const previousTileCount = countTrayTiles();
1444
1513
  localAttachments = [...localAttachments, attachmentInput];
1445
- const attachmentIndex = localAttachments.length - 1;
1446
1514
  notifyDraftChange();
1447
- expandChatForAttachmentGrowth(attachmentIndex);
1515
+ expandChatForAttachmentGrowth(previousTileCount);
1448
1516
  chatStore.actions.updateUI({ errorMessage: null });
1449
- console.log('[Chat] attachments now', localAttachments.length);
1517
+ // console.log('[Chat] attachments now', localAttachments.length);
1450
1518
 
1451
1519
  if (onUploadChatFile) {
1452
1520
  await uploadAttachmentToCdn(screenshotFile, attachmentInput, {
@@ -1499,7 +1567,7 @@
1499
1567
 
1500
1568
  // Add to attachments
1501
1569
  localAttachments = [...localAttachments, attachmentInput];
1502
- console.log('[Chat] attachments now', localAttachments.length);
1570
+ // console.log('[Chat] attachments now', localAttachments.length);
1503
1571
 
1504
1572
  // chatLog('Recording stopped and added to attachments');
1505
1573
 
@@ -1588,7 +1656,9 @@
1588
1656
  }
1589
1657
 
1590
1658
  function expandChatForAttachmentGrowth(previousCount: number) {
1591
- 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;
1592
1662
 
1593
1663
  // When the first attachment appears, free space in a fixed messages area so the footer tray stays visible.
1594
1664
  if (previousCount === 0 && messagesAreaHeight !== null) {
@@ -1598,7 +1668,7 @@
1598
1668
  if (!resizeExpandsContainer) return;
1599
1669
  // Grow the fixed-height host once per net attachment increase so the tray is not clipped.
1600
1670
  onMessagesResize?.(120);
1601
- chatLog('[Chat] Expanded chat host for attachments:', previousCount, '→', localAttachments.length);
1671
+ chatLog('[Chat] Expanded chat host for attachments:', previousCount, '→', tileCount);
1602
1672
  }
1603
1673
 
1604
1674
  function isImageAttachment(attachment: AttachmentInput): boolean {
@@ -1642,7 +1712,48 @@
1642
1712
  chatLog('[Chat] Removed footer attachment at index:', index);
1643
1713
  }
1644
1714
 
1645
- 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
+ }
1646
1757
 
1647
1758
  /** Biggest image kept in the draft: a draft is written to the browser's storage on every change. */
1648
1759
  const MAX_PERSISTED_IMAGE_BYTES = 6 * 1024 * 1024;
@@ -1680,25 +1791,137 @@
1680
1791
  }
1681
1792
 
1682
1793
  /**
1683
- * Attaches files to the message being written: the ones dropped on the box, picked with "+", or pasted into it. A file may
1684
- * 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
1685
- * first and the files are uploaded after, one by one; `onTilesAdded` is called between the two, so a caller that keeps a
1686
- * 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.
1687
1908
  */
1688
1909
  async function attachFiles(
1689
- entries: Array<{ file: File; label?: string }>,
1690
- options: { onTilesAdded?: () => void } = {},
1910
+ entries: Array<ArrivingFile & { fingerprint?: string }>,
1911
+ options: { onTilesAdded?: (addedAttachments: AttachmentInput[]) => void } = {},
1691
1912
  ) {
1692
1913
  const usableEntries = (entries || []).filter(({ file }) => file && file.size > 0);
1693
1914
  if (usableEntries.length === 0) return;
1694
1915
 
1695
- const previousCount = localAttachments.length;
1696
- const newAttachments: AttachmentInput[] = usableEntries.map(({ file, label }) => ({
1916
+ const previousTileCount = countTrayTiles();
1917
+ const newAttachments: AttachmentInput[] = usableEntries.map(({ file, label, excerpt, fingerprint }) => ({
1697
1918
  // Tells the tiles apart while the tray shows them (two pasted screenshots are both "image.png"), and is how the upload
1698
1919
  // finds its tile again while other uploads run: see `updateAttachment`.
1699
1920
  id: generateFileId(),
1700
1921
  file,
1701
1922
  label,
1923
+ excerpt,
1924
+ fingerprint,
1702
1925
  type: file.type.startsWith('image/')
1703
1926
  ? 'image'
1704
1927
  : file.type.startsWith('video/')
@@ -1712,13 +1935,13 @@
1712
1935
  labelNewAttachments(newAttachments);
1713
1936
  localAttachments = [...localAttachments, ...newAttachments];
1714
1937
  notifyDraftChange();
1715
- expandChatForAttachmentGrowth(previousCount);
1938
+ expandChatForAttachmentGrowth(previousTileCount);
1716
1939
  chatStore.actions.updateUI({ errorMessage: null });
1717
- console.log('[Chat] attachments now', localAttachments.length);
1940
+ // console.log('[Chat] attachments now', localAttachments.length);
1718
1941
  // The draft keeps each picture as it is attached, before the upload ends (a refresh can come at any time).
1719
1942
  for (const entry of newAttachments) void rememberImageForDraft(entry);
1720
1943
  // Everything the next paste has to see is in the tray now; the uploads below are not waited for.
1721
- options.onTilesAdded?.();
1944
+ options.onTilesAdded?.(newAttachments);
1722
1945
 
1723
1946
  try {
1724
1947
  localIsUploading = true;
@@ -1733,18 +1956,126 @@
1733
1956
  }
1734
1957
 
1735
1958
  /**
1736
- * The files dropped on the box or picked with "+". A picture is made smaller first when it is large (see
1737
- * `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.
1738
1963
  */
1739
1964
  async function addFilesAsAttachments(files: File[]) {
1740
- const incoming = (files || []).filter((file) => file && file.size > 0);
1965
+ const incoming = Array.from(files || []).filter((file) => !!file);
1741
1966
  if (incoming.length === 0) return;
1742
- const usableFiles = await Promise.all(
1743
- incoming.map(async (file) =>
1744
- file.type.startsWith('image/') ? await prepareChatImageFileForUpload(file) : file,
1745
- ),
1746
- );
1747
- 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
+ }
1748
2079
  }
1749
2080
 
1750
2081
  /**
@@ -1756,31 +2087,118 @@
1756
2087
  */
1757
2088
  const pasteTileLine = createOrderedLine();
1758
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
+
1759
2125
  /**
1760
2126
  * What a paste into the box brought in (see `attachmentsFromPaste`): a screenshot or a file, or a long text as a text file.
1761
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
1762
- * (see `prepareImagesOfPaste`). The tile of a pasted text says its first words, not "pasted-text.txt". Every paste is an
1763
- * attachment of its own, with a name of its own among the files already in the tray: two screenshots are both "image.png"
1764
- * and two texts both "pasted-text.txt", and the builder names the text files it reads (and the person is told which it
1765
- * 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`).
1766
2134
  */
1767
- async function addPastedAttachments(pastedAttachments: PastedAttachment[]) {
1768
- // 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;
1769
2139
  const placeInLine = pasteTileLine.takePlace();
2140
+ let heldFingerprints: string[] = [];
1770
2141
  try {
1771
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
+
1772
2162
  // Preparing is done by all the pastes at once; only the tiles wait for their place.
1773
- const preparedAttachments = await prepareImagesOfPaste(pastedAttachments, prepareChatImageFileForUpload);
2163
+ const preparedAttachments = await prepareImagesOfPaste(fresh, prepareChatImageFileForUpload);
1774
2164
  await placeInLine.untilReached;
1775
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.
1776
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
+ }
1777
2184
  // The place is left as soon as the tiles are in the tray, not when the uploads end: they run side by side.
1778
- 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
+ });
1779
2196
  } catch (error) {
1780
2197
  console.error('[Chat] Could not attach the pasted content:', error);
1781
2198
  } finally {
1782
2199
  // The next paste's tiles may come now, even when this one could not be attached (leaving a second time changes nothing).
1783
2200
  placeInLine.leave();
2201
+ releaseFingerprints(heldFingerprints);
1784
2202
  }
1785
2203
  }
1786
2204
 
@@ -1790,7 +2208,8 @@
1790
2208
  const fileInput = document.createElement('input');
1791
2209
  fileInput.type = 'file';
1792
2210
  fileInput.multiple = true;
1793
- 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;
1794
2213
 
1795
2214
  fileInput.onchange = async (event) => {
1796
2215
  const files = Array.from((event.target as HTMLInputElement).files || []);
@@ -1848,8 +2267,13 @@
1848
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. */
1849
2268
  const mentionLinkHints = $derived(findMentionLinkHints(localInputText, mentionSources, localMentions, mentionLimit));
1850
2269
 
1851
- /** 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. */
1852
- 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
+ );
1853
2277
 
1854
2278
  function addMentionPick(mention: ComposerMention) {
1855
2279
  localMentions = addMention(localMentions, mention, mentionLimit);
@@ -2047,7 +2471,7 @@
2047
2471
  file_name: attachment.file_name || attachment.fileName || 'design-screenshot.png',
2048
2472
  file_size: attachment.file_size ?? attachment.fileSize,
2049
2473
  }));
2050
- console.log('[Chat] Restore echo attachments', restoredAttachments.length);
2474
+ // console.log('[Chat] Restore echo attachments', restoredAttachments.length);
2051
2475
  addUserMessage(promptCopy, restoredAttachments.length ? restoredAttachments : undefined);
2052
2476
  addAssistantMessage(`Restored from ${sourceLabel}\n\nCommit: ${newSha.slice(0, 8)}`);
2053
2477
  }
@@ -2100,6 +2524,7 @@
2100
2524
  const mimeMatch = dataUrl.match(/data:(image\/[^;]+);/);
2101
2525
  const mimeType = mimeMatch?.[1] || blob.type || 'image/png';
2102
2526
  const handedOverFile = new File([blob], fileName, { type: mimeType });
2527
+ const pictureFingerprint = await fingerprintFile(handedOverFile);
2103
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
2104
2529
  // `prepareImageWithTimeLimit`: a picture that never gets ready must not hold up the pastes after it); a large one comes
2105
2530
  // back smaller, under a new name.
@@ -2125,13 +2550,15 @@
2125
2550
  // The tile keeps drawing this `data:` URL, and the draft keeps it too: the stored address that comes when the upload
2126
2551
  // ends is only the picture's second choice (see `readAttachmentPreviewUrl`).
2127
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,
2128
2555
  uploadProgress: 0,
2129
2556
  };
2130
2557
  labelNewAttachments([attachmentInput], [forcedLabel]);
2131
- const attachmentIndex = localAttachments.length;
2558
+ const previousTileCount = countTrayTiles();
2132
2559
  localAttachments = [...localAttachments, attachmentInput];
2133
2560
  notifyDraftChange();
2134
- expandChatForAttachmentGrowth(attachmentIndex);
2561
+ expandChatForAttachmentGrowth(previousTileCount);
2135
2562
  } catch (err) {
2136
2563
  console.error('[Chat] Failed to add image attachment:', err);
2137
2564
  } finally {
@@ -2299,8 +2726,8 @@
2299
2726
  const queuedMessage: QueuedMessage = {
2300
2727
  id: createQueuedMessageId(),
2301
2728
  text: trimmed,
2302
- // The files move with the message: they are not given back, they belong to the queue now
2303
- 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),
2304
2731
  chipIntent: pendingChipIntent ?? undefined,
2305
2732
  skipIntentGate: pendingSkipIntentGate,
2306
2733
  };
@@ -2993,11 +3420,54 @@
2993
3420
  }
2994
3421
  </script>
2995
3422
 
3423
+ <!--
3424
+ The action bar, drawn only when something is left for it to hold. The plain chat keeps it in the footer, above the message
3425
+ box. The docked panel keeps it under its header (`atTop`): its footer is the message box and what belongs to it, so the
3426
+ suggestions of an empty chat (and "Try next" under a reply) touch the message box, with no bar of options between them.
3427
+ -->
3428
+ {#snippet actionBarView(atTop: boolean)}
3429
+ {#if showActionBar}
3430
+ <ActionBar
3431
+ {context}
3432
+ {atTop}
3433
+ conversationId={currentConversationId}
3434
+ isRecording={localIsRecording}
3435
+ isCompleted={isCompleted}
3436
+ disabled={isLoading}
3437
+ showScreenshot={config?.features?.screenshot !== false}
3438
+ showRecord={config?.features?.screenRecording !== false}
3439
+ showUpload={false}
3440
+ {showSelector}
3441
+ {isSelectorActive}
3442
+ showComplete={config?.features?.markComplete !== false}
3443
+ onScreenshot={() => void handleScreenshot()}
3444
+ onUpload={() => void handleUpload()}
3445
+ onToggleSelector={(active) => onToggleSelector?.(active)}
3446
+ onRecordStart={() => void handleRecordStart()}
3447
+ onRecordStop={() => void handleRecordStop()}
3448
+ onComplete={(detail) => void handleComplete(detail)}
3449
+ onError={handleActionError}
3450
+ {completeReplacement}
3451
+ {replaceComplete}
3452
+ >
3453
+ {#if actionBarExtras}
3454
+ {@render actionBarExtras()}
3455
+ {/if}
3456
+ </ActionBar>
3457
+ {/if}
3458
+ {/snippet}
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 -->
2996
3462
  <div
2997
3463
  bind:this={chatContainer}
2998
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'}"
2999
3465
  dir={$textDirection}
3000
3466
  style={style}
3467
+ ondragenter={handleChatFileDrag}
3468
+ ondragover={handleChatFileDrag}
3469
+ ondragleave={handleChatFileDragLeave}
3470
+ ondrop={handleChatFileDrop}
3001
3471
  >
3002
3472
  {#if showPanelHeader}
3003
3473
  {@const panelTitle =
@@ -3045,6 +3515,10 @@
3045
3515
  </div>
3046
3516
  {/if}
3047
3517
 
3518
+ {#if showPanelHeader}
3519
+ {@render actionBarView(true)}
3520
+ {/if}
3521
+
3048
3522
  <!-- Chat Interface -->
3049
3523
  <div
3050
3524
  class="prompt-chat-messages-area flex min-h-0 flex-col overflow-hidden {showPanelHeader ? 'flex-1' : ''}"
@@ -3057,7 +3531,7 @@
3057
3531
  messages={currentMessages || []}
3058
3532
  isLoading={isLoading}
3059
3533
  isInitialized={isInitialized}
3060
- showEmptyState={showEmptyState && localAttachments.length === 0}
3534
+ showEmptyState={showEmptyState && !composerHasTiles}
3061
3535
  panelLayout={showPanelHeader}
3062
3536
  {context}
3063
3537
  isCompleted={isCompleted}
@@ -3076,6 +3550,7 @@
3076
3550
  generationPlan={isGenerating ? generationPlan : null}
3077
3551
  generationPlanPending={isGenerating ? generationPlanPending : false}
3078
3552
  {generationChanges}
3553
+ {generationSummary}
3079
3554
  onSuggestionSelected={handleSuggestionSelected}
3080
3555
  draftText={localInputText}
3081
3556
  onRestoreCheckpoint={onRestoreCheckpointBackend ? handleRestoreCheckpoint : undefined}
@@ -3117,33 +3592,8 @@
3117
3592
  <div
3118
3593
  class="prompt-chat-footer-ct shrink-0 flex flex-col {showPanelHeader ? 'px-3 pb-4 max-lg:px-3' : ''}"
3119
3594
  >
3120
- {#if showActionBar}
3121
- <ActionBar
3122
- {context}
3123
- conversationId={currentConversationId}
3124
- isRecording={localIsRecording}
3125
- isCompleted={isCompleted}
3126
- disabled={isLoading}
3127
- showScreenshot={config?.features?.screenshot !== false}
3128
- showRecord={config?.features?.screenRecording !== false}
3129
- showUpload={false}
3130
- {showSelector}
3131
- {isSelectorActive}
3132
- showComplete={config?.features?.markComplete !== false}
3133
- onScreenshot={() => void handleScreenshot()}
3134
- onUpload={() => void handleUpload()}
3135
- onToggleSelector={(active) => onToggleSelector?.(active)}
3136
- onRecordStart={() => void handleRecordStart()}
3137
- onRecordStop={() => void handleRecordStop()}
3138
- onComplete={(detail) => void handleComplete(detail)}
3139
- onError={handleActionError}
3140
- {completeReplacement}
3141
- {replaceComplete}
3142
- >
3143
- {#if actionBarExtras}
3144
- {@render actionBarExtras()}
3145
- {/if}
3146
- </ActionBar>
3595
+ {#if !showPanelHeader}
3596
+ {@render actionBarView(false)}
3147
3597
  {/if}
3148
3598
  {#if composerExtras}
3149
3599
  <div class="prompt-chat-generation-options shrink-0 flex flex-col" bind:this={generationOptionsEl}>
@@ -3165,19 +3615,6 @@
3165
3615
  </div>
3166
3616
  {/if}
3167
3617
 
3168
- {#if localAttachments.length > 0}
3169
- <ComposerAttachmentsTray
3170
- attachments={localAttachments}
3171
- previewUrl={getFooterAttachmentPreviewUrl}
3172
- isImage={isImageAttachment}
3173
- highlightedLabel={highlightedReferenceLabel}
3174
- onRemove={removeFooterAttachment}
3175
- onOpenPreview={(url) => {
3176
- footerLightboxSrc = url;
3177
- }}
3178
- />
3179
- {/if}
3180
-
3181
3618
  <!--
3182
3619
  The parts the person picked on the preview, as chips inside the message box (Figma: Selecting elements, frames 2 to 4).
3183
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
@@ -3224,9 +3661,23 @@
3224
3661
  {#if selectedElements && selectedElements.length > 0}
3225
3662
  {@render selectedElementChips()}
3226
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}
3227
3677
  {/snippet}
3228
3678
 
3229
3679
  <ChatComposer
3680
+ bind:this={composerHandle}
3230
3681
  {sendNudgeToken}
3231
3682
  {completion}
3232
3683
  {referenceItems}
@@ -3265,45 +3716,29 @@
3265
3716
  const attachmentInputs = localAttachments.length > 0 ? localAttachments : undefined;
3266
3717
  handleComposerSend(content, attachmentInputs, sendOptions);
3267
3718
  }}
3268
- onFilesDropped={(files) => {
3269
- void addFilesAsAttachments(files);
3270
- }}
3271
3719
  onFilesPasted={config?.features?.fileUpload !== false
3272
- ? (pastedAttachments) => void addPastedAttachments(pastedAttachments)
3720
+ ? (pastedAttachments, selection) => void addPastedAttachments(pastedAttachments, selection)
3273
3721
  : undefined}
3274
3722
  onAttach={config?.features?.fileUpload !== false ? () => void handleUpload() : undefined}
3275
3723
  canSendWithoutText={(selectedElements ?? []).some((element) => !!element.note?.trim())}
3276
3724
  />
3277
3725
  </div>
3278
3726
 
3279
- {#if footerLightboxSrc}
3280
- <!-- svelte-ignore a11y_click_events_have_key_events -->
3281
- <!-- svelte-ignore a11y_no_static_element_interactions -->
3282
- <div
3283
- class="prompt-chat-footer-lightbox-overlay fixed inset-0 z-[9999] flex items-center justify-center bg-black/85"
3284
- onclick={() => (footerLightboxSrc = null)}
3285
- >
3286
- <button
3287
- type="button"
3288
- 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"
3289
- onclick={() => (footerLightboxSrc = null)}
3290
- title={$t('chat.attachment.close')}
3291
- aria-label={$t('chat.attachment.close')}
3292
- >
3293
- ✕
3294
- </button>
3295
- <!-- svelte-ignore a11y_click_events_have_key_events -->
3296
- <!-- svelte-ignore a11y_no_static_element_interactions -->
3297
- <div class="prompt-chat-footer-lightbox-content max-w-[90vw] max-h-[90vh]" onclick={(e) => e.stopPropagation()}>
3298
- <img
3299
- src={footerLightboxSrc}
3300
- alt={$t('chat.attachment.previewAlt')}
3301
- class="prompt-chat-footer-lightbox-image max-w-[90vw] max-h-[85vh] object-contain rounded-lg"
3302
- />
3303
- </div>
3304
- </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
+ />
3305
3737
  {/if}
3306
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
+
3307
3742
  <!-- Error Display -->
3308
3743
  {#if ui?.errorMessage}
3309
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">