Open History to see the last commit
1import { useNavigation } from "@react-navigation/native";
2import type { WorktreeSetupCardProps } from "./worktree-setup-card";
3import type { ComposerTextPaste } from "../../native/T3ComposerEditor.types";
4import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
5import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
6import type {
7 CodexFeedbackSubmission,
8 EnvironmentThreadStatus,
9} from "@t3tools/client-runtime/state/threads";
10import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
11import { resolveProviderSkillsForCwd } from "@t3tools/client-runtime/providerSkills";
12import type { LegendListRef } from "@legendapp/list/react-native";
13import { HeaderHeightContext } from "@react-navigation/elements";
14import type {
15 EnvironmentId,
16 MessageId,
17 ModelSelection,
18 ProviderApprovalDecision,
19 ProviderInteractionMode,
20 RuntimeMode,
21 RuntimeRequestId,
22 ServerConfig as T3ServerConfig,
23 ThreadId,
24 UsageLimitsReport,
25} from "@t3tools/contracts";
26import {
27 appendCodexArtifactTemplateUsePrompt,
28 type CodexArtifactTemplate,
29} from "@t3tools/client-runtime/codex-artifact-templates";
30import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";
31import { resolveSubagentPillSegment } from "@t3tools/client-runtime/state/thread-subagents";
32import type { QueuedRunEdit } from "../../state/queued-run-edit";
33import type { FollowUpBehavior } from "../../lib/followUpBehavior";
34import * as Haptics from "expo-haptics";
35import {
36 memo,
37 useCallback,
38 useContext,
39 useEffect,
40 useLayoutEffect,
41 useMemo,
42 useRef,
43 useState,
44} from "react";
45import {
46 Alert,
47 AppState,
48 Keyboard,
49 Platform,
50 useWindowDimensions,
51 View,
52 type GestureResponderEvent,
53} from "react-native";
54import {
55 KeyboardController,
56 KeyboardStickyView,
57 useKeyboardState,
58} from "react-native-keyboard-controller";
59import Animated, {
60 Easing,
61 FadeInDown,
62 FadeOut,
63 ReduceMotion,
64 useAnimatedReaction,
65 useAnimatedStyle,
66 useSharedValue,
67 withTiming,
68} from "react-native-reanimated";
69import { useSafeAreaInsets } from "react-native-safe-area-context";
70import { useWorkspaceContentWidth } from "../layout/workspace-content-width";
71import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
72import { collectProviderUsageLimits } from "@t3tools/shared/usageLimits";
73import type { ComposerEditorHandle } from "../../components/ComposerEditor";
74import type { StatusTone } from "../../components/StatusPill";
75import type { DraftComposerAttachment } from "../../lib/composerImages";
76import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
77import { editPendingThreadMessage } from "../../state/edit-pending-thread-message";
78import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
79import { scopedThreadKey } from "../../lib/scopedEntities";
80import { threadEnvironment } from "../../state/threads";
81import { useAtomCommand } from "../../state/use-atom-command";
82import type {
83 PendingApproval,
84 PendingUserInput,
85 PendingUserInputDraftAnswer,
86 ThreadFeedEntry,
87 ThreadFeedLatestRun,
88} from "../../lib/threadActivity";
89import { PendingApprovalCard } from "./PendingApprovalCard";
90import { ComposerFeedback } from "./ComposerFeedback";
91import { ComposerUsageLimits } from "./ComposerUsageLimits";
92import { PendingUserInputCard } from "./PendingUserInputCard";
93import { ThreadCreationFailedCard } from "./ThreadCreationFailedCard";
94import {
95 FLOATING_WORKING_CONTROL_COVERAGE,
96 FloatingWorkingControl,
97} from "./floating-working-control";
98import { connectionFloatingStatus, type FloatingWorkingStatus } from "./floating-working-status";
99import {
100 derivePendingUserInputMaxHeight,
101 ESTIMATED_KEYBOARD_HEIGHT,
102 USER_INPUT_TOGGLE_DURATION_MS,
103} from "./pendingUserInputLayout";
104import {
105 COMPOSER_COLLAPSED_CHROME,
106 COMPOSER_EXPANDED_CHROME,
107 COMPOSER_LAYOUT_TRANSITION,
108 COMPOSER_TRANSITION_DURATION_MS,
109 ThreadComposer,
110} from "./ThreadComposer";
111import { ThreadFeed, type ThreadFeedHistoryControls } from "./ThreadFeed";
112import { useThreadTurnSubagents } from "./ThreadAgentsSheet";
113import { ComposerQueuedEditBanner } from "./ComposerQueuedEdit";
114import { useThreadQueuedCount } from "./ThreadQueueControl";
115import type { ThreadContentPresentation } from "./threadContentPresentation";
116import { resolveThreadFeedSubmissionAnchor } from "./thread-feed-live-follow";
117
118export interface ThreadDetailScreenProps {
119 readonly worktreeSetup?: WorktreeSetupCardProps | null;
120 readonly setupWorkingStartedAt?: string | null;
121 readonly selectedThread: EnvironmentThreadShell;
122 readonly contentPresentation: ThreadContentPresentation;
123 readonly screenTone: StatusTone;
124 readonly connectionError: string | null;
125 readonly environmentLabel: string | null;
126 readonly feedbackSubmissions: ReadonlyArray<CodexFeedbackSubmission>;
127 readonly onDismissFeedback: (id: MessageId) => void;
128 readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
129 readonly activityRun: ThreadFeedLatestRun | null;
130 readonly activeWorkStartedAt: string | null;
131 readonly isCompacting: boolean;
132 /**
133 * The server has not created this thread yet. "preparing" runs while the
134 * queued creation is delivered (a worktree may be checking out); "failed"
135 * is a rejected creation whose content went back to the project draft.
136 */
137 readonly creationState:
138 | { readonly kind: "preparing"; readonly preparingWorktree: boolean }
139 | { readonly kind: "failed"; readonly reason: string; readonly onEditTask: () => void }
140 | null;
141 readonly activePendingApproval: PendingApproval | null;
142 readonly respondingApprovalId: RuntimeRequestId | null;
143 readonly activePendingUserInput: PendingUserInput | null;
144 readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
145 readonly activePendingUserInputAnswers: Record<string, string | ReadonlyArray<string>> | null;
146 readonly respondingUserInputId: RuntimeRequestId | null;
147 readonly draftMessage: string;
148 readonly draftAttachments: ReadonlyArray<DraftComposerAttachment>;
149 readonly connectionStateLabel: EnvironmentConnectionPhase;
150 /** Message sync status for the selected thread (drives the composer status pill). */
151 readonly threadSyncStatus?: EnvironmentThreadStatus;
152 /** Progressive history controls for oversized mobile thread opens. */
153 readonly historyControls?: ThreadFeedHistoryControls;
154 readonly activeThreadBusy: boolean;
155 readonly canStopThread: boolean;
156 /** Set while a queued message is open in the composer for editing. */
157 readonly queuedRunEdit: QueuedRunEdit | null;
158 readonly composerDraftKey: string | null;
159 readonly followUpBehavior: FollowUpBehavior;
160 readonly canSteerActiveTurn: boolean;
161 readonly isSavingQueuedEdit: boolean;
162 readonly onCancelQueuedRunEdit: () => void;
163 readonly onRemoveQueuedEditAttachment: (attachmentId: string) => void;
164 readonly environmentId: EnvironmentId;
165 readonly projectWorkspaceRoot: string | null;
166 readonly threadCwd: string | null;
167 readonly selectedThreadQueueCount: number;
168 readonly queuedMessages: ReadonlyArray<QueuedThreadMessage>;
169 readonly dispatchingMessageId: MessageId | null;
170 readonly serverConfig: T3ServerConfig | null;
171 readonly layoutVariant?: LayoutVariant;
172 readonly usesAutomaticContentInsets?: boolean;
173 readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
174 readonly onOpenConnectionEditor: () => void;
175 readonly onChangeDraftMessage: (value: string) => void;
176 readonly onPickDraftMedia: () => Promise<void>;
177 readonly onPickDraftFiles: () => Promise<void>;
178 readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
179 readonly onNativePasteText: (paste: ComposerTextPaste) => Promise<void>;
180 readonly onRemoveDraftImage: (imageId: string) => void;
181 readonly onStopThread: () => void;
182 readonly onSendMessage: () => Promise<MessageId | null>;
183 readonly onReconnectEnvironment: () => void;
184 /** Whether the model picker may offer providers other than this thread's. */
185 readonly canSwitchThreadProvider: boolean;
186 readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
187 readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
188 readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
189 readonly onRespondToApproval: (
190 requestId: RuntimeRequestId,
191 decision: ProviderApprovalDecision,
192 ) => Promise<unknown>;
193 readonly onSelectUserInputOption: (
194 requestId: RuntimeRequestId,
195 question: ThreadUserInputQuestion,
196 value: string,
197 ) => void;
198 readonly onChangeUserInputCustomAnswer: (
199 requestId: RuntimeRequestId,
200 questionId: string,
201 customAnswer: string,
202 ) => void;
203 readonly onSubmitUserInput: () => Promise<unknown>;
204 readonly onDismissUserInput: () => Promise<unknown>;
205 readonly showContent?: boolean;
206}
207
208function latestStreamingAssistantMessage(
209 feed: ReadonlyArray<ThreadFeedEntry>,
210): { readonly id: string; readonly textLength: number } | null {
211 for (let index = feed.length - 1; index >= 0; index -= 1) {
212 const entry = feed[index];
213 if (entry?.type !== "message") {
214 continue;
215 }
216 if (entry.message.role !== "assistant" || !entry.message.streaming) {
217 continue;
218 }
219 return {
220 id: entry.message.id,
221 textLength: entry.message.text.length,
222 };
223 }
224
225 return null;
226}
227
228function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedEntry>) {
229 const lastStreamingAssistantRef = useRef<{
230 readonly id: string;
231 readonly textLength: number;
232 } | null>(null);
233 const lastStreamHapticAtRef = useRef(0);
234 const hydratedRef = useRef(false);
235 const previousThreadIdRef = useRef(threadId);
236
237 useEffect(() => {
238 if (previousThreadIdRef.current !== threadId) {
239 previousThreadIdRef.current = threadId;
240 hydratedRef.current = false;
241 }
242
243 const latestStreamingMessage = latestStreamingAssistantMessage(feed);
244
245 if (!hydratedRef.current) {
246 hydratedRef.current = true;
247 lastStreamingAssistantRef.current = latestStreamingMessage;
248 return;
249 }
250
251 if (!latestStreamingMessage) {
252 lastStreamingAssistantRef.current = null;
253 return;
254 }
255
256 const previousStreamingMessage = lastStreamingAssistantRef.current;
257 lastStreamingAssistantRef.current = latestStreamingMessage;
258
259 const isNewStream = previousStreamingMessage?.id !== latestStreamingMessage.id;
260 const textGrew =
261 previousStreamingMessage?.id === latestStreamingMessage.id &&
262 latestStreamingMessage.textLength > previousStreamingMessage.textLength;
263
264 if (!isNewStream && !textGrew) {
265 return;
266 }
267
268 const now = Date.now();
269 if (!isNewStream && now - lastStreamHapticAtRef.current < 320) {
270 return;
271 }
272
273 lastStreamHapticAtRef.current = now;
274 void Haptics.selectionAsync();
275 }, [threadId, feed]);
276}
277
278const USER_INPUT_TOGGLE_TIMING = {
279 duration: USER_INPUT_TOGGLE_DURATION_MS,
280 easing: Easing.out(Easing.cubic),
281};
282
283export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
284 const insets = useSafeAreaInsets();
285 const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
286 const liveKeyboardHeight = useKeyboardState((state) => state.height);
287 // Android can swallow the IME hide callbacks when the app is backgrounded
288 // mid keyboard-hide (the reported repro: send — which blurs and starts the
289 // hide — then Home within a second). The keyboard library's height AND
290 // visibility then stay frozen open, so gating the sticky translation on
291 // visibility alone still strands the composer after resume. Quarantine the
292 // translation on every Android resume instead; any sign of a live keyboard
293 // stream — an owned input gaining focus, or any visibility/height movement —
294 // lifts it. A healthy resume sees no visual difference (the translation is
295 // already zero while the keyboard is closed).
296 const [keyboardStateSuspect, setKeyboardStateSuspect] = useState(false);
297 useEffect(() => {
298 if (Platform.OS !== "android") {
299 return;
300 }
301 const subscription = AppState.addEventListener("change", (state) => {
302 if (state === "active") {
303 setKeyboardStateSuspect(true);
304 }
305 });
306 return () => {
307 subscription.remove();
308 };
309 }, []);
310 useEffect(() => {
311 setKeyboardStateSuspect(false);
312 }, [isKeyboardVisible, liveKeyboardHeight]);
313 const handleOwnedInputFocusChange = useCallback((focused: boolean) => {
314 if (focused) {
315 setKeyboardStateSuspect(false);
316 }
317 }, []);
318 const windowHeight = useWindowDimensions().height;
319 const navigationHeaderHeight = useContext(HeaderHeightContext) || insets.top + 44;
320 const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
321 const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
322 const navigation = useNavigation();
323 const queuedCount = useThreadQueuedCount({
324 environmentId: props.environmentId,
325 threadId: props.selectedThread.id,
326 });
327 const turnSubagents = useThreadTurnSubagents({
328 environmentId: props.environmentId,
329 threadId: props.selectedThread.id,
330 });
331 const agentsSegment = resolveSubagentPillSegment(turnSubagents);
332 const composerEditorRef = useRef<ComposerEditorHandle>(null);
333 // Entering edit mode from the queue sheet should land in a ready composer,
334 // not require a second tap on a composer already holding the message.
335 const editingRunId = props.queuedRunEdit?.runId ?? null;
336 useEffect(() => {
337 if (editingRunId === null) return;
338 const frame = requestAnimationFrame(() => composerEditorRef.current?.focus());
339 return () => cancelAnimationFrame(frame);
340 }, [editingRunId]);
341 const draftMessageRef = useRef(props.draftMessage);
342 draftMessageRef.current = props.draftMessage;
343 const composerOverlayRef = useRef<View>(null);
344 const listRef = useRef<LegendListRef>(null);
345 const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
346 const selectedThreadKeyRef = useRef(selectedThreadKey);
347 const lastScrolledSubmittedMessageIdRef = useRef<MessageId | null>(null);
348 const [composerExpanded, setComposerExpanded] = useState(false);
349 const [composerFocused, setComposerFocused] = useState(false);
350 const handleComposerFocusChange = useCallback(
351 (focused: boolean) => {
352 setComposerFocused(focused);
353 handleOwnedInputFocusChange(focused);
354 },
355 [handleOwnedInputFocusChange],
356 );
357 const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
358 const [submittedMessageId, setSubmittedMessageId] = useState<MessageId | null>(null);
359 const [endFollowEnabled, setEndFollowEnabled] = useState(true);
360 // Android keys the safe-area padding on keyboard visibility (#5988): the
361 // back gesture closes the keyboard while the editor stays focused, and a
362 // focus-keyed inset would leave the toolbar under the gesture bar. iOS must
363 // NOT use visibility — it only flips on keyboardDidHide, after the hide
364 // animation, so the composer would ride down flush to the screen edge and
365 // then snap up into the inset. On iOS blur precedes the hide, so the
366 // focus-keyed inset is already in place while the composer rides down.
367 // Dictation keeps that focus while the composer switches to its compact pill.
368 const composerBottomInset = (
369 Platform.OS === "android" ? isKeyboardVisible : composerExpanded || composerFocused
370 )
371 ? 0
372 : Math.max(insets.bottom, 12);
373 const contentPresentationKind = props.contentPresentation.kind;
374 // The raw sync status enters "synchronizing" on every full fetch, cached or
375 // not. Whether messages are already on screen decides the pill label: no
376 // data yet → "Loading messages", cached data reconciling → "Syncing".
377 const threadSyncLabel = (() => {
378 switch (props.threadSyncStatus) {
379 case "empty":
380 case "cached":
381 case "synchronizing":
382 if (contentPresentationKind === "ready") {
383 return "Syncing messages...";
384 }
385 return contentPresentationKind === "loading" ? "Loading messages..." : null;
386 default:
387 return null;
388 }
389 })();
390 // One floating pill above the composer: it reads the connection phase while
391 // disconnected, the sync state while messages load, then the working timer
392 // once the feed is settled.
393 const floatingStatus = ((): FloatingWorkingStatus | null => {
394 const connectionStatus = connectionFloatingStatus({
395 connectionError: props.connectionError,
396 connectionState: props.connectionStateLabel,
397 environmentLabel: props.environmentLabel,
398 onReconnect: props.onReconnectEnvironment,
399 });
400 if (connectionStatus !== null) {
401 return connectionStatus;
402 }
403 if (props.activePendingApproval !== null || props.activePendingUserInput !== null) {
404 return null;
405 }
406 if (props.creationState?.kind === "preparing") {
407 // The setup header already reports progress in the feed.
408 if (props.worktreeSetup) return null;
409 return {
410 kind: "preparing",
411 label: props.creationState.preparingWorktree ? "Setting up worktree…" : "Starting…",
412 };
413 }
414 if (props.creationState?.kind === "failed") {
415 return null;
416 }
417 if (threadSyncLabel !== null) {
418 return { kind: "syncing", label: threadSyncLabel };
419 }
420 if (props.isCompacting && contentPresentationKind === "ready") {
421 return { kind: "compacting" };
422 }
423 if (props.activeWorkStartedAt !== null && contentPresentationKind === "ready") {
424 return { kind: "working", startedAt: props.activeWorkStartedAt };
425 }
426 return null;
427 })();
428 const showWorkingControl = floatingStatus !== null;
429 // Connection and working status occupy the same space. Keep the feed inset
430 // stable when reconnecting hands off to syncing and then to a running turn.
431 const showFloatingStatus =
432 showWorkingControl ||
433 queuedCount > 0 ||
434 agentsSegment !== null ||
435 props.connectionStateLabel !== "connected" ||
436 props.queuedMessages.length > 0 ||
437 props.selectedThreadFeed.some(
438 (entry) => "acknowledged" in entry && entry.acknowledged === true,
439 );
440 const selectedThreadFeed = props.selectedThreadFeed;
441 const hasCompactableConversation =
442 selectedThreadFeed.some(
443 (entry) =>
444 entry.type === "message" &&
445 entry.message.role === "user" &&
446 ((entry.message.attachments?.length ?? 0) > 0 ||
447 entry.message.text.trim().toLowerCase() !== "/compact"),
448 ) ||
449 (props.historyControls?.hasMoreHistory === true &&
450 props.selectedThread.latestUserMessageAt !== null);
451 const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
452 const composerOverlapHeight = composerChrome + composerBottomInset;
453 // While a user-input request is pending, the questionnaire owns the
454 // composer slot outright: expanded it is the full card, collapsed it is a
455 // composer-style bar in the same place (with its own stop control). The
456 // composer never mounts into the transition, which keeps the collapse and
457 // keyboard animations coherent. Collapse state is keyed by request id so a
458 // new request re-expands automatically.
459 const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
460 useState<RuntimeRequestId | null>(null);
461 const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
462 // The open /usage-limits panel for this thread, model and turn. Only the open
463 // moment is stored: the rows read live provider data, so a redeemed reset
464 // credit or refreshed probe shows through. Anything that spends quota closes
465 // it: a new turn from any source, or the agent resuming after an approval or
466 // answered question.
467 const [usageLimitsPanel, setUsageLimitsPanel] = useState<{
468 readonly key: string;
469 readonly threadKey: string;
470 readonly now: number;
471 } | null>(null);
472 // A pending approval or question is part of the key: once it is answered,
473 // from this client or any other, the agent resumes and spends quota.
474 const usageLimitsKey = [
475 selectedThreadKey,
476 props.selectedThread.modelSelection.instanceId,
477 props.selectedThread.latestRun?.runId ?? "",
478 props.activePendingApproval?.requestId ?? props.activePendingUserInput?.requestId ?? "",
479 ].join(":");
480 // Drop the snapshot as soon as the key changes so it cannot resurface stale.
481 if (usageLimitsPanel !== null && usageLimitsPanel.key !== usageLimitsKey) {
482 setUsageLimitsPanel(null);
483 }
484 const usageLimitsReport = useMemo(
485 () =>
486 usageLimitsPanel !== null && usageLimitsPanel.key === usageLimitsKey
487 ? collectProviderUsageLimits(
488 props.selectedThread.modelSelection.instanceId,
489 props.serverConfig?.providers ?? [],
490 props.serverConfig?.usageLimitSources ?? [],
491 usageLimitsPanel.now,
492 )
493 : null,
494 [
495 props.selectedThread.modelSelection.instanceId,
496 props.serverConfig,
497 usageLimitsKey,
498 usageLimitsPanel,
499 ],
500 );
501 const showUsageLimits = useCallback(
502 (report: UsageLimitsReport | null) =>
503 setUsageLimitsPanel(
504 report === null
505 ? null
506 : {
507 key: usageLimitsKey,
508 threadKey: selectedThreadKey,
509 now: Date.parse(report.createdAt),
510 },
511 ),
512 [selectedThreadKey, usageLimitsKey],
513 );
514 const dismissUsageLimits = useCallback(() => setUsageLimitsPanel(null), []);
515 // A send may resolve after navigating away, so only the originating
516 // thread's panel is cleared; a panel opened elsewhere in the meantime stays.
517 const clearUsageLimitsFor = useCallback(
518 (threadKey: string) =>
519 setUsageLimitsPanel((current) =>
520 current !== null && current.threadKey === threadKey ? null : current,
521 ),
522 [],
523 );
524 const userInputCollapsed =
525 activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
526 // The card's height RESERVES keyboard space at all times instead of
527 // tracking the keyboard: transforms (the sticky translation) apply
528 // same-frame on the UI thread while layout props lag a Yoga pass behind,
529 // so any height that follows the keyboard flashes the card over the nav
530 // header on the way up. With a constant height the keyboard transition is
531 // pure translation — frame-perfect by construction — and the resting card
532 // stays compact over the transcript. Before the first open the reserve is
533 // an estimate; once a real height is known the card corrects once,
534 // discretely.
535 const [lastKnownKeyboardHeight, setLastKnownKeyboardHeight] = useState(0);
536 useEffect(() => {
537 if (liveKeyboardHeight > 0 && liveKeyboardHeight !== lastKnownKeyboardHeight) {
538 setLastKnownKeyboardHeight(liveKeyboardHeight);
539 }
540 }, [lastKnownKeyboardHeight, liveKeyboardHeight]);
541 const pendingUserInputMaxHeight = derivePendingUserInputMaxHeight({
542 windowHeight,
543 keyboardHeight:
544 lastKnownKeyboardHeight > 0 ? lastKnownKeyboardHeight : ESTIMATED_KEYBOARD_HEIGHT,
545 navigationHeaderHeight,
546 // The questionnaire owns the composer slot, so only the composer's
547 // bottom inset still overlaps.
548 composerOverlapHeight: composerBottomInset,
549 });
550 const estimatedOverlayHeight = composerOverlapHeight;
551 // The overlay's measured height includes the home-indicator inset (the
552 // composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
553 // UIKit add the safe-area bottom to the content inset AGAIN — leaving a
554 // dead strip between the resting content and the composer. Report the
555 // overlay height minus the safe area; UIKit adds it back, and ThreadFeed
556 // hands LegendList the same delta via contentInsetEndStaticAdjustment so
557 // its end-scroll math matches the real resting position.
558 const nativeInsetOvercount =
559 props.usesAutomaticContentInsets === true && Platform.OS === "ios" ? insets.bottom : 0;
560 const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
561 listRef,
562 composerOverlayRef,
563 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
564 -nativeInsetOvercount,
565 Platform.OS === "ios" ? COMPOSER_TRANSITION_DURATION_MS : 0,
566 );
567 // The expanded questionnaire is an absolute overlay on iOS, so it never
568 // changes the measured overlay height (that constancy is what keeps the
569 // feed from snapping on collapse/expand). The toggle choreography runs on
570 // SHARED VALUES set directly in the tap handler — one JS hop, then the
571 // card's rise/sink and the feed's end-inset glide animate in lockstep on
572 // the UI thread, keyboard-style, instead of waiting on React mount +
573 // onLayout + state round trips. Coverage (how far the card extends above
574 // the bar) is measured straight into a shared value by the card's
575 // onLayout, with no re-render.
576 const userInputCardProgress = useSharedValue(1);
577 const userInputInsetProgress = useSharedValue(1);
578 const userInputCardCoverage = useSharedValue(0);
579 const floatingControlCoverage = useSharedValue(
580 showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0,
581 );
582 useEffect(() => {
583 floatingControlCoverage.value = withTiming(
584 showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0,
585 { duration: 180, reduceMotion: ReduceMotion.System },
586 );
587 }, [floatingControlCoverage, showFloatingStatus]);
588 // Android renders the expanded card in-flow (it cannot hit-test the iOS
589 // overlay outside the bar's bounds), so its measured overlay height already
590 // includes the card — the coverage extra is iOS-only.
591 const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null;
592 const combinedContentInsetEndAdjustment = useSharedValue(
593 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
594 );
595 useAnimatedReaction(
596 () =>
597 contentInsetEndAdjustment.value +
598 floatingControlCoverage.value +
599 (userInputCoverageApplies ? userInputInsetProgress.value * userInputCardCoverage.value : 0),
600 (value) => {
601 combinedContentInsetEndAdjustment.value = value;
602 },
603 [userInputCoverageApplies],
604 );
605 const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
606 const endFollowEnabledRef = useRef(true);
607 endFollowEnabledRef.current = endFollowEnabled;
608 const overlayRepinTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
609 const previousWorkingControlStateRef = useRef({
610 threadKey: selectedThreadKey,
611 visible: false,
612 });
613 // The list's own corrections for these inset changes drift on short
614 // content (and the error compounds across toggles), so deterministically
615 // re-pin the end once a toggle settles: a no-op when the resting position
616 // is already right, corrective when it is not. Follow state is re-checked
617 // inside the callback — the user may grab the list during the settle
618 // window, and yanking them back would override a live gesture.
619 const scheduleOverlayRepin = useCallback(
620 (delayMs: number) => {
621 if (overlayRepinTimerRef.current !== null) {
622 clearTimeout(overlayRepinTimerRef.current);
623 }
624 overlayRepinTimerRef.current = setTimeout(() => {
625 overlayRepinTimerRef.current = null;
626 if (!endFollowEnabledRef.current) {
627 return;
628 }
629 void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
630 freeze.set(false);
631 });
632 }, delayMs);
633 },
634 [freeze, scrollMessageToEnd],
635 );
636 useEffect(
637 () => () => {
638 if (overlayRepinTimerRef.current !== null) {
639 clearTimeout(overlayRepinTimerRef.current);
640 }
641 },
642 [],
643 );
644 useEffect(() => {
645 const previous = previousWorkingControlStateRef.current;
646 const threadChanged = previous.threadKey !== selectedThreadKey;
647 const visibilityChanged = previous.visible !== showFloatingStatus;
648 previousWorkingControlStateRef.current = {
649 threadKey: selectedThreadKey,
650 visible: showFloatingStatus,
651 };
652 if ((!threadChanged && !visibilityChanged) || (threadChanged && !showFloatingStatus)) {
653 return;
654 }
655 // LegendList applies the larger inset but does not re-anchor short
656 // followed conversations when this floating coverage changes after the
657 // initial load. Re-pin after the finite inset transition; the callback
658 // checks follow state again so a user who scrolled up stays put.
659 scheduleOverlayRepin(230);
660 }, [scheduleOverlayRepin, selectedThreadKey, showFloatingStatus]);
661 const handleToggleUserInputCollapsed = useCallback(() => {
662 if (activeUserInputRequestId === null) {
663 return;
664 }
665 if (userInputCollapsed) {
666 // Expanding: card and feed glide start NOW, on the UI thread.
667 userInputCardProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
668 userInputInsetProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
669 setCollapsedUserInputRequestId(null);
670 scheduleOverlayRepin(USER_INPUT_TOGGLE_DURATION_MS + 50);
671 } else {
672 // Collapsing hides the custom-answer inputs; release the keyboard with
673 // them instead of leaving it up over a dead responder.
674 Keyboard.dismiss();
675 userInputCardProgress.value = withTiming(0, USER_INPUT_TOGGLE_TIMING);
676 // Instant: the sinking card still covers the strip being revealed, and
677 // animating the inset downward is what drifted the short-content end
678 // anchor.
679 userInputInsetProgress.value = 0;
680 setCollapsedUserInputRequestId(activeUserInputRequestId);
681 scheduleOverlayRepin(60);
682 }
683 }, [
684 activeUserInputRequestId,
685 scheduleOverlayRepin,
686 userInputCardProgress,
687 userInputCollapsed,
688 userInputInsetProgress,
689 ]);
690 useEffect(() => {
691 // A new request always arrives expanded.
692 userInputCardProgress.value = 1;
693 userInputInsetProgress.value = 1;
694 }, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]);
695 const showContent = props.showContent ?? true;
696 const layoutVariant = props.layoutVariant ?? "compact";
697 const isSplitLayout = layoutVariant === "split";
698 const contentMaxWidth = isSplitLayout ? CHAT_CONTENT_MAX_WIDTH : undefined;
699 const workspaceContentWidth = useWorkspaceContentWidth();
700 const composerWidthStyle = useAnimatedStyle(() =>
701 isSplitLayout && workspaceContentWidth !== null
702 ? { width: workspaceContentWidth.value, right: undefined }
703 : { width: undefined, right: 0 },
704 );
705 const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
706 useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
707 const selectedProviderSkills = useMemo(() => {
708 const provider = props.serverConfig?.providers.find(
709 (candidate) => candidate.instanceId === selectedInstanceId,
710 );
711 return provider
712 ? resolveProviderSkillsForCwd(provider, props.threadCwd ?? props.projectWorkspaceRoot)
713 : [];
714 }, [props.projectWorkspaceRoot, props.serverConfig, props.threadCwd, selectedInstanceId]);
715
716 useLayoutEffect(() => {
717 selectedThreadKeyRef.current = selectedThreadKey;
718 // A replaced or unmounted native editor may not emit a blur event.
719 setComposerFocused(false);
720 }, [selectedThreadKey, showContent]);
721
722 const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
723 const lastDispatchedVisitRef = useRef<string | null>(null);
724 const lastVisitDispatchRef = useRef({ threadKey: selectedThreadKey, at: 0 });
725 const selectedThreadId = props.selectedThread.id;
726 const selectedThreadUpdatedAt = props.selectedThread.updatedAt;
727 const selectedThreadLastVisitedAt = props.selectedThread.lastVisitedAt;
728 const selectedThreadCompletedAt = props.selectedThread.latestRun?.completedAt;
729 useEffect(() => {
730 // Records the server-side visited watermark while the thread is on
731 // screen (mirror of web ChatView), so the "Done" marker clears on every
732 // device. Field absent → the server predates visited tracking.
733 if (!showContent || selectedThreadLastVisitedAt === undefined) return;
734 const threadUpdatedAtMs = Date.parse(selectedThreadUpdatedAt);
735 if (Number.isNaN(threadUpdatedAtMs)) return;
736 const lastVisitedAtMs = selectedThreadLastVisitedAt
737 ? Date.parse(selectedThreadLastVisitedAt)
738 : NaN;
739 if (!Number.isNaN(lastVisitedAtMs) && lastVisitedAtMs >= threadUpdatedAtMs) return;
740 // Dedupe per watermark — the effect re-runs before the command echo lands.
741 const dispatchKey = `${selectedThreadKey}:${selectedThreadUpdatedAt}`;
742 if (lastDispatchedVisitRef.current === dispatchKey) return;
743 const dispatch = () => {
744 lastDispatchedVisitRef.current = dispatchKey;
745 lastVisitDispatchRef.current = { threadKey: selectedThreadKey, at: Date.now() };
746 void visitThread({
747 environmentId: props.environmentId,
748 input: { threadId: selectedThreadId, visitedAt: selectedThreadUpdatedAt },
749 });
750 };
751 // Completion clears unread state immediately; streaming watermarks use the
752 // same ten-second trailing throttle as web, keeping the newest update.
753 const completedAtMs = selectedThreadCompletedAt ? Date.parse(selectedThreadCompletedAt) : NaN;
754 const hasUnseenCompletion =
755 !Number.isNaN(completedAtMs) &&
756 (Number.isNaN(lastVisitedAtMs) || completedAtMs > lastVisitedAtMs);
757 const previous = lastVisitDispatchRef.current;
758 const elapsed = Date.now() - previous.at;
759 if (previous.threadKey !== selectedThreadKey || hasUnseenCompletion || elapsed >= 10_000) {
760 dispatch();
761 return;
762 }
763 const timer = setTimeout(dispatch, 10_000 - elapsed);
764 return () => clearTimeout(timer);
765 }, [
766 props.environmentId,
767 selectedThreadId,
768 selectedThreadKey,
769 selectedThreadLastVisitedAt,
770 selectedThreadCompletedAt,
771 selectedThreadUpdatedAt,
772 showContent,
773 visitThread,
774 ]);
775
776 useEffect(() => {
777 setAnchorMessageId(null);
778 setSubmittedMessageId(null);
779 lastScrolledSubmittedMessageIdRef.current = null;
780 setEndFollowEnabled(true);
781 freeze.set(false);
782 }, [freeze, selectedThreadKey]);
783
784 useEffect(() => {
785 if (
786 submittedMessageId === null ||
787 anchorMessageId !== submittedMessageId ||
788 lastScrolledSubmittedMessageIdRef.current === submittedMessageId ||
789 contentPresentationKind !== "ready" ||
790 (!selectedThreadFeed.some(
791 (entry) => entry.type === "message" && entry.id === submittedMessageId,
792 ) &&
793 !props.queuedMessages.some((message) => message.messageId === submittedMessageId))
794 ) {
795 return;
796 }
797
798 const targetThreadKey = selectedThreadKey;
799 const frame = requestAnimationFrame(() => {
800 if (selectedThreadKeyRef.current !== targetThreadKey) {
801 return;
802 }
803 lastScrolledSubmittedMessageIdRef.current = submittedMessageId;
804 // Wait for the keyboard dismissal (started by blur() on send) to finish
805 // before scrolling: scrollMessageToEnd freezes keyboard-driven inset
806 // updates while it runs, and a close event swallowed by that freeze
807 // leaves the keyboard padding permanently applied — overshooting the
808 // anchor and leaving a phantom bottom inset once the reply streams in.
809 void KeyboardController.dismiss()
810 .then(() => {
811 if (
812 selectedThreadKeyRef.current !== targetThreadKey ||
813 lastScrolledSubmittedMessageIdRef.current !== submittedMessageId
814 ) {
815 return;
816 }
817 return scrollMessageToEnd({ animated: true, closeKeyboard: false });
818 })
819 .catch(() => {
820 if (
821 selectedThreadKeyRef.current !== targetThreadKey ||
822 lastScrolledSubmittedMessageIdRef.current !== submittedMessageId
823 ) {
824 return;
825 }
826 lastScrolledSubmittedMessageIdRef.current = null;
827 freeze.set(false);
828 });
829 });
830 return () => cancelAnimationFrame(frame);
831 }, [
832 anchorMessageId,
833 submittedMessageId,
834 freeze,
835 contentPresentationKind,
836 props.queuedMessages,
837 selectedThreadFeed,
838 scrollMessageToEnd,
839 selectedThreadKey,
840 ]);
841
842 const handleSendMessage = useCallback(async () => {
843 const targetThreadKey = selectedThreadKey;
844 const hasUserMessage = selectedThreadFeed.some(
845 (entry) => entry.type === "message" && entry.message.role === "user",
846 );
847 const messageId = await props.onSendMessage();
848 if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
849 return messageId;
850 }
851
852 // A sent message makes the snapshot stale; a refused send leaves it in place.
853 clearUsageLimitsFor(targetThreadKey);
854
855 setSubmittedMessageId(messageId);
856 setAnchorMessageId(
857 resolveThreadFeedSubmissionAnchor({
858 currentAnchorMessageId: anchorMessageId,
859 submittedMessageId: messageId,
860 hasStartedTurn: props.selectedThread.latestRun !== null,
861 hasUserMessage,
862 queuedMessageCount: props.selectedThreadQueueCount,
863 }),
864 );
865 composerEditorRef.current?.blur();
866 return messageId;
867 }, [
868 anchorMessageId,
869 clearUsageLimitsFor,
870 props.onSendMessage,
871 props.selectedThread.latestRun,
872 props.selectedThreadQueueCount,
873 selectedThreadFeed,
874 selectedThreadKey,
875 ]);
876
877 const handleEditPendingMessage = useCallback(async (message: QueuedThreadMessage) => {
878 try {
879 if (
880 (await editPendingThreadMessage(message)) &&
881 selectedThreadKeyRef.current === scopedThreadKey(message.environmentId, message.threadId)
882 ) {
883 composerEditorRef.current?.focus();
884 }
885 } catch (error) {
886 Alert.alert(
887 "Could not edit message",
888 error instanceof Error ? error.message : "Please try again.",
889 );
890 }
891 }, []);
892
893 const collapseComposer = useCallback(() => {
894 composerEditorRef.current?.blur();
895 }, []);
896
897 const handleUseArtifactTemplate = useCallback(
898 (template: CodexArtifactTemplate) => {
899 const currentDraft = draftMessageRef.current;
900 const nextDraft = appendCodexArtifactTemplateUsePrompt(currentDraft, template);
901 if (nextDraft !== currentDraft) {
902 draftMessageRef.current = nextDraft;
903 props.onChangeDraftMessage(nextDraft);
904 }
905 requestAnimationFrame(() => {
906 composerEditorRef.current?.focus();
907 composerEditorRef.current?.setSelection({ start: nextDraft.length, end: nextDraft.length });
908 });
909 },
910 [props.onChangeDraftMessage],
911 );
912
913 const handleScrollToEnd = useCallback(() => {
914 void Haptics.selectionAsync();
915 void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
916 freeze.set(false);
917 });
918 }, [freeze, scrollMessageToEnd]);
919
920 const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled;
921 const { themeAppearance } = useAppearancePreferences();
922 const isDarkMode = themeAppearance === "dark";
923
924 const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
925 feedTouchStartRef.current = {
926 pageX: event.nativeEvent.pageX,
927 pageY: event.nativeEvent.pageY,
928 };
929 }, []);
930
931 const handleFeedTouchMove = useCallback((event: GestureResponderEvent) => {
932 const start = feedTouchStartRef.current;
933 if (!start) {
934 return;
935 }
936 const deltaX = event.nativeEvent.pageX - start.pageX;
937 const deltaY = event.nativeEvent.pageY - start.pageY;
938 if (Math.hypot(deltaX, deltaY) > 8) {
939 feedTouchStartRef.current = null;
940 }
941 }, []);
942
943 const handleFeedTouchEnd = useCallback(() => {
944 if (feedTouchStartRef.current) {
945 collapseComposer();
946 }
947 feedTouchStartRef.current = null;
948 }, [collapseComposer]);
949
950 const handleFeedTouchCancel = useCallback(() => {
951 feedTouchStartRef.current = null;
952 }, []);
953
954 return (
955 <View className="flex-1">
956 {showContent ? (
957 <View
958 style={{ flex: 1 }}
959 onTouchStart={handleFeedTouchStart}
960 onTouchMove={handleFeedTouchMove}
961 onTouchEnd={handleFeedTouchEnd}
962 onTouchCancel={handleFeedTouchCancel}
963 >
964 <View
965 pointerEvents="none"
966 className={
967 Platform.OS === "android"
968 ? "absolute inset-0 bg-thread-canvas"
969 : "absolute inset-0 bg-screen"
970 }
971 />
972 <ThreadFeed
973 key={selectedThreadKey}
974 environmentId={props.environmentId}
975 threadId={props.selectedThread.id}
976 workspaceRoot={props.threadCwd}
977 feed={props.selectedThreadFeed}
978 worktreeSetup={props.worktreeSetup}
979 setupWorkingStartedAt={props.setupWorkingStartedAt}
980 queuedMessages={props.queuedMessages}
981 dispatchingMessageId={props.dispatchingMessageId}
982 onEditPendingMessage={handleEditPendingMessage}
983 contentPresentation={props.contentPresentation}
984 agentLabel={agentLabel}
985 threadTitle={props.selectedThread.title}
986 latestRun={props.activityRun}
987 activeWorkStartedAt={props.activeWorkStartedAt}
988 listRef={listRef}
989 freeze={freeze}
990 anchorMessageId={anchorMessageId}
991 submittedMessageId={submittedMessageId}
992 contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
993 contentTopInset={0}
994 contentBottomInset={
995 estimatedOverlayHeight + (showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0)
996 }
997 contentMaxWidth={contentMaxWidth}
998 historyControls={props.historyControls}
999 layoutVariant={layoutVariant}
1000 usesAutomaticContentInsets={props.usesAutomaticContentInsets}
1001 onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
1002 onEndFollowEnabledChange={setEndFollowEnabled}
1003 skills={selectedProviderSkills}
1004 onUseArtifactTemplate={handleUseArtifactTemplate}
1005 />
1006 </View>
1007 ) : (
1008 <View className="flex-1" />
1009 )}
1010
1011 {/* Floating composer — sticks to keyboard via KeyboardStickyView */}
1012 {showContent ? (
1013 <KeyboardStickyView
1014 // iOS emits a native animated height target on both will-show and
1015 // will-hide, so stay subscribed for the full transition. Android
1016 // retains its background/resume stale-state quarantine.
1017 enabled={Platform.OS === "ios" || (isKeyboardVisible && !keyboardStateSuspect)}
1018 pointerEvents="box-none"
1019 style={{ position: "absolute", bottom: 0, left: 0, right: 0, top: 0 }}
1020 offset={{ closed: 0, opened: 0 }}
1021 >
1022 {/* The fixed sticky host gives this bottom-anchored child a stable
1023 coordinate space. Its top and height can then animate together
1024 instead of the auto-sized host jumping to Yoga's destination. */}
1025 <Animated.View
1026 layout={COMPOSER_LAYOUT_TRANSITION}
1027 pointerEvents="box-none"
1028 style={[{ position: "absolute", bottom: 0, left: 0, right: 0 }, composerWidthStyle]}
1029 >
1030 {/* No paddingTop here: the overlay's measured height becomes the
1031 list's bottom inset, so any padding above the pill/composer
1032 pushes the resting content floor up by the same amount. */}
1033 <View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
1034 <FloatingWorkingControl
1035 colorScheme={isDarkMode ? "dark" : "light"}
1036 status={floatingStatus}
1037 showScrollToEnd={showScrollToEndButton}
1038 onScrollToEnd={handleScrollToEnd}
1039 agents={agentsSegment}
1040 onOpenAgents={() => {
1041 Keyboard.dismiss();
1042 navigation.navigate("ThreadAgents", {
1043 environmentId: props.environmentId,
1044 threadId: props.selectedThread.id,
1045 });
1046 }}
1047 queuedCount={queuedCount}
1048 onOpenQueue={() => {
1049 Keyboard.dismiss();
1050 navigation.navigate("ThreadQueue", {
1051 environmentId: props.environmentId,
1052 threadId: props.selectedThread.id,
1053 });
1054 }}
1055 />
1056 <View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
1057 {props.queuedRunEdit !== null ? (
1058 <Animated.View
1059 className="shrink-0"
1060 entering={FadeInDown.duration(180)}
1061 exiting={FadeOut.duration(120)}
1062 >
1063 <ComposerQueuedEditBanner
1064 saving={props.isSavingQueuedEdit}
1065 onCancel={props.onCancelQueuedRunEdit}
1066 />
1067 </Animated.View>
1068 ) : null}
1069 {props.feedbackSubmissions.map((submission) => (
1070 <ComposerFeedback
1071 key={submission.id}
1072 submission={submission}
1073 onDismiss={() => props.onDismissFeedback(submission.id)}
1074 />
1075 ))}
1076 {usageLimitsReport && activeUserInputRequestId === null ? (
1077 <Animated.View
1078 className="shrink-0 px-4 pb-3"
1079 entering={FadeInDown.duration(220)}
1080 exiting={FadeOut.duration(140)}
1081 >
1082 <ComposerUsageLimits
1083 report={usageLimitsReport}
1084 environmentId={props.environmentId}
1085 onClose={dismissUsageLimits}
1086 />
1087 </Animated.View>
1088 ) : null}
1089 {props.creationState?.kind === "failed" ? (
1090 <Animated.View
1091 className="shrink-0 px-4"
1092 style={{ paddingBottom: composerBottomInset }}
1093 entering={FadeInDown.duration(220)}
1094 exiting={FadeOut.duration(140)}
1095 >
1096 <ThreadCreationFailedCard
1097 reason={props.creationState.reason}
1098 onEditTask={props.creationState.onEditTask}
1099 />
1100 </Animated.View>
1101 ) : null}
1102 {props.activePendingApproval || props.activePendingUserInput ? (
1103 <Animated.View
1104 className="shrink-0 gap-3 px-4 pb-3"
1105 // The questionnaire replaces the composer, so it must pad
1106 // the home indicator the composer normally covers.
1107 style={
1108 activeUserInputRequestId !== null
1109 ? { paddingBottom: composerBottomInset }
1110 : undefined
1111 }
1112 entering={FadeInDown.duration(220)}
1113 exiting={FadeOut.duration(140)}
1114 >
1115 {props.activePendingApproval ? (
1116 <PendingApprovalCard
1117 approval={props.activePendingApproval}
1118 respondingApprovalId={props.respondingApprovalId}
1119 onRespond={props.onRespondToApproval}
1120 />
1121 ) : null}
1122 {props.activePendingUserInput ? (
1123 <PendingUserInputCard
1124 pendingUserInput={props.activePendingUserInput}
1125 maxHeight={pendingUserInputMaxHeight}
1126 collapsed={userInputCollapsed}
1127 onToggleCollapsed={handleToggleUserInputCollapsed}
1128 onStopThread={props.onStopThread}
1129 cardProgress={userInputCardProgress}
1130 cardCoverage={userInputCardCoverage}
1131 onInputFocusChange={handleOwnedInputFocusChange}
1132 drafts={props.activePendingUserInputDrafts}
1133 answers={props.activePendingUserInputAnswers}
1134 respondingUserInputId={props.respondingUserInputId}
1135 onSelectOption={props.onSelectUserInputOption}
1136 onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
1137 onSubmit={props.onSubmitUserInput}
1138 onDismiss={props.onDismissUserInput}
1139 />
1140 ) : null}
1141 </Animated.View>
1142 ) : null}
1143 </View>
1144
1145 {/* Hidden (not unmounted) while a user-input request owns the
1146 composer slot, so composer drafts and editor state survive.
1147 A rejected creation has no thread to send to; the failure card
1148 owns the slot instead. */}
1149 <View
1150 style={
1151 activeUserInputRequestId !== null || props.creationState?.kind === "failed"
1152 ? { display: "none" }
1153 : undefined
1154 }
1155 >
1156 <>
1157 <ThreadComposer
1158 editorRef={composerEditorRef}
1159 draftMessage={props.draftMessage}
1160 draftAttachments={props.draftAttachments}
1161 placeholder="Ask the repo agent, or run a command…"
1162 contentMaxWidth={contentMaxWidth}
1163 connectionState={props.connectionStateLabel}
1164 environmentLabel={props.environmentLabel}
1165 selectedThread={props.selectedThread}
1166 hasCompactableConversation={hasCompactableConversation && !props.isCompacting}
1167 serverConfig={props.serverConfig}
1168 queueCount={props.selectedThreadQueueCount}
1169 activeThreadBusy={props.activeThreadBusy}
1170 canStopThread={props.canStopThread}
1171 environmentId={props.environmentId}
1172 projectCwd={props.threadCwd ?? props.projectWorkspaceRoot}
1173 // Follow-ups typed during setup wait in the draft: queueing
1174 // them against a thread id the server may still reject
1175 // would strand them in the outbox.
1176 sendBlockedReason={
1177 props.creationState?.kind === "preparing" ? "Starting the task…" : null
1178 }
1179 draftKey={props.composerDraftKey ?? undefined}
1180 followUpBehavior={props.followUpBehavior}
1181 canSteerActiveTurn={props.canSteerActiveTurn}
1182 queuedEdit={
1183 props.queuedRunEdit === null
1184 ? null
1185 : {
1186 existingAttachments: props.queuedRunEdit.existingAttachments,
1187 saving: props.isSavingQueuedEdit,
1188 onRemoveExistingAttachment: props.onRemoveQueuedEditAttachment,
1189 }
1190 }
1191 bottomInset={composerBottomInset}
1192 onChangeDraftMessage={props.onChangeDraftMessage}
1193 onPickDraftMedia={props.onPickDraftMedia}
1194 onPickDraftFiles={props.onPickDraftFiles}
1195 onNativePasteImages={props.onNativePasteImages}
1196 onNativePasteText={props.onNativePasteText}
1197 onRemoveDraftImage={props.onRemoveDraftImage}
1198 onStopThread={props.onStopThread}
1199 onSendMessage={handleSendMessage}
1200 onShowUsageLimits={showUsageLimits}
1201 canSwitchProvider={props.canSwitchThreadProvider}
1202 onUpdateModelSelection={props.onUpdateThreadModelSelection}
1203 onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
1204 onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
1205 onExpandedChange={setComposerExpanded}
1206 onEditorFocusChange={handleComposerFocusChange}
1207 />
1208 </>
1209 </View>
1210 </View>
1211 </Animated.View>
1212 </KeyboardStickyView>
1213 ) : null}
1214 </View>
1215 );
1216});