Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(entitlement): paid-feature restrictions with read-only downgrade, starting with private projects (MUL-9482) (#10819)
Multica Eve2d4da48ce077
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 53c52813f6..d7b3141611 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -264,6 +264,7 @@ import type {CreateBillingPortalSessionResponse,WorkspaceSubscriptionSummary,WorkspaceSubscriptionPrices,+ WorkspaceFeatures,CreateWorkspaceSubscriptionCheckoutRequest,CreateWorkspaceSubscriptionCheckoutResponse,WorkspaceSubscriptionSeatReconcileResult,@@ -421,6 +422,7 @@ import {BatchUpdateIssuesResponseSchema,UNCONFIRMED_BATCH_UPDATE,WorkspaceSubscriptionPricesSchema,+ WorkspaceFeaturesSchema,CreateWorkspaceSubscriptionCheckoutResponseSchema,WorkspaceSubscriptionSeatReconcileResultSchema,WorkspaceSeatPurchasePreviewSchema,@@ -2469,6 +2471,19 @@ export class ApiClient {);}+ // Paid-feature states for read-only and upgrade UI (MUL-9482). A response+ // that cannot be read falls back to every feature available: the server+ // still enforces on write.+ async getWorkspaceFeatures(workspaceId: string): Promise<WorkspaceFeatures> {+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/features`);+ return parseWithFallback<WorkspaceFeatures>(+ raw,+ WorkspaceFeaturesSchema,+ { features: {} },+ { endpoint: "GET /api/workspaces/:id/features" },+ );+ }+async getWorkspaceSubscriptionPrices(): Promise<WorkspaceSubscriptionPrices | null> {const raw = await this.fetch<unknown>("/api/cloud-subscriptions/prices");return parseWithFallback<WorkspaceSubscriptionPrices | null>(diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 0948b4273f..bc68f84d12 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -36,6 +36,8 @@ import type {CreateBillingCheckoutSessionResponse,CreateBillingPortalSessionResponse,WorkspaceSubscriptionEntitlements,+ WorkspaceFeatureState,+ WorkspaceFeatures,WorkspaceSubscriptionSummary,WorkspaceSubscriptionPrice,WorkspaceSubscriptionPrices,@@ -3791,6 +3793,26 @@ export const WorkspaceSubscriptionPricesSchema = z}),);+// An unknown state from a newer server reads as available: the server still+// enforces on write, so the worst case is an upgrade prompt after the attempt+// instead of before it. A malformed entry is dropped the same way.+const WorkspaceFeatureStateSchema = z+ .object({ state: z.enum(["available", "locked"]).catch("available") })+ .loose()+ .transform((value): WorkspaceFeatureState => value.state)+ .catch("available" as const);++export const WorkspaceFeaturesSchema = z+ .object({+ features: z.record(z.string(), WorkspaceFeatureStateSchema).catch({}),+ })+ .loose()+ .transform(+ (value): WorkspaceFeatures => ({+ features: value.features as WorkspaceFeatures["features"],+ }),+ );+export const CreateWorkspaceSubscriptionCheckoutResponseSchema = z.object({request_id: z.string(),diff --git a/packages/core/billing/index.ts b/packages/core/billing/index.tsindex 36c877a0dc..0dfbaf2b92 100644--- a/packages/core/billing/index.ts+++ b/packages/core/billing/index.ts@@ -3,3 +3,4 @@ export * from "./mutations";export * from "./workspace-subscription-queries";export * from "./workspace-subscription-mutations";export * from "./recovery";+export * from "./paid-features";diff --git a/packages/core/billing/paid-features.test.tsx b/packages/core/billing/paid-features.test.tsxnew file mode 100644index 0000000000..50b495b21d--- /dev/null+++ b/packages/core/billing/paid-features.test.tsx@@ -0,0 +1,141 @@+/**+ * @vitest-environment jsdom+ */+import { renderHook, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { ReactNode } from "react";+import { afterEach, describe, expect, it, vi } from "vitest";++import { ApiError, setApiInstance } from "../api";+import type { ApiClient } from "../api/client";+import { WorkspaceFeaturesSchema } from "../api/schemas";+import type { WorkspaceFeatures } from "../types";+import {+ isFeatureLockedError,+ refreshFeaturesOnLockedError,+ resolvePaidFeatureAccess,+ usePaidFeatureAccess,+ workspaceFeatureKeys,+} from "./paid-features";++function setup(getWorkspaceFeatures: (wsId: string) => Promise<WorkspaceFeatures>) {+ const api = { getWorkspaceFeatures: vi.fn(getWorkspaceFeatures) };+ setApiInstance(api as unknown as ApiClient);+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>+ );+ return { api, qc, wrapper };+}++afterEach(() => {+ vi.restoreAllMocks();+});++describe("resolvePaidFeatureAccess", () => {+ it("maps the server state and the resource's own configuration to a UI state", () => {+ expect(resolvePaidFeatureAccess("available", false)).toBe("available");+ expect(resolvePaidFeatureAccess("available", true)).toBe("available");+ expect(resolvePaidFeatureAccess("locked", true)).toBe("read_only");+ expect(resolvePaidFeatureAccess("locked", false)).toBe("unavailable");+ });+});++describe("usePaidFeatureAccess", () => {+ it("is read-only for a resource that already uses a locked feature, and never blocks reductions", async () => {+ const { wrapper } = setup(async () => ({ features: { private_projects: "locked" } }));+ const { result } = renderHook(+ () => usePaidFeatureAccess("ws-1", "private_projects", { hasExistingConfig: true }),+ { wrapper },+ );+ await waitFor(() => expect(result.current.isPending).toBe(false));+ expect(result.current).toMatchObject({ state: "read_only", canAdd: false, canReduce: true });+ });++ it("keys the read by workspace", async () => {+ const { api, wrapper } = setup(async (wsId) => ({+ features: { private_projects: wsId === "ws-locked" ? "locked" : "available" },+ }));+ const locked = renderHook(+ () => usePaidFeatureAccess("ws-locked", "private_projects", { hasExistingConfig: false }),+ { wrapper },+ );+ const open = renderHook(+ () => usePaidFeatureAccess("ws-open", "private_projects", { hasExistingConfig: false }),+ { wrapper },+ );+ await waitFor(() => expect(locked.result.current.state).toBe("unavailable"));+ await waitFor(() => expect(open.result.current.state).toBe("available"));+ expect(api.getWorkspaceFeatures).toHaveBeenCalledWith("ws-locked");+ expect(api.getWorkspaceFeatures).toHaveBeenCalledWith("ws-open");+ });++ it("offers no additions while loading, so a locked form never flashes as editable", () => {+ const { wrapper } = setup(() => new Promise<WorkspaceFeatures>(() => {}));+ const { result } = renderHook(+ () => usePaidFeatureAccess("ws-1", "private_projects", { hasExistingConfig: false }),+ { wrapper },+ );+ expect(result.current).toMatchObject({ state: null, isPending: true, canAdd: false });+ });++ it("leaves additions to the server when the read fails, without an upgrade prompt", async () => {+ const { wrapper } = setup(async () => {+ throw new Error("offline");+ });+ const { result } = renderHook(+ () => usePaidFeatureAccess("ws-1", "private_projects", { hasExistingConfig: false }),+ { wrapper },+ );+ await waitFor(() => expect(result.current.isError).toBe(true));+ expect(result.current).toMatchObject({ state: null, canAdd: true });+ });++ it("treats a feature the server did not report as available", async () => {+ const { wrapper } = setup(async () => ({ features: {} }));+ const { result } = renderHook(+ () => usePaidFeatureAccess("ws-1", "private_projects", { hasExistingConfig: true }),+ { wrapper },+ );+ await waitFor(() => expect(result.current.state).toBe("available"));+ });+});++describe("feature_locked errors", () => {+ const locked = new ApiError("locked", 403, "Forbidden", { code: "feature_locked", feature: "private_projects" });++ it("is recognised only from the machine-readable code", () => {+ expect(isFeatureLockedError(locked)).toBe(true);+ expect(isFeatureLockedError(new ApiError("no", 403, "Forbidden", { error: "only admins" }))).toBe(false);+ expect(isFeatureLockedError(new ApiError("no", 400, "Bad Request", { code: "feature_locked" }))).toBe(false);+ expect(isFeatureLockedError(new Error("feature_locked"))).toBe(false);+ });++ it("refetches the workspace's features so the form shows its locked state", () => {+ const qc = new QueryClient();+ const invalidate = vi.spyOn(qc, "invalidateQueries");+ refreshFeaturesOnLockedError(qc, "ws-1", new ApiError("no", 403, "Forbidden", { error: "only admins" }));+ expect(invalidate).not.toHaveBeenCalled();+ refreshFeaturesOnLockedError(qc, "ws-1", locked);+ expect(invalidate).toHaveBeenCalledWith({ queryKey: workspaceFeatureKeys.all("ws-1") });+ });+});++describe("WorkspaceFeaturesSchema", () => {+ it("reads known states and falls back to available for anything it cannot read", () => {+ expect(+ WorkspaceFeaturesSchema.parse({+ features: {+ private_projects: { state: "locked" },+ future_feature: { state: "something_new" },+ broken: "locked",+ },+ extra: true,+ }),+ ).toEqual({+ features: { private_projects: "locked", future_feature: "available", broken: "available" },+ });+ expect(WorkspaceFeaturesSchema.parse({ features: [] })).toEqual({ features: {} });+ expect(WorkspaceFeaturesSchema.parse({})).toEqual({ features: {} });+ });+});diff --git a/packages/core/billing/paid-features.ts b/packages/core/billing/paid-features.tsnew file mode 100644index 0000000000..c317cb9ffa--- /dev/null+++ b/packages/core/billing/paid-features.ts@@ -0,0 +1,113 @@+import { queryOptions, useQuery, type QueryClient } from "@tanstack/react-query";+import { api, ApiError } from "../api";+import type { PaidFeature, WorkspaceFeatureState } from "../types";++/**+ * Paid features (MUL-9482).+ *+ * The server says, per workspace, whether each paid feature is `available` or+ * `locked`. Locked never takes anything away: existing configuration keeps+ * working and can always be reduced or removed, but nothing can be added. A+ * component turns that into one of three UI states for the resource it shows:+ *+ * - `available`: use it normally.+ * - `read_only`: locked, and this resource already uses the feature. Show+ * "Read-only. Upgrade to edit." and hide only the add/widen actions.+ * - `unavailable`: locked, and this resource does not use the feature yet.+ * Show the upgrade prompt where the feature would be turned on.+ */+export type PaidFeatureAccessState = "available" | "read_only" | "unavailable";++export const FEATURE_LOCKED_CODE = "feature_locked";++export const workspaceFeatureKeys = {+ all: (wsId: string) => ["workspace-features", wsId] as const,+};++/**+ * Short stale time plus refetch on focus: a plan change or a trial ending+ * happens outside this tab (Stripe, another device, a clock), and the read is+ * cheap.+ */+export function workspaceFeaturesOptions(wsId: string) {+ return queryOptions({+ queryKey: workspaceFeatureKeys.all(wsId),+ queryFn: () => api.getWorkspaceFeatures(wsId),+ enabled: wsId.length > 0,+ staleTime: 30 * 1000,+ refetchOnWindowFocus: true,+ });+}++export function resolvePaidFeatureAccess(+ state: WorkspaceFeatureState,+ hasExistingConfig: boolean,+): PaidFeatureAccessState {+ if (state === "available") return "available";+ return hasExistingConfig ? "read_only" : "unavailable";+}++export interface PaidFeatureAccess {+ /** Null while the state is loading or could not be read. */+ state: PaidFeatureAccessState | null;+ isPending: boolean;+ isError: boolean;+ /**+ * Whether add/widen actions are offered. False while loading so a locked+ * workspace never flashes an editable form; true when the read failed,+ * because the server still decides on write and a failed read must not+ * show an upgrade prompt to a workspace that may well have the feature.+ */+ canAdd: boolean;+ /** Reducing or removing configuration is never restricted by plan. */+ canReduce: true;+}++/**+ * The paid-feature access for one resource in one workspace.+ * `hasExistingConfig` describes that resource only (this project is private),+ * never the workspace as a whole.+ */+export function usePaidFeatureAccess(+ wsId: string,+ feature: PaidFeature,+ { hasExistingConfig }: { hasExistingConfig: boolean },+): PaidFeatureAccess {+ const query = useQuery(workspaceFeaturesOptions(wsId));+ if (query.isPending) {+ return { state: null, isPending: true, isError: false, canAdd: false, canReduce: true };+ }+ if (query.isError) {+ return { state: null, isPending: false, isError: true, canAdd: true, canReduce: true };+ }+ const state = resolvePaidFeatureAccess(+ query.data?.features?.[feature] ?? "available",+ hasExistingConfig,+ );+ return { state, isPending: false, isError: false, canAdd: state === "available", canReduce: true };+}++/** The server refused to add to a paid feature the workspace's plan lacks. */+export function isFeatureLockedError(error: unknown): boolean {+ if (!(error instanceof ApiError) || error.status !== 403) return false;+ const body = error.body;+ return (+ typeof body === "object" &&+ body !== null &&+ (body as { code?: unknown }).code === FEATURE_LOCKED_CODE+ );+}++/**+ * A feature_locked refusal means this client's view of the plan was stale:+ * refetch it so the form switches to its read-only or upgrade state.+ */+export function refreshFeaturesOnLockedError(+ queryClient: QueryClient,+ wsId: string,+ error: unknown,+): void {+ if (isFeatureLockedError(error)) {+ void queryClient.invalidateQueries({ queryKey: workspaceFeatureKeys.all(wsId) });+ }+}diff --git a/packages/core/projects/access.ts b/packages/core/projects/access.tsindex cb5578566d..1912b07df1 100644--- a/packages/core/projects/access.ts+++ b/packages/core/projects/access.ts@@ -2,6 +2,7 @@ import { onlineManager, useMutation, useQuery, useQueryClient } from "@tanstack/import { api } from "../api";import { projectKeys, projectMembersOptions } from "./queries";import { issueKeys } from "../issues/queries";+import { refreshFeaturesOnLockedError } from "../billing/paid-features";import type { Project, ProjectVisibility } from "../types";// Mirrors the server (canManageProjectAccess in project_member.go). The caller@@ -76,6 +77,7 @@ export function useProjectAccessMutation(wsId: string, projectId: string) {await api.removeProjectMember(projectId, change.userId);}},+ onError: (err) => refreshFeaturesOnLockedError(qc, wsId, err),onSettled: async () => {await qc.invalidateQueries({ queryKey: projectKeys.all(wsId) });await qc.invalidateQueries({ queryKey: issueKeys.all(wsId) });diff --git a/packages/core/projects/mutations.ts b/packages/core/projects/mutations.tsindex cd7189b01f..d18d6810e2 100644--- a/packages/core/projects/mutations.ts+++ b/packages/core/projects/mutations.ts@@ -4,6 +4,7 @@ import { projectKeys } from "./queries";import { issueKeys } from "../issues/queries";import { autopilotKeys } from "../autopilots/queries";import { useWorkspaceId } from "../hooks";+import { refreshFeaturesOnLockedError } from "../billing/paid-features";import { useRecentContextStore } from "../chat/recent-context-store";import { clearIssueSurfaceViewState } from "../issues/stores/surface-view-store";import { issueScopeKey } from "../issues/surface/scope";@@ -14,6 +15,7 @@ export function useCreateProject() {const wsId = useWorkspaceId();return useMutation({mutationFn: (data: CreateProjectRequest) => api.createProject(data),+ onError: (err) => refreshFeaturesOnLockedError(qc, wsId, err),onSuccess: (newProject) => {qc.setQueryData<ListProjectsResponse>(projectKeys.list(wsId), (old) =>old && !old.projects.some((p) => p.id === newProject.id)@@ -45,9 +47,10 @@ export function useUpdateProject() {);return { prevList, prevDetail, id };},- onError: (_err, _vars, ctx) => {+ onError: (err, _vars, ctx) => {if (ctx?.prevList) qc.setQueryData(projectKeys.list(wsId), ctx.prevList);if (ctx?.prevDetail) qc.setQueryData(projectKeys.detail(wsId, ctx.id), ctx.prevDetail);+ refreshFeaturesOnLockedError(qc, wsId, err);},onSettled: (_data, _err, vars) => {qc.invalidateQueries({ queryKey: projectKeys.detail(wsId, vars.id) });diff --git a/packages/core/types/billing.ts b/packages/core/types/billing.tsindex c236eddae2..cef631d863 100644--- a/packages/core/types/billing.ts+++ b/packages/core/types/billing.ts@@ -332,3 +332,18 @@ export interface WorkspaceSubscriptionSeatReconcileResult {export interface CreateWorkspaceSubscriptionPortalResponse {url: string;}++/**+ * Paid features (MUL-9482). The server evaluates each feature for the+ * workspace: `available` means it can be used and extended, `locked` means+ * the plan does not include it, so existing configuration keeps working and+ * can be reduced, but nothing can be added. The server enforces on every+ * write; this is only for rendering.+ */+export type PaidFeature = "private_projects";++export type WorkspaceFeatureState = "available" | "locked";++export interface WorkspaceFeatures {+ features: Partial<Record<PaidFeature, WorkspaceFeatureState>>;+}diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 94cf0b2341..cd8c143b88 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -422,6 +422,9 @@ export type {PurchaseWorkspaceSeatsResponse,WorkspaceSubscriptionSeatReconcileResult,CreateWorkspaceSubscriptionPortalResponse,+ PaidFeature,+ WorkspaceFeatureState,+ WorkspaceFeatures,} from "./billing";export type { IssueWakeup, IssueWakeupInput, SystemWakeup, WorkspaceSystemWakeup, WakeupPreview, IssueWakeupSummaryRow, WakeupCondition, WakeupPausedReason, WakeupRun, PausedWakeup, WakeupSource } from "./issue-wakeup";diff --git a/packages/views/billing/index.ts b/packages/views/billing/index.tsindex 1b9f38ef12..17ae245206 100644--- a/packages/views/billing/index.ts+++ b/packages/views/billing/index.ts@@ -1 +1,2 @@export { BillingReturnPage } from "./billing-return-page";+export { PaidFeatureNotice, usePaidFeatureErrorMessage } from "./paid-feature-notice";diff --git a/packages/views/billing/paid-feature-notice.tsx b/packages/views/billing/paid-feature-notice.tsxnew file mode 100644index 0000000000..8c7c0687c7--- /dev/null+++ b/packages/views/billing/paid-feature-notice.tsx@@ -0,0 +1,50 @@+"use client";++import { useCallback } from "react";+import { Lock } from "@multica/ui/icons";+import { isFeatureLockedError, type PaidFeatureAccessState } from "@multica/core/billing";+import { useWorkspacePaths } from "@multica/core/paths";+import { AppLink } from "../navigation";+import { useT } from "../i18n";++/**+ * The one notice every paid feature shows when the workspace's plan does not+ * include it (MUL-9482): "read_only" where the resource already uses the+ * feature, "unavailable" where it would be turned on. Both link to Billing.+ */+export function PaidFeatureNotice({+ state,+ className,+}: {+ state: Exclude<PaidFeatureAccessState, "available">;+ className?: string;+}) {+ const { t } = useT("billing");+ const paths = useWorkspacePaths();+ return (+ <p className={`flex items-start gap-2 text-caption text-muted-foreground ${className ?? ""}`}>+ <Lock className="mt-0.5 size-4 shrink-0" aria-hidden="true" />+ <span>+ {state === "read_only"+ ? t(($) => $.paid_feature.read_only)+ : t(($) => $.paid_feature.unavailable)}{" "}+ <AppLink href={`${paths.settings()}?tab=billing`} className="font-medium text-foreground underline-offset-4 hover:underline">+ {t(($) => $.paid_feature.view_plans)}+ </AppLink>+ </span>+ </p>+ );+}++/**+ * The message for a failed write: the localized paid-feature copy for a+ * feature_locked refusal, otherwise the caller's fallback.+ */+export function usePaidFeatureErrorMessage() {+ const { t } = useT("billing");+ return useCallback(+ (error: unknown, fallback: string) =>+ isFeatureLockedError(error) ? t(($) => $.paid_feature.locked_error) : fallback,+ [t],+ );+}diff --git a/packages/views/locales/en/billing.json b/packages/views/locales/en/billing.jsonindex b674007029..d8e9cceed6 100644--- a/packages/views/locales/en/billing.json+++ b/packages/views/locales/en/billing.json@@ -186,5 +186,11 @@"workspace_missing_description": "You came back from Stripe, but this workspace is no longer available to you — it may have been removed, or your access changed. Open Billing in the workspace you expected to check the current state.","retry": "Try again","go_to_app": "Go to Multica"+ },+ "paid_feature": {+ "read_only": "Read-only. Upgrade to edit.",+ "unavailable": "Not included in this workspace's plan.",+ "view_plans": "View plans",+ "locked_error": "This isn't included in the workspace's plan. Existing settings keep working; upgrade to add more."}}diff --git a/packages/views/locales/es/billing.json b/packages/views/locales/es/billing.jsonindex 67a7abaf57..65f62fcc4a 100644--- a/packages/views/locales/es/billing.json+++ b/packages/views/locales/es/billing.json@@ -186,5 +186,11 @@"workspace_missing_description": "Has vuelto de Stripe, pero este espacio de trabajo ya no está disponible para ti: puede que se haya eliminado o que tu acceso haya cambiado. Abre Facturación en el espacio de trabajo que esperabas para comprobar el estado actual.","retry": "Reintentar","go_to_app": "Ir a Multica"+ },+ "paid_feature": {+ "read_only": "Solo lectura. Mejora el plan para editar.",+ "unavailable": "No está incluido en el plan de este espacio de trabajo.",+ "view_plans": "Ver planes",+ "locked_error": "No está incluido en el plan del espacio de trabajo. La configuración existente sigue funcionando; mejora el plan para añadir más."}}diff --git a/packages/views/locales/fr/billing.json b/packages/views/locales/fr/billing.jsonindex d67d057578..53c1dd04cf 100644--- a/packages/views/locales/fr/billing.json+++ b/packages/views/locales/fr/billing.json@@ -186,5 +186,11 @@"workspace_missing_description": "Vous revenez de Stripe, mais cet espace de travail ne vous est plus accessible — il a peut-être été supprimé, ou vos droits ont changé. Ouvrez Facturation dans l'espace de travail attendu pour vérifier l'état actuel.","retry": "Réessayer","go_to_app": "Aller sur Multica"+ },+ "paid_feature": {+ "read_only": "Lecture seule. Passez à un forfait supérieur pour modifier.",+ "unavailable": "Non inclus dans le forfait de cet espace de travail.",+ "view_plans": "Voir les forfaits",+ "locked_error": "Non inclus dans le forfait de l'espace de travail. Les réglages existants restent actifs ; changez de forfait pour en ajouter."}}diff --git a/packages/views/locales/ja/billing.json b/packages/views/locales/ja/billing.jsonindex 3b07f089ec..8e224a6929 100644--- a/packages/views/locales/ja/billing.json+++ b/packages/views/locales/ja/billing.json@@ -179,5 +179,11 @@"workspace_missing_description": "Stripe から戻りましたが、このワークスペースは利用できません。削除されたか、アクセス権が変更された可能性があります。対象のワークスペースの請求ページで現在の状態を確認してください。","retry": "再試行","go_to_app": "Multica を開く"+ },+ "paid_feature": {+ "read_only": "読み取り専用です。編集するにはアップグレードしてください。",+ "unavailable": "このワークスペースのプランには含まれていません。",+ "view_plans": "プランを見る",+ "locked_error": "このワークスペースのプランには含まれていません。既存の設定はそのまま有効です。追加するにはアップグレードしてください。"}}diff --git a/packages/views/locales/ko/billing.json b/packages/views/locales/ko/billing.jsonindex f3a3a0882e..6693b0000c 100644--- a/packages/views/locales/ko/billing.json+++ b/packages/views/locales/ko/billing.json@@ -179,5 +179,11 @@"workspace_missing_description": "Stripe에서 돌아왔지만 이 워크스페이스를 사용할 수 없습니다. 삭제되었거나 접근 권한이 변경되었을 수 있습니다. 원하는 워크스페이스의 결제 페이지에서 현재 상태를 확인해 주세요.","retry": "다시 시도","go_to_app": "Multica로 이동"+ },+ "paid_feature": {+ "read_only": "읽기 전용입니다. 편집하려면 업그레이드하세요.",+ "unavailable": "이 워크스페이스의 요금제에 포함되어 있지 않습니다.",+ "view_plans": "요금제 보기",+ "locked_error": "이 워크스페이스의 요금제에 포함되어 있지 않습니다. 기존 설정은 계속 적용되며, 추가하려면 업그레이드하세요."}}diff --git a/packages/views/locales/ru/billing.json b/packages/views/locales/ru/billing.jsonindex 6a31277255..b22cb2f2e5 100644--- a/packages/views/locales/ru/billing.json+++ b/packages/views/locales/ru/billing.json@@ -200,5 +200,11 @@"workspace_missing_description": "Вы вернулись из Stripe, но это рабочее пространство больше вам недоступно — возможно, оно было удалено или изменился ваш доступ. Откройте Биллинг в ожидаемом рабочем пространстве, чтобы проверить текущее состояние.","retry": "Повторить","go_to_app": "Перейти в Multica"+ },+ "paid_feature": {+ "read_only": "Только чтение. Чтобы редактировать, повысьте тариф.",+ "unavailable": "Не входит в тариф этого рабочего пространства.",+ "view_plans": "Посмотреть тарифы",+ "locked_error": "Не входит в тариф рабочего пространства. Существующие настройки продолжают работать; чтобы добавить новые, повысьте тариф."}}diff --git a/packages/views/locales/zh-Hans/billing.json b/packages/views/locales/zh-Hans/billing.jsonindex 9b284d8811..beda8f6170 100644--- a/packages/views/locales/zh-Hans/billing.json+++ b/packages/views/locales/zh-Hans/billing.json@@ -179,5 +179,11 @@"workspace_missing_description": "你已从 Stripe 返回,但该工作区对你已不可用——可能已被删除,或你的访问权限发生了变化。请到你预期的那个工作区的账单页确认当前状态。","retry": "重试","go_to_app": "前往 Multica"+ },+ "paid_feature": {+ "read_only": "只读,升级后可编辑",+ "unavailable": "当前工作区的套餐不包含此功能。",+ "view_plans": "查看套餐",+ "locked_error": "当前工作区的套餐不包含此功能。已有设置继续生效,升级后可以新增。"}}diff --git a/packages/views/locales/zh-Hant/billing.json b/packages/views/locales/zh-Hant/billing.jsonindex db9969b65b..d773949b50 100644--- a/packages/views/locales/zh-Hant/billing.json+++ b/packages/views/locales/zh-Hant/billing.json@@ -179,5 +179,11 @@"workspace_missing_description": "你已從 Stripe 返回,但該工作區對你已不可用——可能已被刪除,或你的訪問權限發生了變化。請到你預期的那個工作區的帳單頁確認當前狀態。","retry": "重試","go_to_app": "前往 Multica"+ },+ "paid_feature": {+ "read_only": "唯讀,升級後可編輯",+ "unavailable": "目前工作區的套餐不包含此功能。",+ "view_plans": "查看套餐",+ "locked_error": "目前工作區的套餐不包含此功能。既有設定繼續生效,升級後可以新增。"}}diff --git a/packages/views/modals/create-project.tsx b/packages/views/modals/create-project.tsxindex 96cf647b12..eb9a823b0d 100644--- a/packages/views/modals/create-project.tsx+++ b/packages/views/modals/create-project.tsx@@ -62,6 +62,7 @@ import {import { ProjectStartDatePicker } from "../projects/components/project-start-date-picker";import { ProjectDueDatePicker } from "../projects/components/project-due-date-picker";import { ProjectAccessDraftPicker } from "../projects/components/project-access";+import { usePaidFeatureErrorMessage } from "../billing";import { PillButton } from "../common/pill-button";import { WorkflowPill } from "../workflows/workflow-pill";import { githubShortLabel } from "../common/github-url";@@ -357,6 +358,7 @@ export function CreateProjectModal({const hasSource = sourceMode === "local" ? !!selectedLocalPath : selectedRepos.length > 0;const createProject = useCreateProject();+ const paidFeatureError = usePaidFeatureErrorMessage();// Every selected repo's branch, not just the one in the add field. A branch// edited on an already-selected row goes through setRepoRef and used to@@ -428,9 +430,12 @@ export function CreateProjectModal({router.push(wsPaths.projectDetail(project.id));} catch (err) {toast.error(- err instanceof Error && err.message- ? err.message- : t(($) => $.create_project.toast_failed),+ paidFeatureError(+ err,+ err instanceof Error && err.message+ ? err.message+ : t(($) => $.create_project.toast_failed),+ ),);} finally {setSubmitting(false);diff --git a/packages/views/projects/components/project-access.test.tsx b/packages/views/projects/components/project-access.test.tsxindex b515f94e90..a483eb5ea7 100644--- a/packages/views/projects/components/project-access.test.tsx+++ b/packages/views/projects/components/project-access.test.tsx@@ -2,9 +2,9 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest";import { screen, waitFor, within } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { setApiInstance } from "@multica/core/api";+import { ApiError, setApiInstance } from "@multica/core/api";import type { ApiClient } from "@multica/core/api/client";-import type { Project, MemberWithUser } from "@multica/core/types";+import type { Project, MemberWithUser, WorkspaceFeatureState } from "@multica/core/types";import { EMPTY_PROJECT } from "@multica/core/api/schemas";import { renderWithI18n } from "../../test/i18n";import { ProjectAccessControl, ProjectAccessDraftPicker } from "./project-access";@@ -14,6 +14,8 @@ const state = vi.hoisted(() => ({ viewer: "owner" }));vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws" }));vi.mock("@multica/core/auth", () => ({ useAuthStore: Object.assign((selector: (s: { user: { id: string } }) => unknown) => selector({ user: { id: state.viewer } }), { getState: () => ({ user: { id: state.viewer } }) }) }));vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => <span aria-hidden="true" /> }));+vi.mock("../../navigation", async (importOriginal) => ({ ...(await importOriginal<object>()), AppLink: ({ href, children, ...props }: React.ComponentProps<"a"> & { href: string }) => <a href={href} {...props}>{children}</a> }));+vi.mock("@multica/core/paths", async (importOriginal) => ({ ...(await importOriginal<object>()), useWorkspacePaths: () => ({ settings: () => "/acme/settings" }) }));vi.mock("@multica/core/workspace/hooks", () => ({ useActorName: () => ({ getActorName: () => "Lead" }) }));const members: MemberWithUser[] = [@@ -28,19 +30,27 @@ let qc: QueryClient;let ids: string[];// Who the server names as the project's access manager.let managerId: string | null;-let api: { listMembers: ReturnType<typeof vi.fn>; listAgents: ReturnType<typeof vi.fn>; getProjectMembers: ReturnType<typeof vi.fn>; addProjectMembers: ReturnType<typeof vi.fn>; removeProjectMember: ReturnType<typeof vi.fn>; updateProject: ReturnType<typeof vi.fn> };+// The workspace's private_projects state as the server reports it.+let privateProjects: WorkspaceFeatureState;+let api: { getWorkspaceFeatures: ReturnType<typeof vi.fn>; listMembers: ReturnType<typeof vi.fn>; listAgents: ReturnType<typeof vi.fn>; getProjectMembers: ReturnType<typeof vi.fn>; addProjectMembers: ReturnType<typeof vi.fn>; removeProjectMember: ReturnType<typeof vi.fn>; updateProject: ReturnType<typeof vi.fn> };function renderControl(value: Project = project) {return renderWithI18n(<QueryClientProvider client={qc}><ProjectAccessControl project={value} /></QueryClientProvider>);}+function renderDraft(props: Omit<Parameters<typeof ProjectAccessDraftPicker>[0], "members">) {+ return renderWithI18n(<QueryClientProvider client={qc}><ProjectAccessDraftPicker members={members} {...props} /></QueryClientProvider>);+}+beforeEach(() => {state.viewer = "owner";qc = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });ids = ["owner", "lead", "member"];managerId = "lead";+ privateProjects = "available";const response = () => ({ members: members.filter((m) => ids.includes(m.user_id)).map((m) => ({ ...m, project_id: "p1" })), total: ids.length, manager_id: managerId });api = {+ getWorkspaceFeatures: vi.fn().mockImplementation(async () => ({ features: { private_projects: privateProjects } })),listMembers: vi.fn().mockResolvedValue(members),listAgents: vi.fn().mockResolvedValue([]),getProjectMembers: vi.fn().mockImplementation(async () => response()),@@ -246,13 +256,13 @@ it("names no lead for a project that turns private without one, and keeps whoeveit("shows who will manage a new private project: a person named lead, otherwise its creator", async () => {const user = userEvent.setup();- const { unmount } = renderWithI18n(<ProjectAccessDraftPicker visibility="private" memberIds={["member"]} leadId="lead" members={members} onChange={vi.fn()} />);+ const { unmount } = renderDraft({ visibility: "private", memberIds: ["member"], leadId: "lead", onChange: vi.fn() });await user.click(screen.getByRole("button", { name: "Access" }));let row = (await screen.findByText("lead@test")).parentElement!.parentElement!;expect(within(row).getByText("Lead · Manages access")).toBeVisible();unmount();- renderWithI18n(<ProjectAccessDraftPicker visibility="private" memberIds={["member"]} members={members} onChange={vi.fn()} />);+ renderDraft({ visibility: "private", memberIds: ["member"], onChange: vi.fn() });await user.click(screen.getByRole("button", { name: "Access" }));row = (await screen.findByText("owner@test")).parentElement!.parentElement!;expect(within(row).getByText("Manages access")).toBeVisible();@@ -262,10 +272,70 @@ it("shows who will manage a new private project: a person named lead, otherwiseit("keeps new-project access in the draft until the project is created", async () => {const changed = vi.fn();const user = userEvent.setup();- renderWithI18n(<ProjectAccessDraftPicker visibility="workspace" memberIds={[]} leadId="lead" members={members} onChange={changed} />);+ renderDraft({ visibility: "workspace", memberIds: [], leadId: "lead", onChange: changed });await user.click(screen.getByRole("button", { name: "Access" }));await user.click(screen.getByRole("radio", { name: "Project members only" }));expect(changed).toHaveBeenCalledWith("private", ["owner", "lead"]);expect(api.updateProject).not.toHaveBeenCalled();expect(api.addProjectMembers).not.toHaveBeenCalled();});++// MUL-9482: a workspace whose plan lacks private projects keeps every existing+// private project working; only adding to one is withheld.+it("keeps an existing private project read-only to additions when the plan lacks the feature", async () => {+ privateProjects = "locked";+ const user = userEvent.setup();+ renderControl();+ await user.click(screen.getByRole("button", { name: "Access" }));+ await screen.findByText("member@test");+ expect(await screen.findByText(/Read-only\. Upgrade to edit\./)).toBeVisible();+ expect(screen.getByRole("link", { name: "View plans" })).toBeVisible();+ expect(screen.queryByRole("button", { name: "Add workspace member" })).not.toBeInTheDocument();+ // Reductions stay available: removing someone and making it public.+ await user.click(screen.getByRole("button", { name: "Remove Member" }));+ await waitFor(() => expect(api.removeProjectMember).toHaveBeenCalledWith("p1", "member"));+ expect(screen.getByRole("radio", { name: "Entire workspace" })).toBeEnabled();+});++it("offers no way to make a workspace project private when the plan lacks the feature", async () => {+ privateProjects = "locked";+ const user = userEvent.setup();+ renderControl({ ...project, visibility: "workspace" });+ await user.click(screen.getByRole("button", { name: "Access" }));+ expect(await screen.findByText(/Not included in this workspace's plan\./)).toBeVisible();+ expect(screen.getByRole("radio", { name: "Project members only" })).toBeDisabled();+ expect(screen.queryByText(/Read-only/)).not.toBeInTheDocument();+});++it("shows no plan notice while the feature is available", async () => {+ const user = userEvent.setup();+ renderControl();+ await user.click(screen.getByRole("button", { name: "Access" }));+ await screen.findByRole("button", { name: "Add workspace member" });+ expect(screen.queryByText(/Read-only/)).not.toBeInTheDocument();+ expect(screen.queryByRole("link", { name: "View plans" })).not.toBeInTheDocument();+});++it("explains a plan refusal from the server and switches the dialog to read-only", async () => {+ api.addProjectMembers.mockImplementation(async () => {+ privateProjects = "locked";+ throw new ApiError("forbidden", 403, "Forbidden", { code: "feature_locked", feature: "private_projects" });+ });+ const user = userEvent.setup();+ renderControl();+ await user.click(screen.getByRole("button", { name: "Access" }));+ await user.click(await screen.findByRole("button", { name: "Add workspace member" }));+ await user.click(await screen.findByText("outside@test"));+ expect(await screen.findByText(/isn't included in the workspace's plan/)).toBeVisible();+ expect(await screen.findByText(/Read-only\. Upgrade to edit\./)).toBeVisible();+ expect(screen.queryByRole("button", { name: "Add workspace member" })).not.toBeInTheDocument();+});++it("does not offer a new private project when the plan lacks the feature", async () => {+ privateProjects = "locked";+ const user = userEvent.setup();+ renderDraft({ visibility: "workspace", memberIds: [], onChange: vi.fn() });+ await user.click(screen.getByRole("button", { name: "Access" }));+ expect(await screen.findByText(/Not included in this workspace's plan\./)).toBeVisible();+ expect(screen.getByRole("radio", { name: "Project members only" })).toBeDisabled();+});diff --git a/packages/views/projects/components/project-access.tsx b/packages/views/projects/components/project-access.tsxindex 8654bf06a2..cb3a04de2c 100644--- a/packages/views/projects/components/project-access.tsx+++ b/packages/views/projects/components/project-access.tsx@@ -1,6 +1,6 @@"use client";-import { useId, useState } from "react";+import { useId, useState, type ReactNode } from "react";import { useQuery } from "@tanstack/react-query";import { Bot, Globe, Lock, Shield, UserPlus, X } from "@multica/ui/icons";import type { MemberWithUser, Project, ProjectVisibility } from "@multica/core/types";@@ -9,6 +9,7 @@ import { useWorkspaceId } from "@multica/core/hooks";import { memberListOptions } from "@multica/core/workspace/queries";import { projectMembersOptions } from "@multica/core/projects/queries";import { canManageProjectAccess, useProjectAccessMutation } from "@multica/core/projects/access";+import { usePaidFeatureAccess } from "@multica/core/billing";import { Button } from "@multica/ui/components/ui/button";import { Spinner } from "@multica/ui/components/ui/spinner";import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@multica/ui/components/ui/dialog";@@ -17,11 +18,12 @@ import { Command, CommandEmpty, CommandInput, CommandItem, CommandList } from "@import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@multica/ui/components/ui/alert-dialog";import { ActorAvatar } from "../../common/actor-avatar";import { PillButton } from "../../common/pill-button";+import { PaidFeatureNotice, usePaidFeatureErrorMessage } from "../../billing";import { useT } from "../../i18n";const EMPTY_IDS: string[] = [];-function AccessFields({ visibility, onVisibilityChange, members, selected, leadId, managerId, userId, disabled, canChangeScope, canUsePrivate, canAdd, canRemove, onAdd, onRemove }: {+function AccessFields({ visibility, onVisibilityChange, members, selected, leadId, managerId, userId, disabled, canChangeScope, canUsePrivate, canAdd, canRemove, onAdd, onRemove, notice }: {visibility: ProjectVisibility;onVisibilityChange: (value: ProjectVisibility) => void;members: MemberWithUser[];@@ -37,6 +39,8 @@ function AccessFields({ visibility, onVisibilityChange, members, selected, leadIcanRemove: (id: string) => boolean;onAdd: (id: string) => Promise<boolean | void> | void;onRemove: (id: string) => Promise<void> | void;+ // Shown under the visibility choice, e.g. the paid-feature notice.+ notice?: ReactNode;}) {const { t } = useT("projects");const groupId = useId();@@ -59,6 +63,7 @@ function AccessFields({ visibility, onVisibilityChange, members, selected, leadI);})}</fieldset>+ {notice}{visibility === "private" ? (<div className="space-y-3"><p className="text-caption font-medium">{t(($) => $.access.members_count, { count: recipients.length })}</p>@@ -147,9 +152,14 @@ function ProjectAccessEditor({ project, onClose, changeAccess }: { project: Projconst [draftIds, setDraftIds] = useState<string[] | null>(null);const [error, setError] = useState("");const [confirmPublic, setConfirmPublic] = useState(false);+ const paidFeatureError = usePaidFeatureErrorMessage();const members = workspaceMembers.data ?? [];const role = members.find((member) => member.user_id === userId)?.role;const isPrivate = project.visibility === "private";+ // Without the private_projects feature an existing private project keeps+ // its members and access: people can still be removed and the project made+ // public, but nobody can be added and a public one cannot be made private.+ const privateProjects = usePaidFeatureAccess(wsId, "private_projects", { hasExistingConfig: isPrivate });const projectLeadId = project.lead_type === "member" ? project.lead_id : null;// A person who leads the project joins it when it turns private, unless// they have left the workspace: the draft list cannot name them then.@@ -165,7 +175,7 @@ function ProjectAccessEditor({ project, onClose, changeAccess }: { project: Projconst run = async (change: Parameters<typeof changeAccess.mutateAsync>[0]) => {setError("");try { await changeAccess.mutateAsync(change); return true; }- catch (err) { setError(err instanceof Error ? err.message : t(($) => $.access.failed)); return false; }+ catch (err) { setError(paidFeatureError(err, err instanceof Error ? err.message : t(($) => $.access.failed))); return false; }};const saveScope = async () => {if (await run({ type: "visibility", visibility, memberIds: selected })) { setConfirmPublic(false); onClose(); }@@ -177,8 +187,10 @@ function ProjectAccessEditor({ project, onClose, changeAccess }: { project: Proj<div role="alert" className="space-y-2 text-body"><p>{t(($) => $.access.load_failed)}</p><Button variant="outline" size="sm" onClick={() => { void workspaceMembers.refetch(); void projectMembers.refetch(); }}>{t(($) => $.access.retry)}</Button></div>) : (<AccessFields visibility={visibility} onVisibilityChange={setVisibility} members={members} selected={selected} userId={userId} leadId={leadId} managerId={managerId}- disabled={pending} canChangeScope={canManage} canUsePrivate- canAdd={canManage}+ disabled={pending} canChangeScope={canManage} canUsePrivate={isPrivate || privateProjects.canAdd}+ canAdd={canManage && privateProjects.canAdd}+ notice={privateProjects.state === "read_only" || privateProjects.state === "unavailable"+ ? <PaidFeatureNotice state={privateProjects.state} /> : null}canRemove={(id) => canManage && id !== leadId && (isPrivate || id !== userId)}onAdd={async (id) => { if (isPrivate) return run({ type: "add", userId: id }); setDraftIds([...selected, id]); return true; }}onRemove={async (id) => {@@ -214,7 +226,11 @@ export function ProjectAccessDraftPicker({ visibility, memberIds, leadId, memberonChange: (visibility: ProjectVisibility, ids: string[]) => void;}) {const { t } = useT("projects");+ const wsId = useWorkspaceId();const userId = useAuthStore((s) => s.user?.id);+ // A project being created has no configuration yet, so a locked feature is+ // unavailable here rather than read-only.+ const privateProjects = usePaidFeatureAccess(wsId, "private_projects", { hasExistingConfig: false });const fixed = [userId, leadId].filter((id): id is string => !!id);const selected = Array.from(new Set([...memberIds, ...fixed]));// A person named as lead manages the new project's access; with an agent@@ -231,7 +247,8 @@ export function ProjectAccessDraftPicker({ visibility, memberIds, leadId, member} /><PopoverContent side="top" align="end" className="max-h-[70dvh] w-96 max-w-[calc(100vw-2rem)] overflow-y-auto"><AccessFields visibility={visibility} onVisibilityChange={(value) => onChange(value, selected)} members={members} selected={selected} leadId={leadId} managerId={managerId} userId={userId}- disabled={false} canChangeScope canUsePrivate canAdd+ disabled={false} canChangeScope canUsePrivate={privateProjects.canAdd} canAdd={privateProjects.canAdd}+ notice={privateProjects.state === "unavailable" ? <PaidFeatureNotice state="unavailable" /> : null}canRemove={(id) => !fixed.includes(id)}onAdd={(id) => onChange(visibility, [...selected, id])}onRemove={(id) => onChange(visibility, selected.filter((value) => value !== id))} />diff --git a/packages/views/projects/components/project-detail.tsx b/packages/views/projects/components/project-detail.tsxindex d9d2f49d4c..e4a130aa05 100644--- a/packages/views/projects/components/project-detail.tsx+++ b/packages/views/projects/components/project-detail.tsx@@ -8,6 +8,7 @@ import { useQuery } from "@tanstack/react-query";import { cn } from "@multica/ui/lib/utils";import { copyText, copyTextAndHtml } from "@multica/ui/lib/clipboard";import { toast } from "sonner";+import { isFeatureLockedError } from "@multica/core/billing";import type { Project, ProjectStatus, ProjectPriority } from "@multica/core/types";import { useAuthStore } from "@multica/core/auth";import { canDeleteProject } from "@multica/core/projects/deletion-permissions";@@ -32,6 +33,7 @@ import { PriorityIcon } from "../../issues/components/priority-icon";import { ProjectResourcesSection } from "./project-resources-section";import { ProjectStartDatePicker } from "./project-start-date-picker";import { ProjectDueDatePicker } from "./project-due-date-picker";+import { usePaidFeatureErrorMessage } from "../../billing";import { ProjectAccessControl } from "./project-access";import { ProjectLeadPicker } from "./project-lead-picker";import { ProjectWorkflowControl } from "../../workflows/project-workflow-row";@@ -166,6 +168,7 @@ export function ProjectDetail({ projectId }: { projectId: string }) {const { data: agents = [] } = useQuery(agentListOptions(wsId));const { getActorName } = useActorName();const updateProject = useUpdateProject();+ const paidFeatureError = usePaidFeatureErrorMessage();const deleting = deleteProject.isPending;const { data: pinnedItems = [] } = useQuery({...pinListOptions(wsId, userId ?? ""),@@ -259,9 +262,13 @@ export function ProjectDetail({ projectId }: { projectId: string }) {const handleUpdateField = useCallback((data: Parameters<typeof updateProject.mutate>[0] extends { id: string } & infer R ? R : never) => {if (!project) return;- updateProject.mutate({ id: project.id, ...data });+ // Field edits roll back silently; a plan refusal (a lead who would join+ // a private project) needs saying why.+ updateProject.mutateAsync({ id: project.id, ...data }).catch((err: unknown) => {+ if (isFeatureLockedError(err)) toast.error(paidFeatureError(err, ""));+ });},- [project, updateProject],+ [project, updateProject, paidFeatureError],);const handleStatusChange = useCallback(diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 664075651b..a0990b51a4 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -145,6 +145,7 @@ var concurrentIndexCleanups = map[string]string{"678_chat_wakeup_requester_idx": "idx_chat_wakeup_requester","680_entitlement_limit_overage_scope_idx": "uq_entitlement_limit_overage_scope","682_project_folder_name_idx": "uq_project_folder_workspace_name",+ "684_entitlement_feature_attempt_scope_idx": "uq_entitlement_feature_attempt_scope","671_weixin_account_state_unique_index": "weixin_account_state_pkey","669_weixin_login_session_unique_index": "weixin_login_session_pkey","666_weixin_login_expiry_idx": "weixin_login_expiry_idx",diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 450f119956..ce322d6b31 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -480,6 +480,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busopts.BusinessMetrics.RecordEntitlementConfigError()} else if entitlementClient.Enabled() {h.Entitlements = entitlementClient+ h.Features = entitlementClienth.AutopilotService.Entitlements = entitlementClienth.AutopilotService.QuotaMetrics = opts.BusinessMetrics}@@ -1834,6 +1835,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Get("/", h.GetWorkspace)r.Put("/pin", h.SetWorkspacePinned)r.Get("/members", h.ListMembersWithUser)+ // Paid-feature states for read-only and upgrade UI; the+ // server enforces on every write regardless.+ r.Get("/features", h.GetWorkspaceFeatures)r.Post("/leave", h.LeaveWorkspace)r.Get("/invitations", h.ListWorkspaceInvitations)// Listing GitHub installations is member-visible so thediff --git a/server/internal/entitlement/README.md b/server/internal/entitlement/README.mdindex 870bda852e..dcb14878b4 100644--- a/server/internal/entitlement/README.md+++ b/server/internal/entitlement/README.md@@ -17,7 +17,7 @@ The client reads:- `schema_version`: only version 1 is accepted.- `policy_revision`: the effective-instruction generation, currently fixed at- `3` by Cloud and not deployment configuration. Cloud advances it when the+ `4` by Cloud and not deployment configuration. Cloud advances it when themeaning or set of actionable instructions changes, including additiveinstructions; `schema_version` changes only for incompatible wire parsing.- `subscription_version`: the workspace's monotonic subscription revision. A@@ -39,6 +39,12 @@ The client reads:workspace notice for the first rejected execution in the Cloud-defined quotaperiod. A malformed notification policy is ignored without invalidating anotherwise valid enforcement gate.+- `features`: paid-feature restrictions, one `{"action": ...}` per feature+ (revision 4). See [Paid features](#paid-features). Each feature is parsed on+ its own, after the rest of the policy: a missing, unknown, or malformed+ feature (including `features` of the wrong JSON type) falls back to `off`+ for that feature only, with reason `feature_missing` or `feature_invalid`,+ and never invalidates the gates.No deployment order is required for the optional notification policy. Theconsumer treats a missing policy as notices-disabled while continuing to@@ -48,6 +54,10 @@ Deploy this consumer before Cloud policy revision 3, which is the first to send`observe`. A consumer released before revision 3 rejects `observe` as anunknown action and fails the whole policy open to `off`.+Revision 4 (`features`) is safe in either order: an older consumer ignores+`features`, and this consumer treats a policy without it as every feature+`off`.+Responses tolerate unknown JSON fields and gates for additive compatibility.Unknown schema/action, malformed fields, a missing `autopilot_runs` gate, HTTPfailures, and timeouts fail open.@@ -110,3 +120,53 @@ structured localization; in-app quota views localize from `details`.Future consumers should depend on the small `Provider` interface. Tests can use`server/internal/entitlement/entitlementtest.Stub` without Cloud.++## Paid features++A paid feature is restricted for a workspace whose plan does not include it.+Cloud decides which workspaces that is and sends one action per feature; this+consumer never sees plan names. `FeatureProvider` is the only interface+callers use, so a self-hosted license provider can replace the Cloud client+without changing them. A nil provider (no `MULTICA_CLOUD_URL`) leaves every+feature usable.++The rule is the same for every feature:++| Write | `off` | `observe` | `enforce` |+| --- | --- | --- | --- |+| Add to the configuration (create, add a person, widen) | allowed | allowed, recorded | rejected `403 feature_locked`, recorded |+| Reduce or remove it (remove a person, make public, delete) | allowed | allowed | allowed |+| Edit without changing it (rename, same-value write-back) | allowed | allowed | allowed |++Reads never consult a feature. Existing configuration keeps working exactly as+configured, including the access control it defines: a private project stays+visible only to its members after a downgrade. Each feature classifies its own+writes; the handler entry point is `requireFeatureAddition`+(`server/internal/handler/paid_feature.go`), called after the ordinary+permission checks, so a caller refused by those gets the ordinary error.++| Feature | Restricted additions | Always allowed |+| --- | --- | --- |+| `private_projects` | create a private project; make a project private; add someone who is not a member yet, directly or by making them the lead | remove members; make it workspace-visible; delete or archive; set the lead to an existing member, an agent or nobody; other fields; the owner's recovery join |++A stale cached `enforce` is downgraded to `observe` with reason `stale` and+`Downgraded` set, then to `off`, exactly like gates, so a Cloud outage admits additions rather than+blocking them. Cloud failure before any policy was cached is `off`.++Attempts are aggregated per workspace, feature, and UTC day in+`entitlement_feature_attempt` (`service.EntitlementFeatureAttempts`):+`observed_count` (admitted under a configured observe), `degraded_count`+(admitted only because a stale enforce was downgraded), and `enforced_count`+(rejected), with the latest operation, action, reason, policy and subscription+revisions, and first/last attempt times. Admitted attempts are recorded after+the write commits, rejections after authorization; recording is best-effort,+bounded by its own one-second timeout so a contended row cannot hold the+response, and never changes the result. A configured `observe` served from a+stale cache still counts as observed; only a downgraded `enforce` counts as+degraded. Attempts measure demand, not existing+configuration: count existing private projects from the product tables.++Clients read `GET /api/workspaces/{id}/features`, which returns only+`available` (off or observe) or `locked` (enforce) per feature, and render+read-only and upgrade states from it. The server enforces on every write+regardless.diff --git a/server/internal/entitlement/cache.go b/server/internal/entitlement/cache.goindex f7ed8fc6ab..027b45c574 100644--- a/server/internal/entitlement/cache.go+++ b/server/internal/entitlement/cache.go@@ -16,6 +16,14 @@ type policySnapshot struct {subscriptionVersion int64cloudValidUntil time.Timegates map[GateName]Gate+ features map[FeatureName]featureEntry+}++// featureEntry is one normalized paid feature. A feature Cloud did not send,+// or sent malformed, is stored as off with the reason it fell back.+type featureEntry struct {+ action Action+ reason Reason}type cacheEntry struct {diff --git a/server/internal/entitlement/client.go b/server/internal/entitlement/client.goindex cbeffdd07c..94ad2e12e9 100644--- a/server/internal/entitlement/client.go+++ b/server/internal/entitlement/client.go@@ -54,7 +54,10 @@ type Client struct {refreshes singleflight.Group}-var _ Provider = (*Client)(nil)+var (+ _ Provider = (*Client)(nil)+ _ FeatureProvider = (*Client)(nil)+)func New(cfg Config) (*Client, error) {if strings.TrimSpace(cfg.BaseURL) == "" {@@ -104,19 +107,48 @@ func (c *Client) Gate(ctx context.Context, workspaceID uuid.UUID, name GateName)if !name.valid() {return c.recordDecision(name, offDecision(ReasonUnknownGate))}+ entry, reason, stale, ok := c.policy(ctx, workspaceID)+ if !ok {+ return c.recordDecision(name, offDecision(reason))+ }+ return c.recordDecision(name, decisionFromEntry(entry, name, reason, stale))+}++// Feature resolves one paid feature from the same cached policy as Gate, so+// reading both costs at most one Cloud request per workspace.+func (c *Client) Feature(ctx context.Context, workspaceID uuid.UUID, name FeatureName) FeatureDecision {+ if !c.Enabled() {+ return c.recordFeatureDecision(name, FeatureDecision{Action: ActionOff, Reason: ReasonDisabled})+ }+ if workspaceID == uuid.Nil {+ return c.recordFeatureDecision(name, FeatureDecision{Action: ActionOff, Reason: ReasonInvalidWorkspace})+ }+ if !name.Valid() {+ return c.recordFeatureDecision(name, FeatureDecision{Action: ActionOff, Reason: ReasonUnknownGate})+ }+ entry, reason, stale, ok := c.policy(ctx, workspaceID)+ if !ok {+ return c.recordFeatureDecision(name, FeatureDecision{Action: ActionOff, Reason: reason})+ }+ return c.recordFeatureDecision(name, featureDecisionFromEntry(entry, name, reason, stale))+}+// policy returns the workspace's usable cached or refreshed policy. ok=false+// means there is none and reason says why every gate and feature is off.+// stale=true means the policy may no longer enforce.+func (c *Client) policy(ctx context.Context, workspaceID uuid.UUID) (entry cacheEntry, reason Reason, stale, ok bool) {now := c.now()cached, cachedOK := c.cache.get(workspaceID)if cachedOK && cached.hasPolicy && now.Before(cached.freshUntil) {c.recordCache("hit")- return c.recordDecision(name, decisionFromEntry(cached, name, ReasonCacheFresh, false))+ return cached, ReasonCacheFresh, false, true}if cachedOK && now.Before(cached.retryAfter) {c.recordCache("retry_suppressed")if cached.hasPolicy && now.Before(cached.staleUntil) {- return c.recordDecision(name, decisionFromEntry(cached, name, ReasonStale, true))+ return cached, ReasonStale, true, true}- return c.recordDecision(name, offDecision(ReasonUnavailable))+ return cacheEntry{}, ReasonUnavailable, false, false}if cachedOK && cached.hasPolicy {c.recordCache("expired")@@ -124,13 +156,12 @@ func (c *Client) Gate(ctx context.Context, workspaceID uuid.UUID, name GateName)c.recordCache("miss")}- entry, refreshed, err := c.refresh(ctx, workspaceID)+ refreshedEntry, refreshed, err := c.refresh(ctx, workspaceID)if err == nil {- reason := ReasonRefreshedif !refreshed {- reason = ReasonCacheFresh+ return refreshedEntry, ReasonCacheFresh, false, true}- return c.recordDecision(name, decisionFromEntry(entry, name, reason, false))+ return refreshedEntry, ReasonRefreshed, false, true}// A stale policy is safe only after enforcement is downgraded to observe.@@ -138,16 +169,16 @@ func (c *Client) Gate(ctx context.Context, workspaceID uuid.UUID, name GateName)// call was waiting in singleflight.now = c.now()if cached, ok := c.cache.get(workspaceID); ok && cached.hasPolicy && now.Before(cached.staleUntil) {- return c.recordDecision(name, decisionFromEntry(cached, name, ReasonStale, true))+ return cached, ReasonStale, true, true}- reason := ReasonUnavailable+ reason = ReasonUnavailableif errors.Is(err, ErrInvalidPolicy) {reason = ReasonInvalidPolicy}if errors.Is(err, errVersionRegression) {reason = ReasonVersionRegression}- return c.recordDecision(name, offDecision(reason))+ return cacheEntry{}, reason, false, false}type refreshResult struct {@@ -216,6 +247,10 @@ type wirePolicy struct {ValidUntil time.Time `json:"valid_until"`ValidForSeconds int64 `json:"valid_for_seconds"`Gates map[string]wireGate `json:"gates"`+ // Features stays raw so one malformed feature, or a features value of the+ // wrong JSON type, cannot fail the decode of the whole policy and with it+ // the metered gates. normalizeFeatures parses it entry by entry.+ Features json.RawMessage `json:"features"`}type wireGate struct {@@ -299,6 +334,7 @@ func normalizePolicy(wire wirePolicy) (fetchedPolicy, error) {subscriptionVersion: wire.SubscriptionVersion,cloudValidUntil: wire.ValidUntil,gates: gates,+ features: normalizeFeatures(wire.Features),},validForSeconds: wire.ValidForSeconds,}, nil@@ -343,6 +379,49 @@ func normalizeGate(name GateName, wire wireGate) (Gate, error) {return gate, nil}+// normalizeFeatures reads every known paid feature independently. A missing,+// unknown or malformed feature falls back to off for that feature alone; it+// never invalidates the policy, so the metered gates keep their instructions.+// Features this consumer does not know are ignored.+func normalizeFeatures(raw json.RawMessage) map[FeatureName]featureEntry {+ out := make(map[FeatureName]featureEntry, len(Features()))+ var entries map[string]json.RawMessage+ objectOK := len(raw) > 0 && json.Unmarshal(raw, &entries) == nil && entries != nil+ for _, name := range Features() {+ if !objectOK {+ reason := ReasonFeatureMissing+ if len(raw) > 0 && string(raw) != "null" {+ reason = ReasonFeatureInvalid+ }+ out[name] = featureEntry{action: ActionOff, reason: reason}+ continue+ }+ entry, ok := entries[string(name)]+ if !ok {+ out[name] = featureEntry{action: ActionOff, reason: ReasonFeatureMissing}+ continue+ }+ out[name] = normalizeFeature(entry)+ }+ return out+}++func normalizeFeature(raw json.RawMessage) featureEntry {+ var wire struct {+ Action json.RawMessage `json:"action"`+ }+ var action string+ if json.Unmarshal(raw, &wire) != nil || json.Unmarshal(wire.Action, &action) != nil {+ return featureEntry{action: ActionOff, reason: ReasonFeatureInvalid}+ }+ switch Action(action) {+ case ActionOff, ActionObserve, ActionEnforce:+ return featureEntry{action: Action(action)}+ default:+ return featureEntry{action: ActionOff, reason: ReasonFeatureInvalid}+ }+}+// Notification instructions are additive presentation policy. A malformed// notification object must never invalidate the enforcement gate and fail open// the underlying quota, so it is dropped independently.@@ -369,6 +448,29 @@ func decisionFromEntry(entry cacheEntry, name GateName, reason Reason, stale boo}}+func featureDecisionFromEntry(entry cacheEntry, name FeatureName, reason Reason, stale bool) FeatureDecision {+ feature, ok := entry.policy.features[name]+ if !ok {+ feature = featureEntry{action: ActionOff, reason: ReasonFeatureMissing}+ }+ if feature.reason != "" {+ reason = feature.reason+ }+ action := feature.action+ downgraded := stale && action == ActionEnforce+ if downgraded {+ action = ActionObserve+ }+ return FeatureDecision{+ Action: action,+ Reason: reason,+ Downgraded: downgraded,+ PolicyRevision: entry.policy.policyRevision,+ SubscriptionVersion: entry.policy.subscriptionVersion,+ CloudValidUntil: entry.policy.cloudValidUntil,+ }+}+type fetchError struct {outcome string}@@ -413,6 +515,19 @@ func (c *Client) recordRefresh(outcome string, duration time.Duration) {}}+// Feature decisions share the decision metric under a "feature:" prefix; the+// label set stays bounded by the known feature list.+func (c *Client) recordFeatureDecision(name FeatureName, decision FeatureDecision) FeatureDecision {+ if c != nil && c.observer != nil {+ label := "feature:unknown"+ if name.Valid() {+ label = "feature:" + string(name)+ }+ c.observer.RecordEntitlementDecision(label, string(decision.Action), string(decision.Reason))+ }+ return decision+}+func (c *Client) recordDecision(name GateName, decision Decision) Decision {if c != nil && c.observer != nil {gate := "unknown"diff --git a/server/internal/entitlement/entitlementtest/stub.go b/server/internal/entitlement/entitlementtest/stub.goindex ea9021f02a..eb102e7b46 100644--- a/server/internal/entitlement/entitlementtest/stub.go+++ b/server/internal/entitlement/entitlementtest/stub.go@@ -18,13 +18,43 @@ type Call struct {type Stub struct {mu sync.RWMutexdecisions map[uuid.UUID]map[entitlement.GateName]entitlement.Decision+ features map[uuid.UUID]map[entitlement.FeatureName]entitlement.FeatureDecisioncalls []Call}-var _ entitlement.Provider = (*Stub)(nil)+var (+ _ entitlement.Provider = (*Stub)(nil)+ _ entitlement.FeatureProvider = (*Stub)(nil)+)func New() *Stub {- return &Stub{decisions: make(map[uuid.UUID]map[entitlement.GateName]entitlement.Decision)}+ return &Stub{+ decisions: make(map[uuid.UUID]map[entitlement.GateName]entitlement.Decision),+ features: make(map[uuid.UUID]map[entitlement.FeatureName]entitlement.FeatureDecision),+ }+}++// SetFeature fixes one workspace's paid-feature decision. The Reason given is+// kept, so tests can tell a configured observe from a stale downgrade.+func (s *Stub) SetFeature(workspaceID uuid.UUID, name entitlement.FeatureName, decision entitlement.FeatureDecision) {+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.features[workspaceID] == nil {+ s.features[workspaceID] = make(map[entitlement.FeatureName]entitlement.FeatureDecision)+ }+ if decision.Reason == "" {+ decision.Reason = entitlement.ReasonStub+ }+ s.features[workspaceID][name] = decision+}++func (s *Stub) Feature(_ context.Context, workspaceID uuid.UUID, name entitlement.FeatureName) entitlement.FeatureDecision {+ s.mu.RLock()+ defer s.mu.RUnlock()+ if decision, ok := s.features[workspaceID][name]; ok {+ return decision+ }+ return entitlement.FeatureDecision{Action: entitlement.ActionOff, Reason: entitlement.ReasonStub}}func (s *Stub) Set(workspaceID uuid.UUID, name entitlement.GateName, decision entitlement.Decision) {diff --git a/server/internal/entitlement/feature_test.go b/server/internal/entitlement/feature_test.gonew file mode 100644index 0000000000..c3d2f612c9--- /dev/null+++ b/server/internal/entitlement/feature_test.go@@ -0,0 +1,217 @@+package entitlement++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "sync/atomic"+ "testing"+ "time"++ "github.com/google/uuid"+)++func featurePolicyHandler(t *testing.T, features string) http.HandlerFunc {+ return func(w http.ResponseWriter, _ *http.Request) {+ policy := samplePolicy(4, 2, 60, ActionEnforce)+ if features != "" {+ policy.Features = json.RawMessage(features)+ }+ writePolicy(t, w, policy)+ }+}++func TestDisabledClientLeavesFeaturesUsableWithoutIO(t *testing.T) {+ var calls atomic.Int64+ client, err := New(Config{HTTPClient: &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {+ calls.Add(1)+ return nil, errors.New("must not be called")+ })}})+ if err != nil {+ t.Fatalf("New: %v", err)+ }+ decision := client.Feature(context.Background(), uuid.New(), FeaturePrivateProjects)+ if decision.Action != ActionOff || decision.Reason != ReasonDisabled || decision.Restricted() || calls.Load() != 0 {+ t.Fatalf("decision = %+v, calls = %d", decision, calls.Load())+ }+}++func TestCloudFeatureActionsAreDeliveredUnchanged(t *testing.T) {+ for _, action := range []Action{ActionOff, ActionObserve, ActionEnforce} {+ t.Run(string(action), func(t *testing.T) {+ server := httptest.NewServer(featurePolicyHandler(t, `{"private_projects":{"action":"`+string(action)+`"}}`))+ defer server.Close()+ client := newTestClient(t, server.URL, nil)+ decision := client.Feature(context.Background(), uuid.New(), FeaturePrivateProjects)+ if decision.Action != action || decision.Reason != ReasonRefreshed ||+ decision.PolicyRevision != 4 || decision.SubscriptionVersion != 2 {+ t.Fatalf("decision = %+v", decision)+ }+ if decision.Restricted() != (action == ActionEnforce) {+ t.Fatalf("Restricted() = %v for %s", decision.Restricted(), action)+ }+ })+ }+}++// One feature that cannot be read falls back to off with a reason, and the+// metered gate from the same response still enforces.+func TestMalformedFeatureIsIsolatedFromGatesAndOtherFeatures(t *testing.T) {+ cases := []struct {+ name string+ features string+ reason Reason+ }{+ {"features absent", "", ReasonFeatureMissing},+ {"features null", `null`, ReasonFeatureMissing},+ {"features is an array", `[]`, ReasonFeatureInvalid},+ {"features is a string", `"enforce"`, ReasonFeatureInvalid},+ {"feature missing", `{"unknown_feature":{"action":"enforce"}}`, ReasonFeatureMissing},+ {"action is a number", `{"private_projects":{"action":123}}`, ReasonFeatureInvalid},+ {"action is unknown", `{"private_projects":{"action":"block"}}`, ReasonFeatureInvalid},+ {"feature is not an object", `{"private_projects":"enforce"}`, ReasonFeatureInvalid},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ server := httptest.NewServer(featurePolicyHandler(t, tc.features))+ defer server.Close()+ client := newTestClient(t, server.URL, nil)+ workspaceID := uuid.New()++ feature := client.Feature(context.Background(), workspaceID, FeaturePrivateProjects)+ if feature.Action != ActionOff || feature.Reason != tc.reason || feature.PolicyRevision != 4 {+ t.Fatalf("feature = %+v, want off with %s", feature, tc.reason)+ }+ gate := client.Gate(context.Background(), workspaceID, GateAutopilotRuns)+ if gate.Gate.Action != ActionEnforce || gate.Reason != ReasonCacheFresh {+ t.Fatalf("gate must keep enforcing from the same policy: %+v", gate)+ }+ })+ }+}++// Gates and features share one cached policy: reading both costs one request.+func TestFeatureAndGateShareOnePolicyFetch(t *testing.T) {+ var calls atomic.Int64+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ calls.Add(1)+ featurePolicyHandler(t, `{"private_projects":{"action":"enforce"}}`)(w, r)+ }))+ defer server.Close()+ client := newTestClient(t, server.URL, nil)+ workspaceID := uuid.New()++ if got := client.Gate(context.Background(), workspaceID, GateAutopilotRuns); got.Gate.Action != ActionEnforce {+ t.Fatalf("gate = %+v", got)+ }+ feature := client.Feature(context.Background(), workspaceID, FeaturePrivateProjects)+ if feature.Action != ActionEnforce || feature.Reason != ReasonCacheFresh || calls.Load() != 1 {+ t.Fatalf("feature = %+v, calls = %d", feature, calls.Load())+ }+}++// A stale enforce is downgraded to observe with Reason stale, so recorded+// attempts can tell a Cloud outage from a configured observe rollout, and the+// expired policy stops restricting entirely.+func TestStaleFeatureEnforceDowngradesThenFailsOpen(t *testing.T) {+ clock := time.Date(2026, 8, 18, 9, 0, 0, 0, time.UTC)+ var fail atomic.Bool+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if fail.Load() {+ w.WriteHeader(http.StatusServiceUnavailable)+ return+ }+ policy := samplePolicy(4, 0, 5, ActionEnforce)+ policy.Features = json.RawMessage(`{"private_projects":{"action":"enforce"}}`)+ writePolicy(t, w, policy)+ }))+ defer server.Close()+ client := newTestClient(t, server.URL, nil)+ client.staleGrace = 10 * time.Second+ client.now = func() time.Time { return clock }+ workspaceID := uuid.New()++ if fresh := client.Feature(context.Background(), workspaceID, FeaturePrivateProjects); fresh.Action != ActionEnforce {+ t.Fatalf("fresh = %+v", fresh)+ }+ fail.Store(true)+ clock = clock.Add(6 * time.Second)+ stale := client.Feature(context.Background(), workspaceID, FeaturePrivateProjects)+ if stale.Action != ActionObserve || stale.Reason != ReasonStale || !stale.Downgraded || stale.Restricted() {+ t.Fatalf("stale = %+v", stale)+ }+ clock = clock.Add(10 * time.Second)+ expired := client.Feature(context.Background(), workspaceID, FeaturePrivateProjects)+ if expired.Action != ActionOff || expired.Reason != ReasonUnavailable {+ t.Fatalf("expired = %+v", expired)+ }+}++// A feature Cloud already sent as observe stays an ordinary observe when the+// cache goes stale: nothing was downgraded, so attempts count as observed.+func TestStaleFeatureObserveIsNotDowngraded(t *testing.T) {+ clock := time.Date(2026, 8, 18, 9, 0, 0, 0, time.UTC)+ var fail atomic.Bool+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if fail.Load() {+ w.WriteHeader(http.StatusServiceUnavailable)+ return+ }+ policy := samplePolicy(4, 0, 5, ActionEnforce)+ policy.Features = json.RawMessage(`{"private_projects":{"action":"observe"}}`)+ writePolicy(t, w, policy)+ }))+ defer server.Close()+ client := newTestClient(t, server.URL, nil)+ client.staleGrace = 10 * time.Second+ client.now = func() time.Time { return clock }+ workspaceID := uuid.New()++ if fresh := client.Feature(context.Background(), workspaceID, FeaturePrivateProjects); fresh.Action != ActionObserve || fresh.Downgraded {+ t.Fatalf("fresh = %+v", fresh)+ }+ fail.Store(true)+ clock = clock.Add(6 * time.Second)+ stale := client.Feature(context.Background(), workspaceID, FeaturePrivateProjects)+ if stale.Action != ActionObserve || stale.Reason != ReasonStale || stale.Downgraded {+ t.Fatalf("stale observe = %+v, want observe without Downgraded", stale)+ }+}++func TestColdFailureLeavesFeaturesUsable(t *testing.T) {+ server := httptest.NewServer(statusHandler(http.StatusServiceUnavailable))+ defer server.Close()+ client := newTestClient(t, server.URL, nil)+ decision := client.Feature(context.Background(), uuid.New(), FeaturePrivateProjects)+ if decision.Action != ActionOff || decision.Reason != ReasonUnavailable {+ t.Fatalf("decision = %+v", decision)+ }+}++func TestInvalidWorkspaceAndUnknownFeatureDoNotFetch(t *testing.T) {+ var calls atomic.Int64+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ calls.Add(1)+ w.WriteHeader(http.StatusOK)+ }))+ defer server.Close()+ observer := &recordingObserver{}+ client := newTestClient(t, server.URL, func(c *Config) { c.Observer = observer })++ if got := client.Feature(context.Background(), uuid.Nil, FeaturePrivateProjects); got.Reason != ReasonInvalidWorkspace {+ t.Fatalf("nil workspace = %+v", got)+ }+ if got := client.Feature(context.Background(), uuid.New(), FeatureName("custom")); got.Reason != ReasonUnknownGate {+ t.Fatalf("unknown feature = %+v", got)+ }+ if calls.Load() != 0 {+ t.Fatalf("calls = %d, want 0", calls.Load())+ }+ _, _, decisions, _ := observer.snapshot()+ if len(decisions) != 2 || decisions[0] != "feature:private_projects/off/invalid_workspace" ||+ decisions[1] != "feature:unknown/off/unknown_gate" {+ t.Fatalf("decision labels = %v", decisions)+ }+}diff --git a/server/internal/entitlement/types.go b/server/internal/entitlement/types.goindex 92302c1d99..0b29b1a8a2 100644--- a/server/internal/entitlement/types.go+++ b/server/internal/entitlement/types.go@@ -49,6 +49,10 @@ const (ReasonInvalidPolicy Reason = "invalid_policy"ReasonVersionRegression Reason = "version_regression"ReasonStub Reason = "stub"+ // ReasonFeatureMissing and ReasonFeatureInvalid fail one paid feature open+ // without touching the rest of an otherwise valid policy.+ ReasonFeatureMissing Reason = "feature_missing"+ ReasonFeatureInvalid Reason = "feature_invalid")// Gate is the effective instruction for one generic enforcement point. Limits@@ -88,6 +92,64 @@ type Provider interface {Gate(ctx context.Context, workspaceID uuid.UUID, name GateName) Decision}+// FeatureName is a stable paid-feature key. Unlike a GateName it meters+// nothing: it says whether a workspace may add to the feature's configuration.+type FeatureName string++const (+ FeaturePrivateProjects FeatureName = "private_projects"+)++// Features lists every paid feature this consumer understands.+func Features() []FeatureName {+ return []FeatureName{FeaturePrivateProjects}+}++func (n FeatureName) Valid() bool {+ switch n {+ case FeaturePrivateProjects:+ return true+ default:+ return false+ }+}++// FeatureDecision is the effective restriction on one paid feature:+//+// - off: the feature is fully usable.+// - observe: fully usable; each attempt to add to its configuration is+// recorded. A stale cached enforce is also downgraded to observe, with+// Downgraded set, so a Cloud outage never keeps blocking.+// - enforce: existing configuration keeps working and can always be reduced+// or removed; attempts to add to it are rejected.+//+// Reads never consult a FeatureDecision. Access control built on a paid+// feature (who sees a private project, who may invoke an agent) stays exactly+// as configured whatever the decision is.+type FeatureDecision struct {+ Action Action+ Reason Reason+ // Downgraded is set when Cloud sent enforce but the cached policy has gone+ // stale, so Action was lowered to observe. A stale policy whose feature+ // was already observe keeps Downgraded false: Reason stale alone does not+ // say whether anything would have been blocked.+ Downgraded bool+ PolicyRevision int64+ SubscriptionVersion int64+ CloudValidUntil time.Time+}++// Restricted reports whether additions to the feature are rejected.+func (d FeatureDecision) Restricted() bool { return d.Action == ActionEnforce }++// FeatureProvider is the source of paid-feature decisions. The Cloud policy+// client implements it today; a self-hosted license provider can replace it+// without changing any caller. Like Provider it has no error return: every+// failure is a fail-open decision.+type FeatureProvider interface {+ Feature(ctx context.Context, workspaceID uuid.UUID, name FeatureName) FeatureDecision+}+// Observer is a low-cardinality instrumentation seam. Implementations must not// attach workspace IDs or policy values as metric labels.type Observer interface {diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex c0903921a0..8814c1c137 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -238,6 +238,9 @@ type Handler struct {// Entitlements supplies workspace-scoped commercial gates. A nil provider// preserves self-hosted behavior without extra reads.Entitlements entitlement.Provider+ // Features restricts paid features (paid_feature.go). Nil leaves every+ // feature usable, which is the self-hosted behavior.+ Features entitlement.FeatureProvider// SeatCapacity executes Cloud's pre-purchased human-seat protocol. Nil or// disabled preserves self-hosted behavior.SeatCapacity seatcapacity.Executordiff --git a/server/internal/handler/paid_feature.go b/server/internal/handler/paid_feature.gonew file mode 100644index 0000000000..8ed81306b6--- /dev/null+++ b/server/internal/handler/paid_feature.go@@ -0,0 +1,129 @@+package handler++import (+ "context"+ "net/http"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/entitlement"+ "github.com/multica-ai/multica/server/internal/service"+)++// Paid features (MUL-9482).+//+// A paid feature is restricted for a workspace whose plan does not include+// it. The rule is the same for every feature:+//+// - Existing configuration keeps working. Reads, access checks and anything+// that runs on the configuration never consult the restriction.+// - Reducing or removing configuration is never restricted: removing a+// person, making something public again, deleting.+// - Adding to it is restricted: creating, adding a person, widening.+// - Edits that leave the feature's configuration unchanged (renaming, a+// same-value write-back) are not restricted.+//+// Each feature classifies its own writes and calls requireFeatureAddition+// only for the ones that add. The restriction is commercial, not+// authorization: callers run their normal permission checks first, so a+// caller who could not make the change anyway gets the ordinary 403.+//+// The decision comes from h.Features. Nil, as on a self-hosted deployment+// without Cloud, leaves every feature usable.++const featureLockedCode = "feature_locked"++// featureAdmission is an admitted addition to a paid feature that is being+// observed. Call admitted once the write has committed; it records the attempt+// and is a no-op when nothing needs recording.+type featureAdmission struct {+ attempts service.EntitlementFeatureAttempts+ attempt service.FeatureAttempt+ record bool+}++func (a featureAdmission) admitted(ctx context.Context) {+ if a.record {+ a.attempts.Record(ctx, a.attempt)+ }+}++// requireFeatureAddition decides whether the caller may add to feature's+// configuration in workspaceID. operation names the addition for the attempt+// record, e.g. "create" or "add_members". Under enforce it records the+// rejection and answers 403 feature_locked; under observe it admits the+// addition and returns an admission to record after the write commits.+func (h *Handler) requireFeatureAddition(w http.ResponseWriter, r *http.Request, workspaceID pgtype.UUID, feature entitlement.FeatureName, operation string) (featureAdmission, bool) {+ if h.Features == nil || !workspaceID.Valid {+ return featureAdmission{}, true+ }+ decision := h.Features.Feature(r.Context(), uuid.UUID(workspaceID.Bytes), feature)+ if decision.Action == entitlement.ActionOff {+ return featureAdmission{}, true+ }+ attempts := service.EntitlementFeatureAttempts{Queries: h.Queries}+ attempt := service.FeatureAttempt{+ WorkspaceID: workspaceID,+ Feature: feature,+ Operation: operation,+ Decision: decision,+ }+ if decision.Restricted() {+ attempts.Record(r.Context(), attempt)+ writeFeatureLocked(w, feature)+ return featureAdmission{}, false+ }+ return featureAdmission{attempts: attempts, attempt: attempt, record: true}, true+}++func writeFeatureLocked(w http.ResponseWriter, feature entitlement.FeatureName) {+ writeJSON(w, http.StatusForbidden, map[string]string{+ "error": "This feature is not included in the workspace's plan. Existing settings keep working; upgrade to add more.",+ "code": featureLockedCode,+ "feature": string(feature),+ })+}++// WorkspaceFeatureState is what a client may do with one paid feature.+// available covers off and observe, so an observed rollout is invisible to+// users; locked is enforce.+type WorkspaceFeatureState struct {+ State string `json:"state"`+}++const (+ workspaceFeatureAvailable = "available"+ workspaceFeatureLocked = "locked"+)++type WorkspaceFeaturesResponse struct {+ Features map[string]WorkspaceFeatureState `json:"features"`+}++// GetWorkspaceFeatures — GET /api/workspaces/{id}/features+//+// Member-readable: every member sees the same restriction on the shared+// workspace. The response carries only the evaluated state per feature, never+// plan, subscription or policy details. Clients use it to show read-only and+// upgrade states; the server enforces on every write regardless.+func (h *Handler) GetWorkspaceFeatures(w http.ResponseWriter, r *http.Request) {+ wsID := workspaceIDFromURL(r, "id")+ if _, ok := h.requireWorkspaceMember(w, r, wsID, "workspace not found"); !ok {+ return+ }+ workspaceID, ok := parseUUIDOrBadRequest(w, wsID, "workspace id")+ if !ok {+ return+ }+ features := entitlement.Features()+ resp := WorkspaceFeaturesResponse{Features: make(map[string]WorkspaceFeatureState, len(features))}+ for _, feature := range features {+ state := workspaceFeatureAvailable+ if h.Features != nil && h.Features.Feature(r.Context(), uuid.UUID(workspaceID.Bytes), feature).Restricted() {+ state = workspaceFeatureLocked+ }+ resp.Features[string(feature)] = WorkspaceFeatureState{State: state}+ }+ writeJSON(w, http.StatusOK, resp)+}diff --git a/server/internal/handler/private_project_feature_test.go b/server/internal/handler/private_project_feature_test.gonew file mode 100644index 0000000000..7e13a77efc--- /dev/null+++ b/server/internal/handler/private_project_feature_test.go@@ -0,0 +1,329 @@+package handler++import (+ "context"+ "net/http"+ "testing"+ "time"++ "github.com/google/uuid"++ "github.com/multica-ai/multica/server/internal/entitlement"+ "github.com/multica-ai/multica/server/internal/entitlement/entitlementtest"+ "github.com/multica-ai/multica/server/internal/testutil"+)++// usePrivateProjectsFeature points the shared test handler at a stub that+// returns decision for private_projects in the test workspace, and clears the+// workspace's recorded attempts before and after.+func usePrivateProjectsFeature(t *testing.T, decision entitlement.FeatureDecision) {+ t.Helper()+ stub := entitlementtest.New()+ stub.SetFeature(uuid.MustParse(testWorkspaceID), entitlement.FeaturePrivateProjects, decision)+ prior := testHandler.Features+ testHandler.Features = stub+ clearFeatureAttempts(t)+ t.Cleanup(func() {+ testHandler.Features = prior+ clearFeatureAttempts(t)+ })+}++func clearFeatureAttempts(t *testing.T) {+ t.Helper()+ if _, err := testPool.Exec(context.Background(),+ `DELETE FROM entitlement_feature_attempt WHERE workspace_id = $1`, testWorkspaceID); err != nil {+ t.Fatalf("clear feature attempts: %v", err)+ }+}++type featureAttemptCounts struct {+ observed, degraded, enforced int64+ lastOperation string+}++func privateProjectAttempts(t *testing.T) featureAttemptCounts {+ t.Helper()+ var c featureAttemptCounts+ err := testPool.QueryRow(context.Background(), `+ SELECT COALESCE(SUM(observed_count), 0), COALESCE(SUM(degraded_count), 0), COALESCE(SUM(enforced_count), 0),+ COALESCE(MAX(last_operation), '')+ FROM entitlement_feature_attempt+ WHERE workspace_id = $1 AND feature = 'private_projects'`, testWorkspaceID,+ ).Scan(&c.observed, &c.degraded, &c.enforced, &c.lastOperation)+ if err != nil {+ t.Fatalf("read feature attempts: %v", err)+ }+ return c+}++func wantFeatureLocked(t *testing.T, resp *testutil.Response) {+ t.Helper()+ var body struct {+ Code string `json:"code"`+ Feature string `json:"feature"`+ }+ resp.Want(http.StatusForbidden).JSON(&body)+ if body.Code != "feature_locked" || body.Feature != "private_projects" {+ t.Fatalf("locked body = %+v, want feature_locked/private_projects", body)+ }+}++func createPrivateProjectAs(t *testing.T, userID, title string) *testutil.Response {+ t.Helper()+ body := map[string]any{"title": title, "visibility": "private"}+ resp := testutil.Call(t, testHandler.CreateProject, asUser(newRequest(http.MethodPost, "/api/projects", body), userID))+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM project_member WHERE project_id IN (SELECT id FROM project WHERE title = $1)`, title)+ testPool.Exec(context.Background(), `DELETE FROM project WHERE title = $1`, title)+ })+ return resp+}++func projectCountByTitle(t *testing.T, title string) int {+ t.Helper()+ var n int+ if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM project WHERE title = $1`, title).Scan(&n); err != nil {+ t.Fatalf("count projects: %v", err)+ }+ return n+}++// The example feature end to end: the same create works under off, is+// admitted and recorded under observe, and is rejected and recorded under+// enforce without writing anything.+func TestPrivateProjectCreateUnderEachFeatureAction(t *testing.T) {+ for _, tc := range []struct {+ action entitlement.Action+ want int+ attempts featureAttemptCounts+ }{+ {entitlement.ActionOff, http.StatusCreated, featureAttemptCounts{}},+ {entitlement.ActionObserve, http.StatusCreated, featureAttemptCounts{observed: 1, lastOperation: "create"}},+ {entitlement.ActionEnforce, http.StatusForbidden, featureAttemptCounts{enforced: 1, lastOperation: "create"}},+ } {+ t.Run(string(tc.action), func(t *testing.T) {+ usePrivateProjectsFeature(t, entitlement.FeatureDecision{Action: tc.action, Reason: entitlement.ReasonRefreshed, PolicyRevision: 4})+ title := "feature create " + string(tc.action) + " " + uuid.NewString()+ resp := createPrivateProjectAs(t, testUserID, title)+ if tc.want == http.StatusForbidden {+ wantFeatureLocked(t, resp)+ if n := projectCountByTitle(t, title); n != 0 {+ t.Fatalf("rejected create wrote %d projects", n)+ }+ } else {+ resp.Want(tc.want)+ }+ if got := privateProjectAttempts(t); got != tc.attempts {+ t.Fatalf("attempts = %+v, want %+v", got, tc.attempts)+ }+ })+ }+}++// A workspace-visible project is not the paid feature: creating one is never+// restricted or recorded.+func TestWorkspaceProjectCreateIgnoresPrivateProjectsFeature(t *testing.T) {+ usePrivateProjectsFeature(t, entitlement.FeatureDecision{Action: entitlement.ActionEnforce})+ title := "feature public " + uuid.NewString()+ resp := testutil.Call(t, testHandler.CreateProject, newRequest(http.MethodPost, "/api/projects", map[string]any{"title": title}))+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM project WHERE title = $1`, title) })+ resp.Want(http.StatusCreated)+ if got := privateProjectAttempts(t); got != (featureAttemptCounts{}) {+ t.Fatalf("attempts = %+v, want none", got)+ }+}++// After a downgrade the existing private project keeps working exactly as+// configured, can be reduced and made public, and only additions are refused.+func TestPrivateProjectEnforcedKeepsExistingConfigAndAllowsReductions(t *testing.T) {+ f := newPrivateProjectFixture(t)+ usePrivateProjectsFeature(t, entitlement.FeatureDecision{Action: entitlement.ActionEnforce, Reason: entitlement.ReasonRefreshed})++ // Access control is untouched: still members only.+ getProject := func(userID string) *testutil.Response {+ req := withURLParam(asUser(newRequest(http.MethodGet, "/api/projects/"+f.projectID, nil), userID), "id", f.projectID)+ return testutil.Call(t, testHandler.GetProject, req)+ }+ getProject(f.insider).Want(http.StatusOK)+ getProject(f.outsider).Want(http.StatusNotFound)+ getProject(f.outsideAdmin).Want(http.StatusNotFound)++ // Edits that do not add to the private configuration.+ updateProjectAs(t, testUserID, f.projectID, map[string]any{"title": f.marker + " renamed"}).Want(http.StatusOK)+ updateProjectAs(t, testUserID, f.projectID, map[string]any{"member_ids": []string{testUserID, f.insider}}).Want(http.StatusOK)+ addProjectMembersAs(t, testUserID, f.projectID, f.insider).Want(http.StatusOK)+ updateProjectAs(t, testUserID, f.projectID, map[string]any{"lead_type": "member", "lead_id": f.insider}).Want(http.StatusOK)+ updateProjectAs(t, testUserID, f.projectID, map[string]any{"lead_type": nil, "lead_id": nil}).Want(http.StatusOK)+ if got := privateProjectAttempts(t); got != (featureAttemptCounts{}) {+ t.Fatalf("unchanged configuration recorded attempts: %+v", got)+ }++ // Additions, directly or through a lead who is not a member yet.+ wantFeatureLocked(t, addProjectMembersAs(t, testUserID, f.projectID, f.outsider))+ wantFeatureLocked(t, updateProjectAs(t, testUserID, f.projectID, map[string]any{"member_ids": []string{f.outsider}}))+ wantFeatureLocked(t, updateProjectAs(t, testUserID, f.projectID, map[string]any{"lead_type": "member", "lead_id": f.outsider}))+ getProject(f.outsider).Want(http.StatusNotFound)+ if got := privateProjectAttempts(t); got.enforced != 3 || got.lastOperation != "add_members" {+ t.Fatalf("attempts = %+v, want 3 enforced add_members", got)+ }++ // Reductions.+ req := testutil.WithURLParams(newRequest(http.MethodDelete, "/api/projects/"+f.projectID+"/members/"+f.insider, nil),+ "id", f.projectID, "userId", f.insider)+ testutil.Call(t, testHandler.RemoveProjectMember, req).Want(http.StatusNoContent)+ updateProjectAs(t, testUserID, f.projectID, map[string]any{"visibility": "workspace"}).Want(http.StatusOK)+ getProject(f.outsider).Want(http.StatusOK)++ // Making it private again adds to the configuration.+ wantFeatureLocked(t, updateProjectAs(t, testUserID, f.projectID, map[string]any{"visibility": "private"}))+ if got := privateProjectAttempts(t); got.enforced != 4 || got.lastOperation != "make_private" {+ t.Fatalf("attempts = %+v, want 4 enforced, last make_private", got)+ }+}++// The restriction is commercial. A caller the ordinary rules already refuse+// gets the ordinary 403, and nothing is recorded as a feature attempt.+func TestPrivateProjectFeatureRunsAfterAuthorization(t *testing.T) {+ f := newPrivateProjectFixture(t)+ usePrivateProjectsFeature(t, entitlement.FeatureDecision{Action: entitlement.ActionEnforce})++ var body struct {+ Code string `json:"code"`+ }+ addProjectMembersAs(t, f.insider, f.projectID, f.outsider).Want(http.StatusForbidden).JSON(&body)+ if body.Code == "feature_locked" {+ t.Fatal("a caller without permission must get the ordinary permission error")+ }+ if got := privateProjectAttempts(t); got != (featureAttemptCounts{}) {+ t.Fatalf("attempts = %+v, want none", got)+ }+}++// A workspace owner's recovery join keeps a private project with no members+// reachable, so it is never restricted.+func TestPrivateProjectOwnerRecoveryJoinIsNotRestricted(t *testing.T) {+ f := newPrivateProjectFixture(t)+ removeProjectMemberRow(t, f.projectID, testUserID)+ usePrivateProjectsFeature(t, entitlement.FeatureDecision{Action: entitlement.ActionEnforce})++ req := withURLParam(newRequest(http.MethodPost, "/api/projects/"+f.projectID+"/join", nil), "id", f.projectID)+ testutil.Call(t, testHandler.JoinPrivateProject, req).Want(http.StatusOK)+}++// Additions admitted only because a stale enforce was downgraded during a+// Cloud outage are recorded apart from a configured observe rollout, and a+// configured observe served from a stale cache still counts as observed.+func TestPrivateProjectStaleDecisionsAreRecordedByOrigin(t *testing.T) {+ for _, tc := range []struct {+ name string+ decision entitlement.FeatureDecision+ want featureAttemptCounts+ }{+ {"stale enforce downgraded", entitlement.FeatureDecision{Action: entitlement.ActionObserve, Reason: entitlement.ReasonStale, Downgraded: true},+ featureAttemptCounts{degraded: 1, lastOperation: "add_members"}},+ {"stale observe", entitlement.FeatureDecision{Action: entitlement.ActionObserve, Reason: entitlement.ReasonStale},+ featureAttemptCounts{observed: 1, lastOperation: "add_members"}},+ } {+ t.Run(tc.name, func(t *testing.T) {+ f := newPrivateProjectFixture(t)+ usePrivateProjectsFeature(t, tc.decision)+ addProjectMembersAs(t, testUserID, f.projectID, f.outsider).Want(http.StatusOK)+ if got := privateProjectAttempts(t); got != tc.want {+ t.Fatalf("attempts = %+v, want %+v", got, tc.want)+ }+ })+ }+}++// Recording happens before the response is written. A contended attempt row+// must cost at most the record's own short timeout, and the already-decided+// result is returned either way: the committed create for observe, the+// refusal for enforce.+func TestPrivateProjectAttemptRecordCannotHoldTheResponse(t *testing.T) {+ for _, tc := range []struct {+ action entitlement.Action+ want int+ }{+ {entitlement.ActionObserve, http.StatusCreated},+ {entitlement.ActionEnforce, http.StatusForbidden},+ } {+ t.Run(string(tc.action), func(t *testing.T) {+ usePrivateProjectsFeature(t, entitlement.FeatureDecision{Action: tc.action})+ ctx := context.Background()+ // Hold today's attempt row for this workspace and feature in an+ // open transaction, so the handler's upsert has to wait for it.+ tx, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatalf("begin: %v", err)+ }+ defer tx.Rollback(ctx)+ if _, err := tx.Exec(ctx, `+ INSERT INTO entitlement_feature_attempt (workspace_id, feature, day, last_operation, last_action, last_reason)+ VALUES ($1, 'private_projects', (now() AT TIME ZONE 'UTC')::date, 'lock', 'observe', '')`, testWorkspaceID); err != nil {+ t.Fatalf("hold attempt row: %v", err)+ }++ title := "feature contended " + string(tc.action) + " " + uuid.NewString()+ started := time.Now()+ resp := createPrivateProjectAs(t, testUserID, title)+ elapsed := time.Since(started)+ resp.Want(tc.want)+ if elapsed > 3*time.Second {+ t.Fatalf("response took %s while the attempt row was locked", elapsed)+ }+ wantProjects := 0+ if tc.want == http.StatusCreated {+ wantProjects = 1+ }+ if n := projectCountByTitle(t, title); n != wantProjects {+ t.Fatalf("projects = %d, want %d", n, wantProjects)+ }+ })+ }+}++func TestGetWorkspaceFeatures(t *testing.T) {+ get := func(t *testing.T, userID string) *testutil.Response {+ t.Helper()+ req := withURLParam(asUser(newRequest(http.MethodGet, "/api/workspaces/"+testWorkspaceID+"/features", nil), userID), "id", testWorkspaceID)+ return testutil.Call(t, testHandler.GetWorkspaceFeatures, req)+ }+ state := func(t *testing.T) string {+ t.Helper()+ var resp WorkspaceFeaturesResponse+ get(t, testUserID).Want(http.StatusOK).JSON(&resp)+ return resp.Features["private_projects"].State+ }++ t.Run("self-host leaves every feature available", func(t *testing.T) {+ prior := testHandler.Features+ testHandler.Features = nil+ t.Cleanup(func() { testHandler.Features = prior })+ if got := state(t); got != "available" {+ t.Fatalf("state = %q, want available", got)+ }+ })+ for _, tc := range []struct {+ decision entitlement.FeatureDecision+ want string+ }{+ {entitlement.FeatureDecision{Action: entitlement.ActionOff}, "available"},+ {entitlement.FeatureDecision{Action: entitlement.ActionObserve}, "available"},+ {entitlement.FeatureDecision{Action: entitlement.ActionObserve, Reason: entitlement.ReasonStale}, "available"},+ {entitlement.FeatureDecision{Action: entitlement.ActionEnforce}, "locked"},+ } {+ t.Run(string(tc.decision.Action)+"/"+string(tc.decision.Reason), func(t *testing.T) {+ usePrivateProjectsFeature(t, tc.decision)+ if got := state(t); got != tc.want {+ t.Fatalf("state = %q, want %q", got, tc.want)+ }+ })+ }+ t.Run("non-member is refused", func(t *testing.T) {+ resp := get(t, uuid.NewString())+ if resp.Code == http.StatusOK {+ t.Fatal("a non-member must not read the workspace's features")+ }+ })+}diff --git a/server/internal/handler/project.go b/server/internal/handler/project.goindex 6fcbe9163d..46c337fbef 100644--- a/server/internal/handler/project.go+++ b/server/internal/handler/project.go@@ -14,6 +14,7 @@ import ("github.com/go-chi/chi/v5""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/entitlement""github.com/multica-ai/multica/server/internal/issuestatus""github.com/multica-ai/multica/server/internal/logger""github.com/multica-ai/multica/server/internal/projectaccess"@@ -490,6 +491,12 @@ func (h *Handler) CreateProject(w http.ResponseWriter, r *http.Request) {private = trueprivateMemberIDs = ids}+ var admission featureAdmission+ if private {+ if admission, ok = h.requireFeatureAddition(w, r, wsUUID, entitlement.FeaturePrivateProjects, privateProjectOpCreate); !ok {+ return+ }+ }actorType, actorID := h.resolveActor(r, userID, workspaceID)creatorID, ok := parseUUIDOrBadRequest(w, actorID, "creator_id")@@ -598,6 +605,7 @@ func (h *Handler) CreateProject(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to commit project create")return}+ admission.admitted(r.Context())resourceResp := make([]ProjectResourceResponse, len(resourceRows))for i, row := range resourceRows {@@ -754,10 +762,17 @@ func (h *Handler) UpdateProject(w http.ResponseWriter, r *http.Request) {if !ok {return}+ var admission featureAdmission+ if access.privateAddition != "" {+ if admission, ok = h.requireFeatureAddition(w, r, prevProject.WorkspaceID, entitlement.FeaturePrivateProjects, access.privateAddition); !ok {+ return+ }+ }project, ok := h.writeProjectUpdate(w, r, params, access, userID)if !ok {return}+ admission.admitted(r.Context())resp := projectToResponse(project)h.fillProjectIssueStats(r.Context(), &resp, project)resp.ResourceCount = h.loadProjectResourceCount(r.Context(), project.ID)diff --git a/server/internal/handler/project_member.go b/server/internal/handler/project_member.goindex c09b71bbab..f397bf2582 100644--- a/server/internal/handler/project_member.go+++ b/server/internal/handler/project_member.go@@ -12,6 +12,7 @@ import ("github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/entitlement""github.com/multica-ai/multica/server/internal/logger""github.com/multica-ai/multica/server/internal/projectaccess""github.com/multica-ai/multica/server/internal/util"@@ -47,6 +48,10 @@ type AddProjectMembersRequest struct {type projectAccessUpdate struct {visibility string // target visibility; "" leaves it unchangedaddIDs []pgtype.UUID+ // privateAddition names how the update adds to private-project+ // configuration ("make_private", "add_members"), or is "" when it does+ // not. It decides whether the private_projects paid feature applies.+ privateAddition string}func (u projectAccessUpdate) empty() bool { return u.visibility == "" && len(u.addIDs) == 0 }@@ -216,6 +221,7 @@ func (h *Handler) prepareProjectAccessUpdate(w http.ResponseWriter, r *http.Requ}}update.addIDs = ids+ update.privateAddition = privateProjectOpMakePrivate} else if !h.requireExistingProjectMembers(w, r, project, rawMemberIDs) {return projectAccessUpdate{}, false}@@ -247,18 +253,59 @@ func (h *Handler) prepareProjectAccessUpdate(w http.ResponseWriter, r *http.Requ}update.addIDs = ids}- if !leadChanged || !memberLead {- return update, true+ if leadChanged && memberLead && !slices.Contains(update.addIDs, newLeadID) {+ isMember, err := h.isProjectMember(r, project, newLeadID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to check project membership")+ return projectAccessUpdate{}, false+ }+ if !isMember {+ update.addIDs = append(update.addIDs, newLeadID)+ }+ }+ // The web app's access dialog writes back the current member list, so only+ // someone who is not a member yet adds to the private project.+ if len(update.addIDs) > 0 {+ grows, err := h.projectMembersGrow(r, project, update.addIDs)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list project members")+ return projectAccessUpdate{}, false+ }+ if grows {+ update.privateAddition = privateProjectOpAddMembers+ }}- isMember, err := h.isProjectMember(r, project, newLeadID)+ return update, true+}++// Private-project operations restricted by the private_projects paid feature.+// Everything else on a private project stays allowed under the restriction:+// removing members, making it workspace-visible, deleting or archiving it,+// changing the lead to an existing member, an agent or nobody, editing any+// other field, and the workspace owner's recovery join (JoinPrivateProject),+// which must keep a project with no members reachable.+const (+ privateProjectOpCreate = "create"+ privateProjectOpMakePrivate = "make_private"+ privateProjectOpAddMembers = "add_members"+)++// projectMembersGrow reports whether adding ids to project would add anyone+// who is not a member yet.+func (h *Handler) projectMembersGrow(r *http.Request, project db.Project, ids []pgtype.UUID) (bool, error) {+ existing, err := h.Queries.ListProjectMemberUserIDs(r.Context(), db.ListProjectMemberUserIDsParams{+ ProjectID: project.ID,+ WorkspaceID: project.WorkspaceID,+ })if err != nil {- writeError(w, http.StatusInternalServerError, "failed to check project membership")- return projectAccessUpdate{}, false+ return false, err}- if !isMember && !slices.Contains(update.addIDs, newLeadID) {- update.addIDs = append(update.addIDs, newLeadID)+ for _, id := range ids {+ if !slices.Contains(existing, id) {+ return true, nil+ }}- return update, true+ return false, nil}// requireExistingProjectMembers answers 400 unless every id in member_ids is@@ -492,6 +539,19 @@ func (h *Handler) AddProjectMembers(w http.ResponseWriter, r *http.Request) {if !h.requireProjectAccessManager(w, r, member, project, "only workspace admins and the member who manages this project's access can add members") {return}+ var admission featureAdmission+ if projectVisibilityOrDefault(project.Visibility) == projectaccess.VisibilityPrivate {+ grows, err := h.projectMembersGrow(r, project, ids)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list project members")+ return+ }+ if grows {+ if admission, ok = h.requireFeatureAddition(w, r, project.WorkspaceID, entitlement.FeaturePrivateProjects, privateProjectOpAddMembers); !ok {+ return+ }+ }+ }tx, err := h.TxStarter.Begin(r.Context())if err != nil {writeError(w, http.StatusInternalServerError, "failed to start transaction")@@ -520,6 +580,7 @@ func (h *Handler) AddProjectMembers(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to commit project members")return}+ admission.admitted(r.Context())h.publishProjectMembersChanged(project, member.UserID)h.ListProjectMembers(w, r)}diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.goindex 0e23e236b0..40cf8fdd8b 100644--- a/server/internal/handler/workspace.go+++ b/server/internal/handler/workspace.go@@ -1335,6 +1335,10 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {name: "delete entitlement limit overages",run: func() error { return qtx.DeleteWorkspaceEntitlementLimitOverages(ctx, requester.WorkspaceID) },},+ {+ name: "delete entitlement feature attempts",+ run: func() error { return qtx.DeleteWorkspaceEntitlementFeatureAttempts(ctx, requester.WorkspaceID) },+ },{name: "delete chat messages",run: func() error { return qtx.DeleteWorkspaceChatMessages(ctx, requester.WorkspaceID) },diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex e1ed183931..81c737b50d 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -65,6 +65,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"dingtalk_group_presence": workspaceDelete,"dingtalk_bot_identity": workspaceDelete,"dingtalk_group_route": workspaceDelete,+ "entitlement_feature_attempt": workspaceDelete,"entitlement_limit_overage": workspaceDelete,"feedback": workspaceDeleteDetach,"github_installation": workspaceDelete,diff --git a/server/internal/service/entitlement_feature_attempt.go b/server/internal/service/entitlement_feature_attempt.gonew file mode 100644index 0000000000..9f4616d15d--- /dev/null+++ b/server/internal/service/entitlement_feature_attempt.go@@ -0,0 +1,166 @@+package service++import (+ "context"+ "fmt"+ "log/slog"+ "time"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/entitlement"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// FeatureAttemptOutcome is what happened to one attempt to add to a paid+// feature that was not off.+type FeatureAttemptOutcome string++const (+ // FeatureAttemptObserved was admitted under a configured observe.+ FeatureAttemptObserved FeatureAttemptOutcome = "observed"+ // FeatureAttemptDegraded was admitted only because a stale cached enforce+ // had been downgraded to observe during a Cloud outage.+ FeatureAttemptDegraded FeatureAttemptOutcome = "degraded"+ // FeatureAttemptEnforced was rejected.+ FeatureAttemptEnforced FeatureAttemptOutcome = "enforced"+)++// FeatureAttemptOutcomeFor maps a decision to the outcome of an attempt made+// under it. ok=false for off: an unrestricted feature records nothing.+func FeatureAttemptOutcomeFor(decision entitlement.FeatureDecision) (FeatureAttemptOutcome, bool) {+ switch decision.Action {+ case entitlement.ActionEnforce:+ return FeatureAttemptEnforced, true+ case entitlement.ActionObserve:+ if decision.Downgraded {+ return FeatureAttemptDegraded, true+ }+ return FeatureAttemptObserved, true+ default:+ return "", false+ }+}++// FeatureAttempt is one attempt to add to a paid feature's configuration.+type FeatureAttempt struct {+ WorkspaceID pgtype.UUID+ Feature entitlement.FeatureName+ // Operation names what was attempted, e.g. "create" or "add_members".+ Operation string+ Decision entitlement.FeatureDecision+}++// FeatureAttemptDay is one workspace's attempts on one feature in one UTC day.+type FeatureAttemptDay struct {+ WorkspaceID uuid.UUID+ Feature entitlement.FeatureName+ Day time.Time+ ObservedCount int64+ DegradedCount int64+ EnforcedCount int64+ LastOperation string+ LastAction entitlement.Action+ LastReason entitlement.Reason+ LastPolicyRevision int64+ LastSubscriptionVersion int64+ FirstAttemptAt time.Time+ LastAttemptAt time.Time+}++// EntitlementFeatureAttempts records and reads attempts to add to restricted+// paid features. Only features that are observing or enforcing reach it, so a+// self-hosted deployment never touches the table.+type EntitlementFeatureAttempts struct {+ Queries *db.Queries+ // RecordTimeout bounds one Record; zero means defaultFeatureAttemptRecordTimeout.+ RecordTimeout time.Duration+}++// Recording runs before the caller writes its response, so it gets its own+// short deadline: a contended row lock or a slow database drops the record+// instead of holding a request whose outcome is already decided.+const defaultFeatureAttemptRecordTimeout = time.Second++// Record stores one attempt. It is best-effort: callers record an admitted+// attempt after their write commits and a rejected one after authorization,+// and a failure here never changes the operation's result. It is detached from+// the caller's cancellation, so a client that disconnects after a committed+// write still leaves a record, and bounded by RecordTimeout, so it can never+// hold the response.+func (a EntitlementFeatureAttempts) Record(ctx context.Context, attempt FeatureAttempt) {+ outcome, ok := FeatureAttemptOutcomeFor(attempt.Decision)+ if !ok || a.Queries == nil {+ return+ }+ timeout := a.RecordTimeout+ if timeout <= 0 {+ timeout = defaultFeatureAttemptRecordTimeout+ }+ ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), timeout)+ defer cancel()+ _, err := a.Queries.RecordEntitlementFeatureAttempt(ctx, db.RecordEntitlementFeatureAttemptParams{+ WorkspaceID: attempt.WorkspaceID,+ Feature: string(attempt.Feature),+ Outcome: string(outcome),+ Operation: attempt.Operation,+ Action: string(attempt.Decision.Action),+ Reason: string(attempt.Decision.Reason),+ PolicyRevision: attempt.Decision.PolicyRevision,+ SubscriptionVersion: attempt.Decision.SubscriptionVersion,+ })+ if err != nil {+ slog.Warn("entitlement feature attempt was not recorded; the operation's result is unchanged",+ "workspace_id", util.UUIDToString(attempt.WorkspaceID),+ "feature", string(attempt.Feature),+ "outcome", string(outcome),+ "error", err,+ )+ }+}++// ForWorkspace lists every day on which a workspace tried to add to a+// restricted feature, newest first.+func (a EntitlementFeatureAttempts) ForWorkspace(ctx context.Context, workspaceID pgtype.UUID) ([]FeatureAttemptDay, error) {+ rows, err := a.Queries.ListWorkspaceEntitlementFeatureAttempts(ctx, workspaceID)+ if err != nil {+ return nil, fmt.Errorf("list workspace feature attempts: %w", err)+ }+ return featureAttemptDaysFromRows(rows), nil+}++// Since lists, per workspace and day, the attempts on one feature from a UTC+// day on.+func (a EntitlementFeatureAttempts) Since(ctx context.Context, feature entitlement.FeatureName, day time.Time) ([]FeatureAttemptDay, error) {+ rows, err := a.Queries.ListEntitlementFeatureAttemptsSince(ctx, db.ListEntitlementFeatureAttemptsSinceParams{+ Feature: string(feature),+ SinceDay: pgtype.Date{Time: day.UTC(), Valid: true},+ })+ if err != nil {+ return nil, fmt.Errorf("list feature attempts since day: %w", err)+ }+ return featureAttemptDaysFromRows(rows), nil+}++func featureAttemptDaysFromRows(rows []db.EntitlementFeatureAttempt) []FeatureAttemptDay {+ out := make([]FeatureAttemptDay, 0, len(rows))+ for _, row := range rows {+ out = append(out, FeatureAttemptDay{+ WorkspaceID: uuid.UUID(row.WorkspaceID.Bytes),+ Feature: entitlement.FeatureName(row.Feature),+ Day: row.Day.Time.UTC(),+ ObservedCount: row.ObservedCount,+ DegradedCount: row.DegradedCount,+ EnforcedCount: row.EnforcedCount,+ LastOperation: row.LastOperation,+ LastAction: entitlement.Action(row.LastAction),+ LastReason: entitlement.Reason(row.LastReason),+ LastPolicyRevision: row.LastPolicyRevision,+ LastSubscriptionVersion: row.LastSubscriptionVersion,+ FirstAttemptAt: row.FirstAttemptAt.Time.UTC(),+ LastAttemptAt: row.LastAttemptAt.Time.UTC(),+ })+ }+ return out+}diff --git a/server/migrations/683_entitlement_feature_attempt.down.sql b/server/migrations/683_entitlement_feature_attempt.down.sqlnew file mode 100644index 0000000000..a1eac50572--- /dev/null+++ b/server/migrations/683_entitlement_feature_attempt.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS entitlement_feature_attempt;diff --git a/server/migrations/683_entitlement_feature_attempt.up.sql b/server/migrations/683_entitlement_feature_attempt.up.sqlnew file mode 100644index 0000000000..6caf80d8ba--- /dev/null+++ b/server/migrations/683_entitlement_feature_attempt.up.sql@@ -0,0 +1,30 @@+-- Per-workspace record of attempts to add to a restricted paid feature's+-- configuration (create a private project, add people to it, ...). Under+-- observe the attempt was admitted and only recorded here; under enforce it+-- was rejected. Rollout reach and the impact of turning a feature on are read+-- from this table; metrics carry no workspace label.+--+-- Features have no billing period, so attempts are aggregated per UTC day.+-- degraded_count separates attempts admitted only because the cached Cloud+-- policy had gone stale (a would-be enforce downgraded to observe) from a+-- configured observe rollout. The last_* columns describe the latest attempt.+--+-- The scope unique index is built concurrently in 684. No foreign keys (repo+-- rule): workspace deletion removes these rows explicitly.+CREATE TABLE IF NOT EXISTS entitlement_feature_attempt (+ workspace_id UUID NOT NULL,+ feature TEXT NOT NULL,+ day DATE NOT NULL,+ observed_count BIGINT NOT NULL DEFAULT 0 CHECK (observed_count >= 0),+ degraded_count BIGINT NOT NULL DEFAULT 0 CHECK (degraded_count >= 0),+ enforced_count BIGINT NOT NULL DEFAULT 0 CHECK (enforced_count >= 0),+ last_operation TEXT NOT NULL,+ last_action TEXT NOT NULL,+ last_reason TEXT NOT NULL,+ last_policy_revision BIGINT NOT NULL DEFAULT 0,+ last_subscription_version BIGINT NOT NULL DEFAULT 0,+ first_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ last_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);diff --git a/server/migrations/684_entitlement_feature_attempt_scope_idx.down.sql b/server/migrations/684_entitlement_feature_attempt_scope_idx.down.sqlnew file mode 100644index 0000000000..223c5d628f--- /dev/null+++ b/server/migrations/684_entitlement_feature_attempt_scope_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS uq_entitlement_feature_attempt_scope;diff --git a/server/migrations/684_entitlement_feature_attempt_scope_idx.up.sql b/server/migrations/684_entitlement_feature_attempt_scope_idx.up.sqlnew file mode 100644index 0000000000..d247c6e32a--- /dev/null+++ b/server/migrations/684_entitlement_feature_attempt_scope_idx.up.sql@@ -0,0 +1,3 @@+-- Upsert key for RecordEntitlementFeatureAttempt and the per-workspace lookup.+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_entitlement_feature_attempt_scope+ ON entitlement_feature_attempt (workspace_id, feature, day);diff --git a/server/pkg/db/generated/entitlement_feature_attempt.sql.go b/server/pkg/db/generated/entitlement_feature_attempt.sql.gonew file mode 100644index 0000000000..ea8969b56f--- /dev/null+++ b/server/pkg/db/generated/entitlement_feature_attempt.sql.go@@ -0,0 +1,181 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: entitlement_feature_attempt.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const listEntitlementFeatureAttemptsSince = `-- name: ListEntitlementFeatureAttemptsSince :many+SELECT workspace_id, feature, day, observed_count, degraded_count, enforced_count, last_operation, last_action, last_reason, last_policy_revision, last_subscription_version, first_attempt_at, last_attempt_at, created_at, updated_at FROM entitlement_feature_attempt+WHERE feature = $1+ AND day >= $2+ORDER BY day DESC, workspace_id+`++type ListEntitlementFeatureAttemptsSinceParams struct {+ Feature string `json:"feature"`+ SinceDay pgtype.Date `json:"since_day"`+}++// Workspaces that tried to add to one feature from a UTC day on, one row per+// workspace and day. Distinct workspaces are the reach of the restriction.+func (q *Queries) ListEntitlementFeatureAttemptsSince(ctx context.Context, arg ListEntitlementFeatureAttemptsSinceParams) ([]EntitlementFeatureAttempt, error) {+ rows, err := q.db.Query(ctx, listEntitlementFeatureAttemptsSince, arg.Feature, arg.SinceDay)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []EntitlementFeatureAttempt{}+ for rows.Next() {+ var i EntitlementFeatureAttempt+ if err := rows.Scan(+ &i.WorkspaceID,+ &i.Feature,+ &i.Day,+ &i.ObservedCount,+ &i.DegradedCount,+ &i.EnforcedCount,+ &i.LastOperation,+ &i.LastAction,+ &i.LastReason,+ &i.LastPolicyRevision,+ &i.LastSubscriptionVersion,+ &i.FirstAttemptAt,+ &i.LastAttemptAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listWorkspaceEntitlementFeatureAttempts = `-- name: ListWorkspaceEntitlementFeatureAttempts :many+SELECT workspace_id, feature, day, observed_count, degraded_count, enforced_count, last_operation, last_action, last_reason, last_policy_revision, last_subscription_version, first_attempt_at, last_attempt_at, created_at, updated_at FROM entitlement_feature_attempt+WHERE workspace_id = $1+ORDER BY day DESC, feature+`++// Every recorded day of one workspace, newest first.+func (q *Queries) ListWorkspaceEntitlementFeatureAttempts(ctx context.Context, workspaceID pgtype.UUID) ([]EntitlementFeatureAttempt, error) {+ rows, err := q.db.Query(ctx, listWorkspaceEntitlementFeatureAttempts, workspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []EntitlementFeatureAttempt{}+ for rows.Next() {+ var i EntitlementFeatureAttempt+ if err := rows.Scan(+ &i.WorkspaceID,+ &i.Feature,+ &i.Day,+ &i.ObservedCount,+ &i.DegradedCount,+ &i.EnforcedCount,+ &i.LastOperation,+ &i.LastAction,+ &i.LastReason,+ &i.LastPolicyRevision,+ &i.LastSubscriptionVersion,+ &i.FirstAttemptAt,+ &i.LastAttemptAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const recordEntitlementFeatureAttempt = `-- name: RecordEntitlementFeatureAttempt :one+INSERT INTO entitlement_feature_attempt (+ workspace_id, feature, day,+ observed_count, degraded_count, enforced_count,+ last_operation, last_action, last_reason,+ last_policy_revision, last_subscription_version,+ first_attempt_at, last_attempt_at+) VALUES (+ $1, $2, (now() AT TIME ZONE 'UTC')::date,+ CASE WHEN $3::text = 'observed' THEN 1 ELSE 0 END,+ CASE WHEN $3::text = 'degraded' THEN 1 ELSE 0 END,+ CASE WHEN $3::text = 'enforced' THEN 1 ELSE 0 END,+ $4, $5, $6,+ $7, $8,+ now(), now()+)+ON CONFLICT (workspace_id, feature, day) DO UPDATE+SET observed_count = entitlement_feature_attempt.observed_count + EXCLUDED.observed_count,+ degraded_count = entitlement_feature_attempt.degraded_count + EXCLUDED.degraded_count,+ enforced_count = entitlement_feature_attempt.enforced_count + EXCLUDED.enforced_count,+ last_operation = EXCLUDED.last_operation,+ last_action = EXCLUDED.last_action,+ last_reason = EXCLUDED.last_reason,+ last_policy_revision = EXCLUDED.last_policy_revision,+ last_subscription_version = EXCLUDED.last_subscription_version,+ last_attempt_at = now(),+ updated_at = now()+RETURNING workspace_id, feature, day, observed_count, degraded_count, enforced_count, last_operation, last_action, last_reason, last_policy_revision, last_subscription_version, first_attempt_at, last_attempt_at, created_at, updated_at+`++type RecordEntitlementFeatureAttemptParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Feature string `json:"feature"`+ Outcome string `json:"outcome"`+ Operation string `json:"operation"`+ Action string `json:"action"`+ Reason string `json:"reason"`+ PolicyRevision int64 `json:"policy_revision"`+ SubscriptionVersion int64 `json:"subscription_version"`+}++// One attempt to add to a restricted paid feature. outcome is observed+// (admitted under a configured observe), degraded (admitted because a stale+// enforce was downgraded) or enforced (rejected).+func (q *Queries) RecordEntitlementFeatureAttempt(ctx context.Context, arg RecordEntitlementFeatureAttemptParams) (EntitlementFeatureAttempt, error) {+ row := q.db.QueryRow(ctx, recordEntitlementFeatureAttempt,+ arg.WorkspaceID,+ arg.Feature,+ arg.Outcome,+ arg.Operation,+ arg.Action,+ arg.Reason,+ arg.PolicyRevision,+ arg.SubscriptionVersion,+ )+ var i EntitlementFeatureAttempt+ err := row.Scan(+ &i.WorkspaceID,+ &i.Feature,+ &i.Day,+ &i.ObservedCount,+ &i.DegradedCount,+ &i.EnforcedCount,+ &i.LastOperation,+ &i.LastAction,+ &i.LastReason,+ &i.LastPolicyRevision,+ &i.LastSubscriptionVersion,+ &i.FirstAttemptAt,+ &i.LastAttemptAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex f2b71f7d59..c7b9f1c112 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -843,6 +843,24 @@ type DingtalkGroupRoute struct {UpdatedAt pgtype.Timestamptz `json:"updated_at"`}+type EntitlementFeatureAttempt struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Feature string `json:"feature"`+ Day pgtype.Date `json:"day"`+ ObservedCount int64 `json:"observed_count"`+ DegradedCount int64 `json:"degraded_count"`+ EnforcedCount int64 `json:"enforced_count"`+ LastOperation string `json:"last_operation"`+ LastAction string `json:"last_action"`+ LastReason string `json:"last_reason"`+ LastPolicyRevision int64 `json:"last_policy_revision"`+ LastSubscriptionVersion int64 `json:"last_subscription_version"`+ FirstAttemptAt pgtype.Timestamptz `json:"first_attempt_at"`+ LastAttemptAt pgtype.Timestamptz `json:"last_attempt_at"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}+type EntitlementLimitOverage struct {WorkspaceID pgtype.UUID `json:"workspace_id"`Gate string `json:"gate"`diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.goindex b97bc150e9..be66ef845f 100644--- a/server/pkg/db/generated/workspace_delete.sql.go+++ b/server/pkg/db/generated/workspace_delete.sql.go@@ -235,6 +235,16 @@ func (q *Queries) DeleteWorkspaceConnections(ctx context.Context, workspaceID pgreturn err}+const deleteWorkspaceEntitlementFeatureAttempts = `-- name: DeleteWorkspaceEntitlementFeatureAttempts :exec+DELETE FROM entitlement_feature_attempt+WHERE entitlement_feature_attempt.workspace_id = $1+`++func (q *Queries) DeleteWorkspaceEntitlementFeatureAttempts(ctx context.Context, workspaceID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deleteWorkspaceEntitlementFeatureAttempts, workspaceID)+ return err+}+const deleteWorkspaceEntitlementLimitOverages = `-- name: DeleteWorkspaceEntitlementLimitOverages :execDELETE FROM entitlement_limit_overageWHERE entitlement_limit_overage.workspace_id = $1diff --git a/server/pkg/db/queries/entitlement_feature_attempt.sql b/server/pkg/db/queries/entitlement_feature_attempt.sqlnew file mode 100644index 0000000000..88175e9702--- /dev/null+++ b/server/pkg/db/queries/entitlement_feature_attempt.sql@@ -0,0 +1,45 @@+-- name: RecordEntitlementFeatureAttempt :one+-- One attempt to add to a restricted paid feature. outcome is observed+-- (admitted under a configured observe), degraded (admitted because a stale+-- enforce was downgraded) or enforced (rejected).+INSERT INTO entitlement_feature_attempt (+ workspace_id, feature, day,+ observed_count, degraded_count, enforced_count,+ last_operation, last_action, last_reason,+ last_policy_revision, last_subscription_version,+ first_attempt_at, last_attempt_at+) VALUES (+ @workspace_id, @feature, (now() AT TIME ZONE 'UTC')::date,+ CASE WHEN @outcome::text = 'observed' THEN 1 ELSE 0 END,+ CASE WHEN @outcome::text = 'degraded' THEN 1 ELSE 0 END,+ CASE WHEN @outcome::text = 'enforced' THEN 1 ELSE 0 END,+ @operation, @action, @reason,+ @policy_revision, @subscription_version,+ now(), now()+)+ON CONFLICT (workspace_id, feature, day) DO UPDATE+SET observed_count = entitlement_feature_attempt.observed_count + EXCLUDED.observed_count,+ degraded_count = entitlement_feature_attempt.degraded_count + EXCLUDED.degraded_count,+ enforced_count = entitlement_feature_attempt.enforced_count + EXCLUDED.enforced_count,+ last_operation = EXCLUDED.last_operation,+ last_action = EXCLUDED.last_action,+ last_reason = EXCLUDED.last_reason,+ last_policy_revision = EXCLUDED.last_policy_revision,+ last_subscription_version = EXCLUDED.last_subscription_version,+ last_attempt_at = now(),+ updated_at = now()+RETURNING *;++-- name: ListWorkspaceEntitlementFeatureAttempts :many+-- Every recorded day of one workspace, newest first.+SELECT * FROM entitlement_feature_attempt+WHERE workspace_id = @workspace_id+ORDER BY day DESC, feature;++-- name: ListEntitlementFeatureAttemptsSince :many+-- Workspaces that tried to add to one feature from a UTC day on, one row per+-- workspace and day. Distinct workspaces are the reach of the restriction.+SELECT * FROM entitlement_feature_attempt+WHERE feature = @feature+ AND day >= @since_day+ORDER BY day DESC, workspace_id;diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sqlindex ffc5fc4e24..664f61b5aa 100644--- a/server/pkg/db/queries/workspace_delete.sql+++ b/server/pkg/db/queries/workspace_delete.sql@@ -650,6 +650,10 @@ WHERE autopilot_quota_period.workspace_id = $1;DELETE FROM entitlement_limit_overageWHERE entitlement_limit_overage.workspace_id = $1;+-- name: DeleteWorkspaceEntitlementFeatureAttempts :exec+DELETE FROM entitlement_feature_attempt+WHERE entitlement_feature_attempt.workspace_id = $1;+-- name: DeleteWorkspaceAutopilotChildren :execWITHdeleted_triggers AS (