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