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

@@ -1,4 +1,10 @@
import { useAtomValue } from "@effect/atom-react";
import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
import {
nextPastedTextFileName,
pastedTextDisposition,
replaceTextSelection,
} from "@t3tools/client-runtime/text-paste";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import {
CommonActions,
@@ -22,11 +28,16 @@ import { useFontFamily } from "../../lib/useFontFamily";
import {
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
resolveEnvironmentMachineKind,
type EnvironmentId,
} from "@t3tools/contracts";
import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
import {
ComposerEditor,
type ComposerEditorHandle,
type ComposerTextPaste,
} from "../../components/ComposerEditor";
import { composerContextImportsAtom } from "../../state/use-composer-drafts";
import {
composerContextSendBlockReason,
@@ -41,7 +52,6 @@ import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
import { ComposerAttachmentButton } from "../../components/ComposerAttachmentButton";
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
import { composerStripAttachments } from "../../lib/composerImages";
import { collectComposerContextReferences } from "@t3tools/shared/composerContextReferences";
import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
import {
composerAttachmentUploadBlockReason,
@@ -73,13 +83,17 @@ import {
import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
import {
convertPastedImagesToAttachments,
createPastedTextComposerAttachment,
pickComposerFiles,
pickComposerMedia,
removePersistedComposerAttachmentFile,
type DraftComposerFileAttachment,
} from "../../lib/composerImages";
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
import {
clearComposerDraftContent,
captureComposerDraftInsertion,
countComposerDraftAttachmentsAfterSelection,
getComposerDraftSnapshot,
mergeComposerDraftContent,
restoreComposerDraftSnapshot,
@@ -297,6 +311,12 @@ export function NewTaskDraftScreen(props: {
const shareImportDraftBackupRef = useRef(new Map<string, ComposerDraft>());
const activeShareImportTokenRef = useRef<symbol | null>(null);
const shareImportMountedRef = useRef(true);
const pendingPastedTextAttachmentCountRef = useRef(0);
const [pendingPastedTextAttachmentCount, setPendingPastedTextAttachmentCount] = useState(0);
const pastedTextFileNamesRef = useRef<{ draftKey: string | null; names: Set<string> }>({
draftKey: null,
names: new Set(),
});
const latestDraftKeyRef = useRef(flow.draftKey);
const latestIncomingShareIdRef = useRef(props.incomingShareId);
latestDraftKeyRef.current = flow.draftKey;
@@ -344,16 +364,8 @@ export function NewTaskDraftScreen(props: {
: (flow.selectedWorktreePath ?? selectedProject?.workspaceRoot)) || null;
// Media needs its thumbnail; every other file already reads as its inline chip.
const stripAttachments = useMemo(
() =>
composerStripAttachments(
flow.attachments,
new Set(
collectComposerContextReferences(flow.prompt).map(
(occurrence) => occurrence.contextId as string,
),
),
),
[flow.attachments, flow.prompt],
() => composerStripAttachments(flow.attachments),
[flow.attachments],
);
const composerMenu = useComposerCommandMenu({
draftMessage: flow.prompt,
@@ -903,15 +915,19 @@ export function NewTaskDraftScreen(props: {
return;
}
const capabilities = selectedEnvironmentServerConfig?.environment.capabilities;
const insertion = flow.draftKey ? captureComposerDraftInsertion(flow.draftKey) : undefined;
const result = await pickComposerMedia({
existingCount: flow.attachments.length,
existingCount:
flow.draftKey && insertion
? countComposerDraftAttachmentsAfterSelection(flow.draftKey, insertion)
: flow.attachments.length,
maxVideoBytes:
capabilities?.attachmentUploads === true
? capabilities.fileAttachments?.maxUploadBytes
: undefined,
});
const rejectedCount =
result.attachments.length > 0 ? flow.appendAttachments(result.attachments) : 0;
result.attachments.length > 0 ? flow.appendAttachments(result.attachments, insertion) : 0;
const problems = [
...(result.error ? [result.error] : []),
...(rejectedCount > 0
@@ -933,11 +949,16 @@ export function NewTaskDraftScreen(props: {
Alert.alert("File attachments are not available on this server.");
return;
}
const insertion = flow.draftKey ? captureComposerDraftInsertion(flow.draftKey) : undefined;
const result = await pickComposerFiles({
existingCount: flow.attachments.length,
existingCount:
flow.draftKey && insertion
? countComposerDraftAttachmentsAfterSelection(flow.draftKey, insertion)
: flow.attachments.length,
maxBytes,
});
const rejectedCount = result.files.length > 0 ? flow.appendAttachments(result.files) : 0;
const rejectedCount =
result.files.length > 0 ? flow.appendAttachments(result.files, insertion) : 0;
// The picker error and the live-cap rejection can both happen in one
// pick; report both in a single alert.
const problems = [
@@ -954,12 +975,16 @@ export function NewTaskDraftScreen(props: {
const handleNativePasteImages = useCallback(
async (uris: ReadonlyArray<string>) => {
try {
const insertion = flow.draftKey ? captureComposerDraftInsertion(flow.draftKey) : undefined;
const images = await convertPastedImagesToAttachments({
uris,
existingCount: flow.attachments.length,
existingCount:
flow.draftKey && insertion
? countComposerDraftAttachmentsAfterSelection(flow.draftKey, insertion)
: flow.attachments.length,
});
if (images.length > 0) {
flow.appendAttachments(images);
flow.appendAttachments(images, insertion);
}
} catch (error) {
console.error("[native paste] error converting images", error);
@@ -968,8 +993,106 @@ export function NewTaskDraftScreen(props: {
[flow],
);
const handleNativePasteText = useCallback(
async (paste: ComposerTextPaste) => {
const draftKey = flow.draftKey;
if (!draftKey) return;
const insertion = { text: paste.value, ...paste.selection };
const insertPaste = () => {
const insertion = replaceTextSelection({
value: paste.value,
selection: paste.selection,
text: paste.text,
});
const selection = { start: insertion.cursor, end: insertion.cursor };
flow.setPrompt(insertion.value);
composerMenu.onSelectionChange(selection);
};
const capabilities = selectedEnvironmentServerConfig?.environment.capabilities;
const advertisedMax =
capabilities?.attachmentUploads === true
? capabilities.fileAttachments?.maxUploadBytes
: undefined;
const maxBytes =
advertisedMax === undefined ? null : clampFileAttachmentUploadBytes(advertisedMax);
const wouldExceedInputLimit =
paste.value.length -
Math.max(0, paste.selection.end - paste.selection.start) +
paste.text.length >
PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
const canAttach =
maxBytes !== null &&
countComposerDraftAttachmentsAfterSelection(draftKey, insertion) <
PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
new TextEncoder().encode(paste.text).byteLength <= maxBytes;
if (
pastedTextDisposition({
text: paste.text,
wouldExceedInputLimit,
canAttach: true,
}) === "attachment"
) {
if (canAttach && maxBytes !== null) {
pendingPastedTextAttachmentCountRef.current += 1;
setPendingPastedTextAttachmentCount(pendingPastedTextAttachmentCountRef.current);
try {
if (pastedTextFileNamesRef.current.draftKey !== draftKey) {
pastedTextFileNamesRef.current = { draftKey, names: new Set() };
}
const reservedNames = pastedTextFileNamesRef.current.names;
for (const attachment of flow.attachments) reservedNames.add(attachment.name);
const name = nextPastedTextFileName([...reservedNames]);
reservedNames.add(name);
const attachment = await createPastedTextComposerAttachment({
text: paste.text,
name,
maxBytes,
});
if (latestDraftKeyRef.current !== draftKey) {
await removePersistedComposerAttachmentFile(attachment.fileUri);
return;
}
if (flow.appendAttachments([attachment], insertion) > 0) {
await removePersistedComposerAttachmentFile(attachment.fileUri);
Alert.alert(
"Could not attach pasted text",
`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
);
}
} catch (error) {
Alert.alert(
"Could not attach pasted text",
error instanceof Error ? error.message : "Try again.",
);
} finally {
pendingPastedTextAttachmentCountRef.current = Math.max(
0,
pendingPastedTextAttachmentCountRef.current - 1,
);
setPendingPastedTextAttachmentCount(pendingPastedTextAttachmentCountRef.current);
}
} else if (!wouldExceedInputLimit) {
insertPaste();
} else {
Alert.alert(
wouldExceedInputLimit
? "Pasted text is too large for this message"
: "Could not attach pasted text",
wouldExceedInputLimit
? "Remove some text or an attachment, then paste again."
: "Remove an attachment or use a smaller paste, then try again.",
);
}
return;
}
insertPaste();
},
[composerMenu, flow, selectedEnvironmentServerConfig],
);
async function handleStart(): Promise<void> {
if (voiceInput.blocksSubmission) return;
if (voiceInput.blocksSubmission || pendingPastedTextAttachmentCountRef.current > 0) return;
const selectedProject = flow.selectedProject;
const draftKey = flow.draftKey;
if (!selectedProject || !draftKey) {
@@ -1139,6 +1262,7 @@ export function NewTaskDraftScreen(props: {
isIncomingShareReady &&
!isImportingShare &&
!flow.submitting &&
pendingPastedTextAttachmentCount === 0 &&
!voiceInput.blocksSubmission &&
!(flow.workspaceMode === "worktree" && !flow.selectedBranchName);
const openDraftDocument = (attachment: ComposerDocumentAttachment) => {
@@ -1195,6 +1319,7 @@ export function NewTaskDraftScreen(props: {
onFocus={() => setIsComposerFocused(true)}
onBlur={() => setIsComposerFocused(false)}
onPasteImages={(uris) => void handleNativePasteImages(uris)}
onPasteText={(paste) => void handleNativePasteText(paste)}
placeholder="Ask anything…"
singleLineCentered={false}
contentInsetVertical={0}
@@ -1486,13 +1611,15 @@ export function NewTaskDraftScreen(props: {
<ComposerActionButton
accessibilityLabel={
attachmentBlockReason ??
(flow.submitting
? "Starting task"
: attachmentsUploading
? "Queue task, sends when uploads finish"
: environmentConnected
? "Start task"
: "Queue task")
(pendingPastedTextAttachmentCount > 0
? "Attaching pasted text"
: flow.submitting
? "Starting task"
: attachmentsUploading
? "Queue task, sends when uploads finish"
: environmentConnected
? "Start task"
: "Queue task")
}
disabled={!canStart}
icon={queuesInsteadOfStarting ? "tray.and.arrow.up" : "arrow.up"}
@@ -1,14 +1,19 @@
import type { ComposerTextPaste } from "../../native/T3ComposerEditor.types";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
import { useAtomValue } from "@effect/atom-react";
import type {
EnvironmentId,
MessageId,
ModelSelection,
OrchestrationThreadShell,
ProviderInteractionMode,
RuntimeMode,
ServerConfig as T3ServerConfig,
UsageLimitsReport,
import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
import { pastedTextDisposition, replaceTextSelection } from "@t3tools/client-runtime/text-paste";
import {
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
type EnvironmentId,
type MessageId,
type ModelSelection,
type OrchestrationThreadShell,
type ProviderInteractionMode,
type RuntimeMode,
type ServerConfig as T3ServerConfig,
type UsageLimitsReport,
} from "@t3tools/contracts";
import {
collectProviderUsageLimits,
@@ -46,7 +51,10 @@ import Animated, {
import { useUniwindTheme } from "../../lib/useUniwindTheme";
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { composerContextImportsAtom } from "../../state/use-composer-drafts";
import {
composerContextImportsAtom,
countComposerDraftAttachmentsAfterSelection,
} from "../../state/use-composer-drafts";
import type { ComposerDocumentAttachment } from "../../lib/composerContext";
import { useProject } from "../../state/entities";
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
@@ -72,7 +80,6 @@ import {
type DraftComposerAttachment,
type DraftComposerFileAttachment,
} from "../../lib/composerImages";
import { collectComposerContextReferences } from "@t3tools/shared/composerContextReferences";
import {
buildModelOptions,
groupByProvider,
@@ -135,6 +142,7 @@ export interface ThreadComposerProps {
readonly onPickDraftMedia: () => Promise<void>;
readonly onPickDraftFiles: () => Promise<void>;
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
readonly onNativePasteText: (paste: ComposerTextPaste) => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void;
readonly onStopThread: () => void;
readonly onSendMessage: () => Promise<MessageId | null>;
@@ -278,6 +286,8 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const fallbackInputRef = useRef<ComposerEditorHandle>(null);
const inputRef = props.editorRef ?? fallbackInputRef;
const [isFocused, setIsFocused] = useState(false);
const pendingPastedTextAttachmentCountRef = useRef(0);
const [pendingPastedTextAttachmentCount, setPendingPastedTextAttachmentCount] = useState(0);
const settingsSheetPresentation = useThreadSettingsSheetPresentation({
editorRef: inputRef,
isEditorFocused: isFocused,
@@ -291,19 +301,10 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);
const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
// Attachment context ids are the attachment id, so the prompt alone says which attachments
// already read as an inline chip and need no strip tile.
// Only media belongs above the composer; every other file reads as its inline chip.
const stripAttachments = useMemo(
() =>
composerStripAttachments(
props.draftAttachments,
new Set(
collectComposerContextReferences(props.draftMessage).map(
(occurrence) => occurrence.contextId as string,
),
),
),
[props.draftAttachments, props.draftMessage],
() => composerStripAttachments(props.draftAttachments),
[props.draftAttachments],
);
const showStopAction =
!hasContent &&
@@ -422,7 +423,10 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
states: uploadStates,
});
const contextImports = useAtomValue(composerContextImportsAtom);
const sendBlockedReason = props.sendBlockedReason ?? attachmentBlockReason;
const sendBlockedReason =
props.sendBlockedReason ??
(pendingPastedTextAttachmentCount > 0 ? "Attaching pasted text" : null) ??
attachmentBlockReason;
const canSend =
hasContent &&
!contextImports[composerOwnerKey] &&
@@ -478,6 +482,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
onEditorFocusChange?.(false);
}, [onEditorFocusChange, onExpandedChange, settingsSheetPresentation.keepsComposerExpanded]);
const handleSend = useCallback(async () => {
if (voiceInput.blocksSubmission || pendingPastedTextAttachmentCountRef.current > 0) return;
// Typed out in full rather than picked from the menu. Attachments mean the
// user is sending a prompt, so those go through as usual.
if (
@@ -488,7 +493,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
if (openUsageLimits()) onChangeDraftMessage("");
return;
}
if (voiceInput.blocksSubmission) return;
const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
if (inFlightThreadIdsRef.current.has(threadKey)) return;
inFlightThreadIdsRef.current.add(threadKey);
@@ -736,6 +740,10 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
});
}}
onOpenAttachment={openDraftDocument}
// A rested composer full of chips left almost nowhere to tap to start typing:
// every chip opened its file instead. Collapsed, they focus the editor.
chipsInert={!isExpanded}
onInertChipPress={() => inputRef.current?.focus()}
ref={inputRef}
multiline
value={props.draftMessage}
@@ -745,6 +753,76 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
onChangeText={props.onChangeDraftMessage}
onSelectionChange={composerMenu.onSelectionChange}
onPasteImages={(uris) => void props.onNativePasteImages(uris)}
onPasteText={(paste) => {
const insertPaste = () => {
const insertion = replaceTextSelection({
value: paste.value,
selection: paste.selection,
text: paste.text,
});
const selection = { start: insertion.cursor, end: insertion.cursor };
props.onChangeDraftMessage(insertion.value);
composerMenu.onSelectionChange(selection);
};
const capabilities = props.serverConfig?.environment.capabilities;
const advertisedMax =
capabilities?.attachmentUploads === true
? capabilities.fileAttachments?.maxUploadBytes
: undefined;
const maxBytes =
advertisedMax === undefined
? null
: clampFileAttachmentUploadBytes(advertisedMax);
const wouldExceedInputLimit =
paste.value.length -
Math.max(0, paste.selection.end - paste.selection.start) +
paste.text.length >
PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
const canAttach =
maxBytes !== null &&
countComposerDraftAttachmentsAfterSelection(composerOwnerKey, {
text: paste.value,
...paste.selection,
}) < PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
new TextEncoder().encode(paste.text).byteLength <= maxBytes;
if (
pastedTextDisposition({
text: paste.text,
wouldExceedInputLimit,
canAttach: true,
}) === "attachment"
) {
if (canAttach) {
pendingPastedTextAttachmentCountRef.current += 1;
setPendingPastedTextAttachmentCount(
pendingPastedTextAttachmentCountRef.current,
);
const finishAttachment = () => {
pendingPastedTextAttachmentCountRef.current = Math.max(
0,
pendingPastedTextAttachmentCountRef.current - 1,
);
setPendingPastedTextAttachmentCount(
pendingPastedTextAttachmentCountRef.current,
);
};
void props.onNativePasteText(paste).then(finishAttachment, finishAttachment);
} else if (!wouldExceedInputLimit) {
insertPaste();
} else {
Alert.alert(
wouldExceedInputLimit
? "Pasted text is too large for this message"
: "Could not attach pasted text",
wouldExceedInputLimit
? "Remove some text or an attachment, then paste again."
: "Remove an attachment or use a smaller paste, then try again.",
);
}
return;
}
insertPaste();
}}
placeholder={props.placeholder}
onFocus={handleFocus}
onBlur={handleBlur}
@@ -1,3 +1,4 @@
import type { ComposerTextPaste } from "../../native/T3ComposerEditor.types";
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
import {
appendCodexArtifactTemplateUsePrompt,
@@ -155,6 +156,7 @@ export interface ThreadDetailScreenProps {
readonly onPickDraftMedia: () => Promise<void>;
readonly onPickDraftFiles: () => Promise<void>;
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
readonly onNativePasteText: (paste: ComposerTextPaste) => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void;
readonly onStopThread: () => void;
readonly onSendMessage: () => Promise<MessageId | null>;
@@ -1049,6 +1051,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
onPickDraftMedia={props.onPickDraftMedia}
onPickDraftFiles={props.onPickDraftFiles}
onNativePasteImages={props.onNativePasteImages}
onNativePasteText={props.onNativePasteText}
onRemoveDraftImage={props.onRemoveDraftImage}
onStopThread={props.onStopThread}
onSendMessage={handleSendMessage}
@@ -891,6 +891,7 @@ function ThreadRouteContent(
onPickDraftMedia={composer.onPickDraftMedia}
onPickDraftFiles={composer.onPickDraftFiles}
onNativePasteImages={composer.onNativePasteImages}
onNativePasteText={composer.onNativePasteText}
onRemoveDraftImage={composer.onRemoveDraftImage}
serverConfig={serverConfig}
onStopThread={handleStopThread}
@@ -44,6 +44,7 @@ import { projectEnvironment } from "../../state/projects";
import { useEnvironmentQuery } from "../../state/query";
import {
appendComposerDraftAttachments,
type ComposerDraftInsertion,
clearComposerDraft,
composerDraftsAtom,
createNewTaskDraft,
@@ -203,7 +204,10 @@ type NewTaskFlowContextValue = {
readonly setPrompt: (value: string) => void;
readonly replaceAttachments: (attachments: ReadonlyArray<DraftComposerAttachment>) => void;
/** Appends draft attachments; returns how many the live cap rejected. */
readonly appendAttachments: (attachments: ReadonlyArray<DraftComposerAttachment>) => number;
readonly appendAttachments: (
attachments: ReadonlyArray<DraftComposerAttachment>,
insertion?: ComposerDraftInsertion,
) => number;
readonly removeAttachment: (imageId: string) => void;
readonly clearAttachments: () => void;
readonly setSubmitting: (value: boolean) => void;
@@ -600,12 +604,16 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
// Returns how many attachments the live cap rejected so the caller can
// tell the user (a concurrent add can fill the draft mid-pick).
const appendAttachments = useCallback(
(nextAttachments: ReadonlyArray<DraftComposerAttachment>): number => {
(
nextAttachments: ReadonlyArray<DraftComposerAttachment>,
insertion?: ComposerDraftInsertion,
): number => {
if (!selectedProjectDraftKey) {
return 0;
}
return appendComposerDraftAttachments(selectedProjectDraftKey, nextAttachments, {
appendReference: true,
insertion,
});
},
[selectedProjectDraftKey],