feat(chat): render shell_exec as a command and stream card

Give sandbox shell calls a display_type and keep stdout/stderr on the
live payload so the timeline can show the command, exit code, and
streams instead of the generic raw-output fallback.
main
wizardchen 2026-08-25 17:43:34 +08:00 committed by lyingbug
parent 790ae75b5f
commit 94a2faf391
17 changed files with 549 additions and 16 deletions

View File

@ -335,10 +335,21 @@ const messages = {
"queryKnowledgeGraph": "知识图谱查询",
"readSkill": "读取技能",
"executeSkillScript": "执行技能脚本",
"shellExec": "执行沙箱命令",
"dataAnalysis": "数据分析",
"dataSchema": "数据结构",
"databaseQuery": "数据库查询"
},
"shellExec": {
"workDir": "目录",
"exitCode": "退出码",
"stdout": "标准输出",
"stderr": "标准错误",
"emptyOutput": "无输出",
"truncated": "输出已截断",
"killed": "已超时终止",
"binarySuppressed": "二进制输出已省略,请将文件写入产物目录后下载"
},
"summary": {
"searchKb": "检索知识库 <strong>{count}</strong> 次",
"thinking": "思考 <strong>{count}</strong> 次",
@ -432,7 +443,8 @@ const messages = {
"queryUnderstanding": "正在理解问题...",
"queryUnderstandDone": "已完成问题理解",
"called": "调用 {name}",
"calledFailed": "调用 {name} 失败"
"calledFailed": "调用 {name} 失败",
"shellExecRunning": "正在执行沙箱命令..."
},
"copy": {
"emptyContent": "当前回答为空,无法复制",
@ -832,10 +844,21 @@ const messages = {
"queryKnowledgeGraph": "Knowledge Graph Query",
"readSkill": "Read Skill",
"executeSkillScript": "Execute Skill Script",
"shellExec": "Run sandbox command",
"dataAnalysis": "Data Analysis",
"dataSchema": "Data Schema",
"databaseQuery": "Database Query"
},
"shellExec": {
"workDir": "Directory",
"exitCode": "Exit code",
"stdout": "Stdout",
"stderr": "Stderr",
"emptyOutput": "No output",
"truncated": "Output truncated",
"killed": "Timed out",
"binarySuppressed": "Binary output omitted. Write files to the artifact directory to download them."
},
"summary": {
"searchKb": "Searched knowledge base <strong>{count}</strong> time(s)",
"thinking": "Thought <strong>{count}</strong> time(s)",
@ -929,7 +952,8 @@ const messages = {
"queryUnderstanding": "Understanding query...",
"queryUnderstandDone": "Query understood",
"called": "Called {name}",
"calledFailed": "Failed to call {name}"
"calledFailed": "Failed to call {name}",
"shellExecRunning": "Running sandbox command..."
},
"copy": {
"emptyContent": "Current response is empty, cannot copy",

View File

@ -5156,10 +5156,21 @@ export default {
queryKnowledgeGraph: 'Knowledge Graph Query',
readSkill: 'Read Skill',
executeSkillScript: 'Execute Skill Script',
shellExec: 'Run sandbox command',
dataAnalysis: 'Data Analysis',
dataSchema: 'Data Schema',
databaseQuery: 'Database Query'
},
shellExec: {
workDir: 'Directory',
exitCode: 'Exit code',
stdout: 'Stdout',
stderr: 'Stderr',
emptyOutput: 'No output',
truncated: 'Output truncated',
killed: 'Timed out',
binarySuppressed: 'Binary output omitted. Write files to the artifact directory to download them.'
},
citation: {
notFound: 'Content not found',
loadFailed: 'Failed to load',
@ -5236,7 +5247,8 @@ export default {
queryUnderstanding: 'Understanding query...',
queryUnderstandDone: 'Query understood',
called: 'Called {name}',
calledFailed: 'Failed to call {name}'
calledFailed: 'Failed to call {name}',
shellExecRunning: 'Running sandbox command...'
},
copy: {
emptyContent: 'Current response is empty, cannot copy',

View File

@ -1236,7 +1236,8 @@ export default {
queryUnderstanding: '질문 이해 중...',
queryUnderstandDone: '질문 이해 완료',
called: '{name} 호출 완료',
calledFailed: '{name} 호출 실패'
calledFailed: '{name} 호출 실패',
shellExecRunning: '샌드박스 명령 실행 중...'
},
ragPipeline: {
searching: '지식베이스 검색 중...',
@ -1307,10 +1308,21 @@ export default {
queryKnowledgeGraph: '지식 그래프 조회',
readSkill: '스킬 읽기',
executeSkillScript: '스킬 스크립트 실행',
shellExec: '샌드박스 명령 실행',
dataAnalysis: '데이터 분석',
dataSchema: '데이터 구조',
databaseQuery: '데이터베이스 조회'
},
shellExec: {
workDir: '디렉터리',
exitCode: '종료 코드',
stdout: '표준 출력',
stderr: '표준 에러',
emptyOutput: '출력 없음',
truncated: '출력이 잘림',
killed: '시간 초과로 종료됨',
binarySuppressed: '바이너리 출력은 생략되었습니다. 파일은 산출물 디렉터리에 저장한 뒤 다운로드하세요.'
},
mcpOAuth: {
waiting: '인증 대기 · {target}',
waitingStatus: '인증 대기',

View File

@ -1236,7 +1236,8 @@ export default {
queryUnderstanding: 'Анализ запроса...',
queryUnderstandDone: 'Запрос понят',
called: 'Вызван {name}',
calledFailed: 'Ошибка вызова {name}'
calledFailed: 'Ошибка вызова {name}',
shellExecRunning: 'Выполнение команды в песочнице...'
},
ragPipeline: {
searching: 'Поиск в базе знаний...',
@ -1307,10 +1308,21 @@ export default {
queryKnowledgeGraph: 'Запрос графа знаний',
readSkill: 'Чтение навыка',
executeSkillScript: 'Выполнение скрипта навыка',
shellExec: 'Выполнение команды в песочнице',
dataAnalysis: 'Анализ данных',
dataSchema: 'Структура данных',
databaseQuery: 'Запрос к базе данных'
},
shellExec: {
workDir: 'Каталог',
exitCode: 'Код выхода',
stdout: 'Stdout',
stderr: 'Stderr',
emptyOutput: 'Нет вывода',
truncated: 'Вывод обрезан',
killed: 'Прервано по таймауту',
binarySuppressed: 'Двоичный вывод опущен. Сохраните файлы в каталог артефактов и скачайте их.'
},
mcpOAuth: {
waiting: 'Ожидание авторизации · {target}',
waitingStatus: 'Ожидание авторизации',

View File

@ -1238,7 +1238,8 @@ export default {
queryUnderstanding: '正在理解问题...',
queryUnderstandDone: '已完成问题理解',
called: '调用 {name}',
calledFailed: '调用 {name} 失败'
calledFailed: '调用 {name} 失败',
shellExecRunning: '正在执行沙箱命令...'
},
ragPipeline: {
searching: '正在检索知识库...',
@ -1309,10 +1310,21 @@ export default {
queryKnowledgeGraph: '知识图谱查询',
readSkill: '读取技能',
executeSkillScript: '执行技能脚本',
shellExec: '执行沙箱命令',
dataAnalysis: '数据分析',
dataSchema: '数据结构',
databaseQuery: '数据库查询'
},
shellExec: {
workDir: '目录',
exitCode: '退出码',
stdout: '标准输出',
stderr: '标准错误',
emptyOutput: '无输出',
truncated: '输出已截断',
killed: '已超时终止',
binarySuppressed: '二进制输出已省略,请将文件写入产物目录后下载'
},
mcpOAuth: {
waiting: '等待授权 · {target}',
waitingStatus: '等待授权',

View File

@ -25,7 +25,8 @@ export type DisplayType =
| 'wiki_write_page'
| 'wiki_replace_text'
| 'wiki_rename_page'
| 'wiki_delete_page';
| 'wiki_delete_page'
| 'shell_exec';
// Search result item
export interface SearchResultItem {
@ -321,6 +322,22 @@ export interface WikiDeletePageData {
affected_pages?: string[];
}
export interface ShellExecData {
display_type: 'shell_exec';
command?: string;
work_dir?: string;
exit_code?: number;
duration_ms?: number;
killed?: boolean;
truncated?: boolean;
stdout?: string;
stderr?: string;
stdout_binary?: boolean;
stderr_binary?: boolean;
stdout_truncated?: boolean;
stderr_truncated?: boolean;
}
// Union type for all wiki edit data
export type WikiEditData = WikiWritePageData | WikiReplaceTextData | WikiRenamePageData | WikiDeletePageData;
@ -342,7 +359,8 @@ export type ToolResultData =
| WikiWritePageData
| WikiReplaceTextData
| WikiRenamePageData
| WikiDeletePageData;
| WikiDeletePageData
| ShellExecData;
// Action data (from index.vue)
export interface ActionData {

View File

@ -26,6 +26,10 @@ test('getAgentToolIconName maps rag pipeline tools', () => {
assert.equal(getAgentToolIconName('knowledge_search'), 'data-search')
})
test('getAgentToolIconName maps sandbox shell tools to the terminal icon', () => {
assert.equal(getAgentToolIconName('shell_exec'), 'terminal')
})
test('getAgentToolIconName maps Wiki tools to semantic search and reading icons', () => {
assert.equal(getAgentToolIconName('wiki_search'), 'search')
assert.equal(getAgentToolIconName('wiki_read_page'), 'file-search')

View File

@ -39,5 +39,11 @@ export function getAgentToolIconName(
if (toolName.startsWith('mcp_')) {
return 'terminal'
}
if (toolName === 'shell_exec' || toolName === 'list_sandbox_files' || toolName === 'read_sandbox_file') {
return 'terminal'
}
if (toolName === 'execute_skill_script') {
return 'code'
}
return 'file-paste'
}

View File

@ -0,0 +1,50 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { buildShellExecView, previewShellCommand } from './shellExecResult.ts'
test('buildShellExecView prefers structured streams over markdown output', () => {
const view = buildShellExecView(
{ command: 'ls', work_dir: '/workspace', exit_code: 0, stdout: 'a.txt\n', stderr: '' },
{ command: 'ignored' },
'## Stdout\n\n```\nold\n```\n',
)
assert.equal(view.command, 'ls')
assert.equal(view.workDir, '/workspace')
assert.equal(view.exitCode, 0)
assert.equal(view.stdout, 'a.txt\n')
})
test('buildShellExecView parses legacy markdown output when streams were stripped', () => {
const view = buildShellExecView(
{ command: 'cat README.md', exit_code: 0 },
null,
[
'=== Shell Exec (session=abc) ===',
'',
'**Command**: `cat README.md`',
'**Work Dir**: /workspace',
'**Exit Code**: 0',
'',
'## Stdout',
'',
'```',
'# title',
'```',
'',
'## Stderr',
'',
'```',
'warn',
'```',
'',
].join('\n'),
)
assert.equal(view.command, 'cat README.md')
assert.equal(view.stdout, '# title')
assert.equal(view.stderr, 'warn')
})
test('previewShellCommand collapses whitespace and truncates', () => {
assert.equal(previewShellCommand('ls -la'), 'ls -la')
assert.equal(previewShellCommand('abcdefghij', 8), 'abcdefg…')
})

View File

@ -0,0 +1,114 @@
/**
* Helpers for rendering shell_exec tool cards.
* Live results carry stdout/stderr on tool_data; older turns only have the
* markdown Output blob that used to be shown as "raw output".
*/
export type ShellExecView = {
command: string
workDir: string
exitCode: number | null
durationMs: number | null
killed: boolean
truncated: boolean
stdoutBinary: boolean
stderrBinary: boolean
stdout: string
stderr: string
}
function asRecord(value: unknown): Record<string, unknown> {
if (value && typeof value === 'object' && !Array.isArray(value)) {
return value as Record<string, unknown>
}
if (typeof value === 'string') {
try {
const parsed = JSON.parse(value)
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
return parsed as Record<string, unknown>
}
} catch {
return {}
}
}
return {}
}
function asString(value: unknown): string {
return typeof value === 'string' ? value : value == null ? '' : String(value)
}
function asNumber(value: unknown): number | null {
if (typeof value === 'number' && Number.isFinite(value)) return value
if (typeof value === 'string' && value.trim()) {
const n = Number(value)
return Number.isFinite(n) ? n : null
}
return null
}
function asBool(value: unknown): boolean {
return value === true || value === 'true'
}
function extractFencedSection(output: string, heading: string): string {
const headingMatch = output.match(new RegExp(`##\\s+${heading}\\b[\\s\\S]*?\`\`\``, 'i'))
if (!headingMatch) return ''
const afterOpenFence = output.slice(output.indexOf(headingMatch[0]) + headingMatch[0].length)
const start = afterOpenFence.startsWith('\n') ? 1 : 0
const end = afterOpenFence.indexOf('```', start)
const body = end >= 0 ? afterOpenFence.slice(start, end) : afterOpenFence.slice(start)
return body.replace(/^\n/, '').replace(/\n$/, '')
}
function stripLegacyShellHeader(output: string): string {
return output
.replace(/^=== Shell Exec[\s\S]*?\n\n/, '')
.replace(/\*\*Command\*\*:[\s\S]*?(?:\n(?!\*\*)|$)/, '')
.replace(/\*\*Work Dir\*\*:.*\n/, '')
.replace(/\*\*Exit Code\*\*:.*\n/, '')
.replace(/\*\*Duration\*\*:.*\n/, '')
.replace(/\*\*Killed\*\*:.*\n/, '')
.replace(/\*\*Truncated\*\*:.*\n/, '')
.replace(/\*\*Binary Output Suppressed\*\*:.*\n/, '')
.trim()
}
export function buildShellExecView(
data: Record<string, unknown> | null | undefined,
args: unknown,
output?: string,
): ShellExecView {
const record = data || {}
const argumentsRecord = asRecord(args)
const rawOutput = asString(output)
const stdoutFromData = asString(record.stdout)
const stderrFromData = asString(record.stderr)
const parsedStdout = stdoutFromData ? '' : extractFencedSection(rawOutput, 'Stdout')
const parsedStderr = stderrFromData ? '' : extractFencedSection(rawOutput, 'Stderr')
let stdout = stdoutFromData || parsedStdout
let stderr = stderrFromData || parsedStderr
if (!stdout && !stderr && rawOutput) {
stdout = stripLegacyShellHeader(rawOutput)
}
return {
command: asString(record.command) || asString(argumentsRecord.command),
workDir: asString(record.work_dir) || asString(argumentsRecord.work_dir),
exitCode: asNumber(record.exit_code),
durationMs: asNumber(record.duration_ms),
killed: asBool(record.killed),
truncated: asBool(record.truncated) || asBool(record.stdout_truncated) || asBool(record.stderr_truncated),
stdoutBinary: asBool(record.stdout_binary),
stderrBinary: asBool(record.stderr_binary),
stdout,
stderr,
}
}
export function previewShellCommand(command: string, max = 72): string {
const trimmed = command.replace(/\s+/g, ' ').trim()
if (trimmed.length <= max) return trimmed
return `${trimmed.slice(0, max - 1)}…`
}

View File

@ -178,10 +178,10 @@
<div class="results-summary-text" v-html="getAttachmentParsingSummary(event)"></div>
</div>
<div v-if="isEventExpanded(event.tool_call_id) && !event.pending && hasExpandableResults(event)"
<div v-if="isEventExpanded(event.tool_call_id) && !event.pending && hasExpandableResults(event)"
class="action-details">
<div v-if="event.display_type && event.tool_data" class="tool-result-wrapper">
<ToolResultRenderer :display-type="event.display_type" :tool-data="event.tool_data"
<div v-if="resolveToolDisplayType(event)" class="tool-result-wrapper">
<ToolResultRenderer :display-type="resolveToolDisplayType(event)" :tool-data="event.tool_data"
:output="event.output" :arguments="event.arguments" />
</div>
<div v-else-if="event.output" class="tool-output-wrapper">
@ -440,8 +440,8 @@
<div v-if="isEventExpanded(event.tool_call_id) && !event.pending && hasExpandableResults(event)"
class="action-details">
<div v-if="event.display_type && event.tool_data" class="tool-result-wrapper">
<ToolResultRenderer :display-type="event.display_type" :tool-data="event.tool_data"
<div v-if="resolveToolDisplayType(event)" class="tool-result-wrapper">
<ToolResultRenderer :display-type="resolveToolDisplayType(event)" :tool-data="event.tool_data"
:output="event.output" :arguments="event.arguments" />
</div>
@ -559,6 +559,7 @@ import type { ProtectedFileAccessContext } from '@/utils/protectedFileAccess';
import { unwrapFinalAnswerWrappers, thinkingEqualsAnswer } from '@/utils/finalAnswer';
import { getAgentToolIconName } from '@/utils/agent-tool-icons';
import { getQueryText, getWikiPageText } from '@/utils/agent-tool-display';
import { previewShellCommand } from '@/utils/shellExecResult';
import { parseWikiToolReferences } from '@/utils/wikiToolReferences';
import {
buildManualMarkdown,
@ -624,6 +625,7 @@ const TOOL_NAME_KEYS: Record<string, string> = {
query_knowledge_graph: 'agentStream.tools.queryKnowledgeGraph',
read_skill: 'agentStream.tools.readSkill',
execute_skill_script: 'agentStream.tools.executeSkillScript',
shell_exec: 'agentStream.tools.shellExec',
data_analysis: 'agentStream.tools.dataAnalysis',
data_schema: 'agentStream.tools.dataSchema',
database_query: 'agentStream.tools.databaseQuery',
@ -1043,6 +1045,12 @@ const formatToolResultContent = (value: unknown): string => {
const isMcpTool = (toolName?: string | null): boolean => String(toolName || '').startsWith('mcp_');
const resolveToolDisplayType = (event: any): string | undefined => {
if (event?.display_type) return event.display_type
if (event?.tool_name === 'shell_exec') return 'shell_exec'
return undefined
};
const WIKI_EDIT_TOOL_NAMES = new Set([
'wiki_write_page',
'wiki_replace_text',
@ -2605,6 +2613,9 @@ const getToolTitle = (event: any): string => {
if (event.tool_name === 'wiki_search' || event.tool_name === 'wiki_read_page') {
return `${getLocalizedToolName(event.tool_name)}...`;
}
if (event.tool_name === 'shell_exec') {
return t('agentStream.toolStatus.shellExecRunning');
}
const localizedName = getLocalizedToolName(event.tool_name);
return t('agentStream.toolStatus.calling', { name: localizedName });
}
@ -2700,6 +2711,14 @@ const getToolTitle = (event: any): string => {
return pageLabel ? `${baseTitle}:「${sanitizeForDisplay(pageLabel)}」` : baseTitle;
}
if (toolName === 'shell_exec') {
const command = previewShellCommand(
String(event.tool_data?.command || event.arguments?.command || ''),
)
const baseTitle = getToolDescription(event)
return command ? `${baseTitle}:${command}` : baseTitle
}
// Use tool summary if available
const summary = getToolSummary(event);
return summary || getToolDescription(event);
@ -2717,6 +2736,9 @@ const getToolDescription = (event: any): string => {
if (event.tool_name === 'query_understand') {
return t('agentStream.toolStatus.queryUnderstanding');
}
if (event.tool_name === 'shell_exec') {
return t('agentStream.toolStatus.shellExecRunning');
}
const localizedName = getLocalizedToolName(event.tool_name);
return t('agentStream.toolStatus.calling', { name: localizedName });
}
@ -2747,6 +2769,9 @@ const getToolDescription = (event: any): string => {
return success ? t('agentStream.toolStatus.attachmentParsingDone') : t('agentStream.toolStatus.attachmentParsingFailed');
} else if (toolName === 'query_understand') {
return success ? t('agentStream.toolStatus.queryUnderstandDone') : t('agentStream.toolStatus.calledFailed', { name: getLocalizedToolName(toolName) });
} else if (toolName === 'shell_exec') {
const localizedName = getLocalizedToolName(toolName);
return success ? localizedName : t('agentStream.toolStatus.calledFailed', { name: localizedName });
} else {
const localizedName = getLocalizedToolName(toolName);
return success ? t('agentStream.toolStatus.called', { name: localizedName }) : t('agentStream.toolStatus.calledFailed', { name: localizedName });

View File

@ -46,6 +46,13 @@
v-else-if="displayType === 'wiki_write_page' || displayType === 'wiki_replace_text' || displayType === 'wiki_rename_page' || displayType === 'wiki_delete_page'"
:data="toolData as WikiEditData" />
<ShellExecResult
v-else-if="displayType === 'shell_exec'"
:data="toolData as ShellExecData"
:output="output"
:arguments="toolArguments"
/>
<!-- Fallback: Display raw output -->
<div v-else class="fallback-output">
<div class="fallback-header">
@ -75,7 +82,8 @@ import type {
WebFetchResultsData,
GrepResultsData,
KnowledgeChunksListData,
WikiEditData
WikiEditData,
ShellExecData
} from '@/types/tool-results';
import SearchResults from './tool-results/SearchResults.vue';
@ -92,6 +100,7 @@ import WebFetchResults from './tool-results/WebFetchResults.vue';
import GrepResults from './tool-results/GrepResults.vue';
import KnowledgeChunksList from './tool-results/KnowledgeChunksList.vue';
import WikiEditResult from './tool-results/WikiEditResult.vue';
import ShellExecResult from './tool-results/ShellExecResult.vue';
interface Props {
displayType?: DisplayType;

View File

@ -0,0 +1,177 @@
<template>
<div class="shell-exec-result">
<div v-if="view.command" class="shell-exec-command">
<span class="shell-exec-prompt" aria-hidden="true">$</span>
<pre class="shell-exec-command-text">{{ view.command }}</pre>
</div>
<div v-if="hasMeta" class="shell-exec-meta">
<span v-if="view.workDir">{{ $t('agentStream.shellExec.workDir') }} {{ view.workDir }}</span>
<span v-if="view.exitCode !== null" :class="{ 'is-error': view.exitCode !== 0 }">
{{ $t('agentStream.shellExec.exitCode') }} {{ view.exitCode }}
</span>
<span v-if="durationLabel">{{ durationLabel }}</span>
<span v-if="view.killed">{{ $t('agentStream.shellExec.killed') }}</span>
<span v-if="view.truncated">{{ $t('agentStream.shellExec.truncated') }}</span>
</div>
<div v-if="view.stdoutBinary || view.stderrBinary" class="shell-exec-note">
{{ $t('agentStream.shellExec.binarySuppressed') }}
</div>
<div v-if="view.stdout" class="shell-exec-stream">
<div class="shell-exec-stream-label">{{ $t('agentStream.shellExec.stdout') }}</div>
<pre class="shell-exec-stream-body">{{ view.stdout }}</pre>
</div>
<div v-if="view.stderr" class="shell-exec-stream is-stderr">
<div class="shell-exec-stream-label">{{ $t('agentStream.shellExec.stderr') }}</div>
<pre class="shell-exec-stream-body">{{ view.stderr }}</pre>
</div>
<div v-if="!view.stdout && !view.stderr && !view.stdoutBinary && !view.stderrBinary" class="shell-exec-empty">
{{ $t('agentStream.shellExec.emptyOutput') }}
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import type { ShellExecData } from '@/types/tool-results'
import { buildShellExecView } from '@/utils/shellExecResult'
const props = defineProps<{
data: ShellExecData | Record<string, unknown>
output?: string
arguments?: Record<string, unknown>
}>()
const view = computed(() =>
buildShellExecView(props.data as Record<string, unknown>, props.arguments, props.output),
)
const hasMeta = computed(() =>
Boolean(
view.value.workDir ||
view.value.exitCode !== null ||
view.value.durationMs !== null ||
view.value.killed ||
view.value.truncated,
),
)
const durationLabel = computed(() => {
const ms = view.value.durationMs
if (ms == null) return ''
if (ms < 1000) return `${Math.round(ms)}ms`
const seconds = ms / 1000
if (seconds < 10) return `${seconds.toFixed(1)}s`
return `${Math.round(seconds)}s`
})
</script>
<style lang="less" scoped>
.shell-exec-result {
display: flex;
flex-direction: column;
gap: 8px;
min-width: 0;
}
.shell-exec-command {
display: flex;
align-items: flex-start;
gap: 8px;
padding: 10px 12px;
border: 1px solid var(--td-component-stroke);
border-radius: 6px;
background: var(--td-bg-color-secondarycontainer);
}
.shell-exec-prompt {
flex-shrink: 0;
margin-top: 1px;
font-family: var(--app-font-family-mono);
font-size: 12px;
font-weight: 600;
line-height: 1.55;
color: var(--td-text-color-placeholder);
}
.shell-exec-command-text {
flex: 1;
min-width: 0;
margin: 0;
font-family: var(--app-font-family-mono);
font-size: 12px;
line-height: 1.55;
color: var(--td-text-color-primary);
white-space: pre-wrap;
word-break: break-word;
}
.shell-exec-meta {
display: flex;
flex-wrap: wrap;
gap: 4px 12px;
font-size: 12px;
line-height: 1.4;
color: var(--td-text-color-placeholder);
.is-error {
color: var(--td-error-color);
}
}
.shell-exec-note,
.shell-exec-empty {
font-size: 12px;
line-height: 1.4;
color: var(--td-text-color-placeholder);
}
.shell-exec-stream {
min-width: 0;
border: 1px solid var(--td-component-stroke);
border-radius: 6px;
overflow: hidden;
background: var(--td-bg-color-container);
&.is-stderr .shell-exec-stream-label {
color: var(--td-error-color);
}
}
.shell-exec-stream-label {
padding: 6px 12px;
font-size: 12px;
font-weight: 500;
line-height: 1.4;
color: var(--td-text-color-secondary);
background: var(--td-bg-color-secondarycontainer);
border-bottom: 1px solid var(--td-component-stroke);
}
.shell-exec-stream-body {
margin: 0;
padding: 10px 12px;
max-height: 280px;
overflow: auto;
font-family: var(--app-font-family-mono);
font-size: 12px;
line-height: 1.55;
color: var(--td-text-color-primary);
white-space: pre-wrap;
word-break: break-word;
&::-webkit-scrollbar {
width: 8px;
height: 8px;
}
&::-webkit-scrollbar-thumb {
background: var(--td-component-border);
border-radius: 4px;
}
}
</style>

View File

@ -18,6 +18,14 @@ var persistStripFieldsByTool = map[string][]string{
ToolReadSandboxFile: {"stdout", "stderr", "content", "content_base64"},
}
// clientStripFieldsByTool is the lighter omit list for live SSE. The UI
// needs stdout/stderr to render a terminal card; those streams are already
// capped by the tool. Persist still uses persistStripFieldsByTool.
var clientStripFieldsByTool = map[string][]string{
ToolShellExec: {"content", "content_base64"},
ToolReadSandboxFile: {"content", "content_base64"},
}
const historicalSandboxOutputChars = 4 * 1024
// ShouldOmitRawToolOutput reports whether the raw XML/text Output should be
@ -33,6 +41,18 @@ func ShouldOmitRawToolOutput(_ string, data map[string]interface{}) bool {
// SanitizeToolDataForPersist returns a copy of tool Data safe for DB / SSE replay.
func SanitizeToolDataForPersist(toolName string, data map[string]interface{}) map[string]interface{} {
return sanitizeToolData(data, persistStripFieldsByTool[toolName])
}
func sanitizeToolDataForClient(toolName string, data map[string]interface{}) map[string]interface{} {
omit := clientStripFieldsByTool[toolName]
if omit == nil {
omit = persistStripFieldsByTool[toolName]
}
return sanitizeToolData(data, omit)
}
func sanitizeToolData(data map[string]interface{}, extraOmit []string) map[string]interface{} {
if data == nil {
return nil
}
@ -44,7 +64,7 @@ func SanitizeToolDataForPersist(toolName string, data map[string]interface{}) ma
for _, key := range persistStripFields[displayType] {
delete(out, key)
}
for _, key := range persistStripFieldsByTool[toolName] {
for _, key := range extraOmit {
delete(out, key)
}
return out
@ -57,7 +77,7 @@ func SanitizeToolResultForClient(toolName string, result *types.ToolResult) map[
return meta
}
if result.Data != nil {
for k, v := range SanitizeToolDataForPersist(toolName, result.Data) {
for k, v := range sanitizeToolDataForClient(toolName, result.Data) {
meta[k] = v
}
}
@ -185,6 +205,16 @@ func compactToolSummary(success bool, errMsg string, data map[string]interface{}
if count > 0 {
return fmt.Sprintf("Semantic search returned %d result(s) (details omitted from history)", count)
}
case "shell_exec":
exit := intField(data, "exit_code")
cmd := stringField(data, "command")
if cmd != "" {
if len(cmd) > 80 {
cmd = cmd[:80] + "..."
}
return fmt.Sprintf("shell_exec exit=%d command=%s (output omitted from history)", exit, cmd)
}
return fmt.Sprintf("shell_exec exit=%d (output omitted from history)", exit)
case "attachment_parsing":
parsed := intField(data, "parsed_count")
skipped := intField(data, "skipped_count")

View File

@ -127,3 +127,29 @@ func TestSandboxToolPersistenceStripsDuplicatePayloadsAndCompactsHistory(t *test
assert(len(CompactToolOutputForHistory(ToolShellExec, steps[0].ToolCalls[0].Result)) <= historicalSandboxOutputChars,
"historical replay must independently cap legacy raw output")
}
func TestSanitizeToolResultForClientKeepsShellStreams(t *testing.T) {
meta := SanitizeToolResultForClient(ToolShellExec, &types.ToolResult{
Success: true,
Output: "=== Shell Exec ===\n**Command**: `ls`\n",
Data: map[string]interface{}{
"display_type": "shell_exec",
"command": "ls",
"exit_code": 0,
"stdout": "README.md\n",
"stderr": "",
},
})
if _, ok := meta["output"]; ok {
t.Fatal("structured shell_exec should omit the markdown Output from client metadata")
}
if meta["stdout"] != "README.md\n" {
t.Fatalf("live UI needs stdout, got %#v", meta["stdout"])
}
if meta["command"] != "ls" {
t.Fatalf("command should remain, got %#v", meta["command"])
}
if meta["display_type"] != "shell_exec" {
t.Fatalf("display_type should remain, got %#v", meta["display_type"])
}
}

View File

@ -431,6 +431,7 @@ func (t *ShellExecTool) Execute(ctx context.Context, args json.RawMessage) (*typ
// only mark Success=false when a wire-level problem prevented the command
// from running at all (already handled above via err != nil).
resultData := map[string]interface{}{
"display_type": "shell_exec",
"session_id": sessionID,
"command": command,
"work_dir": workDir,

View File

@ -111,6 +111,7 @@ func TestShellExecConfigurableOutputAndRegistryOverride(t *testing.T) {
assert.Contains(t, result.Output, content)
assert.NotContains(t, result.Output, "output truncated")
assert.Equal(t, 32768, result.Data["max_output_bytes"])
assert.Equal(t, "shell_exec", result.Data["display_type"])
}
func TestShellExecOutputLimitIsHardCapped(t *testing.T) {