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

ThreadComposer.tsx

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