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

ThreadComposer.tsx

832 lines31.9 KB

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