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