Open History to see the last commit
1import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
2import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
3import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
4import type { LegendListRef } from "@legendapp/list/react-native";
5import type {
6 ApprovalRequestId,
7 EnvironmentId,
8 MessageId,
9 ModelSelection,
10 OrchestrationThreadShell,
11 ProviderApprovalDecision,
12 ProviderInteractionMode,
13 RuntimeMode,
14 ServerConfig as T3ServerConfig,
15 ThreadId,
16} from "@t3tools/contracts";
17import * as Haptics from "expo-haptics";
18import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
19import { Platform, View, type GestureResponderEvent } from "react-native";
20import { KeyboardController, KeyboardStickyView } from "react-native-keyboard-controller";
21import Animated, { FadeInDown, FadeOut } from "react-native-reanimated";
22import { useSafeAreaInsets } from "react-native-safe-area-context";
23
24import { ControlPill } from "../../components/ControlPill";
25import type { ComposerEditorHandle } from "../../components/ComposerEditor";
26import type { StatusTone } from "../../components/StatusPill";
27import type { DraftComposerImageAttachment } from "../../lib/composerImages";
28import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
29import { scopedThreadKey } from "../../lib/scopedEntities";
30import type {
31 PendingApproval,
32 PendingUserInput,
33 PendingUserInputDraftAnswer,
34 ThreadFeedEntry,
35} from "../../lib/threadActivity";
36import { PendingApprovalCard } from "./PendingApprovalCard";
37import { PendingUserInputCard } from "./PendingUserInputCard";
38import {
39 COMPOSER_COLLAPSED_CHROME,
40 COMPOSER_EXPANDED_CHROME,
41 ThreadComposer,
42} from "./ThreadComposer";
43import { ThreadFeed } from "./ThreadFeed";
44import type { ThreadContentPresentation } from "./threadContentPresentation";
45
46export interface ThreadDetailScreenProps {
47 readonly selectedThread: OrchestrationThreadShell;
48 readonly contentPresentation: ThreadContentPresentation;
49 readonly screenTone: StatusTone;
50 readonly connectionError: string | null;
51 readonly environmentLabel: string | null;
52 readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
53 readonly activeWorkStartedAt: string | null;
54 readonly activePendingApproval: PendingApproval | null;
55 readonly respondingApprovalId: ApprovalRequestId | null;
56 readonly activePendingUserInput: PendingUserInput | null;
57 readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
58 readonly activePendingUserInputAnswers: Record<string, string> | null;
59 readonly respondingUserInputId: ApprovalRequestId | null;
60 readonly draftMessage: string;
61 readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
62 readonly connectionStateLabel: EnvironmentConnectionPhase;
63 /** Message sync status for the selected thread (drives the composer status pill). */
64 readonly threadSyncStatus?: EnvironmentThreadStatus;
65 /** Non-null when older turns exist beyond the loaded window. */
66 readonly loadEarlier?: { readonly loading: boolean; readonly onLoadEarlier: () => void } | null;
67 readonly activeThreadBusy: boolean;
68 readonly environmentId: EnvironmentId;
69 readonly projectWorkspaceRoot: string | null;
70 readonly threadCwd: string | null;
71 readonly selectedThreadQueueCount: number;
72 readonly serverConfig: T3ServerConfig | null;
73 readonly layoutVariant?: LayoutVariant;
74 readonly usesAutomaticContentInsets?: boolean;
75 readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
76 readonly onOpenConnectionEditor: () => void;
77 readonly onChangeDraftMessage: (value: string) => void;
78 readonly onPickDraftImages: () => Promise<void>;
79 readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
80 readonly onRemoveDraftImage: (imageId: string) => void;
81 readonly onStopThread: () => void;
82 readonly onSendMessage: () => Promise<MessageId | null>;
83 readonly onReconnectEnvironment: () => void;
84 readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
85 readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
86 readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
87 readonly onRespondToApproval: (
88 requestId: ApprovalRequestId,
89 decision: ProviderApprovalDecision,
90 ) => Promise<unknown>;
91 readonly onSelectUserInputOption: (
92 requestId: ApprovalRequestId,
93 questionId: string,
94 label: string,
95 ) => void;
96 readonly onChangeUserInputCustomAnswer: (
97 requestId: ApprovalRequestId,
98 questionId: string,
99 customAnswer: string,
100 ) => void;
101 readonly onSubmitUserInput: () => Promise<unknown>;
102 readonly showContent?: boolean;
103}
104
105function latestStreamingAssistantMessage(
106 feed: ReadonlyArray<ThreadFeedEntry>,
107): { readonly id: string; readonly textLength: number } | null {
108 for (let index = feed.length - 1; index >= 0; index -= 1) {
109 const entry = feed[index];
110 if (entry?.type !== "message") {
111 continue;
112 }
113 if (entry.message.role !== "assistant" || !entry.message.streaming) {
114 continue;
115 }
116 return {
117 id: entry.message.id,
118 textLength: entry.message.text.length,
119 };
120 }
121
122 return null;
123}
124
125function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedEntry>) {
126 const lastStreamingAssistantRef = useRef<{
127 readonly id: string;
128 readonly textLength: number;
129 } | null>(null);
130 const lastStreamHapticAtRef = useRef(0);
131 const hydratedRef = useRef(false);
132 const previousThreadIdRef = useRef(threadId);
133
134 useEffect(() => {
135 if (previousThreadIdRef.current !== threadId) {
136 previousThreadIdRef.current = threadId;
137 hydratedRef.current = false;
138 }
139
140 const latestStreamingMessage = latestStreamingAssistantMessage(feed);
141
142 if (!hydratedRef.current) {
143 hydratedRef.current = true;
144 lastStreamingAssistantRef.current = latestStreamingMessage;
145 return;
146 }
147
148 if (!latestStreamingMessage) {
149 lastStreamingAssistantRef.current = null;
150 return;
151 }
152
153 const previousStreamingMessage = lastStreamingAssistantRef.current;
154 lastStreamingAssistantRef.current = latestStreamingMessage;
155
156 const isNewStream = previousStreamingMessage?.id !== latestStreamingMessage.id;
157 const textGrew =
158 previousStreamingMessage?.id === latestStreamingMessage.id &&
159 latestStreamingMessage.textLength > previousStreamingMessage.textLength;
160
161 if (!isNewStream && !textGrew) {
162 return;
163 }
164
165 const now = Date.now();
166 if (!isNewStream && now - lastStreamHapticAtRef.current < 320) {
167 return;
168 }
169
170 lastStreamHapticAtRef.current = now;
171 void Haptics.selectionAsync();
172 }, [threadId, feed]);
173}
174
175export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
176 const insets = useSafeAreaInsets();
177 const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
178 const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
179 const composerEditorRef = useRef<ComposerEditorHandle>(null);
180 const composerOverlayRef = useRef<View>(null);
181 const listRef = useRef<LegendListRef>(null);
182 const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
183 const selectedThreadKeyRef = useRef(selectedThreadKey);
184 const lastScrolledAnchorMessageIdRef = useRef<MessageId | null>(null);
185 const [composerExpanded, setComposerExpanded] = useState(false);
186 const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
187 const [endFollowEnabled, setEndFollowEnabled] = useState(true);
188 const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
189 const contentPresentationKind = props.contentPresentation.kind;
190 // The raw sync status enters "synchronizing" on every full fetch, cached or
191 // not. Whether messages are already on screen decides the pill label: no
192 // data yet → "Loading messages", cached data reconciling → "Syncing".
193 const threadSyncPhase = (() => {
194 switch (props.threadSyncStatus) {
195 case "empty":
196 case "cached":
197 case "synchronizing":
198 if (contentPresentationKind === "ready") {
199 return "syncing" as const;
200 }
201 return contentPresentationKind === "loading" ? ("loading" as const) : null;
202 default:
203 return null;
204 }
205 })();
206 const selectedThreadFeed = props.selectedThreadFeed;
207 const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
208 const composerOverlapHeight = composerChrome + composerBottomInset;
209 const estimatedOverlayHeight = composerOverlapHeight;
210 // The overlay's measured height includes the home-indicator inset (the
211 // composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
212 // UIKit add the safe-area bottom to the content inset AGAIN — leaving a
213 // dead strip between the resting content and the composer. Report the
214 // overlay height minus the safe area; UIKit adds it back, and ThreadFeed
215 // hands LegendList the same delta via contentInsetEndStaticAdjustment so
216 // its end-scroll math matches the real resting position.
217 const nativeInsetOvercount =
218 props.usesAutomaticContentInsets === true && Platform.OS === "ios" ? insets.bottom : 0;
219 const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
220 listRef,
221 composerOverlayRef,
222 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
223 -nativeInsetOvercount,
224 );
225 const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
226 const showContent = props.showContent ?? true;
227 const layoutVariant = props.layoutVariant ?? "compact";
228 const isSplitLayout = layoutVariant === "split";
229 const contentMaxWidth = isSplitLayout ? CHAT_CONTENT_MAX_WIDTH : undefined;
230 const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
231 useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
232 const selectedProviderSkills = useMemo(
233 () =>
234 props.serverConfig?.providers.find((provider) => provider.instanceId === selectedInstanceId)
235 ?.skills ?? [],
236 [props.serverConfig, selectedInstanceId],
237 );
238
239 useLayoutEffect(() => {
240 selectedThreadKeyRef.current = selectedThreadKey;
241 }, [selectedThreadKey]);
242
243 useEffect(() => {
244 setAnchorMessageId(null);
245 lastScrolledAnchorMessageIdRef.current = null;
246 setEndFollowEnabled(true);
247 freeze.set(false);
248 }, [freeze, selectedThreadKey]);
249
250 useEffect(() => {
251 if (
252 anchorMessageId === null ||
253 lastScrolledAnchorMessageIdRef.current === anchorMessageId ||
254 contentPresentationKind !== "ready" ||
255 !selectedThreadFeed.some((entry) => entry.type === "message" && entry.id === anchorMessageId)
256 ) {
257 return;
258 }
259
260 const targetThreadKey = selectedThreadKey;
261 const frame = requestAnimationFrame(() => {
262 if (selectedThreadKeyRef.current !== targetThreadKey) {
263 return;
264 }
265 lastScrolledAnchorMessageIdRef.current = anchorMessageId;
266 // Wait for the keyboard dismissal (started by blur() on send) to finish
267 // before scrolling: scrollMessageToEnd freezes keyboard-driven inset
268 // updates while it runs, and a close event swallowed by that freeze
269 // leaves the keyboard padding permanently applied — overshooting the
270 // anchor and leaving a phantom bottom inset once the reply streams in.
271 void KeyboardController.dismiss()
272 .then(() => {
273 if (
274 selectedThreadKeyRef.current !== targetThreadKey ||
275 lastScrolledAnchorMessageIdRef.current !== anchorMessageId
276 ) {
277 return;
278 }
279 return scrollMessageToEnd({ animated: true, closeKeyboard: false });
280 })
281 .catch(() => {
282 if (
283 selectedThreadKeyRef.current !== targetThreadKey ||
284 lastScrolledAnchorMessageIdRef.current !== anchorMessageId
285 ) {
286 return;
287 }
288 lastScrolledAnchorMessageIdRef.current = null;
289 freeze.set(false);
290 });
291 });
292 return () => cancelAnimationFrame(frame);
293 }, [
294 anchorMessageId,
295 freeze,
296 contentPresentationKind,
297 selectedThreadFeed,
298 scrollMessageToEnd,
299 selectedThreadKey,
300 ]);
301
302 const handleSendMessage = useCallback(async () => {
303 const targetThreadKey = selectedThreadKey;
304 const messageId = await props.onSendMessage();
305 if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
306 return messageId;
307 }
308
309 setAnchorMessageId(messageId);
310 composerEditorRef.current?.blur();
311 return messageId;
312 }, [props.onSendMessage, selectedThreadKey]);
313
314 const collapseComposer = useCallback(() => {
315 composerEditorRef.current?.blur();
316 }, []);
317
318 const handleScrollToEnd = useCallback(() => {
319 void Haptics.selectionAsync();
320 void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
321 freeze.set(false);
322 });
323 }, [freeze, scrollMessageToEnd]);
324
325 const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled;
326
327 const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
328 feedTouchStartRef.current = {
329 pageX: event.nativeEvent.pageX,
330 pageY: event.nativeEvent.pageY,
331 };
332 }, []);
333
334 const handleFeedTouchMove = useCallback((event: GestureResponderEvent) => {
335 const start = feedTouchStartRef.current;
336 if (!start) {
337 return;
338 }
339 const deltaX = event.nativeEvent.pageX - start.pageX;
340 const deltaY = event.nativeEvent.pageY - start.pageY;
341 if (Math.hypot(deltaX, deltaY) > 8) {
342 feedTouchStartRef.current = null;
343 }
344 }, []);
345
346 const handleFeedTouchEnd = useCallback(() => {
347 if (feedTouchStartRef.current) {
348 collapseComposer();
349 }
350 feedTouchStartRef.current = null;
351 }, [collapseComposer]);
352
353 const handleFeedTouchCancel = useCallback(() => {
354 feedTouchStartRef.current = null;
355 }, []);
356
357 return (
358 <View className="flex-1">
359 {showContent ? (
360 <View
361 className="flex-1"
362 onTouchStart={handleFeedTouchStart}
363 onTouchMove={handleFeedTouchMove}
364 onTouchEnd={handleFeedTouchEnd}
365 onTouchCancel={handleFeedTouchCancel}
366 >
367 <ThreadFeed
368 key={props.selectedThread.id}
369 environmentId={props.environmentId}
370 threadId={props.selectedThread.id}
371 workspaceRoot={props.threadCwd}
372 feed={props.selectedThreadFeed}
373 contentPresentation={props.contentPresentation}
374 agentLabel={agentLabel}
375 latestTurn={props.selectedThread.latestTurn}
376 activeWorkStartedAt={props.activeWorkStartedAt}
377 listRef={listRef}
378 freeze={freeze}
379 anchorMessageId={anchorMessageId}
380 contentInsetEndAdjustment={contentInsetEndAdjustment}
381 contentTopInset={0}
382 contentBottomInset={estimatedOverlayHeight}
383 contentMaxWidth={contentMaxWidth}
384 layoutVariant={layoutVariant}
385 usesAutomaticContentInsets={props.usesAutomaticContentInsets}
386 onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
387 onEndFollowEnabledChange={setEndFollowEnabled}
388 skills={selectedProviderSkills}
389 loadEarlier={props.loadEarlier ?? null}
390 />
391 </View>
392 ) : (
393 <View className="flex-1" />
394 )}
395
396 {/* Floating composer — sticks to keyboard via KeyboardStickyView */}
397 {showContent ? (
398 <KeyboardStickyView
399 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
400 offset={{ closed: 0, opened: 0 }}
401 >
402 {/* No paddingTop here: the overlay's measured height becomes the
403 list's bottom inset, so any padding above the pill/composer
404 pushes the resting content floor up by the same amount. */}
405 <View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
406 {showScrollToEndButton ? (
407 <Animated.View
408 pointerEvents="box-none"
409 className="absolute -top-28 left-0 right-0 z-20 items-center"
410 entering={FadeInDown.duration(160)}
411 exiting={FadeOut.duration(100)}
412 >
413 <ControlPill
414 accessibilityLabel="Scroll to end"
415 activateOnPressIn
416 className="border border-border bg-card shadow-md shadow-black/10"
417 icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
418 onPress={handleScrollToEnd}
419 />
420 </Animated.View>
421 ) : null}
422 <View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
423 {props.activePendingApproval || props.activePendingUserInput ? (
424 <Animated.View
425 className="shrink-0 gap-3 px-4 pb-3"
426 entering={FadeInDown.duration(220)}
427 exiting={FadeOut.duration(140)}
428 >
429 {props.activePendingApproval ? (
430 <PendingApprovalCard
431 approval={props.activePendingApproval}
432 respondingApprovalId={props.respondingApprovalId}
433 onRespond={props.onRespondToApproval}
434 />
435 ) : null}
436 {props.activePendingUserInput ? (
437 <PendingUserInputCard
438 pendingUserInput={props.activePendingUserInput}
439 drafts={props.activePendingUserInputDrafts}
440 answers={props.activePendingUserInputAnswers}
441 respondingUserInputId={props.respondingUserInputId}
442 onSelectOption={props.onSelectUserInputOption}
443 onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
444 onSubmit={props.onSubmitUserInput}
445 />
446 ) : null}
447 </Animated.View>
448 ) : null}
449 </View>
450
451 <ThreadComposer
452 editorRef={composerEditorRef}
453 draftMessage={props.draftMessage}
454 draftAttachments={props.draftAttachments}
455 placeholder="Ask the repo agent, or run a command…"
456 contentMaxWidth={contentMaxWidth}
457 connectionState={props.connectionStateLabel}
458 connectionError={props.connectionError}
459 environmentLabel={props.environmentLabel}
460 threadSyncPhase={threadSyncPhase}
461 selectedThread={props.selectedThread}
462 serverConfig={props.serverConfig}
463 queueCount={props.selectedThreadQueueCount}
464 activeThreadBusy={props.activeThreadBusy}
465 environmentId={props.environmentId}
466 projectCwd={props.projectWorkspaceRoot}
467 bottomInset={composerBottomInset}
468 onChangeDraftMessage={props.onChangeDraftMessage}
469 onPickDraftImages={props.onPickDraftImages}
470 onNativePasteImages={props.onNativePasteImages}
471 onRemoveDraftImage={props.onRemoveDraftImage}
472 onStopThread={props.onStopThread}
473 onSendMessage={handleSendMessage}
474 onReconnectEnvironment={props.onReconnectEnvironment}
475 onUpdateModelSelection={props.onUpdateThreadModelSelection}
476 onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
477 onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
478 onExpandedChange={setComposerExpanded}
479 />
480 </View>
481 </KeyboardStickyView>
482 ) : null}
483 </View>
484 );
485});