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