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