Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadDetailScreen.tsx

464 lines18.6 KB

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