⏳ refactor: Move ProgressText Into @librechat/chat (#18176)

- refactor: Move ProgressText Into The Chat Package
- fix: Keep ProgressText Behavior Unchanged After the Move
This commit is contained in:
Marco Beretta 2026-11-15 01:52:29 +01:00 • committed by GitHub
parent 6cacfb0007
commit b07a9f9e9f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 441 additions and 431 deletions

View file

@ -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<HTMLDivElement>;
children: React.ReactNode;
}) => {
if (popover) {
return (
<div className={wrapperClass} ref={rootRef}>
<Popover.Trigger asChild>
<div className={contentClass}>{children}</div>
</Popover.Trigger>
</div>
);
}
return (
<div className={wrapperClass} ref={rootRef}>
<div className={contentClass}>{children}</div>
</div>
);
};
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<HTMLDivElement>(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' ? <CancelledIcon /> : (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 (
<Wrapper popover={popover} rootRef={rootRef}>
<Button
type="button"
variant="disclosure"
className="group/disclosure"
disabled={!hasInput}
tabIndex={hasInput ? 0 : -1}
onClick={hasInput ? onClick : undefined}
aria-expanded={hasInput ? isExpanded : undefined}
>
{icon != null && (
<span className={ROW_GLYPH_SLOT} aria-hidden="true">
{icon}
</span>
)}
{/* The label names the card and stays whole; a subtitle can be
arbitrary authored text (a question, an error line), so it takes
ALL of the shrink and ellipsizes instead of pushing the line past
the message column. All, not most: a weighted share left the label
a fraction of a pixel short of its text, and that fraction is
enough for `truncate` to swap its last letters for an ellipsis.
The pair sits in its own shrinking box so the verdict, the
duration and the chevron after it never lose width: the box gives
up the subtitle first, and a label wider than the box truncates at
the box (`max-w-full`), not past the row. */}
<span className="flex min-w-0 items-center gap-2">
<Shimmer
active={showShimmer}
className={cn('max-w-full min-w-0 truncate font-medium', subtitle && 'shrink-0')}
>
{text}
</Shimmer>
{subtitle && (
<span className="text-text-secondary min-w-0 shrink truncate font-normal">
{subtitle}
</span>
)}
</span>
{/* A reason ("timed out", "exit code 2") already says the call failed,
so it replaces the generic word instead of following it. */}
{errorSuffix && (
<span className="text-status-error shrink-0 font-normal">· {verdict || errorSuffix}</span>
)}
{/* Pinned to the row's end so every row's time and chevron line up. */}
<span className="ms-auto flex shrink-0 items-center gap-2">
{timer}
{timer == null && isRunning && phaseStartAt != null && localPhaseStart != null && (
<ElapsedTimer start={localPhaseStart} />
)}
{durationParts.map(({ label, phrase, duration }) => (
<span
key={label}
className="text-text-secondary shrink-0 text-xs font-normal tabular-nums"
>
<span aria-hidden="true">
{phrase
? localize(phrase, { 0: localize(duration.key, duration.values) })
: localize(duration.key, duration.values)}
</span>
<span className="sr-only">
{label && `${label} `}
{localize(duration.announcedKey, duration.announcedValues)}
</span>
</span>
))}
{hasInput && (
<ChevronDown
className={cn(
disclosureChevronVariants({ expanded: isExpanded }),
'size-4 shrink-0 translate-y-[0.0625rem]',
)}
aria-hidden="true"
/>
)}
</span>
</Button>
</Wrapper>
);
}
/** App import path for the shared tool-row header. Cards keep importing it here. */
export default ProgressText;

View file

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

View file

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

View file

@ -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<HTMLDivElement>;
children: ReactNode;
}): ReactElement => {
if (popover) {
return (
<div className={wrapperClass} ref={rootRef}>
<PopoverTrigger asChild>
<div className={contentClass}>{children}</div>
</PopoverTrigger>
</div>
);
}
return (
<div className={wrapperClass} ref={rootRef}>
<div className={contentClass}>{children}</div>
</div>
);
};
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<HTMLDivElement>(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' ? <CancelledIcon /> : (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 (
<Wrapper popover={popover} rootRef={rootRef}>
<Button
type="button"
variant="disclosure"
className="group/disclosure"
disabled={!hasInput}
tabIndex={hasInput ? 0 : -1}
onClick={hasInput ? onClick : undefined}
aria-expanded={hasInput ? isExpanded : undefined}
>
{icon != null && (
<span className={ROW_GLYPH_SLOT} aria-hidden="true">
{icon}
</span>
)}
{/* The label names the card and stays whole; a subtitle can be
arbitrary authored text (a question, an error line), so it takes
ALL of the shrink and ellipsizes instead of pushing the line past
the message column. All, not most: a weighted share left the label
a fraction of a pixel short of its text, and that fraction is
enough for `truncate` to swap its last letters for an ellipsis.
The pair sits in its own shrinking box so the verdict, the
duration and the chevron after it never lose width: the box gives
up the subtitle first, and a label wider than the box truncates at
the box (`max-w-full`), not past the row. */}
<span className="flex min-w-0 items-center gap-2">
<Shimmer
active={showShimmer}
className={cn('max-w-full min-w-0 truncate font-medium', hasSubtitle && 'shrink-0')}
>
{text}
</Shimmer>
{hasSubtitle && (
<span className="text-text-secondary min-w-0 shrink truncate font-normal">
{subtitle}
</span>
)}
</span>
{/* A reason ("timed out", "exit code 2") already says the call failed,
so it replaces the generic word instead of following it. */}
{errorSuffix && (
<span className="text-status-error shrink-0 font-normal">· {verdict || errorSuffix}</span>
)}
{/* Pinned to the row's end so every row's time and chevron line up. */}
<span className="ms-auto flex shrink-0 items-center gap-2">
{timer}
{timer == null && isRunning && phaseStartAt != null && localPhaseStart != null && (
<ElapsedTimer start={localPhaseStart} />
)}
{durationParts.map(({ label, phrase, duration }) => (
<span
key={label}
className="text-text-secondary shrink-0 text-xs font-normal tabular-nums"
>
<span aria-hidden="true">
{phrase
? localize(phrase, { 0: localize(duration.key, duration.values) })
: localize(duration.key, duration.values)}
</span>
<span className="sr-only">
{label && `${label} `}
{localize(duration.announcedKey, duration.announcedValues)}
</span>
</span>
))}
{hasInput && (
<ChevronDown
className={cn(
disclosureChevronVariants({ expanded: isExpanded }),
'size-4 shrink-0 translate-y-[0.0625rem]',
)}
aria-hidden="true"
/>
)}
</span>
</Button>
</Wrapper>
);
}

