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 const advance = useStableCallback(onAdvance);
89 const [optimisticSingleSelect, setOptimisticSingleSelect] = useState<{
90 questionId: string;
91 optionValue: string;
92 } | null>(null);
93 const [collapsedQuestionId, setCollapsedQuestionId] = useState<string | null>(null);
94 // Keep question identity stable for its shortcut listener.
95 const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);
96 const activeQuestion = progress.activeQuestion;
97 const customAnswerActive = progress.customAnswer.trim().length > 0;
98 // Read before later hooks to preserve the question's compiler cache.
99 const draftSelectedOptions = activeQuestion?.options.map(
100 (option) =>
101 !customAnswerActive && progress.selectedOptionValues.includes(option.value ?? option.label),
102 );
103 const isCollapsed = collapsedQuestionId !== null && collapsedQuestionId === activeQuestion?.id;
104
105 if (
106 optimisticSingleSelect &&
107 activeQuestion &&
108 !activeQuestion.multiSelect &&
109 (optimisticSingleSelect.questionId !== activeQuestion.id ||
110 (!customAnswerActive &&
111 progress.selectedOptionValues.includes(optimisticSingleSelect.optionValue)))
112 ) {
113 setOptimisticSingleSelect(null);
114 }
115
116 useEffect(() => {
117 const clearAutoAdvance = () => {
118 if (autoAdvanceTimerRef.current !== null) {
119 window.clearTimeout(autoAdvanceTimerRef.current);
120 autoAdvanceTimerRef.current = null;
121 }
122 };
123 if (disabled || activeQuestion?.id === undefined) clearAutoAdvance();
124 return clearAutoAdvance;
125 }, [activeQuestion?.id, disabled]);
126
127 const handleOptionSelection = (questionId: string, optionValue: string) => {
128 if (disabled || isResponding) return;
129 if (activeQuestion?.multiSelect) {
130 onToggleOption(questionId, optionValue);
131 return;
132 }
133 setOptimisticSingleSelect({ questionId, optionValue });
134 onToggleOption(questionId, optionValue);
135 if (autoAdvanceTimerRef.current !== null) {
136 window.clearTimeout(autoAdvanceTimerRef.current);
137 }
138 autoAdvanceTimerRef.current = window.setTimeout(() => {
139 autoAdvanceTimerRef.current = null;
140 advance();
141 }, 200);
142 };
143
144 const selectOptionFromShortcut = useEffectEvent(handleOptionSelection);
145
146 useEffect(() => {
147 if (!activeQuestion || responseDisabled || isCollapsed) return;
148 const handler = (event: globalThis.KeyboardEvent) => {
149 if (event.metaKey || event.ctrlKey || event.altKey) return;
150 const target = event.target;
151 if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
152 return;
153 }
154 if (
155 target instanceof HTMLElement &&
156 target.closest('[contenteditable]:not([contenteditable="false"])')
157 ) {
158 return;
159 }
160 const digit = Number.parseInt(event.key, 10);
161 if (Number.isNaN(digit) || digit < 1 || digit > 9) return;
162 const optionIndex = digit - 1;
163 if (optionIndex >= activeQuestion.options.length) return;
164 const option = activeQuestion.options[optionIndex];
165 if (!option) return;
166 event.preventDefault();
167 selectOptionFromShortcut(activeQuestion.id, option.value ?? option.label);
168 };
169 document.addEventListener("keydown", handler);
170 return () => document.removeEventListener("keydown", handler);
171 }, [activeQuestion, isCollapsed, responseDisabled]);
172
173 if (!activeQuestion) {
174 return null;
175 }
176
177 return (
178 <Collapsible
179 open={!isCollapsed}
180 onOpenChange={(open) => {
181 setCollapsedQuestionId(open ? null : activeQuestion.id);
182 }}
183 >
184 <CollapsibleTrigger
185 render={<ComposerBanner.Row render={<button type="button" />} />}
186 title={
187 isCollapsed ? "Show the question and its options" : "Hide the question and its options"
188 }
189 data-pending-user-input-toggle={isCollapsed ? "collapsed" : "expanded"}
190 >
191 <ComposerBanner.Icon />
192 <ComposerBanner.Content>
193 <span className="shrink-0 font-medium text-muted-foreground">
194 {activeQuestion.header}
195 </span>
196 {isCollapsed ? (
197 <span className="min-w-0 flex-1 truncate text-secondary-label">
198 {activeQuestion.question}
199 </span>
200 ) : null}
201 </ComposerBanner.Content>
202 <ComposerBanner.Actions>
203 {prompt.questions.length > 1 ? (
204 <span className="text-3xs font-medium text-muted-foreground tabular-nums">
205 {questionIndex + 1}/{prompt.questions.length}
206 </span>
207 ) : null}
208 <ComposerBanner.ToggleIcon expanded={!isCollapsed} />
209 {prompt.dismissible ? (
210 <ComposerBanner.Dismiss
211 render={<span role="button" tabIndex={0} />}
212 aria-label="Dismiss question without answering"
213 title="Dismiss question without answering"
214 disabled={isResponding}
215 data-pending-user-input-dismiss
216 onClick={(event) => {
217 event.preventDefault();
218 event.stopPropagation();
219 onDismiss(prompt.requestId);
220 }}
221 onKeyDown={(event) => {
222 if (event.key !== "Enter" && event.key !== " ") return;
223 event.preventDefault();
224 event.stopPropagation();
225 onDismiss(prompt.requestId);
226 }}
227 />
228 ) : null}
229 </ComposerBanner.Actions>
230 </CollapsibleTrigger>
231 <CollapsiblePanel>
232 <ComposerBanner.Scroll>
233 <ComposerBanner.Body className="pe-1 pb-1 wrap-anywhere">
234 <ChatMarkdown
235 text={activeQuestion.question}
236 cwd={cwd}
237 threadRef={threadRef}
238 className="text-foreground/85"
239 />
240 {activeQuestion.multiSelect ? (
241 <p className="mt-1 text-secondary-label text-xs">Select one or more options.</p>
242 ) : null}
243 <div className="mt-2 space-y-0.5">
244 {activeQuestion.options.map((option, index) => {
245 const optionValue = option.value ?? option.label;
246 const isOptimisticallySelected =
247 optimisticSingleSelect?.questionId === activeQuestion.id &&
248 optimisticSingleSelect.optionValue === optionValue;
249 const isSelected =
250 isOptimisticallySelected || draftSelectedOptions?.[index] === true;
251 const shortcutKey = index < 9 ? index + 1 : null;
252 const className = cn(
253 "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",
254 isSelected
255 ? "bg-muted/55 text-foreground"
256 : "bg-transparent text-foreground/85 hover:bg-muted/30",
257 (disabled || isResponding) && "opacity-50 cursor-not-allowed",
258 !disabled && !isResponding && "cursor-pointer",
259 );
260 const content = (
261 <>
262 <div className="min-w-0 flex-1 flex flex-col gap-0.5">
263 <span className="text-sm font-medium">{option.label}</span>
264 {option.description && option.description !== option.label ? (
265 <span className="text-secondary-label text-2xs">{option.description}</span>
266 ) : null}
267 </div>
268 {isSelected ? (
269 <CheckIcon className="size-3.5 shrink-0 text-primary" />
270 ) : shortcutKey !== null ? (
271 <kbd
272 className={cn(
273 "flex size-5 shrink-0 items-center justify-center text-3xs font-medium text-muted-foreground tabular-nums",
274 )}
275 >
276 {shortcutKey}
277 </kbd>
278 ) : null}
279 </>
280 );
281 return (
282 <button
283 key={`${activeQuestion.id}:${optionValue}`}
284 type="button"
285 disabled={disabled || isResponding}
286 onClick={() => {
287 handleOptionSelection(activeQuestion.id, optionValue);
288 }}
289 className={className}
290 >
291 {content}
292 </button>
293 );
294 })}
295 </div>
296 </ComposerBanner.Body>
297 </ComposerBanner.Scroll>
298 </CollapsiblePanel>
299 </Collapsible>
300 );
301});