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

@@ -20,6 +20,7 @@ import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import { useUniwindTheme } from "../../lib/useUniwindTheme";
import { removeComposerDraftAttachment, useComposerDraft } from "../../state/use-composer-drafts";
import { FileMarkdownPreview } from "./FileMarkdownPreview";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
import { SourceFileSurface } from "./SourceFileSurface";
import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview";
@@ -99,7 +100,7 @@ function AttachmentDocumentBody(props: {
</Text>
</View>
) : null}
{table && document.rendered ? (
{table && document.activeMode === "table" ? (
<ScrollView className="flex-1">
{table.truncated ? (
<View className="border-b border-warning-border bg-warning px-4 py-2">
@@ -137,7 +138,7 @@ function AttachmentDocumentBody(props: {
</View>
</ScrollView>
</ScrollView>
) : document.kind === "markdown" && document.rendered && props.environmentId ? (
) : document.activeMode === "markdown" && props.environmentId ? (
<FileMarkdownPreview
cwd=""
relativePath=""
@@ -147,7 +148,7 @@ function AttachmentDocumentBody(props: {
captured
/>
) : (
<SourceFileSurface contents={content.text} path={props.name} />
<SourceFileSurface contents={content.text} path={props.name} selectable />
)}
</View>
);
@@ -175,6 +176,7 @@ function AttachmentDocumentBody(props: {
export function AttachmentFileScreen(props: AttachmentFileScreenProps) {
const navigation = useNavigation();
const { appearance, setCodeWordBreak } = useAppearancePreferences();
const iconColor = useUniwindTheme()["--color-icon"];
const isAndroid = Platform.OS === "android";
const params = props.route.params;
@@ -249,7 +251,7 @@ export function AttachmentFileScreen(props: AttachmentFileScreenProps) {
handleBack();
}, [draftKey, handleBack, params.attachmentId]);
const { content, renderedMode, rendered, setRendered, share, sharing } = document;
const { content, renderedMode, activeMode, setRendered, share, sharing } = document;
const menuActions = useMemo(
() =>
[
@@ -271,6 +273,15 @@ export function AttachmentFileScreen(props: AttachmentFileScreenProps) {
onPress: () => setRendered(false),
} as const)
: null,
content && activeMode === "source"
? ({
id: "word-wrap",
title: appearance.codeWordBreak ? "Disable word wrap" : "Enable word wrap",
icon: "text.alignleft",
inline: false,
onPress: () => setCodeWordBreak(!appearance.codeWordBreak),
} as const)
: null,
content
? ({
id: "copy",
@@ -312,19 +323,31 @@ export function AttachmentFileScreen(props: AttachmentFileScreenProps) {
} as const)
: null,
].filter((action) => action !== null),
[content, draftKey, removeFromDraft, renderedMode, setRendered, share, sharing, uri],
[
appearance.codeWordBreak,
setCodeWordBreak,
content,
draftKey,
removeFromDraft,
activeMode,
renderedMode,
setRendered,
share,
sharing,
uri,
],
);
const activeMode = rendered ? "preview" : "source";
const selectedAction = activeMode === "source" ? "source" : "preview";
const androidMenuActions = useMemo<MenuAction[]>(
() =>
menuActions.map((action) => ({
id: action.id,
title: action.title,
image: action.icon,
state: action.inline ? (action.id === activeMode ? "on" : "off") : undefined,
state: action.inline ? (action.id === selectedAction ? "on" : "off") : undefined,
...("destructive" in action ? { attributes: { destructive: true } } : {}),
})),
[activeMode, menuActions],
[selectedAction, menuActions],
);
const handleAndroidMenuAction = useCallback(
(event: { nativeEvent: { event: string } }) => {
@@ -372,7 +395,7 @@ export function AttachmentFileScreen(props: AttachmentFileScreenProps) {
<NativeHeaderToolbar.MenuAction
key={action.id}
icon={action.icon}
isOn={action.id === activeMode}
isOn={action.id === selectedAction}
onPress={action.onPress}
>
{action.title}
@@ -2,7 +2,14 @@ import { useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import type { ComponentType } from "react";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { FlatList, ScrollView, Text as NativeText, useWindowDimensions, View } from "react-native";
import {
FlatList,
RefreshControl,
ScrollView,
Text as NativeText,
useWindowDimensions,
View,
} from "react-native";
import { AppText as Text } from "../../components/AppText";
import { LoadingStrip } from "../../components/LoadingStrip";
@@ -23,13 +30,17 @@ import {
NATIVE_SOURCE_CONTENT_WIDTH,
nativeSourceRowId,
} from "./nativeSourceFileAdapter";
import { prepareSourceFileDocument } from "./source-file-document";
import { MarkdownTextPrimitive } from "@t3tools/mobile-markdown-text/primitive";
import { boundedSelectableSourceTokens, prepareSourceFileDocument } from "./source-file-document";
import { sourceHighlightAtom } from "./sourceHighlightingState";
interface SourceFileSurfaceProps {
readonly contents: string;
readonly path: string;
readonly initialLine?: number | null;
/** Keep the entire document in one native text-selection scope. */
readonly selectable?: boolean;
/** Enables native pull-to-refresh on the source surface. */
readonly onRefresh?: () => Promise<void> | void;
}
@@ -129,7 +140,7 @@ function useSourceFileModel(props: SourceFileSurfaceProps) {
? "ready"
: "highlighting";
return { lines, rowsJson, status, targetIndex, theme, tokens };
return { normalizedContents, lines, rowsJson, status, targetIndex, theme, tokens };
}
function SourceHighlightStatusView(props: { readonly status: SourceHighlightStatus }) {
@@ -146,17 +157,7 @@ function SourceHighlightStatusView(props: { readonly status: SourceHighlightStat
return null;
}
function NativeSourceFileSurface(
props: SourceFileSurfaceProps & {
readonly NativeView: ComponentType<NativeReviewDiffViewProps>;
},
) {
const { NativeView, onRefresh } = props;
const { codeSurface, codeWordBreak, nativeSourceStyle } = useAppearanceCodeSurface();
const { themeAppearance, themeId } = useAppearancePreferences();
const appTheme = useUniwindTheme();
const { width: viewportWidth } = useWindowDimensions();
const { rowsJson, status, targetIndex, tokens } = useSourceFileModel(props);
function useSourceFileRefresh(onRefresh: SourceFileSurfaceProps["onRefresh"]) {
const [isPullRefreshing, setIsPullRefreshing] = useState(false);
const handlePullToRefresh = useCallback(async () => {
if (!onRefresh) {
@@ -169,6 +170,21 @@ function NativeSourceFileSurface(
setIsPullRefreshing(false);
}
}, [onRefresh]);
return { isPullRefreshing, handlePullToRefresh };
}
function NativeSourceFileSurface(
props: SourceFileSurfaceProps & {
readonly NativeView: ComponentType<NativeReviewDiffViewProps>;
},
) {
const { NativeView, onRefresh } = props;
const { codeSurface, codeWordBreak, nativeSourceStyle } = useAppearanceCodeSurface();
const { themeAppearance, themeId } = useAppearancePreferences();
const appTheme = useUniwindTheme();
const { width: viewportWidth } = useWindowDimensions();
const { rowsJson, status, targetIndex, tokens } = useSourceFileModel(props);
const { isPullRefreshing, handlePullToRefresh } = useSourceFileRefresh(onRefresh);
const tokensJson = useMemo(() => JSON.stringify(buildNativeSourceTokens(tokens)), [tokens]);
const selectedRowIdsJson = useMemo(
() => JSON.stringify(targetIndex === null ? [] : [nativeSourceRowId(targetIndex)]),
@@ -212,9 +228,18 @@ function NativeSourceFileSurface(
}
function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
const foreground = useUniwindTheme()["--color-foreground"];
const { codeSurface, codeWordBreak } = useAppearanceCodeSurface();
const { lines, status, targetIndex, tokens } = useSourceFileModel(props);
const { normalizedContents, lines, status, targetIndex, tokens } = useSourceFileModel(props);
const selectableTokens = useMemo(
() => (props.selectable ? boundedSelectableSourceTokens(tokens) : null),
[props.selectable, tokens],
);
const listRef = useRef<FlatList<string>>(null);
const { isPullRefreshing, handlePullToRefresh } = useSourceFileRefresh(props.onRefresh);
const refreshControl = props.onRefresh ? (
<RefreshControl refreshing={isPullRefreshing} onRefresh={() => void handlePullToRefresh()} />
) : undefined;
useEffect(() => {
if (targetIndex === null) {
@@ -240,9 +265,59 @@ function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
[codeSurface, codeWordBreak, targetIndex, tokens],
);
// One selectable text for the whole file. On iOS `uiTextView` renders a real `UITextView`,
// which selects across every line, wraps, and lays out long documents through TextKit; on
// Android the primitive is an RN `Text`, which selects across its nested children. Either
// way "select all" takes the file rather than a line, which a `FlatList` row can never do
// because each row is its own selection scope.
const selectableBlock = props.selectable ? (
<MarkdownTextPrimitive
uiTextView
selectable
style={{
color: foreground,
fontFamily: REVIEW_MONO_FONT_FAMILY,
fontSize: codeSurface.fontSize,
lineHeight: codeSurface.rowHeight,
}}
>
{selectableTokens
? lines.map((line, index) => {
const lineTokens = selectableTokens[index] ?? null;
const body =
lineTokens && lineTokens.length > 0
? lineTokens.map((token, tokenIndex) => (
<MarkdownTextPrimitive
key={`${index}:${tokenIndex}`}
style={{
color: token.color ?? foreground,
fontWeight:
token.fontStyle !== null && (token.fontStyle & 2) === 2 ? "700" : "400",
fontStyle:
token.fontStyle !== null && (token.fontStyle & 1) === 1
? "italic"
: "normal",
}}
>
{token.content}
</MarkdownTextPrimitive>
))
: line;
return (
<MarkdownTextPrimitive key={index}>
{body}
{index < lines.length - 1 ? "\n" : ""}
</MarkdownTextPrimitive>
);
})
: normalizedContents}
</MarkdownTextPrimitive>
) : null;
const list = (
<FlatList
ref={listRef}
refreshControl={refreshControl}
data={lines}
keyExtractor={(_line, index) => String(index)}
initialNumToRender={80}
@@ -266,14 +341,40 @@ function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
/>
);
// Workspace files retain their numbered, virtualized rows, with or without a line target.
// Attachments opt into one selection scope for the entire document.
const usesLineList = !props.selectable;
const padded = (
<ScrollView
refreshControl={refreshControl}
className="flex-1"
contentContainerStyle={{
paddingBottom: codeSurface.rowHeight,
paddingHorizontal: 12,
paddingTop: 8,
}}
>
{selectableBlock}
</ScrollView>
);
return (
<View className="relative flex-1 bg-sheet">
<SourceHighlightStatusView status={status} />
{codeWordBreak ? (
list
{usesLineList ? (
codeWordBreak ? (
list
) : (
<ScrollView horizontal bounces={false} className="flex-1">
{list}
</ScrollView>
)
) : codeWordBreak ? (
padded
) : (
// Without wrapping the text keeps its natural width and the reader pans to it.
<ScrollView horizontal bounces={false} className="flex-1">
{list}
{padded}
</ScrollView>
)}
</View>
@@ -282,7 +383,11 @@ function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
export function SourceFileSurface(props: SourceFileSurfaceProps) {
const NativeView = resolveNativeReviewDiffView();
return NativeView ? (
const { codeWordBreak } = useAppearanceCodeSurface();
// The native canvas draws source lines without text selection or wrapping. Attachments
// need one selectable text view in either wrap mode; workspace line navigation can still
// use the canvas when wrapping is disabled.
return NativeView && !codeWordBreak && !props.selectable ? (
<NativeSourceFileSurface {...props} NativeView={NativeView} />
) : (
<JavaScriptSourceFileSurface {...props} />
@@ -583,6 +583,7 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
useAdaptiveWorkspacePaneRole("inspector");
const navigation = useNavigation();
const { fileInspector, panes, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
const { appearance, setCodeWordBreak } = useAppearancePreferences();
const iconColor = useUniwindTheme()["--color-icon"];
const isAndroid = Platform.OS === "android";
const params = props.route.params;
@@ -763,6 +764,16 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
onPress: () => setModeOverride({ path: relativePath, mode: "source" }),
} as const)
: null,
// Only the source body wraps; a rendered preview lays itself out.
resolvedActiveMode === "source"
? ({
id: "word-wrap",
title: appearance.codeWordBreak ? "Disable word wrap" : "Enable word wrap",
icon: "text.alignleft",
inline: false,
onPress: () => setCodeWordBreak(!appearance.codeWordBreak),
} as const)
: null,
...(mediaSource
? mediaActions.actions
.filter(({ id }) => id !== "open-file")
@@ -783,6 +794,17 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
onPress: () => copyTextWithHaptic(relativePath),
} as const,
]),
// Selecting a long file by hand is painful on a phone, so copying the whole thing is
// the action most readers actually want. The attachment screen already offers it.
fileData?.contents != null
? ({
id: "copy-contents",
title: fileData.truncated ? "Copy preview" : "Copy contents",
icon: "doc.on.doc",
inline: false,
onPress: () => copyTextWithHaptic(fileData.contents),
} as const)
: null,
isPdfFile({ name: relativePath }) && previewUri !== null
? ({
id: "open-pdf",
@@ -821,6 +843,8 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
: null,
].filter((action) => action !== null);
}, [
appearance.codeWordBreak,
setCodeWordBreak,
assetPreviewUri,
assetPreview.refresh,
previewUri,
@@ -833,6 +857,8 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
resolvedActiveMode,
mediaSource,
mediaActions.actions,
fileData?.contents,
fileData?.truncated,
]);
const androidFileMenuActions = useMemo<MenuAction[]>(
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import { prepareSourceFileDocument } from "./source-file-document";
import { boundedSelectableSourceTokens, prepareSourceFileDocument } from "./source-file-document";
describe("prepareSourceFileDocument", () => {
it("normalizes and serializes source rows once for repeated consumers", () => {
@@ -14,3 +14,14 @@ describe("prepareSourceFileDocument", () => {
expect(second).toBe(first);
});
});
it("bounds selectable highlighting without allocating spans for huge files", () => {
const token = { content: "text", color: "#fff", fontStyle: null };
const small = [[token]];
expect(boundedSelectableSourceTokens(small)).toBe(small);
expect(boundedSelectableSourceTokens(null)).toBeNull();
expect(boundedSelectableSourceTokens(Array.from({ length: 20_000 }, () => [token]))).toBeNull();
expect(boundedSelectableSourceTokens([Array.from({ length: 2_000 }, () => token)])).toBeNull();
const longPlainText = "full contents\n".repeat(50_000);
expect(prepareSourceFileDocument(longPlainText).contents).toBe(longPlainText);
});
@@ -1,3 +1,4 @@
import type { ReviewHighlightedToken } from "../review/shikiReviewHighlighter";
import { buildNativeSourceRows } from "./nativeSourceFileAdapter";
const MAX_CACHED_DOCUMENTS = 8;
@@ -52,3 +53,17 @@ export function prepareSourceFileDocument(contents: string): SourceFileDocument
return document;
}
// A selectable document cannot virtualize its rows. Cap React spans instead; large
// attachments remain fully selectable as one plain string, including every newline.
export function boundedSelectableSourceTokens(
tokens: ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>> | null,
): typeof tokens {
if (!tokens) return null;
let spans = tokens.length;
for (const line of tokens) {
spans += line.length;
if (spans > 2_000) return null;
}
return tokens;
}
@@ -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],