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

useComposerAttachmentIntake.ts

423 lines16.0 KB

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