Open History to see the last commit
1import type {
2 ApprovalRequestId,
3 EnvironmentId,
4 ModelSelection,
5 OrchestrationThread,
6 ProviderApprovalDecision,
7 ProviderInteractionMode,
8 RuntimeMode,
9 ServerConfig as T3ServerConfig,
10 ThreadId,
11} from "@t3tools/contracts";
12import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
13import * as Haptics from "expo-haptics";
14import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
15import { View, type LayoutChangeEvent } from "react-native";
16import { Gesture, GestureDetector } from "react-native-gesture-handler";
17import { KeyboardStickyView } from "react-native-keyboard-controller";
18import { useSafeAreaInsets } from "react-native-safe-area-context";
19import { runOnJS } from "react-native-reanimated";
20
21import { AppText as Text } from "../../components/AppText";
22import type { StatusTone } from "../../components/StatusPill";
23import type { DraftComposerImageAttachment } from "../../lib/composerImages";
24import type { MobileLayoutVariant } from "../../lib/mobileLayout";
25import type {
26 PendingApproval,
27 PendingUserInput,
28 PendingUserInputDraftAnswer,
29 ThreadFeedEntry,
30} from "../../lib/threadActivity";
31import { PendingApprovalCard } from "./PendingApprovalCard";
32import { PendingUserInputCard } from "./PendingUserInputCard";
33import {
34 COMPOSER_COLLAPSED_CHROME,
35 COMPOSER_EXPANDED_CHROME,
36 COMPOSER_EXPANDED_TOOLBAR_CHROME,
37 ThreadComposer,
38} from "./ThreadComposer";
39import { ThreadFeed } from "./ThreadFeed";
40
41export interface ThreadDetailScreenProps {
42 readonly selectedThread: OrchestrationThread;
43 readonly screenTone: StatusTone;
44 readonly connectionError: string | null;
45 readonly httpBaseUrl: string | null;
46 readonly bearerToken: string | null;
47 readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
48 readonly activeWorkStartedAt: string | null;
49 readonly activePendingApproval: PendingApproval | null;
50 readonly respondingApprovalId: ApprovalRequestId | null;
51 readonly activePendingUserInput: PendingUserInput | null;
52 readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
53 readonly activePendingUserInputAnswers: Record<string, string> | null;
54 readonly respondingUserInputId: ApprovalRequestId | null;
55 readonly draftMessage: string;
56 readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
57 readonly connectionStateLabel: "ready" | "connecting" | "reconnecting" | "disconnected" | "idle";
58 readonly activeThreadBusy: boolean;
59 readonly environmentId: EnvironmentId;
60 readonly projectWorkspaceRoot: string | null;
61 readonly selectedThreadQueueCount: number;
62 readonly serverConfig: T3ServerConfig | null;
63 readonly layoutVariant?: MobileLayoutVariant;
64 readonly onOpenDrawer: () => void;
65 readonly onOpenConnectionEditor: () => void;
66 readonly onChangeDraftMessage: (value: string) => void;
67 readonly onPickDraftImages: () => Promise<void>;
68 readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
69 readonly onRemoveDraftImage: (imageId: string) => void;
70 readonly onRefresh: () => Promise<void>;
71 readonly onStopThread: () => Promise<void>;
72 readonly onSendMessage: () => void;
73 readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => Promise<void>;
74 readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => Promise<void>;
75 readonly onUpdateThreadInteractionMode: (
76 interactionMode: ProviderInteractionMode,
77 ) => Promise<void>;
78 readonly onRespondToApproval: (
79 requestId: ApprovalRequestId,
80 decision: ProviderApprovalDecision,
81 ) => Promise<void>;
82 readonly onSelectUserInputOption: (
83 requestId: ApprovalRequestId,
84 questionId: string,
85 label: string,
86 ) => void;
87 readonly onChangeUserInputCustomAnswer: (
88 requestId: ApprovalRequestId,
89 questionId: string,
90 customAnswer: string,
91 ) => void;
92 readonly onSubmitUserInput: () => Promise<void>;
93 readonly showContent?: boolean;
94}
95
96function latestStreamingAssistantMessage(
97 feed: ReadonlyArray<ThreadFeedEntry>,
98): { readonly id: string; readonly textLength: number } | null {
99 for (let index = feed.length - 1; index >= 0; index -= 1) {
100 const entry = feed[index];
101 if (entry?.type !== "message") {
102 continue;
103 }
104 if (entry.message.role !== "assistant" || !entry.message.streaming) {
105 continue;
106 }
107 return {
108 id: entry.message.id,
109 textLength: entry.message.text.length,
110 };
111 }
112
113 return null;
114}
115
116function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedEntry>) {
117 const lastStreamingAssistantRef = useRef<{
118 readonly id: string;
119 readonly textLength: number;
120 } | null>(null);
121 const lastStreamHapticAtRef = useRef(0);
122 const hydratedRef = useRef(false);
123 const previousThreadIdRef = useRef(threadId);
124
125 useEffect(() => {
126 if (previousThreadIdRef.current !== threadId) {
127 previousThreadIdRef.current = threadId;
128 hydratedRef.current = false;
129 }
130
131 const latestStreamingMessage = latestStreamingAssistantMessage(feed);
132
133 if (!hydratedRef.current) {
134 hydratedRef.current = true;
135 lastStreamingAssistantRef.current = latestStreamingMessage;
136 return;
137 }
138
139 if (!latestStreamingMessage) {
140 lastStreamingAssistantRef.current = null;
141 return;
142 }
143
144 const previousStreamingMessage = lastStreamingAssistantRef.current;
145 lastStreamingAssistantRef.current = latestStreamingMessage;
146
147 const isNewStream = previousStreamingMessage?.id !== latestStreamingMessage.id;
148 const textGrew =
149 previousStreamingMessage?.id === latestStreamingMessage.id &&
150 latestStreamingMessage.textLength > previousStreamingMessage.textLength;
151
152 if (!isNewStream && !textGrew) {
153 return;
154 }
155
156 const now = Date.now();
157 if (!isNewStream && now - lastStreamHapticAtRef.current < 320) {
158 return;
159 }
160
161 lastStreamHapticAtRef.current = now;
162 void Haptics.selectionAsync();
163 }, [threadId, feed]);
164}
165
166const WORKING_INDICATOR_HEIGHT = 44;
167
168const WorkingDurationPill = memo(function WorkingDurationPill(props: {
169 readonly startedAt: string;
170}) {
171 const [nowMs, setNowMs] = useState(() => Date.now());
172
173 useEffect(() => {
174 const intervalId = setInterval(() => {
175 setNowMs(Date.now());
176 }, 1_000);
177 return () => clearInterval(intervalId);
178 }, [props.startedAt]);
179
180 const durationLabel = formatElapsed(props.startedAt, new Date(nowMs).toISOString()) ?? "0s";
181
182 return (
183 <View className="px-4 pb-2" style={{ flexShrink: 0 }}>
184 <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]">
185 <View className="flex-row items-center gap-2">
186 <View className="flex-row items-center gap-1">
187 <View className="h-1.5 w-1.5 rounded-full bg-neutral-400 dark:bg-neutral-500" />
188 <View className="h-1.5 w-1.5 rounded-full bg-neutral-400/80 dark:bg-neutral-500/80" />
189 <View className="h-1.5 w-1.5 rounded-full bg-neutral-400/60 dark:bg-neutral-500/60" />
190 </View>
191 <Text className="font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
192 Working for {durationLabel}
193 </Text>
194 </View>
195 </View>
196 </View>
197 );
198});
199
200export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
201 const { onOpenDrawer, onRefresh } = props;
202
203 const insets = useSafeAreaInsets();
204 const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
205 const composerBottomInset = Math.max(insets.bottom, 12);
206 const [composerExpanded, setComposerExpanded] = useState(false);
207 const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
208 const composerOverlapHeight = composerChrome + composerBottomInset;
209 const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0;
210 const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight;
211 const [measuredOverlayHeight, setMeasuredOverlayHeight] = useState(0);
212 const [refreshing, setRefreshing] = useState(false);
213 const showContent = props.showContent ?? true;
214 const layoutVariant = props.layoutVariant ?? "compact";
215 const isSplitLayout = layoutVariant === "split";
216 useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
217 const expandedToolbarInset = composerExpanded ? COMPOSER_EXPANDED_TOOLBAR_CHROME : 0;
218 const feedBottomInset =
219 Math.max(estimatedOverlayHeight, measuredOverlayHeight) + expandedToolbarInset + 8;
220
221 const completeDrawerGesture = useCallback(() => {
222 void Haptics.selectionAsync();
223 onOpenDrawer();
224 }, [onOpenDrawer]);
225
226 const handleRefresh = useCallback(async (): Promise<void> => {
227 if (refreshing) {
228 return;
229 }
230
231 setRefreshing(true);
232 try {
233 await onRefresh();
234 } finally {
235 setRefreshing(false);
236 }
237 }, [onRefresh, refreshing]);
238
239 const drawerGestureThreshold = 80;
240 const headerDrawerGesture = useMemo(
241 () =>
242 Gesture.Pan()
243 .enabled(!isSplitLayout)
244 .hitSlop({ left: 0, width: 40 })
245 .activeOffsetX([10, 999])
246 .failOffsetY([-24, 24])
247 .onEnd((event) => {
248 const translationX = Math.max(event.translationX, 0);
249 if (event.y < drawerGestureThreshold && translationX > 56) {
250 runOnJS(completeDrawerGesture)();
251 }
252 }),
253 [completeDrawerGesture, isSplitLayout],
254 );
255
256 const handleOverlayLayout = useCallback((event: LayoutChangeEvent) => {
257 const nextHeight = Math.ceil(event.nativeEvent.layout.height);
258 setMeasuredOverlayHeight((current) =>
259 Math.abs(current - nextHeight) > 1 ? nextHeight : current,
260 );
261 }, []);
262
263 return (
264 <GestureDetector gesture={headerDrawerGesture}>
265 <View className="flex-1">
266 {showContent ? (
267 <ThreadFeed
268 threadId={props.selectedThread.id}
269 feed={props.selectedThreadFeed}
270 httpBaseUrl={props.httpBaseUrl}
271 bearerToken={props.bearerToken}
272 agentLabel={agentLabel}
273 contentBottomInset={feedBottomInset}
274 layoutVariant={layoutVariant}
275 composerExpanded={composerExpanded}
276 refreshing={refreshing}
277 onRefresh={handleRefresh}
278 />
279 ) : (
280 <View style={{ flex: 1 }} />
281 )}
282
283 {/* Floating composer — sticks to keyboard via KeyboardStickyView */}
284 {showContent ? (
285 <KeyboardStickyView
286 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
287 offset={{ closed: 0, opened: 0 }}
288 >
289 <View onLayout={handleOverlayLayout}>
290 {props.activeWorkStartedAt ? (
291 <WorkingDurationPill startedAt={props.activeWorkStartedAt} />
292 ) : null}
293
294 {props.activePendingApproval || props.activePendingUserInput ? (
295 <View className="gap-3 px-4 pb-3" style={{ flexShrink: 0 }}>
296 {props.activePendingApproval ? (
297 <PendingApprovalCard
298 approval={props.activePendingApproval}
299 respondingApprovalId={props.respondingApprovalId}
300 onRespond={props.onRespondToApproval}
301 />
302 ) : null}
303 {props.activePendingUserInput ? (
304 <PendingUserInputCard
305 pendingUserInput={props.activePendingUserInput}
306 drafts={props.activePendingUserInputDrafts}
307 answers={props.activePendingUserInputAnswers}
308 respondingUserInputId={props.respondingUserInputId}
309 onSelectOption={props.onSelectUserInputOption}
310 onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
311 onSubmit={props.onSubmitUserInput}
312 />
313 ) : null}
314 </View>
315 ) : null}
316
317 <ThreadComposer
318 draftMessage={props.draftMessage}
319 draftAttachments={props.draftAttachments}
320 placeholder="Ask the repo agent, or run a command…"
321 connectionState={props.connectionStateLabel}
322 selectedThread={props.selectedThread}
323 serverConfig={props.serverConfig}
324 queueCount={props.selectedThreadQueueCount}
325 activeThreadBusy={props.activeThreadBusy}
326 environmentId={props.environmentId}
327 projectCwd={props.projectWorkspaceRoot}
328 bottomInset={composerBottomInset}
329 onChangeDraftMessage={props.onChangeDraftMessage}
330 onPickDraftImages={props.onPickDraftImages}
331 onNativePasteImages={props.onNativePasteImages}
332 onRemoveDraftImage={props.onRemoveDraftImage}
333 onRefresh={props.onRefresh}
334 onStopThread={props.onStopThread}
335 onSendMessage={props.onSendMessage}
336 onUpdateModelSelection={props.onUpdateThreadModelSelection}
337 onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
338 onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
339 onExpandedChange={setComposerExpanded}
340 />
341 </View>
342 </KeyboardStickyView>
343 ) : null}
344 </View>
345 </GestureDetector>
346 );
347});