Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import type {
3 EnvironmentId,
4 MessageId,
5 ModelSelection,
6 OrchestrationThreadShell,
7 ProviderInteractionMode,
8 RuntimeMode,
9 ServerConfig as T3ServerConfig,
10} from "@t3tools/contracts";
11import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";
12import type { ReactNode } from "react";
13import {
14 memo,
15 useCallback,
16 useEffect,
17 useLayoutEffect,
18 useMemo,
19 useRef,
20 useState,
21 type RefObject,
22} from "react";
23import { ActivityIndicator, Platform, Pressable, View, type ViewStyle } from "react-native";
24import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
25import {
26 composerAttachmentUploadBlockReason,
27 composerAttachmentUploadsAtom,
28} from "../../state/composer-attachment-uploads";
29import Animated, {
30 FadeIn,
31 FadeInDown,
32 FadeOut,
33 FadeOutDown,
34 LinearTransition,
35 ReduceMotion,
36 useAnimatedStyle,
37 useSharedValue,
38 withTiming,
39} from "react-native-reanimated";
40import { useUniwindTheme } from "../../lib/useUniwindTheme";
41import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
42import { scopedThreadKey } from "../../lib/scopedEntities";
43
44import { AppText as Text } from "../../components/AppText";
45import { ComposerAttachmentButton } from "../../components/ComposerAttachmentButton";
46import {
47 ComposerAttachmentStrip,
48 ComposerAttachmentThumbnail,
49} from "../../components/ComposerAttachmentStrip";
50import { VideoPreviewModal, type VideoPreviewSource } from "../../components/VideoPreviewModal";
51import { GlassSurface } from "../../components/GlassSurface";
52import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
53import {
54 ComposerActionButton,
55 ComposerInlineControl,
56 ComposerToolbarRow,
57} from "../../components/ComposerToolbar";
58import { ProviderIcon } from "../../components/ProviderIcon";
59import type {
60 DraftComposerAttachment,
61 DraftComposerFileAttachment,
62} from "../../lib/composerImages";
63import {
64 buildModelOptions,
65 groupByProvider,
66 isModelSelectionUnavailable,
67} from "../../lib/modelOptions";
68import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
69import type { RemoteClientConnectionState } from "../../lib/connection";
70import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
71import { ComposerCommandPopover } from "./ComposerCommandPopover";
72import { useComposerCommandMenu } from "./use-composer-command-menu";
73import {
74 ComposerDictationCancelAction,
75 ComposerDictationDraftContent,
76 ComposerDictationPrimaryAction,
77 ComposerDictationStartAction,
78 ComposerDictationStatus,
79 ComposerDictationToolbar,
80} from "../voice-input/ComposerDictationControl";
81import { useVoiceInputController } from "../voice-input/useVoiceInputController";
82import { resolveVoiceComposerPresentation } from "../voice-input/voiceInputPresentation";
83import {
84 type ExistingThreadSettingsRouteSession,
85 useExistingThreadSettingsRoutePresentation,
86} from "./ThreadSettingsSheet";
87import {
88 useThreadSettingsSheetPresentation,
89 type NavigationWithFinishTransitioning,
90} from "./use-thread-settings-sheet-presentation";
91
92/**
93 * Height of the collapsed composer (pill + vertical padding, excluding safe-area inset).
94 * Exported so the parent can compute feed overlap / content insets.
95 */
96export const COMPOSER_COLLAPSED_CHROME = 60;
97
98/**
99 * Height of the expanded composer (card + toolbar + vertical padding, excluding safe-area inset).
100 * Used by the parent to compute the larger feed bottom inset when the composer is focused.
101 */
102export const COMPOSER_EXPANDED_CHROME = 156;
103
104export interface ThreadComposerProps {
105 readonly draftMessage: string;
106 readonly draftAttachments: ReadonlyArray<DraftComposerAttachment>;
107 readonly placeholder: string;
108 readonly contentMaxWidth?: number;
109 readonly bottomInset?: number;
110 readonly connectionState: RemoteClientConnectionState;
111 readonly connectionError: string | null;
112 readonly environmentLabel: string | null;
113 readonly selectedThread: OrchestrationThreadShell;
114 readonly hasCompactableConversation: boolean;
115 readonly serverConfig: T3ServerConfig | null;
116 readonly queueCount: number;
117 readonly environmentId: EnvironmentId;
118 readonly projectCwd: string | null;
119 readonly editorRef?: RefObject<ComposerEditorHandle | null>;
120 readonly onChangeDraftMessage: (value: string) => void;
121 readonly onPickDraftMedia: () => Promise<void>;
122 readonly onPickDraftFiles: () => Promise<void>;
123 readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
124 readonly onRemoveDraftImage: (imageId: string) => void;
125 readonly onStopThread: () => void;
126 readonly onSendMessage: () => Promise<MessageId | null>;
127 readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
128 readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;
129 readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
130 readonly onReconnectEnvironment: () => void;
131 readonly onExpandedChange?: (expanded: boolean) => void;
132 /** Fires on editor focus/blur; hosts use it to vet stale keyboard state. */
133 readonly onEditorFocusChange?: (focused: boolean) => void;
134}
135
136/**
137 * The pill / card container — renders with Expo's native GlassView on supported
138 * iOS 26+ devices and keeps the existing opaque fallback elsewhere.
139 * Exported so NewTaskDraftScreen can render the same composer chrome.
140 */
141// The bottom-anchored dock position and clipped surface height use the same
142// transition so the card grows upward without exposing its final-size content.
143// Android gets NO layout transition: the composer rides the keyboard via
144// KeyboardStickyView (frame-synced to the IME), and a time-based morph
145// running alongside that translate reads as jitter. Snapping the layout and
146// letting the keyboard-synced slide be the only motion looks native there.
147export const COMPOSER_TRANSITION_DURATION_MS = 220;
148export const COMPOSER_LAYOUT_TRANSITION =
149 Platform.OS === "android"
150 ? undefined
151 : LinearTransition.duration(COMPOSER_TRANSITION_DURATION_MS).reduceMotion(ReduceMotion.System);
152
153const COMPOSER_ATTACHMENT_ENTERING =
154 Platform.OS === "android"
155 ? FadeIn.duration(160)
156 : FadeIn.delay(COMPOSER_TRANSITION_DURATION_MS).duration(160).reduceMotion(ReduceMotion.System);
157
158const AnimatedGlassSurface = Animated.createAnimatedComponent(GlassSurface);
159
160export function ComposerSurface(props: {
161 readonly children: ReactNode;
162 readonly style: ViewStyle;
163 /** Morphs between the compact and expanded composer layouts. */
164 readonly animateLayout?: boolean;
165}) {
166 const targetBorderRadius =
167 typeof props.style.borderRadius === "number" ? props.style.borderRadius : 0;
168 const animatedBorderRadius = useSharedValue(targetBorderRadius);
169 const shouldAnimate = props.animateLayout !== false && Platform.OS !== "android";
170 useLayoutEffect(() => {
171 animatedBorderRadius.value = shouldAnimate
172 ? withTiming(targetBorderRadius, {
173 duration: COMPOSER_TRANSITION_DURATION_MS,
174 reduceMotion: ReduceMotion.System,
175 })
176 : targetBorderRadius;
177 }, [animatedBorderRadius, shouldAnimate, targetBorderRadius]);
178 const animatedShapeStyle = useAnimatedStyle(() => ({
179 borderRadius: animatedBorderRadius.value,
180 }));
181 const layoutTransition = shouldAnimate ? COMPOSER_LAYOUT_TRANSITION : undefined;
182
183 // Each native frame follows the same transition. Animating only the outer
184 // clip leaves the glass and content at their final height on the first frame.
185 return (
186 <Animated.View
187 className="shadow-[0_6px_28px] shadow-adaptive-black-a15-a35"
188 layout={layoutTransition}
189 style={[
190 animatedShapeStyle,
191 {
192 overflow: "hidden",
193 // Android versions before 9 do not support outset box shadows.
194 elevation: Platform.OS === "android" && Platform.Version < 28 ? 10 : undefined,
195 },
196 ]}
197 >
198 <AnimatedGlassSurface
199 chrome="none"
200 fallbackClassName="border border-border bg-card-translucent"
201 glassEffectStyle="regular"
202 // The composer is a passive material containing interactive controls.
203 // Keep native glass out of the interactive content's layout path.
204 pointerEvents="none"
205 tintColor="transparent"
206 layout={layoutTransition}
207 style={[{ position: "absolute", inset: 0 }, animatedShapeStyle]}
208 >
209 {null}
210 </AnimatedGlassSurface>
211 <Animated.View
212 collapsable={false}
213 layout={layoutTransition}
214 style={[props.style, animatedShapeStyle]}
215 >
216 {props.children}
217 </Animated.View>
218 </Animated.View>
219 );
220}
221
222type ComposerStatusPillState = {
223 readonly kind: "unavailable" | "reconnecting";
224 readonly label: string;
225};
226
227function composerConnectionStatus(input: {
228 readonly connectionError: string | null;
229 readonly connectionState: RemoteClientConnectionState;
230 readonly environmentLabel: string | null;
231}): ComposerStatusPillState | null {
232 const environmentLabel = input.environmentLabel ?? "Environment";
233
234 switch (input.connectionState) {
235 case "connecting":
236 case "reconnecting":
237 return {
238 kind: "reconnecting",
239 label:
240 input.connectionError === null
241 ? `Reconnecting to ${environmentLabel}...`
242 : `Failed to connect. Retrying ${environmentLabel}...`,
243 };
244 case "offline":
245 return { kind: "unavailable", label: "You are offline" };
246 case "error":
247 return {
248 kind: "unavailable",
249 label: input.connectionError
250 ? `Failed to connect to ${environmentLabel}: ${input.connectionError}`
251 : `Failed to connect to ${environmentLabel}`,
252 };
253 case "available":
254 return { kind: "unavailable", label: `${environmentLabel} is not connected` };
255 case "connected":
256 return null;
257 }
258}
259
260const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill(props: {
261 readonly onPress: () => void;
262 readonly status: ComposerStatusPillState;
263}) {
264 const isReconnecting = props.status.kind === "reconnecting";
265 return (
266 <Animated.View
267 className="absolute inset-x-0 bottom-full items-center pb-2"
268 entering={FadeInDown.duration(180)}
269 exiting={FadeOutDown.duration(140)}
270 pointerEvents="box-none"
271 >
272 <Pressable
273 accessibilityRole="button"
274 onPress={props.onPress}
275 className="max-w-full flex-row items-center gap-2 rounded-full bg-card px-3 py-2 shadow-sm active:opacity-70"
276 >
277 {isReconnecting ? (
278 <ActivityIndicator size="small" colorClassName={"accent-icon-muted"} />
279 ) : (
280 <View className="h-2 w-2 rounded-full bg-red-500" />
281 )}
282 <Text
283 className="max-w-[260px] text-sm font-t3-bold leading-snug text-foreground"
284 numberOfLines={1}
285 >
286 {props.status.label}
287 </Text>
288 </Pressable>
289 </Animated.View>
290 );
291});
292
293export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) {
294 const navigation = useNavigation();
295 const foregroundColor = useUniwindTheme()["--color-foreground"];
296 const bodyText = useScaledTextRole("body");
297 const fallbackInputRef = useRef<ComposerEditorHandle>(null);
298 const inputRef = props.editorRef ?? fallbackInputRef;
299 const [isFocused, setIsFocused] = useState(false);
300 const settingsSheetPresentation = useThreadSettingsSheetPresentation({
301 editorRef: inputRef,
302 isEditorFocused: isFocused,
303 });
304 const settingsRoutePresentation = useExistingThreadSettingsRoutePresentation();
305 const settingsRoutePresentedRef = useRef(false);
306 const wasExpandedBeforePreviewRef = useRef(false);
307 const inFlightThreadIdsRef = useRef(new Set<string>());
308 const { onExpandedChange } = props;
309
310 const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
311 const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);
312 const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
313 const showStopAction =
314 !hasContent &&
315 (props.selectedThread.session?.status === "running" ||
316 props.selectedThread.session?.status === "starting");
317
318 const sendLabel =
319 props.connectionState !== "connected" || props.queueCount > 0 ? "Queue" : "Send";
320 const currentModelSelection = props.selectedThread.modelSelection;
321 const currentRuntimeMode = props.selectedThread.runtimeMode;
322 const modelUnavailable =
323 props.connectionState === "connected" &&
324 isModelSelectionUnavailable(props.serverConfig, currentModelSelection);
325 const connectionStatus = composerConnectionStatus({
326 connectionError: props.connectionError,
327 connectionState: props.connectionState,
328 environmentLabel: props.environmentLabel,
329 });
330 const selectedProviderStatus = useMemo(() => {
331 if (!props.serverConfig) return null;
332 return (
333 props.serverConfig.providers.find(
334 (p) => p.instanceId === props.selectedThread.modelSelection.instanceId,
335 ) ?? null
336 );
337 }, [props.serverConfig, props.selectedThread.modelSelection.instanceId]);
338 const composerOwnerKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
339
340 const composerMenu = useComposerCommandMenu({
341 draftMessage: props.draftMessage,
342 ownerKey: composerOwnerKey,
343 environmentId: props.environmentId,
344 projectCwd: props.projectCwd,
345 selectedProviderStatus,
346 hasThread: true,
347 hasCompactableConversation: props.hasCompactableConversation,
348 onChangeDraftMessage: props.onChangeDraftMessage,
349 onUpdateInteractionMode:
350 selectedProviderStatus?.showInteractionModeToggle === false
351 ? undefined
352 : props.onUpdateInteractionMode,
353 });
354 const voiceInput = useVoiceInputController({
355 ownerKey: composerOwnerKey,
356 draftMessage: props.draftMessage,
357 selection: composerMenu.selection,
358 onChangeDraftMessage: props.onChangeDraftMessage,
359 onChangeSelection: composerMenu.onSelectionChange,
360 });
361 const voicePresentation = resolveVoiceComposerPresentation(
362 voiceInput.state,
363 voiceInput.elapsedSeconds,
364 );
365 const isVoiceInputPresented = voicePresentation.statusLabel !== null;
366 // An open draft stays visible; only a collapsed composer becomes a voice strip.
367 const isExpanded = isFocused || settingsSheetPresentation.isActive;
368 const showsCompactDictation = isVoiceInputPresented && !isExpanded;
369 const isToolbarVisible = isExpanded || isVoiceInputPresented;
370 const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
371 const attachmentBlockReason = composerAttachmentUploadBlockReason({
372 environmentId: props.environmentId,
373 attachments: props.draftAttachments,
374 connected: props.connectionState === "connected",
375 serverConfig: props.serverConfig,
376 states: uploadStates,
377 });
378 const canSend =
379 hasContent &&
380 !voiceInput.blocksSubmission &&
381 attachmentBlockReason === null &&
382 !modelUnavailable;
383
384 // Keep the feed inset aligned with the card or compact dictation strip.
385 useEffect(() => {
386 onExpandedChange?.(isExpanded);
387 }, [isExpanded, onExpandedChange]);
388
389 const onPressPreview = useCallback(
390 (source: FilePreviewSource) => {
391 wasExpandedBeforePreviewRef.current = isFocused;
392 setPreviewVideo(null);
393 setPreviewFile((current) => current ?? source);
394 },
395 [isFocused],
396 );
397
398 const closePreview = useCallback(() => {
399 setPreviewFile(null);
400 setPreviewVideo(null);
401 if (wasExpandedBeforePreviewRef.current) {
402 setTimeout(() => {
403 if (navigation.isFocused()) inputRef.current?.focus();
404 }, 100);
405 }
406 }, [inputRef, navigation]);
407
408 const onPressVideo = useCallback(
409 (attachment: DraftComposerFileAttachment, sourceIdentifier: string) => {
410 wasExpandedBeforePreviewRef.current = isFocused;
411 setPreviewFile(null);
412 setPreviewVideo((current) => current ?? { type: "local", attachment, sourceIdentifier });
413 },
414 [isFocused],
415 );
416
417 const onEditorFocusChange = props.onEditorFocusChange;
418 const handleFocus = useCallback(() => {
419 setIsFocused(true);
420 onExpandedChange?.(true);
421 onEditorFocusChange?.(true);
422 }, [onEditorFocusChange, onExpandedChange]);
423
424 const handleBlur = useCallback(() => {
425 setIsFocused(false);
426 if (!settingsSheetPresentation.isActive) {
427 onExpandedChange?.(false);
428 }
429 onEditorFocusChange?.(false);
430 }, [onEditorFocusChange, onExpandedChange, settingsSheetPresentation.isActive]);
431 const { onSendMessage } = props;
432
433 const handleSend = useCallback(async () => {
434 if (voiceInput.blocksSubmission) return;
435 const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
436 if (inFlightThreadIdsRef.current.has(threadKey)) return;
437 inFlightThreadIdsRef.current.add(threadKey);
438 try {
439 const messageId = await onSendMessage();
440 if (messageId === null) {
441 return;
442 }
443 // Sending a prompt starts agent work: arm the lock-screen card while the
444 // app is foregrounded and the activity token can be registered. Armed
445 // after the send so its preference read and native Activity start don't
446 // contend with the queued-message feedback on the tap frame.
447 armAgentAwarenessLiveActivityForLocalWork({
448 environmentId: props.environmentId,
449 threadTitle: props.selectedThread.title,
450 projectTitle: props.environmentLabel ?? "T3 Code",
451 });
452 } finally {
453 inFlightThreadIdsRef.current.delete(threadKey);
454 }
455 }, [
456 onSendMessage,
457 props.environmentId,
458 props.environmentLabel,
459 props.selectedThread.id,
460 props.selectedThread.title,
461 voiceInput.blocksSubmission,
462 ]);
463
464 // ── Model menu ───────────────────────────────────────────
465 const modelOptions = useMemo(
466 () => buildModelOptions(props.serverConfig, currentModelSelection),
467 [props.serverConfig, currentModelSelection],
468 );
469 const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
470 // An existing thread is bound to its harness: sessions can't move between
471 // provider instances, so the picker only offers the thread's own group.
472 const threadProviderGroups = useMemo(
473 () => providerGroups.filter((group) => group.providerKey === currentModelSelection.instanceId),
474 [providerGroups, currentModelSelection.instanceId],
475 );
476 const currentModelOption =
477 modelOptions.find(
478 (option) =>
479 option.selection.instanceId === currentModelSelection.instanceId &&
480 option.selection.model === currentModelSelection.model,
481 ) ?? null;
482 const providerOptionDescriptors = useMemo(
483 () =>
484 resolveProviderOptionDescriptors({
485 capabilities: currentModelOption?.capabilities,
486 selections: currentModelSelection.options,
487 }),
488 [currentModelOption?.capabilities, currentModelSelection.options],
489 );
490 const settingsOwnerId = composerOwnerKey;
491 const settingsRouteSession = useMemo<ExistingThreadSettingsRouteSession>(
492 () => ({
493 ownerId: settingsOwnerId,
494 environmentId: props.environmentId,
495 providerInstanceId: currentModelSelection.instanceId,
496 providerGroups: threadProviderGroups,
497 selectedModel: currentModelSelection,
498 onSelectModel: (option) => props.onUpdateModelSelection(option.selection),
499 optionDescriptors: providerOptionDescriptors,
500 onUpdateOptionSelections: (options) =>
501 props.onUpdateModelSelection({ ...currentModelSelection, options }),
502 runtimeMode: currentRuntimeMode,
503 onUpdateRuntimeMode: props.onUpdateRuntimeMode,
504 }),
505 [
506 currentModelSelection,
507 currentRuntimeMode,
508 props.onUpdateModelSelection,
509 props.onUpdateRuntimeMode,
510 providerOptionDescriptors,
511 settingsOwnerId,
512 threadProviderGroups,
513 ],
514 );
515 const openSettings = useCallback(() => {
516 settingsRoutePresentation.present(settingsRouteSession);
517 settingsSheetPresentation.open();
518 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.open]);
519
520 useEffect(() => {
521 if (settingsSheetPresentation.isActive) {
522 settingsRoutePresentation.present(settingsRouteSession);
523 }
524 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.isActive]);
525
526 useEffect(() => {
527 if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
528 return;
529 }
530
531 settingsRoutePresentedRef.current = true;
532 navigation.dispatch(StackActions.push("ThreadSettingsSheet"));
533 }, [navigation, settingsSheetPresentation.isVisible]);
534
535 useFocusEffect(
536 useCallback(() => {
537 if (!settingsRoutePresentedRef.current) {
538 return;
539 }
540
541 settingsRoutePresentedRef.current = false;
542 settingsSheetPresentation.onDismissed();
543 settingsRoutePresentation.clear(settingsOwnerId);
544 }, [settingsOwnerId, settingsRoutePresentation.clear, settingsSheetPresentation.onDismissed]),
545 );
546
547 useEffect(
548 () =>
549 // UIKit's completion callback for the sheet dismissal, surfaced by the
550 // native-stack patch. This is when the queued keyboard restore runs.
551 (navigation as unknown as NavigationWithFinishTransitioning).addListener(
552 "finishTransitioning",
553 settingsSheetPresentation.onStackTransitionsFinished,
554 ),
555 [navigation, settingsSheetPresentation.onStackTransitionsFinished],
556 );
557
558 return (
559 <Animated.View
560 className="px-[12px]"
561 style={{
562 paddingTop: isExpanded ? 8 : 6,
563 paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 8 : 6),
564 }}
565 >
566 {/* The backdrop gradient lives on a plain View: Reanimated's Animated.View
567 silently drops experimental_backgroundImage on Android, which left this
568 strip fully transparent and the feed text legible through the composer. */}
569 <View
570 className="absolute inset-0 bg-linear-to-b from-screen/0 via-screen/60 to-screen/90"
571 pointerEvents="none"
572 />
573 <Animated.View
574 className="relative w-full self-center"
575 style={{ maxWidth: props.contentMaxWidth }}
576 >
577 {!voiceInput.isBusy && composerMenu.trigger && composerMenu.items.length > 0 ? (
578 <View className="absolute inset-x-0 bottom-full z-10 mb-2">
579 <ComposerCommandPopover
580 items={composerMenu.items}
581 triggerKind={composerMenu.trigger.kind}
582 isLoading={composerMenu.isLoading}
583 onSelect={composerMenu.onSelect}
584 />
585 </View>
586 ) : null}
587
588 {connectionStatus ? (
589 <ComposerConnectionStatusPill
590 status={connectionStatus}
591 onPress={props.onReconnectEnvironment}
592 />
593 ) : null}
594
595 {modelUnavailable ? (
596 <Pressable accessibilityRole="button" className="px-3 py-2" onPress={openSettings}>
597 <Text className="text-xs text-foreground">Model unavailable. Open model settings.</Text>
598 </Pressable>
599 ) : null}
600
601 <ComposerSurface
602 style={
603 isExpanded
604 ? {
605 borderRadius: 26,
606 minHeight: 140,
607 overflow: "hidden" as const,
608 paddingBottom: 6,
609 paddingTop: 14,
610 }
611 : {
612 // Keep the numeric radius close to the expanded card so the
613 // shape morph stays bounded while rendering as a capsule.
614 borderRadius: 27,
615 overflow: "hidden" as const,
616 paddingVertical: 2,
617 }
618 }
619 >
620 <ComposerDictationDraftContent
621 className={isExpanded ? undefined : "flex-row items-center"}
622 compact={!isExpanded}
623 hidden={showsCompactDictation}
624 >
625 {!isExpanded ? (
626 <ComposerAttachmentButton
627 supportsFiles={Boolean(
628 props.serverConfig?.environment.capabilities.fileAttachments,
629 )}
630 onPickMedia={props.onPickDraftMedia}
631 onPickFiles={props.onPickDraftFiles}
632 />
633 ) : null}
634 {isExpanded && props.draftAttachments.length > 0 ? (
635 <Animated.View
636 className="px-[14px] pb-2.5"
637 entering={COMPOSER_ATTACHMENT_ENTERING}
638 exiting={FadeOut.duration(120)}
639 >
640 <ComposerAttachmentStrip
641 environmentId={props.environmentId}
642 attachments={props.draftAttachments}
643 onRemove={voiceInput.isBusy ? () => undefined : props.onRemoveDraftImage}
644 onPressPreview={voiceInput.isBusy ? undefined : onPressPreview}
645 onPressVideo={voiceInput.isBusy ? undefined : onPressVideo}
646 />
647 </Animated.View>
648 ) : null}
649 <Animated.View
650 className={isExpanded ? "px-[14px]" : "min-w-0 flex-1 px-[4px]"}
651 layout={COMPOSER_LAYOUT_TRANSITION}
652 >
653 <ComposerEditor
654 ref={inputRef}
655 multiline
656 value={props.draftMessage}
657 readOnly={voiceInput.freezesEditor}
658 skills={composerMenu.skills}
659 selection={composerMenu.selection}
660 onChangeText={props.onChangeDraftMessage}
661 onSelectionChange={composerMenu.onSelectionChange}
662 onPasteImages={(uris) => void props.onNativePasteImages(uris)}
663 placeholder={props.placeholder}
664 onFocus={handleFocus}
665 onBlur={handleBlur}
666 onSubmit={handleSend}
667 scrollEnabled={isExpanded}
668 // Android: collapsed single line centers natively (gravity) in
669 // a pill-height box matching the send button; iOS keeps insets.
670 singleLineCentered={!isExpanded}
671 contentInsetVertical={isExpanded || Platform.OS === "android" ? 0 : 6}
672 style={
673 isExpanded
674 ? {
675 minHeight: 72,
676 maxHeight: 160,
677 paddingVertical: 4,
678 }
679 : {
680 height: 36,
681 }
682 }
683 textStyle={{
684 ...bodyText,
685 color: foregroundColor,
686 }}
687 />
688 </Animated.View>
689 {!isExpanded && props.draftAttachments.length > 0 ? (
690 <View className="flex-row gap-1 pl-1">
691 {props.draftAttachments.slice(0, 3).map((attachment) => (
692 <ComposerAttachmentThumbnail
693 environmentId={props.environmentId}
694 key={attachment.id}
695 attachment={attachment}
696 size={30}
697 borderRadius={8}
698 compact
699 onPressPreview={onPressPreview}
700 onPressVideo={onPressVideo}
701 />
702 ))}
703 {props.draftAttachments.length > 3 ? (
704 <View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
705 <Text className="text-foreground-muted text-2xs font-t3-bold">
706 +{props.draftAttachments.length - 3}
707 </Text>
708 </View>
709 ) : null}
710 </View>
711 ) : null}
712 {!isExpanded ? (
713 <View className="flex-row items-center">
714 <ComposerDictationStartAction
715 state={voiceInput.state}
716 isAvailable={voiceInput.isAvailable}
717 onStart={voiceInput.start}
718 onCancel={voiceInput.cancel}
719 />
720 {showStopAction ? (
721 <ComposerActionButton
722 accessibilityLabel="Stop agent"
723 icon="stop.fill"
724 variant="danger"
725 onPress={props.onStopThread}
726 />
727 ) : (
728 <ComposerActionButton
729 accessibilityLabel={attachmentBlockReason ?? sendLabel}
730 icon="arrow.up"
731 variant="primary"
732 disabled={!canSend}
733 onPress={handleSend}
734 />
735 )}
736 </View>
737 ) : null}
738 {isExpanded ? <View className="h-1" /> : null}
739 </ComposerDictationDraftContent>
740 <Animated.View
741 accessibilityElementsHidden={!isToolbarVisible}
742 collapsable={false}
743 importantForAccessibility={isToolbarVisible ? "auto" : "no-hide-descendants"}
744 layout={COMPOSER_LAYOUT_TRANSITION}
745 pointerEvents={isToolbarVisible ? "auto" : "none"}
746 style={
747 isExpanded
748 ? undefined
749 : {
750 position: "absolute",
751 bottom: 2,
752 left: 0,
753 right: 0,
754 }
755 }
756 >
757 <ComposerDictationToolbar
758 showsDictation={isVoiceInputPresented}
759 visible={isToolbarVisible}
760 >
761 <ComposerToolbarRow
762 paddingBottom={0}
763 paddingHorizontal={0}
764 paddingTop={0}
765 style={{ gap: 0 }}
766 >
767 <ComposerDictationCancelAction
768 presentation={voicePresentation}
769 onCancel={voiceInput.cancel}
770 />
771 {isVoiceInputPresented ? (
772 <ComposerDictationStatus
773 audioLevels={voiceInput.audioLevels}
774 elapsedSeconds={voiceInput.elapsedSeconds}
775 phase={voiceInput.state.phase}
776 presentation={voicePresentation}
777 onDismissError={voiceInput.cancel}
778 />
779 ) : (
780 <View className="min-w-0 flex-1 flex-row items-center justify-between">
781 <ComposerAttachmentButton
782 supportsFiles={Boolean(
783 props.serverConfig?.environment.capabilities.fileAttachments,
784 )}
785 onPickMedia={props.onPickDraftMedia}
786 onPickFiles={props.onPickDraftFiles}
787 />
788 <View className="min-w-0 shrink" style={{ maxWidth: 152 }}>
789 <ComposerInlineControl
790 accessibilityLabel="Model and reasoning settings"
791 emphasized
792 iconNode={
793 <ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
794 }
795 label={currentModelOption?.label ?? currentModelSelection.model}
796 maxWidth={152}
797 onPress={openSettings}
798 />
799 </View>
800 </View>
801 )}
802 <View className="shrink-0 flex-row items-center">
803 <ComposerDictationPrimaryAction
804 state={voiceInput.state}
805 presentation={voicePresentation}
806 isAvailable={voiceInput.isAvailable}
807 onStart={voiceInput.start}
808 onConfirm={voiceInput.stop}
809 onCancel={voiceInput.cancel}
810 />
811 {showStopAction ? (
812 <ComposerActionButton
813 accessibilityLabel="Stop agent"
814 icon="stop.fill"
815 variant="danger"
816 onPress={props.onStopThread}
817 />
818 ) : voicePresentation.showsSend ? (
819 <ComposerActionButton
820 accessibilityLabel={attachmentBlockReason ?? sendLabel}
821 icon="arrow.up"
822 variant="primary"
823 disabled={!canSend}
824 onPress={handleSend}
825 />
826 ) : null}
827 </View>
828 </ComposerToolbarRow>
829 </ComposerDictationToolbar>
830 </Animated.View>
831 </ComposerSurface>
832
833 {/* Queue count */}
834 {props.queueCount > 0 ? (
835 <Animated.View entering={FadeIn.duration(180)} exiting={FadeOut.duration(120)}>
836 <Text className="pt-2 text-xs text-foreground-muted">
837 {props.queueCount} queued message{props.queueCount === 1 ? "" : "s"} will send
838 automatically.
839 </Text>
840 </Animated.View>
841 ) : null}
842 </Animated.View>
843
844 <VideoPreviewModal source={previewVideo} onRequestClose={closePreview} />
845 <FilePreviewModal source={previewFile} onRequestClose={closePreview} />
846 </Animated.View>
847 );
848});