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 =
151 Platform.OS === "android" ? COLLAPSED_EDITOR_DEFAULT_INSET : collapsedEditorInset(text);
152 const minimum = Math.max(INLINE_EDITOR_HEIGHT, Math.ceil(text.lineHeight) + 2 * inset);
153 const height = Math.max(
154 minimum,
155 Math.min(text.lineHeight * 4 + 2 * inset, contentHeight + 2 * inset),
156 );
157 // A line that fits the expanded editor may still overflow its compact slot.
158 // Compare its measured width too so widening cannot trigger a collapse loop.
159 const isExpanded =
160 value.length > 0 &&
161 (contentHeight > text.lineHeight * 1.5 ||
162 (compactWidth > 0 && contentSize.width > compactWidth));
163 const compactRowHeight = Math.max(44, minimum);
164 const animatedHeight = useSharedValue(height);
165 const surfaceHeight = useSharedValue(compactRowHeight);
166 const targetSurfaceHeight = isExpanded ? height + 52 : compactRowHeight;
167 const expansion = useSharedValue(0);
168 useLayoutEffect(() => {
169 const config = { duration: 180, reduceMotion: ReduceMotion.System };
170 if (Platform.OS === "android") {
171 animatedHeight.set(height);
172 surfaceHeight.set(targetSurfaceHeight);
173 expansion.set(Number(isExpanded));
174 return;
175 }
176 // Resolve wrapping at the destination width before animating vertically.
177 // Intermediate widths otherwise produce taller measurements mid-transition.
178 let nextFrame: number | undefined;
179 const frame = requestAnimationFrame(() => {
180 nextFrame = requestAnimationFrame(() => {
181 animatedHeight.set(withTiming(height, config));
182 surfaceHeight.set(withTiming(targetSurfaceHeight, config));
183 expansion.set(withTiming(Number(isExpanded), config));
184 });
185 });
186 return () => {
187 cancelAnimationFrame(frame);
188 if (nextFrame !== undefined) cancelAnimationFrame(nextFrame);
189 };
190 }, [animatedHeight, expansion, height, isExpanded, surfaceHeight, targetSurfaceHeight]);
191 const containerStyle = useAnimatedStyle(() => ({
192 height: surfaceHeight.value,
193 }));
194 const editorStyle = useAnimatedStyle(() => ({
195 position: "absolute",
196 overflow: "hidden",
197 height: animatedHeight.value,
198 left: isExpanded ? 14 : editorX.value + 4,
199 right: isExpanded ? 14 : rowWidth.value - editorX.value - editorWidth.value + 4,
200 bottom:
201 (compactRowHeight - minimum) / 2 + expansion.value * (52 - (compactRowHeight - minimum) / 2),
202 }));
203 return {
204 isExpanded,
205 containerStyle,
206 editorStyle,
207 onRowLayout: (event: { nativeEvent: { layout: { width: number } } }) => {
208 rowWidth.set(event.nativeEvent.layout.width);
209 },
210 onEditorLayout: (event: { nativeEvent: { layout: { x: number; width: number } } }) => {
211 // The expanded toolbar gives this slot to the model control. Keep the
212 // compact geometry for the return transition, rather than recording zero.
213 if (!isExpanded) {
214 editorX.set(event.nativeEvent.layout.x);
215 editorWidth.set(event.nativeEvent.layout.width);
216 setCompactWidth(Math.max(0, event.nativeEvent.layout.width - 8));
217 }
218 },
219 editorProps: {
220 singleLineCentered: !isExpanded,
221 scrollEnabled: Platform.OS === "android" || contentHeight >= text.lineHeight * 4,
222 contentInsetVertical: inset,
223 onContentSizeChange: (size: { width: number; height: number }) => {
224 setContentSize(size);
225 },
226 style: { flex: 1 },
227 },
228 };
229}
230
231export interface ThreadComposerProps {
232 readonly isDraft?: boolean;
233 readonly canOperateThread: boolean;
234 readonly placeholder: string;
235 readonly contentMaxWidth?: number;
236 readonly draftControls?: ReactNode;
237 readonly bottomInset?: number;
238 readonly connectionState: RemoteClientConnectionState;
239 readonly environmentLabel: string | null;
240 readonly threadSyncPhase?: "loading" | "syncing" | null;
241 readonly selectedThread: EnvironmentThreadShell;
242 readonly reportedModelSelection?: ModelSelection | null;
243 readonly hasCompactableConversation: boolean;
244 readonly serverConfig: T3ServerConfig | null;
245 readonly queueCount: number;
246 readonly activeThreadBusy: boolean;
247 readonly canStopThread: boolean;
248 readonly environmentId: EnvironmentId;
249 readonly projectCwd: string | null;
250 readonly sendBlockedReason?: string | null;
251 readonly interactionLocked?: boolean;
252 readonly draftKey?: string;
253 readonly queuedEdit?: {
254 readonly existingAttachments: ReadonlyArray<ChatAttachment>;
255 readonly saving: boolean;
256 readonly onRemoveExistingAttachment: (attachmentId: string) => void;
257 } | null;
258 readonly followUpBehavior: FollowUpBehavior;
259 readonly canSteerActiveTurn: boolean;
260 readonly hidden: boolean;
261 readonly editorRef?: RefObject<ComposerEditorHandle | null>;
262 readonly onChangeDraftMessage: (value: string) => void;
263 readonly onPickDraftMedia: () => Promise<void>;
264 readonly onPickDraftFiles: () => Promise<void>;
265 readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
266 readonly onNativePasteText: (paste: ComposerTextPaste) => Promise<void>;
267 readonly onRemoveDraftImage: (imageId: string) => void;
268 readonly onStopThread: () => void;
269 /** Present while the thread's queue is held. */
270 readonly onResumeQueue: (() => Promise<void>) | null;
271 /** `stillSendable` reports whether the draft is unchanged after any wait before sending. */
272 readonly onSendMessage: (
273 followUp?: ActiveTurnComposerAction,
274 stillSendable?: () => boolean,
275 ) => Promise<MessageId | null>;
276 readonly onShowUsageLimits: (report: UsageLimitsReport | null) => void;
277 readonly canSwitchProvider: boolean;
278 readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
279 readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;
280 readonly onUpdateInteractionMode?: (interactionMode: ProviderInteractionMode) => void;
281 readonly onHeightChange?: (height: number) => void;
282 readonly onEditorFocusChange?: (focused: boolean) => void;
283}
284
285// Android KeyboardStickyView tracks the IME; concurrent timed layout morphs cause jitter.
286export const COMPOSER_TRANSITION_DURATION_MS = 220;
287// Side panes animate dock width; nested horizontal transitions would make the surface trail the toolbar.
288const composerHeightTransition: LayoutAnimationFunction = (values) => {
289 "worklet";
290 const timing = {
291 duration: COMPOSER_TRANSITION_DURATION_MS,
292 reduceMotion: ReduceMotion.System,
293 };
294 return {
295 initialValues: {
296 originX: values.targetOriginX,
297 originY: values.currentOriginY,
298 width: values.targetWidth,
299 height: values.currentHeight,
300 },
301 animations: {
302 originX: values.targetOriginX,
303 originY: withTiming(values.targetOriginY, timing),
304 width: values.targetWidth,
305 height: withTiming(values.targetHeight, timing),
306 },
307 };
308};
309export const COMPOSER_LAYOUT_TRANSITION =
310 Platform.OS === "android" ? undefined : composerHeightTransition;
311// Share of the one-row composer the draft keeps; a long model name truncates first.
312const INLINE_EDITOR_MIN_WIDTH = "40%";
313const INLINE_EDITOR_HEIGHT = 36;
314
315const COMPOSER_ATTACHMENT_ENTERING =
316 Platform.OS === "android"
317 ? FadeIn.duration(160)
318 : FadeIn.delay(COMPOSER_TRANSITION_DURATION_MS).duration(160).reduceMotion(ReduceMotion.System);
319
320const AnimatedGlassSurface = Animated.createAnimatedComponent(GlassSurface);
321
322const FOLLOW_UP_ACTION_LABEL = {
323 queue: "Queue",
324 steer: "Steer now",
325 restart: "Restart turn",
326} as const;
327
328const FOLLOW_UP_ACTION_SUBTITLE = {
329 queue: "Run after the current turn",
330 steer: "Interrupt what the agent is doing",
331 restart: "Start the turn over with this message",
332} as const;
333
334function SendActionButton(props: {
335 readonly size?: "regular" | "large";
336 readonly accessibilityLabel: string;
337 readonly presentation: ComposerSendPresentation;
338 readonly disabled: boolean;
339 readonly onSend: (followUp?: ActiveTurnComposerAction) => void;
340}) {
341 const { presentation } = props;
342 const button = (
343 <ComposerActionButton
344 accessibilityLabel={props.accessibilityLabel}
345 size={props.size}
346 icon={presentation.icon}
347 variant="primary"
348 disabled={props.disabled}
349 onPress={() => props.onSend()}
350 />
351 );
352 if (!presentation.offersFollowUpChoice || presentation.action === null || props.disabled) {
353 return button;
354 }
355 const actions = [presentation.action, presentation.alternate].filter(
356 (action): action is ActiveTurnComposerAction => action !== null,
357 );
358 return (
359 <Menu
360 accessibilityLabel="Choose how to send this message"
361 shouldOpenOnLongPress
362 actions={actions.map((action) => ({
363 id: action,
364 title: FOLLOW_UP_ACTION_LABEL[action],
365 subtitle: FOLLOW_UP_ACTION_SUBTITLE[action],
366 state: action === presentation.action ? ("on" as const) : ("off" as const),
367 }))}
368 onPressAction={({ nativeEvent }) =>
369 props.onSend(nativeEvent.event as ActiveTurnComposerAction)
370 }
371 >
372 {button}
373 </Menu>
374 );
375}
376
377export function ComposerSurface(props: {
378 readonly children: ReactNode;
379 readonly style: ViewStyle;
380 readonly animateLayout?: boolean;
381}) {
382 const colors = useUniwindTheme();
383 const targetBorderRadius =
384 typeof props.style.borderRadius === "number" ? props.style.borderRadius : 0;
385 const animatedBorderRadius = useSharedValue(targetBorderRadius);
386 const shouldAnimate = props.animateLayout !== false && Platform.OS !== "android";
387 useLayoutEffect(() => {
388 animatedBorderRadius.set(
389 shouldAnimate
390 ? withTiming(targetBorderRadius, {
391 duration: COMPOSER_TRANSITION_DURATION_MS,
392 reduceMotion: ReduceMotion.System,
393 })
394 : targetBorderRadius,
395 );
396 }, [animatedBorderRadius, shouldAnimate, targetBorderRadius]);
397 const borderCurve = props.style.borderCurve;
398 const animatedShapeStyle = useAnimatedStyle(() => ({
399 borderRadius: animatedBorderRadius.value,
400 ...(borderCurve ? { borderCurve } : {}),
401 }));
402 const layoutTransition = shouldAnimate ? COMPOSER_LAYOUT_TRANSITION : undefined;
403
404 // Animate every native frame or glass and content jump to final height inside the clip.
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 console.error("[composer] send failed", squashAtomCommandFailure(sent));
704 return;
705 }
706 if (sent.value === null) return;
707 // Arm after send so preference reads and native Activity startup do not delay tap-frame feedback.
708 armAgentAwarenessLiveActivityForLocalWork({
709 environmentId: props.environmentId,
710 threadTitle: props.selectedThread.title,
711 projectTitle: props.environmentLabel ?? "T3 Code",
712 });
713 };
714
715 const lockedProviderInstanceId = props.canSwitchProvider
716 ? undefined
717 : currentModelSelection.instanceId;
718 const modelOptions = buildModelOptions(
719 props.serverConfig,
720 currentModelSelection,
721 lockedProviderInstanceId,
722 props.selectedThread.projectId,
723 );
724 const threadProviderGroups = groupByProvider(modelOptions);
725 const currentModelOption =
726 modelOptions.find(
727 (option) =>
728 option.selection.instanceId === currentModelSelection.instanceId &&
729 option.selection.model === currentModelSelection.model,
730 ) ?? null;
731 const providerOptionDescriptors = resolveProviderOptionDescriptors({
732 capabilities: currentModelOption?.capabilities,
733 selections: currentModelSelection.options,
734 });
735 const settingsOwnerId = composerOwnerKey;
736 const settingsRouteSession = {
737 ownerId: settingsOwnerId,
738 environmentId: props.environmentId,
739 projectId: props.selectedThread.projectId,
740 providerInstanceId: currentModelSelection.instanceId,
741 ...(lockedProviderInstanceId ? { lockedProviderInstanceId } : {}),
742 providerGroups: threadProviderGroups,
743 selectedModel: currentModelSelection,
744 prompt: draftMessage,
745 onPromptChange: (text) => setComposerDraftText(composerDraftKey, text),
746 reportedModelSelection: props.reportedModelSelection,
747 onSelectModel: (option) =>
748 props.onUpdateModelSelection(withRememberedModelOptions(option.selection)),
749 restoreSelection: withRememberedModelOptions,
750 optionDescriptors: providerOptionDescriptors,
751 onUpdateOptionSelections: (options) => {
752 rememberModelOptions(
753 currentModelSelection.instanceId,
754 currentModelSelection.model,
755 options ?? [],
756 );
757 props.onUpdateModelSelection({ ...currentModelSelection, options });
758 },
759 runtimeMode: currentRuntimeMode,
760 onUpdateRuntimeMode: props.onUpdateRuntimeMode,
761 } satisfies ExistingThreadSettingsRouteSession;
762 const openSettings = () => {
763 settingsRoutePresentation.present(settingsRouteSession);
764 settingsSheetPresentation.open();
765 };
766
767 useEffect(() => {
768 if (settingsSheetPresentation.isActive) {
769 settingsRoutePresentation.present(settingsRouteSession);
770 }
771 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.isActive]);
772
773 useEffect(() => {
774 if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
775 return;
776 }
777
778 settingsRoutePresentedRef.current = true;
779 navigation.dispatch(StackActions.push("ThreadSettingsSheet"));
780 }, [navigation, settingsSheetPresentation.isVisible]);
781
782 useFocusEffect(() => {
783 if (!settingsRoutePresentedRef.current) {
784 return;
785 }
786
787 settingsRoutePresentedRef.current = false;
788 settingsSheetPresentation.onDismissed();
789 settingsRoutePresentation.clear(settingsOwnerId);
790 });
791
792 useEffect(
793 () =>
794 // The native-stack patch exposes UIKit dismissal completion; restore the keyboard then.
795 (navigation as unknown as NavigationWithFinishTransitioning).addListener(
796 "finishTransitioning",
797 settingsSheetPresentation.onStackTransitionsFinished,
798 ),
799 [navigation, settingsSheetPresentation.onStackTransitionsFinished],
800 );
801
802 // Removable attachments: inside the card, or above the focused one-row composer.
803 const editingAttachments = hasEditingAttachments ? (
804 <>
805 {queuedEdit !== null && queuedEdit.existingAttachments.length > 0 ? (
806 <Animated.View
807 className="px-[14px] pb-2.5 pt-2"
808 entering={COMPOSER_ATTACHMENT_ENTERING}
809 exiting={FadeOut.duration(120)}
810 >
811 <ComposerQueuedEditAttachments
812 environmentId={props.environmentId}
813 attachments={queuedEdit.existingAttachments}
814 disabled={isSubmissionLocked}
815 onRemove={queuedEdit.onRemoveExistingAttachment}
816 />
817 </Animated.View>
818 ) : null}
819 {stripAttachments.length > 0 ? (
820 <Animated.View
821 className="px-[14px] pb-2.5 pt-2"
822 entering={COMPOSER_ATTACHMENT_ENTERING}
823 exiting={FadeOut.duration(120)}
824 >
825 <ComposerAttachmentStrip
826 environmentId={props.environmentId}
827 attachments={stripAttachments}
828 onRemove={isSubmissionLocked ? () => undefined : props.onRemoveDraftImage}
829 onPressPreview={isSubmissionLocked ? undefined : onPressPreview}
830 onPressVideo={isSubmissionLocked ? undefined : onPressVideo}
831 onPressDocument={
832 isSubmissionLocked
833 ? undefined
834 : (attachment) =>
835 openDraftDocument({
836 attachmentId: attachment.id,
837 name: attachment.name,
838 mimeType: attachment.mimeType,
839 sizeBytes: attachment.sizeBytes,
840 })
841 }
842 />
843 </Animated.View>
844 ) : null}
845 </>
846 ) : null;
847
848 const modelControl = (
849 <View className="min-w-0 shrink">
850 <ComposerModelControl
851 size={hasSidebarTabBar ? "large" : "regular"}
852 modelOption={currentModelOption}
853 selection={currentModelSelection}
854 provider={selectedProviderStatus?.driver}
855 reportedSelection={props.reportedModelSelection}
856 prompt={draftMessage}
857 surfaceColor={composerPanel}
858 iconOnly={!compactEditor.isExpanded}
859 onPress={openSettings}
860 />
861 </View>
862 );
863
864 return (
865 <Animated.View
866 onLayout={(event) => props.onHeightChange?.(event.nativeEvent.layout.height)}
867 className="px-[12px]"
868 style={{
869 paddingTop: 6,
870 paddingBottom: (props.bottomInset ?? 0) + THREAD_COMPOSER_BOTTOM_GUTTER,
871 backgroundColor:
872 Platform.OS === "android" ? themeColorWithAlpha(composerPanel, 1) : undefined,
873 }}
874 >
875 {/* Use a plain View: Reanimated Animated.View drops experimental_backgroundImage on Android. */}
876 <View
877 className={
878 Platform.OS === "android"
879 ? "hidden"
880 : "absolute inset-0 bg-linear-to-b from-screen/0 via-screen/60 to-screen/90"
881 }
882 pointerEvents="none"
883 />
884 <Animated.View
885 className="relative w-full self-center"
886 style={{ maxWidth: props.contentMaxWidth }}
887 >
888 {props.draftControls}
889 {!isSubmissionLocked &&
890 composerMenu.trigger &&
891 (composerMenu.items.length > 0 || composerMenu.trigger.kind === "pull-request") ? (
892 <ComposerPopoverAnchor>
893 <ComposerCommandPopover
894 items={composerMenu.items}
895 triggerKind={composerMenu.trigger.kind}
896 isLoading={composerMenu.isLoading}
897 error={composerMenu.error}
898 onSelect={composerMenu.onSelect}
899 />
900 </ComposerPopoverAnchor>
901 ) : null}
902
903 {selectedProviderStatus?.compatibilityAdvisory?.message &&
904 (selectedProviderStatus.compatibilityAdvisory.status === "unsupported" ||
905 selectedProviderStatus.compatibilityAdvisory.status === "broken") ? (
906 <Text
907 accessibilityRole={
908 selectedProviderStatus.compatibilityAdvisory.status === "broken" ? "alert" : undefined
909 }
910 accessibilityLiveRegion={
911 selectedProviderStatus.compatibilityAdvisory.status === "broken"
912 ? "assertive"
913 : "polite"
914 }
915 className={
916 selectedProviderStatus.compatibilityAdvisory.status === "broken"
917 ? "bg-danger px-3 py-2 text-xs text-danger-foreground"
918 : "px-3 py-2 text-xs text-foreground"
919 }
920 >
921 {selectedProviderStatus.compatibilityAdvisory.message}
922 </Text>
923 ) : null}
924 {modelUnavailable ? (
925 <Button
926 label="Model unavailable. Open model settings."
927 tone="text"
928 onPress={openSettings}
929 />
930 ) : null}
931
932 <ComposerSurface
933 animateLayout={false}
934 style={{
935 borderRadius: hasSidebarTabBar ? 31 : 27,
936 borderCurve: "circular",
937 overflow: "hidden",
938 paddingVertical: hasSidebarTabBar ? 9 : 2,
939 }}
940 >
941 {isExpanded ? editingAttachments : null}
942 <View
943 onLayout={(event) => {
944 compactEditor.onRowLayout(event);
945 setCompactRowWidth(event.nativeEvent.layout.width);
946 }}
947 >
948 <ComposerDictationDraftContent
949 className="flex-row items-end"
950 compact
951 hidden={showsCompactDictation}
952 >
953 <ComposerAttachmentButton
954 size={hasSidebarTabBar ? "large" : "regular"}
955 disabled={isSubmissionLocked}
956 supportsFiles={Boolean(
957 props.serverConfig?.environment.capabilities.fileAttachments,
958 )}
959 onPickMedia={props.onPickDraftMedia}
960 onPickFiles={props.onPickDraftFiles}
961 />
962 <Animated.View
963 className="min-w-0 flex-1"
964 onLayout={compactEditor.onEditorLayout}
965 style={[
966 {
967 minWidth:
968 compactEditor.isExpanded || stripAttachments.length > 0
969 ? 0
970 : INLINE_EDITOR_MIN_WIDTH,
971 },
972 compactEditor.containerStyle,
973 compactEditor.isExpanded ? { flex: 0, width: 0 } : undefined,
974 ]}
975 ></Animated.View>
976 {!isExpanded && stripAttachments.length > 0 ? (
977 <View className="h-[44px] shrink-0 flex-row items-center gap-1 pl-1">
978 {stripAttachments.slice(0, compactAttachmentLimit).map((attachment) => (
979 <ComposerAttachmentThumbnail
980 environmentId={props.environmentId}
981 key={attachment.id}
982 attachment={attachment}
983 size={30}
984 borderRadius={8}
985 compact
986 onPressPreview={isSubmissionLocked ? undefined : onPressPreview}
987 onPressVideo={isSubmissionLocked ? undefined : onPressVideo}
988 />
989 ))}
990 {stripAttachments.length > compactAttachmentLimit ? (
991 <View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
992 <Text className="text-foreground-muted text-2xs font-t3-bold">
993 +{stripAttachments.length - compactAttachmentLimit}
994 </Text>
995 </View>
996 ) : null}
997 </View>
998 ) : null}
999 <View
1000 className="min-w-0 shrink flex-row items-center"
1001 style={
1002 compactEditor.isExpanded ? { flex: 1, justifyContent: "flex-end" } : undefined
1003 }
1004 >
1005 {modelControl}
1006 <ComposerDictationStartAction
1007 size={hasSidebarTabBar ? "large" : "regular"}
1008 state={voiceInput.state}
1009 isAvailable={voiceInput.isAvailable}
1010 disabled={isSubmissionLocked}
1011 onStart={voiceInput.start}
1012 onCancel={voiceInput.cancel}
1013 />
1014 {showStopAction ? (
1015 <ComposerActionButton
1016 size={hasSidebarTabBar ? "large" : "regular"}
1017 accessibilityLabel="Stop agent"
1018 icon="stop.fill"
1019 variant="danger"
1020 disabled={!props.canOperateThread}
1021 onPress={props.onStopThread}
1022 />
1023 ) : showResumeAction ? (
1024 <ComposerActionButton
1025 size={hasSidebarTabBar ? "large" : "regular"}
1026 accessibilityLabel="Resume queue"
1027 icon="play"
1028 disabled={!props.canOperateThread || resumingQueue}
1029 onPress={() => void handleResumeQueue()}
1030 />
1031 ) : (
1032 <SendActionButton
1033 size={hasSidebarTabBar ? "large" : "regular"}
1034 accessibilityLabel={sendBlockedReason ?? sendLabel}
1035 presentation={sendPresentation}
1036 disabled={!canSend}
1037 onSend={handleSend}
1038 />
1039 )}
1040 </View>
1041 </ComposerDictationDraftContent>
1042 <Animated.View
1043 style={[
1044 compactEditor.editorStyle,
1045 showsCompactDictation ? { display: "none" } : undefined,
1046 ]}
1047 >
1048 <ComposerEditor
1049 hidden={props.hidden}
1050 draftKey={composerDraftKey}
1051 environmentId={props.environmentId}
1052 onOpenMention={(path) => {
1053 Keyboard.dismiss();
1054 if (props.isDraft) {
1055 navigation.navigate("NewTaskFile", {
1056 environmentId: String(props.environmentId),
1057 cwd: props.projectCwd ?? undefined,
1058 path: fileRoutePathSegments(path),
1059 });
1060 } else {
1061 navigation.navigate("ThreadFile", {
1062 environmentId: String(props.environmentId),
1063 threadId: String(props.selectedThread.id),
1064 path: fileRoutePathSegments(path),
1065 });
1066 }
1067 }}
1068 onOpenAttachment={openDraftDocument}
1069 chipsInert={!isExpanded}
1070 onInertChipPress={() => inputRef.current?.focus()}
1071 ref={inputRef}
1072 multiline
1073 value={draftMessage}
1074 // The save uses a draft snapshot; further typing would be discarded on success.
1075 readOnly={isSubmissionLocked}
1076 skills={composerMenu.skills}
1077 selection={composerMenu.selection}
1078 onChangeText={(text) => {
1079 if (!isSubmissionLocked) props.onChangeDraftMessage(text);
1080 }}
1081 onSelectionChange={composerMenu.onSelectionChange}
1082 onPasteImages={(uris) => {
1083 if (isSubmissionLocked) return;
1084 pendingNativeImagePasteCountRef.current += 1;
1085 void props.onNativePasteImages(uris).finally(() => {
1086 pendingNativeImagePasteCountRef.current -= 1;
1087 });
1088 }}
1089 onPasteText={(paste) => {
1090 if (isSubmissionLocked) return;
1091 const insertPaste = () => {
1092 const insertion = replaceTextSelection({
1093 value: paste.value,
1094 selection: paste.selection,
1095 text: paste.text,
1096 });
1097 const selection = { start: insertion.cursor, end: insertion.cursor };
1098 props.onChangeDraftMessage(insertion.value);
1099 composerMenu.onSelectionChange(selection);
1100 };
1101 const capabilities = props.serverConfig?.environment.capabilities;
1102 const advertisedMax =
1103 capabilities?.attachmentUploads === true
1104 ? capabilities.fileAttachments?.maxUploadBytes
1105 : undefined;
1106 const maxBytes =
1107 advertisedMax === undefined
1108 ? null
1109 : clampFileAttachmentUploadBytes(advertisedMax);
1110 const wouldExceedInputLimit =
1111 paste.value.length -
1112 Math.max(0, paste.selection.end - paste.selection.start) +
1113 paste.text.length >
1114 PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
1115 const canAttach =
1116 maxBytes !== null &&
1117 countComposerDraftAttachmentsAfterSelection(composerDraftKey, {
1118 text: paste.value,
1119 ...paste.selection,
1120 }) < PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
1121 new TextEncoder().encode(paste.text).byteLength <= maxBytes;
1122 if (
1123 pastedTextDisposition({
1124 text: paste.text,
1125 wouldExceedInputLimit,
1126 canAttach: true,
1127 }) === "attachment"
1128 ) {
1129 if (canAttach) {
1130 pendingPastedTextAttachmentCountRef.current += 1;
1131 setPendingPastedTextAttachmentCount(
1132 pendingPastedTextAttachmentCountRef.current,
1133 );
1134 const finishAttachment = () => {
1135 pendingPastedTextAttachmentCountRef.current = Math.max(
1136 0,
1137 pendingPastedTextAttachmentCountRef.current - 1,
1138 );
1139 setPendingPastedTextAttachmentCount(
1140 pendingPastedTextAttachmentCountRef.current,
1141 );
1142 };
1143 void props.onNativePasteText(paste).then(finishAttachment, finishAttachment);
1144 } else if (!wouldExceedInputLimit) {
1145 insertPaste();
1146 } else {
1147 Dialog.alert(
1148 wouldExceedInputLimit
1149 ? "Pasted text is too large for this message"
1150 : "Could not attach pasted text",
1151 wouldExceedInputLimit
1152 ? "Remove some text or an attachment, then paste again."
1153 : "Remove an attachment or use a smaller paste, then try again.",
1154 );
1155 }
1156 return;
1157 }
1158 insertPaste();
1159 }}
1160 placeholder={props.placeholder}
1161 onFocus={handleFocus}
1162 onBlur={handleBlur}
1163 onSubmit={(alternate) =>
1164 void handleSend(
1165 alternate && sendPresentation.alternate !== null
1166 ? sendPresentation.alternate
1167 : undefined,
1168 )
1169 }
1170 submitTitle={sendPresentation.label}
1171 alternateSubmitTitle={
1172 sendPresentation.alternate === null
1173 ? sendPresentation.label
1174 : FOLLOW_UP_ACTION_LABEL[sendPresentation.alternate]
1175 }
1176 {...compactEditor.editorProps}
1177 textStyle={{
1178 ...bodyText,
1179 color: foregroundColor,
1180 }}
1181 />
1182 </Animated.View>
1183 </View>
1184 <Animated.View
1185 accessibilityElementsHidden={!isToolbarVisible}
1186 collapsable={false}
1187 importantForAccessibility={isToolbarVisible ? "auto" : "no-hide-descendants"}
1188 pointerEvents={isToolbarVisible ? "auto" : "none"}
1189 style={{ position: "absolute", bottom: hasSidebarTabBar ? 9 : 2, left: 0, right: 0 }}
1190 >
1191 <ComposerDictationToolbar
1192 showsDictation={isVoiceInputPresented}
1193 visible={isToolbarVisible}
1194 >
1195 <ComposerToolbarRow
1196 paddingBottom={0}
1197 paddingHorizontal={0}
1198 paddingTop={0}
1199 style={{ gap: 0 }}
1200 >
1201 <ComposerDictationCancelAction
1202 size={hasSidebarTabBar ? "large" : "regular"}
1203 presentation={voicePresentation}
1204 onCancel={voiceInput.cancel}
1205 />
1206 {isVoiceInputPresented ? (
1207 <ComposerDictationStatus
1208 audioLevels={voiceInput.audioLevels}
1209 elapsedSeconds={voiceInput.elapsedSeconds}
1210 phase={voiceInput.state.phase}
1211 presentation={voicePresentation}
1212 onDismissError={voiceInput.cancel}
1213 />
1214 ) : (
1215 <View className="min-w-0 flex-1 flex-row items-center justify-between">
1216 <ComposerAttachmentButton
1217 size={hasSidebarTabBar ? "large" : "regular"}
1218 disabled={isSubmissionLocked}
1219 supportsFiles={Boolean(
1220 props.serverConfig?.environment.capabilities.fileAttachments,
1221 )}
1222 onPickMedia={props.onPickDraftMedia}
1223 onPickFiles={props.onPickDraftFiles}
1224 />
1225 {modelControl}
1226 </View>
1227 )}
1228 <View className="shrink-0 flex-row items-center">
1229 <ComposerDictationPrimaryAction
1230 size={hasSidebarTabBar ? "large" : "regular"}
1231 state={voiceInput.state}
1232 presentation={voicePresentation}
1233 isAvailable={voiceInput.isAvailable}
1234 disabled={isSubmissionLocked}
1235 onStart={voiceInput.start}
1236 onConfirm={voiceInput.stop}
1237 onCancel={voiceInput.cancel}
1238 />
1239 {showStopAction ? (
1240 <ComposerActionButton
1241 accessibilityLabel="Stop agent"
1242 icon="stop.fill"
1243 variant="danger"
1244 disabled={!props.canOperateThread}
1245 onPress={props.onStopThread}
1246 />
1247 ) : showResumeAction && voicePresentation.showsSend ? (
1248 <ComposerActionButton
1249 accessibilityLabel="Resume queue"
1250 icon="play"
1251 disabled={!props.canOperateThread || resumingQueue}
1252 onPress={() => void handleResumeQueue()}
1253 />
1254 ) : voicePresentation.showsSend ? (
1255 <SendActionButton
1256 accessibilityLabel={sendBlockedReason ?? sendLabel}
1257 presentation={sendPresentation}
1258 disabled={!canSend}
1259 onSend={handleSend}
1260 />
1261 ) : null}
1262 </View>
1263 </ComposerToolbarRow>
1264 </ComposerDictationToolbar>
1265 </Animated.View>
1266 </ComposerSurface>
1267
1268 {props.connectionState === "connected" && !props.canOperateThread ? (
1269 <Text className="pt-2 text-xs text-foreground-muted">
1270 This connection cannot control this task. You can still edit your draft.
1271 </Text>
1272 ) : null}
1273 </Animated.View>
1274
1275 <VideoPreviewModal source={previewVideo} onRequestClose={closePreview} />
1276 <FilePreviewModal source={previewFile} onRequestClose={closePreview} />
1277 </Animated.View>
1278 );
1279};