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 normalizeComposerImageFileMimeType,
29} from "./composerAttachmentFiles";
30import {
31 fileAttachmentTooLargeMessage,
32 formatAttachmentSize,
33} from "@t3tools/client-runtime/state/attachments";
34import { fileContextReference, imageContextReference } from "~/lib/composerContextRecords";
35import { isMacPlatform, randomUUID } from "~/lib/utils";
36import {
37 nextPastedTextFileName,
38 pastedTextDisposition,
39 wouldTextPasteExceedLimit,
40} from "@t3tools/client-runtime/text-paste";
41import {
42 inheritComposerImageThumbnail,
43 prepareImageForAttachment,
44} from "../../lib/imageCompression";
45import { requestConfirmDialog } from "~/confirmDialog";
46import { toastManager } from "../ui/toast";
47import { type RefObject, useRef } from "react";
48import { videoMimeType } from "../../types";
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"
166 ? (videoMimeType({ name: file.name, mimeType: file.type }) ??
167 (file.type || "application/octet-stream"))
168 : file.type;
169 const matchingReattachMarker =
170 attachmentKind === "file"
171 ? reattachMarkers.find(
172 (marker) =>
173 !replacedReattachMarkerIds.has(marker.id) &&
174 composerFileMatchesReattachMarker(marker, {
175 name: file.name || "file",
176 mimeType: fileMimeType,
177 sizeBytes: file.size,
178 }),
179 )
180 : undefined;
181 if (matchingReattachMarker) {
182 replacedReattachMarkerIds.add(matchingReattachMarker.id);
183 }
184 if (!matchingReattachMarker && reservedCount >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
185 error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`;
186 continue;
187 }
188 if (attachmentKind === "unsupported-image") {
189 error = `'${file.name}' is not a supported image type. Attach GIF, HEIC, HEIF, JPEG, PNG, or WebP images.`;
190 continue;
191 }
192 if (attachmentKind === "image") {
193 acceptedImages.push(normalizeComposerImageFileMimeType(file));
194 } else {
195 if (fileStagingLimit === null) {
196 error = "This server does not support file attachments.";
197 continue;
198 }
199 if (file.size <= 0) {
200 error = `'${file.name}' is empty or could not be read.`;
201 continue;
202 }
203 if (file.size > fileStagingLimit) {
204 error = fileAttachmentTooLargeMessage(file.name, fileStagingLimit);
205 continue;
206 }
207 const attachmentFile =
208 file.type === fileMimeType
209 ? file
210 : new File([file], file.name, { type: fileMimeType, lastModified: file.lastModified });
211 acceptedFiles.push({
212 type: "file",
213 id: randomUUID(),
214 name: attachmentFile.name || "file",
215 mimeType: fileMimeType,
216 sizeBytes: attachmentFile.size,
217 file: attachmentFile,
218 ...(options?.source ? { source: options.source } : {}),
219 });
220 }
221 if (!matchingReattachMarker) {
222 reservedCount += 1;
223 }
224 }
225 setThreadError(threadId, error);
226 let insertedAny = false;
227 if (acceptedFiles.length > 0) {
228 const storedIds = new Set(addComposerFilesToDraft(acceptedFiles));
229 const storedFiles = acceptedFiles.filter((file) => storedIds.has(file.id));
230 if (storedFiles.length > 0) {
231 insertedAny = insertAttachmentReferences(
232 storedFiles.map(fileContextReference),
233 options?.selection,
234 );
235 }
236 if (options?.source?._tag === "pasted-text" && storedFiles.length > 0) {
237 const attached = storedFiles[0]!;
238 toastManager.add({
239 type: "info",
240 title: `Large paste attached as ${attached.name}`,
241 description: `${formatAttachmentSize(attached.sizeBytes)} · Use ${
242 isMacPlatform(navigator.platform) ? "⌘⇧V" : "Ctrl+Shift+V"
243 } to keep a large paste inline.`,
244 data: { hideCopyButton: true },
245 });
246 }
247 }
248 if (acceptedImages.length === 0) return insertedAny;
249
250 // The draft image reuses its placeholder's id and thumbnail so the strip tile stays exactly
251 // as it is when the compressed file replaces it.
252 const preparingImages = acceptedImages.map((file) => ({
253 id: randomUUID(),
254 name: file.name || "image",
255 file,
256 }));
257 addPreparingComposerImages(attachmentTargetKey, preparingImages);
258 if (questionAttachmentTarget)
259 changeQuestionAttachmentPreparation(questionAttachmentTarget, acceptedImages.length);
260 const compressed: { id: string; file: File }[] = [];
261 // Keyed by image so a failure whose tile was removed (even mid-compression) is not reported.
262 const compressionErrors = new Map<string, string>();
263 for (const { id, file } of preparingImages) {
264 // Removed from the strip while an earlier image was compressing.
265 if (!isPreparingComposerImage(attachmentTargetKey, id)) continue;
266 // A rejection must still reach the cleanup below: a leaked
267 // placeholder would block sending from this draft for good.
268 const result = await prepareImageForAttachment(
269 file,
270 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
271 ).catch(() => ({ ok: false, reason: "unreadable" }) as const);
272 if (!result.ok) {
273 compressionErrors.set(
274 id,
275 result.reason === "unreadable"
276 ? `'${file.name}' could not be read as an image.`
277 : `'${file.name}' is too large to attach, even after compression.`,
278 );
279 continue;
280 }
281 inheritComposerImageThumbnail(file, result.file);
282 compressed.push({ id, file: result.file });
283 }
284 const questionDiscarded =
285 questionAttachmentTarget !== null &&
286 !useQuestionAttachmentPreparation.getState().counts[questionAttachmentTarget];
287 // Same tick as the draft insert below, so the strip swaps placeholders for
288 // real tiles in one render. A placeholder removed meanwhile stays removed.
289 const stillPreparingIds = removePreparingComposerImages(
290 attachmentTargetKey,
291 new Set(preparingImages.map((image) => image.id)),
292 );
293 if (questionAttachmentTarget)
294 changeQuestionAttachmentPreparation(questionAttachmentTarget, -stillPreparingIds.size);
295 if (questionDiscarded) return false;
296 const nextImages: ComposerImageAttachment[] = compressed
297 .filter(({ id }) => stillPreparingIds.has(id))
298 .map(({ id, file }) => ({
299 type: "image",
300 id,
301 name: file.name || "image",
302 mimeType: file.type,
303 sizeBytes: file.size,
304 previewUrl: URL.createObjectURL(file),
305 file,
306 }));
307 const storedImageIds = new Set(
308 nextImages.length === 1 && nextImages[0]
309 ? addComposerImage(nextImages[0])
310 : nextImages.length > 1
311 ? addComposerImagesToDraft(nextImages)
312 : [],
313 );
314 const storedImages = nextImages.filter((image) => storedImageIds.has(image.id));
315 // The draft may be gone by now; revoking a URL the store already revoked is harmless.
316 for (const image of nextImages) {
317 if (!storedImageIds.has(image.id)) URL.revokeObjectURL(image.previewUrl);
318 }
319 if (storedImages.length > 0 && imageAttachmentsGetChips) {
320 insertedAny =
321 insertAttachmentReferences(storedImages.map(imageContextReference)) || insertedAny;
322 }
323 // Only failures are reported here. Success must not pass `null`: by
324 // now other work (a failed send, an overlapping paste) may have set a
325 // thread error this call knows nothing about, and clearing it would
326 // swallow that message.
327 const compressionError = [...compressionErrors]
328 .filter(([id]) => stillPreparingIds.has(id))
329 .map(([, message]) => message)
330 .at(-1);
331 if (compressionError !== undefined) {
332 setThreadError(threadId, compressionError);
333 }
334 return insertedAny;
335 };
336
337 const removeComposerImage = (imageId: string) => {
338 if (removePreparingComposerImages(attachmentTargetKey, new Set([imageId])).size > 0) {
339 // Its compression finishes in the background and is dropped.
340 if (questionAttachmentTarget)
341 changeQuestionAttachmentPreparation(questionAttachmentTarget, -1);
342 return;
343 }
344 const image = composerImagesRef.current.find((candidate) => candidate.id === imageId);
345 const referenced = collectInlineContextIds(promptRef.current).includes(
346 image ? imageContextReference(image).contextId : "",
347 );
348 if (!referenced) {
349 removeComposerImageFromDraft(imageId);
350 return;
351 }
352 const confirmation = requestConfirmDialog(
353 `Remove ${image?.name ?? "this image"} from the message?\nIt is referenced in your text; removing it also removes every reference.`,
354 { variant: "destructive" },
355 );
356 if (!confirmation) {
357 removeComposerImageFromDraft(imageId);
358 return;
359 }
360 void confirmation.then((confirmed) => {
361 if (confirmed) removeComposerImageFromDraft(imageId);
362 });
363 };
364
365 const foldPastedText = (
366 plainText: string,
367 bypassAutoAttachment: boolean,
368 selectionOverride?: { start: number; end: number },
369 ): boolean => {
370 if (isLiteralPendingAnswer) return false;
371 const questionCanAttach =
372 pendingUserInputs.length === 0 ||
373 (supportsQuestionAttachments &&
374 activePendingProgress?.activeQuestion?.allowCustomAnswer !== false &&
375 !activePendingIsResponding);
376 const hasAttachmentSlot = countReservedAttachments() < PROVIDER_SEND_TURN_MAX_ATTACHMENTS;
377 const selection = selectionOverride ?? composerEditorRef.current?.readSelectionRange();
378 const wouldExceedInputLimit = wouldTextPasteExceedLimit({
379 valueLength: promptRef.current.length,
380 selection: selection ?? { start: 0, end: 0 },
381 textLength: plainText.length,
382 maxLength: PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
383 });
384 const shouldFold =
385 pastedTextDisposition({
386 text: plainText,
387 bypassAutoAttachment,
388 wouldExceedInputLimit,
389 canAttach: true,
390 }) === "attachment";
391 if (!shouldFold) {
392 return false;
393 }
394
395 const canStageAttachment =
396 Boolean(activeThreadId) &&
397 !isRevertingCheckpointRef.current &&
398 questionCanAttach &&
399 hasAttachmentSlot;
400 if (!canStageAttachment || fileStagingLimit === null) {
401 if (!wouldExceedInputLimit) {
402 return false;
403 }
404 toastManager.add({
405 type: "error",
406 title: "Pasted text is too large for this message",
407 description: "Remove some text or an attachment, then paste again.",
408 data: { hideCopyButton: true },
409 });
410 return true;
411 }
412
413 if (pastedTextFileNamesRef.current.targetKey !== attachmentTargetKey) {
414 pastedTextFileNamesRef.current = { targetKey: attachmentTargetKey, names: new Set() };
415 }
416 const reservedNames = pastedTextFileNamesRef.current.names;
417 for (const file of composerFilesRef.current) reservedNames.add(file.name);
418 const foldedFileName = nextPastedTextFileName([...reservedNames]);
419 reservedNames.add(foldedFileName);
420 const foldedFile = new File([plainText], foldedFileName, {
421 type: "text/plain;charset=utf-8",
422 });
423 if (foldedFile.size > fileStagingLimit) {
424 reservedNames.delete(foldedFileName);
425 if (!wouldExceedInputLimit) return false;
426 toastManager.add({
427 type: "error",
428 title: "Pasted text is too large to attach",
429 description: "Reduce the clipboard contents or save a smaller excerpt as a file.",
430 data: { hideCopyButton: true },
431 });
432 return true;
433 }
434
435 void addComposerAttachments([foldedFile], {
436 source: { _tag: "pasted-text" },
437 ...(selection ? { selection } : {}),
438 });
439 return true;
440 };
441
442 return {
443 addComposerAttachments,
444 removeComposerImage,
445 foldPastedText,
446 };
447}