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