diff --git a/client/src/components/Chat/Messages/Content/ProgressText.tsx b/client/src/components/Chat/Messages/Content/ProgressText.tsx index 570c2c1073..65c8b154dd 100644 --- a/client/src/components/Chat/Messages/Content/ProgressText.tsx +++ b/client/src/components/Chat/Messages/Content/ProgressText.tsx @@ -1,283 +1,4 @@ -import { useCallback, useRef } from 'react'; -import { useStore } from 'jotai'; -import { ChevronDown } from 'lucide-react'; -import { useTranslation } from 'react-i18next'; -import * as Popover from '@radix-ui/react-popover'; -import { phaseReceipts } from '@librechat/chat/react'; -import { isReportableRunStepDuration } from 'librechat-data-provider'; -import { Button, Shimmer, disclosureChevronVariants } from '@librechat/client'; -import { - ElapsedTimer, - CancelledIcon, - ROW_GLYPH_SLOT, - 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'; +import { ProgressText } from '@librechat/chat/components'; -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; - -const Wrapper = ({ - popover, - rootRef, - children, -}: { - popover: boolean; - rootRef: React.RefObject; - children: React.ReactNode; -}) => { - if (popover) { - return ( -
- -
{children}
-
-
- ); - } - - return ( -
-
{children}
-
- ); -}; - -export default function ProgressText({ - phase, - onClick, - inProgressText, - finishedText, - authText, - icon: iconProp, - subtitle, - durationMs, - toolPreparationDurationMs, - toolExecutionDurationMs, - phaseStartAt, - phaseStepId, - hasInput = true, - popover = false, - isExpanded = false, - verdict, - timer, -}: { - /** - * The card's settled state, resolved once by the caller via - * `resolveToolCallPhase`. Replaces the former `error`+ `errorSuffix` - * pair, which encoded three terminal states in two booleans — `error` - * meant cancelled, a present `errorSuffix` meant failed, and every - * consumer had to reconstruct the distinction. That shape is what let a - * duration render beside "failed" and a live region announce "completed" - * over a visibly failed card. - */ - phase: ToolCallPhase; - onClick?: () => void; - inProgressText: string; - finishedText: string; - authText?: string; - icon?: React.ReactNode; - subtitle?: string; - /** Total run-step lifetime, not necessarily tool execution. */ - durationMs?: number; - toolPreparationDurationMs?: number; - toolExecutionDurationMs?: number; - phaseStartAt?: number; - phaseStepId?: string; - hasInput?: boolean; - popover?: boolean; - isExpanded?: boolean; - /** Why a failed card failed ("exit code 2"), shown in place of the generic failure - * suffix. Plain text inside the button, so it is part of its name. */ - verdict?: string; - timer?: React.ReactNode; -}) { - const localize = useLocalize(); - /** For locale-aware decimal formatting of the sub-10s duration value. */ - const { i18n } = useTranslation(); - const preparationText = useToolPreparation(); - const isRunning = phase === 'running'; - const receiptStore = useStore(); - /** Stream receipts are recorded before the matching phase reaches the message renderer. */ - const receivedAt = - phaseStepId != null && phaseStartAt != null - ? receiptStore.get(phaseReceipts).get(phaseStepId)?.get(phaseStartAt) - : undefined; - /** A server-authored phase stamp is an identity, not a browser clock origin. - * On reconnect we can only time from local receipt, never infer cross-host skew. */ - const phaseTimer = useRef<{ stamp?: number; receivedAt: number } | null>(null); - if (!isRunning || phaseStartAt == null) { - phaseTimer.current = null; - } else if (phaseTimer.current?.stamp !== phaseStartAt) { - phaseTimer.current = { stamp: phaseStartAt, receivedAt: receivedAt ?? Date.now() }; - } - const localPhaseStart = receivedAt ?? phaseTimer.current?.receivedAt; - const rootRef = useRef(null); - /** A header above asked for its failures. This control is the disclosure - * every card renders, so answering here reaches a failed bash, code, - * memory or file card the same as a generic one: open through the card's - * own toggle, and, for the one row the request lets take focus, land the - * reader on the labeled button rather than on a wrapper. */ - const revealFailure = useCallback( - (claimFocus: () => boolean) => { - if (!isExpanded) { - 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 }); - }, - [isExpanded, onClick], - ); - useFailedReveal(phase === 'failed' && hasInput, revealFailure); - - /** Every branch below reads `phase`, so the label, the icon, the shimmer, - * the failure suffix and the duration cannot disagree about what state - * the card is in. */ - const text = isRunning ? (authText ?? preparationText ?? inProgressText) : finishedText; - const icon = phase === 'cancelled' ? : (iconProp ?? null); - const showShimmer = isRunning; - const errorSuffix = phase === 'failed' ? localize('com_ui_tool_failed') : undefined; - /** - * Shown only on a settled, successful card. While the step is still running - * the number would be stale the instant it rendered, and on a cancelled or - * failed card "how long it took" is not the fact the reader needs — that - * slot already carries the cancelled icon or the failure suffix. - */ - const measured = toolPreparationDurationMs != null || toolExecutionDurationMs != null; - /** The formatter rounds to tenths below ten seconds. Shorter than 50 ms reads as 0.0s. */ - const showToolCallTime = - toolExecutionDurationMs != null && - Number.isFinite(toolExecutionDurationMs) && - toolExecutionDurationMs >= 50; - /** Pinned beside the chevron: "2.4s (prepared in 0.3s)". */ - const durationParts = - phase !== 'completed' - ? [] - : [ - ...(showToolCallTime - ? [ - { - label: localize('com_ui_tool_call_time'), - phrase: undefined, - duration: getRunStepDurationLabels(toolExecutionDurationMs, i18n.language), - }, - ] - : []), - ...(isReportableRunStepDuration(toolPreparationDurationMs) - ? [ - { - label: localize('com_ui_tool_preparation_time'), - phrase: 'com_ui_duration_prepared_in' as const, - duration: getRunStepDurationLabels(toolPreparationDurationMs, i18n.language), - }, - ] - : []), - ...(!measured && isReportableRunStepDuration(durationMs) - ? [ - { - label: '', - phrase: undefined, - duration: getRunStepDurationLabels(durationMs, i18n.language), - }, - ] - : []), - ]; - - return ( - - - - ); -} +/** App import path for the shared tool-row header. Cards keep importing it here. */ +export default ProgressText; diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json index b9ef380af8..ece65bff6a 100644 --- a/client/src/locales/en/translation.json +++ b/client/src/locales/en/translation.json @@ -1903,7 +1903,6 @@ "com_ui_tool_call_time": "Tool call", "com_ui_tool_content_error": "Couldn't load the full tool call.", "com_ui_tool_content_loading": "Loading the full tool call…", - "com_ui_tool_total_time": "Total elapsed", "com_ui_during_run_actions": "More send options", "com_ui_edit": "Edit", "com_ui_edit_editing_image": "Editing image", diff --git a/packages/chat/src/components.ts b/packages/chat/src/components.ts index 2955bb7448..81a45a8340 100644 --- a/packages/chat/src/components.ts +++ b/packages/chat/src/components.ts @@ -172,6 +172,8 @@ export { default as PendingSkillCall } from './components/parts/PendingSkillCall export { default as ToolCallLimitNotice } from './components/parts/ToolCallLimitNotice'; export { default as ToolCall } from './components/parts/ToolCall'; export type { ToolCallProps } from './components/parts/ToolCall'; +export { default as ProgressText } from './components/parts/ProgressText'; +export type { ProgressTextProps } from './components/parts/ProgressText'; export { default as ResumeAuthorHeader } from './components/parts/ResumeAuthorHeader'; export { ToolAuthWarning, ToolAuthWarningContext } from './components/parts/auth'; export { ToolPreparation, useToolPreparation } from './components/parts/preparation'; diff --git a/packages/chat/src/components/parts/ProgressText.tsx b/packages/chat/src/components/parts/ProgressText.tsx new file mode 100644 index 0000000000..8a6a700711 --- /dev/null +++ b/packages/chat/src/components/parts/ProgressText.tsx @@ -0,0 +1,299 @@ +import { useCallback, useRef } from 'react'; +import { useStore } from 'jotai'; +import { ChevronDown } from 'lucide-react'; +import { isReportableRunStepDuration } from 'librechat-data-provider'; +import { + cn, + Button, + Shimmer, + useLanguage, + useLocalize, + PopoverTrigger, + disclosureChevronVariants, +} from '@librechat/client'; +import type { ReactElement, ReactNode, RefObject } from 'react'; +import type { ToolCallPhase } from '../../core/parts/toolCallPhase'; +import { PROGRESS_TEXT_CONTENT, PROGRESS_TEXT_WRAPPER, ROW_GLYPH_SLOT } from './rows'; +import { getRunStepDurationLabels } from '../messages/duration'; +import { phaseReceipts } from '../../react/stream/receipt'; +import { ElapsedTimer } from '../messages/Elapsed'; +import { useToolPreparation } from './preparation'; +import CancelledIcon from './CancelledIcon'; +import { useFailedReveal } from './reveal'; + +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; + +const Wrapper = ({ + popover, + rootRef, + children, +}: { + popover: boolean; + rootRef: RefObject; + children: ReactNode; +}): ReactElement => { + if (popover) { + return ( +
+ +
{children}
+
+
+ ); + } + + return ( +
+
{children}
+
+ ); +}; + +export type ProgressTextProps = { + /** + * The card's settled state, resolved once by the caller via + * `resolveToolCallPhase`. Replaces the former `error`+ `errorSuffix` + * pair, which encoded three terminal states in two booleans: `error` + * meant cancelled, a present `errorSuffix` meant failed, and every + * consumer had to reconstruct the distinction. That shape is what let a + * duration render beside "failed" and a live region announce "completed" + * over a visibly failed card. + */ + phase: ToolCallPhase; + onClick?: () => void; + inProgressText: string; + finishedText: string; + authText?: string; + icon?: ReactNode; + /** + * Secondary line beside the label. An empty string is no subtitle, so a card + * with nothing to say lays out the same as one that passes none. + */ + subtitle?: string; + /** + * Counts an empty `subtitle` as present: the label stops shrinking and the + * empty line holds its place in the row, as the settled question header + * draws a blank question. + */ + keepEmptySubtitle?: boolean; + /** Total run-step lifetime, not necessarily tool execution. */ + durationMs?: number; + toolPreparationDurationMs?: number; + toolExecutionDurationMs?: number; + phaseStartAt?: number; + phaseStepId?: string; + hasInput?: boolean; + popover?: boolean; + isExpanded?: boolean; + /** Why a failed card failed ("exit code 2"), shown in place of the generic failure + * suffix. Plain text inside the button, so it is part of its name. */ + verdict?: string; + timer?: ReactNode; +}; + +export default function ProgressText({ + phase, + onClick, + inProgressText, + finishedText, + authText, + icon: iconProp, + subtitle, + keepEmptySubtitle = false, + durationMs, + toolPreparationDurationMs, + toolExecutionDurationMs, + phaseStartAt, + phaseStepId, + hasInput = true, + popover = false, + isExpanded = false, + verdict, + timer, +}: ProgressTextProps): ReactElement { + const localize = useLocalize(); + /** Locale of the active translation, for the sub-10s duration decimal. */ + const language = useLanguage(); + const preparationText = useToolPreparation(); + const isRunning = phase === 'running'; + const receiptStore = useStore(); + /** Stream receipts are recorded before the matching phase reaches the message renderer. */ + const receivedAt = + phaseStepId != null && phaseStartAt != null + ? receiptStore.get(phaseReceipts).get(phaseStepId)?.get(phaseStartAt) + : undefined; + /** A server-authored phase stamp is an identity, not a browser clock origin. + * On reconnect we can only time from local receipt, never infer cross-host skew. */ + const phaseTimer = useRef<{ stamp?: number; receivedAt: number } | null>(null); + if (!isRunning || phaseStartAt == null) { + phaseTimer.current = null; + } else if (phaseTimer.current?.stamp !== phaseStartAt) { + phaseTimer.current = { stamp: phaseStartAt, receivedAt: receivedAt ?? Date.now() }; + } + const localPhaseStart = receivedAt ?? phaseTimer.current?.receivedAt; + const rootRef = useRef(null); + /** A header above asked for its failures. This control is the disclosure + * every card renders, so answering here reaches a failed bash, code, + * memory or file card the same as a generic one: open through the card's + * own toggle, and, for the one row the request lets take focus, land the + * reader on the labeled button rather than on a wrapper. */ + const revealFailure = useCallback( + (claimFocus: () => boolean) => { + if (!isExpanded) { + 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 }); + }, + [isExpanded, onClick], + ); + useFailedReveal(phase === 'failed' && hasInput, revealFailure); + + /** Every branch below reads `phase`, so the label, the icon, the shimmer, + * the failure suffix and the duration cannot disagree about what state + * the card is in. */ + const text = isRunning ? (authText ?? preparationText ?? inProgressText) : finishedText; + const icon = phase === 'cancelled' ? : (iconProp ?? null); + const showShimmer = isRunning; + const errorSuffix = phase === 'failed' ? localize('com_ui_tool_failed') : undefined; + const hasSubtitle = keepEmptySubtitle ? subtitle != null : Boolean(subtitle); + /** + * Shown only on a settled, successful card. While the step is still running + * the number would be stale the instant it rendered, and on a cancelled or + * failed card "how long it took" is not the fact the reader needs: that + * slot already carries the cancelled icon or the failure suffix. + */ + const measured = toolPreparationDurationMs != null || toolExecutionDurationMs != null; + /** The formatter rounds to tenths below ten seconds. Shorter than 50 ms reads as 0.0s. */ + const showToolCallTime = + toolExecutionDurationMs != null && + Number.isFinite(toolExecutionDurationMs) && + toolExecutionDurationMs >= 50; + /** Pinned beside the chevron: "2.4s (prepared in 0.3s)". */ + const durationParts = + phase !== 'completed' + ? [] + : [ + ...(showToolCallTime + ? [ + { + label: localize('com_ui_tool_call_time'), + phrase: undefined, + duration: getRunStepDurationLabels(toolExecutionDurationMs, language), + }, + ] + : []), + ...(isReportableRunStepDuration(toolPreparationDurationMs) + ? [ + { + label: localize('com_ui_tool_preparation_time'), + phrase: 'com_ui_duration_prepared_in' as const, + duration: getRunStepDurationLabels(toolPreparationDurationMs, language), + }, + ] + : []), + ...(!measured && isReportableRunStepDuration(durationMs) + ? [ + { + label: '', + phrase: undefined, + duration: getRunStepDurationLabels(durationMs, language), + }, + ] + : []), + ]; + + return ( + + + + ); +} diff --git a/client/src/components/Chat/Messages/Content/__tests__/ProgressText.test.tsx b/packages/chat/src/components/parts/__tests__/ProgressText.spec.tsx similarity index 85% rename from client/src/components/Chat/Messages/Content/__tests__/ProgressText.test.tsx rename to packages/chat/src/components/parts/__tests__/ProgressText.spec.tsx index 1ed6eaa1b5..c75c81518d 100644 --- a/client/src/components/Chat/Messages/Content/__tests__/ProgressText.test.tsx +++ b/packages/chat/src/components/parts/__tests__/ProgressText.spec.tsx @@ -1,39 +1,31 @@ -import React from 'react'; +/** + * @jest-environment jsdom + */ +import i18next from 'i18next'; import { createStore, Provider } from 'jotai'; -import { phaseReceipts } from '@librechat/chat/react'; -import { FailedRevealContext } from '@librechat/chat/components'; import { fireEvent, render, screen } from '@testing-library/react'; +import type { ComponentProps } from 'react'; +import { phaseReceipts } from '../../../react/stream/receipt'; +import { initEnglish } from '../../../__fixtures__/i18n'; +import { FailedRevealContext } from '../reveal'; import ProgressText from '../ProgressText'; -function mockLocalize(key: string, values?: Record): string { - const translations: Record = { - com_ui_duration_seconds: `${values?.[0]}s`, - com_ui_tool_preparation_time: 'Preparation', - com_ui_tool_call_time: 'Tool call', - com_ui_duration_prepared_in: `(prepared in ${values?.[0]})`, - com_ui_tool_total_time: 'Total elapsed', - com_ui_duration_minutes: `${values?.[0]}m ${values?.[1]}s`, - com_ui_duration_announced_seconds: `took ${values?.value} ${values?.count === 1 ? 'second' : 'seconds'}`, - com_ui_duration_announced_minutes: `took ${values?.value} ${values?.count === 1 ? 'minute' : 'minutes'}`, - }; - return translations[key] ?? key; -} +beforeAll(async () => { + await initEnglish(); + i18next.addResourceBundle( + 'de', + 'translation', + i18next.getResourceBundle('en', 'translation'), + true, + true, + ); +}); -jest.mock('~/hooks', () => ({ useLocalize: () => mockLocalize })); - -jest.mock('@librechat/client', () => ({ - ...jest.requireActual('@librechat/client'), - useLocalize: () => mockLocalize, -})); - -jest.mock('react-i18next', () => ({ - useTranslation: () => ({ i18n: { language: 'en' } }), -})); - -jest.mock('@librechat/chat/components', () => ({ - ...jest.requireActual('@librechat/chat/components'), - CancelledIcon: () => , -})); +afterEach(async () => { + if (i18next.language !== 'en') { + await i18next.changeLanguage('en'); + } +}); const defaults = { phase: 'completed' as const, @@ -42,7 +34,7 @@ const defaults = { phaseStepId: 'timer-step', }; -const renderProgressText = (props: Partial> = {}) => +const renderProgressText = (props: Partial> = {}) => render(); describe('ProgressText duration', () => { @@ -89,7 +81,7 @@ describe('ProgressText duration', () => { }); expect(screen.getByText('(prepared in 4m 2s)')).toBeInTheDocument(); expect(screen.getByText('5.7s')).toBeInTheDocument(); - expect(screen.queryByText(/Total elapsed/)).not.toBeInTheDocument(); + expect(screen.queryByText('4m 8s')).not.toBeInTheDocument(); }); it('shows a few-hundred-millisecond tool call beside minutes of preparation', () => { @@ -100,7 +92,7 @@ describe('ProgressText duration', () => { }); expect(screen.getByText('(prepared in 4m 7s)')).toBeInTheDocument(); expect(screen.getByText('0.3s')).toBeInTheDocument(); - expect(screen.queryByText(/Total elapsed/)).not.toBeInTheDocument(); + expect(screen.queryByText('4m 7s')).not.toBeInTheDocument(); }); it('does not show a measured call too short to format as a nonzero interval', () => { @@ -113,6 +105,12 @@ describe('ProgressText duration', () => { expect(screen.getByText('1m 5s')).toBeInTheDocument(); }); + it('formats a short duration with the active locale decimal mark', async () => { + await i18next.changeLanguage('de'); + renderProgressText({ durationMs: 1400 }); + expect(screen.getByText('1,4s')).toBeInTheDocument(); + }); + /** * The number would be stale the moment it rendered, and the label beside it * is still the in-progress one. @@ -229,12 +227,33 @@ describe('ProgressText subtitle', () => { renderProgressText(); expect(screen.getByText('Completed foo')).not.toHaveClass('shrink-0'); }); + + it('treats an empty subtitle as no subtitle', () => { + renderProgressText({ subtitle: '' }); + const label = screen.getByText('Completed foo'); + expect(label).not.toHaveClass('shrink-0'); + expect(label.nextElementSibling).toBeNull(); + }); + + it('keeps an empty subtitle when the caller keeps the slot', () => { + renderProgressText({ subtitle: '', keepEmptySubtitle: true }); + const label = screen.getByText('Completed foo'); + expect(label).toHaveClass('shrink-0'); + expect(label.nextElementSibling).toBeEmptyDOMElement(); + }); + + it('adds no subtitle slot without a subtitle, even when the caller keeps empty ones', () => { + renderProgressText({ keepEmptySubtitle: true }); + const label = screen.getByText('Completed foo'); + expect(label).not.toHaveClass('shrink-0'); + expect(label.nextElementSibling).toBeNull(); + }); }); describe('ProgressText failure', () => { it('keeps the verdict word on a failed row, open or not', () => { renderProgressText({ phase: 'failed', hasInput: true, isExpanded: true }); - expect(screen.getByText('· com_ui_tool_failed')).toBeInTheDocument(); + expect(screen.getByText('· failed')).toBeInTheDocument(); }); it('does not add a failure stripe to a tool row', () => { @@ -319,7 +338,7 @@ describe('ProgressText verdict', () => { it('states the reason in place of the generic failure word', () => { renderProgressText({ phase: 'failed', verdict: 'timed out' }); - expect(screen.queryByText(/com_ui_tool_failed/)).not.toBeInTheDocument(); + expect(screen.queryByText('· failed')).not.toBeInTheDocument(); }); it('keeps the failure verdict but hides preparation, call, total, and live timers', () => { @@ -332,7 +351,7 @@ describe('ProgressText verdict', () => { phaseStartAt: 1_000, }); expect(screen.getByRole('button')).toHaveTextContent('exit code 2'); - expect(screen.queryByText(/Preparation|Tool call|Total elapsed|took/)).toBeNull(); + expect(screen.queryByText(/Preparation|Tool call|took/)).toBeNull(); expect(screen.queryByTestId('stream-elapsed')).toBeNull(); }); diff --git a/packages/chat/src/components/parts/ask/Call.tsx b/packages/chat/src/components/parts/ask/Call.tsx index e1c262bdad..93f8e5f86c 100644 --- a/packages/chat/src/components/parts/ask/Call.tsx +++ b/packages/chat/src/components/parts/ask/Call.tsx @@ -1,24 +1,18 @@ -import { useCallback, useRef } from 'react'; -import { ChevronDown, MessageCircleQuestion, TriangleAlert } from 'lucide-react'; -import { cn, Button, disclosureChevronVariants, useLocalize } from '@librechat/client'; +import { useCallback } from 'react'; +import { cn, useLocalize } from '@librechat/client'; +import { MessageCircleQuestion, TriangleAlert } from 'lucide-react'; import type { Agents, PartMetadata } from 'librechat-data-provider'; import type { CSSProperties, ReactNode } from 'react'; -import { - DISCLOSURE_COLLAPSE, - PROGRESS_TEXT_CONTENT, - PROGRESS_TEXT_WRAPPER, - ROW_GLYPH_SLOT, - TOOL_ROW_CLASSES, -} from '../rows'; import { getSubmittedAskAnswer, parseAskUserQuestionArgs, parseAskUserQuestionsArgs, } from '../../../core/parts/questions'; import { toolPanelSpacingClassName, useToolExpansion } from '../../../react/parts/disclosure'; +import { DISCLOSURE_COLLAPSE, TOOL_ROW_CLASSES } from '../rows'; import useExpandCollapse from '../useExpandCollapse'; import AskUserQuestionProgress from './Progress'; -import { useFailedReveal } from '../reveal'; +import ProgressText from '../ProgressText'; import EmptyText from '../../EmptyText'; import Container from '../Container'; @@ -146,12 +140,28 @@ export default function AskUserQuestionCall({ return ( <>
-
{/* A rejected call is the one state the reader did not ask for and @@ -222,101 +232,6 @@ export default function AskUserQuestionCall({ ); } -/** - * The settled row. Same disclosure, failure reveal, and line as the other tool - * cards: a failed call opens and takes focus when a parent fold asks. - */ -function AskCallHeader({ - failed, - expanded, - label, - subtitle, - onClick, -}: { - failed: boolean; - expanded: boolean; - label: string; - subtitle?: string; - onClick: () => void; -}) { - const localize = useLocalize(); - const rootRef = useRef(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` diff --git a/packages/chat/src/components/parts/ask/__tests__/Call.spec.tsx b/packages/chat/src/components/parts/ask/__tests__/Call.spec.tsx index ab3f503b79..c7bbaaa549 100644 --- a/packages/chat/src/components/parts/ask/__tests__/Call.spec.tsx +++ b/packages/chat/src/components/parts/ask/__tests__/Call.spec.tsx @@ -5,9 +5,12 @@ import React from 'react'; import { fireEvent, render, screen } from '@testing-library/react'; import type { MessagePartsHost } from '../../../../react/host'; import { emptyToolCallChrome, MessagePartsHostProvider } from '../../../../react/host'; +import { initEnglish } from '../../../../__fixtures__/i18n'; import { FailedRevealContext } from '../../reveal'; import AskUserQuestionCall from '../Call'; +beforeAll(initEnglish); + const translations: Record = { com_ui_asked: 'Asked', com_ui_asking: 'Asking', @@ -97,6 +100,58 @@ describe('AskUserQuestionCall', () => { }, ); + test('keeps the question glyph, subtitle shrink, and a settled header with no timer', () => { + renderCall(); + + const header = screen.getByRole('button'); + expect(header).toHaveClass('group/disclosure'); + expect(header).not.toBeDisabled(); + expect(header).toHaveAttribute('aria-expanded', 'false'); + expect(header.querySelector('.shimmer')).toBeNull(); + expect(screen.queryByTestId('stream-elapsed')).toBeNull(); + expect(header.querySelector('.fold-glyph svg')).toHaveClass('text-text-secondary'); + expect(header.querySelector('.font-medium')).toHaveClass('shrink-0', 'truncate'); + expect(header.querySelector('.font-normal')).toHaveTextContent( + 'How would you like me to get the data?', + ); + expect(header.querySelector('.font-normal')).toHaveClass('shrink', 'min-w-0', 'truncate'); + const icons = header.querySelectorAll('svg'); + expect(icons[icons.length - 1]).toHaveClass('transition-transform'); + }); + + test('keeps the subtitle slot for a blank question, as the settled header always drew it', () => { + renderCall(); + + const header = screen.getByRole('button'); + expect(header.querySelector('.font-medium')).toHaveClass('shrink-0'); + expect(header.querySelector('.font-normal')).toBeEmptyDOMElement(); + }); + + test('summarizes a batch by its count, so the header has no subtitle slot', () => { + const batch = JSON.stringify({ + questions: [ + { id: 'first', question: 'First?' }, + { id: 'second', question: 'Second?' }, + ], + }); + renderCall(); + + const header = screen.getByRole('button'); + expect(header).toHaveTextContent('Asked 2 questions'); + expect(header.querySelector('.font-medium')).not.toHaveClass('shrink-0'); + expect(header.querySelector('.font-normal')).toBeNull(); + }); + + test('keeps the warning glyph and failure suffix on a rejected question', () => { + renderCall(); + + const header = screen.getByRole('button'); + expect(header.querySelector('.fold-glyph svg')).toHaveClass('text-text-warning'); + expect(header).toHaveTextContent('com_ui_tool_failed'); + expect(header.querySelector('.shimmer')).toBeNull(); + expect(screen.queryByTestId('stream-elapsed')).toBeNull(); + }); + test('mounts collapsed and opens on click, like any other tool card', () => { renderCall();