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

ThreadDetailScreen.tsx

840 lines35.2 KB

1import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
2import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
3import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
4import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
5import type { LegendListRef } from "@legendapp/list/react-native";
6import { HeaderHeightContext } from "@react-navigation/elements";
7import type {
8 EnvironmentId,
9 MessageId,
10 ModelSelection,
11 ProviderApprovalDecision,
12 ProviderInteractionMode,
13 RuntimeMode,
14 RuntimeRequestId,
15 ServerConfig as T3ServerConfig,
16 ThreadId,
17} from "@t3tools/contracts";
18import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";
19import * as Haptics from "expo-haptics";
20import {
21 memo,
22 useCallback,
23 useContext,
24 useEffect,
25 useLayoutEffect,
26 useMemo,
27 useRef,
28 useState,
29} from "react";
30import {
31 AppState,
32 Keyboard,
33 Platform,
34 useWindowDimensions,
35 View,
36 type GestureResponderEvent,
37} from "react-native";
38import {
39 KeyboardController,
40 KeyboardStickyView,
41 useKeyboardState,
42} from "react-native-keyboard-controller";
43import Animated, {
44 Easing,
45 FadeInDown,
46 FadeOut,
47 ReduceMotion,
48 useAnimatedReaction,
49 useSharedValue,
50 withTiming,
51} from "react-native-reanimated";
52import { useSafeAreaInsets } from "react-native-safe-area-context";
53​
54import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
55import type { ComposerEditorHandle } from "../../components/ComposerEditor";
56import type { StatusTone } from "../../components/StatusPill";
57import type { DraftComposerAttachment } from "../../lib/composerImages";
58import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
59import { scopedThreadKey } from "../../lib/scopedEntities";
60import { threadEnvironment } from "../../state/threads";
61import { useAtomCommand } from "../../state/use-atom-command";
62import type {
63 PendingApproval,
64 PendingUserInput,
65 PendingUserInputDraftAnswer,
66 ThreadFeedEntry,
67 ThreadFeedLatestRun,
68} from "../../lib/threadActivity";
69import { PendingApprovalCard } from "./PendingApprovalCard";
70import { PendingUserInputCard } from "./PendingUserInputCard";
71import {
72 FLOATING_WORKING_CONTROL_COVERAGE,
73 FloatingWorkingControl,
74} from "./floating-working-control";
75import {
76 derivePendingUserInputMaxHeight,
77 ESTIMATED_KEYBOARD_HEIGHT,
78 USER_INPUT_TOGGLE_DURATION_MS,
79} from "./pendingUserInputLayout";
80import {
81 COMPOSER_COLLAPSED_CHROME,
82 COMPOSER_EXPANDED_CHROME,
83 COMPOSER_LAYOUT_TRANSITION,
84 COMPOSER_TRANSITION_DURATION_MS,
85 ThreadComposer,
86} from "./ThreadComposer";
87import { ThreadFeed, type ThreadFeedHistoryControls } from "./ThreadFeed";
88import { ThreadRelationshipsBanner } from "./ThreadRelationshipsBanner";
89import { ThreadQueueControl } from "./ThreadQueueControl";
90import type { ThreadContentPresentation } from "./threadContentPresentation";
91​
92export interface ThreadDetailScreenProps {
93 readonly selectedThread: EnvironmentThreadShell;
94 readonly contentPresentation: ThreadContentPresentation;
95 readonly screenTone: StatusTone;
96 readonly connectionError: string | null;
97 readonly environmentLabel: string | null;
98 readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
99 readonly activityRun: ThreadFeedLatestRun | null;
100 readonly activeWorkStartedAt: string | null;
101 readonly activePendingApproval: PendingApproval | null;
102 readonly respondingApprovalId: RuntimeRequestId | null;
103 readonly activePendingUserInput: PendingUserInput | null;
104 readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
105 readonly activePendingUserInputAnswers: Record<string, string | ReadonlyArray<string>> | null;
106 readonly respondingUserInputId: RuntimeRequestId | null;
107 readonly draftMessage: string;
108 readonly draftAttachments: ReadonlyArray<DraftComposerAttachment>;
109 readonly connectionStateLabel: EnvironmentConnectionPhase;
110 /** Message sync status for the selected thread (drives the composer status pill). */
111 readonly threadSyncStatus?: EnvironmentThreadStatus;
112 /** Progressive history controls for oversized mobile thread opens. */
113 readonly historyControls?: ThreadFeedHistoryControls;
114 readonly activeThreadBusy: boolean;
115 readonly canStopThread: boolean;
116 readonly environmentId: EnvironmentId;
117 readonly projectWorkspaceRoot: string | null;
118 readonly threadCwd: string | null;
119 readonly selectedThreadQueueCount: number;
120 readonly serverConfig: T3ServerConfig | null;
121 readonly layoutVariant?: LayoutVariant;
122 readonly usesAutomaticContentInsets?: boolean;
123 readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
124 readonly onOpenConnectionEditor: () => void;
125 readonly onChangeDraftMessage: (value: string) => void;
126 readonly onPickDraftMedia: () => Promise<void>;
127 readonly onPickDraftFiles: () => Promise<void>;
128 readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
129 readonly onRemoveDraftImage: (imageId: string) => void;
130 readonly onStopThread: () => void;
131 readonly onSendMessage: () => Promise<MessageId | null>;
132 readonly onReconnectEnvironment: () => void;
133 readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
134 readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
135 readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
136 readonly onRespondToApproval: (
137 requestId: RuntimeRequestId,
138 decision: ProviderApprovalDecision,
139 ) => Promise<unknown>;
140 readonly onSelectUserInputOption: (
141 requestId: RuntimeRequestId,
142 question: ThreadUserInputQuestion,
143 label: string,
144 ) => void;
145 readonly onChangeUserInputCustomAnswer: (
146 requestId: RuntimeRequestId,
147 questionId: string,
148 customAnswer: string,
149 ) => void;
150 readonly onSubmitUserInput: () => Promise<unknown>;
151 readonly showContent?: boolean;
153​
154function latestStreamingAssistantMessage(
155 feed: ReadonlyArray<ThreadFeedEntry>,
156): { readonly id: string; readonly textLength: number } | null {
157 for (let index = feed.length - 1; index >= 0; index -= 1) {
158 const entry = feed[index];
159 if (entry?.type !== "message") {
160 continue;
161 }
162 if (entry.message.role !== "assistant" || !entry.message.streaming) {
163 continue;
164 }
165 return {
166 id: entry.message.id,
167 textLength: entry.message.text.length,
168 };
169 }
170​
171 return null;
173​
174function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedEntry>) {
175 const lastStreamingAssistantRef = useRef<{
176 readonly id: string;
177 readonly textLength: number;
178 } | null>(null);
179 const lastStreamHapticAtRef = useRef(0);
180 const hydratedRef = useRef(false);
181 const previousThreadIdRef = useRef(threadId);
182​
183 useEffect(() => {
184 if (previousThreadIdRef.current !== threadId) {
185 previousThreadIdRef.current = threadId;
186 hydratedRef.current = false;
187 }
188​
189 const latestStreamingMessage = latestStreamingAssistantMessage(feed);
190​
191 if (!hydratedRef.current) {
192 hydratedRef.current = true;
193 lastStreamingAssistantRef.current = latestStreamingMessage;
194 return;
195 }
196​
197 if (!latestStreamingMessage) {
198 lastStreamingAssistantRef.current = null;
199 return;
200 }
201​
202 const previousStreamingMessage = lastStreamingAssistantRef.current;
203 lastStreamingAssistantRef.current = latestStreamingMessage;
204​
205 const isNewStream = previousStreamingMessage?.id !== latestStreamingMessage.id;
206 const textGrew =
207 previousStreamingMessage?.id === latestStreamingMessage.id &&
208 latestStreamingMessage.textLength > previousStreamingMessage.textLength;
209​
210 if (!isNewStream && !textGrew) {
211 return;
212 }
213​
214 const now = Date.now();
215 if (!isNewStream && now - lastStreamHapticAtRef.current < 320) {
216 return;
217 }
218​
219 lastStreamHapticAtRef.current = now;
220 void Haptics.selectionAsync();
221 }, [threadId, feed]);
223​
224const USER_INPUT_TOGGLE_TIMING = {
225 duration: USER_INPUT_TOGGLE_DURATION_MS,
226 easing: Easing.out(Easing.cubic),
227};
228​
229export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
230 const insets = useSafeAreaInsets();
231 const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
232 const liveKeyboardHeight = useKeyboardState((state) => state.height);
233 // Android can swallow the IME hide callbacks when the app is backgrounded
234 // mid keyboard-hide (the reported repro: send — which blurs and starts the
235 // hide — then Home within a second). The keyboard library's height AND
236 // visibility then stay frozen open, so gating the sticky translation on
237 // visibility alone still strands the composer after resume. Quarantine the
238 // translation on every Android resume instead; any sign of a live keyboard
239 // stream — an owned input gaining focus, or any visibility/height movement —
240 // lifts it. A healthy resume sees no visual difference (the translation is
241 // already zero while the keyboard is closed).
242 const [keyboardStateSuspect, setKeyboardStateSuspect] = useState(false);
243 useEffect(() => {
244 if (Platform.OS !== "android") {
245 return;
246 }
247 const subscription = AppState.addEventListener("change", (state) => {
248 if (state === "active") {
249 setKeyboardStateSuspect(true);
250 }
251 });
252 return () => {
253 subscription.remove();
254 };
255 }, []);
256 useEffect(() => {
257 setKeyboardStateSuspect(false);
258 }, [isKeyboardVisible, liveKeyboardHeight]);
259 const handleOwnedInputFocusChange = useCallback((focused: boolean) => {
260 if (focused) {
261 setKeyboardStateSuspect(false);
262 }
263 }, []);
264 const windowHeight = useWindowDimensions().height;
265 const navigationHeaderHeight = useContext(HeaderHeightContext) || insets.top + 44;
266 const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
267 const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
268 const composerEditorRef = useRef<ComposerEditorHandle>(null);
269 const draftMessageRef = useRef(props.draftMessage);
270 draftMessageRef.current = props.draftMessage;
271 const composerOverlayRef = useRef<View>(null);
272 const listRef = useRef<LegendListRef>(null);
273 const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
274 const selectedThreadKeyRef = useRef(selectedThreadKey);
275 const lastScrolledAnchorMessageIdRef = useRef<MessageId | null>(null);
276 const [composerExpanded, setComposerExpanded] = useState(false);
277 const [composerFocused, setComposerFocused] = useState(false);
278 const handleComposerFocusChange = useCallback(
279 (focused: boolean) => {
280 setComposerFocused(focused);
281 handleOwnedInputFocusChange(focused);
282 },
283 [handleOwnedInputFocusChange],
284 );
285 const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
286 const [endFollowEnabled, setEndFollowEnabled] = useState(true);
287 // Android keys the safe-area padding on keyboard visibility (#5988): the
288 // back gesture closes the keyboard while the editor stays focused, and a
289 // focus-keyed inset would leave the toolbar under the gesture bar. iOS must
290 // NOT use visibility — it only flips on keyboardDidHide, after the hide
291 // animation, so the composer would ride down flush to the screen edge and
292 // then snap up into the inset. On iOS blur precedes the hide, so the
293 // focus-keyed inset is already in place while the composer rides down.
294 const composerBottomInset = (Platform.OS === "android" ? isKeyboardVisible : composerExpanded)
295 ? 0
296 : Math.max(insets.bottom, 12);
297 const contentPresentationKind = props.contentPresentation.kind;
298 // The raw sync status enters "synchronizing" on every full fetch, cached or
299 // not. Whether messages are already on screen decides the pill label: no
300 // data yet → "Loading messages", cached data reconciling → "Syncing".
301 const threadSyncPhase = (() => {
302 switch (props.threadSyncStatus) {
303 case "empty":
304 case "cached":
305 case "synchronizing":
306 if (contentPresentationKind === "ready") {
307 return "syncing" as const;
308 }
309 return contentPresentationKind === "loading" ? ("loading" as const) : null;
310 default:
311 return null;
312 }
313 })();
314 const showWorkingControl =
315 props.activeWorkStartedAt !== null &&
316 contentPresentationKind === "ready" &&
317 threadSyncPhase === null &&
318 props.connectionStateLabel === "connected" &&
319 props.activePendingApproval === null &&
320 props.activePendingUserInput === null;
321 const floatingWorkingStartedAt = showWorkingControl ? props.activeWorkStartedAt : null;
322 const selectedThreadFeed = props.selectedThreadFeed;
323 const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
324 const composerOverlapHeight = composerChrome + composerBottomInset;
325 // While a user-input request is pending, the questionnaire owns the
326 // composer slot outright: expanded it is the full card, collapsed it is a
327 // composer-style bar in the same place (with its own stop control). The
328 // composer never mounts into the transition, which keeps the collapse and
329 // keyboard animations coherent. Collapse state is keyed by request id so a
330 // new request re-expands automatically.
331 const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
332 useState<RuntimeRequestId | null>(null);
333 const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
334 const userInputCollapsed =
335 activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
336 // The card's height RESERVES keyboard space at all times instead of
337 // tracking the keyboard: transforms (the sticky translation) apply
338 // same-frame on the UI thread while layout props lag a Yoga pass behind,
339 // so any height that follows the keyboard flashes the card over the nav
340 // header on the way up. With a constant height the keyboard transition is
341 // pure translation — frame-perfect by construction — and the resting card
342 // stays compact over the transcript. Before the first open the reserve is
343 // an estimate; once a real height is known the card corrects once,
344 // discretely.
345 const [lastKnownKeyboardHeight, setLastKnownKeyboardHeight] = useState(0);
346 useEffect(() => {
347 if (liveKeyboardHeight > 0 && liveKeyboardHeight !== lastKnownKeyboardHeight) {
348 setLastKnownKeyboardHeight(liveKeyboardHeight);
349 }
350 }, [lastKnownKeyboardHeight, liveKeyboardHeight]);
351 const pendingUserInputMaxHeight = derivePendingUserInputMaxHeight({
352 windowHeight,
353 keyboardHeight:
354 lastKnownKeyboardHeight > 0 ? lastKnownKeyboardHeight : ESTIMATED_KEYBOARD_HEIGHT,
355 navigationHeaderHeight,
356 // The questionnaire owns the composer slot, so only the composer's
357 // bottom inset still overlaps.
358 composerOverlapHeight: composerBottomInset,
359 });
360 const estimatedOverlayHeight = composerOverlapHeight;
361 // The overlay's measured height includes the home-indicator inset (the
362 // composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
363 // UIKit add the safe-area bottom to the content inset AGAIN — leaving a
364 // dead strip between the resting content and the composer. Report the
365 // overlay height minus the safe area; UIKit adds it back, and ThreadFeed
366 // hands LegendList the same delta via contentInsetEndStaticAdjustment so
367 // its end-scroll math matches the real resting position.
368 const nativeInsetOvercount =
369 props.usesAutomaticContentInsets === true && Platform.OS === "ios" ? insets.bottom : 0;
370 const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
371 listRef,
372 composerOverlayRef,
373 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
374 -nativeInsetOvercount,
375 Platform.OS === "ios" ? COMPOSER_TRANSITION_DURATION_MS : 0,
376 );
377 // The expanded questionnaire is an absolute overlay on iOS, so it never
378 // changes the measured overlay height (that constancy is what keeps the
379 // feed from snapping on collapse/expand). The toggle choreography runs on
380 // SHARED VALUES set directly in the tap handler — one JS hop, then the
381 // card's rise/sink and the feed's end-inset glide animate in lockstep on
382 // the UI thread, keyboard-style, instead of waiting on React mount +
383 // onLayout + state round trips. Coverage (how far the card extends above
384 // the bar) is measured straight into a shared value by the card's
385 // onLayout, with no re-render.
386 const userInputCardProgress = useSharedValue(1);
387 const userInputInsetProgress = useSharedValue(1);
388 const userInputCardCoverage = useSharedValue(0);
389 const floatingControlCoverage = useSharedValue(
390 showWorkingControl ? FLOATING_WORKING_CONTROL_COVERAGE : 0,
391 );
392 useEffect(() => {
393 floatingControlCoverage.value = withTiming(
394 showWorkingControl ? FLOATING_WORKING_CONTROL_COVERAGE : 0,
395 { duration: 180, reduceMotion: ReduceMotion.System },
396 );
397 }, [floatingControlCoverage, showWorkingControl]);
398 // Android renders the expanded card in-flow (it cannot hit-test the iOS
399 // overlay outside the bar's bounds), so its measured overlay height already
400 // includes the card — the coverage extra is iOS-only.
401 const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null;
402 const combinedContentInsetEndAdjustment = useSharedValue(
403 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
404 );
405 useAnimatedReaction(
406 () =>
407 contentInsetEndAdjustment.value +
408 floatingControlCoverage.value +
409 (userInputCoverageApplies ? userInputInsetProgress.value * userInputCardCoverage.value : 0),
410 (value) => {
411 combinedContentInsetEndAdjustment.value = value;
412 },
413 [userInputCoverageApplies],
414 );
415 const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
416 const endFollowEnabledRef = useRef(true);
417 endFollowEnabledRef.current = endFollowEnabled;
418 const overlayRepinTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
419 const previousWorkingControlStateRef = useRef({
420 threadKey: selectedThreadKey,
421 visible: false,
422 });
423 // The list's own corrections for these inset changes drift on short
424 // content (and the error compounds across toggles), so deterministically
425 // re-pin the end once a toggle settles: a no-op when the resting position
426 // is already right, corrective when it is not. Follow state is re-checked
427 // inside the callback — the user may grab the list during the settle
428 // window, and yanking them back would override a live gesture.
429 const scheduleOverlayRepin = useCallback(
430 (delayMs: number) => {
431 if (overlayRepinTimerRef.current !== null) {
432 clearTimeout(overlayRepinTimerRef.current);
433 }
434 overlayRepinTimerRef.current = setTimeout(() => {
435 overlayRepinTimerRef.current = null;
436 if (!endFollowEnabledRef.current) {
437 return;
438 }
439 void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
440 freeze.set(false);
441 });
442 }, delayMs);
443 },
444 [freeze, scrollMessageToEnd],
445 );
446 useEffect(
447 () => () => {
448 if (overlayRepinTimerRef.current !== null) {
449 clearTimeout(overlayRepinTimerRef.current);
450 }
451 },
452 [],
453 );
454 useEffect(() => {
455 const previous = previousWorkingControlStateRef.current;
456 const threadChanged = previous.threadKey !== selectedThreadKey;
457 const visibilityChanged = previous.visible !== showWorkingControl;
458 previousWorkingControlStateRef.current = {
459 threadKey: selectedThreadKey,
460 visible: showWorkingControl,
461 };
462 if ((!threadChanged && !visibilityChanged) || (threadChanged && !showWorkingControl)) {
463 return;
464 }
465 // LegendList applies the larger inset but does not re-anchor short
466 // followed conversations when this floating coverage changes after the
467 // initial load. Re-pin after the finite inset transition; the callback
468 // checks follow state again so a user who scrolled up stays put.
469 scheduleOverlayRepin(230);
470 }, [scheduleOverlayRepin, selectedThreadKey, showWorkingControl]);
471 const handleToggleUserInputCollapsed = useCallback(() => {
472 if (activeUserInputRequestId === null) {
473 return;
474 }
475 if (userInputCollapsed) {
476 // Expanding: card and feed glide start NOW, on the UI thread.
477 userInputCardProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
478 userInputInsetProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
479 setCollapsedUserInputRequestId(null);
480 scheduleOverlayRepin(USER_INPUT_TOGGLE_DURATION_MS + 50);
481 } else {
482 // Collapsing hides the custom-answer inputs; release the keyboard with
483 // them instead of leaving it up over a dead responder.
484 Keyboard.dismiss();
485 userInputCardProgress.value = withTiming(0, USER_INPUT_TOGGLE_TIMING);
486 // Instant: the sinking card still covers the strip being revealed, and
487 // animating the inset downward is what drifted the short-content end
488 // anchor.
489 userInputInsetProgress.value = 0;
490 setCollapsedUserInputRequestId(activeUserInputRequestId);
491 scheduleOverlayRepin(60);
492 }
493 }, [
494 activeUserInputRequestId,
495 scheduleOverlayRepin,
496 userInputCardProgress,
497 userInputCollapsed,
498 userInputInsetProgress,
499 ]);
500 useEffect(() => {
501 // A new request always arrives expanded.
502 userInputCardProgress.value = 1;
503 userInputInsetProgress.value = 1;
504 }, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]);
505 const showContent = props.showContent ?? true;
506 const layoutVariant = props.layoutVariant ?? "compact";
507 const isSplitLayout = layoutVariant === "split";
508 const contentMaxWidth = isSplitLayout ? CHAT_CONTENT_MAX_WIDTH : undefined;
509 const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
510 useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
511 const selectedProviderSkills = useMemo(
512 () =>
513 props.serverConfig?.providers.find((provider) => provider.instanceId === selectedInstanceId)
514 ?.skills ?? [],
515 [props.serverConfig, selectedInstanceId],
516 );
517​
518 useLayoutEffect(() => {
519 selectedThreadKeyRef.current = selectedThreadKey;
520 // A replaced or unmounted native editor may not emit a blur event.
521 setComposerFocused(false);
522 }, [selectedThreadKey, showContent]);
523​
524 const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
525 const lastDispatchedVisitRef = useRef<string | null>(null);
526 const selectedThreadId = props.selectedThread.id;
527 const selectedThreadUpdatedAt = props.selectedThread.updatedAt;
528 const selectedThreadLastVisitedAt = props.selectedThread.lastVisitedAt;
529 useEffect(() => {
530 // Records the server-side visited watermark while the thread is on
531 // screen (mirror of web ChatView), so the "Done" marker clears on every
532 // device. Field absent → the server predates visited tracking.
533 if (selectedThreadLastVisitedAt === undefined) return;
534 const threadUpdatedAtMs = Date.parse(selectedThreadUpdatedAt);
535 if (Number.isNaN(threadUpdatedAtMs)) return;
536 const lastVisitedAtMs = selectedThreadLastVisitedAt
537 ? Date.parse(selectedThreadLastVisitedAt)
538 : NaN;
539 if (!Number.isNaN(lastVisitedAtMs) && lastVisitedAtMs >= threadUpdatedAtMs) return;
540 // Dedupe per watermark — the effect re-runs before the command echo lands.
541 const dispatchKey = `${selectedThreadKey}:${selectedThreadUpdatedAt}`;
542 if (lastDispatchedVisitRef.current === dispatchKey) return;
543 lastDispatchedVisitRef.current = dispatchKey;
544 void visitThread({
545 environmentId: props.environmentId,
546 input: { threadId: selectedThreadId, visitedAt: selectedThreadUpdatedAt },
547 });
548 }, [
549 props.environmentId,
550 selectedThreadId,
551 selectedThreadKey,
552 selectedThreadLastVisitedAt,
553 selectedThreadUpdatedAt,
554 visitThread,
555 ]);
556​
557 useEffect(() => {
558 setAnchorMessageId(null);
559 lastScrolledAnchorMessageIdRef.current = null;
560 setEndFollowEnabled(true);
561 freeze.set(false);
562 }, [freeze, selectedThreadKey]);
563​
564 useEffect(() => {
565 if (
566 anchorMessageId === null ||
567 lastScrolledAnchorMessageIdRef.current === anchorMessageId ||
568 contentPresentationKind !== "ready" ||
569 !selectedThreadFeed.some((entry) => entry.type === "message" && entry.id === anchorMessageId)
570 ) {
571 return;
572 }
573​
574 const targetThreadKey = selectedThreadKey;
575 const frame = requestAnimationFrame(() => {
576 if (selectedThreadKeyRef.current !== targetThreadKey) {
577 return;
578 }
579 lastScrolledAnchorMessageIdRef.current = anchorMessageId;
580 // Wait for the keyboard dismissal (started by blur() on send) to finish
581 // before scrolling: scrollMessageToEnd freezes keyboard-driven inset
582 // updates while it runs, and a close event swallowed by that freeze
583 // leaves the keyboard padding permanently applied — overshooting the
584 // anchor and leaving a phantom bottom inset once the reply streams in.
585 void KeyboardController.dismiss()
586 .then(() => {
587 if (
588 selectedThreadKeyRef.current !== targetThreadKey ||
589 lastScrolledAnchorMessageIdRef.current !== anchorMessageId
590 ) {
591 return;
592 }
593 return scrollMessageToEnd({ animated: true, closeKeyboard: false });
594 })
595 .catch(() => {
596 if (
597 selectedThreadKeyRef.current !== targetThreadKey ||
598 lastScrolledAnchorMessageIdRef.current !== anchorMessageId
599 ) {
600 return;
601 }
602 lastScrolledAnchorMessageIdRef.current = null;
603 freeze.set(false);
604 });
605 });
606 return () => cancelAnimationFrame(frame);
607 }, [
608 anchorMessageId,
609 freeze,
610 contentPresentationKind,
611 selectedThreadFeed,
612 scrollMessageToEnd,
613 selectedThreadKey,
614 ]);
615​
616 const handleSendMessage = useCallback(async () => {
617 const targetThreadKey = selectedThreadKey;
618 const messageId = await props.onSendMessage();
619 if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
620 return messageId;
621 }
622​
623 setAnchorMessageId(messageId);
624 composerEditorRef.current?.blur();
625 return messageId;
626 }, [props.onSendMessage, selectedThreadKey]);
627​
628 const collapseComposer = useCallback(() => {
629 composerEditorRef.current?.blur();
630 }, []);
631​
632 const handleScrollToEnd = useCallback(() => {
633 void Haptics.selectionAsync();
634 void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
635 freeze.set(false);
636 });
637 }, [freeze, scrollMessageToEnd]);
638​
639 const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled;
640 const { themeAppearance } = useAppearancePreferences();
641 const isDarkMode = themeAppearance === "dark";
642​
643 const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
644 feedTouchStartRef.current = {
645 pageX: event.nativeEvent.pageX,
646 pageY: event.nativeEvent.pageY,
647 };
648 }, []);
649​
650 const handleFeedTouchMove = useCallback((event: GestureResponderEvent) => {
651 const start = feedTouchStartRef.current;
652 if (!start) {
653 return;
654 }
655 const deltaX = event.nativeEvent.pageX - start.pageX;
656 const deltaY = event.nativeEvent.pageY - start.pageY;
657 if (Math.hypot(deltaX, deltaY) > 8) {
658 feedTouchStartRef.current = null;
659 }
660 }, []);
661​
662 const handleFeedTouchEnd = useCallback(() => {
663 if (feedTouchStartRef.current) {
664 collapseComposer();
665 }
666 feedTouchStartRef.current = null;
667 }, [collapseComposer]);
668​
669 const handleFeedTouchCancel = useCallback(() => {
670 feedTouchStartRef.current = null;
671 }, []);
672​
673 return (
674 <View className="flex-1">
675 {showContent ? (
676 <View
677 className="flex-1"
678 onTouchStart={handleFeedTouchStart}
679 onTouchMove={handleFeedTouchMove}
680 onTouchEnd={handleFeedTouchEnd}
681 onTouchCancel={handleFeedTouchCancel}
682 >
683 <ThreadFeed
684 key={props.selectedThread.id}
685 environmentId={props.environmentId}
686 threadId={props.selectedThread.id}
687 workspaceRoot={props.threadCwd}
688 feed={props.selectedThreadFeed}
689 contentPresentation={props.contentPresentation}
690 agentLabel={agentLabel}
691 threadTitle={props.selectedThread.title}
692 latestRun={props.activityRun}
693 activeWorkStartedAt={props.activeWorkStartedAt}
694 listRef={listRef}
695 freeze={freeze}
696 anchorMessageId={anchorMessageId}
697 contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
698 contentTopInset={0}
699 contentBottomInset={
700 estimatedOverlayHeight + (showWorkingControl ? FLOATING_WORKING_CONTROL_COVERAGE : 0)
701 }
702 contentMaxWidth={contentMaxWidth}
703 historyControls={props.historyControls}
704 topAccessory={
705 <ThreadRelationshipsBanner
706 environmentId={props.environmentId}
707 threadId={props.selectedThread.id}
708 />
709 }
710 layoutVariant={layoutVariant}
711 usesAutomaticContentInsets={props.usesAutomaticContentInsets}
712 onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
713 onEndFollowEnabledChange={setEndFollowEnabled}
714 skills={selectedProviderSkills}
715 />
716 </View>
717 ) : (
718 <View className="flex-1" />
719 )}
720​
721 {/* Floating composer — sticks to keyboard via KeyboardStickyView */}
722 {showContent ? (
723 <KeyboardStickyView
724 // iOS emits a native animated height target on both will-show and
725 // will-hide, so stay subscribed for the full transition. Android
726 // retains its background/resume stale-state quarantine.
727 enabled={Platform.OS === "ios" || (isKeyboardVisible && !keyboardStateSuspect)}
728 pointerEvents="box-none"
729 style={{ position: "absolute", bottom: 0, left: 0, right: 0, top: 0 }}
730 offset={{ closed: 0, opened: 0 }}
731 >
732 {/* The fixed sticky host gives this bottom-anchored child a stable
733 coordinate space. Its top and height can then animate together
734 instead of the auto-sized host jumping to Yoga's destination. */}
735 <Animated.View
736 layout={COMPOSER_LAYOUT_TRANSITION}
737 pointerEvents="box-none"
738 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
739 >
740 {/* No paddingTop here: the overlay's measured height becomes the
741 list's bottom inset, so any padding above the pill/composer
742 pushes the resting content floor up by the same amount. */}
743 <View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
744 <FloatingWorkingControl
745 colorScheme={isDarkMode ? "dark" : "light"}
746 startedAt={floatingWorkingStartedAt}
747 showScrollToEnd={showScrollToEndButton}
748 onScrollToEnd={handleScrollToEnd}
749 />
750 <View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
751 <ThreadQueueControl
752 environmentId={props.environmentId}
753 threadId={props.selectedThread.id}
754 />
755​
756 {props.activePendingApproval || props.activePendingUserInput ? (
757 <Animated.View
758 className="shrink-0 gap-3 px-4 pb-3"
759 // The questionnaire replaces the composer, so it must pad
760 // the home indicator the composer normally covers.
761 style={
762 activeUserInputRequestId !== null
763 ? { paddingBottom: composerBottomInset }
764 : undefined
765 }
766 entering={FadeInDown.duration(220)}
767 exiting={FadeOut.duration(140)}
768 >
769 {props.activePendingApproval ? (
770 <PendingApprovalCard
771 approval={props.activePendingApproval}
772 respondingApprovalId={props.respondingApprovalId}
773 onRespond={props.onRespondToApproval}
774 />
775 ) : null}
776 {props.activePendingUserInput ? (
777 <PendingUserInputCard
778 pendingUserInput={props.activePendingUserInput}
779 maxHeight={pendingUserInputMaxHeight}
780 collapsed={userInputCollapsed}
781 onToggleCollapsed={handleToggleUserInputCollapsed}
782 onStopThread={props.onStopThread}
783 cardProgress={userInputCardProgress}
784 cardCoverage={userInputCardCoverage}
785 onInputFocusChange={handleOwnedInputFocusChange}
786 drafts={props.activePendingUserInputDrafts}
787 answers={props.activePendingUserInputAnswers}
788 respondingUserInputId={props.respondingUserInputId}
789 onSelectOption={props.onSelectUserInputOption}
790 onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
791 onSubmit={props.onSubmitUserInput}
792 />
793 ) : null}
794 </Animated.View>
795 ) : null}
796 </View>
797​
798 {/* Hidden (not unmounted) while a user-input request owns the
799 composer slot, so composer drafts and editor state survive. */}
800 <View style={activeUserInputRequestId !== null ? { display: "none" } : undefined}>
801 <ThreadComposer
802 editorRef={composerEditorRef}
803 draftMessage={props.draftMessage}
804 draftAttachments={props.draftAttachments}
805 placeholder="Ask the repo agent, or run a command…"
806 contentMaxWidth={contentMaxWidth}
807 connectionState={props.connectionStateLabel}
808 connectionError={props.connectionError}
809 environmentLabel={props.environmentLabel}
810 threadSyncPhase={threadSyncPhase}
811 selectedThread={props.selectedThread}
812 serverConfig={props.serverConfig}
813 queueCount={props.selectedThreadQueueCount}
814 activeThreadBusy={props.activeThreadBusy}
815 canStopThread={props.canStopThread}
816 environmentId={props.environmentId}
817 projectCwd={props.projectWorkspaceRoot}
818 bottomInset={composerBottomInset}
819 onChangeDraftMessage={props.onChangeDraftMessage}
820 onPickDraftMedia={props.onPickDraftMedia}
821 onPickDraftFiles={props.onPickDraftFiles}
822 onNativePasteImages={props.onNativePasteImages}
823 onRemoveDraftImage={props.onRemoveDraftImage}
824 onStopThread={props.onStopThread}
825 onSendMessage={handleSendMessage}
826 onReconnectEnvironment={props.onReconnectEnvironment}
827 onUpdateModelSelection={props.onUpdateThreadModelSelection}
828 onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
829 onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
830 onExpandedChange={setComposerExpanded}
831 onEditorFocusChange={handleOwnedInputFocusChange}
832 />
833 </View>
834 </View>
835 </Animated.View>
836 </KeyboardStickyView>
837 ) : null}
838 </View>
839 );
840});