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