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