Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agent/codex): surface stderr tail in initialize / turn startup errors (#1314)
Bohan Jiangec73710dd214
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.goindex a178a89690..b887c15169 100644--- a/server/pkg/agent/codex.go+++ b/server/pkg/agent/codex.go@@ -5,6 +5,7 @@ import ("context""encoding/json""fmt"+ "io""log/slog""os""os/exec"@@ -20,6 +21,62 @@ var codexBlockedArgs = map[string]blockedArgMode{"--listen": blockedWithValue, // stdio:// transport for daemon communication}+// codexStderrTailBytes bounds the stderr tail captured for inclusion in+// error messages when codex exits before the JSON-RPC handshake (e.g. the+// user supplied a custom_args flag that the `app-server` subcommand+// rejects). Large enough to contain typical CLI error lines, small enough+// to stay sensible inside a task-level Result.Error string.+const codexStderrTailBytes = 2048++// stderrTail forwards writes to an inner writer (typically the daemon's+// log) while also retaining a bounded tail of the bytes written. Consumers+// call Tail() to include that context in error messages when the codex+// process exits before we can read a structured JSON-RPC error — otherwise+// all the user sees is "codex process exited", with the real reason stuck+// in daemon logs.+type stderrTail struct {+ inner io.Writer+ max int++ mu sync.Mutex+ buf []byte+}++func newStderrTail(inner io.Writer, max int) *stderrTail {+ return &stderrTail{inner: inner, max: max}+}++func (s *stderrTail) Write(p []byte) (int, error) {+ if _, err := s.inner.Write(p); err != nil {+ return 0, err+ }+ s.mu.Lock()+ s.buf = append(s.buf, p...)+ if len(s.buf) > s.max {+ s.buf = s.buf[len(s.buf)-s.max:]+ }+ s.mu.Unlock()+ return len(p), nil+}++// Tail returns the captured stderr with leading/trailing whitespace+// trimmed; empty string means nothing was written or everything was+// whitespace.+func (s *stderrTail) Tail() string {+ s.mu.Lock()+ defer s.mu.Unlock()+ return strings.TrimSpace(string(s.buf))+}++// withCodexStderr appends a stderr tail hint to an error message when+// non-empty, otherwise returns msg unchanged.+func withCodexStderr(msg, tail string) string {+ if tail == "" {+ return msg+ }+ return msg + "; codex stderr: " + tail+}+// codexBackend implements Backend by spawning `codex app-server --listen stdio://`// and communicating via JSON-RPC 2.0 over stdin/stdout.type codexBackend struct {@@ -59,7 +116,8 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpticancel()return nil, fmt.Errorf("codex stdin pipe: %w", err)}- cmd.Stderr = newLogWriter(b.cfg.Logger, "[codex:stderr] ")+ stderrBuf := newStderrTail(newLogWriter(b.cfg.Logger, "[codex:stderr] "), codexStderrTailBytes)+ cmd.Stderr = stderrBufif err := cmd.Start(); err != nil {cancel()@@ -115,6 +173,22 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOptic.closeAllPending(fmt.Errorf("codex process exited"))}()+ // drainAndWait closes stdin so codex shuts down, then joins cmd.Wait().+ // cmd.Wait() is the only Go-stdlib-documented synchronization point for+ // os/exec's internal stderr/stdout copy goroutines — until it returns,+ // stderrBuf may not have observed every byte codex wrote before it+ // exited, and stderrBuf.Tail() can come back empty or truncated. Any+ // code that reads stderrBuf.Tail() must call drainAndWait() first.+ // sync.Once makes it safe to call from both error paths and the deferred+ // cleanup.+ var waitOnce sync.Once+ drainAndWait := func() {+ waitOnce.Do(func() {+ stdin.Close()+ _ = cmd.Wait()+ })+ }+// Drive the session lifecycle in a goroutine.// Shutdown sequence: lifecycle goroutine closes stdin + cancels context →// codex process exits → reader goroutine's scanner.Scan() returns false →@@ -123,10 +197,7 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOptidefer cancel()defer close(msgCh)defer close(resCh)- defer func() {- stdin.Close()- _ = cmd.Wait()- }()+ defer drainAndWait()startTime := time.Now()finalStatus := "completed"@@ -144,8 +215,9 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti},})if err != nil {+ drainAndWait() // flush os/exec stderr goroutine before sampling TailfinalStatus = "failed"- finalError = fmt.Sprintf("codex initialize failed: %v", err)+ finalError = withCodexStderr(fmt.Sprintf("codex initialize failed: %v", err), stderrBuf.Tail())resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}return}@@ -156,8 +228,9 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti// back to a fresh thread so the task still makes progress.threadID, resumed, err := c.startOrResumeThread(runCtx, opts, b.cfg.Logger)if err != nil {+ drainAndWait() // flush os/exec stderr goroutine before sampling TailfinalStatus = "failed"- finalError = err.Error()+ finalError = withCodexStderr(err.Error(), stderrBuf.Tail())resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}return}@@ -176,8 +249,9 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti},})if err != nil {+ drainAndWait() // flush os/exec stderr goroutine before sampling TailfinalStatus = "failed"- finalError = fmt.Sprintf("codex turn/start failed: %v", err)+ finalError = withCodexStderr(fmt.Sprintf("codex turn/start failed: %v", err), stderrBuf.Tail())resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}return}@@ -315,14 +389,14 @@ func (c *codexClient) startOrResumeThread(ctx context.Context, opts ExecOptions,// ── codexClient: JSON-RPC 2.0 transport ──type codexClient struct {- cfg Config- stdin interface{ Write([]byte) (int, error) }- mu sync.Mutex- nextID int- pending map[int]*pendingRPC- threadID string- turnID string- onMessage func(Message)+ cfg Config+ stdin interface{ Write([]byte) (int, error) }+ mu sync.Mutex+ nextID int+ pending map[int]*pendingRPC+ threadID string+ turnID string+ onMessage func(Message)onTurnDone func(aborted bool)notificationProtocol string // "unknown", "legacy", "raw"diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.goindex 20361ae273..314af8d458 100644--- a/server/pkg/agent/codex_test.go+++ b/server/pkg/agent/codex_test.go@@ -5,6 +5,9 @@ import ("encoding/json""fmt""log/slog"+ "os"+ "path/filepath"+ "runtime""strings""sync""testing"@@ -911,3 +914,115 @@ func TestCodexProtocolDetectionLegacyBlocksRaw(t *testing.T) {t.Fatal("raw notification should be ignored in legacy mode")}}++func TestStderrTailForwardsAndCapturesTail(t *testing.T) {+ t.Parallel()++ var sink strings.Builder+ s := newStderrTail(&sink, 16)++ if _, err := s.Write([]byte("first line\n")); err != nil {+ t.Fatalf("write: %v", err)+ }+ if _, err := s.Write([]byte("error: unexpected argument '-m' found\n")); err != nil {+ t.Fatalf("write: %v", err)+ }++ // Inner writer sees every byte verbatim.+ want := "first line\nerror: unexpected argument '-m' found\n"+ if sink.String() != want {+ t.Errorf("inner sink: got %q, want %q", sink.String(), want)+ }++ // Tail is bounded by max; earlier bytes get dropped.+ tail := s.Tail()+ if len(tail) > 16 {+ t.Errorf("tail exceeds bound: got %d bytes (%q)", len(tail), tail)+ }+ if tail == "" {+ t.Fatal("expected non-empty tail")+ }+ // Tail must be a suffix of what was written (whitespace-trimmed).+ if !strings.HasSuffix(strings.TrimSpace(want), tail) {+ t.Errorf("tail %q is not a suffix of %q", tail, want)+ }+}++func TestStderrTailEmptyWhenNothingWritten(t *testing.T) {+ t.Parallel()++ var sink strings.Builder+ s := newStderrTail(&sink, 16)+ if tail := s.Tail(); tail != "" {+ t.Errorf("expected empty tail, got %q", tail)+ }+}++func TestCodexExecuteSurfacesStderrWhenChildExitsEarly(t *testing.T) {+ t.Parallel()+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }++ // Fake codex binary: writes a canonical CLI rejection line to stderr and+ // exits before ever responding to `initialize`, mimicking what real codex+ // does when `app-server` gets a flag it doesn't accept. This exercises the+ // real os/exec stderr pipe-copy goroutine — without drainAndWait joining+ // cmd.Wait() before sampling stderrBuf.Tail(), Result.Error would come+ // back empty or truncated here.+ fakePath := filepath.Join(t.TempDir(), "codex")+ script := "#!/bin/sh\n" ++ "echo \"error: unexpected argument '-m' found\" >&2\n" ++ "exit 2\n"+ if err := os.WriteFile(fakePath, []byte(script), 0o755); err != nil {+ t.Fatalf("write fake codex: %v", err)+ }++ backend, err := New("codex", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("new codex backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{Timeout: 5 * time.Second})+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ // Drain message stream so the lifecycle goroutine can progress.+ go func() {+ for range session.Messages {+ }+ }()++ select {+ case result, ok := <-session.Result:+ if !ok {+ t.Fatal("result channel closed without a value")+ }+ if result.Status != "failed" {+ t.Fatalf("expected status=failed, got %q (error=%q)", result.Status, result.Error)+ }+ if !strings.Contains(result.Error, "codex initialize failed") {+ t.Fatalf("expected error to mention initialize failure, got %q", result.Error)+ }+ if !strings.Contains(result.Error, "unexpected argument '-m' found") {+ t.Fatalf("expected error to include stderr hint, got %q", result.Error)+ }+ case <-time.After(10 * time.Second):+ t.Fatal("timeout waiting for result")+ }+}++func TestWithCodexStderrAppendsHint(t *testing.T) {+ t.Parallel()++ if got := withCodexStderr("codex initialize failed: process exited", ""); got != "codex initialize failed: process exited" {+ t.Errorf("empty tail should not modify msg, got %q", got)+ }+ msg := withCodexStderr("codex initialize failed: process exited", "unexpected argument '-m' found")+ want := "codex initialize failed: process exited; codex stderr: unexpected argument '-m' found"+ if msg != want {+ t.Errorf("got %q, want %q", msg, want)+ }+}