diff --git a/frontend/src/components/SandboxCommandProgress.vue b/frontend/src/components/SandboxCommandProgress.vue new file mode 100644 index 00000000..3087fdb0 --- /dev/null +++ b/frontend/src/components/SandboxCommandProgress.vue @@ -0,0 +1,85 @@ + + + + + diff --git a/frontend/src/components/SkillInstallTimeline.test.mjs b/frontend/src/components/SkillInstallTimeline.test.mjs index 49e0911d..2970a069 100644 --- a/frontend/src/components/SkillInstallTimeline.test.mjs +++ b/frontend/src/components/SkillInstallTimeline.test.mjs @@ -96,3 +96,34 @@ test('verification refuses live sends and a finished run reinstalls with instruc assert.equal(calls[0][2], 'Install from the official guide') assert.deepEqual(h.emitted, ['restarted']) }) + +test('live output renders before tool completion and ignores a previous run', async () => { + const progressLogic = source.slice(source.indexOf('const commandOutput ='), source.indexOf('const loading =')) + const followLogic = source.slice(source.indexOf('async function follow('), source.indexOf('function wait(')) + const js = ts.transpileModule(`${progressLogic}\n${followLogic}`, { + compilerOptions: { target: ts.ScriptTarget.ES2022 }, + }).outputText + let handlers + const modelChunks = [] + const h = vm.runInNewContext(`${js}\n({ follow, commandOutput, changeRun: () => { openRun++ } })`, { + props: { live: true, configId: 'cfg', skillId: 'skill' }, + ref: value => ({ value }), computed: get => ({ get value() { return get() } }), + watch() {}, onUnmounted() {}, clearInterval() {}, + getApiBaseUrl: () => '', configSkillTranscriptUrl: () => '/transcript', + localStorage: { getItem: () => null }, AbortController, + controller: null, openRun: 1, i18n: { global: {} }, generateRandomString: () => 'request', + fetchEventSource: async (_url, options) => { handlers = options; await options.onopen({ ok: true }) }, + applyPrompt() {}, processStreamChunk: frame => modelChunks.push(frame), + }) + assert.equal(await h.follow(1), true) + const frame = data => handlers.onmessage({ data: JSON.stringify({ response_type: 'install_output', data }) }) + const started = new Date('2026-09-10T12:00:00Z').toISOString() + frame({ command: 'uv pip install -r requirements.lock', started_at: started, output: 'Downloading numpy', done: false }) + assert.equal(h.commandOutput.value.output, 'Downloading numpy') + assert.equal(modelChunks.length, 0) + frame({ command: 'uv pip install -r requirements.lock', started_at: started, output: 'Installed', done: true }) + assert.equal(h.commandOutput.value.done, true) + h.changeRun() + frame({ command: 'old command', output: 'late output', done: false }) + assert.equal(h.commandOutput.value.output, 'Installed') +}) diff --git a/frontend/src/components/SkillInstallTimeline.vue b/frontend/src/components/SkillInstallTimeline.vue index c791d1d7..0997aa2c 100644 --- a/frontend/src/components/SkillInstallTimeline.vue +++ b/frontend/src/components/SkillInstallTimeline.vue @@ -8,7 +8,8 @@ : $t('settings.sandbox.skillTranscriptEmpty') }}

+
{{ $t(`settings.sandbox.skillGuidance.${item.status}`) }}

{{ item.content }}

@@ -55,6 +61,7 @@ import { configSkillTranscriptUrl, getConfigSkillGuidance, steerConfigSkill, rei import { getApiBaseUrl } from '@/utils/api-base' import { generateRandomString } from '@/utils/index' import { makeSteerClientId } from '@/utils/steerId' +import SandboxCommandProgress from './SandboxCommandProgress.vue' import AgentStreamDisplay from '@/views/chat/components/AgentStreamDisplay.vue' import i18n from '@/i18n' @@ -144,6 +151,7 @@ watch( onUnmounted(() => { guidanceEpoch++; clearTimeout(guidanceTimer) }) const messages = reactive([]) +const commandOutput = ref<{ command: string; started_at: string; output: string; done: boolean } | null>(null) const loading = ref(false) const isReplying = ref(false) const currentAssistantMessageId = ref('') @@ -244,6 +252,10 @@ async function follow(run: number): Promise { } catch { return } + if (frame.response_type === 'install_output') { + commandOutput.value = frame.data || null + return + } if (frame.response_type === 'install_prompt') { applyPrompt(frame.content || '') return @@ -269,6 +281,7 @@ async function open() { const run = ++openRun closed = false messages.splice(0, messages.length) + commandOutput.value = null const stale = () => run !== openRun || closed try { // A finished install already has durable rows. Replaying the event log @@ -453,4 +466,11 @@ onUnmounted(stop) .skill-timeline--compact :deep(.agent-stream-display .answer-content.markdown-content h3) { font-size: 12px; } +.skill-timeline__turn--command { + // AgentStreamDisplay also renders an empty inline image-viewer trigger. + // Stack its roots so that trigger cannot create a blank text line above the command. + display: flex; + flex-direction: column; +} +.skill-timeline__command { margin: 4px 0 8px 42px; } diff --git a/frontend/src/components/css/chat-timeline-loading.less b/frontend/src/components/css/chat-timeline-loading.less index 53fb8047..ea68cf60 100644 --- a/frontend/src/components/css/chat-timeline-loading.less +++ b/frontend/src/components/css/chat-timeline-loading.less @@ -38,14 +38,16 @@ // In-progress step / thinking / tool-call titles shimmer while pending. Both the // agent timeline (.action-pending) and the RAG pipeline (.is-running) opt in. .action-card.action-pending .action-name, -.action-name.is-running { +.action-name.is-running, +.sandbox-command-code.is-running { .chat-stream-shimmer-text(); } @media (prefers-reduced-motion: reduce) { .action-card.action-pending .action-name, - .action-name.is-running { + .action-name.is-running, + .sandbox-command-code.is-running { animation: none; background-image: none; -webkit-text-fill-color: var(--td-text-color-secondary); diff --git a/frontend/src/composables/useChatStreamHandler.test.mjs b/frontend/src/composables/useChatStreamHandler.test.mjs index c862b069..d4e31044 100644 --- a/frontend/src/composables/useChatStreamHandler.test.mjs +++ b/frontend/src/composables/useChatStreamHandler.test.mjs @@ -7,6 +7,28 @@ import { resetSteerTurnForReplay } from '../utils/steerStreamFork.ts' const source = readFileSync(new URL('./useChatStreamHandler.ts', import.meta.url), 'utf8') +test('command output updates only its pending tool and cannot replace a final result', () => { + const start = source.indexOf("case 'command_output': {") + const block = source.slice(start, source.indexOf("case 'tool_result':", start)) + const command = { type: 'tool_call', tool_name: 'shell_exec', tool_call_id: 'a', pending: true } + const other = { type: 'tool_call', tool_name: 'shell_exec', tool_call_id: 'b', pending: true } + const message = { agentEventStream: [command, other] } + const process = vm.runInNewContext(ts.transpile(`(dataPayload) => { switch ('command_output') { ${block} } }`), { message }) + process({ tool_call_id: 'a', output: 'Reading CSV', done: false }) + assert.equal(command.command_output.output, 'Reading CSV') + assert.equal(command.pending, true) + assert.equal(other.command_output, undefined) + process({ tool_call_id: 'missing', output: 'unmatched' }) + assert.equal(message.agentEventStream.length, 2) + process({ tool_call_id: 'a', output: 'Finished', done: true }) + process({ tool_call_id: 'a', output: 'late chunk', done: false }) + assert.equal(command.command_output.output, 'Finished') + command.pending = false + command.output = 'Final tool result' + process({ tool_call_id: 'a', output: 'more late output', done: false }) + assert.equal(command.output, 'Final tool result') +}) + test('replaying agent_query binds the first segment and preserves distinct row IDs', () => { const messagesList = [ { id: 'a', role: 'assistant', request_id: 'r', steerForked: true, is_completed: true }, diff --git a/frontend/src/composables/useChatStreamHandler.ts b/frontend/src/composables/useChatStreamHandler.ts index 21300413..de8549f3 100644 --- a/frontend/src/composables/useChatStreamHandler.ts +++ b/frontend/src/composables/useChatStreamHandler.ts @@ -809,6 +809,19 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) { } break } + case 'command_output': { + const toolCallId = dataPayload?.tool_call_id as string | undefined + if (!toolCallId) break + const tool = (message.agentEventStream as ChatMessage[] | undefined)?.find( + event => event.type === 'tool_call' && event.tool_call_id === toolCallId, + ) + // Late progress must not resurrect a completed command or attach to + // another concurrent call just because it uses the same tool name. + if (tool?.pending && tool.tool_name === 'shell_exec' && !(tool.command_output as ChatMessage | undefined)?.done) { + tool.command_output = dataPayload + } + break + } case 'tool_result': case 'error': { if (dataPayload) { @@ -1118,6 +1131,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) { data.response_type === 'thinking' || data.response_type === 'tool_call' || data.response_type === 'tool_result' || + data.response_type === 'command_output' || data.response_type === 'reflection' || data.response_type === 'artifacts_pending' || data.response_type === 'context_compacted' || diff --git a/frontend/src/i18n/localeKeyAudit.test.ts b/frontend/src/i18n/localeKeyAudit.test.ts index da120fb7..35a0a0af 100644 --- a/frontend/src/i18n/localeKeyAudit.test.ts +++ b/frontend/src/i18n/localeKeyAudit.test.ts @@ -51,6 +51,15 @@ test('critical runtime i18n trees are present', () => { assert.deepEqual(missing, [], missing.join('\n')) }) +test('installer command progress messages resolve in the settings namespace', () => { + for (const [locale, bundle] of Object.entries(LOCALE_BUNDLES)) { + for (const name of ['installCommandRunning', 'installCommandWaiting']) { + const key = `settings.sandbox.${name}` + assert.equal(typeof getLocaleValueAtPath(bundle, key), 'string', `${locale}: missing ${key}`) + } + } +}) + test('referenced i18n keys used in app code exist in every locale', () => { const failures = findUsedKeysMissingInLocales(referencedKeys, localeKeysByName) assert.deepEqual(failures, [], failures.slice(0, 20).join('\n')) diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index f4e395dc..15af33cc 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -1548,6 +1548,8 @@ export default { }, skillTranscriptEmpty: 'This install left no transcript.', skillTranscriptWaiting: 'Install has started. Waiting for the process log…', + installCommandRunning: "Command running", + installCommandWaiting: "Waiting for command output. Elapsed time continues to update.", skillFiles: 'View files', skillFilesTitle: 'Files', skillFilesEmpty: 'This skill has no files to browse yet.', diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts index 66b824d9..93dbb9c4 100644 --- a/frontend/src/i18n/locales/ja-JP.ts +++ b/frontend/src/i18n/locales/ja-JP.ts @@ -1548,6 +1548,8 @@ export default { }, skillTranscriptEmpty: 'このインストールには記録が残っていません。', skillTranscriptWaiting: 'インストールを開始しました。処理ログを待っています…', + installCommandRunning: "コマンド実行中", + installCommandWaiting: "出力を待っています。経過時間は更新されます。", skillFiles: 'ファイルを表示', skillFilesTitle: 'ファイル', skillFilesEmpty: 'このスキルには参照できるファイルがまだありません。', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index c5775373..894ad67f 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -5684,6 +5684,8 @@ export default { }, skillTranscriptEmpty: 'This install left no transcript.', skillTranscriptWaiting: 'Install has started. Waiting for the process log…', + installCommandRunning: "명령 실행 중", + installCommandWaiting: "명령 출력을 기다리는 중입니다. 경과 시간은 계속 업데이트됩니다.", skillFiles: '파일 보기', skillFilesTitle: '파일', skillFilesEmpty: '이 스킬에서 볼 수 있는 파일이 아직 없습니다.', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index db6a51f2..a056e970 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -5684,6 +5684,8 @@ export default { }, skillTranscriptEmpty: 'This install left no transcript.', skillTranscriptWaiting: 'Install has started. Waiting for the process log…', + installCommandRunning: "Команда выполняется", + installCommandWaiting: "Ожидание вывода команды. Время выполнения обновляется.", skillFiles: 'Просмотреть файлы', skillFilesTitle: 'Файлы', skillFilesEmpty: 'У этого навыка пока нет файлов для просмотра.', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 24e3d18a..b214229e 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -5686,6 +5686,8 @@ export default { }, skillTranscriptEmpty: '这次安装没有留下记录。', skillTranscriptWaiting: '安装已开始,正在等待过程记录…', + installCommandRunning: "命令执行中", + installCommandWaiting: "等待命令输出,耗时持续更新。", skillFiles: '查看文件', skillFilesTitle: '文件', skillFilesEmpty: '该技能还没有可查看的文件。', diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue index acec1e61..561a489e 100644 --- a/frontend/src/views/chat/components/AgentStreamDisplay.vue +++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue @@ -204,6 +204,11 @@
+ +
@@ -495,6 +500,11 @@
+ +
@@ -597,6 +607,7 @@ import { ref, computed, watch, onMounted, onBeforeUnmount, onUpdated, nextTick } import { useRouter, useRoute } from 'vue-router'; import { marked } from 'marked'; import 'katex/dist/katex.min.css'; +import SandboxCommandProgress from '@/components/SandboxCommandProgress.vue'; import ToolResultRenderer from './ToolResultRenderer.vue'; import ToolApprovalCard from './ToolApprovalCard.vue'; import McpOAuthCard from './McpOAuthCard.vue'; diff --git a/internal/agent/tools/shell_command_output.go b/internal/agent/tools/shell_command_output.go new file mode 100644 index 00000000..08db3c58 --- /dev/null +++ b/internal/agent/tools/shell_command_output.go @@ -0,0 +1,85 @@ +package tools + +import ( + "context" + "strings" + "sync" + "time" + "unicode/utf8" + + "github.com/Tencent/WeKnora/internal/event" + "github.com/google/uuid" +) + +// Shell tools publish this bounded, human-facing preview. It is not +// appended to the model conversation and does not change the final tool result. +func shellCommandOutput(ctx context.Context, command string) (func(string, []byte), func()) { + meta, ok := ToolExecFromContext(ctx) + if !ok || meta.EventBus == nil { + return nil, func() {} + } + started := time.Now() + var mu sync.Mutex + var tail string + var last time.Time + var flushTimer *time.Timer + sentOutput := false + closed := false + emit := func(done bool) { + last = time.Now() + _ = meta.EventBus.Emit(ctx, event.Event{ + ID: uuid.NewString(), Type: event.EventAgentCommandOutput, SessionID: meta.SessionID, + Data: event.CommandOutputData{ + ToolCallID: meta.ToolCallID, + Command: maskCommandAssignments(command), StartedAt: started, + Output: strings.ToValidUTF8(tail, ""), Done: done, + }, + }) + } + emit(false) + appendOutput := func(_ string, chunk []byte) { + mu.Lock() + defer mu.Unlock() + if closed { + return + } + tail += string(chunk) + const limit = 8192 + if len(tail) > limit { + tail = tail[len(tail)-limit:] + for len(tail) > 0 && !utf8.RuneStart(tail[0]) { + tail = tail[1:] + } + } + if !sentOutput || time.Since(last) >= 500*time.Millisecond { + if flushTimer != nil { + flushTimer.Stop() + flushTimer = nil + } + sentOutput = true + emit(false) + } else if flushTimer == nil { + flushTimer = time.AfterFunc(500*time.Millisecond-time.Since(last), func() { + mu.Lock() + defer mu.Unlock() + flushTimer = nil + if !closed { + emit(false) + } + }) + } + } + finish := func() { + mu.Lock() + defer mu.Unlock() + if !closed { + closed = true + if flushTimer != nil { + flushTimer.Stop() + flushTimer = nil + } + emit(true) + } + } + return appendOutput, finish +} diff --git a/internal/agent/tools/shell_command_output_test.go b/internal/agent/tools/shell_command_output_test.go new file mode 100644 index 00000000..ed3538ec --- /dev/null +++ b/internal/agent/tools/shell_command_output_test.go @@ -0,0 +1,74 @@ +package tools + +import ( + "context" + "encoding/json" + "strings" + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/event" + "github.com/stretchr/testify/require" +) + +func TestShellCommandOutputIsBoundedAndFinishes(t *testing.T) { + bus := event.NewEventBus() + + updates := make(chan event.CommandOutputData, 16) + bus.On(event.EventAgentCommandOutput, func(_ context.Context, e event.Event) error { + updates <- e.Data.(event.CommandOutputData) + return nil + }) + next := func() event.CommandOutputData { + select { + case update := <-updates: + return update + case <-time.After(3 * time.Second): + t.Fatal("missing progress event") + return event.CommandOutputData{} + } + } + ctx := WithToolExecContext(context.Background(), &ToolExecContext{ + EventBus: bus, ToolCallID: "cmd-1", SessionID: "session", + }) + output, finish := shellCommandOutput(ctx, "uv pip install -r requirements.lock") + defer finish() + start := next() + require.Equal(t, "cmd-1", start.ToolCallID) + require.False(t, start.Done) + output("stdout", []byte(strings.Repeat("x", 16000))) + first := next() + require.LessOrEqual(t, len(first.Output), 8192) + output("stderr", []byte("\ndownloading wheel")) + // A short burst followed by a long silent download must still flush before completion. + progress := next() + require.Contains(t, progress.Output, "downloading wheel") + require.False(t, progress.Done) + finish() + finish() + require.True(t, next().Done) + output("stdout", []byte("late callback")) + require.Empty(t, updates) +} + +func TestShellExecPublishesCommandProgress(t *testing.T) { + bus := event.NewEventBus() + var updates []event.CommandOutputData + bus.On(event.EventAgentCommandOutput, func(_ context.Context, e event.Event) error { + updates = append(updates, e.Data.(event.CommandOutputData)) + return nil + }) + executor := &fakeShellExecutor{} + tool := NewShellExecTool(executor, nil) + ctx := WithToolExecContext(context.Background(), &ToolExecContext{ + EventBus: bus, SessionID: "session", ToolCallID: "call", + }) + result, err := tool.Execute(ctx, json.RawMessage(`{"command":"cat","stdin":"private input"}`)) + require.NoError(t, err) + require.True(t, result.Success) + require.Len(t, updates, 2) + require.Equal(t, "call", updates[0].ToolCallID) + require.Equal(t, "cat", updates[0].Command, "progress shows the requested command, not the encoded stdin wrapper") + require.False(t, updates[0].Done) + require.True(t, updates[1].Done) +} diff --git a/internal/agent/tools/shell_exec.go b/internal/agent/tools/shell_exec.go index 81634ee1..ef10f36f 100644 --- a/internal/agent/tools/shell_exec.go +++ b/internal/agent/tools/shell_exec.go @@ -491,7 +491,12 @@ func (t *ShellExecTool) Execute(ctx context.Context, args json.RawMessage) (*typ " | base64 -d | /bin/bash --noprofile --norc -c " + sandbox.ShellQuote(execCommand) } beforeOutputs, inspectedOutputs := sandboxOutputSnapshot(ctx, t.executor, sessionID) - res, err := t.executor.ExecShellCommand(ctx, sessionID, execCommand, workDir, timeout, env) + output, finishOutput := shellCommandOutput(ctx, command) + defer finishOutput() + // Observe only the requested command, not skill staging or artifact probes. + execCtx := sandbox.WithCommandOutput(ctx, output) + res, err := t.executor.ExecShellCommand(execCtx, sessionID, execCommand, workDir, timeout, env) + finishOutput() noteSandboxMutation() if err != nil { logger.Warnf(ctx, "[Tool][ShellExec] execution error: session=%s err=%v", sessionID, err) diff --git a/internal/application/service/tenant_skill_transcript.go b/internal/application/service/tenant_skill_transcript.go index 19158389..089541c2 100644 --- a/internal/application/service/tenant_skill_transcript.go +++ b/internal/application/service/tenant_skill_transcript.go @@ -155,6 +155,7 @@ func (tr *installTranscript) Subscribe() { } tr.bus.On(event.EventAgentThought, tr.onThought) tr.bus.On(event.EventAgentToolCall, tr.onToolCall) + tr.bus.On(event.EventAgentCommandOutput, tr.onInstallOutput) tr.bus.On(event.EventAgentToolResult, tr.onToolResult) tr.bus.On(event.EventAgentFinalAnswer, tr.onAnswer) tr.bus.On(event.EventError, tr.onError) @@ -560,3 +561,24 @@ func asymptoticInstallPercent(k int) int { } return p } + +func (tr *installTranscript) onInstallOutput(_ context.Context, evt event.Event) error { + data, ok := evt.Data.(event.CommandOutputData) + if !ok { + return nil + } + tr.mu.Lock() + closed := tr.closed + tr.mu.Unlock() + if closed { + return nil + } + tr.append(interfaces.StreamEvent{ + ID: evt.ID, Type: types.ResponseTypeInstallOutput, Timestamp: time.Now(), + Data: map[string]interface{}{ + "tool_call_id": data.ToolCallID, "command": data.Command, + "started_at": data.StartedAt, "output": data.Output, "done": data.Done, + }, + }) + return nil +} diff --git a/internal/application/service/tenant_skill_transcript_test.go b/internal/application/service/tenant_skill_transcript_test.go index ab993681..453fddfc 100644 --- a/internal/application/service/tenant_skill_transcript_test.go +++ b/internal/application/service/tenant_skill_transcript_test.go @@ -453,3 +453,24 @@ func TestInstallTranscriptWithoutActivityPublisherStaysSilent(t *testing.T) { require.Equal(t, []types.ResponseType{types.ResponseTypeToolCall, types.ResponseTypeComplete}, streams.types(), "the transcript itself is unchanged by progress being unwired") } + +func TestInstallTranscriptProjectsOutputWithoutCompletingTool(t *testing.T) { + streams := &transcriptStreams{} + bus := event.NewEventBus() + tr := newInstallTranscript(context.Background(), bus, streams, nil, "session", "message", nil) + tr.Subscribe() + require.NoError(t, bus.Emit(context.Background(), event.Event{ + ID: "chunk", Type: event.EventAgentCommandOutput, + Data: event.CommandOutputData{ToolCallID: "tool", Output: "Downloading polars", Done: false}, + })) + require.Len(t, streams.events, 1) + require.Equal(t, types.ResponseTypeInstallOutput, streams.events[0].Type) + require.Equal(t, "tool", streams.events[0].Data["tool_call_id"]) + require.Equal(t, "Downloading polars", streams.events[0].Data["output"]) + require.False(t, streams.events[0].Done) + tr.closed = true + require.NoError(t, tr.onInstallOutput(context.Background(), event.Event{ + Data: event.CommandOutputData{Output: "late"}, + })) + require.Len(t, streams.events, 1) +} diff --git a/internal/event/event.go b/internal/event/event.go index e686d44d..b9b556b5 100644 --- a/internal/event/event.go +++ b/internal/event/event.go @@ -49,12 +49,13 @@ const ( EventAgentComplete EventType = "agent.complete" // Agent 完成 // Agent streaming events (for real-time feedback) - EventAgentThought EventType = "thought" // Agent 思考过程 - EventAgentToolCall EventType = "tool_call" // 工具调用通知 - EventAgentToolResult EventType = "tool_result" // 工具结果 - EventAgentReflection EventType = "reflection" // Agent 反思 - EventAgentReferences EventType = "references" // 知识引用 - EventAgentFinalAnswer EventType = "final_answer" // 最终答案 + EventAgentThought EventType = "thought" // Agent 思考过程 + EventAgentCommandOutput EventType = "command_output" // bounded command output + EventAgentToolCall EventType = "tool_call" // 工具调用通知 + EventAgentToolResult EventType = "tool_result" // 工具结果 + EventAgentReflection EventType = "reflection" // Agent 反思 + EventAgentReferences EventType = "references" // 知识引用 + EventAgentFinalAnswer EventType = "final_answer" // 最终答案 // MCP tool human approval (issue #1173) EventToolApprovalRequired EventType = "tool_approval_required" diff --git a/internal/event/event_data.go b/internal/event/event_data.go index a92ab367..0182ecda 100644 --- a/internal/event/event_data.go +++ b/internal/event/event_data.go @@ -1,5 +1,7 @@ package event +import "time" + // EventData contains common event data structures for different stages // QueryData represents query-related event data @@ -303,3 +305,13 @@ type MCPOAuthResolvedData struct { TimedOut bool `json:"timed_out,omitempty"` Canceled bool `json:"canceled,omitempty"` } + +// CommandOutputData is a cumulative tail, so reconnect/replay needs no +// byte offsets and a missed update does not corrupt the displayed log. +type CommandOutputData struct { + ToolCallID string `json:"tool_call_id"` + Command string `json:"command"` + StartedAt time.Time `json:"started_at"` + Output string `json:"output"` + Done bool `json:"done"` +} diff --git a/internal/handler/session/agent_stream_handler.go b/internal/handler/session/agent_stream_handler.go index 77d3d1d9..6ef0a2e2 100644 --- a/internal/handler/session/agent_stream_handler.go +++ b/internal/handler/session/agent_stream_handler.go @@ -114,6 +114,7 @@ func (h *AgentStreamHandler) Subscribe() { h.eventBus.On(event.EventAgentThought, h.handleThought) h.eventBus.On(event.EventAgentToolCall, h.handleToolCall) h.eventBus.On(event.EventAgentToolResult, h.handleToolResult) + h.eventBus.On(event.EventAgentCommandOutput, h.handleCommandOutput) h.eventBus.On(event.EventAgentReferences, h.handleReferences) h.eventBus.On(event.EventMemoryRecalled, h.handleMemoryRecalled) h.eventBus.On(event.EventContextCompacted, h.handleContextCompacted) @@ -877,3 +878,19 @@ func publicArtifactViews(list types.MessageArtifacts) []map[string]interface{} { } return out } + +// handleCommandOutput forwards UI-only progress without adding partial output +// to the model conversation or completing the tool call. +func (h *AgentStreamHandler) handleCommandOutput(_ context.Context, evt event.Event) error { + data, ok := evt.Data.(event.CommandOutputData) + if !ok || data.ToolCallID == "" { + return nil + } + return h.streamManager.AppendEvent(h.ctx, h.sessionID, h.assistantMessageID, interfaces.StreamEvent{ + ID: evt.ID, Type: types.ResponseTypeCommandOutput, Timestamp: time.Now(), + Data: map[string]interface{}{ + "tool_call_id": data.ToolCallID, "command": data.Command, + "started_at": data.StartedAt, "output": data.Output, "done": data.Done, + }, + }) +} diff --git a/internal/handler/session/command_output_test.go b/internal/handler/session/command_output_test.go new file mode 100644 index 00000000..4d8ce297 --- /dev/null +++ b/internal/handler/session/command_output_test.go @@ -0,0 +1,39 @@ +package session + +import ( + "context" + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/event" + "github.com/Tencent/WeKnora/internal/types" + "github.com/stretchr/testify/require" +) + +func TestCommandOutputReachesChatStreamWithoutCompletingTool(t *testing.T) { + ctx := context.Background() + bus := event.NewEventBus() + streams := &completionEventRecorder{} + message := &types.Message{ID: "message"} + h := NewAgentStreamHandler(ctx, "session", "message", "request", 1, time.Now(), message, streams, bus, nil) + h.Subscribe() + for _, done := range []bool{false, true} { + require.NoError(t, bus.Emit(ctx, event.Event{ + Type: event.EventAgentCommandOutput, + Data: event.CommandOutputData{ + ToolCallID: "call-1", Command: "python analysis.py", Output: "reading CSV", Done: done, + }, + })) + } + require.Len(t, streams.events, 2) + for _, e := range streams.events { + require.Equal(t, types.ResponseTypeCommandOutput, e.Type) + require.False(t, e.Done, "command progress is not a completed assistant turn") + frame := buildStreamResponse(e, "request") + require.Equal(t, "call-1", frame.Data["tool_call_id"]) + require.Equal(t, "reading CSV", frame.Data["output"]) + } + require.Equal(t, true, streams.events[1].Data["done"]) + require.Empty(t, message.Content) + require.Empty(t, message.AgentSteps) +} diff --git a/internal/sandbox/command_output.go b/internal/sandbox/command_output.go new file mode 100644 index 00000000..ad3a5769 --- /dev/null +++ b/internal/sandbox/command_output.go @@ -0,0 +1,19 @@ +package sandbox + +import "context" + +type commandOutputKey struct{} + +// WithCommandOutput observes the command executed with this context. It does +// not grant installer privileges or change the final command result. +func WithCommandOutput(ctx context.Context, callback func(string, []byte)) context.Context { + return context.WithValue(ctx, commandOutputKey{}, callback) +} + +func commandOutputCallback(ctx context.Context, explicit func(string, []byte)) func(string, []byte) { + if explicit != nil { + return explicit + } + callback, _ := ctx.Value(commandOutputKey{}).(func(string, []byte)) + return callback +} diff --git a/internal/sandbox/docker_remote_client.go b/internal/sandbox/docker_remote_client.go index 0733b9f7..d5629650 100644 --- a/internal/sandbox/docker_remote_client.go +++ b/internal/sandbox/docker_remote_client.go @@ -692,7 +692,7 @@ func (c *DockerRemoteClient) Exec( } start := time.Now() - stdout, stderr, err := c.streamExec(execCtx, created.ID, req.Stdin) + stdout, stderr, err := c.streamExec(execCtx, created.ID, req.Stdin, req.OnOutput) if err != nil { return nil, err } @@ -724,6 +724,7 @@ func (c *DockerRemoteClient) streamExec( ctx context.Context, execID string, stdin string, + output ...func(string, []byte), ) (string, string, error) { attached, err := c.api.ExecAttach(ctx, execID, client.ExecAttachOptions{}) if err != nil { @@ -753,7 +754,12 @@ func (c *DockerRemoteClient) streamExec( var stdout, stderr bytes.Buffer done := make(chan error, 1) go func() { - _, copyErr := stdcopy.StdCopy(&stdout, &stderr, attached.Reader) + var out, errOut io.Writer = &stdout, &stderr + if len(output) > 0 && output[0] != nil { + out = io.MultiWriter(&stdout, remoteOutputWriter{stream: "stdout", callback: output[0]}) + errOut = io.MultiWriter(&stderr, remoteOutputWriter{stream: "stderr", callback: output[0]}) + } + _, copyErr := stdcopy.StdCopy(out, errOut, attached.Reader) done <- copyErr }() @@ -1288,3 +1294,11 @@ var ( _ RemoteSandboxClient = (*DockerRemoteClient)(nil) _ RemoteSnapshotManager = (*DockerRemoteClient)(nil) ) + +// remoteOutputWriter observes bytes without changing buffered exec results. +type remoteOutputWriter struct { + stream string + callback func(string, []byte) +} + +func (w remoteOutputWriter) Write(p []byte) (int, error) { w.callback(w.stream, p); return len(p), nil } diff --git a/internal/sandbox/docker_remote_client_test.go b/internal/sandbox/docker_remote_client_test.go index 14495296..f4d932dc 100644 --- a/internal/sandbox/docker_remote_client_test.go +++ b/internal/sandbox/docker_remote_client_test.go @@ -1201,3 +1201,18 @@ func TestDockerSessionCreateRequestDeletesIdleSandboxes(t *testing.T) { require.Equal(t, RemoteOnTimeoutKill, request.Timeout.Action, "pausing a container keeps its memory on the host, so it reclaims nothing") } + +func TestDockerExecObservesBothOutputStreamsWithoutChangingResult(t *testing.T) { + engine := newFakeDockerEngine() + engine.execStdout = "download started\n" + engine.execStderr = "download progress\n" + docker := newTestDockerClient(t, engine) + observed := map[string]string{} + result, err := docker.Exec(context.Background(), testHandle("container-1"), RemoteExecRequest{ + Command: "echo", Timeout: time.Second, + OnOutput: func(stream string, p []byte) { observed[stream] += string(p) }, + }) + require.NoError(t, err) + require.Equal(t, result.Stdout, observed["stdout"]) + require.Equal(t, result.Stderr, observed["stderr"]) +} diff --git a/internal/sandbox/e2b_remote_client.go b/internal/sandbox/e2b_remote_client.go index ad258301..0a3f92dc 100644 --- a/internal/sandbox/e2b_remote_client.go +++ b/internal/sandbox/e2b_remote_client.go @@ -812,6 +812,10 @@ func (c *E2BRemoteClient) Exec( start := time.Now() options := []e2b.RunOption{} + if request.OnOutput != nil { + options = append(options, e2b.WithOnStdout(func(p []byte) { request.OnOutput("stdout", p) }), + e2b.WithOnStderr(func(p []byte) { request.OnOutput("stderr", p) })) + } if request.WorkDir != "" { options = append(options, e2b.WithCwd(request.WorkDir)) } diff --git a/internal/sandbox/remote_client.go b/internal/sandbox/remote_client.go index 36eb28d8..d6a191dd 100644 --- a/internal/sandbox/remote_client.go +++ b/internal/sandbox/remote_client.go @@ -297,6 +297,10 @@ type RemoteListFilter struct { // RemoteExecRequest describes a single command invocation. See the // RemoteSandboxClient.Exec contract for how Shell interacts with Args. type RemoteExecRequest struct { + // OnOutput receives stdout/stderr chunks while the command runs. It is an + // observation hook only; callers must not retain the supplied bytes. + OnOutput func(stream string, chunk []byte) `json:"-"` + // Command is the executable name (Shell=false) or the shell expression // (Shell=true). Command string diff --git a/internal/sandbox/session_manager.go b/internal/sandbox/session_manager.go index 34447f07..deb35796 100644 --- a/internal/sandbox/session_manager.go +++ b/internal/sandbox/session_manager.go @@ -685,6 +685,8 @@ func (m *SessionBoundManager) WriteSessionFile( // flags select the installer working-directory allowlist and bootstrap. Both // ordinary and install calls currently execute as root. type ShellExecOptions struct { + OnOutput func(stream string, chunk []byte) + WorkDir string Timeout time.Duration Env map[string]string @@ -776,12 +778,13 @@ func (m *SessionBoundManager) ExecShellCommandWithOptions( start := time.Now() execResult, execErr := m.client.Exec(ctx, handle, RemoteExecRequest{ - Command: command, - Shell: true, - Env: opts.Env, - WorkDir: workDir, - User: user, - Timeout: timeout, + Command: command, + OnOutput: commandOutputCallback(ctx, opts.OnOutput), + Shell: true, + Env: opts.Env, + WorkDir: workDir, + User: user, + Timeout: timeout, }) duration := time.Since(start) return remoteExecuteResult(execResult, execErr, duration), nil diff --git a/internal/types/chat.go b/internal/types/chat.go index 55f5e1b8..69b9051e 100644 --- a/internal/types/chat.go +++ b/internal/types/chat.go @@ -221,6 +221,10 @@ const ( ResponseTypeToolCall ResponseType = "tool_call" // Tool result response type (for agent tool results) ResponseTypeToolResult ResponseType = "tool_result" + // ResponseTypeInstallOutput carries installer progress without completing a tool. + ResponseTypeInstallOutput ResponseType = "install_output" + // ResponseTypeCommandOutput updates the pending tool card without completing it. + ResponseTypeCommandOutput ResponseType = "command_output" // Error response type ResponseTypeError ResponseType = "error" // Reflection response type (for agent reflection)