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

ThreadComposer.tsx

1,200 lines48.3 KB

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