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