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