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