Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useComposerAttachmentIntake.ts

500 lines19.0 KB

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