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

ThreadDetailScreen.tsx

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