@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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