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

ThreadDetailScreen.tsx

1,347 lines57.6 KB

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