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

useComposerAttachmentIntake.ts

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