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