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