Skip to content

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

Go

MUL-7983: fix(agent): handle CodeBuddy startup errors without aborting active runs (#9214)

小七74ff8aabd7f8
diff --git a/server/pkg/agent/codebuddy.go b/server/pkg/agent/codebuddy.go
index f0d6e0dce6..9e0f155877 100644
--- a/server/pkg/agent/codebuddy.go
+++ b/server/pkg/agent/codebuddy.go
@@ -206,6 +206,9 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Exec
sawResult := false
resultIsError := false
sawBackgroundTask := false
+ sawStartedEvent := false
+ topLevelError := ""
+ fatalStartupError := false
var sessionID string
usage := make(map[string]TokenUsage)
seenUsage := make(map[string]struct{})
@@ -239,6 +242,7 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Exec
switch msg.Type {
case "assistant":
+ sawStartedEvent = true
assistantEventCount++
turn := b.handleAssistant(msg, msgCh, usage, seenUsage)
toolUseCount += turn.toolUses
@@ -247,8 +251,10 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Exec
}
lastAssistantText = turn.resolveFallback(lastAssistantText)
case "user":
+ sawStartedEvent = true
b.handleUser(msg, msgCh)
case "system":
+ sawStartedEvent = true
if msg.SessionID != "" {
sessionID = msg.SessionID
}
@@ -270,6 +276,25 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Exec
usage = resultUsage
}
closeStdin()
+ case "error":
+ // Startup failures can leave CodeBuddy alive and silent (issue
+ // #9200). Once a run has emitted system/assistant activity, the
+ // same event can be recoverable, so keep the process running.
+ if sawResult || fatalStartupError {
+ break
+ }
+ topLevelError = strings.TrimSpace(msg.Error)
+ if topLevelError == "" {
+ topLevelError = "codebuddy emitted a top-level error event without details"
+ }
+ if !sawStartedEvent && runCtx.Err() == nil {
+ fatalStartupError = true
+ // Cancel only before the run starts; this also releases the
+ // scanner and cmd.Wait when the CLI remains alive.
+ cancel()
+ } else {
+ trySend(msgCh, Message{Type: MessageLog, Level: "error", Content: topLevelError})
+ }
case "log":
if msg.Log != nil {
trySend(msgCh, Message{
@@ -320,6 +345,14 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Exec
},
completionGuardError,
)
+ // A startup error explains our own cancellation. After the run has
+ // started, use its last error only if it exited without a result;
+ // preserve an external cancellation or timeout otherwise.
+ if topLevelError != "" && !sawResult && (fatalStartupError || runCtx.Err() == nil) {
+ finalStatus = "failed"
+ finalOutput = ""
+ finalError = topLevelError
+ }
// cmd.Wait() has returned — stderrBuf.Tail() is complete. Resume
// rejection phrases often land only on stderr (mirror Claude MUL-4966).
@@ -534,17 +567,33 @@ func writeCodebuddyInput(w io.Writer, prompt string) error {
const codebuddyDisableBackgroundTasksEnv = "CODEBUDDY_CODE_DISABLE_BACKGROUND_TASKS"
-// buildCodebuddyEnv merges task env and always forces background tasks off.
+// CodeBuddy's PowerShell tool moves a command to the background when it hits
+// its foreground timeout and only honors this variable — the headless
+// background-task disable above does not stop it (issue #9200).
+const codebuddyDisableBashAutoBackgroundEnv = "CODEBUDDY_BASH_AUTO_BACKGROUND_DISABLED"
+
+// A user-scope SERVER__PORT (shared by several tools' configs) pins every
+// codebuddy run's internal HTTP server to one port; a second concurrent run
+// then dies with EADDRINUSE before doing any work (issue #9200). Port 0 lets
+// the OS assign a free port per run.
+const codebuddyInternalPortEnv = "SERVER__PORT"
+
+// buildCodebuddyEnv merges task env and always forces background tasks off,
+// a random internal HTTP port and the PowerShell auto-background disable.
// Multica's adapter closes stdin after the first result; CodeBuddy's
// background lifecycle can push task_notification after that point, which we
-// cannot observe. The official CLI documents this variable for exactly that
-// headless shape (https://www.codebuddy.ai/docs/cli/headless).
+// cannot observe. The official CLI documents the disable variable for exactly
+// that headless shape (https://www.codebuddy.ai/docs/cli/headless).
//
-// Append the forced entry last so os/exec's platform-aware dedup
-// (case-insensitive on Windows, last-wins) keeps our "=1" even when the
+// Append the forced entries last so os/exec's platform-aware dedup
+// (case-insensitive on Windows, last-wins) keeps them even when the
// inherited or custom_env key differs only by case.
func buildCodebuddyEnv(extra map[string]string) []string {
- return append(buildEnv(extra), codebuddyDisableBackgroundTasksEnv+"=1")
+ return append(buildEnv(extra),
+ codebuddyInternalPortEnv+"=0",
+ codebuddyDisableBashAutoBackgroundEnv+"=1",
+ codebuddyDisableBackgroundTasksEnv+"=1",
+ )
}
// codebuddySystemIsBackgroundTask reports CodeBuddy's real background-task
@@ -568,6 +617,10 @@ type codebuddySDKMessage struct {
Model string `json:"model,omitempty"`
ParentToolUseID string `json:"parent_tool_use_id,omitempty"`
+ // Top-level error events can be fatal during startup or recoverable once
+ // the run has begun; the message is inline rather than in a result event.
+ Error string `json:"error,omitempty"`
+
// result fields — CodeBuddy failures use is_error + errors/errors_info;
// there is no Claude-style terminal_reason=prompt_too_long signal in the
// shipped @tencent-ai/codebuddy-code 2.150.0 protocol.
diff --git a/server/pkg/agent/codebuddy_test.go b/server/pkg/agent/codebuddy_test.go
index e8707a09f4..7e6fcd6cf5 100644
--- a/server/pkg/agent/codebuddy_test.go
+++ b/server/pkg/agent/codebuddy_test.go
@@ -680,3 +680,248 @@ func TestCodebuddyExecuteFailsOnBackgroundTaskStarted(t *testing.T) {
t.Fatal("timeout waiting for result")
}
}
+
+func TestCodebuddyExecuteFailsOnTopLevelError(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ // Issue #9200: with an inherited SERVER__PORT a second concurrent codebuddy
+ // run fails to listen, prints one top-level {"type":"error"} line and then
+ // stays alive without emitting anything else. The parser had no branch for
+ // that type, so the run sat at "waiting for agent response" until the idle
+ // watchdog stopped it. The fake replays exactly that shape: error line,
+ // then a process that stays alive and silent. Timeout is 0 (watchdog-only
+ // liveness, like the incident), so without the error branch this test only
+ // ends via the 5s result-wait deadline.
+ fakePath := filepath.Join(t.TempDir(), "codebuddy")
+ script := "#!/bin/sh\n" +
+ "IFS= read -r _\n" +
+ `printf '%s\n' '{"type":"error","error":"listen EADDRINUSE: address already in use 127.0.0.1:42888"}'` + "\n" +
+ "sleep 60\n"
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ b := &codebuddyBackend{cfg: Config{ExecutablePath: fakePath, Logger: slog.Default()}}
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ session, err := b.Execute(ctx, "prompt", ExecOptions{})
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ 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 failed on top-level error event, got %q (error=%q)", result.Status, result.Error)
+ }
+ if !strings.Contains(result.Error, "EADDRINUSE") {
+ t.Fatalf("expected the CLI error text in result.Error, got %q", result.Error)
+ }
+ if result.Output != "" {
+ t.Fatalf("failed run must return empty output, got %q", result.Output)
+ }
+ // 30s budget: in a fully parallel suite the teardown path (spawn → error
+ // line → cancel → process-group kill → finalize) has been observed to take
+ // up to ~13s on a loaded machine; on the unfixed baseline the run never
+ // ends, so any budget detects it.
+ case <-time.After(30 * time.Second):
+ t.Fatal("top-level error event did not fail the run; still waiting for the idle watchdog")
+ }
+}
+
+func TestCodebuddyExecuteErrorAfterResultDoesNotFlipOutcome(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ // An error line trailing an already-seen terminal result must not flip a
+ // finished run to failed: the result event governs the outcome.
+ fakePath := filepath.Join(t.TempDir(), "codebuddy")
+ script := "#!/bin/sh\n" +
+ "IFS= read -r _\n" +
+ `printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"session_id":"sess-late","result":"done"}'` + "\n" +
+ `printf '%s\n' '{"type":"error","error":"late noise"}'` + "\n" +
+ "exit 0\n"
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ b := &codebuddyBackend{cfg: Config{ExecutablePath: fakePath, Logger: slog.Default()}}
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ session, err := b.Execute(ctx, "prompt", ExecOptions{Timeout: 5 * time.Second})
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ 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 != "completed" {
+ t.Fatalf("expected completed when result precedes the error line, got %q (error=%q)", result.Status, result.Error)
+ }
+ if result.Output != "done" {
+ t.Fatalf("expected output to survive, got %q", result.Output)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("timeout waiting for result")
+ }
+}
+
+func TestCodebuddyExecuteContinuesAfterRuntimeError(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ // CodeBuddy can report a recoverable control-message error after its run
+ // has started, then still produce a successful terminal result.
+ fakePath := filepath.Join(t.TempDir(), "codebuddy")
+ script := "#!/bin/sh\n" +
+ "IFS= read -r _\n" +
+ `printf '%s\n' '{"type":"system","subtype":"init","session_id":"sess-recovered"}'` + "\n" +
+ `printf '%s\n' '{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"Working"}]}}'` + "\n" +
+ `printf '%s\n' '{"type":"error","error":"control response rejected"}'` + "\n" +
+ `printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"session_id":"sess-recovered","result":"done"}'` + "\n"
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ b := &codebuddyBackend{cfg: Config{ExecutablePath: fakePath, Logger: slog.Default()}}
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ session, err := b.Execute(ctx, "prompt", ExecOptions{})
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+
+ var sawErrorLog bool
+ for msg := range session.Messages {
+ if msg.Type == MessageLog && msg.Level == "error" && msg.Content == "control response rejected" {
+ sawErrorLog = true
+ }
+ }
+ result := <-session.Result
+ if result.Status != "completed" || result.Output != "done" {
+ t.Fatalf("recoverable error must not stop the run, got %+v", result)
+ }
+ if !sawErrorLog {
+ t.Fatal("expected recoverable error to appear in the message stream")
+ }
+}
+
+func TestCodebuddyExecuteReportsRuntimeErrorWithoutResult(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ fakePath := filepath.Join(t.TempDir(), "codebuddy")
+ script := "#!/bin/sh\n" +
+ "IFS= read -r _\n" +
+ `printf '%s\n' '{"type":"system","subtype":"init","session_id":"sess-no-result"}'` + "\n" +
+ `printf '%s\n' '{"type":"error","error":"control channel failed"}'` + "\n" +
+ "exit 0\n"
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ b := &codebuddyBackend{cfg: Config{ExecutablePath: fakePath, Logger: slog.Default()}}
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ session, err := b.Execute(ctx, "prompt", ExecOptions{})
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ for range session.Messages {
+ }
+ result := <-session.Result
+ if result.Status != "failed" || result.Output != "" || !strings.Contains(result.Error, "control channel failed") {
+ t.Fatalf("expected the CLI error when the stream ends without a result, got %+v", result)
+ }
+}
+
+func TestCodebuddyExecuteRuntimeErrorDoesNotOverrideCancellation(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ fakePath := filepath.Join(t.TempDir(), "codebuddy")
+ script := "#!/bin/sh\n" +
+ "IFS= read -r _\n" +
+ `printf '%s\n' '{"type":"system","subtype":"init","session_id":"sess-cancel"}'` + "\n" +
+ `printf '%s\n' '{"type":"error","error":"recoverable control error"}'` + "\n" +
+ "sleep 60\n"
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ b := &codebuddyBackend{cfg: Config{ExecutablePath: fakePath, Logger: slog.Default()}}
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ session, err := b.Execute(ctx, "prompt", ExecOptions{})
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+
+ var sawErrorLog bool
+ for msg := range session.Messages {
+ if msg.Type == MessageLog && msg.Content == "recoverable control error" {
+ sawErrorLog = true
+ cancel()
+ }
+ }
+ result := <-session.Result
+ if !sawErrorLog || result.Status != "aborted" {
+ t.Fatalf("user cancellation must outrank a prior recoverable error, log=%v result=%+v", sawErrorLog, result)
+ }
+}
+
+func TestBuildCodebuddyEnvForcesRandomInternalPortAndBashBackground(t *testing.T) {
+ t.Parallel()
+
+ // Issue #9200: a user-scope SERVER__PORT pins every codebuddy run's
+ // internal HTTP server to one port, so concurrent runs of the same agent
+ // collide with EADDRINUSE. Force port 0 (OS-assigned) the same way the
+ // background-task disable is forced.
+ env := buildCodebuddyEnv(map[string]string{"SERVER__PORT": "42888", "FOO": "bar"})
+ if got := lastEnvValueFold(env, "SERVER__PORT"); got != "0" {
+ t.Fatalf("expected forced SERVER__PORT=0 in child env, got %q (env=%v)", got, env)
+ }
+ if got := lastEnvValueFold(env, "CODEBUDDY_BASH_AUTO_BACKGROUND_DISABLED"); got != "1" {
+ t.Fatalf("expected CODEBUDDY_BASH_AUTO_BACKGROUND_DISABLED=1 in child env, got %q (env=%v)", got, env)
+ }
+
+ // The PowerShell tool moves timed-out commands to the background unless
+ // CODEBUDDY_BASH_AUTO_BACKGROUND_DISABLED is set; a caller-provided "0"
+ // must lose to the forced "1".
+ env = buildCodebuddyEnv(map[string]string{"CODEBUDDY_BASH_AUTO_BACKGROUND_DISABLED": "0"})
+ if got := lastEnvValueFold(env, "CODEBUDDY_BASH_AUTO_BACKGROUND_DISABLED"); got != "1" {
+ t.Fatalf("expected forced =1 even when caller passes 0, got %q", got)
+ }
+
+ // Forced entries must be the last exact-key occurrences so os/exec's
+ // Windows dedup (case-insensitive, last-wins) keeps them.
+ for _, key := range []string{"SERVER__PORT", "CODEBUDDY_BASH_AUTO_BACKGROUND_DISABLED"} {
+ lastExact := ""
+ for _, entry := range env {
+ k, v, ok := strings.Cut(entry, "=")
+ if ok && k == key {
+ lastExact = v
+ }
+ }
+ if (key == "SERVER__PORT" && lastExact != "0") || (key == "CODEBUDDY_BASH_AUTO_BACKGROUND_DISABLED" && lastExact != "1") {
+ t.Fatalf("forced %s entry must be last exact key for Windows dedup, got last=%q (env=%v)", key, lastExact, env)
+ }
+ }
+}