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

ThreadComposer.tsx

1,163 lines48.0 KB

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