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