Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5619: fix(cli): surface the server's 409 message instead of the generic conflict template (#6267)
Bohan Jiangd38da27ed4cb
diff --git a/server/internal/cli/errors.go b/server/internal/cli/errors.goindex e095d7ec70..0c83fe8929 100644--- a/server/internal/cli/errors.go+++ b/server/internal/cli/errors.go@@ -337,6 +337,22 @@ var kindMessages = map[ErrorKind][2]string{},}+// serverMessagePrefixes lists the kinds whose response body carries a+// hand-written, actionable message worth showing instead of the generic+// template, with the {English, Chinese} lead-in used to introduce it.+//+// 409 belongs here because the generic conflict copy is not merely vague, it+// points the wrong way: it reads as a transient race ("re-fetch the latest+// state and try again") while every conflict this API returns is a+// deterministic refusal that names its own fix ("a skill with this name+// already exists", "set parent_id (--parent) to <id>"). Agents took the retry+// hint literally and burned hours re-sending an unchanged request (GH #6264,+// GH #5948), and the server-side wording added in MUL-4417 never reached them.+var serverMessagePrefixes = map[ErrorKind][2]string{+ KindValidation: {"Invalid request: ", "请求无效:"},+ KindConflict: {"Request conflict: ", "请求冲突:"},+}+// messageFor returns the localized message for a kind.func messageFor(kind ErrorKind, lang Language) string {m, ok := kindMessages[kind]@@ -391,14 +407,16 @@ func userMessage(err error, lang Language) string {var httpErr *HTTPErrorif errors.As(err, &httpErr) {kind := httpErr.Kind()- // Validation errors usually carry a useful server-provided message;- // surface it instead of the generic line.- if kind == KindValidation {+ // Validation and conflict errors carry a useful server-provided+ // message; surface it instead of the generic line. A body we cannot+ // recognize still falls back to the template, so this never dumps a+ // raw response at the user.+ if prefix, ok := serverMessagePrefixes[kind]; ok {if serverMsg := extractServerMessage(httpErr.Body); serverMsg != "" {if lang == LangZH {- return "请求无效:" + serverMsg+ return prefix[1] + serverMsg}- return "Invalid request: " + serverMsg+ return prefix[0] + serverMsg}}return messageFor(kind, lang)@@ -413,6 +431,11 @@ func userMessage(err error, lang Language) string {// extractServerMessage tries to pull a human-readable message out of a JSON// error body like {"error":"..."} or {"message":"..."}. Returns "" if the// body is not JSON or has no recognizable message field.+//+// A few endpoints put a stable machine code in "error" and the prose in+// "message" (the issue-table cursor responses do this). Prose always wins;+// a bare code is kept only as a last resort so the user still gets something+// greppable when no sentence is on offer.func extractServerMessage(body string) string {body = strings.TrimSpace(body)if body == "" || body[0] != '{' {@@ -422,14 +445,47 @@ func extractServerMessage(body string) string {if err := json.Unmarshal([]byte(body), &parsed); err != nil {return ""}+ var code stringfor _, key := range []string{"error", "message", "detail", "title"} {- if v, ok := parsed[key]; ok {- if s, ok := v.(string); ok && strings.TrimSpace(s) != "" {- return strings.TrimSpace(s)+ v, ok := parsed[key]+ if !ok {+ continue+ }+ s, ok := v.(string)+ if !ok {+ continue+ }+ if s = strings.TrimSpace(s); s == "" {+ continue+ }+ if looksLikeMachineCode(s) {+ if code == "" {+ code = s}+ continue+ }+ return s+ }+ return code+}++// looksLikeMachineCode reports whether s is a bare identifier such as+// "cursor_query_mismatch" rather than a sentence meant for a person. The test+// is deliberately narrow — lowercase word characters only — so that ordinary+// prose in any language, including Chinese without ASCII spaces, is never+// mistaken for a code.+func looksLikeMachineCode(s string) bool {+ if s == "" {+ return false+ }+ for _, r := range s {+ switch {+ case r >= 'a' && r <= 'z', r >= '0' && r <= '9', r == '_', r == '-', r == '.':+ default:+ return false}}- return ""+ return true}// debugDetail renders the full original error chain plus any structureddiff --git a/server/internal/cli/errors_test.go b/server/internal/cli/errors_test.goindex 9e7474d21f..980c335705 100644--- a/server/internal/cli/errors_test.go+++ b/server/internal/cli/errors_test.go@@ -133,6 +133,107 @@ func TestFormatErrorValidationUsesServerMessage(t *testing.T) {}}+// TestFormatErrorConflictUsesServerMessage pins GH #6264: a 409 body carries a+// hand-written fix ("reply under this comment", "a skill with that name+// exists"), and the generic conflict template actively misdirects by telling+// the caller to retry. The server message must reach the user by default, with+// no --debug required.+func TestFormatErrorConflictUsesServerMessage(t *testing.T) {+ withLang(t, "en_US.UTF-8")+ httpErr := &HTTPError{+ Method: "POST",+ Path: "/api/issues/abc/comments",+ StatusCode: 409,+ Body: `{"error":"parent_id 11111111-1111-1111-1111-111111111111 is not a comment this task may reply under; set parent_id (--parent) to 22222222-2222-2222-2222-222222222222 or a coalesced comment id"}`,+ }+ wrapped := fmt.Errorf("add comment: %w", httpErr)++ got := FormatError(wrapped, false)+ if !strings.Contains(got, "set parent_id (--parent) to 22222222-2222-2222-2222-222222222222") {+ t.Errorf("expected server conflict message surfaced, got %q", got)+ }+ // The retry advice is what sent agents into multi-hour loops; it must not+ // be what they see when the server already named the fix.+ if strings.Contains(got, "Re-fetch the latest state") {+ t.Errorf("generic retry template should be replaced by the server message, got %q", got)+ }+ if strings.Contains(got, "/api/issues/abc/comments") {+ t.Errorf("user message leaked the request path: %q", got)+ }+}++func TestFormatErrorConflictChineseLocale(t *testing.T) {+ withLang(t, "zh_CN.UTF-8")+ httpErr := &HTTPError{StatusCode: 409, Body: `{"error":"a skill with this name already exists"}`}+ got := FormatError(httpErr, false)+ if !strings.Contains(got, "请求冲突:") || !strings.Contains(got, "a skill with this name already exists") {+ t.Errorf("expected Chinese conflict prefix with server message, got %q", got)+ }+}++// TestFormatErrorConflictFallsBackToGenericTemplate is the safety half: only a+// JSON body with a known message field is surfaced, so an HTML error page or a+// proxy response never gets dumped at the user.+func TestFormatErrorConflictFallsBackToGenericTemplate(t *testing.T) {+ withLang(t, "en_US.UTF-8")+ for _, body := range []string{+ `<html><body>409 Conflict</body></html>`,+ `{"code":"runtime_has_active_agents"}`,+ ``,+ } {+ got := FormatError(&HTTPError{StatusCode: 409, Body: body}, false)+ if !strings.Contains(got, "Re-fetch the latest state") {+ t.Errorf("body %q: expected generic conflict template, got %q", body, got)+ }+ if body != "" && strings.Contains(got, body) {+ t.Errorf("body %q: raw body leaked into user message %q", body, got)+ }+ }+}++// TestExtractServerMessagePrefersProseOverMachineCode covers the endpoints that+// put a stable code in "error" and the sentence in "message" (issue-table+// cursor responses). The sentence is what helps a person.+func TestExtractServerMessagePrefersProseOverMachineCode(t *testing.T) {+ got := extractServerMessage(`{"error":"cursor_query_mismatch","message":"cursor does not belong to this table branch"}`)+ if got != "cursor does not belong to this table branch" {+ t.Errorf("expected the prose message, got %q", got)+ }++ // With no sentence available the code is still better than nothing.+ if got := extractServerMessage(`{"error":"cursor_query_mismatch"}`); got != "cursor_query_mismatch" {+ t.Errorf("expected the bare code as fallback, got %q", got)+ }++ // Prose in a language without ASCII spaces must not be mistaken for a code.+ if got := extractServerMessage(`{"error":"该名称已被占用"}`); got != "该名称已被占用" {+ t.Errorf("expected non-ASCII prose preserved, got %q", got)+ }+}++// TestFormatErrorValidationPrefersProseOverMachineCode pins an intentional+// behavior change that rides along with the conflict fix: the prose preference+// lives in the shared extractor, so a 400/422 whose "error" holds a machine code+// now shows its "message" instead of the code. Only the issue-table endpoints+// are shaped this way and none of them is reachable from the CLI today, but the+// change is deliberate and should fail loudly if someone reverts it by accident.+func TestFormatErrorValidationPrefersProseOverMachineCode(t *testing.T) {+ withLang(t, "en_US.UTF-8")+ got := FormatError(&HTTPError{+ StatusCode: 422,+ Body: `{"error":"unsupported_group","code":"group_kind_unsupported","message":"This group type is not supported."}`,+ }, false)+ if !strings.Contains(got, "This group type is not supported.") {+ t.Errorf("expected the prose message, got %q", got)+ }++ // A validation body carrying only a code is unchanged.+ only := FormatError(&HTTPError{StatusCode: 422, Body: `{"error":"title_is_required"}`}, false)+ if !strings.Contains(only, "title_is_required") {+ t.Errorf("code-only validation body should still surface the code, got %q", only)+ }+}+func TestFormatErrorDebugIncludesRawChain(t *testing.T) {withLang(t, "en_US.UTF-8")httpErr := &HTTPError{Method: "GET", Path: "/api/issues/abc", StatusCode: 404, Body: `{"error":"not found"}`}diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex 091cba404d..3086fab75a 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -1804,8 +1804,18 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {if task.TriggerCommentID.Valid {if !taskCoversReplyParent(task, parentID) {// Keep this error actionable for agents (MUL-4417 / GH #5266).- writeError(w, http.StatusConflict,- "comment-triggered tasks cannot create top-level comments; set parent_id (--parent) to "+uuidToString(task.TriggerCommentID)+" or a coalesced comment id")+ // The two rejections need different copy. A resumed+ // session carrying a previous turn's --parent forward+ // (GH #6264) did NOT ask for a top-level comment, and+ // telling it that it did sends it looking for a+ // new-thread opt-in instead of simply correcting the+ // parent it already passed.+ fix := "set parent_id (--parent) to " + uuidToString(task.TriggerCommentID) + " or a coalesced comment id"+ msg := "comment-triggered tasks cannot create top-level comments; " + fix+ if parentID.Valid {+ msg = "parent_id " + uuidToString(parentID) + " is not a comment this task may reply under; " + fix+ }+ writeError(w, http.StatusConflict, msg)return}}diff --git a/server/internal/handler/comment_reply_authz_handler_test.go b/server/internal/handler/comment_reply_authz_handler_test.goindex fd124918bd..edbcef9604 100644--- a/server/internal/handler/comment_reply_authz_handler_test.go+++ b/server/internal/handler/comment_reply_authz_handler_test.go@@ -1,6 +1,7 @@package handlerimport (+ "context""encoding/json""net/http""net/http/httptest"@@ -82,3 +83,63 @@ func TestCreateComment_TriggeredTaskAllowsReplyUnderTrigger(t *testing.T) {t.Fatalf("CreateComment reply-under-trigger: expected 201, got %d: %s", w.Code, w.Body.String())}}++// TestCreateComment_TriggeredTaskRejectsForeignParent covers the resumed-session+// drift in GH #6264: the task passes a --parent that is a real comment on its+// own issue but not one this run was given to answer. The refusal must name+// both the parent it rejected and the parent to use — and must NOT say a+// top-level comment was attempted, since that wording sent agents looking for a+// new-thread opt-in instead of correcting the --parent they already passed.+func TestCreateComment_TriggeredTaskRejectsForeignParent(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ fx := newRunningSquadLeaderTaskFixture(t)++ // Must be a real comment on the same issue: a nonexistent id, or one from+ // another issue, is refused earlier with a 400 and never reaches this guard.+ var foreignParentID string+ if err := testPool.QueryRow(context.Background(), `+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type)+ VALUES ($1, $2, 'member', $3, 'an earlier thread this task never owned', 'comment')+ RETURNING id+ `, fx.IssueID, testWorkspaceID, testUserID).Scan(&foreignParentID); err != nil {+ t.Fatalf("create foreign parent comment: %v", err)+ }++ w := httptest.NewRecorder()+ r := newRequest("POST", "/api/issues/"+fx.IssueID+"/comments", map[string]any{+ "content": "posting under a parent carried over from a previous turn",+ "parent_id": foreignParentID,+ })+ r = withURLParam(r, "id", fx.IssueID)+ r.Header.Set("X-Agent-ID", fx.LeaderID)+ r.Header.Set("X-Task-ID", fx.TaskID)++ testHandler.CreateComment(w, r)+ if w.Code != http.StatusConflict {+ t.Fatalf("CreateComment foreign parent: expected 409, got %d: %s", w.Code, w.Body.String())+ }+ if got := countAgentCommentsForIssue(t, fx.IssueID, fx.LeaderID); got != 0 {+ t.Fatalf("expected rejected comment not to be stored, got %d", got)+ }++ var body map[string]any+ if err := json.NewDecoder(w.Body).Decode(&body); err != nil {+ t.Fatalf("decode error response: %v", err)+ }+ msg, _ := body["error"].(string)+ for _, want := range []string{+ foreignParentID, // the parent that was refused+ fx.TriggerCommentID, // the parent to use instead+ "parent_id (--parent)", // actionable fix+ } {+ if !strings.Contains(msg, want) {+ t.Fatalf("409 message should contain %q, got %q", want, msg)+ }+ }+ if strings.Contains(msg, "top-level") {+ t.Fatalf("409 message must not claim a top-level comment was attempted, got %q", msg)+ }+}diff --git a/server/internal/handler/runtime_update.go b/server/internal/handler/runtime_update.goindex 493b699854..2a30b11f38 100644--- a/server/internal/handler/runtime_update.go+++ b/server/internal/handler/runtime_update.go@@ -3,6 +3,7 @@ package handlerimport ("context""encoding/json"+ "errors""log/slog""net/http""sync"@@ -249,7 +250,19 @@ func (h *Handler) InitiateUpdate(w http.ResponseWriter, r *http.Request) {uuidToString(member.UserID),)if err != nil {- writeError(w, http.StatusConflict, err.Error())+ // Only the in-progress rejection is a conflict the caller can act on.+ // Every other Create failure is infrastructure — the Redis store wraps+ // connection failures as "reserve active update: ..." / "persist update+ // request: ..." — and echoing it back would both leak internals and+ // label an outage as a user-fixable conflict. That was survivable while+ // the CLI hid 409 bodies; it no longer is, now that they are shown by+ // default.+ if errors.Is(err, errUpdateInProgress) {+ writeError(w, http.StatusConflict, err.Error())+ return+ }+ slog.Error("UpdateStore Create failed", "error", err, "runtime_id", uuidToString(rt.ID))+ writeError(w, http.StatusInternalServerError, "failed to start the update")return}diff --git a/server/internal/handler/runtime_update_error_classification_test.go b/server/internal/handler/runtime_update_error_classification_test.gonew file mode 100644index 0000000000..6b5548eee3--- /dev/null+++ b/server/internal/handler/runtime_update_error_classification_test.go@@ -0,0 +1,83 @@+package handler++import (+ "context"+ "errors"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++// failingUpdateStore returns a chosen error from Create. The embedded interface+// supplies the rest of the method set; InitiateUpdate only reaches Create, so+// anything else calling through would panic loudly rather than pass silently.+type failingUpdateStore struct {+ UpdateStore+ createErr error+}++func (s *failingUpdateStore) Create(context.Context, string, string, string) (*UpdateRequest, error) {+ return nil, s.createErr+}++// TestInitiateUpdate_InfrastructureErrorIsNotAConflict pins the classification+// split this PR adds alongside GH #6264. InitiateUpdate used to answer every+// UpdateStore.Create failure with a 409 carrying err.Error(). That was survivable+// while the CLI hid conflict bodies; now that they print by default, a Redis+// outage would show its dial address to the user and read as a conflict they+// could fix by retrying.+func TestInitiateUpdate_InfrastructureErrorIsNotAConflict(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ // Shape mirrors RedisUpdateStore.Create wrapping a dial failure.+ infraErr := errors.New("reserve active update: dial tcp 10.1.2.3:6379: connect: connection refused")++ original := testHandler.UpdateStore+ testHandler.UpdateStore = &failingUpdateStore{createErr: infraErr}+ t.Cleanup(func() { testHandler.UpdateStore = original })++ w := httptest.NewRecorder()+ r := newRequest("POST", "/api/runtimes/"+testRuntimeID+"/update", map[string]any{"target_version": "v1.2.3"})+ r = withURLParams(r, "runtimeId", testRuntimeID)++ testHandler.InitiateUpdate(w, r)++ if w.Code != http.StatusInternalServerError {+ t.Fatalf("infrastructure failure: expected 500, got %d: %s", w.Code, w.Body.String())+ }+ body := w.Body.String()+ for _, leak := range []string{"10.1.2.3:6379", "connection refused", "reserve active update"} {+ if strings.Contains(body, leak) {+ t.Fatalf("response leaked internal detail %q: %s", leak, body)+ }+ }+}++// TestInitiateUpdate_InProgressStillConflicts is the positive half: the one+// Create failure a caller can actually act on keeps its 409 and its actionable+// wording, which is exactly what the CLI now surfaces by default.+func TestInitiateUpdate_InProgressStillConflicts(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ original := testHandler.UpdateStore+ testHandler.UpdateStore = &failingUpdateStore{createErr: errUpdateInProgress}+ t.Cleanup(func() { testHandler.UpdateStore = original })++ w := httptest.NewRecorder()+ r := newRequest("POST", "/api/runtimes/"+testRuntimeID+"/update", map[string]any{"target_version": "v1.2.3"})+ r = withURLParams(r, "runtimeId", testRuntimeID)++ testHandler.InitiateUpdate(w, r)++ if w.Code != http.StatusConflict {+ t.Fatalf("update-in-progress: expected 409, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "already in progress") {+ t.Fatalf("409 should keep its actionable message, got %s", w.Body.String())+ }+}