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={colors["--color-composer-surface"]}
348 fallbackClassName="border border-composer-border"
349 glassEffectStyle="regular"
350 // The composer is a passive material containing interactive controls.
351 // Keep native glass out of the interactive content's layout path.
352 pointerEvents="none"
353 tintColor="transparent"
354 layout={layoutTransition}
355 style={[{ position: "absolute", inset: 0 }, animatedShapeStyle]}
356 >
357 {null}
358 </AnimatedGlassSurface>
359 <Animated.View
360 collapsable={false}
361 layout={layoutTransition}
362 style={[props.style, animatedShapeStyle]}
363 >
364 {props.children}
365 </Animated.View>
366 </Animated.View>
367 );
368}
369
370export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) {
371 const project = useProject(scopeProjectRef(props.environmentId, props.selectedThread.projectId));
372 const { themeVariables: materialTheme } = useAppearancePreferences();
373 const composerPanel = materialTheme["--color-composer-panel"];
374 const navigation = useNavigation();
375 const foregroundColor = useUniwindTheme()["--color-foreground"];
376 const bodyText = useScaledTextRole("body");
377 const fallbackInputRef = useRef<ComposerEditorHandle>(null);
378 const inputRef = props.editorRef ?? fallbackInputRef;
379 const [isFocused, setIsFocused] = useState(false);
380 const pendingPastedTextAttachmentCountRef = useRef(0);
381 const [pendingPastedTextAttachmentCount, setPendingPastedTextAttachmentCount] = useState(0);
382 const settingsSheetPresentation = useThreadSettingsSheetPresentation({
383 editorRef: inputRef,
384 isEditorFocused: isFocused,
385 });
386 const settingsRoutePresentation = useExistingThreadSettingsRoutePresentation();
387 const settingsRoutePresentedRef = useRef(false);
388 const wasExpandedBeforePreviewRef = useRef(false);
389 const inFlightThreadIdsRef = useRef(new Set<string>());
390 const { onExpandedChange } = props;
391
392 const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
393 const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);
394 const queuedEdit = props.queuedEdit ?? null;
395 const hasContent =
396 props.draftMessage.trim().length > 0 ||
397 props.draftAttachments.length > 0 ||
398 (queuedEdit?.existingAttachments.length ?? 0) > 0;
399 // Only media belongs above the composer; every other file reads as its inline chip.
400 const stripAttachments = useMemo(
401 () => composerStripAttachments(props.draftAttachments),
402 [props.draftAttachments],
403 );
404 // Stopping the agent is not what the send button means in edit mode.
405 const showStopAction = !hasContent && props.canStopThread && queuedEdit === null;
406
407 const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
408 const attachmentsUploading =
409 props.connectionState === "connected" &&
410 composerAttachmentsStillUploading({
411 environmentId: props.environmentId,
412 attachments: props.draftAttachments,
413 serverConfig: props.serverConfig,
414 states: uploadStates,
415 });
416 // Every send goes through the outbox; the label says whether it leaves now
417 // or waits (for the connection, an earlier queued message, or an upload).
418 const sendPresentation = resolveComposerSendPresentation({
419 editingQueuedMessage: queuedEdit !== null,
420 running: props.activeThreadBusy,
421 canSteer: props.canSteerActiveTurn,
422 followUpBehavior: props.followUpBehavior,
423 deliveryDeferred:
424 props.connectionState !== "connected" || props.queueCount > 0 || attachmentsUploading,
425 });
426 const sendLabel = sendPresentation.label;
427 const currentModelSelection = props.selectedThread.modelSelection;
428 const currentRuntimeMode = props.selectedThread.runtimeMode;
429 const modelUnavailable =
430 props.connectionState === "connected" &&
431 isModelSelectionUnavailable(props.serverConfig, currentModelSelection);
432 const selectedProviderStatus = useMemo(() => {
433 if (!props.serverConfig) return null;
434 return (
435 props.serverConfig.providers.find(
436 (p) => p.instanceId === props.selectedThread.modelSelection.instanceId,
437 ) ?? null
438 );
439 }, [props.serverConfig, props.selectedThread.modelSelection.instanceId]);
440 const composerOwnerKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
441 // Content lives under the edit's own draft while a queued message is open;
442 // the owner key still identifies this composer for settings and dictation.
443 const composerDraftKey = props.draftKey ?? composerOwnerKey;
444 const openDraftDocument = (attachment: ComposerDocumentAttachment) => {
445 Keyboard.dismiss();
446 navigation.navigate("ThreadAttachment", {
447 environmentId: String(props.environmentId),
448 threadId: String(props.selectedThread.id),
449 attachmentId: attachment.attachmentId,
450 name: attachment.name,
451 mimeType: attachment.mimeType,
452 sizeBytes: String(attachment.sizeBytes),
453 draftKey: composerDraftKey,
454 });
455 };
456 const { onSendMessage, onChangeDraftMessage, onShowUsageLimits } = props;
457 // T3 owns /usage-limits only where Limits has data for the selected provider;
458 // elsewhere the name stays the provider's own and is sent through untouched.
459 const usageLimitsOffered =
460 selectedProviderStatus !== null &&
461 hasProviderUsageLimits(
462 selectedProviderStatus.driver,
463 props.serverConfig?.providers ?? [],
464 props.serverConfig?.usageLimitSources ?? [],
465 );
466 // Answered locally from the last Limits snapshot; the agent never sees it.
467 const openUsageLimits = useCallback(() => {
468 const report = collectProviderUsageLimits(
469 currentModelSelection.instanceId,
470 props.serverConfig?.providers ?? [],
471 props.serverConfig?.usageLimitSources ?? [],
472 Date.now(),
473 );
474 onShowUsageLimits(report);
475 if (!report) {
476 Alert.alert("Usage limits unavailable", "This provider does not currently report limits.");
477 }
478 return report !== null;
479 }, [currentModelSelection.instanceId, onShowUsageLimits, props.serverConfig]);
480
481 const composerMenu = useComposerCommandMenu({
482 draftMessage: props.draftMessage,
483 ownerKey: composerOwnerKey,
484 environmentId: props.environmentId,
485 threadShells: useThreadShells(),
486 currentThreadId: props.selectedThread.id,
487 projectCwd: props.projectCwd,
488 pullRequestProjectId: props.serverConfig?.environment.capabilities.pullRequests
489 ? (project?.id ?? null)
490 : null,
491 pullRequestRepository: project?.repositoryIdentity?.displayName ?? null,
492 selectedProviderStatus,
493 hasThread: true,
494 hasCompactableConversation: props.hasCompactableConversation,
495 onChangeDraftMessage: props.onChangeDraftMessage,
496 onUpdateInteractionMode:
497 selectedProviderStatus?.showInteractionModeToggle === false
498 ? undefined
499 : props.onUpdateInteractionMode,
500 offersUsageLimits: usageLimitsOffered,
501 // With attachments aboard the pick just inserts the text, so it sends as a prompt.
502 onUsageLimits:
503 usageLimitsOffered && props.draftAttachments.length === 0 ? openUsageLimits : undefined,
504 });
505 const voiceInput = useVoiceInputController({
506 ownerKey: composerOwnerKey,
507 draftMessage: props.draftMessage,
508 selection: composerMenu.selection,
509 onChangeDraftMessage: props.onChangeDraftMessage,
510 onChangeSelection: composerMenu.onSelectionChange,
511 });
512 const voicePresentation = resolveVoiceComposerPresentation(
513 voiceInput.state,
514 voiceInput.elapsedSeconds,
515 );
516 const isVoiceInputPresented = voicePresentation.statusLabel !== null;
517 // An open draft stays visible; only a collapsed composer becomes a voice strip.
518 const isExpanded = isFocused || settingsSheetPresentation.keepsComposerExpanded;
519 const showsCompactDictation = isVoiceInputPresented && !isExpanded;
520 const isToolbarVisible = isExpanded || isVoiceInputPresented;
521 const attachmentBlockReason = composerAttachmentUploadBlockReason({
522 environmentId: props.environmentId,
523 attachments: props.draftAttachments,
524 connected: props.connectionState === "connected",
525 serverConfig: props.serverConfig,
526 states: uploadStates,
527 });
528 const contextImports = useAtomValue(composerContextImportsAtom);
529 const sendBlockedReason =
530 (queuedEdit?.saving === true ? "Saving…" : null) ??
531 props.sendBlockedReason ??
532 (pendingPastedTextAttachmentCount > 0 ? "Attaching pasted text" : null) ??
533 attachmentBlockReason;
534 const canSend =
535 hasContent &&
536 !contextImports[composerDraftKey] &&
537 !voiceInput.blocksSubmission &&
538 sendBlockedReason === null &&
539 !modelUnavailable;
540
541 // Keep the feed inset aligned with the card or compact dictation strip.
542 useEffect(() => {
543 onExpandedChange?.(isExpanded);
544 }, [isExpanded, onExpandedChange]);
545
546 const onPressPreview = useCallback(
547 (source: FilePreviewSource) => {
548 wasExpandedBeforePreviewRef.current = isFocused;
549 setPreviewVideo(null);
550 setPreviewFile((current) => current ?? source);
551 },
552 [isFocused],
553 );
554
555 const closePreview = useCallback(() => {
556 setPreviewFile(null);
557 setPreviewVideo(null);
558 if (wasExpandedBeforePreviewRef.current) {
559 setTimeout(() => {
560 if (navigation.isFocused()) inputRef.current?.focus();
561 }, 100);
562 }
563 }, [inputRef, navigation]);
564
565 const onPressVideo = useCallback(
566 (attachment: DraftComposerFileAttachment, sourceIdentifier: string) => {
567 wasExpandedBeforePreviewRef.current = isFocused;
568 setPreviewFile(null);
569 setPreviewVideo((current) => current ?? { type: "local", attachment, sourceIdentifier });
570 },
571 [isFocused],
572 );
573
574 const onEditorFocusChange = props.onEditorFocusChange;
575 const handleFocus = useCallback(() => {
576 setIsFocused(true);
577 onExpandedChange?.(true);
578 onEditorFocusChange?.(true);
579 }, [onEditorFocusChange, onExpandedChange]);
580
581 const handleBlur = useCallback(() => {
582 setIsFocused(false);
583 if (!settingsSheetPresentation.keepsComposerExpanded) {
584 onExpandedChange?.(false);
585 }
586 onEditorFocusChange?.(false);
587 }, [onEditorFocusChange, onExpandedChange, settingsSheetPresentation.keepsComposerExpanded]);
588 const handleSend = useCallback(
589 async (followUp?: ActiveTurnComposerAction) => {
590 if (voiceInput.blocksSubmission || pendingPastedTextAttachmentCountRef.current > 0) return;
591 // Typed out in full rather than picked from the menu. Attachments mean the
592 // user is sending a prompt, so those go through as usual.
593 if (
594 usageLimitsOffered &&
595 isUsageLimitsCommand(props.draftMessage) &&
596 props.draftAttachments.length === 0
597 ) {
598 if (openUsageLimits()) onChangeDraftMessage("");
599 return;
600 }
601 const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
602 if (inFlightThreadIdsRef.current.has(threadKey)) return;
603 inFlightThreadIdsRef.current.add(threadKey);
604 try {
605 const messageId = await onSendMessage(followUp);
606 if (messageId === null) {
607 return;
608 }
609 // Sending a prompt starts agent work: arm the lock-screen card while the
610 // app is foregrounded and the activity token can be registered. Armed
611 // after the send so its preference read and native Activity start don't
612 // contend with the queued-message feedback on the tap frame.
613 armAgentAwarenessLiveActivityForLocalWork({
614 environmentId: props.environmentId,
615 threadTitle: props.selectedThread.title,
616 projectTitle: props.environmentLabel ?? "T3 Code",
617 });
618 } finally {
619 inFlightThreadIdsRef.current.delete(threadKey);
620 }
621 },
622 [
623 props.draftMessage,
624 props.draftAttachments.length,
625 onChangeDraftMessage,
626 openUsageLimits,
627 usageLimitsOffered,
628 onSendMessage,
629 props.environmentId,
630 props.environmentLabel,
631 props.selectedThread.id,
632 props.selectedThread.title,
633 voiceInput.blocksSubmission,
634 ],
635 );
636
637 // ── Model menu ───────────────────────────────────────────
638 // A session that hands the conversation to another provider lets the picker
639 // offer the whole catalog; one that can't stays on its own instance.
640 const lockedProviderInstanceId = props.canSwitchProvider
641 ? undefined
642 : currentModelSelection.instanceId;
643 const modelOptions = useMemo(
644 () => buildModelOptions(props.serverConfig, currentModelSelection, lockedProviderInstanceId),
645 [props.serverConfig, currentModelSelection, lockedProviderInstanceId],
646 );
647 const threadProviderGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
648 const currentModelOption =
649 modelOptions.find(
650 (option) =>
651 option.selection.instanceId === currentModelSelection.instanceId &&
652 option.selection.model === currentModelSelection.model,
653 ) ?? null;
654 const providerOptionDescriptors = useMemo(
655 () =>
656 resolveProviderOptionDescriptors({
657 capabilities: currentModelOption?.capabilities,
658 selections: currentModelSelection.options,
659 }),
660 [currentModelOption?.capabilities, currentModelSelection.options],
661 );
662 const settingsOwnerId = composerOwnerKey;
663 const settingsRouteSession = useMemo<ExistingThreadSettingsRouteSession>(
664 () => ({
665 ownerId: settingsOwnerId,
666 environmentId: props.environmentId,
667 providerInstanceId: currentModelSelection.instanceId,
668 providerGroups: threadProviderGroups,
669 selectedModel: currentModelSelection,
670 onSelectModel: (option) =>
671 props.onUpdateModelSelection(withRememberedModelOptions(option.selection)),
672 optionDescriptors: providerOptionDescriptors,
673 onUpdateOptionSelections: (options) => {
674 rememberModelOptions(
675 currentModelSelection.instanceId,
676 currentModelSelection.model,
677 options ?? [],
678 );
679 props.onUpdateModelSelection({ ...currentModelSelection, options });
680 },
681 runtimeMode: currentRuntimeMode,
682 onUpdateRuntimeMode: props.onUpdateRuntimeMode,
683 }),
684 [
685 currentModelSelection,
686 currentRuntimeMode,
687 props.onUpdateModelSelection,
688 props.onUpdateRuntimeMode,
689 providerOptionDescriptors,
690 settingsOwnerId,
691 threadProviderGroups,
692 ],
693 );
694 const openSettings = useCallback(() => {
695 settingsRoutePresentation.present(settingsRouteSession);
696 settingsSheetPresentation.open();
697 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.open]);
698
699 useEffect(() => {
700 if (settingsSheetPresentation.isActive) {
701 settingsRoutePresentation.present(settingsRouteSession);
702 }
703 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.isActive]);
704
705 useEffect(() => {
706 if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
707 return;
708 }
709
710 settingsRoutePresentedRef.current = true;
711 navigation.dispatch(StackActions.push("ThreadSettingsSheet"));
712 }, [navigation, settingsSheetPresentation.isVisible]);
713
714 useFocusEffect(
715 useCallback(() => {
716 if (!settingsRoutePresentedRef.current) {
717 return;
718 }
719
720 settingsRoutePresentedRef.current = false;
721 settingsSheetPresentation.onDismissed();
722 settingsRoutePresentation.clear(settingsOwnerId);
723 }, [settingsOwnerId, settingsRoutePresentation.clear, settingsSheetPresentation.onDismissed]),
724 );
725
726 useEffect(
727 () =>
728 // UIKit's completion callback for the sheet dismissal, surfaced by the
729 // native-stack patch. This is when the queued keyboard restore runs.
730 (navigation as unknown as NavigationWithFinishTransitioning).addListener(
731 "finishTransitioning",
732 settingsSheetPresentation.onStackTransitionsFinished,
733 ),
734 [navigation, settingsSheetPresentation.onStackTransitionsFinished],
735 );
736
737 return (
738 <Animated.View
739 className="px-[12px]"
740 style={{
741 paddingTop: isExpanded ? 8 : 6,
742 paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 8 : 6),
743 backgroundColor:
744 Platform.OS === "android" ? themeColorWithAlpha(composerPanel, 1) : undefined,
745 }}
746 >
747 {/* The backdrop gradient lives on a plain View: Reanimated's Animated.View
748 silently drops experimental_backgroundImage on Android, which left this
749 strip fully transparent and the feed text legible through the composer. */}
750 <View
751 className={
752 Platform.OS === "android"
753 ? "hidden"
754 : "absolute inset-0 bg-linear-to-b from-screen/0 via-screen/60 to-screen/90"
755 }
756 pointerEvents="none"
757 />
758 <Animated.View
759 className="relative w-full self-center"
760 style={{ maxWidth: props.contentMaxWidth }}
761 >
762 {!voiceInput.isBusy &&
763 composerMenu.trigger &&
764 (composerMenu.items.length > 0 || composerMenu.trigger.kind === "pull-request") ? (
765 <View className="absolute inset-x-0 bottom-full z-10 mb-2">
766 <ComposerCommandPopover
767 items={composerMenu.items}
768 triggerKind={composerMenu.trigger.kind}
769 isLoading={composerMenu.isLoading}
770 error={composerMenu.error}
771 onSelect={composerMenu.onSelect}
772 />
773 </View>
774 ) : null}
775
776 {selectedProviderStatus?.compatibilityAdvisory?.message &&
777 (selectedProviderStatus.compatibilityAdvisory.status === "unsupported" ||
778 selectedProviderStatus.compatibilityAdvisory.status === "broken") ? (
779 <Text
780 accessibilityRole={
781 selectedProviderStatus.compatibilityAdvisory.status === "broken" ? "alert" : undefined
782 }
783 accessibilityLiveRegion={
784 selectedProviderStatus.compatibilityAdvisory.status === "broken"
785 ? "assertive"
786 : "polite"
787 }
788 className="px-3 py-2 text-xs text-foreground"
789 >
790 {selectedProviderStatus.compatibilityAdvisory.message}
791 </Text>
792 ) : null}
793 {modelUnavailable ? (
794 <Pressable accessibilityRole="button" className="px-3 py-2" onPress={openSettings}>
795 <Text className="text-xs text-foreground">Model unavailable. Open model settings.</Text>
796 </Pressable>
797 ) : null}
798
799 <ComposerSurface
800 style={
801 isExpanded
802 ? {
803 borderRadius: 26,
804 minHeight: 140,
805 overflow: "hidden" as const,
806 paddingBottom: 6,
807 paddingTop: 14,
808 }
809 : {
810 // Keep the numeric radius close to the expanded card so the
811 // shape morph stays bounded while rendering as a capsule.
812 borderRadius: 27,
813 overflow: "hidden" as const,
814 paddingVertical: 2,
815 }
816 }
817 >
818 <ComposerDictationDraftContent
819 className={isExpanded ? undefined : "flex-row items-center"}
820 compact={!isExpanded}
821 hidden={showsCompactDictation}
822 >
823 {!isExpanded ? (
824 <ComposerAttachmentButton
825 supportsFiles={Boolean(
826 props.serverConfig?.environment.capabilities.fileAttachments,
827 )}
828 onPickMedia={props.onPickDraftMedia}
829 onPickFiles={props.onPickDraftFiles}
830 />
831 ) : null}
832 {isExpanded && queuedEdit !== null && queuedEdit.existingAttachments.length > 0 ? (
833 <Animated.View
834 className="px-[14px] pb-2.5"
835 entering={COMPOSER_ATTACHMENT_ENTERING}
836 exiting={FadeOut.duration(120)}
837 >
838 <ComposerQueuedEditAttachments
839 environmentId={props.environmentId}
840 attachments={queuedEdit.existingAttachments}
841 disabled={queuedEdit.saving || voiceInput.isBusy}
842 onRemove={queuedEdit.onRemoveExistingAttachment}
843 />
844 </Animated.View>
845 ) : null}
846 {isExpanded && stripAttachments.length > 0 ? (
847 <Animated.View
848 className="px-[14px] pb-2.5"
849 entering={COMPOSER_ATTACHMENT_ENTERING}
850 exiting={FadeOut.duration(120)}
851 >
852 <ComposerAttachmentStrip
853 environmentId={props.environmentId}
854 attachments={stripAttachments}
855 onRemove={voiceInput.isBusy ? () => undefined : props.onRemoveDraftImage}
856 onPressPreview={voiceInput.isBusy ? undefined : onPressPreview}
857 onPressVideo={voiceInput.isBusy ? undefined : onPressVideo}
858 onPressDocument={
859 voiceInput.isBusy
860 ? undefined
861 : (attachment) =>
862 openDraftDocument({
863 attachmentId: attachment.id,
864 name: attachment.name,
865 mimeType: attachment.mimeType,
866 sizeBytes: attachment.sizeBytes,
867 })
868 }
869 />
870 </Animated.View>
871 ) : null}
872 <Animated.View
873 className={isExpanded ? "px-[14px]" : "min-w-0 flex-1 px-[4px]"}
874 layout={COMPOSER_LAYOUT_TRANSITION}
875 >
876 <ComposerEditor
877 draftKey={composerDraftKey}
878 environmentId={props.environmentId}
879 onOpenMention={(path) => {
880 Keyboard.dismiss();
881 navigation.navigate("ThreadFile", {
882 environmentId: String(props.environmentId),
883 threadId: String(props.selectedThread.id),
884 path: fileRoutePathSegments(path),
885 });
886 }}
887 onOpenAttachment={openDraftDocument}
888 // A rested composer full of chips left almost nowhere to tap to start typing:
889 // every chip opened its file instead. Collapsed, they focus the editor.
890 chipsInert={!isExpanded}
891 onInertChipPress={() => inputRef.current?.focus()}
892 ref={inputRef}
893 multiline
894 value={props.draftMessage}
895 readOnly={voiceInput.freezesEditor}
896 skills={composerMenu.skills}
897 selection={composerMenu.selection}
898 onChangeText={props.onChangeDraftMessage}
899 onSelectionChange={composerMenu.onSelectionChange}
900 onPasteImages={(uris) => void props.onNativePasteImages(uris)}
901 onPasteText={(paste) => {
902 const insertPaste = () => {
903 const insertion = replaceTextSelection({
904 value: paste.value,
905 selection: paste.selection,
906 text: paste.text,
907 });
908 const selection = { start: insertion.cursor, end: insertion.cursor };
909 props.onChangeDraftMessage(insertion.value);
910 composerMenu.onSelectionChange(selection);
911 };
912 const capabilities = props.serverConfig?.environment.capabilities;
913 const advertisedMax =
914 capabilities?.attachmentUploads === true
915 ? capabilities.fileAttachments?.maxUploadBytes
916 : undefined;
917 const maxBytes =
918 advertisedMax === undefined
919 ? null
920 : clampFileAttachmentUploadBytes(advertisedMax);
921 const wouldExceedInputLimit =
922 paste.value.length -
923 Math.max(0, paste.selection.end - paste.selection.start) +
924 paste.text.length >
925 PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
926 const canAttach =
927 maxBytes !== null &&
928 countComposerDraftAttachmentsAfterSelection(composerDraftKey, {
929 text: paste.value,
930 ...paste.selection,
931 }) < PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
932 new TextEncoder().encode(paste.text).byteLength <= maxBytes;
933 if (
934 pastedTextDisposition({
935 text: paste.text,
936 wouldExceedInputLimit,
937 canAttach: true,
938 }) === "attachment"
939 ) {
940 if (canAttach) {
941 pendingPastedTextAttachmentCountRef.current += 1;
942 setPendingPastedTextAttachmentCount(
943 pendingPastedTextAttachmentCountRef.current,
944 );
945 const finishAttachment = () => {
946 pendingPastedTextAttachmentCountRef.current = Math.max(
947 0,
948 pendingPastedTextAttachmentCountRef.current - 1,
949 );
950 setPendingPastedTextAttachmentCount(
951 pendingPastedTextAttachmentCountRef.current,
952 );
953 };
954 void props.onNativePasteText(paste).then(finishAttachment, finishAttachment);
955 } else if (!wouldExceedInputLimit) {
956 insertPaste();
957 } else {
958 Alert.alert(
959 wouldExceedInputLimit
960 ? "Pasted text is too large for this message"
961 : "Could not attach pasted text",
962 wouldExceedInputLimit
963 ? "Remove some text or an attachment, then paste again."
964 : "Remove an attachment or use a smaller paste, then try again.",
965 );
966 }
967 return;
968 }
969 insertPaste();
970 }}
971 placeholder={props.placeholder}
972 onFocus={handleFocus}
973 onBlur={handleBlur}
974 // Command-Return sends the other way, matching web's Mod+Enter.
975 onSubmit={(alternate) =>
976 void handleSend(
977 alternate && sendPresentation.alternate !== null
978 ? sendPresentation.alternate
979 : undefined,
980 )
981 }
982 submitTitle={sendPresentation.label}
983 alternateSubmitTitle={
984 sendPresentation.alternate === null
985 ? sendPresentation.label
986 : FOLLOW_UP_ACTION_LABEL[sendPresentation.alternate]
987 }
988 scrollEnabled={isExpanded}
989 // Android: collapsed single line centers natively (gravity) in
990 // a pill-height box matching the send button; iOS keeps insets.
991 singleLineCentered={!isExpanded}
992 contentInsetVertical={isExpanded || Platform.OS === "android" ? 0 : 6}
993 style={
994 isExpanded
995 ? {
996 minHeight: 72,
997 maxHeight: 160,
998 paddingVertical: 4,
999 }
1000 : {
1001 height: 36,
1002 }
1003 }
1004 textStyle={{
1005 ...bodyText,
1006 color: foregroundColor,
1007 }}
1008 />
1009 </Animated.View>
1010 {!isExpanded && stripAttachments.length > 0 ? (
1011 <View className="flex-row gap-1 pl-1">
1012 {stripAttachments.slice(0, 3).map((attachment) => (
1013 <ComposerAttachmentThumbnail
1014 environmentId={props.environmentId}
1015 key={attachment.id}
1016 attachment={attachment}
1017 size={30}
1018 borderRadius={8}
1019 compact
1020 onPressPreview={onPressPreview}
1021 onPressVideo={onPressVideo}
1022 />
1023 ))}
1024 {stripAttachments.length > 3 ? (
1025 <View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
1026 <Text className="text-foreground-muted text-2xs font-t3-bold">
1027 +{stripAttachments.length - 3}
1028 </Text>
1029 </View>
1030 ) : null}
1031 </View>
1032 ) : null}
1033 {!isExpanded ? (
1034 <View className="flex-row items-center">
1035 <ComposerDictationStartAction
1036 state={voiceInput.state}
1037 isAvailable={voiceInput.isAvailable}
1038 onStart={voiceInput.start}
1039 onCancel={voiceInput.cancel}
1040 />
1041 {showStopAction ? (
1042 <ComposerActionButton
1043 accessibilityLabel="Stop agent"
1044 icon="stop.fill"
1045 variant="danger"
1046 onPress={props.onStopThread}
1047 />
1048 ) : (
1049 <SendActionButton
1050 accessibilityLabel={sendBlockedReason ?? sendLabel}
1051 presentation={sendPresentation}
1052 disabled={!canSend}
1053 onSend={handleSend}
1054 />
1055 )}
1056 </View>
1057 ) : null}
1058 {isExpanded ? <View className="h-1" /> : null}
1059 </ComposerDictationDraftContent>
1060 <Animated.View
1061 accessibilityElementsHidden={!isToolbarVisible}
1062 collapsable={false}
1063 importantForAccessibility={isToolbarVisible ? "auto" : "no-hide-descendants"}
1064 layout={COMPOSER_LAYOUT_TRANSITION}
1065 pointerEvents={isToolbarVisible ? "auto" : "none"}
1066 style={
1067 isExpanded
1068 ? undefined
1069 : {
1070 position: "absolute",
1071 bottom: 2,
1072 left: 0,
1073 right: 0,
1074 }
1075 }
1076 >
1077 <ComposerDictationToolbar
1078 showsDictation={isVoiceInputPresented}
1079 visible={isToolbarVisible}
1080 >
1081 <ComposerToolbarRow
1082 paddingBottom={0}
1083 paddingHorizontal={0}
1084 paddingTop={0}
1085 style={{ gap: 0 }}
1086 >
1087 <ComposerDictationCancelAction
1088 presentation={voicePresentation}
1089 onCancel={voiceInput.cancel}
1090 />
1091 {isVoiceInputPresented ? (
1092 <ComposerDictationStatus
1093 audioLevels={voiceInput.audioLevels}
1094 elapsedSeconds={voiceInput.elapsedSeconds}
1095 phase={voiceInput.state.phase}
1096 presentation={voicePresentation}
1097 onDismissError={voiceInput.cancel}
1098 />
1099 ) : (
1100 <View className="min-w-0 flex-1 flex-row items-center justify-between">
1101 <ComposerAttachmentButton
1102 supportsFiles={Boolean(
1103 props.serverConfig?.environment.capabilities.fileAttachments,
1104 )}
1105 onPickMedia={props.onPickDraftMedia}
1106 onPickFiles={props.onPickDraftFiles}
1107 />
1108 <View className="min-w-0 shrink">
1109 <ComposerInlineControl
1110 accessibilityLabel="Model and reasoning settings"
1111 emphasized
1112 iconNode={
1113 <ProviderIcon
1114 iconUrl={currentModelOption?.providerIconUrl}
1115 provider={currentModelOption?.providerDriver}
1116 size={16}
1117 />
1118 }
1119 label={currentModelOption?.label ?? currentModelSelection.model}
1120 maxWidth="100%"
1121 onPress={openSettings}
1122 />
1123 </View>
1124 </View>
1125 )}
1126 <View className="shrink-0 flex-row items-center">
1127 <ComposerDictationPrimaryAction
1128 state={voiceInput.state}
1129 presentation={voicePresentation}
1130 isAvailable={voiceInput.isAvailable}
1131 onStart={voiceInput.start}
1132 onConfirm={voiceInput.stop}
1133 onCancel={voiceInput.cancel}
1134 />
1135 {showStopAction ? (
1136 <ComposerActionButton
1137 accessibilityLabel="Stop agent"
1138 icon="stop.fill"
1139 variant="danger"
1140 onPress={props.onStopThread}
1141 />
1142 ) : voicePresentation.showsSend ? (
1143 <SendActionButton
1144 accessibilityLabel={sendBlockedReason ?? sendLabel}
1145 presentation={sendPresentation}
1146 disabled={!canSend}
1147 onSend={handleSend}
1148 />
1149 ) : null}
1150 </View>
1151 </ComposerToolbarRow>
1152 </ComposerDictationToolbar>
1153 </Animated.View>
1154 </ComposerSurface>
1155 </Animated.View>
1156
1157 <VideoPreviewModal source={previewVideo} onRequestClose={closePreview} />
1158 <FilePreviewModal source={previewFile} onRequestClose={closePreview} />
1159 </Animated.View>
1160 );
1161});