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