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

ThreadComposer.tsx

1,021 lines41.3 KB

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