Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agent/codex): stop reconnects and input echoes from holding a turn open (#11634)
Bohan Jiang02d7642fc4f4
diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex 79b5f49d85..464d4a2750 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -49,8 +49,8 @@ type ExecOptions struct {Timeout time.DurationSemanticInactivityTimeout time.Duration// FirstTurnNoProgressTimeout optionally overrides the Codex first-turn- // no-progress ceiling — the window a turn may stay completely silent after- // the app-server reports turn/started before the watchdog fails it. Zero+ // no-progress ceiling — the window a turn may go without model progress+ // after the app-server accepts turn/start before the watchdog fails it. Zero// keeps the provider default and the existing behaviour where// SemanticInactivityTimeout can only shrink that ceiling; a positive value// sets it explicitly, upward included. This answers a different question thandiff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.goindex ef77a75fb2..8c79e8d707 100644--- a/server/pkg/agent/codex.go+++ b/server/pkg/agent/codex.go@@ -46,8 +46,8 @@ const (const (codexStderrTailBytes = 2048defaultCodexSemanticInactivityTimeout = 10 * time.Minute- // defaultCodexFirstTurnNoProgressTimeout caps how long the first turn may- // stay completely silent after the app-server reports turn/started. Its only+ // defaultCodexFirstTurnNoProgressTimeout caps how long a turn may go+ // without model progress after the app-server accepts turn/start. Its only// job is to fail fast instead of waiting out// defaultCodexSemanticInactivityTimeout, so it only has to stay well under// that 10 minute backstop.@@ -183,7 +183,8 @@ func classifyCodexStartupStderr(stderr string, timedOut bool) codexStderrClassifconst CodexSemanticInactivityMarker = "codex semantic inactivity timeout"// CodexFirstTurnNoProgressMarker identifies the app-server failure mode where-// Codex accepts a turn and then never emits any item, completion, or error.+// Codex accepts a turn and then never emits model progress, completion, or a+// terminal error — including a turn that only echoes its input and reconnects.const CodexFirstTurnNoProgressMarker = "codex app-server no progress timeout"// CodexHandshakeTimeoutMarker identifies a Codex app-server startup RPC that@@ -325,10 +326,13 @@ type codexTimeoutDiagnostic struct {Kind codexTimeoutKindTimeout time.DurationLastActivity string- ThreadID string- TurnID string- Model string- CodexVersion string+ // LastReconnect is the latest reconnect reason since the last progress;+ // empty when Codex was not reconnecting when the watchdog fired.+ LastReconnect string+ ThreadID string+ TurnID string+ Model string+ CodexVersion string}// codexFirstItemWaitObservation records the interval from turn/started to the@@ -1192,7 +1196,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts ExecmsgCh := make(chan Message, 256)resCh := make(chan Result, 1)- semanticActivityCh := make(chan string, 256)+ semanticActivityCh := make(chan codexWatchdogEvent, 256)guardianRateLimitTrip := make(chan struct{}, 1)var guardianRateLimitTripped atomic.Bool@@ -1215,7 +1219,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Execif activity == "status:running" {firstItemWait.start(time.Now(), c.activeTurnID())}- trySendString(semanticActivityCh, activity)+ trySendWatchdogEvent(semanticActivityCh, codexWatchdogEvent{activity: activity})if activity != "" {semanticObserved.Store(true)}@@ -1276,7 +1280,11 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts ExeconSemanticActivity: func(description string) {semanticObserved.Store(true)b.cfg.Logger.Debug("codex semantic activity observed", "activity", description)- trySendString(semanticActivityCh, description)+ trySendWatchdogEvent(semanticActivityCh, codexWatchdogEvent{activity: description})+ },+ onReconnect: func(reason string) {+ semanticObserved.Store(true)+ trySendWatchdogEvent(semanticActivityCh, codexWatchdogEvent{reconnect: reason})},onTurnDone: func(aborted bool) {select {@@ -1536,14 +1544,23 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts ExeclastSemanticActivity := time.Now()lastSemanticActivityDescription := "turn/start"+ // lastReconnect is the latest reconnect reason since the last progress.+ // Reconnects never postpone a watchdog; they only explain its timeout.+ lastReconnect := ""semanticTimer := time.NewTimer(semanticInactivityTimeout)defer semanticTimer.Stop()+ // The first-turn watchdog runs from the accepted turn/start rather than+ // from turn/started, so an app-server that never reports the turn as+ // started still fails fast instead of waiting out the semantic timer.firstTurnNoProgressTimeout := codexFirstTurnNoProgressTimeout(semanticInactivityTimeout, opts.FirstTurnNoProgressTimeout)var firstTurnNoProgressTimer *time.Timervar firstTurnNoProgressTimerC <-chan time.Time- firstTurnStarted := falsefirstTurnProgressObserved := false+ if waitingForTurn {+ firstTurnNoProgressTimer = time.NewTimer(firstTurnNoProgressTimeout)+ firstTurnNoProgressTimerC = firstTurnNoProgressTimer.C+ }stopFirstTurnNoProgressTimer := func() {if firstTurnNoProgressTimer == nil {return@@ -1565,23 +1582,28 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Execif !interruptCodexTurn(c, threadID, turnDone, opts.TurnInterruptTimeout, b.cfg.Logger) {proc.stopProcess()}- case activity := <-semanticActivityCh:+ case event := <-semanticActivityCh:+ if event.reconnect != "" {+ lastReconnect = event.reconnect+ break+ }+ activity := event.activitylastSemanticActivity = time.Now()lastSemanticActivityDescription = activityresetTimer(semanticTimer, semanticInactivityTimeout)- if activity == "status:running" && !firstTurnStarted {- firstTurnStarted = true+ if activity == "status:running" {firstItemWait.start(time.Now(), c.activeTurnID())- firstTurnNoProgressTimer = time.NewTimer(firstTurnNoProgressTimeout)- firstTurnNoProgressTimerC = firstTurnNoProgressTimer.C- } else if firstTurnStarted && !firstTurnProgressObserved && isCodexFirstTurnProgressActivity(activity) {- firstTurnProgressObserved = true- if activity == "error:terminal" {- finishFirstItemWait("turn_failed")- } else {- finishFirstItemWait("progress")+ } else if isCodexFirstTurnProgressActivity(activity) {+ lastReconnect = ""+ if !firstTurnProgressObserved {+ firstTurnProgressObserved = true+ if activity == "error:terminal" {+ finishFirstItemWait("turn_failed")+ } else {+ finishFirstItemWait("progress")+ }+ stopFirstTurnNoProgressTimer()}- stopFirstTurnNoProgressTimer()}case <-firstTurnNoProgressTimerC:waitingForTurn = false@@ -1589,12 +1611,13 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts ExecfinalStatus = "timeout"turnID := c.activeTurnID()timeoutDiagnostic = codexTimeoutDiagnostic{- Kind: codexTimeoutFirstTurnNoProgress,- Timeout: firstTurnNoProgressTimeout,- LastActivity: lastSemanticActivityDescription,- ThreadID: threadID,- TurnID: turnID,- Model: opts.Model,+ Kind: codexTimeoutFirstTurnNoProgress,+ Timeout: firstTurnNoProgressTimeout,+ LastActivity: lastSemanticActivityDescription,+ LastReconnect: lastReconnect,+ ThreadID: threadID,+ TurnID: turnID,+ Model: opts.Model,}b.cfg.Logger.Warn(CodexFirstTurnNoProgressMarker,"pid", proc.cmd.Process.Pid,@@ -1602,6 +1625,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec"turn_id", turnID,"timeout", firstTurnNoProgressTimeout.String(),"last_activity", lastSemanticActivityDescription,+ "last_reconnect", lastReconnect,)case <-semanticTimer.C:waitingForTurn = false@@ -1609,12 +1633,13 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts ExecfinalStatus = "timeout"turnID := c.activeTurnID()timeoutDiagnostic = codexTimeoutDiagnostic{- Kind: codexTimeoutSemanticInactivity,- Timeout: semanticInactivityTimeout,- LastActivity: lastSemanticActivityDescription,- ThreadID: threadID,- TurnID: turnID,- Model: opts.Model,+ Kind: codexTimeoutSemanticInactivity,+ Timeout: semanticInactivityTimeout,+ LastActivity: lastSemanticActivityDescription,+ LastReconnect: lastReconnect,+ ThreadID: threadID,+ TurnID: turnID,+ Model: opts.Model,}b.cfg.Logger.Warn(CodexSemanticInactivityMarker,"pid", proc.cmd.Process.Pid,@@ -1622,6 +1647,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec"turn_id", turnID,"timeout", semanticInactivityTimeout.String(),"last_activity", lastSemanticActivityDescription,+ "last_reconnect", lastReconnect,"idle_for", time.Since(lastSemanticActivity).Round(time.Millisecond).String(),)case <-runCtx.Done():@@ -2062,10 +2088,10 @@ func stopTimer(timer *time.Timer) {}// codexFirstTurnNoProgressTimeout resolves the first-turn watchdog ceiling:-// how long the first turn may stay silent after turn/started before that one-// watchdog fails it. This is only the first-turn timer's own duration — NOT-// the effective first-item wait. The semantic-inactivity timer is armed-// concurrently (the same first status:running resets it and starts this one),+// how long a turn may go without model progress after turn/start is accepted+// before that one watchdog fails it. This is only the first-turn timer's own+// duration — NOT the effective first-item wait. The semantic-inactivity timer+// is armed concurrently (both start at the accepted turn/start),// so the real wait is min(this, semanticInactivityTimeout, execution timeout).// Raising the override above the semantic timeout therefore does not extend the// wait unless the semantic timeout is raised too; LoadConfig warns when it does@@ -2096,7 +2122,7 @@ func codexFirstTurnNoProgressTimeout(semanticInactivityTimeout, configured time.}func isCodexFirstTurnProgressActivity(activity string) bool {- return activity != "" && activity != "status:running" && activity != "error:retry"+ return activity != "" && activity != "status:running"}func buildCodexTimeoutDiagnosticError(diag codexTimeoutDiagnostic, stderrTail string) string {@@ -2104,18 +2130,37 @@ func buildCodexTimeoutDiagnosticError(diag codexTimeoutDiagnostic, stderrTail stvar msg stringswitch diag.Kind {case codexTimeoutFirstTurnNoProgress:- msg = fmt.Sprintf("%s after %s: received turn start but no item, message, tool, turn/completed, or error event (%s)",- CodexFirstTurnNoProgressMarker,- diag.Timeout,- formatCodexDiagnosticFields(diag),- )+ if diag.LastReconnect != "" {+ msg = fmt.Sprintf("%s after %s: Codex kept reconnecting to the model service and made no progress (last reconnect: %s; %s)",+ CodexFirstTurnNoProgressMarker,+ diag.Timeout,+ diag.LastReconnect,+ formatCodexDiagnosticFields(diag),+ )+ } else {+ msg = fmt.Sprintf("%s after %s: received turn start but no item, message, tool, turn/completed, or error event (%s)",+ CodexFirstTurnNoProgressMarker,+ diag.Timeout,+ formatCodexDiagnosticFields(diag),+ )+ }case codexTimeoutSemanticInactivity:- msg = fmt.Sprintf("%s after %s without agent progress (last activity: %s; %s)",- CodexSemanticInactivityMarker,- diag.Timeout,- nonEmptyCodexDiagnosticValue(diag.LastActivity),- formatCodexDiagnosticFields(diag),- )+ if diag.LastReconnect != "" {+ msg = fmt.Sprintf("%s after %s: Codex kept reconnecting to the model service without agent progress (last reconnect: %s; last activity: %s; %s)",+ CodexSemanticInactivityMarker,+ diag.Timeout,+ diag.LastReconnect,+ nonEmptyCodexDiagnosticValue(diag.LastActivity),+ formatCodexDiagnosticFields(diag),+ )+ } else {+ msg = fmt.Sprintf("%s after %s without agent progress (last activity: %s; %s)",+ CodexSemanticInactivityMarker,+ diag.Timeout,+ nonEmptyCodexDiagnosticValue(diag.LastActivity),+ formatCodexDiagnosticFields(diag),+ )+ }default:msg = "codex timed out"}@@ -2173,9 +2218,17 @@ func detectCodexVersionForDiagnostics(ctx context.Context, runtimeCmd Command, ereturn version}-func trySendString(ch chan<- string, value string) {+// codexWatchdogEvent is one observation for the turn watchdogs. Exactly one+// field is set: activity describes semantic activity, reconnect carries the+// reason of a retrying error notification.+type codexWatchdogEvent struct {+ activity string+ reconnect string+}++func trySendWatchdogEvent(ch chan<- codexWatchdogEvent, event codexWatchdogEvent) {select {- case ch <- value:+ case ch <- event:default:}}@@ -2293,8 +2346,12 @@ type codexClient struct {// message and its phase label ("" when the protocol carries none).// onAgentMessageChunk may deliver that text incrementally, so// Result.Output fallbacks must use this callback rather than the last chunk.- onAgentMessage func(text, phase string)- onSemanticActivity func(description string)+ onAgentMessage func(text, phase string)+ onSemanticActivity func(description string)+ // onReconnect receives the reason of each retrying error notification.+ // A reconnect proves the app-server is alive, not that the model made+ // progress, so it is reported apart from onSemanticActivity.+ onReconnect func(reason string)onTurnDone func(aborted bool)guardianRateLimitCircuit *codexGuardianRateLimitCircuitonGuardianRateLimit func()@@ -3467,14 +3524,14 @@ func (c *codexClient) handleRawNotification(method string, params map[string]any}if errMsg != "" {c.cfg.Logger.Warn("codex error notification", "message", errMsg, "will_retry", willRetry)- if c.onSemanticActivity != nil {- if willRetry {- c.onSemanticActivity("error:retry")- } else {+ if willRetry {+ if c.onReconnect != nil {+ c.onReconnect(codexReconnectReason(errMsg, params))+ }+ } else {+ if c.onSemanticActivity != nil {c.onSemanticActivity("error:terminal")}- }- if !willRetry {c.setTurnError(errMsg)}}@@ -3656,7 +3713,7 @@ func (c *codexClient) handleItemNotification(method string, params map[string]anitemType = "agentMessage"itemID, _ = params["itemId"].(string)}- if isCodexItemProgressActivity(method) && c.onSemanticActivity != nil {+ if isCodexItemProgressActivity(method, itemType) && c.onSemanticActivity != nil {c.onSemanticActivity(describeCodexItemProgressActivity(method, itemType, itemID))}if item == nil && method != "item/agentMessage/delta" {@@ -3813,8 +3870,23 @@ func codexRawTokenUsageFromV2(usage map[string]any) codexRawTokenUsage {}}-func isCodexItemProgressActivity(method string) bool {- return strings.HasPrefix(method, "item/")+// isCodexItemProgressActivity reports whether an item notification shows the+// model working. userMessage items are app-server echoing the submitted input,+// which it does before reaching the model service, so they prove nothing about+// the model and must not satisfy either watchdog (GH #5901, #11618).+func isCodexItemProgressActivity(method, itemType string) bool {+ return strings.HasPrefix(method, "item/") && itemType != "userMessage"+}++// codexReconnectReason renders a retrying error notification for timeout+// diagnostics, e.g. "Reconnecting... waiting for network; Connection failed:+// error sending request".+func codexReconnectReason(message string, params map[string]any) string {+ reason := message+ if details := strings.TrimSpace(extractNestedString(params, "error", "additionalDetails")); details != "" {+ reason += "; " + details+ }+ return sanitizeCodexDiagnostic(reason)}func describeCodexItemProgressActivity(method, itemType, itemID string) string {diff --git a/server/pkg/agent/codex_process.go b/server/pkg/agent/codex_process.goindex 6beb628f68..366965ac44 100644--- a/server/pkg/agent/codex_process.go+++ b/server/pkg/agent/codex_process.go@@ -44,6 +44,7 @@ type codexTurnHooks struct {onAgentMessage func(text, phase string)onFinalAnswer func(text string)onSemanticActivity func(description string)+ onReconnect func(reason string)onTurnDone func(aborted bool)guardianRateLimitCircuit *codexGuardianRateLimitCircuitonGuardianRateLimit func()@@ -63,6 +64,7 @@ func (c *codexClient) attachTurnHooks(h codexTurnHooks) {c.onAgentMessage = h.onAgentMessagec.onFinalAnswer = h.onFinalAnswerc.onSemanticActivity = h.onSemanticActivity+ c.onReconnect = h.onReconnectc.onTurnDone = h.onTurnDonec.guardianRateLimitCircuit = h.guardianRateLimitCircuitc.onGuardianRateLimit = h.onGuardianRateLimit@@ -98,6 +100,7 @@ func (c *codexClient) detachTurnHooks() {c.onAgentMessage = nilc.onFinalAnswer = nilc.onSemanticActivity = nil+ c.onReconnect = nilc.onTurnDone = nilc.onGuardianRateLimit = nilc.rateLimits = nildiff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.goindex 76623aa192..df380c5749 100644--- a/server/pkg/agent/codex_test.go+++ b/server/pkg/agent/codex_test.go@@ -819,20 +819,59 @@ func TestCodexRawErrorNotificationRetryingIgnored(t *testing.T) {c, _, _ := newTestCodexClient(t)c.notificationProtocol = "raw"- var activities []string+ var activities, reconnects []stringc.onSemanticActivity = func(activity string) {activities = append(activities, activity)}+ c.onReconnect = func(reason string) {+ reconnects = append(reconnects, reason)+ }c.onTurnDone = func(aborted bool) {t.Fatal("retrying error should not finish the turn")}- c.handleLine(`{"jsonrpc":"2.0","method":"error","params":{"error":{"message":"reconnecting"},"willRetry":true}}`)+ c.handleLine(`{"jsonrpc":"2.0","method":"error","params":{"error":{"message":"Reconnecting... 2/5"},"willRetry":true}}`)+ c.handleLine(`{"jsonrpc":"2.0","method":"error","params":{"error":{"message":"Reconnecting... waiting for network","additionalDetails":"Connection failed: error sending request"},"willRetry":true}}`)if got := c.getTurnError(); got != "" {t.Fatalf("retrying error should not be captured, got %q", got)}- if got, want := strings.Join(activities, ","), "error:retry"; got != want {+ // A reconnect is not semantic activity: it must not feed either watchdog+ // (GH #11618).+ if len(activities) != 0 {+ t.Fatalf("retrying error must not report semantic activity, got %q", activities)+ }+ want := []string{+ "Reconnecting... 2/5",+ "Reconnecting... waiting for network; Connection failed: error sending request",+ }+ if got := strings.Join(reconnects, "|"); got != strings.Join(want, "|") {+ t.Fatalf("reconnect reasons = %q, want %q", reconnects, want)+ }+}++// TestCodexUserMessageItemsAreNotProgress pins the input-echo half of GH+// #11618 (and #5901): app-server echoes the submitted prompt as userMessage+// items before it reaches the model service, so those items must not report+// semantic activity, while every other item still does.+func TestCodexUserMessageItemsAreNotProgress(t *testing.T) {+ t.Parallel()++ c, _, _ := newTestCodexClient(t)+ c.notificationProtocol = "raw"+ var activities []string+ c.onSemanticActivity = func(activity string) {+ activities = append(activities, activity)+ }++ c.handleLine(`{"jsonrpc":"2.0","method":"item/started","params":{"item":{"type":"userMessage","id":"user-1"}}}`)+ c.handleLine(`{"jsonrpc":"2.0","method":"item/completed","params":{"item":{"type":"userMessage","id":"user-1"}}}`)+ if len(activities) != 0 {+ t.Fatalf("userMessage echo must not report semantic activity, got %q", activities)+ }++ c.handleLine(`{"jsonrpc":"2.0","method":"item/started","params":{"item":{"type":"reasoning","id":"rs-1"}}}`)+ if got, want := strings.Join(activities, ","), "item/started:reasoning:rs-1"; got != want {t.Fatalf("semantic activity = %q, want %q", got, want)}}@@ -846,7 +885,6 @@ func TestCodexFirstTurnProgressActivity(t *testing.T) {}{{activity: "", want: false},{activity: "status:running", want: false},- {activity: "error:retry", want: false},{activity: "error", want: true},{activity: "text", want: true},{activity: "tool-use:exec_command", want: true},@@ -3371,7 +3409,7 @@ func TestCodexExecuteFirstTurnNoProgressSurfacesDiagnostics(t *testing.T) {// TestCodexExecuteFirstTurnOverrideAboveSemanticIsTruncated pins the competing-// timer contract for MULTICA_CODEX_FIRST_TURN_TIMEOUT (GH #3262 / #5959): the-// first status:running arms the semantic-inactivity timer and the first-turn+// accepted turn/start arms the semantic-inactivity timer and the first-turn// timer together, so a first-turn override ABOVE the semantic timeout cannot// extend the first-item wait — the semantic timer fires first. That also// reclassifies the failure as semantic inactivity, so the model-catalog startup@@ -4788,6 +4826,246 @@ func TestCodexExecuteDoesNotRetryFirstTurnNoProgressWithoutCatalogSignal(t *testassertCodexAttemptCount(t, fakePath, "1")}+// codexReconnectLoopFixture emits the reconnect notification Codex sends while+// it cannot reach the model service (GH #11618), every 100ms for ~3s.+func codexReconnectLoopFixture(threadID string) string {+ return `i=0` + "\n" ++ `while [ $i -lt 30 ]; do` + "\n" ++ ` echo '{"jsonrpc":"2.0","method":"error","params":{"threadId":"` + threadID + `","error":{"message":"Reconnecting... waiting for network","codexErrorInfo":{"responseStreamDisconnected":{"httpStatusCode":null}},"additionalDetails":"Connection failed: error sending request"},"willRetry":true}}'` + "\n" ++ ` sleep 0.1` + "\n" ++ ` i=$((i+1))` + "\n" ++ `done` + "\n"+}++// TestCodexExecuteFirstTurnFailsWhileOnlyReconnecting replays GH #11618: Codex+// accepts the turn, echoes the input, then only reconnects to an unreachable+// model service. Neither the echo nor the reconnects are model progress, so the+// first-turn watchdog must fail the attempt and name the reconnect reason,+// instead of the reconnects holding the run open until the execution timeout.+func TestCodexExecuteFirstTurnFailsWhileOnlyReconnecting(t *testing.T) {+ // Not t.Parallel(): this test mutates codexGracefulShutdownTimeoutNanos.+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }+ codexGracefulShutdownTimeoutNanos.Store(int64(100 * time.Millisecond))+ t.Cleanup(func() { codexGracefulShutdownTimeoutNanos.Store(0) })++ fakePath := writeFakeCodexAppServer(t, ""++ `STATE="$(dirname "$0")/attempts"`+"\n"++ `ATTEMPT=$(cat "$STATE" 2>/dev/null || echo 0)`+"\n"++ `ATTEMPT=$((ATTEMPT+1))`+"\n"++ `echo "$ATTEMPT" > "$STATE"`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'`+"\n"++ `read line`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thr-offline"}}}'`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-offline","turn":{"id":"turn-offline"}}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"item/started","params":{"threadId":"thr-offline","item":{"type":"userMessage","id":"user-echo"}}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr-offline","item":{"type":"userMessage","id":"user-echo"}}}'`+"\n"++ codexReconnectLoopFixture("thr-offline"))++ result := executeFakeCodex(t, fakePath, ExecOptions{+ Timeout: 5 * time.Second,+ SemanticInactivityTimeout: 2 * time.Second,+ FirstTurnNoProgressTimeout: 400 * time.Millisecond,+ })+ if result.Status != "timeout" {+ t.Fatalf("expected timeout, got status=%q error=%q", result.Status, result.Error)+ }+ for _, want := range []string{+ CodexFirstTurnNoProgressMarker,+ "Codex kept reconnecting to the model service",+ "last reconnect: Reconnecting... waiting for network; Connection failed: error sending request",+ "turn-offline",+ } {+ if !strings.Contains(result.Error, want) {+ t.Fatalf("expected error to contain %q, got %q", want, result.Error)+ }+ }+ // No model catalog signal: the existing retry gate stays closed.+ assertCodexAttemptCount(t, fakePath, "1")+}++// TestCodexExecuteFirstTurnWatchdogRunsWithoutTurnStarted covers an+// app-server that accepts turn/start but never reports turn/started: the+// first-turn watchdog is armed by the accepted request, so the attempt fails+// fast instead of waiting out the semantic-inactivity backstop.+func TestCodexExecuteFirstTurnWatchdogRunsWithoutTurnStarted(t *testing.T) {+ // Not t.Parallel(): this test mutates codexGracefulShutdownTimeoutNanos.+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }+ codexGracefulShutdownTimeoutNanos.Store(int64(100 * time.Millisecond))+ t.Cleanup(func() { codexGracefulShutdownTimeoutNanos.Store(0) })++ fakePath := writeFakeCodexAppServer(t, ""++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'`+"\n"++ `read line`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thr-unstarted"}}}'`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"++ `sleep 3`+"\n")++ result := executeFakeCodex(t, fakePath, ExecOptions{+ Timeout: 5 * time.Second,+ SemanticInactivityTimeout: 2 * time.Second,+ FirstTurnNoProgressTimeout: 300 * time.Millisecond,+ })+ if result.Status != "timeout" {+ t.Fatalf("expected timeout, got status=%q error=%q", result.Status, result.Error)+ }+ if !strings.Contains(result.Error, CodexFirstTurnNoProgressMarker) {+ t.Fatalf("expected the first-turn watchdog to fire, got %q", result.Error)+ }+ if strings.Contains(result.Error, "kept reconnecting") {+ t.Fatalf("no reconnect happened, error must not claim one: %q", result.Error)+ }+}++// TestCodexExecuteSemanticInactivityFiresWhileReconnectingAfterProgress covers+// a turn that made progress and then lost the model service: reconnects must+// not keep resetting the semantic-inactivity timer, and its timeout names the+// reconnect reason.+func TestCodexExecuteSemanticInactivityFiresWhileReconnectingAfterProgress(t *testing.T) {+ // Not t.Parallel(): this test mutates codexGracefulShutdownTimeoutNanos.+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }+ codexGracefulShutdownTimeoutNanos.Store(int64(100 * time.Millisecond))+ t.Cleanup(func() { codexGracefulShutdownTimeoutNanos.Store(0) })++ fakePath := writeFakeCodexAppServer(t, ""++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'`+"\n"++ `read line`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thr-dropped"}}}'`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-dropped","turn":{"id":"turn-dropped"}}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr-dropped","item":{"type":"agentMessage","id":"msg-1","text":"Working on it"}}}'`+"\n"++ codexReconnectLoopFixture("thr-dropped"))++ result := executeFakeCodex(t, fakePath, ExecOptions{+ Timeout: 5 * time.Second,+ SemanticInactivityTimeout: 400 * time.Millisecond,+ FirstTurnNoProgressTimeout: 300 * time.Millisecond,+ })+ if result.Status != "timeout" {+ t.Fatalf("expected timeout, got status=%q error=%q", result.Status, result.Error)+ }+ for _, want := range []string{+ CodexSemanticInactivityMarker,+ "Codex kept reconnecting to the model service",+ "last reconnect: Reconnecting... waiting for network",+ } {+ if !strings.Contains(result.Error, want) {+ t.Fatalf("expected error to contain %q, got %q", want, result.Error)+ }+ }+}++// TestCodexExecuteRecoveredReconnectIsNotReported checks that progress after a+// reconnect clears it: a later timeout must not blame a reconnect that already+// recovered.+func TestCodexExecuteRecoveredReconnectIsNotReported(t *testing.T) {+ // Not t.Parallel(): this test mutates codexGracefulShutdownTimeoutNanos.+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }+ codexGracefulShutdownTimeoutNanos.Store(int64(100 * time.Millisecond))+ t.Cleanup(func() { codexGracefulShutdownTimeoutNanos.Store(0) })++ fakePath := writeFakeCodexAppServer(t, ""++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'`+"\n"++ `read line`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thr-blip"}}}'`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-blip","turn":{"id":"turn-blip"}}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"error","params":{"threadId":"thr-blip","error":{"message":"Reconnecting... 1/5"},"willRetry":true}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr-blip","item":{"type":"agentMessage","id":"msg-1","text":"Back online"}}}'`+"\n"++ `sleep 3`+"\n")++ result := executeFakeCodex(t, fakePath, ExecOptions{+ Timeout: 5 * time.Second,+ SemanticInactivityTimeout: 300 * time.Millisecond,+ FirstTurnNoProgressTimeout: 200 * time.Millisecond,+ })+ if result.Status != "timeout" {+ t.Fatalf("expected timeout, got status=%q error=%q", result.Status, result.Error)+ }+ if !strings.Contains(result.Error, CodexSemanticInactivityMarker) {+ t.Fatalf("expected semantic inactivity, got %q", result.Error)+ }+ if strings.Contains(result.Error, "kept reconnecting") {+ t.Fatalf("a recovered reconnect must not be reported, got %q", result.Error)+ }+}++// TestCodexExecuteCatalogRefreshRetryAfterUserMessageEcho replays GH #5901:+// app-server echoes the input, reconnects, and fails to refresh the model+// catalog. The echo must not count as progress, so the first-turn watchdog+// fires and the existing fresh-process catalog retry recovers the run.+func TestCodexExecuteCatalogRefreshRetryAfterUserMessageEcho(t *testing.T) {+ // Not t.Parallel(): this test mutates codexGracefulShutdownTimeoutNanos.+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }+ codexGracefulShutdownTimeoutNanos.Store(int64(100 * time.Millisecond))+ t.Cleanup(func() { codexGracefulShutdownTimeoutNanos.Store(0) })++ fakePath := writeFakeCodexAppServer(t, ""++ `STATE="$(dirname "$0")/attempts"`+"\n"++ `ATTEMPT=$(cat "$STATE" 2>/dev/null || echo 0)`+"\n"++ `ATTEMPT=$((ATTEMPT+1))`+"\n"++ `echo "$ATTEMPT" > "$STATE"`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'`+"\n"++ `read line`+"\n"++ `read line`+"\n"++ `if [ "$ATTEMPT" = "1" ]; then`+"\n"++ ` echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thr-echo-stuck"}}}'`+"\n"++ ` read line`+"\n"++ ` echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"++ ` echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-echo-stuck","turn":{"id":"turn-echo-stuck"}}}'`+"\n"++ ` echo '{"jsonrpc":"2.0","method":"item/started","params":{"threadId":"thr-echo-stuck","item":{"type":"userMessage","id":"user-echo"}}}'`+"\n"++ ` echo '{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr-echo-stuck","item":{"type":"userMessage","id":"user-echo"}}}'`+"\n"++ ` echo '{"jsonrpc":"2.0","method":"error","params":{"threadId":"thr-echo-stuck","error":{"message":"Reconnecting... 2/5"},"willRetry":true}}'`+"\n"++ ` echo 'ERROR codex_models_manager::manager: failed to refresh available models: timeout waiting for child process to exit' >&2`+"\n"++ ` sleep 2`+"\n"++ `else`+"\n"++ ` echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thr-echo-recovered"}}}'`+"\n"++ ` read line`+"\n"++ ` echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"++ ` echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-echo-recovered","turn":{"id":"turn-echo-recovered"}}}'`+"\n"++ ` echo '{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr-echo-recovered","item":{"type":"agentMessage","id":"msg-recovered","text":"Recovered after echo"}}}'`+"\n"++ ` echo '{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"thr-echo-recovered","turn":{"id":"turn-echo-recovered","status":"completed"}}}'`+"\n"++ `fi`+"\n")++ result, _ := executeFakeCodexCollectingMessages(t, fakePath, ExecOptions{+ Timeout: 20 * time.Second,+ SemanticInactivityTimeout: 100 * time.Millisecond,+ }, 20*time.Second)+ if result.Status != "completed" {+ t.Fatalf("user-message echo must not suppress the catalog retry: status=%q error=%q", result.Status, result.Error)+ }+ if result.Output != "Recovered after echo" {+ t.Fatalf("expected output from the recovered attempt, got %q", result.Output)+ }+ if result.SessionID != "thr-echo-recovered" {+ t.Fatalf("expected the recovered thread id, got %q", result.SessionID)+ }+ assertCodexAttemptCount(t, fakePath, "2")+}+func TestCodexExecuteTurnCompletionCanPrecedeTurnStartResponse(t *testing.T) {t.Parallel()if runtime.GOOS == "windows" {