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