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