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

ThreadDetailScreen.tsx

754 lines31.3 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 onCancelQueuedMessage: (messageId: MessageId) => void;
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;
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;
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]);
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 lastScrolledAnchorMessageIdRef = useRef<MessageId | null>(null);
262 const [composerExpanded, setComposerExpanded] = useState(false);
263 const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
264 const [endFollowEnabled, setEndFollowEnabled] = useState(true);
265 // Android keys the safe-area padding on keyboard visibility (#5988): the
266 // back gesture closes the keyboard while the editor stays focused, and a
267 // focus-keyed inset would leave the toolbar under the gesture bar. iOS must
268 // NOT use visibility — it only flips on keyboardDidHide, after the hide
269 // animation, so the composer would ride down flush to the screen edge and
270 // then snap up into the inset. On iOS blur precedes the hide, so the
271 // focus-keyed inset is already in place while the composer rides down.
272 const composerBottomInset = (Platform.OS === "android" ? isKeyboardVisible : composerExpanded)
273 ? 0
274 : Math.max(insets.bottom, 12);
275 const contentPresentationKind = props.contentPresentation.kind;
276 // The raw sync status enters "synchronizing" on every full fetch, cached or
277 // not. Whether messages are already on screen decides the pill label: no
278 // data yet → "Loading messages", cached data reconciling → "Syncing".
279 const threadSyncPhase = (() => {
280 switch (props.threadSyncStatus) {
281 case "empty":
282 case "cached":
283 case "synchronizing":
284 if (contentPresentationKind === "ready") {
285 return "syncing" as const;
286 }
287 return contentPresentationKind === "loading" ? ("loading" as const) : null;
288 default:
289 return null;
290 }
291 })();
292 const selectedThreadFeed = props.selectedThreadFeed;
293 const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
294 const composerOverlapHeight = composerChrome + composerBottomInset;
295 // While a user-input request is pending, the questionnaire owns the
296 // composer slot outright: expanded it is the full card, collapsed it is a
297 // composer-style bar in the same place (with its own stop control). The
298 // composer never mounts into the transition, which keeps the collapse and
299 // keyboard animations coherent. Collapse state is keyed by request id so a
300 // new request re-expands automatically.
301 const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
302 useState<ApprovalRequestId | null>(null);
303 const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
304 const userInputCollapsed =
305 activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
306 // The card's height RESERVES keyboard space at all times instead of
307 // tracking the keyboard: transforms (the sticky translation) apply
308 // same-frame on the UI thread while layout props lag a Yoga pass behind,
309 // so any height that follows the keyboard flashes the card over the nav
310 // header on the way up. With a constant height the keyboard transition is
311 // pure translation — frame-perfect by construction — and the resting card
312 // stays compact over the transcript. Before the first open the reserve is
313 // an estimate; once a real height is known the card corrects once,
314 // discretely.
315 const [lastKnownKeyboardHeight, setLastKnownKeyboardHeight] = useState(0);
316 useEffect(() => {
317 if (liveKeyboardHeight > 0 && liveKeyboardHeight !== lastKnownKeyboardHeight) {
318 setLastKnownKeyboardHeight(liveKeyboardHeight);
319 }
320 }, [lastKnownKeyboardHeight, liveKeyboardHeight]);
321 const pendingUserInputMaxHeight = derivePendingUserInputMaxHeight({
322 windowHeight,
323 keyboardHeight:
324 lastKnownKeyboardHeight > 0 ? lastKnownKeyboardHeight : ESTIMATED_KEYBOARD_HEIGHT,
325 navigationHeaderHeight,
326 // The questionnaire owns the composer slot, so only the composer's
327 // bottom inset still overlaps.
328 composerOverlapHeight: composerBottomInset,
329 });
330 const estimatedOverlayHeight = composerOverlapHeight;
331 // The overlay's measured height includes the home-indicator inset (the
332 // composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
333 // UIKit add the safe-area bottom to the content inset AGAIN — leaving a
334 // dead strip between the resting content and the composer. Report the
335 // overlay height minus the safe area; UIKit adds it back, and ThreadFeed
336 // hands LegendList the same delta via contentInsetEndStaticAdjustment so
337 // its end-scroll math matches the real resting position.
338 const nativeInsetOvercount =
339 props.usesAutomaticContentInsets === true && Platform.OS === "ios" ? insets.bottom : 0;
340 const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
341 listRef,
342 composerOverlayRef,
343 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
344 -nativeInsetOvercount,
345 );
346 // The expanded questionnaire is an absolute overlay on iOS, so it never
347 // changes the measured overlay height (that constancy is what keeps the
348 // feed from snapping on collapse/expand). The toggle choreography runs on
349 // SHARED VALUES set directly in the tap handler — one JS hop, then the
350 // card's rise/sink and the feed's end-inset glide animate in lockstep on
351 // the UI thread, keyboard-style, instead of waiting on React mount +
352 // onLayout + state round trips. Coverage (how far the card extends above
353 // the bar) is measured straight into a shared value by the card's
354 // onLayout, with no re-render.
355 const userInputCardProgress = useSharedValue(1);
356 const userInputInsetProgress = useSharedValue(1);
357 const userInputCardCoverage = useSharedValue(0);
358 // Android renders the expanded card in-flow (it cannot hit-test the iOS
359 // overlay outside the bar's bounds), so its measured overlay height already
360 // includes the card — the coverage extra is iOS-only.
361 const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null;
362 const combinedContentInsetEndAdjustment = useSharedValue(
363 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
364 );
365 useAnimatedReaction(
366 () =>
367 contentInsetEndAdjustment.value +
368 (userInputCoverageApplies ? userInputInsetProgress.value * userInputCardCoverage.value : 0),
369 (value) => {
370 combinedContentInsetEndAdjustment.value = value;
371 },
372 [userInputCoverageApplies],
373 );
374 const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
375 const endFollowEnabledRef = useRef(true);
376 endFollowEnabledRef.current = endFollowEnabled;
377 const userInputRepinTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
378 // The list's own corrections for these inset changes drift on short
379 // content (and the error compounds across toggles), so deterministically
380 // re-pin the end once a toggle settles: a no-op when the resting position
381 // is already right, corrective when it is not. Follow state is re-checked
382 // inside the callback — the user may grab the list during the settle
383 // window, and yanking them back would override a live gesture.
384 const scheduleUserInputRepin = useCallback(
385 (delayMs: number) => {
386 if (userInputRepinTimerRef.current !== null) {
387 clearTimeout(userInputRepinTimerRef.current);
388 }
389 userInputRepinTimerRef.current = setTimeout(() => {
390 userInputRepinTimerRef.current = null;
391 if (!endFollowEnabledRef.current) {
392 return;
393 }
394 void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
395 freeze.set(false);
396 });
397 }, delayMs);
398 },
399 [freeze, scrollMessageToEnd],
400 );
401 useEffect(
402 () => () => {
403 if (userInputRepinTimerRef.current !== null) {
404 clearTimeout(userInputRepinTimerRef.current);
405 }
406 },
407 [],
408 );
409 const handleToggleUserInputCollapsed = useCallback(() => {
410 if (activeUserInputRequestId === null) {
411 return;
412 }
413 if (userInputCollapsed) {
414 // Expanding: card and feed glide start NOW, on the UI thread.
415 userInputCardProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
416 userInputInsetProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
417 setCollapsedUserInputRequestId(null);
418 scheduleUserInputRepin(USER_INPUT_TOGGLE_DURATION_MS + 50);
419 } else {
420 // Collapsing hides the custom-answer inputs; release the keyboard with
421 // them instead of leaving it up over a dead responder.
422 Keyboard.dismiss();
423 userInputCardProgress.value = withTiming(0, USER_INPUT_TOGGLE_TIMING);
424 // Instant: the sinking card still covers the strip being revealed, and
425 // animating the inset downward is what drifted the short-content end
426 // anchor.
427 userInputInsetProgress.value = 0;
428 setCollapsedUserInputRequestId(activeUserInputRequestId);
429 scheduleUserInputRepin(60);
430 }
431 }, [
432 activeUserInputRequestId,
433 scheduleUserInputRepin,
434 userInputCardProgress,
435 userInputCollapsed,
436 userInputInsetProgress,
437 ]);
438 useEffect(() => {
439 // A new request always arrives expanded.
440 userInputCardProgress.value = 1;
441 userInputInsetProgress.value = 1;
442 }, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]);
443 const showContent = props.showContent ?? true;
444 const layoutVariant = props.layoutVariant ?? "compact";
445 const isSplitLayout = layoutVariant === "split";
446 const contentMaxWidth = isSplitLayout ? CHAT_CONTENT_MAX_WIDTH : undefined;
447 const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
448 useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
449 const selectedProviderSkills = useMemo(
450 () =>
451 props.serverConfig?.providers.find((provider) => provider.instanceId === selectedInstanceId)
452 ?.skills ?? [],
453 [props.serverConfig, selectedInstanceId],
454 );
455​
456 useLayoutEffect(() => {
457 selectedThreadKeyRef.current = selectedThreadKey;
458 }, [selectedThreadKey]);
459​
460 useEffect(() => {
461 setAnchorMessageId(null);
462 lastScrolledAnchorMessageIdRef.current = null;
463 setEndFollowEnabled(true);
464 freeze.set(false);
465 }, [freeze, selectedThreadKey]);
466​
467 useEffect(() => {
468 if (
469 anchorMessageId === null ||
470 lastScrolledAnchorMessageIdRef.current === anchorMessageId ||
471 contentPresentationKind !== "ready" ||
472 !selectedThreadFeed.some((entry) => entry.type === "message" && entry.id === anchorMessageId)
473 ) {
474 return;
475 }
476​
477 const targetThreadKey = selectedThreadKey;
478 const frame = requestAnimationFrame(() => {
479 if (selectedThreadKeyRef.current !== targetThreadKey) {
480 return;
481 }
482 lastScrolledAnchorMessageIdRef.current = anchorMessageId;
483 // Wait for the keyboard dismissal (started by blur() on send) to finish
484 // before scrolling: scrollMessageToEnd freezes keyboard-driven inset
485 // updates while it runs, and a close event swallowed by that freeze
486 // leaves the keyboard padding permanently applied — overshooting the
487 // anchor and leaving a phantom bottom inset once the reply streams in.
488 void KeyboardController.dismiss()
489 .then(() => {
490 if (
491 selectedThreadKeyRef.current !== targetThreadKey ||
492 lastScrolledAnchorMessageIdRef.current !== anchorMessageId
493 ) {
494 return;
495 }
496 return scrollMessageToEnd({ animated: true, closeKeyboard: false });
497 })
498 .catch(() => {
499 if (
500 selectedThreadKeyRef.current !== targetThreadKey ||
501 lastScrolledAnchorMessageIdRef.current !== anchorMessageId
502 ) {
503 return;
504 }
505 lastScrolledAnchorMessageIdRef.current = null;
506 freeze.set(false);
507 });
508 });
509 return () => cancelAnimationFrame(frame);
510 }, [
511 anchorMessageId,
512 freeze,
513 contentPresentationKind,
514 selectedThreadFeed,
515 scrollMessageToEnd,
516 selectedThreadKey,
517 ]);
518​
519 const handleSendMessage = useCallback(async () => {
520 const targetThreadKey = selectedThreadKey;
521 const messageId = await props.onSendMessage();
522 if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
523 return messageId;
524 }
525​
526 setAnchorMessageId(messageId);
527 composerEditorRef.current?.blur();
528 return messageId;
529 }, [props.onSendMessage, selectedThreadKey]);
530​
531 const collapseComposer = useCallback(() => {
532 composerEditorRef.current?.blur();
533 }, []);
534​
535 const handleScrollToEnd = useCallback(() => {
536 void Haptics.selectionAsync();
537 void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
538 freeze.set(false);
539 });
540 }, [freeze, scrollMessageToEnd]);
541​
542 const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled;
543 const { themeAppearance } = useAppearancePreferences();
544 const isDarkMode = themeAppearance === "dark";
545​
546 const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
547 feedTouchStartRef.current = {
548 pageX: event.nativeEvent.pageX,
549 pageY: event.nativeEvent.pageY,
550 };
551 }, []);
552​
553 const handleFeedTouchMove = useCallback((event: GestureResponderEvent) => {
554 const start = feedTouchStartRef.current;
555 if (!start) {
556 return;
557 }
558 const deltaX = event.nativeEvent.pageX - start.pageX;
559 const deltaY = event.nativeEvent.pageY - start.pageY;
560 if (Math.hypot(deltaX, deltaY) > 8) {
561 feedTouchStartRef.current = null;
562 }
563 }, []);
564​
565 const handleFeedTouchEnd = useCallback(() => {
566 if (feedTouchStartRef.current) {
567 collapseComposer();
568 }
569 feedTouchStartRef.current = null;
570 }, [collapseComposer]);
571​
572 const handleFeedTouchCancel = useCallback(() => {
573 feedTouchStartRef.current = null;
574 }, []);
575​
576 return (
577 <View className="flex-1">
578 {showContent ? (
579 <View
580 className="flex-1"
581 onTouchStart={handleFeedTouchStart}
582 onTouchMove={handleFeedTouchMove}
583 onTouchEnd={handleFeedTouchEnd}
584 onTouchCancel={handleFeedTouchCancel}
585 >
586 <ThreadFeed
587 key={props.selectedThread.id}
588 environmentId={props.environmentId}
589 threadId={props.selectedThread.id}
590 workspaceRoot={props.threadCwd}
591 feed={props.selectedThreadFeed}
592 contentPresentation={props.contentPresentation}
593 agentLabel={agentLabel}
594 latestTurn={props.selectedThread.latestTurn}
595 activeWorkStartedAt={props.activeWorkStartedAt}
596 listRef={listRef}
597 freeze={freeze}
598 anchorMessageId={anchorMessageId}
599 contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
600 contentTopInset={0}
601 contentBottomInset={estimatedOverlayHeight}
602 contentMaxWidth={contentMaxWidth}
603 layoutVariant={layoutVariant}
604 usesAutomaticContentInsets={props.usesAutomaticContentInsets}
605 onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
606 onEndFollowEnabledChange={setEndFollowEnabled}
607 skills={selectedProviderSkills}
608 loadEarlier={props.loadEarlier ?? null}
609 onCancelQueuedMessage={props.onCancelQueuedMessage}
610 />
611 </View>
612 ) : (
613 <View className="flex-1" />
614 )}
615​
616 {/* Floating composer — sticks to keyboard via KeyboardStickyView */}
617 {showContent ? (
618 <KeyboardStickyView
619 // The animated keyboard height can remain stale after a dismissed
620 // IME on both platforms. Visibility is the authoritative closed
621 // state, so disable the translation rather than stranding the pill.
622 enabled={isKeyboardVisible && !keyboardStateSuspect}
623 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
624 offset={{ closed: 0, opened: 0 }}
625 >
626 {/* No paddingTop here: the overlay's measured height becomes the
627 list's bottom inset, so any padding above the pill/composer
628 pushes the resting content floor up by the same amount. */}
629 <View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
630 {showScrollToEndButton ? (
631 <Animated.View
632 pointerEvents="box-none"
633 className="absolute -top-11 left-0 right-0 z-20 items-center"
634 entering={FadeInDown.duration(160)}
635 exiting={FadeOut.duration(100)}
636 >
637 {isLiquidGlassSupported ? (
638 <LiquidGlassView
639 colorScheme={isDarkMode ? "dark" : "light"}
640 effect="regular"
641 interactive
642 // Interactive glass can render larger than the requested
643 // box (minimum touch size), so center the pill instead of
644 // relying on it filling the glass exactly.
645 style={{
646 alignItems: "center",
647 borderRadius: 18,
648 height: 36,
649 justifyContent: "center",
650 overflow: "hidden",
651 width: 36,
652 }}
653 >
654 <ControlPill
655 accessibilityLabel="Scroll to end"
656 activateOnPressIn
657 className="h-9 w-9 bg-transparent"
658 icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
659 onPress={handleScrollToEnd}
660 />
661 </LiquidGlassView>
662 ) : (
663 <ControlPill
664 accessibilityLabel="Scroll to end"
665 activateOnPressIn
666 className="h-9 w-9 border border-border bg-card shadow-md shadow-black/10"
667 icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
668 onPress={handleScrollToEnd}
669 />
670 )}
671 </Animated.View>
672 ) : null}
673 <View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
674 {props.activePendingApproval || props.activePendingUserInput ? (
675 <Animated.View
676 className="shrink-0 gap-3 px-4 pb-3"
677 // The questionnaire replaces the composer, so it must pad
678 // the home indicator the composer normally covers.
679 style={
680 activeUserInputRequestId !== null
681 ? { paddingBottom: composerBottomInset }
682 : undefined
683 }
684 entering={FadeInDown.duration(220)}
685 exiting={FadeOut.duration(140)}
686 >
687 {props.activePendingApproval ? (
688 <PendingApprovalCard
689 approval={props.activePendingApproval}
690 respondingApprovalId={props.respondingApprovalId}
691 onRespond={props.onRespondToApproval}
692 />
693 ) : null}
694 {props.activePendingUserInput ? (
695 <PendingUserInputCard
696 pendingUserInput={props.activePendingUserInput}
697 maxHeight={pendingUserInputMaxHeight}
698 collapsed={userInputCollapsed}
699 onToggleCollapsed={handleToggleUserInputCollapsed}
700 onStopThread={props.onStopThread}
701 cardProgress={userInputCardProgress}
702 cardCoverage={userInputCardCoverage}
703 onInputFocusChange={handleOwnedInputFocusChange}
704 drafts={props.activePendingUserInputDrafts}
705 answers={props.activePendingUserInputAnswers}
706 respondingUserInputId={props.respondingUserInputId}
707 onSelectOption={props.onSelectUserInputOption}
708 onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
709 onSubmit={props.onSubmitUserInput}
710 />
711 ) : null}
712 </Animated.View>
713 ) : null}
714 </View>
715​
716 {/* Hidden (not unmounted) while a user-input request owns the
717 composer slot, so composer drafts and editor state survive. */}
718 <View style={activeUserInputRequestId !== null ? { display: "none" } : undefined}>
719 <ThreadComposer
720 editorRef={composerEditorRef}
721 draftMessage={props.draftMessage}
722 draftAttachments={props.draftAttachments}
723 placeholder="Ask the repo agent, or run a command…"
724 contentMaxWidth={contentMaxWidth}
725 connectionState={props.connectionStateLabel}
726 connectionError={props.connectionError}
727 environmentLabel={props.environmentLabel}
728 threadSyncPhase={threadSyncPhase}
729 selectedThread={props.selectedThread}
730 serverConfig={props.serverConfig}
731 queueCount={props.selectedThreadQueueCount}
732 environmentId={props.environmentId}
733 projectCwd={props.projectWorkspaceRoot}
734 bottomInset={composerBottomInset}
735 onChangeDraftMessage={props.onChangeDraftMessage}
736 onPickDraftImages={props.onPickDraftImages}
737 onNativePasteImages={props.onNativePasteImages}
738 onRemoveDraftImage={props.onRemoveDraftImage}
739 onStopThread={props.onStopThread}
740 onSendMessage={handleSendMessage}
741 onReconnectEnvironment={props.onReconnectEnvironment}
742 onUpdateModelSelection={props.onUpdateThreadModelSelection}
743 onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
744 onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
745 onExpandedChange={setComposerExpanded}
746 onEditorFocusChange={handleOwnedInputFocusChange}
747 />
748 </View>
749 </View>
750 </KeyboardStickyView>
751 ) : null}
752 </View>
753 );
754});