❓ refactor: Move the Ask-User Question Cards Into @librechat/chat (#18161)

- refactor: Move Ask User Question Cards Into the Chat Package
- fix: Preserve Ask Card Styling Without Suppression Growth
- fix: Provide Live Ask Pauses As Scoped Context Data
- test: Cover the Settled Ask Record Collapse Cascade
- fix: Give the Ask Call Spec Host the Tool Call Chrome
This commit is contained in:
Marco Beretta 2026-11-14 19:11:57 +01:00 • committed by GitHub
parent 33cab12ae5
commit 2bf6ca847a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
44 changed files with 2052 additions and 1345 deletions

View file

@ -0,0 +1,33 @@
import { useContext } from 'react';
import { collectLiveAskToolCallIds } from '@librechat/chat';
import { AskAnswerHostProvider } from '@librechat/chat/react';
import type { LiveAskPauses } from '@librechat/chat/react';
import type { ReactNode } from 'react';
import { ChatContext } from '~/Providers/ChatContext';
import { useCachedMessages } from '~/data-provider';
/**
* Live ask pauses in the open conversation, subscribed by the host.
*/
export function useChatLiveAskPauses(): LiveAskPauses | null {
const conversationId = useContext(ChatContext)?.conversation?.conversationId;
const enabled = conversationId != null && conversationId !== 'new';
const { data } = useCachedMessages(enabled ? conversationId : '', collectLiveAskToolCallIds);
return data ?? null;
}
/** The chat's ask host: whether drafts are saved, and which ask calls are already interactive. */
export default function AskHost({
saveDrafts,
children,
}: {
saveDrafts: boolean;
children?: ReactNode;
}) {
const liveAskPauses = useChatLiveAskPauses();
return (
<AskAnswerHostProvider saveDrafts={saveDrafts} liveAskPauses={liveAskPauses}>
{children}
</AskAnswerHostProvider>
);
}

View file

@ -9,7 +9,6 @@ import {
submissionByIndex,
ChatSessionProvider,
useScrollbarGutterSeed,
AskAnswerHostProvider,
ComposerRestoreProvider,
pendingApprovalActionFamily,
} from '@librechat/chat/react';
@ -32,6 +31,7 @@ import Presentation from './Presentation';
import ChatForm from './Input/ChatForm';
import { TraceSurface } from './Trace';
import Lia from '~/components/Lia';
import AskHost from './AskHost';
import Landing from './Landing';
import Header from './Header';
import store from '~/store';
@ -150,7 +150,7 @@ function ChatViewPane({
<TargetContext.Provider value={readiness}>
<AgentsMapContext.Provider value={selectedAgents}>
<AssistantsMapContext.Provider value={selectedAssistants}>
<AskAnswerHostProvider saveDrafts={saveDrafts}>
<AskHost saveDrafts={saveDrafts}>
<ChatFormProvider {...methods}>
<ComposerRestoreProvider>
<QueuedTurnPortalProvider>
@ -219,7 +219,7 @@ function ChatViewPane({
</QueuedTurnPortalProvider>
</ComposerRestoreProvider>
</ChatFormProvider>
</AskAnswerHostProvider>
</AskHost>
</AssistantsMapContext.Provider>
</AgentsMapContext.Provider>
</TargetContext.Provider>

View file

@ -1,445 +1,30 @@
import { useContext, useMemo, useRef, useState } from 'react';
import { AskOptions } from '@librechat/chat/components';
import { useOptionalChatSurface } from '@librechat/chat/react';
import { ChevronDown, MessageCircleQuestion, TriangleAlert } from 'lucide-react';
import { Button, Shimmer, TooltipAnchor, TextareaAutosize } from '@librechat/client';
import {
isCancelKey,
isReboundSubmitChord,
resolveComposerKeyDown,
splitOtherOption,
ASK_USER_DECLINED_ANSWER,
} from '@librechat/chat';
import type { Agents } from 'librechat-data-provider';
import type { KeyboardEvent } from 'react';
import { useApprovalContext, useAskSubmitStatus, useResumeSubmit } from './ApprovalContext';
import useArrivalFocus, { isFocusIdle } from '~/hooks/Input/useArrivalFocus';
import { NO_HOST_BINDINGS } from '~/hooks/Input/useComposerBindings';
import { cn, forceResize, insertTextAtCursor } from '~/utils';
import { useContext } from 'react';
import { AskUserQuestion as Question } from '@librechat/chat/components';
import type { ComponentProps } from 'react';
import { useApprovalContext, useResumeSubmit } from './ApprovalContext';
import useAskAnswerMode from '~/hooks/Input/useAskAnswerMode';
import { ChatContext } from '~/Providers/ChatContext';
import AskUserQuestions from './AskUserQuestions';
import { useLocalize } from '~/hooks';
/**
* Single questions whose card has already had its arrival. A card remounts when
* its row scrolls back into view or the question moves between the chat and the
* composer, and none of those is a new arrival. Holds only action ids, one per
* question asked in this tab.
*/
const arrivedSingleQuestions = new Set<string>();
type QuestionProps = ComponentProps<typeof Question>;
/** Stock preferences for a card rendered outside a chat surface. */
/**
* Renders an `ask_user_question` pause: the prompt, optional description, any
* curated option buttons, and a free-form text answer. Single-select options
* submit on click; multi-select options toggle and Submit confirms the set
* (plus any typed text). While this card is the LIVE pause's surface it
* shares selection state and submit paths with {@link useAskAnswerMode}, so
* the composer, the popover, and this card always agree on what will be
* sent; outside a live pause (Share/search) it falls back to local state.
*/
export default function AskUserQuestion({
actionId,
question,
questions,
}: {
actionId: string;
question: Agents.AskUserQuestionRequest;
questions?: Agents.AskUserQuestionBatchItem[];
}) {
/** The app's ask card: answer mode, resume, and the draft the approval host keeps. */
export default function AskUserQuestion(
props: Omit<
QuestionProps,
'answerMode' | 'submitAskAnswer' | 'getAskAnswerDraft' | 'setAskAnswerDraft'
>,
) {
const conversationId = useContext(ChatContext)?.conversation?.conversationId;
const answerMode = useAskAnswerMode(conversationId);
const isLivePause = answerMode.liveAsk?.actionId === actionId;
if (questions != null && questions.length > 0) {
/** 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}
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}
focusOnArrival={live}
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,
answerMode,
}: {
actionId: string;
question: Agents.AskUserQuestionRequest;
answerMode: ReturnType<typeof useAskAnswerMode>;
}) {
const localize = useLocalize();
const { getAskAnswerDraft, setAskAnswerDraft } = useApprovalContext();
const { getAskStatus } = useAskSubmitStatus();
const { submitAskAnswer } = useResumeSubmit();
const [answer, setAnswer] = useState(() => getAskAnswerDraft(actionId));
const [localChecked, setLocalChecked] = useState<number[]>([]);
const surface = useOptionalChatSurface();
const enterToSend = surface?.enterToSend ?? false;
const { shortcutsEnabled, submitOverride, yieldedChords } =
surface?.composerBindings ?? NO_HOST_BINDINGS;
/**
* This card is the question's default surface, in thread order and at the
* thread's width, so it reads the same on a phone as on a desktop. Its
* chevron moves a live question into the composer popover; while the
* popover is VISIBLE, rendering the card too would duplicate the question,
* so the card holds its footprint hidden until the question comes back.
*/
const { popoverVisible, collapsed, expand, liveAsk } = answerMode;
const isLivePause = liveAsk?.actionId === actionId;
/** Same fold as the popover: a model-supplied catch-all "Other" option
* becomes the free-form textarea's placeholder, not a submittable row. */
const { choices, otherLabel } = useMemo(
() => splitOtherOption(question.options),
[question.options],
);
const status = getAskStatus(actionId);
const locked = status === 'submitting' || status === 'submitted' || status === 'expired';
const showPlaceholder = popoverVisible && isLivePause;
/**
* The question arriving in the chat puts the user on its first option, or on
* its answer field when it has none, so keys typed next answer it rather than
* going out as an ordinary message. Only once it is on screen, and only when
* focus is idle then (nowhere, or the empty composer that sent the turn).
*/
const cardRef = useRef<HTMLDivElement>(null);
const optionRefs = useRef<(HTMLButtonElement | null)[]>([]);
const answerRef = useRef<HTMLTextAreaElement>(null);
useArrivalFocus(
isLivePause && !showPlaceholder && !locked && !arrivedSingleQuestions.has(actionId),
cardRef,
() => {
if (arrivedSingleQuestions.has(actionId)) {
return;
}
arrivedSingleQuestions.add(actionId);
if (!isFocusIdle()) {
return;
}
const target = optionRefs.current.find((option) => option != null && !option.disabled);
(target ?? answerRef.current)?.focus({ preventScroll: true });
},
);
if (status === 'submitted') {
return null;
}
const multiSelect = question.multiSelect === true;
/** Live pause: share the hook's checked set so the composer's Enter and
* this card submit exactly what the card displays. */
const checkedIndices = isLivePause ? answerMode.checked : localChecked;
const answerValue = isLivePause ? answerMode.answerText : answer;
const setAnswerValue = (value: string) => {
if (isLivePause) {
answerMode.setAnswerText(value);
return;
}
setAnswer(value);
};
const toggleIndex = (index: number) => {
if (isLivePause) {
answerMode.toggleChecked(index);
return;
}
setLocalChecked((prev) =>
prev.includes(index) ? prev.filter((i) => i !== index) : [...prev, index],
);
};
const trimmed = answerValue.trim();
const canSubmit = multiSelect
? checkedIndices.length > 0 || trimmed.length > 0
: trimmed.length > 0;
const submitSingle = (index: number) => {
if (isLivePause) {
answerMode.submitOption(index);
return;
}
const value = choices[index]?.value;
if (value != null) {
submitAskAnswer(actionId, value);
}
};
/** `answerMode.skip()` is gated on answer mode being ACTIVE, which a
* question moved to the chat is not. That is precisely when this card
* is the only surface left. Decline through the answer path instead,
* which is gated on the live pause rather than on answer mode. */
const handleSkip = () => {
if (isLivePause) {
answerMode.submitAnswer([ASK_USER_DECLINED_ANSWER]);
return;
}
submitAskAnswer(actionId, ASK_USER_DECLINED_ANSWER);
};
const submitCombined = () => {
const values = multiSelect
? checkedIndices
.map((index) => choices[index]?.value)
.filter((value): value is string => typeof value === 'string')
: [];
if (trimmed.length > 0) {
values.push(trimmed);
}
if (values.length === 0) {
return;
}
if (isLivePause) {
answerMode.submitAnswer(values);
return;
}
submitAskAnswer(actionId, values.join(', '));
};
/**
* The answer box follows the composer's Enter table, so the user's
* Enter-to-send preference and any rebound submit chord apply here too. The
* run is paused on this question rather than generating, so it resolves as
* idle: Ctrl/Cmd+Enter must submit the answer, not reach the during-run
* steer/queue actions.
*/
const handleAnswerKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
const isComposing = e.nativeEvent.isComposing || e.key === 'Process' || e.keyCode === 229;
if (!isComposing && isReboundSubmitChord(e.nativeEvent, { shortcutsEnabled, submitOverride })) {
e.preventDefault();
if (canSubmit && !locked) {
submitCombined();
}
return;
}
const action = resolveComposerKeyDown(e.nativeEvent, {
isComposing,
isSubmitting: false,
allowSubmitWhileGenerating: false,
hasDuringRunModifier: false,
shortcutsEnabled,
enterToSend,
submitOverride,
yieldedChords,
});
if (action === 'none') {
return;
}
e.preventDefault();
if (action === 'newline') {
insertTextAtCursor(e.currentTarget, '\n');
forceResize(e.currentTarget);
return;
}
if (action === 'submit' && canSubmit && !locked) {
submitCombined();
}
};
/** Escape skips, but only before anything is entered, so a stray Escape
* cannot discard an answer and resume the run. */
const handleCardKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
if (!isCancelKey(e.nativeEvent) || e.nativeEvent.isComposing) {
return;
}
if (locked || trimmed.length > 0 || (multiSelect && checkedIndices.length > 0)) {
return;
}
e.preventDefault();
handleSkip();
};
/**
* The live card shares its view-transition-name with the popover panel, so
* collapse/expand morphs one surface into the other. The placeholder copy
* is `visibility: hidden` (out of the tab order and the a11y tree) and
* carries NO transition name because duplicate names would void the morph, but
* it still occupies the card's exact footprint, so the thread reserves the
* space while the question lives in the composer and nothing reflows when
* it moves back.
*/
const card = (
<div
ref={cardRef}
className={cn(
'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}
onKeyDown={handleCardKeyDown}
>
<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>
{question.description != null && question.description.length > 0 && (
<p className="text-text-secondary mt-0.5 text-xs [overflow-wrap:anywhere]">
{question.description}
</p>
)}
</div>
{collapsed && isLivePause && (
<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={expand}
>
<ChevronDown
className="size-4 rotate-180 [view-transition-name:ask-question-chevron]"
aria-hidden="true"
/>
</Button>
}
/>
)}
</div>
{choices.length > 0 && (
<AskOptions
options={choices}
multiSelect={multiSelect}
checked={checkedIndices}
locked={locked}
onActivate={(index) => (multiSelect ? toggleIndex(index) : submitSingle(index))}
optionRefs={optionRefs}
/>
)}
<TextareaAutosize
ref={answerRef}
focusOutline="hidden"
value={answerValue}
disabled={locked}
onChange={(e) => {
setAnswerValue(e.target.value);
setAskAnswerDraft(actionId, e.target.value);
}}
onKeyDown={handleAnswerKeyDown}
minRows={2}
maxRows={12}
placeholder={otherLabel ?? localize('com_ui_your_answer')}
className="border-border-light bg-surface-chat text-text-primary placeholder:text-text-secondary focus-visible:ring-text-primary w-full resize-none rounded-lg border px-3 py-2 text-sm focus-visible:ring-2"
aria-label={localize('com_ui_your_answer')}
/>
<div className="flex items-center gap-3">
<Button size="sm" variant="outline" disabled={locked} onClick={handleSkip}>
{localize('com_ui_skip')}
</Button>
{(status === 'expired' || status === 'error') && (
<span className="text-text-warning flex min-w-0 items-center text-xs">
<TriangleAlert className="me-1.5 size-4 shrink-0" aria-hidden="true" />
{localize(status === 'expired' ? 'com_ui_approval_expired' : 'com_ui_approval_error')}
</span>
)}
<Button
size="sm"
variant="submit"
className="ms-auto"
disabled={!canSubmit || locked}
onClick={submitCombined}
>
{status === 'submitting' ? localize('com_ui_submitting') : localize('com_ui_submit')}
</Button>
</div>
</div>
);
if (!showPlaceholder) {
return card;
}
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">
{children}
<div className="text-text-secondary absolute inset-x-0 top-0 my-1 flex h-5 items-center gap-2.5">
<MessageCircleQuestion className="size-4 shrink-0" aria-hidden="true" />
<Shimmer className="tool-status-text font-medium">{localize('com_ui_asking')}</Shimmer>
</div>
</div>
<Question
{...props}
answerMode={answerMode}
submitAskAnswer={submitAskAnswer}
getAskAnswerDraft={getAskAnswerDraft}
setAskAnswerDraft={setAskAnswerDraft}
/>
);
}

View file

@ -1,294 +0,0 @@
import { useCallback } from 'react';
import { MessageCircleQuestion, TriangleAlert } from 'lucide-react';
import { toolPanelSpacingClassName, useToolExpansion } from '@librechat/chat/react';
import {
EmptyText,
TOOL_ROW_CLASSES,
Container,
useExpandCollapse,
} from '@librechat/chat/components';
import {
getSubmittedAskAnswer,
parseAskUserQuestionArgs,
parseAskUserQuestionsArgs,
} from '@librechat/chat';
import type { Agents, PartMetadata } from 'librechat-data-provider';
import AskUserQuestionProgress from './AskUserQuestionProgress';
import ProgressText from './ProgressText';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
/**
* Static rendering of a COMPLETED (or abandoned) `ask_user_question` tool call —
* the durable record of the Q&A after the pause resolves. The generic tool card
* is wrong here: it labels a no-output call "cancelled" and shows raw JSON args.
* The interactive card ({@link AskUserQuestion}) renders only while the pause is
* live; this component owns the part everywhere else (history, reload, exports).
*
* Settled, it is history — so it reads as one collapsed tool-call line (status
* label plus the question itself) and opens on demand, under the same
* `autoExpandTools` preference every other tool card follows. Answers are
* frequently long, multi-paragraph text; left expanded they buried the reply
* that followed them.
*/
export default function AskUserQuestionCall({
args,
output,
toolCallId,
isSubmitting = false,
runStepStatus,
failed = false,
showCursor = false,
onExpand,
}: {
args: string | Record<string, unknown> | undefined;
output: string;
toolCallId?: string;
isSubmitting?: boolean;
runStepStatus?: PartMetadata['runStepStatus'];
failed?: boolean;
showCursor?: boolean;
onExpand?: () => void;
}) {
const localize = useLocalize();
const [expanded, setExpanded] = useToolExpansion(true);
const { style: expandStyle, ref: expandRef } = useExpandCollapse(expanded);
const toggleExpanded = useCallback(() => {
setExpanded(!expanded);
if (!expanded) {
onExpand?.();
}
}, [expanded, onExpand, setExpanded]);
const question = parseAskUserQuestionArgs(args);
const batch = parseAskUserQuestionsArgs(args);
/**
* The part's own output arrives from the server only at finalize, and the
* streaming handler's message copy can overwrite the optimistic store stamp
* mid-stream — fall back to the locally-recorded submitted answer so the
* Q&A record never blinks out while the resumed segment streams.
*/
const effectiveOutput = output.length > 0 ? output : (getSubmittedAskAnswer(toolCallId) ?? '');
const batchAnswers = (() => {
if (batch == null || effectiveOutput.length === 0) {
return null;
}
try {
const parsed = JSON.parse(effectiveOutput) as { answers?: unknown };
return parsed.answers != null && typeof parsed.answers === 'object'
? (parsed.answers as Record<string, string>)
: null;
} catch {
return null;
}
})();
const terminalFailure = failed || runStepStatus === 'failed';
const answered =
!terminalFailure &&
(batch != null
? batch.questions.every((item) => typeof batchAnswers?.[item.id] === 'string')
: effectiveOutput.length > 0);
/**
* While the turn is live and unanswered, the INTERACTIVE card (rendered from
* the pendingAction's synthetic part) owns the question UI — rendering the
* durable record too would duplicate it with a misleading "no answer" line.
* Until that pause actually starts (args still streaming, interrupt not yet
* delivered) the progress card fills the gap. Once the user answers, the
* submit handler stamps `output` onto this part, so the record takes over
* immediately; an abandoned pause only shows its "no answer" state after
* the turn is no longer submitting.
*/
if (!answered && !terminalFailure && runStepStatus == null && isSubmitting) {
return <AskUserQuestionProgress args={args} toolCallId={toolCallId} />;
}
/**
* The run resumes the moment the pause resolves (an answer submits, or a
* schema-rejected call auto-retries), but its first token takes a beat to
* arrive — hold the streaming cursor under the settled card so the turn
* never looks stalled between the answer and the resumed text.
*/
const resumingCursor =
isSubmitting && showCursor ? (
<Container>
<EmptyText />
</Container>
) : null;
const count = batch?.questions.length ?? 1;
/**
* Past tense unconditionally: a live, unanswered pause returns above, so
* every state that reaches this header is settled — answered, abandoned
* (the run stopped before an answer), or rejected. An abandoned pause was
* still ASKED; it explains itself with "no answer" inside the panel, and a
* present-tense summary would strand it as permanently in-flight now that
* the panel starts closed. Matches `ToolCallGroup`, which settles its own
* question header on `!isSubmitting`.
*/
const statusLabel = (() => {
if (terminalFailure) {
return localize('com_ui_question_failed');
}
return count > 1
? localize('com_ui_asked_n_questions', { 0: String(count) })
: localize('com_ui_asked');
})();
/** A batch is summarized by its count; a lone question is summarized by
* itself, so the collapsed line still says what was asked. */
const summary = count > 1 ? undefined : (batch?.questions[0]?.question ?? question?.question);
return (
<>
<div className={TOOL_ROW_CLASSES} data-testid="ask-user-question-call">
<ProgressText
phase={terminalFailure ? 'failed' : 'completed'}
onClick={toggleExpanded}
inProgressText={statusLabel}
finishedText={statusLabel}
subtitle={summary}
icon={
terminalFailure ? (
<TriangleAlert className="text-text-warning size-4 shrink-0" aria-hidden="true" />
) : (
<MessageCircleQuestion
className="text-text-secondary size-4 shrink-0"
aria-hidden="true"
/>
)
}
isExpanded={expanded}
/>
</div>
{/* A rejected call is the one state the reader did not ask for and
cannot see coming. The explanation lives in the panel, which starts
closed and is `inert` while it is — so the announcement has to sit
outside the disclosure to reach the accessibility tree at all. */}
{terminalFailure && (
<span className="sr-only" role="status">
{`${statusLabel}. ${localize('com_ui_question_failed_description')}`}
</span>
)}
<div style={expandStyle}>
<div className="overflow-hidden" ref={expandRef}>
<div
className={cn(
toolPanelSpacingClassName,
'border-border-light bg-surface-secondary flex w-full flex-col gap-4 rounded-lg border p-4',
)}
>
{batch != null ? (
batch.questions.map((item, index) => (
<div
key={item.id}
className={index > 0 ? 'border-border-inset border-t pt-4' : undefined}
>
{item.header != null && (
<p className="text-text-secondary mb-1 text-xs font-medium">{item.header}</p>
)}
<QuestionBody
question={item.question}
description={item.description}
answer={batchAnswers?.[item.id]}
options={item.options}
multiSelect={item.multiSelect}
failed={terminalFailure}
/>
</div>
))
) : (
<QuestionBody
question={question?.question ?? ''}
description={question?.description}
answer={answered ? effectiveOutput : undefined}
options={question?.options}
multiSelect={question?.multiSelect}
failed={terminalFailure}
/>
)}
{terminalFailure && (
<p className="text-text-secondary text-sm leading-relaxed">
{localize('com_ui_question_failed_description')}
</p>
)}
</div>
</div>
</div>
{resumingCursor}
</>
);
}
/**
* One question and its answer. Every text slot here is authored — by the model
* or by the user — so line breaks are content, not whitespace: `pre-wrap`
* keeps a numbered or paragraphed answer legible instead of collapsing it into
* one wall of text. The answer sits under its own label behind a rule rather
* than running on from it, so the eye can find where the reply starts.
*/
function QuestionBody({
question,
description,
answer,
options,
multiSelect,
failed,
}: {
question: string;
description?: string;
answer?: string;
options?: Agents.AskUserQuestionRequest['options'];
multiSelect?: boolean;
failed: boolean;
}) {
const localize = useLocalize();
return (
<div className="min-w-0">
{question.length > 0 && (
<p className="text-text-primary text-sm leading-relaxed font-medium [overflow-wrap:anywhere] whitespace-pre-wrap">
{question}
</p>
)}
{description != null && description.length > 0 && (
<p className="text-text-secondary mt-1 text-sm leading-relaxed [overflow-wrap:anywhere] whitespace-pre-wrap">
{description}
</p>
)}
{typeof answer === 'string' && (
<div className="border-border-medium mt-2.5 border-s-2 ps-3">
<p className="text-text-secondary text-xs font-medium">
{localize('com_ui_you_answered')}
</p>
<p className="text-text-primary mt-0.5 text-sm leading-relaxed [overflow-wrap:anywhere] whitespace-pre-wrap">
{formatAnswerLabel({ question, options, multiSelect }, answer)}
</p>
</div>
)}
{typeof answer !== 'string' && !failed && (
<p className="text-text-secondary mt-2.5 text-sm italic">
{localize('com_ui_question_unanswered')}
</p>
)}
</div>
);
}
/**
* Prefer the picked option's label over its wire value when they differ.
* Multi-select answers are option values joined by ", " — map the segments
* back to labels only when EVERY segment matches an option: values may
* legally contain ", " themselves, and a partial mapping could mis-split
* such a value into fragments that relabel as options the user never
* picked. When any segment misses, show the raw answer untouched.
*/
function formatAnswerLabel(question: Agents.AskUserQuestionRequest, answer: string): string {
const exactLabel = question.options?.find((option) => option.value === answer)?.label;
if (exactLabel != null || question.multiSelect !== true || question.options == null) {
return exactLabel ?? answer;
}
const labels = answer
.split(', ')
.map((segment) => question.options?.find((option) => option.value === segment)?.label);
return labels.every((label) => label != null) ? labels.join(', ') : answer;
}

View file

@ -1,92 +0,0 @@
import { useContext } from 'react';
import { Shimmer } from '@librechat/client';
import { MessageCircleQuestion } from 'lucide-react';
import { useToolPreparation } from '@librechat/chat/components';
import {
parseJsonField,
parseJsonFieldOccurrences,
collectLiveAskToolCallIds,
} from '@librechat/chat';
import { ChatContext } from '~/Providers/ChatContext';
import { useCachedMessages } from '~/data-provider';
import { useLocalize } from '~/hooks';
/**
* Interim card for an `ask_user_question` call whose pause hasn't gone
* interactive yet: the window between the model starting the call and the
* interrupt's synthetic part arriving (which hands the UI to the popover /
* interactive card). Without it a long question, many options, or several
* parallel questions leave a dead gap after the last streamed token.
*
* The first question text streams in live from either the legacy top-level
* field or the first item in the batched `questions` array.
*
* Mounted only for a live, unanswered call ({@link AskUserQuestionCall}
* gates on `isSubmitting`), so the live-ask subscription below never runs
* for the settled cards in history.
*/
export default function AskUserQuestionProgress({
args,
toolCallId,
}: {
args: string | Record<string, unknown> | undefined;
toolCallId?: string;
}) {
const localize = useLocalize();
const preparationText = useToolPreparation();
const conversationId = useContext(ChatContext)?.conversation?.conversationId;
const enabled = conversationId != null && conversationId !== 'new';
const { data: livePauses } = useCachedMessages(
enabled ? conversationId : '',
collectLiveAskToolCallIds,
);
const legacyQuestion = parseJsonField(args, 'question');
const batchQuestion = (() => {
if (typeof args === 'string') {
return parseJsonFieldOccurrences(args, 'question')[0] ?? '';
}
const questions = args?.questions;
if (!Array.isArray(questions)) {
return '';
}
const first = questions[0];
if (first == null || typeof first !== 'object') {
return '';
}
const firstQuestion = (first as { question?: unknown }).question;
return typeof firstQuestion === 'string' ? firstQuestion : '';
})();
const question = legacyQuestion || batchQuestion;
/**
* THIS call's pause went interactive: the popover (or the interactive card)
* now owns the question's UI. Checked against every live pause, not just the
* newest, so a sibling pause arriving later can never resurrect this card
* next to its own interactive one. An unattributed live ask (no
* `tool_call_id` on older payloads) can't be matched to a call, so treat it
* as owning every placeholder rather than duplicating the question on screen.
*/
const interactive =
livePauses != null &&
(livePauses.hasUnattributed || (toolCallId != null && livePauses.ids.includes(toolCallId)));
if (interactive) {
return null;
}
return (
<div className="border-border-light bg-surface-secondary my-2 flex w-full flex-col gap-1.5 rounded-lg border p-3">
<div
className="text-text-secondary flex items-center gap-2 text-xs font-medium"
role="status"
>
<MessageCircleQuestion className="h-4 w-4 animate-pulse" aria-hidden="true" />
<Shimmer>{preparationText ?? localize('com_ui_asking')}</Shimmer>
</div>
{question.length > 0 ? (
<p className="text-text-primary text-sm font-medium [overflow-wrap:anywhere]">{question}</p>
) : (
<div className="bg-surface-tertiary h-4 w-2/5 animate-pulse rounded" aria-hidden="true" />
)}
</div>
);
}

View file

@ -1,463 +1,11 @@
import { useCallback, useEffect, useId, useMemo, useRef } from 'react';
import { TriangleAlert } from 'lucide-react';
import { Input, Button } from '@librechat/client';
import { AskOptions } from '@librechat/chat/components';
import { useOptionalChatSurface } from '@librechat/chat/react';
import { isCancelKey, isReboundSubmitChord, splitOtherOption } from '@librechat/chat';
import type { Agents } from 'librechat-data-provider';
import type { KeyboardEvent, ReactNode } from 'react';
import useArrivalFocus, { isFocusIdle } from '~/hooks/Input/useArrivalFocus';
import useAskQuestionsForm from '~/hooks/Input/useAskQuestionsForm';
import { AutoHeight } from '~/components/ui';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
import { AskUserQuestions as Questions } from '@librechat/chat/components';
import type { ComponentProps } from 'react';
import { useResumeSubmit } from './ApprovalContext';
/**
* One bounded batch of `ask_user_question` items, presented a single question at
* a time. The batch arrives as one interrupt and submits as one answer map — the
* stepper is purely presentational, so Submit still waits until every question
* has an answer and Skip still declines the whole batch from any step.
*/
export default function AskUserQuestions({
actionId,
questions,
className,
headerAction,
focusOnArrival = false,
focusOnHandoff = false,
onEscape,
}: {
actionId: string;
questions: Agents.AskUserQuestionBatchItem[];
className?: string;
/** This surface is the live pause's visible one, so the batch arriving may
* take focus. A Share view or a hidden footprint copy leaves it alone. */
focusOnArrival?: boolean;
/** The batch was just moved onto this surface, which is on screen: it takes
* focus whenever focus is idle, even after an earlier arrival did. */
focusOnHandoff?: boolean;
/** 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;
/** Escape on this surface. Without one, Escape skips the batch. */
onEscape?: () => void;
}) {
const localize = useLocalize();
const promptId = useId();
const form = useAskQuestionsForm(actionId, questions);
const composerBindings = useOptionalChatSurface()?.composerBindings;
const { goToStep, selectOption } = form;
type QuestionsProps = ComponentProps<typeof Questions>;
const scrollRef = useRef<HTMLDivElement>(null);
const stepRef = useRef<HTMLFieldSetElement>(null);
const answerRef = useRef<HTMLInputElement>(null);
/** Set only when a choice click or an Enter is about to swap the step out
* from under focus, which would otherwise drop focus to <body> mid-batch. */
const refocusRef = useRef(false);
const total = questions.length;
const stepped = total > 1;
const activeIndex = form.step;
const isLastStep = activeIndex === total - 1;
/** Narrower than `locked`: an expired or errored batch is unanswerable but
* still worth paging through, so only an in-flight submit freezes the steps. */
const navLocked = form.status === 'submitting';
const firstUnanswered = useMemo(() => {
for (let index = 0; index < questions.length; index++) {
if (!Object.hasOwn(form.answers, questions[index].id)) {
return index;
}
}
return -1;
}, [questions, form.answers]);
const handleSelectOption = useCallback(
(question: Agents.AskUserQuestionBatchItem, value: string) => {
selectOption(question, value);
if (question.multiSelect === true || activeIndex >= total - 1) {
return;
}
refocusRef.current = true;
goToStep(activeIndex + 1);
},
[activeIndex, goToStep, selectOption, total],
);
/**
* Focus the step's control that is ready to answer: its picked option, else
* the answer field. Each is labelled within the step, so a screen reader
* still announces the new question. The step itself is the fallback when
* every control is locked.
*
* An unpicked option is only a target on arrival (`firstOption`). After a
* step change the key that caused it may still be down: a held or
* double-tapped Enter on a focused option is its click, which would pick it,
* advance again, and on the last step confirm the pick and submit the batch.
*/
const focusStep = useCallback(
({ firstOption = false, ...options }: FocusOptions & { firstOption?: boolean } = {}) => {
const step = stepRef.current;
if (step == null) {
return;
}
const target =
step.querySelector<HTMLElement>('button[data-selected]:not(:disabled)') ??
(firstOption ? step.querySelector<HTMLElement>('button:not(:disabled)') : null) ??
(answerRef.current?.disabled === false ? answerRef.current : null) ??
step;
target.focus(options);
},
[],
);
useEffect(() => {
if (scrollRef.current != null) {
scrollRef.current.scrollTop = 0;
}
if (!refocusRef.current) {
return;
}
refocusRef.current = false;
focusStep();
}, [activeIndex, focusStep]);
/**
* A batch moved onto this surface by the user's own handoff always takes
* focus: the control that did it is gone or hidden (Safari keeps focus on a
* clicked button's previous owner, which may be the now-inert card), so
* there is nothing of the user's to protect.
*/
useEffect(() => {
if (!focusOnHandoff || form.locked) {
return;
}
focusStep({ firstOption: true, preventScroll: true });
form.markArrivalFocused();
// eslint-disable-next-line react-hooks/exhaustive-deps -- handoff happens on mount
}, []);
/**
* An arriving batch puts the user on the first question's controls once it
* is on screen, but only when focus is idle then, so a draft or any other
* control the user is in keeps focus. It happens once per batch: moving it
* between the popover and the chat is not a new arrival.
*/
const latestFormRef = useRef(form);
latestFormRef.current = form;
useArrivalFocus(
focusOnArrival && !focusOnHandoff && !form.locked && !form.arrivalFocused,
stepRef,
() => {
const current = latestFormRef.current;
if (current.locked || current.arrivalFocused || !isFocusIdle()) {
return;
}
focusStep({ firstOption: true, preventScroll: true });
if (stepRef.current?.contains(document.activeElement) === true) {
current.markArrivalFocused();
}
},
);
if (form.status === 'submitted') {
return null;
}
if (questions[activeIndex] == null) {
return null;
}
/** Only worth surfacing when the gap is somewhere the user cannot see: the
* last step's own blank answer field already explains a disabled Submit. */
const remaining = total - Object.keys(form.answers).length;
const showRemaining =
stepped &&
isLastStep &&
!form.locked &&
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] : '';
/** Confirm the current answer: the next step, or the batch on the last one. */
const confirmStep = () => {
if (!isLastStep) {
if (!navLocked) {
refocusRef.current = true;
goToStep(activeIndex + 1);
}
return;
}
form.submit();
};
/**
* Escape is the surface's way out when it has one (the popover moves the
* batch to the chat), else Skip. Skip only fires before anything is
* answered, so a stray Escape cannot discard answers and resume the run.
*/
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
if (!isCancelKey(event.nativeEvent) || event.nativeEvent.isComposing) {
return;
}
if (onEscape != null) {
event.preventDefault();
onEscape();
return;
}
if (form.locked || Object.keys(form.answers).length > 0) {
return;
}
event.preventDefault();
form.skip();
};
return (
<div className={cn('flex min-h-0 flex-col', className)} onKeyDown={handleKeyDown}>
{/* 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 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>
{(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>
)}
</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"
onKeyDown={(event) => {
/* Picking and confirming stay separate (WCAG 3.2.2): Enter on an
option is its click, so a pick never submits by itself. Enter
on the single-select option that is ALREADY the answer confirms
that answer, like Enter in the field: the next step, or the
batch. */
const target = event.target;
if (
event.key !== 'Enter' ||
event.repeat ||
event.shiftKey ||
event.altKey ||
question.multiSelect === true ||
!(target instanceof HTMLButtonElement) ||
target.getAttribute('aria-pressed') !== 'true'
) {
return;
}
event.preventDefault();
confirmStep();
}}
>
{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
ref={answerRef}
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 (or Ctrl/Cmd+Enter) confirms this answer: the next step,
or the batch, and so does a submit shortcut rebound off Enter.
Shift+Enter and Alt+Enter never submit, as in the
composer, and neither does a held Enter repeating into the next
step; those are still kept from submitting the form. An Enter
that confirms an IME composition is left alone, with the same
Safari fallback as the composer. */
const composing =
event.nativeEvent.isComposing || event.nativeEvent.keyCode === 229;
if (
!composing &&
composerBindings != null &&
isReboundSubmitChord(event.nativeEvent, composerBindings)
) {
event.preventDefault();
if (!event.repeat) {
confirmStep();
}
return;
}
if (event.key !== 'Enter' || composing) {
return;
}
event.preventDefault();
if (event.repeat || event.shiftKey || event.altKey) {
return;
}
confirmStep();
}}
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>
)}
{showRemaining && (
<button
type="button"
className="text-text-secondary hover:text-text-primary pt-2 text-start text-xs select-none hover:underline"
onClick={() => goToStep(firstUnanswered)}
>
{localize(
remaining === 1 ? 'com_ui_questions_remaining_one' : 'com_ui_questions_remaining',
{ count: remaining, 0: remaining },
)}
</button>
)}
</div>
</AutoHeight>
<div
className={cn(
'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}
onClick={form.skip}
>
{localize('com_ui_skip')}
</Button>
<div className="flex items-center gap-2">
{stepped && (
<Button
type="button"
className="select-none"
size="sm"
variant="outline"
disabled={navLocked || activeIndex === 0}
onClick={() => goToStep(activeIndex - 1)}
>
{localize('com_ui_back')}
</Button>
)}
{isLastStep ? (
<Button
type="button"
className="select-none"
size="sm"
variant="submit"
disabled={!form.canSubmit}
onClick={form.submit}
>
{form.status === 'submitting'
? localize('com_ui_submitting')
: localize('com_ui_submit')}
</Button>
) : (
<Button
type="button"
className="select-none"
size="sm"
variant="submit"
disabled={navLocked}
onClick={() => goToStep(activeIndex + 1)}
>
{localize('com_ui_next')}
</Button>
)}
</div>
</div>
</div>
);
/** The app's question batch: resume goes through the approval host. */
export default function AskUserQuestions(props: Omit<QuestionsProps, 'submitAskAnswer'>) {
const { submitAskAnswer } = useResumeSubmit();
return <Questions {...props} submitAskAnswer={submitAskAnswer} />;
}

View file

@ -1,5 +1,11 @@
import { memo } from 'react';
import { Part as ChatPart, ToolCall, ToolPreparation, Container } from '@librechat/chat/components';
import {
Part as ChatPart,
ToolCall,
ToolPreparation,
Container,
AskUserQuestionCall,
} from '@librechat/chat/components';
import {
isBashProgrammaticToolCall,
getAskUserQuestionPart,
@ -44,7 +50,6 @@ import {
} from './Parts';
import { getCachedPreview, getPartKeyIndex } from '~/utils';
import BackgroundTaskCall from './Parts/BackgroundTaskCall';
import AskUserQuestionCall from './AskUserQuestionCall';
import { isError } from './ToolOutput/OutputRenderer';
import { ErrorMessage } from './MessageContent';
import AskUserQuestion from './AskUserQuestion';

View file

@ -10,21 +10,21 @@ import {
ElapsedTimer,
CancelledIcon,
ROW_GLYPH_SLOT,
useToolPreparation,
useFailedReveal,
useToolPreparation,
PROGRESS_TEXT_CONTENT,
PROGRESS_TEXT_WRAPPER,
} from '@librechat/chat/components';
import type { ToolCallPhase } from '@librechat/chat';
import { cn, getRunStepDurationLabels } from '~/utils';
import { useLocalize } from '~/hooks';
const wrapperClass =
'progress-text-wrapper text-text-secondary relative -mt-[0.046875rem] h-5 w-full leading-5';
const wrapperClass = PROGRESS_TEXT_WRAPPER;
/** `right-0` and `max-w-full` cap the absolutely-positioned line at the message
* column; the label span truncates itself, so overflow stays visible for the
* button's focus ring. */
const contentClass =
'progress-text-content absolute left-0 right-0 top-0 max-w-full overflow-visible whitespace-nowrap';
const contentClass = PROGRESS_TEXT_CONTENT;
const Wrapper = ({
popover,

View file

@ -0,0 +1,106 @@
import React from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import { ChatContext } from '~/Providers/ChatContext';
import AskUserQuestions from '../AskUserQuestions';
import ApprovalProvider from '../ApprovalContext';
import AskUserQuestion from '../AskUserQuestion';
const mockMutate = jest.fn();
jest.mock('~/data-provider', () => ({
useCachedMessages: () => ({ data: null }),
useSubmitToolApprovalMutation: () => ({ mutate: jest.fn() }),
useSubmitAskAnswerMutation: () => ({ mutate: mockMutate }),
}));
const conversation = {
conversation: { conversationId: 'conversation-1', endpoint: 'agents' },
getMessages: () => [],
setMessages: jest.fn(),
};
function renderQuestion() {
return render(
<ChatContext.Provider value={conversation as never}>
<ApprovalProvider>
<AskUserQuestion
actionId="ask-1"
question={{
question: 'Which environment?',
options: [{ label: 'Staging', value: 'staging' }],
}}
/>
</ApprovalProvider>
</ChatContext.Provider>,
);
}
describe('ask card adapters', () => {
beforeEach(() => {
mockMutate.mockClear();
});
test('restores a typed answer through the approval host after the card remounts', () => {
const view = renderQuestion();
fireEvent.change(screen.getByRole('textbox', { name: 'Type your answer…' }), {
target: { value: 'Use staging first' },
});
view.rerender(
<ChatContext.Provider value={conversation as never}>
<ApprovalProvider>
<AskUserQuestion
key="again"
actionId="ask-1"
question={{ question: 'Which environment?' }}
/>
</ApprovalProvider>
</ChatContext.Provider>,
);
expect(screen.getByRole('textbox', { name: 'Type your answer…' })).toHaveValue(
'Use staging first',
);
});
test('submits a chosen option through the resume mutation', () => {
renderQuestion();
fireEvent.click(screen.getByRole('button', { name: /Staging/ }));
expect(mockMutate).toHaveBeenCalledWith(
expect.objectContaining({
conversationId: 'conversation-1',
actionId: 'ask-1',
answer: 'staging',
}),
expect.any(Object),
);
});
test('submits a batch through the resume mutation', () => {
render(
<ChatContext.Provider value={conversation as never}>
<ApprovalProvider>
<AskUserQuestions
actionId="ask-batch"
questions={[
{ id: 'confirm', question: 'Continue?', options: [{ label: 'Yes', value: 'yes' }] },
]}
/>
</ApprovalProvider>
</ChatContext.Provider>,
);
fireEvent.click(screen.getByRole('button', { name: /Yes/ }));
fireEvent.click(screen.getByRole('button', { name: 'Submit' }));
expect(mockMutate).toHaveBeenCalledWith(
expect.objectContaining({
conversationId: 'conversation-1',
actionId: 'ask-batch',
answers: { confirm: 'yes' },
}),
expect.any(Object),
);
});
});

View file

@ -1,320 +0,0 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
import { ASK_USER_DECLINED_ANSWER } from '@librechat/chat';
import { ChatSurfaceProvider } from '@librechat/chat/react';
import { fireEvent, render, screen } from '@testing-library/react';
import type { ShortcutBinding } from '@librechat/chat';
import type { Agents } from 'librechat-data-provider';
import ApprovalProvider from '../ApprovalContext';
import AskUserQuestion from '../AskUserQuestion';
const mockSubmitAnswer = jest.fn();
const mockSetAnswerText = jest.fn();
const mockInsertTextAtCursor = jest.fn();
let mockPopoverVisible = false;
let mockCollapsed = false;
let mockLiveActionId: string | null = null;
let mockChecked: number[] = [];
let mockAnswerText = '';
/** jsdom has no execCommand, so the newline path is observed through the mock. */
jest.mock('~/utils/textarea', () => ({
...jest.requireActual('~/utils/textarea'),
forceResize: jest.fn(),
insertTextAtCursor: (...args: unknown[]) => mockInsertTextAtCursor(...args),
}));
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => {
const labels: Record<string, string> = {
com_ui_your_answer: 'Your answer',
com_ui_skip: 'Skip',
com_ui_submit: 'Submit',
com_ui_submitting: 'Submitting',
};
return labels[key] ?? key;
},
}));
jest.mock('~/hooks/Input/useAskAnswerMode', () => ({
__esModule: true,
default: () => ({
popoverVisible: mockPopoverVisible,
collapsed: mockCollapsed,
expand: jest.fn(),
liveAsk: mockLiveActionId == null ? null : { actionId: mockLiveActionId },
checked: mockChecked,
toggleChecked: jest.fn(),
submitOption: jest.fn(),
submitAnswer: mockSubmitAnswer,
answerText: mockAnswerText,
setAnswerText: mockSetAnswerText,
}),
}));
jest.mock('~/data-provider', () => ({
useSubmitToolApprovalMutation: () => ({ mutate: jest.fn() }),
useSubmitAskAnswerMutation: () => ({ mutate: jest.fn() }),
}));
jest.mock('~/store/agents', () => ({
useGetEphemeralAgent: () => () => undefined,
}));
jest.mock('~/Providers/ChatContext', () => ({
ChatContext: jest.requireActual('react').createContext({
conversation: { conversationId: 'conversation-1' },
}),
}));
const yieldedChords = new Set<string>();
let submitOverride: ShortcutBinding | undefined;
const tree = (
key: string,
question: Agents.AskUserQuestionRequest = { question: 'Which environment?' },
enterToSend = true,
actionId = 'ask-1',
) => (
<RecoilRoot>
<ChatSurfaceProvider
value={{
enterToSend,
maximizeChatSpace: false,
showScrollButton: false,
composerBindings: { shortcutsEnabled: true, submitOverride, yieldedChords },
claimForeground: jest.fn(),
handOffComposerText: jest.fn(),
}}
>
<ApprovalProvider>
<AskUserQuestion key={key} actionId={actionId} question={question} />
</ApprovalProvider>
</ChatSurfaceProvider>
</RecoilRoot>
);
const withOptions: Agents.AskUserQuestionRequest = {
question: 'Which environment?',
options: [
{ label: 'Staging', value: 'staging' },
{ label: 'Production', value: 'production' },
],
};
describe('AskUserQuestion', () => {
beforeEach(() => {
jest.clearAllMocks();
mockPopoverVisible = false;
mockCollapsed = false;
mockLiveActionId = null;
mockChecked = [];
mockAnswerText = '';
submitOverride = undefined;
});
test('restores a typed answer after the card remounts inside the same message', () => {
const view = render(tree('direct'));
fireEvent.change(screen.getByRole('textbox', { name: 'Your answer' }), {
target: { value: 'Use staging first' },
});
view.rerender(tree('phase-slice'));
expect(screen.getByRole('textbox', { name: 'Your answer' })).toHaveValue('Use staging first');
});
test('submits checked options together with free text carried from the composer', () => {
mockCollapsed = true;
mockLiveActionId = 'ask-1';
mockChecked = [0];
mockAnswerText = 'carried free-form answer';
render(
tree('live', {
question: 'Choose a source',
multiSelect: true,
options: [{ label: 'Public data', value: 'public' }],
}),
);
expect(screen.getByRole('textbox', { name: 'Your answer' })).toHaveValue(
'carried free-form answer',
);
fireEvent.click(screen.getByRole('button', { name: 'Submit' }));
expect(mockSubmitAnswer).toHaveBeenCalledWith(['public', 'carried free-form answer']);
});
describe('answer box keyboard submit', () => {
const liveTree = (enterToSend: boolean, answerText = 'Use staging first') => {
mockCollapsed = true;
mockLiveActionId = 'ask-1';
mockAnswerText = answerText;
return tree('live', { question: 'Which environment?' }, enterToSend);
};
const answerBox = () => screen.getByRole('textbox', { name: 'Your answer' });
test('Enter submits when Enter-to-send is on', () => {
render(liveTree(true));
fireEvent.keyDown(answerBox(), { key: 'Enter' });
expect(mockSubmitAnswer).toHaveBeenCalledWith(['Use staging first']);
});
test('Ctrl+Enter and Cmd+Enter submit when Enter-to-send is off', () => {
render(liveTree(false));
fireEvent.keyDown(answerBox(), { key: 'Enter', ctrlKey: true });
fireEvent.keyDown(answerBox(), { key: 'Enter', metaKey: true });
expect(mockSubmitAnswer).toHaveBeenCalledTimes(2);
});
test('plain Enter writes a newline instead of submitting when Enter-to-send is off', () => {
render(liveTree(false));
fireEvent.keyDown(answerBox(), { key: 'Enter' });
expect(mockSubmitAnswer).not.toHaveBeenCalled();
expect(mockInsertTextAtCursor).toHaveBeenCalledWith(answerBox(), '\n');
});
test('Shift+Enter never submits', () => {
render(liveTree(true));
fireEvent.keyDown(answerBox(), { key: 'Enter', shiftKey: true });
expect(mockSubmitAnswer).not.toHaveBeenCalled();
});
test('Enter confirming an IME composition does not submit', () => {
render(liveTree(true));
fireEvent.keyDown(answerBox(), { key: 'Enter', keyCode: 229 });
expect(mockSubmitAnswer).not.toHaveBeenCalled();
});
test('a submit shortcut rebound off Enter submits the answer', () => {
submitOverride = { meta: false, ctrl: true, alt: false, shift: false, key: 'J' };
render(liveTree(true));
fireEvent.keyDown(answerBox(), { key: 'j', ctrlKey: true });
expect(mockSubmitAnswer).toHaveBeenCalledWith(['Use staging first']);
});
test('does not submit an empty answer', () => {
render(liveTree(true, ' '));
fireEvent.keyDown(answerBox(), { key: 'Enter' });
expect(mockSubmitAnswer).not.toHaveBeenCalled();
});
});
describe('Escape', () => {
const liveTree = (answerText = '') => {
mockCollapsed = true;
mockLiveActionId = 'ask-1';
mockAnswerText = answerText;
return tree('live', { question: 'Which environment?' });
};
const answerBox = () => screen.getByRole('textbox', { name: 'Your answer' });
test('skips the question when nothing is entered', () => {
render(liveTree());
fireEvent.keyDown(answerBox(), { key: 'Escape' });
expect(mockSubmitAnswer).toHaveBeenCalledWith([ASK_USER_DECLINED_ANSWER]);
});
test('keeps a typed answer instead of skipping', () => {
render(liveTree('Use staging first'));
fireEvent.keyDown(answerBox(), { key: 'Escape' });
expect(mockSubmitAnswer).not.toHaveBeenCalled();
});
test('keeps checked options instead of skipping', () => {
mockCollapsed = true;
mockLiveActionId = 'ask-1';
mockChecked = [0];
render(
tree('live', {
question: 'Choose a source',
multiSelect: true,
options: [{ label: 'Public data', value: 'public' }],
}),
);
fireEvent.keyDown(answerBox(), { key: 'Escape' });
expect(mockSubmitAnswer).not.toHaveBeenCalled();
});
test('ignores Escape that cancels an IME composition or carries a modifier', () => {
render(liveTree());
fireEvent.keyDown(answerBox(), { key: 'Escape', isComposing: true });
fireEvent.keyDown(answerBox(), { key: 'Escape', shiftKey: true });
expect(mockSubmitAnswer).not.toHaveBeenCalled();
});
});
describe('arrival focus', () => {
/* jsdom has no layout, so without an observer `useArrivalFocus` arrives at once. The shared
inert observer never reports, so nothing would arrive and the negative cases would pass
without testing anything. */
const inertObserver = window.IntersectionObserver;
beforeEach(() => {
Reflect.deleteProperty(window, 'IntersectionObserver');
});
afterEach(() => {
window.IntersectionObserver = inertObserver;
document.getElementById('prompt-textarea')?.remove();
});
test('puts the user on the first option when a live question arrives', () => {
mockLiveActionId = 'arrive-option';
render(tree('arrive', withOptions, true, 'arrive-option'));
expect(screen.getByRole('button', { name: /Staging/ })).toHaveFocus();
});
test('puts the user in the answer field when the question has no options', () => {
mockLiveActionId = 'arrive-field';
render(tree('arrive', { question: 'Which environment?' }, true, 'arrive-field'));
expect(screen.getByRole('textbox', { name: 'Your answer' })).toHaveFocus();
});
test('takes focus from the empty composer that sent the turn', () => {
const composer = document.createElement('textarea');
composer.id = 'prompt-textarea';
document.body.appendChild(composer);
composer.focus();
mockLiveActionId = 'arrive-composer';
render(tree('arrive', withOptions, true, 'arrive-composer'));
expect(screen.getByRole('button', { name: /Staging/ })).toHaveFocus();
});
test('leaves focus alone while the user is drafting in the composer', () => {
const composer = document.createElement('textarea');
composer.id = 'prompt-textarea';
composer.value = 'half a thought';
document.body.appendChild(composer);
composer.focus();
mockLiveActionId = 'arrive-draft';
render(tree('arrive', withOptions, true, 'arrive-draft'));
expect(composer).toHaveFocus();
});
test('arrives once, not again when the card remounts', () => {
mockLiveActionId = 'arrive-once';
const view = render(tree('arrive', withOptions, true, 'arrive-once'));
expect(screen.getByRole('button', { name: /Staging/ })).toHaveFocus();
view.unmount();
render(tree('arrive', withOptions, true, 'arrive-once'));
expect(document.body).toHaveFocus();
});
test('does not take focus while the question is in the composer popover', () => {
mockLiveActionId = 'arrive-popover';
mockPopoverVisible = true;
render(tree('arrive', withOptions, true, 'arrive-popover'));
expect(document.body).toHaveFocus();
});
test('does not take focus for a question that is not the live pause', () => {
render(tree('arrive', withOptions, true, 'arrive-not-live'));
expect(document.body).toHaveFocus();
});
});
});

View file

@ -1,295 +0,0 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
import { fireEvent, render, screen } from '@testing-library/react';
import '~/Providers/MessagePartsHostContext';
import { FailedRevealContext } from '@librechat/chat/components';
import AskUserQuestionCall from '../AskUserQuestionCall';
import store from '~/store';
const translations: Record<string, string> = {
com_ui_asked: 'Asked',
com_ui_asking: 'Asking',
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_unanswered: 'No answer was given',
com_ui_you_answered: 'You answered:',
com_ui_asked_n_questions: 'Asked {{0}} questions',
com_ui_asking_n_questions: 'Asking {{0}} questions',
};
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string, values?: Record<string, string>) => {
const template = translations[key] ?? key;
return values == null
? template
: template.replace(/\{\{(\w+)\}\}/g, (_match, name: string) => values[name] ?? '');
},
}));
jest.mock('@librechat/chat', () => ({
...jest.requireActual('@librechat/chat'),
getSubmittedAskAnswer: () => undefined,
parseAskUserQuestionArgs: (args: string | Record<string, unknown> | undefined) => {
if (typeof args === 'string') {
return JSON.parse(args) as Record<string, unknown>;
}
return args ?? null;
},
parseAskUserQuestionsArgs: (args: string | Record<string, unknown> | undefined) => {
const parsed = typeof args === 'string' ? JSON.parse(args) : args;
return Array.isArray(parsed?.questions) ? parsed : null;
},
}));
jest.mock('../AskUserQuestionProgress', () => ({
__esModule: true,
default: () => {
const { createElement } = jest.requireActual<typeof React>('react');
return createElement('div', { 'data-testid': 'ask-progress' });
},
}));
jest.mock('@librechat/chat/components', () => ({
...jest.requireActual('@librechat/chat/components'),
Container: ({ children }: { children: React.ReactNode }) => {
const { createElement } = jest.requireActual<typeof React>('react');
return createElement('div', null, children);
},
}));
/** Settled records mount collapsed, exactly like every other tool card. */
const renderCall = (ui: React.ReactElement, autoExpand = false) =>
render(
<RecoilRoot initializeState={({ set }) => set(store.autoExpandTools, autoExpand)}>
{ui}
</RecoilRoot>,
);
describe('AskUserQuestionCall', () => {
const args = JSON.stringify({
question: 'How would you like me to get the data?',
options: [{ label: 'Use public data', value: 'public' }],
});
test('renders the progress card while the call is live and unanswered', () => {
renderCall(<AskUserQuestionCall args={args} output="" toolCallId="call_1" isSubmitting />);
expect(screen.getByTestId('ask-progress')).toBeInTheDocument();
expect(screen.queryByText('You answered:')).not.toBeInTheDocument();
});
test.each(['cancelled', 'failed'] as const)(
'does not render a terminal %s question as pending while its message streams',
(runStepStatus) => {
renderCall(
<AskUserQuestionCall
args={args}
output=""
toolCallId="call_1"
isSubmitting
runStepStatus={runStepStatus}
/>,
);
expect(screen.queryByTestId('ask-progress')).not.toBeInTheDocument();
expect(screen.getByTestId('ask-user-question-call')).toBeInTheDocument();
},
);
test('mounts collapsed and opens on click, like any other tool card', () => {
renderCall(<AskUserQuestionCall args={args} output="public" />);
const header = screen.getByRole('button');
expect(header).toHaveAttribute('aria-expanded', 'false');
/** The collapsed line still says what was asked. */
expect(header).toHaveTextContent('Asked');
expect(header).toHaveTextContent('How would you like me to get the data?');
fireEvent.click(header);
expect(header).toHaveAttribute('aria-expanded', 'true');
});
test.each([
{ failed: true, runStepStatus: 'completed' as const },
{ failed: false, runStepStatus: 'failed' as const },
])('reveals a terminal question failure from its parent fold (%p)', (failure) => {
const call = <AskUserQuestionCall args={args} output="" {...failure} />;
const tree = (tick: number) => (
<RecoilRoot>
<FailedRevealContext.Provider value={{ tick, claimFocus: () => true }}>
{call}
</FailedRevealContext.Provider>
</RecoilRoot>
);
const { rerender } = render(tree(0));
const button = screen.getByRole('button', { name: /Question wasn't shown/ });
expect(button).toHaveAttribute('aria-expanded', 'false');
rerender(tree(1));
expect(button).toHaveAttribute('aria-expanded', 'true');
expect(button).toHaveFocus();
expect(button).toHaveTextContent('failed');
});
test('opens at mount when auto-expand is on', () => {
renderCall(<AskUserQuestionCall args={args} output="public" />, true);
expect(screen.getByRole('button')).toHaveAttribute('aria-expanded', 'true');
});
test('summarizes a batch by its question count', () => {
renderCall(
<AskUserQuestionCall
args={JSON.stringify({
questions: [
{ id: 'environment', question: 'Where should this run?' },
{ id: 'window', question: 'Which window?' },
],
})}
output={JSON.stringify({ answers: { environment: 'staging', window: '7d' } })}
/>,
);
expect(screen.getByRole('button')).toHaveTextContent('Asked 2 questions');
});
test('keeps authored line breaks in a multi-paragraph answer', () => {
const answer = 'First point\n\nSecond point';
renderCall(<AskUserQuestionCall args={args} output={answer} />);
/** Identity normalizer: the default one collapses the very newlines
* this asserts are preserved. */
expect(screen.getByText(answer, { normalizer: (text) => text })).toHaveClass(
'whitespace-pre-wrap',
);
});
test('reads as settled when a run is stopped before the question is answered', () => {
renderCall(<AskUserQuestionCall args={args} output="" toolCallId="call_1" />);
const header = screen.getByRole('button');
/** The pause ended; only its panel says the answer never came, and that
* panel starts closed — a present-tense summary would strand the record
* as permanently in flight. */
expect(header).toHaveTextContent('Asked');
expect(header).not.toHaveTextContent('Asking');
expect(screen.getByText('No answer was given')).toBeInTheDocument();
});
test('announces a rejected question from outside the collapsed panel', () => {
renderCall(<AskUserQuestionCall args={args} output="Error processing tool" failed />);
const announcement = screen.getByRole('status');
expect(announcement).toHaveTextContent("Question wasn't shown");
expect(announcement).toHaveTextContent(
"The agent couldn't show this question and may retry automatically.",
);
/** `useExpandCollapse` marks the closed panel inert, so an announcement
* inside it would never reach the accessibility tree. */
expect(announcement.closest('[inert]')).toBeNull();
});
test('renders a successful tool result as the user answer', () => {
renderCall(<AskUserQuestionCall args={args} output="public" />);
expect(screen.getByText('You answered:')).toBeInTheDocument();
expect(screen.getByText('Use public data')).toBeInTheDocument();
});
test('holds the streaming cursor under the answered card while the resume is in flight', () => {
const { container } = renderCall(
<AskUserQuestionCall
args={args}
output="public"
toolCallId="call_1"
isSubmitting
showCursor
/>,
);
expect(screen.getByText('You answered:')).toBeInTheDocument();
expect(container.querySelector('.result-thinking')).not.toBeNull();
});
test('shows no cursor once the record is not the streaming tail', () => {
const settled = renderCall(<AskUserQuestionCall args={args} output="public" showCursor />);
expect(settled.container.querySelector('.result-thinking')).toBeNull();
const midStream = renderCall(
<AskUserQuestionCall args={args} output="public" toolCallId="call_1" isSubmitting />,
);
expect(midStream.container.querySelector('.result-thinking')).toBeNull();
});
test('renders schema rejection as an internal question failure, not a user answer', () => {
const output =
'Error processing tool: Received tool input did not match expected schema ' +
'✖ String must contain at most 120 character(s) → at options[0].label';
renderCall(<AskUserQuestionCall args={args} output={output} failed />);
expect(screen.getByText("Question wasn't shown")).toBeInTheDocument();
expect(
screen.getByText("The agent couldn't show this question and may retry automatically."),
).toBeInTheDocument();
expect(screen.queryByText('You answered:')).not.toBeInTheDocument();
expect(screen.queryByText(/Received tool input did not match expected schema/)).toBeNull();
});
test('preserves a user answer that contains the complete schema error text', () => {
const output =
'Error processing tool: Received tool input did not match expected schema ' +
'✖ String must contain at most 120 character(s) → at options[0].label';
renderCall(<AskUserQuestionCall args={args} output={output} />);
expect(screen.getByText('You answered:')).toBeInTheDocument();
expect(screen.getByText(output)).toBeInTheDocument();
expect(screen.queryByText("Question wasn't shown")).not.toBeInTheDocument();
});
test('renders each question and answer from one completed batch', () => {
renderCall(
<AskUserQuestionCall
args={JSON.stringify({
questions: [
{
id: 'environment',
header: 'Environment',
question: 'Where should this run?',
description: 'Choose the deployment target.',
options: [{ label: 'Staging', value: 'staging' }],
},
{ id: 'window', question: 'Which window?' },
],
})}
output={JSON.stringify({ answers: { environment: 'staging', window: '7d' } })}
/>,
);
expect(screen.getByText('Environment')).toBeInTheDocument();
expect(screen.getByText('Where should this run?')).toBeInTheDocument();
expect(screen.getByText('Choose the deployment target.')).toBeInTheDocument();
expect(screen.getByText('Staging')).toBeInTheDocument();
expect(screen.getByText('Which window?')).toBeInTheDocument();
expect(screen.getByText('7d')).toBeInTheDocument();
});
test('renders a failed batch without implying the user declined to answer', () => {
renderCall(
<AskUserQuestionCall
args={{ questions: [{ id: 'environment', question: 'Where should this run?' }] }}
output="Error processing tool"
failed
/>,
);
expect(screen.getByText("Question wasn't shown")).toBeInTheDocument();
expect(
screen.getByText("The agent couldn't show this question and may retry automatically."),
).toBeInTheDocument();
expect(screen.queryByText('No answer was given')).not.toBeInTheDocument();
});
});

View file

@ -1,149 +0,0 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import { ToolPreparation } from '@librechat/chat/components';
import AskUserQuestionProgress from '../AskUserQuestionProgress';
const translations: Record<string, string> = {
com_ui_asking: 'Asking',
com_ui_tool_name_ask_user_question: 'Question',
};
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string, values?: Record<string, string>) =>
key === 'com_ui_tool_preparing' ? `Preparing ${values?.[0]}` : (translations[key] ?? key),
}));
jest.mock('~/Providers/ChatContext', () => {
const { createContext } = jest.requireActual<typeof React>('react');
return {
ChatContext: createContext({ conversation: { conversationId: 'convo-1' } }),
};
});
let mockLivePauses: { ids: string[]; hasUnattributed: boolean } = {
ids: [],
hasUnattributed: false,
};
jest.mock('~/data-provider', () => ({
useCachedMessages: () => ({ data: mockLivePauses }),
}));
describe('AskUserQuestionProgress', () => {
beforeEach(() => {
mockLivePauses = { ids: [], hasUnattributed: false };
});
test('streams the question text from partial args', () => {
render(
<AskUserQuestionProgress
args={'{"question":"Which environment should I dep'}
toolCallId="call_1"
/>,
);
expect(screen.getByText('Asking')).toBeInTheDocument();
expect(screen.getByText('Which environment should I dep')).toBeInTheDocument();
});
test('decodes JSON escapes in the streaming question', () => {
render(
<AskUserQuestionProgress args={'{"question":"Caf\\u00e9 or \\"bar\\"'} toolCallId="call_1" />,
);
expect(screen.getByText('Café or "bar"')).toBeInTheDocument();
});
test('streams the first question from partial batched args', () => {
render(
<AskUserQuestionProgress
args={'{"questions":[{"id":"environment","question":"Which environ'}
toolCallId="call_1"
/>,
);
expect(screen.getByText('Which environ')).toBeInTheDocument();
});
test('reads the first question from settled batched args', () => {
render(
<AskUserQuestionProgress
args={{ questions: [{ id: 'environment', question: 'Which environment?' }] }}
toolCallId="call_1"
/>,
);
expect(screen.getByText('Which environment?')).toBeInTheDocument();
});
test('renders a skeleton line before any question text streams', () => {
render(<AskUserQuestionProgress args="" toolCallId="call_1" />);
expect(screen.getByText('Asking')).toBeInTheDocument();
expect(screen.getByRole('status')).toBeInTheDocument();
});
test('hides once the interactive pause for this call is live', () => {
mockLivePauses = { ids: ['call_1'], hasUnattributed: false };
const { container } = render(
<AskUserQuestionProgress args={'{"question":"Ready?"}'} toolCallId="call_1" />,
);
expect(container).toBeEmptyDOMElement();
});
test('hides for an unattributed live pause (no tool_call_id on the payload)', () => {
mockLivePauses = { ids: [], hasUnattributed: true };
const { container } = render(
<AskUserQuestionProgress args={'{"question":"Ready?"}'} toolCallId="call_1" />,
);
expect(container).toBeEmptyDOMElement();
});
test("stays visible while a DIFFERENT call's pause is interactive", () => {
mockLivePauses = { ids: ['call_1'], hasUnattributed: false };
render(
<AskUserQuestionProgress args={'{"question":"Second question?"}'} toolCallId="call_2" />,
);
expect(screen.getByText('Second question?')).toBeInTheDocument();
});
test('hides when its own pause is live alongside a newer sibling pause', () => {
mockLivePauses = { ids: ['call_1', 'call_2'], hasUnattributed: false };
const { container } = render(
<AskUserQuestionProgress args={'{"question":"First question?"}'} toolCallId="call_1" />,
);
expect(container).toBeEmptyDOMElement();
});
});
describe('question preparation transitions', () => {
test('announces preparation until measured dispatch, then asking until its interactive pause', () => {
mockLivePauses = { ids: [], hasUnattributed: false };
const frame = (args: string, toolDispatchedAt?: number) => (
<ToolPreparation
call={{ name: 'ask_user_question', args, toolPreparationStartedAt: 0, toolDispatchedAt }}
isSubmitting
>
<AskUserQuestionProgress args={args} toolCallId="call_1" />
</ToolPreparation>
);
const { rerender } = render(frame('{"question":"Which environment'));
expect(screen.getByRole('status')).toHaveTextContent('Preparing Question');
expect(screen.getByText('Which environment')).toBeInTheDocument();
rerender(frame('{"question":"Which environment?"}'));
expect(screen.getByRole('status')).toHaveTextContent('Preparing Question');
rerender(frame('{"question":"Which environment?"}', 100));
expect(screen.getByRole('status')).toHaveTextContent('Asking');
mockLivePauses = { ids: ['call_1'], hasUnattributed: false };
rerender(frame('{"question":"Which environment?"}', 100));
expect(screen.queryByRole('status')).not.toBeInTheDocument();
});
});

