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