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