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 { formatElapsed } from "@t3tools/shared/orchestrationTiming";
18import * as Haptics from "expo-haptics";
19import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
20import { Platform, View, type GestureResponderEvent } from "react-native";
21import { KeyboardController, KeyboardStickyView } from "react-native-keyboard-controller";
22import Animated, { FadeInDown, FadeOut, LinearTransition } from "react-native-reanimated";
23import { useSafeAreaInsets } from "react-native-safe-area-context";
24
25import { AppText as Text } from "../../components/AppText";
26import type { ComposerEditorHandle } from "../../components/ComposerEditor";
27import type { StatusTone } from "../../components/StatusPill";
28import type { DraftComposerImageAttachment } from "../../lib/composerImages";
29import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
30import { scopedThreadKey } from "../../lib/scopedEntities";
31import type {
32 PendingApproval,
33 PendingUserInput,
34 PendingUserInputDraftAnswer,
35 ThreadFeedEntry,
36} from "../../lib/threadActivity";
37import { PendingApprovalCard } from "./PendingApprovalCard";
38import { PendingUserInputCard } from "./PendingUserInputCard";
39import {
40 COMPOSER_COLLAPSED_CHROME,
41 COMPOSER_EXPANDED_CHROME,
42 ThreadComposer,
43} from "./ThreadComposer";
44import { ThreadFeed } from "./ThreadFeed";
45import type { ThreadContentPresentation } from "./threadContentPresentation";
46
47export interface ThreadDetailScreenProps {
48 readonly selectedThread: OrchestrationThreadShell;
49 readonly contentPresentation: ThreadContentPresentation;
50 readonly screenTone: StatusTone;
51 readonly connectionError: string | null;
52 readonly environmentLabel: string | null;
53 readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
54 readonly activeWorkStartedAt: string | null;
55 readonly activePendingApproval: PendingApproval | null;
56 readonly respondingApprovalId: ApprovalRequestId | null;
57 readonly activePendingUserInput: PendingUserInput | null;
58 readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
59 readonly activePendingUserInputAnswers: Record<string, string> | null;
60 readonly respondingUserInputId: ApprovalRequestId | null;
61 readonly draftMessage: string;
62 readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
63 readonly connectionStateLabel: EnvironmentConnectionPhase;
64 /** Message sync status for the selected thread (drives the composer status pill). */
65 readonly threadSyncStatus?: EnvironmentThreadStatus;
66 readonly activeThreadBusy: boolean;
67 readonly environmentId: EnvironmentId;
68 readonly projectWorkspaceRoot: string | null;
69 readonly threadCwd: string | null;
70 readonly selectedThreadQueueCount: number;
71 readonly serverConfig: T3ServerConfig | null;
72 readonly layoutVariant?: LayoutVariant;
73 readonly usesAutomaticContentInsets?: boolean;
74 readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => 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: ApprovalRequestId,
88 decision: ProviderApprovalDecision,
89 ) => Promise<unknown>;
90 readonly onSelectUserInputOption: (
91 requestId: ApprovalRequestId,
92 questionId: string,
93 label: string,
94 ) => void;
95 readonly onChangeUserInputCustomAnswer: (
96 requestId: ApprovalRequestId,
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
174// Pre-measurement estimate for the working pill's slot (the real height is
175// measured via onComposerLayout since the pill lives inside the composer
176// overlay). Matches the rendered pill: pt-2 + pb-2 (16) wrapping a bordered
177// px-3/py-2 row (~36), so ~52 — keep it in sync with WorkingDurationPill.
178const WORKING_INDICATOR_HEIGHT = 52;
179
180const WorkingDurationPill = memo(function WorkingDurationPill(props: {
181 readonly startedAt: string;
182}) {
183 const [nowMs, setNowMs] = useState(() => Date.now());
184
185 useEffect(() => {
186 const intervalId = setInterval(() => {
187 setNowMs(Date.now());
188 }, 1_000);
189 return () => clearInterval(intervalId);
190 }, [props.startedAt]);
191
192 const durationLabel = formatElapsed(props.startedAt, new Date(nowMs).toISOString()) ?? "0s";
193
194 return (
195 <Animated.View
196 className="px-4 pb-2 pt-2"
197 entering={FadeInDown.duration(200)}
198 exiting={FadeOut.duration(140)}
199 style={{ flexShrink: 0 }}
200 >
201 <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]">
202 <View className="flex-row items-center gap-2">
203 <View className="flex-row items-center gap-1">
204 <View className="h-1.5 w-1.5 rounded-full bg-neutral-400 dark:bg-neutral-500" />
205 <View className="h-1.5 w-1.5 rounded-full bg-neutral-400/80 dark:bg-neutral-500/80" />
206 <View className="h-1.5 w-1.5 rounded-full bg-neutral-400/60 dark:bg-neutral-500/60" />
207 </View>
208 <Text className="font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
209 Working for {durationLabel}
210 </Text>
211 </View>
212 </View>
213 </Animated.View>
214 );
215});
216
217export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
218 const insets = useSafeAreaInsets();
219 const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
220 const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
221 const composerEditorRef = useRef<ComposerEditorHandle>(null);
222 const composerOverlayRef = useRef<View>(null);
223 const listRef = useRef<LegendListRef>(null);
224 const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
225 const selectedThreadKeyRef = useRef(selectedThreadKey);
226 const lastScrolledAnchorMessageIdRef = useRef<MessageId | null>(null);
227 const [composerExpanded, setComposerExpanded] = useState(false);
228 const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
229 const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
230 const contentPresentationKind = props.contentPresentation.kind;
231 // The raw sync status enters "synchronizing" on every full fetch, cached or
232 // not. Whether messages are already on screen decides the pill label: no
233 // data yet → "Loading messages", cached data reconciling → "Syncing".
234 const threadSyncPhase = (() => {
235 switch (props.threadSyncStatus) {
236 case "empty":
237 case "cached":
238 case "synchronizing":
239 if (contentPresentationKind === "ready") {
240 return "syncing" as const;
241 }
242 return contentPresentationKind === "loading" ? ("loading" as const) : null;
243 default:
244 return null;
245 }
246 })();
247 const selectedThreadFeed = props.selectedThreadFeed;
248 const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
249 const composerOverlapHeight = composerChrome + composerBottomInset;
250 const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0;
251 const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight;
252 // The overlay's measured height includes the home-indicator inset (the
253 // composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
254 // UIKit add the safe-area bottom to the content inset AGAIN — leaving a
255 // dead strip between the resting content and the composer. Report the
256 // overlay height minus the safe area; UIKit adds it back, and ThreadFeed
257 // hands LegendList the same delta via contentInsetEndStaticAdjustment so
258 // its end-scroll math matches the real resting position.
259 const nativeInsetOvercount =
260 props.usesAutomaticContentInsets === true && Platform.OS === "ios" ? insets.bottom : 0;
261 const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
262 listRef,
263 composerOverlayRef,
264 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
265 -nativeInsetOvercount,
266 );
267 const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
268 const showContent = props.showContent ?? true;
269 const layoutVariant = props.layoutVariant ?? "compact";
270 const isSplitLayout = layoutVariant === "split";
271 const contentMaxWidth = isSplitLayout ? CHAT_CONTENT_MAX_WIDTH : undefined;
272 const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
273 useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
274 const selectedProviderSkills = useMemo(
275 () =>
276 props.serverConfig?.providers.find((provider) => provider.instanceId === selectedInstanceId)
277 ?.skills ?? [],
278 [props.serverConfig, selectedInstanceId],
279 );
280
281 useLayoutEffect(() => {
282 selectedThreadKeyRef.current = selectedThreadKey;
283 }, [selectedThreadKey]);
284
285 useEffect(() => {
286 setAnchorMessageId(null);
287 lastScrolledAnchorMessageIdRef.current = null;
288 freeze.set(false);
289 }, [freeze, selectedThreadKey]);
290
291 useEffect(() => {
292 if (
293 anchorMessageId === null ||
294 lastScrolledAnchorMessageIdRef.current === anchorMessageId ||
295 contentPresentationKind !== "ready" ||
296 !selectedThreadFeed.some((entry) => entry.type === "message" && entry.id === anchorMessageId)
297 ) {
298 return;
299 }
300
301 const targetThreadKey = selectedThreadKey;
302 const frame = requestAnimationFrame(() => {
303 if (selectedThreadKeyRef.current !== targetThreadKey) {
304 return;
305 }
306 lastScrolledAnchorMessageIdRef.current = anchorMessageId;
307 // Wait for the keyboard dismissal (started by blur() on send) to finish
308 // before scrolling: scrollMessageToEnd freezes keyboard-driven inset
309 // updates while it runs, and a close event swallowed by that freeze
310 // leaves the keyboard padding permanently applied — overshooting the
311 // anchor and leaving a phantom bottom inset once the reply streams in.
312 void KeyboardController.dismiss()
313 .then(() => {
314 if (
315 selectedThreadKeyRef.current !== targetThreadKey ||
316 lastScrolledAnchorMessageIdRef.current !== anchorMessageId
317 ) {
318 return;
319 }
320 return scrollMessageToEnd({ animated: true, closeKeyboard: false });
321 })
322 .catch(() => {
323 if (
324 selectedThreadKeyRef.current !== targetThreadKey ||
325 lastScrolledAnchorMessageIdRef.current !== anchorMessageId
326 ) {
327 return;
328 }
329 lastScrolledAnchorMessageIdRef.current = null;
330 freeze.set(false);
331 });
332 });
333 return () => cancelAnimationFrame(frame);
334 }, [
335 anchorMessageId,
336 freeze,
337 contentPresentationKind,
338 selectedThreadFeed,
339 scrollMessageToEnd,
340 selectedThreadKey,
341 ]);
342
343 const handleSendMessage = useCallback(async () => {
344 const targetThreadKey = selectedThreadKey;
345 const messageId = await props.onSendMessage();
346 if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
347 return messageId;
348 }
349
350 setAnchorMessageId(messageId);
351 composerEditorRef.current?.blur();
352 return messageId;
353 }, [props.onSendMessage, selectedThreadKey]);
354
355 const collapseComposer = useCallback(() => {
356 composerEditorRef.current?.blur();
357 }, []);
358
359 const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
360 feedTouchStartRef.current = {
361 pageX: event.nativeEvent.pageX,
362 pageY: event.nativeEvent.pageY,
363 };
364 }, []);
365
366 const handleFeedTouchMove = useCallback((event: GestureResponderEvent) => {
367 const start = feedTouchStartRef.current;
368 if (!start) {
369 return;
370 }
371 const deltaX = event.nativeEvent.pageX - start.pageX;
372 const deltaY = event.nativeEvent.pageY - start.pageY;
373 if (Math.hypot(deltaX, deltaY) > 8) {
374 feedTouchStartRef.current = null;
375 }
376 }, []);
377
378 const handleFeedTouchEnd = useCallback(() => {
379 if (feedTouchStartRef.current) {
380 collapseComposer();
381 }
382 feedTouchStartRef.current = null;
383 }, [collapseComposer]);
384
385 const handleFeedTouchCancel = useCallback(() => {
386 feedTouchStartRef.current = null;
387 }, []);
388
389 return (
390 <View className="flex-1">
391 {showContent ? (
392 <View
393 style={{ flex: 1 }}
394 onTouchStart={handleFeedTouchStart}
395 onTouchMove={handleFeedTouchMove}
396 onTouchEnd={handleFeedTouchEnd}
397 onTouchCancel={handleFeedTouchCancel}
398 >
399 <ThreadFeed
400 key={props.selectedThread.id}
401 environmentId={props.environmentId}
402 threadId={props.selectedThread.id}
403 workspaceRoot={props.threadCwd}
404 feed={props.selectedThreadFeed}
405 contentPresentation={props.contentPresentation}
406 agentLabel={agentLabel}
407 latestTurn={props.selectedThread.latestTurn}
408 listRef={listRef}
409 freeze={freeze}
410 anchorMessageId={anchorMessageId}
411 contentInsetEndAdjustment={contentInsetEndAdjustment}
412 contentTopInset={0}
413 contentBottomInset={estimatedOverlayHeight}
414 contentMaxWidth={contentMaxWidth}
415 layoutVariant={layoutVariant}
416 usesAutomaticContentInsets={props.usesAutomaticContentInsets}
417 onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
418 skills={selectedProviderSkills}
419 />
420 </View>
421 ) : (
422 <View style={{ flex: 1 }} />
423 )}
424
425 {/* Floating composer — sticks to keyboard via KeyboardStickyView */}
426 {showContent ? (
427 <KeyboardStickyView
428 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
429 offset={{ closed: 0, opened: 0 }}
430 >
431 {/* No paddingTop here: the overlay's measured height becomes the
432 list's bottom inset, so any padding above the pill/composer
433 pushes the resting content floor up by the same amount. */}
434 <View ref={composerOverlayRef} onLayout={onComposerLayout} style={{ width: "100%" }}>
435 <Animated.View
436 layout={LinearTransition.duration(220)}
437 style={{ alignSelf: "center", maxWidth: contentMaxWidth, width: "100%" }}
438 >
439 {props.activeWorkStartedAt ? (
440 <WorkingDurationPill startedAt={props.activeWorkStartedAt} />
441 ) : null}
442
443 {props.activePendingApproval || props.activePendingUserInput ? (
444 <Animated.View
445 className="gap-3 px-4 pb-3"
446 entering={FadeInDown.duration(220)}
447 exiting={FadeOut.duration(140)}
448 style={{ flexShrink: 0 }}
449 >
450 {props.activePendingApproval ? (
451 <PendingApprovalCard
452 approval={props.activePendingApproval}
453 respondingApprovalId={props.respondingApprovalId}
454 onRespond={props.onRespondToApproval}
455 />
456 ) : null}
457 {props.activePendingUserInput ? (
458 <PendingUserInputCard
459 pendingUserInput={props.activePendingUserInput}
460 drafts={props.activePendingUserInputDrafts}
461 answers={props.activePendingUserInputAnswers}
462 respondingUserInputId={props.respondingUserInputId}
463 onSelectOption={props.onSelectUserInputOption}
464 onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
465 onSubmit={props.onSubmitUserInput}
466 />
467 ) : null}
468 </Animated.View>
469 ) : null}
470 </Animated.View>
471
472 <ThreadComposer
473 editorRef={composerEditorRef}
474 draftMessage={props.draftMessage}
475 draftAttachments={props.draftAttachments}
476 placeholder="Ask the repo agent, or run a command…"
477 contentMaxWidth={contentMaxWidth}
478 connectionState={props.connectionStateLabel}
479 connectionError={props.connectionError}
480 environmentLabel={props.environmentLabel}
481 threadSyncPhase={threadSyncPhase}
482 selectedThread={props.selectedThread}
483 serverConfig={props.serverConfig}
484 queueCount={props.selectedThreadQueueCount}
485 activeThreadBusy={props.activeThreadBusy}
486 environmentId={props.environmentId}
487 projectCwd={props.projectWorkspaceRoot}
488 bottomInset={composerBottomInset}
489 onChangeDraftMessage={props.onChangeDraftMessage}
490 onPickDraftImages={props.onPickDraftImages}
491 onNativePasteImages={props.onNativePasteImages}
492 onRemoveDraftImage={props.onRemoveDraftImage}
493 onStopThread={props.onStopThread}
494 onSendMessage={handleSendMessage}
495 onReconnectEnvironment={props.onReconnectEnvironment}
496 onUpdateModelSelection={props.onUpdateThreadModelSelection}
497 onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
498 onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
499 onExpandedChange={setComposerExpanded}
500 />
501 </View>
502 </KeyboardStickyView>
503 ) : null}
504 </View>
505 );
506});