Open History to see the last commit
1import { type EnvironmentConnectionPhase } from "@v12/client-runtime/connection";
2import type { EnvironmentThreadStatus } from "@v12/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 V12ServerConfig,
15 ThreadId,
16} from "@v12/contracts";
17import { formatElapsed } from "@v12/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: V12ServerConfig | 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="shrink-0 px-4 pb-2 pt-2"
197 entering={FadeInDown.duration(200)}
198 exiting={FadeOut.duration(140)}
199 >
200 <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]">
201 <View className="flex-row items-center gap-2">
202 <View className="flex-row items-center gap-1">
203 <View className="h-1.5 w-1.5 rounded-full bg-neutral-400 dark:bg-neutral-500" />
204 <View className="h-1.5 w-1.5 rounded-full bg-neutral-400/80 dark:bg-neutral-500/80" />
205 <View className="h-1.5 w-1.5 rounded-full bg-neutral-400/60 dark:bg-neutral-500/60" />
206 </View>
207 <Text className="font-v12-medium text-xs text-neutral-600 dark:text-neutral-400">
208 Working for {durationLabel}
209 </Text>
210 </View>
211 </View>
212 </Animated.View>
213 );
214});
215
216export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
217 const insets = useSafeAreaInsets();
218 const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
219 const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
220 const composerEditorRef = useRef<ComposerEditorHandle>(null);
221 const composerOverlayRef = useRef<View>(null);
222 const listRef = useRef<LegendListRef>(null);
223 const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
224 const selectedThreadKeyRef = useRef(selectedThreadKey);
225 const lastScrolledAnchorMessageIdRef = useRef<MessageId | null>(null);
226 const [composerExpanded, setComposerExpanded] = useState(false);
227 const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
228 const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
229 const contentPresentationKind = props.contentPresentation.kind;
230 // The raw sync status enters "synchronizing" on every full fetch, cached or
231 // not. Whether messages are already on screen decides the pill label: no
232 // data yet → "Loading messages", cached data reconciling → "Syncing".
233 const threadSyncPhase = (() => {
234 switch (props.threadSyncStatus) {
235 case "empty":
236 case "cached":
237 case "synchronizing":
238 if (contentPresentationKind === "ready") {
239 return "syncing" as const;
240 }
241 return contentPresentationKind === "loading" ? ("loading" as const) : null;
242 default:
243 return null;
244 }
245 })();
246 const selectedThreadFeed = props.selectedThreadFeed;
247 const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
248 const composerOverlapHeight = composerChrome + composerBottomInset;
249 const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0;
250 const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight;
251 // The overlay's measured height includes the home-indicator inset (the
252 // composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
253 // UIKit add the safe-area bottom to the content inset AGAIN — leaving a
254 // dead strip between the resting content and the composer. Report the
255 // overlay height minus the safe area; UIKit adds it back, and ThreadFeed
256 // hands LegendList the same delta via contentInsetEndStaticAdjustment so
257 // its end-scroll math matches the real resting position.
258 const nativeInsetOvercount =
259 props.usesAutomaticContentInsets === true && Platform.OS === "ios" ? insets.bottom : 0;
260 const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
261 listRef,
262 composerOverlayRef,
263 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
264 -nativeInsetOvercount,
265 );
266 const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
267 const showContent = props.showContent ?? true;
268 const layoutVariant = props.layoutVariant ?? "compact";
269 const isSplitLayout = layoutVariant === "split";
270 const contentMaxWidth = isSplitLayout ? CHAT_CONTENT_MAX_WIDTH : undefined;
271 const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
272 useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
273 const selectedProviderSkills = useMemo(
274 () =>
275 props.serverConfig?.providers.find((provider) => provider.instanceId === selectedInstanceId)
276 ?.skills ?? [],
277 [props.serverConfig, selectedInstanceId],
278 );
279
280 useLayoutEffect(() => {
281 selectedThreadKeyRef.current = selectedThreadKey;
282 }, [selectedThreadKey]);
283
284 useEffect(() => {
285 setAnchorMessageId(null);
286 lastScrolledAnchorMessageIdRef.current = null;
287 freeze.set(false);
288 }, [freeze, selectedThreadKey]);
289
290 useEffect(() => {
291 if (
292 anchorMessageId === null ||
293 lastScrolledAnchorMessageIdRef.current === anchorMessageId ||
294 contentPresentationKind !== "ready" ||
295 !selectedThreadFeed.some((entry) => entry.type === "message" && entry.id === anchorMessageId)
296 ) {
297 return;
298 }
299
300 const targetThreadKey = selectedThreadKey;
301 const frame = requestAnimationFrame(() => {
302 if (selectedThreadKeyRef.current !== targetThreadKey) {
303 return;
304 }
305 lastScrolledAnchorMessageIdRef.current = anchorMessageId;
306 // Wait for the keyboard dismissal (started by blur() on send) to finish
307 // before scrolling: scrollMessageToEnd freezes keyboard-driven inset
308 // updates while it runs, and a close event swallowed by that freeze
309 // leaves the keyboard padding permanently applied — overshooting the
310 // anchor and leaving a phantom bottom inset once the reply streams in.
311 void KeyboardController.dismiss()
312 .then(() => {
313 if (
314 selectedThreadKeyRef.current !== targetThreadKey ||
315 lastScrolledAnchorMessageIdRef.current !== anchorMessageId
316 ) {
317 return;
318 }
319 return scrollMessageToEnd({ animated: true, closeKeyboard: false });
320 })
321 .catch(() => {
322 if (
323 selectedThreadKeyRef.current !== targetThreadKey ||
324 lastScrolledAnchorMessageIdRef.current !== anchorMessageId
325 ) {
326 return;
327 }
328 lastScrolledAnchorMessageIdRef.current = null;
329 freeze.set(false);
330 });
331 });
332 return () => cancelAnimationFrame(frame);
333 }, [
334 anchorMessageId,
335 freeze,
336 contentPresentationKind,
337 selectedThreadFeed,
338 scrollMessageToEnd,
339 selectedThreadKey,
340 ]);
341
342 const handleSendMessage = useCallback(async () => {
343 const targetThreadKey = selectedThreadKey;
344 const messageId = await props.onSendMessage();
345 if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
346 return messageId;
347 }
348
349 setAnchorMessageId(messageId);
350 composerEditorRef.current?.blur();
351 return messageId;
352 }, [props.onSendMessage, selectedThreadKey]);
353
354 const collapseComposer = useCallback(() => {
355 composerEditorRef.current?.blur();
356 }, []);
357
358 const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
359 feedTouchStartRef.current = {
360 pageX: event.nativeEvent.pageX,
361 pageY: event.nativeEvent.pageY,
362 };
363 }, []);
364
365 const handleFeedTouchMove = useCallback((event: GestureResponderEvent) => {
366 const start = feedTouchStartRef.current;
367 if (!start) {
368 return;
369 }
370 const deltaX = event.nativeEvent.pageX - start.pageX;
371 const deltaY = event.nativeEvent.pageY - start.pageY;
372 if (Math.hypot(deltaX, deltaY) > 8) {
373 feedTouchStartRef.current = null;
374 }
375 }, []);
376
377 const handleFeedTouchEnd = useCallback(() => {
378 if (feedTouchStartRef.current) {
379 collapseComposer();
380 }
381 feedTouchStartRef.current = null;
382 }, [collapseComposer]);
383
384 const handleFeedTouchCancel = useCallback(() => {
385 feedTouchStartRef.current = null;
386 }, []);
387
388 return (
389 <View className="flex-1">
390 {showContent ? (
391 <View
392 className="flex-1"
393 onTouchStart={handleFeedTouchStart}
394 onTouchMove={handleFeedTouchMove}
395 onTouchEnd={handleFeedTouchEnd}
396 onTouchCancel={handleFeedTouchCancel}
397 >
398 <ThreadFeed
399 key={props.selectedThread.id}
400 environmentId={props.environmentId}
401 threadId={props.selectedThread.id}
402 workspaceRoot={props.threadCwd}
403 feed={props.selectedThreadFeed}
404 contentPresentation={props.contentPresentation}
405 agentLabel={agentLabel}
406 latestTurn={props.selectedThread.latestTurn}
407 listRef={listRef}
408 freeze={freeze}
409 anchorMessageId={anchorMessageId}
410 contentInsetEndAdjustment={contentInsetEndAdjustment}
411 contentTopInset={0}
412 contentBottomInset={estimatedOverlayHeight}
413 contentMaxWidth={contentMaxWidth}
414 layoutVariant={layoutVariant}
415 usesAutomaticContentInsets={props.usesAutomaticContentInsets}
416 onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
417 skills={selectedProviderSkills}
418 />
419 </View>
420 ) : (
421 <View className="flex-1" />
422 )}
423
424 {/* Floating composer — sticks to keyboard via KeyboardStickyView */}
425 {showContent ? (
426 <KeyboardStickyView
427 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
428 offset={{ closed: 0, opened: 0 }}
429 >
430 {/* No paddingTop here: the overlay's measured height becomes the
431 list's bottom inset, so any padding above the pill/composer
432 pushes the resting content floor up by the same amount. */}
433 <View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
434 <Animated.View
435 className="w-full self-center"
436 layout={LinearTransition.duration(220)}
437 style={{ maxWidth: contentMaxWidth }}
438 >
439 {props.activeWorkStartedAt ? (
440 <WorkingDurationPill startedAt={props.activeWorkStartedAt} />
441 ) : null}
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 </Animated.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 environmentId={props.environmentId}
486 projectCwd={props.projectWorkspaceRoot}
487 bottomInset={composerBottomInset}
488 onChangeDraftMessage={props.onChangeDraftMessage}
489 onPickDraftImages={props.onPickDraftImages}
490 onNativePasteImages={props.onNativePasteImages}
491 onRemoveDraftImage={props.onRemoveDraftImage}
492 onStopThread={props.onStopThread}
493 onSendMessage={handleSendMessage}
494 onReconnectEnvironment={props.onReconnectEnvironment}
495 onUpdateModelSelection={props.onUpdateThreadModelSelection}
496 onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
497 onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
498 onExpandedChange={setComposerExpanded}
499 />
500 </View>
501 </KeyboardStickyView>
502 ) : null}
503 </View>
504 );
505});