Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

fix(agent): preserve tool errors and redact logs (#21533)

Sbaaoui Idriss2be16144212b
diff --git a/internal/agent/canvas/node_body.go b/internal/agent/canvas/node_body.go
index 0438d4e468..83b4f491c2 100644
--- a/internal/agent/canvas/node_body.go
+++ b/internal/agent/canvas/node_body.go
@@ -254,11 +254,16 @@ func realComponentBodyWithOptions(cpnID, componentClass, displayName string, com
cctx = runtime.BindComponentFraction(cctx, cpnID)
var out map[string]any
+ var componentOut map[string]any
invokeErr := runtime.TrackProgress(cpnID, runtime.ProgressCallbackFromContext(ctx), func() error {
var e error
out, e = runtime.TrackElapsed(componentClass, func() (map[string]any, error) {
- return comp.Invoke(runtime.WithComponentExecutionOptions(cctx, opts), dao.DB, in)
+ componentOut, e = comp.Invoke(runtime.WithComponentExecutionOptions(cctx, opts), dao.DB, in)
+ return componentOut, e
})
+ if out == nil {
+ out = componentOut
+ }
return e
})
if invokeErr != nil {
@@ -270,12 +275,12 @@ func realComponentBodyWithOptions(cpnID, componentClass, displayName string, com
common.Debug("agent: component invoke cancelled",
zap.String("component_id", cpnID),
zap.String("component_class", componentClass))
- return nil, fmt.Errorf("agent: component %q invoke: cancelled: %w", logName, invokeErr)
+ return out, fmt.Errorf("agent: component %q invoke: cancelled: %w", logName, invokeErr)
case errors.Is(invokeErr, context.DeadlineExceeded):
common.Error("agent: component invoke failed", invokeErr,
zap.String("component_id", cpnID),
zap.String("component_class", componentClass))
- return nil, fmt.Errorf("agent: component %q invoke: context deadline exceeded: %w", logName, invokeErr)
+ return out, fmt.Errorf("agent: component %q invoke: context deadline exceeded: %w", logName, invokeErr)
default:
// Surface the failure as a structured log line. The wrapped error
// already carries the full cause chain (e.g. deepseek DNS/timeout),
@@ -284,7 +289,7 @@ func realComponentBodyWithOptions(cpnID, componentClass, displayName string, com
common.Error("agent: component invoke failed", invokeErr,
zap.String("component_id", cpnID),
zap.String("component_class", componentClass))
- return nil, fmt.Errorf("agent: component %q invoke: %w", logName, invokeErr)
+ return out, fmt.Errorf("agent: component %q invoke: %w", logName, invokeErr)
}
}
if out == nil {
diff --git a/internal/agent/canvas/node_body_timeout_test.go b/internal/agent/canvas/node_body_timeout_test.go
index b3141c19a5..cb770ee2f6 100644
--- a/internal/agent/canvas/node_body_timeout_test.go
+++ b/internal/agent/canvas/node_body_timeout_test.go
@@ -25,6 +25,7 @@ package canvas
import (
"context"
+ "encoding/json"
"errors"
"strings"
"testing"
@@ -38,12 +39,14 @@ import (
// cancelled.
type blockingComponent struct{}
-type failingComponent struct{}
+type failingComponent struct {
+ output map[string]any
+}
func (f *failingComponent) Name() string { return "failing" }
func (f *failingComponent) Invoke(_ context.Context, _ *gorm.DB, _ map[string]any) (map[string]any, error) {
- return nil, errors.New("boom")
+ return f.output, errors.New("boom")
}
func (f *failingComponent) Stream(_ context.Context, _ map[string]any) (<-chan map[string]any, error) {
@@ -105,6 +108,94 @@ func TestRealComponentBody_UsesDisplayNameInError(t *testing.T) {
}
}
+func TestWithStateBracket_PersistsToolInvocationsOnComponentError(t *testing.T) {
+ invocations := []map[string]any{{"tool_name": "search"}}
+ state := runtime.NewCanvasState("run-agent", "session-agent")
+ events := make(chan RunEvent, 2)
+ ctx := WithRunMeta(WithState(t.Context(), state), &RunMeta{Events: events})
+ component := &failingComponent{output: map[string]any{"tool_invocations": invocations}}
+ body := withStateBracket("agent_0", "Agent", realComponentBody("agent_0", "Agent", "Agent", component))
+
+ if _, err := body(ctx, nil); err == nil {
+ t.Fatal("expected component error")
+ }
+ <-events // node_started
+ finished := <-events
+ if finished.Type != "node_finished" {
+ t.Fatalf("event type = %q, want node_finished", finished.Type)
+ }
+ var payload map[string]any
+ if err := json.Unmarshal([]byte(finished.Data), &payload); err != nil {
+ t.Fatalf("unmarshal node_finished: %v", err)
+ }
+ outputs, ok := payload["outputs"].(map[string]any)
+ if !ok {
+ t.Fatalf("node_finished outputs = %T, want map", payload["outputs"])
+ }
+ got, ok := outputs["tool_invocations"].([]any)
+ if !ok || len(got) != 1 {
+ t.Fatalf("node_finished tool_invocations = %#v, want one invocation", outputs["tool_invocations"])
+ }
+ if got[0].(map[string]any)["tool_name"] != "search" {
+ t.Fatalf("node_finished invocation = %#v, want search", got[0])
+ }
+}
+
+func TestBuildWorkflow_PersistsOutputsAndFinishesNodeOnComponentError(t *testing.T) {
+ previousFactory := runtime.DefaultFactory()
+ runtime.SetDefaultFactory(func(string, map[string]any) (runtime.Component, error) {
+ return &failingComponent{output: map[string]any{
+ "tool_invocations": []map[string]any{{"tool_name": "search"}},
+ }}, nil
+ })
+ t.Cleanup(func() { runtime.SetDefaultFactory(previousFactory) })
+
+ compiled, err := Compile(t.Context(), &Canvas{Components: map[string]CanvasComponent{
+ "agent_0": {Obj: CanvasComponentObj{ComponentName: "Agent", Params: map[string]any{}}},
+ }})
+ if err != nil {
+ t.Fatalf("Compile: %v", err)
+ }
+ state := runtime.NewCanvasState("run-agent-error", "session-agent-error")
+ events := make(chan RunEvent, 4)
+ ctx := WithRunMeta(WithState(t.Context(), state), &RunMeta{Events: events})
+ if _, err := compiled.Workflow.Invoke(ctx, map[string]any{}); err == nil {
+ t.Fatal("expected workflow error")
+ }
+
+ got, stateErr := state.GetVar("agent_0@tool_invocations")
+ invocations, ok := got.([]map[string]any)
+ if stateErr != nil || !ok || len(invocations) != 1 {
+ t.Fatalf("tool_invocations = %#v, state error = %v; want one recorded invocation", got, stateErr)
+ }
+ finishedCount := 0
+ persisted := false
+ for len(events) > 0 {
+ event := <-events
+ if event.Type != "node_finished" {
+ continue
+ }
+ finishedCount++
+ var payload map[string]any
+ if err := json.Unmarshal([]byte(event.Data), &payload); err != nil {
+ t.Fatalf("unmarshal node_finished: %v", err)
+ }
+ outputs, _ := payload["outputs"].(map[string]any)
+ if invocations, ok := outputs["tool_invocations"].([]any); ok && len(invocations) == 1 {
+ persisted = true
+ if nodeErr, ok := payload["error"].(string); !ok || !strings.Contains(nodeErr, "boom") {
+ t.Errorf("node_finished error = %v, want component failure", payload["error"])
+ }
+ }
+ }
+ if finishedCount != 1 {
+ t.Errorf("node_finished events = %d, want 1", finishedCount)
+ }
+ if !persisted {
+ t.Fatal("node_finished event did not include tool_invocations")
+ }
+}
+
// TestRealComponentBody_NoTimeoutWhenFast verifies that a component returning
// immediately does not incur any timeout-induced latency or error wrapping.
func TestRealComponentBody_NoTimeoutWhenFast(t *testing.T) {
diff --git a/internal/agent/canvas/scheduler.go b/internal/agent/canvas/scheduler.go
index 5be179b7e0..7936ce3a17 100644
--- a/internal/agent/canvas/scheduler.go
+++ b/internal/agent/canvas/scheduler.go
@@ -20,6 +20,7 @@ package canvas
import (
"context"
+ "errors"
"fmt"
"sort"
"strings"
@@ -602,7 +603,24 @@ func BuildWorkflow(ctx context.Context, c *Canvas) (*compose.Workflow[map[string
}
return result, postErr
}
- lambda := compose.InvokableLambda[map[string]any, map[string]any](body)
+ // Eino skips statePost on errors, so persist failed node outputs here.
+ nodeBody := func(ctx context.Context, in map[string]any) (map[string]any, error) {
+ out, invokeErr := body(ctx, in)
+ if invokeErr == nil || IsInterruptError(invokeErr) {
+ return out, invokeErr
+ }
+ if out == nil {
+ out = make(map[string]any, 2)
+ }
+ out["__cpn_id__"] = cpnID
+ stateErr := compose.ProcessState(ctx, func(ctx context.Context, state *CanvasState) error {
+ _, postErr := statePost(ctx, out, state)
+ nodeFinishedNow(ctx, state, cpnID, componentName, componentName, invokeErr)
+ return postErr
+ })
+ return out, errors.Join(invokeErr, stateErr)
+ }
+ lambda := compose.InvokableLambda[map[string]any, map[string]any](nodeBody)
node := wf.AddLambdaNode(cpnID, lambda,
compose.WithStatePreHandler[map[string]any, *CanvasState](nodePre),
compose.WithStatePostHandler[map[string]any, *CanvasState](nodePost),
diff --git a/internal/agent/component/agent.go b/internal/agent/component/agent.go
index 316d58767d..fd73eda402 100644
--- a/internal/agent/component/agent.go
+++ b/internal/agent/component/agent.go
@@ -1091,15 +1091,20 @@ func (c *AgentComponent) invokeNow(ctx context.Context, db *gorm.DB, inputs map[
}
}
if err != nil {
- if invocations := p.toolInvocations.snapshot(); len(invocations) > 0 {
- return map[string]any{"tool_invocations": invocations}, fmt.Errorf("component: Agent.Invoke: %w", err)
- }
+ invocations := p.toolInvocations.snapshot()
// Only step exhaustion is an _ERROR output. Model/tool failures must
// stop execution before downstream nodes read an absent content output.
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) || !errors.Is(err, compose.ErrExceedMaxSteps) {
+ if len(invocations) > 0 {
+ return map[string]any{"tool_invocations": invocations}, fmt.Errorf("component: Agent.Invoke: %w", err)
+ }
return nil, fmt.Errorf("component: Agent.Invoke: %w", err)
}
- return map[string]any{"_ERROR": "**ERROR**: " + runtime.MarkdownSafeErrorText(err)}, nil
+ out := map[string]any{"_ERROR": "**ERROR**: " + runtime.MarkdownSafeErrorText(err)}
+ if len(invocations) > 0 {
+ out["tool_invocations"] = invocations
+ }
+ return out, nil
}
// Post-stream citation grounding. When Cite is enabled and
// the canvas state has recorded retrieval chunks (populated
diff --git a/internal/agent/component/agent_test.go b/internal/agent/component/agent_test.go
index f648661aad..0a08689c0c 100644
--- a/internal/agent/component/agent_test.go
+++ b/internal/agent/component/agent_test.go
@@ -821,6 +821,51 @@ func TestAgent_ExhaustRoundsError(t *testing.T) {
}
}
+func TestAgent_ToolInvocationsWithRunnerErrors(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ runnerErr error
+ wantError bool
+ wantEnvelope bool
+ }{
+ {name: "max steps", runnerErr: fmt.Errorf("[GraphRunError] %w", compose.ErrExceedMaxSteps), wantEnvelope: true},
+ {name: "other failure", runnerErr: errors.New("provider failed"), wantError: true},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ withAgentRunner(t, func(ctx context.Context, p AgentParam) (*schema.Message, error) {
+ recorder := &toolInvocationRecordingTool{
+ InvokableTool: &referenceRecordingFakeTool{out: `{"ok":true}`},
+ name: "search",
+ recorder: p.toolInvocations,
+ }
+ if _, err := recorder.InvokableRun(ctx, `{"query":"test"}`); err != nil {
+ return nil, err
+ }
+ return nil, tt.runnerErr
+ })
+
+ out, err := NewAgentComponent(AgentParam{ModelID: "stub", MaxRounds: 1}).Invoke(t.Context(), nil, map[string]any{"user_prompt": "test"})
+ if tt.wantError {
+ if err == nil || !errors.Is(err, tt.runnerErr) {
+ t.Fatalf("Invoke error = %v, want wrapped %v", err, tt.runnerErr)
+ }
+ } else if err != nil {
+ t.Fatalf("Invoke: %v", err)
+ }
+ if tt.wantEnvelope {
+ if got := out["_ERROR"]; got != "**ERROR**: [GraphRunError] exceeds max steps" {
+ t.Fatalf("_ERROR = %v, want step-exhaustion envelope", got)
+ }
+ } else if _, ok := out["_ERROR"]; ok {
+ t.Fatalf("unexpected _ERROR output: %#v", out["_ERROR"])
+ }
+ if invocations, ok := out["tool_invocations"].([]map[string]any); !ok || len(invocations) != 1 {
+ t.Fatalf("tool_invocations = %#v, want one invocation", out["tool_invocations"])
+ }
+ })
+ }
+}
+
func TestAgent_MissingModelID(t *testing.T) {
c := NewAgentComponent(AgentParam{MaxRounds: 1})
_, err := c.Invoke(t.Context(), nil, map[string]any{"user_prompt": "x"})
diff --git a/internal/agent/component/message.go b/internal/agent/component/message.go
index e912b7f0d8..551290fdcc 100644
--- a/internal/agent/component/message.go
+++ b/internal/agent/component/message.go
@@ -474,6 +474,11 @@ func (m *MessageComponent) resolveDeferredTemplate(ctx context.Context, text str
if targetNodeID == "" && strings.Contains(ref, "@") {
targetNodeID, _, _ = strings.Cut(ref, "@")
}
+ if targetNodeID != "" && result != nil {
+ for key, output := range result {
+ state.SetVar(targetNodeID, key, output)
+ }
+ }
if err != nil {
if targetNodeID != "" {
runtime.CompleteDeferredNode(ctx, targetNodeID, err)
@@ -498,11 +503,6 @@ func (m *MessageComponent) resolveDeferredTemplate(ctx context.Context, text str
}
}
if targetNodeID != "" {
- if result != nil {
- for key, output := range result {
- state.SetVar(targetNodeID, key, output)
- }
- }
runtime.CompleteDeferredNode(ctx, targetNodeID, nil)
}
resolved := runtime.ResolveTemplateForDisplay(text[start:end], state)
diff --git a/internal/agent/component/message_test.go b/internal/agent/component/message_test.go
index 10e8051d8b..9f8d0b907f 100644
--- a/internal/agent/component/message_test.go
+++ b/internal/agent/component/message_test.go
@@ -466,6 +466,41 @@ func TestMessage_DeferredStreamOpenFailure(t *testing.T) {
}
}
+func TestMessage_DeferredStreamErrorPersistsOutputsBeforeCompletion(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ result map[string]any
+ err error
+ }{
+ {name: "provider error", result: map[string]any{"tool_invocations": []map[string]any{{"tool_name": "search"}}}, err: errors.New("provider failed")},
+ {name: "step exhaustion", result: map[string]any{"_ERROR": "**ERROR**: exceeds max steps", "tool_invocations": []map[string]any{{"tool_name": "search"}}}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ c, _ := NewMessageComponent(nil)
+ state := canvas.NewCanvasState("run-deferred-output", "task-deferred-output")
+ state.SetVar("agent_0", "content", &runtime.DeferredStream{
+ Open: func(context.Context, runtime.AgentDeltaSink) (map[string]any, error) {
+ return tc.result, tc.err
+ },
+ })
+ ctx := runtime.WithDeferredNodeRegistry(withStateForTest(t.Context(), state))
+ var outputAtCompletion any
+ runtime.RegisterDeferredNode(ctx, "agent_0", func(error) {
+ outputAtCompletion, _ = state.GetVar("agent_0@tool_invocations")
+ })
+
+ _, err := c.Invoke(ctx, nil, map[string]any{"text": "{{agent_0@content}}"})
+ if err == nil {
+ t.Fatal("expected deferred stream failure")
+ }
+ invocations, ok := outputAtCompletion.([]map[string]any)
+ if !ok || len(invocations) != 1 || invocations[0]["tool_name"] != "search" {
+ t.Fatalf("tool_invocations at completion = %#v, want recorded search invocation", outputAtCompletion)
+ }
+ })
+ }
+}
+
func TestMessage_FormalizedContentFallback(t *testing.T) {
c, _ := NewMessageComponent(nil)
state := canvas.NewCanvasState("run-5", "task-5")
diff --git a/internal/agent/component/reference_recording_tool.go b/internal/agent/component/reference_recording_tool.go
index 6003d072fc..17c792bafe 100644
--- a/internal/agent/component/reference_recording_tool.go
+++ b/internal/agent/component/reference_recording_tool.go
@@ -35,7 +35,8 @@ const maxToolLogResultRunes = 4096
const maxToolLogInputRunes = 8192
const maxToolLogInvocations = 64
-var sensitiveToolLogText = regexp.MustCompile(`(?i)(api[_-]?key|access[_-]?token|authorization|password|secret)(["']?\s*[:=]\s*["']?)([^"'\s,}]+)`)
+var sensitiveToolLogText = regexp.MustCompile(`(?i)(api[_-]?key|access[_-]?token|refresh[_-]?token|auth[_-]?token|authorization|auth|token|password|secret)(["']?\s*[:=]\s*)("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|(?:bearer|basic)\s+[^\s,}]+|[^"'\s,}]+)`)
+var bearerToolLogText = regexp.MustCompile(`(?i)\b(?:bearer|basic)\s+[^\s"',}]+`)
type toolInvocationRecorder struct {
mu sync.Mutex
@@ -79,13 +80,7 @@ func (t *toolInvocationRecordingTool) InvokableRun(ctx context.Context, argsJSON
if err != nil {
logResult = err.Error()
}
- var resultJSON any
- if json.Unmarshal([]byte(logResult), &resultJSON) == nil {
- if redacted, err := json.Marshal(redactToolLogValue(resultJSON)); err == nil {
- logResult = string(redacted)
- }
- }
- logResult = sensitiveToolLogText.ReplaceAllString(logResult, "$1$2[REDACTED]")
+ logResult = redactToolLogText(logResult)
redactedArgs := redactToolLogValue(args)
if encoded, marshalErr := json.Marshal(redactedArgs); marshalErr == nil && len(encoded) > maxToolLogInputRunes {
redactedArgs = map[string]any{"_truncated": true, "preview": utility.TruncateRunes(string(encoded), maxToolLogInputRunes)}
@@ -99,7 +94,7 @@ func (t *toolInvocationRecordingTool) InvokableRun(ctx context.Context, argsJSON
"status": status,
}
if err != nil {
- entry["error"] = utility.TruncateRunes(err.Error(), maxToolLogResultRunes)
+ entry["error"] = utility.TruncateRunes(redactToolLogText(err.Error()), maxToolLogResultRunes)
}
t.recorder.mu.Lock()
if len(t.recorder.entries) < maxToolLogInvocations {
@@ -127,12 +122,14 @@ func wrapToolInvocationRecording(tools []einotool.BaseTool, recorder *toolInvoca
func redactToolLogValue(value any) any {
switch v := value.(type) {
+ case string:
+ return redactToolLogText(v)
case map[string]any:
out := make(map[string]any, len(v))
for key, child := range v {
lower := strings.ToLower(key)
normalized := strings.NewReplacer("_", "", "-", "").Replace(lower)
- if strings.Contains(normalized, "apikey") || strings.Contains(lower, "token") || strings.Contains(lower, "password") || strings.Contains(lower, "secret") || lower == "authorization" {
+ if strings.Contains(normalized, "apikey") || strings.Contains(lower, "token") || strings.Contains(lower, "password") || strings.Contains(lower, "secret") || lower == "auth" || lower == "authorization" {
out[key] = "[REDACTED]"
} else {
out[key] = redactToolLogValue(child)
@@ -150,6 +147,25 @@ func redactToolLogValue(value any) any {
}
}
+func redactToolLogText(value string) string {
+ var structured any
+ if json.Unmarshal([]byte(value), &structured) == nil {
+ if redacted, err := json.Marshal(redactToolLogValue(structured)); err == nil {
+ return string(redacted)
+ }
+ }
+ value = sensitiveToolLogText.ReplaceAllStringFunc(value, func(match string) string {
+ parts := sensitiveToolLogText.FindStringSubmatch(match)
+ redacted := parts[1] + parts[2]
+ credential := parts[3]
+ if len(credential) >= 2 && credential[0] == credential[len(credential)-1] && (credential[0] == '"' || credential[0] == '\'') {
+ return redacted + string(credential[0]) + "[REDACTED]" + string(credential[0])
+ }
+ return redacted + "[REDACTED]"
+ })
+ return bearerToolLogText.ReplaceAllString(value, "[REDACTED]")
+}
+
// referenceRecordingTool decorates an Agent tool so each invocation records
// the retrieval references it produced into the canvas state. Canvas tool
// nodes already do this in ToolBackedComponent.Invoke; tools called from the
diff --git a/internal/agent/component/reference_recording_tool_test.go b/internal/agent/component/reference_recording_tool_test.go
index a7a2a923cd..b3f941daf6 100644
--- a/internal/agent/component/reference_recording_tool_test.go
+++ b/internal/agent/component/reference_recording_tool_test.go
@@ -18,8 +18,10 @@ package component
import (
"context"
+ "encoding/json"
"errors"
"fmt"
+ "strings"
"testing"
einotool "github.com/cloudwego/eino/components/tool"
@@ -95,6 +97,111 @@ func TestReferenceRecordingTool_SkipsErrorsAndNonJSON(t *testing.T) {
}
}
+func TestToolInvocationRecordingToolRedactsSensitiveText(t *testing.T) {
+ recorder := &toolInvocationRecorder{}
+ inner := &referenceRecordingFakeTool{err: errors.New("request failed: Authorization: Bearer error-secret")}
+ tool := &toolInvocationRecordingTool{InvokableTool: inner, name: "fake_search", recorder: recorder}
+ _, err := tool.InvokableRun(t.Context(), `{"note":"Authorization: Bearer argument-secret","detail":"access_token=other-secret"}`)
+ if err == nil {
+ t.Fatal("expected inner tool error")
+ }
+
+ entries := recorder.snapshot()
+ if len(entries) != 1 {
+ t.Fatalf("recorded entries = %d, want 1", len(entries))
+ }
+ entry := entries[0]
+ for _, field := range []string{"result", "error"} {
+ got, _ := entry[field].(string)
+ if strings.Contains(got, "error-secret") || strings.Contains(strings.ToLower(got), "bearer") {
+ t.Errorf("%s contains unredacted credential: %q", field, got)
+ }
+ }
+ arguments, ok := entry["arguments"].(map[string]any)
+ if !ok {
+ t.Fatalf("arguments = %T, want map", entry["arguments"])
+ }
+ for key, secret := range map[string]string{"note": "argument-secret", "detail": "other-secret"} {
+ got, _ := arguments[key].(string)
+ if strings.Contains(got, secret) || strings.Contains(strings.ToLower(got), "bearer") {
+ t.Errorf("argument %q contains unredacted credential: %q", key, got)
+ }
+ }
+}
+
+func TestToolInvocationRecordingToolRedactsQuotedAndStructuredCredentials(t *testing.T) {
+ rawError := `{"message":"request failed","refresh_token":"refresh secret with spaces","authToken":"auth secret with spaces","authorization":"Basic basic-secret"}`
+ args := `{"note":"authorization: \"Bearer argument secret with spaces\"","detail":"token=\"quoted token secret\"","auth_note":"auth=\"quoted auth secret with spaces\""}`
+ recorder := &toolInvocationRecorder{}
+ inner := &referenceRecordingFakeTool{out: `{"ok":false}`, err: errors.New(rawError)}
+ tool := &toolInvocationRecordingTool{InvokableTool: inner, name: "fake_search", recorder: recorder}
+ if _, err := tool.InvokableRun(t.Context(), args); err == nil {
+ t.Fatal("expected inner tool error")
+ }
+
+ entries := recorder.snapshot()
+ if len(entries) != 1 {
+ t.Fatalf("recorded entries = %d, want 1", len(entries))
+ }
+ for _, field := range []string{"result", "error"} {
+ got, _ := entries[0][field].(string)
+ for _, secret := range []string{"refresh secret", "auth secret", "basic-secret", "Bearer argument", "argument secret", "quoted token secret", "quoted auth secret", "basic ", "bearer "} {
+ if strings.Contains(got, secret) {
+ t.Errorf("%s contains unredacted %q: %s", field, secret, got)
+ }
+ }
+ }
+ encodedArgs, err := json.Marshal(entries[0]["arguments"])
+ if err != nil {
+ t.Fatalf("marshal redacted arguments: %v", err)
+ }
+ for _, secret := range []string{"Bearer argument", "argument secret", "quoted token secret", "quoted auth secret"} {
+ if strings.Contains(string(encodedArgs), secret) {
+ t.Errorf("arguments contain unredacted %q: %s", secret, encodedArgs)
+ }
+ }
+}
+
+func TestToolInvocationRecordingToolRedactsStructuredResult(t *testing.T) {
+ recorder := &toolInvocationRecorder{}
+ inner := &referenceRecordingFakeTool{out: `{"authorization":"Basic result-secret","refresh_token":"refresh result secret"}`}
+ tool := &toolInvocationRecordingTool{InvokableTool: inner, name: "fake_search", recorder: recorder}
+ if _, err := tool.InvokableRun(t.Context(), `{}`); err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ got, _ := recorder.snapshot()[0]["result"].(string)
+ for _, secret := range []string{"result-secret", "refresh result secret", "Basic"} {
+ if strings.Contains(got, secret) {
+ t.Errorf("result contains unredacted %q: %s", secret, got)
+ }
+ }
+}
+
+func TestRedactToolLogTextCredentials(t *testing.T) {
+ for _, input := range []string{
+ `Authorization: Basic hidden-credential`,
+ `Authorization: Bearer hidden-credential`,
+ `Authorization: hidden-credential`,
+ `Authorization: "Bearer hidden-credential with spaces"`,
+ `authorization='Basic hidden-credential with spaces'`,
+ `token=hidden-credential`,
+ `refresh_token=hidden-credential`,
+ `authToken=hidden-credential`,
+ `"token": "hidden-credential with spaces"`,
+ `"auth": "hidden-credential with spaces"`,
+ `api_key=hidden-credential`,
+ `password='hidden-credential with spaces'`,
+ `secret=hidden-credential`,
+ } {
+ t.Run(input, func(t *testing.T) {
+ got := redactToolLogText(input)
+ if strings.Contains(got, "hidden-credential") || strings.Contains(got, "with spaces") || !strings.Contains(got, "[REDACTED]") {
+ t.Fatalf("redacted text = %q, want complete credential removed", got)
+ }
+ })
+ }
+}
+
func TestReferenceRecordingTool_KeepsSameTitleDifferentDocumentIDs(t *testing.T) {
state := runtime.NewCanvasState("run-refs", "task-refs")
ctx := runtime.WithState(t.Context(), state)
diff --git a/web/src/pages/agent/log-sheet/tool-timeline-item.tsx b/web/src/pages/agent/log-sheet/tool-timeline-item.tsx
index 70e36cf2f8..4d00fe9382 100644
--- a/web/src/pages/agent/log-sheet/tool-timeline-item.tsx
+++ b/web/src/pages/agent/log-sheet/tool-timeline-item.tsx
@@ -180,7 +180,9 @@ const ToolTimelineItem = ({
: 'bg-state--success',
)}
>
- <span className="sr-only">Online</span>
+ <span className="sr-only">
+ {tool.status === 'error' ? 'Error' : 'Online'}
+ </span>
</span>
</div>
</AccordionTrigger>