Open History to see the last commit
1import * as Dialog from "../../components/ui/Dialog";
2import type { ComposerTextPaste } from "../../native/T3ComposerEditor.types";
3import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
4import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
5import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
6import { AsyncResult } from "effect/reactivity";
7import { useAtomValue } from "@effect/atom-react";
8import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
9import { pastedTextDisposition, replaceTextSelection } from "@t3tools/client-runtime/text-paste";
10import {
11 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
12 PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
13 type ChatAttachment,
14 type EnvironmentId,
15 type MessageId,
16 type ModelSelection,
17 type ProviderInteractionMode,
18 type RuntimeMode,
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 type { ReactNode } from "react";
29import { useEffect, useLayoutEffect, useRef, useState, type RefObject } from "react";
30import { Keyboard, Platform, Pressable, View, type ViewStyle } from "react-native";
31import { composerImageGallery } from "../../lib/composerImageGallery";
32import { filePreviewGallery } from "../../lib/filePreviewGallery";
33import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
34import {
35 composerAttachmentUploadBlockReason,
36 composerAttachmentsStillUploading,
37 composerAttachmentUploadsAtom,
38} from "../../state/composer-attachment-uploads";
39import Animated, {
40 FadeIn,
41 FadeOut,
42 type LayoutAnimationFunction,
43 ReduceMotion,
44 useAnimatedStyle,
45 useSharedValue,
46 withTiming,
47} from "react-native-reanimated";
48import { useUniwindTheme } from "../../lib/useUniwindTheme";
49import { themeColorWithAlpha } from "../../lib/mobileTheme";
50import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
51import { scopedThreadKey } from "../../lib/scopedEntities";
52import {
53 getComposerDraftSnapshot,
54 composerDraftsAtom,
55 setComposerDraftText,
56 composerContextImportsAtom,
57 countComposerDraftAttachmentsAfterSelection,
58 useComposerDraft,
59} from "../../state/use-composer-drafts";
60import { appAtomRegistry } from "../../state/atom-registry";
61import type { ComposerDocumentAttachment } from "../../lib/composerContext";
62import { useProject, useThreadShells } from "../../state/entities";
63import { scopeProjectRef } from "@t3tools/client-runtime/environment";
64
65import { AppText as Text } from "../../components/ui/AppText";
66import { ComposerAttachmentButton } from "./ComposerAttachmentButton";
67import {
68 ComposerAttachmentStrip,
69 ComposerAttachmentThumbnail,
70} from "../../components/ComposerAttachmentStrip";
71import { VideoPreviewModal, type VideoPreviewSource } from "../../components/VideoPreviewModal";
72import { GlassSurface } from "../../components/ui/GlassSurface";
73import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
74import { fileRoutePathSegments } from "../files/filePath";
75import {
76 ComposerActionButton,
77 ComposerInlineControl,
78 ComposerToolbarRow,
79} from "../../components/ComposerToolbar";
80import { ProviderIcon } from "../../components/ProviderIcon";
81import {
82 composerStripAttachments,
83 type DraftComposerFileAttachment,
84} from "../../lib/composerImages";
85import {
86 buildModelOptions,
87 groupByProvider,
88 isModelSelectionUnavailable,
89} from "../../lib/modelOptions";
90import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
91import type { RemoteClientConnectionState } from "../../lib/connection";
92import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
93import { Menu } from "../../components/ui/Menu";
94import type { ActiveTurnComposerAction } from "@t3tools/client-runtime/state/composer-dispatch";
95import type { FollowUpBehavior } from "../../lib/followUpBehavior";
96import {
97 resolveComposerSendPresentation,
98 type ComposerSendPresentation,
99} from "./composerSendPresentation";
100import { ComposerCommandPopover } from "./ComposerCommandPopover";
101import { ComposerPopoverAnchor } from "./ComposerPopoverAnchor";
102import { ComposerQueuedEditAttachments } from "./ComposerQueuedEdit";
103import { useComposerCommandMenu } from "./use-composer-command-menu";
104import {
105 ComposerDictationCancelAction,
106 ComposerDictationDraftContent,
107 ComposerDictationPrimaryAction,
108 ComposerDictationStartAction,
109 ComposerDictationStatus,
110 ComposerDictationToolbar,
111} from "../voice-input/ComposerDictationControl";
112import { useVoiceInputController } from "../voice-input/useVoiceInputController";
113import { resolveVoiceComposerPresentation } from "../voice-input/voiceInputPresentation";
114import {
115 rememberModelOptions,
116 withRememberedModelOptions,
117} from "../../state/use-model-option-memory";
118import {
119 type ExistingThreadSettingsRouteSession,
120 useExistingThreadSettingsRoutePresentation,
121} from "./ThreadSettingsSheet";
122import {
123 useThreadSettingsSheetPresentation,
124 type NavigationWithFinishTransitioning,
125} from "./use-thread-settings-sheet-presentation";
126
127export const COMPOSER_COLLAPSED_CHROME = 60;
128
129export const COMPOSER_EXPANDED_CHROME = 156;
130
131export interface ThreadComposerProps {
132 readonly canOperateThread: boolean;
133 readonly placeholder: string;
134 readonly contentMaxWidth?: number;
135 readonly bottomInset?: number;
136 readonly connectionState: RemoteClientConnectionState;
137 readonly environmentLabel: string | null;
138 readonly threadSyncPhase?: "loading" | "syncing" | null;
139 readonly selectedThread: EnvironmentThreadShell;
140 readonly reportedModelSelection?: ModelSelection | null;
141 readonly hasCompactableConversation: boolean;
142 readonly serverConfig: T3ServerConfig | null;
143 readonly queueCount: number;
144 readonly activeThreadBusy: boolean;
145 readonly canStopThread: boolean;
146 readonly environmentId: EnvironmentId;
147 readonly projectCwd: string | null;
148 readonly sendBlockedReason?: string | null;
149 readonly draftKey?: string;
150 readonly queuedEdit?: {
151 readonly existingAttachments: ReadonlyArray<ChatAttachment>;
152 readonly saving: boolean;
153 readonly onRemoveExistingAttachment: (attachmentId: string) => void;
154 } | null;
155 readonly followUpBehavior: FollowUpBehavior;
156 readonly canSteerActiveTurn: boolean;
157 readonly editorRef?: RefObject<ComposerEditorHandle | null>;
158 readonly onChangeDraftMessage: (value: string) => void;
159 readonly onPickDraftMedia: () => Promise<void>;
160 readonly onPickDraftFiles: () => Promise<void>;
161 readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
162 readonly onNativePasteText: (paste: ComposerTextPaste) => Promise<void>;
163 readonly onRemoveDraftImage: (imageId: string) => void;
164 readonly onStopThread: () => void;
165 /** Present while the thread's queue is held. */
166 readonly onResumeQueue: (() => Promise<void>) | null;
167 readonly onSendMessage: (followUp?: ActiveTurnComposerAction) => Promise<MessageId | null>;
168 readonly onShowUsageLimits: (report: UsageLimitsReport | null) => void;
169 readonly canSwitchProvider: boolean;
170 readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
171 readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;
172 readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
173 readonly onExpandedChange?: (expanded: boolean) => void;
174 readonly onEditorFocusChange?: (focused: boolean) => void;
175}
176
177// Android gets NO layout transition: the composer rides the keyboard via KeyboardStickyView
178// (frame-synced to the IME), and a time-based morph running alongside that translate reads as
179// jitter.
180export const COMPOSER_TRANSITION_DURATION_MS = 220;
181// Side panes already animate the dock's width. Nested horizontal layout
182// transitions would leave the surface trailing its toolbar's new position.
183const composerHeightTransition: LayoutAnimationFunction = (values) => {
184 "worklet";
185 const timing = {
186 duration: COMPOSER_TRANSITION_DURATION_MS,
187 reduceMotion: ReduceMotion.System,
188 };
189 return {
190 initialValues: {
191 originX: values.targetOriginX,
192 originY: values.currentOriginY,
193 width: values.targetWidth,
194 height: values.currentHeight,
195 },
196 animations: {
197 originX: values.targetOriginX,
198 originY: withTiming(values.targetOriginY, timing),
199 width: values.targetWidth,
200 height: withTiming(values.targetHeight, timing),
201 },
202 };
203};
204export const COMPOSER_LAYOUT_TRANSITION =
205 Platform.OS === "android" ? undefined : composerHeightTransition;
206
207const COMPOSER_ATTACHMENT_ENTERING =
208 Platform.OS === "android"
209 ? FadeIn.duration(160)
210 : FadeIn.delay(COMPOSER_TRANSITION_DURATION_MS).duration(160).reduceMotion(ReduceMotion.System);
211
212const AnimatedGlassSurface = Animated.createAnimatedComponent(GlassSurface);
213
214const FOLLOW_UP_ACTION_LABEL = {
215 queue: "Queue",
216 steer: "Steer now",
217 restart: "Restart turn",
218} as const;
219
220const FOLLOW_UP_ACTION_SUBTITLE = {
221 queue: "Run after the current turn",
222 steer: "Interrupt what the agent is doing",
223 restart: "Start the turn over with this message",
224} as const;
225
226function SendActionButton(props: {
227 readonly accessibilityLabel: string;
228 readonly presentation: ComposerSendPresentation;
229 readonly disabled: boolean;
230 readonly onSend: (followUp?: ActiveTurnComposerAction) => void;
231}) {
232 const { presentation } = props;
233 const button = (
234 <ComposerActionButton
235 accessibilityLabel={props.accessibilityLabel}
236 icon={presentation.icon}
237 variant="primary"
238 disabled={props.disabled}
239 onPress={() => props.onSend()}
240 />
241 );
242 if (!presentation.offersFollowUpChoice || presentation.action === null || props.disabled) {
243 return button;
244 }
245 const actions = [presentation.action, presentation.alternate].filter(
246 (action): action is ActiveTurnComposerAction => action !== null,
247 );
248 return (
249 <Menu
250 accessibilityLabel="Choose how to send this message"
251 shouldOpenOnLongPress
252 actions={actions.map((action) => ({
253 id: action,
254 title: FOLLOW_UP_ACTION_LABEL[action],
255 subtitle: FOLLOW_UP_ACTION_SUBTITLE[action],
256 state: action === presentation.action ? ("on" as const) : ("off" as const),
257 }))}
258 onPressAction={({ nativeEvent }) =>
259 props.onSend(nativeEvent.event as ActiveTurnComposerAction)
260 }
261 >
262 {button}
263 </Menu>
264 );
265}
266
267export function ComposerSurface(props: {
268 readonly children: ReactNode;
269 readonly style: ViewStyle;
270 readonly animateLayout?: boolean;
271}) {
272 const colors = useUniwindTheme();
273 const targetBorderRadius =
274 typeof props.style.borderRadius === "number" ? props.style.borderRadius : 0;
275 const animatedBorderRadius = useSharedValue(targetBorderRadius);
276 const shouldAnimate = props.animateLayout !== false && Platform.OS !== "android";
277 useLayoutEffect(() => {
278 animatedBorderRadius.value = shouldAnimate
279 ? withTiming(targetBorderRadius, {
280 duration: COMPOSER_TRANSITION_DURATION_MS,
281 reduceMotion: ReduceMotion.System,
282 })
283 : targetBorderRadius;
284 }, [animatedBorderRadius, shouldAnimate, targetBorderRadius]);
285 const animatedShapeStyle = useAnimatedStyle(() => ({
286 borderRadius: animatedBorderRadius.value,
287 }));
288 const layoutTransition = shouldAnimate ? COMPOSER_LAYOUT_TRANSITION : undefined;
289
290 // Each native frame follows the same transition. Animating only the outer
291 // clip leaves the glass and content at their final height on the first frame.
292 return (
293 <Animated.View
294 className={
295 Platform.OS === "android" ? undefined : "shadow-[0_6px_28px] shadow-adaptive-black-a15-a35"
296 }
297 layout={layoutTransition}
298 style={[
299 animatedShapeStyle,
300 {
301 overflow: "hidden",
302 },
303 ]}
304 >
305 <AnimatedGlassSurface
306 chrome="none"
307 fallbackColor={colors["--color-composer-surface"]}
308 fallbackClassName="border border-composer-border"
309 glassEffectStyle="regular"
310 pointerEvents="none"
311 tintColor="transparent"
312 layout={layoutTransition}
313 style={[{ position: "absolute", inset: 0 }, animatedShapeStyle]}
314 >
315 {null}
316 </AnimatedGlassSurface>
317 <Animated.View
318 collapsable={false}
319 layout={layoutTransition}
320 style={[props.style, animatedShapeStyle]}
321 >
322 {props.children}
323 </Animated.View>
324 </Animated.View>
325 );
326}
327
328export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps) {
329 const project = useProject(scopeProjectRef(props.environmentId, props.selectedThread.projectId));
330 const { themeVariables: materialTheme } = useAppearancePreferences();
331 const composerPanel = materialTheme["--color-composer-panel"];
332 const navigation = useNavigation();
333 const foregroundColor = useUniwindTheme()["--color-foreground"];
334 const bodyText = useScaledTextRole("body");
335 const fallbackInputRef = useRef<ComposerEditorHandle>(null);
336 const inputRef = props.editorRef ?? fallbackInputRef;
337 const [isFocused, setIsFocused] = useState(false);
338 const pendingPastedTextAttachmentCountRef = useRef(0);
339 const [pendingPastedTextAttachmentCount, setPendingPastedTextAttachmentCount] = useState(0);
340 const settingsSheetPresentation = useThreadSettingsSheetPresentation({
341 editorRef: inputRef,
342 isEditorFocused: isFocused,
343 });
344 const settingsRoutePresentation = useExistingThreadSettingsRoutePresentation();
345 const settingsRoutePresentedRef = useRef(false);
346 const wasExpandedBeforePreviewRef = useRef(false);
347 const inFlightThreadIdsRef = useRef(new Set<string>());
348 const { onExpandedChange } = props;
349
350 const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
351 const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);
352 const composerOwnerKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
353 const composerDraftKey = props.draftKey ?? composerOwnerKey;
354 const { text: draftMessage, attachments: draftAttachments } = useComposerDraft(composerDraftKey);
355 const queuedEdit = props.queuedEdit ?? null;
356 const hasContent =
357 draftMessage.trim().length > 0 ||
358 draftAttachments.length > 0 ||
359 (queuedEdit?.existingAttachments.length ?? 0) > 0;
360 const stripAttachments = composerStripAttachments(draftAttachments);
361 const showStopAction = !hasContent && props.canStopThread && queuedEdit === null;
362 const onResumeQueue = props.onResumeQueue;
363 const [resumingQueue, setResumingQueue] = useState(false);
364 const showResumeAction =
365 !hasContent && !showStopAction && queuedEdit === null && onResumeQueue !== null;
366 const handleResumeQueue = async () => {
367 if (resumingQueue || onResumeQueue === null) return;
368 setResumingQueue(true);
369 await onResumeQueue();
370 setResumingQueue(false);
371 };
372
373 const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
374 const attachmentsUploading =
375 props.connectionState === "connected" &&
376 composerAttachmentsStillUploading({
377 environmentId: props.environmentId,
378 attachments: draftAttachments,
379 serverConfig: props.serverConfig,
380 states: uploadStates,
381 });
382 const sendPresentation = resolveComposerSendPresentation({
383 editingQueuedMessage: queuedEdit !== null,
384 running: props.activeThreadBusy,
385 canSteer: props.canSteerActiveTurn,
386 followUpBehavior: props.followUpBehavior,
387 deliveryDeferred:
388 props.connectionState !== "connected" || props.queueCount > 0 || attachmentsUploading,
389 });
390 const sendLabel = sendPresentation.label;
391 const currentModelSelection = props.selectedThread.modelSelection;
392 const currentRuntimeMode = props.selectedThread.runtimeMode;
393 const modelUnavailable =
394 props.connectionState === "connected" &&
395 isModelSelectionUnavailable(
396 props.serverConfig,
397 currentModelSelection,
398 props.selectedThread.projectId,
399 );
400 const selectedProviderStatus = (() => {
401 if (!props.serverConfig) return null;
402 return (
403 props.serverConfig.providers.find(
404 (p) => p.instanceId === props.selectedThread.modelSelection.instanceId,
405 ) ?? null
406 );
407 })();
408 const openDraftDocument = (attachment: ComposerDocumentAttachment) => {
409 Keyboard.dismiss();
410 navigation.navigate("ThreadAttachment", {
411 environmentId: String(props.environmentId),
412 threadId: String(props.selectedThread.id),
413 attachmentId: attachment.attachmentId,
414 name: attachment.name,
415 mimeType: attachment.mimeType,
416 sizeBytes: String(attachment.sizeBytes),
417 draftKey: composerDraftKey,
418 });
419 };
420 const { onSendMessage, onChangeDraftMessage, onShowUsageLimits } = props;
421 const usageLimitsOffered =
422 selectedProviderStatus !== null &&
423 hasProviderUsageLimits(
424 selectedProviderStatus.driver,
425 props.serverConfig?.providers ?? [],
426 props.serverConfig?.usageLimitSources ?? [],
427 );
428 const openUsageLimits = () => {
429 const report = collectProviderUsageLimits(
430 currentModelSelection.instanceId,
431 props.serverConfig?.providers ?? [],
432 props.serverConfig?.usageLimitSources ?? [],
433 Date.now(),
434 );
435 onShowUsageLimits(report);
436 if (!report) {
437 Dialog.alert("Usage limits unavailable", "This provider does not currently report limits.");
438 }
439 return report !== null;
440 };
441
442 const composerMenu = useComposerCommandMenu({
443 draftMessage: draftMessage,
444 ownerKey: composerDraftKey,
445 environmentId: props.environmentId,
446 threadShells: useThreadShells(),
447 currentThreadId: props.selectedThread.id,
448 projectCwd: props.projectCwd,
449 pullRequestProjectId: props.serverConfig?.environment.capabilities.pullRequests
450 ? (project?.id ?? null)
451 : null,
452 pullRequestRepository: project?.repositoryIdentity?.displayName ?? null,
453 threadPullRequests: props.selectedThread.pullRequests,
454 selectedProviderStatus,
455 hasThread: true,
456 hasCompactableConversation: props.hasCompactableConversation,
457 onChangeDraftMessage: props.onChangeDraftMessage,
458 onUpdateInteractionMode:
459 selectedProviderStatus?.showInteractionModeToggle === false
460 ? undefined
461 : props.onUpdateInteractionMode,
462 offersUsageLimits: usageLimitsOffered,
463 onUsageLimits:
464 usageLimitsOffered && draftAttachments.length === 0 ? openUsageLimits : undefined,
465 });
466 const voiceInput = useVoiceInputController({
467 ownerKey: composerDraftKey,
468 label: props.selectedThread.title || "Untitled thread",
469 readDraftMessage: () => getComposerDraftSnapshot(composerDraftKey).text,
470 subscribeToDraftChanges: (onChange) => appAtomRegistry.subscribe(composerDraftsAtom, onChange),
471 selection: composerMenu.selection,
472 onChangeDraftMessage: (text) => setComposerDraftText(composerDraftKey, text),
473 onChangeSelection: composerMenu.onSelectionChange,
474 });
475 const voicePresentation = resolveVoiceComposerPresentation(
476 voiceInput.state,
477 voiceInput.elapsedSeconds,
478 );
479 const isVoiceInputPresented = voicePresentation.statusLabel !== null;
480 const isExpanded = isFocused || settingsSheetPresentation.keepsComposerExpanded;
481 const showsCompactDictation = isVoiceInputPresented && !isExpanded;
482 const isToolbarVisible = isExpanded || isVoiceInputPresented;
483 const attachmentBlockReason = composerAttachmentUploadBlockReason({
484 environmentId: props.environmentId,
485 attachments: draftAttachments,
486 connected: props.connectionState === "connected",
487 serverConfig: props.serverConfig,
488 states: uploadStates,
489 });
490 const contextImports = useAtomValue(composerContextImportsAtom);
491 const sendBlockedReason =
492 (queuedEdit?.saving === true ? "Saving…" : null) ??
493 props.sendBlockedReason ??
494 (pendingPastedTextAttachmentCount > 0 ? "Attaching pasted text" : null) ??
495 attachmentBlockReason;
496 const canSend =
497 (props.canOperateThread || props.connectionState !== "connected") &&
498 hasContent &&
499 !contextImports[composerDraftKey] &&
500 !voiceInput.blocksSubmission &&
501 sendBlockedReason === null &&
502 !modelUnavailable;
503
504 useEffect(() => {
505 onExpandedChange?.(isExpanded);
506 }, [isExpanded, onExpandedChange]);
507
508 const onPressPreview = (source: FilePreviewSource) => {
509 wasExpandedBeforePreviewRef.current = isFocused;
510 setPreviewVideo(null);
511 setPreviewFile(
512 (current) =>
513 current ?? {
514 ...source,
515 gallery: filePreviewGallery(source, composerImageGallery(draftAttachments)),
516 },
517 );
518 };
519
520 const closePreview = () => {
521 setPreviewFile(null);
522 setPreviewVideo(null);
523 if (wasExpandedBeforePreviewRef.current) {
524 setTimeout(() => {
525 if (navigation.isFocused()) inputRef.current?.focus();
526 }, 100);
527 }
528 };
529
530 const onPressVideo = (attachment: DraftComposerFileAttachment, sourceIdentifier: string) => {
531 wasExpandedBeforePreviewRef.current = isFocused;
532 setPreviewFile(null);
533 setPreviewVideo((current) => current ?? { type: "local", attachment, sourceIdentifier });
534 };
535
536 const onEditorFocusChange = props.onEditorFocusChange;
537 const handleFocus = () => {
538 setIsFocused(true);
539 onExpandedChange?.(true);
540 onEditorFocusChange?.(true);
541 };
542
543 const handleBlur = () => {
544 setIsFocused(false);
545 if (!settingsSheetPresentation.keepsComposerExpanded) {
546 onExpandedChange?.(false);
547 }
548 onEditorFocusChange?.(false);
549 };
550 const handleSend = async (followUp?: ActiveTurnComposerAction) => {
551 if (voiceInput.blocksSubmission || pendingPastedTextAttachmentCountRef.current > 0) return;
552 if (usageLimitsOffered && isUsageLimitsCommand(draftMessage) && draftAttachments.length === 0) {
553 if (openUsageLimits()) onChangeDraftMessage("");
554 return;
555 }
556 const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
557 if (inFlightThreadIdsRef.current.has(threadKey)) return;
558 inFlightThreadIdsRef.current.add(threadKey);
559 const sent = await settlePromise(() => onSendMessage(followUp));
560 inFlightThreadIdsRef.current.delete(threadKey);
561 if (AsyncResult.isFailure(sent)) {
562 // The composer state already surfaces send errors; only the lock needed releasing.
563 console.error("[composer] send failed", squashAtomCommandFailure(sent));
564 return;
565 }
566 if (sent.value === null) return;
567 // Armed after the send so its preference read and native Activity start don't contend
568 // with the queued-message feedback on the tap frame.
569 armAgentAwarenessLiveActivityForLocalWork({
570 environmentId: props.environmentId,
571 threadTitle: props.selectedThread.title,
572 projectTitle: props.environmentLabel ?? "T3 Code",
573 });
574 };
575
576 const lockedProviderInstanceId = props.canSwitchProvider
577 ? undefined
578 : currentModelSelection.instanceId;
579 const modelOptions = buildModelOptions(
580 props.serverConfig,
581 currentModelSelection,
582 lockedProviderInstanceId,
583 props.selectedThread.projectId,
584 );
585 const threadProviderGroups = groupByProvider(modelOptions);
586 const currentModelOption =
587 modelOptions.find(
588 (option) =>
589 option.selection.instanceId === currentModelSelection.instanceId &&
590 option.selection.model === currentModelSelection.model,
591 ) ?? null;
592 const providerOptionDescriptors = resolveProviderOptionDescriptors({
593 capabilities: currentModelOption?.capabilities,
594 selections: currentModelSelection.options,
595 });
596 const settingsOwnerId = composerOwnerKey;
597 const settingsRouteSession = {
598 ownerId: settingsOwnerId,
599 environmentId: props.environmentId,
600 projectId: props.selectedThread.projectId,
601 providerInstanceId: currentModelSelection.instanceId,
602 ...(lockedProviderInstanceId ? { lockedProviderInstanceId } : {}),
603 providerGroups: threadProviderGroups,
604 selectedModel: currentModelSelection,
605 reportedModelSelection: props.reportedModelSelection,
606 onSelectModel: (option) =>
607 props.onUpdateModelSelection(withRememberedModelOptions(option.selection)),
608 restoreSelection: withRememberedModelOptions,
609 optionDescriptors: providerOptionDescriptors,
610 onUpdateOptionSelections: (options) => {
611 rememberModelOptions(
612 currentModelSelection.instanceId,
613 currentModelSelection.model,
614 options ?? [],
615 );
616 props.onUpdateModelSelection({ ...currentModelSelection, options });
617 },
618 runtimeMode: currentRuntimeMode,
619 onUpdateRuntimeMode: props.onUpdateRuntimeMode,
620 } satisfies ExistingThreadSettingsRouteSession;
621 const openSettings = () => {
622 settingsRoutePresentation.present(settingsRouteSession);
623 settingsSheetPresentation.open();
624 };
625
626 useEffect(() => {
627 if (settingsSheetPresentation.isActive) {
628 settingsRoutePresentation.present(settingsRouteSession);
629 }
630 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.isActive]);
631
632 useEffect(() => {
633 if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
634 return;
635 }
636
637 settingsRoutePresentedRef.current = true;
638 navigation.dispatch(StackActions.push("ThreadSettingsSheet"));
639 }, [navigation, settingsSheetPresentation.isVisible]);
640
641 useFocusEffect(() => {
642 if (!settingsRoutePresentedRef.current) {
643 return;
644 }
645
646 settingsRoutePresentedRef.current = false;
647 settingsSheetPresentation.onDismissed();
648 settingsRoutePresentation.clear(settingsOwnerId);
649 });
650
651 useEffect(
652 () =>
653 // UIKit's completion callback for the sheet dismissal, surfaced by the
654 // native-stack patch. This is when the queued keyboard restore runs.
655 (navigation as unknown as NavigationWithFinishTransitioning).addListener(
656 "finishTransitioning",
657 settingsSheetPresentation.onStackTransitionsFinished,
658 ),
659 [navigation, settingsSheetPresentation.onStackTransitionsFinished],
660 );
661
662 return (
663 <Animated.View
664 className="px-[12px]"
665 style={{
666 paddingTop: isExpanded ? 8 : 6,
667 paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 8 : 6),
668 backgroundColor:
669 Platform.OS === "android" ? themeColorWithAlpha(composerPanel, 1) : undefined,
670 }}
671 >
672 {/* The backdrop gradient lives on a plain View: Reanimated's Animated.View
673 silently drops experimental_backgroundImage on Android, which left this
674 strip fully transparent and the feed text legible through the composer. */}
675 <View
676 className={
677 Platform.OS === "android"
678 ? "hidden"
679 : "absolute inset-0 bg-linear-to-b from-screen/0 via-screen/60 to-screen/90"
680 }
681 pointerEvents="none"
682 />
683 <Animated.View
684 className="relative w-full self-center"
685 style={{ maxWidth: props.contentMaxWidth }}
686 >
687 {!voiceInput.isBusy &&
688 composerMenu.trigger &&
689 (composerMenu.items.length > 0 || composerMenu.trigger.kind === "pull-request") ? (
690 <ComposerPopoverAnchor>
691 <ComposerCommandPopover
692 items={composerMenu.items}
693 triggerKind={composerMenu.trigger.kind}
694 isLoading={composerMenu.isLoading}
695 error={composerMenu.error}
696 onSelect={composerMenu.onSelect}
697 />
698 </ComposerPopoverAnchor>
699 ) : null}
700
701 {selectedProviderStatus?.compatibilityAdvisory?.message &&
702 (selectedProviderStatus.compatibilityAdvisory.status === "unsupported" ||
703 selectedProviderStatus.compatibilityAdvisory.status === "broken") ? (
704 <Text
705 accessibilityRole={
706 selectedProviderStatus.compatibilityAdvisory.status === "broken" ? "alert" : undefined
707 }
708 accessibilityLiveRegion={
709 selectedProviderStatus.compatibilityAdvisory.status === "broken"
710 ? "assertive"
711 : "polite"
712 }
713 className={
714 selectedProviderStatus.compatibilityAdvisory.status === "broken"
715 ? "bg-danger px-3 py-2 text-xs text-danger-foreground"
716 : "px-3 py-2 text-xs text-foreground"
717 }
718 >
719 {selectedProviderStatus.compatibilityAdvisory.message}
720 </Text>
721 ) : null}
722 {modelUnavailable ? (
723 <Pressable accessibilityRole="button" className="px-3 py-2" onPress={openSettings}>
724 <Text className="text-xs text-foreground">Model unavailable. Open model settings.</Text>
725 </Pressable>
726 ) : null}
727
728 <ComposerSurface
729 style={
730 isExpanded
731 ? {
732 borderRadius: 26,
733 minHeight: 140,
734 overflow: "hidden" as const,
735 paddingBottom: 6,
736 paddingTop: 14,
737 }
738 : {
739 borderRadius: 27,
740 overflow: "hidden" as const,
741 paddingVertical: 2,
742 }
743 }
744 >
745 <ComposerDictationDraftContent
746 className={isExpanded ? undefined : "flex-row items-center"}
747 compact={!isExpanded}
748 hidden={showsCompactDictation}
749 >
750 {!isExpanded ? (
751 <ComposerAttachmentButton
752 supportsFiles={Boolean(
753 props.serverConfig?.environment.capabilities.fileAttachments,
754 )}
755 onPickMedia={props.onPickDraftMedia}
756 onPickFiles={props.onPickDraftFiles}
757 />
758 ) : null}
759 {isExpanded && queuedEdit !== null && queuedEdit.existingAttachments.length > 0 ? (
760 <Animated.View
761 className="px-[14px] pb-2.5"
762 entering={COMPOSER_ATTACHMENT_ENTERING}
763 exiting={FadeOut.duration(120)}
764 >
765 <ComposerQueuedEditAttachments
766 environmentId={props.environmentId}
767 attachments={queuedEdit.existingAttachments}
768 disabled={queuedEdit.saving || voiceInput.isBusy}
769 onRemove={queuedEdit.onRemoveExistingAttachment}
770 />
771 </Animated.View>
772 ) : null}
773 {isExpanded && stripAttachments.length > 0 ? (
774 <Animated.View
775 className="px-[14px] pb-2.5"
776 entering={COMPOSER_ATTACHMENT_ENTERING}
777 exiting={FadeOut.duration(120)}
778 >
779 <ComposerAttachmentStrip
780 environmentId={props.environmentId}
781 attachments={stripAttachments}
782 onRemove={voiceInput.isBusy ? () => undefined : props.onRemoveDraftImage}
783 onPressPreview={voiceInput.isBusy ? undefined : onPressPreview}
784 onPressVideo={voiceInput.isBusy ? undefined : onPressVideo}
785 onPressDocument={
786 voiceInput.isBusy
787 ? undefined
788 : (attachment) =>
789 openDraftDocument({
790 attachmentId: attachment.id,
791 name: attachment.name,
792 mimeType: attachment.mimeType,
793 sizeBytes: attachment.sizeBytes,
794 })
795 }
796 />
797 </Animated.View>
798 ) : null}
799 <Animated.View
800 className={isExpanded ? "px-[14px]" : "min-w-0 flex-1 px-[4px]"}
801 layout={COMPOSER_LAYOUT_TRANSITION}
802 >
803 <ComposerEditor
804 draftKey={composerDraftKey}
805 environmentId={props.environmentId}
806 onOpenMention={(path) => {
807 Keyboard.dismiss();
808 navigation.navigate("ThreadFile", {
809 environmentId: String(props.environmentId),
810 threadId: String(props.selectedThread.id),
811 path: fileRoutePathSegments(path),
812 });
813 }}
814 onOpenAttachment={openDraftDocument}
815 chipsInert={!isExpanded}
816 onInertChipPress={() => inputRef.current?.focus()}
817 ref={inputRef}
818 multiline
819 value={draftMessage}
820 readOnly={voiceInput.freezesEditor}
821 skills={composerMenu.skills}
822 selection={composerMenu.selection}
823 onChangeText={props.onChangeDraftMessage}
824 onSelectionChange={composerMenu.onSelectionChange}
825 onPasteImages={(uris) => void props.onNativePasteImages(uris)}
826 onPasteText={(paste) => {
827 const insertPaste = () => {
828 const insertion = replaceTextSelection({
829 value: paste.value,
830 selection: paste.selection,
831 text: paste.text,
832 });
833 const selection = { start: insertion.cursor, end: insertion.cursor };
834 props.onChangeDraftMessage(insertion.value);
835 composerMenu.onSelectionChange(selection);
836 };
837 const capabilities = props.serverConfig?.environment.capabilities;
838 const advertisedMax =
839 capabilities?.attachmentUploads === true
840 ? capabilities.fileAttachments?.maxUploadBytes
841 : undefined;
842 const maxBytes =
843 advertisedMax === undefined
844 ? null
845 : clampFileAttachmentUploadBytes(advertisedMax);
846 const wouldExceedInputLimit =
847 paste.value.length -
848 Math.max(0, paste.selection.end - paste.selection.start) +
849 paste.text.length >
850 PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
851 const canAttach =
852 maxBytes !== null &&
853 countComposerDraftAttachmentsAfterSelection(composerDraftKey, {
854 text: paste.value,
855 ...paste.selection,
856 }) < PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
857 new TextEncoder().encode(paste.text).byteLength <= maxBytes;
858 if (
859 pastedTextDisposition({
860 text: paste.text,
861 wouldExceedInputLimit,
862 canAttach: true,
863 }) === "attachment"
864 ) {
865 if (canAttach) {
866 pendingPastedTextAttachmentCountRef.current += 1;
867 setPendingPastedTextAttachmentCount(
868 pendingPastedTextAttachmentCountRef.current,
869 );
870 const finishAttachment = () => {
871 pendingPastedTextAttachmentCountRef.current = Math.max(
872 0,
873 pendingPastedTextAttachmentCountRef.current - 1,
874 );
875 setPendingPastedTextAttachmentCount(
876 pendingPastedTextAttachmentCountRef.current,
877 );
878 };
879 void props.onNativePasteText(paste).then(finishAttachment, finishAttachment);
880 } else if (!wouldExceedInputLimit) {
881 insertPaste();
882 } else {
883 Dialog.alert(
884 wouldExceedInputLimit
885 ? "Pasted text is too large for this message"
886 : "Could not attach pasted text",
887 wouldExceedInputLimit
888 ? "Remove some text or an attachment, then paste again."
889 : "Remove an attachment or use a smaller paste, then try again.",
890 );
891 }
892 return;
893 }
894 insertPaste();
895 }}
896 placeholder={props.placeholder}
897 onFocus={handleFocus}
898 onBlur={handleBlur}
899 onSubmit={(alternate) =>
900 void handleSend(
901 alternate && sendPresentation.alternate !== null
902 ? sendPresentation.alternate
903 : undefined,
904 )
905 }
906 submitTitle={sendPresentation.label}
907 alternateSubmitTitle={
908 sendPresentation.alternate === null
909 ? sendPresentation.label
910 : FOLLOW_UP_ACTION_LABEL[sendPresentation.alternate]
911 }
912 scrollEnabled={isExpanded}
913 singleLineCentered={!isExpanded}
914 contentInsetVertical={isExpanded || Platform.OS === "android" ? 0 : 6}
915 style={
916 isExpanded
917 ? {
918 minHeight: 72,
919 maxHeight: 160,
920 paddingVertical: 4,
921 }
922 : {
923 height: 36,
924 }
925 }
926 textStyle={{
927 ...bodyText,
928 color: foregroundColor,
929 }}
930 />
931 </Animated.View>
932 {!isExpanded && stripAttachments.length > 0 ? (
933 <View className="flex-row gap-1 pl-1">
934 {stripAttachments.slice(0, 3).map((attachment) => (
935 <ComposerAttachmentThumbnail
936 environmentId={props.environmentId}
937 key={attachment.id}
938 attachment={attachment}
939 size={30}
940 borderRadius={8}
941 compact
942 onPressPreview={onPressPreview}
943 onPressVideo={onPressVideo}
944 />
945 ))}
946 {stripAttachments.length > 3 ? (
947 <View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
948 <Text className="text-foreground-muted text-2xs font-t3-bold">
949 +{stripAttachments.length - 3}
950 </Text>
951 </View>
952 ) : null}
953 </View>
954 ) : null}
955 {!isExpanded ? (
956 <View className="flex-row items-center">
957 <ComposerDictationStartAction
958 state={voiceInput.state}
959 isAvailable={voiceInput.isAvailable}
960 onStart={voiceInput.start}
961 onCancel={voiceInput.cancel}
962 />
963 {showStopAction ? (
964 <ComposerActionButton
965 accessibilityLabel="Stop agent"
966 icon="stop.fill"
967 variant="danger"
968 disabled={!props.canOperateThread}
969 onPress={props.onStopThread}
970 />
971 ) : showResumeAction ? (
972 <ComposerActionButton
973 accessibilityLabel="Resume queue"
974 icon="play"
975 disabled={!props.canOperateThread || resumingQueue}
976 onPress={() => void handleResumeQueue()}
977 />
978 ) : (
979 <SendActionButton
980 accessibilityLabel={sendBlockedReason ?? sendLabel}
981 presentation={sendPresentation}
982 disabled={!canSend}
983 onSend={handleSend}
984 />
985 )}
986 </View>
987 ) : null}
988 {isExpanded ? <View className="h-1" /> : null}
989 </ComposerDictationDraftContent>
990 <Animated.View
991 accessibilityElementsHidden={!isToolbarVisible}
992 collapsable={false}
993 importantForAccessibility={isToolbarVisible ? "auto" : "no-hide-descendants"}
994 layout={COMPOSER_LAYOUT_TRANSITION}
995 pointerEvents={isToolbarVisible ? "auto" : "none"}
996 style={
997 isExpanded
998 ? undefined
999 : {
1000 position: "absolute",
1001 bottom: 2,
1002 left: 0,
1003 right: 0,
1004 }
1005 }
1006 >
1007 <ComposerDictationToolbar
1008 showsDictation={isVoiceInputPresented}
1009 visible={isToolbarVisible}
1010 >
1011 <ComposerToolbarRow
1012 paddingBottom={0}
1013 paddingHorizontal={0}
1014 paddingTop={0}
1015 style={{ gap: 0 }}
1016 >
1017 <ComposerDictationCancelAction
1018 presentation={voicePresentation}
1019 onCancel={voiceInput.cancel}
1020 />
1021 {isVoiceInputPresented ? (
1022 <ComposerDictationStatus
1023 audioLevels={voiceInput.audioLevels}
1024 elapsedSeconds={voiceInput.elapsedSeconds}
1025 phase={voiceInput.state.phase}
1026 presentation={voicePresentation}
1027 onDismissError={voiceInput.cancel}
1028 />
1029 ) : (
1030 <View className="min-w-0 flex-1 flex-row items-center justify-between">
1031 <ComposerAttachmentButton
1032 supportsFiles={Boolean(
1033 props.serverConfig?.environment.capabilities.fileAttachments,
1034 )}
1035 onPickMedia={props.onPickDraftMedia}
1036 onPickFiles={props.onPickDraftFiles}
1037 />
1038 <View className="min-w-0 shrink">
1039 <ComposerInlineControl
1040 accessibilityLabel="Model and reasoning settings"
1041 emphasized
1042 renderIcon={(size) => (
1043 <ProviderIcon
1044 iconUrl={currentModelOption?.providerIconUrl}
1045 provider={currentModelOption?.providerDriver}
1046 size={size}
1047 />
1048 )}
1049 label={currentModelOption?.label ?? currentModelSelection.model}
1050 maxWidth="100%"
1051 onPress={openSettings}
1052 />
1053 </View>
1054 </View>
1055 )}
1056 <View className="shrink-0 flex-row items-center">
1057 <ComposerDictationPrimaryAction
1058 state={voiceInput.state}
1059 presentation={voicePresentation}
1060 isAvailable={voiceInput.isAvailable}
1061 onStart={voiceInput.start}
1062 onConfirm={voiceInput.stop}
1063 onCancel={voiceInput.cancel}
1064 />
1065 {showStopAction ? (
1066 <ComposerActionButton
1067 accessibilityLabel="Stop agent"
1068 icon="stop.fill"
1069 variant="danger"
1070 disabled={!props.canOperateThread}
1071 onPress={props.onStopThread}
1072 />
1073 ) : showResumeAction && voicePresentation.showsSend ? (
1074 <ComposerActionButton
1075 accessibilityLabel="Resume queue"
1076 icon="play"
1077 disabled={!props.canOperateThread || resumingQueue}
1078 onPress={() => void handleResumeQueue()}
1079 />
1080 ) : voicePresentation.showsSend ? (
1081 <SendActionButton
1082 accessibilityLabel={sendBlockedReason ?? sendLabel}
1083 presentation={sendPresentation}
1084 disabled={!canSend}
1085 onSend={handleSend}
1086 />
1087 ) : null}
1088 </View>
1089 </ComposerToolbarRow>
1090 </ComposerDictationToolbar>
1091 </Animated.View>
1092 </ComposerSurface>
1093
1094 {props.connectionState === "connected" && !props.canOperateThread ? (
1095 <Text className="pt-2 text-xs text-foreground-muted">
1096 This connection cannot control this task. You can still edit your draft.
1097 </Text>
1098 ) : null}
1099 </Animated.View>
1100
1101 <VideoPreviewModal source={previewVideo} onRequestClose={closePreview} />
1102 <FilePreviewModal source={previewFile} onRequestClose={closePreview} />
1103 </Animated.View>
1104 );
1105};