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 respondingRequestIds: RuntimeRequestId[];
16 answers: Record<string, PendingUserInputDraftAnswer>;
17 questionIndex: number;
18 onToggleOption: (questionId: string, optionValue: string) => void;
19 onAdvance: () => void;
20 onDismiss: (requestId: RuntimeRequestId) => void;
21}
22
23export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInputPanel({
24 pendingUserInputs,
25 respondingRequestIds,
26 answers,
27 questionIndex,
28 onToggleOption,
29 onAdvance,
30 onDismiss,
31}: PendingUserInputPanelProps) {
32 if (pendingUserInputs.length === 0) return null;
33 const activePrompt = pendingUserInputs[0];
34 if (!activePrompt) return null;
35
36 return (
37 <ComposerPendingUserInputCard
38 key={activePrompt.requestId}
39 prompt={activePrompt}
40 isResponding={respondingRequestIds.includes(activePrompt.requestId)}
41 answers={answers}
42 questionIndex={questionIndex}
43 onToggleOption={onToggleOption}
44 onAdvance={onAdvance}
45 onDismiss={onDismiss}
46 />
47 );
48});
49
50const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard({
51 prompt,
52 isResponding,
53 answers,
54 questionIndex,
55 onToggleOption,
56 onAdvance,
57 onDismiss,
58}: {
59 prompt: PendingUserInput;
60 isResponding: boolean;
61 answers: Record<string, PendingUserInputDraftAnswer>;
62 questionIndex: number;
63 onToggleOption: (questionId: string, optionValue: string) => void;
64 onAdvance: () => void;
65 onDismiss: (requestId: RuntimeRequestId) => void;
66}) {
67 // Message-mode requests remain answerable after their provider turn ends.
68 const canRespond = prompt.responseCapability !== "not_resumable";
69 const responseDisabled = isResponding || !canRespond;
70 const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);
71 const activeQuestion = progress.activeQuestion;
72 const autoAdvanceTimerRef = useRef<number | null>(null);
73 const onAdvanceRef = useRef(onAdvance);
74 const [optimisticSingleSelect, setOptimisticSingleSelect] = useState<{
75 questionId: string;
76 optionValue: string;
77 } | null>(null);
78 // Collapsing hides everything but the header so a tall prompt stops covering
79 // the thread the user is trying to read. Scoped to a single question: the card
80 // is keyed by request id so the next prompt starts expanded, and storing the
81 // collapsed question's id (rather than a bare flag) reopens the card when the
82 // prompt advances to its next question, which can happen without a click —
83 // sending from the composer advances the active question.
84 const [collapsedQuestionId, setCollapsedQuestionId] = useState<string | null>(null);
85 const isCollapsed = collapsedQuestionId !== null && collapsedQuestionId === activeQuestion?.id;
86
87 useEffect(() => {
88 onAdvanceRef.current = onAdvance;
89 }, [onAdvance]);
90
91 useEffect(() => {
92 if (!activeQuestion || activeQuestion.multiSelect || !optimisticSingleSelect) {
93 return;
94 }
95 if (optimisticSingleSelect.questionId !== activeQuestion.id) {
96 setOptimisticSingleSelect(null);
97 return;
98 }
99 if (
100 progress.customAnswer.trim().length === 0 &&
101 progress.selectedOptionValues.includes(optimisticSingleSelect.optionValue)
102 ) {
103 setOptimisticSingleSelect(null);
104 }
105 }, [
106 activeQuestion,
107 optimisticSingleSelect,
108 progress.customAnswer,
109 progress.selectedOptionValues,
110 ]);
111
112 // Clear auto-advance timer on unmount
113 useEffect(() => {
114 return () => {
115 if (autoAdvanceTimerRef.current !== null) {
116 window.clearTimeout(autoAdvanceTimerRef.current);
117 }
118 };
119 }, []);
120
121 const handleOptionSelection = useCallback(
122 (questionId: string, optionValue: string) => {
123 if (activeQuestion?.multiSelect) {
124 onToggleOption(questionId, optionValue);
125 return;
126 }
127 setOptimisticSingleSelect({ questionId, optionValue });
128 onToggleOption(questionId, optionValue);
129 if (autoAdvanceTimerRef.current !== null) {
130 window.clearTimeout(autoAdvanceTimerRef.current);
131 }
132 autoAdvanceTimerRef.current = window.setTimeout(() => {
133 autoAdvanceTimerRef.current = null;
134 onAdvanceRef.current();
135 }, 200);
136 },
137 [activeQuestion, onToggleOption],
138 );
139
140 // Keyboard shortcut: number keys 1-9 select corresponding options when focus is
141 // outside editable fields. Multi-select prompts toggle options in place; single-
142 // select prompts keep the existing auto-advance behavior. Collapsed prompts opt
143 // out, since the numbers they refer to are not on screen.
144 useEffect(() => {
145 if (!activeQuestion || responseDisabled || isCollapsed) return;
146 const handler = (event: globalThis.KeyboardEvent) => {
147 if (event.metaKey || event.ctrlKey || event.altKey) return;
148 const target = event.target;
149 if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
150 return;
151 }
152 if (
153 target instanceof HTMLElement &&
154 target.closest('[contenteditable]:not([contenteditable="false"])')
155 ) {
156 return;
157 }
158 const digit = Number.parseInt(event.key, 10);
159 if (Number.isNaN(digit) || digit < 1 || digit > 9) return;
160 const optionIndex = digit - 1;
161 if (optionIndex >= activeQuestion.options.length) return;
162 const option = activeQuestion.options[optionIndex];
163 if (!option) return;
164 event.preventDefault();
165 handleOptionSelection(activeQuestion.id, option.value ?? option.label);
166 };
167 document.addEventListener("keydown", handler);
168 return () => document.removeEventListener("keydown", handler);
169 }, [activeQuestion, handleOptionSelection, isCollapsed, responseDisabled]);
170
171 if (!activeQuestion) {
172 return null;
173 }
174
175 const customAnswerActive = progress.customAnswer.trim().length > 0;
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-[10px] 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 // Sits inside the trigger button, so stop the click from toggling
211 // the disclosure. Dismiss closes the question without a reply.
212 <ComposerBanner.Dismiss
213 render={<span role="button" tabIndex={0} />}
214 aria-label="Dismiss question without answering"
215 title="Dismiss question without answering"
216 disabled={isResponding}
217 data-pending-user-input-dismiss
218 onClick={(event) => {
219 event.preventDefault();
220 event.stopPropagation();
221 onDismiss(prompt.requestId);
222 }}
223 onKeyDown={(event) => {
224 if (event.key !== "Enter" && event.key !== " ") return;
225 event.preventDefault();
226 event.stopPropagation();
227 onDismiss(prompt.requestId);
228 }}
229 />
230 ) : null}
231 </ComposerBanner.Actions>
232 </CollapsibleTrigger>
233 <CollapsiblePanel>
234 <ComposerBanner.Body className="pe-1 pb-1">
235 <p className="text-sm text-foreground/85">{activeQuestion.question}</p>
236 {activeQuestion.multiSelect ? (
237 <p className="mt-1 text-secondary-label text-xs">Select one or more options.</p>
238 ) : null}
239 <div className="mt-2 space-y-0.5">
240 {activeQuestion.options.map((option, index) => {
241 const optionValue = option.value ?? option.label;
242 const isOptimisticallySelected =
243 optimisticSingleSelect?.questionId === activeQuestion.id &&
244 optimisticSingleSelect.optionValue === optionValue;
245 const isSelected =
246 isOptimisticallySelected ||
247 (!customAnswerActive && progress.selectedOptionValues.includes(optionValue));
248 const shortcutKey = index < 9 ? index + 1 : null;
249 const className = cn(
250 "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-primary/25",
251 isSelected
252 ? "bg-muted/55 text-foreground"
253 : "bg-transparent text-foreground/85 hover:bg-muted/30",
254 isResponding && "opacity-50 cursor-not-allowed",
255 !isResponding && "cursor-pointer",
256 );
257 const content = (
258 <>
259 <div className="min-w-0 flex-1 flex flex-col gap-0.5">
260 <span className="text-sm font-medium">{option.label}</span>
261 {option.description && option.description !== option.label ? (
262 <span className="text-secondary-label text-[11px]">{option.description}</span>
263 ) : null}
264 </div>
265 {isSelected ? (
266 <CheckIcon className="size-3.5 shrink-0 text-primary" />
267 ) : shortcutKey !== null ? (
268 <kbd
269 className={cn(
270 "flex size-5 shrink-0 items-center justify-center text-[10px] font-medium text-muted-foreground tabular-nums",
271 )}
272 >
273 {shortcutKey}
274 </kbd>
275 ) : null}
276 </>
277 );
278 return (
279 <button
280 key={`${activeQuestion.id}:${optionValue}`}
281 type="button"
282 disabled={isResponding}
283 onClick={() => {
284 handleOptionSelection(activeQuestion.id, optionValue);
285 }}
286 className={className}
287 >
288 {content}
289 </button>
290 );
291 })}
292 </div>
293 </ComposerBanner.Body>
294 </CollapsiblePanel>
295 </Collapsible>
296 );
297});