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,13 +226,15 @@ function ComposerAttachmentContent(props: ComposerAttachmentThumbnailProps) {
// The document picker types every pick as a plain file, so a picture arrives here as one.
// What it *is* decides how it presents, the same way videos are already recognised below.
if (attachment.type === "image" || imageMimeType(attachment) !== null) {
// A pasted-text marker does not fit the snapshot source a picture carries.
const { source: _droppedSource, ...rest } = attachment;
return (
<ComposerImageAttachment
{...props}
attachment={
attachment.type === "image"
? attachment
: { ...attachment, type: "image", previewUri: attachment.fileUri }
: { ...rest, type: "image", previewUri: attachment.fileUri }
}
/>
);
+44 -27
View File
@@ -9,17 +9,16 @@ import type { ComposerEditorProps as NativeComposerEditorProps } from "../native
import {
appendComposerDraftAttachments,
createComposerDraftContextHistory,
getComposerDraftAfterSelection,
getComposerDraftSnapshot,
insertComposerDraftContext,
insertComposerDraftText,
rememberComposerDraftSelection,
setComposerDraftContext,
setComposerContextImporting,
useComposerDraft,
} from "../state/use-composer-drafts";
import {
importComposerContextClipboard,
type NativeContextClipboard,
} from "../lib/composerContextClipboard";
import { importComposerContextClipboard } from "../lib/composerContextClipboard";
import { ComposerContextSheet } from "./ComposerContextSheet";
import { AppText as Text } from "./AppText";
import {
@@ -34,6 +33,14 @@ export type ComposerEditorProps = NativeComposerEditorProps & {
readonly onOpenMention?: (path: string) => void;
/** Documents open in the file screen; pictures, video and PDF keep their native viewers. */
readonly onOpenAttachment?: (attachment: ComposerDocumentAttachment) => void;
/**
* A resting composer is a target to type in, not a document to navigate. Its chips go inert
* so a draft full of them can still be tapped anywhere to start writing; the caller focuses
* the editor instead. Chips become live again once the composer is open.
*/
readonly chipsInert?: boolean;
/** Called instead of opening a chip while `chipsInert` is set. */
readonly onInertChipPress?: () => void;
};
export function ComposerEditor({
@@ -41,6 +48,8 @@ export function ComposerEditor({
environmentId,
onOpenMention,
onOpenAttachment,
chipsInert,
onInertChipPress,
...props
}: ComposerEditorProps) {
const draft = useComposerDraft(draftKey ?? null);
@@ -68,40 +77,35 @@ export function ComposerEditor({
},
[draftKey],
);
const pasteContext = async (clipboard: NativeContextClipboard) => {
const pasteContext = async (
clipboard: Parameters<NonNullable<NativeComposerEditorProps["onPasteContext"]>>[0],
) => {
if (!draftKey || importRef.current || props.readOnly || props.editable === false) return;
const insertion = { text: clipboard.value, ...clipboard.selection };
const controller = new AbortController();
importRef.current = controller;
setImporting(true);
setComposerContextImporting(draftKey, true);
try {
const retained = getComposerDraftAfterSelection(draftKey, insertion);
const result = await importComposerContextClipboard(
clipboard,
getComposerDraftSnapshot(draftKey).attachments.length,
retained.attachments.length,
controller.signal,
getComposerDraftSnapshot(draftKey).context?.records.length ?? 0,
retained.context?.records.length ?? 0,
);
if (!result) {
insertComposerDraftContext(draftKey, {
text: clipboard.text,
context: { version: 1, records: [] },
});
insertComposerDraftText(draftKey, clipboard.text, insertion);
return;
}
const rejected = appendComposerDraftAttachments(draftKey, result.attachments);
const ids = new Set(
getComposerDraftSnapshot(draftKey).attachments.map((attachment) => attachment.id),
);
insertComposerDraftContext(draftKey, {
text: result.text,
context: {
version: 1,
records: result.context.records.filter(
(record) => !("attachmentId" in record) || ids.has(record.attachmentId),
),
},
});
if (result.failures.length > 0 || rejected > 0)
if (!insertComposerDraftContext(draftKey, result, insertion)) {
Alert.alert(
"Could not paste context",
"Remove some attachments or context items from the draft, then paste again.",
);
return;
}
if (result.failures.length > 0)
Alert.alert(
"Some attachments could not be copied",
"Reconnect to the source environment and copy them again. References without their files are marked unavailable.",
@@ -161,6 +165,10 @@ export function ComposerEditor({
onPasteContext={(clipboard) => void pasteContext(clipboard)}
context={draft.context}
onContextPress={(selection) => {
if (chipsInert) {
onInertChipPress?.();
return;
}
const path = composerMentionPath(selection.source, draft.context);
if (path && onOpenMention) {
onOpenMention(path);
@@ -174,7 +182,12 @@ export function ComposerEditor({
setSelected(selection);
}}
onSelectionChange={(selection) => {
if (draftKey) rememberComposerDraftSelection(draftKey, props.value, selection);
if (draftKey)
rememberComposerDraftSelection(
draftKey,
getComposerDraftSnapshot(draftKey).text,
selection,
);
props.onSelectionChange?.(selection);
}}
/>
@@ -229,4 +242,8 @@ export function ComposerEditor({
</>
);
}
export type { ComposerEditorHandle, ComposerEditorSelection } from "../native/T3ComposerEditor";
export type {
ComposerEditorHandle,
ComposerEditorSelection,
ComposerTextPaste,
} from "../native/T3ComposerEditor";
@@ -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],
@@ -90,6 +90,13 @@ describe("appearancePreferences", () => {
expect(resolveAppearancePreferences({ codeWordBreak: true }).codeWordBreak).toBe(true);
});
it("preserves the no-wrap default unless wrapping is explicitly enabled", () => {
expect(resolveAppearancePreferences(undefined).codeWordBreak).toBe(false);
expect(resolveAppearancePreferences({}).codeWordBreak).toBe(false);
expect(resolveAppearancePreferences({ codeWordBreak: null }).codeWordBreak).toBe(false);
expect(resolveAppearancePreferences({ codeWordBreak: false }).codeWordBreak).toBe(false);
});
it("returns the authored text scale at the 16pt default", () => {
expect(DEFAULT_BASE_FONT_SIZE).toBe(16);
+8 -3
View File
@@ -11,6 +11,7 @@ import type { FileBackedComposerAttachment } from "./composerImages";
import { loadLocalAttachmentPreview } from "./localAttachmentPreview";
import { downloadAndShareAttachment, shareLocalAttachment } from "./attachmentDownload";
import { useRefreshAssetUrl } from "../state/assets";
import { attachmentDocumentPresentation } from "./attachmentDocumentPresentation";
const isLocalUri = (uri: string) => /^(file|content):/.test(uri);
@@ -32,8 +33,6 @@ export function useAttachmentDocument(input: {
}) {
const kind = filePreviewKind(input);
const delimiter = filePreviewDelimiter(input);
const renderedMode =
kind === "markdown" ? "markdown" : kind === "html" ? "html" : delimiter ? "table" : null;
const shareController = useRef<AbortController | null>(null);
useEffect(() => () => shareController.current?.abort(), []);
const resource = useMemo(
@@ -61,6 +60,12 @@ export function useAttachmentDocument(input: {
const [contentError, setContentError] = useState<string | null>(null);
const textReadUrl = useRef<{ uri: string; authorizedAt: number } | null>(null);
const [rendered, setRendered] = useState(true);
const presentation = attachmentDocumentPresentation({
kind,
hasTable: table !== null,
hasEnvironment: input.environmentId !== null,
rendered,
});
const [revision, setRevision] = useState(0);
const [sharing, setSharing] = useState(false);
const uri = input.attachment ? localUri : remoteUri;
@@ -185,7 +190,7 @@ export function useAttachmentDocument(input: {
};
return {
kind,
renderedMode,
...presentation,
uri,
/** Native viewers resolve their own fresh URL from this instead of reusing `uri`. */
resource,
@@ -0,0 +1,71 @@
import { expect, it } from "vite-plus/test";
import { attachmentDocumentPresentation } from "./attachmentDocumentPresentation";
it.each([
{
kind: "markdown",
hasTable: false,
hasEnvironment: false,
rendered: true,
renderedMode: null,
activeMode: "source",
},
{
kind: "markdown",
hasTable: false,
hasEnvironment: true,
rendered: true,
renderedMode: "markdown",
activeMode: "markdown",
},
{
kind: "markdown",
hasTable: false,
hasEnvironment: true,
rendered: false,
renderedMode: "markdown",
activeMode: "source",
},
{
kind: "text",
hasTable: false,
hasEnvironment: true,
rendered: true,
renderedMode: null,
activeMode: "source",
},
{
kind: "text",
hasTable: true,
hasEnvironment: false,
rendered: true,
renderedMode: "table",
activeMode: "table",
},
{
kind: "text",
hasTable: true,
hasEnvironment: true,
rendered: false,
renderedMode: "table",
activeMode: "source",
},
{
kind: "html",
hasTable: false,
hasEnvironment: false,
rendered: true,
renderedMode: "html",
activeMode: "html",
},
{
kind: "html",
hasTable: false,
hasEnvironment: true,
rendered: false,
renderedMode: "html",
activeMode: "source",
},
] as const)("matches the available preview for %j", ({ renderedMode, activeMode, ...input }) => {
expect(attachmentDocumentPresentation(input)).toEqual({ renderedMode, activeMode });
});
@@ -0,0 +1,21 @@
import type { FilePreviewKind } from "@t3tools/shared/filePreview";
/** The available preview and selected body must agree, including source-only draft files. */
export function attachmentDocumentPresentation(input: {
kind: FilePreviewKind;
hasTable: boolean;
hasEnvironment: boolean;
rendered: boolean;
}) {
const renderedMode = input.hasTable
? "table"
: input.kind === "markdown" && input.hasEnvironment
? "markdown"
: input.kind === "html"
? "html"
: null;
return {
renderedMode,
activeMode: input.rendered && renderedMode !== null ? renderedMode : "source",
} as const;
}
+10 -2
View File
@@ -360,7 +360,14 @@ describe("prepareTurnAttachments", () => {
});
it("uploads generic file bytes directly and keeps mixed attachment order", async () => {
const prepared = await prepareTurnAttachments({ environmentId, attachments: [file, image] });
const pastedFile = {
...file,
source: { _tag: "pasted-text" as const },
};
const prepared = await prepareTurnAttachments({
environmentId,
attachments: [pastedFile, image],
});
expect(mocks.upload).toHaveBeenCalledWith(
"file:///documents/report.pdf",
@@ -379,11 +386,12 @@ describe("prepareTurnAttachments", () => {
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 42,
source: { _tag: "pasted-text" },
});
expect(prepared.attachments[1]?.type).toBe("image");
expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]);
expect(prepared.draftAttachments[0]).toEqual({
...file,
...pastedFile,
uploadedAttachmentId: MINTED_ID,
uploadEnvironmentId: environmentId,
});
+5 -1
View File
@@ -198,7 +198,11 @@ function uploadedReference(
// chat view with nothing to show a thumbnail from, on every client.
return isComposerImageAttachment(attachment)
? { type: "image", ...fields }
: { type: "file", ...fields };
: {
type: "file",
...fields,
...(attachment.source ? { source: attachment.source } : {}),
};
}
function attachmentUploadInput(attachment: DraftComposerAttachment) {
+2 -1
View File
@@ -1,5 +1,5 @@
import * as Schema from "effect/Schema";
import { EnvironmentId } from "@t3tools/contracts";
import { EnvironmentId, PastedTextAttachmentSource } from "@t3tools/contracts";
export const DraftComposerImageAttachmentSchema = Schema.Struct({
id: Schema.String,
@@ -29,6 +29,7 @@ export const DraftComposerFileAttachmentSchema = Schema.Struct({
mimeType: Schema.String,
sizeBytes: Schema.Number,
fileUri: Schema.String,
source: Schema.optional(PastedTextAttachmentSource),
uploadedAttachmentId: Schema.optional(Schema.String),
uploadEnvironmentId: Schema.optional(EnvironmentId),
});
+139 -11
View File
@@ -1,14 +1,28 @@
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS } from "@t3tools/contracts";
const files = new Map<string, { base64: string; deleted: boolean }>();
const files = new Map<string, { base64: string; deleted: boolean; text?: string }>();
const clipboard = vi.hoisted(() => ({
hasImageAsync: vi.fn(),
getImageAsync: vi.fn(),
hasStringAsync: vi.fn(),
getStringAsync: vi.fn(),
}));
vi.mock("expo-clipboard", () => clipboard);
vi.mock("expo-file-system", () => ({
File: class {
readonly uri: string;
readonly name: string;
readonly parentDirectory: { readonly uri: string };
constructor(uri: string) {
this.uri = uri;
constructor(parent: string | { readonly uri: string }, name?: string) {
const parentUri = typeof parent === "string" ? parent : parent.uri;
this.uri = name ? `${parentUri}/${name}` : parentUri;
this.name = name ?? this.uri.split("/").at(-1) ?? "file";
this.parentDirectory = { uri: this.uri.slice(0, -(this.name.length + 1)) };
}
get exists(): boolean {
@@ -29,14 +43,90 @@ vi.mock("expo-file-system", () => ({
entry.deleted = true;
}
}
create(): void {
files.set(this.uri, { base64: "", deleted: false });
}
write(text: string): void {
files.set(this.uri, { base64: "", deleted: false, text });
}
moveSync(destination: { readonly uri: string }): void {
const entry = files.get(this.uri);
if (!entry) throw new Error("missing staged file");
files.set(destination.uri, entry);
files.delete(this.uri);
}
},
Directory: class {
readonly uri: string;
constructor(parent: string, name: string) {
this.uri = `${parent}/${name}`;
}
create(): void {}
},
Paths: { document: "file:///documents" },
}));
vi.mock("./uuid", () => ({
uuidv4: () => "attachment-id",
}));
import { convertPastedImagesToAttachments, isOwnedPastedImageUri } from "./composerImages";
import {
convertPastedImagesToAttachments,
createPastedTextComposerAttachment,
isOwnedPastedImageUri,
pasteComposerClipboard,
} from "./composerImages";
describe("composer clipboard paste", () => {
beforeEach(() => {
vi.clearAllMocks();
clipboard.hasImageAsync.mockResolvedValue(false);
clipboard.hasStringAsync.mockResolvedValue(true);
clipboard.getStringAsync.mockResolvedValue("clipboard text");
clipboard.getImageAsync.mockResolvedValue({ data: "data:image/png;base64,aGVsbG8=" });
});
it("returns only the image when the clipboard contains both image and text", async () => {
clipboard.hasImageAsync.mockResolvedValue(true);
const result = await pasteComposerClipboard({ existingCount: 0 });
expect(result).toEqual({
images: [expect.objectContaining({ type: "image", name: "pasted-image.png" })],
text: null,
error: null,
});
expect(clipboard.getStringAsync).not.toHaveBeenCalled();
});
it("does not paste alternate text when the image cannot fit", async () => {
clipboard.hasImageAsync.mockResolvedValue(true);
expect(
await pasteComposerClipboard({ existingCount: PROVIDER_SEND_TURN_MAX_ATTACHMENTS }),
).toEqual({ images: [], text: null, error: expect.stringContaining("up to") });
expect(clipboard.getStringAsync).not.toHaveBeenCalled();
});
it("returns plain text without image chips", async () => {
expect(await pasteComposerClipboard({ existingCount: 0 })).toEqual({
images: [],
text: "clipboard text",
error: null,
});
});
it("reports an empty text clipboard", async () => {
clipboard.getStringAsync.mockResolvedValue("");
expect(await pasteComposerClipboard({ existingCount: 0 })).toEqual({
images: [],
text: null,
error: "Clipboard is empty.",
});
});
});
describe("native pasted image cleanup", () => {
beforeEach(() => {
@@ -91,6 +181,26 @@ describe("native pasted image cleanup", () => {
expect(files.get(overflow)?.deleted).toBe(true);
expect(files.get(userOwned)?.deleted).toBe(false);
});
it("persists folded text unchanged in the app-owned attachment directory", async () => {
const text = "first line\nUnicode: 🙂\n";
const attachment = await createPastedTextComposerAttachment({
text,
name: "pasted-text.txt",
maxBytes: 1024,
});
expect(attachment).toEqual({
id: "attachment-id",
type: "file",
name: "pasted-text.txt",
mimeType: "text/plain;charset=utf-8",
sizeBytes: new TextEncoder().encode(text).byteLength,
fileUri: "file:///documents/t3-composer-attachments/attachment-id-pasted-text.txt",
source: { _tag: "pasted-text" },
});
expect(files.get(attachment.fileUri)?.text).toBe(text);
});
});
describe("composerStripAttachments", () => {
@@ -119,21 +229,39 @@ describe("composerStripAttachments", () => {
fileUri: "file:///notes.txt",
};
it("keeps media even when it already has an inline chip", async () => {
it("keeps media, because a thumbnail is the only way to see it", async () => {
const { composerStripAttachments } = await import("./composerImages");
const kept = composerStripAttachments([image, video] as never, new Set(["img-1", "vid-1"]));
// A thumbnail is the only way to see media, so it stays regardless of the chip.
const kept = composerStripAttachments([image, video] as never);
expect(kept.map((a) => a.id)).toEqual(["img-1", "vid-1"]);
});
it("drops a plain file once its inline chip represents it", async () => {
it("never shows a non-media file above the composer", async () => {
const { composerStripAttachments } = await import("./composerImages");
expect(composerStripAttachments([doc] as never, new Set(["doc-1"]))).toEqual([]);
// A document reads as its inline chip. A tile with a generic glyph says less than the
// chip does, so it is not a fallback worth having, chip present or not.
expect(composerStripAttachments([doc] as never)).toEqual([]);
});
it("keeps a plain file that has no inline chip", async () => {
it("keeps media beside a document rather than dropping the whole strip", async () => {
const { composerStripAttachments } = await import("./composerImages");
expect(composerStripAttachments([doc] as never, new Set()).map((a) => a.id)).toEqual(["doc-1"]);
expect(composerStripAttachments([doc, image, video] as never).map((a) => a.id)).toEqual([
"img-1",
"vid-1",
]);
});
it("treats a picture picked through the document picker as media", async () => {
const { composerStripAttachments } = await import("./composerImages");
// The document picker types every pick as a plain file; what it *is* decides the strip.
const pickedImage = {
id: "pick-1",
type: "file" as const,
name: "photo.png",
mimeType: "image/png",
sizeBytes: 30,
fileUri: "file:///photo.png",
};
expect(composerStripAttachments([pickedImage] as never).map((a) => a.id)).toEqual(["pick-1"]);
});
});
+57 -16
View File
@@ -8,6 +8,7 @@ import {
PROVIDER_SEND_TURN_MAX_FILE_BYTES,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
type EnvironmentId,
type PastedTextAttachmentSource,
type UploadChatImageAttachment,
} from "@t3tools/contracts";
import type { DocumentPickerResult } from "expo-document-picker";
@@ -21,6 +22,7 @@ import { imageMimeType } from "@t3tools/shared/image";
import { videoMimeType } from "@t3tools/shared/video";
import { beginForegroundHandoff } from "./foreground-handoff";
import { uuidv4 } from "./uuid";
import { writeFileAtomically } from "./atomic-file";
export interface DraftComposerImageAttachment extends Omit<UploadChatImageAttachment, "dataUrl"> {
readonly id: string;
@@ -40,27 +42,59 @@ export interface DraftComposerFileAttachment {
readonly mimeType: string;
readonly sizeBytes: number;
readonly fileUri: string;
readonly source?: PastedTextAttachmentSource;
readonly uploadedAttachmentId?: string;
readonly uploadEnvironmentId?: EnvironmentId;
}
export async function createPastedTextComposerAttachment(input: {
readonly text: string;
readonly name: string;
readonly maxBytes: number;
}): Promise<DraftComposerFileAttachment> {
const bytes = new TextEncoder().encode(input.text).byteLength;
if (bytes <= 0) {
throw new Error("Clipboard is empty.");
}
if (bytes > input.maxBytes) {
throw new Error(fileAttachmentTooLargeMessage(input.name, input.maxBytes));
}
const { Directory, File, Paths } = await import("expo-file-system");
const directory = new Directory(Paths.document, COMPOSER_ATTACHMENT_DIRECTORY);
directory.create({ idempotent: true, intermediates: true });
const file = new File(directory, `${uuidv4()}-${input.name}`);
await writeFileAtomically(file, input.text);
return {
id: uuidv4(),
type: "file",
name: input.name,
mimeType: "text/plain;charset=utf-8",
sizeBytes: bytes,
fileUri: file.uri,
source: { _tag: "pasted-text" },
};
}
export type DraftComposerAttachment = DraftComposerImageAttachment | DraftComposerFileAttachment;
/**
* What the strip above the composer shows. Media previews there because a thumbnail is the
* only way to see it; every other file is already legible as its inline chip, so it only
* falls back to the strip when the prompt carries no reference to it. Mirrors web's
* `composerOtherFilesForPresentation`.
* What the strip above the composer shows: media, and nothing else. A thumbnail is the only
* way to see a picture or a video, so those always preview there. Everything else reads as
* its inline chip, which carries the name, the type and the size in the line of prose the
* file belongs to — a square tile showing a generic document glyph says strictly less.
*
* The chip is not optional for a non-media file. Every path that attaches one also writes
* its reference, so a file with no chip means the draft lost it rather than that the strip
* should stand in. Which attachments carry a chip is therefore not consulted at all; surfaces
* whose attachments never get chips (a question answer) pass them to the strip directly
* instead of through this filter.
*/
export function composerStripAttachments(
attachments: ReadonlyArray<DraftComposerAttachment>,
inlineAttachmentIds: ReadonlySet<string>,
): ReadonlyArray<DraftComposerAttachment> {
return attachments.filter(
(attachment) =>
isComposerImageAttachment(attachment) ||
videoMimeType(attachment) !== null ||
!inlineAttachmentIds.has(attachment.id),
(attachment) => isComposerImageAttachment(attachment) || videoMimeType(attachment) !== null,
);
}
@@ -539,11 +573,19 @@ export async function pickComposerMedia(input: {
};
}
export async function pasteComposerClipboard(input: { readonly existingCount: number }): Promise<{
readonly images: ReadonlyArray<DraftComposerImageAttachment>;
readonly text: string | null;
readonly error: string | null;
}> {
/** Clipboard images take priority over their alternate text representation. */
export async function pasteComposerClipboard(input: { readonly existingCount: number }): Promise<
| {
readonly images: ReadonlyArray<DraftComposerImageAttachment>;
readonly text: null;
readonly error: string | null;
}
| {
readonly images: readonly [];
readonly text: string;
readonly error: null;
}
> {
let clipboard: Awaited<ReturnType<typeof loadClipboard>>;
try {
clipboard = await loadClipboard();
@@ -605,8 +647,7 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu
const text = await clipboard.getStringAsync();
return {
images: [],
text: text.length > 0 ? text : null,
error: text.length > 0 ? null : "Clipboard is empty.",
...(text.length > 0 ? { text, error: null } : { text: null, error: "Clipboard is empty." }),
};
}
@@ -1,3 +1,5 @@
import { PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES } from "@t3tools/client-runtime/text-paste";
import { PROVIDER_SEND_TURN_MAX_INPUT_CHARS } from "@t3tools/contracts";
import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens";
import { composerContextEditorTokens } from "../lib/composerContext";
import { requireNativeView } from "expo";
@@ -52,6 +54,13 @@ type NativePasteImagesEvent = NativeSyntheticEvent<{
readonly uris: ReadonlyArray<string>;
}>;
type NativePasteTextEvent = NativeSyntheticEvent<{
readonly value: string;
readonly eventCount: number;
readonly text: string;
readonly selection: ComposerEditorSelection;
}>;
interface NativeComposerEditorRef {
focus: () => Promise<void>;
blur: () => Promise<void>;
@@ -81,8 +90,11 @@ interface NativeComposerEditorProps extends ViewProps {
event: NativeSyntheticEvent<{ source: string; start: number; end: number }>,
) => void;
readonly onComposerPasteContext?: (
event: NativeSyntheticEvent<{ text: string; fragment: string; html: string }>,
event: NativePasteTextEvent & NativeSyntheticEvent<{ fragment: string; html: string }>,
) => void;
readonly textPasteThresholdBytes: number;
readonly maxInputChars: number;
readonly onComposerPasteText?: (event: NativePasteTextEvent) => void;
readonly onComposerFocus?: () => void;
readonly onComposerBlur?: () => void;
readonly onComposerSubmit?: () => void;
@@ -108,6 +120,7 @@ export function ComposerEditor({
onChangeText,
onSelectionChange,
onPasteImages,
onPasteText,
onFocus,
onBlur,
onSubmit,
@@ -282,6 +295,8 @@ export function ComposerEditor({
autoFocus={props.autoFocus ?? false}
autoCorrect={props.autoCorrect ?? true}
spellCheck={props.spellCheck ?? true}
textPasteThresholdBytes={onPasteText ? PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES : 0}
maxInputChars={PROVIDER_SEND_TURN_MAX_INPUT_CHARS}
style={style as StyleProp<ViewStyle>}
onComposerChange={(event) => {
const acknowledgedEventCount = acceptNativeEvent(
@@ -315,7 +330,36 @@ export function ComposerEditor({
}}
onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)}
onComposerPasteContext={(event) => props.onPasteContext?.(event.nativeEvent)}
onComposerPasteContext={(event) => {
const paste = event.nativeEvent;
const acknowledgedEventCount = acceptNativeEvent(
paste.eventCount,
paste.value,
paste.selection,
);
if (acknowledgedEventCount === false) return;
onChangeText(paste.value);
onSelectionChange?.(paste.selection);
props.onPasteContext?.(paste);
setMostRecentEventCount(acknowledgedEventCount);
forceNativeEventRender((sequence) => sequence + 1);
}}
onComposerPasteText={(event) => {
const paste = event.nativeEvent;
const acknowledgedEventCount = acceptNativeEvent(
paste.eventCount,
paste.value,
paste.selection,
);
if (acknowledgedEventCount === false) return;
// Synchronize the draft before an async paste captures its insertion target.
// React props can still precede the last native keystroke.
onChangeText(paste.value);
onSelectionChange?.(paste.selection);
onPasteText?.(paste);
setMostRecentEventCount(acknowledgedEventCount);
forceNativeEventRender((sequence) => sequence + 1);
}}
onComposerFocus={onFocus}
onComposerBlur={onBlur}
onComposerSubmit={onSubmit}
@@ -327,4 +371,5 @@ export type {
ComposerEditorHandle,
ComposerEditorProps,
ComposerEditorSelection,
ComposerTextPaste,
} from "./T3ComposerEditor.types";
@@ -1,3 +1,5 @@
import { PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES } from "@t3tools/client-runtime/text-paste";
import { PROVIDER_SEND_TURN_MAX_INPUT_CHARS } from "@t3tools/contracts";
import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens";
import { composerContextEditorTokens } from "../lib/composerContext";
import { requireNativeView } from "expo";
@@ -55,6 +57,13 @@ type NativePasteImagesEvent = NativeSyntheticEvent<{
readonly uris: ReadonlyArray<string>;
}>;
type NativePasteTextEvent = NativeSyntheticEvent<{
readonly value: string;
readonly eventCount: number;
readonly text: string;
readonly selection: ComposerEditorSelection;
}>;
interface NativeComposerEditorRef {
focus: () => Promise<void>;
blur: () => Promise<void>;
@@ -85,8 +94,11 @@ interface NativeComposerEditorProps extends ViewProps {
event: NativeSyntheticEvent<{ source: string; start: number; end: number }>,
) => void;
readonly onComposerPasteContext?: (
event: NativeSyntheticEvent<{ text: string; fragment: string; html: string }>,
event: NativePasteTextEvent & NativeSyntheticEvent<{ fragment: string; html: string }>,
) => void;
readonly textPasteThresholdBytes: number;
readonly maxInputChars: number;
readonly onComposerPasteText?: (event: NativePasteTextEvent) => void;
readonly onComposerFocus?: () => void;
readonly onComposerBlur?: () => void;
}
@@ -111,6 +123,7 @@ export function ComposerEditor({
onChangeText,
onSelectionChange,
onPasteImages,
onPasteText,
onFocus,
onBlur,
contentInsetVertical = 0,
@@ -291,6 +304,8 @@ export function ComposerEditor({
autoFocus={props.autoFocus ?? false}
autoCorrect={props.autoCorrect ?? true}
spellCheck={props.spellCheck ?? true}
textPasteThresholdBytes={onPasteText ? PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES : 0}
maxInputChars={PROVIDER_SEND_TURN_MAX_INPUT_CHARS}
style={{ flex: 1, minHeight: 0 }}
onComposerChange={(event) => {
const acknowledgedEventCount = acceptNativeEvent(
@@ -325,7 +340,36 @@ export function ComposerEditor({
}}
onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)}
onComposerPasteContext={(event) => props.onPasteContext?.(event.nativeEvent)}
onComposerPasteContext={(event) => {
const paste = event.nativeEvent;
const acknowledgedEventCount = acceptNativeEvent(
paste.eventCount,
paste.value,
paste.selection,
);
if (acknowledgedEventCount === false) return;
onChangeText(paste.value);
onSelectionChange?.(paste.selection);
props.onPasteContext?.(paste);
setMostRecentEventCount(acknowledgedEventCount);
forceNativeEventRender((sequence) => sequence + 1);
}}
onComposerPasteText={(event) => {
const paste = event.nativeEvent;
const acknowledgedEventCount = acceptNativeEvent(
paste.eventCount,
paste.value,
paste.selection,
);
if (acknowledgedEventCount === false) return;
// Synchronize the draft before an async paste captures its insertion target.
// React props can still precede the last native keystroke.
onChangeText(paste.value);
onSelectionChange?.(paste.selection);
onPasteText?.(paste);
setMostRecentEventCount(acknowledgedEventCount);
forceNativeEventRender((sequence) => sequence + 1);
}}
onComposerFocus={onFocus}
onComposerBlur={onBlur}
/>
@@ -337,4 +381,5 @@ export type {
ComposerEditorHandle,
ComposerEditorProps,
ComposerEditorSelection,
ComposerTextPaste,
} from "./T3ComposerEditor.types";
@@ -12,6 +12,7 @@ export function ComposerEditor({
skills: _skills,
selection,
onPasteImages,
onPasteText: _onPasteText,
style,
textStyle,
contentInsetVertical = 0,
@@ -65,4 +66,5 @@ export type {
ComposerEditorHandle,
ComposerEditorProps,
ComposerEditorSelection,
ComposerTextPaste,
} from "./T3ComposerEditor.types";
@@ -7,6 +7,13 @@ export type ComposerEditorSelection = {
readonly end: number;
};
export type ComposerTextPaste = {
readonly value: string;
readonly eventCount: number;
readonly text: string;
readonly selection: ComposerEditorSelection;
};
export interface ComposerEditorHandle {
focus: () => void;
blur: () => void;
@@ -18,11 +25,12 @@ export interface ComposerEditorProps {
readonly value: string;
readonly context?: OrchestrationMessageContext;
readonly clipboardFragment?: string;
readonly onPasteContext?: (clipboard: {
readonly text: string;
readonly fragment: string;
readonly html: string;
}) => void;
readonly onPasteContext?: (
clipboard: ComposerTextPaste & {
readonly fragment: string;
readonly html: string;
},
) => void;
readonly skills?: ReadonlyArray<
Pick<ServerProviderSkill, "name" | "displayName" | "shortDescription" | "description"> &
Partial<Pick<ServerProviderSkill, "path">>
@@ -50,6 +58,7 @@ export interface ComposerEditorProps {
readonly start: number;
readonly end: number;
}) => void;
readonly onPasteText?: (paste: ComposerTextPaste) => void;
readonly onFocus?: () => void;
readonly onBlur?: () => void;
/** Invoked by the native editor when Command-Return is pressed on a hardware keyboard. */
@@ -192,3 +192,25 @@ describe("assumeComposerControlledState", () => {
);
});
});
describe("typing immediately before an intercepted paste", () => {
it("keeps the pre-paste React value behind the native paste revision", () => {
const snapshots = [
{ eventCount: 0, value: "", selection: { start: 0, end: 0 } },
{ eventCount: 1, value: "typed", selection: { start: 5, end: 5 } },
{ eventCount: 2, value: "typed", selection: { start: 0, end: 5 } },
];
// Both native platforms stamp the paste with its current value and selection.
// A render still carrying the typing caret cannot overwrite that selection.
expect(resolveComposerControlledEventCount("typed", { start: 5, end: 5 }, 2, snapshots)).toBe(
1,
);
expect(isComposerNativeEcho("typed", { start: 0, end: 5 }, 2, snapshots)).toBe(true);
// The replacement is a parent edit at the acknowledged paste revision.
expect(resolveComposerControlledEventCount("pasted", { start: 6, end: 6 }, 2, snapshots)).toBe(
2,
);
expect(isComposerNativeEcho("pasted", { start: 6, end: 6 }, 2, snapshots)).toBe(false);
expect(acknowledgeComposerNativeEvent(2, 1)).toBeNull();
});
});
+405 -39
View File
@@ -148,10 +148,14 @@ vi.mock("../features/sharing/incoming-share-storage", () => ({
}));
import type { DraftComposerAttachment } from "../lib/composerImages";
import { formatComposerContextReference } from "@t3tools/shared/composerContextReferences";
import { appAtomRegistry } from "./atom-registry";
import { threadOutboxManager } from "./thread-outbox";
import {
appendComposerDraftAttachments,
captureComposerDraftInsertion,
countComposerDraftAttachmentsAfterSelection,
getComposerDraftAfterSelection,
archiveCloudComposerDrafts,
clearComposerDraftContent,
clearComposerDraftContentState,
@@ -181,6 +185,7 @@ import {
retargetNewTaskDraft,
setComposerDraftText,
insertComposerDraftContext,
insertComposerDraftText,
rememberComposerDraftSelection,
setComposerDraftAttachmentUpload,
waitForComposerDraftsLoaded,
@@ -233,6 +238,81 @@ function contextDraft(start: number, count: number): ComposerDraft {
}
describe("mobile composer drafts", () => {
it.each([false, true])(
"restores visible file chips from legacy drafts (archived: %s)",
async (archived) => {
const file = {
type: "file" as const,
id: "legacy-file",
name: "notes.txt",
mimeType: "text/plain",
sizeBytes: 10,
fileUri: "file:///notes.txt",
};
const image = { ...file, id: "photo", name: "photo.png", mimeType: "image/png" };
const video = { ...file, id: "video", name: "clip.mp4", mimeType: "video/mp4" };
const legacy = { text: "Review these", attachments: [file, image, video] };
const document = {
schemaVersion: 1,
drafts: archived ? {} : { thread: legacy },
...(archived
? { signedOutDrafts: { account: { drafts: { thread: legacy }, queuedMessages: [] } } }
: {}),
};
const decoded = decodePersistedComposerState(document);
const restored = archived
? decoded.cloudDrafts.signedOut.account?.drafts.thread
: decoded.drafts.thread;
expect(restored?.text).toBe("Review these [notes.txt](t3-context://v1/file/legacy-file) ");
expect(restored?.attachments).toEqual(legacy.attachments);
expect(restored?.context?.records).toEqual([
expect.objectContaining({ kind: "file", attachmentId: file.id }),
]);
expect(
decodePersistedComposerState({ schemaVersion: 1, drafts: { thread: restored } }).drafts
.thread,
).toEqual(restored);
appAtomRegistry.set(composerDraftsAtom, { thread: restored! });
setComposerDraftText("thread", "Review these");
expect(getComposerDraftSnapshot("thread").attachments).toEqual([image, video]);
await releaseUnusedComposerAttachmentFiles([file]);
},
);
it("restores a missing file reference without duplicating its record or replacing another record's id", () => {
const file = {
type: "file" as const,
id: "file",
name: "notes.txt",
mimeType: "text/plain",
sizeBytes: 10,
fileUri: "file:///notes.txt",
};
const existing = {
version: 1,
contextId: "original",
kind: "file",
label: file.name,
attachmentId: file.id,
name: file.name,
mimeType: file.mimeType,
sizeBytes: file.sizeBytes,
};
const skill = { version: 1, contextId: "file", kind: "skill", label: "Skill", name: "skill" };
for (const records of [[existing, skill], [skill]]) {
const restored = decodePersistedComposerState({
schemaVersion: 1,
drafts: {
thread: { text: "", attachments: [file], context: { version: 1, records } },
},
}).drafts.thread;
expect(restored?.context?.records).toHaveLength(2);
expect(restored?.context?.records).toContainEqual(skill);
expect(restored?.text).toBe(
`[notes.txt](t3-context://v1/file/${records.length === 2 ? "original" : "file_2"}) `,
);
}
});
it.each([false, true])(
"restores deleted file chips and releases undo history (uploaded: %s)",
async (uploaded) => {
@@ -303,6 +383,30 @@ describe("mobile composer drafts", () => {
expect(reloaded?.context?.records[0]?.label.length).toBeLessThanOrEqual(200);
});
it("gives a folded paste a chip that survives the send", () => {
const key = "environment-1:thread-1";
// What `createPastedTextComposerAttachment` produces for a long paste.
const pasted = {
type: "file" as const,
id: "pasted-1",
name: "pasted-text.txt",
mimeType: "text/plain",
sizeBytes: 40_000,
fileUri: "file:///pasted-text.txt",
};
appendComposerDraftAttachments(key, [pasted], { appendReference: true });
const draft = getComposerDraftSnapshot(key);
// Visible in the composer before sending, not only once the message lands.
expect(draft.text).toContain("pasted-text.txt");
expect(draft.context?.records).toMatchObject([
{ kind: "file", attachmentId: pasted.id, name: pasted.name },
]);
// The reference points at the record, so the chip stays a chip in the sent message.
const [record] = draft.context?.records ?? [];
expect(draft.text).toContain(String(record?.contextId));
});
it("drops chips and records for attachments a replace no longer keeps", () => {
const key = "new-task:draft-1";
const kept = {
@@ -426,41 +530,57 @@ describe("mobile composer drafts", () => {
expect(reloaded.cloudDrafts.signedOut).toEqual({});
});
it("removes a file only after its last reference is deleted, while retaining images", async () => {
const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
onTestFinished(() => outboxLoad.mockRestore());
const cleanup = Promise.withResolvers<void>();
composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
cleanup.resolve();
});
const key = "environment-1:remove-context-files";
const file = {
id: "file-1",
type: "file" as const,
name: "notes.txt",
mimeType: "text/plain",
sizeBytes: 4,
fileUri: "file:///notes.txt",
};
const image = {
...file,
id: "image-1",
type: "image" as const,
name: "image.png",
mimeType: "image/png",
fileUri: "file:///image.png",
previewUri: "file:///image.png",
};
appendComposerDraftAttachments(key, [file, image], { appendReference: true });
const fileLink = "[notes.txt](t3-context://v1/file/file-1)";
setComposerDraftText(key, `${fileLink} ${fileLink}`);
expect(getComposerDraftSnapshot(key).attachments).toEqual([file, image]);
setComposerDraftText(key, fileLink);
expect(getComposerDraftSnapshot(key).attachments).toEqual([file, image]);
setComposerDraftText(key, "plain text");
expect(getComposerDraftSnapshot(key).attachments).toEqual([image]);
await cleanup.promise;
});
it.each([
{ name: "notes.txt", mimeType: "text/plain" },
{ name: "document-photo.png", mimeType: "image/png" },
{ name: "recording.mp4", mimeType: "video/mp4" },
])(
"removes $name after its last reference is deleted, while retaining native images",
async ({ name, mimeType }) => {
const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
onTestFinished(() => outboxLoad.mockRestore());
const cleanup = Promise.withResolvers<void>();
composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
cleanup.resolve();
});
const key = "environment-1:remove-context-files";
const file = {
id: "file-1",
type: "file" as const,
name,
mimeType,
sizeBytes: 4,
fileUri: `file:///${name}`,
};
const image = {
...file,
id: "image-1",
type: "image" as const,
name: "image.png",
mimeType: "image/png",
fileUri: "file:///image.png",
previewUri: "file:///image.png",
};
appendComposerDraftAttachments(key, [file, image], { appendReference: true });
const fileLink = formatComposerContextReference(
getComposerDraftSnapshot(key).context!.records[0]!,
);
setComposerDraftText(key, `${fileLink} ${fileLink}`);
expect(getComposerDraftSnapshot(key).attachments).toEqual([file, image]);
setComposerDraftText(key, fileLink);
expect(getComposerDraftSnapshot(key).attachments).toEqual([file, image]);
expect(
countComposerDraftAttachmentsAfterSelection(key, {
text: fileLink,
start: 0,
end: fileLink.length,
}),
).toBe(1);
setComposerDraftText(key, "plain text");
expect(getComposerDraftSnapshot(key).attachments).toEqual([image]);
await cleanup.promise;
},
);
it("rejects attachments atomically when no context slots remain", async () => {
const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
@@ -506,6 +626,190 @@ describe("mobile composer drafts", () => {
expect(getComposerDraftSnapshot(key)).toEqual(before);
await cleanup.promise;
});
it.each(["environment-1:thread", "environment-1:new-task:draft"])(
"preserves the captured paste selection across async writes in %s",
async (key) => {
const file = {
id: "paste",
type: "file" as const,
name: "pasted-text.txt",
mimeType: "text/plain",
sizeBytes: 40_000,
fileUri: "file:///paste.txt",
};
setComposerDraftText(key, "before selected after");
const insertion = captureComposerDraftInsertion(key, { start: 7, end: 15 });
const write = Promise.withResolvers<typeof file>();
const pending = write.promise.then((attachment) =>
appendComposerDraftAttachments(key, [attachment], { appendReference: true, insertion }),
);
rememberComposerDraftSelection(key, insertion.text, { start: 0, end: 6 });
rememberComposerDraftSelection("another-draft", "unrelated", { start: 0, end: 9 });
write.resolve(file);
expect(await pending).toBe(0);
const draft = getComposerDraftSnapshot(key);
expect(draft.text).toBe("before [pasted-text.txt](t3-context://v1/file/paste) after");
expect(draft.attachments).toEqual([file]);
},
);
it("preserves edits made while a paste is pending instead of deleting stale offsets", async () => {
const key = "environment-1:typing-during-paste";
setComposerDraftText(key, "old selection");
const insertion = captureComposerDraftInsertion(key, { start: 0, end: 13 });
const write = Promise.withResolvers<void>();
const pending = write.promise.then(() => insertComposerDraftText(key, " pasted", insertion));
setComposerDraftText(key, "keep newly typed text");
write.resolve();
await pending;
expect(getComposerDraftSnapshot(key).text).toBe("keep newly typed text pasted");
});
it.each(["attachment", "context", "imported context"])(
"releases a selected file when replaced by %s",
async (kind) => {
const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
onTestFinished(() => outboxLoad.mockRestore());
const cleanup = Promise.withResolvers<void>();
composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
cleanup.resolve();
return undefined;
});
const key = "environment-1:replace-file";
const files = Array.from({ length: 8 }, (_, index) => ({
id: `file-${index}`,
type: "file" as const,
name: `notes-${index}.txt`,
mimeType: "text/plain",
sizeBytes: 4,
fileUri: `file:///notes-${index}.txt`,
}));
appendComposerDraftAttachments(key, files, { appendReference: true });
const firstLink = "[notes-0.txt](t3-context://v1/file/file-0)";
const insertion = captureComposerDraftInsertion(key, { start: 0, end: firstLink.length });
expect(countComposerDraftAttachmentsAfterSelection(key, insertion)).toBe(7);
expect(getComposerDraftAfterSelection(key, insertion).context?.records).toHaveLength(7);
const replacement = { ...files[0]!, id: "replacement", fileUri: "file:///replacement.txt" };
if (kind === "attachment") {
expect(
appendComposerDraftAttachments(key, [replacement], { appendReference: true, insertion }),
).toBe(0);
} else if (kind === "imported context") {
const record = {
version: 1 as const,
kind: "file" as const,
contextId: ComposerContextId.make("replacement"),
attachmentId: replacement.id,
label: replacement.name,
name: replacement.name,
mimeType: replacement.mimeType,
sizeBytes: replacement.sizeBytes,
};
expect(
insertComposerDraftContext(
key,
{
text: formatComposerContextReference(record),
context: { version: 1, records: [record] },
attachments: [replacement],
},
insertion,
),
).toBe(true);
expect(getComposerDraftSnapshot(key).attachments).toHaveLength(8);
expect(getComposerDraftSnapshot(key).context?.records).toContainEqual(record);
expect(getComposerDraftSnapshot(key).text).toBe(
`${formatComposerContextReference(record)}${insertion.text.slice(firstLink.length)}`,
);
} else {
insertComposerDraftContext(
key,
{ text: "replacement", context: { version: 1, records: [] } },
insertion,
);
}
const draft = getComposerDraftSnapshot(key);
expect(draft.attachments.map((file) => file.id)).not.toContain("file-0");
expect(draft.attachments.slice(0, 7)).toEqual(files.slice(1));
expect(draft.context?.records.some((record) => record.contextId === "file-0")).toBe(false);
await cleanup.promise;
expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(files[0]!.fileUri);
},
);
it("rejects an imported file atomically when edits during import use up its replacement slot", async () => {
const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
onTestFinished(() => outboxLoad.mockRestore());
const cleanup = Promise.withResolvers<void>();
composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
cleanup.resolve();
return undefined;
});
const key = "environment-1:concurrent-import";
const files = Array.from({ length: 8 }, (_, index) => ({
id: `existing-${index}`,
type: "file" as const,
name: `notes-${index}.txt`,
mimeType: "text/plain",
sizeBytes: 4,
fileUri: `file:///notes-${index}.txt`,
}));
appendComposerDraftAttachments(key, files, { appendReference: true });
const firstLink = "[notes-0.txt](t3-context://v1/file/existing-0)";
const insertion = captureComposerDraftInsertion(key, { start: 0, end: firstLink.length });
setComposerDraftText(key, `New edit ${insertion.text}`);
const edited = getComposerDraftSnapshot(key);
const imported = { ...files[0]!, id: "imported", fileUri: "file:///imported.txt" };
const record = {
version: 1 as const,
kind: "file" as const,
contextId: ComposerContextId.make("imported"),
attachmentId: imported.id,
label: imported.name,
name: imported.name,
mimeType: imported.mimeType,
sizeBytes: imported.sizeBytes,
};
expect(
insertComposerDraftContext(
key,
{
text: formatComposerContextReference(record),
context: { version: 1, records: [record] },
attachments: [imported],
},
insertion,
),
).toBe(false);
expect(getComposerDraftSnapshot(key)).toEqual(edited);
await cleanup.promise;
expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(imported.fileUri);
});
it("retains a file when replacing only one of its repeated references", () => {
const key = "environment-1:repeat-reference";
const file = {
id: "repeat",
type: "file" as const,
name: "notes.txt",
mimeType: "text/plain",
sizeBytes: 4,
fileUri: "file:///repeat.txt",
};
appendComposerDraftAttachments(key, [file], { appendReference: true });
const link = getComposerDraftSnapshot(key).text;
setComposerDraftText(key, `${link} ${link}`);
const insertion = captureComposerDraftInsertion(key, { start: 0, end: link.length });
expect(countComposerDraftAttachmentsAfterSelection(key, insertion)).toBe(1);
insertComposerDraftContext(
key,
{ text: "replaced", context: { version: 1, records: [] } },
insertion,
);
expect(getComposerDraftSnapshot(key).attachments).toEqual([file]);
expect(getComposerDraftSnapshot(key).text).toBe(`replaced ${link}`);
});
it("inserts context at the saved caret and retains its payload through persistence and restore", () => {
const draftKey = "context-environment:context-thread";
const record = {
@@ -564,7 +868,25 @@ describe("mobile composer drafts", () => {
},
}).drafts,
).toEqual({
"environment-1:thread-1": { text: "Review this file", attachments: [file] },
"environment-1:thread-1": {
text: "Review this file [report.pdf](t3-context://v1/file/file-1) ",
attachments: [file],
context: {
version: 1,
records: [
{
version: 1,
contextId: file.id,
kind: "file",
label: file.name,
attachmentId: file.id,
name: file.name,
mimeType: file.mimeType,
sizeBytes: file.sizeBytes,
},
],
},
},
});
});
@@ -882,8 +1204,34 @@ describe("mobile composer drafts", () => {
const enqueue = vi.spyOn(threadOutboxManager, "enqueue").mockResolvedValue();
onTestFinished(() => enqueue.mockRestore());
await restoreCloudComposerDrafts("account-a");
expect(getComposerDraftSnapshot(key)).toEqual({ text: "Unsent notes", attachments: [file] });
expect(getComposerDraftSnapshot("pending-task:queued-1").text).toBe("Edited queued task");
expect(getComposerDraftSnapshot(key)).toEqual(
type === "image"
? { text: "Unsent notes", attachments: [file] }
: {
text: "Unsent notes [notes.pdf](t3-context://v1/file/local-notes) ",
attachments: [file],
context: {
version: 1,
records: [
{
version: 1,
contextId: file.id,
kind: "file",
label: file.name,
attachmentId: file.id,
name: file.name,
mimeType: file.mimeType,
sizeBytes: file.sizeBytes,
},
],
},
},
);
expect(getComposerDraftSnapshot("pending-task:queued-1").text).toBe(
type === "image"
? "Edited queued task"
: "Edited queued task [notes.pdf](t3-context://v1/file/local-notes) ",
);
expect(enqueue).toHaveBeenCalledExactlyOnceWith(queued);
expect(appAtomRegistry.get(composerCloudDraftsAtom).signedOut).toEqual({});
const persisted = decodePersistedComposerState(
@@ -2314,7 +2662,25 @@ describe("mobile composer drafts", () => {
await fresh.releaseUnusedComposerAttachmentFiles([file]);
expect(freshRegistry.get(fresh.composerDraftsAtom)).toEqual({
"environment-1:thread-1": { text: "Persisted draft", attachments: [file] },
"environment-1:thread-1": {
text: "Persisted draft [report.pdf](t3-context://v1/file/file-cold-start) ",
attachments: [file],
context: {
version: 1,
records: [
{
version: 1,
contextId: file.id,
kind: "file",
label: file.name,
attachmentId: file.id,
name: file.name,
mimeType: file.mimeType,
sizeBytes: file.sizeBytes,
},
],
},
},
});
expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
});
+213 -51
View File
@@ -24,11 +24,13 @@ import { Atom } from "effect/unstable/reactivity";
import { writeFileAtomically } from "../lib/atomic-file";
import { createComposerContextHistory, referencedComposerContext } from "../lib/composerContext";
import {
collectComposerContextReferences,
formatComposerContextReference,
sanitizeComposerContextLabel,
replaceComposerContextReferences,
} from "@t3tools/shared/composerContextReferences";
import { imageMimeType } from "@t3tools/shared/image";
import { videoMimeType } from "@t3tools/shared/video";
import { DraftComposerAttachmentSchema } from "../lib/composer-image-schema";
import {
composerAttachmentFileReferenceKey,
@@ -95,6 +97,89 @@ export function readComposerDraftSelection(
return { start: lastComposerSelection.start, end: lastComposerSelection.end };
}
export interface ComposerDraftInsertion {
readonly text: string;
readonly start: number;
readonly end: number;
}
/** Capture the paste target before any clipboard reads, downloads, or file writes. */
export function captureComposerDraftInsertion(
draftKey: string,
selection?: { start: number; end: number },
): ComposerDraftInsertion {
const { text } = getComposerDraftSnapshot(draftKey);
return {
text,
...(selection ??
readComposerDraftSelection(draftKey, text) ?? { start: text.length, end: text.length }),
};
}
function contextInsertionRange(
draftKey: string,
draft: ComposerDraft,
target?: ComposerDraftInsertion,
) {
const captured =
target ?? (lastComposerSelection?.draftKey === draftKey ? lastComposerSelection : null);
// Edits made during a file write must not be replaced using stale offsets. A changed
// draft receives the file at its end; moving only the caret preserves the captured range.
const selection = captured?.text === draft.text ? captured : null;
const start = Math.max(0, Math.min(selection?.start ?? draft.text.length, draft.text.length));
return { start, end: Math.max(start, Math.min(selection?.end ?? start, draft.text.length)) };
}
function draftWithoutInsertionSelection(
draftKey: string,
draft: ComposerDraft,
target?: ComposerDraftInsertion,
) {
const { start, end } = contextInsertionRange(draftKey, draft, target);
const text = `${draft.text.slice(0, start)} ${draft.text.slice(end)}`;
return withReferencedContextFiles(draft, text, referencedComposerContext(text, draft.context));
}
export function countComposerDraftAttachmentsAfterSelection(
draftKey: string,
target: ComposerDraftInsertion,
): number {
return getComposerDraftAfterSelection(draftKey, target).attachments.length;
}
export function getComposerDraftAfterSelection(
draftKey: string,
target: ComposerDraftInsertion,
): ComposerDraft {
return draftWithoutInsertionSelection(draftKey, getComposerDraftSnapshot(draftKey), target);
}
function withReferencedContextFiles(
draft: ComposerDraft,
text: string,
context: OrchestrationMessageContext | undefined,
): ComposerDraft {
const previousIds = new Set(
draft.context?.records.flatMap((record) =>
"attachmentId" in record ? [record.attachmentId] : [],
),
);
const retainedIds = new Set(
context?.records.flatMap((record) => ("attachmentId" in record ? [record.attachmentId] : [])),
);
return {
...draft,
text,
context,
attachments: draft.attachments.filter(
(attachment) =>
attachment.type === "image" ||
!previousIds.has(attachment.id) ||
retainedIds.has(attachment.id),
),
};
}
/** Retains file bytes while native text undo can restore their references. */
export function createComposerDraftContextHistory() {
const restoreContext = createComposerContextHistory();
@@ -162,16 +247,36 @@ export function setComposerDraftContext(
export function insertComposerDraftContext(
draftKey: string,
content: { text: string; context: OrchestrationMessageContext },
content: {
text: string;
context: OrchestrationMessageContext;
attachments?: ReadonlyArray<DraftComposerAttachment>;
},
target?: ComposerDraftInsertion,
): boolean {
let inserted = false;
let removed: ReadonlyArray<DraftComposerAttachment> = [];
updateComposerDrafts((current) => {
const draft = normalizeDraft(current[draftKey]);
const nextDraft = draftWithInsertedContext(draftKey, draft, content);
const attachments = content.attachments ?? [];
const retained = draftWithoutInsertionSelection(draftKey, draft, target);
if (
attachments.length > 0 &&
retained.attachments.length + attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS
)
return current;
const nextDraft = draftWithInsertedContext(
draftKey,
{ ...draft, attachments: [...draft.attachments, ...attachments] },
content,
target,
);
if (!nextDraft) return current;
inserted = true;
removed = draft.attachments.filter((attachment) => !nextDraft.attachments.includes(attachment));
return { ...current, [draftKey]: nextDraft };
});
scheduleUnusedComposerAttachmentCleanup(inserted ? removed : (content.attachments ?? []));
return inserted;
}
@@ -179,13 +284,9 @@ function draftWithInsertedContext(
draftKey: string,
draft: ComposerDraft,
content: { text: string; context: OrchestrationMessageContext },
target?: ComposerDraftInsertion,
): ComposerDraft | null {
const selection =
lastComposerSelection?.draftKey === draftKey && lastComposerSelection.text === draft.text
? lastComposerSelection
: null;
const start = Math.max(0, Math.min(selection?.start ?? draft.text.length, draft.text.length));
const end = Math.max(start, Math.min(selection?.end ?? start, draft.text.length));
const { start, end } = contextInsertionRange(draftKey, draft, target);
const before = draft.text.slice(0, start);
const after = draft.text.slice(end);
const insertion = `${before.length > 0 && !/\s$/.test(before) && !/^\s/.test(content.text) ? " " : ""}${content.text}${!/\s$/.test(content.text) && (after.length === 0 || !/^\s/.test(after)) ? " " : ""}`;
@@ -200,7 +301,7 @@ function draftWithInsertedContext(
start: start + insertion.length,
end: start + insertion.length,
};
return { ...draft, text, context };
return withReferencedContextFiles(draft, text, context);
}
export class ComposerDraftPersistenceError extends Schema.TaggedError<ComposerDraftPersistenceError>()(
@@ -352,6 +453,68 @@ export function resetComposerDraftsLoadState(): void {
persistRetryNeeded = false;
}
function attachmentContextRecord(
attachment: DraftComposerAttachment,
contextId = ComposerContextId.make(attachment.id),
) {
const common = {
version: 1 as const,
contextId,
label: sanitizeComposerContextLabel(attachment.name, attachment.type),
attachmentId: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
};
// A picture picked through the document picker is typed as a plain file, but the
// record has to say what it is or no client will offer to open it as an image.
return attachment.type === "image" || imageMimeType(attachment) !== null
? { ...common, kind: "image" as const }
: { ...common, kind: "file" as const };
}
/** Older drafts stored documents only in the attachment strip. Restore their missing chips. */
function restoreMissingComposerFileReferences(draft: ComposerDraft): ComposerDraft {
const records = [...(draft.context?.records ?? [])];
const usedIds = new Set<string>(records.map((record) => record.contextId));
const referenced = new Set(
collectComposerContextReferences(draft.text).map(
(reference) => `${reference.kind}:${reference.contextId}`,
),
);
let text = draft.text;
let changed = false;
for (const attachment of draft.attachments) {
if (
attachment.type === "image" ||
imageMimeType(attachment) !== null ||
videoMimeType(attachment) !== null
)
continue;
let record = records.find(
(candidate) =>
candidate.kind === "file" &&
"attachmentId" in candidate &&
candidate.attachmentId === attachment.id,
);
if (!record) {
const baseId = attachment.id.replace(/[^a-z0-9_-]/gi, "_").slice(0, 110) || "file";
let contextId = baseId;
for (let suffix = 2; usedIds.has(contextId); suffix += 1) contextId = `${baseId}_${suffix}`;
usedIds.add(contextId);
record = attachmentContextRecord(attachment, ComposerContextId.make(contextId));
records.push(record);
changed = true;
}
const key = `${record.kind}:${record.contextId}`;
if (referenced.has(key)) continue;
text += `${text.length > 0 && !/\s$/.test(text) ? " " : ""}${formatComposerContextReference(record)} `;
referenced.add(key);
changed = true;
}
return changed ? { ...draft, text, context: { version: 1, records } } : draft;
}
function normalizeDraft(draft: ComposerDraft | undefined): ComposerDraft {
if (!draft) {
return EMPTY_DRAFT;
@@ -421,14 +584,15 @@ export function migrateLegacyNewTaskDraft(
draft: ComposerDraft,
now: string,
): readonly [key: string, draft: ComposerDraft] {
const restored = restoreMissingComposerFileReferences(draft);
const legacy = draft.project === undefined ? parseLegacyNewTaskDraftKey(key) : null;
if (legacy === null) {
return [key, draft];
return [key, restored];
}
return [
newTaskDraftKey(newDraftId()),
{
...draft,
...restored,
project: {
environmentId: EnvironmentIdSchema.make(legacy.environmentId),
projectId: ProjectIdSchema.make(legacy.projectId),
@@ -1089,28 +1253,28 @@ export function setComposerDraftText(draftKey: string, value: string): void {
updateComposerDrafts((current) => {
const existing = normalizeDraft(current[draftKey]);
const context = referencedComposerContext(value, existing.context);
const retainedIds = new Set(context?.records.map((record) => record.contextId));
const removedFileIds = new Set(
existing.context?.records.flatMap((record) =>
record.kind === "file" && "attachmentId" in record && !retainedIds.has(record.contextId)
? [record.attachmentId]
: [],
),
);
removed = existing.attachments.filter(
(attachment) => attachment.type !== "image" && removedFileIds.has(attachment.id),
);
const draft = {
...existing,
text: value,
context,
attachments: existing.attachments.filter((attachment) => !removed.includes(attachment)),
};
const draft = withReferencedContextFiles(existing, value, context);
removed = existing.attachments.filter((attachment) => !draft.attachments.includes(attachment));
return withComposerDraft(current, draftKey, draft);
});
scheduleUnusedComposerAttachmentCleanup(removed);
}
export function insertComposerDraftText(
draftKey: string,
value: string,
target: ComposerDraftInsertion,
): void {
const draft = getComposerDraftSnapshot(draftKey);
const { start, end } = contextInsertionRange(draftKey, draft, target);
const text = draft.text.slice(0, start) + value + draft.text.slice(end);
setComposerDraftText(draftKey, text);
rememberComposerDraftSelection(draftKey, text, {
start: start + value.length,
end: start + value.length,
});
}
export function appendComposerDraftText(draftKey: string, value: string): void {
updateComposerDrafts((current) => {
const existing = normalizeDraft(current[draftKey]);
@@ -1137,6 +1301,7 @@ export function appendComposerDraftAttachments(
options?: {
readonly allowOverflow?: boolean;
readonly appendReference?: boolean;
readonly insertion?: ComposerDraftInsertion;
readonly maxAttachments?: number;
},
): number {
@@ -1144,8 +1309,12 @@ export function appendComposerDraftAttachments(
return 0;
}
let rejected: ReadonlyArray<DraftComposerAttachment> = [];
let removed: ReadonlyArray<DraftComposerAttachment> = [];
updateComposerDrafts((current) => {
const existing = normalizeDraft(current[draftKey]);
const retained = options?.appendReference
? draftWithoutInsertionSelection(draftKey, existing, options.insertion)
: existing;
const remaining = options?.allowOverflow
? attachments.length
: Math.max(
@@ -1153,10 +1322,10 @@ export function appendComposerDraftAttachments(
Math.min(
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
options?.maxAttachments ?? PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
) - existing.attachments.length,
) - retained.attachments.length,
);
const contextCapacity = options?.appendReference
? Math.max(0, COMPOSER_CONTEXT_MAX_RECORDS - (existing.context?.records.length ?? 0))
? Math.max(0, COMPOSER_CONTEXT_MAX_RECORDS - (retained.context?.records.length ?? 0))
: attachments.length;
const accepted = attachments.slice(0, Math.min(remaining, contextCapacity));
rejected = attachments.slice(accepted.length);
@@ -1165,38 +1334,31 @@ export function appendComposerDraftAttachments(
}
let draft = { ...existing, attachments: [...existing.attachments, ...accepted] };
if (options?.appendReference) {
const records = accepted.map((attachment) => {
const common = {
version: 1 as const,
contextId: ComposerContextId.make(attachment.id),
label: sanitizeComposerContextLabel(attachment.name, attachment.type),
attachmentId: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
};
// A picture picked through the document picker is typed as a plain file, but the
// record has to say what it is or no client will offer to open it as an image.
return attachment.type === "image" || imageMimeType(attachment) !== null
? { ...common, kind: "image" as const }
: { ...common, kind: "file" as const };
});
const inserted = draftWithInsertedContext(draftKey, draft, {
text: records.map(formatComposerContextReference).join(" "),
context: { version: 1, records },
});
const records = accepted.map((attachment) => attachmentContextRecord(attachment));
const inserted = draftWithInsertedContext(
draftKey,
draft,
{
text: records.map(formatComposerContextReference).join(" "),
context: { version: 1, records },
},
options?.insertion,
);
if (!inserted) {
rejected = attachments;
return current;
}
draft = { ...inserted, attachments: [...inserted.attachments] };
removed = existing.attachments.filter(
(attachment) => !draft.attachments.includes(attachment),
);
}
return {
...current,
[draftKey]: draft,
};
});
scheduleUnusedComposerAttachmentCleanup(rejected);
scheduleUnusedComposerAttachmentCleanup([...rejected, ...removed]);
return rejected.length;
}
@@ -1,5 +1,6 @@
import type { ComposerTextPaste } from "../native/T3ComposerEditor.types";
import { useAtomValue } from "@effect/atom-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Alert } from "react-native";
import {
@@ -7,6 +8,7 @@ import {
DEFAULT_PROVIDER_INTERACTION_MODE,
MessageId,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
type EnvironmentId,
type ModelSelection,
type ProviderInteractionMode,
@@ -14,6 +16,8 @@ import {
type ThreadId,
} from "@t3tools/contracts";
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
import { nextPastedTextFileName, pastedTextDisposition } from "@t3tools/client-runtime/text-paste";
import {
parseCodexFeedbackCommand,
submitCodexFeedback,
@@ -29,9 +33,11 @@ import { isModelSelectionUnavailable } from "../lib/modelOptions";
import { resolveProviderInteractionMode } from "../features/threads/legacy-plan-mode";
import {
convertPastedImagesToAttachments,
createPastedTextComposerAttachment,
pasteComposerClipboard,
pickComposerFiles,
pickComposerMedia,
removePersistedComposerAttachmentFile,
} from "../lib/composerImages";
import type { DraftComposerImageAttachment } from "../lib/composerImages";
import { scopedThreadKey } from "../lib/scopedEntities";
@@ -42,7 +48,9 @@ import { appAtomRegistry } from "../state/atom-registry";
import { pendingThreadCreationMessage } from "./pending-thread-creation";
import {
appendComposerDraftAttachments,
appendComposerDraftText,
captureComposerDraftInsertion,
countComposerDraftAttachmentsAfterSelection,
insertComposerDraftText,
insertComposerDraftContext,
clearComposerDraftContent,
composerDraftsAtom,
@@ -132,6 +140,23 @@ export function useThreadComposerState() {
const uploadThreadFeedback = useAtomCommand(threadEnvironment.uploadFeedback, {
reportFailure: false,
});
const pastedTextFileNamesRef = useRef<{ threadKey: string | null; names: Set<string> }>({
threadKey: null,
names: new Set(),
});
const reservePastedTextFileName = useCallback(
(threadKey: string, existingNames: ReadonlyArray<string>) => {
if (pastedTextFileNamesRef.current.threadKey !== threadKey) {
pastedTextFileNamesRef.current = { threadKey, names: new Set() };
}
const names = pastedTextFileNamesRef.current.names;
for (const name of existingNames) names.add(name);
const nextName = nextPastedTextFileName([...names]);
names.add(nextName);
return nextName;
},
[],
);
useEffect(() => {
ensureComposerDraftsLoaded();
@@ -479,9 +504,10 @@ export function useThreadComposerState() {
}
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
const insertion = captureComposerDraftInsertion(threadKey);
const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
const result = await pickComposerMedia({
existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
maxVideoBytes:
capabilities?.attachmentUploads === true
? capabilities.fileAttachments?.maxUploadBytes
@@ -489,6 +515,7 @@ export function useThreadComposerState() {
});
const rejectedCount = appendComposerDraftAttachments(threadKey, result.attachments, {
appendReference: true,
insertion,
});
const problems = [
...(result.error ? [result.error] : []),
@@ -514,13 +541,15 @@ export function useThreadComposerState() {
}
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
const insertion = captureComposerDraftInsertion(threadKey);
// pickComposerFiles clamps the advertised limit to the contract maximum.
const result = await pickComposerFiles({
existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
maxBytes,
});
const rejectedCount = appendComposerDraftAttachments(threadKey, result.files, {
appendReference: true,
insertion,
});
// The picker error and the live-cap rejection can both happen in one
// pick; report both in a single alert.
@@ -541,14 +570,81 @@ export function useThreadComposerState() {
}
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
const insertion = captureComposerDraftInsertion(threadKey);
const result = await pasteComposerClipboard({
existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
});
const rejectedPasteCount = appendComposerDraftAttachments(threadKey, result.images, {
appendReference: true,
insertion,
});
if (result.text) {
appendComposerDraftText(threadKey, result.text);
const currentDraft = getComposerDraftSnapshot(threadKey);
const currentAttachments = currentDraft.attachments;
const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
const advertisedMax =
capabilities?.attachmentUploads === true
? capabilities.fileAttachments?.maxUploadBytes
: undefined;
const maxBytes =
advertisedMax === undefined ? null : clampFileAttachmentUploadBytes(advertisedMax);
const wouldExceedInputLimit =
currentDraft.text.length -
(currentDraft.text === insertion.text
? Math.max(0, insertion.end - insertion.start)
: 0) +
result.text.length >
PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
const shouldFold =
pastedTextDisposition({
text: result.text,
wouldExceedInputLimit,
canAttach: true,
}) === "attachment";
const canAttach =
maxBytes !== null &&
countComposerDraftAttachmentsAfterSelection(threadKey, insertion) <
PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
new TextEncoder().encode(result.text).byteLength <= maxBytes;
if (shouldFold && canAttach && maxBytes !== null) {
try {
const attachment = await createPastedTextComposerAttachment({
text: result.text,
name: reservePastedTextFileName(
threadKey,
currentAttachments.map((item) => item.name),
),
maxBytes,
});
// Same reference the pasted images above get: a folded paste is only visible
// as its chip until the message is sent.
if (
appendComposerDraftAttachments(threadKey, [attachment], {
appendReference: true,
insertion,
}) > 0
) {
await removePersistedComposerAttachmentFile(attachment.fileUri);
setPendingConnectionError(
`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
);
}
} catch (error) {
setPendingConnectionError(
error instanceof Error ? error.message : "Could not attach pasted text.",
);
}
} else if (shouldFold && !wouldExceedInputLimit) {
insertComposerDraftText(threadKey, result.text, insertion);
} else if (shouldFold) {
setPendingConnectionError(
wouldExceedInputLimit
? "Pasted text is too large for this message. Remove some text or an attachment, then paste again."
: "Could not attach pasted text. Remove an attachment or use a smaller paste, then try again.",
);
} else {
insertComposerDraftText(threadKey, result.text, insertion);
}
}
if (result.error) {
setPendingConnectionError(result.error);
@@ -557,7 +653,12 @@ export function useThreadComposerState() {
`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
);
}
}, [composerDrafts, selectedThreadShell]);
}, [
composerDrafts,
reservePastedTextFileName,
selectedEnvironmentRuntime?.serverConfig,
selectedThreadShell,
]);
const onNativePasteImages = useCallback(
async (uris: ReadonlyArray<string>) => {
@@ -566,13 +667,14 @@ export function useThreadComposerState() {
}
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
const insertion = captureComposerDraftInsertion(threadKey);
try {
const images = await convertPastedImagesToAttachments({
uris,
existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
});
if (images.length > 0) {
appendComposerDraftAttachments(threadKey, images, { appendReference: true });
appendComposerDraftAttachments(threadKey, images, { appendReference: true, insertion });
}
} catch (error) {
console.error("[native paste] error converting images", {
@@ -586,6 +688,55 @@ export function useThreadComposerState() {
[composerDrafts, selectedThreadShell],
);
const onNativePasteText = useCallback(
async (paste: ComposerTextPaste) => {
if (!selectedThreadShell) return;
const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
const advertisedMax =
capabilities?.attachmentUploads === true
? capabilities.fileAttachments?.maxUploadBytes
: undefined;
if (advertisedMax === undefined) return;
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
const insertion = { text: paste.value, ...paste.selection };
const currentAttachments = getComposerDraftSnapshot(threadKey).attachments;
try {
const attachment = await createPastedTextComposerAttachment({
text: paste.text,
name: reservePastedTextFileName(
threadKey,
currentAttachments.map((item) => item.name),
),
maxBytes: clampFileAttachmentUploadBytes(advertisedMax),
});
// The chip is how a folded paste stays visible: without it the attachment is in the
// draft but nothing in the composer says so until the message is sent. Web folds
// through its ordinary attach path, which always writes a reference; match that.
const rejectedCount = appendComposerDraftAttachments(threadKey, [attachment], {
appendReference: true,
insertion,
});
if (rejectedCount > 0) {
await removePersistedComposerAttachmentFile(attachment.fileUri);
setPendingConnectionError(
`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
);
}
} catch (error) {
setPendingConnectionError(
error instanceof Error ? error.message : "Could not attach pasted text.",
);
}
},
[
composerDrafts,
reservePastedTextFileName,
selectedEnvironmentRuntime?.serverConfig,
selectedThreadShell,
],
);
const onRemoveDraftImage = useCallback(
(imageId: string) => {
if (!selectedThreadShell) {
@@ -663,6 +814,7 @@ export function useThreadComposerState() {
onPickDraftFiles,
onPasteIntoDraft,
onNativePasteImages,
onNativePasteText,
onRemoveDraftImage,
onSendMessage,
onUpdateModelSelection,