Open History to see the last commit
1import { useSidebarWorkspaceTabs } from "../layout/workspace/useSystemWorkspaceTabBar";
2import { Button } from "../../components/ui/Button";
3import * as Dialog from "../../components/ui/Dialog";
4import type { ComposerTextPaste } from "../../native/T3ComposerEditor.types";
5import { useDeviceType } from "../../native/native-layout-metrics";
6import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
7import {
8 useAppearancePreferences,
9 useAndroidFloatingTabs,
10} from "../settings/appearance/AppearancePreferencesProvider";
11import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
12import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
13import { AsyncResult } from "effect/reactivity";
14import { useAtomValue } from "@effect/atom-react";
15import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
16import { pastedTextDisposition, replaceTextSelection } from "@t3tools/client-runtime/text-paste";
17import {
18 AuthOrchestrationOperateScope,
19 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
20 PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
21 type ChatAttachment,
22 type EnvironmentId,
23 type MessageId,
24 type ModelSelection,
25 type ServerConfig as T3ServerConfig,
26 type UsageLimitsReport,
27} from "@t3tools/contracts";
28import {
29 collectProviderUsageLimits,
30 hasProviderUsageLimits,
31 isUsageLimitsCommand,
32} from "@t3tools/shared/usageLimits";
33import { parseSideChatCommand } from "@t3tools/shared/composerTrigger";
34import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";
35import type { ReactNode } from "react";
36import { useEffect, useEffectEvent, useRef, useState, type RefObject } from "react";
37import { I18nManager, Keyboard, Platform, View, type ViewStyle } from "react-native";
38import { composerImageGallery } from "../../lib/composerImageGallery";
39import { filePreviewGallery } from "../../lib/filePreviewGallery";
40import { FilePreviewModal, type FilePreviewSource } from "../../components/ui/FilePreviewModal";
41import {
42 composerAttachmentUploadBlockReason,
43 composerAttachmentsStillUploading,
44 composerAttachmentUploadsAtom,
45} from "../../state/composer-attachment-uploads";
46import Animated, {
47 FadeIn,
48 FadeOut,
49 type LayoutAnimationFunction,
50 ReduceMotion,
51 useAnimatedStyle,
52 useDerivedValue,
53 useSharedValue,
54 withTiming,
55} from "react-native-reanimated";
56import { useUniwindTheme } from "../../lib/useUniwindTheme";
57import { themeColorWithAlpha } from "../../lib/mobileTheme";
58import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
59import { scopedThreadKey } from "../../lib/scopedEntities";
60import {
61 getComposerDraftSnapshot,
62 setComposerDraftText,
63 composerContextImportsAtom,
64 countComposerDraftAttachmentsAfterSelection,
65 useComposerDraft,
66} from "../../state/use-composer-drafts";
67import type { ComposerDocumentAttachment } from "../../lib/composerContext";
68import { useProject, useVisibleThreadShells } from "../../state/entities";
69import { useMentionableEnvironments } from "../../state/environments";
70import { useLinkedEnvironments } from "../../state/peerLinks";
71import { useEnvironmentScopeDenied } from "../../state/session";
72import { scopeProjectRef } from "@t3tools/client-runtime/environment";
73
74import { AppText as Text } from "../../components/ui/AppText";
75import { ComposerAttachmentButton } from "./ComposerAttachmentButton";
76import {
77 ComposerAttachmentStrip,
78 ComposerAttachmentThumbnail,
79} from "../../components/ComposerAttachmentStrip";
80import { VideoPreviewModal, type VideoPreviewSource } from "../../components/ui/VideoPreviewModal";
81import { GlassSurface } from "../../components/ui/GlassSurface";
82import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
83import { fileRoutePathSegments } from "../files/filePath";
84import {
85 ComposerActionButton,
86 ComposerInlineControl,
87 ComposerToolbarRow,
88} from "../../components/ComposerToolbar";
89import { formatTokens } from "@t3tools/shared/usageFormat";
90import { ComposerModelControl } from "../../components/ComposerModelControl";
91import {
92 composerStripAttachments,
93 type DraftComposerFileAttachment,
94} from "../../lib/composerImages";
95import {
96 buildModelOptions,
97 isModelSelectionUnavailable,
98 serverConfigForCwd,
99} from "../../lib/modelOptions";
100import { useComposerTextRole, type ScaledTextRole } from "../settings/appearance/useScaledTextRole";
101import type { RemoteClientConnectionState } from "../../lib/connection";
102import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
103import { Menu } from "../../components/ui/Menu";
104import type { ActiveTurnComposerAction } from "@t3tools/client-runtime/state/composer-dispatch";
105import type { FollowUpBehavior } from "../../lib/followUpBehavior";
106import {
107 resolveComposerSendPresentation,
108 type ComposerSendPresentation,
109} from "./composerSendPresentation";
110import { compactEditorInsets } from "./compactEditorInsets";
111import { ComposerCommandPopover } from "./ComposerCommandPopover";
112import { ComposerPopoverAnchor } from "./ComposerPopoverAnchor";
113import { ComposerQueuedEditAttachments } from "./ComposerQueuedEdit";
114import { useComposerCommandMenu } from "./use-composer-command-menu";
115import type { ComposerEnvironmentCandidate } from "@t3tools/client-runtime/composerThreadItems";
116import { offersLinkedEnvironments } from "@t3tools/client-runtime/link-request";
117import {
118 ComposerDictationCancelAction,
119 ComposerDictationDraftContent,
120 ComposerDictationError,
121 ComposerDictationPrimaryAction,
122 ComposerDictationStartAction,
123 ComposerDictationStatus,
124 ComposerDictationToolbar,
125} from "../voice-input/ComposerDictationControl";
126import { useVoiceInputController } from "../voice-input/useVoiceInputController";
127import { resolveVoiceComposerPresentation } from "../voice-input/voiceInputPresentation";
128import type { ExistingThreadSettingsRouteParams } from "./ThreadSettingsSheet";
129import {
130 useThreadSettingsSheetPresentation,
131 type NavigationWithFinishTransitioning,
132} from "./use-thread-settings-sheet-presentation";
133
134export const COMPOSER_COLLAPSED_CHROME = 60;
135
136const NO_MACHINES: ReadonlyArray<ComposerEnvironmentCandidate> = [];
137const COLLAPSED_EDITOR_DEFAULT_INSET = 6;
138// iOS puts line-height slack above glyphs. DM Sans's lowercase midline is
139// descender (0.31em) + half x-height (0.504em) above the line bottom.
140const LOWERCASE_MIDLINE_EM = 0.562;
141
142function lowercaseMidline(text: ScaledTextRole): number {
143 return text.lineHeight - LOWERCASE_MIDLINE_EM * text.fontSize;
144}
145
146function collapsedEditorInset(text: ScaledTextRole): number {
147 const shift = lowercaseMidline(text) - lowercaseMidline(MOBILE_TYPOGRAPHY.body);
148 return Math.max(0, Math.round(COLLAPSED_EDITOR_DEFAULT_INSET - shift));
149}
150
151const EXPANDED_EDITOR_INSET = 14;
152// Room under the expanded editor for the toolbar row.
153const EXPANDED_EDITOR_BOTTOM = 52;
154
155function useCompactComposerEditor(text: ScaledTextRole, value: string, animate: boolean) {
156 const [contentSize, setContentSize] = useState({ width: 0, height: 0 });
157 const [compactWidth, setCompactWidth] = useState(0);
158 const contentHeight = contentSize.height;
159 const rowWidth = useSharedValue(0);
160 const editorX = useSharedValue(0);
161 const editorWidth = useSharedValue(0);
162 const inset =
163 Platform.OS === "android" ? COLLAPSED_EDITOR_DEFAULT_INSET : collapsedEditorInset(text);
164 const minimum = Math.max(INLINE_EDITOR_HEIGHT, Math.ceil(text.lineHeight) + 2 * inset);
165 const height = Math.max(
166 minimum,
167 Math.min(text.lineHeight * 4 + 2 * inset, contentHeight + 2 * inset),
168 );
169 // A line that fits the expanded editor may still overflow its compact slot.
170 // Compare its measured width too so widening cannot trigger a collapse loop.
171 const isExpanded =
172 value.length > 0 &&
173 (contentHeight > text.lineHeight * 1.5 ||
174 (compactWidth > 0 && contentSize.width > compactWidth));
175 const compactRowHeight = Math.max(44, minimum);
176 const compactBottom = (compactRowHeight - minimum) / 2;
177 const isRTL = I18nManager.isRTL;
178 const expandedRowHeight = height + EXPANDED_EDITOR_BOTTOM;
179 const expansion = useDerivedValue(() => {
180 const target = isExpanded ? 1 : 0;
181 return animate
182 ? withTiming(target, {
183 duration: COMPOSER_TRANSITION_DURATION_MS,
184 reduceMotion: ReduceMotion.System,
185 })
186 : target;
187 });
188 const editorStyle = useAnimatedStyle(() => {
189 const compactInsets = compactEditorInsets({
190 slotX: editorX.value,
191 slotWidth: editorWidth.value,
192 rowWidth: rowWidth.value,
193 isRTL,
194 });
195 const progress = expansion.value;
196 // Hanging from the row top lets the text ride the growing edge and ignore the stale
197 // height measured while it still wrapped in the compact slot. Layout props only:
198 // Reanimated applies transforms frames ahead of layout, which tore the text from its frame.
199 return {
200 position: "absolute",
201 overflow: "hidden",
202 // The compact slot is unknown until its first layout, so the editor would draw over the + button.
203 opacity: isExpanded || editorWidth.value > 0 ? 1 : 0,
204 height,
205 top: compactBottom * (1 - progress),
206 left: compactInsets.left + (EXPANDED_EDITOR_INSET - compactInsets.left) * progress,
207 // Snapping the far edge keeps the line from rewrapping while the near edge moves.
208 right: isExpanded ? EXPANDED_EDITOR_INSET : compactInsets.right,
209 };
210 });
211 const containerStyle = useAnimatedStyle(() => ({
212 height: compactRowHeight + (expandedRowHeight - compactRowHeight) * expansion.value,
213 }));
214 return {
215 isExpanded,
216 containerStyle,
217 // The expanded toolbar takes the row the text is leaving; reveal it once the text has lifted.
218 // An entering animation hides it from its first frame, which a shared-value opacity cannot.
219 toolbarControlsEntering:
220 animate && isExpanded
221 ? FadeIn.delay(COMPOSER_TRANSITION_DURATION_MS / 2)
222 .duration(COMPOSER_TRANSITION_DURATION_MS / 2)
223 .reduceMotion(ReduceMotion.System)
224 : undefined,
225 editorStyle,
226 onRowLayout: (event: { nativeEvent: { layout: { width: number } } }) => {
227 rowWidth.set(event.nativeEvent.layout.width);
228 },
229 onEditorLayout: (event: { nativeEvent: { layout: { x: number; width: number } } }) => {
230 // The expanded toolbar gives this slot to the model control. Keep the
231 // compact geometry for the return transition, rather than recording zero.
232 if (!isExpanded) {
233 editorX.set(event.nativeEvent.layout.x);
234 editorWidth.set(event.nativeEvent.layout.width);
235 setCompactWidth(Math.max(0, event.nativeEvent.layout.width - 8));
236 }
237 },
238 editorProps: {
239 singleLineCentered: !isExpanded,
240 scrollEnabled: Platform.OS === "android" || contentHeight >= text.lineHeight * 4,
241 contentInsetVertical: inset,
242 onContentSizeChange: (size: { width: number; height: number }) => {
243 setContentSize(size);
244 },
245 style: { flex: 1 },
246 },
247 };
248}
249
250export interface ThreadComposerProps {
251 readonly isDraft?: boolean;
252 readonly canOperateThread: boolean;
253 readonly placeholder: string;
254 readonly contentMaxWidth?: number;
255 readonly draftControls?: ReactNode;
256 readonly bottomInset?: number;
257 readonly connectionState: RemoteClientConnectionState;
258 readonly environmentLabel: string | null;
259 readonly selectedThread: EnvironmentThreadShell;
260 readonly reportedModelSelection?: ModelSelection | null;
261 readonly hasCompactableConversation: boolean;
262 /** Set while the next send compacts the thread first. */
263 readonly compactBeforeSend?: {
264 readonly tokens: number;
265 readonly keepFullHistory: boolean;
266 readonly toggleKeepFullHistory: () => void;
267 } | null;
268 /** Arms a fresh session for the next message; absent where `/clear` is unavailable. */
269 readonly onFreshSession?: () => void;
270 readonly offersSideChat?: boolean;
271 readonly serverConfig: T3ServerConfig | null;
272 readonly queueCount: number;
273 readonly activeThreadBusy: boolean;
274 /** Sending declines a pending approval and redirects the agent, so `/side` is plain text. */
275 readonly redirectsApproval: boolean;
276 readonly canStopThread: boolean;
277 readonly environmentId: EnvironmentId;
278 readonly projectCwd: string | null;
279 readonly sendBlockedReason?: string | null;
280 readonly interactionLocked?: boolean;
281 readonly draftKey?: string;
282 readonly queuedEdit?: {
283 readonly existingAttachments: ReadonlyArray<ChatAttachment>;
284 readonly saving: boolean;
285 readonly onRemoveExistingAttachment: (attachmentId: string) => void;
286 } | null;
287 readonly followUpBehavior: FollowUpBehavior;
288 readonly canSteerActiveTurn: boolean;
289 readonly hidden: boolean;
290 readonly editorRef?: RefObject<ComposerEditorHandle | null>;
291 readonly onChangeDraftMessage: (value: string) => void;
292 readonly onPickDraftMedia: () => Promise<void>;
293 readonly onPickDraftFiles: () => Promise<void>;
294 readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
295 readonly onNativePasteText: (paste: ComposerTextPaste) => Promise<void>;
296 readonly onRemoveDraftImage: (imageId: string) => void;
297 readonly onStopThread: () => void;
298 /** Present while the thread's queue is held. */
299 readonly onResumeQueue: (() => Promise<void>) | null;
300 /** `stillSendable` reports whether the draft is unchanged after any wait before sending. */
301 readonly onSendMessage: (
302 followUp?: ActiveTurnComposerAction,
303 stillSendable?: () => boolean,
304 ) => Promise<MessageId | null>;
305 readonly onShowUsageLimits: (report: UsageLimitsReport | null) => void;
306 readonly canSwitchProvider: boolean;
307 readonly onHeightChange?: (height: number) => void;
308 readonly onEditorFocusChange?: (focused: boolean) => void;
309}
310
311// Android KeyboardStickyView tracks the IME; concurrent timed layout morphs cause jitter.
312const COMPOSER_TRANSITION_DURATION_MS = 220;
313// Side panes animate dock width; nested horizontal transitions would make the surface trail the toolbar.
314const composerHeightTransition: LayoutAnimationFunction = (values) => {
315 "worklet";
316 const timing = {
317 duration: COMPOSER_TRANSITION_DURATION_MS,
318 reduceMotion: ReduceMotion.System,
319 };
320 return {
321 initialValues: {
322 originX: values.targetOriginX,
323 originY: values.currentOriginY,
324 width: values.targetWidth,
325 height: values.currentHeight,
326 },
327 animations: {
328 originX: values.targetOriginX,
329 originY: withTiming(values.targetOriginY, timing),
330 width: values.targetWidth,
331 height: withTiming(values.targetHeight, timing),
332 },
333 };
334};
335const COMPOSER_LAYOUT_TRANSITION = Platform.OS === "android" ? undefined : composerHeightTransition;
336// Share of the one-row composer the draft keeps; a long model name truncates first.
337const INLINE_EDITOR_MIN_WIDTH = "40%";
338const INLINE_EDITOR_HEIGHT = 36;
339
340const COMPOSER_ATTACHMENT_ENTERING =
341 Platform.OS === "android"
342 ? FadeIn.duration(160)
343 : FadeIn.delay(COMPOSER_TRANSITION_DURATION_MS).duration(160).reduceMotion(ReduceMotion.System);
344
345const AnimatedGlassSurface = Animated.createAnimatedComponent(GlassSurface);
346
347const FOLLOW_UP_ACTION_LABEL = {
348 queue: "Queue",
349 steer: "Steer now",
350 restart: "Restart turn",
351} as const;
352
353const FOLLOW_UP_ACTION_SUBTITLE = {
354 queue: "Run after the current turn",
355 steer: "Interrupt what the agent is doing",
356 restart: "Start the turn over with this message",
357} as const;
358
359function SendActionButton(props: {
360 readonly size?: "regular" | "large";
361 readonly accessibilityLabel: string;
362 readonly presentation: ComposerSendPresentation;
363 readonly disabled: boolean;
364 readonly onSend: (followUp?: ActiveTurnComposerAction) => void;
365}) {
366 const { presentation } = props;
367 const button = (
368 <ComposerActionButton
369 accessibilityLabel={props.accessibilityLabel}
370 size={props.size}
371 icon={presentation.icon}
372 variant="primary"
373 disabled={props.disabled}
374 onPress={() => props.onSend()}
375 />
376 );
377 if (!presentation.offersFollowUpChoice || presentation.action === null || props.disabled) {
378 return button;
379 }
380 const actions = [presentation.action, presentation.alternate].filter(
381 (action): action is ActiveTurnComposerAction => action !== null,
382 );
383 return (
384 <Menu
385 accessibilityLabel="Choose how to send this message"
386 shouldOpenOnLongPress
387 actions={actions.map((action) => ({
388 id: action,
389 title: FOLLOW_UP_ACTION_LABEL[action],
390 subtitle: FOLLOW_UP_ACTION_SUBTITLE[action],
391 state: action === presentation.action ? ("on" as const) : ("off" as const),
392 }))}
393 onPressAction={({ nativeEvent }) =>
394 props.onSend(nativeEvent.event as ActiveTurnComposerAction)
395 }
396 >
397 {button}
398 </Menu>
399 );
400}
401
402function ComposerSurface(props: {
403 readonly children: ReactNode;
404 readonly style: ViewStyle;
405 readonly animateLayout?: boolean;
406}) {
407 const colors = useUniwindTheme();
408 const targetBorderRadius =
409 typeof props.style.borderRadius === "number" ? props.style.borderRadius : 0;
410 const shouldAnimate = props.animateLayout !== false && Platform.OS !== "android";
411 const animatedBorderRadius = useDerivedValue(() =>
412 shouldAnimate
413 ? withTiming(targetBorderRadius, {
414 duration: COMPOSER_TRANSITION_DURATION_MS,
415 reduceMotion: ReduceMotion.System,
416 })
417 : targetBorderRadius,
418 );
419 const borderCurve = props.style.borderCurve;
420 const animatedShapeStyle = useAnimatedStyle(() => ({
421 borderRadius: animatedBorderRadius.value,
422 ...(borderCurve ? { borderCurve } : {}),
423 }));
424 const layoutTransition = shouldAnimate ? COMPOSER_LAYOUT_TRANSITION : undefined;
425
426 // Animate every native frame or glass and content jump to final height inside the clip.
427 return (
428 <Animated.View
429 className={
430 Platform.OS === "android" ? undefined : "shadow-[0_6px_28px] shadow-adaptive-black-a15-a35"
431 }
432 layout={layoutTransition}
433 style={[
434 animatedShapeStyle,
435 {
436 overflow: "hidden",
437 },
438 ]}
439 >
440 <AnimatedGlassSurface
441 chrome="none"
442 fallbackColor={colors["--color-composer-surface"]}
443 fallbackClassName="border border-composer-border"
444 glassEffectStyle="regular"
445 pointerEvents="none"
446 tintColor="transparent"
447 layout={layoutTransition}
448 style={[{ position: "absolute", inset: 0 }, animatedShapeStyle]}
449 >
450 {null}
451 </AnimatedGlassSurface>
452 <Animated.View
453 collapsable={false}
454 layout={layoutTransition}
455 style={[props.style, animatedShapeStyle]}
456 >
457 {props.children}
458 </Animated.View>
459 </Animated.View>
460 );
461}
462
463/** Space below the composer pill, inside the bottom inset it is given. */
464export const THREAD_COMPOSER_BOTTOM_GUTTER = 6;
465
466export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps) {
467 const project = useProject(scopeProjectRef(props.environmentId, props.selectedThread.projectId));
468 const { themeVariables: materialTheme } = useAppearancePreferences();
469 const composerPanel = materialTheme["--color-composer-panel"];
470 const navigation = useNavigation();
471 const foregroundColor = useUniwindTheme()["--color-foreground"];
472 const bodyText = useComposerTextRole();
473 const fallbackInputRef = useRef<ComposerEditorHandle>(null);
474 const inputRef = props.editorRef ?? fallbackInputRef;
475 const [isFocused, setIsFocused] = useState(false);
476 const pendingPastedTextAttachmentCountRef = useRef(0);
477 const pendingNativeImagePasteCountRef = useRef(0);
478 const [pendingPastedTextAttachmentCount, setPendingPastedTextAttachmentCount] = useState(0);
479 const settingsRoutePresentedRef = useRef(false);
480 const settingsSheetPresentation = useThreadSettingsSheetPresentation({
481 editorRef: inputRef,
482 onPresent: () => {
483 if (settingsRoutePresentedRef.current) return;
484 settingsRoutePresentedRef.current = true;
485 // The draft composer edits the new-task flow, which owns its own settings route.
486 navigation.dispatch(
487 props.isDraft
488 ? StackActions.push("NewTaskThreadSettings")
489 : StackActions.push("ThreadSettingsSheet", {
490 environmentId: props.environmentId,
491 threadId: props.selectedThread.id,
492 draftKey: composerDraftKey,
493 } satisfies ExistingThreadSettingsRouteParams),
494 );
495 },
496 });
497 const disposeSettingsSheetPresentation = useEffectEvent(settingsSheetPresentation.dispose);
498 const wasExpandedBeforePreviewRef = useRef(false);
499 const inFlightThreadIdsRef = useRef(new Set<string>());
500
501 const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
502 const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);
503 const composerOwnerKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
504 const composerDraftKey = props.draftKey ?? composerOwnerKey;
505 const { text: draftMessage, attachments: draftAttachments } = useComposerDraft(composerDraftKey);
506 const queuedEdit = props.queuedEdit ?? null;
507 const hasContent =
508 draftMessage.trim().length > 0 ||
509 draftAttachments.length > 0 ||
510 (queuedEdit?.existingAttachments.length ?? 0) > 0;
511 const stripAttachments = composerStripAttachments(draftAttachments);
512 const showStopAction = !hasContent && props.canStopThread && queuedEdit === null;
513 const onResumeQueue = props.onResumeQueue;
514 const [resumingQueue, setResumingQueue] = useState(false);
515 const showResumeAction =
516 !hasContent && !showStopAction && queuedEdit === null && onResumeQueue !== null;
517 const handleResumeQueue = async () => {
518 if (resumingQueue || onResumeQueue === null) return;
519 setResumingQueue(true);
520 await onResumeQueue();
521 setResumingQueue(false);
522 };
523
524 const operateDenied = useEnvironmentScopeDenied(
525 props.environmentId,
526 AuthOrchestrationOperateScope,
527 );
528 const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
529 const attachmentsUploading =
530 props.connectionState === "connected" &&
531 composerAttachmentsStillUploading({
532 environmentId: props.environmentId,
533 attachments: draftAttachments,
534 serverConfig: props.serverConfig,
535 states: uploadStates,
536 });
537 const sendPresentation = resolveComposerSendPresentation({
538 editingQueuedMessage: queuedEdit !== null,
539 // A side-chat command starts a side chat; it never queues or steers the running turn.
540 running:
541 props.activeThreadBusy &&
542 (props.redirectsApproval || parseSideChatCommand(draftMessage) === null),
543 canSteer: props.canSteerActiveTurn,
544 followUpBehavior: props.followUpBehavior,
545 deliveryDeferred:
546 props.connectionState !== "connected" || props.queueCount > 0 || attachmentsUploading,
547 });
548 const sendLabel = sendPresentation.label;
549 const currentModelSelection = props.selectedThread.modelSelection;
550 const modelUnavailable =
551 props.connectionState === "connected" &&
552 isModelSelectionUnavailable(
553 props.serverConfig,
554 currentModelSelection,
555 props.selectedThread.projectId,
556 );
557 const selectedProviderStatus = (() => {
558 if (!props.serverConfig) return null;
559 return (
560 props.serverConfig.providers.find(
561 (p) => p.instanceId === props.selectedThread.modelSelection.instanceId,
562 ) ?? null
563 );
564 })();
565 const openDraftDocument = (attachment: ComposerDocumentAttachment) => {
566 Keyboard.dismiss();
567 navigation.navigate("ThreadAttachment", {
568 environmentId: String(props.environmentId),
569 threadId: String(props.selectedThread.id),
570 attachmentId: attachment.attachmentId,
571 name: attachment.name,
572 mimeType: attachment.mimeType,
573 sizeBytes: String(attachment.sizeBytes),
574 draftKey: composerDraftKey,
575 });
576 };
577 const { onSendMessage, onChangeDraftMessage, onShowUsageLimits } = props;
578 const usageLimitsOffered =
579 selectedProviderStatus !== null &&
580 hasProviderUsageLimits(
581 selectedProviderStatus.driver,
582 props.serverConfig?.providers ?? [],
583 props.serverConfig?.usageLimitSources ?? [],
584 );
585 const openUsageLimits = () => {
586 const report = collectProviderUsageLimits(
587 currentModelSelection.instanceId,
588 props.serverConfig?.providers ?? [],
589 props.serverConfig?.usageLimitSources ?? [],
590 Date.now(),
591 );
592 onShowUsageLimits(report);
593 if (!report) {
594 Dialog.alert("Usage limits unavailable", "This provider does not currently report limits.");
595 }
596 return report !== null;
597 };
598
599 const mentionableEnvironments = useMentionableEnvironments();
600 // Mentions name any model for the agent, so they aren't limited to models this thread can switch to.
601 const mentionModelOptions = buildModelOptions(
602 props.serverConfig,
603 currentModelSelection,
604 undefined,
605 props.selectedThread.projectId,
606 );
607 const composerMenu = useComposerCommandMenu({
608 draftMessage: draftMessage,
609 ownerKey: composerDraftKey,
610 environmentId: props.environmentId,
611 threadShells: useVisibleThreadShells(),
612 environments: offersLinkedEnvironments(props.serverConfig)
613 ? mentionableEnvironments
614 : NO_MACHINES,
615 linkedEnvironments: useLinkedEnvironments(props.environmentId),
616 currentThreadId: props.selectedThread.id,
617 projectCwd: props.projectCwd,
618 pullRequestProjectId: props.serverConfig ? (project?.id ?? null) : null,
619 pullRequestRepository: project?.repositoryIdentity?.displayName ?? null,
620 threadPullRequests: props.selectedThread.pullRequests,
621 selectedProviderStatus,
622 hasThread: !props.isDraft,
623 hasCompactableConversation: props.hasCompactableConversation,
624 onChangeDraftMessage: props.onChangeDraftMessage,
625 offersUsageLimits: usageLimitsOffered,
626 onUsageLimits:
627 usageLimitsOffered && draftAttachments.length === 0 ? openUsageLimits : undefined,
628 onOpenModelPicker: settingsSheetPresentation.open,
629 modelOptions: mentionModelOptions,
630 modelProviders: props.serverConfig?.providers,
631 ...(props.onFreshSession === undefined ? {} : { onFreshSession: props.onFreshSession }),
632 offersSideChat: props.offersSideChat === true,
633 });
634 const voiceInput = useVoiceInputController({
635 ownerKey: composerDraftKey,
636 label: props.selectedThread.title || "Untitled thread",
637 readDraftMessage: () => getComposerDraftSnapshot(composerDraftKey).text,
638 selection: composerMenu.selection,
639 onChangeDraftMessage: (text) => setComposerDraftText(composerDraftKey, text),
640 onChangeSelection: composerMenu.onSelectionChange,
641 });
642 const isSubmissionLocked =
643 props.interactionLocked === true || queuedEdit?.saving === true || voiceInput.blocksSubmission;
644 const voicePresentation = resolveVoiceComposerPresentation(
645 voiceInput.state,
646 voiceInput.elapsedSeconds,
647 );
648 const isVoiceInputPresented = voicePresentation.statusKind === "active";
649 const isExpanded = isFocused || settingsSheetPresentation.keepsComposerExpanded;
650 const { layout } = useAdaptiveWorkspaceLayout();
651 const floatingSidebarComposer = useAndroidFloatingTabs() && layout.usesSplitView;
652 const sidebarWorkspaceTabs = useSidebarWorkspaceTabs();
653 const deviceType = useDeviceType();
654 const usesLargeControls = sidebarWorkspaceTabs === "picker" || deviceType === "pad";
655 const surfacePaddingVertical = usesLargeControls ? 9 : floatingSidebarComposer ? 6 : 2;
656 const [compactRowWidth, setCompactRowWidth] = useState(0);
657 const compactAttachmentLimit = compactRowWidth >= 500 ? 3 : 1;
658 // Animate only while typing; a thread switch or restored draft lands in place.
659 const compactEditor = useCompactComposerEditor(
660 bodyText,
661 draftMessage,
662 Platform.OS === "ios" && isFocused,
663 );
664 const showsCompactDictation = isVoiceInputPresented;
665 const isToolbarVisible = isVoiceInputPresented;
666 const hasEditingAttachments =
667 (queuedEdit !== null && queuedEdit.existingAttachments.length > 0) ||
668 stripAttachments.length > 0;
669 const attachmentBlockReason = composerAttachmentUploadBlockReason({
670 environmentId: props.environmentId,
671 attachments: draftAttachments,
672 connected: props.connectionState === "connected",
673 serverConfig: props.serverConfig,
674 states: uploadStates,
675 });
676 const contextImports = useAtomValue(composerContextImportsAtom);
677 const sendBlockedReason =
678 (queuedEdit?.saving === true ? "Saving…" : null) ??
679 props.sendBlockedReason ??
680 (pendingPastedTextAttachmentCount > 0 ? "Attaching pasted text" : null) ??
681 attachmentBlockReason;
682 const canSend =
683 (props.canOperateThread || props.connectionState !== "connected") &&
684 hasContent &&
685 !contextImports[composerDraftKey] &&
686 !isSubmissionLocked &&
687 sendBlockedReason === null &&
688 !modelUnavailable;
689
690 // A pending sheet presentation or focus restore has no composer left to act on.
691 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- disposes the pending settings sheet presentation and focus restore on unmount
692 useEffect(() => () => disposeSettingsSheetPresentation(), []);
693
694 const onPressPreview = (source: FilePreviewSource) => {
695 wasExpandedBeforePreviewRef.current = isFocused;
696 setPreviewVideo(null);
697 setPreviewFile(
698 (current) =>
699 current ?? {
700 ...source,
701 gallery: filePreviewGallery(source, composerImageGallery(draftAttachments)),
702 },
703 );
704 };
705
706 const closePreview = () => {
707 setPreviewFile(null);
708 setPreviewVideo(null);
709 if (wasExpandedBeforePreviewRef.current) {
710 setTimeout(() => {
711 if (navigation.isFocused()) inputRef.current?.focus();
712 }, 100);
713 }
714 };
715
716 const onPressVideo = (attachment: DraftComposerFileAttachment, sourceIdentifier: string) => {
717 wasExpandedBeforePreviewRef.current = isFocused;
718 setPreviewFile(null);
719 setPreviewVideo((current) => current ?? { type: "local", attachment, sourceIdentifier });
720 };
721
722 const onEditorFocusChange = props.onEditorFocusChange;
723 const handleFocus = () => {
724 setIsFocused(true);
725 settingsSheetPresentation.onEditorFocusChange(true);
726 onEditorFocusChange?.(true);
727 };
728
729 const handleBlur = () => {
730 setIsFocused(false);
731 settingsSheetPresentation.onEditorFocusChange(false);
732 onEditorFocusChange?.(false);
733 };
734 const handleSend = async (followUp?: ActiveTurnComposerAction) => {
735 if (
736 isSubmissionLocked ||
737 sendBlockedReason !== null ||
738 pendingPastedTextAttachmentCountRef.current > 0 ||
739 pendingNativeImagePasteCountRef.current > 0
740 )
741 return;
742 if (usageLimitsOffered && isUsageLimitsCommand(draftMessage) && draftAttachments.length === 0) {
743 if (openUsageLimits()) onChangeDraftMessage("");
744 return;
745 }
746 const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
747 if (inFlightThreadIdsRef.current.has(threadKey)) return;
748 inFlightThreadIdsRef.current.add(threadKey);
749 await inputRef.current?.flushPendingInput();
750 const draftAtSend = getComposerDraftSnapshot(composerDraftKey);
751 const stillSendable = () => {
752 const draft = getComposerDraftSnapshot(composerDraftKey);
753 return (
754 pendingPastedTextAttachmentCountRef.current === 0 &&
755 pendingNativeImagePasteCountRef.current === 0 &&
756 draft.text === draftAtSend.text &&
757 draft.attachments.length === draftAtSend.attachments.length &&
758 draft.attachments.every(
759 (attachment, index) => attachment.id === draftAtSend.attachments[index]?.id,
760 )
761 );
762 };
763 const sent = await settlePromise(() => onSendMessage(followUp, stillSendable));
764 inFlightThreadIdsRef.current.delete(threadKey);
765 if (AsyncResult.isFailure(sent)) {
766 console.error("[composer] send failed", squashAtomCommandFailure(sent));
767 return;
768 }
769 if (sent.value === null) return;
770 // Arm after send so preference reads and native Activity startup do not delay tap-frame feedback.
771 armAgentAwarenessLiveActivityForLocalWork({
772 environmentId: props.environmentId,
773 threadTitle: props.selectedThread.title,
774 projectTitle: props.environmentLabel ?? "T3 Code",
775 });
776 };
777
778 const lockedProviderInstanceId = props.canSwitchProvider
779 ? undefined
780 : currentModelSelection.instanceId;
781 const modelOptions = buildModelOptions(
782 serverConfigForCwd(props.serverConfig, props.projectCwd),
783 currentModelSelection,
784 lockedProviderInstanceId,
785 props.selectedThread.projectId,
786 );
787 const currentModelOption =
788 modelOptions.find(
789 (option) =>
790 option.selection.instanceId === currentModelSelection.instanceId &&
791 option.selection.model === currentModelSelection.model,
792 ) ?? null;
793 const openSettings = () => {
794 settingsSheetPresentation.open();
795 };
796
797 useFocusEffect(() => {
798 if (!settingsRoutePresentedRef.current) {
799 return;
800 }
801
802 settingsRoutePresentedRef.current = false;
803 settingsSheetPresentation.onDismissed();
804 });
805
806 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the native stack's finishTransitioning event to restore the keyboard after a sheet dismisses
807 useEffect(
808 () =>
809 // The native-stack patch exposes UIKit dismissal completion; restore the keyboard then.
810 (navigation as unknown as NavigationWithFinishTransitioning).addListener(
811 "finishTransitioning",
812 settingsSheetPresentation.onStackTransitionsFinished,
813 ),
814 [navigation, settingsSheetPresentation.onStackTransitionsFinished],
815 );
816
817 // Removable attachments: inside the card, or above the focused one-row composer.
818 const editingAttachments = hasEditingAttachments ? (
819 <>
820 {queuedEdit !== null && queuedEdit.existingAttachments.length > 0 ? (
821 <Animated.View
822 className="px-[14px] pb-2.5 pt-2"
823 entering={COMPOSER_ATTACHMENT_ENTERING}
824 exiting={FadeOut.duration(120)}
825 >
826 <ComposerQueuedEditAttachments
827 environmentId={props.environmentId}
828 attachments={queuedEdit.existingAttachments}
829 disabled={isSubmissionLocked}
830 onRemove={queuedEdit.onRemoveExistingAttachment}
831 />
832 </Animated.View>
833 ) : null}
834 {stripAttachments.length > 0 ? (
835 <Animated.View
836 className="px-[14px] pb-2.5 pt-2"
837 entering={COMPOSER_ATTACHMENT_ENTERING}
838 exiting={FadeOut.duration(120)}
839 >
840 <ComposerAttachmentStrip
841 environmentId={props.environmentId}
842 attachments={stripAttachments}
843 onRemove={isSubmissionLocked ? () => undefined : props.onRemoveDraftImage}
844 onPressPreview={isSubmissionLocked ? undefined : onPressPreview}
845 onPressVideo={isSubmissionLocked ? undefined : onPressVideo}
846 onPressDocument={
847 isSubmissionLocked
848 ? undefined
849 : (attachment) =>
850 openDraftDocument({
851 attachmentId: attachment.id,
852 name: attachment.name,
853 mimeType: attachment.mimeType,
854 sizeBytes: attachment.sizeBytes,
855 })
856 }
857 />
858 </Animated.View>
859 ) : null}
860 </>
861 ) : null;
862
863 const modelControl = (
864 <View className="min-w-0 shrink">
865 <ComposerModelControl
866 size={usesLargeControls ? "large" : "regular"}
867 modelOption={currentModelOption}
868 selection={currentModelSelection}
869 provider={selectedProviderStatus?.driver}
870 reportedSelection={props.reportedModelSelection}
871 prompt={draftMessage}
872 surfaceColor={composerPanel}
873 iconOnly={!compactEditor.isExpanded}
874 onPress={openSettings}
875 />
876 </View>
877 );
878
879 const compactBeforeSend =
880 props.compactBeforeSend && !showResumeAction && queuedEdit === null
881 ? props.compactBeforeSend
882 : null;
883 const compactTokens = compactBeforeSend ? formatTokens(compactBeforeSend.tokens) : null;
884 const compactControl =
885 compactBeforeSend && compactTokens !== null ? (
886 <ComposerInlineControl
887 size={usesLargeControls ? "large" : "regular"}
888 icon="arrow.down.right.and.arrow.up.left"
889 label={compactTokens}
890 selected={!compactBeforeSend.keepFullHistory}
891 showChevron={false}
892 disabled={!props.canOperateThread}
893 accessibilityLabel={
894 compactBeforeSend.keepFullHistory
895 ? `Next send keeps all ${compactTokens} tokens of history`
896 : `Next send compacts ${compactTokens} tokens of history first`
897 }
898 accessibilityHint={
899 compactBeforeSend.keepFullHistory ? "Compacts first" : "Keeps the full history"
900 }
901 onPress={compactBeforeSend.toggleKeepFullHistory}
902 />
903 ) : null;
904
905 return (
906 <Animated.View
907 onLayout={(event) => props.onHeightChange?.(event.nativeEvent.layout.height)}
908 className="px-[12px]"
909 style={{
910 paddingTop: 6,
911 paddingBottom: (props.bottomInset ?? 0) + THREAD_COMPOSER_BOTTOM_GUTTER,
912 backgroundColor:
913 Platform.OS === "android" ? themeColorWithAlpha(composerPanel, 1) : undefined,
914 }}
915 >
916 {/* Use a plain View: Reanimated Animated.View drops experimental_backgroundImage on Android. */}
917 <View
918 className={
919 Platform.OS === "android"
920 ? "hidden"
921 : "absolute inset-0 bg-linear-to-b from-screen/0 via-screen/60 to-screen/90"
922 }
923 pointerEvents="none"
924 />
925 <Animated.View
926 className="relative w-full self-center"
927 style={{ maxWidth: props.contentMaxWidth }}
928 >
929 {props.draftControls}
930 {!isSubmissionLocked &&
931 composerMenu.trigger &&
932 (composerMenu.items.length > 0 || composerMenu.trigger.kind === "pull-request") ? (
933 <ComposerPopoverAnchor>
934 <ComposerCommandPopover
935 items={composerMenu.items}
936 triggerKind={composerMenu.trigger.kind}
937 isLoading={composerMenu.isLoading}
938 error={composerMenu.error}
939 onSelect={composerMenu.onSelect}
940 />
941 </ComposerPopoverAnchor>
942 ) : null}
943
944 {selectedProviderStatus?.compatibilityAdvisory?.message &&
945 (selectedProviderStatus.compatibilityAdvisory.status === "unsupported" ||
946 selectedProviderStatus.compatibilityAdvisory.status === "broken") ? (
947 <Text
948 accessibilityRole={
949 selectedProviderStatus.compatibilityAdvisory.status === "broken" ? "alert" : undefined
950 }
951 accessibilityLiveRegion={
952 selectedProviderStatus.compatibilityAdvisory.status === "broken"
953 ? "assertive"
954 : "polite"
955 }
956 className={
957 selectedProviderStatus.compatibilityAdvisory.status === "broken"
958 ? "bg-danger px-3 py-2 text-xs text-danger-foreground"
959 : "px-3 py-2 text-xs text-foreground"
960 }
961 >
962 {selectedProviderStatus.compatibilityAdvisory.message}
963 </Text>
964 ) : null}
965 {modelUnavailable ? (
966 <Button
967 label="Model unavailable. Open model settings."
968 tone="text"
969 onPress={openSettings}
970 />
971 ) : null}
972
973 <ComposerSurface
974 animateLayout={false}
975 style={{
976 borderRadius: usesLargeControls ? 31 : 27,
977 borderCurve: "circular",
978 overflow: "hidden",
979 paddingVertical: surfacePaddingVertical,
980 }}
981 >
982 <ComposerDictationError
983 error={voiceInput.state.phase === "error" ? voiceInput.state.error : null}
984 onDismiss={voiceInput.cancel}
985 />
986 {isExpanded ? editingAttachments : null}
987 <View
988 onLayout={(event) => {
989 compactEditor.onRowLayout(event);
990 setCompactRowWidth(event.nativeEvent.layout.width);
991 }}
992 >
993 <ComposerDictationDraftContent
994 className="flex-row items-end"
995 compact
996 hidden={showsCompactDictation}
997 >
998 <ComposerAttachmentButton
999 size={usesLargeControls ? "large" : "regular"}
1000 disabled={isSubmissionLocked}
1001 supportsFiles={props.serverConfig !== null}
1002 onPickMedia={props.onPickDraftMedia}
1003 onPickFiles={props.onPickDraftFiles}
1004 />
1005 <Animated.View
1006 className="min-w-0 flex-1"
1007 onLayout={compactEditor.onEditorLayout}
1008 style={[
1009 {
1010 minWidth:
1011 compactEditor.isExpanded || stripAttachments.length > 0
1012 ? 0
1013 : INLINE_EDITOR_MIN_WIDTH,
1014 },
1015 compactEditor.containerStyle,
1016 compactEditor.isExpanded ? { flex: 0, width: 0 } : undefined,
1017 ]}
1018 ></Animated.View>
1019 {/* TalkBack orders siblings by position; outside this row the editor reads after Send. */}
1020 <Animated.View
1021 style={[
1022 compactEditor.editorStyle,
1023 showsCompactDictation ? { display: "none" } : undefined,
1024 ]}
1025 >
1026 <ComposerEditor
1027 hidden={props.hidden}
1028 draftKey={composerDraftKey}
1029 environmentId={props.environmentId}
1030 onOpenMention={(path) => {
1031 Keyboard.dismiss();
1032 if (props.isDraft) {
1033 navigation.navigate("NewTaskFile", {
1034 environmentId: String(props.environmentId),
1035 cwd: props.projectCwd ?? undefined,
1036 path: fileRoutePathSegments(path),
1037 });
1038 } else {
1039 navigation.navigate("ThreadFile", {
1040 environmentId: String(props.environmentId),
1041 threadId: String(props.selectedThread.id),
1042 path: fileRoutePathSegments(path),
1043 });
1044 }
1045 }}
1046 onOpenAttachment={openDraftDocument}
1047 chipsInert={!isExpanded}
1048 onInertChipPress={() => inputRef.current?.focus()}
1049 ref={inputRef}
1050 multiline
1051 value={draftMessage}
1052 // The save uses a draft snapshot; further typing would be discarded on success.
1053 readOnly={isSubmissionLocked}
1054 skills={composerMenu.skills}
1055 selection={composerMenu.selection}
1056 onChangeText={(text) => {
1057 if (!isSubmissionLocked) props.onChangeDraftMessage(text);
1058 }}
1059 onSelectionChange={composerMenu.onSelectionChange}
1060 onPasteImages={(uris) => {
1061 if (isSubmissionLocked) return;
1062 pendingNativeImagePasteCountRef.current += 1;
1063 void props.onNativePasteImages(uris).finally(() => {
1064 pendingNativeImagePasteCountRef.current -= 1;
1065 });
1066 }}
1067 onPasteText={(paste) => {
1068 if (isSubmissionLocked) return;
1069 const insertPaste = () => {
1070 const insertion = replaceTextSelection({
1071 value: paste.value,
1072 selection: paste.selection,
1073 text: paste.text,
1074 });
1075 const selection = { start: insertion.cursor, end: insertion.cursor };
1076 props.onChangeDraftMessage(insertion.value);
1077 composerMenu.onSelectionChange(selection);
1078 };
1079 const capabilities = props.serverConfig?.environment.capabilities;
1080 const advertisedMax = capabilities?.fileAttachments?.maxUploadBytes;
1081 const maxBytes =
1082 advertisedMax === undefined
1083 ? null
1084 : clampFileAttachmentUploadBytes(advertisedMax);
1085 const wouldExceedInputLimit =
1086 paste.value.length -
1087 Math.max(0, paste.selection.end - paste.selection.start) +
1088 paste.text.length >
1089 PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
1090 const canAttach =
1091 maxBytes !== null &&
1092 countComposerDraftAttachmentsAfterSelection(composerDraftKey, {
1093 text: paste.value,
1094 ...paste.selection,
1095 }) < PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
1096 new TextEncoder().encode(paste.text).byteLength <= maxBytes;
1097 if (
1098 pastedTextDisposition({
1099 text: paste.text,
1100 wouldExceedInputLimit,
1101 canAttach: true,
1102 }) === "attachment"
1103 ) {
1104 if (canAttach) {
1105 pendingPastedTextAttachmentCountRef.current += 1;
1106 setPendingPastedTextAttachmentCount(
1107 pendingPastedTextAttachmentCountRef.current,
1108 );
1109 const finishAttachment = () => {
1110 pendingPastedTextAttachmentCountRef.current = Math.max(
1111 0,
1112 pendingPastedTextAttachmentCountRef.current - 1,
1113 );
1114 setPendingPastedTextAttachmentCount(
1115 pendingPastedTextAttachmentCountRef.current,
1116 );
1117 };
1118 void props
1119 .onNativePasteText(paste)
1120 .then(finishAttachment, finishAttachment);
1121 } else if (!wouldExceedInputLimit) {
1122 insertPaste();
1123 } else {
1124 Dialog.alert(
1125 "Pasted text is too large for this message",
1126 "Remove some text or an attachment, then paste again.",
1127 );
1128 }
1129 return;
1130 }
1131 insertPaste();
1132 }}
1133 placeholder={props.placeholder}
1134 onFocus={handleFocus}
1135 onBlur={handleBlur}
1136 onSubmit={(alternate) =>
1137 void handleSend(
1138 alternate && sendPresentation.alternate !== null
1139 ? sendPresentation.alternate
1140 : undefined,
1141 )
1142 }
1143 submitTitle={sendPresentation.label}
1144 alternateSubmitTitle={
1145 sendPresentation.alternate === null
1146 ? sendPresentation.label
1147 : FOLLOW_UP_ACTION_LABEL[sendPresentation.alternate]
1148 }
1149 {...compactEditor.editorProps}
1150 textStyle={{
1151 ...bodyText,
1152 color: foregroundColor,
1153 }}
1154 />
1155 </Animated.View>
1156 {!isExpanded && stripAttachments.length > 0 ? (
1157 <View className="h-[44px] shrink-0 flex-row items-center gap-1 pl-1">
1158 {stripAttachments.slice(0, compactAttachmentLimit).map((attachment) => (
1159 <ComposerAttachmentThumbnail
1160 environmentId={props.environmentId}
1161 key={attachment.id}
1162 attachment={attachment}
1163 size={30}
1164 borderRadius={8}
1165 compact
1166 onPressPreview={isSubmissionLocked ? undefined : onPressPreview}
1167 onPressVideo={isSubmissionLocked ? undefined : onPressVideo}
1168 />
1169 ))}
1170 {stripAttachments.length > compactAttachmentLimit ? (
1171 <View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
1172 <Text className="text-foreground-muted text-2xs font-t3-bold">
1173 +{stripAttachments.length - compactAttachmentLimit}
1174 </Text>
1175 </View>
1176 ) : null}
1177 </View>
1178 ) : null}
1179 <View
1180 className="min-w-0 shrink flex-row items-center"
1181 style={
1182 compactEditor.isExpanded ? { flex: 1, justifyContent: "flex-end" } : undefined
1183 }
1184 >
1185 <Animated.View
1186 key={compactEditor.isExpanded ? "expanded" : "compact"}
1187 className="min-w-0 shrink flex-row items-center"
1188 entering={compactEditor.toolbarControlsEntering}
1189 >
1190 {compactControl}
1191 {modelControl}
1192 </Animated.View>
1193 <ComposerDictationStartAction
1194 size={usesLargeControls ? "large" : "regular"}
1195 state={voiceInput.state}
1196 isAvailable={voiceInput.isAvailable}
1197 disabled={isSubmissionLocked}
1198 onStart={voiceInput.start}
1199 onCancel={voiceInput.cancel}
1200 />
1201 {showStopAction ? (
1202 <ComposerActionButton
1203 size={usesLargeControls ? "large" : "regular"}
1204 accessibilityLabel="Stop agent"
1205 icon="stop.fill"
1206 variant="danger"
1207 disabled={!props.canOperateThread}
1208 onPress={props.onStopThread}
1209 />
1210 ) : showResumeAction ? (
1211 <ComposerActionButton
1212 size={usesLargeControls ? "large" : "regular"}
1213 accessibilityLabel="Resume thread"
1214 icon="play"
1215 disabled={!props.canOperateThread || resumingQueue}
1216 onPress={() => void handleResumeQueue()}
1217 />
1218 ) : (
1219 <SendActionButton
1220 size={usesLargeControls ? "large" : "regular"}
1221 accessibilityLabel={sendBlockedReason ?? sendLabel}
1222 presentation={sendPresentation}
1223 disabled={!canSend}
1224 onSend={handleSend}
1225 />
1226 )}
1227 </View>
1228 </ComposerDictationDraftContent>
1229 </View>
1230 <Animated.View
1231 accessibilityElementsHidden={!isToolbarVisible}
1232 collapsable={false}
1233 importantForAccessibility={isToolbarVisible ? "auto" : "no-hide-descendants"}
1234 pointerEvents={isToolbarVisible ? "auto" : "none"}
1235 style={{ position: "absolute", bottom: surfacePaddingVertical, left: 0, right: 0 }}
1236 >
1237 <ComposerDictationToolbar
1238 showsDictation={isVoiceInputPresented}
1239 visible={isToolbarVisible}
1240 >
1241 <ComposerToolbarRow
1242 paddingBottom={0}
1243 paddingHorizontal={0}
1244 paddingTop={0}
1245 style={{ gap: 0 }}
1246 >
1247 <ComposerDictationCancelAction
1248 size={usesLargeControls ? "large" : "regular"}
1249 presentation={voicePresentation}
1250 onCancel={voiceInput.cancel}
1251 />
1252 <ComposerDictationStatus
1253 audioLevels={voiceInput.audioLevels}
1254 elapsedSeconds={voiceInput.elapsedSeconds}
1255 phase={voiceInput.state.phase}
1256 presentation={voicePresentation}
1257 />
1258 <View className="shrink-0 flex-row items-center">
1259 <ComposerDictationPrimaryAction
1260 size={usesLargeControls ? "large" : "regular"}
1261 state={voiceInput.state}
1262 presentation={voicePresentation}
1263 isAvailable={voiceInput.isAvailable}
1264 disabled={isSubmissionLocked}
1265 onStart={voiceInput.start}
1266 onConfirm={voiceInput.stop}
1267 onCancel={voiceInput.cancel}
1268 />
1269 {showStopAction ? (
1270 <ComposerActionButton
1271 size={usesLargeControls ? "large" : "regular"}
1272 accessibilityLabel="Stop agent"
1273 icon="stop.fill"
1274 variant="danger"
1275 disabled={!props.canOperateThread}
1276 onPress={props.onStopThread}
1277 />
1278 ) : showResumeAction && voicePresentation.showsSend ? (
1279 <ComposerActionButton
1280 size={usesLargeControls ? "large" : "regular"}
1281 accessibilityLabel="Resume thread"
1282 icon="play"
1283 disabled={!props.canOperateThread || resumingQueue}
1284 onPress={() => void handleResumeQueue()}
1285 />
1286 ) : voicePresentation.showsSend ? (
1287 <SendActionButton
1288 size={usesLargeControls ? "large" : "regular"}
1289 accessibilityLabel={sendBlockedReason ?? sendLabel}
1290 presentation={sendPresentation}
1291 disabled={!canSend}
1292 onSend={handleSend}
1293 />
1294 ) : null}
1295 </View>
1296 </ComposerToolbarRow>
1297 </ComposerDictationToolbar>
1298 </Animated.View>
1299 </ComposerSurface>
1300
1301 {props.connectionState === "connected" && operateDenied ? (
1302 <Text className="pt-2 text-xs text-foreground-muted">
1303 This connection cannot control this task. You can still edit your draft.
1304 </Text>
1305 ) : null}
1306 </Animated.View>
1307
1308 <VideoPreviewModal source={previewVideo} onRequestClose={closePreview} />
1309 <FilePreviewModal source={previewFile} onRequestClose={closePreview} />
1310 </Animated.View>
1311 );
1312};