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

ThreadDetailScreen.tsx

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