Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🙋 feat: Refine the Ask Question Card and Smooth Batched Question Steps (#16641)

Marco Berettafc05ea3946f2
diff --git a/client/src/components/Chat/Input/AskUserQuestionPopover.tsx b/client/src/components/Chat/Input/AskUserQuestionPopover.tsx
index 53b53cbb75..c54c323ec6 100644
--- a/client/src/components/Chat/Input/AskUserQuestionPopover.tsx
+++ b/client/src/components/Chat/Input/AskUserQuestionPopover.tsx
@@ -46,7 +46,6 @@ function AskUserQuestionPopoverContent({
}
function AskUserQuestionsPopoverPanel({ ask }: { ask: ReturnType<typeof useAskAnswerMode> }) {
- const localize = useLocalize();
const { liveAsk, collapse } = ask;
const questions = liveAsk?.questions;
if (liveAsk == null || questions == null || questions.length === 0) {
@@ -54,37 +53,46 @@ function AskUserQuestionsPopoverPanel({ ask }: { ask: ReturnType<typeof useAskAn
}
return (
- <div className="absolute bottom-28 z-10 w-full">
- <div className="popover border-border-light bg-surface-primary-alt flex max-h-[70vh] flex-col rounded-2xl border shadow-lg">
- <div className="border-border-light flex shrink-0 items-center justify-between gap-2 border-b px-3 py-2">
- <p className="text-text-primary text-sm font-medium">
- {localize(
- questions.length === 1 ? 'com_ui_asking_questions_one' : 'com_ui_asking_questions',
- { 0: questions.length },
- )}
- </p>
- <TooltipAnchor
- description={localize('com_ui_ask_move_to_chat')}
- side="top"
- render={
- <Button
- variant="ghost"
- size="icon"
- aria-label={localize('com_ui_ask_move_to_chat')}
- className="text-text-secondary size-auto rounded-md p-1"
- onClick={collapse}
- >
- <ChevronDown className="size-4" aria-hidden="true" />
- </Button>
- }
- />
- </div>
- <AskUserQuestions actionId={liveAsk.actionId} questions={questions} />
+ <div className="absolute bottom-full z-10 mb-2 w-full">
+ {/* The prompt and answers each scroll within their own caps; this outer cap keeps
+ the whole card on screen when both are at their limit on a short viewport. */}
+ <div className="popover border-border-light bg-surface-secondary flex max-h-[70vh] flex-col overflow-y-auto rounded-2xl border shadow-lg [view-transition-name:ask-question]">
+ {/* Kept at full height so the cap above scrolls it rather than clipping its end. */}
+ <AskUserQuestions
+ actionId={liveAsk.actionId}
+ questions={questions}
+ className="shrink-0"
+ headerAction={<MoveToChatButton onClick={collapse} />}
+ />
</div>
</div>
);
}
+/** Moves the question to the chat card and hands the composer back. */
+function MoveToChatButton({ onClick }: { onClick: () => void }) {
+ const localize = useLocalize();
+ return (
+ <TooltipAnchor
+ description={localize('com_ui_ask_move_to_chat')}
+ side="top"
+ render={
+ <Button
+ variant="row-action"
+ size="icon-xs"
+ aria-label={localize('com_ui_ask_move_to_chat')}
+ onClick={onClick}
+ >
+ <ChevronDown
+ className="size-4 [view-transition-name:ask-question-chevron]"
+ aria-hidden="true"
+ />
+ </Button>
+ }
+ />
+ );
+}
+
/**
* Split from the gate above so the per-keystroke `useWatch` subscription only
* exists while the popover is actually visible — the invisible popover was
@@ -149,18 +157,18 @@ function AskUserQuestionPopoverPanel({
const composerHasText = composerText.trim().length > 0;
return (
- <div className="absolute bottom-28 z-10 w-full space-y-2">
+ <div className="absolute bottom-full z-10 mb-2 w-full">
{/* Digit shortcuts (1..N) work when focus is inside the popover too, not
only from the composer — keydown bubbles here from the focused row/
control. Height is viewport-bounded with the option list as the only
scroll region: the panel is absolutely positioned, so anything that
overflows it is unreachable by page scroll. */}
<div
- className="popover border-border-light bg-surface-primary-alt flex max-h-[60vh] flex-col rounded-2xl border p-2 shadow-lg [view-transition-name:ask-question]"
+ className="popover border-border-light bg-surface-secondary flex max-h-[60vh] flex-col rounded-2xl border p-2 shadow-lg [view-transition-name:ask-question]"
onKeyDown={handlePopoverKeyDown}
>
- <div className="flex shrink-0 items-start justify-between gap-2 p-2">
- <div className="max-h-[24vh] min-w-0 overflow-y-auto">
+ <div className="text-text-secondary flex shrink-0 items-start justify-between gap-2 p-1 pl-2">
+ <div className="max-h-[24vh] min-w-0 overflow-y-auto pt-1">
<p className="text-text-primary text-sm font-medium [overflow-wrap:anywhere]">
{liveAsk.question.question}
</p>
@@ -170,23 +178,7 @@ function AskUserQuestionPopoverPanel({
</p>
)}
</div>
- {/* Single exit: moves the question to the chat card and hands the
- composer back for normal messages. */}
- <TooltipAnchor
- description={localize('com_ui_ask_move_to_chat')}
- side="top"
- render={
- <Button
- variant="ghost"
- size="icon"
- aria-label={localize('com_ui_ask_move_to_chat')}
- className="text-text-secondary size-auto rounded-md p-1"
- onClick={collapse}
- >
- <ChevronDown className="size-4" aria-hidden="true" />
- </Button>
- }
- />
+ <MoveToChatButton onClick={collapse} />
</div>
<AskOptions
options={options}
diff --git a/client/src/components/Chat/Input/ChatForm.tsx b/client/src/components/Chat/Input/ChatForm.tsx
index 88046f5f36..be905123e0 100644
--- a/client/src/components/Chat/Input/ChatForm.tsx
+++ b/client/src/components/Chat/Input/ChatForm.tsx
@@ -458,7 +458,9 @@ const ChatForm = memo(function ChatForm({
textAreaRef,
submitButtonRef,
setIsScrollable,
- disabled: disableInputs || answerMode.composerLocked,
+ /* Only picks the missing-key placeholder; a batch lock is applied to the
+ textarea itself and keeps its own "answer above" placeholder. */
+ disabled: disableInputs,
// The composer IS the free-form answer box while a question pause is live.
placeholder: composerReserved ? answerPlaceholder : placeholder,
// Enter stays live during a run when it can steer/queue instead of send.
@@ -864,6 +866,8 @@ const ChatForm = memo(function ChatForm({
'relative flex-1',
listening &&
'[&_textarea]:caret-transparent [&_textarea]:placeholder:text-transparent',
+ /* Locked behind a question: the placeholder is a notice, not text. */
+ answerMode.composerLocked && '[&_textarea]:select-none',
)}
style={
isCollapsed
@@ -1017,7 +1021,6 @@ const ChatForm = memo(function ChatForm({
isSubmitting={isSubmitting}
duringRunActive={steering.duringRunActive}
canControlGeneration={steering.canControlGeneration}
- canStop={canStop}
steerInterruptsByDefault={steering.steerInterruptsByDefault}
duringRunAction={steering.effectiveAction}
/* A staged reasoning choice forces the message to queue, and the
diff --git a/client/src/components/Chat/Input/Composer/__tests__/Hints.spec.tsx b/client/src/components/Chat/Input/Composer/__tests__/Hints.spec.tsx
index f66f89e1b8..2847c46d99 100644
--- a/client/src/components/Chat/Input/Composer/__tests__/Hints.spec.tsx
+++ b/client/src/components/Chat/Input/Composer/__tests__/Hints.spec.tsx
@@ -12,10 +12,6 @@ jest.mock('~/hooks/Input/useComposerBindings', () => ({
}),
}));
-jest.mock('~/hooks/useKeyboardShortcuts', () => ({
- useShortcutDisplay: () => 'Ctrl+Shift+X',
-}));
-
const baseState: ComposerHintState = {
hasText: true,
isSubmitting: false,
diff --git a/client/src/components/Chat/Messages/Content/AskUserQuestion.tsx b/client/src/components/Chat/Messages/Content/AskUserQuestion.tsx
index 5949ff9d9d..13af9061a1 100644
--- a/client/src/components/Chat/Messages/Content/AskUserQuestion.tsx
+++ b/client/src/components/Chat/Messages/Content/AskUserQuestion.tsx
@@ -1,6 +1,6 @@
import { useContext, useMemo, useState } from 'react';
import { Button, TextareaAutosize, TooltipAnchor } from '@librechat/client';
-import { ChevronUp, MessageCircleQuestion, TriangleAlert } from 'lucide-react';
+import { ChevronDown, MessageCircleQuestion, TriangleAlert } from 'lucide-react';
import type { Agents } from 'librechat-data-provider';
import { useApprovalContext, useAskSubmitStatus, useResumeSubmit } from './ApprovalContext';
import { splitOtherOption, ASK_USER_DECLINED_ANSWER } from '~/utils/approval';
@@ -33,21 +33,80 @@ export default function AskUserQuestion({
const answerMode = useAskAnswerMode(conversationId);
const isLivePause = answerMode.liveAsk?.actionId === actionId;
if (questions != null && questions.length > 0) {
- if (answerMode.popoverVisible && isLivePause) {
- return null;
- }
- return (
- <AskUserQuestions
+ /** Same footprint reservation as a single question: while the popover owns
+ * the batch, a hidden copy of the card holds its place in the thread, so
+ * moving it between the composer and the chat reflows nothing. */
+ const reserved = answerMode.popoverVisible && isLivePause;
+ const card = (
+ <AskUserQuestionsCard
actionId={actionId}
questions={questions}
- className="border-border-light bg-surface-secondary my-2 max-h-[70vh] w-full rounded-lg border"
+ live={isLivePause && !reserved}
+ reserved={reserved}
onExpand={answerMode.collapsed && isLivePause ? answerMode.expand : undefined}
/>
);
+ return reserved ? <AskingPlaceholder>{card}</AskingPlaceholder> : card;
}
return <AskUserQuestionSingle actionId={actionId} question={question} answerMode={answerMode} />;
}
+/** The batch's chat card. Shares the popover's view-transition-name while it is
+ * the live pause's surface, so moving the batch between the composer and the
+ * chat morphs one surface into the other, like a single question does. */
+function AskUserQuestionsCard({
+ actionId,
+ questions,
+ live,
+ reserved,
+ onExpand,
+}: {
+ actionId: string;
+ questions: Agents.AskUserQuestionBatchItem[];
+ live: boolean;
+ reserved: boolean;
+ onExpand?: () => void;
+}) {
+ const localize = useLocalize();
+ return (
+ <div
+ className={cn(
+ 'border-border-light bg-surface-secondary my-2 flex w-full flex-col rounded-2xl border',
+ live && '[view-transition-name:ask-question]',
+ reserved && 'invisible',
+ )}
+ aria-hidden={reserved || undefined}
+ inert={reserved ? '' : undefined}
+ >
+ <AskUserQuestions
+ actionId={actionId}
+ questions={questions}
+ headerAction={
+ onExpand != null && (
+ <TooltipAnchor
+ description={localize('com_ui_ask_move_to_composer')}
+ side="top"
+ render={
+ <Button
+ variant="row-action"
+ size="icon-xs"
+ aria-label={localize('com_ui_ask_move_to_composer')}
+ onClick={onExpand}
+ >
+ <ChevronDown
+ className="size-4 rotate-180 [view-transition-name:ask-question-chevron]"
+ aria-hidden="true"
+ />
+ </Button>
+ }
+ />
+ )
+ }
+ />
+ </div>
+ );
+}
+
function AskUserQuestionSingle({
actionId,
question,
@@ -169,14 +228,14 @@ function AskUserQuestionSingle({
const card = (
<div
className={cn(
- 'border-border-light bg-surface-secondary my-2 flex w-full flex-col gap-2.5 rounded-xl border p-3',
+ 'border-border-light bg-surface-secondary my-2 flex w-full flex-col gap-2.5 rounded-2xl border p-3',
showPlaceholder && 'invisible',
+ isLivePause && !showPlaceholder && '[view-transition-name:ask-question]',
)}
aria-hidden={showPlaceholder || undefined}
- style={isLivePause && !showPlaceholder ? { viewTransitionName: 'ask-question' } : undefined}
>
- <div className="flex items-start justify-between gap-2">
- <div className="min-w-0">
+ <div className="text-text-secondary flex items-start justify-between gap-2">
+ <div className="min-w-0 pt-1">
<p className="text-text-primary text-sm font-medium [overflow-wrap:anywhere]">
{question.question}
</p>
@@ -192,13 +251,15 @@ function AskUserQuestionSingle({
side="top"
render={
<Button
- variant="ghost"
- size="icon"
+ variant="row-action"
+ size="icon-xs"
aria-label={localize('com_ui_ask_move_to_composer')}
- className="text-text-secondary size-auto rounded-md p-1"
onClick={expand}
>
- <ChevronUp className="size-4" aria-hidden="true" />
+ <ChevronDown
+ className="size-4 rotate-180 [view-transition-name:ask-question-chevron]"
+ aria-hidden="true"
+ />
</Button>
}
/>
@@ -257,12 +318,17 @@ function AskUserQuestionSingle({
return card;
}
- /** Popover has the question: the reserved card sits hidden underneath the
- * same compact in-progress row the other tools use, so the turn still
- * shows the call is running. */
+ return <AskingPlaceholder>{card}</AskingPlaceholder>;
+}
+
+/** Popover has the question: the reserved card sits hidden underneath the
+ * same compact in-progress row the other tools use, so the turn still
+ * shows the call is running. */
+function AskingPlaceholder({ children }: { children: React.ReactNode }) {
+ const localize = useLocalize();
return (
<div className="relative">
- {card}
+ {children}
<div className="absolute inset-x-0 top-0 my-1 flex h-5 items-center gap-2.5">
<MessageCircleQuestion className="text-text-secondary size-4 shrink-0" aria-hidden="true" />
<span className="tool-status-text shimmer text-text-secondary font-medium">
diff --git a/client/src/components/Chat/Messages/Content/AskUserQuestions.tsx b/client/src/components/Chat/Messages/Content/AskUserQuestions.tsx
index 7eccda3146..2f4b43e3a9 100644
--- a/client/src/components/Chat/Messages/Content/AskUserQuestions.tsx
+++ b/client/src/components/Chat/Messages/Content/AskUserQuestions.tsx
@@ -1,9 +1,12 @@
import { useCallback, useEffect, useId, useMemo, useRef } from 'react';
-import { Button, TextareaAutosize } from '@librechat/client';
-import { Check, ChevronUp, TriangleAlert, X } from 'lucide-react';
+import { TriangleAlert } from 'lucide-react';
+import { Input, Button } from '@librechat/client';
import type { Agents } from 'librechat-data-provider';
+import type { ReactNode } from 'react';
import useAskQuestionsForm from '~/hooks/Input/useAskQuestionsForm';
+import AskOptions from '~/components/Chat/ask/options';
import { splitOtherOption } from '~/utils/approval';
+import { AutoHeight } from '~/components/ui';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
@@ -17,14 +20,14 @@ export default function AskUserQuestions({
actionId,
questions,
className,
- onExpand,
- onDismiss,
+ headerAction,
}: {
actionId: string;
questions: Agents.AskUserQuestionBatchItem[];
className?: string;
- onExpand?: () => void;
- onDismiss?: () => void;
+ /** The surface's own control (move to chat, move back), set in the
+ * question's header row so it shares the form's inset. */
+ headerAction?: ReactNode;
}) {
const localize = useLocalize();
const promptId = useId();
@@ -81,19 +84,12 @@ export default function AskUserQuestions({
return null;
}
- const question = questions[activeIndex];
- if (question == null) {
+ if (questions[activeIndex] == null) {
return null;
}
- const { choices, otherLabel } = splitOtherOption(question.options);
- const selected = Object.hasOwn(form.state.selected, question.id)
- ? form.state.selected[question.id]
- : [];
- const text = Object.hasOwn(form.state.text, question.id) ? form.state.text[question.id] : '';
- const legend = question.header ?? (stepped ? null : localize('com_ui_question_number', { 0: 1 }));
/** Only worth surfacing when the gap is somewhere the user cannot see: the
- * last step's own blank textarea already explains a disabled Submit. */
+ * last step's own blank answer field already explains a disabled Submit. */
const remaining = total - Object.keys(form.answers).length;
const showRemaining =
stepped &&
@@ -102,168 +98,175 @@ export default function AskUserQuestions({
firstUnanswered >= 0 &&
firstUnanswered !== activeIndex;
+ const question = questions[activeIndex];
+ const { choices, otherLabel } = splitOtherOption(question.options);
+ const selected = Object.hasOwn(form.state.selected, question.id)
+ ? form.state.selected[question.id]
+ : [];
+ const selectedIndices = choices.flatMap((option, optionIndex) =>
+ selected.includes(option.value) ? [optionIndex] : [],
+ );
+ const text = Object.hasOwn(form.state.text, question.id) ? form.state.text[question.id] : '';
+
return (
<div className={cn('flex min-h-0 flex-col', className)}>
- {(onExpand != null || onDismiss != null) && (
- <div className="border-border-light flex shrink-0 items-center justify-end border-b px-2 py-1">
- {onExpand != null && (
- <Button
- variant="ghost"
- size="icon-sm"
- aria-label={localize('com_ui_expand')}
- className="text-text-secondary"
- onClick={onExpand}
- >
- <ChevronUp className="h-4 w-4" aria-hidden="true" />
- </Button>
- )}
- {/** The collapsed card is the ONLY surface left for a collapsed
- * batch, so it has to carry the popover's dismiss too — without it
- * the pause can only be answered or skipped. */}
- {onDismiss != null && (
- <Button
- variant="ghost"
- size="icon-sm"
- aria-label={localize('com_ui_close')}
- className="text-text-secondary"
- onClick={onDismiss}
- >
- <X className="h-4 w-4" aria-hidden="true" />
- </Button>
- )}
- </div>
- )}
- {stepped && (
- <div className="border-border-light flex shrink-0 items-center justify-between gap-2 border-b px-3 py-2">
- <p className="text-text-secondary text-xs font-medium" aria-live="polite">
+ {/* Only the active step renders, laid out at its final size at once.
+ One `AutoHeight` holds everything above the buttons and clips only at
+ its bottom edge, so the header and title stay put and the footer
+ rides that edge as the card eases to the new height. */}
+ <AutoHeight>
+ {stepped && (
+ <p className="sr-only" aria-live="polite">
{localize('com_ui_question_step', { 0: activeIndex + 1, 1: total })}
</p>
- <div
- role="group"
- aria-label={localize('com_ui_question_navigation')}
- className="flex flex-wrap items-center justify-end"
- >
- {questions.map((item, index) => {
- const isAnswered = Object.hasOwn(form.answers, item.id);
- const isActive = index === activeIndex;
- return (
- <button
- key={item.id}
- type="button"
- disabled={navLocked}
- aria-current={isActive ? 'step' : undefined}
- aria-label={localize(
- isAnswered
- ? 'com_ui_question_step_answered'
- : 'com_ui_question_step_unanswered',
- { 0: index + 1 },
- )}
- className="flex h-6 items-center justify-center px-1"
- onClick={() => goToStep(index)}
- >
- <span
- className={cn(
- 'h-2 rounded-full',
- isActive ? 'w-4' : 'w-2',
- isAnswered ? 'bg-surface-submit' : 'bg-border-heavy',
- )}
- />
- </button>
- );
- })}
+ )}
+ <div className="text-text-secondary flex shrink-0 items-start justify-between gap-2 px-3 pt-3">
+ {/* Bounded so a long prompt scrolls rather than pushing the composer
+ popover past the top of the viewport. */}
+ <div className="max-h-[25vh] min-w-0 flex-1 overflow-y-auto">
+ {question.header != null && question.header !== '' && (
+ <p className="mb-1 text-xs font-medium">{question.header}</p>
+ )}
+ <p
+ id={promptId}
+ className="text-text-primary text-sm font-medium [overflow-wrap:anywhere]"
+ >
+ {question.question}
+ </p>
+ {question.description != null && question.description.length > 0 && (
+ <p className="mt-0.5 text-sm [overflow-wrap:anywhere]">{question.description}</p>
+ )}
</div>
- </div>
- )}
- <div ref={scrollRef} className="min-h-0 flex-1 overflow-y-auto px-3">
- {/* The height floor sits on the step itself, not the scroll container:
- the container needs `min-h-0` to shrink inside the flex column, and
- tailwind-merge would drop it for a second `min-h-*`. */}
- <fieldset
- ref={stepRef}
- tabIndex={-1}
- aria-labelledby={promptId}
- className={cn('py-3 outline-hidden', stepped && 'min-h-40')}
- >
- {legend != null && (
- <legend className="text-text-secondary mb-1 text-xs font-medium">{legend}</legend>
+ {(stepped || headerAction != null) && (
+ <div className="flex shrink-0 items-center gap-1">
+ {stepped && (
+ <div
+ role="group"
+ aria-label={localize('com_ui_question_navigation')}
+ className="flex items-center"
+ >
+ {questions.map((item, index) => {
+ const isAnswered = Object.hasOwn(form.answers, item.id);
+ const isActive = index === activeIndex;
+ return (
+ <button
+ key={item.id}
+ type="button"
+ disabled={navLocked}
+ aria-current={isActive ? 'step' : undefined}
+ aria-label={localize(
+ isAnswered
+ ? 'com_ui_question_step_answered'
+ : 'com_ui_question_step_unanswered',
+ { 0: index + 1 },
+ )}
+ className="flex h-7 items-center justify-center px-1"
+ onClick={() => goToStep(index)}
+ >
+ <span
+ className={cn(
+ 'h-2 rounded-full transition-all duration-300 ease-out motion-reduce:transition-none',
+ isActive ? 'w-4' : 'w-2',
+ isAnswered ? 'bg-surface-submit' : 'bg-border-heavy',
+ )}
+ />
+ </button>
+ );
+ })}
+ </div>
+ )}
+ {headerAction}
+ </div>
)}
- <p
- id={promptId}
- className="text-text-primary text-sm font-medium [overflow-wrap:anywhere]"
+ </div>
+ {/* `pb-1 -mb-1` keeps the answer field's focus ring inside the padding
+ box, so focusing it never counts as overflow and draws a scrollbar. */}
+ <div ref={scrollRef} className="-mb-1 max-h-[45vh] overflow-y-auto px-3 pb-1">
+ <fieldset
+ key={question.id}
+ ref={stepRef}
+ tabIndex={-1}
+ aria-labelledby={promptId}
+ className="flex flex-col gap-2 pt-3 outline-hidden"
>
- {question.question}
- </p>
- {question.description != null && question.description.length > 0 && (
- <p className="text-text-secondary mt-1 text-sm [overflow-wrap:anywhere]">
- {question.description}
- </p>
- )}
- {choices.length > 0 && (
- <div className="mt-2 flex flex-wrap gap-2" role="group">
- {choices.map((option) => {
- const isSelected = selected.includes(option.value);
- return (
- <Button
- key={option.value}
- type="button"
- size="sm"
- variant={isSelected ? 'submit' : 'choice'}
- role={question.multiSelect === true ? 'checkbox' : undefined}
- aria-checked={question.multiSelect === true ? isSelected : undefined}
- aria-pressed={question.multiSelect === true ? undefined : isSelected}
- disabled={form.locked}
- className="h-auto min-h-9 max-w-full py-1.5 text-left [overflow-wrap:anywhere] whitespace-normal"
- onClick={() => handleSelectOption(question, option.value)}
- >
- {question.multiSelect === true && isSelected && (
- <Check className="mr-1.5 h-4 w-4 shrink-0" aria-hidden="true" />
- )}
- {option.label}
- </Button>
- );
- })}
+ {choices.length > 0 && (
+ <AskOptions
+ options={choices}
+ multiSelect={question.multiSelect === true}
+ checked={selectedIndices}
+ selected={question.multiSelect === true ? null : (selectedIndices[0] ?? null)}
+ selectedIsAnswer
+ locked={form.locked || text.trim().length > 0}
+ onActivate={(optionIndex) =>
+ handleSelectOption(question, choices[optionIndex].value)
+ }
+ className="flex flex-col"
+ />
+ )}
+ <Input
+ value={text}
+ disabled={form.locked}
+ onChange={(event) => form.setText(question, event.target.value)}
+ onKeyDown={(event) => {
+ /* The composer popover sits inside the chat form, where Enter in a
+ single-line field would submit the composer draft instead.
+ Enter confirms this answer: the next step, or the batch. An Enter that
+ confirms an IME composition is left alone, with the same Safari
+ fallback as the composer. */
+ if (
+ event.key !== 'Enter' ||
+ event.nativeEvent.isComposing ||
+ event.nativeEvent.keyCode === 229
+ ) {
+ return;
+ }
+ event.preventDefault();
+ if (!isLastStep) {
+ if (!navLocked) {
+ refocusRef.current = true;
+ goToStep(activeIndex + 1);
+ }
+ return;
+ }
+ form.submit();
+ }}
+ placeholder={otherLabel ?? localize('com_ui_your_answer')}
+ aria-label={`${question.question} ${localize('com_ui_your_answer')}`}
+ />
+ </fieldset>
+ </div>
+ <div className="shrink-0 px-3">
+ {(form.status === 'error' || form.status === 'expired') && (
+ <div className="text-text-warning flex items-center gap-1.5 pt-2 text-xs">
+ <TriangleAlert className="h-4 w-4 shrink-0" aria-hidden="true" />
+ {form.status === 'expired'
+ ? localize('com_ui_approval_expired')
+ : localize('com_ui_ask_answer_error')}
</div>
)}
- <TextareaAutosize
- value={text}
- disabled={form.locked}
- onChange={(event) => form.setText(question, event.target.value)}
- minRows={1}
- maxRows={6}
- placeholder={otherLabel ?? localize('com_ui_your_answer')}
- className="border-border-xheavy bg-surface-primary text-text-primary mt-2 w-full resize-none rounded-md border p-2 text-sm"
- aria-label={`${question.question} ${localize('com_ui_your_answer')}`}
- />
- </fieldset>
- </div>
- {(form.status === 'error' || form.status === 'expired') && (
- <div className="text-text-warning flex items-center gap-1.5 px-3 py-1 text-xs">
- <TriangleAlert className="h-4 w-4 shrink-0" aria-hidden="true" />
- {form.status === 'expired'
- ? localize('com_ui_approval_expired')
- : localize('com_ui_ask_answer_error')}
- </div>
- )}
- {showRemaining && (
- <button
- type="button"
- className="text-text-secondary hover:text-text-primary shrink-0 px-3 py-1 text-left text-xs hover:underline"
- onClick={() => goToStep(firstUnanswered)}
- >
- {localize(
- remaining === 1 ? 'com_ui_questions_remaining_one' : 'com_ui_questions_remaining',
- { 0: remaining },
+ {showRemaining && (
+ <button
+ type="button"
+ className="text-text-secondary hover:text-text-primary pt-2 text-left text-xs select-none hover:underline"
+ onClick={() => goToStep(firstUnanswered)}
+ >
+ {localize(
+ remaining === 1 ? 'com_ui_questions_remaining_one' : 'com_ui_questions_remaining',
+ { 0: remaining },
+ )}
+ </button>
)}
- </button>
- )}
+ </div>
+ </AutoHeight>
<div
className={cn(
- 'border-border-light flex shrink-0 items-center gap-2 border-t p-3',
+ 'flex shrink-0 items-center gap-2 p-3',
stepped ? 'justify-between' : 'justify-end',
)}
>
<Button
type="button"
+ className="select-none"
size="sm"
variant="outline"
disabled={form.locked}
@@ -275,6 +278,7 @@ export default function AskUserQuestions({
{stepped && (
<Button
type="button"
+ className="select-none"
size="sm"
variant="outline"
disabled={navLocked || activeIndex === 0}
@@ -286,6 +290,7 @@ export default function AskUserQuestions({
{isLastStep ? (
<Button
type="button"
+ className="select-none"
size="sm"
variant="submit"
disabled={!form.canSubmit}
@@ -298,6 +303,7 @@ export default function AskUserQuestions({
) : (
<Button
type="button"
+ className="select-none"
size="sm"
variant="submit"
disabled={navLocked}
diff --git a/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionCollapse.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionCollapse.test.tsx
index 2f3d9e7dfe..31b3652f30 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionCollapse.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionCollapse.test.tsx
@@ -89,15 +89,20 @@ describe('collapsing a live ask_user_question', () => {
it('locks the composer only while the popover is up', () => {
renderPause();
expect(screen.getByTestId('composer-locked').textContent).toBe('true');
- /** The popover owns the question, so the card stays out of the way. */
- expect(screen.queryByText('North star or full funnel?')).toBeNull();
+ /** The popover owns the question; the card only holds its place in the
+ * thread, hidden, so moving the batch back reflows nothing. */
+ expect(
+ screen.getByText('North star or full funnel?').closest('[aria-hidden="true"]'),
+ ).not.toBeNull();
fireEvent.click(screen.getByTestId('collapse-from-popover'));
expect(screen.getByTestId('popover-visible').textContent).toBe('false');
/** The pause is still live, but the card owns it outside answer mode. */
expect(screen.getByTestId('active').textContent).toBe('false');
- expect(screen.getByText('North star or full funnel?')).toBeInTheDocument();
+ expect(
+ screen.getByText('North star or full funnel?').closest('[aria-hidden="true"]'),
+ ).toBeNull();
/** The composer is a normal composer again. */
expect(screen.getByTestId('composer-locked').textContent).toBe('false');
expect(screen.getByTestId('composer-answers').textContent).toBe('false');
@@ -107,12 +112,12 @@ describe('collapsing a live ask_user_question', () => {
renderPause();
fireEvent.click(screen.getByTestId('collapse-from-popover'));
- fireEvent.click(screen.getByLabelText('Expand'));
+ fireEvent.click(screen.getByLabelText('Answer from the message box'));
expect(screen.getByTestId('active').textContent).toBe('true');
expect(screen.getByTestId('popover-visible').textContent).toBe('true');
expect(screen.getByTestId('composer-locked').textContent).toBe('true');
- expect(screen.queryByLabelText('Expand')).not.toBeInTheDocument();
+ expect(screen.queryByLabelText('Answer from the message box')).not.toBeInTheDocument();
});
});
diff --git a/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestions.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestions.test.tsx
index aa17d8b05b..f6a8dc0788 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestions.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestions.test.tsx
@@ -54,6 +54,9 @@ const renderBatch = (actionId: string, batch: Agents.AskUserQuestionBatchItem[]
</RecoilRoot>,
);
+/** Only the active step renders. */
+const isShown = (text: string) => screen.queryByText(text) != null;
+
describe('AskUserQuestions', () => {
beforeEach(() => {
mockStatus = 'idle';
@@ -63,30 +66,30 @@ describe('AskUserQuestions', () => {
test('shows one question at a time and walks the batch with Next/Back', () => {
renderBatch('ask-steps');
- expect(screen.getByText('Where should this run?')).toBeInTheDocument();
- expect(screen.queryByText('Which time window?')).not.toBeInTheDocument();
+ expect(isShown('Where should this run?')).toBe(true);
+ expect(isShown('Which time window?')).toBe(false);
expect(screen.getByText('Question 1 of 2')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Submit' })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Next' }));
- expect(screen.getByText('Which time window?')).toBeInTheDocument();
- expect(screen.queryByText('Where should this run?')).not.toBeInTheDocument();
+ expect(isShown('Which time window?')).toBe(true);
+ expect(isShown('Where should this run?')).toBe(false);
expect(screen.getByText('Question 2 of 2')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Next' })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Back' }));
- expect(screen.getByText('Where should this run?')).toBeInTheDocument();
+ expect(isShown('Where should this run?')).toBe(true);
expect(screen.getByRole('button', { name: 'Back' })).toBeDisabled();
});
test('advances automatically when a single-select choice is picked', () => {
renderBatch('ask-advance');
- fireEvent.click(screen.getByRole('button', { name: 'Staging' }));
+ fireEvent.click(screen.getByRole('button', { name: /Staging/ }));
- expect(screen.getByText('Which time window?')).toBeInTheDocument();
+ expect(isShown('Which time window?')).toBe(true);
expect(screen.getByText('Question 2 of 2')).toBeInTheDocument();
});
@@ -104,16 +107,62 @@ describe('AskUserQuestions', () => {
{ id: 'window', question: 'Which time window?' },
]);
- fireEvent.click(screen.getByRole('checkbox', { name: 'us-east' }));
+ fireEvent.click(screen.getByRole('checkbox', { name: /us-east/ }));
- expect(screen.getByText('Which regions?')).toBeInTheDocument();
+ expect(isShown('Which regions?')).toBe(true);
expect(screen.getByText('Question 1 of 2')).toBeInTheDocument();
});
+ test('marks the chosen single-select answer with a check', () => {
+ renderBatch('ask-check', [
+ {
+ id: 'tests',
+ question: 'Should I add tests?',
+ options: [
+ { label: 'Yes', value: 'yes' },
+ { label: 'No', value: 'no' },
+ ],
+ },
+ ]);
+
+ const yes = screen.getByRole('button', { name: /Yes/ });
+ expect(yes).toHaveTextContent('1');
+ fireEvent.click(yes);
+ expect(yes).toHaveAttribute('aria-pressed', 'true');
+ expect(yes).not.toHaveTextContent('1');
+ expect(yes.querySelector('svg')).not.toBeNull();
+ });
+
+ test('clears and locks the choices once an answer is typed', () => {
+ renderBatch('ask-typed', [
+ {
+ id: 'regions',
+ question: 'Which regions?',
+ multiSelect: true,
+ options: [
+ { label: 'us-east', value: 'us-east' },
+ { label: 'eu-west', value: 'eu-west' },
+ ],
+ },
+ ]);
+
+ const usEast = screen.getByRole('checkbox', { name: /us-east/ });
+ fireEvent.click(usEast);
+ expect(usEast).toHaveAttribute('aria-checked', 'true');
+
+ const field = screen.getByRole('textbox', { name: /Which regions/ });
+ fireEvent.change(field, { target: { value: 'ap-south' } });
+ expect(usEast).toHaveAttribute('aria-checked', 'false');
+ expect(usEast).toBeDisabled();
+
+ fireEvent.change(field, { target: { value: '' } });
+ expect(usEast).toBeEnabled();
+ });
+
test('submits one answer map after every question is complete', () => {
renderBatch('ask-batch');
- fireEvent.click(screen.getByRole('button', { name: 'Staging' }));
+ fireEvent.click(screen.getByRole('button', { name: /Staging/ }));
fireEvent.change(screen.getByRole('textbox', { name: /Which time window/ }), {
target: { value: 'Last seven days' },
});
@@ -147,9 +196,9 @@ describe('AskUserQuestions', () => {
expect(screen.getByRole('button', { name: 'Submit' })).toBeDisabled();
fireEvent.click(screen.getByRole('button', { name: '1 question still needs an answer' }));
- expect(screen.getByText('Where should this run?')).toBeInTheDocument();
+ expect(isShown('Where should this run?')).toBe(true);
- fireEvent.click(screen.getByRole('button', { name: 'Staging' }));
+ fireEvent.click(screen.getByRole('button', { name: /Staging/ }));
expect(screen.getByRole('button', { name: 'Submit' })).toBeEnabled();
});
@@ -157,7 +206,7 @@ describe('AskUserQuestions', () => {
renderBatch('ask-dots');
fireEvent.click(screen.getByRole('button', { name: 'Go to question 2, not answered' }));
- expect(screen.getByText('Which time window?')).toBeInTheDocument();
+ expect(isShown('Which time window?')).toBe(true);
fireEvent.change(screen.getByRole('textbox', { name: /Which time window/ }), {
target: { value: 'Today' },
@@ -165,7 +214,55 @@ describe('AskUserQuestions', () => {
expect(screen.getByRole('button', { name: 'Go to question 2, answered' })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Go to question 1, not answered' }));
- expect(screen.getByText('Where should this run?')).toBeInTheDocument();
+ expect(isShown('Where should this run?')).toBe(true);
+ });
+
+ test('Enter in an answer field confirms the answer instead of submitting a surrounding form', () => {
+ const onFormSubmit = jest.fn((event: React.FormEvent) => event.preventDefault());
+ render(
+ <RecoilRoot>
+ <form onSubmit={onFormSubmit}>
+ <AskUserQuestions actionId="ask-enter" questions={questions} />
+ <button type="submit" aria-label="Send composer" />
+ </form>
+ </RecoilRoot>,
+ );
+
+ const first = screen.getByRole('textbox', { name: /Where should this run/ });
+ fireEvent.change(first, { target: { value: 'Locally' } });
+ fireEvent.keyDown(first, { key: 'Enter' });
+ expect(isShown('Which time window?')).toBe(true);
+
+ const last = screen.getByRole('textbox', { name: /Which time window/ });
+ fireEvent.change(last, { target: { value: 'Today' } });
+ fireEvent.keyDown(last, { key: 'Enter' });
+
+ expect(onFormSubmit).not.toHaveBeenCalled();
+ expect(mockSubmitAskAnswer).toHaveBeenCalledWith(
+ 'ask-enter',
+ { environment: 'Locally', window: 'Today' },
+ expect.anything(),
+ );
+ });
+
+ test('Enter that confirms an IME composition neither advances nor submits', () => {
+ renderBatch('ask-ime');
+ const first = screen.getByRole('textbox', { name: /Where should this run/ });
+ fireEvent.change(first, { target: { value: '本番' } });
+ fireEvent.keyDown(first, { key: 'Enter', keyCode: 229 });
+
+ expect(isShown('Where should this run?')).toBe(true);
+ expect(mockSubmitAskAnswer).not.toHaveBeenCalled();
+ });
+
+ test('Enter moves focus to the next question', () => {
+ renderBatch('ask-enter-focus');
+ const first = screen.getByRole('textbox', { name: /Where should this run/ });
+ fireEvent.change(first, { target: { value: 'Locally' } });
+ fireEvent.keyDown(first, { key: 'Enter' });
+
+ expect(isShown('Which time window?')).toBe(true);
+ expect(screen.getByRole('group', { name: 'Which time window?' })).toHaveFocus();
});
test('retains partial answers and the current step across surface remounts', () => {
@@ -194,7 +291,7 @@ describe('AskUserQuestions', () => {
expect(screen.queryByRole('button', { name: 'Back' })).not.toBeInTheDocument();
expect(screen.queryByRole('group', { name: 'Question navigation' })).not.toBeInTheDocument();
- fireEvent.click(screen.getByRole('button', { name: 'Yes' }));
+ fireEvent.click(screen.getByRole('button', { name: /Yes/ }));
fireEvent.click(screen.getByRole('button', { name: 'Submit' }));
expect(mockSubmitAskAnswer).toHaveBeenCalledWith(
@@ -213,7 +310,7 @@ describe('AskUserQuestions', () => {
},
]);
- fireEvent.click(screen.getByRole('button', { name: 'Yes' }));
+ fireEvent.click(screen.getByRole('button', { name: /Yes/ }));
fireEvent.click(screen.getByRole('button', { name: 'Submit' }));
expect(mockSubmitAskAnswer).toHaveBeenCalledWith(
@@ -228,7 +325,7 @@ describe('AskUserQuestions', () => {
const view = renderBatch('ask-expired');
fireEvent.click(screen.getByRole('button', { name: 'Next' }));
- expect(screen.getByText('Which time window?')).toBeInTheDocument();
+ expect(isShown('Which time window?')).toBe(true);
mockStatus = 'submitting';
view.rerender(
diff --git a/client/src/components/Chat/ask/options.tsx b/client/src/components/Chat/ask/options.tsx
index 88301c58fd..9af98b07fe 100644
--- a/client/src/components/Chat/ask/options.tsx
+++ b/client/src/components/Chat/ask/options.tsx
@@ -23,6 +23,7 @@ export default function AskOptions({
multiSelect,
checked,
selected,
+ selectedIsAnswer = false,
locked,
onActivate,
optionRefs,
@@ -33,6 +34,9 @@ export default function AskOptions({
multiSelect: boolean;
checked: number[];
selected?: number | null;
+ /** `selected` is the recorded answer rather than a keyboard highlight, so a
+ * single-select row announces it as pressed. */
+ selectedIsAnswer?: boolean;
locked: boolean;
onActivate: (index: number) => void;
optionRefs?: React.MutableRefObject<(HTMLButtonElement | null)[]>;
@@ -42,7 +46,11 @@ export default function AskOptions({
return (
<div ref={listRef} className={className}>
{options.map((option, index) => {
- const isChecked = multiSelect && checked.includes(index);
+ /** A recorded single-select answer wears the same check as a ticked
+ * multi-select row; a keyboard highlight keeps its number. */
+ const isChecked = multiSelect
+ ? checked.includes(index)
+ : selectedIsAnswer && selected === index;
return (
<Button
key={option.value}
@@ -51,19 +59,17 @@ export default function AskOptions({
optionRefs.current[index] = el;
}
}}
- variant="ghost"
+ variant="option"
+ data-selected={selected === index || undefined}
role={multiSelect ? 'checkbox' : undefined}
aria-checked={multiSelect ? isChecked : undefined}
+ aria-pressed={!multiSelect && selectedIsAnswer ? selected === index : undefined}
disabled={locked}
- className={cn(
- 'flex h-auto w-full justify-start gap-2.5 whitespace-normal px-2.5 py-2 text-left text-sm font-normal text-text-primary',
- selected === index && 'bg-surface-active hover:bg-surface-active',
- )}
onClick={() => onActivate(index)}
>
<span
className={cn(
- 'flex size-5 shrink-0 items-center justify-center rounded-md text-[11px] font-medium tabular-nums transition-colors',
+ 'flex size-5 shrink-0 items-center justify-center rounded-md text-[11px] font-medium tabular-nums',
isChecked
? 'bg-surface-submit text-text-on-status'
: 'bg-surface-tertiary text-text-secondary',
diff --git a/client/src/components/ui/AutoHeight.tsx b/client/src/components/ui/AutoHeight.tsx
new file mode 100644
index 0000000000..9d378628b1
--- /dev/null
+++ b/client/src/components/ui/AutoHeight.tsx
@@ -0,0 +1,55 @@
+import { useLayoutEffect, useRef, useState } from 'react';
+import type { ReactNode } from 'react';
+import { cn } from '~/utils';
+
+/**
+ * Swaps its content instantly and eases only its own height to the new
+ * content's size. The single element that animates: wrap content that does not
+ * animate its own height (for that, stack `Collapse`s instead), or the two
+ * motions stack. Measures the fractional border-box height, so nothing is
+ * clipped by rounding, and stays `auto` until the first measurement so mounting
+ * does not animate. The clip box bleeds 4px past the content on every side, so
+ * focus rings on the controls inside are not cut off.
+ */
+export default function AutoHeight({
+ children,
+ className,
+}: {
+ children: ReactNode;
+ className?: string;
+}) {
+ const contentRef = useRef<HTMLDivElement>(null);
+ const [height, setHeight] = useState<number | null>(null);
+
+ useLayoutEffect(() => {
+ const node = contentRef.current;
+ if (node == null) {
+ return;
+ }
+ const measure = () => {
+ const next = node.getBoundingClientRect().height;
+ setHeight((previous) => (previous === next ? previous : next));
+ };
+ measure();
+ if (typeof ResizeObserver === 'undefined') {
+ return;
+ }
+ const observer = new ResizeObserver(measure);
+ observer.observe(node);
+ return () => observer.disconnect();
+ }, []);
+
+ return (
+ <div
+ className={cn(
+ '-m-1 overflow-hidden transition-all duration-300 ease-out motion-reduce:transition-none',
+ className,
+ )}
+ style={height == null ? undefined : { height }}
+ >
+ <div ref={contentRef} className="p-1">
+ {children}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/ui/__tests__/AutoHeight.spec.tsx b/client/src/components/ui/__tests__/AutoHeight.spec.tsx
new file mode 100644
index 0000000000..be3574c817
--- /dev/null
+++ b/client/src/components/ui/__tests__/AutoHeight.spec.tsx
@@ -0,0 +1,26 @@
+import React from 'react';
+import { render, screen } from '@testing-library/react';
+import AutoHeight from '../AutoHeight';
+
+describe('AutoHeight', () => {
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it('sizes the clip box to the measured content, fractions included', () => {
+ jest
+ .spyOn(HTMLElement.prototype, 'getBoundingClientRect')
+ .mockReturnValue({ height: 87.5 } as DOMRect);
+
+ render(
+ <AutoHeight>
+ <p>{'Which time window?'}</p>
+ </AutoHeight>,
+ );
+
+ const content = screen.getByText('Which time window?').parentElement as HTMLElement;
+ const clip = content.parentElement as HTMLElement;
+ expect(clip.style.height).toBe('87.5px');
+ expect(clip).toHaveClass('overflow-hidden', 'transition-all', 'motion-reduce:transition-none');
+ });
+});
diff --git a/client/src/components/ui/index.ts b/client/src/components/ui/index.ts
index cc841484dd..bbc8022214 100644
--- a/client/src/components/ui/index.ts
+++ b/client/src/components/ui/index.ts
@@ -1,5 +1,6 @@
export { Button, FieldMessage } from '@librechat/client';
export { default as Collapse } from './Collapse';
+export { default as AutoHeight } from './AutoHeight';
export { default as Description } from './Description';
export { getPlainDescription, isHtmlDescription } from './Description';
export { default as CustomIcon } from './CustomIcon';
diff --git a/client/src/hooks/Input/__tests__/useComposerHint.spec.ts b/client/src/hooks/Input/__tests__/useComposerHint.spec.ts
index 57ea6393ee..264b4b4c1c 100644
--- a/client/src/hooks/Input/__tests__/useComposerHint.spec.ts
+++ b/client/src/hooks/Input/__tests__/useComposerHint.spec.ts
@@ -20,20 +20,11 @@ const baseState: ComposerHintState = {
idleActions: { prompts: true, mentions: true, attach: true },
};
-/** What `useShortcutDisplay('stopGenerating')` resolves to by default on a Mac. */
-const STOP = '⌘ ⇧ X';
-
-const hint = (
- overrides: Partial<ComposerHintState>,
- isMac = true,
- stop = STOP,
- altEnterInterrupt = true,
-) =>
- composeHint({ ...baseState, ...overrides }, localize, isMac, stop, undefined, altEnterInterrupt)
- .text;
+const hint = (overrides: Partial<ComposerHintState>, isMac = true, altEnterInterrupt = true) =>
+ composeHint({ ...baseState, ...overrides }, localize, isMac, undefined, altEnterInterrupt).text;
const kindOf = (overrides: Partial<ComposerHintState>) =>
- composeHint({ ...baseState, ...overrides }, localize, true, STOP).kind;
+ composeHint({ ...baseState, ...overrides }, localize, true).kind;
describe('composeHint', () => {
it('shows discovery affordances on an untouched composer', () => {
@@ -58,23 +49,11 @@ describe('composeHint', () => {
expect(hint({ hasText: true })).toBe('com_ui_composer_hint_typing');
});
- /* The line used to read "Esc to stop", which no handler anywhere implements:
- stopping is bound to the `stopGenerating` shortcut, and the user can rebind
- it. Naming a key the composer does not answer to is worse than naming none. */
- it('names the live stop binding while generating with an empty composer', () => {
- expect(hint({ isSubmitting: true })).toBe('⌘ ⇧ X com_ui_composer_hint_stop');
- expect(hint({ isSubmitting: true }, false, 'Ctrl+Shift+X')).toBe(
- 'Ctrl+Shift+X com_ui_composer_hint_stop',
- );
- });
-
- it('names no stop key until the stop control can act', () => {
- expect(hint({ isSubmitting: true, canStop: false })).toBe('com_ui_composer_hint_running');
- expect(hint({ isSubmitting: true, canStop: true })).toBe('⌘ ⇧ X com_ui_composer_hint_stop');
- });
-
- it('names no key at all once the binding is cleared', () => {
- expect(hint({ isSubmitting: true }, true, '')).toBe('com_ui_composer_hint_running');
+ /* The stop button sits beside the composer, so a plain running reply names
+ no key; the copy is ambient, shown only to users who keep tips on. */
+ it('names no stop key while generating with an empty composer', () => {
+ expect(hint({ isSubmitting: true })).toBe('com_ui_composer_hint_running');
+ expect(kindOf({ isSubmitting: true })).toBe('tip');
});
describe('during a run with text', () => {
@@ -105,9 +84,9 @@ describe('composeHint', () => {
expect(hint(state, false)).toContain('Alt+⏎');
});
- it('falls back to stop when the modifiers have no text to act on', () => {
+ it('falls back to the running copy when the modifiers have no text to act on', () => {
expect(hint({ duringRunActive: true, hasText: false, isSubmitting: true })).toBe(
- '⌘ ⇧ X com_ui_composer_hint_stop',
+ 'com_ui_composer_hint_running',
);
});
@@ -150,7 +129,7 @@ describe('composeHint', () => {
or disabled shortcuts each make the chord do something else; the hint
follows the same verdict the during-run button reads. */
it('omits the interrupt chord when the resolver no longer returns it', () => {
- const result = hint({ ...preEpoch, canControlGeneration: true }, true, STOP, false);
+ const result = hint({ ...preEpoch, canControlGeneration: true }, true, false);
expect(result).not.toContain('com_ui_composer_hint_interrupt');
expect(result).not.toContain('⌥⏎');
expect(result).toContain('com_ui_composer_hint_send_now');
@@ -172,7 +151,6 @@ describe('composeHint', () => {
{ ...baseState, hasText: true, enterToSend: false },
localize,
true,
- STOP,
{ customized: true, display: '' },
).text;
expect(result).toBe('⏎ com_ui_composer_hint_newline');
@@ -199,7 +177,6 @@ describe('composeHint', () => {
});
it('marks anything happening right now as state, which always shows', () => {
- expect(kindOf({ isSubmitting: true })).toBe('state');
expect(kindOf({ uploadingCount: 1 })).toBe('state');
expect(kindOf({ answerModeActive: true })).toBe('state');
expect(kindOf({ duringRunActive: true, hasText: true })).toBe('state');
diff --git a/client/src/hooks/Input/useAskAnswerMode.ts b/client/src/hooks/Input/useAskAnswerMode.ts
index a3e4b06de7..a01cb9c33f 100644
--- a/client/src/hooks/Input/useAskAnswerMode.ts
+++ b/client/src/hooks/Input/useAskAnswerMode.ts
@@ -229,24 +229,11 @@ export default function useAskAnswerMode(conversationId?: string | null) {
}, [liveAsk?.actionId, setSelected, setChecked]);
/** Popover ⇄ chat-card handoffs run inside a view transition: both
- * surfaces carry the same `view-transition-name`, so the browser morphs
- * one into the other instead of swapping. Both are user-event driven,
- * which morphTransition's synchronous flush requires.
- *
- * Batches opt out: only the single-question surfaces declare
- * `view-transition-name: ask-question`, so wrapping a batch handoff would
- * give the browser nothing to pair and it would cross-fade the whole root
- * (chat plus composer) instead. */
- const runHandoff = useCallback(
- (update: () => void) => {
- if (batchMode) {
- update();
- return;
- }
- morphTransition(update);
- },
- [batchMode],
- );
+ * surfaces carry the same `view-transition-name`, single questions and
+ * batches alike, so the browser morphs one into the other instead of
+ * swapping. Both are user-event driven, which morphTransition's
+ * synchronous flush requires. */
+ const runHandoff = morphTransition;
const collapse = useCallback(() => {
if (liveAsk) {
diff --git a/client/src/hooks/Input/useAskQuestionsForm.ts b/client/src/hooks/Input/useAskQuestionsForm.ts
index f4f4b21d8c..5357831f9b 100644
--- a/client/src/hooks/Input/useAskQuestionsForm.ts
+++ b/client/src/hooks/Input/useAskQuestionsForm.ts
@@ -1,5 +1,6 @@
import { useCallback, useMemo } from 'react';
-import { atomFamily, useRecoilState, useResetRecoilState } from 'recoil';
+import { atom, useAtom } from 'jotai';
+import { atomFamily } from 'jotai/utils';
import type { Agents } from 'librechat-data-provider';
import {
useAskSubmitStatus,
@@ -16,10 +17,12 @@ interface AskQuestionsFormState {
selected: Record<string, string[]>;
}
-const askQuestionsFormState = atomFamily<AskQuestionsFormState, string>({
- key: 'askQuestionsFormState',
- default: { step: 0, text: {}, selected: {} },
-});
+const EMPTY_FORM: AskQuestionsFormState = { step: 0, text: {}, selected: {} };
+
+/** Keyed by action id, so the composer popover and the chat card share one form. */
+const askQuestionsFormFamily = atomFamily((_actionId: string) =>
+ atom<AskQuestionsFormState>(EMPTY_FORM),
+);
function ownValue<T>(record: Record<string, T>, key: string): T | undefined {
return Object.hasOwn(record, key) ? record[key] : undefined;
@@ -29,8 +32,8 @@ export default function useAskQuestionsForm(
actionId: string,
questions: Agents.AskUserQuestionBatchItem[],
) {
- const [state, setState] = useRecoilState(askQuestionsFormState(actionId));
- const resetState = useResetRecoilState(askQuestionsFormState(actionId));
+ const [state, setState] = useAtom(askQuestionsFormFamily(actionId));
+ const resetState = useCallback(() => setState(EMPTY_FORM), [setState]);
const { submitAskAnswer } = useResumeSubmit();
const { getAskStatus } = useAskSubmitStatus();
const status = getAskStatus(actionId);
@@ -41,8 +44,10 @@ export default function useAskQuestionsForm(
setState((previous) => ({
...previous,
text: { ...previous.text, [question.id]: value },
+ /** A typed answer replaces the choices: the rows lock while the field
+ * has text, so nothing stays selected behind them. */
selected:
- question.multiSelect === true || value.length === 0
+ value.trim().length === 0
? previous.selected
: { ...previous.selected, [question.id]: [] },
}));
diff --git a/client/src/hooks/Input/useComposerHint.ts b/client/src/hooks/Input/useComposerHint.ts
index 12f0e882db..19f54d2e85 100644
--- a/client/src/hooks/Input/useComposerHint.ts
+++ b/client/src/hooks/Input/useComposerHint.ts
@@ -2,7 +2,6 @@ import { useMemo } from 'react';
import type { LocalizeFunction } from '~/common';
import { isMacPlatform, bindingDisplayString, resolveComposerKeyDown } from '~/utils/shortcuts';
import useComposerBindings from '~/hooks/Input/useComposerBindings';
-import { useShortcutDisplay } from '~/hooks/useKeyboardShortcuts';
import useLocalize from '~/hooks/useLocalize';
/** The effective `submitMessage` binding, reduced to what the hints need.
@@ -25,9 +24,6 @@ export interface ComposerHintState {
* later, and until it lands every chord that touches the live run refuses.
* Queueing is local, so it works throughout. */
canControlGeneration: boolean;
- /** Whether the stop control can act yet; the stop shortcut presses it, so
- * the key is named only once it does something. Defaults to reachable. */
- canStop?: boolean;
/** Which action Enter takes during a run, per the effective setting. */
duringRunAction: 'steer' | 'queue';
steerInterruptsByDefault?: boolean;
@@ -74,9 +70,6 @@ export function composeHint(
state: ComposerHintState,
localize: LocalizeFunction,
isMac: boolean,
- /** The live binding for `stopGenerating`, which the user can rebind or clear
- * outright, so the stop line is built from it rather than naming a key. */
- stopShortcut: string,
/** The live `submitMessage` binding, for the same reason: the send chords
* named below follow the customization instead of asserting the stock one. */
sendBinding: SendBinding = DEFAULT_SEND_BINDING,
@@ -167,16 +160,10 @@ export function composeHint(
}
if (state.isSubmitting) {
- /* Nothing to advertise when the binding has been cleared: the stop button
- is right there, and naming a key that does nothing is worse than saying
- only that a reply is running. */
- return {
- text:
- stopShortcut && state.canStop !== false
- ? `${stopShortcut} ${localize('com_ui_composer_hint_stop')}`
- : localize('com_ui_composer_hint_running'),
- kind: 'state',
- };
+ /* The stop button is right there, so a plain running reply advertises
+ nothing under the composer; the line stays as ambient copy for screen
+ readers and for users who keep tips on. */
+ return { text: localize('com_ui_composer_hint_running'), kind: 'tip' };
}
if (state.hasText) {
@@ -207,7 +194,6 @@ export function composeHint(
export default function useComposerHint(state: ComposerHintState): ComposerHint {
const localize = useLocalize();
- const stopShortcut = useShortcutDisplay('stopGenerating');
const { shortcutsEnabled, submitOverride, yieldedChords } = useComposerBindings();
const sendBinding = useMemo<SendBinding>(
() => ({
@@ -241,5 +227,5 @@ export default function useComposerHint(state: ComposerHintState): ComposerHint
) === 'interrupt',
[shortcutsEnabled, state.enterToSend, submitOverride, yieldedChords],
);
- return composeHint(state, localize, isMacPlatform, stopShortcut, sendBinding, altEnterInterrupt);
+ return composeHint(state, localize, isMacPlatform, sendBinding, altEnterInterrupt);
}
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 797ac500a2..e693f8998d 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -1350,7 +1350,6 @@
"com_ui_composer_hint_send_now": "send now",
"com_ui_composer_hint_steer": "Enter steers",
"com_ui_composer_hint_steer_verb": "steers",
- "com_ui_composer_hint_stop": "to stop",
"com_ui_composer_hint_typing": "Enter to send · Shift+Enter for newline",
"com_ui_composer_hint_uploading": "Uploading {{count}} files…",
"com_ui_composer_hint_uploading_one": "Uploading {{count}} file…",
@@ -2267,7 +2266,6 @@
"com_ui_quality": "Quality",
"com_ui_question_failed": "Question wasn't shown",
"com_ui_question_failed_description": "The agent couldn't show this question and may retry automatically.",
- "com_ui_question_number": "Question {{0}}",
"com_ui_question_step": "Question {{0}} of {{1}}",
"com_ui_question_navigation": "Question navigation",
"com_ui_question_step_answered": "Go to question {{0}}, answered",
@@ -2275,8 +2273,6 @@
"com_ui_questions_remaining_one": "{{0}} question still needs an answer",
"com_ui_questions_remaining": "{{0}} questions still need an answer",
"com_ui_answer_questions_above": "Answer the questions above",
- "com_ui_asking_questions_one": "Asking {{0}} question",
- "com_ui_asking_questions": "Asking {{0}} questions",
"com_ui_question_unanswered": "No answer was given",
"com_ui_queue": "Queue",
"com_ui_queue_edit_blocked": "Clear the message box in this chat, or finish answering the question, to edit this message.",
diff --git a/client/src/style.css b/client/src/style.css
index d193d4f3c4..a521364058 100644
--- a/client/src/style.css
+++ b/client/src/style.css
@@ -2523,11 +2523,21 @@ html[data-input-modality='keyboard']
/* ask_user_question popover <-> chat-card morph (view transition) */
::view-transition-group(ask-question),
::view-transition-old(ask-question),
-::view-transition-new(ask-question) {
+::view-transition-new(ask-question),
+::view-transition-group(ask-question-chevron),
+::view-transition-old(ask-question-chevron),
+::view-transition-new(ask-question-chevron) {
animation-duration: 280ms;
animation-timing-function: cubic-bezier(0.32, 0.72, 0.22, 1);
}
+/* The move control's chevron is its own group, so the morph also turns it
+ (down in the composer, up in the chat): the group interpolates the icon's
+ rotate-180. Above its card, below the composer like the card itself. */
+::view-transition-group(ask-question-chevron) {
+ z-index: 1;
+}
+
/* The composer keeps its own snapshot group stacked above the morphing
question card, so the card travels behind the ChatForm, not over it. */
::view-transition-group(chat-form) {
diff --git a/e2e/setup/fake-model.js b/e2e/setup/fake-model.js
index e0743d68ae..051add55a3 100644
--- a/e2e/setup/fake-model.js
+++ b/e2e/setup/fake-model.js
@@ -63,6 +63,9 @@ const ACTIVITY_PHASE_REPLY_MARKER = 'E2E_ACTIVITY_PHASE_REPLY:';
const ACTIVITY_FAILED_REPLY_MARKER = 'E2E_ACTIVITY_FAILED_REPLY:';
const ACTIVITY_PROSE_REPLY_MARKER = 'E2E_ACTIVITY_PROSE_REPLY:';
const ASK_USER_QUESTION_MARKER = 'E2E_ASK_USER_QUESTION:';
+/** A three-question batch; the LONG variant gives the first question a maximum-size prompt. */
+const ASK_USER_QUESTIONS_MARKER = 'E2E_ASK_USER_QUESTIONS:';
+const ASK_USER_LONG_QUESTIONS_MARKER = 'E2E_ASK_USER_LONG_QUESTIONS:';
const RESUME_ICON_REPLY_MARKER = 'E2E_RESUME_ICON_REPLY:';
const FORCED_ERROR_MARKER = 'E2E_FORCED_ERROR:';
const MARKDOWN_REPLY_MARKER = 'E2E_MARKDOWN_REPLY';
@@ -1876,6 +1879,68 @@ function askUserQuestionResponses(label, toolNames) {
};
}
+function askUserQuestionBatchResponses(label, toolNames, { long }) {
+ if (!toolNames.has(ASK_USER_QUESTION_TOOL_NAME)) {
+ return askUserQuestionResponses(label, toolNames);
+ }
+ /** Near the tool's limits: a 2,000-character question and a 4,000-character description. */
+ const longQuestion =
+ `Which environment for ${label}? ${'Explain the deployment target. '.repeat(64)}`
+ .slice(0, 2000)
+ .trim();
+ const longDescription = Array.from(
+ { length: 60 },
+ (_, index) => `Line ${index + 1} of the long clarification for ${label}.`,
+ )
+ .join(' ')
+ .slice(0, 4000);
+ return {
+ responses: [''],
+ toolCalls: [
+ {
+ id: `call_e2e_ask_user_questions_${label}`,
+ name: ASK_USER_QUESTION_TOOL_NAME,
+ args: {
+ questions: [
+ {
+ id: 'environment',
+ question: long ? longQuestion : `Which environment for ${label}?`,
+ ...(long ? { description: longDescription } : {}),
+ options: [
+ { label: 'Staging', value: 'staging' },
+ { label: 'Production', value: 'production' },
+ ...(long
+ ? Array.from({ length: 6 }, (_, index) => ({
+ label: `Region ${index + 1}: ${'a deliberately long option label '.repeat(4)}`,
+ value: `region-${index + 1}`,
+ }))
+ : []),
+ ],
+ },
+ {
+ id: 'region',
+ question: `Which region for ${label}?`,
+ options: [
+ { label: 'Europe', value: 'europe' },
+ { label: 'Americas', value: 'americas' },
+ ],
+ },
+ {
+ id: 'notes',
+ question: `Anything else for ${label}?`,
+ options: [
+ { label: 'Nothing else', value: 'none' },
+ { label: 'Call me first', value: 'call' },
+ ],
+ },
+ ],
+ },
+ type: 'tool_call',
+ },
+ ],
+ };
+}
+
function findLastToolMessageText(messages, requiredToken) {
for (let index = (messages ?? []).length - 1; index >= 0; index--) {
const message = messages[index];
@@ -3387,6 +3452,14 @@ function resolveResponses({ graph, messages, text, toolNames }) {
return activityFailedReplyResponses(activityFailedLabel, toolNames);
}
+ const askBatchLabel = getMarkerValue(text, ASK_USER_QUESTIONS_MARKER);
+ const askLongBatchLabel = getMarkerValue(text, ASK_USER_LONG_QUESTIONS_MARKER);
+ if (askBatchLabel || askLongBatchLabel) {
+ return askUserQuestionBatchResponses(askBatchLabel || askLongBatchLabel, toolNames, {
+ long: Boolean(askLongBatchLabel),
+ });
+ }
+
const askUserQuestionLabel = getMarkerValue(text, ASK_USER_QUESTION_MARKER);
if (askUserQuestionLabel) {
return askUserQuestionResponses(askUserQuestionLabel, toolNames);
diff --git a/e2e/specs/mock/scenarios/ask-question-refine.spec.ts b/e2e/specs/mock/scenarios/ask-question-refine.spec.ts
new file mode 100644
index 0000000000..e04d229831
--- /dev/null
+++ b/e2e/specs/mock/scenarios/ask-question-refine.spec.ts
@@ -0,0 +1,328 @@
+import { expect, test } from '@playwright/test';
+import type { Page, Request } from '@playwright/test';
+import type { AgentDetail } from '../agents.helpers';
+import { cleanupAgent, openAgentBuilder, uniqueAgentName } from '../agents.helpers';
+import {
+ MOCK_ENDPOINTS,
+ NEW_CHAT_PATH,
+ escapeRegExp,
+ getAccessToken,
+ messagesView,
+ requestJson,
+ sendMessage,
+} from '../helpers';
+
+/**
+ * The fake model (e2e/setup/fake-model.js) pauses a real agent run at
+ * `ask_user_question` with a three-question batch for `E2E_ASK_USER_QUESTIONS:`,
+ * and with a maximum-size first prompt for `E2E_ASK_USER_LONG_QUESTIONS:`. The
+ * popover, card, form state and resume request are all the production ones.
+ */
+
+/* The agent setup goes through the desktop agent builder side panel, so these scenarios pin a
+ desktop pointer context; the long-prompt one shrinks the height to keep its bound meaningful. */
+test.use({ viewport: { width: 1280, height: 800 }, isMobile: false, hasTouch: false });
+
+type BatchQuestion = {
+ id: string;
+ question: string;
+ description?: string;
+ header?: string;
+ multiSelect?: boolean;
+ options?: Array<{ label: string; value: string }>;
+};
+
+type AskResumeBody = { actionId?: string; answers?: Record<string, string> };
+
+const ASK_TOOL_ID = 'ask_user_question';
+const MOVE_TO_CHAT = 'Answer later in the chat';
+const MOVE_TO_COMPOSER = 'Answer from the message box';
+
+const isResumeRequest = (request: Request) =>
+ request.method() === 'POST' && new URL(request.url()).pathname === '/api/agents/chat/resume';
+
+/** A new generation (not a resume or abort): what a composer submit would start. */
+const isGenerationStart = (request: Request) => {
+ const { pathname } = new URL(request.url());
+ return (
+ request.method() === 'POST' &&
+ pathname.startsWith('/api/agents/chat') &&
+ !pathname.endsWith('/resume') &&
+ !pathname.endsWith('/abort')
+ );
+};
+
+/** The batch the fake model asks, in order. */
+function buildBatch(label: string): BatchQuestion[] {
+ return [
+ { id: 'environment', question: `Which environment for ${label}?` },
+ { id: 'region', question: `Which region for ${label}?` },
+ { id: 'notes', question: `Anything else for ${label}?` },
+ ];
+}
+
+async function createAgent(page: Page): Promise<AgentDetail> {
+ await page.goto(NEW_CHAT_PATH, { timeout: 15000 });
+ const token = await getAccessToken(page);
+ const agent = await requestJson<AgentDetail>(page, {
+ path: '/api/agents',
+ token,
+ method: 'POST',
+ body: {
+ name: uniqueAgentName('E2E Ask Batch Agent'),
+ description: 'Pauses at ask_user_question for the batched question scenarios.',
+ instructions: 'Ask the user the question the test requests.',
+ provider: MOCK_ENDPOINTS[0].label,
+ model: MOCK_ENDPOINTS[0].model,
+ tools: [ASK_TOOL_ID],
+ },
+ });
+ expect(agent.tools).toEqual(expect.arrayContaining([ASK_TOOL_ID]));
+ return agent;
+}
+
+async function selectAgent(page: Page, agent: AgentDetail) {
+ const form = await openAgentBuilder(page);
+ await form.getByRole('combobox', { name: 'Agent', exact: true }).click();
+ await page.getByRole('option', { name: agent.name }).click();
+ await expect(form.getByLabel('Agent name')).toHaveValue(agent.name ?? '');
+ await form.getByRole('button', { name: 'Select Agent' }).click();
+}
+
+/**
+ * Pauses a real run at ask_user_question with the fake model's batch and
+ * returns the composer popover, identified by its move-to-chat control.
+ */
+async function openBatch(page: Page, agent: AgentDetail, label: string, long = false) {
+ await selectAgent(page, agent);
+ const marker = long ? 'E2E_ASK_USER_LONG_QUESTIONS' : 'E2E_ASK_USER_QUESTIONS';
+ const response = await sendMessage(page, `${marker}:${label}`);
+ expect(response.ok()).toBeTruthy();
+ await expect(page).toHaveURL(/\/c\/(?!new)/, { timeout: 15000 });
+ await expect(page.getByRole('button', { name: MOVE_TO_CHAT })).toBeVisible({ timeout: 30000 });
+ await expect(page.getByRole('group', { name: 'Question navigation' })).toBeVisible();
+ return popoverOf(page);
+}
+
+const popoverOf = (page: Page) =>
+ page.locator('.popover').filter({ has: page.getByRole('button', { name: MOVE_TO_CHAT }) });
+
+const answerField = (scope: Page | ReturnType<typeof popoverOf>, question: string) =>
+ scope.getByRole('textbox', { name: new RegExp(`^${escapeRegExp(question)}`) });
+
+const optionRow = (scope: Page | ReturnType<typeof popoverOf>, name: string) =>
+ scope.getByRole('button', { name: new RegExp(`${escapeRegExp(name)}$`) });
+
+test.describe('ask question batch refinements', () => {
+ test('Enter in an answer field confirms the step instead of sending the composer @scenario:ask-batch-enter-confirms-answer', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ const label = `${Date.now()}-${Math.floor(Math.random() * 1e4)}`;
+ const questions = buildBatch(label);
+ let agentId: string | undefined;
+
+ try {
+ const agent = await createAgent(page);
+ agentId = agent.id;
+ const popover = await openBatch(page, agent, label);
+
+ const generationStarts: string[] = [];
+ page.on('request', (request) => {
+ if (isGenerationStart(request)) {
+ generationStarts.push(request.url());
+ }
+ });
+
+ const first = answerField(popover, questions[0].question);
+ await expect(first).toBeVisible();
+ await first.fill('typed-first-answer');
+ await first.press('Enter');
+
+ await expect(popover.getByText(questions[1].question, { exact: true })).toBeVisible();
+ await expect(popover.getByText(questions[0].question, { exact: true })).toBeHidden();
+ expect(generationStarts).toEqual([]);
+ await expect(messagesView(page).getByText('typed-first-answer')).toHaveCount(0);
+
+ const middle = answerField(popover, questions[1].question);
+ await middle.fill('typed-middle-answer');
+ await middle.press('Enter');
+ await expect(popover.getByText(questions[2].question, { exact: true })).toBeVisible();
+
+ const last = answerField(popover, questions[2].question);
+ await last.fill('typed-last-answer');
+ const [resumeRequest] = await Promise.all([
+ page.waitForRequest(isResumeRequest),
+ last.press('Enter'),
+ ]);
+ const body = resumeRequest.postDataJSON() as AskResumeBody;
+ expect(body.answers).toEqual({
+ [questions[0].id]: 'typed-first-answer',
+ [questions[1].id]: 'typed-middle-answer',
+ [questions[2].id]: 'typed-last-answer',
+ });
+ await expect(popover).toBeHidden({ timeout: 30000 });
+ expect(generationStarts).toEqual([]);
+ } finally {
+ await cleanupAgent(page, agentId);
+ }
+ });
+
+ test('a very long prompt keeps the popover inside the viewport and scrolls @scenario:ask-batch-long-prompt-fits-viewport', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ await page.setViewportSize({ width: 1280, height: 640 });
+ const label = `${Date.now()}-${Math.floor(Math.random() * 1e4)}`;
+ let agentId: string | undefined;
+
+ try {
+ const agent = await createAgent(page);
+ agentId = agent.id;
+ const popover = await openBatch(page, agent, label, true);
+
+ const prompt = popover.locator('div[class*="max-h-[25vh]"]').first();
+ await expect(prompt).toContainText(`Line 60 of the long clarification for ${label}`);
+
+ /** The card eases to its height, so wait for the settled box. */
+ await expect
+ .poll(async () => (await popover.boundingBox())?.y ?? -1, { timeout: 5000 })
+ .toBeGreaterThanOrEqual(0);
+ const metrics = await prompt.evaluate((element) => ({
+ scrollHeight: element.scrollHeight,
+ clientHeight: element.clientHeight,
+ overflowY: getComputedStyle(element).overflowY,
+ viewportHeight: window.innerHeight,
+ }));
+ expect(metrics.overflowY).toBe('auto');
+ expect(metrics.scrollHeight).toBeGreaterThan(metrics.clientHeight);
+ expect(metrics.clientHeight).toBeLessThanOrEqual(
+ Math.ceil(metrics.viewportHeight * 0.25) + 1,
+ );
+
+ const box = await popover.boundingBox();
+ expect(box).not.toBeNull();
+ expect(box!.y).toBeGreaterThanOrEqual(0);
+ expect(box!.height).toBeLessThanOrEqual(Math.ceil(metrics.viewportHeight * 0.7) + 1);
+
+ /* With both regions at their caps, scrolling the card reaches the answer field rather
+ than leaving it clipped below the footer. */
+ await popover.evaluate((element) => {
+ element.scrollTop = element.scrollHeight;
+ });
+ await popover.locator('div[class*="max-h-[45vh]"]').evaluate((element) => {
+ element.scrollTop = element.scrollHeight;
+ });
+ await expect(popover.getByRole('textbox')).toBeInViewport();
+ } finally {
+ await cleanupAgent(page, agentId);
+ }
+ });
+
+ test('option rows skip their fade under reduced motion @scenario:ask-option-rows-skip-fade-under-reduced-motion', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ await page.emulateMedia({ reducedMotion: 'reduce' });
+ const label = `${Date.now()}-${Math.floor(Math.random() * 1e4)}`;
+ const questions = buildBatch(label);
+ let agentId: string | undefined;
+
+ const fadeOf = (row: ReturnType<typeof optionRow>) =>
+ row.evaluate((element) => {
+ const style = getComputedStyle(element);
+ return { property: style.transitionProperty, duration: style.transitionDuration };
+ });
+ const expectNoFade = (fade: { property: string; duration: string }) => {
+ const instant = fade.property === 'none' || /^(0s)(,\s*0s)*$/.test(fade.duration);
+ expect(instant, `transition ${fade.property} / ${fade.duration}`).toBe(true);
+ };
+
+ try {
+ const agent = await createAgent(page);
+ agentId = agent.id;
+ const popover = await openBatch(page, agent, label);
+
+ const row = optionRow(popover, 'Staging');
+ await expect(row).toBeEnabled();
+ expectNoFade(await fadeOf(row));
+
+ await answerField(popover, questions[0].question).fill('locks the rows');
+ await expect(row).toBeDisabled();
+ expectNoFade(await fadeOf(row));
+ } finally {
+ await cleanupAgent(page, agentId);
+ }
+ });
+
+ test('typed answers survive moving the batch to the chat card @scenario:ask-batch-answers-survive-move-to-chat', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ const label = `${Date.now()}-${Math.floor(Math.random() * 1e4)}`;
+ const questions = buildBatch(label);
+ let agentId: string | undefined;
+
+ try {
+ const agent = await createAgent(page);
+ agentId = agent.id;
+ const popover = await openBatch(page, agent, label);
+
+ await answerField(popover, questions[0].question).fill('kept-across-surfaces');
+ await popover.getByRole('button', { name: 'Next', exact: true }).click();
+ await expect(popover.getByText(questions[1].question, { exact: true })).toBeVisible();
+
+ await popover.getByRole('button', { name: MOVE_TO_CHAT }).click();
+ await expect(popover).toBeHidden();
+
+ /** The card resumes on step 2, not step 1. */
+ const card = messagesView(page);
+ await expect(card.getByText(questions[1].question, { exact: true })).toBeVisible();
+ await expect(card.getByText(questions[0].question, { exact: true })).toBeHidden();
+ await expect(card.getByRole('button', { name: MOVE_TO_COMPOSER })).toBeVisible();
+
+ await card.getByRole('button', { name: 'Back', exact: true }).click();
+ await expect(card.getByText(questions[0].question, { exact: true })).toBeVisible();
+ await expect(answerField(card, questions[0].question)).toHaveValue('kept-across-surfaces');
+ } finally {
+ await cleanupAgent(page, agentId);
+ }
+ });
+
+ test('a typed answer deselects the option and locks the rows until cleared @scenario:ask-typed-answer-locks-options', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ const label = `${Date.now()}-${Math.floor(Math.random() * 1e4)}`;
+ const questions = buildBatch(label).slice(0, 2);
+ let agentId: string | undefined;
+
+ try {
+ const agent = await createAgent(page);
+ agentId = agent.id;
+ const popover = await openBatch(page, agent, label);
+
+ /** A single-select choice records the answer and advances; come back to it. */
+ await optionRow(popover, 'Staging').click();
+ await expect(popover.getByText(questions[1].question, { exact: true })).toBeVisible();
+ await popover.getByRole('button', { name: 'Go to question 1, answered' }).click();
+
+ const staging = optionRow(popover, 'Staging');
+ const production = optionRow(popover, 'Production');
+ await expect(staging).toHaveAttribute('aria-pressed', 'true');
+
+ const field = answerField(popover, questions[0].question);
+ await field.fill('something else');
+ await expect(staging).toHaveAttribute('aria-pressed', 'false');
+ await expect(staging).toBeDisabled();
+ await expect(production).toBeDisabled();
+
+ await field.fill('');
+ await expect(staging).toBeEnabled();
+ await expect(production).toBeEnabled();
+ await expect(staging).toHaveAttribute('aria-pressed', 'false');
+ } finally {
+ await cleanupAgent(page, agentId);
+ }
+ });
+});
diff --git a/eslint-suppressions.json b/eslint-suppressions.json
index 8bb8ca3c90..6f0f8ac839 100644
--- a/eslint-suppressions.json
+++ b/eslint-suppressions.json
@@ -158,7 +158,7 @@
},
"client/src/components/Chat/Input/AskUserQuestionPopover.tsx": {
"shadcn/no-restyle": {
- "count": 13
+ "count": 7
}
},
"client/src/components/Chat/Input/ChatForm.tsx": {
@@ -402,11 +402,8 @@
}
},
"client/src/components/Chat/Messages/Content/AskUserQuestion.tsx": {
- "shadcn/no-inline-styles": {
- "count": 1
- },
"shadcn/no-restyle": {
- "count": 14
+ "count": 11
}
},
"client/src/components/Chat/Messages/Content/AskUserQuestionCall.tsx": {
@@ -414,11 +411,6 @@
"count": 1
}
},
- "client/src/components/Chat/Messages/Content/AskUserQuestions.tsx": {
- "shadcn/no-restyle": {
- "count": 10
- }
- },
"client/src/components/Chat/Messages/Content/Container.tsx": {
"shadcn/no-raw-colors": {
"count": 1
@@ -883,9 +875,6 @@
"client/src/components/Chat/ask/options.tsx": {
"shadcn/no-arbitrary-values": {
"count": 1
- },
- "shadcn/no-restyle": {
- "count": 8
}
},
"client/src/components/Conversations/Convo.tsx": {
diff --git a/packages/client/src/components/Button.spec.tsx b/packages/client/src/components/Button.spec.tsx
index 617f27a5c2..a816eea93c 100644
--- a/packages/client/src/components/Button.spec.tsx
+++ b/packages/client/src/components/Button.spec.tsx
@@ -258,6 +258,21 @@ describe('Button', () => {
expect(header).not.toMatch(/(^|\s)(hover:)?active:bg-/);
});
+ it('gives an option row an instant fill, a slow disabled fade and its own height', () => {
+ const row = cn(buttonVariants({ variant: 'option' }));
+
+ /** Only opacity eases while enabled, so the hover fill stays instant. */
+ expect(row).toContain('transition-opacity');
+ expect(row).toContain('enabled:duration-500');
+ expect(row).toContain('disabled:duration-500');
+ /** Reduced motion drops both fades, the disabled one included. */
+ expect(row).toContain('motion-reduce:transition-none');
+ expect(row).toContain('motion-reduce:disabled:transition-none');
+ expect(row).toContain('h-auto');
+ expect(row).not.toContain('h-theme-button');
+ expect(row).not.toMatch(/(^|\s)transition-colors(\s|$)/);
+ });
+
it('still takes a size when a caller asks for one', () => {
expect(cn(buttonVariants({ variant: 'section-header', size: 'sm' }))).toContain(
'h-theme-button-sm',
diff --git a/packages/client/src/components/Button.tsx b/packages/client/src/components/Button.tsx
index 9e67358801..3f979e6ea8 100644
--- a/packages/client/src/components/Button.tsx
+++ b/packages/client/src/components/Button.tsx
@@ -27,6 +27,7 @@ type ButtonVariantOptions =
| 'inline-edit'
| 'card'
| 'disclosure'
+ | 'option'
| null
| undefined;
size?:
@@ -157,6 +158,19 @@ const buttonVariantRecipe = cva(
*/
disclosure:
'w-full justify-start focus-visible:ring-border-heavy focus-visible:ring-offset-0 disabled:opacity-100',
+ /**
+ * A full-width answer row in an option list, such as the choices of an
+ * `ask_user_question`. The fill follows the pointer instantly rather than
+ * easing, so moving down a list reads as a cursor, while locking and
+ * unlocking fades slowly: only opacity transitions while enabled, and a
+ * disabled row, which cannot be hovered, eases its theme colors too.
+ * The duration rides on `enabled:`/`disabled:` so it outranks the base
+ * `duration-theme-fast` by specificity, which tailwind-merge cannot
+ * resolve between the two. Reduced motion drops both fades.
+ * `data-selected` marks the highlighted or chosen row.
+ */
+ option:
+ 'w-full select-none justify-start gap-2.5 whitespace-normal text-left font-normal text-text-primary transition-opacity enabled:duration-500 disabled:duration-500 disabled:transition-all motion-reduce:transition-none motion-reduce:disabled:transition-none hover:bg-surface-hover hover:active:bg-surface-pressed data-[selected=true]:bg-surface-active data-[selected=true]:hover:bg-surface-active',
card: 'justify-start whitespace-normal rounded-2xl text-left font-normal hover:bg-surface-hover focus-visible:ring-inset focus-visible:ring-offset-0',
},
size: {
@@ -210,6 +224,12 @@ const buttonVariantRecipe = cva(
size: 'default',
class: 'h-auto px-1 py-2',
},
+ /* Sized by its own label, so a long option wraps instead of clipping. */
+ {
+ variant: 'option',
+ size: 'default',
+ class: 'h-auto px-2.5 py-2',
+ },
/* Sized and shaped by the row it heads, like `section-header`. */
{
variant: 'disclosure',