@devries-cameron20 / t3code Mirror · read-only / commits / 98c494ec69
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 19:30 UTC

refactor(web): composer file intake lives in useComposerAttachmentIntake (#23049)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 21, 2026 at 13:23 UTC 98c494ec69a47871d8544e45df23d61928326692
2 files changed +450 -330
apps/web/src/components/chat/ChatComposer.tsx
+27 -330
@@ -10,7 +10,6 @@ import {
10 questionAttachmentDraftId,
11 trackOpenQuestionAttachmentDraft,
12 useQuestionAttachmentPreparation,
13 - changeQuestionAttachmentPreparation,
13 } from "../../questionAttachments";
14 import type {
15 KeybindingCommand,
@@ -37,18 +36,11 @@ import {
36 ProviderDriverKind,
37 ProviderInstanceId,
38 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
40 - PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
41 - PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
39 } from "@t3tools/contracts";
40 import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";
41 import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
42 import * as Schema from "effect/Schema";
46 -import {
47 - isPasteAsTextShortcut,
48 - nextPastedTextFileName,
49 - pastedTextDisposition,
50 - wouldTextPasteExceedLimit,
51 -} from "@t3tools/client-runtime/text-paste";
43 +import { isPasteAsTextShortcut } from "@t3tools/client-runtime/text-paste";
44 import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
45 import { folderDropTarget, resolveDroppedFolderPath } from "./folderDrop";
46 import { splitTransferredFiles } from "./workspaceFileDrop";
@@ -102,7 +94,6 @@ import {
94 type ComposerImageAttachment,
95 type DraftId,
96 type PersistedComposerImageAttachment,
105 - composerFileMatchesReattachMarker,
97 composerFileNeedsReattach,
98 composerDraftHasUserContent,
99 composerTargetKey,
@@ -135,19 +126,12 @@ import {
126 type ComposerBannerStackContent,
127 type ComposerBannerStackItem,
128 } from "./ComposerBannerStack";
138 -import { prepareImageForAttachment } from "../../lib/imageCompression";
139 -import {
140 - fileAttachmentTooLargeMessage,
141 - formatAttachmentSize,
142 -} from "@t3tools/client-runtime/state/attachments";
129 import {
130 attachmentsToReleaseOnUploadCapabilityLoss,
131 composerOtherFilesForPresentation,
146 - classifyComposerAttachmentFile,
132 fileAttachmentCapabilityBlockReason,
133 fileAttachmentStagingLimit,
134 isPreviewableComposerVideo,
150 - normalizeComposerImageFileMimeType,
135 shouldHandleComposerAttachmentPaste,
136 } from "./composerAttachmentFiles";
137 import {
@@ -181,7 +165,6 @@ import {
165 import { useOpenPrLink } from "~/lib/openPullRequestLink";
166 import {
167 collectInlineContextIds,
184 - stripInlineContextReferences,
168 type ComposerContextReference,
169 ensureInlineContextReferences,
170 formatInlineContextReference,
@@ -191,8 +174,6 @@ import {
174 import {
175 attachmentContextRecord,
176 uploadedAttachmentContextRecord,
194 - fileContextReference,
195 - imageContextReference,
177 previewAnnotationContextId,
178 previewAnnotationContextRecord,
179 reviewCommentContextId,
@@ -206,7 +187,6 @@ import {
187 import { rememberCopiedComposerAttachments } from "~/lib/copiedComposerAttachments";
188 import { useThreadContextDrop, threadContextDropTargetProps } from "./threadContextDrag";
189 import { readThreadShell } from "~/state/entities";
209 -import { requestConfirmDialog } from "~/confirmDialog";
190 import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";
191 import type { ComposerContextRecord, ThreadPullRequestLink } from "@t3tools/contracts";
192 import { threadContextAttachment } from "~/lib/threadContextAttachment";
@@ -289,7 +269,6 @@ import {
269 type SessionPhase,
270 type Thread,
271 type ThreadShell,
292 - videoMimeType,
272 } from "../../types";
273 import {
274 buildComposerPromptHistoryEntries,
@@ -326,6 +305,7 @@ import { useComposerProviderModel } from "./useComposerProviderModel";
305 import { useComposerImageGroups } from "./useComposerImageGroups";
306 import { useComposerStash } from "./useComposerStash";
307 import { useComposerContextImport } from "./useComposerContextImport";
308 +import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake";
309
310 /** Reads and disarms a paste-as-text deadline: the shortcut applies to one paste only. */
311 function consumePasteAsTextShortcut(deadline: { current: number }): boolean {
@@ -1154,10 +1134,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
1134
1135 const composerEditorRef = useRef<ComposerPromptEditorHandle>(null);
1136 const pasteAsTextShortcutUntilRef = useRef(0);
1157 - const pastedTextFileNamesRef = useRef<{ targetKey: string; names: Set<string> }>({
1158 - targetKey: "",
1159 - names: new Set(),
1160 - });
1137 const composerFormRef = useRef<HTMLFormElement>(null);
1138 const composerSurfaceRef = useRef<HTMLDivElement>(null);
1139 const providerInputRejectedRef = useRef(false);
@@ -3015,312 +2991,33 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2991 });
2992 };
2993
3018 - const addComposerAttachments = async (
3019 - files: File[],
3020 - options?: {
3021 - readonly source?: ChatFileAttachment["source"];
3022 - readonly selection?: { start: number; end: number };
3023 - readonly skipImageInlineChip?: boolean;
3024 - },
3025 - ): Promise<boolean> => {
3026 - if (!activeThreadId || files.length === 0 || isRevertingCheckpointRef.current) return false;
3027 - if (
3028 - pendingUserInputs.length > 0 &&
3029 - (!supportsQuestionAttachments ||
3030 - activePendingProgress?.activeQuestion?.allowCustomAnswer === false ||
3031 - activePendingIsResponding)
3032 - ) {
3033 - toastManager.add({
3034 - type: "error",
3035 - title: "This question cannot accept attachments.",
3036 - });
3037 - return false;
3038 - }
3039 - // Captured before the awaits below: the user may switch threads while a
3040 - // large image is being compressed, and the attachments and errors belong
3041 - // to the thread the paste happened in.
3042 - const threadId = activeThreadId;
3043 - const imageAttachmentsGetChips =
3044 - !options?.skipImageInlineChip &&
3045 - (options?.selection !== undefined ||
3046 - isConnecting ||
3047 - pendingUserInputs.length > 0 ||
3048 - projectSelectionRequired ||
3049 - stripInlineContextReferences(promptRef.current).trim().length > 0);
3050 -
3051 - // Validation happens synchronously so concurrent pastes see each other:
3052 - // accepted files reserve their attachment slots (via the pending counter)
3053 - // before the first await, keeping the total under the limit.
3054 - const pendingCount = pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0;
3055 - let reservedCount = countReservedAttachments();
3056 - // A pick that matches a needs-reattach marker replaces it in the draft, so
3057 - // it must not consume a slot; a draft full of markers would otherwise hit
3058 - // the capacity error before the replacement path could run.
3059 - const reattachMarkers = composerFilesRef.current.filter(composerFileNeedsReattach);
3060 - const replacedReattachMarkerIds = new Set<string>();
3061 - const acceptedImages: File[] = [];
3062 - const acceptedFiles: ComposerFileAttachment[] = [];
3063 - let error: string | null = null;
3064 - for (const file of files) {
3065 - const attachmentKind = classifyComposerAttachmentFile(file);
3066 - const fileMimeType =
3067 - attachmentKind === "file"
3068 - ? (videoMimeType({ name: file.name, mimeType: file.type }) ??
3069 - (file.type || "application/octet-stream"))
3070 - : file.type;
3071 - const matchingReattachMarker =
3072 - attachmentKind === "file"
3073 - ? reattachMarkers.find(
3074 - (marker) =>
3075 - !replacedReattachMarkerIds.has(marker.id) &&
3076 - composerFileMatchesReattachMarker(marker, {
3077 - name: file.name || "file",
3078 - mimeType: fileMimeType,
3079 - sizeBytes: file.size,
3080 - }),
3081 - )
3082 - : undefined;
3083 - if (matchingReattachMarker) {
3084 - replacedReattachMarkerIds.add(matchingReattachMarker.id);
3085 - }
3086 - if (!matchingReattachMarker && reservedCount >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
3087 - error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`;
3088 - continue;
3089 - }
3090 - if (attachmentKind === "unsupported-image") {
3091 - error = `'${file.name}' is not a supported image type. Attach GIF, HEIC, HEIF, JPEG, PNG, or WebP images.`;
3092 - continue;
3093 - }
3094 - if (attachmentKind === "image") {
3095 - acceptedImages.push(normalizeComposerImageFileMimeType(file));
3096 - } else {
3097 - if (fileStagingLimit === null) {
3098 - error = "This server does not support file attachments.";
3099 - continue;
3100 - }
3101 - if (file.size <= 0) {
3102 - error = `'${file.name}' is empty or could not be read.`;
3103 - continue;
3104 - }
3105 - if (file.size > fileStagingLimit) {
3106 - error = fileAttachmentTooLargeMessage(file.name, fileStagingLimit);
3107 - continue;
3108 - }
3109 - const attachmentFile =
3110 - file.type === fileMimeType
3111 - ? file
3112 - : new File([file], file.name, { type: fileMimeType, lastModified: file.lastModified });
3113 - acceptedFiles.push({
3114 - type: "file",
3115 - id: randomUUID(),
3116 - name: attachmentFile.name || "file",
3117 - mimeType: fileMimeType,
3118 - sizeBytes: attachmentFile.size,
3119 - file: attachmentFile,
3120 - ...(options?.source ? { source: options.source } : {}),
3121 - });
3122 - }
3123 - if (!matchingReattachMarker) {
3124 - reservedCount += 1;
3125 - }
3126 - }
3127 - setThreadError(threadId, error);
3128 - let insertedAny = false;
3129 - if (acceptedFiles.length > 0) {
3130 - const storedIds = new Set(addComposerFilesToDraft(acceptedFiles));
3131 - const storedFiles = acceptedFiles.filter((file) => storedIds.has(file.id));
3132 - if (storedFiles.length > 0) {
3133 - insertedAny = insertAttachmentReferences(
3134 - storedFiles.map(fileContextReference),
3135 - options?.selection,
3136 - );
3137 - }
3138 - if (options?.source?._tag === "pasted-text" && storedFiles.length > 0) {
3139 - const attached = storedFiles[0]!;
3140 - toastManager.add({
3141 - type: "info",
3142 - title: `Large paste attached as ${attached.name}`,
3143 - description: `${formatAttachmentSize(attached.sizeBytes)} · Use ${
3144 - isMacPlatform(navigator.platform) ? "⌘⇧V" : "Ctrl+Shift+V"
3145 - } to keep a large paste inline.`,
3146 - data: { hideCopyButton: true },
3147 - });
3148 - }
3149 - }
3150 - if (acceptedImages.length === 0) return insertedAny;
3151 -
3152 - pendingImageCompressionsRef.current.set(
2994 + const { addComposerAttachments, removeComposerImage, foldPastedText } =
2995 + useComposerAttachmentIntake({
2996 + activeThreadId,
2997 + activePendingProgress,
2998 + activePendingIsResponding,
2999 + pendingUserInputs,
3000 + supportsQuestionAttachments,
3001 + isLiteralPendingAnswer,
3002 + isConnecting,
3003 + projectSelectionRequired,
3004 + questionAttachmentTarget,
3005 attachmentTargetKey,
3154 - pendingCount + acceptedImages.length,
3155 - );
3156 - if (questionAttachmentTarget)
3157 - changeQuestionAttachmentPreparation(questionAttachmentTarget, acceptedImages.length);
3158 - const compressAndStoreImages = async (): Promise<boolean> => {
3159 - const nextImages: ComposerImageAttachment[] = [];
3160 - let compressionError: string | null = null;
3161 - for (const file of acceptedImages) {
3162 - const compressed = await prepareImageForAttachment(
3163 - file,
3164 - PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
3165 - );
3166 - if (!compressed.ok) {
3167 - compressionError =
3168 - compressed.reason === "unreadable"
3169 - ? `'${file.name}' could not be read as an image.`
3170 - : `'${file.name}' is too large to attach, even after compression.`;
3171 - continue;
3172 - }
3173 - const attachmentFile = compressed.file;
3174 - const previewUrl = URL.createObjectURL(attachmentFile);
3175 - nextImages.push({
3176 - type: "image",
3177 - id: randomUUID(),
3178 - name: attachmentFile.name || "image",
3179 - mimeType: attachmentFile.type,
3180 - sizeBytes: attachmentFile.size,
3181 - previewUrl,
3182 - file: attachmentFile,
3183 - });
3184 - }
3185 - if (
3186 - questionAttachmentTarget &&
3187 - !useQuestionAttachmentPreparation.getState().counts[questionAttachmentTarget]
3188 - ) {
3189 - for (const image of nextImages) URL.revokeObjectURL(image.previewUrl);
3190 - return false;
3191 - }
3192 - const storedImageIds = new Set(
3193 - nextImages.length === 1 && nextImages[0]
3194 - ? addComposerImage(nextImages[0])
3195 - : nextImages.length > 1
3196 - ? addComposerImagesToDraft(nextImages)
3197 - : [],
3198 - );
3199 - const storedImages = nextImages.filter((image) => storedImageIds.has(image.id));
3200 - if (storedImages.length > 0 && imageAttachmentsGetChips) {
3201 - insertedAny =
3202 - insertAttachmentReferences(storedImages.map(imageContextReference)) || insertedAny;
3203 - }
3204 - // Only failures are reported here. Success must not pass `null`: by
3205 - // now other work (a failed send, an overlapping paste) may have set a
3206 - // thread error this call knows nothing about, and clearing it would
3207 - // swallow that message.
3208 - if (compressionError !== null) {
3209 - setThreadError(threadId, compressionError);
3210 - }
3211 - return insertedAny;
3212 - };
3213 - return await compressAndStoreImages().finally(() => {
3214 - if (questionAttachmentTarget)
3215 - changeQuestionAttachmentPreparation(questionAttachmentTarget, -acceptedImages.length);
3216 - const remaining =
3217 - (pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) - acceptedImages.length;
3218 - if (remaining > 0) {
3219 - pendingImageCompressionsRef.current.set(attachmentTargetKey, remaining);
3220 - } else {
3221 - pendingImageCompressionsRef.current.delete(attachmentTargetKey);
3222 - }
3223 - });
3224 - };
3225 -
3226 - const removeComposerImage = (imageId: string) => {
3227 - const image = composerImagesRef.current.find((candidate) => candidate.id === imageId);
3228 - const referenced = collectInlineContextIds(promptRef.current).includes(
3229 - image ? imageContextReference(image).contextId : "",
3230 - );
3231 - if (!referenced) {
3232 - removeComposerImageFromDraft(imageId);
3233 - return;
3234 - }
3235 - const confirmation = requestConfirmDialog(
3236 - `Remove ${image?.name ?? "this image"} from the message?\nIt is referenced in your text; removing it also removes every reference.`,
3237 - { variant: "destructive" },
3238 - );
3239 - if (!confirmation) {
3240 - removeComposerImageFromDraft(imageId);
3241 - return;
3242 - }
3243 - void confirmation.then((confirmed) => {
3244 - if (confirmed) removeComposerImageFromDraft(imageId);
3245 - });
3246 - };
3247 -
3248 - const foldPastedText = (
3249 - plainText: string,
3250 - bypassAutoAttachment: boolean,
3251 - selectionOverride?: { start: number; end: number },
3252 - ): boolean => {
3253 - if (isLiteralPendingAnswer) return false;
3254 - const questionCanAttach =
3255 - pendingUserInputs.length === 0 ||
3256 - (supportsQuestionAttachments &&
3257 - activePendingProgress?.activeQuestion?.allowCustomAnswer !== false &&
3258 - !activePendingIsResponding);
3259 - const hasAttachmentSlot = countReservedAttachments() < PROVIDER_SEND_TURN_MAX_ATTACHMENTS;
3260 - const selection = selectionOverride ?? composerEditorRef.current?.readSelectionRange();
3261 - const wouldExceedInputLimit = wouldTextPasteExceedLimit({
3262 - valueLength: promptRef.current.length,
3263 - selection: selection ?? { start: 0, end: 0 },
3264 - textLength: plainText.length,
3265 - maxLength: PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
3266 - });
3267 - const shouldFold =
3268 - pastedTextDisposition({
3269 - text: plainText,
3270 - bypassAutoAttachment,
3271 - wouldExceedInputLimit,
3272 - canAttach: true,
3273 - }) === "attachment";
3274 - if (!shouldFold) {
3275 - return false;
3276 - }
3277 -
3278 - const canStageAttachment =
3279 - Boolean(activeThreadId) &&
3280 - !isRevertingCheckpointRef.current &&
3281 - questionCanAttach &&
3282 - hasAttachmentSlot;
3283 - if (!canStageAttachment || fileStagingLimit === null) {
3284 - if (!wouldExceedInputLimit) {
3285 - return false;
3286 - }
3287 - toastManager.add({
3288 - type: "error",
3289 - title: "Pasted text is too large for this message",
3290 - description: "Remove some text or an attachment, then paste again.",
3291 - data: { hideCopyButton: true },
3292 - });
3293 - return true;
3294 - }
3295 -
3296 - if (pastedTextFileNamesRef.current.targetKey !== attachmentTargetKey) {
3297 - pastedTextFileNamesRef.current = { targetKey: attachmentTargetKey, names: new Set() };
3298 - }
3299 - const reservedNames = pastedTextFileNamesRef.current.names;
3300 - for (const file of composerFilesRef.current) reservedNames.add(file.name);
3301 - const foldedFileName = nextPastedTextFileName([...reservedNames]);
3302 - reservedNames.add(foldedFileName);
3303 - const foldedFile = new File([plainText], foldedFileName, {
3304 - type: "text/plain;charset=utf-8",
3305 - });
3306 - if (foldedFile.size > fileStagingLimit) {
3307 - reservedNames.delete(foldedFileName);
3308 - if (!wouldExceedInputLimit) return false;
3309 - toastManager.add({
3310 - type: "error",
3311 - title: "Pasted text is too large to attach",
3312 - description: "Reduce the clipboard contents or save a smaller excerpt as a file.",
3313 - data: { hideCopyButton: true },
3314 - });
3315 - return true;
3316 - }
3317 -
3318 - void addComposerAttachments([foldedFile], {
3319 - source: { _tag: "pasted-text" },
3320 - ...(selection ? { selection } : {}),
3006 + fileStagingLimit,
3007 + promptRef,
3008 + composerImagesRef,
3009 + composerFilesRef,
3010 + composerEditorRef,
3011 + isRevertingCheckpointRef,
3012 + pendingImageCompressionsRef,
3013 + setThreadError,
3014 + countReservedAttachments,
3015 + addComposerImage,
3016 + addComposerImagesToDraft,
3017 + addComposerFilesToDraft,
3018 + removeComposerImageFromDraft,
3019 + insertAttachmentReferences,
3020 });
3322 - return true;
3323 - };
3021
3022 const onComposerCommandKeyStable = useStableCallback(onComposerCommandKey);
3023 const isPathQueryActiveStable = useStableCallback(
apps/web/src/components/chat/useComposerAttachmentIntake.ts new
+423
@@ -0,0 +1,423 @@
1 +import type { ChatComposerProps } from "./ChatComposer";
2 +import {
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";
8 +import {
9 + type ComposerContextReference,
10 + collectInlineContextIds,
11 + stripInlineContextReferences,
12 +} from "~/lib/composerContextReferences";
13 +import {
14 + type ComposerFileAttachment,
15 + type ComposerImageAttachment,
16 + type DraftId,
17 + composerFileMatchesReattachMarker,
18 + composerFileNeedsReattach,
19 +} from "../../composerDraftStore";
20 +import { type ComposerPromptEditorHandle } from "../ComposerPromptEditor";
21 +import { type PendingUserInput } from "../../session-logic";
22 +import {
23 + changeQuestionAttachmentPreparation,
24 + useQuestionAttachmentPreparation,
25 +} from "../../questionAttachments";
26 +import {
27 + classifyComposerAttachmentFile,
28 + normalizeComposerImageFileMimeType,
29 +} from "./composerAttachmentFiles";
30 +import {
31 + fileAttachmentTooLargeMessage,
32 + formatAttachmentSize,
33 +} from "@t3tools/client-runtime/state/attachments";
34 +import { fileContextReference, imageContextReference } from "~/lib/composerContextRecords";
35 +import { isMacPlatform, randomUUID } from "~/lib/utils";
36 +import {
37 + nextPastedTextFileName,
38 + pastedTextDisposition,
39 + wouldTextPasteExceedLimit,
40 +} from "@t3tools/client-runtime/text-paste";
41 +import { prepareImageForAttachment } from "../../lib/imageCompression";
42 +import { requestConfirmDialog } from "~/confirmDialog";
43 +import { toastManager } from "../ui/toast";
44 +import { type RefObject, useRef } from "react";
45 +import { 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 + */
51 +export 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 + };
423 +}