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