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={colors["--color-composer-surface"]}
248 fallbackClassName="border border-composer-border"
249 glassEffectStyle="regular"
250 // The composer is a passive material containing interactive controls.
251 // Keep native glass out of the interactive content's layout path.
252 pointerEvents="none"
253 tintColor="transparent"
254 layout={layoutTransition}
255 style={[{ position: "absolute", inset: 0 }, animatedShapeStyle]}
256 >
257 {null}
258 </AnimatedGlassSurface>
259 <Animated.View
260 collapsable={false}
261 layout={layoutTransition}
262 style={[props.style, animatedShapeStyle]}
263 >
264 {props.children}
265 </Animated.View>
266 </Animated.View>
267 );
268}
269
270export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) {
271 const project = useProject(scopeProjectRef(props.environmentId, props.selectedThread.projectId));
272 const { themeVariables: materialTheme } = useAppearancePreferences();
273 const composerPanel = materialTheme["--color-composer-panel"];
274 const navigation = useNavigation();
275 const foregroundColor = useUniwindTheme()["--color-foreground"];
276 const bodyText = useScaledTextRole("body");
277 const fallbackInputRef = useRef<ComposerEditorHandle>(null);
278 const inputRef = props.editorRef ?? fallbackInputRef;
279 const [isFocused, setIsFocused] = useState(false);
280 const pendingPastedTextAttachmentCountRef = useRef(0);
281 const [pendingPastedTextAttachmentCount, setPendingPastedTextAttachmentCount] = useState(0);
282 const settingsSheetPresentation = useThreadSettingsSheetPresentation({
283 editorRef: inputRef,
284 isEditorFocused: isFocused,
285 });
286 const settingsRoutePresentation = useExistingThreadSettingsRoutePresentation();
287 const settingsRoutePresentedRef = useRef(false);
288 const wasExpandedBeforePreviewRef = useRef(false);
289 const inFlightThreadIdsRef = useRef(new Set<string>());
290 const { onExpandedChange } = props;
291
292 const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
293 const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);
294 const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
295 // Only media belongs above the composer; every other file reads as its inline chip.
296 const stripAttachments = useMemo(
297 () => composerStripAttachments(props.draftAttachments),
298 [props.draftAttachments],
299 );
300 const showStopAction =
301 !hasContent &&
302 (props.selectedThread.session?.status === "running" ||
303 props.selectedThread.session?.status === "starting");
304
305 const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
306 const attachmentsUploading =
307 props.connectionState === "connected" &&
308 composerAttachmentsStillUploading({
309 environmentId: props.environmentId,
310 attachments: props.draftAttachments,
311 serverConfig: props.serverConfig,
312 states: uploadStates,
313 });
314 // Every send goes through the outbox; the label says whether it leaves now
315 // or waits (for the connection, an earlier queued message, or an upload).
316 const sendLabel =
317 props.connectionState !== "connected" || props.queueCount > 0 || attachmentsUploading
318 ? "Queue"
319 : "Send";
320 const currentModelSelection = props.selectedThread.modelSelection;
321 const currentRuntimeMode = props.selectedThread.runtimeMode;
322 const modelUnavailable =
323 props.connectionState === "connected" &&
324 isModelSelectionUnavailable(props.serverConfig, currentModelSelection);
325 const selectedProviderStatus = useMemo(() => {
326 if (!props.serverConfig) return null;
327 return (
328 props.serverConfig.providers.find(
329 (p) => p.instanceId === props.selectedThread.modelSelection.instanceId,
330 ) ?? null
331 );
332 }, [props.serverConfig, props.selectedThread.modelSelection.instanceId]);
333 const composerOwnerKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
334 const openDraftDocument = (attachment: ComposerDocumentAttachment) => {
335 Keyboard.dismiss();
336 navigation.navigate("ThreadAttachment", {
337 environmentId: String(props.environmentId),
338 threadId: String(props.selectedThread.id),
339 attachmentId: attachment.attachmentId,
340 name: attachment.name,
341 mimeType: attachment.mimeType,
342 sizeBytes: String(attachment.sizeBytes),
343 draftKey: composerOwnerKey,
344 });
345 };
346 const { onSendMessage, onChangeDraftMessage, onShowUsageLimits } = props;
347 // T3 owns /usage-limits only where Limits has data for the selected provider;
348 // elsewhere the name stays the provider's own and is sent through untouched.
349 const usageLimitsOffered =
350 selectedProviderStatus !== null &&
351 hasProviderUsageLimits(
352 selectedProviderStatus.driver,
353 props.serverConfig?.providers ?? [],
354 props.serverConfig?.usageLimitSources ?? [],
355 );
356 // Answered locally from the last Limits snapshot; the agent never sees it.
357 const openUsageLimits = useCallback(() => {
358 const report = collectProviderUsageLimits(
359 currentModelSelection.instanceId,
360 props.serverConfig?.providers ?? [],
361 props.serverConfig?.usageLimitSources ?? [],
362 Date.now(),
363 );
364 onShowUsageLimits(report);
365 if (!report) {
366 Alert.alert("Usage limits unavailable", "This provider does not currently report limits.");
367 }
368 return report !== null;
369 }, [currentModelSelection.instanceId, onShowUsageLimits, props.serverConfig]);
370
371 const composerMenu = useComposerCommandMenu({
372 draftMessage: props.draftMessage,
373 ownerKey: composerOwnerKey,
374 environmentId: props.environmentId,
375 projectCwd: props.projectCwd,
376 pullRequestProjectId: props.serverConfig?.environment.capabilities.pullRequests
377 ? (project?.id ?? null)
378 : null,
379 pullRequestRepository: project?.repositoryIdentity?.displayName ?? null,
380 selectedProviderStatus,
381 hasThread: true,
382 hasCompactableConversation: props.hasCompactableConversation,
383 onChangeDraftMessage: props.onChangeDraftMessage,
384 onUpdateInteractionMode:
385 selectedProviderStatus?.showInteractionModeToggle === false
386 ? undefined
387 : props.onUpdateInteractionMode,
388 offersUsageLimits: usageLimitsOffered,
389 // With attachments aboard the pick just inserts the text, so it sends as a prompt.
390 onUsageLimits:
391 usageLimitsOffered && props.draftAttachments.length === 0 ? openUsageLimits : undefined,
392 });
393 const voiceInput = useVoiceInputController({
394 ownerKey: composerOwnerKey,
395 draftMessage: props.draftMessage,
396 selection: composerMenu.selection,
397 onChangeDraftMessage: props.onChangeDraftMessage,
398 onChangeSelection: composerMenu.onSelectionChange,
399 });
400 const voicePresentation = resolveVoiceComposerPresentation(
401 voiceInput.state,
402 voiceInput.elapsedSeconds,
403 );
404 const isVoiceInputPresented = voicePresentation.statusLabel !== null;
405 // An open draft stays visible; only a collapsed composer becomes a voice strip.
406 const isExpanded = isFocused || settingsSheetPresentation.keepsComposerExpanded;
407 const showsCompactDictation = isVoiceInputPresented && !isExpanded;
408 const isToolbarVisible = isExpanded || isVoiceInputPresented;
409 const attachmentBlockReason = composerAttachmentUploadBlockReason({
410 environmentId: props.environmentId,
411 attachments: props.draftAttachments,
412 connected: props.connectionState === "connected",
413 serverConfig: props.serverConfig,
414 states: uploadStates,
415 });
416 const contextImports = useAtomValue(composerContextImportsAtom);
417 const sendBlockedReason =
418 props.sendBlockedReason ??
419 (pendingPastedTextAttachmentCount > 0 ? "Attaching pasted text" : null) ??
420 attachmentBlockReason;
421 const canSend =
422 hasContent &&
423 !contextImports[composerOwnerKey] &&
424 !voiceInput.blocksSubmission &&
425 sendBlockedReason === null &&
426 !modelUnavailable;
427
428 // Keep the feed inset aligned with the card or compact dictation strip.
429 useEffect(() => {
430 onExpandedChange?.(isExpanded);
431 }, [isExpanded, onExpandedChange]);
432
433 const onPressPreview = useCallback(
434 (source: FilePreviewSource) => {
435 wasExpandedBeforePreviewRef.current = isFocused;
436 setPreviewVideo(null);
437 setPreviewFile((current) => current ?? source);
438 },
439 [isFocused],
440 );
441
442 const closePreview = useCallback(() => {
443 setPreviewFile(null);
444 setPreviewVideo(null);
445 if (wasExpandedBeforePreviewRef.current) {
446 setTimeout(() => {
447 if (navigation.isFocused()) inputRef.current?.focus();
448 }, 100);
449 }
450 }, [inputRef, navigation]);
451
452 const onPressVideo = useCallback(
453 (attachment: DraftComposerFileAttachment, sourceIdentifier: string) => {
454 wasExpandedBeforePreviewRef.current = isFocused;
455 setPreviewFile(null);
456 setPreviewVideo((current) => current ?? { type: "local", attachment, sourceIdentifier });
457 },
458 [isFocused],
459 );
460
461 const onEditorFocusChange = props.onEditorFocusChange;
462 const handleFocus = useCallback(() => {
463 setIsFocused(true);
464 onExpandedChange?.(true);
465 onEditorFocusChange?.(true);
466 }, [onEditorFocusChange, onExpandedChange]);
467
468 const handleBlur = useCallback(() => {
469 setIsFocused(false);
470 if (!settingsSheetPresentation.keepsComposerExpanded) {
471 onExpandedChange?.(false);
472 }
473 onEditorFocusChange?.(false);
474 }, [onEditorFocusChange, onExpandedChange, settingsSheetPresentation.keepsComposerExpanded]);
475 const handleSend = useCallback(async () => {
476 if (voiceInput.blocksSubmission || pendingPastedTextAttachmentCountRef.current > 0) return;
477 // Typed out in full rather than picked from the menu. Attachments mean the
478 // user is sending a prompt, so those go through as usual.
479 if (
480 usageLimitsOffered &&
481 isUsageLimitsCommand(props.draftMessage) &&
482 props.draftAttachments.length === 0
483 ) {
484 if (openUsageLimits()) onChangeDraftMessage("");
485 return;
486 }
487 const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
488 if (inFlightThreadIdsRef.current.has(threadKey)) return;
489 inFlightThreadIdsRef.current.add(threadKey);
490 try {
491 const messageId = await onSendMessage();
492 if (messageId === null) {
493 return;
494 }
495 // Sending a prompt starts agent work: arm the lock-screen card while the
496 // app is foregrounded and the activity token can be registered. Armed
497 // after the send so its preference read and native Activity start don't
498 // contend with the queued-message feedback on the tap frame.
499 armAgentAwarenessLiveActivityForLocalWork({
500 environmentId: props.environmentId,
501 threadTitle: props.selectedThread.title,
502 projectTitle: props.environmentLabel ?? "T3 Code",
503 });
504 } finally {
505 inFlightThreadIdsRef.current.delete(threadKey);
506 }
507 }, [
508 props.draftMessage,
509 props.draftAttachments.length,
510 onChangeDraftMessage,
511 openUsageLimits,
512 usageLimitsOffered,
513 onSendMessage,
514 props.environmentId,
515 props.environmentLabel,
516 props.selectedThread.id,
517 props.selectedThread.title,
518 voiceInput.blocksSubmission,
519 ]);
520
521 // ── Model menu ───────────────────────────────────────────
522 const modelOptions = useMemo(
523 () => buildModelOptions(props.serverConfig, currentModelSelection),
524 [props.serverConfig, currentModelSelection],
525 );
526 const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
527 // An existing thread is bound to its harness: sessions can't move between
528 // provider instances, so the picker only offers the thread's own group.
529 const threadProviderGroups = useMemo(
530 () => providerGroups.filter((group) => group.providerKey === currentModelSelection.instanceId),
531 [providerGroups, currentModelSelection.instanceId],
532 );
533 const currentModelOption =
534 modelOptions.find(
535 (option) =>
536 option.selection.instanceId === currentModelSelection.instanceId &&
537 option.selection.model === currentModelSelection.model,
538 ) ?? null;
539 const providerOptionDescriptors = useMemo(
540 () =>
541 resolveProviderOptionDescriptors({
542 capabilities: currentModelOption?.capabilities,
543 selections: currentModelSelection.options,
544 }),
545 [currentModelOption?.capabilities, currentModelSelection.options],
546 );
547 const settingsOwnerId = composerOwnerKey;
548 const settingsRouteSession = useMemo<ExistingThreadSettingsRouteSession>(
549 () => ({
550 ownerId: settingsOwnerId,
551 environmentId: props.environmentId,
552 providerInstanceId: currentModelSelection.instanceId,
553 providerGroups: threadProviderGroups,
554 selectedModel: currentModelSelection,
555 onSelectModel: (option) => props.onUpdateModelSelection(option.selection),
556 optionDescriptors: providerOptionDescriptors,
557 onUpdateOptionSelections: (options) =>
558 props.onUpdateModelSelection({ ...currentModelSelection, options }),
559 runtimeMode: currentRuntimeMode,
560 onUpdateRuntimeMode: props.onUpdateRuntimeMode,
561 }),
562 [
563 currentModelSelection,
564 currentRuntimeMode,
565 props.onUpdateModelSelection,
566 props.onUpdateRuntimeMode,
567 providerOptionDescriptors,
568 settingsOwnerId,
569 threadProviderGroups,
570 ],
571 );
572 const openSettings = useCallback(() => {
573 settingsRoutePresentation.present(settingsRouteSession);
574 settingsSheetPresentation.open();
575 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.open]);
576
577 useEffect(() => {
578 if (settingsSheetPresentation.isActive) {
579 settingsRoutePresentation.present(settingsRouteSession);
580 }
581 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.isActive]);
582
583 useEffect(() => {
584 if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
585 return;
586 }
587
588 settingsRoutePresentedRef.current = true;
589 navigation.dispatch(StackActions.push("ThreadSettingsSheet"));
590 }, [navigation, settingsSheetPresentation.isVisible]);
591
592 useFocusEffect(
593 useCallback(() => {
594 if (!settingsRoutePresentedRef.current) {
595 return;
596 }
597
598 settingsRoutePresentedRef.current = false;
599 settingsSheetPresentation.onDismissed();
600 settingsRoutePresentation.clear(settingsOwnerId);
601 }, [settingsOwnerId, settingsRoutePresentation.clear, settingsSheetPresentation.onDismissed]),
602 );
603
604 useEffect(
605 () =>
606 // UIKit's completion callback for the sheet dismissal, surfaced by the
607 // native-stack patch. This is when the queued keyboard restore runs.
608 (navigation as unknown as NavigationWithFinishTransitioning).addListener(
609 "finishTransitioning",
610 settingsSheetPresentation.onStackTransitionsFinished,
611 ),
612 [navigation, settingsSheetPresentation.onStackTransitionsFinished],
613 );
614
615 return (
616 <Animated.View
617 className="px-[12px]"
618 style={{
619 paddingTop: isExpanded ? 8 : 6,
620 paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 8 : 6),
621 backgroundColor:
622 Platform.OS === "android" ? themeColorWithAlpha(composerPanel, 1) : undefined,
623 }}
624 >
625 {/* The backdrop gradient lives on a plain View: Reanimated's Animated.View
626 silently drops experimental_backgroundImage on Android, which left this
627 strip fully transparent and the feed text legible through the composer. */}
628 <View
629 className={
630 Platform.OS === "android"
631 ? "hidden"
632 : "absolute inset-0 bg-linear-to-b from-screen/0 via-screen/60 to-screen/90"
633 }
634 pointerEvents="none"
635 />
636 <Animated.View
637 className="relative w-full self-center"
638 style={{ maxWidth: props.contentMaxWidth }}
639 >
640 {!voiceInput.isBusy &&
641 composerMenu.trigger &&
642 (composerMenu.items.length > 0 || composerMenu.trigger.kind === "pull-request") ? (
643 <View className="absolute inset-x-0 bottom-full z-10 mb-2">
644 <ComposerCommandPopover
645 items={composerMenu.items}
646 triggerKind={composerMenu.trigger.kind}
647 isLoading={composerMenu.isLoading}
648 error={composerMenu.error}
649 onSelect={composerMenu.onSelect}
650 />
651 </View>
652 ) : null}
653
654 {modelUnavailable ? (
655 <Pressable accessibilityRole="button" className="px-3 py-2" onPress={openSettings}>
656 <Text className="text-xs text-foreground">Model unavailable. Open model settings.</Text>
657 </Pressable>
658 ) : null}
659
660 <ComposerSurface
661 style={
662 isExpanded
663 ? {
664 borderRadius: 26,
665 minHeight: 140,
666 overflow: "hidden" as const,
667 paddingBottom: 6,
668 paddingTop: 14,
669 }
670 : {
671 // Keep the numeric radius close to the expanded card so the
672 // shape morph stays bounded while rendering as a capsule.
673 borderRadius: 27,
674 overflow: "hidden" as const,
675 paddingVertical: 2,
676 }
677 }
678 >
679 <ComposerDictationDraftContent
680 className={isExpanded ? undefined : "flex-row items-center"}
681 compact={!isExpanded}
682 hidden={showsCompactDictation}
683 >
684 {!isExpanded ? (
685 <ComposerAttachmentButton
686 supportsFiles={Boolean(
687 props.serverConfig?.environment.capabilities.fileAttachments,
688 )}
689 onPickMedia={props.onPickDraftMedia}
690 onPickFiles={props.onPickDraftFiles}
691 />
692 ) : null}
693 {isExpanded && stripAttachments.length > 0 ? (
694 <Animated.View
695 className="px-[14px] pb-2.5"
696 entering={COMPOSER_ATTACHMENT_ENTERING}
697 exiting={FadeOut.duration(120)}
698 >
699 <ComposerAttachmentStrip
700 environmentId={props.environmentId}
701 attachments={stripAttachments}
702 onRemove={voiceInput.isBusy ? () => undefined : props.onRemoveDraftImage}
703 onPressPreview={voiceInput.isBusy ? undefined : onPressPreview}
704 onPressVideo={voiceInput.isBusy ? undefined : onPressVideo}
705 onPressDocument={
706 voiceInput.isBusy
707 ? undefined
708 : (attachment) =>
709 openDraftDocument({
710 attachmentId: attachment.id,
711 name: attachment.name,
712 mimeType: attachment.mimeType,
713 sizeBytes: attachment.sizeBytes,
714 })
715 }
716 />
717 </Animated.View>
718 ) : null}
719 <Animated.View
720 className={isExpanded ? "px-[14px]" : "min-w-0 flex-1 px-[4px]"}
721 layout={COMPOSER_LAYOUT_TRANSITION}
722 >
723 <ComposerEditor
724 draftKey={composerOwnerKey}
725 environmentId={props.environmentId}
726 onOpenMention={(path) => {
727 Keyboard.dismiss();
728 navigation.navigate("ThreadFile", {
729 environmentId: String(props.environmentId),
730 threadId: String(props.selectedThread.id),
731 path: fileRoutePathSegments(path),
732 });
733 }}
734 onOpenAttachment={openDraftDocument}
735 // A rested composer full of chips left almost nowhere to tap to start typing:
736 // every chip opened its file instead. Collapsed, they focus the editor.
737 chipsInert={!isExpanded}
738 onInertChipPress={() => inputRef.current?.focus()}
739 ref={inputRef}
740 multiline
741 value={props.draftMessage}
742 readOnly={voiceInput.freezesEditor}
743 skills={composerMenu.skills}
744 selection={composerMenu.selection}
745 onChangeText={props.onChangeDraftMessage}
746 onSelectionChange={composerMenu.onSelectionChange}
747 onPasteImages={(uris) => void props.onNativePasteImages(uris)}
748 onPasteText={(paste) => {
749 const insertPaste = () => {
750 const insertion = replaceTextSelection({
751 value: paste.value,
752 selection: paste.selection,
753 text: paste.text,
754 });
755 const selection = { start: insertion.cursor, end: insertion.cursor };
756 props.onChangeDraftMessage(insertion.value);
757 composerMenu.onSelectionChange(selection);
758 };
759 const capabilities = props.serverConfig?.environment.capabilities;
760 const advertisedMax =
761 capabilities?.attachmentUploads === true
762 ? capabilities.fileAttachments?.maxUploadBytes
763 : undefined;
764 const maxBytes =
765 advertisedMax === undefined
766 ? null
767 : clampFileAttachmentUploadBytes(advertisedMax);
768 const wouldExceedInputLimit =
769 paste.value.length -
770 Math.max(0, paste.selection.end - paste.selection.start) +
771 paste.text.length >
772 PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
773 const canAttach =
774 maxBytes !== null &&
775 countComposerDraftAttachmentsAfterSelection(composerOwnerKey, {
776 text: paste.value,
777 ...paste.selection,
778 }) < PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
779 new TextEncoder().encode(paste.text).byteLength <= maxBytes;
780 if (
781 pastedTextDisposition({
782 text: paste.text,
783 wouldExceedInputLimit,
784 canAttach: true,
785 }) === "attachment"
786 ) {
787 if (canAttach) {
788 pendingPastedTextAttachmentCountRef.current += 1;
789 setPendingPastedTextAttachmentCount(
790 pendingPastedTextAttachmentCountRef.current,
791 );
792 const finishAttachment = () => {
793 pendingPastedTextAttachmentCountRef.current = Math.max(
794 0,
795 pendingPastedTextAttachmentCountRef.current - 1,
796 );
797 setPendingPastedTextAttachmentCount(
798 pendingPastedTextAttachmentCountRef.current,
799 );
800 };
801 void props.onNativePasteText(paste).then(finishAttachment, finishAttachment);
802 } else if (!wouldExceedInputLimit) {
803 insertPaste();
804 } else {
805 Alert.alert(
806 wouldExceedInputLimit
807 ? "Pasted text is too large for this message"
808 : "Could not attach pasted text",
809 wouldExceedInputLimit
810 ? "Remove some text or an attachment, then paste again."
811 : "Remove an attachment or use a smaller paste, then try again.",
812 );
813 }
814 return;
815 }
816 insertPaste();
817 }}
818 placeholder={props.placeholder}
819 onFocus={handleFocus}
820 onBlur={handleBlur}
821 onSubmit={handleSend}
822 scrollEnabled={isExpanded}
823 // Android: collapsed single line centers natively (gravity) in
824 // a pill-height box matching the send button; iOS keeps insets.
825 singleLineCentered={!isExpanded}
826 contentInsetVertical={isExpanded || Platform.OS === "android" ? 0 : 6}
827 style={
828 isExpanded
829 ? {
830 minHeight: 72,
831 maxHeight: 160,
832 paddingVertical: 4,
833 }
834 : {
835 height: 36,
836 }
837 }
838 textStyle={{
839 ...bodyText,
840 color: foregroundColor,
841 }}
842 />
843 </Animated.View>
844 {!isExpanded && stripAttachments.length > 0 ? (
845 <View className="flex-row gap-1 pl-1">
846 {stripAttachments.slice(0, 3).map((attachment) => (
847 <ComposerAttachmentThumbnail
848 environmentId={props.environmentId}
849 key={attachment.id}
850 attachment={attachment}
851 size={30}
852 borderRadius={8}
853 compact
854 onPressPreview={onPressPreview}
855 onPressVideo={onPressVideo}
856 />
857 ))}
858 {stripAttachments.length > 3 ? (
859 <View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
860 <Text className="text-foreground-muted text-2xs font-t3-bold">
861 +{stripAttachments.length - 3}
862 </Text>
863 </View>
864 ) : null}
865 </View>
866 ) : null}
867 {!isExpanded ? (
868 <View className="flex-row items-center">
869 <ComposerDictationStartAction
870 state={voiceInput.state}
871 isAvailable={voiceInput.isAvailable}
872 onStart={voiceInput.start}
873 onCancel={voiceInput.cancel}
874 />
875 {showStopAction ? (
876 <ComposerActionButton
877 accessibilityLabel="Stop agent"
878 icon="stop.fill"
879 variant="danger"
880 onPress={props.onStopThread}
881 />
882 ) : (
883 <ComposerActionButton
884 accessibilityLabel={sendBlockedReason ?? sendLabel}
885 icon="arrow.up"
886 variant="primary"
887 disabled={!canSend}
888 onPress={handleSend}
889 />
890 )}
891 </View>
892 ) : null}
893 {isExpanded ? <View className="h-1" /> : null}
894 </ComposerDictationDraftContent>
895 <Animated.View
896 accessibilityElementsHidden={!isToolbarVisible}
897 collapsable={false}
898 importantForAccessibility={isToolbarVisible ? "auto" : "no-hide-descendants"}
899 layout={COMPOSER_LAYOUT_TRANSITION}
900 pointerEvents={isToolbarVisible ? "auto" : "none"}
901 style={
902 isExpanded
903 ? undefined
904 : {
905 position: "absolute",
906 bottom: 2,
907 left: 0,
908 right: 0,
909 }
910 }
911 >
912 <ComposerDictationToolbar
913 showsDictation={isVoiceInputPresented}
914 visible={isToolbarVisible}
915 >
916 <ComposerToolbarRow
917 paddingBottom={0}
918 paddingHorizontal={0}
919 paddingTop={0}
920 style={{ gap: 0 }}
921 >
922 <ComposerDictationCancelAction
923 presentation={voicePresentation}
924 onCancel={voiceInput.cancel}
925 />
926 {isVoiceInputPresented ? (
927 <ComposerDictationStatus
928 audioLevels={voiceInput.audioLevels}
929 elapsedSeconds={voiceInput.elapsedSeconds}
930 phase={voiceInput.state.phase}
931 presentation={voicePresentation}
932 onDismissError={voiceInput.cancel}
933 />
934 ) : (
935 <View className="min-w-0 flex-1 flex-row items-center justify-between">
936 <ComposerAttachmentButton
937 supportsFiles={Boolean(
938 props.serverConfig?.environment.capabilities.fileAttachments,
939 )}
940 onPickMedia={props.onPickDraftMedia}
941 onPickFiles={props.onPickDraftFiles}
942 />
943 <View className="min-w-0 shrink">
944 <ComposerInlineControl
945 accessibilityLabel="Model and reasoning settings"
946 emphasized
947 iconNode={
948 <ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
949 }
950 label={currentModelOption?.label ?? currentModelSelection.model}
951 maxWidth="100%"
952 onPress={openSettings}
953 />
954 </View>
955 </View>
956 )}
957 <View className="shrink-0 flex-row items-center">
958 <ComposerDictationPrimaryAction
959 state={voiceInput.state}
960 presentation={voicePresentation}
961 isAvailable={voiceInput.isAvailable}
962 onStart={voiceInput.start}
963 onConfirm={voiceInput.stop}
964 onCancel={voiceInput.cancel}
965 />
966 {showStopAction ? (
967 <ComposerActionButton
968 accessibilityLabel="Stop agent"
969 icon="stop.fill"
970 variant="danger"
971 onPress={props.onStopThread}
972 />
973 ) : voicePresentation.showsSend ? (
974 <ComposerActionButton
975 accessibilityLabel={sendBlockedReason ?? sendLabel}
976 icon="arrow.up"
977 variant="primary"
978 disabled={!canSend}
979 onPress={handleSend}
980 />
981 ) : null}
982 </View>
983 </ComposerToolbarRow>
984 </ComposerDictationToolbar>
985 </Animated.View>
986 </ComposerSurface>
987 </Animated.View>
988
989 <VideoPreviewModal source={previewVideo} onRequestClose={closePreview} />
990 <FilePreviewModal source={previewFile} onRequestClose={closePreview} />
991 </Animated.View>
992 );
993});