Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadComposer.tsx

997 lines40.4 KB

1import type { ComposerTextPaste } from "../../native/T3ComposerEditor.types";
2import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
3import { useAtomValue } from "@effect/atom-react";
4import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
5import { pastedTextDisposition, replaceTextSelection } from "@t3tools/client-runtime/text-paste";
6import {
7 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
8 PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
9 type EnvironmentId,
10 type MessageId,
11 type ModelSelection,
12 type OrchestrationThreadShell,
13 type ProviderInteractionMode,
14 type RuntimeMode,
15 type ServerConfig as T3ServerConfig,
16 type UsageLimitsReport,
17} from "@t3tools/contracts";
18import {
19 collectProviderUsageLimits,
20 hasProviderUsageLimits,
21 isUsageLimitsCommand,
22} from "@t3tools/shared/usageLimits";
23import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";
24import type { ReactNode } from "react";
25import {
26 memo,
27 useCallback,
28 useEffect,
29 useLayoutEffect,
30 useMemo,
31 useRef,
32 useState,
33 type RefObject,
34} from "react";
35import { Alert, Keyboard, Platform, Pressable, View, type ViewStyle } from "react-native";
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 composerContextImportsAtom,
57 countComposerDraftAttachmentsAfterSelection,
58} from "../../state/use-composer-drafts";
59import type { ComposerDocumentAttachment } from "../../lib/composerContext";
60import { useProject } from "../../state/entities";
61import { scopeProjectRef } from "@t3tools/client-runtime/environment";
62​
63import { AppText as Text } from "../../components/AppText";
64import { ComposerAttachmentButton } from "../../components/ComposerAttachmentButton";
65import {
66 ComposerAttachmentStrip,
67 ComposerAttachmentThumbnail,
68} from "../../components/ComposerAttachmentStrip";
69import { VideoPreviewModal, type VideoPreviewSource } from "../../components/VideoPreviewModal";
70import { GlassSurface } from "../../components/GlassSurface";
71import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
72import { fileRoutePathSegments } from "../files/filePath";
73import {
74 ComposerActionButton,
75 ComposerInlineControl,
76 ComposerToolbarRow,
77} from "../../components/ComposerToolbar";
78import { ProviderIcon } from "../../components/ProviderIcon";
79import {
80 composerStripAttachments,
81 type DraftComposerAttachment,
82 type DraftComposerFileAttachment,
83} from "../../lib/composerImages";
84import {
85 buildModelOptions,
86 groupByProvider,
87 isModelSelectionUnavailable,
88} from "../../lib/modelOptions";
89import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
90import type { RemoteClientConnectionState } from "../../lib/connection";
91import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
92import { ComposerCommandPopover } from "./ComposerCommandPopover";
93import { useComposerCommandMenu } from "./use-composer-command-menu";
94import {
95 ComposerDictationCancelAction,
96 ComposerDictationDraftContent,
97 ComposerDictationPrimaryAction,
98 ComposerDictationStartAction,
99 ComposerDictationStatus,
100 ComposerDictationToolbar,
101} from "../voice-input/ComposerDictationControl";
102import { useVoiceInputController } from "../voice-input/useVoiceInputController";
103import { resolveVoiceComposerPresentation } from "../voice-input/voiceInputPresentation";
104import {
105 type ExistingThreadSettingsRouteSession,
106 useExistingThreadSettingsRoutePresentation,
107} from "./ThreadSettingsSheet";
108import {
109 useThreadSettingsSheetPresentation,
110 type NavigationWithFinishTransitioning,
111} from "./use-thread-settings-sheet-presentation";
112​
113/**
114 * Height of the collapsed composer (pill + vertical padding, excluding safe-area inset).
115 * Exported so the parent can compute feed overlap / content insets.
116 */
117export const COMPOSER_COLLAPSED_CHROME = 60;
118​
119/**
120 * Height of the expanded composer (card + toolbar + vertical padding, excluding safe-area inset).
121 * Used by the parent to compute the larger feed bottom inset when the composer is focused.
122 */
123export const COMPOSER_EXPANDED_CHROME = 156;
124​
125export interface ThreadComposerProps {
126 readonly draftMessage: string;
127 readonly draftAttachments: ReadonlyArray<DraftComposerAttachment>;
128 readonly placeholder: string;
129 readonly contentMaxWidth?: number;
130 readonly bottomInset?: number;
131 readonly connectionState: RemoteClientConnectionState;
132 readonly environmentLabel: string | null;
133 readonly selectedThread: OrchestrationThreadShell;
134 readonly hasCompactableConversation: boolean;
135 readonly serverConfig: T3ServerConfig | null;
136 readonly queueCount: number;
137 readonly environmentId: EnvironmentId;
138 readonly projectCwd: string | null;
139 /** Why sending is blocked right now (shown as the send button's label), or null. */
140 readonly sendBlockedReason?: string | null;
141 readonly editorRef?: RefObject<ComposerEditorHandle | null>;
142 readonly onChangeDraftMessage: (value: string) => void;
143 readonly onPickDraftMedia: () => Promise<void>;
144 readonly onPickDraftFiles: () => Promise<void>;
145 readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
146 readonly onNativePasteText: (paste: ComposerTextPaste) => Promise<void>;
147 readonly onRemoveDraftImage: (imageId: string) => void;
148 readonly onStopThread: () => void;
149 readonly onSendMessage: () => Promise<MessageId | null>;
150 /** `/usage-limits` resolves locally; the host decides where the report shows. Null clears it. */
151 readonly onShowUsageLimits: (report: UsageLimitsReport | null) => void;
152 readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
153 readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;
154 readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
155 readonly onExpandedChange?: (expanded: boolean) => void;
156 /** Fires on editor focus/blur; hosts use it to vet stale keyboard state. */
157 readonly onEditorFocusChange?: (focused: boolean) => void;
159​
160/**
161 * The pill / card container — renders with Expo's native GlassView on supported
162 * iOS 26+ devices, with a frosted blur fallback where supported.
163 * Exported so NewTaskDraftScreen can render the same composer chrome.
164 */
165// The bottom-anchored dock position and clipped surface height use the same
166// transition so the card grows upward without exposing its final-size content.
167// Android gets NO layout transition: the composer rides the keyboard via
168// KeyboardStickyView (frame-synced to the IME), and a time-based morph
169// running alongside that translate reads as jitter. Snapping the layout and
170// letting the keyboard-synced slide be the only motion looks native there.
171export const COMPOSER_TRANSITION_DURATION_MS = 220;
172// Side panes already animate the dock's width. Nested horizontal layout
173// transitions would leave the surface trailing its toolbar's new position.
174// Keep the vertical pill/card morph while horizontal layout follows the dock.
175const composerHeightTransition: LayoutAnimationFunction = (values) => {
176 "worklet";
177 const timing = {
178 duration: COMPOSER_TRANSITION_DURATION_MS,
179 reduceMotion: ReduceMotion.System,
180 };
181 return {
182 initialValues: {
183 originX: values.targetOriginX,
184 originY: values.currentOriginY,
185 width: values.targetWidth,
186 height: values.currentHeight,
187 },
188 animations: {
189 originX: values.targetOriginX,
190 originY: withTiming(values.targetOriginY, timing),
191 width: values.targetWidth,
192 height: withTiming(values.targetHeight, timing),
193 },
194 };
195};
196export const COMPOSER_LAYOUT_TRANSITION =
197 Platform.OS === "android" ? undefined : composerHeightTransition;
198​
199const COMPOSER_ATTACHMENT_ENTERING =
200 Platform.OS === "android"
201 ? FadeIn.duration(160)
202 : FadeIn.delay(COMPOSER_TRANSITION_DURATION_MS).duration(160).reduceMotion(ReduceMotion.System);
203​
204const AnimatedGlassSurface = Animated.createAnimatedComponent(GlassSurface);
205​
206export function ComposerSurface(props: {
207 readonly children: ReactNode;
208 readonly style: ViewStyle;
209 /** Morphs between the compact and expanded composer layouts. */
210 readonly animateLayout?: boolean;
211}) {
212 const colors = useUniwindTheme();
213 const targetBorderRadius =
214 typeof props.style.borderRadius === "number" ? props.style.borderRadius : 0;
215 const animatedBorderRadius = useSharedValue(targetBorderRadius);
216 const shouldAnimate = props.animateLayout !== false && Platform.OS !== "android";
217 useLayoutEffect(() => {
218 animatedBorderRadius.value = shouldAnimate
219 ? withTiming(targetBorderRadius, {
220 duration: COMPOSER_TRANSITION_DURATION_MS,
221 reduceMotion: ReduceMotion.System,
222 })
223 : targetBorderRadius;
224 }, [animatedBorderRadius, shouldAnimate, targetBorderRadius]);
225 const animatedShapeStyle = useAnimatedStyle(() => ({
226 borderRadius: animatedBorderRadius.value,
227 }));
228 const layoutTransition = shouldAnimate ? COMPOSER_LAYOUT_TRANSITION : undefined;
229​
230 // Each native frame follows the same transition. Animating only the outer
231 // clip leaves the glass and content at their final height on the first frame.
232 return (
233 <Animated.View
234 className={
235 Platform.OS === "android" ? undefined : "shadow-[0_6px_28px] shadow-adaptive-black-a15-a35"
236 }
237 layout={layoutTransition}
238 style={[
239 animatedShapeStyle,
240 {
241 overflow: "hidden",
242 },
243 ]}
244 >
245 <AnimatedGlassSurface
246 chrome="none"
247 fallbackColor={
248 Platform.OS === "android" ? colors["--color-composer-surface"] : colors["--color-card"]
249 }
250 fallbackClassName={
251 Platform.OS === "android" ? "border border-composer-border" : "border border-border"
252 }
253 glassEffectStyle="regular"
254 // The composer is a passive material containing interactive controls.
255 // Keep native glass out of the interactive content's layout path.
256 pointerEvents="none"
257 tintColor="transparent"
258 layout={layoutTransition}
259 style={[{ position: "absolute", inset: 0 }, animatedShapeStyle]}
260 >
261 {null}
262 </AnimatedGlassSurface>
263 <Animated.View
264 collapsable={false}
265 layout={layoutTransition}
266 style={[props.style, animatedShapeStyle]}
267 >
268 {props.children}
269 </Animated.View>
270 </Animated.View>
271 );
273​
274export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) {
275 const project = useProject(scopeProjectRef(props.environmentId, props.selectedThread.projectId));
276 const { themeVariables: materialTheme } = useAppearancePreferences();
277 const composerPanel = materialTheme["--color-composer-panel"];
278 const navigation = useNavigation();
279 const foregroundColor = useUniwindTheme()["--color-foreground"];
280 const bodyText = useScaledTextRole("body");
281 const fallbackInputRef = useRef<ComposerEditorHandle>(null);
282 const inputRef = props.editorRef ?? fallbackInputRef;
283 const [isFocused, setIsFocused] = useState(false);
284 const pendingPastedTextAttachmentCountRef = useRef(0);
285 const [pendingPastedTextAttachmentCount, setPendingPastedTextAttachmentCount] = useState(0);
286 const settingsSheetPresentation = useThreadSettingsSheetPresentation({
287 editorRef: inputRef,
288 isEditorFocused: isFocused,
289 });
290 const settingsRoutePresentation = useExistingThreadSettingsRoutePresentation();
291 const settingsRoutePresentedRef = useRef(false);
292 const wasExpandedBeforePreviewRef = useRef(false);
293 const inFlightThreadIdsRef = useRef(new Set<string>());
294 const { onExpandedChange } = props;
295​
296 const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
297 const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);
298 const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
299 // Only media belongs above the composer; every other file reads as its inline chip.
300 const stripAttachments = useMemo(
301 () => composerStripAttachments(props.draftAttachments),
302 [props.draftAttachments],
303 );
304 const showStopAction =
305 !hasContent &&
306 (props.selectedThread.session?.status === "running" ||
307 props.selectedThread.session?.status === "starting");
308​
309 const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
310 const attachmentsUploading =
311 props.connectionState === "connected" &&
312 composerAttachmentsStillUploading({
313 environmentId: props.environmentId,
314 attachments: props.draftAttachments,
315 serverConfig: props.serverConfig,
316 states: uploadStates,
317 });
318 // Every send goes through the outbox; the label says whether it leaves now
319 // or waits (for the connection, an earlier queued message, or an upload).
320 const sendLabel =
321 props.connectionState !== "connected" || props.queueCount > 0 || attachmentsUploading
322 ? "Queue"
323 : "Send";
324 const currentModelSelection = props.selectedThread.modelSelection;
325 const currentRuntimeMode = props.selectedThread.runtimeMode;
326 const modelUnavailable =
327 props.connectionState === "connected" &&
328 isModelSelectionUnavailable(props.serverConfig, currentModelSelection);
329 const selectedProviderStatus = useMemo(() => {
330 if (!props.serverConfig) return null;
331 return (
332 props.serverConfig.providers.find(
333 (p) => p.instanceId === props.selectedThread.modelSelection.instanceId,
334 ) ?? null
335 );
336 }, [props.serverConfig, props.selectedThread.modelSelection.instanceId]);
337 const composerOwnerKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
338 const openDraftDocument = (attachment: ComposerDocumentAttachment) => {
339 Keyboard.dismiss();
340 navigation.navigate("ThreadAttachment", {
341 environmentId: String(props.environmentId),
342 threadId: String(props.selectedThread.id),
343 attachmentId: attachment.attachmentId,
344 name: attachment.name,
345 mimeType: attachment.mimeType,
346 sizeBytes: String(attachment.sizeBytes),
347 draftKey: composerOwnerKey,
348 });
349 };
350 const { onSendMessage, onChangeDraftMessage, onShowUsageLimits } = props;
351 // T3 owns /usage-limits only where Limits has data for the selected provider;
352 // elsewhere the name stays the provider's own and is sent through untouched.
353 const usageLimitsOffered =
354 selectedProviderStatus !== null &&
355 hasProviderUsageLimits(
356 selectedProviderStatus.driver,
357 props.serverConfig?.providers ?? [],
358 props.serverConfig?.usageLimitSources ?? [],
359 );
360 // Answered locally from the last Limits snapshot; the agent never sees it.
361 const openUsageLimits = useCallback(() => {
362 const report = collectProviderUsageLimits(
363 currentModelSelection.instanceId,
364 props.serverConfig?.providers ?? [],
365 props.serverConfig?.usageLimitSources ?? [],
366 Date.now(),
367 );
368 onShowUsageLimits(report);
369 if (!report) {
370 Alert.alert("Usage limits unavailable", "This provider does not currently report limits.");
371 }
372 return report !== null;
373 }, [currentModelSelection.instanceId, onShowUsageLimits, props.serverConfig]);
374​
375 const composerMenu = useComposerCommandMenu({
376 draftMessage: props.draftMessage,
377 ownerKey: composerOwnerKey,
378 environmentId: props.environmentId,
379 projectCwd: props.projectCwd,
380 pullRequestProjectId: props.serverConfig?.environment.capabilities.pullRequests
381 ? (project?.id ?? null)
382 : null,
383 pullRequestRepository: project?.repositoryIdentity?.displayName ?? null,
384 selectedProviderStatus,
385 hasThread: true,
386 hasCompactableConversation: props.hasCompactableConversation,
387 onChangeDraftMessage: props.onChangeDraftMessage,
388 onUpdateInteractionMode:
389 selectedProviderStatus?.showInteractionModeToggle === false
390 ? undefined
391 : props.onUpdateInteractionMode,
392 offersUsageLimits: usageLimitsOffered,
393 // With attachments aboard the pick just inserts the text, so it sends as a prompt.
394 onUsageLimits:
395 usageLimitsOffered && props.draftAttachments.length === 0 ? openUsageLimits : undefined,
396 });
397 const voiceInput = useVoiceInputController({
398 ownerKey: composerOwnerKey,
399 draftMessage: props.draftMessage,
400 selection: composerMenu.selection,
401 onChangeDraftMessage: props.onChangeDraftMessage,
402 onChangeSelection: composerMenu.onSelectionChange,
403 });
404 const voicePresentation = resolveVoiceComposerPresentation(
405 voiceInput.state,
406 voiceInput.elapsedSeconds,
407 );
408 const isVoiceInputPresented = voicePresentation.statusLabel !== null;
409 // An open draft stays visible; only a collapsed composer becomes a voice strip.
410 const isExpanded = isFocused || settingsSheetPresentation.keepsComposerExpanded;
411 const showsCompactDictation = isVoiceInputPresented && !isExpanded;
412 const isToolbarVisible = isExpanded || isVoiceInputPresented;
413 const attachmentBlockReason = composerAttachmentUploadBlockReason({
414 environmentId: props.environmentId,
415 attachments: props.draftAttachments,
416 connected: props.connectionState === "connected",
417 serverConfig: props.serverConfig,
418 states: uploadStates,
419 });
420 const contextImports = useAtomValue(composerContextImportsAtom);
421 const sendBlockedReason =
422 props.sendBlockedReason ??
423 (pendingPastedTextAttachmentCount > 0 ? "Attaching pasted text" : null) ??
424 attachmentBlockReason;
425 const canSend =
426 hasContent &&
427 !contextImports[composerOwnerKey] &&
428 !voiceInput.blocksSubmission &&
429 sendBlockedReason === null &&
430 !modelUnavailable;
431​
432 // Keep the feed inset aligned with the card or compact dictation strip.
433 useEffect(() => {
434 onExpandedChange?.(isExpanded);
435 }, [isExpanded, onExpandedChange]);
436​
437 const onPressPreview = useCallback(
438 (source: FilePreviewSource) => {
439 wasExpandedBeforePreviewRef.current = isFocused;
440 setPreviewVideo(null);
441 setPreviewFile((current) => current ?? source);
442 },
443 [isFocused],
444 );
445​
446 const closePreview = useCallback(() => {
447 setPreviewFile(null);
448 setPreviewVideo(null);
449 if (wasExpandedBeforePreviewRef.current) {
450 setTimeout(() => {
451 if (navigation.isFocused()) inputRef.current?.focus();
452 }, 100);
453 }
454 }, [inputRef, navigation]);
455​
456 const onPressVideo = useCallback(
457 (attachment: DraftComposerFileAttachment, sourceIdentifier: string) => {
458 wasExpandedBeforePreviewRef.current = isFocused;
459 setPreviewFile(null);
460 setPreviewVideo((current) => current ?? { type: "local", attachment, sourceIdentifier });
461 },
462 [isFocused],
463 );
464​
465 const onEditorFocusChange = props.onEditorFocusChange;
466 const handleFocus = useCallback(() => {
467 setIsFocused(true);
468 onExpandedChange?.(true);
469 onEditorFocusChange?.(true);
470 }, [onEditorFocusChange, onExpandedChange]);
471​
472 const handleBlur = useCallback(() => {
473 setIsFocused(false);
474 if (!settingsSheetPresentation.keepsComposerExpanded) {
475 onExpandedChange?.(false);
476 }
477 onEditorFocusChange?.(false);
478 }, [onEditorFocusChange, onExpandedChange, settingsSheetPresentation.keepsComposerExpanded]);
479 const handleSend = useCallback(async () => {
480 if (voiceInput.blocksSubmission || pendingPastedTextAttachmentCountRef.current > 0) return;
481 // Typed out in full rather than picked from the menu. Attachments mean the
482 // user is sending a prompt, so those go through as usual.
483 if (
484 usageLimitsOffered &&
485 isUsageLimitsCommand(props.draftMessage) &&
486 props.draftAttachments.length === 0
487 ) {
488 if (openUsageLimits()) onChangeDraftMessage("");
489 return;
490 }
491 const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
492 if (inFlightThreadIdsRef.current.has(threadKey)) return;
493 inFlightThreadIdsRef.current.add(threadKey);
494 try {
495 const messageId = await onSendMessage();
496 if (messageId === null) {
497 return;
498 }
499 // Sending a prompt starts agent work: arm the lock-screen card while the
500 // app is foregrounded and the activity token can be registered. Armed
501 // after the send so its preference read and native Activity start don't
502 // contend with the queued-message feedback on the tap frame.
503 armAgentAwarenessLiveActivityForLocalWork({
504 environmentId: props.environmentId,
505 threadTitle: props.selectedThread.title,
506 projectTitle: props.environmentLabel ?? "T3 Code",
507 });
508 } finally {
509 inFlightThreadIdsRef.current.delete(threadKey);
510 }
511 }, [
512 props.draftMessage,
513 props.draftAttachments.length,
514 onChangeDraftMessage,
515 openUsageLimits,
516 usageLimitsOffered,
517 onSendMessage,
518 props.environmentId,
519 props.environmentLabel,
520 props.selectedThread.id,
521 props.selectedThread.title,
522 voiceInput.blocksSubmission,
523 ]);
524​
525 // ── Model menu ───────────────────────────────────────────
526 const modelOptions = useMemo(
527 () => buildModelOptions(props.serverConfig, currentModelSelection),
528 [props.serverConfig, currentModelSelection],
529 );
530 const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
531 // An existing thread is bound to its harness: sessions can't move between
532 // provider instances, so the picker only offers the thread's own group.
533 const threadProviderGroups = useMemo(
534 () => providerGroups.filter((group) => group.providerKey === currentModelSelection.instanceId),
535 [providerGroups, currentModelSelection.instanceId],
536 );
537 const currentModelOption =
538 modelOptions.find(
539 (option) =>
540 option.selection.instanceId === currentModelSelection.instanceId &&
541 option.selection.model === currentModelSelection.model,
542 ) ?? null;
543 const providerOptionDescriptors = useMemo(
544 () =>
545 resolveProviderOptionDescriptors({
546 capabilities: currentModelOption?.capabilities,
547 selections: currentModelSelection.options,
548 }),
549 [currentModelOption?.capabilities, currentModelSelection.options],
550 );
551 const settingsOwnerId = composerOwnerKey;
552 const settingsRouteSession = useMemo<ExistingThreadSettingsRouteSession>(
553 () => ({
554 ownerId: settingsOwnerId,
555 environmentId: props.environmentId,
556 providerInstanceId: currentModelSelection.instanceId,
557 providerGroups: threadProviderGroups,
558 selectedModel: currentModelSelection,
559 onSelectModel: (option) => props.onUpdateModelSelection(option.selection),
560 optionDescriptors: providerOptionDescriptors,
561 onUpdateOptionSelections: (options) =>
562 props.onUpdateModelSelection({ ...currentModelSelection, options }),
563 runtimeMode: currentRuntimeMode,
564 onUpdateRuntimeMode: props.onUpdateRuntimeMode,
565 }),
566 [
567 currentModelSelection,
568 currentRuntimeMode,
569 props.onUpdateModelSelection,
570 props.onUpdateRuntimeMode,
571 providerOptionDescriptors,
572 settingsOwnerId,
573 threadProviderGroups,
574 ],
575 );
576 const openSettings = useCallback(() => {
577 settingsRoutePresentation.present(settingsRouteSession);
578 settingsSheetPresentation.open();
579 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.open]);
580​
581 useEffect(() => {
582 if (settingsSheetPresentation.isActive) {
583 settingsRoutePresentation.present(settingsRouteSession);
584 }
585 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.isActive]);
586​
587 useEffect(() => {
588 if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
589 return;
590 }
591​
592 settingsRoutePresentedRef.current = true;
593 navigation.dispatch(StackActions.push("ThreadSettingsSheet"));
594 }, [navigation, settingsSheetPresentation.isVisible]);
595​
596 useFocusEffect(
597 useCallback(() => {
598 if (!settingsRoutePresentedRef.current) {
599 return;
600 }
601​
602 settingsRoutePresentedRef.current = false;
603 settingsSheetPresentation.onDismissed();
604 settingsRoutePresentation.clear(settingsOwnerId);
605 }, [settingsOwnerId, settingsRoutePresentation.clear, settingsSheetPresentation.onDismissed]),
606 );
607​
608 useEffect(
609 () =>
610 // UIKit's completion callback for the sheet dismissal, surfaced by the
611 // native-stack patch. This is when the queued keyboard restore runs.
612 (navigation as unknown as NavigationWithFinishTransitioning).addListener(
613 "finishTransitioning",
614 settingsSheetPresentation.onStackTransitionsFinished,
615 ),
616 [navigation, settingsSheetPresentation.onStackTransitionsFinished],
617 );
618​
619 return (
620 <Animated.View
621 className="px-[12px]"
622 style={{
623 paddingTop: isExpanded ? 8 : 6,
624 paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 8 : 6),
625 backgroundColor:
626 Platform.OS === "android" ? themeColorWithAlpha(composerPanel, 1) : undefined,
627 }}
628 >
629 {/* The backdrop gradient lives on a plain View: Reanimated's Animated.View
630 silently drops experimental_backgroundImage on Android, which left this
631 strip fully transparent and the feed text legible through the composer. */}
632 <View
633 className={
634 Platform.OS === "android"
635 ? "hidden"
636 : "absolute inset-0 bg-linear-to-b from-screen/0 via-screen/60 to-screen/90"
637 }
638 pointerEvents="none"
639 />
640 <Animated.View
641 className="relative w-full self-center"
642 style={{ maxWidth: props.contentMaxWidth }}
643 >
644 {!voiceInput.isBusy &&
645 composerMenu.trigger &&
646 (composerMenu.items.length > 0 || composerMenu.trigger.kind === "pull-request") ? (
647 <View className="absolute inset-x-0 bottom-full z-10 mb-2">
648 <ComposerCommandPopover
649 items={composerMenu.items}
650 triggerKind={composerMenu.trigger.kind}
651 isLoading={composerMenu.isLoading}
652 error={composerMenu.error}
653 onSelect={composerMenu.onSelect}
654 />
655 </View>
656 ) : null}
657​
658 {modelUnavailable ? (
659 <Pressable accessibilityRole="button" className="px-3 py-2" onPress={openSettings}>
660 <Text className="text-xs text-foreground">Model unavailable. Open model settings.</Text>
661 </Pressable>
662 ) : null}
663​
664 <ComposerSurface
665 style={
666 isExpanded
667 ? {
668 borderRadius: 26,
669 minHeight: 140,
670 overflow: "hidden" as const,
671 paddingBottom: 6,
672 paddingTop: 14,
673 }
674 : {
675 // Keep the numeric radius close to the expanded card so the
676 // shape morph stays bounded while rendering as a capsule.
677 borderRadius: 27,
678 overflow: "hidden" as const,
679 paddingVertical: 2,
680 }
681 }
682 >
683 <ComposerDictationDraftContent
684 className={isExpanded ? undefined : "flex-row items-center"}
685 compact={!isExpanded}
686 hidden={showsCompactDictation}
687 >
688 {!isExpanded ? (
689 <ComposerAttachmentButton
690 supportsFiles={Boolean(
691 props.serverConfig?.environment.capabilities.fileAttachments,
692 )}
693 onPickMedia={props.onPickDraftMedia}
694 onPickFiles={props.onPickDraftFiles}
695 />
696 ) : null}
697 {isExpanded && stripAttachments.length > 0 ? (
698 <Animated.View
699 className="px-[14px] pb-2.5"
700 entering={COMPOSER_ATTACHMENT_ENTERING}
701 exiting={FadeOut.duration(120)}
702 >
703 <ComposerAttachmentStrip
704 environmentId={props.environmentId}
705 attachments={stripAttachments}
706 onRemove={voiceInput.isBusy ? () => undefined : props.onRemoveDraftImage}
707 onPressPreview={voiceInput.isBusy ? undefined : onPressPreview}
708 onPressVideo={voiceInput.isBusy ? undefined : onPressVideo}
709 onPressDocument={
710 voiceInput.isBusy
711 ? undefined
712 : (attachment) =>
713 openDraftDocument({
714 attachmentId: attachment.id,
715 name: attachment.name,
716 mimeType: attachment.mimeType,
717 sizeBytes: attachment.sizeBytes,
718 })
719 }
720 />
721 </Animated.View>
722 ) : null}
723 <Animated.View
724 className={isExpanded ? "px-[14px]" : "min-w-0 flex-1 px-[4px]"}
725 layout={COMPOSER_LAYOUT_TRANSITION}
726 >
727 <ComposerEditor
728 draftKey={composerOwnerKey}
729 environmentId={props.environmentId}
730 onOpenMention={(path) => {
731 Keyboard.dismiss();
732 navigation.navigate("ThreadFile", {
733 environmentId: String(props.environmentId),
734 threadId: String(props.selectedThread.id),
735 path: fileRoutePathSegments(path),
736 });
737 }}
738 onOpenAttachment={openDraftDocument}
739 // A rested composer full of chips left almost nowhere to tap to start typing:
740 // every chip opened its file instead. Collapsed, they focus the editor.
741 chipsInert={!isExpanded}
742 onInertChipPress={() => inputRef.current?.focus()}
743 ref={inputRef}
744 multiline
745 value={props.draftMessage}
746 readOnly={voiceInput.freezesEditor}
747 skills={composerMenu.skills}
748 selection={composerMenu.selection}
749 onChangeText={props.onChangeDraftMessage}
750 onSelectionChange={composerMenu.onSelectionChange}
751 onPasteImages={(uris) => void props.onNativePasteImages(uris)}
752 onPasteText={(paste) => {
753 const insertPaste = () => {
754 const insertion = replaceTextSelection({
755 value: paste.value,
756 selection: paste.selection,
757 text: paste.text,
758 });
759 const selection = { start: insertion.cursor, end: insertion.cursor };
760 props.onChangeDraftMessage(insertion.value);
761 composerMenu.onSelectionChange(selection);
762 };
763 const capabilities = props.serverConfig?.environment.capabilities;
764 const advertisedMax =
765 capabilities?.attachmentUploads === true
766 ? capabilities.fileAttachments?.maxUploadBytes
767 : undefined;
768 const maxBytes =
769 advertisedMax === undefined
770 ? null
771 : clampFileAttachmentUploadBytes(advertisedMax);
772 const wouldExceedInputLimit =
773 paste.value.length -
774 Math.max(0, paste.selection.end - paste.selection.start) +
775 paste.text.length >
776 PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
777 const canAttach =
778 maxBytes !== null &&
779 countComposerDraftAttachmentsAfterSelection(composerOwnerKey, {
780 text: paste.value,
781 ...paste.selection,
782 }) < PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
783 new TextEncoder().encode(paste.text).byteLength <= maxBytes;
784 if (
785 pastedTextDisposition({
786 text: paste.text,
787 wouldExceedInputLimit,
788 canAttach: true,
789 }) === "attachment"
790 ) {
791 if (canAttach) {
792 pendingPastedTextAttachmentCountRef.current += 1;
793 setPendingPastedTextAttachmentCount(
794 pendingPastedTextAttachmentCountRef.current,
795 );
796 const finishAttachment = () => {
797 pendingPastedTextAttachmentCountRef.current = Math.max(
798 0,
799 pendingPastedTextAttachmentCountRef.current - 1,
800 );
801 setPendingPastedTextAttachmentCount(
802 pendingPastedTextAttachmentCountRef.current,
803 );
804 };
805 void props.onNativePasteText(paste).then(finishAttachment, finishAttachment);
806 } else if (!wouldExceedInputLimit) {
807 insertPaste();
808 } else {
809 Alert.alert(
810 wouldExceedInputLimit
811 ? "Pasted text is too large for this message"
812 : "Could not attach pasted text",
813 wouldExceedInputLimit
814 ? "Remove some text or an attachment, then paste again."
815 : "Remove an attachment or use a smaller paste, then try again.",
816 );
817 }
818 return;
819 }
820 insertPaste();
821 }}
822 placeholder={props.placeholder}
823 onFocus={handleFocus}
824 onBlur={handleBlur}
825 onSubmit={handleSend}
826 scrollEnabled={isExpanded}
827 // Android: collapsed single line centers natively (gravity) in
828 // a pill-height box matching the send button; iOS keeps insets.
829 singleLineCentered={!isExpanded}
830 contentInsetVertical={isExpanded || Platform.OS === "android" ? 0 : 6}
831 style={
832 isExpanded
833 ? {
834 minHeight: 72,
835 maxHeight: 160,
836 paddingVertical: 4,
837 }
838 : {
839 height: 36,
840 }
841 }
842 textStyle={{
843 ...bodyText,
844 color: foregroundColor,
845 }}
846 />
847 </Animated.View>
848 {!isExpanded && stripAttachments.length > 0 ? (
849 <View className="flex-row gap-1 pl-1">
850 {stripAttachments.slice(0, 3).map((attachment) => (
851 <ComposerAttachmentThumbnail
852 environmentId={props.environmentId}
853 key={attachment.id}
854 attachment={attachment}
855 size={30}
856 borderRadius={8}
857 compact
858 onPressPreview={onPressPreview}
859 onPressVideo={onPressVideo}
860 />
861 ))}
862 {stripAttachments.length > 3 ? (
863 <View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
864 <Text className="text-foreground-muted text-2xs font-t3-bold">
865 +{stripAttachments.length - 3}
866 </Text>
867 </View>
868 ) : null}
869 </View>
870 ) : null}
871 {!isExpanded ? (
872 <View className="flex-row items-center">
873 <ComposerDictationStartAction
874 state={voiceInput.state}
875 isAvailable={voiceInput.isAvailable}
876 onStart={voiceInput.start}
877 onCancel={voiceInput.cancel}
878 />
879 {showStopAction ? (
880 <ComposerActionButton
881 accessibilityLabel="Stop agent"
882 icon="stop.fill"
883 variant="danger"
884 onPress={props.onStopThread}
885 />
886 ) : (
887 <ComposerActionButton
888 accessibilityLabel={sendBlockedReason ?? sendLabel}
889 icon="arrow.up"
890 variant="primary"
891 disabled={!canSend}
892 onPress={handleSend}
893 />
894 )}
895 </View>
896 ) : null}
897 {isExpanded ? <View className="h-1" /> : null}
898 </ComposerDictationDraftContent>
899 <Animated.View
900 accessibilityElementsHidden={!isToolbarVisible}
901 collapsable={false}
902 importantForAccessibility={isToolbarVisible ? "auto" : "no-hide-descendants"}
903 layout={COMPOSER_LAYOUT_TRANSITION}
904 pointerEvents={isToolbarVisible ? "auto" : "none"}
905 style={
906 isExpanded
907 ? undefined
908 : {
909 position: "absolute",
910 bottom: 2,
911 left: 0,
912 right: 0,
913 }
914 }
915 >
916 <ComposerDictationToolbar
917 showsDictation={isVoiceInputPresented}
918 visible={isToolbarVisible}
919 >
920 <ComposerToolbarRow
921 paddingBottom={0}
922 paddingHorizontal={0}
923 paddingTop={0}
924 style={{ gap: 0 }}
925 >
926 <ComposerDictationCancelAction
927 presentation={voicePresentation}
928 onCancel={voiceInput.cancel}
929 />
930 {isVoiceInputPresented ? (
931 <ComposerDictationStatus
932 audioLevels={voiceInput.audioLevels}
933 elapsedSeconds={voiceInput.elapsedSeconds}
934 phase={voiceInput.state.phase}
935 presentation={voicePresentation}
936 onDismissError={voiceInput.cancel}
937 />
938 ) : (
939 <View className="min-w-0 flex-1 flex-row items-center justify-between">
940 <ComposerAttachmentButton
941 supportsFiles={Boolean(
942 props.serverConfig?.environment.capabilities.fileAttachments,
943 )}
944 onPickMedia={props.onPickDraftMedia}
945 onPickFiles={props.onPickDraftFiles}
946 />
947 <View className="min-w-0 shrink">
948 <ComposerInlineControl
949 accessibilityLabel="Model and reasoning settings"
950 emphasized
951 iconNode={
952 <ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
953 }
954 label={currentModelOption?.label ?? currentModelSelection.model}
955 maxWidth="100%"
956 onPress={openSettings}
957 />
958 </View>
959 </View>
960 )}
961 <View className="shrink-0 flex-row items-center">
962 <ComposerDictationPrimaryAction
963 state={voiceInput.state}
964 presentation={voicePresentation}
965 isAvailable={voiceInput.isAvailable}
966 onStart={voiceInput.start}
967 onConfirm={voiceInput.stop}
968 onCancel={voiceInput.cancel}
969 />
970 {showStopAction ? (
971 <ComposerActionButton
972 accessibilityLabel="Stop agent"
973 icon="stop.fill"
974 variant="danger"
975 onPress={props.onStopThread}
976 />
977 ) : voicePresentation.showsSend ? (
978 <ComposerActionButton
979 accessibilityLabel={sendBlockedReason ?? sendLabel}
980 icon="arrow.up"
981 variant="primary"
982 disabled={!canSend}
983 onPress={handleSend}
984 />
985 ) : null}
986 </View>
987 </ComposerToolbarRow>
988 </ComposerDictationToolbar>
989 </Animated.View>
990 </ComposerSurface>
991 </Animated.View>
992​
993 <VideoPreviewModal source={previewVideo} onRequestClose={closePreview} />
994 <FilePreviewModal source={previewFile} onRequestClose={closePreview} />
995 </Animated.View>
996 );
997});