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