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

ThreadComposer.tsx

1,012 lines41.1 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: (providerCommand?: string) => 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={colors["--color-composer-surface"]}
248 fallbackClassName="border border-composer-border"
249 glassEffectStyle="regular"
250 // The composer is a passive material containing interactive controls.
251 // Keep native glass out of the interactive content's layout path.
252 pointerEvents="none"
253 tintColor="transparent"
254 layout={layoutTransition}
255 style={[{ position: "absolute", inset: 0 }, animatedShapeStyle]}
256 >
257 {null}
258 </AnimatedGlassSurface>
259 <Animated.View
260 collapsable={false}
261 layout={layoutTransition}
262 style={[props.style, animatedShapeStyle]}
263 >
264 {props.children}
265 </Animated.View>
266 </Animated.View>
267 );
269​
270export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) {
271 const project = useProject(scopeProjectRef(props.environmentId, props.selectedThread.projectId));
272 const { themeVariables: materialTheme } = useAppearancePreferences();
273 const composerPanel = materialTheme["--color-composer-panel"];
274 const navigation = useNavigation();
275 const foregroundColor = useUniwindTheme()["--color-foreground"];
276 const bodyText = useScaledTextRole("body");
277 const fallbackInputRef = useRef<ComposerEditorHandle>(null);
278 const inputRef = props.editorRef ?? fallbackInputRef;
279 const [isFocused, setIsFocused] = useState(false);
280 const pendingPastedTextAttachmentCountRef = useRef(0);
281 const [pendingPastedTextAttachmentCount, setPendingPastedTextAttachmentCount] = useState(0);
282 const settingsSheetPresentation = useThreadSettingsSheetPresentation({
283 editorRef: inputRef,
284 isEditorFocused: isFocused,
285 });
286 const settingsRoutePresentation = useExistingThreadSettingsRoutePresentation();
287 const settingsRoutePresentedRef = useRef(false);
288 const wasExpandedBeforePreviewRef = useRef(false);
289 const inFlightThreadIdsRef = useRef(new Set<string>());
290 const { onExpandedChange } = props;
291​
292 const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
293 const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);
294 const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
295 // Only media belongs above the composer; every other file reads as its inline chip.
296 const stripAttachments = useMemo(
297 () => composerStripAttachments(props.draftAttachments),
298 [props.draftAttachments],
299 );
300 const showStopAction =
301 !hasContent &&
302 (props.selectedThread.session?.status === "running" ||
303 props.selectedThread.session?.status === "starting");
304​
305 const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
306 const attachmentsUploading =
307 props.connectionState === "connected" &&
308 composerAttachmentsStillUploading({
309 environmentId: props.environmentId,
310 attachments: props.draftAttachments,
311 serverConfig: props.serverConfig,
312 states: uploadStates,
313 });
314 // Every send goes through the outbox; the label says whether it leaves now
315 // or waits (for the connection, an earlier queued message, or an upload).
316 const sendLabel =
317 props.connectionState !== "connected" || props.queueCount > 0 || attachmentsUploading
318 ? "Queue"
319 : "Send";
320 const currentModelSelection = props.selectedThread.modelSelection;
321 const currentRuntimeMode = props.selectedThread.runtimeMode;
322 const modelUnavailable =
323 props.connectionState === "connected" &&
324 isModelSelectionUnavailable(props.serverConfig, currentModelSelection);
325 const selectedProviderStatus = useMemo(() => {
326 if (!props.serverConfig) return null;
327 return (
328 props.serverConfig.providers.find(
329 (p) => p.instanceId === props.selectedThread.modelSelection.instanceId,
330 ) ?? null
331 );
332 }, [props.serverConfig, props.selectedThread.modelSelection.instanceId]);
333 const composerOwnerKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
334 const openDraftDocument = (attachment: ComposerDocumentAttachment) => {
335 Keyboard.dismiss();
336 navigation.navigate("ThreadAttachment", {
337 environmentId: String(props.environmentId),
338 threadId: String(props.selectedThread.id),
339 attachmentId: attachment.attachmentId,
340 name: attachment.name,
341 mimeType: attachment.mimeType,
342 sizeBytes: String(attachment.sizeBytes),
343 draftKey: composerOwnerKey,
344 });
345 };
346 const { onSendMessage, onChangeDraftMessage, onShowUsageLimits } = props;
347 // T3 owns /usage-limits only where Limits has data for the selected provider;
348 // elsewhere the name stays the provider's own and is sent through untouched.
349 const usageLimitsOffered =
350 selectedProviderStatus !== null &&
351 hasProviderUsageLimits(
352 selectedProviderStatus.driver,
353 props.serverConfig?.providers ?? [],
354 props.serverConfig?.usageLimitSources ?? [],
355 );
356 // Answered locally from the last Limits snapshot; the agent never sees it.
357 const openUsageLimits = useCallback(() => {
358 const report = collectProviderUsageLimits(
359 currentModelSelection.instanceId,
360 props.serverConfig?.providers ?? [],
361 props.serverConfig?.usageLimitSources ?? [],
362 Date.now(),
363 );
364 onShowUsageLimits(report);
365 if (!report) {
366 Alert.alert("Usage limits unavailable", "This provider does not currently report limits.");
367 }
368 return report !== null;
369 }, [currentModelSelection.instanceId, onShowUsageLimits, props.serverConfig]);
370​
371 const composerMenu = useComposerCommandMenu({
372 draftMessage: props.draftMessage,
373 ownerKey: composerOwnerKey,
374 environmentId: props.environmentId,
375 projectCwd: props.projectCwd,
376 pullRequestProjectId: props.serverConfig?.environment.capabilities.pullRequests
377 ? (project?.id ?? null)
378 : null,
379 pullRequestRepository: project?.repositoryIdentity?.displayName ?? null,
380 selectedProviderStatus,
381 hasThread: true,
382 hasCompactableConversation: props.hasCompactableConversation,
383 onChangeDraftMessage: props.onChangeDraftMessage,
384 onUpdateInteractionMode:
385 selectedProviderStatus?.showInteractionModeToggle === false
386 ? undefined
387 : props.onUpdateInteractionMode,
388 offersUsageLimits: usageLimitsOffered,
389 // With attachments aboard the pick just inserts the text, so it sends as a prompt.
390 onUsageLimits:
391 usageLimitsOffered && props.draftAttachments.length === 0 ? openUsageLimits : undefined,
392 onProviderCommand:
393 props.draftAttachments.length === 0 ? (name) => void onSendMessage(name) : undefined,
394 });
395 const voiceInput = useVoiceInputController({
396 ownerKey: composerOwnerKey,
397 draftMessage: props.draftMessage,
398 selection: composerMenu.selection,
399 onChangeDraftMessage: props.onChangeDraftMessage,
400 onChangeSelection: composerMenu.onSelectionChange,
401 });
402 const voicePresentation = resolveVoiceComposerPresentation(
403 voiceInput.state,
404 voiceInput.elapsedSeconds,
405 );
406 const isVoiceInputPresented = voicePresentation.statusLabel !== null;
407 // An open draft stays visible; only a collapsed composer becomes a voice strip.
408 const isExpanded = isFocused || settingsSheetPresentation.keepsComposerExpanded;
409 const showsCompactDictation = isVoiceInputPresented && !isExpanded;
410 const isToolbarVisible = isExpanded || isVoiceInputPresented;
411 const attachmentBlockReason = composerAttachmentUploadBlockReason({
412 environmentId: props.environmentId,
413 attachments: props.draftAttachments,
414 connected: props.connectionState === "connected",
415 serverConfig: props.serverConfig,
416 states: uploadStates,
417 });
418 const contextImports = useAtomValue(composerContextImportsAtom);
419 const sendBlockedReason =
420 props.sendBlockedReason ??
421 (pendingPastedTextAttachmentCount > 0 ? "Attaching pasted text" : null) ??
422 attachmentBlockReason;
423 const canSend =
424 hasContent &&
425 !contextImports[composerOwnerKey] &&
426 !voiceInput.blocksSubmission &&
427 sendBlockedReason === null &&
428 !modelUnavailable;
429​
430 // Keep the feed inset aligned with the card or compact dictation strip.
431 useEffect(() => {
432 onExpandedChange?.(isExpanded);
433 }, [isExpanded, onExpandedChange]);
434​
435 const onPressPreview = useCallback(
436 (source: FilePreviewSource) => {
437 wasExpandedBeforePreviewRef.current = isFocused;
438 setPreviewVideo(null);
439 setPreviewFile((current) => current ?? source);
440 },
441 [isFocused],
442 );
443​
444 const closePreview = useCallback(() => {
445 setPreviewFile(null);
446 setPreviewVideo(null);
447 if (wasExpandedBeforePreviewRef.current) {
448 setTimeout(() => {
449 if (navigation.isFocused()) inputRef.current?.focus();
450 }, 100);
451 }
452 }, [inputRef, navigation]);
453​
454 const onPressVideo = useCallback(
455 (attachment: DraftComposerFileAttachment, sourceIdentifier: string) => {
456 wasExpandedBeforePreviewRef.current = isFocused;
457 setPreviewFile(null);
458 setPreviewVideo((current) => current ?? { type: "local", attachment, sourceIdentifier });
459 },
460 [isFocused],
461 );
462​
463 const onEditorFocusChange = props.onEditorFocusChange;
464 const handleFocus = useCallback(() => {
465 setIsFocused(true);
466 onExpandedChange?.(true);
467 onEditorFocusChange?.(true);
468 }, [onEditorFocusChange, onExpandedChange]);
469​
470 const handleBlur = useCallback(() => {
471 setIsFocused(false);
472 if (!settingsSheetPresentation.keepsComposerExpanded) {
473 onExpandedChange?.(false);
474 }
475 onEditorFocusChange?.(false);
476 }, [onEditorFocusChange, onExpandedChange, settingsSheetPresentation.keepsComposerExpanded]);
477 const handleSend = useCallback(async () => {
478 if (voiceInput.blocksSubmission || pendingPastedTextAttachmentCountRef.current > 0) return;
479 // Typed out in full rather than picked from the menu. Attachments mean the
480 // user is sending a prompt, so those go through as usual.
481 if (
482 usageLimitsOffered &&
483 isUsageLimitsCommand(props.draftMessage) &&
484 props.draftAttachments.length === 0
485 ) {
486 if (openUsageLimits()) onChangeDraftMessage("");
487 return;
488 }
489 const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
490 if (inFlightThreadIdsRef.current.has(threadKey)) return;
491 inFlightThreadIdsRef.current.add(threadKey);
492 try {
493 const messageId = await onSendMessage();
494 if (messageId === null) {
495 return;
496 }
497 // Sending a prompt starts agent work: arm the lock-screen card while the
498 // app is foregrounded and the activity token can be registered. Armed
499 // after the send so its preference read and native Activity start don't
500 // contend with the queued-message feedback on the tap frame.
501 armAgentAwarenessLiveActivityForLocalWork({
502 environmentId: props.environmentId,
503 threadTitle: props.selectedThread.title,
504 projectTitle: props.environmentLabel ?? "T3 Code",
505 });
506 } finally {
507 inFlightThreadIdsRef.current.delete(threadKey);
508 }
509 }, [
510 props.draftMessage,
511 props.draftAttachments.length,
512 onChangeDraftMessage,
513 openUsageLimits,
514 usageLimitsOffered,
515 onSendMessage,
516 props.environmentId,
517 props.environmentLabel,
518 props.selectedThread.id,
519 props.selectedThread.title,
520 voiceInput.blocksSubmission,
521 ]);
522​
523 // ── Model menu ───────────────────────────────────────────
524 const modelOptions = useMemo(
525 () => buildModelOptions(props.serverConfig, currentModelSelection),
526 [props.serverConfig, currentModelSelection],
527 );
528 const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
529 // An existing thread is bound to its harness: sessions can't move between
530 // provider instances, so the picker only offers the thread's own group.
531 const threadProviderGroups = useMemo(
532 () => providerGroups.filter((group) => group.providerKey === currentModelSelection.instanceId),
533 [providerGroups, currentModelSelection.instanceId],
534 );
535 const currentModelOption =
536 modelOptions.find(
537 (option) =>
538 option.selection.instanceId === currentModelSelection.instanceId &&
539 option.selection.model === currentModelSelection.model,
540 ) ?? null;
541 const providerOptionDescriptors = useMemo(
542 () =>
543 resolveProviderOptionDescriptors({
544 capabilities: currentModelOption?.capabilities,
545 selections: currentModelSelection.options,
546 }),
547 [currentModelOption?.capabilities, currentModelSelection.options],
548 );
549 const settingsOwnerId = composerOwnerKey;
550 const settingsRouteSession = useMemo<ExistingThreadSettingsRouteSession>(
551 () => ({
552 ownerId: settingsOwnerId,
553 environmentId: props.environmentId,
554 providerInstanceId: currentModelSelection.instanceId,
555 providerGroups: threadProviderGroups,
556 selectedModel: currentModelSelection,
557 onSelectModel: (option) => props.onUpdateModelSelection(option.selection),
558 optionDescriptors: providerOptionDescriptors,
559 onUpdateOptionSelections: (options) =>
560 props.onUpdateModelSelection({ ...currentModelSelection, options }),
561 runtimeMode: currentRuntimeMode,
562 onUpdateRuntimeMode: props.onUpdateRuntimeMode,
563 }),
564 [
565 currentModelSelection,
566 currentRuntimeMode,
567 props.onUpdateModelSelection,
568 props.onUpdateRuntimeMode,
569 providerOptionDescriptors,
570 settingsOwnerId,
571 threadProviderGroups,
572 ],
573 );
574 const openSettings = useCallback(() => {
575 settingsRoutePresentation.present(settingsRouteSession);
576 settingsSheetPresentation.open();
577 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.open]);
578​
579 useEffect(() => {
580 if (settingsSheetPresentation.isActive) {
581 settingsRoutePresentation.present(settingsRouteSession);
582 }
583 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.isActive]);
584​
585 useEffect(() => {
586 if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
587 return;
588 }
589​
590 settingsRoutePresentedRef.current = true;
591 navigation.dispatch(StackActions.push("ThreadSettingsSheet"));
592 }, [navigation, settingsSheetPresentation.isVisible]);
593​
594 useFocusEffect(
595 useCallback(() => {
596 if (!settingsRoutePresentedRef.current) {
597 return;
598 }
599​
600 settingsRoutePresentedRef.current = false;
601 settingsSheetPresentation.onDismissed();
602 settingsRoutePresentation.clear(settingsOwnerId);
603 }, [settingsOwnerId, settingsRoutePresentation.clear, settingsSheetPresentation.onDismissed]),
604 );
605​
606 useEffect(
607 () =>
608 // UIKit's completion callback for the sheet dismissal, surfaced by the
609 // native-stack patch. This is when the queued keyboard restore runs.
610 (navigation as unknown as NavigationWithFinishTransitioning).addListener(
611 "finishTransitioning",
612 settingsSheetPresentation.onStackTransitionsFinished,
613 ),
614 [navigation, settingsSheetPresentation.onStackTransitionsFinished],
615 );
616​
617 return (
618 <Animated.View
619 className="px-[12px]"
620 style={{
621 paddingTop: isExpanded ? 8 : 6,
622 paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 8 : 6),
623 backgroundColor:
624 Platform.OS === "android" ? themeColorWithAlpha(composerPanel, 1) : undefined,
625 }}
626 >
627 {/* The backdrop gradient lives on a plain View: Reanimated's Animated.View
628 silently drops experimental_backgroundImage on Android, which left this
629 strip fully transparent and the feed text legible through the composer. */}
630 <View
631 className={
632 Platform.OS === "android"
633 ? "hidden"
634 : "absolute inset-0 bg-linear-to-b from-screen/0 via-screen/60 to-screen/90"
635 }
636 pointerEvents="none"
637 />
638 <Animated.View
639 className="relative w-full self-center"
640 style={{ maxWidth: props.contentMaxWidth }}
641 >
642 {!voiceInput.isBusy &&
643 composerMenu.trigger &&
644 (composerMenu.items.length > 0 || composerMenu.trigger.kind === "pull-request") ? (
645 <View className="absolute inset-x-0 bottom-full z-10 mb-2">
646 <ComposerCommandPopover
647 items={composerMenu.items}
648 triggerKind={composerMenu.trigger.kind}
649 isLoading={composerMenu.isLoading}
650 error={composerMenu.error}
651 onSelect={composerMenu.onSelect}
652 />
653 </View>
654 ) : null}
655​
656 {selectedProviderStatus?.compatibilityAdvisory?.message &&
657 (selectedProviderStatus.compatibilityAdvisory.status === "unsupported" ||
658 selectedProviderStatus.compatibilityAdvisory.status === "broken") ? (
659 <Text
660 accessibilityRole={
661 selectedProviderStatus.compatibilityAdvisory.status === "broken" ? "alert" : undefined
662 }
663 accessibilityLiveRegion={
664 selectedProviderStatus.compatibilityAdvisory.status === "broken"
665 ? "assertive"
666 : "polite"
667 }
668 className="px-3 py-2 text-xs text-foreground"
669 >
670 {selectedProviderStatus.compatibilityAdvisory.message}
671 </Text>
672 ) : null}
673 {modelUnavailable ? (
674 <Pressable accessibilityRole="button" className="px-3 py-2" onPress={openSettings}>
675 <Text className="text-xs text-foreground">Model unavailable. Open model settings.</Text>
676 </Pressable>
677 ) : null}
678​
679 <ComposerSurface
680 style={
681 isExpanded
682 ? {
683 borderRadius: 26,
684 minHeight: 140,
685 overflow: "hidden" as const,
686 paddingBottom: 6,
687 paddingTop: 14,
688 }
689 : {
690 // Keep the numeric radius close to the expanded card so the
691 // shape morph stays bounded while rendering as a capsule.
692 borderRadius: 27,
693 overflow: "hidden" as const,
694 paddingVertical: 2,
695 }
696 }
697 >
698 <ComposerDictationDraftContent
699 className={isExpanded ? undefined : "flex-row items-center"}
700 compact={!isExpanded}
701 hidden={showsCompactDictation}
702 >
703 {!isExpanded ? (
704 <ComposerAttachmentButton
705 supportsFiles={Boolean(
706 props.serverConfig?.environment.capabilities.fileAttachments,
707 )}
708 onPickMedia={props.onPickDraftMedia}
709 onPickFiles={props.onPickDraftFiles}
710 />
711 ) : null}
712 {isExpanded && stripAttachments.length > 0 ? (
713 <Animated.View
714 className="px-[14px] pb-2.5"
715 entering={COMPOSER_ATTACHMENT_ENTERING}
716 exiting={FadeOut.duration(120)}
717 >
718 <ComposerAttachmentStrip
719 environmentId={props.environmentId}
720 attachments={stripAttachments}
721 onRemove={voiceInput.isBusy ? () => undefined : props.onRemoveDraftImage}
722 onPressPreview={voiceInput.isBusy ? undefined : onPressPreview}
723 onPressVideo={voiceInput.isBusy ? undefined : onPressVideo}
724 onPressDocument={
725 voiceInput.isBusy
726 ? undefined
727 : (attachment) =>
728 openDraftDocument({
729 attachmentId: attachment.id,
730 name: attachment.name,
731 mimeType: attachment.mimeType,
732 sizeBytes: attachment.sizeBytes,
733 })
734 }
735 />
736 </Animated.View>
737 ) : null}
738 <Animated.View
739 className={isExpanded ? "px-[14px]" : "min-w-0 flex-1 px-[4px]"}
740 layout={COMPOSER_LAYOUT_TRANSITION}
741 >
742 <ComposerEditor
743 draftKey={composerOwnerKey}
744 environmentId={props.environmentId}
745 onOpenMention={(path) => {
746 Keyboard.dismiss();
747 navigation.navigate("ThreadFile", {
748 environmentId: String(props.environmentId),
749 threadId: String(props.selectedThread.id),
750 path: fileRoutePathSegments(path),
751 });
752 }}
753 onOpenAttachment={openDraftDocument}
754 // A rested composer full of chips left almost nowhere to tap to start typing:
755 // every chip opened its file instead. Collapsed, they focus the editor.
756 chipsInert={!isExpanded}
757 onInertChipPress={() => inputRef.current?.focus()}
758 ref={inputRef}
759 multiline
760 value={props.draftMessage}
761 readOnly={voiceInput.freezesEditor}
762 skills={composerMenu.skills}
763 selection={composerMenu.selection}
764 onChangeText={props.onChangeDraftMessage}
765 onSelectionChange={composerMenu.onSelectionChange}
766 onPasteImages={(uris) => void props.onNativePasteImages(uris)}
767 onPasteText={(paste) => {
768 const insertPaste = () => {
769 const insertion = replaceTextSelection({
770 value: paste.value,
771 selection: paste.selection,
772 text: paste.text,
773 });
774 const selection = { start: insertion.cursor, end: insertion.cursor };
775 props.onChangeDraftMessage(insertion.value);
776 composerMenu.onSelectionChange(selection);
777 };
778 const capabilities = props.serverConfig?.environment.capabilities;
779 const advertisedMax =
780 capabilities?.attachmentUploads === true
781 ? capabilities.fileAttachments?.maxUploadBytes
782 : undefined;
783 const maxBytes =
784 advertisedMax === undefined
785 ? null
786 : clampFileAttachmentUploadBytes(advertisedMax);
787 const wouldExceedInputLimit =
788 paste.value.length -
789 Math.max(0, paste.selection.end - paste.selection.start) +
790 paste.text.length >
791 PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
792 const canAttach =
793 maxBytes !== null &&
794 countComposerDraftAttachmentsAfterSelection(composerOwnerKey, {
795 text: paste.value,
796 ...paste.selection,
797 }) < PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
798 new TextEncoder().encode(paste.text).byteLength <= maxBytes;
799 if (
800 pastedTextDisposition({
801 text: paste.text,
802 wouldExceedInputLimit,
803 canAttach: true,
804 }) === "attachment"
805 ) {
806 if (canAttach) {
807 pendingPastedTextAttachmentCountRef.current += 1;
808 setPendingPastedTextAttachmentCount(
809 pendingPastedTextAttachmentCountRef.current,
810 );
811 const finishAttachment = () => {
812 pendingPastedTextAttachmentCountRef.current = Math.max(
813 0,
814 pendingPastedTextAttachmentCountRef.current - 1,
815 );
816 setPendingPastedTextAttachmentCount(
817 pendingPastedTextAttachmentCountRef.current,
818 );
819 };
820 void props.onNativePasteText(paste).then(finishAttachment, finishAttachment);
821 } else if (!wouldExceedInputLimit) {
822 insertPaste();
823 } else {
824 Alert.alert(
825 wouldExceedInputLimit
826 ? "Pasted text is too large for this message"
827 : "Could not attach pasted text",
828 wouldExceedInputLimit
829 ? "Remove some text or an attachment, then paste again."
830 : "Remove an attachment or use a smaller paste, then try again.",
831 );
832 }
833 return;
834 }
835 insertPaste();
836 }}
837 placeholder={props.placeholder}
838 onFocus={handleFocus}
839 onBlur={handleBlur}
840 onSubmit={handleSend}
841 scrollEnabled={isExpanded}
842 // Android: collapsed single line centers natively (gravity) in
843 // a pill-height box matching the send button; iOS keeps insets.
844 singleLineCentered={!isExpanded}
845 contentInsetVertical={isExpanded || Platform.OS === "android" ? 0 : 6}
846 style={
847 isExpanded
848 ? {
849 minHeight: 72,
850 maxHeight: 160,
851 paddingVertical: 4,
852 }
853 : {
854 height: 36,
855 }
856 }
857 textStyle={{
858 ...bodyText,
859 color: foregroundColor,
860 }}
861 />
862 </Animated.View>
863 {!isExpanded && stripAttachments.length > 0 ? (
864 <View className="flex-row gap-1 pl-1">
865 {stripAttachments.slice(0, 3).map((attachment) => (
866 <ComposerAttachmentThumbnail
867 environmentId={props.environmentId}
868 key={attachment.id}
869 attachment={attachment}
870 size={30}
871 borderRadius={8}
872 compact
873 onPressPreview={onPressPreview}
874 onPressVideo={onPressVideo}
875 />
876 ))}
877 {stripAttachments.length > 3 ? (
878 <View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
879 <Text className="text-foreground-muted text-2xs font-t3-bold">
880 +{stripAttachments.length - 3}
881 </Text>
882 </View>
883 ) : null}
884 </View>
885 ) : null}
886 {!isExpanded ? (
887 <View className="flex-row items-center">
888 <ComposerDictationStartAction
889 state={voiceInput.state}
890 isAvailable={voiceInput.isAvailable}
891 onStart={voiceInput.start}
892 onCancel={voiceInput.cancel}
893 />
894 {showStopAction ? (
895 <ComposerActionButton
896 accessibilityLabel="Stop agent"
897 icon="stop.fill"
898 variant="danger"
899 onPress={props.onStopThread}
900 />
901 ) : (
902 <ComposerActionButton
903 accessibilityLabel={sendBlockedReason ?? sendLabel}
904 icon="arrow.up"
905 variant="primary"
906 disabled={!canSend}
907 onPress={handleSend}
908 />
909 )}
910 </View>
911 ) : null}
912 {isExpanded ? <View className="h-1" /> : null}
913 </ComposerDictationDraftContent>
914 <Animated.View
915 accessibilityElementsHidden={!isToolbarVisible}
916 collapsable={false}
917 importantForAccessibility={isToolbarVisible ? "auto" : "no-hide-descendants"}
918 layout={COMPOSER_LAYOUT_TRANSITION}
919 pointerEvents={isToolbarVisible ? "auto" : "none"}
920 style={
921 isExpanded
922 ? undefined
923 : {
924 position: "absolute",
925 bottom: 2,
926 left: 0,
927 right: 0,
928 }
929 }
930 >
931 <ComposerDictationToolbar
932 showsDictation={isVoiceInputPresented}
933 visible={isToolbarVisible}
934 >
935 <ComposerToolbarRow
936 paddingBottom={0}
937 paddingHorizontal={0}
938 paddingTop={0}
939 style={{ gap: 0 }}
940 >
941 <ComposerDictationCancelAction
942 presentation={voicePresentation}
943 onCancel={voiceInput.cancel}
944 />
945 {isVoiceInputPresented ? (
946 <ComposerDictationStatus
947 audioLevels={voiceInput.audioLevels}
948 elapsedSeconds={voiceInput.elapsedSeconds}
949 phase={voiceInput.state.phase}
950 presentation={voicePresentation}
951 onDismissError={voiceInput.cancel}
952 />
953 ) : (
954 <View className="min-w-0 flex-1 flex-row items-center justify-between">
955 <ComposerAttachmentButton
956 supportsFiles={Boolean(
957 props.serverConfig?.environment.capabilities.fileAttachments,
958 )}
959 onPickMedia={props.onPickDraftMedia}
960 onPickFiles={props.onPickDraftFiles}
961 />
962 <View className="min-w-0 shrink">
963 <ComposerInlineControl
964 accessibilityLabel="Model and reasoning settings"
965 emphasized
966 renderIcon={(size) => (
967 <ProviderIcon provider={currentModelOption?.providerDriver} size={size} />
968 )}
969 label={currentModelOption?.label ?? currentModelSelection.model}
970 maxWidth="100%"
971 onPress={openSettings}
972 />
973 </View>
974 </View>
975 )}
976 <View className="shrink-0 flex-row items-center">
977 <ComposerDictationPrimaryAction
978 state={voiceInput.state}
979 presentation={voicePresentation}
980 isAvailable={voiceInput.isAvailable}
981 onStart={voiceInput.start}
982 onConfirm={voiceInput.stop}
983 onCancel={voiceInput.cancel}
984 />
985 {showStopAction ? (
986 <ComposerActionButton
987 accessibilityLabel="Stop agent"
988 icon="stop.fill"
989 variant="danger"
990 onPress={props.onStopThread}
991 />
992 ) : voicePresentation.showsSend ? (
993 <ComposerActionButton
994 accessibilityLabel={sendBlockedReason ?? sendLabel}
995 icon="arrow.up"
996 variant="primary"
997 disabled={!canSend}
998 onPress={handleSend}
999 />
1000 ) : null}
1001 </View>
1002 </ComposerToolbarRow>
1003 </ComposerDictationToolbar>
1004 </Animated.View>
1005 </ComposerSurface>
1006 </Animated.View>
1007​
1008 <VideoPreviewModal source={previewVideo} onRequestClose={closePreview} />
1009 <FilePreviewModal source={previewFile} onRequestClose={closePreview} />
1010 </Animated.View>
1011 );
1012});