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

ThreadDetailScreen.tsx

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