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 readonly activeThreadBusy: boolean;
65 readonly hasMoreOlderActivities: boolean;
66 readonly loadingOlderActivities: boolean;
67 readonly onLoadOlderActivities: () => void;
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 composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
188 const contentPresentationKind = props.contentPresentation.kind;
189 // The raw sync status enters "synchronizing" on every full fetch, cached or
190 // not. Whether messages are already on screen decides the pill label: no
191 // data yet → "Loading messages", cached data reconciling → "Syncing".
192 const threadSyncPhase = (() => {
193 switch (props.threadSyncStatus) {
194 case "empty":
195 case "cached":
196 case "synchronizing":
197 if (contentPresentationKind === "ready") {
198 return "syncing" as const;
199 }
200 return contentPresentationKind === "loading" ? ("loading" as const) : null;
201 default:
202 return null;
203 }
204 })();
205 const selectedThreadFeed = props.selectedThreadFeed;
206 const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
207 const composerOverlapHeight = composerChrome + composerBottomInset;
208 const estimatedOverlayHeight = composerOverlapHeight;
209 // The overlay's measured height includes the home-indicator inset (the
210 // composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
211 // UIKit add the safe-area bottom to the content inset AGAIN — leaving a
212 // dead strip between the resting content and the composer. Report the
213 // overlay height minus the safe area; UIKit adds it back, and ThreadFeed
214 // hands LegendList the same delta via contentInsetEndStaticAdjustment so
215 // its end-scroll math matches the real resting position.
216 const nativeInsetOvercount =
217 props.usesAutomaticContentInsets === true && Platform.OS === "ios" ? insets.bottom : 0;
218 const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
219 listRef,
220 composerOverlayRef,
221 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
222 -nativeInsetOvercount,
223 );
224 const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
225 const showContent = props.showContent ?? true;
226 const layoutVariant = props.layoutVariant ?? "compact";
227 const isSplitLayout = layoutVariant === "split";
228 const contentMaxWidth = isSplitLayout ? CHAT_CONTENT_MAX_WIDTH : undefined;
229 const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
230 useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
231 const selectedProviderSkills = useMemo(
232 () =>
233 props.serverConfig?.providers.find((provider) => provider.instanceId === selectedInstanceId)
234 ?.skills ?? [],
235 [props.serverConfig, selectedInstanceId],
236 );
237
238 useLayoutEffect(() => {
239 selectedThreadKeyRef.current = selectedThreadKey;
240 }, [selectedThreadKey]);
241
242 useEffect(() => {
243 setAnchorMessageId(null);
244 lastScrolledAnchorMessageIdRef.current = null;
245 freeze.set(false);
246 }, [freeze, selectedThreadKey]);
247
248 useEffect(() => {
249 if (
250 anchorMessageId === null ||
251 lastScrolledAnchorMessageIdRef.current === anchorMessageId ||
252 contentPresentationKind !== "ready" ||
253 !selectedThreadFeed.some((entry) => entry.type === "message" && entry.id === anchorMessageId)
254 ) {
255 return;
256 }
257
258 const targetThreadKey = selectedThreadKey;
259 const frame = requestAnimationFrame(() => {
260 if (selectedThreadKeyRef.current !== targetThreadKey) {
261 return;
262 }
263 lastScrolledAnchorMessageIdRef.current = anchorMessageId;
264 // Wait for the keyboard dismissal (started by blur() on send) to finish
265 // before scrolling: scrollMessageToEnd freezes keyboard-driven inset
266 // updates while it runs, and a close event swallowed by that freeze
267 // leaves the keyboard padding permanently applied — overshooting the
268 // anchor and leaving a phantom bottom inset once the reply streams in.
269 void KeyboardController.dismiss()
270 .then(() => {
271 if (
272 selectedThreadKeyRef.current !== targetThreadKey ||
273 lastScrolledAnchorMessageIdRef.current !== anchorMessageId
274 ) {
275 return;
276 }
277 return scrollMessageToEnd({ animated: true, closeKeyboard: false });
278 })
279 .catch(() => {
280 if (
281 selectedThreadKeyRef.current !== targetThreadKey ||
282 lastScrolledAnchorMessageIdRef.current !== anchorMessageId
283 ) {
284 return;
285 }
286 lastScrolledAnchorMessageIdRef.current = null;
287 freeze.set(false);
288 });
289 });
290 return () => cancelAnimationFrame(frame);
291 }, [
292 anchorMessageId,
293 freeze,
294 contentPresentationKind,
295 selectedThreadFeed,
296 scrollMessageToEnd,
297 selectedThreadKey,
298 ]);
299
300 const handleSendMessage = useCallback(async () => {
301 const targetThreadKey = selectedThreadKey;
302 const messageId = await props.onSendMessage();
303 if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
304 return messageId;
305 }
306
307 setAnchorMessageId(messageId);
308 composerEditorRef.current?.blur();
309 return messageId;
310 }, [props.onSendMessage, selectedThreadKey]);
311
312 const collapseComposer = useCallback(() => {
313 composerEditorRef.current?.blur();
314 }, []);
315
316 const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
317 feedTouchStartRef.current = {
318 pageX: event.nativeEvent.pageX,
319 pageY: event.nativeEvent.pageY,
320 };
321 }, []);
322
323 const handleFeedTouchMove = useCallback((event: GestureResponderEvent) => {
324 const start = feedTouchStartRef.current;
325 if (!start) {
326 return;
327 }
328 const deltaX = event.nativeEvent.pageX - start.pageX;
329 const deltaY = event.nativeEvent.pageY - start.pageY;
330 if (Math.hypot(deltaX, deltaY) > 8) {
331 feedTouchStartRef.current = null;
332 }
333 }, []);
334
335 const handleFeedTouchEnd = useCallback(() => {
336 if (feedTouchStartRef.current) {
337 collapseComposer();
338 }
339 feedTouchStartRef.current = null;
340 }, [collapseComposer]);
341
342 const handleFeedTouchCancel = useCallback(() => {
343 feedTouchStartRef.current = null;
344 }, []);
345
346 return (
347 <View className="flex-1">
348 {showContent ? (
349 <View
350 className="flex-1"
351 onTouchStart={handleFeedTouchStart}
352 onTouchMove={handleFeedTouchMove}
353 onTouchEnd={handleFeedTouchEnd}
354 onTouchCancel={handleFeedTouchCancel}
355 >
356 <ThreadFeed
357 key={props.selectedThread.id}
358 environmentId={props.environmentId}
359 threadId={props.selectedThread.id}
360 workspaceRoot={props.threadCwd}
361 feed={props.selectedThreadFeed}
362 contentPresentation={props.contentPresentation}
363 agentLabel={agentLabel}
364 latestTurn={props.selectedThread.latestTurn}
365 activeWorkStartedAt={props.activeWorkStartedAt}
366 listRef={listRef}
367 freeze={freeze}
368 anchorMessageId={anchorMessageId}
369 contentInsetEndAdjustment={contentInsetEndAdjustment}
370 contentTopInset={0}
371 contentBottomInset={estimatedOverlayHeight}
372 contentMaxWidth={contentMaxWidth}
373 layoutVariant={layoutVariant}
374 usesAutomaticContentInsets={props.usesAutomaticContentInsets}
375 onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
376 skills={selectedProviderSkills}
377 hasMoreOlder={props.hasMoreOlderActivities}
378 loadingOlder={props.loadingOlderActivities}
379 onLoadOlder={props.onLoadOlderActivities}
380 />
381 </View>
382 ) : (
383 <View className="flex-1" />
384 )}
385
386 {/* Floating composer — sticks to keyboard via KeyboardStickyView */}
387 {showContent ? (
388 <KeyboardStickyView
389 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
390 offset={{ closed: 0, opened: 0 }}
391 >
392 {/* No paddingTop here: the overlay's measured height becomes the
393 list's bottom inset, so any padding above the pill/composer
394 pushes the resting content floor up by the same amount. */}
395 <View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
396 <View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
397 {props.activePendingApproval || props.activePendingUserInput ? (
398 <Animated.View
399 className="shrink-0 gap-3 px-4 pb-3"
400 entering={FadeInDown.duration(220)}
401 exiting={FadeOut.duration(140)}
402 >
403 {props.activePendingApproval ? (
404 <PendingApprovalCard
405 approval={props.activePendingApproval}
406 respondingApprovalId={props.respondingApprovalId}
407 onRespond={props.onRespondToApproval}
408 />
409 ) : null}
410 {props.activePendingUserInput ? (
411 <PendingUserInputCard
412 pendingUserInput={props.activePendingUserInput}
413 drafts={props.activePendingUserInputDrafts}
414 answers={props.activePendingUserInputAnswers}
415 respondingUserInputId={props.respondingUserInputId}
416 onSelectOption={props.onSelectUserInputOption}
417 onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
418 onSubmit={props.onSubmitUserInput}
419 />
420 ) : null}
421 </Animated.View>
422 ) : null}
423 </View>
424
425 <ThreadComposer
426 editorRef={composerEditorRef}
427 draftMessage={props.draftMessage}
428 draftAttachments={props.draftAttachments}
429 placeholder="Ask the repo agent, or run a command…"
430 contentMaxWidth={contentMaxWidth}
431 connectionState={props.connectionStateLabel}
432 connectionError={props.connectionError}
433 environmentLabel={props.environmentLabel}
434 threadSyncPhase={threadSyncPhase}
435 selectedThread={props.selectedThread}
436 serverConfig={props.serverConfig}
437 queueCount={props.selectedThreadQueueCount}
438 activeThreadBusy={props.activeThreadBusy}
439 environmentId={props.environmentId}
440 projectCwd={props.projectWorkspaceRoot}
441 bottomInset={composerBottomInset}
442 onChangeDraftMessage={props.onChangeDraftMessage}
443 onPickDraftImages={props.onPickDraftImages}
444 onNativePasteImages={props.onNativePasteImages}
445 onRemoveDraftImage={props.onRemoveDraftImage}
446 onStopThread={props.onStopThread}
447 onSendMessage={handleSendMessage}
448 onReconnectEnvironment={props.onReconnectEnvironment}
449 onUpdateModelSelection={props.onUpdateThreadModelSelection}
450 onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
451 onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
452 onExpandedChange={setComposerExpanded}
453 />
454 </View>
455 </KeyboardStickyView>
456 ) : null}
457 </View>
458 );
459});