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

ThreadComposer.tsx

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