Open History to see the last commit
1import { type RuntimeRequestId, type ScopedThreadRef } from "@t3tools/contracts";
2import { memo, useEffect, useEffectEvent, useRef, useState } from "react";
3import { useStableCallback } from "~/hooks/useStableCallback";
4import { type PendingUserInput } from "../../session-logic";
5import {
6 derivePendingUserInputProgress,
7 type PendingUserInputDraftAnswer,
8} from "../../pendingUserInput";
9import { CheckIcon } from "lucide-react";
10import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
11import { cn } from "~/lib/utils";
12import { ComposerBanner } from "./ComposerBanner";
13import ChatMarkdown from "../ChatMarkdown";
14
15interface PendingUserInputPanelProps {
16 pendingUserInputs: PendingUserInput[];
17 cwd: string | undefined;
18 threadRef: ScopedThreadRef;
19 disabled?: boolean;
20 respondingRequestIds: RuntimeRequestId[];
21 answers: Record<string, PendingUserInputDraftAnswer>;
22 questionIndex: number;
23 onToggleOption: (questionId: string, optionValue: string) => void;
24 onAdvance: () => void;
25 onDismiss: (requestId: RuntimeRequestId) => void;
26}
27
28export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInputPanel({
29 pendingUserInputs,
30 cwd,
31 threadRef,
32 disabled = false,
33 respondingRequestIds,
34 answers,
35 questionIndex,
36 onToggleOption,
37 onAdvance,
38 onDismiss,
39}: PendingUserInputPanelProps) {
40 if (pendingUserInputs.length === 0) return null;
41 const activePrompt = pendingUserInputs[0];
42 if (!activePrompt) return null;
43
44 return (
45 <ComposerPendingUserInputCard
46 key={activePrompt.requestId}
47 prompt={activePrompt}
48 cwd={cwd}
49 threadRef={threadRef}
50 disabled={disabled}
51 isResponding={respondingRequestIds.includes(activePrompt.requestId)}
52 answers={answers}
53 questionIndex={questionIndex}
54 onToggleOption={onToggleOption}
55 onAdvance={onAdvance}
56 onDismiss={onDismiss}
57 />
58 );
59});
60
61const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard({
62 prompt,
63 cwd,
64 threadRef,
65 disabled,
66 isResponding,
67 answers,
68 questionIndex,
69 onToggleOption,
70 onAdvance,
71 onDismiss,
72}: {
73 prompt: PendingUserInput;
74 cwd: string | undefined;
75 threadRef: ScopedThreadRef;
76 disabled: boolean;
77 isResponding: boolean;
78 answers: Record<string, PendingUserInputDraftAnswer>;
79 questionIndex: number;
80 onToggleOption: (questionId: string, optionValue: string) => void;
81 onAdvance: () => void;
82 onDismiss: (requestId: RuntimeRequestId) => void;
83}) {
84 // Message-mode requests remain answerable after their provider turn ends.
85 const canRespond = prompt.responseCapability !== "not_resumable";
86 const responseDisabled = disabled || isResponding || !canRespond;
87 const autoAdvanceTimerRef = useRef<number | null>(null);
88 // The auto-advance timer fires after the render that armed it.
89 const advance = useStableCallback(onAdvance);
90 const [optimisticSingleSelect, setOptimisticSingleSelect] = useState<{
91 questionId: string;
92 optionValue: string;
93 } | null>(null);
94 const [focusedOption, setFocusedOption] = useState<{
95 questionId: string;
96 optionIndex: number;
97 } | null>(null);
98 const [collapsedQuestionId, setCollapsedQuestionId] = useState<string | null>(null);
99 // The active question keys the shortcut listener, so it must keep its identity across renders.
100 const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);
101 const activeQuestion = progress.activeQuestion;
102 const customAnswerActive = progress.customAnswer.trim().length > 0;
103 // Read here, before the hooks below, so the compiler can keep `activeQuestion` cached.
104 const draftSelectedOptions = activeQuestion?.options.map(
105 (option) =>
106 !customAnswerActive && progress.selectedOptionValues.includes(option.value ?? option.label),
107 );
108 const isCollapsed = collapsedQuestionId !== null && collapsedQuestionId === activeQuestion?.id;
109 const selectedOptionValue = progress.selectedOptionValues.at(-1);
110 const savedOptionMatches = activeQuestion?.options.filter(
111 (option) => (option.value ?? option.label) === selectedOptionValue,
112 );
113 const previewOption = customAnswerActive
114 ? undefined
115 : focusedOption && focusedOption.questionId === activeQuestion?.id
116 ? activeQuestion?.options[focusedOption.optionIndex]
117 : selectedOptionValue === undefined
118 ? activeQuestion?.options[0]
119 : savedOptionMatches?.length === 1
120 ? savedOptionMatches[0]
121 : undefined;
122
123 if (focusedOption && (focusedOption.questionId !== activeQuestion?.id || customAnswerActive)) {
124 setFocusedOption(null);
125 }
126
127 // The optimistic pick is dropped once the draft confirms it or the question moves on.
128 if (
129 optimisticSingleSelect &&
130 activeQuestion &&
131 !activeQuestion.multiSelect &&
132 (optimisticSingleSelect.questionId !== activeQuestion.id ||
133 (!customAnswerActive &&
134 progress.selectedOptionValues.includes(optimisticSingleSelect.optionValue)))
135 ) {
136 setOptimisticSingleSelect(null);
137 }
138
139 // A delayed answer only advances its own question, while permission remains granted.
140 useEffect(() => {
141 const clearAutoAdvance = () => {
142 if (autoAdvanceTimerRef.current !== null) {
143 window.clearTimeout(autoAdvanceTimerRef.current);
144 autoAdvanceTimerRef.current = null;
145 }
146 };
147 if (disabled || activeQuestion?.id === undefined) clearAutoAdvance();
148 return clearAutoAdvance;
149 }, [activeQuestion?.id, disabled]);
150
151 const handleOptionSelection = (questionId: string, optionValue: string, optionIndex: number) => {
152 if (disabled || isResponding) return;
153 setFocusedOption({ questionId, optionIndex });
154 if (activeQuestion?.multiSelect) {
155 onToggleOption(questionId, optionValue);
156 return;
157 }
158 setOptimisticSingleSelect({ questionId, optionValue });
159 onToggleOption(questionId, optionValue);
160 if (autoAdvanceTimerRef.current !== null) {
161 window.clearTimeout(autoAdvanceTimerRef.current);
162 }
163 autoAdvanceTimerRef.current = window.setTimeout(() => {
164 autoAdvanceTimerRef.current = null;
165 advance();
166 }, 200);
167 };
168
169 const selectOptionFromShortcut = useEffectEvent(handleOptionSelection);
170
171 useEffect(() => {
172 if (!activeQuestion || responseDisabled || isCollapsed) return;
173 const handler = (event: globalThis.KeyboardEvent) => {
174 if (event.metaKey || event.ctrlKey || event.altKey) return;
175 const target = event.target;
176 if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
177 return;
178 }
179 if (
180 target instanceof HTMLElement &&
181 target.closest('[contenteditable]:not([contenteditable="false"])')
182 ) {
183 return;
184 }
185 const digit = Number.parseInt(event.key, 10);
186 if (Number.isNaN(digit) || digit < 1 || digit > 9) return;
187 const optionIndex = digit - 1;
188 if (optionIndex >= activeQuestion.options.length) return;
189 const option = activeQuestion.options[optionIndex];
190 if (!option) return;
191 event.preventDefault();
192 selectOptionFromShortcut(activeQuestion.id, option.value ?? option.label, optionIndex);
193 };
194 document.addEventListener("keydown", handler);
195 return () => document.removeEventListener("keydown", handler);
196 }, [activeQuestion, isCollapsed, responseDisabled]);
197
198 if (!activeQuestion) {
199 return null;
200 }
201
202 return (
203 <Collapsible
204 open={!isCollapsed}
205 onOpenChange={(open) => {
206 setCollapsedQuestionId(open ? null : activeQuestion.id);
207 }}
208 >
209 <CollapsibleTrigger
210 render={<ComposerBanner.Row render={<button type="button" />} />}
211 title={
212 isCollapsed ? "Show the question and its options" : "Hide the question and its options"
213 }
214 data-pending-user-input-toggle={isCollapsed ? "collapsed" : "expanded"}
215 >
216 <ComposerBanner.Icon />
217 <ComposerBanner.Content>
218 <span className="shrink-0 font-medium text-muted-foreground">
219 {activeQuestion.header}
220 </span>
221 {isCollapsed ? (
222 <span className="min-w-0 flex-1 truncate text-secondary-label">
223 {activeQuestion.question}
224 </span>
225 ) : null}
226 </ComposerBanner.Content>
227 <ComposerBanner.Actions>
228 {prompt.questions.length > 1 ? (
229 <span className="text-3xs font-medium text-muted-foreground tabular-nums">
230 {questionIndex + 1}/{prompt.questions.length}
231 </span>
232 ) : null}
233 <ComposerBanner.ToggleIcon expanded={!isCollapsed} />
234 {prompt.dismissible ? (
235 <ComposerBanner.Dismiss
236 render={<span role="button" tabIndex={0} />}
237 aria-label="Dismiss question without answering"
238 title="Dismiss question without answering"
239 disabled={isResponding}
240 data-pending-user-input-dismiss
241 onClick={(event) => {
242 event.preventDefault();
243 event.stopPropagation();
244 onDismiss(prompt.requestId);
245 }}
246 onKeyDown={(event) => {
247 if (event.key !== "Enter" && event.key !== " ") return;
248 event.preventDefault();
249 event.stopPropagation();
250 onDismiss(prompt.requestId);
251 }}
252 />
253 ) : null}
254 </ComposerBanner.Actions>
255 </CollapsibleTrigger>
256 <CollapsiblePanel>
257 <ComposerBanner.Scroll>
258 <ComposerBanner.Body className="pe-1 pb-1 wrap-anywhere">
259 <ChatMarkdown
260 text={activeQuestion.question}
261 cwd={cwd}
262 threadRef={threadRef}
263 className="text-foreground/85"
264 />
265 {activeQuestion.multiSelect ? (
266 <p className="mt-1 text-secondary-label text-xs">Select one or more options.</p>
267 ) : null}
268 <div className="mt-2 space-y-0.5">
269 {activeQuestion.options.map((option, index) => {
270 const optionValue = option.value ?? option.label;
271 const isOptimisticallySelected =
272 optimisticSingleSelect?.questionId === activeQuestion.id &&
273 optimisticSingleSelect.optionValue === optionValue;
274 const isSelected =
275 isOptimisticallySelected || draftSelectedOptions?.[index] === true;
276 const shortcutKey = index < 9 ? index + 1 : null;
277 const className = cn(
278 "group flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left outline-none transition-colors duration-150 focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary/25",
279 isSelected
280 ? "bg-muted/55 text-foreground"
281 : "bg-transparent text-foreground/85 hover:bg-muted/30",
282 (disabled || isResponding) && "opacity-50 cursor-not-allowed",
283 !disabled && !isResponding && "cursor-pointer",
284 );
285 const content = (
286 <>
287 <div className="min-w-0 flex-1 flex flex-col gap-0.5">
288 <span className="text-sm font-medium">{option.label}</span>
289 {option.description && option.description !== option.label ? (
290 <span className="text-secondary-label text-2xs">{option.description}</span>
291 ) : null}
292 </div>
293 {isSelected ? (
294 <CheckIcon className="size-3.5 shrink-0 text-primary" />
295 ) : shortcutKey !== null ? (
296 <kbd
297 className={cn(
298 "flex size-5 shrink-0 items-center justify-center text-3xs font-medium text-muted-foreground tabular-nums",
299 )}
300 >
301 {shortcutKey}
302 </kbd>
303 ) : null}
304 </>
305 );
306 return (
307 <button
308 // Options keep their positions within a question and may share answer values.
309 // oxlint-disable-next-line react/no-array-index-key
310 key={`${activeQuestion.id}:${index}`}
311 type="button"
312 disabled={disabled || isResponding}
313 onMouseEnter={() =>
314 setFocusedOption({ questionId: activeQuestion.id, optionIndex: index })
315 }
316 onFocus={() =>
317 setFocusedOption({ questionId: activeQuestion.id, optionIndex: index })
318 }
319 onClick={() => {
320 handleOptionSelection(activeQuestion.id, optionValue, index);
321 }}
322 className={className}
323 >
324 {content}
325 </button>
326 );
327 })}
328 </div>
329 {previewOption?.preview?.trim() ? (
330 <section
331 aria-label={`Preview: ${previewOption.label}`}
332 className="mt-2 min-w-0 rounded-md border border-border/60 bg-muted/25 p-2.5"
333 >
334 <p className="mb-1.5 text-3xs font-medium text-muted-foreground">
335 Preview · {previewOption.label}
336 </p>
337 <ChatMarkdown
338 key={`${activeQuestion.id}:${activeQuestion.options.indexOf(previewOption)}`}
339 text={previewOption.preview}
340 cwd={cwd}
341 threadRef={threadRef}
342 parseRawHtml={false}
343 />
344 </section>
345 ) : null}
346 </ComposerBanner.Body>
347 </ComposerBanner.Scroll>
348 </CollapsiblePanel>
349 </Collapsible>
350 );
351});