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: "background",
478 label: pendingBackgroundWork.title,
479 accessibilityLabel: `${pendingBackgroundWork.title}: ${pendingBackgroundWork.items
480 .map((item) => item.label)
481 .join(", ")}`,
482 waiting: pendingBackgroundWork.waiting,
483 };
484 }
485 return null;
486 })();
487 const showWorkingControl = floatingStatus !== null;
488 // Connection and working status occupy the same space. Keep the feed inset
489 // stable when reconnecting hands off to syncing and then to a running turn.
490 const showFloatingStatus =
491 showWorkingControl ||
492 queuedCount > 0 ||
493 agentsSegment !== null ||
494 devicePreviews.length > 0 ||
495 props.connectionStateLabel !== "connected" ||
496 props.queuedMessages.length > 0 ||
497 props.selectedThreadFeed.some(
498 (entry) => "acknowledged" in entry && entry.acknowledged === true,
499 );
500 const selectedThreadFeed = props.selectedThreadFeed;
501 const hasCompactableConversation =
502 selectedThreadFeed.some(
503 (entry) =>
504 entry.type === "message" &&
505 entry.message.role === "user" &&
506 ((entry.message.attachments?.length ?? 0) > 0 ||
507 entry.message.text.trim().toLowerCase() !== "/compact"),
508 ) ||
509 (props.historyControls?.hasMoreHistory === true &&
510 props.selectedThread.latestUserMessageAt !== null);
511 const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
512 const composerOverlapHeight = composerChrome + composerBottomInset;
513 // While a user-input request is pending, the questionnaire owns the
514 // composer slot outright: expanded it is the full card, collapsed it is a
515 // composer-style bar in the same place (with its own stop control). The
516 // composer never mounts into the transition, which keeps the collapse and
517 // keyboard animations coherent. Collapse state is keyed by request id so a
518 // new request re-expands automatically.
519 const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
520 useState<RuntimeRequestId | null>(null);
521 const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
522 // The open /usage-limits panel for this thread, model and turn. Only the open
523 // moment is stored: the rows read live provider data, so a redeemed reset
524 // credit or refreshed probe shows through. Anything that spends quota closes
525 // it: a new turn from any source, or the agent resuming after an approval or
526 // answered question.
527 const [usageLimitsPanel, setUsageLimitsPanel] = useState<{
528 readonly key: string;
529 readonly threadKey: string;
530 readonly now: number;
531 } | null>(null);
532 // A pending approval or question is part of the key: once it is answered,
533 // from this client or any other, the agent resumes and spends quota.
534 const usageLimitsKey = [
535 selectedThreadKey,
536 props.selectedThread.modelSelection.instanceId,
537 props.selectedThread.latestRun?.runId ?? "",
538 props.activePendingApproval?.requestId ?? props.activePendingUserInput?.requestId ?? "",
539 ].join(":");
540 // Drop the snapshot as soon as the key changes so it cannot resurface stale.
541 if (usageLimitsPanel !== null && usageLimitsPanel.key !== usageLimitsKey) {
542 setUsageLimitsPanel(null);
543 }
544 const usageLimitsReport = useMemo(
545 () =>
546 usageLimitsPanel !== null && usageLimitsPanel.key === usageLimitsKey
547 ? collectProviderUsageLimits(
548 props.selectedThread.modelSelection.instanceId,
549 props.serverConfig?.providers ?? [],
550 props.serverConfig?.usageLimitSources ?? [],
551 usageLimitsPanel.now,
552 )
553 : null,
554 [
555 props.selectedThread.modelSelection.instanceId,
556 props.serverConfig,
557 usageLimitsKey,
558 usageLimitsPanel,
559 ],
560 );
561 const showUsageLimits = useCallback(
562 (report: UsageLimitsReport | null) =>
563 setUsageLimitsPanel(
564 report === null
565 ? null
566 : {
567 key: usageLimitsKey,
568 threadKey: selectedThreadKey,
569 now: Date.parse(report.createdAt),
570 },
571 ),
572 [selectedThreadKey, usageLimitsKey],
573 );
574 const dismissUsageLimits = useCallback(() => setUsageLimitsPanel(null), []);
575 // A send may resolve after navigating away, so only the originating
576 // thread's panel is cleared; a panel opened elsewhere in the meantime stays.
577 const clearUsageLimitsFor = useCallback(
578 (threadKey: string) =>
579 setUsageLimitsPanel((current) =>
580 current !== null && current.threadKey === threadKey ? null : current,
581 ),
582 [],
583 );
584 const userInputCollapsed =
585 activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
586 // The card's height RESERVES keyboard space at all times instead of
587 // tracking the keyboard: transforms (the sticky translation) apply
588 // same-frame on the UI thread while layout props lag a Yoga pass behind,
589 // so any height that follows the keyboard flashes the card over the nav
590 // header on the way up. With a constant height the keyboard transition is
591 // pure translation — frame-perfect by construction — and the resting card
592 // stays compact over the transcript. Before the first open the reserve is
593 // an estimate; once a real height is known the card corrects once,
594 // discretely.
595 const [lastKnownKeyboardHeight, setLastKnownKeyboardHeight] = useState(0);
596 useEffect(() => {
597 if (liveKeyboardHeight > 0 && liveKeyboardHeight !== lastKnownKeyboardHeight) {
598 setLastKnownKeyboardHeight(liveKeyboardHeight);
599 }
600 }, [lastKnownKeyboardHeight, liveKeyboardHeight]);
601 const pendingUserInputMaxHeight = derivePendingUserInputMaxHeight({
602 windowHeight,
603 keyboardHeight:
604 lastKnownKeyboardHeight > 0 ? lastKnownKeyboardHeight : ESTIMATED_KEYBOARD_HEIGHT,
605 navigationHeaderHeight,
606 // The questionnaire owns the composer slot, so only the composer's
607 // bottom inset still overlaps.
608 composerOverlapHeight: composerBottomInset,
609 });
610 const estimatedOverlayHeight = composerOverlapHeight;
611 // The overlay's measured height includes the home-indicator inset (the
612 // composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
613 // UIKit add the safe-area bottom to the content inset AGAIN — leaving a
614 // dead strip between the resting content and the composer. Report the
615 // overlay height minus the safe area; UIKit adds it back, and ThreadFeed
616 // hands LegendList the same delta via contentInsetEndStaticAdjustment so
617 // its end-scroll math matches the real resting position.
618 const nativeInsetOvercount =
619 props.usesAutomaticContentInsets === true && Platform.OS === "ios" ? insets.bottom : 0;
620 const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
621 listRef,
622 composerOverlayRef,
623 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
624 -nativeInsetOvercount,
625 Platform.OS === "ios" ? COMPOSER_TRANSITION_DURATION_MS : 0,
626 );
627 // The expanded questionnaire is an absolute overlay on iOS, so it never
628 // changes the measured overlay height (that constancy is what keeps the
629 // feed from snapping on collapse/expand). The toggle choreography runs on
630 // SHARED VALUES set directly in the tap handler — one JS hop, then the
631 // card's rise/sink and the feed's end-inset glide animate in lockstep on
632 // the UI thread, keyboard-style, instead of waiting on React mount +
633 // onLayout + state round trips. Coverage (how far the card extends above
634 // the bar) is measured straight into a shared value by the card's
635 // onLayout, with no re-render.
636 const userInputCardProgress = useSharedValue(1);
637 const userInputInsetProgress = useSharedValue(1);
638 const userInputCardCoverage = useSharedValue(0);
639 const floatingControlCoverage = useSharedValue(
640 showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0,
641 );
642 useEffect(() => {
643 floatingControlCoverage.value = withTiming(
644 showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0,
645 { duration: 180, reduceMotion: ReduceMotion.System },
646 );
647 }, [floatingControlCoverage, showFloatingStatus]);
648 // Android renders the expanded card in-flow (it cannot hit-test the iOS
649 // overlay outside the bar's bounds), so its measured overlay height already
650 // includes the card — the coverage extra is iOS-only.
651 const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null;
652 const combinedContentInsetEndAdjustment = useSharedValue(
653 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
654 );
655 useAnimatedReaction(
656 () =>
657 contentInsetEndAdjustment.value +
658 floatingControlCoverage.value +
659 (userInputCoverageApplies ? userInputInsetProgress.value * userInputCardCoverage.value : 0),
660 (value) => {
661 combinedContentInsetEndAdjustment.value = value;
662 },
663 [userInputCoverageApplies],
664 );
665 // The floating control is anchored to the bar's top edge, so ride it up
666 // with the expanded card instead of drawing it over the questions.
667 const floatingControlLift = useDerivedValue(
668 () =>
669 userInputCoverageApplies ? userInputCardProgress.value * userInputCardCoverage.value : 0,
670 [userInputCoverageApplies],
671 );
672 const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
673 const endFollowEnabledRef = useRef(true);
674 endFollowEnabledRef.current = endFollowEnabled;
675 const overlayRepinTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
676 const previousWorkingControlStateRef = useRef({
677 threadKey: selectedThreadKey,
678 visible: false,
679 });
680 // The list's own corrections for these inset changes drift on short
681 // content (and the error compounds across toggles), so deterministically
682 // re-pin the end once a toggle settles: a no-op when the resting position
683 // is already right, corrective when it is not. Follow state is re-checked
684 // inside the callback — the user may grab the list during the settle
685 // window, and yanking them back would override a live gesture.
686 const scheduleOverlayRepin = useCallback(
687 (delayMs: number) => {
688 if (overlayRepinTimerRef.current !== null) {
689 clearTimeout(overlayRepinTimerRef.current);
690 }
691 overlayRepinTimerRef.current = setTimeout(() => {
692 overlayRepinTimerRef.current = null;
693 if (!endFollowEnabledRef.current) {
694 return;
695 }
696 void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
697 freeze.set(false);
698 });
699 }, delayMs);
700 },
701 [freeze, scrollMessageToEnd],
702 );
703 useEffect(
704 () => () => {
705 if (overlayRepinTimerRef.current !== null) {
706 clearTimeout(overlayRepinTimerRef.current);
707 }
708 },
709 [],
710 );
711 useEffect(() => {
712 const previous = previousWorkingControlStateRef.current;
713 const threadChanged = previous.threadKey !== selectedThreadKey;
714 const visibilityChanged = previous.visible !== showFloatingStatus;
715 previousWorkingControlStateRef.current = {
716 threadKey: selectedThreadKey,
717 visible: showFloatingStatus,
718 };
719 if ((!threadChanged && !visibilityChanged) || (threadChanged && !showFloatingStatus)) {
720 return;
721 }
722 // LegendList applies the larger inset but does not re-anchor short
723 // followed conversations when this floating coverage changes after the
724 // initial load. Re-pin after the finite inset transition; the callback
725 // checks follow state again so a user who scrolled up stays put.
726 scheduleOverlayRepin(230);
727 }, [scheduleOverlayRepin, selectedThreadKey, showFloatingStatus]);
728 const handleToggleUserInputCollapsed = useCallback(() => {
729 if (activeUserInputRequestId === null) {
730 return;
731 }
732 if (userInputCollapsed) {
733 // Expanding: card and feed glide start NOW, on the UI thread.
734 userInputCardProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
735 userInputInsetProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
736 setCollapsedUserInputRequestId(null);
737 scheduleOverlayRepin(USER_INPUT_TOGGLE_DURATION_MS + 50);
738 } else {
739 // Collapsing hides the custom-answer inputs; release the keyboard with
740 // them instead of leaving it up over a dead responder.
741 Keyboard.dismiss();
742 userInputCardProgress.value = withTiming(0, USER_INPUT_TOGGLE_TIMING);
743 // Instant: the sinking card still covers the strip being revealed, and
744 // animating the inset downward is what drifted the short-content end
745 // anchor.
746 userInputInsetProgress.value = 0;
747 setCollapsedUserInputRequestId(activeUserInputRequestId);
748 scheduleOverlayRepin(60);
749 }
750 }, [
751 activeUserInputRequestId,
752 scheduleOverlayRepin,
753 userInputCardProgress,
754 userInputCollapsed,
755 userInputInsetProgress,
756 ]);
757 useEffect(() => {
758 // A new request always arrives expanded.
759 userInputCardProgress.value = 1;
760 userInputInsetProgress.value = 1;
761 }, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]);
762 const showContent = props.showContent ?? true;
763 const layoutVariant = props.layoutVariant ?? "compact";
764 const isSplitLayout = layoutVariant === "split";
765 const contentMaxWidth = isSplitLayout ? CHAT_CONTENT_MAX_WIDTH : undefined;
766 const providerSubagentProvider = props.serverConfig?.providers.find(
767 (provider) => provider.instanceId === props.selectedThread.modelSelection.instanceId,
768 );
769 // Providers can report a dated id or alias (claude-haiku-4-5-20251001).
770 const providerSubagentModelSlug = providerSubagentProvider
771 ? resolveSelectableModel(
772 providerSubagentProvider.driver,
773 props.selectedThread.modelSelection.model,
774 providerSubagentProvider.models,
775 )
776 : null;
777 const providerSubagentCatalogModel = providerSubagentProvider?.models.find(
778 (model) => model.slug === providerSubagentModelSlug,
779 );
780 const workspaceContentWidth = useWorkspaceContentWidth();
781 // Clearing animated width can retain the unfolded width after Android resumes folded.
782 // Assign both layouts explicitly so the dock always follows its current parent.
783 const composerWidthStyle = useAnimatedStyle(() =>
784 isSplitLayout && workspaceContentWidth !== null
785 ? { width: workspaceContentWidth.value }
786 : { width: "100%" },
787 );
788 const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
789 useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
790 const selectedProviderSkills = useMemo(() => {
791 const provider = props.serverConfig?.providers.find(
792 (candidate) => candidate.instanceId === selectedInstanceId,
793 );
794 return provider
795 ? resolveProviderSkillsForCwd(provider, props.threadCwd ?? props.projectWorkspaceRoot)
796 : [];
797 }, [props.projectWorkspaceRoot, props.serverConfig, props.threadCwd, selectedInstanceId]);
798
799 useLayoutEffect(() => {
800 selectedThreadKeyRef.current = selectedThreadKey;
801 // A replaced or unmounted native editor may not emit a blur event.
802 setComposerFocused(false);
803 }, [selectedThreadKey, showContent]);
804
805 const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
806 const lastDispatchedVisitRef = useRef<string | null>(null);
807 const lastVisitDispatchRef = useRef({ threadKey: selectedThreadKey, at: 0 });
808 const selectedThreadId = props.selectedThread.id;
809 const selectedThreadUpdatedAt = props.selectedThread.updatedAt;
810 const selectedThreadLastVisitedAt = props.selectedThread.lastVisitedAt;
811 const selectedThreadCompletedAt = props.selectedThread.latestRun?.completedAt;
812 useEffect(() => {
813 // Records the server-side visited watermark while the thread is on
814 // screen (mirror of web ChatView), so the "Done" marker clears on every
815 // device. Field absent → the server predates visited tracking.
816 if (!showContent || selectedThreadLastVisitedAt === undefined) return;
817 const threadUpdatedAtMs = Date.parse(selectedThreadUpdatedAt);
818 if (Number.isNaN(threadUpdatedAtMs)) return;
819 const lastVisitedAtMs = selectedThreadLastVisitedAt
820 ? Date.parse(selectedThreadLastVisitedAt)
821 : NaN;
822 if (!Number.isNaN(lastVisitedAtMs) && lastVisitedAtMs >= threadUpdatedAtMs) return;
823 // Dedupe per watermark — the effect re-runs before the command echo lands.
824 const dispatchKey = `${selectedThreadKey}:${selectedThreadUpdatedAt}`;
825 if (lastDispatchedVisitRef.current === dispatchKey) return;
826 const dispatch = () => {
827 lastDispatchedVisitRef.current = dispatchKey;
828 lastVisitDispatchRef.current = { threadKey: selectedThreadKey, at: Date.now() };
829 void visitThread({
830 environmentId: props.environmentId,
831 input: { threadId: selectedThreadId, visitedAt: selectedThreadUpdatedAt },
832 });
833 };
834 // Completion clears unread state immediately; streaming watermarks use the
835 // same ten-second trailing throttle as web, keeping the newest update.
836 const completedAtMs = selectedThreadCompletedAt ? Date.parse(selectedThreadCompletedAt) : NaN;
837 const hasUnseenCompletion =
838 !Number.isNaN(completedAtMs) &&
839 (Number.isNaN(lastVisitedAtMs) || completedAtMs > lastVisitedAtMs);
840 const previous = lastVisitDispatchRef.current;
841 const elapsed = Date.now() - previous.at;
842 if (previous.threadKey !== selectedThreadKey || hasUnseenCompletion || elapsed >= 10_000) {
843 dispatch();
844 return;
845 }
846 const timer = setTimeout(dispatch, 10_000 - elapsed);
847 return () => clearTimeout(timer);
848 }, [
849 props.environmentId,
850 selectedThreadId,
851 selectedThreadKey,
852 selectedThreadLastVisitedAt,
853 selectedThreadCompletedAt,
854 selectedThreadUpdatedAt,
855 showContent,
856 visitThread,
857 ]);
858
859 useEffect(() => {
860 setAnchorMessageId(null);
861 setSubmittedMessageId(null);
862 lastScrolledSubmittedMessageIdRef.current = null;
863 setEndFollowEnabled(true);
864 freeze.set(false);
865 }, [freeze, selectedThreadKey]);
866
867 useEffect(() => {
868 if (
869 submittedMessageId === null ||
870 anchorMessageId !== submittedMessageId ||
871 lastScrolledSubmittedMessageIdRef.current === submittedMessageId ||
872 contentPresentationKind !== "ready" ||
873 (!selectedThreadFeed.some(
874 (entry) => entry.type === "message" && entry.id === submittedMessageId,
875 ) &&
876 !props.queuedMessages.some((message) => message.messageId === submittedMessageId))
877 ) {
878 return;
879 }
880
881 const targetThreadKey = selectedThreadKey;
882 const frame = requestAnimationFrame(() => {
883 if (selectedThreadKeyRef.current !== targetThreadKey) {
884 return;
885 }
886 lastScrolledSubmittedMessageIdRef.current = submittedMessageId;
887 // Wait for the keyboard dismissal (started by blur() on send) to finish
888 // before scrolling: scrollMessageToEnd freezes keyboard-driven inset
889 // updates while it runs, and a close event swallowed by that freeze
890 // leaves the keyboard padding permanently applied — overshooting the
891 // anchor and leaving a phantom bottom inset once the reply streams in.
892 void KeyboardController.dismiss()
893 .then(() => {
894 if (
895 selectedThreadKeyRef.current !== targetThreadKey ||
896 lastScrolledSubmittedMessageIdRef.current !== submittedMessageId
897 ) {
898 return;
899 }
900 return scrollMessageToEnd({ animated: true, closeKeyboard: false });
901 })
902 .catch(() => {
903 if (
904 selectedThreadKeyRef.current !== targetThreadKey ||
905 lastScrolledSubmittedMessageIdRef.current !== submittedMessageId
906 ) {
907 return;
908 }
909 lastScrolledSubmittedMessageIdRef.current = null;
910 freeze.set(false);
911 });
912 });
913 return () => cancelAnimationFrame(frame);
914 }, [
915 anchorMessageId,
916 submittedMessageId,
917 freeze,
918 contentPresentationKind,
919 props.queuedMessages,
920 selectedThreadFeed,
921 scrollMessageToEnd,
922 selectedThreadKey,
923 ]);
924
925 const handleSendMessage = useCallback(
926 async (followUp?: ActiveTurnComposerAction) => {
927 const targetThreadKey = selectedThreadKey;
928 const hasUserMessage = selectedThreadFeed.some(
929 (entry) => entry.type === "message" && entry.message.role === "user",
930 );
931 const messageId = await props.onSendMessage(followUp);
932 if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
933 return messageId;
934 }
935
936 // A sent message makes the snapshot stale; a refused send leaves it in place.
937 clearUsageLimitsFor(targetThreadKey);
938
939 setSubmittedMessageId(messageId);
940 setAnchorMessageId(
941 resolveThreadFeedSubmissionAnchor({
942 currentAnchorMessageId: anchorMessageId,
943 submittedMessageId: messageId,
944 hasStartedTurn: props.selectedThread.latestRun !== null,
945 hasUserMessage,
946 queuedMessageCount: props.selectedThreadQueueCount,
947 }),
948 );
949 composerEditorRef.current?.blur();
950 return messageId;
951 },
952 [
953 anchorMessageId,
954 clearUsageLimitsFor,
955 props.onSendMessage,
956 props.selectedThread.latestRun,
957 props.selectedThreadQueueCount,
958 selectedThreadFeed,
959 selectedThreadKey,
960 ],
961 );
962
963 const handleEditPendingMessage = useCallback(async (message: QueuedThreadMessage) => {
964 try {
965 if (
966 (await editPendingThreadMessage(message)) &&
967 selectedThreadKeyRef.current === scopedThreadKey(message.environmentId, message.threadId)
968 ) {
969 composerEditorRef.current?.focus();
970 }
971 } catch (error) {
972 Alert.alert(
973 "Could not edit message",
974 error instanceof Error ? error.message : "Please try again.",
975 );
976 }
977 }, []);
978
979 const collapseComposer = useCallback(() => {
980 composerEditorRef.current?.blur();
981 }, []);
982
983 const handleUseArtifactTemplate = useCallback(
984 (template: CodexArtifactTemplate) => {
985 const currentDraft = draftMessageRef.current;
986 const nextDraft = appendCodexArtifactTemplateUsePrompt(currentDraft, template);
987 if (nextDraft !== currentDraft) {
988 draftMessageRef.current = nextDraft;
989 props.onChangeDraftMessage(nextDraft);
990 }
991 requestAnimationFrame(() => {
992 composerEditorRef.current?.focus();
993 composerEditorRef.current?.setSelection({ start: nextDraft.length, end: nextDraft.length });
994 });
995 },
996 [props.onChangeDraftMessage],
997 );
998
999 const handleScrollToEnd = useCallback(() => {
1000 void Haptics.selectionAsync();
1001 void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
1002 freeze.set(false);
1003 });
1004 }, [freeze, scrollMessageToEnd]);
1005
1006 const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled;
1007 const { themeAppearance } = useAppearancePreferences();
1008 const isDarkMode = themeAppearance === "dark";
1009
1010 const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
1011 feedTouchStartRef.current = {
1012 pageX: event.nativeEvent.pageX,
1013 pageY: event.nativeEvent.pageY,
1014 };
1015 }, []);
1016
1017 const handleFeedTouchMove = useCallback((event: GestureResponderEvent) => {
1018 const start = feedTouchStartRef.current;
1019 if (!start) {
1020 return;
1021 }
1022 const deltaX = event.nativeEvent.pageX - start.pageX;
1023 const deltaY = event.nativeEvent.pageY - start.pageY;
1024 if (Math.hypot(deltaX, deltaY) > 8) {
1025 feedTouchStartRef.current = null;
1026 }
1027 }, []);
1028
1029 const handleFeedTouchEnd = useCallback(() => {
1030 if (feedTouchStartRef.current) {
1031 collapseComposer();
1032 }
1033 feedTouchStartRef.current = null;
1034 }, [collapseComposer]);
1035
1036 const handleFeedTouchCancel = useCallback(() => {
1037 feedTouchStartRef.current = null;
1038 }, []);
1039
1040 return (
1041 <View className="flex-1">
1042 {showContent ? (
1043 <View
1044 style={{ flex: 1 }}
1045 onTouchStart={handleFeedTouchStart}
1046 onTouchMove={handleFeedTouchMove}
1047 onTouchEnd={handleFeedTouchEnd}
1048 onTouchCancel={handleFeedTouchCancel}
1049 >
1050 <View
1051 pointerEvents="none"
1052 className={
1053 Platform.OS === "android"
1054 ? "absolute inset-0 bg-thread-canvas"
1055 : "absolute inset-0 bg-screen"
1056 }
1057 />
1058 <RenderErrorBoundary
1059 key={selectedThreadKey}
1060 resetKeys={[props.threadCwd]}
1061 renderFallback={(fallback) => (
1062 <RenderFailureView
1063 {...fallback}
1064 title="The conversation couldn't be displayed"
1065 bottomInset={estimatedOverlayHeight}
1066 />
1067 )}
1068 >
1069 <ThreadFeed
1070 environmentId={props.environmentId}
1071 threadId={props.selectedThread.id}
1072 workspaceRoot={props.threadCwd}
1073 feed={props.selectedThreadFeed}
1074 worktreeSetup={props.worktreeSetup}
1075 setupWorkingStartedAt={props.setupWorkingStartedAt}
1076 queuedMessages={props.queuedMessages}
1077 dispatchingMessageId={props.dispatchingMessageId}
1078 // A native subagent has no composer to edit a pending message in;
1079 // Cancel on the edit banner would discard it.
1080 onEditPendingMessage={isProviderSubagent ? null : handleEditPendingMessage}
1081 contentPresentation={props.contentPresentation}
1082 agentLabel={agentLabel}
1083 threadTitle={props.selectedThread.title}
1084 latestRun={props.activityRun}
1085 activeWorkStartedAt={props.activeWorkStartedAt}
1086 runlessWorkActive={props.runlessWorkActive ?? false}
1087 listRef={listRef}
1088 freeze={freeze}
1089 anchorMessageId={anchorMessageId}
1090 submittedMessageId={submittedMessageId}
1091 contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
1092 contentTopInset={0}
1093 contentBottomInset={
1094 estimatedOverlayHeight +
1095 (showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0)
1096 }
1097 contentMaxWidth={contentMaxWidth}
1098 historyControls={props.historyControls}
1099 layoutVariant={layoutVariant}
1100 usesAutomaticContentInsets={props.usesAutomaticContentInsets}
1101 onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
1102 onEndFollowEnabledChange={setEndFollowEnabled}
1103 skills={selectedProviderSkills}
1104 onUseArtifactTemplate={handleUseArtifactTemplate}
1105 />
1106 </RenderErrorBoundary>
1107 </View>
1108 ) : (
1109 <View className="flex-1" />
1110 )}
1111
1112 {/* Floating composer — sticks to keyboard via KeyboardStickyView */}
1113 {showContent ? (
1114 <KeyboardStickyView
1115 // iOS emits a native animated height target on both will-show and
1116 // will-hide, so stay subscribed for the full transition. Android
1117 // retains its background/resume stale-state quarantine.
1118 enabled={Platform.OS === "ios" || (isKeyboardVisible && !keyboardStateSuspect)}
1119 pointerEvents="box-none"
1120 style={{ position: "absolute", bottom: 0, left: 0, right: 0, top: 0 }}
1121 offset={{ closed: 0, opened: 0 }}
1122 >
1123 {/* The fixed sticky host gives this bottom-anchored child a stable
1124 coordinate space. Its top and height can then animate together
1125 instead of the auto-sized host jumping to Yoga's destination. */}
1126 <Animated.View
1127 layout={COMPOSER_LAYOUT_TRANSITION}
1128 pointerEvents="box-none"
1129 style={[{ position: "absolute", bottom: 0, left: 0 }, composerWidthStyle]}
1130 >
1131 {/* No paddingTop here: the overlay's measured height becomes the
1132 list's bottom inset, so any padding above the pill/composer
1133 pushes the resting content floor up by the same amount. */}
1134 <View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
1135 <FloatingWorkingControl
1136 colorScheme={isDarkMode ? "dark" : "light"}
1137 status={floatingStatus}
1138 lift={floatingControlLift}
1139 devicePreview={
1140 devicePreviews.length > 0
1141 ? { count: devicePreviews.length, onPress: openDevicePreview }
1142 : null
1143 }
1144 showScrollToEnd={showScrollToEndButton}
1145 onScrollToEnd={handleScrollToEnd}
1146 agents={agentsSegment}
1147 onOpenAgents={() => {
1148 Keyboard.dismiss();
1149 navigation.navigate("ThreadAgents", {
1150 environmentId: props.environmentId,
1151 threadId: props.selectedThread.id,
1152 });
1153 }}
1154 queuedCount={queuedCount}
1155 onOpenQueue={() => {
1156 Keyboard.dismiss();
1157 navigation.navigate("ThreadQueue", {
1158 environmentId: props.environmentId,
1159 threadId: props.selectedThread.id,
1160 });
1161 }}
1162 />
1163 <View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
1164 {props.queuedRunEdit !== null ? (
1165 <Animated.View
1166 className="shrink-0"
1167 entering={FadeInDown.duration(180)}
1168 exiting={FadeOut.duration(120)}
1169 >
1170 <ComposerQueuedEditBanner
1171 saving={props.isSavingQueuedEdit}
1172 onCancel={props.onCancelQueuedRunEdit}
1173 />
1174 </Animated.View>
1175 ) : null}
1176 <UsageLimitRecoveryCard
1177 key={props.selectedThread.latestRun?.runId}
1178 thread={props.selectedThread}
1179 environmentId={props.environmentId}
1180 />
1181 {props.feedbackSubmissions.map((submission) => (
1182 <ComposerFeedback
1183 key={submission.id}
1184 submission={submission}
1185 onDismiss={() => props.onDismissFeedback(submission.id)}
1186 />
1187 ))}
1188 {usageLimitsReport && activeUserInputRequestId === null ? (
1189 <Animated.View
1190 className="shrink-0 px-4 pb-3"
1191 entering={FadeInDown.duration(220)}
1192 exiting={FadeOut.duration(140)}
1193 >
1194 <ComposerUsageLimits
1195 report={usageLimitsReport}
1196 environmentId={props.environmentId}
1197 onClose={dismissUsageLimits}
1198 />
1199 </Animated.View>
1200 ) : null}
1201 {props.creationState?.kind === "failed" ? (
1202 <Animated.View
1203 className="shrink-0 px-4"
1204 style={{ paddingBottom: composerBottomInset }}
1205 entering={FadeInDown.duration(220)}
1206 exiting={FadeOut.duration(140)}
1207 >
1208 <ThreadCreationFailedCard
1209 reason={props.creationState.reason}
1210 onEditTask={props.creationState.onEditTask}
1211 />
1212 </Animated.View>
1213 ) : null}
1214 {props.activePendingApproval || props.activePendingUserInput ? (
1215 <Animated.View
1216 className="shrink-0 gap-3 px-4 pb-3"
1217 // The questionnaire replaces the composer, so it must pad
1218 // the home indicator the composer normally covers.
1219 style={
1220 activeUserInputRequestId !== null
1221 ? { paddingBottom: composerBottomInset }
1222 : undefined
1223 }
1224 entering={FadeInDown.duration(220)}
1225 exiting={FadeOut.duration(140)}
1226 >
1227 {props.activePendingApproval ? (
1228 <PendingApprovalCard
1229 approval={props.activePendingApproval}
1230 respondingApprovalId={props.respondingApprovalId}
1231 onRespond={props.onRespondToApproval}
1232 />
1233 ) : null}
1234 {props.activePendingUserInput ? (
1235 <PendingUserInputCard
1236 pendingUserInput={props.activePendingUserInput}
1237 maxHeight={pendingUserInputMaxHeight}
1238 collapsed={userInputCollapsed}
1239 onToggleCollapsed={handleToggleUserInputCollapsed}
1240 onStopThread={props.onStopThread}
1241 cardProgress={userInputCardProgress}
1242 cardCoverage={userInputCardCoverage}
1243 onInputFocusChange={handleOwnedInputFocusChange}
1244 drafts={props.activePendingUserInputDrafts}
1245 answers={props.activePendingUserInputAnswers}
1246 respondingUserInputId={props.respondingUserInputId}
1247 onSelectOption={props.onSelectUserInputOption}
1248 onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
1249 onSubmit={props.onSubmitUserInput}
1250 onDismiss={props.onDismissUserInput}
1251 />
1252 ) : null}
1253 </Animated.View>
1254 ) : null}
1255 </View>
1256
1257 {/* Hidden (not unmounted) while a user-input request owns the
1258 composer slot, so composer drafts and editor state survive.
1259 A rejected creation has no thread to send to; the failure card
1260 owns the slot instead. */}
1261 <View
1262 style={
1263 activeUserInputRequestId !== null || props.creationState?.kind === "failed"
1264 ? { display: "none" }
1265 : undefined
1266 }
1267 >
1268 {isProviderSubagent ? (
1269 <View
1270 className="self-center px-3 pt-1.5"
1271 style={{
1272 width: "100%",
1273 maxWidth: contentMaxWidth,
1274 paddingBottom: composerBottomInset + 6,
1275 }}
1276 >
1277 <ProviderSubagentBar
1278 provider={providerSubagentProvider ?? null}
1279 modelLabel={
1280 providerSubagentCatalogModel?.name ??
1281 formatModelSlugName(props.selectedThread.modelSelection.model)
1282 }
1283 effortLabel={formatModelSelectionEffort(
1284 props.selectedThread.modelSelection,
1285 providerSubagentProvider?.models,
1286 reportedModelSelection,
1287 )}
1288 status={props.providerSubagentStatus ?? null}
1289 onOpenParent={
1290 props.selectedThread.lineage.parentThreadId === null
1291 ? null
1292 : () =>
1293 navigation.navigate("Thread", {
1294 environmentId: String(props.environmentId),
1295 threadId: String(props.selectedThread.lineage.parentThreadId),
1296 })
1297 }
1298 />
1299 </View>
1300 ) : (
1301 <>
1302 <ThreadComposer
1303 reportedModelSelection={reportedModelSelection}
1304 editorRef={composerEditorRef}
1305 draftMessage={props.draftMessage}
1306 draftAttachments={props.draftAttachments}
1307 placeholder="Ask the repo agent, or run a command…"
1308 contentMaxWidth={contentMaxWidth}
1309 connectionState={props.connectionStateLabel}
1310 environmentLabel={props.environmentLabel}
1311 selectedThread={props.selectedThread}
1312 hasCompactableConversation={hasCompactableConversation && !props.isCompacting}
1313 serverConfig={props.serverConfig}
1314 queueCount={props.selectedThreadQueueCount}
1315 activeThreadBusy={props.activeThreadBusy}
1316 canStopThread={props.canStopThread}
1317 environmentId={props.environmentId}
1318 projectCwd={props.threadCwd ?? props.projectWorkspaceRoot}
1319 // Follow-ups typed during setup wait in the draft: queueing
1320 // them against a thread id the server may still reject
1321 // would strand them in the outbox.
1322 sendBlockedReason={
1323 props.creationState?.kind === "preparing" ? "Starting the task…" : null
1324 }
1325 draftKey={props.composerDraftKey ?? undefined}
1326 followUpBehavior={props.followUpBehavior}
1327 canSteerActiveTurn={props.canSteerActiveTurn}
1328 queuedEdit={
1329 props.queuedRunEdit === null
1330 ? null
1331 : {
1332 existingAttachments: props.queuedRunEdit.existingAttachments,
1333 saving: props.isSavingQueuedEdit,
1334 onRemoveExistingAttachment: props.onRemoveQueuedEditAttachment,
1335 }
1336 }
1337 bottomInset={composerBottomInset}
1338 onChangeDraftMessage={props.onChangeDraftMessage}
1339 onPickDraftMedia={props.onPickDraftMedia}
1340 onPickDraftFiles={props.onPickDraftFiles}
1341 onNativePasteImages={props.onNativePasteImages}
1342 onNativePasteText={props.onNativePasteText}
1343 onRemoveDraftImage={props.onRemoveDraftImage}
1344 onStopThread={props.onStopThread}
1345 onSendMessage={handleSendMessage}
1346 onShowUsageLimits={showUsageLimits}
1347 canSwitchProvider={props.canSwitchThreadProvider}
1348 onUpdateModelSelection={props.onUpdateThreadModelSelection}
1349 onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
1350 onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
1351 onExpandedChange={setComposerExpanded}
1352 onEditorFocusChange={handleComposerFocusChange}
1353 />
1354 </>
1355 )}
1356 </View>
1357 </View>
1358 </Animated.View>
1359 </KeyboardStickyView>
1360 ) : null}
1361 </View>
1362 );
1363});