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