View file

@ -1,748 +0,0 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
import { ASK_USER_DECLINED_ANSWER } from '@librechat/chat';
import { ChatSurfaceProvider } from '@librechat/chat/react';
import { act, fireEvent, render, screen } from '@testing-library/react';
import type { Agents } from 'librechat-data-provider';
import AskUserQuestions from '../AskUserQuestions';
const mockSubmitAskAnswer = jest.fn();
let mockStatus = 'idle';
jest.mock('~/components/Chat/Messages/Content/ApprovalContext', () => ({
useAskSubmitStatus: () => ({ getAskStatus: () => mockStatus }),
useResumeSubmit: () => ({ submitAskAnswer: mockSubmitAskAnswer }),
}));
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string, values?: Record<number, number>) => {
const labels: Record<string, string> = {
com_ui_question_number: `Question ${values?.[0] ?? ''}`,
com_ui_question_step: `Question ${values?.[0] ?? ''} of ${values?.[1] ?? ''}`,
com_ui_question_step_answered: `Go to question ${values?.[0] ?? ''}, answered`,
com_ui_question_step_unanswered: `Go to question ${values?.[0] ?? ''}, not answered`,
com_ui_question_navigation: 'Question navigation',
com_ui_questions_remaining_one: `${values?.[0] ?? ''} question still needs an answer`,
com_ui_questions_remaining: `${values?.[0] ?? ''} questions still need an answer`,
com_ui_your_answer: 'Your answer',
com_ui_back: 'Back',
com_ui_next: 'Next',
com_ui_skip: 'Skip',
com_ui_submit: 'Submit',
com_ui_submitting: 'Submitting',
};
return labels[key] ?? key;
},
}));
const questions: Agents.AskUserQuestionBatchItem[] = [
{
id: 'environment',
header: 'Environment',
question: 'Where should this run?',
options: [
{ label: 'Staging', value: 'staging' },
{ label: 'Production', value: 'production' },
],
},
{ id: 'window', question: 'Which time window?' },
];
const renderBatch = (
actionId: string,
batch: Agents.AskUserQuestionBatchItem[] = questions,
focusOnArrival = true,
) =>
render(
<RecoilRoot>
<AskUserQuestions actionId={actionId} questions={batch} focusOnArrival={focusOnArrival} />
</RecoilRoot>,
);
const optionBatch: Agents.AskUserQuestionBatchItem[] = [
{ id: 'window', question: 'Which time window?' },
{
id: 'environment',
question: 'Where should this run?',
options: [
{ label: 'Staging', value: 'staging' },
{ label: 'Production', value: 'production' },
],
},
{
id: 'region',
question: 'Which region?',
options: [
{ label: 'us-east', value: 'us-east' },
{ label: 'eu-west', value: 'eu-west' },
],
},
];
/** Only the active step renders. */
const isShown = (text: string) => screen.queryByText(text) != null;
describe('AskUserQuestions', () => {
beforeEach(() => {
mockStatus = 'idle';
mockSubmitAskAnswer.mockClear();
});
test('shows one question at a time and walks the batch with Next/Back', () => {
renderBatch('ask-steps');
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(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(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/ }));
expect(isShown('Which time window?')).toBe(true);
expect(screen.getByText('Question 2 of 2')).toBeInTheDocument();
});
test('does not auto-advance a multi-select question', () => {
renderBatch('ask-multi', [
{
id: 'regions',
question: 'Which regions?',
multiSelect: true,
options: [
{ label: 'us-east', value: 'us-east' },
{ label: 'eu-west', value: 'eu-west' },
],
},
{ id: 'window', question: 'Which time window?' },
]);
fireEvent.click(screen.getByRole('checkbox', { name: /us-east/ }));
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.change(screen.getByRole('textbox', { name: /Which time window/ }), {
target: { value: 'Last seven days' },
});
const submit = screen.getByRole('button', { name: 'Submit' });
expect(submit).toBeEnabled();
fireEvent.click(submit);
expect(mockSubmitAskAnswer).toHaveBeenCalledWith(
'ask-batch',
{
environment: 'staging',
window: 'Last seven days',
},
expect.objectContaining({ onSuccess: expect.any(Function) }),
);
});
test('keeps Submit gated on the last step until every question is answered', () => {
renderBatch('ask-gated');
fireEvent.click(screen.getByRole('button', { name: 'Next' }));
expect(screen.getByRole('button', { name: 'Submit' })).toBeDisabled();
expect(
screen.getByRole('button', { name: '2 questions still need an answer' }),
).toBeInTheDocument();
fireEvent.change(screen.getByRole('textbox', { name: /Which time window/ }), {
target: { value: 'Today' },
});
expect(screen.getByRole('button', { name: 'Submit' })).toBeDisabled();
fireEvent.click(screen.getByRole('button', { name: '1 question still needs an answer' }));
expect(isShown('Where should this run?')).toBe(true);
fireEvent.click(screen.getByRole('button', { name: /Staging/ }));
expect(screen.getByRole('button', { name: 'Submit' })).toBeEnabled();
});
test('jumps to any question from the step dots and marks answered ones', () => {
renderBatch('ask-dots');
fireEvent.click(screen.getByRole('button', { name: 'Go to question 2, not answered' }));
expect(isShown('Which time window?')).toBe(true);
fireEvent.change(screen.getByRole('textbox', { name: /Which time window/ }), {
target: { value: 'Today' },
});
expect(screen.getByRole('button', { name: 'Go to question 2, answered' })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Go to question 1, not answered' }));
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 into the next question, ready to answer', () => {
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('textbox', { name: /Which time window/ })).toHaveFocus();
});
test('Ctrl/Cmd+Enter confirm like Enter; Shift+Enter never does', () => {
renderBatch('ask-modifiers');
const first = screen.getByRole('textbox', { name: /Where should this run/ });
fireEvent.change(first, { target: { value: 'Locally' } });
fireEvent.keyDown(first, { key: 'Enter', shiftKey: true });
expect(isShown('Where should this run?')).toBe(true);
fireEvent.keyDown(first, { key: 'Enter', ctrlKey: true });
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', metaKey: true });
expect(mockSubmitAskAnswer).toHaveBeenCalledTimes(1);
});
test('modified or repeated Enter in an answer field keeps the enclosing form from submitting', () => {
const onSubmit = jest.fn((event: React.FormEvent) => event.preventDefault());
render(
<RecoilRoot>
<form onSubmit={onSubmit}>
<AskUserQuestions actionId="ask-implicit-submit" questions={questions} />
</form>
</RecoilRoot>,
);
const first = screen.getByRole('textbox', { name: /Where should this run/ });
fireEvent.change(first, { target: { value: 'Locally' } });
for (const init of [{ shiftKey: true }, { altKey: true }, { repeat: true }]) {
/* fireEvent returns false when the default (implicit submit) was prevented. */
expect(fireEvent.keyDown(first, { key: 'Enter', ...init })).toBe(false);
}
expect(isShown('Where should this run?')).toBe(true);
expect(onSubmit).not.toHaveBeenCalled();
});
test('a submit shortcut rebound off Enter confirms the answer like Enter', () => {
render(
<RecoilRoot>
<ChatSurfaceProvider
value={{
enterToSend: false,
maximizeChatSpace: false,
showScrollButton: false,
composerBindings: {
shortcutsEnabled: true,
submitOverride: { meta: false, ctrl: true, alt: false, shift: false, key: 'J' },
yieldedChords: new Set(),
},
claimForeground: jest.fn(),
handOffComposerText: jest.fn(),
}}
>
<AskUserQuestions actionId="ask-rebound-submit" questions={questions} />
</ChatSurfaceProvider>
</RecoilRoot>,
);
const first = screen.getByRole('textbox', { name: /Where should this run/ });
fireEvent.change(first, { target: { value: 'Locally' } });
fireEvent.keyDown(first, { key: 'j', ctrlKey: true });
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: 'j', ctrlKey: true });
expect(mockSubmitAskAnswer).toHaveBeenCalledTimes(1);
});
describe('focus on arrival', () => {
/* jsdom has no layout, so without an observer `useArrivalFocus` arrives at once. The shared
inert observer never reports, so nothing would arrive and the negative cases would pass
without testing anything. */
const inertObserver = window.IntersectionObserver;
beforeEach(() => {
Reflect.deleteProperty(window, 'IntersectionObserver');
});
afterEach(() => {
window.IntersectionObserver = inertObserver;
document.getElementById('prompt-textarea')?.remove();
});
test('lands on the first option when the question offers choices', () => {
renderBatch('ask-focus-option');
expect(screen.getByRole('button', { name: /Staging/ })).toHaveFocus();
});
test('lands in the answer field when the question has no choices', () => {
renderBatch('ask-focus-field', [{ id: 'window', question: 'Which time window?' }]);
expect(screen.getByRole('textbox', { name: /Which time window/ })).toHaveFocus();
});
test('takes focus from the empty composer that sent the turn', () => {
const composer = document.createElement('textarea');
composer.id = 'prompt-textarea';
document.body.appendChild(composer);
composer.focus();
renderBatch('ask-focus-composer');
expect(screen.getByRole('button', { name: /Staging/ })).toHaveFocus();
});
test('stays put on a surface that is not the live pause', () => {
renderBatch('ask-focus-not-live', questions, false);
expect(document.body).toHaveFocus();
});
test('happens once per batch, not again when it moves between surfaces', () => {
const view = renderBatch('ask-focus-once');
expect(screen.getByRole('button', { name: /Staging/ })).toHaveFocus();
view.unmount();
renderBatch('ask-focus-once');
expect(document.body).toHaveFocus();
});
test('leaves focus alone while the user is drafting in the composer', () => {
const composer = document.createElement('textarea');
composer.id = 'prompt-textarea';
composer.value = 'half a thought';
document.body.appendChild(composer);
composer.focus();
renderBatch('ask-focus-draft');
expect(composer).toHaveFocus();
});
test('takes focus again when the batch is moved onto a new surface', () => {
const view = render(
<RecoilRoot>
<AskUserQuestions actionId="ask-focus-handoff" questions={questions} focusOnArrival />
</RecoilRoot>,
);
expect(screen.getByRole('button', { name: /Staging/ })).toHaveFocus();
view.unmount();
render(
<RecoilRoot>
<AskUserQuestions actionId="ask-focus-handoff" questions={questions} focusOnHandoff />
</RecoilRoot>,
);
expect(screen.getByRole('button', { name: /Staging/ })).toHaveFocus();
});
test('takes focus on a handoff even when focus stayed in the card it left', () => {
/* Safari leaves focus where it was when a button is clicked, which can be
the answer field of the now-hidden chat card. */
const leftBehind = document.createElement('input');
document.body.appendChild(leftBehind);
leftBehind.focus();
render(
<RecoilRoot>
<AskUserQuestions actionId="ask-focus-left-behind" questions={questions} focusOnHandoff />
</RecoilRoot>,
);
expect(screen.getByRole('button', { name: /Staging/ })).toHaveFocus();
leftBehind.remove();
});
describe('below a reader who has scrolled up', () => {
const originalObserver = global.IntersectionObserver;
let notify: () => void = () => undefined;
let onScreen = false;
let rectSpy: jest.SpyInstance;
beforeEach(() => {
onScreen = false;
global.IntersectionObserver = jest.fn((callback: IntersectionObserverCallback) => {
notify = () => callback([], {} as IntersectionObserver);
return { observe: jest.fn(), disconnect: jest.fn() };
}) as unknown as typeof IntersectionObserver;
rectSpy = jest
.spyOn(HTMLElement.prototype, 'getBoundingClientRect')
.mockImplementation(() =>
onScreen
? ({ top: 100, bottom: 300 } as DOMRect)
: ({ top: window.innerHeight + 200, bottom: window.innerHeight + 400 } as DOMRect),
);
});
afterEach(() => {
global.IntersectionObserver = originalObserver;
rectSpy.mockRestore();
});
test('waits until the card is on screen before taking focus', () => {
renderBatch('ask-focus-offscreen');
act(() => notify());
expect(document.body).toHaveFocus();
onScreen = true;
act(() => notify());
expect(screen.getByRole('button', { name: /Staging/ })).toHaveFocus();
});
test('does not take focus once the reader has started typing elsewhere', () => {
renderBatch('ask-focus-offscreen-busy');
const composer = document.createElement('textarea');
composer.id = 'prompt-textarea';
composer.value = 'typing while it arrived';
document.body.appendChild(composer);
composer.focus();
onScreen = true;
act(() => notify());
expect(composer).toHaveFocus();
});
});
});
describe('option keyboard', () => {
/** A keyboard Enter on a button is its click; jsdom does not synthesize
* that, so the click fires only when the handler leaves Enter alone. */
const pressEnter = (option: HTMLElement) => {
if (fireEvent.keyDown(option, { key: 'Enter' })) {
fireEvent.click(option);
}
};
test('Enter on an option mid-batch picks it and moves to the next question', () => {
renderBatch('ask-option-enter');
pressEnter(screen.getByRole('button', { name: /Production/ }));
expect(isShown('Which time window?')).toBe(true);
expect(screen.getByRole('textbox', { name: /Which time window/ })).toHaveFocus();
});
test('on the last question, Enter picks an option and a second Enter submits', () => {
renderBatch('ask-option-submit', [
{ id: 'window', question: 'Which time window?' },
{
id: 'environment',
question: 'Where should this run?',
options: [
{ label: 'Staging', value: 'staging' },
{ label: 'Production', value: 'production' },
],
},
]);
fireEvent.change(screen.getByRole('textbox', { name: /Which time window/ }), {
target: { value: 'Today' },
});
fireEvent.click(screen.getByRole('button', { name: 'Next' }));
const staging = screen.getByRole('button', { name: /Staging/ });
pressEnter(staging);
expect(staging).toHaveAttribute('aria-pressed', 'true');
expect(mockSubmitAskAnswer).not.toHaveBeenCalled();
pressEnter(staging);
expect(mockSubmitAskAnswer).toHaveBeenCalledWith(
'ask-option-submit',
{ window: 'Today', environment: 'staging' },
expect.objectContaining({ onSuccess: expect.any(Function) }),
);
});
test('a held Enter that picks an option on the last question does not also submit', () => {
renderBatch('ask-option-held-last', [
{
id: 'environment',
question: 'Where should this run?',
options: [
{ label: 'Staging', value: 'staging' },
{ label: 'Production', value: 'production' },
],
},
]);
const staging = screen.getByRole('button', { name: /Staging/ });
pressEnter(staging);
expect(staging).toHaveAttribute('aria-pressed', 'true');
fireEvent.keyDown(staging, { key: 'Enter', repeat: true });
fireEvent.keyDown(staging, { key: 'Enter', repeat: true });
expect(mockSubmitAskAnswer).not.toHaveBeenCalled();
pressEnter(staging);
expect(mockSubmitAskAnswer).toHaveBeenCalledTimes(1);
});
test('a held or double-tapped Enter from the answer field never picks the next options', () => {
renderBatch('ask-option-held', optionBatch);
const first = screen.getByRole('textbox', { name: /Which time window/ });
fireEvent.change(first, { target: { value: 'Today' } });
fireEvent.keyDown(first, { key: 'Enter' });
expect(isShown('Where should this run?')).toBe(true);
/* Focus waits in the answer field, not on an option, so the repeats
reach a field: they can page on, but never pick an option for the user. */
expect(screen.getByRole('textbox', { name: /Where should this run/ })).toHaveFocus();
for (let i = 0; i < 3; i++) {
pressEnter(document.activeElement as HTMLElement);
}
expect(screen.queryByRole('button', { pressed: true })).not.toBeInTheDocument();
expect(mockSubmitAskAnswer).not.toHaveBeenCalled();
});
test('Enter on a multi-select option toggles it and never submits', () => {
renderBatch('ask-option-multi', [
{
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);
pressEnter(usEast);
pressEnter(screen.getByRole('checkbox', { name: /eu-west/ }));
expect(usEast).toHaveAttribute('aria-checked', 'false');
expect(screen.getByRole('checkbox', { name: /eu-west/ })).toHaveAttribute(
'aria-checked',
'true',
);
expect(mockSubmitAskAnswer).not.toHaveBeenCalled();
});
});
test('retains partial answers and the current step across surface remounts', () => {
const view = renderBatch('ask-remount');
fireEvent.click(screen.getByRole('button', { name: 'Next' }));
fireEvent.change(screen.getByRole('textbox', { name: /Which time window/ }), {
target: { value: 'Today' },
});
view.rerender(
<RecoilRoot>
<AskUserQuestions actionId="ask-remount" questions={questions} />
</RecoilRoot>,
);
expect(screen.getByText('Question 2 of 2')).toBeInTheDocument();
expect(screen.getByRole('textbox', { name: /Which time window/ })).toHaveValue('Today');
});
test('leaves a single-question batch free of stepper chrome', () => {
renderBatch('ask-single', [
{ id: 'confirmation', question: 'Continue?', options: [{ label: 'Yes', value: 'yes' }] },
]);
expect(screen.queryByRole('button', { name: 'Next' })).not.toBeInTheDocument();
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: 'Submit' }));
expect(mockSubmitAskAnswer).toHaveBeenCalledWith(
'ask-single',
{ confirmation: 'yes' },
expect.objectContaining({ onSuccess: expect.any(Function) }),
);
});
test('supports question ids inherited by ordinary objects', () => {
renderBatch('ask-prototype-id', [
{
id: 'constructor',
question: 'Continue?',
options: [{ label: 'Yes', value: 'yes' }],
},
]);
fireEvent.click(screen.getByRole('button', { name: /Yes/ }));
fireEvent.click(screen.getByRole('button', { name: 'Submit' }));
expect(mockSubmitAskAnswer).toHaveBeenCalledWith(
'ask-prototype-id',
{ constructor: 'yes' },
expect.objectContaining({ onSuccess: expect.any(Function) }),
);
});
test('keeps an expired batch readable but freezes steps mid-submit', () => {
mockStatus = 'expired';
const view = renderBatch('ask-expired');
fireEvent.click(screen.getByRole('button', { name: 'Next' }));
expect(isShown('Which time window?')).toBe(true);
mockStatus = 'submitting';
view.rerender(
<RecoilRoot>
<AskUserQuestions actionId="ask-expired" questions={questions} />
</RecoilRoot>,
);
expect(screen.getByRole('button', { name: 'Back' })).toBeDisabled();
});
test('skips the whole batch from any step', () => {
renderBatch('ask-skip');
fireEvent.click(screen.getByRole('button', { name: 'Next' }));
fireEvent.click(screen.getByRole('button', { name: 'Skip' }));
expect(mockSubmitAskAnswer).toHaveBeenCalledWith(
'ask-skip',
{ environment: ASK_USER_DECLINED_ANSWER, window: ASK_USER_DECLINED_ANSWER },
expect.objectContaining({ onSuccess: expect.any(Function) }),
);
});
describe('Escape', () => {
test('skips the batch when nothing is answered yet', () => {
renderBatch('ask-escape-skip');
fireEvent.keyDown(screen.getByRole('button', { name: /Staging/ }), { key: 'Escape' });
expect(mockSubmitAskAnswer).toHaveBeenCalledWith(
'ask-escape-skip',
{ environment: ASK_USER_DECLINED_ANSWER, window: ASK_USER_DECLINED_ANSWER },
expect.objectContaining({ onSuccess: expect.any(Function) }),
);
});
test('keeps partial answers instead of skipping', () => {
renderBatch('ask-escape-partial');
fireEvent.click(screen.getByRole('button', { name: /Staging/ }));
fireEvent.keyDown(screen.getByRole('textbox', { name: /Your answer/ }), { key: 'Escape' });
expect(mockSubmitAskAnswer).not.toHaveBeenCalled();
});
test('ignores Escape that cancels an IME composition or carries a modifier', () => {
renderBatch('ask-escape-ime', [{ id: 'window', question: 'Which time window?' }]);
const field = screen.getByRole('textbox', { name: /Your answer/ });
fireEvent.keyDown(field, { key: 'Escape', isComposing: true });
fireEvent.keyDown(field, { key: 'Escape', shiftKey: true });
expect(mockSubmitAskAnswer).not.toHaveBeenCalled();
});
test('hands Escape to the surface instead of skipping when it supplies one', () => {
const onEscape = jest.fn();
render(
<RecoilRoot>
<AskUserQuestions
actionId="ask-escape-surface"
questions={questions}
onEscape={onEscape}
/>
</RecoilRoot>,
);
fireEvent.keyDown(screen.getByRole('button', { name: /Staging/ }), { key: 'Escape' });
expect(onEscape).toHaveBeenCalledTimes(1);
expect(mockSubmitAskAnswer).not.toHaveBeenCalled();
});
});
});

