Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadDetailScreen.tsx

1,066 lines44.2 KB

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