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