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