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

ThreadComposer.tsx

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