View file

@ -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, string | number>): string {
const translations: Record<string, string> = {
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: () => <span data-testid="cancelled-icon" />,
}));
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<React.ComponentProps<typeof ProgressText>> = {}) =>
const renderProgressText = (props: Partial<ComponentProps<typeof ProgressText>> = {}) =>
render(<ProgressText {...defaults} {...props} />);
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();
});

View file

@ -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 (
<>
<div className={TOOL_ROW_CLASSES} data-testid="ask-user-question-call">
<AskCallHeader
failed={terminalFailure}
expanded={expanded}
label={statusLabel}
subtitle={summary}
{/* Settled row. Same disclosure, failure reveal, and line as the other
tool cards. `failed` keeps the warning glyph; `cancelled` would
replace it with the stop mark, which a rejected question does not use.
A blank question keeps its empty summary slot, as this header always did. */}
<ProgressText
phase={terminalFailure ? 'failed' : 'completed'}
onClick={toggleExpanded}
inProgressText={statusLabel}
finishedText={statusLabel}
subtitle={summary}
keepEmptySubtitle
icon={
terminalFailure ? (
<TriangleAlert className="text-text-warning size-4 shrink-0" aria-hidden="true" />
) : (
<MessageCircleQuestion
className="text-text-secondary size-4 shrink-0"
aria-hidden="true"
/>
)
}
isExpanded={expanded}
/>
</div>
{/* A rejected call is the one state the reader did not ask for and
@ -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<HTMLDivElement>(null);
const revealFailure = useCallback(
(claimFocus: () => boolean) => {
if (!expanded) {
onClick();
}
if (!claimFocus()) {
return;
}
const button = rootRef.current?.querySelector('button');
if (button == null) {
return;
}
if (typeof button.scrollIntoView === 'function') {
button.scrollIntoView({ block: 'nearest' });
}
button.focus({ preventScroll: true });
},
[expanded, onClick],
);
useFailedReveal(failed, revealFailure);
return (
<div className={PROGRESS_TEXT_WRAPPER} ref={rootRef}>
<div className={PROGRESS_TEXT_CONTENT}>
<Button
type="button"
variant="disclosure"
className="group/disclosure"
onClick={onClick}
aria-expanded={expanded}
>
<span className={ROW_GLYPH_SLOT} aria-hidden="true">
{failed ? (
<TriangleAlert className="text-text-warning size-4 shrink-0" aria-hidden="true" />
) : (
<MessageCircleQuestion
className="text-text-secondary size-4 shrink-0"
aria-hidden="true"
/>
)}
</span>
<span className="flex min-w-0 items-center gap-2">
<span
className={cn(
'max-w-full min-w-0 truncate font-medium',
subtitle != null && 'shrink-0',
)}
>
{label}
</span>
{subtitle != null && (
<span className="text-text-secondary min-w-0 shrink truncate font-normal">
{subtitle}
</span>
)}
</span>
{failed && (
<span className="text-status-error shrink-0 font-normal">
{'· '}
{localize('com_ui_tool_failed')}
</span>
)}
<span className="ms-auto flex shrink-0 items-center gap-2">
<ChevronDown
className={cn(
disclosureChevronVariants({ expanded }),
'size-4 shrink-0 translate-y-[0.0625rem]',
)}
aria-hidden="true"
/>
</span>
</Button>
</div>
</div>
);
}
/**
* One question and its answer. Every text slot here is authored, by the model
* or by the user, so line breaks are content, not whitespace: `pre-wrap`

View file

@ -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<string, string> = {
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(<AskUserQuestionCall args={args} output="public" />);
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(<AskUserQuestionCall args={JSON.stringify({ question: '' })} output="done" />);
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(<AskUserQuestionCall args={batch} output="" />);
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(<AskUserQuestionCall args={args} output="" failed />);
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(<AskUserQuestionCall args={args} output="public" />);