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