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

ThreadDetailScreen.tsx

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