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

ThreadDetailScreen.tsx

1,073 lines44.6 KB

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