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

ThreadDetailScreen.tsx

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