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