Open History to see the last commit
1import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
2import { useAtomValue } from "@effect/atom-react";
3import type {
4 EnvironmentId,
5 MessageId,
6 ModelSelection,
7 OrchestrationThreadShell,
8 ProviderInteractionMode,
9 RuntimeMode,
10 ServerConfig as T3ServerConfig,
11 UsageLimitsReport,
12} from "@t3tools/contracts";
13import {
14 collectProviderUsageLimits,
15 hasProviderUsageLimits,
16 isUsageLimitsCommand,
17} from "@t3tools/shared/usageLimits";
18import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";
19import type { ReactNode } from "react";
20import {
21 memo,
22 useCallback,
23 useEffect,
24 useLayoutEffect,
25 useMemo,
26 useRef,
27 useState,
28 type RefObject,
29} from "react";
30import { Alert, Platform, Pressable, View, type ViewStyle } from "react-native";
31import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
32import {
33 composerAttachmentUploadBlockReason,
34 composerAttachmentsStillUploading,
35 composerAttachmentUploadsAtom,
36} from "../../state/composer-attachment-uploads";
37import Animated, {
38 FadeIn,
39 FadeOut,
40 type LayoutAnimationFunction,
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 environmentLabel: string | null;
118 readonly selectedThread: OrchestrationThreadShell;
119 readonly hasCompactableConversation: boolean;
120 readonly serverConfig: T3ServerConfig | null;
121 readonly queueCount: number;
122 readonly environmentId: EnvironmentId;
123 readonly projectCwd: string | null;
124 /** Why sending is blocked right now (shown as the send button's label), or null. */
125 readonly sendBlockedReason?: string | null;
126 readonly editorRef?: RefObject<ComposerEditorHandle | null>;
127 readonly onChangeDraftMessage: (value: string) => void;
128 readonly onPickDraftMedia: () => Promise<void>;
129 readonly onPickDraftFiles: () => Promise<void>;
130 readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
131 readonly onRemoveDraftImage: (imageId: string) => void;
132 readonly onStopThread: () => void;
133 readonly onSendMessage: () => Promise<MessageId | null>;
134 /** `/usage-limits` resolves locally; the host decides where the report shows. Null clears it. */
135 readonly onShowUsageLimits: (report: UsageLimitsReport | null) => void;
136 readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
137 readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;
138 readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => 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, with a frosted blur fallback where supported.
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;
156// Side panes already animate the dock's width. Nested horizontal layout
157// transitions would leave the surface trailing its toolbar's new position.
158// Keep the vertical pill/card morph while horizontal layout follows the dock.
159const composerHeightTransition: LayoutAnimationFunction = (values) => {
160 "worklet";
161 const timing = {
162 duration: COMPOSER_TRANSITION_DURATION_MS,
163 reduceMotion: ReduceMotion.System,
164 };
165 return {
166 initialValues: {
167 originX: values.targetOriginX,
168 originY: values.currentOriginY,
169 width: values.targetWidth,
170 height: values.currentHeight,
171 },
172 animations: {
173 originX: values.targetOriginX,
174 originY: withTiming(values.targetOriginY, timing),
175 width: values.targetWidth,
176 height: withTiming(values.targetHeight, timing),
177 },
178 };
179};
180export const COMPOSER_LAYOUT_TRANSITION =
181 Platform.OS === "android" ? undefined : composerHeightTransition;
182
183const COMPOSER_ATTACHMENT_ENTERING =
184 Platform.OS === "android"
185 ? FadeIn.duration(160)
186 : FadeIn.delay(COMPOSER_TRANSITION_DURATION_MS).duration(160).reduceMotion(ReduceMotion.System);
187
188const AnimatedGlassSurface = Animated.createAnimatedComponent(GlassSurface);
189
190export function ComposerSurface(props: {
191 readonly children: ReactNode;
192 readonly style: ViewStyle;
193 /** Morphs between the compact and expanded composer layouts. */
194 readonly animateLayout?: boolean;
195}) {
196 const { materialYouStyleLayoutActive } = useAppearancePreferences();
197 const colors = useUniwindTheme();
198 const targetBorderRadius =
199 typeof props.style.borderRadius === "number" ? props.style.borderRadius : 0;
200 const animatedBorderRadius = useSharedValue(targetBorderRadius);
201 const shouldAnimate = props.animateLayout !== false && Platform.OS !== "android";
202 useLayoutEffect(() => {
203 animatedBorderRadius.value = shouldAnimate
204 ? withTiming(targetBorderRadius, {
205 duration: COMPOSER_TRANSITION_DURATION_MS,
206 reduceMotion: ReduceMotion.System,
207 })
208 : targetBorderRadius;
209 }, [animatedBorderRadius, shouldAnimate, targetBorderRadius]);
210 const animatedShapeStyle = useAnimatedStyle(() => ({
211 borderRadius: animatedBorderRadius.value,
212 }));
213 const layoutTransition = shouldAnimate ? COMPOSER_LAYOUT_TRANSITION : undefined;
214
215 // Each native frame follows the same transition. Animating only the outer
216 // clip leaves the glass and content at their final height on the first frame.
217 return (
218 <Animated.View
219 className={
220 materialYouStyleLayoutActive
221 ? undefined
222 : "shadow-[0_6px_28px] shadow-adaptive-black-a15-a35"
223 }
224 layout={layoutTransition}
225 style={[
226 animatedShapeStyle,
227 {
228 overflow: "hidden",
229 // Android versions before 9 do not support outset box shadows.
230 elevation: Platform.OS === "android" && Platform.Version < 28 ? 10 : undefined,
231 },
232 ]}
233 >
234 <AnimatedGlassSurface
235 chrome="none"
236 fallbackColor={
237 materialYouStyleLayoutActive ? colors["--color-composer-surface"] : colors["--color-card"]
238 }
239 fallbackClassName={
240 materialYouStyleLayoutActive ? "border border-composer-border" : "border border-border"
241 }
242 glassEffectStyle="regular"
243 // The composer is a passive material containing interactive controls.
244 // Keep native glass out of the interactive content's layout path.
245 pointerEvents="none"
246 tintColor="transparent"
247 layout={layoutTransition}
248 style={[{ position: "absolute", inset: 0 }, animatedShapeStyle]}
249 >
250 {null}
251 </AnimatedGlassSurface>
252 <Animated.View
253 collapsable={false}
254 layout={layoutTransition}
255 style={[props.style, animatedShapeStyle]}
256 >
257 {props.children}
258 </Animated.View>
259 </Animated.View>
260 );
261}
262
263export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) {
264 const { materialYouStyleLayoutActive, themeVariables: materialTheme } =
265 useAppearancePreferences();
266 const composerPanel = materialTheme["--color-composer-panel"];
267 const navigation = useNavigation();
268 const foregroundColor = useUniwindTheme()["--color-foreground"];
269 const bodyText = useScaledTextRole("body");
270 const fallbackInputRef = useRef<ComposerEditorHandle>(null);
271 const inputRef = props.editorRef ?? fallbackInputRef;
272 const [isFocused, setIsFocused] = useState(false);
273 const settingsSheetPresentation = useThreadSettingsSheetPresentation({
274 editorRef: inputRef,
275 isEditorFocused: isFocused,
276 });
277 const settingsRoutePresentation = useExistingThreadSettingsRoutePresentation();
278 const settingsRoutePresentedRef = useRef(false);
279 const wasExpandedBeforePreviewRef = useRef(false);
280 const inFlightThreadIdsRef = useRef(new Set<string>());
281 const { onExpandedChange } = props;
282
283 const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
284 const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);
285 const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
286 const showStopAction =
287 !hasContent &&
288 (props.selectedThread.session?.status === "running" ||
289 props.selectedThread.session?.status === "starting");
290
291 const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
292 const attachmentsUploading =
293 props.connectionState === "connected" &&
294 composerAttachmentsStillUploading({
295 environmentId: props.environmentId,
296 attachments: props.draftAttachments,
297 serverConfig: props.serverConfig,
298 states: uploadStates,
299 });
300 // Every send goes through the outbox; the label says whether it leaves now
301 // or waits (for the connection, an earlier queued message, or an upload).
302 const sendLabel =
303 props.connectionState !== "connected" || props.queueCount > 0 || attachmentsUploading
304 ? "Queue"
305 : "Send";
306 const currentModelSelection = props.selectedThread.modelSelection;
307 const currentRuntimeMode = props.selectedThread.runtimeMode;
308 const modelUnavailable =
309 props.connectionState === "connected" &&
310 isModelSelectionUnavailable(props.serverConfig, currentModelSelection);
311 const selectedProviderStatus = useMemo(() => {
312 if (!props.serverConfig) return null;
313 return (
314 props.serverConfig.providers.find(
315 (p) => p.instanceId === props.selectedThread.modelSelection.instanceId,
316 ) ?? null
317 );
318 }, [props.serverConfig, props.selectedThread.modelSelection.instanceId]);
319 const composerOwnerKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
320 const { onSendMessage, onChangeDraftMessage, onShowUsageLimits } = props;
321 // T3 owns /usage-limits only where Limits has data for the selected provider;
322 // elsewhere the name stays the provider's own and is sent through untouched.
323 const usageLimitsOffered =
324 selectedProviderStatus !== null &&
325 hasProviderUsageLimits(
326 selectedProviderStatus.driver,
327 props.serverConfig?.providers ?? [],
328 props.serverConfig?.usageLimitSources ?? [],
329 );
330 // Answered locally from the last Limits snapshot; the agent never sees it.
331 const openUsageLimits = useCallback(() => {
332 const report = collectProviderUsageLimits(
333 currentModelSelection.instanceId,
334 props.serverConfig?.providers ?? [],
335 props.serverConfig?.usageLimitSources ?? [],
336 Date.now(),
337 );
338 onShowUsageLimits(report);
339 if (!report) {
340 Alert.alert("Usage limits unavailable", "This provider does not currently report limits.");
341 }
342 return report !== null;
343 }, [currentModelSelection.instanceId, onShowUsageLimits, props.serverConfig]);
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 offersUsageLimits: usageLimitsOffered,
359 // With attachments aboard the pick just inserts the text, so it sends as a prompt.
360 onUsageLimits:
361 usageLimitsOffered && props.draftAttachments.length === 0 ? openUsageLimits : undefined,
362 });
363 const voiceInput = useVoiceInputController({
364 ownerKey: composerOwnerKey,
365 draftMessage: props.draftMessage,
366 selection: composerMenu.selection,
367 onChangeDraftMessage: props.onChangeDraftMessage,
368 onChangeSelection: composerMenu.onSelectionChange,
369 });
370 const voicePresentation = resolveVoiceComposerPresentation(
371 voiceInput.state,
372 voiceInput.elapsedSeconds,
373 );
374 const isVoiceInputPresented = voicePresentation.statusLabel !== null;
375 // An open draft stays visible; only a collapsed composer becomes a voice strip.
376 const isExpanded = isFocused || settingsSheetPresentation.keepsComposerExpanded;
377 const showsCompactDictation = isVoiceInputPresented && !isExpanded;
378 const isToolbarVisible = isExpanded || isVoiceInputPresented;
379 const attachmentBlockReason = composerAttachmentUploadBlockReason({
380 environmentId: props.environmentId,
381 attachments: props.draftAttachments,
382 connected: props.connectionState === "connected",
383 serverConfig: props.serverConfig,
384 states: uploadStates,
385 });
386 const sendBlockedReason = props.sendBlockedReason ?? attachmentBlockReason;
387 const canSend =
388 hasContent && !voiceInput.blocksSubmission && sendBlockedReason === null && !modelUnavailable;
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.keepsComposerExpanded) {
433 onExpandedChange?.(false);
434 }
435 onEditorFocusChange?.(false);
436 }, [onEditorFocusChange, onExpandedChange, settingsSheetPresentation.keepsComposerExpanded]);
437 const handleSend = useCallback(async () => {
438 // Typed out in full rather than picked from the menu. Attachments mean the
439 // user is sending a prompt, so those go through as usual.
440 if (
441 usageLimitsOffered &&
442 isUsageLimitsCommand(props.draftMessage) &&
443 props.draftAttachments.length === 0
444 ) {
445 if (openUsageLimits()) onChangeDraftMessage("");
446 return;
447 }
448 if (voiceInput.blocksSubmission) return;
449 const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
450 if (inFlightThreadIdsRef.current.has(threadKey)) return;
451 inFlightThreadIdsRef.current.add(threadKey);
452 try {
453 const messageId = await onSendMessage();
454 if (messageId === null) {
455 return;
456 }
457 // Sending a prompt starts agent work: arm the lock-screen card while the
458 // app is foregrounded and the activity token can be registered. Armed
459 // after the send so its preference read and native Activity start don't
460 // contend with the queued-message feedback on the tap frame.
461 armAgentAwarenessLiveActivityForLocalWork({
462 environmentId: props.environmentId,
463 threadTitle: props.selectedThread.title,
464 projectTitle: props.environmentLabel ?? "T3 Code",
465 });
466 } finally {
467 inFlightThreadIdsRef.current.delete(threadKey);
468 }
469 }, [
470 props.draftMessage,
471 props.draftAttachments.length,
472 onChangeDraftMessage,
473 openUsageLimits,
474 usageLimitsOffered,
475 onSendMessage,
476 props.environmentId,
477 props.environmentLabel,
478 props.selectedThread.id,
479 props.selectedThread.title,
480 voiceInput.blocksSubmission,
481 ]);
482
483 // ── Model menu ───────────────────────────────────────────
484 const modelOptions = useMemo(
485 () => buildModelOptions(props.serverConfig, currentModelSelection),
486 [props.serverConfig, currentModelSelection],
487 );
488 const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
489 // An existing thread is bound to its harness: sessions can't move between
490 // provider instances, so the picker only offers the thread's own group.
491 const threadProviderGroups = useMemo(
492 () => providerGroups.filter((group) => group.providerKey === currentModelSelection.instanceId),
493 [providerGroups, currentModelSelection.instanceId],
494 );
495 const currentModelOption =
496 modelOptions.find(
497 (option) =>
498 option.selection.instanceId === currentModelSelection.instanceId &&
499 option.selection.model === currentModelSelection.model,
500 ) ?? null;
501 const providerOptionDescriptors = useMemo(
502 () =>
503 resolveProviderOptionDescriptors({
504 capabilities: currentModelOption?.capabilities,
505 selections: currentModelSelection.options,
506 }),
507 [currentModelOption?.capabilities, currentModelSelection.options],
508 );
509 const settingsOwnerId = composerOwnerKey;
510 const settingsRouteSession = useMemo<ExistingThreadSettingsRouteSession>(
511 () => ({
512 ownerId: settingsOwnerId,
513 environmentId: props.environmentId,
514 providerInstanceId: currentModelSelection.instanceId,
515 providerGroups: threadProviderGroups,
516 selectedModel: currentModelSelection,
517 onSelectModel: (option) => props.onUpdateModelSelection(option.selection),
518 optionDescriptors: providerOptionDescriptors,
519 onUpdateOptionSelections: (options) =>
520 props.onUpdateModelSelection({ ...currentModelSelection, options }),
521 runtimeMode: currentRuntimeMode,
522 onUpdateRuntimeMode: props.onUpdateRuntimeMode,
523 }),
524 [
525 currentModelSelection,
526 currentRuntimeMode,
527 props.onUpdateModelSelection,
528 props.onUpdateRuntimeMode,
529 providerOptionDescriptors,
530 settingsOwnerId,
531 threadProviderGroups,
532 ],
533 );
534 const openSettings = useCallback(() => {
535 settingsRoutePresentation.present(settingsRouteSession);
536 settingsSheetPresentation.open();
537 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.open]);
538
539 useEffect(() => {
540 if (settingsSheetPresentation.isActive) {
541 settingsRoutePresentation.present(settingsRouteSession);
542 }
543 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.isActive]);
544
545 useEffect(() => {
546 if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
547 return;
548 }
549
550 settingsRoutePresentedRef.current = true;
551 navigation.dispatch(StackActions.push("ThreadSettingsSheet"));
552 }, [navigation, settingsSheetPresentation.isVisible]);
553
554 useFocusEffect(
555 useCallback(() => {
556 if (!settingsRoutePresentedRef.current) {
557 return;
558 }
559
560 settingsRoutePresentedRef.current = false;
561 settingsSheetPresentation.onDismissed();
562 settingsRoutePresentation.clear(settingsOwnerId);
563 }, [settingsOwnerId, settingsRoutePresentation.clear, settingsSheetPresentation.onDismissed]),
564 );
565
566 useEffect(
567 () =>
568 // UIKit's completion callback for the sheet dismissal, surfaced by the
569 // native-stack patch. This is when the queued keyboard restore runs.
570 (navigation as unknown as NavigationWithFinishTransitioning).addListener(
571 "finishTransitioning",
572 settingsSheetPresentation.onStackTransitionsFinished,
573 ),
574 [navigation, settingsSheetPresentation.onStackTransitionsFinished],
575 );
576
577 return (
578 <Animated.View
579 className="px-[12px]"
580 style={{
581 paddingTop: isExpanded ? 8 : 6,
582 paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 8 : 6),
583 backgroundColor: materialYouStyleLayoutActive ? composerPanel : undefined,
584 }}
585 >
586 {/* The backdrop gradient lives on a plain View: Reanimated's Animated.View
587 silently drops experimental_backgroundImage on Android, which left this
588 strip fully transparent and the feed text legible through the composer. */}
589 <View
590 className={
591 materialYouStyleLayoutActive
592 ? "hidden"
593 : "absolute inset-0 bg-linear-to-b from-screen/0 via-screen/60 to-screen/90"
594 }
595 pointerEvents="none"
596 />
597 <Animated.View
598 className="relative w-full self-center"
599 style={{ maxWidth: props.contentMaxWidth }}
600 >
601 {!voiceInput.isBusy && composerMenu.trigger && composerMenu.items.length > 0 ? (
602 <View className="absolute inset-x-0 bottom-full z-10 mb-2">
603 <ComposerCommandPopover
604 items={composerMenu.items}
605 triggerKind={composerMenu.trigger.kind}
606 isLoading={composerMenu.isLoading}
607 onSelect={composerMenu.onSelect}
608 />
609 </View>
610 ) : null}
611
612 {modelUnavailable ? (
613 <Pressable accessibilityRole="button" className="px-3 py-2" onPress={openSettings}>
614 <Text className="text-xs text-foreground">Model unavailable. Open model settings.</Text>
615 </Pressable>
616 ) : null}
617
618 <ComposerSurface
619 style={
620 isExpanded
621 ? {
622 borderRadius: 26,
623 minHeight: 140,
624 overflow: "hidden" as const,
625 paddingBottom: 6,
626 paddingTop: 14,
627 }
628 : {
629 // Keep the numeric radius close to the expanded card so the
630 // shape morph stays bounded while rendering as a capsule.
631 borderRadius: 27,
632 overflow: "hidden" as const,
633 paddingVertical: 2,
634 }
635 }
636 >
637 <ComposerDictationDraftContent
638 className={isExpanded ? undefined : "flex-row items-center"}
639 compact={!isExpanded}
640 hidden={showsCompactDictation}
641 >
642 {!isExpanded ? (
643 <ComposerAttachmentButton
644 supportsFiles={Boolean(
645 props.serverConfig?.environment.capabilities.fileAttachments,
646 )}
647 onPickMedia={props.onPickDraftMedia}
648 onPickFiles={props.onPickDraftFiles}
649 />
650 ) : null}
651 {isExpanded && props.draftAttachments.length > 0 ? (
652 <Animated.View
653 className="px-[14px] pb-2.5"
654 entering={COMPOSER_ATTACHMENT_ENTERING}
655 exiting={FadeOut.duration(120)}
656 >
657 <ComposerAttachmentStrip
658 environmentId={props.environmentId}
659 attachments={props.draftAttachments}
660 onRemove={voiceInput.isBusy ? () => undefined : props.onRemoveDraftImage}
661 onPressPreview={voiceInput.isBusy ? undefined : onPressPreview}
662 onPressVideo={voiceInput.isBusy ? undefined : onPressVideo}
663 />
664 </Animated.View>
665 ) : null}
666 <Animated.View
667 className={isExpanded ? "px-[14px]" : "min-w-0 flex-1 px-[4px]"}
668 layout={COMPOSER_LAYOUT_TRANSITION}
669 >
670 <ComposerEditor
671 ref={inputRef}
672 multiline
673 value={props.draftMessage}
674 readOnly={voiceInput.freezesEditor}
675 skills={composerMenu.skills}
676 selection={composerMenu.selection}
677 onChangeText={props.onChangeDraftMessage}
678 onSelectionChange={composerMenu.onSelectionChange}
679 onPasteImages={(uris) => void props.onNativePasteImages(uris)}
680 placeholder={props.placeholder}
681 onFocus={handleFocus}
682 onBlur={handleBlur}
683 onSubmit={handleSend}
684 scrollEnabled={isExpanded}
685 // Android: collapsed single line centers natively (gravity) in
686 // a pill-height box matching the send button; iOS keeps insets.
687 singleLineCentered={!isExpanded}
688 contentInsetVertical={isExpanded || Platform.OS === "android" ? 0 : 6}
689 style={
690 isExpanded
691 ? {
692 minHeight: 72,
693 maxHeight: 160,
694 paddingVertical: 4,
695 }
696 : {
697 height: 36,
698 }
699 }
700 textStyle={{
701 ...bodyText,
702 color: foregroundColor,
703 }}
704 />
705 </Animated.View>
706 {!isExpanded && props.draftAttachments.length > 0 ? (
707 <View className="flex-row gap-1 pl-1">
708 {props.draftAttachments.slice(0, 3).map((attachment) => (
709 <ComposerAttachmentThumbnail
710 environmentId={props.environmentId}
711 key={attachment.id}
712 attachment={attachment}
713 size={30}
714 borderRadius={8}
715 compact
716 onPressPreview={onPressPreview}
717 onPressVideo={onPressVideo}
718 />
719 ))}
720 {props.draftAttachments.length > 3 ? (
721 <View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
722 <Text className="text-foreground-muted text-2xs font-t3-bold">
723 +{props.draftAttachments.length - 3}
724 </Text>
725 </View>
726 ) : null}
727 </View>
728 ) : null}
729 {!isExpanded ? (
730 <View className="flex-row items-center">
731 <ComposerDictationStartAction
732 state={voiceInput.state}
733 isAvailable={voiceInput.isAvailable}
734 onStart={voiceInput.start}
735 onCancel={voiceInput.cancel}
736 />
737 {showStopAction ? (
738 <ComposerActionButton
739 accessibilityLabel="Stop agent"
740 icon="stop.fill"
741 variant="danger"
742 onPress={props.onStopThread}
743 />
744 ) : (
745 <ComposerActionButton
746 accessibilityLabel={sendBlockedReason ?? sendLabel}
747 icon="arrow.up"
748 variant="primary"
749 disabled={!canSend}
750 onPress={handleSend}
751 />
752 )}
753 </View>
754 ) : null}
755 {isExpanded ? <View className="h-1" /> : null}
756 </ComposerDictationDraftContent>
757 <Animated.View
758 accessibilityElementsHidden={!isToolbarVisible}
759 collapsable={false}
760 importantForAccessibility={isToolbarVisible ? "auto" : "no-hide-descendants"}
761 layout={COMPOSER_LAYOUT_TRANSITION}
762 pointerEvents={isToolbarVisible ? "auto" : "none"}
763 style={
764 isExpanded
765 ? undefined
766 : {
767 position: "absolute",
768 bottom: 2,
769 left: 0,
770 right: 0,
771 }
772 }
773 >
774 <ComposerDictationToolbar
775 showsDictation={isVoiceInputPresented}
776 visible={isToolbarVisible}
777 >
778 <ComposerToolbarRow
779 paddingBottom={0}
780 paddingHorizontal={0}
781 paddingTop={0}
782 style={{ gap: 0 }}
783 >
784 <ComposerDictationCancelAction
785 presentation={voicePresentation}
786 onCancel={voiceInput.cancel}
787 />
788 {isVoiceInputPresented ? (
789 <ComposerDictationStatus
790 audioLevels={voiceInput.audioLevels}
791 elapsedSeconds={voiceInput.elapsedSeconds}
792 phase={voiceInput.state.phase}
793 presentation={voicePresentation}
794 onDismissError={voiceInput.cancel}
795 />
796 ) : (
797 <View className="min-w-0 flex-1 flex-row items-center justify-between">
798 <ComposerAttachmentButton
799 supportsFiles={Boolean(
800 props.serverConfig?.environment.capabilities.fileAttachments,
801 )}
802 onPickMedia={props.onPickDraftMedia}
803 onPickFiles={props.onPickDraftFiles}
804 />
805 <View className="min-w-0 shrink">
806 <ComposerInlineControl
807 accessibilityLabel="Model and reasoning settings"
808 emphasized
809 iconNode={
810 <ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
811 }
812 label={currentModelOption?.label ?? currentModelSelection.model}
813 maxWidth="100%"
814 onPress={openSettings}
815 />
816 </View>
817 </View>
818 )}
819 <View className="shrink-0 flex-row items-center">
820 <ComposerDictationPrimaryAction
821 state={voiceInput.state}
822 presentation={voicePresentation}
823 isAvailable={voiceInput.isAvailable}
824 onStart={voiceInput.start}
825 onConfirm={voiceInput.stop}
826 onCancel={voiceInput.cancel}
827 />
828 {showStopAction ? (
829 <ComposerActionButton
830 accessibilityLabel="Stop agent"
831 icon="stop.fill"
832 variant="danger"
833 onPress={props.onStopThread}
834 />
835 ) : voicePresentation.showsSend ? (
836 <ComposerActionButton
837 accessibilityLabel={sendBlockedReason ?? sendLabel}
838 icon="arrow.up"
839 variant="primary"
840 disabled={!canSend}
841 onPress={handleSend}
842 />
843 ) : null}
844 </View>
845 </ComposerToolbarRow>
846 </ComposerDictationToolbar>
847 </Animated.View>
848 </ComposerSurface>
849 </Animated.View>
850
851 <VideoPreviewModal source={previewVideo} onRequestClose={closePreview} />
852 <FilePreviewModal source={previewFile} onRequestClose={closePreview} />
853 </Animated.View>
854 );
855});