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

ThreadDetailScreen.tsx

329 lines12.7 KB

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 onStopThread: () => Promise<void>;
71 readonly onSendMessage: () => void;
72 readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => Promise<void>;
73 readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => Promise<void>;
74 readonly onUpdateThreadInteractionMode: (
75 interactionMode: ProviderInteractionMode,
76 ) => Promise<void>;
77 readonly onRespondToApproval: (
78 requestId: ApprovalRequestId,
79 decision: ProviderApprovalDecision,
80 ) => Promise<void>;
81 readonly onSelectUserInputOption: (
82 requestId: ApprovalRequestId,
83 questionId: string,
84 label: string,
85 ) => void;
86 readonly onChangeUserInputCustomAnswer: (
87 requestId: ApprovalRequestId,
88 questionId: string,
89 customAnswer: string,
90 ) => void;
91 readonly onSubmitUserInput: () => Promise<void>;
92 readonly showContent?: boolean;
94​
95function latestStreamingAssistantMessage(
96 feed: ReadonlyArray<ThreadFeedEntry>,
97): { readonly id: string; readonly textLength: number } | null {
98 for (let index = feed.length - 1; index >= 0; index -= 1) {
99 const entry = feed[index];
100 if (entry?.type !== "message") {
101 continue;
102 }
103 if (entry.message.role !== "assistant" || !entry.message.streaming) {
104 continue;
105 }
106 return {
107 id: entry.message.id,
108 textLength: entry.message.text.length,
109 };
110 }
111​
112 return null;
114​
115function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedEntry>) {
116 const lastStreamingAssistantRef = useRef<{
117 readonly id: string;
118 readonly textLength: number;
119 } | null>(null);
120 const lastStreamHapticAtRef = useRef(0);
121 const hydratedRef = useRef(false);
122 const previousThreadIdRef = useRef(threadId);
123​
124 useEffect(() => {
125 if (previousThreadIdRef.current !== threadId) {
126 previousThreadIdRef.current = threadId;
127 hydratedRef.current = false;
128 }
129​
130 const latestStreamingMessage = latestStreamingAssistantMessage(feed);
131​
132 if (!hydratedRef.current) {
133 hydratedRef.current = true;
134 lastStreamingAssistantRef.current = latestStreamingMessage;
135 return;
136 }
137​
138 if (!latestStreamingMessage) {
139 lastStreamingAssistantRef.current = null;
140 return;
141 }
142​
143 const previousStreamingMessage = lastStreamingAssistantRef.current;
144 lastStreamingAssistantRef.current = latestStreamingMessage;
145​
146 const isNewStream = previousStreamingMessage?.id !== latestStreamingMessage.id;
147 const textGrew =
148 previousStreamingMessage?.id === latestStreamingMessage.id &&
149 latestStreamingMessage.textLength > previousStreamingMessage.textLength;
150​
151 if (!isNewStream && !textGrew) {
152 return;
153 }
154​
155 const now = Date.now();
156 if (!isNewStream && now - lastStreamHapticAtRef.current < 320) {
157 return;
158 }
159​
160 lastStreamHapticAtRef.current = now;
161 void Haptics.selectionAsync();
162 }, [threadId, feed]);
164​
165const WORKING_INDICATOR_HEIGHT = 44;
166​
167const WorkingDurationPill = memo(function WorkingDurationPill(props: {
168 readonly startedAt: string;
169}) {
170 const [nowMs, setNowMs] = useState(() => Date.now());
171​
172 useEffect(() => {
173 const intervalId = setInterval(() => {
174 setNowMs(Date.now());
175 }, 1_000);
176 return () => clearInterval(intervalId);
177 }, [props.startedAt]);
178​
179 const durationLabel = formatElapsed(props.startedAt, new Date(nowMs).toISOString()) ?? "0s";
180​
181 return (
182 <View className="px-4 pb-2" style={{ flexShrink: 0 }}>
183 <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]">
184 <View className="flex-row items-center gap-2">
185 <View className="flex-row items-center gap-1">
186 <View className="h-1.5 w-1.5 rounded-full bg-neutral-400 dark:bg-neutral-500" />
187 <View className="h-1.5 w-1.5 rounded-full bg-neutral-400/80 dark:bg-neutral-500/80" />
188 <View className="h-1.5 w-1.5 rounded-full bg-neutral-400/60 dark:bg-neutral-500/60" />
189 </View>
190 <Text className="font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
191 Working for {durationLabel}
192 </Text>
193 </View>
194 </View>
195 </View>
196 );
197});
198​
199export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
200 const { onOpenDrawer } = props;
201​
202 const insets = useSafeAreaInsets();
203 const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
204 const [composerExpanded, setComposerExpanded] = useState(false);
205 const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
206 const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
207 const composerOverlapHeight = composerChrome + composerBottomInset;
208 const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0;
209 const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight;
210 const [measuredOverlayHeight, setMeasuredOverlayHeight] = useState(0);
211 const showContent = props.showContent ?? true;
212 const layoutVariant = props.layoutVariant ?? "compact";
213 const isSplitLayout = layoutVariant === "split";
214 useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
215 const expandedToolbarInset = composerExpanded ? COMPOSER_EXPANDED_TOOLBAR_CHROME : 0;
216 const feedBottomInset =
217 Math.max(estimatedOverlayHeight, measuredOverlayHeight) + expandedToolbarInset + 8;
218​
219 const completeDrawerGesture = useCallback(() => {
220 void Haptics.selectionAsync();
221 onOpenDrawer();
222 }, [onOpenDrawer]);
223​
224 const drawerGestureThreshold = 80;
225 const headerDrawerGesture = useMemo(
226 () =>
227 Gesture.Pan()
228 .enabled(!isSplitLayout)
229 .hitSlop({ left: 0, width: 40 })
230 .activeOffsetX([10, 999])
231 .failOffsetY([-24, 24])
232 .onEnd((event) => {
233 const translationX = Math.max(event.translationX, 0);
234 if (event.y < drawerGestureThreshold && translationX > 56) {
235 runOnJS(completeDrawerGesture)();
236 }
237 }),
238 [completeDrawerGesture, isSplitLayout],
239 );
240​
241 const handleOverlayLayout = useCallback((event: LayoutChangeEvent) => {
242 const nextHeight = Math.ceil(event.nativeEvent.layout.height);
243 setMeasuredOverlayHeight((current) =>
244 Math.abs(current - nextHeight) > 1 ? nextHeight : current,
245 );
246 }, []);
247​
248 return (
249 <GestureDetector gesture={headerDrawerGesture}>
250 <View className="flex-1">
251 {showContent ? (
252 <ThreadFeed
253 threadId={props.selectedThread.id}
254 feed={props.selectedThreadFeed}
255 httpBaseUrl={props.httpBaseUrl}
256 bearerToken={props.bearerToken}
257 agentLabel={agentLabel}
258 contentBottomInset={feedBottomInset}
259 layoutVariant={layoutVariant}
260 composerExpanded={composerExpanded}
261 />
262 ) : (
263 <View style={{ flex: 1 }} />
264 )}
265​
266 {/* Floating composer — sticks to keyboard via KeyboardStickyView */}
267 {showContent ? (
268 <KeyboardStickyView
269 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
270 offset={{ closed: 0, opened: 0 }}
271 >
272 <View onLayout={handleOverlayLayout}>
273 {props.activeWorkStartedAt ? (
274 <WorkingDurationPill startedAt={props.activeWorkStartedAt} />
275 ) : null}
276​
277 {props.activePendingApproval || props.activePendingUserInput ? (
278 <View className="gap-3 px-4 pb-3" style={{ flexShrink: 0 }}>
279 {props.activePendingApproval ? (
280 <PendingApprovalCard
281 approval={props.activePendingApproval}
282 respondingApprovalId={props.respondingApprovalId}
283 onRespond={props.onRespondToApproval}
284 />
285 ) : null}
286 {props.activePendingUserInput ? (
287 <PendingUserInputCard
288 pendingUserInput={props.activePendingUserInput}
289 drafts={props.activePendingUserInputDrafts}
290 answers={props.activePendingUserInputAnswers}
291 respondingUserInputId={props.respondingUserInputId}
292 onSelectOption={props.onSelectUserInputOption}
293 onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
294 onSubmit={props.onSubmitUserInput}
295 />
296 ) : null}
297 </View>
298 ) : null}
299​
300 <ThreadComposer
301 draftMessage={props.draftMessage}
302 draftAttachments={props.draftAttachments}
303 placeholder="Ask the repo agent, or run a command…"
304 connectionState={props.connectionStateLabel}
305 selectedThread={props.selectedThread}
306 serverConfig={props.serverConfig}
307 queueCount={props.selectedThreadQueueCount}
308 activeThreadBusy={props.activeThreadBusy}
309 environmentId={props.environmentId}
310 projectCwd={props.projectWorkspaceRoot}
311 bottomInset={composerBottomInset}
312 onChangeDraftMessage={props.onChangeDraftMessage}
313 onPickDraftImages={props.onPickDraftImages}
314 onNativePasteImages={props.onNativePasteImages}
315 onRemoveDraftImage={props.onRemoveDraftImage}
316 onStopThread={props.onStopThread}
317 onSendMessage={props.onSendMessage}
318 onUpdateModelSelection={props.onUpdateThreadModelSelection}
319 onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
320 onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
321 onExpandedChange={setComposerExpanded}
322 />
323 </View>
324 </KeyboardStickyView>
325 ) : null}
326 </View>
327 </GestureDetector>
328 );
329});