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