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