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

ThreadDetailScreen.tsx

462 lines17.6 KB

1import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
2import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
3import type { LegendListRef } from "@legendapp/list/react-native";
4import type {
5 ApprovalRequestId,
6 EnvironmentId,
7 MessageId,
8 ModelSelection,
9 OrchestrationThreadShell,
10 ProviderApprovalDecision,
11 ProviderInteractionMode,
12 RuntimeMode,
13 ServerConfig as T3ServerConfig,
14 ThreadId,
15} from "@t3tools/contracts";
16import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
17import * as Haptics from "expo-haptics";
18import { useHeaderHeight } from "expo-router/build/react-navigation/elements";
19import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
20import { View, type GestureResponderEvent } from "react-native";
21import { Gesture, GestureDetector } from "react-native-gesture-handler";
22import { KeyboardStickyView } from "react-native-keyboard-controller";
23import { useSafeAreaInsets } from "react-native-safe-area-context";
24import { runOnJS } from "react-native-reanimated";
25​
26import { AppText as Text } from "../../components/AppText";
27import type { ComposerEditorHandle } from "../../components/ComposerEditor";
28import type { StatusTone } from "../../components/StatusPill";
29import type { DraftComposerImageAttachment } from "../../lib/composerImages";
30import type { LayoutVariant } from "../../lib/layout";
31import { scopedThreadKey } from "../../lib/scopedEntities";
32import type {
33 PendingApproval,
34 PendingUserInput,
35 PendingUserInputDraftAnswer,
36 ThreadFeedEntry,
37} from "../../lib/threadActivity";
38import { PendingApprovalCard } from "./PendingApprovalCard";
39import { PendingUserInputCard } from "./PendingUserInputCard";
40import {
41 COMPOSER_COLLAPSED_CHROME,
42 COMPOSER_EXPANDED_CHROME,
43 ThreadComposer,
44} from "./ThreadComposer";
45import { ThreadFeed } from "./ThreadFeed";
46import type { ThreadContentPresentation } from "./threadContentPresentation";
47​
48export interface ThreadDetailScreenProps {
49 readonly selectedThread: OrchestrationThreadShell;
50 readonly contentPresentation: ThreadContentPresentation;
51 readonly screenTone: StatusTone;
52 readonly connectionError: string | null;
53 readonly environmentLabel: string | null;
54 readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
55 readonly activeWorkStartedAt: string | null;
56 readonly activePendingApproval: PendingApproval | null;
57 readonly respondingApprovalId: ApprovalRequestId | null;
58 readonly activePendingUserInput: PendingUserInput | null;
59 readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
60 readonly activePendingUserInputAnswers: Record<string, string> | null;
61 readonly respondingUserInputId: ApprovalRequestId | null;
62 readonly draftMessage: string;
63 readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
64 readonly connectionStateLabel: EnvironmentConnectionPhase;
65 readonly activeThreadBusy: boolean;
66 readonly environmentId: EnvironmentId;
67 readonly projectWorkspaceRoot: string | null;
68 readonly threadCwd: string | null;
69 readonly selectedThreadQueueCount: number;
70 readonly serverConfig: T3ServerConfig | null;
71 readonly layoutVariant?: LayoutVariant;
72 readonly onOpenDrawer: () => 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;
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;
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]);
171​
172const WORKING_INDICATOR_HEIGHT = 44;
173​
174const WorkingDurationPill = memo(function WorkingDurationPill(props: {
175 readonly startedAt: string;
176}) {
177 const [nowMs, setNowMs] = useState(() => Date.now());
178​
179 useEffect(() => {
180 const intervalId = setInterval(() => {
181 setNowMs(Date.now());
182 }, 1_000);
183 return () => clearInterval(intervalId);
184 }, [props.startedAt]);
185​
186 const durationLabel = formatElapsed(props.startedAt, new Date(nowMs).toISOString()) ?? "0s";
187​
188 return (
189 <View className="px-4 pb-2" style={{ flexShrink: 0 }}>
190 <View className="self-start rounded-full border border-neutral-200/80 bg-neutral-50/90 px-3 py-2 dark:border-white/[0.08] dark:bg-white/[0.04]">
191 <View className="flex-row items-center gap-2">
192 <View className="flex-row items-center gap-1">
193 <View className="h-1.5 w-1.5 rounded-full bg-neutral-400 dark:bg-neutral-500" />
194 <View className="h-1.5 w-1.5 rounded-full bg-neutral-400/80 dark:bg-neutral-500/80" />
195 <View className="h-1.5 w-1.5 rounded-full bg-neutral-400/60 dark:bg-neutral-500/60" />
196 </View>
197 <Text className="font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
198 Working for {durationLabel}
199 </Text>
200 </View>
201 </View>
202 </View>
203 );
204});
205​
206export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
207 const { onOpenDrawer } = props;
208​
209 const insets = useSafeAreaInsets();
210 const headerHeight = useHeaderHeight();
211 const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
212 const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
213 const composerEditorRef = useRef<ComposerEditorHandle>(null);
214 const composerOverlayRef = useRef<View>(null);
215 const listRef = useRef<LegendListRef>(null);
216 const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
217 const selectedThreadKeyRef = useRef(selectedThreadKey);
218 const lastScrolledAnchorMessageIdRef = useRef<MessageId | null>(null);
219 const [composerExpanded, setComposerExpanded] = useState(false);
220 const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
221 const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
222 const contentPresentationKind = props.contentPresentation.kind;
223 const selectedThreadFeed = props.selectedThreadFeed;
224 const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
225 const composerOverlapHeight = composerChrome + composerBottomInset;
226 const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0;
227 const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight + 8;
228 const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
229 listRef,
230 composerOverlayRef,
231 estimatedOverlayHeight,
232 );
233 const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
234 const showContent = props.showContent ?? true;
235 const layoutVariant = props.layoutVariant ?? "compact";
236 const isSplitLayout = layoutVariant === "split";
237 const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
238 useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
239 const selectedProviderSkills = useMemo(
240 () =>
241 props.serverConfig?.providers.find((provider) => provider.instanceId === selectedInstanceId)
242 ?.skills ?? [],
243 [props.serverConfig, selectedInstanceId],
244 );
245​
246 const completeDrawerGesture = useCallback(() => {
247 void Haptics.selectionAsync();
248 onOpenDrawer();
249 }, [onOpenDrawer]);
250​
251 const drawerGestureThreshold = 80;
252 const headerDrawerGesture = useMemo(
253 () =>
254 Gesture.Pan()
255 .enabled(!isSplitLayout)
256 .hitSlop({ left: 0, width: 40 })
257 .activeOffsetX([10, 999])
258 .failOffsetY([-24, 24])
259 .onEnd((event) => {
260 const translationX = Math.max(event.translationX, 0);
261 if (event.y < drawerGestureThreshold && translationX > 56) {
262 runOnJS(completeDrawerGesture)();
263 }
264 }),
265 [completeDrawerGesture, isSplitLayout],
266 );
267​
268 useLayoutEffect(() => {
269 selectedThreadKeyRef.current = selectedThreadKey;
270 }, [selectedThreadKey]);
271​
272 useEffect(() => {
273 setAnchorMessageId(null);
274 lastScrolledAnchorMessageIdRef.current = null;
275 freeze.set(false);
276 }, [freeze, selectedThreadKey]);
277​
278 useEffect(() => {
279 if (
280 anchorMessageId === null ||
281 lastScrolledAnchorMessageIdRef.current === anchorMessageId ||
282 contentPresentationKind !== "ready" ||
283 !selectedThreadFeed.some((entry) => entry.type === "message" && entry.id === anchorMessageId)
284 ) {
285 return;
286 }
287​
288 const targetThreadKey = selectedThreadKey;
289 const frame = requestAnimationFrame(() => {
290 if (selectedThreadKeyRef.current !== targetThreadKey) {
291 return;
292 }
293 lastScrolledAnchorMessageIdRef.current = anchorMessageId;
294 void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
295 if (
296 selectedThreadKeyRef.current !== targetThreadKey ||
297 lastScrolledAnchorMessageIdRef.current !== anchorMessageId
298 ) {
299 return;
300 }
301 lastScrolledAnchorMessageIdRef.current = null;
302 freeze.set(false);
303 });
304 });
305 return () => cancelAnimationFrame(frame);
306 }, [
307 anchorMessageId,
308 freeze,
309 contentPresentationKind,
310 selectedThreadFeed,
311 scrollMessageToEnd,
312 selectedThreadKey,
313 ]);
314​
315 const handleSendMessage = useCallback(async () => {
316 const targetThreadKey = selectedThreadKey;
317 const messageId = await props.onSendMessage();
318 if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
319 return messageId;
320 }
321​
322 setAnchorMessageId(messageId);
323 composerEditorRef.current?.blur();
324 return messageId;
325 }, [props.onSendMessage, selectedThreadKey]);
326​
327 const collapseComposer = useCallback(() => {
328 composerEditorRef.current?.blur();
329 }, []);
330​
331 const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
332 feedTouchStartRef.current = {
333 pageX: event.nativeEvent.pageX,
334 pageY: event.nativeEvent.pageY,
335 };
336 }, []);
337​
338 const handleFeedTouchMove = useCallback((event: GestureResponderEvent) => {
339 const start = feedTouchStartRef.current;
340 if (!start) {
341 return;
342 }
343 const deltaX = event.nativeEvent.pageX - start.pageX;
344 const deltaY = event.nativeEvent.pageY - start.pageY;
345 if (Math.hypot(deltaX, deltaY) > 8) {
346 feedTouchStartRef.current = null;
347 }
348 }, []);
349​
350 const handleFeedTouchEnd = useCallback(() => {
351 if (feedTouchStartRef.current) {
352 collapseComposer();
353 }
354 feedTouchStartRef.current = null;
355 }, [collapseComposer]);
356​
357 const handleFeedTouchCancel = useCallback(() => {
358 feedTouchStartRef.current = null;
359 }, []);
360​
361 return (
362 <GestureDetector gesture={headerDrawerGesture}>
363 <View className="flex-1">
364 {showContent ? (
365 <View
366 style={{ flex: 1 }}
367 onTouchStart={handleFeedTouchStart}
368 onTouchMove={handleFeedTouchMove}
369 onTouchEnd={handleFeedTouchEnd}
370 onTouchCancel={handleFeedTouchCancel}
371 >
372 <ThreadFeed
373 key={props.selectedThread.id}
374 environmentId={props.environmentId}
375 threadId={props.selectedThread.id}
376 workspaceRoot={props.threadCwd}
377 feed={props.selectedThreadFeed}
378 contentPresentation={props.contentPresentation}
379 agentLabel={agentLabel}
380 latestTurn={props.selectedThread.latestTurn}
381 listRef={listRef}
382 freeze={freeze}
383 anchorMessageId={anchorMessageId}
384 contentInsetEndAdjustment={contentInsetEndAdjustment}
385 contentTopInset={headerHeight}
386 contentBottomInset={estimatedOverlayHeight}
387 layoutVariant={layoutVariant}
388 skills={selectedProviderSkills}
389 />
390 </View>
391 ) : (
392 <View style={{ flex: 1 }} />
393 )}
394​
395 {/* Floating composer — sticks to keyboard via KeyboardStickyView */}
396 {showContent ? (
397 <KeyboardStickyView
398 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
399 offset={{ closed: 0, opened: 0 }}
400 >
401 <View ref={composerOverlayRef} onLayout={onComposerLayout} style={{ paddingTop: 8 }}>
402 {props.activeWorkStartedAt ? (
403 <WorkingDurationPill startedAt={props.activeWorkStartedAt} />
404 ) : null}
405​
406 {props.activePendingApproval || props.activePendingUserInput ? (
407 <View className="gap-3 px-4 pb-3" style={{ flexShrink: 0 }}>
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 </View>
427 ) : null}
428​
429 <ThreadComposer
430 editorRef={composerEditorRef}
431 draftMessage={props.draftMessage}
432 draftAttachments={props.draftAttachments}
433 placeholder="Ask the repo agent, or run a command…"
434 connectionState={props.connectionStateLabel}
435 connectionError={props.connectionError}
436 environmentLabel={props.environmentLabel}
437 selectedThread={props.selectedThread}
438 serverConfig={props.serverConfig}
439 queueCount={props.selectedThreadQueueCount}
440 activeThreadBusy={props.activeThreadBusy}
441 environmentId={props.environmentId}
442 projectCwd={props.projectWorkspaceRoot}
443 bottomInset={composerBottomInset}
444 onChangeDraftMessage={props.onChangeDraftMessage}
445 onPickDraftImages={props.onPickDraftImages}
446 onNativePasteImages={props.onNativePasteImages}
447 onRemoveDraftImage={props.onRemoveDraftImage}
448 onStopThread={props.onStopThread}
449 onSendMessage={handleSendMessage}
450 onReconnectEnvironment={props.onReconnectEnvironment}
451 onUpdateModelSelection={props.onUpdateThreadModelSelection}
452 onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
453 onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
454 onExpandedChange={setComposerExpanded}
455 />
456 </View>
457 </KeyboardStickyView>
458 ) : null}
459 </View>
460 </GestureDetector>
461 );
462});