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

ThreadDetailScreen.tsx

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