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