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

ThreadComposer.tsx

1,214 lines48.9 KB

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