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

ThreadDetailScreen.tsx

1,365 lines57.6 KB

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