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

ThreadComposer.tsx

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