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

ThreadComposer.tsx

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