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

ThreadDetailScreen.tsx

1,116 lines46.5 KB

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