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