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