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

ThreadComposer.tsx

1,104 lines43.9 KB

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;
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 );
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 );
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 optionDescriptors: providerOptionDescriptors,
609 onUpdateOptionSelections: (options) => {
610 rememberModelOptions(
611 currentModelSelection.instanceId,
612 currentModelSelection.model,
613 options ?? [],
614 );
615 props.onUpdateModelSelection({ ...currentModelSelection, options });
616 },
617 runtimeMode: currentRuntimeMode,
618 onUpdateRuntimeMode: props.onUpdateRuntimeMode,
619 } satisfies ExistingThreadSettingsRouteSession;
620 const openSettings = () => {
621 settingsRoutePresentation.present(settingsRouteSession);
622 settingsSheetPresentation.open();
623 };
624​
625 useEffect(() => {
626 if (settingsSheetPresentation.isActive) {
627 settingsRoutePresentation.present(settingsRouteSession);
628 }
629 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.isActive]);
630​
631 useEffect(() => {
632 if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
633 return;
634 }
635​
636 settingsRoutePresentedRef.current = true;
637 navigation.dispatch(StackActions.push("ThreadSettingsSheet"));
638 }, [navigation, settingsSheetPresentation.isVisible]);
639​
640 useFocusEffect(() => {
641 if (!settingsRoutePresentedRef.current) {
642 return;
643 }
644​
645 settingsRoutePresentedRef.current = false;
646 settingsSheetPresentation.onDismissed();
647 settingsRoutePresentation.clear(settingsOwnerId);
648 });
649​
650 useEffect(
651 () =>
652 // UIKit's completion callback for the sheet dismissal, surfaced by the
653 // native-stack patch. This is when the queued keyboard restore runs.
654 (navigation as unknown as NavigationWithFinishTransitioning).addListener(
655 "finishTransitioning",
656 settingsSheetPresentation.onStackTransitionsFinished,
657 ),
658 [navigation, settingsSheetPresentation.onStackTransitionsFinished],
659 );
660​
661 return (
662 <Animated.View
663 className="px-[12px]"
664 style={{
665 paddingTop: isExpanded ? 8 : 6,
666 paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 8 : 6),
667 backgroundColor:
668 Platform.OS === "android" ? themeColorWithAlpha(composerPanel, 1) : undefined,
669 }}
670 >
671 {/* The backdrop gradient lives on a plain View: Reanimated's Animated.View
672 silently drops experimental_backgroundImage on Android, which left this
673 strip fully transparent and the feed text legible through the composer. */}
674 <View
675 className={
676 Platform.OS === "android"
677 ? "hidden"
678 : "absolute inset-0 bg-linear-to-b from-screen/0 via-screen/60 to-screen/90"
679 }
680 pointerEvents="none"
681 />
682 <Animated.View
683 className="relative w-full self-center"
684 style={{ maxWidth: props.contentMaxWidth }}
685 >
686 {!voiceInput.isBusy &&
687 composerMenu.trigger &&
688 (composerMenu.items.length > 0 || composerMenu.trigger.kind === "pull-request") ? (
689 <ComposerPopoverAnchor>
690 <ComposerCommandPopover
691 items={composerMenu.items}
692 triggerKind={composerMenu.trigger.kind}
693 isLoading={composerMenu.isLoading}
694 error={composerMenu.error}
695 onSelect={composerMenu.onSelect}
696 />
697 </ComposerPopoverAnchor>
698 ) : null}
699​
700 {selectedProviderStatus?.compatibilityAdvisory?.message &&
701 (selectedProviderStatus.compatibilityAdvisory.status === "unsupported" ||
702 selectedProviderStatus.compatibilityAdvisory.status === "broken") ? (
703 <Text
704 accessibilityRole={
705 selectedProviderStatus.compatibilityAdvisory.status === "broken" ? "alert" : undefined
706 }
707 accessibilityLiveRegion={
708 selectedProviderStatus.compatibilityAdvisory.status === "broken"
709 ? "assertive"
710 : "polite"
711 }
712 className={
713 selectedProviderStatus.compatibilityAdvisory.status === "broken"
714 ? "bg-danger px-3 py-2 text-xs text-danger-foreground"
715 : "px-3 py-2 text-xs text-foreground"
716 }
717 >
718 {selectedProviderStatus.compatibilityAdvisory.message}
719 </Text>
720 ) : null}
721 {modelUnavailable ? (
722 <Pressable accessibilityRole="button" className="px-3 py-2" onPress={openSettings}>
723 <Text className="text-xs text-foreground">Model unavailable. Open model settings.</Text>
724 </Pressable>
725 ) : null}
726​
727 <ComposerSurface
728 style={
729 isExpanded
730 ? {
731 borderRadius: 26,
732 minHeight: 140,
733 overflow: "hidden" as const,
734 paddingBottom: 6,
735 paddingTop: 14,
736 }
737 : {
738 borderRadius: 27,
739 overflow: "hidden" as const,
740 paddingVertical: 2,
741 }
742 }
743 >
744 <ComposerDictationDraftContent
745 className={isExpanded ? undefined : "flex-row items-center"}
746 compact={!isExpanded}
747 hidden={showsCompactDictation}
748 >
749 {!isExpanded ? (
750 <ComposerAttachmentButton
751 supportsFiles={Boolean(
752 props.serverConfig?.environment.capabilities.fileAttachments,
753 )}
754 onPickMedia={props.onPickDraftMedia}
755 onPickFiles={props.onPickDraftFiles}
756 />
757 ) : null}
758 {isExpanded && queuedEdit !== null && queuedEdit.existingAttachments.length > 0 ? (
759 <Animated.View
760 className="px-[14px] pb-2.5"
761 entering={COMPOSER_ATTACHMENT_ENTERING}
762 exiting={FadeOut.duration(120)}
763 >
764 <ComposerQueuedEditAttachments
765 environmentId={props.environmentId}
766 attachments={queuedEdit.existingAttachments}
767 disabled={queuedEdit.saving || voiceInput.isBusy}
768 onRemove={queuedEdit.onRemoveExistingAttachment}
769 />
770 </Animated.View>
771 ) : null}
772 {isExpanded && stripAttachments.length > 0 ? (
773 <Animated.View
774 className="px-[14px] pb-2.5"
775 entering={COMPOSER_ATTACHMENT_ENTERING}
776 exiting={FadeOut.duration(120)}
777 >
778 <ComposerAttachmentStrip
779 environmentId={props.environmentId}
780 attachments={stripAttachments}
781 onRemove={voiceInput.isBusy ? () => undefined : props.onRemoveDraftImage}
782 onPressPreview={voiceInput.isBusy ? undefined : onPressPreview}
783 onPressVideo={voiceInput.isBusy ? undefined : onPressVideo}
784 onPressDocument={
785 voiceInput.isBusy
786 ? undefined
787 : (attachment) =>
788 openDraftDocument({
789 attachmentId: attachment.id,
790 name: attachment.name,
791 mimeType: attachment.mimeType,
792 sizeBytes: attachment.sizeBytes,
793 })
794 }
795 />
796 </Animated.View>
797 ) : null}
798 <Animated.View
799 className={isExpanded ? "px-[14px]" : "min-w-0 flex-1 px-[4px]"}
800 layout={COMPOSER_LAYOUT_TRANSITION}
801 >
802 <ComposerEditor
803 draftKey={composerDraftKey}
804 environmentId={props.environmentId}
805 onOpenMention={(path) => {
806 Keyboard.dismiss();
807 navigation.navigate("ThreadFile", {
808 environmentId: String(props.environmentId),
809 threadId: String(props.selectedThread.id),
810 path: fileRoutePathSegments(path),
811 });
812 }}
813 onOpenAttachment={openDraftDocument}
814 chipsInert={!isExpanded}
815 onInertChipPress={() => inputRef.current?.focus()}
816 ref={inputRef}
817 multiline
818 value={draftMessage}
819 readOnly={voiceInput.freezesEditor}
820 skills={composerMenu.skills}
821 selection={composerMenu.selection}
822 onChangeText={props.onChangeDraftMessage}
823 onSelectionChange={composerMenu.onSelectionChange}
824 onPasteImages={(uris) => void props.onNativePasteImages(uris)}
825 onPasteText={(paste) => {
826 const insertPaste = () => {
827 const insertion = replaceTextSelection({
828 value: paste.value,
829 selection: paste.selection,
830 text: paste.text,
831 });
832 const selection = { start: insertion.cursor, end: insertion.cursor };
833 props.onChangeDraftMessage(insertion.value);
834 composerMenu.onSelectionChange(selection);
835 };
836 const capabilities = props.serverConfig?.environment.capabilities;
837 const advertisedMax =
838 capabilities?.attachmentUploads === true
839 ? capabilities.fileAttachments?.maxUploadBytes
840 : undefined;
841 const maxBytes =
842 advertisedMax === undefined
843 ? null
844 : clampFileAttachmentUploadBytes(advertisedMax);
845 const wouldExceedInputLimit =
846 paste.value.length -
847 Math.max(0, paste.selection.end - paste.selection.start) +
848 paste.text.length >
849 PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
850 const canAttach =
851 maxBytes !== null &&
852 countComposerDraftAttachmentsAfterSelection(composerDraftKey, {
853 text: paste.value,
854 ...paste.selection,
855 }) < PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
856 new TextEncoder().encode(paste.text).byteLength <= maxBytes;
857 if (
858 pastedTextDisposition({
859 text: paste.text,
860 wouldExceedInputLimit,
861 canAttach: true,
862 }) === "attachment"
863 ) {
864 if (canAttach) {
865 pendingPastedTextAttachmentCountRef.current += 1;
866 setPendingPastedTextAttachmentCount(
867 pendingPastedTextAttachmentCountRef.current,
868 );
869 const finishAttachment = () => {
870 pendingPastedTextAttachmentCountRef.current = Math.max(
871 0,
872 pendingPastedTextAttachmentCountRef.current - 1,
873 );
874 setPendingPastedTextAttachmentCount(
875 pendingPastedTextAttachmentCountRef.current,
876 );
877 };
878 void props.onNativePasteText(paste).then(finishAttachment, finishAttachment);
879 } else if (!wouldExceedInputLimit) {
880 insertPaste();
881 } else {
882 Dialog.alert(
883 wouldExceedInputLimit
884 ? "Pasted text is too large for this message"
885 : "Could not attach pasted text",
886 wouldExceedInputLimit
887 ? "Remove some text or an attachment, then paste again."
888 : "Remove an attachment or use a smaller paste, then try again.",
889 );
890 }
891 return;
892 }
893 insertPaste();
894 }}
895 placeholder={props.placeholder}
896 onFocus={handleFocus}
897 onBlur={handleBlur}
898 onSubmit={(alternate) =>
899 void handleSend(
900 alternate && sendPresentation.alternate !== null
901 ? sendPresentation.alternate
902 : undefined,
903 )
904 }
905 submitTitle={sendPresentation.label}
906 alternateSubmitTitle={
907 sendPresentation.alternate === null
908 ? sendPresentation.label
909 : FOLLOW_UP_ACTION_LABEL[sendPresentation.alternate]
910 }
911 scrollEnabled={isExpanded}
912 singleLineCentered={!isExpanded}
913 contentInsetVertical={isExpanded || Platform.OS === "android" ? 0 : 6}
914 style={
915 isExpanded
916 ? {
917 minHeight: 72,
918 maxHeight: 160,
919 paddingVertical: 4,
920 }
921 : {
922 height: 36,
923 }
924 }
925 textStyle={{
926 ...bodyText,
927 color: foregroundColor,
928 }}
929 />
930 </Animated.View>
931 {!isExpanded && stripAttachments.length > 0 ? (
932 <View className="flex-row gap-1 pl-1">
933 {stripAttachments.slice(0, 3).map((attachment) => (
934 <ComposerAttachmentThumbnail
935 environmentId={props.environmentId}
936 key={attachment.id}
937 attachment={attachment}
938 size={30}
939 borderRadius={8}
940 compact
941 onPressPreview={onPressPreview}
942 onPressVideo={onPressVideo}
943 />
944 ))}
945 {stripAttachments.length > 3 ? (
946 <View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
947 <Text className="text-foreground-muted text-2xs font-t3-bold">
948 +{stripAttachments.length - 3}
949 </Text>
950 </View>
951 ) : null}
952 </View>
953 ) : null}
954 {!isExpanded ? (
955 <View className="flex-row items-center">
956 <ComposerDictationStartAction
957 state={voiceInput.state}
958 isAvailable={voiceInput.isAvailable}
959 onStart={voiceInput.start}
960 onCancel={voiceInput.cancel}
961 />
962 {showStopAction ? (
963 <ComposerActionButton
964 accessibilityLabel="Stop agent"
965 icon="stop.fill"
966 variant="danger"
967 disabled={!props.canOperateThread}
968 onPress={props.onStopThread}
969 />
970 ) : showResumeAction ? (
971 <ComposerActionButton
972 accessibilityLabel="Resume queue"
973 icon="play"
974 disabled={!props.canOperateThread || resumingQueue}
975 onPress={() => void handleResumeQueue()}
976 />
977 ) : (
978 <SendActionButton
979 accessibilityLabel={sendBlockedReason ?? sendLabel}
980 presentation={sendPresentation}
981 disabled={!canSend}
982 onSend={handleSend}
983 />
984 )}
985 </View>
986 ) : null}
987 {isExpanded ? <View className="h-1" /> : null}
988 </ComposerDictationDraftContent>
989 <Animated.View
990 accessibilityElementsHidden={!isToolbarVisible}
991 collapsable={false}
992 importantForAccessibility={isToolbarVisible ? "auto" : "no-hide-descendants"}
993 layout={COMPOSER_LAYOUT_TRANSITION}
994 pointerEvents={isToolbarVisible ? "auto" : "none"}
995 style={
996 isExpanded
997 ? undefined
998 : {
999 position: "absolute",
1000 bottom: 2,
1001 left: 0,
1002 right: 0,
1006 <ComposerDictationToolbar
1007 showsDictation={isVoiceInputPresented}
1008 visible={isToolbarVisible}
1010 <ComposerToolbarRow
1011 paddingBottom={0}
1012 paddingHorizontal={0}
1013 paddingTop={0}
1014 style={{ gap: 0 }}
1016 <ComposerDictationCancelAction
1017 presentation={voicePresentation}
1018 onCancel={voiceInput.cancel}
1019 />
1020 {isVoiceInputPresented ? (
1021 <ComposerDictationStatus
1022 audioLevels={voiceInput.audioLevels}
1023 elapsedSeconds={voiceInput.elapsedSeconds}
1024 phase={voiceInput.state.phase}
1025 presentation={voicePresentation}
1026 onDismissError={voiceInput.cancel}
1027 />
1028 ) : (
1029 <View className="min-w-0 flex-1 flex-row items-center justify-between">
1030 <ComposerAttachmentButton
1031 supportsFiles={Boolean(
1032 props.serverConfig?.environment.capabilities.fileAttachments,
1033 )}
1034 onPickMedia={props.onPickDraftMedia}
1035 onPickFiles={props.onPickDraftFiles}
1036 />
1037 <View className="min-w-0 shrink">
1038 <ComposerInlineControl
1039 accessibilityLabel="Model and reasoning settings"
1040 emphasized
1041 renderIcon={(size) => (
1042 <ProviderIcon
1043 iconUrl={currentModelOption?.providerIconUrl}
1044 provider={currentModelOption?.providerDriver}
1045 size={size}
1046 />
1047 )}
1048 label={currentModelOption?.label ?? currentModelSelection.model}
1049 maxWidth="100%"
1050 onPress={openSettings}
1051 />
1052 </View>
1053 </View>
1054 )}
1055 <View className="shrink-0 flex-row items-center">
1056 <ComposerDictationPrimaryAction
1057 state={voiceInput.state}
1058 presentation={voicePresentation}
1059 isAvailable={voiceInput.isAvailable}
1060 onStart={voiceInput.start}
1061 onConfirm={voiceInput.stop}
1062 onCancel={voiceInput.cancel}
1063 />
1064 {showStopAction ? (
1065 <ComposerActionButton
1066 accessibilityLabel="Stop agent"
1067 icon="stop.fill"
1068 variant="danger"
1069 disabled={!props.canOperateThread}
1070 onPress={props.onStopThread}
1071 />
1072 ) : showResumeAction && voicePresentation.showsSend ? (
1073 <ComposerActionButton
1074 accessibilityLabel="Resume queue"
1075 icon="play"
1076 disabled={!props.canOperateThread || resumingQueue}
1077 onPress={() => void handleResumeQueue()}
1078 />
1079 ) : voicePresentation.showsSend ? (
1080 <SendActionButton
1081 accessibilityLabel={sendBlockedReason ?? sendLabel}
1082 presentation={sendPresentation}
1083 disabled={!canSend}
1084 onSend={handleSend}
1085 />
1086 ) : null}
1087 </View>
1088 </ComposerToolbarRow>
1089 </ComposerDictationToolbar>
1090 </Animated.View>
1091 </ComposerSurface>
1092​
1093 {props.connectionState === "connected" && !props.canOperateThread ? (
1094 <Text className="pt-2 text-xs text-foreground-muted">
1095 This connection cannot control this task. You can still edit your draft.
1096 </Text>
1097 ) : null}
1098 </Animated.View>
1099​
1100 <VideoPreviewModal source={previewVideo} onRequestClose={closePreview} />
1101 <FilePreviewModal source={previewFile} onRequestClose={closePreview} />
1102 </Animated.View>
1103 );