Open History to see the last commit
1import { type RuntimeRequestId } from "@t3tools/contracts";
2import { memo, useCallback, useEffect, useRef, useState } from "react";
3import { type PendingUserInput } from "../../session-logic";
4import {
5 derivePendingUserInputProgress,
6 type PendingUserInputDraftAnswer,
7} from "../../pendingUserInput";
8import { CheckIcon } from "lucide-react";
9import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
10import { cn } from "~/lib/utils";
11import { ComposerBanner } from "./ComposerBanner";
12
13interface PendingUserInputPanelProps {
14 pendingUserInputs: PendingUserInput[];
15 disabled?: boolean;
16 respondingRequestIds: RuntimeRequestId[];
17 answers: Record<string, PendingUserInputDraftAnswer>;
18 questionIndex: number;
19 onToggleOption: (questionId: string, optionValue: string) => void;
20 onAdvance: () => void;
21 onDismiss: (requestId: RuntimeRequestId) => void;
22}
23
24export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInputPanel({
25 pendingUserInputs,
26 disabled = false,
27 respondingRequestIds,
28 answers,
29 questionIndex,
30 onToggleOption,
31 onAdvance,
32 onDismiss,
33}: PendingUserInputPanelProps) {
34 if (pendingUserInputs.length === 0) return null;
35 const activePrompt = pendingUserInputs[0];
36 if (!activePrompt) return null;
37
38 return (
39 <ComposerPendingUserInputCard
40 key={activePrompt.requestId}
41 prompt={activePrompt}
42 disabled={disabled}
43 isResponding={respondingRequestIds.includes(activePrompt.requestId)}
44 answers={answers}
45 questionIndex={questionIndex}
46 onToggleOption={onToggleOption}
47 onAdvance={onAdvance}
48 onDismiss={onDismiss}
49 />
50 );
51});
52
53const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard({
54 prompt,
55 disabled,
56 isResponding,
57 answers,
58 questionIndex,
59 onToggleOption,
60 onAdvance,
61 onDismiss,
62}: {
63 prompt: PendingUserInput;
64 disabled: boolean;
65 isResponding: boolean;
66 answers: Record<string, PendingUserInputDraftAnswer>;
67 questionIndex: number;
68 onToggleOption: (questionId: string, optionValue: string) => void;
69 onAdvance: () => void;
70 onDismiss: (requestId: RuntimeRequestId) => void;
71}) {
72 // Message-mode requests remain answerable after their provider turn ends.
73 const canRespond = prompt.responseCapability !== "not_resumable";
74 const responseDisabled = disabled || isResponding || !canRespond;
75 const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);
76 const activeQuestion = progress.activeQuestion;
77 const autoAdvanceTimerRef = useRef<number | null>(null);
78 const onAdvanceRef = useRef(onAdvance);
79 const [optimisticSingleSelect, setOptimisticSingleSelect] = useState<{
80 questionId: string;
81 optionValue: string;
82 } | null>(null);
83 // Collapsing hides everything but the header so a tall prompt stops covering
84 // the thread the user is trying to read. Scoped to a single question: the card
85 // is keyed by request id so the next prompt starts expanded, and storing the
86 // collapsed question's id (rather than a bare flag) reopens the card when the
87 // prompt advances to its next question, which can happen without a click —
88 // sending from the composer advances the active question.
89 const [collapsedQuestionId, setCollapsedQuestionId] = useState<string | null>(null);
90 const isCollapsed = collapsedQuestionId !== null && collapsedQuestionId === activeQuestion?.id;
91
92 useEffect(() => {
93 onAdvanceRef.current = onAdvance;
94 }, [onAdvance]);
95
96 useEffect(() => {
97 if (!activeQuestion || activeQuestion.multiSelect || !optimisticSingleSelect) {
98 return;
99 }
100 if (optimisticSingleSelect.questionId !== activeQuestion.id) {
101 setOptimisticSingleSelect(null);
102 return;
103 }
104 if (
105 progress.customAnswer.trim().length === 0 &&
106 progress.selectedOptionValues.includes(optimisticSingleSelect.optionValue)
107 ) {
108 setOptimisticSingleSelect(null);
109 }
110 }, [
111 activeQuestion,
112 optimisticSingleSelect,
113 progress.customAnswer,
114 progress.selectedOptionValues,
115 ]);
116
117 // A delayed answer only advances its own question, while permission remains granted.
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 = useCallback(
130 (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 onAdvanceRef.current();
144 }, 200);
145 },
146 [activeQuestion, disabled, isResponding, onToggleOption],
147 );
148
149 // Keyboard shortcut: number keys 1-9 select corresponding options when focus is
150 // outside editable fields. Multi-select prompts toggle options in place; single-
151 // select prompts keep the existing auto-advance behavior. Collapsed prompts opt
152 // out, since the numbers they refer to are not on screen.
153 useEffect(() => {
154 if (!activeQuestion || responseDisabled || isCollapsed) return;
155 const handler = (event: globalThis.KeyboardEvent) => {
156 if (event.metaKey || event.ctrlKey || event.altKey) return;
157 const target = event.target;
158 if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
159 return;
160 }
161 if (
162 target instanceof HTMLElement &&
163 target.closest('[contenteditable]:not([contenteditable="false"])')
164 ) {
165 return;
166 }
167 const digit = Number.parseInt(event.key, 10);
168 if (Number.isNaN(digit) || digit < 1 || digit > 9) return;
169 const optionIndex = digit - 1;
170 if (optionIndex >= activeQuestion.options.length) return;
171 const option = activeQuestion.options[optionIndex];
172 if (!option) return;
173 event.preventDefault();
174 handleOptionSelection(activeQuestion.id, option.value ?? option.label);
175 };
176 document.addEventListener("keydown", handler);
177 return () => document.removeEventListener("keydown", handler);
178 }, [activeQuestion, handleOptionSelection, isCollapsed, responseDisabled]);
179
180 if (!activeQuestion) {
181 return null;
182 }
183
184 const customAnswerActive = progress.customAnswer.trim().length > 0;
185
186 return (
187 <Collapsible
188 open={!isCollapsed}
189 onOpenChange={(open) => {
190 setCollapsedQuestionId(open ? null : activeQuestion.id);
191 }}
192 >
193 <CollapsibleTrigger
194 render={<ComposerBanner.Row render={<button type="button" />} />}
195 title={
196 isCollapsed ? "Show the question and its options" : "Hide the question and its options"
197 }
198 data-pending-user-input-toggle={isCollapsed ? "collapsed" : "expanded"}
199 >
200 <ComposerBanner.Icon />
201 <ComposerBanner.Content>
202 <span className="shrink-0 font-medium text-muted-foreground">
203 {activeQuestion.header}
204 </span>
205 {isCollapsed ? (
206 <span className="min-w-0 flex-1 truncate text-secondary-label">
207 {activeQuestion.question}
208 </span>
209 ) : null}
210 </ComposerBanner.Content>
211 <ComposerBanner.Actions>
212 {prompt.questions.length > 1 ? (
213 <span className="text-3xs font-medium text-muted-foreground tabular-nums">
214 {questionIndex + 1}/{prompt.questions.length}
215 </span>
216 ) : null}
217 <ComposerBanner.ToggleIcon expanded={!isCollapsed} />
218 {prompt.dismissible ? (
219 // Sits inside the trigger button, so stop the click from toggling
220 // the disclosure. Dismiss closes the question without a reply.
221 <ComposerBanner.Dismiss
222 render={<span role="button" tabIndex={0} />}
223 aria-label="Dismiss question without answering"
224 title="Dismiss question without answering"
225 disabled={isResponding}
226 data-pending-user-input-dismiss
227 onClick={(event) => {
228 event.preventDefault();
229 event.stopPropagation();
230 onDismiss(prompt.requestId);
231 }}
232 onKeyDown={(event) => {
233 if (event.key !== "Enter" && event.key !== " ") return;
234 event.preventDefault();
235 event.stopPropagation();
236 onDismiss(prompt.requestId);
237 }}
238 />
239 ) : null}
240 </ComposerBanner.Actions>
241 </CollapsibleTrigger>
242 <CollapsiblePanel>
243 <ComposerBanner.Scroll>
244 <ComposerBanner.Body className="pe-1 pb-1 wrap-anywhere">
245 <p className="text-sm text-foreground/85">{activeQuestion.question}</p>
246 {activeQuestion.multiSelect ? (
247 <p className="mt-1 text-secondary-label text-xs">Select one or more options.</p>
248 ) : null}
249 <div className="mt-2 space-y-0.5">
250 {activeQuestion.options.map((option, index) => {
251 const optionValue = option.value ?? option.label;
252 const isOptimisticallySelected =
253 optimisticSingleSelect?.questionId === activeQuestion.id &&
254 optimisticSingleSelect.optionValue === optionValue;
255 const isSelected =
256 isOptimisticallySelected ||
257 (!customAnswerActive && progress.selectedOptionValues.includes(optionValue));
258 const shortcutKey = index < 9 ? index + 1 : null;
259 const className = cn(
260 "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",
261 isSelected
262 ? "bg-muted/55 text-foreground"
263 : "bg-transparent text-foreground/85 hover:bg-muted/30",
264 (disabled || isResponding) && "opacity-50 cursor-not-allowed",
265 !disabled && !isResponding && "cursor-pointer",
266 );
267 const content = (
268 <>
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 {isSelected ? (
276 <CheckIcon className="size-3.5 shrink-0 text-primary" />
277 ) : shortcutKey !== null ? (
278 <kbd
279 className={cn(
280 "flex size-5 shrink-0 items-center justify-center text-3xs font-medium text-muted-foreground tabular-nums",
281 )}
282 >
283 {shortcutKey}
284 </kbd>
285 ) : null}
286 </>
287 );
288 return (
289 <button
290 key={`${activeQuestion.id}:${optionValue}`}
291 type="button"
292 disabled={disabled || isResponding}
293 onClick={() => {
294 handleOptionSelection(activeQuestion.id, optionValue);
295 }}
296 className={className}
297 >
298 {content}
299 </button>
300 );
301 })}
302 </div>
303 </ComposerBanner.Body>
304 </ComposerBanner.Scroll>
305 </CollapsiblePanel>
306 </Collapsible>
307 );
308});