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