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 {modelUnavailable ? (
777 <Pressable accessibilityRole="button" className="px-3 py-2" onPress={openSettings}>
778 <Text className="text-xs text-foreground">Model unavailable. Open model settings.</Text>
779 </Pressable>
780 ) : null}
781
782 <ComposerSurface
783 style={
784 isExpanded
785 ? {
786 borderRadius: 26,
787 minHeight: 140,
788 overflow: "hidden" as const,
789 paddingBottom: 6,
790 paddingTop: 14,
791 }
792 : {
793 // Keep the numeric radius close to the expanded card so the
794 // shape morph stays bounded while rendering as a capsule.
795 borderRadius: 27,
796 overflow: "hidden" as const,
797 paddingVertical: 2,
798 }
799 }
800 >
801 <ComposerDictationDraftContent
802 className={isExpanded ? undefined : "flex-row items-center"}
803 compact={!isExpanded}
804 hidden={showsCompactDictation}
805 >
806 {!isExpanded ? (
807 <ComposerAttachmentButton
808 supportsFiles={Boolean(
809 props.serverConfig?.environment.capabilities.fileAttachments,
810 )}
811 onPickMedia={props.onPickDraftMedia}
812 onPickFiles={props.onPickDraftFiles}
813 />
814 ) : null}
815 {isExpanded && queuedEdit !== null && queuedEdit.existingAttachments.length > 0 ? (
816 <Animated.View
817 className="px-[14px] pb-2.5"
818 entering={COMPOSER_ATTACHMENT_ENTERING}
819 exiting={FadeOut.duration(120)}
820 >
821 <ComposerQueuedEditAttachments
822 environmentId={props.environmentId}
823 attachments={queuedEdit.existingAttachments}
824 disabled={queuedEdit.saving || voiceInput.isBusy}
825 onRemove={queuedEdit.onRemoveExistingAttachment}
826 />
827 </Animated.View>
828 ) : null}
829 {isExpanded && stripAttachments.length > 0 ? (
830 <Animated.View
831 className="px-[14px] pb-2.5"
832 entering={COMPOSER_ATTACHMENT_ENTERING}
833 exiting={FadeOut.duration(120)}
834 >
835 <ComposerAttachmentStrip
836 environmentId={props.environmentId}
837 attachments={stripAttachments}
838 onRemove={voiceInput.isBusy ? () => undefined : props.onRemoveDraftImage}
839 onPressPreview={voiceInput.isBusy ? undefined : onPressPreview}
840 onPressVideo={voiceInput.isBusy ? undefined : onPressVideo}
841 onPressDocument={
842 voiceInput.isBusy
843 ? undefined
844 : (attachment) =>
845 openDraftDocument({
846 attachmentId: attachment.id,
847 name: attachment.name,
848 mimeType: attachment.mimeType,
849 sizeBytes: attachment.sizeBytes,
850 })
851 }
852 />
853 </Animated.View>
854 ) : null}
855 <Animated.View
856 className={isExpanded ? "px-[14px]" : "min-w-0 flex-1 px-[4px]"}
857 layout={COMPOSER_LAYOUT_TRANSITION}
858 >
859 <ComposerEditor
860 draftKey={composerDraftKey}
861 environmentId={props.environmentId}
862 onOpenMention={(path) => {
863 Keyboard.dismiss();
864 navigation.navigate("ThreadFile", {
865 environmentId: String(props.environmentId),
866 threadId: String(props.selectedThread.id),
867 path: fileRoutePathSegments(path),
868 });
869 }}
870 onOpenAttachment={openDraftDocument}
871 // A rested composer full of chips left almost nowhere to tap to start typing:
872 // every chip opened its file instead. Collapsed, they focus the editor.
873 chipsInert={!isExpanded}
874 onInertChipPress={() => inputRef.current?.focus()}
875 ref={inputRef}
876 multiline
877 value={props.draftMessage}
878 readOnly={voiceInput.freezesEditor}
879 skills={composerMenu.skills}
880 selection={composerMenu.selection}
881 onChangeText={props.onChangeDraftMessage}
882 onSelectionChange={composerMenu.onSelectionChange}
883 onPasteImages={(uris) => void props.onNativePasteImages(uris)}
884 onPasteText={(paste) => {
885 const insertPaste = () => {
886 const insertion = replaceTextSelection({
887 value: paste.value,
888 selection: paste.selection,
889 text: paste.text,
890 });
891 const selection = { start: insertion.cursor, end: insertion.cursor };
892 props.onChangeDraftMessage(insertion.value);
893 composerMenu.onSelectionChange(selection);
894 };
895 const capabilities = props.serverConfig?.environment.capabilities;
896 const advertisedMax =
897 capabilities?.attachmentUploads === true
898 ? capabilities.fileAttachments?.maxUploadBytes
899 : undefined;
900 const maxBytes =
901 advertisedMax === undefined
902 ? null
903 : clampFileAttachmentUploadBytes(advertisedMax);
904 const wouldExceedInputLimit =
905 paste.value.length -
906 Math.max(0, paste.selection.end - paste.selection.start) +
907 paste.text.length >
908 PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
909 const canAttach =
910 maxBytes !== null &&
911 countComposerDraftAttachmentsAfterSelection(composerDraftKey, {
912 text: paste.value,
913 ...paste.selection,
914 }) < PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
915 new TextEncoder().encode(paste.text).byteLength <= maxBytes;
916 if (
917 pastedTextDisposition({
918 text: paste.text,
919 wouldExceedInputLimit,
920 canAttach: true,
921 }) === "attachment"
922 ) {
923 if (canAttach) {
924 pendingPastedTextAttachmentCountRef.current += 1;
925 setPendingPastedTextAttachmentCount(
926 pendingPastedTextAttachmentCountRef.current,
927 );
928 const finishAttachment = () => {
929 pendingPastedTextAttachmentCountRef.current = Math.max(
930 0,
931 pendingPastedTextAttachmentCountRef.current - 1,
932 );
933 setPendingPastedTextAttachmentCount(
934 pendingPastedTextAttachmentCountRef.current,
935 );
936 };
937 void props.onNativePasteText(paste).then(finishAttachment, finishAttachment);
938 } else if (!wouldExceedInputLimit) {
939 insertPaste();
940 } else {
941 Alert.alert(
942 wouldExceedInputLimit
943 ? "Pasted text is too large for this message"
944 : "Could not attach pasted text",
945 wouldExceedInputLimit
946 ? "Remove some text or an attachment, then paste again."
947 : "Remove an attachment or use a smaller paste, then try again.",
948 );
949 }
950 return;
951 }
952 insertPaste();
953 }}
954 placeholder={props.placeholder}
955 onFocus={handleFocus}
956 onBlur={handleBlur}
957 // Command-Return sends the other way, matching web's Mod+Enter.
958 onSubmit={(alternate) =>
959 void handleSend(
960 alternate && sendPresentation.alternate !== null
961 ? sendPresentation.alternate
962 : undefined,
963 )
964 }
965 submitTitle={sendPresentation.label}
966 alternateSubmitTitle={
967 sendPresentation.alternate === null
968 ? sendPresentation.label
969 : FOLLOW_UP_ACTION_LABEL[sendPresentation.alternate]
970 }
971 scrollEnabled={isExpanded}
972 // Android: collapsed single line centers natively (gravity) in
973 // a pill-height box matching the send button; iOS keeps insets.
974 singleLineCentered={!isExpanded}
975 contentInsetVertical={isExpanded || Platform.OS === "android" ? 0 : 6}
976 style={
977 isExpanded
978 ? {
979 minHeight: 72,
980 maxHeight: 160,
981 paddingVertical: 4,
982 }
983 : {
984 height: 36,
985 }
986 }
987 textStyle={{
988 ...bodyText,
989 color: foregroundColor,
990 }}
991 />
992 </Animated.View>
993 {!isExpanded && stripAttachments.length > 0 ? (
994 <View className="flex-row gap-1 pl-1">
995 {stripAttachments.slice(0, 3).map((attachment) => (
996 <ComposerAttachmentThumbnail
997 environmentId={props.environmentId}
998 key={attachment.id}
999 attachment={attachment}
1000 size={30}
1001 borderRadius={8}
1002 compact
1003 onPressPreview={onPressPreview}
1004 onPressVideo={onPressVideo}
1005 />
1006 ))}
1007 {stripAttachments.length > 3 ? (
1008 <View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
1009 <Text className="text-foreground-muted text-2xs font-t3-bold">
1010 +{stripAttachments.length - 3}
1011 </Text>
1012 </View>
1013 ) : null}
1014 </View>
1015 ) : null}
1016 {!isExpanded ? (
1017 <View className="flex-row items-center">
1018 <ComposerDictationStartAction
1019 state={voiceInput.state}
1020 isAvailable={voiceInput.isAvailable}
1021 onStart={voiceInput.start}
1022 onCancel={voiceInput.cancel}
1023 />
1024 {showStopAction ? (
1025 <ComposerActionButton
1026 accessibilityLabel="Stop agent"
1027 icon="stop.fill"
1028 variant="danger"
1029 onPress={props.onStopThread}
1030 />
1031 ) : (
1032 <SendActionButton
1033 accessibilityLabel={sendBlockedReason ?? sendLabel}
1034 presentation={sendPresentation}
1035 disabled={!canSend}
1036 onSend={handleSend}
1037 />
1038 )}
1039 </View>
1040 ) : null}
1041 {isExpanded ? <View className="h-1" /> : null}
1042 </ComposerDictationDraftContent>
1043 <Animated.View
1044 accessibilityElementsHidden={!isToolbarVisible}
1045 collapsable={false}
1046 importantForAccessibility={isToolbarVisible ? "auto" : "no-hide-descendants"}
1047 layout={COMPOSER_LAYOUT_TRANSITION}
1048 pointerEvents={isToolbarVisible ? "auto" : "none"}
1049 style={
1050 isExpanded
1051 ? undefined
1052 : {
1053 position: "absolute",
1054 bottom: 2,
1055 left: 0,
1056 right: 0,
1057 }
1058 }
1059 >
1060 <ComposerDictationToolbar
1061 showsDictation={isVoiceInputPresented}
1062 visible={isToolbarVisible}
1063 >
1064 <ComposerToolbarRow
1065 paddingBottom={0}
1066 paddingHorizontal={0}
1067 paddingTop={0}
1068 style={{ gap: 0 }}
1069 >
1070 <ComposerDictationCancelAction
1071 presentation={voicePresentation}
1072 onCancel={voiceInput.cancel}
1073 />
1074 {isVoiceInputPresented ? (
1075 <ComposerDictationStatus
1076 audioLevels={voiceInput.audioLevels}
1077 elapsedSeconds={voiceInput.elapsedSeconds}
1078 phase={voiceInput.state.phase}
1079 presentation={voicePresentation}
1080 onDismissError={voiceInput.cancel}
1081 />
1082 ) : (
1083 <View className="min-w-0 flex-1 flex-row items-center justify-between">
1084 <ComposerAttachmentButton
1085 supportsFiles={Boolean(
1086 props.serverConfig?.environment.capabilities.fileAttachments,
1087 )}
1088 onPickMedia={props.onPickDraftMedia}
1089 onPickFiles={props.onPickDraftFiles}
1090 />
1091 <View className="min-w-0 shrink">
1092 <ComposerInlineControl
1093 accessibilityLabel="Model and reasoning settings"
1094 emphasized
1095 iconNode={
1096 <ProviderIcon
1097 iconUrl={currentModelOption?.providerIconUrl}
1098 provider={currentModelOption?.providerDriver}
1099 size={16}
1100 />
1101 }
1102 label={currentModelOption?.label ?? currentModelSelection.model}
1103 maxWidth="100%"
1104 onPress={openSettings}
1105 />
1106 </View>
1107 </View>
1108 )}
1109 <View className="shrink-0 flex-row items-center">
1110 <ComposerDictationPrimaryAction
1111 state={voiceInput.state}
1112 presentation={voicePresentation}
1113 isAvailable={voiceInput.isAvailable}
1114 onStart={voiceInput.start}
1115 onConfirm={voiceInput.stop}
1116 onCancel={voiceInput.cancel}
1117 />
1118 {showStopAction ? (
1119 <ComposerActionButton
1120 accessibilityLabel="Stop agent"
1121 icon="stop.fill"
1122 variant="danger"
1123 onPress={props.onStopThread}
1124 />
1125 ) : voicePresentation.showsSend ? (
1126 <SendActionButton
1127 accessibilityLabel={sendBlockedReason ?? sendLabel}
1128 presentation={sendPresentation}
1129 disabled={!canSend}
1130 onSend={handleSend}
1131 />
1132 ) : null}
1133 </View>
1134 </ComposerToolbarRow>
1135 </ComposerDictationToolbar>
1136 </Animated.View>
1137 </ComposerSurface>
1138 </Animated.View>
1139
1140 <VideoPreviewModal source={previewVideo} onRequestClose={closePreview} />
1141 <FilePreviewModal source={previewFile} onRequestClose={closePreview} />
1142 </Animated.View>
1143 );
1144});