Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadComposer.tsx

866 lines33.2 KB

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