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