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

ThreadDetailScreen.tsx

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