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