🪟 feat: Expand, Copy and Tail Long Bash Output (#16555)

* feat: Expand, Copy and Tail Long Bash Output

Render bash output through OutputRenderer with a terminal variant: the
collapsed view keeps the last 15 lines, where failures land, with Show more
and a Copy output button; JSON stdout stays verbatim. The sandbox empty-stdout
notice renders as a localized "No output" state, and the command wraps at the
prompt size despite the global code.hljs rule.

* fix: Keep Terminal Output Verbatim Including Leading Whitespace

* fix: Keep Whitespace-Only Output and Ignore the Final Newline When Tailing

(cherry picked from commit a537ba8e0d)

Original-PR: https://github.com/LibreChat-AI/LibreChat/pull/16555
This commit is contained in:
Marco Beretta 2026-09-30 15:20:32 +02:00 • committed by Lia
parent 0b7d49f829
commit 0d8d8f6d38
5 changed files with 170 additions and 19 deletions

View file

@ -12,6 +12,7 @@ import { sandboxStartingByToolCallId } from '~/store';
import useToolCallState from './useToolCallState';
import useLazyHighlight from './useLazyHighlight';
import useFollowScroll from './useFollowScroll';
import { OutputRenderer } from '../ToolOutput';
import { ERROR_PATTERNS } from './ExecuteCode';
import { AttachmentGroup } from './Attachment';
import { useToolCallIntent } from './intent';
@ -20,6 +21,9 @@ import PtcToolTrace from './PtcToolTrace';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
/** The SDK's sandbox executors emit this line in place of empty stdout. */
const SANDBOX_EMPTY_OUTPUT = "stdout: Empty. Ensure you're writing output explicitly.";
export default function BashCall({
isSubmitting,
runStepStatus,
@ -55,6 +59,7 @@ export default function BashCall({
const sandboxStarting = useAtomValue(sandboxStartingByToolCallId(toolCallId ?? ''));
const outputHasError = useMemo(() => ERROR_PATTERNS.test(output), [output]);
const outputIsEmpty = output.trim() === SANDBOX_EMPTY_OUTPUT;
/** A backgrounded call's persisted output stays the dispatch handle until
* the detached run settles and patches it; render a background state
* instead of the handle JSON. Completion arrives live as the status marker
@ -190,7 +195,12 @@ export default function BashCall({
<span className="text-text-tertiary select-none" aria-hidden="true">
{'$ '}
</span>
<code className="hljs language-bash">{highlighted ?? command}</code>
{/* `code.hljs` in style.css sets `white-space: pre`, `word-wrap: normal`
and 0.85rem, which would stop long commands wrapping and size the
command larger than the `$` prompt. */}
<code className="hljs language-bash !text-xs !break-words !whitespace-pre-wrap">
{highlighted ?? command}
</code>
</pre>
</div>
</div>
@ -201,15 +211,19 @@ export default function BashCall({
className={cn(command && 'border-border-light border-t')}
/>
{hasOutput && backgroundHandle == null && (
<div className={cn(command && 'border-border-light border-t')}>
<pre
className={cn(
'max-h-[300px] overflow-auto px-3 py-2.5 font-mono text-xs break-words whitespace-pre-wrap',
outputHasError ? 'text-status-error' : 'text-text-primary',
)}
>
{output}
</pre>
<div className={cn('px-3 py-2.5', command && 'border-border-light border-t')}>
{outputIsEmpty ? (
<p className="text-text-secondary text-xs italic">
{localize('com_ui_no_output')}
</p>
) : (
<OutputRenderer
text={output}
copyText={output}
error={outputHasError}
variant="terminal"
/>
)}
</div>
)}
</div>

View file

@ -1,5 +1,6 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
import copy from 'copy-to-clipboard';
import { render, screen, fireEvent } from '@testing-library/react';
import BashCall from '../BashCall';
import store from '~/store';
@ -17,6 +18,10 @@ jest.mock('~/hooks', () => ({
com_ui_background_running: 'Running in background',
com_ui_background_finished: 'Finished in background',
com_ui_tool_failed: 'tool failed',
com_ui_copy: 'Copy output',
com_ui_no_output: 'No output',
com_ui_show_more: 'Show more',
com_ui_show_less: 'Show less',
};
return translations[key] ?? key;
},
@ -53,7 +58,11 @@ jest.mock('~/components/Chat/Messages/Content/ProgressText', () => ({
jest.mock('~/components/Messages/Content/CopyButton', () => ({
__esModule: true,
default: ({ label }: { label?: string }) => <button type="button">{label}</button>,
default: ({ label, onClick }: { label?: string; onClick?: () => void }) => (
<button type="button" onClick={onClick}>
{label}
</button>
),
}));
jest.mock('~/components/Messages/Content/LangIcon', () => ({
@ -414,3 +423,78 @@ describe('BashCall streaming follow-scroll', () => {
expect(state.writes).toHaveLength(0);
});
});
describe('BashCall output pane', () => {
const finished = (output: string, command = 'npm test') =>
render(
<RecoilRoot>
<BashCall initialProgress={1} isSubmitting={false} args={{ command }} output={output} />
</RecoilRoot>,
);
const numbered = (count: number) =>
Array.from({ length: count }, (_, i) => `line ${i + 1}`).join('\n');
it('collapses long output to its tail and expands to the full text', () => {
finished(numbered(40));
const pre = screen.getByText(/line 40/);
const shown = () => (pre.textContent ?? '').split('\n');
expect(shown()).toEqual(numbered(40).split('\n').slice(-15));
fireEvent.click(screen.getByRole('button', { name: 'Show more' }));
expect(shown()).toHaveLength(40);
expect(shown()[0]).toBe('line 1');
expect(screen.getByRole('button', { name: 'Show less' })).toBeInTheDocument();
});
it('keeps leading whitespace and blank lines verbatim', () => {
const output = '\n indented\n\n deeper';
finished(output);
expect(screen.getByText(/indented/).textContent).toBe(output);
});
it('copies the raw output', () => {
const output = 'ok 1\nok 2\n';
finished(output);
fireEvent.click(screen.getByRole('button', { name: 'Copy output' }));
expect(copy).toHaveBeenCalledWith(output, { format: 'text/plain' });
});
it('renders JSON stdout verbatim instead of reformatting it', () => {
finished('{"a":1}');
expect(screen.getByText('{"a":1}')).toBeInTheDocument();
});
it.each([
"stdout: Empty. Ensure you're writing output explicitly.\n",
" stdout: Empty. Ensure you're writing output explicitly. ",
])('shows a "No output" state for the sandbox empty-stdout notice: %j', (output) => {
finished(output, 'true');
expect(screen.getByText('No output')).toBeInTheDocument();
expect(screen.queryByText(/Ensure you're writing output/)).not.toBeInTheDocument();
});
it('keeps the notice when it is not the entire output', () => {
finished("stdout: Empty. Ensure you're writing output explicitly.\nstderr: boom");
expect(screen.queryByText('No output')).not.toBeInTheDocument();
expect(screen.getByText(/stderr: boom/)).toBeInTheDocument();
});
it('keeps error colouring for failing output', () => {
finished('Traceback (most recent call last):\n File "x.py"\nValueError: bad');
expect(screen.getByText(/ValueError: bad/)).toHaveClass('text-status-error');
});
it('uses the primary text colour for ordinary output', () => {
finished('all good');
const pre = screen.getByText('all good');
expect(pre).toHaveClass('text-text-primary');
expect(pre).not.toHaveClass('text-status-error');
});
it('lets the command wrap at the prompt size despite the global hljs rule', () => {
const { container } = finished('done', 'echo a-very-long-command');
const code = container.querySelector('code.hljs') as HTMLElement;
expect(code).toHaveClass('!text-xs', '!whitespace-pre-wrap', '!break-words');
});
});

View file

@ -49,7 +49,13 @@ interface ExtractedText {
isJson: boolean;
}
function extractText(raw: string): ExtractedText {
function extractText(raw: string, verbatim = false): ExtractedText {
/** Command output keeps its exact bytes, whitespace-only output included:
* indentation and blank lines are part of it. */
if (verbatim) {
return { text: raw, rawError: '', error: isError(raw.trim()), isJson: false };
}
const trimmed = raw.trim();
if (!trimmed) {
return { text: '', rawError: '', error: false, isJson: false };
@ -100,11 +106,24 @@ const VISIBLE_LINES = 15;
interface OutputRendererProps {
text: string;
copyText?: string;
/** Forces error styling when the caller detected a failure the text itself does not mark. */
error?: boolean;
/** `terminal` renders command output: monospace, verbatim (no JSON reformatting), and the
* collapsed view keeps the LAST lines, where failures and stack traces land. */
variant?: 'default' | 'terminal';
}
export default function OutputRenderer({ text, copyText }: OutputRendererProps) {
export default function OutputRenderer({
text,
copyText,
error: forceError = false,
variant = 'default',
}: OutputRendererProps) {
const localize = useLocalize();
const { text: displayText, rawError, error, isJson } = useMemo(() => extractText(text), [text]);
const terminal = variant === 'terminal';
const extracted = useMemo(() => extractText(text, terminal), [text, terminal]);
const { text: displayText, rawError, isJson } = extracted;
const error = extracted.error || forceError;
const [isExpanded, setIsExpanded] = useState(false);
const [showErrorDetails, setShowErrorDetails] = useState(false);
const [isCopied, setIsCopied] = useState(false);
@ -119,11 +138,13 @@ export default function OutputRenderer({ text, copyText }: OutputRendererProps)
return null;
}
const lines = displayText.split('\n');
/** A final newline ends the last line; it does not start an empty one. */
const body = displayText.endsWith('\n') ? displayText.slice(0, -1) : displayText;
const lines = body.split('\n');
const needsTruncation = lines.length > TRUNCATE_LINES;
const visibleText =
needsTruncation && !isExpanded ? lines.slice(0, VISIBLE_LINES).join('\n') : displayText;
const structured = !isJson && isStructuredText(displayText);
const collapsedLines = terminal ? lines.slice(-VISIBLE_LINES) : lines.slice(0, VISIBLE_LINES);
const visibleText = needsTruncation && !isExpanded ? collapsedLines.join('\n') : displayText;
const structured = !isJson && (terminal || isStructuredText(displayText));
return (
<div>
@ -139,7 +160,8 @@ export default function OutputRenderer({ text, copyText }: OutputRendererProps)
className={cn(
'max-h-[300px] overflow-auto text-xs break-words whitespace-pre-wrap',
error && 'text-status-error font-mono',
!error && structured && 'text-text-secondary font-mono',
!error && structured && 'font-mono',
!error && structured && (terminal ? 'text-text-primary' : 'text-text-secondary'),
!error && !structured && 'text-text-primary font-sans text-sm',
)}
>

View file

@ -32,6 +32,36 @@ describe('OutputRenderer', () => {
expect(copy).toHaveBeenCalledWith(raw, { format: 'text/plain' });
});
it('keeps the head by default and the tail for terminal output when collapsed', () => {
const text = Array.from({ length: 30 }, (_, i) => `line ${i + 1}`).join('\n');
const { unmount } = render(<OutputRenderer text={text} />);
expect(screen.getByText(/line 1/).textContent?.split('\n')[0]).toBe('line 1');
unmount();
render(<OutputRenderer text={text} variant="terminal" />);
const shown = screen.getByText(/line 30/).textContent?.split('\n') ?? [];
expect(shown[0]).toBe('line 16');
expect(shown).toHaveLength(15);
});
it('keeps whitespace-only terminal output', () => {
const { container } = render(<OutputRenderer text={'\n\n'} variant="terminal" />);
expect(container.querySelector('pre')?.textContent).toBe('\n\n');
});
it('does not count a final newline as a line when collapsing terminal output', () => {
const numbered = (n: number) =>
Array.from({ length: n }, (_, i) => `line ${i + 1}`).join('\n') + '\n';
const { unmount } = render(<OutputRenderer text={numbered(20)} variant="terminal" />);
expect(screen.queryByText('com_ui_show_more')).not.toBeInTheDocument();
unmount();
render(<OutputRenderer text={numbered(30)} variant="terminal" />);
const shown = screen.getByText(/line 30/).textContent?.split('\n') ?? [];
expect(shown).toHaveLength(15);
expect(shown[0]).toBe('line 16');
});
it('does not treat text between bracketed prefixes as a tool-call error', () => {
expect(isError('Error: [agent] unexpected [search] tool call failed: unavailable')).toBe(false);
});

View file

@ -1984,6 +1984,7 @@
"com_ui_no_memories_title": "No memories yet",
"com_ui_no_matching_projects": "No projects match your search",
"com_ui_no_options": "No options available",
"com_ui_no_output": "No output",
"com_ui_no_project_chats": "No chats yet",
"com_ui_no_projects": "No projects yet",
"com_ui_no_prompts_title": "No prompts yet",