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

ThreadDetailScreen.tsx

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