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

ThreadDetailScreen.tsx

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