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

ThreadDetailScreen.tsx

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