View file

@ -36,10 +36,6 @@ jest.mock('../Parts/BackgroundTaskCall', () => ({
default: mockStub('background-task-call'),
}));
jest.mock('../MessageContent', () => ({ ErrorMessage: mockStub('error-message') }));
jest.mock('../AskUserQuestionCall', () => ({
__esModule: true,
default: mockStub('ask-user-question-call'),
}));
jest.mock('../AskUserQuestion', () => ({
__esModule: true,
default: mockStub('ask-user-question'),
@ -55,6 +51,7 @@ jest.mock('@librechat/chat/components', () => ({
Container: mockPassthrough,
ToolPreparation: mockPassthrough,
ToolCall: mockStub('tool-call'),
AskUserQuestionCall: mockStub('ask-user-question-call'),
}));
/** What `Part` drew: the stubbed component's test id, or the text of an inline element. */
const drawn = (part: TMessageContentParts): string | null => {

View file

@ -0,0 +1,54 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import { AskUserQuestionProgress } from '@librechat/chat/components';
import { ChatContext } from '~/Providers/ChatContext';
import AskHost from '../AskHost';
let mockPauses = { ids: [] as string[], hasUnattributed: false };
jest.mock('~/data-provider', () => ({
useCachedMessages: () => ({ data: mockPauses }),
}));
function renderProgress(toolCallId: string) {
return render(
<ChatContext.Provider value={{ conversation: { conversationId: 'conversation-1' } } as never}>
<AskHost saveDrafts={false}>
<AskUserQuestionProgress args='{"question":"Which environment?"}' toolCallId={toolCallId} />
</AskHost>
</ChatContext.Provider>,
);
}
describe('AskHost live pauses', () => {
beforeEach(() => {
mockPauses = { ids: [], hasUnattributed: false };
});
test('updates mounted progress cards when the conversation pause changes', () => {
const view = () => (
<AskHost saveDrafts={false}>
<AskUserQuestionProgress args='{"question":"Ready?"}' toolCallId="call-1" />
</AskHost>
);
const { rerender } = render(view());
expect(screen.getByText('Ready?')).toBeInTheDocument();
mockPauses = { ids: ['call-1'], hasUnattributed: false };
rerender(view());
expect(screen.queryByText('Ready?')).not.toBeInTheDocument();
mockPauses = { ids: [], hasUnattributed: false };
rerender(view());
expect(screen.getByText('Ready?')).toBeInTheDocument();
});
test('shows the in-progress question the conversation has not opened yet', () => {
renderProgress('call-1');
expect(screen.getByText('Which environment?')).toBeInTheDocument();
});
test('hides the card once this call is the live pause', () => {
mockPauses = { ids: ['call-1'], hasUnattributed: false };
const { container } = renderProgress('call-1');
expect(container).toBeEmptyDOMElement();
});
});

View file

@ -23,6 +23,7 @@ jest.mock('~/hooks/Chat/target', () => ({
}));
jest.mock('~/data-provider', () => ({
useCachedMessages: () => ({ data: null }),
useProjectQuery: () => ({ data: undefined }),
}));

View file

@ -26,6 +26,7 @@ jest.mock('~/hooks/Chat/target', () => ({
}));
jest.mock('~/data-provider', () => ({
useCachedMessages: () => ({ data: null }),
useProjectQuery: () => ({ data: undefined }),
}));

View file

@ -78,6 +78,7 @@ jest.mock('~/hooks/Chat/target', () => ({
}));
jest.mock('~/data-provider', () => ({
useCachedMessages: () => ({ data: null }),
useProjectQuery: () => ({ data: undefined }),
}));

View file

@ -1,55 +1,6 @@
import { useLayoutEffect, useRef, useState } from 'react';
import type { ReactNode } from 'react';
import { cn } from '~/utils';
import { AutoHeight as ChatAutoHeight } from '@librechat/chat/components';
import type { ComponentProps } from 'react';
/**
* 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>
);
export default function AutoHeight(props: ComponentProps<typeof ChatAutoHeight>) {
return <ChatAutoHeight {...props} />;
}

View file

@ -7,6 +7,17 @@ describe('AutoHeight', () => {
jest.restoreAllMocks();
});
it('keeps caller class overrides when the shared component merges classes', () => {
render(
<AutoHeight className="overflow-visible duration-150">
<p>{'Override layout'}</p>
</AutoHeight>,
);
const clip = screen.getByText('Override layout').parentElement?.parentElement;
expect(clip).toHaveClass('overflow-visible', 'duration-150');
expect(clip).not.toHaveClass('overflow-hidden', 'duration-300');
});
it('sizes the clip box to the measured content, fractions included', () => {
jest
.spyOn(HTMLElement.prototype, 'getBoundingClientRect')

View file

@ -1,54 +0,0 @@
import { useEffect, useRef } from 'react';
import type { RefObject } from 'react';
import { mainTextareaId } from '~/common';
import { isRectVisible } from '~/utils';
/** Focus is nowhere, or in the empty composer that just sent the turn. */
export function isFocusIdle(): boolean {
const active = document.activeElement;
return (
active == null ||
active === document.body ||
(active instanceof HTMLTextAreaElement &&
active.id === mainTextareaId &&
active.value.trim().length === 0)
);
}
/**
* Runs `arrive` once, the first moment `targetRef` is on screen after `enabled`
* turns on. A question card can arrive below a reader who has scrolled up, where
* focus would land on a control they cannot see: the thread following its tail
* brings the card on screen at once, a reader scrolled away brings it there by
* scrolling back. `arrive` decides whether focus is still idle by then.
*
* Observer entries can be stale while the thread is still settling, so each one
* re-measures the target against the viewport and its scroll containers.
*/
export default function useArrivalFocus(
enabled: boolean,
targetRef: RefObject<HTMLElement>,
arrive: () => void,
): void {
const arriveRef = useRef(arrive);
arriveRef.current = arrive;
useEffect(() => {
if (!enabled) {
return;
}
const target = targetRef.current;
if (target == null || typeof IntersectionObserver === 'undefined') {
arriveRef.current();
return;
}
const observer = new IntersectionObserver(() => {
if (!isRectVisible(target)) {
return;
}
observer.disconnect();
arriveRef.current();
});
observer.observe(target);
return () => observer.disconnect();
}, [enabled, targetRef]);
}

View file

@ -1,160 +0,0 @@
import { useCallback, useMemo } from 'react';
import { atom, useAtom } from 'jotai';
import { atomFamily } from 'jotai/utils';
import { ASK_USER_DECLINED_ANSWER } from '@librechat/chat';
import type { Agents } from 'librechat-data-provider';
import {
useAskSubmitStatus,
useResumeSubmit,
} from '~/components/Chat/Messages/Content/ApprovalContext';
interface AskQuestionsFormState {
/** Index of the question currently on screen. Lives beside the answers so the
* composer popover and the chat card resume on the same step when one
* surface hands over to the other. */
step: number;
text: Record<string, string>;
selected: Record<string, string[]>;
/** The batch's arrival already placed focus. Moving it between the composer
* popover and the chat card remounts it, and that is not a new arrival. */
arrivalFocused: boolean;
}
const EMPTY_FORM: AskQuestionsFormState = {
step: 0,
text: {},
selected: {},
arrivalFocused: false,
};
/** 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;
}
export default function useAskQuestionsForm(
actionId: string,
questions: Agents.AskUserQuestionBatchItem[],
) {
const [state, setState] = useAtom(askQuestionsFormFamily(actionId));
const resetState = useCallback(() => setState(EMPTY_FORM), [setState]);
const { submitAskAnswer } = useResumeSubmit();
const { getAskStatus } = useAskSubmitStatus();
const status = getAskStatus(actionId);
const locked = status === 'submitting' || status === 'submitted' || status === 'expired';
const setText = useCallback(
(question: Agents.AskUserQuestionBatchItem, value: string) => {
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:
value.trim().length === 0
? previous.selected
: { ...previous.selected, [question.id]: [] },
}));
},
[setState],
);
const selectOption = useCallback(
(question: Agents.AskUserQuestionBatchItem, value: string) => {
setState((previous) => {
const current = ownValue(previous.selected, question.id) ?? [];
let selected = [value];
if (question.multiSelect === true) {
selected = current.includes(value)
? current.filter((item) => item !== value)
: [...current, value];
}
return {
...previous,
text:
question.multiSelect === true ? previous.text : { ...previous.text, [question.id]: '' },
selected: { ...previous.selected, [question.id]: selected },
};
});
},
[setState],
);
const goToStep = useCallback(
(index: number) => {
const bounded = Math.min(Math.max(index, 0), Math.max(questions.length - 1, 0));
setState((previous) =>
previous.step === bounded ? previous : { ...previous, step: bounded },
);
},
[questions.length, setState],
);
const markArrivalFocused = useCallback(
() =>
setState((previous) =>
previous.arrivalFocused ? previous : { ...previous, arrivalFocused: true },
),
[setState],
);
const answers = useMemo(() => {
const resolved = Object.create(null) as Record<string, string>;
for (const question of questions) {
const text = ownValue(state.text, question.id)?.trim() ?? '';
const selected = ownValue(state.selected, question.id) ?? [];
const values = question.multiSelect === true ? [...selected] : [];
if (text.length > 0) {
values.push(text);
} else if (question.multiSelect !== true && selected[0] != null) {
values.push(selected[0]);
}
if (values.length > 0) {
resolved[question.id] = values.join(', ');
}
}
return resolved;
}, [questions, state.text, state.selected]);
const canSubmit =
!locked && questions.every((question) => (ownValue(answers, question.id)?.length ?? 0) > 0);
const submit = useCallback(() => {
if (!canSubmit) {
return false;
}
submitAskAnswer(actionId, answers, { onSuccess: resetState });
return true;
}, [actionId, answers, canSubmit, resetState, submitAskAnswer]);
const skip = useCallback(() => {
if (locked) {
return false;
}
const declined = Object.fromEntries(
questions.map((question) => [question.id, ASK_USER_DECLINED_ANSWER]),
);
submitAskAnswer(actionId, declined, { onSuccess: resetState });
return true;
}, [actionId, locked, questions, resetState, submitAskAnswer]);
return {
state,
step: Math.min(state.step, Math.max(questions.length - 1, 0)),
status,
locked,
answers,
canSubmit,
setText,
selectOption,
goToStep,
submit,
skip,
arrivalFocused: state.arrivalFocused,
markArrivalFocused,
};
}

View file

@ -1,50 +1,7 @@
/**
* Insert text at the cursor position in a textarea.
*/
export function insertTextAtCursor(element: HTMLTextAreaElement, textToInsert: string) {
element.focus();
export { insertTextAtCursor, forceResize } from '@librechat/chat';
// Use the browser's built-in undoable actions if possible
if (window.getSelection() && document.queryCommandSupported('insertText')) {
document.execCommand('insertText', false, textToInsert);
} else {
console.warn('insertTextAtCursor: document.execCommand is not supported');
const startPos = element.selectionStart;
const endPos = element.selectionEnd;
const beforeText = element.value.substring(0, startPos);
const afterText = element.value.substring(endPos);
element.value = beforeText + textToInsert + afterText;
element.selectionStart = element.selectionEnd = startPos + textToInsert.length;
const event = new Event('input', { bubbles: true });
element.dispatchEvent(event);
}
}
/**
* Necessary resize helper for edge cases where paste doesn't update the container height.
*
1) Resetting the height to 'auto' forces the component to recalculate height based on its current content
2) Forcing a reflow. Accessing offsetHeight will cause a reflow of the page,
ensuring that the reset height takes effect before resetting back to the scrollHeight.
This step is necessary because changes to the DOM do not instantly cause reflows.
3) Reseting back to scrollHeight reads and applies the ideal height for the current content dynamically
*/
export const forceResize = (element: HTMLTextAreaElement | null) => {
if (!element) {
return;
}
element.style.height = 'auto';
element.style.height = `${element.scrollHeight}px`;
};
/**
* Check if the textarea is scrollable.
* @param element
* @returns
*/
export const checkIfScrollable = (element: HTMLTextAreaElement | null) => {
/** Whether the textarea can scroll its content. */
export const checkIfScrollable = (element: HTMLTextAreaElement | null): boolean => {
if (!element) {
return false;
}

View file

@ -1,16 +1 @@
/** Whether any part of `el` is inside the viewport and every clipping ancestor. */
export function isRectVisible(el: HTMLElement): boolean {
const rect = el.getBoundingClientRect();
let top = Math.max(rect.top, 0);
let bottom = Math.min(rect.bottom, window.innerHeight);
for (let node = el.parentElement; node != null && top < bottom; node = node.parentElement) {
const { overflowY } = getComputedStyle(node);
if (overflowY === 'visible') {
continue;
}
const clip = node.getBoundingClientRect();
top = Math.max(top, clip.top);
bottom = Math.min(bottom, clip.bottom);
}
return top < bottom;
}
export { isRectVisible } from '@librechat/chat';