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.value = shouldAnimate
389 ? withTiming(targetBorderRadius, {
390 duration: COMPOSER_TRANSITION_DURATION_MS,
391 reduceMotion: ReduceMotion.System,
392 })
393 : targetBorderRadius;
394 }, [animatedBorderRadius, shouldAnimate, targetBorderRadius]);
395 const borderCurve = props.style.borderCurve;
396 const animatedShapeStyle = useAnimatedStyle(() => ({
397 borderRadius: animatedBorderRadius.value,
398 ...(borderCurve ? { borderCurve } : {}),
399 }));
400 const layoutTransition = shouldAnimate ? COMPOSER_LAYOUT_TRANSITION : undefined;
401
402 // Animate every native frame or glass and content jump to final height inside the clip.
403 return (
404 <Animated.View
405 className={
406 Platform.OS === "android" ? undefined : "shadow-[0_6px_28px] shadow-adaptive-black-a15-a35"
407 }
408 layout={layoutTransition}
409 style={[
410 animatedShapeStyle,
411 {
412 overflow: "hidden",
413 },
414 ]}
415 >
416 <AnimatedGlassSurface
417 chrome="none"
418 fallbackColor={colors["--color-composer-surface"]}
419 fallbackClassName="border border-composer-border"
420 glassEffectStyle="regular"
421 pointerEvents="none"
422 tintColor="transparent"
423 layout={layoutTransition}
424 style={[{ position: "absolute", inset: 0 }, animatedShapeStyle]}
425 >
426 {null}
427 </AnimatedGlassSurface>
428 <Animated.View
429 collapsable={false}
430 layout={layoutTransition}
431 style={[props.style, animatedShapeStyle]}
432 >
433 {props.children}
434 </Animated.View>
435 </Animated.View>
436 );
437}
438
439/** Space below the composer pill, inside the bottom inset it is given. */
440export const THREAD_COMPOSER_BOTTOM_GUTTER = 6;
441
442export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps) {
443 const project = useProject(scopeProjectRef(props.environmentId, props.selectedThread.projectId));
444 const { themeVariables: materialTheme } = useAppearancePreferences();
445 const composerPanel = materialTheme["--color-composer-panel"];
446 const navigation = useNavigation();
447 const foregroundColor = useUniwindTheme()["--color-foreground"];
448 const bodyText = useScaledTextRole("body");
449 const fallbackInputRef = useRef<ComposerEditorHandle>(null);
450 const inputRef = props.editorRef ?? fallbackInputRef;
451 const [isFocused, setIsFocused] = useState(false);
452 const pendingPastedTextAttachmentCountRef = useRef(0);
453 const pendingNativeImagePasteCountRef = useRef(0);
454 const [pendingPastedTextAttachmentCount, setPendingPastedTextAttachmentCount] = useState(0);
455 const settingsSheetPresentation = useThreadSettingsSheetPresentation({
456 editorRef: inputRef,
457 isEditorFocused: isFocused,
458 });
459 const settingsRoutePresentation = useExistingThreadSettingsRoutePresentation();
460 const settingsRoutePresentedRef = useRef(false);
461 const wasExpandedBeforePreviewRef = useRef(false);
462 const inFlightThreadIdsRef = useRef(new Set<string>());
463
464 const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
465 const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);
466 const composerOwnerKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
467 const composerDraftKey = props.draftKey ?? composerOwnerKey;
468 const { text: draftMessage, attachments: draftAttachments } = useComposerDraft(composerDraftKey);
469 const queuedEdit = props.queuedEdit ?? null;
470 const hasContent =
471 draftMessage.trim().length > 0 ||
472 draftAttachments.length > 0 ||
473 (queuedEdit?.existingAttachments.length ?? 0) > 0;
474 const stripAttachments = composerStripAttachments(draftAttachments);
475 const showStopAction = !hasContent && props.canStopThread && queuedEdit === null;
476 const onResumeQueue = props.onResumeQueue;
477 const [resumingQueue, setResumingQueue] = useState(false);
478 const showResumeAction =
479 !hasContent && !showStopAction && queuedEdit === null && onResumeQueue !== null;
480 const handleResumeQueue = async () => {
481 if (resumingQueue || onResumeQueue === null) return;
482 setResumingQueue(true);
483 await onResumeQueue();
484 setResumingQueue(false);
485 };
486
487 const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
488 const attachmentsUploading =
489 props.connectionState === "connected" &&
490 composerAttachmentsStillUploading({
491 environmentId: props.environmentId,
492 attachments: draftAttachments,
493 serverConfig: props.serverConfig,
494 states: uploadStates,
495 });
496 const sendPresentation = resolveComposerSendPresentation({
497 editingQueuedMessage: queuedEdit !== null,
498 running: props.activeThreadBusy,
499 canSteer: props.canSteerActiveTurn,
500 followUpBehavior: props.followUpBehavior,
501 deliveryDeferred:
502 props.connectionState !== "connected" || props.queueCount > 0 || attachmentsUploading,
503 });
504 const sendLabel = sendPresentation.label;
505 const currentModelSelection = props.selectedThread.modelSelection;
506 const currentRuntimeMode = props.selectedThread.runtimeMode;
507 const modelUnavailable =
508 props.connectionState === "connected" &&
509 isModelSelectionUnavailable(
510 props.serverConfig,
511 currentModelSelection,
512 props.selectedThread.projectId,
513 );
514 const selectedProviderStatus = (() => {
515 if (!props.serverConfig) return null;
516 return (
517 props.serverConfig.providers.find(
518 (p) => p.instanceId === props.selectedThread.modelSelection.instanceId,
519 ) ?? null
520 );
521 })();
522 const openDraftDocument = (attachment: ComposerDocumentAttachment) => {
523 Keyboard.dismiss();
524 navigation.navigate("ThreadAttachment", {
525 environmentId: String(props.environmentId),
526 threadId: String(props.selectedThread.id),
527 attachmentId: attachment.attachmentId,
528 name: attachment.name,
529 mimeType: attachment.mimeType,
530 sizeBytes: String(attachment.sizeBytes),
531 draftKey: composerDraftKey,
532 });
533 };
534 const { onSendMessage, onChangeDraftMessage, onShowUsageLimits } = props;
535 const usageLimitsOffered =
536 selectedProviderStatus !== null &&
537 hasProviderUsageLimits(
538 selectedProviderStatus.driver,
539 props.serverConfig?.providers ?? [],
540 props.serverConfig?.usageLimitSources ?? [],
541 );
542 const openUsageLimits = () => {
543 const report = collectProviderUsageLimits(
544 currentModelSelection.instanceId,
545 props.serverConfig?.providers ?? [],
546 props.serverConfig?.usageLimitSources ?? [],
547 Date.now(),
548 );
549 onShowUsageLimits(report);
550 if (!report) {
551 Dialog.alert("Usage limits unavailable", "This provider does not currently report limits.");
552 }
553 return report !== null;
554 };
555
556 const composerMenu = useComposerCommandMenu({
557 draftMessage: draftMessage,
558 ownerKey: composerDraftKey,
559 environmentId: props.environmentId,
560 threadShells: useThreadShells(),
561 currentThreadId: props.selectedThread.id,
562 projectCwd: props.projectCwd,
563 pullRequestProjectId: props.serverConfig?.environment.capabilities.pullRequests
564 ? (project?.id ?? null)
565 : null,
566 pullRequestRepository: project?.repositoryIdentity?.displayName ?? null,
567 threadPullRequests: props.selectedThread.pullRequests,
568 selectedProviderStatus,
569 hasThread: !props.isDraft,
570 hasCompactableConversation: props.hasCompactableConversation,
571 onChangeDraftMessage: props.onChangeDraftMessage,
572 onUpdateInteractionMode:
573 selectedProviderStatus?.showInteractionModeToggle === false
574 ? undefined
575 : props.onUpdateInteractionMode,
576 offersUsageLimits: usageLimitsOffered,
577 onUsageLimits:
578 usageLimitsOffered && draftAttachments.length === 0 ? openUsageLimits : undefined,
579 });
580 const voiceInput = useVoiceInputController({
581 ownerKey: composerDraftKey,
582 label: props.selectedThread.title || "Untitled thread",
583 readDraftMessage: () => getComposerDraftSnapshot(composerDraftKey).text,
584 subscribeToDraftChanges: (onChange) => appAtomRegistry.subscribe(composerDraftsAtom, onChange),
585 selection: composerMenu.selection,
586 onChangeDraftMessage: (text) => setComposerDraftText(composerDraftKey, text),
587 onChangeSelection: composerMenu.onSelectionChange,
588 });
589 const isSubmissionLocked =
590 props.interactionLocked === true || queuedEdit?.saving === true || voiceInput.blocksSubmission;
591 const voicePresentation = resolveVoiceComposerPresentation(
592 voiceInput.state,
593 voiceInput.elapsedSeconds,
594 );
595 const isVoiceInputPresented = voicePresentation.statusLabel !== null;
596 const isExpanded = isFocused || settingsSheetPresentation.keepsComposerExpanded;
597 const { setComposerEditing } = useAdaptiveWorkspaceLayout();
598 const hasSidebarTabBar = useSidebarWorkspaceTabs() === "picker";
599 const [compactRowWidth, setCompactRowWidth] = useState(0);
600 const compactAttachmentLimit = compactRowWidth >= 500 ? 3 : 1;
601 const compactEditor = useCompactComposerEditor(bodyText, draftMessage);
602 const showsCompactDictation = isVoiceInputPresented;
603 const isToolbarVisible = isVoiceInputPresented;
604 const hasEditingAttachments =
605 (queuedEdit !== null && queuedEdit.existingAttachments.length > 0) ||
606 stripAttachments.length > 0;
607 const attachmentBlockReason = composerAttachmentUploadBlockReason({
608 environmentId: props.environmentId,
609 attachments: draftAttachments,
610 connected: props.connectionState === "connected",
611 serverConfig: props.serverConfig,
612 states: uploadStates,
613 });
614 const contextImports = useAtomValue(composerContextImportsAtom);
615 const sendBlockedReason =
616 (queuedEdit?.saving === true ? "Saving…" : null) ??
617 props.sendBlockedReason ??
618 (pendingPastedTextAttachmentCount > 0 ? "Attaching pasted text" : null) ??
619 attachmentBlockReason;
620 const canSend =
621 (props.canOperateThread || props.connectionState !== "connected") &&
622 hasContent &&
623 !contextImports[composerDraftKey] &&
624 !isSubmissionLocked &&
625 sendBlockedReason === null &&
626 !modelUnavailable;
627
628 useEffect(() => () => setComposerEditing(false), [setComposerEditing]);
629
630 const onPressPreview = (source: FilePreviewSource) => {
631 wasExpandedBeforePreviewRef.current = isFocused;
632 setPreviewVideo(null);
633 setPreviewFile(
634 (current) =>
635 current ?? {
636 ...source,
637 gallery: filePreviewGallery(source, composerImageGallery(draftAttachments)),
638 },
639 );
640 };
641
642 const closePreview = () => {
643 setPreviewFile(null);
644 setPreviewVideo(null);
645 if (wasExpandedBeforePreviewRef.current) {
646 setTimeout(() => {
647 if (navigation.isFocused()) inputRef.current?.focus();
648 }, 100);
649 }
650 };
651
652 const onPressVideo = (attachment: DraftComposerFileAttachment, sourceIdentifier: string) => {
653 wasExpandedBeforePreviewRef.current = isFocused;
654 setPreviewFile(null);
655 setPreviewVideo((current) => current ?? { type: "local", attachment, sourceIdentifier });
656 };
657
658 const onEditorFocusChange = props.onEditorFocusChange;
659 const handleFocus = () => {
660 setIsFocused(true);
661 onEditorFocusChange?.(true);
662 setComposerEditing(true);
663 };
664
665 const handleBlur = () => {
666 setIsFocused(false);
667 onEditorFocusChange?.(false);
668 setComposerEditing(false);
669 };
670 const handleSend = async (followUp?: ActiveTurnComposerAction) => {
671 if (
672 isSubmissionLocked ||
673 sendBlockedReason !== null ||
674 pendingPastedTextAttachmentCountRef.current > 0 ||
675 pendingNativeImagePasteCountRef.current > 0
676 )
677 return;
678 if (usageLimitsOffered && isUsageLimitsCommand(draftMessage) && draftAttachments.length === 0) {
679 if (openUsageLimits()) onChangeDraftMessage("");
680 return;
681 }
682 const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
683 if (inFlightThreadIdsRef.current.has(threadKey)) return;
684 inFlightThreadIdsRef.current.add(threadKey);
685 const draftAtSend = getComposerDraftSnapshot(composerDraftKey);
686 const stillSendable = () => {
687 const draft = getComposerDraftSnapshot(composerDraftKey);
688 return (
689 pendingPastedTextAttachmentCountRef.current === 0 &&
690 pendingNativeImagePasteCountRef.current === 0 &&
691 draft.text === draftAtSend.text &&
692 draft.attachments.length === draftAtSend.attachments.length &&
693 draft.attachments.every(
694 (attachment, index) => attachment.id === draftAtSend.attachments[index]?.id,
695 )
696 );
697 };
698 const sent = await settlePromise(() => onSendMessage(followUp, stillSendable));
699 inFlightThreadIdsRef.current.delete(threadKey);
700 if (AsyncResult.isFailure(sent)) {
701 console.error("[composer] send failed", squashAtomCommandFailure(sent));
702 return;
703 }
704 if (sent.value === null) return;
705 // Arm after send so preference reads and native Activity startup do not delay tap-frame feedback.
706 armAgentAwarenessLiveActivityForLocalWork({
707 environmentId: props.environmentId,
708 threadTitle: props.selectedThread.title,
709 projectTitle: props.environmentLabel ?? "T3 Code",
710 });
711 };
712
713 const lockedProviderInstanceId = props.canSwitchProvider
714 ? undefined
715 : currentModelSelection.instanceId;
716 const modelOptions = buildModelOptions(
717 props.serverConfig,
718 currentModelSelection,
719 lockedProviderInstanceId,
720 props.selectedThread.projectId,
721 );
722 const threadProviderGroups = groupByProvider(modelOptions);
723 const currentModelOption =
724 modelOptions.find(
725 (option) =>
726 option.selection.instanceId === currentModelSelection.instanceId &&
727 option.selection.model === currentModelSelection.model,
728 ) ?? null;
729 const providerOptionDescriptors = resolveProviderOptionDescriptors({
730 capabilities: currentModelOption?.capabilities,
731 selections: currentModelSelection.options,
732 });
733 const settingsOwnerId = composerOwnerKey;
734 const settingsRouteSession = {
735 ownerId: settingsOwnerId,
736 environmentId: props.environmentId,
737 projectId: props.selectedThread.projectId,
738 providerInstanceId: currentModelSelection.instanceId,
739 ...(lockedProviderInstanceId ? { lockedProviderInstanceId } : {}),
740 providerGroups: threadProviderGroups,
741 selectedModel: currentModelSelection,
742 prompt: draftMessage,
743 onPromptChange: (text) => setComposerDraftText(composerDraftKey, text),
744 reportedModelSelection: props.reportedModelSelection,
745 onSelectModel: (option) =>
746 props.onUpdateModelSelection(withRememberedModelOptions(option.selection)),
747 restoreSelection: withRememberedModelOptions,
748 optionDescriptors: providerOptionDescriptors,
749 onUpdateOptionSelections: (options) => {
750 rememberModelOptions(
751 currentModelSelection.instanceId,
752 currentModelSelection.model,
753 options ?? [],
754 );
755 props.onUpdateModelSelection({ ...currentModelSelection, options });
756 },
757 runtimeMode: currentRuntimeMode,
758 onUpdateRuntimeMode: props.onUpdateRuntimeMode,
759 } satisfies ExistingThreadSettingsRouteSession;
760 const openSettings = () => {
761 settingsRoutePresentation.present(settingsRouteSession);
762 settingsSheetPresentation.open();
763 };
764
765 useEffect(() => {
766 if (settingsSheetPresentation.isActive) {
767 settingsRoutePresentation.present(settingsRouteSession);
768 }
769 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.isActive]);
770
771 useEffect(() => {
772 if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
773 return;
774 }
775
776 settingsRoutePresentedRef.current = true;
777 navigation.dispatch(StackActions.push("ThreadSettingsSheet"));
778 }, [navigation, settingsSheetPresentation.isVisible]);
779
780 useFocusEffect(() => {
781 if (!settingsRoutePresentedRef.current) {
782 return;
783 }
784
785 settingsRoutePresentedRef.current = false;
786 settingsSheetPresentation.onDismissed();
787 settingsRoutePresentation.clear(settingsOwnerId);
788 });
789
790 useEffect(
791 () =>
792 // The native-stack patch exposes UIKit dismissal completion; restore the keyboard then.
793 (navigation as unknown as NavigationWithFinishTransitioning).addListener(
794 "finishTransitioning",
795 settingsSheetPresentation.onStackTransitionsFinished,
796 ),
797 [navigation, settingsSheetPresentation.onStackTransitionsFinished],
798 );
799
800 // Removable attachments: inside the card, or above the focused one-row composer.
801 const editingAttachments = hasEditingAttachments ? (
802 <>
803 {queuedEdit !== null && queuedEdit.existingAttachments.length > 0 ? (
804 <Animated.View
805 className="px-[14px] pb-2.5 pt-2"
806 entering={COMPOSER_ATTACHMENT_ENTERING}
807 exiting={FadeOut.duration(120)}
808 >
809 <ComposerQueuedEditAttachments
810 environmentId={props.environmentId}
811 attachments={queuedEdit.existingAttachments}
812 disabled={isSubmissionLocked}
813 onRemove={queuedEdit.onRemoveExistingAttachment}
814 />
815 </Animated.View>
816 ) : null}
817 {stripAttachments.length > 0 ? (
818 <Animated.View
819 className="px-[14px] pb-2.5 pt-2"
820 entering={COMPOSER_ATTACHMENT_ENTERING}
821 exiting={FadeOut.duration(120)}
822 >
823 <ComposerAttachmentStrip
824 environmentId={props.environmentId}
825 attachments={stripAttachments}
826 onRemove={isSubmissionLocked ? () => undefined : props.onRemoveDraftImage}
827 onPressPreview={isSubmissionLocked ? undefined : onPressPreview}
828 onPressVideo={isSubmissionLocked ? undefined : onPressVideo}
829 onPressDocument={
830 isSubmissionLocked
831 ? undefined
832 : (attachment) =>
833 openDraftDocument({
834 attachmentId: attachment.id,
835 name: attachment.name,
836 mimeType: attachment.mimeType,
837 sizeBytes: attachment.sizeBytes,
838 })
839 }
840 />
841 </Animated.View>
842 ) : null}
843 </>
844 ) : null;
845
846 const modelControl = (
847 <View className="min-w-0 shrink">
848 <ComposerModelControl
849 size={hasSidebarTabBar ? "large" : "regular"}
850 modelOption={currentModelOption}
851 selection={currentModelSelection}
852 provider={selectedProviderStatus?.driver}
853 reportedSelection={props.reportedModelSelection}
854 prompt={draftMessage}
855 surfaceColor={composerPanel}
856 iconOnly={!compactEditor.isExpanded}
857 onPress={openSettings}
858 />
859 </View>
860 );
861
862 return (
863 <Animated.View
864 onLayout={(event) => props.onHeightChange?.(event.nativeEvent.layout.height)}
865 className="px-[12px]"
866 style={{
867 paddingTop: 6,
868 paddingBottom: (props.bottomInset ?? 0) + THREAD_COMPOSER_BOTTOM_GUTTER,
869 backgroundColor:
870 Platform.OS === "android" ? themeColorWithAlpha(composerPanel, 1) : undefined,
871 }}
872 >
873 {/* Use a plain View: Reanimated Animated.View drops experimental_backgroundImage on Android. */}
874 <View
875 className={
876 Platform.OS === "android"
877 ? "hidden"
878 : "absolute inset-0 bg-linear-to-b from-screen/0 via-screen/60 to-screen/90"
879 }
880 pointerEvents="none"
881 />
882 <Animated.View
883 className="relative w-full self-center"
884 style={{ maxWidth: props.contentMaxWidth }}
885 >
886 {props.draftControls}
887 {!isSubmissionLocked &&
888 composerMenu.trigger &&
889 (composerMenu.items.length > 0 || composerMenu.trigger.kind === "pull-request") ? (
890 <ComposerPopoverAnchor>
891 <ComposerCommandPopover
892 items={composerMenu.items}
893 triggerKind={composerMenu.trigger.kind}
894 isLoading={composerMenu.isLoading}
895 error={composerMenu.error}
896 onSelect={composerMenu.onSelect}
897 />
898 </ComposerPopoverAnchor>
899 ) : null}
900
901 {selectedProviderStatus?.compatibilityAdvisory?.message &&
902 (selectedProviderStatus.compatibilityAdvisory.status === "unsupported" ||
903 selectedProviderStatus.compatibilityAdvisory.status === "broken") ? (
904 <Text
905 accessibilityRole={
906 selectedProviderStatus.compatibilityAdvisory.status === "broken" ? "alert" : undefined
907 }
908 accessibilityLiveRegion={
909 selectedProviderStatus.compatibilityAdvisory.status === "broken"
910 ? "assertive"
911 : "polite"
912 }
913 className={
914 selectedProviderStatus.compatibilityAdvisory.status === "broken"
915 ? "bg-danger px-3 py-2 text-xs text-danger-foreground"
916 : "px-3 py-2 text-xs text-foreground"
917 }
918 >
919 {selectedProviderStatus.compatibilityAdvisory.message}
920 </Text>
921 ) : null}
922 {modelUnavailable ? (
923 <Button
924 label="Model unavailable. Open model settings."
925 tone="text"
926 onPress={openSettings}
927 />
928 ) : null}
929
930 <ComposerSurface
931 animateLayout={false}
932 style={{
933 borderRadius: hasSidebarTabBar ? 31 : 27,
934 borderCurve: "circular",
935 overflow: "hidden",
936 paddingVertical: hasSidebarTabBar ? 9 : 2,
937 }}
938 >
939 {isExpanded ? editingAttachments : null}
940 <View
941 onLayout={(event) => {
942 compactEditor.onRowLayout(event);
943 setCompactRowWidth(event.nativeEvent.layout.width);
944 }}
945 >
946 <ComposerDictationDraftContent
947 className="flex-row items-end"
948 compact
949 hidden={showsCompactDictation}
950 >
951 <ComposerAttachmentButton
952 size={hasSidebarTabBar ? "large" : "regular"}
953 disabled={isSubmissionLocked}
954 supportsFiles={Boolean(
955 props.serverConfig?.environment.capabilities.fileAttachments,
956 )}
957 onPickMedia={props.onPickDraftMedia}
958 onPickFiles={props.onPickDraftFiles}
959 />
960 <Animated.View
961 className="min-w-0 flex-1"
962 onLayout={compactEditor.onEditorLayout}
963 style={[
964 {
965 minWidth:
966 compactEditor.isExpanded || stripAttachments.length > 0
967 ? 0
968 : INLINE_EDITOR_MIN_WIDTH,
969 },
970 compactEditor.containerStyle,
971 compactEditor.isExpanded ? { flex: 0, width: 0 } : undefined,
972 ]}
973 ></Animated.View>
974 {!isExpanded && stripAttachments.length > 0 ? (
975 <View className="h-[44px] shrink-0 flex-row items-center gap-1 pl-1">
976 {stripAttachments.slice(0, compactAttachmentLimit).map((attachment) => (
977 <ComposerAttachmentThumbnail
978 environmentId={props.environmentId}
979 key={attachment.id}
980 attachment={attachment}
981 size={30}
982 borderRadius={8}
983 compact
984 onPressPreview={isSubmissionLocked ? undefined : onPressPreview}
985 onPressVideo={isSubmissionLocked ? undefined : onPressVideo}
986 />
987 ))}
988 {stripAttachments.length > compactAttachmentLimit ? (
989 <View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
990 <Text className="text-foreground-muted text-2xs font-t3-bold">
991 +{stripAttachments.length - compactAttachmentLimit}
992 </Text>
993 </View>
994 ) : null}
995 </View>
996 ) : null}
997 <View
998 className="min-w-0 shrink flex-row items-center"
999 style={
1000 compactEditor.isExpanded ? { flex: 1, justifyContent: "flex-end" } : undefined
1001 }
1002 >
1003 {modelControl}
1004 <ComposerDictationStartAction
1005 size={hasSidebarTabBar ? "large" : "regular"}
1006 state={voiceInput.state}
1007 isAvailable={voiceInput.isAvailable}
1008 disabled={isSubmissionLocked}
1009 onStart={voiceInput.start}
1010 onCancel={voiceInput.cancel}
1011 />
1012 {showStopAction ? (
1013 <ComposerActionButton
1014 size={hasSidebarTabBar ? "large" : "regular"}
1015 accessibilityLabel="Stop agent"
1016 icon="stop.fill"
1017 variant="danger"
1018 disabled={!props.canOperateThread}
1019 onPress={props.onStopThread}
1020 />
1021 ) : showResumeAction ? (
1022 <ComposerActionButton
1023 size={hasSidebarTabBar ? "large" : "regular"}
1024 accessibilityLabel="Resume queue"
1025 icon="play"
1026 disabled={!props.canOperateThread || resumingQueue}
1027 onPress={() => void handleResumeQueue()}
1028 />
1029 ) : (
1030 <SendActionButton
1031 size={hasSidebarTabBar ? "large" : "regular"}
1032 accessibilityLabel={sendBlockedReason ?? sendLabel}
1033 presentation={sendPresentation}
1034 disabled={!canSend}
1035 onSend={handleSend}
1036 />
1037 )}
1038 </View>
1039 </ComposerDictationDraftContent>
1040 <Animated.View
1041 style={[
1042 compactEditor.editorStyle,
1043 showsCompactDictation ? { display: "none" } : undefined,
1044 ]}
1045 >
1046 <ComposerEditor
1047 hidden={props.hidden}
1048 draftKey={composerDraftKey}
1049 environmentId={props.environmentId}
1050 onOpenMention={(path) => {
1051 Keyboard.dismiss();
1052 if (props.isDraft) {
1053 navigation.navigate("NewTaskFile", {
1054 environmentId: String(props.environmentId),
1055 cwd: props.projectCwd ?? undefined,
1056 path: fileRoutePathSegments(path),
1057 });
1058 } else {
1059 navigation.navigate("ThreadFile", {
1060 environmentId: String(props.environmentId),
1061 threadId: String(props.selectedThread.id),
1062 path: fileRoutePathSegments(path),
1063 });
1064 }
1065 }}
1066 onOpenAttachment={openDraftDocument}
1067 chipsInert={!isExpanded}
1068 onInertChipPress={() => inputRef.current?.focus()}
1069 ref={inputRef}
1070 multiline
1071 value={draftMessage}
1072 // The save uses a draft snapshot; further typing would be discarded on success.
1073 readOnly={isSubmissionLocked}
1074 skills={composerMenu.skills}
1075 selection={composerMenu.selection}
1076 onChangeText={(text) => {
1077 if (!isSubmissionLocked) props.onChangeDraftMessage(text);
1078 }}
1079 onSelectionChange={composerMenu.onSelectionChange}
1080 onPasteImages={(uris) => {
1081 if (isSubmissionLocked) return;
1082 pendingNativeImagePasteCountRef.current += 1;
1083 void props.onNativePasteImages(uris).finally(() => {
1084 pendingNativeImagePasteCountRef.current -= 1;
1085 });
1086 }}
1087 onPasteText={(paste) => {
1088 if (isSubmissionLocked) return;
1089 const insertPaste = () => {
1090 const insertion = replaceTextSelection({
1091 value: paste.value,
1092 selection: paste.selection,
1093 text: paste.text,
1094 });
1095 const selection = { start: insertion.cursor, end: insertion.cursor };
1096 props.onChangeDraftMessage(insertion.value);
1097 composerMenu.onSelectionChange(selection);
1098 };
1099 const capabilities = props.serverConfig?.environment.capabilities;
1100 const advertisedMax =
1101 capabilities?.attachmentUploads === true
1102 ? capabilities.fileAttachments?.maxUploadBytes
1103 : undefined;
1104 const maxBytes =
1105 advertisedMax === undefined
1106 ? null
1107 : clampFileAttachmentUploadBytes(advertisedMax);
1108 const wouldExceedInputLimit =
1109 paste.value.length -
1110 Math.max(0, paste.selection.end - paste.selection.start) +
1111 paste.text.length >
1112 PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
1113 const canAttach =
1114 maxBytes !== null &&
1115 countComposerDraftAttachmentsAfterSelection(composerDraftKey, {
1116 text: paste.value,
1117 ...paste.selection,
1118 }) < PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
1119 new TextEncoder().encode(paste.text).byteLength <= maxBytes;
1120 if (
1121 pastedTextDisposition({
1122 text: paste.text,
1123 wouldExceedInputLimit,
1124 canAttach: true,
1125 }) === "attachment"
1126 ) {
1127 if (canAttach) {
1128 pendingPastedTextAttachmentCountRef.current += 1;
1129 setPendingPastedTextAttachmentCount(
1130 pendingPastedTextAttachmentCountRef.current,
1131 );
1132 const finishAttachment = () => {
1133 pendingPastedTextAttachmentCountRef.current = Math.max(
1134 0,
1135 pendingPastedTextAttachmentCountRef.current - 1,
1136 );
1137 setPendingPastedTextAttachmentCount(
1138 pendingPastedTextAttachmentCountRef.current,
1139 );
1140 };
1141 void props.onNativePasteText(paste).then(finishAttachment, finishAttachment);
1142 } else if (!wouldExceedInputLimit) {
1143 insertPaste();
1144 } else {
1145 Dialog.alert(
1146 wouldExceedInputLimit
1147 ? "Pasted text is too large for this message"
1148 : "Could not attach pasted text",
1149 wouldExceedInputLimit
1150 ? "Remove some text or an attachment, then paste again."
1151 : "Remove an attachment or use a smaller paste, then try again.",
1152 );
1153 }
1154 return;
1155 }
1156 insertPaste();
1157 }}
1158 placeholder={props.placeholder}
1159 onFocus={handleFocus}
1160 onBlur={handleBlur}
1161 onSubmit={(alternate) =>
1162 void handleSend(
1163 alternate && sendPresentation.alternate !== null
1164 ? sendPresentation.alternate
1165 : undefined,
1166 )
1167 }
1168 submitTitle={sendPresentation.label}
1169 alternateSubmitTitle={
1170 sendPresentation.alternate === null
1171 ? sendPresentation.label
1172 : FOLLOW_UP_ACTION_LABEL[sendPresentation.alternate]
1173 }
1174 {...compactEditor.editorProps}
1175 textStyle={{
1176 ...bodyText,
1177 color: foregroundColor,
1178 }}
1179 />
1180 </Animated.View>
1181 </View>
1182 <Animated.View
1183 accessibilityElementsHidden={!isToolbarVisible}
1184 collapsable={false}
1185 importantForAccessibility={isToolbarVisible ? "auto" : "no-hide-descendants"}
1186 pointerEvents={isToolbarVisible ? "auto" : "none"}
1187 style={{ position: "absolute", bottom: hasSidebarTabBar ? 9 : 2, left: 0, right: 0 }}
1188 >
1189 <ComposerDictationToolbar
1190 showsDictation={isVoiceInputPresented}
1191 visible={isToolbarVisible}
1192 >
1193 <ComposerToolbarRow
1194 paddingBottom={0}
1195 paddingHorizontal={0}
1196 paddingTop={0}
1197 style={{ gap: 0 }}
1198 >
1199 <ComposerDictationCancelAction
1200 size={hasSidebarTabBar ? "large" : "regular"}
1201 presentation={voicePresentation}
1202 onCancel={voiceInput.cancel}
1203 />
1204 {isVoiceInputPresented ? (
1205 <ComposerDictationStatus
1206 audioLevels={voiceInput.audioLevels}
1207 elapsedSeconds={voiceInput.elapsedSeconds}
1208 phase={voiceInput.state.phase}
1209 presentation={voicePresentation}
1210 onDismissError={voiceInput.cancel}
1211 />
1212 ) : (
1213 <View className="min-w-0 flex-1 flex-row items-center justify-between">
1214 <ComposerAttachmentButton
1215 size={hasSidebarTabBar ? "large" : "regular"}
1216 disabled={isSubmissionLocked}
1217 supportsFiles={Boolean(
1218 props.serverConfig?.environment.capabilities.fileAttachments,
1219 )}
1220 onPickMedia={props.onPickDraftMedia}
1221 onPickFiles={props.onPickDraftFiles}
1222 />
1223 {modelControl}
1224 </View>
1225 )}
1226 <View className="shrink-0 flex-row items-center">
1227 <ComposerDictationPrimaryAction
1228 size={hasSidebarTabBar ? "large" : "regular"}
1229 state={voiceInput.state}
1230 presentation={voicePresentation}
1231 isAvailable={voiceInput.isAvailable}
1232 disabled={isSubmissionLocked}
1233 onStart={voiceInput.start}
1234 onConfirm={voiceInput.stop}
1235 onCancel={voiceInput.cancel}
1236 />
1237 {showStopAction ? (
1238 <ComposerActionButton
1239 accessibilityLabel="Stop agent"
1240 icon="stop.fill"
1241 variant="danger"
1242 disabled={!props.canOperateThread}
1243 onPress={props.onStopThread}
1244 />
1245 ) : showResumeAction && voicePresentation.showsSend ? (
1246 <ComposerActionButton
1247 accessibilityLabel="Resume queue"
1248 icon="play"
1249 disabled={!props.canOperateThread || resumingQueue}
1250 onPress={() => void handleResumeQueue()}
1251 />
1252 ) : voicePresentation.showsSend ? (
1253 <SendActionButton
1254 accessibilityLabel={sendBlockedReason ?? sendLabel}
1255 presentation={sendPresentation}
1256 disabled={!canSend}
1257 onSend={handleSend}
1258 />
1259 ) : null}
1260 </View>
1261 </ComposerToolbarRow>
1262 </ComposerDictationToolbar>
1263 </Animated.View>
1264 </ComposerSurface>
1265
1266 {props.connectionState === "connected" && !props.canOperateThread ? (
1267 <Text className="pt-2 text-xs text-foreground-muted">
1268 This connection cannot control this task. You can still edit your draft.
1269 </Text>
1270 ) : null}
1271 </Animated.View>
1272
1273 <VideoPreviewModal source={previewVideo} onRequestClose={closePreview} />
1274 <FilePreviewModal source={previewFile} onRequestClose={closePreview} />
1275 </Animated.View>
1276 );
1277};