feat(composer): fold large pastes into text attachments (#11442)

This commit is contained in:
Chris Deeming authored and GitHub committed 2026-09-12 17:28:28 -07:00
1 parent 36caf200c2
commit 68c2277f50
77 files changed
+3278 -465

No files matched your search

+226 -35
View File
@@ -1,13 +1,15 @@
import { DESKTOP_PASTE_AS_TEXT_EVENT } from "../../lib/desktopPasteAsText";
import { runtimeModeConfig, runtimeModeOptions } from "./runtimeModeConfig";
import { useRightPanelStore } from "~/rightPanelStore";
import { AttachmentFilePreview } from "../files/AttachmentFilePreview";
import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";
import { filterComposerPullRequestMatches } from "@t3tools/shared/composerPullRequestMatches";
import { importPastedComposerText } from "../composerInlineTokenPaste";
import { importPastedComposerText, readPastedComposerContext } from "../composerInlineTokenPaste";
import { elementContextToPreviewAnnotation } from "../../lib/elementContext";
import { RefreshIcon } from "~/components/ui/refresh-icon";
import {
questionAttachmentDraftId,
countQuestionAttachments,
useQuestionAttachmentPreparation,
changeQuestionAttachmentPreparation,
} from "../../questionAttachments";
@@ -34,8 +36,15 @@ import {
ProviderInstanceId,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
} from "@t3tools/contracts";
import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";
import {
isPasteAsTextShortcut,
nextPastedTextFileName,
pastedTextDisposition,
wouldTextPasteExceedLimit,
} from "@t3tools/client-runtime/text-paste";
import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model";
import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits";
@@ -194,6 +203,7 @@ import {
ensureInlineContextReferences,
formatInlineContextReference,
insertInlineContextReference,
inlineContextReferenceReplacement,
toKindScopedComposerContextId,
} from "~/lib/composerContextReferences";
import {
@@ -284,7 +294,7 @@ import {
} from "../../lib/snapShotAnimation";
import { resizeSnapShotSource } from "../../lib/snapShotSource";
import { basenameOfPath } from "../../pierre-icons";
import { cn, randomUUID } from "~/lib/utils";
import { cn, isMacPlatform, randomUUID } from "~/lib/utils";
import {
getComposerPromptLengthValidationMessage,
getComposerSubmissionValidationMessage,
@@ -1212,6 +1222,8 @@ export interface ChatComposerHandle {
text: string,
options?: { ensureLeadingBoundary?: boolean; clipboardData?: DataTransfer },
) => boolean;
/** Apply large-paste folding for text redirected from a blurred composer. */
pasteTextAtEnd: (text: string, options?: { bypassAutoAttachment?: boolean }) => boolean;
citeAssistantText: (
citation: AssistantCitation,
sourceAnchor: AssistantCitationSourceAnchor,
@@ -2064,6 +2076,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// Refs
// ------------------------------------------------------------------
const composerEditorRef = useRef<ComposerPromptEditorHandle>(null);
const pasteAsTextShortcutUntilRef = useRef(0);
const pastedTextFileNamesRef = useRef<{ targetKey: string; names: Set<string> }>({
targetKey: "",
names: new Set(),
});
const attachmentInputRef = useRef<HTMLInputElement>(null);
const composerFormRef = useRef<HTMLFormElement>(null);
const composerFooterControlsRef = useRef<HTMLDivElement>(null);
@@ -2099,6 +2116,49 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const isRevertingCheckpointRef = useRef(isRevertingCheckpoint);
isRevertingCheckpointRef.current = isRevertingCheckpoint;
useEffect(() => {
const armPasteAsTextShortcut = () => {
// Electron can deliver its native menu action just before the paste
// event, while browsers normally deliver keydown first. A short deadline
// bridges both event paths without leaving later pastes in bypass mode.
pasteAsTextShortcutUntilRef.current = Date.now() + 1_000;
};
const onKeyDown = (event: KeyboardEvent) => {
if (
event.target instanceof Node &&
composerFormRef.current?.contains(event.target) &&
isPasteAsTextShortcut(event, isMacPlatform(navigator.platform))
) {
armPasteAsTextShortcut();
}
};
const onBlur = () => {
pasteAsTextShortcutUntilRef.current = 0;
};
const onDesktopPasteAsText = () => {
const activeElement = document.activeElement;
const blocksPasteToFocus =
activeElement instanceof Element &&
activeElement.closest(
'input, textarea, select, button, a[href], summary, [contenteditable="true"], [contenteditable="plaintext-only"], [role="textbox"], [role="button"], [role="menuitem"], [role="option"]',
) !== null;
if (
(activeElement instanceof Node && composerFormRef.current?.contains(activeElement)) ||
!blocksPasteToFocus
) {
armPasteAsTextShortcut();
}
};
window.addEventListener(DESKTOP_PASTE_AS_TEXT_EVENT, onDesktopPasteAsText);
window.addEventListener("keydown", onKeyDown, true);
window.addEventListener("blur", onBlur);
return () => {
window.removeEventListener(DESKTOP_PASTE_AS_TEXT_EVENT, onDesktopPasteAsText);
window.removeEventListener("keydown", onKeyDown, true);
window.removeEventListener("blur", onBlur);
};
}, []);
// ------------------------------------------------------------------
// Derived: composer send state
// ------------------------------------------------------------------
@@ -4041,6 +4101,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
mimeType: file.mimeType,
sizeBytes: file.sizeBytes,
file: null,
...(file.source ? { source: file.source } : {}),
// An expired upload carries no ids, so it hydrates as a
// needs-reattach row and the "Attach again" flow takes over.
...(expired
@@ -4319,6 +4380,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
sizeBytes: file.sizeBytes,
attachmentId: upload.attachmentId,
environmentId,
...(file.source ? { source: file.source } : {}),
});
}
// A repeat ⌘S on the *same* still-unencoded snapshot would stash it
@@ -5032,8 +5094,36 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// ------------------------------------------------------------------
// Callbacks: attachments
// ------------------------------------------------------------------
const countReservedAttachments = () => {
const questionRequest = pendingUserInputs[0];
const otherQuestionKeys =
questionAttachmentTarget && questionRequest && activeThreadId
? questionRequest.questions
.map((question) =>
questionAttachmentDraftId(
environmentId,
activeThreadId,
questionRequest.requestId,
question.id,
),
)
.filter((key) => key !== questionAttachmentTarget)
: [];
return (
composerImagesRef.current.length +
composerFilesRef.current.length +
(pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) +
countQuestionAttachments(otherQuestionKeys)
);
};
/** Resolves true when at least one chip was inserted for the accepted attachments. */
const addComposerAttachments = async (files: File[]): Promise<boolean> => {
const addComposerAttachments = async (
files: File[],
options?: {
readonly source?: ChatFileAttachment["source"];
readonly selection?: { start: number; end: number };
},
): Promise<boolean> => {
if (!activeThreadId || files.length === 0 || isRevertingCheckpointRef.current) return false;
if (
pendingUserInputs.length > 0 &&
@@ -5056,30 +5146,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// accepted files reserve their attachment slots (via the pending counter)
// before the first await, keeping the total under the limit.
const pendingCount = pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0;
const otherQuestionAttachments =
questionAttachmentTarget && pendingUserInputs[0]
? pendingUserInputs[0].questions.reduce((count, question) => {
const target = questionAttachmentDraftId(
environmentId,
threadId,
pendingUserInputs[0]!.requestId,
question.id,
);
if (target === questionAttachmentTarget) return count;
const draft = getComposerDraft(target);
return (
count +
(draft?.images.length ?? 0) +
(draft?.files.length ?? 0) +
(useQuestionAttachmentPreparation.getState().counts[target] ?? 0)
);
}, 0)
: 0;
let reservedCount =
composerImagesRef.current.length +
composerFilesRef.current.length +
pendingCount +
otherQuestionAttachments;
let reservedCount = countReservedAttachments();
// A pick that matches a needs-reattach marker replaces it in the draft, so
// it must not consume a slot; a draft full of markers would otherwise hit
// the capacity error before the replacement path could run.
@@ -5146,6 +5213,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
mimeType: fileMimeType,
sizeBytes: attachmentFile.size,
file: attachmentFile,
...(options?.source ? { source: options.source } : {}),
});
}
if (!matchingReattachMarker) {
@@ -5160,7 +5228,21 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const storedIds = new Set(addComposerFilesToDraft(acceptedFiles));
const storedFiles = acceptedFiles.filter((file) => storedIds.has(file.id));
if (storedFiles.length > 0) {
insertedAny = insertAttachmentReferences(storedFiles.map(fileContextReference));
insertedAny = insertAttachmentReferences(
storedFiles.map(fileContextReference),
options?.selection,
);
}
if (options?.source?._tag === "pasted-text" && storedFiles.length > 0) {
const attached = storedFiles[0]!;
toastManager.add({
type: "info",
title: `Large paste attached as ${attached.name}`,
description: `${formatAttachmentSize(attached.sizeBytes)} · Use ${
isMacPlatform(navigator.platform) ? "⌘⇧V" : "Ctrl+Shift+V"
} to keep a large paste inline.`,
data: { hideCopyButton: true },
});
}
}
if (acceptedImages.length === 0) return insertedAny;
@@ -5246,11 +5328,16 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
*/
const insertAttachmentReferences = (
references: ReadonlyArray<ComposerContextReference>,
selection?: { start: number; end: number },
): boolean => {
if (references.length === 0) return false;
// Question answers carry attachments beside the answer, never as chips. Falling back to
// the thread prompt here would hide the file behind a reference the question never shows.
if (questionAttachmentTarget) return false;
if (selection) {
const edit = inlineContextReferenceReplacement(promptRef.current, selection, references);
return applyPromptReplacement(edit.start, edit.end, edit.text);
}
const text = references.map(formatInlineContextReference).join(" ");
const inserted = insertComposerText(`${text} `, "cursor", { ensureLeadingBoundary: true });
if (!inserted) {
@@ -5284,24 +5371,110 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// ------------------------------------------------------------------
// Callbacks: paste / drag
// ------------------------------------------------------------------
const foldPastedText = (
plainText: string,
bypassAutoAttachment: boolean,
selectionOverride?: { start: number; end: number },
): boolean => {
const questionCanAttach =
pendingUserInputs.length === 0 ||
(supportsQuestionAttachments &&
activePendingProgress?.activeQuestion?.allowCustomAnswer !== false &&
!activePendingIsResponding);
const hasAttachmentSlot = countReservedAttachments() < PROVIDER_SEND_TURN_MAX_ATTACHMENTS;
const selection = selectionOverride ?? composerEditorRef.current?.readSelectionRange();
const wouldExceedInputLimit = wouldTextPasteExceedLimit({
valueLength: promptRef.current.length,
selection: selection ?? { start: 0, end: 0 },
textLength: plainText.length,
maxLength: PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
});
const shouldFold =
pastedTextDisposition({
text: plainText,
bypassAutoAttachment,
wouldExceedInputLimit,
canAttach: true,
}) === "attachment";
if (!shouldFold) {
return false;
}
const canStageAttachment =
Boolean(activeThreadId) &&
!isRevertingCheckpointRef.current &&
questionCanAttach &&
hasAttachmentSlot;
if (!canStageAttachment || fileStagingLimit === null) {
if (!wouldExceedInputLimit) {
return false;
}
toastManager.add({
type: "error",
title: "Pasted text is too large for this message",
description: "Remove some text or an attachment, then paste again.",
data: { hideCopyButton: true },
});
return true;
}
if (pastedTextFileNamesRef.current.targetKey !== attachmentTargetKey) {
pastedTextFileNamesRef.current = { targetKey: attachmentTargetKey, names: new Set() };
}
const reservedNames = pastedTextFileNamesRef.current.names;
for (const file of composerFilesRef.current) reservedNames.add(file.name);
const foldedFileName = nextPastedTextFileName([...reservedNames]);
reservedNames.add(foldedFileName);
const foldedFile = new File([plainText], foldedFileName, {
type: "text/plain;charset=utf-8",
});
if (foldedFile.size > fileStagingLimit) {
reservedNames.delete(foldedFileName);
if (!wouldExceedInputLimit) return false;
toastManager.add({
type: "error",
title: "Pasted text is too large to attach",
description: "Reduce the clipboard contents or save a smaller excerpt as a file.",
data: { hideCopyButton: true },
});
return true;
}
void addComposerAttachments([foldedFile], {
source: { _tag: "pasted-text" },
...(selection ? { selection } : {}),
});
return true;
};
const onComposerPaste = (event: React.ClipboardEvent<HTMLElement>) => {
const files = Array.from(event.clipboardData.files);
const plainText = event.clipboardData.getData("text/plain");
const bypassAutoAttachment = Date.now() <= pasteAsTextShortcutUntilRef.current;
pasteAsTextShortcutUntilRef.current = 0;
// Claimable pastes go through even when agent questions are pending or the
// composer is at its attachment limit: `addComposerAttachments` surfaces
// those as a toast and a thread error. An early return here would swallow
// the paste with no feedback.
if (
files.length === 0 ||
!activeThreadId ||
!shouldHandleComposerAttachmentPaste({
files,
plainText: event.clipboardData.getData("text/plain"),
})
files.length > 0 &&
activeThreadId &&
shouldHandleComposerAttachmentPaste({ files, plainText })
) {
event.preventDefault();
event.stopPropagation();
void addComposerAttachments(files);
return;
}
// Copied T3 chips need the structured importer to bring their records and files along.
if ((readPastedComposerContext(event.clipboardData)?.records.length ?? 0) > 0) return;
if (!foldPastedText(plainText, bypassAutoAttachment)) {
return;
}
event.preventDefault();
void addComposerAttachments(files);
event.stopPropagation();
};
const insertComposerText = useCallback(
@@ -5526,6 +5699,23 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
hasPendingAttachments: () =>
(pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) > 0,
insertTextAtEnd: insertComposerTextAtEnd,
pasteTextAtEnd: (text: string, options) => {
const bypassAutoAttachment =
options?.bypassAutoAttachment === true ||
Date.now() <= pasteAsTextShortcutUntilRef.current;
pasteAsTextShortcutUntilRef.current = 0;
const promptLength = promptRef.current.length;
if (
!foldPastedText(text, bypassAutoAttachment, {
start: promptLength,
end: promptLength,
})
) {
return false;
}
focusComposer();
return true;
},
citeAssistantText: (citation, sourceAnchor) =>
insertComposerText(
formatAssistantCitationForComposer(citation, citation.comment),
@@ -5626,6 +5816,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
[
activeThread,
addComposerAttachments,
foldPastedText,
composerDraftTarget,
composerCursor,
composerTerminalContexts,