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