Open History to see the last commit
1import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
2import {
3 appendCodexArtifactTemplateUsePrompt,
4 type CodexArtifactTemplate,
5} from "@t3tools/client-runtime/codex-artifact-templates";
6import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
7import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
8import { resolveProviderSkillsForCwd } from "@t3tools/client-runtime/providerSkills";
9import type { LegendListRef } from "@legendapp/list/react-native";
10import { HeaderHeightContext } from "@react-navigation/elements";
11import type {
12 ApprovalRequestId,
13 EnvironmentId,
14 MessageId,
15 ModelSelection,
16 OrchestrationThreadShell,
17 ProviderApprovalDecision,
18 ProviderInteractionMode,
19 RuntimeMode,
20 ServerConfig as T3ServerConfig,
21 ThreadId,
22 UserInputQuestion,
23} from "@t3tools/contracts";
24import * as Haptics from "expo-haptics";
25import {
26 memo,
27 useCallback,
28 useContext,
29 useEffect,
30 useLayoutEffect,
31 useMemo,
32 useRef,
33 useState,
34} from "react";
35import {
36 AppState,
37 Keyboard,
38 Platform,
39 useWindowDimensions,
40 View,
41 type GestureResponderEvent,
42} from "react-native";
43import {
44 KeyboardController,
45 KeyboardStickyView,
46 useKeyboardState,
47} from "react-native-keyboard-controller";
48import Animated, {
49 Easing,
50 FadeInDown,
51 FadeOut,
52 ReduceMotion,
53 useAnimatedReaction,
54 useSharedValue,
55 withTiming,
56} from "react-native-reanimated";
57import { useSafeAreaInsets } from "react-native-safe-area-context";
58
59import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
60import type { ComposerEditorHandle } from "../../components/ComposerEditor";
61import type { StatusTone } from "../../components/StatusPill";
62import type { DraftComposerAttachment } from "../../lib/composerImages";
63import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
64import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
65import { scopedThreadKey } from "../../lib/scopedEntities";
66import type {
67 PendingApproval,
68 PendingUserInput,
69 PendingUserInputDraftAnswer,
70 ThreadFeedEntry,
71} from "../../lib/threadActivity";
72import { PendingApprovalCard } from "./PendingApprovalCard";
73import { PendingUserInputCard } from "./PendingUserInputCard";
74import {
75 FLOATING_WORKING_CONTROL_COVERAGE,
76 FloatingWorkingControl,
77} from "./floating-working-control";
78import {
79 derivePendingUserInputMaxHeight,
80 ESTIMATED_KEYBOARD_HEIGHT,
81 USER_INPUT_TOGGLE_DURATION_MS,
82} from "./pendingUserInputLayout";
83import {
84 COMPOSER_COLLAPSED_CHROME,
85 COMPOSER_EXPANDED_CHROME,
86 COMPOSER_LAYOUT_TRANSITION,
87 COMPOSER_TRANSITION_DURATION_MS,
88 ThreadComposer,
89} from "./ThreadComposer";
90import { ThreadFeed } from "./ThreadFeed";
91import type { ThreadContentPresentation } from "./threadContentPresentation";
92import { resolveThreadFeedSubmissionAnchor } from "./thread-feed-live-follow";
93
94export interface ThreadDetailScreenProps {
95 readonly selectedThread: OrchestrationThreadShell;
96 readonly contentPresentation: ThreadContentPresentation;
97 readonly screenTone: StatusTone;
98 readonly connectionError: string | null;
99 readonly environmentLabel: string | null;
100 readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
101 readonly activeWorkStartedAt: string | null;
102 readonly activePendingApproval: PendingApproval | null;
103 readonly respondingApprovalId: ApprovalRequestId | null;
104 readonly activePendingUserInput: PendingUserInput | null;
105 readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
106 readonly activePendingUserInputAnswers: Record<string, string | ReadonlyArray<string>> | null;
107 readonly respondingUserInputId: ApprovalRequestId | null;
108 readonly draftMessage: string;
109 readonly draftAttachments: ReadonlyArray<DraftComposerAttachment>;
110 readonly connectionStateLabel: EnvironmentConnectionPhase;
111 /** Message sync status for the selected thread (drives the composer status pill). */
112 readonly threadSyncStatus?: EnvironmentThreadStatus;
113 /** Non-null when older turns exist beyond the loaded window. */
114 readonly loadEarlier?: { readonly loading: boolean; readonly onLoadEarlier: () => void } | null;
115 readonly environmentId: EnvironmentId;
116 readonly projectWorkspaceRoot: string | null;
117 readonly threadCwd: string | null;
118 readonly selectedThreadQueueCount: number;
119 readonly serverConfig: T3ServerConfig | null;
120 readonly layoutVariant?: LayoutVariant;
121 readonly usesAutomaticContentInsets?: boolean;
122 readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
123 readonly onOpenConnectionEditor: () => void;
124 readonly onChangeDraftMessage: (value: string) => void;
125 readonly onPickDraftMedia: () => Promise<void>;
126 readonly onPickDraftFiles: () => Promise<void>;
127 readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
128 readonly onRemoveDraftImage: (imageId: string) => void;
129 readonly onStopThread: () => void;
130 /** Optimistic Stop feedback: set on press, cleared when work ends (#8618). */
131 readonly isStoppingThread: boolean;
132 readonly onSendMessage: () => Promise<MessageId | null>;
133 readonly onReconnectEnvironment: () => void;
134 readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
135 readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
136 readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
137 readonly onRespondToApproval: (
138 requestId: ApprovalRequestId,
139 decision: ProviderApprovalDecision,
140 ) => Promise<unknown>;
141 readonly onSelectUserInputOption: (
142 requestId: ApprovalRequestId,
143 question: UserInputQuestion,
144 label: string,
145 ) => void;
146 readonly onChangeUserInputCustomAnswer: (
147 requestId: ApprovalRequestId,
148 questionId: string,
149 customAnswer: string,
150 ) => void;
151 readonly onSubmitUserInput: () => Promise<unknown>;
152 readonly showContent?: boolean;
153}
154
155function latestStreamingAssistantMessage(
156 feed: ReadonlyArray<ThreadFeedEntry>,
157): { readonly id: string; readonly textLength: number } | null {
158 for (let index = feed.length - 1; index >= 0; index -= 1) {
159 const entry = feed[index];
160 if (entry?.type !== "message") {
161 continue;
162 }
163 if (entry.message.role !== "assistant" || !entry.message.streaming) {
164 continue;
165 }
166 return {
167 id: entry.message.id,
168 textLength: entry.message.text.length,
169 };
170 }
171
172 return null;
173}
174
175function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedEntry>) {
176 const lastStreamingAssistantRef = useRef<{
177 readonly id: string;
178 readonly textLength: number;
179 } | null>(null);
180 const lastStreamHapticAtRef = useRef(0);
181 const hydratedRef = useRef(false);
182 const previousThreadIdRef = useRef(threadId);
183
184 useEffect(() => {
185 if (previousThreadIdRef.current !== threadId) {
186 previousThreadIdRef.current = threadId;
187 hydratedRef.current = false;
188 }
189
190 const latestStreamingMessage = latestStreamingAssistantMessage(feed);
191
192 if (!hydratedRef.current) {
193 hydratedRef.current = true;
194 lastStreamingAssistantRef.current = latestStreamingMessage;
195 return;
196 }
197
198 if (!latestStreamingMessage) {
199 lastStreamingAssistantRef.current = null;
200 return;
201 }
202
203 const previousStreamingMessage = lastStreamingAssistantRef.current;
204 lastStreamingAssistantRef.current = latestStreamingMessage;
205
206 const isNewStream = previousStreamingMessage?.id !== latestStreamingMessage.id;
207 const textGrew =
208 previousStreamingMessage?.id === latestStreamingMessage.id &&
209 latestStreamingMessage.textLength > previousStreamingMessage.textLength;
210
211 if (!isNewStream && !textGrew) {
212 return;
213 }
214
215 const now = Date.now();
216 if (!isNewStream && now - lastStreamHapticAtRef.current < 320) {
217 return;
218 }
219
220 lastStreamHapticAtRef.current = now;
221 void Haptics.selectionAsync();
222 }, [threadId, feed]);
223}
224
225const USER_INPUT_TOGGLE_TIMING = {
226 duration: USER_INPUT_TOGGLE_DURATION_MS,
227 easing: Easing.out(Easing.cubic),
228};
229
230export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
231 const insets = useSafeAreaInsets();
232 const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
233 const liveKeyboardHeight = useKeyboardState((state) => state.height);
234 // Android can swallow the IME hide callbacks when the app is backgrounded
235 // mid keyboard-hide (the reported repro: send — which blurs and starts the
236 // hide — then Home within a second). The keyboard library's height AND
237 // visibility then stay frozen open, so gating the sticky translation on
238 // visibility alone still strands the composer after resume. Quarantine the
239 // translation on every Android resume instead; any sign of a live keyboard
240 // stream — an owned input gaining focus, or any visibility/height movement —
241 // lifts it. A healthy resume sees no visual difference (the translation is
242 // already zero while the keyboard is closed).
243 const [keyboardStateSuspect, setKeyboardStateSuspect] = useState(false);
244 useEffect(() => {
245 if (Platform.OS !== "android") {
246 return;
247 }
248 const subscription = AppState.addEventListener("change", (state) => {
249 if (state === "active") {
250 setKeyboardStateSuspect(true);
251 }
252 });
253 return () => {
254 subscription.remove();
255 };
256 }, []);
257 useEffect(() => {
258 setKeyboardStateSuspect(false);
259 }, [isKeyboardVisible, liveKeyboardHeight]);
260 const handleOwnedInputFocusChange = useCallback((focused: boolean) => {
261 if (focused) {
262 setKeyboardStateSuspect(false);
263 }
264 }, []);
265 const windowHeight = useWindowDimensions().height;
266 const navigationHeaderHeight = useContext(HeaderHeightContext) || insets.top + IOS_NAV_BAR_HEIGHT;
267 const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
268 const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
269 const composerEditorRef = useRef<ComposerEditorHandle>(null);
270 const draftMessageRef = useRef(props.draftMessage);
271 draftMessageRef.current = props.draftMessage;
272 const composerOverlayRef = useRef<View>(null);
273 const listRef = useRef<LegendListRef>(null);
274 const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
275 const selectedThreadKeyRef = useRef(selectedThreadKey);
276 const lastScrolledSubmittedMessageIdRef = useRef<MessageId | null>(null);
277 const [composerExpanded, setComposerExpanded] = useState(false);
278 const [composerFocused, setComposerFocused] = useState(false);
279 const handleComposerFocusChange = useCallback(
280 (focused: boolean) => {
281 setComposerFocused(focused);
282 handleOwnedInputFocusChange(focused);
283 },
284 [handleOwnedInputFocusChange],
285 );
286 const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
287 const [submittedMessageId, setSubmittedMessageId] = useState<MessageId | null>(null);
288 const [endFollowEnabled, setEndFollowEnabled] = useState(true);
289 // Android keys the safe-area padding on keyboard visibility (#5988): the
290 // back gesture closes the keyboard while the editor stays focused, and a
291 // focus-keyed inset would leave the toolbar under the gesture bar. iOS must
292 // NOT use visibility — it only flips on keyboardDidHide, after the hide
293 // animation, so the composer would ride down flush to the screen edge and
294 // then snap up into the inset. On iOS blur precedes the hide, so the
295 // focus-keyed inset is already in place while the composer rides down.
296 // Dictation keeps that focus while the composer switches to its compact pill.
297 const composerBottomInset = (
298 Platform.OS === "android" ? isKeyboardVisible : composerExpanded || composerFocused
299 )
300 ? 0
301 : Math.max(insets.bottom, 12);
302 const contentPresentationKind = props.contentPresentation.kind;
303 // The raw sync status enters "synchronizing" on every full fetch, cached or
304 // not. Whether messages are already on screen decides the pill label: no
305 // data yet → "Loading messages", cached data reconciling → "Syncing".
306 const threadSyncPhase = (() => {
307 switch (props.threadSyncStatus) {
308 case "empty":
309 case "cached":
310 case "synchronizing":
311 if (contentPresentationKind === "ready") {
312 return "syncing" as const;
313 }
314 return contentPresentationKind === "loading" ? ("loading" as const) : null;
315 default:
316 return null;
317 }
318 })();
319 const showWorkingControl =
320 props.activeWorkStartedAt !== null &&
321 contentPresentationKind === "ready" &&
322 threadSyncPhase === null &&
323 props.connectionStateLabel === "connected" &&
324 props.activePendingApproval === null &&
325 props.activePendingUserInput === null;
326 const floatingWorkingStartedAt = showWorkingControl ? props.activeWorkStartedAt : null;
327 const selectedThreadFeed = props.selectedThreadFeed;
328 const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
329 const composerOverlapHeight = composerChrome + composerBottomInset;
330 // While a user-input request is pending, the questionnaire owns the
331 // composer slot outright: expanded it is the full card, collapsed it is a
332 // composer-style bar in the same place (with its own stop control). The
333 // composer never mounts into the transition, which keeps the collapse and
334 // keyboard animations coherent. Collapse state is keyed by request id so a
335 // new request re-expands automatically.
336 const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
337 useState<ApprovalRequestId | null>(null);
338 const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
339 const userInputCollapsed =
340 activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
341 // The card's height RESERVES keyboard space at all times instead of
342 // tracking the keyboard: transforms (the sticky translation) apply
343 // same-frame on the UI thread while layout props lag a Yoga pass behind,
344 // so any height that follows the keyboard flashes the card over the nav
345 // header on the way up. With a constant height the keyboard transition is
346 // pure translation — frame-perfect by construction — and the resting card
347 // stays compact over the transcript. Before the first open the reserve is
348 // an estimate; once a real height is known the card corrects once,
349 // discretely.
350 const [lastKnownKeyboardHeight, setLastKnownKeyboardHeight] = useState(0);
351 useEffect(() => {
352 if (liveKeyboardHeight > 0 && liveKeyboardHeight !== lastKnownKeyboardHeight) {
353 setLastKnownKeyboardHeight(liveKeyboardHeight);
354 }
355 }, [lastKnownKeyboardHeight, liveKeyboardHeight]);
356 const pendingUserInputMaxHeight = derivePendingUserInputMaxHeight({
357 windowHeight,
358 keyboardHeight:
359 lastKnownKeyboardHeight > 0 ? lastKnownKeyboardHeight : ESTIMATED_KEYBOARD_HEIGHT,
360 navigationHeaderHeight,
361 // The questionnaire owns the composer slot, so only the composer's
362 // bottom inset still overlaps.
363 composerOverlapHeight: composerBottomInset,
364 });
365 const estimatedOverlayHeight = composerOverlapHeight;
366 // The overlay's measured height includes the home-indicator inset (the
367 // composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
368 // UIKit add the safe-area bottom to the content inset AGAIN — leaving a
369 // dead strip between the resting content and the composer. Report the
370 // overlay height minus the safe area; UIKit adds it back, and ThreadFeed
371 // hands LegendList the same delta via contentInsetEndStaticAdjustment so
372 // its end-scroll math matches the real resting position.
373 const nativeInsetOvercount =
374 props.usesAutomaticContentInsets === true && Platform.OS === "ios" ? insets.bottom : 0;
375 const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
376 listRef,
377 composerOverlayRef,
378 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
379 -nativeInsetOvercount,
380 Platform.OS === "ios" ? COMPOSER_TRANSITION_DURATION_MS : 0,
381 );
382 // The expanded questionnaire is an absolute overlay on iOS, so it never
383 // changes the measured overlay height (that constancy is what keeps the
384 // feed from snapping on collapse/expand). The toggle choreography runs on
385 // SHARED VALUES set directly in the tap handler — one JS hop, then the
386 // card's rise/sink and the feed's end-inset glide animate in lockstep on
387 // the UI thread, keyboard-style, instead of waiting on React mount +
388 // onLayout + state round trips. Coverage (how far the card extends above
389 // the bar) is measured straight into a shared value by the card's
390 // onLayout, with no re-render.
391 const userInputCardProgress = useSharedValue(1);
392 const userInputInsetProgress = useSharedValue(1);
393 const userInputCardCoverage = useSharedValue(0);
394 const floatingControlCoverage = useSharedValue(
395 showWorkingControl ? FLOATING_WORKING_CONTROL_COVERAGE : 0,
396 );
397 useEffect(() => {
398 floatingControlCoverage.value = withTiming(
399 showWorkingControl ? FLOATING_WORKING_CONTROL_COVERAGE : 0,
400 { duration: 180, reduceMotion: ReduceMotion.System },
401 );
402 }, [floatingControlCoverage, showWorkingControl]);
403 // Android renders the expanded card in-flow (it cannot hit-test the iOS
404 // overlay outside the bar's bounds), so its measured overlay height already
405 // includes the card — the coverage extra is iOS-only.
406 const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null;
407 const combinedContentInsetEndAdjustment = useSharedValue(
408 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
409 );
410 useAnimatedReaction(
411 () =>
412 contentInsetEndAdjustment.value +
413 floatingControlCoverage.value +
414 (userInputCoverageApplies ? userInputInsetProgress.value * userInputCardCoverage.value : 0),
415 (value) => {
416 combinedContentInsetEndAdjustment.value = value;
417 },
418 [userInputCoverageApplies],
419 );
420 const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
421 const endFollowEnabledRef = useRef(true);
422 endFollowEnabledRef.current = endFollowEnabled;
423 const overlayRepinTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
424 const previousWorkingControlStateRef = useRef({
425 threadKey: selectedThreadKey,
426 visible: false,
427 });
428 // The list's own corrections for these inset changes drift on short
429 // content (and the error compounds across toggles), so deterministically
430 // re-pin the end once a toggle settles: a no-op when the resting position
431 // is already right, corrective when it is not. Follow state is re-checked
432 // inside the callback — the user may grab the list during the settle
433 // window, and yanking them back would override a live gesture.
434 const scheduleOverlayRepin = useCallback(
435 (delayMs: number) => {
436 if (overlayRepinTimerRef.current !== null) {
437 clearTimeout(overlayRepinTimerRef.current);
438 }
439 overlayRepinTimerRef.current = setTimeout(() => {
440 overlayRepinTimerRef.current = null;
441 if (!endFollowEnabledRef.current) {
442 return;
443 }
444 void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
445 freeze.set(false);
446 });
447 }, delayMs);
448 },
449 [freeze, scrollMessageToEnd],
450 );
451 useEffect(
452 () => () => {
453 if (overlayRepinTimerRef.current !== null) {
454 clearTimeout(overlayRepinTimerRef.current);
455 }
456 },
457 [],
458 );
459 useEffect(() => {
460 const previous = previousWorkingControlStateRef.current;
461 const threadChanged = previous.threadKey !== selectedThreadKey;
462 const visibilityChanged = previous.visible !== showWorkingControl;
463 previousWorkingControlStateRef.current = {
464 threadKey: selectedThreadKey,
465 visible: showWorkingControl,
466 };
467 if ((!threadChanged && !visibilityChanged) || (threadChanged && !showWorkingControl)) {
468 return;
469 }
470 // LegendList applies the larger inset but does not re-anchor short
471 // followed conversations when this floating coverage changes after the
472 // initial load. Re-pin after the finite inset transition; the callback
473 // checks follow state again so a user who scrolled up stays put.
474 scheduleOverlayRepin(230);
475 }, [scheduleOverlayRepin, selectedThreadKey, showWorkingControl]);
476 const handleToggleUserInputCollapsed = useCallback(() => {
477 if (activeUserInputRequestId === null) {
478 return;
479 }
480 if (userInputCollapsed) {
481 // Expanding: card and feed glide start NOW, on the UI thread.
482 userInputCardProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
483 userInputInsetProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
484 setCollapsedUserInputRequestId(null);
485 scheduleOverlayRepin(USER_INPUT_TOGGLE_DURATION_MS + 50);
486 } else {
487 // Collapsing hides the custom-answer inputs; release the keyboard with
488 // them instead of leaving it up over a dead responder.
489 Keyboard.dismiss();
490 userInputCardProgress.value = withTiming(0, USER_INPUT_TOGGLE_TIMING);
491 // Instant: the sinking card still covers the strip being revealed, and
492 // animating the inset downward is what drifted the short-content end
493 // anchor.
494 userInputInsetProgress.value = 0;
495 setCollapsedUserInputRequestId(activeUserInputRequestId);
496 scheduleOverlayRepin(60);
497 }
498 }, [
499 activeUserInputRequestId,
500 scheduleOverlayRepin,
501 userInputCardProgress,
502 userInputCollapsed,
503 userInputInsetProgress,
504 ]);
505 useEffect(() => {
506 // A new request always arrives expanded.
507 userInputCardProgress.value = 1;
508 userInputInsetProgress.value = 1;
509 }, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]);
510 const showContent = props.showContent ?? true;
511 const layoutVariant = props.layoutVariant ?? "compact";
512 const isSplitLayout = layoutVariant === "split";
513 const contentMaxWidth = isSplitLayout ? CHAT_CONTENT_MAX_WIDTH : undefined;
514 const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
515 useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
516 const selectedProviderSkills = useMemo(() => {
517 const provider = props.serverConfig?.providers.find(
518 (candidate) => candidate.instanceId === selectedInstanceId,
519 );
520 return provider
521 ? resolveProviderSkillsForCwd(provider, props.threadCwd ?? props.projectWorkspaceRoot)
522 : [];
523 }, [props.projectWorkspaceRoot, props.serverConfig, props.threadCwd, selectedInstanceId]);
524
525 useLayoutEffect(() => {
526 selectedThreadKeyRef.current = selectedThreadKey;
527 // A replaced or unmounted native editor may not emit a blur event.
528 setComposerFocused(false);
529 }, [selectedThreadKey, showContent]);
530
531 useEffect(() => {
532 setAnchorMessageId(null);
533 setSubmittedMessageId(null);
534 lastScrolledSubmittedMessageIdRef.current = null;
535 setEndFollowEnabled(true);
536 freeze.set(false);
537 }, [freeze, selectedThreadKey]);
538
539 useEffect(() => {
540 if (
541 submittedMessageId === null ||
542 lastScrolledSubmittedMessageIdRef.current === submittedMessageId ||
543 contentPresentationKind !== "ready" ||
544 !selectedThreadFeed.some(
545 (entry) => entry.type === "message" && entry.id === submittedMessageId,
546 )
547 ) {
548 return;
549 }
550
551 const targetThreadKey = selectedThreadKey;
552 const frame = requestAnimationFrame(() => {
553 if (selectedThreadKeyRef.current !== targetThreadKey) {
554 return;
555 }
556 lastScrolledSubmittedMessageIdRef.current = submittedMessageId;
557 // Wait for the keyboard dismissal (started by blur() on send) to finish
558 // before scrolling: scrollMessageToEnd freezes keyboard-driven inset
559 // updates while it runs, and a close event swallowed by that freeze
560 // leaves the keyboard padding permanently applied — overshooting the
561 // anchor and leaving a phantom bottom inset once the reply streams in.
562 void KeyboardController.dismiss()
563 .then(() => {
564 if (
565 selectedThreadKeyRef.current !== targetThreadKey ||
566 lastScrolledSubmittedMessageIdRef.current !== submittedMessageId
567 ) {
568 return;
569 }
570 return scrollMessageToEnd({ animated: true, closeKeyboard: false });
571 })
572 .catch(() => {
573 if (
574 selectedThreadKeyRef.current !== targetThreadKey ||
575 lastScrolledSubmittedMessageIdRef.current !== submittedMessageId
576 ) {
577 return;
578 }
579 lastScrolledSubmittedMessageIdRef.current = null;
580 freeze.set(false);
581 });
582 });
583 return () => cancelAnimationFrame(frame);
584 }, [
585 submittedMessageId,
586 freeze,
587 contentPresentationKind,
588 selectedThreadFeed,
589 scrollMessageToEnd,
590 selectedThreadKey,
591 ]);
592
593 const handleSendMessage = useCallback(async () => {
594 const targetThreadKey = selectedThreadKey;
595 const hasUserMessage = selectedThreadFeed.some(
596 (entry) => entry.type === "message" && entry.message.role === "user",
597 );
598 const messageId = await props.onSendMessage();
599 if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
600 return messageId;
601 }
602
603 setSubmittedMessageId(messageId);
604 setAnchorMessageId(
605 resolveThreadFeedSubmissionAnchor({
606 currentAnchorMessageId: anchorMessageId,
607 submittedMessageId: messageId,
608 hasStartedTurn: props.selectedThread.latestTurn !== null,
609 hasUserMessage,
610 queuedMessageCount: props.selectedThreadQueueCount,
611 }),
612 );
613 composerEditorRef.current?.blur();
614 return messageId;
615 }, [
616 anchorMessageId,
617 props.onSendMessage,
618 props.selectedThread.latestTurn,
619 props.selectedThreadQueueCount,
620 selectedThreadFeed,
621 selectedThreadKey,
622 ]);
623
624 const collapseComposer = useCallback(() => {
625 composerEditorRef.current?.blur();
626 }, []);
627
628 const handleUseArtifactTemplate = useCallback(
629 (template: CodexArtifactTemplate) => {
630 const currentDraft = draftMessageRef.current;
631 const nextDraft = appendCodexArtifactTemplateUsePrompt(currentDraft, template);
632 if (nextDraft !== currentDraft) {
633 draftMessageRef.current = nextDraft;
634 props.onChangeDraftMessage(nextDraft);
635 }
636 requestAnimationFrame(() => {
637 composerEditorRef.current?.focus();
638 composerEditorRef.current?.setSelection({ start: nextDraft.length, end: nextDraft.length });
639 });
640 },
641 [props.onChangeDraftMessage],
642 );
643
644 const handleScrollToEnd = useCallback(() => {
645 void Haptics.selectionAsync();
646 void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
647 freeze.set(false);
648 });
649 }, [freeze, scrollMessageToEnd]);
650
651 const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled;
652 const { themeAppearance } = useAppearancePreferences();
653 const isDarkMode = themeAppearance === "dark";
654
655 const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
656 feedTouchStartRef.current = {
657 pageX: event.nativeEvent.pageX,
658 pageY: event.nativeEvent.pageY,
659 };
660 }, []);
661
662 const handleFeedTouchMove = useCallback((event: GestureResponderEvent) => {
663 const start = feedTouchStartRef.current;
664 if (!start) {
665 return;
666 }
667 const deltaX = event.nativeEvent.pageX - start.pageX;
668 const deltaY = event.nativeEvent.pageY - start.pageY;
669 if (Math.hypot(deltaX, deltaY) > 8) {
670 feedTouchStartRef.current = null;
671 }
672 }, []);
673
674 const handleFeedTouchEnd = useCallback(() => {
675 if (feedTouchStartRef.current) {
676 collapseComposer();
677 }
678 feedTouchStartRef.current = null;
679 }, [collapseComposer]);
680
681 const handleFeedTouchCancel = useCallback(() => {
682 feedTouchStartRef.current = null;
683 }, []);
684
685 return (
686 <View className="flex-1">
687 {showContent ? (
688 <View
689 className="flex-1"
690 onTouchStart={handleFeedTouchStart}
691 onTouchMove={handleFeedTouchMove}
692 onTouchEnd={handleFeedTouchEnd}
693 onTouchCancel={handleFeedTouchCancel}
694 >
695 <ThreadFeed
696 key={selectedThreadKey}
697 environmentId={props.environmentId}
698 threadId={props.selectedThread.id}
699 workspaceRoot={props.threadCwd}
700 feed={props.selectedThreadFeed}
701 contentPresentation={props.contentPresentation}
702 agentLabel={agentLabel}
703 latestTurn={props.selectedThread.latestTurn}
704 activeWorkStartedAt={props.activeWorkStartedAt}
705 listRef={listRef}
706 freeze={freeze}
707 anchorMessageId={anchorMessageId}
708 submittedMessageId={submittedMessageId}
709 contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
710 contentTopInset={0}
711 contentBottomInset={
712 estimatedOverlayHeight + (showWorkingControl ? FLOATING_WORKING_CONTROL_COVERAGE : 0)
713 }
714 contentMaxWidth={contentMaxWidth}
715 layoutVariant={layoutVariant}
716 usesAutomaticContentInsets={props.usesAutomaticContentInsets}
717 onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
718 onEndFollowEnabledChange={setEndFollowEnabled}
719 skills={selectedProviderSkills}
720 onUseArtifactTemplate={handleUseArtifactTemplate}
721 loadEarlier={props.loadEarlier ?? null}
722 />
723 </View>
724 ) : (
725 <View className="flex-1" />
726 )}
727
728 {/* Floating composer — sticks to keyboard via KeyboardStickyView */}
729 {showContent ? (
730 <KeyboardStickyView
731 // iOS emits a native animated height target on both will-show and
732 // will-hide, so stay subscribed for the full transition. Android
733 // retains its background/resume stale-state quarantine.
734 enabled={Platform.OS === "ios" || (isKeyboardVisible && !keyboardStateSuspect)}
735 pointerEvents="box-none"
736 style={{ position: "absolute", bottom: 0, left: 0, right: 0, top: 0 }}
737 offset={{ closed: 0, opened: 0 }}
738 >
739 {/* The fixed sticky host gives this bottom-anchored child a stable
740 coordinate space. Its top and height can then animate together
741 instead of the auto-sized host jumping to Yoga's destination. */}
742 <Animated.View
743 layout={COMPOSER_LAYOUT_TRANSITION}
744 pointerEvents="box-none"
745 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
746 >
747 {/* No paddingTop here: the overlay's measured height becomes the
748 list's bottom inset, so any padding above the pill/composer
749 pushes the resting content floor up by the same amount. */}
750 <View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
751 <FloatingWorkingControl
752 colorScheme={isDarkMode ? "dark" : "light"}
753 startedAt={floatingWorkingStartedAt}
754 showScrollToEnd={showScrollToEndButton}
755 onScrollToEnd={handleScrollToEnd}
756 />
757 <View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
758 {props.activePendingApproval || props.activePendingUserInput ? (
759 <Animated.View
760 className="shrink-0 gap-3 px-4 pb-3"
761 // The questionnaire replaces the composer, so it must pad
762 // the home indicator the composer normally covers.
763 style={
764 activeUserInputRequestId !== null
765 ? { paddingBottom: composerBottomInset }
766 : undefined
767 }
768 entering={FadeInDown.duration(220)}
769 exiting={FadeOut.duration(140)}
770 >
771 {props.activePendingApproval ? (
772 <PendingApprovalCard
773 approval={props.activePendingApproval}
774 respondingApprovalId={props.respondingApprovalId}
775 onRespond={props.onRespondToApproval}
776 />
777 ) : null}
778 {props.activePendingUserInput ? (
779 <PendingUserInputCard
780 pendingUserInput={props.activePendingUserInput}
781 maxHeight={pendingUserInputMaxHeight}
782 collapsed={userInputCollapsed}
783 onToggleCollapsed={handleToggleUserInputCollapsed}
784 onStopThread={props.onStopThread}
785 isStoppingThread={props.isStoppingThread}
786 cardProgress={userInputCardProgress}
787 cardCoverage={userInputCardCoverage}
788 onInputFocusChange={handleOwnedInputFocusChange}
789 drafts={props.activePendingUserInputDrafts}
790 answers={props.activePendingUserInputAnswers}
791 respondingUserInputId={props.respondingUserInputId}
792 onSelectOption={props.onSelectUserInputOption}
793 onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
794 onSubmit={props.onSubmitUserInput}
795 />
796 ) : null}
797 </Animated.View>
798 ) : null}
799 </View>
800
801 {/* Hidden (not unmounted) while a user-input request owns the
802 composer slot, so composer drafts and editor state survive. */}
803 <View style={activeUserInputRequestId !== null ? { display: "none" } : undefined}>
804 <ThreadComposer
805 editorRef={composerEditorRef}
806 draftMessage={props.draftMessage}
807 draftAttachments={props.draftAttachments}
808 placeholder="Ask the repo agent, or run a command…"
809 contentMaxWidth={contentMaxWidth}
810 connectionState={props.connectionStateLabel}
811 connectionError={props.connectionError}
812 environmentLabel={props.environmentLabel}
813 threadSyncPhase={threadSyncPhase}
814 selectedThread={props.selectedThread}
815 serverConfig={props.serverConfig}
816 queueCount={props.selectedThreadQueueCount}
817 environmentId={props.environmentId}
818 projectCwd={props.threadCwd ?? props.projectWorkspaceRoot}
819 bottomInset={composerBottomInset}
820 onChangeDraftMessage={props.onChangeDraftMessage}
821 onPickDraftMedia={props.onPickDraftMedia}
822 onPickDraftFiles={props.onPickDraftFiles}
823 onNativePasteImages={props.onNativePasteImages}
824 onRemoveDraftImage={props.onRemoveDraftImage}
825 onStopThread={props.onStopThread}
826 isStoppingThread={props.isStoppingThread}
827 onSendMessage={handleSendMessage}
828 onReconnectEnvironment={props.onReconnectEnvironment}
829 onUpdateModelSelection={props.onUpdateThreadModelSelection}
830 onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
831 onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
832 onExpandedChange={setComposerExpanded}
833 onEditorFocusChange={handleComposerFocusChange}
834 />
835 </View>
836 </View>
837 </Animated.View>
838 </KeyboardStickyView>
839 ) : null}
840 </View>
841 );
842});