Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions internal/httpapi/assistant_diagnostic_evidence.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"log"
"math"
"regexp"
"strconv"
"strings"
Expand Down Expand Up @@ -84,7 +85,8 @@ func (a *assistantDiagnosticAttempt) process(event domain.TelemetryEvent) {
p := attempt.Process
switch event.Name {
case "process.started":
p.PID, _ = event.Attributes["pid"].(int)
pid, _ := diagnosticProcessInt64(event.Attributes["pid"])
p.PID = int(pid)
p.State, p.StartedAt = "running", &now
case "process.start_failed":
p.State, p.FinishedAt = "start_failed", &now
Expand All @@ -94,9 +96,10 @@ func (a *assistantDiagnosticAttempt) process(event domain.TelemetryEvent) {
}
p.FinishedAt = &now
p.Signal, _ = event.Attributes["signal"].(string)
p.UserCPUMs, _ = event.Attributes["userCpuMs"].(int64)
p.SystemCPUMs, _ = event.Attributes["systemCpuMs"].(int64)
if code, ok := event.Attributes["exitCode"].(int); ok {
p.UserCPUMs, _ = diagnosticProcessInt64(event.Attributes["userCpuMs"])
p.SystemCPUMs, _ = diagnosticProcessInt64(event.Attributes["systemCpuMs"])
if value, ok := diagnosticProcessInt64(event.Attributes["exitCode"]); ok {
code := int(value)
attempt.ExitCode = &code
}
if incomplete, _ := event.Attributes["outputIncomplete"].(bool); incomplete {
Expand Down Expand Up @@ -129,6 +132,25 @@ func (a *assistantDiagnosticAttempt) process(event domain.TelemetryEvent) {
})
}

// In-process events use Go integers; the runner JSON transport decodes map
// values as float64 (or json.Number when UseNumber is enabled).
func diagnosticProcessInt64(value any) (int64, bool) {
switch v := value.(type) {
case int:
return int64(v), true
case int64:
return v, true
case float64:
if v >= -0x1p63 && v < 0x1p63 && math.Trunc(v) == v {
return int64(v), true
}
case json.Number:
n, err := v.Int64()
return n, err == nil
}
return 0, false
}

var (
diagnosticRequestID = regexp.MustCompile(`(?i)\b(?:request[ _-]?id|x-request-id)\s*[=:]\s*["']?([A-Za-z0-9_.:/-]{4,160})`)
diagnosticTraceID = regexp.MustCompile(`(?i)\b(?:trace[ _-]?id|x-trace-id)\s*[=:]\s*["']?([A-Za-z0-9_.:/-]{4,160})`)
Expand Down
86 changes: 86 additions & 0 deletions internal/httpapi/assistant_diagnostic_process_transport_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package httpapi

import (
"bytes"
"context"
"encoding/json"
"errors"
"testing"
"time"

"agentflow/internal/domain"
"agentflow/internal/runtime"
)

func TestAssistantDiagnosticProcessEvidenceSurvivesRunnerJSON(t *testing.T) {
for _, transport := range []string{"direct", "runner JSON", "runner JSON numbers"} {
t.Run(transport, func(t *testing.T) {
g := domain.AssistantGeneration{ID: transport, Status: "running", StartedAt: time.Now().UTC()}
d := newAssistantDiagnosticsCollector(g)
a := d.begin("codebuddy", "test-model", false, domain.User{})
started := time.Now().UTC()
events := []domain.TelemetryEvent{
{Name: "process.started", Timestamp: started, Message: "private-command-argument", Attributes: map[string]any{"pid": 1234}},
{Name: "process.stdout", Message: "output"},
{Name: "process.finished", Attributes: map[string]any{"exitCode": 7, "signal": "terminated", "userCpuMs": int64(12), "systemCpuMs": int64(3)}},
}
for _, event := range events {
if transport != "direct" {
raw, err := json.Marshal(event)
if err != nil {
t.Fatal(err)
}
var decoded domain.TelemetryEvent
decoder := json.NewDecoder(bytes.NewReader(raw))
if transport == "runner JSON numbers" {
decoder.UseNumber()
}
if err := decoder.Decode(&decoded); err != nil {
t.Fatal(err)
}
event = decoded
}
a.process(event)
if event.Name == "process.started" {
p := d.snapshot(g).Attempts[0].Process
if p.State != "running" || p.PID != 1234 || p.StartedAt == nil || !p.StartedAt.Equal(started) {
t.Fatalf("lost started evidence: %+v", p)
}
}
}
report := d.snapshot(g)
attempt := report.Attempts[0]
p := attempt.Process
if p.State != "exited" || p.StdoutLines != 1 || p.FinishedAt == nil || p.Signal != "terminated" || p.UserCPUMs != 12 || p.SystemCPUMs != 3 || attempt.ExitCode == nil || *attempt.ExitCode != 7 {
t.Fatalf("lost finished evidence: %+v process=%+v", attempt, p)
}
raw, _ := json.Marshal(report)
if bytes.Contains(raw, []byte("private-command-argument")) {
t.Fatal("diagnostics exposed command arguments")
}
})
}
}

func TestConversationExecutorKeepsExitEvidenceAfterCancellation(t *testing.T) {
h, user := workbenchFixture(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
session := &AgentToolSession{ctx: ctx, ChatOwnerID: user.ID, ChatSessionID: "process-cancel-evidence", User: user}
var events []domain.TelemetryEvent
_, err := h.conversationExecutor(session, t.TempDir())(ctx, "", runtime.CommandSpec{Argv: []string{"sh", "-c", "printf 'ready\\n'; sleep 30"}}, runtime.RunCredentials{}, func(event domain.TelemetryEvent) {
events = append(events, event)
if event.Name == "process.stdout" {
cancel()
}
})
if !errors.Is(err, context.Canceled) {
t.Fatalf("lost cancellation outcome: %v", err)
}
if len(events) == 0 || events[len(events)-1].Name != "process.finished" {
t.Fatalf("stopped process lost its final evidence: %+v", events)
}
if _, ok := events[len(events)-1].Attributes["exitCode"]; !ok {
t.Fatal("stopped process lost its exit code")
}
}
32 changes: 31 additions & 1 deletion internal/httpapi/assistant_process.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ func (h *assistantHandlers) conversationExecutor(s *AgentToolSession, root strin
if err != nil {
return "", err
}
after := int64(0)
var stopOnce sync.Once
stopProcess := func() {
stopOnce.Do(func() {
Expand All @@ -245,6 +246,26 @@ func (h *assistantHandlers) conversationExecutor(s *AgentToolSession, root strin
defer cancel()
if err := waitConversationProcessStop(stopCtx, id, call, nil); err != nil {
assistantDiagnosticsFrom(ctx).platform("cli.stop_abandoned", fmt.Sprintf("停止原生进程超过 %s 仍未确认(%v),放弃等待", conversationProcessStopTimeout, err), s.User)
return
}
// Cancellation ends the normal poll loop before the process exits.
// Drain remaining lifecycle evidence with the same bounded cleanup
// context, without replaying protocol output after the turn stopped.
for sink != nil {
result, err := call(stopCtx, runtime.ConversationProcessRequest{Operation: "poll", ID: id, After: after})
if err != nil {
assistantDiagnosticsFrom(ctx).platform("cli.exit_evidence_unavailable", "停止后读取进程退出证据失败:"+err.Error(), s.User)
return
}
for _, event := range result.Events {
if event.Name == "process.started" || event.Name == "process.start_failed" || event.Name == "process.finished" {
sink(event)
}
}
after = result.Sequence
if result.Done {
return
}
}
})
}
Expand Down Expand Up @@ -298,7 +319,6 @@ func (h *assistantHandlers) conversationExecutor(s *AgentToolSession, root strin
}
}()
}
after := int64(0)
for {
if err := ioCtx.Err(); err != nil {
return "", err
Expand All @@ -311,6 +331,16 @@ func (h *assistantHandlers) conversationExecutor(s *AgentToolSession, root strin
}
select {
case inputErr := <-inputErrors:
// A final poll may race a trailing stdin error. Keep its exit
// evidence even when Done has already disabled stop cleanup.
if pollErr == nil {
for _, event := range result.Events {
if sink != nil && (event.Name == "process.started" || event.Name == "process.start_failed" || event.Name == "process.finished") {
sink(event)
}
}
after = result.Sequence
}
return "", inputErr
default:
}
Expand Down
7 changes: 6 additions & 1 deletion internal/runtime/conversation_process.go
Original file line number Diff line number Diff line change
Expand Up @@ -693,7 +693,12 @@ func (p *ConversationProcessPool) start(ctx context.Context, root, workspace str
}
}()
sink := func(ev domain.TelemetryEvent) {
if ev.Name != "process.stdout" && ev.Name != "process.stderr" {
switch ev.Name {
case "process.started":
// Keep lifecycle metadata without forwarding argv or prompts.
ev.Message = ""
case "process.stdout", "process.stderr", "process.start_failed", "process.finished":
default:
return
}
proc.mu.Lock()
Expand Down
83 changes: 83 additions & 0 deletions internal/runtime/conversation_process_evidence_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package runtime

import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"

"agentflow/internal/domain"
)

func TestConversationProcessPreservesLifecycleEvidence(t *testing.T) {
for _, tt := range []struct {
name string
code int
startFail bool
}{
{name: "success"},
{name: "nonzero exit", code: 7},
{name: "start failure", startFail: true},
} {
t.Run(tt.name, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
root := t.TempDir()
argv := []string{"sh", "-c", "printf 'out\\n'; printf 'err\\n' >&2; exit 0", "private-argv-marker"}
if tt.code != 0 {
argv[2] = "printf 'out\\n'; exit 7"
}
if tt.startFail {
bin := filepath.Join(t.TempDir(), "broken-cli")
if err := os.WriteFile(bin, []byte("#!/missing-loopforge-interpreter\n"), 0700); err != nil {
t.Fatal(err)
}
argv = []string{bin, "private-argv-marker"}
}
pool := &ConversationProcessPool{}
started, err := pool.Handle(ctx, root, "", nil, ConversationProcessRequest{Operation: "start", Command: &ConversationCommand{Argv: argv}}, nil)
if err != nil {
t.Fatal(err)
}
var events []domain.TelemetryEvent
var after int64
for {
result, err := pool.Handle(ctx, root, "", nil, ConversationProcessRequest{Operation: "poll", ID: started.ID, After: after}, nil)
if err != nil {
t.Fatal(err)
}
events = append(events, result.Events...)
after = result.Sequence
if result.Done {
if (result.Error != "") != (tt.startFail || tt.code != 0) {
t.Fatalf("unexpected process error: %q", result.Error)
}
break
}
}
first := "process.started"
if tt.startFail {
first = "process.start_failed"
}
if len(events) < 2 || events[0].Name != first || events[len(events)-1].Name != "process.finished" {
t.Fatalf("missing or unordered process lifecycle: %+v", events)
}
for _, event := range events {
if strings.Contains(event.Message, "private-argv-marker") {
t.Fatalf("process telemetry exposed command arguments: %+v", event)
}
}
if !tt.startFail {
if pid, _ := events[0].Attributes["pid"].(int); pid <= 0 {
t.Fatalf("missing process PID: %+v", events[0])
}
last := events[len(events)-1]
if code, ok := last.Attributes["exitCode"].(int); !ok || code != tt.code {
t.Fatalf("missing exit code %d: %+v", tt.code, last)
}
}
})
}
}
4 changes: 3 additions & 1 deletion internal/runtime/conversation_process_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ func conversationPoll(t *testing.T, p *ConversationProcessPool, ctx context.Cont
t.Fatal(err)
}
for _, e := range r.Events {
out.WriteString(e.Message)
if e.Name == "process.stdout" || e.Name == "process.stderr" {
out.WriteString(e.Message)
}
}
after = r.Sequence
if r.Done {
Expand Down