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