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

ThreadDetailScreen.tsx

959 lines39.5 KB

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