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 {selectedProviderStatus?.compatibilityAdvisory?.message &&
655 (selectedProviderStatus.compatibilityAdvisory.status === "unsupported" ||
656 selectedProviderStatus.compatibilityAdvisory.status === "broken") ? (
657 <Text
658 accessibilityRole={
659 selectedProviderStatus.compatibilityAdvisory.status === "broken" ? "alert" : undefined
660 }
661 accessibilityLiveRegion={
662 selectedProviderStatus.compatibilityAdvisory.status === "broken"
663 ? "assertive"
664 : "polite"
665 }
666 className="px-3 py-2 text-xs text-foreground"
667 >
668 {selectedProviderStatus.compatibilityAdvisory.message}
669 </Text>
670 ) : null}
671 {modelUnavailable ? (
672 <Pressable accessibilityRole="button" className="px-3 py-2" onPress={openSettings}>
673 <Text className="text-xs text-foreground">Model unavailable. Open model settings.</Text>
674 </Pressable>
675 ) : null}
676
677 <ComposerSurface
678 style={
679 isExpanded
680 ? {
681 borderRadius: 26,
682 minHeight: 140,
683 overflow: "hidden" as const,
684 paddingBottom: 6,
685 paddingTop: 14,
686 }
687 : {
688 // Keep the numeric radius close to the expanded card so the
689 // shape morph stays bounded while rendering as a capsule.
690 borderRadius: 27,
691 overflow: "hidden" as const,
692 paddingVertical: 2,
693 }
694 }
695 >
696 <ComposerDictationDraftContent
697 className={isExpanded ? undefined : "flex-row items-center"}
698 compact={!isExpanded}
699 hidden={showsCompactDictation}
700 >
701 {!isExpanded ? (
702 <ComposerAttachmentButton
703 supportsFiles={Boolean(
704 props.serverConfig?.environment.capabilities.fileAttachments,
705 )}
706 onPickMedia={props.onPickDraftMedia}
707 onPickFiles={props.onPickDraftFiles}
708 />
709 ) : null}
710 {isExpanded && stripAttachments.length > 0 ? (
711 <Animated.View
712 className="px-[14px] pb-2.5"
713 entering={COMPOSER_ATTACHMENT_ENTERING}
714 exiting={FadeOut.duration(120)}
715 >
716 <ComposerAttachmentStrip
717 environmentId={props.environmentId}
718 attachments={stripAttachments}
719 onRemove={voiceInput.isBusy ? () => undefined : props.onRemoveDraftImage}
720 onPressPreview={voiceInput.isBusy ? undefined : onPressPreview}
721 onPressVideo={voiceInput.isBusy ? undefined : onPressVideo}
722 onPressDocument={
723 voiceInput.isBusy
724 ? undefined
725 : (attachment) =>
726 openDraftDocument({
727 attachmentId: attachment.id,
728 name: attachment.name,
729 mimeType: attachment.mimeType,
730 sizeBytes: attachment.sizeBytes,
731 })
732 }
733 />
734 </Animated.View>
735 ) : null}
736 <Animated.View
737 className={isExpanded ? "px-[14px]" : "min-w-0 flex-1 px-[4px]"}
738 layout={COMPOSER_LAYOUT_TRANSITION}
739 >
740 <ComposerEditor
741 draftKey={composerOwnerKey}
742 environmentId={props.environmentId}
743 onOpenMention={(path) => {
744 Keyboard.dismiss();
745 navigation.navigate("ThreadFile", {
746 environmentId: String(props.environmentId),
747 threadId: String(props.selectedThread.id),
748 path: fileRoutePathSegments(path),
749 });
750 }}
751 onOpenAttachment={openDraftDocument}
752 // A rested composer full of chips left almost nowhere to tap to start typing:
753 // every chip opened its file instead. Collapsed, they focus the editor.
754 chipsInert={!isExpanded}
755 onInertChipPress={() => inputRef.current?.focus()}
756 ref={inputRef}
757 multiline
758 value={props.draftMessage}
759 readOnly={voiceInput.freezesEditor}
760 skills={composerMenu.skills}
761 selection={composerMenu.selection}
762 onChangeText={props.onChangeDraftMessage}
763 onSelectionChange={composerMenu.onSelectionChange}
764 onPasteImages={(uris) => void props.onNativePasteImages(uris)}
765 onPasteText={(paste) => {
766 const insertPaste = () => {
767 const insertion = replaceTextSelection({
768 value: paste.value,
769 selection: paste.selection,
770 text: paste.text,
771 });
772 const selection = { start: insertion.cursor, end: insertion.cursor };
773 props.onChangeDraftMessage(insertion.value);
774 composerMenu.onSelectionChange(selection);
775 };
776 const capabilities = props.serverConfig?.environment.capabilities;
777 const advertisedMax =
778 capabilities?.attachmentUploads === true
779 ? capabilities.fileAttachments?.maxUploadBytes
780 : undefined;
781 const maxBytes =
782 advertisedMax === undefined
783 ? null
784 : clampFileAttachmentUploadBytes(advertisedMax);
785 const wouldExceedInputLimit =
786 paste.value.length -
787 Math.max(0, paste.selection.end - paste.selection.start) +
788 paste.text.length >
789 PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
790 const canAttach =
791 maxBytes !== null &&
792 countComposerDraftAttachmentsAfterSelection(composerOwnerKey, {
793 text: paste.value,
794 ...paste.selection,
795 }) < PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
796 new TextEncoder().encode(paste.text).byteLength <= maxBytes;
797 if (
798 pastedTextDisposition({
799 text: paste.text,
800 wouldExceedInputLimit,
801 canAttach: true,
802 }) === "attachment"
803 ) {
804 if (canAttach) {
805 pendingPastedTextAttachmentCountRef.current += 1;
806 setPendingPastedTextAttachmentCount(
807 pendingPastedTextAttachmentCountRef.current,
808 );
809 const finishAttachment = () => {
810 pendingPastedTextAttachmentCountRef.current = Math.max(
811 0,
812 pendingPastedTextAttachmentCountRef.current - 1,
813 );
814 setPendingPastedTextAttachmentCount(
815 pendingPastedTextAttachmentCountRef.current,
816 );
817 };
818 void props.onNativePasteText(paste).then(finishAttachment, finishAttachment);
819 } else if (!wouldExceedInputLimit) {
820 insertPaste();
821 } else {
822 Alert.alert(
823 wouldExceedInputLimit
824 ? "Pasted text is too large for this message"
825 : "Could not attach pasted text",
826 wouldExceedInputLimit
827 ? "Remove some text or an attachment, then paste again."
828 : "Remove an attachment or use a smaller paste, then try again.",
829 );
830 }
831 return;
832 }
833 insertPaste();
834 }}
835 placeholder={props.placeholder}
836 onFocus={handleFocus}
837 onBlur={handleBlur}
838 onSubmit={handleSend}
839 scrollEnabled={isExpanded}
840 // Android: collapsed single line centers natively (gravity) in
841 // a pill-height box matching the send button; iOS keeps insets.
842 singleLineCentered={!isExpanded}
843 contentInsetVertical={isExpanded || Platform.OS === "android" ? 0 : 6}
844 style={
845 isExpanded
846 ? {
847 minHeight: 72,
848 maxHeight: 160,
849 paddingVertical: 4,
850 }
851 : {
852 height: 36,
853 }
854 }
855 textStyle={{
856 ...bodyText,
857 color: foregroundColor,
858 }}
859 />
860 </Animated.View>
861 {!isExpanded && stripAttachments.length > 0 ? (
862 <View className="flex-row gap-1 pl-1">
863 {stripAttachments.slice(0, 3).map((attachment) => (
864 <ComposerAttachmentThumbnail
865 environmentId={props.environmentId}
866 key={attachment.id}
867 attachment={attachment}
868 size={30}
869 borderRadius={8}
870 compact
871 onPressPreview={onPressPreview}
872 onPressVideo={onPressVideo}
873 />
874 ))}
875 {stripAttachments.length > 3 ? (
876 <View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
877 <Text className="text-foreground-muted text-2xs font-t3-bold">
878 +{stripAttachments.length - 3}
879 </Text>
880 </View>
881 ) : null}
882 </View>
883 ) : null}
884 {!isExpanded ? (
885 <View className="flex-row items-center">
886 <ComposerDictationStartAction
887 state={voiceInput.state}
888 isAvailable={voiceInput.isAvailable}
889 onStart={voiceInput.start}
890 onCancel={voiceInput.cancel}
891 />
892 {showStopAction ? (
893 <ComposerActionButton
894 accessibilityLabel="Stop agent"
895 icon="stop.fill"
896 variant="danger"
897 onPress={props.onStopThread}
898 />
899 ) : (
900 <ComposerActionButton
901 accessibilityLabel={sendBlockedReason ?? sendLabel}
902 icon="arrow.up"
903 variant="primary"
904 disabled={!canSend}
905 onPress={handleSend}
906 />
907 )}
908 </View>
909 ) : null}
910 {isExpanded ? <View className="h-1" /> : null}
911 </ComposerDictationDraftContent>
912 <Animated.View
913 accessibilityElementsHidden={!isToolbarVisible}
914 collapsable={false}
915 importantForAccessibility={isToolbarVisible ? "auto" : "no-hide-descendants"}
916 layout={COMPOSER_LAYOUT_TRANSITION}
917 pointerEvents={isToolbarVisible ? "auto" : "none"}
918 style={
919 isExpanded
920 ? undefined
921 : {
922 position: "absolute",
923 bottom: 2,
924 left: 0,
925 right: 0,
926 }
927 }
928 >
929 <ComposerDictationToolbar
930 showsDictation={isVoiceInputPresented}
931 visible={isToolbarVisible}
932 >
933 <ComposerToolbarRow
934 paddingBottom={0}
935 paddingHorizontal={0}
936 paddingTop={0}
937 style={{ gap: 0 }}
938 >
939 <ComposerDictationCancelAction
940 presentation={voicePresentation}
941 onCancel={voiceInput.cancel}
942 />
943 {isVoiceInputPresented ? (
944 <ComposerDictationStatus
945 audioLevels={voiceInput.audioLevels}
946 elapsedSeconds={voiceInput.elapsedSeconds}
947 phase={voiceInput.state.phase}
948 presentation={voicePresentation}
949 onDismissError={voiceInput.cancel}
950 />
951 ) : (
952 <View className="min-w-0 flex-1 flex-row items-center justify-between">
953 <ComposerAttachmentButton
954 supportsFiles={Boolean(
955 props.serverConfig?.environment.capabilities.fileAttachments,
956 )}
957 onPickMedia={props.onPickDraftMedia}
958 onPickFiles={props.onPickDraftFiles}
959 />
960 <View className="min-w-0 shrink">
961 <ComposerInlineControl
962 accessibilityLabel="Model and reasoning settings"
963 emphasized
964 renderIcon={(size) => (
965 <ProviderIcon provider={currentModelOption?.providerDriver} size={size} />
966 )}
967 label={currentModelOption?.label ?? currentModelSelection.model}
968 maxWidth="100%"
969 onPress={openSettings}
970 />
971 </View>
972 </View>
973 )}
974 <View className="shrink-0 flex-row items-center">
975 <ComposerDictationPrimaryAction
976 state={voiceInput.state}
977 presentation={voicePresentation}
978 isAvailable={voiceInput.isAvailable}
979 onStart={voiceInput.start}
980 onConfirm={voiceInput.stop}
981 onCancel={voiceInput.cancel}
982 />
983 {showStopAction ? (
984 <ComposerActionButton
985 accessibilityLabel="Stop agent"
986 icon="stop.fill"
987 variant="danger"
988 onPress={props.onStopThread}
989 />
990 ) : voicePresentation.showsSend ? (
991 <ComposerActionButton
992 accessibilityLabel={sendBlockedReason ?? sendLabel}
993 icon="arrow.up"
994 variant="primary"
995 disabled={!canSend}
996 onPress={handleSend}
997 />
998 ) : null}
999 </View>
1000 </ComposerToolbarRow>
1001 </ComposerDictationToolbar>
1002 </Animated.View>
1003 </ComposerSurface>
1004 </Animated.View>
1005
1006 <VideoPreviewModal source={previewVideo} onRequestClose={closePreview} />
1007 <FilePreviewModal source={previewFile} onRequestClose={closePreview} />
1008 </Animated.View>
1009 );
1010});