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 UsageLimitsReport,
11} from "@t3tools/contracts";
12import {
13 collectProviderUsageLimits,
14 hasProviderUsageLimits,
15 isUsageLimitsCommand,
16} from "@t3tools/shared/usageLimits";
17import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";
18import type { ReactNode } from "react";
19import {
20 memo,
21 useCallback,
22 useEffect,
23 useLayoutEffect,
24 useMemo,
25 useRef,
26 useState,
27 type RefObject,
28} from "react";
29import { ActivityIndicator, Alert, Platform, Pressable, View, type ViewStyle } from "react-native";
30import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
31import {
32 composerAttachmentUploadBlockReason,
33 composerAttachmentUploadsAtom,
34} from "../../state/composer-attachment-uploads";
35import Animated, {
36 FadeIn,
37 FadeInDown,
38 FadeOut,
39 FadeOutDown,
40 LinearTransition,
41 ReduceMotion,
42 useAnimatedStyle,
43 useSharedValue,
44 withTiming,
45} from "react-native-reanimated";
46import { useUniwindTheme } from "../../lib/useUniwindTheme";
47import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
48import { scopedThreadKey } from "../../lib/scopedEntities";
49
50import { AppText as Text } from "../../components/AppText";
51import { ComposerAttachmentButton } from "../../components/ComposerAttachmentButton";
52import {
53 ComposerAttachmentStrip,
54 ComposerAttachmentThumbnail,
55} from "../../components/ComposerAttachmentStrip";
56import { VideoPreviewModal, type VideoPreviewSource } from "../../components/VideoPreviewModal";
57import { GlassSurface } from "../../components/GlassSurface";
58import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
59import {
60 ComposerActionButton,
61 ComposerInlineControl,
62 ComposerToolbarRow,
63} from "../../components/ComposerToolbar";
64import { ProviderIcon } from "../../components/ProviderIcon";
65import type {
66 DraftComposerAttachment,
67 DraftComposerFileAttachment,
68} from "../../lib/composerImages";
69import {
70 buildModelOptions,
71 groupByProvider,
72 isModelSelectionUnavailable,
73} from "../../lib/modelOptions";
74import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
75import type { RemoteClientConnectionState } from "../../lib/connection";
76import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
77import { ComposerCommandPopover } from "./ComposerCommandPopover";
78import { useComposerCommandMenu } from "./use-composer-command-menu";
79import {
80 ComposerDictationCancelAction,
81 ComposerDictationDraftContent,
82 ComposerDictationPrimaryAction,
83 ComposerDictationStartAction,
84 ComposerDictationStatus,
85 ComposerDictationToolbar,
86} from "../voice-input/ComposerDictationControl";
87import { useVoiceInputController } from "../voice-input/useVoiceInputController";
88import { resolveVoiceComposerPresentation } from "../voice-input/voiceInputPresentation";
89import {
90 type ExistingThreadSettingsRouteSession,
91 useExistingThreadSettingsRoutePresentation,
92} from "./ThreadSettingsSheet";
93import {
94 useThreadSettingsSheetPresentation,
95 type NavigationWithFinishTransitioning,
96} from "./use-thread-settings-sheet-presentation";
97
98/**
99 * Height of the collapsed composer (pill + vertical padding, excluding safe-area inset).
100 * Exported so the parent can compute feed overlap / content insets.
101 */
102export const COMPOSER_COLLAPSED_CHROME = 60;
103
104/**
105 * Height of the expanded composer (card + toolbar + vertical padding, excluding safe-area inset).
106 * Used by the parent to compute the larger feed bottom inset when the composer is focused.
107 */
108export const COMPOSER_EXPANDED_CHROME = 156;
109
110export interface ThreadComposerProps {
111 readonly draftMessage: string;
112 readonly draftAttachments: ReadonlyArray<DraftComposerAttachment>;
113 readonly placeholder: string;
114 readonly contentMaxWidth?: number;
115 readonly bottomInset?: number;
116 readonly connectionState: RemoteClientConnectionState;
117 readonly connectionError: string | null;
118 readonly environmentLabel: string | null;
119 readonly selectedThread: OrchestrationThreadShell;
120 readonly hasCompactableConversation: boolean;
121 readonly serverConfig: T3ServerConfig | null;
122 readonly queueCount: number;
123 readonly environmentId: EnvironmentId;
124 readonly projectCwd: string | null;
125 readonly editorRef?: RefObject<ComposerEditorHandle | null>;
126 readonly onChangeDraftMessage: (value: string) => void;
127 readonly onPickDraftMedia: () => Promise<void>;
128 readonly onPickDraftFiles: () => Promise<void>;
129 readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
130 readonly onRemoveDraftImage: (imageId: string) => void;
131 readonly onStopThread: () => void;
132 readonly onSendMessage: () => Promise<MessageId | null>;
133 /** `/usage-limits` resolves locally; the host decides where the report shows. Null clears it. */
134 readonly onShowUsageLimits: (report: UsageLimitsReport | null) => void;
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 =
322 !hasContent &&
323 (props.selectedThread.session?.status === "running" ||
324 props.selectedThread.session?.status === "starting");
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 modelUnavailable =
331 props.connectionState === "connected" &&
332 isModelSelectionUnavailable(props.serverConfig, currentModelSelection);
333 const connectionStatus = composerConnectionStatus({
334 connectionError: props.connectionError,
335 connectionState: props.connectionState,
336 environmentLabel: props.environmentLabel,
337 });
338 const selectedProviderStatus = useMemo(() => {
339 if (!props.serverConfig) return null;
340 return (
341 props.serverConfig.providers.find(
342 (p) => p.instanceId === props.selectedThread.modelSelection.instanceId,
343 ) ?? null
344 );
345 }, [props.serverConfig, props.selectedThread.modelSelection.instanceId]);
346 const composerOwnerKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
347 const { onSendMessage, onChangeDraftMessage, onShowUsageLimits } = props;
348 // T3 owns /usage-limits only where Limits has data for the selected provider;
349 // elsewhere the name stays the provider's own and is sent through untouched.
350 const usageLimitsOffered =
351 selectedProviderStatus !== null &&
352 hasProviderUsageLimits(
353 selectedProviderStatus.driver,
354 props.serverConfig?.providers ?? [],
355 props.serverConfig?.usageLimitSources ?? [],
356 );
357 // Answered locally from the last Limits snapshot; the agent never sees it.
358 const openUsageLimits = useCallback(() => {
359 const report = collectProviderUsageLimits(
360 currentModelSelection.instanceId,
361 props.serverConfig?.providers ?? [],
362 props.serverConfig?.usageLimitSources ?? [],
363 Date.now(),
364 );
365 onShowUsageLimits(report);
366 if (!report) {
367 Alert.alert("Usage limits unavailable", "This provider does not currently report limits.");
368 }
369 return report !== null;
370 }, [currentModelSelection.instanceId, onShowUsageLimits, props.serverConfig]);
371
372 const composerMenu = useComposerCommandMenu({
373 draftMessage: props.draftMessage,
374 ownerKey: composerOwnerKey,
375 environmentId: props.environmentId,
376 projectCwd: props.projectCwd,
377 selectedProviderStatus,
378 hasThread: true,
379 hasCompactableConversation: props.hasCompactableConversation,
380 onChangeDraftMessage: props.onChangeDraftMessage,
381 onUpdateInteractionMode:
382 selectedProviderStatus?.showInteractionModeToggle === false
383 ? undefined
384 : props.onUpdateInteractionMode,
385 offersUsageLimits: usageLimitsOffered,
386 // With attachments aboard the pick just inserts the text, so it sends as a prompt.
387 onUsageLimits:
388 usageLimitsOffered && props.draftAttachments.length === 0 ? openUsageLimits : undefined,
389 });
390 const voiceInput = useVoiceInputController({
391 ownerKey: composerOwnerKey,
392 draftMessage: props.draftMessage,
393 selection: composerMenu.selection,
394 onChangeDraftMessage: props.onChangeDraftMessage,
395 onChangeSelection: composerMenu.onSelectionChange,
396 });
397 const voicePresentation = resolveVoiceComposerPresentation(
398 voiceInput.state,
399 voiceInput.elapsedSeconds,
400 );
401 const isVoiceInputPresented = voicePresentation.statusLabel !== null;
402 // An open draft stays visible; only a collapsed composer becomes a voice strip.
403 const isExpanded = isFocused || settingsSheetPresentation.isActive;
404 const showsCompactDictation = isVoiceInputPresented && !isExpanded;
405 const isToolbarVisible = isExpanded || isVoiceInputPresented;
406 const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
407 const attachmentBlockReason = composerAttachmentUploadBlockReason({
408 environmentId: props.environmentId,
409 attachments: props.draftAttachments,
410 connected: props.connectionState === "connected",
411 serverConfig: props.serverConfig,
412 states: uploadStates,
413 });
414 const canSend =
415 hasContent &&
416 !voiceInput.blocksSubmission &&
417 attachmentBlockReason === null &&
418 !modelUnavailable;
419
420 // Keep the feed inset aligned with the card or compact dictation strip.
421 useEffect(() => {
422 onExpandedChange?.(isExpanded);
423 }, [isExpanded, onExpandedChange]);
424
425 const onPressPreview = useCallback(
426 (source: FilePreviewSource) => {
427 wasExpandedBeforePreviewRef.current = isFocused;
428 setPreviewVideo(null);
429 setPreviewFile((current) => current ?? source);
430 },
431 [isFocused],
432 );
433
434 const closePreview = useCallback(() => {
435 setPreviewFile(null);
436 setPreviewVideo(null);
437 if (wasExpandedBeforePreviewRef.current) {
438 setTimeout(() => {
439 if (navigation.isFocused()) inputRef.current?.focus();
440 }, 100);
441 }
442 }, [inputRef, navigation]);
443
444 const onPressVideo = useCallback(
445 (attachment: DraftComposerFileAttachment, sourceIdentifier: string) => {
446 wasExpandedBeforePreviewRef.current = isFocused;
447 setPreviewFile(null);
448 setPreviewVideo((current) => current ?? { type: "local", attachment, sourceIdentifier });
449 },
450 [isFocused],
451 );
452
453 const onEditorFocusChange = props.onEditorFocusChange;
454 const handleFocus = useCallback(() => {
455 setIsFocused(true);
456 onExpandedChange?.(true);
457 onEditorFocusChange?.(true);
458 }, [onEditorFocusChange, onExpandedChange]);
459
460 const handleBlur = useCallback(() => {
461 setIsFocused(false);
462 if (!settingsSheetPresentation.isActive) {
463 onExpandedChange?.(false);
464 }
465 onEditorFocusChange?.(false);
466 }, [onEditorFocusChange, onExpandedChange, settingsSheetPresentation.isActive]);
467 const handleSend = useCallback(async () => {
468 // Typed out in full rather than picked from the menu. Attachments mean the
469 // user is sending a prompt, so those go through as usual.
470 if (
471 usageLimitsOffered &&
472 isUsageLimitsCommand(props.draftMessage) &&
473 props.draftAttachments.length === 0
474 ) {
475 if (openUsageLimits()) onChangeDraftMessage("");
476 return;
477 }
478 if (voiceInput.blocksSubmission) return;
479 const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
480 if (inFlightThreadIdsRef.current.has(threadKey)) return;
481 inFlightThreadIdsRef.current.add(threadKey);
482 try {
483 const messageId = await onSendMessage();
484 if (messageId === null) {
485 return;
486 }
487 // Sending a prompt starts agent work: arm the lock-screen card while the
488 // app is foregrounded and the activity token can be registered. Armed
489 // after the send so its preference read and native Activity start don't
490 // contend with the queued-message feedback on the tap frame.
491 armAgentAwarenessLiveActivityForLocalWork({
492 environmentId: props.environmentId,
493 threadTitle: props.selectedThread.title,
494 projectTitle: props.environmentLabel ?? "T3 Code",
495 });
496 } finally {
497 inFlightThreadIdsRef.current.delete(threadKey);
498 }
499 }, [
500 props.draftMessage,
501 props.draftAttachments.length,
502 onChangeDraftMessage,
503 openUsageLimits,
504 usageLimitsOffered,
505 onSendMessage,
506 props.environmentId,
507 props.environmentLabel,
508 props.selectedThread.id,
509 props.selectedThread.title,
510 voiceInput.blocksSubmission,
511 ]);
512
513 // ── Model menu ───────────────────────────────────────────
514 const modelOptions = useMemo(
515 () => buildModelOptions(props.serverConfig, currentModelSelection),
516 [props.serverConfig, currentModelSelection],
517 );
518 const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
519 // An existing thread is bound to its harness: sessions can't move between
520 // provider instances, so the picker only offers the thread's own group.
521 const threadProviderGroups = useMemo(
522 () => providerGroups.filter((group) => group.providerKey === currentModelSelection.instanceId),
523 [providerGroups, currentModelSelection.instanceId],
524 );
525 const currentModelOption =
526 modelOptions.find(
527 (option) =>
528 option.selection.instanceId === currentModelSelection.instanceId &&
529 option.selection.model === currentModelSelection.model,
530 ) ?? null;
531 const providerOptionDescriptors = useMemo(
532 () =>
533 resolveProviderOptionDescriptors({
534 capabilities: currentModelOption?.capabilities,
535 selections: currentModelSelection.options,
536 }),
537 [currentModelOption?.capabilities, currentModelSelection.options],
538 );
539 const settingsOwnerId = composerOwnerKey;
540 const settingsRouteSession = useMemo<ExistingThreadSettingsRouteSession>(
541 () => ({
542 ownerId: settingsOwnerId,
543 environmentId: props.environmentId,
544 providerInstanceId: currentModelSelection.instanceId,
545 providerGroups: threadProviderGroups,
546 selectedModel: currentModelSelection,
547 onSelectModel: (option) => props.onUpdateModelSelection(option.selection),
548 optionDescriptors: providerOptionDescriptors,
549 onUpdateOptionSelections: (options) =>
550 props.onUpdateModelSelection({ ...currentModelSelection, options }),
551 runtimeMode: currentRuntimeMode,
552 onUpdateRuntimeMode: props.onUpdateRuntimeMode,
553 }),
554 [
555 currentModelSelection,
556 currentRuntimeMode,
557 props.onUpdateModelSelection,
558 props.onUpdateRuntimeMode,
559 providerOptionDescriptors,
560 settingsOwnerId,
561 threadProviderGroups,
562 ],
563 );
564 const openSettings = useCallback(() => {
565 settingsRoutePresentation.present(settingsRouteSession);
566 settingsSheetPresentation.open();
567 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.open]);
568
569 useEffect(() => {
570 if (settingsSheetPresentation.isActive) {
571 settingsRoutePresentation.present(settingsRouteSession);
572 }
573 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.isActive]);
574
575 useEffect(() => {
576 if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
577 return;
578 }
579
580 settingsRoutePresentedRef.current = true;
581 navigation.dispatch(StackActions.push("ThreadSettingsSheet"));
582 }, [navigation, settingsSheetPresentation.isVisible]);
583
584 useFocusEffect(
585 useCallback(() => {
586 if (!settingsRoutePresentedRef.current) {
587 return;
588 }
589
590 settingsRoutePresentedRef.current = false;
591 settingsSheetPresentation.onDismissed();
592 settingsRoutePresentation.clear(settingsOwnerId);
593 }, [settingsOwnerId, settingsRoutePresentation.clear, settingsSheetPresentation.onDismissed]),
594 );
595
596 useEffect(
597 () =>
598 // UIKit's completion callback for the sheet dismissal, surfaced by the
599 // native-stack patch. This is when the queued keyboard restore runs.
600 (navigation as unknown as NavigationWithFinishTransitioning).addListener(
601 "finishTransitioning",
602 settingsSheetPresentation.onStackTransitionsFinished,
603 ),
604 [navigation, settingsSheetPresentation.onStackTransitionsFinished],
605 );
606
607 return (
608 <Animated.View
609 className="px-[12px]"
610 style={{
611 paddingTop: isExpanded ? 8 : 6,
612 paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 8 : 6),
613 }}
614 >
615 {/* The backdrop gradient lives on a plain View: Reanimated's Animated.View
616 silently drops experimental_backgroundImage on Android, which left this
617 strip fully transparent and the feed text legible through the composer. */}
618 <View
619 className="absolute inset-0 bg-linear-to-b from-screen/0 via-screen/60 to-screen/90"
620 pointerEvents="none"
621 />
622 <Animated.View
623 className="relative w-full self-center"
624 style={{ maxWidth: props.contentMaxWidth }}
625 >
626 {!voiceInput.isBusy && composerMenu.trigger && composerMenu.items.length > 0 ? (
627 <View className="absolute inset-x-0 bottom-full z-10 mb-2">
628 <ComposerCommandPopover
629 items={composerMenu.items}
630 triggerKind={composerMenu.trigger.kind}
631 isLoading={composerMenu.isLoading}
632 onSelect={composerMenu.onSelect}
633 />
634 </View>
635 ) : null}
636
637 {connectionStatus ? (
638 <ComposerConnectionStatusPill
639 status={connectionStatus}
640 onPress={props.onReconnectEnvironment}
641 />
642 ) : null}
643
644 {modelUnavailable ? (
645 <Pressable accessibilityRole="button" className="px-3 py-2" onPress={openSettings}>
646 <Text className="text-xs text-foreground">Model unavailable. Open model settings.</Text>
647 </Pressable>
648 ) : null}
649
650 <ComposerSurface
651 style={
652 isExpanded
653 ? {
654 borderRadius: 26,
655 minHeight: 140,
656 overflow: "hidden" as const,
657 paddingBottom: 6,
658 paddingTop: 14,
659 }
660 : {
661 // Keep the numeric radius close to the expanded card so the
662 // shape morph stays bounded while rendering as a capsule.
663 borderRadius: 27,
664 overflow: "hidden" as const,
665 paddingVertical: 2,
666 }
667 }
668 >
669 <ComposerDictationDraftContent
670 className={isExpanded ? undefined : "flex-row items-center"}
671 compact={!isExpanded}
672 hidden={showsCompactDictation}
673 >
674 {!isExpanded ? (
675 <ComposerAttachmentButton
676 supportsFiles={Boolean(
677 props.serverConfig?.environment.capabilities.fileAttachments,
678 )}
679 onPickMedia={props.onPickDraftMedia}
680 onPickFiles={props.onPickDraftFiles}
681 />
682 ) : null}
683 {isExpanded && props.draftAttachments.length > 0 ? (
684 <Animated.View
685 className="px-[14px] pb-2.5"
686 entering={COMPOSER_ATTACHMENT_ENTERING}
687 exiting={FadeOut.duration(120)}
688 >
689 <ComposerAttachmentStrip
690 environmentId={props.environmentId}
691 attachments={props.draftAttachments}
692 onRemove={voiceInput.isBusy ? () => undefined : props.onRemoveDraftImage}
693 onPressPreview={voiceInput.isBusy ? undefined : onPressPreview}
694 onPressVideo={voiceInput.isBusy ? undefined : onPressVideo}
695 />
696 </Animated.View>
697 ) : null}
698 <Animated.View
699 className={isExpanded ? "px-[14px]" : "min-w-0 flex-1 px-[4px]"}
700 layout={COMPOSER_LAYOUT_TRANSITION}
701 >
702 <ComposerEditor
703 ref={inputRef}
704 multiline
705 value={props.draftMessage}
706 readOnly={voiceInput.freezesEditor}
707 skills={composerMenu.skills}
708 selection={composerMenu.selection}
709 onChangeText={props.onChangeDraftMessage}
710 onSelectionChange={composerMenu.onSelectionChange}
711 onPasteImages={(uris) => void props.onNativePasteImages(uris)}
712 placeholder={props.placeholder}
713 onFocus={handleFocus}
714 onBlur={handleBlur}
715 onSubmit={handleSend}
716 scrollEnabled={isExpanded}
717 // Android: collapsed single line centers natively (gravity) in
718 // a pill-height box matching the send button; iOS keeps insets.
719 singleLineCentered={!isExpanded}
720 contentInsetVertical={isExpanded || Platform.OS === "android" ? 0 : 6}
721 style={
722 isExpanded
723 ? {
724 minHeight: 72,
725 maxHeight: 160,
726 paddingVertical: 4,
727 }
728 : {
729 height: 36,
730 }
731 }
732 textStyle={{
733 ...bodyText,
734 color: foregroundColor,
735 }}
736 />
737 </Animated.View>
738 {!isExpanded && props.draftAttachments.length > 0 ? (
739 <View className="flex-row gap-1 pl-1">
740 {props.draftAttachments.slice(0, 3).map((attachment) => (
741 <ComposerAttachmentThumbnail
742 environmentId={props.environmentId}
743 key={attachment.id}
744 attachment={attachment}
745 size={30}
746 borderRadius={8}
747 compact
748 onPressPreview={onPressPreview}
749 onPressVideo={onPressVideo}
750 />
751 ))}
752 {props.draftAttachments.length > 3 ? (
753 <View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
754 <Text className="text-foreground-muted text-2xs font-t3-bold">
755 +{props.draftAttachments.length - 3}
756 </Text>
757 </View>
758 ) : null}
759 </View>
760 ) : null}
761 {!isExpanded ? (
762 <View className="flex-row items-center">
763 <ComposerDictationStartAction
764 state={voiceInput.state}
765 isAvailable={voiceInput.isAvailable}
766 onStart={voiceInput.start}
767 onCancel={voiceInput.cancel}
768 />
769 {showStopAction ? (
770 <ComposerActionButton
771 accessibilityLabel="Stop agent"
772 icon="stop.fill"
773 variant="danger"
774 onPress={props.onStopThread}
775 />
776 ) : (
777 <ComposerActionButton
778 accessibilityLabel={attachmentBlockReason ?? sendLabel}
779 icon="arrow.up"
780 variant="primary"
781 disabled={!canSend}
782 onPress={handleSend}
783 />
784 )}
785 </View>
786 ) : null}
787 {isExpanded ? <View className="h-1" /> : null}
788 </ComposerDictationDraftContent>
789 <Animated.View
790 accessibilityElementsHidden={!isToolbarVisible}
791 collapsable={false}
792 importantForAccessibility={isToolbarVisible ? "auto" : "no-hide-descendants"}
793 layout={COMPOSER_LAYOUT_TRANSITION}
794 pointerEvents={isToolbarVisible ? "auto" : "none"}
795 style={
796 isExpanded
797 ? undefined
798 : {
799 position: "absolute",
800 bottom: 2,
801 left: 0,
802 right: 0,
803 }
804 }
805 >
806 <ComposerDictationToolbar
807 showsDictation={isVoiceInputPresented}
808 visible={isToolbarVisible}
809 >
810 <ComposerToolbarRow
811 paddingBottom={0}
812 paddingHorizontal={0}
813 paddingTop={0}
814 style={{ gap: 0 }}
815 >
816 <ComposerDictationCancelAction
817 presentation={voicePresentation}
818 onCancel={voiceInput.cancel}
819 />
820 {isVoiceInputPresented ? (
821 <ComposerDictationStatus
822 audioLevels={voiceInput.audioLevels}
823 elapsedSeconds={voiceInput.elapsedSeconds}
824 phase={voiceInput.state.phase}
825 presentation={voicePresentation}
826 onDismissError={voiceInput.cancel}
827 />
828 ) : (
829 <View className="min-w-0 flex-1 flex-row items-center justify-between">
830 <ComposerAttachmentButton
831 supportsFiles={Boolean(
832 props.serverConfig?.environment.capabilities.fileAttachments,
833 )}
834 onPickMedia={props.onPickDraftMedia}
835 onPickFiles={props.onPickDraftFiles}
836 />
837 <View className="min-w-0 shrink" style={{ maxWidth: 152 }}>
838 <ComposerInlineControl
839 accessibilityLabel="Model and reasoning settings"
840 emphasized
841 iconNode={
842 <ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
843 }
844 label={currentModelOption?.label ?? currentModelSelection.model}
845 maxWidth={152}
846 onPress={openSettings}
847 />
848 </View>
849 </View>
850 )}
851 <View className="shrink-0 flex-row items-center">
852 <ComposerDictationPrimaryAction
853 state={voiceInput.state}
854 presentation={voicePresentation}
855 isAvailable={voiceInput.isAvailable}
856 onStart={voiceInput.start}
857 onConfirm={voiceInput.stop}
858 onCancel={voiceInput.cancel}
859 />
860 {showStopAction ? (
861 <ComposerActionButton
862 accessibilityLabel="Stop agent"
863 icon="stop.fill"
864 variant="danger"
865 onPress={props.onStopThread}
866 />
867 ) : voicePresentation.showsSend ? (
868 <ComposerActionButton
869 accessibilityLabel={attachmentBlockReason ?? sendLabel}
870 icon="arrow.up"
871 variant="primary"
872 disabled={!canSend}
873 onPress={handleSend}
874 />
875 ) : null}
876 </View>
877 </ComposerToolbarRow>
878 </ComposerDictationToolbar>
879 </Animated.View>
880 </ComposerSurface>
881
882 {/* Queue count */}
883 {props.queueCount > 0 ? (
884 <Animated.View entering={FadeIn.duration(180)} exiting={FadeOut.duration(120)}>
885 <Text className="pt-2 text-xs text-foreground-muted">
886 {props.queueCount} queued message{props.queueCount === 1 ? "" : "s"} will send
887 automatically.
888 </Text>
889 </Animated.View>
890 ) : null}
891 </Animated.View>
892
893 <VideoPreviewModal source={previewVideo} onRequestClose={closePreview} />
894 <FilePreviewModal source={previewFile} onRequestClose={closePreview} />
895 </Animated.View>
896 );
897});