From 04f02c56d6ddf31c82bc6d0f2540f0f3f6057421 Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 13 Jun 2026 15:33:02 +0800 Subject: [PATCH] fix(runtime): RunSync returns context.Canceled on aborted run --- runtime/agent_test.go | 31 +++++++++++++++++++++++++++++++ runtime/runtime.go | 2 ++ 2 files changed, 33 insertions(+) diff --git a/runtime/agent_test.go b/runtime/agent_test.go index 61d4d64..6779728 100644 --- a/runtime/agent_test.go +++ b/runtime/agent_test.go @@ -896,6 +896,37 @@ func TestRun_AbortMidDispatchProducesPairedSession(t *testing.T) { } } +// TestRunSync_ReturnsErrorOnAbort verifies that RunSync surfaces an aborted run +// as a non-nil error (context.Canceled) rather than returning (partialText, +// nil). Cron/sync callers must be able to distinguish a completed run from a +// cancelled one. Reuses the same abort scaffolding as +// TestRun_AbortMidDispatchProducesPairedSession (a tool batch + cancelOnNth). +func TestRunSync_ReturnsErrorOnAbort(t *testing.T) { + threeToolCalls := []llm.ToolCall{ + {ID: "tc_0", Name: "noop", Input: json.RawMessage(`{}`)}, + {ID: "tc_1", Name: "noop", Input: json.RawMessage(`{}`)}, + {ID: "tc_2", Name: "noop", Input: json.RawMessage(`{}`)}, + } + llmFake := &threeToolCallLLM{toolCalls: threeToolCalls} + + ctx, cancel := context.WithCancel(context.Background()) + count := 0 + exec := &cancelOnNthExecutor{n: 1, cancel: cancel, count: &count} + + r := &Runtime{ + LLM: llmFake, + Tools: exec, + Session: session.NewSession("a", "k"), + AgentID: "a", + Model: "test-model", + MaxTurns: 5, + } + + _, err := r.RunSync(ctx, "go", nil) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + // threeToolCallLLM emits the configured tool_calls as one assistant turn, // then EventDone. On the next call (after tool results, if the runtime // loops back), emits only EventDone with no tool_calls so Run terminates. diff --git a/runtime/runtime.go b/runtime/runtime.go index 25b7379..d527287 100644 --- a/runtime/runtime.go +++ b/runtime/runtime.go @@ -849,6 +849,8 @@ func (r *Runtime) RunSync(ctx context.Context, userMsg string, images []llm.Imag switch event.Type { case EventTextDelta: response.WriteString(event.Text) + case EventAborted: + return response.String(), context.Canceled case EventError: return response.String(), event.Error }