From 2bf6ca847a67f6c68187c72f3a00a3dcaca687a2 Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:11:57 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9D=93=20refactor:=20Move=20the=20Ask-User?= =?UTF-8?q?=20Question=20Cards=20Into=20@librechat/chat=20(#18161)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- .github/guard-specs.json | 5 + client/src/components/Chat/AskHost.tsx | 33 ++ client/src/components/Chat/ChatView.tsx | 6 +- .../Chat/Messages/Content/AskUserQuestion.tsx | 453 +-------------- .../Messages/Content/AskUserQuestions.tsx | 468 +--------------- .../components/Chat/Messages/Content/Part.tsx | 9 +- .../Chat/Messages/Content/ProgressText.tsx | 10 +- .../AskUserQuestion.adapter.test.tsx | 106 ++++ .../Content/__tests__/Part.registry.test.tsx | 5 +- .../Chat/__tests__/AskHost.spec.tsx | 54 ++ .../Chat/__tests__/ChatView.slots.spec.tsx | 1 + .../Chat/__tests__/ChatView.spec.tsx | 1 + .../Chat/__tests__/ChatView.subagent.spec.tsx | 1 + client/src/components/ui/AutoHeight.tsx | 57 +- .../ui/__tests__/AutoHeight.spec.tsx | 11 + client/src/utils/textarea.ts | 49 +- client/src/utils/viewport.ts | 17 +- e2e/specs/mock/scenarios/ask-keyboard.spec.ts | 54 ++ eslint-suppressions.json | 10 - packages/chat/src/components.ts | 8 + .../chat/src/components/parts/AutoHeight.tsx | 55 ++ .../src/components/parts/PendingSkillCall.tsx | 11 +- .../chat/src/components/parts/ask/Call.tsx | 179 ++++-- .../src/components/parts/ask/Progress.tsx | 30 +- .../src/components/parts/ask/Question.tsx | 514 ++++++++++++++++++ .../src/components/parts/ask/Questions.tsx | 478 ++++++++++++++++ .../parts/ask/__tests__/Call.spec.tsx | 91 ++-- .../parts/ask/__tests__/Progress.spec.tsx | 79 ++- .../parts/ask/__tests__/Question.spec.tsx | 104 ++-- .../parts/ask/__tests__/Questions.spec.tsx | 162 +++--- packages/chat/src/components/parts/rows.ts | 15 + .../subagents/__tests__/conversation.spec.tsx | 24 + .../src/components/subagents/conversation.tsx | 82 +-- packages/chat/src/core/index.ts | 3 +- packages/chat/src/core/textarea.ts | 29 + packages/chat/src/core/viewport.ts | 16 + packages/chat/src/react.ts | 8 +- .../chat/src/react/parts/arrival.ts | 4 +- packages/chat/src/react/parts/ask.tsx | 33 +- .../chat/src/react/parts/questionsForm.ts | 36 +- packages/client/src/components/Field.spec.tsx | 21 + .../src/components/TextareaAutosize.tsx | 7 +- packages/client/src/theme/askParts.spec.ts | 45 ++ packages/client/src/theme/parts.css | 13 + 44 files changed, 2052 insertions(+), 1345 deletions(-) create mode 100644 client/src/components/Chat/AskHost.tsx create mode 100644 client/src/components/Chat/Messages/Content/__tests__/AskUserQuestion.adapter.test.tsx create mode 100644 client/src/components/Chat/__tests__/AskHost.spec.tsx create mode 100644 packages/chat/src/components/parts/AutoHeight.tsx rename client/src/components/Chat/Messages/Content/AskUserQuestionCall.tsx => packages/chat/src/components/parts/ask/Call.tsx (69%) rename client/src/components/Chat/Messages/Content/AskUserQuestionProgress.tsx => packages/chat/src/components/parts/ask/Progress.tsx (76%) create mode 100644 packages/chat/src/components/parts/ask/Question.tsx create mode 100644 packages/chat/src/components/parts/ask/Questions.tsx rename client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionCall.test.tsx => packages/chat/src/components/parts/ask/__tests__/Call.spec.tsx (83%) rename client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionProgress.test.tsx => packages/chat/src/components/parts/ask/__tests__/Progress.spec.tsx (65%) rename client/src/components/Chat/Messages/Content/__tests__/AskUserQuestion.test.tsx => packages/chat/src/components/parts/ask/__tests__/Question.spec.tsx (83%) rename client/src/components/Chat/Messages/Content/__tests__/AskUserQuestions.test.tsx => packages/chat/src/components/parts/ask/__tests__/Questions.spec.tsx (89%) create mode 100644 packages/chat/src/core/viewport.ts rename client/src/hooks/Input/useArrivalFocus.ts => packages/chat/src/react/parts/arrival.ts (94%) rename client/src/hooks/Input/useAskQuestionsForm.ts => packages/chat/src/react/parts/questionsForm.ts (82%) create mode 100644 packages/client/src/theme/askParts.spec.ts diff --git a/.github/guard-specs.json b/.github/guard-specs.json index 8e9a99e02a..f13cbb56a0 100644 --- a/.github/guard-specs.json +++ b/.github/guard-specs.json @@ -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", diff --git a/client/src/components/Chat/AskHost.tsx b/client/src/components/Chat/AskHost.tsx new file mode 100644 index 0000000000..701db3c3f6 --- /dev/null +++ b/client/src/components/Chat/AskHost.tsx @@ -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 ( + + {children} + + ); +} diff --git a/client/src/components/Chat/ChatView.tsx b/client/src/components/Chat/ChatView.tsx index 47b7d12461..6e50a5adbc 100644 --- a/client/src/components/Chat/ChatView.tsx +++ b/client/src/components/Chat/ChatView.tsx @@ -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({ - + @@ -219,7 +219,7 @@ function ChatViewPane({ - + diff --git a/client/src/components/Chat/Messages/Content/AskUserQuestion.tsx b/client/src/components/Chat/Messages/Content/AskUserQuestion.tsx index 02095611c2..2b6310b6a7 100644 --- a/client/src/components/Chat/Messages/Content/AskUserQuestion.tsx +++ b/client/src/components/Chat/Messages/Content/AskUserQuestion.tsx @@ -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(); +type QuestionProps = ComponentProps; -/** 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 = ( - - ); - return reserved ? {card} : card; - } - return ; -} - -/** 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 ( -
- -
- ); -} - -function AskUserQuestionSingle({ - actionId, - question, - answerMode, -}: { - actionId: string; - question: Agents.AskUserQuestionRequest; - answerMode: ReturnType; -}) { - const localize = useLocalize(); const { getAskAnswerDraft, setAskAnswerDraft } = useApprovalContext(); - const { getAskStatus } = useAskSubmitStatus(); const { submitAskAnswer } = useResumeSubmit(); - const [answer, setAnswer] = useState(() => getAskAnswerDraft(actionId)); - const [localChecked, setLocalChecked] = useState([]); - 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(null); - const optionRefs = useRef<(HTMLButtonElement | null)[]>([]); - const answerRef = useRef(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) => { - 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) => { - 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 = ( -
-
-
-

- {question.question} -

- {question.description != null && question.description.length > 0 && ( -

- {question.description} -

- )} -
- {collapsed && isLivePause && ( - -
- - {choices.length > 0 && ( - (multiSelect ? toggleIndex(index) : submitSingle(index))} - optionRefs={optionRefs} - /> - )} - - { - 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')} - /> - -
- - {(status === 'expired' || status === 'error') && ( - - - )} - -
-
- ); - - if (!showPlaceholder) { - return card; - } - - return {card}; -} - -/** Popover has the question: the reserved card sits hidden underneath the - * same compact in-progress row the other tools use, so the turn still - * shows the call is running. */ -function AskingPlaceholder({ children }: { children: React.ReactNode }) { - const localize = useLocalize(); return ( -
- {children} -
-
-
+ ); } diff --git a/client/src/components/Chat/Messages/Content/AskUserQuestions.tsx b/client/src/components/Chat/Messages/Content/AskUserQuestions.tsx index d1e96be3f0..9e95706ed0 100644 --- a/client/src/components/Chat/Messages/Content/AskUserQuestions.tsx +++ b/client/src/components/Chat/Messages/Content/AskUserQuestions.tsx @@ -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; - const scrollRef = useRef(null); - const stepRef = useRef(null); - const answerRef = useRef(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 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('button[data-selected]:not(:disabled)') ?? - (firstOption ? step.querySelector('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) => { - 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 ( -
- {/* 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. */} - - {stepped && ( -

- {localize('com_ui_question_step', { 0: activeIndex + 1, 1: total })} -

- )} -
- {/* Bounded so a long prompt scrolls rather than pushing the composer - popover past the top of the viewport. */} -
- {question.header != null && question.header !== '' && ( -

{question.header}

- )} -

- {question.question} -

- {question.description != null && question.description.length > 0 && ( -

{question.description}

- )} -
- {(stepped || headerAction != null) && ( -
- {stepped && ( -
- {questions.map((item, index) => { - const isAnswered = Object.hasOwn(form.answers, item.id); - const isActive = index === activeIndex; - return ( - - ); - })} -
- )} - {headerAction} -
- )} -
- {/* `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. */} -
-
{ - /* 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 && ( - 0} - onActivate={(optionIndex) => - handleSelectOption(question, choices[optionIndex].value) - } - className="flex flex-col" - /> - )} - 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')}`} - /> -
-
-
- {(form.status === 'error' || form.status === 'expired') && ( -
-
- )} - {showRemaining && ( - - )} -
-
-
- -
- {stepped && ( - - )} - {isLastStep ? ( - - ) : ( - - )} -
-
-
- ); +/** The app's question batch: resume goes through the approval host. */ +export default function AskUserQuestions(props: Omit) { + const { submitAskAnswer } = useResumeSubmit(); + return ; } diff --git a/client/src/components/Chat/Messages/Content/Part.tsx b/client/src/components/Chat/Messages/Content/Part.tsx index cf6b0da7bf..cc5996daf5 100644 --- a/client/src/components/Chat/Messages/Content/Part.tsx +++ b/client/src/components/Chat/Messages/Content/Part.tsx @@ -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'; diff --git a/client/src/components/Chat/Messages/Content/ProgressText.tsx b/client/src/components/Chat/Messages/Content/ProgressText.tsx index 46932a0d3d..570c2c1073 100644 --- a/client/src/components/Chat/Messages/Content/ProgressText.tsx +++ b/client/src/components/Chat/Messages/Content/ProgressText.tsx @@ -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, diff --git a/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestion.adapter.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestion.adapter.test.tsx new file mode 100644 index 0000000000..1c686fde41 --- /dev/null +++ b/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestion.adapter.test.tsx @@ -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( + + + + + , + ); +} + +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( + + + + + , + ); + + 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( + + + + + , + ); + + 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), + ); + }); +}); diff --git a/client/src/components/Chat/Messages/Content/__tests__/Part.registry.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/Part.registry.test.tsx index a88b6c05a2..1271649d7a 100644 --- a/client/src/components/Chat/Messages/Content/__tests__/Part.registry.test.tsx +++ b/client/src/components/Chat/Messages/Content/__tests__/Part.registry.test.tsx @@ -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 => { diff --git a/client/src/components/Chat/__tests__/AskHost.spec.tsx b/client/src/components/Chat/__tests__/AskHost.spec.tsx new file mode 100644 index 0000000000..fc7b3d0d00 --- /dev/null +++ b/client/src/components/Chat/__tests__/AskHost.spec.tsx @@ -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( + + + + + , + ); +} + +describe('AskHost live pauses', () => { + beforeEach(() => { + mockPauses = { ids: [], hasUnattributed: false }; + }); + + test('updates mounted progress cards when the conversation pause changes', () => { + const view = () => ( + + + + ); + 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(); + }); +}); diff --git a/client/src/components/Chat/__tests__/ChatView.slots.spec.tsx b/client/src/components/Chat/__tests__/ChatView.slots.spec.tsx index 8cac77ab09..a86b4fd2a8 100644 --- a/client/src/components/Chat/__tests__/ChatView.slots.spec.tsx +++ b/client/src/components/Chat/__tests__/ChatView.slots.spec.tsx @@ -23,6 +23,7 @@ jest.mock('~/hooks/Chat/target', () => ({ })); jest.mock('~/data-provider', () => ({ + useCachedMessages: () => ({ data: null }), useProjectQuery: () => ({ data: undefined }), })); diff --git a/client/src/components/Chat/__tests__/ChatView.spec.tsx b/client/src/components/Chat/__tests__/ChatView.spec.tsx index 0cb260f34f..9c88425acc 100644 --- a/client/src/components/Chat/__tests__/ChatView.spec.tsx +++ b/client/src/components/Chat/__tests__/ChatView.spec.tsx @@ -26,6 +26,7 @@ jest.mock('~/hooks/Chat/target', () => ({ })); jest.mock('~/data-provider', () => ({ + useCachedMessages: () => ({ data: null }), useProjectQuery: () => ({ data: undefined }), })); diff --git a/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx b/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx index 36aeae5c27..79d8131293 100644 --- a/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx +++ b/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx @@ -78,6 +78,7 @@ jest.mock('~/hooks/Chat/target', () => ({ })); jest.mock('~/data-provider', () => ({ + useCachedMessages: () => ({ data: null }), useProjectQuery: () => ({ data: undefined }), })); diff --git a/client/src/components/ui/AutoHeight.tsx b/client/src/components/ui/AutoHeight.tsx index 9d378628b1..2ecfa8161f 100644 --- a/client/src/components/ui/AutoHeight.tsx +++ b/client/src/components/ui/AutoHeight.tsx @@ -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(null); - const [height, setHeight] = useState(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 ( -
-
- {children} -
-
- ); +export default function AutoHeight(props: ComponentProps) { + return ; } diff --git a/client/src/components/ui/__tests__/AutoHeight.spec.tsx b/client/src/components/ui/__tests__/AutoHeight.spec.tsx index be3574c817..2bb0b4db20 100644 --- a/client/src/components/ui/__tests__/AutoHeight.spec.tsx +++ b/client/src/components/ui/__tests__/AutoHeight.spec.tsx @@ -7,6 +7,17 @@ describe('AutoHeight', () => { jest.restoreAllMocks(); }); + it('keeps caller class overrides when the shared component merges classes', () => { + render( + +

{'Override layout'}

+
, + ); + 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') diff --git a/client/src/utils/textarea.ts b/client/src/utils/textarea.ts index 882cfebb3d..2cb31cc4f4 100644 --- a/client/src/utils/textarea.ts +++ b/client/src/utils/textarea.ts @@ -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; } diff --git a/client/src/utils/viewport.ts b/client/src/utils/viewport.ts index 3af9e7ef8d..57625a70e7 100644 --- a/client/src/utils/viewport.ts +++ b/client/src/utils/viewport.ts @@ -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'; diff --git a/e2e/specs/mock/scenarios/ask-keyboard.spec.ts b/e2e/specs/mock/scenarios/ask-keyboard.spec.ts index ed3499018b..98f6601c86 100644 --- a/e2e/specs/mock/scenarios/ask-keyboard.spec.ts +++ b/e2e/specs/mock/scenarios/ask-keyboard.spec.ts @@ -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); + } + }); }); diff --git a/eslint-suppressions.json b/eslint-suppressions.json index ee91e5a581..de15eee56b 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -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 diff --git a/packages/chat/src/components.ts b/packages/chat/src/components.ts index d065a55a25..45f47c8a0e 100644 --- a/packages/chat/src/components.ts +++ b/packages/chat/src/components.ts @@ -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'; diff --git a/packages/chat/src/components/parts/AutoHeight.tsx b/packages/chat/src/components/parts/AutoHeight.tsx new file mode 100644 index 0000000000..28c7318277 --- /dev/null +++ b/packages/chat/src/components/parts/AutoHeight.tsx @@ -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(null); + const [height, setHeight] = useState(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 ( +
+
+ {children} +
+
+ ); +} diff --git a/packages/chat/src/components/parts/PendingSkillCall.tsx b/packages/chat/src/components/parts/PendingSkillCall.tsx index d7b7542968..78bcf729e4 100644 --- a/packages/chat/src/components/parts/PendingSkillCall.tsx +++ b/packages/chat/src/components/parts/PendingSkillCall.tsx @@ -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 (
-
-
+
+
{/** The real `SkillCall` replaces this row in place once the skill * finalizes; sharing its glyph slot keeps that swap still. */} diff --git a/client/src/components/Chat/Messages/Content/AskUserQuestionCall.tsx b/packages/chat/src/components/parts/ask/Call.tsx similarity index 69% rename from client/src/components/Chat/Messages/Content/AskUserQuestionCall.tsx rename to packages/chat/src/components/parts/ask/Call.tsx index e2b61ca08c..e1c262bdad 100644 --- a/client/src/components/Chat/Messages/Content/AskUserQuestionCall.tsx +++ b/packages/chat/src/components/parts/ask/Call.tsx @@ -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 ( <>
-
{/* 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 && ( {`${statusLabel}. ${localize('com_ui_question_failed_description')}`} )} -
+
void; +}) { + const localize = useLocalize(); + const rootRef = useRef(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 ( +
+
+ +
+
+ ); +} + +/** + * 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 diff --git a/client/src/components/Chat/Messages/Content/AskUserQuestionProgress.tsx b/packages/chat/src/components/parts/ask/Progress.tsx similarity index 76% rename from client/src/components/Chat/Messages/Content/AskUserQuestionProgress.tsx rename to packages/chat/src/components/parts/ask/Progress.tsx index 22be19b4e6..d87fee082f 100644 --- a/client/src/components/Chat/Messages/Content/AskUserQuestionProgress.tsx +++ b/packages/chat/src/components/parts/ask/Progress.tsx @@ -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 | 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') { diff --git a/packages/chat/src/components/parts/ask/Question.tsx b/packages/chat/src/components/parts/ask/Question.tsx new file mode 100644 index 0000000000..a56f4708c0 --- /dev/null +++ b/packages/chat/src/components/parts/ask/Question.tsx @@ -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(); + +/** 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 = ( + + ); + return reserved ? {card} : card; + } + return ( + + ); +} + +/** 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 ( +
{ + if (node == null) { + return; + } + if (reserved) { + node.setAttribute('inert', ''); + return; + } + node.removeAttribute('inert'); + }} + > + +
+ ); +} + +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([]); + 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(null); + const optionRefs = useRef<(HTMLButtonElement | null)[]>([]); + const answerRef = useRef(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) => { + 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) => { + 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 = ( +
+
+
+

+ {question.question} +

+ {question.description != null && question.description.length > 0 && ( +

+ {question.description} +

+ )} +
+ {collapsed && isLivePause && ( + +
+ + {choices.length > 0 && ( + (multiSelect ? toggleIndex(index) : submitSingle(index))} + optionRefs={optionRefs} + /> + )} + + { + 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')} + /> + +
+ + {(status === 'expired' || status === 'error') && ( + + + )} + +
+
+ ); + + if (!showPlaceholder) { + return card; + } + + return {card}; +} + +/** Popover has the question: the reserved card sits hidden underneath the + * same compact in-progress row the other tools use, so the turn still + * shows the call is running. */ +function AskingPlaceholder({ children }: { children: React.ReactNode }) { + const localize = useLocalize(); + return ( +
+ {children} +
+
+
+ ); +} diff --git a/packages/chat/src/components/parts/ask/Questions.tsx b/packages/chat/src/components/parts/ask/Questions.tsx new file mode 100644 index 0000000000..d7e9e9f6c1 --- /dev/null +++ b/packages/chat/src/components/parts/ask/Questions.tsx @@ -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(null); + const stepRef = useRef(null); + const answerRef = useRef(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 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('button[data-selected]:not(:disabled)') ?? + (firstOption ? step.querySelector('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) => { + 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 ( +
+ {/* 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. */} + + {stepped && ( +

+ {localize('com_ui_question_step', { 0: activeIndex + 1, 1: total })} +

+ )} +
+ {/* Bounded so a long prompt scrolls rather than pushing the composer + popover past the top of the viewport. */} +
+ {question.header != null && question.header !== '' && ( +

{question.header}

+ )} +

+ {question.question} +

+ {question.description != null && question.description.length > 0 && ( +

{question.description}

+ )} +
+ {(stepped || headerAction != null) && ( +
+ {stepped && ( +
+ {questions.map((item, index) => { + const isAnswered = Object.prototype.hasOwnProperty.call(form.answers, item.id); + const isActive = index === activeIndex; + return ( + + ); + })} +
+ )} + {headerAction} +
+ )} +
+ {/* `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. */} +
+
+ {choices.length > 0 && ( + 0} + onActivate={(optionIndex) => + handleSelectOption(question, choices[optionIndex].value) + } + className="flex flex-col" + /> + )} + 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')}`} + /> +
+
+
+ {(form.status === 'error' || form.status === 'expired') && ( +
+
+ )} + {showRemaining && ( + + )} +
+
+
+ +
+ {stepped && ( + + )} + {isLastStep ? ( + + ) : ( + + )} +
+
+
+ ); +} diff --git a/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionCall.test.tsx b/packages/chat/src/components/parts/ask/__tests__/Call.spec.tsx similarity index 83% rename from client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionCall.test.tsx rename to packages/chat/src/components/parts/ask/__tests__/Call.spec.tsx index 40b328be69..ab3f503b79 100644 --- a/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionCall.test.tsx +++ b/packages/chat/src/components/parts/ask/__tests__/Call.spec.tsx @@ -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 = { com_ui_asked: 'Asked', @@ -18,7 +20,8 @@ const translations: Record = { com_ui_asking_n_questions: 'Asking {{0}} questions', }; -jest.mock('~/hooks', () => ({ +jest.mock('@librechat/client', () => ({ + ...jest.requireActual('@librechat/client'), useLocalize: () => (key: string, values?: Record) => { 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 | undefined) => { - if (typeof args === 'string') { - return JSON.parse(args) as Record; - } - return args ?? null; - }, - parseAskUserQuestionsArgs: (args: string | Record | 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('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('react'); - return createElement('div', null, children); - }, -})); /** Settled records mount collapsed, exactly like every other tool card. */ const renderCall = (ui: React.ReactElement, autoExpand = false) => - render( - set(store.autoExpandTools, autoExpand)}> - {ui} - , - ); + render({ui}); 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(); - 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 = ; const tree = (tick: number) => ( - + true }}> {call} - + ); 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'); diff --git a/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionProgress.test.tsx b/packages/chat/src/components/parts/ask/__tests__/Progress.spec.tsx similarity index 65% rename from client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionProgress.test.tsx rename to packages/chat/src/components/parts/ask/__tests__/Progress.spec.tsx index cf93a32714..55c223fac2 100644 --- a/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionProgress.test.tsx +++ b/packages/chat/src/components/parts/ask/__tests__/Progress.spec.tsx @@ -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 = { 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) => key === 'com_ui_tool_preparing' ? `Preparing ${values?.[0]}` : (translations[key] ?? key), })); -jest.mock('~/Providers/ChatContext', () => { - const { createContext } = jest.requireActual('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( + + {ui} + , + ); describe('AskUserQuestionProgress', () => { beforeEach(() => { mockLivePauses = { ids: [], hasUnattributed: false }; }); + test('updates live pause data without changing consumer hooks and defaults to visible', () => { + const card = ; + const hosted = (liveAskPauses?: LiveAskPauses | null) => ( + + {card} + + ); + 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( { }); test('decodes JSON escapes in the streaming question', () => { - render( + renderProgress( , ); @@ -55,7 +75,7 @@ describe('AskUserQuestionProgress', () => { }); test('streams the first question from partial batched args', () => { - render( + renderProgress( { }); test('reads the first question from settled batched args', () => { - render( + renderProgress( { }); test('renders a skeleton line before any question text streams', () => { - render(); + renderProgress(); 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( , ); @@ -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( , ); @@ -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( , ); @@ -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( , ); @@ -135,15 +155,20 @@ describe('question preparation transitions', () => { ); - const { rerender } = render(frame('{"question":"Which environment')); + const hosted = (node: React.ReactElement) => ( + + {node} + + ); + 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(); }); }); diff --git a/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestion.test.tsx b/packages/chat/src/components/parts/ask/__tests__/Question.spec.tsx similarity index 83% rename from client/src/components/Chat/Messages/Content/__tests__/AskUserQuestion.test.tsx rename to packages/chat/src/components/parts/ask/__tests__/Question.spec.tsx index c8986a3d2f..fe93836d82 100644 --- a/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestion.test.tsx +++ b/packages/chat/src/components/parts/ask/__tests__/Question.spec.tsx @@ -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 = { 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(); -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(); let submitOverride: ShortcutBinding | undefined; @@ -76,22 +63,32 @@ const tree = ( enterToSend = true, actionId = 'ask-1', ) => ( - - + drafts.get(id) ?? ''} + setAskAnswerDraft={(id, answer) => { + if (answer.length === 0) { + drafts.delete(id); + return; + } + drafts.set(id, answer); }} - > - - - - - + /> + ); 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; diff --git a/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestions.test.tsx b/packages/chat/src/components/parts/ask/__tests__/Questions.spec.tsx similarity index 89% rename from client/src/components/Chat/Messages/Content/__tests__/AskUserQuestions.test.tsx rename to packages/chat/src/components/parts/ask/__tests__/Questions.spec.tsx index 9b5623c4cc..75e7794f7b 100644 --- a/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestions.test.tsx +++ b/packages/chat/src/components/parts/ask/__tests__/Questions.spec.tsx @@ -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) => { const labels: Record = { 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( - - - , + , ); 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( - -
- -