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