diff --git a/client/src/components/Chat/Messages/Content/Parts/BackgroundTaskCall.tsx b/client/src/components/Chat/Messages/Content/Parts/BackgroundTaskCall.tsx index b1b5c042ea..405bfffacd 100644 --- a/client/src/components/Chat/Messages/Content/Parts/BackgroundTaskCall.tsx +++ b/client/src/components/Chat/Messages/Content/Parts/BackgroundTaskCall.tsx @@ -68,11 +68,13 @@ export default function BackgroundTaskCall({ () => (display?.kind === 'list' ? backgroundListGuidanceKeys(display) : []), [display], ); - const { showCode, toggleCode, expandRef, phase, hasContent } = useToolCallState({ + const { showCode, toggleCode, expandRef, phase, hasContent, bare, rowRef } = useToolCallState({ initialProgress, isSubmitting, output, hasInput: hasParams || (attachments?.length ?? 0) > 0, + panelReady: display != null, + keepRow: intent != null, onExpand, runStepStatus, extraError: outcome === 'failed', @@ -111,22 +113,25 @@ export default function BackgroundTaskCall({ {announcedText} -
- } - hasInput={hasContent} - isExpanded={showCode} - /> -
+ {!bare && ( +
+ } + hasInput={hasContent} + isExpanded={showCode} + /> +
+ )}
+ {active ? text : ''} + + ); +} diff --git a/client/src/components/Chat/Messages/Content/Parts/BashCall.tsx b/client/src/components/Chat/Messages/Content/Parts/BashCall.tsx index 06b30cf924..f953ecd617 100644 --- a/client/src/components/Chat/Messages/Content/Parts/BashCall.tsx +++ b/client/src/components/Chat/Messages/Content/Parts/BashCall.tsx @@ -18,6 +18,7 @@ import { AttachmentGroup } from './Attachment'; import { parseCommandOutput } from './command'; import { useToolCallIntent } from './intent'; import PtcToolTrace from './PtcToolTrace'; +import BareStatus from './BareStatus'; import { useLocalize } from '~/hooks'; import { cn } from '~/utils'; @@ -120,16 +121,21 @@ export default function BashCall({ ) : null; - const { showCode, toggleCode, expandStyle, expandRef, phase, hasOutput } = useToolCallState({ - initialProgress, - isSubmitting, - output, - hasInput: !!command, - onExpand, - runStepStatus, - extraError: backgroundFailed || result?.failed === true, - extraCancelled: cancelledInBackground, - }); + /** The model-authored `intent` is the settled label too, and only the row + * renders it, so a call that carries one keeps its row. */ + const intent = useToolCallIntent(args); + const { showCode, toggleCode, expandStyle, expandRef, phase, hasOutput, bare, rowRef } = + useToolCallState({ + initialProgress, + isSubmitting, + output, + hasInput: !!command, + onExpand, + runStepStatus, + extraError: backgroundFailed || result?.failed === true, + extraCancelled: cancelledInBackground, + keepRow: backgroundHandle != null || intent != null, + }); const highlighted = useLazyHighlight(showCode ? command || undefined : undefined, 'bash'); const { ref: commandPaneRef, onScroll: onCommandPaneScroll } = useFollowScroll( @@ -157,7 +163,6 @@ export default function BashCall({ * live label from the earliest delta — before the command exists and while * it runs. It persists as the settled label too (completion is a UI state, * not a tense change); the generic texts are the no-intent fallback. */ - const intent = useToolCallIntent(args); const inProgressText = (() => { if (intent != null) { return intent; @@ -171,41 +176,45 @@ export default function BashCall({ return localize('com_ui_running_command'); })(); + const finishedText = + phase === 'cancelled' + ? localize('com_ui_cancelled') + : (backgroundFinishedText ?? intent ?? localize('com_ui_command_finished')); + return ( <> -
- - } - hasInput={!!command || hasOutput} - isExpanded={showCode} - verdict={verdict} - /> -
+ + {!bare && ( +
+ + } + hasInput={!!command || hasOutput} + isExpanded={showCode} + verdict={verdict} + /> +
+ )}
( @@ -135,43 +138,47 @@ export default function ExecuteCode({ showCode, ); + const finishedText = + phase === 'cancelled' + ? localize('com_ui_cancelled') + : (backgroundFinishedText ?? intent ?? localize('com_ui_analyzing_finished')); + return ( <> -
-
+ + {!bare && ( +
+
+ )}
-
-
+ + {!bare && ( +
+
+ )}
{!!preview && ( diff --git a/client/src/components/Chat/Messages/Content/Parts/MemoryCall.tsx b/client/src/components/Chat/Messages/Content/Parts/MemoryCall.tsx index 9b67b57e81..f9ddd21d8b 100644 --- a/client/src/components/Chat/Messages/Content/Parts/MemoryCall.tsx +++ b/client/src/components/Chat/Messages/Content/Parts/MemoryCall.tsx @@ -8,6 +8,7 @@ import useToolCallState from './useToolCallState'; import { AttachmentGroup } from './Attachment'; import parseJsonField from './parseJsonField'; import MemoryInfo from '../MemoryInfo'; +import BareStatus from './BareStatus'; import { useLocalize } from '~/hooks'; import { cn } from '~/utils'; @@ -63,11 +64,12 @@ export default function MemoryCall({ }, [attachments]); const memoryFailed = isMemoryFailureOutput(toolName, output) || memoryErrors.length > 0; - const { showCode, toggleCode, expandStyle, expandRef, phase } = useToolCallState({ + const { showCode, toggleCode, expandStyle, expandRef, phase, bare, rowRef } = useToolCallState({ initialProgress, isSubmitting, output, hasInput: hasPanel || memoryFailed || runStepStatus === 'failed', + panelReady: hasPanel, onExpand, runStepStatus, extraError: memoryFailed, @@ -81,39 +83,42 @@ export default function MemoryCall({ return ( <> -
-
+ + {!bare && ( +
+
+ )}
{(hasPanel || phase === 'failed') && (
{phase === 'failed' ? ( <> -
+                  
                     {output}
                   
@@ -121,12 +126,12 @@ export default function MemoryCall({ ) : ( <> {memoryKey && ( -
+
{memoryKey}
)} {isSave && memoryValue && ( -
+
{memoryValue}
)} @@ -136,7 +141,7 @@ export default function MemoryCall({ claimed the memory was gone while the header said Cancelled. The key above already shows what was tried. */} {!isSave && phase === 'completed' && ( -
+
{localize('com_ui_memory_deleted')}
)} diff --git a/client/src/components/Chat/Messages/Content/Parts/ReadFileCall.tsx b/client/src/components/Chat/Messages/Content/Parts/ReadFileCall.tsx index 1955d445d7..7246391179 100644 --- a/client/src/components/Chat/Messages/Content/Parts/ReadFileCall.tsx +++ b/client/src/components/Chat/Messages/Content/Parts/ReadFileCall.tsx @@ -10,6 +10,7 @@ import { AttachmentGroup } from './Attachment'; import parseJsonField from './parseJsonField'; import { useToolCallIntent } from './intent'; import { TOOL_ROW_CLASSES } from '../rows'; +import BareStatus from './BareStatus'; import { useLocalize } from '~/hooks'; import { cn } from '~/utils'; @@ -94,43 +95,50 @@ export default function ReadFileCall({ const fileName = filePath.split('/').pop() || filePath; const lang = useMemo(() => langFromPath(filePath), [filePath]); - const { showCode, toggleCode, expandStyle, expandRef, phase, hasOutput } = useToolCallState({ - initialProgress, - isSubmitting, - output, - hasInput: !!filePath, - onExpand, - runStepStatus, - }); + const { showCode, toggleCode, expandStyle, expandRef, phase, hasOutput, bare, rowRef } = + useToolCallState({ + initialProgress, + isSubmitting, + output, + hasInput: !!filePath, + panelReady: output.length > 0, + keepRow: intent != null, + onExpand, + runStepStatus, + }); const highlighted = useLazyHighlight(showCode && hasOutput ? output : undefined, lang); + const finishedText = + phase === 'cancelled' + ? localize('com_ui_cancelled') + : (intent ?? localize('com_ui_read_file', { 0: fileName })); + return ( <> -
-
+ + {!bare && ( +
+
+ )}
{hasOutput && ( diff --git a/client/src/components/Chat/Messages/Content/Parts/SkillCall.tsx b/client/src/components/Chat/Messages/Content/Parts/SkillCall.tsx index 635c2050b1..1bd4965e22 100644 --- a/client/src/components/Chat/Messages/Content/Parts/SkillCall.tsx +++ b/client/src/components/Chat/Messages/Content/Parts/SkillCall.tsx @@ -8,6 +8,7 @@ import { AttachmentGroup } from './Attachment'; import parseJsonField from './parseJsonField'; import { useToolCallIntent } from './intent'; import { TOOL_ROW_CLASSES } from '../rows'; +import BareStatus from './BareStatus'; import { useLocalize } from '~/hooks'; import Stdout from './Stdout'; import { cn } from '~/utils'; @@ -38,41 +39,48 @@ export default function SkillCall({ const skillName = parsedSkillName || localize('com_ui_skill').toLowerCase(); const intent = useToolCallIntent(args); - const { showCode, toggleCode, expandStyle, expandRef, phase, hasOutput } = useToolCallState({ - initialProgress, - isSubmitting, - output, - hasInput: !!parsedSkillName, - onExpand, - runStepStatus, - }); + const { showCode, toggleCode, expandStyle, expandRef, phase, hasOutput, bare, rowRef } = + useToolCallState({ + initialProgress, + isSubmitting, + output, + hasInput: !!parsedSkillName, + /** The row is the only place that names the skill that ran. */ + keepRow: true, + onExpand, + runStepStatus, + }); + + const finishedText = + phase === 'cancelled' + ? localize('com_ui_cancelled') + : (intent ?? localize('com_ui_skill_finished', { 0: skillName })); return ( <> -
-
+ + {!bare && ( +
+
+ )}
{hasOutput && ( diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/BashCall.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/BashCall.test.tsx index f8f6635d04..0960cd1a8f 100644 --- a/client/src/components/Chat/Messages/Content/Parts/__tests__/BashCall.test.tsx +++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/BashCall.test.tsx @@ -2,8 +2,7 @@ import React from 'react'; import { RecoilRoot } from 'recoil'; import copy from 'copy-to-clipboard'; import { render, screen, fireEvent } from '@testing-library/react'; -import type { ToolDisclosures } from '../../disclosure'; -import { SoleToolContext, ToolDisclosureContext, ToolDisclosureKeyContext } from '../../disclosure'; +import { LoneGroupContext, SoleToolContext } from '../../disclosure'; import BashCall from '../BashCall'; import store from '~/store'; @@ -353,6 +352,104 @@ describe('BashCall sole tool disclosure', () => { expect(panel(container).style.gridTemplateRows).toBe('0fr'); }); + it('drops its own row when it is the only call, so the output follows the group header', () => { + renderCall(true); + expect(screen.queryByTestId('progress-text')).not.toBeInTheDocument(); + expect(screen.getByText('hi')).toBeInTheDocument(); + }); + + it('keeps its row when it is one of several calls', () => { + renderCall(false); + expect(screen.getByTestId('progress-text')).toBeInTheDocument(); + }); + + it('keeps its row when the call carries a model-authored intent', () => { + render( + + + + + , + ); + expect(screen.getByTestId('progress-text')).toHaveTextContent('Check the build'); + }); + + it('drops its row when its group holds one call inside a phase of several', () => { + render( + + + + + + + , + ); + expect(screen.queryByTestId('progress-text')).not.toBeInTheDocument(); + expect(screen.getByText('hi')).toBeInTheDocument(); + }); + + it('keeps its row while the only call is still running', () => { + render( + + + + + , + ); + expect(screen.getByTestId('progress-text')).toHaveTextContent('Running command'); + }); + + it('keeps its row when the only call failed, so the failure stays reachable', () => { + render( + + + + + , + ); + expect(screen.getByTestId('progress-text')).toHaveTextContent('tool failed'); + }); + + it('keeps its row for a detached task whose dispatch step has closed', () => { + const handle = JSON.stringify({ + background_task_id: 'task-1', + tool: 'bash_tool', + status: 'running', + message: 'Use check_background_task to follow it', + }); + render( + + + + + , + ); + expect(screen.getByTestId('progress-text')).toHaveTextContent('Running in background'); + }); + it('closes the card again when its group gains a second call', () => { const { container, rerender } = renderCall(true); expect(panel(container).style.gridTemplateRows).toBe('1fr'); @@ -370,32 +467,6 @@ describe('BashCall sole tool disclosure', () => { ); expect(panel(container).style.gridTemplateRows).toBe('0fr'); }); - - it('keeps a closed sole card closed when it remounts under a new group', () => { - const disclosures: ToolDisclosures = new Map(); - const tree = () => ( - - - - - - - - - - ); - const first = render(tree()); - fireEvent.click(first.getByTestId('progress-text')); - expect(panel(first.container).style.gridTemplateRows).toBe('0fr'); - first.unmount(); - const second = render(tree()); - expect(panel(second.container).style.gridTemplateRows).toBe('0fr'); - }); }); /** diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/SoleFocus.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/SoleFocus.test.tsx new file mode 100644 index 0000000000..aebb455c1a --- /dev/null +++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/SoleFocus.test.tsx @@ -0,0 +1,96 @@ +import React from 'react'; +import { RecoilRoot } from 'recoil'; +import { act, render, screen } from '@testing-library/react'; +import { SoleToolContext } from '../../disclosure'; +import BashCall from '../BashCall'; + +jest.mock('~/hooks', () => ({ + useLocalize: () => (key: string) => key, + useProgress: (initialProgress: number) => initialProgress, + useExpandCollapse: (isExpanded: boolean) => ({ + style: { display: 'grid', gridTemplateRows: isExpanded ? '1fr' : '0fr' }, + ref: { current: null }, + }), +})); + +jest.mock('~/components/Chat/Messages/Content/ProgressText', () => ({ + __esModule: true, + default: ({ onClick, finishedText }: { onClick?: () => void; finishedText: string }) => ( + + ), +})); + +const tree = (settled: boolean, announcer = false) => ( + + +
+ {announcer && } +
+ +
+ + + +
+
+); + +describe('a sole call that drops its row on completion', () => { + it('hands keyboard focus to the group header when the focused row goes away', () => { + const { rerender } = render(tree(false)); + act(() => screen.getByTestId('progress-text').focus()); + expect(screen.getByTestId('progress-text')).toHaveFocus(); + + rerender(tree(true)); + + expect(screen.queryByTestId('progress-text')).not.toBeInTheDocument(); + expect(screen.getByTestId('group-header')).toHaveFocus(); + }); + + it('finds the header when the fold root leads with a screen-reader announcer', () => { + const { rerender } = render(tree(false, true)); + act(() => screen.getByTestId('progress-text').focus()); + + rerender(tree(true, true)); + + expect(screen.getByTestId('group-header')).toHaveFocus(); + }); + + it('leaves focus alone when it was somewhere else', () => { + const { rerender } = render(tree(false)); + act(() => screen.getByTestId('outside').focus()); + + rerender(tree(true)); + + expect(screen.getByTestId('outside')).toHaveFocus(); + }); + + it('leaves focus alone when the row was never focused', () => { + const { rerender } = render(tree(false)); + + rerender(tree(true)); + + expect(screen.getByTestId('group-header')).not.toHaveFocus(); + }); + + it('announces the settled outcome through a live region that outlives the row', () => { + const { container, rerender } = render(tree(false)); + const region = () => container.querySelector('[aria-live="polite"]'); + expect(region()).toBeInTheDocument(); + expect(region()).toHaveTextContent(''); + + rerender(tree(true)); + + expect(region()).toHaveTextContent('com_ui_command_finished'); + }); +}); diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/SoleRow.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/SoleRow.test.tsx new file mode 100644 index 0000000000..78c3b99501 --- /dev/null +++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/SoleRow.test.tsx @@ -0,0 +1,140 @@ +import React from 'react'; +import { RecoilRoot } from 'recoil'; +import { render, screen } from '@testing-library/react'; +import FileAuthoringCall from '../FileAuthoringCall'; +import { SoleToolContext } from '../../disclosure'; +import ReadFileCall from '../ReadFileCall'; +import MemoryCall from '../MemoryCall'; +import SkillCall from '../SkillCall'; + +jest.mock('~/hooks', () => ({ + useLocalize: () => (key: string) => key, + useProgress: (initialProgress: number) => initialProgress, + useExpandCollapse: (isExpanded: boolean) => ({ + style: { display: 'grid', gridTemplateRows: isExpanded ? '1fr' : '0fr' }, + ref: { current: null }, + }), +})); + +jest.mock('~/components/Chat/Messages/Content/ProgressText', () => ({ + __esModule: true, + default: ({ finishedText }: { finishedText: string }) => ( +
{finishedText}
+ ), +})); + +const renderSole = (ui: React.ReactElement, sole = true) => + render( + + {ui} + , + ); + +describe('a sole call keeps its row when its panel would be empty', () => { + it('ReadFileCall: an empty file still shows the file name row', () => { + renderSole( + , + ); + expect(screen.getByTestId('progress-text')).toBeInTheDocument(); + }); + + it('ReadFileCall: drops the row once there is output to show', () => { + renderSole( + , + ); + expect(screen.queryByTestId('progress-text')).not.toBeInTheDocument(); + }); + + it('ReadFileCall: keeps the row that carries the model-authored intent', () => { + renderSole( + , + ); + expect(screen.getByTestId('progress-text')).toHaveTextContent('Check the config'); + }); + + it('FileAuthoringCall: a create that overwrote a file keeps the row naming the update', () => { + renderSole( + , + ); + expect(screen.getByTestId('progress-text')).toBeInTheDocument(); + }); + + it('FileAuthoringCall: a fresh create drops the row once there is a preview', () => { + renderSole( + , + ); + expect(screen.queryByTestId('progress-text')).not.toBeInTheDocument(); + }); + + it('MemoryCall: output with no parseable key or value keeps its row', () => { + renderSole( + , + ); + expect(screen.getByTestId('progress-text')).toBeInTheDocument(); + }); + + it('SkillCall: a named skill keeps its row so the skill name stays visible', () => { + renderSole( + , + ); + expect(screen.getByTestId('progress-text')).toBeInTheDocument(); + }); + + it('SkillCall: a named skill with empty output keeps its row', () => { + renderSole( + , + ); + expect(screen.getByTestId('progress-text')).toBeInTheDocument(); + }); +}); diff --git a/client/src/components/Chat/Messages/Content/Parts/useToolCallState.ts b/client/src/components/Chat/Messages/Content/Parts/useToolCallState.ts index 98ef27288f..aeb4a695cc 100644 --- a/client/src/components/Chat/Messages/Content/Parts/useToolCallState.ts +++ b/client/src/components/Chat/Messages/Content/Parts/useToolCallState.ts @@ -1,10 +1,11 @@ -import { useCallback } from 'react'; +import { useCallback, useContext } from 'react'; import type { PartMetadata } from 'librechat-data-provider'; import type { ToolCallPhase } from '~/utils/toolCallPhase'; +import { LoneGroupContext, SoleToolContext, useToolExpansion } from '../disclosure'; import { isError } from '~/components/Chat/Messages/Content/ToolOutput'; import { resolveToolCallPhase } from '~/utils/toolCallPhase'; import { useProgress, useExpandCollapse } from '~/hooks'; -import { useToolExpansion } from '../disclosure'; +import useRowHandoff from '../handoff'; interface ToolCallState { showCode: boolean; @@ -19,6 +20,11 @@ interface ToolCallState { phase: ToolCallPhase; hasOutput: boolean; hasContent: boolean; + /** Goes on the card's row so focus can follow it out. */ + rowRef: (node: HTMLElement | null) => void; + /** The only call of its group, with a panel to show: the group header is + * already the row, so the card renders its panel alone, held open. */ + bare: boolean; } export interface UseToolCallStateInput { @@ -40,6 +46,13 @@ export interface UseToolCallStateInput { * cancelled ordinary background tool. Cancellation outranks error-shaped * output so the card never relabels an intentional stop as failure. */ extraCancelled?: boolean; + /** Keep the card's own row even as the only call, for a state its phase does + * not carry (a detached task still running after its dispatch step closed). */ + keepRow?: boolean; + /** Whether the panel has a body to show. Defaults to `hasContent`; a card + * whose panel needs more than its input (a read file's output) passes its + * own, so a sole call never loses its row to an empty panel. */ + panelReady?: boolean; } export default function useToolCallState({ @@ -51,13 +64,12 @@ export default function useToolCallState({ runStepStatus, extraError = false, extraCancelled = false, + keepRow = false, + panelReady, }: UseToolCallStateInput): ToolCallState { const hasOutput = output.length > 0; const hasContent = hasInput || hasOutput; - const [showCode, setExpansionOverride] = useToolExpansion(hasContent); - const { style: expandStyle, ref: expandRef } = useExpandCollapse(showCode); - const isClosed = runStepStatus != null; /** * Passing 1 in for a closed step stops `useProgress` scheduling its 200ms @@ -67,13 +79,6 @@ export default function useToolCallState({ * 0.99 can no longer read as in-flight. */ const rawProgress = useProgress(isClosed ? 1 : initialProgress); - const toggleCode = useCallback(() => { - const next = !showCode; - setExpansionOverride(next); - if (next) { - onExpand?.(); - } - }, [onExpand, setExpansionOverride, showCode]); /** * One resolution; everything the card shows is a read of this value. The @@ -88,6 +93,25 @@ export default function useToolCallState({ hasError: (hasOutput && isError(output)) || extraError, }); + /** The only call of its group, settled successfully: the group header is + * already the row, so the card renders its panel alone, held open. While it + * runs, or once it failed or was stopped, the row is the only place that + * says so, and `keepRow` covers a state the phase cannot express. */ + const lone = useContext(LoneGroupContext); + const solo = useContext(SoleToolContext) === true || lone; + const bare = solo && (panelReady ?? hasContent) && phase === 'completed' && !keepRow; + const [expanded, setExpansionOverride] = useToolExpansion(hasContent); + const showCode = bare || expanded; + const { style: expandStyle, ref: expandRef } = useExpandCollapse(showCode); + const rowRef = useRowHandoff(bare); + const toggleCode = useCallback(() => { + const next = !showCode; + setExpansionOverride(next); + if (next) { + onExpand?.(); + } + }, [onExpand, setExpansionOverride, showCode]); + return { showCode, toggleCode, @@ -96,5 +120,7 @@ export default function useToolCallState({ phase, hasOutput, hasContent, + rowRef, + bare, }; } diff --git a/client/src/components/Chat/Messages/Content/ToolCall.tsx b/client/src/components/Chat/Messages/Content/ToolCall.tsx index 23fbbe9af9..e02114abb0 100644 --- a/client/src/components/Chat/Messages/Content/ToolCall.tsx +++ b/client/src/components/Chat/Messages/Content/ToolCall.tsx @@ -8,11 +8,16 @@ import { splitToolCallName, } from 'librechat-data-provider'; import type { TAttachment, PartMetadata } from 'librechat-data-provider'; -import { toolPanelSpacingClassName, useToolExpansion, SoleToolContext } from './disclosure'; +import { + toolPanelSpacingClassName, + useToolExpansion, + LoneGroupContext, + SoleToolContext, +} from './disclosure'; import { useLocalize, useProgress, useExpandCollapse, useLazyCollapseBody } from '~/hooks'; +import { ToolIcon, getToolIconType, isError, hasRenderableOutput } from './ToolOutput'; import { cn, getToolDisplayLabel, logger, openInNewTab } from '~/utils'; import { isToolCallPreparing, useToolPreparation } from './preparation'; -import { ToolIcon, getToolIconType, isError } from './ToolOutput'; import { useMCPIconMap, useMCPServerNames } from '~/hooks/MCP'; import { resolveToolCallPhase } from '~/utils/toolCallPhase'; import { MCPAppViews } from '~/components/MCPUIResource'; @@ -21,8 +26,10 @@ import { AttachmentGroup } from './Parts'; import ToolCallInfo from './ToolCallInfo'; import ProgressText from './ProgressText'; import { TOOL_ROW_CLASSES } from './rows'; +import { hasToolParams } from './params'; import { ToolAuthWarning } from './auth'; import { firstErrorLine } from './live'; +import useRowHandoff from './handoff'; export default function ToolCall({ initialProgress = 0.1, @@ -193,10 +200,6 @@ export default function ToolCall({ /** The preference opens a card once it has output; a sole call opens on * its arguments too, so a call that returned nothing still shows them. */ const soleTool = useContext(SoleToolContext) === true; - const [showInfo, setShowInfo] = useToolExpansion(soleTool ? hasInfo : (output?.length ?? 0) > 0); - const { style: expandStyle, ref: expandRef } = useExpandCollapse(showInfo); - const { shouldRenderBody, mountBody, handleTransitionEnd } = useLazyCollapseBody(showInfo); - const authDomain = useMemo(() => { return parsedAuthUrl?.hostname ?? ''; }, [parsedAuthUrl]); @@ -222,6 +225,31 @@ export default function ToolCall({ }); const showOAuth = Boolean(auth) && phase === 'running'; + const [expandedInfo, setShowInfo] = useToolExpansion( + soleTool ? hasInfo : (output?.length ?? 0) > 0, + ); + /** The only call of its group, settled successfully: the group header is the + * row, so the panel stands alone and stays open. An MCP or action call keeps + * its row, the only place its function name and domain appear, as does a call + * with a model-authored intent. */ + const intent = useToolCallIntent(_args); + const isActionCall = domain != null && domain !== ''; + const loneGroup = useContext(LoneGroupContext); + /** The cheap, identity and phase checks run first: a streaming call re-renders + * on every argument delta, and the panel check parses its payload. */ + const bare = + phase === 'completed' && + (soleTool || loneGroup) && + !isMCPToolCall && + !isActionCall && + intent == null && + hasInfo && + (hasToolParams(args) || hasRenderableOutput(output)); + const showInfo = bare || expandedInfo; + const { style: expandStyle, ref: expandRef } = useExpandCollapse(showInfo); + const rowRef = useRowHandoff(bare); + const { shouldRenderBody, mountBody, handleTransitionEnd } = useLazyCollapseBody(showInfo); + /** * Binds when the sign-in prompt appears instead of on tap, so the tap opens the provider * synchronously: an iOS home-screen app drops a tab opened after an awaited request. The button @@ -315,7 +343,6 @@ export default function ToolCall({ /** Model-authored live label, streamed as the first args key (injected by * the `tool_intents` capability); persists as the settled label — * completion is a UI state, not a tense change. */ - const intent = useToolCallIntent(_args); const preparationText = useToolPreparation(); const preparing = useMemo( () => @@ -401,29 +428,40 @@ export default function ToolCall({ return getFinishedText(); })()} -
- 0 - ? localize('com_ui_requires_auth') - : undefined - } - finishedText={getFinishedText()} - subtitle={subtitle} - durationMs={runStepDurationMs} - toolPreparationDurationMs={toolPreparationDurationMs} - toolExecutionDurationMs={toolExecutionDurationMs} - phaseStartAt={toolDispatchedAt ?? toolPreparationStartedAt} - icon={ - - } - hasInput={hasInfo} - isExpanded={showInfo} - /> -
+ {!bare && ( +
+ 0 + ? localize('com_ui_requires_auth') + : undefined + } + finishedText={getFinishedText()} + subtitle={subtitle} + durationMs={runStepDurationMs} + toolPreparationDurationMs={toolPreparationDurationMs} + toolExecutionDurationMs={toolExecutionDurationMs} + phaseStartAt={toolDispatchedAt ?? toolPreparationStartedAt} + icon={ + + } + hasInput={hasInfo} + isExpanded={showInfo} + /> +
+ )}
0 && (labelPart?.part as { pending?: boolean } | undefined)?.pending !== true; + /** A detached task's dispatch step closes with a handle as its output, so + * the call reads as done while the work is still going. Only the code + * cards interpret that handle and say "Running in background"; a generic + * MCP or action row reports the closed step as ran, and the header must + * not contradict the row it sits above. */ + const detachedRunning = useMemo( + () => + toolMetadata.some( + (m) => + m.background === 'running' && + !m.cancelled && + !m.failed && + parseToolName(m.name, mcpServerNames).friendlyKey === 'com_ui_tool_name_code', + ), + [toolMetadata, mcpServerNames], + ); const allCompleted = useMemo( - () => labelSettled || toolMetadata.every((m) => m.hasOutput === true), - [toolMetadata, labelSettled], + () => !detachedRunning && (labelSettled || toolMetadata.every((m) => m.hasOutput === true)), + [toolMetadata, labelSettled, detachedRunning], ); const sourceDomains = useMemo( () => getSourceDomains(sourceAttachments ?? groupAttachments, 3), @@ -281,7 +298,9 @@ export default function ToolCallGroup({ /** Past tense once the turn is settled — matches the Asking/Asked record * card. While a multi-question turn streams, the still-open question's * tool_call part has no output yet, so keep the present tense. */ - const groupDone = allCompleted || !isSubmitting; + /** A detached task keeps the group in the running tense after the response + * ends: its handle is the call's output, but the work is still going. */ + const groupDone = (allCompleted || !isSubmitting) && !detachedRunning; const askQuestionsDone = allAskQuestions && (groupDone || askQuestionsAnswered); /** One verdict for the header's tense, its glyph and its icon animation — @@ -291,6 +310,9 @@ export default function ToolCallGroup({ /** For a single-tool group, lead with the tool's own (capitalized) label * instead of the generic "Used 1 tool: name", which reads awkwardly. */ + const singleToolIsCode = + toolMetadata[0]?.name != null && + parseToolName(toolMetadata[0].name, mcpServerNames).friendlyKey === 'com_ui_tool_name_code'; const singleToolLabel = useMemo(() => { const raw = getToolDisplayLabel(toolMetadata[0]?.name ?? '', localize, mcpServerNames); return raw ? raw.charAt(0).toUpperCase() + raw.slice(1) : ''; @@ -344,6 +366,19 @@ export default function ToolCallGroup({ useEffect(() => { if (autoCollapse && !userOverride) { + /** A row that held focus goes inert with the collapse, so focus moves to + * the header first rather than falling to the document. */ + const header = headerRef.current?.querySelector('button'); + const active = document.activeElement; + if ( + header != null && + active != null && + active !== header && + rootRef.current?.contains(active) === true && + !headerRef.current?.contains(active) + ) { + header.focus(); + } setIsExpanded(false); } }, [autoCollapse, userOverride]); @@ -479,6 +514,37 @@ export default function ToolCallGroup({ ); } if (count === 1) { + /** A bare "Code" reads as a category, not as what the call is doing, so + * the code tool says the verb its live row says. Other tools already + * name an action ("Create File"). */ + if (singleToolLabel && singleToolIsCode) { + /** Only a success signal earns "Ran": a detached task's output is its + * handle, a stopped or failed call did not run to the end, and a + * legacy record that was cut off has no output to show for it. */ + const only = toolMetadata[0]; + const rawCall = parts.find(({ part }) => part.type === ContentTypes.TOOL_CALL)?.part; + const legacyCall = + rawCall?.type === ContentTypes.TOOL_CALL + ? (rawCall[ContentTypes.TOOL_CALL] as { runStepStatus?: unknown; progress?: number }) + : undefined; + /** The card infers a stop from a legacy record with no step status whose + * progress never reached 1 once the stream is over, and `Part` supplies + * 0.1 when the field is absent; the metadata does not. */ + const interrupted = + !isSubmitting && legacyCall?.runStepStatus == null && (legacyCall?.progress ?? 0.1) < 1; + if (only?.failed) { + return localize('com_ui_failed_subject', { 0: singleToolLabel }); + } + if (only?.cancelled || interrupted) { + return localize('com_ui_cancelled'); + } + if (!groupDone) { + return localize('com_assistants_running_var', { 0: singleToolLabel }); + } + return only?.hasOutput + ? localize('com_assistants_completed_function', { 0: singleToolLabel }) + : singleToolLabel; + } return singleToolLabel || localize('com_ui_used_one_tool'); } return localize(groupDone ? 'com_ui_ran_n_actions' : 'com_ui_running_n_actions', { @@ -656,57 +722,60 @@ export default function ToolCallGroup({ /> - -
- {parts.map(({ part, idx }, partIndex) => { - if (part.type === ContentTypes.THINK) { - const think = part.think; - const reasoning = typeof think === 'string' ? think : (think?.value ?? ''); - /** A detached-subagent projection carries an empty THINK - * part flagged `reasoning_unavailable`, which `Part` - * renders as a `ReasoningMarker`. `ReasoningCompact` has - * no text to show and returns null, so the marker has to - * keep going through the standalone path or it vanishes - * the moment its call joins a group. */ - if (reasoning.trim() === '' && part.reasoning_unavailable === true) { - return renderPart( - part, - idx, - isLast && idx === lastContentIdx, - handleToolExpand, + + +
+ {parts.map(({ part, idx }, partIndex) => { + if (part.type === ContentTypes.THINK) { + const think = part.think; + const reasoning = + typeof think === 'string' ? think : (think?.value ?? ''); + /** A detached-subagent projection carries an empty THINK + * part flagged `reasoning_unavailable`, which `Part` + * renders as a `ReasoningMarker`. `ReasoningCompact` has + * no text to show and returns null, so the marker has to + * keep going through the standalone path or it vanishes + * the moment its call joins a group. */ + if (reasoning.trim() === '' && part.reasoning_unavailable === true) { + return renderPart( + part, + idx, + isLast && idx === lastContentIdx, + handleToolExpand, + ); + } + const streaming = isSubmitting && idx === lastContentIdx; + const isAfterTool = + partIndex > 0 && + parts[partIndex - 1]?.part.type === ContentTypes.TOOL_CALL; + /** Mirrors the standalone `Reasoning` path: the authored + * label wins, generic text is only a fallback. */ + const generatedLabel = part.reasoning_label?.trim(); + const label = + generatedLabel || + (streaming ? localize('com_ui_thinking') : localize('com_ui_thoughts')); + return ( + ); } - const streaming = isSubmitting && idx === lastContentIdx; - const isAfterTool = - partIndex > 0 && - parts[partIndex - 1]?.part.type === ContentTypes.TOOL_CALL; - /** Mirrors the standalone `Reasoning` path: the authored - * label wins, generic text is only a fallback. */ - const generatedLabel = part.reasoning_label?.trim(); - const label = - generatedLabel || - (streaming ? localize('com_ui_thinking') : localize('com_ui_thoughts')); - return ( - + return renderPart( + part, + idx, + isLast && idx === lastContentIdx, + handleToolExpand, ); - } - return renderPart( - part, - idx, - isLast && idx === lastContentIdx, - handleToolExpand, - ); - })} -
-
+ })} +
+
+
{hasPendingAuthRequest && } diff --git a/client/src/components/Chat/Messages/Content/ToolCallInfo.tsx b/client/src/components/Chat/Messages/Content/ToolCallInfo.tsx index abb1636218..25f44df226 100644 --- a/client/src/components/Chat/Messages/Content/ToolCallInfo.tsx +++ b/client/src/components/Chat/Messages/Content/ToolCallInfo.tsx @@ -2,6 +2,7 @@ import { useState, useMemo } from 'react'; import { ChevronDown } from 'lucide-react'; import { useLocalize, useExpandCollapse } from '~/hooks'; import { OutputRenderer } from './ToolOutput'; +import { hasToolParams } from './params'; import { cn } from '~/utils'; function isSimpleObject(obj: unknown): obj is Record { @@ -92,20 +93,7 @@ export default function ToolCallInfo({ input, output }: { input: string; output? const [showParams, setShowParams] = useState(false); const { style: paramsExpandStyle, ref: paramsExpandRef } = useExpandCollapse(showParams); - const hasParams = useMemo(() => { - if (!input || input.trim().length === 0) { - return false; - } - try { - const parsed = JSON.parse(input); - if (typeof parsed === 'object' && parsed !== null) { - return Object.keys(parsed).length > 0; - } - } catch { - // Not JSON - } - return input.trim().length > 0; - }, [input]); + const hasParams = useMemo(() => hasToolParams(input), [input]); return (
diff --git a/client/src/components/Chat/Messages/Content/ToolOutput/OutputRenderer.tsx b/client/src/components/Chat/Messages/Content/ToolOutput/OutputRenderer.tsx index dabc548799..40bd2bf725 100644 --- a/client/src/components/Chat/Messages/Content/ToolOutput/OutputRenderer.tsx +++ b/client/src/components/Chat/Messages/Content/ToolOutput/OutputRenderer.tsx @@ -103,6 +103,12 @@ function extractText(raw: string, verbatim = false): ExtractedText { return { text: trimmed, rawError: '', error: false, isJson: false }; } +/** Whether the default renderer would draw anything for this output. Callers + * that decide a panel is worth showing use it, so the two cannot disagree. */ +export function hasRenderableOutput(raw?: string | null): boolean { + return extractText(raw ?? '').text.length > 0; +} + export interface OutputSegment { text: string; className?: string; diff --git a/client/src/components/Chat/Messages/Content/ToolOutput/index.ts b/client/src/components/Chat/Messages/Content/ToolOutput/index.ts index fbac042099..ee29df34f5 100644 --- a/client/src/components/Chat/Messages/Content/ToolOutput/index.ts +++ b/client/src/components/Chat/Messages/Content/ToolOutput/index.ts @@ -1,4 +1,4 @@ export type { ToolIconType } from './ToolIcon'; export { default as StackedToolIcons } from './StackedToolIcons'; -export { default as OutputRenderer, isError } from './OutputRenderer'; +export { default as OutputRenderer, isError, hasRenderableOutput } from './OutputRenderer'; export { default as ToolIcon, getToolIconType, getMCPServerName } from './ToolIcon'; diff --git a/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx index ef960ec963..83a68a028a 100644 --- a/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx +++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx @@ -4,8 +4,8 @@ import { Tools, Constants, dataService } from 'librechat-data-provider'; import { render, screen, waitFor, fireEvent } from '@testing-library/react'; import type { TStartupConfig } from 'librechat-data-provider'; import { MCPAppsPolicyProvider } from '~/Providers/MCPAppsPolicyContext'; +import { LoneGroupContext, SoleToolContext } from '../disclosure'; import { ToolAuthWarningContext } from '../auth'; -import { SoleToolContext } from '../disclosure'; import ToolCall from '../ToolCall'; import { logger } from '~/utils'; import store from '~/store'; @@ -987,6 +987,223 @@ describe('ToolCall failure fast path', () => { }); describe('ToolCall sole tool disclosure', () => { + it('keeps the row of an only MCP call, the one place its function name shows', () => { + render( + + + + + + + , + ); + expect(screen.getByTestId('tool-call')).toBeInTheDocument(); + }); + + it('drops its row when its group holds one call inside a phase of several', () => { + render( + + + + + + + + + , + ); + expect(screen.queryByTestId('tool-call')).not.toBeInTheDocument(); + expect(screen.getByTestId('tool-call-info')).toBeInTheDocument(); + }); + + it.each([['{}'], ['[]']])( + 'keeps the row of an only call whose arguments are %s and output is empty', + (args) => { + render( + + + + + + + , + ); + expect(screen.getByTestId('tool-call')).toBeInTheDocument(); + }, + ); + + it('keeps the row of an only call whose output is only whitespace', () => { + render( + + + + + + + , + ); + expect(screen.getByTestId('tool-call')).toBeInTheDocument(); + }); + + it('keeps the row of an only call whose output blocks render as empty text', () => { + render( + + + + + + + , + ); + expect(screen.getByTestId('tool-call')).toBeInTheDocument(); + }); + + it('keeps the row of an only call that is still running', () => { + render( + + + + + + + , + ); + expect(screen.getByTestId('tool-call')).toBeInTheDocument(); + }); + + it('keeps the row of an only call that carries a model-authored intent', () => { + render( + + + + + + + , + ); + expect(screen.getByTestId('tool-call')).toBeInTheDocument(); + }); + + it('keeps the row of an only action call, which names the operation and domain', () => { + render( + + + + + + + , + ); + expect(screen.getByTestId('tool-call')).toBeInTheDocument(); + }); + + it('drops its own row once the only call has settled, leaving the info panel', () => { + render( + + + + + + + , + ); + expect(screen.queryByTestId('tool-call')).not.toBeInTheDocument(); + expect(screen.getByTestId('tool-call-info')).toBeInTheDocument(); + }); + it('opens the only call of a group when it returned no output but has arguments', () => { const { container } = render( diff --git a/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx index a44b2cd91b..bd92c1c724 100644 --- a/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx +++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx @@ -1,9 +1,9 @@ -import React from 'react'; +import React, { useContext } from 'react'; import { RecoilRoot } from 'recoil'; import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { Tools, Constants, ContentTypes, ToolCallTypes } from 'librechat-data-provider'; import type { TAttachment, TMessageContentParts } from 'librechat-data-provider'; -import { SoleToolContext, useToolAutoExpand } from '../disclosure'; +import { LoneGroupContext, SoleToolContext, useToolAutoExpand } from '../disclosure'; import { FailedRevealContext, useFailedReveal } from '../reveal'; import { scheduleMessageContentLayoutReconcile } from '~/hooks'; import ToolCallGroup from '../ToolCallGroup'; @@ -207,6 +207,15 @@ const makePart = ( }, }) as unknown as TMessageContentParts; +const completed = (part: TMessageContentParts): TMessageContentParts => + ({ + ...part, + [ContentTypes.TOOL_CALL]: { + ...(part as unknown as Record)[ContentTypes.TOOL_CALL], + runStepStatus: 'completed', + }, + }) as unknown as TMessageContentParts; + const makeApprovalPart = (id: string, output = ''): TMessageContentParts => ({ type: ContentTypes.TOOL_CALL, @@ -941,6 +950,359 @@ describe('ToolCallGroup image hoisting', () => { expect(screen.getByRole('button', { name: 'Create File' })).toBeInTheDocument(); }); + it('names a lone code call by what it did, not by the bare tool name', () => { + renderGroup({ + ...baseProps, + parts: [{ part: completed(makePart('code-1', 'done', 'execute_code')), idx: 0 }], + lastContentIdx: 0, + }); + + expect( + screen.getByRole('button', { name: /^com_assistants_completed_function/ }), + ).toBeInTheDocument(); + }); + + it('names a lone running code call by what it is doing', () => { + renderGroup({ + ...baseProps, + isSubmitting: true, + parts: [{ part: makePart('code-1', '', 'execute_code'), idx: 0 }], + lastContentIdx: 0, + }); + + expect(screen.getByRole('button', { name: /^com_assistants_running_var/ })).toBeInTheDocument(); + }); + + it('keeps a multi-call group in the running tense while one detached task runs', () => { + renderGroup({ + ...baseProps, + isSubmitting: false, + parts: [ + { part: completed(makePart('plain-1', 'ok', 'fetch_image')), idx: 0 }, + { + part: completed( + makePart( + 'code-bg-2', + JSON.stringify({ + background_task_id: 'task-2', + tool: 'bash_tool', + status: 'running', + message: 'Use check_background_task to follow it', + }), + 'bash_tool', + ), + ), + idx: 1, + }, + ], + lastContentIdx: 1, + }); + + expect(screen.getByRole('button', { name: /^Running 2 actions/ })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /^Ran 2 actions/ })).not.toBeInTheDocument(); + }); + + it('does not hold a group in the running tense for a detached MCP call its row reports as ran', () => { + renderGroup({ + ...baseProps, + isSubmitting: false, + parts: [ + { part: completed(makePart('plain-1', 'ok', 'fetch_image')), idx: 0 }, + { + part: completed( + makePart( + 'mcp-bg', + JSON.stringify({ + background_task_id: 'task-3', + tool: 'search', + status: 'running', + message: 'Use check_background_task to follow it', + }), + 'search_mcp_github', + ), + ), + idx: 1, + }, + ], + lastContentIdx: 1, + }); + + expect(screen.getByRole('button', { name: /^Ran 2 actions/ })).toBeInTheDocument(); + }); + + it('keeps the group open while a lone detached task is still running', () => { + renderGroup({ + ...baseProps, + parts: [ + { + part: completed( + makePart( + 'code-bg', + JSON.stringify({ + background_task_id: 'task-1', + tool: 'bash_tool', + status: 'running', + message: 'Use check_background_task to follow it', + }), + 'bash_tool', + ), + ), + idx: 0, + }, + ], + lastContentIdx: 0, + }); + + expect(screen.getByRole('button', { name: /^com_assistants_running_var/ })).toHaveAttribute( + 'aria-expanded', + 'true', + ); + }); + + it('keeps a lone code call in the running tense while its detached task runs', () => { + renderGroup({ + ...baseProps, + parts: [ + { + part: completed( + makePart( + 'code-1', + JSON.stringify({ + background_task_id: 'task-1', + tool: 'bash_tool', + status: 'running', + message: 'Use check_background_task to follow it', + }), + 'bash_tool', + ), + ), + idx: 0, + }, + ], + lastContentIdx: 0, + }); + + expect(screen.getByRole('button', { name: /^com_assistants_running_var/ })).toBeInTheDocument(); + }); + + const handleOutput = JSON.stringify({ + background_task_id: 'task-1', + tool: 'bash_tool', + status: 'running', + message: 'Use check_background_task to follow it', + }); + const detachedProps = (attachments: TAttachment[] = []) => ({ + ...baseProps, + parts: [{ part: completed(makePart('code-1', handleOutput, 'bash_tool')), idx: 0 }], + lastContentIdx: 0, + groupAttachments: attachments, + }); + + it('does not keep a cancelled detached task open or live', () => { + const cancelled = completed(makePart('code-1', handleOutput, 'bash_tool')); + (cancelled as unknown as Record>)[ + ContentTypes.TOOL_CALL + ].backgroundTask = { cancelled: true }; + renderGroup({ ...baseProps, parts: [{ part: cancelled, idx: 0 }], lastContentIdx: 0 }); + + expect(screen.getByRole('button', { name: /^com_ui_cancelled/ })).toHaveAttribute( + 'aria-expanded', + 'false', + ); + }); + + it('moves focus to the header when a focused detached task settles and the group collapses', () => { + const renderPart = (_p: TMessageContentParts, idx: number) => ( + + ); + const settled = { + type: 'background_task_status', + status: 'finished', + toolCallId: 'code-1', + messageId: 'm1', + } as unknown as TAttachment; + const tree = (attachments: TAttachment[]) => ( + + + + ); + const { rerender } = render(tree([])); + screen.getByTestId('row').focus(); + expect(screen.getByTestId('row')).toHaveFocus(); + + rerender(tree([settled])); + + expect( + screen.getByRole('button', { name: /^com_assistants_completed_function/ }), + ).toHaveFocus(); + }); + + it('does not call a failed lone code call "ran"', () => { + const failed = { + type: ContentTypes.TOOL_CALL, + [ContentTypes.TOOL_CALL]: { + id: 'code-f', + name: 'execute_code', + args: '{}', + output: 'boom', + runStepStatus: 'failed', + }, + } as unknown as TMessageContentParts; + + renderGroup({ + ...baseProps, + parts: [{ part: failed, idx: 0 }], + lastContentIdx: 0, + }); + + expect( + screen.queryByRole('button', { name: /^com_assistants_completed_function/ }), + ).not.toBeInTheDocument(); + }); + + it('does not call a failed lone code call "running"', () => { + const failed = { + type: ContentTypes.TOOL_CALL, + [ContentTypes.TOOL_CALL]: { + id: 'code-f2', + name: 'execute_code', + args: '{}', + output: 'boom', + runStepStatus: 'failed', + }, + } as unknown as TMessageContentParts; + + renderGroup({ + ...baseProps, + parts: [{ part: failed, idx: 0 }], + lastContentIdx: 0, + }); + + expect( + screen.queryByRole('button', { name: /^com_assistants_running_var/ }), + ).not.toBeInTheDocument(); + }); + + it('does not claim a lone code call ran when an interrupted legacy record has no success signal', () => { + const interrupted = { + type: ContentTypes.TOOL_CALL, + [ContentTypes.TOOL_CALL]: { + id: 'code-legacy', + name: 'execute_code', + args: '{}', + output: '', + progress: 0.5, + }, + } as unknown as TMessageContentParts; + + renderGroup({ + ...baseProps, + isSubmitting: false, + parts: [{ part: interrupted, idx: 0 }], + lastContentIdx: 0, + }); + + expect( + screen.queryByRole('button', { name: /^com_assistants_completed_function/ }), + ).not.toBeInTheDocument(); + }); + + it('does not claim a lone code call ran when an interrupted legacy record kept partial output', () => { + const interrupted = { + type: ContentTypes.TOOL_CALL, + [ContentTypes.TOOL_CALL]: { + id: 'code-partial', + name: 'execute_code', + args: '{}', + output: 'partial', + progress: 0.5, + }, + } as unknown as TMessageContentParts; + + renderGroup({ + ...baseProps, + isSubmitting: false, + parts: [{ part: interrupted, idx: 0 }], + lastContentIdx: 0, + }); + + expect( + screen.queryByRole('button', { name: /^com_assistants_completed_function/ }), + ).not.toBeInTheDocument(); + }); + + it('does not claim a lone code call ran when a legacy record has output but no progress field', () => { + const noProgress = { + type: ContentTypes.TOOL_CALL, + [ContentTypes.TOOL_CALL]: { + id: 'code-no-progress', + name: 'execute_code', + args: '{}', + output: 'done', + }, + } as unknown as TMessageContentParts; + + renderGroup({ + ...baseProps, + isSubmitting: false, + parts: [{ part: noProgress, idx: 0 }], + lastContentIdx: 0, + }); + + expect( + screen.queryByRole('button', { name: /^com_assistants_completed_function/ }), + ).not.toBeInTheDocument(); + }); + + it('calls a lone legacy code call ran once its progress reaches 1', () => { + const finished = { + type: ContentTypes.TOOL_CALL, + [ContentTypes.TOOL_CALL]: { + id: 'code-legacy-ok', + name: 'execute_code', + args: '{}', + output: 'done', + progress: 1, + }, + } as unknown as TMessageContentParts; + + renderGroup({ + ...baseProps, + isSubmitting: false, + parts: [{ part: finished, idx: 0 }], + lastContentIdx: 0, + }); + + expect( + screen.getByRole('button', { name: /^com_assistants_completed_function/ }), + ).toBeInTheDocument(); + }); + + it('does not call a stopped lone code call "ran"', () => { + const cancelled = { + type: ContentTypes.TOOL_CALL, + [ContentTypes.TOOL_CALL]: { + id: 'code-c', + name: 'execute_code', + args: '{}', + output: '', + runStepStatus: 'cancelled', + }, + } as unknown as TMessageContentParts; + + renderGroup({ + ...baseProps, + parts: [{ part: cancelled, idx: 0 }], + lastContentIdx: 0, + }); + + expect( + screen.queryByRole('button', { name: /^com_assistants_completed_function/ }), + ).not.toBeInTheDocument(); + }); + it('keeps repeated action counts and failed-call status in the compact summary', () => { renderGroup({ ...baseProps, @@ -1591,6 +1953,36 @@ describe('ToolCallGroup sole tool', () => { expect(screen.getByTestId('probe-0')).toHaveTextContent('true'); }); + it('marks a one-call group as lone even when its phase holds several calls', () => { + function LoneProbe() { + return
{String(useContext(LoneGroupContext))}
; + } + render( + + + } + /> + + , + ); + fireEvent.click(screen.getByRole('button', { expanded: false })); + expect(screen.getByTestId('lone')).toHaveTextContent('true'); + }); + + it('does not mark a two-call group as lone', () => { + function LoneProbe({ idx }: { idx: number }) { + return
{String(useContext(LoneGroupContext))}
; + } + renderGroup({ + ...props(['a', 'b']), + renderPart: (_p: TMessageContentParts, idx: number) => , + }); + fireEvent.click(screen.getByRole('button', { expanded: false })); + expect(screen.getByTestId('lone-0')).toHaveTextContent('false'); + }); + it('keeps a one-call group collapsed when its phase holds several calls', () => { render( diff --git a/client/src/components/Chat/Messages/Content/disclosure.ts b/client/src/components/Chat/Messages/Content/disclosure.ts index ec08a1b99c..d6cc0737e1 100644 --- a/client/src/components/Chat/Messages/Content/disclosure.ts +++ b/client/src/components/Chat/Messages/Content/disclosure.ts @@ -62,6 +62,12 @@ export function useToolDisclosure() { * wins over the groups inside it. */ export const SoleToolContext = createContext(undefined); +/** Set by a tool group for its own rows: true when the group holds exactly one + * tool call, whatever the phase around it holds. `SoleToolContext` lets the + * phase decide whether a card opens by default; this one decides whether the + * card's own row is redundant under the group header it sits beneath. */ +export const LoneGroupContext = createContext(false); + /** Whether a tool card opens by default: the user's "auto-expand tools" * preference, or being the only call inside its group. */ export function useToolAutoExpand() { diff --git a/client/src/components/Chat/Messages/Content/handoff.ts b/client/src/components/Chat/Messages/Content/handoff.ts new file mode 100644 index 0000000000..4db6adafb0 --- /dev/null +++ b/client/src/components/Chat/Messages/Content/handoff.ts @@ -0,0 +1,40 @@ +import { useCallback, useLayoutEffect, useRef } from 'react'; + +/** + * A sole call drops its own row once it settles, because the group header is + * the row. If that row held keyboard focus, the browser would drop focus to the + * document, so focus moves to the header the row is replaced by. + * + * The row is watched through its ref callback: React detaches it before the + * node leaves the DOM, which is the last moment `document.activeElement` still + * says whether the row had focus, and the node can still name its group. + */ +export default function useRowHandoff(bare: boolean) { + const rowNode = useRef(null); + const handoff = useRef(null); + + const rowRef = useCallback((node: HTMLElement | null) => { + if (node == null) { + const held = rowNode.current?.contains(document.activeElement) === true; + const root = rowNode.current?.closest('[data-fold-root]'); + /** The header precedes every row in document order, whatever else the + * root leads with (a phase puts its announcer first). */ + const header = held ? (root?.querySelector('button') ?? null) : null; + handoff.current = header != null && !rowNode.current?.contains(header) ? header : null; + } else { + handoff.current = null; + } + rowNode.current = node; + }, []); + + useLayoutEffect(() => { + if (!bare || handoff.current == null) { + return; + } + const target = handoff.current; + handoff.current = null; + target.focus(); + }, [bare]); + + return rowRef; +} diff --git a/client/src/components/Chat/Messages/Content/params.ts b/client/src/components/Chat/Messages/Content/params.ts new file mode 100644 index 0000000000..64f4e420b6 --- /dev/null +++ b/client/src/components/Chat/Messages/Content/params.ts @@ -0,0 +1,17 @@ +/** Whether serialized tool arguments hold anything the info panel can show. + * An empty object or array renders nothing, so a card must not count it as + * content. Shared by the panel and by the card deciding to drop its row. */ +export function hasToolParams(input?: string | null): boolean { + if (!input || input.trim().length === 0) { + return false; + } + try { + const parsed = JSON.parse(input); + if (typeof parsed === 'object' && parsed !== null) { + return Object.keys(parsed).length > 0; + } + } catch { + // Not JSON + } + return input.trim().length > 0; +}