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

ThreadDetailScreen.tsx

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