mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-20 06:51:59 +00:00
🧩 refactor: Move Tool Group Header Into Chat Package (#18181)
Some checks failed
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Backend Unit Tests / backend (push) Blocked by required conditions
Codegraph E2E Vote Gate / Gate (push) Waiting to run
Codegraph E2E Votes / vote (shard 1/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 10/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 2/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 3/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 4/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 5/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 6/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 7/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 8/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 9/10) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/chat (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Frontend Unit Tests / frontend (push) Blocked by required conditions
Playwright E2E Tests / Codegraph select (push) Waiting to run
Playwright E2E Tests / Shard timings (push) Waiting to run
Playwright E2E Tests / e2e () (push) Blocked by required conditions
Playwright E2E Tests / MCP list_changed (replica count 1) (push) Blocked by required conditions
Playwright E2E Tests / MCP list_changed (replica count 2) (push) Blocked by required conditions
Playwright E2E Tests / MCP Apps (browser and server) (push) Waiting to run
Playwright E2E Tests / e2e (push) Blocked by required conditions
Playwright Shard Timings / Record shard timings (push) Waiting to run
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (push) Has been cancelled
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (push) Has been cancelled
Some checks failed
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Backend Unit Tests / backend (push) Blocked by required conditions
Codegraph E2E Vote Gate / Gate (push) Waiting to run
Codegraph E2E Votes / vote (shard 1/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 10/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 2/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 3/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 4/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 5/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 6/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 7/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 8/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 9/10) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/chat (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Frontend Unit Tests / frontend (push) Blocked by required conditions
Playwright E2E Tests / Codegraph select (push) Waiting to run
Playwright E2E Tests / Shard timings (push) Waiting to run
Playwright E2E Tests / e2e () (push) Blocked by required conditions
Playwright E2E Tests / MCP list_changed (replica count 1) (push) Blocked by required conditions
Playwright E2E Tests / MCP list_changed (replica count 2) (push) Blocked by required conditions
Playwright E2E Tests / MCP Apps (browser and server) (push) Waiting to run
Playwright E2E Tests / e2e (push) Blocked by required conditions
Playwright Shard Timings / Record shard timings (push) Waiting to run
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (push) Has been cancelled
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (push) Has been cancelled
- refactor: Move Tool Group Header Into Chat Package
This commit is contained in:
parent
7531a8b2ab
commit
dd753672f7
8 changed files with 417 additions and 84 deletions
|
|
@ -1,6 +1,6 @@
|
|||
import { useState, useRef, useMemo, useEffect, useContext, useCallback } from 'react';
|
||||
import { ListChecks, MessageCircleQuestion, TriangleAlert, Users } from 'lucide-react';
|
||||
import { Tools, Constants, ContentTypes, isOpaqueReasoning } from 'librechat-data-provider';
|
||||
import { ChevronDown, ListChecks, MessageCircleQuestion, TriangleAlert, Users } from 'lucide-react';
|
||||
import {
|
||||
LoneGroupContext,
|
||||
SoleToolContext,
|
||||
|
|
@ -21,18 +21,17 @@ import {
|
|||
FOLD_RAIL_CLASSES,
|
||||
ROW_GLYPH_SLOT,
|
||||
FoldRail,
|
||||
RailGlyph,
|
||||
useFoldPath,
|
||||
useRailHover,
|
||||
revealFoldHeader,
|
||||
FoldHeaderContext,
|
||||
FailedRevealContext,
|
||||
FailedRevealPill,
|
||||
useFailedReveal,
|
||||
useFailedRevealTrigger,
|
||||
ToolAuthWarning,
|
||||
ToolAuthWarningContext,
|
||||
useExpandCollapse,
|
||||
ToolGroupHeader,
|
||||
} from '@librechat/chat/components';
|
||||
import type { TAttachment, TMessageContentParts } from 'librechat-data-provider';
|
||||
import type { ToolMeta } from '@librechat/chat';
|
||||
|
|
@ -43,7 +42,6 @@ import { cn, getPartKeyIndex, hasPendingAuthInPart } from '~/utils';
|
|||
import { useMCPIconMap, useMCPServerNames } from '~/hooks/MCP';
|
||||
import { AttachmentGroup, ReasoningCompact } from './Parts';
|
||||
import { MCPAppViews } from '~/components/MCPUIResource';
|
||||
import { PhaseLabel } from './ActivityPhaseGroup';
|
||||
import { HeaderActionSlotContext } from './slot';
|
||||
import { StackedToolIcons } from './ToolOutput';
|
||||
import { mapAttachments } from '~/utils/map';
|
||||
|
|
@ -648,24 +646,24 @@ export default function ToolCallGroup({
|
|||
return (
|
||||
<HeaderActionSlotContext.Provider value={flattenGroup ? parentActionSlot : actionSlot}>
|
||||
<div className="mt-1 mb-2" ref={rootRef} data-fold-root={flattenGroup ? undefined : ''}>
|
||||
<div
|
||||
className={cn(
|
||||
'relative w-full items-center gap-2 pe-6',
|
||||
flattenGroup ? 'hidden' : 'flex',
|
||||
)}
|
||||
<ToolGroupHeader
|
||||
label={groupLabel}
|
||||
detail={visibleGroupDetail}
|
||||
ariaLabel={groupAriaLabel}
|
||||
expanded={isExpanded}
|
||||
hidden={flattenGroup}
|
||||
ref={headerRef}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
'text-text-secondary hover:text-text-secondary focus-visible:ring-focus-subtle inline-flex h-auto min-w-0 flex-1 items-center justify-start gap-2 rounded-none bg-transparent p-0 py-1 hover:bg-transparent focus-visible:ring-2 focus-visible:ring-offset-0 focus-visible:outline-none',
|
||||
)}
|
||||
onClick={handleToggle}
|
||||
aria-expanded={isExpanded}
|
||||
aria-label={groupAriaLabel}
|
||||
>
|
||||
<RailGlyph hover={railHover}>
|
||||
animate={smoothStreaming}
|
||||
hover={railHover}
|
||||
headerRef={headerRef}
|
||||
actionSlotRef={setActionSlot}
|
||||
onToggle={handleToggle}
|
||||
failure={
|
||||
!withinActivityPhase && !parentPhaseOwnsFailurePill
|
||||
? { count: activitySummary.failedCount, total: count, onReveal: handleRevealFailed }
|
||||
: undefined
|
||||
}
|
||||
glyph={
|
||||
<>
|
||||
{partialMarkerFallback && (
|
||||
<TriangleAlert className="text-status-warning size-4 shrink-0" aria-hidden="true" />
|
||||
)}
|
||||
|
|
@ -695,39 +693,9 @@ export default function ToolCallGroup({
|
|||
/>
|
||||
</div>
|
||||
))}
|
||||
</RailGlyph>
|
||||
<span
|
||||
className="tool-status-text min-w-0 truncate font-medium"
|
||||
role="status"
|
||||
title={groupLabel}
|
||||
>
|
||||
<PhaseLabel text={groupLabel} animate={smoothStreaming} />
|
||||
</span>
|
||||
{visibleGroupDetail && (
|
||||
<span
|
||||
className="text-text-secondary max-w-[40%] min-w-0 truncate text-xs font-normal"
|
||||
title={visibleGroupDetail}
|
||||
>
|
||||
· {visibleGroupDetail}
|
||||
</span>
|
||||
)}
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
'text-text-secondary absolute end-0 size-4 shrink-0 transition-transform duration-200 ease-out',
|
||||
isExpanded && 'rotate-180',
|
||||
)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</button>
|
||||
{!withinActivityPhase && !parentPhaseOwnsFailurePill && (
|
||||
<FailedRevealPill
|
||||
count={activitySummary.failedCount}
|
||||
total={count}
|
||||
onReveal={handleRevealFailed}
|
||||
/>
|
||||
)}
|
||||
<span ref={setActionSlot} className="flex shrink-0 items-center empty:hidden" />
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
<div
|
||||
style={flattenGroup ? undefined : expandStyle}
|
||||
onTransitionEnd={handleTransitionEnd}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import React, { useContext } from 'react';
|
||||
import { RecoilRoot } from 'recoil';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { GeneratedToolLabelContext } from '@librechat/chat/react';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { Tools, Constants, ContentTypes, ToolCallTypes } from 'librechat-data-provider';
|
||||
|
|
@ -12,6 +13,7 @@ import {
|
|||
} from '@librechat/chat/components';
|
||||
import type { TAttachment, TMessageContentParts } from 'librechat-data-provider';
|
||||
import { scheduleMessageContentLayoutReconcile } from '~/hooks';
|
||||
import { HeaderActionSlotContext } from '../slot';
|
||||
import ToolCallGroup from '../ToolCallGroup';
|
||||
|
||||
const mockMCPServerNames: string[] = [];
|
||||
|
|
@ -436,10 +438,35 @@ describe('ToolCallGroup image hoisting', () => {
|
|||
expect(screen.queryByText('Only allow sites you trust')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps the group disclosure chevron visible', () => {
|
||||
renderGroup(baseProps);
|
||||
|
||||
expect(screen.getByTestId('group-chevron')).not.toHaveClass('opacity-0');
|
||||
it('keeps the real header action target stable while the group updates', () => {
|
||||
const actionTargets: HTMLElement[] = [];
|
||||
function Action() {
|
||||
const target = useContext(HeaderActionSlotContext);
|
||||
if (target == null) {
|
||||
return null;
|
||||
}
|
||||
actionTargets.push(target);
|
||||
return createPortal(<span data-testid="tool-action">{'Sources'}</span>, target);
|
||||
}
|
||||
const props = {
|
||||
...baseProps,
|
||||
initialExpansionState: { isExpanded: true, userOverride: true },
|
||||
renderPart: (_part: TMessageContentParts, idx: number) => <Action key={idx} />,
|
||||
};
|
||||
const { rerender } = renderGroup(props);
|
||||
const header = screen.getByRole('button', { expanded: true });
|
||||
const target = screen.getAllByTestId('tool-action')[0].parentElement;
|
||||
expect(target?.parentElement).toBe(header.parentElement);
|
||||
expect(header).not.toContainElement(target);
|
||||
rerender(
|
||||
<RecoilRoot>
|
||||
<ToolCallGroup {...props} isSubmitting />
|
||||
</RecoilRoot>,
|
||||
);
|
||||
expect(screen.getAllByTestId('tool-action')[0].parentElement).toBe(target);
|
||||
expect(actionTargets.every((element) => element === target)).toBe(true);
|
||||
fireEvent.click(header);
|
||||
expect(header).toHaveAttribute('aria-expanded', 'false');
|
||||
});
|
||||
|
||||
it('does not reconcile layout for an initially collapsed completed group', () => {
|
||||
|
|
@ -1809,30 +1836,6 @@ describe('ToolCallGroup failure fast path', () => {
|
|||
expect(onReveal).toHaveBeenCalledTimes(failedParts.length);
|
||||
});
|
||||
|
||||
it('keeps the count quiet when the group contains both successful and failed calls', () => {
|
||||
renderGroup(props(jest.fn()));
|
||||
expect(
|
||||
screen
|
||||
.getByTestId('failed-reveal-pill')
|
||||
.querySelector('span.text-text-secondary, span.text-status-error'),
|
||||
).toHaveClass('text-text-secondary');
|
||||
});
|
||||
|
||||
it('keeps the count in the error tone when every call failed', () => {
|
||||
renderGroup({
|
||||
...props(jest.fn()),
|
||||
parts: [
|
||||
failedParts[1],
|
||||
{ part: makePart('c3', 'Error processing tool: gone', 'create_file'), idx: 1 },
|
||||
],
|
||||
});
|
||||
expect(
|
||||
screen
|
||||
.getByTestId('failed-reveal-pill')
|
||||
.querySelector('span.text-text-secondary, span.text-status-error'),
|
||||
).toHaveClass('text-status-error');
|
||||
});
|
||||
|
||||
it.each(['created', 'Error processing tool: unavailable'])(
|
||||
'preserves a sparse partial batch with output %s',
|
||||
(output) => {
|
||||
|
|
|
|||
|
|
@ -198,6 +198,128 @@ Promise.all(${JSON.stringify([
|
|||
});
|
||||
});
|
||||
|
||||
test.describe('tool group header cascade', () => {
|
||||
let markup: string;
|
||||
let libraryCss: string;
|
||||
let appCss: string;
|
||||
|
||||
test.beforeAll(async ({ browserName }, testInfo) => {
|
||||
const fixturePath = testInfo.outputPath(`tool-group-${browserName}.html`);
|
||||
mkdirSync(resolve(fixturePath, '..'), { recursive: true });
|
||||
const rendered = spawnSync(
|
||||
process.execPath,
|
||||
[
|
||||
resolve(repoRoot, 'node_modules/jest/bin/jest.js'),
|
||||
'src/components/parts/group/__tests__/Header.spec.tsx',
|
||||
'--maxWorkers=2',
|
||||
'-t',
|
||||
'exports the real group header for the browser cascade checks',
|
||||
],
|
||||
{
|
||||
cwd: resolve(repoRoot, 'packages/chat'),
|
||||
env: { ...process.env, E2E_TOOL_GROUP_CASCADE_FIXTURE: fixturePath },
|
||||
encoding: 'utf8',
|
||||
},
|
||||
);
|
||||
expect(rendered.status, rendered.stdout + rendered.stderr).toBe(0);
|
||||
markup = readFileSync(fixturePath, 'utf8');
|
||||
const compilerPath = testInfo.outputPath('compile-tool-group.cjs');
|
||||
const compiledPath = testInfo.outputPath('tool-group-app.css');
|
||||
writeFileSync(
|
||||
compilerPath,
|
||||
`const {readFileSync, writeFileSync} = require('node:fs');
|
||||
const postcss = require(${JSON.stringify(require.resolve('postcss'))});
|
||||
const tailwind = require(${JSON.stringify(require.resolve('@tailwindcss/postcss'))});
|
||||
const input = ${JSON.stringify(resolve(repoRoot, 'client/src/style.css'))};
|
||||
postcss([tailwind()]).process(readFileSync(input, 'utf8'), {from: input})
|
||||
.then(result => writeFileSync(${JSON.stringify(compiledPath)}, result.css))
|
||||
.catch(error => { console.error(error); process.exitCode = 1; });`,
|
||||
);
|
||||
const compiled = run(process.execPath, [compilerPath]);
|
||||
expect(compiled.status, compiled.output).toBe(0);
|
||||
libraryCss = readFileSync(DIST_STYLESHEET, 'utf8');
|
||||
appCss = readFileSync(compiledPath, 'utf8');
|
||||
});
|
||||
|
||||
for (const { mode, reference, scenario } of [
|
||||
{ mode: 'light', reference: false, scenario: '@scenario:tool-group-header-light-cascade' },
|
||||
{ mode: 'dark', reference: false, scenario: '@scenario:tool-group-header-dark-cascade' },
|
||||
{ mode: 'light', reference: true, scenario: '@scenario:tool-group-header-light-reference' },
|
||||
{ mode: 'dark', reference: true, scenario: '@scenario:tool-group-header-dark-reference' },
|
||||
] as const) {
|
||||
test(`preserves inherited header appearance ${scenario}`, async ({ page }) => {
|
||||
await page.setContent(
|
||||
`<!doctype html><html class="${mode}"><head></head><body>
|
||||
<div class="message-content" style="width:600px" data-version="before">${markup}</div>
|
||||
<div class="message-content" style="width:600px" data-version="after">${markup}</div>
|
||||
</body></html>`,
|
||||
);
|
||||
// Load both complete stylesheets in main.jsx order, including every competing selector.
|
||||
await page.addStyleTag({ content: libraryCss });
|
||||
await page.addStyleTag({ content: appCss });
|
||||
await page.evaluate((changed) => {
|
||||
// Freeze dev's original control recipe; the surrounding DOM is pinned by the header spec.
|
||||
const before = document.querySelector('[data-version="before"] button')!;
|
||||
before.className =
|
||||
'text-text-secondary hover:text-text-secondary focus-visible:ring-focus-subtle inline-flex h-auto min-w-0 flex-1 items-center justify-start gap-2 rounded-none bg-transparent p-0 py-1 hover:bg-transparent focus-visible:ring-2 focus-visible:ring-offset-0 focus-visible:outline-none';
|
||||
const detail = document.querySelector('[data-version="before"] [title="Create File"]')!;
|
||||
detail.classList.replace('max-w-2/5', 'max-w-[40%]');
|
||||
if (changed) {
|
||||
document.documentElement.style.setProperty('--markdown-font-size', '20px');
|
||||
document.documentElement.style.setProperty('--font-size-base', '18px');
|
||||
document.documentElement.style.setProperty('--theme-control-font-weight', '800');
|
||||
document.body.style.fontWeight = '700';
|
||||
}
|
||||
}, reference);
|
||||
for (const state of ['rest', 'hover', 'focus']) {
|
||||
const read = async (version: string) => {
|
||||
const button = page.locator(`[data-version="${version}"] button`);
|
||||
await page.mouse.move(0, 0);
|
||||
await page.evaluate(() => (document.activeElement as HTMLElement)?.blur());
|
||||
if (state === 'hover') {
|
||||
await button.hover();
|
||||
} else if (state === 'focus') {
|
||||
await page.keyboard.press('Tab');
|
||||
await button.focus();
|
||||
}
|
||||
return button.evaluate((element) => {
|
||||
const properties = [
|
||||
'font-size',
|
||||
'font-weight',
|
||||
'line-height',
|
||||
'padding',
|
||||
'width',
|
||||
'height',
|
||||
'color',
|
||||
'background-color',
|
||||
'border-radius',
|
||||
'outline',
|
||||
'box-shadow',
|
||||
'transition-property',
|
||||
'transition-duration',
|
||||
'max-width',
|
||||
];
|
||||
return [
|
||||
element,
|
||||
...element.querySelectorAll('[role="status"], [title="Create File"]'),
|
||||
].map((target) => {
|
||||
const style = getComputedStyle(target);
|
||||
return Object.fromEntries(
|
||||
properties.map((name) => [name, style.getPropertyValue(name)]),
|
||||
);
|
||||
});
|
||||
});
|
||||
};
|
||||
const before = await read('before');
|
||||
const after = await read('after');
|
||||
expect(after, `${mode} reference=${reference} ${state}`).toEqual(before);
|
||||
expect(after[0]['transition-duration']).toBe('0s');
|
||||
expect(after[after.length - 1]['max-width']).toBe('40%');
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/** The client test renders both real consumers. Only this browser lane asks it to save markup,
|
||||
* so ordinary Jest needs neither a browser binary nor the browser lane's services. */
|
||||
test.describe('phase label animation cascade', () => {
|
||||
|
|
|
|||
|
|
@ -125,6 +125,8 @@ export type { MessageFooterProps } from './components/messages/MessageFooter';
|
|||
export { getMessageAriaLabel, getHeaderPrefixForScreenReader } from './components/messages/labels';
|
||||
|
||||
export { default as PhaseLabel, FOLD_EASING } from './components/parts/PhaseLabel';
|
||||
export { default as ToolGroupHeader } from './components/parts/group/Header';
|
||||
export type { ToolGroupHeaderProps } from './components/parts/group/Header';
|
||||
|
||||
/** Parts: the leaf components and row classes tool cards share. */
|
||||
export { default as Stdout } from './components/parts/Stdout';
|
||||
|
|
|
|||
77
packages/chat/src/components/parts/group/Header.tsx
Normal file
77
packages/chat/src/components/parts/group/Header.tsx
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
import { ChevronDown } from 'lucide-react';
|
||||
import { Button, cn } from '@librechat/client';
|
||||
import type { ReactElement, ReactNode, Ref } from 'react';
|
||||
import type { RailHover } from '../rail';
|
||||
import { FailedRevealPill } from '../reveal';
|
||||
import PhaseLabel from '../PhaseLabel';
|
||||
import { RailGlyph } from '../rail';
|
||||
|
||||
export type ToolGroupHeaderProps = {
|
||||
label: string;
|
||||
detail: string;
|
||||
ariaLabel: string;
|
||||
expanded: boolean;
|
||||
hidden: boolean;
|
||||
animate: boolean;
|
||||
glyph: ReactNode;
|
||||
hover: RailHover;
|
||||
headerRef: Ref<HTMLDivElement>;
|
||||
actionSlotRef: Ref<HTMLSpanElement>;
|
||||
onToggle: () => void;
|
||||
failure?: { count: number; total: number; onReveal: () => void };
|
||||
};
|
||||
|
||||
/** The group owns disclosure state; its host supplies the glyph and header action target. */
|
||||
export default function ToolGroupHeader({
|
||||
label,
|
||||
detail,
|
||||
ariaLabel,
|
||||
expanded,
|
||||
hidden,
|
||||
animate,
|
||||
glyph,
|
||||
hover,
|
||||
headerRef,
|
||||
actionSlotRef,
|
||||
onToggle,
|
||||
failure,
|
||||
}: ToolGroupHeaderProps): ReactElement {
|
||||
return (
|
||||
<div
|
||||
className={cn('relative w-full items-center gap-2 pe-6', hidden ? 'hidden' : 'flex')}
|
||||
hidden={hidden}
|
||||
ref={headerRef}
|
||||
>
|
||||
<Button
|
||||
type="button"
|
||||
variant="fold-header"
|
||||
className="min-w-0 flex-1"
|
||||
onClick={onToggle}
|
||||
aria-expanded={expanded}
|
||||
aria-label={ariaLabel}
|
||||
>
|
||||
<RailGlyph hover={hover}>{glyph}</RailGlyph>
|
||||
<span className="tool-status-text min-w-0 truncate font-medium" role="status" title={label}>
|
||||
<PhaseLabel text={label} animate={animate} />
|
||||
</span>
|
||||
{detail && (
|
||||
<span
|
||||
className="text-text-secondary max-w-2/5 min-w-0 truncate text-xs font-normal"
|
||||
title={detail}
|
||||
>
|
||||
· {detail}
|
||||
</span>
|
||||
)}
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
'text-text-secondary absolute end-0 size-4 shrink-0 transition-transform duration-200 ease-out',
|
||||
expanded && 'rotate-180',
|
||||
)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</Button>
|
||||
{failure && <FailedRevealPill {...failure} />}
|
||||
<span ref={actionSlotRef} className="flex shrink-0 items-center empty:hidden" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,117 @@
|
|||
/** @jest-environment jsdom */
|
||||
import { createRef } from 'react';
|
||||
import { writeFileSync } from 'node:fs';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import type { ToolGroupHeaderProps } from '../Header';
|
||||
import { initEnglish } from '../../../../__fixtures__/i18n';
|
||||
import { useRailHover } from '../../rail';
|
||||
import Header from '../Header';
|
||||
|
||||
beforeAll(initEnglish);
|
||||
|
||||
const defaults = {
|
||||
label: 'Created the config files',
|
||||
detail: 'Create File',
|
||||
ariaLabel: 'Created the config files, Create File, Thoughts',
|
||||
expanded: false,
|
||||
hidden: false,
|
||||
animate: false,
|
||||
glyph: <svg className="size-4" data-testid="glyph" />,
|
||||
headerRef: createRef<HTMLDivElement>(),
|
||||
actionSlotRef: createRef<HTMLSpanElement>(),
|
||||
onToggle: jest.fn(),
|
||||
} satisfies Omit<ToolGroupHeaderProps, 'hover'>;
|
||||
|
||||
function Harness(props: Partial<ToolGroupHeaderProps>) {
|
||||
const hover = useRailHover();
|
||||
return <Header {...defaults} hover={hover} {...props} />;
|
||||
}
|
||||
|
||||
describe('ToolGroupHeader', () => {
|
||||
it('exports the real group header for the browser cascade checks', () => {
|
||||
const { container } = render(<Harness expanded />);
|
||||
expect(screen.getByRole('button')).toHaveAttribute('aria-expanded', 'true');
|
||||
const fixturePath = process.env.E2E_TOOL_GROUP_CASCADE_FIXTURE;
|
||||
if (fixturePath) {
|
||||
writeFileSync(fixturePath, container.innerHTML);
|
||||
}
|
||||
});
|
||||
|
||||
it('preserves the accessible name, status, titles and sibling action target without a host', () => {
|
||||
render(<Harness />);
|
||||
const button = screen.getByRole('button', { name: defaults.ariaLabel });
|
||||
const header = defaults.headerRef.current;
|
||||
expect(button).toHaveAttribute('type', 'button');
|
||||
expect(button).toHaveAttribute('aria-expanded', 'false');
|
||||
expect(header?.firstElementChild).toBe(button);
|
||||
expect(header?.lastElementChild).toBe(defaults.actionSlotRef.current);
|
||||
expect(button).not.toContainElement(defaults.actionSlotRef.current);
|
||||
expect(screen.getByRole('status')).toHaveAttribute('title', defaults.label);
|
||||
expect(screen.getByTitle(defaults.detail)).toHaveClass('max-w-2/5');
|
||||
expect(screen.getByTestId('glyph').closest('[aria-hidden]')).toHaveAttribute(
|
||||
'aria-hidden',
|
||||
'true',
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps the group disclosure chevron visible', () => {
|
||||
render(<Harness />);
|
||||
const chevron = screen.getByRole('button').lastElementChild;
|
||||
expect(chevron).not.toHaveClass('opacity-0', 'rotate-180');
|
||||
expect(chevron).toHaveAttribute('aria-hidden', 'true');
|
||||
});
|
||||
|
||||
it('supports keyboard activation and controlled updates without remounting the refs', async () => {
|
||||
const onToggle = jest.fn();
|
||||
const { rerender } = render(<Harness onToggle={onToggle} />);
|
||||
const button = screen.getByRole('button');
|
||||
const header = defaults.headerRef.current;
|
||||
const actions = defaults.actionSlotRef.current;
|
||||
button.focus();
|
||||
await userEvent.keyboard('{Enter} ');
|
||||
expect(onToggle).toHaveBeenCalledTimes(2);
|
||||
rerender(<Harness expanded onToggle={onToggle} />);
|
||||
expect(button).toHaveFocus();
|
||||
expect(button).toHaveAttribute('aria-expanded', 'true');
|
||||
expect(button.lastElementChild).toHaveClass('rotate-180');
|
||||
expect(defaults.headerRef.current).toBe(header);
|
||||
expect(defaults.actionSlotRef.current).toBe(actions);
|
||||
});
|
||||
|
||||
it('keeps flattened headers mounted and hidden without hiding their caller', () => {
|
||||
const { container } = render(<Harness hidden />);
|
||||
expect(screen.queryByRole('button')).toBeNull();
|
||||
expect(defaults.headerRef.current).toHaveAttribute('hidden');
|
||||
expect(defaults.headerRef.current).toHaveClass('hidden');
|
||||
expect(defaults.headerRef.current?.parentElement).toBe(container);
|
||||
expect(defaults.actionSlotRef.current).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('reveals failures from a sibling button without toggling the disclosure', async () => {
|
||||
const onReveal = jest.fn();
|
||||
const onToggle = jest.fn();
|
||||
render(<Harness onToggle={onToggle} failure={{ count: 1, total: 2, onReveal }} />);
|
||||
const disclosure = screen.getByRole('button', { name: defaults.ariaLabel });
|
||||
const failure = screen.getByTestId('failed-reveal-pill');
|
||||
expect(disclosure).not.toContainElement(failure);
|
||||
expect(failure.parentElement).toBe(disclosure.parentElement);
|
||||
await userEvent.click(failure);
|
||||
expect(onReveal).toHaveBeenCalledTimes(1);
|
||||
expect(onToggle).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[1, 'text-text-secondary'],
|
||||
[2, 'text-status-error'],
|
||||
])('uses the failure count tone for %i of two failures', (count, tone) => {
|
||||
render(<Harness failure={{ count, total: 2, onReveal: jest.fn() }} />);
|
||||
expect(screen.getByTestId('failed-reveal-pill').querySelector('span')).toHaveClass(tone);
|
||||
});
|
||||
|
||||
it('omits empty details and failure controls owned by a parent', () => {
|
||||
render(<Harness detail="" />);
|
||||
expect(screen.queryByTitle(defaults.detail)).toBeNull();
|
||||
expect(screen.queryByTestId('failed-reveal-pill')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
|
@ -10,6 +10,40 @@ jest.mock('react-i18next', () => ({
|
|||
}));
|
||||
|
||||
describe('Button', () => {
|
||||
it('keeps fold headers in inherited typography with their original hover and focus geometry', () => {
|
||||
render(<Button variant="fold-header">Tool activity</Button>);
|
||||
const header = screen.getByRole('button', { name: 'Tool activity' });
|
||||
expect(header).toHaveAttribute('type', 'button');
|
||||
expect(header).not.toHaveAttribute('data-activity-card');
|
||||
expect(header).toHaveClass(
|
||||
'text-text-secondary',
|
||||
'hover:text-text-secondary',
|
||||
'bg-transparent',
|
||||
'hover:bg-transparent',
|
||||
'rounded-none',
|
||||
'p-0',
|
||||
'py-1',
|
||||
'focus-visible:ring-focus-subtle',
|
||||
'focus-visible:ring-2',
|
||||
'focus-visible:ring-offset-0',
|
||||
);
|
||||
expect(header).not.toHaveClass(
|
||||
'text-sm',
|
||||
'font-theme-control',
|
||||
'whitespace-nowrap',
|
||||
'transition-colors',
|
||||
'h-theme-button',
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps the ordinary button recipe after adding the fold header bypass', () => {
|
||||
render(<Button>Continue</Button>);
|
||||
const button = screen.getByRole('button', { name: 'Continue' });
|
||||
expect(button).toHaveClass('text-sm', 'font-theme-control', 'h-theme-button');
|
||||
expect(button).not.toHaveClass('rounded-none', 'py-1');
|
||||
expect(button).not.toHaveAttribute('data-activity-card');
|
||||
});
|
||||
|
||||
it('keeps the activity card content-sized with native focus and disabled semantics', () => {
|
||||
render(
|
||||
<Button variant="activity-card" disabled>
|
||||
|
|
|
|||
|
|
@ -43,6 +43,7 @@ type ButtonVariantOptions =
|
|||
| 'inline-edit'
|
||||
| 'card'
|
||||
| 'activity-card'
|
||||
| 'fold-header'
|
||||
| 'disclosure'
|
||||
| 'disclosure-line'
|
||||
| 'disclosure-panel'
|
||||
|
|
@ -297,6 +298,7 @@ const buttonVariantRecipe = cva(
|
|||
option:
|
||||
'w-full select-none justify-start gap-2.5 whitespace-normal text-start font-normal text-text-primary transition-opacity enabled:duration-500 disabled:duration-500 disabled:transition-all motion-reduce:transition-none motion-reduce:disabled:transition-none hover:bg-surface-hover hover:active:bg-surface-pressed data-[selected=true]:bg-surface-active data-[selected=true]:hover:bg-surface-active',
|
||||
'activity-card': '',
|
||||
'fold-header': '',
|
||||
card: 'justify-start whitespace-normal rounded-2xl text-start font-normal hover:bg-surface-hover focus-visible:ring-inset focus-visible:ring-offset-0',
|
||||
/** A small text action in the secondary ink beside a status line, such as a failed
|
||||
* steer's Retry or a pending one's Cancel; it rises to the primary ink under the pointer. */
|
||||
|
|
@ -483,8 +485,15 @@ const buttonVariantRecipe = cva(
|
|||
|
||||
/** A status card keeps native focus and its content-sized box. Unlike action buttons,
|
||||
* unavailable details dim the whole card without replacing its surface or descendant ink. */
|
||||
const buttonVariants: (props?: ButtonVariantOptions) => string = (props) =>
|
||||
props?.variant === 'activity-card'
|
||||
const buttonVariants: (props?: ButtonVariantOptions) => string = (props) => {
|
||||
if (props?.variant === 'fold-header') {
|
||||
return cn(
|
||||
'text-text-secondary hover:text-text-secondary focus-visible:ring-focus-subtle inline-flex h-auto items-center justify-start gap-2 rounded-none bg-transparent p-0 py-1 hover:bg-transparent focus-visible:ring-2 focus-visible:ring-offset-0 focus-visible:outline-none',
|
||||
props.class,
|
||||
props.className,
|
||||
);
|
||||
}
|
||||
return props?.variant === 'activity-card'
|
||||
? cn(
|
||||
'border-border-light bg-surface-secondary flex w-full flex-col gap-1 rounded-lg border px-3 py-2 text-start transition',
|
||||
props.class,
|
||||
|
|
@ -493,6 +502,7 @@ const buttonVariants: (props?: ButtonVariantOptions) => string = (props) =>
|
|||
: buttonVariantRecipe(
|
||||
props == null ? props : { ...props, shape: props.shape == null ? 'unset' : props.shape },
|
||||
);
|
||||
};
|
||||
|
||||
export interface ButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue