Skip to content
Merged
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
18 changes: 15 additions & 3 deletions core/types/result.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,25 @@ func (j *JobResult) SetResult(text ActionState) {
}

// Finish marks the job as done and closes the ready channel.
//
// Finish is idempotent: a job may be finished from more than one code path
// (for example an early finish inside a tool decision followed by the regular
// completion). Closing the ready channel twice would panic with
// "close of closed channel" and take the whole agent down, so the first call
// wins: its error is kept and its finalizers run; later calls are no-ops.
func (j *JobResult) Finish(e error) {
j.Lock()
j.Error = e
select {
case <-j.ready:
// Already finished.
j.Unlock()
return
default:
j.Error = e
close(j.ready)
}
j.Unlock()

close(j.ready)

for _, f := range j.Finalizers {
f(j.Conversation)
}
Expand Down
29 changes: 29 additions & 0 deletions core/types/result_finish_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package types

import (
"errors"
"testing"

"github.com/sashabaranov/go-openai"
)

// A job finished twice must not panic (close of closed channel); the first
// error wins and the finalizers run exactly once.
func TestJobResultFinishIsIdempotent(t *testing.T) {
j := NewJobResult()
calls := 0
j.AddFinalizer(func(c []openai.ChatCompletionMessage) { calls++ })
j.Finish(errors.New("first"))
j.Finish(nil) // second call: must be a no-op
if j.Error == nil || j.Error.Error() != "first" {
t.Fatalf("first error must win, got %v", j.Error)
}
if calls != 1 {
t.Fatalf("finalizers must run once, ran %d times", calls)
}
select {
case <-j.ready:
default:
t.Fatal("ready channel must be closed after Finish")
}
}