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