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

ThreadComposer.tsx

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