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

ThreadDetailScreen.tsx

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