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