Skip to content

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

Go

MUL-7437: fix(api): classify disabled capabilities as non-retryable (#8487)

Multica Evef0c9146c4b4e
diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.ts
index a70a2b4736..68abbf9e73 100644
--- a/packages/core/api/schema.test.ts
+++ b/packages/core/api/schema.test.ts
@@ -1134,7 +1134,7 @@ describe("parseWithFallback", () => {
// Workspace subscription reads carry a specific hazard the wallet schemas do
// not: the fallback for a paid workspace must never be a shape that reads as
-// Free. An older cloud, a 503, or a renamed field has to surface as "unknown"
+// Free. An older/disabled cloud, an upstream 503, or a renamed field has to surface as "unknown"
// so the UI shows "unavailable" instead of quietly downgrading a paying team.
describe("workspace subscription contract", () => {
const entitlement = {
@@ -1289,7 +1289,7 @@ describe("workspace subscription contract", () => {
// parsing: fetch rejects first and a React Query caller sees isError. What
// matters for both paths is the same — no snapshot is produced, so nothing
// can be mistaken for a Free workspace.
- for (const status of [404, 503]) {
+ for (const status of [403, 404, 503]) {
stubFetchJson({ error: "unavailable" }, status);
const client = new ApiClient("https://api.example.test");
await expect(client.getWorkspaceSubscriptionSummary()).rejects.toThrow();
diff --git a/packages/views/agents/components/tabs/integrations-tab.tsx b/packages/views/agents/components/tabs/integrations-tab.tsx
index fd368f3aaa..9db4340ac5 100644
--- a/packages/views/agents/components/tabs/integrations-tab.tsx
+++ b/packages/views/agents/components/tabs/integrations-tab.tsx
@@ -289,8 +289,8 @@ export function IntegrationsTab({ agent }: { agent: Agent }) {
</p>
) : !slackInstallSupported && !slackHasActiveInstall ? (
// Secret key is set but the OAuth client credentials aren't, so a
- // fresh "Connect Slack" would 503. Surface the "coming soon" notice
- // instead of a broken CTA; an already-bound agent still renders.
+ // fresh "Connect Slack" would be rejected. Surface the "coming soon"
+ // notice instead of a broken CTA; an already-bound agent still renders.
<div className="space-y-1">
<p className="text-caption font-medium">{ts(($) => $.slack.preview_title)}</p>
<p className="text-caption text-muted-foreground">
diff --git a/packages/views/locales/en/billing.json b/packages/views/locales/en/billing.json
index cf2edb93d4..32ce53a6bf 100644
--- a/packages/views/locales/en/billing.json
+++ b/packages/views/locales/en/billing.json
@@ -103,6 +103,7 @@
"errors": {
"action_title": "Billing action failed",
"temporarily_unavailable": "Billing is temporarily unavailable. Retry in a moment.",
+ "not_enabled": "Workspace subscriptions are not enabled for this deployment. Contact your administrator.",
"permission_changed": "Your workspace role no longer allows this action. Refresh the page to see your current access.",
"checkout_response": "Checkout could not open because the server response was unreadable. Retry without changing your selected interval.",
"already_subscribed": "This workspace already has a subscription. The current plan has been refreshed.",
diff --git a/packages/views/locales/fr/billing.json b/packages/views/locales/fr/billing.json
index b54a0b3926..2e35855e9d 100644
--- a/packages/views/locales/fr/billing.json
+++ b/packages/views/locales/fr/billing.json
@@ -103,6 +103,7 @@
"errors": {
"action_title": "Échec de l'action de facturation",
"temporarily_unavailable": "La facturation est temporairement indisponible. Réessayez dans un instant.",
+ "not_enabled": "Les abonnements d’espace de travail ne sont pas activés pour ce déploiement. Contactez votre administrateur.",
"permission_changed": "Votre rôle dans l'espace de travail n'autorise plus cette action. Actualisez la page pour voir vos droits actuels.",
"checkout_response": "Le paiement n'a pas pu s'ouvrir car la réponse du serveur était illisible. Réessayez sans changer l'intervalle sélectionné.",
"already_subscribed": "Cet espace de travail a déjà un abonnement. Le forfait actuel a été actualisé.",
diff --git a/packages/views/locales/ja/billing.json b/packages/views/locales/ja/billing.json
index 07eadbeb9e..dae35de86f 100644
--- a/packages/views/locales/ja/billing.json
+++ b/packages/views/locales/ja/billing.json
@@ -103,6 +103,7 @@
"errors": {
"action_title": "請求操作に失敗しました",
"temporarily_unavailable": "請求サービスは一時的に利用できません。しばらくしてから再試行してください。",
+ "not_enabled": "この環境ではワークスペースのサブスクリプションが有効になっていません。管理者にお問い合わせください。",
"permission_changed": "現在のワークスペース権限ではこの操作を実行できません。ページを更新して権限を確認してください。",
"checkout_response": "サーバー応答を読み取れないため Checkout を開けませんでした。選択した期間を変えずに再試行してください。",
"already_subscribed": "このワークスペースにはすでにサブスクリプションがあります。現在のプランを更新しました。",
diff --git a/packages/views/locales/ko/billing.json b/packages/views/locales/ko/billing.json
index d6e0f07c4d..bef7f6743c 100644
--- a/packages/views/locales/ko/billing.json
+++ b/packages/views/locales/ko/billing.json
@@ -103,6 +103,7 @@
"errors": {
"action_title": "결제 작업 실패",
"temporarily_unavailable": "결제 서비스를 일시적으로 사용할 수 없습니다. 잠시 후 다시 시도하세요.",
+ "not_enabled": "이 배포에서는 워크스페이스 구독을 사용할 수 없습니다. 관리자에게 문의하세요.",
"permission_changed": "현재 워크스페이스 역할로는 이 작업을 수행할 수 없습니다. 페이지를 새로고침해 현재 권한을 확인하세요.",
"checkout_response": "서버 응답을 읽을 수 없어 Checkout을 열지 못했습니다. 선택한 결제 주기를 유지하고 다시 시도하세요.",
"already_subscribed": "이 워크스페이스에는 이미 구독이 있습니다. 현재 요금제를 새로고침했습니다.",
diff --git a/packages/views/locales/zh-Hans/billing.json b/packages/views/locales/zh-Hans/billing.json
index 6a0894ba93..c0b45ea99c 100644
--- a/packages/views/locales/zh-Hans/billing.json
+++ b/packages/views/locales/zh-Hans/billing.json
@@ -103,6 +103,7 @@
"errors": {
"action_title": "账单操作失败",
"temporarily_unavailable": "账单服务暂时不可用,请稍后重试。",
+ "not_enabled": "此部署未启用工作区订阅,请联系管理员。",
"permission_changed": "你的工作区角色已不允许执行此操作。刷新页面可查看当前权限。",
"checkout_response": "服务端响应无法读取,无法打开 Checkout。请保留当前周期并重试。",
"already_subscribed": "这个工作区已经有订阅,当前套餐已刷新。",
diff --git a/packages/views/settings/components/billing-tab.test.tsx b/packages/views/settings/components/billing-tab.test.tsx
index dc6c6e2d6d..ca86ed859b 100644
--- a/packages/views/settings/components/billing-tab.test.tsx
+++ b/packages/views/settings/components/billing-tab.test.tsx
@@ -604,6 +604,25 @@ describe("BillingTab", () => {
expect(await screen.findByText(copy)).toBeInTheDocument();
});
+ it("explains that a disabled billing capability requires an administrator", async () => {
+ const user = userEvent.setup();
+ mocks.checkout.mockRejectedValue(
+ new ApiError("request failed", 403, "Forbidden", {
+ code: "workspace_subscriptions_disabled",
+ }),
+ );
+ renderWithI18n(<BillingTab />);
+
+ await user.click(screen.getByRole("button", { name: "Upgrade to Pro" }));
+ await user.click(screen.getByRole("button", { name: "Continue to Stripe" }));
+
+ expect(
+ await screen.findByText(
+ "Workspace subscriptions are not enabled for this deployment. Contact your administrator.",
+ ),
+ ).toBeInTheDocument();
+ });
+
it("consumes cancel callback params once while preserving the active tab", () => {
navigationState.search =
"tab=billing&result=cancel&session_id=cs_test_1&source=email";
diff --git a/packages/views/settings/components/billing-tab.tsx b/packages/views/settings/components/billing-tab.tsx
index 3e81a5f7d8..2cde529ae7 100644
--- a/packages/views/settings/components/billing-tab.tsx
+++ b/packages/views/settings/components/billing-tab.tsx
@@ -541,6 +541,14 @@ function BillingTabContent() {
};
const reportActionError = (error: unknown, fallback: string) => {
+ const code = errorCode(error);
+ if (
+ code === "workspace_subscriptions_disabled" ||
+ code === "cloud_runtime_not_configured"
+ ) {
+ setActionError(t(($) => $.workspace.errors.not_enabled));
+ return;
+ }
if (error instanceof ApiError && error.status === 503) {
setActionError(t(($) => $.workspace.errors.temporarily_unavailable));
return;
diff --git a/packages/views/settings/components/composio-tab.tsx b/packages/views/settings/components/composio-tab.tsx
index 7e9c682e3d..55f930b266 100644
--- a/packages/views/settings/components/composio-tab.tsx
+++ b/packages/views/settings/components/composio-tab.tsx
@@ -141,10 +141,10 @@ export function ComposioTab() {
);
}, [toolkits, query]);
- // 503 handling lives in the parent IntegrationsTab, which hides the whole
- // Composio section when COMPOSIO_API_KEY is unset — this component only
- // mounts when the integration is configured, so it deals with the loaded /
- // error / empty / list states below.
+ // Deployment-disabled handling lives in the parent IntegrationsTab, which
+ // hides the whole Composio section when COMPOSIO_API_KEY is unset — this
+ // component only mounts when the integration is configured, so it deals with
+ // the loaded / error / empty / list states below.
async function handleConnect(tk: ComposioToolkit) {
if (connectingSlug) return;
diff --git a/packages/views/settings/components/integrations-tab.test.tsx b/packages/views/settings/components/integrations-tab.test.tsx
index 3d4ba0d624..cef16dac6b 100644
--- a/packages/views/settings/components/integrations-tab.test.tsx
+++ b/packages/views/settings/components/integrations-tab.test.tsx
@@ -128,6 +128,15 @@ describe("Integration directory", () => {
).toBe(true);
});
it("hides Composio when the server reports it unconfigured", () => {
+ state.error = new ApiError("unavailable", 403, "Forbidden", {
+ code: "composio_not_configured",
+ });
+ renderWithI18n(<IntegrationsTab />);
+ expect(
+ screen.queryByRole("link", { name: /Composio/ }),
+ ).not.toBeInTheDocument();
+ });
+ it("keeps hiding Composio when an older server reports 503", () => {
state.error = new ApiError("unavailable", 503, "Service Unavailable");
renderWithI18n(<IntegrationsTab />);
expect(
diff --git a/packages/views/settings/components/integrations-tab.tsx b/packages/views/settings/components/integrations-tab.tsx
index 01889f16db..a2e2230b31 100644
--- a/packages/views/settings/components/integrations-tab.tsx
+++ b/packages/views/settings/components/integrations-tab.tsx
@@ -3,7 +3,7 @@
import type { ReactNode } from "react";
import { ArrowLeft, ChevronRight, FolderGit2, Blocks } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
-import { ApiError } from "@multica/core/api";
+import { ApiError, errorCode } from "@multica/core/api";
import { useWorkspaceId } from "@multica/core/hooks";
import { useCurrentMember } from "@multica/core/permissions";
import {
@@ -64,6 +64,7 @@ export function IntegrationsTab() {
});
const composioAvailable =
composioEnabled &&
+ errorCode(toolkits.error) !== "composio_not_configured" &&
!(toolkits.error instanceof ApiError && toolkits.error.status === 503);
// Reuse the detail pages' query caches. Never report a failed or pending read
diff --git a/packages/views/settings/components/lark-tab.tsx b/packages/views/settings/components/lark-tab.tsx
index 2c636e8bc4..c0f873cbb6 100644
--- a/packages/views/settings/components/lark-tab.tsx
+++ b/packages/views/settings/components/lark-tab.tsx
@@ -125,7 +125,7 @@ export function LarkTab() {
// Device-flow install path is not wired (HTTP client is the stub
// or RegistrationService didn't initialize). We deliberately do
// NOT direct users to the agent-detail "Bind" button because the
- // backend would 503 anyway. Existing installations still render
+ // backend would reject it anyway. Existing installations still render
// via the branch below; this only hides the empty-state CTA
// when there is nothing to manage.
<Card>
diff --git a/packages/views/settings/components/slack-tab.tsx b/packages/views/settings/components/slack-tab.tsx
index b0eab08d5e..1f362ae618 100644
--- a/packages/views/settings/components/slack-tab.tsx
+++ b/packages/views/settings/components/slack-tab.tsx
@@ -64,9 +64,9 @@ export function SlackTab() {
const installations = data?.installations ?? [];
const configured = data?.configured === true;
// install_supported tracks whether the OAuth client credentials are wired on
- // the server. When false, "Connect Slack" would 503, so we hide the connect
- // entry points and surface a "coming soon" notice. Already-installed bots
- // still appear below and remain manageable.
+ // the server. When false, "Connect Slack" would be rejected, so we hide the
+ // connect entry points and surface a "coming soon" notice. Already-installed
+ // bots still appear below and remain manageable.
const installSupported = data?.install_supported === true;
const [disconnectTarget, setDisconnectTarget] = useState<string | null>(null);
diff --git a/server/cmd/server/composio_callback_public_test.go b/server/cmd/server/composio_callback_public_test.go
index 08b2d45065..acfdf8c3ff 100644
--- a/server/cmd/server/composio_callback_public_test.go
+++ b/server/cmd/server/composio_callback_public_test.go
@@ -15,7 +15,7 @@ import (
// settings redirect — the exact symptom Yushen hit.
//
// With no COMPOSIO_API_KEY configured in the test env, h.Composio == nil, so a
-// cookie-less hit on the callback now reaches the handler and returns 503
+// cookie-less hit on the callback now reaches the handler and returns 403
// ("not configured") rather than being short-circuited to 401 by the Auth
// middleware. The precise non-401 code is incidental; what this test pins is
// that the request is NOT rejected by auth.
diff --git a/server/cmd/server/integration_test.go b/server/cmd/server/integration_test.go
index c0e039951e..a4bb9f6b89 100644
--- a/server/cmd/server/integration_test.go
+++ b/server/cmd/server/integration_test.go
@@ -884,8 +884,8 @@ UPDATE agent SET owner_id = $2 WHERE id = $1
t.Fatalf("member DingTalk install request failed: %v", err)
}
resp.Body.Close()
- if resp.StatusCode != http.StatusBadRequest && resp.StatusCode != http.StatusServiceUnavailable {
- t.Fatalf("agent-owner DingTalk install status = %d, want 400 or 503", resp.StatusCode)
+ if resp.StatusCode != http.StatusBadRequest && resp.StatusCode != http.StatusForbidden {
+ t.Fatalf("agent-owner DingTalk install status = %d, want 400 or 403", resp.StatusCode)
}
if _, err := testPool.Exec(context.Background(), `
UPDATE agent SET owner_id = $2 WHERE id = $1
diff --git a/server/internal/handler/attachment_capability.go b/server/internal/handler/attachment_capability.go
index c6f86b74fb..6ad7ba46b0 100644
--- a/server/internal/handler/attachment_capability.go
+++ b/server/internal/handler/attachment_capability.go
@@ -223,7 +223,7 @@ func (h *Handler) DownloadAttachmentWithCapability(w http.ResponseWriter, r *htt
return
}
if h.Storage == nil {
- writeError(w, http.StatusServiceUnavailable, "storage not configured")
+ writeFeatureDisabled(w, "storage_not_configured", "storage not configured")
return
}
diff --git a/server/internal/handler/auth.go b/server/internal/handler/auth.go
index b4ff4d9fa3..dd03d46281 100644
--- a/server/internal/handler/auth.go
+++ b/server/internal/handler/auth.go
@@ -548,7 +548,7 @@ func (h *Handler) GoogleLogin(w http.ResponseWriter, r *http.Request) {
clientID := os.Getenv("GOOGLE_CLIENT_ID")
clientSecret := os.Getenv("GOOGLE_CLIENT_SECRET")
if clientID == "" || clientSecret == "" {
- writeError(w, http.StatusServiceUnavailable, "Google login is not configured")
+ writeFeatureDisabled(w, "google_login_not_configured", "Google login is not configured")
return
}
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index b80b5b497e..fe447b17e5 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -1157,7 +1157,7 @@ func (h *Handler) RegenerateChatQuickActions(w http.ResponseWriter, r *http.Requ
case errors.Is(err, service.ErrChatQuickActionsNoTurn):
writeError(w, http.StatusConflict, "no assistant reply to refresh yet")
case errors.Is(err, service.ErrChatQuickActionsUnavailable):
- writeError(w, http.StatusServiceUnavailable, "suggestions are not available on this deployment")
+ writeFeatureDisabled(w, "suggestions_not_available", "suggestions are not available on this deployment")
default:
writeError(w, http.StatusInternalServerError, "failed to regenerate quick actions")
}
diff --git a/server/internal/handler/cloud_billing.go b/server/internal/handler/cloud_billing.go
index da1f3208d7..07ded6b82a 100644
--- a/server/internal/handler/cloud_billing.go
+++ b/server/internal/handler/cloud_billing.go
@@ -87,7 +87,7 @@ func (h *Handler) requireCloudSubscriptionWorkspace(w http.ResponseWriter, r *ht
return "", "", false
}
if !featureflags.BillingWorkspaceSubscriptionsEnabled(r.Context(), h.FeatureFlags) {
- writeError(w, http.StatusServiceUnavailable, "workspace subscriptions are not enabled")
+ writeFeatureDisabled(w, "workspace_subscriptions_disabled", "workspace subscriptions are not enabled")
return "", "", false
}
@@ -115,7 +115,7 @@ func (h *Handler) requireCloudSubscriptionWorkspace(w http.ResponseWriter, r *ht
func (h *Handler) proxyCloudSubscription(w http.ResponseWriter, r *http.Request, method, path, userID string, body []byte, headers http.Header) {
if h.CloudRuntime == nil || !h.CloudRuntime.Enabled() {
- writeError(w, http.StatusServiceUnavailable, "cloud runtime is not configured")
+ writeFeatureDisabled(w, "cloud_runtime_not_configured", "cloud runtime is not configured")
return
}
resp, err := h.CloudRuntime.Do(r.Context(), cloudruntime.Request{
@@ -519,7 +519,7 @@ func (h *Handler) CreateCloudBillingPortalSession(w http.ResponseWriter, r *http
// own delivery dashboard view.
func (h *Handler) HandleCloudBillingStripeWebhook(w http.ResponseWriter, r *http.Request) {
if h.CloudRuntime == nil || !h.CloudRuntime.Enabled() {
- writeError(w, http.StatusServiceUnavailable, "cloud runtime is not configured")
+ writeFeatureDisabled(w, "cloud_runtime_not_configured", "cloud runtime is not configured")
return
}
diff --git a/server/internal/handler/cloud_billing_test.go b/server/internal/handler/cloud_billing_test.go
index 5c6d065416..98490e3236 100644
--- a/server/internal/handler/cloud_billing_test.go
+++ b/server/internal/handler/cloud_billing_test.go
@@ -233,17 +233,17 @@ func TestGetCloudBillingCheckoutSession_MissingPathParamReturns400(t *testing.T)
}
}
-// TestCloudBillingDisabledReturnsUnavailable confirms self-hosted
-// deployments (no cloud URL configured) get a clean 503 rather than
+// TestCloudBillingDisabledReturnsForbidden confirms self-hosted
+// deployments (no cloud URL configured) get a non-retryable 403 rather than
// a cryptic upstream error.
-func TestCloudBillingDisabledReturnsUnavailable(t *testing.T) {
+func TestCloudBillingDisabledReturnsForbidden(t *testing.T) {
useCloudRuntimeProxy(t, &fakeCloudRuntimeProxy{enabled: false})
req := newRequest(http.MethodGet, "/api/cloud-billing/balance", nil)
w := httptest.NewRecorder()
testHandler.GetCloudBillingBalance(w, req)
- if w.Code != http.StatusServiceUnavailable {
+ if w.Code != http.StatusForbidden {
t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
}
}
@@ -269,7 +269,7 @@ func TestCloudWorkspaceSubscriptionsDisabledByDefault(t *testing.T) {
w := httptest.NewRecorder()
invoke(w, req)
- if w.Code != http.StatusServiceUnavailable {
+ if w.Code != http.StatusForbidden {
t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
}
if proxy.called {
@@ -851,10 +851,10 @@ func TestStripeWebhookRejectsLargeBody(t *testing.T) {
}
}
-// TestStripeWebhookDisabledReturnsUnavailable mirrors the
+// TestStripeWebhookDisabledReturnsForbidden mirrors the
// cloud-runtime disabled test but for the webhook path. Self-hosted
-// deployments without a cloud URL must return 503, not crash.
-func TestStripeWebhookDisabledReturnsUnavailable(t *testing.T) {
+// deployments without a cloud URL must return a non-retryable 403, not crash.
+func TestStripeWebhookDisabledReturnsForbidden(t *testing.T) {
useCloudRuntimeProxy(t, &fakeCloudRuntimeProxy{enabled: false})
req := httptest.NewRequest(http.MethodPost, "/api/webhooks/stripe",
@@ -863,7 +863,7 @@ func TestStripeWebhookDisabledReturnsUnavailable(t *testing.T) {
w := httptest.NewRecorder()
testHandler.HandleCloudBillingStripeWebhook(w, req)
- if w.Code != http.StatusServiceUnavailable {
+ if w.Code != http.StatusForbidden {
t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
}
}
diff --git a/server/internal/handler/cloud_runtime.go b/server/internal/handler/cloud_runtime.go
index 2b39a04d1d..e9c3e4e2bd 100644
--- a/server/internal/handler/cloud_runtime.go
+++ b/server/internal/handler/cloud_runtime.go
@@ -102,7 +102,7 @@ func (h *Handler) ExecCloudRuntimeNode(w http.ResponseWriter, r *http.Request) {
func (h *Handler) proxyCloudRuntime(w http.ResponseWriter, r *http.Request, method, path string, opts cloudRuntimeProxyOptions) {
if h.CloudRuntime == nil || !h.CloudRuntime.Enabled() {
- writeError(w, http.StatusServiceUnavailable, "cloud runtime is not configured")
+ writeFeatureDisabled(w, "cloud_runtime_not_configured", "cloud runtime is not configured")
return
}
@@ -196,9 +196,9 @@ func writeCloudRuntimeResponse(w http.ResponseWriter, resp *cloudruntime.Respons
func writeCloudRuntimeError(w http.ResponseWriter, r *http.Request, err error) {
switch {
case errors.Is(err, cloudruntime.ErrDisabled):
- writeError(w, http.StatusServiceUnavailable, "cloud runtime is not configured")
+ writeFeatureDisabled(w, "cloud_runtime_not_configured", "cloud runtime is not configured")
case errors.Is(err, cloudruntime.ErrInvalidBaseURL):
- writeError(w, http.StatusServiceUnavailable, "cloud runtime is misconfigured")
+ writeErrorCode(w, http.StatusInternalServerError, "cloud_runtime_misconfigured", "cloud runtime is misconfigured")
case errors.Is(err, context.DeadlineExceeded):
writeError(w, http.StatusGatewayTimeout, "cloud runtime request timed out")
default:
diff --git a/server/internal/handler/cloud_runtime_test.go b/server/internal/handler/cloud_runtime_test.go
index 3ae831c59e..8e72c5e4dd 100644
--- a/server/internal/handler/cloud_runtime_test.go
+++ b/server/internal/handler/cloud_runtime_test.go
@@ -3,6 +3,7 @@ package handler
import (
"bytes"
"context"
+ "encoding/json"
"net/http"
"net/http/httptest"
"strings"
@@ -85,7 +86,7 @@ func TestCreateCloudRuntimeNodeForwardsBody(t *testing.T) {
}
}
-func TestCloudRuntimeDisabledReturnsUnavailable(t *testing.T) {
+func TestCloudRuntimeDisabledReturnsForbidden(t *testing.T) {
useCloudRuntimeProxy(t, &fakeCloudRuntimeProxy{enabled: false})
req := newRequest(http.MethodGet, "/api/cloud-runtime/nodes", nil)
@@ -93,9 +94,13 @@ func TestCloudRuntimeDisabledReturnsUnavailable(t *testing.T) {
testHandler.ListCloudRuntimeNodes(w, req)
- if w.Code != http.StatusServiceUnavailable {
+ if w.Code != http.StatusForbidden {
t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
}
+ var body map[string]string
+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || body["code"] != "cloud_runtime_not_configured" {
+ t.Fatalf("unexpected disabled response: body=%v err=%v", body, err)
+ }
}
func TestListCloudRuntimeNodesForwardsQuery(t *testing.T) {
diff --git a/server/internal/handler/daemon_ws.go b/server/internal/handler/daemon_ws.go
index 1ad1c1b45e..dd450f59b4 100644
--- a/server/internal/handler/daemon_ws.go
+++ b/server/internal/handler/daemon_ws.go
@@ -11,7 +11,7 @@ import (
func (h *Handler) DaemonWebSocket(w http.ResponseWriter, r *http.Request) {
if h.DaemonHub == nil {
- writeError(w, http.StatusServiceUnavailable, "daemon websocket unavailable")
+ writeErrorCode(w, http.StatusInternalServerError, "daemon_websocket_misconfigured", "daemon websocket unavailable")
return
}
diff --git a/server/internal/handler/daemon_ws_test.go b/server/internal/handler/daemon_ws_test.go
index 80132494a4..cfd221096d 100644
--- a/server/internal/handler/daemon_ws_test.go
+++ b/server/internal/handler/daemon_ws_test.go
@@ -1,6 +1,7 @@
package handler
import (
+ "encoding/json"
"net/http"
"net/http/httptest"
"testing"
@@ -10,6 +11,23 @@ import (
"github.com/multica-ai/multica/server/internal/testutil"
)
+func TestDaemonWebSocketMissingHubIsInternalError(t *testing.T) {
+ h := &Handler{}
+ w := httptest.NewRecorder()
+ h.DaemonWebSocket(w, httptest.NewRequest(http.MethodGet, "/api/daemon/ws", nil))
+
+ if w.Code != http.StatusInternalServerError {
+ t.Fatalf("status = %d, want 500: %s", w.Code, w.Body.String())
+ }
+ var body map[string]string
+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if body["code"] != "daemon_websocket_misconfigured" {
+ t.Fatalf("code = %q, want daemon_websocket_misconfigured", body["code"])
+ }
+}
+
func TestBuildDaemonWebSocketIdentitySeedsBatchRuntimeLeases(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
diff --git a/server/internal/handler/dingtalk.go b/server/internal/handler/dingtalk.go
index 099490ee5b..29e340aa13 100644
--- a/server/internal/handler/dingtalk.go
+++ b/server/internal/handler/dingtalk.go
@@ -570,7 +570,7 @@ type RegisterDingTalkBYORequest struct {
// BYO path this needs only the at-rest key configured (DingTalkInstall != nil).
func (h *Handler) RegisterDingTalkBYO(w http.ResponseWriter, r *http.Request) {
if h.DingTalkInstall == nil {
- writeError(w, http.StatusServiceUnavailable, "dingtalk integration not enabled")
+ writeFeatureDisabled(w, "dingtalk_not_configured", "dingtalk integration not enabled")
return
}
userID, ok := requireUserID(w, r)
@@ -665,7 +665,7 @@ func (h *Handler) publishDingTalkInstallationCreated(row db.ChannelInstallation,
// workspace owner/admin-only cleanup because there is no agent owner to resolve.
func (h *Handler) RevokeDingTalkInstallation(w http.ResponseWriter, r *http.Request) {
if h.DingTalkInstall == nil {
- writeError(w, http.StatusServiceUnavailable, "dingtalk integration not configured")
+ writeFeatureDisabled(w, "dingtalk_not_configured", "dingtalk integration not configured")
return
}
userID, ok := requireUserID(w, r)
@@ -736,7 +736,7 @@ type RedeemDingTalkBindingTokenResponse struct {
// - 403 Forbidden: redeemer is not a workspace member
func (h *Handler) RedeemDingTalkBindingToken(w http.ResponseWriter, r *http.Request) {
if h.DingTalkBindingTokens == nil {
- writeError(w, http.StatusServiceUnavailable, "dingtalk integration not configured")
+ writeFeatureDisabled(w, "dingtalk_not_configured", "dingtalk integration not configured")
return
}
userID, ok := requireUserID(w, r)
diff --git a/server/internal/handler/file.go b/server/internal/handler/file.go
index be76c83c7d..1963ccd24f 100644
--- a/server/internal/handler/file.go
+++ b/server/internal/handler/file.go
@@ -378,7 +378,7 @@ func (h *Handler) groupChatMessageAttachments(ctx context.Context, workspaceID s
func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {
if h.Storage == nil {
- writeError(w, http.StatusServiceUnavailable, "file upload not configured")
+ writeFeatureDisabled(w, "file_upload_not_configured", "file upload not configured")
return
}
@@ -849,7 +849,7 @@ func (h *Handler) DownloadAttachment(w http.ResponseWriter, r *http.Request) {
return
}
if h.Storage == nil {
- writeError(w, http.StatusServiceUnavailable, "storage not configured")
+ writeFeatureDisabled(w, "storage_not_configured", "storage not configured")
return
}
@@ -1292,7 +1292,7 @@ func (h *Handler) GetAttachmentContent(w http.ResponseWriter, r *http.Request) {
}
if h.Storage == nil {
- writeError(w, http.StatusServiceUnavailable, "storage not configured")
+ writeFeatureDisabled(w, "storage_not_configured", "storage not configured")
return
}
key := h.Storage.KeyFromURL(att.Url)
diff --git a/server/internal/handler/github.go b/server/internal/handler/github.go
index 85f5a29566..77c085640a 100644
--- a/server/internal/handler/github.go
+++ b/server/internal/handler/github.go
@@ -767,7 +767,7 @@ func (h *Handler) ListGitHubInstallationRepositories(w http.ResponseWriter, r *h
return
}
if !isGitHubRepositoryBrowseConfigured() {
- writeError(w, http.StatusServiceUnavailable, "github repository browsing is not configured")
+ writeFeatureDisabled(w, "github_repository_browsing_not_configured", "github repository browsing is not configured")
return
}
page, ok := parseGitHubPageParam(w, r, "page", 1, 1, 100000)
@@ -1062,7 +1062,7 @@ func (h *Handler) HandleGitHubWebhook(w http.ResponseWriter, r *http.Request) {
if secret == "" {
// Refusing to process webhooks at all is safer than treating an
// unconfigured deployment as "all signatures valid".
- writeError(w, http.StatusServiceUnavailable, "github webhooks not configured")
+ writeError(w, http.StatusNotFound, "not found")
return
}
sigHeader := r.Header.Get("X-Hub-Signature-256")
diff --git a/server/internal/handler/github_test.go b/server/internal/handler/github_test.go
index fba5bf7104..954e0be2d2 100644
--- a/server/internal/handler/github_test.go
+++ b/server/internal/handler/github_test.go
@@ -2454,6 +2454,18 @@ func TestListGitHubInstallationRepositoriesRejectsCrossWorkspaceRow(t *testing.T
}
}
+func TestGitHubWebhook_UnconfiguredDeploymentReturns404(t *testing.T) {
+ t.Setenv("GITHUB_WEBHOOK_SECRET", "")
+ req := httptest.NewRequest(http.MethodPost, "/api/webhooks/github", strings.NewReader(`{}`))
+ rec := httptest.NewRecorder()
+
+ (&Handler{}).HandleGitHubWebhook(rec, req)
+
+ if rec.Code != http.StatusNotFound {
+ t.Fatalf("expected 404 when webhook is unconfigured, got %d (%s)", rec.Code, rec.Body.String())
+ }
+}
+
// TestFetchInstallationAccount_AuthenticatedPopulatesRow simulates the
// GitHub `/app/installations/{id}` endpoint with a JWT-gated mock and
// verifies that fetchInstallationAccount, when fully configured,
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 6edc70029f..9e23de71ff 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -110,7 +110,7 @@ type Config struct {
// without a header-stripping reverse proxy in front.
TrustedProxies []netip.Prefix
// CloudURL enables the SaaS-only multica-cloud connection when set. Empty
- // keeps self-hosted deployments explicit: Cloud endpoints return 503 instead
+ // keeps self-hosted deployments explicit: Cloud endpoints return 403 instead
// of attempting to dial a hard-coded private service.
CloudURL string
CloudTimeout time.Duration
@@ -256,7 +256,7 @@ type Handler struct {
googleOAuthHTTPClient *http.Client
// Lark integration. All three are nil when the Lark master key
// (MULTICA_LARK_SECRET_KEY) is unset; the corresponding HTTP
- // handlers return 503 in that case so a misconfigured self-host
+ // handlers return 403 in that case so a misconfigured self-host
// deployment surfaces a clear error instead of silently using a
// zero key. Wired in cmd/server/router.go after handler.New.
LarkInstallations *lark.InstallationService
@@ -277,7 +277,7 @@ type Handler struct {
// entry points.
LarkAPIClient lark.APIClient
// Composio integration (MUL-3720). Nil when COMPOSIO_API_KEY is unset;
- // the composio HTTP handlers return 503 in that case. Wired in
+ // the composio HTTP handlers return 403 in that case. Wired in
// cmd/server/router.go after handler.New.
Composio *composio.Service
// ChannelSupervisor owns the per-installation supervisor goroutines
@@ -325,7 +325,7 @@ type Handler struct {
SlackHistory ChatChannelHistoryReader
// WecomStore is the read/write handle over channel_installation rows scoped
// to channel_type='wecom'. Nil disables the wecom Web-UI endpoints (they
- // return 503) and prevents boot from wiring the smart-bot supervisor.
+ // return 403) and prevents boot from wiring the smart-bot supervisor.
WecomStore *wecom.Store
// WecomCredentials unseals a wecom installation's smart-bot secret for the
// WebSocket subscribe frame. Nil disables the wecom integration.
@@ -334,7 +334,7 @@ type Handler struct {
// "link your Multica account" prompt sent to first-time WeCom users
// (their aibot userid is a "T"-prefixed anonymized id with no relation
// to their real userid or email, so an explicit binding is required —
- // see wecom/binding.go). Nil disables the redeem endpoint (returns 503)
+ // see wecom/binding.go). Nil disables the redeem endpoint (returns 403)
// and the OutboundReplier's binding-prompt path.
WecomBindingTokens WecomBindingRedeemer
@@ -386,7 +386,7 @@ type Handler struct {
LLM *llm.Client
// VCSSecretBox encrypts/decrypts per-workspace Git provider access tokens and
// webhook secrets at rest (Forgejo / Gitea / GitLab). Nil when
- // MULTICA_VCS_SECRET_KEY is unset; the connect/webhook handlers return 503
+ // MULTICA_VCS_SECRET_KEY is unset; connect returns 403 and webhook returns 404
// in that case so a misconfigured self-host deployment surfaces a clear
// error rather than silently storing plaintext. Wired in
// cmd/server/router.go after New.
@@ -572,6 +572,13 @@ func writeErrorCode(w http.ResponseWriter, status int, code, msg string) {
writeJSON(w, status, map[string]string{"error": msg, "code": code})
}
+// writeFeatureDisabled reports a deliberate deployment or feature gate as a
+// non-retryable refusal. A disabled capability is not a transient service
+// failure: returning 503 would invite retries and pollute availability alerts.
+func writeFeatureDisabled(w http.ResponseWriter, code, msg string) {
+ writeErrorCode(w, http.StatusForbidden, code, msg)
+}
+
func writeRevisionConflict(w http.ResponseWriter, resourceType string, resourceID pgtype.UUID, expected, actual int64) {
writeJSON(w, http.StatusConflict, map[string]any{
"error": "resource changed since it was loaded",
diff --git a/server/internal/handler/handler_writejson_test.go b/server/internal/handler/handler_writejson_test.go
index 9e042c4280..eb5b50a2a4 100644
--- a/server/internal/handler/handler_writejson_test.go
+++ b/server/internal/handler/handler_writejson_test.go
@@ -2,12 +2,32 @@ package handler
import (
"bytes"
+ "encoding/json"
"net/http"
"net/http/httptest"
"strconv"
"testing"
)
+func TestWriteFeatureDisabledIsNonRetryable(t *testing.T) {
+ rec := httptest.NewRecorder()
+ writeFeatureDisabled(rec, "feature_disabled", "feature is disabled")
+
+ if rec.Code != http.StatusForbidden {
+ t.Fatalf("status = %d, want %d", rec.Code, http.StatusForbidden)
+ }
+ if retryAfter := rec.Header().Get("Retry-After"); retryAfter != "" {
+ t.Fatalf("Retry-After = %q, want empty", retryAfter)
+ }
+ var body map[string]string
+ if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if body["code"] != "feature_disabled" {
+ t.Fatalf("code = %q, want feature_disabled", body["code"])
+ }
+}
+
// TestWriteMeasuredJSONByteIdenticalToWriteJSON locks the load-bearing assumption
// behind the F2 claim-observability patch: swapping writeJSON for writeMeasuredJSON
// at the /tasks/claim response sites must not change a single byte on the wire.
diff --git a/server/internal/handler/integrations_composio.go b/server/internal/handler/integrations_composio.go
index d088c212c9..174e78daf6 100644
--- a/server/internal/handler/integrations_composio.go
+++ b/server/internal/handler/integrations_composio.go
@@ -19,9 +19,10 @@ import (
// the Auth middleware. ComposioCallback is the exception: it is a public route
// (outside the Auth group, see router.go / MUL-3843) because the browser often
// arrives without a session cookie — its identity comes from the signed state,
-// not requireUserID. The whole block returns 503 when h.Composio is nil
+// not requireUserID. The whole block returns 403 when h.Composio is nil
// (COMPOSIO_API_KEY unset), matching the Lark/GitHub "integration not
-// configured" convention.
+// configured" convention. A missing deployment capability is a non-retryable
+// 403, not a transient 503.
// ComposioConnectInitRequest is the POST /connect/init body.
type ComposioConnectInitRequest struct {
@@ -65,7 +66,7 @@ func (h *Handler) composioMCPAppsEnabled(ctx context.Context) bool {
// URL. An unsupported toolkit slug is a 400 (the MVP only wires Notion).
func (h *Handler) ComposioConnectInit(w http.ResponseWriter, r *http.Request) {
if h.Composio == nil || !h.composioMCPAppsEnabled(r.Context()) {
- writeError(w, http.StatusServiceUnavailable, "composio integration not configured")
+ writeFeatureDisabled(w, "composio_not_configured", "composio integration not configured")
return
}
userID, ok := requireUserID(w, r)
@@ -110,7 +111,7 @@ func (h *Handler) ComposioConnectInit(w http.ResponseWriter, r *http.Request) {
// error code so the user is never left on a blank API response.
func (h *Handler) ComposioCallback(w http.ResponseWriter, r *http.Request) {
if h.Composio == nil || !h.composioMCPAppsEnabled(r.Context()) {
- writeError(w, http.StatusServiceUnavailable, "composio integration not configured")
+ writeFeatureDisabled(w, "composio_not_configured", "composio integration not configured")
return
}
q := r.URL.Query()
@@ -133,7 +134,7 @@ func (h *Handler) ComposioCallback(w http.ResponseWriter, r *http.Request) {
// the caller's active connections.
func (h *Handler) ListComposioConnections(w http.ResponseWriter, r *http.Request) {
if h.Composio == nil || !h.composioMCPAppsEnabled(r.Context()) {
- writeError(w, http.StatusServiceUnavailable, "composio integration not configured")
+ writeFeatureDisabled(w, "composio_not_configured", "composio integration not configured")
return
}
userID, ok := requireUserID(w, r)
@@ -172,7 +173,7 @@ func (h *Handler) ListComposioConnections(w http.ResponseWriter, r *http.Request
// load-failed state rather than a misleading empty catalog.
func (h *Handler) ListComposioToolkits(w http.ResponseWriter, r *http.Request) {
if h.Composio == nil || !h.composioMCPAppsEnabled(r.Context()) {
- writeError(w, http.StatusServiceUnavailable, "composio integration not configured")
+ writeFeatureDisabled(w, "composio_not_configured", "composio integration not configured")
return
}
if _, ok := requireUserID(w, r); !ok {
@@ -201,7 +202,7 @@ func (h *Handler) ListComposioToolkits(w http.ResponseWriter, r *http.Request) {
// a connection that does not belong to the caller is a 404.
func (h *Handler) DeleteComposioConnection(w http.ResponseWriter, r *http.Request) {
if h.Composio == nil || !h.composioMCPAppsEnabled(r.Context()) {
- writeError(w, http.StatusServiceUnavailable, "composio integration not configured")
+ writeFeatureDisabled(w, "composio_not_configured", "composio integration not configured")
return
}
userID, ok := requireUserID(w, r)
diff --git a/server/internal/handler/integrations_composio_test.go b/server/internal/handler/integrations_composio_test.go
index 56330b9471..e780fe2ce1 100644
--- a/server/internal/handler/integrations_composio_test.go
+++ b/server/internal/handler/integrations_composio_test.go
@@ -163,27 +163,31 @@ func composioReq(method, target, body string) *http.Request {
// --- tests ---
-func TestComposio_ServiceUnavailableWhenNil(t *testing.T) {
+func TestComposio_ForbiddenWhenNil(t *testing.T) {
h := &Handler{}
for _, hf := range []http.HandlerFunc{
h.ComposioConnectInit, h.ComposioCallback, h.ListComposioConnections, h.DeleteComposioConnection,
} {
w := httptest.NewRecorder()
hf(w, composioReq(http.MethodGet, "/", ""))
- if w.Code != http.StatusServiceUnavailable {
- t.Errorf("expected 503 when Composio nil, got %d", w.Code)
+ if w.Code != http.StatusForbidden {
+ t.Errorf("expected 403 when Composio nil, got %d", w.Code)
}
}
}
-func TestComposio_ServiceUnavailableWhenFlagDisabled(t *testing.T) {
+func TestComposio_ForbiddenWhenFlagDisabled(t *testing.T) {
h := newComposioTestHandler(t, &composioFakeSDK{}, &composioFakeStore{})
withComposioMCPAppsFlag(t, h, false)
w := httptest.NewRecorder()
h.ListComposioToolkits(w, composioReq(http.MethodGet, "/toolkits", ""))
- if w.Code != http.StatusServiceUnavailable {
- t.Fatalf("expected 503 when feature flag disabled, got %d", w.Code)
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("expected 403 when feature flag disabled, got %d", w.Code)
+ }
+ var body map[string]string
+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || body["code"] != "composio_not_configured" {
+ t.Fatalf("unexpected disabled response: body=%v err=%v", body, err)
}
}
diff --git a/server/internal/handler/lark.go b/server/internal/handler/lark.go
index 5428e779be..2ee134be32 100644
--- a/server/internal/handler/lark.go
+++ b/server/internal/handler/lark.go
@@ -122,7 +122,7 @@ func (h *Handler) ListLarkInstallations(w http.ResponseWriter, r *http.Request)
// rights.
func (h *Handler) RevokeLarkInstallation(w http.ResponseWriter, r *http.Request) {
if h.LarkInstallations == nil {
- writeError(w, http.StatusServiceUnavailable, "lark integration not configured")
+ writeFeatureDisabled(w, "lark_not_configured", "lark integration not configured")
return
}
userID, ok := requireUserID(w, r)
@@ -209,7 +209,7 @@ type RedeemLarkBindingTokenResponse struct {
// - 403 Forbidden: redeemer is not a workspace member
func (h *Handler) RedeemLarkBindingToken(w http.ResponseWriter, r *http.Request) {
if h.LarkBindingTokens == nil {
- writeError(w, http.StatusServiceUnavailable, "lark integration not configured")
+ writeFeatureDisabled(w, "lark_not_configured", "lark integration not configured")
return
}
userID, ok := requireUserID(w, r)
@@ -277,7 +277,7 @@ type BeginLarkInstallResponse struct {
// in that case so this should not be reached through the normal flow.
func (h *Handler) BeginLarkInstall(w http.ResponseWriter, r *http.Request) {
if h.LarkRegistration == nil {
- writeError(w, http.StatusServiceUnavailable, "lark install not configured")
+ writeFeatureDisabled(w, "lark_not_configured", "lark install not configured")
return
}
userID, ok := requireUserID(w, r)
@@ -385,7 +385,7 @@ type LarkInstallStatusResponse struct {
// idempotent.
func (h *Handler) GetLarkInstallStatus(w http.ResponseWriter, r *http.Request) {
if h.LarkRegistration == nil {
- writeError(w, http.StatusServiceUnavailable, "lark install not configured")
+ writeFeatureDisabled(w, "lark_not_configured", "lark install not configured")
return
}
userID, ok := requireUserID(w, r)
diff --git a/server/internal/handler/lark_test.go b/server/internal/handler/lark_test.go
index f2dfa7715b..f537b74b5e 100644
--- a/server/internal/handler/lark_test.go
+++ b/server/internal/handler/lark_test.go
@@ -26,8 +26,8 @@ func TestRevokeLarkInstallation_NotConfigured(t *testing.T) {
req := httptest.NewRequest(http.MethodDelete, "/api/workspaces/x/lark/installations/y", nil)
w := httptest.NewRecorder()
h.RevokeLarkInstallation(w, req)
- if w.Code != http.StatusServiceUnavailable {
- t.Fatalf("expected 503, got %d", w.Code)
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("expected 403, got %d", w.Code)
}
}
@@ -36,15 +36,15 @@ func TestRedeemLarkBindingToken_NotConfigured(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/api/lark/binding/redeem", strings.NewReader(`{"token":"x"}`))
w := httptest.NewRecorder()
h.RedeemLarkBindingToken(w, req)
- if w.Code != http.StatusServiceUnavailable {
- t.Fatalf("expected 503, got %d", w.Code)
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("expected 403, got %d", w.Code)
}
}
func TestBeginLarkInstall_NotConfigured(t *testing.T) {
// When the device-flow registration service is nil (no at-rest
// key, or the stub APIClient is the only one wired), the begin
- // endpoint must short-circuit to 503 — silently returning a
+ // endpoint must short-circuit to 403 — silently returning a
// "configured: false" envelope would hide a real misconfiguration
// from the operator. The UI hides the bind button in that case
// so this should not be reached through the normal flow.
@@ -52,8 +52,8 @@ func TestBeginLarkInstall_NotConfigured(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/api/workspaces/x/lark/install/begin?agent_id=y", nil)
w := httptest.NewRecorder()
h.BeginLarkInstall(w, req)
- if w.Code != http.StatusServiceUnavailable {
- t.Fatalf("expected 503, got %d body=%s", w.Code, w.Body.String())
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("expected 403, got %d body=%s", w.Code, w.Body.String())
}
}
@@ -62,15 +62,15 @@ func TestGetLarkInstallStatus_NotConfigured(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/api/workspaces/x/lark/install/sess_y/status", nil)
w := httptest.NewRecorder()
h.GetLarkInstallStatus(w, req)
- if w.Code != http.StatusServiceUnavailable {
- t.Fatalf("expected 503, got %d", w.Code)
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("expected 403, got %d", w.Code)
}
}
func TestListLarkInstallations_NotConfiguredReturnsEmpty(t *testing.T) {
// Listing is intentionally a "soft" endpoint: when lark is not
// configured we return an empty list + configured:false rather
- // than a 503, so the Integrations tab renders normally with a
+ // than a 403, so the Integrations tab renders normally with a
// "not connected" empty state instead of an error banner.
h := &Handler{}
req := httptest.NewRequest(http.MethodGet, "/api/workspaces/x/lark/installations", nil)
diff --git a/server/internal/handler/plugin.go b/server/internal/handler/plugin.go
index b40418891a..4c61de4916 100644
--- a/server/internal/handler/plugin.go
+++ b/server/internal/handler/plugin.go
@@ -21,7 +21,7 @@ func (h *Handler) requirePluginsV1(w http.ResponseWriter, r *http.Request) bool
if h.pluginsV1Enabled(r.Context()) {
return true
}
- writeError(w, http.StatusServiceUnavailable, "Plugin management is not enabled")
+ writeFeatureDisabled(w, "plugin_api_disabled", "Plugin management is not enabled")
return false
}
diff --git a/server/internal/handler/plugin_action.go b/server/internal/handler/plugin_action.go
index 5f937f5369..1c1e095e03 100644
--- a/server/internal/handler/plugin_action.go
+++ b/server/internal/handler/plugin_action.go
@@ -77,7 +77,7 @@ func (h *Handler) requirePluginActionV1(w http.ResponseWriter, r *http.Request)
if h.pluginsV1Enabled(r.Context()) {
return true
}
- publicapiv1.WriteProblem(w, r, http.StatusServiceUnavailable, "plugin_api_disabled", "Plugin management is not enabled")
+ publicapiv1.WriteProblem(w, r, http.StatusForbidden, "plugin_api_disabled", "Plugin management is not enabled")
return false
}
diff --git a/server/internal/handler/plugin_action_test.go b/server/internal/handler/plugin_action_test.go
index 957baade08..c437e009e7 100644
--- a/server/internal/handler/plugin_action_test.go
+++ b/server/internal/handler/plugin_action_test.go
@@ -79,6 +79,27 @@ func pluginInstallTokenRequest(method, path, token string, body any, params map[
return request
}
+func TestPluginActionRequiresTheFeatureFlag(t *testing.T) {
+ withPluginsV1Flag(t, testHandler, false)
+ recorder := httptest.NewRecorder()
+
+ testHandler.GetPluginContext(recorder, pluginInstallTokenRequest(http.MethodGet, "/v1/context", "mpi_invalid", nil, nil))
+
+ if recorder.Code != http.StatusForbidden {
+ t.Fatalf("status=%d body=%s, want 403", recorder.Code, recorder.Body.String())
+ }
+ if got := recorder.Header().Get("Retry-After"); got != "" {
+ t.Fatalf("Retry-After=%q, want empty for a non-retryable feature gate", got)
+ }
+ var problem publicapiv1.Problem
+ if err := json.Unmarshal(recorder.Body.Bytes(), &problem); err != nil {
+ t.Fatalf("decode feature flag problem: %v", err)
+ }
+ if problem.Status != http.StatusForbidden || problem.Code != "plugin_api_disabled" || problem.Title != "Forbidden" {
+ t.Fatalf("unexpected feature flag problem: %+v", problem)
+ }
+}
+
func TestPluginInstallTokenRunsIssueCommentWorkflow(t *testing.T) {
installationID := installPluginForAction(t, []string{"issues:read", "issues:write", "comments:read", "comments:write"})
token, err := testHandler.PluginService.IssueInstallToken(context.Background(), parseUUID(installationID))
diff --git a/server/internal/handler/plugin_hook_test.go b/server/internal/handler/plugin_hook_test.go
index 36658eaee3..be3e4def4d 100644
--- a/server/internal/handler/plugin_hook_test.go
+++ b/server/internal/handler/plugin_hook_test.go
@@ -129,15 +129,11 @@ func TestInvokePluginHookRefusesUnknownHook(t *testing.T) {
// The flag gates the hook endpoint like every other plugin route: fail closed,
// not merely hidden from the UI.
func TestInvokePluginHookRequiresTheFeatureFlag(t *testing.T) {
- withPluginsV1Flag(t, testHandler, true)
- cleanupPluginInstallations(t)
- installationID := installHookPlugin(t)
-
withPluginsV1Flag(t, testHandler, false)
recorder := httptest.NewRecorder()
- testHandler.InvokePluginHook(recorder, invokeHookRequest(installationID, "summarize", map[string]any{"trigger": "manual"}))
- if recorder.Code != http.StatusServiceUnavailable {
- t.Fatalf("status=%d body=%s, want 503", recorder.Code, recorder.Body.String())
+ testHandler.InvokePluginHook(recorder, invokeHookRequest("11111111-1111-1111-1111-111111111111", "summarize", map[string]any{"trigger": "manual"}))
+ if recorder.Code != http.StatusForbidden {
+ t.Fatalf("status=%d body=%s, want 403", recorder.Code, recorder.Body.String())
}
}
diff --git a/server/internal/handler/plugin_surface.go b/server/internal/handler/plugin_surface.go
index 7202aff173..ab7fc39cc6 100644
--- a/server/internal/handler/plugin_surface.go
+++ b/server/internal/handler/plugin_surface.go
@@ -153,13 +153,17 @@ func (h *Handler) GetPluginSurfaceLaunch(w http.ResponseWriter, r *http.Request)
if !h.requirePluginsV1(w, r) {
return
}
+ if strings.TrimSpace(h.cfg.PluginSurfaceOrigin) == "" || h.PluginSurfaceTokens == nil {
+ writeFeatureDisabled(w, "plugin_surfaces_not_configured", "Plugin surfaces are unavailable: MULTICA_PLUGIN_SURFACE_ORIGIN and MULTICA_PLUGIN_SECRET_KEY must be configured")
+ return
+ }
origin, err := parsePluginSurfaceOrigin(h.cfg.PluginSurfaceOrigin)
- if err != nil || h.PluginSurfaceTokens == nil {
- writeError(w, http.StatusServiceUnavailable, "Plugin surfaces are unavailable: MULTICA_PLUGIN_SURFACE_ORIGIN and MULTICA_PLUGIN_SECRET_KEY must be configured")
+ if err != nil {
+ writeErrorCode(w, http.StatusInternalServerError, "plugin_surfaces_misconfigured", "Plugin surfaces require a valid MULTICA_PLUGIN_SURFACE_ORIGIN")
return
}
if !h.pluginSurfaceOriginIsDedicated(origin) {
- writeError(w, http.StatusServiceUnavailable, "Plugin surfaces require a dedicated content origin separate from the app and API origins")
+ writeErrorCode(w, http.StatusInternalServerError, "plugin_surfaces_misconfigured", "Plugin surfaces require a dedicated content origin separate from the app and API origins")
return
}
diff --git a/server/internal/handler/plugin_surface_test.go b/server/internal/handler/plugin_surface_test.go
index f2ac4aa614..ea54cb4b1e 100644
--- a/server/internal/handler/plugin_surface_test.go
+++ b/server/internal/handler/plugin_surface_test.go
@@ -2,6 +2,7 @@ package handler
import (
"bytes"
+ "encoding/json"
"net/http"
"net/http/httptest"
"strings"
@@ -105,6 +106,63 @@ func TestPluginSurfaceOriginMustDifferFromEveryAppOrigin(t *testing.T) {
}
}
+func TestPluginSurfaceLaunchDistinguishesDisabledFromMisconfigured(t *testing.T) {
+ tests := []struct {
+ name string
+ handler func(t *testing.T) *Handler
+ wantStatus int
+ wantCode string
+ }{
+ {
+ name: "missing configuration",
+ handler: func(*testing.T) *Handler { return &Handler{} },
+ wantStatus: http.StatusForbidden,
+ wantCode: "plugin_surfaces_not_configured",
+ },
+ {
+ name: "invalid origin",
+ handler: func(t *testing.T) *Handler {
+ h := pluginSurfaceTokenHandler(t)
+ h.cfg.PluginSurfaceOrigin = "not-an-origin"
+ return h
+ },
+ wantStatus: http.StatusInternalServerError,
+ wantCode: "plugin_surfaces_misconfigured",
+ },
+ {
+ name: "shared app origin",
+ handler: func(t *testing.T) *Handler {
+ h := pluginSurfaceTokenHandler(t)
+ h.cfg.PluginSurfaceOrigin = "https://app.example.test"
+ h.cfg.AppURL = "https://app.example.test"
+ return h
+ },
+ wantStatus: http.StatusInternalServerError,
+ wantCode: "plugin_surfaces_misconfigured",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ h := tt.handler(t)
+ withPluginsV1Flag(t, h, true)
+ recorder := httptest.NewRecorder()
+ h.GetPluginSurfaceLaunch(recorder, pluginHandlerRequest(http.MethodGet, "/plugins/surface", nil, nil))
+
+ if recorder.Code != tt.wantStatus {
+ t.Fatalf("status=%d body=%s, want %d", recorder.Code, recorder.Body.String(), tt.wantStatus)
+ }
+ var body map[string]string
+ if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if body["code"] != tt.wantCode {
+ t.Fatalf("code=%q, want %q", body["code"], tt.wantCode)
+ }
+ })
+ }
+}
+
func TestServePluginSurfaceRejectsConfiguredAppOriginBeforeOpeningToken(t *testing.T) {
h := pluginSurfaceTokenHandler(t)
h.cfg.AppURL = "https://app.example.test"
diff --git a/server/internal/handler/plugin_test.go b/server/internal/handler/plugin_test.go
index 95d692340a..cea637aae1 100644
--- a/server/internal/handler/plugin_test.go
+++ b/server/internal/handler/plugin_test.go
@@ -378,7 +378,7 @@ func TestPluginManagementRequiresPluginsV1(t *testing.T) {
t.Run(name, func(t *testing.T) {
recorder := httptest.NewRecorder()
handler(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", []byte(`{}`), map[string]string{"id": testWorkspaceID}))
- if recorder.Code != http.StatusServiceUnavailable {
+ if recorder.Code != http.StatusForbidden {
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
}
})
diff --git a/server/internal/handler/slack.go b/server/internal/handler/slack.go
index 527e547645..ffc9da2257 100644
--- a/server/internal/handler/slack.go
+++ b/server/internal/handler/slack.go
@@ -97,7 +97,7 @@ type RegisterSlackBYORequest struct {
// credentials — BYO is exactly the path for deployments without a hosted app.
func (h *Handler) RegisterSlackBYO(w http.ResponseWriter, r *http.Request) {
if h.SlackInstall == nil {
- writeError(w, http.StatusServiceUnavailable, "slack integration not enabled")
+ writeFeatureDisabled(w, "slack_not_configured", "slack integration not enabled")
return
}
userID, ok := requireUserID(w, r)
@@ -181,7 +181,7 @@ func (h *Handler) publishSlackInstallationCreated(row db.ChannelInstallation, ac
// audit; a re-install (re-pasting the app's tokens) flips status back to 'active'.
func (h *Handler) RevokeSlackInstallation(w http.ResponseWriter, r *http.Request) {
if h.SlackInstall == nil {
- writeError(w, http.StatusServiceUnavailable, "slack integration not configured")
+ writeFeatureDisabled(w, "slack_not_configured", "slack integration not configured")
return
}
userID, ok := requireUserID(w, r)
@@ -239,7 +239,7 @@ type RedeemSlackBindingTokenResponse struct {
// - 403 Forbidden: redeemer is not a workspace member
func (h *Handler) RedeemSlackBindingToken(w http.ResponseWriter, r *http.Request) {
if h.SlackBindingTokens == nil {
- writeError(w, http.StatusServiceUnavailable, "slack integration not configured")
+ writeFeatureDisabled(w, "slack_not_configured", "slack integration not configured")
return
}
userID, ok := requireUserID(w, r)
diff --git a/server/internal/handler/telegram.go b/server/internal/handler/telegram.go
index 062e13fc78..10877f2c8c 100644
--- a/server/internal/handler/telegram.go
+++ b/server/internal/handler/telegram.go
@@ -90,7 +90,7 @@ type RegisterTelegramRequest struct {
// router. Mirrors RegisterSlackBYO.
func (h *Handler) RegisterTelegramBot(w http.ResponseWriter, r *http.Request) {
if h.TelegramInstall == nil {
- writeError(w, http.StatusServiceUnavailable, "telegram integration not enabled")
+ writeFeatureDisabled(w, "telegram_not_configured", "telegram integration not enabled")
return
}
userID, ok := requireUserID(w, r)
@@ -168,7 +168,7 @@ func (h *Handler) RegisterTelegramBot(w http.ResponseWriter, r *http.Request) {
// bot's token) flips status back to 'active'.
func (h *Handler) RevokeTelegramInstallation(w http.ResponseWriter, r *http.Request) {
if h.TelegramInstall == nil {
- writeError(w, http.StatusServiceUnavailable, "telegram integration not configured")
+ writeFeatureDisabled(w, "telegram_not_configured", "telegram integration not configured")
return
}
userID, ok := requireUserID(w, r)
@@ -223,7 +223,7 @@ type RedeemTelegramBindingTokenResponse struct {
// mirror the Slack redeem handler.
func (h *Handler) RedeemTelegramBindingToken(w http.ResponseWriter, r *http.Request) {
if h.TelegramBindingTokens == nil {
- writeError(w, http.StatusServiceUnavailable, "telegram integration not configured")
+ writeFeatureDisabled(w, "telegram_not_configured", "telegram integration not configured")
return
}
userID, ok := requireUserID(w, r)
diff --git a/server/internal/handler/telegram_test.go b/server/internal/handler/telegram_test.go
index 1145c15455..e392187717 100644
--- a/server/internal/handler/telegram_test.go
+++ b/server/internal/handler/telegram_test.go
@@ -74,8 +74,8 @@ func TestTelegramMutationHandlersRejectUnconfiguredDeployment(t *testing.T) {
tt.run(h, w, req)
- if w.Code != http.StatusServiceUnavailable {
- t.Fatalf("expected 503, got %d body=%s", w.Code, w.Body.String())
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("expected 403, got %d body=%s", w.Code, w.Body.String())
}
})
}
diff --git a/server/internal/handler/vcs.go b/server/internal/handler/vcs.go
index 0a4cbbe387..ea0f301e16 100644
--- a/server/internal/handler/vcs.go
+++ b/server/internal/handler/vcs.go
@@ -165,7 +165,7 @@ func (h *Handler) ConnectVCS(w http.ResponseWriter, r *http.Request) {
return
}
if !h.isVCSConfigured() {
- writeError(w, http.StatusServiceUnavailable, "vcs integration not configured (MULTICA_VCS_SECRET_KEY unset)")
+ writeFeatureDisabled(w, "vcs_not_configured", "vcs integration not configured (MULTICA_VCS_SECRET_KEY unset)")
return
}
@@ -287,7 +287,7 @@ func (h *Handler) RotateVCSConnectionWebhook(w http.ResponseWriter, r *http.Requ
return
}
if !h.isVCSConfigured() {
- writeError(w, http.StatusServiceUnavailable, "vcs integration not configured (MULTICA_VCS_SECRET_KEY unset)")
+ writeFeatureDisabled(w, "vcs_not_configured", "vcs integration not configured (MULTICA_VCS_SECRET_KEY unset)")
return
}
diff --git a/server/internal/handler/vcs_webhook.go b/server/internal/handler/vcs_webhook.go
index 59590b8458..32b3c218c5 100644
--- a/server/internal/handler/vcs_webhook.go
+++ b/server/internal/handler/vcs_webhook.go
@@ -97,7 +97,7 @@ func (h *Handler) HandleVCSWebhook(w http.ResponseWriter, r *http.Request) {
return
}
if !h.isVCSConfigured() {
- writeError(w, http.StatusServiceUnavailable, "vcs webhooks not configured")
+ writeError(w, http.StatusNotFound, "unknown connection")
return
}
connUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "connectionId"), "connection id")
diff --git a/server/internal/handler/vcs_webhook_test.go b/server/internal/handler/vcs_webhook_test.go
index 43ef005762..504eb5f352 100644
--- a/server/internal/handler/vcs_webhook_test.go
+++ b/server/internal/handler/vcs_webhook_test.go
@@ -536,6 +536,16 @@ func TestVCSWebhook_DisabledDeploymentReturns404(t *testing.T) {
}
}
+func TestVCSWebhook_UnconfiguredDeploymentReturns404(t *testing.T) {
+ h := &Handler{cfg: Config{VCSIntegrationEnabled: true}}
+ w := httptest.NewRecorder()
+ h.HandleVCSWebhook(w, vcsWebhookReq("00000000-0000-0000-0000-000000000000", nil, []byte(`{}`)))
+
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("expected 404 when integration is unconfigured, got %d (%s)", w.Code, w.Body.String())
+ }
+}
+
func TestVCSWebhook_MalformedTolerated(t *testing.T) {
ctx := context.Background()
box := withVCSBox(t)
diff --git a/server/internal/handler/wecom_web.go b/server/internal/handler/wecom_web.go
index 136c18d053..3d9bdf4894 100644
--- a/server/internal/handler/wecom_web.go
+++ b/server/internal/handler/wecom_web.go
@@ -63,7 +63,7 @@ func wecomInstallationToResponse(inst wecom.Installation) WecomInstallationRespo
// wecomIntegrationConfigured reports whether the wecom integration is
// wired on this deployment. Both surfaces (list + register) short-circuit
-// on it: list degrades to an empty response, register returns 503.
+// on it: list degrades to an empty response, register returns 403.
func (h *Handler) wecomIntegrationConfigured() bool {
return h.WecomStore != nil && h.WecomCredentials != nil && h.ChannelRouter != nil
}
@@ -86,7 +86,7 @@ func (h *Handler) ListWecomInstallations(w http.ResponseWriter, r *http.Request)
}
svc := h.wecomInstallService()
if svc == nil {
- writeError(w, http.StatusServiceUnavailable, "wecom integration not enabled")
+ writeFeatureDisabled(w, "wecom_not_configured", "wecom integration not enabled")
return
}
rows, err := svc.ListByWorkspace(r.Context(), wsUUID)
@@ -126,12 +126,12 @@ type RegisterWecomBYORequest struct {
// Admin-only at the router.
func (h *Handler) RegisterWecomBYO(w http.ResponseWriter, r *http.Request) {
if !h.wecomIntegrationConfigured() {
- writeError(w, http.StatusServiceUnavailable, "wecom integration not enabled")
+ writeFeatureDisabled(w, "wecom_not_configured", "wecom integration not enabled")
return
}
svc := h.wecomInstallService()
if svc == nil {
- writeError(w, http.StatusServiceUnavailable, "wecom integration not enabled")
+ writeFeatureDisabled(w, "wecom_not_configured", "wecom integration not enabled")
return
}
userID, ok := requireUserID(w, r)
@@ -264,12 +264,12 @@ func writeWecomInstallError(w http.ResponseWriter, err error, wsUUID, agentUUID
// re-install through Upsert flips it back to 'active' atomically.
func (h *Handler) RevokeWecomInstallation(w http.ResponseWriter, r *http.Request) {
if !h.wecomIntegrationConfigured() {
- writeError(w, http.StatusServiceUnavailable, "wecom integration not enabled")
+ writeFeatureDisabled(w, "wecom_not_configured", "wecom integration not enabled")
return
}
svc := h.wecomInstallService()
if svc == nil {
- writeError(w, http.StatusServiceUnavailable, "wecom integration not enabled")
+ writeFeatureDisabled(w, "wecom_not_configured", "wecom integration not enabled")
return
}
userID, ok := requireUserID(w, r)
@@ -358,7 +358,7 @@ type RedeemWecomBindingTokenResponse struct {
// - 403 Forbidden: redeemer is not a workspace member
func (h *Handler) RedeemWecomBindingToken(w http.ResponseWriter, r *http.Request) {
if h.WecomBindingTokens == nil {
- writeError(w, http.StatusServiceUnavailable, "wecom integration not configured")
+ writeFeatureDisabled(w, "wecom_not_configured", "wecom integration not configured")
return
}
userID, ok := requireUserID(w, r)
diff --git a/server/internal/maintenance/http.go b/server/internal/maintenance/http.go
index f830946e36..8507d3ffc1 100644
--- a/server/internal/maintenance/http.go
+++ b/server/internal/maintenance/http.go
@@ -135,7 +135,7 @@ func respond(w http.ResponseWriter, j Job, err error) {
case errors.Is(err, ErrThrottled):
status = http.StatusTooManyRequests
default:
- status = http.StatusServiceUnavailable
+ status = http.StatusInternalServerError
}
slog.Warn("maintenance request failed", "job_id", j.ID, "revision", j.Revision, "error", err)
}
diff --git a/server/internal/maintenance/http_test.go b/server/internal/maintenance/http_test.go
index d797b91c5f..1b3ab6dba2 100644
--- a/server/internal/maintenance/http_test.go
+++ b/server/internal/maintenance/http_test.go
@@ -31,6 +31,24 @@ func TestInternalListenerConfiguration(t *testing.T) {
t.Fatalf("listener=%+v err=%v", server, err)
}
}
+
+func TestInternalHTTPUnexpectedErrorIsNotRetryable(t *testing.T) {
+ w := httptest.NewRecorder()
+ respond(w, Job{}, errors.New("unexpected failure"))
+ if w.Code != http.StatusInternalServerError {
+ t.Fatalf("status=%d body=%s, want 500", w.Code, w.Body.String())
+ }
+ var body struct {
+ Retryable bool `json:"retryable"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if body.Retryable {
+ t.Fatal("unexpected internal errors must not be labeled retryable")
+ }
+}
+
func TestInternalHTTPRejectsMalformedRequestsWithoutDatabase(t *testing.T) {
h := NewHandler(NewService(nil, StatusCategory{}))
for _, body := range []string{"null", "[]", "{} {}", "{} garbage", `{"unknown":true}`, string(bytes.Repeat([]byte("x"), 17000))} {