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

ThreadDetailScreen.tsx

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