Open History to see the last commit
1import { msg } from "gt-react";
2import { m } from "~/i18n/messages";
3import type { ChatComposerProps } from "./ChatComposer";
4import {
5 type ChatFileAttachment,
6 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
7 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
8 PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
9} from "@t3tools/contracts";
10import {
11 type ComposerContextReference,
12 collectInlineContextIds,
13 stripInlineContextReferences,
14} from "~/lib/composerContextReferences";
15import {
16 type ComposerFileAttachment,
17 type ComposerImageAttachment,
18 type DraftId,
19 composerFileMatchesReattachMarker,
20 composerFileNeedsReattach,
21 composerTargetKey,
22 useComposerDraftStore,
23} from "../../composerDraftStore";
24import { type ComposerPromptEditorHandle } from "../ComposerPromptEditorTiptap";
25import type { PendingUserInputProgress } from "../../pendingUserInput";
26import type { ComposerAttachmentInsertion } from "../composerAttachmentInsertion";
27import { type PendingUserInput } from "../../session-logic";
28import { changeQuestionAttachmentPreparation } from "../../questionAttachments";
29import {
30 classifyComposerAttachmentFile,
31 composerFileAttachmentMimeType,
32 composerImageSourceKey,
33 readComposerImageBytes,
34 normalizeComposerImageFileMimeType,
35 rememberComposerImageSource,
36} from "./composerAttachmentFiles";
37import {
38 fileAttachmentTooLargeMessage,
39 formatAttachmentSize,
40} from "@t3tools/client-runtime/state/attachments";
41import { fileContextReference, imageContextReference } from "~/lib/composerContextRecords";
42import { isMacPlatform, randomUUID } from "~/lib/utils";
43import {
44 nextPastedTextFileName,
45 pastedTextDisposition,
46 wouldTextPasteExceedLimit,
47} from "@t3tools/client-runtime/text-paste";
48import {
49 inheritComposerImageThumbnail,
50 prepareImageForAttachment,
51} from "../../lib/imageCompression";
52import { requestConfirmDialog } from "~/confirmDialog";
53import { toastManager } from "../ui/toast";
54import { type RefObject, useRef } from "react";
55import { serializeComposerImages } from "./composerImagePersistence";
56import {
57 addPreparingComposerImages,
58 getPreparingComposerImages,
59 isPreparingComposerImage,
60 joinPreparedImagesToDraft,
61 movedPreparingImageThread,
62 removePreparingComposerImages,
63} from "./preparingComposerImages";
64
65/**
66 * Takes files into the draft: validates and reserves slots, compresses images, inserts
67 * their inline chips, folds large pastes into text attachments, and confirms removing a referenced image.
68 */
69export function useComposerAttachmentIntake(input: {
70 readonly activeThreadId: ChatComposerProps["activeThreadId"];
71 readonly activePendingProgress: PendingUserInputProgress | null;
72 readonly activePendingIsResponding: boolean;
73 readonly pendingUserInputs: ReadonlyArray<PendingUserInput>;
74 readonly supportsQuestionAttachments: boolean;
75 readonly isLiteralPendingAnswer: boolean;
76 readonly projectSelectionRequired: boolean;
77 readonly questionAttachmentTarget: DraftId | null;
78 readonly attachmentTargetKey: string;
79 readonly fileStagingLimit: number | null;
80 readonly promptRef: ChatComposerProps["promptRef"];
81 readonly composerImagesRef: ChatComposerProps["composerImagesRef"];
82 readonly composerFilesRef: ChatComposerProps["composerFilesRef"];
83 readonly composerEditorRef: RefObject<ComposerPromptEditorHandle | null>;
84 readonly isRevertingCheckpointRef: RefObject<boolean>;
85 readonly setThreadError: ChatComposerProps["setThreadError"];
86 readonly countReservedAttachments: () => number;
87 readonly addComposerImage: (image: ComposerImageAttachment) => string[];
88 readonly addComposerImagesToDraft: (images: ComposerImageAttachment[]) => string[];
89 readonly addComposerFilesToDraft: (files: ComposerFileAttachment[]) => string[];
90 readonly removeComposerImageFromDraft: (imageId: string) => void;
91 readonly insertAttachmentReferences: (
92 references: ReadonlyArray<ComposerContextReference>,
93 selection?: { start: number; end: number },
94 pendingInsertion?: ComposerAttachmentInsertion,
95 ) => boolean;
96}) {
97 const {
98 activeThreadId,
99 activePendingProgress,
100 activePendingIsResponding,
101 pendingUserInputs,
102 supportsQuestionAttachments,
103 isLiteralPendingAnswer,
104 projectSelectionRequired,
105 questionAttachmentTarget,
106 attachmentTargetKey,
107 fileStagingLimit,
108 promptRef,
109 composerImagesRef,
110 composerFilesRef,
111 composerEditorRef,
112 isRevertingCheckpointRef,
113 setThreadError,
114 countReservedAttachments,
115 addComposerImage,
116 addComposerImagesToDraft,
117 addComposerFilesToDraft,
118 removeComposerImageFromDraft,
119 insertAttachmentReferences,
120 } = input;
121 const pastedTextFileNamesRef = useRef<{ targetKey: string; names: Set<string> }>({
122 targetKey: "",
123 names: new Set(),
124 });
125
126 const addComposerAttachments = async (
127 files: File[],
128 options?: {
129 readonly source?: ChatFileAttachment["source"];
130 readonly selection?: { start: number; end: number };
131 readonly skipImageInlineChip?: boolean;
132 },
133 ): Promise<boolean> => {
134 if (!activeThreadId || files.length === 0 || isRevertingCheckpointRef.current) return false;
135 if (
136 pendingUserInputs.length > 0 &&
137 (!supportsQuestionAttachments ||
138 activePendingProgress?.activeQuestion?.allowCustomAnswer === false ||
139 activePendingIsResponding)
140 ) {
141 toastManager.add({
142 type: "error",
143 title: m(msg("This question cannot accept attachments.")),
144 });
145 return false;
146 }
147 // Captured before the awaits below: the user may switch threads while a
148 // large image is being compressed, and the attachments and errors belong
149 // to the thread the paste happened in.
150 const threadId = activeThreadId;
151 const imageAttachmentsGetChips =
152 !options?.skipImageInlineChip &&
153 (options?.selection !== undefined ||
154 pendingUserInputs.length > 0 ||
155 projectSelectionRequired ||
156 stripInlineContextReferences(promptRef.current).trim().length > 0);
157
158 // Validation happens synchronously so concurrent pastes see each other:
159 // accepted files reserve their attachment slots (as preparing images)
160 // before the first await, keeping the total under the limit.
161 let reservedCount = countReservedAttachments();
162 // A pick that matches a needs-reattach marker replaces it in the draft, so
163 // it must not consume a slot; a draft full of markers would otherwise hit
164 // the capacity error before the replacement path could run.
165 const reattachMarkers = composerFilesRef.current.filter(composerFileNeedsReattach);
166 const replacedReattachMarkerIds = new Set<string>();
167 const acceptedImages: File[] = [];
168 const acceptedFiles: ComposerFileAttachment[] = [];
169 let error: string | null = null;
170 for (const file of files) {
171 const attachmentKind = classifyComposerAttachmentFile(file);
172 const fileMimeType =
173 attachmentKind === "file" ? composerFileAttachmentMimeType(file) : file.type;
174 const matchingReattachMarker =
175 attachmentKind === "file"
176 ? reattachMarkers.find(
177 (marker) =>
178 !replacedReattachMarkerIds.has(marker.id) &&
179 composerFileMatchesReattachMarker(marker, {
180 name: file.name || "file",
181 mimeType: fileMimeType,
182 sizeBytes: file.size,
183 }),
184 )
185 : undefined;
186 if (matchingReattachMarker) {
187 replacedReattachMarkerIds.add(matchingReattachMarker.id);
188 }
189 if (!matchingReattachMarker && reservedCount >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
190 error = m(
191 msg("You can attach up to {max} files per message.", {
192 max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
193 }),
194 );
195 continue;
196 }
197 if (attachmentKind === "unsupported-image") {
198 error = m(
199 msg(
200 "''{name}'' is not a supported image type. Attach GIF, HEIC, HEIF, JPEG, PNG, or WebP images.",
201 { name: file.name },
202 ),
203 );
204 continue;
205 }
206 if (attachmentKind === "image") {
207 acceptedImages.push(normalizeComposerImageFileMimeType(file));
208 } else {
209 if (fileStagingLimit === null) {
210 error = m(msg("This server does not support file attachments."));
211 continue;
212 }
213 if (file.size <= 0) {
214 error = m(msg("''{name}'' is empty or could not be read.", { name: file.name }));
215 continue;
216 }
217 if (file.size > fileStagingLimit) {
218 error = fileAttachmentTooLargeMessage(file.name, fileStagingLimit, m);
219 continue;
220 }
221 const attachmentFile =
222 file.type === fileMimeType
223 ? file
224 : new File([file], file.name, { type: fileMimeType, lastModified: file.lastModified });
225 acceptedFiles.push({
226 type: "file",
227 id: randomUUID(),
228 name: attachmentFile.name || "file",
229 mimeType: fileMimeType,
230 sizeBytes: attachmentFile.size,
231 file: attachmentFile,
232 ...(options?.source ? { source: options.source } : {}),
233 });
234 }
235 if (!matchingReattachMarker) {
236 reservedCount += 1;
237 }
238 }
239 setThreadError(threadId, error);
240 let insertedAny = false;
241 if (acceptedFiles.length > 0) {
242 const storedIds = new Set(addComposerFilesToDraft(acceptedFiles));
243 const storedFiles = acceptedFiles.filter((file) => storedIds.has(file.id));
244 if (storedFiles.length > 0) {
245 insertedAny = insertAttachmentReferences(
246 storedFiles.map(fileContextReference),
247 options?.selection,
248 );
249 }
250 if (options?.source?._tag === "pasted-text" && storedFiles.length > 0) {
251 const attached = storedFiles[0]!;
252 toastManager.add({
253 type: "info",
254 title: m(msg("Large paste attached as {name}", { name: attached.name })),
255 description: m(
256 msg("{size} · Use {shortcut} to keep a large paste inline.", {
257 size: formatAttachmentSize(attached.sizeBytes, m),
258 shortcut: isMacPlatform(navigator.platform) ? "⌘⇧V" : "Ctrl+Shift+V",
259 }),
260 ),
261 data: { hideCopyButton: true },
262 });
263 }
264 }
265 if (acceptedImages.length === 0) return insertedAny;
266
267 // The store drops a repeated image only after compressing it, so a likely repeat prepares
268 // without a tile instead of flashing one. Only the store decides it is a duplicate.
269 const imageSourceKeys = new Set(
270 [...composerImagesRef.current, ...getPreparingComposerImages(attachmentTargetKey)].map(
271 (image) => composerImageSourceKey(image.file),
272 ),
273 );
274 // The draft image reuses its placeholder's id and thumbnail so the strip tile stays exactly
275 // as it is when the compressed file replaces it.
276 const preparingImages = acceptedImages.map((file) => {
277 const sourceKey = composerImageSourceKey(file);
278 const hidden = imageSourceKeys.has(sourceKey);
279 imageSourceKeys.add(sourceKey);
280 return { id: randomUUID(), name: file.name || "image", file, hidden };
281 });
282 addPreparingComposerImages(attachmentTargetKey, preparingImages);
283 if (questionAttachmentTarget)
284 changeQuestionAttachmentPreparation(questionAttachmentTarget, acceptedImages.length);
285 const compressed: { id: string; file: File }[] = [];
286 // Keyed by image so a failure whose tile was removed (even mid-compression) is not reported.
287 const compressionErrors = new Map<string, string>();
288 const pendingInsertion = imageAttachmentsGetChips
289 ? composerEditorRef.current?.captureAttachmentInsertion()
290 : undefined;
291 for (const image of preparingImages) {
292 const { id, file } = image;
293 const movedThread = movedPreparingImageThread(image);
294 // Removed from the strip while an earlier image was compressing.
295 if (
296 !isPreparingComposerImage(
297 movedThread ? composerTargetKey(movedThread) : attachmentTargetKey,
298 id,
299 )
300 )
301 continue;
302 // A rejection must still reach the cleanup below: a leaked
303 // placeholder would block sending from this draft for good.
304 const result = await prepareImageForAttachment(
305 file,
306 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
307 ).catch(() => ({ ok: false, reason: "unreadable" }) as const);
308 if (!result.ok) {
309 compressionErrors.set(
310 id,
311 result.reason === "unreadable"
312 ? m(msg("''{name}'' could not be read as an image.", { name: file.name }))
313 : m(
314 msg("''{name}'' is too large to attach, even after compression.", {
315 name: file.name,
316 }),
317 ),
318 );
319 continue;
320 }
321 await inheritComposerImageThumbnail(file, result.file);
322 await readComposerImageBytes(result.file);
323 rememberComposerImageSource(file, result.file);
324 compressed.push({ id, file: result.file });
325 }
326 pendingInsertion?.dispose();
327 const movedThread = preparingImages.map(movedPreparingImageThread).find(Boolean);
328 const completionTargetKey = movedThread ? composerTargetKey(movedThread) : attachmentTargetKey;
329 const nextImages: ComposerImageAttachment[] = compressed
330 .filter(({ id }) => isPreparingComposerImage(completionTargetKey, id))
331 .map(({ id, file }) => ({
332 type: "image",
333 id,
334 name: file.name || "image",
335 mimeType: file.type,
336 sizeBytes: file.size,
337 previewUrl: URL.createObjectURL(file),
338 file,
339 }));
340 const unrestoredImageNames: string[] = [];
341 const draftStore = useComposerDraftStore.getState();
342 const storedImageIds = joinPreparedImagesToDraft(
343 () =>
344 new Set(
345 movedThread
346 ? draftStore.addImages(movedThread, nextImages, {
347 onCapacityExceeded: (image) => unrestoredImageNames.push(image.name),
348 })
349 : nextImages.length === 1 && nextImages[0]
350 ? addComposerImage(nextImages[0])
351 : nextImages.length > 1
352 ? addComposerImagesToDraft(nextImages)
353 : [],
354 ),
355 );
356 // Keep the placeholders until the draft decides whether the recovered images fit,
357 // so a held send can be cancelled before the last placeholder disappears.
358 const stillPreparingIds = removePreparingComposerImages(
359 completionTargetKey,
360 new Set(preparingImages.map((image) => image.id)),
361 { cancelSubmission: compressionErrors.size > 0 || unrestoredImageNames.length > 0 },
362 );
363 if (questionAttachmentTarget && !movedThread)
364 changeQuestionAttachmentPreparation(questionAttachmentTarget, -stillPreparingIds.size);
365 const storedImages = nextImages.filter((image) => storedImageIds.has(image.id));
366 // The draft may be gone by now; revoking a URL the store already revoked is harmless.
367 for (const image of nextImages) {
368 if (!storedImageIds.has(image.id)) URL.revokeObjectURL(image.previewUrl);
369 }
370 if (storedImages.length > 0 && imageAttachmentsGetChips && !movedThread) {
371 insertedAny =
372 joinPreparedImagesToDraft(() =>
373 insertAttachmentReferences(
374 storedImages.map(imageContextReference),
375 undefined,
376 pendingInsertion,
377 ),
378 ) || insertedAny;
379 }
380 // Only failures are reported here. Success must not pass `null`: by
381 // now other work (a failed send, an overlapping paste) may have set a
382 // thread error this call knows nothing about, and clearing it would
383 // swallow that message.
384 const completionErrors = [...compressionErrors]
385 .filter(([id]) => stillPreparingIds.has(id))
386 .map(([, message]) => message)
387 .slice(-1);
388 if (unrestoredImageNames.length > 0) {
389 completionErrors.push(
390 m(
391 msg("{names} could not be restored: the composer is at its {limit}-attachment limit.", {
392 names: unrestoredImageNames.join(", "),
393 limit: PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
394 }),
395 ),
396 );
397 }
398 if (completionErrors.length > 0) {
399 setThreadError(threadId, completionErrors.join("\n"));
400 }
401 if (movedThread && storedImages.length > 0) {
402 const serialized = await serializeComposerImages(storedImages, []);
403 await draftStore.appendPersistedAttachments(movedThread, storedImages, serialized);
404 }
405 return insertedAny;
406 };
407
408 const removeComposerImage = (imageId: string) => {
409 if (
410 removePreparingComposerImages(attachmentTargetKey, new Set([imageId]), {
411 cancelSubmission: true,
412 }).size > 0
413 ) {
414 // Its compression finishes in the background and is dropped.
415 if (questionAttachmentTarget)
416 changeQuestionAttachmentPreparation(questionAttachmentTarget, -1);
417 return;
418 }
419 const image = composerImagesRef.current.find((candidate) => candidate.id === imageId);
420 const referenced = collectInlineContextIds(promptRef.current).includes(
421 image ? imageContextReference(image).contextId : "",
422 );
423 if (!referenced) {
424 removeComposerImageFromDraft(imageId);
425 return;
426 }
427 const confirmation = requestConfirmDialog(
428 image?.name != null
429 ? m(
430 msg(
431 "Remove {name} from the message?\nIt is referenced in your text; removing it also removes every reference.",
432 { name: image.name },
433 ),
434 )
435 : m(
436 msg(
437 "Remove this image from the message?\nIt is referenced in your text; removing it also removes every reference.",
438 ),
439 ),
440 { variant: "destructive" },
441 );
442 if (!confirmation) {
443 removeComposerImageFromDraft(imageId);
444 return;
445 }
446 void confirmation.then((confirmed) => {
447 if (confirmed) removeComposerImageFromDraft(imageId);
448 });
449 };
450
451 const foldPastedText = (
452 plainText: string,
453 bypassAutoAttachment: boolean,
454 selectionOverride?: { start: number; end: number },
455 ): boolean => {
456 if (isLiteralPendingAnswer) return false;
457 const questionCanAttach =
458 pendingUserInputs.length === 0 ||
459 (supportsQuestionAttachments &&
460 activePendingProgress?.activeQuestion?.allowCustomAnswer !== false &&
461 !activePendingIsResponding);
462 const hasAttachmentSlot = countReservedAttachments() < PROVIDER_SEND_TURN_MAX_ATTACHMENTS;
463 const selection = selectionOverride ?? composerEditorRef.current?.readSelectionRange();
464 const wouldExceedInputLimit = wouldTextPasteExceedLimit({
465 valueLength: promptRef.current.length,
466 selection: selection ?? { start: 0, end: 0 },
467 textLength: plainText.length,
468 maxLength: PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
469 });
470 const shouldFold =
471 pastedTextDisposition({
472 text: plainText,
473 bypassAutoAttachment,
474 wouldExceedInputLimit,
475 canAttach: true,
476 }) === "attachment";
477 if (!shouldFold) {
478 return false;
479 }
480
481 const canStageAttachment =
482 Boolean(activeThreadId) &&
483 !isRevertingCheckpointRef.current &&
484 questionCanAttach &&
485 hasAttachmentSlot;
486 if (!canStageAttachment || fileStagingLimit === null) {
487 if (!wouldExceedInputLimit) {
488 return false;
489 }
490 toastManager.add({
491 type: "error",
492 title: m(msg("Pasted text is too large for this message")),
493 description: m(msg("Remove some text or an attachment, then paste again.")),
494 data: { hideCopyButton: true },
495 });
496 return true;
497 }
498
499 if (pastedTextFileNamesRef.current.targetKey !== attachmentTargetKey) {
500 pastedTextFileNamesRef.current = { targetKey: attachmentTargetKey, names: new Set() };
501 }
502 const reservedNames = pastedTextFileNamesRef.current.names;
503 for (const file of composerFilesRef.current) reservedNames.add(file.name);
504 const foldedFileName = nextPastedTextFileName([...reservedNames]);
505 reservedNames.add(foldedFileName);
506 const foldedFile = new File([plainText], foldedFileName, {
507 type: "text/plain;charset=utf-8",
508 });
509 if (foldedFile.size > fileStagingLimit) {
510 reservedNames.delete(foldedFileName);
511 if (!wouldExceedInputLimit) return false;
512 toastManager.add({
513 type: "error",
514 title: m(msg("Pasted text is too large to attach")),
515 description: m(msg("Reduce the clipboard contents or save a smaller excerpt as a file.")),
516 data: { hideCopyButton: true },
517 });
518 return true;
519 }
520
521 void addComposerAttachments([foldedFile], {
522 source: { _tag: "pasted-text" },
523 ...(selection ? { selection } : {}),
524 });
525 return true;
526 };
527
528 return {
529 addComposerAttachments,
530 removeComposerImage,
531 foldPastedText,
532 };
533}