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