Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agent): surface Codex app-server no-progress diagnostics (MUL-2688)
Multica Eve311cf4d99842
diff --git a/server/internal/daemon/poisoned.go b/server/internal/daemon/poisoned.goindex 459229a343..6757bb7509 100644--- a/server/internal/daemon/poisoned.go+++ b/server/internal/daemon/poisoned.go@@ -116,7 +116,9 @@ func classifyResumeUnsafeTimeout(provider, errMsg string) (string, bool) {if strings.ToLower(strings.TrimSpace(provider)) != "codex" || errMsg == "" {return "", false}- if strings.Contains(strings.ToLower(errMsg), strings.ToLower(agent.CodexSemanticInactivityMarker)) {+ lowered := strings.ToLower(errMsg)+ if strings.Contains(lowered, strings.ToLower(agent.CodexSemanticInactivityMarker)) ||+ strings.Contains(lowered, strings.ToLower(agent.CodexFirstTurnNoProgressMarker)) {return FailureReasonCodexSemanticInactivity, true}return "", falsediff --git a/server/internal/daemon/poisoned_test.go b/server/internal/daemon/poisoned_test.goindex a4800c470f..6ce5b7752d 100644--- a/server/internal/daemon/poisoned_test.go+++ b/server/internal/daemon/poisoned_test.go@@ -187,6 +187,13 @@ func TestClassifyResumeUnsafeTimeout(t *testing.T) {wantOK: true,wantReason: FailureReasonCodexSemanticInactivity,},+ {+ name: "codex first turn no progress",+ provider: "codex",+ errMsg: agent.CodexFirstTurnNoProgressMarker + ` after 30s: received turn start but no item, turn/completed, or error event`,+ wantOK: true,+ wantReason: FailureReasonCodexSemanticInactivity,+ },{name: "codex ordinary timeout remains resumable",provider: "codex",diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.goindex d8bb283aa1..4874f15ef3 100644--- a/server/pkg/agent/codex.go+++ b/server/pkg/agent/codex.go@@ -26,14 +26,40 @@ var codexBlockedArgs = map[string]blockedArgMode{// rejects). Kept as its own constant so bumping codex independently of// other agents stays easy if codex starts shipping longer failure traces.const (- codexStderrTailBytes = 2048- defaultCodexSemanticInactivityTimeout = 10 * time.Minute+ codexStderrTailBytes = 2048+ defaultCodexSemanticInactivityTimeout = 10 * time.Minute+ defaultCodexFirstTurnNoProgressTimeout = 30 * time.Second+ codexVersionDiagnosticTimeout = 2 * time.Second)// CodexSemanticInactivityMarker prefixes timeout errors emitted when Codex// stops making semantic progress while the process is still alive.const 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.+const CodexFirstTurnNoProgressMarker = "codex app-server no progress timeout"++const codexModelCatalogRefreshTimeoutSignal = "failed to refresh available models: timeout waiting for child process to exit"++type codexTimeoutKind int++const (+ codexTimeoutNone codexTimeoutKind = iota+ codexTimeoutSemanticInactivity+ codexTimeoutFirstTurnNoProgress+)++type codexTimeoutDiagnostic struct {+ Kind codexTimeoutKind+ Timeout time.Duration+ LastActivity string+ ThreadID string+ TurnID string+ Model string+ CodexVersion string+}+// codexBackend implements Backend by spawning `codex app-server --listen stdio://`// and communicating via JSON-RPC 2.0 over stdin/stdout.type codexBackend struct {@@ -244,7 +270,22 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOptisemanticTimer := time.NewTimer(semanticInactivityTimeout)defer semanticTimer.Stop()+ firstTurnNoProgressTimeout := codexFirstTurnNoProgressTimeout(semanticInactivityTimeout)+ var firstTurnNoProgressTimer *time.Timer+ var firstTurnNoProgressTimerC <-chan time.Time+ firstTurnStarted := false+ firstTurnProgressObserved := false+ stopFirstTurnNoProgressTimer := func() {+ if firstTurnNoProgressTimer == nil {+ return+ }+ stopTimer(firstTurnNoProgressTimer)+ firstTurnNoProgressTimerC = nil+ }+ defer stopFirstTurnNoProgressTimer()+waitingForTurn := true+ var timeoutDiagnostic codexTimeoutDiagnosticfor waitingForTurn {select {case aborted := <-turnDone:@@ -263,10 +304,43 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOptilastSemanticActivity = time.Now()lastSemanticActivityDescription = activityresetTimer(semanticTimer, semanticInactivityTimeout)+ if activity == "status:running" && !firstTurnStarted {+ firstTurnStarted = true+ firstTurnNoProgressTimer = time.NewTimer(firstTurnNoProgressTimeout)+ firstTurnNoProgressTimerC = firstTurnNoProgressTimer.C+ } else if firstTurnStarted && !firstTurnProgressObserved && isCodexFirstTurnProgressActivity(activity) {+ firstTurnProgressObserved = true+ stopFirstTurnNoProgressTimer()+ }+ case <-firstTurnNoProgressTimerC:+ waitingForTurn = false+ finalStatus = "timeout"+ timeoutDiagnostic = codexTimeoutDiagnostic{+ Kind: codexTimeoutFirstTurnNoProgress,+ Timeout: firstTurnNoProgressTimeout,+ LastActivity: lastSemanticActivityDescription,+ ThreadID: threadID,+ TurnID: c.turnID,+ Model: opts.Model,+ }+ b.cfg.Logger.Warn(CodexFirstTurnNoProgressMarker,+ "pid", cmd.Process.Pid,+ "thread_id", threadID,+ "turn_id", c.turnID,+ "timeout", firstTurnNoProgressTimeout.String(),+ "last_activity", lastSemanticActivityDescription,+ )case <-semanticTimer.C:waitingForTurn = falsefinalStatus = "timeout"- finalError = fmt.Sprintf("%s after %s without agent progress (last activity: %s)", CodexSemanticInactivityMarker, semanticInactivityTimeout, lastSemanticActivityDescription)+ timeoutDiagnostic = codexTimeoutDiagnostic{+ Kind: codexTimeoutSemanticInactivity,+ Timeout: semanticInactivityTimeout,+ LastActivity: lastSemanticActivityDescription,+ ThreadID: threadID,+ TurnID: c.turnID,+ Model: opts.Model,+ }b.cfg.Logger.Warn(CodexSemanticInactivityMarker,"pid", cmd.Process.Pid,"thread_id", threadID,@@ -298,6 +372,12 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti// Wait for the reader goroutine to finish so all output is accumulated.<-readerDone+ drainAndWait()++ if timeoutDiagnostic.Kind != codexTimeoutNone {+ timeoutDiagnostic.CodexVersion = detectCodexVersionForDiagnostics(context.Background(), execPath, cmd.Env, b.cfg.Logger)+ finalError = buildCodexTimeoutDiagnosticError(timeoutDiagnostic, stderrBuf.Tail())+ }outputMu.Lock()finalOutput := output.String()@@ -446,6 +526,106 @@ func resetTimer(timer *time.Timer, d time.Duration) {timer.Reset(d)}+func stopTimer(timer *time.Timer) {+ if timer == nil {+ return+ }+ if !timer.Stop() {+ select {+ case <-timer.C:+ default:+ }+ }+}++func codexFirstTurnNoProgressTimeout(semanticInactivityTimeout time.Duration) time.Duration {+ if semanticInactivityTimeout <= 0 || semanticInactivityTimeout > defaultCodexFirstTurnNoProgressTimeout {+ return defaultCodexFirstTurnNoProgressTimeout+ }+ scaled := semanticInactivityTimeout * 4 / 5+ if scaled <= 0 {+ return semanticInactivityTimeout+ }+ return scaled+}++func isCodexFirstTurnProgressActivity(activity string) bool {+ return activity != "" && activity != "status:running" && activity != "error:retry"+}++func buildCodexTimeoutDiagnosticError(diag codexTimeoutDiagnostic, stderrTail string) string {+ var msg string+ switch 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),+ )+ case codexTimeoutSemanticInactivity:+ 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"+ }+ msg = appendCodexKnownStderrHint(msg, stderrTail)+ return withAgentStderr(msg, "codex", stderrTail)+}++func formatCodexDiagnosticFields(diag codexTimeoutDiagnostic) string {+ return fmt.Sprintf("codex_version=%q thread_id=%q turn_id=%q model=%q",+ nonEmptyCodexDiagnosticValue(diag.CodexVersion),+ nonEmptyCodexDiagnosticValue(diag.ThreadID),+ nonEmptyCodexDiagnosticValue(diag.TurnID),+ formatCodexDiagnosticModel(diag.Model),+ )+}++func nonEmptyCodexDiagnosticValue(value string) string {+ if strings.TrimSpace(value) == "" {+ return "unknown"+ }+ return value+}++func formatCodexDiagnosticModel(model string) string {+ if strings.TrimSpace(model) == "" {+ return "default(empty)"+ }+ return model+}++func appendCodexKnownStderrHint(msg, stderrTail string) string {+ if strings.Contains(stderrTail, codexModelCatalogRefreshTimeoutSignal) {+ return msg + "; diagnosis: Codex stderr shows the model catalog refresh timed out. Try setting an explicit model, switching Codex CLI versions, or using another runtime while Codex app-server recovers"+ }+ return msg+}++func detectCodexVersionForDiagnostics(ctx context.Context, execPath string, env []string, logger *slog.Logger) string {+ versionCtx, cancel := context.WithTimeout(ctx, codexVersionDiagnosticTimeout)+ defer cancel()++ cmd := exec.CommandContext(versionCtx, execPath, "--version")+ cmd.Env = env+ data, err := cmd.Output()+ if err != nil {+ if logger != nil {+ logger.Debug("codex version diagnostic failed", "error", err)+ }+ return "unknown"+ }+ version := extractVersionLine(string(data))+ if strings.TrimSpace(version) == "" {+ return "unknown"+ }+ return version+}+func trySendString(ch chan<- string, value string) {select {case ch <- value:@@ -884,8 +1064,18 @@ 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 {+ c.onSemanticActivity("error:terminal")+ }+ }if !willRetry {c.setTurnError(errMsg)+ if c.onTurnDone != nil {+ c.onTurnDone(false)+ }}}@@ -971,15 +1161,7 @@ func (c *codexClient) handleItemNotification(method string, params map[string]an}func isCodexItemProgressActivity(method string) bool {- switch method {- case "item/agentMessage/delta",- "item/commandExecution/outputDelta",- "item/fileChange/outputDelta",- "item/mcpToolCall/progress":- return true- default:- return false- }+ return strings.HasPrefix(method, "item/")}func describeCodexItemProgressActivity(method, itemType, itemID string) string {diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.goindex 7e6d88a63e..3420247374 100644--- a/server/pkg/agent/codex_test.go+++ b/server/pkg/agent/codex_test.go@@ -456,12 +456,29 @@ func TestCodexRawErrorNotificationTerminal(t *testing.T) {c, _, _ := newTestCodexClient(t)c.notificationProtocol = "raw"+ 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+ }c.handleLine(`{"jsonrpc":"2.0","method":"error","params":{"error":{"message":"boom"},"willRetry":false}}`)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 got, want := strings.Join(activities, ","), "error:terminal"; got != want {+ t.Fatalf("semantic activity = %q, want %q", got, want)+ }}func TestCodexRawErrorNotificationRetryingIgnored(t *testing.T) {@@ -469,12 +486,51 @@ func TestCodexRawErrorNotificationRetryingIgnored(t *testing.T) {c, _, _ := newTestCodexClient(t)c.notificationProtocol = "raw"+ var activities []string+ c.onSemanticActivity = func(activity string) {+ activities = append(activities, activity)+ }+ 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}}`)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 {+ t.Fatalf("semantic activity = %q, want %q", got, want)+ }+}++func TestCodexFirstTurnProgressActivity(t *testing.T) {+ t.Parallel()++ cases := []struct {+ activity string+ want bool+ }{+ {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},+ {activity: "tool-result:exec_command", want: true},+ {activity: "item/started:commandExecution:cmd-1", want: true},+ {activity: "item/completed:agentMessage:msg-1", want: true},+ {activity: "error:terminal", want: true},+ {activity: "turn:completed", want: true},+ }++ for _, tc := range cases {+ t.Run(tc.activity, func(t *testing.T) {+ if got := isCodexFirstTurnProgressActivity(tc.activity); got != tc.want {+ t.Fatalf("isCodexFirstTurnProgressActivity(%q) = %v, want %v", tc.activity, got, tc.want)+ }+ })+ }}func TestCodexSetTurnErrorFirstWins(t *testing.T) {@@ -1107,6 +1163,112 @@ func TestCodexExecuteTimesOutWhenTurnStopsAfterToolResult(t *testing.T) {}}+func TestCodexExecuteFirstTurnNoProgressSurfacesDiagnostics(t *testing.T) {+ t.Parallel()+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }++ 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-stuck"}}}'`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-stuck","turn":{"id":"turn-stuck"}}}'`+"\n"++ `echo 'ERROR codex_models_manager::manager: failed to refresh available models: timeout waiting for child process to exit' >&2`+"\n"++ `sleep 5`+"\n")++ result := executeFakeCodex(t, fakePath, ExecOptions{+ Timeout: 5 * time.Second,+ SemanticInactivityTimeout: 100 * time.Millisecond,+ })+ if result.Status != "timeout" {+ t.Fatalf("expected timeout, got status=%q error=%q", result.Status, result.Error)+ }+ for _, want := range []string{+ CodexFirstTurnNoProgressMarker,+ "thr-stuck",+ "turn-stuck",+ `model="default(empty)"`,+ `codex_version="codex-cli 0.0.0-test"`,+ "model catalog refresh timed out",+ "codex stderr:",+ codexModelCatalogRefreshTimeoutSignal,+ } {+ if !strings.Contains(result.Error, want) {+ t.Fatalf("expected error to contain %q, got %q", want, result.Error)+ }+ }+}++func TestCodexExecuteFirstTurnRetryErrorDoesNotSatisfyProgress(t *testing.T) {+ t.Parallel()+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }++ 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-retry"}}}'`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-retry","turn":{"id":"turn-retry"}}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"error","params":{"threadId":"thr-retry","error":{"message":"temporary reconnect"},"willRetry":true}}'`+"\n"++ `sleep 5`+"\n")++ result := executeFakeCodex(t, fakePath, ExecOptions{+ Timeout: 5 * time.Second,+ SemanticInactivityTimeout: 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, CodexFirstTurnNoProgressMarker) {+ t.Fatalf("expected first-turn no-progress error, got %q", result.Error)+ }+ if strings.Contains(result.Error, CodexSemanticInactivityMarker) {+ t.Fatalf("retrying error should not demote first-turn timeout to semantic inactivity, got %q", result.Error)+ }+}++func TestCodexExecuteLegacyFirstTurnMessageSatisfiesProgress(t *testing.T) {+ t.Parallel()+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }++ 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-legacy"}}}'`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"task_started"}}}'`+"\n"++ `sleep 0.05`+"\n"++ `echo '{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"agent_message","message":"legacy alive"}}}'`+"\n"++ `sleep 0.07`+"\n"++ `echo '{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"task_complete"}}}'`+"\n")++ result := executeFakeCodex(t, fakePath, ExecOptions{+ Timeout: 5 * time.Second,+ SemanticInactivityTimeout: 100 * time.Millisecond,+ })+ if result.Status != "completed" {+ t.Fatalf("expected completed, got status=%q error=%q", result.Status, result.Error)+ }+ if result.Output != "legacy alive" {+ t.Fatalf("expected legacy output, got %q", result.Output)+ }+}+func TestCodexExecuteSemanticInactivityAllowsContinuousMessages(t *testing.T) {t.Parallel()if runtime.GOOS == "windows" {@@ -1156,7 +1318,6 @@ func TestCodexExecuteSemanticInactivityAllowsContinuousDeltaProgress(t *testing.`read line`+"\n"+`echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"+`echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-delta","turn":{"id":"turn-delta"}}}'`+"\n"+- `sleep 0.05`+"\n"+`echo '{"jsonrpc":"2.0","method":"item/commandExecution/outputDelta","params":{"threadId":"thr-delta","item":{"type":"commandExecution","id":"cmd-1"},"delta":"line 1\n"}}'`+"\n"+`sleep 0.05`+"\n"+`echo '{"jsonrpc":"2.0","method":"item/agentMessage/delta","params":{"threadId":"thr-delta","item":{"type":"agentMessage","id":"msg-1"},"delta":"thinking"}}'`+"\n"+@@ -1209,7 +1370,9 @@ func TestCodexExecuteSemanticInactivityDoesNotAffectNormalTurnCompletion(t *testfunc writeFakeCodexAppServer(t *testing.T, body string) string {t.Helper()fakePath := filepath.Join(t.TempDir(), "codex")- script := "#!/bin/sh\n" + body+ script := "#!/bin/sh\n" ++ `if [ "$1" = "--version" ]; then echo "codex-cli 0.0.0-test"; exit 0; fi` + "\n" ++ bodywriteTestExecutable(t, fakePath, []byte(script))return fakePath}