Open History to see the last commit
1import { type RuntimeRequestId, type ScopedThreadRef } from "@t3tools/contracts";
2import { memo, use, useEffect, useEffectEvent, useRef, useState } from "react";
3import { BackgroundThreadContext } from "./backgroundThread";
4import { useStableCallback } from "~/hooks/useStableCallback";
5import { type PendingUserInput } from "../../session-logic";
6import {
7 derivePendingUserInputProgress,
8 type PendingUserInputDraftAnswer,
9} from "../../pendingUserInput";
10import { CheckboxMark } from "../ui/checkbox";
11import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
12import { Kbd } from "../ui/kbd";
13import { cn } from "~/lib/utils";
14import { ComposerBanner } from "./ComposerBanner";
15import ChatMarkdown from "../ChatMarkdown";
16
17interface PendingUserInputPanelProps {
18 pendingUserInputs: PendingUserInput[];
19 cwd: string | undefined;
20 threadRef: ScopedThreadRef;
21 disabled?: boolean;
22 respondingRequestIds: RuntimeRequestId[];
23 answers: Record<string, PendingUserInputDraftAnswer>;
24 questionIndex: number;
25 onToggleOption: (questionId: string, optionValue: string) => void;
26 onAdvance: () => void;
27 onDismiss: (requestId: RuntimeRequestId) => void;
28}
29
30export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInputPanel({
31 pendingUserInputs,
32 cwd,
33 threadRef,
34 disabled = false,
35 respondingRequestIds,
36 answers,
37 questionIndex,
38 onToggleOption,
39 onAdvance,
40 onDismiss,
41}: PendingUserInputPanelProps) {
42 if (pendingUserInputs.length === 0) return null;
43 const activePrompt = pendingUserInputs[0];
44 if (!activePrompt) return null;
45
46 return (
47 <ComposerPendingUserInputCard
48 key={activePrompt.requestId}
49 prompt={activePrompt}
50 cwd={cwd}
51 threadRef={threadRef}
52 disabled={disabled}
53 isResponding={respondingRequestIds.includes(activePrompt.requestId)}
54 answers={answers}
55 questionIndex={questionIndex}
56 onToggleOption={onToggleOption}
57 onAdvance={onAdvance}
58 onDismiss={onDismiss}
59 />
60 );
61});
62
63const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard({
64 prompt,
65 cwd,
66 threadRef,
67 disabled,
68 isResponding,
69 answers,
70 questionIndex,
71 onToggleOption,
72 onAdvance,
73 onDismiss,
74}: {
75 prompt: PendingUserInput;
76 cwd: string | undefined;
77 threadRef: ScopedThreadRef;
78 disabled: boolean;
79 isResponding: boolean;
80 answers: Record<string, PendingUserInputDraftAnswer>;
81 questionIndex: number;
82 onToggleOption: (questionId: string, optionValue: string) => void;
83 onAdvance: () => void;
84 onDismiss: (requestId: RuntimeRequestId) => void;
85}) {
86 // Message-mode requests remain answerable after their provider turn ends.
87 const canRespond = prompt.responseCapability !== "not_resumable";
88 const responseDisabled = disabled || isResponding || !canRespond;
89 const autoAdvanceTimerRef = useRef<number | null>(null);
90 const advance = useStableCallback(onAdvance);
91 const [optimisticSingleSelect, setOptimisticSingleSelect] = useState<{
92 questionId: string;
93 optionValue: string;
94 } | null>(null);
95 const [collapsedQuestionId, setCollapsedQuestionId] = useState<string | null>(null);
96 // Keep question identity stable for its shortcut listener.
97 const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);
98 const activeQuestion = progress.activeQuestion;
99 const customAnswerActive = progress.customAnswer.trim().length > 0;
100 // Read before later hooks to preserve the question's compiler cache.
101 const draftSelectedOptions = activeQuestion?.options.map(
102 (option) =>
103 !customAnswerActive && progress.selectedOptionValues.includes(option.value ?? option.label),
104 );
105 const isCollapsed = collapsedQuestionId !== null && collapsedQuestionId === activeQuestion?.id;
106
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 useEffect(() => {
119 const clearAutoAdvance = () => {
120 if (autoAdvanceTimerRef.current !== null) {
121 window.clearTimeout(autoAdvanceTimerRef.current);
122 autoAdvanceTimerRef.current = null;
123 }
124 };
125 if (disabled || activeQuestion?.id === undefined) clearAutoAdvance();
126 return clearAutoAdvance;
127 }, [activeQuestion?.id, disabled]);
128
129 const handleOptionSelection = (questionId: string, optionValue: string) => {
130 if (disabled || isResponding) return;
131 if (activeQuestion?.multiSelect) {
132 onToggleOption(questionId, optionValue);
133 return;
134 }
135 setOptimisticSingleSelect({ questionId, optionValue });
136 onToggleOption(questionId, optionValue);
137 if (autoAdvanceTimerRef.current !== null) {
138 window.clearTimeout(autoAdvanceTimerRef.current);
139 }
140 autoAdvanceTimerRef.current = window.setTimeout(() => {
141 autoAdvanceTimerRef.current = null;
142 advance();
143 }, 200);
144 };
145
146 const selectOptionFromShortcut = useEffectEvent(handleOptionSelection);
147 const backgroundThread = use(BackgroundThreadContext);
148
149 useEffect(() => {
150 if (!activeQuestion || responseDisabled || isCollapsed || backgroundThread) 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, backgroundThread, 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 className="px-4 pt-1.5"
194 >
195 <ComposerBanner.Content>
196 <span className="shrink-0 text-muted-foreground">{activeQuestion.header}</span>
197 {isCollapsed ? (
198 <>
199 <ComposerBanner.Separator />
200 <span className="min-w-0 flex-1 truncate text-secondary-label">
201 {activeQuestion.question}
202 </span>
203 </>
204 ) : null}
205 </ComposerBanner.Content>
206 <ComposerBanner.Actions className="gap-0">
207 {prompt.questions.length > 1 ? (
208 <ComposerBanner.Count>
209 {questionIndex + 1}/{prompt.questions.length}
210 </ComposerBanner.Count>
211 ) : null}
212 <ComposerBanner.ToggleIcon expanded={!isCollapsed} />
213 {prompt.dismissible ? (
214 <ComposerBanner.Dismiss
215 render={<span role="button" tabIndex={0} />}
216 aria-label="Dismiss question without answering"
217 title="Dismiss question without answering"
218 disabled={isResponding}
219 data-pending-user-input-dismiss
220 onClick={(event) => {
221 event.preventDefault();
222 event.stopPropagation();
223 onDismiss(prompt.requestId);
224 }}
225 onKeyDown={(event) => {
226 if (event.key !== "Enter" && event.key !== " ") return;
227 event.preventDefault();
228 event.stopPropagation();
229 onDismiss(prompt.requestId);
230 }}
231 />
232 ) : null}
233 </ComposerBanner.Actions>
234 </CollapsibleTrigger>
235 <CollapsiblePanel>
236 <ComposerBanner.Scroll>
237 <ComposerBanner.Body className="ps-6 pe-4 pb-1 wrap-anywhere sm:ps-5.5">
238 <ChatMarkdown
239 text={activeQuestion.question}
240 cwd={cwd}
241 threadRef={threadRef}
242 className="pt-2 text-foreground/85"
243 />
244 {/* Rows span the header row's width so the radios align with the question text and the shortcut column sits under the dismiss button. */}
245 <div className="-ms-2 mt-1.5 sm:-ms-1.5">
246 {activeQuestion.options.map((option, index) => {
247 const optionValue = option.value ?? option.label;
248 const isOptimisticallySelected =
249 optimisticSingleSelect?.questionId === activeQuestion.id &&
250 optimisticSingleSelect.optionValue === optionValue;
251 const isSelected =
252 isOptimisticallySelected || draftSelectedOptions?.[index] === true;
253 const className = cn(
254 "group flex w-full items-start gap-2.5 rounded-md bg-transparent py-1.5 ps-2 text-left sm:ps-1.5 outline-none transition-colors duration-150 focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary/25",
255 isSelected ? "text-foreground" : "text-foreground/70 hover:bg-muted/30",
256 (disabled || isResponding) && "opacity-50 cursor-not-allowed",
257 !disabled && !isResponding && "cursor-pointer",
258 );
259 // The h-5 slots match the label's line box, so the indicator and shortcut stay on its first line.
260 const content = (
261 <>
262 <span className="pointer-events-none flex h-5 shrink-0 items-center">
263 {activeQuestion.multiSelect ? (
264 <CheckboxMark checked={isSelected} />
265 ) : (
266 <OptionRadio checked={isSelected} />
267 )}
268 </span>
269 <div className="min-w-0 flex-1 flex flex-col gap-0.5">
270 <span className="text-sm font-medium">{option.label}</span>
271 {option.description && option.description !== option.label ? (
272 <span className="text-secondary-label text-2xs">{option.description}</span>
273 ) : null}
274 </div>
275 {index < 9 ? (
276 <span className="flex h-5 w-7 shrink-0 items-center justify-center sm:w-6">
277 <Kbd>{index + 1}</Kbd>
278 </span>
279 ) : null}
280 </>
281 );
282 return (
283 <button
284 key={`${activeQuestion.id}:${optionValue}`}
285 type="button"
286 aria-pressed={isSelected}
287 disabled={disabled || isResponding}
288 onClick={() => {
289 handleOptionSelection(activeQuestion.id, optionValue);
290 }}
291 className={className}
292 >
293 {content}
294 </button>
295 );
296 })}
297 </div>
298 </ComposerBanner.Body>
299 </ComposerBanner.Scroll>
300 </CollapsiblePanel>
301 </Collapsible>
302 );
303});
304
305// Drawn with ui/radio-group's look instead of using its Radio: Radio only checks inside a
306// RadioGroup, whose arrow keys select options and would trip the single-select auto-advance.
307function OptionRadio({ checked }: { checked: boolean }) {
308 return (
309 <span
310 aria-hidden
311 className={cn(
312 "relative inline-flex size-4.5 shrink-0 items-center justify-center rounded-full border border-input bg-background not-dark:bg-clip-padding sm:size-4 dark:bg-input/32",
313 checked ? "shadow-none" : "shadow-xs/5",
314 )}
315 >
316 {checked ? (
317 <span className="-inset-px absolute flex items-center justify-center rounded-full bg-primary before:size-2 before:rounded-full before:bg-primary-foreground sm:before:size-1.5" />
318 ) : null}
319 </span>
320 );
321}