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