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