Skip to content

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

Go

MUL-6655 Fix MCode ACP session startup race (ZIC-199) (#7516)

ZIce750fc0cc5aef
diff --git a/server/pkg/agent/mcode.go b/server/pkg/agent/mcode.go
index a9de902bb8..e62ec427b1 100644
--- a/server/pkg/agent/mcode.go
+++ b/server/pkg/agent/mcode.go
@@ -3,6 +3,7 @@ package agent
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
"os/exec"
@@ -41,6 +42,9 @@ type mcodeBackend struct {
}
var mcodeReaderDrainGrace = 2 * time.Second
+var mcodeSessionStartupReadyDelay = 100 * time.Millisecond
+
+var errMcodeProcessExited = errors.New("mcode process exited")
type mcodeMessageStream struct {
ch chan Message
@@ -183,7 +187,7 @@ func (b *mcodeBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
c.handleLine(line)
}
}
- c.closeAllPending(fmt.Errorf("mcode process exited"))
+ c.closeAllPending(errMcodeProcessExited)
}()
go func() {
@@ -243,6 +247,16 @@ func (b *mcodeBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
}
return
}
+ if err := mcodeWaitForSessionStartup(runCtx); err != nil {
+ finalStatus, finalError = mcodeRequestFailure(runCtx, opts.Timeout, "session/load", err)
+ resCh <- Result{
+ Status: finalStatus,
+ Error: finalError,
+ DurationMs: time.Since(startTime).Milliseconds(),
+ ResumeRejected: resumeRejected,
+ }
+ return
+ }
result, loadErr := c.request(runCtx, "session/load", map[string]any{
"cwd": cwd,
"sessionId": opts.ResumeSessionID,
@@ -263,6 +277,11 @@ func (b *mcodeBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
}
sessionID, _ = resolveResumedSessionID(opts.ResumeSessionID, result)
} else {
+ if err := mcodeWaitForSessionStartup(runCtx); err != nil {
+ finalStatus, finalError = mcodeRequestFailure(runCtx, opts.Timeout, "session/new", err)
+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}
+ return
+ }
result, newErr := c.request(runCtx, "session/new", map[string]any{
"cwd": cwd,
"mcpServers": mcpServers,
@@ -357,6 +376,17 @@ func mcodeLoadSessionSupported(result json.RawMessage) bool {
return json.Unmarshal(result, &payload) == nil && payload.AgentCapabilities.LoadSession
}
+func mcodeWaitForSessionStartup(ctx context.Context) error {
+ timer := time.NewTimer(mcodeSessionStartupReadyDelay)
+ defer timer.Stop()
+ select {
+ case <-timer.C:
+ return nil
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
+
func mcodeRequestFailure(ctx context.Context, timeout time.Duration, operation string, err error) (string, string) {
if ctx.Err() == context.DeadlineExceeded {
return "timeout", fmt.Sprintf("mcode timed out during %s after %s", operation, timeout)
@@ -364,5 +394,20 @@ func mcodeRequestFailure(ctx context.Context, timeout time.Duration, operation s
if ctx.Err() == context.Canceled {
return "aborted", "execution cancelled"
}
+ if mcodeSessionStartupExited(operation, err) {
+ return "failed", "mcode session/new failed after initialize: MiniMax Code ACP exited before starting a session; retry agent creation, and if it persists upgrade MiniMax Code or verify `mcode acp` starts successfully"
+ }
return "failed", fmt.Sprintf("mcode %s failed: %v", operation, err)
}
+
+func mcodeSessionStartupExited(operation string, err error) bool {
+ if operation != "session/new" {
+ return false
+ }
+ // Only trust transport-level signals. A still-running MCode reports
+ // session/new failures as a JSON-RPC error, and session/new is where
+ // mcpServers are launched, so text matching on "process exited" or
+ // "broken pipe" would rewrite a caller's real MCP startup error into
+ // an MCode-exited message and drop its root cause.
+ return errors.Is(err, errMcodeProcessExited) || errors.Is(err, io.ErrClosedPipe) || errors.Is(err, syscall.EPIPE)
+}
diff --git a/server/pkg/agent/mcode_test.go b/server/pkg/agent/mcode_test.go
index e4bcf8c639..891040579f 100644
--- a/server/pkg/agent/mcode_test.go
+++ b/server/pkg/agent/mcode_test.go
@@ -4,11 +4,14 @@ import (
"context"
"encoding/json"
"fmt"
+ "io"
"log/slog"
"os"
"path/filepath"
"strings"
+ "syscall"
"testing"
+ "time"
)
func writeFakeMcodeACP(t *testing.T, loadSession bool) (string, string, string) {
@@ -49,6 +52,70 @@ done
return bin, requests, args
}
+func writeFakeMcodeACPReadyAfterInitialize(t *testing.T, readyAfter time.Duration) (string, string) {
+ t.Helper()
+ dir := t.TempDir()
+ bin := filepath.Join(dir, "mcode")
+ requests := filepath.Join(dir, "requests.jsonl")
+ ready := filepath.Join(dir, "ready")
+ script := fmt.Sprintf(`#!/bin/sh
+while IFS= read -r line; do
+ printf '%%s\n' "$line" >> %q
+ id=$(printf '%%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
+ case "$line" in
+ *'"method":"initialize"'*)
+ printf '{"jsonrpc":"2.0","id":%%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"
+ ( sleep %.3f; : > %q ) &
+ ;;
+ *'"method":"session/new"'*)
+ if [ ! -f %q ]; then
+ exit 42
+ fi
+ printf '{"jsonrpc":"2.0","id":%%s,"result":{"sessionId":"mcode-ready-session"}}\n' "$id"
+ ;;
+ *'"method":"session/prompt"'*)
+ printf '{"jsonrpc":"2.0","id":%%s,"result":{"stopReason":"end_turn"}}\n' "$id"
+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"mcode-ready-session","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ready"}}}}\n'
+ ;;
+ *)
+ printf '{"jsonrpc":"2.0","id":%%s,"error":{"code":-32601,"message":"method not found"}}\n' "$id"
+ ;;
+ esac
+done
+`, requests, readyAfter.Seconds(), ready, ready)
+ if err := os.WriteFile(bin, []byte(script), 0o755); err != nil {
+ t.Fatalf("write fake mcode: %v", err)
+ }
+ return bin, requests
+}
+
+func writeFakeMcodeACPExitsOnSessionNew(t *testing.T) string {
+ t.Helper()
+ dir := t.TempDir()
+ bin := filepath.Join(dir, "mcode")
+ script := `#!/bin/sh
+while IFS= read -r line; do
+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
+ case "$line" in
+ *'"method":"initialize"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"
+ ;;
+ *'"method":"session/new"'*)
+ printf 'mcode exited while starting a session\n' >&2
+ exit 42
+ ;;
+ *)
+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32601,"message":"method not found"}}\n' "$id"
+ ;;
+ esac
+done
+`
+ if err := os.WriteFile(bin, []byte(script), 0o755); err != nil {
+ t.Fatalf("write fake mcode: %v", err)
+ }
+ return bin
+}
+
func TestNewReturnsMcodeBackend(t *testing.T) {
t.Parallel()
backend, err := New("mcode", Config{ExecutablePath: "/nonexistent/mcode"})
@@ -120,6 +187,57 @@ func TestMcodeFreshSessionUsesACPAndForwardsMCP(t *testing.T) {
}
}
+func TestMcodeWaitsForSessionNewReadinessAfterInitialize(t *testing.T) {
+ t.Parallel()
+ bin, requestsFile := writeFakeMcodeACPReadyAfterInitialize(t, 50*time.Millisecond)
+ backend, err := New("mcode", Config{ExecutablePath: bin, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("New(mcode): %v", err)
+ }
+ session, err := backend.Execute(context.Background(), "ship it", ExecOptions{Cwd: t.TempDir()})
+ if err != nil {
+ t.Fatalf("Execute: %v", err)
+ }
+ for range session.Messages {
+ }
+ result := <-session.Result
+ if result.Status != "completed" || result.SessionID != "mcode-ready-session" {
+ t.Fatalf("result = %+v", result)
+ }
+ requests, err := os.ReadFile(requestsFile)
+ if err != nil {
+ t.Fatalf("read requests: %v", err)
+ }
+ if !strings.Contains(string(requests), `"method":"session/new"`) {
+ t.Fatalf("session/new was not sent:\n%s", requests)
+ }
+}
+
+func TestMcodeSessionNewExitAfterInitializeReportsStartupFailure(t *testing.T) {
+ t.Parallel()
+ bin := writeFakeMcodeACPExitsOnSessionNew(t)
+ backend, err := New("mcode", Config{ExecutablePath: bin, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("New(mcode): %v", err)
+ }
+ session, err := backend.Execute(context.Background(), "ship it", ExecOptions{Cwd: t.TempDir()})
+ if err != nil {
+ t.Fatalf("Execute: %v", err)
+ }
+ for range session.Messages {
+ }
+ result := <-session.Result
+ if result.Status != "failed" {
+ t.Fatalf("result = %+v, want failed", result)
+ }
+ if !strings.Contains(result.Error, "session/new failed after initialize") {
+ t.Fatalf("error = %q, want session/new startup failure", result.Error)
+ }
+ if strings.Contains(result.Error, "initialize failed") {
+ t.Fatalf("error = %q, must not blame initialize", result.Error)
+ }
+}
+
func TestMcodeUnsupportedResumeRequestsFreshRetry(t *testing.T) {
t.Parallel()
bin, requestsFile, _ := writeFakeMcodeACP(t, false)
@@ -190,3 +308,86 @@ func TestMcodeBlockedArgsKeepACPTransportStable(t *testing.T) {
}
}
}
+
+// A still-running MCode reports session/new failures as a JSON-RPC error, and
+// session/new is the call that launches mcpServers. Only transport-level exit
+// signals may be reported as "MiniMax Code ACP exited" — anything else must
+// reach the member with its root cause intact.
+func TestMcodeSessionStartupExitedOnlyTrustsTransportSignals(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ operation string
+ err error
+ want bool
+ }{
+ {
+ name: "reader saw the process exit",
+ operation: "session/new",
+ err: errMcodeProcessExited,
+ want: true,
+ },
+ {
+ name: "stdin write raced the exit",
+ operation: "session/new",
+ err: fmt.Errorf("write session/new: %w", syscall.EPIPE),
+ want: true,
+ },
+ {
+ name: "closed pipe",
+ operation: "session/new",
+ err: fmt.Errorf("write session/new: %w", io.ErrClosedPipe),
+ want: true,
+ },
+ {
+ name: "live mcode reporting a failed MCP server is not an mcode exit",
+ operation: "session/new",
+ err: &acpRPCError{Method: "session/new", Code: -32603, Message: "Internal error", Data: `failed to start MCP server "filesystem": process exited with code 1`},
+ want: false,
+ },
+ {
+ name: "live mcode reporting a broken pipe to an MCP child is not an mcode exit",
+ operation: "session/new",
+ err: &acpRPCError{Method: "session/new", Code: -32603, Message: "Internal error", Data: "write to mcp stdio: broken pipe"},
+ want: false,
+ },
+ {
+ name: "unrelated live error",
+ operation: "session/new",
+ err: &acpRPCError{Method: "session/new", Code: -32602, Message: "Invalid params", Data: "cwd must be absolute"},
+ want: false,
+ },
+ {
+ name: "wrong operation does not match",
+ operation: "session/load",
+ err: errMcodeProcessExited,
+ want: false,
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := mcodeSessionStartupExited(tt.operation, tt.err); got != tt.want {
+ t.Fatalf("mcodeSessionStartupExited(%q, %v) = %v, want %v", tt.operation, tt.err, got, tt.want)
+ }
+ })
+ }
+}
+
+// The rewritten startup message carries no %v, so a false positive would not
+// just mislabel the failure — it would drop the original error entirely.
+func TestMcodeRequestFailureKeepsLiveSessionErrorRootCause(t *testing.T) {
+ t.Parallel()
+
+ err := &acpRPCError{Method: "session/new", Code: -32603, Message: "Internal error", Data: `failed to start MCP server "filesystem": process exited with code 1`}
+ status, msg := mcodeRequestFailure(context.Background(), 0, "session/new", err)
+ if status != "failed" {
+ t.Fatalf("status = %q, want failed", status)
+ }
+ if !strings.Contains(msg, "failed to start MCP server") {
+ t.Fatalf("error = %q, want the original MCP failure preserved", msg)
+ }
+ if strings.Contains(msg, "MiniMax Code ACP exited") {
+ t.Fatalf("error = %q, must not blame an mcode exit while mcode is still running", msg)
+ }
+}