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