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

ThreadDetailScreen.tsx

1,239 lines52.3 KB

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