Open History to see the last commit
1import type { WorktreeSetupCardProps } from "./worktree-setup-card";
2import type { ComposerTextPaste } from "../../native/T3ComposerEditor.types";
3import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
4import {
5 appendCodexArtifactTemplateUsePrompt,
6 type CodexArtifactTemplate,
7} from "@t3tools/client-runtime/codex-artifact-templates";
8import type {
9 CodexFeedbackSubmission,
10 EnvironmentThreadStatus,
11} from "@t3tools/client-runtime/state/threads";
12import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
13import { resolveProviderSkillsForCwd } from "@t3tools/client-runtime/providerSkills";
14import type { LegendListRef } from "@legendapp/list/react-native";
15import { HeaderHeightContext } from "@react-navigation/elements";
16import { useNavigation } from "@react-navigation/native";
17import type {
18 ApprovalRequestId,
19 EnvironmentId,
20 MessageId,
21 ModelSelection,
22 OrchestrationThreadShell,
23 ProviderApprovalDecision,
24 ProviderInteractionMode,
25 RuntimeMode,
26 ServerConfig as T3ServerConfig,
27 ThreadId,
28 UsageLimitsReport,
29 UserInputQuestion,
30} from "@t3tools/contracts";
31import * as Haptics from "expo-haptics";
32import {
33 memo,
34 useCallback,
35 useContext,
36 useEffect,
37 useLayoutEffect,
38 useMemo,
39 useRef,
40 useState,
41} from "react";
42import {
43 Alert,
44 AppState,
45 Keyboard,
46 Platform,
47 useWindowDimensions,
48 View,
49 type GestureResponderEvent,
50} from "react-native";
51import {
52 KeyboardController,
53 KeyboardStickyView,
54 useKeyboardState,
55} from "react-native-keyboard-controller";
56import Animated, {
57 Easing,
58 FadeInDown,
59 FadeOut,
60 ReduceMotion,
61 useAnimatedReaction,
62 useAnimatedStyle,
63 useSharedValue,
64 withTiming,
65} from "react-native-reanimated";
66import { useSafeAreaInsets } from "react-native-safe-area-context";
67import { useWorkspaceContentWidth } from "../layout/workspace-content-width";
68import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
69import { collectProviderUsageLimits } from "@t3tools/shared/usageLimits";
70import type { ComposerEditorHandle } from "../../components/ComposerEditor";
71import type { StatusTone } from "../../components/StatusPill";
72import type { DraftComposerAttachment } from "../../lib/composerImages";
73import { RenderErrorBoundary, RenderFailureView } from "../../components/RenderErrorBoundary";
74import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
75import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
76import { editPendingThreadMessage } from "../../state/edit-pending-thread-message";
77import { deviceEnvironment } from "../../state/device";
78import { useEnvironmentQuery } from "../../state/query";
79import { threadDevicePreviews } from "../devices/threadDevicePreviews";
80import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
81import { scopedThreadKey } from "../../lib/scopedEntities";
82import { useDelayedStatus } from "../../lib/useDelayedStatus";
83import type {
84 PendingApproval,
85 PendingUserInput,
86 PendingUserInputDraftAnswer,
87 ThreadFeedEntry,
88} from "../../lib/threadActivity";
89import { PendingApprovalCard } from "./PendingApprovalCard";
90import { ComposerFeedback } from "./ComposerFeedback";
91import { ComposerUsageLimits } from "./ComposerUsageLimits";
92import { PendingUserInputCard } from "./PendingUserInputCard";
93import { ThreadCreationFailedCard } from "./ThreadCreationFailedCard";
94import {
95 FLOATING_WORKING_CONTROL_COVERAGE,
96 FloatingWorkingControl,
97} from "./floating-working-control";
98import { connectionFloatingStatus, type FloatingWorkingStatus } from "./floating-working-status";
99import {
100 derivePendingUserInputMaxHeight,
101 ESTIMATED_KEYBOARD_HEIGHT,
102 USER_INPUT_TOGGLE_DURATION_MS,
103} from "./pendingUserInputLayout";
104import {
105 COMPOSER_COLLAPSED_CHROME,
106 COMPOSER_EXPANDED_CHROME,
107 COMPOSER_LAYOUT_TRANSITION,
108 COMPOSER_TRANSITION_DURATION_MS,
109 ThreadComposer,
110} from "./ThreadComposer";
111import { ThreadFeed } from "./ThreadFeed";
112import type { ThreadContentPresentation } from "./threadContentPresentation";
113import { resolveThreadFeedSubmissionAnchor } from "./thread-feed-live-follow";
114
115export interface ThreadDetailScreenProps {
116 readonly worktreeSetup?: WorktreeSetupCardProps | null;
117 readonly setupWorkingStartedAt?: string | null;
118 readonly selectedThread: OrchestrationThreadShell;
119 readonly contentPresentation: ThreadContentPresentation;
120 readonly screenTone: StatusTone;
121 readonly connectionError: string | null;
122 readonly environmentLabel: string | null;
123 readonly feedbackSubmissions: ReadonlyArray<CodexFeedbackSubmission>;
124 readonly onDismissFeedback: (id: MessageId) => void;
125 readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
126 readonly activeWorkStartedAt: string | null;
127 readonly isCompacting: boolean;
128 /**
129 * The server has not created this thread yet. "preparing" runs while the
130 * queued creation is delivered (a worktree may be checking out); "failed"
131 * is a rejected creation whose content went back to the project draft.
132 */
133 readonly creationState:
134 | { readonly kind: "preparing"; readonly preparingWorktree: boolean }
135 | { readonly kind: "failed"; readonly reason: string; readonly onEditTask: () => void }
136 | null;
137 readonly activePendingApproval: PendingApproval | null;
138 readonly respondingApprovalId: ApprovalRequestId | null;
139 readonly activePendingUserInput: PendingUserInput | null;
140 readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
141 readonly activePendingUserInputAnswers: Record<string, string | ReadonlyArray<string>> | null;
142 readonly respondingUserInputId: ApprovalRequestId | null;
143 readonly draftMessage: string;
144 readonly draftAttachments: ReadonlyArray<DraftComposerAttachment>;
145 readonly connectionStateLabel: EnvironmentConnectionPhase;
146 /** Message sync status for the selected thread (drives the composer status pill). */
147 readonly threadSyncStatus?: EnvironmentThreadStatus;
148 /** Non-null when older turns exist beyond the loaded window. */
149 readonly loadEarlier?: { readonly loading: boolean; readonly onLoadEarlier: () => void } | null;
150 readonly environmentId: EnvironmentId;
151 readonly projectWorkspaceRoot: string | null;
152 readonly threadCwd: string | null;
153 readonly selectedThreadQueueCount: number;
154 readonly queuedMessages: ReadonlyArray<QueuedThreadMessage>;
155 readonly dispatchingMessageId: MessageId | null;
156 readonly serverConfig: T3ServerConfig | null;
157 readonly layoutVariant?: LayoutVariant;
158 readonly usesAutomaticContentInsets?: boolean;
159 readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
160 readonly onOpenConnectionEditor: () => void;
161 readonly onChangeDraftMessage: (value: string) => void;
162 readonly onPickDraftMedia: () => Promise<void>;
163 readonly onPickDraftFiles: () => Promise<void>;
164 readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
165 readonly onNativePasteText: (paste: ComposerTextPaste) => Promise<void>;
166 readonly onRemoveDraftImage: (imageId: string) => void;
167 readonly onStopThread: () => void;
168 readonly onSendMessage: () => Promise<MessageId | null>;
169 readonly onReconnectEnvironment: () => void;
170 readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
171 readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
172 readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
173 readonly onRespondToApproval: (
174 requestId: ApprovalRequestId,
175 decision: ProviderApprovalDecision,
176 ) => Promise<unknown>;
177 readonly onSelectUserInputOption: (
178 requestId: ApprovalRequestId,
179 question: UserInputQuestion,
180 value: string,
181 ) => void;
182 readonly onChangeUserInputCustomAnswer: (
183 requestId: ApprovalRequestId,
184 questionId: string,
185 customAnswer: string,
186 ) => void;
187 readonly onSubmitUserInput: () => Promise<unknown>;
188 readonly onDismissUserInput: () => Promise<unknown>;
189 readonly showContent?: boolean;
190}
191
192function latestStreamingAssistantMessage(
193 feed: ReadonlyArray<ThreadFeedEntry>,
194): { readonly id: string; readonly textLength: number } | null {
195 for (let index = feed.length - 1; index >= 0; index -= 1) {
196 const entry = feed[index];
197 if (entry?.type !== "message") {
198 continue;
199 }
200 if (entry.message.role !== "assistant" || !entry.message.streaming) {
201 continue;
202 }
203 return {
204 id: entry.message.id,
205 textLength: entry.message.text.length,
206 };
207 }
208
209 return null;
210}
211
212function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedEntry>) {
213 const lastStreamingAssistantRef = useRef<{
214 readonly id: string;
215 readonly textLength: number;
216 } | null>(null);
217 const lastStreamHapticAtRef = useRef(0);
218 const hydratedRef = useRef(false);
219 const previousThreadIdRef = useRef(threadId);
220
221 useEffect(() => {
222 if (previousThreadIdRef.current !== threadId) {
223 previousThreadIdRef.current = threadId;
224 hydratedRef.current = false;
225 }
226
227 const latestStreamingMessage = latestStreamingAssistantMessage(feed);
228
229 if (!hydratedRef.current) {
230 hydratedRef.current = true;
231 lastStreamingAssistantRef.current = latestStreamingMessage;
232 return;
233 }
234
235 if (!latestStreamingMessage) {
236 lastStreamingAssistantRef.current = null;
237 return;
238 }
239
240 const previousStreamingMessage = lastStreamingAssistantRef.current;
241 lastStreamingAssistantRef.current = latestStreamingMessage;
242
243 const isNewStream = previousStreamingMessage?.id !== latestStreamingMessage.id;
244 const textGrew =
245 previousStreamingMessage?.id === latestStreamingMessage.id &&
246 latestStreamingMessage.textLength > previousStreamingMessage.textLength;
247
248 if (!isNewStream && !textGrew) {
249 return;
250 }
251
252 const now = Date.now();
253 if (!isNewStream && now - lastStreamHapticAtRef.current < 320) {
254 return;
255 }
256
257 lastStreamHapticAtRef.current = now;
258 void Haptics.selectionAsync();
259 }, [threadId, feed]);
260}
261
262const USER_INPUT_TOGGLE_TIMING = {
263 duration: USER_INPUT_TOGGLE_DURATION_MS,
264 easing: Easing.out(Easing.cubic),
265};
266
267export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
268 const navigation = useNavigation();
269 const deviceState = useEnvironmentQuery(
270 deviceEnvironment.state({ environmentId: props.environmentId, input: {} }),
271 );
272 const devicePreviews = useMemo(
273 () => threadDevicePreviews(deviceState.data, props.selectedThread.id),
274 [deviceState.data, props.selectedThread.id],
275 );
276 const openDevicePreview = useCallback(() => {
277 Keyboard.dismiss();
278 navigation.navigate("ThreadDevicePreview", {
279 environmentId: props.environmentId,
280 threadId: props.selectedThread.id,
281 });
282 }, [navigation, props.environmentId, props.selectedThread.id]);
283 const insets = useSafeAreaInsets();
284 const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
285 const liveKeyboardHeight = useKeyboardState((state) => state.height);
286 // Android can swallow the IME hide callbacks when the app is backgrounded
287 // mid keyboard-hide (the reported repro: send — which blurs and starts the
288 // hide — then Home within a second). The keyboard library's height AND
289 // visibility then stay frozen open, so gating the sticky translation on
290 // visibility alone still strands the composer after resume. Quarantine the
291 // translation on every Android resume instead; any sign of a live keyboard
292 // stream — an owned input gaining focus, or any visibility/height movement —
293 // lifts it. A healthy resume sees no visual difference (the translation is
294 // already zero while the keyboard is closed).
295 const [keyboardStateSuspect, setKeyboardStateSuspect] = useState(false);
296 useEffect(() => {
297 if (Platform.OS !== "android") {
298 return;
299 }
300 const subscription = AppState.addEventListener("change", (state) => {
301 if (state === "active") {
302 setKeyboardStateSuspect(true);
303 }
304 });
305 return () => {
306 subscription.remove();
307 };
308 }, []);
309 useEffect(() => {
310 setKeyboardStateSuspect(false);
311 }, [isKeyboardVisible, liveKeyboardHeight]);
312 const handleOwnedInputFocusChange = useCallback((focused: boolean) => {
313 if (focused) {
314 setKeyboardStateSuspect(false);
315 }
316 }, []);
317 const windowHeight = useWindowDimensions().height;
318 const navigationHeaderHeight = useContext(HeaderHeightContext) || insets.top + IOS_NAV_BAR_HEIGHT;
319 const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
320 const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
321 const composerEditorRef = useRef<ComposerEditorHandle>(null);
322 const draftMessageRef = useRef(props.draftMessage);
323 draftMessageRef.current = props.draftMessage;
324 const composerOverlayRef = useRef<View>(null);
325 const listRef = useRef<LegendListRef>(null);
326 const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
327 const selectedThreadKeyRef = useRef(selectedThreadKey);
328 const lastScrolledSubmittedMessageIdRef = useRef<MessageId | null>(null);
329 const [composerExpanded, setComposerExpanded] = useState(false);
330 const [composerFocused, setComposerFocused] = useState(false);
331 const handleComposerFocusChange = useCallback(
332 (focused: boolean) => {
333 setComposerFocused(focused);
334 handleOwnedInputFocusChange(focused);
335 },
336 [handleOwnedInputFocusChange],
337 );
338 const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
339 const [submittedMessageId, setSubmittedMessageId] = useState<MessageId | null>(null);
340 const [endFollowEnabled, setEndFollowEnabled] = useState(true);
341 // Android keys the safe-area padding on keyboard visibility (#5988): the
342 // back gesture closes the keyboard while the editor stays focused, and a
343 // focus-keyed inset would leave the toolbar under the gesture bar. iOS must
344 // NOT use visibility — it only flips on keyboardDidHide, after the hide
345 // animation, so the composer would ride down flush to the screen edge and
346 // then snap up into the inset. On iOS blur precedes the hide, so the
347 // focus-keyed inset is already in place while the composer rides down.
348 // Dictation keeps that focus while the composer switches to its compact pill.
349 const composerBottomInset = (
350 Platform.OS === "android" ? isKeyboardVisible : composerExpanded || composerFocused
351 )
352 ? 0
353 : Math.max(insets.bottom, 12);
354 const contentPresentationKind = props.contentPresentation.kind;
355 // The raw sync status enters "synchronizing" on every full fetch, cached or
356 // not. Whether messages are already on screen decides the pill label: no
357 // data yet → "Loading messages", cached data reconciling → "Syncing".
358 const realThreadSyncLabel = (() => {
359 switch (props.threadSyncStatus) {
360 case "empty":
361 case "cached":
362 case "synchronizing":
363 if (contentPresentationKind === "ready") {
364 return "Syncing messages...";
365 }
366 return contentPresentationKind === "loading" ? "Loading messages..." : null;
367 default:
368 return null;
369 }
370 })();
371 // Opening a running thread resyncs for a few frames. The pill shows the
372 // sync label only when the sync lasts, so it does not flash before the timer.
373 const threadSyncLabel = useDelayedStatus(selectedThreadKey, realThreadSyncLabel);
374 // One floating pill above the composer: it reads the connection phase while
375 // disconnected, the sync state while messages load, then the working timer
376 // once the feed is settled.
377 const floatingStatus = ((): FloatingWorkingStatus | null => {
378 const connectionStatus = connectionFloatingStatus({
379 connectionError: props.connectionError,
380 connectionState: props.connectionStateLabel,
381 environmentLabel: props.environmentLabel,
382 onReconnect: props.onReconnectEnvironment,
383 });
384 if (connectionStatus !== null) {
385 return connectionStatus;
386 }
387 if (props.activePendingApproval !== null || props.activePendingUserInput !== null) {
388 return null;
389 }
390 if (props.creationState?.kind === "preparing") {
391 // The setup header already reports progress in the feed.
392 if (props.worktreeSetup) return null;
393 return {
394 kind: "preparing",
395 label: props.creationState.preparingWorktree ? "Setting up worktree…" : "Starting…",
396 };
397 }
398 if (props.creationState?.kind === "failed") {
399 return null;
400 }
401 if (threadSyncLabel !== null) {
402 return { kind: "syncing", label: threadSyncLabel };
403 }
404 if (props.isCompacting && contentPresentationKind === "ready") {
405 return { kind: "compacting" };
406 }
407 if (props.activeWorkStartedAt !== null && contentPresentationKind === "ready") {
408 return { kind: "working", startedAt: props.activeWorkStartedAt };
409 }
410 return null;
411 })();
412 const showWorkingControl = floatingStatus !== null;
413 // Connection and working status occupy the same space. Keep the feed inset
414 // stable when reconnecting hands off to syncing and then to a running turn.
415 const showFloatingStatus =
416 showWorkingControl ||
417 devicePreviews.length > 0 ||
418 props.connectionStateLabel !== "connected" ||
419 props.queuedMessages.length > 0 ||
420 props.selectedThreadFeed.some(
421 (entry) => "acknowledged" in entry && entry.acknowledged === true,
422 );
423 const selectedThreadFeed = props.selectedThreadFeed;
424 const hasCompactableConversation =
425 selectedThreadFeed.some(
426 (entry) =>
427 entry.type === "message" &&
428 entry.message.role === "user" &&
429 ((entry.message.attachments?.length ?? 0) > 0 ||
430 entry.message.text.trim().toLowerCase() !== "/compact"),
431 ) ||
432 (Boolean(props.loadEarlier) && props.selectedThread.latestUserMessageAt !== null);
433 const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
434 const composerOverlapHeight = composerChrome + composerBottomInset;
435 // While a user-input request is pending, the questionnaire owns the
436 // composer slot outright: expanded it is the full card, collapsed it is a
437 // composer-style bar in the same place (with its own stop control). The
438 // composer never mounts into the transition, which keeps the collapse and
439 // keyboard animations coherent. Collapse state is keyed by request id so a
440 // new request re-expands automatically.
441 const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
442 useState<ApprovalRequestId | null>(null);
443 const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
444 // The open /usage-limits panel for this thread, model and turn. Only the open
445 // moment is stored: the rows read live provider data, so a redeemed reset
446 // credit or refreshed probe shows through. Anything that spends quota closes
447 // it: a new turn from any source, or the agent resuming after an approval or
448 // answered question.
449 const [usageLimitsPanel, setUsageLimitsPanel] = useState<{
450 readonly key: string;
451 readonly threadKey: string;
452 readonly now: number;
453 } | null>(null);
454 // A pending approval or question is part of the key: once it is answered,
455 // from this client or any other, the agent resumes and spends quota.
456 const usageLimitsKey = [
457 selectedThreadKey,
458 props.selectedThread.modelSelection.instanceId,
459 props.selectedThread.latestTurn?.turnId ?? "",
460 props.activePendingApproval?.requestId ?? props.activePendingUserInput?.requestId ?? "",
461 ].join(":");
462 // Drop the snapshot as soon as the key changes so it cannot resurface stale.
463 if (usageLimitsPanel !== null && usageLimitsPanel.key !== usageLimitsKey) {
464 setUsageLimitsPanel(null);
465 }
466 const usageLimitsReport = useMemo(
467 () =>
468 usageLimitsPanel !== null && usageLimitsPanel.key === usageLimitsKey
469 ? collectProviderUsageLimits(
470 props.selectedThread.modelSelection.instanceId,
471 props.serverConfig?.providers ?? [],
472 props.serverConfig?.usageLimitSources ?? [],
473 usageLimitsPanel.now,
474 )
475 : null,
476 [
477 props.selectedThread.modelSelection.instanceId,
478 props.serverConfig,
479 usageLimitsKey,
480 usageLimitsPanel,
481 ],
482 );
483 const showUsageLimits = useCallback(
484 (report: UsageLimitsReport | null) =>
485 setUsageLimitsPanel(
486 report === null
487 ? null
488 : {
489 key: usageLimitsKey,
490 threadKey: selectedThreadKey,
491 now: Date.parse(report.createdAt),
492 },
493 ),
494 [selectedThreadKey, usageLimitsKey],
495 );
496 const dismissUsageLimits = useCallback(() => setUsageLimitsPanel(null), []);
497 // A send may resolve after navigating away, so only the originating
498 // thread's panel is cleared; a panel opened elsewhere in the meantime stays.
499 const clearUsageLimitsFor = useCallback(
500 (threadKey: string) =>
501 setUsageLimitsPanel((current) =>
502 current !== null && current.threadKey === threadKey ? null : current,
503 ),
504 [],
505 );
506 const userInputCollapsed =
507 activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
508 // The card's height RESERVES keyboard space at all times instead of
509 // tracking the keyboard: transforms (the sticky translation) apply
510 // same-frame on the UI thread while layout props lag a Yoga pass behind,
511 // so any height that follows the keyboard flashes the card over the nav
512 // header on the way up. With a constant height the keyboard transition is
513 // pure translation — frame-perfect by construction — and the resting card
514 // stays compact over the transcript. Before the first open the reserve is
515 // an estimate; once a real height is known the card corrects once,
516 // discretely.
517 const [lastKnownKeyboardHeight, setLastKnownKeyboardHeight] = useState(0);
518 useEffect(() => {
519 if (liveKeyboardHeight > 0 && liveKeyboardHeight !== lastKnownKeyboardHeight) {
520 setLastKnownKeyboardHeight(liveKeyboardHeight);
521 }
522 }, [lastKnownKeyboardHeight, liveKeyboardHeight]);
523 const pendingUserInputMaxHeight = derivePendingUserInputMaxHeight({
524 windowHeight,
525 keyboardHeight:
526 lastKnownKeyboardHeight > 0 ? lastKnownKeyboardHeight : ESTIMATED_KEYBOARD_HEIGHT,
527 navigationHeaderHeight,
528 // The questionnaire owns the composer slot, so only the composer's
529 // bottom inset still overlaps.
530 composerOverlapHeight: composerBottomInset,
531 });
532 const estimatedOverlayHeight = composerOverlapHeight;
533 // The overlay's measured height includes the home-indicator inset (the
534 // composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
535 // UIKit add the safe-area bottom to the content inset AGAIN — leaving a
536 // dead strip between the resting content and the composer. Report the
537 // overlay height minus the safe area; UIKit adds it back, and ThreadFeed
538 // hands LegendList the same delta via contentInsetEndStaticAdjustment so
539 // its end-scroll math matches the real resting position.
540 const nativeInsetOvercount =
541 props.usesAutomaticContentInsets === true && Platform.OS === "ios" ? insets.bottom : 0;
542 const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
543 listRef,
544 composerOverlayRef,
545 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
546 -nativeInsetOvercount,
547 Platform.OS === "ios" ? COMPOSER_TRANSITION_DURATION_MS : 0,
548 );
549 // The expanded questionnaire is an absolute overlay on iOS, so it never
550 // changes the measured overlay height (that constancy is what keeps the
551 // feed from snapping on collapse/expand). The toggle choreography runs on
552 // SHARED VALUES set directly in the tap handler — one JS hop, then the
553 // card's rise/sink and the feed's end-inset glide animate in lockstep on
554 // the UI thread, keyboard-style, instead of waiting on React mount +
555 // onLayout + state round trips. Coverage (how far the card extends above
556 // the bar) is measured straight into a shared value by the card's
557 // onLayout, with no re-render.
558 const userInputCardProgress = useSharedValue(1);
559 const userInputInsetProgress = useSharedValue(1);
560 const userInputCardCoverage = useSharedValue(0);
561 const floatingControlCoverage = useSharedValue(
562 showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0,
563 );
564 useEffect(() => {
565 floatingControlCoverage.value = withTiming(
566 showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0,
567 { duration: 180, reduceMotion: ReduceMotion.System },
568 );
569 }, [floatingControlCoverage, showFloatingStatus]);
570 // Android renders the expanded card in-flow (it cannot hit-test the iOS
571 // overlay outside the bar's bounds), so its measured overlay height already
572 // includes the card — the coverage extra is iOS-only.
573 const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null;
574 const combinedContentInsetEndAdjustment = useSharedValue(
575 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
576 );
577 useAnimatedReaction(
578 () =>
579 contentInsetEndAdjustment.value +
580 floatingControlCoverage.value +
581 (userInputCoverageApplies ? userInputInsetProgress.value * userInputCardCoverage.value : 0),
582 (value) => {
583 combinedContentInsetEndAdjustment.value = value;
584 },
585 [userInputCoverageApplies],
586 );
587 const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
588 const endFollowEnabledRef = useRef(true);
589 endFollowEnabledRef.current = endFollowEnabled;
590 const overlayRepinTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
591 const previousWorkingControlStateRef = useRef({
592 threadKey: selectedThreadKey,
593 visible: false,
594 });
595 // The list's own corrections for these inset changes drift on short
596 // content (and the error compounds across toggles), so deterministically
597 // re-pin the end once a toggle settles: a no-op when the resting position
598 // is already right, corrective when it is not. Follow state is re-checked
599 // inside the callback — the user may grab the list during the settle
600 // window, and yanking them back would override a live gesture.
601 const scheduleOverlayRepin = useCallback(
602 (delayMs: number) => {
603 if (overlayRepinTimerRef.current !== null) {
604 clearTimeout(overlayRepinTimerRef.current);
605 }
606 overlayRepinTimerRef.current = setTimeout(() => {
607 overlayRepinTimerRef.current = null;
608 if (!endFollowEnabledRef.current) {
609 return;
610 }
611 void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
612 freeze.set(false);
613 });
614 }, delayMs);
615 },
616 [freeze, scrollMessageToEnd],
617 );
618 useEffect(
619 () => () => {
620 if (overlayRepinTimerRef.current !== null) {
621 clearTimeout(overlayRepinTimerRef.current);
622 }
623 },
624 [],
625 );
626 useEffect(() => {
627 const previous = previousWorkingControlStateRef.current;
628 const threadChanged = previous.threadKey !== selectedThreadKey;
629 const visibilityChanged = previous.visible !== showFloatingStatus;
630 previousWorkingControlStateRef.current = {
631 threadKey: selectedThreadKey,
632 visible: showFloatingStatus,
633 };
634 if ((!threadChanged && !visibilityChanged) || (threadChanged && !showFloatingStatus)) {
635 return;
636 }
637 // LegendList applies the larger inset but does not re-anchor short
638 // followed conversations when this floating coverage changes after the
639 // initial load. Re-pin after the finite inset transition; the callback
640 // checks follow state again so a user who scrolled up stays put.
641 scheduleOverlayRepin(230);
642 }, [scheduleOverlayRepin, selectedThreadKey, showFloatingStatus]);
643 const handleToggleUserInputCollapsed = useCallback(() => {
644 if (activeUserInputRequestId === null) {
645 return;
646 }
647 if (userInputCollapsed) {
648 // Expanding: card and feed glide start NOW, on the UI thread.
649 userInputCardProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
650 userInputInsetProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
651 setCollapsedUserInputRequestId(null);
652 scheduleOverlayRepin(USER_INPUT_TOGGLE_DURATION_MS + 50);
653 } else {
654 // Collapsing hides the custom-answer inputs; release the keyboard with
655 // them instead of leaving it up over a dead responder.
656 Keyboard.dismiss();
657 userInputCardProgress.value = withTiming(0, USER_INPUT_TOGGLE_TIMING);
658 // Instant: the sinking card still covers the strip being revealed, and
659 // animating the inset downward is what drifted the short-content end
660 // anchor.
661 userInputInsetProgress.value = 0;
662 setCollapsedUserInputRequestId(activeUserInputRequestId);
663 scheduleOverlayRepin(60);
664 }
665 }, [
666 activeUserInputRequestId,
667 scheduleOverlayRepin,
668 userInputCardProgress,
669 userInputCollapsed,
670 userInputInsetProgress,
671 ]);
672 useEffect(() => {
673 // A new request always arrives expanded.
674 userInputCardProgress.value = 1;
675 userInputInsetProgress.value = 1;
676 }, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]);
677 const showContent = props.showContent ?? true;
678 const layoutVariant = props.layoutVariant ?? "compact";
679 const isSplitLayout = layoutVariant === "split";
680 const contentMaxWidth = isSplitLayout ? CHAT_CONTENT_MAX_WIDTH : undefined;
681 const workspaceContentWidth = useWorkspaceContentWidth();
682 // Clearing animated width can retain the unfolded width after Android resumes folded.
683 // Assign both layouts explicitly so the dock always follows its current parent.
684 const composerWidthStyle = useAnimatedStyle(() =>
685 isSplitLayout && workspaceContentWidth !== null
686 ? { width: workspaceContentWidth.value }
687 : { width: "100%" },
688 );
689 const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
690 useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
691 const selectedProviderSkills = useMemo(() => {
692 const provider = props.serverConfig?.providers.find(
693 (candidate) => candidate.instanceId === selectedInstanceId,
694 );
695 return provider
696 ? resolveProviderSkillsForCwd(provider, props.threadCwd ?? props.projectWorkspaceRoot)
697 : [];
698 }, [props.projectWorkspaceRoot, props.serverConfig, props.threadCwd, selectedInstanceId]);
699
700 useLayoutEffect(() => {
701 selectedThreadKeyRef.current = selectedThreadKey;
702 // A replaced or unmounted native editor may not emit a blur event.
703 setComposerFocused(false);
704 }, [selectedThreadKey, showContent]);
705
706 useEffect(() => {
707 setAnchorMessageId(null);
708 setSubmittedMessageId(null);
709 lastScrolledSubmittedMessageIdRef.current = null;
710 setEndFollowEnabled(true);
711 freeze.set(false);
712 }, [freeze, selectedThreadKey]);
713
714 useEffect(() => {
715 if (
716 submittedMessageId === null ||
717 anchorMessageId !== submittedMessageId ||
718 lastScrolledSubmittedMessageIdRef.current === submittedMessageId ||
719 contentPresentationKind !== "ready" ||
720 (!selectedThreadFeed.some(
721 (entry) => entry.type === "message" && entry.id === submittedMessageId,
722 ) &&
723 !props.queuedMessages.some((message) => message.messageId === submittedMessageId))
724 ) {
725 return;
726 }
727
728 const targetThreadKey = selectedThreadKey;
729 const frame = requestAnimationFrame(() => {
730 if (selectedThreadKeyRef.current !== targetThreadKey) {
731 return;
732 }
733 lastScrolledSubmittedMessageIdRef.current = submittedMessageId;
734 // Wait for the keyboard dismissal (started by blur() on send) to finish
735 // before scrolling: scrollMessageToEnd freezes keyboard-driven inset
736 // updates while it runs, and a close event swallowed by that freeze
737 // leaves the keyboard padding permanently applied — overshooting the
738 // anchor and leaving a phantom bottom inset once the reply streams in.
739 void KeyboardController.dismiss()
740 .then(() => {
741 if (
742 selectedThreadKeyRef.current !== targetThreadKey ||
743 lastScrolledSubmittedMessageIdRef.current !== submittedMessageId
744 ) {
745 return;
746 }
747 return scrollMessageToEnd({ animated: true, closeKeyboard: false });
748 })
749 .catch(() => {
750 if (
751 selectedThreadKeyRef.current !== targetThreadKey ||
752 lastScrolledSubmittedMessageIdRef.current !== submittedMessageId
753 ) {
754 return;
755 }
756 lastScrolledSubmittedMessageIdRef.current = null;
757 freeze.set(false);
758 });
759 });
760 return () => cancelAnimationFrame(frame);
761 }, [
762 anchorMessageId,
763 submittedMessageId,
764 freeze,
765 contentPresentationKind,
766 props.queuedMessages,
767 selectedThreadFeed,
768 scrollMessageToEnd,
769 selectedThreadKey,
770 ]);
771
772 const handleSendMessage = useCallback(async () => {
773 const targetThreadKey = selectedThreadKey;
774 const hasUserMessage = selectedThreadFeed.some(
775 (entry) => entry.type === "message" && entry.message.role === "user",
776 );
777 const messageId = await props.onSendMessage();
778 if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
779 return messageId;
780 }
781
782 // A sent message makes the snapshot stale; a refused send leaves it in place.
783 clearUsageLimitsFor(targetThreadKey);
784
785 setSubmittedMessageId(messageId);
786 setAnchorMessageId(
787 resolveThreadFeedSubmissionAnchor({
788 currentAnchorMessageId: anchorMessageId,
789 submittedMessageId: messageId,
790 hasStartedTurn: props.selectedThread.latestTurn !== null,
791 hasUserMessage,
792 queuedMessageCount: props.selectedThreadQueueCount,
793 }),
794 );
795 composerEditorRef.current?.blur();
796 return messageId;
797 }, [
798 anchorMessageId,
799 clearUsageLimitsFor,
800 props.onSendMessage,
801 props.selectedThread.latestTurn,
802 props.selectedThreadQueueCount,
803 selectedThreadFeed,
804 selectedThreadKey,
805 ]);
806
807 const handleEditPendingMessage = useCallback(async (message: QueuedThreadMessage) => {
808 try {
809 if (
810 (await editPendingThreadMessage(message)) &&
811 selectedThreadKeyRef.current === scopedThreadKey(message.environmentId, message.threadId)
812 ) {
813 composerEditorRef.current?.focus();
814 }
815 } catch (error) {
816 Alert.alert(
817 "Could not edit message",
818 error instanceof Error ? error.message : "Please try again.",
819 );
820 }
821 }, []);
822
823 const collapseComposer = useCallback(() => {
824 composerEditorRef.current?.blur();
825 }, []);
826
827 const handleUseArtifactTemplate = useCallback(
828 (template: CodexArtifactTemplate) => {
829 const currentDraft = draftMessageRef.current;
830 const nextDraft = appendCodexArtifactTemplateUsePrompt(currentDraft, template);
831 if (nextDraft !== currentDraft) {
832 draftMessageRef.current = nextDraft;
833 props.onChangeDraftMessage(nextDraft);
834 }
835 requestAnimationFrame(() => {
836 composerEditorRef.current?.focus();
837 composerEditorRef.current?.setSelection({ start: nextDraft.length, end: nextDraft.length });
838 });
839 },
840 [props.onChangeDraftMessage],
841 );
842
843 const handleScrollToEnd = useCallback(() => {
844 void Haptics.selectionAsync();
845 void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
846 freeze.set(false);
847 });
848 }, [freeze, scrollMessageToEnd]);
849
850 const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled;
851 const { themeAppearance } = useAppearancePreferences();
852 const isDarkMode = themeAppearance === "dark";
853
854 const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
855 feedTouchStartRef.current = {
856 pageX: event.nativeEvent.pageX,
857 pageY: event.nativeEvent.pageY,
858 };
859 }, []);
860
861 const handleFeedTouchMove = useCallback((event: GestureResponderEvent) => {
862 const start = feedTouchStartRef.current;
863 if (!start) {
864 return;
865 }
866 const deltaX = event.nativeEvent.pageX - start.pageX;
867 const deltaY = event.nativeEvent.pageY - start.pageY;
868 if (Math.hypot(deltaX, deltaY) > 8) {
869 feedTouchStartRef.current = null;
870 }
871 }, []);
872
873 const handleFeedTouchEnd = useCallback(() => {
874 if (feedTouchStartRef.current) {
875 collapseComposer();
876 }
877 feedTouchStartRef.current = null;
878 }, [collapseComposer]);
879
880 const handleFeedTouchCancel = useCallback(() => {
881 feedTouchStartRef.current = null;
882 }, []);
883
884 return (
885 <View className="flex-1">
886 {showContent ? (
887 <View
888 style={{ flex: 1 }}
889 onTouchStart={handleFeedTouchStart}
890 onTouchMove={handleFeedTouchMove}
891 onTouchEnd={handleFeedTouchEnd}
892 onTouchCancel={handleFeedTouchCancel}
893 >
894 <View
895 pointerEvents="none"
896 className={
897 Platform.OS === "android"
898 ? "absolute inset-0 bg-thread-canvas"
899 : "absolute inset-0 bg-screen"
900 }
901 />
902 <RenderErrorBoundary
903 key={selectedThreadKey}
904 resetKeys={[props.threadCwd]}
905 renderFallback={(fallback) => (
906 <RenderFailureView
907 {...fallback}
908 title="The conversation couldn't be displayed"
909 bottomInset={estimatedOverlayHeight}
910 />
911 )}
912 >
913 <ThreadFeed
914 environmentId={props.environmentId}
915 threadId={props.selectedThread.id}
916 workspaceRoot={props.threadCwd}
917 feed={props.selectedThreadFeed}
918 worktreeSetup={props.worktreeSetup}
919 setupWorkingStartedAt={props.setupWorkingStartedAt}
920 queuedMessages={props.queuedMessages}
921 dispatchingMessageId={props.dispatchingMessageId}
922 onEditPendingMessage={handleEditPendingMessage}
923 contentPresentation={props.contentPresentation}
924 agentLabel={agentLabel}
925 latestTurn={props.selectedThread.latestTurn}
926 activeWorkStartedAt={props.activeWorkStartedAt}
927 listRef={listRef}
928 freeze={freeze}
929 anchorMessageId={anchorMessageId}
930 submittedMessageId={submittedMessageId}
931 contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
932 contentTopInset={0}
933 contentBottomInset={
934 estimatedOverlayHeight +
935 (showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0)
936 }
937 contentMaxWidth={contentMaxWidth}
938 layoutVariant={layoutVariant}
939 usesAutomaticContentInsets={props.usesAutomaticContentInsets}
940 onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
941 onEndFollowEnabledChange={setEndFollowEnabled}
942 skills={selectedProviderSkills}
943 onUseArtifactTemplate={handleUseArtifactTemplate}
944 loadEarlier={props.loadEarlier ?? null}
945 />
946 </RenderErrorBoundary>
947 </View>
948 ) : (
949 <View className="flex-1" />
950 )}
951
952 {/* Floating composer — sticks to keyboard via KeyboardStickyView */}
953 {showContent ? (
954 <KeyboardStickyView
955 // iOS emits a native animated height target on both will-show and
956 // will-hide, so stay subscribed for the full transition. Android
957 // retains its background/resume stale-state quarantine.
958 enabled={Platform.OS === "ios" || (isKeyboardVisible && !keyboardStateSuspect)}
959 pointerEvents="box-none"
960 style={{ position: "absolute", bottom: 0, left: 0, right: 0, top: 0 }}
961 offset={{ closed: 0, opened: 0 }}
962 >
963 {/* The fixed sticky host gives this bottom-anchored child a stable
964 coordinate space. Its top and height can then animate together
965 instead of the auto-sized host jumping to Yoga's destination. */}
966 <Animated.View
967 layout={COMPOSER_LAYOUT_TRANSITION}
968 pointerEvents="box-none"
969 style={[{ position: "absolute", bottom: 0, left: 0 }, composerWidthStyle]}
970 >
971 {/* No paddingTop here: the overlay's measured height becomes the
972 list's bottom inset, so any padding above the pill/composer
973 pushes the resting content floor up by the same amount. */}
974 <View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
975 <FloatingWorkingControl
976 colorScheme={isDarkMode ? "dark" : "light"}
977 status={floatingStatus}
978 devicePreview={
979 devicePreviews.length > 0
980 ? { count: devicePreviews.length, onPress: openDevicePreview }
981 : null
982 }
983 showScrollToEnd={showScrollToEndButton}
984 onScrollToEnd={handleScrollToEnd}
985 />
986 <View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
987 {props.feedbackSubmissions.map((submission) => (
988 <ComposerFeedback
989 key={submission.id}
990 submission={submission}
991 onDismiss={() => props.onDismissFeedback(submission.id)}
992 />
993 ))}
994 {usageLimitsReport && activeUserInputRequestId === null ? (
995 <Animated.View
996 className="shrink-0 px-4 pb-3"
997 entering={FadeInDown.duration(220)}
998 exiting={FadeOut.duration(140)}
999 >
1000 <ComposerUsageLimits
1001 report={usageLimitsReport}
1002 environmentId={props.environmentId}
1003 onClose={dismissUsageLimits}
1004 />
1005 </Animated.View>
1006 ) : null}
1007 {props.creationState?.kind === "failed" ? (
1008 <Animated.View
1009 className="shrink-0 px-4"
1010 style={{ paddingBottom: composerBottomInset }}
1011 entering={FadeInDown.duration(220)}
1012 exiting={FadeOut.duration(140)}
1013 >
1014 <ThreadCreationFailedCard
1015 reason={props.creationState.reason}
1016 onEditTask={props.creationState.onEditTask}
1017 />
1018 </Animated.View>
1019 ) : null}
1020 {props.activePendingApproval || props.activePendingUserInput ? (
1021 <Animated.View
1022 className="shrink-0 gap-3 px-4 pb-3"
1023 // The questionnaire replaces the composer, so it must pad
1024 // the home indicator the composer normally covers.
1025 style={
1026 activeUserInputRequestId !== null
1027 ? { paddingBottom: composerBottomInset }
1028 : undefined
1029 }
1030 entering={FadeInDown.duration(220)}
1031 exiting={FadeOut.duration(140)}
1032 >
1033 {props.activePendingApproval ? (
1034 <PendingApprovalCard
1035 approval={props.activePendingApproval}
1036 respondingApprovalId={props.respondingApprovalId}
1037 onRespond={props.onRespondToApproval}
1038 />
1039 ) : null}
1040 {props.activePendingUserInput ? (
1041 <PendingUserInputCard
1042 pendingUserInput={props.activePendingUserInput}
1043 maxHeight={pendingUserInputMaxHeight}
1044 collapsed={userInputCollapsed}
1045 onToggleCollapsed={handleToggleUserInputCollapsed}
1046 onStopThread={props.onStopThread}
1047 cardProgress={userInputCardProgress}
1048 cardCoverage={userInputCardCoverage}
1049 onInputFocusChange={handleOwnedInputFocusChange}
1050 drafts={props.activePendingUserInputDrafts}
1051 answers={props.activePendingUserInputAnswers}
1052 respondingUserInputId={props.respondingUserInputId}
1053 onSelectOption={props.onSelectUserInputOption}
1054 onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
1055 onSubmit={props.onSubmitUserInput}
1056 onDismiss={props.onDismissUserInput}
1057 />
1058 ) : null}
1059 </Animated.View>
1060 ) : null}
1061 </View>
1062
1063 {/* Hidden (not unmounted) while a user-input request owns the
1064 composer slot, so composer drafts and editor state survive.
1065 A rejected creation has no thread to send to; the failure card
1066 owns the slot instead. */}
1067 <View
1068 style={
1069 activeUserInputRequestId !== null || props.creationState?.kind === "failed"
1070 ? { display: "none" }
1071 : undefined
1072 }
1073 >
1074 <ThreadComposer
1075 editorRef={composerEditorRef}
1076 draftMessage={props.draftMessage}
1077 draftAttachments={props.draftAttachments}
1078 placeholder="Ask the repo agent, or run a command…"
1079 contentMaxWidth={contentMaxWidth}
1080 connectionState={props.connectionStateLabel}
1081 environmentLabel={props.environmentLabel}
1082 selectedThread={props.selectedThread}
1083 hasCompactableConversation={hasCompactableConversation && !props.isCompacting}
1084 serverConfig={props.serverConfig}
1085 queueCount={props.selectedThreadQueueCount}
1086 environmentId={props.environmentId}
1087 projectCwd={props.threadCwd ?? props.projectWorkspaceRoot}
1088 // Follow-ups typed during setup wait in the draft: queueing
1089 // them against a thread id the server may still reject
1090 // would strand them in the outbox.
1091 sendBlockedReason={
1092 props.creationState?.kind === "preparing" ? "Starting the task…" : null
1093 }
1094 bottomInset={composerBottomInset}
1095 onChangeDraftMessage={props.onChangeDraftMessage}
1096 onPickDraftMedia={props.onPickDraftMedia}
1097 onPickDraftFiles={props.onPickDraftFiles}
1098 onNativePasteImages={props.onNativePasteImages}
1099 onNativePasteText={props.onNativePasteText}
1100 onRemoveDraftImage={props.onRemoveDraftImage}
1101 onStopThread={props.onStopThread}
1102 onSendMessage={handleSendMessage}
1103 onShowUsageLimits={showUsageLimits}
1104 onUpdateModelSelection={props.onUpdateThreadModelSelection}
1105 onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
1106 onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
1107 onExpandedChange={setComposerExpanded}
1108 onEditorFocusChange={handleComposerFocusChange}
1109 />
1110 </View>
1111 </View>
1112 </Animated.View>
1113 </KeyboardStickyView>
1114 ) : null}
1115 </View>
1116 );
1117});