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