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

ThreadDetailScreen.tsx

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