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

ThreadComposer.tsx

833 lines32.9 KB

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