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