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