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

ThreadComposer.tsx

1,229 lines48.2 KB

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