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
12 changes: 12 additions & 0 deletions pkg/agent/loop_iteration.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package agent

import (
"context"
"errors"
"fmt"
"sync"

Expand Down Expand Up @@ -54,6 +55,17 @@ func (al *AgentLoop) runIteration(ctx context.Context, sessionKey string, stream
finalContent, result, err := al.callLLMWithRetry(ctx, st, msgsForLLM)
if err != nil {
al.saveSession(ctx, sessionKey, *msgs)
// A cancel that lands while the provider stream is in flight surfaces
// as a provider error. Classify it as cancellation (not an LLM
// failure) so adopters' errors.Is(err, ErrContextCancelled) checks
// fire — mirroring the pre-call cancel path above.
if cause := ctx.Err(); cause != nil || errors.Is(err, context.Canceled) {
if cause == nil {
cause = err
}
al.emit(ctx, sessionKey, streamChan, errEvent(fmt.Errorf("%w: %w", ErrContextCancelled, cause)))
return 0, true
}
al.emit(ctx, sessionKey, streamChan, errEvent(&LLMFailureError{Cause: err}))
return 0, true
}
Expand Down
29 changes: 29 additions & 0 deletions pkg/agent/loop_stream_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,35 @@ func TestRunIterationStream_ForwardsErrorOnCancelledCtx(t *testing.T) {
}
}

func TestRunIteration_MidStreamCancelClassifiedAsContextCancelled(t *testing.T) {
// A cancel landing while the provider stream is in flight surfaces as a
// provider error wrapping context.Canceled. It must be classified as
// ErrContextCancelled (not LLMFailureError) so adopters' documented
// errors.Is(err, ErrContextCancelled) terminal check fires. The ctx itself
// is not cancelled here, exercising the errors.Is(err, context.Canceled)
// race branch specifically.
provider := &errorProvider{err: fmt.Errorf("provider stream error: %w", context.Canceled)}
loop, _ := setup(provider)

var sawErr bool
for ev := range loop.RunText(context.Background(), "s1", "hello") {
p, ok := ev.Payload.(ErrorEvent)
if !ok {
continue
}
sawErr = true
if !errors.Is(p.Err, ErrContextCancelled) {
t.Fatalf("expected ErrContextCancelled, got %v", p.Err)
}
if errors.Is(p.Err, ErrLLMFailure) {
t.Fatalf("must not classify cancellation as LLM failure: %v", p.Err)
}
}
if !sawErr {
t.Fatal("expected an error event")
}
}

func TestRunIteration_ParallelToolCalls(t *testing.T) {
provider := &scriptProvider{turns: []LLMResult{
{ToolCalls: []PendingToolCall{
Expand Down
Loading