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