Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(codex): wait for authoritative turn completion (#7554)

Roman Yufimov620f99d8ce16
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index ae8b6238c8..d5526f9544 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -2169,8 +2169,7 @@ type codexClient struct {
onDiscardedNotification func(method string, params map[string]any)
notificationProtocol string // "unknown", "legacy", "raw"
- turnStarted bool
- completedTurnIDs map[string]bool
+ turnCompleted bool
usageMu sync.Mutex
usage TokenUsage // accumulated from turn events
@@ -2656,7 +2655,7 @@ func (c *codexClient) handleNotification(raw map[string]json.RawMessage) {
if c.notificationProtocol != "legacy" {
if c.notificationProtocol == "unknown" &&
(method == "turn/started" || method == "turn/completed" ||
- method == "thread/started" || strings.HasPrefix(method, "item/")) {
+ method == "thread/started" || method == "error" || strings.HasPrefix(method, "item/")) {
c.notificationProtocol = "raw"
}
@@ -3015,7 +3014,6 @@ func (c *codexClient) handleEvent(msg map[string]any) {
switch msgType {
case "task_started":
- c.turnStarted = true
if c.onMessage != nil {
c.onMessage(Message{Type: MessageStatus, Status: "running", SessionID: c.threadID})
}
@@ -3110,7 +3108,6 @@ func (c *codexClient) handleRawNotification(method string, params map[string]any
switch method {
case "turn/started":
- c.turnStarted = true
if turnID := extractNestedString(params, "turn", "id"); turnID != "" {
c.turnID = turnID
}
@@ -3123,6 +3120,10 @@ func (c *codexClient) handleRawNotification(method string, params map[string]any
status := extractNestedString(params, "turn", "status")
threadID, _ := params["threadId"].(string)
c.cfg.Logger.Info("codex turn/completed received", "thread_id", threadID, "turn_id", turnID, "status", status)
+ if c.turnCompleted {
+ return
+ }
+ c.turnCompleted = true
aborted := status == "cancelled" || status == "canceled" ||
status == "aborted" || status == "interrupted"
@@ -3136,16 +3137,6 @@ func (c *codexClient) handleRawNotification(method string, params map[string]any
c.setTurnError(errMsg)
}
- if c.completedTurnIDs == nil {
- c.completedTurnIDs = map[string]bool{}
- }
- if turnID != "" {
- if c.completedTurnIDs[turnID] {
- return
- }
- c.completedTurnIDs[turnID] = true
- }
-
// Extract usage from turn/completed if present (e.g. params.turn.usage).
if turn, ok := params["turn"].(map[string]any); ok {
c.extractUsageFromMap(turn)
@@ -3175,19 +3166,12 @@ func (c *codexClient) handleRawNotification(method string, params map[string]any
}
if !willRetry {
c.setTurnError(errMsg)
- if c.onTurnDone != nil {
- c.onTurnDone(false)
- }
}
}
case "thread/status/changed":
- statusType := extractNestedString(params, "status", "type")
- if statusType == "idle" && c.turnStarted {
- if c.onTurnDone != nil {
- c.onTurnDone(false)
- }
- }
+ // Status changes are informational. Only turn/completed carries the
+ // authoritative terminal state for a raw-protocol turn.
default:
if strings.HasPrefix(method, "item/") {
@@ -3286,8 +3270,7 @@ func (c *codexClient) handleItemNotification(method string, params map[string]an
}
phase, _ := item["phase"].(string)
if phase == "final_answer" {
- // Deliberately NOT gated on turnStarted, unlike onTurnDone below:
- // the gate exists so a subagent or a replayed history turn cannot
+ // The gate exists so a subagent or a replayed history turn cannot
// end OUR turn early, and the thread guard at the top of this
// function already keeps foreign threads out. A final answer that
// arrives before we observed turn/started is still this thread's
@@ -3295,9 +3278,8 @@ func (c *codexClient) handleItemNotification(method string, params map[string]an
if text != "" && c.onFinalAnswer != nil {
c.onFinalAnswer(text)
}
- if c.turnStarted && c.onTurnDone != nil {
- c.onTurnDone(false)
- }
+ // Keep the stream open until turn/completed. A final answer is the
+ // deliverable, not the authoritative lifecycle boundary.
}
}
}
diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.go
index 9c8f6e51c7..5a5b218339 100644
--- a/server/pkg/agent/codex_test.go
+++ b/server/pkg/agent/codex_test.go
@@ -365,9 +365,6 @@ func TestCodexLegacyEventTaskStarted(t *testing.T) {
if !gotStatus {
t.Fatal("expected status=running message")
}
- if !c.turnStarted {
- t.Fatal("expected turnStarted=true")
- }
if c.notificationProtocol != "legacy" {
t.Fatalf("expected protocol=legacy, got %q", c.notificationProtocol)
}
@@ -592,12 +589,92 @@ func TestCodexRawTurnCompletedDeduplication(t *testing.T) {
doneCount++
}
- c.handleLine(`{"jsonrpc":"2.0","method":"turn/completed","params":{"turn":{"id":"turn-1","status":"completed"}}}`)
- c.handleLine(`{"jsonrpc":"2.0","method":"turn/completed","params":{"turn":{"id":"turn-1","status":"completed"}}}`)
+ line := `{"jsonrpc":"2.0","method":"turn/completed","params":{"turn":{"id":"turn-1","status":"completed","usage":{"input_tokens":100,"output_tokens":10}}}}`
+ c.handleLine(line)
+ c.handleLine(line)
if doneCount != 1 {
t.Fatalf("expected deduplication, but onTurnDone called %d times", doneCount)
}
+ c.usageMu.Lock()
+ defer c.usageMu.Unlock()
+ if c.usage.InputTokens != 100 || c.usage.OutputTokens != 10 {
+ t.Fatalf("duplicate completion double-counted usage: %+v", c.usage)
+ }
+}
+
+func TestCodexRawTurnCompletedWithoutIDDeduplicatesLifecycleAndUsage(t *testing.T) {
+ t.Parallel()
+
+ c, _, _ := newTestCodexClient(t)
+ c.notificationProtocol = "raw"
+
+ var doneCount int
+ c.onTurnDone = func(aborted bool) { doneCount++ }
+ line := `{"jsonrpc":"2.0","method":"turn/completed","params":{"turn":{"status":"completed","usage":{"input_tokens":100,"output_tokens":10}}}}`
+ c.handleLine(line)
+ // An empty-ID start cannot prove that a new turn began, so it must not
+ // reopen an already completed turn.
+ c.handleLine(`{"jsonrpc":"2.0","method":"turn/started","params":{"turn":{}}}`)
+ c.handleLine(line)
+
+ if doneCount != 1 {
+ t.Fatalf("completion count = %d, want 1", doneCount)
+ }
+ c.usageMu.Lock()
+ defer c.usageMu.Unlock()
+ if c.usage.InputTokens != 100 || c.usage.OutputTokens != 10 {
+ t.Fatalf("duplicate empty-id completion double-counted usage: %+v", c.usage)
+ }
+}
+
+func TestCodexRawTurnCompletedReplayDoesNotReopenSameTurn(t *testing.T) {
+ t.Parallel()
+
+ c, _, _ := newTestCodexClient(t)
+ c.notificationProtocol = "raw"
+
+ var doneCount int
+ c.onTurnDone = func(aborted bool) { doneCount++ }
+ started := `{"jsonrpc":"2.0","method":"turn/started","params":{"turn":{"id":"turn-1"}}}`
+ completed := `{"jsonrpc":"2.0","method":"turn/completed","params":{"turn":{"id":"turn-1","status":"completed","usage":{"input_tokens":100,"output_tokens":10}}}}`
+ c.handleLine(started)
+ c.handleLine(completed)
+ c.handleLine(started)
+ c.handleLine(completed)
+
+ if doneCount != 1 {
+ t.Fatalf("completion count = %d, want 1 after replay", doneCount)
+ }
+ c.usageMu.Lock()
+ defer c.usageMu.Unlock()
+ if c.usage.InputTokens != 100 || c.usage.OutputTokens != 10 {
+ t.Fatalf("replayed turn double-counted usage: %+v", c.usage)
+ }
+}
+
+func TestCodexRawLateCompletionWithoutIDCannotReopenClient(t *testing.T) {
+ t.Parallel()
+
+ c, _, _ := newTestCodexClient(t)
+ c.notificationProtocol = "raw"
+
+ var doneCount int
+ c.onTurnDone = func(aborted bool) { doneCount++ }
+ c.handleLine(`{"jsonrpc":"2.0","method":"turn/started","params":{"turn":{"id":"turn-1"}}}`)
+ completedWithoutID := `{"jsonrpc":"2.0","method":"turn/completed","params":{"turn":{"status":"completed","usage":{"input_tokens":100,"output_tokens":10}}}}`
+ c.handleLine(completedWithoutID)
+ c.handleLine(`{"jsonrpc":"2.0","method":"turn/started","params":{"turn":{"id":"turn-2"}}}`)
+ c.handleLine(completedWithoutID)
+
+ if doneCount != 1 {
+ t.Fatalf("completion count = %d, want 1 after late no-ID replay", doneCount)
+ }
+ c.usageMu.Lock()
+ defer c.usageMu.Unlock()
+ if c.usage.InputTokens != 100 || c.usage.OutputTokens != 10 {
+ t.Fatalf("late no-ID completion double-counted usage: %+v", c.usage)
+ }
}
func TestCodexRawTurnCompletedAborted(t *testing.T) {
@@ -657,16 +734,13 @@ func TestCodexRawErrorNotificationTerminal(t *testing.T) {
t.Parallel()
c, _, _ := newTestCodexClient(t)
- c.notificationProtocol = "raw"
+ c.notificationProtocol = "unknown"
done := false
var activities []string
c.onSemanticActivity = func(activity string) {
activities = append(activities, activity)
}
c.onTurnDone = func(aborted bool) {
- if aborted {
- t.Fatal("terminal error should not mark the turn aborted")
- }
done = true
}
@@ -675,12 +749,17 @@ func TestCodexRawErrorNotificationTerminal(t *testing.T) {
if got := c.getTurnError(); got != "boom" {
t.Fatalf("expected terminal error captured, got %q", got)
}
- if !done {
- t.Fatal("terminal error should finish the turn")
+ if done {
+ t.Fatal("terminal error must wait for turn/completed")
}
if got, want := strings.Join(activities, ","), "error:terminal"; got != want {
t.Fatalf("semantic activity = %q, want %q", got, want)
}
+
+ c.handleLine(`{"jsonrpc":"2.0","method":"turn/completed","params":{"turn":{"id":"turn-error","status":"failed","error":{"message":"boom"}}}}`)
+ if !done {
+ t.Fatal("turn/completed should finish the failed turn")
+ }
}
func TestCodexRawErrorNotificationRetryingIgnored(t *testing.T) {
@@ -1295,12 +1374,11 @@ func TestCodexRawItemMCPToolCallFailureIsSanitized(t *testing.T) {
}
}
-func TestCodexRawItemAgentMessageFinalAnswer(t *testing.T) {
+func TestCodexRawItemAgentMessageFinalAnswerWaitsForTurnCompleted(t *testing.T) {
t.Parallel()
c, _, _ := newTestCodexClient(t)
c.notificationProtocol = "raw"
- c.turnStarted = true
var gotText string
var turnDone bool
@@ -1318,8 +1396,13 @@ func TestCodexRawItemAgentMessageFinalAnswer(t *testing.T) {
if gotText != "Done!" {
t.Fatalf("expected text 'Done!', got %q", gotText)
}
+ if turnDone {
+ t.Fatal("final_answer must not finish the turn")
+ }
+
+ c.handleLine(`{"jsonrpc":"2.0","method":"turn/completed","params":{"turn":{"id":"turn-1","status":"completed"}}}`)
if !turnDone {
- t.Fatal("expected onTurnDone for final_answer")
+ t.Fatal("turn/completed should finish the turn")
}
}
@@ -1372,7 +1455,6 @@ func TestCodexDeliverableOutputExcludesNarration(t *testing.T) {
c, _, _ := newTestCodexClient(t)
c.notificationProtocol = tc.protocol
- c.turnStarted = true
var finalAnswer, lastAgentMessage string
var streamed []string
@@ -1400,25 +1482,24 @@ func TestCodexDeliverableOutputExcludesNarration(t *testing.T) {
}
}
-func TestCodexRawThreadStatusIdle(t *testing.T) {
+func TestCodexRawThreadStatusIdleWaitsForTurnCompleted(t *testing.T) {
t.Parallel()
c, _, _ := newTestCodexClient(t)
c.notificationProtocol = "raw"
- c.turnStarted = true
var turnDone bool
- c.onTurnDone = func(aborted bool) {
- turnDone = true
- if aborted {
- t.Fatal("expected aborted=false for idle")
- }
- }
+ c.onTurnDone = func(aborted bool) { turnDone = true }
c.handleLine(`{"jsonrpc":"2.0","method":"thread/status/changed","params":{"status":{"type":"idle"}}}`)
+ if turnDone {
+ t.Fatal("idle status must not finish the turn")
+ }
+
+ c.handleLine(`{"jsonrpc":"2.0","method":"turn/completed","params":{"turn":{"id":"turn-1","status":"completed"}}}`)
if !turnDone {
- t.Fatal("expected onTurnDone for idle status")
+ t.Fatal("turn/completed should finish the turn")
}
}
@@ -1507,7 +1588,6 @@ func TestCodexRawItemAgentMessageFinalAnswerFromSubagentIgnored(t *testing.T) {
c, _, _ := newTestCodexClient(t)
c.notificationProtocol = "raw"
c.threadID = "thr_main"
- c.turnStarted = true
var messages []Message
var doneCount int