Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6472: fix(autopilots): stop leaking dispatch error text through Run now (#7311)
Bohan Jianga12985ab01c6
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex 9873fd4d09..785ead4a50 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -1,5 +1,5 @@import { afterEach, describe, expect, it, vi } from "vitest";-import { ApiClient, ApiError, CHAT_DRAFT_RESTORE_CAPABILITY } from "./client";+import { ApiClient, ApiError, CHAT_DRAFT_RESTORE_CAPABILITY, clientErrorMessage } from "./client";import { EMPTY_PLUGIN_PREVIEW } from "./schemas";afterEach(() => {@@ -2292,3 +2292,28 @@ describe("ApiClient workspace MCP servers", () => {expect(init.method).toBe("DELETE");});});++describe("clientErrorMessage", () => {+ it("returns a 4xx message, which handlers write for the user", () => {+ expect(clientErrorMessage(new ApiError("autopilot is not active", 400, "Bad Request")))+ .toBe("autopilot is not active");+ expect(clientErrorMessage(new ApiError("forbidden", 403, "Forbidden"))).toBe("forbidden");+ });++ it("withholds a 5xx message, which carries internal server detail", () => {+ // MUL-6472: the pre-fix body for a failed autopilot trigger looked like+ // this, and it was rendered verbatim in the run-now toast.+ const leaky = new ApiError(+ 'failed to trigger autopilot: create run: ERROR: duplicate key value violates unique constraint "autopilot_run_pkey" (SQLSTATE 23505)',+ 500,+ "Internal Server Error",+ );+ expect(clientErrorMessage(leaky)).toBeUndefined();+ expect(clientErrorMessage(new ApiError("internal error", 503, "Service Unavailable"))).toBeUndefined();+ });++ it("withholds a transport failure, whose message says nothing actionable", () => {+ expect(clientErrorMessage(new TypeError("Failed to fetch"))).toBeUndefined();+ expect(clientErrorMessage(undefined)).toBeUndefined();+ });+});diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 5f1115e5bb..1561fd6cc1 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -507,6 +507,20 @@ export function dispatchReasonCode(err: unknown): string | undefined {return undefined;}+// clientErrorMessage returns the server's message only when it is a CLIENT+// error (4xx). Handlers write those for the user — "autopilot is not active",+// "Idempotency-Key is too long" — so they are worth rendering. A 5xx message is+// internal detail (Go error chains, pgx table/constraint names, internal ids)+// that must never reach a toast (MUL-6472), and a non-ApiError is a transport+// failure whose message ("Failed to fetch") says nothing a user can act on.+// Both return undefined so the caller falls back to its own localized sentence.+export function clientErrorMessage(err: unknown): string | undefined {+ if (err instanceof ApiError && err.status >= 400 && err.status < 500) {+ return err.message || undefined;+ }+ return undefined;+}+// Thrown by getAttachmentTextContent when the server refuses to inline a// file because it exceeds the 2 MB cap. UI maps to a "too large, please// download" affordance with the Download CTA still available.diff --git a/packages/core/api/index.ts b/packages/core/api/index.tsindex 37ceca318d..10ad9a254e 100644--- a/packages/core/api/index.ts+++ b/packages/core/api/index.ts@@ -1,6 +1,7 @@export {ApiClient,ApiError,+ clientErrorMessage,dispatchReasonCode,errorCode,PreviewTooLargeError,diff --git a/packages/views/autopilots/components/autopilot-detail-page.tsx b/packages/views/autopilots/components/autopilot-detail-page.tsxindex 2414b8c8ae..f7ad2f79b5 100644--- a/packages/views/autopilots/components/autopilot-detail-page.tsx+++ b/packages/views/autopilots/components/autopilot-detail-page.tsx@@ -18,7 +18,7 @@ import {useRotateAutopilotTriggerWebhookToken,} from "@multica/core/autopilots/mutations";import { buildAutopilotWebhookUrl } from "@multica/core/autopilots";-import { api, dispatchReasonCode } from "@multica/core/api";+import { api, clientErrorMessage, dispatchReasonCode } from "@multica/core/api";import { useWorkspaceId } from "@multica/core/hooks";import { useWorkspacePaths } from "@multica/core/paths";import { useActorName } from "@multica/core/workspace/hooks";@@ -742,11 +742,14 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {}} catch (e: any) {const reason = dispatchReasonCode(e);- toast.error(- reason- ? t(($) => $.detail[runNowBlockedKey(reason)])- : e?.message || t(($) => $.detail.toast_trigger_failed),- );+ if (reason) {+ toast.error(t(($) => $.detail[runNowBlockedKey(reason)]));+ return;+ }+ // Only a 4xx message is written for the user; a 5xx one is internal+ // server detail (MUL-6472), so an unclassified dispatch failure shows the+ // localized generic sentence instead of the raw body.+ toast.error(clientErrorMessage(e) || t(($) => $.detail.toast_trigger_failed));}};diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.goindex c102a781bd..dc9e951dcd 100644--- a/server/internal/handler/autopilot.go+++ b/server/internal/handler/autopilot.go@@ -7,6 +7,7 @@ import ("errors""fmt""io"+ "log/slog""net/http""strconv""strings"@@ -2116,7 +2117,16 @@ func (h *Handler) TriggerAutopilot(w http.ResponseWriter, r *http.Request) {})return}- writeError(w, http.StatusInternalServerError, "failed to trigger autopilot: "+err.Error())+ // Everything past the quota branch is an unclassified internal failure+ // whose chain carries pgx constraint/table names and internal ids. Any+ // workspace member can reach "run now", so the detail stays in the log+ // and the response is the same fixed 5xx string the rest of this file+ // returns (MUL-6472).+ slog.Error("trigger autopilot failed",+ "error", err,+ "autopilot_id", uuidToString(autopilot.ID),+ )+ writeError(w, http.StatusInternalServerError, "failed to trigger autopilot")return}diff --git a/server/internal/handler/autopilot_trigger_error_test.go b/server/internal/handler/autopilot_trigger_error_test.gonew file mode 100644index 0000000000..bf693c100e--- /dev/null+++ b/server/internal/handler/autopilot_trigger_error_test.go@@ -0,0 +1,85 @@+package handler++import (+ "context"+ "net/http"+ "strings"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/multica-ai/multica/server/internal/entitlement"+ "github.com/multica-ai/multica/server/internal/entitlement/entitlementtest"+ "github.com/multica-ai/multica/server/internal/testutil"+)++// TestTriggerAutopilot_InternalFailureDoesNotEchoError pins MUL-6472: an+// unclassified dispatch failure answers with a FIXED 500 string. The chain+// behind it names internal machinery (here "create run: load idempotent quota+// run: no rows in result set", elsewhere pgx table/constraint names), and every+// workspace member can reach "run now" — so none of it may reach the body. The+// 429 quota branch above it is deliberately structured and stays covered by+// TestAutopilotQuotaManualAndWebhookEnforcement.+func TestTriggerAutopilot_InternalFailureDoesNotEchoError(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ // A valid, far-from-exhausted policy: the request has to travel past the+ // 429 branch and into the idempotency lookup this test breaks.+ start := time.Now().UTC().Truncate(time.Second).Add(-time.Hour)+ end := start.Add(24 * time.Hour)+ limit := 1000+ stub := entitlementtest.New()+ stub.Set(uuid.MustParse(testWorkspaceID), entitlement.GateAutopilotRuns, entitlement.Decision{+ Gate: entitlement.Gate{+ Action: entitlement.ActionEnforce, Limit: &limit,+ PeriodStart: &start, PeriodEnd: &end, ResetAt: &end,+ },+ PolicyRevision: 3, SubscriptionVersion: 5,+ })+ priorProvider := testHandler.AutopilotService.Entitlements+ testHandler.AutopilotService.Entitlements = stub+ t.Cleanup(func() {+ testHandler.AutopilotService.Entitlements = priorProvider+ testPool.Exec(context.Background(), `DELETE FROM autopilot_quota_period WHERE workspace_id = $1`, testWorkspaceID)+ })++ agentID := createWebhookTestAgent(t, "MUL-6472 Trigger Agent")+ autopilotID := createWebhookTestAutopilot(t, agentID, "active", "run_only")++ // A settled reservation with no run row pointing back at it. Reusing its+ // key sends dispatch down the idempotent-reuse path, where the missing run+ // is an internal error rather than the recoverable "reserved" orphan case.+ // The stored key is the one the manual entry point composes, not the raw+ // header value.+ const idempotencyKey = "mul-6472-orphaned-reservation"+ dbfx.Insert(t, "autopilot_quota_reservation", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "period_start": start,+ "period_end": end,+ "policy_revision": 3,+ "subscription_version": 5,+ "source": "manual",+ "idempotency_key": "manual:" + autopilotID + ":" + idempotencyKey,+ "state": "consumed",+ })++ req := testutil.WithHeaders(+ newRequest("POST", "/api/autopilots/"+autopilotID+"/trigger", nil),+ "Idempotency-Key", idempotencyKey,+ )+ res := testutil.Call(t, testHandler.TriggerAutopilot, withURLParam(req, "id", autopilotID)).+ Want(http.StatusInternalServerError)++ if got := res.Map()["error"]; got != "failed to trigger autopilot" {+ t.Fatalf("error = %#v, want the fixed string with no error chain appended", got)+ }+ // Substrings of the chain this failure actually produces, plus the pgx+ // marker every DB-level failure on this path would carry.+ for _, leak := range []string{"create run", "idempotent", "quota", "no rows", "sqlstate"} {+ if strings.Contains(strings.ToLower(res.Text()), leak) {+ t.Fatalf("500 body leaks internal detail %q: %s", leak, res.Text())+ }+ }+}