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