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

ThreadComposer.tsx

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