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