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 { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
5import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
6import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
7import { AsyncResult } from "effect/reactivity";
8import { useAtomValue } from "@effect/atom-react";
9import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
10import { pastedTextDisposition, replaceTextSelection } from "@t3tools/client-runtime/text-paste";
11import {
12 AuthOrchestrationOperateScope,
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 ServerConfig as T3ServerConfig,
20 type UsageLimitsReport,
21} from "@t3tools/contracts";
22import {
23 collectProviderUsageLimits,
24 hasProviderUsageLimits,
25 isUsageLimitsCommand,
26} from "@t3tools/shared/usageLimits";
27import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";
28import { msg, T, useGT, useMessages } from "gt-react-native";
29import type { ReactNode } from "react";
30import { useEffect, useEffectEvent, useRef, useState, type RefObject } from "react";
31import { Keyboard, Platform, View } from "react-native";
32import { composerImageGallery } from "../../lib/composerImageGallery";
33import { filePreviewGallery } from "../../lib/filePreviewGallery";
34import { FilePreviewModal, type FilePreviewSource } from "../../components/ui/FilePreviewModal";
35import {
36 composerAttachmentUploadBlockReason,
37 composerAttachmentsStillUploading,
38 composerAttachmentUploadsAtom,
39} from "../../state/composer-attachment-uploads";
40import Animated, { FadeIn, FadeOut, ReduceMotion } from "react-native-reanimated";
41import { useUniwindTheme } from "../../lib/useUniwindTheme";
42import { themeColorWithAlpha } from "../../lib/mobileTheme";
43import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
44import { scopedThreadKey } from "../../lib/scopedEntities";
45import {
46 getComposerDraftSnapshot,
47 setComposerDraftText,
48 composerContextImportsAtom,
49 countComposerDraftAttachmentsAfterSelection,
50 useComposerDraft,
51 useComposerDraftResetGeneration,
52} from "../../state/use-composer-drafts";
53import type { ComposerDocumentAttachment } from "../../lib/composerContext";
54import { useProject, useVisibleThreadShells } from "../../state/entities";
55import { useMentionableEnvironments } from "../../state/environments";
56import { useLinkedEnvironments } from "../../state/peerLinks";
57import { useEnvironmentScopeDenied } from "../../state/session";
58import { scopeProjectRef } from "@t3tools/client-runtime/environment";
59
60import { AppText as Text } from "../../components/ui/AppText";
61import { ComposerAttachmentButton } from "./ComposerAttachmentButton";
62import {
63 ComposerAttachmentStrip,
64 ComposerAttachmentThumbnail,
65} from "../../components/ComposerAttachmentStrip";
66import { VideoPreviewModal, type VideoPreviewSource } from "../../components/ui/VideoPreviewModal";
67import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
68import {
69 COMPOSER_BOTTOM_GUTTER,
70 COMPOSER_TRANSITION_DURATION_MS,
71 ComposerSurface,
72 INLINE_EDITOR_MIN_WIDTH,
73 useComposerChrome,
74 useCompactComposerEditor,
75} from "../../components/ComposerSurface";
76import { fileRoutePathSegments } from "../files/filePath";
77import {
78 ComposerActionButton,
79 ComposerInlineControl,
80 ComposerToolbarRow,
81} from "../../components/ComposerToolbar";
82import { formatTokens } from "@t3tools/shared/usageFormat";
83import { ComposerModelControl } from "../../components/ComposerModelControl";
84import {
85 composerStripAttachments,
86 type DraftComposerFileAttachment,
87} from "../../lib/composerImages";
88import { composerAttachmentUploadKey } from "../../lib/composerAttachmentUploadQueue";
89import {
90 buildModelOptions,
91 isModelSelectionUnavailable,
92 serverConfigForCwd,
93} from "../../lib/modelOptions";
94import { useComposerTextRole } from "../settings/appearance/useScaledTextRole";
95import type { RemoteClientConnectionState } from "../../lib/connection";
96import { Menu } from "../../components/ui/Menu";
97import {
98 composerRunsDraftLocally,
99 type ActiveTurnComposerAction,
100} from "@t3tools/client-runtime/state/composer-dispatch";
101import type { FollowUpBehavior } from "../../lib/followUpBehavior";
102import {
103 resolveComposerSendPresentation,
104 type ComposerSendPresentation,
105} from "./composerSendPresentation";
106import { useSubmitAfterNativeImages } from "./useSubmitAfterNativeImages";
107import { ComposerCommandPopover } from "./ComposerCommandPopover";
108import { ComposerPopoverAnchor } from "./ComposerPopoverAnchor";
109import { ComposerQueuedEditAttachments } from "./ComposerQueuedEdit";
110import { useComposerCommandMenu } from "./use-composer-command-menu";
111import type { ComposerEnvironmentCandidate } from "@t3tools/client-runtime/composerThreadItems";
112import { offersLinkedEnvironments } from "@t3tools/client-runtime/link-request";
113import {
114 ComposerDictationCancelAction,
115 ComposerDictationDraftContent,
116 ComposerDictationError,
117 ComposerDictationPrimaryAction,
118 ComposerDictationStartAction,
119 ComposerDictationStatus,
120 ComposerDictationToolbar,
121} from "../voice-input/ComposerDictationControl";
122import { useVoiceInputController } from "../voice-input/useVoiceInputController";
123import { resolveVoiceComposerPresentation } from "../voice-input/voiceInputPresentation";
124import type { ExistingThreadSettingsRouteParams } from "./ThreadSettingsSheet";
125import {
126 useThreadSettingsSheetPresentation,
127 type NavigationWithFinishTransitioning,
128} from "./use-thread-settings-sheet-presentation";
129
130export const COMPOSER_COLLAPSED_CHROME = 60;
131export const THREAD_COMPOSER_BOTTOM_GUTTER = COMPOSER_BOTTOM_GUTTER;
132
133const NO_MACHINES: ReadonlyArray<ComposerEnvironmentCandidate> = [];
134
135export interface ThreadComposerProps {
136 readonly isDraft?: boolean;
137 readonly canOperateThread: boolean;
138 readonly placeholder: string;
139 readonly contentMaxWidth?: number;
140 readonly draftControls?: ReactNode;
141 readonly bottomInset?: number;
142 readonly connectionState: RemoteClientConnectionState;
143 readonly environmentLabel: string | null;
144 readonly selectedThread: EnvironmentThreadShell;
145 readonly reportedModelSelection?: ModelSelection | null;
146 readonly hasCompactableConversation: boolean;
147 /** Set while the next send compacts the thread first. */
148 readonly compactBeforeSend?: {
149 readonly tokens: number;
150 readonly keepFullHistory: boolean;
151 readonly toggleKeepFullHistory: () => void;
152 } | null;
153 /** Arms a fresh session for the next message; absent where `/clear` is unavailable. */
154 readonly onFreshSession?: () => void;
155 readonly offersSideChat?: boolean;
156 readonly serverConfig: T3ServerConfig | null;
157 readonly queueCount: number;
158 readonly activeThreadBusy: boolean;
159 /** Sending declines a pending approval and redirects the agent, so `/side` is plain text. */
160 readonly redirectsApproval: boolean;
161 readonly canStopThread: boolean;
162 readonly environmentId: EnvironmentId;
163 readonly projectCwd: string | null;
164 readonly sendBlockedReason?: string | null;
165 readonly interactionLocked?: boolean;
166 readonly draftKey?: string;
167 readonly queuedEdit?: {
168 readonly existingAttachments: ReadonlyArray<ChatAttachment>;
169 readonly saving: boolean;
170 readonly onRemoveExistingAttachment: (attachmentId: string) => void;
171 } | null;
172 readonly followUpBehavior: FollowUpBehavior;
173 readonly canSteerActiveTurn: boolean;
174 readonly hidden: boolean;
175 readonly editorRef?: RefObject<ComposerEditorHandle | null>;
176 readonly onChangeDraftMessage: (value: string) => void;
177 readonly onPickDraftMedia: () => Promise<void>;
178 readonly onPickDraftFiles: () => Promise<void>;
179 readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<boolean>;
180 readonly onNativePasteText: (paste: ComposerTextPaste) => Promise<void>;
181 readonly onRemoveDraftImage: (imageId: string) => void;
182 readonly onStopThread: () => void;
183 /** Present while the thread's queue is held. */
184 readonly onResumeQueue: (() => Promise<void>) | null;
185 /** `stillSendable` reports whether the draft is unchanged after any wait before sending. */
186 readonly onSendMessage: (
187 followUp?: ActiveTurnComposerAction,
188 stillSendable?: () => boolean,
189 ) => Promise<MessageId | null>;
190 readonly onShowUsageLimits: (report: UsageLimitsReport | null) => void;
191 readonly canSwitchProvider: boolean;
192 readonly onHeightChange?: (height: number) => void;
193 readonly onEditorFocusChange?: (focused: boolean) => void;
194}
195
196const COMPOSER_ATTACHMENT_ENTERING =
197 Platform.OS === "android"
198 ? FadeIn.duration(160)
199 : FadeIn.delay(COMPOSER_TRANSITION_DURATION_MS).duration(160).reduceMotion(ReduceMotion.System);
200
201const FOLLOW_UP_ACTION_LABEL = {
202 queue: msg("Queue", { $context: "verb, send after the current turn" }),
203 steer: msg("Steer now"),
204 restart: msg("Restart turn"),
205} as const;
206
207const FOLLOW_UP_ACTION_SUBTITLE = {
208 queue: msg("Run after the current turn"),
209 steer: msg("Interrupt what the agent is doing"),
210 restart: msg("Start the turn over with this message"),
211} as const;
212
213function SendActionButton(props: {
214 readonly size?: "regular" | "large";
215 readonly accessibilityLabel: string;
216 readonly presentation: ComposerSendPresentation;
217 readonly disabled: boolean;
218 readonly onSend: (followUp?: ActiveTurnComposerAction) => void;
219}) {
220 const { presentation } = props;
221 const gt = useGT();
222 const m = useMessages();
223 const button = (
224 <ComposerActionButton
225 accessibilityLabel={props.accessibilityLabel}
226 size={props.size}
227 icon={presentation.icon}
228 variant="primary"
229 disabled={props.disabled}
230 onPress={() => props.onSend()}
231 />
232 );
233 if (!presentation.offersFollowUpChoice || presentation.action === null || props.disabled) {
234 return button;
235 }
236 const actions = [presentation.action, presentation.alternate].filter(
237 (action): action is ActiveTurnComposerAction => action !== null,
238 );
239 return (
240 <Menu
241 accessibilityLabel={gt("Choose how to send this message")}
242 shouldOpenOnLongPress
243 actions={actions.map((action) => ({
244 id: action,
245 title: m(FOLLOW_UP_ACTION_LABEL[action]),
246 subtitle: m(FOLLOW_UP_ACTION_SUBTITLE[action]),
247 state: action === presentation.action ? ("on" as const) : ("off" as const),
248 }))}
249 onPressAction={({ nativeEvent }) =>
250 props.onSend(nativeEvent.event as ActiveTurnComposerAction)
251 }
252 >
253 {button}
254 </Menu>
255 );
256}
257
258export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps) {
259 const gt = useGT();
260 const messages = useMessages();
261 const project = useProject(scopeProjectRef(props.environmentId, props.selectedThread.projectId));
262 const { themeVariables: materialTheme } = useAppearancePreferences();
263 const composerPanel = materialTheme["--color-composer-panel"];
264 const navigation = useNavigation();
265 const foregroundColor = useUniwindTheme()["--color-foreground"];
266 const bodyText = useComposerTextRole();
267 const fallbackInputRef = useRef<ComposerEditorHandle>(null);
268 const inputRef = props.editorRef ?? fallbackInputRef;
269 const [isFocused, setIsFocused] = useState(false);
270 const pendingPastedTextAttachmentCountRef = useRef(0);
271 const pendingNativeImagePasteCountRef = useRef(0);
272 const [pendingPastedTextAttachmentCount, setPendingPastedTextAttachmentCount] = useState(0);
273 const settingsRoutePresentedRef = useRef(false);
274 const settingsSheetPresentation = useThreadSettingsSheetPresentation({
275 editorRef: inputRef,
276 onPresent: () => {
277 if (settingsRoutePresentedRef.current) return;
278 settingsRoutePresentedRef.current = true;
279 // The draft composer edits the new-task flow, which owns its own settings route.
280 navigation.dispatch(
281 props.isDraft
282 ? StackActions.push("NewTaskThreadSettings")
283 : StackActions.push("ThreadSettingsSheet", {
284 environmentId: props.environmentId,
285 threadId: props.selectedThread.id,
286 draftKey: composerDraftKey,
287 } satisfies ExistingThreadSettingsRouteParams),
288 );
289 },
290 });
291 const disposeSettingsSheetPresentation = useEffectEvent(settingsSheetPresentation.dispose);
292 const wasExpandedBeforePreviewRef = useRef(false);
293 const inFlightThreadIdsRef = useRef(new Set<string>());
294
295 const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
296 const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);
297 const composerOwnerKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
298 const composerDraftKey = props.draftKey ?? composerOwnerKey;
299 const readResetGeneration = useComposerDraftResetGeneration(composerDraftKey);
300 const {
301 text: draftMessage,
302 attachments: draftAttachments,
303 context: draftContext,
304 } = useComposerDraft(composerDraftKey);
305 const queuedEdit = props.queuedEdit ?? null;
306 const hasContent =
307 draftMessage.trim().length > 0 ||
308 draftAttachments.length > 0 ||
309 (queuedEdit?.existingAttachments.length ?? 0) > 0;
310 const showStopAction = !hasContent && props.canStopThread && queuedEdit === null;
311 const onResumeQueue = props.onResumeQueue;
312 const [resumingQueue, setResumingQueue] = useState(false);
313 const showResumeAction =
314 !hasContent && !showStopAction && queuedEdit === null && onResumeQueue !== null;
315 const handleResumeQueue = async () => {
316 if (resumingQueue || onResumeQueue === null) return;
317 setResumingQueue(true);
318 await onResumeQueue();
319 setResumingQueue(false);
320 };
321
322 const operateDenied = useEnvironmentScopeDenied(
323 props.environmentId,
324 AuthOrchestrationOperateScope,
325 );
326 const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
327 const stripAttachments = composerStripAttachments(
328 draftAttachments,
329 (attachment) => uploadStates[composerAttachmentUploadKey(props.environmentId, attachment.id)],
330 );
331 const attachmentsUploading =
332 props.connectionState === "connected" &&
333 composerAttachmentsStillUploading({
334 environmentId: props.environmentId,
335 attachments: draftAttachments,
336 serverConfig: props.serverConfig,
337 states: uploadStates,
338 });
339 const currentModelSelection = props.selectedThread.modelSelection;
340 const modelUnavailable =
341 props.connectionState === "connected" &&
342 isModelSelectionUnavailable(
343 props.serverConfig,
344 currentModelSelection,
345 props.selectedThread.projectId,
346 );
347 const selectedProviderStatus = (() => {
348 if (!props.serverConfig) return null;
349 return (
350 props.serverConfig.providers.find(
351 (p) => p.instanceId === props.selectedThread.modelSelection.instanceId,
352 ) ?? null
353 );
354 })();
355 const openDraftDocument = (attachment: ComposerDocumentAttachment) => {
356 Keyboard.dismiss();
357 navigation.navigate("ThreadAttachment", {
358 environmentId: String(props.environmentId),
359 threadId: String(props.selectedThread.id),
360 attachmentId: attachment.attachmentId,
361 name: attachment.name,
362 mimeType: attachment.mimeType,
363 sizeBytes: String(attachment.sizeBytes),
364 draftKey: composerDraftKey,
365 });
366 };
367 const { onSendMessage, onChangeDraftMessage, onShowUsageLimits } = props;
368 const usageLimitsOffered =
369 selectedProviderStatus !== null &&
370 hasProviderUsageLimits(
371 selectedProviderStatus.driver,
372 props.serverConfig?.providers ?? [],
373 props.serverConfig?.usageLimitSources ?? [],
374 );
375 const draftRunsLocally = composerRunsDraftLocally({
376 text: draftMessage,
377 holdsOnlyText: draftAttachments.length === 0,
378 // A redirect's text answers its approval, so `/side` there is that text.
379 sideChat: !props.redirectsApproval,
380 usageLimits: usageLimitsOffered,
381 codexFeedback: selectedProviderStatus?.driver === "codex",
382 freshSession: props.onFreshSession !== undefined && draftContext === undefined,
383 });
384 const sendPresentation = resolveComposerSendPresentation(
385 {
386 editingQueuedMessage: queuedEdit !== null,
387 running: props.activeThreadBusy && !draftRunsLocally,
388 canSteer: props.canSteerActiveTurn,
389 followUpBehavior: props.followUpBehavior,
390 deliveryDeferred:
391 !draftRunsLocally &&
392 (props.connectionState !== "connected" || props.queueCount > 0 || attachmentsUploading),
393 },
394 messages,
395 );
396 const sendLabel = sendPresentation.label;
397 const openUsageLimits = () => {
398 const report = collectProviderUsageLimits(
399 currentModelSelection.instanceId,
400 props.serverConfig?.providers ?? [],
401 props.serverConfig?.usageLimitSources ?? [],
402 Date.now(),
403 );
404 onShowUsageLimits(report);
405 if (!report) {
406 Dialog.alert(
407 gt("Usage limits unavailable"),
408 gt("This provider does not currently report limits."),
409 );
410 }
411 return report !== null;
412 };
413
414 const mentionableEnvironments = useMentionableEnvironments();
415 // Mentions name any model for the agent, so they aren't limited to models this thread can switch to.
416 const mentionModelOptions = buildModelOptions(
417 props.serverConfig,
418 currentModelSelection,
419 undefined,
420 props.selectedThread.projectId,
421 );
422 const composerMenu = useComposerCommandMenu({
423 draftMessage: draftMessage,
424 ownerKey: composerDraftKey,
425 environmentId: props.environmentId,
426 threadShells: useVisibleThreadShells(),
427 environments: offersLinkedEnvironments(props.serverConfig)
428 ? mentionableEnvironments
429 : NO_MACHINES,
430 linkedEnvironments: useLinkedEnvironments(props.environmentId),
431 currentThreadId: props.selectedThread.id,
432 projectCwd: props.projectCwd,
433 pullRequestProjectId: props.serverConfig ? (project?.id ?? null) : null,
434 pullRequestRepository: project?.repositoryIdentity?.displayName ?? null,
435 threadPullRequests: props.selectedThread.pullRequests,
436 selectedProviderStatus,
437 hasThread: !props.isDraft,
438 hasCompactableConversation: props.hasCompactableConversation,
439 onChangeDraftMessage: props.onChangeDraftMessage,
440 offersUsageLimits: usageLimitsOffered,
441 onUsageLimits:
442 usageLimitsOffered && draftAttachments.length === 0 ? openUsageLimits : undefined,
443 onOpenModelPicker: settingsSheetPresentation.open,
444 modelOptions: mentionModelOptions,
445 modelProviders: props.serverConfig?.providers,
446 ...(props.onFreshSession === undefined ? {} : { onFreshSession: props.onFreshSession }),
447 offersSideChat: props.offersSideChat === true,
448 });
449 const voiceInput = useVoiceInputController({
450 ownerKey: composerDraftKey,
451 label: props.selectedThread.title || gt("Untitled thread"),
452 readDraftMessage: () => getComposerDraftSnapshot(composerDraftKey).text,
453 selection: composerMenu.selection,
454 onChangeDraftMessage: (text) => setComposerDraftText(composerDraftKey, text),
455 onChangeSelection: composerMenu.onSelectionChange,
456 });
457 const isSubmissionLocked =
458 props.interactionLocked === true || queuedEdit?.saving === true || voiceInput.blocksSubmission;
459 const voicePresentation = resolveVoiceComposerPresentation(
460 voiceInput.state,
461 voiceInput.elapsedSeconds,
462 messages,
463 );
464 const isVoiceInputPresented = voicePresentation.statusKind === "active";
465 const isExpanded = isFocused || settingsSheetPresentation.keepsComposerExpanded;
466 const { usesLargeControls, paddingVertical: surfacePaddingVertical } = useComposerChrome();
467 const [compactRowWidth, setCompactRowWidth] = useState(0);
468 const compactAttachmentLimit = compactRowWidth >= 500 ? 3 : 1;
469 // Animate only while typing; a thread switch or restored draft lands in place.
470 const compactEditor = useCompactComposerEditor(
471 bodyText,
472 draftMessage,
473 Platform.OS === "ios" && isFocused,
474 );
475 const showsCompactDictation = isVoiceInputPresented;
476 const isToolbarVisible = isVoiceInputPresented;
477 const hasEditingAttachments =
478 (queuedEdit !== null && queuedEdit.existingAttachments.length > 0) ||
479 stripAttachments.length > 0;
480 const attachmentBlockReason = composerAttachmentUploadBlockReason(
481 {
482 environmentId: props.environmentId,
483 attachments: draftAttachments,
484 connected: props.connectionState === "connected",
485 serverConfig: props.serverConfig,
486 states: uploadStates,
487 },
488 messages,
489 );
490 const contextImports = useAtomValue(composerContextImportsAtom);
491 const sendBlockedReason =
492 (queuedEdit?.saving === true ? gt("Saving…") : null) ??
493 props.sendBlockedReason ??
494 (pendingPastedTextAttachmentCount > 0 ? gt("Attaching pasted text") : null) ??
495 attachmentBlockReason;
496 const canSend =
497 (props.canOperateThread || props.connectionState !== "connected") &&
498 hasContent &&
499 !contextImports[composerDraftKey] &&
500 !isSubmissionLocked &&
501 sendBlockedReason === null &&
502 !modelUnavailable;
503
504 // A pending sheet presentation or focus restore has no composer left to act on.
505 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- disposes the pending settings sheet presentation and focus restore on unmount
506 useEffect(() => () => disposeSettingsSheetPresentation(), []);
507
508 const onPressPreview = (source: FilePreviewSource) => {
509 wasExpandedBeforePreviewRef.current = isFocused;
510 setPreviewVideo(null);
511 setPreviewFile(
512 (current) =>
513 current ?? {
514 ...source,
515 gallery: filePreviewGallery(source, composerImageGallery(draftAttachments)),
516 },
517 );
518 };
519
520 const closePreview = () => {
521 setPreviewFile(null);
522 setPreviewVideo(null);
523 if (wasExpandedBeforePreviewRef.current) {
524 setTimeout(() => {
525 if (navigation.isFocused()) inputRef.current?.focus();
526 }, 100);
527 }
528 };
529
530 const onPressVideo = (attachment: DraftComposerFileAttachment, sourceIdentifier: string) => {
531 wasExpandedBeforePreviewRef.current = isFocused;
532 setPreviewFile(null);
533 setPreviewVideo((current) => current ?? { type: "local", attachment, sourceIdentifier });
534 };
535
536 const onEditorFocusChange = props.onEditorFocusChange;
537 const handleFocus = () => {
538 setIsFocused(true);
539 settingsSheetPresentation.onEditorFocusChange(true);
540 onEditorFocusChange?.(true);
541 };
542
543 const handleBlur = () => {
544 setIsFocused(false);
545 settingsSheetPresentation.onEditorFocusChange(false);
546 onEditorFocusChange?.(false);
547 };
548 const handleSend = async (followUp?: ActiveTurnComposerAction) => {
549 if (isSubmissionLocked || sendBlockedReason !== null) return;
550 // Sending now would leave a still-converting pasted image out of the turn, so wait for it.
551 if (nativeImageSubmit.deferSend(followUp)) return;
552 if (pendingPastedTextAttachmentCountRef.current > 0) return;
553 if (usageLimitsOffered && isUsageLimitsCommand(draftMessage) && draftAttachments.length === 0) {
554 if (openUsageLimits()) onChangeDraftMessage("");
555 return;
556 }
557 const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
558 if (inFlightThreadIdsRef.current.has(threadKey)) return;
559 inFlightThreadIdsRef.current.add(threadKey);
560 await inputRef.current?.flushPendingInput();
561 const draftAtSend = getComposerDraftSnapshot(composerDraftKey);
562 const stillSendable = () => {
563 const draft = getComposerDraftSnapshot(composerDraftKey);
564 return (
565 pendingPastedTextAttachmentCountRef.current === 0 &&
566 pendingNativeImagePasteCountRef.current === 0 &&
567 draft.text === draftAtSend.text &&
568 draft.attachments.length === draftAtSend.attachments.length &&
569 draft.attachments.every(
570 (attachment, index) => attachment.id === draftAtSend.attachments[index]?.id,
571 )
572 );
573 };
574 const sent = await settlePromise(() => onSendMessage(followUp, stillSendable));
575 inFlightThreadIdsRef.current.delete(threadKey);
576 if (AsyncResult.isFailure(sent)) {
577 console.error("[composer] send failed", squashAtomCommandFailure(sent));
578 return;
579 }
580 if (sent.value === null) return;
581 // Arm after send so preference reads and native Activity startup do not delay tap-frame feedback.
582 armAgentAwarenessLiveActivityForLocalWork({
583 environmentId: props.environmentId,
584 threadTitle: props.selectedThread.title,
585 projectTitle: props.environmentLabel ?? "T3 Code",
586 });
587 };
588
589 const nativeImageSubmit = useSubmitAfterNativeImages({
590 draftKey: composerDraftKey,
591 readResetGeneration,
592 blocked: isSubmissionLocked || sendBlockedReason !== null,
593 onPasteImages: props.onNativePasteImages,
594 onSubmit: (followUp) => void handleSend(followUp),
595 });
596
597 const lockedProviderInstanceId = props.canSwitchProvider
598 ? undefined
599 : currentModelSelection.instanceId;
600 const modelOptions = buildModelOptions(
601 serverConfigForCwd(props.serverConfig, props.projectCwd),
602 currentModelSelection,
603 lockedProviderInstanceId,
604 props.selectedThread.projectId,
605 );
606 const currentModelOption =
607 modelOptions.find(
608 (option) =>
609 option.selection.instanceId === currentModelSelection.instanceId &&
610 option.selection.model === currentModelSelection.model,
611 ) ?? null;
612 const openSettings = () => {
613 settingsSheetPresentation.open();
614 };
615
616 useFocusEffect(() => {
617 if (!settingsRoutePresentedRef.current) {
618 return;
619 }
620
621 settingsRoutePresentedRef.current = false;
622 settingsSheetPresentation.onDismissed();
623 });
624
625 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the native stack's finishTransitioning event to restore the keyboard after a sheet dismisses
626 useEffect(
627 () =>
628 // The native-stack patch exposes UIKit dismissal completion; restore the keyboard then.
629 (navigation as unknown as NavigationWithFinishTransitioning).addListener(
630 "finishTransitioning",
631 settingsSheetPresentation.onStackTransitionsFinished,
632 ),
633 [navigation, settingsSheetPresentation.onStackTransitionsFinished],
634 );
635
636 // Removable attachments: inside the card, or above the focused one-row composer.
637 const editingAttachments = hasEditingAttachments ? (
638 <>
639 {queuedEdit !== null && queuedEdit.existingAttachments.length > 0 ? (
640 <Animated.View
641 className="px-[14px] pb-2.5 pt-2"
642 entering={COMPOSER_ATTACHMENT_ENTERING}
643 exiting={FadeOut.duration(120)}
644 >
645 <ComposerQueuedEditAttachments
646 environmentId={props.environmentId}
647 attachments={queuedEdit.existingAttachments}
648 disabled={isSubmissionLocked}
649 onRemove={queuedEdit.onRemoveExistingAttachment}
650 />
651 </Animated.View>
652 ) : null}
653 {stripAttachments.length > 0 ? (
654 <Animated.View
655 className="px-[14px] pb-2.5 pt-2"
656 entering={COMPOSER_ATTACHMENT_ENTERING}
657 exiting={FadeOut.duration(120)}
658 >
659 <ComposerAttachmentStrip
660 environmentId={props.environmentId}
661 attachments={stripAttachments}
662 onRemove={isSubmissionLocked ? () => undefined : props.onRemoveDraftImage}
663 onPressPreview={isSubmissionLocked ? undefined : onPressPreview}
664 onPressVideo={isSubmissionLocked ? undefined : onPressVideo}
665 onPressDocument={
666 isSubmissionLocked
667 ? undefined
668 : (attachment) =>
669 openDraftDocument({
670 attachmentId: attachment.id,
671 name: attachment.name,
672 mimeType: attachment.mimeType,
673 sizeBytes: attachment.sizeBytes,
674 })
675 }
676 />
677 </Animated.View>
678 ) : null}
679 </>
680 ) : null;
681
682 const modelControl = (
683 // Only the expanded label can truncate; shrinking the icon-only control clips the icon.
684 <View className={compactEditor.isExpanded ? "min-w-0 shrink" : "shrink-0"}>
685 <ComposerModelControl
686 size={usesLargeControls ? "large" : "regular"}
687 modelOption={currentModelOption}
688 selection={currentModelSelection}
689 provider={selectedProviderStatus?.driver}
690 reportedSelection={props.reportedModelSelection}
691 prompt={draftMessage}
692 surfaceColor={composerPanel}
693 iconOnly={!compactEditor.isExpanded}
694 onPress={openSettings}
695 />
696 </View>
697 );
698
699 const compactBeforeSend =
700 props.compactBeforeSend && !showResumeAction && queuedEdit === null
701 ? props.compactBeforeSend
702 : null;
703 const compactTokens = compactBeforeSend ? formatTokens(compactBeforeSend.tokens) : null;
704 const compactControl =
705 compactBeforeSend && compactTokens !== null ? (
706 <ComposerInlineControl
707 size={usesLargeControls ? "large" : "regular"}
708 icon="arrow.down.right.and.arrow.up.left"
709 label={compactTokens}
710 selected={!compactBeforeSend.keepFullHistory}
711 showChevron={false}
712 disabled={!props.canOperateThread}
713 accessibilityLabel={
714 compactBeforeSend.keepFullHistory
715 ? gt("Next send keeps all {tokens} tokens of history", { tokens: compactTokens })
716 : gt("Next send compacts {tokens} tokens of history first", { tokens: compactTokens })
717 }
718 accessibilityHint={
719 compactBeforeSend.keepFullHistory ? gt("Compacts first") : gt("Keeps the full history")
720 }
721 onPress={compactBeforeSend.toggleKeepFullHistory}
722 />
723 ) : null;
724
725 return (
726 <Animated.View
727 onLayout={(event) => props.onHeightChange?.(event.nativeEvent.layout.height)}
728 className="px-[12px]"
729 style={{
730 paddingTop: 6,
731 paddingBottom: (props.bottomInset ?? 0) + THREAD_COMPOSER_BOTTOM_GUTTER,
732 backgroundColor:
733 Platform.OS === "android" ? themeColorWithAlpha(composerPanel, 1) : undefined,
734 }}
735 >
736 {/* Use a plain View: Reanimated Animated.View drops experimental_backgroundImage on Android. */}
737 <View
738 className={
739 Platform.OS === "android"
740 ? "hidden"
741 : "absolute inset-0 bg-linear-to-b from-screen/0 via-screen/60 to-screen/90"
742 }
743 pointerEvents="none"
744 />
745 <Animated.View
746 className="relative w-full self-center"
747 style={{ maxWidth: props.contentMaxWidth }}
748 >
749 {props.draftControls}
750 {!isSubmissionLocked &&
751 composerMenu.trigger &&
752 (composerMenu.items.length > 0 || composerMenu.trigger.kind === "pull-request") ? (
753 <ComposerPopoverAnchor>
754 <ComposerCommandPopover
755 items={composerMenu.items}
756 triggerKind={composerMenu.trigger.kind}
757 isLoading={composerMenu.isLoading}
758 error={composerMenu.error}
759 onSelect={composerMenu.onSelect}
760 />
761 </ComposerPopoverAnchor>
762 ) : null}
763
764 {selectedProviderStatus?.compatibilityAdvisory?.message &&
765 (selectedProviderStatus.compatibilityAdvisory.status === "unsupported" ||
766 selectedProviderStatus.compatibilityAdvisory.status === "broken") ? (
767 <Text
768 accessibilityRole={
769 selectedProviderStatus.compatibilityAdvisory.status === "broken" ? "alert" : undefined
770 }
771 accessibilityLiveRegion={
772 selectedProviderStatus.compatibilityAdvisory.status === "broken"
773 ? "assertive"
774 : "polite"
775 }
776 className={
777 selectedProviderStatus.compatibilityAdvisory.status === "broken"
778 ? "bg-danger px-3 py-2 text-xs text-danger-foreground"
779 : "px-3 py-2 text-xs text-foreground"
780 }
781 >
782 {selectedProviderStatus.compatibilityAdvisory.message}
783 </Text>
784 ) : null}
785 {modelUnavailable ? (
786 <Button
787 label={gt("Model unavailable. Open model settings.")}
788 tone="text"
789 onPress={openSettings}
790 />
791 ) : null}
792
793 <ComposerSurface
794 animateLayout={false}
795 style={{
796 borderRadius: usesLargeControls ? 31 : 27,
797 borderCurve: "circular",
798 overflow: "hidden",
799 paddingVertical: surfacePaddingVertical,
800 }}
801 >
802 <ComposerDictationError
803 error={voiceInput.state.phase === "error" ? voiceInput.state.error : null}
804 onDismiss={voiceInput.cancel}
805 />
806 {isExpanded ? editingAttachments : null}
807 <View
808 onLayout={(event) => {
809 compactEditor.onRowLayout(event);
810 setCompactRowWidth(event.nativeEvent.layout.width);
811 }}
812 >
813 <ComposerDictationDraftContent
814 className="flex-row items-end"
815 compact
816 hidden={showsCompactDictation}
817 >
818 <ComposerAttachmentButton
819 size={usesLargeControls ? "large" : "regular"}
820 disabled={isSubmissionLocked}
821 supportsFiles={props.serverConfig !== null}
822 onPickMedia={props.onPickDraftMedia}
823 onPickFiles={props.onPickDraftFiles}
824 />
825 <Animated.View
826 className="min-w-0 flex-1"
827 onLayout={compactEditor.onEditorLayout}
828 style={[
829 {
830 minWidth:
831 compactEditor.isExpanded ||
832 stripAttachments.length > 0 ||
833 compactControl !== null
834 ? 0
835 : INLINE_EDITOR_MIN_WIDTH,
836 },
837 compactEditor.containerStyle,
838 compactEditor.isExpanded ? { flex: 0, width: 0 } : undefined,
839 ]}
840 ></Animated.View>
841 {/* TalkBack orders siblings by position; outside this row the editor reads after Send. */}
842 <Animated.View
843 style={[
844 compactEditor.editorStyle,
845 showsCompactDictation ? { display: "none" } : undefined,
846 ]}
847 >
848 <ComposerEditor
849 hidden={props.hidden}
850 draftKey={composerDraftKey}
851 environmentId={props.environmentId}
852 onOpenMention={(path) => {
853 Keyboard.dismiss();
854 if (props.isDraft) {
855 navigation.navigate("NewTaskFile", {
856 environmentId: String(props.environmentId),
857 cwd: props.projectCwd ?? undefined,
858 path: fileRoutePathSegments(path),
859 });
860 } else {
861 navigation.navigate("ThreadFile", {
862 environmentId: String(props.environmentId),
863 threadId: String(props.selectedThread.id),
864 path: fileRoutePathSegments(path),
865 });
866 }
867 }}
868 onOpenAttachment={openDraftDocument}
869 chipsInert={!isExpanded}
870 onInertChipPress={() => inputRef.current?.focus()}
871 ref={inputRef}
872 multiline
873 value={draftMessage}
874 // The save uses a draft snapshot; further typing would be discarded on success.
875 readOnly={isSubmissionLocked}
876 skills={composerMenu.skills}
877 selection={composerMenu.selection}
878 onChangeText={(text) => {
879 if (!isSubmissionLocked) props.onChangeDraftMessage(text);
880 }}
881 onSelectionChange={composerMenu.onSelectionChange}
882 onPasteImages={(uris) => {
883 if (isSubmissionLocked) return;
884 pendingNativeImagePasteCountRef.current += 1;
885 void nativeImageSubmit.pasteImages(uris).finally(() => {
886 pendingNativeImagePasteCountRef.current -= 1;
887 });
888 }}
889 onPasteText={(paste) => {
890 if (isSubmissionLocked) return;
891 const insertPaste = () => {
892 const insertion = replaceTextSelection({
893 value: paste.value,
894 selection: paste.selection,
895 text: paste.text,
896 });
897 const selection = { start: insertion.cursor, end: insertion.cursor };
898 props.onChangeDraftMessage(insertion.value);
899 composerMenu.onSelectionChange(selection);
900 };
901 const capabilities = props.serverConfig?.environment.capabilities;
902 const advertisedMax = capabilities?.fileAttachments?.maxUploadBytes;
903 const maxBytes =
904 advertisedMax === undefined
905 ? null
906 : clampFileAttachmentUploadBytes(advertisedMax);
907 const wouldExceedInputLimit =
908 paste.value.length -
909 Math.max(0, paste.selection.end - paste.selection.start) +
910 paste.text.length >
911 PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
912 const canAttach =
913 maxBytes !== null &&
914 countComposerDraftAttachmentsAfterSelection(composerDraftKey, {
915 text: paste.value,
916 ...paste.selection,
917 }) < PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
918 new TextEncoder().encode(paste.text).byteLength <= maxBytes;
919 if (
920 pastedTextDisposition({
921 text: paste.text,
922 wouldExceedInputLimit,
923 canAttach: true,
924 }) === "attachment"
925 ) {
926 if (canAttach) {
927 pendingPastedTextAttachmentCountRef.current += 1;
928 setPendingPastedTextAttachmentCount(
929 pendingPastedTextAttachmentCountRef.current,
930 );
931 const finishAttachment = () => {
932 pendingPastedTextAttachmentCountRef.current = Math.max(
933 0,
934 pendingPastedTextAttachmentCountRef.current - 1,
935 );
936 setPendingPastedTextAttachmentCount(
937 pendingPastedTextAttachmentCountRef.current,
938 );
939 };
940 void props
941 .onNativePasteText(paste)
942 .then(finishAttachment, finishAttachment);
943 } else if (!wouldExceedInputLimit) {
944 insertPaste();
945 } else {
946 Dialog.alert(
947 gt("Pasted text is too large for this message"),
948 gt("Remove some text or an attachment, then paste again."),
949 );
950 }
951 return;
952 }
953 insertPaste();
954 }}
955 placeholder={props.placeholder}
956 onFocus={handleFocus}
957 onBlur={handleBlur}
958 onSubmit={(alternate) =>
959 void handleSend(
960 alternate && sendPresentation.alternate !== null
961 ? sendPresentation.alternate
962 : undefined,
963 )
964 }
965 submitTitle={sendPresentation.label}
966 alternateSubmitTitle={
967 sendPresentation.alternate === null
968 ? sendPresentation.label
969 : FOLLOW_UP_ACTION_LABEL[sendPresentation.alternate]
970 }
971 {...compactEditor.editorProps}
972 textStyle={{
973 ...bodyText,
974 color: foregroundColor,
975 }}
976 />
977 </Animated.View>
978 {!isExpanded && stripAttachments.length > 0 ? (
979 <View className="h-[44px] shrink-0 flex-row items-center gap-1 pl-1">
980 {stripAttachments.slice(0, compactAttachmentLimit).map((attachment) => (
981 <ComposerAttachmentThumbnail
982 environmentId={props.environmentId}
983 key={attachment.id}
984 attachment={attachment}
985 size={30}
986 borderRadius={8}
987 compact
988 onPressPreview={isSubmissionLocked ? undefined : onPressPreview}
989 onPressVideo={isSubmissionLocked ? undefined : onPressVideo}
990 />
991 ))}
992 {stripAttachments.length > compactAttachmentLimit ? (
993 <View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
994 <Text className="text-foreground-muted text-2xs font-t3-bold">
995 +{stripAttachments.length - compactAttachmentLimit}
996 </Text>
997 </View>
998 ) : null}
999 </View>
1000 ) : null}
1001 <View
1002 className="min-w-0 shrink flex-row items-center"
1003 style={
1004 compactEditor.isExpanded ? { flex: 1, justifyContent: "flex-end" } : undefined
1005 }
1006 >
1007 <Animated.View
1008 key={compactEditor.isExpanded ? "expanded" : "compact"}
1009 className="min-w-0 shrink flex-row items-center"
1010 entering={compactEditor.toolbarControlsEntering}
1011 >
1012 {compactControl}
1013 {modelControl}
1014 </Animated.View>
1015 <ComposerDictationStartAction
1016 size={usesLargeControls ? "large" : "regular"}
1017 state={voiceInput.state}
1018 isAvailable={voiceInput.isAvailable}
1019 disabled={isSubmissionLocked}
1020 onStart={voiceInput.start}
1021 onCancel={voiceInput.cancel}
1022 />
1023 {showStopAction ? (
1024 <ComposerActionButton
1025 size={usesLargeControls ? "large" : "regular"}
1026 accessibilityLabel={gt("Stop agent")}
1027 icon="stop.fill"
1028 variant="danger"
1029 disabled={!props.canOperateThread}
1030 onPress={props.onStopThread}
1031 />
1032 ) : showResumeAction ? (
1033 <ComposerActionButton
1034 size={usesLargeControls ? "large" : "regular"}
1035 accessibilityLabel={gt("Resume thread")}
1036 icon="play"
1037 disabled={!props.canOperateThread || resumingQueue}
1038 onPress={() => void handleResumeQueue()}
1039 />
1040 ) : (
1041 <SendActionButton
1042 size={usesLargeControls ? "large" : "regular"}
1043 accessibilityLabel={sendBlockedReason ?? sendLabel}
1044 presentation={sendPresentation}
1045 disabled={!canSend}
1046 onSend={handleSend}
1047 />
1048 )}
1049 </View>
1050 </ComposerDictationDraftContent>
1051 </View>
1052 <Animated.View
1053 accessibilityElementsHidden={!isToolbarVisible}
1054 collapsable={false}
1055 importantForAccessibility={isToolbarVisible ? "auto" : "no-hide-descendants"}
1056 pointerEvents={isToolbarVisible ? "auto" : "none"}
1057 style={{ position: "absolute", bottom: surfacePaddingVertical, left: 0, right: 0 }}
1058 >
1059 <ComposerDictationToolbar
1060 showsDictation={isVoiceInputPresented}
1061 visible={isToolbarVisible}
1062 >
1063 <ComposerToolbarRow
1064 paddingBottom={0}
1065 paddingHorizontal={0}
1066 paddingTop={0}
1067 style={{ gap: 0 }}
1068 >
1069 <ComposerDictationCancelAction
1070 size={usesLargeControls ? "large" : "regular"}
1071 presentation={voicePresentation}
1072 onCancel={voiceInput.cancel}
1073 />
1074 <ComposerDictationStatus
1075 audioLevels={voiceInput.audioLevels}
1076 elapsedSeconds={voiceInput.elapsedSeconds}
1077 phase={voiceInput.state.phase}
1078 presentation={voicePresentation}
1079 />
1080 <View className="shrink-0 flex-row items-center">
1081 <ComposerDictationPrimaryAction
1082 size={usesLargeControls ? "large" : "regular"}
1083 state={voiceInput.state}
1084 presentation={voicePresentation}
1085 isAvailable={voiceInput.isAvailable}
1086 disabled={isSubmissionLocked}
1087 onStart={voiceInput.start}
1088 onConfirm={voiceInput.stop}
1089 onCancel={voiceInput.cancel}
1090 />
1091 {showStopAction ? (
1092 <ComposerActionButton
1093 size={usesLargeControls ? "large" : "regular"}
1094 accessibilityLabel={gt("Stop agent")}
1095 icon="stop.fill"
1096 variant="danger"
1097 disabled={!props.canOperateThread}
1098 onPress={props.onStopThread}
1099 />
1100 ) : showResumeAction && voicePresentation.showsSend ? (
1101 <ComposerActionButton
1102 size={usesLargeControls ? "large" : "regular"}
1103 accessibilityLabel={gt("Resume thread")}
1104 icon="play"
1105 disabled={!props.canOperateThread || resumingQueue}
1106 onPress={() => void handleResumeQueue()}
1107 />
1108 ) : voicePresentation.showsSend ? (
1109 <SendActionButton
1110 size={usesLargeControls ? "large" : "regular"}
1111 accessibilityLabel={sendBlockedReason ?? sendLabel}
1112 presentation={sendPresentation}
1113 disabled={!canSend}
1114 onSend={handleSend}
1115 />
1116 ) : null}
1117 </View>
1118 </ComposerToolbarRow>
1119 </ComposerDictationToolbar>
1120 </Animated.View>
1121 </ComposerSurface>
1122
1123 {props.connectionState === "connected" && operateDenied ? (
1124 <Text className="pt-2 text-xs text-foreground-muted">
1125 <T>This connection cannot control this task. You can still edit your draft.</T>
1126 </Text>
1127 ) : null}
1128 </Animated.View>
1129
1130 <VideoPreviewModal source={previewVideo} onRequestClose={closePreview} />
1131 <FilePreviewModal source={previewFile} onRequestClose={closePreview} />
1132 </Animated.View>
1133 );
1134};