Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(wecom): stop blaming an admin's credentials when the fault is ours (#6589)
Xichang(Seacen) Zhao0db0055964e9
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 5b932be1de..e74e7abd60 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -401,6 +401,20 @@ export class ApiError extends Error {}}+// errorCode extracts the stable `code` a handler attaches to a failure+// (writeErrorCode), so a caller can render its own localized sentence instead+// of toasting the server's English one. Returns undefined for a non-ApiError,+// or a server that did not send one — the caller then falls back to+// err.message, which is what every endpoint that has not adopted this yet+// produces.+export function errorCode(err: unknown): string | undefined {+ if (err instanceof ApiError && err.body && typeof err.body === "object") {+ const code = (err.body as { code?: unknown }).code;+ if (typeof code === "string" && code.length > 0) return code;+ }+ return undefined;+}+// dispatchReasonCode extracts the stable, machine-readable admission reason// (MUL-4525) from a blocked-trigger error's structured body, when present. UI// callers localize a blocked/partial trigger from this code instead of patterndiff --git a/packages/core/api/index.ts b/packages/core/api/index.tsindex d1143ebfd5..37ceca318d 100644--- a/packages/core/api/index.ts+++ b/packages/core/api/index.ts@@ -2,6 +2,7 @@ export {ApiClient,ApiError,dispatchReasonCode,+ errorCode,PreviewTooLargeError,PreviewUnsupportedError,} from "./client";diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 47ef81db3c..a0317dbf62 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -766,6 +766,13 @@"byo_submitting": "Connecting…","byo_cancel": "Cancel","byo_success_toast": "WeCom bot connected",+ "byo_conflict_same_workspace": "This bot is already connected to another Agent in this workspace. Disconnect it there first, then connect it here.",+ "byo_conflict_archived_agent": "This bot is connected to an archived Agent in this workspace. Restore that Agent, or disconnect its bot, before connecting it here.",+ "byo_conflict_other_workspace": "This bot is already connected to a different Multica workspace. Disconnect it there before connecting it here.",+ "byo_rejected": "Could not connect the bot. Check the Bot ID and secret from the WeCom admin console, and that it is a smart bot with the long connection enabled.",+ "byo_credentials_rejected": "WeCom rejected this Bot ID and secret. Check both on the WeCom admin console, and that it is a smart bot with the long connection enabled.",+ "byo_credentials_unverifiable": "Couldn't reach WeCom to verify this bot. Your credentials were not changed — try again in a moment.",+ "byo_install_failed": "Couldn't save this bot — something went wrong on our side. Your credentials were not changed; try again, and contact support if it keeps failing.","byo_failed_toast": "Could not connect the WeCom bot"},"repositories": {diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex 2074023fcc..778c3aff04 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -765,6 +765,13 @@"byo_submitting": "接続中…","byo_cancel": "キャンセル","byo_success_toast": "WeCom ボットを接続しました",+ "byo_conflict_same_workspace": "このボットはこのワークスペースの別のエージェントに接続済みです。先にそちらで切断してから、ここに接続してください。",+ "byo_conflict_archived_agent": "このボットはこのワークスペースのアーカイブ済みエージェントに接続されています。そのエージェントを復元するか、ボットを切断してから接続してください。",+ "byo_conflict_other_workspace": "このボットは別の Multica ワークスペースに接続済みです。先にそちらで切断してから接続してください。",+ "byo_rejected": "ボットを接続できませんでした。WeCom 管理コンソールの Bot ID とシークレット、および長時間接続が有効なスマートボットであることを確認してください。",+ "byo_credentials_rejected": "WeCom がこの Bot ID とシークレットを拒否しました。WeCom 管理コンソールで両方を確認し、長時間接続が有効なスマートボットであることもご確認ください。",+ "byo_credentials_unverifiable": "WeCom に接続できず、このボットを検証できませんでした。認証情報は変更されていません。少し時間をおいてもう一度お試しください。",+ "byo_install_failed": "ボットを保存できませんでした。こちら側の問題です。認証情報は変更されていません。もう一度お試しいただき、続くようならサポートにご連絡ください。","byo_failed_toast": "WeCom ボットを接続できませんでした"},"repositories": {diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex f4cc05b845..bcb7601301 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -870,6 +870,13 @@"byo_submitting": "연결 중…","byo_cancel": "취소","byo_success_toast": "WeCom 봇을 연결했어요",+ "byo_conflict_same_workspace": "이 봇은 이미 이 워크스페이스의 다른 에이전트에 연결되어 있어요. 거기서 먼저 연결을 해제한 뒤 여기에 연결해 주세요.",+ "byo_conflict_archived_agent": "이 봇은 이 워크스페이스의 보관된 에이전트에 연결되어 있어요. 그 에이전트를 복원하거나 봇 연결을 해제한 뒤 연결해 주세요.",+ "byo_conflict_other_workspace": "이 봇은 이미 다른 Multica 워크스페이스에 연결되어 있어요. 거기서 먼저 연결을 해제한 뒤 연결해 주세요.",+ "byo_rejected": "봇을 연결하지 못했어요. WeCom 관리 콘솔의 Bot ID와 시크릿, 그리고 장기 연결이 켜진 스마트 봇인지 확인해 주세요.",+ "byo_credentials_rejected": "WeCom이 이 Bot ID와 시크릿을 거부했어요. WeCom 관리 콘솔에서 두 값을 확인하고, 장기 연결이 켜진 스마트 봇인지도 확인해 주세요.",+ "byo_credentials_unverifiable": "WeCom에 연결하지 못해 이 봇을 확인할 수 없었어요. 인증 정보는 변경되지 않았어요. 잠시 후 다시 시도해 주세요.",+ "byo_install_failed": "봇을 저장하지 못했어요. 저희 쪽 문제입니다. 인증 정보는 변경되지 않았어요. 다시 시도해 보시고, 계속 실패하면 지원팀에 문의해 주세요.","byo_failed_toast": "WeCom 봇을 연결하지 못했어요"}}diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex d8b6ad9f07..3710d3964e 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -765,6 +765,13 @@"byo_submitting": "连接中…","byo_cancel": "取消","byo_success_toast": "企业微信机器人已连接",+ "byo_conflict_same_workspace": "该机器人已连接到本工作区的另一个智能体。请先在那里断开,再连接到这里。",+ "byo_conflict_archived_agent": "该机器人连接在本工作区一个已归档的智能体上。请先恢复那个智能体,或断开它的机器人,再连接到这里。",+ "byo_conflict_other_workspace": "该机器人已连接到另一个 Multica 工作区。请先在那边断开,再连接到这里。",+ "byo_rejected": "无法连接机器人。请核对企业微信管理后台的 Bot ID 与密钥,并确认它是已开启长连接的智能机器人。",+ "byo_credentials_rejected": "企业微信拒绝了这组 Bot ID 和密钥。请在企业微信管理后台核对这两项,并确认它是已开启长连接的智能机器人。",+ "byo_credentials_unverifiable": "没能连上企业微信来校验这个机器人。你的凭据没有被改动,请稍后重试。",+ "byo_install_failed": "没能保存这个机器人,是我们这边出了问题。你的凭据没有被改动,请重试;如果一直失败,请联系支持。","byo_failed_toast": "无法连接企业微信机器人"},"repositories": {diff --git a/packages/views/settings/components/wecom-tab.test.tsx b/packages/views/settings/components/wecom-tab.test.tsxindex 4c63715261..f047a223b6 100644--- a/packages/views/settings/components/wecom-tab.test.tsx+++ b/packages/views/settings/components/wecom-tab.test.tsx@@ -79,6 +79,10 @@ vi.mock("@multica/core/api", () => ({registerWecomBYO: mockRegisterBYO,deleteWecomInstallation: mockDeleteInstallation,},+ // The real one digs the code out of an ApiError body; the fake reads it off+ // whatever the test threw, so a test can drive one branch of the switch.+ errorCode: (e: unknown) =>+ e && typeof e === "object" ? (e as { code?: string }).code : undefined,}));vi.mock("@multica/core/auth", () => {@@ -94,6 +98,7 @@ vi.mock("sonner", () => ({toast: { success: vi.fn(), error: vi.fn(), message: vi.fn() },}));+import { toast } from "sonner";import { WecomAgentBindButton, WecomTab } from "./wecom-tab";const TEST_RESOURCES = { en: { common: enCommon, settings: enSettings } };@@ -133,6 +138,78 @@ describe("WecomAgentBindButton", () => {);});+ // The whole point of the server sending a code: a zh-Hans admin gets the+ // Chinese sentence, not the English one the API happens to carry.+ it("renders the localized sentence for a coded failure, not the server's English", async () => {+ mockRegisterBYO.mockRejectedValue(+ Object.assign(new Error("this bot is already connected to another agent in this workspace"), {+ code: "wecom_bot_owned_by_same_workspace",+ }),+ );+ renderUI(<WecomAgentBindButton agentId="agent-1" agentName="Bot" />);+ await userEvent.click(screen.getByTestId("wecom-agent-connect"));+ await userEvent.type(await screen.findByTestId("wecom-byo-bot-id"), "aibot_xyz");+ await userEvent.type(screen.getByTestId("wecom-byo-secret"), "s3cr3t");+ await userEvent.click(screen.getByTestId("wecom-byo-submit"));+ await waitFor(() =>+ expect(toast.error).toHaveBeenCalledWith(enSettings.wecom.byo_conflict_same_workspace),+ );+ });++ // The 503 branch: we could not reach WeCom, so nothing was verified and+ // nothing was changed. The admin must not read this as "your secret is+ // wrong" — that sends them to rotate one that was fine, and a rotated WeCom+ // secret cannot be recovered. Separate code, separate sentence.+ it("tells the admin their credentials were not changed when WeCom was unreachable", async () => {+ mockRegisterBYO.mockRejectedValue(+ Object.assign(new Error("could not reach WeCom to verify this bot"), {+ code: "wecom_credentials_unverifiable",+ }),+ );+ renderUI(<WecomAgentBindButton agentId="agent-1" agentName="Bot" />);+ await userEvent.click(screen.getByTestId("wecom-agent-connect"));+ await userEvent.type(await screen.findByTestId("wecom-byo-bot-id"), "aibot_xyz");+ await userEvent.type(screen.getByTestId("wecom-byo-secret"), "s3cr3t");+ await userEvent.click(screen.getByTestId("wecom-byo-submit"));+ await waitFor(() =>+ expect(toast.error).toHaveBeenCalledWith(enSettings.wecom.byo_credentials_unverifiable),+ );+ });++ // WeCom refusing the pair is the one outcome entitled to blame the+ // credentials, and it must not reuse byo_rejected — that sentence means+ // "you left a field out".+ it("renders the credentials-rejected sentence, distinct from the missing-field one", async () => {+ mockRegisterBYO.mockRejectedValue(+ Object.assign(new Error("WeCom rejected this Bot ID and secret"), {+ code: "wecom_credentials_rejected",+ }),+ );+ renderUI(<WecomAgentBindButton agentId="agent-1" agentName="Bot" />);+ await userEvent.click(screen.getByTestId("wecom-agent-connect"));+ await userEvent.type(await screen.findByTestId("wecom-byo-bot-id"), "aibot_xyz");+ await userEvent.type(screen.getByTestId("wecom-byo-secret"), "s3cr3t");+ await userEvent.click(screen.getByTestId("wecom-byo-submit"));+ await waitFor(() =>+ expect(toast.error).toHaveBeenCalledWith(enSettings.wecom.byo_credentials_rejected),+ );+ expect(toast.error).not.toHaveBeenCalledWith(enSettings.wecom.byo_rejected);+ });++ // A server that sends no code must still say something useful, so the+ // fallback cannot regress into the generic toast.+ it("falls back to the server's message when no code is attached", async () => {+ mockRegisterBYO.mockRejectedValue(new Error("something the server said"));+ renderUI(<WecomAgentBindButton agentId="agent-1" agentName="Bot" />);+ await userEvent.click(screen.getByTestId("wecom-agent-connect"));+ await userEvent.type(await screen.findByTestId("wecom-byo-bot-id"), "aibot_xyz");+ await userEvent.type(screen.getByTestId("wecom-byo-secret"), "s3cr3t");+ await userEvent.click(screen.getByTestId("wecom-byo-submit"));+ await waitFor(() =>+ expect(toast.error).toHaveBeenCalledWith("something the server said"),+ );+ });+// The bot's chat name reaches the server, and only when it was typed.//// WeCom delivers a group @-mention as literal text with no structureddiff --git a/packages/views/settings/components/wecom-tab.tsx b/packages/views/settings/components/wecom-tab.tsxindex 508fb34b3b..c71df732b5 100644--- a/packages/views/settings/components/wecom-tab.tsx+++ b/packages/views/settings/components/wecom-tab.tsx@@ -31,6 +31,7 @@ import { useWorkspaceId } from "@multica/core/hooks";import { memberListOptions } from "@multica/core/workspace/queries";import { useActorName } from "@multica/core/workspace/hooks";import { wecomInstallationsOptions, wecomKeys } from "@multica/core/wecom";+import { errorCode } from "@multica/core/api";import { api } from "@multica/core/api";import type { WecomInstallation } from "@multica/core/types";import { ActorAvatar } from "../../common/actor-avatar";@@ -319,8 +320,40 @@ export function WecomAgentBindButton({setSecret("");setBotName("");} catch (e) {+ // The server sends a stable `code` alongside the English sentence, so+ // the admin reads the failure in their own language. The sentence is+ // still the fallback: an older server, or a failure that has not been+ // given a code, sends none.+ let localized: string | undefined;+ switch (errorCode(e)) {+ case "wecom_bot_owned_by_same_workspace":+ localized = t(($) => $.wecom.byo_conflict_same_workspace);+ break;+ case "wecom_bot_owned_by_archived_agent":+ localized = t(($) => $.wecom.byo_conflict_archived_agent);+ break;+ case "wecom_bot_owned_by_another_workspace":+ localized = t(($) => $.wecom.byo_conflict_other_workspace);+ break;+ case "wecom_install_rejected":+ localized = t(($) => $.wecom.byo_rejected);+ break;+ // Distinct from the two above on purpose: "you left a field out",+ // "WeCom said no" and "we couldn't ask WeCom" are three different+ // things for the admin to do, so they get three different sentences.+ case "wecom_credentials_rejected":+ localized = t(($) => $.wecom.byo_credentials_rejected);+ break;+ case "wecom_credentials_unverifiable":+ localized = t(($) => $.wecom.byo_credentials_unverifiable);+ break;+ case "wecom_install_failed":+ localized = t(($) => $.wecom.byo_install_failed);+ break;+ }toast.error(- e instanceof Error ? e.message : t(($) => $.wecom.byo_failed_toast),+ localized ??+ (e instanceof Error ? e.message : t(($) => $.wecom.byo_failed_toast)),);} finally {setSubmitting(false);diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 7686881521..df9643dc77 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -443,6 +443,14 @@ func writeError(w http.ResponseWriter, status int, msg string) {writeJSON(w, status, map[string]string{"error": msg})}+// writeErrorCode is writeError plus a stable machine-readable code, so a UI+// can translate the failure instead of toasting the English sentence at a+// user whose console is in another language. The sentence stays as the+// fallback for anything that has not been given a translation yet.+func writeErrorCode(w http.ResponseWriter, status int, code, msg string) {+ writeJSON(w, status, map[string]string{"error": msg, "code": code})+}+// Thin wrappers around util functions.//// parseUUID is intentionally the panicking variant: any handler call sitediff --git a/server/internal/handler/wecom_install_error_matrix_test.go b/server/internal/handler/wecom_install_error_matrix_test.gonew file mode 100644index 0000000000..0763cb806e--- /dev/null+++ b/server/internal/handler/wecom_install_error_matrix_test.go@@ -0,0 +1,199 @@+package handler++// wecom_install_error_matrix_test.go — the install response matrix is a+// contract with two clients at once: an HTTP status the API caller branches on,+// and a stable `code` the settings tab translates. Neither is visible to the+// tests one layer down. installation_params_test.go proves the sentinel+// matching inside the wecom package, and the frontend test mocks the code it+// expects to receive — so between them sits the wiring, where the sentinel is+// turned into a status and a code, and nothing was asserting that.+//+// That gap is exactly where a merge goes wrong: this switch has now taken new+// arms from two directions (the credential probe's rejected/unverifiable pair,+// and this branch's stable codes), and a resolution that drops an arm or gives+// two outcomes the same code still compiles and still passes every other test+// in the tree. The table below is the matrix itself, so a dropped arm fails+// here instead of reaching an admin as the wrong next action.++import (+ "encoding/json"+ "errors"+ "fmt"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/integrations/wecom"+)++// TestWecomInstallErrorMatrix pins status + error + code for every error class+// the install path can produce.+func TestWecomInstallErrorMatrix(t *testing.T) {+ wsUUID := pgtype.UUID{Bytes: [16]byte{1}, Valid: true}+ agentUUID := pgtype.UUID{Bytes: [16]byte{2}, Valid: true}++ cases := []struct {+ name string+ err error+ wantStatus int+ wantCode string+ // wantError is the exact sentence, not a smoke check that one exists.+ // It is what a client too old to know the codes shows the admin, so it+ // is as much a part of the contract as the status: an outcome that+ // keeps its status and code but picks up a neighbour's sentence still+ // sends those clients to do the wrong thing, and only pinning the text+ // catches that.+ wantError string+ // why records the admin action this outcome is telling them to take.+ // Two rows that share a code cannot be telling them different things.+ why string+ }{+ {+ name: "bot owned by another agent in this workspace",+ err: wecom.ErrBotOwnedBySameWorkspace,+ wantStatus: http.StatusConflict,+ wantCode: "wecom_bot_owned_by_same_workspace",+ wantError: "this bot is already connected to another agent in this workspace — disconnect it there first, then connect it here",+ why: "go disconnect it from the other agent here",+ },+ {+ name: "bot owned by an archived agent",+ err: wecom.ErrBotOwnedByArchivedAgent,+ wantStatus: http.StatusConflict,+ wantCode: "wecom_bot_owned_by_archived_agent",+ wantError: "this bot is connected to an archived agent in this workspace — restore that agent, or disconnect its bot, before connecting it here",+ why: "restore that agent or disconnect its bot",+ },+ {+ name: "bot owned by another workspace",+ err: wecom.ErrBotOwnedByAnotherWorkspace,+ wantStatus: http.StatusConflict,+ wantCode: "wecom_bot_owned_by_another_workspace",+ wantError: "this bot is already connected to a different Multica workspace — disconnect it there before connecting it here",+ why: "go disconnect it in the other workspace",+ },+ {+ name: "required field missing",+ err: fmt.Errorf("%w: bot_id is required", wecom.ErrInvalidInstallationParams),+ wantStatus: http.StatusBadRequest,+ wantCode: "wecom_install_rejected",+ wantError: "could not connect the WeCom bot — check the Bot ID and secret from the WeCom admin console, and that the bot is a smart bot with the long connection enabled",+ why: "fill in the field you left out",+ },+ {+ name: "WeCom refused the credentials",+ err: wecom.ErrCredentialsRejected,+ wantStatus: http.StatusBadRequest,+ wantCode: "wecom_credentials_rejected",+ wantError: "WeCom rejected this Bot ID and secret — check both on the WeCom admin console, and that the bot is a smart bot with the long connection enabled",+ why: "go check the pair on the WeCom console — the only outcome that may say this",+ },+ {+ name: "WeCom unreachable, credentials unverified",+ err: wecom.ErrCredentialsUnverifiable,+ wantStatus: http.StatusServiceUnavailable,+ wantCode: "wecom_credentials_unverifiable",+ wantError: "could not reach WeCom to verify this bot — the credentials were not changed; try again in a moment",+ why: "wait and retry; the credentials were not changed",+ },+ {+ name: "our database is down",+ err: errors.New("dial tcp 10.0.0.5:5432: connect: connection refused"),+ wantStatus: http.StatusInternalServerError,+ wantCode: "wecom_install_failed",+ wantError: "could not save this bot — something went wrong on our side. Your credentials were not changed; please try again, and contact support if it keeps failing",+ why: "nothing — it is ours to fix, and the admin must not be sent to rotate a secret",+ },+ {+ name: "the encryption key is missing",+ err: errors.New("wecom: encrypt secret: secretbox: no key"),+ wantStatus: http.StatusInternalServerError,+ wantCode: "wecom_install_failed",+ wantError: "could not save this bot — something went wrong on our side. Your credentials were not changed; please try again, and contact support if it keeps failing",+ why: "nothing — ours",+ },+ {+ name: "a wrapped sentinel is still classified by its cause",+ err: fmt.Errorf("upsert: %w", wecom.ErrCredentialsUnverifiable),+ wantStatus: http.StatusServiceUnavailable,+ wantCode: "wecom_credentials_unverifiable",+ wantError: "could not reach WeCom to verify this bot — the credentials were not changed; try again in a moment",+ why: "errors.Is, not string matching",+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ w := httptest.NewRecorder()+ writeWecomInstallError(w, tc.err, wsUUID, agentUUID)++ if w.Code != tc.wantStatus {+ t.Errorf("status = %d, want %d (%s)", w.Code, tc.wantStatus, tc.why)+ }++ var body struct {+ Error string `json:"error"`+ Code string `json:"code"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {+ t.Fatalf("response body is not JSON: %v (body: %s)", err, w.Body.String())+ }+ if body.Code != tc.wantCode {+ t.Errorf("code = %q, want %q (%s)", body.Code, tc.wantCode, tc.why)+ }+ // The sentence is what a client that does not know the code shows,+ // so it has to be this outcome's own sentence — an empty one leaves+ // those clients a bare status, and a neighbour's tells the admin to+ // take the wrong action.+ if body.Error != tc.wantError {+ t.Errorf("error = %q, want %q (%s)", body.Error, tc.wantError, tc.why)+ }+ })+ }+}++// TestWecomInstallCodesAreDistinct: the codes are the contract the frontend+// switches on, so two outcomes sharing one code means the tab cannot tell them+// apart and shows the wrong next action for one of them. In particular+// wecom_install_rejected means "you left a field out" and must not widen to+// cover "WeCom said no" or "we could not ask WeCom" — those are different+// actions, and #6594 made them separately detectable for that reason.+func TestWecomInstallCodesAreDistinct(t *testing.T) {+ wsUUID := pgtype.UUID{Bytes: [16]byte{1}, Valid: true}+ agentUUID := pgtype.UUID{Bytes: [16]byte{2}, Valid: true}++ errs := map[string]error{+ "same workspace": wecom.ErrBotOwnedBySameWorkspace,+ "archived agent": wecom.ErrBotOwnedByArchivedAgent,+ "other workspace": wecom.ErrBotOwnedByAnotherWorkspace,+ "invalid params": wecom.ErrInvalidInstallationParams,+ "creds rejected": wecom.ErrCredentialsRejected,+ "creds unverified": wecom.ErrCredentialsUnverifiable,+ "ours": errors.New("something we broke"),+ }++ seen := make(map[string]string, len(errs))+ for name, err := range errs {+ w := httptest.NewRecorder()+ writeWecomInstallError(w, err, wsUUID, agentUUID)++ var body struct {+ Code string `json:"code"`+ }+ if uerr := json.Unmarshal(w.Body.Bytes(), &body); uerr != nil {+ t.Fatalf("%s: response body is not JSON: %v", name, uerr)+ }+ if body.Code == "" {+ t.Errorf("%s: no code — the settings tab falls back to the English sentence", name)+ continue+ }+ if prev, dup := seen[body.Code]; dup {+ t.Errorf("%q is returned for both %q and %q; the frontend cannot tell them apart, so one of the two gets the wrong next action",+ body.Code, prev, name)+ continue+ }+ seen[body.Code] = name+ }+}diff --git a/server/internal/handler/wecom_web.go b/server/internal/handler/wecom_web.goindex 45b3b44659..136c18d053 100644--- a/server/internal/handler/wecom_web.go+++ b/server/internal/handler/wecom_web.go@@ -177,40 +177,7 @@ func (h *Handler) RegisterWecomBYO(w http.ResponseWriter, r *http.Request) {BotDisplayName: strings.TrimSpace(body.BotName),})if err != nil {- // One bot is one live long connection, so the (wecom, bot_id) slot has- // exactly one owner. Upsert conflicts on- // (workspace_id, agent_id, channel_type), which means connecting an- // already-connected bot to a SECOND agent misses ON CONFLICT and trips- // idx_channel_installation_type_appid instead. Each sentinel gets the- // sentence that tells the admin where the bot actually is; returning- // err.Error() here used to toast them the raw "duplicate key value- // violates unique constraint" text — and forwarded every other database- // error verbatim to the API caller besides.- switch {- case errors.Is(err, wecom.ErrBotOwnedBySameWorkspace):- writeError(w, http.StatusConflict, "this bot is already connected to another agent in this workspace — disconnect it there first, then connect it here")- case errors.Is(err, wecom.ErrBotOwnedByArchivedAgent):- writeError(w, http.StatusConflict, "this bot is connected to an archived agent in this workspace — restore that agent, or disconnect its bot, before connecting it here")- case errors.Is(err, wecom.ErrBotOwnedByAnotherWorkspace):- writeError(w, http.StatusConflict, "this bot is already connected to a different Multica workspace — disconnect it there before connecting it here")- case errors.Is(err, wecom.ErrCredentialsRejected):- // WeCom itself refused the pair. This is the one branch entitled- // to blame the credentials, and the only one the admin can act on- // by going back to the console.- writeError(w, http.StatusBadRequest, "WeCom rejected this Bot ID and secret — check both on the WeCom admin console, and that the bot is a smart bot with the long connection enabled")- case errors.Is(err, wecom.ErrCredentialsUnverifiable):- // The deployment could not reach WeCom. Reporting this as a bad- // credential sends the admin to rotate a secret that was fine —- // and a rotated WeCom secret cannot be recovered. 503: nothing is- // wrong with the input, the check could not be made.- slog.Warn("wecom install could not verify the bot",- "error", err, "workspace_id", uuidToString(wsUUID), "agent_id", uuidToString(agentUUID))- writeError(w, http.StatusServiceUnavailable, "could not reach WeCom to verify this bot — the credentials were not changed; try again in a moment")- default:- slog.Warn("wecom install failed",- "error", err, "workspace_id", uuidToString(wsUUID), "agent_id", uuidToString(agentUUID))- writeError(w, http.StatusBadRequest, "could not connect the WeCom bot — check the Bot ID and secret from the WeCom admin console, and that the bot is a smart bot with the long connection enabled")- }+ writeWecomInstallError(w, err, wsUUID, agentUUID)return}h.publish(protocol.EventWecomInstallationCreated, uuidToString(inst.WorkspaceID), "user", userID, map[string]any{@@ -219,6 +186,79 @@ func (h *Handler) RegisterWecomBYO(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, wecomInstallationToResponse(inst))}+// writeWecomInstallError is the whole response matrix for a failed install, in+// one place so it can be read and tested as a matrix rather than inferred from+// a switch buried in the handler.+//+// The distinction it draws is who has to do something about the failure:+//+// bot already owned (same ws / archived agent / other ws) → 409, go disconnect it there+// required field missing → 400, the admin's input+// WeCom refused the pair → 400, the ONE branch that may blame the credentials+// WeCom unreachable, so unverified → 503, say the credentials were not changed+// anything else (DB, encryption key, a bug) → 500, log it, do not blame the admin+//+// One bot is one live long connection, so the (wecom, bot_id) slot has exactly+// one owner. Upsert conflicts on (workspace_id, agent_id, channel_type), which+// means connecting an already-connected bot to a SECOND agent misses ON+// CONFLICT and trips idx_channel_installation_type_appid instead. Each sentinel+// gets the sentence that tells the admin where the bot actually is; returning+// err.Error() here used to toast them the raw "duplicate key value violates+// unique constraint" text — and forwarded every other database error verbatim+// to the API caller besides.+//+// Every case carries a stable code as well as the sentence, so the settings tab+// can say this in the admin's own language instead of toasting English at them.+// The sentence stays as the fallback for a client that does not know the code.+// The codes are a published contract: each one means one outcome and keeps+// meaning it, because the admin action differs per outcome.+func writeWecomInstallError(w http.ResponseWriter, err error, wsUUID, agentUUID pgtype.UUID) {+ switch {+ case errors.Is(err, wecom.ErrBotOwnedBySameWorkspace):+ writeErrorCode(w, http.StatusConflict, "wecom_bot_owned_by_same_workspace",+ "this bot is already connected to another agent in this workspace — disconnect it there first, then connect it here")+ case errors.Is(err, wecom.ErrBotOwnedByArchivedAgent):+ writeErrorCode(w, http.StatusConflict, "wecom_bot_owned_by_archived_agent",+ "this bot is connected to an archived agent in this workspace — restore that agent, or disconnect its bot, before connecting it here")+ case errors.Is(err, wecom.ErrBotOwnedByAnotherWorkspace):+ writeErrorCode(w, http.StatusConflict, "wecom_bot_owned_by_another_workspace",+ "this bot is already connected to a different Multica workspace — disconnect it there before connecting it here")+ case errors.Is(err, wecom.ErrInvalidInstallationParams):+ // Something the admin left out. Their input, their fix. This code means+ // exactly that and nothing else — the two credential outcomes below get+ // their own, because "you left a field out", "WeCom said no" and "we+ // could not ask WeCom" are three different next actions for the admin,+ // and a client keying off one code cannot tell them apart.+ writeErrorCode(w, http.StatusBadRequest, "wecom_install_rejected",+ "could not connect the WeCom bot — check the Bot ID and secret from the WeCom admin console, and that the bot is a smart bot with the long connection enabled")+ case errors.Is(err, wecom.ErrCredentialsRejected):+ // WeCom itself refused the pair. This is the one branch entitled to+ // blame the credentials, and the only one the admin can act on by going+ // back to the console.+ writeErrorCode(w, http.StatusBadRequest, "wecom_credentials_rejected",+ "WeCom rejected this Bot ID and secret — check both on the WeCom admin console, and that the bot is a smart bot with the long connection enabled")+ case errors.Is(err, wecom.ErrCredentialsUnverifiable):+ // The deployment could not reach WeCom. Reporting this as a bad+ // credential sends the admin to rotate a secret that was fine — and a+ // rotated WeCom secret cannot be recovered. 503: nothing is wrong with+ // the input, the check could not be made.+ slog.Warn("wecom install could not verify the bot",+ "error", err, "workspace_id", uuidToString(wsUUID), "agent_id", uuidToString(agentUUID))+ writeErrorCode(w, http.StatusServiceUnavailable, "wecom_credentials_unverifiable",+ "could not reach WeCom to verify this bot — the credentials were not changed; try again in a moment")+ default:+ // Ours: the database, the encryption key, a bug. This branch used to+ // answer 400 and blame the credentials, which sent the admin to the+ // WeCom console to rotate a secret that was fine — and a rotated WeCom+ // secret cannot be recovered, so a thirty-second Postgres failover cost+ // them a working bot. Whatever went wrong here, it was not their Bot ID.+ slog.Error("wecom install failed",+ "error", err, "workspace_id", uuidToString(wsUUID), "agent_id", uuidToString(agentUUID))+ writeErrorCode(w, http.StatusInternalServerError, "wecom_install_failed",+ "could not save this bot — something went wrong on our side. Your credentials were not changed; please try again, and contact support if it keeps failing")+ }+}+// RevokeWecomInstallation (DELETE /api/workspaces/{id}/wecom/installations/{installationId})// flips status to 'revoked'. Admin-only at the router. Row-preserving so a// re-install through Upsert flips it back to 'active' atomically.diff --git a/server/internal/integrations/wecom/installation.go b/server/internal/integrations/wecom/installation.goindex f93fa6c684..fff96a0fb7 100644--- a/server/internal/integrations/wecom/installation.go+++ b/server/internal/integrations/wecom/installation.go@@ -450,23 +450,33 @@ func (s *InstallationService) GetInWorkspace(ctx context.Context, id, workspaceIreturn installationFromRow(row)}+// ErrInvalidInstallationParams marks a request the caller can fix by filling+// something in, as opposed to a failure of ours. It exists so the HTTP layer+// can tell them apart: a missing field is the caller's 400, ErrCredentialsRejected+// and ErrCredentialsUnverifiable carry the two outcomes of actually asking WeCom+// (400 and 503), and everything left over is a 500 — because telling an admin+// their credentials are wrong when Postgres briefly went away sends them to+// rotate a secret that was fine, and a WeCom secret, once rotated, cannot be+// recovered. writeWecomInstallError holds the full matrix.+var ErrInvalidInstallationParams = errors.New("wecom: invalid installation parameters")+// validateInstallationParams is a lightweight pre-write check for// required fields. It does NOT verify anything against WeCom.func validateInstallationParams(p InstallationParams) error {- if !p.WorkspaceID.Valid {- return errors.New("wecom: workspace_id is required")- }- if !p.AgentID.Valid {- return errors.New("wecom: agent_id is required")- }- if !p.InstallerUserID.Valid {- return errors.New("wecom: installer_user_id is required")- }- if p.BotID == "" {- return errors.New("wecom: bot_id is required")- }- if p.Secret == "" {- return errors.New("wecom: secret is required")+ missing := ""+ switch {+ case !p.WorkspaceID.Valid:+ missing = "workspace_id"+ case !p.AgentID.Valid:+ missing = "agent_id"+ case !p.InstallerUserID.Valid:+ missing = "installer_user_id"+ case p.BotID == "":+ missing = "bot_id"+ case p.Secret == "":+ missing = "secret"+ default:+ return nil}- return nil+ return fmt.Errorf("%w: %s is required", ErrInvalidInstallationParams, missing)}diff --git a/server/internal/integrations/wecom/installation_params_test.go b/server/internal/integrations/wecom/installation_params_test.gonew file mode 100644index 0000000000..bbba3b1e27--- /dev/null+++ b/server/internal/integrations/wecom/installation_params_test.go@@ -0,0 +1,65 @@+package wecom++// installation_params_test.go — the HTTP layer decides between "the admin+// left a field out" (their fix) and "something broke on our side" (not their+// fix) by matching on ErrInvalidInstallationParams. If a validation failure+// stops matching, that request silently becomes a 500; if a real failure+// starts matching, the admin gets sent to rotate a secret that was fine.++import (+ "errors"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+)++func validParams() InstallationParams {+ id := pgtype.UUID{Bytes: [16]byte{1}, Valid: true}+ return InstallationParams{+ WorkspaceID: id,+ AgentID: id,+ InstallerUserID: id,+ BotID: "bot-1",+ Secret: "s3cret",+ }+}++func TestEveryMissingFieldIsTheCallersToFix(t *testing.T) {+ cases := map[string]func(*InstallationParams){+ "workspace_id": func(p *InstallationParams) { p.WorkspaceID = pgtype.UUID{} },+ "agent_id": func(p *InstallationParams) { p.AgentID = pgtype.UUID{} },+ "installer_user_id": func(p *InstallationParams) { p.InstallerUserID = pgtype.UUID{} },+ "bot_id": func(p *InstallationParams) { p.BotID = "" },+ "secret": func(p *InstallationParams) { p.Secret = "" },+ }+ for field, blank := range cases {+ p := validParams()+ blank(&p)+ err := validateInstallationParams(p)+ if err == nil {+ t.Errorf("%s: missing field accepted", field)+ continue+ }+ if !errors.Is(err, ErrInvalidInstallationParams) {+ t.Errorf("%s: error does not match ErrInvalidInstallationParams, so the handler will answer 500 instead of 400: %v", field, err)+ }+ if !strings.Contains(err.Error(), field) {+ t.Errorf("%s: error does not name the field: %v", field, err)+ }+ }+}++func TestCompleteParamsPass(t *testing.T) {+ if err := validateInstallationParams(validParams()); err != nil {+ t.Fatalf("complete params rejected: %v", err)+ }+}++// A failure that is NOT a validation failure must not match the sentinel —+// otherwise a database outage is reported to the admin as bad credentials.+func TestAnUnrelatedFailureIsNotTheCallersToFix(t *testing.T) {+ if errors.Is(errors.New("dial tcp: connection refused"), ErrInvalidInstallationParams) {+ t.Fatal("an infrastructure error matched the caller-error sentinel")+ }+}