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