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