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