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

ThreadDetailScreen.tsx

835 lines34.5 KB

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