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 { ComposerTextPaste } from "../../native/T3ComposerEditor.types";
2import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
3import {
4 appendCodexArtifactTemplateUsePrompt,
5 type CodexArtifactTemplate,
6} from "@t3tools/client-runtime/codex-artifact-templates";
7import type {
8 CodexFeedbackSubmission,
9 EnvironmentThreadStatus,
10} from "@t3tools/client-runtime/state/threads";
11import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
12import { resolveProviderSkillsForCwd } from "@t3tools/client-runtime/providerSkills";
13import type { LegendListRef } from "@legendapp/list/react-native";
14import { HeaderHeightContext } from "@react-navigation/elements";
15import type {
16 ApprovalRequestId,
17 EnvironmentId,
18 MessageId,
19 ModelSelection,
20 OrchestrationThreadShell,
21 ProviderApprovalDecision,
22 ProviderInteractionMode,
23 RuntimeMode,
24 ServerConfig as T3ServerConfig,
25 ThreadId,
26 UsageLimitsReport,
27 UserInputQuestion,
28} from "@t3tools/contracts";
29import * as Haptics from "expo-haptics";
30import { BlurTargetView } from "expo-blur";
31import { GlassBlurTargetContext } from "../../lib/glassBlurTarget";
32import {
33 memo,
34 useCallback,
35 useContext,
36 useEffect,
37 useLayoutEffect,
38 useMemo,
39 useRef,
40 useState,
41} from "react";
42import {
43 Alert,
44 AppState,
45 Keyboard,
46 Platform,
47 useWindowDimensions,
48 View,
49 type GestureResponderEvent,
50} from "react-native";
51import {
52 KeyboardController,
53 KeyboardStickyView,
54 useKeyboardState,
55} from "react-native-keyboard-controller";
56import Animated, {
57 Easing,
58 FadeInDown,
59 FadeOut,
60 ReduceMotion,
61 useAnimatedReaction,
62 useAnimatedStyle,
63 useSharedValue,
64 withTiming,
65} from "react-native-reanimated";
66import { useSafeAreaInsets } from "react-native-safe-area-context";
67import { useWorkspaceContentWidth } from "../layout/workspace-content-width";
68​
69import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
70import { collectProviderUsageLimits } from "@t3tools/shared/usageLimits";
71import type { ComposerEditorHandle } from "../../components/ComposerEditor";
72import type { StatusTone } from "../../components/StatusPill";
73import type { DraftComposerAttachment } from "../../lib/composerImages";
74import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
75import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
76import { editPendingThreadMessage } from "../../state/edit-pending-thread-message";
77import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
78import { scopedThreadKey } from "../../lib/scopedEntities";
79import type {
80 PendingApproval,
81 PendingUserInput,
82 PendingUserInputDraftAnswer,
83 ThreadFeedEntry,
84} from "../../lib/threadActivity";
85import { PendingApprovalCard } from "./PendingApprovalCard";
86import { ComposerFeedback } from "./ComposerFeedback";
87import { ComposerUsageLimits } from "./ComposerUsageLimits";
88import { PendingUserInputCard } from "./PendingUserInputCard";
89import { ThreadCreationFailedCard } from "./ThreadCreationFailedCard";
90import {
91 FLOATING_WORKING_CONTROL_COVERAGE,
92 FloatingWorkingControl,
93} from "./floating-working-control";
94import { connectionFloatingStatus, type FloatingWorkingStatus } from "./floating-working-status";
95import {
96 derivePendingUserInputMaxHeight,
97 ESTIMATED_KEYBOARD_HEIGHT,
98 USER_INPUT_TOGGLE_DURATION_MS,
99} from "./pendingUserInputLayout";
100import {
101 COMPOSER_COLLAPSED_CHROME,
102 COMPOSER_EXPANDED_CHROME,
103 COMPOSER_LAYOUT_TRANSITION,
104 COMPOSER_TRANSITION_DURATION_MS,
105 ThreadComposer,
106} from "./ThreadComposer";
107import { ThreadFeed } from "./ThreadFeed";
108import type { ThreadContentPresentation } from "./threadContentPresentation";
109import { resolveThreadFeedSubmissionAnchor } from "./thread-feed-live-follow";
110​
111export interface ThreadDetailScreenProps {
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 return {
368 kind: "preparing",
369 label: props.creationState.preparingWorktree ? "Setting up worktree…" : "Starting…",
370 };
371 }
372 if (props.creationState?.kind === "failed") {
373 return null;
374 }
375 if (threadSyncLabel !== null) {
376 return { kind: "syncing", label: threadSyncLabel };
377 }
378 if (props.isCompacting && contentPresentationKind === "ready") {
379 return { kind: "compacting" };
380 }
381 if (props.activeWorkStartedAt !== null && contentPresentationKind === "ready") {
382 return { kind: "working", startedAt: props.activeWorkStartedAt };
383 }
384 return null;
385 })();
386 const showWorkingControl = floatingStatus !== null;
387 // Connection and working status occupy the same space. Keep the feed inset
388 // stable when reconnecting hands off to syncing and then to a running turn.
389 const showFloatingStatus =
390 showWorkingControl ||
391 props.connectionStateLabel !== "connected" ||
392 props.queuedMessages.length > 0 ||
393 props.selectedThreadFeed.some(
394 (entry) => "acknowledged" in entry && entry.acknowledged === true,
395 );
396 const selectedThreadFeed = props.selectedThreadFeed;
397 const hasCompactableConversation =
398 selectedThreadFeed.some(
399 (entry) =>
400 entry.type === "message" &&
401 entry.message.role === "user" &&
402 ((entry.message.attachments?.length ?? 0) > 0 ||
403 entry.message.text.trim().toLowerCase() !== "/compact"),
404 ) ||
405 (Boolean(props.loadEarlier) && props.selectedThread.latestUserMessageAt !== null);
406 const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
407 const composerOverlapHeight = composerChrome + composerBottomInset;
408 // While a user-input request is pending, the questionnaire owns the
409 // composer slot outright: expanded it is the full card, collapsed it is a
410 // composer-style bar in the same place (with its own stop control). The
411 // composer never mounts into the transition, which keeps the collapse and
412 // keyboard animations coherent. Collapse state is keyed by request id so a
413 // new request re-expands automatically.
414 const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
415 useState<ApprovalRequestId | null>(null);
416 const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
417 // The open /usage-limits panel for this thread, model and turn. Only the open
418 // moment is stored: the rows read live provider data, so a redeemed reset
419 // credit or refreshed probe shows through. Anything that spends quota closes
420 // it: a new turn from any source, or the agent resuming after an approval or
421 // answered question.
422 const [usageLimitsPanel, setUsageLimitsPanel] = useState<{
423 readonly key: string;
424 readonly threadKey: string;
425 readonly now: number;
426 } | null>(null);
427 // A pending approval or question is part of the key: once it is answered,
428 // from this client or any other, the agent resumes and spends quota.
429 const usageLimitsKey = [
430 selectedThreadKey,
431 props.selectedThread.modelSelection.instanceId,
432 props.selectedThread.latestTurn?.turnId ?? "",
433 props.activePendingApproval?.requestId ?? props.activePendingUserInput?.requestId ?? "",
434 ].join(":");
435 // Drop the snapshot as soon as the key changes so it cannot resurface stale.
436 if (usageLimitsPanel !== null && usageLimitsPanel.key !== usageLimitsKey) {
437 setUsageLimitsPanel(null);
438 }
439 const usageLimitsReport = useMemo(
440 () =>
441 usageLimitsPanel !== null && usageLimitsPanel.key === usageLimitsKey
442 ? collectProviderUsageLimits(
443 props.selectedThread.modelSelection.instanceId,
444 props.serverConfig?.providers ?? [],
445 props.serverConfig?.usageLimitSources ?? [],
446 usageLimitsPanel.now,
447 )
448 : null,
449 [
450 props.selectedThread.modelSelection.instanceId,
451 props.serverConfig,
452 usageLimitsKey,
453 usageLimitsPanel,
454 ],
455 );
456 const showUsageLimits = useCallback(
457 (report: UsageLimitsReport | null) =>
458 setUsageLimitsPanel(
459 report === null
460 ? null
461 : {
462 key: usageLimitsKey,
463 threadKey: selectedThreadKey,
464 now: Date.parse(report.createdAt),
465 },
466 ),
467 [selectedThreadKey, usageLimitsKey],
468 );
469 const dismissUsageLimits = useCallback(() => setUsageLimitsPanel(null), []);
470 // A send may resolve after navigating away, so only the originating
471 // thread's panel is cleared; a panel opened elsewhere in the meantime stays.
472 const clearUsageLimitsFor = useCallback(
473 (threadKey: string) =>
474 setUsageLimitsPanel((current) =>
475 current !== null && current.threadKey === threadKey ? null : current,
476 ),
477 [],
478 );
479 const userInputCollapsed =
480 activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
481 // The card's height RESERVES keyboard space at all times instead of
482 // tracking the keyboard: transforms (the sticky translation) apply
483 // same-frame on the UI thread while layout props lag a Yoga pass behind,
484 // so any height that follows the keyboard flashes the card over the nav
485 // header on the way up. With a constant height the keyboard transition is
486 // pure translation — frame-perfect by construction — and the resting card
487 // stays compact over the transcript. Before the first open the reserve is
488 // an estimate; once a real height is known the card corrects once,
489 // discretely.
490 const [lastKnownKeyboardHeight, setLastKnownKeyboardHeight] = useState(0);
491 useEffect(() => {
492 if (liveKeyboardHeight > 0 && liveKeyboardHeight !== lastKnownKeyboardHeight) {
493 setLastKnownKeyboardHeight(liveKeyboardHeight);
494 }
495 }, [lastKnownKeyboardHeight, liveKeyboardHeight]);
496 const pendingUserInputMaxHeight = derivePendingUserInputMaxHeight({
497 windowHeight,
498 keyboardHeight:
499 lastKnownKeyboardHeight > 0 ? lastKnownKeyboardHeight : ESTIMATED_KEYBOARD_HEIGHT,
500 navigationHeaderHeight,
501 // The questionnaire owns the composer slot, so only the composer's
502 // bottom inset still overlaps.
503 composerOverlapHeight: composerBottomInset,
504 });
505 const estimatedOverlayHeight = composerOverlapHeight;
506 // The overlay's measured height includes the home-indicator inset (the
507 // composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
508 // UIKit add the safe-area bottom to the content inset AGAIN — leaving a
509 // dead strip between the resting content and the composer. Report the
510 // overlay height minus the safe area; UIKit adds it back, and ThreadFeed
511 // hands LegendList the same delta via contentInsetEndStaticAdjustment so
512 // its end-scroll math matches the real resting position.
513 const nativeInsetOvercount =
514 props.usesAutomaticContentInsets === true && Platform.OS === "ios" ? insets.bottom : 0;
515 const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
516 listRef,
517 composerOverlayRef,
518 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
519 -nativeInsetOvercount,
520 Platform.OS === "ios" ? COMPOSER_TRANSITION_DURATION_MS : 0,
521 );
522 // The expanded questionnaire is an absolute overlay on iOS, so it never
523 // changes the measured overlay height (that constancy is what keeps the
524 // feed from snapping on collapse/expand). The toggle choreography runs on
525 // SHARED VALUES set directly in the tap handler — one JS hop, then the
526 // card's rise/sink and the feed's end-inset glide animate in lockstep on
527 // the UI thread, keyboard-style, instead of waiting on React mount +
528 // onLayout + state round trips. Coverage (how far the card extends above
529 // the bar) is measured straight into a shared value by the card's
530 // onLayout, with no re-render.
531 const userInputCardProgress = useSharedValue(1);
532 const userInputInsetProgress = useSharedValue(1);
533 const userInputCardCoverage = useSharedValue(0);
534 const floatingControlCoverage = useSharedValue(
535 showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0,
536 );
537 useEffect(() => {
538 floatingControlCoverage.value = withTiming(
539 showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0,
540 { duration: 180, reduceMotion: ReduceMotion.System },
541 );
542 }, [floatingControlCoverage, showFloatingStatus]);
543 // Android renders the expanded card in-flow (it cannot hit-test the iOS
544 // overlay outside the bar's bounds), so its measured overlay height already
545 // includes the card — the coverage extra is iOS-only.
546 const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null;
547 const combinedContentInsetEndAdjustment = useSharedValue(
548 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
549 );
550 useAnimatedReaction(
551 () =>
552 contentInsetEndAdjustment.value +
553 floatingControlCoverage.value +
554 (userInputCoverageApplies ? userInputInsetProgress.value * userInputCardCoverage.value : 0),
555 (value) => {
556 combinedContentInsetEndAdjustment.value = value;
557 },
558 [userInputCoverageApplies],
559 );
560 const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
561 const endFollowEnabledRef = useRef(true);
562 endFollowEnabledRef.current = endFollowEnabled;
563 const overlayRepinTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
564 const previousWorkingControlStateRef = useRef({
565 threadKey: selectedThreadKey,
566 visible: false,
567 });
568 // The list's own corrections for these inset changes drift on short
569 // content (and the error compounds across toggles), so deterministically
570 // re-pin the end once a toggle settles: a no-op when the resting position
571 // is already right, corrective when it is not. Follow state is re-checked
572 // inside the callback — the user may grab the list during the settle
573 // window, and yanking them back would override a live gesture.
574 const scheduleOverlayRepin = useCallback(
575 (delayMs: number) => {
576 if (overlayRepinTimerRef.current !== null) {
577 clearTimeout(overlayRepinTimerRef.current);
578 }
579 overlayRepinTimerRef.current = setTimeout(() => {
580 overlayRepinTimerRef.current = null;
581 if (!endFollowEnabledRef.current) {
582 return;
583 }
584 void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
585 freeze.set(false);
586 });
587 }, delayMs);
588 },
589 [freeze, scrollMessageToEnd],
590 );
591 useEffect(
592 () => () => {
593 if (overlayRepinTimerRef.current !== null) {
594 clearTimeout(overlayRepinTimerRef.current);
595 }
596 },
597 [],
598 );
599 useEffect(() => {
600 const previous = previousWorkingControlStateRef.current;
601 const threadChanged = previous.threadKey !== selectedThreadKey;
602 const visibilityChanged = previous.visible !== showFloatingStatus;
603 previousWorkingControlStateRef.current = {
604 threadKey: selectedThreadKey,
605 visible: showFloatingStatus,
606 };
607 if ((!threadChanged && !visibilityChanged) || (threadChanged && !showFloatingStatus)) {
608 return;
609 }
610 // LegendList applies the larger inset but does not re-anchor short
611 // followed conversations when this floating coverage changes after the
612 // initial load. Re-pin after the finite inset transition; the callback
613 // checks follow state again so a user who scrolled up stays put.
614 scheduleOverlayRepin(230);
615 }, [scheduleOverlayRepin, selectedThreadKey, showFloatingStatus]);
616 const handleToggleUserInputCollapsed = useCallback(() => {
617 if (activeUserInputRequestId === null) {
618 return;
619 }
620 if (userInputCollapsed) {
621 // Expanding: card and feed glide start NOW, on the UI thread.
622 userInputCardProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
623 userInputInsetProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
624 setCollapsedUserInputRequestId(null);
625 scheduleOverlayRepin(USER_INPUT_TOGGLE_DURATION_MS + 50);
626 } else {
627 // Collapsing hides the custom-answer inputs; release the keyboard with
628 // them instead of leaving it up over a dead responder.
629 Keyboard.dismiss();
630 userInputCardProgress.value = withTiming(0, USER_INPUT_TOGGLE_TIMING);
631 // Instant: the sinking card still covers the strip being revealed, and
632 // animating the inset downward is what drifted the short-content end
633 // anchor.
634 userInputInsetProgress.value = 0;
635 setCollapsedUserInputRequestId(activeUserInputRequestId);
636 scheduleOverlayRepin(60);
637 }
638 }, [
639 activeUserInputRequestId,
640 scheduleOverlayRepin,
641 userInputCardProgress,
642 userInputCollapsed,
643 userInputInsetProgress,
644 ]);
645 useEffect(() => {
646 // A new request always arrives expanded.
647 userInputCardProgress.value = 1;
648 userInputInsetProgress.value = 1;
649 }, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]);
650 const showContent = props.showContent ?? true;
651 const layoutVariant = props.layoutVariant ?? "compact";
652 const isSplitLayout = layoutVariant === "split";
653 const contentMaxWidth = isSplitLayout ? CHAT_CONTENT_MAX_WIDTH : undefined;
654 const workspaceContentWidth = useWorkspaceContentWidth();
655 const composerWidthStyle = useAnimatedStyle(() =>
656 isSplitLayout && workspaceContentWidth !== null
657 ? { width: workspaceContentWidth.value, right: undefined }
658 : { width: undefined, right: 0 },
659 );
660 const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
661 useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
662 const selectedProviderSkills = useMemo(() => {
663 const provider = props.serverConfig?.providers.find(
664 (candidate) => candidate.instanceId === selectedInstanceId,
665 );
666 return provider
667 ? resolveProviderSkillsForCwd(provider, props.threadCwd ?? props.projectWorkspaceRoot)
668 : [];
669 }, [props.projectWorkspaceRoot, props.serverConfig, props.threadCwd, selectedInstanceId]);
670​
671 useLayoutEffect(() => {
672 selectedThreadKeyRef.current = selectedThreadKey;
673 // A replaced or unmounted native editor may not emit a blur event.
674 setComposerFocused(false);
675 }, [selectedThreadKey, showContent]);
676​
677 useEffect(() => {
678 setAnchorMessageId(null);
679 setSubmittedMessageId(null);
680 lastScrolledSubmittedMessageIdRef.current = null;
681 setEndFollowEnabled(true);
682 freeze.set(false);
683 }, [freeze, selectedThreadKey]);
684​
685 useEffect(() => {
686 if (
687 submittedMessageId === null ||
688 anchorMessageId !== submittedMessageId ||
689 lastScrolledSubmittedMessageIdRef.current === submittedMessageId ||
690 contentPresentationKind !== "ready" ||
691 (!selectedThreadFeed.some(
692 (entry) => entry.type === "message" && entry.id === submittedMessageId,
693 ) &&
694 !props.queuedMessages.some((message) => message.messageId === submittedMessageId))
695 ) {
696 return;
697 }
698​
699 const targetThreadKey = selectedThreadKey;
700 const frame = requestAnimationFrame(() => {
701 if (selectedThreadKeyRef.current !== targetThreadKey) {
702 return;
703 }
704 lastScrolledSubmittedMessageIdRef.current = submittedMessageId;
705 // Wait for the keyboard dismissal (started by blur() on send) to finish
706 // before scrolling: scrollMessageToEnd freezes keyboard-driven inset
707 // updates while it runs, and a close event swallowed by that freeze
708 // leaves the keyboard padding permanently applied — overshooting the
709 // anchor and leaving a phantom bottom inset once the reply streams in.
710 void KeyboardController.dismiss()
711 .then(() => {
712 if (
713 selectedThreadKeyRef.current !== targetThreadKey ||
714 lastScrolledSubmittedMessageIdRef.current !== submittedMessageId
715 ) {
716 return;
717 }
718 return scrollMessageToEnd({ animated: true, closeKeyboard: false });
719 })
720 .catch(() => {
721 if (
722 selectedThreadKeyRef.current !== targetThreadKey ||
723 lastScrolledSubmittedMessageIdRef.current !== submittedMessageId
724 ) {
725 return;
726 }
727 lastScrolledSubmittedMessageIdRef.current = null;
728 freeze.set(false);
729 });
730 });
731 return () => cancelAnimationFrame(frame);
732 }, [
733 anchorMessageId,
734 submittedMessageId,
735 freeze,
736 contentPresentationKind,
737 props.queuedMessages,
738 selectedThreadFeed,
739 scrollMessageToEnd,
740 selectedThreadKey,
741 ]);
742​
743 const handleSendMessage = useCallback(async () => {
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();
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 anchorMessageId,
770 clearUsageLimitsFor,
771 props.onSendMessage,
772 props.selectedThread.latestTurn,
773 props.selectedThreadQueueCount,
774 selectedThreadFeed,
775 selectedThreadKey,
776 ]);
777​
778 const handleEditPendingMessage = useCallback(async (message: QueuedThreadMessage) => {
779 try {
780 if (
781 (await editPendingThreadMessage(message)) &&
782 selectedThreadKeyRef.current === scopedThreadKey(message.environmentId, message.threadId)
783 ) {
784 composerEditorRef.current?.focus();
785 }
786 } catch (error) {
787 Alert.alert(
788 "Could not edit message",
789 error instanceof Error ? error.message : "Please try again.",
790 );
791 }
792 }, []);
793​
794 const collapseComposer = useCallback(() => {
795 composerEditorRef.current?.blur();
796 }, []);
797​
798 const handleUseArtifactTemplate = useCallback(
799 (template: CodexArtifactTemplate) => {
800 const currentDraft = draftMessageRef.current;
801 const nextDraft = appendCodexArtifactTemplateUsePrompt(currentDraft, template);
802 if (nextDraft !== currentDraft) {
803 draftMessageRef.current = nextDraft;
804 props.onChangeDraftMessage(nextDraft);
805 }
806 requestAnimationFrame(() => {
807 composerEditorRef.current?.focus();
808 composerEditorRef.current?.setSelection({ start: nextDraft.length, end: nextDraft.length });
809 });
810 },
811 [props.onChangeDraftMessage],
812 );
813​
814 const handleScrollToEnd = useCallback(() => {
815 void Haptics.selectionAsync();
816 void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
817 freeze.set(false);
818 });
819 }, [freeze, scrollMessageToEnd]);
820​
821 const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled;
822 const { themeAppearance, materialYouStyleLayoutActive } = useAppearancePreferences();
823 const isDarkMode = themeAppearance === "dark";
824​
825 const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
826 feedTouchStartRef.current = {
827 pageX: event.nativeEvent.pageX,
828 pageY: event.nativeEvent.pageY,
829 };
830 }, []);
831​
832 const handleFeedTouchMove = useCallback((event: GestureResponderEvent) => {
833 const start = feedTouchStartRef.current;
834 if (!start) {
835 return;
836 }
837 const deltaX = event.nativeEvent.pageX - start.pageX;
838 const deltaY = event.nativeEvent.pageY - start.pageY;
839 if (Math.hypot(deltaX, deltaY) > 8) {
840 feedTouchStartRef.current = null;
841 }
842 }, []);
843​
844 const handleFeedTouchEnd = useCallback(() => {
845 if (feedTouchStartRef.current) {
846 collapseComposer();
847 }
848 feedTouchStartRef.current = null;
849 }, [collapseComposer]);
850​
851 const handleFeedTouchCancel = useCallback(() => {
852 feedTouchStartRef.current = null;
853 }, []);
854 const feedBlurTarget = useRef<View>(null);
855​
856 return (
857 <View className="flex-1">
858 {showContent ? (
859 <BlurTargetView
860 ref={feedBlurTarget}
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 materialYouStyleLayoutActive
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 queuedMessages={props.queuedMessages}
882 dispatchingMessageId={props.dispatchingMessageId}
883 onEditPendingMessage={handleEditPendingMessage}
884 contentPresentation={props.contentPresentation}
885 agentLabel={agentLabel}
886 latestTurn={props.selectedThread.latestTurn}
887 activeWorkStartedAt={props.activeWorkStartedAt}
888 listRef={listRef}
889 freeze={freeze}
890 anchorMessageId={anchorMessageId}
891 submittedMessageId={submittedMessageId}
892 contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
893 contentTopInset={0}
894 contentBottomInset={
895 estimatedOverlayHeight + (showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0)
896 }
897 contentMaxWidth={contentMaxWidth}
898 layoutVariant={layoutVariant}
899 usesAutomaticContentInsets={props.usesAutomaticContentInsets}
900 onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
901 onEndFollowEnabledChange={setEndFollowEnabled}
902 skills={selectedProviderSkills}
903 onUseArtifactTemplate={handleUseArtifactTemplate}
904 loadEarlier={props.loadEarlier ?? null}
905 />
906 </BlurTargetView>
907 ) : (
908 <View className="flex-1" />
909 )}
910​
911 {/* Floating composer — sticks to keyboard via KeyboardStickyView */}
912 {showContent ? (
913 <KeyboardStickyView
914 // iOS emits a native animated height target on both will-show and
915 // will-hide, so stay subscribed for the full transition. Android
916 // retains its background/resume stale-state quarantine.
917 enabled={Platform.OS === "ios" || (isKeyboardVisible && !keyboardStateSuspect)}
918 pointerEvents="box-none"
919 style={{ position: "absolute", bottom: 0, left: 0, right: 0, top: 0 }}
920 offset={{ closed: 0, opened: 0 }}
921 >
922 {/* The fixed sticky host gives this bottom-anchored child a stable
923 coordinate space. Its top and height can then animate together
924 instead of the auto-sized host jumping to Yoga's destination. */}
925 <Animated.View
926 layout={COMPOSER_LAYOUT_TRANSITION}
927 pointerEvents="box-none"
928 style={[{ position: "absolute", bottom: 0, left: 0, right: 0 }, composerWidthStyle]}
929 >
930 {/* No paddingTop here: the overlay's measured height becomes the
931 list's bottom inset, so any padding above the pill/composer
932 pushes the resting content floor up by the same amount. */}
933 <View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
934 <FloatingWorkingControl
935 colorScheme={isDarkMode ? "dark" : "light"}
936 status={floatingStatus}
937 showScrollToEnd={showScrollToEndButton}
938 onScrollToEnd={handleScrollToEnd}
939 />
940 <View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
941 {props.feedbackSubmissions.map((submission) => (
942 <ComposerFeedback
943 key={submission.id}
944 submission={submission}
945 onDismiss={() => props.onDismissFeedback(submission.id)}
946 />
947 ))}
948 {usageLimitsReport && activeUserInputRequestId === null ? (
949 <Animated.View
950 className="shrink-0 px-4 pb-3"
951 entering={FadeInDown.duration(220)}
952 exiting={FadeOut.duration(140)}
953 >
954 <ComposerUsageLimits
955 report={usageLimitsReport}
956 environmentId={props.environmentId}
957 onClose={dismissUsageLimits}
958 />
959 </Animated.View>
960 ) : null}
961 {props.creationState?.kind === "failed" ? (
962 <Animated.View
963 className="shrink-0 px-4"
964 style={{ paddingBottom: composerBottomInset }}
965 entering={FadeInDown.duration(220)}
966 exiting={FadeOut.duration(140)}
967 >
968 <ThreadCreationFailedCard
969 reason={props.creationState.reason}
970 onEditTask={props.creationState.onEditTask}
971 />
972 </Animated.View>
973 ) : null}
974 {props.activePendingApproval || props.activePendingUserInput ? (
975 <Animated.View
976 className="shrink-0 gap-3 px-4 pb-3"
977 // The questionnaire replaces the composer, so it must pad
978 // the home indicator the composer normally covers.
979 style={
980 activeUserInputRequestId !== null
981 ? { paddingBottom: composerBottomInset }
982 : undefined
983 }
984 entering={FadeInDown.duration(220)}
985 exiting={FadeOut.duration(140)}
986 >
987 {props.activePendingApproval ? (
988 <PendingApprovalCard
989 approval={props.activePendingApproval}
990 respondingApprovalId={props.respondingApprovalId}
991 onRespond={props.onRespondToApproval}
992 />
993 ) : null}
994 {props.activePendingUserInput ? (
995 <PendingUserInputCard
996 pendingUserInput={props.activePendingUserInput}
997 maxHeight={pendingUserInputMaxHeight}
998 collapsed={userInputCollapsed}
999 onToggleCollapsed={handleToggleUserInputCollapsed}
1000 onStopThread={props.onStopThread}
1001 cardProgress={userInputCardProgress}
1002 cardCoverage={userInputCardCoverage}
1003 onInputFocusChange={handleOwnedInputFocusChange}
1004 drafts={props.activePendingUserInputDrafts}
1005 answers={props.activePendingUserInputAnswers}
1006 respondingUserInputId={props.respondingUserInputId}
1007 onSelectOption={props.onSelectUserInputOption}
1008 onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
1009 onSubmit={props.onSubmitUserInput}
1010 onDismiss={props.onDismissUserInput}
1011 />
1012 ) : null}
1013 </Animated.View>
1014 ) : null}
1015 </View>
1016​
1017 {/* Hidden (not unmounted) while a user-input request owns the
1018 composer slot, so composer drafts and editor state survive.
1019 A rejected creation has no thread to send to; the failure card
1020 owns the slot instead. */}
1021 <View
1022 style={
1023 activeUserInputRequestId !== null || props.creationState?.kind === "failed"
1024 ? { display: "none" }
1025 : undefined
1028 <GlassBlurTargetContext value={feedBlurTarget}>
1029 <ThreadComposer
1030 editorRef={composerEditorRef}
1031 draftMessage={props.draftMessage}
1032 draftAttachments={props.draftAttachments}
1033 placeholder="Ask the repo agent, or run a command…"
1034 contentMaxWidth={contentMaxWidth}
1035 connectionState={props.connectionStateLabel}
1036 environmentLabel={props.environmentLabel}
1037 selectedThread={props.selectedThread}
1038 hasCompactableConversation={hasCompactableConversation && !props.isCompacting}
1039 serverConfig={props.serverConfig}
1040 queueCount={props.selectedThreadQueueCount}
1041 environmentId={props.environmentId}
1042 projectCwd={props.threadCwd ?? props.projectWorkspaceRoot}
1043 // Follow-ups typed during setup wait in the draft: queueing
1044 // them against a thread id the server may still reject
1045 // would strand them in the outbox.
1046 sendBlockedReason={
1047 props.creationState?.kind === "preparing" ? "Starting the task…" : null
1049 bottomInset={composerBottomInset}
1050 onChangeDraftMessage={props.onChangeDraftMessage}
1051 onPickDraftMedia={props.onPickDraftMedia}
1052 onPickDraftFiles={props.onPickDraftFiles}
1053 onNativePasteImages={props.onNativePasteImages}
1054 onNativePasteText={props.onNativePasteText}
1055 onRemoveDraftImage={props.onRemoveDraftImage}
1056 onStopThread={props.onStopThread}
1057 onSendMessage={handleSendMessage}
1058 onShowUsageLimits={showUsageLimits}
1059 onUpdateModelSelection={props.onUpdateThreadModelSelection}
1060 onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
1061 onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
1062 onExpandedChange={setComposerExpanded}
1063 onEditorFocusChange={handleComposerFocusChange}
1064 />
1065 </GlassBlurTargetContext>
1066 </View>
1067 </View>
1068 </Animated.View>
1069 </KeyboardStickyView>
1070 ) : null}
1071 </View>
1072 );
1073});