❓ 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

@ -83,6 +83,11 @@
"package-lock.json"
],
"packages/client/src/components/__tests__/radixLayers.spec.ts": ["package-lock.json"],
"packages/client/src/theme/askParts.spec.ts": [
"packages/client/src/theme/parts.css",
"client/src/style.css",
"client/src/main.jsx"
],
"packages/client/src/theme/defaults.spec.ts": ["packages/client/src/theme/defaults.css"],
"packages/client/src/theme/parts.spec.ts": [
"client/src/style.css",

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,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

@ -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,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';

View file

@ -10,6 +10,7 @@ import {
messagesView,
requestJson,
sendMessage,
mockReply,
} from '../helpers';
/**
@ -237,4 +238,57 @@ test.describe('ask question keyboard control', () => {
await cleanupAgent(page, agentId);
}
});
test('a settled batch is one record line whose answers open on demand @scenario:ask-settled-record-opens-on-demand', async ({
page,
}) => {
test.setTimeout(120000);
const label = uniqueLabel();
let agentId: string | undefined;
try {
const agent = await createAgent(page);
agentId = agent.id;
const chat = await openBatch(page, agent, label);
const field = answerField(chat, questionsFor(label).environment);
await expect(field).toBeVisible();
await Promise.all([page.waitForRequest(isResumeRequest), field.press('Escape')]);
/* The resumed turn regroups the message's parts as it streams, so a click before it ends
can land on a card that is then replaced. Open the record once the turn is over. */
await expect(mockReply(page)).toBeVisible({ timeout: 30000 });
await expect(page.getByTestId('stop-generation-button')).toBeHidden({ timeout: 30000 });
const record = chat.getByTestId('ask-user-question-call');
const toggle = record.getByRole('button');
await expect(toggle).toBeVisible();
/* The collapse rule lives in the shared stylesheet, which the app's own sheet follows in
the bundle. Read what the cascade resolved rather than which rule was authored. */
const panel = chat.locator('.disclosure-collapse');
const resolved = () =>
panel.evaluate((node) => {
const style = getComputedStyle(node);
return { display: style.display, opacity: style.opacity, rows: style.gridTemplateRows };
});
await expect(toggle).toHaveAttribute('aria-expanded', 'false');
await expect.poll(resolved).toEqual({ display: 'grid', opacity: '0', rows: '0px' });
await toggle.click();
await expect(toggle).toHaveAttribute('aria-expanded', 'true');
await expect
.poll(async () => {
const { display, opacity, rows } = await resolved();
return { display, opacity, open: rows !== '0px' && rows !== 'none' };
})
.toEqual({ display: 'grid', opacity: '1', open: true });
await toggle.click();
await expect(toggle).toHaveAttribute('aria-expanded', 'false');
await expect.poll(resolved).toEqual({ display: 'grid', opacity: '0', rows: '0px' });
} finally {
await cleanupAgent(page, agentId);
}
});
});

View file

@ -142,16 +142,6 @@
"count": 1
}
},
"client/src/components/Chat/Messages/Content/AskUserQuestion.tsx": {
"shadcn/no-restyle": {
"count": 11
}
},
"client/src/components/Chat/Messages/Content/AskUserQuestionCall.tsx": {
"shadcn/no-inline-styles": {
"count": 1
}
},
"client/src/components/Chat/Messages/Content/EditContentParts.tsx": {
"design/disabled-recipe": {
"count": 1

View file

@ -137,12 +137,20 @@ export {
TOOL_ROW_CLASSES,
FOLD_RAIL_CLASSES,
FOLD_GLYPH_SELECTOR,
PROGRESS_TEXT_CONTENT,
PROGRESS_TEXT_WRAPPER,
ARTIFACT_ROW_NAV_SPACING,
} from './components/parts/rows';
export { default as AskOptions } from './components/parts/AskOptions';
export { default as AskPopover } from './components/composer/ask/Popover';
export type { LiveAsk, AskAnswerView, AskPopoverProps } from './components/composer/ask/Popover';
export type { AskOption } from './components/parts/AskOptions';
export { default as AutoHeight } from './components/parts/AutoHeight';
export { default as AskUserQuestion } from './components/parts/ask/Question';
export { default as AskUserQuestions } from './components/parts/ask/Questions';
export { default as AskUserQuestionCall } from './components/parts/ask/Call';
export { default as AskUserQuestionProgress } from './components/parts/ask/Progress';
export type { AskCardMode } from './components/parts/ask/Question';
export { default as SkillPills } from './components/parts/SkillPills';
export type { SkillPillsSource } from './components/parts/SkillPills';
export { default as MessageQuotes } from './components/parts/MessageQuotes';

View file

@ -0,0 +1,55 @@
import { useLayoutEffect, useRef, useState } from 'react';
import { cn } from '@librechat/client';
import type { ReactNode } 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 collapses 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;
}): ReactNode {
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>
);
}

View file

@ -1,6 +1,11 @@
import { ScrollText } from 'lucide-react';
import { cn, Shimmer, useLocalize } from '@librechat/client';
import { ROW_GLYPH_SLOT, TOOL_ROW_CLASSES } from './rows';
import {
PROGRESS_TEXT_CONTENT,
PROGRESS_TEXT_WRAPPER,
ROW_GLYPH_SLOT,
TOOL_ROW_CLASSES,
} from './rows';
/**
* Minimal variant of `SkillCall` used for the interim window between
@ -34,8 +39,8 @@ export default function PendingSkillCall({
return (
<div className={TOOL_ROW_CLASSES}>
<div className="progress-text-wrapper text-text-secondary relative -mt-[0.046875rem] h-5 w-full leading-5">
<div className="progress-text-content absolute top-0 right-0 left-0 max-w-full overflow-visible whitespace-nowrap">
<div className={PROGRESS_TEXT_WRAPPER}>
<div className={PROGRESS_TEXT_CONTENT}>
<div className="inline-flex w-full items-center gap-2">
{/** The real `SkillCall` replaces this row in place once the skill
* finalizes; sharing its glyph slot keeps that swap still. */}

View file

