Open History to see the last commit
1import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
2import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
3import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
4import type { LegendListRef } from "@legendapp/list/react-native";
5import type {
6 EnvironmentId,
7 MessageId,
8 ModelSelection,
9 ProviderApprovalDecision,
10 ProviderInteractionMode,
11 RuntimeMode,
12 RuntimeRequestId,
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 { ThreadRelationshipsBanner } from "./ThreadRelationshipsBanner";
47import { ThreadQueueControl } from "./ThreadQueueControl";
48import type { ThreadContentPresentation } from "./threadContentPresentation";
49
50export interface ThreadDetailScreenProps {
51 readonly selectedThread: EnvironmentThreadShell;
52 readonly contentPresentation: ThreadContentPresentation;
53 readonly screenTone: StatusTone;
54 readonly connectionError: string | null;
55 readonly environmentLabel: string | null;
56 readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
57 readonly activeWorkStartedAt: string | null;
58 readonly activePendingApproval: PendingApproval | null;
59 readonly respondingApprovalId: RuntimeRequestId | null;
60 readonly activePendingUserInput: PendingUserInput | null;
61 readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
62 readonly activePendingUserInputAnswers: Record<string, string> | null;
63 readonly respondingUserInputId: RuntimeRequestId | null;
64 readonly draftMessage: string;
65 readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
66 readonly connectionStateLabel: EnvironmentConnectionPhase;
67 readonly activeThreadBusy: boolean;
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 onOpenDrawer: () => void;
75 readonly onOpenConnectionEditor: () => void;
76 readonly onChangeDraftMessage: (value: string) => void;
77 readonly onPickDraftImages: () => Promise<void>;
78 readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
79 readonly onRemoveDraftImage: (imageId: string) => void;
80 readonly onStopThread: () => void;
81 readonly onSendMessage: () => Promise<MessageId | null>;
82 readonly onReconnectEnvironment: () => void;
83 readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
84 readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
85 readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
86 readonly onRespondToApproval: (
87 requestId: RuntimeRequestId,
88 decision: ProviderApprovalDecision,
89 ) => Promise<unknown>;
90 readonly onSelectUserInputOption: (
91 requestId: RuntimeRequestId,
92 questionId: string,
93 label: string,
94 ) => void;
95 readonly onChangeUserInputCustomAnswer: (
96 requestId: RuntimeRequestId,
97 questionId: string,
98 customAnswer: string,
99 ) => void;
100 readonly onSubmitUserInput: () => Promise<unknown>;
101 readonly showContent?: boolean;
102}
103
104function latestStreamingAssistantMessage(
105 feed: ReadonlyArray<ThreadFeedEntry>,
106): { readonly id: string; readonly textLength: number } | null {
107 for (let index = feed.length - 1; index >= 0; index -= 1) {
108 const entry = feed[index];
109 if (entry?.type !== "message") {
110 continue;
111 }
112 if (entry.message.role !== "assistant" || !entry.message.streaming) {
113 continue;
114 }
115 return {
116 id: entry.message.id,
117 textLength: entry.message.text.length,
118 };
119 }
120
121 return null;
122}
123
124function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedEntry>) {
125 const lastStreamingAssistantRef = useRef<{
126 readonly id: string;
127 readonly textLength: number;
128 } | null>(null);
129 const lastStreamHapticAtRef = useRef(0);
130 const hydratedRef = useRef(false);
131 const previousThreadIdRef = useRef(threadId);
132
133 useEffect(() => {
134 if (previousThreadIdRef.current !== threadId) {
135 previousThreadIdRef.current = threadId;
136 hydratedRef.current = false;
137 }
138
139 const latestStreamingMessage = latestStreamingAssistantMessage(feed);
140
141 if (!hydratedRef.current) {
142 hydratedRef.current = true;
143 lastStreamingAssistantRef.current = latestStreamingMessage;
144 return;
145 }
146
147 if (!latestStreamingMessage) {
148 lastStreamingAssistantRef.current = null;
149 return;
150 }
151
152 const previousStreamingMessage = lastStreamingAssistantRef.current;
153 lastStreamingAssistantRef.current = latestStreamingMessage;
154
155 const isNewStream = previousStreamingMessage?.id !== latestStreamingMessage.id;
156 const textGrew =
157 previousStreamingMessage?.id === latestStreamingMessage.id &&
158 latestStreamingMessage.textLength > previousStreamingMessage.textLength;
159
160 if (!isNewStream && !textGrew) {
161 return;
162 }
163
164 const now = Date.now();
165 if (!isNewStream && now - lastStreamHapticAtRef.current < 320) {
166 return;
167 }
168
169 lastStreamHapticAtRef.current = now;
170 void Haptics.selectionAsync();
171 }, [threadId, feed]);
172}
173
174const WORKING_INDICATOR_HEIGHT = 44;
175
176const WorkingDurationPill = memo(function WorkingDurationPill(props: {
177 readonly startedAt: string;
178}) {
179 const [nowMs, setNowMs] = useState(() => Date.now());
180
181 useEffect(() => {
182 const intervalId = setInterval(() => {
183 setNowMs(Date.now());
184 }, 1_000);
185 return () => clearInterval(intervalId);
186 }, [props.startedAt]);
187
188 const durationLabel = formatElapsed(props.startedAt, new Date(nowMs).toISOString()) ?? "0s";
189
190 return (
191 <View className="px-4 pb-2" style={{ flexShrink: 0 }}>
192 <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]">
193 <View className="flex-row items-center gap-2">
194 <View className="flex-row items-center gap-1">
195 <View className="h-1.5 w-1.5 rounded-full bg-neutral-400 dark:bg-neutral-500" />
196 <View className="h-1.5 w-1.5 rounded-full bg-neutral-400/80 dark:bg-neutral-500/80" />
197 <View className="h-1.5 w-1.5 rounded-full bg-neutral-400/60 dark:bg-neutral-500/60" />
198 </View>
199 <Text className="font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
200 Working for {durationLabel}
201 </Text>
202 </View>
203 </View>
204 </View>
205 );
206});
207
208export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
209 const { onOpenDrawer } = props;
210
211 const insets = useSafeAreaInsets();
212 const headerHeight = useHeaderHeight();
213 const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
214 const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
215 const composerEditorRef = useRef<ComposerEditorHandle>(null);
216 const composerOverlayRef = useRef<View>(null);
217 const listRef = useRef<LegendListRef>(null);
218 const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
219 const selectedThreadKeyRef = useRef(selectedThreadKey);
220 const lastScrolledAnchorMessageIdRef = useRef<MessageId | null>(null);
221 const [composerExpanded, setComposerExpanded] = useState(false);
222 const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
223 const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
224 const contentPresentationKind = props.contentPresentation.kind;
225 const selectedThreadFeed = props.selectedThreadFeed;
226 const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
227 const composerOverlapHeight = composerChrome + composerBottomInset;
228 const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0;
229 const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight + 8;
230 const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
231 listRef,
232 composerOverlayRef,
233 estimatedOverlayHeight,
234 );
235 const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
236 const showContent = props.showContent ?? true;
237 const layoutVariant = props.layoutVariant ?? "compact";
238 const isSplitLayout = layoutVariant === "split";
239 const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
240 useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
241 const selectedProviderSkills = useMemo(
242 () =>
243 props.serverConfig?.providers.find((provider) => provider.instanceId === selectedInstanceId)
244 ?.skills ?? [],
245 [props.serverConfig, selectedInstanceId],
246 );
247
248 const completeDrawerGesture = useCallback(() => {
249 void Haptics.selectionAsync();
250 onOpenDrawer();
251 }, [onOpenDrawer]);
252
253 const drawerGestureThreshold = 80;
254 const headerDrawerGesture = useMemo(
255 () =>
256 Gesture.Pan()
257 .enabled(!isSplitLayout)
258 .hitSlop({ left: 0, width: 40 })
259 .activeOffsetX([10, 999])
260 .failOffsetY([-24, 24])
261 .onEnd((event) => {
262 const translationX = Math.max(event.translationX, 0);
263 if (event.y < drawerGestureThreshold && translationX > 56) {
264 runOnJS(completeDrawerGesture)();
265 }
266 }),
267 [completeDrawerGesture, isSplitLayout],
268 );
269
270 useLayoutEffect(() => {
271 selectedThreadKeyRef.current = selectedThreadKey;
272 }, [selectedThreadKey]);
273
274 useEffect(() => {
275 setAnchorMessageId(null);
276 lastScrolledAnchorMessageIdRef.current = null;
277 freeze.set(false);
278 }, [freeze, selectedThreadKey]);
279
280 useEffect(() => {
281 if (
282 anchorMessageId === null ||
283 lastScrolledAnchorMessageIdRef.current === anchorMessageId ||
284 contentPresentationKind !== "ready" ||
285 !selectedThreadFeed.some((entry) => entry.type === "message" && entry.id === anchorMessageId)
286 ) {
287 return;
288 }
289
290 const targetThreadKey = selectedThreadKey;
291 const frame = requestAnimationFrame(() => {
292 if (selectedThreadKeyRef.current !== targetThreadKey) {
293 return;
294 }
295 lastScrolledAnchorMessageIdRef.current = anchorMessageId;
296 void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
297 if (
298 selectedThreadKeyRef.current !== targetThreadKey ||
299 lastScrolledAnchorMessageIdRef.current !== anchorMessageId
300 ) {
301 return;
302 }
303 lastScrolledAnchorMessageIdRef.current = null;
304 freeze.set(false);
305 });
306 });
307 return () => cancelAnimationFrame(frame);
308 }, [
309 anchorMessageId,
310 freeze,
311 contentPresentationKind,
312 selectedThreadFeed,
313 scrollMessageToEnd,
314 selectedThreadKey,
315 ]);
316
317 const handleSendMessage = useCallback(async () => {
318 const targetThreadKey = selectedThreadKey;
319 const messageId = await props.onSendMessage();
320 if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
321 return messageId;
322 }
323
324 setAnchorMessageId(messageId);
325 composerEditorRef.current?.blur();
326 return messageId;
327 }, [props.onSendMessage, selectedThreadKey]);
328
329 const collapseComposer = useCallback(() => {
330 composerEditorRef.current?.blur();
331 }, []);
332
333 const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
334 feedTouchStartRef.current = {
335 pageX: event.nativeEvent.pageX,
336 pageY: event.nativeEvent.pageY,
337 };
338 }, []);
339
340 const handleFeedTouchMove = useCallback((event: GestureResponderEvent) => {
341 const start = feedTouchStartRef.current;
342 if (!start) {
343 return;
344 }
345 const deltaX = event.nativeEvent.pageX - start.pageX;
346 const deltaY = event.nativeEvent.pageY - start.pageY;
347 if (Math.hypot(deltaX, deltaY) > 8) {
348 feedTouchStartRef.current = null;
349 }
350 }, []);
351
352 const handleFeedTouchEnd = useCallback(() => {
353 if (feedTouchStartRef.current) {
354 collapseComposer();
355 }
356 feedTouchStartRef.current = null;
357 }, [collapseComposer]);
358
359 const handleFeedTouchCancel = useCallback(() => {
360 feedTouchStartRef.current = null;
361 }, []);
362
363 return (
364 <GestureDetector gesture={headerDrawerGesture}>
365 <View className="flex-1">
366 {showContent ? (
367 <View
368 style={{ flex: 1 }}
369 onTouchStart={handleFeedTouchStart}
370 onTouchMove={handleFeedTouchMove}
371 onTouchEnd={handleFeedTouchEnd}
372 onTouchCancel={handleFeedTouchCancel}
373 >
374 <ThreadFeed
375 key={props.selectedThread.id}
376 environmentId={props.environmentId}
377 threadId={props.selectedThread.id}
378 threadTitle={props.selectedThread.title}
379 workspaceRoot={props.threadCwd}
380 feed={props.selectedThreadFeed}
381 contentPresentation={props.contentPresentation}
382 agentLabel={agentLabel}
383 latestRun={props.selectedThread.latestRun}
384 listRef={listRef}
385 freeze={freeze}
386 anchorMessageId={anchorMessageId}
387 contentInsetEndAdjustment={contentInsetEndAdjustment}
388 contentTopInset={headerHeight}
389 contentBottomInset={estimatedOverlayHeight}
390 topAccessory={
391 <ThreadRelationshipsBanner
392 environmentId={props.environmentId}
393 threadId={props.selectedThread.id}
394 />
395 }
396 layoutVariant={layoutVariant}
397 skills={selectedProviderSkills}
398 />
399 </View>
400 ) : (
401 <View style={{ flex: 1 }} />
402 )}
403
404 {/* Floating composer — sticks to keyboard via KeyboardStickyView */}
405 {showContent ? (
406 <KeyboardStickyView
407 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
408 offset={{ closed: 0, opened: 0 }}
409 >
410 <View ref={composerOverlayRef} onLayout={onComposerLayout} style={{ paddingTop: 8 }}>
411 {props.activeWorkStartedAt ? (
412 <WorkingDurationPill startedAt={props.activeWorkStartedAt} />
413 ) : null}
414
415 <ThreadQueueControl
416 environmentId={props.environmentId}
417 threadId={props.selectedThread.id}
418 />
419
420 {props.activePendingApproval || props.activePendingUserInput ? (
421 <View className="gap-3 px-4 pb-3" style={{ flexShrink: 0 }}>
422 {props.activePendingApproval ? (
423 <PendingApprovalCard
424 approval={props.activePendingApproval}
425 respondingApprovalId={props.respondingApprovalId}
426 onRespond={props.onRespondToApproval}
427 />
428 ) : null}
429 {props.activePendingUserInput ? (
430 <PendingUserInputCard
431 pendingUserInput={props.activePendingUserInput}
432 drafts={props.activePendingUserInputDrafts}
433 answers={props.activePendingUserInputAnswers}
434 respondingUserInputId={props.respondingUserInputId}
435 onSelectOption={props.onSelectUserInputOption}
436 onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
437 onSubmit={props.onSubmitUserInput}
438 />
439 ) : null}
440 </View>
441 ) : null}
442
443 <ThreadComposer
444 editorRef={composerEditorRef}
445 draftMessage={props.draftMessage}
446 draftAttachments={props.draftAttachments}
447 placeholder="Ask the repo agent, or run a command…"
448 connectionState={props.connectionStateLabel}
449 connectionError={props.connectionError}
450 environmentLabel={props.environmentLabel}
451 selectedThread={props.selectedThread}
452 serverConfig={props.serverConfig}
453 queueCount={props.selectedThreadQueueCount}
454 activeThreadBusy={props.activeThreadBusy}
455 environmentId={props.environmentId}
456 projectCwd={props.projectWorkspaceRoot}
457 bottomInset={composerBottomInset}
458 onChangeDraftMessage={props.onChangeDraftMessage}
459 onPickDraftImages={props.onPickDraftImages}
460 onNativePasteImages={props.onNativePasteImages}
461 onRemoveDraftImage={props.onRemoveDraftImage}
462 onStopThread={props.onStopThread}
463 onSendMessage={handleSendMessage}
464 onReconnectEnvironment={props.onReconnectEnvironment}
465 onUpdateModelSelection={props.onUpdateThreadModelSelection}
466 onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
467 onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
468 onExpandedChange={setComposerExpanded}
469 />
470 </View>
471 </KeyboardStickyView>
472 ) : null}
473 </View>
474 </GestureDetector>
475 );
476});