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