Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadDetailScreen.tsx

752 lines31.2 KB

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";
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;
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;
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]);
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 { themeAppearance } = useAppearancePreferences();
543 const isDarkMode = themeAppearance === "dark";
544​
545 const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
546 feedTouchStartRef.current = {
547 pageX: event.nativeEvent.pageX,
548 pageY: event.nativeEvent.pageY,
549 };
550 }, []);
551​
552 const handleFeedTouchMove = useCallback((event: GestureResponderEvent) => {
553 const start = feedTouchStartRef.current;
554 if (!start) {
555 return;
556 }
557 const deltaX = event.nativeEvent.pageX - start.pageX;
558 const deltaY = event.nativeEvent.pageY - start.pageY;
559 if (Math.hypot(deltaX, deltaY) > 8) {
560 feedTouchStartRef.current = null;
561 }
562 }, []);
563​
564 const handleFeedTouchEnd = useCallback(() => {
565 if (feedTouchStartRef.current) {
566 collapseComposer();
567 }
568 feedTouchStartRef.current = null;
569 }, [collapseComposer]);
570​
571 const handleFeedTouchCancel = useCallback(() => {
572 feedTouchStartRef.current = null;
573 }, []);
574​
575 return (
576 <View className="flex-1">
577 {showContent ? (
578 <View
579 className="flex-1"
580 onTouchStart={handleFeedTouchStart}
581 onTouchMove={handleFeedTouchMove}
582 onTouchEnd={handleFeedTouchEnd}
583 onTouchCancel={handleFeedTouchCancel}
584 >
585 <ThreadFeed
586 key={props.selectedThread.id}
587 environmentId={props.environmentId}
588 threadId={props.selectedThread.id}
589 workspaceRoot={props.threadCwd}
590 feed={props.selectedThreadFeed}
591 contentPresentation={props.contentPresentation}
592 agentLabel={agentLabel}
593 latestTurn={props.selectedThread.latestTurn}
594 activeWorkStartedAt={props.activeWorkStartedAt}
595 listRef={listRef}
596 freeze={freeze}
597 anchorMessageId={anchorMessageId}
598 contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
599 contentTopInset={0}
600 contentBottomInset={estimatedOverlayHeight}
601 contentMaxWidth={contentMaxWidth}
602 layoutVariant={layoutVariant}
603 usesAutomaticContentInsets={props.usesAutomaticContentInsets}
604 onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
605 onEndFollowEnabledChange={setEndFollowEnabled}
606 skills={selectedProviderSkills}
607 loadEarlier={props.loadEarlier ?? null}
608 />
609 </View>
610 ) : (
611 <View className="flex-1" />
612 )}
613​
614 {/* Floating composer — sticks to keyboard via KeyboardStickyView */}
615 {showContent ? (
616 <KeyboardStickyView
617 // The animated keyboard height can remain stale after a dismissed
618 // IME on both platforms. Visibility is the authoritative closed
619 // state, so disable the translation rather than stranding the pill.
620 enabled={isKeyboardVisible && !keyboardStateSuspect}
621 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
622 offset={{ closed: 0, opened: 0 }}
623 >
624 {/* No paddingTop here: the overlay's measured height becomes the
625 list's bottom inset, so any padding above the pill/composer
626 pushes the resting content floor up by the same amount. */}
627 <View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
628 {showScrollToEndButton ? (
629 <Animated.View
630 pointerEvents="box-none"
631 className="absolute -top-11 left-0 right-0 z-20 items-center"
632 entering={FadeInDown.duration(160)}
633 exiting={FadeOut.duration(100)}
634 >
635 {isLiquidGlassSupported ? (
636 <LiquidGlassView
637 colorScheme={isDarkMode ? "dark" : "light"}
638 effect="regular"
639 interactive
640 // Interactive glass can render larger than the requested
641 // box (minimum touch size), so center the pill instead of
642 // relying on it filling the glass exactly.
643 style={{
644 alignItems: "center",
645 borderRadius: 18,
646 height: 36,
647 justifyContent: "center",
648 overflow: "hidden",
649 width: 36,
650 }}
651 >
652 <ControlPill
653 accessibilityLabel="Scroll to end"
654 activateOnPressIn
655 className="h-9 w-9 bg-transparent"
656 icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
657 onPress={handleScrollToEnd}
658 />
659 </LiquidGlassView>
660 ) : (
661 <ControlPill
662 accessibilityLabel="Scroll to end"
663 activateOnPressIn
664 className="h-9 w-9 border border-border bg-card shadow-md shadow-black/10"
665 icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
666 onPress={handleScrollToEnd}
667 />
668 )}
669 </Animated.View>
670 ) : null}
671 <View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
672 {props.activePendingApproval || props.activePendingUserInput ? (
673 <Animated.View
674 className="shrink-0 gap-3 px-4 pb-3"
675 // The questionnaire replaces the composer, so it must pad
676 // the home indicator the composer normally covers.
677 style={
678 activeUserInputRequestId !== null
679 ? { paddingBottom: composerBottomInset }
680 : undefined
681 }
682 entering={FadeInDown.duration(220)}
683 exiting={FadeOut.duration(140)}
684 >
685 {props.activePendingApproval ? (
686 <PendingApprovalCard
687 approval={props.activePendingApproval}
688 respondingApprovalId={props.respondingApprovalId}
689 onRespond={props.onRespondToApproval}
690 />
691 ) : null}
692 {props.activePendingUserInput ? (
693 <PendingUserInputCard
694 pendingUserInput={props.activePendingUserInput}
695 maxHeight={pendingUserInputMaxHeight}
696 collapsed={userInputCollapsed}
697 onToggleCollapsed={handleToggleUserInputCollapsed}
698 onStopThread={props.onStopThread}
699 cardProgress={userInputCardProgress}
700 cardCoverage={userInputCardCoverage}
701 onInputFocusChange={handleOwnedInputFocusChange}
702 drafts={props.activePendingUserInputDrafts}
703 answers={props.activePendingUserInputAnswers}
704 respondingUserInputId={props.respondingUserInputId}
705 onSelectOption={props.onSelectUserInputOption}
706 onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
707 onSubmit={props.onSubmitUserInput}
708 />
709 ) : null}
710 </Animated.View>
711 ) : null}
712 </View>
713​
714 {/* Hidden (not unmounted) while a user-input request owns the
715 composer slot, so composer drafts and editor state survive. */}
716 <View style={activeUserInputRequestId !== null ? { display: "none" } : undefined}>
717 <ThreadComposer
718 editorRef={composerEditorRef}
719 draftMessage={props.draftMessage}
720 draftAttachments={props.draftAttachments}
721 placeholder="Ask the repo agent, or run a command…"
722 contentMaxWidth={contentMaxWidth}
723 connectionState={props.connectionStateLabel}
724 connectionError={props.connectionError}
725 environmentLabel={props.environmentLabel}
726 threadSyncPhase={threadSyncPhase}
727 selectedThread={props.selectedThread}
728 serverConfig={props.serverConfig}
729 queueCount={props.selectedThreadQueueCount}
730 environmentId={props.environmentId}
731 projectCwd={props.projectWorkspaceRoot}
732 bottomInset={composerBottomInset}
733 onChangeDraftMessage={props.onChangeDraftMessage}
734 onPickDraftImages={props.onPickDraftImages}
735 onNativePasteImages={props.onNativePasteImages}
736 onRemoveDraftImage={props.onRemoveDraftImage}
737 onStopThread={props.onStopThread}
738 onSendMessage={handleSendMessage}
739 onReconnectEnvironment={props.onReconnectEnvironment}
740 onUpdateModelSelection={props.onUpdateThreadModelSelection}
741 onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
742 onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
743 onExpandedChange={setComposerExpanded}
744 onEditorFocusChange={handleOwnedInputFocusChange}
745 />
746 </View>
747 </View>
748 </KeyboardStickyView>
749 ) : null}
750 </View>
751 );
752});