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

ThreadDetailScreen.tsx

1,249 lines52.8 KB

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