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