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

ThreadDetailScreen.tsx

506 lines20.4 KB

1import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
2import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
3import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
4import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
5import type { LegendListRef } from "@legendapp/list/react-native";
6import type {
7 EnvironmentId,
8 MessageId,
9 ModelSelection,
10 ProviderApprovalDecision,
11 ProviderInteractionMode,
12 RuntimeMode,
13 RuntimeRequestId,
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 { KeyboardController, KeyboardStickyView } from "react-native-keyboard-controller";
21import Animated, { FadeInDown, FadeOut } from "react-native-reanimated";
22import { useSafeAreaInsets } from "react-native-safe-area-context";
23​
24import type { ComposerEditorHandle } from "../../components/ComposerEditor";
25import type { StatusTone } from "../../components/StatusPill";
26import type { DraftComposerImageAttachment } from "../../lib/composerImages";
27import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
28import { scopedThreadKey } from "../../lib/scopedEntities";
29import { threadEnvironment } from "../../state/threads";
30import { useAtomCommand } from "../../state/use-atom-command";
31import type {
32 PendingApproval,
33 PendingUserInput,
34 PendingUserInputDraftAnswer,
35 ThreadFeedEntry,
36 ThreadFeedLatestRun,
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 activityRun: ThreadFeedLatestRun | null;
58 readonly activeWorkStartedAt: string | null;
59 readonly activePendingApproval: PendingApproval | null;
60 readonly respondingApprovalId: RuntimeRequestId | null;
61 readonly activePendingUserInput: PendingUserInput | null;
62 readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
63 readonly activePendingUserInputAnswers: Record<string, string> | null;
64 readonly respondingUserInputId: RuntimeRequestId | null;
65 readonly draftMessage: string;
66 readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
67 readonly connectionStateLabel: EnvironmentConnectionPhase;
68 /** Message sync status for the selected thread (drives the composer status pill). */
69 readonly threadSyncStatus?: EnvironmentThreadStatus;
70 readonly activeThreadBusy: boolean;
71 readonly canStopThread: boolean;
72 readonly environmentId: EnvironmentId;
73 readonly projectWorkspaceRoot: string | null;
74 readonly threadCwd: string | null;
75 readonly selectedThreadQueueCount: number;
76 readonly serverConfig: T3ServerConfig | null;
77 readonly layoutVariant?: LayoutVariant;
78 readonly usesAutomaticContentInsets?: boolean;
79 readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
80 readonly onOpenConnectionEditor: () => void;
81 readonly onChangeDraftMessage: (value: string) => void;
82 readonly onPickDraftImages: () => Promise<void>;
83 readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
84 readonly onRemoveDraftImage: (imageId: string) => void;
85 readonly onStopThread: () => void;
86 readonly onSendMessage: () => Promise<MessageId | null>;
87 readonly onReconnectEnvironment: () => void;
88 readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
89 readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
90 readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
91 readonly onRespondToApproval: (
92 requestId: RuntimeRequestId,
93 decision: ProviderApprovalDecision,
94 ) => Promise<unknown>;
95 readonly onSelectUserInputOption: (
96 requestId: RuntimeRequestId,
97 questionId: string,
98 label: string,
99 ) => void;
100 readonly onChangeUserInputCustomAnswer: (
101 requestId: RuntimeRequestId,
102 questionId: string,
103 customAnswer: string,
104 ) => void;
105 readonly onSubmitUserInput: () => Promise<unknown>;
106 readonly showContent?: boolean;
108​
109function latestStreamingAssistantMessage(
110 feed: ReadonlyArray<ThreadFeedEntry>,
111): { readonly id: string; readonly textLength: number } | null {
112 for (let index = feed.length - 1; index >= 0; index -= 1) {
113 const entry = feed[index];
114 if (entry?.type !== "message") {
115 continue;
116 }
117 if (entry.message.role !== "assistant" || !entry.message.streaming) {
118 continue;
119 }
120 return {
121 id: entry.message.id,
122 textLength: entry.message.text.length,
123 };
124 }
125​
126 return null;
128​
129function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedEntry>) {
130 const lastStreamingAssistantRef = useRef<{
131 readonly id: string;
132 readonly textLength: number;
133 } | null>(null);
134 const lastStreamHapticAtRef = useRef(0);
135 const hydratedRef = useRef(false);
136 const previousThreadIdRef = useRef(threadId);
137​
138 useEffect(() => {
139 if (previousThreadIdRef.current !== threadId) {
140 previousThreadIdRef.current = threadId;
141 hydratedRef.current = false;
142 }
143​
144 const latestStreamingMessage = latestStreamingAssistantMessage(feed);
145​
146 if (!hydratedRef.current) {
147 hydratedRef.current = true;
148 lastStreamingAssistantRef.current = latestStreamingMessage;
149 return;
150 }
151​
152 if (!latestStreamingMessage) {
153 lastStreamingAssistantRef.current = null;
154 return;
155 }
156​
157 const previousStreamingMessage = lastStreamingAssistantRef.current;
158 lastStreamingAssistantRef.current = latestStreamingMessage;
159​
160 const isNewStream = previousStreamingMessage?.id !== latestStreamingMessage.id;
161 const textGrew =
162 previousStreamingMessage?.id === latestStreamingMessage.id &&
163 latestStreamingMessage.textLength > previousStreamingMessage.textLength;
164​
165 if (!isNewStream && !textGrew) {
166 return;
167 }
168​
169 const now = Date.now();
170 if (!isNewStream && now - lastStreamHapticAtRef.current < 320) {
171 return;
172 }
173​
174 lastStreamHapticAtRef.current = now;
175 void Haptics.selectionAsync();
176 }, [threadId, feed]);
178​
179export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
180 const insets = useSafeAreaInsets();
181 const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
182 const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
183 const composerEditorRef = useRef<ComposerEditorHandle>(null);
184 const composerOverlayRef = useRef<View>(null);
185 const listRef = useRef<LegendListRef>(null);
186 const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
187 const selectedThreadKeyRef = useRef(selectedThreadKey);
188 const lastScrolledAnchorMessageIdRef = useRef<MessageId | null>(null);
189 const [composerExpanded, setComposerExpanded] = useState(false);
190 const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
191 const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
192 const contentPresentationKind = props.contentPresentation.kind;
193 // The raw sync status enters "synchronizing" on every full fetch, cached or
194 // not. Whether messages are already on screen decides the pill label: no
195 // data yet → "Loading messages", cached data reconciling → "Syncing".
196 const threadSyncPhase = (() => {
197 switch (props.threadSyncStatus) {
198 case "empty":
199 case "cached":
200 case "synchronizing":
201 if (contentPresentationKind === "ready") {
202 return "syncing" as const;
203 }
204 return contentPresentationKind === "loading" ? ("loading" as const) : null;
205 default:
206 return null;
207 }
208 })();
209 const selectedThreadFeed = props.selectedThreadFeed;
210 const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
211 const composerOverlapHeight = composerChrome + composerBottomInset;
212 const estimatedOverlayHeight = composerOverlapHeight;
213 // The overlay's measured height includes the home-indicator inset (the
214 // composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
215 // UIKit add the safe-area bottom to the content inset AGAIN — leaving a
216 // dead strip between the resting content and the composer. Report the
217 // overlay height minus the safe area; UIKit adds it back, and ThreadFeed
218 // hands LegendList the same delta via contentInsetEndStaticAdjustment so
219 // its end-scroll math matches the real resting position.
220 const nativeInsetOvercount =
221 props.usesAutomaticContentInsets === true && Platform.OS === "ios" ? insets.bottom : 0;
222 const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
223 listRef,
224 composerOverlayRef,
225 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
226 -nativeInsetOvercount,
227 );
228 const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
229 const showContent = props.showContent ?? true;
230 const layoutVariant = props.layoutVariant ?? "compact";
231 const isSplitLayout = layoutVariant === "split";
232 const contentMaxWidth = isSplitLayout ? CHAT_CONTENT_MAX_WIDTH : undefined;
233 const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
234 useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
235 const selectedProviderSkills = useMemo(
236 () =>
237 props.serverConfig?.providers.find((provider) => provider.instanceId === selectedInstanceId)
238 ?.skills ?? [],
239 [props.serverConfig, selectedInstanceId],
240 );
241​
242 useLayoutEffect(() => {
243 selectedThreadKeyRef.current = selectedThreadKey;
244 }, [selectedThreadKey]);
245​
246 const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
247 const lastDispatchedVisitRef = useRef<string | null>(null);
248 const selectedThreadId = props.selectedThread.id;
249 const selectedThreadUpdatedAt = props.selectedThread.updatedAt;
250 const selectedThreadLastVisitedAt = props.selectedThread.lastVisitedAt;
251 useEffect(() => {
252 // Records the server-side visited watermark while the thread is on
253 // screen (mirror of web ChatView), so the "Done" marker clears on every
254 // device. Field absent → the server predates visited tracking.
255 if (selectedThreadLastVisitedAt === undefined) return;
256 const threadUpdatedAtMs = Date.parse(selectedThreadUpdatedAt);
257 if (Number.isNaN(threadUpdatedAtMs)) return;
258 const lastVisitedAtMs = selectedThreadLastVisitedAt
259 ? Date.parse(selectedThreadLastVisitedAt)
260 : NaN;
261 if (!Number.isNaN(lastVisitedAtMs) && lastVisitedAtMs >= threadUpdatedAtMs) return;
262 // Dedupe per watermark — the effect re-runs before the command echo lands.
263 const dispatchKey = `${selectedThreadKey}:${selectedThreadUpdatedAt}`;
264 if (lastDispatchedVisitRef.current === dispatchKey) return;
265 lastDispatchedVisitRef.current = dispatchKey;
266 void visitThread({
267 environmentId: props.environmentId,
268 input: { threadId: selectedThreadId, visitedAt: selectedThreadUpdatedAt },
269 });
270 }, [
271 props.environmentId,
272 selectedThreadId,
273 selectedThreadKey,
274 selectedThreadLastVisitedAt,
275 selectedThreadUpdatedAt,
276 visitThread,
277 ]);
278​
279 useEffect(() => {
280 setAnchorMessageId(null);
281 lastScrolledAnchorMessageIdRef.current = null;
282 freeze.set(false);
283 }, [freeze, selectedThreadKey]);
284​
285 useEffect(() => {
286 if (
287 anchorMessageId === null ||
288 lastScrolledAnchorMessageIdRef.current === anchorMessageId ||
289 contentPresentationKind !== "ready" ||
290 !selectedThreadFeed.some((entry) => entry.type === "message" && entry.id === anchorMessageId)
291 ) {
292 return;
293 }
294​
295 const targetThreadKey = selectedThreadKey;
296 const frame = requestAnimationFrame(() => {
297 if (selectedThreadKeyRef.current !== targetThreadKey) {
298 return;
299 }
300 lastScrolledAnchorMessageIdRef.current = anchorMessageId;
301 // Wait for the keyboard dismissal (started by blur() on send) to finish
302 // before scrolling: scrollMessageToEnd freezes keyboard-driven inset
303 // updates while it runs, and a close event swallowed by that freeze
304 // leaves the keyboard padding permanently applied — overshooting the
305 // anchor and leaving a phantom bottom inset once the reply streams in.
306 void KeyboardController.dismiss()
307 .then(() => {
308 if (
309 selectedThreadKeyRef.current !== targetThreadKey ||
310 lastScrolledAnchorMessageIdRef.current !== anchorMessageId
311 ) {
312 return;
313 }
314 return scrollMessageToEnd({ animated: true, closeKeyboard: false });
315 })
316 .catch(() => {
317 if (
318 selectedThreadKeyRef.current !== targetThreadKey ||
319 lastScrolledAnchorMessageIdRef.current !== anchorMessageId
320 ) {
321 return;
322 }
323 lastScrolledAnchorMessageIdRef.current = null;
324 freeze.set(false);
325 });
326 });
327 return () => cancelAnimationFrame(frame);
328 }, [
329 anchorMessageId,
330 freeze,
331 contentPresentationKind,
332 selectedThreadFeed,
333 scrollMessageToEnd,
334 selectedThreadKey,
335 ]);
336​
337 const handleSendMessage = useCallback(async () => {
338 const targetThreadKey = selectedThreadKey;
339 const messageId = await props.onSendMessage();
340 if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
341 return messageId;
342 }
343​
344 setAnchorMessageId(messageId);
345 composerEditorRef.current?.blur();
346 return messageId;
347 }, [props.onSendMessage, selectedThreadKey]);
348​
349 const collapseComposer = useCallback(() => {
350 composerEditorRef.current?.blur();
351 }, []);
352​
353 const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
354 feedTouchStartRef.current = {
355 pageX: event.nativeEvent.pageX,
356 pageY: event.nativeEvent.pageY,
357 };
358 }, []);
359​
360 const handleFeedTouchMove = useCallback((event: GestureResponderEvent) => {
361 const start = feedTouchStartRef.current;
362 if (!start) {
363 return;
364 }
365 const deltaX = event.nativeEvent.pageX - start.pageX;
366 const deltaY = event.nativeEvent.pageY - start.pageY;
367 if (Math.hypot(deltaX, deltaY) > 8) {
368 feedTouchStartRef.current = null;
369 }
370 }, []);
371​
372 const handleFeedTouchEnd = useCallback(() => {
373 if (feedTouchStartRef.current) {
374 collapseComposer();
375 }
376 feedTouchStartRef.current = null;
377 }, [collapseComposer]);
378​
379 const handleFeedTouchCancel = useCallback(() => {
380 feedTouchStartRef.current = null;
381 }, []);
382​
383 return (
384 <View className="flex-1">
385 {showContent ? (
386 <View
387 className="flex-1"
388 onTouchStart={handleFeedTouchStart}
389 onTouchMove={handleFeedTouchMove}
390 onTouchEnd={handleFeedTouchEnd}
391 onTouchCancel={handleFeedTouchCancel}
392 >
393 <ThreadFeed
394 key={props.selectedThread.id}
395 environmentId={props.environmentId}
396 threadId={props.selectedThread.id}
397 workspaceRoot={props.threadCwd}
398 feed={props.selectedThreadFeed}
399 contentPresentation={props.contentPresentation}
400 agentLabel={agentLabel}
401 threadTitle={props.selectedThread.title}
402 latestRun={props.activityRun}
403 activeWorkStartedAt={props.activeWorkStartedAt}
404 listRef={listRef}
405 freeze={freeze}
406 anchorMessageId={anchorMessageId}
407 contentInsetEndAdjustment={contentInsetEndAdjustment}
408 contentTopInset={0}
409 contentBottomInset={estimatedOverlayHeight}
410 contentMaxWidth={contentMaxWidth}
411 topAccessory={
412 <ThreadRelationshipsBanner
413 environmentId={props.environmentId}
414 threadId={props.selectedThread.id}
415 />
416 }
417 layoutVariant={layoutVariant}
418 usesAutomaticContentInsets={props.usesAutomaticContentInsets}
419 onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
420 skills={selectedProviderSkills}
421 />
422 </View>
423 ) : (
424 <View className="flex-1" />
425 )}
426​
427 {/* Floating composer — sticks to keyboard via KeyboardStickyView */}
428 {showContent ? (
429 <KeyboardStickyView
430 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
431 offset={{ closed: 0, opened: 0 }}
432 >
433 {/* No paddingTop here: the overlay's measured height becomes the
434 list's bottom inset, so any padding above the pill/composer
435 pushes the resting content floor up by the same amount. */}
436 <View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
437 <View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
438 <ThreadQueueControl
439 environmentId={props.environmentId}
440 threadId={props.selectedThread.id}
441 />
442​
443 {props.activePendingApproval || props.activePendingUserInput ? (
444 <Animated.View
445 className="shrink-0 gap-3 px-4 pb-3"
446 entering={FadeInDown.duration(220)}
447 exiting={FadeOut.duration(140)}
448 >
449 {props.activePendingApproval ? (
450 <PendingApprovalCard
451 approval={props.activePendingApproval}
452 respondingApprovalId={props.respondingApprovalId}
453 onRespond={props.onRespondToApproval}
454 />
455 ) : null}
456 {props.activePendingUserInput ? (
457 <PendingUserInputCard
458 pendingUserInput={props.activePendingUserInput}
459 drafts={props.activePendingUserInputDrafts}
460 answers={props.activePendingUserInputAnswers}
461 respondingUserInputId={props.respondingUserInputId}
462 onSelectOption={props.onSelectUserInputOption}
463 onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
464 onSubmit={props.onSubmitUserInput}
465 />
466 ) : null}
467 </Animated.View>
468 ) : null}
469 </View>
470​
471 <ThreadComposer
472 editorRef={composerEditorRef}
473 draftMessage={props.draftMessage}
474 draftAttachments={props.draftAttachments}
475 placeholder="Ask the repo agent, or run a command…"
476 contentMaxWidth={contentMaxWidth}
477 connectionState={props.connectionStateLabel}
478 connectionError={props.connectionError}
479 environmentLabel={props.environmentLabel}
480 threadSyncPhase={threadSyncPhase}
481 selectedThread={props.selectedThread}
482 serverConfig={props.serverConfig}
483 queueCount={props.selectedThreadQueueCount}
484 activeThreadBusy={props.activeThreadBusy}
485 canStopThread={props.canStopThread}
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});