Skip to content
TypeScript

Add mobile composer attachment menu with video support (#8843)

Julius Marmingee3dcc1615c91
diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts
index 2755f066bb7..8bfc151487a 100644
--- a/apps/mobile/app.config.ts
+++ b/apps/mobile/app.config.ts
@@ -148,6 +148,7 @@ const sharingPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
supportsText: true,
supportsWebUrlWithMaxCount: 1,
supportsImageWithMaxCount: 8,
+ supportsMovieWithMaxCount: 8,
supportsFileWithMaxCount: 8,
},
},
diff --git a/apps/mobile/src/components/AppSymbol.tsx b/apps/mobile/src/components/AppSymbol.tsx
index a5d56d97375..13d9e620857 100644
--- a/apps/mobile/src/components/AppSymbol.tsx
+++ b/apps/mobile/src/components/AppSymbol.tsx
@@ -59,6 +59,7 @@ import IconMinus from "@tabler/icons-react-native/IconMinus";
import IconMoon from "@tabler/icons-react-native/IconMoon";
import IconNetwork from "@tabler/icons-react-native/IconNetwork";
import IconPalette from "@tabler/icons-react-native/IconPalette";
+import IconPhoto from "@tabler/icons-react-native/IconPhoto";
import IconPin from "@tabler/icons-react-native/IconPin";
import IconPinnedOff from "@tabler/icons-react-native/IconPinnedOff";
import IconPlayerPlay from "@tabler/icons-react-native/IconPlayerPlay";
@@ -133,6 +134,7 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
magnifyingglass: IconSearch,
paintbrush: IconPalette,
"person.crop.circle": IconUserCircle,
+ photo: IconPhoto,
pin: IconPin,
"pin.slash": IconPinnedOff,
play: IconPlayerPlay,
diff --git a/apps/mobile/src/components/ComposerAttachmentButton.tsx b/apps/mobile/src/components/ComposerAttachmentButton.tsx
new file mode 100644
index 00000000000..1af72d8883d
--- /dev/null
+++ b/apps/mobile/src/components/ComposerAttachmentButton.tsx
@@ -0,0 +1,55 @@
+import type { MenuAction } from "@react-native-menu/menu";
+import { Pressable } from "react-native";
+
+import { SymbolView } from "./AppSymbol";
+import { ControlPillMenu } from "./ControlPill";
+
+const ATTACHMENT_MENU_ACTIONS: MenuAction[] = [
+ { id: "photos", title: "Photo Library", image: "photo" },
+ { id: "files", title: "Choose Files", image: "folder" },
+];
+
+export function ComposerAttachmentButton(props: {
+ readonly disabled?: boolean;
+ readonly supportsFiles: boolean;
+ readonly onPickMedia: () => Promise<void>;
+ readonly onPickFiles: () => Promise<void>;
+}) {
+ const button = (
+ <Pressable
+ accessibilityLabel="Add attachment"
+ accessibilityRole="button"
+ accessibilityState={{ disabled: props.disabled }}
+ className="size-[44px] shrink-0 items-center justify-center rounded-full active:opacity-70 disabled:opacity-50"
+ disabled={props.disabled}
+ onPress={props.supportsFiles ? undefined : () => void props.onPickMedia()}
+ >
+ <SymbolView
+ name="plus"
+ size={20}
+ weight="regular"
+ tintColorClassName="accent-icon"
+ type="monochrome"
+ />
+ </Pressable>
+ );
+
+ if (props.disabled || !props.supportsFiles) {
+ return button;
+ }
+
+ return (
+ <ControlPillMenu
+ actions={ATTACHMENT_MENU_ACTIONS}
+ onPressAction={({ nativeEvent }) => {
+ if (nativeEvent.event === "photos") {
+ void props.onPickMedia();
+ } else if (nativeEvent.event === "files") {
+ void props.onPickFiles();
+ }
+ }}
+ >
+ {button}
+ </ControlPillMenu>
+ );
+}
diff --git a/apps/mobile/src/components/ComposerToolbar.tsx b/apps/mobile/src/components/ComposerToolbar.tsx
index b64e44b1937..8cc7f8523e9 100644
--- a/apps/mobile/src/components/ComposerToolbar.tsx
+++ b/apps/mobile/src/components/ComposerToolbar.tsx
@@ -113,6 +113,7 @@ export function ComposerToolbarRow(props: {
export function ComposerToolbarScroller(props: {
readonly children: ReactNode;
+ readonly align?: "start" | "end";
/** Only for non-Uniwind surfaces such as the native terminal palette. */
readonly fadeOpaque?: string;
/** Only for non-Uniwind surfaces such as the native terminal palette. */
@@ -167,6 +168,8 @@ export function ComposerToolbarScroller(props: {
showsHorizontalScrollIndicator={false}
contentContainerStyle={{
alignItems: "center",
+ flexGrow: props.align === "end" ? 1 : undefined,
+ justifyContent: props.align === "end" ? "flex-end" : undefined,
gap: COMPOSER_TOOLBAR_GAP,
paddingLeft: 0,
paddingRight: props.contentPaddingRight ?? 1,
@@ -214,6 +217,46 @@ export function ComposerToolbarScroller(props: {
);
}
+export function ComposerActionButton(props: {
+ readonly accessibilityLabel: string;
+ readonly disabled?: boolean;
+ readonly icon: ComponentProps<typeof SymbolView>["name"];
+ readonly onPress: () => void;
+ readonly variant?: "primary" | "danger";
+}) {
+ return (
+ <Pressable
+ accessibilityLabel={props.accessibilityLabel}
+ accessibilityRole="button"
+ accessibilityState={{ disabled: props.disabled }}
+ className="size-[44px] shrink-0 items-center justify-center active:opacity-70"
+ disabled={props.disabled}
+ onPress={props.onPress}
+ >
+ <View
+ className={cn(
+ "size-[30px] items-center justify-center rounded-full",
+ props.variant === "danger"
+ ? "bg-danger"
+ : props.disabled
+ ? "bg-primary/15"
+ : "bg-primary",
+ )}
+ >
+ <SymbolView
+ name={props.icon}
+ size={16}
+ weight="semibold"
+ tintColorClassName={
+ props.variant === "danger" ? "accent-danger-foreground" : "accent-primary-foreground"
+ }
+ type="monochrome"
+ />
+ </View>
+ </Pressable>
+ );
+}
+
export function ComposerToolbarButton(props: {
readonly icon?: ComponentProps<typeof SymbolView>["name"];
readonly iconNode?: ReactNode;
diff --git a/apps/mobile/src/components/ControlPill.tsx b/apps/mobile/src/components/ControlPill.tsx
index 31839d9dc67..18cba964320 100644
--- a/apps/mobile/src/components/ControlPill.tsx
+++ b/apps/mobile/src/components/ControlPill.tsx
@@ -6,16 +6,38 @@ import {
type ComponentProps,
type ReactElement,
type ReactNode,
+ useMemo,
useRef,
} from "react";
-import { Platform, Pressable, View, type PressableProps } from "react-native";
+import { Platform, Pressable, View, type ColorValue, type PressableProps } from "react-native";
+import { withUniwind } from "uniwind";
import { useAppearancePreferences } from "../features/settings/appearance/AppearancePreferencesProvider";
import { cn } from "../lib/cn";
+import { withMenuActionIconColors } from "../lib/menu-action-colors";
import { AndroidAnchoredMenu } from "./AndroidAnchoredMenu";
import { SymbolView } from "./AppSymbol";
import { AppText as Text } from "./AppText";
+const ThemedMenuView = withUniwind(function NativeMenuView({
+ iconColor,
+ destructiveIconColor,
+ ...props
+}: ComponentProps<typeof MenuView> & {
+ readonly iconColor?: ColorValue;
+ readonly destructiveIconColor?: ColorValue;
+}) {
+ const actions = useMemo(
+ () =>
+ withMenuActionIconColors(props.actions, {
+ icon: iconColor,
+ destructiveIcon: destructiveIconColor,
+ }),
+ [props.actions, iconColor, destructiveIconColor],
+ );
+ return <MenuView {...props} actions={actions} />;
+});
+
export function ControlPill(props: {
readonly icon?: ComponentProps<typeof SymbolView>["name"];
readonly iconNode?: ReactNode;
@@ -217,8 +239,13 @@ export function ControlPillMenu(
};
}
return (
- <MenuView {...menuProps} themeVariant={isDarkMode ? "dark" : "light"}>
+ <ThemedMenuView
+ {...menuProps}
+ iconColorClassName="accent-icon"
+ destructiveIconColorClassName="accent-danger-foreground"
+ themeVariant={isDarkMode ? "dark" : "light"}
+ >
{children}
- </MenuView>
+ </ThemedMenuView>
);
}
diff --git a/apps/mobile/src/features/sharing/incoming-share-model.test.ts b/apps/mobile/src/features/sharing/incoming-share-model.test.ts
index 58caae4dac7..ce2011650e7 100644
--- a/apps/mobile/src/features/sharing/incoming-share-model.test.ts
+++ b/apps/mobile/src/features/sharing/incoming-share-model.test.ts
@@ -181,6 +181,54 @@ describe("incoming native shares", () => {
expect(removeOwnedFile).toHaveBeenCalledWith(file.value);
});
+ it.each([
+ { value: "file:///shared/clip.MOV", mimeType: "video/quicktime", originalName: "clip.MOV" },
+ { value: "content://media/videos/12", mimeType: "video/mp4", originalName: "clip.mp4" },
+ ])("imports a shared video from $value without reading it as an image", async (video) => {
+ const sizeBytes = 20 * 1024 * 1024;
+ const fileUri = `file:///documents/${video.originalName}`;
+ const readBase64 = vi.fn(async () => "unused");
+ const persistFile = vi.fn(async () => fileUri);
+ const removeOwnedFile = vi.fn(async () => undefined);
+
+ const result = await buildIncomingShareDraft({
+ id: "share-video",
+ createdAt: "2026-08-30T10:00:00.000Z",
+ payloads: [{ ...video, shareType: "video" }],
+ resolvedPayloads: [],
+ fileReader: { readBase64, persistFile, readSize: async () => sizeBytes, removeOwnedFile },
+ });
+
+ expect(result.warnings).toEqual([]);
+ expect(result.attachments).toEqual([
+ {
+ id: "share-video:file:0",
+ type: "file",
+ name: video.originalName,
+ mimeType: video.mimeType,
+ sizeBytes,
+ fileUri,
+ },
+ ]);
+ expect(readBase64).not.toHaveBeenCalled();
+ expect(removeOwnedFile).toHaveBeenCalledWith(video.value);
+ expect(
+ selectIncomingShareAttachments({
+ attachments: result.attachments,
+ maxFileAttachmentBytes: 50 * 1024 * 1024,
+ }),
+ ).toEqual({ attachments: result.attachments, warnings: [] });
+ expect(
+ selectIncomingShareAttachments({
+ attachments: result.attachments,
+ maxFileAttachmentBytes: 10 * 1024 * 1024,
+ }),
+ ).toEqual({
+ attachments: [],
+ warnings: [`'${video.originalName}' exceeds the 10 MB attachment limit.`],
+ });
+ });
+
it("reports an unreadable shared file without calling it oversized", async () => {
const file: SharePayload = {
shareType: "file",
diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
index 0fa2ac16b8c..ca44385cb05 100644
--- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
+++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
@@ -25,12 +25,13 @@ import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS } from "@t3tools/contracts";
import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
import {
+ ComposerActionButton,
ComposerInlineControl,
- ComposerToolbarButton,
ComposerToolbarRow,
ComposerToolbarScroller,
} from "../../components/ComposerToolbar";
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
+import { ComposerAttachmentButton } from "../../components/ComposerAttachmentButton";
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
import { ProviderIcon } from "../../components/ProviderIcon";
import { SymbolView } from "../../components/AppSymbol";
@@ -55,7 +56,7 @@ import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
import {
convertPastedImagesToAttachments,
pickComposerFiles,
- pickComposerImages,
+ pickComposerMedia,
} from "../../lib/composerImages";
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
import {
@@ -715,12 +716,20 @@ export function NewTaskDraftScreen(props: {
});
const showBranchLoading = flow.branchesLoading && flow.availableBranches.length === 0;
- async function handlePickImages(): Promise<void> {
+ async function handlePickMedia(): Promise<void> {
if (isComposerInteractionLocked || voiceInput.isBusy) {
return;
}
- const result = await pickComposerImages({ existingCount: flow.attachments.length });
- const rejectedCount = result.images.length > 0 ? flow.appendAttachments(result.images) : 0;
+ const capabilities = selectedEnvironmentServerConfig?.environment.capabilities;
+ const result = await pickComposerMedia({
+ existingCount: flow.attachments.length,
+ maxVideoBytes:
+ capabilities?.attachmentUploads === true
+ ? capabilities.fileAttachments?.maxUploadBytes
+ : undefined,
+ });
+ const rejectedCount =
+ result.attachments.length > 0 ? flow.appendAttachments(result.attachments) : 0;
const problems = [
...(result.error ? [result.error] : []),
...(rejectedCount > 0
@@ -728,7 +737,7 @@ export function NewTaskDraftScreen(props: {
: []),
];
if (problems.length > 0) {
- Alert.alert("Could not attach photo", problems.join("\n\n"));
+ Alert.alert("Could not attach photo or video", problems.join("\n\n"));
}
}
@@ -991,7 +1000,6 @@ export function NewTaskDraftScreen(props: {
style={{
minHeight: 72,
maxHeight: 160,
- paddingHorizontal: 4,
paddingVertical: 4,
}}
textStyle={{ ...bodyText, color: foregroundColor, fontFamily: regularFontFamily }}
@@ -1115,7 +1123,7 @@ export function NewTaskDraftScreen(props: {
);
const composerDock = (
- <View className="bg-sheet px-4 pt-1" style={{ paddingBottom: controlsBottomPadding }}>
+ <View className="bg-sheet px-[12px] pt-1" style={{ paddingBottom: controlsBottomPadding }}>
{!voiceInput.isBusy && composerMenu.trigger && composerMenu.items.length > 0 ? (
<View className="mb-2">
<ComposerCommandPopover
@@ -1134,12 +1142,11 @@ export function NewTaskDraftScreen(props: {
minHeight: 140,
overflow: "hidden",
paddingBottom: 6,
- paddingHorizontal: 14,
paddingTop: 14,
}}
>
{flow.attachments.length > 0 ? (
- <View className="pb-2.5">
+ <View className="px-[14px] pb-2.5">
<ComposerAttachmentStrip
attachments={flow.attachments}
imageBorderRadius={16}
@@ -1153,12 +1160,17 @@ export function NewTaskDraftScreen(props: {
</View>
) : null}
- {promptEditor}
+ <View className="px-[14px]">{promptEditor}</View>
<View className="h-1" />
<Animated.View layout={COMPOSER_LAYOUT_TRANSITION} collapsable={false}>
<ComposerDictationToolbar showsDictation={isVoiceInputPresented}>
- <ComposerToolbarRow paddingBottom={0} paddingHorizontal={0} paddingTop={0}>
+ <ComposerToolbarRow
+ paddingBottom={0}
+ paddingHorizontal={0}
+ paddingTop={0}
+ style={{ gap: 0 }}
+ >
<ComposerDictationCancelAction
presentation={voicePresentation}
onCancel={voiceInput.cancel}
@@ -1172,58 +1184,52 @@ export function NewTaskDraftScreen(props: {
onDismissError={voiceInput.cancel}
/>
) : (
- <ComposerToolbarScroller contentPaddingRight={8} fadeSurface="sheet">
- <ComposerToolbarButton
- accessibilityLabel="Add attachment"
- disabled={isComposerInteractionLocked}
- icon="plus"
- onPress={() => {
- if (
- selectedEnvironmentServerConfig?.environment.capabilities.fileAttachments
- ) {
- Alert.alert("Add attachment", undefined, [
- { text: "Photos", onPress: () => void handlePickImages() },
- { text: "Files", onPress: () => void handlePickFiles() },
- { text: "Cancel", style: "cancel" },
- ]);
- return;
- }
- void handlePickImages();
- }}
- showChevron={false}
- />
- <ComposerInlineControl
- accessibilityLabel="Model and reasoning settings"
+ <>
+ <ComposerAttachmentButton
disabled={isComposerInteractionLocked}
- emphasized
- iconNode={
- <ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />
- }
- label={flow.selectedModelOption?.label ?? "Choose model"}
- maxWidth={152}
- onPress={settingsSheetPresentation.open}
+ supportsFiles={Boolean(
+ selectedEnvironmentServerConfig?.environment.capabilities.fileAttachments,
+ )}
+ onPickMedia={handlePickMedia}
+ onPickFiles={handlePickFiles}
/>
- {flow.planModeEnabled ? (
+ <ComposerToolbarScroller align="end" contentPaddingRight={0} fadeSurface="sheet">
<ComposerInlineControl
- accessibilityHint={`Switches to ${flow.interactionMode === "plan" ? "Build" : "Plan"} mode`}
- accessibilityLabel={`Interaction mode: ${flow.interactionMode === "plan" ? "Plan" : "Build"}`}
+ accessibilityLabel="Model and reasoning settings"
disabled={isComposerInteractionLocked}
emphasized
- icon={
- flow.interactionMode === "plan"
- ? { ios: "list.bullet.clipboard", android: "auto_awesome" }
- : { ios: "hammer", android: "construction" }
- }
- label={flow.interactionMode === "plan" ? "Plan" : "Build"}
- onPress={() =>
- flow.setInteractionMode(
- flow.interactionMode === "plan" ? "default" : "plan",
- )
+ iconNode={
+ <ProviderIcon
+ provider={flow.selectedModelOption?.providerDriver}
+ size={16}
+ />
}
- showChevron={false}
+ label={flow.selectedModelOption?.label ?? "Choose model"}
+ maxWidth={152}
+ onPress={settingsSheetPresentation.open}
/>
- ) : null}
- </ComposerToolbarScroller>
+ {flow.planModeEnabled ? (
+ <ComposerInlineControl
+ accessibilityHint={`Switches to ${flow.interactionMode === "plan" ? "Build" : "Plan"} mode`}
+ accessibilityLabel={`Interaction mode: ${flow.interactionMode === "plan" ? "Plan" : "Build"}`}
+ disabled={isComposerInteractionLocked}
+ emphasized
+ icon={
+ flow.interactionMode === "plan"
+ ? { ios: "list.bullet.clipboard", android: "auto_awesome" }
+ : { ios: "hammer", android: "construction" }
+ }
+ label={flow.interactionMode === "plan" ? "Plan" : "Build"}
+ onPress={() =>
+ flow.setInteractionMode(
+ flow.interactionMode === "plan" ? "default" : "plan",
+ )
+ }
+ showChevron={false}
+ />
+ ) : null}
+ </ComposerToolbarScroller>
+ </>
)}
<ComposerDictationPrimaryAction
state={voiceInput.state}
@@ -1235,7 +1241,7 @@ export function NewTaskDraftScreen(props: {
onCancel={voiceInput.cancel}
/>
{voicePresentation.showsSend ? (
- <ComposerToolbarButton
+ <ComposerActionButton
accessibilityLabel={
flow.submitting
? "Starting task"
@@ -1246,7 +1252,6 @@ export function NewTaskDraftScreen(props: {
disabled={!canStart}
icon={environmentConnected ? "arrow.up" : "tray.and.arrow.up"}
onPress={() => void handleStart()}
- showChevron={false}
variant="primary"
/>
) : null}
diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx
index 2a5c25e11fa..b792ecd51e2 100644
--- a/apps/mobile/src/features/threads/ThreadComposer.tsx
+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx
@@ -19,15 +19,7 @@ import {
useState,
type RefObject,
} from "react";
-import {
- ActivityIndicator,
- Alert,
- Image,
- Platform,
- Pressable,
- View,
- type ViewStyle,
-} from "react-native";
+import { ActivityIndicator, Image, Platform, Pressable, View, type ViewStyle } from "react-native";
import ImageViewing from "react-native-image-viewing";
import Animated, {
FadeIn,
@@ -46,15 +38,15 @@ import { scopedThreadKey } from "../../lib/scopedEntities";
import { AppText as Text } from "../../components/AppText";
import { SymbolView } from "../../components/AppSymbol";
+import { ComposerAttachmentButton } from "../../components/ComposerAttachmentButton";
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
import { GlassSurface } from "../../components/GlassSurface";
import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
import {
+ ComposerActionButton,
ComposerInlineControl,
- ComposerToolbarButton,
ComposerToolbarRow,
} from "../../components/ComposerToolbar";
-import { ControlPill } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
import type { DraftComposerAttachment } from "../../lib/composerImages";
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
@@ -67,6 +59,7 @@ import {
ComposerDictationCancelAction,
ComposerDictationDraftContent,
ComposerDictationPrimaryAction,
+ ComposerDictationStartAction,
ComposerDictationStatus,
ComposerDictationToolbar,
} from "../voice-input/ComposerDictationControl";
@@ -115,7 +108,7 @@ export interface ThreadComposerProps {
readonly projectCwd: string | null;
readonly editorRef?: RefObject<ComposerEditorHandle | null>;
readonly onChangeDraftMessage: (value: string) => void;
- readonly onPickDraftImages: () => Promise<void>;
+ readonly onPickDraftMedia: () => Promise<void>;
readonly onPickDraftFiles: () => Promise<void>;
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void;
@@ -315,8 +308,9 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const [previewImageUri, setPreviewImageUri] = useState<string | null>(null);
const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
const showStopAction =
- props.selectedThread.session?.status === "running" ||
- props.selectedThread.session?.status === "starting";
+ !hasContent &&
+ (props.selectedThread.session?.status === "running" ||
+ props.selectedThread.session?.status === "starting");
const sendLabel =
props.connectionState !== "connected" || props.queueCount > 0 ? "Queue" : "Send";
@@ -528,7 +522,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
return (
<Animated.View
- className="px-4"
+ className="px-[12px]"
style={{
paddingTop: isExpanded ? 8 : 6,
paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 8 : 6),
@@ -571,7 +565,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
minHeight: 140,
overflow: "hidden" as const,
paddingBottom: 6,
- paddingHorizontal: 14,
paddingTop: 14,
}
: {
@@ -579,18 +572,27 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
// shape morph stays bounded while rendering as a capsule.
borderRadius: 27,
overflow: "hidden" as const,
- paddingHorizontal: 14,
- paddingVertical: showsCompactDictation ? 2 : 5,
+ paddingVertical: 2,
}
}
>
<ComposerDictationDraftContent
className={isExpanded ? undefined : "flex-row items-center"}
- collapsed={showsCompactDictation}
+ compact={!isExpanded}
+ hidden={showsCompactDictation}
>
+ {!isExpanded ? (
+ <ComposerAttachmentButton
+ supportsFiles={Boolean(
+ props.serverConfig?.environment.capabilities.fileAttachments,
+ )}
+ onPickMedia={props.onPickDraftMedia}
+ onPickFiles={props.onPickDraftFiles}
+ />
+ ) : null}
{isExpanded ? (
<Animated.View
- className={props.draftAttachments.length > 0 ? "pb-2.5" : undefined}
+ className={props.draftAttachments.length > 0 ? "px-[14px] pb-2.5" : undefined}
entering={FadeIn.duration(160)}
exiting={FadeOut.duration(120)}
>
@@ -602,7 +604,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
</Animated.View>
) : null}
<Animated.View
- className={isExpanded ? undefined : "min-w-0 flex-1"}
+ className={isExpanded ? "px-[14px]" : "min-w-0 flex-1 px-[4px]"}
layout={COMPOSER_LAYOUT_TRANSITION}
>
<ComposerEditor
@@ -629,12 +631,10 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
? {
minHeight: 72,
maxHeight: 160,
- paddingHorizontal: 4,
paddingVertical: 4,
}
: {
height: 36,
- paddingHorizontal: 4,
}
}
textStyle={{
@@ -643,7 +643,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
}}
/>
</Animated.View>
- {!isExpanded && !voiceInput.isBusy && props.draftAttachments.length > 0 ? (
+ {!isExpanded && props.draftAttachments.length > 0 ? (
<View className="flex-row gap-1 pl-1">
{props.draftAttachments.slice(0, 3).map((attachment) =>
attachment.type === "image" ? (
@@ -675,33 +675,31 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
) : null}
</View>
) : null}
- {!isExpanded && !voiceInput.isBusy ? (
- <Animated.View
- className="flex-row items-center gap-1.5"
- entering={FadeIn.duration(180)}
- exiting={FadeOut.duration(100)}
- >
- {voiceInput.isAvailable ? (
- <ComposerDictationPrimaryAction
- state={voiceInput.state}
- presentation={voicePresentation}
- isAvailable={voiceInput.isAvailable}
- onStart={voiceInput.start}
- onConfirm={voiceInput.stop}
- onCancel={voiceInput.cancel}
- />
- ) : null}
+ {!isExpanded ? (
+ <View className="flex-row items-center">
+ <ComposerDictationStartAction
+ state={voiceInput.state}
+ isAvailable={voiceInput.isAvailable}
+ onStart={voiceInput.start}
+ onCancel={voiceInput.cancel}
+ />
{showStopAction ? (
- <ControlPill icon="stop.fill" variant="danger" onPress={props.onStopThread} />
+ <ComposerActionButton
+ accessibilityLabel="Stop agent"
+ icon="stop.fill"
+ variant="danger"
+ onPress={props.onStopThread}
+ />
) : (
- <ControlPill
+ <ComposerActionButton
+ accessibilityLabel={sendLabel}
icon="arrow.up"
variant="primary"
- disabled={!canSend}
+ disabled={!hasContent}
onPress={handleSend}
/>
)}
- </Animated.View>
+ </View>
) : null}
{isExpanded ? <View className="h-1" /> : null}
</ComposerDictationDraftContent>
@@ -712,12 +710,13 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
layout={COMPOSER_LAYOUT_TRANSITION}
pointerEvents={isToolbarVisible ? "auto" : "none"}
style={
- isToolbarVisible
+ isExpanded
? undefined
: {
- height: 0,
- opacity: 0,
- overflow: "hidden",
+ position: "absolute",
+ bottom: 2,
+ left: 0,
+ right: 0,
}
}
>
@@ -725,7 +724,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
showsDictation={isVoiceInputPresented}
visible={isToolbarVisible}
>
- <ComposerToolbarRow paddingBottom={0} paddingHorizontal={0} paddingTop={0}>
+ <ComposerToolbarRow
+ paddingBottom={0}
+ paddingHorizontal={0}
+ paddingTop={0}
+ style={{ gap: 0 }}
+ >
<ComposerDictationCancelAction
presentation={voicePresentation}
onCancel={voiceInput.cancel}
@@ -739,24 +743,15 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
onDismissError={voiceInput.cancel}
/>
) : (
- <View className="min-w-0 flex-1 flex-row items-center gap-2">
- <ComposerToolbarButton
- accessibilityLabel="Add attachment"
- icon="plus"
- onPress={() => {
- if (props.serverConfig?.environment.capabilities.fileAttachments) {
- Alert.alert("Add attachment", undefined, [
- { text: "Photos", onPress: () => void props.onPickDraftImages() },
- { text: "Files", onPress: () => void props.onPickDraftFiles() },
- { text: "Cancel", style: "cancel" },
- ]);
- return;
- }
- void props.onPickDraftImages();
- }}
- showChevron={false}
+ <View className="min-w-0 flex-1 flex-row items-center justify-between">
+ <ComposerAttachmentButton
+ supportsFiles={Boolean(
+ props.serverConfig?.environment.capabilities.fileAttachments,
+ )}
+ onPickMedia={props.onPickDraftMedia}
+ onPickFiles={props.onPickDraftFiles}
/>
- <View className="min-w-0 flex-1" style={{ maxWidth: 152 }}>
+ <View className="min-w-0 shrink" style={{ maxWidth: 152 }}>
<ComposerInlineControl
accessibilityLabel="Model and reasoning settings"
emphasized
@@ -770,7 +765,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
</View>
</View>
)}
- <View className="shrink-0 flex-row items-center gap-2">
+ <View className="shrink-0 flex-row items-center">
<ComposerDictationPrimaryAction
state={voiceInput.state}
presentation={voicePresentation}
@@ -779,23 +774,20 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
onConfirm={voiceInput.stop}
onCancel={voiceInput.cancel}
/>
- {voicePresentation.showsSend ? (
- <ComposerToolbarButton
- accessibilityLabel={sendLabel}
- icon="arrow.up"
- variant="primary"
- disabled={!canSend}
- onPress={handleSend}
- showChevron={false}
- />
- ) : null}
{showStopAction ? (
- <ComposerToolbarButton
+ <ComposerActionButton
accessibilityLabel="Stop agent"
icon="stop.fill"
variant="danger"
onPress={props.onStopThread}
- showChevron={false}
+ />
+ ) : voicePresentation.showsSend ? (
+ <ComposerActionButton
+ accessibilityLabel={sendLabel}
+ icon="arrow.up"
+ variant="primary"
+ disabled={!canSend}
+ onPress={handleSend}
/>
) : null}
</View>
diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
index c46d597adbb..41489bca952 100644
--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
@@ -121,7 +121,7 @@ export interface ThreadDetailScreenProps {
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
readonly onOpenConnectionEditor: () => void;
readonly onChangeDraftMessage: (value: string) => void;
- readonly onPickDraftImages: () => Promise<void>;
+ readonly onPickDraftMedia: () => Promise<void>;
readonly onPickDraftFiles: () => Promise<void>;
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void;
@@ -812,7 +812,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
projectCwd={props.projectWorkspaceRoot}
bottomInset={composerBottomInset}
onChangeDraftMessage={props.onChangeDraftMessage}
- onPickDraftImages={props.onPickDraftImages}
+ onPickDraftMedia={props.onPickDraftMedia}
onPickDraftFiles={props.onPickDraftFiles}
onNativePasteImages={props.onNativePasteImages}
onRemoveDraftImage={props.onRemoveDraftImage}
diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
index 6647eb3bb9a..79e898eaa1c 100644
--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
@@ -793,7 +793,7 @@ function ThreadRouteContent(
usesAutomaticContentInsets={usesNativeHeaderGlass}
onOpenConnectionEditor={handleOpenConnectionEditor}
onChangeDraftMessage={composer.onChangeDraftMessage}
- onPickDraftImages={composer.onPickDraftImages}
+ onPickDraftMedia={composer.onPickDraftMedia}
onPickDraftFiles={composer.onPickDraftFiles}
onNativePasteImages={composer.onNativePasteImages}
onRemoveDraftImage={composer.onRemoveDraftImage}
diff --git a/apps/mobile/src/features/voice-input/ComposerDictationControl.tsx b/apps/mobile/src/features/voice-input/ComposerDictationControl.tsx
index 739825a57fa..93838440ad6 100644
--- a/apps/mobile/src/features/voice-input/ComposerDictationControl.tsx
+++ b/apps/mobile/src/features/voice-input/ComposerDictationControl.tsx
@@ -10,13 +10,12 @@ import {
} from "react-native";
import Animated, {
Easing,
- FadeIn,
- FadeOut,
LinearTransition,
ReduceMotion,
useAnimatedStyle,
useSharedValue,
withTiming,
+ type EntryExitAnimationFunction,
type SharedValue,
} from "react-native-reanimated";
@@ -35,8 +34,56 @@ const DICTATION_LAYOUT =
Platform.OS === "android"
? undefined
: LinearTransition.duration(DICTATION_TIMING.duration).reduceMotion(ReduceMotion.System);
-const DICTATION_ENTERING = FadeIn.duration(180).reduceMotion(ReduceMotion.System);
-const DICTATION_EXITING = FadeOut.duration(120).reduceMotion(ReduceMotion.System);
+const TOOLBAR_FLIP_TIMING = {
+ duration: 260,
+ easing: Easing.inOut(Easing.cubic),
+ reduceMotion: ReduceMotion.System,
+} as const;
+const TOOLBAR_HALF_HEIGHT = 22;
+const TOOLBAR_PERSPECTIVE = 600;
+
+/** Moves each face around the same horizontal axis, keeping their edges together. */
+function toolbarFlip(fromDegrees: number, toDegrees: number): EntryExitAnimationFunction {
+ return () => {
+ "worklet";
+ const fromRadians = (fromDegrees * Math.PI) / 180;
+ const toRadians = (toDegrees * Math.PI) / 180;
+ const fromSine = Math.sin(fromRadians);
+ const toSine = Math.sin(toRadians);
+ return {
+ initialValues: {
+ opacity: fromDegrees === 0 ? 1 : 0,
+ transform: [
+ { perspective: TOOLBAR_PERSPECTIVE },
+ { translateY: -TOOLBAR_HALF_HEIGHT * fromSine },
+ { rotateX: `${fromDegrees}deg` },
+ ],
+ },
+ animations: {
+ opacity: withTiming(toDegrees === 0 ? 1 : 0, TOOLBAR_FLIP_TIMING),
+ transform: [
+ { perspective: TOOLBAR_PERSPECTIVE },
+ {
+ translateY: withTiming(-TOOLBAR_HALF_HEIGHT * toSine, {
+ ...TOOLBAR_FLIP_TIMING,
+ easing: (time) => {
+ const angle =
+ fromRadians + (toRadians - fromRadians) * TOOLBAR_FLIP_TIMING.easing(time);
+ return (Math.sin(angle) - fromSine) / (toSine - fromSine);
+ },
+ }),
+ },
+ { rotateX: withTiming(`${toDegrees}deg`, TOOLBAR_FLIP_TIMING) },
+ ],
+ },
+ };
+ };
+}
+
+const DRAFT_TOOLBAR_ENTERING = toolbarFlip(90, 0);
+const DRAFT_TOOLBAR_EXITING = toolbarFlip(0, 90);
+const DICTATION_TOOLBAR_ENTERING = toolbarFlip(-90, 0);
+const DICTATION_TOOLBAR_EXITING = toolbarFlip(0, -90);
const WAVEFORM_BAR_HEIGHT = 32;
const WAVEFORM_MIN_BAR_HEIGHT = 2;
const WAVEFORM_BAR_SPACING = 5;
@@ -46,51 +93,63 @@ const WAVEFORM_TIMING = {
reduceMotion: ReduceMotion.System,
} as const;
-/** Keeps the native editor mounted when compact dictation replaces the draft area. */
+/** Rotates the compact draft away without unmounting or resizing its native editor. */
export function ComposerDictationDraftContent(props: {
readonly children: ReactNode;
readonly className?: string;
- readonly collapsed: boolean;
+ readonly compact: boolean;
+ readonly hidden: boolean;
}) {
- const visibility = useSharedValue(props.collapsed ? 0 : 1);
+ const rotation = useSharedValue(props.hidden ? 1 : 0);
useLayoutEffect(() => {
- visibility.value = withTiming(props.collapsed ? 0 : 1, DICTATION_TIMING);
- }, [props.collapsed, visibility]);
+ rotation.value = withTiming(props.hidden ? 1 : 0, TOOLBAR_FLIP_TIMING);
+ }, [props.hidden, rotation]);
+ const compact = props.compact;
const animatedStyle = useAnimatedStyle(() => ({
- opacity: visibility.value,
- transform: [{ translateY: -4 * (1 - visibility.value) }],
+ opacity: compact ? 1 - rotation.value : 1,
+ transform: compact
+ ? [
+ { perspective: TOOLBAR_PERSPECTIVE },
+ { translateY: -TOOLBAR_HALF_HEIGHT * Math.sin((rotation.value * Math.PI) / 2) },
+ { rotateX: `${rotation.value * 90}deg` },
+ ]
+ : [],
}));
return (
<Animated.View
- accessibilityElementsHidden={props.collapsed}
- importantForAccessibility={props.collapsed ? "no-hide-descendants" : "auto"}
+ accessibilityElementsHidden={props.hidden}
+ importantForAccessibility={props.hidden ? "no-hide-descendants" : "auto"}
collapsable={false}
className={props.className}
layout={DICTATION_LAYOUT}
- style={[animatedStyle, { overflow: "hidden" }, props.collapsed ? { height: 0 } : undefined]}
+ pointerEvents={props.hidden ? "none" : "auto"}
+ style={[animatedStyle, { backfaceVisibility: "hidden" }]}
>
{props.children}
</Animated.View>
);
}
-/** Crossfades controls within one toolbar row while the draft keeps its position. */
+/** Flips the entire row while keeping the outgoing controls intact until it leaves. */
export function ComposerDictationToolbar(props: {
readonly children: ReactNode;
readonly showsDictation: boolean;
readonly visible?: boolean;
}) {
return (
- <View className="relative h-11">
- <Animated.View
- key={props.showsDictation ? "dictation" : "draft"}
- className="absolute inset-0"
- entering={DICTATION_ENTERING}
- exiting={props.visible === false ? undefined : DICTATION_EXITING}
- >
- {props.children}
- </Animated.View>
+ <View className="relative h-[44px] overflow-hidden">
+ {props.visible !== false ? (
+ <Animated.View
+ key={props.showsDictation ? "dictation" : "draft"}
+ className="absolute inset-0"
+ entering={props.showsDictation ? DICTATION_TOOLBAR_ENTERING : DRAFT_TOOLBAR_ENTERING}
+ exiting={props.showsDictation ? DICTATION_TOOLBAR_EXITING : DRAFT_TOOLBAR_EXITING}
+ style={{ backfaceVisibility: "hidden" }}
+ >
+ {props.children}
+ </Animated.View>
+ ) : null}
</View>
);
}
@@ -179,19 +238,15 @@ function VoiceActionButton(props: {
accessibilityLabel={props.accessibilityLabel}
accessibilityRole="button"
accessibilityState={{ busy: props.loading, disabled: props.disabled }}
- className={cn(
- "items-center justify-center active:opacity-70",
- variant === "primary" ? "size-11" : "size-9",
- )}
+ className="size-[44px] shrink-0 items-center justify-center active:opacity-70"
disabled={props.disabled}
- hitSlop={variant === "plain" ? 4 : undefined}
onPress={props.onPress}
style={{ opacity: props.disabled && !props.loading ? 0.4 : 1 }}
>
<View
className={cn(
"items-center justify-center",
- variant === "primary" ? "size-11 rounded-full bg-subtle" : "size-9",
+ variant === "primary" ? "size-[30px] rounded-full bg-subtle" : "size-[44px]",
)}
>
{variant === "primary" ? (
@@ -200,25 +255,21 @@ function VoiceActionButton(props: {
style={primaryStyle}
/>
) : null}
- <Animated.View
- key={props.loading ? "loading" : "icon"}
- className="absolute inset-0 items-center justify-center"
- entering={DICTATION_ENTERING}
- exiting={DICTATION_EXITING}
- >
+ <View className="absolute inset-0 items-center justify-center">
{props.loading ? (
<ActivityIndicator size="small" colorClassName="accent-icon-muted" />
) : (
<SymbolView
name={props.icon}
- size={17}
+ size={variant === "primary" ? 16 : 20}
+ weight={variant === "primary" ? "semibold" : "regular"}
tintColorClassName={
variant === "primary" ? "accent-primary-foreground" : "accent-icon"
}
type="monochrome"
/>
)}
- </Animated.View>
+ </View>
</View>
</Pressable>
);
@@ -237,11 +288,9 @@ export function ComposerDictationStatus(props: {
}, [props.phase, recordingVisibility]);
const waveformStyle = useAnimatedStyle(() => ({
opacity: recordingVisibility.value,
- transform: [{ translateY: -4 * (1 - recordingVisibility.value) }],
}));
const labelStyle = useAnimatedStyle(() => ({
opacity: 1 - recordingVisibility.value,
- transform: [{ translateY: 4 * recordingVisibility.value }],
}));
if (!props.presentation.statusLabel) return null;
@@ -340,6 +389,16 @@ export function ComposerDictationPrimaryAction(props: {
);
}
+ return <ComposerDictationStartAction {...props} />;
+}
+
+export function ComposerDictationStartAction(props: {
+ readonly state: VoiceInputState;
+ readonly isAvailable: boolean;
+ readonly disabled?: boolean;
+ readonly onStart: () => void;
+ readonly onCancel: () => void;
+}) {
if (!props.isAvailable) return null;
const openSettings = props.state.phase === "error" && props.state.errorAction === "settings";
return (
diff --git a/apps/mobile/src/lib/composerFiles.test.ts b/apps/mobile/src/lib/composerFiles.test.ts
index 3f0270ca5c9..f52bd9276cf 100644
--- a/apps/mobile/src/lib/composerFiles.test.ts
+++ b/apps/mobile/src/lib/composerFiles.test.ts
@@ -1,8 +1,10 @@
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import type { ImagePickerAsset } from "expo-image-picker";
const mocks = vi.hoisted(() => ({
documentUri: "file:///documents",
pickFile: vi.fn(),
+ pickMedia: vi.fn(),
copy: vi.fn(),
delete: vi.fn(),
open: vi.fn(),
@@ -37,6 +39,14 @@ vi.mock("expo-file-system", () => {
return mocks.size(this.uri) ?? null;
}
+ get name(): string {
+ return this.uri.split("/").at(-1) ?? "";
+ }
+
+ get type(): string {
+ return "video/quicktime";
+ }
+
create(): void {}
open(mode: string) {
@@ -64,18 +74,23 @@ vi.mock("expo-file-system", () => {
};
});
+vi.mock("expo-image-picker", () => ({ launchImageLibraryAsync: mocks.pickMedia }));
vi.mock("./uuid", () => ({ uuidv4: () => "attachment-id" }));
import {
persistComposerAttachmentFile,
pickComposerFiles,
+ pickComposerImages,
+ pickComposerMedia,
removePersistedComposerAttachmentFile,
} from "./composerImages";
+import { isForegroundHandoffActive } from "./foreground-handoff";
-describe("pickComposerFiles", () => {
+describe("composer file attachments", () => {
beforeEach(() => {
mocks.documentUri = "file:///documents";
mocks.pickFile.mockReset();
+ mocks.pickMedia.mockReset();
mocks.copy.mockReset();
mocks.delete.mockReset();
mocks.open.mockReset();
@@ -83,6 +98,179 @@ describe("pickComposerFiles", () => {
mocks.size.mockImplementation((uri: string) => (uri.startsWith("content:") ? null : 42));
});
+ describe("photo library videos", () => {
+ const image: ImagePickerAsset = {
+ uri: "file:///picker/photo.png",
+ type: "image",
+ fileName: "photo.png",
+ mimeType: "image/png",
+ fileSize: 3,
+ base64: "YWJj",
+ width: 1,
+ height: 1,
+ };
+ const video: ImagePickerAsset = {
+ uri: "file:///picker/clip.mov",
+ type: "video",
+ fileName: "clip.mov",
+ mimeType: "video/quicktime",
+ fileSize: 20 * 1024 * 1024,
+ base64: null,
+ width: 1920,
+ height: 1080,
+ };
+
+ it("retains mixed photos and videos, keeping video bytes in durable file storage", async () => {
+ mocks.pickMedia.mockResolvedValue({ canceled: false, assets: [image, video] });
+ mocks.size.mockReturnValue(video.fileSize);
+
+ const result = await pickComposerMedia({ existingCount: 0, maxVideoBytes: 50 * 1024 * 1024 });
+
+ expect(mocks.pickMedia).toHaveBeenCalledWith(
+ expect.objectContaining({
+ mediaTypes: ["images", "videos"],
+ shouldDownloadFromNetwork: true,
+ }),
+ );
+ expect(result).toEqual({
+ attachments: [
+ expect.objectContaining({ type: "image", dataUrl: "data:image/png;base64,YWJj" }),
+ {
+ id: "attachment-id",
+ type: "file",
+ name: "clip.mov",
+ mimeType: "video/quicktime",
+ sizeBytes: video.fileSize,
+ fileUri: "file:///documents/t3-composer-attachments/attachment-id-clip.mov",
+ },
+ ],
+ error: null,
+ });
+ expect(mocks.copy).toHaveBeenCalledWith(
+ video.uri,
+ "file:///documents/t3-composer-attachments/attachment-id-clip.mov",
+ );
+ expect(mocks.delete).not.toHaveBeenCalled();
+ });
+
+ it("keeps image-only destinations on the image picker path", async () => {
+ mocks.pickMedia.mockResolvedValue({ canceled: false, assets: [image] });
+
+ const result = await pickComposerImages({ existingCount: 0 });
+
+ expect(mocks.pickMedia).toHaveBeenCalledWith(
+ expect.objectContaining({ mediaTypes: ["images"] }),
+ );
+ expect(result.images).toEqual([
+ expect.objectContaining({ type: "image", name: "photo.png" }),
+ ]);
+ expect(result.error).toBeNull();
+ expect(mocks.copy).not.toHaveBeenCalled();
+ });
+
+ it("does not persist videos when the destination lacks file support", async () => {
+ mocks.pickMedia.mockResolvedValue({ canceled: false, assets: [video, image] });
+
+ const result = await pickComposerMedia({ existingCount: 0 });
+
+ expect(result.attachments).toEqual([expect.objectContaining({ type: "image" })]);
+ expect(result.error).toBe("Video attachments are unavailable here.");
+ expect(mocks.copy).not.toHaveBeenCalled();
+ });
+
+ it("uses local video metadata when the picker omits its name, MIME type, or size", async () => {
+ mocks.pickMedia.mockResolvedValue({
+ canceled: false,
+ assets: [{ ...video, fileName: null, mimeType: undefined, fileSize: undefined }],
+ });
+
+ const result = await pickComposerMedia({ existingCount: 0, maxVideoBytes: 1024 });
+
+ expect(result.error).toBeNull();
+ expect(result.attachments).toEqual([
+ expect.objectContaining({
+ type: "file",
+ name: "clip.mov",
+ mimeType: "video/quicktime",
+ sizeBytes: 42,
+ }),
+ ]);
+ });
+
+ it.each([
+ {
+ reason: "picker size exceeds the server limit",
+ reported: 2 * 1024 * 1024,
+ stored: 42,
+ limit: 1024 * 1024,
+ error: "'clip.mov' exceeds the 1 MB attachment limit.",
+ },
+ {
+ reason: "actual size exceeds the server limit",
+ reported: 42,
+ stored: 2 * 1024 * 1024,
+ limit: 1024 * 1024,
+ error: "'clip.mov' exceeds the 1 MB attachment limit.",
+ },
+ {
+ reason: "stored copy is empty",
+ reported: 42,
+ stored: 0,
+ limit: 1024 * 1024,
+ error: "'clip.mov' is empty or could not be read.",
+ },
+ {
+ reason: "server advertises more than the contract limit",
+ reported: 51 * 1024 * 1024,
+ stored: 42,
+ limit: 80 * 1024 * 1024,
+ error: "'clip.mov' exceeds the 50 MB attachment limit.",
+ },
+ ])(
+ "rejects a video when $reason while retaining the selected photo",
+ async ({ reported, stored, limit, error }) => {
+ mocks.pickMedia.mockResolvedValue({
+ canceled: false,
+ assets: [{ ...video, fileSize: reported }, image],
+ });
+ mocks.size.mockReturnValue(stored);
+
+ const result = await pickComposerMedia({ existingCount: 0, maxVideoBytes: limit });
+
+ expect(result).toEqual({
+ attachments: [expect.objectContaining({ type: "image" })],
+ error,
+ });
+ if (stored === 0) {
+ expect(mocks.delete).toHaveBeenCalledWith(
+ "file:///documents/t3-composer-attachments/attachment-id-clip.mov",
+ );
+ }
+ },
+ );
+
+ it("applies the remaining attachment slots to photos and videos together", async () => {
+ mocks.pickMedia.mockResolvedValue({ canceled: false, assets: [image, video] });
+
+ const result = await pickComposerMedia({ existingCount: 7, maxVideoBytes: 50 * 1024 * 1024 });
+
+ expect(result.attachments).toEqual([expect.objectContaining({ type: "image" })]);
+ expect(result.error).toBe("You can attach up to 8 attachments per message.");
+ expect(mocks.pickMedia).toHaveBeenCalledWith(expect.objectContaining({ selectionLimit: 1 }));
+ expect(mocks.copy).not.toHaveBeenCalled();
+ });
+
+ it("reports a native video retrieval error and ends the foreground handoff", async () => {
+ mocks.pickMedia.mockRejectedValue(new Error("Could not download video from iCloud."));
+
+ await expect(pickComposerMedia({ existingCount: 0, maxVideoBytes: 1024 })).resolves.toEqual({
+ attachments: [],
+ error: "Could not download video from iCloud.",
+ });
+ expect(isForegroundHandoffActive()).toBe(false);
+ });
+ });
+
it("copies picked files into app-owned storage without loading their contents", async () => {
mocks.pickFile.mockResolvedValue({
canceled: false,
diff --git a/apps/mobile/src/lib/composerImages.ts b/apps/mobile/src/lib/composerImages.ts
index 4e8908b71eb..c1919315021 100644
--- a/apps/mobile/src/lib/composerImages.ts
+++ b/apps/mobile/src/lib/composerImages.ts
@@ -157,6 +157,40 @@ export async function removePersistedComposerAttachmentFile(uri: string): Promis
}
}
+async function createComposerFileAttachment(input: {
+ readonly uri: string;
+ readonly name: string;
+ readonly mimeType: string;
+ readonly sizeBytes: number | null;
+ readonly maxBytes: number;
+}): Promise<DraftComposerFileAttachment> {
+ if (input.sizeBytes !== null && input.sizeBytes > input.maxBytes) {
+ throw new Error(fileAttachmentTooLargeMessage(input.name, input.maxBytes));
+ }
+ const { File } = await import("expo-file-system");
+ const fileUri = await persistComposerAttachmentFile(input.uri, input.name, input.maxBytes);
+ try {
+ const sizeBytes = new File(fileUri).size ?? input.sizeBytes ?? 0;
+ if (sizeBytes <= 0) {
+ throw new Error(`'${input.name}' is empty or could not be read.`);
+ }
+ if (sizeBytes > input.maxBytes) {
+ throw new Error(fileAttachmentTooLargeMessage(input.name, input.maxBytes));
+ }
+ return {
+ id: uuidv4(),
+ type: "file",
+ name: input.name,
+ mimeType: input.mimeType,
+ sizeBytes,
+ fileUri,
+ };
+ } catch (error) {
+ await removePersistedComposerAttachmentFile(fileUri);
+ throw error;
+ }
+}
+
export async function pickComposerFiles(input: {
readonly existingCount: number;
readonly maxBytes?: number;
@@ -199,32 +233,16 @@ export async function pickComposerFiles(input: {
// contract rejects empty names at send time, so fall back before the name
// reaches storage, errors, or the attachment itself.
const name = file.name.trim().length > 0 ? file.name : "file";
- const sizeBytes = file.size ?? null;
- if (sizeBytes !== null && sizeBytes > maxBytes) {
- error = fileAttachmentTooLargeMessage(name, maxBytes);
- continue;
- }
try {
- const fileUri = await persistComposerAttachmentFile(file.uri, name, maxBytes);
- const storedSizeBytes = new File(fileUri).size ?? sizeBytes ?? 0;
- if (storedSizeBytes <= 0) {
- await removePersistedComposerAttachmentFile(fileUri);
- error = `'${name}' is empty or could not be read.`;
- continue;
- }
- if (storedSizeBytes > maxBytes) {
- await removePersistedComposerAttachmentFile(fileUri);
- error = fileAttachmentTooLargeMessage(name, maxBytes);
- continue;
- }
- attachments.push({
- id: uuidv4(),
- type: "file",
- name,
- mimeType: file.type || "application/octet-stream",
- sizeBytes: storedSizeBytes,
- fileUri,
- });
+ attachments.push(
+ await createComposerFileAttachment({
+ uri: file.uri,
+ name,
+ mimeType: file.type || "application/octet-stream",
+ sizeBytes: file.size ?? null,
+ maxBytes,
+ }),
+ );
} catch (cause) {
error = cause instanceof Error ? cause.message : `Could not read '${name}'.`;
}
@@ -239,7 +257,7 @@ async function loadImagePicker() {
try {
return await import("expo-image-picker");
} catch (error) {
- throw new Error("Image attachments are unavailable right now.", { cause: error });
+ throw new Error("The photo library is unavailable right now.", { cause: error });
}
}
@@ -254,12 +272,27 @@ async function loadClipboard() {
export async function pickComposerImages(input: { readonly existingCount: number }): Promise<{
readonly images: ReadonlyArray<DraftComposerImageAttachment>;
readonly error: string | null;
+}> {
+ const result = await pickComposerMedia(input);
+ return {
+ images: result.attachments.filter((attachment) => attachment.type === "image"),
+ error: result.error,
+ };
+}
+
+/** Videos use file uploads; omit maxVideoBytes for image-only destinations. */
+export async function pickComposerMedia(input: {
+ readonly existingCount: number;
+ readonly maxVideoBytes?: number;
+}): Promise<{
+ readonly attachments: ReadonlyArray<DraftComposerAttachment>;
+ readonly error: string | null;
}> {
const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
if (remainingSlots <= 0) {
return {
- images: [],
- error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`,
+ attachments: [],
+ error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`,
};
}
@@ -268,9 +301,8 @@ export async function pickComposerImages(input: { readonly existingCount: number
imagePicker = await loadImagePicker();
} catch (error) {
return {
- images: [],
- error:
- error instanceof Error ? error.message : "Image attachments are unavailable right now.",
+ attachments: [],
+ error: error instanceof Error ? error.message : "The photo library is unavailable right now.",
};
}
@@ -280,28 +312,61 @@ export async function pickComposerImages(input: { readonly existingCount: number
let result: Awaited<ReturnType<typeof imagePicker.launchImageLibraryAsync>>;
try {
result = await imagePicker.launchImageLibraryAsync({
- mediaTypes: ["images"],
+ mediaTypes: input.maxVideoBytes === undefined ? ["images"] : ["images", "videos"],
allowsMultipleSelection: true,
selectionLimit: remainingSlots,
base64: true,
quality: 1,
+ shouldDownloadFromNetwork: true,
});
+ } catch (error) {
+ return {
+ attachments: [],
+ error: error instanceof Error ? error.message : "Could not open the photo library.",
+ };
} finally {
endHandoff();
}
if (result.canceled) {
return {
- images: [],
+ attachments: [],
error: null,
};
}
- const nextImages: DraftComposerImageAttachment[] = [];
+ const attachments: DraftComposerAttachment[] = [];
let error: string | null = null;
for (const asset of result.assets) {
+ if (attachments.length >= remainingSlots) {
+ error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`;
+ break;
+ }
const mimeType = asset.mimeType?.toLowerCase();
+ if (asset.type === "video" || mimeType?.startsWith("video/")) {
+ if (input.maxVideoBytes === undefined) {
+ error = "Video attachments are unavailable here.";
+ continue;
+ }
+ try {
+ const { File } = await import("expo-file-system");
+ const file = new File(asset.uri);
+ attachments.push(
+ await createComposerFileAttachment({
+ uri: asset.uri,
+ name: asset.fileName?.trim() || file.name || "video",
+ mimeType: mimeType || file.type || "application/octet-stream",
+ sizeBytes: asset.fileSize ?? null,
+ maxBytes: clampFileAttachmentUploadBytes(input.maxVideoBytes),
+ }),
+ );
+ } catch (cause) {
+ error =
+ cause instanceof Error ? cause.message : `Could not read '${asset.fileName ?? "video"}'.`;
+ }
+ continue;
+ }
if (!mimeType?.startsWith("image/")) {
error = `Unsupported file type for '${asset.fileName ?? "image"}'.`;
continue;
@@ -323,7 +388,7 @@ export async function pickComposerImages(input: { readonly existingCount: number
continue;
}
- nextImages.push({
+ attachments.push({
id: uuidv4(),
type: "image",
name: asset.fileName ?? "image",
@@ -335,7 +400,7 @@ export async function pickComposerImages(input: { readonly existingCount: number
}
return {
- images: nextImages,
+ attachments,
error,
};
}
diff --git a/apps/mobile/src/lib/menu-action-colors.test.ts b/apps/mobile/src/lib/menu-action-colors.test.ts
new file mode 100644
index 00000000000..a6ee03e58c4
--- /dev/null
+++ b/apps/mobile/src/lib/menu-action-colors.test.ts
@@ -0,0 +1,67 @@
+import type { MenuAction } from "@react-native-menu/menu";
+import { describe, expect, it } from "vite-plus/test";
+
+import { withMenuActionIconColors } from "./menu-action-colors";
+
+describe("withMenuActionIconColors", () => {
+ it.each(["#111111", "#eeeeee"])(
+ "gives icons a visible color at every menu depth for the %s theme",
+ (icon) => {
+ const actions: MenuAction[] = [
+ { id: "photos", title: "Photos", image: "photo" },
+ {
+ title: "Thread",
+ subactions: [
+ {
+ title: "Pinned thread",
+ image: "pin",
+ subactions: [{ title: "Move up", image: "arrow.up" }],
+ },
+ ],
+ },
+ ];
+
+ const result = withMenuActionIconColors(actions, { icon, destructiveIcon: "#ff0000" });
+
+ expect(result[0]?.imageColor).toBe(icon);
+ expect(result[1]).not.toHaveProperty("imageColor");
+ expect(result[1]?.subactions?.[0]?.imageColor).toBe(icon);
+ expect(result[1]?.subactions?.[0]?.subactions?.[0]?.imageColor).toBe(icon);
+ expect(actions[0]).not.toHaveProperty("imageColor");
+ expect(actions[1]?.subactions?.[0]).not.toHaveProperty("imageColor");
+ },
+ );
+
+ it("uses the destructive color while retaining action state and attributes", () => {
+ const action: MenuAction = {
+ id: "delete",
+ title: "Delete",
+ image: "trash",
+ state: "off",
+ attributes: { destructive: true, disabled: true },
+ };
+
+ expect(
+ withMenuActionIconColors([action], {
+ icon: "#111111",
+ destructiveIcon: "#cc0000",
+ }),
+ ).toEqual([{ ...action, imageColor: "#cc0000" }]);
+ });
+
+ it.each(["#123456", "transparent", 0])("preserves explicit icon color %s", (imageColor) => {
+ const action: MenuAction = {
+ title: "Delete",
+ image: "trash",
+ imageColor,
+ attributes: { destructive: true },
+ };
+
+ expect(
+ withMenuActionIconColors([action], {
+ icon: "#111111",
+ destructiveIcon: "#cc0000",
+ }),
+ ).toEqual([action]);
+ });
+});
diff --git a/apps/mobile/src/lib/menu-action-colors.ts b/apps/mobile/src/lib/menu-action-colors.ts
new file mode 100644
index 00000000000..611784319ca
--- /dev/null
+++ b/apps/mobile/src/lib/menu-action-colors.ts
@@ -0,0 +1,24 @@
+import type { MenuAction } from "@react-native-menu/menu";
+
+// MenuView's iOS bridge treats an omitted imageColor as transparent.
+export function withMenuActionIconColors(
+ actions: readonly MenuAction[],
+ colors: {
+ readonly icon: MenuAction["imageColor"];
+ readonly destructiveIcon: MenuAction["imageColor"];
+ },
+): MenuAction[] {
+ return actions.map((action) => ({
+ ...action,
+ ...(action.image
+ ? {
+ imageColor:
+ action.imageColor ??
+ (action.attributes?.destructive ? colors.destructiveIcon : colors.icon),
+ }
+ : {}),
+ ...(action.subactions
+ ? { subactions: withMenuActionIconColors(action.subactions, colors) }
+ : {}),
+ }));
+}
diff --git a/apps/mobile/src/state/use-composer-drafts.test.ts b/apps/mobile/src/state/use-composer-drafts.test.ts
index c2f69d887e6..3ab0baa3904 100644
--- a/apps/mobile/src/state/use-composer-drafts.test.ts
+++ b/apps/mobile/src/state/use-composer-drafts.test.ts
@@ -221,40 +221,49 @@ describe("mobile composer drafts", () => {
});
});
- it("caps appended attachments at the send limit against the live draft", () => {
+ it("releases videos rejected by the live draft limit and keeps accepted files", async () => {
+ const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
+ onTestFinished(() => outboxLoad.mockRestore());
+ const cleanup = Promise.withResolvers<void>();
+ composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
+ cleanup.resolve();
+ });
const makeAttachment = (id: string) => ({
id,
type: "file" as const,
- name: `${id}.pdf`,
- mimeType: "application/pdf",
+ name: `${id}.mov`,
+ mimeType: "video/quicktime",
sizeBytes: 42,
- fileUri: `file:///documents/t3-composer-attachments/${id}.pdf`,
+ fileUri: `file:///documents/t3-composer-attachments/${id}.mov`,
});
+ const draftKey = "new-task:environment-1:project-cap";
const existing = Array.from({ length: 7 }, (_, index) => makeAttachment(`held-${index}`));
appAtomRegistry.set(composerDraftsAtom, {
- "environment-1:thread-cap": { text: "send this", attachments: existing },
+ [draftKey]: { text: "send this", attachments: existing },
});
- const rejected = appendComposerDraftAttachments("environment-1:thread-cap", [
+ const rejected = appendComposerDraftAttachments(draftKey, [
makeAttachment("incoming-1"),
makeAttachment("incoming-2"),
]);
expect(rejected).toBe(1);
- const draft = appAtomRegistry.get(composerDraftsAtom)["environment-1:thread-cap"];
+ const draft = appAtomRegistry.get(composerDraftsAtom)[draftKey];
expect(draft?.attachments).toHaveLength(8);
expect(draft?.attachments.at(-1)?.id).toBe("incoming-1");
+ await cleanup.promise;
+ expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledExactlyOnceWith(
+ makeAttachment("incoming-2").fileUri,
+ );
// Restore paths bypass the cap so a failed send never drops its files.
const overflowRejected = appendComposerDraftAttachments(
- "environment-1:thread-cap",
+ draftKey,
[makeAttachment("restored-1")],
{ allowOverflow: true },
);
expect(overflowRejected).toBe(0);
- expect(
- appAtomRegistry.get(composerDraftsAtom)["environment-1:thread-cap"]?.attachments,
- ).toHaveLength(9);
+ expect(appAtomRegistry.get(composerDraftsAtom)[draftKey]?.attachments).toHaveLength(9);
});
it("keeps shared attachment files until every draft releases them", async () => {
diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts
index 7b220093796..603a38ecc81 100644
--- a/apps/mobile/src/state/use-thread-composer-state.ts
+++ b/apps/mobile/src/state/use-thread-composer-state.ts
@@ -28,7 +28,7 @@ import {
convertPastedImagesToAttachments,
pasteComposerClipboard,
pickComposerFiles,
- pickComposerImages,
+ pickComposerMedia,
} from "../lib/composerImages";
import type { DraftComposerImageAttachment } from "../lib/composerImages";
import { scopedThreadKey } from "../lib/scopedEntities";
@@ -316,26 +316,31 @@ export function useThreadComposerState() {
[selectedThreadShell],
);
- const onPickDraftImages = useCallback(async () => {
+ const onPickDraftMedia = useCallback(async () => {
if (!selectedThreadShell) {
return;
}
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
- const result = await pickComposerImages({
+ const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
+ const result = await pickComposerMedia({
existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
+ maxVideoBytes:
+ capabilities?.attachmentUploads === true
+ ? capabilities.fileAttachments?.maxUploadBytes
+ : undefined,
});
- const rejectedImageCount = appendComposerDraftAttachments(threadKey, result.images);
+ const rejectedCount = appendComposerDraftAttachments(threadKey, result.attachments);
const problems = [
...(result.error ? [result.error] : []),
- ...(rejectedImageCount > 0
+ ...(rejectedCount > 0
? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`]
: []),
];
if (problems.length > 0) {
- Alert.alert("Could not attach image", problems.join("\n\n"));
+ Alert.alert("Could not attach photo or video", problems.join("\n\n"));
}
- }, [composerDrafts, selectedThreadShell]);
+ }, [composerDrafts, selectedEnvironmentRuntime?.serverConfig, selectedThreadShell]);
const onPickDraftFiles = useCallback(async () => {
if (!selectedThreadShell) {
@@ -470,7 +475,7 @@ export function useThreadComposerState() {
runtimeMode,
interactionMode,
onChangeDraftMessage,
- onPickDraftImages,
+ onPickDraftMedia,
onPickDraftFiles,
onPasteIntoDraft,
onNativePasteImages,
diff --git a/docs/internals/mobile-navigation.md b/docs/internals/mobile-navigation.md
index b559f39bcbc..86c61921ffc 100644
--- a/docs/internals/mobile-navigation.md
+++ b/docs/internals/mobile-navigation.md
@@ -41,3 +41,10 @@ After changing a dependency patch, refresh CocoaPods before rebuilding an
existing iOS project. pnpm installs each patch hash in a different directory;
an old Pods project can keep compiling the previous directory even though Metro
and `apps/mobile/node_modules` resolve to the new patch.
+
+`ControlPillMenu` resolves semantic icon colors through `withUniwind` and supplies them to every
+iOS `MenuView` action, including nested actions. The menu library's Fabric bridge converts a missing
+`imageColor` to transparent, so callers should use this wrapper instead of
+rendering `MenuView` directly. Explicit colors are preserved, and destructive
+actions default to the theme's danger foreground color. Native stack header menus
+use a separate implementation and do not need this workaround.
diff --git a/docs/user/composer.md b/docs/user/composer.md
index 19365317564..2a4b3b127d0 100644
--- a/docs/user/composer.md
+++ b/docs/user/composer.md
@@ -4,15 +4,21 @@ Messages can contain up to 120,000 characters. If a draft is longer, T3 Code kee
composer and shows how many characters need to be removed. Shorten the draft or split it into
multiple messages, then send again in the same thread.
+On mobile, an empty composer shows an interrupt button while the agent is working. Adding text
+or an attachment replaces it with the send button. This applies to both compact and expanded
+composers.
+
You can attach images up to 10 MB. On servers that support file uploads, you can also
-attach text files, PDFs, ZIP archives, and other files. Each file can be up to the limit advertised
+attach videos, text files, PDFs, ZIP archives, and other files. Each file can be up to the limit advertised
by the server, capped at 50 MB. Each message can contain up to eight attachments in total. Files
upload directly to the environment, where your agent can read, copy, or edit them by their file path.
On web and desktop, attachments upload as soon as you add them. The send button becomes available
-after every upload finishes. Failed uploads can be retried or removed. On mobile, the **+** control
-offers Photos, and adds Files when the connected server supports file uploads. You can share a file
-into T3 Code from any app through the system share sheet. Mobile uploads happen when the message
+after every upload finishes. Failed uploads can be retried or removed. On mobile, tap **+** to open
+the photo library from either the compact or expanded composer. When the connected server supports
+file uploads, **+** opens a menu beside the button with **Photo Library** and **Choose Files**.
+Videos use the server's file upload limit. You can also share photos, videos, and files into
+T3 Code from other apps through the system share sheet. Mobile uploads happen when the message
sends, so queued messages keep their files until they deliver. Select a received file on mobile
to save it or open it in another app through the system share sheet.
@@ -41,9 +47,10 @@ send.
## Voice input on iPhone
On supported iPhones with iOS 26 or later, tap the microphone in the composer to record a message.
-An expanded composer keeps your draft visible and replaces its toolbar with waves that respond to
-your voice. A collapsed composer shows a compact recording strip instead. Tap the checkmark to
-finish and transcribe on your device. The waves fade into a transcription status, then the usual
+An expanded composer keeps your draft visible and flips its bottom toolbar into recording controls
+with waves that respond to your voice. A collapsed composer flips into a compact recording strip
+without changing height. Tap the checkmark to finish and transcribe on your device. The waves fade
+into a transcription status, then the usual
controls return with the text inserted at the selection where recording started. If the keyboard
is open when you start, it stays open during voice input. You can review and edit the text before
you send it.