@ -1,31 +1,35 @@
import { useCallback } from 'react';
import { MessageCircleQuestion, TriangleAlert } from 'lucide-react';
import { toolPanelSpacingClassName, useToolExpansion } from '@librechat/chat/react';
import { useCallback, useRef } from 'react';
import { ChevronDown, MessageCircleQuestion, TriangleAlert } from 'lucide-react';
import { cn, Button, disclosureChevronVariants, useLocalize } from '@librechat/client';
import type { Agents, PartMetadata } from 'librechat-data-provider';
import type { CSSProperties, ReactNode } from 'react';
import {
EmptyText,
DISCLOSURE_COLLAPSE,
PROGRESS_TEXT_CONTENT,
PROGRESS_TEXT_WRAPPER,
ROW_GLYPH_SLOT,
TOOL_ROW_CLASSES,
Container,
useExpandCollapse,
} from '@librechat/chat/components';
} from '../rows';
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';
} from '../../../core/parts/questions';
import { toolPanelSpacingClassName, useToolExpansion } from '../../../react/parts/disclosure';
import useExpandCollapse from '../useExpandCollapse';
import AskUserQuestionProgress from './Progress';
import { useFailedReveal } from '../reveal';
import EmptyText from '../../EmptyText';
import Container from '../Container';
/**
* Static rendering of a COMPLETED (or abandoned) `ask_user_question` tool call —
* 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
* 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
@ -49,7 +53,7 @@ export default function AskUserQuestionCall({
failed?: boolean;
showCursor?: boolean;
onExpand?: () => void;
}) {
}): ReactNode {
const localize = useLocalize();
const [expanded, setExpanded] = useToolExpansion(true);
const { style: expandStyle, ref: expandRef } = useExpandCollapse(expanded);
@ -66,7 +70,7 @@ export default function AskUserQuestionCall({
/**
* 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
* 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) ?? '');
@ -92,7 +96,7 @@ export default function AskUserQuestionCall({
/**
* While the turn is live and unanswered, the INTERACTIVE card (rendered from
* the pendingAction's synthetic part) owns the question UI — rendering the
* 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
@ -107,7 +111,7 @@ export default function AskUserQuestionCall({
/**
* 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
* arrive. Hold the streaming cursor under the settled card so the turn
* never looks stalled between the answer and the resumed text.
*/
const resumingCursor =
@ -120,7 +124,7 @@ export default function AskUserQuestionCall({
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
* 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
@ -142,35 +146,33 @@ export default function AskUserQuestionCall({
return (
<>
<div className={TOOL_ROW_CLASSES} data-testid="ask-user-question-call">
<ProgressText
phase={terminalFailure ? 'failed' : 'completed'}
onClick={toggleExpanded}
inProgressText={statusLabel}
finishedText={statusLabel}
<AskCallHeader
failed={terminalFailure}
expanded={expanded}
label={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}
onClick={toggleExpanded}
/>
</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
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={DISCLOSURE_COLLAPSE}
style={
{
'--expand-rows': String(expandStyle.gridTemplateRows),
'--expand-opacity': String(expandStyle.opacity),
'--expand-transition': String(expandStyle.transition),
} as CSSProperties
}
>
<div className="overflow-hidden" ref={expandRef}>
<div
className={cn(
@ -221,8 +223,103 @@ export default function AskUserQuestionCall({
}
/**
* 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`
* The settled row. Same disclosure, failure reveal, and line as the other tool
* cards: a failed call opens and takes focus when a parent fold asks.
*/
function AskCallHeader({
failed,
expanded,
label,
subtitle,
onClick,
}: {
failed: boolean;
expanded: boolean;
label: string;
subtitle?: string;
onClick: () => void;
}) {
const localize = useLocalize();
const rootRef = useRef<HTMLDivElement>(null);
const revealFailure = useCallback(
(claimFocus: () => boolean) => {
if (!expanded) {
onClick();
}
if (!claimFocus()) {
return;
}
const button = rootRef.current?.querySelector('button');
if (button == null) {
return;
}
if (typeof button.scrollIntoView === 'function') {
button.scrollIntoView({ block: 'nearest' });
}
button.focus({ preventScroll: true });
},
[expanded, onClick],
);
useFailedReveal(failed, revealFailure);
return (
<div className={PROGRESS_TEXT_WRAPPER} ref={rootRef}>
<div className={PROGRESS_TEXT_CONTENT}>
<Button
type="button"
variant="disclosure"
className="group/disclosure"
onClick={onClick}
aria-expanded={expanded}
>
<span className={ROW_GLYPH_SLOT} aria-hidden="true">
{failed ? (
<TriangleAlert className="text-text-warning size-4 shrink-0" aria-hidden="true" />
) : (
<MessageCircleQuestion
className="text-text-secondary size-4 shrink-0"
aria-hidden="true"
/>
)}
</span>
<span className="flex min-w-0 items-center gap-2">
<span
className={cn(
'max-w-full min-w-0 truncate font-medium',
subtitle != null && 'shrink-0',
)}
>
{label}
</span>
{subtitle != null && (
<span className="text-text-secondary min-w-0 shrink truncate font-normal">
{subtitle}
</span>
)}
</span>
{failed && (
<span className="text-status-error shrink-0 font-normal">
{'· '}
{localize('com_ui_tool_failed')}
</span>
)}
<span className="ms-auto flex shrink-0 items-center gap-2">
<ChevronDown
className={cn(
disclosureChevronVariants({ expanded }),
'size-4 shrink-0 translate-y-[0.0625rem]',
)}
aria-hidden="true"
/>
</span>
</Button>
</div>
</div>
);
}
/**
* 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.
@ -276,7 +373,7 @@ function QuestionBody({
/**
* Prefer the picked option's label over its wire value when they differ.
* Multi-select answers are option values joined by ", " — map the segments
* 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

View file

@ -1,15 +1,9 @@
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';
import { Shimmer, useLocalize } from '@librechat/client';
import type { ReactNode } from 'react';
import { parseJsonField, parseJsonFieldOccurrences } from '../../../core/parts/parseJsonField';
import { useLiveAskPauses } from '../../../react/parts/ask';
import { useToolPreparation } from '../preparation';
/**
* Interim card for an `ask_user_question` call whose pause hasn't gone
@ -21,9 +15,8 @@ import { useLocalize } from '~/hooks';
* 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.
* Mounted only for a live, unanswered call (the settled record gates on
* `isSubmitting`). The host supplies the conversation's live pauses.
*/
export default function AskUserQuestionProgress({
args,
@ -31,15 +24,10 @@ export default function AskUserQuestionProgress({
}: {
args: string | Record<string, unknown> | undefined;
toolCallId?: string;
}) {
}): ReactNode {
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 livePauses = useLiveAskPauses();
const legacyQuestion = parseJsonField(args, 'question');
const batchQuestion = (() => {
if (typeof args === 'string') {

View file

@ -0,0 +1,514 @@
import { useMemo, useRef, useState } from 'react';
import { useAtomValue } from 'jotai';
import { ChevronDown, MessageCircleQuestion, TriangleAlert } from 'lucide-react';
import {
cn,
Button,
Shimmer,
TextareaAutosize,
TooltipAnchor,
useLocalize,
} from '@librechat/client';
import type { Agents } from 'librechat-data-provider';
import type { KeyboardEvent, ReactNode } from 'react';
import type { AskAnswerSubmit } from '../../../react/parts/ask';
import {
isCancelKey,
isReboundSubmitChord,
resolveComposerKeyDown,
splitOtherOption,
ASK_USER_DECLINED_ANSWER,
} from '../../../core';
import useArrivalFocus, { isFocusIdle } from '../../../react/parts/arrival';
import { useOptionalChatSurface } from '../../../react/subagents/surface';
import { forceResize, insertTextAtCursor } from '../../../core/textarea';
import { askSubmitStatusAtom } from '../../../react/parts/ask';
import { NO_HOST_BINDINGS } from '../../../core/shortcuts';
import AskUserQuestions from './Questions';
import AskOptions from '../AskOptions';
/**
* 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>();
/** What the live pause shares with the composer. Omitted outside a live chat. */
export type AskCardMode = {
popoverVisible: boolean;
collapsed: boolean;
expand: () => void;
liveAsk: { actionId: string } | null;
checked: number[];
toggleChecked: (index: number) => void;
submitOption: (index: number) => void;
submitAnswer: (values: string[]) => void;
answerText: string;
setAnswerText: (value: string) => void;
};
const INERT_ASK_MODE: AskCardMode = {
popoverVisible: false,
collapsed: false,
expand: () => undefined,
liveAsk: null,
checked: [],
toggleChecked: () => undefined,
submitOption: () => undefined,
submitAnswer: () => undefined,
answerText: '',
setAnswerText: () => undefined,
};
/**
* 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 the composer's answer mode, 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,
answerMode = INERT_ASK_MODE,
submitAskAnswer = () => undefined,
getAskAnswerDraft = () => '',
setAskAnswerDraft = () => undefined,
}: {
actionId: string;
question: Agents.AskUserQuestionRequest;
questions?: Agents.AskUserQuestionBatchItem[];
/** The live pause, when this card is inside a chat that can move it to the composer. */
answerMode?: AskCardMode;
/** Resumes the run. Absent, the card still renders and submit does nothing. */
submitAskAnswer?: AskAnswerSubmit;
/** Restores a free-form answer after the card remounts outside a live pause. */
getAskAnswerDraft?: (actionId: string) => string;
setAskAnswerDraft?: (actionId: string, answer: string) => void;
}): ReactNode {
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}
submitAskAnswer={submitAskAnswer}
onExpand={answerMode.collapsed && isLivePause ? answerMode.expand : undefined}
/>
);
return reserved ? <AskingPlaceholder>{card}</AskingPlaceholder> : card;
}
return (
<AskUserQuestionSingle
actionId={actionId}
question={question}
answerMode={answerMode}
submitAskAnswer={submitAskAnswer}
getAskAnswerDraft={getAskAnswerDraft}
setAskAnswerDraft={setAskAnswerDraft}
/>
);
}
/** 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,
submitAskAnswer,
}: {
actionId: string;
questions: Agents.AskUserQuestionBatchItem[];
live: boolean;
reserved: boolean;
onExpand?: () => void;
submitAskAnswer: AskAnswerSubmit;
}) {
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}
ref={(node) => {
if (node == null) {
return;
}
if (reserved) {
node.setAttribute('inert', '');
return;
}
node.removeAttribute('inert');
}}
>
<AskUserQuestions
actionId={actionId}
questions={questions}
focusOnArrival={live}
submitAskAnswer={submitAskAnswer}
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,
submitAskAnswer,
getAskAnswerDraft,
setAskAnswerDraft,
}: {
actionId: string;
question: Agents.AskUserQuestionRequest;
answerMode: AskCardMode;
submitAskAnswer: AskAnswerSubmit;
getAskAnswerDraft: (actionId: string) => string;
setAskAnswerDraft: (actionId: string, answer: string) => void;
}) {
const localize = useLocalize();
const statusMap = useAtomValue(askSubmitStatusAtom);
const getAskStatus = (id: string) => statusMap[id] ?? 'idle';
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')}
variant="filled"
className="w-full resize-none"
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>
);
}

View file

@ -0,0 +1,478 @@
import { useCallback, useEffect, useId, useMemo, useRef } from 'react';
import { TriangleAlert } from 'lucide-react';
import { cn, Input, Button, useLocalize } from '@librechat/client';
import type { Agents } from 'librechat-data-provider';
import type { KeyboardEvent, ReactNode } from 'react';
import type { AskAnswerSubmit } from '../../../react/parts/ask';
import { isCancelKey, isReboundSubmitChord, splitOtherOption } from '../../../core';
import useArrivalFocus, { isFocusIdle } from '../../../react/parts/arrival';
import { useOptionalChatSurface } from '../../../react/subagents/surface';
import useAskQuestionsForm from '../../../react/parts/questionsForm';
import AutoHeight from '../AutoHeight';
import AskOptions from '../AskOptions';
/**
* 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,
submitAskAnswer = () => undefined,
}: {
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;
/** Resumes the run. Absent, the card still renders and submit does nothing. */
submitAskAnswer?: AskAnswerSubmit;
}): ReactNode {
const localize = useLocalize();
const promptId = useId();
const form = useAskQuestionsForm(actionId, questions, submitAskAnswer);
const composerBindings = useOptionalChatSurface()?.composerBindings;
const { goToStep, selectOption } = form;
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.prototype.hasOwnProperty.call(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.
*/
const handoffRef = useRef({
focusOnHandoff,
locked: form.locked,
focusStep,
markArrivalFocused: form.markArrivalFocused,
});
handoffRef.current = {
focusOnHandoff,
locked: form.locked,
focusStep,
markArrivalFocused: form.markArrivalFocused,
};
/** Mount only: a handoff is the surface appearing, not a later prop change. */
useEffect(() => {
const current = handoffRef.current;
if (!current.focusOnHandoff || current.locked) {
return;
}
current.focusStep({ firstOption: true, preventScroll: true });
current.markArrivalFocused();
}, []);
/**
* 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.prototype.hasOwnProperty.call(form.state.selected, question.id)
? form.state.selected[question.id]
: [];
const selectedIndices = choices.flatMap((option, optionIndex) =>
selected.includes(option.value) ? [optionIndex] : [],
);
const text = Object.prototype.hasOwnProperty.call(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) {
if (onEscape != null) {
event.preventDefault();
onEscape();
return;
}
if (form.locked || Object.keys(form.answers).length > 0) {
return;
}
event.preventDefault();
form.skip();
return;
}
/* 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. The handler sits on this surface
rather than the fieldset, which is not an interactive element. */
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();
};
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.prototype.hasOwnProperty.call(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"
>
{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>
);
}

View file

@ -1,10 +1,12 @@
/**
* @jest-environment jsdom
*/
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';
import type { MessagePartsHost } from '../../../../react/host';
import { emptyToolCallChrome, MessagePartsHostProvider } from '../../../../react/host';
import { FailedRevealContext } from '../../reveal';
import AskUserQuestionCall from '../Call';
const translations: Record<string, string> = {
com_ui_asked: 'Asked',
@ -18,7 +20,8 @@ const translations: Record<string, string> = {
com_ui_asking_n_questions: 'Asking {{0}} questions',
};
jest.mock('~/hooks', () => ({
jest.mock('@librechat/client', () => ({
...jest.requireActual('@librechat/client'),
useLocalize: () => (key: string, values?: Record<string, string>) => {
const template = translations[key] ?? key;
return values == null
@ -27,43 +30,41 @@ jest.mock('~/hooks', () => ({
},
}));
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;
},
}));
const createHost = (autoExpand: boolean): MessagePartsHost => ({
useMessage: () => ({ messageId: 'msg-1', isSubmitting: false, isLatestMessage: true }),
renderMarkdown: () => null,
useSmoothStreaming: () => false,
useAgent: () => undefined,
renderAgentIcon: () => null,
renderAgentAvatar: () => null,
renderContentParts: () => null,
renderImage: () => null,
renderFilePreview: () => null,
useFontSize: () => 'text-base',
useShowThinking: () => false,
useAutoExpandTools: () => autoExpand,
useLaTeXParsing: () => false,
useChatDirection: () => 'ltr',
useUserTextPreferences: () => ({
usernameDisplay: false,
enableUserMsgMarkdown: false,
collapseLongUserMessages: false,
}),
useUser: () => undefined,
useFileMap: () => undefined,
useToast: () => jest.fn(),
useSandboxStarting: () => false,
useToolArtifactClaim: () => [null, jest.fn()],
useSteerEscalating: () => false,
usePaneConversationId: () => null,
useLiveAppliedSteer: () => [false, jest.fn()],
useToolCallChrome: emptyToolCallChrome,
useShare: () => ({}),
});
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>,
);
render(<MessagePartsHostProvider host={createHost(autoExpand)}>{ui}</MessagePartsHostProvider>);
describe('AskUserQuestionCall', () => {
const args = JSON.stringify({
@ -74,7 +75,7 @@ describe('AskUserQuestionCall', () => {
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.getByRole('status')).toHaveTextContent('Asking');
expect(screen.queryByText('You answered:')).not.toBeInTheDocument();
});
@ -91,7 +92,7 @@ describe('AskUserQuestionCall', () => {
/>,
);
expect(screen.queryByTestId('ask-progress')).not.toBeInTheDocument();
expect(screen.queryByText('Asking')).not.toBeInTheDocument();
expect(screen.getByTestId('ask-user-question-call')).toBeInTheDocument();
},
);
@ -116,11 +117,11 @@ describe('AskUserQuestionCall', () => {
])('reveals a terminal question failure from its parent fold (%p)', (failure) => {
const call = <AskUserQuestionCall args={args} output="" {...failure} />;
const tree = (tick: number) => (
<RecoilRoot>
<MessagePartsHostProvider host={createHost(false)}>
<FailedRevealContext.Provider value={{ tick, claimFocus: () => true }}>
{call}
</FailedRevealContext.Provider>
</RecoilRoot>
</MessagePartsHostProvider>
);
const { rerender } = render(tree(0));
const button = screen.getByRole('button', { name: /Question wasn't shown/ });
@ -171,7 +172,7 @@ describe('AskUserQuestionCall', () => {
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
* panel starts closed: a present-tense summary would strand the record
* as permanently in flight. */
expect(header).toHaveTextContent('Asked');
expect(header).not.toHaveTextContent('Asking');

View file

@ -1,41 +1,61 @@
/**
* @jest-environment jsdom
*/
import React from 'react';
import { render, screen } from '@testing-library/react';
import { ToolPreparation } from '@librechat/chat/components';
import AskUserQuestionProgress from '../AskUserQuestionProgress';
import type { LiveAskPauses } from '../../../../react/parts/ask';
import { AskAnswerHostProvider } from '../../../../react/parts/ask';
import { ToolPreparation } from '../../preparation';
import AskUserQuestionProgress from '../Progress';
const translations: Record<string, string> = {
com_ui_asking: 'Asking',
com_ui_tool_name_ask_user_question: 'Question',
};
jest.mock('~/hooks', () => ({
jest.mock('@librechat/client', () => ({
...jest.requireActual('@librechat/client'),
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 } = {
let mockLivePauses: LiveAskPauses = {
ids: [],
hasUnattributed: false,
};
jest.mock('~/data-provider', () => ({
useCachedMessages: () => ({ data: mockLivePauses }),
}));
const renderProgress = (ui: React.ReactElement) =>
render(
<AskAnswerHostProvider saveDrafts={false} liveAskPauses={mockLivePauses}>
{ui}
</AskAnswerHostProvider>,
);
describe('AskUserQuestionProgress', () => {
beforeEach(() => {
mockLivePauses = { ids: [], hasUnattributed: false };
});
test('updates live pause data without changing consumer hooks and defaults to visible', () => {
const card = <AskUserQuestionProgress args='{"question":"Ready?"}' toolCallId="call_1" />;
const hosted = (liveAskPauses?: LiveAskPauses | null) => (
<AskAnswerHostProvider saveDrafts={false} liveAskPauses={liveAskPauses}>
{card}
</AskAnswerHostProvider>
);
const { rerender, unmount } = render(hosted());
expect(screen.getByText('Ready?')).toBeInTheDocument();
expect(() => rerender(hosted({ ids: ['call_1'], hasUnattributed: false }))).not.toThrow();
expect(screen.queryByText('Ready?')).not.toBeInTheDocument();
expect(() => rerender(hosted(null))).not.toThrow();
expect(screen.getByText('Ready?')).toBeInTheDocument();
unmount();
render(card);
expect(screen.getByText('Ready?')).toBeInTheDocument();
});
test('streams the question text from partial args', () => {
render(
renderProgress(
<AskUserQuestionProgress
args={'{"question":"Which environment should I dep'}
toolCallId="call_1"
@ -47,7 +67,7 @@ describe('AskUserQuestionProgress', () => {
});
test('decodes JSON escapes in the streaming question', () => {
render(
renderProgress(
<AskUserQuestionProgress args={'{"question":"Caf\\u00e9 or \\"bar\\"'} toolCallId="call_1" />,
);
@ -55,7 +75,7 @@ describe('AskUserQuestionProgress', () => {
});
test('streams the first question from partial batched args', () => {
render(
renderProgress(
<AskUserQuestionProgress
args={'{"questions":[{"id":"environment","question":"Which environ'}
toolCallId="call_1"
@ -66,7 +86,7 @@ describe('AskUserQuestionProgress', () => {
});
test('reads the first question from settled batched args', () => {
render(
renderProgress(
<AskUserQuestionProgress
args={{ questions: [{ id: 'environment', question: 'Which environment?' }] }}
toolCallId="call_1"
@ -77,7 +97,7 @@ describe('AskUserQuestionProgress', () => {
});
test('renders a skeleton line before any question text streams', () => {
render(<AskUserQuestionProgress args="" toolCallId="call_1" />);
renderProgress(<AskUserQuestionProgress args="" toolCallId="call_1" />);
expect(screen.getByText('Asking')).toBeInTheDocument();
expect(screen.getByRole('status')).toBeInTheDocument();
@ -86,7 +106,7 @@ describe('AskUserQuestionProgress', () => {
test('hides once the interactive pause for this call is live', () => {
mockLivePauses = { ids: ['call_1'], hasUnattributed: false };
const { container } = render(
const { container } = renderProgress(
<AskUserQuestionProgress args={'{"question":"Ready?"}'} toolCallId="call_1" />,
);
@ -96,7 +116,7 @@ describe('AskUserQuestionProgress', () => {
test('hides for an unattributed live pause (no tool_call_id on the payload)', () => {
mockLivePauses = { ids: [], hasUnattributed: true };
const { container } = render(
const { container } = renderProgress(
<AskUserQuestionProgress args={'{"question":"Ready?"}'} toolCallId="call_1" />,
);
@ -106,7 +126,7 @@ describe('AskUserQuestionProgress', () => {
test("stays visible while a DIFFERENT call's pause is interactive", () => {
mockLivePauses = { ids: ['call_1'], hasUnattributed: false };
render(
renderProgress(
<AskUserQuestionProgress args={'{"question":"Second question?"}'} toolCallId="call_2" />,
);
@ -116,7 +136,7 @@ describe('AskUserQuestionProgress', () => {
test('hides when its own pause is live alongside a newer sibling pause', () => {
mockLivePauses = { ids: ['call_1', 'call_2'], hasUnattributed: false };
const { container } = render(
const { container } = renderProgress(
<AskUserQuestionProgress args={'{"question":"First question?"}'} toolCallId="call_1" />,
);
@ -135,15 +155,20 @@ describe('question preparation transitions', () => {
<AskUserQuestionProgress args={args} toolCallId="call_1" />
</ToolPreparation>
);
const { rerender } = render(frame('{"question":"Which environment'));
const hosted = (node: React.ReactElement) => (
<AskAnswerHostProvider saveDrafts={false} liveAskPauses={mockLivePauses}>
{node}
</AskAnswerHostProvider>
);
const { rerender } = render(hosted(frame('{"question":"Which environment')));
expect(screen.getByRole('status')).toHaveTextContent('Preparing Question');
expect(screen.getByText('Which environment')).toBeInTheDocument();
rerender(frame('{"question":"Which environment?"}'));
rerender(hosted(frame('{"question":"Which environment?"}')));
expect(screen.getByRole('status')).toHaveTextContent('Preparing Question');
rerender(frame('{"question":"Which environment?"}', 100));
rerender(hosted(frame('{"question":"Which environment?"}', 100)));
expect(screen.getByRole('status')).toHaveTextContent('Asking');
mockLivePauses = { ids: ['call_1'], hasUnattributed: false };
rerender(frame('{"question":"Which environment?"}', 100));
rerender(hosted(frame('{"question":"Which environment?"}', 100)));
expect(screen.queryByRole('status')).not.toBeInTheDocument();
});
});

View file

@ -1,12 +1,14 @@
/**
* @jest-environment jsdom
*/
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';
import type { ShortcutBinding } from '../../../../core/shortcuts';
import type { AskCardMode } from '../Question';
import { ChatSurfaceProvider } from '../../../../react/subagents/provider';
import { ASK_USER_DECLINED_ANSWER } from '../../../../core';
import AskUserQuestion from '../Question';
const mockSubmitAnswer = jest.fn();
const mockSetAnswerText = jest.fn();
@ -18,13 +20,14 @@ 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'),
jest.mock('../../../../core/textarea', () => ({
...jest.requireActual('../../../../core/textarea'),
forceResize: jest.fn(),
insertTextAtCursor: (...args: unknown[]) => mockInsertTextAtCursor(...args),
}));
jest.mock('~/hooks', () => ({
jest.mock('@librechat/client', () => ({
...jest.requireActual('@librechat/client'),
useLocalize: () => (key: string) => {
const labels: Record<string, string> = {
com_ui_your_answer: 'Your answer',
@ -36,36 +39,20 @@ jest.mock('~/hooks', () => ({
},
}));
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,
}),
}));
const drafts = new Map<string, string>();
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 answerMode = (): AskCardMode => ({
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,
});
const yieldedChords = new Set<string>();
let submitOverride: ShortcutBinding | undefined;
@ -76,22 +63,32 @@ const tree = (
enterToSend = true,
actionId = 'ask-1',
) => (
<RecoilRoot>
<ChatSurfaceProvider
value={{
enterToSend,
maximizeChatSpace: false,
showScrollButton: false,
composerBindings: { shortcutsEnabled: true, submitOverride, yieldedChords },
claimForeground: jest.fn(),
handOffComposerText: jest.fn(),
<ChatSurfaceProvider
value={{
enterToSend,
maximizeChatSpace: false,
showScrollButton: false,
composerBindings: { shortcutsEnabled: true, submitOverride, yieldedChords },
claimForeground: jest.fn(),
handOffComposerText: jest.fn(),
}}
>
<AskUserQuestion
key={key}
actionId={actionId}
question={question}
answerMode={answerMode()}
submitAskAnswer={mockSubmitAnswer}
getAskAnswerDraft={(id) => drafts.get(id) ?? ''}
setAskAnswerDraft={(id, answer) => {
if (answer.length === 0) {
drafts.delete(id);
return;
}
drafts.set(id, answer);
}}
>
<ApprovalProvider>
<AskUserQuestion key={key} actionId={actionId} question={question} />
</ApprovalProvider>
</ChatSurfaceProvider>
</RecoilRoot>
/>
</ChatSurfaceProvider>
);
const withOptions: Agents.AskUserQuestionRequest = {
@ -105,6 +102,7 @@ const withOptions: Agents.AskUserQuestionRequest = {
describe('AskUserQuestion', () => {
beforeEach(() => {
jest.clearAllMocks();
drafts.clear();
mockPopoverVisible = false;
mockCollapsed = false;
mockLiveActionId = null;

View file

@ -1,20 +1,20 @@
/**
* @jest-environment jsdom
*/
import React from 'react';
import { RecoilRoot } from 'recoil';
import { ASK_USER_DECLINED_ANSWER } from '@librechat/chat';
import { ChatSurfaceProvider } from '@librechat/chat/react';
import { getDefaultStore } from 'jotai';
import { act, fireEvent, render, screen } from '@testing-library/react';
import type { Agents } from 'librechat-data-provider';
import AskUserQuestions from '../AskUserQuestions';
import type { AskAnswerStatus } from '../../../../react/parts/ask';
import { ChatSurfaceProvider } from '../../../../react/subagents/provider';
import { askSubmitStatusAtom } from '../../../../react/parts/ask';
import { ASK_USER_DECLINED_ANSWER } from '../../../../core';
import AskUserQuestions from '../Questions';
const mockSubmitAskAnswer = jest.fn();
let mockStatus = 'idle';
jest.mock('~/components/Chat/Messages/Content/ApprovalContext', () => ({
useAskSubmitStatus: () => ({ getAskStatus: () => mockStatus }),
useResumeSubmit: () => ({ submitAskAnswer: mockSubmitAskAnswer }),
}));
jest.mock('~/hooks', () => ({
jest.mock('@librechat/client', () => ({
...jest.requireActual('@librechat/client'),
useLocalize: () => (key: string, values?: Record<number, number>) => {
const labels: Record<string, string> = {
com_ui_question_number: `Question ${values?.[0] ?? ''}`,
@ -35,6 +35,11 @@ jest.mock('~/hooks', () => ({
},
}));
const setStatus = (actionId: string, status: AskAnswerStatus) => {
const store = getDefaultStore();
store.set(askSubmitStatusAtom, { ...store.get(askSubmitStatusAtom), [actionId]: status });
};
const questions: Agents.AskUserQuestionBatchItem[] = [
{
id: 'environment',
@ -54,9 +59,12 @@ const renderBatch = (
focusOnArrival = true,
) =>
render(
<RecoilRoot>
<AskUserQuestions actionId={actionId} questions={batch} focusOnArrival={focusOnArrival} />
</RecoilRoot>,
<AskUserQuestions
actionId={actionId}
questions={batch}
focusOnArrival={focusOnArrival}
submitAskAnswer={mockSubmitAskAnswer}
/>,
);
const optionBatch: Agents.AskUserQuestionBatchItem[] = [
@ -84,7 +92,7 @@ const isShown = (text: string) => screen.queryByText(text) != null;
describe('AskUserQuestions', () => {
beforeEach(() => {
mockStatus = 'idle';
getDefaultStore().set(askSubmitStatusAtom, {});
mockSubmitAskAnswer.mockClear();
});
@ -245,12 +253,14 @@ describe('AskUserQuestions', () => {
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>,
<form onSubmit={onFormSubmit}>
<AskUserQuestions
submitAskAnswer={mockSubmitAskAnswer}
actionId="ask-enter"
questions={questions}
/>
<button type="submit" aria-label="Send composer" />
</form>,
);
const first = screen.getByRole('textbox', { name: /Where should this run/ });
@ -310,11 +320,13 @@ describe('AskUserQuestions', () => {
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>,
<form onSubmit={onSubmit}>
<AskUserQuestions
submitAskAnswer={mockSubmitAskAnswer}
actionId="ask-implicit-submit"
questions={questions}
/>
</form>,
);
const first = screen.getByRole('textbox', { name: /Where should this run/ });
fireEvent.change(first, { target: { value: 'Locally' } });
@ -329,24 +341,26 @@ describe('AskUserQuestions', () => {
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>,
<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
submitAskAnswer={mockSubmitAskAnswer}
actionId="ask-rebound-submit"
questions={questions}
/>
</ChatSurfaceProvider>,
);
const first = screen.getByRole('textbox', { name: /Where should this run/ });
fireEvent.change(first, { target: { value: 'Locally' } });
@ -421,17 +435,23 @@ describe('AskUserQuestions', () => {
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>,
<AskUserQuestions
submitAskAnswer={mockSubmitAskAnswer}
actionId="ask-focus-handoff"
questions={questions}
focusOnArrival
/>,
);
expect(screen.getByRole('button', { name: /Staging/ })).toHaveFocus();
view.unmount();
render(
<RecoilRoot>
<AskUserQuestions actionId="ask-focus-handoff" questions={questions} focusOnHandoff />
</RecoilRoot>,
<AskUserQuestions
submitAskAnswer={mockSubmitAskAnswer}
actionId="ask-focus-handoff"
questions={questions}
focusOnHandoff
/>,
);
expect(screen.getByRole('button', { name: /Staging/ })).toHaveFocus();
});
@ -444,9 +464,12 @@ describe('AskUserQuestions', () => {
leftBehind.focus();
render(
<RecoilRoot>
<AskUserQuestions actionId="ask-focus-left-behind" questions={questions} focusOnHandoff />
</RecoilRoot>,
<AskUserQuestions
submitAskAnswer={mockSubmitAskAnswer}
actionId="ask-focus-left-behind"
questions={questions}
focusOnHandoff
/>,
);
expect(screen.getByRole('button', { name: /Staging/ })).toHaveFocus();
leftBehind.remove();
@ -627,9 +650,11 @@ describe('AskUserQuestions', () => {
});
view.rerender(
<RecoilRoot>
<AskUserQuestions actionId="ask-remount" questions={questions} />
</RecoilRoot>,
<AskUserQuestions
submitAskAnswer={mockSubmitAskAnswer}
actionId="ask-remount"
questions={questions}
/>,
);
expect(screen.getByText('Question 2 of 2')).toBeInTheDocument();
@ -675,17 +700,19 @@ describe('AskUserQuestions', () => {
});
test('keeps an expired batch readable but freezes steps mid-submit', () => {
mockStatus = 'expired';
setStatus('ask-expired', 'expired');
const view = renderBatch('ask-expired');
fireEvent.click(screen.getByRole('button', { name: 'Next' }));
expect(isShown('Which time window?')).toBe(true);
mockStatus = 'submitting';
setStatus('ask-expired', 'submitting');
view.rerender(
<RecoilRoot>
<AskUserQuestions actionId="ask-expired" questions={questions} />
</RecoilRoot>,
<AskUserQuestions
submitAskAnswer={mockSubmitAskAnswer}
actionId="ask-expired"
questions={questions}
/>,
);
expect(screen.getByRole('button', { name: 'Back' })).toBeDisabled();
});
@ -732,13 +759,12 @@ describe('AskUserQuestions', () => {
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>,
<AskUserQuestions
submitAskAnswer={mockSubmitAskAnswer}
actionId="ask-escape-surface"
questions={questions}
onEscape={onEscape}
/>,
);
fireEvent.keyDown(screen.getByRole('button', { name: /Staging/ }), { key: 'Escape' });
expect(onEscape).toHaveBeenCalledTimes(1);

View file

@ -7,6 +7,21 @@
*/
export const TOOL_ROW_CLASSES = 'relative my-1.5 flex h-5 shrink-0 items-center gap-2.5';
/** The absolutely positioned line inside a tool row, shared by every progress header. */
export const PROGRESS_TEXT_WRAPPER =
'progress-text-wrapper text-text-secondary relative -mt-[0.046875rem] h-5 w-full leading-5';
/** Caps that line at the message column while leaving the focus ring visible. */
export const PROGRESS_TEXT_CONTENT =
'progress-text-content absolute top-0 right-0 left-0 max-w-full overflow-visible whitespace-nowrap';
/**
* Grid collapse for a disclosure panel. The rules live in `parts.css`; the
* rows, opacity and transition are the `--expand-*` custom properties
* `useExpandCollapse` already computes.
*/
export const DISCLOSURE_COLLAPSE = 'disclosure-collapse';
/** Leave an 8px gap beside MessageNav's hit area in full-width chat. */
export const ARTIFACT_ROW_NAV_SPACING = 'pe-3 md:pe-17';

View file

@ -22,6 +22,7 @@ import {
MessagePartsHostProvider,
useMessagePartsHost,
} from '../../../react/host';
import { AskAnswerHostProvider, useLiveAskPauses } from '../../../react/parts/ask';
import { mergeChildConversationTurns } from '../../../react/subagents/adapters';
import { createSubagentsHost } from '../../../__fixtures__/subagentsHost';
import { ChatSurfaceProvider } from '../../../react/subagents/provider';
@ -37,6 +38,7 @@ const mockRenderedContent = jest.fn<void, [Array<TMessageContentParts | undefine
const mockPartScope = jest.fn<void, [ChatContract | null, Ask | undefined]>();
const lastCall = <T,>(calls: T[]): T => calls[calls.length - 1];
const mockParentAsk = jest.fn();
const mockAskPauses = jest.fn();
jest.mock('../../messages/MinimalHoverButtons', () => ({
__esModule: true,
@ -79,6 +81,8 @@ function partLabel(part: TMessageContentParts | undefined): string {
function ContentPartsMock({ content, messageId }: ContentPartsSlotProps) {
const host = useMessagePartsHost();
const liveAskPauses = useLiveAskPauses();
mockAskPauses(liveAskPauses);
mockPartScope(useContext(ChatContext), hasAsk(host) ? host.useMessagesAsk() : undefined);
mockRenderedContent(content);
return (
@ -207,6 +211,26 @@ const turns: ChildConversationTurn[] = [
},
];
describe('child ask pause scope', () => {
test.each([false, true])('only shares parent live pauses for interactive=%s', (interactive) => {
const pauses = { ids: ['parent-call'], hasUnattributed: false };
render(
<ChatSurfaceHarness>
<AskAnswerHostProvider saveDrafts={false} liveAskPauses={pauses}>
<SubagentConversation
turns={turns}
author={author}
parentAuthor={parentAuthor}
interactive={interactive}
/>
</AskAnswerHostProvider>
</ChatSurfaceHarness>,
);
expect(mockAskPauses).toHaveBeenCalled();
expect(mockAskPauses).toHaveBeenLastCalledWith(interactive ? pauses : null);
});
});
describe('SubagentConversation', () => {
it('renders parent turns and child activity through the main chat row and content modules', () => {
const { container } = render(

View file

@ -16,6 +16,7 @@ import type { ChildConversationTurn } from '../../react/subagents/adapters';
import type { ToolContentQuery } from '../../react/parts/disclosure';
import type { TaskContentScope } from '../../react/subagents/scope';
import type { TurnAuthor } from '../../react/subagents/author';
import { AskAnswerHostProvider, useAskAnswerHost, useLiveAskPauses } from '../../react/parts/ask';
import { isAbnormalTerminalStatus, isLiveSubagentStatus } from '../../react/subagents/status';
import { SubagentActivityContent, SubagentStatus, getActivityContent } from './transcript';
import { MessagePartsHostProvider, useMessagePartsHost } from '../../react/host';
@ -455,48 +456,55 @@ export default function SubagentConversation({
}): ReactNode {
const { maximizeChatSpace: fullWidth } = useChatSurface();
const parentChat = useContext(ChatContext);
const saveDrafts = useAskAnswerHost();
const liveAskPauses = useLiveAskPauses();
const host = useMessagePartsHost();
const contentHost = useSubagentsHost().useChildPartsHost(host);
const Message = recovery == null ? ChildMessage : RecoveredChildMessage;
return (
<ChatContext.Provider value={interactive ? parentChat : null}>
<MessagePartsHostProvider host={contentHost}>
<div className="flex flex-col gap-6 py-4" data-subagent-conversation>
{turns.map((turn) => (
<section
key={turn.taskId}
className="flex flex-col gap-4"
data-subagent-thread-turn={turn.taskId}
>
<div className="px-4">
<TriggerMessage turn={turn} fullWidth={fullWidth} parentAuthor={parentAuthor} />
</div>
<div className="px-4">
<Message
turn={turn}
recovery={recovery}
author={author}
conversationId={conversationId}
fullWidth={fullWidth}
state={stateByTask?.get(turn.taskId) ?? 'ready'}
onCancelControl={
onCancelControl == null || turn.taskId !== controllableTaskId
? undefined
: (controlId) => onCancelControl(turn.taskId, controlId)
}
toolContentQuery={toolContentQueries?.get(turn.taskId)}
detailState={detailStateByTask?.get(turn.taskId)}
onLoadDetails={
turn.activity.activityTruncated !== true || onLoadTurnDetails == null
? undefined
: () => onLoadTurnDetails(turn.taskId)
}
/>
</div>
</section>
))}
</div>
</MessagePartsHostProvider>
<AskAnswerHostProvider
saveDrafts={saveDrafts}
liveAskPauses={interactive ? liveAskPauses : null}
>
<MessagePartsHostProvider host={contentHost}>
<div className="flex flex-col gap-6 py-4" data-subagent-conversation>
{turns.map((turn) => (
<section
key={turn.taskId}
className="flex flex-col gap-4"
data-subagent-thread-turn={turn.taskId}
>
<div className="px-4">
<TriggerMessage turn={turn} fullWidth={fullWidth} parentAuthor={parentAuthor} />
</div>
<div className="px-4">
<Message
turn={turn}
recovery={recovery}
author={author}
conversationId={conversationId}
fullWidth={fullWidth}
state={stateByTask?.get(turn.taskId) ?? 'ready'}
onCancelControl={
onCancelControl == null || turn.taskId !== controllableTaskId
? undefined
: (controlId) => onCancelControl(turn.taskId, controlId)
}
toolContentQuery={toolContentQueries?.get(turn.taskId)}
detailState={detailStateByTask?.get(turn.taskId)}
onLoadDetails={
turn.activity.activityTruncated !== true || onLoadTurnDetails == null
? undefined
: () => onLoadTurnDetails(turn.taskId)
}
/>
</div>
</section>
))}
</div>
</MessagePartsHostProvider>
</AskAnswerHostProvider>
</ChatContext.Provider>
);
}

View file

@ -24,7 +24,8 @@ export * from './branch';
export * from './subagents';
export { strongDirection } from './direction';
export * from './shortcuts';
export { removeCharIfLast } from './textarea';
export { removeCharIfLast, insertTextAtCursor, forceResize } from './textarea';
export { isRectVisible } from './viewport';
export * from './pane';
export * from './documents';
export * from './thread';

View file

@ -1,3 +1,32 @@
/** Inserts text at the caret as an undoable edit when the browser allows it. */
export function insertTextAtCursor(element: HTMLTextAreaElement, textToInsert: string): void {
element.focus();
if (window.getSelection() && document.queryCommandSupported('insertText')) {
document.execCommand('insertText', false, textToInsert);
return;
}
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;
element.dispatchEvent(new Event('input', { bubbles: true }));
}
/**
* Recalculates a textarea's height after a change the browser did not measure,
* such as a newline inserted at the caret.
*/
export function forceResize(element: HTMLTextAreaElement | null): void {
if (!element) {
return;
}
element.style.height = 'auto';
element.style.height = `${element.scrollHeight}px`;
}
/** Drops the command character a popover was opened with when it still ends the draft, and puts
* the caret back in the textarea. */
export function removeCharIfLast(textarea: HTMLTextAreaElement, charToRemove: string): void {

View file

@ -0,0 +1,16 @@
/** 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;
}

View file

@ -247,6 +247,7 @@ export { default as useRowHandoff } from './react/parts/handoff';
export {
askAnswerTextAtom,
useAskAnswerHost,
useLiveAskPauses,
askSubmitStatusAtom,
askAnswerCheckedAtom,
AskAnswerHostProvider,
@ -254,7 +255,12 @@ export {
expandedAskActionsAtom,
releasedComposerTextAtom,
} from './react/parts/ask';
export type { AskAnswerStatus, ReleasedComposerStash } from './react/parts/ask';
export type {
LiveAskPauses,
AskAnswerStatus,
AskAnswerSubmit,
ReleasedComposerStash,
} from './react/parts/ask';
export { default as useComposerItems } from './react/items';
export type { ComposerItem, ComposerItemKind } from './react/items';
export { useFilesHost, FilesHostProvider } from './react/files';

View file

@ -1,7 +1,7 @@
import { useEffect, useRef } from 'react';
import type { RefObject } from 'react';
import { mainTextareaId } from '~/common';
import { isRectVisible } from '~/utils';
import { mainTextareaId } from '../../core/composer';
import { isRectVisible } from '../../core/viewport';
/** Focus is nowhere, or in the empty composer that just sent the turn. */
export function isFocusIdle(): boolean {

View file

@ -38,20 +38,51 @@ export const askSubmitStatusAtom: PrimitiveAtom<Record<string, AskAnswerStatus>>
Record<string, AskAnswerStatus>
>({});
/** Live ask pauses already on screen, keyed the way the progress card matches a call. */
export type LiveAskPauses = {
ids: string[];
hasUnattributed: boolean;
};
/** What a card submits, and the free-form draft it restores after a remount. */
export type AskAnswerSubmit = (
actionId: string,
resolution: string | Record<string, string>,
opts?: { onSuccess?: () => void },
) => void;
const AskAnswerHostContext = createContext(false);
/** No live pause. A card outside the host stays visible rather than hiding itself. */
const LiveAskPausesContext = createContext<LiveAskPauses | null>(null);
export function AskAnswerHostProvider({
saveDrafts,
liveAskPauses = null,
children,
}: {
saveDrafts: boolean;
/**
* Which ask calls already have an interactive pause. The host owns the subscription;
* absent data leaves the in-progress card visible.
*/
liveAskPauses?: LiveAskPauses | null;
children?: ReactNode;
}): ReactNode {
return (
<AskAnswerHostContext.Provider value={saveDrafts}>{children}</AskAnswerHostContext.Provider>
<AskAnswerHostContext.Provider value={saveDrafts}>
<LiveAskPausesContext.Provider value={liveAskPauses}>
{children}
</LiveAskPausesContext.Provider>
</AskAnswerHostContext.Provider>
);
}
export function useAskAnswerHost(): boolean {
return useContext(AskAnswerHostContext);
}
/** The host's live pauses, or none outside a provider. */
export function useLiveAskPauses(): LiveAskPauses | null {
return useContext(LiveAskPausesContext);
}

View file

@ -1,12 +1,10 @@
import { useCallback, useMemo } from 'react';
import { atom, useAtom } from 'jotai';
import { atomFamily } from 'jotai/utils';
import { ASK_USER_DECLINED_ANSWER } from '@librechat/chat';
import { atom, useAtom, useAtomValue } from 'jotai';
import type { Agents } from 'librechat-data-provider';
import {
useAskSubmitStatus,
useResumeSubmit,
} from '~/components/Chat/Messages/Content/ApprovalContext';
import type { AskAnswerStatus, AskAnswerSubmit } from './ask';
import { ASK_USER_DECLINED_ANSWER } from '../../core/parts/questions';
import { askSubmitStatusAtom } from './ask';
interface AskQuestionsFormState {
/** Index of the question currently on screen. Lives beside the answers so the
@ -33,18 +31,34 @@ const askQuestionsFormFamily = atomFamily((_actionId: string) =>
);
function ownValue<T>(record: Record<string, T>, key: string): T | undefined {
return Object.hasOwn(record, key) ? record[key] : undefined;
return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined;
}
interface AskQuestionsForm {
state: AskQuestionsFormState;
step: number;
status: AskAnswerStatus;
locked: boolean;
answers: Record<string, string>;
canSubmit: boolean;
setText: (question: Agents.AskUserQuestionBatchItem, value: string) => void;
selectOption: (question: Agents.AskUserQuestionBatchItem, value: string) => void;
goToStep: (index: number) => void;
submit: () => boolean;
skip: () => boolean;
arrivalFocused: boolean;
markArrivalFocused: () => void;
}
export default function useAskQuestionsForm(
actionId: string,
questions: Agents.AskUserQuestionBatchItem[],
) {
submitAskAnswer: AskAnswerSubmit,
): AskQuestionsForm {
const [state, setState] = useAtom(askQuestionsFormFamily(actionId));
const resetState = useCallback(() => setState(EMPTY_FORM), [setState]);
const { submitAskAnswer } = useResumeSubmit();
const { getAskStatus } = useAskSubmitStatus();
const status = getAskStatus(actionId);
const statusMap = useAtomValue(askSubmitStatusAtom);
const status: AskAnswerStatus = ownValue(statusMap, actionId) ?? 'idle';
const locked = status === 'submitting' || status === 'submitted' || status === 'expired';
const setText = useCallback(

View file

@ -20,6 +20,19 @@ const EMBEDDED = [
'text-text-primary',
'theme-field-fill:bg-surface-tertiary-alt',
];
const FILLED = [
'rounded-lg',
'border',
'border-border-light',
'bg-surface-chat',
'px-3',
'py-2',
'text-sm',
'text-text-primary',
'placeholder:text-text-secondary',
'focus-visible:ring-2',
'focus-visible:ring-text-primary',
];
const FRAMED = [
'lc-own-focus',
'rounded-xl',
@ -98,6 +111,14 @@ describe('field variants', () => {
);
});
it('TextareaAutosize filled carries the compact card field exactly', () => {
render(
<TextareaAutosize aria-label="answer" variant="filled" className="w-full resize-none" />,
);
const field = screen.getByLabelText('answer');
expect(field).toHaveClass(...FILLED, 'w-full', 'resize-none');
});
it('TextareaAutosize framed carries the bordered editor box exactly', () => {
render(<TextareaAutosize aria-label="draft" variant="framed" className="min-h-20" />);
const field = screen.getByLabelText('draft');

View file

@ -16,6 +16,10 @@ import './Field.css';
/** A rounded editor box of its own, such as a prompt or message editor. */
const framed = `${FIELD_OWN_FOCUS} rounded-xl border border-border-medium bg-transparent text-text-primary placeholder:text-text-secondary focus-visible:ring-2 focus-visible:ring-focus-control`;
/** A compact filled field inside a card: light border, chat surface, small type. */
const filled =
'rounded-lg border border-border-light bg-surface-chat px-3 py-2 text-sm text-text-primary placeholder:text-text-secondary focus-visible:ring-2 focus-visible:ring-text-primary';
/** The chat composer's draft: no frame of its own (the composer surface draws it), the composer
* type scale, and a max height that eases as the draft collapses. `data-listening` hides the
* caret and placeholder while dictation stands in for them; `data-locked` stops selection. */
@ -27,12 +31,13 @@ const composer =
* editor box, `flush` draws no border or ring because the surrounding frame owns the indicator,
* `embedded` fills a list or popover row edge to edge, and `composer` is the chat draft. */
const AUTOSIZE_VARIANTS: Record<
'default' | 'field' | 'framed' | 'flush' | 'embedded' | 'composer',
'default' | 'field' | 'framed' | 'filled' | 'flush' | 'embedded' | 'composer',
string
> = {
default: '',
field: fieldBase,
framed,
filled,
flush: `${FIELD_OWN_FOCUS} ${fieldFlush}`,
embedded: fieldEmbedded,
composer,

View file

@ -0,0 +1,45 @@
import postcss from 'postcss';
import { resolve } from 'path';
import { readFileSync } from 'fs';
const read = (path: string) => readFileSync(resolve(__dirname, path), 'utf8');
const parts = postcss.parse(read('./parts.css'));
const app = postcss.parse(read('../../../../client/src/style.css'));
const sharedSelectors = [
'.tool-status-text',
'.shimmer',
'.progress-text-wrapper',
'.progress-text-content',
'.progress-text-wrapper button',
'.disclosure-collapse',
];
describe('ask card stylesheet cascade', () => {
test('loads the shared stylesheet first without app redefinitions of the moved rules', () => {
const main = read('../../../../client/src/main.jsx');
expect(main.indexOf("import '@librechat/client/style.css'")).toBeLessThan(
main.indexOf("import './style.css'"),
);
const selectors: string[] = [];
app.walkRules((rule) => {
selectors.push(...rule.selectors);
});
for (const selector of sharedSelectors) {
expect(selectors).not.toContain(selector);
}
});
test('keeps card presentation outside Tailwind layers so later app utilities cannot override it', () => {
for (const selector of sharedSelectors) {
const rules = parts.nodes.filter(
(node) => node.type === 'rule' && node.selectors.includes(selector),
);
expect(rules).toHaveLength(1);
}
const collapse = parts.nodes.find(
(node) => node.type === 'rule' && node.selector === '.disclosure-collapse',
);
expect(collapse?.toString()).toContain('grid-template-rows: var(--expand-rows, 1fr)');
expect(collapse?.toString()).toContain('transition: var(--expand-transition)');
});
});

View file

@ -347,3 +347,16 @@
transform: none;
}
}
/**
* The grid collapse `useExpandCollapse` measures. Rows, opacity and the
* transition are custom properties so a reduced-motion reader still gets the
* 0.01ms transition that fires `transitionend`. Inline style cannot say that
* in the chat package.
*/
.disclosure-collapse {
display: grid;
grid-template-rows: var(--expand-rows, 1fr);
opacity: var(--expand-opacity, 1);
transition: var(--expand-transition);
}