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