@@ -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)