Open History to see the last commit
1import { Button } from "../../components/ui/Button";
2import { QuestionAttachments } from "./QuestionAttachments";
3import type { EnvironmentId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";
4import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";
5import {
6 markdownProseDirection,
7 textDirection,
8 type TextDirection,
9} from "@t3tools/shared/textDirection";
10import { useNavigation } from "@react-navigation/native";
11import { useRef } from "react";
12import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native";
13import Animated, {
14 useAnimatedStyle,
15 useSharedValue,
16 type DerivedValue,
17 type SharedValue,
18} from "react-native-reanimated";
19
20import { SymbolView } from "../../components/ui/AppSymbol";
21import { AppText as Text } from "../../components/ui/AppText";
22import { ControlPill } from "../../components/ui/ControlPill";
23import { cn } from "../../lib/cn";
24import { resolveMarkdownLinkPresentation } from "../../lib/markdownLinks";
25import { SelectableMarkdownText } from "../../native/SelectableMarkdownText";
26import { useOpenPullRequest } from "../../native/useOpenPullRequest";
27import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview";
28import {
29 fileRoutePathSegments,
30 resolveFileLinkPath,
31 resolveWorkspaceRelativeFilePath,
32} from "../files/filePath";
33import { useLiveThreadLinkLabels } from "../../state/entities";
34import {
35 isPendingUserInputOptionSelected,
36 type PendingUserInputDraftAnswer,
37} from "@t3tools/client-runtime/state/pending-user-input";
38import type { PendingUserInput } from "../../lib/threadActivity";
39
40export interface PendingUserInputCardProps {
41 readonly environmentId: EnvironmentId;
42 readonly threadId: ThreadId;
43 readonly workspaceRoot: string | null;
44 readonly canOperateThread: boolean;
45 readonly pendingUserInput: PendingUserInput;
46 readonly maxHeight: DerivedValue<number>;
47 readonly collapsed: boolean;
48 readonly onToggleCollapsed: () => void;
49 readonly onStopThread?: () => void;
50 readonly cardProgress: SharedValue<number>;
51 readonly cardCoverage: SharedValue<number>;
52 readonly onInputFocusChange?: (focused: boolean) => void;
53 readonly drafts: Record<string, PendingUserInputDraftAnswer>;
54 readonly answers: Record<string, string | ReadonlyArray<string>> | null;
55 readonly respondingUserInputId: RuntimeRequestId | null;
56 readonly onSelectOption: (
57 requestId: RuntimeRequestId,
58 question: ThreadUserInputQuestion,
59 value: string,
60 ) => void;
61 readonly onChangeCustomAnswer: (
62 requestId: RuntimeRequestId,
63 questionId: string,
64 customAnswer: string,
65 ) => void;
66 readonly onSubmit: () => Promise<unknown>;
67 readonly onDismiss: () => Promise<unknown>;
68}
69
70function proseDirectionStyle(text: string, setDirection: TextDirection | undefined) {
71 const direction = textDirection(text);
72 return {
73 ...(direction ? { direction, writingDirection: direction } : null),
74 textAlign: (direction === "rtl") === (setDirection === "rtl") ? "left" : "right",
75 } as const;
76}
77
78function QuestionText(props: {
79 readonly markdown: string;
80 readonly environmentId: EnvironmentId;
81 readonly threadId: ThreadId;
82 readonly workspaceRoot: string | null;
83 readonly setDirection: TextDirection | undefined;
84}) {
85 const styles = useMarkdownPreviewStyles();
86 const markdown = useLiveThreadLinkLabels(props.markdown, props.environmentId);
87 const navigation = useNavigation();
88 const openPullRequest = useOpenPullRequest();
89 const openLink = (href: string) => {
90 const link = resolveMarkdownLinkPresentation(href);
91 if (link.kind !== "file") {
92 void openPullRequest(href);
93 return;
94 }
95 const path = resolveFileLinkPath(props.workspaceRoot, link.path);
96 if (path === null) return;
97 navigation.navigate("ThreadFile", {
98 environmentId: String(props.environmentId),
99 threadId: String(props.threadId),
100 path: fileRoutePathSegments(
101 resolveWorkspaceRelativeFilePath(props.workspaceRoot, path) ?? path,
102 ),
103 ...(link.line ? { line: String(link.line) } : {}),
104 });
105 };
106 return (
107 <SelectableMarkdownText
108 markdown={markdown}
109 textStyle={styles.nativeTextStyle}
110 writingDirection={markdownProseDirection(markdown)}
111 // Android's renderer aligns relative to each paragraph's direction.
112 textAlign={
113 Platform.OS === "android" ? undefined : props.setDirection === "rtl" ? "right" : "left"
114 }
115 onLinkPress={openLink}
116 />
117 );
118}
119
120export function PendingUserInputCard(props: PendingUserInputCardProps) {
121 const questionCount = props.pendingUserInput.questions.length;
122 const canRespond = props.pendingUserInput.responseCapability !== "not_resumable";
123 const isResponding = props.respondingUserInputId === props.pendingUserInput.requestId;
124 const responseDisabled = !canRespond || isResponding;
125 const setDirection = markdownProseDirection(
126 props.pendingUserInput.questions
127 .flatMap((question) => [
128 question.header,
129 question.question,
130 ...question.options.flatMap((option) => [option.label, option.description ?? ""]),
131 ])
132 .join(" "),
133 );
134
135 const { cardCoverage, cardProgress, maxHeight } = props;
136 const barHeightRef = useRef(0);
137 const cardHeightRef = useRef(0);
138 const cardHeight = useSharedValue(0);
139 const notifyCoverage = () => {
140 // The card resizes with the keyboard every frame, so easing each sample would leave the
141 // feed inset and floating controls trailing it.
142 cardCoverage.set(Math.max(0, cardHeightRef.current - barHeightRef.current));
143 };
144 const handleBarLayout = (event: LayoutChangeEvent) => {
145 barHeightRef.current = event.nativeEvent.layout.height;
146 notifyCoverage();
147 };
148 const handleCardLayout = (event: LayoutChangeEvent) => {
149 cardHeightRef.current = event.nativeEvent.layout.height;
150 cardHeight.set(event.nativeEvent.layout.height);
151 notifyCoverage();
152 };
153 const cardAnimatedStyle = useAnimatedStyle(() => {
154 const progress = cardProgress.value;
155 const travel = Platform.OS === "android" ? cardCoverage.value : cardHeight.value;
156 return {
157 maxHeight: maxHeight.value,
158 opacity:
159 Platform.OS === "android"
160 ? Math.min(1, (progress * cardHeight.value) / Math.max(1, cardHeight.value - travel))
161 : 1,
162 transform: [{ translateY: (1 - progress) * travel }],
163 };
164 });
165 // Android hit-tests inside the parent; its height is also the space the card takes below the feed.
166 const androidBoundsStyle = useAnimatedStyle(() => ({
167 paddingTop: cardCoverage.value * cardProgress.value,
168 }));
169 const overlayHeightStyle = useAnimatedStyle(() => ({ height: maxHeight.value }));
170
171 const bar = (
172 <View
173 onLayout={handleBarLayout}
174 pointerEvents={props.collapsed ? "auto" : "none"}
175 accessibilityElementsHidden={!props.collapsed}
176 importantForAccessibility={props.collapsed ? "auto" : "no-hide-descendants"}
177 className="flex-row items-center gap-2 rounded-full border border-border bg-card-alt py-1.5 pl-4 pr-1.5"
178 >
179 <Pressable
180 accessibilityRole="button"
181 accessibilityLabel={`Expand user input, ${questionCount} question${
182 questionCount === 1 ? "" : "s"
183 }`}
184 onPress={props.onToggleCollapsed}
185 className="min-h-10 flex-1 flex-row items-center gap-2 active:opacity-70"
186 >
187 <Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-foreground-secondary">
188 User input needed
189 </Text>
190 <Text className="font-sans text-xs text-foreground-muted">
191 {questionCount} question{questionCount === 1 ? "" : "s"}
192 </Text>
193 <View className="flex-1" />
194 <SymbolView
195 name="chevron.up"
196 size={12}
197 tintColorClassName={"accent-icon-subtle"}
198 type="monochrome"
199 />
200 </Pressable>
201 {props.onStopThread ? (
202 <ControlPill
203 accessibilityLabel="Stop"
204 icon="stop.fill"
205 variant="danger"
206 className="h-9 w-9"
207 disabled={!props.canOperateThread}
208 onPress={props.onStopThread}
209 />
210 ) : null}
211 </View>
212 );
213 const card = (
214 <Animated.View
215 onLayout={handleCardLayout}
216 pointerEvents={props.collapsed ? "none" : "auto"}
217 accessibilityElementsHidden={props.collapsed}
218 importantForAccessibility={props.collapsed ? "no-hide-descendants" : "auto"}
219 className="overflow-hidden gap-2.5 rounded-[20px] border border-border bg-card-alt p-4"
220 style={cardAnimatedStyle}
221 >
222 <Pressable
223 accessibilityRole="button"
224 accessibilityLabel="Collapse user input"
225 onPress={props.onToggleCollapsed}
226 className="flex-row items-start gap-2"
227 >
228 <View className="flex-1 gap-2.5">
229 <Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-foreground-secondary">
230 User input needed
231 </Text>
232 <Text className="font-t3-bold text-lg text-foreground">Fill in the pending answers</Text>
233 </View>
234 <View className="h-8 w-8 items-center justify-center rounded-full bg-subtle-strong">
235 <SymbolView
236 name="chevron.down"
237 size={13}
238 tintColorClassName={"accent-icon-subtle"}
239 type="monochrome"
240 />
241 </View>
242 </Pressable>
243 <ScrollView
244 bounces={false}
245 className="min-h-0"
246 contentContainerClassName="gap-2.5 pb-1"
247 keyboardShouldPersistTaps="handled"
248 nestedScrollEnabled
249 showsVerticalScrollIndicator
250 style={{ flexShrink: 1 }}
251 >
252 {!canRespond ? (
253 <Text className="font-sans text-sm leading-5 text-foreground-muted">
254 The provider process for this request is no longer available. Interrupt or restart the
255 run to continue.
256 </Text>
257 ) : null}
258 {props.pendingUserInput.questions.map((question) => {
259 const draft = props.drafts[question.id];
260 return (
261 <View key={question.id} className="gap-2 pt-1">
262 <Text
263 className="font-t3-bold text-xs uppercase tracking-[1px] text-foreground-muted"
264 style={proseDirectionStyle(question.header, setDirection)}
265 >
266 {question.header}
267 </Text>
268 <QuestionText
269 markdown={question.question}
270 environmentId={props.environmentId}
271 threadId={props.threadId}
272 workspaceRoot={props.workspaceRoot}
273 setDirection={setDirection}
274 />
275 <View className="gap-2">
276 {question.options.map((option) => {
277 const optionValue = option.value ?? option.label.trim();
278 const selected = isPendingUserInputOptionSelected(question, draft, optionValue);
279 const description =
280 option.description !== option.label ? option.description : undefined;
281 return (
282 <Pressable
283 key={optionValue}
284 accessibilityRole={question.multiSelect ? "checkbox" : "radio"}
285 accessibilityState={{ checked: selected, disabled: responseDisabled }}
286 disabled={responseDisabled}
287 className={cn(
288 "min-h-12 w-full rounded-2xl border px-3.5 py-3",
289 selected ? "border-primary bg-primary/10" : "border-border bg-input",
290 )}
291 onPress={() =>
292 props.onSelectOption(
293 props.pendingUserInput.requestId,
294 question,
295 optionValue,
296 )
297 }
298 >
299 <View className="min-w-0 flex-1 gap-0.5">
300 <Text
301 className={cn(
302 "font-t3-bold text-sm",
303 selected ? "text-foreground" : "text-foreground-secondary",
304 )}
305 style={proseDirectionStyle(option.label, setDirection)}
306 >
307 {option.label}
308 </Text>
309 {description ? (
310 <Text
311 className="font-sans text-sm leading-5 text-foreground-muted"
312 style={proseDirectionStyle(description, setDirection)}
313 >
314 {description}
315 </Text>
316 ) : null}
317 </View>
318 </Pressable>
319 );
320 })}
321 </View>
322 {question.allowCustomAnswer !== false ? (
323 <QuestionAttachments
324 key={`${props.pendingUserInput.requestId}:${question.id}`}
325 requestId={props.pendingUserInput.requestId}
326 question={question}
327 questions={props.pendingUserInput.questions}
328 disabled={responseDisabled}
329 value={draft?.customAnswer ?? ""}
330 onChangeText={(value) =>
331 props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
332 }
333 onInputFocusChange={props.onInputFocusChange}
334 />
335 ) : null}
336 </View>
337 );
338 })}
339 </ScrollView>
340 <Button
341 label="Submit answers"
342 fullWidth
343 tone={props.answers ? "primary" : "secondary"}
344 disabled={!props.canOperateThread || responseDisabled || props.answers === null}
345 onPress={() => void props.onSubmit()}
346 />
347 {props.pendingUserInput.dismissible ? (
348 <Button
349 label="Dismiss without answering"
350 tone="text"
351 disabled={isResponding}
352 onPress={() => void props.onDismiss()}
353 />
354 ) : null}
355 {!props.canOperateThread ? (
356 <Text className="font-sans text-xs text-foreground-tertiary">
357 This connection cannot submit answers.
358 </Text>
359 ) : null}
360 </Animated.View>
361 );
362 return (
363 <Animated.View
364 className="relative"
365 style={Platform.OS === "android" ? androidBoundsStyle : undefined}
366 >
367 {bar}
368 <Animated.View
369 pointerEvents={props.collapsed ? "none" : "box-none"}
370 className="absolute inset-x-0 bottom-0 justify-end overflow-hidden"
371 style={overlayHeightStyle}
372 >
373 {card}
374 </Animated.View>
375 </Animated.View>
376 );
377}